clipboard: text/CF_HTML codec, in-band chunking, bulk header, Reassembler

Ported from App/Core/Clipboard.cs (42-47, 190-201, 253-373, 1101-1194),
App/Helper/FormHelper.cs (180-218) and App/Class/SocketStuff.cs (1673-1811).
Foundation's .zlib is raw DEFLATE, verified against Python zlib -15.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
This commit is contained in:
lucioandClaude Opus 5 committed 2026-09-16 04:36:51 -07:00
1 parent 18c9702524
commit 8105f5f24f
1 file changed
+384
+384
View File
@@ -0,0 +1,384 @@
// The clipboard payload formats: the tag/SEP text blob, its raw-DEFLATE
// compression, the CF_HTML envelope, the 48-byte in-band chunking and the
// 1024-byte bulk header. See docs/protocol.md §6.1-§6.3 and §10.7.
//
// Ported from App/Core/Clipboard.cs (42-47, 190-201, 253-306, 1101-1194),
// App/Helper/FormHelper.cs (180-218) and App/Class/SocketStuff.cs (1673-1811).
//
// Sans-I/O: nothing here touches a pasteboard, a socket or a file.
import Foundation
/// The three flavours Windows puts in one clipboard payload
/// (`FormHelper.cs:180-218`). Every field is optional: the sender only
/// includes the flavours the clipboard actually held.
public struct ClipboardText: Sendable, Equatable {
/// `TXT` — plain Unicode text.
public var plain: String?
/// `RTF` — rich text, as an RTF document string.
public var rtf: String?
/// `HTM` — HTML. On the wire this is **CF_HTML**, header block and all;
/// `ClipboardCodec.htmlFragment(from:)` reduces it to markup.
public var html: String?
/// A text payload with the flavours given.
public init(plain: String? = nil, rtf: String? = nil, html: String? = nil) {
self.plain = plain
self.rtf = rtf
self.html = html
}
/// True when no flavour carries anything.
public var isEmpty: Bool {
(plain?.isEmpty ?? true) && (rtf?.isEmpty ?? true) && (html?.isEmpty ?? true)
}
}
/// What one clipboard transfer carries (`FormHelper.cs:269-330`).
public enum ClipboardContent: Sendable, Equatable {
/// Text in its three flavours.
case text(ClipboardText)
/// An image, always PNG bytes (`FormHelper.cs:281`).
case image(png: Data)
/// Exactly one file. Windows refuses folders (`SocketStuff.cs:1693`).
case file(URL)
}
/// Why a clipboard payload could not be encoded or decoded.
public enum ClipboardCodecError: Error, Sendable, Equatable {
/// `NSData.compressed(using: .zlib)` failed.
case compressionFailed
/// The DEFLATE stream could not be inflated — a truncated or foreign blob.
case decompressionFailed
/// The decompressed bytes are not UTF-16LE text.
case notUTF16
/// The 1024-byte bulk header is not `"<byteLength>*<name>"`
/// (`Clipboard.cs:587-600`).
case malformedHeader
}
/// The formats, the limits and the chunking, all dictated by the Windows side.
public enum ClipboardCodec {
/// Separator between the tagged text flavours (`Clipboard.cs:47`).
public static let textSeparator = "{4CFF57F7-BEDD-43d5-AE8F-27A61E886F2F}"
/// Compressed payloads up to this size go in-band on the control channel;
/// anything bigger becomes a `Clipboard (69)` beat and a bulk transfer
/// (`MAX_CLIPBOARD_DATA_SIZE_CAN_BE_SENT_INSTANTLY_TCP`, `Clipboard.cs:43`).
public static let inBandLimit = 1024 * 1024
/// Largest file that is offered at all (`Clipboard.cs:44`).
public static let maxFileSize: Int64 = 100 * 1024 * 1024
/// Largest text blob the Windows helper will even read off its clipboard
/// (`FormHelper.cs:28`), measured in UTF-16 code units before compression.
public static let maxTextLength = 20 * 1024 * 1024
/// Largest PNG the Windows helper will read (`FormHelper.cs:29`).
public static let maxImageSize = 50 * 1024 * 1024
/// How long a `Clipboard (69)` beat stays worth pulling
/// (`BIG_CLIPBOARD_DATA_TIMEOUT = 30000`, `Clipboard.cs:42`).
public static let bigDataWindow: TimeInterval = 30
/// Clipboard changes closer together than this are ignored
/// (`Clipboard.cs:100-107`, `FormHelper.cs:246-250`).
public static let quietPeriod: TimeInterval = 1
/// The fixed size of the bulk transfer's first record (`Clipboard.cs:564`).
public static let bulkHeaderSize = 1024
/// Bytes per write on the bulk connection
/// (`NETWORK_STREAM_BUF_SIZE`, `Common.cs:112`).
public static let bulkChunkSize = 1024 * 1024
/// The header name a text transfer announces (`SocketStuff.cs:1749`).
public static let textStreamName = "text"
/// The header name an image transfer announces (`SocketStuff.cs:1781`).
public static let imageStreamName = "image"
// MARK: - Text
/// Builds the tagged blob and compresses it, which is what travels
/// (`FormHelper.cs:180-218` then `Clipboard.cs:190-201`).
///
/// Order and tags are fixed: `TXT`, `RTF`, `HTM`, each followed by the
/// separator. An absent flavour contributes nothing at all.
public static func encodeText(_ text: ClipboardText) throws -> Data {
var blob = ""
if let plain = text.plain, !plain.isEmpty { blob += "TXT" + plain + textSeparator }
if let rtf = text.rtf, !rtf.isEmpty { blob += "RTF" + rtf + textSeparator }
if let html = text.html, !html.isEmpty { blob += "HTM" + html + textSeparator }
return try deflate(utf16LE(blob))
}
/// Inflates and splits a received text blob (`Clipboard.cs:1101-1194`).
///
/// Trailing zero bytes are expected and harmless: the in-band chunker
/// zero-fills its last 48-byte chunk (`Clipboard.cs:281`) and the Windows
/// sender ships `MemoryStream.GetBuffer()`, which is capacity-sized rather
/// than length-sized (`Clipboard.cs:201`). See docs/protocol.md §10.7.
public static func decodeText(_ compressed: Data) throws -> ClipboardText {
let blob = try string(fromUTF16LE: inflate(compressed))
var text = ClipboardText()
var pieceIndex = 0
for piece in blob.components(separatedBy: textSeparator) {
let trimmed = piece.trimmingCharacters(in: CharacterSet(charactersIn: "\0"))
if trimmed.isEmpty { continue } // StringSplitOptions.RemoveEmptyEntries
let body = String(piece.dropFirst(3))
if piece.hasPrefix3(caseInsensitive: "RTF") {
text.rtf = body
} else if piece.hasPrefix3(caseInsensitive: "HTM") {
text.html = body
} else if piece.hasPrefix3(caseInsensitive: "TXT") {
text.plain = body
} else if pieceIndex == 0 {
// `Clipboard.cs:1176-1185`: an untagged first piece is taken as
// plain text; anything later is dropped with a log line.
text.plain = piece
}
pieceIndex += 1
}
return text
}
// MARK: - CF_HTML (`DataFormats.Html`)
/// Strips the CF_HTML header block a Windows peer sends, leaving markup
/// that `NSPasteboard.PasteboardType.html` can hold.
///
/// Prefers the `StartFragment`/`EndFragment` **byte** offsets in the
/// header, falls back to the `<!--StartFragment-->` comments, and finally
/// to dropping the `Key:value` header lines.
public static func htmlFragment(from cfHTML: String) -> String {
guard cfHTML.hasPrefix("Version:") else { return cfHTML }
let utf8 = Array(cfHTML.utf8)
if let start = headerOffset(in: cfHTML, key: "StartFragment"),
let end = headerOffset(in: cfHTML, key: "EndFragment"),
start >= 0, end >= start, end <= utf8.count,
let fragment = String(bytes: utf8[start..<end], encoding: .utf8)
{
return fragment
}
if let open = cfHTML.range(of: "<!--StartFragment-->"),
let close = cfHTML.range(of: "<!--EndFragment-->"), open.upperBound <= close.lowerBound
{
return String(cfHTML[open.upperBound..<close.lowerBound])
}
let lines = cfHTML.split(separator: "\n", omittingEmptySubsequences: false)
let body = lines.drop { line in
let head = line.prefix(while: { $0 != ":" })
return !head.isEmpty && head.allSatisfy(\.isLetter) && line.contains(":")
}
return body.joined(separator: "\n")
}
/// Wraps markup in the CF_HTML envelope a Windows peer expects, with byte
/// offsets that count the finished string's UTF-8 bytes.
///
/// The header is fixed-width (ten-digit, zero-padded offsets), so the
/// offsets can be computed from the prefix lengths without a second pass.
public static func cfHTML(wrapping fragment: String) -> String {
let header =
"Version:0.9\r\nStartHTML:%010d\r\nEndHTML:%010d\r\n"
+ "StartFragment:%010d\r\nEndFragment:%010d\r\n"
let headerLength = String(format: header, 0, 0, 0, 0).utf8.count
let preamble = "<html>\r\n<body>\r\n<!--StartFragment-->"
let epilogue = "<!--EndFragment-->\r\n</body>\r\n</html>"
let startHTML = headerLength
let startFragment = startHTML + preamble.utf8.count
let endFragment = startFragment + fragment.utf8.count
let endHTML = endFragment + epilogue.utf8.count
return String(format: header, startHTML, endHTML, startFragment, endFragment)
+ preamble + fragment + epilogue
}
// MARK: - In-band chunking (`Clipboard.cs:253-306`)
/// Splits a payload into 64-byte packets with 48 payload bytes at offset
/// 16, terminated by `ClipboardDataEnd`.
///
/// Every packet is addressed to `MachineID.all` and carries no length
/// field: the last chunk is zero-padded and the receiver stops on the
/// terminator. The packets come back unstamped — the app gives them one
/// `Id` each and forwards them (contracts C1).
public static func chunkPackets(payload: Data, isImage: Bool) -> [Packet] {
var packets: [Packet] = []
let type: PackageType = isImage ? .clipboardImage : .clipboardText
var index = 0
repeat {
var packet = Packet(type: type)
packet.des = MachineID.all
let end = min(index + Packet.clipboardChunkSize, payload.count)
packet.payload48 = payload.subdata(in: index..<end) // zero-fills a short chunk
packets.append(packet)
index += Packet.clipboardChunkSize
} while index < payload.count
var end = Packet(type: .clipboardDataEnd)
end.des = MachineID.all
packets.append(end)
return packets
}
// MARK: - The bulk header (`SocketStuff.cs:1701, 1749, 1781`)
/// The 1024-byte UTF-16LE zero-padded `"<byteLength>*<name>"` record that
/// opens every bulk transfer. A name longer than the record is truncated
/// rather than overflowing it, which is what `CopyTo` does on Windows.
public static func bulkHeader(byteCount: Int64, name: String) -> Data {
var header = Data(repeating: 0, count: bulkHeaderSize)
let encoded = utf16LE("\(byteCount)*\(name)")
let n = min(encoded.count, bulkHeaderSize)
header.replaceSubrange(0..<n, with: encoded.prefix(n))
return header
}
/// Reads that record back (`Clipboard.cs:583-602`).
///
/// Windows drops every NUL in the decoded string before splitting, so the
/// zero padding disappears and the name is whatever precedes it.
public static func parseBulkHeader(_ header: Data) throws -> (byteCount: Int64, name: String) {
guard header.count == bulkHeaderSize else { throw ClipboardCodecError.malformedHeader }
let text = try string(fromUTF16LE: header).replacingOccurrences(of: "\0", with: "")
let parts = text.split(separator: "*", maxSplits: 1, omittingEmptySubsequences: false)
guard parts.count >= 2, let size = Int64(parts[0]) else {
throw ClipboardCodecError.malformedHeader
}
return (size, String(parts[1]))
}
/// The last path component of a header name, which may be a Windows path.
///
/// `Path.GetFileName` (`Clipboard.cs:727`) splits on both separators, so a
/// peer cannot name `..\..\something` and escape the download folder.
public static func fileName(fromHeaderName name: String) -> String {
let last = name.split(whereSeparator: { $0 == "\\" || $0 == "/" }).last.map(String.init)
guard let last, !last.isEmpty, last != ".", last != ".." else { return "clipboard" }
return last
}
/// Zero bytes appended after a bulk body so the stream ends on a boundary
/// (`SendFileEx`, `SocketStuff.cs:1832-1836`).
///
/// A CBC stream holds back any final partial block, so a body whose length
/// is not a multiple of the 16-byte block would never reach the peer. The
/// receiver reads exactly `byteCount` bytes and discards the rest.
public static func trailingPadding(forBodyLength length: Int64) -> Int {
let block = Int64(packageSize)
return Int(block - (length % block))
}
// MARK: - Compression (docs/protocol.md §10.7)
/// Raw DEFLATE, the stream .NET's `DeflateStream` writes.
public static func deflate(_ plain: Data) throws -> Data {
do {
return try (plain as NSData).compressed(using: .zlib) as Data
} catch {
throw ClipboardCodecError.compressionFailed
}
}
/// Inflates raw DEFLATE, tolerating trailing zero padding.
public static func inflate(_ compressed: Data) throws -> Data {
do {
return try (compressed as NSData).decompressed(using: .zlib) as Data
} catch {
throw ClipboardCodecError.decompressionFailed
}
}
// MARK: - UTF-16LE (`Common.GetBytesU` / `GetStringU`, `Common.cs:407-415`)
/// The UTF-16LE bytes of a string, with no byte-order mark.
public static func utf16LE(_ text: String) -> Data {
var out = Data(capacity: text.utf16.count * 2)
for unit in text.utf16 {
out.append(UInt8(truncatingIfNeeded: unit))
out.append(UInt8(truncatingIfNeeded: unit >> 8))
}
return out
}
/// Decodes UTF-16LE bytes. An odd trailing byte is dropped, which is what
/// .NET's decoder does with an incomplete unit.
public static func string(fromUTF16LE data: Data) throws -> String {
let even = data.count - (data.count % 2)
guard let text = String(data: data.prefix(even), encoding: .utf16LittleEndian) else {
throw ClipboardCodecError.notUTF16
}
return text
}
private static func headerOffset(in cfHTML: String, key: String) -> Int? {
guard let range = cfHTML.range(of: key + ":") else { return nil }
let digits = cfHTML[range.upperBound...].prefix(while: \.isNumber)
return Int(digits)
}
}
extension String {
/// Case-insensitive test of the three-character flavour tag
/// (`StringComparison.CurrentCultureIgnoreCase`, `Clipboard.cs:1161-1171`).
fileprivate func hasPrefix3(caseInsensitive tag: String) -> Bool {
count >= 3 && prefix(3).caseInsensitiveCompare(tag) == .orderedSame
}
}
/// Rebuilds one in-band payload from the 48-byte chunks of one sender
/// (`Clipboard.cs:308-373`).
///
/// One instance per source machine. Windows instead blocks its receive loop
/// until `ClipboardDataEnd` arrives and gives up after 100 interleaved foreign
/// packets; we have no blocking loop, so the guards here are a size cap and the
/// caller's idle timeout (docs/protocol.md §10.7).
public final class Reassembler {
/// Bytes accepted before the transfer is abandoned: the in-band limit plus
/// one chunk of zero padding.
public static let sizeLimit = ClipboardCodec.inBandLimit + Packet.clipboardChunkSize
/// True when the payload grew past `sizeLimit` and was thrown away.
public private(set) var abandoned = false
/// Whether the chunks seen so far are image bytes.
public private(set) var isImage = false
/// When the last chunk arrived, on the caller's clock.
public private(set) var lastChunk: TimeInterval
private var payload = Data()
/// An empty reassembly, started at `now`.
public init(now: TimeInterval) {
lastChunk = now
}
/// Feeds one packet; returns the finished payload on `ClipboardDataEnd`.
///
/// A chunk after the size cap is dropped and the whole transfer is marked
/// abandoned, so its terminator yields nothing.
public func feed(_ packet: Packet, now: TimeInterval) -> Data? {
lastChunk = now
switch packet.type {
case .clipboardText, .clipboardImage:
isImage = packet.type == .clipboardImage
guard !abandoned else { return nil }
payload.append(packet.payload48)
if payload.count > Reassembler.sizeLimit {
abandoned = true
payload = Data()
}
return nil
case .clipboardDataEnd:
guard !abandoned, !payload.isEmpty else { return nil }
return payload
default:
return nil
}
}
}