diff --git a/CHANGES.md b/CHANGES.md index 92ada47..1264e40 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -3,6 +3,9 @@ ## [Unreleased] ### New +- Settings → Screen has a switch "Let other computers use this keyboard and mouse (Deskflow)", off by default. Once it is on, computers that run the Deskflow client show up there, and after you compare the fingerprint you attach one beside a monitor. Pushing the pointer past that edge then moves keyboard and mouse to the computer, and Ctrl+Alt+Shift+Escape always brings them back. +- Text copied on ThinFloe can be pasted on a computer attached with Deskflow, and text copied there can be pasted on ThinFloe; images, files and texts over 1 MiB are not carried, and copying one on ThinFloe empties the clipboard of the attached computers. Each attached computer has a "Share the clipboard" switch in Settings → Screen, on by default. +- While the pointer is on a computer attached with Deskflow, the volume and brightness keys act on that computer and ThinFloe shows no volume or brightness display. The microphone mute key still mutes ThinFloe, when "Volume keys control this machine" is on. ### Changed diff --git a/CLAUDE.md b/CLAUDE.md index 7350755..bc07e97 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -62,6 +62,7 @@ release. - Stick writer and upgrades: `overlay/usr/bin/thinfloe-upgrade`. - Time zone and NTP: `overlay/usr/bin/thinfloe-time` (live, as root), `install_local_time()` in `thinfloe-lib.sh` (boot), `overlay/usr/libexec/thinfloe/dhcp-timezone` (DHCP zone and NTP servers), the Time band in `timeband.rs`/`network_ui.rs`. Notes: [docs/notes/time-zone.md](docs/notes/time-zone.md). - Add-ons: `overlay/usr/bin/thinfloe-addon` (its docstring lists the commands), hooks in `overlay/usr/libexec/thinfloe/addon-hooks/`. +- Deskflow server: `src/thinfloe-menu/src/deskflow/` (daemon, `thinfloe-menu --deskflow`), `deskflow_sup.rs` (the menu's supervision), `deskflowtab.rs`/`deskflow_ui.rs` (the Deskflow band). Notes: [docs/notes/deskflow.md](docs/notes/deskflow.md). - Battery reader: `overlay/usr/libexec/thinfloe/peripheral-battery` and its units. Bolt microphone mute key (HID++ divert, F20 through uinput): `overlay/usr/libexec/thinfloe/logitech-keys` and `thinfloe-logitech-keys.service`, started by the same udev rule. - Boot screen: `overlay/usr/share/plymouth/themes/thinfloe/`. - User defaults: `overlay/home/tfuser/` (`.config/thinfloe/` with `environment`, `sessionrc` and `home-version`; `.thinlinc/tlclient.conf`). Layout of `~/.config/thinfloe/`: [docs/notes/home-persistence.md](docs/notes/home-persistence.md). @@ -99,7 +100,7 @@ Not standing constraints, but each has broken something or is guarded by a test. - labwc runs with `-C` on a directory composed by `thinfloe-compose-labwc-config` (system files symlinked, `environment` = system defaults, then `generated/environment`, then the user's file). Pointing `-C` at `/etc/thinfloe/labwc` again makes labwc reset user keys to the system values. Guards: `test-labwc-config-merge.sh`, `test-labwc-runtime.sh`. Story: [docs/notes/session.md](docs/notes/session.md). - `thinfloe-save-home` takes the home from `getent passwd tfuser`, never `$HOME` (`sudo` sets `HOME=/root`), and every read under `/run/thinfloe/state` ends in `|| true` (`set -e`). On USB it writes only to the ESP mounted at `/run/thinfloe/storage/efi` (tested with `mountpoint -q`), atomically; the netboot upload uses `curl -f`. Exit codes 0 to 5 are a contract. Guard: `test-save-home.sh`. - The remote-access password hash (`~/.config/thinfloe/password`) and the SSH host keys (`~/.config/thinfloe/ssh-host-keys`) ride the home archive in the clear: on the FAT ESP, or POSTed over plain HTTP on netboot. Accepted; see [docs/notes/home-persistence.md](docs/notes/home-persistence.md). -- A fresh install's home copy always leaves out `~/.config/thinfloe/ssh-host-keys` and `wg0.conf`, their 4.x paths, `~/.dbrrg-ssh-host-keys` and the attic copies in `~/cfg-attic/` (`IDENTITY_EXCLUDES`). Guard: `test_upgrade_image.py`. +- A fresh install's home copy always leaves out `~/.config/thinfloe/ssh-host-keys`, `wg0.conf` and `deskflow/` (the Deskflow private key), their 4.x paths, `~/.dbrrg-ssh-host-keys` and the attic copies in `~/cfg-attic/` (`IDENTITY_EXCLUDES`). Guard: `test_upgrade_image.py`. - Reboot and power off from the session need `sudo systemctl ...`: the image has no polkit. - Screen blanking uses `swayidle` and `wlopm`, never `wlr-randr --off`, which changes the monitor layout. No lock screen: tfuser has no password. - No keybinding for a terminal or screenshots (see the keybinding constraint); from a VT: `XDG_RUNTIME_DIR=/run/user/1001 WAYLAND_DISPLAY=wayland-0 foot` (or `grim`). @@ -114,6 +115,7 @@ Not standing constraints, but each has broken something or is guarded by a test. - A `[keyboard]` value reaches `generated/environment` only through `keyboard::validate`, and values from outside the tab through `keyboard::repair`; the composer checks again with `thinfloe-menu --check-keyboard`. labwc 0.9.3 segfaults at start on a pair XKB cannot build. See [docs/notes/menu.md](docs/notes/menu.md) (Keyboard tab). - The scale file `$XDG_RUNTIME_DIR/thinfloe-scale` is written atomically (one number and a newline); `labwc-scale`, `thinfloe-terminal` and the OSD read it. - The OSD never takes focus or a click (layer overlay, empty input region, keyboard interactivity none), and only the composer writes `allowWhenInhibited`. See [docs/notes/media-keys.md](docs/notes/media-keys.md). +- Deskflow: the daemon is its own process (`thinfloe-menu --deskflow`) and reads only `generated/deskflow`, never `config.toml`; the menu is the only writer of `[deskflow]`. The state file `$XDG_RUNTIME_DIR/thinfloe-deskflow.state` (first line `self` or `error`, then `namefingerprintstatesincewidthheightflags`) and the command socket `thinfloe-deskflow.sock` are a contract between daemon and menu; readers ignore unknown trailing fields. Getting back to ThinFloe never waits for the network or the client (Ctrl+Alt+Shift+Escape, watchdog, keep-alive), and no daemon may outlive the menu. Guard: `test-labwc-runtime.sh`. Notes: [docs/notes/deskflow.md](docs/notes/deskflow.md). - Status area: an element is one module in `status/` plus a line in `status::ELEMENTS`; `draw` is pure and stays in its rect. The layout is `[status]` in `config.toml`, written only by the menu. Notes: [docs/notes/status-area.md](docs/notes/status-area.md). - sysfs attribute files are read with `bounded::read_attr`, never a size-checked reader: sysfs reports one page (4096 bytes on most hosts) for every attribute, and a 256-byte check hid every GPU, MAC and WiFi chip in 4.6.0. Facts on the Network, Screen and This machine tabs are `infopanel::Line`s, labelled. Guards: `bounded`, `graphics` and `netdetail` tests (on the host's real `/sys`). See [docs/notes/menu.md](docs/notes/menu.md) (Settings facts). - The battery file `/run/thinfloe/peripherals/battery` is a contract between the root reader and the menu: one line per device, `namepercentstateread_epochkind`; the menu still reads a 4-field line (kind unknown). See [docs/notes/peripheral-battery.md](docs/notes/peripheral-battery.md). @@ -206,7 +208,8 @@ defines none, and `containers/ubuntu/patches/0005-no-default-keybinds.patch` removes that fallback. `thinfloe-compose-labwc-config` adds bindings only when a switch in Settings → Keyboard is on, and then exactly the six media keys with `allowWhenInhibited="yes"` (patch `0006`), which pass a ThinLinc -grab or an OxuLnk inhibitor; every other key reaches the focused program. +grab or an OxuLnk inhibitor but not the Deskflow capture strip's inhibitor +(patch `0007`); every other key reaches the focused program. Adding any other binding is a deliberate decision followed by `make test-runtime`. Guards: `test-session-packages.sh`, `test-labwc-config-merge.sh`, `test-labwc-runtime.sh` (no `load default key @@ -235,7 +238,8 @@ Guards: `scripts/check-boot-smoke.sh` (any `Found ordering cycle`), The Dockerfile builds `labwc_0.9.3-1+thinfloe1` with `containers/ubuntu/patches/` (fullscreen across outputs, `LABWC_FULLSCREEN_SPAN_OUTPUTS`; `zwp_xwayland_keyboard_grab_manager_v1`; -no default keybindings, `0005`; `allowWhenInhibited` on a keybind, `0006`). +no default keybindings, `0005`; `allowWhenInhibited` on a keybind, +`0006`; a layer-surface inhibitor blocks every keybinding, `0007`). The archive package silently loses all of them. Patches, overlay and brand directories are `Makefile` prerequisites. Guards: `make test`, `make test-runtime`, `test-container-inputs.sh`, `test-container-stamp.sh`. @@ -365,6 +369,7 @@ and hardware results: - [peripheral-battery.md](docs/notes/peripheral-battery.md): the battery reader, its units, the HID++ details and hardware results. - [session.md](docs/notes/session.md): session startup, the user files, the labwc config merge, audio volume, screen blanking, GPU wait, terminals, screenshots. - [time-zone.md](docs/notes/time-zone.md): the Time band, the precedence of menu, DHCP and `TZ=`, chrony and the DHCP NTP servers, and their tests. +- [deskflow.md](docs/notes/deskflow.md): the Deskflow server, pairing, capture and the way back, the state file and socket, known limits. - [home-persistence.md](docs/notes/home-persistence.md): home restore and save, the archive, the password file, exit codes. - [esp-and-upgrade.md](docs/notes/esp-and-upgrade.md): `thinfloe-upgrade`: home copy, size check, the batch interface, check timers. - [network-boot.md](docs/notes/network-boot.md): netboot networking and its smoke test. diff --git a/containers/ubuntu/Dockerfile b/containers/ubuntu/Dockerfile index 1b6a2f3..88ee351 100644 --- a/containers/ubuntu/Dockerfile +++ b/containers/ubuntu/Dockerfile @@ -9,7 +9,9 @@ # default keybindings when rc.xml defines none # (0005-no-default-keybinds.patch), and a keybinding marked # allowWhenInhibited="yes" still runs under a keyboard grab or shortcuts -# inhibitor (0006-keybind-allow-when-inhibited.patch); +# inhibitor (0006-keybind-allow-when-inhibited.patch), but no keybinding +# runs while a layer surface with a shortcuts inhibitor, the Deskflow +# capture strip, has the keyboard (0007-layer-inhibitor-blocks-all-keybinds.patch); # see docs/superpowers/specs/2026-07-27-labwc-multimonitor-fullscreen-design.md. # # Patches live in containers/ubuntu/patches/ and are appended to the source diff --git a/containers/ubuntu/patches/0007-layer-inhibitor-blocks-all-keybinds.patch b/containers/ubuntu/patches/0007-layer-inhibitor-blocks-all-keybinds.patch new file mode 100644 index 0000000..0193e73 --- /dev/null +++ b/containers/ubuntu/patches/0007-layer-inhibitor-blocks-all-keybinds.patch @@ -0,0 +1,134 @@ +Description: a layer-surface inhibitor blocks every keybinding + The Deskflow capture strip of thinfloe-menu is an overlay layer surface + that takes the keyboard exclusively while the pointer is on an attached + device. With 0004 an inhibitor on a layer surface was ignored, and the + media key bindings carry allowWhenInhibited="yes" (0006), so the volume + and brightness keys changed the local machine instead of reaching the + device, even over an X11 keyboard grab. + . + An inhibitor on a layer surface is now activated and stays in the wlroots + manager's list until it or its surface goes. While the seat's keyboard + focus is a layer surface with such an inhibitor, no keybinding runs, + allowWhenInhibited ones included, and every key goes to that surface. + Inhibitors on views behave as before. + . + thinfloe-specific: not proposed for upstream inclusion, see Forwarded below. +Author: ThinFloe maintainers +Origin: vendor +Forwarded: not-needed +Last-Update: 2026-11-22 +--- +diff --git a/include/labwc.h b/include/labwc.h +index f4dfd8e..c0bc4ae 100644 +--- a/include/labwc.h ++++ b/include/labwc.h +@@ -452,6 +452,7 @@ void server_finish(struct server *server); + + void xwayland_keyboard_grab_manager_create(struct server *server); + void keyboard_shortcuts_inhibit_create(struct server *server); ++bool keyboard_shortcuts_inhibited_by_layer(struct seat *seat); + + void create_constraint(struct wl_listener *listener, void *data); + void constrain_cursor(struct server *server, struct wlr_pointer_constraint_v1 +diff --git a/src/input/keyboard.c b/src/input/keyboard.c +index e6f82a4..cb6bec1 100644 +--- a/src/input/keyboard.c ++++ b/src/input/keyboard.c +@@ -538,6 +538,16 @@ handle_compositor_keybindings(struct keyboard *keyboard, + } + } + ++ /* ++ * thinfloe (0007): a layer surface with the keyboard focus and a ++ * shortcuts inhibitor gets every key; no binding runs, not even an ++ * allowWhenInhibited one. ++ */ ++ if (keyboard_shortcuts_inhibited_by_layer(seat)) { ++ cur_keybind = NULL; ++ return LAB_KEY_HANDLED_FALSE; ++ } ++ + /* + * Handle compositor keybinds + */ +diff --git a/src/protocols/keyboard-shortcuts-inhibit.c b/src/protocols/keyboard-shortcuts-inhibit.c +index 38a0936..8397c31 100644 +--- a/src/protocols/keyboard-shortcuts-inhibit.c ++++ b/src/protocols/keyboard-shortcuts-inhibit.c +@@ -20,6 +20,8 @@ + #include + #include + #include ++#include ++#include + #include + #include "common/mem.h" + #include "labwc.h" +@@ -33,6 +35,8 @@ struct lab_shortcuts_inhibitor { + + static struct wl_listener on_new_inhibitor; + static struct wl_listener on_manager_destroy; ++/* thinfloe (0007): to find the inhibitors of a focused layer surface */ ++static struct wlr_keyboard_shortcuts_inhibit_manager_v1 *inhibit_manager; + + static void + handle_view_destroy(struct wl_listener *listener, void *data) +@@ -66,7 +70,15 @@ handle_new_inhibitor(struct wl_listener *listener, void *data) + wlr_surface_get_root_surface(inhibitor->surface); + struct view *view = root ? view_from_wlr_surface(root) : NULL; + if (!view) { +- /* No window (e.g. a layer surface): nothing to inhibit for. */ ++ /* ++ * thinfloe (0007): no window. An inhibitor on a layer surface ++ * needs no count: wlroots keeps it in the manager's list until ++ * it or its surface goes, and keyboard_shortcuts_inhibited_by_ ++ * layer() looks it up there while the layer has the focus. ++ */ ++ if (root && wlr_layer_surface_v1_try_from_wlr_surface(root)) { ++ wlr_keyboard_shortcuts_inhibitor_v1_activate(inhibitor); ++ } + return; + } + +@@ -87,6 +99,33 @@ handle_manager_destroy(struct wl_listener *listener, void *data) + { + wl_list_remove(&on_new_inhibitor.link); + wl_list_remove(&on_manager_destroy.link); ++ inhibit_manager = NULL; ++} ++ ++/* ++ * thinfloe (0007): true while the seat's keyboard focus is a layer surface ++ * with an inhibitor. A layer surface that takes the keyboard exclusively ++ * and asks for the inhibition (the Deskflow capture strip) gets every key, ++ * so no keybinding runs, allowWhenInhibited ones included: the volume and ++ * brightness keys go to the client that holds the keyboard. ++ */ ++bool ++keyboard_shortcuts_inhibited_by_layer(struct seat *seat) ++{ ++ struct wlr_surface *focused = seat->seat->keyboard_state.focused_surface; ++ if (!inhibit_manager || !focused ++ || !wlr_layer_surface_v1_try_from_wlr_surface(focused)) { ++ return false; ++ } ++ struct wlr_keyboard_shortcuts_inhibitor_v1 *inhibitor; ++ wl_list_for_each(inhibitor, &inhibit_manager->inhibitors, link) { ++ if (inhibitor->seat == seat->seat ++ && wlr_surface_get_root_surface(inhibitor->surface) ++ == focused) { ++ return true; ++ } ++ } ++ return false; + } + + void +@@ -99,6 +138,7 @@ keyboard_shortcuts_inhibit_create(struct server *server) + wlr_log(WLR_ERROR, "cannot create the keyboard shortcuts inhibit manager"); + return; + } ++ inhibit_manager = manager; + on_new_inhibitor.notify = handle_new_inhibitor; + wl_signal_add(&manager->events.new_inhibitor, &on_new_inhibitor); + on_manager_destroy.notify = handle_manager_destroy; diff --git a/docs/notes/deskflow.md b/docs/notes/deskflow.md new file mode 100644 index 0000000..f74bc91 --- /dev/null +++ b/docs/notes/deskflow.md @@ -0,0 +1,85 @@ +# Deskflow server + +ThinFloe is a Deskflow server (protocol 1.6 to 1.8). Computers that run the Deskflow client attach to a side of a ThinFloe monitor; pushing the pointer past that edge moves keyboard and mouse to them. Design: [the spec](../superpowers/specs/2026-11-21-deskflow-server-design.md). + +## Processes + +- The daemon is `thinfloe-menu --deskflow`, a process of its own. The menu starts it when `[deskflow] listen = true`, restarts it after a crash with a back-off (1 s doubling to 60 s), sends SIGHUP after each write of `[deskflow]` and after each saved keyboard choice, SIGTERM when the switch goes off, and SIGTERM before it exits 0, 10 or 11 (waiting up to 1 s). The menu shows "Deskflow stopped: " when the daemon keeps failing. +- The daemon ends by itself when its parent dies or its Wayland connection closes, so no daemon keeps port 24800 after a logout, a restart or a killed menu. Guard: `test/runtime/test-labwc-runtime.sh` (`test-session-lifecycle.sh` runs stub menus without Wayland and only points there). +- A watchdog thread ends the daemon when its event loop stalls for 2 s. All capture state lives in Wayland objects the daemon owns, so a crash returns pointer and keyboard to ThinFloe. +- The daemon reads `~/.config/thinfloe/generated/deskflow` (derived by the menu from `[deskflow]` in `config.toml`, plus `mic_mute_local`, the volume key switch of `[keyboard]`), never `config.toml`. An absent file means the switch is off; a file without `mic_mute_local` reads as false. It writes only its state file and its identity. + +## Contracts + +- State file `$XDG_RUNTIME_DIR/thinfloe-deskflow.state`, written atomically by the daemon. First line `self` or `error`; then one line per (name, fingerprint) pair: `namefingerprintstatesince_epochwidthheightflags`. State is `pending`, `rejected`, `connected`, `active` or `offline`; the size comes from the device's last DINF (0 when unknown); flags is a comma list, so far `fp-changed`. The parser ignores unknown trailing fields. +- Command socket `$XDG_RUNTIME_DIR/thinfloe-deskflow.sock` (datagrams): `reject `, `reload`. +- Identity: `~/.config/thinfloe/deskflow/identity.pem` (mode 600), a self-signed ECDSA P-256 certificate made at the first start, valid 2000-01-01 to 2099-12-31 so that the boot clock does not shape it. A damaged file is reported and never regenerated. A fresh install leaves the directory out (`IDENTITY_EXCLUDES`); it travels with the home like the SSH host keys. + +## Pairing + +- The fingerprint is the SHA-256 of the DER certificate, shown as Deskflow's picture and as colon hex. +- The server always asks for a client certificate and drops a client without one: approving by name alone would let any computer on the LAN take over an attached slot. Trust is the fingerprint; the chain is not checked. +- After Hello and HelloBack, a known (name, fingerprint) pair proceeds. An unknown pair is recorded as `pending` and answered with EUNK. A known name with another fingerprint is refused the same way and marked `fp-changed`; the user must attach it again. A second connection under an attached name gets EBSY. +- A refused connection stays open up to 2 s after EUNK. Without that, the 1.26 client never parses EUNK and treats the close as a network failure. +- Limits: 8 pending devices (the oldest drops), 4 connections in the TLS and Hello phase, 10 s to finish both, messages up to 1 MiB. +- Order on first contact: the client checks ThinFloe's fingerprint during the TLS handshake and drops the connection before HelloBack when it does not trust it. The user trusts ThinFloe on the client first (comparing the picture), and only then does the device show up as pending. + +## Settings → Screen + +- The Deskflow band has the switch "Let other computers use this keyboard and mouse (Deskflow)", ThinFloe's address, port and fingerprint, and the edge resistance select. +- A pending device lists its name and fingerprint with a Position select and Reject. Picking an edge in the Position select attaches the device and saves it at once; there is no confirm button. Cancel ends an attach. "No monitor edge is free in the current arrangement." shows when no edge is free. +- An attached device is drawn in the monitor arrangement beside its monitor, scaled from the size it reports, with a status dot. Selecting it shows Position and Forget. +- A device whose edge another monitor took (or whose monitor is gone) is not drawn in the arrangement. The band lists it with "This edge is not free in the current arrangement.", Position and Forget. +- `[deskflow]` in `config.toml`: `listen`, `port`, `edge_resistance` and one `[[deskflow.device]]` per device (`name`, `fingerprint`, `output`, `side`). The position belongs to the monitor and applies in every profile. + +## Capture and the way back + +- For each attached, connected device the daemon puts a 1 px layer-shell strip on the overlay layer along the attached edge. Only edges that touch no other monitor qualify. +- Edge resistance: the pointer goes to the device only after the user keeps pushing outward. Outward motion from the relative pointer is summed, and the sum resets when the pointer leaves the strip or stops pushing for 300 ms. Thresholds: `off` 0, `low` 15, `medium` 40 (default), `high` 100 logical pixels. +- Only motion outward starts a capture, at every level: with `off` the first outward motion on the strip does. Reaching the strip, and motion inward or along the edge, never do, so the pointer that comes back from a device stays on ThinFloe although it still sits on the strip. +- At the threshold the daemon creates the pointer lock first, then takes exclusive keyboard focus on the strip, puts a keyboard-shortcuts inhibitor on the strip, waits for `locked`, and only then sends CINN. With the inhibitor ThinFloe's labwc runs no keybinding while the strip has the keyboard, the media keys included (patch 0007); `end_capture` destroys it. labwc 0.9.3 activates a new lock only for the active view or on a focus change, so the lock must exist before the focus moves. +- The pointer returns when the tracked position crosses back over the attached edge (no resistance). +- Release always wins and does not wait for the client: Ctrl+Alt+Shift+Escape on the ThinFloe keyboard (seen by the strip's own keyboard focus, not a compositor binding; by key code when the keymap cannot be read), a missed keep-alive (3 s, 3 misses) or a failing socket, the lock cancelled, the strip losing focus or its output going away, and the watchdog. +- Keys held at entry are not sent; keys held at exit get DKUP before COUT. Repeats are generated at the compositor's rate and delay. Ctrl+Alt+Fn falls back to the level-0 keysym, as Deskflow does. + +## Media keys + +- While a device has the keyboard, the strip's inhibitor keeps labwc's media key bindings from running, so the volume, mute and brightness keys go to the device (Deskflow key ids `0xE0AD` to `0xE0B9`) and ThinFloe shows no OSD for them. +- The microphone mute key (`XF86AudioMicMute`) has no Deskflow key id and stays on ThinFloe: its press and release are never sent, and on the release, when `mic_mute_local` is true, the daemon runs `thinfloe-menu --osd-key mic-mute` (`TF_OSD_KEY_CMD` replaces `thinfloe-menu --osd-key`, as for the composer) in a process group of its own without waiting; the loop reaps it. While 4 such commands still run, a further release runs nothing. A release whose press came before the capture does nothing. +- The menu writes `mic_mute_local` with the volume key switch (`Table::Keyboard` renders `generated/deskflow` too) and sends the daemon SIGHUP after a saved keyboard choice. +- Runtime test (`test-labwc-runtime.sh`, Deskflow media keys): with the stock client attached and captured, `XF86AudioRaiseVolume` reaches the client and not the recorder, `XF86AudioMicMute` reaches the recorder as `mic-mute` and not the client, and after the escape chord the volume key runs the binding again. + +## Clipboard + +- Text only. The daemon watches ThinFloe's clipboard through the data-control protocol (ext_data_control_v1, else zwlr_data_control_v1) on a Wayland connection of its own, so a clipboard fault never touches the capture. It reads a selection as UTF-8 text (`text/plain;charset=utf-8`, `UTF8_STRING`, `text/plain`, `STRING`, `TEXT`), and offers a device's text under the same types plus `application/x-thinfloe-deskflow`. A selection carrying that marker is the daemon's own and is not reported back. +- ThinFloe's clipboard changes: the device with the pointer gets the text at once (CCLP, then DCLP); every other device that shares the clipboard only learns of the grab (CCLP). When the pointer enters a device later, the device gets the remembered text, unless it already holds those bytes (it gave them, or was sent them). +- ThinFloe's clipboard becomes something the bridge does not carry (no text type, an empty text, over the cap, or a read that failed or took over 2 s): the daemon forgets the remembered text and every device that shares the clipboard, the one with the pointer too, gets CCLP, so its clipboard empties and no older text reaches it later. A selection that ends because its program exited keeps the remembered text. +- A device whose Clipboard switch changes no longer counts as holding ThinFloe's text: the next entry sends it again. +- A device copies: the Deskflow client sends CCLP at once and its text (DCLP) when the pointer leaves it, or at once when the pointer is not there. The text becomes ThinFloe's selection, and the other devices learn of the grab. +- Cap: 1 MiB of text either way. DSOP tells the client `CLPS 1, CLSZ 1024` (KiB); a larger local selection is not sent and counts as one the bridge does not carry. +- Per device: Settings → Screen, the attached device's "Share the clipboard" switch, saved as `clipboard = true/false` in its `[[deskflow.device]]` (absent means on). Off sends DSOP `CLPS 0`, and the daemon sends that device nothing and takes nothing from it. +- Probe: `thinfloe-menu --deskflow --probe-clip` runs the bridge alone: it prints `changed ` for each selection another client sets, and a `set ` line on its stdin makes that text the selection. +- Runtime test (`test-labwc-runtime.sh`): the stock 1.26 client runs on an Xvfb of its own, because labwc's Xwayland would carry the text between the X and the Wayland clipboard by itself and a test there would pass without Deskflow. The 1.26 X11 client notices a copy on its side only through the SelectionClear it gets when it owned the clipboard before, so the case from the device runs after the device received ThinFloe's text. + +## Clients that send a certificate + +ThinFloe needs a client that presents a TLS client certificate. The first releases that do, from their release notes and source history (only Deskflow 1.26.0 is tested): + +- `Deskflow 1.20.0` (2025-03-03): "Peer Id Checking", deskflow/deskflow#7931, the fix for CVE-2021-42072 and CVE-2021-42073. Deskflow 1.17.0 to 1.19.0 are not checked. +- `Barrier 2.4.0` (2021-11-01): "Implement client identity verification" (debauchee/barrier commit 229abab), the same CVE fix. It is Barrier's last release. +- `Input Leap 3.0.0` (2024-10-04): the first Input Leap release; its history contains the Barrier commit. + +## Verified against Deskflow 1.26.0 + +- The ECDSA P-256 server certificate is accepted, and the client ignores validity dates. +- `deskflow-core client --new-instance -s /Deskflow.conf` takes everything from the INI file; its TLS directory is `/tls` with the client certificate in `deskflow.pem` and trusted servers as `v2:sha256:` lines in `trusted-servers`. The runtime test makes the certificate with openssl. +- After EUNK the client retries after 1 s. + +## Known limits + +- While Deskflow is on, the strip covers the outermost row or column of pixels at each edge where a connected device is attached. A click there reaches the strip and does nothing, and a full-screen ThinLinc or OxuLnk session never sees the pointer in that row: an auto-hide taskbar, a hot corner or a close button in the corner at that edge does not react. Other edges are not affected. The owner decides on hardware whether this stays (Task 14). +- Clipboard, text only: images, files and rich text are not bridged, nor is the primary selection (select and middle-click). Text over 1 MiB is not carried. +- Clipboard, stale text: after a device took the clipboard and before its text arrives (while the pointer is still on it, or for the moment its DCLP is on the way), ThinFloe's clipboard still holds the old text. +- A client that sends no certificate is not supported. +- First contact needs the order above: trust ThinFloe on the client first. +- Layout mismatches between ThinFloe and a client are a Deskflow limit (keys travel by key id). diff --git a/docs/notes/home-persistence.md b/docs/notes/home-persistence.md index d9806ba..5d69c50 100644 --- a/docs/notes/home-persistence.md +++ b/docs/notes/home-persistence.md @@ -101,6 +101,7 @@ cannot parse TOML, read files the menu derives from it into `generated/`. | `sessionrc` | by hand | `thinfloe-session` | commands run at session start | | `menu/*.desktop`, `addons` | by hand, `thinfloe-addon` | the menu, `thinfloe-addon` | user tiles, ticked add-ons | | `password`, `ssh-host-keys/`, `wg0.conf`, `save-home-exclude` | root tools, by hand | the same, the initramfs, `thinfloe-save-home`, `thinfloe-upgrade` | remote-access hash, SSH host keys, WireGuard, save exclude list | +| `deskflow/identity.pem` | the Deskflow daemon | the daemon | private key of the Deskflow server; rides the home archive in the clear like the SSH host keys, and a fresh install leaves `deskflow/` out | | `home-version` | the migration | the initramfs | marks the new layout (`2`) | The menu writes the generated files first and renames `config.toml` last, and diff --git a/docs/superpowers/plans/2026-11-21-deskflow-server-core.md b/docs/superpowers/plans/2026-11-21-deskflow-server-core.md new file mode 100644 index 0000000..1262e6b --- /dev/null +++ b/docs/superpowers/plans/2026-11-21-deskflow-server-core.md @@ -0,0 +1,278 @@ +# Deskflow Server, Step 1 (Server Core) Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** ThinFloe's keyboard and pointer drive paired computers that run the stock Deskflow client, attached to a side of a ThinFloe monitor in Settings → Screen. + +**Architecture:** A new mode `thinfloe-menu --deskflow` (module `src/thinfloe-menu/src/deskflow/`) runs one single-threaded `libc::poll` loop over the Wayland fd, the TCP listener, the TLS connections, a command socket and a signal pipe, plus a watchdog thread. Protocol, pairing, key mapping and edge logic are sans-IO modules with unit tests; the loop only moves bytes and Wayland events. The menu supervises the process, owns all UI and is the only writer of `config.toml`; the daemon reads `generated/deskflow` and writes a state file. + +**Tech Stack:** Rust 1.96 (edition 2024), wayland-client 0.31, wayland-protocols(-wlr) client bindings, rustls (ring provider), rcgen, ring (SHA-256), xkbcommon-dl (already in Cargo.lock), shadcn-egui for the UI; bash runtime tests in headless labwc with `wlrctl`/`wtype` and Ubuntu's `deskflow` 1.26.0 package as the interop client. + +**Spec:** [docs/superpowers/specs/2026-11-21-deskflow-server-design.md](../specs/2026-11-21-deskflow-server-design.md) — read it first. This plan covers its **Build order step 1** only. Clipboard (step 2) and media keys/patch `0007` (step 3) get their own plans; in step 1 media keys keep acting on ThinFloe and no clipboard message is sent or handled (incoming CCLP/DCLP are read and dropped). + +## Global Constraints + +- Builds and tests use at most 4 cores: `CARGO_BUILD_JOBS=4`, `cargo test -j 4 -- --test-threads=4`; any test that feeds network or adversarial input runs under `systemd-run --user --scope -p MemoryMax=2G --` (the Makefile's `$(MEMCAP)`). +- No `wgpu`, `glow`, `eframe` (menu draws on the CPU). New crates: `default-features = false`, only the features named in Task 4. +- `config.toml` is written only by the menu through `store.rs`; the daemon never opens it. +- UI colours from the theme, text sizes from `brand.rs` constants (`ui_code_has_no_style_literals` must stay green); shadcn-egui `lyra`, nothing rounded. +- No new labwc keybinding and no labwc patch in step 1. +- English for code, comments, keys; UI text in Simplified Technical English. +- Defaults pinned by the spec: listen `false`, port `24800`, edge_resistance `medium` (off 0 / low 15 / medium 40 / high 100 logical px), resistance reset after 300 ms without outward push, keep-alive 3 s with 3 misses, watchdog stall 2 s, TLS+Hello deadline 10 s, ≤ 4 simultaneous handshakes, ≤ 8 pending devices, message cap 1 MiB, client name cap 64 bytes, protocol minor 6–8 (send 8, Hello name `Barrier`), escape `Ctrl+Alt+Shift+Escape`, restart back-off 1, 2, 4 … 60 s. +- Identity: ECDSA P-256 self-signed, CN `ThinFloe `, valid 2000-01-01 to 2099-12-31, `~/.config/thinfloe/deskflow/identity.pem` mode 0600; fingerprint `v2:sha256:` over the DER certificate. +- Every behaviour change gets a `CHANGES.md` line under `## [Unreleased]` (Task 13); no release headers. +- Commit after each task with a Conventional-Commit subject and the `Co-Authored-By` trailer. + +## Review Focus + +1. **The monitor the device is attached to is unplugged or powered off while captured** → capture ends at once, keys and pointer are back on ThinFloe (Task 10 test `output_gone_releases`). +2. **A scaled (1.5) or rotated monitor** → the strip covers exactly the logical edge and the entry point maps proportionally (Task 9 test `strip_on_scaled_and_rotated_output`). +3. **Keys held when capture ends** (including the escape chord itself) → every key sent down to the device is sent up before COUT; nothing stays pressed on the device (Task 10 test `release_sends_up_for_held_keys`). +4. **A hostile or broken client name** (control characters, 10 kB, invalid UTF-8, a TAB or newline) → stored capped and escaped; the state file stays one line per device (Task 6 test `state_line_escapes_hostile_names`, Task 5 test `hello_back_name_capped`). +5. **The daemon gets SIGTERM while captured** (switch off, menu exit) → pointer and keyboard return to ThinFloe before exit, the device gets CBYE (Task 10 runtime case `sigterm_while_captured`). + +--- + +## File Structure + +New, under `src/thinfloe-menu/src/deskflow/`: + +| File | Responsibility | +|---|---| +| `mod.rs` | `DESKFLOW_ARG`, `deskflow_main`, paths from env | +| `proto.rs` | messages, encode/decode, 4-byte framing (pure) | +| `ident.rs` | identity load/create, fingerprint, random art (pure except file I/O) | +| `tls.rs` | rustls server config, accept-any client cert verifier | +| `pair.rs` | trust decision, pending list and its limits (pure) | +| `session.rs` | one connection's protocol state machine (sans-IO) | +| `statefile.rs` | state file write/parse (shared with the menu) | +| `cmd.rs` | command datagram encode/decode, socket bind/send | +| `keymap.rs` | keysym → KeyID, XKB mods → KeyModifierMask (pure) | +| `edge.rs` | strip geometry, entry mapping, tracked position, resistance (pure) | +| `capture.rs` | Wayland: outputs, strips, pointer lock, keyboard, relative motion | +| `run.rs` | poll loop, listener, connections, watchdog, signals | + +Menu side: `deskflowcfg.rs` (schema conversions + generated file), `deskflowtab.rs` (tab state and actions), `deskflow_ui.rs` (band), `deskflow_sup.rs` (supervisor). Modified: `config.rs`, `generated.rs`, `store.rs`, `lib.rs`, `main.rs`, `app.rs`, `menu.rs`, `monitors_ui.rs`, `Cargo.toml`, `overlay/usr/bin/thinfloe-upgrade`, `test/unit/test_upgrade_image.py`, `test/runtime/Dockerfile`, `test/runtime/test-labwc-runtime.sh`, docs. + +The `Makefile` needs no change: `MENU_FILES`/`MENU_DIRS` are a `find` over the crate. + +--- + +### Task 1: Capture spike — strip, lock and keyboard over a full-screen grab (gate) + +This is the spec's Risk 1. It builds the real Wayland part of `capture.rs`, not a throwaway. + +**Files:** +- Create: `src/thinfloe-menu/src/deskflow/mod.rs`, `deskflow/capture.rs`, `deskflow/edge.rs` (only `pub struct Rect { pub x: i32, pub y: i32, pub w: i32, pub h: i32 }` here; Task 9 adds the rest) +- Modify: `src/thinfloe-menu/src/lib.rs` (`pub mod deskflow;`), `src/thinfloe-menu/src/main.rs` (dispatch next to `osd::OSD_ARG`), `Cargo.toml` (`wayland-protocols = { version = "0.32", default-features = false, features = ["client", "unstable", "staging"] }` — use the version that matches `wayland-client 0.31`), `test/runtime/test-labwc-runtime.sh` + +**Interfaces:** +- Produces: `pub const DESKFLOW_ARG: &str = "--deskflow"`; `pub fn deskflow_main(args: &[OsString]) -> ExitCode`; `--deskflow --probe-capture ` test hook. +- Produces in `capture.rs`: + - `pub struct Capture` with `connect() -> Result`, `fd()`, `dispatch() -> Result, String>`, `flush()` + - `pub fn outputs(&self) -> Vec` (name, logical x, y, w, h from `zxdg_output_v1`) + - `pub fn set_strips(&mut self, strips: &[StripSpec])` (`StripSpec { id: u32, output: String, rect: Rect }`) + - `pub fn begin_capture(&mut self, strip: u32)`, `pub fn end_capture(&mut self)` + - `pub enum CapEvent { Enter{strip:u32, x:f64, y:f64}, Leave{strip:u32}, Relative{dx:f64, dy:f64}, Locked, Unlocked, Key{code:u32, pressed:bool}, Modifiers{depressed:u32, latched:u32, locked:u32, group:u32}, Keymap{fd:OwnedFd, size:u32}, RepeatInfo{rate:i32, delay:i32}, Button{button:u32, pressed:bool}, Axis{v120_x:i32, v120_y:i32}, KeyboardLeft, OutputsChanged }` + +- [ ] **Step 1: Write the runtime case** `run_capture_probe_case` in `test-labwc-runtime.sh`: start an X11 full-screen window with `XGrabKeyboard` (reuse `x11-probe.py`'s grab window), start `thinfloe-menu --deskflow --probe-capture HEADLESS-1 right-of` (prints one line per `CapEvent` on stdout; on `Enter` it calls `begin_capture` at once, on Escape key `end_capture`), `wlrctl pointer move` to the right edge of HEADLESS-1, `wtype x`, `wtype -k Escape`, `wtype y`. Assert: probe printed `enter`, `locked`, `key 45 down` (x) in that order; the X window got no `x`; after Escape the probe printed `unlocked` and the X window got `y` and is `state:active` again (`wlrctl toplevel find`). +- [ ] **Step 2: Run** `make test-runtime`. Expected: FAIL (no `--deskflow` mode). +- [ ] **Step 3: Implement `capture.rs` and the probe.** Strip = `zwlr_layer_surface_v1` on layer Overlay, anchored to the edge, 1 px deep, exclusive zone 0, interactivity None, a a transparent ARGB `wl_shm` buffer of the strip's size, input region = whole strip. `begin_capture` order (spec, pushback finding 1): (1) `zwp_pointer_constraints_v1.lock_pointer(strip, pointer, None, Oneshot)` and `zwp_relative_pointer_manager_v1.get_relative_pointer`, (2) `set_keyboard_interactivity(Exclusive)` + commit, (3) emit nothing until `locked` arrives. `end_capture`: destroy lock, interactivity None, commit. Relative motion uses `dx_unaccel`/`dy_unaccel`. +- [ ] **Step 4: Run** `make test-runtime`. Expected: the new case PASSes. +- [ ] **Step 5: Gate.** If `locked` never arrives or the key goes to the X window: **stop the plan** and report to the owner with the probe output (the spec's labwc-patch fall-back is a decision for them). Otherwise commit: `feat(deskflow): edge strip with pointer lock and keyboard capture`. + +### Task 2: Protocol codec + +**Files:** Create `deskflow/proto.rs` (tests inline, as the crate does). + +**Interfaces:** +- Produces: `pub enum Msg` with variants for every message the spec's *Protocol subset* lists for step 1: `Hello{major:u16,minor:u16}`, `HelloBack{major,minor,name:Vec}`, `Qinf`, `Ciak`, `Calv`, `Cnop`, `Crop`, `Dsop(Vec)`, `Csec(u8)`, `Cinn{x:i16,y:i16,seq:u32,mods:u16}`, `Cout`, `Cbye`, `Dinf{x,y,w,h,warp,mx,my: i16}`, `KeyDown{id:u16,mods:u16,button:u16}`, `KeyRepeat{id,mods,count,button: u16}`, `KeyUp{id,mods,button: u16}`, `MouseDown(i8)`, `MouseUp(i8)`, `MouseMove{x:i16,y:i16}`, `Wheel{dx:i16,dy:i16}`, `Cclp{id:u8,seq:u32}`, `Dclp{id:u8,seq:u32,mark:u8,data:Vec}`, `Eicv{major,minor}`, `Ebsy`, `Eunk`, `Ebad`, `Unknown([u8;4])` +- `pub fn encode(m: &Msg, minor: u16) -> Vec` (payload only; KeyDown → `DKDL…%s` with empty lang at minor 8, `DKDN` at 6–7; KeyRepeat → 5-field with empty lang at 8, 4-field below) +- `pub fn decode(payload: &[u8]) -> Result`; `pub fn decode_hello_back(payload:&[u8]) -> Result` (Hello has no 4-letter code) +- `pub struct Framer` with `push(&mut self, bytes: &[u8])`, `next(&mut self) -> Result>, ProtoError>`; `pub fn frame(payload: &[u8]) -> Vec`; `pub const MAX_MSG: usize = 1 << 20`. + +- [ ] **Step 1: Write failing tests:** `hello_bytes` (`encode(Hello{1,8})` == `b"Barrier\x00\x01\x00\x08"`); `hello_back_parses_name` (`b"Barrier\0\x01\0\x08\0\0\0\x06laptop"` → name `laptop`); `frame_is_be_length` (`frame(b"CALV")` == `[0,0,0,4,b'C',b'A',b'L',b'V']`); `framer_splits_and_joins` (two frames pushed one byte at a time); `framer_refuses_oversize` (length `MAX_MSG+1` → Err); `key_down_v18_has_lang` (ends with `[0,0,0,0]` and code `DKDL`); `key_down_v16_is_dkdn`; `key_repeat_v18_five_fields` (payload len 4+8+4); `dinf_roundtrip` (1920×1080 → bytes `\x07\x80`); `cinn_layout`; `truncated_payload_is_error` for every fixed-size message; `unknown_code_kept`. +- [ ] **Step 2: Run** `cargo test -j 4 deskflow::proto -- --test-threads=4` in `src/thinfloe-menu`. Expected: FAIL (module missing). +- [ ] **Step 3: Implement** big-endian, strings as `u32` length + bytes capped by the frame. +- [ ] **Step 4: Run** the same command. Expected: PASS. +- [ ] **Step 5: Commit** `feat(deskflow): protocol messages and framing`. + +### Task 3: Config schema and `generated/deskflow` + +**Files:** Modify `config.rs` (`DeskflowCfg`, `DeviceCfg`, field `deskflow` in `ThinfloeConfig`), `generated.rs` (`Table::Deskflow` → `&["deskflow"]`, render arm), `store.rs` (rebuild-from-generated reads it back); create `deskflowcfg.rs`. + +**Interfaces:** +- `pub struct DeskflowCfg { pub listen: bool, pub port: u16, pub edge_resistance: Resistance, pub devices: Vec }` (TOML: `[deskflow]`, `[[deskflow.device]]` exactly as the spec's *Configuration* block; `device` is the TOML key of `devices`) +- `pub struct DeviceCfg { pub name: String, pub fingerprint: String, pub output: String, pub side: Side, pub clipboard: bool }` (`side` as `kanshi::Side` words; `clipboard` default true, unused in step 1) +- `pub enum Resistance { Off, Low, Medium, High }` with `pub fn px(self) -> f64` (0, 15, 40, 100) +- `deskflowcfg::render(&DeskflowCfg) -> String` (body of `generated/deskflow`: the same TOML table, after `generated::HEADER`) and `deskflowcfg::parse(text:&str) -> Result`; `deskflowcfg::validate(&DeskflowCfg) -> Result<(),String>` (fingerprint matches `^v2:sha256:[0-9a-f]{64}$`, name 1–64 bytes, unique names, at most one device per (output, side), port ≠ 0). +- The generated file is mode 0600 (`generated::mode_of`). + +- [ ] **Step 1: Failing tests:** `default_is_off` (listen false, port 24800, Medium); `toml_roundtrip_matches_spec_block`; `render_parse_roundtrip`; `validate_refuses_bad_fingerprint`, `…_duplicate_edge`, `…_duplicate_name`; `generated_mode_0600`; in `store.rs` tests `broken_config_keeps_deskflow_devices` (break `config.toml`, reopen, devices back from `generated/deskflow`). +- [ ] **Step 2: Run** `cargo test -j 4 -- --test-threads=4 deskflow store`. Expected: FAIL. +- [ ] **Step 3: Implement.** +- [ ] **Step 4: Run** full `cargo test -j 4 -- --test-threads=4` (existing config/migrate tests must stay green). Expected: PASS. +- [ ] **Step 5: Commit** `feat(config): [deskflow] table and generated/deskflow`. + +### Task 4: Identity, fingerprint, random art; TLS config + +**Files:** Create `deskflow/ident.rs`, `deskflow/tls.rs`; `Cargo.toml`: `rustls` (features `ring`, `std`, `tls12`, `logging` off), `rcgen` (features `ring`, `pem`), `ring` (default off), `rustls-pki-types`. Add each with `cargo add --no-default-features` at its current stable version; `--locked` builds need the updated `Cargo.lock` committed. + +**Interfaces:** +- `pub struct Identity { pub cert_der: Vec, pub key_der: Vec }`; `pub fn load_or_create(path:&Path, hostname:&str) -> Result` (creates dir 0700, file 0600, atomically via `crate::atomic`) +- `pub fn fingerprint(der:&[u8]) -> String` → `v2:sha256:`; `pub fn colon_hex(fp:&str) -> String` (uppercase, colons); `pub fn random_art(fp:&str) -> Vec` (Deskflow's `generateFingerprintArt` in `src/lib/net/SecureUtils.cpp` — port the algorithm, cite the Deskflow commit in a comment; 17 columns) +- `tls::server_config(id:&Identity) -> Arc`: TLS 1.2+1.3, client certificate **required**, a `ClientCertVerifier` that accepts any certificate (signature checks of the handshake still on) — trust is decided later by fingerprint; `tls::peer_fingerprint(conn:&rustls::ServerConnection) -> Option`. + +- [ ] **Step 1: Failing tests:** `create_then_load_same_fingerprint`, `identity_file_mode_0600`, `fingerprint_format` (regex), `fingerprint_known_vector` (SHA-256 of a fixed DER byte string), `colon_hex_shape` (95 chars, uppercase), `random_art_shape` (box 19 wide incl. borders, 9+2 lines, stable for a fixed fp), `tls_handshake_needs_client_cert` (in-memory rustls client without cert → server errors; with any self-signed cert → `peer_fingerprint` equals that cert's fingerprint). +- [ ] **Step 2: Run** `cargo test -j 4 deskflow::ident deskflow::tls -- --test-threads=4`. Expected: FAIL. +- [ ] **Step 3: Implement.** +- [ ] **Step 4: Run.** Expected: PASS. Also `cargo clippy -j 4` clean. +- [ ] **Step 5: Commit** `feat(deskflow): TLS identity and fingerprints`. + +### Task 5: Pairing and the session state machine + +**Files:** Create `deskflow/pair.rs`, `deskflow/session.rs`. + +**Interfaces:** +- `pair.rs`: `pub enum Verdict { Trusted(usize /* device index */), Pending, FingerprintChanged }`; `pub fn judge(devices:&[DeviceCfg], name:&str, fp:&str) -> Verdict`; `pub struct Pending` with `note(&mut self, name, fp, flags, now_epoch)` (keeps at most 8, drops the oldest), `reject(name, fp)`, `is_rejected(name, fp) -> bool`, `entries() -> &[PendingEntry]`, `forget_trusted(devices)`. +- `session.rs`: `pub struct Session`; `Session::new(now: Instant) -> (Session, Vec)` (sends Hello 1.8); `on_payload(&mut self, p:&[u8], now) -> Vec`; `tick(&mut self, now) -> Vec`; `set_verdict(&mut self, v: Verdict) -> Vec`; `enter(&mut self, x:i16, y:i16, mods:u16) -> Vec`, `leave(&mut self) -> Vec`, `send(&mut self, m: Msg) -> Vec`; `pub enum Out { Send(Vec /* framed */), Named{name:String}, Screen{w:i16,h:i16}, Close(&'static str) }`; `pub fn minor(&self) -> u16`. +- Rules: HelloBack major ≠ 1 or minor ∉ 6..=8 → EICV + Close; name capped to 64 bytes, bytes kept raw (escaped only for display); after `Trusted` → QINF, then on the first DINF → CIAK, CROP, DSOP(empty) + `Screen`, on later DINFs CIAK + `Screen`; `Pending`/`FingerprintChanged` → EUNK + Close; no HelloBack within 10 s of `new` → Close; CALV sent every 3 s, Close after 9 s without any message from the client; CALV from client is answered. + +- [ ] **Step 1: Failing tests:** `judge_known_pending_changed`; `pending_keeps_eight_newest`; `rejected_not_noted_again`; `hello_first`; `old_minor_gets_eicv` (minor 5); `hello_back_name_capped` (10 kB name → 64 bytes); `trusted_gets_qinf_then_ciak_after_dinf`; `pending_gets_eunk_and_close`; `hello_deadline_10s`; `keepalive_every_3s_dead_after_9s`; `calv_is_answered`; `key_form_follows_minor` (minor 7 session encodes DKDN). +- [ ] **Step 2–4:** run `cargo test -j 4 deskflow:: -- --test-threads=4` red, implement, green. +- [ ] **Step 5: Commit** `feat(deskflow): pairing rules and protocol session`. + +### Task 6: State file and command socket + +**Files:** Create `deskflow/statefile.rs`, `deskflow/cmd.rs`. + +**Interfaces:** +- `pub enum DevState { Pending, Rejected, Connected, Active, Offline }`; `pub struct DevLine { name: String, fingerprint: String, state: DevState, since: i64, width: u32, height: u32, flags: Vec }`; `pub enum Head { SelfInfo{fingerprint:String, listen:String}, Error(String) }`; `pub struct StateFile { head: Head, devices: Vec }` +- `pub fn render(s:&StateFile) -> String`; `pub fn parse(text:&str) -> StateFile` (ignores unknown trailing fields and bad lines); `pub fn write(path:&Path, s:&StateFile) -> io::Result<()>` (atomic, 0600); line format exactly as the spec's *Processes* section; names escaped with `\t`, `\n`, `\\`, `\xNN` for other control bytes and invalid UTF-8. +- Path: `$TF_DESKFLOW_STATE`, else `$XDG_RUNTIME_DIR/thinfloe-deskflow.state`; socket `$TF_DESKFLOW_SOCKET`, else `$XDG_RUNTIME_DIR/thinfloe-deskflow.sock`. +- `pub enum Cmd { Reject{name:String, fingerprint:String}, Reload }`; `encode`/`decode` as one datagram `reject\t\t\n` / `reload\n`; `bind`/`send` follow `osd/socket.rs` (remove stale file, 0600, non-blocking). + +- [ ] **Step 1: Failing tests:** `render_parse_roundtrip`, `state_line_escapes_hostile_names` (name with TAB, newline, `\x01`, invalid UTF-8 → one line, roundtrips), `parse_ignores_extra_fields`, `same_name_two_lines`, `error_head`, `cmd_roundtrip`, `cmd_garbage_is_none`. +- [ ] **Step 2–4:** red, implement, green. +- [ ] **Step 5: Commit** `feat(deskflow): state file and command socket`. + +### Task 7: Daemon loop and the interop harness + +**Files:** Create `deskflow/run.rs`; modify `deskflow/mod.rs`, `test/runtime/Dockerfile` (add `deskflow`; it is in Ubuntu 26.04 universe, 1.26.0), `test/runtime/test-labwc-runtime.sh`. + +**Interfaces:** +- `pub fn run(env: RunEnv) -> Result<(), String>` with `RunEnv { generated: PathBuf /* generated/deskflow */, identity: PathBuf, state: PathBuf, socket: PathBuf, hostname: String }`. +- Loop: `libc::poll` with timeout ≤ 250 ms over capture fd, listener, each connection, command socket, signal self-pipe (SIGTERM, SIGHUP via `signal-hook`-free `libc::sigaction` writing to a pipe). Connections: non-blocking `TcpStream` + `rustls::ServerConnection` (`read_tls`/`process_new_packets`/`write_tls`), ≤ 4 in handshake (extra accepts are closed at once), handshake + HelloBack ≤ 10 s. After TLS, `pair::judge` with the peer fingerprint feeds `Session::set_verdict`. Two connections with the same trusted name: the newer gets EBSY. +- Reload (SIGHUP or `Cmd::Reload`): re-read `generated/deskflow`; close connections whose device is gone; if `listen` is false, exit 0; if the port changed, re-bind. +- Watchdog: a thread checks an `AtomicU64` heartbeat (ms since start) the loop stores each turn; stale > 2 s → `libc::_exit(70)`. +- Exit 0 when the Wayland connection fails (`Capture::dispatch` returns Err): labwc is gone, so is the session. +- State file rewritten on every change of any device line; first line `self` with the identity fingerprint and `0.0.0.0:`; `Head::Error` when bind fails (e.g. `port 24800 in use`), then exit 1. + +- [ ] **Step 1: Discover the client CLI** in the runtime image: `podman run --rm deskflow-core --help` (or `deskflow-client`); write down the exact flags for name, server address, TLS on, log level DEBUG2, config dir, in a comment at the top of the new runtime case. Find the client's `trusted-servers` path from `Settings::tlsTrustedServersDb()` for that config dir. +- [ ] **Step 2: Write the runtime case** `run_deskflow_pairing_case`: start the daemon with a `TF_CONFIG_DIR` whose `generated/deskflow` has `listen = true`, port 24800, no devices; read our fingerprint from the state file's first line; pre-fill the client's `trusted-servers` with it; start the client (name `laptop`, server `127.0.0.1`, under Xwayland of the same labwc). Assert, each within 15 s: state file has `laptop … pending`; append the device (fingerprint from that line, `output = "HEADLESS-1"`, `side = "right-of"`) to `generated/deskflow` and send `reload` over the socket; state becomes `connected` with width/height of the client's screen; the client log shows it connected. Then a second client with name `laptop` and a fresh config dir (other certificate) → line `laptop … pending … fp-changed` and the first stays `connected`. Then `listen = false` + reload → daemon exits 0, nothing listens on 24800 (`ss -ltn`). Wrap the client in `timeout`. +- [ ] **Step 3: Run** `make test-runtime`. Expected: FAIL. +- [ ] **Step 4: Implement** `run.rs`; `deskflow_main` builds `RunEnv` from `ConfigDir::from_env()`, `/etc/hostname` and the env paths of Task 6, and sets `PR_SET_PDEATHSIG` SIGTERM. If ECDSA is refused by the client (TLS alert in its log), switch `ident::load_or_create` to RSA-2048 (rcgen + ring cannot make RSA keys: use `rcgen` with the `aws_lc_rs` feature for that case only) and note it in the commit. +- [ ] **Step 5: Run** `make test-runtime`. Expected: PASS. Write in the commit body the facts the spec marked "verify": ECDSA accepted (yes/no), client retried after EUNK, Hello framed. +- [ ] **Step 6: Commit** `feat(deskflow): listening daemon with pairing`. + +### Task 8: Key mapping + +**Files:** Create `deskflow/keymap.rs`. + +**Interfaces:** +- `pub fn key_id(keysym: u32, utf32: u32) -> Option`: Unicode (BMP) when the keysym yields a printable character; else the Deskflow `kKey…` value for function, navigation, editing, keypad and modifier keysyms, taken as numeric constants from Deskflow's `src/lib/deskflow/KeyTypes.h` (cite the commit hash in the table's comment); media keysyms map too (`kKeyAudioMute` 0xE0AD, `kKeyBrightnessDown` 0xE0B8, `kKeyBrightnessUp` 0xE0B9, the volume keys) for step 3, though labwc keeps them in step 1; `XF86AudioMicMute` → None. +- `pub fn mod_mask(shift:bool, ctrl:bool, alt:bool, logo:bool, altgr:bool, caps:bool, num:bool, scroll:bool) -> u16` with the `KeyModifierMask` bits from `KeyTypes.h`. +- `pub fn button(evdev: u32) -> u16` = evdev + 8. +- `pub struct Xkb` (via `xkbcommon-dl`; add it to `Cargo.toml` at the version already in `Cargo.lock`): `from_keymap_fd(fd, size) -> Result`, `update_mask(d,l,lk,g)`, `keysym(evdev) -> u32`, `utf32(evdev) -> u32`, `mods() -> Mods`. + +- [ ] **Step 1: Failing tests:** `latin_letters_are_unicode` (keysym `a` → 0x61, `A` → 0x41), `umlaut` (`adiaeresis` → 0xE4), `return_escape_f1_match_keytypes` (values from `KeyTypes.h`), `mic_mute_is_none`, `mod_mask_bits`, `button_is_x11_keycode` (evdev 30 → 38), `xkb_de_layout_y_is_z` (build a keymap for `de` from names; evdev `KEY_Y` (21) → keysym `z`). +- [ ] **Step 2–4:** red, implement, green. +- [ ] **Step 5: Commit** `feat(deskflow): key ids and modifier mask`. + +### Task 9: Edge geometry and edge resistance + +**Files:** Create `deskflow/edge.rs`. + +**Interfaces:** +- `Rect` from Task 1 (logical px) +- `pub fn strip_rect(out: Rect, side: Side) -> Rect` (1 px deep along that edge) +- `pub fn edge_free(out: Rect, side: Side, others: &[Rect]) -> bool` (false when any other output shares that edge segment) +- `pub fn entry_point(out: Rect, side: Side, at: (f64,f64), dev: (i16,i16)) -> (i16,i16)` (proportional along the edge, on the device's opposite edge: right-of → x = 0) +- `pub struct Tracker` with `new(side, start:(i16,i16), dev:(i16,i16))`, `motion(&mut self, dx:f64, dy:f64) -> Track`; `pub enum Track { Move(i16,i16), Back{along: f64 /* 0..1 */} }` (clamped inside the device; `Back` when the position crosses the attached edge back towards ThinFloe). +- `pub struct Resistance` with `new(threshold_px: f64)`, `push(&mut self, side, dx, dy, now: Instant) -> bool` (true when the outward sum reaches the threshold; threshold 0 → true on the first event, also with zero motion), `reset()`; resets itself when `now` is ≥ 300 ms after the last outward push; inward motion does not subtract. + +- [ ] **Step 1: Failing tests:** `strip_rects_each_side`; `strip_on_scaled_and_rotated_output` (logical 1707×960 at x=1920 and a 1080×1920 portrait output: strip lengths equal the logical edge); `edge_between_two_monitors_not_free`; `entry_maps_proportionally` (y 360 of 720 → 540 of 1080); `tracker_clamps_and_comes_back`; `resistance_levels` (15/40/100 reached after exactly that outward sum); `resistance_ignores_inward_and_sideways`; `resistance_resets_after_300ms`; `resistance_off_fires_at_once`. +- [ ] **Step 2–4:** red, implement, green. +- [ ] **Step 5: Commit** `feat(deskflow): edge geometry and edge resistance`. + +### Task 10: Forwarding and the way back + +**Files:** Modify `deskflow/run.rs`, `deskflow/capture.rs`; `test-labwc-runtime.sh`. + +**Interfaces:** Consumes Tasks 1, 5, 8, 9. Produces the captured state in `run.rs`: `struct Active { device: usize, tracker: Tracker, held: Vec<(u16 /*id*/, u16 /*button*/)> }`. + +Behaviour: +- Strips: one per connected device whose output exists and whose edge is `edge_free`; recomputed on `OutputsChanged`, connect, disconnect, reload. A device without a strip shows `flags` `edge-busy` or state `offline` in the state file. +- `Enter` + `Relative` events feed `Resistance`; when it fires → `begin_capture`; on `Locked` → CINN at `entry_point`, state `active`. +- Captured: Relative → `Tracker::motion` → DMMV, or on `Back` → release; Button → DMDN/DMUP with Deskflow's button ids from `src/lib/deskflow/MouseTypes.h` (the protocol header's comment and the code disagree on which of 2 and 3 is right; the header file wins, and the interop case clicks both); Axis → DMWM with v120 values (positive up/right as Deskflow); Key → DKDN/DKRP/DKUP via `keymap`, with client-side repeat generated from `RepeatInfo`; keys already down at capture start are not sent. +- Release (one function `release(reason: &str)`): DKUP for every `held` key, DMUP for held buttons, COUT, `end_capture`, log `thinfloe-deskflow: released ()` to stderr. Triggers: `Back`; Escape pressed while Ctrl, Alt, Shift are down (not forwarded); session Close or socket error; `Unlocked`; `KeyboardLeft`; the strip's output gone; SIGTERM (then CBYE to all, exit 0). + +- [ ] **Step 1: Write runtime cases** on top of Task 7's pairing setup (`edge_resistance = "low"`): `pointer_reaches_client` (`wlrctl pointer move` to the right edge, then several `wlrctl pointer move 10 0`; client DEBUG log shows "entering screen" and mouse moves; `wtype x` shows a key event in the client log and not in a local foot window); `touch_without_push_stays` (one move to the edge only: no enter in the client log); `escape_chord_releases`; `client_killed_releases` (kill the client while captured → `wtype y` reaches the local window within 1 s); `output_gone_releases` (`wlr-randr --output HEADLESS-1 --off` while captured); `sigterm_while_captured` (SIGTERM → local keys work, client log shows a clean disconnect). +- [ ] **Step 2: Unit test** `release_sends_up_for_held_keys` in `run.rs` (factor the captured-state logic into a pure `fn on_cap_event(&mut Active, &CapEvent, …) -> Vec` so it is testable without Wayland): press a, Ctrl, Alt, Shift, Escape → the output has DKDN a, DKDN Ctrl/Alt/Shift, then DKUP for all four, then COUT, and no Escape. +- [ ] **Step 3: Run** `make test-runtime` and `cargo test -j 4 -- --test-threads=4`. Expected: FAIL. +- [ ] **Step 4: Implement.** +- [ ] **Step 5: Run both.** Expected: PASS. +- [ ] **Step 6: Commit** `feat(deskflow): forward keyboard and pointer, release on every way back`. + +### Task 11: Menu supervisor and lifecycle + +**Files:** Create `deskflow_sup.rs`; modify `app.rs` (start/stop with the config, SIGTERM before exit 0/10/11), `test-labwc-runtime.sh`. + +**Interfaces:** +- `pub struct Supervisor`: `new(program: PathBuf) -> Supervisor`; `want(&mut self, listen: bool, now: Instant)`; `tick(&mut self, now: Instant) -> Option`; `reload(&self)` (SIGHUP); `stop(&mut self, wait: Duration)` (SIGTERM to the process group, wait ≤ 1 s, then SIGKILL); `pub fn last_failure(&self) -> Option`. +- Spawn: `process_group(0)`, stdout/stderr to the session log the menu's other children use, `--deskflow`. Exit status ≠ 0 → restart after 1, 2, 4 … 60 s; a run longer than 60 s resets the back-off. Exit 0 with listen still wanted is also restarted. +- The menu calls `reload()` after each successful `store.update(Table::Deskflow, …)`. + +- [ ] **Step 1: Failing unit tests** (with `/bin/sh -c` stand-ins as `program`): `backoff_doubles_to_60`, `long_run_resets_backoff`, `listen_off_stops`, `stop_kills_group`. +- [ ] **Step 2: Runtime case** `deskflow_lifecycle`: menu with `listen = true` → a `--deskflow` process and a listener on 24800; menu exits 0 → both gone within 2 s; start again, `kill -9` the menu → daemon gone within 2 s (PDEATHSIG); start again, `kill -9` the daemon → a new one within 2 s. +- [ ] **Step 3–4:** red, implement, green (`cargo test` and `make test-runtime`). +- [ ] **Step 5: Commit** `feat(menu): run and supervise the Deskflow daemon`. + +### Task 12: Screen band, pairing UI and devices in the arrangement + +**Files:** Create `deskflowtab.rs`, `deskflow_ui.rs`; modify `menu.rs` (state + events), `monitors_ui.rs` (draw devices), the Screen tab's drawing code (the place that draws `SettingsTab::Screen` today), `brand.rs` if a new text size is needed. + +**Interfaces:** +- `pub struct DeskflowTab { pub cfg: DeskflowCfg, pub state: StateFile, pub attaching: Option<(String /*name*/, String /*fp*/)>, pub error: Option }` +- `pub enum DeskflowEvent { Listen(bool), Resistance(Resistance), Attach{name,fp}, Place{name, output:String, side:Side}, Reject{name,fp}, Forget{name}, CancelAttach }`; `pub fn apply(tab:&mut DeskflowTab, ev: DeskflowEvent) -> Option`; `pub enum DeskflowRequest { Save(DeskflowCfg), Send(Cmd) }` (the menu turns `Save` into `store.update(Table::Deskflow, …)` + `Supervisor::reload`, `Send` into `cmd::send`). +- `pub fn free_edges(profile:&Profile, heads) -> Vec<(String /*criteria*/, Side)>` minus edges taken by other devices — what the Position control offers. +- `deskflow_ui::band(ui:&mut Ui, t:&Theme, tab:&DeskflowTab) -> Option`. +- The menu re-reads the state file when its mtime changes, at the cadence it reads the battery file. + +UI copy (exact): +- switch: "Let other computers use this keyboard and mouse (Deskflow)" +- line: "This computer: :" and its fingerprint (random art + colon hex), with the note "Check this fingerprint on the other computer before you trust it there." +- select: "Edge resistance" with "Off", "Low", "Medium", "High" +- pending row: " wants to attach" + art + hex; buttons "Attach…", "Reject"; with `fp-changed`: " has a new fingerprint. Attach it again only if you expect this." +- attached device: rectangle beside its monitor in the arrangement, scaled from width/height (a default 16:9 box when 0), status dot in theme colours (connected, active, offline); selected: "Position", "Forget"; inactive: "This edge is not free in the current arrangement." +- daemon failure: "Deskflow stopped: " + +- [ ] **Step 1: Failing tests** in `deskflowtab.rs`: `attach_then_place_saves_device` (fingerprint from the pending line, output/side from Place), `reject_sends_cmd`, `forget_removes`, `free_edges_excludes_shared_and_taken`, `listen_toggle_saves`; `ui_code_has_no_style_literals` covers the new UI files (check the test's file list includes them). +- [ ] **Step 2–4:** red, implement, green; then `make test-runtime` (menu still maps and runs). +- [ ] **Step 5: Owner look:** a screenshot of Settings → Screen with one pending and one attached device (headless run, `grim`), attached to the task's report. +- [ ] **Step 6: Commit** `feat(menu): Deskflow band and devices in the monitor arrangement`. + +### Task 13: Identity exclusion, notes, changelog + +**Files:** Modify `overlay/usr/bin/thinfloe-upgrade` (`IDENTITY_EXCLUDES` += `"./.config/thinfloe/deskflow"`), `test/unit/test_upgrade_image.py`, `CLAUDE.md` (fresh-install rule; *Where code lives*; a *Menu* rule for the state file contract; the notes list), create `docs/notes/deskflow.md`, modify `docs/notes/home-persistence.md`, `CHANGES.md`. + +- [ ] **Step 1: Failing test** `test_fresh_install_skips_deskflow_identity` in `test_upgrade_image.py` (next to the ssh-host-keys case: `--exclude=./.config/thinfloe/deskflow` in argv, and the file absent from the copied home). +- [ ] **Step 2: Run** `python3 -m unittest test.unit.test_upgrade_image -v`. Expected: FAIL. Implement. Expected: PASS. +- [ ] **Step 3: Write** `docs/notes/deskflow.md` (how pairing, capture, resistance and the way back work; the state file and socket contract; the facts Task 7 verified; known limits: no clipboard yet, media keys on ThinFloe until step 3, clients without a certificate, the first-contact order) and the CLAUDE.md lines. +- [ ] **Step 4: CHANGES.md** under `### New` (user's view, ≤ 3 sentences): Settings → Screen has a switch "Let other computers use this keyboard and mouse (Deskflow)"; computers running the Deskflow client then show up there, and after you compare the fingerprint and attach one beside a monitor, pushing the pointer past that edge moves keyboard and mouse to it. Ctrl+Alt+Shift+Escape always brings them back. +- [ ] **Step 5: Full gates:** `make test-unit`, `make test`, `make test-runtime`, `cargo clippy -j 4`, `cargo fmt --check` in the crate; `test-image-size.sh` green (raise the budget only with a reason in the commit). +- [ ] **Step 6: Commit** `docs(deskflow): notes, fresh-install exclusion, changelog`. + +### Task 14: Owner hardware check (not automatable) + +- [ ] A real stick, a Linux or macOS laptop with Deskflow 1.26: pair, attach right-of, type with `de` on both sides, push through the edge at each resistance level, use the escape chord; repeat inside a full-screen ThinLinc session. Record the result in `docs/notes/deskflow.md`. diff --git a/docs/superpowers/plans/2026-11-22-deskflow-clipboard-media-keys.md b/docs/superpowers/plans/2026-11-22-deskflow-clipboard-media-keys.md new file mode 100644 index 0000000..907b5c1 --- /dev/null +++ b/docs/superpowers/plans/2026-11-22-deskflow-clipboard-media-keys.md @@ -0,0 +1,160 @@ +# Deskflow clipboard and media keys (steps 2 and 3) Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** Text copied on ThinFloe can be pasted on an attached Deskflow device and back (step 2), and while the pointer is on a device the volume and brightness keys act on that device while the microphone mute key stays on ThinFloe (step 3). + +**Architecture:** Step 2 adds a pure clipboard codec (`deskflow/clipdata.rs`), clipboard messages in the sans-IO `Session`, a Wayland data-control bridge on its own connection (`deskflow/clip.rs`), a pure policy (`deskflow/clipsync.rs`) that `run.rs` drives, and the per-device Clipboard switch in the Deskflow band. Step 3 adds labwc patch `0007`, a keyboard-shortcuts inhibitor on the capture strip, and the local mic-mute rule. + +**Tech Stack:** Rust (menu crate, wayland-client 0.31, wayland-protocols 0.32 `staging` for `ext_data_control_v1`, wayland-protocols-wlr for `zwlr_data_control_v1`), C patch on labwc 0.9.3, bash runtime tests. + +**Spec:** `docs/superpowers/specs/2026-11-21-deskflow-server-design.md` (sections Clipboard, Keyboard → Media keys follow the pointer, Build order 2 and 3). Step-1 plan for conventions: `docs/superpowers/plans/2026-11-21-deskflow-server-core.md`. Notes: `docs/notes/deskflow.md`. + +## Global Constraints + +- Text clipboard only (format Text = 0, UTF-8, LF); clipboard id 0 (`kClipboardClipboard`) only; the primary selection (id 1) is not bridged. +- Cap: 1 MiB (1048576 bytes) of marshalled clipboard data per transfer; larger content is not sent and not accepted. +- The daemon reads only `generated/deskflow`, never `config.toml`; the menu is the only writer of `[deskflow]`. +- The daemon's event loop never blocks: every pipe read/write of clipboard data is non-blocking and polled; the 2 s watchdog must never fire because of a slow or hung clipboard peer. +- Getting back to ThinFloe never waits for the network or the client (Ctrl+Alt+Shift+Escape, watchdog, keep-alive) — unchanged by this work. +- No new compositor keybinding. The six media-key bindings stay `allowWhenInhibited="yes"`; toplevel inhibitors (OxuLnk, ThinLinc grab) keep today's meaning. +- Microphone mute stays on ThinFloe: `XF86AudioMicMute` is never sent to a device; on its release while captured the daemon runs `thinfloe-menu --osd-key mic-mute` only when the volume-key switch (`THINFLOE_VOLUME_KEYS=on`, which also binds mic-mute) is on. +- Builds: `make … VERSION=deskflow BUILD_JOBS=4`; cargo with `CARGO_TARGET_DIR=/scratch/oetiker/cargo-target-thinfloe-deskflow` and `-j 4`. Never more than 4 cores. Tests that feed adversarial input run under `systemd-run --user --scope -p MemoryMax=2G`. +- UI code: colours from the theme, text sizes from `brand.rs` (`ui_code_has_no_style_literals`). Labels in English, Simplified Technical English. +- CHANGES.md entries per the user's rules (reader-facing, ≤3 sentences, no release header). +- No code copied from Deskflow or lan-mouse (MIT project). + +## Deskflow wire facts (read from Deskflow source 80221f0; the implementer may re-check in the clone at `/scratch/oetiker/claude-tmp/claude-1003/-scratch-oetiker-claude-worktrees-thinfloe-deskflow/4b793ca4-6740-4c0b-93d1-cdc95c78106a/scratchpad/deskflow-src`) + +- Marshalled clipboard: u32 BE number of formats, then per format u32 format id, u32 size, bytes (`IClipboard.cpp`). ThinFloe sends exactly one format (Text, 0); on receive it takes the first Text entry and ignores other formats; a truncated entry yields no text. +- DCLP transfer = one start chunk (mark 1, data = the marshalled size as ASCII decimal, no NUL), one or more data chunks (mark 2, ≤ 512 KiB each), one end chunk (mark 3, empty data); all carry the same id and seq. An empty transfer still has one (empty) data chunk (`StreamChunker.cpp`). +- Receive (`ClipboardChunk::assemble`): data before start or end before start is an error; data beyond the declared size is an error; end with fewer bytes than declared is an error; a declared size above the cap is dropped silently (chunks ignored until end), not a disconnect. +- The client sends CCLP(id, seq) when it grabs; if it is not the active screen it sends the DCLP at once, else after COUT (`Client.cpp` ~l.240, ~l.660). The server sends CCLP to every other screen when one grabs and DCLP to the active screen; on entering a screen the server sends it DCLP. +- DSOP options: pairs of u32 (option code, value). `CLPS` (`kOptionClipboardSharing`, value 0/1) and `CLSZ` (`kOptionClipboardSharingSize`, value in KiB). Option codes are the four ASCII bytes as a big-endian u32 (`OPTION_CODE`, `OptionTypes.h` l.30 — verify). + +## Review Focus + +1. A clipboard owner that never writes, or writes forever (a hung app, `yes | wl-copy`): the daemon must stop reading at 1 MiB or after 2 s, drop the transfer, and keep forwarding input. → test in Task 2 (`reader_stops_at_cap_and_deadline`). +2. A hostile client sending DCLP chunks without start, oversize declared sizes, more data than declared, or an endless stream of chunks: no allocation above the cap, no disconnect for an oversize transfer, disconnect only for a protocol error. → tests in Task 1. +3. The daemon setting the ThinFloe selection from a device must not bounce the same text straight back to that device as a "change" (echo loop, like the CALV one of step 1). → test in Task 3 (`own_selection_is_not_sent_back`). +4. Clipboard switch off for one device: that device gets no CCLP/DCLP, its DSOP says `CLPS 0`, and text it sends anyway is ignored; switching it on or off takes effect on reload without a reconnect. → tests in Task 1 (DSOP on reload) and Task 3. +5. Media keys while captured with the volume-key switch off: they go to the device too (there is no ThinFloe binding to suppress), and mic-mute does nothing locally. With the switch on and not captured, every media key still acts on ThinFloe with a ThinLinc/OxuLnk inhibitor. → runtime cases in Task 6 and Task 7. + +--- + +## Step 2: Clipboard + +### Task 1: Clipboard codec and Session messages + +**Files:** +- Create: `src/thinfloe-menu/src/deskflow/clipdata.rs` (+ `pub mod clipdata;` in `deskflow/mod.rs`) +- Modify: `src/thinfloe-menu/src/deskflow/session.rs` + +**Interfaces:** +- Produces (clipdata.rs): + - `pub const CLIP_MAX: usize = 1 << 20;` `pub const CHUNK: usize = 512 * 1024;` + - `pub fn marshal_text(text: &[u8]) -> Vec` + - `pub fn unmarshal_text(data: &[u8]) -> Option>` + - `pub fn chunks(id: u8, seq: u32, marshalled: &[u8]) -> Vec` (Msg::Dclp start/data…/end) + - `pub struct Assembler` with `pub fn push(&mut self, id: u8, seq: u32, mark: u8, data: &[u8]) -> Asm`; `pub enum Asm { Started, InProgress, Finished(Vec), Dropped, Error }` (Finished carries the marshalled bytes; Dropped = oversize transfer ended or chunk of an oversize transfer). + - `pub fn options(clipboard: bool) -> Vec`: `[CLPS, 1, CLSZ, 1024]` when on, `[CLPS, 0]` when off. +- Produces (session.rs): + - `Session::set_clipboard(&mut self, on: bool) -> Vec`: stores the flag; when Active and the flag changed, sends a new DSOP. + - The first DINF's DSOP now carries `clipdata::options(flag)` (flag default true until set). + - `Out::Clipboard { text: Vec }` — a finished inbound transfer for id 0 with Text, only while the flag is on. + - `Out::Grabbed` — the client sent CCLP for id 0 (flag on). + - `Session::clipboard(&mut self, text: &[u8]) -> Vec`: CCLP + DCLP chunks (id 0, next seq) when live and flag on and `marshal_text(text).len() <= CLIP_MAX`; else nothing. + - `Session::grab(&mut self) -> Vec`: CCLP only (tells an inactive device ThinFloe owns the clipboard). + - An Assembler Error closes the connection ("bad clipboard"); Dropped is ignored. + +- [ ] Step 1: failing tests in clipdata.rs: `marshal_roundtrip` (`unmarshal_text(&marshal_text(b"h\xc3\xa4llo\n")) == Some(b"h\xc3\xa4llo\n".to_vec())`), `unmarshal_skips_other_formats` (formats HTML then Text → the Text), `unmarshal_truncated_is_none`, `chunks_split_at_512k` (a marshalled input of CHUNK*2+1 bytes → start data "1048577", marks [1,2,2,2,3], data lengths [CHUNK, CHUNK, 1]), `empty_transfer_has_one_data_chunk`, `assembler_errors` (data before start → Error; more than declared → Error; end short → Error), `assembler_oversize_is_dropped_not_error` (start "2000000" → Dropped for start, data, end; no buffer grows: check an internal len accessor is 0), `options_codes` (CLPS == u32::from_be_bytes(*b"CLPS")). +- [ ] Step 2: failing tests in session.rs: `dsop_carries_clipboard_option`, `set_clipboard_resends_dsop_when_active`, `inbound_transfer_yields_clipboard`, `inbound_ignored_when_off`, `bad_chunk_closes`, `clipboard_out_sends_cclp_then_dclp`, `clipboard_over_cap_sends_nothing`. +- [ ] Step 3: implement; run `cargo test -j 4 deskflow::`; clippy, fmt. +- [ ] Step 4: commit `feat(deskflow): clipboard codec and messages`. + +### Task 2: Wayland clipboard bridge + +**Files:** +- Create: `src/thinfloe-menu/src/deskflow/clip.rs` +- Modify: `Cargo.toml` only if a feature is missing (`staging` is already on). + +**Interfaces:** +- Produces: + - `pub struct Clip`; `pub fn connect() -> Result` — its own `wayland_client::Connection`; binds `ext_data_control_manager_v1`, else `zwlr_data_control_manager_v1`, else Err (the daemon then runs without clipboard and logs once). + - `pub fn fd(&self) -> BorrowedFd<'_>`, `pub fn dispatch(&mut self, now: Instant) -> Result, String>`, `pub fn flush(&mut self) -> Result<(), String>`. + - `pub fn pipe_fds(&self) -> Vec<(RawFd, libc::c_short)>` and `pub fn on_pipe_ready(&mut self, fd: RawFd, now: Instant) -> Vec`, `pub fn deadline(&self) -> Option` and `pub fn tick(&mut self, now: Instant) -> Vec` (drops transfers older than 2 s). + - `pub enum ClipEvent { Changed(Vec) }` — a selection set by another client, text read in full (≤ CLIP_MAX). + - `pub fn set_text(&mut self, text: Vec)` — new data source offering `text/plain;charset=utf-8`, `text/plain`, `UTF8_STRING`, `STRING`, `TEXT` and the private marker `application/x-thinfloe-deskflow`; each `send(mime, fd)` writes the text non-blocking from the poll loop and closes the fd. +- Decisions: an offer that lists `application/x-thinfloe-deskflow` is ThinFloe's own and produces no event. Mime preference to read: `text/plain;charset=utf-8`, `UTF8_STRING`, `text/plain`, `STRING`, `TEXT`; an offer with none → no event. A new selection cancels a read in progress. Reading stops at CLIP_MAX+1 bytes (transfer dropped) or after 2 s. Pure helpers `pick_mime(&[String]) -> Option<&str>` and a `CappedRead` buffer type are unit-tested. + +- [ ] Step 1: failing unit tests: `pick_mime_prefers_utf8`, `own_marker_is_skipped`, `reader_stops_at_cap_and_deadline` (CappedRead fed CLIP_MAX+1 bytes → Over; fed nothing past 2 s → Expired). +- [ ] Step 2: implement; a runtime smoke under headless labwc: `thinfloe-menu --deskflow-probe-clip` (hidden test mode, like the existing `probe_capture`) prints `changed ` on each foreign selection and sets the selection from stdin lines `set `. Add a case to `test/runtime/test-labwc-runtime.sh`: `wl-copy` some text → probe prints it; probe sets text → `wl-paste` returns it; `yes | head -c 3000000 | wl-copy` → probe prints nothing and keeps answering. If `wl-clipboard` is missing in `test/runtime/Dockerfile`, add it there (runtime test image only, not the ThinFloe image). +- [ ] Step 3: run `cargo test -j 4` and the runtime case (iterate with `TF_RUNTIME_MENU=`); clippy, fmt. +- [ ] Step 4: commit `feat(deskflow): Wayland clipboard bridge`. + +### Task 3: Clipboard policy and daemon wiring + +**Files:** +- Create: `src/thinfloe-menu/src/deskflow/clipsync.rs` +- Modify: `src/thinfloe-menu/src/deskflow/run.rs` (poll the Clip fd and pipe fds; route events) + +**Interfaces:** +- Consumes: Task 1 Session API, Task 2 Clip API. +- Produces (pure, sans-IO): + - `pub struct ClipSync`; `pub enum ClipAct { Send { conn: usize, text: Vec }, Grab { conn: usize }, SetLocal(Vec) }` (conn = the daemon's connection index). + - `fn on_local(&mut self, text: Vec, active: Option, live: &[(usize, bool)]) -> Vec` — ThinFloe's selection changed: Send to the active conn if its clipboard is on, Grab to every other live conn with clipboard on; remembers the text. + - `fn on_enter(&mut self, conn: usize, clipboard: bool) -> Vec` — Send the remembered text (none if ThinFloe never had text). + - `fn on_remote(&mut self, conn: usize, text: Vec) -> Vec` — SetLocal(text), remember it, and mark it so the `ClipEvent::Changed` that may follow with the same bytes is not sent back to `conn` (Clip already skips its own offers; this covers a second client re-offering the same text). + - `fn on_grabbed(&mut self, conn: usize, live: &[(usize, bool)]) -> Vec` — a device grabbed: Grab to every other live clipboard conn. +- [ ] Step 1: failing tests: `enter_sends_remembered_text`, `enter_without_text_sends_nothing`, `local_change_goes_to_active_and_grab_to_others`, `switch_off_device_gets_nothing`, `remote_text_sets_local`, `own_selection_is_not_sent_back`, `grab_from_one_device_reaches_the_others`. +- [ ] Step 2: implement ClipSync; wire run.rs: Clip connected at start (failure logged, clipboard off), its fds in the poll set, its deadline in the timeout; `Out::Clipboard`/`Out::Grabbed` and capture enter call ClipSync; `set_clipboard` called on every connection at reload with the device's `clipboard` flag. A Clip error drops the bridge (logged) and never ends the daemon. +- [ ] Step 3: `cargo test -j 4`; clippy, fmt. +- [ ] Step 4: commit `feat(deskflow): bridge the text clipboard to attached devices`. + +### Task 4: Clipboard switch in the Deskflow band + +**Files:** +- Modify: `src/thinfloe-menu/src/deskflowtab.rs`, `src/thinfloe-menu/src/deskflow_ui.rs` + +**Interfaces:** +- Produces: in the selected device's detail (next to Position and Forget) a switch labelled `Share the clipboard`; toggling writes `clipboard` of that `[[deskflow.device]]` through the store and reloads the daemon like every `[deskflow]` write. +- [ ] Step 1: failing test in deskflowtab.rs: `clipboard_switch_writes_device` (toggle off → the saved config has `clipboard = false` for that device only). +- [ ] Step 2: implement; `ui_code_has_no_style_literals` stays green. +- [ ] Step 3: `cargo test -j 4`; clippy, fmt; commit `feat(menu): per-device clipboard switch for Deskflow`. + +### Task 5: Clipboard interop test, notes, changelog + +**Files:** +- Modify: `test/runtime/test-labwc-runtime.sh` (the Deskflow interop section), `test/runtime/Dockerfile` if a tool is missing, `docs/notes/deskflow.md`, `CHANGES.md`. + +- [ ] Step 1: interop cases with the real `deskflow-core client`: (a) `wl-copy` text on ThinFloe, capture into the client → the client's X clipboard (`xclip -o -selection clipboard` or `xsel` on the client's display) holds the text; (b) set the client's clipboard while captured, leave (pointer back) → `wl-paste` on ThinFloe returns it; (c) the device with `clipboard = false` → after capture the client's clipboard is unchanged. If the client cannot be driven to own its clipboard in the harness, document why in the notes and keep (a) and (c). +- [ ] Step 2: `make test-runtime VERSION=deskflow BUILD_JOBS=4` green (iterate with `TF_RUNTIME_MENU`, final run on the make-built image). +- [ ] Step 3: notes: a Clipboard section (flow, cap, own-offer marker, what is not bridged); CHANGES.md entry: e.g. "Text copied on ThinFloe can now be pasted on a computer attached with Deskflow, and text copied there can be pasted on ThinFloe. Settings → Screen has a "Share the clipboard" switch per device." +- [ ] Step 4: commit `test(deskflow): clipboard interop; docs`. + +## Step 3: Media keys follow the pointer + +### Task 6: labwc patch 0007 + +**Files:** +- Create: `containers/ubuntu/patches/0007-layer-inhibitor-blocks-all-keybinds.patch` (DEP-3 header like 0004) +- Modify: the Dockerfile's patch list if patches are listed by name; `Makefile` `PATCH_FILES` if listed by name (check `test-container-inputs.sh`); `test/runtime/test-labwc-runtime.sh`. + +**Interfaces:** +- Produces: a `zwp_keyboard_shortcuts_inhibitor_v1` on a layer surface counts (a server-wide counter or a list, decremented on destroy) and, while that layer surface has the seat's keyboard focus, `handle_keybinding` runs no binding at all, `allowWhenInhibited` ones included. Inhibitors on views behave as in 0004/0006. +- [ ] Step 1: runtime case (red on the current image): a probe client (`thinfloe-menu --deskflow-probe` gains `--inhibit`, or the existing capture probe) holds an overlay layer surface with exclusive keyboard + inhibitor; with `THINFLOE_VOLUME_KEYS=on` and `TF_OSD_KEY_CMD` pointing at a recorder, inject `XF86AudioRaiseVolume` → the recorder is not called and the probe sees the key; after the probe exits the key calls the recorder again. Also inject while an x11-probe window holds an X11 keyboard grab (Risk 1 part 2) and the strip took the focus → recorder not called. Existing case (`allowWhenInhibited` passes a toplevel inhibitor) stays green. +- [ ] Step 2: write the patch on labwc 0.9.3 with 0001–0006 applied; rebuild the container; runtime case green. +- [ ] Step 3: CLAUDE.md: patch list in "labwc is a local rebuild" and the keybinding constraint gain `0007`; commit `feat(labwc): a layer-surface inhibitor blocks every keybinding`. + +### Task 7: Inhibitor at capture and the local mic-mute key + +**Files:** +- Modify: `src/thinfloe-menu/src/deskflow/capture.rs` (bind `zwp_keyboard_shortcuts_inhibit_manager_v1`; create the inhibitor on the strip right after setting exclusive interactivity in `begin_capture`, destroy it in `end_capture`), `src/thinfloe-menu/src/deskflow/forward.rs` (new `Action::LocalMicMute` on the release of keysym `XF86AudioMicMute` 0x1008ffb2 while captured; the press and release are not sent), `run.rs` (runs `thinfloe-menu --osd-key mic-mute` detached, own process group, no wait, when `mic_mute_local` is true), `src/thinfloe-menu/src/deskflowcfg.rs` / `generated.rs` (the generated file gains `mic_mute_local = `; it is regenerated, and the daemon reloaded, when the volume-key switch changes; it is not part of `config.toml`'s `[deskflow]`). +- [ ] Step 1: failing unit tests: `mic_mute_release_is_local_and_not_sent` (forward), `generated_deskflow_carries_mic_mute_local` (generated.rs), `volume_switch_regenerates_deskflow`. +- [ ] Step 2: implement; interop case: while captured, inject `XF86AudioRaiseVolume` → the client sees the key (its log or the harness's key trace shows the down for KeyID 0xE0AF) and the ThinFloe recorder is not called; inject `XF86AudioMicMute` → recorder called with `mic-mute`, client sees nothing; after release (escape chord) the volume key reaches the recorder again. +- [ ] Step 3: `cargo test -j 4`, clippy, fmt, `make test-runtime` green; notes (Media keys section; replace "Media keys still act on ThinFloe in this step"), CLAUDE.md Deskflow rule line if needed, CHANGES.md entry ("While the pointer is on a computer attached with Deskflow, the volume and brightness keys act on that computer and ThinFloe shows no volume or brightness display. The microphone mute key still mutes ThinFloe."). +- [ ] Step 4: commit `feat(deskflow): media keys follow the pointer`. + +### Task 8: Final gates + +- [ ] `cargo test`, clippy, fmt; `make test-unit`; `make test-runtime`; `make test`; `test-image-size.sh` (record growth with reason if needed). Whole-branch review of steps 2–3, fix wave, then PR. diff --git a/docs/superpowers/specs/2026-11-21-deskflow-server-design.md b/docs/superpowers/specs/2026-11-21-deskflow-server-design.md new file mode 100644 index 0000000..80e41d1 --- /dev/null +++ b/docs/superpowers/specs/2026-11-21-deskflow-server-design.md @@ -0,0 +1,411 @@ +# Deskflow server in ThinFloe: design + +Date: 2026-11-21. Status: draft for approval. + +## Intent + +ThinFloe's keyboard and mouse should drive the other computers on the desk +(a laptop, a Mac, a Windows box) the way they drive a second monitor: move +the pointer off the edge of a ThinFloe monitor and it continues on the +other computer, typing goes there, and text copied on one side can be +pasted on the other. The other computers run the stock Deskflow client +(also Barrier and Input Leap clients, which speak the same protocol). +ThinFloe is the Deskflow **server**. + +The owner's picture of it: the multi-monitor arrangement in Settings → +Screen grows a second kind of screen. With the listen switch on, a device +that connects shows up there; the user checks its fingerprint and decides +where it attaches, exactly like placing a monitor. + +## Goals + +- ThinFloe acts as a Deskflow server (protocol 1.6 to 1.8) for stock + clients on Linux, macOS and Windows that present a TLS client + certificate: current Deskflow, and Input Leap and Barrier releases that + send one. Clients that send no certificate are not supported (see + Identity and pairing). The first Deskflow, Input Leap and Barrier + releases that send a client certificate are named in + `docs/notes/deskflow.md`; the interop test runs current Deskflow. +- Pairing at the machine: a connecting device appears as *pending* with its + name and fingerprint; the user attaches it to a side of a ThinFloe + monitor, or rejects it. Nothing connects without that step. +- Mutual TLS with fingerprint pinning, compatible with Deskflow's own + scheme. ThinFloe shows its own fingerprint for the user to compare on the + client. +- Keyboard, pointer, buttons and wheel go to the attached device while the + pointer is on it, also when a ThinLinc or OxuLnk window fills the screen. +- Text clipboard in both directions (UTF-8 text only, size-capped). +- No root. One labwc patch is in scope for the media keys (see Keyboard); + a second only if the ThinLinc spike (Risk 1) shows one is needed. + +## Non-goals + +- ThinFloe as a Deskflow **client** (being driven by another computer). +- Image, HTML or file clipboard; drag and drop (DFTR/DDRG are deprecated in + Deskflow anyway). +- Plain-text (non-TLS) clients. +- Devices attached to other devices (a chain laptop → tablet). Every device + attaches to a ThinFloe monitor. +- Hotkeys that switch screens; the screen-saver sync (CSEC is sent, nothing + more); the macOS secure-input message (SECN) and language sync (LSYN) are + accepted silently or not sent. + +## Anti-goals (a failure even if it works) + +- A ThinFloe screen that no longer takes keys because the pointer is "on" + a device that is gone, hung or unreachable. Getting back must never depend + on the network or on the client. +- A device that can connect without the user having attached it at this + machine. +- A crash or hang in the Deskflow code that takes the menu (and with it the + home save) down. +- A new compositor keybinding (standing constraint: labwc has none unless a + key switch is on). + +## Constraints from the project + +- The menu crate draws on the CPU; no new GPU dependencies. +- `config.toml` is written only by the menu (`store.rs`); readers that are + not the menu read it, never write it. +- labwc 0.9.3 in the image already offers every protocol needed (checked in + the built `labwc` binary, 2026-11-21): `zwlr_layer_shell_v1`, + `zwp_pointer_constraints_v1`, `zwp_relative_pointer_manager_v1`, + `zwlr_data_control_manager_v1` / `ext_data_control_manager_v1`, and the + shortcuts inhibitor of patch `0004`. +- The identity (private key) must not be copied by a fresh install; it + rides the home archive like the SSH host keys (in the clear on the ESP, + over plain HTTP on netboot — the same accepted risk). +- No firewall exists in the image; the listen switch is the only gate. +- New Makefile inputs (none expected beyond the crate) and the image size + budget (`test-image-size.sh`) apply. + +## Approaches considered + +- **A. Inside the menu process.** Simplest wiring, but a fault in network or + capture code can crash or stall the menu, which must save the home before + it exits, and the menu's own UI would have to cope with "the keyboard is + away". Rejected. +- **B. A second mode of the same binary, `thinfloe-menu --deskflow`** + (chosen by the owner). Shares the crate's config schema, monitor geometry + and Wayland code; runs as its own process, so a crash only ends Deskflow. + The menu stays the only UI and the only writer of `config.toml`. +- **C. A separate crate and binary.** Strongest isolation, but duplicates the + config, store and monitor code or forces a library split. No gain over B. + +lan-mouse (GPL-3.0) is the reference for the capture technique; ThinFloe is +MIT, so no code is copied from it or from Deskflow. + +## Design + +### Processes + +- The **menu** starts `thinfloe-menu --deskflow` when `[deskflow] listen = + true`, in a process group of its own (child sets `PR_SET_PDEATHSIG` + SIGTERM), restarts it after a crash with a + back-off (1 s, 2 s, 4 s … 60 s cap), stops it with SIGTERM when the switch + goes off, and sends SIGHUP after each write of `[deskflow]` so it reloads + its config. The menu shows "Deskflow stopped: " from the state + file when the daemon keeps failing. Before it exits (0, 10, 11) the menu + sends the daemon SIGTERM and waits up to 1 s. +- The daemon also exits by itself when its Wayland connection closes, so a + menu crash (labwc kept up by the failure window) or the end of labwc never + leaves a daemon holding port 24800. Guard: `test-labwc-runtime.sh` + (no `--deskflow` process and no listener on 24800 after logout, restart + and a killed menu). +- The **daemon** (`--deskflow`) owns: the TCP listener, TLS, the protocol, + the edge strips and pointer lock, the clipboard bridge. It reads + `~/.config/thinfloe/generated/deskflow` (see Configuration), never + `config.toml`, which holds the WiFi passwords and is read by nobody but + the menu (`store.rs`). It writes only its state file and its identity. +- Commands from the menu go over a datagram socket + `$XDG_RUNTIME_DIR/thinfloe-deskflow.sock`, like the OSD's + (`osd/socket.rs`): `reject `, `reload`. SIGHUP stays + as the reload fallback. +- State file `$XDG_RUNTIME_DIR/thinfloe-deskflow.state`, written atomically + by the daemon, read by the menu on change (inotify or the menu's existing + polling): one line per (name, fingerprint) pair, + `namefingerprintstatesince_epochwidthheightflags`, + state one of `pending`, `rejected`, `connected`, `active` (pointer on + it), `offline`; width and height from the device's last DINF (0 when + unknown); flags a comma list, so far `fp-changed` (the name is attached + with another fingerprint). The same name may appear twice (the attached + fingerprint and a changed one). First line + `self` or `error`. A + contract like the battery file, with a unit-tested parser that ignores + unknown trailing fields. + +### Identity and pairing + +- First start: the daemon makes a self-signed certificate (ECDSA P-256, + CN `ThinFloe `, valid 2000-01-01 to 2099-12-31 so that the + boot clock does not shape it) and stores key and certificate + in `~/.config/thinfloe/deskflow/identity.pem` (mode 600). This path goes + into `IDENTITY_EXCLUDES` of `thinfloe-upgrade`; a fresh stick gets its own. + Guard: an assertion in `test_upgrade_image.py`; the fresh-install rule in + CLAUDE.md and `docs/notes/home-persistence.md` name the file. + *Verify in the interop test that Deskflow clients accept an ECDSA server + key; fall back to RSA-2048 if not.* +- Fingerprint = SHA-256 over the DER certificate, as Deskflow computes it. + Shown as Deskflow's random-art picture plus the colon hex, so the user + can compare it with what the Deskflow client shows. +- TLS: rustls, TLS 1.2 and 1.3, server always requests a client + certificate. A client without one is dropped: approving by name alone + would let any computer on the LAN take over an attached device's slot by + sending its name. Client certificates are not + chain-checked (Deskflow's are self-signed); trust is the fingerprint. +- Connection flow: + 1. TLS handshake; fingerprint F of the client certificate. + 2. Hello / HelloBack; client name N (capped at 64 bytes, shown escaped). + 3. If (N, F) is in `[[deskflow.device]]`: proceed (QINF/DINF, keep-alive). + 4. If N is known with a **different** F: refuse (EUNK, close), state + `pending` with a warning "fingerprint changed" — the user must + re-attach explicitly. + 5. Otherwise: record N, F as `pending`, send EUNK and close. The Deskflow + client sets its retry flag on EUNK (`Client.cpp`) and tries again; + once the user attaches it, the next try succeeds. +- **Order on first contact.** The Deskflow client checks ThinFloe's + fingerprint during the TLS handshake and drops the connection before + HelloBack if it does not trust it (`SecureSocket.cpp`). So the user first + trusts ThinFloe on the client (comparing with the picture in the menu); + only then does the device appear as pending here. The Screen band says + so next to ThinFloe's fingerprint. The interop test pre-fills the client's + `tls/trusted-servers` (`v2:sha256:`). +- Rejected devices are remembered in the state file for the session only + and not shown again until they change fingerprint or the session ends. +- Limits against a noisy LAN: at most 8 pending devices (oldest dropped), + 4 simultaneous handshakes, 10 s to finish TLS and Hello, messages capped + at 1 MiB except clipboard chunks. + +### Configuration (`config.toml`) + +```toml +[deskflow] +listen = false # the switch; off by default +port = 24800 + +[[deskflow.device]] +name = "laptop" +fingerprint = "v2:sha256:…" # Deskflow's own trusted-db line format +output = "DP-1" # the ThinFloe monitor it attaches to +side = "right-of" # left-of | right-of | above | below +clipboard = true +``` + +The menu derives `generated/deskflow` from this table (store order: +generated first, `config.toml` last), and `store.rs`'s rebuild of a broken +`config.toml` from `generated/` reads it back, so a broken `config.toml` +does not lose the pairings. The daemon reads only the generated file. + +The output is named by the same criteria string the `[monitors]` profiles +use, so a device follows its monitor when the monitor arrangement changes. +The position belongs to the monitor, not to a profile: it applies in every +profile. In a profile where that monitor is missing, or where the chosen +edge touches another ThinFloe monitor, the device is shown but inactive +("this edge is not free in the current arrangement") and gets no strip. +The Position control offers the edges that are free in the active profile. + +### Screen tab + +- Settings → Screen gets a **Deskflow** band under the monitor arrangement: + the switch "Let other computers use this keyboard and mouse (Deskflow)", + ThinFloe's address and port, and its fingerprint picture. +- Pending devices are listed with name, fingerprint picture and two buttons: + **Attach…** and **Reject**. Attach opens the same Position control the + monitors use ("Right of DP-1"); confirming writes the device to + `config.toml`. +- Attached devices are drawn in the arrangement view next to their monitor, + as outlined rectangles scaled from the size the client reports in DINF, + with a status dot (connected, active, offline). Selecting one shows + Position, Clipboard on/off and **Forget**. +- All colours and text sizes from the theme and `brand.rs` (the style-literal + test applies). + +### Edge capture and the way back + +- For each attached, connected device the daemon puts a layer-shell surface + on the **overlay** layer along the attached edge of its monitor: 1 px deep, + as long as the edge, transparent buffer, input region = the strip, + exclusive zone 0, keyboard interactivity `none` while idle. Only edges + that do not touch another ThinFloe monitor qualify (the Position control + offers only those). +- **Edge resistance** (owner, 2026-11-21). Touching the edge is not + enough: the pointer goes to the device only when the user keeps pushing + into the edge. While the pointer is on the strip (the cursor cannot move + further, but `zwp_relative_pointer_v1` still reports motion to the + surface under the pointer), the daemon sums the outward component of the + relative motion. The sum resets when the pointer leaves the strip or stops + pushing outward for 300 ms. When it reaches the threshold, capture starts. + A brush against the edge thus stays on ThinFloe. The strip still covers + the edge pixel: a click there, and the pointer in the last row of a + full-screen remote desktop at that edge (an auto-hide taskbar, a hot + corner), reach the strip. Step 1 keeps this; the owner decides on + hardware (notes, Known limits). + - Setting `[deskflow] edge_resistance`: `off` (0 px), `low` (15), + `medium` (40, default), `high` (100), in logical pixels of unaccelerated + motion. One value for all devices, shown as a select in the Deskflow band. + - Back from the device: no resistance (the tracked position crossing the + attached edge ends the capture, as in Deskflow). + - No visual hint while resistance builds up in the first version. + - Unit tests: the accumulator (outward only, reset on leave and on the + 300 ms pause, each level's threshold). +- Resistance reached → the daemon: + 1. creates the pointer lock first (`zwp_pointer_constraints_v1`, lock, + lifetime oneshot) and the relative-pointer object; + 2. then sets keyboard interactivity `exclusive` on the strip and + activates a keyboard-shortcuts inhibitor on it (honoured by the new + labwc patch, see Keyboard). Order matters: labwc 0.9.3 activates a new + lock only for the active view (`create_constraint`, + `src/input/cursor.c`) or on a keyboard focus change (`seat_focus`), so + the lock must exist before the focus moves; + 3. waits for the `locked` event, and only then sends CINN with the entry point mapped proportionally along the edge, + and from then forwards DMMV (absolute, tracked by the daemon inside the + device's DINF size), DMDN/DMUP, DMWM, DKDN/DKRP/DKUP. +- The pointer leaves the device when the tracked position crosses back over + the attached edge → COUT, unlock, interactivity `none`, warp-free return + (the real pointer never moved while locked). +- **Release always wins.** The capture is dropped at once, without waiting + for the client, on any of: + - the escape combination **Ctrl+Alt+Shift+Escape** pressed on the ThinFloe + keyboard (seen by the daemon's own keyboard focus; not a compositor + binding); + - a missed keep-alive (3 s rate, 3 misses) or a closed or failing socket; + - the lock being cancelled by the compositor (`unlocked` event), the strip + losing keyboard focus, or its output going away; + - a watchdog thread that sees the event loop stall for more than 2 s: it + aborts the process, and the compositor drops lock and focus when the + client dies. + Because all capture state lives in Wayland objects owned by the daemon, a + crash of the daemon always returns pointer and keyboard to ThinFloe. + +### Keyboard + +- Keys come from the strip's `wl_keyboard` (evdev code plus the compositor's + keymap); xkbcommon (already in the dependency tree through winit's + `xkbcommon-dl`) turns them into keysyms and modifier state. +- KeyID: Deskflow's key ids (Unicode for characters, Deskflow's `kKey…` + values for the rest, from `KeyTypes.h`). KeyButton: the evdev code + 8 + (the X11 keycode). Modifier mask from XKB state using Deskflow's + `KeyModifierMask` bits. *Builder: take the KeyID table and mask bits from + Deskflow's `KeyTypes.h`; they were not checked yet.* +- Keys held at entry are not sent; keys held at exit are released (DKUP) on + the device before COUT. Repeat: Wayland sends no repeats, so the daemon + generates DKRP at the rate and delay `wl_keyboard.repeat_info` reports. +- **Media keys follow the pointer** (owner, 2026-11-21). While the pointer + is on a device, volume, mute, microphone mute and brightness act on that + device, not on ThinFloe, and ThinFloe shows no OSD. + - Today labwc runs the six media-key bindings (`allowWhenInhibited`, + patch `0006`) before any client sees the key, and patch `0004` counts + shortcut inhibitors only on toplevel views, so the strip cannot stop them. + - New patch `0007-layer-inhibitor-blocks-all-keybinds.patch`: a + keyboard-shortcuts inhibitor on a layer surface that has exclusive + keyboard focus suppresses **every** keybinding, `allowWhenInhibited` + ones too. Inhibitors on toplevel views keep today's meaning (OxuLnk and + ThinLinc grabs still pass the media keys to ThinFloe). The daemon + activates the inhibitor at capture and destroys it at release; a crash + destroys it with the surface, so ThinFloe's media keys come back by + themselves. + - Rejected: rewriting `rc.xml` without the media keys and running + `labwc --reconfigure` at each capture. It is slow, races fast edge + crossings, and a crash in the captured state leaves ThinFloe without + media keys. + - The keysyms `XF86AudioRaiseVolume`, `…LowerVolume`, `…Mute`, + `XF86MonBrightnessUp`, `…Down` map to Deskflow's audio and brightness + KeyIDs (`KeyTypes.h`: `kKeyAudioMute` 0xE0AD, `kKeyBrightnessDown` + 0xE0B8, `kKeyBrightnessUp` 0xE0B9, the volume keys next to them). + - **The microphone mute key stays on ThinFloe** (owner, 2026-11-21): + Deskflow has no KeyID for it. While captured, the daemon does not send + `XF86AudioMicMute` (F20 from `logitech-keys`, mapped by XKB) to the + device; on its release it runs the same command the labwc binding runs, + `thinfloe-menu --osd-key mic-mute` (`thinfloe-compose-labwc-config`), + and only when the mic-mute key switch is on. So muting during a ThinLinc + call works with the pointer on the laptop, and the OSD mark updates. + - Guards: `make test-runtime` (the existing check that `allowWhenInhibited` + keys pass a toplevel inhibitor, plus a new one that no binding fires + while a layer surface with an inhibitor has the focus); the interop + test checks that a volume key while captured reaches the client as + DKDN and that ThinFloe's volume does not change. + - The standing constraint "labwc has no keybindings unless a key switch is + on" and the patch list in CLAUDE.md gain a line for `0007`. +- Key messages use the form the negotiated minor version requires: at 1.8 + DKDL and a DKRP with a trailing language string (`%2i%2i%2i%2i%s`, sent + empty); at 1.6 and 1.7 DKDN and the four-field DKRP. + +### Clipboard + +- Text only, through `ext_data_control_manager_v1` (fall back to the wlr + variant). Deskflow's flow (`Server.cpp`), which the client expects: + - right after CINN the server sends DCLP with its current clipboard to + the device it enters (no message lets a client ask for it); + - while a device is active, every change of the ThinFloe selection is sent + to it at once as DCLP; + - CCLP tells devices that ThinFloe grabbed the clipboard; + - after COUT the device sends CCLP and DCLP for what it copied; that text + sets the ThinFloe selection. + DCLP is chunked with marks 1/2/3 (all clients are ≥ 1.6). +- Cap: 1 MiB per transfer; larger content is not sent. Per-device switch. +- The primary selection (middle-click paste) is not bridged. + +### Protocol subset + +Server sends: Hello, QINF, CIAK, CALV, CROP, DSOP (empty), CSEC, CINN, COUT, +CCLP, DCLP, DKDL/DKDN, DKRP, DKUP, DMDN, DMUP, DMMV, DMWM, CBYE, EICV, EBSY, +EUNK, EBAD. Server handles: HelloBack, DINF, CALV, CNOP, CCLP, DCLP. Framing: +4-byte big-endian length before every message, the Hello included +(`PacketStreamFilter.cpp`, `ClientListener.cpp`). Hello name `Barrier`, +version 1.8, negotiate down to the client's minor (accept 6 to 8, else +EICV). + +### Tests + +- Unit tests (cargo): message encode/decode for every message above, version + negotiation, framing limits, pairing decisions (known, pending, changed + fingerprint, limits), KeyID mapping table, edge mapping and the + tracked-position exit test, release triggers, state-file format. +- Interop test (`make test-runtime`, headless labwc): the real + `deskflow-core client` (or `input-leapc`) in a container connects to the + daemon; checks pending → attach via a written `config.toml` → connected; + fingerprint changed → refused; injected pointer motion into the strip + reaches the client (the client's log shows CINN/DMMV); escape combination + and killing the client both release. Memory-capped like every adversarial + input test (`systemd-run --user --scope -p MemoryMax=2G`). +- Hardware check by the owner: a ThinLinc full-screen session, a Mac or + Windows client, typing with a non-US layout on both sides. +- Image size: record the growth in `test-image-size.sh` if needed. + +## Risks + +1. **Full-screen ThinLinc.** ThinLinc's X11 keyboard grab (patch `0002`) and + patch `0003` (full-screen keeps focus) may keep the keyboard from going + to the overlay strip. This is the first thing to build: a spike that puts + a strip over a full-screen Xwayland window holding a grab and checks that + pointer lock and exclusive keyboard focus move to it. The spike also + tries patch `0007` against a grab, since an X11 grab is a toplevel + inhibitor of its own. If they do not, a + small labwc patch (an exclusive overlay layer surface takes focus over a + grab) is the fall-back, with `make test-runtime`. +2. Deskflow client behaviour the source does not settle: the GUI's + first-connect fingerprint dialog and ECDSA acceptance. Both are checked + by the interop test before the UI work. +3. Non-US layouts on a client with a different layout: Deskflow maps by + KeyID; mismatches are a known Deskflow limit, not fixed here. + +## Build order + +One design, built in three steps; each step ships something usable +(owner, 2026-11-21): + +1. **Server core:** the ThinLinc spike (Risk 1), the interop harness, + protocol, TLS and pairing, edge capture with edge resistance and the way + back, keyboard and pointer, the Screen band. Media keys still act on + ThinFloe in this step. +2. **Clipboard** (text). +3. **Media keys follow the pointer:** patch `0007`, the mic-mute rule, their + runtime and interop checks. + +## Left to the builder + +The crate layout of the new modules (`deskflow/` with `proto`, `tls`, +`pair`, `capture`, `clip`, `state`), the choice of rustls crypto provider +and of the certificate crate (rcgen or hand-built DER), how the menu notices +state-file changes, the exact drawing of the device rectangles, and the +text of the Screen-tab labels (English, Simplified Technical English). diff --git a/overlay/usr/bin/thinfloe-upgrade b/overlay/usr/bin/thinfloe-upgrade index 1b50e73..12520b8 100755 --- a/overlay/usr/bin/thinfloe-upgrade +++ b/overlay/usr/bin/thinfloe-upgrade @@ -134,6 +134,9 @@ SAVE_HOME_EXCLUDE_DEFAULT = "/etc/thinfloe/save-home-exclude" # stick without them generates its own on first boot. Both layouts and # both 3.x names: a save on a 3.x fallback boot leaves a real # ~/.dbrrg-ssh-host-keys in the home. +# - the Deskflow identity (~/.config/thinfloe/deskflow/identity.pem): the +# private key that makes this machine the Deskflow server the paired +# computers trust; two machines sharing it would pass for each other. # - the WireGuard config: it holds the machine's private key, and two peers # sharing one key break both tunnels. # - the same files inside ~/cfg-attic, where the migration to the @@ -144,6 +147,7 @@ SAVE_HOME_EXCLUDE_DEFAULT = "/etc/thinfloe/save-home-exclude" IDENTITY_EXCLUDES = ( "./.config/thinfloe/ssh-host-keys", "./.config/thinfloe/wg0.conf", + "./.config/thinfloe/deskflow", "./.thinfloe-ssh-host-keys", "./.dbrrg-ssh-host-keys", "./wg0.conf", diff --git a/src/thinfloe-menu/Cargo.lock b/src/thinfloe-menu/Cargo.lock index d90b7af..5621751 100644 --- a/src/thinfloe-menu/Cargo.lock +++ b/src/thinfloe-menu/Cargo.lock @@ -94,6 +94,45 @@ version = "0.7.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d3fb67a6e08acf24fdeccbac2cb6ac4305825bd1f117462e0e6f2f193345ad56" +[[package]] +name = "asn1-rs" +version = "0.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7f43a50ac4fdca5df8e885c21b835997f0a1cdee65494a6847694a98652d9d8" +dependencies = [ + "asn1-rs-derive", + "asn1-rs-impl", + "displaydoc", + "nom 7.1.3", + "num-traits", + "rusticata-macros", + "thiserror 2.0.21", + "time", +] + +[[package]] +name = "asn1-rs-derive" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3109e49b1e4909e9db6515a30c633684d68cdeaa252f215214cb4fa1a5bfee2c" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", + "synstructure 0.13.2", +] + +[[package]] +name = "asn1-rs-impl" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b18050c2cd6fe86c3a76584ef5e0baf286d038cda203eb6223df2cc413565f7" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "atomic-waker" version = "1.1.2" @@ -106,6 +145,21 @@ version = "1.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" +[[package]] +name = "base64" +version = "0.23.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" + +[[package]] +name = "bit-vec" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b71798fca2c1fe1086445a7258a4bc81e6e49dcd24c8d0dd9a1e57395b603f51" +dependencies = [ + "serde", +] + [[package]] name = "bitflags" version = "1.3.2" @@ -328,6 +382,12 @@ version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f27ae1dd37df86211c42e150270f82743308803d90a6f6e6651cd730d5e1732f" +[[package]] +name = "data-encoding" +version = "2.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4583a4551df46e2792f82ceeac45e850d2e2d5debba0b91f102385cda5b11f06" + [[package]] name = "data-url" version = "0.3.2" @@ -365,6 +425,26 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "der-parser" +version = "10.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "07da5016415d5a3c4dd39b11ed26f915f52fc4e0dc197d87908bc916e51bc1a6" +dependencies = [ + "asn1-rs", + "displaydoc", + "nom 7.1.3", + "num-bigint", + "num-traits", + "rusticata-macros", +] + +[[package]] +name = "deranged" +version = "0.5.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e9de72ce2ad1f90dc62fa25f0f430ef85eb4b0d8fa0be4f30373bc40a21d28e" + [[package]] name = "dispatch" version = "0.2.0" @@ -690,6 +770,17 @@ dependencies = [ "windows-link", ] +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "libc", + "wasi", +] + [[package]] name = "getrandom" version = "0.3.4" @@ -1071,6 +1162,12 @@ dependencies = [ "smallvec", ] +[[package]] +name = "lazy_static" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb" + [[package]] name = "libc" version = "0.2.190" @@ -1153,6 +1250,12 @@ dependencies = [ "libc", ] +[[package]] +name = "minimal-lexical" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" + [[package]] name = "miniz_oxide" version = "0.8.9" @@ -1219,6 +1322,16 @@ version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2bf50223579dc7cdcfb3bfcacf7069ff68243f8c363f62ffa99cf000a6b9c451" +[[package]] +name = "nom" +version = "7.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a" +dependencies = [ + "memchr", + "minimal-lexical", +] + [[package]] name = "nom" version = "8.0.0" @@ -1228,6 +1341,31 @@ dependencies = [ "memchr", ] +[[package]] +name = "num-bigint" +version = "0.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c89e69e7e0f03bea5ef08013795c25018e101932225a656383bd384495ecc367" +dependencies = [ + "num-integer", + "num-traits", +] + +[[package]] +name = "num-conv" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441" + +[[package]] +name = "num-integer" +version = "0.1.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ce2d95d4b3734dc35aa2f45e1aa22cd416814592a4f9d9205e11affd5b8e10b" +dependencies = [ + "num-traits", +] + [[package]] name = "num-traits" version = "0.2.19" @@ -1554,6 +1692,15 @@ dependencies = [ "objc2-foundation 0.2.2", ] +[[package]] +name = "oid-registry" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12f40cff3dde1b6087cc5d5f5d4d65712f34016a03ed60e9c08dcc392736b5b7" +dependencies = [ + "asn1-rs", +] + [[package]] name = "once_cell" version = "1.21.4" @@ -1603,6 +1750,16 @@ dependencies = [ "windows-link", ] +[[package]] +name = "pem" +version = "4.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d354a98a3d1251555de99e8fdd8afda05573c31b82f59063a7b0a29b5527f120" +dependencies = [ + "base64", + "serde_core", +] + [[package]] name = "peniko" version = "0.6.1" @@ -1737,6 +1894,12 @@ dependencies = [ "zerovec", ] +[[package]] +name = "powerfmt" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a6394b9e965e73d0a289ee54f589087e2c676aedf60885baf52c76b771e4958" + [[package]] name = "proc-macro-crate" version = "3.5.0" @@ -1809,6 +1972,20 @@ version = "0.6.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "20675572f6f24e9e76ef639bc5552774ed45f1c30e2951e1e99c59888861c539" +[[package]] +name = "rcgen" +version = "0.14.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8774e05a7d0de114588e6a28fe7e71694b82614ed569d86d8b389dfbc98b8ad8" +dependencies = [ + "pem", + "ring", + "rustls-pki-types", + "time", + "x509-parser", + "yasna", +] + [[package]] name = "read-fonts" version = "0.41.0" @@ -1871,6 +2048,20 @@ dependencies = [ "bytemuck", ] +[[package]] +name = "ring" +version = "0.17.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" +dependencies = [ + "cc", + "cfg-if", + "getrandom 0.2.17", + "libc", + "untrusted", + "windows-sys 0.52.0", +] + [[package]] name = "roxmltree" version = "0.21.1" @@ -1889,6 +2080,15 @@ dependencies = [ "semver", ] +[[package]] +name = "rusticata-macros" +version = "4.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "faf0c4a6ece9950b9abdb62b1cfcf2a68b3b67a10ba445b3bb85be2a293d0632" +dependencies = [ + "nom 7.1.3", +] + [[package]] name = "rustix" version = "0.38.44" @@ -1915,6 +2115,40 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "rustls" +version = "0.23.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" +dependencies = [ + "once_cell", + "ring", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-pki-types" +version = "1.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "102f35f7de7b06d8c61f1cff6592f5253e0dea431c74867aad5dfd70f44663fb" +dependencies = [ + "zeroize", +] + +[[package]] +name = "rustls-webpki" +version = "0.103.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3a0760a887c14823fca5a1c970b01d47c328c696c0c64829d1df50e8f853fd5" +dependencies = [ + "ring", + "rustls-pki-types", + "untrusted", +] + [[package]] name = "rustversion" version = "1.0.23" @@ -2186,6 +2420,12 @@ dependencies = [ "float-cmp", ] +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + [[package]] name = "svgtypes" version = "0.16.1" @@ -2218,6 +2458,17 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "synstructure" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "synstructure" version = "0.14.0" @@ -2238,16 +2489,22 @@ dependencies = [ "epaint_default_fonts", "jiff", "libc", + "rcgen", "resvg", + "ring", "roxmltree", + "rustls", + "rustls-pki-types", "serde", "serde_json", "shadcn-egui", "softbuffer", "toml", "wayland-client", + "wayland-protocols", "wayland-protocols-wlr", "winit", + "xkbcommon-dl", "yaml-rust2", ] @@ -2305,6 +2562,36 @@ dependencies = [ "zune-jpeg", ] +[[package]] +name = "time" +version = "0.3.55" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cdb87b95ec50ddfa440816d227a17b2ccbdda963a316a727fda0fc4334f7d134" +dependencies = [ + "deranged", + "num-conv", + "powerfmt", + "serde_core", + "time-core", + "time-macros", +] + +[[package]] +name = "time-core" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e1c906769ad99c88eaa54e728060edef082f8e358ff32030cb7c7d315e81109" + +[[package]] +name = "time-macros" +version = "0.2.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e689342a48d2ea927c87ea50cabf8594854bf940e9310208848d680d668ed85" +dependencies = [ + "num-conv", + "time-core", +] + [[package]] name = "tiny-skia" version = "0.12.0" @@ -2424,7 +2711,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b8765b90061cba6c22b5831f675da109ae5561588290f9fa2317adab2714d5a6" dependencies = [ "memchr", - "nom", + "nom 8.0.0", "petgraph", ] @@ -2452,6 +2739,12 @@ version = "1.13.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8" +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + [[package]] name = "url" version = "2.5.8" @@ -2538,6 +2831,12 @@ dependencies = [ "winapi-util", ] +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + [[package]] name = "wasip2" version = "1.0.4+wasi-0.2.12" @@ -2963,6 +3262,24 @@ version = "0.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ea6fc2961e4ef194dcbfe56bb845534d0dc8098940c7e5c012a258bfec6701bd" +[[package]] +name = "x509-parser" +version = "0.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d43b0f71ce057da06bc0851b23ee24f3f86190b07203dd8f567d0b706a185202" +dependencies = [ + "asn1-rs", + "data-encoding", + "der-parser", + "lazy_static", + "nom 7.1.3", + "oid-registry", + "ring", + "rusticata-macros", + "thiserror 2.0.21", + "time", +] + [[package]] name = "xcursor" version = "0.3.11" @@ -2998,6 +3315,16 @@ dependencies = [ "hashlink", ] +[[package]] +name = "yasna" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b5f6765e852b9b4dc8e2a76843e4d64d1cea8e79bcde0b6901aea8e7c7f08282" +dependencies = [ + "bit-vec", + "time", +] + [[package]] name = "yoke" version = "0.8.3" @@ -3018,7 +3345,7 @@ dependencies = [ "proc-macro2", "quote", "syn 3.0.6", - "synstructure", + "synstructure 0.14.0", ] [[package]] @@ -3059,9 +3386,15 @@ dependencies = [ "proc-macro2", "quote", "syn 3.0.6", - "synstructure", + "synstructure 0.14.0", ] +[[package]] +name = "zeroize" +version = "1.9.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85ccff8a4805aba1eaa4cd4afcd49f7557dd2cf5fd79ffc37f8959466effc5aa" + [[package]] name = "zerotrie" version = "0.2.5" diff --git a/src/thinfloe-menu/Cargo.toml b/src/thinfloe-menu/Cargo.toml index 6959b18..35918e0 100644 --- a/src/thinfloe-menu/Cargo.toml +++ b/src/thinfloe-menu/Cargo.toml @@ -15,13 +15,19 @@ softbuffer = { version = "0.4.8", default-features = false, features = ["wayland resvg = { version = "0.48.1", default-features = false } libc = "0.2.190" wayland-client = "0.31" +wayland-protocols = { version = "0.32", default-features = false, features = ["client", "unstable", "staging"] } wayland-protocols-wlr = { version = "0.3", default-features = false, features = ["client"] } +xkbcommon-dl = { version = "0.4.2", default-features = false } jiff = { version = "0.2.38", default-features = false, features = ["std", "tzdb-zoneinfo"] } serde_json = "1" yaml-rust2 = { version = "0.13", default-features = false } toml = "1.2.1" serde = { version = "1.0.229", features = ["derive"] } roxmltree = "0.21" +rustls = { version = "0.23.46", default-features = false, features = ["ring", "std", "tls12"] } +rcgen = { version = "0.14.10", default-features = false, features = ["ring", "pem"] } +ring = { version = "0.17.14", default-features = false } +rustls-pki-types = { version = "1.16.0", default-features = false } [profile.dev] debug = "line-tables-only" diff --git a/src/thinfloe-menu/src/app.rs b/src/thinfloe-menu/src/app.rs index 752195f..3511bdd 100644 --- a/src/thinfloe-menu/src/app.rs +++ b/src/thinfloe-menu/src/app.rs @@ -8,6 +8,7 @@ use crate::addons::{self, AddonLog}; use crate::battery; use crate::damage::Tracker; use crate::density::{self, OutputInfo}; +use crate::deskflowtab::DeskflowRequest; use crate::icons::IconRoots; use crate::jobs::{self, JobResult, Paths}; use crate::log::Feed; @@ -65,8 +66,16 @@ pub enum Wake { PublicIp, /// The status layout file changed. Status, + /// The Deskflow daemon ended. + Deskflow, + /// The Deskflow daemon's state file changed. + DeskflowState, } +/// Before the menu exits, how long the Deskflow daemon has after SIGTERM +/// (spec, Processes); SIGKILL follows. +const DESKFLOW_STOP_WAIT: Duration = Duration::from_secs(1); + /// How often the add-on files are looked at, while the window is visible. const ADDON_POLL: Duration = Duration::from_secs(1); /// Polls of the log in one wake-up: a log of 500 lines read at 200 a poll. @@ -176,6 +185,8 @@ pub struct App { /// last frame: what `sync_samplers` decides from. covered: bool, height: f32, + /// The Deskflow daemon, run while `[deskflow] listen` is on. + deskflow: crate::deskflow_sup::Supervisor, } /// Starts a sampler thread with its `on` flag and returns its shared copy. @@ -384,7 +395,18 @@ pub fn run(mut cfg: Config) -> Result { }), ) }; + // Spawned from this thread only (tick in about_to_wait): the daemon's + // PR_SET_PDEATHSIG follows the thread that forked it, and the event + // loop's thread lives as long as the menu. + let deskflow = { + let waker = event_loop.create_proxy(); + let program = std::env::current_exe().unwrap_or_else(|_| PathBuf::from("/usr/bin/thinfloe-menu")); + crate::deskflow_sup::Supervisor::new(program).with_notify(move || { + let _ = waker.send_event(Wake::Deskflow); + }) + }; let mut app = App { + deskflow, samplers, covered: false, height: ui::SHORT_SCREEN_H, @@ -407,7 +429,12 @@ pub fn run(mut cfg: Config) -> Result { // Before the first frame, so a sampler the layout needs has a reading // by the time the area shows. The first frame corrects the height. app.sync_samplers(); - event_loop.run_app(&mut app).map_err(|e| e.to_string())?; + app.deskflow_changed(); + let ran = event_loop.run_app(&mut app).map_err(|e| e.to_string()); + // Every way out, also an exit 0, 10 or 11 after its save: the daemon + // must not hold port 24800 into the next session. + app.deskflow.stop(DESKFLOW_STOP_WAIT); + ran?; app.exit .ok_or_else(|| "the event loop ended without an exit request".to_string()) } @@ -424,6 +451,9 @@ struct Watch { battery: battery::Watcher, /// A stamp watcher like the battery file's. status: battery::Watcher, + /// The Deskflow daemon's state file, looked at like the battery file. + deskflow_state: Option, + deskflow: battery::Watcher, } impl Watch { @@ -440,6 +470,8 @@ impl Watch { release: release::Watcher::default(), battery: battery::Watcher::default(), status: battery::Watcher::default(), + deskflow_state: crate::deskflow::statefile::path(), + deskflow: battery::Watcher::default(), } } @@ -458,6 +490,11 @@ impl Watch { if self.status.tick(&self.config_toml) { wakes.push(Wake::Status); } + if let Some(p) = self.deskflow_state.as_ref() + && self.deskflow.tick(p) + { + wakes.push(Wake::DeskflowState); + } wakes } } @@ -835,6 +872,15 @@ fn frame_wanted(covered: bool, frame_due: Option, now: Instant) -> bool !covered || frame_due.is_some_and(|due| due <= now) } +/// Wake the loop at `at` at the latest, keeping an earlier deadline. +fn wake_by(event_loop: &ActiveEventLoop, at: Instant) { + match event_loop.control_flow() { + ControlFlow::WaitUntil(t) if t <= at => {} + ControlFlow::Poll => {} + _ => event_loop.set_control_flow(ControlFlow::WaitUntil(at)), + } +} + fn wake_flow(at: Option) -> ControlFlow { at.map_or(ControlFlow::Wait, ControlFlow::WaitUntil) } @@ -920,6 +966,24 @@ impl App { ); } + /// `[deskflow]` was written (or the menu starts): a running daemon + /// reads its file again, and it runs as the switch says. Call after + /// each successful `store.update(Table::Deskflow, …)`. The reload comes + /// first: a daemon started now reads the new file anyway. + fn deskflow_changed(&mut self) { + let listen = self + .cfg + .paths + .config + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .cfg + .deskflow + .listen; + self.deskflow.reload(); + self.deskflow.want(listen, Instant::now()); + } + /// Read the status layout file again: the person or the menu changed it. fn refresh_status(&mut self) { reload_status( @@ -931,6 +995,12 @@ impl App { ); } + /// Read the Deskflow daemon's state file again. + fn refresh_deskflow_state(&mut self) { + self.cfg.menu.deskflow.state = crate::deskflow::statefile::path() + .map_or_else(crate::deskflowtab::no_state, |p| crate::deskflowtab::read_state(&p)); + } + /// Read the battery file again. fn refresh_battery(&mut self) { self.cfg @@ -1040,6 +1110,19 @@ impl App { let next = apply_screen(idle, &self.cfg.screen, &self.cfg.paths.config, &mut self.cfg.menu); self.apply(next, event_loop); } + Some(Effect::Deskflow(DeskflowRequest::Save(cfg))) => { + // The store writes generated/deskflow before config.toml, + // so the daemon reads the new table once it is signalled. + let (written, next) = apply_deskflow(cfg, &self.cfg.paths.config, &mut self.cfg.menu); + if written { + self.deskflow_changed(); + } + self.apply(next, event_loop); + } + Some(Effect::Deskflow(DeskflowRequest::Send(cmd))) => { + let error = send_deskflow(&cmd).err(); + self.cfg.menu.deskflow_sent(error); + } None => {} } } @@ -1072,6 +1155,9 @@ impl App { live.chrome.clock = crate::header::clock_text_in(wall, &zone); live.chrome.covered = covered; self.cfg.menu.set_clock(wall, zone); + // The Deskflow band says whether the daemon runs and why it stopped. + self.cfg.menu.deskflow.running = self.deskflow.pid().is_some(); + self.cfg.menu.deskflow.stopped = self.deskflow.last_failure(); // The sampler's latest copy, taken under its lock for as long as a // copy of 600 numbers takes. let (network, hardware) = self.samplers.copies(); @@ -1106,7 +1192,7 @@ impl App { if needs_backdrop(self.cfg.menu.dialog(), self.frozen, live.painted, settling) { let mut under = input.clone(); under.events.clear(); - let out = self.ctx.run_ui(under, |ui| { + let mut out = self.ctx.run_ui(under, |ui| { ui::show_screen(ui, &self.cfg.menu, &live.icons, &live.chrome, now); }); live.textures.apply_set(&out.textures_delta); @@ -1115,9 +1201,10 @@ impl App { live.canvas.restore_background(all); live.canvas.draw(&prims, &live.textures, out.pixels_per_point, all); live.textures.apply_free(&out.textures_delta); + out.textures_delta.clear(); live.painted = true; } - let out = self.ctx.run_ui(input, |ui| { + let mut out = self.ctx.run_ui(input, |ui| { event = ui::show(ui, &self.cfg.menu, &live.icons, &live.chrome, now); }); live.egui.handle_platform_output(&live.window, out.platform_output); @@ -1145,6 +1232,7 @@ impl App { // Nothing of this pass reaches the screen; the textures were // taken above, so the font atlas upload is not lost. live.textures.apply_free(&out.textures_delta); + out.textures_delta.clear(); live.window.request_redraw(); return; } @@ -1175,6 +1263,7 @@ impl App { } } live.textures.apply_free(&out.textures_delta); + out.textures_delta.clear(); // Honour egui's own repaint requests. Ignoring them leaves the first // screen in fallback fonts until the mouse moves, because the font @@ -1471,12 +1560,12 @@ impl ApplicationHandler for App { self.sync_menu_output(event_loop); let now = Instant::now(); if let Some(d) = self.menu_move.next_wake(now) { - let at = now + d; - match event_loop.control_flow() { - ControlFlow::WaitUntil(t) if t <= at => {} - ControlFlow::Poll => {} - _ => event_loop.set_control_flow(ControlFlow::WaitUntil(at)), - } + wake_by(event_loop, now + d); + } + // A daemon that ended wakes the loop (Wake::Deskflow); a start or a + // SIGKILL that is due sets a deadline. + if let Some(at) = self.deskflow.tick(now) { + wake_by(event_loop, at); } } @@ -1508,11 +1597,17 @@ impl ApplicationHandler for App { // The status changed with the job; the watcher would see it // only a second later. let addon = matches!(result, JobResult::Addon { .. }); + // A saved keyboard choice rewrote generated/deskflow when + // the volume key switch changed (mic_mute_local). + let keyboard = matches!(result, JobResult::KeyboardApplied { result: Ok(_), .. }); let effect = self.cfg.menu.finished(result, Instant::now()); self.apply(effect, event_loop); if addon { self.refresh_addons(); } + if keyboard { + self.deskflow.reload(); + } } Wake::Addons => self.refresh_addons(), Wake::Release => self.refresh_release(), @@ -1525,6 +1620,9 @@ impl ApplicationHandler for App { self.apply(effect, event_loop); } } + // about_to_wait reaps it and starts it again. + Wake::Deskflow => {} + Wake::DeskflowState => self.refresh_deskflow_state(), Wake::Output | Wake::Network | Wake::Hardware | Wake::PublicIp => {} } if let Some(live) = self.live.as_ref() { @@ -1618,6 +1716,34 @@ fn apply_screen(idle: u32, screen: &ScreenFile, store: &crate::store::Shared, me } } +/// Carry out `DeskflowRequest::Save`: keep `cfg` as the `[deskflow]` +/// table (the store renders `generated/deskflow` first) and report to the +/// menu. Whether it was written (the caller then tells the daemon), and +/// what the menu asks next. +fn apply_deskflow( + cfg: crate::config::DeskflowCfg, + store: &crate::store::Shared, + menu: &mut Menu, +) -> (bool, Option) { + let (result, stored) = { + let mut store = store.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let result = store.update(crate::generated::Table::Deskflow, |c| c.deskflow = cfg); + (result, store.cfg.deskflow.clone()) + }; + let written = result.is_ok(); + (written, menu.deskflow_written(stored, result.err())) +} + +/// Send `cmd` to the Deskflow daemon's socket. +fn send_deskflow(cmd: &crate::deskflow::cmd::Cmd) -> Result<(), String> { + use crate::deskflow::cmd::{self, SendError}; + let path = cmd::socket_path().ok_or("Deskflow: no runtime directory for its socket")?; + cmd::send(&path, cmd).map_err(|e| match e { + SendError::NoServer => "Deskflow does not run.".to_string(), + SendError::Io(e) => format!("Deskflow did not get the command: {e}"), + }) +} + /// Tell the idle helper to read the screen file again. fn signal_idle_helper(pid: i32) -> bool { // Never init, never a process group. @@ -1935,6 +2061,8 @@ esac"#; release: release::Watcher::default(), battery: battery::Watcher::default(), status: battery::Watcher::default(), + deskflow_state: None, + deskflow: battery::Watcher::default(), }; let is_release = |v: &[Wake]| v.iter().filter(|w| matches!(w, Wake::Release)).count(); // The first look reads both, whatever the files hold. @@ -2182,6 +2310,8 @@ esac"#; release: release::Watcher::default(), battery: battery::Watcher::default(), status: battery::Watcher::default(), + deskflow_state: None, + deskflow: battery::Watcher::default(), }; let is_status = |v: &[Wake]| v.iter().filter(|w| matches!(w, Wake::Status)).count(); // The first look reads it, also when there is none. @@ -2543,6 +2673,58 @@ esac"#; assert!(menu.log.lines().any(|l| l.plain() == crate::menu::NEXT_SESSION)); } + #[test] + fn a_deskflow_save_writes_the_generated_file_and_config_and_saves_the_home() { + let d = TestDir::new("app", "write-deskflow"); + let store = crate::store::test_shared(&d); + let mut menu = screen_menu(); + let mut cfg = crate::config::DeskflowCfg { + listen: true, + ..Default::default() + }; + cfg.devices.push(crate::config::DeviceCfg { + name: "laptop".into(), + fingerprint: format!("v2:sha256:{}", "a".repeat(64)), + output: "DP-1".into(), + side: crate::kanshi::Side::RightOf, + clipboard: true, + }); + let (written, next) = apply_deskflow(cfg.clone(), &store, &mut menu); + assert!(written); + assert_eq!(next, Some(Effect::Start(Job::Save))); + assert_eq!(menu.deskflow.cfg, cfg); + assert_eq!(menu.deskflow.error, None); + let generated = std::fs::read_to_string(d.join("generated/deskflow")).unwrap(); + assert_eq!(crate::deskflowcfg::parse(&generated).unwrap().deskflow, cfg); + let text = std::fs::read_to_string(d.join("config.toml")).unwrap(); + assert_eq!(crate::config::parse(&text).unwrap().deskflow, cfg); + } + + #[test] + fn a_deskflow_save_the_store_refuses_keeps_the_stored_table() { + let d = TestDir::new("app", "write-deskflow-bad"); + let store = crate::store::test_shared(&d); + let mut menu = screen_menu(); + let cfg = crate::config::DeskflowCfg { + port: 0, + ..Default::default() + }; + menu.deskflow.cfg = cfg.clone(); + let (written, next) = apply_deskflow(cfg, &store, &mut menu); + assert!(!written); + assert_eq!(next, None); + assert_eq!( + menu.deskflow.cfg, + crate::config::DeskflowCfg::default(), + "the tab shows what is kept" + ); + assert!( + menu.deskflow.error.as_deref().is_some_and(|e| e.contains("port")), + "{:?}", + menu.deskflow.error + ); + } + #[test] fn write_screen_on_a_store_that_refuses_is_the_error_in_the_tab() { let d = TestDir::new("app", "write-screen-ro"); diff --git a/src/thinfloe-menu/src/brand.rs b/src/thinfloe-menu/src/brand.rs index 7d06920..b3fd6cb 100644 --- a/src/thinfloe-menu/src/brand.rs +++ b/src/thinfloe-menu/src/brand.rs @@ -431,6 +431,8 @@ mod tests { ("upgrade_ui.rs", include_str!("upgrade_ui.rs")), ("network_ui.rs", include_str!("network_ui.rs")), ("monitors_ui.rs", include_str!("monitors_ui.rs")), + ("deskflow_ui.rs", include_str!("deskflow_ui.rs")), + ("deskflowtab.rs", include_str!("deskflowtab.rs")), ("keyboardtab_ui.rs", include_str!("keyboardtab_ui.rs")), ("machine.rs", include_str!("machine.rs")), ("machine_ui.rs", include_str!("machine_ui.rs")), diff --git a/src/thinfloe-menu/src/config.rs b/src/thinfloe-menu/src/config.rs index 1ba7c61..2c1fd62 100644 --- a/src/thinfloe-menu/src/config.rs +++ b/src/thinfloe-menu/src/config.rs @@ -107,6 +107,7 @@ pub struct ThinfloeConfig { pub monitors: MonitorsCfg, pub network: NetworkCfg, pub time: TimeCfg, + pub deskflow: DeskflowCfg, pub notice: NoticeCfg, } @@ -120,6 +121,7 @@ impl Default for ThinfloeConfig { monitors: MonitorsCfg::default(), network: NetworkCfg::default(), time: TimeCfg::default(), + deskflow: DeskflowCfg::default(), notice: NoticeCfg::default(), } } @@ -446,6 +448,49 @@ pub struct TimeCfg { pub ntp: Vec, } +// ---- deskflow ---- + +/// Other computers that use this keyboard and mouse; see `deskflowcfg`. +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)] +#[serde(default)] +pub struct DeskflowCfg { + /// The switch. + pub listen: bool, + pub port: u16, + pub edge_resistance: crate::deskflowcfg::Resistance, + /// The paired computers, `[[deskflow.device]]`. + #[serde(rename = "device", skip_serializing_if = "Vec::is_empty")] + pub devices: Vec, +} + +impl Default for DeskflowCfg { + fn default() -> Self { + DeskflowCfg { + listen: false, + port: crate::deskflowcfg::DEFAULT_PORT, + edge_resistance: crate::deskflowcfg::Resistance::default(), + devices: Vec::new(), + } + } +} + +/// A paired computer and the edge of a monitor it sits at. +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)] +pub struct DeviceCfg { + pub name: String, + /// `v2:sha256:` and 64 hex digits. + pub fingerprint: String, + /// The monitor, by its criteria string as in `[monitors]`. + pub output: String, + pub side: Side, + #[serde(default = "default_true")] + pub clipboard: bool, +} + +fn default_true() -> bool { + true +} + // ---- network ---- #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, Default)] diff --git a/src/thinfloe-menu/src/convert.rs b/src/thinfloe-menu/src/convert.rs index 0d94ce8..431c7ac 100644 --- a/src/thinfloe-menu/src/convert.rs +++ b/src/thinfloe-menu/src/convert.rs @@ -345,7 +345,8 @@ pub fn from_generated(dir: &Path) -> Result, String> { let wifi = read_generated(dir, "wifi.yaml")?; let wired = read_generated(dir, "ethernet.yaml")?; let time = read_generated(dir, "time")?; - if [&env, &screen, &kanshi_text, &wifi, &wired, &time] + let deskflow = read_generated(dir, "deskflow")?; + if [&env, &screen, &kanshi_text, &wifi, &wired, &time, &deskflow] .iter() .all(|f| f.is_none()) { @@ -370,6 +371,10 @@ pub fn from_generated(dir: &Path) -> Result, String> { if let Some(t) = &time { cfg.time = crate::timecfg::from_body(strip_header(t)); } + // A broken file is an error, not defaults: the pairings stay on disk. + if let Some(t) = &deskflow { + cfg.deskflow = crate::deskflowcfg::parse(t)?.deskflow; + } Ok(Some(cfg)) } @@ -729,6 +734,14 @@ mod tests { zone: Some("Europe/Zurich".into()), ntp: vec!["ntp.example.ch".into(), "10.0.0.1".into()], }; + c.deskflow.listen = true; + c.deskflow.devices = vec![crate::config::DeviceCfg { + name: "laptop".into(), + fingerprint: format!("v2:sha256:{}", "ab".repeat(32)), + output: "eDP-1".into(), + side: crate::kanshi::Side::LeftOf, + clipboard: false, + }]; c } @@ -736,7 +749,15 @@ mod tests { fn from_generated_reads_back_what_render_wrote() { let d = TestDir::new("convert", "roundtrip"); let cfg = sample(); - for name in ["environment", "screen", "kanshi", "wifi.yaml", "ethernet.yaml", "time"] { + for name in [ + "environment", + "screen", + "kanshi", + "wifi.yaml", + "ethernet.yaml", + "time", + "deskflow", + ] { let body = generated::render(&cfg, name, &inp()).unwrap(); generated::write_if_changed(&d, name, body.as_deref()).unwrap(); } diff --git a/src/thinfloe-menu/src/deskflow/capture.rs b/src/thinfloe-menu/src/deskflow/capture.rs new file mode 100644 index 0000000..ae41a10 --- /dev/null +++ b/src/thinfloe-menu/src/deskflow/capture.rs @@ -0,0 +1,1127 @@ +//! The Wayland side of the Deskflow server: one edge strip per attached +//! device, the pointer lock and the keyboard focus while a device has +//! them, and every input event in between (spec, Edge capture). +//! +//! A strip is a layer-shell surface on the overlay layer of its output, +//! anchored to one edge, 1 px deep, with exclusive zone 0, keyboard +//! interactivity none while idle, a transparent buffer and the whole strip +//! as its input region: the pointer enters it at the edge, and no key +//! reaches it until a capture begins. +//! +//! A capture first asks for a oneshot pointer lock on the strip and only +//! then sets keyboard interactivity exclusive: labwc 0.9.3 activates a lock +//! only for the active view (`create_constraint`) or when the keyboard +//! focus moves (`seat_focus`), so the lock must exist before the focus +//! moves to the strip. Until the compositor reports `Locked`, the capture +//! passes on no input event. Everything a capture holds is a Wayland object +//! of this connection, so a crash of the process gives pointer and keyboard +//! back. +//! +//! The relative pointer lives as long as the `wl_pointer` does, so motion +//! on a strip is reported before a capture too (edge resistance); the +//! compositor sends it only while the pointer is on one of our surfaces. + +use std::collections::BTreeMap; +use std::ffi::CString; +use std::fs::File; +use std::io::Write; +use std::os::fd::{AsFd, BorrowedFd, FromRawFd, OwnedFd}; + +use wayland_client::backend::{Backend, WaylandError}; +use wayland_client::globals::{GlobalListContents, registry_queue_init}; +use wayland_client::protocol::{ + wl_buffer, wl_compositor, wl_keyboard, wl_output, wl_pointer, wl_region, wl_registry, wl_seat, wl_shm, wl_shm_pool, + wl_surface, +}; +use wayland_client::{Connection, Dispatch, EventQueue, Proxy, QueueHandle, WEnum}; +use wayland_protocols::wp::keyboard_shortcuts_inhibit::zv1::client::{ + zwp_keyboard_shortcuts_inhibit_manager_v1, zwp_keyboard_shortcuts_inhibitor_v1, +}; +use wayland_protocols::wp::pointer_constraints::zv1::client::{zwp_locked_pointer_v1, zwp_pointer_constraints_v1}; +use wayland_protocols::wp::relative_pointer::zv1::client::{zwp_relative_pointer_manager_v1, zwp_relative_pointer_v1}; +use wayland_protocols::xdg::xdg_output::zv1::client::{zxdg_output_manager_v1, zxdg_output_v1}; +use wayland_protocols_wlr::layer_shell::v1::client::{zwlr_layer_shell_v1, zwlr_layer_surface_v1}; + +use super::edge::Rect; + +/// One output in the compositor's logical layout: position and size from +/// `zxdg_output_v1` (logical, so scale and rotation are applied), name and +/// description from `wl_output` v4. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct OutputGeom { + pub name: String, + /// wlroots makes it " ()". + pub description: String, + pub x: i32, + pub y: i32, + pub w: i32, + pub h: i32, +} + +impl OutputGeom { + /// Whether this is the monitor a `[monitors]` criteria string names: + /// the output name, or " " (`kanshi::criteria`), + /// which starts the description. + pub fn matches(&self, criteria: &str) -> bool { + self.name == criteria + || self + .description + .strip_prefix(criteria) + .is_some_and(|rest| rest.starts_with(" (")) + } +} + +/// A strip to show: `rect` in the layout coordinates of `OutputGeom`, +/// along one edge of `output`. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct StripSpec { + pub id: u32, + pub output: String, + pub rect: Rect, +} + +/// What the compositor reported, in order. `Enter` is in layout +/// coordinates; key codes are evdev codes, as `wl_keyboard` sends them. +#[derive(Debug)] +pub enum CapEvent { + Enter { + strip: u32, + x: f64, + y: f64, + }, + Leave { + strip: u32, + }, + /// The pointer moved on a strip, in layout coordinates. + Motion { + x: f64, + y: f64, + }, + /// Relative motion: `dx`, `dy` with the pointer acceleration, the + /// `_unaccel` pair without. + Relative { + dx: f64, + dy: f64, + dx_unaccel: f64, + dy_unaccel: f64, + }, + Locked, + /// The capture is over: the compositor cancelled the lock, it could + /// not be made, or `end_capture` destroyed it (the compositor reports + /// nothing for a lock the client destroys). + Unlocked, + Key { + code: u32, + pressed: bool, + }, + Modifiers { + depressed: u32, + latched: u32, + locked: u32, + group: u32, + }, + Keymap { + fd: OwnedFd, + size: u32, + }, + RepeatInfo { + rate: i32, + delay: i32, + }, + Button { + button: u32, + pressed: bool, + }, + /// One pointer frame's wheel motion in 1/120 steps. + Axis { + v120_x: i32, + v120_y: i32, + }, + KeyboardLeft, + OutputsChanged, +} + +impl CapEvent { + /// Input that a capture passes on only once the lock is active. + fn is_input(&self) -> bool { + matches!( + self, + CapEvent::Relative { .. } | CapEvent::Key { .. } | CapEvent::Button { .. } | CapEvent::Axis { .. } + ) + } +} + +/// Whether an event reaches the caller: while a capture waits for its lock +/// (`captured` and not `locked`), no input does, so nothing typed or +/// clicked before the lock reaches a device, and a key pressed then is +/// never released on it either. +pub fn passes(captured: bool, locked: bool, ev: &CapEvent) -> bool { + !(ev.is_input() && captured && !locked) +} + +type Margins = (i32, i32, i32, i32); + +/// Where a layer surface for `rect` sits on `out`: anchor, margins (top, +/// right, bottom, left) and size. A strip taller than wide is on the left +/// or right edge, else on the top or bottom one; it is on the far edge +/// when it starts past the output's middle. +fn placement(out: &OutputGeom, rect: &Rect) -> (zwlr_layer_surface_v1::Anchor, Margins, (u32, u32)) { + use zwlr_layer_surface_v1::Anchor; + let size = (rect.w.max(1) as u32, rect.h.max(1) as u32); + if rect.h > rect.w { + let side = if rect.x - out.x >= out.w / 2 { + Anchor::Right + } else { + Anchor::Left + }; + (side | Anchor::Top, (rect.y - out.y, 0, 0, 0), size) + } else { + let side = if rect.y - out.y >= out.h / 2 { + Anchor::Bottom + } else { + Anchor::Top + }; + (side | Anchor::Left, (0, 0, 0, rect.x - out.x), size) + } +} + +struct Output { + wl: wl_output::WlOutput, + xdg: zxdg_output_v1::ZxdgOutputV1, + name: Option, + description: String, + pos: Option<(i32, i32)>, + size: Option<(i32, i32)>, +} + +impl Output { + fn geom(&self) -> Option { + let ((x, y), (w, h)) = (self.pos?, self.size?); + Some(OutputGeom { + name: self.name.clone()?, + description: self.description.clone(), + x, + y, + w, + h, + }) + } +} + +struct Strip { + spec: StripSpec, + surface: wl_surface::WlSurface, + layer: zwlr_layer_surface_v1::ZwlrLayerSurfaceV1, + size: (u32, u32), +} + +impl Strip { + fn destroy(self) { + self.layer.destroy(); + self.surface.destroy(); + } +} + +/// The wheel motion of the current pointer frame. +#[derive(Default)] +struct Wheel { + v120: (i32, i32), + /// `axis_discrete` steps, all a seat before version 8 sends. + discrete: (i32, i32), + /// Continuous scrolling (touchpads, virtual pointers) in surface + /// pixels, when the frame has neither of the above. + continuous: (f64, f64), +} + +/// Continuous scrolling per wheel step: libinput's 15 px. +const PX_PER_STEP: f64 = 15.0; + +/// A strip the compositor closed is made again this long after, so a +/// compositor that keeps closing it does not keep the loop busy. +const RECREATE_AFTER: std::time::Duration = std::time::Duration::from_secs(1); + +/// A strip closed at `closed_at` counts as missing by `now`. +fn recreate_due(closed_at: Option, now: std::time::Instant) -> bool { + closed_at.is_some_and(|t| now.saturating_duration_since(t) >= RECREATE_AFTER) +} + +impl Wheel { + /// The frame's motion in 1/120 steps. + fn v120(&self) -> (i32, i32) { + if self.v120 != (0, 0) { + return self.v120; + } + if self.discrete != (0, 0) { + return (self.discrete.0.saturating_mul(120), self.discrete.1.saturating_mul(120)); + } + // `as` saturates and maps NaN to 0. + let step = |px: f64| (px * 120.0 / PX_PER_STEP).round() as i32; + (step(self.continuous.0), step(self.continuous.1)) + } +} + +struct State { + compositor: wl_compositor::WlCompositor, + shm: wl_shm::WlShm, + layer_shell: zwlr_layer_shell_v1::ZwlrLayerShellV1, + xdg_outputs: zxdg_output_manager_v1::ZxdgOutputManagerV1, + constraints: zwp_pointer_constraints_v1::ZwpPointerConstraintsV1, + relative_mgr: zwp_relative_pointer_manager_v1::ZwpRelativePointerManagerV1, + /// None on a compositor without it: the capture works, but the + /// compositor's media keys still run while it is on. + inhibit_mgr: Option, + seat: wl_seat::WlSeat, + pointer: Option, + relative: Option, + keyboard: Option, + /// By the output's global name. + outputs: BTreeMap, + strips: Vec, + /// The strip under the pointer. + hover: Option, + /// The strip being captured, its lock, and whether the lock is active. + captured: Option, + lock: Option, + locked: bool, + /// The captured strip's shortcuts inhibitor: ThinFloe's labwc runs no + /// keybinding, not even a media key, while the strip has the keyboard + /// (patch 0007), so every key goes to the device. + inhibitor: Option, + wheel: Wheel, + events: Vec, + outputs_changed: bool, + /// When the compositor last closed a strip, until it is made again. + closed_at: Option, +} + +pub struct Capture { + conn: Connection, + backend: Backend, + queue: EventQueue, + state: State, +} + +impl Capture { + pub fn connect() -> Result { + let conn = Connection::connect_to_env().map_err(|e| format!("no Wayland connection: {e}"))?; + let (globals, mut queue): (_, EventQueue) = + registry_queue_init(&conn).map_err(|e| format!("Wayland registry: {e}"))?; + let qh = queue.handle(); + let err = |what: &'static str| move |e| format!("{what}: {e}"); + let mut state = State { + compositor: globals.bind(&qh, 4..=4, ()).map_err(err("wl_compositor v4"))?, + shm: globals.bind(&qh, 1..=1, ()).map_err(err("wl_shm"))?, + layer_shell: globals.bind(&qh, 1..=4, ()).map_err(err("zwlr_layer_shell_v1"))?, + xdg_outputs: globals.bind(&qh, 2..=3, ()).map_err(err("zxdg_output_manager_v1 v2"))?, + constraints: globals + .bind(&qh, 1..=1, ()) + .map_err(err("zwp_pointer_constraints_v1"))?, + relative_mgr: globals + .bind(&qh, 1..=1, ()) + .map_err(err("zwp_relative_pointer_manager_v1"))?, + inhibit_mgr: globals.bind(&qh, 1..=1, ()).ok(), + seat: globals.bind(&qh, 5..=8, ()).map_err(err("wl_seat v5"))?, + pointer: None, + relative: None, + keyboard: None, + outputs: BTreeMap::new(), + strips: Vec::new(), + hover: None, + captured: None, + lock: None, + locked: false, + inhibitor: None, + wheel: Wheel::default(), + events: Vec::new(), + outputs_changed: false, + closed_at: None, + }; + if state.inhibit_mgr.is_none() { + eprintln!( + "thinfloe-menu --deskflow: no zwp_keyboard_shortcuts_inhibit_manager_v1: the compositor's keys still act while a device has the keyboard" + ); + } + for g in globals.contents().clone_list() { + if g.interface == "wl_output" { + state.bind_output(globals.registry(), g.name, g.version, &qh); + } + } + // The outputs' names and logical geometry, the seat's capabilities. + queue + .roundtrip(&mut state) + .map_err(|e| format!("Wayland roundtrip: {e}"))?; + state.outputs_changed = false; + let backend = conn.backend(); + Ok(Capture { + conn, + backend, + queue, + state, + }) + } + + /// The connection's file descriptor, to poll for readable events. + pub fn fd(&self) -> BorrowedFd<'_> { + self.backend.poll_fd() + } + + /// Reads what the compositor sent, without blocking, and returns what + /// happened since the last call. + pub fn dispatch(&mut self) -> Result, String> { + self.flush()?; + self.queue + .dispatch_pending(&mut self.state) + .map_err(|e| format!("Wayland dispatch: {e}"))?; + if let Some(guard) = self.queue.prepare_read() { + match guard.read() { + Ok(_) => {} + Err(WaylandError::Io(e)) if e.kind() == std::io::ErrorKind::WouldBlock => {} + Err(e) => return Err(format!("Wayland read: {e}")), + } + } + self.queue + .dispatch_pending(&mut self.state) + .map_err(|e| format!("Wayland dispatch: {e}"))?; + if std::mem::take(&mut self.state.outputs_changed) { + self.state.events.push(CapEvent::OutputsChanged); + } + Ok(std::mem::take(&mut self.state.events)) + } + + pub fn flush(&mut self) -> Result<(), String> { + match self.conn.flush() { + Ok(()) => Ok(()), + Err(WaylandError::Io(e)) if e.kind() == std::io::ErrorKind::WouldBlock => Ok(()), + Err(e) => Err(format!("Wayland flush: {e}")), + } + } + + /// The outputs whose name and logical geometry are known. + pub fn outputs(&self) -> Vec { + self.state.outputs.values().filter_map(Output::geom).collect() + } + + /// Show exactly these strips: a strip whose spec is unchanged stays, one + /// that changed is made again, one not listed goes (and ends a capture + /// on it). A strip on an output that is not known is left out. + pub fn set_strips(&mut self, strips: &[StripSpec]) { + let qh = self.queue.handle(); + let (keep, gone): (Vec, Vec) = std::mem::take(&mut self.state.strips) + .into_iter() + .partition(|s| strips.contains(&s.spec)); + self.state.strips = keep; + for s in gone { + self.state.remove_strip(s); + } + for spec in strips { + if self.state.strips.iter().any(|s| s.spec.id == spec.id) { + continue; + } + if let Some(strip) = self.state.make_strip(spec, &qh) { + self.state.strips.push(strip); + } + } + } + + /// True once, when a strip the compositor closed is due to be made + /// again: the caller passes its strips to `set_strips` then, although + /// they did not change. + pub fn take_closed(&mut self, now: std::time::Instant) -> bool { + if recreate_due(self.state.closed_at, now) { + self.state.closed_at = None; + return true; + } + false + } + + /// Take pointer and keyboard on `strip`: the lock first, then the + /// exclusive keyboard focus. A capture that cannot start (no such + /// strip, no pointer) reports `Unlocked` at once. + pub fn begin_capture(&mut self, strip: u32) { + let s = &mut self.state; + if s.captured.is_some() { + return; + } + let (Some(st), Some(pointer)) = (s.strips.iter().find(|x| x.spec.id == strip), s.pointer.as_ref()) else { + s.events.push(CapEvent::Unlocked); + return; + }; + let qh = self.queue.handle(); + s.lock = Some(s.constraints.lock_pointer( + &st.surface, + pointer, + None, + zwp_pointer_constraints_v1::Lifetime::Oneshot, + &qh, + (), + )); + st.layer + .set_keyboard_interactivity(zwlr_layer_surface_v1::KeyboardInteractivity::Exclusive); + s.inhibitor = s + .inhibit_mgr + .as_ref() + .map(|m| m.inhibit_shortcuts(&st.surface, &s.seat, &qh, ())); + st.surface.commit(); + s.captured = Some(strip); + s.locked = false; + } + + /// Give pointer and keyboard back: the lock goes and the strip takes + /// no keys again. Reports `Unlocked` when a capture was on, and then + /// returns true. + pub fn end_capture(&mut self) -> bool { + self.state.end_capture() + } +} + +impl State { + fn end_capture(&mut self) -> bool { + let Some(id) = self.captured.take() else { + return false; + }; + if let Some(lock) = self.lock.take() { + lock.destroy(); + } + if let Some(inhibitor) = self.inhibitor.take() { + inhibitor.destroy(); + } + self.locked = false; + if let Some(st) = self.strips.iter().find(|x| x.spec.id == id) { + st.layer + .set_keyboard_interactivity(zwlr_layer_surface_v1::KeyboardInteractivity::None); + st.surface.commit(); + } + self.events.push(CapEvent::Unlocked); + true + } + + /// An event for the caller; input during a capture waits for the lock. + fn push(&mut self, e: CapEvent) { + if passes(self.captured.is_some(), self.locked, &e) { + self.events.push(e); + } + } + + fn strip_of(&self, surface: &wl_surface::WlSurface) -> Option<&Strip> { + self.strips.iter().find(|s| s.surface == *surface) + } + + fn remove_strip(&mut self, s: Strip) { + if self.captured == Some(s.spec.id) { + self.end_capture(); + } + if self.hover == Some(s.spec.id) { + self.hover = None; + } + s.destroy(); + } + + fn make_strip(&mut self, spec: &StripSpec, qh: &QueueHandle) -> Option { + let out = self + .outputs + .values() + .find(|o| o.name.as_deref() == Some(&spec.output))?; + let (anchor, (top, right, bottom, left), size) = placement(&out.geom()?, &spec.rect); + let surface = self.compositor.create_surface(qh, ()); + let layer = self.layer_shell.get_layer_surface( + &surface, + Some(&out.wl), + zwlr_layer_shell_v1::Layer::Overlay, + "thinfloe-deskflow".into(), + qh, + spec.id, + ); + layer.set_size(size.0, size.1); + layer.set_anchor(anchor); + layer.set_margin(top, right, bottom, left); + layer.set_exclusive_zone(0); + layer.set_keyboard_interactivity(zwlr_layer_surface_v1::KeyboardInteractivity::None); + let region = self.compositor.create_region(qh, ()); + region.add(0, 0, size.0 as i32, size.1 as i32); + surface.set_input_region(Some(®ion)); + region.destroy(); + surface.commit(); + Some(Strip { + spec: spec.clone(), + surface, + layer, + size, + }) + } + + /// A fully transparent ARGB buffer of the strip's size. + fn attach_clear(&self, strip: &Strip, qh: &QueueHandle) -> Result<(), String> { + let (w, h) = (strip.size.0 as i32, strip.size.1 as i32); + let file = clear_file(w as usize * h as usize * 4)?; + let pool = self.shm.create_pool(file.as_fd(), w * h * 4, qh, ()); + let buffer = pool.create_buffer(0, w, h, w * 4, wl_shm::Format::Argb8888, qh, BufferFile { _file: file }); + pool.destroy(); + strip.surface.attach(Some(&buffer), 0, 0); + strip.surface.damage_buffer(0, 0, w, h); + strip.surface.commit(); + Ok(()) + } + + fn bind_output(&mut self, registry: &wl_registry::WlRegistry, id: u32, version: u32, qh: &QueueHandle) { + // Only v4 sends the name strips are placed by. + if version < 4 { + return; + } + let wl: wl_output::WlOutput = registry.bind(id, 4, qh, id); + let xdg = self.xdg_outputs.get_xdg_output(&wl, qh, id); + self.outputs.insert( + id, + Output { + wl, + xdg, + name: None, + description: String::new(), + pos: None, + size: None, + }, + ); + self.outputs_changed = true; + } + + fn drop_output(&mut self, id: u32) { + let Some(out) = self.outputs.remove(&id) else { + return; + }; + out.xdg.destroy(); + out.wl.release(); + let (gone, keep): (Vec, Vec) = std::mem::take(&mut self.strips) + .into_iter() + .partition(|s| out.name.as_ref() == Some(&s.spec.output)); + self.strips = keep; + for s in gone { + self.remove_strip(s); + } + self.outputs_changed = true; + } + + fn capabilities(&mut self, caps: wl_seat::Capability, qh: &QueueHandle) { + let has_pointer = caps.contains(wl_seat::Capability::Pointer); + if has_pointer && self.pointer.is_none() { + let p = self.seat.get_pointer(qh, ()); + self.relative = Some(self.relative_mgr.get_relative_pointer(&p, qh, ())); + self.pointer = Some(p); + } else if !has_pointer && let Some(p) = self.pointer.take() { + if let Some(r) = self.relative.take() { + r.destroy(); + } + p.release(); + } + let has_keyboard = caps.contains(wl_seat::Capability::Keyboard); + if has_keyboard && self.keyboard.is_none() { + self.keyboard = Some(self.seat.get_keyboard(qh, ())); + } else if !has_keyboard && let Some(k) = self.keyboard.take() { + k.release(); + } + } +} + +/// A memfd of `len` zero bytes: transparent ARGB8888. +fn clear_file(len: usize) -> Result { + let name = CString::new("thinfloe-deskflow").expect("no NUL"); + // SAFETY: a valid C string; the returned descriptor is checked and + // owned by the File from here on. + let fd = unsafe { libc::memfd_create(name.as_ptr(), libc::MFD_CLOEXEC) }; + if fd < 0 { + return Err(format!("memfd_create: {}", std::io::Error::last_os_error())); + } + // SAFETY: fd is a fresh descriptor nothing else owns. + let mut file = unsafe { File::from_raw_fd(fd) }; + file.write_all(&vec![0u8; len]) + .map_err(|e| format!("memfd write: {e}"))?; + Ok(file) +} + +/// The memfd behind a buffer, closed with the buffer. +struct BufferFile { + _file: File, +} + +impl Dispatch for State { + fn event( + state: &mut Self, + registry: &wl_registry::WlRegistry, + event: wl_registry::Event, + _: &GlobalListContents, + _: &Connection, + qh: &QueueHandle, + ) { + match event { + wl_registry::Event::Global { + name, + interface, + version, + } if interface == "wl_output" => state.bind_output(registry, name, version, qh), + wl_registry::Event::GlobalRemove { name } => state.drop_output(name), + _ => {} + } + } +} + +impl Dispatch for State { + fn event( + state: &mut Self, + _: &wl_output::WlOutput, + event: wl_output::Event, + id: &u32, + _: &Connection, + _: &QueueHandle, + ) { + let Some(out) = state.outputs.get_mut(id) else { + return; + }; + match event { + wl_output::Event::Name { name } => out.name = Some(name), + wl_output::Event::Description { description } => out.description = description, + _ => return, + } + state.outputs_changed = true; + } +} + +impl Dispatch for State { + fn event( + state: &mut Self, + _: &zxdg_output_v1::ZxdgOutputV1, + event: zxdg_output_v1::Event, + id: &u32, + _: &Connection, + _: &QueueHandle, + ) { + let Some(out) = state.outputs.get_mut(id) else { + return; + }; + match event { + zxdg_output_v1::Event::LogicalPosition { x, y } if out.pos != Some((x, y)) => { + out.pos = Some((x, y)); + state.outputs_changed = true; + } + zxdg_output_v1::Event::LogicalSize { width, height } if out.size != Some((width, height)) => { + out.size = Some((width, height)); + state.outputs_changed = true; + } + _ => {} + } + } +} + +impl Dispatch for State { + fn event( + state: &mut Self, + layer: &zwlr_layer_surface_v1::ZwlrLayerSurfaceV1, + event: zwlr_layer_surface_v1::Event, + id: &u32, + _: &Connection, + qh: &QueueHandle, + ) { + // An event for a strip already replaced or dropped. + let Some(pos) = state.strips.iter().position(|s| s.layer == *layer) else { + return; + }; + match event { + zwlr_layer_surface_v1::Event::Configure { serial, .. } => { + layer.ack_configure(serial); + // The strip's size is ours; each configure gets a fresh buffer. + if let Err(e) = state.attach_clear(&state.strips[pos], qh) { + eprintln!("thinfloe-menu --deskflow: strip {id}: {e}"); + } + } + // Gone without being asked: `set_strips` makes it again once + // `take_closed` says so. + zwlr_layer_surface_v1::Event::Closed => { + let s = state.strips.remove(pos); + state.remove_strip(s); + state.closed_at.get_or_insert_with(std::time::Instant::now); + } + _ => {} + } + } +} + +impl Dispatch for State { + fn event( + state: &mut Self, + _: &wl_seat::WlSeat, + event: wl_seat::Event, + _: &(), + _: &Connection, + qh: &QueueHandle, + ) { + if let wl_seat::Event::Capabilities { + capabilities: WEnum::Value(caps), + } = event + { + state.capabilities(caps, qh); + } + } +} + +impl Dispatch for State { + fn event( + state: &mut Self, + _: &wl_pointer::WlPointer, + event: wl_pointer::Event, + _: &(), + _: &Connection, + _: &QueueHandle, + ) { + use wl_pointer::{Axis, ButtonState, Event}; + match event { + Event::Enter { + surface, + surface_x, + surface_y, + .. + } => { + if let Some(s) = state.strip_of(&surface) { + let (strip, r) = (s.spec.id, s.spec.rect); + let (x, y) = (f64::from(r.x) + surface_x, f64::from(r.y) + surface_y); + state.hover = Some(strip); + state.push(CapEvent::Enter { strip, x, y }); + } + } + Event::Leave { surface, .. } => { + if let Some(s) = state.strip_of(&surface) { + let strip = s.spec.id; + if state.hover == Some(strip) { + state.hover = None; + } + state.push(CapEvent::Leave { strip }); + } + } + Event::Motion { + surface_x, surface_y, .. + } => { + let at = state.hover.and_then(|h| state.strips.iter().find(|s| s.spec.id == h)); + if let Some(r) = at.map(|s| s.spec.rect) { + let (x, y) = (f64::from(r.x) + surface_x, f64::from(r.y) + surface_y); + state.push(CapEvent::Motion { x, y }); + } + } + Event::Button { button, state: b, .. } => { + let pressed = matches!(b, WEnum::Value(ButtonState::Pressed)); + state.push(CapEvent::Button { button, pressed }); + } + Event::AxisValue120 { axis, value120 } => match axis { + WEnum::Value(Axis::HorizontalScroll) => state.wheel.v120.0 += value120, + WEnum::Value(Axis::VerticalScroll) => state.wheel.v120.1 += value120, + _ => {} + }, + Event::Axis { axis, value, .. } => match axis { + WEnum::Value(Axis::HorizontalScroll) => state.wheel.continuous.0 += value, + WEnum::Value(Axis::VerticalScroll) => state.wheel.continuous.1 += value, + _ => {} + }, + Event::AxisDiscrete { axis, discrete } => match axis { + WEnum::Value(Axis::HorizontalScroll) => state.wheel.discrete.0 += discrete, + WEnum::Value(Axis::VerticalScroll) => state.wheel.discrete.1 += discrete, + _ => {} + }, + Event::Frame => { + let (x, y) = std::mem::take(&mut state.wheel).v120(); + if (x, y) != (0, 0) { + state.push(CapEvent::Axis { v120_x: x, v120_y: y }); + } + } + _ => {} + } + } +} + +impl Dispatch for State { + fn event( + state: &mut Self, + _: &zwp_relative_pointer_v1::ZwpRelativePointerV1, + event: zwp_relative_pointer_v1::Event, + _: &(), + _: &Connection, + _: &QueueHandle, + ) { + if let zwp_relative_pointer_v1::Event::RelativeMotion { + dx, + dy, + dx_unaccel, + dy_unaccel, + .. + } = event + { + state.push(CapEvent::Relative { + dx, + dy, + dx_unaccel, + dy_unaccel, + }); + } + } +} + +impl Dispatch for State { + fn event( + state: &mut Self, + lock: &zwp_locked_pointer_v1::ZwpLockedPointerV1, + event: zwp_locked_pointer_v1::Event, + _: &(), + _: &Connection, + _: &QueueHandle, + ) { + if state.lock.as_ref() != Some(lock) { + return; + } + match event { + zwp_locked_pointer_v1::Event::Locked => { + state.locked = true; + state.events.push(CapEvent::Locked); + } + // A oneshot lock is dead once it is deactivated. + zwp_locked_pointer_v1::Event::Unlocked => { + state.end_capture(); + } + _ => {} + } + } +} + +impl Dispatch for State { + fn event( + state: &mut Self, + _: &wl_keyboard::WlKeyboard, + event: wl_keyboard::Event, + _: &(), + _: &Connection, + _: &QueueHandle, + ) { + use wl_keyboard::{Event, KeyState, KeymapFormat}; + match event { + Event::Keymap { + format: WEnum::Value(KeymapFormat::XkbV1), + fd, + size, + } => state.events.push(CapEvent::Keymap { fd, size }), + // The keys held when the focus arrives are not passed on. + Event::Enter { .. } => {} + Event::Leave { .. } => state.events.push(CapEvent::KeyboardLeft), + Event::Key { key, state: k, .. } => { + let pressed = match k { + WEnum::Value(KeyState::Pressed) => true, + WEnum::Value(KeyState::Released) => false, + // A compositor-side repeat (wl_seat v10): not bound here. + _ => return, + }; + state.push(CapEvent::Key { code: key, pressed }); + } + Event::Modifiers { + mods_depressed, + mods_latched, + mods_locked, + group, + .. + } => state.events.push(CapEvent::Modifiers { + depressed: mods_depressed, + latched: mods_latched, + locked: mods_locked, + group, + }), + Event::RepeatInfo { rate, delay } => state.events.push(CapEvent::RepeatInfo { rate, delay }), + _ => {} + } + } +} + +impl Dispatch for State { + fn event( + _: &mut Self, + buffer: &wl_buffer::WlBuffer, + event: wl_buffer::Event, + _: &BufferFile, + _: &Connection, + _: &QueueHandle, + ) { + if let wl_buffer::Event::Release = event { + buffer.destroy(); + } + } +} + +macro_rules! no_events { + ($($t:ty),*) => {$( + impl Dispatch<$t, ()> for State { + fn event(_: &mut Self, _: &$t, _: <$t as Proxy>::Event, _: &(), _: &Connection, _: &QueueHandle) {} + } + )*}; +} + +no_events!( + wl_compositor::WlCompositor, + wl_shm::WlShm, + wl_shm_pool::WlShmPool, + wl_region::WlRegion, + wl_surface::WlSurface, + zwlr_layer_shell_v1::ZwlrLayerShellV1, + zxdg_output_manager_v1::ZxdgOutputManagerV1, + zwp_pointer_constraints_v1::ZwpPointerConstraintsV1, + zwp_relative_pointer_manager_v1::ZwpRelativePointerManagerV1, + zwp_keyboard_shortcuts_inhibit_manager_v1::ZwpKeyboardShortcutsInhibitManagerV1, + zwp_keyboard_shortcuts_inhibitor_v1::ZwpKeyboardShortcutsInhibitorV1 +); + +#[cfg(test)] +mod tests { + use super::*; + use zwlr_layer_surface_v1::Anchor; + + fn out() -> OutputGeom { + OutputGeom { + name: "HEADLESS-1".into(), + description: "Dell Inc. DELL U2720Q 7XK0T13 (HEADLESS-1)".into(), + x: 1280, + y: 0, + w: 1920, + h: 1080, + } + } + + fn rect(x: i32, y: i32, w: i32, h: i32) -> Rect { + Rect { x, y, w, h } + } + + #[test] + fn a_closed_strip_counts_as_missing_a_second_later() { + let t = std::time::Instant::now(); + let ms = std::time::Duration::from_millis; + assert!(!recreate_due(None, t + ms(5000)), "nothing closed"); + assert!(!recreate_due(Some(t), t + ms(999))); + assert!(recreate_due(Some(t), t + ms(1000))); + assert!(recreate_due(Some(t), t + ms(60_000))); + } + + #[test] + fn a_strip_is_anchored_to_the_edge_it_lies_on() { + assert_eq!( + placement(&out(), &rect(1280 + 1919, 0, 1, 1080)), + (Anchor::Right | Anchor::Top, (0, 0, 0, 0), (1, 1080)) + ); + assert_eq!( + placement(&out(), &rect(1280, 100, 1, 500)), + (Anchor::Left | Anchor::Top, (100, 0, 0, 0), (1, 500)) + ); + assert_eq!( + placement(&out(), &rect(1280, 0, 1920, 1)), + (Anchor::Top | Anchor::Left, (0, 0, 0, 0), (1920, 1)) + ); + assert_eq!( + placement(&out(), &rect(1380, 1079, 800, 1)), + (Anchor::Bottom | Anchor::Left, (0, 0, 0, 100), (800, 1)) + ); + } + + #[test] + fn only_motion_keys_buttons_and_the_wheel_wait_for_the_lock() { + assert!( + CapEvent::Key { + code: 45, + pressed: true + } + .is_input() + ); + assert!( + CapEvent::Relative { + dx: 1.0, + dy: 0.0, + dx_unaccel: 1.0, + dy_unaccel: 0.0 + } + .is_input() + ); + assert!(!CapEvent::Motion { x: 1.0, y: 2.0 }.is_input()); + assert!( + CapEvent::Button { + button: 272, + pressed: true + } + .is_input() + ); + assert!(CapEvent::Axis { v120_x: 0, v120_y: 120 }.is_input()); + assert!(!CapEvent::Locked.is_input()); + assert!( + !CapEvent::Enter { + strip: 1, + x: 0.0, + y: 0.0 + } + .is_input() + ); + let m = CapEvent::Modifiers { + depressed: 0, + latched: 0, + locked: 0, + group: 0, + }; + assert!(!m.is_input()); + } + + #[test] + fn input_waits_for_the_lock_and_nothing_else_does() { + let key = CapEvent::Key { + code: 30, + pressed: true, + }; + let wheel = CapEvent::Axis { v120_x: 0, v120_y: 120 }; + // Idle: motion and keys pass (edge resistance needs the motion). + assert!(passes(false, false, &key)); + // Waiting for the lock: no input. + assert!(!passes(true, false, &key)); + assert!(!passes(true, false, &wheel)); + // Locked: all of it. + assert!(passes(true, true, &key)); + assert!(passes(true, true, &wheel)); + // The lock itself, the keymap and the modifiers always pass. + for ev in [ + CapEvent::Locked, + CapEvent::Unlocked, + CapEvent::KeyboardLeft, + CapEvent::RepeatInfo { rate: 25, delay: 600 }, + ] { + assert!(passes(true, false, &ev), "{ev:?}"); + } + } + + #[test] + fn an_output_matches_its_name_or_its_kanshi_criteria() { + let o = out(); + assert!(o.matches("HEADLESS-1")); + assert!(o.matches("Dell Inc. DELL U2720Q 7XK0T13")); + assert!(!o.matches("Dell Inc. DELL U2720Q")); + assert!(!o.matches("HEADLESS-2")); + assert!(!o.matches("")); + } + + #[test] + fn the_wheel_prefers_v120_then_steps_then_pixels() { + let w = Wheel { + v120: (0, 60), + discrete: (0, 1), + continuous: (0.0, 15.0), + }; + assert_eq!(w.v120(), (0, 60)); + let w = Wheel { + discrete: (-1, 2), + continuous: (3.0, 15.0), + ..Wheel::default() + }; + assert_eq!(w.v120(), (-120, 240)); + let w = Wheel { + continuous: (-7.5, 30.0), + ..Wheel::default() + }; + assert_eq!(w.v120(), (-60, 240)); + let w = Wheel { + continuous: (f64::NAN, f64::INFINITY), + ..Wheel::default() + }; + assert_eq!(w.v120(), (0, i32::MAX)); + } +} diff --git a/src/thinfloe-menu/src/deskflow/clip.rs b/src/thinfloe-menu/src/deskflow/clip.rs new file mode 100644 index 0000000..6ba0d85 --- /dev/null +++ b/src/thinfloe-menu/src/deskflow/clip.rs @@ -0,0 +1,705 @@ +//! The Wayland side of the text clipboard (spec, Clipboard): a data-control +//! client on a connection of its own, so a clipboard fault never touches +//! the capture's. It reports a selection another client set (text read in +//! full) and offers text received from the remote computer. +//! +//! The protocol exists twice with the same shape: ext_data_control_v1 is +//! preferred, zwlr_data_control_v1 the fallback. The reads and writes of +//! the selection data run on pipes the daemon's poll loop watches +//! ([ Clip::pipe_fds ]); nothing here blocks. + +use std::os::fd::{AsFd, AsRawFd, BorrowedFd, FromRawFd, OwnedFd, RawFd}; +use std::rc::Rc; +use std::time::{Duration, Instant}; + +use wayland_client::backend::{Backend, WaylandError}; +use wayland_client::globals::{GlobalListContents, registry_queue_init}; +use wayland_client::protocol::{wl_registry, wl_seat}; +use wayland_client::{Connection, Dispatch, EventQueue, Proxy, QueueHandle, event_created_child}; +use wayland_protocols::ext::data_control::v1::client::{ + ext_data_control_device_v1, ext_data_control_manager_v1, ext_data_control_offer_v1, ext_data_control_source_v1, +}; +use wayland_protocols_wlr::data_control::v1::client::{ + zwlr_data_control_device_v1, zwlr_data_control_manager_v1, zwlr_data_control_offer_v1, zwlr_data_control_source_v1, +}; + +use super::clipdata::CLIP_MAX; + +/// A transfer that makes no progress for this long is dropped. +const TRANSFER_TIMEOUT: Duration = Duration::from_secs(2); +/// The mime type only ThinFloe's own source offers. +const MARKER: &str = "application/x-thinfloe-deskflow"; +/// What a source offers, in this order, besides the marker. +const OFFERED: [&str; 5] = [ + "text/plain;charset=utf-8", + "text/plain", + "UTF8_STRING", + "STRING", + "TEXT", +]; +/// What a selection is read as, most wanted first. +const PREFERRED: [&str; 5] = [ + "text/plain;charset=utf-8", + "UTF8_STRING", + "text/plain", + "STRING", + "TEXT", +]; + +#[derive(Debug, PartialEq, Eq)] +pub enum ClipEvent { + /// Another client set the selection: its text, at most [CLIP_MAX] bytes. + Changed(Vec), + /// Another client set a selection the bridge does not carry: no text + /// mime, an empty text, more than [CLIP_MAX] bytes, or a read that + /// failed or ran out of time. The text seen before is no longer + /// ThinFloe's clipboard. + Cleared, +} + +/// The mime type to read from an offer, or None when it has no text. +pub fn pick_mime(mimes: &[String]) -> Option<&str> { + PREFERRED + .iter() + .find_map(|want| mimes.iter().find(|m| m.as_str() == *want).map(String::as_str)) +} + +/// An offer that lists the marker comes from ThinFloe's own source. +fn is_own(mimes: &[String]) -> bool { + mimes.iter().any(|m| m == MARKER) +} + +/// What a [CappedRead] has come to. +#[derive(Debug, PartialEq, Eq, Clone, Copy)] +pub enum ReadState { + Open, + /// More than [CLIP_MAX] bytes arrived. + Over, + /// Open for longer than the timeout. + Expired, +} + +/// The bytes of one read, bounded in size and time. +#[derive(Debug)] +pub struct CappedRead { + buf: Vec, + started: Instant, + over: bool, +} + +impl CappedRead { + pub fn new(started: Instant) -> Self { + CappedRead { + buf: Vec::new(), + started, + over: false, + } + } + + /// Takes more bytes; at most CLIP_MAX+1 are kept, which is enough to + /// know the read is over the cap. + pub fn feed(&mut self, data: &[u8]) { + let room = (CLIP_MAX + 1).saturating_sub(self.buf.len()); + self.buf.extend_from_slice(&data[..data.len().min(room)]); + if self.buf.len() > CLIP_MAX { + self.over = true; + } + } + + pub fn state(&self, now: Instant) -> ReadState { + if self.over { + ReadState::Over + } else if now.saturating_duration_since(self.started) >= TRANSFER_TIMEOUT { + ReadState::Expired + } else { + ReadState::Open + } + } + + pub fn into_bytes(self) -> Vec { + self.buf + } +} + +/// An offer of either protocol. +#[derive(Clone, PartialEq)] +enum Offer { + Ext(ext_data_control_offer_v1::ExtDataControlOfferV1), + Wlr(zwlr_data_control_offer_v1::ZwlrDataControlOfferV1), +} + +impl Offer { + fn receive(&self, mime: &str, fd: BorrowedFd<'_>) { + match self { + Offer::Ext(o) => o.receive(mime.to_string(), fd), + Offer::Wlr(o) => o.receive(mime.to_string(), fd), + } + } + fn destroy(&self) { + match self { + Offer::Ext(o) => o.destroy(), + Offer::Wlr(o) => o.destroy(), + } + } +} + +/// A source of either protocol. +#[derive(Clone, PartialEq)] +enum Source { + Ext(ext_data_control_source_v1::ExtDataControlSourceV1), + Wlr(zwlr_data_control_source_v1::ZwlrDataControlSourceV1), +} + +impl Source { + fn offer(&self, mime: &str) { + match self { + Source::Ext(s) => s.offer(mime.to_string()), + Source::Wlr(s) => s.offer(mime.to_string()), + } + } + fn destroy(&self) { + match self { + Source::Ext(s) => s.destroy(), + Source::Wlr(s) => s.destroy(), + } + } +} + +/// The manager and device of whichever protocol the compositor has. +enum Control { + Ext { + mgr: ext_data_control_manager_v1::ExtDataControlManagerV1, + dev: ext_data_control_device_v1::ExtDataControlDeviceV1, + }, + Wlr { + mgr: zwlr_data_control_manager_v1::ZwlrDataControlManagerV1, + dev: zwlr_data_control_device_v1::ZwlrDataControlDeviceV1, + }, +} + +impl Control { + fn new_source(&self, qh: &QueueHandle) -> Source { + match self { + Control::Ext { mgr, .. } => Source::Ext(mgr.create_data_source(qh, ())), + Control::Wlr { mgr, .. } => Source::Wlr(mgr.create_data_source(qh, ())), + } + } + fn set_selection(&self, source: &Source) { + match (self, source) { + (Control::Ext { dev, .. }, Source::Ext(s)) => dev.set_selection(Some(s)), + (Control::Wlr { dev, .. }, Source::Wlr(s)) => dev.set_selection(Some(s)), + _ => {} + } + } +} + +/// A selection being read from a pipe, or a text being written to one. +enum Transfer { + Read { + fd: OwnedFd, + offer: Offer, + read: CappedRead, + }, + Write { + fd: OwnedFd, + data: Rc>, + done: usize, + started: Instant, + }, +} + +impl Transfer { + fn fd(&self) -> RawFd { + match self { + Transfer::Read { fd, .. } | Transfer::Write { fd, .. } => fd.as_raw_fd(), + } + } + fn started(&self) -> Instant { + match self { + Transfer::Read { read, .. } => read.started, + Transfer::Write { started, .. } => *started, + } + } + /// Gives the offer back to the compositor. + fn finish(self) { + if let Transfer::Read { offer, .. } = self { + offer.destroy(); + } + } +} + +struct State { + /// Offers announced and their mime types, until a selection takes them. + pending: Vec<(Offer, Vec)>, + own: Option<(Source, Rc>)>, + transfers: Vec, + now: Instant, + /// Events of the Wayland callbacks, until [Clip::dispatch] returns them. + events: Vec, +} + +pub struct Clip { + conn: Connection, + backend: Backend, + queue: EventQueue, + control: Control, + state: State, +} + +fn nonblocking_pipe() -> Result<(OwnedFd, OwnedFd), String> { + let mut fds = [0; 2]; + // SAFETY: fds has room for the two descriptors pipe2 writes. + if unsafe { libc::pipe2(fds.as_mut_ptr(), libc::O_CLOEXEC | libc::O_NONBLOCK) } != 0 { + return Err(format!("pipe2: {}", std::io::Error::last_os_error())); + } + // SAFETY: pipe2 made both and nothing else owns them. + Ok(unsafe { (OwnedFd::from_raw_fd(fds[0]), OwnedFd::from_raw_fd(fds[1])) }) +} + +fn set_nonblocking(fd: &OwnedFd) { + // SAFETY: fcntl on a descriptor we own. + unsafe { + let fl = libc::fcntl(fd.as_raw_fd(), libc::F_GETFL); + if fl >= 0 { + libc::fcntl(fd.as_raw_fd(), libc::F_SETFL, fl | libc::O_NONBLOCK); + } + } +} + +impl State { + /// A new selection: a read in progress is cancelled; text of a foreign + /// owner starts a read. + fn on_selection(&mut self, offer: Option) { + let (reads, rest): (Vec<_>, Vec<_>) = std::mem::take(&mut self.transfers) + .into_iter() + .partition(|t| matches!(t, Transfer::Read { .. })); + self.transfers = rest; + reads.into_iter().for_each(Transfer::finish); + let Some(offer) = offer else { return }; + let mimes = match self.pending.iter().position(|(o, _)| *o == offer) { + Some(i) => self.pending.remove(i).1, + None => Vec::new(), + }; + let mime = match pick_mime(&mimes) { + Some(m) if !is_own(&mimes) => m.to_string(), + None if !is_own(&mimes) => { + offer.destroy(); + self.events.push(ClipEvent::Cleared); + return; + } + _ => { + offer.destroy(); + return; + } + }; + match nonblocking_pipe() { + Ok((rd, wr)) => { + offer.receive(&mime, wr.as_fd()); + self.transfers.push(Transfer::Read { + fd: rd, + offer, + read: CappedRead::new(self.now), + }); + } + Err(e) => { + eprintln!("thinfloe-menu --deskflow: clipboard: {e}"); + offer.destroy(); + self.events.push(ClipEvent::Cleared); + } + } + } + + /// The compositor wants our text on a pipe. + fn on_send(&mut self, source: &Source, fd: OwnedFd) { + let Some((own, data)) = &self.own else { return }; + if own != source { + return; + } + set_nonblocking(&fd); + self.transfers.push(Transfer::Write { + fd, + data: Rc::clone(data), + done: 0, + started: self.now, + }); + } + + fn on_cancelled(&mut self, source: &Source) { + if self.own.as_ref().is_some_and(|(o, _)| o == source) { + source.destroy(); + self.own = None; + } + } + + fn on_offer_mime(&mut self, offer: &Offer, mime: String) { + if let Some((_, mimes)) = self.pending.iter_mut().find(|(o, _)| o == offer) { + mimes.push(mime); + } + } + + fn on_primary(&mut self, offer: Option) { + if let Some(offer) = offer { + self.pending.retain(|(o, _)| *o != offer); + offer.destroy(); + } + } +} + +impl Clip { + /// The data-control protocol of the compositor, ext first. + pub fn connect() -> Result { + let conn = Connection::connect_to_env().map_err(|e| format!("no Wayland connection: {e}"))?; + let (globals, mut queue): (_, EventQueue) = + registry_queue_init(&conn).map_err(|e| format!("Wayland registry: {e}"))?; + let qh = queue.handle(); + let seat: wl_seat::WlSeat = globals.bind(&qh, 1..=1, ()).map_err(|e| format!("wl_seat: {e}"))?; + let control = if let Ok(mgr) = + globals.bind::(&qh, 1..=1, ()) + { + let dev = mgr.get_data_device(&seat, &qh, ()); + Control::Ext { mgr, dev } + } else if let Ok(mgr) = + globals.bind::(&qh, 1..=2, ()) + { + let dev = mgr.get_data_device(&seat, &qh, ()); + Control::Wlr { mgr, dev } + } else { + return Err("the compositor has neither ext_data_control_v1 nor zwlr_data_control_v1".into()); + }; + let mut state = State { + pending: Vec::new(), + own: None, + transfers: Vec::new(), + now: Instant::now(), + events: Vec::new(), + }; + queue + .roundtrip(&mut state) + .map_err(|e| format!("Wayland roundtrip: {e}"))?; + let backend = conn.backend(); + Ok(Clip { + conn, + backend, + queue, + control, + state, + }) + } + + /// The connection's file descriptor, to poll for readable events. + pub fn fd(&self) -> BorrowedFd<'_> { + self.backend.poll_fd() + } + + /// Reads what the compositor sent, without blocking, and acts on it: a + /// foreign selection starts a read, a request for our text starts a + /// write. The text itself arrives through [Clip::on_pipe_ready]; from + /// here comes only [ClipEvent::Cleared] for a selection without text. + pub fn dispatch(&mut self, now: Instant) -> Result, String> { + self.state.now = now; + self.flush()?; + self.queue + .dispatch_pending(&mut self.state) + .map_err(|e| format!("Wayland dispatch: {e}"))?; + if let Some(guard) = self.queue.prepare_read() { + match guard.read() { + Ok(_) => {} + Err(WaylandError::Io(e)) if e.kind() == std::io::ErrorKind::WouldBlock => {} + Err(e) => return Err(format!("Wayland read: {e}")), + } + } + self.queue + .dispatch_pending(&mut self.state) + .map_err(|e| format!("Wayland dispatch: {e}"))?; + self.flush()?; + Ok(std::mem::take(&mut self.state.events)) + } + + pub fn flush(&mut self) -> Result<(), String> { + match self.conn.flush() { + Ok(()) => Ok(()), + Err(WaylandError::Io(e)) if e.kind() == std::io::ErrorKind::WouldBlock => Ok(()), + Err(e) => Err(format!("Wayland flush: {e}")), + } + } + + /// The pipes to poll: POLLIN for a read, POLLOUT for a write. + pub fn pipe_fds(&self) -> Vec<(RawFd, libc::c_short)> { + self.state + .transfers + .iter() + .map(|t| match t { + Transfer::Read { .. } => (t.fd(), libc::POLLIN), + Transfer::Write { .. } => (t.fd(), libc::POLLOUT), + }) + .collect() + } + + /// A pipe from [Clip::pipe_fds] is ready: moves what it can. A text read + /// in full is the event; a read that failed or went over the cap is + /// dropped and reported as [ClipEvent::Cleared]; a failed write is + /// dropped. + pub fn on_pipe_ready(&mut self, fd: RawFd, now: Instant) -> Vec { + let Some(i) = self.state.transfers.iter().position(|t| t.fd() == fd) else { + return Vec::new(); + }; + let mut t = self.state.transfers.swap_remove(i); + let mut events = Vec::new(); + let keep = match &mut t { + Transfer::Read { fd, read, .. } => { + let mut buf = [0u8; 65536]; + loop { + // SAFETY: buf is valid for buf.len() bytes. + let n = unsafe { libc::read(fd.as_raw_fd(), buf.as_mut_ptr().cast(), buf.len()) }; + if n > 0 { + read.feed(&buf[..n as usize]); + if read.state(now) == ReadState::Over { + events.push(ClipEvent::Cleared); + break false; + } + } else if n == 0 { + let text = std::mem::replace(read, CappedRead::new(now)).into_bytes(); + events.push(if text.is_empty() { + ClipEvent::Cleared + } else { + ClipEvent::Changed(text) + }); + break false; + } else { + let e = std::io::Error::last_os_error().kind(); + match e { + std::io::ErrorKind::WouldBlock => break true, + std::io::ErrorKind::Interrupted => {} + _ => { + events.push(ClipEvent::Cleared); + break false; + } + } + } + } + } + Transfer::Write { fd, data, done, .. } => loop { + if *done >= data.len() { + break false; + } + let rest = &data[*done..]; + // SAFETY: rest is valid for rest.len() bytes. A closed + // reader gives EPIPE (the runtime ignores SIGPIPE). + let n = unsafe { libc::write(fd.as_raw_fd(), rest.as_ptr().cast(), rest.len()) }; + if n >= 0 { + *done += n as usize; + } else { + match std::io::Error::last_os_error().kind() { + std::io::ErrorKind::WouldBlock => break true, + std::io::ErrorKind::Interrupted => {} + _ => break false, + } + } + }, + }; + if keep { + self.state.transfers.push(t); + } else { + t.finish(); + } + events + } + + /// When the oldest transfer runs out of time. + pub fn deadline(&self) -> Option { + self.state + .transfers + .iter() + .map(|t| t.started() + TRANSFER_TIMEOUT) + .min() + } + + /// Drops the transfers older than the timeout; a read that ran out of + /// time is reported as [ClipEvent::Cleared]. + pub fn tick(&mut self, now: Instant) -> Vec { + let (old, keep): (Vec<_>, Vec<_>) = std::mem::take(&mut self.state.transfers) + .into_iter() + .partition(|t| now.saturating_duration_since(t.started()) >= TRANSFER_TIMEOUT); + self.state.transfers = keep; + let events = old + .iter() + .filter(|t| matches!(t, Transfer::Read { .. })) + .map(|_| ClipEvent::Cleared) + .collect(); + old.into_iter().for_each(Transfer::finish); + events + } + + /// Makes this text the selection; a reader's pipe is served from the + /// poll loop. + pub fn set_text(&mut self, text: Vec) { + let qh = self.queue.handle(); + let source = self.control.new_source(&qh); + for mime in OFFERED.iter().copied().chain([MARKER]) { + source.offer(mime); + } + self.control.set_selection(&source); + if let Some((old, _)) = self.state.own.replace((source, Rc::new(text))) { + old.destroy(); + } + let _ = self.flush(); + } +} + +macro_rules! protocol { + ($variant:ident, $mgr:ty, $dev:ty, $dev_mod:ident, $src:ty, $src_mod:ident, $off:ty, $off_mod:ident) => { + impl Dispatch<$mgr, ()> for State { + fn event(_: &mut Self, _: &$mgr, _: <$mgr as Proxy>::Event, _: &(), _: &Connection, _: &QueueHandle) {} + } + + impl Dispatch<$dev, ()> for State { + fn event( + state: &mut Self, + _: &$dev, + event: <$dev as Proxy>::Event, + _: &(), + _: &Connection, + _: &QueueHandle, + ) { + use $dev_mod::Event; + match event { + Event::DataOffer { id } => state.pending.push((Offer::$variant(id), Vec::new())), + Event::Selection { id } => state.on_selection(id.map(Offer::$variant)), + Event::PrimarySelection { id } => state.on_primary(id.map(Offer::$variant)), + _ => {} + } + } + + event_created_child!(State, $dev, [ + 0 => ($off, ()), + ]); + } + + impl Dispatch<$src, ()> for State { + fn event( + state: &mut Self, + source: &$src, + event: <$src as Proxy>::Event, + _: &(), + _: &Connection, + _: &QueueHandle, + ) { + use $src_mod::Event; + match event { + Event::Send { fd, .. } => state.on_send(&Source::$variant(source.clone()), fd), + Event::Cancelled => state.on_cancelled(&Source::$variant(source.clone())), + _ => {} + } + } + } + + impl Dispatch<$off, ()> for State { + fn event( + state: &mut Self, + offer: &$off, + event: <$off as Proxy>::Event, + _: &(), + _: &Connection, + _: &QueueHandle, + ) { + use $off_mod::Event; + if let Event::Offer { mime_type } = event { + state.on_offer_mime(&Offer::$variant(offer.clone()), mime_type); + } + } + } + }; +} + +protocol!( + Ext, + ext_data_control_manager_v1::ExtDataControlManagerV1, + ext_data_control_device_v1::ExtDataControlDeviceV1, + ext_data_control_device_v1, + ext_data_control_source_v1::ExtDataControlSourceV1, + ext_data_control_source_v1, + ext_data_control_offer_v1::ExtDataControlOfferV1, + ext_data_control_offer_v1 +); +protocol!( + Wlr, + zwlr_data_control_manager_v1::ZwlrDataControlManagerV1, + zwlr_data_control_device_v1::ZwlrDataControlDeviceV1, + zwlr_data_control_device_v1, + zwlr_data_control_source_v1::ZwlrDataControlSourceV1, + zwlr_data_control_source_v1, + zwlr_data_control_offer_v1::ZwlrDataControlOfferV1, + zwlr_data_control_offer_v1 +); + +impl Dispatch for State { + fn event( + _: &mut Self, + _: &wl_registry::WlRegistry, + _: wl_registry::Event, + _: &GlobalListContents, + _: &Connection, + _: &QueueHandle, + ) { + } +} + +impl Dispatch for State { + fn event(_: &mut Self, _: &wl_seat::WlSeat, _: wl_seat::Event, _: &(), _: &Connection, _: &QueueHandle) {} +} + +#[cfg(test)] +mod tests { + use super::*; + + fn v(s: &[&str]) -> Vec { + s.iter().map(|s| s.to_string()).collect() + } + + #[test] + fn pick_mime_prefers_utf8() { + assert_eq!( + pick_mime(&v(&[ + "TEXT", + "STRING", + "text/plain", + "UTF8_STRING", + "text/plain;charset=utf-8" + ])), + Some("text/plain;charset=utf-8") + ); + assert_eq!( + pick_mime(&v(&["STRING", "text/plain", "UTF8_STRING"])), + Some("UTF8_STRING") + ); + assert_eq!(pick_mime(&v(&["STRING", "text/plain"])), Some("text/plain")); + assert_eq!(pick_mime(&v(&["TEXT", "STRING"])), Some("STRING")); + assert_eq!(pick_mime(&v(&["TEXT"])), Some("TEXT")); + assert_eq!(pick_mime(&v(&["image/png", "text/html"])), None); + assert_eq!(pick_mime(&[]), None); + } + + #[test] + fn own_marker_is_skipped() { + assert!(is_own(&v(&["text/plain", MARKER]))); + assert!(!is_own(&v(&["text/plain", "UTF8_STRING"]))); + // Every mime the source offers is one that would be read. + assert!(pick_mime(&v(&OFFERED)).is_some()); + } + + #[test] + fn reader_stops_at_cap_and_deadline() { + let t0 = Instant::now(); + let mut r = CappedRead::new(t0); + r.feed(&vec![b'a'; CLIP_MAX]); + assert_eq!(r.state(t0), ReadState::Open); + r.feed(b"a"); + assert_eq!(r.state(t0), ReadState::Over); + r.feed(&vec![b'a'; 1000]); + assert_eq!(r.into_bytes().len(), CLIP_MAX + 1); + + let idle = CappedRead::new(t0); + assert_eq!(idle.state(t0 + Duration::from_millis(1999)), ReadState::Open); + assert_eq!(idle.state(t0 + Duration::from_secs(2)), ReadState::Expired); + } +} diff --git a/src/thinfloe-menu/src/deskflow/clipdata.rs b/src/thinfloe-menu/src/deskflow/clipdata.rs new file mode 100644 index 0000000..155f4b5 --- /dev/null +++ b/src/thinfloe-menu/src/deskflow/clipdata.rs @@ -0,0 +1,285 @@ +//! The text clipboard on the wire (spec, Clipboard): the marshalled form, +//! the DCLP transfer split and the inbound assembler. Pure data, no I/O. + +use super::proto::Msg; + +/// The largest marshalled clipboard sent or accepted, in bytes (1 MiB). +pub const CLIP_MAX: usize = 1 << 20; +/// The largest data chunk of one DCLP message. +pub const CHUNK: usize = 512 * 1024; + +const FORMAT_TEXT: u32 = 0; +const MARK_START: u8 = 1; +const MARK_DATA: u8 = 2; +const MARK_END: u8 = 3; + +const fn code(s: &[u8; 4]) -> u32 { + u32::from_be_bytes(*s) +} +/// Option codes of the DSOP message (OptionTypes.h). +pub const CLPS: u32 = code(b"CLPS"); +pub const CLSZ: u32 = code(b"CLSZ"); + +/// The DSOP options for the clipboard switch; CLSZ is in KiB. +pub fn options(clipboard: bool) -> Vec { + if clipboard { + vec![CLPS, 1, CLSZ, 1024] + } else { + vec![CLPS, 0] + } +} + +/// One format (Text, id 0) in the marshalled form: a count, then per format +/// id, size and bytes, all big-endian u32. +pub fn marshal_text(text: &[u8]) -> Vec { + let mut v = Vec::with_capacity(12 + text.len()); + v.extend_from_slice(&1u32.to_be_bytes()); + v.extend_from_slice(&FORMAT_TEXT.to_be_bytes()); + v.extend_from_slice(&(text.len() as u32).to_be_bytes()); + v.extend_from_slice(text); + v +} + +/// The Text format of a marshalled clipboard, other formats skipped; +/// `None` when it is truncated or has no Text. +pub fn unmarshal_text(data: &[u8]) -> Option> { + let u32_at = + |p: usize| -> Option { Some(u32::from_be_bytes(data.get(p..p.checked_add(4)?)?.try_into().ok()?)) }; + let count = u32_at(0)?; + let mut pos = 4usize; + for _ in 0..count { + let id = u32_at(pos)?; + let size = u32_at(pos.checked_add(4)?)? as usize; + let start = pos.checked_add(8)?; + let end = start.checked_add(size)?; + let body = data.get(start..end)?; + if id == FORMAT_TEXT { + return Some(body.to_vec()); + } + pos = end; + } + None +} + +/// The DCLP messages of one transfer: start, data chunks, end. An empty +/// transfer has one empty data chunk. +pub fn chunks(id: u8, seq: u32, marshalled: &[u8]) -> Vec { + let dclp = |mark: u8, data: Vec| Msg::Dclp { id, seq, mark, data }; + let mut v = vec![dclp(MARK_START, marshalled.len().to_string().into_bytes())]; + if marshalled.is_empty() { + v.push(dclp(MARK_DATA, Vec::new())); + } else { + v.extend(marshalled.chunks(CHUNK).map(|c| dclp(MARK_DATA, c.to_vec()))); + } + v.push(dclp(MARK_END, Vec::new())); + v +} + +/// What one DCLP message did to the assembler. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Asm { + Started, + InProgress, + /// The transfer ended; the marshalled bytes. + Finished(Vec), + /// Part of a transfer too large to keep, or of an unused clipboard id. + Dropped, + /// The stream broke the protocol. + Error, +} + +#[derive(Default)] +enum Slot { + #[default] + Idle, + Receiving { + declared: usize, + buf: Vec, + }, + Oversize, +} + +/// Inbound DCLP transfers, one slot per clipboard id (0 and 1 exist). +#[derive(Default)] +pub struct Assembler { + slots: [Slot; 2], +} + +impl Assembler { + pub fn push(&mut self, id: u8, _seq: u32, mark: u8, data: &[u8]) -> Asm { + let Some(slot) = self.slots.get_mut(id as usize) else { + return Asm::Dropped; + }; + match (mark, std::mem::take(slot)) { + (MARK_START, _) => { + let declared = std::str::from_utf8(data).ok().and_then(|s| s.parse::().ok()); + match declared { + None => Asm::Error, + Some(n) if n > CLIP_MAX => { + *slot = Slot::Oversize; + Asm::Dropped + } + Some(declared) => { + *slot = Slot::Receiving { + declared, + buf: Vec::with_capacity(declared), + }; + Asm::Started + } + } + } + (MARK_DATA, Slot::Receiving { declared, mut buf }) => { + if buf.len() + data.len() > declared { + return Asm::Error; + } + buf.extend_from_slice(data); + *slot = Slot::Receiving { declared, buf }; + Asm::InProgress + } + (MARK_DATA, Slot::Oversize) => { + *slot = Slot::Oversize; + Asm::Dropped + } + (MARK_END, Slot::Receiving { declared, buf }) => { + if buf.len() == declared { + Asm::Finished(buf) + } else { + Asm::Error + } + } + (MARK_END, Slot::Oversize) => Asm::Dropped, + _ => Asm::Error, + } + } + + /// Bytes buffered over all slots. + #[cfg(test)] + fn buffered(&self) -> usize { + self.slots + .iter() + .map(|s| match s { + Slot::Receiving { buf, .. } => buf.len(), + _ => 0, + }) + .sum() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn marshal_roundtrip() { + let t = b"h\xc3\xa4llo\n"; + assert_eq!(unmarshal_text(&marshal_text(t)), Some(t.to_vec())); + } + + #[test] + fn unmarshal_skips_other_formats() { + let mut d = 2u32.to_be_bytes().to_vec(); + d.extend_from_slice(&1u32.to_be_bytes()); + d.extend_from_slice(&3u32.to_be_bytes()); + d.extend_from_slice(b""); + d.extend_from_slice(&0u32.to_be_bytes()); + d.extend_from_slice(&2u32.to_be_bytes()); + d.extend_from_slice(b"hi"); + assert_eq!(unmarshal_text(&d), Some(b"hi".to_vec())); + } + + #[test] + fn unmarshal_truncated_is_none() { + let m = marshal_text(b"hello"); + for n in 0..m.len() { + assert_eq!(unmarshal_text(&m[..n]), None, "{n}"); + } + assert_eq!(unmarshal_text(&u32::MAX.to_be_bytes()), None); + } + + fn parts(v: &[Msg]) -> Vec<(u8, usize)> { + v.iter() + .map(|m| match m { + Msg::Dclp { mark, data, .. } => (*mark, data.len()), + _ => panic!("not DCLP"), + }) + .collect() + } + + #[test] + fn chunks_split_at_512k() { + let m = vec![7u8; CHUNK * 2 + 1]; + let c = chunks(0, 5, &m); + assert_eq!( + c[0], + Msg::Dclp { + id: 0, + seq: 5, + mark: 1, + data: b"1048577".to_vec() + } + ); + assert_eq!(parts(&c), [(1, 7), (2, CHUNK), (2, CHUNK), (2, 1), (3, 0)]); + } + + #[test] + fn empty_transfer_has_one_data_chunk() { + let c = chunks(0, 1, &[]); + assert_eq!(parts(&c), [(1, 1), (2, 0), (3, 0)]); + } + + #[test] + fn chunks_reassemble() { + let m = marshal_text(&vec![b'x'; CHUNK + 10]); + let mut a = Assembler::default(); + let mut last = Asm::Error; + for c in chunks(0, 1, &m) { + let Msg::Dclp { id, seq, mark, data } = c else { panic!() }; + last = a.push(id, seq, mark, &data); + } + assert_eq!(last, Asm::Finished(m)); + } + + #[test] + fn assembler_errors() { + let mut a = Assembler::default(); + assert_eq!(a.push(0, 0, 2, b"x"), Asm::Error); + assert_eq!(a.push(0, 0, 3, b""), Asm::Error); + assert_eq!(a.push(0, 0, 1, b"2"), Asm::Started); + assert_eq!(a.push(0, 0, 2, b"abc"), Asm::Error); + assert_eq!(a.push(0, 0, 1, b"3"), Asm::Started); + assert_eq!(a.push(0, 0, 2, b"ab"), Asm::InProgress); + assert_eq!(a.push(0, 0, 3, b""), Asm::Error); + assert_eq!(a.push(0, 0, 1, b"x"), Asm::Error); + } + + #[test] + fn assembler_oversize_is_dropped_not_error() { + let mut a = Assembler::default(); + assert_eq!(a.push(0, 0, 1, b"2000000"), Asm::Dropped); + assert_eq!(a.push(0, 0, 2, &[0; 1000]), Asm::Dropped); + assert_eq!(a.buffered(), 0); + assert_eq!(a.push(0, 0, 3, b""), Asm::Dropped); + assert_eq!(a.buffered(), 0); + // The slot is free again. + assert_eq!(a.push(0, 0, 1, b"0"), Asm::Started); + } + + #[test] + fn assembler_ids_are_independent() { + let mut a = Assembler::default(); + assert_eq!(a.push(0, 0, 1, b"1"), Asm::Started); + assert_eq!(a.push(1, 0, 1, b"1"), Asm::Started); + assert_eq!(a.push(1, 0, 2, b"y"), Asm::InProgress); + assert_eq!(a.push(1, 0, 3, b""), Asm::Finished(b"y".to_vec())); + assert_eq!(a.push(0, 0, 2, b"x"), Asm::InProgress); + assert_eq!(a.push(0, 0, 3, b""), Asm::Finished(b"x".to_vec())); + assert_eq!(a.push(9, 0, 2, b"x"), Asm::Dropped); + } + + #[test] + fn options_codes() { + assert_eq!(CLPS, u32::from_be_bytes(*b"CLPS")); + assert_eq!(options(true), [CLPS, 1, CLSZ, 1024]); + assert_eq!(options(false), [CLPS, 0]); + } +} diff --git a/src/thinfloe-menu/src/deskflow/clipsync.rs b/src/thinfloe-menu/src/deskflow/clipsync.rs new file mode 100644 index 0000000..7107a47 --- /dev/null +++ b/src/thinfloe-menu/src/deskflow/clipsync.rs @@ -0,0 +1,270 @@ +//! The clipboard policy of the Deskflow daemon, without IO: who gets +//! ThinFloe's text, who only learns that ThinFloe took the clipboard, and +//! which device text becomes ThinFloe's selection. `conn` is the +//! daemon's connection id ([`super::conn::Conn::id`]), stable for the +//! life of a connection; `live` lists the trusted connections with their +//! device's Clipboard switch. + +/// What the daemon does for the policy. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum ClipAct { + /// CCLP and DCLP: the device gets this text. + Send { conn: usize, text: Vec }, + /// CCLP alone: the device learns that someone else owns the clipboard. + Grab { conn: usize }, + /// The text becomes ThinFloe's selection. + SetLocal(Vec), +} + +#[derive(Debug, Default)] +pub struct ClipSync { + /// ThinFloe's text as last seen, local or from a device. + text: Option>, + /// The devices that hold that text: the one it came from and those it + /// was sent to. They are not sent it again. + holders: Vec, +} + +impl ClipSync { + /// ThinFloe's selection changed: the device with the pointer gets the + /// text, every other device learns of the grab. A device that holds + /// the same bytes already (it gave them) gets neither. + pub fn on_local(&mut self, text: Vec, active: Option, live: &[(usize, bool)]) -> Vec { + if self.text.as_ref() != Some(&text) { + self.holders.clear(); + } + let mut acts = Vec::new(); + if let Some(a) = active + && !self.holders.contains(&a) + && live.contains(&(a, true)) + { + acts.push(ClipAct::Send { + conn: a, + text: text.clone(), + }); + self.holders.push(a); + } + acts.extend( + live.iter() + .filter(|&&(c, on)| on && Some(c) != active && !self.holders.contains(&c)) + .map(|&(conn, _)| ClipAct::Grab { conn }), + ); + self.text = Some(text); + acts + } + + /// The pointer entered a device: it gets ThinFloe's text, unless it + /// holds it already. + pub fn on_enter(&mut self, conn: usize, clipboard: bool) -> Vec { + match &self.text { + Some(text) if clipboard && !self.holders.contains(&conn) => { + self.holders.push(conn); + vec![ClipAct::Send { + conn, + text: text.clone(), + }] + } + _ => Vec::new(), + } + } + + /// A device sent its text: it becomes ThinFloe's selection, and that + /// device is the only one holding it. + pub fn on_remote(&mut self, conn: usize, text: Vec) -> Vec { + self.text = Some(text.clone()); + self.holders = vec![conn]; + vec![ClipAct::SetLocal(text)] + } + + /// ThinFloe's selection became something the bridge does not carry (an + /// image, a file list, a text over the cap). The text seen before is + /// forgotten, so no device gets it later, and every sharing device + /// learns of the grab, the active one too: a Deskflow client empties + /// its clipboard on a grab. + pub fn on_cleared(&mut self, live: &[(usize, bool)]) -> Vec { + self.text = None; + self.holders.clear(); + live.iter() + .filter(|&&(_, on)| on) + .map(|&(conn, _)| ClipAct::Grab { conn }) + .collect() + } + + /// The device's Clipboard switch changed: it no longer counts as + /// holding ThinFloe's text, so the next entry sends it again. + pub fn forget(&mut self, conn: usize) { + self.holders.retain(|&c| c != conn); + } + + /// A device took the clipboard: the others learn of it. None holds + /// ThinFloe's text now (a Deskflow client empties its clipboard on a + /// grab), so the next enter sends it again. + pub fn on_grabbed(&mut self, conn: usize, live: &[(usize, bool)]) -> Vec { + self.holders.clear(); + live.iter() + .filter(|&&(c, on)| on && c != conn) + .map(|&(conn, _)| ClipAct::Grab { conn }) + .collect() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn t(s: &str) -> Vec { + s.as_bytes().to_vec() + } + + #[test] + fn enter_sends_remembered_text() { + let mut s = ClipSync::default(); + s.on_local(t("hello"), None, &[(1, true)]); + assert_eq!( + s.on_enter(1, true), + [ClipAct::Send { + conn: 1, + text: t("hello") + }] + ); + // The device holds it now: the next enter sends nothing. + assert!(s.on_enter(1, true).is_empty()); + } + + #[test] + fn enter_without_text_sends_nothing() { + let mut s = ClipSync::default(); + assert!(s.on_enter(1, true).is_empty()); + } + + #[test] + fn local_change_goes_to_active_and_grab_to_others() { + let mut s = ClipSync::default(); + let acts = s.on_local(t("x"), Some(2), &[(1, true), (2, true), (3, true)]); + assert_eq!( + acts, + [ + ClipAct::Send { conn: 2, text: t("x") }, + ClipAct::Grab { conn: 1 }, + ClipAct::Grab { conn: 3 }, + ] + ); + // Without a capture every device only learns of the grab. + let acts = s.on_local(t("y"), None, &[(1, true), (2, true)]); + assert_eq!(acts, [ClipAct::Grab { conn: 1 }, ClipAct::Grab { conn: 2 }]); + } + + #[test] + fn switch_off_device_gets_nothing() { + let mut s = ClipSync::default(); + let acts = s.on_local(t("x"), Some(2), &[(1, false), (2, false), (3, true)]); + assert_eq!(acts, [ClipAct::Grab { conn: 3 }]); + assert!(s.on_enter(2, false).is_empty()); + assert_eq!(s.on_grabbed(3, &[(1, false), (2, false), (3, true)]), []); + } + + #[test] + fn remote_text_sets_local() { + let mut s = ClipSync::default(); + assert_eq!(s.on_remote(1, t("from laptop")), [ClipAct::SetLocal(t("from laptop"))]); + // Remembered: the next device that is entered gets it. + assert_eq!( + s.on_enter(2, true), + [ClipAct::Send { + conn: 2, + text: t("from laptop") + }] + ); + } + + #[test] + fn own_selection_is_not_sent_back() { + let mut s = ClipSync::default(); + s.on_remote(1, t("same")); + // The same bytes offered again on ThinFloe: device 1 has them. + let acts = s.on_local(t("same"), Some(1), &[(1, true), (2, true)]); + assert_eq!(acts, [ClipAct::Grab { conn: 2 }]); + assert!(s.on_enter(1, true).is_empty()); + // A new text on ThinFloe reaches device 1 again. + let acts = s.on_local(t("new"), Some(1), &[(1, true), (2, true)]); + assert_eq!( + acts, + [ + ClipAct::Send { + conn: 1, + text: t("new") + }, + ClipAct::Grab { conn: 2 } + ] + ); + assert!(s.on_enter(1, true).is_empty()); + } + + #[test] + fn a_grab_or_remote_text_clears_what_a_device_holds() { + let mut s = ClipSync::default(); + let live = [(1, true), (2, true)]; + s.on_local(t("x"), None, &live); + assert_eq!(s.on_enter(1, true), [ClipAct::Send { conn: 1, text: t("x") }]); + assert!(s.on_enter(1, true).is_empty()); + // Device 1 takes the clipboard: its copy of "x" is gone. + s.on_grabbed(1, &live); + assert_eq!(s.on_enter(1, true), [ClipAct::Send { conn: 1, text: t("x") }]); + // Device 2's text: device 1 no longer holds ThinFloe's text. + s.on_remote(2, t("y")); + assert_eq!(s.on_enter(1, true), [ClipAct::Send { conn: 1, text: t("y") }]); + assert!(s.on_enter(2, true).is_empty()); + } + + #[test] + fn an_uncarried_selection_forgets_the_old_text() { + let mut s = ClipSync::default(); + let live = [(1, true), (2, false), (3, true)]; + s.on_local(t("secret"), Some(1), &live); + // An image or a text over the cap on ThinFloe: every sharing + // device, the active one too, learns of the grab. + assert_eq!( + s.on_cleared(&live), + [ClipAct::Grab { conn: 1 }, ClipAct::Grab { conn: 3 }] + ); + // The old text is never sent later. + assert!(s.on_enter(1, true).is_empty()); + assert!(s.on_enter(3, true).is_empty()); + // The next text goes out again, to the device that held the old one too. + assert_eq!( + s.on_local(t("secret"), Some(1), &live), + [ + ClipAct::Send { + conn: 1, + text: t("secret") + }, + ClipAct::Grab { conn: 3 } + ] + ); + } + + #[test] + fn a_cleared_remote_text_is_not_sent_either() { + let mut s = ClipSync::default(); + s.on_remote(1, t("from laptop")); + s.on_cleared(&[(1, true), (2, true)]); + assert!(s.on_enter(2, true).is_empty()); + } + + #[test] + fn a_forgotten_holder_gets_the_text_on_its_next_entry() { + let mut s = ClipSync::default(); + s.on_local(t("x"), Some(1), &[(1, true)]); + assert!(s.on_enter(1, true).is_empty()); + // Its switch went off and on again: it may hold something else. + s.forget(1); + assert_eq!(s.on_enter(1, true), [ClipAct::Send { conn: 1, text: t("x") }]); + } + + #[test] + fn grab_from_one_device_reaches_the_others() { + let mut s = ClipSync::default(); + let acts = s.on_grabbed(2, &[(1, true), (2, true), (3, true)]); + assert_eq!(acts, [ClipAct::Grab { conn: 1 }, ClipAct::Grab { conn: 3 }]); + } +} diff --git a/src/thinfloe-menu/src/deskflow/cmd.rs b/src/thinfloe-menu/src/deskflow/cmd.rs new file mode 100644 index 0000000..aa6abfb --- /dev/null +++ b/src/thinfloe-menu/src/deskflow/cmd.rs @@ -0,0 +1,205 @@ +//! The menu's commands to the Deskflow daemon: one Unix datagram each, +//! `reject\t\t\n` or `reload\n`. Like the OSD's +//! socket, neither side ever blocks on the other. + +use std::ffi::OsString; +use std::io::{self, ErrorKind}; +use std::os::unix::fs::PermissionsExt; +use std::os::unix::net::UnixDatagram; +use std::path::{Path, PathBuf}; + +use super::statefile::{escape, unescape}; + +/// The largest datagram the daemon reads. +pub const DATAGRAM_MAX: usize = 4096; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Cmd { + /// Reject the pending device with this name and fingerprint. + Reject { name: String, fingerprint: String }, + /// Read `generated/deskflow` again. + Reload, +} + +#[derive(Debug)] +pub enum SendError { + /// No daemon listens at the path. + NoServer, + Io(io::Error), +} + +/// Where the daemon listens: `TF_DESKFLOW_SOCKET`, else +/// `$XDG_RUNTIME_DIR/thinfloe-deskflow.sock`; an empty variable is unset. +pub fn socket_path() -> Option { + socket_path_from( + std::env::var_os("TF_DESKFLOW_SOCKET"), + std::env::var_os("XDG_RUNTIME_DIR"), + ) +} + +fn socket_path_from(sock: Option, runtime_dir: Option) -> Option { + if let Some(p) = sock.filter(|p| !p.is_empty()) { + return Some(PathBuf::from(p)); + } + let dir = runtime_dir.filter(|d| !d.is_empty())?; + Some(PathBuf::from(dir).join("thinfloe-deskflow.sock")) +} + +pub fn encode(c: &Cmd) -> Vec { + match c { + Cmd::Reject { name, fingerprint } => { + format!("reject\t{}\t{}\n", escape(name), escape(fingerprint)).into_bytes() + } + Cmd::Reload => b"reload\n".to_vec(), + } +} + +/// The command in one datagram; anything malformed is `None`. +pub fn decode(buf: &[u8]) -> Option { + if buf.len() > DATAGRAM_MAX { + return None; + } + let s = std::str::from_utf8(buf).ok()?; + let line = s.strip_suffix('\n')?; + if line.contains('\n') { + return None; + } + if line == "reload" { + return Some(Cmd::Reload); + } + let mut f = line.split('\t'); + if f.next()? != "reject" { + return None; + } + let (name, fp) = (f.next()?, f.next()?); + if f.next().is_some() || fp.is_empty() { + return None; + } + Some(Cmd::Reject { + name: unescape(name), + fingerprint: unescape(fp), + }) +} + +/// Bind the daemon's socket at `path`: a file left by an earlier daemon is +/// removed first, the socket is mode 0600 and non-blocking. +pub fn bind(path: &Path) -> io::Result { + match std::fs::remove_file(path) { + Err(e) if e.kind() != ErrorKind::NotFound => return Err(e), + _ => {} + } + let sock = UnixDatagram::bind(path)?; + std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600))?; + sock.set_nonblocking(true)?; + Ok(sock) +} + +/// Send `c` to the daemon at `path` as one datagram, without blocking. +pub fn send(path: &Path, c: &Cmd) -> Result<(), SendError> { + let msg = encode(c); + if msg.len() > DATAGRAM_MAX { + return Err(SendError::Io(io::Error::new( + ErrorKind::InvalidInput, + "command too long", + ))); + } + let sock = UnixDatagram::unbound().map_err(SendError::Io)?; + sock.set_nonblocking(true).map_err(SendError::Io)?; + match sock.send_to(&msg, path) { + Ok(_) => Ok(()), + Err(e) if matches!(e.kind(), ErrorKind::NotFound | ErrorKind::ConnectionRefused) => Err(SendError::NoServer), + Err(e) => Err(SendError::Io(e)), + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::testdir::TestDir; + + #[test] + fn cmd_roundtrip() { + let r = Cmd::Reject { + name: "lap\ttop\n\\x01".into(), + fingerprint: "v2:sha256:ab".into(), + }; + let bytes = encode(&r); + assert_eq!(bytes.iter().filter(|&&b| b == b'\n').count(), 1); + assert_eq!(decode(&bytes), Some(r)); + assert_eq!(encode(&Cmd::Reload), b"reload\n"); + assert_eq!(decode(b"reload\n"), Some(Cmd::Reload)); + } + + #[test] + fn cmd_garbage_is_none() { + let big = vec![b'a'; DATAGRAM_MAX + 1]; + let cases: [&[u8]; 12] = [ + b"", + b"\n", + b"reload", + b"reload\n\n", + b"reload\textra\n", + b"reject\n", + b"reject\tname\n", + b"reject\tname\t\n", + b"reject\tn\tfp\textra\n", + b"explode\n", + &[0xff, 0xfe, b'\n'], + &big, + ]; + for c in cases { + assert_eq!(decode(c), None, "{c:?}"); + } + assert_eq!(decode(b"reject\ta\nb\tfp\n"), None); + } + + #[test] + fn a_datagram_reaches_the_bound_socket() { + let d = TestDir::sockets("df"); + let path = d.socket("s"); + let server = bind(&path).unwrap(); + let c = Cmd::Reject { + name: "x".into(), + fingerprint: "fp".into(), + }; + send(&path, &c).unwrap(); + let mut buf = [0u8; DATAGRAM_MAX]; + let n = server.recv(&mut buf).unwrap(); + assert_eq!(decode(&buf[..n]), Some(c)); + assert_eq!(std::fs::metadata(&path).unwrap().permissions().mode() & 0o777, 0o600); + assert_eq!(server.recv(&mut buf).unwrap_err().kind(), ErrorKind::WouldBlock); + } + + #[test] + fn send_without_a_server_is_no_server() { + let d = TestDir::sockets("dn"); + assert!(matches!(send(&d.socket("x"), &Cmd::Reload), Err(SendError::NoServer))); + let stale = d.socket("st"); + drop(UnixDatagram::bind(&stale).unwrap()); + assert!(matches!(send(&stale, &Cmd::Reload), Err(SendError::NoServer))); + let server = bind(&stale).unwrap(); + send(&stale, &Cmd::Reload).unwrap(); + drop(server); + } + + #[test] + fn an_oversized_command_is_refused() { + let d = TestDir::sockets("do"); + let c = Cmd::Reject { + name: "a".repeat(DATAGRAM_MAX), + fingerprint: "fp".into(), + }; + assert!(matches!(send(&d.socket("s"), &c), Err(SendError::Io(_)))); + } + + #[test] + fn socket_path_prefers_the_override() { + let o = |s: &str| Some(OsString::from(s)); + assert_eq!(socket_path_from(o("/x/s"), o("/run")), Some(PathBuf::from("/x/s"))); + assert_eq!( + socket_path_from(o(""), o("/run")), + Some(PathBuf::from("/run/thinfloe-deskflow.sock")) + ); + assert_eq!(socket_path_from(None, None), None); + } +} diff --git a/src/thinfloe-menu/src/deskflow/conn.rs b/src/thinfloe-menu/src/deskflow/conn.rs new file mode 100644 index 0000000..b325734 --- /dev/null +++ b/src/thinfloe-menu/src/deskflow/conn.rs @@ -0,0 +1,463 @@ +//! One client connection of the Deskflow daemon: a non-blocking TCP stream +//! under rustls, the frames cut from it and its protocol [`Session`] (spec, +//! Identity and pairing). The daemon passes the time in and answers the +//! client's name with a verdict. + +use std::io::{self, ErrorKind, Read, Write}; +use std::net::TcpStream; +use std::os::fd::{AsRawFd, RawFd}; +use std::sync::Arc; +use std::time::{Duration, Instant}; + +use rustls::{ServerConfig, ServerConnection}; + +use super::clipdata; +use super::pair::Verdict; +use super::proto::{self, Framer, Msg}; +use super::session::{Out, Session}; +use super::tls; + +/// The most plaintext taken from the TLS layer at once; its frames are cut +/// before the next read, so the framer never holds much more than one +/// message. +pub const READ_CHUNK: usize = 64 * 1024; +/// TLS, Hello and HelloBack together must be done within this time. +pub const HANDSHAKE_DEADLINE: Duration = Duration::from_secs(10); +/// After a refusal (EUNK, EBSY, EICV) the connection stays open this long +/// for the client to read it and hang up, as a Deskflow server does: a +/// Deskflow 1.26 client that sees the end of the stream with the message +/// drops the message and does not log the refusal. +pub const LINGER: Duration = Duration::from_secs(2); +/// What TLS may hold for the client before it counts as not reading: a +/// whole clipboard transfer fits, with room for the input around it. +/// rustls's own default, 64 KiB, cut a larger clipboard short. +pub const SEND_BUFFER: usize = 2 * clipdata::CLIP_MAX; + +/// What a connection tells the daemon. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Event { + /// The client's name: the daemon owes [`Conn::set_verdict`] in the + /// same loop pass. + Named(String), + /// The size of the client's screen, from its DINF. + Screen { w: i16, h: i16 }, + /// The client's text clipboard, received in full. + Clipboard(Vec), + /// The client took the clipboard. + Grabbed, +} + +pub struct Conn { + /// The daemon's number for it, unique for the life of the process. + id: usize, + stream: TcpStream, + tls: ServerConnection, + framer: Framer, + /// Made when the TLS handshake is done. + session: Option, + accepted: Instant, + /// The fingerprint of the client's certificate, once TLS is done. + fingerprint: Option, + /// The client's name, once its HelloBack is in. + name: Option, + /// The verdict was Trusted. + trusted: bool, + /// The last DINF size. + screen: Option<(i16, i16)>, + /// The session ended it: why, and until when the client may read. + ending: Option<(String, Instant)>, + /// Why the connection ends; the daemon drops it after the next flush. + closing: Option, +} + +impl Conn { + pub fn new(id: usize, stream: TcpStream, cfg: Arc, now: Instant) -> io::Result { + stream.set_nonblocking(true)?; + let mut tls = ServerConnection::new(cfg).map_err(io::Error::other)?; + tls.set_buffer_limit(Some(SEND_BUFFER)); + Ok(Conn { + id, + stream, + tls, + framer: Framer::default(), + session: None, + accepted: now, + fingerprint: None, + name: None, + trusted: false, + screen: None, + ending: None, + closing: None, + }) + } + + pub fn id(&self) -> usize { + self.id + } + + pub fn fd(&self) -> RawFd { + self.stream.as_raw_fd() + } + + /// TLS, the HelloBack or the verdict are still to come. + pub fn in_handshake(&self) -> bool { + !self.trusted && self.closing.is_none() + } + + pub fn wants_write(&self) -> bool { + self.tls.wants_write() + } + + pub fn fingerprint(&self) -> Option<&str> { + self.fingerprint.as_deref() + } + + pub fn name(&self) -> Option<&str> { + self.name.as_deref() + } + + /// Trusted and not ending. + pub fn trusted(&self) -> bool { + self.trusted && self.ending.is_none() && self.closing.is_none() + } + + pub fn screen(&self) -> Option<(i16, i16)> { + self.screen + } + + /// Why it ends, once it does. + pub fn closing(&self) -> Option<&str> { + self.closing.as_deref() + } + + pub fn close(&mut self, why: &str) { + if self.closing.is_none() { + self.closing = Some(why.to_string()); + self.tls.send_close_notify(); + } + } + + /// The socket is readable: one TLS read, then every frame in the + /// plaintext, cut [`READ_CHUNK`] bytes at a time. + pub fn on_readable(&mut self, now: Instant) -> Vec { + if self.closing.is_some() { + return Vec::new(); + } + match self.tls.read_tls(&mut self.stream) { + Ok(0) => { + self.close("the client closed the connection"); + return Vec::new(); + } + Ok(_) => {} + Err(e) if matches!(e.kind(), ErrorKind::WouldBlock | ErrorKind::Interrupted) => return Vec::new(), + Err(e) => { + self.close(&format!("read: {e}")); + return Vec::new(); + } + } + if let Err(e) = self.tls.process_new_packets() { + // rustls has queued an alert; the next flush sends it. + self.close(&format!("TLS: {e}")); + return Vec::new(); + } + let mut events = Vec::new(); + if self.ending.is_some() { + self.drain(); + return events; + } + if self.session.is_none() && !self.tls.is_handshaking() { + let Some(fp) = tls::peer_fingerprint(&self.tls) else { + self.close("no client certificate"); + return events; + }; + self.fingerprint = Some(fp); + // The Hello deadline counts from the accept: TLS and Hello + // share the 10 s. + let (session, out) = Session::new(self.accepted); + self.session = Some(session); + self.apply(out, now, &mut events); + } + let mut buf = vec![0u8; READ_CHUNK]; + while self.session.is_some() && self.ending.is_none() && self.closing.is_none() { + let n = match self.tls.reader().read(&mut buf) { + Ok(0) => { + self.close("the client ended TLS"); + break; + } + Ok(n) => n, + Err(e) if e.kind() == ErrorKind::WouldBlock => break, + Err(e) => { + self.close(&format!("read: {e}")); + break; + } + }; + self.framer.push(&buf[..n]); + self.cut_frames(now, &mut events); + } + events + } + + /// While ending: what the client still sends is read and dropped, + /// until it hangs up. + fn drain(&mut self) { + let mut buf = vec![0u8; READ_CHUNK]; + loop { + match self.tls.reader().read(&mut buf) { + Ok(0) => return self.close("the client hung up"), + Ok(_) => {} + Err(e) if e.kind() == ErrorKind::WouldBlock => return, + Err(e) => return self.close(&format!("read: {e}")), + } + } + } + + fn cut_frames(&mut self, now: Instant, events: &mut Vec) { + while self.ending.is_none() && self.closing.is_none() { + match self.framer.next() { + Ok(Some(payload)) => { + let Some(s) = self.session.as_mut() else { + return; + }; + let out = s.on_payload(&payload, now); + self.apply(out, now, events); + } + Ok(None) => return, + Err(e) => { + self.close(&format!("bad frame: {e:?}")); + return; + } + } + } + } + + fn apply(&mut self, out: Vec, now: Instant, events: &mut Vec) { + for o in out { + match o { + Out::Send(bytes) => self.write(&bytes), + Out::Named { name } => { + self.name = Some(name.clone()); + events.push(Event::Named(name)); + } + Out::Screen { w, h } => { + self.screen = Some((w, h)); + events.push(Event::Screen { w, h }); + } + Out::Close(why) => self.end(why, now), + Out::Clipboard { text } => events.push(Event::Clipboard(text)), + Out::Grabbed => events.push(Event::Grabbed), + } + } + } + + /// The session is over: the client gets [`LINGER`] to read the last + /// message and hang up. + fn end(&mut self, why: &str, now: Instant) { + if self.ending.is_none() && self.closing.is_none() { + self.ending = Some((why.to_string(), now + LINGER)); + } + } + + fn write(&mut self, bytes: &[u8]) { + if self.ending.is_some() || self.closing.is_some() { + return; + } + // rustls buffers a bounded amount of plaintext; a client that does + // not read fills it and is dropped. + match self.tls.writer().write(bytes) { + Ok(n) if n == bytes.len() => {} + Ok(_) => self.close("the client does not read"), + Err(e) => self.close(&format!("write: {e}")), + } + } + + /// The answer to [`Event::Named`]. + pub fn set_verdict(&mut self, v: Verdict, now: Instant) { + let Some(s) = self.session.as_mut() else { + return; + }; + let out = s.set_verdict(v); + if matches!(v, Verdict::Trusted(_)) && !out.is_empty() { + self.trusted = true; + } + self.apply(out, now, &mut Vec::new()); + } + + /// CINN: the pointer enters the client's screen at (x, y). + pub fn enter(&mut self, x: i16, y: i16, mods: u16) { + if let Some(s) = self.session.as_mut() { + let out = s.enter(x, y, mods); + self.apply_sends(out); + } + } + + /// A message for a client that is past the handshake; dropped before. + pub fn send(&mut self, m: Msg) { + if let Some(s) = self.session.as_mut() { + let out = s.send(m); + self.apply_sends(out); + } + } + + /// Turns clipboard sharing on or off (DSOP to an active client). + pub fn set_clipboard(&mut self, on: bool) { + if let Some(s) = self.session.as_mut() { + let out = s.set_clipboard(on); + self.apply_sends(out); + } + } + + /// CCLP and DCLP: the client gets ThinFloe's text. + pub fn clipboard(&mut self, text: &[u8]) { + if let Some(s) = self.session.as_mut() { + let out = s.clipboard(text); + self.apply_sends(out); + } + } + + /// CCLP: the client learns that someone else owns the clipboard. + pub fn grab(&mut self) { + if let Some(s) = self.session.as_mut() { + let out = s.grab(); + self.apply_sends(out); + } + } + + /// The bytes of the session's answer (these calls make no other). + fn apply_sends(&mut self, out: Vec) { + for o in out { + if let Out::Send(bytes) = o { + self.write(&bytes); + } + } + } + + /// Another connection holds this client's name: EBSY, then the end. + pub fn refuse_busy(&mut self, now: Instant) { + if let Some(s) = &self.session { + let bytes = proto::frame(&proto::encode(&Msg::Ebsy, s.minor())); + self.write(&bytes); + } + self.end("a client with this name is connected", now); + } + + /// Time passes: the TLS deadline and the session's timers. + pub fn tick(&mut self, now: Instant) { + if self.closing.is_some() { + return; + } + if let Some((why, until)) = &self.ending { + if now >= *until { + let why = why.clone(); + self.close(&why); + } + return; + } + match self.session.as_mut() { + None => { + if now.saturating_duration_since(self.accepted) >= HANDSHAKE_DEADLINE { + self.close("TLS handshake timed out"); + } + } + Some(s) => { + let out = s.tick(now); + self.apply(out, now, &mut Vec::new()); + } + } + } + + /// Writes what TLS has queued, as far as the socket takes it. + pub fn flush(&mut self) { + while self.tls.wants_write() { + match self.tls.write_tls(&mut self.stream) { + Ok(0) => break, + Ok(_) => {} + Err(e) if e.kind() == ErrorKind::WouldBlock => break, + Err(e) if e.kind() == ErrorKind::Interrupted => {} + Err(e) => { + self.close(&format!("write: {e}")); + break; + } + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::deskflow::proto::{self, Msg}; + use crate::deskflow::tls::testclient; + use crate::deskflow::{ident, tls}; + use std::net::TcpListener; + + fn read_msg(c: &mut impl Read) -> Msg { + let mut len = [0u8; 4]; + c.read_exact(&mut len).unwrap(); + let mut p = vec![0u8; u32::from_be_bytes(len) as usize]; + c.read_exact(&mut p).unwrap(); + proto::decode(&p).unwrap() + } + + #[test] + fn a_clipboard_larger_than_the_tls_default_reaches_the_client() { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let port = listener.local_addr().unwrap().port(); + let client = std::thread::spawn(move || { + let cert = rcgen::generate_simple_self_signed(vec!["big".to_string()]).unwrap(); + let tcp = TcpStream::connect(("127.0.0.1", port)).unwrap(); + tcp.set_read_timeout(Some(Duration::from_secs(5))).unwrap(); + let conn = rustls::ClientConnection::new(testclient::config(&cert), testclient::server_name()).unwrap(); + let mut c = rustls::StreamOwned::new(conn, tcp); + let mut len = [0u8; 4]; + c.read_exact(&mut len).unwrap(); + let mut hello = vec![0u8; u32::from_be_bytes(len) as usize]; + c.read_exact(&mut hello).unwrap(); + let back = Msg::HelloBack { + major: 1, + minor: 8, + name: b"big".to_vec(), + }; + c.write_all(&proto::frame(&proto::encode(&back, 8))).unwrap(); + c.flush().unwrap(); + assert_eq!(read_msg(&mut c), Msg::Qinf); + let mut asm = clipdata::Assembler::default(); + loop { + match read_msg(&mut c) { + Msg::Cclp { .. } => {} + Msg::Dclp { id, seq, mark, data } => { + if let clipdata::Asm::Finished(m) = asm.push(id, seq, mark, &data) { + return clipdata::unmarshal_text(&m).unwrap(); + } + } + m => panic!("{m:?}"), + } + } + }); + let (stream, _) = listener.accept().unwrap(); + let id = ident::load_or_create( + &crate::testdir::TestDir::new("deskflow-conn", "big").join("identity.pem"), + "test", + ) + .unwrap(); + let mut c = Conn::new(1, stream, tls::server_config(&id), Instant::now()).unwrap(); + let text = vec![b'x'; 900 * 1024]; + let mut sent = false; + let end = Instant::now() + Duration::from_secs(10); + while !client.is_finished() && Instant::now() < end { + let now = Instant::now(); + for ev in c.on_readable(now) { + if let Event::Named(_) = ev { + c.set_verdict(Verdict::Trusted(0), now); + } + } + if c.trusted() && !sent { + c.clipboard(&text); + sent = true; + } + c.flush(); + assert_eq!(c.closing(), None); + std::thread::sleep(Duration::from_millis(2)); + } + assert_eq!(client.join().unwrap(), text); + } +} diff --git a/src/thinfloe-menu/src/deskflow/edge.rs b/src/thinfloe-menu/src/deskflow/edge.rs new file mode 100644 index 0000000..fc9d504 --- /dev/null +++ b/src/thinfloe-menu/src/deskflow/edge.rs @@ -0,0 +1,357 @@ +//! Edge geometry of the Deskflow server: the capture strip, the entry point +//! on the device, pointer tracking on the device and edge resistance. + +use crate::kanshi::Side; +use std::time::{Duration, Instant}; + +/// A rectangle in logical pixels of the compositor's layout. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Rect { + pub x: i32, + pub y: i32, + pub w: i32, + pub h: i32, +} + +/// Pause without outward push after which the resistance sum starts again. +const RESISTANCE_RESET: Duration = Duration::from_millis(300); + +/// The 1 px deep strip on the `side` edge of the output (logical pixels, so +/// it covers the whole logical edge of a scaled or rotated output). +pub fn strip_rect(out: Rect, side: Side) -> Rect { + let w = out.w.max(0); + let h = out.h.max(0); + match side { + Side::RightOf => Rect { + x: out.x.saturating_add(w).saturating_sub(1), + y: out.y, + w: w.min(1), + h, + }, + Side::LeftOf => Rect { + x: out.x, + y: out.y, + w: w.min(1), + h, + }, + Side::Above => Rect { + x: out.x, + y: out.y, + w, + h: h.min(1), + }, + Side::Below => Rect { + x: out.x, + y: out.y.saturating_add(h).saturating_sub(1), + w, + h: h.min(1), + }, + } +} + +/// True when no other output touches the `side` edge of `out` along a +/// shared segment. +pub fn edge_free(out: Rect, side: Side, others: &[Rect]) -> bool { + let end = |a: i32, b: i32| i64::from(a) + i64::from(b); + let overlap = |a0: i32, al: i32, b0: i32, bl: i32| i64::from(a0.max(b0)) < end(a0, al).min(end(b0, bl)); + !others.iter().any(|o| match side { + Side::RightOf => end(out.x, out.w) == i64::from(o.x) && overlap(out.y, out.h, o.y, o.h), + Side::LeftOf => end(o.x, o.w) == i64::from(out.x) && overlap(out.y, out.h, o.y, o.h), + Side::Below => end(out.y, out.h) == i64::from(o.y) && overlap(out.x, out.w, o.x, o.w), + Side::Above => end(o.y, o.h) == i64::from(out.y) && overlap(out.x, out.w, o.x, o.w), + }) +} + +fn clamp_i16(v: f64, max: i16) -> i16 { + // `as` saturates and maps NaN to 0. + let v = v.round().clamp(0.0, f64::from(max.max(0))); + v as i16 +} + +/// Where the pointer enters the device when it leaves the output at `at` +/// (absolute logical position): proportional along the edge, on the device's +/// edge opposite the attached one. +pub fn entry_point(out: Rect, side: Side, at: (f64, f64), dev: (i16, i16)) -> (i16, i16) { + let (mx, my) = (dev.0.saturating_sub(1), dev.1.saturating_sub(1)); + let frac = |pos: f64, start: i32, len: i32| { + if len <= 0 { + 0.0 + } else { + ((pos - f64::from(start)) / f64::from(len)).clamp(0.0, 1.0) + } + }; + let ax = frac(at.0, out.x, out.w); + let ay = frac(at.1, out.y, out.h); + match side { + Side::RightOf => (0, clamp_i16(ay * f64::from(dev.1), my)), + Side::LeftOf => (mx.max(0), clamp_i16(ay * f64::from(dev.1), my)), + Side::Below => (clamp_i16(ax * f64::from(dev.0), mx), 0), + Side::Above => (clamp_i16(ax * f64::from(dev.0), mx), my.max(0)), + } +} + +/// Result of one motion on the device. +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum Track { + /// New position, clamped inside the device. + Move(i16, i16), + /// The position crossed the attached edge; `along` is 0..1 along it. + Back { along: f64 }, +} + +/// The pointer's position on the device. +#[derive(Clone, Debug)] +pub struct Tracker { + side: Side, + x: f64, + y: f64, + max: (f64, f64), + dev: (f64, f64), +} + +impl Tracker { + pub fn new(side: Side, start: (i16, i16), dev: (i16, i16)) -> Tracker { + let max = (f64::from(dev.0.max(1) - 1), f64::from(dev.1.max(1) - 1)); + Tracker { + side, + x: f64::from(start.0).clamp(0.0, max.0), + y: f64::from(start.1).clamp(0.0, max.1), + max, + dev: (f64::from(dev.0.max(0)), f64::from(dev.1.max(0))), + } + } + + pub fn motion(&mut self, dx: f64, dy: f64) -> Track { + let (nx, ny) = (self.x + dx, self.y + dy); + let crossed = match self.side { + Side::RightOf => nx < 0.0, + Side::LeftOf => nx > self.max.0, + Side::Below => ny < 0.0, + Side::Above => ny > self.max.1, + }; + if crossed { + let (pos, len) = match self.side { + Side::RightOf | Side::LeftOf => (self.y + dy, self.dev.1), + Side::Below | Side::Above => (self.x + dx, self.dev.0), + }; + let along = if len > 0.0 { (pos / len).clamp(0.0, 1.0) } else { 0.0 }; + return Track::Back { along }; + } + self.x = nx.clamp(0.0, self.max.0); + self.y = ny.clamp(0.0, self.max.1); + Track::Move(clamp_i16(self.x, i16::MAX), clamp_i16(self.y, i16::MAX)) + } +} + +/// Edge resistance: sums the outward push on the strip until it reaches the +/// threshold; the sum starts again after 300 ms without outward push. +#[derive(Clone, Debug)] +pub struct Resistance { + threshold: f64, + sum: f64, + last_outward: Option, +} + +impl Resistance { + pub fn new(threshold_px: f64) -> Resistance { + Resistance { + threshold: threshold_px, + sum: 0.0, + last_outward: None, + } + } + + /// True when this motion pushes outward and the outward sum has reached + /// the threshold; motion inward, sideways or none never fires, so a + /// pointer that came back from the device stays home. + pub fn push(&mut self, side: Side, dx: f64, dy: f64, now: Instant) -> bool { + if let Some(last) = self.last_outward + && now.saturating_duration_since(last) >= RESISTANCE_RESET + { + self.reset(); + } + let outward = match side { + Side::RightOf => dx, + Side::LeftOf => -dx, + Side::Below => dy, + Side::Above => -dy, + }; + if outward <= 0.0 { + return false; + } + self.sum += outward; + self.last_outward = Some(now); + self.sum >= self.threshold + } + + pub fn reset(&mut self) { + self.sum = 0.0; + self.last_outward = None; + } +} + +#[cfg(test)] +mod tests { + use super::*; + + const fn r(x: i32, y: i32, w: i32, h: i32) -> Rect { + Rect { x, y, w, h } + } + + #[test] + fn strip_rects_each_side() { + let o = r(100, 50, 800, 600); + assert_eq!(strip_rect(o, Side::RightOf), r(899, 50, 1, 600)); + assert_eq!(strip_rect(o, Side::LeftOf), r(100, 50, 1, 600)); + assert_eq!(strip_rect(o, Side::Above), r(100, 50, 800, 1)); + assert_eq!(strip_rect(o, Side::Below), r(100, 649, 800, 1)); + } + + #[test] + fn strip_on_scaled_and_rotated_output() { + // 2560x1440 at scale 1.5 is 1707x960 logical. + let s = r(1920, 0, 1707, 960); + assert_eq!(strip_rect(s, Side::RightOf), r(3626, 0, 1, 960)); + assert_eq!(strip_rect(s, Side::Below), r(1920, 959, 1707, 1)); + // Rotated: 1920x1080 turned to 1080x1920. + let p = r(0, 0, 1080, 1920); + assert_eq!(strip_rect(p, Side::RightOf), r(1079, 0, 1, 1920)); + assert_eq!(strip_rect(p, Side::Above), r(0, 0, 1080, 1)); + } + + #[test] + fn edge_between_two_monitors_not_free() { + let a = r(0, 0, 1920, 1080); + let b = r(1920, 0, 1920, 1080); + assert!(!edge_free(a, Side::RightOf, &[b])); + assert!(!edge_free(b, Side::LeftOf, &[a])); + assert!(edge_free(a, Side::LeftOf, &[b])); + assert!(edge_free(b, Side::RightOf, &[a])); + assert!(edge_free(a, Side::Below, &[b])); + // Touching only at a corner shares no segment. + let c = r(1920, 1080, 800, 600); + assert!(edge_free(a, Side::RightOf, &[c])); + // A shorter neighbour still shares part of the edge. + let d = r(1920, 900, 800, 600); + assert!(!edge_free(a, Side::RightOf, &[d])); + let e = r(0, 1080, 100, 100); + assert!(!edge_free(a, Side::Below, &[e])); + assert!(!edge_free(e, Side::Above, &[a])); + } + + #[test] + fn entry_maps_proportionally() { + let o = r(0, 0, 1280, 720); + assert_eq!(entry_point(o, Side::RightOf, (1279.0, 360.0), (1920, 1080)), (0, 540)); + assert_eq!(entry_point(o, Side::LeftOf, (0.0, 360.0), (1920, 1080)), (1919, 540)); + assert_eq!(entry_point(o, Side::Below, (640.0, 719.0), (1920, 1080)), (960, 0)); + assert_eq!(entry_point(o, Side::Above, (640.0, 0.0), (1920, 1080)), (960, 1079)); + // Offset output, position at the far end stays inside the device. + let s = r(1920, 0, 1707, 960); + assert_eq!(entry_point(s, Side::Below, (3627.0, 959.0), (1000, 800)), (999, 0)); + // Degenerate device does not panic. + assert_eq!(entry_point(o, Side::RightOf, (1.0, 1.0), (0, 0)), (0, 0)); + } + + #[test] + fn tracker_clamps_and_comes_back() { + let mut t = Tracker::new(Side::RightOf, (0, 540), (1920, 1080)); + assert_eq!(t.motion(10.0, 0.0), Track::Move(10, 540)); + assert_eq!(t.motion(0.0, 1000.0), Track::Move(10, 1079)); + assert_eq!(t.motion(100000.0, 0.0), Track::Move(1919, 1079)); + assert_eq!(t.motion(-1919.0, -539.0), Track::Move(0, 540)); + match t.motion(-1.0, 0.0) { + Track::Back { along } => assert!((along - 0.5).abs() < 1e-9), + o => panic!("{o:?}"), + } + let mut a = Tracker::new(Side::Above, (100, 1079), (1000, 1080)); + assert_eq!(a.motion(0.0, -5.0), Track::Move(100, 1074)); + assert!(matches!(a.motion(0.0, 10.0), Track::Back { .. })); + let mut z = Tracker::new(Side::LeftOf, (0, 0), (0, 0)); + assert!(matches!(z.motion(1.0, 1.0), Track::Back { .. })); + } + + #[test] + fn resistance_levels() { + for th in [15.0, 40.0, 100.0] { + let mut r = Resistance::new(th); + let t = Instant::now(); + let mut sum = 0.0; + while sum + 5.0 < th { + sum += 5.0; + assert!(!r.push(Side::RightOf, 5.0, 0.0, t)); + } + assert!(!r.push(Side::RightOf, th - sum - 0.5, 0.0, t)); + assert!(r.push(Side::RightOf, 0.5, 0.0, t)); + } + } + + #[test] + fn resistance_ignores_inward_and_sideways() { + let t = Instant::now(); + let mut r = Resistance::new(15.0); + assert!(!r.push(Side::RightOf, 10.0, 0.0, t)); + assert!(!r.push(Side::RightOf, -50.0, 0.0, t)); + assert!(!r.push(Side::RightOf, 0.0, 500.0, t)); + assert!(r.push(Side::RightOf, 5.0, 0.0, t)); + let mut u = Resistance::new(10.0); + assert!(!u.push(Side::Above, 0.0, 9.0, t)); + assert!(u.push(Side::Above, 0.0, -10.0, t)); + let mut l = Resistance::new(10.0); + assert!(l.push(Side::LeftOf, -10.0, 0.0, t)); + let mut b = Resistance::new(10.0); + assert!(b.push(Side::Below, 0.0, 10.0, t)); + } + + #[test] + fn resistance_resets_after_300ms() { + let t = Instant::now(); + let ms = Duration::from_millis; + let mut r = Resistance::new(15.0); + assert!(!r.push(Side::RightOf, 10.0, 0.0, t)); + assert!(r.push(Side::RightOf, 5.0, 0.0, t + ms(299))); + let mut r = Resistance::new(15.0); + assert!(!r.push(Side::RightOf, 10.0, 0.0, t)); + assert!(!r.push(Side::RightOf, 5.0, 0.0, t + ms(300))); + assert!(r.push(Side::RightOf, 10.0, 0.0, t + ms(400))); + // Inward motion does not keep the sum alive. + let mut r = Resistance::new(15.0); + assert!(!r.push(Side::RightOf, 10.0, 0.0, t)); + assert!(!r.push(Side::RightOf, -1.0, 0.0, t + ms(200))); + assert!(!r.push(Side::RightOf, 5.0, 0.0, t + ms(350))); + r.reset(); + assert!(!r.push(Side::RightOf, 14.0, 0.0, t)); + } + + #[test] + fn resistance_off_fires_at_once_on_outward_motion() { + let t = Instant::now(); + let mut r = Resistance::new(0.0); + assert!(r.push(Side::RightOf, 0.1, 0.0, t)); + let mut r = Resistance::new(0.0); + assert!(r.push(Side::Above, 0.0, -1.0, t)); + } + + #[test] + fn inward_sideways_and_still_never_fire_at_any_level() { + // After a release by moving back the pointer is still on the strip: + // only a push outward may begin the next capture. + let t = Instant::now(); + for th in [0.0, 15.0, 40.0, 100.0] { + for side in [Side::RightOf, Side::LeftOf, Side::Above, Side::Below] { + let mut r = Resistance::new(th); + let (ox, oy) = match side { + Side::RightOf => (1.0, 0.0), + Side::LeftOf => (-1.0, 0.0), + Side::Below => (0.0, 1.0), + Side::Above => (0.0, -1.0), + }; + for _ in 0..50 { + assert!(!r.push(side, 0.0, 0.0, t), "still, {th} {side:?}"); + assert!(!r.push(side, -ox * 200.0, -oy * 200.0, t), "inward, {th} {side:?}"); + assert!(!r.push(side, oy * 200.0, ox * 200.0, t), "sideways, {th} {side:?}"); + } + } + } + } +} diff --git a/src/thinfloe-menu/src/deskflow/forward.rs b/src/thinfloe-menu/src/deskflow/forward.rs new file mode 100644 index 0000000..931cc8a --- /dev/null +++ b/src/thinfloe-menu/src/deskflow/forward.rs @@ -0,0 +1,745 @@ +//! The captured state of the Deskflow server: while a device has the +//! keyboard and the pointer, their events become its messages, and every +//! way back first releases on the device what was sent down (spec, Edge +//! capture and the way back, Keyboard). Pure: events and the time go in, +//! messages come out; the daemon (`run.rs`) sends them and ends the capture. + +use std::time::{Duration, Instant}; + +use super::capture::CapEvent; +use super::edge::{Track, Tracker}; +use super::keymap::{self, Xkb}; +use super::proto::Msg; + +/// Escape's keysym: with Ctrl, Alt and Shift down it releases. +const XK_ESCAPE: u32 = 0xff1b; +/// The microphone mute key stays on ThinFloe: Deskflow has no key id for +/// it, and the device's microphone is not the one at the desk. +const XF86_AUDIO_MIC_MUTE: u32 = 0x1008_ffb2; + +// The escape chord's keys, linux/input-event-codes.h: what decides it +// when the keymap could not be read. +const KEY_ESC: u32 = 1; +const KEY_LEFTCTRL: u32 = 29; +const KEY_RIGHTCTRL: u32 = 97; +const KEY_LEFTALT: u32 = 56; +const KEY_RIGHTALT: u32 = 100; +const KEY_LEFTSHIFT: u32 = 42; +const KEY_RIGHTSHIFT: u32 = 54; + +// Pointer buttons, linux/input-event-codes.h. +const BTN_LEFT: u32 = 0x110; +const BTN_RIGHT: u32 = 0x111; +const BTN_MIDDLE: u32 = 0x112; +const BTN_SIDE: u32 = 0x113; +const BTN_EXTRA: u32 = 0x114; + +/// Deskflow's id of a pointer button, from `src/lib/deskflow/MouseTypes.h` +/// at commit 80221f0: left 1, middle 2, right 3, the two extra buttons 4 +/// and 5. (The comment in the protocol header swaps 2 and 3; the header +/// with the constants wins.) Other buttons have no id. +pub fn button_id(evdev: u32) -> Option { + Some(match evdev { + BTN_LEFT => 1, + BTN_MIDDLE => 2, + BTN_RIGHT => 3, + BTN_SIDE => 4, + BTN_EXTRA => 5, + _ => return None, + }) +} + +/// What the daemon does with the result of an event. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Action { + /// A message for the captured device. + Send(Msg), + /// End the capture ([`release`] first). + Release(&'static str), + /// The microphone mute key was released: ThinFloe's microphone. + LocalMicMute, +} + +/// The keyboard as the compositor describes it: its keymap and modifier +/// state, and the key repeat it asks for. +#[derive(Default)] +pub struct Keyboard { + xkb: Option, + /// Repeats per second (0: none) and the delay before the first, in ms. + rate: i32, + delay: i32, + /// The evdev codes of the keys down, as the key events tell. + down: Vec, +} + +impl Keyboard { + /// Takes a keymap, modifier or repeat event; true when `ev` was one. + pub fn update(&mut self, ev: &CapEvent) -> bool { + match ev { + CapEvent::Key { code, pressed } => { + self.down.retain(|c| c != code); + if *pressed { + self.down.push(*code); + } + return false; + } + CapEvent::Unlocked | CapEvent::KeyboardLeft => { + self.down.clear(); + return false; + } + CapEvent::Keymap { fd, size } => { + self.xkb = match Xkb::from_keymap_fd(fd, *size) { + Ok(x) => Some(x), + Err(e) => { + eprintln!("thinfloe-deskflow: keymap: {e}"); + None + } + }; + } + CapEvent::Modifiers { + depressed, + latched, + locked, + group, + } => { + if let Some(x) = self.xkb.as_mut() { + x.update_mask(*depressed, *latched, *locked, *group); + } + } + CapEvent::RepeatInfo { rate, delay } => (self.rate, self.delay) = (*rate, *delay), + _ => return false, + } + true + } + + /// The `KeyModifierMask` of the modifiers down now. + pub fn mask(&self) -> u16 { + self.xkb.as_ref().map_or(0, |x| x.mods().mask()) + } + + /// The key id of a key in the current state; when its keysym has none + /// (`XF86Switch_VT_1` under Ctrl+Alt), the id of its first-level keysym, + /// as Deskflow does, so Ctrl+Alt+F1 reaches the device as F1. + fn key_id(&self, code: u32) -> Option { + let x = self.xkb.as_ref()?; + keymap::key_id(x.keysym(code), x.utf32(code)).or_else(|| keymap::key_id(x.keysym_level0(code), 0)) + } + + /// Escape while Ctrl, Alt and Shift are down. Without a keymap the + /// evdev codes decide, so the way back never depends on it. + fn escape_chord(&self, code: u32) -> bool { + let Some(x) = self.xkb.as_ref() else { + let down = |a: u32, b: u32| self.down.iter().any(|c| *c == a || *c == b); + return code == KEY_ESC + && down(KEY_LEFTCTRL, KEY_RIGHTCTRL) + && down(KEY_LEFTALT, KEY_RIGHTALT) + && down(KEY_LEFTSHIFT, KEY_RIGHTSHIFT); + }; + let m = x.mods(); + m.ctrl && m.alt && m.shift && (x.keysym(code) == XK_ESCAPE || x.keysym_level0(code) == XK_ESCAPE) + } + + /// The key is the microphone mute key, at any level. + fn mic_mute(&self, code: u32) -> bool { + self.xkb + .as_ref() + .is_some_and(|x| x.keysym(code) == XF86_AUDIO_MIC_MUTE || x.keysym_level0(code) == XF86_AUDIO_MIC_MUTE) + } + + /// The repeat period and delay for a key, when it repeats. + fn repeat_of(&self, code: u32) -> Option<(Duration, Duration)> { + let x = self.xkb.as_ref()?; + if self.rate <= 0 || !x.repeats(code) { + return None; + } + let every = Duration::from_secs(1) / self.rate.unsigned_abs(); + Some(( + every, + Duration::from_millis(u64::from(self.delay.max(0).unsigned_abs())), + )) + } +} + +/// The key that repeats: the last one pressed, while it is down. +#[derive(Debug)] +struct Repeat { + id: u16, + button: u16, + next: Instant, + every: Duration, +} + +/// A device that has the keyboard and the pointer. +#[derive(Debug)] +pub struct Active { + /// The connection's id. + pub device: usize, + pub tracker: Tracker, + /// (key id, button) of each key sent down and not up yet. + pub held: Vec<(u16, u16)>, + /// The pointer buttons sent down. + buttons: Vec, + /// The position last sent. + pos: (i16, i16), + repeat: Option, + /// The microphone mute key went down during the capture. + mic_down: bool, +} + +impl Active { + /// The pointer entered the device at `at` (the CINN position). + pub fn new(device: usize, tracker: Tracker, at: (i16, i16)) -> Active { + Active { + device, + tracker, + held: Vec::new(), + buttons: Vec::new(), + pos: at, + repeat: None, + mic_down: false, + } + } + + /// When [`tick`] has the next repeat to send. + pub fn deadline(&self) -> Option { + self.repeat.as_ref().map(|r| r.next) + } +} + +/// One event while captured. Keymap, modifier and repeat events update +/// `kb`; a key or button released that was never sent down is dropped. +pub fn on_cap_event(a: &mut Active, ev: &CapEvent, kb: &mut Keyboard, now: Instant) -> Vec { + if kb.update(ev) { + return Vec::new(); + } + match *ev { + CapEvent::Relative { dx, dy, .. } => { + if !dx.is_finite() || !dy.is_finite() { + return Vec::new(); + } + match a.tracker.motion(dx, dy) { + Track::Back { .. } => vec![Action::Release("back")], + Track::Move(x, y) if (x, y) != a.pos => { + a.pos = (x, y); + vec![Action::Send(Msg::MouseMove { x, y })] + } + Track::Move(..) => Vec::new(), + } + } + CapEvent::Button { button, pressed } => { + let Some(id) = button_id(button) else { + return Vec::new(); + }; + let down = a.buttons.iter().position(|b| *b == id); + match (pressed, down) { + (true, None) => { + a.buttons.push(id); + vec![Action::Send(Msg::MouseDown(id))] + } + (false, Some(i)) => { + a.buttons.remove(i); + vec![Action::Send(Msg::MouseUp(id))] + } + _ => Vec::new(), + } + } + CapEvent::Axis { v120_x, v120_y } => { + // Deskflow: positive is right and up; Wayland's vertical axis + // is positive down. + let clamp = |v: i32| v.clamp(i32::from(i16::MIN), i32::from(i16::MAX)) as i16; + vec![Action::Send(Msg::Wheel { + dx: clamp(v120_x), + dy: clamp(v120_y.saturating_neg()), + })] + } + CapEvent::Key { code, pressed: true } => key_down(a, kb, code, now), + CapEvent::Key { code, pressed: false } => key_up(a, kb, code), + CapEvent::Unlocked => vec![Action::Release("unlocked")], + CapEvent::KeyboardLeft => vec![Action::Release("keyboard left")], + _ => Vec::new(), + } +} + +fn key_down(a: &mut Active, kb: &Keyboard, code: u32, now: Instant) -> Vec { + if kb.escape_chord(code) { + return vec![Action::Release("escape chord")]; + } + if kb.mic_mute(code) { + a.mic_down = true; + return Vec::new(); + } + let button = keymap::button(code); + let Some(id) = kb.key_id(code) else { + return Vec::new(); + }; + if a.held.iter().any(|h| h.1 == button) { + return Vec::new(); + } + a.held.push((id, button)); + // A key that does not repeat (a modifier) leaves the repeat of the + // key held, as the X server does. + if let Some((every, delay)) = kb.repeat_of(code) { + a.repeat = Some(Repeat { + id, + button, + next: now + delay, + every, + }); + } + vec![Action::Send(Msg::KeyDown { + id, + mods: kb.mask(), + button, + })] +} + +fn key_up(a: &mut Active, kb: &Keyboard, code: u32) -> Vec { + // On the release, as labwc's binding (onRelease); a press before the + // capture was ThinFloe's. + if kb.mic_mute(code) { + return if std::mem::take(&mut a.mic_down) { + vec![Action::LocalMicMute] + } else { + Vec::new() + }; + } + let button = keymap::button(code); + let Some(i) = a.held.iter().position(|h| h.1 == button) else { + return Vec::new(); + }; + let (id, _) = a.held.remove(i); + if a.repeat.as_ref().is_some_and(|r| r.button == button) { + a.repeat = None; + } + vec![Action::Send(Msg::KeyUp { + id, + mods: kb.mask(), + button, + })] +} + +/// Time passes: the repeats due for the key held, as one DKRP with their +/// count, as Deskflow sends them. +pub fn tick(a: &mut Active, kb: &Keyboard, now: Instant) -> Vec { + let Some(r) = a.repeat.as_mut() else { + return Vec::new(); + }; + if now < r.next { + return Vec::new(); + } + let late = now.duration_since(r.next).as_nanos() / r.every.as_nanos().max(1); + let count = u16::try_from(late + 1).unwrap_or(u16::MAX); + r.next += r.every * u32::from(count); + vec![Action::Send(Msg::KeyRepeat { + id: r.id, + mods: kb.mask(), + count, + button: r.button, + })] +} + +/// The messages that end a capture on the device: DKUP for every key sent +/// down, DMUP for every button, then COUT. +pub fn release(a: &mut Active, kb: &Keyboard) -> Vec { + let mods = kb.mask(); + let mut out: Vec = a + .held + .drain(..) + .rev() + .map(|(id, button)| Msg::KeyUp { id, mods, button }) + .collect(); + out.extend(a.buttons.drain(..).rev().map(Msg::MouseUp)); + a.repeat = None; + out.push(Msg::Cout); + out +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::kanshi::Side; + + const KEY_A: u32 = 30; + const KEY_F1: u32 = 59; + // Real modifier bits of an XKB keymap. + const SHIFT: u32 = 1; + const CONTROL: u32 = 4; + const MOD1: u32 = 8; + + fn us() -> Keyboard { + Keyboard { + xkb: Some( + Xkb::from_layout("us").expect("libxkbcommon and the xkeyboard-config data are needed for this test"), + ), + rate: 25, + delay: 600, + down: Vec::new(), + } + } + + fn active() -> Active { + Active::new(7, Tracker::new(Side::RightOf, (0, 540), (1920, 1080)), (0, 540)) + } + + fn key(code: u32, pressed: bool) -> CapEvent { + CapEvent::Key { code, pressed } + } + + fn mods(depressed: u32) -> CapEvent { + CapEvent::Modifiers { + depressed, + latched: 0, + locked: 0, + group: 0, + } + } + + /// Feeds the events; a Release ends the run with the release messages. + fn run(a: &mut Active, kb: &mut Keyboard, evs: &[CapEvent]) -> (Vec, Option<&'static str>) { + let now = Instant::now(); + let mut out = Vec::new(); + for ev in evs { + for act in on_cap_event(a, ev, kb, now) { + match act { + Action::Send(m) => out.push(m), + Action::Release(why) => { + out.extend(release(a, kb)); + return (out, Some(why)); + } + Action::LocalMicMute => {} + } + } + } + (out, None) + } + + fn down(id: u16, mods: u16, code: u32) -> Msg { + Msg::KeyDown { + id, + mods, + button: keymap::button(code), + } + } + + fn up(id: u16, mods: u16, code: u32) -> Msg { + Msg::KeyUp { + id, + mods, + button: keymap::button(code), + } + } + + #[test] + fn mic_mute_release_is_local_and_not_sent() { + // linux/input-event-codes.h + const KEY_VOLUMEUP: u32 = 115; + const KEY_MICMUTE: u32 = 248; + let (mut a, mut kb) = (active(), us()); + let now = Instant::now(); + assert_eq!(on_cap_event(&mut a, &key(KEY_MICMUTE, true), &mut kb, now), Vec::new()); + assert_eq!( + on_cap_event(&mut a, &key(KEY_MICMUTE, false), &mut kb, now), + vec![Action::LocalMicMute] + ); + // A release whose press the capture did not see does nothing. + assert_eq!(on_cap_event(&mut a, &key(KEY_MICMUTE, false), &mut kb, now), Vec::new()); + // The volume keys go to the device: kKeyAudioUp. + let (out, why) = run(&mut a, &mut kb, &[key(KEY_VOLUMEUP, true), key(KEY_VOLUMEUP, false)]); + assert_eq!(why, None); + assert_eq!(out, vec![down(0xE0AF, 0, KEY_VOLUMEUP), up(0xE0AF, 0, KEY_VOLUMEUP)]); + assert_eq!(release(&mut a, &kb), vec![Msg::Cout]); + } + + #[test] + fn release_sends_up_for_held_keys() { + let (mut a, mut kb) = (active(), us()); + let evs = [ + key(KEY_A, true), + key(KEY_LEFTCTRL, true), + mods(CONTROL), + key(KEY_LEFTALT, true), + mods(CONTROL | MOD1), + key(KEY_LEFTSHIFT, true), + mods(CONTROL | MOD1 | SHIFT), + key(KEY_ESC, true), + ]; + let (out, why) = run(&mut a, &mut kb, &evs); + assert_eq!(why, Some("escape chord")); + // Ctrl, Alt and Shift: kKeyControl_L, kKeyAlt_L, kKeyShift_L. + let all = 0x0001 | 0x0002 | 0x0004; + assert_eq!( + out, + [ + down(0x61, 0, KEY_A), + down(0xEFE3, 0, KEY_LEFTCTRL), + down(0xEFE9, 0x0002, KEY_LEFTALT), + down(0xEFE1, 0x0006, KEY_LEFTSHIFT), + up(0xEFE1, all, KEY_LEFTSHIFT), + up(0xEFE9, all, KEY_LEFTALT), + up(0xEFE3, all, KEY_LEFTCTRL), + up(0x61, all, KEY_A), + Msg::Cout, + ] + ); + assert!( + !out.iter() + .any(|m| matches!(m, Msg::KeyDown { id: 0xEF1B, .. } | Msg::KeyUp { id: 0xEF1B, .. })) + ); + assert!(a.held.is_empty()); + } + + #[test] + fn a_key_never_sent_down_is_never_sent_up() { + let (mut a, mut kb) = (active(), us()); + // Pressed before the lock (held back by the capture): only its + // release arrives. + let (out, _) = run(&mut a, &mut kb, &[key(KEY_A, false)]); + assert_eq!(out, []); + // A key that has no id goes neither down nor up. + const KEY_MICMUTE: u32 = 248; + let (out, _) = run(&mut a, &mut kb, &[key(KEY_MICMUTE, true), key(KEY_MICMUTE, false)]); + assert_eq!(out, []); + let (out, _) = run( + &mut a, + &mut kb, + &[key(KEY_A, true), key(KEY_A, false), key(KEY_A, false)], + ); + assert_eq!(out, [down(0x61, 0, KEY_A), up(0x61, 0, KEY_A)]); + assert_eq!(release(&mut a, &kb), [Msg::Cout]); + } + + #[test] + fn the_key_up_carries_the_id_of_its_key_down() { + let (mut a, mut kb) = (active(), us()); + let evs = [ + key(KEY_LEFTSHIFT, true), + mods(SHIFT), + key(KEY_A, true), + key(KEY_LEFTSHIFT, false), + mods(0), + key(KEY_A, false), + ]; + let (out, _) = run(&mut a, &mut kb, &evs); + assert_eq!( + out, + [ + down(0xEFE1, 0, KEY_LEFTSHIFT), + down(0x41, 0x0001, KEY_A), + up(0xEFE1, 0x0001, KEY_LEFTSHIFT), + up(0x41, 0, KEY_A), + ] + ); + } + + #[test] + fn ctrl_alt_f1_reaches_the_device_as_f1() { + let (mut a, mut kb) = (active(), us()); + let (out, _) = run(&mut a, &mut kb, &[mods(CONTROL | MOD1), key(KEY_F1, true)]); + assert_eq!(out, [down(0xEFBE, 0x0006, KEY_F1)]); + } + + #[test] + fn escape_alone_or_with_two_modifiers_is_forwarded() { + let (mut a, mut kb) = (active(), us()); + let (out, why) = run( + &mut a, + &mut kb, + &[key(KEY_ESC, true), mods(CONTROL | MOD1), key(KEY_ESC, true)], + ); + assert_eq!(why, None); + assert_eq!(out, [down(0xEF1B, 0, KEY_ESC)]); + } + + #[test] + fn buttons_have_deskflows_ids_and_are_released() { + let (mut a, mut kb) = (active(), us()); + let b = |button, pressed| CapEvent::Button { button, pressed }; + let evs = [ + b(BTN_LEFT, true), + b(BTN_LEFT, false), + b(BTN_MIDDLE, true), + b(BTN_RIGHT, true), + b(BTN_RIGHT, false), + b(BTN_SIDE, true), + b(BTN_SIDE, false), + b(BTN_EXTRA, true), + b(0x115, true), + b(BTN_LEFT, false), + ]; + let (out, _) = run(&mut a, &mut kb, &evs); + use Msg::{MouseDown as Dn, MouseUp as Up}; + assert_eq!(out, [Dn(1), Up(1), Dn(2), Dn(3), Up(3), Dn(4), Up(4), Dn(5)]); + assert_eq!(release(&mut a, &kb), [Up(5), Up(2), Msg::Cout]); + } + + #[test] + fn the_wheel_is_positive_up_and_right() { + let (mut a, mut kb) = (active(), us()); + let (out, _) = run( + &mut a, + &mut kb, + &[ + CapEvent::Axis { v120_x: 0, v120_y: 120 }, + CapEvent::Axis { + v120_x: -240, + v120_y: -60, + }, + CapEvent::Axis { + v120_x: i32::MAX, + v120_y: i32::MIN, + }, + ], + ); + assert_eq!( + out, + [ + Msg::Wheel { dx: 0, dy: -120 }, + Msg::Wheel { dx: -240, dy: 60 }, + Msg::Wheel { + dx: i16::MAX, + dy: i16::MAX + }, + ] + ); + } + + fn rel(dx: f64, dy: f64) -> CapEvent { + CapEvent::Relative { + dx, + dy, + dx_unaccel: dx / 2.0, + dy_unaccel: dy / 2.0, + } + } + + #[test] + fn motion_moves_the_device_pointer_until_it_crosses_back() { + let (mut a, mut kb) = (active(), us()); + let evs = [ + rel(10.0, 5.0), + rel(0.0, 0.0), + rel(f64::NAN, 1.0), + rel(1.0, f64::INFINITY), + rel(-5.0, 0.0), + rel(-6.0, 0.0), + rel(10.0, 0.0), + ]; + let (out, why) = run(&mut a, &mut kb, &evs); + assert_eq!(why, Some("back")); + assert_eq!( + out, + [ + Msg::MouseMove { x: 10, y: 545 }, + Msg::MouseMove { x: 5, y: 545 }, + Msg::Cout + ] + ); + } + + #[test] + fn the_lock_going_or_the_keyboard_leaving_releases() { + for (ev, why) in [ + (CapEvent::Unlocked, "unlocked"), + (CapEvent::KeyboardLeft, "keyboard left"), + ] { + let (mut a, mut kb) = (active(), us()); + let (out, w) = run(&mut a, &mut kb, &[key(KEY_A, true), ev]); + assert_eq!(w, Some(why)); + assert_eq!(out, [down(0x61, 0, KEY_A), up(0x61, 0, KEY_A), Msg::Cout]); + } + } + + #[test] + fn a_held_key_repeats_at_the_rate_the_compositor_gives() { + let (mut a, mut kb) = (active(), us()); + assert!(kb.update(&CapEvent::RepeatInfo { rate: 20, delay: 500 })); + let t = Instant::now(); + on_cap_event(&mut a, &key(KEY_A, true), &mut kb, t); + let ms = Duration::from_millis; + assert_eq!(a.deadline(), Some(t + ms(500))); + assert_eq!(tick(&mut a, &kb, t + ms(499)), []); + let rp = |count| { + vec![Action::Send(Msg::KeyRepeat { + id: 0x61, + mods: 0, + count, + button: keymap::button(KEY_A), + })] + }; + assert_eq!(tick(&mut a, &kb, t + ms(500)), rp(1)); + assert_eq!(tick(&mut a, &kb, t + ms(520)), []); + // A late loop sends the repeats it missed as one count. + assert_eq!(tick(&mut a, &kb, t + ms(710)), rp(4)); + assert_eq!(a.deadline(), Some(t + ms(750))); + on_cap_event(&mut a, &key(KEY_A, false), &mut kb, t + ms(720)); + assert_eq!(a.deadline(), None); + // Modifiers do not repeat, nor anything at rate 0. + on_cap_event(&mut a, &key(KEY_LEFTSHIFT, true), &mut kb, t); + assert_eq!(a.deadline(), None); + kb.update(&CapEvent::RepeatInfo { rate: 0, delay: 500 }); + on_cap_event(&mut a, &key(KEY_A, true), &mut kb, t); + assert_eq!(a.deadline(), None); + } + + #[test] + fn without_a_keymap_the_escape_chord_still_releases() { + for (c, al, sh) in [ + (KEY_LEFTCTRL, KEY_LEFTALT, KEY_LEFTSHIFT), + (KEY_RIGHTCTRL, KEY_RIGHTALT, KEY_RIGHTSHIFT), + ] { + let mut a = active(); + let mut kb = Keyboard::default(); + let evs = [key(c, true), key(al, true), key(sh, true), key(KEY_ESC, true)]; + let (out, why) = run(&mut a, &mut kb, &evs); + assert_eq!(why, Some("escape chord")); + assert_eq!(out, [Msg::Cout]); + } + // Two of the three, or a modifier let go, is no chord. + let mut a = active(); + let mut kb = Keyboard::default(); + let evs = [ + key(KEY_LEFTCTRL, true), + key(KEY_LEFTALT, true), + key(KEY_ESC, true), + key(KEY_LEFTSHIFT, true), + key(KEY_LEFTSHIFT, false), + key(KEY_ESC, true), + ]; + assert_eq!(run(&mut a, &mut kb, &evs).1, None); + } + + #[test] + fn a_modifier_pressed_does_not_stop_the_repeat_of_a_held_key() { + const KEY_RIGHT: u32 = 106; + let (mut a, mut kb) = (active(), us()); + let t = Instant::now(); + let ms = Duration::from_millis; + on_cap_event(&mut a, &key(KEY_RIGHT, true), &mut kb, t); + assert_eq!(a.deadline(), Some(t + ms(600))); + on_cap_event(&mut a, &key(KEY_LEFTSHIFT, true), &mut kb, t + ms(100)); + on_cap_event(&mut a, &mods(SHIFT), &mut kb, t + ms(100)); + assert_eq!(a.deadline(), Some(t + ms(600))); + match tick(&mut a, &kb, t + ms(600)).as_slice() { + [ + Action::Send(Msg::KeyRepeat { + mods, button, count: 1, .. + }), + ] => { + assert_eq!(*button, keymap::button(KEY_RIGHT)); + assert_eq!(*mods, 0x0001); + } + o => panic!("{o:?}"), + } + // Another key that repeats takes the repeat over. + on_cap_event(&mut a, &key(KEY_A, true), &mut kb, t + ms(700)); + assert_eq!(a.deadline(), Some(t + ms(1300))); + } + + #[test] + fn without_a_keymap_no_key_is_sent() { + let mut a = active(); + let mut kb = Keyboard::default(); + let (out, _) = run(&mut a, &mut kb, &[key(KEY_A, true), mods(SHIFT), key(KEY_A, false)]); + assert_eq!(out, []); + } +} diff --git a/src/thinfloe-menu/src/deskflow/ident.rs b/src/thinfloe-menu/src/deskflow/ident.rs new file mode 100644 index 0000000..e1c3851 --- /dev/null +++ b/src/thinfloe-menu/src/deskflow/ident.rs @@ -0,0 +1,312 @@ +//! ThinFloe's own TLS identity for the Deskflow server (spec, Identity +//! and pairing): a self-signed ECDSA P-256 certificate and its key in one +//! PEM file, and the fingerprint forms the user compares with what the +//! Deskflow client shows. + +use std::fs; +use std::os::unix::fs::DirBuilderExt; +use std::path::Path; +use std::sync::Arc; + +use rustls::pki_types::pem::PemObject; +use rustls::pki_types::{CertificateDer, PrivateKeyDer, PrivatePkcs8KeyDer}; + +/// The largest identity file read: a P-256 key and certificate take about +/// 1 KiB. +const IDENTITY_MAX: u64 = 64 * 1024; +/// The certificate's validity, fixed: a first boot with a clock that is +/// off must not shorten a certificate that is kept for good. Deskflow +/// clients do not check the dates (their verify callback accepts any +/// certificate; trust is the fingerprint). +const NOT_BEFORE: (i32, u8, u8) = (2000, 1, 1); +const NOT_AFTER: (i32, u8, u8) = (2099, 12, 31); +/// The prefix of a fingerprint, as Deskflow writes it in its trust files. +const FP_PREFIX: &str = "v2:sha256:"; + +/// ThinFloe's certificate and its PKCS#8 private key, both DER. +pub struct Identity { + pub cert_der: Vec, + pub key_der: Vec, +} + +/// The identity in `path`, made and stored there (directory 0700 when it is +/// created, file 0600) when there is none. A file that does not hold a +/// certificate and its matching key is an error and is left as it is: a +/// new identity would make every client distrust ThinFloe. +pub fn load_or_create(path: &Path, hostname: &str) -> Result { + let shown = crate::atomic::home_relative(path); + if let Some(bytes) = crate::atomic::read(path, IDENTITY_MAX).map_err(|e| format!("{shown}: {e}"))? { + return parse(&bytes).map_err(|e| format!("{shown}: {e}")); + } + let (id, pem) = generate(hostname)?; + if let Some(dir) = path.parent() + && !dir.exists() + { + fs::DirBuilder::new() + .recursive(true) + .mode(0o700) + .create(dir) + .map_err(|e| format!("{}: {e}", crate::atomic::home_relative(dir)))?; + } + crate::atomic::write(path, pem.as_bytes(), 0o600).map_err(|e| format!("{shown}: {e}"))?; + Ok(id) +} + +/// A new identity and its PEM text (certificate, then key). +fn generate(hostname: &str) -> Result<(Identity, String), String> { + let err = |e: rcgen::Error| format!("making the certificate: {e}"); + let key = rcgen::KeyPair::generate_for(&rcgen::PKCS_ECDSA_P256_SHA256).map_err(err)?; + let mut params = rcgen::CertificateParams::new(Vec::::new()).map_err(err)?; + let mut dn = rcgen::DistinguishedName::new(); + dn.push(rcgen::DnType::CommonName, format!("ThinFloe {hostname}")); + params.distinguished_name = dn; + params.not_before = rcgen::date_time_ymd(NOT_BEFORE.0, NOT_BEFORE.1, NOT_BEFORE.2); + params.not_after = rcgen::date_time_ymd(NOT_AFTER.0, NOT_AFTER.1, NOT_AFTER.2); + let cert = params.self_signed(&key).map_err(err)?; + let pem = format!("{}{}", cert.pem(), key.serialize_pem()); + let id = Identity { + cert_der: cert.der().to_vec(), + key_der: key.serialize_der(), + }; + Ok((id, pem)) +} + +/// The identity in a PEM file's bytes; the key must belong to the +/// certificate, so the server config built from it cannot fail. +fn parse(pem: &[u8]) -> Result { + let cert = CertificateDer::from_pem_slice(pem).map_err(|e| format!("no certificate: {e}"))?; + let key = PrivatePkcs8KeyDer::from_pem_slice(pem).map_err(|e| format!("no PKCS#8 key: {e}"))?; + let id = Identity { + cert_der: cert.as_ref().to_vec(), + key_der: key.secret_pkcs8_der().to_vec(), + }; + let provider = Arc::new(rustls::crypto::ring::default_provider()); + rustls::sign::CertifiedKey::from_der(vec![cert], PrivateKeyDer::Pkcs8(key), &provider) + .map_err(|e| format!("unusable key: {e}"))?; + Ok(id) +} + +/// The fingerprint of a DER certificate as Deskflow writes it: +/// `v2:sha256:` and the SHA-256 in lowercase hex. +pub fn fingerprint(der: &[u8]) -> String { + let digest = ring::digest::digest(&ring::digest::SHA256, der); + let mut s = String::with_capacity(FP_PREFIX.len() + 64); + s.push_str(FP_PREFIX); + for b in digest.as_ref() { + s.push_str(&format!("{b:02x}")); + } + s +} + +/// The hex digits of a fingerprint, with or without its prefix. +fn fp_hex(fp: &str) -> &str { + fp.strip_prefix(FP_PREFIX).unwrap_or(fp) +} + +/// The fingerprint as Deskflow's dialogs show it: uppercase hex, the bytes +/// joined by colons (`BA:78:16:...`). +pub fn colon_hex(fp: &str) -> String { + let hex = fp_hex(fp).to_ascii_uppercase(); + let pairs: Vec<&str> = hex + .as_bytes() + .chunks(2) + .filter_map(|p| std::str::from_utf8(p).ok()) + .collect(); + pairs.join(":") +} + +/// The fingerprint's digest bytes; `None` for anything but pairs of hex +/// digits. +fn digest_bytes(fp: &str) -> Option> { + let hex = fp_hex(fp).as_bytes(); + if !hex.len().is_multiple_of(2) { + return None; + } + hex.chunks(2) + .map(|p| u8::from_str_radix(std::str::from_utf8(p).ok()?, 16).ok()) + .collect() +} + +/// Columns and rows of the random-art field. +const ART_W: usize = 17; +const ART_H: usize = 9; +/// A cell's symbol by how often the walk visited it; the last two mark +/// the start and the end. +const ART_SYMBOLS: [char; 17] = [ + ' ', '.', 'o', '+', '=', '*', 'B', 'O', 'X', '@', '%', '&', '#', '/', '^', 'S', 'E', +]; + +/// The fingerprint as Deskflow's random-art picture: 11 lines of 19 +/// characters, a box around a 17 x 9 field. An algorithm port of +/// `generateFingerprintArt` in Deskflow's `src/lib/net/SecureUtils.cpp` +/// (commit 80221f0), the OpenSSH "drunken bishop": from the middle of the +/// field each byte of the digest, low bits first, gives four diagonal +/// steps (bit 0 right or left, bit 1 down or up), clamped at the border; +/// each visit counts up in its cell, to at most 14. A fingerprint that is +/// not hex draws an empty field. +pub fn random_art(fp: &str) -> Vec { + let start = ART_SYMBOLS.len() - 2; + let end = ART_SYMBOLS.len() - 1; + let mut field = [[0usize; ART_H]; ART_W]; + let (mut x, mut y) = (ART_W / 2, ART_H / 2); + for byte in digest_bytes(fp).unwrap_or_default() { + let mut bits = byte; + for _ in 0..4 { + x = if bits & 1 != 0 { + (x + 1).min(ART_W - 1) + } else { + x.saturating_sub(1) + }; + y = if bits & 2 != 0 { + (y + 1).min(ART_H - 1) + } else { + y.saturating_sub(1) + }; + if field[x][y] < start - 1 { + field[x][y] += 1; + } + bits >>= 2; + } + } + field[ART_W / 2][ART_H / 2] = start; + field[x][y] = end; + + let bar = "═".repeat(ART_W); + let mut lines = Vec::with_capacity(ART_H + 2); + lines.push(format!("╔{bar}╗")); + for row in 0..ART_H { + let cells: String = (0..ART_W).map(|col| ART_SYMBOLS[field[col][row]]).collect(); + lines.push(format!("║{cells}║")); + } + lines.push(format!("╚{bar}╝")); + lines +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::testdir::TestDir; + use std::os::unix::fs::PermissionsExt; + + #[test] + fn create_then_load_same_fingerprint() { + let d = TestDir::new("deskflow-ident", "reload"); + let path = d.join("deskflow/identity.pem"); + let made = load_or_create(&path, "host-a").unwrap(); + let loaded = load_or_create(&path, "host-b").unwrap(); + assert_eq!(fingerprint(&made.cert_der), fingerprint(&loaded.cert_der)); + assert_eq!(made.cert_der, loaded.cert_der); + assert_eq!(made.key_der, loaded.key_der); + } + + #[test] + fn the_certificate_names_thinfloe_and_the_host() { + let d = TestDir::new("deskflow-ident", "cn"); + let id = load_or_create(&d.join("identity.pem"), "thinfloe-0a1b2c").unwrap(); + let cn = b"ThinFloe thinfloe-0a1b2c"; + assert!(id.cert_der.windows(cn.len()).any(|w| w == cn)); + } + + #[test] + fn the_certificate_has_fixed_dates() { + let d = TestDir::new("deskflow-ident", "dates"); + let id = load_or_create(&d.join("identity.pem"), "host").unwrap(); + // notBefore as UTCTime, notAfter (after 2049) as GeneralizedTime. + let has = |s: &[u8]| id.cert_der.windows(s.len()).any(|w| w == s); + assert!(has(b"000101000000Z"), "not before 2000-01-01"); + assert!(has(b"20991231000000Z"), "not after 2099-12-31"); + } + + #[test] + fn identity_file_mode_0600() { + let d = TestDir::new("deskflow-ident", "mode"); + let dir = d.join("deskflow"); + let path = dir.join("identity.pem"); + load_or_create(&path, "host").unwrap(); + assert_eq!(fs::metadata(&path).unwrap().permissions().mode() & 0o777, 0o600); + assert_eq!(fs::metadata(&dir).unwrap().permissions().mode() & 0o777, 0o700); + } + + #[test] + fn a_damaged_identity_is_an_error_and_stays() { + let d = TestDir::new("deskflow-ident", "damaged"); + let path = d.join("identity.pem"); + fs::write(&path, "not a pem\n").unwrap(); + assert!(load_or_create(&path, "host").is_err()); + assert_eq!(fs::read_to_string(&path).unwrap(), "not a pem\n"); + } + + #[test] + fn a_key_of_another_certificate_is_an_error() { + let d = TestDir::new("deskflow-ident", "mismatch"); + let a = d.join("a.pem"); + let b = d.join("b.pem"); + load_or_create(&a, "a").unwrap(); + load_or_create(&b, "b").unwrap(); + let a = fs::read_to_string(&a).unwrap(); + let b = fs::read_to_string(&b).unwrap(); + let cert_a = &a[..a.find("-----BEGIN PRIVATE KEY").unwrap()]; + let key_b = &b[b.find("-----BEGIN PRIVATE KEY").unwrap()..]; + let mixed = d.join("mixed.pem"); + fs::write(&mixed, format!("{cert_a}{key_b}")).unwrap(); + assert!(load_or_create(&mixed, "host").is_err()); + } + + #[test] + fn fingerprint_format() { + let fp = fingerprint(b"any bytes"); + let hex = fp.strip_prefix("v2:sha256:").unwrap(); + assert_eq!(hex.len(), 64); + assert!(hex.bytes().all(|c| c.is_ascii_digit() || (b'a'..=b'f').contains(&c))); + } + + #[test] + fn fingerprint_known_vector() { + assert_eq!( + fingerprint(b"abc"), + "v2:sha256:ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad" + ); + } + + #[test] + fn colon_hex_shape() { + let c = colon_hex(&fingerprint(b"abc")); + assert_eq!(c.len(), 95); + assert!(c.starts_with("BA:78:16:BF:")); + assert!(c.ends_with(":00:15:AD")); + assert!(!c.bytes().any(|b| b.is_ascii_lowercase())); + } + + #[test] + fn random_art_shape() { + let art = random_art(&fingerprint(b"abc")); + assert_eq!(art.len(), 11); + for line in &art { + assert_eq!(line.chars().count(), 19, "{line:?}"); + } + assert_eq!(art[0], "╔═════════════════╗"); + assert_eq!(art[10], "╚═════════════════╝"); + assert!(art[1..10].iter().all(|l| l.starts_with('║') && l.ends_with('║'))); + // The walk starts in the middle of the field. + assert_eq!(art[5].chars().nth(9), Some('S')); + assert_eq!(art.concat().matches('E').count(), 1); + assert_eq!(random_art(&fingerprint(b"abc")), art); + } + + #[test] + fn random_art_follows_deskflows_walk() { + // One byte 0b11_11_11_11 walks down-right four times from the + // middle (8, 4): it visits (9, 5), (10, 6), (11, 7) and ends on + // (12, 8). + let art = random_art("v2:sha256:ff"); + let row = |y: usize| art[y + 1].chars().skip(1).take(17).collect::(); + assert_eq!(row(4), " S "); + assert_eq!(row(5), " . "); + assert_eq!(row(6), " . "); + assert_eq!(row(7), " . "); + assert_eq!(row(8), " E "); + // A walk into the corner stays there and stacks up. + let art = random_art(&format!("v2:sha256:{}", "00".repeat(8))); + assert_eq!(art[1].chars().nth(1), Some('E')); + } +} diff --git a/src/thinfloe-menu/src/deskflow/keymap.rs b/src/thinfloe-menu/src/deskflow/keymap.rs new file mode 100644 index 0000000..fd2ae79 --- /dev/null +++ b/src/thinfloe-menu/src/deskflow/keymap.rs @@ -0,0 +1,502 @@ +//! Key translation for the Deskflow server: a Wayland keyboard event +//! (XKB keymap, evdev code, modifier state) becomes the key id, modifier mask +//! and button of a DKDL, DKUP or DKRP message. +//! +//! The numeric values are Deskflow's wire values (`src/lib/deskflow/KeyTypes.h` +//! at commit 80221f0). The rules for which keysym becomes a Unicode key id +//! and which a `kKey…` value follow Deskflow's keysym mapping +//! (`XDGKeyUtil::mapKeySymToKeyID`); only the rules and the numbers are +//! taken over. Where the table of Deskflow has no entry, libxkbcommon's +//! keysym-to-Unicode conversion decides, which also covers the keysyms +//! Deskflow's table misses (Unicode keysyms such as `U+0100_0000 + cp`). + +use std::ffi::{CStr, c_char}; +use std::fs::File; +use std::os::fd::OwnedFd; +use std::os::unix::fs::FileExt; + +use xkbcommon_dl::{ + XkbCommon, xkb_context, xkb_context_flags, xkb_keymap, xkb_keymap_compile_flags, xkb_keymap_format, xkb_state, + xkb_state_component, +}; + +/// The largest keymap read from a compositor. +const KEYMAP_MAX: u32 = 1 << 20; + +// KeyModifierMask bits, Deskflow commit 80221f0 (KeyTypes.h). +const MOD_SHIFT: u16 = 0x0001; +const MOD_CONTROL: u16 = 0x0002; +const MOD_ALT: u16 = 0x0004; +const MOD_SUPER: u16 = 0x0010; +const MOD_ALTGR: u16 = 0x0020; +const MOD_CAPS_LOCK: u16 = 0x1000; +const MOD_NUM_LOCK: u16 = 0x2000; +const MOD_SCROLL_LOCK: u16 = 0x4000; + +/// The modifier mask of a DKDL, DKUP or DKRP. +#[allow(clippy::too_many_arguments)] +pub fn mod_mask( + shift: bool, + ctrl: bool, + alt: bool, + logo: bool, + altgr: bool, + caps: bool, + num: bool, + scroll: bool, +) -> u16 { + [ + (shift, MOD_SHIFT), + (ctrl, MOD_CONTROL), + (alt, MOD_ALT), + (logo, MOD_SUPER), + (altgr, MOD_ALTGR), + (caps, MOD_CAPS_LOCK), + (num, MOD_NUM_LOCK), + (scroll, MOD_SCROLL_LOCK), + ] + .into_iter() + .filter(|(on, _)| *on) + .fold(0, |m, (_, bit)| m | bit) +} + +/// The button of a key: the X11 keycode, which is the evdev code plus 8. +pub fn button(evdev: u32) -> u16 { + (evdev + 8) as u16 +} + +/// A keysym's Deskflow key id; `None` for a key the client cannot be +/// given (no id, or beyond the 16 bit of the wire). `utf32` is the Unicode +/// character the key produces now (0 for none), used for keysyms that +/// have no `kKey…` value. +pub fn key_id(keysym: u32, utf32: u32) -> Option { + let id: u32 = match keysym { + // Latin-1 printable characters are their own id. + 0x20..=0x7e | 0xa0..=0xff => keysym, + // ISO 9995 function keys and dead keys. + 0xfe00..=0xfeff => iso_key(keysym)?, + // Miscellany: keysym - 0x1000. + 0xff00..=0xffff => keysym - 0x1000, + // "Internet" keys. + 0x1008_ff00..=0x1008_ffff => internet_key(keysym & 0xff)?, + _ => match utf32 { + 0x20..=0x7e | 0xa0..=0xd7ff | 0xe000..=0xffff => utf32, + _ => return None, + }, + }; + u16::try_from(id).ok().filter(|id| *id != 0) +} + +fn iso_key(keysym: u32) -> Option { + Some(match keysym { + 0xfe20 => 0xEE20, // ISO_Left_Tab: kKeyLeftTab + 0xfe03 => 0xEF7E, // ISO_Level3_Shift: kKeyAltGr + 0xfe11 => 0xfe11, // ISO_Level5_Shift: Deskflow passes the keysym on + 0xfe08 => 0xEE08, // ISO_Next_Group: kKeyNextGroup + 0xfe0a => 0xEE0A, // ISO_Prev_Group: kKeyPrevGroup + // The dead keys are the combining characters. + 0xfe50 => 0x0300, // dead_grave + 0xfe51 => 0x0301, // dead_acute + 0xfe52 => 0x0302, // dead_circumflex + 0xfe53 => 0x0303, // dead_tilde + 0xfe54 => 0x0304, // dead_macron + 0xfe55 => 0x0306, // dead_breve + 0xfe56 => 0x0307, // dead_abovedot + 0xfe57 => 0x0308, // dead_diaeresis + 0xfe58 => 0x030a, // dead_abovering + 0xfe59 => 0x030b, // dead_doubleacute + 0xfe5a => 0x030c, // dead_caron + 0xfe5b => 0x0327, // dead_cedilla + 0xfe5c => 0x0328, // dead_ogonek + _ => return None, + }) +} + +/// The XF86 keysyms Deskflow forwards, by the low byte of the keysym +/// (0x1008ff__); the values are the 0xE0__ ids of KeyTypes.h at commit +/// 80221f0. XF86AudioMicMute (0xb2) has none. +fn internet_key(low: u32) -> Option { + Some(match low { + 0x02 => 0xE0B9, // MonBrightnessUp: kKeyBrightnessUp + 0x03 => 0xE0B8, // MonBrightnessDown: kKeyBrightnessDown + 0x11 => 0xE0AE, // AudioLowerVolume: kKeyAudioDown + 0x12 => 0xE0AD, // AudioMute: kKeyAudioMute + 0x13 => 0xE0AF, // AudioRaiseVolume: kKeyAudioUp + 0x14 => 0xE0B3, // AudioPlay + 0x15 => 0xE0B2, // AudioStop + 0x16 => 0xE0B1, // AudioPrev + 0x17 => 0xE0B0, // AudioNext + 0x18 => 0xE0AC, // HomePage: kKeyWWWHome + 0x19 => 0xE0B4, // Mail: kKeyAppMail + 0x1b => 0xE0AA, // Search: kKeyWWWSearch + 0x26 => 0xE0A6, // Back: kKeyWWWBack + 0x27 => 0xE0A7, // Forward: kKeyWWWForward + 0x28 => 0xE0A9, // Stop: kKeyWWWStop + 0x29 => 0xE0A8, // Refresh: kKeyWWWRefresh + 0x2c => 0xE001, // Eject: kKeyEject + 0x30 => 0xE0AB, // Favorites: kKeyWWWFavorites + 0x32 => 0xE0B5, // AudioMedia: kKeyAppMedia + 0x40 => 0xE0B6, // Launch0: kKeyAppUser1 + 0x41 => 0xE0B7, // Launch1: kKeyAppUser2 + 0x4a => 0xE0C0, // kKeyMissionControl + 0x4b => 0xE0C1, // kKeyLaunchpad + _ => return None, + }) +} + +/// The modifiers in effect, as XKB reports them. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct Mods { + pub shift: bool, + pub ctrl: bool, + pub alt: bool, + pub logo: bool, + pub altgr: bool, + pub caps: bool, + pub num: bool, + pub scroll: bool, +} + +impl Mods { + /// The `KeyModifierMask` of these. + pub fn mask(&self) -> u16 { + mod_mask( + self.shift, + self.ctrl, + self.alt, + self.logo, + self.altgr, + self.caps, + self.num, + self.scroll, + ) + } +} + +/// The compositor's keymap and the modifier state, through libxkbcommon. +pub struct Xkb { + lib: &'static XkbCommon, + ctx: *mut xkb_context, + keymap: *mut xkb_keymap, + state: *mut xkb_state, +} + +impl Xkb { + /// Compiles the keymap the compositor sent (the fd's first `size` bytes). + pub fn from_keymap_fd(fd: &OwnedFd, size: u32) -> Result { + let lib = xkbcommon_dl::xkbcommon_option().ok_or("libxkbcommon is not available")?; + if size == 0 || size > KEYMAP_MAX { + return Err(format!("a keymap of {size} bytes")); + } + let file = File::from(fd.try_clone().map_err(|e| format!("dup: {e}"))?); + let mut text = vec![0u8; size as usize]; + file.read_exact_at(&mut text, 0).map_err(|e| format!("read: {e}"))?; + while text.last() == Some(&0) { + text.pop(); + } + text.push(0); + let text = CStr::from_bytes_until_nul(&text).map_err(|e| e.to_string())?; + Xkb::build(lib, |ctx| { + // SAFETY: ctx is a live context; text is NUL-terminated. + unsafe { + (lib.xkb_keymap_new_from_string)( + ctx, + text.as_ptr(), + xkb_keymap_format::XKB_KEYMAP_FORMAT_TEXT_V1, + xkb_keymap_compile_flags::XKB_KEYMAP_COMPILE_NO_FLAGS, + ) + } + }) + .map_err(|e| { + if e == NO_KEYMAP { + "the keymap does not compile".into() + } else { + e + } + }) + } + + /// A keymap for the layout name from the system's XKB data (tests). + #[cfg(test)] + pub(crate) fn from_layout(layout: &str) -> Result { + let lib = xkbcommon_dl::xkbcommon_option().ok_or("libxkbcommon is not available")?; + let layout = std::ffi::CString::new(layout).map_err(|e| e.to_string())?; + let names = xkbcommon_dl::xkb_rule_names { + rules: std::ptr::null(), + model: std::ptr::null(), + layout: layout.as_ptr(), + variant: std::ptr::null(), + options: std::ptr::null(), + }; + Xkb::build(lib, |ctx| { + // SAFETY: ctx is live; names points to NUL-terminated strings. + unsafe { + (lib.xkb_keymap_new_from_names)(ctx, &names, xkb_keymap_compile_flags::XKB_KEYMAP_COMPILE_NO_FLAGS) + } + }) + .map_err(|e| { + if e == NO_KEYMAP { + format!("no keymap for layout {}", layout.to_string_lossy()) + } else { + e + } + }) + } + + fn build(lib: &'static XkbCommon, make: impl FnOnce(*mut xkb_context) -> *mut xkb_keymap) -> Result { + // SAFETY: plain libxkbcommon calls on pointers checked for NULL; the + // three objects are owned by the Xkb and freed in Drop. + unsafe { + let ctx = (lib.xkb_context_new)(xkb_context_flags::XKB_CONTEXT_NO_FLAGS); + if ctx.is_null() { + return Err("xkb_context_new failed".into()); + } + let keymap = make(ctx); + if keymap.is_null() { + (lib.xkb_context_unref)(ctx); + return Err(NO_KEYMAP.into()); + } + let state = (lib.xkb_state_new)(keymap); + if state.is_null() { + (lib.xkb_keymap_unref)(keymap); + (lib.xkb_context_unref)(ctx); + return Err("xkb_state_new failed".into()); + } + Ok(Xkb { + lib, + ctx, + keymap, + state, + }) + } + } + + /// Takes the modifier state of a `wl_keyboard.modifiers` event. + pub fn update_mask(&mut self, depressed: u32, latched: u32, locked: u32, group: u32) { + // SAFETY: state is valid until Drop. + unsafe { + (self.lib.xkb_state_update_mask)(self.state, depressed, latched, locked, 0, 0, group); + } + } + + /// The keysym the key gives in the current state; 0 for none. + pub fn keysym(&self, evdev: u32) -> u32 { + // SAFETY: state is valid until Drop. + unsafe { (self.lib.xkb_state_key_get_one_sym)(self.state, evdev + 8) } + } + + /// The keysym on the key's first level in its current layout, whatever + /// the modifiers; 0 for none. Ctrl+Alt+F1 gives `XF86Switch_VT_1` in + /// the current state and `F1` here. + pub fn keysym_level0(&self, evdev: u32) -> u32 { + // SAFETY: state and keymap are valid until Drop; syms points into + // the keymap and is read only when the count says it holds one. + unsafe { + let layout = (self.lib.xkb_state_key_get_layout)(self.state, evdev + 8); + let mut syms: *const u32 = std::ptr::null(); + let n = (self.lib.xkb_keymap_key_get_syms_by_level)(self.keymap, evdev + 8, layout, 0, &mut syms); + if n == 1 && !syms.is_null() { *syms } else { 0 } + } + } + + /// Whether the keymap lets the key repeat (modifiers do not). + pub fn repeats(&self, evdev: u32) -> bool { + // SAFETY: keymap is valid until Drop. + unsafe { (self.lib.xkb_keymap_key_repeats)(self.keymap, evdev + 8) > 0 } + } + + /// The Unicode character the key gives in the current state; 0 for none. + pub fn utf32(&self, evdev: u32) -> u32 { + // SAFETY: state is valid until Drop. + unsafe { (self.lib.xkb_state_key_get_utf32)(self.state, evdev + 8) } + } + + /// The effective modifiers. + pub fn mods(&self) -> Mods { + let on = |names: &[&[u8]]| names.iter().any(|n| self.mod_active(n)); + Mods { + shift: on(&[b"Shift\0"]), + ctrl: on(&[b"Control\0"]), + alt: on(&[b"Mod1\0", b"Alt\0"]), + logo: on(&[b"Mod4\0", b"Super\0", b"Hyper\0"]), + altgr: on(&[b"Mod5\0", b"LevelThree\0"]), + caps: on(&[b"Lock\0"]), + num: on(&[b"Mod2\0", b"NumLock\0"]), + scroll: on(&[b"ScrollLock\0"]), + } + } + + /// Whether the modifier is active; a name the keymap lacks is not. + fn mod_active(&self, name: &[u8]) -> bool { + debug_assert_eq!(name.last(), Some(&0)); + // SAFETY: name is NUL-terminated; state is valid until Drop. + unsafe { + (self.lib.xkb_state_mod_name_is_active)( + self.state, + name.as_ptr().cast::(), + xkb_state_component::XKB_STATE_MODS_EFFECTIVE, + ) > 0 + } + } +} + +const NO_KEYMAP: &str = "the keymap does not build"; + +impl Drop for Xkb { + fn drop(&mut self) { + // SAFETY: all three were made in build and are freed only here. + unsafe { + (self.lib.xkb_state_unref)(self.state); + (self.lib.xkb_keymap_unref)(self.keymap); + (self.lib.xkb_context_unref)(self.ctx); + } + } +} + +/// The name of a keysym, for logs; its hex value when libxkbcommon has none. +pub fn keysym_name(sym: u32) -> String { + let Some(lib) = xkbcommon_dl::xkbcommon_option() else { + return format!("0x{sym:x}"); + }; + let mut buf = [0 as c_char; 64]; + // SAFETY: the buffer and its length match; libxkbcommon NUL-terminates. + let n = unsafe { (lib.xkb_keysym_get_name)(sym, buf.as_mut_ptr(), buf.len()) }; + if n <= 0 { + return format!("0x{sym:x}"); + } + // SAFETY: a NUL-terminated string in buf. + unsafe { CStr::from_ptr(buf.as_ptr()) }.to_string_lossy().into_owned() +} + +#[cfg(test)] +mod tests { + use super::*; + + const KEY_Y: u32 = 21; + const KEY_A: u32 = 30; + + #[test] + fn latin_letters_are_unicode() { + assert_eq!(key_id(0x61, 0x61), Some(0x61)); + assert_eq!(key_id(0x41, 0x41), Some(0x41)); + assert_eq!(key_id(0x20, 0x20), Some(0x20)); + } + + #[test] + fn umlaut() { + assert_eq!(key_id(0xe4, 0xe4), Some(0xE4)); + } + + #[test] + fn other_scripts_and_the_euro_sign_are_unicode() { + assert_eq!(key_id(0x20ac, 0x20ac), Some(0x20AC)); // EuroSign + assert_eq!(key_id(0x6c1, 0x0430), Some(0x0430)); // Cyrillic_a + assert_eq!(key_id(0x0100_20ac, 0x20ac), Some(0x20AC)); // a Unicode keysym + assert_eq!(key_id(0x0101_f600, 0x1f600), None); // beyond the BMP + assert_eq!(key_id(0x6c1, 0), None); // no character + assert_eq!(key_id(0x6c1, 0x01), None); // a control character + } + + #[test] + fn return_escape_f1_match_keytypes() { + assert_eq!(key_id(0xff0d, 0x0d), Some(0xEF0D)); // kKeyReturn + assert_eq!(key_id(0xff1b, 0x1b), Some(0xEF1B)); // kKeyEscape + assert_eq!(key_id(0xffbe, 0), Some(0xEFBE)); // kKeyF1 + assert_eq!(key_id(0xff08, 0x08), Some(0xEF08)); // kKeyBackSpace + assert_eq!(key_id(0xff09, 0x09), Some(0xEF09)); // kKeyTab + assert_eq!(key_id(0xffff, 0x7f), Some(0xEFFF)); // kKeyDelete + assert_eq!(key_id(0xff51, 0), Some(0xEF51)); // kKeyLeft + assert_eq!(key_id(0xff8d, 0x0d), Some(0xEF8D)); // kKeyKP_Enter + assert_eq!(key_id(0xffb5, 0x35), Some(0xEFB5)); // kKeyKP_5 + assert_eq!(key_id(0xffe1, 0), Some(0xEFE1)); // kKeyShift_L + assert_eq!(key_id(0xffeb, 0), Some(0xEFEB)); // kKeySuper_L + assert_eq!(key_id(0xfe20, 0), Some(0xEE20)); // ISO_Left_Tab: kKeyLeftTab + assert_eq!(key_id(0xfe03, 0), Some(0xEF7E)); // ISO_Level3_Shift: kKeyAltGr + assert_eq!(key_id(0xfe57, 0), Some(0x0308)); // dead_diaeresis + assert_eq!(key_id(0xfeff, 0), None); + } + + #[test] + fn media_keys_match_keytypes() { + assert_eq!(key_id(0x1008_ff12, 0), Some(0xE0AD)); // AudioMute + assert_eq!(key_id(0x1008_ff11, 0), Some(0xE0AE)); // AudioLowerVolume + assert_eq!(key_id(0x1008_ff13, 0), Some(0xE0AF)); // AudioRaiseVolume + assert_eq!(key_id(0x1008_ff03, 0), Some(0xE0B8)); // MonBrightnessDown + assert_eq!(key_id(0x1008_ff02, 0), Some(0xE0B9)); // MonBrightnessUp + } + + #[test] + fn mic_mute_is_none() { + assert_eq!(key_id(0x1008_ffb2, 0), None); + } + + #[test] + fn mod_mask_bits() { + assert_eq!(mod_mask(true, false, false, false, false, false, false, false), 0x0001); + assert_eq!(mod_mask(false, true, false, false, false, false, false, false), 0x0002); + assert_eq!(mod_mask(false, false, true, false, false, false, false, false), 0x0004); + assert_eq!(mod_mask(false, false, false, true, false, false, false, false), 0x0010); + assert_eq!(mod_mask(false, false, false, false, true, false, false, false), 0x0020); + assert_eq!(mod_mask(false, false, false, false, false, true, false, false), 0x1000); + assert_eq!(mod_mask(false, false, false, false, false, false, true, false), 0x2000); + assert_eq!(mod_mask(false, false, false, false, false, false, false, true), 0x4000); + assert_eq!(mod_mask(true, true, true, true, true, true, true, true), 0x7037); + assert_eq!(mod_mask(false, false, false, false, false, false, false, false), 0); + } + + #[test] + fn button_is_x11_keycode() { + assert_eq!(button(30), 38); + } + + fn de() -> Xkb { + Xkb::from_layout("de").expect("libxkbcommon and the xkeyboard-config data are needed for this test") + } + + #[test] + fn xkb_de_layout_y_is_z() { + let x = de(); + assert_eq!(x.keysym(KEY_Y), 0x7a); + assert_eq!(x.utf32(KEY_Y), 0x7a); + assert_eq!(key_id(x.keysym(KEY_Y), x.utf32(KEY_Y)), Some(0x7a)); + } + + #[test] + fn xkb_modifier_state_changes_keysym_and_mask() { + let mut x = de(); + assert_eq!(x.keysym(KEY_A), 0x61); + assert_eq!(x.mods().mask(), 0); + x.update_mask(1, 0, 0, 0); // Shift + assert_eq!(x.keysym(KEY_A), 0x41); + assert!(x.mods().shift); + assert_eq!(x.mods().mask(), 0x0001); + x.update_mask(0, 0, 2, 0); // Lock (Caps Lock) + assert!(x.mods().caps); + assert_eq!(x.mods().mask(), 0x1000); + x.update_mask(0, 0, 0, 0); + assert_eq!(x.mods(), Mods::default()); + } + + #[test] + fn level0_ignores_the_modifiers_and_only_keys_repeat() { + const KEY_F1: u32 = 59; + const KEY_LEFTCTRL: u32 = 29; + let mut x = + Xkb::from_layout("us").expect("libxkbcommon and the xkeyboard-config data are needed for this test"); + x.update_mask(4 | 8, 0, 0, 0); // Control, Mod1 + assert_eq!(x.keysym(KEY_F1), 0x1008_fe01); // XF86Switch_VT_1 + assert_eq!(key_id(x.keysym(KEY_F1), x.utf32(KEY_F1)), None); + assert_eq!(x.keysym_level0(KEY_F1), 0xffbe); // F1 + x.update_mask(1, 0, 0, 0); // Shift + assert_eq!(x.keysym(KEY_A), 0x41); + assert_eq!(x.keysym_level0(KEY_A), 0x61); + assert!(x.repeats(KEY_A)); + assert!(!x.repeats(KEY_LEFTCTRL)); + } + + #[test] + fn a_bad_keymap_is_an_error() { + let file = File::open("/dev/null").unwrap(); + assert!(Xkb::from_keymap_fd(&OwnedFd::from(file), 0).is_err()); + } +} diff --git a/src/thinfloe-menu/src/deskflow/mod.rs b/src/thinfloe-menu/src/deskflow/mod.rs new file mode 100644 index 0000000..98c3741 --- /dev/null +++ b/src/thinfloe-menu/src/deskflow/mod.rs @@ -0,0 +1,434 @@ +//! `thinfloe-menu --deskflow`: the Deskflow server, a process of its own +//! beside the menu (spec, Processes). Its keyboard and pointer drive the +//! computers attached at the edges of ThinFloe's monitors. +//! +//! `--deskflow --probe-capture ` is a test hook for the +//! runtime tests: it puts one strip on that edge of the output, prints one +//! line per capture event, begins a capture as soon as the pointer enters +//! the strip and ends it on Escape, until SIGTERM. +//! +//! `--deskflow --probe-clip` is a test hook for the clipboard bridge: it +//! prints `changed ` for each text another client puts on +//! the clipboard, `cleared` for a selection it does not carry (no text, or +//! over the cap), and sets the clipboard from stdin lines `set `. +//! +//! `--deskflow` alone is the daemon ([`run`]). + +pub mod capture; +pub mod clip; +pub mod clipdata; +pub mod clipsync; +pub mod cmd; +pub mod conn; +pub mod edge; +pub mod forward; +pub mod ident; +pub mod keymap; +pub mod pair; +pub mod proto; +pub mod run; +pub mod session; +pub mod statefile; +pub mod tls; + +use std::ffi::OsString; +use std::io::ErrorKind; +use std::os::fd::AsRawFd; +use std::process::ExitCode; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::time::Instant; + +use capture::{CapEvent, Capture, OutputGeom, StripSpec}; +use edge::Rect; +use keymap::{Xkb, keysym_name}; + +pub const DESKFLOW_ARG: &str = "--deskflow"; +/// The pid of the menu that started the daemon (`deskflow_sup`). +pub const PARENT_ENV: &str = "TF_DESKFLOW_PARENT"; +const PROBE_CAPTURE_ARG: &str = "--probe-capture"; +const PROBE_CLIP_ARG: &str = "--probe-clip"; + +/// The evdev code of Escape, for a keymap that cannot be read. +const KEY_ESC: u32 = 1; +/// Escape's keysym. +const XK_ESCAPE: u32 = 0xff1b; + +static STOP: AtomicBool = AtomicBool::new(false); + +extern "C" fn on_sigterm(_: libc::c_int) { + STOP.store(true, Ordering::SeqCst); +} + +fn install_sigterm() { + // SAFETY: the handler only stores to an atomic, which is + // async-signal-safe. + unsafe { + libc::signal(libc::SIGTERM, on_sigterm as *const () as libc::sighandler_t); + } +} + +pub fn deskflow_main(args: &[OsString]) -> ExitCode { + let arg = |i: usize| args.get(i).and_then(|a| a.to_str()); + if arg(0) == Some(PROBE_CAPTURE_ARG) + && let (Some(output), Some(side)) = (arg(1), arg(2)) + { + return match probe_capture(output, side) { + Ok(()) => ExitCode::SUCCESS, + Err(e) => { + eprintln!("thinfloe-menu --deskflow: {e}"); + ExitCode::from(1) + } + }; + } + if arg(0) == Some(PROBE_CLIP_ARG) { + return match probe_clip() { + Ok(()) => ExitCode::SUCCESS, + Err(e) => { + eprintln!("thinfloe-menu --deskflow: {e}"); + ExitCode::from(1) + } + }; + } + if args.is_empty() { + return daemon(); + } + eprintln!( + "usage: thinfloe-menu --deskflow [--probe-capture | --probe-clip]" + ); + ExitCode::from(2) +} + +/// The daemon, with the paths of the session. +fn daemon() -> ExitCode { + let fail = |e: &str| { + eprintln!("thinfloe-menu --deskflow: {e}"); + ExitCode::from(1) + }; + // The menu starts the daemon; it must not outlive it. A parent that + // died before the prctl sends nothing, so the parent is checked after + // it: the menu's pid from the environment, else the parent at start. + // SAFETY: getppid and prctl take no pointers. + let parent = std::env::var(PARENT_ENV) + .ok() + .and_then(|p| p.parse::().ok()) + .unwrap_or_else(|| unsafe { libc::getppid() }); + if unsafe { libc::prctl(libc::PR_SET_PDEATHSIG, libc::SIGTERM as libc::c_ulong, 0, 0, 0) } != 0 { + return fail(&format!("PR_SET_PDEATHSIG: {}", std::io::Error::last_os_error())); + } + if unsafe { libc::getppid() } != parent { + eprintln!("thinfloe-menu --deskflow: the menu that started it is gone"); + return ExitCode::SUCCESS; + } + let (Some(state), Some(socket)) = (statefile::path(), cmd::socket_path()) else { + return fail("XDG_RUNTIME_DIR is not set"); + }; + let dir = crate::config::ConfigDir::from_env(); + let env = run::RunEnv { + generated: dir.generated_file("deskflow"), + identity: dir.root.join("deskflow").join("identity.pem"), + state, + socket, + hostname: hostname(), + osd_key: run::osd_key_command(std::env::var("TF_OSD_KEY_CMD").ok().as_deref()), + }; + match run::run(env) { + Ok(()) => ExitCode::SUCCESS, + Err(e) => fail(&e), + } +} + +/// The host name for the certificate, from /etc/hostname (the initramfs +/// writes it). +fn hostname() -> String { + std::fs::read_to_string("/etc/hostname") + .ok() + .map(|s| s.trim().to_string()) + .filter(|s| !s.is_empty()) + .unwrap_or_else(|| "thinfloe".into()) +} + +/// The 1 px strip along `side` of `out`, in layout coordinates. +fn probe_strip(out: &OutputGeom, side: &str) -> Option { + let (x, y, w, h) = (out.x, out.y, out.w, out.h); + Some(match side { + "left-of" => Rect { x, y, w: 1, h }, + "right-of" => Rect { + x: x + w - 1, + y, + w: 1, + h, + }, + "above" => Rect { x, y, w, h: 1 }, + "below" => Rect { + x, + y: y + h - 1, + w, + h: 1, + }, + _ => return None, + }) +} + +fn probe_capture(output: &str, side: &str) -> Result<(), String> { + install_sigterm(); + let mut cap = Capture::connect()?; + let geom = cap + .outputs() + .into_iter() + .find(|o| o.name == output) + .ok_or_else(|| format!("no output {output}"))?; + let rect = probe_strip(&geom, side).ok_or_else(|| format!("unknown side {side}"))?; + cap.set_strips(&[StripSpec { + id: 1, + output: output.to_string(), + rect, + }]); + let mut keys: Option = None; + while !STOP.load(Ordering::SeqCst) { + cap.flush()?; + let mut fds = [libc::pollfd { + fd: cap.fd().as_raw_fd(), + events: libc::POLLIN, + revents: 0, + }]; + // SAFETY: one valid pollfd for the duration of the call. + let r = unsafe { libc::poll(fds.as_mut_ptr(), 1, 500) }; + if r < 0 { + let e = std::io::Error::last_os_error(); + if e.kind() == ErrorKind::Interrupted { + continue; + } + return Err(format!("poll: {e}")); + } + if fds[0].revents & (libc::POLLERR | libc::POLLHUP) != 0 { + return Err("the compositor closed the connection".into()); + } + for ev in cap.dispatch()? { + match &ev { + CapEvent::Enter { strip, .. } => cap.begin_capture(*strip), + CapEvent::Keymap { fd, size } => match Xkb::from_keymap_fd(fd, *size) { + Ok(k) => keys = Some(k), + Err(e) => { + eprintln!("thinfloe-menu --deskflow: keymap: {e}"); + keys = None; + } + }, + _ => {} + } + println!("{}", probe_line(&ev, keys.as_ref())); + if let CapEvent::Key { code, pressed: true } = ev { + let escape = match &keys { + Some(k) => k.keysym(code) == XK_ESCAPE, + None => code == KEY_ESC, + }; + if escape { + let _ = cap.end_capture(); + } + } + } + } + Ok(()) +} + +fn probe_clip() -> Result<(), String> { + install_sigterm(); + let mut clip = clip::Clip::connect()?; + let mut input = Vec::new(); + let mut stdin_open = true; + while !STOP.load(Ordering::SeqCst) { + clip.flush()?; + let now = Instant::now(); + let mut fds = vec![ + libc::pollfd { + fd: clip.fd().as_raw_fd(), + events: libc::POLLIN, + revents: 0, + }, + libc::pollfd { + fd: if stdin_open { 0 } else { -1 }, + events: libc::POLLIN, + revents: 0, + }, + ]; + fds.extend( + clip.pipe_fds() + .into_iter() + .map(|(fd, events)| libc::pollfd { fd, events, revents: 0 }), + ); + let wait = clip + .deadline() + .map_or(500, |d| d.saturating_duration_since(now).as_millis().min(500) as i32); + // SAFETY: fds is valid for fds.len() entries for the call. + let r = unsafe { libc::poll(fds.as_mut_ptr(), fds.len() as libc::nfds_t, wait) }; + if r < 0 { + let e = std::io::Error::last_os_error(); + if e.kind() == ErrorKind::Interrupted { + continue; + } + return Err(format!("poll: {e}")); + } + let now = Instant::now(); + if fds[0].revents & (libc::POLLERR | libc::POLLHUP) != 0 { + return Err("the compositor closed the connection".into()); + } + let mut events = clip.dispatch(now)?; + for p in &fds[2..] { + if p.revents != 0 { + events.extend(clip.on_pipe_ready(p.fd, now)); + } + } + events.extend(clip.tick(now)); + for ev in events { + match ev { + clip::ClipEvent::Changed(text) => { + let digest = ring::digest::digest(&ring::digest::SHA256, &text); + let hex: String = digest.as_ref().iter().map(|b| format!("{b:02x}")).collect(); + println!("changed {} {hex}", text.len()); + } + clip::ClipEvent::Cleared => println!("cleared"), + } + } + if fds[1].revents != 0 { + let mut buf = [0u8; 4096]; + // SAFETY: buf is valid for buf.len() bytes. + let n = unsafe { libc::read(0, buf.as_mut_ptr().cast(), buf.len()) }; + if n > 0 { + input.extend_from_slice(&buf[..n as usize]); + } else if n == 0 { + stdin_open = false; + } + while let Some(i) = input.iter().position(|&b| b == b'\n') { + let line: Vec = input.drain(..=i).collect(); + if let Some(text) = line.strip_prefix(b"set ") { + clip.set_text(text.strip_suffix(b"\n").unwrap_or(text).to_vec()); + } + } + } + } + Ok(()) +} + +/// The probe's line for one event; a key also shows its keysym's name, +/// "-" without a keymap. +fn probe_line(ev: &CapEvent, keys: Option<&Xkb>) -> String { + let updown = |p: bool| if p { "down" } else { "up" }; + match ev { + CapEvent::Enter { strip, x, y } => format!("enter {strip} {x:.0} {y:.0}"), + CapEvent::Leave { strip } => format!("leave {strip}"), + CapEvent::Motion { x, y } => format!("motion {x:.0} {y:.0}"), + CapEvent::Relative { dx, dy, .. } => format!("relative {dx:.2} {dy:.2}"), + CapEvent::Locked => "locked".into(), + CapEvent::Unlocked => "unlocked".into(), + CapEvent::Key { code, pressed } => { + let name = keys + .map(|k| k.keysym(*code)) + .filter(|s| *s != 0) + .map_or_else(|| "-".into(), keysym_name); + format!("key {code} {} {name}", updown(*pressed)) + } + CapEvent::Modifiers { + depressed, + latched, + locked, + group, + } => format!("modifiers {depressed} {latched} {locked} {group}"), + CapEvent::Keymap { size, .. } => format!("keymap {size}"), + CapEvent::RepeatInfo { rate, delay } => format!("repeat {rate} {delay}"), + CapEvent::Button { button, pressed } => format!("button {button} {}", updown(*pressed)), + CapEvent::Axis { v120_x, v120_y } => format!("axis {v120_x} {v120_y}"), + CapEvent::KeyboardLeft => "keyboard-left".into(), + CapEvent::OutputsChanged => "outputs-changed".into(), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_probe_strip_lies_on_the_named_edge() { + let out = OutputGeom { + name: "HEADLESS-1".into(), + description: String::new(), + x: 1280, + y: 0, + w: 1280, + h: 720, + }; + assert_eq!( + probe_strip(&out, "right-of"), + Some(Rect { + x: 2559, + y: 0, + w: 1, + h: 720 + }) + ); + assert_eq!( + probe_strip(&out, "left-of"), + Some(Rect { + x: 1280, + y: 0, + w: 1, + h: 720 + }) + ); + assert_eq!( + probe_strip(&out, "above"), + Some(Rect { + x: 1280, + y: 0, + w: 1280, + h: 1 + }) + ); + assert_eq!( + probe_strip(&out, "below"), + Some(Rect { + x: 1280, + y: 719, + w: 1280, + h: 1 + }) + ); + assert_eq!(probe_strip(&out, "behind"), None); + } + + #[test] + fn probe_lines_name_each_event() { + assert_eq!( + probe_line( + &CapEvent::Enter { + strip: 1, + x: 1279.5, + y: 360.0 + }, + None + ), + "enter 1 1280 360" + ); + assert_eq!(probe_line(&CapEvent::Locked, None), "locked"); + assert_eq!(probe_line(&CapEvent::Unlocked, None), "unlocked"); + assert_eq!( + probe_line( + &CapEvent::Key { + code: 45, + pressed: true + }, + None + ), + "key 45 down -" + ); + assert_eq!( + probe_line( + &CapEvent::Button { + button: 272, + pressed: false + }, + None + ), + "button 272 up" + ); + assert_eq!(probe_line(&CapEvent::KeyboardLeft, None), "keyboard-left"); + } +} diff --git a/src/thinfloe-menu/src/deskflow/pair.rs b/src/thinfloe-menu/src/deskflow/pair.rs new file mode 100644 index 0000000..d04c2c8 --- /dev/null +++ b/src/thinfloe-menu/src/deskflow/pair.rs @@ -0,0 +1,202 @@ +//! The trust decision for a connecting device and the list of devices that +//! wait for the user (spec, Identity and pairing). Sans-IO: the caller +//! passes the time in. + +use crate::config::DeviceCfg; + +/// At most this many pending devices are kept; the oldest is dropped. +pub const MAX_PENDING: usize = 8; +/// At most this many rejections are remembered; the oldest is forgotten. +/// A noisy LAN cannot grow the list without bound. +pub const MAX_REJECTED: usize = 64; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Verdict { + /// The (name, fingerprint) pair is attached; the index into the devices. + Trusted(usize), + /// Unknown name: waits for the user. + Pending, + /// The name is attached with another fingerprint. + FingerprintChanged, +} + +/// Decides on a connecting device by exact name and fingerprint. +pub fn judge(devices: &[DeviceCfg], name: &str, fp: &str) -> Verdict { + if let Some(i) = devices.iter().position(|d| d.name == name && d.fingerprint == fp) { + Verdict::Trusted(i) + } else if devices.iter().any(|d| d.name == name) { + Verdict::FingerprintChanged + } else { + Verdict::Pending + } +} + +/// Why a device waits: the flags argument of [`Pending::note`]. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum PendingKind { + /// The name is not attached. + New, + /// The name is attached with another fingerprint (state file flag + /// `fp-changed`). + FingerprintChanged, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct PendingEntry { + pub name: String, + pub fingerprint: String, + pub kind: PendingKind, + /// When the pair was first noted, seconds since the epoch. + pub since_epoch: u64, +} + +#[derive(Default)] +pub struct Pending { + entries: Vec, + rejected: Vec<(String, String)>, +} + +impl Pending { + /// Records a pair that connected and was not trusted. A rejected pair is + /// not noted again; a pair already listed keeps its place and time and + /// takes the new kind. + pub fn note(&mut self, name: &str, fp: &str, kind: PendingKind, now_epoch: u64) { + if self.is_rejected(name, fp) { + return; + } + if let Some(e) = self.entries.iter_mut().find(|e| e.name == name && e.fingerprint == fp) { + e.kind = kind; + return; + } + if self.entries.len() >= MAX_PENDING { + self.entries.remove(0); + } + self.entries.push(PendingEntry { + name: name.to_string(), + fingerprint: fp.to_string(), + kind, + since_epoch: now_epoch, + }); + } + + /// The user rejects a pair: it leaves the list and is not noted again + /// for this session. + pub fn reject(&mut self, name: &str, fp: &str) { + self.entries.retain(|e| !(e.name == name && e.fingerprint == fp)); + if self.is_rejected(name, fp) { + return; + } + if self.rejected.len() >= MAX_REJECTED { + self.rejected.remove(0); + } + self.rejected.push((name.to_string(), fp.to_string())); + } + + pub fn is_rejected(&self, name: &str, fp: &str) -> bool { + self.rejected.iter().any(|(n, f)| n == name && f == fp) + } + + /// Oldest first. + pub fn entries(&self) -> &[PendingEntry] { + &self.entries + } + + /// The rejected pairs of this session, oldest first. + pub fn rejected(&self) -> &[(String, String)] { + &self.rejected + } + + /// Drops the entries that the devices now trust (after an attach). + pub fn forget_trusted(&mut self, devices: &[DeviceCfg]) { + self.entries.retain(|e| { + !devices + .iter() + .any(|d| d.name == e.name && d.fingerprint == e.fingerprint) + }); + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::kanshi::Side; + + fn dev(name: &str, fp: &str) -> DeviceCfg { + DeviceCfg { + name: name.into(), + fingerprint: fp.into(), + output: "DP-1".into(), + side: Side::RightOf, + clipboard: true, + } + } + + #[test] + fn judge_known_pending_changed() { + let devs = [dev("laptop", "fp1"), dev("tablet", "fp2")]; + assert_eq!(judge(&devs, "tablet", "fp2"), Verdict::Trusted(1)); + assert_eq!(judge(&devs, "phone", "fp9"), Verdict::Pending); + assert_eq!(judge(&devs, "laptop", "fpX"), Verdict::FingerprintChanged); + // The fingerprint of another device does not make a name known. + assert_eq!(judge(&devs, "phone", "fp1"), Verdict::Pending); + } + + #[test] + fn pending_keeps_eight_newest() { + let mut p = Pending::default(); + for i in 0..10 { + p.note(&format!("d{i}"), "fp", PendingKind::New, 100 + i); + } + let names: Vec<_> = p.entries().iter().map(|e| e.name.as_str()).collect(); + assert_eq!(names, ["d2", "d3", "d4", "d5", "d6", "d7", "d8", "d9"]); + assert_eq!(p.entries()[0].since_epoch, 102); + } + + #[test] + fn noting_again_keeps_place_and_time() { + let mut p = Pending::default(); + p.note("a", "f", PendingKind::New, 1); + p.note("b", "f", PendingKind::New, 2); + p.note("a", "f", PendingKind::FingerprintChanged, 3); + assert_eq!(p.entries().len(), 2); + assert_eq!(p.entries()[0].name, "a"); + assert_eq!(p.entries()[0].since_epoch, 1); + assert_eq!(p.entries()[0].kind, PendingKind::FingerprintChanged); + } + + #[test] + fn rejected_not_noted_again() { + let mut p = Pending::default(); + p.note("a", "f", PendingKind::New, 1); + p.reject("a", "f"); + assert!(p.entries().is_empty()); + assert!(p.is_rejected("a", "f")); + p.note("a", "f", PendingKind::New, 2); + assert!(p.entries().is_empty()); + // Another fingerprint under the same name is a new pair. + p.note("a", "g", PendingKind::New, 3); + assert_eq!(p.entries().len(), 1); + assert!(!p.is_rejected("a", "g")); + } + + #[test] + fn rejections_are_bounded() { + let mut p = Pending::default(); + for i in 0..(MAX_REJECTED + 5) { + p.reject(&format!("d{i}"), "f"); + } + assert_eq!(p.rejected().len(), MAX_REJECTED); + assert!(!p.is_rejected("d0", "f")); + assert!(p.is_rejected(&format!("d{}", MAX_REJECTED + 4), "f")); + } + + #[test] + fn forget_trusted_drops_attached_pairs() { + let mut p = Pending::default(); + p.note("a", "f", PendingKind::New, 1); + p.note("b", "g", PendingKind::New, 2); + p.forget_trusted(&[dev("a", "f"), dev("b", "other")]); + assert_eq!(p.entries().len(), 1); + assert_eq!(p.entries()[0].name, "b"); + } +} diff --git a/src/thinfloe-menu/src/deskflow/proto.rs b/src/thinfloe-menu/src/deskflow/proto.rs new file mode 100644 index 0000000..8c01eaa --- /dev/null +++ b/src/thinfloe-menu/src/deskflow/proto.rs @@ -0,0 +1,764 @@ +//! The Deskflow wire protocol, the subset the server speaks (spec, +//! Protocol subset). Pure functions on bytes: every integer is big-endian, +//! a string is a u32 length and its bytes, and each message travels in a +//! frame with a u32 length in front (the Hello included). +//! +//! Decoding takes input from a peer that may be hostile: it never panics +//! and never allocates more than the frame it is given holds. + +/// The largest message payload the framer accepts. +pub const MAX_MSG: usize = 1 << 20; + +/// The protocol name in the Hello; Deskflow clients still expect it. +const HELLO_NAME: &[u8; 7] = b"Barrier"; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum ProtoError { + /// The payload ends before the message does. + Truncated, + /// A frame announces more than MAX_MSG bytes. + Oversize, + /// The Hello does not start with the protocol name. + BadHello, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Msg { + Hello { + major: u16, + minor: u16, + }, + HelloBack { + major: u16, + minor: u16, + name: Vec, + }, + Qinf, + Ciak, + Calv, + Cnop, + Crop, + Dsop(Vec), + Csec(u8), + Cinn { + x: i16, + y: i16, + seq: u32, + mods: u16, + }, + Cout, + Cbye, + Dinf { + x: i16, + y: i16, + w: i16, + h: i16, + warp: i16, + mx: i16, + my: i16, + }, + KeyDown { + id: u16, + mods: u16, + button: u16, + }, + KeyRepeat { + id: u16, + mods: u16, + count: u16, + button: u16, + }, + KeyUp { + id: u16, + mods: u16, + button: u16, + }, + MouseDown(i8), + MouseUp(i8), + MouseMove { + x: i16, + y: i16, + }, + Wheel { + dx: i16, + dy: i16, + }, + Cclp { + id: u8, + seq: u32, + }, + Dclp { + id: u8, + seq: u32, + mark: u8, + data: Vec, + }, + Eicv { + major: u16, + minor: u16, + }, + Ebsy, + Eunk, + Ebad, + /// A message code this subset does not know. + Unknown([u8; 4]), +} + +/// The first minor version that sends the language string with a key. +const MINOR_LANG: u16 = 8; + +fn put16(v: &mut Vec, n: u16) { + v.extend_from_slice(&n.to_be_bytes()); +} + +fn put32(v: &mut Vec, n: u32) { + v.extend_from_slice(&n.to_be_bytes()); +} + +fn put_str(v: &mut Vec, s: &[u8]) { + put32(v, s.len() as u32); + v.extend_from_slice(s); +} + +fn code(c: &[u8; 4]) -> Vec { + c.to_vec() +} + +/// The payload of a message (without the frame length). `minor` is the +/// negotiated protocol minor version and picks the key message form. +pub fn encode(m: &Msg, minor: u16) -> Vec { + let lang = minor >= MINOR_LANG; + let mut v; + match m { + Msg::Hello { major, minor } => { + v = HELLO_NAME.to_vec(); + put16(&mut v, *major); + put16(&mut v, *minor); + } + Msg::HelloBack { major, minor, name } => { + v = HELLO_NAME.to_vec(); + put16(&mut v, *major); + put16(&mut v, *minor); + put_str(&mut v, name); + } + Msg::Qinf => v = code(b"QINF"), + Msg::Ciak => v = code(b"CIAK"), + Msg::Calv => v = code(b"CALV"), + Msg::Cnop => v = code(b"CNOP"), + Msg::Crop => v = code(b"CROP"), + Msg::Dsop(opts) => { + v = code(b"DSOP"); + put32(&mut v, opts.len() as u32); + for o in opts { + put32(&mut v, *o); + } + } + Msg::Csec(b) => { + v = code(b"CSEC"); + v.push(*b); + } + Msg::Cinn { x, y, seq, mods } => { + v = code(b"CINN"); + put16(&mut v, *x as u16); + put16(&mut v, *y as u16); + put32(&mut v, *seq); + put16(&mut v, *mods); + } + Msg::Cout => v = code(b"COUT"), + Msg::Cbye => v = code(b"CBYE"), + Msg::Dinf { + x, + y, + w, + h, + warp, + mx, + my, + } => { + v = code(b"DINF"); + for n in [x, y, w, h, warp, mx, my] { + put16(&mut v, *n as u16); + } + } + Msg::KeyDown { id, mods, button } => { + v = code(if lang { b"DKDL" } else { b"DKDN" }); + put16(&mut v, *id); + put16(&mut v, *mods); + put16(&mut v, *button); + if lang { + put_str(&mut v, b""); + } + } + Msg::KeyRepeat { + id, + mods, + count, + button, + } => { + v = code(b"DKRP"); + put16(&mut v, *id); + put16(&mut v, *mods); + put16(&mut v, *count); + put16(&mut v, *button); + if lang { + put_str(&mut v, b""); + } + } + Msg::KeyUp { id, mods, button } => { + v = code(b"DKUP"); + put16(&mut v, *id); + put16(&mut v, *mods); + put16(&mut v, *button); + } + Msg::MouseDown(b) => { + v = code(b"DMDN"); + v.push(*b as u8); + } + Msg::MouseUp(b) => { + v = code(b"DMUP"); + v.push(*b as u8); + } + Msg::MouseMove { x, y } => { + v = code(b"DMMV"); + put16(&mut v, *x as u16); + put16(&mut v, *y as u16); + } + Msg::Wheel { dx, dy } => { + v = code(b"DMWM"); + put16(&mut v, *dx as u16); + put16(&mut v, *dy as u16); + } + Msg::Cclp { id, seq } => { + v = code(b"CCLP"); + v.push(*id); + put32(&mut v, *seq); + } + Msg::Dclp { id, seq, mark, data } => { + v = code(b"DCLP"); + v.push(*id); + put32(&mut v, *seq); + v.push(*mark); + put_str(&mut v, data); + } + Msg::Eicv { major, minor } => { + v = code(b"EICV"); + put16(&mut v, *major); + put16(&mut v, *minor); + } + Msg::Ebsy => v = code(b"EBSY"), + Msg::Eunk => v = code(b"EUNK"), + Msg::Ebad => v = code(b"EBAD"), + Msg::Unknown(c) => v = code(c), + } + v +} + +/// A cursor over one payload; every read checks what is left. +struct Reader<'a> { + b: &'a [u8], +} + +impl<'a> Reader<'a> { + fn take(&mut self, n: usize) -> Result<&'a [u8], ProtoError> { + if self.b.len() < n { + return Err(ProtoError::Truncated); + } + let (head, rest) = self.b.split_at(n); + self.b = rest; + Ok(head) + } + + fn u8(&mut self) -> Result { + Ok(self.take(1)?[0]) + } + + fn u16(&mut self) -> Result { + let b = self.take(2)?; + Ok(u16::from_be_bytes([b[0], b[1]])) + } + + fn i16(&mut self) -> Result { + Ok(self.u16()? as i16) + } + + fn u32(&mut self) -> Result { + let b = self.take(4)?; + Ok(u32::from_be_bytes([b[0], b[1], b[2], b[3]])) + } + + /// A u32 length and that many bytes; a length beyond what is left is + /// an error before anything is allocated. + fn string(&mut self) -> Result, ProtoError> { + let n = self.u32()? as usize; + Ok(self.take(n)?.to_vec()) + } +} + +/// Decodes the first message of a payload; bytes after the message are +/// ignored. +pub fn decode(payload: &[u8]) -> Result { + let mut r = Reader { b: payload }; + let c: [u8; 4] = r.take(4)?.try_into().map_err(|_| ProtoError::Truncated)?; + Ok(match &c { + b"QINF" => Msg::Qinf, + b"CIAK" => Msg::Ciak, + b"CALV" => Msg::Calv, + b"CNOP" => Msg::Cnop, + b"CROP" => Msg::Crop, + b"COUT" => Msg::Cout, + b"CBYE" => Msg::Cbye, + b"EBSY" => Msg::Ebsy, + b"EUNK" => Msg::Eunk, + b"EBAD" => Msg::Ebad, + b"DSOP" => { + let n = r.u32()? as usize; + // Each option takes 4 bytes, so a count beyond what is left is + // an error before the vector is sized. + if n > r.b.len() / 4 { + return Err(ProtoError::Truncated); + } + let mut opts = Vec::with_capacity(n); + for _ in 0..n { + opts.push(r.u32()?); + } + Msg::Dsop(opts) + } + b"CSEC" => Msg::Csec(r.u8()?), + b"CINN" => Msg::Cinn { + x: r.i16()?, + y: r.i16()?, + seq: r.u32()?, + mods: r.u16()?, + }, + b"DINF" => Msg::Dinf { + x: r.i16()?, + y: r.i16()?, + w: r.i16()?, + h: r.i16()?, + warp: r.i16()?, + mx: r.i16()?, + my: r.i16()?, + }, + b"DKDN" | b"DKDL" => { + let m = Msg::KeyDown { + id: r.u16()?, + mods: r.u16()?, + button: r.u16()?, + }; + if &c == b"DKDL" { + r.string()?; + } + m + } + b"DKRP" => { + let m = Msg::KeyRepeat { + id: r.u16()?, + mods: r.u16()?, + count: r.u16()?, + button: r.u16()?, + }; + // The language string is present from 1.8; it is not needed. + if !r.b.is_empty() { + r.string()?; + } + m + } + b"DKUP" => Msg::KeyUp { + id: r.u16()?, + mods: r.u16()?, + button: r.u16()?, + }, + b"DMDN" => Msg::MouseDown(r.u8()? as i8), + b"DMUP" => Msg::MouseUp(r.u8()? as i8), + b"DMMV" => Msg::MouseMove { + x: r.i16()?, + y: r.i16()?, + }, + b"DMWM" => Msg::Wheel { + dx: r.i16()?, + dy: r.i16()?, + }, + b"CCLP" => Msg::Cclp { + id: r.u8()?, + seq: r.u32()?, + }, + b"DCLP" => Msg::Dclp { + id: r.u8()?, + seq: r.u32()?, + mark: r.u8()?, + data: r.string()?, + }, + b"EICV" => Msg::Eicv { + major: r.u16()?, + minor: r.u16()?, + }, + _ => Msg::Unknown(c), + }) +} + +/// The client's answer to the Hello: the protocol name, its version and its +/// screen name. The Hello has no four-letter code, so it has a decoder of +/// its own. +pub fn decode_hello_back(payload: &[u8]) -> Result { + let mut r = Reader { b: payload }; + if r.take(HELLO_NAME.len()).map_err(|_| ProtoError::BadHello)? != HELLO_NAME { + return Err(ProtoError::BadHello); + } + Ok(Msg::HelloBack { + major: r.u16()?, + minor: r.u16()?, + name: r.string()?, + }) +} + +/// A payload with its u32 length in front. +pub fn frame(payload: &[u8]) -> Vec { + let mut v = Vec::with_capacity(4 + payload.len()); + put32(&mut v, payload.len() as u32); + v.extend_from_slice(payload); + v +} + +/// Cuts a byte stream into frames. A length above MAX_MSG is refused as +/// soon as its four bytes are in, before any of the frame is buffered, and +/// the framer stays failed afterwards. +#[derive(Default)] +pub struct Framer { + buf: Vec, + failed: bool, +} + +impl Framer { + pub fn push(&mut self, bytes: &[u8]) { + if !self.failed { + self.buf.extend_from_slice(bytes); + } + } + + /// The next whole payload, or None when more bytes are needed. Not an + /// Iterator: it can fail. + #[allow(clippy::should_implement_trait)] + pub fn next(&mut self) -> Result>, ProtoError> { + if self.failed { + return Err(ProtoError::Oversize); + } + let Some(head) = self.buf.first_chunk::<4>() else { + return Ok(None); + }; + let len = u32::from_be_bytes(*head) as usize; + if len > MAX_MSG { + self.failed = true; + self.buf = Vec::new(); + return Err(ProtoError::Oversize); + } + if self.buf.len() < 4 + len { + return Ok(None); + } + let payload = self.buf[4..4 + len].to_vec(); + self.buf.drain(..4 + len); + Ok(Some(payload)) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn hello_bytes() { + assert_eq!( + encode(&Msg::Hello { major: 1, minor: 8 }, 8), + b"Barrier\x00\x01\x00\x08" + ); + } + + #[test] + fn hello_back_parses_name() { + let m = decode_hello_back(b"Barrier\0\x01\0\x08\0\0\0\x06laptop").unwrap(); + assert_eq!( + m, + Msg::HelloBack { + major: 1, + minor: 8, + name: b"laptop".to_vec() + } + ); + assert_eq!(encode(&m, 8), b"Barrier\0\x01\0\x08\0\0\0\x06laptop"); + } + + #[test] + fn hello_back_rejects_bad_input() { + assert_eq!( + decode_hello_back(b"Synergy\0\x01\0\x08\0\0\0\0"), + Err(ProtoError::BadHello) + ); + assert_eq!(decode_hello_back(b"Bar"), Err(ProtoError::BadHello)); + assert_eq!(decode_hello_back(b"Barrier\0\x01\0"), Err(ProtoError::Truncated)); + // A name longer than the frame holds is an error, not an allocation. + assert_eq!( + decode_hello_back(b"Barrier\0\x01\0\x08\xff\xff\xff\xffab"), + Err(ProtoError::Truncated) + ); + } + + #[test] + fn frame_is_be_length() { + assert_eq!(frame(b"CALV"), [0, 0, 0, 4, b'C', b'A', b'L', b'V']); + } + + #[test] + fn framer_splits_and_joins() { + let mut bytes = frame(b"CALV"); + bytes.extend(frame(b"QINF")); + let mut f = Framer::default(); + let mut got = Vec::new(); + for b in bytes { + f.push(&[b]); + while let Some(p) = f.next().unwrap() { + got.push(p); + } + } + assert_eq!(got, vec![b"CALV".to_vec(), b"QINF".to_vec()]); + } + + #[test] + fn framer_refuses_oversize() { + let mut f = Framer::default(); + f.push(&((MAX_MSG + 1) as u32).to_be_bytes()); + assert_eq!(f.next(), Err(ProtoError::Oversize)); + // It stays failed and keeps nothing. + f.push(&[0; 64]); + assert_eq!(f.next(), Err(ProtoError::Oversize)); + let mut ok = Framer::default(); + ok.push(&(MAX_MSG as u32).to_be_bytes()); + assert_eq!(ok.next(), Ok(None)); + } + + #[test] + fn key_down_v18_has_lang() { + let p = encode( + &Msg::KeyDown { + id: 0x61, + mods: 2, + button: 38, + }, + 8, + ); + assert_eq!(&p[..4], b"DKDL"); + assert!(p.ends_with(&[0, 0, 0, 0])); + assert_eq!(p.len(), 4 + 6 + 4); + } + + #[test] + fn key_down_v16_is_dkdn() { + for minor in [6, 7] { + let p = encode( + &Msg::KeyDown { + id: 0x61, + mods: 2, + button: 38, + }, + minor, + ); + assert_eq!(&p[..4], b"DKDN"); + assert_eq!(p.len(), 4 + 6); + } + } + + #[test] + fn key_repeat_v18_five_fields() { + let m = Msg::KeyRepeat { + id: 1, + mods: 2, + count: 3, + button: 4, + }; + assert_eq!(encode(&m, 8).len(), 4 + 8 + 4); + assert_eq!(encode(&m, 7).len(), 4 + 8); + assert_eq!(decode(&encode(&m, 8)), Ok(m.clone())); + assert_eq!(decode(&encode(&m, 7)), Ok(m)); + } + + #[test] + fn key_down_decodes_both_forms() { + let m = Msg::KeyDown { + id: 9, + mods: 8, + button: 7, + }; + assert_eq!(decode(&encode(&m, 8)), Ok(m.clone())); + assert_eq!(decode(&encode(&m, 6)), Ok(m)); + } + + #[test] + fn dinf_roundtrip() { + let m = Msg::Dinf { + x: 0, + y: 0, + w: 1920, + h: 1080, + warp: 0, + mx: 960, + my: 540, + }; + let p = encode(&m, 8); + assert_eq!(&p[8..10], b"\x07\x80"); + assert_eq!(decode(&p), Ok(m)); + } + + #[test] + fn cinn_layout() { + let p = encode( + &Msg::Cinn { + x: -1, + y: 300, + seq: 0x01020304, + mods: 5, + }, + 8, + ); + assert_eq!(p, b"CINN\xff\xff\x01\x2c\x01\x02\x03\x04\x00\x05"); + assert_eq!( + decode(&p), + Ok(Msg::Cinn { + x: -1, + y: 300, + seq: 0x01020304, + mods: 5 + }) + ); + } + + #[test] + fn every_message_roundtrips() { + let all = [ + Msg::Qinf, + Msg::Ciak, + Msg::Calv, + Msg::Cnop, + Msg::Crop, + Msg::Dsop(vec![]), + Msg::Dsop(vec![1, 2]), + Msg::Csec(1), + Msg::Cout, + Msg::Cbye, + Msg::KeyUp { + id: 1, + mods: 2, + button: 3, + }, + Msg::MouseDown(1), + Msg::MouseUp(-1), + Msg::MouseMove { x: -5, y: 7 }, + Msg::Wheel { dx: 0, dy: -120 }, + Msg::Cclp { id: 0, seq: 77 }, + Msg::Dclp { + id: 0, + seq: 77, + mark: 2, + data: b"text".to_vec(), + }, + Msg::Eicv { major: 1, minor: 8 }, + Msg::Ebsy, + Msg::Eunk, + Msg::Ebad, + ]; + for m in all { + assert_eq!(decode(&encode(&m, 8)), Ok(m)); + } + } + + #[test] + fn truncated_payload_is_error() { + let fixed = [ + Msg::Csec(1), + Msg::Cinn { + x: 1, + y: 2, + seq: 3, + mods: 4, + }, + Msg::Dinf { + x: 0, + y: 0, + w: 1, + h: 1, + warp: 0, + mx: 0, + my: 0, + }, + Msg::KeyDown { + id: 1, + mods: 2, + button: 3, + }, + Msg::KeyRepeat { + id: 1, + mods: 2, + count: 3, + button: 4, + }, + Msg::KeyUp { + id: 1, + mods: 2, + button: 3, + }, + Msg::MouseDown(1), + Msg::MouseUp(1), + Msg::MouseMove { x: 1, y: 2 }, + Msg::Wheel { dx: 1, dy: 2 }, + Msg::Cclp { id: 0, seq: 1 }, + Msg::Dclp { + id: 0, + seq: 1, + mark: 1, + data: b"abc".to_vec(), + }, + Msg::Eicv { major: 1, minor: 8 }, + Msg::Dsop(vec![1]), + ]; + for m in fixed { + let p = encode(&m, 8); + // Every cut inside the code is also an error; cuts after the + // code are errors for these messages, except a DKRP without + // the language string, which is the valid 1.6 form. + for cut in 0..p.len() { + let r = decode(&p[..cut]); + let valid_short = matches!(m, Msg::KeyRepeat { .. }) && cut == 12; + if !valid_short { + assert_eq!(r, Err(ProtoError::Truncated), "{m:?} cut at {cut}"); + } + } + } + } + + #[test] + fn hostile_lengths_do_not_allocate() { + assert_eq!(decode(b"DSOP\xff\xff\xff\xff"), Err(ProtoError::Truncated)); + assert_eq!( + decode(b"DCLP\0\0\0\0\x01\x01\xff\xff\xff\xffab"), + Err(ProtoError::Truncated) + ); + assert_eq!( + decode(b"DKDL\0\x01\0\x02\0\x03\xff\xff\xff\xff"), + Err(ProtoError::Truncated) + ); + } + + #[test] + fn unknown_code_kept() { + assert_eq!(decode(b"XXXXrest"), Ok(Msg::Unknown(*b"XXXX"))); + assert_eq!(encode(&Msg::Unknown(*b"XXXX"), 8), b"XXXX"); + } + + #[test] + fn decode_survives_every_short_input() { + for len in 0..16u8 { + for fill in [0u8, 0xff, b'D'] { + let p = vec![fill; len as usize]; + let _ = decode(&p); + let _ = decode_hello_back(&p); + } + } + } +} diff --git a/src/thinfloe-menu/src/deskflow/run.rs b/src/thinfloe-menu/src/deskflow/run.rs new file mode 100644 index 0000000..24b2e0c --- /dev/null +++ b/src/thinfloe-menu/src/deskflow/run.rs @@ -0,0 +1,1730 @@ +//! The Deskflow daemon, `thinfloe-menu --deskflow` (spec, Processes): the +//! TCP listener, TLS, pairing, the state file and the command socket, in +//! one poll loop. Exit 0 means there is nothing to serve (the switch is +//! off, SIGTERM, the compositor is gone); an error is written to the state +//! file's head and ends it with 1. + +use std::collections::HashMap; +use std::ffi::c_void; +use std::fs::{File, OpenOptions}; +use std::io::{self, ErrorKind}; +use std::net::{TcpListener, TcpStream}; +use std::os::fd::{AsRawFd, FromRawFd, OwnedFd, RawFd}; +use std::os::unix::fs::OpenOptionsExt; +use std::os::unix::net::UnixDatagram; +use std::path::{Path, PathBuf}; +use std::sync::Arc; +use std::sync::atomic::{AtomicI32, AtomicU64, Ordering}; +use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; + +use rustls::ServerConfig; + +use super::capture::{CapEvent, Capture, OutputGeom, StripSpec}; +use super::clip::{Clip, ClipEvent}; +use super::clipsync::{ClipAct, ClipSync}; +use super::cmd::{self, Cmd}; +use super::conn::{Conn, Event}; +use super::edge::{self, Rect, Tracker}; +use super::forward::{self, Action, Active, Keyboard}; +use super::ident::{self, Identity}; +use super::pair::{self, Pending, PendingKind, Verdict}; +use super::proto::Msg; +use super::statefile::{self, DevLine, DevState, Head, StateFile}; +use super::tls; +use crate::config::DeskflowCfg; +use crate::deskflowcfg::Generated; +use crate::kanshi::Side; + +/// The paths and the host name the daemon works with. +pub struct RunEnv { + /// `generated/deskflow`, the daemon's only configuration. + pub generated: PathBuf, + pub identity: PathBuf, + pub state: PathBuf, + pub socket: PathBuf, + pub hostname: String, + /// The OSD key command without its key ([`osd_key_command`]). + pub osd_key: Vec, +} + +/// The OSD key command of labwc's media key bindings. +const OSD_KEY_CMD: &str = "/usr/bin/thinfloe-menu --osd-key"; + +/// The command the microphone key runs while a device has the keyboard, +/// without its key: `TF_OSD_KEY_CMD` (`value`) when set, as +/// thinfloe-compose-labwc-config takes it, else the menu's `--osd-key`. +pub fn osd_key_command(value: Option<&str>) -> Vec { + let v = value.filter(|v| !v.trim().is_empty()).unwrap_or(OSD_KEY_CMD); + v.split_whitespace().map(str::to_string).collect() +} + +/// Starts `cmd key` in a process group of its own, stdin from /dev/null; +/// the caller reaps it. +/// At most this many OSD key commands run at once; a press beyond them is +/// dropped, so a hung command cannot pile up children. +const OSD_KEYS_MAX: usize = 4; + +/// A media key the daemon runs itself: nothing when `enabled` (the volume +/// key switch) is off or [OSD_KEYS_MAX] commands are still running. +fn press_osd_key(enabled: bool, cmd: &[String], running: &mut Vec, key: &str) { + if !enabled { + return; + } + running.retain_mut(|c| matches!(c.try_wait(), Ok(None))); + if running.len() >= OSD_KEYS_MAX { + eprintln!("thinfloe-menu --deskflow: the {key} key: {OSD_KEYS_MAX} commands still run"); + return; + } + match spawn_osd_key(cmd, key) { + Ok(c) => running.push(c), + Err(e) => eprintln!("thinfloe-menu --deskflow: the {key} key: {e}"), + } +} + +fn spawn_osd_key(cmd: &[String], key: &str) -> io::Result { + use std::os::unix::process::CommandExt; + let (prog, args) = cmd + .split_first() + .ok_or_else(|| io::Error::new(ErrorKind::InvalidInput, "no OSD key command"))?; + std::process::Command::new(prog) + .args(args) + .arg(key) + .process_group(0) + .stdin(std::process::Stdio::null()) + .spawn() +} + +/// The longest poll; the watchdog's heartbeat is stored once per turn. +const TURN: Duration = Duration::from_millis(250); +/// The watchdog ends the process when the loop has not turned for this long. +const STALL: Duration = Duration::from_secs(2); +/// The watchdog's exit status (EX_SOFTWARE). +const STALL_EXIT: i32 = 70; +/// At most this many connections may be in TLS, Hello or the verdict. +const MAX_HANDSHAKES: usize = 4; +/// At most this many connections are taken from the listener per turn. +const MAX_ACCEPTS: usize = 64; +/// A capture whose pointer lock is not active this long after it was +/// asked for is given up. +const LOCK_WAIT: Duration = Duration::from_millis(500); +/// The largest generated/deskflow read. +const CONFIG_MAX: u64 = 256 * 1024; + +pub fn run(env: RunEnv) -> Result<(), String> { + let _lock = lock(&env.state)?; + let cfg = read_config(&env.generated).map_err(|e| fail(&env.state, e))?; + if !cfg.deskflow.listen { + return Ok(()); + } + let id = + ident::load_or_create(&env.identity, &env.hostname).map_err(|e| fail(&env.state, format!("identity: {e}")))?; + let listener = listen(cfg.deskflow.port).map_err(|e| fail(&env.state, e))?; + let sock = cmd::bind(&env.socket).map_err(|e| fail(&env.state, format!("command socket: {e}")))?; + let wake = Wake::new().map_err(|e| fail(&env.state, e))?; + wake.install_signals(); + // The menu starts the daemon with SIGHUP blocked, so a reload before + // the handler was set waits for it instead of ending the daemon. + unblock_sighup(); + let capture = Capture::connect().map_err(|e| fail(&env.state, e))?; + let beat = Watchdog::start(); + let mut d = Daemon::new(env, cfg, &id, listener, sock, Some(capture)); + d.clip = match Clip::connect() { + Ok(c) => Some(c), + Err(e) => { + eprintln!("thinfloe-menu --deskflow: no clipboard sharing: {e}"); + None + } + }; + d.serve(&wake, Some(&beat)) +} + +/// Unblock SIGHUP for this thread; a reload that waited arrives now. +fn unblock_sighup() { + // SAFETY: a sigset on the stack, filled by sigemptyset and sigaddset. + unsafe { + let mut set: libc::sigset_t = std::mem::zeroed(); + libc::sigemptyset(&mut set); + libc::sigaddset(&mut set, libc::SIGHUP); + libc::pthread_sigmask(libc::SIG_UNBLOCK, &set, std::ptr::null_mut()); + } +} + +/// Writes the error head and hands the text back. +fn fail(state: &Path, why: String) -> String { + let s = StateFile { + head: Head::Error(why.clone()), + devices: Vec::new(), + }; + if let Err(e) = statefile::write(state, &s) { + eprintln!("thinfloe-menu --deskflow: {}: {e}", state.display()); + } + why +} + +/// One daemon per state file: an exclusive lock on `.lock`, held +/// for the life of the process, comes before the command socket, whose +/// bind removes the socket of a running daemon. +fn lock(state: &Path) -> Result { + let mut path = state.as_os_str().to_owned(); + path.push(".lock"); + let path = PathBuf::from(path); + let f = OpenOptions::new() + .read(true) + .write(true) + .create(true) + .truncate(false) + .mode(0o600) + .open(&path) + .map_err(|e| format!("{}: {e}", path.display()))?; + // SAFETY: flock on a valid descriptor owned by f. + if unsafe { libc::flock(f.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) } != 0 { + let e = io::Error::last_os_error(); + if e.kind() == ErrorKind::WouldBlock { + return Err("another deskflow daemon runs".into()); + } + return Err(format!("{}: {e}", path.display())); + } + Ok(f) +} + +/// The configuration in generated/deskflow; none there means the switch +/// is off. +fn read_config(path: &Path) -> Result { + let Some(bytes) = crate::atomic::read(path, CONFIG_MAX).map_err(|e| format!("generated/deskflow: {e}"))? else { + return Ok(Generated::default()); + }; + let text = String::from_utf8(bytes).map_err(|_| "generated/deskflow: not UTF-8".to_string())?; + let g = crate::deskflowcfg::parse(&text)?; + crate::deskflowcfg::validate(&g.deskflow)?; + Ok(g) +} + +fn listen(port: u16) -> Result { + let l = TcpListener::bind(("0.0.0.0", port)).map_err(|e| match e.kind() { + ErrorKind::AddrInUse => format!("port {port} in use"), + _ => format!("port {port}: {e}"), + })?; + l.set_nonblocking(true).map_err(|e| format!("port {port}: {e}"))?; + Ok(l) +} + +/// The write end of the signal pipe, for the handler. +static SIGNAL_FD: AtomicI32 = AtomicI32::new(-1); + +extern "C" fn on_signal(sig: libc::c_int) { + let fd = SIGNAL_FD.load(Ordering::Relaxed); + if fd >= 0 { + // SAFETY: write and errno are async-signal-safe; errno is put back + // so the interrupted code does not see the handler's. + unsafe { + let errno = *libc::__errno_location(); + let b = sig as u8; + libc::write(fd, (&b as *const u8).cast::(), 1); + *libc::__errno_location() = errno; + } + } +} + +/// A self-pipe: one byte per signal (its number), read by the loop. +struct Wake { + rd: OwnedFd, + wr: OwnedFd, +} + +impl Wake { + fn new() -> Result { + let mut fds = [0 as RawFd; 2]; + // SAFETY: pipe2 fills two descriptors on success, owned from here. + if unsafe { libc::pipe2(fds.as_mut_ptr(), libc::O_NONBLOCK | libc::O_CLOEXEC) } != 0 { + return Err(format!("pipe: {}", io::Error::last_os_error())); + } + // SAFETY: both are fresh descriptors nobody else owns. + Ok(unsafe { + Wake { + rd: OwnedFd::from_raw_fd(fds[0]), + wr: OwnedFd::from_raw_fd(fds[1]), + } + }) + } + + /// SIGTERM and SIGHUP write to this pipe. + fn install_signals(&self) { + SIGNAL_FD.store(self.wr.as_raw_fd(), Ordering::Relaxed); + for sig in [libc::SIGTERM, libc::SIGHUP] { + // SAFETY: a zeroed sigaction with a handler that only writes + // to a pipe. + unsafe { + let mut sa: libc::sigaction = std::mem::zeroed(); + sa.sa_sigaction = on_signal as *const () as libc::sighandler_t; + sa.sa_flags = libc::SA_RESTART; + libc::sigemptyset(&mut sa.sa_mask); + libc::sigaction(sig, &sa, std::ptr::null_mut()); + } + } + } + + /// Delivers a signal number as the handler would (tests). + #[cfg(test)] + fn send(&self, sig: libc::c_int) { + let b = sig as u8; + // SAFETY: a one-byte write to our own pipe. + unsafe { libc::write(self.wr.as_raw_fd(), (&b as *const u8).cast::(), 1) }; + } + + /// The signals that arrived since the last call. + fn take(&self) -> Vec { + let mut buf = [0u8; 64]; + let mut sigs = Vec::new(); + loop { + // SAFETY: a read into a buffer of its length. + let n = unsafe { libc::read(self.rd.as_raw_fd(), buf.as_mut_ptr().cast::(), buf.len()) }; + if n <= 0 { + return sigs; + } + sigs.extend(buf[..n as usize].iter().map(|&b| b as libc::c_int)); + } + } +} + +impl Drop for Wake { + fn drop(&mut self) { + let _ = SIGNAL_FD.compare_exchange(self.wr.as_raw_fd(), -1, Ordering::Relaxed, Ordering::Relaxed); + } +} + +/// A thread that ends the process when the loop stalls: the compositor then +/// drops the pointer lock and the keyboard focus (spec, Release always +/// wins). +struct Watchdog { + start: Instant, + beat: Arc, +} + +impl Watchdog { + fn start() -> Watchdog { + let start = Instant::now(); + let beat = Arc::new(AtomicU64::new(0)); + let seen = beat.clone(); + std::thread::spawn(move || { + loop { + std::thread::sleep(Duration::from_millis(500)); + let now = start.elapsed().as_millis() as u64; + if now.saturating_sub(seen.load(Ordering::Relaxed)) > STALL.as_millis() as u64 { + eprintln!("thinfloe-menu --deskflow: the event loop stalled; exiting"); + // SAFETY: ends the process at once, without unwinding. + unsafe { libc::_exit(STALL_EXIT) }; + } + } + }); + Watchdog { start, beat } + } + + fn beat(&self) { + self.beat + .store(self.start.elapsed().as_millis() as u64, Ordering::Relaxed); + } +} + +fn epoch_now() -> i64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .map_or(0, |d| d.as_secs() as i64) +} + +/// What a turn decides. +enum Next { + Go, + Exit(Result<(), String>), +} + +/// A strip shown for a connected device, with what the capture needs of +/// it. Its id is the connection's. +struct Strip { + spec: StripSpec, + /// The output's logical rectangle. + out: Rect, + side: Side, + /// The device's screen, from its DINF. + dev: (i16, i16), +} + +/// The pointer on a strip: where, and the push into the edge so far. +struct Hover { + strip: u32, + at: (f64, f64), + push: edge::Resistance, +} + +/// Who has the keyboard and the pointer. +enum Mode { + /// ThinFloe. + Idle, + /// A capture of this strip waits for its pointer lock. + Locking { + strip: u32, + since: Instant, + }, + Active(Active), +} + +struct Daemon { + env: RunEnv, + cfg: DeskflowCfg, + /// generated/deskflow's `mic_mute_local`. + mic_mute_local: bool, + /// The OSD key commands started and not yet reaped. + osd_keys: Vec, + tls: Arc, + fingerprint: String, + listener: TcpListener, + sock: UnixDatagram, + capture: Option, + /// The clipboard bridge; none when the compositor has no data control + /// or the bridge failed. + clip: Option, + sync: ClipSync, + conns: Vec, + pending: Pending, + /// The last DINF size of each (name, fingerprint). + screens: HashMap<(String, String), (u32, u32)>, + /// Each line's state and when it took it. + since: HashMap<(String, String), (DevState, i64)>, + /// The text last written to the state file. + written: Option, + /// The id the next connection gets. + next_id: usize, + /// The compositor's outputs, as of the last `OutputsChanged`. + outputs: Vec, + strips: Vec, + /// Connected devices without a strip: their output is missing, or + /// their edge touches another output. + offline: Vec, + busy: Vec, + hover: Option, + mode: Mode, + kb: Keyboard, + /// The `Unlocked` events that our own `end_capture` calls queued. + own_unlocks: usize, +} + +impl Daemon { + fn new( + env: RunEnv, + cfg: Generated, + id: &Identity, + listener: TcpListener, + sock: UnixDatagram, + capture: Option, + ) -> Daemon { + Daemon { + env, + cfg: cfg.deskflow, + mic_mute_local: cfg.mic_mute_local, + osd_keys: Vec::new(), + tls: tls::server_config(id), + fingerprint: ident::fingerprint(&id.cert_der), + listener, + sock, + outputs: capture.as_ref().map(Capture::outputs).unwrap_or_default(), + capture, + clip: None, + sync: ClipSync::default(), + conns: Vec::new(), + pending: Pending::default(), + screens: HashMap::new(), + since: HashMap::new(), + written: None, + next_id: 1, + strips: Vec::new(), + offline: Vec::new(), + busy: Vec::new(), + hover: None, + mode: Mode::Idle, + kb: Keyboard::default(), + own_unlocks: 0, + } + } + + /// The loop, until SIGTERM, the switch going off, the compositor + /// going away or an error. + fn serve(&mut self, wake: &Wake, beat: Option<&Watchdog>) -> Result<(), String> { + self.write_state(); + let result = loop { + if let Some(b) = beat { + b.beat(); + } + if let Next::Exit(r) = self.turn(wake) { + break r; + } + }; + // Every connection ends with the daemon, the device that has the + // pointer first gets its keys and buttons up and COUT, then each a + // CBYE; a failure has written its head already. + self.release("the daemon ends"); + for c in &mut self.conns { + c.send(Msg::Cbye); + c.close("the daemon ends"); + c.flush(); + } + if let Some(c) = self.capture.as_mut() { + let _ = c.flush(); + } + self.conns.clear(); + if result.is_ok() { + self.write_state(); + } + result + } + + fn turn(&mut self, wake: &Wake) -> Next { + self.reap(); + if let Some(c) = self.capture.as_mut() + && c.flush().is_err() + { + return Next::Exit(Ok(())); + } + if let Some(e) = self.clip.as_mut().and_then(|c| c.flush().err()) { + self.drop_clip(&e); + } + const IN: libc::c_short = libc::POLLIN; + let mut fds = vec![ + pollfd(wake.rd.as_raw_fd(), IN), + pollfd(self.sock.as_raw_fd(), IN), + pollfd(self.listener.as_raw_fd(), IN), + pollfd(self.capture.as_ref().map_or(-1, |c| c.fd().as_raw_fd()), IN), + pollfd(self.clip.as_ref().map_or(-1, |c| c.fd().as_raw_fd()), IN), + ]; + let fixed = fds.len(); + for c in &self.conns { + let ev = if c.wants_write() { IN | libc::POLLOUT } else { IN }; + fds.push(pollfd(c.fd(), ev)); + } + let pipes = fds.len(); + if let Some(c) = &self.clip { + fds.extend(c.pipe_fds().into_iter().map(|(fd, ev)| pollfd(fd, ev))); + } + let timeout = self.poll_timeout(Instant::now()); + // SAFETY: fds is a valid array of its length for the call. + let r = unsafe { libc::poll(fds.as_mut_ptr(), fds.len() as libc::nfds_t, timeout) }; + if r < 0 { + let e = io::Error::last_os_error(); + if e.kind() == ErrorKind::Interrupted { + return Next::Go; + } + return Next::Exit(Err(fail(&self.env.state, format!("poll: {e}")))); + } + let ready = |i: usize| fds[i].revents != 0; + let now = Instant::now(); + if ready(0) { + for sig in wake.take() { + let next = match sig { + libc::SIGTERM => { + self.release("SIGTERM"); + Next::Exit(Ok(())) + } + libc::SIGHUP => self.reload(), + _ => Next::Go, + }; + if let Next::Exit(_) = next { + return next; + } + } + } + if ready(1) + && let Next::Exit(r) = self.commands() + { + return Next::Exit(r); + } + if ready(3) && self.capture.is_some() { + // Wayland gone: labwc has ended, and the session with it. + if fds[3].revents & (libc::POLLERR | libc::POLLHUP) != 0 { + return Next::Exit(Ok(())); + } + match self.capture.as_mut().map(Capture::dispatch) { + Some(Ok(events)) => self.on_capture(events, now), + _ => return Next::Exit(Ok(())), + } + } + let known = self.conns.len(); + for i in 0..known { + let revents = fds[fixed + i].revents; + if revents == 0 { + continue; + } + let events = self.conns[i].on_readable(now); + self.on_events(i, events, now); + } + self.on_clip(ready(4).then_some(fds[4].revents), &fds[pipes..], now); + if ready(2) { + self.accept(now); + } + self.timers(now); + for c in &mut self.conns { + c.tick(now); + } + self.check_device(); + self.update_strips(); + for c in &mut self.conns { + c.flush(); + } + self.conns.retain(|c| c.closing().is_none()); + self.write_state(); + Next::Go + } + + /// The poll timeout: a turn, or less when a key repeat or the lock + /// deadline is due sooner. + fn poll_timeout(&self, now: Instant) -> libc::c_int { + let due = match &self.mode { + Mode::Idle => None, + Mode::Locking { since, .. } => Some(*since + LOCK_WAIT), + Mode::Active(a) => a.deadline(), + }; + let due = match (due, self.clip.as_ref().and_then(Clip::deadline)) { + (Some(a), Some(b)) => Some(a.min(b)), + (a, b) => a.or(b), + }; + let wait = due.map_or(TURN, |d| d.saturating_duration_since(now).min(TURN)); + // Rounded up, so the loop does not spin before the deadline. + wait.as_micros().div_ceil(1000) as libc::c_int + } + + /// The lock deadline and the key repeat. + fn timers(&mut self, now: Instant) { + match &mut self.mode { + Mode::Idle => {} + Mode::Locking { since, .. } => { + if now.saturating_duration_since(*since) >= LOCK_WAIT { + self.release("no pointer lock within 500 ms"); + } + } + Mode::Active(a) => { + let acts = forward::tick(a, &self.kb, now); + self.forward(acts); + } + } + } + + /// The events of the Wayland connection. A changed output layout is + /// taken first, so a capture whose output went is released for that + /// reason. + fn on_capture(&mut self, events: Vec, now: Instant) { + if events.iter().any(|e| matches!(e, CapEvent::OutputsChanged)) { + if let Some(c) = &self.capture { + self.outputs = c.outputs(); + } + self.update_strips(); + } + for ev in &events { + self.on_cap_event(ev, now); + } + } + + fn on_cap_event(&mut self, ev: &CapEvent, now: Instant) { + match *ev { + CapEvent::Enter { strip, x, y } => { + self.hover = Some(Hover { + strip, + at: (x, y), + push: edge::Resistance::new(self.cfg.edge_resistance.px()), + }); + } + CapEvent::Motion { x, y } => { + if let Some(h) = self.hover.as_mut() { + h.at = (x, y); + } + } + CapEvent::Leave { strip } => { + if self.hover.as_ref().is_some_and(|h| h.strip == strip) { + self.hover = None; + } + } + // The one our own end_capture reported. + CapEvent::Unlocked if self.own_unlocks > 0 => { + self.own_unlocks -= 1; + return; + } + _ => {} + } + match &mut self.mode { + Mode::Active(a) => { + let acts = forward::on_cap_event(a, ev, &mut self.kb, now); + self.forward(acts); + } + Mode::Locking { .. } => { + self.kb.update(ev); + match ev { + CapEvent::Locked => self.enter_device(), + CapEvent::Unlocked => self.release("unlocked"), + _ => {} + } + } + Mode::Idle => { + self.kb.update(ev); + match *ev { + CapEvent::Relative { + dx_unaccel, dy_unaccel, .. + } if dx_unaccel.is_finite() && dy_unaccel.is_finite() => { + self.push_edge(dx_unaccel, dy_unaccel, now) + } + _ => {} + } + } + } + } + + /// Motion on a strip pushes into its edge; enough of it begins the + /// capture. + fn push_edge(&mut self, dx: f64, dy: f64, now: Instant) { + let Some(h) = self.hover.as_mut() else { + return; + }; + let Some(s) = self.strips.iter().find(|s| s.spec.id == h.strip) else { + return; + }; + if !h.push.push(s.side, dx, dy, now) { + return; + } + h.push.reset(); + let strip = h.strip; + if let Some(c) = self.capture.as_mut() { + c.begin_capture(strip); + } + self.mode = Mode::Locking { strip, since: now }; + } + + /// The lock is active: CINN where the pointer left the edge. + fn enter_device(&mut self) { + let Mode::Locking { strip, .. } = self.mode else { + return; + }; + let Some((out, side, dev, rect)) = self + .strips + .iter() + .find(|s| s.spec.id == strip) + .map(|s| (s.out, s.side, s.dev, s.spec.rect)) + else { + return self.release("the strip went"); + }; + let middle = ( + f64::from(rect.x) + f64::from(rect.w) / 2.0, + f64::from(rect.y) + f64::from(rect.h) / 2.0, + ); + let at = self + .hover + .as_ref() + .filter(|h| h.strip == strip) + .map_or(middle, |h| h.at); + let entry = edge::entry_point(out, side, at, dev); + let device = strip as usize; + let mods = self.kb.mask(); + let Some(i) = self.conns.iter().position(|c| c.id() == device && c.trusted()) else { + return self.release("connection closed"); + }; + let shares = self.shares_clipboard(&self.conns[i]); + self.conns[i].enter(entry.0, entry.1, mods); + self.mode = Mode::Active(Active::new(device, Tracker::new(side, entry, dev), entry)); + let acts = self.sync.on_enter(device, shares); + self.clip_acts(acts); + } + + /// The device's Clipboard switch; off for a connection without one. + fn shares_clipboard(&self, c: &Conn) -> bool { + self.cfg + .devices + .iter() + .find(|d| c.name() == Some(&d.name) && c.fingerprint() == Some(&d.fingerprint)) + .is_some_and(|d| d.clipboard) + } + + /// The trusted connections and their Clipboard switch, for ClipSync. + fn clip_live(&self) -> Vec<(usize, bool)> { + self.conns + .iter() + .filter(|c| c.trusted()) + .map(|c| (c.id(), self.shares_clipboard(c))) + .collect() + } + + /// The bridge's descriptor and pipes, as poll left them. An error + /// drops the bridge; the daemon serves on without a clipboard. + fn on_clip(&mut self, revents: Option, pipes: &[libc::pollfd], now: Instant) { + let Some(clip) = self.clip.as_mut() else { + return; + }; + let mut events = Vec::new(); + if let Some(r) = revents { + if r & (libc::POLLERR | libc::POLLHUP) != 0 { + return self.drop_clip("the compositor closed the connection"); + } + match clip.dispatch(now) { + Ok(ev) => events = ev, + Err(e) => return self.drop_clip(&e), + } + } + for p in pipes.iter().filter(|p| p.revents != 0) { + events.extend(clip.on_pipe_ready(p.fd, now)); + } + events.extend(clip.tick(now)); + let active = match &self.mode { + Mode::Active(a) => Some(a.device), + _ => None, + }; + for ev in events { + let acts = match ev { + ClipEvent::Changed(text) => self.sync.on_local(text, active, &self.clip_live()), + ClipEvent::Cleared => self.sync.on_cleared(&self.clip_live()), + }; + self.clip_acts(acts); + } + } + + fn drop_clip(&mut self, why: &str) { + eprintln!("thinfloe-menu --deskflow: clipboard sharing ends: {why}"); + self.clip = None; + } + + fn clip_acts(&mut self, acts: Vec) { + for act in acts { + match act { + ClipAct::Send { conn, text } => { + if let Some(c) = self.conns.iter_mut().find(|c| c.id() == conn) { + c.clipboard(&text); + } + } + ClipAct::Grab { conn } => { + if let Some(c) = self.conns.iter_mut().find(|c| c.id() == conn) { + c.grab(); + } + } + ClipAct::SetLocal(text) => { + if let Some(c) = self.clip.as_mut() { + c.set_text(text); + } + } + } + } + } + + fn forward(&mut self, acts: Vec) { + for act in acts { + match act { + Action::Send(m) => { + let Mode::Active(a) = &self.mode else { + return; + }; + let id = a.device; + if let Some(c) = self.conns.iter_mut().find(|c| c.id() == id) { + c.send(m); + } + } + Action::Release(why) => self.release(why), + Action::LocalMicMute => self.local_mic_mute(), + } + } + } + + /// The microphone key while a device has the keyboard: labwc's binding + /// cannot act, so the daemon runs it, when the volume keys are on. It + /// does not wait; `reap` collects the command. + fn local_mic_mute(&mut self) { + press_osd_key(self.mic_mute_local, &self.env.osd_key, &mut self.osd_keys, "mic-mute"); + } + + /// Collects the OSD key commands that ended. + fn reap(&mut self) { + self.osd_keys.retain_mut(|c| matches!(c.try_wait(), Ok(None))); + } + + /// Gives keyboard and pointer back to ThinFloe at once: the device gets + /// a key up for every key and button sent down and COUT, the lock and + /// the keyboard focus go. + fn release(&mut self, reason: &str) { + match std::mem::replace(&mut self.mode, Mode::Idle) { + Mode::Idle => return, + Mode::Locking { .. } => {} + Mode::Active(mut a) => { + let msgs = forward::release(&mut a, &self.kb); + if let Some(c) = self.conns.iter_mut().find(|c| c.id() == a.device) { + for m in msgs { + c.send(m); + } + } + } + } + if let Some(c) = self.capture.as_mut() + && c.end_capture() + { + self.own_unlocks += 1; + } + if let Some(h) = self.hover.as_mut() { + h.push.reset(); + } + eprintln!("thinfloe-deskflow: released ({reason})"); + } + + /// The device of a capture must still be connected. + fn check_device(&mut self) { + let id = match &self.mode { + Mode::Idle => return, + Mode::Locking { strip, .. } => *strip as usize, + Mode::Active(a) => a.device, + }; + if !self.conns.iter().any(|c| c.id() == id && c.trusted()) { + self.release("connection closed"); + } + } + + /// The strips the devices need now: one per connected device whose + /// output exists and whose edge is free. Also the ids of the connected + /// devices without an output and of those whose edge is not free. + fn wanted_strips(&self) -> (Vec, Vec, Vec) { + let rect = |o: &OutputGeom| Rect { + x: o.x, + y: o.y, + w: o.w, + h: o.h, + }; + let (mut strips, mut offline, mut busy) = (Vec::new(), Vec::new(), Vec::new()); + for c in self.conns.iter().filter(|c| c.trusted()) { + let Some((w, h)) = c.screen().filter(|(w, h)| *w > 0 && *h > 0) else { + continue; + }; + let Some(d) = self + .cfg + .devices + .iter() + .find(|d| c.name() == Some(&d.name) && c.fingerprint() == Some(&d.fingerprint)) + else { + continue; + }; + let Some(o) = self.outputs.iter().find(|o| o.matches(&d.output)) else { + offline.push(c.id()); + continue; + }; + let others: Vec = self.outputs.iter().filter(|p| p.name != o.name).map(rect).collect(); + if !edge::edge_free(rect(o), d.side, &others) { + busy.push(c.id()); + continue; + } + strips.push(Strip { + spec: StripSpec { + id: c.id() as u32, + output: o.name.clone(), + rect: edge::strip_rect(rect(o), d.side), + }, + out: rect(o), + side: d.side, + dev: (w, h), + }); + } + (strips, offline, busy) + } + + /// Shows the strips the devices need; a capture whose strip goes or + /// moves is released first. + fn update_strips(&mut self) { + let (strips, offline, busy) = self.wanted_strips(); + let spec = |all: &[Strip], id: u32| all.iter().find(|s| s.spec.id == id).map(|s| s.spec.clone()); + let captured = match &self.mode { + Mode::Idle => None, + Mode::Locking { strip, .. } => Some(*strip), + Mode::Active(a) => Some(a.device as u32), + }; + if let Some(id) = captured { + let now = spec(&strips, id); + if now != spec(&self.strips, id) { + let why = match now { + Some(_) => "the output changed", + None if offline.contains(&(id as usize)) => "output gone", + None if busy.contains(&(id as usize)) => "the edge is not free", + None => "the device went", + }; + self.release(why); + } + } + if let Some(h) = &self.hover + && (spec(&strips, h.strip).is_none() || spec(&strips, h.strip) != spec(&self.strips, h.strip)) + { + self.hover = None; + } + let specs: Vec = strips.iter().map(|s| s.spec.clone()).collect(); + if let Some(c) = self.capture.as_mut() { + // A strip the compositor closed counts as missing. + let closed = c.take_closed(Instant::now()); + if closed || self.strips.iter().map(|s| &s.spec).ne(specs.iter()) { + c.set_strips(&specs); + } + } + (self.strips, self.offline, self.busy) = (strips, offline, busy); + } + + fn accept(&mut self, now: Instant) { + for _ in 0..MAX_ACCEPTS { + let stream: TcpStream = match self.listener.accept() { + Ok((s, _)) => s, + Err(e) if e.kind() == ErrorKind::WouldBlock => return, + Err(e) if e.kind() == ErrorKind::Interrupted => continue, + Err(e) => { + eprintln!("thinfloe-menu --deskflow: accept: {e}"); + return; + } + }; + if self.conns.iter().filter(|c| c.in_handshake()).count() >= MAX_HANDSHAKES { + drop(stream); + continue; + } + let id = self.next_id; + self.next_id += 1; + match Conn::new(id, stream, self.tls.clone(), now) { + Ok(c) => self.conns.push(c), + Err(e) => eprintln!("thinfloe-menu --deskflow: {e}"), + } + } + } + + fn on_events(&mut self, i: usize, events: Vec, now: Instant) { + for ev in events { + match ev { + Event::Named(name) => self.judge(i, &name, now), + Event::Screen { w, h } => { + if let Some(fp) = self.conns[i].fingerprint() { + let key = (name_of(&self.conns[i]), fp.to_string()); + self.screens.insert(key, (w.max(0) as u32, h.max(0) as u32)); + } + } + Event::Clipboard(text) => { + let acts = self.sync.on_remote(self.conns[i].id(), text); + self.clip_acts(acts); + } + Event::Grabbed => { + let acts = self.sync.on_grabbed(self.conns[i].id(), &self.clip_live()); + self.clip_acts(acts); + } + } + } + } + + /// The verdict on a named connection, given in the same pass. + fn judge(&mut self, i: usize, name: &str, now: Instant) { + let fp = self.conns[i].fingerprint().unwrap_or_default().to_string(); + let v = pair::judge(&self.cfg.devices, name, &fp); + match v { + Verdict::Trusted(_) => { + let busy = self + .conns + .iter() + .enumerate() + .any(|(j, c)| j != i && c.trusted() && c.name() == Some(name)); + if busy { + self.conns[i].refuse_busy(now); + return; + } + } + Verdict::Pending => self.pending.note(name, &fp, PendingKind::New, epoch_now() as u64), + Verdict::FingerprintChanged => { + self.pending + .note(name, &fp, PendingKind::FingerprintChanged, epoch_now() as u64) + } + } + self.conns[i].set_verdict(v, now); + if let Verdict::Trusted(_) = v { + let shares = self.shares_clipboard(&self.conns[i]); + self.conns[i].set_clipboard(shares); + } + } + + fn commands(&mut self) -> Next { + let mut buf = [0u8; cmd::DATAGRAM_MAX + 1]; + loop { + let n = match self.sock.recv(&mut buf) { + Ok(n) => n, + Err(e) if e.kind() == ErrorKind::Interrupted => continue, + Err(_) => return Next::Go, + }; + match cmd::decode(&buf[..n]) { + Some(Cmd::Reload) => { + if let Next::Exit(r) = self.reload() { + return Next::Exit(r); + } + } + Some(Cmd::Reject { name, fingerprint }) => self.pending.reject(&name, &fingerprint), + None => eprintln!("thinfloe-menu --deskflow: a command it does not know"), + } + } + } + + /// Reads generated/deskflow again. + fn reload(&mut self) -> Next { + let Generated { + deskflow: cfg, + mic_mute_local, + } = match read_config(&self.env.generated) { + Ok(c) => c, + Err(e) => return Next::Exit(Err(fail(&self.env.state, e))), + }; + self.mic_mute_local = mic_mute_local; + if !cfg.listen { + return Next::Exit(Ok(())); + } + if cfg.port != self.cfg.port { + match listen(cfg.port) { + Ok(l) => self.listener = l, + Err(e) => return Next::Exit(Err(fail(&self.env.state, e))), + } + } + for c in &mut self.conns { + if !c.trusted() { + continue; + } + let (name, fp) = (c.name().unwrap_or_default(), c.fingerprint().unwrap_or_default()); + if !cfg.devices.iter().any(|d| d.name == name && d.fingerprint == fp) { + c.close("the device was forgotten"); + } + } + self.pending.forget_trusted(&cfg.devices); + let before = self.clip_live(); + self.cfg = cfg; + for (conn, shares) in self.clip_live() { + if !before.contains(&(conn, shares)) { + self.sync.forget(conn); + } + } + for i in 0..self.conns.len() { + if self.conns[i].trusted() { + let shares = self.shares_clipboard(&self.conns[i]); + self.conns[i].set_clipboard(shares); + } + } + Next::Go + } + + /// The state file as it is now. + fn state(&mut self) -> StateFile { + let now = epoch_now(); + let mut lines: Vec<(String, String, DevState, Vec)> = Vec::new(); + let active = match &self.mode { + Mode::Active(a) => Some(a.device), + _ => None, + }; + for d in &self.cfg.devices { + let on = self.conns.iter().find(|c| { + c.trusted() + && c.screen().is_some() + && c.name() == Some(&d.name) + && c.fingerprint() == Some(&d.fingerprint) + }); + let (state, flags) = match on.map(Conn::id) { + None => (DevState::Offline, Vec::new()), + Some(id) if active == Some(id) => (DevState::Active, Vec::new()), + Some(id) if self.offline.contains(&id) => (DevState::Offline, Vec::new()), + Some(id) if self.busy.contains(&id) => (DevState::Connected, vec!["edge-busy".to_string()]), + Some(_) => (DevState::Connected, Vec::new()), + }; + lines.push((d.name.clone(), d.fingerprint.clone(), state, flags)); + } + for e in self.pending.entries() { + let flags = match e.kind { + PendingKind::FingerprintChanged => vec!["fp-changed".to_string()], + PendingKind::New => Vec::new(), + }; + lines.push((e.name.clone(), e.fingerprint.clone(), DevState::Pending, flags)); + } + for (n, f) in self.pending.rejected() { + if !self.cfg.devices.iter().any(|d| &d.name == n && &d.fingerprint == f) { + lines.push((n.clone(), f.clone(), DevState::Rejected, Vec::new())); + } + } + let mut since = HashMap::new(); + let devices = lines + .into_iter() + .map(|(name, fingerprint, state, flags)| { + let key = (name.clone(), fingerprint.clone()); + let t = match self.since.get(&key) { + Some(&(s, t)) if s == state => t, + _ => now, + }; + since.insert(key.clone(), (state, t)); + let (width, height) = self.screens.get(&key).copied().unwrap_or((0, 0)); + DevLine { + name, + fingerprint, + state, + since: t, + width, + height, + flags, + } + }) + .collect(); + self.since = since; + let listen = self + .listener + .local_addr() + .map_or_else(|_| format!("0.0.0.0:{}", self.cfg.port), |a| a.to_string()); + StateFile { + head: Head::SelfInfo { + fingerprint: self.fingerprint.clone(), + listen, + }, + devices, + } + } + + /// Writes the state file when a line changed. + fn write_state(&mut self) { + let text = statefile::render(&self.state()); + if self.written.as_deref() == Some(text.as_str()) { + return; + } + if let Err(e) = crate::atomic::write(&self.env.state, text.as_bytes(), 0o600) { + eprintln!("thinfloe-menu --deskflow: {}: {e}", self.env.state.display()); + } + self.written = Some(text); + } +} + +fn name_of(c: &Conn) -> String { + c.name().unwrap_or_default().to_string() +} + +fn pollfd(fd: RawFd, events: libc::c_short) -> libc::pollfd { + libc::pollfd { fd, events, revents: 0 } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::deskflow::proto::{self, Msg}; + use crate::deskflow::tls::testclient; + use crate::testdir::TestDir; + use std::io::{Read, Write}; + use std::sync::mpsc; + use std::thread::JoinHandle; + + type Client = rustls::StreamOwned; + + fn test_env(d: &TestDir, s: &TestDir) -> RunEnv { + RunEnv { + generated: d.join("generated/deskflow"), + identity: d.join("deskflow/identity.pem"), + state: d.join("state"), + socket: s.socket("s"), + hostname: "test".into(), + osd_key: osd_key_command(None), + } + } + + #[test] + fn the_osd_key_command_follows_tf_osd_key_cmd() { + assert_eq!(osd_key_command(None), ["/usr/bin/thinfloe-menu", "--osd-key"]); + assert_eq!(osd_key_command(Some(" ")), ["/usr/bin/thinfloe-menu", "--osd-key"]); + assert_eq!(osd_key_command(Some("sh /tmp/rec.sh")), ["sh", "/tmp/rec.sh"]); + } + + #[test] + fn the_osd_key_runs_with_its_key_in_a_group_of_its_own() { + let d = TestDir::new("deskflow-run", "osd-key"); + let out = d.join("key"); + let cmd = vec![ + "sh".to_string(), + "-c".into(), + "printf %s \"$1\" >\"$0\"; exec sleep 1".into(), + out.to_string_lossy().into_owned(), + ]; + let mut c = spawn_osd_key(&cmd, "mic-mute").unwrap(); + let pid = c.id() as libc::pid_t; + // SAFETY: getpgid takes no pointers. The child sleeps, and is not + // reaped before the wait below, so its group is there to read. + let pgid = unsafe { libc::getpgid(pid) }; + assert!(c.wait().unwrap().success()); + assert_eq!(pgid, pid); + assert_eq!(std::fs::read_to_string(&out).unwrap(), "mic-mute"); + assert!(spawn_osd_key(&[], "mic-mute").is_err()); + } + + #[test] + fn the_microphone_key_runs_nothing_with_the_volume_keys_off() { + let d = TestDir::new("deskflow-run", "osd-off"); + let out = d.join("key"); + let cmd = vec![ + "sh".to_string(), + "-c".into(), + "printf %s \"$1\" >\"$0\"".into(), + out.to_string_lossy().into_owned(), + ]; + let mut running = Vec::new(); + press_osd_key(false, &cmd, &mut running, "mic-mute"); + assert!(running.is_empty()); + press_osd_key(true, &cmd, &mut running, "mic-mute"); + assert_eq!(running.len(), 1); + assert!(running[0].wait().unwrap().success()); + assert_eq!(std::fs::read_to_string(&out).unwrap(), "mic-mute"); + } + + #[test] + fn at_most_four_osd_key_commands_run_at_once() { + let cmd = vec!["sh".to_string(), "-c".into(), "exec sleep 5".into()]; + let mut running = Vec::new(); + for _ in 0..6 { + press_osd_key(true, &cmd, &mut running, "mic-mute"); + } + assert_eq!(running.len(), OSD_KEYS_MAX); + for c in &mut running { + c.kill().unwrap(); + c.wait().unwrap(); + } + // The reaped ones make room again. + press_osd_key(true, &cmd, &mut running, "mic-mute"); + assert_eq!(running.len(), 1); + running[0].kill().unwrap(); + running[0].wait().unwrap(); + } + + fn write_cfg(path: &Path, listen: bool, port: u16, devices: &[(&str, &str)]) { + let devices: Vec<_> = devices.iter().map(|&(n, f)| (n, f, true)).collect(); + write_cfg_clip(path, listen, port, &devices); + } + + /// As write_cfg, with each device's Clipboard switch. + fn write_cfg_clip(path: &Path, listen: bool, port: u16, devices: &[(&str, &str, bool)]) { + let mut t = format!("[deskflow]\nlisten = {listen}\nport = {port}\n"); + for (i, (name, fp, clipboard)) in devices.iter().enumerate() { + t.push_str(&format!( + "\n[[deskflow.device]]\nname = \"{name}\"\nfingerprint = \"{fp}\"\noutput = \"DP-{i}\"\nside = \"right-of\"\n" + )); + if !clipboard { + t.push_str("clipboard = false\n"); + } + } + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write(path, t).unwrap(); + } + + struct Running { + port: u16, + wake: Arc, + done: JoinHandle>, + } + + /// The daemon on 127.0.0.1 and a free port, without Wayland, in a + /// thread of its own. + fn start(env: RunEnv) -> Running { + let wake = Arc::new(Wake::new().unwrap()); + let w = wake.clone(); + let (tx, rx) = mpsc::channel(); + let done = std::thread::spawn(move || { + let cfg = read_config(&env.generated)?; + let id = ident::load_or_create(&env.identity, &env.hostname)?; + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + listener.set_nonblocking(true).unwrap(); + // The port goes out once the command socket is bound: a test + // that sends a command right after start finds it. + let sock = cmd::bind(&env.socket).unwrap(); + tx.send(listener.local_addr().unwrap().port()).unwrap(); + let mut d = Daemon::new(env, cfg, &id, listener, sock, None); + // The monitor of the first attached device (write_cfg). + d.outputs = vec![OutputGeom { + name: "DP-0".into(), + description: String::new(), + x: 0, + y: 0, + w: 1920, + h: 1080, + }]; + d.serve(&w, None) + }); + let port = rx.recv().unwrap(); + Running { port, wake, done } + } + + fn cert(name: &str) -> rcgen::CertifiedKey { + rcgen::generate_simple_self_signed(vec![name.to_string()]).unwrap() + } + + fn connect(port: u16, cert: &rcgen::CertifiedKey) -> Client { + let tcp = TcpStream::connect(("127.0.0.1", port)).unwrap(); + tcp.set_read_timeout(Some(Duration::from_secs(5))).unwrap(); + let conn = rustls::ClientConnection::new(testclient::config(cert), testclient::server_name()).unwrap(); + rustls::StreamOwned::new(conn, tcp) + } + + fn read_payload(c: &mut Client) -> io::Result> { + let mut len = [0u8; 4]; + c.read_exact(&mut len)?; + let mut p = vec![0u8; u32::from_be_bytes(len) as usize]; + c.read_exact(&mut p)?; + Ok(p) + } + + fn read_msg(c: &mut Client) -> Msg { + proto::decode(&read_payload(c).unwrap()).unwrap() + } + + fn send(c: &mut Client, m: &Msg) { + c.write_all(&proto::frame(&proto::encode(m, 8))).unwrap(); + c.flush().unwrap(); + } + + /// Hello in, HelloBack out: the daemon's answer. + fn hello(c: &mut Client, name: &str) -> Msg { + let p = read_payload(c).unwrap(); + assert!(p.starts_with(b"Barrier"), "{p:?}"); + send( + c, + &Msg::HelloBack { + major: 1, + minor: 8, + name: name.as_bytes().to_vec(), + }, + ); + read_msg(c) + } + + fn line<'a>(s: &'a StateFile, name: &str, fp: &str) -> Option<&'a DevLine> { + s.devices.iter().find(|d| d.name == name && d.fingerprint == fp) + } + + /// The state file once it satisfies `ok`, within 5 s. + fn wait_state(path: &Path, ok: impl Fn(&StateFile) -> bool) -> StateFile { + let end = Instant::now() + Duration::from_secs(5); + loop { + let s = statefile::parse(&std::fs::read_to_string(path).unwrap_or_default()); + if ok(&s) || Instant::now() > end { + return s; + } + std::thread::sleep(Duration::from_millis(20)); + } + } + + fn fp_of(c: &rcgen::CertifiedKey) -> String { + ident::fingerprint(c.cert.der()) + } + + #[test] + fn pairing_over_loopback() { + let (d, s) = (TestDir::new("deskflow-run", "pair"), TestDir::sockets("dfp")); + let env = test_env(&d, &s); + let (state, gen_path, socket) = (env.state.clone(), env.generated.clone(), env.socket.clone()); + write_cfg(&gen_path, true, 24800, &[]); + let r = start(env); + let (laptop, other) = (cert("laptop"), cert("laptop")); + let (fp1, fp2) = (fp_of(&laptop), fp_of(&other)); + + // Unknown: EUNK, and pending in the state file. + let mut c = connect(r.port, &laptop); + assert_eq!(hello(&mut c, "laptop"), Msg::Eunk); + let st = wait_state(&state, |s| line(s, "laptop", &fp1).is_some()); + assert_eq!(line(&st, "laptop", &fp1).unwrap().state, DevState::Pending); + match &st.head { + Head::SelfInfo { fingerprint, listen } => { + assert!(fingerprint.starts_with("v2:sha256:")); + assert_eq!(listen, &format!("127.0.0.1:{}", r.port)); + } + h => panic!("{h:?}"), + } + + // Attached: QINF, then DINF gets CIAK, CROP and DSOP. + write_cfg(&gen_path, true, 24800, &[("laptop", &fp1)]); + cmd::send(&socket, &Cmd::Reload).unwrap(); + wait_state(&state, |s| { + line(s, "laptop", &fp1).is_some_and(|l| l.state == DevState::Offline) + }); + let mut c = connect(r.port, &laptop); + assert_eq!(hello(&mut c, "laptop"), Msg::Qinf); + let dinf = Msg::Dinf { + x: 0, + y: 0, + w: 1920, + h: 1080, + warp: 0, + mx: 0, + my: 0, + }; + send(&mut c, &dinf); + assert_eq!( + [read_msg(&mut c), read_msg(&mut c), read_msg(&mut c)], + [ + Msg::Ciak, + Msg::Crop, + Msg::Dsop(crate::deskflow::clipdata::options(true)) + ] + ); + let st = wait_state(&state, |s| { + line(s, "laptop", &fp1).is_some_and(|l| l.state == DevState::Connected) + }); + let l = line(&st, "laptop", &fp1).unwrap(); + assert_eq!((l.state, l.width, l.height), (DevState::Connected, 1920, 1080)); + + // The same device again while it is connected: EBSY. + let mut again = connect(r.port, &laptop); + assert_eq!(hello(&mut again, "laptop"), Msg::Ebsy); + + // Its name with another certificate: EUNK, pending, fp-changed. + let mut c2 = connect(r.port, &other); + assert_eq!(hello(&mut c2, "laptop"), Msg::Eunk); + let st = wait_state(&state, |s| line(s, "laptop", &fp2).is_some()); + let l = line(&st, "laptop", &fp2).unwrap(); + assert_eq!( + (l.state, l.flags.clone()), + (DevState::Pending, vec!["fp-changed".to_string()]) + ); + assert_eq!(line(&st, "laptop", &fp1).unwrap().state, DevState::Connected); + + // Rejected: shown as such and refused at once, never pending again. + cmd::send( + &socket, + &Cmd::Reject { + name: "laptop".into(), + fingerprint: fp2.clone(), + }, + ) + .unwrap(); + wait_state(&state, |s| { + line(s, "laptop", &fp2).is_some_and(|l| l.state == DevState::Rejected) + }); + let mut c3 = connect(r.port, &other); + assert_eq!(hello(&mut c3, "laptop"), Msg::Eunk); + let st = wait_state(&state, |_| false); + assert_eq!(line(&st, "laptop", &fp2).unwrap().state, DevState::Rejected); + assert_eq!(st.devices.len(), 2, "{st:?}"); + + // SIGTERM: CBYE to the client, exit 0, and the device is offline. + r.wake.send(libc::SIGTERM); + assert_eq!(r.done.join().unwrap(), Ok(())); + let goodbye = std::iter::from_fn(|| read_payload(&mut c).ok()) + .map(|p| proto::decode(&p).unwrap()) + .find(|m| *m != Msg::Calv); + assert_eq!(goodbye, Some(Msg::Cbye)); + let st = statefile::parse(&std::fs::read_to_string(&state).unwrap()); + assert_eq!(line(&st, "laptop", &fp1).unwrap().state, DevState::Offline); + } + + /// The next message that is not a keep-alive. + fn next_msg(c: &mut Client) -> Msg { + std::iter::repeat_with(|| read_msg(c)) + .find(|m| *m != Msg::Calv) + .unwrap() + } + + /// The messages other than keep-alives within `wait`. + fn quiet_for(c: &mut Client, wait: Duration) -> Vec { + c.sock.set_read_timeout(Some(wait)).unwrap(); + std::iter::from_fn(|| read_payload(c).ok()) + .map(|p| proto::decode(&p).unwrap()) + .filter(|m| *m != Msg::Calv) + .collect() + } + + fn dinf() -> Msg { + Msg::Dinf { + x: 0, + y: 0, + w: 1920, + h: 1080, + warp: 0, + mx: 0, + my: 0, + } + } + + #[test] + fn the_clipboard_switch_reaches_the_device_on_reload() { + let (d, s) = (TestDir::new("deskflow-run", "clipsw"), TestDir::sockets("dfc")); + let env = test_env(&d, &s); + let (state, gen_path, socket) = (env.state.clone(), env.generated.clone(), env.socket.clone()); + let laptop = cert("laptop"); + let fp = fp_of(&laptop); + write_cfg_clip(&gen_path, true, 24800, &[("laptop", &fp, false)]); + let r = start(env); + let mut c = connect(r.port, &laptop); + assert_eq!(hello(&mut c, "laptop"), Msg::Qinf); + send(&mut c, &dinf()); + assert_eq!( + [read_msg(&mut c), read_msg(&mut c), read_msg(&mut c)], + [ + Msg::Ciak, + Msg::Crop, + Msg::Dsop(crate::deskflow::clipdata::options(false)) + ] + ); + wait_state(&state, |s| { + line(s, "laptop", &fp).is_some_and(|l| l.state == DevState::Connected) + }); + for on in [true, false] { + write_cfg_clip(&gen_path, true, 24800, &[("laptop", &fp, on)]); + cmd::send(&socket, &Cmd::Reload).unwrap(); + assert_eq!(next_msg(&mut c), Msg::Dsop(crate::deskflow::clipdata::options(on))); + } + r.wake.send(libc::SIGTERM); + assert_eq!(r.done.join().unwrap(), Ok(())); + } + + #[test] + fn a_grab_from_one_device_reaches_the_others_that_share() { + let (d, s) = (TestDir::new("deskflow-run", "clipgrab"), TestDir::sockets("dfg")); + let env = test_env(&d, &s); + let gen_path = env.generated.clone(); + let (a, b, off) = (cert("a"), cert("b"), cert("off")); + let (fa, fb, foff) = (fp_of(&a), fp_of(&b), fp_of(&off)); + write_cfg_clip( + &gen_path, + true, + 24800, + &[("a", &fa, true), ("b", &fb, true), ("off", &foff, false)], + ); + let r = start(env); + let mut ca = connect(r.port, &a); + assert_eq!(hello(&mut ca, "a"), Msg::Qinf); + let mut cb = connect(r.port, &b); + assert_eq!(hello(&mut cb, "b"), Msg::Qinf); + let mut coff = connect(r.port, &off); + assert_eq!(hello(&mut coff, "off"), Msg::Qinf); + send(&mut ca, &Msg::Cclp { id: 0, seq: 1 }); + assert!(matches!(next_msg(&mut cb), Msg::Cclp { id: 0, .. })); + // The device with the switch off hears nothing of it, and its own + // grab reaches nobody. + send(&mut coff, &Msg::Cclp { id: 0, seq: 1 }); + assert_eq!(quiet_for(&mut coff, Duration::from_millis(300)), []); + assert_eq!(quiet_for(&mut ca, Duration::from_millis(300)), []); + r.wake.send(libc::SIGTERM); + assert_eq!(r.done.join().unwrap(), Ok(())); + } + + #[test] + fn a_reload_with_another_port_listens_there() { + let (d, s) = (TestDir::new("deskflow-run", "port2"), TestDir::sockets("dfr")); + let env = test_env(&d, &s); + let (state, gen_path, socket) = (env.state.clone(), env.generated.clone(), env.socket.clone()); + write_cfg(&gen_path, true, 24800, &[]); + let r = start(env); + let port = TcpListener::bind("0.0.0.0:0").unwrap().local_addr().unwrap().port(); + write_cfg(&gen_path, true, port, &[]); + cmd::send(&socket, &Cmd::Reload).unwrap(); + let want = format!("0.0.0.0:{port}"); + let st = wait_state( + &state, + |s| matches!(&s.head, Head::SelfInfo { listen, .. } if *listen == want), + ); + assert!( + matches!(&st.head, Head::SelfInfo { listen, .. } if *listen == want), + "{st:?}" + ); + let mut c = connect(port, &cert("moved")); + assert!(read_payload(&mut c).unwrap().starts_with(b"Barrier")); + r.wake.send(libc::SIGTERM); + assert_eq!(r.done.join().unwrap(), Ok(())); + } + + #[test] + fn an_oversized_frame_and_a_fifth_handshake_are_dropped() { + let (d, s) = (TestDir::new("deskflow-run", "limits"), TestDir::sockets("dfl")); + let env = test_env(&d, &s); + write_cfg(&env.generated, true, 24800, &[]); + let r = start(env); + let mut c = connect(r.port, &cert("big")); + read_payload(&mut c).unwrap(); + c.write_all(&((proto::MAX_MSG + 1) as u32).to_be_bytes()).unwrap(); + c.flush().unwrap(); + let mut b = [0u8; 16]; + assert!(matches!(c.read(&mut b), Ok(0) | Err(_)), "the daemon closes it"); + + let idle: Vec = (0..MAX_HANDSHAKES) + .map(|_| TcpStream::connect(("127.0.0.1", r.port)).unwrap()) + .collect(); + let mut fifth = TcpStream::connect(("127.0.0.1", r.port)).unwrap(); + fifth.set_read_timeout(Some(Duration::from_secs(5))).unwrap(); + let t = Instant::now(); + assert_eq!(fifth.read(&mut b).unwrap_or(0), 0); + assert!(t.elapsed() < Duration::from_secs(4), "closed at once"); + drop(idle); + r.wake.send(libc::SIGTERM); + assert_eq!(r.done.join().unwrap(), Ok(())); + } + + #[test] + fn switching_off_ends_the_daemon_and_frees_the_port() { + let (d, s) = (TestDir::new("deskflow-run", "off"), TestDir::sockets("dfo")); + let env = test_env(&d, &s); + let (gen_path, socket) = (env.generated.clone(), env.socket.clone()); + write_cfg(&gen_path, true, 24800, &[]); + let r = start(env); + write_cfg(&gen_path, false, 24800, &[]); + cmd::send(&socket, &Cmd::Reload).unwrap(); + assert_eq!(r.done.join().unwrap(), Ok(())); + TcpListener::bind(("127.0.0.1", r.port)).unwrap(); + } + + #[test] + fn a_second_daemon_stops_before_touching_anything() { + let (d, s) = (TestDir::new("deskflow-run", "twice"), TestDir::sockets("dft")); + let env = test_env(&d, &s); + let _held = lock(&env.state).unwrap(); + write_cfg(&env.generated, true, 24800, &[]); + let state = env.state.clone(); + assert_eq!(run(env), Err("another deskflow daemon runs".to_string())); + assert!(!state.exists()); + } + + #[test] + fn no_generated_file_means_off() { + let (d, s) = (TestDir::new("deskflow-run", "absent"), TestDir::sockets("dfa")); + let env = test_env(&d, &s); + let state = env.state.clone(); + assert_eq!(run(env), Ok(())); + assert!(!state.exists()); + } + + fn error_head(state: &Path) -> String { + match statefile::parse(&std::fs::read_to_string(state).unwrap()).head { + Head::Error(e) => e, + h => panic!("{h:?}"), + } + } + + #[test] + fn a_bad_config_is_an_error_head() { + let (d, s) = (TestDir::new("deskflow-run", "bad"), TestDir::sockets("dfb")); + let env = test_env(&d, &s); + std::fs::create_dir_all(env.generated.parent().unwrap()).unwrap(); + std::fs::write(&env.generated, "[deskflow]\nlisten = 7\n").unwrap(); + let state = env.state.clone(); + let e = run(env).unwrap_err(); + assert!(e.starts_with("generated/deskflow:"), "{e}"); + assert_eq!(error_head(&state), e); + + let (d, s) = (TestDir::new("deskflow-run", "invalid"), TestDir::sockets("dfv")); + let env2 = test_env(&d, &s); + write_cfg(&env2.generated, true, 0, &[]); + let state = env2.state.clone(); + let e = run(env2).unwrap_err(); + assert!(e.contains("port"), "{e}"); + assert_eq!(error_head(&state), e); + } + + #[test] + fn a_damaged_identity_is_kept_and_reported() { + let (d, s) = (TestDir::new("deskflow-run", "ident"), TestDir::sockets("dfi")); + let env = test_env(&d, &s); + write_cfg(&env.generated, true, 24800, &[]); + std::fs::create_dir_all(env.identity.parent().unwrap()).unwrap(); + std::fs::write(&env.identity, "junk\n").unwrap(); + let (state, identity) = (env.state.clone(), env.identity.clone()); + let e = run(env).unwrap_err(); + assert!(e.starts_with("identity: "), "{e}"); + assert_eq!(error_head(&state), e); + assert_eq!(std::fs::read_to_string(identity).unwrap(), "junk\n"); + } + + #[test] + fn a_port_in_use_is_an_error_head() { + let (d, s) = (TestDir::new("deskflow-run", "port"), TestDir::sockets("dfu")); + let env = test_env(&d, &s); + let taken = TcpListener::bind("0.0.0.0:0").unwrap(); + let port = taken.local_addr().unwrap().port(); + write_cfg(&env.generated, true, port, &[]); + let state = env.state.clone(); + assert_eq!(run(env), Err(format!("port {port} in use"))); + assert_eq!(error_head(&state), format!("port {port} in use")); + } +} diff --git a/src/thinfloe-menu/src/deskflow/session.rs b/src/thinfloe-menu/src/deskflow/session.rs new file mode 100644 index 0000000..099e715 --- /dev/null +++ b/src/thinfloe-menu/src/deskflow/session.rs @@ -0,0 +1,748 @@ +//! One connection's protocol state machine (spec, Protocol subset and +//! Connection flow). Sans-IO: the daemon feeds it payloads cut by +//! [`proto::Framer`], the current time and the pairing verdict, and writes +//! the [`Out::Send`] bytes to the TLS stream. It never reads a clock. + +use std::time::{Duration, Instant}; + +use super::clipdata::{self, Asm, Assembler}; +use super::pair::Verdict; +use super::proto::{self, Msg}; + +/// The version the server offers. +const MAJOR: u16 = 1; +const MINOR_MAX: u16 = 8; +const MINOR_MIN: u16 = 6; +/// The longest client name kept, in bytes. +pub const NAME_MAX: usize = 64; +/// The client must answer the Hello within this time of `new`. +const HELLO_DEADLINE: Duration = Duration::from_secs(10); +const CALV_EVERY: Duration = Duration::from_secs(3); +/// A trusted client that sent nothing for this long is gone. +const DEAD_AFTER: Duration = Duration::from_secs(9); + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Out { + /// Framed bytes for the TLS stream. + Send(Vec), + /// The client's name (capped, control characters replaced by `?`); the + /// caller answers with [`Session::set_verdict`]. + Named { name: String }, + /// The size of the client's screen, from its DINF. + Screen { w: i16, h: i16 }, + /// A finished inbound text clipboard (id 0), only while sharing is on. + Clipboard { text: Vec }, + /// The client took the clipboard (CCLP for id 0), only while sharing is on. + Grabbed, + /// End the connection after the bytes before this were written. + Close(&'static str), +} + +#[derive(Clone, Copy, PartialEq, Eq)] +enum State { + /// The Hello is out; no HelloBack yet. + AwaitHello, + /// HelloBack accepted, the caller owes a verdict. + AwaitVerdict, + /// Trusted: QINF sent, DINF not yet seen. + Trusted, + /// The first DINF has been answered. + Active, + Closed, +} + +pub struct Session { + state: State, + minor: u16, + created: Instant, + last_rx: Instant, + last_calv: Instant, + seq: u32, + clipboard: bool, + clip_seq: u32, + asm: Assembler, +} + +fn send(m: &Msg, minor: u16) -> Out { + Out::Send(proto::frame(&proto::encode(m, minor))) +} + +/// Unicode format characters (category Cf) and the line and paragraph +/// separators: invisible, and some reorder the text around them. +fn is_format_char(c: char) -> bool { + matches!(c, + '\u{ad}' | '\u{600}'..='\u{605}' | '\u{61c}' | '\u{6dd}' | '\u{70f}' | '\u{890}'..='\u{891}' + | '\u{8e2}' | '\u{180e}' | '\u{200b}'..='\u{200f}' | '\u{2028}'..='\u{202e}' + | '\u{2060}'..='\u{2064}' | '\u{2066}'..='\u{206f}' | '\u{feff}' | '\u{fff9}'..='\u{fffb}' + | '\u{110bd}' | '\u{110cd}' | '\u{13430}'..='\u{1343f}' | '\u{1bca0}'..='\u{1bca3}' + | '\u{1d173}'..='\u{1d17a}' | '\u{e0001}' | '\u{e0020}'..='\u{e007f}') +} + +/// The client's name as shown: at most 64 raw bytes, lossily decoded, every +/// control or format character replaced by `?`, cut again at 64 bytes on a +/// character boundary (the replacement character takes three bytes). +fn clean_name(raw: &[u8]) -> String { + let raw = &raw[..raw.len().min(NAME_MAX)]; + let mut s: String = String::from_utf8_lossy(raw) + .chars() + .map(|c| if c.is_control() || is_format_char(c) { '?' } else { c }) + .collect(); + let mut end = s.len().min(NAME_MAX); + while !s.is_char_boundary(end) { + end -= 1; + } + s.truncate(end); + s +} + +impl Session { + pub fn new(now: Instant) -> (Session, Vec) { + let s = Session { + state: State::AwaitHello, + minor: MINOR_MAX, + created: now, + last_rx: now, + last_calv: now, + seq: 0, + clipboard: true, + clip_seq: 0, + asm: Assembler::default(), + }; + let hello = send( + &Msg::Hello { + major: MAJOR, + minor: MINOR_MAX, + }, + MINOR_MAX, + ); + (s, vec![hello]) + } + + /// The negotiated minor version (the server's until the HelloBack). + pub fn minor(&self) -> u16 { + self.minor + } + + fn close(&mut self, why: &'static str) -> Vec { + self.state = State::Closed; + vec![Out::Close(why)] + } + + pub fn on_payload(&mut self, p: &[u8], now: Instant) -> Vec { + if self.state == State::Closed { + return Vec::new(); + } + self.last_rx = now; + match self.state { + State::AwaitHello => self.hello_back(p), + State::AwaitVerdict | State::Closed => Vec::new(), + State::Trusted | State::Active => self.message(p), + } + } + + fn hello_back(&mut self, p: &[u8]) -> Vec { + let Ok(Msg::HelloBack { major, minor, name }) = proto::decode_hello_back(p) else { + return self.close("bad hello"); + }; + if major != MAJOR || !(MINOR_MIN..=MINOR_MAX).contains(&minor) { + let mut out = vec![send( + &Msg::Eicv { + major: MAJOR, + minor: MINOR_MAX, + }, + MINOR_MAX, + )]; + out.extend(self.close("incompatible version")); + return out; + } + let name = clean_name(&name); + if name.is_empty() { + return self.close("empty client name"); + } + self.minor = minor; + self.state = State::AwaitVerdict; + vec![Out::Named { name }] + } + + fn message(&mut self, p: &[u8]) -> Vec { + let Ok(m) = proto::decode(p) else { + return self.close("bad message"); + }; + match m { + // The client echoes the server's keep-alive; answering its own + // would start an endless exchange. It only shows the client lives. + Msg::Calv => Vec::new(), + Msg::Dinf { w, h, .. } => { + let mut out = vec![send(&Msg::Ciak, self.minor)]; + if self.state == State::Trusted { + self.state = State::Active; + out.push(send(&Msg::Crop, self.minor)); + out.push(send(&Msg::Dsop(clipdata::options(self.clipboard)), self.minor)); + } + out.push(Out::Screen { w, h }); + out + } + Msg::Cclp { id: 0, .. } if self.clipboard => vec![Out::Grabbed], + Msg::Dclp { id, seq, mark, data } => match self.asm.push(id, seq, mark, &data) { + Asm::Error => self.close("bad clipboard"), + Asm::Finished(m) if id == 0 && self.clipboard => clipdata::unmarshal_text(&m) + .map(|text| vec![Out::Clipboard { text }]) + .unwrap_or_default(), + _ => Vec::new(), + }, + _ => Vec::new(), + } + } + + /// Time passes: the Hello deadline, the keep-alive and the dead-client + /// check. + pub fn tick(&mut self, now: Instant) -> Vec { + match self.state { + State::AwaitHello => { + if now.saturating_duration_since(self.created) >= HELLO_DEADLINE { + return self.close("no hello"); + } + } + State::Trusted | State::Active => { + if now.saturating_duration_since(self.last_rx) >= DEAD_AFTER { + return self.close("keep-alive lost"); + } + if now.saturating_duration_since(self.last_calv) >= CALV_EVERY { + self.last_calv = now; + return vec![send(&Msg::Calv, self.minor)]; + } + } + State::AwaitVerdict => { + if now.saturating_duration_since(self.created) >= HELLO_DEADLINE { + return self.close("no verdict"); + } + } + State::Closed => {} + } + Vec::new() + } + + /// The pairing decision for the name given by [`Out::Named`]. + pub fn set_verdict(&mut self, v: Verdict) -> Vec { + if self.state != State::AwaitVerdict { + return Vec::new(); + } + match v { + Verdict::Trusted(_) => { + self.state = State::Trusted; + // The keep-alive runs from the HelloBack. + self.last_calv = self.last_rx; + vec![send(&Msg::Qinf, self.minor)] + } + Verdict::Pending | Verdict::FingerprintChanged => { + let why = if v == Verdict::Pending { + "not paired" + } else { + "fingerprint changed" + }; + let mut out = vec![send(&Msg::Eunk, self.minor)]; + out.extend(self.close(why)); + out + } + } + } + + fn live(&self) -> bool { + matches!(self.state, State::Trusted | State::Active) + } + + /// Turn clipboard sharing on or off; an active session tells the client. + pub fn set_clipboard(&mut self, on: bool) -> Vec { + if self.clipboard == on { + return Vec::new(); + } + self.clipboard = on; + if self.state == State::Active { + vec![send(&Msg::Dsop(clipdata::options(on)), self.minor)] + } else { + Vec::new() + } + } + + /// CCLP only: an inactive device learns that ThinFloe owns the clipboard. + pub fn grab(&mut self) -> Vec { + if !self.live() || !self.clipboard { + return Vec::new(); + } + self.clip_seq = self.clip_seq.wrapping_add(1); + vec![send( + &Msg::Cclp { + id: 0, + seq: self.clip_seq, + }, + self.minor, + )] + } + + /// CCLP and the DCLP transfer of `text` (clipboard id 0). + pub fn clipboard(&mut self, text: &[u8]) -> Vec { + let m = clipdata::marshal_text(text); + if !self.live() || !self.clipboard || m.len() > clipdata::CLIP_MAX { + return Vec::new(); + } + self.clip_seq = self.clip_seq.wrapping_add(1); + let seq = self.clip_seq; + let mut out = vec![send(&Msg::Cclp { id: 0, seq }, self.minor)]; + out.extend(clipdata::chunks(0, seq, &m).iter().map(|c| send(c, self.minor))); + out + } + + /// CINN: the pointer enters the client's screen at (x, y). + pub fn enter(&mut self, x: i16, y: i16, mods: u16) -> Vec { + if !self.live() { + return Vec::new(); + } + self.seq = self.seq.wrapping_add(1); + let seq = self.seq; + vec![send(&Msg::Cinn { x, y, seq, mods }, self.minor)] + } + + /// COUT: the pointer leaves the client's screen. + pub fn leave(&mut self) -> Vec { + if !self.live() { + return Vec::new(); + } + vec![send(&Msg::Cout, self.minor)] + } + + /// Any other message for the client, in the form its minor needs. + pub fn send(&mut self, m: Msg) -> Vec { + if !self.live() { + return Vec::new(); + } + vec![send(&m, self.minor)] + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn s(n: u64) -> Duration { + Duration::from_secs(n) + } + + fn hello_back(minor: u16, name: &[u8]) -> Vec { + proto::encode( + &Msg::HelloBack { + major: 1, + minor, + name: name.to_vec(), + }, + 8, + ) + } + + fn dinf(w: i16, h: i16) -> Vec { + proto::encode( + &Msg::Dinf { + x: 0, + y: 0, + w, + h, + warp: 0, + mx: 0, + my: 0, + }, + 8, + ) + } + + /// The messages in the Send outputs, decoded. + fn sent(out: &[Out]) -> Vec { + out.iter() + .filter_map(|o| match o { + Out::Send(b) => { + assert_eq!(u32::from_be_bytes(b[..4].try_into().unwrap()) as usize, b.len() - 4); + Some(proto::decode(&b[4..]).unwrap()) + } + _ => None, + }) + .collect() + } + + fn closes(out: &[Out]) -> Option<&'static str> { + out.iter().find_map(|o| match o { + Out::Close(w) => Some(*w), + _ => None, + }) + } + + /// A session past HelloBack with the verdict Trusted. + fn trusted(minor: u16, t0: Instant) -> Session { + let (mut se, _) = Session::new(t0); + se.on_payload(&hello_back(minor, b"laptop"), t0); + se.set_verdict(Verdict::Trusted(0)); + se + } + + #[test] + fn hello_first() { + let (se, out) = Session::new(Instant::now()); + assert_eq!(out.len(), 1); + assert_eq!( + out, + [Out::Send(proto::frame(&proto::encode( + &Msg::Hello { major: 1, minor: 8 }, + 8 + )))] + ); + assert_eq!(se.minor(), 8); + } + + #[test] + fn old_minor_gets_eicv() { + let t = Instant::now(); + let (mut se, _) = Session::new(t); + let out = se.on_payload(&hello_back(5, b"laptop"), t); + assert_eq!(sent(&out), [Msg::Eicv { major: 1, minor: 8 }]); + assert_eq!(closes(&out), Some("incompatible version")); + // A wrong major as well, and a minor above 8. + for (major, minor) in [(2u16, 8u16), (1, 9)] { + let (mut se, _) = Session::new(t); + let p = proto::encode( + &Msg::HelloBack { + major, + minor, + name: b"x".to_vec(), + }, + 8, + ); + assert!(closes(&se.on_payload(&p, t)).is_some()); + } + } + + #[test] + fn garbage_hello_back_closes() { + let t = Instant::now(); + let (mut se, _) = Session::new(t); + assert_eq!(closes(&se.on_payload(b"Bar", t)), Some("bad hello")); + assert!(se.on_payload(&hello_back(8, b"x"), t).is_empty()); + } + + #[test] + fn hello_back_negotiates_down() { + let t = Instant::now(); + let (mut se, _) = Session::new(t); + let out = se.on_payload(&hello_back(6, b"laptop"), t); + assert_eq!(out, [Out::Named { name: "laptop".into() }]); + assert_eq!(se.minor(), 6); + } + + #[test] + fn hello_back_name_capped() { + let t = Instant::now(); + let (mut se, _) = Session::new(t); + let out = se.on_payload(&hello_back(8, &vec![b'a'; 10_000]), t); + match &out[..] { + [Out::Named { name }] => assert_eq!(name.len(), 64), + o => panic!("{o:?}"), + } + } + + #[test] + fn name_is_made_safe() { + assert_eq!(clean_name(b"a\tb\r\nc\x7fd\x1b[0m"), "a?b??c?d?[0m"); + assert_eq!(clean_name("a\u{85}b".as_bytes()), "a?b"); + for c in [ + '\u{202e}', '\u{200b}', '\u{200f}', '\u{2066}', '\u{2069}', '\u{feff}', '\u{2028}', '\u{2029}', + ] { + assert_eq!(clean_name(format!("a{c}b").as_bytes()), "a?b", "{c:?}"); + } + // A cut in the middle of a character, and invalid bytes grown to + // three-byte replacement characters, stay within 64 bytes. + let mut raw = vec![b'a'; 63]; + raw.extend("\u{e9}".as_bytes()); + let n = clean_name(&raw); + assert!(n.len() <= 64 && n.starts_with(&"a".repeat(63))); + let n = clean_name(&[0xff; 100]); + assert!(n.len() <= 64 && n.chars().all(|c| c == '\u{fffd}')); + assert_eq!(clean_name("l\u{e4}ptop".as_bytes()), "l\u{e4}ptop"); + } + + #[test] + fn empty_name_closes_without_naming() { + let t = Instant::now(); + let (mut se, _) = Session::new(t); + let out = se.on_payload(&hello_back(8, b""), t); + assert_eq!(out, [Out::Close("empty client name")]); + } + + #[test] + fn trusted_gets_qinf_then_ciak_after_dinf() { + let t = Instant::now(); + let (mut se, _) = Session::new(t); + se.on_payload(&hello_back(8, b"laptop"), t); + let out = se.set_verdict(Verdict::Trusted(0)); + assert_eq!(sent(&out), [Msg::Qinf]); + let out = se.on_payload(&dinf(1920, 1080), t); + assert_eq!(sent(&out), [Msg::Ciak, Msg::Crop, Msg::Dsop(clipdata::options(true))]); + assert_eq!(out.last(), Some(&Out::Screen { w: 1920, h: 1080 })); + let out = se.on_payload(&dinf(1280, 720), t); + assert_eq!(sent(&out), [Msg::Ciak]); + assert_eq!(out.last(), Some(&Out::Screen { w: 1280, h: 720 })); + } + + #[test] + fn pending_gets_eunk_and_close() { + for (v, why) in [ + (Verdict::Pending, "not paired"), + (Verdict::FingerprintChanged, "fingerprint changed"), + ] { + let t = Instant::now(); + let (mut se, _) = Session::new(t); + se.on_payload(&hello_back(8, b"laptop"), t); + let out = se.set_verdict(v); + assert_eq!(sent(&out), [Msg::Eunk]); + assert_eq!(closes(&out), Some(why)); + assert!(se.on_payload(&dinf(1, 1), t).is_empty()); + assert!(se.send(Msg::Calv).is_empty()); + } + } + + #[test] + fn nothing_goes_out_before_a_verdict() { + let t = Instant::now(); + let (mut se, _) = Session::new(t); + se.on_payload(&hello_back(8, b"laptop"), t); + assert!(se.on_payload(&dinf(1, 1), t).is_empty()); + assert!(se.enter(1, 1, 0).is_empty()); + assert!(se.tick(t + s(8)).is_empty()); + } + + #[test] + fn hello_deadline_10s() { + let t = Instant::now(); + let (mut se, _) = Session::new(t); + assert!(se.tick(t + s(9)).is_empty()); + assert_eq!(se.tick(t + s(10)), [Out::Close("no hello")]); + assert!(se.tick(t + s(11)).is_empty()); + assert!(se.on_payload(&hello_back(8, b"x"), t + s(11)).is_empty()); + } + + #[test] + fn verdict_deadline_10s() { + let t = Instant::now(); + let (mut se, _) = Session::new(t); + se.on_payload(&hello_back(8, b"laptop"), t + s(1)); + assert!(se.tick(t + s(9)).is_empty()); + assert_eq!(se.tick(t + s(10)), [Out::Close("no verdict")]); + assert!(se.set_verdict(Verdict::Trusted(0)).is_empty()); + } + + #[test] + fn keepalive_every_3s_dead_after_9s() { + let t = Instant::now(); + let mut se = trusted(8, t); + assert!(se.tick(t + s(2)).is_empty()); + assert_eq!(sent(&se.tick(t + s(3))), [Msg::Calv]); + assert!(se.tick(t + s(5)).is_empty()); + assert_eq!(sent(&se.tick(t + s(6))), [Msg::Calv]); + let out = se.tick(t + s(9)); + assert_eq!(closes(&out), Some("keep-alive lost")); + assert!(se.tick(t + s(12)).is_empty()); + } + + #[test] + fn any_message_postpones_the_dead_check() { + let t = Instant::now(); + let mut se = trusted(8, t); + se.on_payload(&proto::encode(&Msg::Cnop, 8), t + s(8)); + assert!(closes(&se.tick(t + s(9))).is_none()); + assert!(closes(&se.tick(t + s(16))).is_none()); + assert!(closes(&se.tick(t + s(17))).is_some()); + } + + #[test] + fn a_client_calv_is_not_echoed() { + // The stock client echoes every CALV it gets; an answer from the + // server would start an endless exchange. + let t = Instant::now(); + let mut se = trusted(8, t); + assert!(se.on_payload(&proto::encode(&Msg::Calv, 8), t + s(1)).is_empty()); + let mut active = trusted(8, t); + active.on_payload( + &proto::encode( + &Msg::Dinf { + x: 0, + y: 0, + w: 1920, + h: 1080, + warp: 0, + mx: 0, + my: 0, + }, + 8, + ), + t, + ); + assert!(active.on_payload(&proto::encode(&Msg::Calv, 8), t + s(1)).is_empty()); + } + + #[test] + fn a_client_calv_postpones_the_dead_check() { + let t = Instant::now(); + let mut se = trusted(8, t); + se.on_payload(&proto::encode(&Msg::Calv, 8), t + s(8)); + assert!(closes(&se.tick(t + s(16))).is_none()); + assert!(closes(&se.tick(t + s(17))).is_some()); + } + + #[test] + fn undecodable_message_closes() { + let t = Instant::now(); + let mut se = trusted(8, t); + assert_eq!(closes(&se.on_payload(b"DINF", t)), Some("bad message")); + } + + #[test] + fn enter_leave_and_seq() { + let t = Instant::now(); + let mut se = trusted(8, t); + let a = sent(&se.enter(10, 20, 3)); + let b = sent(&se.enter(11, 21, 0)); + assert_eq!( + a, + [Msg::Cinn { + x: 10, + y: 20, + seq: 1, + mods: 3 + }] + ); + assert!(matches!(b[0], Msg::Cinn { seq: 2, .. })); + assert_eq!(sent(&se.leave()), [Msg::Cout]); + } + + #[test] + fn key_form_follows_minor() { + let t = Instant::now(); + let key = Msg::KeyDown { + id: 97, + mods: 0, + button: 38, + }; + let code = |se: &mut Session| match &se.send(key.clone())[0] { + Out::Send(b) => b[4..8].to_vec(), + o => panic!("{o:?}"), + }; + assert_eq!(code(&mut trusted(7, t)), b"DKDN"); + assert_eq!(code(&mut trusted(8, t)), b"DKDL"); + } + + /// An Active session with the setup output drained. + fn active(t: Instant) -> Session { + let mut se = trusted(8, t); + se.on_payload(&dinf(1920, 1080), t); + se + } + + fn dclp(id: u8, mark: u8, data: &[u8]) -> Vec { + proto::encode( + &Msg::Dclp { + id, + seq: 1, + mark, + data: data.to_vec(), + }, + 8, + ) + } + + fn feed_transfer(se: &mut Session, id: u8, text: &[u8], t: Instant) -> Vec { + let m = clipdata::marshal_text(text); + let mut out = Vec::new(); + for c in clipdata::chunks(id, 1, &m) { + out.extend(se.on_payload(&proto::encode(&c, 8), t)); + } + out + } + + #[test] + fn dsop_carries_clipboard_option() { + let t = Instant::now(); + let mut se = trusted(8, t); + let out = se.on_payload(&dinf(10, 10), t); + assert!(sent(&out).contains(&Msg::Dsop(vec![clipdata::CLPS, 1, clipdata::CLSZ, 1024]))); + } + + #[test] + fn set_clipboard_resends_dsop_when_active() { + let t = Instant::now(); + let mut se = active(t); + assert_eq!(sent(&se.set_clipboard(false)), [Msg::Dsop(vec![clipdata::CLPS, 0])]); + assert!(se.set_clipboard(false).is_empty()); + assert_eq!(sent(&se.set_clipboard(true)), [Msg::Dsop(clipdata::options(true))]); + // Before the first DINF only the flag is stored. + let mut se = trusted(8, t); + assert!(se.set_clipboard(false).is_empty()); + let out = se.on_payload(&dinf(10, 10), t); + assert!(sent(&out).contains(&Msg::Dsop(vec![clipdata::CLPS, 0]))); + } + + #[test] + fn inbound_transfer_yields_clipboard() { + let t = Instant::now(); + let mut se = active(t); + let out = feed_transfer(&mut se, 0, b"h\xc3\xa4llo", t); + assert_eq!( + out, + [Out::Clipboard { + text: b"h\xc3\xa4llo".to_vec() + }] + ); + let out = se.on_payload(&proto::encode(&Msg::Cclp { id: 0, seq: 2 }, 8), t); + assert_eq!(out, [Out::Grabbed]); + // The selection (id 1) is assembled and dropped, never an error. + assert!(feed_transfer(&mut se, 1, b"sel", t).is_empty()); + let out = se.on_payload(&proto::encode(&Msg::Cclp { id: 1, seq: 3 }, 8), t); + assert!(out.is_empty()); + assert_eq!(feed_transfer(&mut se, 0, b"x", t).len(), 1); + } + + #[test] + fn inbound_ignored_when_off() { + let t = Instant::now(); + let mut se = active(t); + se.set_clipboard(false); + assert!(feed_transfer(&mut se, 0, b"x", t).is_empty()); + let out = se.on_payload(&proto::encode(&Msg::Cclp { id: 0, seq: 2 }, 8), t); + assert!(out.is_empty()); + } + + #[test] + fn bad_chunk_closes() { + let t = Instant::now(); + let mut se = active(t); + let out = se.on_payload(&dclp(0, 2, b"data without start"), t); + assert_eq!(closes(&out), Some("bad clipboard")); + } + + #[test] + fn clipboard_out_sends_cclp_then_dclp() { + let t = Instant::now(); + let mut se = active(t); + let msgs = sent(&se.clipboard(b"hi")); + let m = clipdata::marshal_text(b"hi"); + assert_eq!(msgs[0], Msg::Cclp { id: 0, seq: 1 }); + assert_eq!(msgs[1..], clipdata::chunks(0, 1, &m)[..]); + assert_eq!(sent(&se.grab()), [Msg::Cclp { id: 0, seq: 2 }]); + // Not live: nothing. + let (mut se, _) = Session::new(t); + assert!(se.clipboard(b"hi").is_empty() && se.grab().is_empty()); + } + + #[test] + fn clipboard_over_cap_sends_nothing() { + let t = Instant::now(); + let mut se = active(t); + assert!(se.clipboard(&vec![b'a'; clipdata::CLIP_MAX]).is_empty()); + se.set_clipboard(false); + assert!(se.clipboard(b"hi").is_empty()); + } +} diff --git a/src/thinfloe-menu/src/deskflow/statefile.rs b/src/thinfloe-menu/src/deskflow/statefile.rs new file mode 100644 index 0000000..e2e1200 --- /dev/null +++ b/src/thinfloe-menu/src/deskflow/statefile.rs @@ -0,0 +1,341 @@ +//! The Deskflow daemon's state file, read by the menu (spec, Processes): +//! the first line is the head, then one line per (name, fingerprint) pair, +//! tab separated. The parser ignores unknown trailing fields and lines it +//! cannot read, so a newer daemon never breaks an older menu. + +use std::ffi::OsString; +use std::io; +use std::path::{Path, PathBuf}; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum DevState { + Pending, + Rejected, + Connected, + /// The pointer is on this device. + Active, + Offline, +} + +impl DevState { + fn as_str(self) -> &'static str { + match self { + DevState::Pending => "pending", + DevState::Rejected => "rejected", + DevState::Connected => "connected", + DevState::Active => "active", + DevState::Offline => "offline", + } + } + + fn parse(s: &str) -> Option { + Some(match s { + "pending" => DevState::Pending, + "rejected" => DevState::Rejected, + "connected" => DevState::Connected, + "active" => DevState::Active, + "offline" => DevState::Offline, + _ => return None, + }) + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct DevLine { + pub name: String, + pub fingerprint: String, + pub state: DevState, + /// Epoch seconds of the last state change. + pub since: i64, + /// From the device's last DINF; 0 when unknown. + pub width: u32, + pub height: u32, + /// So far only "fp-changed". + pub flags: Vec, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Head { + SelfInfo { fingerprint: String, listen: String }, + Error(String), +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct StateFile { + pub head: Head, + pub devices: Vec, +} + +/// Where the daemon writes: `TF_DESKFLOW_STATE`, else +/// `$XDG_RUNTIME_DIR/thinfloe-deskflow.state`; an empty variable is unset. +pub fn path() -> Option { + path_from( + std::env::var_os("TF_DESKFLOW_STATE"), + std::env::var_os("XDG_RUNTIME_DIR"), + ) +} + +fn path_from(file: Option, runtime_dir: Option) -> Option { + if let Some(p) = file.filter(|p| !p.is_empty()) { + return Some(PathBuf::from(p)); + } + let dir = runtime_dir.filter(|d| !d.is_empty())?; + Some(PathBuf::from(dir).join("thinfloe-deskflow.state")) +} + +/// Escape `s` so it holds no TAB, newline or other control byte: a +/// backslash, TAB and LF become `\\`, `\t`, `\n`, any other byte below 0x20 and +/// 0x7f become `\xNN`. Works on the bytes, so it does not rely on any +/// earlier sanitising. +pub(crate) fn escape(s: &str) -> String { + let mut out = String::with_capacity(s.len()); + // Only ASCII bytes are rewritten, and a byte of a multi-byte character + // is never ASCII, so walking the chars equals walking the bytes. + for c in s.chars() { + match c { + '\\' => out.push_str("\\\\"), + '\t' => out.push_str("\\t"), + '\n' => out.push_str("\\n"), + '\0'..='\x1f' | '\x7f' => out.push_str(&format!("\\x{:02x}", c as u8)), + _ => out.push(c), + } + } + out +} + +/// The inverse of `escape`, lossy: bytes that are no UTF-8 become U+FFFD, +/// an escape it does not know stays as written. +pub(crate) fn unescape(s: &str) -> String { + let b = s.as_bytes(); + let mut out: Vec = Vec::with_capacity(b.len()); + let mut i = 0; + while i < b.len() { + if b[i] != b'\\' || i + 1 >= b.len() { + out.push(b[i]); + i += 1; + continue; + } + match b[i + 1] { + b'\\' => out.push(b'\\'), + b't' => out.push(b'\t'), + b'n' => out.push(b'\n'), + b'x' if i + 3 < b.len() && hex(b[i + 2]).is_some() && hex(b[i + 3]).is_some() => { + out.push(hex(b[i + 2]).unwrap_or(0) * 16 + hex(b[i + 3]).unwrap_or(0)); + i += 4; + continue; + } + other => { + out.push(b'\\'); + out.push(other); + } + } + i += 2; + } + String::from_utf8_lossy(&out).into_owned() +} + +fn hex(c: u8) -> Option { + match c { + b'0'..=b'9' => Some(c - b'0'), + b'a'..=b'f' => Some(c - b'a' + 10), + b'A'..=b'F' => Some(c - b'A' + 10), + _ => None, + } +} + +pub fn render(s: &StateFile) -> String { + let mut out = match &s.head { + Head::SelfInfo { fingerprint, listen } => { + format!("self\t{}\t{}\n", escape(fingerprint), escape(listen)) + } + Head::Error(text) => format!("error\t{}\n", escape(text)), + }; + for d in &s.devices { + let flags: Vec = d.flags.iter().map(|f| escape(f).replace(',', "\\x2c")).collect(); + out.push_str(&format!( + "{}\t{}\t{}\t{}\t{}\t{}\t{}\n", + escape(&d.name), + escape(&d.fingerprint), + d.state.as_str(), + d.since, + d.width, + d.height, + flags.join(",") + )); + } + out +} + +/// Read a state file. An unreadable head gives an empty error head; a +/// device line that does not parse is skipped. +pub fn parse(text: &str) -> StateFile { + let mut lines = text.lines(); + let head = lines + .next() + .and_then(parse_head) + .unwrap_or_else(|| Head::Error(String::new())); + let devices = lines.filter_map(parse_device).collect(); + StateFile { head, devices } +} + +fn parse_head(line: &str) -> Option { + let f: Vec<&str> = line.split('\t').collect(); + match f.as_slice() { + ["self", fp, listen, ..] => Some(Head::SelfInfo { + fingerprint: unescape(fp), + listen: unescape(listen), + }), + ["error", text, ..] => Some(Head::Error(unescape(text))), + _ => None, + } +} + +fn parse_device(line: &str) -> Option { + let f: Vec<&str> = line.split('\t').collect(); + if f.len() < 7 { + return None; + } + Some(DevLine { + name: unescape(f[0]), + fingerprint: unescape(f[1]), + state: DevState::parse(f[2])?, + since: f[3].parse().ok()?, + width: f[4].parse().ok()?, + height: f[5].parse().ok()?, + flags: f[6].split(',').filter(|s| !s.is_empty()).map(unescape).collect(), + }) +} + +/// Write the file atomically, mode 0600. +pub fn write(path: &Path, s: &StateFile) -> io::Result<()> { + crate::atomic::write(path, render(s).as_bytes(), 0o600) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn dev(name: &str, fp: &str, state: DevState) -> DevLine { + DevLine { + name: name.into(), + fingerprint: fp.into(), + state, + since: 1_700_000_000, + width: 1920, + height: 1080, + flags: vec![], + } + } + + fn head() -> Head { + Head::SelfInfo { + fingerprint: "v2:sha256:ab".into(), + listen: "0.0.0.0:24800".into(), + } + } + + #[test] + fn render_parse_roundtrip() { + let mut changed = dev("mac", "v2:sha256:02", DevState::Pending); + changed.flags = vec!["fp-changed".into()]; + let s = StateFile { + head: head(), + devices: vec![ + dev("laptop", "v2:sha256:01", DevState::Active), + changed, + dev("ünï ☃", "v2:sha256:03", DevState::Offline), + ], + }; + let text = render(&s); + assert!(text.starts_with("self\tv2:sha256:ab\t0.0.0.0:24800\n")); + assert!(text.contains("laptop\tv2:sha256:01\tactive\t1700000000\t1920\t1080\t\n")); + assert!(text.contains("\tpending\t1700000000\t1920\t1080\tfp-changed\n")); + assert_eq!(parse(&text), s); + } + + #[test] + fn state_line_escapes_hostile_names() { + let name = "a\tb\nc\x01d\\e\x7f\r"; + let s = StateFile { + head: head(), + devices: vec![dev(name, "v2:sha256:01", DevState::Connected)], + }; + let text = render(&s); + assert_eq!(text.lines().count(), 2, "one line per device: {text:?}"); + assert!(text.contains("a\\tb\\nc\\x01d\\\\e\\x7f\\x0d\t")); + assert_eq!(parse(&text), s); + // A hand-made line with bytes that are no UTF-8 stays one device. + let raw = "self\tfp\t:1\nbad\\xff\\xfename\tfp\tpending\t1\t0\t0\t\n"; + let p = parse(raw); + assert_eq!(p.devices.len(), 1); + assert_eq!(p.devices[0].name, "bad\u{fffd}\u{fffd}name"); + assert_eq!(render(&p).lines().count(), 2); + } + + #[test] + fn parse_ignores_extra_fields() { + let text = "self\tfp\t:24800\textra\nn\tf\tactive\t5\t10\t20\tfp-changed\tfuture\tmore\n\ + garbage line\nn2\tf\tbogus\t5\t1\t1\t\nn3\tf\tactive\tx\t1\t1\t\n"; + let p = parse(text); + assert_eq!( + p.head, + Head::SelfInfo { + fingerprint: "fp".into(), + listen: ":24800".into() + } + ); + assert_eq!(p.devices.len(), 1); + assert_eq!(p.devices[0].flags, vec!["fp-changed".to_string()]); + assert_eq!(p.devices[0].width, 10); + } + + #[test] + fn same_name_two_lines() { + let mut changed = dev("laptop", "v2:sha256:bb", DevState::Pending); + changed.flags = vec!["fp-changed".into()]; + let s = StateFile { + head: head(), + devices: vec![dev("laptop", "v2:sha256:aa", DevState::Connected), changed], + }; + let p = parse(&render(&s)); + assert_eq!(p.devices.len(), 2); + assert_eq!(p, s); + } + + #[test] + fn error_head() { + let s = StateFile { + head: Head::Error("cannot bind\t0.0.0.0:24800\nin use".into()), + devices: vec![], + }; + let text = render(&s); + assert_eq!(text.lines().count(), 1); + assert_eq!(parse(&text), s); + assert_eq!(parse("").head, Head::Error(String::new())); + } + + #[test] + fn write_is_atomic_and_private() { + use std::os::unix::fs::PermissionsExt; + let d = crate::testdir::TestDir::new("statefile", "w"); + let p = d.join("state"); + let s = StateFile { + head: head(), + devices: vec![dev("a", "f", DevState::Rejected)], + }; + write(&p, &s).unwrap(); + assert_eq!(std::fs::metadata(&p).unwrap().permissions().mode() & 0o777, 0o600); + assert_eq!(parse(&std::fs::read_to_string(&p).unwrap()), s); + } + + #[test] + fn path_prefers_the_override() { + let o = |s: &str| Some(OsString::from(s)); + assert_eq!(path_from(o("/x/s"), o("/run")), Some(PathBuf::from("/x/s"))); + assert_eq!( + path_from(o(""), o("/run")), + Some(PathBuf::from("/run/thinfloe-deskflow.state")) + ); + assert_eq!(path_from(None, None), None); + } +} diff --git a/src/thinfloe-menu/src/deskflow/tls.rs b/src/thinfloe-menu/src/deskflow/tls.rs new file mode 100644 index 0000000..1fcd8c8 --- /dev/null +++ b/src/thinfloe-menu/src/deskflow/tls.rs @@ -0,0 +1,305 @@ +//! The Deskflow server's TLS: rustls with ring, TLS 1.2 and 1.3, and a +//! client certificate always required (spec, Identity and pairing). The +//! client certificate is not chain-checked, since Deskflow's are +//! self-signed; the daemon decides trust by its fingerprint. + +use std::sync::Arc; + +use rustls::client::danger::HandshakeSignatureValid; +use rustls::crypto::CryptoProvider; +use rustls::pki_types::{CertificateDer, PrivateKeyDer, PrivatePkcs8KeyDer, UnixTime}; +use rustls::server::danger::{ClientCertVerified, ClientCertVerifier}; +use rustls::{DigitallySignedStruct, DistinguishedName, Error, ServerConfig, ServerConnection, SignatureScheme}; + +use super::ident::{self, Identity}; + +/// The server config for ThinFloe's identity. `ident::load_or_create` has +/// checked that the key belongs to the certificate, so building it cannot +/// fail. +pub fn server_config(id: &Identity) -> Arc { + let provider = Arc::new(rustls::crypto::ring::default_provider()); + let key = PrivateKeyDer::Pkcs8(PrivatePkcs8KeyDer::from(id.key_der.clone())); + let cfg = ServerConfig::builder_with_provider(provider) + .with_protocol_versions(&[&rustls::version::TLS13, &rustls::version::TLS12]) + .expect("ring supports TLS 1.2 and 1.3") + .with_client_cert_verifier(Arc::new(AnyClient::new())) + .with_single_cert(vec![CertificateDer::from(id.cert_der.clone())], key) + .expect("the identity was checked when it was loaded"); + Arc::new(cfg) +} + +/// The fingerprint of the certificate the client presented, once the +/// handshake has received it. +pub fn peer_fingerprint(conn: &ServerConnection) -> Option { + conn.peer_certificates()? + .first() + .map(|c| ident::fingerprint(c.as_ref())) +} + +/// Takes any client certificate without a chain or name check, but still +/// verifies the client's handshake signature with it, so the client holds +/// the key of the certificate whose fingerprint the daemon trusts. +#[derive(Debug)] +struct AnyClient(Arc); + +impl AnyClient { + fn new() -> AnyClient { + AnyClient(Arc::new(rustls::crypto::ring::default_provider())) + } +} + +impl ClientCertVerifier for AnyClient { + fn root_hint_subjects(&self) -> &[DistinguishedName] { + &[] + } + + fn verify_client_cert( + &self, + _end_entity: &CertificateDer<'_>, + _intermediates: &[CertificateDer<'_>], + _now: UnixTime, + ) -> Result { + Ok(ClientCertVerified::assertion()) + } + + fn verify_tls12_signature( + &self, + message: &[u8], + cert: &CertificateDer<'_>, + dss: &DigitallySignedStruct, + ) -> Result { + rustls::crypto::verify_tls12_signature(message, cert, dss, &self.0.signature_verification_algorithms) + } + + fn verify_tls13_signature( + &self, + message: &[u8], + cert: &CertificateDer<'_>, + dss: &DigitallySignedStruct, + ) -> Result { + rustls::crypto::verify_tls13_signature(message, cert, dss, &self.0.signature_verification_algorithms) + } + + fn supported_verify_schemes(&self) -> Vec { + self.0.signature_verification_algorithms.supported_schemes() + } +} + +/// A client for the tests that takes any server certificate, as a +/// Deskflow client that trusts the server by fingerprint does. +#[cfg(test)] +pub(crate) mod testclient { + use std::sync::Arc; + + use rustls::client::danger::{HandshakeSignatureValid, ServerCertVerified, ServerCertVerifier}; + use rustls::crypto::CryptoProvider; + use rustls::pki_types::{CertificateDer, PrivateKeyDer, PrivatePkcs8KeyDer, ServerName, UnixTime}; + use rustls::{ClientConfig, DigitallySignedStruct, Error, SignatureScheme}; + + /// A Deskflow client trusts the server by fingerprint too; the test + /// client takes any server certificate (signatures still checked). + #[derive(Debug)] + pub(crate) struct AnyServer(pub(crate) Arc); + + impl ServerCertVerifier for AnyServer { + fn verify_server_cert( + &self, + _: &CertificateDer<'_>, + _: &[CertificateDer<'_>], + _: &ServerName<'_>, + _: &[u8], + _: UnixTime, + ) -> Result { + Ok(ServerCertVerified::assertion()) + } + fn verify_tls12_signature( + &self, + m: &[u8], + c: &CertificateDer<'_>, + d: &DigitallySignedStruct, + ) -> Result { + rustls::crypto::verify_tls12_signature(m, c, d, &self.0.signature_verification_algorithms) + } + fn verify_tls13_signature( + &self, + m: &[u8], + c: &CertificateDer<'_>, + d: &DigitallySignedStruct, + ) -> Result { + rustls::crypto::verify_tls13_signature(m, c, d, &self.0.signature_verification_algorithms) + } + fn supported_verify_schemes(&self) -> Vec { + self.0.signature_verification_algorithms.supported_schemes() + } + } + + /// TLS 1.3 and 1.2, with this client certificate. + pub(crate) fn config(cert: &rcgen::CertifiedKey) -> Arc { + let provider = Arc::new(rustls::crypto::ring::default_provider()); + let cfg = ClientConfig::builder_with_provider(provider.clone()) + .with_safe_default_protocol_versions() + .unwrap() + .dangerous() + .with_custom_certificate_verifier(Arc::new(AnyServer(provider))) + .with_client_auth_cert( + vec![cert.cert.der().clone()], + PrivateKeyDer::Pkcs8(PrivatePkcs8KeyDer::from(cert.signing_key.serialize_der())), + ) + .unwrap(); + Arc::new(cfg) + } + + pub(crate) fn server_name() -> ServerName<'static> { + ServerName::try_from("thinfloe").unwrap() + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::deskflow::ident::{self, fingerprint}; + use crate::testdir::TestDir; + use rustls::pki_types::{PrivateKeyDer, PrivatePkcs8KeyDer, ServerName}; + use rustls::{ClientConfig, ClientConnection, Error, SignatureScheme}; + + use super::testclient::AnyServer; + + fn server_identity(tag: &str) -> (TestDir, ident::Identity) { + let d = TestDir::new("deskflow-tls", tag); + let id = ident::load_or_create(&d.join("identity.pem"), "server").unwrap(); + (d, id) + } + + fn client( + cert: Option<&rcgen::CertifiedKey>, + version: &'static rustls::SupportedProtocolVersion, + ) -> ClientConnection { + let provider = Arc::new(rustls::crypto::ring::default_provider()); + let b = ClientConfig::builder_with_provider(provider.clone()) + .with_protocol_versions(&[version]) + .unwrap() + .dangerous() + .with_custom_certificate_verifier(Arc::new(AnyServer(provider))); + let cfg = match cert { + None => b.with_no_client_auth(), + Some(c) => b + .with_client_auth_cert( + vec![c.cert.der().clone()], + PrivateKeyDer::Pkcs8(PrivatePkcs8KeyDer::from(c.signing_key.serialize_der())), + ) + .unwrap(), + }; + ClientConnection::new(Arc::new(cfg), ServerName::try_from("thinfloe").unwrap()).unwrap() + } + + /// Shuttle records between the two ends until both are done or one + /// fails; the server's error, if any. + fn handshake(c: &mut ClientConnection, s: &mut ServerConnection) -> Result<(), Error> { + for _ in 0..20 { + let mut buf = Vec::new(); + while c.wants_write() { + c.write_tls(&mut buf).unwrap(); + } + if !buf.is_empty() { + s.read_tls(&mut buf.as_slice()).unwrap(); + s.process_new_packets()?; + } + let mut buf = Vec::new(); + while s.wants_write() { + s.write_tls(&mut buf).unwrap(); + } + if !buf.is_empty() { + c.read_tls(&mut buf.as_slice()).unwrap(); + // A client error shows on the server's next read. + let _ = c.process_new_packets(); + } + if !c.is_handshaking() && !s.is_handshaking() && !c.wants_write() { + return Ok(()); + } + } + panic!("the handshake did not finish"); + } + + fn self_signed(name: &str) -> rcgen::CertifiedKey { + rcgen::generate_simple_self_signed(vec![name.to_string()]).unwrap() + } + + #[test] + fn tls_handshake_needs_client_cert() { + let (_d, id) = server_identity("needs"); + let cfg = server_config(&id); + for version in [&rustls::version::TLS13, &rustls::version::TLS12] { + let mut c = client(None, version); + let mut s = ServerConnection::new(cfg.clone()).unwrap(); + let err = handshake(&mut c, &mut s).unwrap_err(); + assert!(matches!(err, Error::NoCertificatesPresented), "{version:?}: {err:?}"); + assert_eq!(peer_fingerprint(&s), None); + + let cert = self_signed("laptop"); + let mut c = client(Some(&cert), version); + let mut s = ServerConnection::new(cfg.clone()).unwrap(); + handshake(&mut c, &mut s).unwrap(); + assert_eq!(peer_fingerprint(&s), Some(fingerprint(cert.cert.der()))); + assert_eq!(s.protocol_version(), Some(version.version)); + } + } + + #[test] + fn the_client_sees_the_identity_certificate() { + let (_d, id) = server_identity("server-cert"); + let cert = self_signed("laptop"); + let mut c = client(Some(&cert), &rustls::version::TLS13); + let mut s = ServerConnection::new(server_config(&id)).unwrap(); + handshake(&mut c, &mut s).unwrap(); + let seen = c.peer_certificates().unwrap()[0].as_ref().to_vec(); + assert_eq!(seen, id.cert_der); + } + + /// Presents one certificate but signs with another key. + #[derive(Debug)] + struct WrongKey(Arc); + + impl rustls::client::ResolvesClientCert for WrongKey { + fn resolve(&self, _: &[&[u8]], _: &[SignatureScheme]) -> Option> { + Some(self.0.clone()) + } + fn has_certs(&self) -> bool { + true + } + } + + #[test] + fn a_client_signing_with_another_key_is_refused() { + let (_d, id) = server_identity("wrong-key"); + let cfg = server_config(&id); + let shown = self_signed("laptop"); + let other = self_signed("other"); + let provider = Arc::new(rustls::crypto::ring::default_provider()); + let key = provider + .key_provider + .load_private_key(PrivateKeyDer::Pkcs8(PrivatePkcs8KeyDer::from( + other.signing_key.serialize_der(), + ))) + .unwrap(); + let resolver = WrongKey(Arc::new(rustls::sign::CertifiedKey::new( + vec![shown.cert.der().clone()], + key, + ))); + let resolver = Arc::new(resolver); + for version in [&rustls::version::TLS13, &rustls::version::TLS12] { + let ccfg = ClientConfig::builder_with_provider(provider.clone()) + .with_protocol_versions(&[version]) + .unwrap() + .dangerous() + .with_custom_certificate_verifier(Arc::new(AnyServer(provider.clone()))) + .with_client_cert_resolver(resolver.clone()); + let mut c = ClientConnection::new(Arc::new(ccfg), ServerName::try_from("thinfloe").unwrap()).unwrap(); + let mut s = ServerConnection::new(cfg.clone()).unwrap(); + let err = handshake(&mut c, &mut s).unwrap_err(); + assert!( + matches!(err, Error::InvalidCertificate(rustls::CertificateError::BadSignature)), + "{version:?}: {err:?}" + ); + } + } +} diff --git a/src/thinfloe-menu/src/deskflow_sup.rs b/src/thinfloe-menu/src/deskflow_sup.rs new file mode 100644 index 0000000..fa36349 --- /dev/null +++ b/src/thinfloe-menu/src/deskflow_sup.rs @@ -0,0 +1,652 @@ +//! The menu's side of the Deskflow daemon (spec, Processes): it runs +//! `thinfloe-menu --deskflow` while `[deskflow] listen` is on, starts it +//! again after it ended (1 s, 2 s, 4 s … 60 s apart), tells it to read its +//! file again after a write, and stops it when the switch goes off or the +//! menu exits. +//! +//! The daemon runs in a process group of its own and is signalled through +//! the group. It sets `PR_SET_PDEATHSIG` itself, so a menu that dies +//! takes it along. That signal follows the *thread* that forked, not the +//! process: the menu calls `tick` (which spawns) only from its event loop +//! on the main thread, which lives as long as the process. A spawn from a +//! job or worker thread would end the daemon when that thread ends. + +use std::ffi::OsString; +use std::os::unix::process::{CommandExt, ExitStatusExt}; +use std::path::PathBuf; +use std::process::{Child, Command, ExitStatus, Stdio}; +use std::time::{Duration, Instant, SystemTime}; + +use crate::deskflow::statefile::{self, Head}; +use crate::deskflow::{DESKFLOW_ARG, PARENT_ENV}; + +/// The first wait before a start again. +const FIRST_DELAY: Duration = Duration::from_secs(1); +/// The longest wait between two starts. +const MAX_DELAY: Duration = Duration::from_secs(60); +/// A run at least this long starts the waits from `FIRST_DELAY` again. +const RESET_AFTER: Duration = Duration::from_secs(60); +/// After SIGTERM for a switch turned off, how long before SIGKILL. +const TERM_GRACE: Duration = Duration::from_secs(1); +/// File times come from a coarse clock, a few milliseconds behind +/// `SystemTime::now`; a state file this much older than the start still +/// counts as written by this run. +const MTIME_SLACK: Duration = Duration::from_secs(1); +/// How often `stop` looks whether the daemon has ended. +const STOP_POLL: Duration = Duration::from_millis(10); + +/// Called from the waiter thread when the daemon has ended (not yet +/// reaped); the menu wakes its loop with it. +type Notify = Box; + +struct Running { + child: Child, + started: Instant, + /// When it started, for the age of the state file. + started_wall: SystemTime, + /// Set when the menu asked it to end: SIGKILL is due then, and the + /// exit is no failure. + kill_at: Option, +} + +pub struct Supervisor { + program: PathBuf, + state_file: Option, + notify: Option>, + wanted: bool, + running: Option, + /// When the next start is due, while wanted and not running. + start_at: Option, + /// The wait before the start after the next exit. + delay: Duration, + failure: Option, +} + +impl Supervisor { + /// `program` is run with `--deskflow`: the menu's own binary. + pub fn new(program: PathBuf) -> Supervisor { + Supervisor { + program, + state_file: statefile::path(), + notify: None, + wanted: false, + running: None, + start_at: None, + delay: FIRST_DELAY, + failure: None, + } + } + + /// The state file the daemon writes its error head to; by default the + /// one `statefile::path` names. + pub fn with_state_file(mut self, path: Option) -> Supervisor { + self.state_file = path; + self + } + + /// `f` runs on a thread of its own each time a daemon ends, so the + /// caller can wake up and `tick`. + pub fn with_notify(mut self, f: impl Fn() + Send + Sync + 'static) -> Supervisor { + self.notify = Some(std::sync::Arc::new(Box::new(f))); + self + } + + /// The switch: on starts the daemon at the next `tick`, off sends it + /// SIGTERM (SIGKILL follows after `TERM_GRACE`). + pub fn want(&mut self, listen: bool, now: Instant) { + if listen == self.wanted { + return; + } + self.wanted = listen; + self.failure = None; + self.delay = FIRST_DELAY; + if listen { + self.start_at = Some(now); + return; + } + self.start_at = None; + if let Some(r) = self.running.as_mut() + && r.kill_at.is_none() + { + signal_group(&r.child, libc::SIGTERM); + r.kill_at = Some(now + TERM_GRACE); + } + } + + /// Reap an ended daemon, start one that is due, send a SIGKILL that is + /// due. Returns when it wants to be called next; `None` while + /// it waits only for the daemon to end (the notifier says when). + pub fn tick(&mut self, now: Instant) -> Option { + if let Some(r) = self.running.as_mut() { + match r.child.try_wait() { + Ok(Some(status)) => self.ended(status, now), + Ok(None) => { + if let Some(at) = r.kill_at { + if now < at { + return Some(at); + } + signal_group(&r.child, libc::SIGKILL); + } + return None; + } + Err(e) => self.lost(e, now), + } + } + if !self.wanted { + return None; + } + let at = self.start_at?; + if now < at { + return Some(at); + } + self.start_at = None; + if let Err(e) = self.spawn(now) { + eprintln!("thinfloe-menu: {e}"); + self.failure = Some(e); + self.schedule(now); + return self.start_at; + } + None + } + + /// Tell a running daemon to read its file again (SIGHUP). A daemon + /// that has not yet set its handler gets the signal once it has: it + /// starts with SIGHUP blocked. + pub fn reload(&self) { + if let Some(r) = self.running.as_ref() + && r.kill_at.is_none() + { + signal_group(&r.child, libc::SIGHUP); + } + } + + /// End the daemon now: SIGTERM to its group, at most `wait` for it to + /// end, then SIGKILL. Blocks; for the menu's exit. + pub fn stop(&mut self, wait: Duration) { + self.wanted = false; + self.start_at = None; + let Some(mut r) = self.running.take() else { return }; + signal_group(&r.child, libc::SIGTERM); + let deadline = Instant::now() + wait; + loop { + match r.child.try_wait() { + Ok(Some(_)) | Err(_) => return, + Ok(None) if Instant::now() >= deadline => break, + Ok(None) => std::thread::sleep(STOP_POLL), + } + } + signal_group(&r.child, libc::SIGKILL); + let _ = r.child.wait(); + } + + /// Why the daemon ended the last time it failed: its error line from + /// the state file, else its exit status. `None` after a switch and + /// after a run of `RESET_AFTER`. + pub fn last_failure(&self) -> Option { + self.failure.clone() + } + + /// The daemon's pid while it runs. + pub fn pid(&self) -> Option { + self.running.as_ref().map(|r| r.child.id()) + } + + fn spawn(&mut self, now: Instant) -> Result<(), String> { + let mut cmd = Command::new(&self.program); + cmd.arg(DESKFLOW_ARG) + .env(PARENT_ENV, OsString::from(std::process::id().to_string())) + .stdin(Stdio::null()) + .process_group(0); + // Output goes where the menu's goes: the session log. + // SAFETY: only signal and sigprocmask, both async-signal-safe. + unsafe { + cmd.pre_exec(|| { + crate::jobs::reset_signals(); + // A SIGHUP before the daemon's handler is set would end it; + // blocked, it waits for the daemon to unblock it. + let mut set: libc::sigset_t = std::mem::zeroed(); + libc::sigemptyset(&mut set); + libc::sigaddset(&mut set, libc::SIGHUP); + libc::sigprocmask(libc::SIG_BLOCK, &set, std::ptr::null_mut()); + Ok(()) + }); + } + let child = cmd.spawn().map_err(|e| { + format!( + "the Deskflow daemon could not be started: {} {e}", + self.program.display() + ) + })?; + if let Some(n) = self.notify.clone() { + let pid = child.id() as libc::id_t; + std::thread::spawn(move || { + wait_ended(pid); + n(); + }); + } + self.running = Some(Running { + child, + started: now, + started_wall: SystemTime::now(), + kill_at: None, + }); + Ok(()) + } + + fn ended(&mut self, status: ExitStatus, now: Instant) { + let Some(r) = self.running.take() else { return }; + if r.kill_at.is_some() { + // Asked to end: a switch turned on again in the meantime starts + // at once. + if self.wanted { + self.start_at = Some(now); + } + return; + } + if now.saturating_duration_since(r.started) >= RESET_AFTER { + self.delay = FIRST_DELAY; + self.failure = None; + } + if !status.success() { + let why = self.reason(status, r.started_wall); + eprintln!("thinfloe-menu: the Deskflow daemon stopped: {why}"); + self.failure = Some(why); + } + if self.wanted { + self.schedule(now); + } + } + + /// `try_wait` failed: the child is beyond reach (reaped elsewhere, so + /// its pid may already be another process's). It counts as ended and is + /// never signalled again; a start again follows as after a failure. + fn lost(&mut self, e: std::io::Error, now: Instant) { + let Some(r) = self.running.take() else { return }; + let why = format!("the Deskflow daemon cannot be waited for: {e}"); + eprintln!("thinfloe-menu: {why}"); + if r.kill_at.is_none() { + self.failure = Some(why); + } + if self.wanted { + if r.kill_at.is_some() { + self.start_at = Some(now); + } else { + self.schedule(now); + } + } + } + + /// The next start after `delay`, and the wait after it doubled. + fn schedule(&mut self, now: Instant) { + self.start_at = Some(now + self.delay); + self.delay = (self.delay * 2).min(MAX_DELAY); + } + + /// The error head the daemon wrote in this run, else its status. + fn reason(&self, status: ExitStatus, started: SystemTime) -> String { + if status.code() == Some(1) + && let Some(path) = self.state_file.as_ref() + && let Ok(meta) = std::fs::metadata(path) + && meta.modified().is_ok_and(|m| m + MTIME_SLACK >= started) + && let Ok(text) = std::fs::read_to_string(path) + && let Head::Error(why) = statefile::parse(&text).head + { + return why; + } + match (status.code(), status.signal()) { + (Some(code), _) => format!("it ended with status {code}"), + (None, Some(sig)) => format!("it was ended by signal {sig}"), + (None, None) => "it ended".into(), + } + } +} + +/// Signal the daemon's process group (its pid: it leads the group). +fn signal_group(child: &Child, sig: libc::c_int) { + if let Some(target) = crate::jobs::stop_target(child.id() as i32) { + // SAFETY: kill has no memory preconditions; ESRCH is ignored. + unsafe { libc::kill(target, sig) }; + } +} + +/// Wait until `pid` has ended, without reaping it: `tick` reaps. +fn wait_ended(pid: libc::id_t) { + loop { + // SAFETY: a zeroed siginfo_t that waitid fills. + let mut info: libc::siginfo_t = unsafe { std::mem::zeroed() }; + let r = unsafe { libc::waitid(libc::P_PID, pid, &mut info, libc::WEXITED | libc::WNOWAIT) }; + if r == 0 || std::io::Error::last_os_error().raw_os_error() != Some(libc::EINTR) { + return; + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::testdir::TestDir; + use std::os::unix::fs::PermissionsExt; + use std::path::Path; + + /// A stand-in daemon: `body` as a shell script, run with `--deskflow`. + fn program(d: &Path, body: &str) -> PathBuf { + program_in(d, "/bin/sh", body) + } + + fn program_in(d: &Path, shell: &str, body: &str) -> PathBuf { + let p = d.join("daemon"); + std::fs::write(&p, format!("#!{shell}\n{body}\n")).unwrap(); + std::fs::set_permissions(&p, std::fs::Permissions::from_mode(0o755)).unwrap(); + p + } + + fn sup(d: &Path, body: &str) -> Supervisor { + Supervisor::new(program(d, body)).with_state_file(Some(d.join("state"))) + } + + /// Tick at `now` until the running daemon has ended and been + /// reaped; the next wake is then returned. + fn until_ended(s: &mut Supervisor, now: Instant) -> Option { + let deadline = Instant::now() + Duration::from_secs(5); + loop { + let wake = s.tick(now); + if s.pid().is_none() { + return wake; + } + assert!(Instant::now() < deadline, "the stand-in did not end"); + std::thread::sleep(Duration::from_millis(5)); + } + } + + /// Ended, as a zombie or gone. + fn gone(pid: u32) -> bool { + match std::fs::read_to_string(format!("/proc/{pid}/stat")) { + Ok(stat) => stat.rsplit_once(") ").is_some_and(|(_, rest)| rest.starts_with('Z')), + Err(_) => true, + } + } + + fn gone_within(pid: u32, within: Duration) -> bool { + let deadline = Instant::now() + within; + while !gone(pid) { + if Instant::now() >= deadline { + return false; + } + std::thread::sleep(Duration::from_millis(10)); + } + true + } + + #[test] + fn backoff_doubles_to_60() { + let d = TestDir::new("deskflow-sup", "backoff"); + let mut s = sup(&d, "exit 1"); + let mut now = Instant::now(); + s.want(true, now); + assert_eq!(s.tick(now), None, "the switch starts the daemon at once"); + assert!(s.pid().is_some()); + let mut waits = Vec::new(); + for _ in 0..8 { + let at = until_ended(&mut s, now).expect("a start again is due"); + waits.push((at - now).as_secs()); + assert_eq!(s.tick(at - Duration::from_millis(1)), Some(at), "nothing starts early"); + now = at; + assert_eq!(s.tick(now), None); + assert!(s.pid().is_some(), "started again when due"); + } + assert_eq!(waits, [1, 2, 4, 8, 16, 32, 60, 60]); + assert_eq!(s.last_failure().as_deref(), Some("it ended with status 1")); + s.stop(Duration::from_secs(1)); + } + + #[test] + fn long_run_resets_backoff() { + let d = TestDir::new("deskflow-sup", "reset"); + let mut s = sup(&d, "exit 3"); + let mut now = Instant::now(); + s.want(true, now); + s.tick(now); + for _ in 0..3 { + now = until_ended(&mut s, now).unwrap(); + s.tick(now); + } + // The fourth run lasts 61 s as far as the supervisor can tell. + let later = now + Duration::from_secs(61); + let at = until_ended(&mut s, later).unwrap(); + assert_eq!(at - later, Duration::from_secs(1)); + assert_eq!(s.last_failure().as_deref(), Some("it ended with status 3")); + s.stop(Duration::from_secs(1)); + } + + #[test] + fn listen_off_stops() { + let d = TestDir::new("deskflow-sup", "off"); + let mut s = sup(&d, "exec sleep 100"); + let now = Instant::now(); + s.want(true, now); + s.tick(now); + let pid = s.pid().unwrap(); + s.want(false, now); + until_ended(&mut s, now); + assert!(gone(pid)); + assert_eq!(s.tick(now + Duration::from_secs(120)), None, "no start again"); + assert_eq!(s.pid(), None); + assert_eq!(s.last_failure(), None, "a stop asked for is no failure"); + } + + #[test] + fn listen_off_kills_a_daemon_that_ignores_sigterm() { + let d = TestDir::new("deskflow-sup", "off-kill"); + let ready = d.join("ready"); + let mut s = sup( + &d, + &format!("trap '' TERM\n: >{}\nwhile :; do sleep 1; done", ready.display()), + ); + let now = Instant::now(); + s.want(true, now); + s.tick(now); + let deadline = Instant::now() + Duration::from_secs(5); + while !ready.exists() { + assert!(Instant::now() < deadline); + std::thread::sleep(Duration::from_millis(5)); + } + s.want(false, now); + let at = s.tick(now).expect("SIGKILL is due"); + assert_eq!(at - now, Duration::from_secs(1)); + assert!(s.pid().is_some(), "still running before the SIGKILL"); + until_ended(&mut s, at); + assert_eq!(s.pid(), None); + } + + #[test] + fn stop_kills_group() { + let d = TestDir::new("deskflow-sup", "stop"); + let kid = d.join("kid"); + // The daemon and a child of it ignore SIGTERM: only SIGKILL to the + // whole group ends both. + let mut s = sup( + &d, + &format!( + "trap '' TERM\nsleep 100 &\necho $! >{}.tmp\nmv {0}.tmp {0}\nwait", + kid.display() + ), + ); + let now = Instant::now(); + s.want(true, now); + s.tick(now); + let pid = s.pid().unwrap(); + let deadline = Instant::now() + Duration::from_secs(5); + while !kid.exists() { + assert!(Instant::now() < deadline); + std::thread::sleep(Duration::from_millis(5)); + } + let kid: u32 = std::fs::read_to_string(&kid).unwrap().trim().parse().unwrap(); + let t0 = Instant::now(); + s.stop(Duration::from_secs(1)); + let took = t0.elapsed(); + assert!( + took >= Duration::from_secs(1) && took < Duration::from_secs(3), + "{took:?}" + ); + assert!(gone(pid)); + assert!( + gone_within(kid, Duration::from_secs(2)), + "the daemon's child outlived the SIGKILL" + ); + assert_eq!(s.pid(), None); + assert_eq!( + s.tick(now + Duration::from_secs(120)), + None, + "a stopped daemon is not started again" + ); + } + + #[test] + fn stop_waits_no_longer_than_the_daemon_takes() { + let d = TestDir::new("deskflow-sup", "stop-quick"); + let mut s = sup(&d, "exec sleep 100"); + let now = Instant::now(); + s.want(true, now); + s.tick(now); + let pid = s.pid().expect("started"); + let t0 = Instant::now(); + s.stop(Duration::from_secs(1)); + assert!(gone(pid)); + assert!(t0.elapsed() < Duration::from_millis(900), "{:?}", t0.elapsed()); + } + + #[test] + fn an_exit_0_with_listen_still_wanted_starts_again() { + let d = TestDir::new("deskflow-sup", "exit0"); + let mut s = sup(&d, "exit 0"); + let now = Instant::now(); + s.want(true, now); + s.tick(now); + let at = until_ended(&mut s, now).expect("a start again is due"); + assert_eq!(at - now, Duration::from_secs(1)); + assert_eq!(s.last_failure(), None, "exit 0 is no failure"); + s.tick(at); + assert!(s.pid().is_some()); + s.stop(Duration::from_secs(1)); + } + + #[test] + fn the_error_head_of_this_run_is_the_last_failure() { + let d = TestDir::new("deskflow-sup", "error-head"); + let state = d.join("state"); + let mut s = sup( + &d, + &format!("printf 'error\\tport 24800 is in use\\n' >{}\nexit 1", state.display()), + ); + let now = Instant::now(); + s.want(true, now); + s.tick(now); + until_ended(&mut s, now); + assert_eq!(s.last_failure().as_deref(), Some("port 24800 is in use")); + // A switch turned off and on again forgets it. + s.want(false, now); + assert_eq!(s.last_failure(), None); + } + + #[test] + fn an_old_error_head_is_not_this_runs_reason() { + let d = TestDir::new("deskflow-sup", "old-head"); + let state = d.join("state"); + std::fs::write(&state, "error\tan old reason\n").unwrap(); + let old = SystemTime::now() - Duration::from_secs(10); + std::fs::File::options() + .write(true) + .open(&state) + .unwrap() + .set_modified(old) + .unwrap(); + let mut s = sup(&d, "exit 1"); + let now = Instant::now(); + s.want(true, now); + s.tick(now); + until_ended(&mut s, now); + assert_eq!(s.last_failure().as_deref(), Some("it ended with status 1")); + } + + #[test] + fn a_reload_reaches_the_daemon_also_before_its_handler_is_set() { + let d = TestDir::new("deskflow-sup", "reload"); + // The stand-in has no handler at all, like the daemon before its + // config, identity and listener. bash, as dash clears the mask. + let mut s = Supervisor::new(program_in(&d, "/bin/bash", "sleep 0.3")).with_state_file(None); + let now = Instant::now(); + s.want(true, now); + s.tick(now); + assert!(s.pid().is_some()); + s.reload(); + until_ended(&mut s, now); + assert_eq!(s.last_failure(), None, "the early SIGHUP ended the daemon"); + } + + #[test] + fn the_daemon_runs_in_a_group_of_its_own_with_the_parent_pid() { + let d = TestDir::new("deskflow-sup", "group"); + let out = d.join("out"); + let mut s = sup( + &d, + &format!( + "echo \"$1 $(ps -o pgid= -p $$ | tr -d ' ') $$ $TF_DESKFLOW_PARENT\" >{}", + out.display() + ), + ); + let now = Instant::now(); + s.want(true, now); + s.tick(now); + let pid = s.pid().unwrap(); + until_ended(&mut s, now); + let text = std::fs::read_to_string(&out).unwrap(); + assert_eq!(text.trim(), format!("--deskflow {pid} {pid} {}", std::process::id())); + } + + #[test] + fn a_daemon_that_cannot_be_waited_for_counts_as_ended() { + let d = TestDir::new("deskflow-sup", "wait-err"); + let mut s = sup(&d, "exit 0"); + let now = Instant::now(); + s.want(true, now); + s.tick(now); + let pid = s.pid().expect("started"); + assert!(gone_within(pid, Duration::from_secs(5)), "the stand-in did not end"); + // Someone else reaps it: try_wait fails from now on (ECHILD). + let mut status = 0; + // SAFETY: waitpid on our own child, with a valid status pointer. + assert_eq!( + unsafe { libc::waitpid(pid as libc::pid_t, &mut status, 0) }, + pid as libc::pid_t + ); + let at = s.tick(now).expect("a start again is due"); + assert_eq!(at - now, Duration::from_secs(1)); + assert_eq!(s.pid(), None, "the lost child is dropped, never signalled again"); + assert!(s.last_failure().is_some_and(|f| f.contains("cannot be waited for"))); + s.tick(at); + assert!(s.pid().is_some(), "started again when due"); + s.stop(Duration::from_secs(1)); + } + + #[test] + fn the_notifier_fires_when_the_daemon_ends() { + let d = TestDir::new("deskflow-sup", "notify"); + let (tx, rx) = std::sync::mpsc::channel(); + let tx = std::sync::Mutex::new(tx); + let mut s = Supervisor::new(program(&d, "sleep 0.1")) + .with_state_file(None) + .with_notify(move || { + let _ = tx.lock().unwrap().send(()); + }); + let now = Instant::now(); + s.want(true, now); + s.tick(now); + assert!(s.pid().is_some()); + rx.recv_timeout(Duration::from_secs(5)).expect("no wake for the exit"); + assert!( + s.tick(now).is_some(), + "the exit is reaped at the first tick after the wake" + ); + assert_eq!(s.pid(), None); + } +} diff --git a/src/thinfloe-menu/src/deskflow_ui.rs b/src/thinfloe-menu/src/deskflow_ui.rs new file mode 100644 index 0000000..3434010 --- /dev/null +++ b/src/thinfloe-menu/src/deskflow_ui.rs @@ -0,0 +1,309 @@ +//! Drawing the Deskflow band of the Screen tab: the switch, this +//! computer's address and fingerprint, edge resistance, the devices that +//! want to attach, and the settings of the device selected in the +//! arrangement. Everything that decides something lives in deskflowtab.rs; +//! this file only paints it and reports clicks. + +use crate::brand::{self, role}; +use crate::config::DeviceCfg; +use crate::deskflow::ident; +use crate::deskflow::statefile::DevLine; +use crate::deskflowcfg::Resistance; +use crate::deskflowtab::{self, DeskflowEvent, DeskflowTab, FP_CHANGED}; +use crate::kanshi::Side; +use crate::monitors::MonTab; +use crate::monitors_ui::DevPlace; +use crate::ui::{ROW_LEFT, ROW_MARGIN_X, ROW_RIGHT}; +use egui::{FontId, RichText, Ui}; +use shadcn_egui::Theme; +use shadcn_egui::components::button::{Button, ButtonVariant}; +use shadcn_egui::components::select::Select; +use shadcn_egui::components::switch::Switch; + +/// Above and below the content of a band, as the monitor band. +const BAND_PAD: i8 = 12; +/// Between the fingerprint picture and the text beside it. +const ART_GAP: f32 = 16.0; +/// Before a device's block, so two pending devices read apart. +const BLOCK_GAP: f32 = 8.0; +/// Bytes of the colon hex on one line: two lines for 32 bytes. +const HEX_BYTES_PER_LINE: usize = 16; + +const CLIPBOARD_TEXT: &str = "Share the clipboard"; +const LISTEN_TEXT: &str = "Let other computers use this keyboard and mouse (Deskflow)"; +const CHECK_NOTE: &str = "Check this fingerprint on the other computer before you trust it there."; +const NOT_FREE: &str = "This edge is not free in the current arrangement."; +const NO_FREE_EDGE: &str = "No monitor edge is free in the current arrangement."; +const RESISTANCES: [Resistance; 4] = [Resistance::Off, Resistance::Low, Resistance::Medium, Resistance::High]; +const RESISTANCE_LABELS: [&str; 4] = ["Off", "Low", "Medium", "High"]; + +/// The attached devices as the arrangement draws them. +pub fn places(tab: &DeskflowTab, mon: &MonTab) -> Vec { + let Some(layout) = mon.layout() else { + return Vec::new(); + }; + tab.cfg + .devices + .iter() + .map(|d| DevPlace { + name: d.name.clone(), + output: d.output.clone(), + side: d.side, + size: deskflowtab::device_size(&tab.state, d), + state: deskflowtab::device_state(tab, d), + inactive: deskflowtab::inactive(layout, mon.heads(), &tab.cfg.devices, d), + }) + .collect() +} + +/// The band, `width` wide as the panel, under the monitor band. `ipv4` is +/// the machine's address, for the *This computer* line. +pub fn band( + ui: &mut Ui, + t: &Theme, + tab: &DeskflowTab, + mon: &MonTab, + ipv4: Option, + width: f32, +) -> Option { + let mut event = None; + egui::Frame::new() + .fill(t.palette().card) + .inner_margin(egui::Margin { + left: ROW_LEFT, + right: ROW_RIGHT, + top: BAND_PAD, + bottom: BAND_PAD, + }) + .show(ui, |ui| { + ui.set_width(width - ROW_MARGIN_X); + ui.label( + RichText::new("Deskflow") + .font(brand::geo(brand::SECTION_PT)) + .color(t.palette().foreground), + ); + let mut on = tab.cfg.listen; + ui.horizontal(|ui| { + if ui.add(Switch::new(&mut on)).changed() { + event = Some(DeskflowEvent::Listen(on)); + } + ui.label(RichText::new(LISTEN_TEXT).color(t.palette().foreground)); + }); + if let Some(line) = deskflowtab::stopped_line(tab) { + warn(ui, t, &line); + } + if let Some(line) = deskflowtab::self_line(tab, ipv4) { + ui.label(RichText::new(line).color(t.palette().foreground)); + } + if let Some(fp) = deskflowtab::self_fingerprint(tab) { + fingerprint(ui, t, fp, |ui| muted(ui, t, CHECK_NOTE)); + } + let mut idx = RESISTANCES + .iter() + .position(|&r| r == tab.cfg.edge_resistance) + .unwrap_or(0); + form_row(ui, t, "Edge resistance", |ui| { + if ui + .add(Select::new("tf-deskflow-resistance", &mut idx, &RESISTANCE_LABELS)) + .changed() + && let Some(&r) = RESISTANCES.get(idx) + { + event = Some(DeskflowEvent::Resistance(r)); + } + }); + for line in deskflowtab::pending(tab) { + if let Some(e) = pending_row(ui, t, tab, mon, line) { + event = Some(e); + } + } + for d in deskflowtab::band_devices(tab, mon.layout(), mon.heads()) { + if let Some(e) = device_rows(ui, t, tab, mon, d) { + event = Some(e); + } + } + if let Some(e) = &tab.error { + warn(ui, t, e); + } + }); + event +} + +/// A device that wants to attach: its name, its fingerprint, and Attach… +/// and Reject, or the Position control after Attach…. +fn pending_row(ui: &mut Ui, t: &Theme, tab: &DeskflowTab, mon: &MonTab, line: &DevLine) -> Option { + let mut event = None; + ui.add_space(BLOCK_GAP); + let name = &line.name; + if line.flags.iter().any(|f| f == FP_CHANGED) { + warn( + ui, + t, + &format!("{name} has a new fingerprint. Attach it again only if you expect this."), + ); + } else { + ui.label(RichText::new(format!("{name} wants to attach")).color(t.palette().foreground)); + } + let attaching = tab + .attaching + .as_ref() + .is_some_and(|(n, f)| n == name && *f == line.fingerprint); + fingerprint(ui, t, &line.fingerprint, |ui| { + if attaching { + if let Some((output, side)) = position(ui, t, tab, mon, name, None) { + event = Some(DeskflowEvent::Place { + name: name.clone(), + output, + side, + }); + } + if ui + .add(Button::new("Cancel").variant(ButtonVariant::Secondary)) + .clicked() + { + event = Some(DeskflowEvent::CancelAttach); + } + return; + } + ui.horizontal(|ui| { + if ui.add(Button::new("Attach…")).clicked() { + event = Some(DeskflowEvent::Attach { + name: name.clone(), + fp: line.fingerprint.clone(), + }); + } + if ui + .add(Button::new("Reject").variant(ButtonVariant::Secondary)) + .clicked() + { + event = Some(DeskflowEvent::Reject { + name: name.clone(), + fp: line.fingerprint.clone(), + }); + } + }); + }); + event +} + +/// An attached device: Position and Forget, with the note when its edge is +/// not free. +fn device_rows(ui: &mut Ui, t: &Theme, tab: &DeskflowTab, mon: &MonTab, d: &DeviceCfg) -> Option { + let mut event = None; + ui.add_space(BLOCK_GAP); + ui.label(RichText::new(&d.name).color(t.palette().foreground)); + if let Some((output, side)) = position(ui, t, tab, mon, &d.name, Some(d)) { + event = Some(DeskflowEvent::Place { + name: d.name.clone(), + output, + side, + }); + } + let inactive = mon + .layout() + .is_none_or(|l| deskflowtab::inactive(l, mon.heads(), &tab.cfg.devices, d)); + if inactive { + warn(ui, t, NOT_FREE); + } + let mut share = d.clipboard; + ui.horizontal(|ui| { + if ui.add(Switch::new(&mut share)).changed() { + event = Some(DeskflowEvent::Clipboard { + name: d.name.clone(), + on: share, + }); + } + ui.label(RichText::new(CLIPBOARD_TEXT).color(t.palette().foreground)); + }); + if ui + .add(Button::new("Forget").variant(ButtonVariant::Secondary)) + .clicked() + { + event = Some(DeskflowEvent::Forget { name: d.name.clone() }); + } + event +} + +/// The Position control: one select of the free edges ("Right of DP-1"). +/// `current` is an attached device, whose own edge shows even when it is +/// not free. The edge chosen, by criteria. +fn position( + ui: &mut Ui, + t: &Theme, + tab: &DeskflowTab, + mon: &MonTab, + name: &str, + current: Option<&DeviceCfg>, +) -> Option<(String, Side)> { + let free = mon.layout().map_or(Vec::new(), |l| { + deskflowtab::position_edges(l, mon.heads(), &tab.cfg.devices, name) + }); + if free.is_empty() && current.is_none() { + muted(ui, t, NO_FREE_EDGE); + return None; + } + let monitor = |c: &str| mon.head(c).map_or(c.to_string(), |h| h.name.clone()); + let labels: Vec = free + .iter() + .map(|(c, s)| deskflowtab::edge_label(*s, &monitor(c))) + .collect(); + let refs: Vec<&str> = labels.iter().map(String::as_str).collect(); + let mut idx = current + .and_then(|d| free.iter().position(|(c, s)| *c == d.output && *s == d.side)) + .unwrap_or(usize::MAX); + let placeholder = current.map_or(String::new(), |d| deskflowtab::edge_label(d.side, &monitor(&d.output))); + let id = format!("tf-deskflow-position-{name}"); + let changed = form_row(ui, t, "Position", |ui| { + ui.add_enabled( + !free.is_empty(), + Select::new(&id, &mut idx, &refs).placeholder(placeholder), + ) + .changed() + }); + if changed { free.get(idx).cloned() } else { None } +} + +/// A fingerprint as Deskflow shows it: the random-art picture, and beside +/// it the colon hex and what `beside` adds. +fn fingerprint(ui: &mut Ui, t: &Theme, fp: &str, beside: impl FnOnce(&mut Ui)) { + let mono = FontId::monospace(brand::ROW_STATUS_PT); + ui.horizontal_top(|ui| { + ui.label( + RichText::new(ident::random_art(fp).join("\n")) + .font(mono.clone()) + .color(t.palette().foreground), + ); + ui.add_space(ART_GAP); + ui.vertical(|ui| { + let hex = ident::colon_hex(fp); + let pairs: Vec<&str> = hex.split(':').collect(); + let lines: Vec = pairs.chunks(HEX_BYTES_PER_LINE).map(|c| c.join(":")).collect(); + ui.label( + RichText::new(lines.join("\n")) + .font(mono) + .color(t.palette().muted_foreground), + ); + beside(ui); + }); + }); +} + +fn muted(ui: &mut Ui, t: &Theme, text: &str) { + ui.label(RichText::new(text).color(t.palette().muted_foreground)); +} + +fn warn(ui: &mut Ui, t: &Theme, text: &str) { + ui.label(RichText::new(text).color(t.role(role::WARN))); +} + +/// A form row: the label in its column, then what `add` draws. +fn form_row(ui: &mut Ui, t: &Theme, label: &str, add: impl FnOnce(&mut Ui) -> R) -> R { + ui.horizontal(|ui| { + ui.scope(|ui| { + ui.set_min_width(brand::FORM_LABEL_W); + ui.set_max_width(brand::FORM_LABEL_W); + ui.label(RichText::new(label).color(t.palette().foreground)); + }); + add(ui) + }) + .inner +} diff --git a/src/thinfloe-menu/src/deskflowcfg.rs b/src/thinfloe-menu/src/deskflowcfg.rs new file mode 100644 index 0000000..2c0942a --- /dev/null +++ b/src/thinfloe-menu/src/deskflowcfg.rs @@ -0,0 +1,268 @@ +//! The `[deskflow]` table of config.toml and the body of +//! `generated/deskflow`, which the Deskflow daemon reads instead of +//! config.toml. The generated file holds the same TOML table and +//! `mic_mute_local`, which the Keyboard tab's volume key switch decides. + +use std::collections::HashSet; + +use serde::de::Error as _; +use serde::{Deserialize, Deserializer, Serialize, Serializer}; + +use crate::config::DeskflowCfg; +use crate::kanshi::Side; + +/// The default port of Deskflow servers. +pub const DEFAULT_PORT: u16 = 24800; + +/// How far the pointer has to push against an edge before it crosses. +#[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq, Default)] +#[serde(rename_all = "lowercase")] +pub enum Resistance { + Off, + Low, + #[default] + Medium, + High, +} + +impl Resistance { + /// The push in pixels. + pub fn px(self) -> f64 { + match self { + Resistance::Off => 0.0, + Resistance::Low => 15.0, + Resistance::Medium => 40.0, + Resistance::High => 100.0, + } + } +} + +// A side is written with the words of the monitor profiles. +impl Serialize for Side { + fn serialize(&self, s: S) -> Result { + s.serialize_str(self.word()) + } +} + +impl<'de> Deserialize<'de> for Side { + fn deserialize>(d: D) -> Result { + let w = String::deserialize(d)?; + Side::from_word(&w).ok_or_else(|| D::Error::custom(format!("not a side: {w}"))) + } +} + +const MAX_NAME_BYTES: usize = 64; +const FINGERPRINT_PREFIX: &str = "v2:sha256:"; + +fn fingerprint_ok(f: &str) -> bool { + f.strip_prefix(FINGERPRINT_PREFIX) + .is_some_and(|h| h.len() == 64 && h.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f'))) +} + +/// Refuses what the daemon could not use: a fingerprint that is not +/// `v2:sha256:` and 64 lower-case hex digits, a name of 0 or more than 64 +/// bytes, a name twice, two devices at one edge of one output, port 0. +pub fn validate(cfg: &DeskflowCfg) -> Result<(), String> { + if cfg.port == 0 { + return Err("Deskflow: the port must not be 0".into()); + } + let mut names = HashSet::new(); + let mut edges = HashSet::new(); + for d in &cfg.devices { + if d.name.is_empty() || d.name.len() > MAX_NAME_BYTES { + return Err(format!("Deskflow: a device name must have 1 to {MAX_NAME_BYTES} bytes")); + } + if !fingerprint_ok(&d.fingerprint) { + return Err(format!( + "Deskflow: the fingerprint of {} is not v2:sha256:<64 hex digits>", + d.name + )); + } + if !names.insert(d.name.as_str()) { + return Err(format!("Deskflow: the name {} is used twice", d.name)); + } + if !edges.insert((d.output.as_str(), d.side.word())) { + return Err(format!("Deskflow: two devices are {} {}", d.side.word(), d.output)); + } + } + Ok(()) +} + +/// What generated/deskflow holds. +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, Default)] +#[serde(default)] +pub struct Generated { + /// The microphone mute key mutes ThinFloe while a device has the + /// keyboard: the volume key switch is on, and labwc's binding cannot + /// act then. Not part of `[deskflow]`. + pub mic_mute_local: bool, + pub deskflow: DeskflowCfg, +} + +/// The TOML text of the file (no generated header). +pub fn render(cfg: &DeskflowCfg, mic_mute_local: bool) -> String { + #[derive(Serialize)] + struct Wrap<'a> { + mic_mute_local: bool, + deskflow: &'a DeskflowCfg, + } + toml::to_string(&Wrap { + mic_mute_local, + deskflow: cfg, + }) + .expect("the Deskflow table serialises to TOML") +} + +/// Reads what `render` wrote (a generated header line is a comment); a +/// file without `mic_mute_local` reads as false. +pub fn parse(text: &str) -> Result { + toml::from_str::(text).map_err(|e| format!("generated/deskflow: {}", e.message())) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::config::DeviceCfg; + + const FP: &str = "v2:sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"; + + fn dev(name: &str, output: &str, side: Side) -> DeviceCfg { + DeviceCfg { + name: name.into(), + fingerprint: FP.into(), + output: output.into(), + side, + clipboard: true, + } + } + + fn sample() -> DeskflowCfg { + DeskflowCfg { + listen: true, + port: 24801, + edge_resistance: Resistance::High, + devices: vec![dev("laptop", "DP-1", Side::RightOf), dev("pad", "DP-1", Side::Below)], + } + } + + #[test] + fn default_is_off() { + let c = DeskflowCfg::default(); + assert!(!c.listen); + assert_eq!(c.port, 24800); + assert_eq!(c.edge_resistance, Resistance::Medium); + assert!(c.devices.is_empty()); + } + + #[test] + fn resistance_pixels() { + let px: Vec = [Resistance::Off, Resistance::Low, Resistance::Medium, Resistance::High] + .iter() + .map(|r| r.px()) + .collect(); + assert_eq!(px, [0.0, 15.0, 40.0, 100.0]); + } + + #[test] + fn toml_roundtrip_matches_spec_block() { + let text = "[deskflow]\nlisten = true\nport = 24800\n\n[[deskflow.device]]\nname = \"laptop\"\nfingerprint = \"v2:sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef\"\noutput = \"DP-1\"\nside = \"right-of\"\nclipboard = true\n"; + let c = crate::config::parse(text).unwrap(); + assert!(c.deskflow.listen); + assert_eq!(c.deskflow.edge_resistance, Resistance::Medium); + assert_eq!(c.deskflow.devices, vec![dev("laptop", "DP-1", Side::RightOf)]); + let again = crate::config::parse(&crate::config::to_text(&c)).unwrap(); + assert_eq!(again, c); + // A device without `clipboard` shares it. + let c = crate::config::parse( + "[[deskflow.device]]\nname = \"a\"\nfingerprint = \"x\"\noutput = \"o\"\nside = \"above\"\n", + ) + .unwrap(); + assert!(c.deskflow.devices[0].clipboard); + assert!( + crate::config::parse("[[deskflow.device]]\nname=\"a\"\nfingerprint=\"x\"\noutput=\"o\"\nside=\"up\"\n") + .is_err() + ); + } + + #[test] + fn render_parse_roundtrip() { + let c = sample(); + let body = render(&c, true); + assert!( + body.starts_with("mic_mute_local = true\n") + && body.contains("[[deskflow.device]]") + && body.contains("side = \"right-of\""), + "{body}" + ); + let g = Generated { + mic_mute_local: true, + deskflow: c.clone(), + }; + assert_eq!(parse(&body).unwrap(), g); + let with_header = format!("{}\n{body}", crate::generated::HEADER); + assert_eq!(parse(&with_header).unwrap(), g); + assert_eq!( + parse(&render(&DeskflowCfg::default(), false)).unwrap(), + Generated::default() + ); + // A file written before the key: the microphone key is not local. + let old = body.replacen("mic_mute_local = true\n", "", 1); + assert_eq!(parse(&old).unwrap().deskflow, c); + assert!(!parse(&old).unwrap().mic_mute_local); + } + + #[test] + fn validate_accepts_a_good_config() { + assert_eq!(validate(&sample()), Ok(())); + assert_eq!(validate(&DeskflowCfg::default()), Ok(())); + } + + #[test] + fn validate_refuses_bad_fingerprint() { + for bad in [ + "", + "v2:sha256:abc", + &FP.to_uppercase(), + &FP.replace("v2:", "v1:"), + &format!("{FP}0"), + ] { + let mut c = sample(); + c.devices[0].fingerprint = bad.into(); + assert!(validate(&c).unwrap_err().contains("fingerprint"), "{bad}"); + } + } + + #[test] + fn validate_refuses_duplicate_edge() { + let mut c = sample(); + c.devices[1] = dev("pad", "DP-1", Side::RightOf); + assert!(validate(&c).is_err()); + c.devices[1] = dev("pad", "DP-2", Side::RightOf); + assert!(validate(&c).is_ok()); + } + + #[test] + fn validate_refuses_duplicate_name() { + let mut c = sample(); + c.devices[1].name = "laptop".into(); + assert!(validate(&c).unwrap_err().contains("twice")); + } + + #[test] + fn validate_refuses_bad_name_and_port() { + let mut c = sample(); + c.devices[0].name = String::new(); + assert!(validate(&c).is_err()); + c.devices[0].name = "x".repeat(65); + assert!(validate(&c).is_err()); + c.devices[0].name = "x".repeat(64); + assert!(validate(&c).is_ok()); + c.port = 0; + assert!(validate(&c).is_err()); + } + + #[test] + fn generated_mode_0600() { + assert_eq!(crate::generated::mode_of("deskflow"), 0o600); + } +} diff --git a/src/thinfloe-menu/src/deskflowtab.rs b/src/thinfloe-menu/src/deskflowtab.rs new file mode 100644 index 0000000..b581206 --- /dev/null +++ b/src/thinfloe-menu/src/deskflowtab.rs @@ -0,0 +1,778 @@ +//! The Deskflow band of the Screen tab: the `[deskflow]` settings as the +//! menu shows them, the daemon's state file, and what a click on the band +//! or on a device in the monitor arrangement asks for. Drawing is in +//! deskflow_ui.rs. + +use crate::config::{DeskflowCfg, DeviceCfg}; +use crate::deskflow::cmd::Cmd; +use crate::deskflow::edge::{self, Rect}; +use crate::deskflow::statefile::{self, DevLine, DevState, Head as StateHead, StateFile}; +use crate::deskflowcfg::Resistance; +use crate::heads::Head; +use crate::kanshi::{self, Profile, Side}; + +/// The edges in the order the Position control lists them. +pub const SIDES: [Side; 4] = [Side::LeftOf, Side::RightOf, Side::Above, Side::Below]; +/// The size a device is drawn at before it reported one: 16:9. +pub const DEFAULT_DEVICE: (u32, u32) = (1920, 1080); +/// The size of a monitor that reports no mode, as the arrangement draws it. +const NO_MODE: (i32, i32) = (1920, 1080); +/// The flag of a pending line whose name is known with another fingerprint. +pub const FP_CHANGED: &str = "fp-changed"; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct DeskflowTab { + pub cfg: DeskflowCfg, + pub state: StateFile, + /// The pending device (name, fingerprint) whose Position control is open. + pub attaching: Option<(String, String)>, + /// Why the last write or command failed. + pub error: Option, + /// The attached device selected in the arrangement, by name. + pub selected: Option, + /// The daemon runs; set by the app before each frame. + pub running: bool, + /// Why the daemon stopped the last time it failed; set by the app. + pub stopped: Option, +} + +impl Default for DeskflowTab { + fn default() -> DeskflowTab { + from_config(&DeskflowCfg::default()) + } +} + +/// The tab for the settings in `config.toml`; no state file read yet. +pub fn from_config(cfg: &DeskflowCfg) -> DeskflowTab { + DeskflowTab { + cfg: cfg.clone(), + state: no_state(), + attaching: None, + error: None, + selected: None, + running: false, + stopped: None, + } +} + +/// What the menu shows while there is no state file. +pub fn no_state() -> StateFile { + StateFile { + head: StateHead::Error(String::new()), + devices: Vec::new(), + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum DeskflowEvent { + Listen(bool), + Resistance(Resistance), + /// *Attach…* on a pending device: its Position control opens. + Attach { + name: String, + fp: String, + }, + /// An edge chosen in a Position control: for the device being attached, + /// or to move an attached one. + Place { + name: String, + output: String, + side: Side, + }, + Reject { + name: String, + fp: String, + }, + Forget { + name: String, + }, + /// The clipboard switch of an attached device. + Clipboard { + name: String, + on: bool, + }, + CancelAttach, + /// A device box clicked in the arrangement. + Select(String), +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum DeskflowRequest { + /// Keep this `[deskflow]` table, then tell the daemon. + Save(DeskflowCfg), + /// Send this to the daemon's socket. + Send(Cmd), +} + +/// Carry out `ev` on the tab; what the menu has to do then. +pub fn apply(tab: &mut DeskflowTab, ev: DeskflowEvent) -> Option { + let save = |tab: &mut DeskflowTab| Some(DeskflowRequest::Save(tab.cfg.clone())); + match ev { + DeskflowEvent::Listen(on) => { + if tab.cfg.listen == on { + return None; + } + tab.cfg.listen = on; + save(tab) + } + DeskflowEvent::Resistance(r) => { + if tab.cfg.edge_resistance == r { + return None; + } + tab.cfg.edge_resistance = r; + save(tab) + } + DeskflowEvent::Attach { name, fp } => { + tab.attaching = Some((name, fp)); + None + } + DeskflowEvent::CancelAttach => { + tab.attaching = None; + None + } + DeskflowEvent::Select(name) => { + tab.selected = Some(name); + None + } + DeskflowEvent::Place { name, output, side } => { + // The fingerprint of a device being attached is the one of its + // pending line; an attached device keeps its own. + if let Some((_, fp)) = tab.attaching.take_if(|(n, _)| *n == name) { + let clipboard = tab + .cfg + .devices + .iter() + .find(|d| d.name == name) + .is_none_or(|d| d.clipboard); + tab.cfg.devices.retain(|d| d.name != name); + tab.cfg.devices.push(DeviceCfg { + name, + fingerprint: fp, + output, + side, + clipboard, + }); + return save(tab); + } + let d = tab.cfg.devices.iter_mut().find(|d| d.name == name)?; + if d.output == output && d.side == side { + return None; + } + d.output = output; + d.side = side; + save(tab) + } + DeskflowEvent::Reject { name, fp } => { + if tab.attaching.as_ref().is_some_and(|(n, f)| *n == name && *f == fp) { + tab.attaching = None; + } + Some(DeskflowRequest::Send(Cmd::Reject { name, fingerprint: fp })) + } + DeskflowEvent::Clipboard { name, on } => { + let d = tab.cfg.devices.iter_mut().find(|d| d.name == name)?; + if d.clipboard == on { + return None; + } + d.clipboard = on; + save(tab) + } + DeskflowEvent::Forget { name } => { + let before = tab.cfg.devices.len(); + tab.cfg.devices.retain(|d| d.name != name); + if tab.selected.as_deref() == Some(name.as_str()) { + tab.selected = None; + } + if tab.cfg.devices.len() == before { + return None; + } + save(tab) + } + } +} + +/// The pending lines of the state file, in its order, while the daemon +/// runs: a file left from an earlier run lists devices that can be neither +/// attached nor rejected. +pub fn pending(tab: &DeskflowTab) -> Vec<&DevLine> { + if !tab.running { + return Vec::new(); + } + tab.state + .devices + .iter() + .filter(|d| d.state == DevState::Pending) + .collect() +} + +/// The state file's line of an attached device: same name and fingerprint. +pub fn line_of<'a>(state: &'a StateFile, dev: &DeviceCfg) -> Option<&'a DevLine> { + state + .devices + .iter() + .find(|l| l.name == dev.name && l.fingerprint == dev.fingerprint && l.state != DevState::Pending) +} + +/// Connected, active or offline: an attached device the daemon does not +/// report (or a daemon that does not run) is offline. +pub fn device_state(tab: &DeskflowTab, dev: &DeviceCfg) -> DevState { + match line_of(&tab.state, dev).map(|l| l.state) { + Some(s @ (DevState::Connected | DevState::Active)) if tab.running => s, + _ => DevState::Offline, + } +} + +/// The size the device reported, else `DEFAULT_DEVICE`. +pub fn device_size(state: &StateFile, dev: &DeviceCfg) -> (u32, u32) { + line_of(state, dev) + .map(|l| (l.width, l.height)) + .filter(|&(w, h)| w > 0 && h > 0) + .unwrap_or(DEFAULT_DEVICE) +} + +/// The size of `o` on the desktop: its mode, else the head's current or +/// preferred mode, else `NO_MODE`. +fn output_size(o: &kanshi::OutputSet, heads: &[Head]) -> (i32, i32) { + if o.mode.w > 0 && o.mode.h > 0 { + return kanshi::size(o); + } + heads + .iter() + .find(|h| kanshi::criteria(h, heads) == o.criteria) + .and_then(|h| { + h.current + .and_then(|i| h.modes.get(i)) + .or_else(|| h.modes.iter().find(|m| m.preferred)) + .or_else(|| h.modes.first()) + }) + .map_or(NO_MODE, |m| (m.w as i32, m.h as i32)) +} + +/// The monitors that are on, by criteria, where `profile` puts them. +pub fn output_rects(profile: &Profile, heads: &[Head]) -> Vec<(String, Rect)> { + let Ok(placed) = kanshi::place_all(profile) else { + return Vec::new(); + }; + profile + .outputs + .iter() + .zip(placed) + .filter_map(|(o, p)| { + let (x, y) = p?; + let (w, h) = output_size(o, heads); + Some((o.criteria.clone(), Rect { x, y, w, h })) + }) + .collect() +} + +/// The edges of the monitors that are on in `profile` that no other +/// monitor touches and no device in `devices` holds, the device named +/// `except` left out: what the Position control offers. +pub fn free_edges( + profile: &Profile, + heads: &[Head], + devices: &[DeviceCfg], + except: Option<&str>, +) -> Vec<(String, Side)> { + let rects = output_rects(profile, heads); + let taken = |c: &str, s: Side| { + devices + .iter() + .any(|d| Some(d.name.as_str()) != except && d.output == c && d.side == s) + }; + let mut free = Vec::new(); + for (i, (criteria, r)) in rects.iter().enumerate() { + let others: Vec = rects + .iter() + .enumerate() + .filter(|&(j, _)| j != i) + .map(|(_, (_, o))| *o) + .collect(); + for side in SIDES { + if edge::edge_free(*r, side, &others) && !taken(criteria, side) { + free.push((criteria.clone(), side)); + } + } + } + free +} + +/// The edges the Position control of the device `name` offers: the free +/// ones and the edge a device of that name holds, so a device attached +/// again under a new fingerprint can keep its edge. +pub fn position_edges(profile: &Profile, heads: &[Head], devices: &[DeviceCfg], name: &str) -> Vec<(String, Side)> { + free_edges(profile, heads, devices, Some(name)) +} + +/// The edge of `dev` is not free in `profile` (its monitor missing or +/// off, or another monitor at that edge): it gets no strip. +pub fn inactive(profile: &Profile, heads: &[Head], devices: &[DeviceCfg], dev: &DeviceCfg) -> bool { + !free_edges(profile, heads, devices, Some(&dev.name)) + .iter() + .any(|(c, s)| *c == dev.output && *s == dev.side) +} + +/// The attached devices the band lists with their rows: the selected +/// one, and those the arrangement does not show at their edge (their +/// monitor off or missing, or the edge not free), so they can be moved +/// or forgotten. +pub fn band_devices<'a>(tab: &'a DeskflowTab, profile: Option<&Profile>, heads: &[Head]) -> Vec<&'a DeviceCfg> { + let shown = |d: &DeviceCfg| { + profile.is_some_and(|p| { + p.outputs.iter().any(|o| o.enabled && o.criteria == d.output) && !inactive(p, heads, &tab.cfg.devices, d) + }) + }; + tab.cfg + .devices + .iter() + .filter(|d| tab.selected.as_deref() == Some(d.name.as_str()) || !shown(d)) + .collect() +} + +/// "Deskflow stopped: " while the daemon does not run and its last +/// run failed. +pub fn stopped_line(tab: &DeskflowTab) -> Option { + if tab.running { + return None; + } + tab.stopped.as_ref().map(|why| format!("Deskflow stopped: {why}")) +} + +/// "Right of DP-1". +pub fn edge_label(side: Side, monitor: &str) -> String { + let word = match side { + Side::LeftOf => "Left of", + Side::RightOf => "Right of", + Side::Above => "Above", + Side::Below => "Below", + }; + format!("{word} {monitor}") +} + +/// "This computer: :" from the state file's head while the +/// daemon runs. A wildcard listen address shows `ipv4`, the machine's +/// address, when it is known. +pub fn self_line(tab: &DeskflowTab, ipv4: Option) -> Option { + let StateHead::SelfInfo { listen, .. } = &tab.state.head else { + return None; + }; + if !tab.running { + return None; + } + let (host, port) = listen.rsplit_once(':')?; + let wildcard = matches!(host, "" | "0.0.0.0" | "::" | "[::]"); + let host = match (wildcard, ipv4) { + (true, Some(ip)) => ip.to_string(), + _ => host.to_string(), + }; + Some(format!("This computer: {host}:{port}")) +} + +/// ThinFloe's own fingerprint from the state file's head. +pub fn self_fingerprint(tab: &DeskflowTab) -> Option<&str> { + match &tab.state.head { + StateHead::SelfInfo { fingerprint, .. } if tab.running && !fingerprint.is_empty() => Some(fingerprint), + _ => None, + } +} + +/// The state file at `path`; no file, or one that cannot be read, is no +/// state. +pub fn read_state(path: &std::path::Path) -> StateFile { + /// Eight pending lines and a few devices fit many times over. + const MAX_BYTES: u64 = 64 * 1024; + crate::bounded::read_text(path, MAX_BYTES).map_or_else(no_state, |t| statefile::parse(&t)) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::heads::{Mode, Rotation}; + use crate::kanshi::{OutputSet, Place}; + + const FP_A: &str = "v2:sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; + const FP_B: &str = "v2:sha256:bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"; + + fn line(name: &str, fp: &str, state: DevState) -> DevLine { + DevLine { + name: name.into(), + fingerprint: fp.into(), + state, + since: 1, + width: 0, + height: 0, + flags: vec![], + } + } + + fn device(name: &str, fp: &str, output: &str, side: Side) -> DeviceCfg { + DeviceCfg { + name: name.into(), + fingerprint: fp.into(), + output: output.into(), + side, + clipboard: true, + } + } + + fn out(criteria: &str, place: Place) -> OutputSet { + OutputSet { + criteria: criteria.into(), + enabled: true, + mode: Mode { + w: 1920, + h: 1080, + refresh_mhz: 60_000, + preferred: true, + }, + rotation: Rotation::Normal, + place, + } + } + + /// DP-1 with DP-2 to its right. + fn two() -> Profile { + Profile { + outputs: vec![ + out("DP-1", Place::Origin), + out( + "DP-2", + Place::Next { + to: "DP-1".into(), + side: Side::RightOf, + }, + ), + ], + menu_output: None, + } + } + + fn with_pending() -> DeskflowTab { + let mut tab = DeskflowTab::default(); + tab.state.devices = vec![line("laptop", FP_A, DevState::Pending)]; + tab + } + + #[test] + fn attach_then_place_saves_device() { + let mut tab = with_pending(); + let r = apply( + &mut tab, + DeskflowEvent::Attach { + name: "laptop".into(), + fp: FP_A.into(), + }, + ); + assert_eq!(r, None, "Attach only opens the Position control"); + assert_eq!(tab.attaching, Some(("laptop".into(), FP_A.into()))); + let r = apply( + &mut tab, + DeskflowEvent::Place { + name: "laptop".into(), + output: "DP-2".into(), + side: Side::RightOf, + }, + ); + let want = device("laptop", FP_A, "DP-2", Side::RightOf); + let Some(DeskflowRequest::Save(cfg)) = r else { + panic!("no save: {r:?}"); + }; + assert_eq!(cfg.devices, vec![want.clone()]); + assert_eq!(tab.cfg.devices, vec![want]); + assert_eq!(tab.attaching, None); + } + + #[test] + fn attach_again_with_a_new_fingerprint_replaces_the_device() { + let mut tab = with_pending(); + tab.cfg.devices = vec![device("laptop", FP_B, "DP-1", Side::LeftOf)]; + apply( + &mut tab, + DeskflowEvent::Attach { + name: "laptop".into(), + fp: FP_A.into(), + }, + ); + apply( + &mut tab, + DeskflowEvent::Place { + name: "laptop".into(), + output: "DP-2".into(), + side: Side::RightOf, + }, + ); + assert_eq!(tab.cfg.devices, vec![device("laptop", FP_A, "DP-2", Side::RightOf)]); + } + + #[test] + fn place_moves_an_attached_device() { + let mut tab = DeskflowTab::default(); + tab.cfg.devices = vec![device("laptop", FP_A, "DP-1", Side::LeftOf)]; + let r = apply( + &mut tab, + DeskflowEvent::Place { + name: "laptop".into(), + output: "DP-2".into(), + side: Side::Below, + }, + ); + assert!(matches!(r, Some(DeskflowRequest::Save(_)))); + assert_eq!(tab.cfg.devices, vec![device("laptop", FP_A, "DP-2", Side::Below)]); + // A name neither attaching nor attached changes nothing. + let r = apply( + &mut tab, + DeskflowEvent::Place { + name: "other".into(), + output: "DP-2".into(), + side: Side::Above, + }, + ); + assert_eq!(r, None); + } + + #[test] + fn reject_sends_cmd() { + let mut tab = with_pending(); + tab.attaching = Some(("laptop".into(), FP_A.into())); + let r = apply( + &mut tab, + DeskflowEvent::Reject { + name: "laptop".into(), + fp: FP_A.into(), + }, + ); + assert_eq!( + r, + Some(DeskflowRequest::Send(Cmd::Reject { + name: "laptop".into(), + fingerprint: FP_A.into(), + })) + ); + assert_eq!(tab.attaching, None, "a rejected device's Position control closes"); + assert!(tab.cfg.devices.is_empty()); + } + + #[test] + fn clipboard_switch_writes_device() { + let mut tab = DeskflowTab::default(); + tab.cfg.devices = vec![ + device("laptop", FP_A, "DP-1", Side::LeftOf), + device("mac", FP_B, "DP-2", Side::RightOf), + ]; + let r = apply( + &mut tab, + DeskflowEvent::Clipboard { + name: "laptop".into(), + on: false, + }, + ); + let Some(DeskflowRequest::Save(cfg)) = r else { + panic!("no save: {r:?}"); + }; + assert!(!cfg.devices[0].clipboard); + assert!(cfg.devices[1].clipboard, "only the named device changes"); + let again = DeskflowEvent::Clipboard { + name: "laptop".into(), + on: false, + }; + assert_eq!(apply(&mut tab, again), None); + } + + #[test] + fn forget_removes() { + let mut tab = DeskflowTab::default(); + tab.cfg.devices = vec![ + device("laptop", FP_A, "DP-1", Side::LeftOf), + device("mac", FP_B, "DP-2", Side::RightOf), + ]; + tab.selected = Some("laptop".into()); + let r = apply(&mut tab, DeskflowEvent::Forget { name: "laptop".into() }); + let Some(DeskflowRequest::Save(cfg)) = r else { + panic!("no save: {r:?}"); + }; + assert_eq!(cfg.devices, vec![device("mac", FP_B, "DP-2", Side::RightOf)]); + assert_eq!(tab.selected, None); + assert_eq!(apply(&mut tab, DeskflowEvent::Forget { name: "laptop".into() }), None); + } + + #[test] + fn free_edges_excludes_shared_and_taken() { + let p = two(); + let all = free_edges(&p, &[], &[], None); + // DP-1's right edge and DP-2's left edge touch each other. + assert_eq!( + all, + vec![ + ("DP-1".to_string(), Side::LeftOf), + ("DP-1".to_string(), Side::Above), + ("DP-1".to_string(), Side::Below), + ("DP-2".to_string(), Side::RightOf), + ("DP-2".to_string(), Side::Above), + ("DP-2".to_string(), Side::Below), + ] + ); + let devs = [device("laptop", FP_A, "DP-2", Side::RightOf)]; + let free = free_edges(&p, &[], &devs, None); + assert!(!free.contains(&("DP-2".to_string(), Side::RightOf)), "taken by laptop"); + assert_eq!(free.len(), 5); + // The device itself may keep its edge. + assert!(free_edges(&p, &[], &devs, Some("laptop")).contains(&("DP-2".to_string(), Side::RightOf))); + // A monitor that is off has no edges. + let mut off = two(); + off.outputs[1].enabled = false; + assert_eq!(free_edges(&off, &[], &[], None).len(), 4); + } + + #[test] + fn the_band_lists_a_device_whose_edge_another_monitor_took() { + let mut tab = DeskflowTab::default(); + tab.cfg.devices = vec![ + device("laptop", FP_A, "DP-1", Side::RightOf), + device("mac", FP_B, "DP-2", Side::RightOf), + ]; + let names = |tab: &DeskflowTab, p: Option<&Profile>| { + band_devices(tab, p, &[]) + .iter() + .map(|d| d.name.clone()) + .collect::>() + }; + // DP-2 docked right of DP-1 takes the laptop's edge. + assert_eq!(names(&tab, Some(&two())), vec!["laptop".to_string()]); + // The selected device is listed too. + tab.selected = Some("mac".into()); + assert_eq!(names(&tab, Some(&two())), vec!["laptop".to_string(), "mac".to_string()]); + tab.selected = None; + // DP-1 alone: the laptop's edge is free, DP-2 is missing. + let mut one = two(); + one.outputs.truncate(1); + assert_eq!(names(&tab, Some(&one)), vec!["mac".to_string()]); + // No arrangement: every device is listed. + assert_eq!(names(&tab, None).len(), 2); + } + + #[test] + fn the_stopped_line_shows_only_while_the_daemon_does_not_run() { + let mut tab = DeskflowTab { + stopped: Some("port 24800 is in use".into()), + running: false, + ..DeskflowTab::default() + }; + assert_eq!( + stopped_line(&tab).as_deref(), + Some("Deskflow stopped: port 24800 is in use") + ); + tab.running = true; + assert_eq!(stopped_line(&tab), None); + tab.running = false; + tab.stopped = None; + assert_eq!(stopped_line(&tab), None); + } + + #[test] + fn inactive_when_the_edge_is_shared_or_the_monitor_missing() { + let p = two(); + let at = |o: &str, s| device("laptop", FP_A, o, s); + assert!(!inactive(&p, &[], &[], &at("DP-2", Side::RightOf))); + assert!(inactive(&p, &[], &[], &at("DP-1", Side::RightOf))); + assert!(inactive(&p, &[], &[], &at("HDMI-1", Side::RightOf))); + } + + #[test] + fn listen_toggle_saves() { + let mut tab = DeskflowTab::default(); + let r = apply(&mut tab, DeskflowEvent::Listen(true)); + let Some(DeskflowRequest::Save(cfg)) = r else { + panic!("no save: {r:?}"); + }; + assert!(cfg.listen); + assert!(tab.cfg.listen); + assert_eq!( + apply(&mut tab, DeskflowEvent::Listen(true)), + None, + "no change, no write" + ); + let r = apply(&mut tab, DeskflowEvent::Resistance(Resistance::High)); + assert!(matches!(r, Some(DeskflowRequest::Save(c)) if c.edge_resistance == Resistance::High)); + } + + #[test] + fn select_and_cancel_change_only_the_tab() { + let mut tab = with_pending(); + tab.cfg.devices = vec![device("mac", FP_B, "DP-1", Side::LeftOf)]; + assert_eq!(apply(&mut tab, DeskflowEvent::Select("mac".into())), None); + assert_eq!(tab.selected.as_deref(), Some("mac")); + apply( + &mut tab, + DeskflowEvent::Attach { + name: "laptop".into(), + fp: FP_A.into(), + }, + ); + assert_eq!(apply(&mut tab, DeskflowEvent::CancelAttach), None); + assert_eq!(tab.attaching, None); + } + + #[test] + fn device_state_and_size_come_from_the_line_of_that_fingerprint() { + let mut tab = DeskflowTab::default(); + let d = device("laptop", FP_A, "DP-1", Side::LeftOf); + let mut l = line("laptop", FP_A, DevState::Active); + l.width = 2560; + l.height = 1600; + tab.state.devices = vec![l, line("laptop", FP_B, DevState::Pending)]; + assert_eq!(device_state(&tab, &d), DevState::Offline, "no daemon runs"); + tab.running = true; + assert_eq!(device_state(&tab, &d), DevState::Active); + assert_eq!(device_size(&tab.state, &d), (2560, 1600)); + let other = device("laptop", FP_B, "DP-1", Side::LeftOf); + assert_eq!( + device_state(&tab, &other), + DevState::Offline, + "a pending line is not its state" + ); + assert_eq!(device_size(&tab.state, &other), DEFAULT_DEVICE); + } + + #[test] + fn self_line_shows_the_machine_address_for_a_wildcard() { + let mut tab = DeskflowTab::default(); + tab.state.head = StateHead::SelfInfo { + fingerprint: FP_A.into(), + listen: "0.0.0.0:24800".into(), + }; + assert_eq!(self_line(&tab, None), None, "nothing while the daemon does not run"); + tab.running = true; + let ip = Some(std::net::Ipv4Addr::new(192, 168, 1, 23)); + assert_eq!( + self_line(&tab, ip).as_deref(), + Some("This computer: 192.168.1.23:24800") + ); + assert_eq!(self_line(&tab, None).as_deref(), Some("This computer: 0.0.0.0:24800")); + assert_eq!(self_fingerprint(&tab), Some(FP_A)); + } + + #[test] + fn pending_rows_show_only_while_the_daemon_runs() { + // A state file left from an earlier run lists a device that can be + // neither attached nor rejected. + let mut tab = with_pending(); + assert!(pending(&tab).is_empty()); + tab.running = true; + assert_eq!(pending(&tab).len(), 1); + } + + #[test] + fn a_device_attached_again_may_keep_its_own_edge() { + let p = two(); + let devs = [device("laptop", FP_B, "DP-2", Side::RightOf)]; + let own = ("DP-2".to_string(), Side::RightOf); + // The pending line of the laptop's new fingerprint. + assert!(position_edges(&p, &[], &devs, "laptop").contains(&own)); + assert!(!position_edges(&p, &[], &devs, "mac").contains(&own)); + } + + #[test] + fn edge_labels() { + assert_eq!(edge_label(Side::RightOf, "DP-1"), "Right of DP-1"); + assert_eq!(edge_label(Side::Above, "HDMI-A-1"), "Above HDMI-A-1"); + } +} diff --git a/src/thinfloe-menu/src/generated.rs b/src/thinfloe-menu/src/generated.rs index 8538a57..72c9401 100644 --- a/src/thinfloe-menu/src/generated.rs +++ b/src/thinfloe-menu/src/generated.rs @@ -32,6 +32,9 @@ pub enum Table { PublicIp, /// `[time]`: the zone and the NTP servers. Time, + /// `[deskflow]`: the listener switch, the port and the paired devices. + /// Its file also follows the volume key switch of `[keyboard]`. + Deskflow, Notice, } @@ -39,12 +42,14 @@ impl Table { /// The generated files this table feeds. pub fn files(self) -> &'static [&'static str] { match self { - Table::Keyboard => &["environment"], + // The volume key switch decides `mic_mute_local` there. + Table::Keyboard => &["environment", "deskflow"], Table::Screen => &["screen"], Table::Status | Table::Notice | Table::PublicIp => &[], Table::Monitors => &["kanshi"], Table::Network => &["wifi.yaml", "ethernet.yaml"], Table::Time => &["time"], + Table::Deskflow => &["deskflow"], } } } @@ -145,15 +150,28 @@ pub fn render(cfg: &ThinfloeConfig, name: &str, inp: &Inputs) -> Result { + crate::deskflowcfg::validate(&cfg.deskflow)?; + // Nothing is shared and nothing changed: no file; the daemon + // reads an absent file as the defaults. + if cfg.deskflow == crate::config::DeskflowCfg::default() { + return Ok(None); + } + Ok(Some(with_header(&crate::deskflowcfg::render( + &cfg.deskflow, + cfg.keyboard.volume_keys, + )))) + } other => Err(format!("No generated file named {other}")), } } /// The file mode of generated file `name`: the netplan files hold -/// passwords. +/// passwords, the Deskflow file the pairings. pub fn mode_of(name: &str) -> u32 { match name { - "wifi.yaml" | "ethernet.yaml" => 0o600, + // The device fingerprints are the pairings. + "wifi.yaml" | "ethernet.yaml" | "deskflow" => 0o600, _ => 0o644, } } @@ -258,6 +276,24 @@ mod tests { assert!(t.contains("\nTHINFLOE_NUMLOCK=off\n"), "{t}"); } + #[test] + fn generated_deskflow_carries_mic_mute_local() { + let mut c = ThinfloeConfig::default(); + c.deskflow.listen = true; + for on in [false, true] { + c.keyboard.volume_keys = on; + let t = render(&c, "deskflow", &inp()).unwrap().unwrap(); + assert!(t.contains(&format!("\nmic_mute_local = {on}\n")), "{t}"); + let g = crate::deskflowcfg::parse(&t).unwrap(); + assert_eq!((g.deskflow, g.mic_mute_local), (c.deskflow.clone(), on)); + } + // No Deskflow settings: still no file, whatever the switch. + let mut c = ThinfloeConfig::default(); + c.keyboard.volume_keys = true; + assert_eq!(render(&c, "deskflow", &inp()).unwrap(), None); + assert!(Table::Keyboard.files().contains(&"deskflow")); + } + #[test] fn media_key_switches_reach_the_environment() { let mut c = ThinfloeConfig::default(); diff --git a/src/thinfloe-menu/src/kanshi.rs b/src/thinfloe-menu/src/kanshi.rs index 4044435..7c6e70b 100644 --- a/src/thinfloe-menu/src/kanshi.rs +++ b/src/thinfloe-menu/src/kanshi.rs @@ -17,7 +17,7 @@ pub enum Side { } impl Side { - fn word(self) -> &'static str { + pub(crate) fn word(self) -> &'static str { match self { Side::LeftOf => "left-of", Side::RightOf => "right-of", @@ -26,7 +26,7 @@ impl Side { } } - fn from_word(w: &str) -> Option { + pub(crate) fn from_word(w: &str) -> Option { Some(match w { "left-of" => Side::LeftOf, "right-of" => Side::RightOf, diff --git a/src/thinfloe-menu/src/lib.rs b/src/thinfloe-menu/src/lib.rs index acd7a5a..185094a 100644 --- a/src/thinfloe-menu/src/lib.rs +++ b/src/thinfloe-menu/src/lib.rs @@ -10,6 +10,11 @@ pub mod config; pub mod convert; pub mod damage; pub mod density; +pub mod deskflow; +pub mod deskflow_sup; +pub mod deskflow_ui; +pub mod deskflowcfg; +pub mod deskflowtab; pub mod desktop; pub mod drives; pub mod generated; diff --git a/src/thinfloe-menu/src/main.rs b/src/thinfloe-menu/src/main.rs index 10f4406..26599e2 100644 --- a/src/thinfloe-menu/src/main.rs +++ b/src/thinfloe-menu/src/main.rs @@ -31,7 +31,9 @@ use thinfloe_menu::jobs::{self, Paths}; use thinfloe_menu::log::Kind; use thinfloe_menu::menu::{ConfigNotes, LEGACY_NOTE, Menu}; use thinfloe_menu::store::{self, OpenMode}; -use thinfloe_menu::{bounded, keyboard, migrate, osd, release, screentab, settings, status, tiles, ui, windows}; +use thinfloe_menu::{ + bounded, deskflow, keyboard, migrate, osd, release, screentab, settings, status, tiles, ui, windows, +}; fn env_path(name: &str, default: &str) -> PathBuf { std::env::var_os(name) @@ -246,6 +248,7 @@ fn build_menu(marker: settings::RetryMarker, mode: OpenMode) -> Built { on: opened.store.cfg.network.public_ip, url: opened.store.cfg.network.public_ip_url.clone(), }; + let deskflow_tab = thinfloe_menu::deskflowtab::from_config(&opened.store.cfg.deskflow); let (screen_tab, status_layout) = ( screentab::from_config(&opened.store.cfg.screen), status::layout_from(&opened.store.cfg.status), @@ -290,6 +293,7 @@ fn build_menu(marker: settings::RetryMarker, mode: OpenMode) -> Built { menu.set_usb_boot(usb_boot(&env_path("TF_ESP_DIR", "/run/thinfloe/storage/efi"))); menu.upgrade.release_file(release::read_status(&upgrade_status_path())); menu.screen_tab = screen_tab; + menu.deskflow = deskflow_tab; menu.network.set_public_ip(public_ip); menu.network.time_mut().set_zones(thinfloe_menu::timecfg::read_zones()); menu.network.time_mut().set_cfg(time_cfg); @@ -498,6 +502,9 @@ fn main() -> ExitCode { if args.get(1).is_some_and(|a| a == osd::OSD_KEY_ARG) { return osd::osd_key_main(&args[2..]); } + if args.get(1).is_some_and(|a| a == deskflow::DESKFLOW_ARG) { + return deskflow::deskflow_main(&args[2..]); + } if args.get(1).is_some_and(|a| a == "--check") { return check(); } diff --git a/src/thinfloe-menu/src/menu.rs b/src/thinfloe-menu/src/menu.rs index b8f1e19..434c662 100644 --- a/src/thinfloe-menu/src/menu.rs +++ b/src/thinfloe-menu/src/menu.rs @@ -237,6 +237,9 @@ pub enum Effect { WriteScreen { idle: u32, }, + /// Keep the `[deskflow]` table or send the daemon a command, then + /// report with `deskflow_written` or `deskflow_sent`. + Deskflow(crate::deskflowtab::DeskflowRequest), } /// What the Settings screen tells about the config directory, in the order @@ -331,6 +334,8 @@ pub struct Menu { pub settings_tab: SettingsTab, /// The screen timeout, as the Screen tab shows it. pub screen_tab: ScreenTab, + /// The Deskflow band of the Screen tab. + pub deskflow: crate::deskflowtab::DeskflowTab, /// The Network tab, and the Apply it runs. pub network: NetTab, /// The monitors of the Screen tab, and the Apply it runs. @@ -403,6 +408,7 @@ impl Menu { usb_boot: false, settings_tab: SettingsTab::Packages, screen_tab: ScreenTab::default(), + deskflow: crate::deskflowtab::DeskflowTab::default(), // Until `set_usb_boot` says otherwise: netboot offers less. network: NetTab::new(true), monitors: MonTab::default(), @@ -878,6 +884,7 @@ impl Menu { SettingsEvent::IdleTimeout(_) | SettingsEvent::Network(_) | SettingsEvent::Monitors(_) + | SettingsEvent::Deskflow(_) | SettingsEvent::Status(_) | SettingsEvent::Keyboard(_) | SettingsEvent::DismissReport @@ -909,7 +916,16 @@ impl Menu { let r = self.network.event(e, self.remote_running())?; return self.net_request(r); } - SettingsEvent::Monitors(e) => return self.monitors_event(e, Instant::now()), + SettingsEvent::Monitors(e) => { + // A monitor or a device is selected, never both. + if matches!(e, crate::monitors::MonEvent::Select(_)) { + self.deskflow.selected = None; + } + return self.monitors_event(e, Instant::now()); + } + SettingsEvent::Deskflow(e) => { + return crate::deskflowtab::apply(&mut self.deskflow, e).map(Effect::Deskflow); + } SettingsEvent::Status(e) => return self.status_event(e), SettingsEvent::Keyboard(e) => { let kb = self.keyboard.event(e)?; @@ -1184,6 +1200,24 @@ impl Menu { self.save_after_change() } + /// The `[deskflow]` write ended: `stored` is the table as the store + /// holds it now, `error` why the write failed. `config.toml` lives in + /// the home, so a change is saved, as `screen_written` does. + pub fn deskflow_written(&mut self, stored: crate::config::DeskflowCfg, error: Option) -> Option { + self.deskflow.cfg = stored; + if let Some(message) = &error { + self.log.note(Kind::Warn, message.clone()); + } + let ok = error.is_none(); + self.deskflow.error = error; + if ok { self.save_after_change() } else { None } + } + + /// A command to the daemon was sent, or why not. + pub fn deskflow_sent(&mut self, error: Option) { + self.deskflow.error = error; + } + /// A file of the home changed: save, or say why not. fn save_after_change(&mut self) -> Option { if self.restore_failed { @@ -4694,6 +4728,39 @@ mod tests { assert!(!m.status.layout.choices[0].shown); } + #[test] + fn a_deskflow_event_asks_for_its_request_and_a_monitor_click_drops_the_device() { + use crate::deskflowtab::{DeskflowEvent, DeskflowRequest}; + let (_d, mut m) = settings_menu("deskflow-event"); + let Some(Effect::Deskflow(DeskflowRequest::Save(cfg))) = + m.settings(SettingsEvent::Deskflow(DeskflowEvent::Listen(true))) + else { + panic!("no save"); + }; + assert!(cfg.listen); + m.settings(SettingsEvent::Deskflow(DeskflowEvent::Select("laptop".into()))); + assert_eq!(m.deskflow.selected.as_deref(), Some("laptop")); + m.settings(SettingsEvent::Monitors(crate::monitors::MonEvent::Select( + "DP-1".into(), + ))); + assert_eq!( + m.deskflow.selected, None, + "a monitor or a device is selected, never both" + ); + let mut lm = legacy_menu(); + assert_eq!(lm.settings(SettingsEvent::Deskflow(DeskflowEvent::Listen(true))), None); + assert!(!lm.deskflow.cfg.listen); + } + + #[test] + fn a_failed_deskflow_write_is_logged_and_shown() { + let (_d, mut m) = settings_menu("deskflow-written"); + let next = m.deskflow_written(crate::config::DeskflowCfg::default(), Some("read-only".into())); + assert_eq!(next, None); + assert_eq!(m.deskflow.error.as_deref(), Some("read-only")); + assert!(m.log.lines().any(|l| l.plain() == "read-only")); + } + fn legacy_menu() -> Menu { let (_d, mut m) = settings_menu("legacy-settings"); m.config_notes.legacy = Some("legacy".into()); diff --git a/src/thinfloe-menu/src/monitors_ui.rs b/src/thinfloe-menu/src/monitors_ui.rs index 8eb54f3..f98c807 100644 --- a/src/thinfloe-menu/src/monitors_ui.rs +++ b/src/thinfloe-menu/src/monitors_ui.rs @@ -4,6 +4,7 @@ //! lives in monitors.rs; this file only paints it and reports clicks. use crate::brand::{self, role}; +use crate::deskflow::statefile::DevState; use crate::heads::{Mode, Rotation}; use crate::kanshi::{self, OutputSet, Place, Profile, Side}; use crate::monitors::{MonEvent, MonSource, MonTab}; @@ -30,6 +31,9 @@ const NO_MODE: (i32, i32) = (1920, 1080); const BAND_PAD: i8 = 12; /// Before the buttons of a dialog, as the other dialogs. const BUTTON_GAP: f32 = 8.0; +/// The radius of a device's status dot, and its gap to the name. +const DOT_R: f32 = 4.0; +const DOT_GAP: f32 = 4.0; /// Between the On tick box and *Show the menu here* on its row. const MENU_BUTTON_GAP: f32 = 24.0; @@ -72,10 +76,46 @@ pub struct MonBox { pub rect: Rect, } +/// An attached Deskflow device as the arrangement draws it. +#[derive(Debug, Clone, PartialEq)] +pub struct DevPlace { + pub name: String, + /// The monitor it sits beside, by criteria. + pub output: String, + pub side: Side, + /// Its screen in its own pixels. + pub size: (u32, u32), + pub state: DevState, + /// Its edge is not free: it gets no strip. + pub inactive: bool, +} + +/// Where a device's box goes in the drawing. +#[derive(Debug, Clone, PartialEq)] +pub struct DevBox { + pub place: DevPlace, + pub rect: Rect, +} + +/// What a click in the monitor band asks for. +#[derive(Debug, Clone, PartialEq)] +pub enum BandEvent { + Mon(MonEvent), + /// A device box, by name. + Device(String), +} + /// The boxes of `layout` fitted into `area`, all at one scale. The /// monitors that are on sit where the arrangement puts them; those that /// are off follow in a row to their right, at the size of their mode. pub fn boxes(mon: &MonTab, layout: &Profile, area: Rect) -> Vec { + arranged(mon, layout, &[], area).0 +} + +/// `boxes`, and the devices beside the monitors that are on: one scale for +/// all, so a device's box shows its size against the monitors. A device +/// whose monitor is off or missing is not drawn. +pub fn arranged(mon: &MonTab, layout: &Profile, devices: &[DevPlace], area: Rect) -> (Vec, Vec) { // An arrangement that cannot be placed shows its monitors in a row. let placed = kanshi::place_all(layout).unwrap_or_else(|_| vec![None; layout.outputs.len()]); let size_of = |o: &OutputSet| { @@ -110,30 +150,91 @@ pub fn boxes(mon: &MonTab, layout: &Profile, area: Rect) -> Vec { cursor += w + gap; } } - let total_w = rects.iter().map(|r| r.0 + r.2).max().unwrap_or(0).max(1) as f32; - let total_h = rects.iter().map(|r| r.1 + r.3).max().unwrap_or(0).max(1) as f32; + let mut dev_rects = Vec::new(); + for d in devices { + let Some(i) = layout.outputs.iter().position(|o| o.criteria == d.output) else { + continue; + }; + if placed[i].is_none() { + continue; + } + let (x, y, w, h) = rects[i]; + let dw = i32::try_from(d.size.0).unwrap_or(i32::MAX / 4).min(i32::MAX / 4); + let dh = i32::try_from(d.size.1).unwrap_or(i32::MAX / 4).min(i32::MAX / 4); + let at = match d.side { + Side::RightOf => (x + w, y), + Side::LeftOf => (x - dw, y), + Side::Above => (x, y - dh), + Side::Below => (x, y + h), + }; + // An inactive device whose box lies on a monitor (another monitor + // took its edge) is not drawn: the monitor would cover it and take + // its clicks. The band lists it instead. + let overlaps = |(ax, ay, aw, ah): (i32, i32, i32, i32)| { + let (ax, ay, aw, ah) = (i64::from(ax), i64::from(ay), i64::from(aw), i64::from(ah)); + rects + .iter() + .zip(&placed) + .filter(|(_, p)| p.is_some()) + .any(|(&(bx, by, bw, bh), _)| { + let (bx, by, bw, bh) = (i64::from(bx), i64::from(by), i64::from(bw), i64::from(bh)); + ax < bx + bw && bx < ax + aw && ay < by + bh && by < ay + ah + }) + }; + if d.inactive && overlaps((at.0, at.1, dw, dh)) { + continue; + } + dev_rects.push((d, (at.0, at.1, dw, dh))); + } + // A device left of or above the monitors moves them right or down. + let all = || rects.iter().chain(dev_rects.iter().map(|(_, r)| r)); + let min_x = all().map(|r| r.0).min().unwrap_or(0).min(0); + let min_y = all().map(|r| r.1).min().unwrap_or(0).min(0); + let total_w = all().map(|r| r.0 + r.2 - min_x).max().unwrap_or(0).max(1) as f32; + let total_h = all().map(|r| r.1 + r.3 - min_y).max().unwrap_or(0).max(1) as f32; let scale = (area.width() / total_w).min(area.height() / total_h); let offset = vec2((area.width() - total_w * scale) / 2.0, 0.0); - layout + let to_area = |(x, y, w, h): (i32, i32, i32, i32)| { + Rect::from_min_size( + area.min + offset + vec2((x - min_x) as f32 * scale, (y - min_y) as f32 * scale), + vec2(w as f32 * scale, h as f32 * scale), + ) + }; + let mons = layout .outputs .iter() - .zip(rects) - .map(|(o, (x, y, w, h))| MonBox { + .zip(rects.iter()) + .map(|(o, r)| MonBox { criteria: o.criteria.clone(), enabled: o.enabled, - rect: Rect::from_min_size( - area.min + offset + vec2(x as f32 * scale, y as f32 * scale), - vec2(w as f32 * scale, h as f32 * scale), - ), + rect: to_area(*r), + }) + .collect(); + let devs = dev_rects + .iter() + .map(|(d, r)| DevBox { + place: (*d).clone(), + rect: to_area(*r), }) - .collect() + .collect(); + (mons, devs) } /// The monitor band of the Screen tab, `width` wide as the panel, under /// the screen timeout: the boxes and the selected monitor's settings. /// Apply follows in `monitors_footer`. `now` keeps the countdown's /// wake-up honest. -pub fn monitors_band(ui: &mut Ui, mon: &MonTab, now: Instant, width: f32) -> Option { +/// +/// `devices` are drawn beside their monitors; `device` is the one +/// selected. +pub fn monitors_band( + ui: &mut Ui, + mon: &MonTab, + devices: &[DevPlace], + device: Option<&str>, + now: Instant, + width: f32, +) -> Option { let t = Theme::current(ui.ctx()); if let Some(d) = mon.next_wake(now) { ui.ctx().request_repaint_after(d); @@ -160,9 +261,7 @@ pub fn monitors_band(ui: &mut Ui, mon: &MonTab, now: Instant, width: f32) -> Opt return; }; let hand = mon.source() == MonSource::Kept; - if let Some(c) = arrangement(ui, &t, mon, layout, !hand) { - event = Some(MonEvent::Select(c)); - } + event = arrangement(ui, &t, mon, layout, !hand, devices, device); if hand { muted(ui, &t, HAND_LINE); if ui @@ -172,10 +271,12 @@ pub fn monitors_band(ui: &mut Ui, mon: &MonTab, now: Instant, width: f32) -> Opt ) .clicked() { - event = Some(MonEvent::TakeOver); + event = Some(BandEvent::Mon(MonEvent::TakeOver)); } - } else if let Some(e) = selected_rows(ui, &t, mon, layout) { - event = Some(e); + } else if device.is_none() + && let Some(e) = selected_rows(ui, &t, mon, layout) + { + event = Some(BandEvent::Mon(e)); } }); event @@ -232,20 +333,35 @@ fn name_of<'a>(mon: &'a MonTab, criteria: &'a str) -> &'a str { mon.head(criteria).map_or(criteria, |h| h.name.as_str()) } -/// The boxes; returns the criteria of a box clicked. `pick`: a click -/// selects, else the boxes only show. -fn arrangement(ui: &mut Ui, t: &Theme, mon: &MonTab, layout: &Profile, pick: bool) -> Option { +/// The boxes; returns what a click on one asks for. `pick`: a click on a +/// monitor selects it, else the monitors only show. A device box always +/// takes a click. +fn arrangement( + ui: &mut Ui, + t: &Theme, + mon: &MonTab, + layout: &Profile, + pick: bool, + devices: &[DevPlace], + device: Option<&str>, +) -> Option { let (area, _) = ui.allocate_exact_size(vec2(ui.available_width(), ARRANGE_H), Sense::hover()); let mut clicked = None; let p = t.palette(); let sense = if pick { Sense::click() } else { Sense::hover() }; - for b in boxes(mon, layout, area) { + let (mons, devs) = arranged(mon, layout, devices, area); + for d in &devs { + if let Some(name) = device_box(ui, t, d, device == Some(d.place.name.as_str())) { + clicked = Some(BandEvent::Device(name)); + } + } + for b in mons { let resp = ui.interact(b.rect, egui::Id::unique(("tf-mon-box", &b.criteria)), sense); if resp.clicked() { - clicked = Some(b.criteria.clone()); + clicked = Some(BandEvent::Mon(MonEvent::Select(b.criteria.clone()))); } let drawn = b.rect.shrink(BOX_GAP / 2.0); - let selected = pick && mon.selected() == Some(b.criteria.as_str()); + let selected = pick && device.is_none() && mon.selected() == Some(b.criteria.as_str()); let fill = match (b.enabled, pick && resp.hovered()) { (true, true) => p.accent, (true, false) => p.muted, @@ -290,6 +406,53 @@ fn arrangement(ui: &mut Ui, t: &Theme, mon: &MonTab, layout: &Profile, pick: boo clicked } +/// One device box: outlined, its name and a status dot. Returns its name +/// when clicked. +fn device_box(ui: &mut Ui, t: &Theme, d: &DevBox, selected: bool) -> Option { + let p = t.palette(); + let name = &d.place.name; + let resp = ui.interact(d.rect, egui::Id::unique(("tf-dev-box", name)), Sense::click()); + resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, true, selected, name)); + let drawn = d.rect.shrink(BOX_GAP / 2.0); + let fill = if resp.hovered() { p.accent } else { Color32::TRANSPARENT }; + let stroke = if selected { + Stroke::new(2.0, p.primary) + } else { + Stroke::new(1.0, p.border) + }; + ui.painter().rect(drawn, 0.0, fill, stroke, StrokeKind::Inside); + let dot = match d.place.state { + DevState::Active => p.primary, + DevState::Connected => t.role(role::GOOD), + _ => p.muted_foreground, + }; + let inside = drawn.shrink(BOX_PAD); + if inside.width() > 0.0 && inside.height() > 0.0 { + let centre = egui::pos2(inside.right() - DOT_R, inside.top() + DOT_R); + ui.painter().circle_filled(centre, DOT_R, dot); + let text_rect = Rect::from_min_max( + inside.min, + egui::pos2(inside.right() - 2.0 * DOT_R - DOT_GAP, inside.bottom()), + ); + if text_rect.width() > 0.0 { + let mut c = ui.new_child( + UiBuilder::new() + .max_rect(text_rect) + .layout(Layout::top_down(Align::Min)), + ); + c.set_clip_rect(text_rect.intersect(ui.clip_rect())); + c.style_mut().interaction.selectable_labels = false; + let colour = if d.place.inactive { + p.muted_foreground + } else { + p.foreground + }; + c.add(egui::Label::new(RichText::new(name).color(colour)).truncate()); + } + } + resp.clicked().then(|| name.clone()) +} + fn opposite(s: Side) -> Side { match s { Side::LeftOf => Side::RightOf, @@ -481,6 +644,70 @@ mod tests { assert_eq!(mode_label(&mode(1920, 1080, 0)), "1920 × 1080"); } + #[test] + fn a_device_sits_beside_its_monitor_at_the_monitors_scale() { + use crate::heads::Rotation; + use crate::kanshi::OutputSet; + let layout = Profile { + outputs: vec![OutputSet { + criteria: "DP-1".into(), + enabled: true, + mode: mode(1920, 1080, 60_000), + rotation: Rotation::Normal, + place: Place::Origin, + }], + menu_output: None, + }; + let dev = |side, output: &str| DevPlace { + name: "laptop".into(), + output: output.into(), + side, + size: (960, 540), + state: DevState::Connected, + inactive: false, + }; + let area = Rect::from_min_size(egui::pos2(0.0, 0.0), vec2(2880.0, 1080.0)); + let mon = MonTab::default(); + let (m, d) = arranged(&mon, &layout, &[dev(Side::RightOf, "DP-1")], area); + assert_eq!( + m[0].rect, + Rect::from_min_size(egui::pos2(0.0, 0.0), vec2(1920.0, 1080.0)) + ); + assert_eq!( + d[0].rect, + Rect::from_min_size(egui::pos2(1920.0, 0.0), vec2(960.0, 540.0)) + ); + // Left of the monitor: the monitor moves right. + let (m, d) = arranged(&mon, &layout, &[dev(Side::LeftOf, "DP-1")], area); + assert_eq!(d[0].rect.min, egui::pos2(0.0, 0.0)); + assert_eq!(m[0].rect.min, egui::pos2(960.0, 0.0)); + // A device whose edge another monitor took is not drawn over it. + let mut docked = layout.clone(); + docked.outputs.push(OutputSet { + criteria: "DP-2".into(), + enabled: true, + mode: mode(1920, 1080, 60_000), + rotation: Rotation::Normal, + place: Place::Next { + to: "DP-1".into(), + side: Side::RightOf, + }, + }); + let mut busy = dev(Side::RightOf, "DP-1"); + busy.inactive = true; + let (m, d) = arranged(&mon, &docked, &[busy.clone()], area); + assert!(d.is_empty(), "the laptop box would lie inside DP-2"); + assert_eq!(m, boxes(&mon, &docked, area)); + // An inactive device that overlaps nothing is still drawn. + let mut free = dev(Side::LeftOf, "DP-1"); + free.inactive = true; + assert_eq!(arranged(&mon, &docked, &[free], area).1.len(), 1); + // A device at a missing monitor is not drawn, and changes nothing. + let (m, d) = arranged(&mon, &layout, &[dev(Side::LeftOf, "HDMI-1")], area); + assert!(d.is_empty()); + assert_eq!(m, boxes(&mon, &layout, area)); + } + #[test] fn going_back_counts_in_words() { assert_eq!(going_back(15), "Going back in 15 seconds."); diff --git a/src/thinfloe-menu/src/settings.rs b/src/thinfloe-menu/src/settings.rs index 5ca0f68..52d5536 100644 --- a/src/thinfloe-menu/src/settings.rs +++ b/src/thinfloe-menu/src/settings.rs @@ -34,6 +34,9 @@ pub enum SettingsEvent { Network(NetEvent), /// Something on the monitor part of the Screen tab. Monitors(crate::monitors::MonEvent), + /// Something on the Deskflow band of the Screen tab, or a device in + /// the monitor arrangement. + Deskflow(crate::deskflowtab::DeskflowEvent), /// Something on the Status tab. Status(crate::statustab::StatusEvent), /// *Dismiss* on the migration report. diff --git a/src/thinfloe-menu/src/store.rs b/src/thinfloe-menu/src/store.rs index 7fc86bb..392f9ef 100644 --- a/src/thinfloe-menu/src/store.rs +++ b/src/thinfloe-menu/src/store.rs @@ -19,7 +19,15 @@ const CONFIG_MODE: u32 = 0o600; pub const CONFIG_MAX_BYTES: u64 = 1024 * 1024; /// Every generated file, in the order they are regenerated. -const ALL_FILES: [&str; 6] = ["environment", "screen", "kanshi", "wifi.yaml", "ethernet.yaml", "time"]; +const ALL_FILES: [&str; 7] = [ + "environment", + "screen", + "kanshi", + "wifi.yaml", + "ethernet.yaml", + "time", + "deskflow", +]; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum OpenMode { @@ -237,13 +245,22 @@ impl ConfigStore { } /// Render all files of `table` from `cfg`; one failing render fails - /// the lot before anything is written. + /// the lot before anything is written. generated/deskflow fails only + /// an update of `[deskflow]`: for another table (the volume key switch + /// of `[keyboard]` feeds it too) a `[deskflow]` that does not validate + /// leaves the file as it is, so it never blocks that table's save. fn render_table(&self, table: Table, cfg: &ThinfloeConfig) -> Result)>, String> { - table - .files() - .iter() - .map(|&n| generated::render(cfg, n, &self.inputs).map(|b| (n, b))) - .collect() + let mut out = Vec::new(); + for &n in table.files() { + match generated::render(cfg, n, &self.inputs) { + Ok(b) => out.push((n, b)), + Err(e) if n == "deskflow" && table != Table::Deskflow => { + eprintln!("thinfloe-menu: generated/deskflow was not regenerated: {e}"); + } + Err(e) => return Err(e), + } + } + Ok(out) } /// Apply `f` to a copy, regenerate the files of `table`, then write @@ -467,6 +484,105 @@ mod tests { assert!(t.ends_with("\nntp=10.0.0.1\n") && !t.contains("zone="), "{t}"); } + /// A broken config.toml does not lose the pairings: they come back + /// from generated/deskflow. + #[test] + fn broken_config_keeps_deskflow_devices() { + let d = TestDir::new("store", "deskflow-broken"); + let mut c = ThinfloeConfig::default(); + c.deskflow.listen = true; + c.deskflow.devices = vec![crate::config::DeviceCfg { + name: "laptop".into(), + fingerprint: format!("v2:sha256:{}", "cd".repeat(32)), + output: "DP-1".into(), + side: crate::kanshi::Side::RightOf, + clipboard: true, + }]; + let mut o = open_session(&d); + o.store + .update(Table::Deskflow, |x| x.deskflow = c.deskflow.clone()) + .unwrap(); + let mode = fs::metadata(cdir(&d).generated_file("deskflow")).unwrap(); + assert_eq!( + std::os::unix::fs::PermissionsExt::mode(&mode.permissions()) & 0o777, + 0o600 + ); + fs::write(cdir(&d).config_toml(), "this is [not toml").unwrap(); + let o = open_session(&d); + assert_eq!(o.store.cfg.deskflow, c.deskflow); + assert!( + o.notes.iter().any(|n| n.contains("rebuilt from generated/")), + "{:?}", + o.notes + ); + let back = parse(&fs::read_to_string(cdir(&d).config_toml()).unwrap()).unwrap(); + assert_eq!(back.deskflow, c.deskflow); + } + + #[test] + fn volume_switch_regenerates_deskflow() { + let d = TestDir::new("store", "deskflow-volume"); + let mut o = open_session(&d); + o.store.update(Table::Deskflow, |c| c.deskflow.listen = true).unwrap(); + let mic = |d: &TestDir| { + crate::deskflowcfg::parse(&gen_text(d, "deskflow").unwrap()) + .unwrap() + .mic_mute_local + }; + assert!(!mic(&d)); + let changed = o + .store + .update(Table::Keyboard, |c| c.keyboard.volume_keys = true) + .unwrap(); + assert!(changed.contains(&"deskflow"), "{changed:?}"); + assert!(mic(&d)); + // Another keyboard change leaves the file alone. + let changed = o.store.update(Table::Keyboard, |c| c.keyboard.numlock = false).unwrap(); + assert!(!changed.contains(&"deskflow"), "{changed:?}"); + } + + #[test] + fn an_invalid_deskflow_table_does_not_block_a_keyboard_save() { + let d = TestDir::new("store", "deskflow-invalid-keyboard"); + let mut o = open_session(&d); + o.store.update(Table::Deskflow, |c| c.deskflow.listen = true).unwrap(); + let before = gen_text(&d, "deskflow").unwrap(); + // A hand edit the store keeps: port 0 does not validate. + let mut c = o.store.cfg.clone(); + c.deskflow.port = 0; + fs::write(cdir(&d).config_toml(), crate::config::to_text(&c)).unwrap(); + let mut o = open_session(&d); + assert_eq!(o.store.cfg.deskflow.port, 0); + let changed = o + .store + .update(Table::Keyboard, |c| c.keyboard.volume_keys = true) + .unwrap(); + assert!(!changed.contains(&"deskflow"), "{changed:?}"); + assert!(o.store.cfg.keyboard.volume_keys); + assert!(gen_text(&d, "environment").unwrap().contains("THINFLOE_VOLUME_KEYS=on")); + assert_eq!(gen_text(&d, "deskflow").unwrap(), before); + // The Deskflow table's own update still refuses it. + assert!(o.store.update(Table::Deskflow, |_| {}).is_err()); + } + + #[test] + fn a_bad_deskflow_device_is_refused_and_writes_nothing() { + let d = TestDir::new("store", "deskflow-bad"); + let mut o = open_session(&d); + let r = o.store.update(Table::Deskflow, |c| { + c.deskflow.devices = vec![crate::config::DeviceCfg { + name: "x".into(), + fingerprint: "nope".into(), + output: "DP-1".into(), + side: crate::kanshi::Side::Above, + clipboard: true, + }]; + }); + assert!(r.is_err()); + assert!(gen_text(&d, "deskflow").is_none()); + assert!(o.store.cfg.deskflow.devices.is_empty()); + } + #[test] fn read_only_open_does_not_repair_the_keymap() { let d = TestDir::new("store", "kb-readonly"); diff --git a/src/thinfloe-menu/src/ui.rs b/src/thinfloe-menu/src/ui.rs index e48f9db..3d15ffc 100644 --- a/src/thinfloe-menu/src/ui.rs +++ b/src/thinfloe-menu/src/ui.rs @@ -1125,12 +1125,35 @@ fn screen_tab(ui: &mut Ui, menu: &Menu, width: f32, now: Instant) -> Option SettingsEvent::Monitors(e), + crate::monitors_ui::BandEvent::Device(name) => { + SettingsEvent::Deskflow(crate::deskflowtab::DeskflowEvent::Select(name)) + } + }); + let ipv4 = menu.netstat.as_ref().and_then(|s| s.info.ipv4).map(|(ip, _)| ip); + let deskflow = ui + .scope(|ui| { + ui.spacing_mut().item_spacing.y = between; + let t = Theme::current(ui.ctx()); + crate::deskflow_ui::band(ui, &t, &menu.deskflow, &menu.monitors, ipv4, band_w) + }) + .inner + .map(SettingsEvent::Deskflow); // The facts close the tab, as on the Network tab: on top they // pushed the monitors' Position row out of a 1080 screen. ui.scope(|ui| { @@ -1139,7 +1162,7 @@ fn screen_tab(ui: &mut Ui, menu: &Menu, width: f32, now: Instant) -> Option/tmp/cp.sh && + WAYLAND_DEBUG=server labwc -C /etc/thinfloe/labwc -S "sh /tmp/cp.sh"' 2>&1) + rc=$? + if [[ $rc -eq 124 || $rc -eq 137 ]]; then + echo "FAIL - podman run timed out after ${RUNTIME_TIMEOUT}s (labwc hang during the capture probe)" + grep -E '^(cap|caperr|x11): |^x_|^cap_rc=' <<<"$out" + podman rm -f "$name" >/dev/null 2>&1 + fail=1 + return + fi + local cap x11 diag + cap=$(grep '^cap: ' <<<"$out" | cut -c6-) + x11=$(grep '^x11: ' <<<"$out" | cut -c6- | tr '\n' ' ') + diag="probe: $(tr '\n' '|' <<<"$cap") stderr: $(grep '^caperr: ' <<<"$out" | cut -c9- | tr '\n' '|') X window: '$x11' $(grep -E '^(x_before|x_after|cap_rc)=' <<<"$out" | tr '\n' ' ')" + if ! grep -Eq 'zwp_xwayland_keyboard_grab_manager_v1[@#][0-9]+\.grab_keyboard\(' <<<"$out"; then + echo "FAIL - the X window took no keyboard grab, so the capture case proves nothing: $diag" + fail=1 + return + fi + # enter, then locked, then the x key, in that order. + if awk '/^enter / && !e {e=NR} /^locked$/ && e && !l {l=NR} / down x$/ && l && !k {k=NR} END {exit !(e && l && k)}' <<<"$cap"; then + echo "ok - over a fullscreen X11 window with a keyboard grab the strip gets the pointer lock, then the keys" + else + echo "FAIL - no enter, locked, x key in that order at the capture strip: $diag" + fail=1 + fi + if [[ " $x11" == *" KEY x "* ]]; then + echo "FAIL - the x typed while captured reached the X window: $diag" + fail=1 + else + echo "ok - the x typed while captured did not reach the X window" + fi + if awk '/ down Escape$/ && !s {s=NR} /^unlocked$/ && s {u=1} END {exit !u}' <<<"$cap" && + [[ " $x11" == *" KEY y "* ]] && grep -qx 'x_before=active' <<<"$out" && grep -qx 'x_after=active' <<<"$out"; then + echo "ok - Escape ends the capture: the probe reports unlocked, y reaches the X window and it is active again" + else + echo "FAIL - after Escape: $diag" + fail=1 + fi + if grep -qx 'cap_rc=0' <<<"$out"; then + echo "ok - the capture probe ends with 0 on SIGTERM" + else + echo "FAIL - the capture probe did not end with 0 on SIGTERM: $diag" + fail=1 + fi +} +run_capture_probe_case + +# While the Deskflow capture strip holds the keyboard, every key belongs to +# the device, the volume and brightness keys too +# (containers/ubuntu/patches/0007-layer-inhibitor-blocks-all-keybinds.patch). +# The capture probe takes the strip's keyboard exclusively and puts a +# zwp_keyboard_shortcuts_inhibitor_v1 on it; THINFLOE_VOLUME_KEYS=on composes +# the media key bindings (allowWhenInhibited="yes") with TF_OSD_KEY_CMD +# pointing at a recorder that appends its argument to /tmp/hits. wtype sends +# XF86AudioRaiseVolume while the strip is captured (the probe must get it, +# the recorder must not run), Escape (the probe ends the capture), the key +# again (the recorder runs) and, after the probe has exited, once more (the +# recorder runs). The grab run does the same over a fullscreen X11 window +# holding a keyboard grab, which alone lets the media keys pass (0006): the +# strip's inhibitor still wins, and the X window gets none of the keys. As +# in the capture case, wtype starts first and --keymap names its key codes +# (1 XF86AudioRaiseVolume, 2 Escape). TF_RUNTIME_MENU names a host-built +# thinfloe-menu to use instead of the image's (iteration only). +# shellcheck disable=SC2016 # expands inside the container +li_script='wtype -s 9000 -k XF86AudioRaiseVolume -s 1500 -k Escape -s 1500 -k XF86AudioRaiseVolume -s 2500 -k XF86AudioRaiseVolume & +sleep 0.5 +if [ "$LI_MODE" = grab ]; then + python3 /usr/local/bin/x11-probe.py --grab --fullscreen --keymap XF86AudioRaiseVolume,Escape --keys 16 >/tmp/xkeys 2>&1 & +fi +sleep 5 +thinfloe-menu --deskflow --probe-capture HEADLESS-1 right-of >/tmp/cap.out 2>/tmp/cap.err & +cap=$! +sleep 1.5 +wlrctl pointer move -5000 -5000 +wlrctl pointer move 5000 360 +sleep 2.7 +echo "hits_captured=$(tr "\n" " " >/tmp/hits\n" >/tmp/rec.sh && + printf "%s\n" "$LI_SCRIPT" >/tmp/li.sh && + printf "THINFLOE_VOLUME_KEYS=on\n" >/tmp/cfg/generated/environment && + thinfloe-compose-labwc-config /etc/thinfloe/labwc /tmp/cfg/generated/environment /nonexistent /tmp/xdg/thinfloe-labwc && + WAYLAND_DEBUG=server labwc -C /tmp/xdg/thinfloe-labwc -S "sh /tmp/li.sh"' 2>&1) + rc=$? + if [[ $rc -eq 124 || $rc -eq 137 ]]; then + echo "FAIL - podman run timed out after ${RUNTIME_TIMEOUT}s (labwc hang during the layer inhibitor case, $mode)" + grep -E '^(cap|caperr|x11): |^hits_|^cap_rc=' <<<"$out" + podman rm -f "$name" >/dev/null 2>&1 + fail=1 + return + fi + local cap x11 diag + cap=$(grep '^cap: ' <<<"$out" | cut -c6-) + x11=$(grep '^x11: ' <<<"$out" | cut -c6- | tr '\n' ' ') + diag="probe: $(tr '\n' '|' <<<"$cap") stderr: $(grep '^caperr: ' <<<"$out" | cut -c9- | tr '\n' '|') X window: '$x11' $(grep -E '^(hits_[a-z]*|cap_rc)=' <<<"$out" | tr '\n' ' ')" + if [[ $mode == grab ]] && ! grep -Eq 'zwp_xwayland_keyboard_grab_manager_v1[@#][0-9]+\.grab_keyboard\(' <<<"$out"; then + echo "FAIL - the X window took no keyboard grab, so the layer inhibitor case ($mode) proves nothing: $diag" + fail=1 + return + fi + if ! grep -Eq 'zwp_keyboard_shortcuts_inhibit_manager_v1[@#][0-9]+\.inhibit_shortcuts\(' <<<"$out"; then + echo "FAIL - the capture strip asked for no shortcuts inhibitor ($mode): $diag" + fail=1 + fi + if awk '/^locked$/ && !l {l=NR} / down XF86AudioRaiseVolume$/ && l {k=1} END {exit !k}' <<<"$cap" && + grep -qx 'hits_captured=' <<<"$out"; then + echo "ok - while the strip is captured ($mode) the volume key reaches the probe and runs no binding" + else + echo "FAIL - volume key while captured ($mode): $diag" + fail=1 + fi + if grep -qx 'hits_released=volume-up ' <<<"$out" && grep -qx 'hits_exited=volume-up volume-up ' <<<"$out"; then + echo "ok - once the capture ends and once the probe exits ($mode) the volume key runs its binding again" + else + echo "FAIL - volume key after the capture ($mode): $diag" + fail=1 + fi + if [[ $mode == grab && " $x11" == *" KEY XF86AudioRaiseVolume "* ]]; then + echo "FAIL - the volume key reached the grabbing X window ($mode): $diag" + fail=1 + fi +} +run_layer_inhibit_case plain +run_layer_inhibit_case grab + + +# Deskflow clipboard bridge: 'thinfloe-menu --deskflow --probe-clip' on its +# own Wayland connection against labwc's data-control protocol. wl-copy puts +# a text on the clipboard and the probe prints 'changed '; a +# 'set ' line on the probe's stdin makes that text the selection, which +# wl-paste then reads; a 3 MB text (over the 1 MiB cap) produces 'cleared' +# and no 'changed' line, and the probe still answers the next copy. The probe's stdin is a fifo the +# script holds open. TF_RUNTIME_MENU names a host-built thinfloe-menu to use +# instead of the image's (iteration only). +# shellcheck disable=SC2016 # expands inside the container +cl_script='mkfifo /tmp/clip.in +thinfloe-menu --deskflow --probe-clip /tmp/clip.out 2>/tmp/clip.err & +clip=$! +exec 3>/tmp/clip.in +sleep 2 +printf "hello clip" | wl-copy +sleep 1.5 +echo "set text from the probe" >&3 +sleep 1.5 +wl-paste -n /tmp/pasted 2>&1 +echo "pasted: $(cat /tmp/pasted)" +yes | head -c 3000000 | wl-copy +sleep 3 +printf "after the big one" | wl-copy +sleep 1.5 +kill $clip +wait $clip +echo clip_rc=$? +sed "s/^/clip: /" /tmp/clip.out +sed "s/^/cliperr: /" /tmp/clip.err | head -20 +exit 0' +run_clip_probe_case() { + local name="thinfloe-runtime-test-clip-$$" rc out mount=() + [[ -n "${TF_RUNTIME_MENU:-}" ]] && mount=(-v "$TF_RUNTIME_MENU:/usr/bin/thinfloe-menu:ro") + out=$(timeout --kill-after=10 "$RUNTIME_TIMEOUT" podman run --rm --log-driver=none --name "$name" \ + "${mount[@]}" \ + -e WLR_BACKENDS=headless \ + -e WLR_HEADLESS_OUTPUTS=1 \ + -e WLR_RENDERER=pixman \ + -e XDG_RUNTIME_DIR=/tmp/xdg \ + -e CL_SCRIPT="$cl_script" \ + "$IMAGE" \ + sh -c 'mkdir -p /tmp/xdg && chmod 700 /tmp/xdg && + printf "%s\n" "$CL_SCRIPT" >/tmp/cl.sh && + labwc -C /etc/thinfloe/labwc -S "sh /tmp/cl.sh"' 2>&1) + rc=$? + if [[ $rc -eq 124 || $rc -eq 137 ]]; then + echo "FAIL - podman run timed out after $RUNTIME_TIMEOUT s (labwc hang during the clipboard probe)" + podman rm -f "$name" >/dev/null 2>&1 + fail=1 + return + fi + local diag h1 h3 n + diag=$(grep -E '^(clip|cliperr): |^pasted: |^clip_rc=' <<<"$out" | tr '\n' '|') + h1=$(printf 'hello clip' | sha256sum | cut -d' ' -f1) + h3=$(printf 'after the big one' | sha256sum | cut -d' ' -f1) + if grep -qx "clip: changed 10 $h1" <<<"$out"; then + echo "ok - a text another client copies reaches the clipboard bridge in full" + else + echo "FAIL - the probe did not report the copied text: $diag" + fail=1 + fi + if grep -qx 'pasted: text from the probe' <<<"$out" && ! grep -q '^clip: changed 19 ' <<<"$out"; then + echo "ok - the text the bridge sets is what wl-paste reads, and the bridge does not report its own selection" + else + echo "FAIL - the bridge's own text: $diag" + fail=1 + fi + n=$(grep -c '^clip: changed ' <<<"$out") + if [[ $n -eq 2 ]] && [[ $(grep -cx 'clip: cleared' <<<"$out") -eq 1 ]] && + grep -qx "clip: changed 17 $h3" <<<"$out"; then + echo "ok - a 3 MB copy is reported as cleared, not as a text, and the bridge answers the next copy" + else + echo "FAIL - after the 3 MB copy: $diag" + fail=1 + fi + if grep -qx 'clip_rc=0' <<<"$out"; then + echo "ok - the clipboard probe ends with 0 on SIGTERM" + else + echo "FAIL - the clipboard probe did not end with 0 on SIGTERM: $diag" + fail=1 + fi +} +run_clip_probe_case + + +# Deskflow interop: the stock Deskflow client (deskflow-core 1.26.0 of the +# image's universe) against 'thinfloe-menu --deskflow', in one labwc. +# deskflow-core has no flags for the connection: 'deskflow-core client +# --new-instance -s /Deskflow.conf' takes every setting from that INI +# file (client/remoteHost, core/port, core/computerName, +# security/tlsEnabled, log/level DEBUG2), logs to stdout, and +# --new-instance lets a +# second client run beside the first. Settings::tlsDir() is the directory of +# that file plus /tls: the client's certificate and key are +# /tls/deskflow.pem (deskflow-core does not make one, the GUI does), the +# servers it trusts /tls/trusted-servers, one 'v2:sha256:' per +# line. Without XDG_SESSION_TYPE=wayland the client drives X11, here +# labwc's Xwayland, whose root window is the 1280x720 output. +# The case: ThinFloe's fingerprint from the state file goes into the trust +# file; the client appears as pending; an attach in generated/deskflow and +# 'reload' on the command socket let its next try in (connected, with its +# screen size); a second 'laptop' with another certificate stays out +# (fp-changed) while the first stays connected; 'listen = false' and a +# reload end the daemon with 0 and nothing listens on 24800 any more. +# The client's console shows only its NOTE and IPC lines, whatever +# log/level says. +# shellcheck disable=SC2016 # expands inside the container +df_script='export TF_CONFIG_DIR=/tmp/tfcfg TF_DESKFLOW_STATE=/tmp/xdg/df.state TF_DESKFLOW_SOCKET=/tmp/xdg/df.sock +gen=$TF_CONFIG_DIR/generated/deskflow +mkdir -p $TF_CONFIG_DIR/generated +printf "[deskflow]\nlisten = true\nport = 24800\n" >$gen +upto() { n=$(($1 * 5)); shift; while [ $n -gt 0 ]; do "$@" && return 0; sleep 0.2; n=$((n - 1)); done; return 1; } +st() { cat $TF_DESKFLOW_STATE 2>/dev/null; } +line() { st | awk -F "\t" -v n="$1" -v f="$2" -v s="$3" "\$1 == n && \$2 == f && \$3 == s" | grep -q .; } +reload() { python3 -c "import socket, sys; socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM).sendto(b\"reload\n\", sys.argv[1])" $TF_DESKFLOW_SOCKET; } +client() { + d=$1; mkdir -p $d/tls + printf "[client]\nremoteHost=127.0.0.1\n[core]\nport=24800\ncomputerName=laptop\n[security]\ntlsEnabled=true\n[log]\nlevel=DEBUG2\n" >$d/Deskflow.conf + openssl req -x509 -newkey rsa:2048 -nodes -keyout $d/key.pem -out $d/cert.pem -days 30 -subj /CN=laptop 2>/dev/null + cat $d/cert.pem $d/key.pem >$d/tls/deskflow.pem + echo "$fp" >$d/tls/trusted-servers + echo "v2:sha256:$(openssl x509 -in $d/cert.pem -outform DER | sha256sum | cut -d" " -f1)" >$d/fp + env -u WAYLAND_DISPLAY XDG_SESSION_TYPE=x11 QT_QPA_PLATFORM=offscreen \ + timeout 60 deskflow-core client --new-instance -s $d/Deskflow.conf >$d/log 2>&1 & +} +thinfloe-menu --deskflow >/tmp/d.out 2>/tmp/d.err & +dpid=$! +upto 15 sh -c "head -1 $TF_DESKFLOW_STATE 2>/dev/null | grep -q \"^self\"" && echo head=yes || echo head=no +fp=$(st | head -1 | cut -f2) +echo "fp=$fp" +client /tmp/c1 +c1=$(cat /tmp/c1/fp) +upto 15 line laptop "$c1" pending && echo pending=yes || echo pending=no +printf "\n[[deskflow.device]]\nname = \"laptop\"\nfingerprint = \"%s\"\noutput = \"HEADLESS-1\"\nside = \"right-of\"\n" "$c1" >>$gen +reload +upto 15 line laptop "$c1" connected && echo connected=yes || echo connected=no +upto 5 grep -q "connected to server" /tmp/c1/log && echo c1_log=yes || echo c1_log=no +client /tmp/c2 +c2=$(cat /tmp/c2/fp) +upto 15 line laptop "$c2" pending && echo pending2=yes || echo pending2=no +line laptop "$c1" connected && echo still=yes || echo still=no +st | sed "s/^/state: /" +printf "[deskflow]\nlisten = false\nport = 24800\n" >$gen +reload +upto 15 sh -c "! kill -0 $dpid 2>/dev/null" +wait $dpid +echo d_rc=$? +ss -Hltn "sport = :24800" | grep -q . && echo listening=yes || echo listening=no +sed "s/^/c1: /" /tmp/c1/log | tail -60 +sed "s/^/c2: /" /tmp/c2/log | tail -30 +sed "s/^/derr: /" /tmp/d.err | head -40 +exit 0' +run_deskflow_pairing_case() { + local name="thinfloe-runtime-test-df-$$" rc out mount=() + [[ -n "${TF_RUNTIME_MENU:-}" ]] && mount=(-v "$TF_RUNTIME_MENU:/usr/bin/thinfloe-menu:ro") + out=$(timeout --kill-after=10 "$RUNTIME_TIMEOUT" podman run --rm --log-driver=none --name "$name" \ + "${mount[@]}" \ + -e WLR_BACKENDS=headless \ + -e WLR_HEADLESS_OUTPUTS=1 \ + -e WLR_RENDERER=pixman \ + -e XDG_RUNTIME_DIR=/tmp/xdg \ + -e DF_SCRIPT="$df_script" \ + "$IMAGE" \ + sh -c 'mkdir -p /tmp/xdg && chmod 700 /tmp/xdg && + printf "%s\n" "$DF_SCRIPT" >/tmp/df.sh && + labwc -C /etc/thinfloe/labwc -S "sh /tmp/df.sh"' 2>&1) + rc=$? + if [[ $rc -eq 124 || $rc -eq 137 ]]; then + echo "FAIL - podman run timed out after ${RUNTIME_TIMEOUT}s (labwc hang during the Deskflow case)" + grep -E '^(state|c1|c2|derr): |^[a-z0-9_]+=' <<<"$out" + podman rm -f "$name" >/dev/null 2>&1 + fail=1 + return + fi + local diag + diag="$(grep -E '^(state|derr): |^[a-z0-9_]+=' <<<"$out" | tr '\n' '|') client 1: $(grep '^c1: ' <<<"$out" | cut -c5- | tail -15 | tr '\n' '|')" + df_ok() { grep -qx "$1" <<<"$out"; } + df_check() { + if [[ $1 -eq 0 ]]; then + echo "ok - $2" + else + echo "FAIL - $2: $diag" + fail=1 + fi + } + df_ok head=yes && grep -Eq '^fp=v2:sha256:[0-9a-f]{64}$' <<<"$out" + df_check $? "the Deskflow daemon writes its fingerprint to the state file" + # Deskflow 1.26 logs only its NOTE and IPC lines here, so the refusal + # shows as a retry without "disconnected from server": a dropped + # connection logs that line, a refusal (EUNK) does not. + df_ok pending=yes && awk '/^c1: .*IPC: peer fingerprint/ && !p {p=NR; next} p && /IPC: disconnected from server/ && !c {d=1} + p && /IPC: connecting to/ {c=1} END {exit !(p && c && !d)}' <<<"$out" + df_check $? "a Deskflow client that trusts ThinFloe is refused with EUNK, tries again, and shows as pending with the fingerprint of its certificate" + df_ok connected=yes && grep -Eq $'^state: laptop\tv2:sha256:[0-9a-f]{64}\tconnected\t[0-9]+\t1280\t720\t' <<<"$out" + df_check $? "after the attach and a reload the client's next try connects, with its 1280x720 screen" + df_ok c1_log=yes + df_check $? "the Deskflow client logs that it connected to the server" + df_ok pending2=yes && df_ok still=yes && grep -Eq $'^state: laptop\tv2:sha256:[0-9a-f]{64}\tpending\t[0-9]+\t0\t0\tfp-changed$' <<<"$out" + df_check $? "a second 'laptop' with another certificate stays out as pending, fp-changed, and the first stays connected" + df_ok d_rc=0 && df_ok listening=no + df_check $? "'listen = false' and a reload end the daemon with 0 and nothing listens on 24800" +} +run_deskflow_pairing_case + + +# Deskflow forwarding and every way back, against the stock client of the +# pairing case, with two outputs: labwc puts HEADLESS-1 right of +# HEADLESS-2, so the right edge of HEADLESS-2 is not free (edge-busy) and +# the device is attached right of HEADLESS-1. What the device gets is what the client +# injects into labwc's Xwayland, seen through the RECORD extension +# (x11-probe.py --record: KEY, BUTTON, MOTION lines), since deskflow-core +# 1.26 logs no input; ThinFloe's side is wev, a Wayland window that has +# the keyboard focus whenever no capture has it. The daemon logs each +# release as 'thinfloe-deskflow: released ()'. Edge resistance is +# low (15 px): one move onto the edge does not capture, pushes of 10 px do. +# shellcheck disable=SC2016 # expands inside the container +fw_script='export TF_CONFIG_DIR=/tmp/tfcfg TF_DESKFLOW_STATE=/tmp/xdg/df.state TF_DESKFLOW_SOCKET=/tmp/xdg/df.sock +gen=$TF_CONFIG_DIR/generated/deskflow +mkdir -p $TF_CONFIG_DIR/generated +head="[deskflow]\nlisten = true\nport = 24800\nedge_resistance = \"low\"\n" +printf "$head" >$gen +upto() { n=$(($1 * 20)); shift; while [ $n -gt 0 ]; do "$@" && return 0; sleep 0.05; n=$((n - 1)); done; return 1; } +st() { cat $TF_DESKFLOW_STATE 2>/dev/null; } +state() { st | awk -F "\t" -v f="$c1" -v s="$1" "\$1 == \"laptop\" && \$2 == f && \$3 == s" | grep -q .; } +reload() { python3 -c "import socket, sys; socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM).sendto(b\"reload\n\", sys.argv[1])" $TF_DESKFLOW_SOCKET; } +attach() { printf "$head\n[[deskflow.device]]\nname = \"laptop\"\nfingerprint = \"%s\"\noutput = \"%s\"\nside = \"right-of\"\n" "$c1" "$1" >$gen; reload; } +run_client() { env -u WAYLAND_DISPLAY XDG_SESSION_TYPE=x11 QT_QPA_PLATFORM=offscreen \ + timeout 150 deskflow-core client --new-instance -s /tmp/c1/Deskflow.conf >>/tmp/c1/log 2>&1 & } +free_edge() { st | grep -q " connected [0-9]* [0-9]* [0-9]* $"; } +released() { grep -q "^thinfloe-deskflow: released ($1)$" /tmp/d.err; } +wev_has() { grep -q "sym: $1 " /tmp/wev.log; } +rec_has() { grep -qx "$1" /tmp/xrec; } +# Three pushes of 10 px, closer together than the 300 ms after which the +# resistance starts again. +push() { wlrctl pointer move 10 0; wlrctl pointer move 10 0; wlrctl pointer move 10 0; upto 2 state active; } +ms() { echo $(( ($(date +%s%N) - $1) / 1000000 )); } +stdbuf -oL wev -f wl_keyboard:key >/tmp/wev.log 2>&1 & +python3 /usr/local/bin/x11-probe.py --record 160 >/tmp/xrec 2>&1 & +thinfloe-menu --deskflow >/tmp/d.out 2>/tmp/d.err & +dpid=$! +upto 5 wlrctl toplevel find app_id:wev state:active && echo wev_focus=active || echo wev_focus=inactive +upto 15 sh -c "head -1 $TF_DESKFLOW_STATE 2>/dev/null | grep -q \"^self\"" +fp=$(st | head -1 | cut -f2) +mkdir -p /tmp/c1/tls +printf "[client]\nremoteHost=127.0.0.1\n[core]\nport=24800\ncomputerName=laptop\n[security]\ntlsEnabled=true\n" >/tmp/c1/Deskflow.conf +openssl req -x509 -newkey rsa:2048 -nodes -keyout /tmp/c1/key.pem -out /tmp/c1/cert.pem -days 30 -subj /CN=laptop 2>/dev/null +cat /tmp/c1/cert.pem /tmp/c1/key.pem >/tmp/c1/tls/deskflow.pem +echo "$fp" >/tmp/c1/tls/trusted-servers +c1="v2:sha256:$(openssl x509 -in /tmp/c1/cert.pem -outform DER | sha256sum | cut -d" " -f1)" +attach HEADLESS-2 +run_client +upto 15 state connected +st | grep -q " edge-busy$" && echo busy=yes || echo busy=no +attach HEADLESS-1 +upto 5 free_edge && echo connected=yes || echo connected=no +wlrctl pointer move -5000 -5000 +wlrctl pointer move 2559 360 +sleep 1 +state active && echo touch=active || echo touch=idle +push && echo push=active || echo push=idle +st | sed "s/^/pushstate: /" +sleep 0.3 +echo "mark=$(wc -l /tmp/fw.sh && + labwc -C /etc/thinfloe/labwc -S "sh /tmp/fw.sh"' 2>&1) + rc=$? + if [[ $rc -eq 124 || $rc -eq 137 ]]; then + echo "FAIL - podman run timed out after ${RUNTIME_TIMEOUT}s (labwc hang during the Deskflow forwarding case)" + grep -E '^(state|rec|wev|derr|c1|randr): |^[a-z0-9_]+=' <<<"$out" + podman rm -f "$name" >/dev/null 2>&1 + fail=1 + return + fi + local diag + diag="$(grep -E '^(state|rec|wev|derr|randr): |^[a-z0-9_]+=' <<<"$out" | tr '\n' '|') client: $(grep '^c1: ' <<<"$out" | cut -c5- | tail -8 | tr '\n' '|')" + fw_ok() { grep -qx "$1" <<<"$out"; } + fw_check() { + if [[ $1 -eq 0 ]]; then + echo "ok - $2" + else + echo "FAIL - $2: $diag" + fail=1 + fi + } + fw_ok busy=yes && fw_ok connected=yes + fw_check $? "a device at an edge that touches another output gets no strip and shows edge-busy; attached at a free edge it is connected" + fw_ok touch=idle + fw_check $? "touch_without_push_stays: one move onto the edge leaves the pointer on ThinFloe" + # After the mark: the entry at the left edge of the device, level with + # where the pointer left (y 360 of 720), then 40 right and 30 down + # (one more push of 10 may land after the lock). + local rec + rec=$(grep '^rec: ' <<<"$out" | cut -c6-) + fw_ok push=active && grep -Eq '^[0-9]+:MOTION 0 360$' <<<"$rec" && grep -Eq '^[0-9]+:MOTION (40|50) 390$' <<<"$rec" + fw_check $? "pointer_reaches_client: pushing into the edge moves the pointer onto the device at the matching height, and motion follows" + grep -qx 'BUTTON 1' <<<"$rec" && grep -qx 'BUTTON 2' <<<"$rec" && grep -qx 'BUTTON 3' <<<"$rec" && grep -qx 'BUTTON 5' <<<"$rec" + fw_check $? "the left, middle and right buttons reach the device as X buttons 1, 2 and 3, the wheel turned down as 5" + fw_ok xkey=yes && fw_ok xup=yes && fw_ok xlocal=no + fw_check $? "a key typed while captured reaches the device, goes up there again, and does not reach the local window" + fw_ok esc=released && fw_ok elocal=yes && fw_ok escfwd=no + fw_check $? "escape_chord_releases: Ctrl+Alt+Shift+Escape gives the keyboard back, and the device never sees the Escape" + local yms + yms=$(grep -o '^ylocal_ms=[0-9]*$' <<<"$out" | cut -d= -f2) + fw_ok push2=active && [[ -n "$yms" && $yms -le 1000 ]] + fw_check $? "client_killed_releases: a key reaches the local window within 1 s of the client's death (${yms:-never} ms)" + fw_ok push3=active && fw_ok gone=released && fw_ok gone_state=offline && fw_ok olocal=yes + fw_check $? "output_gone_releases: switching off the device's output while captured gives keyboard and pointer back at once, and the device shows offline" + fw_ok push4=active && fw_ok d_rc=0 && fw_ok term=released && fw_ok tlocal=yes && fw_ok c_disc=yes + fw_check $? "sigterm_while_captured: SIGTERM releases the capture, the daemon ends with 0, local keys work and the client disconnects" +} +run_deskflow_forward_case + +# Deskflow media keys, against the stock client of the pairing case: while +# the device has the keyboard the volume key goes to the device and the +# microphone mute key stays on ThinFloe. THINFLOE_VOLUME_KEYS=on composes +# the media key bindings with TF_OSD_KEY_CMD pointing at a recorder that +# appends its argument to /tmp/hits, and generated/deskflow says +# mic_mute_local = true (what the menu writes with the switch on), so the +# daemon runs the same recorder for the microphone key. While captured, +# XF86AudioRaiseVolume must reach the device (x11-probe.py --record sees +# the client's key; kKeyAudioUp, 0xE0AF) and not the recorder; +# XF86AudioMicMute must reach the recorder as mic-mute and not the device. +# After the escape chord the volume key runs its binding again. As in the +# forwarding case, a first x takes the client's keymap change. +# shellcheck disable=SC2016 # expands inside the container +mk_script='export TF_CONFIG_DIR=/tmp/tfcfg TF_DESKFLOW_STATE=/tmp/xdg/df.state TF_DESKFLOW_SOCKET=/tmp/xdg/df.sock +gen=$TF_CONFIG_DIR/generated/deskflow +head="mic_mute_local = true\n\n[deskflow]\nlisten = true\nport = 24800\nedge_resistance = \"low\"\n" +printf "$head" >$gen +upto() { n=$(($1 * 20)); shift; while [ $n -gt 0 ]; do "$@" && return 0; sleep 0.05; n=$((n - 1)); done; return 1; } +st() { cat $TF_DESKFLOW_STATE 2>/dev/null; } +state() { st | awk -F "\t" -v f="$c1" -v s="$1" "\$1 == \"laptop\" && \$2 == f && \$3 == s" | grep -q .; } +reload() { python3 -c "import socket, sys; socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM).sendto(b\"reload\n\", sys.argv[1])" $TF_DESKFLOW_SOCKET; } +released() { grep -q "^thinfloe-deskflow: released ($1)$" /tmp/d.err; } +rec_has() { grep -qx "$1" /tmp/xrec; } +hits() { tr "\n" " " /tmp/xrec 2>&1 & +thinfloe-menu --deskflow >/tmp/d.out 2>/tmp/d.err & +dpid=$! +upto 15 sh -c "head -1 $TF_DESKFLOW_STATE 2>/dev/null | grep -q \"^self\"" +fp=$(st | head -1 | cut -f2) +mkdir -p /tmp/c1/tls +printf "[client]\nremoteHost=127.0.0.1\n[core]\nport=24800\ncomputerName=laptop\n[security]\ntlsEnabled=true\n" >/tmp/c1/Deskflow.conf +openssl req -x509 -newkey rsa:2048 -nodes -keyout /tmp/c1/key.pem -out /tmp/c1/cert.pem -days 30 -subj /CN=laptop 2>/dev/null +cat /tmp/c1/cert.pem /tmp/c1/key.pem >/tmp/c1/tls/deskflow.pem +echo "$fp" >/tmp/c1/tls/trusted-servers +c1="v2:sha256:$(openssl x509 -in /tmp/c1/cert.pem -outform DER | sha256sum | cut -d" " -f1)" +printf "$head\n[[deskflow.device]]\nname = \"laptop\"\nfingerprint = \"%s\"\noutput = \"HEADLESS-1\"\nside = \"right-of\"\n" "$c1" >$gen +reload +env -u WAYLAND_DISPLAY XDG_SESSION_TYPE=x11 QT_QPA_PLATFORM=offscreen \ + timeout 80 deskflow-core client --new-instance -s /tmp/c1/Deskflow.conf >/tmp/c1/log 2>&1 & +upto 15 state connected +wlrctl pointer move -5000 -5000 +wlrctl pointer move 1279 360 +push && echo push=active || echo push=idle +wtype -s 300 x -s 500 +wtype -s 300 x -s 500 +wtype -s 300 -k XF86AudioRaiseVolume -s 500 +upto 5 rec_has "KEY XF86AudioRaiseVolume" && echo volfwd=yes || echo volfwd=no +sleep 0.5 +echo "hits_vol=$(hits)" +wtype -s 300 -k XF86AudioMicMute -s 500 +upto 5 hit mic-mute +echo "hits_mic=$(hits)" +rec_has "KEY XF86AudioMicMute" && echo micfwd=yes || echo micfwd=no +state active && echo still=active || echo still=idle +wtype -s 300 -M ctrl -M alt -M shift -k Escape -m shift -m alt -m ctrl +upto 5 released "escape chord" && echo esc=released || echo esc=held +wtype -s 300 -k XF86AudioRaiseVolume -s 300 +upto 5 hit volume-up +echo "hits_after=$(hits)" +kill -TERM $dpid +wait $dpid +echo d_rc=$? +sed "s/^/rec: /" /tmp/xrec | grep -v "^rec: MOTION\|^rec: XTEST 6 " | head -40 +sed "s/^/derr: /" /tmp/d.err | head -40 +sed "s/^/c1: /" /tmp/c1/log | tail -20 +exit 0' +run_deskflow_media_case() { + local name="thinfloe-runtime-test-mk-$$" rc out mount=() + [[ -n "${TF_RUNTIME_MENU:-}" ]] && mount=(-v "$TF_RUNTIME_MENU:/usr/bin/thinfloe-menu:ro") + out=$(timeout --kill-after=10 "$RUNTIME_TIMEOUT" podman run --rm --log-driver=none --name "$name" \ + "${mount[@]}" \ + -e WLR_BACKENDS=headless \ + -e WLR_HEADLESS_OUTPUTS=1 \ + -e WLR_RENDERER=pixman \ + -e XDG_RUNTIME_DIR=/tmp/xdg \ + -e TF_OSD_KEY_CMD="sh /tmp/rec.sh" \ + -e MK_SCRIPT="$mk_script" \ + "$IMAGE" \ + sh -c 'mkdir -p /tmp/xdg /tmp/tfcfg/generated && chmod 700 /tmp/xdg && touch /tmp/hits && + printf "echo \"\$1\" >>/tmp/hits\n" >/tmp/rec.sh && + printf "%s\n" "$MK_SCRIPT" >/tmp/mk.sh && + printf "THINFLOE_VOLUME_KEYS=on\n" >/tmp/tfcfg/generated/environment && + thinfloe-compose-labwc-config /etc/thinfloe/labwc /tmp/tfcfg/generated/environment /nonexistent /tmp/xdg/thinfloe-labwc && + labwc -C /tmp/xdg/thinfloe-labwc -S "sh /tmp/mk.sh"' 2>&1) + rc=$? + if [[ $rc -eq 124 || $rc -eq 137 ]]; then + echo "FAIL - podman run timed out after ${RUNTIME_TIMEOUT}s (labwc hang during the Deskflow media key case)" + grep -E '^(rec|derr|c1): |^[a-z0-9_]+=' <<<"$out" + podman rm -f "$name" >/dev/null 2>&1 + fail=1 + return + fi + local diag + diag="$(grep -E '^(rec|derr): |^[a-z0-9_]+=' <<<"$out" | tr '\n' '|') client: $(grep '^c1: ' <<<"$out" | cut -c5- | tail -8 | tr '\n' '|')" + mk_ok() { grep -qx "$1" <<<"$out"; } + mk_check() { + if [[ $1 -eq 0 ]]; then + echo "ok - $2" + else + echo "FAIL - $2: $diag" + fail=1 + fi + } + mk_ok push=active && mk_ok volfwd=yes && mk_ok 'hits_vol=' + mk_check $? "while a device has the keyboard the volume key reaches the device and runs no ThinFloe binding" + mk_ok 'hits_mic=mic-mute ' && mk_ok micfwd=no && mk_ok still=active + mk_check $? "while a device has the keyboard the microphone mute key mutes ThinFloe (mic-mute) and the device sees nothing" + mk_ok esc=released && mk_ok 'hits_after=mic-mute volume-up ' && mk_ok d_rc=0 + mk_check $? "after the escape chord the volume key runs ThinFloe's binding again" +} +run_deskflow_media_case + +# Deskflow clipboard, against the stock client of the pairing case. The +# client runs on an Xvfb of its own: on labwc's Xwayland the compositor +# itself would carry the text between the X and the Wayland clipboard, and +# the case would pass without Deskflow. The client's clipboard is read and +# set with xclip on that display. The 1.26 X11 client notices a copy on +# its side only when it owned the clipboard before (the SelectionClear it +# gets), so (b) runs after (a) made it the owner; it sends the text on +# leave. The pointer goes back by moving left past the device's edge +# ('released (back)'). +# shellcheck disable=SC2016 # expands inside the container +cb_script='export TF_CONFIG_DIR=/tmp/tfcfg TF_DESKFLOW_STATE=/tmp/xdg/df.state TF_DESKFLOW_SOCKET=/tmp/xdg/df.sock +gen=$TF_CONFIG_DIR/generated/deskflow +mkdir -p $TF_CONFIG_DIR/generated +head="[deskflow]\nlisten = true\nport = 24800\nedge_resistance = \"low\"\n" +printf "$head" >$gen +upto() { n=$(($1 * 20)); shift; while [ $n -gt 0 ]; do "$@" && return 0; sleep 0.05; n=$((n - 1)); done; return 1; } +st() { cat $TF_DESKFLOW_STATE 2>/dev/null; } +state() { st | awk -F "\t" -v f="$c1" -v s="$1" "\$1 == \"laptop\" && \$2 == f && \$3 == s" | grep -q .; } +reload() { python3 -c "import socket, sys; socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM).sendto(b\"reload\n\", sys.argv[1])" $TF_DESKFLOW_SOCKET; } +attach() { printf "$head\n[[deskflow.device]]\nname = \"laptop\"\nfingerprint = \"%s\"\noutput = \"HEADLESS-1\"\nside = \"right-of\"\nclipboard = %s\n" "$c1" "$1" >$gen; reload; } +xc() { DISPLAY=:99 xclip -o -selection clipboard 2>/dev/null; } +xc_is() { [ "$(xc)" = "$1" ]; } +wl_is() { [ "$(wl-paste -n /dev/null)" = "$1" ]; } +backs() { grep -c "^thinfloe-deskflow: released (back)$" /tmp/d.err; } +enter() { wlrctl pointer move -5000 -5000; wlrctl pointer move 1279 360 + wlrctl pointer move 10 0; wlrctl pointer move 10 0; wlrctl pointer move 10 0; upto 2 state active; } +back_after() { [ "$(backs)" -gt "$1" ]; } +leave() { b=$(backs); wlrctl pointer move -100 0; upto 3 back_after $b && upto 3 state connected; } +Xvfb :99 -screen 0 1280x720x24 -nolisten tcp >/tmp/xvfb.log 2>&1 & +thinfloe-menu --deskflow >/tmp/d.out 2>/tmp/d.err & +upto 15 sh -c "head -1 $TF_DESKFLOW_STATE 2>/dev/null | grep -q \"^self\"" +fp=$(st | head -1 | cut -f2) +mkdir -p /tmp/c1/tls +printf "[client]\nremoteHost=127.0.0.1\n[core]\nport=24800\ncomputerName=laptop\n[security]\ntlsEnabled=true\n" >/tmp/c1/Deskflow.conf +openssl req -x509 -newkey rsa:2048 -nodes -keyout /tmp/c1/key.pem -out /tmp/c1/cert.pem -days 30 -subj /CN=laptop 2>/dev/null +cat /tmp/c1/cert.pem /tmp/c1/key.pem >/tmp/c1/tls/deskflow.pem +echo "$fp" >/tmp/c1/tls/trusted-servers +c1="v2:sha256:$(openssl x509 -in /tmp/c1/cert.pem -outform DER | sha256sum | cut -d" " -f1)" +attach true +upto 5 test -e /tmp/.X11-unix/X99 +env -u WAYLAND_DISPLAY XDG_SESSION_TYPE=x11 QT_QPA_PLATFORM=offscreen DISPLAY=:99 \ + timeout 90 deskflow-core client --new-instance -s /tmp/c1/Deskflow.conf >/tmp/c1/log 2>&1 & +upto 15 state connected && echo connected=yes || echo connected=no +printf "from thinfloe" | wl-copy +sleep 0.5 +enter && echo a_enter=active || echo a_enter=idle +upto 5 xc_is "from thinfloe" && echo a_clip=yes || echo a_clip=no +echo "a_seen=$(xc)" +printf "from laptop" | DISPLAY=:99 xclip -i -selection clipboard >/dev/null 2>&1 +sleep 0.5 +leave && echo b_leave=yes || echo b_leave=no +upto 5 wl_is "from laptop" && echo b_paste=yes || echo b_paste=no +echo "b_seen=$(wl-paste -n /dev/null)" +attach false +sleep 0.5 +printf "not for the laptop" | wl-copy +sleep 0.5 +enter && echo c_enter=active || echo c_enter=idle +sleep 1.5 +echo "c_seen=$(xc)" +leave && echo c_leave=yes || echo c_leave=no +st | sed "s/^/state: /" +sed "s/^/derr: /" /tmp/d.err | head -40 +sed "s/^/c1: /" /tmp/c1/log | tail -20 +sed "s/^/xvfb: /" /tmp/xvfb.log | tail -5 +exit 0' +run_deskflow_clipboard_case() { + local name="thinfloe-runtime-test-cb-$$" rc out mount=() + [[ -n "${TF_RUNTIME_MENU:-}" ]] && mount=(-v "$TF_RUNTIME_MENU:/usr/bin/thinfloe-menu:ro") + out=$(timeout --kill-after=10 "$RUNTIME_TIMEOUT" podman run --rm --log-driver=none --name "$name" \ + "${mount[@]}" \ + -e WLR_BACKENDS=headless \ + -e WLR_HEADLESS_OUTPUTS=1 \ + -e WLR_RENDERER=pixman \ + -e XDG_RUNTIME_DIR=/tmp/xdg \ + -e CB_SCRIPT="$cb_script" \ + "$IMAGE" \ + sh -c 'mkdir -p /tmp/xdg && chmod 700 /tmp/xdg && + printf "%s\n" "$CB_SCRIPT" >/tmp/cb.sh && + labwc -C /etc/thinfloe/labwc -S "sh /tmp/cb.sh"' 2>&1) + rc=$? + if [[ $rc -eq 124 || $rc -eq 137 ]]; then + echo "FAIL - podman run timed out after ${RUNTIME_TIMEOUT}s (labwc hang during the Deskflow clipboard case)" + grep -E '^(state|derr|c1|xvfb): |^[a-z0-9_]+=' <<<"$out" + podman rm -f "$name" >/dev/null 2>&1 + fail=1 + return + fi + local diag + diag="$(grep -E '^(state|derr|xvfb): |^[a-z0-9_]+=' <<<"$out" | tr '\n' '|') client: $(grep '^c1: ' <<<"$out" | cut -c5- | tail -8 | tr '\n' '|')" + cb_ok() { grep -qx "$1" <<<"$out"; } + cb_check() { + if [[ $1 -eq 0 ]]; then + echo "ok - $2" + else + echo "FAIL - $2: $diag" + fail=1 + fi + } + cb_ok connected=yes && cb_ok a_enter=active && cb_ok a_clip=yes + cb_check $? "clipboard_to_device: a text copied on ThinFloe is on the device's clipboard once the pointer enters it" + cb_ok b_leave=yes && cb_ok b_paste=yes + cb_check $? "clipboard_from_device: a text copied on the device while the pointer is there is on ThinFloe's clipboard once the pointer comes back" + cb_ok c_enter=active && cb_ok 'c_seen=from laptop' && cb_ok c_leave=yes + cb_check $? "clipboard_switch_off: with clipboard = false the device's clipboard keeps its own text when the pointer enters it" +} +run_deskflow_clipboard_case + +# The menu runs the Deskflow daemon (spec, Processes): with '[deskflow] +# listen = true' in config.toml it starts 'thinfloe-menu --deskflow' in a +# process group of its own, which listens on 24800. Log out (exit 0) and +# Restart (exit 10) end the daemon before the menu's status reaches the +# session; a menu killed with SIGKILL takes it along (PR_SET_PDEATHSIG); +# a daemon killed with SIGKILL is started again after the first back-off +# of 1 s. After an exit 0 or 10 the daemon is gone already: the menu +# waited for it. The only tile is the one clicked (the centre of the grid's first +# row, 640,240 on the 1280x720 output); TF_SAVE_HOME=/bin/true is a save +# that succeeds. +# shellcheck disable=SC2016 # expands inside the container +lc_script='export TF_CONFIG_DIR=/tmp/tfcfg TF_MENU_SHIPPED_DIR=/tmp/tiles TF_MENU_USER_DIR=/tmp/utiles TF_SAVE_HOME=/bin/true TF_STATE_DIR=/tmp/state +mkdir -p $TF_CONFIG_DIR /tmp/tiles /tmp/utiles /tmp/state +printf "[deskflow]\nlisten = true\nport = 24800\n" >$TF_CONFIG_DIR/config.toml +upto() { n=$(($1 * 10)); shift; while [ $n -gt 0 ]; do "$@" && return 0; sleep 0.1; n=$((n - 1)); done; return 1; } +daemon() { pgrep -f "^/usr/bin/thinfloe-menu --deskflow\$"; } +up() { daemon >/dev/null && ss -Hltn "sport = :24800" | grep -q .; } +down() { ! daemon >/dev/null && ! ss -Hltn "sport = :24800" | grep -q .; } +fresh() { p=$(daemon) && [ "$p" != "$d" ]; } +tile() { printf "[Desktop Entry]\nType=Application\nName=%s\nIcon=log-out\nX-TF-Action=%s\n" "$1" "$2" >/tmp/tiles/90-end.desktop; } +start() { thinfloe-menu >>/tmp/m.err 2>&1 & mpid=$!; } +click() { wlrctl pointer move -5000 -5000; wlrctl pointer move 640 240; wlrctl pointer click left; } +tile "Log out" logout +start +upto 15 up && echo up1=yes || echo up1=no +d=$(daemon) +[ -n "$d" ] && [ "$(ps -o pgid= -p "$d" | tr -d " ")" = "$d" ] && echo group=yes || echo group=no +click +wait $mpid +echo logout_rc=$? +down && echo logout_gone=yes || echo logout_gone=no +tile Restart reboot +start +upto 15 up && echo up2=yes || echo up2=no +click +wait $mpid +echo restart_rc=$? +down && echo restart_gone=yes || echo restart_gone=no +start +upto 15 up && echo up3=yes || echo up3=no +kill -9 $mpid +upto 2 down && echo killed_gone=yes || echo killed_gone=no +start +upto 15 up && echo up4=yes || echo up4=no +d=$(daemon) +kill -9 "$d" +upto 2 fresh && echo again=yes || echo again=no +upto 5 up && echo up5=yes || echo up5=no +kill $mpid +wait $mpid +upto 2 down && echo end_gone=yes || echo end_gone=no +sed "s/^/merr: /" /tmp/m.err | grep -v "^merr: thinfloe-menu: icon" | tail -30 +exit 0' +run_deskflow_lifecycle_case() { + local name="thinfloe-runtime-test-lc-$$" rc out mount=() + [[ -n "${TF_RUNTIME_MENU:-}" ]] && mount=(-v "$TF_RUNTIME_MENU:/usr/bin/thinfloe-menu:ro") + out=$(timeout --kill-after=10 "$RUNTIME_TIMEOUT" podman run --rm --log-driver=none --name "$name" \ + "${mount[@]}" \ + -e WLR_BACKENDS=headless \ + -e WLR_HEADLESS_OUTPUTS=1 \ + -e WLR_RENDERER=pixman \ + -e XDG_RUNTIME_DIR=/tmp/xdg \ + -e LC_SCRIPT="$lc_script" \ + "$IMAGE" \ + sh -c 'mkdir -p /tmp/xdg && chmod 700 /tmp/xdg && + printf "%s\n" "$LC_SCRIPT" >/tmp/lc.sh && + labwc -C /etc/thinfloe/labwc -S "sh /tmp/lc.sh"' 2>&1) + rc=$? + if [[ $rc -eq 124 || $rc -eq 137 ]]; then + echo "FAIL - podman run timed out after ${RUNTIME_TIMEOUT}s (labwc hang during the Deskflow lifecycle case)" + grep -E '^merr: |^[a-z0-9_]+=' <<<"$out" + podman rm -f "$name" >/dev/null 2>&1 + fail=1 + return + fi + local diag + diag="$(grep -E '^merr: |^[a-z0-9_]+=' <<<"$out" | tr '\n' '|')" + lc_ok() { grep -qx "$1" <<<"$out"; } + lc_check() { + if [[ $1 -eq 0 ]]; then + echo "ok - $2" + else + echo "FAIL - $2: $diag" + fail=1 + fi + } + lc_ok up1=yes && lc_ok group=yes + lc_check $? "deskflow_lifecycle: with listen = true the menu runs 'thinfloe-menu --deskflow' in a process group of its own, listening on 24800" + lc_ok up1=yes && lc_ok logout_rc=0 && lc_ok logout_gone=yes + lc_check $? "deskflow_lifecycle: after Log out (exit 0) no --deskflow process and no listener on 24800" + lc_ok up2=yes && lc_ok restart_rc=10 && lc_ok restart_gone=yes + lc_check $? "deskflow_lifecycle: after Restart (exit 10) no --deskflow process and no listener on 24800" + lc_ok up3=yes && lc_ok killed_gone=yes + lc_check $? "deskflow_lifecycle: a menu killed with SIGKILL takes the daemon along within 2 s" + lc_ok up4=yes && lc_ok again=yes && lc_ok up5=yes + lc_check $? "deskflow_lifecycle: a daemon killed with SIGKILL is started again within 2 s and listens again" + lc_ok up5=yes && lc_ok end_gone=yes + lc_check $? "deskflow_lifecycle: a menu ended by SIGTERM leaves no daemon behind" +} +run_deskflow_lifecycle_case + exit $fail diff --git a/test/runtime/x11-probe.py b/test/runtime/x11-probe.py index f082a85..9ca64ec 100644 --- a/test/runtime/x11-probe.py +++ b/test/runtime/x11-probe.py @@ -15,6 +15,17 @@ With --buttons it prints "BUTTON " (window coordinates) for every mouse button press, and with --hold SECONDS it stays fullscreen that long after printing GEOMETRY. +With --fullscreen and --keys the window asks for fullscreen before it +prints the keys. +With --record SECONDS it maps no window: it prints what any client makes +the X server do for that long, through the RECORD extension, whichever +window would get it: "KEY " for a key press, "KEYUP " for its release, "BUTTON " and "BUTTONUP " for a button, +"MOTION " (root coordinates) for pointer motion, and "XTEST +" for each XTestFakeInput request a client makes (type 2/3 key +press/release, 4/5 button press/release, 6 motion), whether or not the +server turns it into an event. +The Deskflow client injects what it receives that way (XTest). """ import sys import time @@ -30,6 +41,7 @@ if "--background" in sys.argv: background = int(sys.argv[sys.argv.index("--background") + 1], 16) buttons = "--buttons" in sys.argv +fullscreen_keys = "--fullscreen" in sys.argv hold = 0.0 if "--hold" in sys.argv: hold = float(sys.argv[sys.argv.index("--hold") + 1]) @@ -49,6 +61,61 @@ def keysym_name(keysym): return "0x%x" % keysym +def record(seconds): + import os + import threading + + from Xlib.ext import record as rec + from Xlib.protocol import rq + + ctl = display.Display() + names = display.Display() + XK.load_keysym_group("xf86") + xtest = ctl.query_extension("XTEST").major_opcode + ctx = ctl.record_create_context(0, [rec.AllClients], [{ + "core_requests": (0, 0), "core_replies": (0, 0), + "ext_requests": (xtest, xtest, 2, 2), "ext_replies": (0, 0, 0, 0), + "delivered_events": (0, 0), + "device_events": (X.KeyPress, X.MotionNotify), + "errors": (0, 0), "client_started": False, "client_died": False}]) + + def seen(reply): + if reply.category == rec.FromClient and not reply.client_swapped: + # XTestFakeInput requests, several to a reply: type, detail. + d = bytearray(reply.data) + while len(d) > 5: + n = (d[2] | d[3] << 8) * 4 or len(d) + if d[0] == xtest: + print("XTEST %d %d" % (d[4], d[5]), flush=True) + d = d[n:] + return + if reply.category != rec.FromServer or reply.client_swapped: + return + data = reply.data + while len(data): + e, data = rq.EventField(None).parse_binary_value( + data, ctl.display, None, None) + if e.type == X.KeyPress: + # The client may change the keyboard mapping: ask the server. + sym = names.get_keyboard_mapping(e.detail, 1)[0][0] + print("KEY " + keysym_name(sym), flush=True) + elif e.type == X.KeyRelease: + sym = names.get_keyboard_mapping(e.detail, 1)[0][0] + print("KEYUP " + keysym_name(sym), flush=True) + elif e.type == X.ButtonPress: + print("BUTTON %d" % e.detail, flush=True) + elif e.type == X.ButtonRelease: + print("BUTTONUP %d" % e.detail, flush=True) + elif e.type == X.MotionNotify: + print("MOTION %d %d" % (e.root_x, e.root_y), flush=True) + + threading.Timer(seconds, lambda: os._exit(0)).start() + ctl.record_enable_context(ctx, seen) + + +if "--record" in sys.argv: + record(float(sys.argv[sys.argv.index("--record") + 1])) + d = display.Display() screen = d.screen() # With --keys the window needs content: an X window without a background @@ -87,7 +154,21 @@ def keysym_name(keysym): d.change_keyboard_mapping(9, syms) d.sync() +def ask_fullscreen(): + net_wm_state = d.intern_atom("_NET_WM_STATE") + fullscreen = d.intern_atom("_NET_WM_STATE_FULLSCREEN") + # _NET_WM_STATE_ADD = 1, source = 1 (normal application) + d.screen().root.send_event( + event.ClientMessage(window=win, client_type=net_wm_state, + data=(32, [1, fullscreen, 0, 1, 0])), + event_mask=X.SubstructureRedirectMask | X.SubstructureNotifyMask) + d.sync() + time.sleep(2) + + if keys is not None: + if fullscreen_keys: + ask_fullscreen() win.change_attributes(event_mask=X.StructureNotifyMask | X.KeyPressMask) d.sync() end = time.monotonic() + keys @@ -103,15 +184,7 @@ def keysym_name(keysym): time.sleep(0.05) sys.exit(0) -net_wm_state = d.intern_atom("_NET_WM_STATE") -fullscreen = d.intern_atom("_NET_WM_STATE_FULLSCREEN") -# _NET_WM_STATE_ADD = 1, source = 1 (normal application) -d.screen().root.send_event( - event.ClientMessage(window=win, client_type=net_wm_state, - data=(32, [1, fullscreen, 0, 1, 0])), - event_mask=X.SubstructureRedirectMask | X.SubstructureNotifyMask) -d.sync() -time.sleep(2) +ask_fullscreen() geom = win.get_geometry() print("GEOMETRY %dx%d" % (geom.width, geom.height), flush=True) diff --git a/test/unit/test_upgrade_image.py b/test/unit/test_upgrade_image.py index 398a6e9..144bf20 100644 --- a/test/unit/test_upgrade_image.py +++ b/test/unit/test_upgrade_image.py @@ -424,6 +424,19 @@ def test_fresh_copy_leaves_out_the_attic_identity(self): ) self.assertIn("./.config/thinfloe/password", members) + def test_fresh_install_skips_deskflow_identity(self): + argv = ui.home_archive_argv(str(self.home), str(self.dest), "new") + self.assertIn("--exclude=./.config/thinfloe/deskflow", argv) + dfdir = self.home / ".config" / "thinfloe" / "deskflow" + dfdir.mkdir(parents=True) + (dfdir / "identity.pem").write_text("PRIVATE KEY") + (self.home / ".config" / "thinfloe" / "password").write_text("hash\n") + subprocess.run(argv, check=True) + with tarfile.open(self.dest, "r:gz") as tf: + members = tf.getnames() + self.assertEqual([m for m in members if "deskflow" in m], []) + self.assertIn("./.config/thinfloe/password", members) + def test_no_exclude_file_at_all_still_archives(self): self.assertIn("./.keep/f", self._members())