A machine pair keeps two control connections and PreProcess exempts ClipboardText/ClipboardImage from the replay ring (Receiver.cs:40-82), so every chunk is delivered twice. Windows reassembles from the one socket the first chunk arrived on (Clipboard.cs:308-373) and never sees it; ours is keyed by sending machine, so the copies interleaved and corrupted the payload. Reassembler now keeps a 50-entry ring of chunk Ids, which works because contracts C1 stamps one Id per chunk for both deliveries. docs/protocol.md §10.7 note 11. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
1071 lines
63 KiB
Markdown
1071 lines
63 KiB
Markdown
# protocol.md — the Mouse Without Borders wire protocol, transcribed
|
||
|
||
**Purpose.** The single place the wire format is written down. Every fact
|
||
here is transcribed from the Windows source at
|
||
`/Users/guoliangchen/repo/PowerToys/src/modules/MouseWithoutBorders/App/`
|
||
(commit `3104d5c`, v0.101.2572.0) and cited as `file:line`. The Windows
|
||
source is the authority; this file is our reading of it. Where a fact has
|
||
been confirmed against real Windows bytes it is marked **[verified]**;
|
||
everything else is **[transcribed]** until the `interop-vectors` feature
|
||
lands golden vectors captured from a Windows machine.
|
||
|
||
Transcribed 2026-09-15 (lead + Explore agent). Spot-checked by the lead the
|
||
same day: §1.3 framing, §2.1 magic hash, §2.2 cipher config, §2.3
|
||
sacrificial block (all read directly from source).
|
||
|
||
---
|
||
|
||
## 1. Packets
|
||
|
||
### 1.1 Layout — `Core/DATA.cs`
|
||
|
||
`DATA` is `[StructLayout(LayoutKind.Explicit)]` and marshalled with
|
||
`Marshal.StructureToPtr` (`DATA.cs:135-149`): **little-endian, natural
|
||
alignment, no padding.** Two sizes (`Core/Package.cs:17-19`):
|
||
`PACKAGE_SIZE = 32` (small), `PACKAGE_SIZE_EX = 64` (big).
|
||
|
||
| Offset | Size | Field | Notes |
|
||
|---|---|---|---|
|
||
| 0 | 4 | `Type` (`PackageType`, int) | **only byte 0 survives the wire** — bytes 1–3 are overwritten by framing (§1.3). `DATA.cs:27-28` |
|
||
| 4 | 4 | `Id` (int) | packet sequence number. `DATA.cs:30-31` |
|
||
| 8 | 4 | `Src` (`ID` = uint) | source machine id. `DATA.cs:33-34` |
|
||
| 12 | 4 | `Des` (`ID` = uint) | destination machine id. `DATA.cs:36-37` |
|
||
| 16 | 8 | `DateTime` (long) | only set for `Keyboard` (`Event.cs:266`), unused on receive |
|
||
| 24 | 8 | `Kd` (`KEYBDDATA`) | `{ int wVk; int dwFlags }` `Core/KEYBDDATA.cs:18-25` |
|
||
| 16 | 16 | `Md` (`MOUSEDATA`) | union with DateTime+Kd: `{ int X; int Y; int WheelDelta; int dwFlags }` `Core/MOUSEDATA.cs:18-26` |
|
||
| 16..28 | 4×4 | `Machine1..4` (`ID`) | union; handshake nonce words. `DATA.cs:48-58` |
|
||
| 16 | 4 | `PostAction` (uint) | union; clipboard post action. `DATA.cs:60-61` |
|
||
| 32 | 32 | `MachineName` | big packets only; 4×8 bytes `machineNameP1..P4`. `DATA.cs:63-94` |
|
||
|
||
`MachineName` is **ASCII** (`Common.GetBytes`, `Common.cs:397-405`),
|
||
right-padded with spaces to exactly 32 bytes, trimmed on read. The local
|
||
name is `Dns.GetHostName()` truncated to 32 chars (`Common.cs:1381-1384`).
|
||
Non-ASCII hostnames do not round-trip.
|
||
|
||
**Big vs small** (`DATA.cs:124-133`): a packet is 64 bytes iff `Type` ∈
|
||
{Hello, Awake, Heartbeat, Heartbeat_ex, Handshake, HandshakeAck,
|
||
ClipboardPush, Clipboard, ClipboardAsk, ClipboardImage, ClipboardText,
|
||
ClipboardDataEnd} **or** `(Type & 0x80) != 0` (Matrix). Everything else —
|
||
including `Heartbeat_ex_l2/l3`, `HideMouse`, `MachineSwitched`,
|
||
`NextMachine`, `Mouse`, `Keyboard`, `ByeBye`, `Hi` — is 32 bytes and
|
||
carries no machine name.
|
||
|
||
Receive is two-phase (`Class/SocketStuff.cs:558-610`): read exactly 32
|
||
bytes, validate framing, construct `DATA`; if big, read 32 more into
|
||
bytes 32..63.
|
||
|
||
### 1.2 `PackageType` — `Core/PackageType.cs:15-57`
|
||
|
||
| Name | Value | Size | Name | Value | Size |
|
||
|---|---|---|---|---|---|
|
||
| `Hi` | 2 | 32 | `ClipboardDataEnd` | 76 | 64 |
|
||
| `Hello` | 3 | 64 | `MachineSwitched` | 77 | 32 |
|
||
| `ByeBye` | 4 | 32 | `ClipboardAsk` | 78 | 64 |
|
||
| `Heartbeat` | 20 | 64 | `ClipboardPush` | 79 | 64 |
|
||
| `Awake` | 21 | 64 | `NextMachine` | 121 | 32 |
|
||
| `HideMouse` | 50 | 32 | `Keyboard` | 122 | 32 |
|
||
| `Heartbeat_ex` | 51 | 64 | `Mouse` | 123 | 32 |
|
||
| `Heartbeat_ex_l2` | 52 | 32 | `ClipboardText` | 124 | 64 |
|
||
| `Heartbeat_ex_l3` | 53 | 32 | `ClipboardImage` | 125 | 64 |
|
||
| `Clipboard` | 69 | 64 | `Handshake` | 126 | 64 |
|
||
| `ClipboardDragDrop` | 70 | 32 | `HandshakeAck` | 127 | 64 |
|
||
| `ClipboardDragDropEnd` | 71 | 32 | `Matrix` | 128 (0x80, flag) | 64 |
|
||
| `ExplorerDragDrop` | 72 | 32 | `MatrixSwapFlag` | 2 (OR'd into Matrix) | — |
|
||
| `ClipboardCapture` | 73 | 32 | `MatrixTwoRowFlag` | 4 (OR'd into Matrix) | — |
|
||
| `CaptureScreenCommand` | 74 | 32 | `Error` | 0xFE — local only (0-byte read) | — |
|
||
| `ClipboardDragDropOperation` | 75 | 32 | `Invalid` | 0xFF — local only (bad framing) | — |
|
||
|
||
All values fit in one byte by design (`PackageType.cs:17`).
|
||
|
||
### 1.3 Framing: magic + checksum in bytes 1–3 **[verified against source]**
|
||
|
||
Send — `SocketStuff.cs:497-529` (`TcpSendData`):
|
||
|
||
```
|
||
bytes[3] = (MagicNumber >> 24) & 0xFF
|
||
bytes[2] = (MagicNumber >> 16) & 0xFF
|
||
bytes[1] = 0
|
||
for i in 2..<32: bytes[1] = (bytes[1] + bytes[i]) & 0xFF // bytes 2..31 ONLY
|
||
write(bytes) // 32 or 64 bytes, through the cipher stream
|
||
```
|
||
|
||
Receive — `SocketStuff.cs:531-556` (`ProcessReceivedDataEx`), on the first
|
||
32 bytes only:
|
||
|
||
```
|
||
magic = (buf[3] << 24) | (buf[2] << 16)
|
||
if magic != (MagicNumber & 0xFFFF0000): buf[0] = 0xFF (Invalid)
|
||
if buf[1] != sum(buf[2..31]) & 0xFF: buf[0] = 0xFF (Invalid)
|
||
buf[1] = buf[2] = buf[3] = 0
|
||
```
|
||
|
||
Consequences: `Type` is effectively one byte; the checksum never covers
|
||
bytes 32..63; only the top 16 bits of the magic are transmitted.
|
||
|
||
### 1.4 Sequence numbers and replay window
|
||
|
||
`Id` is a process-global increment (`Common.cs:906`) persisted as the
|
||
`PackageID` setting. `Receiver.PreProcess` (`Core/Receiver.cs:40-82`)
|
||
keeps the last **50** ids in a ring and drops repeats, except for
|
||
`ClipboardText`, `ClipboardImage`, `Handshake`, `HandshakeAck`.
|
||
|
||
### 1.5 Machine IDs — `Core/ID.cs:15-19`
|
||
|
||
`ID` is `uint`; `NONE = 0`, `ALL = 255` (broadcast). A machine's own id is
|
||
a random non-negative `int` persisted as `MachineID`
|
||
(`Class/Setting.cs:1048-1083`), generated when 0, regenerated on collision
|
||
(`SocketStuff.cs:1984-1992`). Peers' ids are learned from `Src` during
|
||
handshake and heartbeats. **Exception:** in `Matrix` packets `Src` is a
|
||
1-based slot index (§4.2).
|
||
|
||
---
|
||
|
||
## 2. Cryptography — `Core/Encryption.cs`
|
||
|
||
### 2.1 Magic number **[verified against source]**
|
||
|
||
`Get24BitHash(MyKey)` (`Encryption.cs:173-200`), computed once per socket
|
||
open (`SocketStuff.cs:227`):
|
||
|
||
```
|
||
b = 32 zero bytes; for i in 0..<min(32, key.count): b[i] = UInt8(truncating: key.utf16[i])
|
||
h = SHA512(b)
|
||
50 000 times: h = SHA512(h) // 50 001 hashes in total
|
||
magic = UInt32((h[0] << 23) + (h[1] << 16) + (h[63] << 8) + h[2])
|
||
```
|
||
|
||
`h[0] << 23`, not `<< 24`: the shifted terms overlap at bit 23 and the
|
||
sum carries. Reproduce exactly. Only bits 16..31 of `magic` go on the wire.
|
||
|
||
### 2.2 Cipher **[verified against source]**
|
||
|
||
AES-256-CBC, **`PaddingMode.Zeros`**, 16-byte blocks
|
||
(`Encryption.cs:92-98`). Key = `PBKDF2-HMAC-SHA512(password: MyKey (UTF-8),
|
||
salt: 16 random bytes, iterations: 100 000, length: 32)`
|
||
(`Encryption.cs:107-115`, constants at `:38-45`).
|
||
|
||
### 2.3 Stream layout, per direction
|
||
|
||
Each direction of each connection is one continuous CBC stream
|
||
(`SocketStuff.cs:104, 118`; the two directions wrap separate
|
||
`NetworkStream`s over the same socket):
|
||
|
||
```
|
||
[16 bytes salt][16 bytes IV] cleartext header, written by the writer, read by the reader
|
||
(Encryption.cs:117-171)
|
||
[16 bytes random] FIRST ciphertext block: the "sacrificial" block,
|
||
written through the cipher and discarded by the reader
|
||
(Common.cs:1528-1558, wired at SocketStuff.cs:105,119)
|
||
[32 or 64 byte packets ...] framed as §1.3; no per-packet IV, no per-packet MAC
|
||
```
|
||
|
||
Zero padding never adds bytes because every write is a multiple of 16.
|
||
Framing is therefore entirely length-driven by `Type` (§1.1). The
|
||
clipboard channel (§5.3) uses the same layout.
|
||
|
||
### 2.4 The security key
|
||
|
||
- Minimum 16 characters; validation is length-only (`Encryption.cs:235-242`).
|
||
- Auto-generated keys are 16 chars drawn round-robin from
|
||
`abcdefghjkmnpqrstuvxyz`, `ABCDEFGHJKMNPQRSTUVXYZ`, `123456789`,
|
||
`` ~!@#$%^*()_-+=:;<,>.?/\|[] `` (`Encryption.cs:207-212`).
|
||
- Stored in **plaintext** in `settings.json` as `SecurityKey`
|
||
(`Class/Setting.cs:479-511`); a key change reopens all sockets.
|
||
|
||
---
|
||
|
||
## 3. Connections and handshake — `Class/SocketStuff.cs`
|
||
|
||
### 3.1 Ports and sockets
|
||
|
||
- `TCPPort` default **15100** (`MouseWithoutBordersProperties.cs:202`).
|
||
- Listener on **port + 1 (15101)**: control channel. Listener on **port
|
||
(15100)**: clipboard/file bulk channel (`SocketStuff.cs:475-495`).
|
||
- Clients connect to port+1 for control (`:1169`) and port for clipboard
|
||
(`Clipboard.cs:1087-1091`).
|
||
- Sockets are IPv6 dual-mode (`:1141-1142`).
|
||
- Each machine pair ends up with two control connections (one client
|
||
each way); dedup keeps the first connected client socket per peer
|
||
name (`:1980-2004`).
|
||
- Options: send/recv buffers 320 000, `NoDelay`, `SendTimeout` 500 ms
|
||
(`:1283-1286`). Connect retried every 1 s for 30 s (`:158, 276, 1179-1198`).
|
||
- **No UDP, no multicast, no discovery** anywhere in the module.
|
||
|
||
### 3.2 Handshake — `SocketStuff.cs:1261-1565` (`MainTCPRoutine`, same path client and server)
|
||
|
||
1. Build a `DATA` from 64 cryptographically random bytes (`:1269-1270`)
|
||
— `Machine1..4` at offsets 16..31 are the nonce.
|
||
2. Set `MachineName = local`, `Type = Handshake (126)`. Send it **10 times**
|
||
(`:1291-1294`). Set expected = `~Machine1..4` (`:1296-1299`).
|
||
3. On receiving `Handshake`: reply `HandshakeAck (127)` with `Src = own
|
||
id` (filled by `TcpSend`, `:666-669`), `MachineName = local`,
|
||
`MachineN = ~MachineN` (`:1371-1384`).
|
||
4. On receiving `HandshakeAck`: all four words must equal expected
|
||
(`:1409-1410`). Then `tcp.MachineId = Src`, status `Connected`, peer
|
||
name := `MachineName` from the packet (`:1412-1419`), and send an
|
||
initial heartbeat (`:1451`).
|
||
5. Guards: >10 non-handshake packets before trust ⇒ send `Invalid` ×10,
|
||
status `InvalidKey`, close (`:1387-1406`). Mismatched ack ⇒
|
||
`InvalidKey`. >10 failures from one endpoint ⇒ app quits
|
||
(`:1482-1499`). Peer name == own name ⇒ close (`:1430-1437`).
|
||
|
||
`SocketStatus` (`:54-66`): NA 0, Resolving 1, Connecting 2, Handshaking 3,
|
||
Error 4, ForceClosed 5, InvalidKey 6, Timeout 7, SendError 8, Connected 9.
|
||
Status colours are in `doc/devdocs/modules/mousewithoutborders.md`.
|
||
|
||
### 3.3 Liveness
|
||
|
||
- Heartbeat from the 100 ms UI timer (`frmScreen.cs:285-288, 565-575`):
|
||
every 60 s when `BlockScreenSaver` is on, else every 300 s.
|
||
`Awake (21)` if real input happened since the previous heartbeat, else
|
||
`Heartbeat (20)` — `SendAwakeBeat` compares `lastRealInputEventCount !=
|
||
Event.RealInputEventCount` and re-records the counter every time it runs
|
||
(`Common.cs:542-559`), so this is a since-the-last-beat test, not a
|
||
sliding window. The counter is bumped by the input hook
|
||
(`Event.cs:51-55`, `InputHook.cs:223, 345`). `Awake` also requires
|
||
`BlockScreenSaver`, `IsMyDesktopActive()` and neither the logon nor the
|
||
screen-saver desktop (`Common.cs:547-548`).
|
||
- Key propagation chain during pairing: `Heartbeat_ex (51)` → receiver
|
||
adopts key, replies `Heartbeat_ex_l2 (52)` → `Heartbeat_ex_l3 (53)`
|
||
(`Receiver.cs:210-243`). *Port decision: not implemented in M2; the
|
||
key is typed on both sides.*
|
||
- `HEARTBEAT_TIMEOUT = 1 500 000 ms` (25 min) (`MachineStuff.cs:32`,
|
||
`MachinePool.cs:304-307`).
|
||
- `Hi (2)` is a liveness probe written by `TestSend` (`Common.cs:822-847`);
|
||
the receiver only counts it. `ByeBye (4)` on shutdown.
|
||
- Reconnect triggers (`InitAndCleanup.cs:28-31`, `frmScreen.cs:427-461`):
|
||
network change, sleep/wake, display change, connection reset, hotkey.
|
||
|
||
---
|
||
|
||
## 4. Machines, matrix, switching — `Core/MachineStuff.cs`, `Class/MachinePool.cs`
|
||
|
||
### 4.1 Model
|
||
|
||
- `MAX_MACHINE = 4`, `MAX_SOCKET = 8` (`MachineStuff.cs:30-31`).
|
||
- Matrix = `string[4]` of names (`:883-933`), persisted as
|
||
`MachineMatrixString`. Layout: one row `[0][1][2][3]` (`MatrixOneRow`,
|
||
default true; up/down disabled `:538-541, 607-610`) or two rows
|
||
`[0][1]/[2][3]`. `MatrixCircle` (= `WrapMouse`, default true) wraps.
|
||
- `MachinePool`: name↔id↔last-seen, max 4, serialized
|
||
`Name:Id,Name:Id,Name:Id,Name:Id`, default `:,:,:,:`
|
||
(`MachinePool.cs:195-243, 287-301`; parser `MachinePoolHelpers.cs:16-43`).
|
||
- `desMachineID` = machine receiving input; `ALL (255)` = broadcast
|
||
mode (`:1030-1050`). `LiveMachineMatrix` blanks disconnected slots in
|
||
one-row mode (`:935-945`).
|
||
|
||
### 4.2 Matrix replication
|
||
|
||
Four `Matrix` packets, one per slot: `Src = slot+1`, `Des = ALL`,
|
||
`MachineName = slot name`, `Type = 0x80 | (circle ? 2 : 0) | (oneRow ? 0 : 4)`
|
||
(`:952-976`). Receiver stores slot `Src-1`; on `Src == 4` commits flags
|
||
and reopens clients (`:978-1006`). Peers are also learned from
|
||
`Heartbeat`/`Hello`/`Awake` via `AddToMachinePool` (`:712-777`).
|
||
|
||
### 4.3 Edge detection — `MoveToMyNeighbourIfNeeded` (`:203-283`)
|
||
|
||
- `SKIP_PIXELS = 1`, `JUMP_PIXELS = 2` (`:33-34`); 100 ms debounce
|
||
(`:217`); disabled in ALL mode.
|
||
- `BlockMouseAtCorners`: no switch within 100 px of a monitor corner
|
||
(`:222-234`).
|
||
- Rectangle tested: `desktopBounds` (union of all monitors) when the
|
||
controller owns the cursor, else `primaryScreenBounds` (`:239-280`).
|
||
- `x < left+1` → left; `x >= right-1` → right; `y < top+1` → up;
|
||
`y >= bottom-1` → down.
|
||
|
||
### 4.4 Coordinates
|
||
|
||
Universal value (`:181-190`): `X = (x - r.left) * 65535 / r.width`,
|
||
same for Y — absolute 0..65535 relative to a rectangle chosen by mode
|
||
(`:385-421`):
|
||
|
||
| case | source rectangle |
|
||
|---|---|
|
||
| `MoveMouseRelatively` on | desktopBounds → 65535 → remote desktopBounds |
|
||
| off, switching back to the controller | primaryScreenBounds |
|
||
| off, switching away from the controller | desktopBounds |
|
||
| off, between two non-controllers | primaryScreenBounds |
|
||
|
||
Mouse-move packets (`Event.cs:112-113`): `Md.X = (x - primary.left) *
|
||
65535 / screenWidth` where `screenWidth` is the **primary** monitor
|
||
(`WinAPI.cs:70-80`). Receiver de-normalizes onto its **desktopBounds**
|
||
(`InputSimulation.cs:160-173`):
|
||
|
||
```
|
||
w = (dB.right - dB.left) * 65535 / screenWidth ; l = dB.left * 65535 / screenWidth
|
||
dx = X * w / 65535 + l (same for Y)
|
||
```
|
||
|
||
Relative mode biases: `MOVE_MOUSE_RELATIVE = 100 000` added to dx/dy
|
||
(`Event.cs:32`, `InputHook.cs:311-312`, stripped at `Receiver.cs:147-153`);
|
||
`XY_BY_PIXEL = 300 000` marks pixel coordinates on the local switch path
|
||
(`Event.cs:33`, `InputHook.cs:272-281`).
|
||
|
||
`NextMachine (121)` (`Common.cs:559-585`): `Md.X/Y` = landing point
|
||
0..65535, **`Md.WheelDelta` = target machine id**, `Des` = controller;
|
||
max one per 100 ms; sent by a controlled machine that hit its own edge
|
||
in relative mode (`Receiver.cs:156-170`).
|
||
|
||
### 4.5 Hotkeys (defaults from `MouseWithoutBordersProperties.cs`)
|
||
|
||
| Setting | Default | Notes |
|
||
|---|---|---|
|
||
| `HotKeySwitchMachine` | `0x70` VK_F1: Ctrl+Alt+F1..F4 → slot 0..3 | `InputHook.cs:611-658` |
|
||
| `LockMachineShortcut` | Win+Ctrl+Alt+L | twice within 500 ms ⇒ ALL mode + lock everywhere (`:539-577`) |
|
||
| `ReconnectShortcut` | Win+Ctrl+Alt+R | `PleaseReopenSocket` (`:578-584`) |
|
||
| `ToggleEasyMouseShortcut` | Win+Ctrl+Alt+E | |
|
||
| `Switch2AllPCShortcut` | disabled | |
|
||
| `HotKeyExitMM` | 0 (disabled) | `Setting.cs:811-817` |
|
||
|
||
Hotkeys are ignored if Shift or Win is also held with Ctrl+Alt
|
||
(`InputHook.cs:604-610`). Every matched hotkey is swallowed except
|
||
`Switch2AllPCShortcut`: its branch (`InputHook.cs:518-522`) falls through
|
||
instead of returning `false`, so with a chord that does not itself hold Ctrl+Alt
|
||
the key toggles ALL mode *and* reaches the OS. Only reachable with a non-default
|
||
setting — the shortcut ships empty (`MouseWithoutBordersProperties.cs:30`) and
|
||
an empty hotkey never matches (`Common.cs:127-129`). Easy Mouse (`EasyMouseOption.cs`, default 1 =
|
||
always): 0 disabled, 1 enabled, Ctrl/Shift variants require the modifier.
|
||
|
||
---
|
||
|
||
## 5. Input encoding
|
||
|
||
### 5.1 Keyboard — `KEYBDDATA { wVk, dwFlags }`
|
||
|
||
- `wVk` = Windows **virtual-key code** (`InputHook.cs:347-349`). Scan
|
||
codes are never sent; the receiver regenerates one with
|
||
`MapVirtualKey` (`InputSimulation.cs:125`).
|
||
- `dwFlags` = raw `LLKHF` bits (`WM.cs:47-54`): `EXTENDED 0x01`,
|
||
`INJECTED 0x10`, `ALTDOWN 0x20`, `UP 0x80`.
|
||
- Receiver: `UP` → key up, `EXTENDED` → extended key
|
||
(`InputSimulation.cs:108-157`); 10 ms sleep after key-up sends
|
||
(`Event.cs:268-271`).
|
||
- Sender swallows the key locally whenever the destination is remote
|
||
(`InputHook.cs:361-368`).
|
||
|
||
### 5.2 Mouse — `MOUSEDATA { X, Y, WheelDelta, dwFlags }`
|
||
|
||
- `dwFlags` = the **`WM_*` message id** (`InputHook.cs:251`; `WM.cs:27-40`):
|
||
`MOUSEMOVE 0x200`, `LBUTTONDOWN 0x201`, `LBUTTONUP 0x202`,
|
||
`LBUTTONDBLCLK 0x203`, `RBUTTONDOWN 0x204`, `RBUTTONUP 0x205`,
|
||
`RBUTTONDBLCLK 0x206`, `MBUTTONDOWN 0x207`, `MBUTTONUP 0x208`,
|
||
`MBUTTONDBLCLK 0x209`, `MOUSEWHEEL 0x20A`, `XBUTTONDOWN 0x20B`,
|
||
`XBUTTONUP 0x20C`, `MOUSEHWHEEL 0x20E`.
|
||
- `WheelDelta = (short)(mouseData >> 16)` (`InputHook.cs:254`): signed
|
||
wheel delta in multiples of 120 for wheel events, XBUTTON1/2 index for
|
||
X-button events.
|
||
- Receiver maps to `MOUSEEVENTF` (`InputSimulation.cs:181-219`); moves
|
||
are absolute; `*DBLCLK` falls through and is effectively dropped.
|
||
|
||
### 5.3 Modifier and cursor state
|
||
|
||
- Sender tracks Win/Ctrl/Alt/Shift for hotkeys (`InputHook.cs:80-92,
|
||
371-473`; only LSHIFT toggles shift). Receiver tracks the same for
|
||
remote Win+L / Ctrl+Alt+Del interception (`InputSimulation.cs:358-475`).
|
||
- `ReleaseAllKeys` (`InitAndCleanup.cs:214-243`) synthesizes key-up for
|
||
every modifier that is down, at most once per 2 s, on switch / mode
|
||
change / lock.
|
||
- `HideMouse (50)` and local switch-away park the real cursor at the
|
||
primary screen's horizontal centre, y = 4 (`Common.cs:1482-1496`,
|
||
`Receiver.cs:383-388`). While controlled remotely the hook clamps the
|
||
virtual cursor to `primaryScreenBounds ± 1` (`InputHook.cs:293-309`).
|
||
|
||
---
|
||
|
||
## 6. Clipboard and files — `Core/Clipboard.cs`, `SocketStuff.cs`
|
||
|
||
### 6.1 Payload formats (`Helper/FormHelper.cs:180-218, 269-330`)
|
||
|
||
- **Text**: `"TXT" + unicode + SEP + "RTF" + rtf + SEP + "HTM" + html + SEP`
|
||
where `SEP = "{4CFF57F7-BEDD-43d5-AE8F-27A61E886F2F}"` (`Clipboard.cs:47`);
|
||
UTF-16LE encoded, then **Deflate** compressed (`Clipboard.cs:190-201`).
|
||
Reassembled at `:1148-1194`.
|
||
- **Image**: PNG bytes, uncompressed (`FormHelper.cs:281`).
|
||
- **File**: exactly one file path; folders refused (`SocketStuff.cs:1693`).
|
||
|
||
### 6.2 Small payloads — in-band on the control channel (≤ 1 MB compressed)
|
||
|
||
`SendClipboardDataUsingTCP` (`Clipboard.cs:253-306`): 64-byte packets of
|
||
type `ClipboardText (124)` / `ClipboardImage (125)`, `Des = ALL`, with
|
||
**48 payload bytes at offsets 16..63**; final chunk zero-padded, no
|
||
length field; terminated by `ClipboardDataEnd (76)`. Receiver appends
|
||
every chunk (`:308-373`) and aborts after 100 interleaved foreign packets.
|
||
|
||
### 6.3 Large payloads and files — bulk channel on port 15100
|
||
|
||
Signal: `Clipboard (69)` broadcast "I have big data" (`Common.cs:665`);
|
||
30 s window (`Clipboard.cs:42`). The machine being switched to pulls
|
||
(`Receiver.cs:284-291`, `Event.cs:219-231`, `MachineSwitched (77)`) or
|
||
asks for a push with `ClipboardAsk (78)` (`Clipboard.cs:425-449`).
|
||
|
||
Bulk connection (`Clipboard.ShakeHand` `:961-1060`, `SendClipboardData`
|
||
`SocketStuff.cs:1673-1811`, receive `Clipboard.cs:498-923`):
|
||
|
||
1. TCP to peer:15100, 30 s receive timeout, 1 024 000 buffers.
|
||
2. Same cipher layout as §2.3 (salt+IV header, sacrificial block).
|
||
3. One 64-byte `DATA` each way: `ClipboardPush (79)` if the connector
|
||
pushes, else `Clipboard (69)`; carries `Src`, `MachineName`, `PostAction`.
|
||
4. Accepted only if `MachinePool.ResolveID(name) == Src` and connected (`:1009`).
|
||
5. Sender writes a **1024-byte UTF-16LE zero-padded header**
|
||
`"<byteLength>*<name>"`, `name` ∈ {`text`, `image`, full file path};
|
||
failures encode as `"0*<path> not found!"` (`SocketStuff.cs:1701, 1749, 1781`).
|
||
6. Then raw bytes in 1 MB chunks (`Common.cs:112`), files padded to a
|
||
32-byte boundary (`SocketStuff.cs:1832-1836`); receiver reads exactly
|
||
`byteLength` (`Clipboard.cs:943-959`).
|
||
7. `ClipboardPostAction` (`Core/ClipboardPostAction.cs:20-25`): `Other 0`,
|
||
`Desktop 1`, `Mspaint 2`.
|
||
|
||
Limits: files ≤ **100 MB** (`Clipboard.cs:44`); clipboard events within
|
||
1 s of the previous are ignored (`:100-107`). Destination:
|
||
`<Desktop>\MouseWithoutBorders\` (`Common.cs:1291-1330`), committed
|
||
atomically via temp file + move (`Core/ReceivedDestinationFile.cs`).
|
||
|
||
### 6.4 Drag and drop — `Core/DragDrop.cs:25-51`
|
||
|
||
Packets `ExplorerDragDrop (72)`, `ClipboardDragDrop (70)`,
|
||
`ClipboardDragDropOperation (75)`, `ClipboardDragDropEnd (71)`; bytes
|
||
travel over §6.3. Requires the Windows-shell helper process. *Port
|
||
decision: out of scope for v1 (see TODO §9).*
|
||
|
||
---
|
||
|
||
## 7. Name resolution (no discovery)
|
||
|
||
1. For every non-local matrix name without a connection, start a client
|
||
(`SocketStuff.cs:797-837`).
|
||
2. Name → address by `Dns.GetHostEntry(name)` (`:950`), IPv4 and IPv6.
|
||
3. `Name2IP`: CRLF-separated lines of `"<name> <ip>"` (`:1258-1259`), used
|
||
in addition to DNS.
|
||
4. Optional reverse-lookup validation (`ValidateRemoteMachineIP`, `:991-1032`)
|
||
and same-subnet check that compares only the first two IPv4 octets
|
||
(`:1065-1107`).
|
||
5. Inbound peers are named by reverse DNS, domain suffix stripped
|
||
(`:733-762`), then overridden by the `HandshakeAck` name.
|
||
|
||
---
|
||
|
||
## 8. Settings file
|
||
|
||
`%LOCALAPPDATA%\Microsoft\PowerToys\MouseWithoutBorders\settings.json`,
|
||
`{ "name": "MouseWithoutBorders", "version": "1.1", "properties": {...} }`.
|
||
Property names, types and defaults: see `README.md` §Settings (transcribed
|
||
from `src/settings-ui/Settings.UI.Library/MouseWithoutBordersProperties.cs:165-206`).
|
||
|
||
---
|
||
|
||
## 9. What the Windows tests cover (and do not)
|
||
|
||
`MouseWithoutBorders.UnitTests/` (MSTest): AES round-trip and unique
|
||
salt/IV per stream (`EncryptionTests.cs`), received-file staging
|
||
(`ReceivedDestinationFileTests.cs`), logger formatting, settings IPC.
|
||
**No tests exist for packet layout, framing, handshake, matrix logic,
|
||
coordinate normalization or clipboard chunking** — the port has no
|
||
upstream oracle for those and must build its own (`interop-vectors`).
|
||
|
||
---
|
||
|
||
## 10. Lane notes
|
||
|
||
Findings a lane made while porting, kept here so the next reader of §1–§9
|
||
sees them. One subsection per lane, appended, never rewritten.
|
||
|
||
### 10.1 wire-core (2026-09-16)
|
||
|
||
1. **A rejected packet still consumes 64 bytes.** `Error` (0xFE) and
|
||
`Invalid` (0xFF) both have the `Matrix` bit 0x80 set, so
|
||
`DATA.IsBigPackage` (`DATA.cs:131`) is true for them. The receive loop
|
||
builds the `DATA` *after* `ProcessReceivedDataEx` has overwritten byte 0
|
||
with 0xFF, then reads 32 more bytes because the packet "is big"
|
||
(`SocketStuff.cs:578-600`). A receiver that treats a framing failure as a
|
||
32-byte event desynchronises against a real Windows sender that has a
|
||
64-byte packet in flight. `PackageType.isBig` reproduces this.
|
||
2. **`Type == 0` throws on Windows** (`DATA.cs:126-127`). We decode it as a
|
||
small `.unknown(0)` instead: throwing inside a receive path would be a
|
||
worse failure than dropping one packet, and 0 is not a legal type.
|
||
3. **The magic-number expression overflows `int` and is meant to.**
|
||
`(hashValue[0] << 23) + (hashValue[1] << 16) + ...` (`Encryption.cs:199`)
|
||
reaches 2 155 806 720 for large digest bytes, past `int.MaxValue`, in C#'s
|
||
default unchecked context; it wraps and is then reinterpreted by the
|
||
`(uint)` cast. Reproduce with wrapping 32-bit addition — `&+` in Swift, not
|
||
`+`, which would trap. **[verified]** against an independent SHA-512
|
||
implementation: key `abcdefghijklmnop` ⇒ magic `334517251` (0x13F0_5403).
|
||
4. **The stream preamble is 48 bytes, not 32.** 16-byte salt and 16-byte IV in
|
||
the clear (`Encryption.cs:124-129`), then one 16-byte *ciphertext* block —
|
||
the sacrificial block is random plaintext written *through* the cipher
|
||
(`Common.cs:1536-1537` on the stream returned by `GetEncryptedStream`,
|
||
wired at `SocketStuff.cs:105, 119`). The reader discards the first 16 bytes
|
||
of plaintext, not of ciphertext.
|
||
5. **PBKDF2's password is the UTF-8 encoding of the key.** .NET's
|
||
`Rfc2898DeriveBytes.Pbkdf2(string, ...)` (`Encryption.cs:109`) documents
|
||
UTF-8 for the string overload. **[verified]** against an independent
|
||
PBKDF2-HMAC-SHA512: key `abcdefghijklmnop`, salt 16×0x01, 100 000 rounds ⇒
|
||
`6c30ca8b15c27f6e…14ae2a4da14728e1`. The whole reader path (48-byte
|
||
preamble, AES-256-CBC, sacrificial discard) was checked against a stream
|
||
produced by `openssl enc -aes-256-cbc -nopad`.
|
||
6. **The security key is whitespace-stripped where it is typed**, not where it
|
||
is validated: `Regex.Replace(text, @"\s+", "")`
|
||
(`Form/Settings/SetupPage2a.cs:92`). `IsKeyValid` only measures length
|
||
(`Encryption.cs:235-242`), which is why the grouped display form
|
||
(`Encryption.cs:65-79`, four characters then two spaces) can be copied
|
||
between machines.
|
||
7. **`MachineName` is trimmed with `String.Trim()`** (`DATA.cs:83`), which
|
||
strips whitespace but *not* NUL. Windows pads with spaces
|
||
(`DATA.cs:88`), so this only matters for a zero-filled field; we trim NUL
|
||
as well so such a field reads as empty.
|
||
8. **The 48-byte clipboard chunk starts at offset 16**, i.e.
|
||
`PACKAGE_SIZE_EX - DATA_SIZE` (`Clipboard.cs:46, 274`), and the last chunk
|
||
is zero-filled by clearing the whole buffer first (`Clipboard.cs:281`).
|
||
|
||
### 10.2 session-matrix (2026-09-16)
|
||
|
||
1. **A `Handshake` packet's `Id`, `Src` and `Des` are random.** The whole
|
||
64-byte buffer starts as `RandomNumberGenerator.GetBytes(PACKAGE_SIZE_EX)`
|
||
(`SocketStuff.cs:1269-1270`) and only `Type` and `MachineName` are written
|
||
over it. `TcpSend` fills `Src` **only when it is `ID.NONE`**
|
||
(`SocketStuff.cs:666-669`) and never touches `Id` — only `SkSend` sequences
|
||
(`Common.cs:916`). A receiver must therefore not learn the peer's id from a
|
||
`Handshake`: it comes from the `HandshakeAck`, whose `Src` is explicitly
|
||
cleared to `NONE` before the reply is sent (`:1374`) so that `TcpSend` fills
|
||
in the real one.
|
||
2. **`Hi (2)` is never processed by the receiver.** `TestSend` builds a zeroed
|
||
`DATA` and sends it through `TcpSend`, so its `Id` stays 0
|
||
(`Common.cs:826-836`); the dedup ring is a zero-filled `int[50]`
|
||
(`Receiver.cs:31`), so id 0 matches on the very first comparison and
|
||
`PreProcess` drops the packet (`:66-73`). `Hi` is purely a *write* probe —
|
||
its value is the exception `TcpSend` throws when the socket is gone. It is
|
||
not a round trip, and nothing should be built on top of receiving one.
|
||
3. **The heartbeat cadence is a modulo on a 100 ms tick that starts at 21.**
|
||
`count` is initialised to 21 (`frmScreen.cs:299`) and the guard is
|
||
`count % 600 == 0 && (BlockScreenSaver || count % 3000 == 0)`
|
||
(`frmScreen.cs:565-570`) — 60 s with `BlockScreenSaverOnOtherMachines` on,
|
||
300 s off. `SendAwakeBeat` then picks `Awake` over `Heartbeat` only when the
|
||
setting is on *and* `RealInputEventCount` moved since the last beat
|
||
(`Common.cs:545-556`).
|
||
4. **`HEARTBEAT_TIMEOUT` is 25 minutes, not 30.** `1500000` ms
|
||
(`MachineStuff.cs:32`); the comment next to it says 30. A machine is also
|
||
alive regardless of the timeout while a socket to it is up
|
||
(`MachinePool.cs:304-307`), and `IsConnectedTo` answers yes for the local
|
||
machine's own id without looking at any socket (`Common.cs:852-855`) — which
|
||
is what keeps the local slot from being blanked out of `LiveMachineMatrix`.
|
||
5. **The two-row neighbour search stops at the first matching arm; the one-row
|
||
search does not.** Each two-row arm is an `else if` on
|
||
`current == mc[from] && mc[to] is non-empty` (`MachineStuff.cs:346-378`), so
|
||
an arm that matches but whose target has no id ends the search — no
|
||
fall-through. The one-row loops instead `break` only on success
|
||
(`:312-323`), so they step over a named-but-unresolvable slot. Both are
|
||
ported as they are.
|
||
6. **`MoveDown` is written as two if-chains, `MoveUp` as one.** `MoveUp`
|
||
(`:556-587`) is a single `else if` chain; `MoveDown` (`:625-657`) runs the
|
||
straight arms and then the wrap arms as a separate statement, so a wrap arm
|
||
can overwrite an answer a straight arm already gave. Observable only when one
|
||
name occupies two slots. Similarly, `MoveRight` scans slots ascending for the
|
||
current machine and `MoveLeft` descending (`:308, 448`).
|
||
7. **`ConvertToUniversalValue` does not convert (0, 0).** The guard is
|
||
`if (!p.IsEmpty)` (`MachineStuff.cs:183`) and `Point.IsEmpty` means exactly
|
||
`X == 0 && Y == 0`, so a point on the origin is passed through unscaled. The
|
||
same value is also the "no switch" sentinel returned by
|
||
`MoveToMyNeighbourIfNeeded`, so on Windows a jump that legitimately lands on
|
||
the origin is indistinguishable from "stay put". The port keeps the
|
||
conversion quirk (the bytes are what matters) but not the sentinel: it
|
||
returns an optional `Jump`.
|
||
8. **An empty `MachinePool` serialises to five fields, not four.**
|
||
`SerializedAsString` joins the machines it has and then appends `",:"` once
|
||
per empty slot (`MachinePool.cs:292-299`), so zero machines give
|
||
`",:,:,:,:"` while the documented default is `":,:,:,:"`. The parser splits
|
||
on commas and reads only the first four fields (`MachinePoolHelpers.cs:31`),
|
||
so both load identically.
|
||
9. **A disconnected machine is back-dated, not removed.**
|
||
`SetMachineDisconnected` clamps the timestamp to
|
||
`now - HEARTBEAT_TIMEOUT + 10 000 ms` (`MachinePool.cs:111-122`), so the
|
||
machine keeps its pool slot and its matrix position and comes back to life on
|
||
the next heartbeat without any renegotiation.
|
||
10. **A failed read is a packet, and it spends the untrusted budget.**
|
||
`TcpReceiveData` does not signal a bad read out of band: it overwrites the
|
||
type byte of the buffer it was filling with `PackageType.Error` when the
|
||
read returned 0 bytes and `PackageType.Invalid` when it returned a short
|
||
count, for both the 32-byte and the 64-byte halves
|
||
(`SocketStuff.cs:574-578, 588-593`). `MainTCPRoutine` then increments a
|
||
private `errCount` for the `Error` case only, closing with
|
||
`SocketStatus.Error` on the sixth in a row (`:1332-1364`), resets `errCount`
|
||
on **any** other type including `Invalid` (`:1366-1368`) — and then lets the
|
||
package fall through the `Type == Handshake` test into the ordinary
|
||
untrusted branch (`:1370-1529`). Consequences worth stating, because they
|
||
are not obvious from the code's shape:
|
||
- A short read during the handshake is counted as one of the ten untrusted
|
||
packets. Five of them raise `SocketStatus.InvalidKey` (`:1519-1521`) and
|
||
ten send the ten `Invalid` packets and close (`:1389-1400`) — so a run of
|
||
malformed reads ends in `InvalidKey`, not `Error`.
|
||
- A 0-byte read spends the untrusted budget **and** an `errCount`, so
|
||
whichever limit is reached first decides how the connection dies: six in
|
||
a row close with `Error` before the tenth untrusted packet, but errors
|
||
interleaved with any other traffic reset `errCount` while `packageCount`
|
||
keeps climbing.
|
||
- The trusted branch is guarded by `receivedCount > 0` (`:1531`), so a
|
||
0-byte read never reaches `Receiver.ProcessPackage`; a short read does,
|
||
and `PreProcess` drops it for being `Invalid` (`Receiver.cs:42-50`).
|
||
11. **`SkSend` stamps one `Id` and writes the same `DATA` to every matching
|
||
socket.** The increment happens once, before the loop
|
||
(`Common.cs:916`), and the same struct is then handed to `TcpSend` for
|
||
each socket whose `MachineId` matches `Des` — or, for `Des == ID.ALL`,
|
||
every socket that is not `exceptDes` and whose machine is in the matrix
|
||
(`:919-929`). `TcpSend` fills `Src` when it is `ID.NONE` and touches
|
||
nothing else (`SocketStuff.cs:666-669`). So a peer reached over two
|
||
connections receives the *same* `Id` twice and the receiver's 50-entry
|
||
replay ring collapses the second delivery (`Receiver.cs:40-82`) — which
|
||
is the mechanism, not an accident, and the reason contracts C1 requires
|
||
the app to stamp an application packet once and distribute it unchanged.
|
||
A per-connection stamp would give the duplicate a fresh `Id` and defeat
|
||
the ring. Only the packets Windows itself sends per connection — the
|
||
handshake pair, the heartbeat written on a fresh connection
|
||
(`SocketStuff.cs:1451`), `Hi` and `ByeBye` — go out through `TcpSend`
|
||
with no `SkSend` in front of them.
|
||
|
||
### 10.3 control-channel (2026-09-16)
|
||
|
||
1. **The 30-second connect budget is per socket-open, not per attempt.**
|
||
`connectTimeout = Common.GetTick() + (CONNECT_TIMEOUT / 2)` with
|
||
`CONNECT_TIMEOUT = 60000` is computed **once**, in the `SocketStuff`
|
||
constructor (`SocketStuff.cs:158, 176, 276`), and every client thread
|
||
compares its 1 s retry loop against that one deadline (`:1179-1193`). So the
|
||
cadence is "retry every second, but only during the first 30 seconds after
|
||
the sockets were opened" — a machine powered on a minute later is not dialled
|
||
at all until something reopens the sockets.
|
||
2. **Dialling is triggered, never polled.** `UpdateTCPClients` (`:797-837`) runs
|
||
only when something calls `MachineStuff.UpdateClientSockets`: after a
|
||
server-side handshake completes (`:1479`), when a peer is learned
|
||
(`MachineStuff.cs:775`), on the matrix's fourth packet (`:997`), on
|
||
`REOPEN_WHEN_WSAECONNRESET` (`frmScreen.cs:461`), once at tick 20
|
||
(`frmScreen.cs:530-537`) and from `ReopenSockets` (`Common.cs:1260`). What
|
||
actually keeps a matrix alive after that window is the **reopen countdown**:
|
||
`PleaseReopenSocket` is set to 9 at init (`InitAndCleanup.cs:140`) and to 10
|
||
on a network-availability change (`:273-276`), and the 100 ms timer reopens
|
||
*all* sockets when it is 10, or every 30 s (`count % 300`) while it is
|
||
positive and no socket is established (`frmScreen.cs:427-450`). The two
|
||
negative sentinels are separate paths: `REOPEN_WHEN_HOTKEY (-10055)` reopens
|
||
everything, `REOPEN_WHEN_WSAECONNRESET (-10054)` only re-runs the client loop
|
||
(`frmScreen.cs:452-461`, `InitAndCleanup.cs:28-29`).
|
||
3. **An id collision force-closes every socket, not just the offending one —
|
||
and it is only ever detected on a client socket.** In `UpdateTcpSockets`,
|
||
`tobeRemovedSockets` starts as the *whole* socket list and
|
||
is narrowed to "other clients with the same machine name" only in the `else`
|
||
branch; the collision branch leaves it whole and sets `tcp = null` so the new
|
||
socket's status is never written (`SocketStuff.cs:1978-1998`). A new
|
||
`MachineId` is drawn and `PleaseReopenSocket = REOPEN_WHEN_HOTKEY` reopens
|
||
everything (`:1985-1990`). The id comparison and the keep-the-first-client
|
||
rule are two branches of one block gated by `status ==
|
||
SocketStatus.Connected && tcp.IsClient` (`:1980-1981`), so a server-accepted
|
||
socket reaches neither: a peer that announces our own `MachineId` over an
|
||
inbound connection is silently tolerated. Note 4's client-only observation
|
||
about the dedup half is the same gate.
|
||
4. **Duplicate clients are suppressed twice; duplicate servers never are.** The
|
||
newcomer closes itself just before it would become trusted
|
||
(`SocketStuff.cs:1421-1428`), and `UpdateTcpSockets` independently keeps the
|
||
first connected client and force-closes the rest (`:1998`). Both tests go
|
||
through `IsConnectedByAClientSocketTo`, which only looks at sockets with
|
||
`IsClient` set (`Common.cs:1142-1161`), so the inbound half of a pair is never
|
||
de-duplicated and a machine pair really does end up with two connections —
|
||
which is why one `Id` must reach both (§10.2 note 11, contracts C1).
|
||
5. **The per-endpoint failure budget is keyed by address *and port*, counts only
|
||
mismatched acks, and quits the app.** `FailedAttempt` is a static
|
||
`ConcurrentDictionary` keyed by `RemoteEndPoint.ToString()`
|
||
(`SocketStuff.cs:159, 1487-1497`), incremented only in the branch where the
|
||
`HandshakeAck` nonce does not match; the eleventh shows a message box and
|
||
calls `Quit`. The ">10 untrusted packets" branch (`:1389-1400`) never touches
|
||
it. Because the key carries the remote *port*, which is new on every TCP
|
||
connection, the counter in practice almost never reaches ten — it is a
|
||
same-connection guard, not a same-peer one.
|
||
6. **`Name2IP` is concatenated with a policy list, is used in addition to DNS,
|
||
and each group is filtered separately — and a mapped group that fails the
|
||
subnet check aborts the whole round.** `Name2IpPolicyList + "\r\n" +
|
||
Name2IP` is split on CRLF and then on blanks (`:906-925`); the mapped
|
||
addresses get their own same-subnet check and are dialled **before**
|
||
`Dns.GetHostEntry` is called at all (`:928-944, 950`), while the DNS group
|
||
gets the reverse-lookup filter (`:989-1032`) and then its own same-subnet
|
||
check (`:1035-1044`). Reverse-lookup validation therefore never applies to a
|
||
user-supplied mapping. The two checks fail differently: the mapped group's
|
||
failure is a `return` from `StartNewTcpClient` (`:934-937`) that skips DNS
|
||
resolution entirely, so **nothing** is dialled for that name that round; the
|
||
DNS group's failure is a `return` reached after the mapped addresses already
|
||
went to `StartNewTcpClientThread` (`:941, 1037-1040`), so it drops only the
|
||
DNS addresses. Filtering the union of the two groups instead would both
|
||
dial out-of-subnet DNS addresses whenever one mapped address matched, and
|
||
dial DNS addresses Windows never resolves.
|
||
7. **The socket options are per connection, set inside `MainTCPRoutine`.**
|
||
`SendBufferSize`/`ReceiveBufferSize = PACKAGE_SIZE * 10000` (320 000),
|
||
`NoDelay = true` and `SendTimeout = 500` are applied to the accepted or
|
||
connected socket, not to the listener (`SocketStuff.cs:1281-1286`).
|
||
8. **After the 48-byte preamble the stream is packet-aligned in both
|
||
directions.** Every write is a whole 32- or 64-byte packet through a
|
||
no-padding CBC stream (§2.3), and the preamble is exactly 48 bytes, so a
|
||
reader that takes 48 bytes and then exactly 32 at a time never straddles a
|
||
packet: 32 bytes of ciphertext in are always 32 bytes of plaintext out. That
|
||
makes a macOS stream read mean exactly what `ReadEx(buf, 0, PACKAGE_SIZE)`
|
||
means on Windows (`:574`), including "a short count is an `Invalid` package
|
||
and a zero count is an `Error` package" (`:574-578, 588-593`).
|
||
|
||
### 10.4 input-capture (2026-09-16)
|
||
|
||
1. **Hotkey matching is one-sided, which is why the Ctrl+Alt block needs its
|
||
own veto.** `Common.HotkeyMatched` (`Common.cs:127-129`) tests only that
|
||
the code is equal and that every modifier the hotkey *asks for* is down;
|
||
extra modifiers are ignored. So Win+Ctrl+Alt+L still fires with Shift also
|
||
held, while the switch-machine keys, which are matched by arithmetic rather
|
||
than by a `HotkeySettings` (`InputHook.cs:611-614`), are guarded by an
|
||
explicit `shiftDown || winDown → return true` (`:604-610`, issue #26597).
|
||
Only the second family is protected.
|
||
2. **`Md.WheelDelta` carries three unrelated things.** For `WM_MOUSEWHEEL` /
|
||
`WM_MOUSEHWHEEL` it is a signed multiple of 120; for `WM_XBUTTON*` it is the
|
||
button index 1 or 2; for `NextMachine (121)` it is a machine id (§4.4). The
|
||
sender extracts it as `(short)((mouseData >> 16) & 0xffff)`
|
||
(`InputHook.cs:254`) — a *signed* 16-bit read, so a wheel notch towards the
|
||
user arrives as −120 and not as 65416.
|
||
3. **While a remote machine is controlled, the coordinates on the wire come
|
||
from a virtual cursor, not from the pointer.** The hook keeps
|
||
`hookCallbackMouseData.X/Y`, adds the raw delta from the real pointer to it,
|
||
and clamps the result to `PrimaryScreenBounds ± 1` (`InputHook.cs:287-309`).
|
||
That clamped value is what `Event.cs:112-113` scales to 0..65535 and what
|
||
edge detection is fed, which is how the *controller's* primary monitor
|
||
becomes the rectangle a controlled machine's pointer roams (§4.4). On macOS
|
||
the real pointer is frozen by `CGAssociateMouseAndMouseCursorPosition(false)`
|
||
while deltas keep arriving, so the same virtual cursor is kept explicitly.
|
||
4. **The relative bias is applied unconditionally; the setting only chooses
|
||
which pair of numbers is sent.** `InputHook.cs:311-312` adds
|
||
`MOVE_MOUSE_RELATIVE` to every `dx`/`dy` it computes, zero included, whether
|
||
or not `MoveMouseRelatively` is on. `Event.cs:105` then picks the tagged
|
||
deltas when the setting is on and the absolute pair when it is off, so its
|
||
`Math.Abs(dx) >= MOVE_MOUSE_RELATIVE` test is always true on that path and
|
||
is not a second condition.
|
||
5. **A pending switch overrides the next few mouse packets.** After
|
||
`PrepareToSwitchToMachine` sets `SwitchLocation`, the hook replaces the
|
||
coordinates of the next `SwitchLocation.Count` mouse events with the landing
|
||
point — in pixels when it is `XY_BY_PIXEL`-tagged, otherwise scaled from the
|
||
controller's primary monitor — and calls `Common.HideMouseCursor(false)`
|
||
once (`InputHook.cs:268-284`). `Event.cs:97` suppresses the outgoing packet
|
||
entirely while that counter is positive.
|
||
6. **`LLKHF_EXTENDED` and `LLKHF_ALTDOWN` are read from the Windows hook
|
||
struct, never computed** (`InputHook.cs:348`), so a non-Windows sender has to
|
||
synthesise them: `ALTDOWN` from its own Alt state, `EXTENDED` from the fixed
|
||
Windows set — the navigation block, right Control and right Alt, both Windows
|
||
keys, keypad divide, Num Lock and the keypad's Enter. The keypad Enter is the
|
||
only key where the bit is load-bearing rather than cosmetic: it and Return
|
||
share `VK_RETURN 0x0D` and the receiver tells them apart by the bit
|
||
(`InputSimulation.cs:108-157`).
|
||
7. **`ReleaseAllKeys` releases eleven virtual keys, not eight.** The list is
|
||
`LSHIFT, LCONTROL, LMENU, LWIN, RSHIFT, RCONTROL, RMENU, RWIN, SHIFT, MENU,
|
||
CONTROL` (`InitAndCleanup.cs:225-229`), each sent only if
|
||
`GetAsyncKeyState` says it is down, and the whole routine is rate-limited to
|
||
once per 2 s (`:215-220`).
|
||
8. **Two input counters, and only one of them means "a human is here".**
|
||
`Event.InputEventCount` is bumped for every hook callback including our own
|
||
injected events (`InputHook.cs:209, 339`); `Event.RealInputEventCount` is
|
||
bumped only after the `RealData` check (`:223, 345`). It is the second one
|
||
`SendAwakeBeat` compares (§3.3), so a machine being driven remotely does not
|
||
keep its own screensaver awake.
|
||
9. **Monitor enumeration seeds the desktop from the primary and never unions
|
||
it.** `GetScreenConfig` copies `Screen.PrimaryScreen.Bounds` into both
|
||
rectangles first (`WinAPI.cs:122-125`), and `MonitorEnumProc` extends
|
||
`newDesktopBounds` only in the `else` branch, i.e. only for monitors that are
|
||
*not* at the origin (`:70-102`). The corner list (`SensitivePoints`,
|
||
`:104-109`) is built from `rcMonitor`'s exclusive right/bottom, so the
|
||
corners of a 1920×1080 monitor at the origin are (0,0), (1920,0),
|
||
(1920,1080), (0,1080) — one pixel outside the monitor on two sides.
|
||
`CGDisplayBounds` uses the same half-open convention, so the macOS corners
|
||
are computed the same way.
|
||
10. **macOS-side facts this lane established.** Left and right modifiers are
|
||
distinguished by the device bits of `CGEvent.flags`, which `CGEventFlags`
|
||
does not expose: `NX_DEVICELCTLKEYMASK 0x01`, `LSHIFT 0x02`, `RSHIFT 0x04`,
|
||
`LCMD 0x08`, `RCMD 0x10`, `LALT 0x20`, `RALT 0x40` and — not adjacent to the
|
||
others — `NX_DEVICERCTLKEYMASK 0x2000`, with Caps Lock's state in
|
||
`NX_ALPHASHIFTMASK 0x10000`. Keys with no Windows virtual-key code (`fn`,
|
||
the keypad `=`, the JIS-only keys) cannot be sent at all and stay local. The
|
||
sign convention of `scrollWheelEventFixedPtDeltaAxis2` against Windows'
|
||
"positive `WM_MOUSEHWHEEL` means scroll right" is **not yet verified** and
|
||
is a CP1 question.
|
||
|
||
### 10.5 input-inject (2026-09-16)
|
||
|
||
1. **The 10 ms sleep after a key-up never happens, on either side.**
|
||
`Event.KeybdEvent` sleeps 10 ms when `KeybdPackage.Kd.dwFlags is WM.WM_KEYUP
|
||
or WM.WM_SYSKEYUP` (`Event.cs:268-271`), i.e. when it equals 0x101 or 0x105.
|
||
But `dwFlags` on that path is the `LLKHF` bit field copied straight out of the
|
||
hook struct (`InputHook.cs:347`), whose only possible values are combinations
|
||
of `EXTENDED 0x01`, `INJECTED 0x10`, `ALTDOWN 0x20` and `UP 0x80` — never
|
||
0x101. The comparison is therefore always false and the sleep is dead code.
|
||
Neither the sender nor the receiver has anything to pace here; TODO §5's "10 ms
|
||
after key-up like Windows only if needed" is answered "not needed".
|
||
2. **The receiver intercepts four chords and eats three of them.**
|
||
`InputSimulation.InputProcessKeyEx` (`:372-475`) runs on every key *about to be
|
||
injected*: the receiver's own `HotKeyLockMachine` (`:406-416`) and Win+L
|
||
(`:450-460`) each set `eatKey`, call `ReleaseAllKeys` and `LockWorkStation`;
|
||
Ctrl+Alt+Del (`:440-448`) is eaten and only releases keys; Ctrl+Alt+End
|
||
(`:462-469`) starts the Windows service and is **not** eaten, so the key still
|
||
reaches the desktop. Locking on a remote chord is thus the *receiver's*
|
||
decision against the *receiver's* settings, not a packet type.
|
||
3. **The modifier state those chords match against is the remote keyboard's,
|
||
rebuilt from the wire.** Four booleans (`:358-361`) are driven only by the
|
||
side-specific VKs `LWIN/RWIN/LCONTROL/RCONTROL/LMENU/RMENU/LSHIFT/RSHIFT`
|
||
(`:380-398, 420-438`); the side-less `VK_SHIFT/CONTROL/MENU` do not touch them
|
||
even though `ReleaseAllKeys` (`InitAndCleanup.cs:225-229`) and the lock-chord
|
||
replay (`InputHook.cs:485-512`) both put those on the wire. They are a
|
||
*separate* set of facts from what the local keyboard is holding, which Windows
|
||
reads back with `GetAsyncKeyState`; `ResetModifiersState` (`:364-370`) edits
|
||
the first without touching the second.
|
||
4. **`SendMouse` fills in dx/dy for every message, and Windows uses them only for
|
||
moves.** `mi.dx/dy` are computed before the switch (`InputSimulation.cs:170-173`)
|
||
but `SendInput` ignores them unless `MOUSEEVENTF_MOVE` is set, which only the
|
||
`WM_MOUSEMOVE` case does (`:183-185`, `NativeMethods.cs:549`). So the position
|
||
in a button or wheel packet is discarded by a Windows receiver — confirmed by
|
||
`Receiver.cs:149-151`, which overwrites `Md.X/Y` from `GetCursorPos` before
|
||
calling `SendMouse` on the relative path. On macOS every mouse event carries a
|
||
location, so the equivalent is to post buttons and wheels at the **current
|
||
pointer**, never at the packet's coordinates.
|
||
5. **`MOUSEEVENTF_ABSOLUTE` is 0..65535 over the *primary* monitor, not the
|
||
desktop** (`NativeMethods.cs:561`; no `MOUSEEVENTF_VIRTUALDESK` anywhere in the
|
||
module). That is the whole reason `SendMouse` rescales the desktop rectangle
|
||
into primary units (`:165-171`) rather than mapping the universal value onto
|
||
the desktop directly. A macOS injector therefore lands an absolute move at
|
||
`Coordinates.fromUniversal(Coordinates.absoluteMove(u, desktop:, primary:),
|
||
in: primary)` — two steps, keeping the Windows rounding of each.
|
||
6. **The lock chord is replayed in a fixed, non-symmetric order**: Alt, Shift,
|
||
Win, Ctrl, then the key (`InputHook.cs:485-512`), with the ups sent in the
|
||
*same* order rather than reversed (`:548-562`), and with the side-less
|
||
`VK_MENU`/`VK_SHIFT`/`VK_CONTROL` plus `VK_LWIN`.
|
||
7. **macOS-side facts this lane established.**
|
||
- A modifier cannot be injected as a key press. `CGEvent(keyboardEventSource:
|
||
virtualKey:keyDown:)` for keycode 56 produces a `keyDown`, which is not how
|
||
anything on macOS learns that Shift is down; the event has to be re-typed to
|
||
`.flagsChanged`, and every *other* event we post has to carry the modifier
|
||
masks in `.flags` as well, because macOS keeps no global modifier state for
|
||
injected input the way `SendInput` does.
|
||
- **Click count is ours.** Windows drops `WM_*BUTTONDBLCLK` (no `MOUSEEVENTF`
|
||
case, `InputSimulation.cs:181-219`) and a double click travels as two plain
|
||
downs, so nothing on the wire says "double". macOS decides from
|
||
`mouseEventClickState`, so the receiver has to count consecutive downs of the
|
||
same button within `NSEvent.doubleClickInterval` and a few pixels, and repeat
|
||
the count on the matching up.
|
||
- `CGMouseButton` names only left/right/center, so an X-button event is created
|
||
as `.center` and corrected with `mouseEventButtonNumber` (3 or 4) afterwards.
|
||
- **Remote Win+L locks this Mac, and ⌘ is Win (README D4), so a remote ⌘L
|
||
locks it too.** Faithful to `:450-460`, and a CP1 question: on a Mac ⌘L is a
|
||
common application shortcut, so a Mac-to-Mac matrix may want this off.
|
||
- Whether the user's "natural scrolling" preference should apply to a remote
|
||
mouse's wheel is also a CP1 question; we post `.line` units with the sign the
|
||
capture side reads, so the two halves agree with each other whatever the
|
||
answer (see §10.4 note 10 for the still-unverified horizontal sign).
|
||
8. **The lock hotkey's desktop gate has no macOS equivalent, so the receiver
|
||
always eats it and always locks.** On Windows the `HotKeyLockMachine` match is
|
||
wrapped in `if (!Common.RunOnLogonDesktop && !Common.RunOnScrSaverDesktop)`
|
||
(`InputSimulation.cs:408-409`): on those two desktops `HotkeyMatched` can be
|
||
true while `eatKey` stays `false`, so the key is passed through and nothing
|
||
locks. Both flags are set only in `Program.Main` when the MWB **service**
|
||
launches a second copy of the process onto the `Winlogon` or `Screen-saver`
|
||
desktop (`Program.cs:150-167`, from `Common.RunOnScrSaverDesktop`/
|
||
`RunOnLogonDesktop`, `Common.cs:176-186`) — Win32 secure desktops, one process
|
||
instance per desktop, each with its own hook. macOS has no such split: there
|
||
is one process per login session, `loginwindow` and the screen saver are not
|
||
desktops that host a copy of us, and once the screen is actually locked the
|
||
system stops delivering to and posting from a user-space event tap anyway. The
|
||
condition is therefore unconditionally true for a Mac receiver, which is why
|
||
`KeyState.processDown` has no guard. The Windows service that creates those
|
||
desktops is out of scope in the first place (README D6). Note that the
|
||
hardcoded Win+L branch (`:450-460`) carries no such gate on Windows either, so
|
||
only the configurable hotkey was ever gated.
|
||
|
||
### 10.6 app-engine (2026-09-16)
|
||
|
||
1. **A switch moves the pointer only when the target is the local machine.**
|
||
`Event.PrepareToSwitchToMachine` records `MachineStuff.SwitchLocation` and sets
|
||
`EvSwitch` (`Event.cs:180-184`); the cursor work is all done afterwards by
|
||
`Helper.HelperThread` (`Helper.cs:75-127`), which branches on
|
||
`NewDesMachineID`: a *remote* target gets `HideMouseCursor(false)` and the
|
||
parked dot, and only `NewDesMachineID == MachineID` reads `SwitchLocation` and
|
||
calls `MoveMouse`/`MoveMouseEx` (`Helper.cs:96-113`). So `SwitchAction.moveCursor` is a landing for
|
||
*this* machine; consuming it unconditionally would throw the user's pointer at
|
||
the far machine's landing coordinates every time control left. The same thread
|
||
calls `ReleaseAllKeys()` whenever `NewDesMachineID == MachineID` (`Helper.cs:120-123`),
|
||
which is the third place Windows releases keys on a switch home.
|
||
2. **A `Mouse` packet addressed to us takes control back by assignment, not by
|
||
switching.** `Receiver.cs:122-125` sets `NewDesMachineID = DesMachineID =
|
||
MachineID` inline: no `HideMouse` to the machine we were driving, no cursor
|
||
move, no `MachineSwitched`. It is a defensive line for the crossed state where
|
||
two machines each think they are the controller. A port that reaches for
|
||
`SwitchToMachine(MachineName)` here must drop that call's cursor move, or the
|
||
jump to the primary screen's centre will fight the mouse packet that is about
|
||
to be injected.
|
||
3. **In relative mode the *controlled* machine does the edge detection.**
|
||
`Receiver.cs:147-172`: after `MoveMouseRelative`, the receiver reads
|
||
`GetCursorPos` and runs `MoveToMyNeighbourIfNeeded(..., Common.MachineID)`
|
||
itself, then `SendNextMachine(package.Src, newDesMachineIdEx, p)` back to the
|
||
controller, which treats it like an edge crossing of its own
|
||
(`Receiver.cs:195-201` → `PrepareToSwitchToMachine`). That is the only reason
|
||
`NextMachine (121)` exists, and it is why the receiving side needs a
|
||
"where is the pointer right now" read that nothing else on the receive path
|
||
needs. The acceptance test on the controller is
|
||
`Event.IsSwitchingByMouseEnabled()` — `EasyMouse == Enable` **or** the Ctrl /
|
||
Shift Easy-Mouse key being held (`InputHook.EasyMouseKeyDown`,
|
||
`InputHook.cs:92, 404, 467-473`), not the setting alone.
|
||
4. **The reconnect countdown is 30 s and is gated on "no socket established".**
|
||
`frmScreen.HelperTimer_Tick` runs every 100 ms (`:285-288`). The reopen block
|
||
is inside `if ((count % 2) == 0)` and fires on `count % 300 == 0`
|
||
(`frmScreen.cs:425-427`) — 30 s — and only when `!Common.AtLeastOneSocketEstablished()`;
|
||
when a socket *is* established it clears `PleaseReopenSocket` instead
|
||
(`frmScreen.cs:446-449`). `PleaseReopenSocket` is a counter with two sentinel values, not a
|
||
flag: `REOPEN_WHEN_HOTKEY = -10055` and `REOPEN_WHEN_WSAECONNRESET = -10054`
|
||
(`InitAndCleanup.cs:28-29`), handled separately at `frmScreen.cs:452-462`. 30 s is also the
|
||
connect budget the control channel gives up after (§10.3 notes 1–2), so the two
|
||
line up: the countdown fires exactly as the budget expires.
|
||
5. **The settings file's JSON shapes, exactly.** The envelope is
|
||
`{"name":"MouseWithoutBorders","version":"1.1","properties":{…}}`
|
||
(`MouseWithoutBordersSettings.cs:27-34`) and the property names are the C#
|
||
property names verbatim — no naming policy is set on the serializer
|
||
(`MouseWithoutBordersSettings.cs:20-25`). Inside `properties`:
|
||
- every `bool` goes through `BoolPropertyJsonConverter` and every `IntProperty`
|
||
/ `StringProperty` / `GenericProperty` is a record with one `value` field, so
|
||
they are all written as `{"value": …}` — `"WrapMouse": {"value": true}`,
|
||
`"TCPPort": {"value": 15100}`;
|
||
- `MachineMatrixString` is the exception: a bare `List<string>`, so a plain
|
||
JSON array (`MouseWithoutBordersProperties.cs:85-86`). The MWB app joins and
|
||
splits it on `,` (`Setting.cs:216-236`), which is where the
|
||
`"a,b,c,d"` form in `MachineMatrixString` comes from;
|
||
- the four shortcuts are `HotkeySettings`, whose fields carry explicit
|
||
lower-case names: `{"win":…,"ctrl":…,"alt":…,"shift":…,"code":…,"key":""}`
|
||
(`HotkeySettings.cs:121-136`). `win` is ⌘ and `alt` is ⌥ on a Mac (README D4);
|
||
- `MachineID` is seeded from `Encryption.Ran.Next()` (`Setting.cs:1058`), i.e.
|
||
`System.Random.Next()`, so it is always a **non-negative** `Int32` — never 0
|
||
after generation, because 0 is the "not set yet" sentinel the getter tests.
|
||
6. **`Heartbeat` and `Awake` are 64-byte packets.** Not new, but worth stating
|
||
where the receiver is described: `MachineStuff.AddToMachinePool` reads
|
||
`package.MachineName` (`:712-777`), which only exists on a big packet, so a
|
||
32-byte heartbeat would teach the peer nothing. `PackageType.isBig` already
|
||
lists them (§1.2).
|
||
|
||
### 10.7 clipboard (2026-09-16)
|
||
|
||
1. **The 64-byte `DATA` on the bulk connection is written raw, not framed.**
|
||
This was the lane's question (a). `Clipboard.ShakeHand` builds the package
|
||
and writes it with `enStream.Write(package.Bytes, 0, PACKAGE_SIZE_EX)`
|
||
(`Clipboard.cs:987`) — no `TcpSendData`, so no magic number and no checksum
|
||
in bytes 1–3 (§1.3). The reader is `deStream.ReadEx(buf, 0,
|
||
PACKAGE_SIZE_EX)` followed by `package.Bytes = buf` (`:996-997`), which
|
||
marshals the buffer straight into the struct, so `Type` is read as the full
|
||
**four-byte** `int` (`DATA.cs:27-28, 115-121`). Consequences:
|
||
- a sender must leave bytes 1–3 **zero**, or the acceptor's `Type` is not
|
||
69/79 and `ShakeHand` rejects the connection;
|
||
- a receiver must check those three bytes, not only byte 0 — our `Packet`
|
||
exposes byte 0 alone, so `BulkConnection.acceptHandshake` tests them
|
||
explicitly;
|
||
- there is no checksum on this connection at all. What authenticates it is
|
||
that the AES-256-CBC stream is derived from the shared key (§2.3) — the
|
||
wrong key turns the 64 bytes into noise whose type byte is not 69 or 79 —
|
||
plus the `MachinePool.ResolveID(name) == Src && IsConnectedTo(Src)` gate
|
||
(`Clipboard.cs:1009`). Both halves are required before a single byte of
|
||
payload is read or written (CLAUDE.md invariant 2).
|
||
2. **Foundation's `.zlib` is raw DEFLATE, byte-compatible with .NET's
|
||
`DeflateStream`.** This was question (b), and it is **[verified]**, not
|
||
transcribed. A UTF-16LE tag/SEP fixture compressed with
|
||
`(data as NSData).compressed(using: .zlib)` begins `ad 8e 3b 0a` — no zlib
|
||
header (`78 xx`) and no gzip header (`1f 8b`) — and Python
|
||
`zlib.decompress(bytes, -15)` inflates it to exactly the original, while
|
||
`zlib.decompress(bytes)` fails with "incorrect header check". The reverse
|
||
direction also holds: bytes from Python's `compressobj(9, DEFLATED, -15)`
|
||
inflate correctly through `NSData.decompressed(using: .zlib)`. So
|
||
`NSData.compressed(using: .zlib)` is what `Clipboard.cs:190-201` writes, and
|
||
`compression_stream` is not needed.
|
||
3. **Trailing zeros after the DEFLATE stream are normal and must be
|
||
tolerated**, from two independent directions: the in-band chunker
|
||
zero-fills its last 48-byte packet (`Clipboard.cs:281`), and the sender
|
||
ships `MemoryStream.GetBuffer()` (`:201`), which is the stream's
|
||
**capacity**, not its length — so a Windows payload is routinely longer
|
||
than the compressed data, in-band and on the bulk connection alike (the
|
||
bulk header's `<len>` is that same padded `data.Length`,
|
||
`SocketStuff.cs:1749`). Foundation's inflater ignores the tail;
|
||
**[verified]** with 13 and 137 zero bytes appended.
|
||
4. **`SendData`'s trailing padding is short by construction, and big text and
|
||
images over the bulk connection suffer for it on Windows.** Both senders
|
||
pad after the body so the CBC stream ends on a block boundary — a
|
||
`CryptoStream` in write mode holds back any final partial block, and
|
||
`Flush()` does not release it — but they compute the padding differently:
|
||
`SendFileEx` writes `PACKAGE_SIZE - (sentCount % PACKAGE_SIZE)` bytes
|
||
(`SocketStuff.cs:1832-1836`), which rounds the total up to 32, while
|
||
`SendData` writes `sentCount % PACKAGE_SIZE` bytes (`:1903-1907`). For a
|
||
body of `len` bytes the second gives `len + (len % 32)`, which is a multiple
|
||
of 16 only when `len ≡ 0 (mod 8)`; otherwise 2 to 14 bytes never leave the
|
||
sender and the receiver's `HasExpectedReceivedDataLength` check
|
||
(`Clipboard.cs:943-946`) fails with "Received incomplete file". Files are
|
||
unaffected. We pad the `SendFileEx` way for every payload
|
||
(`ClipboardCodec.trailingPadding`): the receiver reads exactly `<len>` bytes
|
||
and discards the rest either way, so over-padding is invisible on the wire
|
||
and our sends always arrive. **[transcribed]** — read from the source, not
|
||
observed against a running Windows build.
|
||
5. **The HTML flavour is CF_HTML on the wire.** `GetText(TextDataFormat.Html)`
|
||
(`FormHelper.cs:199`) and `DataFormats.Html` (`Clipboard.cs:1169`) are the
|
||
Windows clipboard's `HTML Format`, i.e. the `Version:0.9 / StartHTML: /
|
||
EndHTML: / StartFragment: / EndFragment:` header block followed by a full
|
||
document with `<!--StartFragment-->` markers, whose offsets count **UTF-8
|
||
bytes of the whole CF_HTML string**. macOS's `NSPasteboard.PasteboardType.
|
||
html` is bare markup, so the port wraps on send and unwraps on receive
|
||
(`ClipboardCodec.cfHTML(wrapping:)` / `htmlFragment(from:)`), and the wire
|
||
form is what `ClipboardText.html` always holds.
|
||
6. **A file lands in two different folders on Windows depending on the post
|
||
action, and neither is quite what §6.3 says.** `postAct == "desktop"` (the
|
||
drag-and-drop path) writes to `<Desktop>\MouseWithoutBorders\` and opens
|
||
that folder in Explorer (`Clipboard.cs:679-688, 840-848`); every other post
|
||
action — including the ordinary pull on a machine switch, whose `postAct` is
|
||
the literal string `"PackageType.MachineSwitched"` — writes to
|
||
`Common.GetMyStorageDir()`, which is
|
||
`<Desktop>\MouseWithoutBorders\ScreenCaptures\` (`Common.cs:1321-1327`,
|
||
`Clipboard.cs:726-727`), and puts the file on the clipboard as a file drop
|
||
list instead of revealing it (`:864-868`). The port writes every received
|
||
file to `~/Desktop/MouseWithoutBorders/`, puts its URL on the pasteboard
|
||
**and** reveals it in Finder: one folder is easier to explain than two, and
|
||
`ScreenCaptures` names something (screen capture to Paint) that is out of
|
||
scope (README D6).
|
||
7. **`Clipboard (69)` is a broadcast nobody is addressed by.** The receiver
|
||
does not test `Des` at all (`Receiver.cs:273-282`): any machine that hears
|
||
the beat records the sender as "the machine with big data" and starts its
|
||
own 30 s window. `MachineSwitched (77)`, by contrast, acts only when
|
||
`package.Des == Common.MachineID` (`:285`), and `ClipboardAsk (78)` only
|
||
when `package.Des == Common.MachineID` (`:318`).
|
||
8. **Who pulls and who pushes is decided by the packet type of the *connector's*
|
||
handshake, and the acceptor's own type is ignored.** The acceptor enters
|
||
`ShakeHand` with `clientPushData = true` and therefore always announces
|
||
`ClipboardPush (79)` (`SocketStuff.cs:1643`, `Clipboard.cs:975`); it then
|
||
overwrites that variable from what it received and sends when the connector
|
||
said `Clipboard (69)`, receives when it said `ClipboardPush (79)`
|
||
(`SocketStuff.cs:1655-1665`). The connector overwrites its own copy too and
|
||
then ignores it (`Clipboard.cs:477-484`). `PostAction` is likewise taken
|
||
from the received packet on both sides.
|
||
9. **The "100 interleaved foreign packets" abort is a property of the Windows
|
||
receive loop, not of the format.** `ReceiveClipboardDataUsingTCP` blocks
|
||
the connection's reader until `ClipboardDataEnd` arrives, dispatching any
|
||
other package inline and giving up after 100 of them
|
||
(`Clipboard.cs:308-373`). Our `Session` delivers packets one at a time and
|
||
never blocks, so there is nothing to interleave: `Reassembler` instead
|
||
abandons a payload that grows past the 1 MB in-band limit plus one chunk,
|
||
and `ClipboardBridge` drops a reassembly that has been idle for 30 s. The
|
||
bound that matters — memory — is kept; the counter is not.
|
||
10. **`MAX_CLIPBOARD_DATA_SIZE_CAN_BE_SENT_INSTANTLY_TCP` is compared against
|
||
the *compressed* length for text and the raw PNG for images**
|
||
(`Clipboard.cs:229-240`, after `LastClipboardData` is set at `:201` or
|
||
`:219`), and the comparison is `>`, so exactly 1 MB still goes in-band —
|
||
24 000 packets of it. The helper refuses to read text over 20 MB or an
|
||
image over 50 MB off the clipboard in the first place
|
||
(`FormHelper.cs:28-29, 206, 287`).
|
||
11. **Every in-band clipboard chunk is delivered twice, and only the Windows
|
||
receive loop's shape hides it.** A machine pair keeps two control
|
||
connections (§10.3 note 4) and `SkSend` writes the same bytes with the same
|
||
`Id` to both (§10.2 note 11), while `Receiver.PreProcess` exempts
|
||
`ClipboardText` and `ClipboardImage` from the 50-entry replay ring
|
||
(`Receiver.cs:40-82`). On Windows the first chunk to arrive hands its
|
||
*socket* to `ReceiveClipboardDataUsingTCP`, which then reads the rest of the
|
||
transfer from that socket alone (`Clipboard.cs:308-373`) — so the second
|
||
copy becomes a separate, parallel reassembly on the other socket's thread
|
||
and ends as a second, identical clipboard write. A port whose reassembly is
|
||
keyed by *sending machine* rather than by socket instead sees the two copies
|
||
interleave into one buffer and corrupt it. `Reassembler` therefore keeps its
|
||
own 50-entry ring of chunk `Id`s — which works precisely because contracts
|
||
C1 stamps one `Id` per chunk for both deliveries. `ClipboardDataEnd (76)` is
|
||
**not** exempt from the replay ring, so exactly one terminator arrives; a
|
||
copy that arrives wholly after the terminator starts a reassembly that can
|
||
never finish and is dropped by the idle timeout.
|