An open-source remote desktop application designed for self-hosting, as an alternative to TeamViewer. https://rustdesk.com
  • Rust 68.2%
  • Dart 23.4%
  • C++ 1.9%
  • Python 1.8%
  • C 1.5%
  • Other 3%
Find a file
Repository files (latest commit first)
Filename Latest commit message Latest commit date
Mariano Abad ddad47925c
feat(linux): DRM/KMS direct capture for Wayland — no portal consent required (#15420)
* feat(drm): opt-in DRM/KMS screen capture for Linux/Wayland

adds an opt-in `drm` feature for unattended remote access on Wayland: it
captures below the compositor via libdrmtap, so there is no
xdg-desktop-portal consent dialog and it works at the login screen.

off by default. when the feature is off the build is byte-identical.
everything is gated behind feature = "drm" or lives only in the separate
rustdesk-unattended-wayland deb, whose package name is the informed consent.

architecture (agreed with the maintainer): the capture runs inside the root
--service, which already holds the privilege it needs, and streams frames to
the user --server over a service-scoped _drm ipc channel. libdrmtap is loaded
with dlopen at runtime (no link-time dependency, so the base build is
unchanged and it still runs on ubuntu 18), and the .so is built in ci from the
rustdesk-org/libdrmtap fork and shipped only in the drm deb. no setcap helper.

- service: DrmReader reads scanout directly via the dlopen loader; an
  IpcDrmCapturer serves _drm consumers with a per-connection capture worker;
  durable availability cache + pre-warm to avoid enumerate/re-probe restarts
- capture: multi-display (targets the selected crtc), hardware cursor over
  _drm, transient-errno retry with a bounded stall, rejects non-32bpp scanouts
  before the frame copy
- robustness: only active, crtc-bound outputs are offered (an unbound
  crtc_id=0 connector is filtered and a client-selected 0 is refused, both
  fall back to pipewire); a per-display rapid-rebuild guard demotes a flapping
  display to pipewire; per-display (not global) zero-frame failure tracking
- root-service hardening: bounded frame allocation and a concurrent-connection
  cap so a malformed scanout or a buggy consumer cannot OOM or thread-exhaust
  the service; a negative availability verdict expires so displays that appear
  after startup recover without a --server restart; exactly-one .so selection
  in the packaging so a stale object is never silently shipped
- build: libdrmtap.so cloned at build time from rustdesk-org/libdrmtap main
  and bundled only for the --drm deb; ci builds a separate
  rustdesk-unattended-wayland deb (incl. an ubuntu 18.04 container)
- DRM_CAPTURE_SECURITY.md: threat model and hardening notes

* feat(drm): phase-2 split, pass the dma-buf fd instead of the converted frame

move the egl detile and rgba pack out of the root --service and into the
unprivileged --server. the root now calls only drmtap_open + drmtap_grab_desc
and exports a raw dma-buf fd; the fd rides the _drm channel over SCM_RIGHTS with
a small descriptor (geometry, per-plane offsets/pitches, modifier, hdr) instead
of the full rgba frame, dropping the per-frame copy. the --server imports the fd
with drmtap_open_render + drmtap_convert_dmabuf, keyed by the import-once egl
cache, and the render context is created and dropped on the recv thread.

the _drm transport moves off Framed<BytesCodec> (which cannot carry a fd) to a
bespoke sendmsg/recvmsg framing (DrmConn) that attaches one SCM_RIGHTS cmsg only
when a fd is present and rejects a truncated ancillary message. the split
symbols are bound optionally so an older libdrmtap still loads the cpu path, and
the whole thing degrades to the cpu BGRA path or PipeWire when no render node is
available. pins libdrmtap-sys to =0.4.13 with the Cargo.lock checksum. folds in
the DP-MST, ldconfig-restart and per-display PipeWire-fallback review fixes and a
udev hotplug refresh.

* drm: address the phase-2 split review

1- do not depend on the libdrmtap-sys crate for the pin: its build.rs statically
compiles the whole libdrmtap C tree and a CAP_SYS_ADMIN helper and links
-ldrm/-lseccomp/-lcap, which defeats the runtime-dlopen model. keep drm a pure
dlopen backend and pin the .so by the build.py DRMTAP_REF release tag, guarded by
a strict vX.Y.Z regex. drops the now-moot Cargo.lock freshness CI checks.
2- render-node-less consumers no longer lose the stream: the --server signals
need_cpu on DrmStart when it cannot open a convert context, and the --service
streams the CPU-converted frame path for that connection instead of a dma-buf fd
the consumer cannot detile (which used to fall through to a PipeWire path nobody
can approve on an unattended seat).
3- mark PipeWire initialized only after every per-display capturer is created, so
a partial failure retries instead of the flag falsely reporting a complete init.
4- reject a degenerate (zero width/height) or short CPU frame before it reaches
PixelBuffer::new (which derives stride as data.len()/height, dividing by zero).
5- keep the export-ledger epoch at DRM_DISPLAY_GENERATION so a hotplug invalidates
cached buffers (elision stays off until the recycled-fb_id inode case is handled).
6- validate the udev uevent source (kernel nl_pid, multicast) with recvmsg so a
local process cannot unicast a spoofed drm-change event to the root listener.

* drm: second review pass on the phase-2 split

1- make PipeWire init atomic: build every per-display capturer into owned staging
first and publish them to CAP_DISPLAY_INFO only after all succeed, so a mid-loop
Capturer::new failure neither leaves partial entries (which the next check_init
would treat as already-initialized) nor leaks the raw pointers already created.
2- pin the immutable libdrmtap commit, not just the tag: git clone --branch
follows a mutable tag, so verify the cloned HEAD equals DRMTAP_SHA in both the CI
workflow and build.py, failing on a moved/compromised tag.
3- drop the stale comment claiming a libdrmtap-sys crate pin (the drm backend has
no such dependency).

* drm: harden the libdrmtap source pin

1- verify the commit-SHA pin on a reused checkout too, not only on a fresh clone:
a stale or mismatched third_party/libdrmtap (e.g. from a failed clone) is now
removed and the build fails instead of silently reusing unpinned source.
2- default DRMTAP_REPO to the fork that actually publishes the pinned tag, so a
clean git clone --branch v0.4.13 resolves (and to the expected commit) instead of
failing on a repo that does not carry the tag.

* ci: make the pinned libdrmtap commit SHA literal

do not let an inherited DRMTAP_SHA override the verified commit in CI, so the
tag/commit pair is immutable there. build.py keeps the env override for local
forks.

* drm: only SHA-verify a git libdrmtap checkout, not a local source tree

gate the commit-SHA pin check on third_party/libdrmtap being a git checkout, so a
clone (fresh, reused, or a stale/failed one) is still verified, but a non-git
source tree a developer placed there on purpose to build unreleased local
libdrmtap is used as-is (it has no tag to verify).

* build: request the libdrmtap shared_library target explicitly

since libdrmtap 0.4.11 the project builds both a shared object and a static
archive, so 'meson compile drmtap' is ambiguous. ask for drmtap:shared_library
(rustdesk dlopens the .so and never links the archive).

* drm: do not reject a non-BGRA scanout on the export side

grab_desc exports the raw scanout dma-buf; the unprivileged converter handles
every format libdrmtap supports (10-bit XR30/AR30 with tone mapping, HDR, CCS)
down to RGBA. The fourcc gate copied from the CPU-mapped grab() wrongly closed
the _drm stream for a 10-bit XR30 primary (0x30335258) that convert_dmabuf
converts fine -- observed live on an i915 seat scanning out XRGB2101010. Keep
the gate only on grab(), whose frame.format is already the converted BGRA.

* drm: do not restart-loop a demoted display PipeWire cannot serve

DRM and PipeWire do not share a display-index space: DRM enumerates one entry
per connector while the portal often exposes a single whole-desktop stream at
index 0. When a per-display DRM capture was demoted to PipeWire for a non-primary
DRM index, cap_map.get(&display_idx) was None and the bail Err made
ServiceTmpl::run retry get_capturer every 1s forever (a multi-monitor restart
loop, latent until a display demotes). Degrade to the whole-desktop stream
(index 0) PipeWire does provide instead of spinning. Healthy DRM displays return
before this and are unaffected.

* ci: build the libdrmtap shared_library target explicitly

the CI .so-prebuild step used the same bare 'drmtap' meson target that is
ambiguous since libdrmtap became both_libraries (0.4.11); ask for
drmtap:shared_library, matching build.py.

* drm: stop altering the stock (drm-off) Wayland path (review 3.2, 4.6)

3.2: get_capturer_for_display no longer falls back to cap_map[0] for a missing
index. CapturerPtr is a bare *mut Capturer cloned by raw-pointer copy, so aliasing
one entry to two display_idx values let two video-service threads call frame() on
the same Recorder unsynchronised (data race / UB), reachable in a plain build via
CaptureDisplays{set:[0,3]}. Restore the exact-index lookup + bail; a demoted DRM
index is dropped from the advertised list at the source instead.
4.6: revert check_init to upstream (flag set before the per-display loop, direct
insert). The staged-all-or-nothing variant turned a partial per-display failure
into a permanent 1Hz retry loop and was not drm-gated. Both restore the drm-off
build to byte-identical with upstream.

* drm: address review findings 3.1, 4.2, 4.3, 4.4, 4.7 + minors

3.1: snapshot the stock flutter bundle before the CI drm relink and restore it
before makepkg, so the official Arch package ships the stock cdylib, not the
drm-enabled one. 4.2: wrap the drm block in a failure-tolerant subshell so a
drm-only failure no longer aborts the stock deb/rpm/arch publish. 4.3: narrow the
publish glob to rustdesk-[0-9]*.deb so the consent-bypass unattended-wayland deb
stays an artifact, not on the public release. 4.4: rewrite the three stale
DRM_CAPTURE_SECURITY.md statements to the split (default path passes a read-only
scanout dma-buf fd over SCM_RIGHTS with an import-once cache; export validation is
metadata-only; BGRA-over-the-wire is the fallback) and document that grab_desc's
fd is O_RDONLY (DRM_RDWR dropped upstream, dup preserves it). 4.7: only
short-circuit to the DRM cursor when it is authoritative (visible, or hidden in a
pure-DRM session); fall through to the normal cursor path in a mixed
DRM+PipeWire session. minors: thread the deb variant by feature not glob; TODO
for the ld.so.conf.d system path; drop a stray blank line. All gated or
whitespace so the drm-off build stays byte-identical.

* drm: re-authorize the _drm stream per frame and auth the producer (review 3.3, 4.1)

3.3: DRM/KMS capture is not session-scoped -- the worker grabs a CRTC's physical
scanout regardless of which session owns the display -- but the peer was
authorized only once at accept. Capture the peer uid and re-check it at the top of
the forward loop: root is always allowed, any other peer must still be the
active-session uid, fail closed otherwise. A session change now tears the stream
down within one frame (~33ms) instead of leaking the incoming user's screen to the
outgoing user's --server.
4.1: connect_drm accepted any producer. Reject a non-root peer (peer_uid != 0) so a
process that won the socket-path race cannot feed the consumer a display list,
frames and dma-buf fds while the DRM path suppresses the portal consent prompt.

* drm: validate cursor body length and coalesce _drm frames to latest-wins (review 4.1, 4.8)

4.1: the DrmCursor consumer handed the wire body straight to the client, which
renders width*height*4 RGBA bytes. Reject a body shorter than that so a truncated
cursor cannot make the client read past the buffer. The hidden-cursor sentinel is
0x0 with an empty body, for which the bound is 0 and the check is a no-op.
4.8: the _drm socket is a FIFO, so a consumer that drains slower than we produce
(a 4K convert on a modest GPU) fell seconds behind stale frames. Drain the producer
channel without blocking each tick and forward only the newest frame; replaced
frames drop in place, closing the zero-copy OwnedFd and freeing the CPU-path pixel
buffer. Cursor updates stay in order and are never coalesced away.

* drm: keep the demoted-display list consistent instead of stretching PipeWire (review 4.5)

A DRM display demoted to PipeWire has no geometry-consistent per-connector stream
on a multi-monitor host -- the portal exposes a single whole-desktop stream. The
fallthrough served that whole-desktop frame while the list still advertised the
demoted connector geometry, so the client stretched the frame and offset all input
by the connector origin (the primary-index-0 demotion reaches this even after the
get_capturer_for_display exact-index fix).

Dropping the display from the list is not an option: its position IS the capturer
index, so a drop would shift every later display and desync get_capturer_info. So
instead: get_display_infos advertises a multi-monitor demoted display OFFLINE at its
stable index, and get_capturer_for_display serves the PipeWire fallback only when
its rect matches the advertised geometry, else bails. A single-display host still
falls through (whole-desktop == that display). All new logic is drm-gated.

* drm: bound the _drm body read, stream-scope cursor teardown, refresh a stale verdict, drop dead clear (review 5)

- recv_msg_timeout2 only gated the wait for the first byte, so a peer that sent one
  byte then stalled pinned the task forever. The same budget now also bounds the body
  read; a body that overruns is a hard error that tears the stream down (recv_msg
  bodies are small JSON, so a healthy peer never trips it).
- The cursor cache is keyed by display index, which a rebuilt stream reuses, so a
  predecessor exiting after its replacement published a fresh cursor erased it. Stamp
  each entry with a monotonic per-stream epoch and compare-and-remove on teardown.
- ProbeState::Available had no TTL, so an idle hotplug left a phantom display in
  enumeration. Give it a timestamp and refresh the list off the hot path once it ages
  past POSITIVE_TTL. The verdict stays true across the refresh (never bounces a live
  session to the portal) and the probe runs on a background thread (never blocks the
  async enumeration).
- Remove the dead clear(): it is unreferenced, and wiring it into teardown would force
  the blocking re-probe on the next enumeration that swap_available_displays exists to
  avoid.

* drm: unit-test the bespoke _drm SCM_RIGHTS framing (review 6)

The _drm wire format is hand-rolled (length prefix plus an fd bound to the frame
first byte) because Framed/BytesCodec cannot carry ancillary data, so it had zero
tests. Add pure-userspace coverage over a socketpair:
- a control message round-trips with and without an attached fd, and the received fd
  refers to the same open file (a byte written into the source is read back through it)
- a raw length-prefixed body (cursor / CPU-fallback path) round-trips byte-for-byte
- a forged length prefix past the JSON cap is rejected at the prefix
- surplus fds packed into one cmsg keep only the first and close the rest
- a control message truncated past DRM_CMSG_CAP is rejected (MSG_CTRUNC), not consumed
- peer_uid_from_fd reads the socket peer credential the producer-auth path relies on

* drm: address the self-review findings on the review rework

Five defects an adversarial pass found in the previous commits:
- refresh_available_async set the single-flight probe guard, then relied on the
  detached thread to clear it; if thread creation failed (EAGAIN) or the closure
  unwound, the guard leaked true and froze every future probe. Release it via RAII
  inside the closure and on a Builder::spawn error.
- The _drm per-frame re-auth called the cached active_uid(), which on a cache miss
  (exactly during a session switch) falls back to a blocking loginctl seat0 lookup --
  on the single-threaded _drm runtime, once per frame, a subprocess storm. Use a new
  cache-only accessor that never blocks and fails closed on a miss, and correct the
  comment: the stop is bounded by the active-uid cache cadence, not one frame.
- set_drm_cursor inserted unconditionally, so a still-draining predecessor stream
  could overwrite (then delete on teardown) the cursor a replacement stream published
  for the same index. Make it a compare-and-set that ignores an older epoch.
- recv_msg_timeout2 treated a spurious readable() wakeup with nothing consumed as a
  mid-frame stall and tore the stream down. Track whether any byte was consumed
  (drm_read_full sets it) and map a zero-progress deadline back to None (re-poll),
  reserving the hard error for a genuine partial-frame stall.

* drm: release the probe single-flight guard via RAII on the cold path too

The cold availability probe in is_available acquired DRM_PROBE_IN_FLIGHT and released
it with a plain store(false) after a synchronous body; a panic there (e.g. a poisoned
DRM_STATE lock) would leak the guard true and freeze both future probes and the
refresh path hardened in the previous commit, since they share the guard. Hoist the
release into a shared ProbeInFlightGuard used by both the cold probe and the refresh
closure, so any exit -- normal, early, or unwinding -- clears it.

* drm: source libdrmtap from rustdesk-org, pinned by sha (review 3.4)

The dlopened .so is loaded into the CAP_SYS_ADMIN root service, so it should come
from the maintainer-owned repo, not a personal fork. rustdesk-org/libdrmtap main is
already synced to the exact commit we pin (c9cf0938 = v0.4.13) but carries no release
tag, so point both build.py and the CI job at rustdesk-org and track main with the
immutable commit pinned via DRMTAP_SHA. The post-clone sha check makes this
fail-closed: main moving off the pinned commit fails the build instead of silently
swapping the .so. The CI ref guard now accepts a vX.Y.Z tag or main (a loose branch is
still rejected). Switch DRMTAP_REF to a tag if rustdesk-org later publishes one.

* drm: dlopen libdrmtap by absolute path + unit-test the _drm admission and re-auth (review 5e, 6a)

5e: the deb dropped /usr/lib/rustdesk into /etc/ld.so.conf.d so the private libdrmtap
could be found by soname -- a system-wide search-path entry that lets it shadow a
system library for every binary on the host, which Debian Policy 10.2 forbids. Resolve
it by absolute path (/usr/lib/rustdesk/libdrmtap.so.0) at the dlopen site instead, with
the bare sonames kept only as a dev fallback, and drop the ld.so.conf.d file and the
ldconfig/try-restart postinst entirely (the .so is present at its absolute path right
after unpack, so the pre-warm resolves with no linker-cache step). The dlopen site is
this PR's own code, so this is in scope, not a follow-up.

6a: extract the _drm admission bound and the per-frame re-auth decision into pure
helpers (drm_conn_admitted, drm_peer_authorized) and unit-test them: admission admits
strictly below MAX_DRM_CONNS and rejects at/above it; re-auth passes root always,
passes a non-root peer only while it equals the active-session uid, and fails closed on
a switched-away, unknown-session, or unknown-peer case. (The /proc/exe-mismatch
rejection is exercised by the accept-time authorize call; unit-testing it in isolation
would need a second process with a different exe, so it stays an integration concern.)

* ci: run the _drm unit tests on every PR (review 6)

The _drm unit tests are behind the opt-in drm feature, which the default workspace
test job does not build, so they would sit in the tree unrun -- no better than no
tests. Add a Linux step to the per-PR ci.yml that runs them with the feature on,
alongside the existing ipc/auth tests. drm is a pure runtime-dlopen backend with no
link-time deps (no libdrm/EGL/gbm) and the tests are pure userspace (socketpair
framing, SCM_RIGHTS, the peer-auth/admission decisions), so this needs no GPU and no
extra system packages. The main build/test stays on default features, so the shipped
drm-off config remains the primary verified one.

* drm: bump the pinned libdrmtap to v0.4.14

Point the DRM capture build at the libdrmtap v0.4.14 release commit
(816766dedaba3140c613712ce97aa2614e8899e7) instead of v0.4.13, in build.py and
the flutter-build workflow, and correct the scrap Cargo.toml note to describe
the actual DRMTAP_SHA anchor. 0.4.14 keeps the same public API, so the dlopen
consumer needs no change.

* drm: address the consumer review (login-screen uid, frame flow control, hotplug)

- Start the login-screen --server as the active seat0 greeter account instead
  of root, so the DRM capture GPU/EGL convert never loads the vendor GPU
  userspace in a privileged process. A genuine root graphical session has no
  lower uid to drop to and stays root, and if the greeter spawn fails we fall
  back to a root --server so the login screen stays remotable. Gated on the drm
  feature so the non-drm build is unchanged.
- Bound the number of frames in flight on the `_drm` channel: the consumer acks
  each frame it finishes converting and the producer only sends while it holds
  credit, waiting on the socket otherwise. Without this the producer kept
  writing descriptors into the socket faster than a slow convert drained them
  and the consumer worked through an ever-growing backlog of stale frames. A
  zero-byte read or write on the ack path is treated as a closed peer rather
  than as success.
- Forward a display list that became empty (last monitor unplugged) instead of
  dropping it, so the availability cache leaves Available rather than keep
  advertising removed displays.
- On a topology change, invalidate the Wayland geometry cache and reapply the
  uinput mouse range for the new layout. The refresh runs off the frame-receive
  loop and is coalesced across the per-display receivers, so a multi-monitor
  hotplug runs one worker and the final layout wins.
- Clear the prefer-CPU-convert hints on a topology change: display indices can
  be renumbered, so a hint learned for an old index no longer refers to the same
  physical display. Re-learned on the next convert failure.
- Report a non-DRM-backed display when the DRM list is shorter than the sync
  list or any entry is offline, covering the present-but-demoted case.

* drm: log why the uinput refresh worker could not start

The worker released its coalescing slot and returned silently when the runtime
failed to build, leaving the uinput range stale for the new layout with nothing
in the log to explain it.

* drm: gate only frames on send credit, never cursor or topology updates

The credit check sat at the top of the producer loop and continued on exhaustion,
so while a slow convert withheld its ack the loop never reached the code that
forwards cursor updates and pushes a changed display list: the remote cursor
froze and a hotplug went unreported until credit returned. The comment claimed
those were not credit-gated; structurally they were.

The loop now always receives and processes producer messages. Only the frame send
is gated: when credit is exhausted the newest frame is held back (latest-wins,
matching the existing coalescing) and flushed as soon as an ack lands, while
cursors and the topology push go out unimpeded. While a frame is held the loop
also waits on the socket, so an ack wakes it promptly rather than only when the
next frame arrives; both select arms are cancel-safe.

* drm: fix three defects in the frame credit gate

Follow-up to the previous commit, from an adversarial review of it.

- The ack wake-up skipped the coalescing drain. When the socket arm of the
  select won, there was no message to seed the drain loop with, so the channel
  was never polled that iteration: a held frame could be sent while a strictly
  newer one already sat queued, and a queued cursor waited for the next producer
  message. Seed the loop from the channel when we woke on an ack instead.
- The loop could wait while holding a frame it was allowed to send. Credit
  replenished by the top-of-loop drain was not consulted before entering the
  select, so the frame waited for the worker's next message; if capture then
  returned WouldBlock it sat there until the stall teardown. Take whatever is
  queued without blocking in that case and fall through to the send.
- The capture worker no longer had any backpressure. Draining the channel every
  iteration (needed so cursors keep flowing) means a full channel no longer
  parks it, so a consumer converting at a fraction of the capture rate made the
  privileged service keep grabbing frames that were then discarded -- a packed
  copy per frame on the CPU path, a PRIME export on the dma-buf path. The worker
  now skips the grab while the task is holding an undeliverable frame, and keeps
  polling the cursor so the remote pointer stays live. The gate is deliberately
  conditioned on holding a frame, not merely on having no credit: with nothing
  held the task blocks in recv() and cannot observe an ack, so gating there
  would stop the worker feeding it at all.

The comment claiming the bounded channel backpressures the worker is corrected.

* drm: gate capture on credit alone, and bound the no-credit wait

Follow-up to the previous commit, from an adversarial review that modelled the
loop with a real runtime, socket pair and worker thread.

Gating the worker only while a frame was already held was wrong: those grabs are
not wasted work, they keep the held frame fresh, because the coalescing below
lets each newer frame supersede it. Pinning the worker at that moment therefore
froze whatever frame happened to be in hand when credit ran out and shipped it
stale once the ack landed -- measured at ~91ms average staleness against ~2ms
with no gate at all. Gating on lack of credit alone, and waiting on the socket
whenever credit is out rather than only while holding a frame, keeps the CPU
saving (the worker still stops grabbing) with no staleness: the ack resumes the
worker and what goes out is a fresh grab. Modelled at 0ms staleness and the same
delivered-frame count, with 31 grabs versus 588 ungated. It is deadlock-free
because the socket is watched in exactly the states where the gate is set.

The no-credit wait is now bounded (5s). While gated the worker does not grab, so
it cannot advance its own MAX_STALLED watchdog; a consumer that stopped acking
without closing the socket could otherwise hold this connection, its worker
thread and the privileged DRM context open indefinitely.

* drm: measure the no-credit deadline from the last ack, not the last wake-up

The bound added in the previous commit was a timeout on the wait itself, so any
wake renewed it -- and cursor messages keep arriving while frames are gated, so
a consumer that had stopped acking but still moved its pointer would renew the
deadline forever and never be torn down. Track when we last held credit instead
and enforce the deadline against that, keeping the wait capped only so we still
wake to re-evaluate it when nothing arrives at all.

* drm: drop to Unavailable when the background refresh finds no displays

The review asked for two things when the last CRTC disappears: push the empty
topology to consumers, and stop advertising the removed displays. Only the first
was done. The positive-TTL refresh still discarded an empty probe result and kept
the previous list, so on an idle host -- where there is no live stream to carry
the hotplug push -- enumeration kept reporting displays that were gone, exactly
as described. It now transitions to Unavailable on an empty result, matching the
hotplug path, while a failed probe (transient open/EACCES, not evidence the
displays are gone) keeps the verdict and only restamps it.

* drm: do not let a stale availability probe overwrite a newer verdict

query_displays() in the background refresh runs unlocked because it is slow, so
a hotplug push can publish a newer verdict while it is in flight; the refresh
then overwrote it with its own older result. Harmless while it only replaced the
list, but the previous commit made an empty result drop to Unavailable, so a
probe that started while the monitors were gone could disable DRM on a host
whose monitor had since come back.

The refresh now samples the stamp of the verdict it is refreshing and publishes
only if that stamp is still current. Every publish stamps a fresh Instant, so an
unchanged stamp means nothing republished in between -- equivalent to threading a
revision counter through every publish site, without having to keep all of them
in sync.

* drm: track availability publishes with a generation, and hold the probe guard across the whole path

Two defects in the previous commit's staleness check.

The single-flight guard was still created inside the spawned closure, but that
commit added a DRM_STATE lock before the spawn. A poisoned lock there would
unwind past the flag with nothing to clear it, leaving DRM_PROBE_IN_FLIGHT set
and freezing every future probe. The guard is now taken immediately after the
flag is acquired and moved into the closure, so it covers the lock, the probe,
and a failed spawn alike. The explicit release on spawn failure is gone with it:
it was not merely redundant but wrong, since by then another refresh may have
acquired the flag and clearing it would let two probes run at once.

The staleness check itself compared Instant stamps, which made correctness
depend on an implicit invariant -- that every publish restamps -- spread across
ten call sites; a future publish that reused a stamp would defeat it silently.
DRM_STATE now carries an explicit generation, bumped by publish_probe_state,
which every write to the state goes through. Instants are left to serve only the
TTL checks. The failed-probe branch deliberately restamps without bumping: it
touches the TTL, not the verdict, so a concurrent probe loses nothing by
publishing over it.

* drm: convert each display on the GPU that exports it

The unprivileged converter opened its render context with
drmtap_open_render(NULL), letting libdrmtap auto-select. On a multi-GPU host
that can land on a different GPU than the one driving the display, and importing
a scanout across vendors can fail permanently on an incompatible tiling
modifier.

The service already knows the exporting device, so it now names its render node
(drmtap_render_node, libdrmtap 0.4.15) in each DrmDisplayInfo, and the consumer
opens the converter on that node. The field is serde(default) and empty means
auto-select, so a service and a server from mismatched builds still interoperate
and a pre-0.4.15 .so degrades to exactly the previous behaviour. The path is
realpath-gated to /dev/dri before it is opened, the same gate the capture device
gets, since it arrives over IPC. When the named node cannot be opened the
converter returns None and the existing need_cpu fallback runs the convert on the
exporting GPU service-side, which is the most correct place for it anyway.

Added a wire-compat test that a pre-render_node DrmDisplayInfo payload still
decodes (empty node) and a current one round-trips the node.

* drm: advertise the displays of every GPU, not just the first card

A drmtap context is bound to a single DRM device, so the service enumerated one
auto-detected card and advertised only its monitors. On a multi-GPU host every
display driven by another card was invisible to the client, and its card-local
CRTC id could not have been opened through the wrong device anyway.

The service now enumerates every card (drmtap_list_devices, libdrmtap 0.4.15),
opens one reader per device, and merges their displays into the one list, each
tagged with its own card node and render node. DrmStart resolves the chosen
index to that display's device + CRTC and the worker reopens the right card;
the converter already binds the display's render node. Both new fields are
serde(default) and empty means the single auto-detected device, so a pre-0.4.15
.so and a mismatched-build peer keep the previous behaviour exactly.

Enumeration replaces the single-reader open in the pre-warm, the udev hotplug
refresh, and the per-connection handshake, so a hotplug on any card is picked up
and an all-monitors-off state now correctly publishes an empty list. The
per-connection cache refresh re-enumerates all cards rather than only the
connection's device, so serving one display never drops the others from the
next handshake.

Verified on a Jetson Orin (its two DRM devices, only card2 driving a display):
list_devices reports card2/renderD129 with one display, enumeration produces
exactly that display tagged to card2, and card1 (no active CRTC) is skipped -
no phantom, no regression on the single-display case.

* drm: bump the pinned libdrmtap to v0.4.15

* drm: do not guess the exporting GPU when the host has several render nodes

The converter binds the render node the service names for a display, and falls
back to auto-selection when that name is empty. An empty name is what an older
libdrmtap produces: the service resolves it with drmtap_render_node, which only
exists since 0.4.15, and rustdesk dlopens libdrmtap.so.0 by soname, so the
runtime library can be older than the one the build was pinned to.

Auto-selecting is not safe there. On a single-SoC multi-device host the wrong
choice does not fail: a Jetson Orin exports the scanout from nvidia-drm while
the first render node belongs to tegra, and importing the scanout on the tegra
node SUCCEEDS and yields corrupted pixels. There is no convert error, so the
prefer-cpu bit never learns anything and the stream simply looks broken with a
clean log.

Request the CPU-converted path instead whenever the exporter is unnamed and the
host exposes more than one render node: the service converts on the device it
already has open, which is correct by construction. Hosts with a single render
node have nothing to pick wrong and keep the dma-buf path untouched.

Verified on a Jetson Orin Nano, the two-device host: with a libdrmtap that
lacks drmtap_render_node the capture used to come through visibly corrupted,
and now falls back to the cpu path and renders correctly. With 0.4.15 the
service names renderD129 and the dma-buf path is used as before.

* drm: name the libdrmtap that was really loaded, and say so when it is stale

Two hours went into a corrupted capture whose only symptom was a clean log
saying "libdrmtap loaded: /usr/lib/rustdesk/libdrmtap.so.0 (v0.4.15)". The
library behind that soname symlink was a pre-release 0.4.15 that reported the
version but did not export drmtap_render_node, so the service silently stopped
naming the exporting GPU. The log named the symlink it asked for, which is not
evidence of anything, and the version it printed came from the library itself,
which was the part that lied.

Log the file the absolute candidate actually resolves to, and warn when a
library reports 0.4.15 or newer while missing drmtap_render_node or
drmtap_list_devices, naming that file: a version that claims features the
symbols do not back means a stale or pre-release build, and the effect is
invisible otherwise. Only the absolute candidate is resolved, because dlopen
does not search the process CWD for a bare soname while canonicalize would.

Also correct two places that no longer matched the code: the security document
still described an /etc/ld.so.conf.d drop-in and an ldconfig trigger that
build.py deliberately does not ship (the .so is dlopened by absolute path and
the package makes the soname symlink itself), and the comment above the render
node lookup still said an unnamed exporter always falls back to auto-selection.

* drm: tighten the render-node count and the loader diagnostics

Four corrections from a review pass over the previous two commits.

Count only a render node whose name is renderD followed by a numeric minor.
The prefix test also matched something like renderD.backup, which would have
inflated the count and pushed a genuinely single-GPU host onto the CPU path.

Log the load only after every required symbol resolved. load() still returns
None when one is missing, so announcing success first could print "libdrmtap
loaded" and then "libdrmtap not available" for the same library.

Name only the capability each absent symbol costs: a library missing just
drmtap_render_node loses exporting-GPU selection, one missing just
drmtap_list_devices loses multi-GPU enumeration, and the previous wording
claimed both were gone in either case.

Fix the security document's audit step. The dlopen names the symlink by
absolute path and the package registers no linker directory, so a leftover
object beside it is not loaded on its own; what matters is where the symlink
points, and a leftover only matters as what a stray ldconfig would repoint it
to. Ask the auditor to read the symlink target instead.

* docs: list every case that selects the CPU-converted frame path

The security document described the CPU fallback without saying when it is
taken, and the multi-GPU safety fallback added in this branch was not mentioned
at all. Enumerate the four cases, including the one where the service could not
name the exporting GPU on a host with several render nodes, and note that a
single-render-node host keeps the DMA-BUF path.

* drm: fetch libdrmtap by commit sha instead of cloning a branch

`git clone --depth 1 --branch main` fetches only the tip of that branch, so the
moment upstream pushes to libdrmtap `main` the pinned commit is no longer present
in the shallow clone at all: the build fails on an unreachable object rather than
on a mismatched pin, and it fails for a reason that has nothing to do with the
checkout being wrong. In the release workflow the whole block is wrapped so the
job stays green, which means the drm deb would simply stop being produced without
anyone noticing.

Fetch the sha directly instead. No branch or tag name takes part in the build now,
so it survives every upstream push and cannot be affected by a ref being moved or
repointed. DRMTAP_REF is gone, along with the regex that validated it.

The post-fetch sha check stays, with a narrower job: a fetch by sha cannot resolve
to anything else, so it now guards a reused checkout left at a different pin, which
is exactly what a version bump leaves behind. It still removes that tree so the
next run re-fetches cleanly.

build.py is now the single source of truth for the pin.

* drm: move the drm CI out of the stock workflow, and stop touching scrap/Cargo.toml

The instruction was that nothing outside the feature should change while the
feature is off, and the runtime code honors that, but the build plumbing did not.
Start undoing that.

ci.yml goes back to upstream byte for byte. The drm test step it carried now lives
in a new workflow that only fires when a drm path changes, so a PR that does not
touch this backend pays nothing for it.

That new workflow also runs the whole rustdesk-crate test set with the feature on
rather than filtering by the `_drm` test names, because the name filter skipped
the sibling assertion that bounds `size_of::<Data>()`, which the new DmabufDesc
variant grows.

It gains a second job that fetches libdrmtap at the pinned commit, builds the .so
and then asserts the contract the runtime depends on: every symbol the loader
resolves, derived from the loader source so the two cannot drift, plus evidence
that the EGL detile path is really compiled in. libdrmtap degrades to a CPU-only
stub when the egl/glesv2 pkg-config files are absent on a build host, and nothing
downstream noticed. Note the check looks for the dlopen target name and the import
call, not for DT_NEEDED: EGL is loaded lazily on purpose so the privileged process
never links the vendor GL stack, so an ELF-level check reports a false negative on
a correct library.

libs/scrap/Cargo.toml keeps only the added feature: the unrelated blank line before
[dependencies.hwcodec] is restored, and the comment no longer describes DRMTAP_REF,
which no longer exists. The feature is now drm = ["wayland"] because all three drm
modules live inside the wayland arm of common/mod.rs, so scrap/drm alone compiled
nothing; it worked only because the root crate always enables scrap/wayland.

* drm: build the unattended-wayland deb in its own workflow, not in the release job

flutter-build.yml goes back to upstream byte for byte. Three separate changes to
the stock release path disappear with it: the drm variant built inside the release
container, the snapshot and restore of the stock flutter bundle that existed only
to keep the drm relink out of the archlinux package, and the narrowing of the
publish glob to keep the consent-free deb off the public release.

The deb now builds in the drm workflow instead, which also removes the failure
mode the old placement forced: the whole block had to run in a subshell ending in
`|| echo WARN` so a drm-only breakage could not abort the stock publish steps,
which meant every failure in it, from the fetch to meson to packaging, kept the
job green and silently stopped producing the deb. A separate job can just fail.

The bridge generator is a reusable workflow, so this calls the stock one rather
than duplicating the codegen.

The deb is asserted rather than trusted: build.py can exit 0 without producing a
package, so the job checks the file exists and that it carries both the real
libdrmtap object and its soname symlink. It stays an artifact and never a release
deliverable, and it is built on the runner rather than in the old container the
stock debs use, so its glibc floor is higher than a released package.

* drm: stop refactoring the shared packaging path in build.py

generate_control_file goes back to upstream byte for byte: no extra parameters, no
conditional inside it. The variant instead rewrites the control file that function
just produced, so everything specific to the consent-free package lives in added
code rather than in the shared one. That rewrite fails loudly if either anchor line
stops matching, so a future upstream change to the control layout cannot quietly
yield a variant deb wearing the stock package name.

finalize_deb is gone. It had pulled the tail of both deb builders into one shared
helper, which is a refactor of a path the feature has no business touching. Both
builders now carry their upstream tail verbatim, with the drm work added as three
guarded blocks: stage the library, retarget the control, rename the output. With
the feature off, every line is upstream's.

Verified rather than argued, by building both packages with this script:
the drm deb is Package: rustdesk-unattended-wayland, carries Conflicts, Replaces
and Provides on rustdesk, has libdrm2, libegl1 and libgles2 appended to Depends,
and ships libdrmtap.so.0.4.15 plus its soname symlink. The stock deb is
Package: rustdesk, carries none of those three fields, and contains no libdrmtap
file at all.

* drm: key per-display state by connector identity, and end a stream whose index moved

The service binds a stream to (device, crtc_id), which survives a topology change.
Everything on the consumer side addressed it by list index, which does not:
drm_enumerate_all_displays concatenates per-card lists, so plugging or unplugging a
monitor renumbers every display after it. Two consequences, one live and one
remembered.

Live: a running stream kept sending monitor A while the advertised list, and so the
client layout and the injected-input rect, had come to mean monitor B. It only
resolved if the stream happened to fail on its own. The stream now records what it
was bound to and ends itself when its index stops meaning that, which routes the
change through the rebuild the video service already does.

Remembered: the zero-frame failure counts and the prefer-cpu verdicts were keyed by
index too, so after a renumbering one monitor could inherit another's demotion or be
forced onto the CPU convert path for a mismatch that was never its own. Both are now
keyed by device plus connector name. The reasoning was already written down for one
of these, in the comment above the prefer-cpu clear, and applied only there.

That bulk clear is gone with it. It existed to limit the damage of index aliasing;
with identity keys it would instead throw away a correct verdict, which costs a real
convert failure to relearn, on every unrelated hotplug.

Also fixes the drm workflow to skip the two tests the stock CI already skips. Both
need a display server and fail on any headless runner, so the job would have gone
red for a reason that has nothing to do with this feature. Verified by running the
exact command: 88 tests, including the size_of::<Data>() assertion that the old
name filter was hiding.

* drm: end the session when the captured display changes geometry mid-stream

A resolution DECREASE wedged the stream. The encoder is sized once, from
CapturerInfo at capturer build time; check_display_changed returns None on Wayland,
so the periodic display-changed broadcast never fires there; and convert_to_yuv only
bails when the source is LARGER than the destination. A smaller frame therefore
passed all three and was encoded into the previous canvas, leaving stale content
along the right and bottom edges for the rest of the connection. An increase
recovered only by accident, because convert then refused and the service rebuilt.

This is ours to contain rather than merely inherited: the DrmDisplaysChanged
handler re-broadcasts the new geometry through SYNC_DISPLAYS, so the client layout
and the pixels it receives actively disagree, where before there was no topology
signal at all.

The capturer now records the geometry its session was built with and returns a hard
error from frame() when a dequeued frame differs, which routes a shrink through the
same rebuild an enlargement already takes. got_frame is set first so a session that
did deliver frames is not counted as one of the zero-frame sessions that demote a
display to PipeWire.

The general fix belongs to the Wayland path rather than to this backend, and is
filed separately as #15695.

Four tests cover it, the first in this file: the matching size is delivered, a
smaller and a larger frame both end the session, and an unknown session size stays
out of the way instead of rejecting everything.

* drm: refuse a libdrmtap that cannot do the split export

The root --service must never load libEGL/libGLESv2: the point of the split is
that it exports the scanout dma-buf and the unprivileged --server converts. Two
paths could still break that, both because the loader accepted a library too
old to export.

drm_prewarm() called grab() when the loaded .so had no drmtap_grab_desc, and
grab() maps and detiles, so the privileged process pulled in the vendor GL stack
at startup, before any consumer had asked for a frame. The per-connection
capture loop then did the same for every frame, through the CPU fallback.

The version guard could not prevent it: it compared the ABI major only, and this
library is still 0.x, so every release it has ever made passed. Add a floor at
0.4.9, where the split entry points landed, and require the three split symbols,
which also rejects a build that reports a new enough version without carrying
them. That is not hypothetical: a pre-release stamped 0.4.15 shipped without the
multi-GPU accessors. Both refusals fall back to PipeWire/portal and say which
file and which symbols, at warn level.

The split symbols are no longer Options, so the type system carries the
guarantee instead of a convention. What is left of the CPU path is only what it
was meant to be: the consumer has no render node of its own, or the seat exports
no transferable dma-buf. Both are facts about the hardware, with no alternative
that keeps the stream, and neither is a property of which file was on the load
path.

Verified against the real library on i915. With 0.4.15 the export path captures
a tiled XR30 scanout and libEGL stays out of /proc/self/maps, while the old
grab() branch maps it, so the finding reproduces. A stub reporting 0.4.8 and a
stub reporting 0.4.15 without the split symbols are both refused, each with its
own diagnostic. The mirrored repr(C) layouts are unchanged across 0.4.9 to
0.4.15, checked field by field against include/drmtap.h at both ends, so the
floor costs no compatibility that was real.

* drm: move the _drm channel and its producer into src/ipc/drm.rs

src/ipc.rs is the file every unrelated IPC change has to be read through, and
this branch had grown it from 2227 lines to 4112. Move the DRM half out, into
the same #[path] submodule form the file already uses for ipc/auth.rs and
ipc/fs.rs, so it lands as ipc/drm.rs beside them.

What moves: the two payload structs, the producer that runs in the root
--service, and the bespoke SCM_RIGHTS framing the channel needs because
Framed/BytesCodec cannot carry ancillary data, plus their tests. What stays is
the Data variants, which belong to a shared enum and cannot live anywhere else,
and three re-exports so every existing call site keeps the path it already uses.

ipc.rs is 2285 lines now, 58 above upstream instead of 1885. The move is
content-identical: the only edits are the 39 per-item cfg attributes, redundant
now that the module is gated once at its declaration, and the test module cfg
that becomes a plain cfg(test). Checked by extracting the moved ranges from the
previous commit and comparing them line by line against the new file. Both
configs build with no new warnings and the same 92 tests pass, 14 of them the
drm ones that moved.

* drm: bound the _drm accept path (M1, M2, M8)

M1: authorization is now done on the blocking pool. It reads the active session
uid, which on a cache miss forks loginctl, and the socket is 0666 so any local
uid can make us do it. The same call exists for _service, but this runtime is
shared by every live capture stream, so a stall here hitches frames instead of
delaying one config sync.

M2: the handshake was a loop that ignored unexpected messages, which restarted
the ten second budget on each one, so a peer sending junk just inside the timeout
held a worker thread and one of the eight connection slots for as long as it
liked, and eight of them denied DRM capture entirely. It is one receive now, and
anything that is not DrmStart closes the connection: the consumer answers the
display list with DrmStart and nothing else, so there is nothing legitimate to
skip past.

M8: dropped the extra unauthorized-connection warn. log_rejected_service_connection
inside the authorization already logs the rejection with the peer and active uid
and rate limits it to one line per five seconds, which is exactly what a
world-connectable socket needs; the second line had no throttle and handed anyone
who can connect an unbounded log write.

Both configs build, 92 tests pass.

* drm: stop the two states that never settle (M4, M6)

M4: a dead producer left the availability verdict positive forever. The
background refresh keeps a positive verdict on a failed probe, which is right for
one failure and wrong for a run of them: if the root --service dies while this
--server lives, every probe fails, the cached list keeps being advertised, and
every display restart-loops. Three consecutive failures now drop the verdict to
Unknown, not to Unavailable, because the evidence is about the producer and not
about the hardware, so the next enumeration probes from scratch. The cold probe
also resets its own failure budget on success: it was never reset, so the five
strike allowance was spent once per process and a later probe demoted on its
first failure.

M6: a display that can never be grabbed churned PeerInfo about every 35 seconds
for the life of the process, because the cooldown was flat: demote, wait 30 s,
get advertised online, burn four sessions in a few seconds, demote again. The
cooldown now doubles per demote cycle up to 8 minutes. Recovery is unchanged in
the way that matters, since the count is erased the moment the display delivers a
frame rather than decaying with time, so a monitor that comes back is served
immediately.

Also, while changing that map: a zero-frame session on a display with no
connector identity was recorded under the empty key, which is the same aliasing
H2 removed for indexes, one unidentifiable display would have demoted the next
one. It is skipped now, as the comment above it always claimed.

Two new tests cover the backoff schedule and the reported 35 second cycle. 94
tests pass, both configs build.

* drm: give the DRM uinput update the timeout and the bookkeeping (M3, M6)

The DRM path sets the uinput absolute range itself, because it bypasses
check_init. That copy awaited update_mouse_resolution raw, and it was missing
three things check_init has sixty lines above it.

No timeout: uinput set_resolution reads its reply with no timeout of its own, so
a hung uinput socket blocked every video-service start on this branch, and wedged
the hotplug worker inside rt.block_on with UINPUT_REFRESH_BUSY latched true,
after which every later hotplug refresh was silently skipped for the process
lifetime. It is bounded at 3 s now, the same bound check_init uses.

No bookkeeping: it never called set_wayland_uinput_rect or
set_wayland_layout_baseline, which is why the #15601 layout-drift remap never
activated on the DRM path. Both are recorded now, and only after a successful
apply, so a transient failure is retried rather than remembered as applied.

No cache invalidation: the cached Wayland layout can predate compositor changes
made while no session was active, which is the case #15601 is about. Dropped
first, as check_init does.

It also stops reprogramming the device when the range has not changed (M6): a
display in a rebuild loop called this about once a second, and reapplying an
identical range is an IPC roundtrip plus a uinput reconfiguration under a user who
may be at the console. The layout baseline is still re-snapshotted on every call,
since it is what the client coordinates are measured against.

Left as a separate copy rather than folded into check_init: check_init ships in
every Linux build and the standing rule for this feature is that the drm-off
build does not change by a line. Both configs build, 94 tests pass.

* drm: check the greeter server is alive, not just spawned (M5, M10)

M5: the greeter fallback tested the wrong thing. start_server reports whether the
SPAWN succeeded, so a greeter account that cannot actually run the server, a
nologin shell or a hardened home, leaves a child that exits at once; the loop
sees only that the child is gone and respawns it as the greeter forever, never
reaching the root fallback, and the login screen becomes un-remotable on a host
where it used to work. It now requires the child to still be alive after a one
second grace before accepting it. A server that dies later than that is a
different, transient failure and the existing restart throttle already bounds it.

While there: the whole greeter branch is now inside the drm cfg, so the drm-off
build is upstream's single start_server line again rather than a run_as_greeter
variable that is always false.

M10: two monitors of the same model and resolution whose names do not normalize
to the compositor's matched no output at all, so both kept the DRM origin, which
is (0,0) for independent CRTCs. The client stacks them and injected coordinates
hit the wrong monitor with certainty. Unmatched connectors now take the next free
output in layout order, preferring one of the same physical size, and say so in
the log. That is at worst a swap of two identically sized rectangles, and the
layout stays coherent. The same pass also stops one output being claimed by two
connectors, which the unique-resolution rule allowed.

The assignment is now a pure function, so the cases are testable without a
compositor: five tests cover the naming difference, the identical-monitor case,
the double claim, name match beating the fallback, and more connectors than
outputs. 99 tests pass, both configs build.

* drm: stop reallocating and recopying whole frames (M9)

The CPU fallback moved a scanout four times: the producer packed it, the kernel
carried it, next_raw allocated and zeroed a fresh buffer to read it into, and the
consumer copied that into the slot. At 4K30 the last two are about 8 GB/s of
memory traffic that does nothing.

next_raw_into reads the body straight into a buffer the caller owns, so the
kernel copy lands where the frame is going to live, and resize costs nothing once
a buffer has seen one frame of that size. The frame buffers then circulate
instead of being freed and reallocated: whatever a new frame displaces goes back
on offer, both when the encoder consumes one and when a frame is superseded
before anyone reads it. The dma-buf path still copies once, because the convert
output is borrowed from the render context and only lives until the next convert,
but it copies into a recycled buffer and does it outside the slot lock, so a
multi-megabyte memcpy no longer holds the encoder off the slot.

Steady state is now one allocation for the whole session on both paths, and the
CPU path carries the pixels twice instead of four times.

The cursor body reads into its own buffer and is moved into the cursor cache
rather than copied; it is small and rare, so it stays out of the frame recycler.

Two tests: the raw body round trip now also covers a shorter body reusing the
buffer, so a stale tail cannot survive into it, and a new test asserts the frame
buffers circulate by allocation identity rather than by inspection. 100 tests
pass, both configs build.

* drm: the polish list, and a correction to my own ABI floor

The version floor I added two commits ago was one release too low.
drmtap_open_render and drmtap_convert_dmabuf are 0.4.9, but drmtap_grab_desc is
0.4.10, so a genuine 0.4.9 library passed the version gate and was then refused
by the symbol gate with a message that called it a stale or pre-release build,
which it is not. The floor is 0.4.10 now, the release where the whole split API
exists, and the test lists 0.4.9 among the rejected versions with the reason.

ExportLedger is deleted. DRM_FD_ELISION was false, so should_send_fd returned
true at its first branch and about sixty lines of eviction and epoch machinery
were unreachable, untested, in a security sensitive file. Why it was disabled
is worth keeping, so here it is: eliding the fd on an fb_id the converter has
already imported looks free, but the kernel can recycle an fb_id onto a
different buffer with identical geometry and modifier, and the exporter cannot
see the dma-buf inode that would tell the difference, so the elision can serve
a stale EGLImage. Sending it is cheap, the converter imports once per buffer and
closes the surplus fd, and libdrmtap's own cache keys on fb_id AND inode and can
only re-import when it is handed a real fd. That reasoning now lives here
instead of in dead code.

The rest:

- num_planes is clamped on the consumer before it reaches the C descriptor. The
  producer normalizes it and must be root, so this is only defense in depth, but
  the wire is the one place the value arrives from another process.
- warm_availability returns early on X11. Nothing there can consume a DRM
  stream, and probing makes the ROOT service open DRM readers, so an X11 host
  running a drm build was paying that at every startup for a path it can never
  take.
- drm_cursor_id no longer clones the cursor. The cursor service polls it at
  frame cadence to compare eight bytes, and a 256x256 cursor is 256 KiB.
- The premultiplied ARGB pass-through is now documented as matching the XFixes
  path, since that is why it is correct rather than an oversight.
- cfg hygiene: input_service.rs uses all(target_os = "linux", feature = "drm")
  like every other site, and active_uid_cached is gated with the feature too,
  which also removes a dead-code warning from drm-off Linux builds.
- Nits: DrmConn is pub(crate) like its constructors, new_drm_listener is no
  longer async with nothing to await, and the two anyhow! plus return Err pairs
  are bail! as the codebase writes them.
- DRM_CAPTURE_SECURITY.md moves to docs/ with the other docs, and its "no
  privileged child process is ever spawned" claim is corrected: an empty
  helper_path is not a disable switch in the C, find_helper searches six fixed
  paths and would exec one if the direct export ever failed. It is unreachable
  here for two independent reasons, the root service holds CAP_SYS_ADMIN so the
  direct path succeeds and the package builds no helper at all, and the paths
  are root-writable only, so the accurate statement is that this package never
  installs one, not that it can never happen.
- The comments that narrated the review rather than the code are rewritten to
  say what the code does. One of them had also drifted: the convert context is
  opened before we answer with DrmStart, not before the handshake.

Both configs build with no new warnings, 100 tests pass.

* drm: one DisplayHealth per connector, and the last index-keyed map

The three per-display verdicts are three answers to one question, can this
display be captured over DRM right now, and they already fed each other: the
rebuild cadence and the zero-frame streak end in the same demotion, and the
convert verdict is what keeps a multi-GPU display off the dma-buf path so it
never gets there. They are one struct now, keyed by connector identity.

This also closes a real leftover from H2. Two of the three maps were re-keyed by
identity then; the rapid-rebuild map was not, and stayed keyed by list index. A
hotplug that renumbers the list therefore moved a flap verdict onto whichever
monitor took that slot, which is the same defect in the third map. There is no
index-keyed per-display state left.

Behaviour is otherwise the same, with one improvement that falls out of the
merge: when a demotion cooldown expires, clearing the streak now keeps the
display's other state rather than replacing the whole entry, so a build cadence
and a convert verdict survive a retry the way they always should have.

One test for the demoted predicate, including that a higher demote count still
holds a display that a lower one would have released. 101 tests pass, both
configs build.

* drm: bound the GITHUB_TOKEN in the drm workflow

CodeQL flagged the new workflow for not declaring permissions, which is fair:
every job here only checks out, builds and tests, and the artifact up/download
in the deb job authenticates with the runtime token rather than this one, so
contents: read is the whole requirement. Declared at the workflow level so the
reusable bridge workflow it calls inherits the same bound.

The stock workflows do not declare it either, but they are upstream's and this
feature does not touch them; a new file can start out right.

* drm: make the outer handshake budget dominate the inner one

Two findings from the review bot on our own fork, both worth taking.

The caller waited HANDSHAKE_TIMEOUT_MS + 500 for the receive thread to hand back
the display list, but that thread is allowed to spend more than that: the connect
budget, and then recv_msg_timeout2 applies its argument twice in the worst case,
once waiting for the first byte and once for the body. So on a slow connect the
outer timer fired first and abandoned a handshake that was still inside its own
budget. The wait is now derived from those parts rather than written as a
constant, so changing either one cannot silently invert the relationship again,
and the two connect sites use the named constant instead of a literal.

The cursor cache insert shadowed hcursor under a cfg, so the same line meant the
requested id in one build and the served id in the other. It is a separate name
now, with the reason on it.

Not taken, and why: the bot also suggested making DrmCursorData carry width and
height as u32 to match the wire. They are i32 because that is what they feed,
protobuf CursorData declares both as int32 and platform/linux.rs assigns them
straight across. One cast has to exist somewhere, and it belongs at the boundary
where the values are already being validated, not at the consumer.

101 tests pass, both configs build.

* drm: bound the body read, and stop the empty key from aliasing displays

From the second review bot on our fork. Two of these are real and one of them is
mine from earlier today.

A raw body read had no deadline. Only the header was bounded, and drm_read_full
loops on readable() until it has the exact length, so a producer that wrote a
header and then stopped (crashed, stopped, wedged) pinned the consumer receive
thread forever. That thread is also the one that observes the stop flag, so every
capturer rebuild would have stranded another thread and its render context. The
whole body is bounded now, and an overrun is a hard error because the header is
already consumed and the frame cannot be resumed.

get_capturer_info collapsed an unknown connector identity to the empty string and
then read and wrote the health map under it, so two unidentifiable displays shared
one entry and one could demote the other. That is exactly the aliasing frame()
refuses to take part in; I fixed one side of it this morning and left the other.
The key is an Option now and both blocks skip when it is None: a display with no
identity simply carries no health.

Also from the same pass, smaller:

- build.py validates the shape of DRMTAP_SHA and DRMTAP_REPO before they reach a
  shell command. Both are env-overridable and get interpolated, and beyond the
  injection argument, an abbreviated sha would defeat the point of pinning while
  failing in a much less obvious place.
- the workflow's push path list is now identical to the pull_request one. It was
  missing four paths, so a push to master touching only those would have skipped
  re-verification.
- the checkouts set persist-credentials: false, so the token does not stay in
  .git/config for the rest of the job.
- a concurrency group supersedes a stale PR run, but never cancels a master run,
  whose whole purpose is to record that a commit was verified.

Not taken: reading VCPKG_COMMIT_ID and FLUTTER_VERSION from a shared .env. There
is no .env at the repo root, and the stock ci.yml and flutter-build.yml hardcode
those same two values, so this matches what is already there.

101 tests pass, both configs build.

* drm: test the half of the accept-time authorization that had none

The review called the accept-time authorization decision the single most
important invariant in this PR, and noted it has no test. Half of it did:
drm_peer_authorized_matrix covers the uid rule. The other half, the
/proc/<pid>/exe identity match that stops a DIFFERENT program running as the
right uid from being handed the screen, did not.

We said last round that testing it needs a second process with a different
executable, so it was integration rather than unit work. That was too
pessimistic: the negative case needs ANY foreign executable, not a second build
of rustdesk, and /bin/sleep is one. So the test covers all three outcomes: our
own pid matches, a live process running another binary is rejected, and a peer
whose pid cannot be resolved is rejected rather than admitted.

The test synchronizes on the child having exec'd before it looks. spawn returns
while the child is still a copy of us, and until exec completes /proc/<pid>/exe
points at OUR binary, so reading it too early sees a match and the assertion
passes for the wrong reason. It failed exactly that way under the parallel suite
and passed when run alone. A real peer has necessarily exec'd and connected
before it can be authorized, so the window exists only in the test.

102 tests pass, three consecutive full runs, both configs build.

* drm: make the refresh decision a pure function, and test it

The review named two untested things: the accept-time authorization decision,
covered by the previous commit, and the availability/demotion state machine. The
demotion half got tests with the backoff work; this is the other half, what a
completed background refresh decides.

It is extracted rather than tested in place on purpose. The effects touch
process-global state, DRM_STATE and the failure counter, which parallel tests
cannot share, so a test driving them would be intermittent by construction, which
is the kind of test nobody ends up trusting. The decision itself has no such
problem, so it is now a total function over the probe result and the consecutive
failure count, and the closure applies it.

Two tests: the decision table, including that a run short of the threshold keeps
a working verdict and the threshold gives it up; and the symptom the policy
exists for, a root service that dies while this server lives, where every probe
fails from then on and the verdict has to be given up in bounded time, to Unknown
rather than Unavailable, because what we learned is about the producer and not
about the hardware.

104 tests pass, both configs build.

* drm: count a display whose frames never match its advertised size

The display list carries the CRTC mode and a frame carries the scanout
framebuffer. Those are two different numbers whenever a CRTC scales a
smaller buffer up to its mode, so such a display fails the geometry guard
on the FIRST frame of every session, having delivered nothing.

That path marked the session as having produced frames, which is what the
zero-frame streak uses to decide a display cannot be served over DRM at
all. So the demotion to PipeWire never armed and the display rebuilt until
the rapid-rebuild guard caught it seconds later, under a message about a
mid-session change that never happened.

Count it instead, through the same bookkeeping the stream-died path uses
(now one helper, so the two cannot drift), and say which of the two cases
the error is. The unit test asserted the old behaviour on a capturer that
had never delivered a frame, so it is split into the mid-session case it
meant to cover and the first-frame case it was silently locking in.

* drm: make an unpinned libdrmtap deliberate, and reject --drm off Linux

Three ways to build a different libdrmtap than the pinned one (DRMTAP_REPO,
DRMTAP_SHA, DRMTAP_PREBUILT_DIR) were each silent, and the last skips the
sha verification entirely. The claim this feature rests on is that the
privileged capture library is the reviewed object at the pinned sha, so any
build that is not that one now has to say so: the overrides still work and
still cover local work and cross-builds, but they need
DRMTAP_ALLOW_UNPINNED=1 alongside them and the build prints what it did.

--drm on Windows or macOS was accepted and then dropped by get_features(),
so it produced a stock build that looked like a DRM one. Reject it.

Also test the _drm body-read deadline, which nothing exercised: the header
and the body are separate reads, so the caller budget does not cover the
second one and a regression there would silently reopen the stall.

* drm: treat an empty DRMTAP_PREBUILT_DIR as unset in the pin gate

build_libdrmtap_so() tests it for truthiness, so an empty value means no
prebuilt directory. The gate compared it against None instead, and would
have demanded the opt-in for an override that was never going to happen.

* drm: never latch the uinput refresh slot, and bound the source stride

The uinput refresh worker released UINPUT_REFRESH_BUSY on its two normal
exits only. The body locks several process-wide mutexes and does a Wayland
roundtrip, so an unwind there left the flag set for the process lifetime,
and every later hotplug then skipped the spawn and never reapplied the
uinput ABS range: the stale-range, wrong-output symptom the refresh exists
to prevent. This file already had the answer for the probe flag, one screen
away, and the hazard is called out in wayland.rs. Fixing one site and not
the other is the same miss as the hotplug maps.

The slot is deliberately handed back and re-taken mid-loop, so the guard
tracks ownership rather than releasing unconditionally: a plain RAII drop
would clear a flag a replacement worker owns.

drm_reader bounded only the destination (w*4*h) while the row loop reads up
to (h-1)*stride + w*4, so a large stride read past the mapping and could
overflow usize in y*stride. drm_render::convert already bounds stride*h;
the privileged half must not be the weaker of the two.

Also give the drm CI jobs a timeout, so a hung meson or vcpkg step fails in
an hour instead of six.

* drm: refuse to ship a libdrmtap built without the EGL backend

libdrmtap treats egl/glesv2 as OPTIONAL: without their headers and
pkg-config files meson silently builds a CPU-only stub. The stub still
exports every symbol the loader gates on, so nothing downstream notices,
and the split capture depends entirely on the unprivileged side
EGL-detiling the scanout it receives. The result is a build where DRM
capture quietly degrades to PipeWire on every tiled-scanout host, which is
most of them. Our CI asserts this on the .so it builds; a developer or
packager running build.py got no such check.

Assert on the artifact rather than passing -Degl=enabled: that option only
exists in libdrmtap past the pinned 0.4.15, and checking what was actually
produced also catches a stale or substituted object, which a build flag
cannot. Same two markers CI looks for, and for the same reason an ELF-level
check does not work: EGL is reached by lazy dlopen so there is no
DT_NEEDED.

* drm: gate the libdrmtap ABI on the minor, and skip the warm probe on X11

Two items from the review that I had recorded as done and were not.

The ABI check had a floor and no ceiling, so 0.5.0 and 0.9.9 passed. Under
0.x semver the minor is the breaking axis, and libdrmtap freezes only
drmtap_device and drmtap_dmabuf_desc: drmtap_frame_info, drmtap_display,
drmtap_config and drmtap_cursor_info are not frozen. A 0.5.0 adding one
field to drmtap_frame_info still reports major 0, so we would have loaded it
and read every field at the wrong offset, in the root service. It now
requires the verified minor; a 0.5.x needs a deliberate bump after comparing
the layouts.

The unit test asserted the opposite of this, in as many words ("0.5.0 must
pass"), so it was holding the hazard in place. Replaced.

warm_availability ran on X11 too, where every consumer of the verdict sits
behind an !is_x11() check, so the root service opened DRM readers for a path
the session can never use.

* drm: close the full-review findings (a third latched flag, and two escapees)

The one that matters: the display-cache refresh worker was the THIRD copy of
the wedged-flag hazard. catch_unwind covered only the enumeration, and
thread::spawn panics on EAGAIN after RUNNING was already swapped true, so
either path parked the flag for the process lifetime and every later refresh
- including every udev hotplug - returned early forever. Same ownership
guard as UINPUT_REFRESH_BUSY (the flag is handed back and re-taken mid-loop,
so an unconditional RAII release would clear a replacement worker's flag),
plus a fallible spawn whose failure drops the closure and releases the slot.
DRM_PROBE_IN_FLIGHT, UINPUT_REFRESH_BUSY, now this: the lesson stays
'grep for every site with the shape', and twice was not enough.

Two findings had been flagged in an earlier round and escaped the ledger:
- an unrecognized convert-output fourcc fell through to 'present as BGRA'
  with a debug log, where every sibling validation in that function is a
  hard error that lets the caller fall back to PipeWire. A 64bpp output
  passes the stride check and encodes garbage. Hard error now.
- the trust-boundary validation constants (fourccs, MAX_DIM,
  MAX_FRAME_BYTES) were declared independently on both sides of the split.
  Hoisted into drm_reader, imported by the converter, so the two halves
  cannot drift apart about what data they will touch.

The rest:
- the CI symbol extraction dropped any loader symbol containing a digit and
  degraded to a pass-with-zero-iterations no-op if the b"..." literals were
  ever refactored; digits allowed, count asserted, notice de-hardcoded.
- 'drm' in features was a substring test on the comma-joined string, so a
  future drm-lease feature would have shipped the consent-bypass deb
  without --drm. Exact membership now.
- the security doc claimed the deb is built on an ubuntu18.04 container;
  the only deb job runs on ubuntu-24.04. The 18.04 sentence now says what
  is true: 2.4.95 is an API floor, the binary floor is the build host's.
- DRM_DISPLAY_CACHE poison handling was recover-in-the-writer,
  panic-in-the-readers; both readers now recover like the writer.
- the producer prewarm ran on X11 where no consumer can connect, the same
  inconsistency just fixed for warm_availability. The listener still starts
  (the service outlives sessions; a later Wayland login must find the
  socket), only the prewarm is skipped.

* drm: measure the verification deb glibc floor and put it in the artifact name

The workflow already said in a comment that this deb is a verification build
with a higher glibc floor than the release debs, because it builds on the
runner rather than in the ubuntu18.04 container the stock job uses. A comment
in this file is not visible to whoever downloads the artifact from the Actions
UI, and the name was a bare rustdesk-unattended-wayland-x86_64.deb, so it read
like something installable anywhere.

The floor is now read off the built object with objdump and goes into the
artifact name, so the constraint travels with the file. Measured rather than
stated: a hardcoded number would drift the next time the runner image moves.
Verified the pipeline against a real deb here (2.39).

Restoring the container build is the other option and is cheap to do -- the
recipe including the two 18.04 traps is still in this repo's history -- but it
belongs with a deb that is actually distributed, not with a job whose contents
are already asserted in-place.

* drm: the same latched-flag bug a fourth time, in my own fix for the third

I built UinputRefreshGuard INSIDE the spawned closure, so it only covered
paths where the closure ran. thread::spawn panics on EAGAIN after the swap,
so no guard existed and the flag stayed set for the process lifetime, which
is the exact failure the guard was introduced to prevent. I then wrote
RefreshSlot correctly - constructed before the spawn, moved in - two hours
later and did not go back to fix its sibling. Both are right now, and the
spawn is fallible in both.

Also from the review:

- DRMTAP_PREBUILT_DIR returned before the EGL-stub assertion, so the check
  only guarded the source build. That is backwards: prebuilt-dir is the
  widest override (no fetch, no sha check, an object this script never sees),
  the likeliest to hand over a stub, and the path our aarch64 cross-build
  actually uses. Verified the assertion accepts a real .so and rejects one
  built with -Degl=disabled.
- convert() bounded only the frame libdrmtap returns, not the descriptor going
  in. offsets/pitches address plane ranges inside the dma-buf, so those are
  what a malformed pair would reach past. Bounded per populated plane, the
  same way the export side is. Defense in depth (the producer is
  root-authenticated and libdrmtap validates against the fd since 0.4.12),
  but the two halves should agree before the C sees the data, not after.
- the flutter patch step used '[[ test ]] && git apply' as its last command,
  so the step would FAIL rather than skip the first time FLUTTER_VERSION
  moves off 3.24.5. Explicit if/else, and the values now come from the
  environment instead of ${{ }} interpolation, which also clears zizmor's
  template-injection warning. Checked both branches.

Declined: the cursor id/cache-key convergence finding. Both accessors use one
selection over one map, so they can only disagree across a publish race, and
state.hcursor is already set to the id ACTUALLY served (drm_served_id), which
is the sync the finding asks for - added in an earlier round.

* drm: stop routing gates from paying for the availability probe

A Major finding I skipped twice, and the file already argued against itself:
wayland.rs's own NOTE says re-probing _drm from the async enumeration path
blocks the executor long enough to trip 'deadline has elapsed' and spiral
into a restart loop -- and then six routing gates called is_available(),
which runs query_displays() inline whenever the state is Unknown (cold start,
or a NEGATIVE_TTL expiry mid-session). ensure_inited, is_inited,
get_displays_and_primary and clear() are exactly the paths the NOTE names.

is_available_cached() is a single mutex read: KNOWN-available or not. The six
gates use it, which is safe because they are routing decisions, not
capability ones -- a cold cache answers 'not DRM' and the caller takes the
PipeWire path it would have taken anyway.

Switching all seven, which is what the finding literally suggested, would
have introduced a worse bug: warm_availability calls query_displays()
directly, so is_available() would have had ZERO callers and nothing would
ever probe lazily again. A --server that started before the root service
would then never see DRM for the rest of its life. get_capturer_for_display
keeps the probing form -- it is sync, on the plain video thread, it is the
capture-build path where a definitive answer is the point, and it is what
makes a cold cache recoverable.

* drm: stop leaking the authorized _drm fd into forked children

libc::dup() does not copy the close-on-exec flag, so the dup'd _drm socket fd
was inherited by every child this process forks. This process is the ROOT
service and it does fork synchronously elsewhere (the loginctl active-uid
lookup), and that fd is an ALREADY-AUTHORIZED channel to the one thing on the
box that hands out scanout dma-bufs. F_DUPFD_CLOEXEC instead. Measured the
difference rather than assuming it: dup() leaves FD_CLOEXEC clear,
F_DUPFD_CLOEXEC sets it.

Also the last two artifact sources without the stub check:

- --package + --drm stages the .so straight out of a bundle somebody else
  produced, with no _assert_so_has_egl. Third source, same exposure as
  DRMTAP_PREBUILT_DIR, now asserted like the other two. All three artifact
  paths are covered.
- the workflow triggers omitted src/server.rs, src/server/input_service.rs and
  src/platform/linux.rs, which all carry DRM wiring (warm_availability, the
  cursor path in run_cursor, the producer start and get_cursor/get_cursor_data),
  so a PR touching only those skipped the entire drm verification. Added to
  BOTH mirrored lists and asserted equal (15 == 15).

* drm: decide x11 inside the prewarm, with a bounded re-check

the one-shot is_x11() gate at the call site misfired during boot:
get_display_server() falls back to "x11" while loginctl cannot name the
seat0 session yet, so on a wayland host with the service enabled at boot
the prewarm was skipped for the life of the service and only ever ran
after a manual restart, which is how every deploy happened to exercise
it.

move the gate inside drm_prewarm and re-ask every 2s for up to 30s. a
genuine x11 or headless host exhausts the budget having opened no
DrmReader and no drm fd; a wayland boot proceeds as soon as the session
reads as wayland. measured on a boot: the skip used to fire 0.8s in
while loginctl reported the wayland greeter in that same second, and
graphical-session.target only arrived at +5s.

* drm: wake idle-disabled displays and settle the topology before the client is promised a list

a compositor that idles long enough does not merely blank a panel: it
disables the connector, leaving no scanout for any capture backend to
read - not drm, not pipewire, not x11. on an unattended box that meant
connecting to whatever was still scanning out (on an apple t2, the
60x2170 touch bar strip) with the real panel sitting disabled next to
it, or a stale cached list advertising a display with nothing behind it
("waiting for image").

the fix has three parts, and where the wake runs is the load-bearing
one:

- the root service answers every _drm handshake with a fresh, settled
  enumeration (drm_enumerate_settled): enumerate, and if a CONNECTED
  display has no crtc, inject one synthetic 1px pointer round trip over
  uinput (rate limited to one per 20s, one winner via compare_exchange)
  and hold the answer until nothing wakeable is left undriven or a 3s
  deadline passes. rate-limited losers wait for the outcome too while a
  wake is recent - answering with the pre-wake list is exactly the
  mid-transition state that produced duplicate, misindexed monitors.
  connectors a wake could not bring back are latched by connector
  identity (device:connector) and the latch is self-refuting: an entry
  later seen scanning out is dropped, so one slow modeset cannot
  disable the wake for the life of the service, and a dummy plug cannot
  suppress the wake for a different panel that idles later.

- the login path refreshes the cached display list over a live
  handshake (refresh_displays_for_login) before peer info is built, so
  the list the client is promised is the post-wake truth and never
  changes under it seconds later. the publish is generation-checked
  against concurrent writers; every failure mode keeps the previous
  cache, so a login can never get harder than before, only truer.

- the capture handshake resolves the display index the client chose by
  connector identity against the handshake list (the service enumerates
  fresh per connection, so an index alone is only meaningful against
  the list it came from), fails the build cleanly when that monitor is
  gone, and no longer republishes its handshake list into the
  availability cache - that unordered write could clobber a newer
  settled list with pre-wake data and re-advertise a reordered list
  under a live session.

the display-list read timeout grows to cover the settle budget
(DISPLAY_LIST_TIMEOUT_MS), or a wake that needs the full recheck would
turn into a spurious handshake timeout on exactly the host it exists
for. removing the display cache from the handshake path also retires
DRM_CACHE_WARMED; the cache still feeds the topology push and the udev
listener.

measured on the t2 (amdgpu panel idle-disabled, appletbdrm touch bar
still scanning out): connect -> wake fires with undriven=1 -> panel
returns in ~330ms -> the same probe answers 2 displays -> the client
starts on the panel. with the panel awake: zero wakes. the root service
still never maps libEGL/libGLESv2.

* drm: close the round-7 review findings

- the renumbering probe in the DrmDisplaysChanged handler now reads the
  pushed list at wire_idx, the slot our monitor held in the service's
  index space, instead of at the index the client chose. the pushed
  list shares the handshake list's construction, so probing the client
  index compared two different index spaces whenever a wake or hotplug
  had renumbered entries - tearing down a healthy stream or missing a
  real renumbering.
- both message-body reads (cpu frame, cursor pixels) now run under a
  deadline. only the header read re-checked `stop`, so a producer dying
  between a header and its body pinned the receive thread forever and
  every rebuild leaked a thread plus its render context.
- the drm cursor cache gets a size ceiling (drm ids are derived from
  the shape's content, so an animated pointer minted a new key per
  shape and the map grew for the life of the service; x11 ids come
  from a small serial set, so the ceiling is gated and the stock build
  is untouched).
- has_non_drm_backed_display reads a two-scalar accessor instead of
  cloning and geometry-augmenting the whole display list on every
  cursor tick.
- the libdrmtap pin validation moved out of import time into
  build_libdrmtap_so(), so leftover DRMTAP_* environment variables or a
  malformed sha cannot fail a stock build that never touches libdrmtap.
- reworded a workflow comment whose literal expression marker broke
  actionlint.

* drm: close the round-8 review findings

- the .so contract check in the drm workflow runs under strict mode:
  without set -e the trailing ::notice echo returned 0 and masked the
  `test "$missing" -eq 0` assertion, so the step passed even with a
  missing loader symbol or a CPU-only stub. the two extraction
  pipelines get an explicit rescue so a zero-match grep still reaches
  the ::error guard that explains WHY instead of dying silently.
- the pipewire-fallback geometry guard no longer compares the physical
  drm size against the portal rect on a single-display host: the rect
  is the compositor's LOGICAL size, so on a scaled output the two
  legitimately disagree (2880x1800 vs 1440x900) and the guard rejected
  the one valid fallback, restart-looping the display instead of
  degrading. on a single-display host the whole-desktop stream is that
  display by construction, so only the position has to agree; the size
  check stays on multi-monitor hosts, where it is what tells one
  connector apart from the full-desktop rect.

* drm: close the round-9 review findings

- strict mode on the remaining two assert steps of the drm workflow
  (the deb-contents assert and the glibc-floor measurement): same
  masking pattern as the .so contract step fixed last round - without
  set -e only the last command's status counts and the mid-script
  checks were decorative. the floor extraction gets an explicit rescue
  so a no-match grep still reaches the `test -n` reporter.
- the security doc states the whole accepted version window (exactly
  the pinned minor with a patch floor; a NEWER minor is refused too,
  because the mirrored struct layouts are only verified against the
  pinned one), and the auditing section carries the command matching
  its leftover-object comment.
- the uinput-missing warning literal lost the embedded space runs a
  reflow had left in it (it is the sole, once-per-process diagnostic
  for that failure and it read as a run-on line with gaps).
- the geometry-mismatch path in frame() hands the taken buffer back to
  the recycler before erroring; dropping it made every rebuild cycle
  re-allocate a scanout-sized buffer.

* drm: document the display wake in the threat model

the wake is deliberate input injection by privileged code, which is
exactly the kind of thing this document exists to state precisely
rather than leave to be discovered in the diff: why it must run in the
root service (uinput is root-only and the compositor holds drm master),
what it can reach (only an already-authorized _drm connection triggers
it), how narrow the trigger is (a connected-but-undriven connector,
with a self-refuting per-connector memory for the hopeless ones), the
rate bound (one wake per 20s process-wide, single winner), the device
lifetime (created and destroyed around the emit), and that a host
without /dev/uinput loses nothing it had (such a session was already
view-only).

* drm: close the round-10 review findings

- the /dev/dri gate returns the CANONICAL path instead of a bool, and
  both callers open that value. answering yes/no meant the caller
  handed the original string to libdrmtap, which re-resolved every
  symlink component after the check - a check-then-use window, in the
  root service. this is the whole point of the gate, so it should
  never have been able to hand back an unresolved path.
- `--package <folder> --drm` builds the capture library instead of
  demanding it inside the bundle. no build path puts libdrmtap in a
  bundle folder (the flutter deb builds it straight into the staged
  deb), so that check made the flag combination impossible to satisfy.
  the safety property it stood in for is now asserted directly and
  better: the staged BINARY must carry the drm dlopen path, so a stock
  binary can never be packaged under the consent-bypass name. a bundle
  that does carry a .so keeps its existing EGL assertion, and the
  variant naming keys on the explicit request rather than on what
  happened to be staged.
- the deb assert step globs into an array and asserts the count: under
  set -e `ls` aborted before its own `test -n` could report, and
  several matches produced a multi-line value whose mv failed with an
  unrelated error.

* drm: finish the logical-geometry comparison, and chain a re-raise

the pipewire-fallback guard now normalizes BOTH sides to logical before
comparing. last round fixed only the single-display case, which left
the same defect on the shape that actually has it: on a multi-monitor
scaled host the advertised geometry carries the PHYSICAL drm mode plus
the compositor scale, while the portal rect is already logical, so a
scaled output disagreed with itself (2880x1800 against 1440x900) and a
per-connector stream that really was that display was rejected,
leaving it advertised offline instead of degrading. the size check
itself stays: on a multi-monitor host it is what tells one connector
apart from the whole-desktop rect. the failure message reports the
logical numbers, the ones actually compared.

also chains the libdrmtap read failure with `from err` so the original
OSError survives (ruff B904).

* drm: fix two review-suggested changes that were wrong, and stop overclaiming in the docs

an adversarial sweep over the whole batch, aimed at the failure that
kept recurring here (a hazard identified and only some instances
fixed), found that two changes made on review advice were themselves
defects. both are reverted with the trace written down so they do not
get "fixed" again:

- the hotplug renumbering probe reads the pushed list at the CLIENT
  index again, not the service one. `bound_to` is an IDENTITY,
  (device, crtc_id), so comparing it against a slot is not a
  cross-index-space comparison; and `swap_available_displays` installs
  that same list as DRM_STATE two lines later, which IS the client
  space - display_service re-advertises it, input is mapped through
  it, the next rebuild reads `expected` out of it. Probing the service
  index answered a question nothing downstream consumes and went quiet
  in exactly the case the guard exists for: a stream whose wire_idx
  differs from its client index kept running while that index came to
  mean another monitor, so the client rendered monitor A believing it
  was monitor B and routed every click accordingly.
- the pipewire-fallback guard compares raw sizes again. BOTH sides are
  physical: `Display::width()` on the wayland variant returns
  `physical_width()`, and `try_fix_logical_size` only repairs the
  capturable's separate logical_size field. Scaling the drm side
  therefore compared logical against physical and rejected the valid
  stream on precisely the scaled outputs it was meant to rescue. The
  single-display carve-out now needs BOTH sides to be single, since a
  monitor on a card the service cannot open is missing from the drm
  list while the compositor still drives it.

also from the sweep:

- a capture build whose index is out of range of the advertised list
  now fails instead of falling back to the raw index, which the wake
  can have grown the service list back past - that bound a second
  video service to a monitor already being served and recorded its
  health under the wrong identity.
- the security doc no longer claims the privileged process never loads
  GL. That is true of the DEFAULT path and measured there, but the CPU
  fallback converts in-process, and a tiled scanout can only be
  decoded through the GPU, so libdrmtap dlopens libEGL in the calling
  process when the frame needs it. The doc now says which property
  belongs to the path and which to the process, and bounds the cases
  instead of overclaiming.
- the wake latch is described honestly: it self-clears when the
  display is next driven by anything, but nothing retries it, so a
  transient failure can leave it latched on an unattended host.
- the wake's uinput device DECLARES two axes and BTN_LEFT (libinput
  ignores a device that does not look like a mouse) while EMITTING
  only the net-zero axis round trip. the doc said one axis and no
  keys, describing the emit as if it were the declaration.
- the drm CI never ran for a change to the root Cargo.toml, where the
  top-level `drm` feature is defined, or to Cargo.lock, which every
  `--locked` build here resolves against. both triggers list them now.
- the deb assertion checks the packaged BINARY carries the libdrmtap
  dlopen path, not just that the library was staged beside it.

* drm: close the round-13 review findings

- the ABI refusal message has a branch for an unverified MINOR. It had
  only two, so a library NEWER than the pinned minor was told it
  "predates the split-capture API" - the opposite of its problem, and
  the kind of message that sends someone looking in the wrong place.
  the warn line names the accepted minor too.
- the libdrm floor no longer claims 18.04 ships 2.4.101: base bionic
  shipped 2.4.91, which is BELOW the 2.4.95 the GetFB2 API needs, and
  only the updates/HWE stack clears it. read as "18.04 with updates,
  or newer".
- the drm-build marker scan reads the staged binaries chunked inside a
  `with`, overlapping by len(marker)-1 so a marker cannot fall across
  a chunk boundary, instead of pulling a 45 MB librustdesk.so into
  memory and leaning on refcounting to close the file. verified
  against a real drm build (found) and an unrelated binary (not
  found).

* drm: close the round-14 review findings

- the .so contract and deb assertions no longer pipe into grep. under
  `set -o pipefail`, `producer | grep -q` reports a FALSE FAILURE once
  the producer outruns the 64 KB pipe buffer: grep -q exits at the
  first match, the producer dies on SIGPIPE, and pipefail makes that
  the pipeline's status - so a library that HAS the symbol is reported
  as missing it and the step fails on a good build. measured on a real
  EGL-enabled .so (101 KB of strings, both markers present): the piped
  form reported both missing. this was introduced by the strictness
  fix two rounds ago and only passes today because a release-sized .so
  fits in the buffer. NOTE the obvious repair does not work either -
  materializing the output and piping the variable keeps the pipe and
  fails identically (measured), so these now match with bash's own
  pattern operator and no subprocess at all. verified with positive
  and negative controls.
- warm_availability decides X11 for itself, inside its retry loop,
  with the UNMEMOISED `scrap::is_x11()`. this is the same one-shot-at
  -startup bug the pre-warm had, in its sibling call site, left behind
  when that one was fixed: the check ran during startup, where
  loginctl cannot yet name the seat0 session and the answer defaults
  to "x11", so a Wayland host that came up slowly skipped the warm for
  the life of the process and got back the cold-probe "No displays"
  symptom the warm exists to remove. the memoised form would have
  moved the bug rather than fixed it, since it latches its first
  answer.
- the grab_desc SAFETY comment says what the frame protocol actually
  is instead of promising a release on every return path: traced in
  the C, a failing grab_desc leaves nothing to release (-EINVAL
  returns before allocating, a failed inner grab has already cleaned
  up, and -ENOTSUP releases the frame itself), so releasing on those
  paths would be a double free.

* drm: bound the work an unauthenticated peer can make the root service do

the `_drm` socket is world-connectable by design (the unprivileged
--server has to reach it), and every accepted peer got a spawn_blocking
authorization - which forks `loginctl` whenever the active-uid cache
misses - BEFORE any admission bound applied. MAX_DRM_CONNS does not
help there: it only counts peers that already passed. So a local uid
that will be rejected could still open connections in a loop and keep
the shared blocking pool busy, and that pool is shared by every live
capture stream, which is exactly the stall the comment above the
authorization warns about.

add a separate, small in-flight bound around the authorization step,
deliberately NOT the same counter as MAX_DRM_CONNS: sharing one would
let a rejected flood eat the capacity the real consumer needs. the
guard is taken before the spawn and released as soon as the verdict is
in, so the slot covers the authorization only. the rejection logs at
debug rather than warn for the same reason the existing rejection is
silent - anything reachable by any local uid must not be an unbounded
log-write primitive. unit-tested like its sibling, including that the
pre-auth bound stays the tighter of the two.

* drm: reject an out-of-range num_planes on the import side instead of clamping it

the incoming descriptor's plane count was clamped to 1..=4 for the
validation loop but passed to libdrmtap RAW, so a wire descriptor
claiming 7 planes was checked as if it had 4 and then handed over
claiming 7. the pinned libdrmtap refuses >4 itself, so this was not an
overflow today - but the stated purpose of that block is that the two
halves of the split agree about what they will touch BEFORE the C sees
it, and that only holds if the count travelling with the descriptor is
the count this side bounded. it also stops this half depending on an
internal check in a library pinned from another repo.

reject and normalize instead, which is what the EXPORT half already
does in grab_desc; the two sides now have the same shape.

* drm: close the round-17 review findings

- the scanout dma-buf fd is duplicated with F_DUPFD_CLOEXEC. `dup(2)`
  never copies close-on-exec, so this fd was inherited by every child
  the ROOT service forks (it forks synchronously for the loginctl
  active-uid lookup) - and what this fd names is the live screen
  contents. this is the SAME defect already closed on the `_drm`
  socket fd in ipc/drm.rs; fixing that one and not grepping for the
  siblings is how this survived. there is exactly one dup in the drm
  path now and it is this one, verified by grep. measured that
  F_DUPFD_CLOEXEC sets FD_CLOEXEC and preserves the O_RDONLY access
  mode the read-only export depends on; SCM_RIGHTS delivery is
  unaffected since the receiver gets its own descriptor.
- Desktop::refresh resolves HOME on the login-Wayland path too, since
  the drm build now starts a --server as the greeter uid there and a
  child with no HOME has nowhere to put its config. the compositor
  variables stay blank deliberately: the drm path talks to the root
  service and a render node, never to the compositor or the portal,
  which is why it works at a login screen at all. reasoned, not
  measured: a current GDM runs its greeter as `gdm-greeter`, which
  `is_gdm_user` does not match, so that path is not reachable on our
  hardware - measured there, the greeter server gets a fully populated
  environment through the branch below.
- the glibc-floor step globs into an array and asserts the count, like
  its sibling assert step. that sibling was fixed two rounds ago and
  this one was left behind.

* drm: put the display wake behind its own compile gate and a runtime option

everything else in this backend READS: it captures a scanout. the wake
WRITES, injecting one synthetic pointer event from the root service
into the user's session. that is a different kind of operation and it
should be switchable on its own, at both levels.

- compile: a `drm-wake` feature on top of `drm`. every wake-only item
  is gated and drm_enumerate_settled has two definitions, so
  `--features drm` builds the same capture path with no wake code in
  the binary. verified on a RELEASE artifact with both controls: the
  drm markers are present (Started drm ipc server) and the wake string
  is gone. the unattended deb passes drm-wake, so answering an
  objection is one word in build.py rather than a revert.
- runtime: `enable-drm-display-wake`, server-side, the same shape
  rustdesk already uses for the closest thing it does to this
  (keep-awake-during-incoming-sessions, which PREVENTS sleep where
  this RECOVERS from it, and is acquired only once a connection
  exists, which is too late for a host that cannot be reached).
  the `enable-` prefix is load-bearing: option2bool reads an absent
  value as ON, and a host whose screen went dark is the case the
  unattended package exists for. set it to "N" and the service stays
  read-only with respect to input.

the key is declared in this file rather than in hbb_common's `keys`
module, where rustdesk's own option constants live: hbb_common is a
submodule of a repo we do not control, so a constant there could only
land after an upstream change plus a submodule bump. the option system
reads by string, so registration is not required; the cost is that the
key is set in the config file rather than the settings UI, which is
how an unattended host is configured anyway.

* drm: enumerate /dev/dri by path instead of trusting one auto-detected card

when `list_devices` gives us nothing to work with, the fallback was a
single auto-detected reader. that is the wrong unit of enumeration on a
multi-card host, and the reason is worth keeping: libdrmtap's
auto-detect picks a card that is SCANNING OUT, so when the interesting
display is asleep it picks a DIFFERENT card and we enumerate only that
one. the asleep display is then invisible - not as a display, and not
as an undriven connector either, which is what the wake keys on.

measured on the t2 with the panel idle-disabled, through a direct
libdrmtap call: auto-detect succeeds and binds card0, the touch bar,
because the touch bar is what is still scanning out; the 2880x1800
panel on card2 is invisible to that reader, while opening card2 by
explicit path in the same instant reports `eDP-1 crtc=0 active=0`
exactly as needed.

so walk /dev/dri/card* and ask each, with auto-detect demoted to a last
resort for the case where no card opens by path. this path is reached
only when list_devices is unavailable (a pre-0.4.15 .so) or opened
nothing, so it costs nothing on the normal path - it is defensive, not
a fix for anything observed with the pinned library.

the enumeration result is logged UNCONDITIONALLY, including the empty
case, because a silent "found nothing" gives no way to tell an empty
host from a failed enumeration.

* docs: state the per-frame reauthz and the wake's one-shot bound

Two things the security doc left implicit, both measured on 2026-07-31.

The `_drm` authorization is described as per-connection, which undersells it.
DRM/KMS capture is not session-scoped - it grabs the physical scanout of a CRTC
no matter which session owns the display - so the check is re-run on every
frame, and when a user logs in at a greeter the greeter's stream is closed
rather than continued. That is the property that stops an outgoing greeter
process from capturing the screen of the user who just logged in, and it is
worth stating where a reader is looking for exactly that confinement.

And the wake section never said what happens after the wake. It resets the
compositor's idle timer; it does not hold the display on. Left alone, the
connector idles off again one full idle period later: 30.3 s at a GDM greeter,
70.3 s in a user session with idle-delay=60. Saying so makes the existing
"useless as a way to keep a screen lit" clause concrete, and points at the
component whose job that actually is.

* drm: ship the wake in the CI deb, and assert the artifact on both package paths

Three findings from the round on the wake-gate commits, all the same shape: the
gate made "what was asked for" and "what was produced" diverge, and two places
still trusted the first.

CI built the unattended-wayland deb with `--features ...,drm` and then packaged
it with `--skip-cargo`. build.py appends `drm-wake` for `--drm`, but skipping
cargo means whatever that explicit line compiled is what ships, so the deb had
no wake code in it at all while being named and documented as the variant that
has it. The feature list has to be complete on the line that actually builds.

The marker assertion that catches exactly this class only guarded one of the two
packaging paths. `build_deb_from_folder` asserts that the staged binary carries
the libdrmtap dlopen path before it takes the unattended-wayland name; the
flutter path did not, and `--skip-cargo` reaches that one. A stock binary could
therefore be packaged under a name that conflicts with and replaces the stock
package, and then never capture. Hoisted the check to module level and called it
from both, before the bundle is renamed.

And the security doc described the synthetic input injection as an unconditional
property of a drm build. It is behind its own compile feature and a runtime
option, which is exactly what an operator auditing the deb needs to know.

* drm: stop a delivered frame from erasing the two verdicts it says nothing about

A deep review pass over the whole branch, run because a maintainer once found
two bugs here that nineteen rounds of an automated reviewer had missed. Three
findings, two of them the same root cause, all confirmed by re-reading the code.

The first frame of a session dropped the display's whole health entry. That is
right for the zero-frame streak, which is exactly the verdict a delivered frame
refutes, and wrong for the other two:

- `last_build`/`rapid_builds` exist for a display that delivers a first frame
  and then fails downstream every cycle. Wiping the cadence on that frame meant
  the flap guard could never reach RAPID_REBUILD_MAX in the one case its own doc
  comment describes. It was a guard that could not fire.
- `prefer_cpu` records which GPU exports a monitor, a property of the host, and
  is documented as following the monitor for the process run. Erasing it on the
  first frame it made possible meant every rebuild re-paid a dead dma-buf
  session: fail, learn, take the CPU path, forget, fail again. It never demotes,
  because the CPU session clears the streak each time, so it repeats for the
  process lifetime. Worse, the bit is set on the recv thread and was deleted on
  the encoder thread, so a convert failure racing a queued frame could destroy
  it inside the very session that learned it.

So reset only the streak. Only a topology change, where the GPU mapping really
can have changed, may still clear the convert verdict.

Second, `get_primary_index` was a second, weaker copy of the connector-to-output
matcher: name-only, with neither the unique-resolution step nor the layout-order
fallback the augmentation grew. On a compositor whose names do not normalize to
the DRM names it answered 0 while the geometry augmentation had matched that
display to a different output, so the advertised primary and the advertised
geometry disagreed. It now asks the same assignment, which makes them agree by
construction.

Third, packaging asserted half of what the deb claims. `assert_staged_binary_is_drm`
looked for the libdrmtap dlopen path, which `--features drm` alone also carries,
so a bundle built without `drm-wake` could still be named and documented as the
variant that wakes an idle-disabled display; it now requires the wake marker too.
And nothing anywhere checked that the libdrmtap being shipped is one the runtime
would accept: `abi_accepted` is the only validation of the pinned version and it
runs at dlopen time on the user's machine, so the pin and the gate could drift
and every existing assertion would still pass -- EGL markers say nothing about
the version, the CI symbol contract never calls drmtap_version(), and the deb
regex matches any version. Staging now applies the gate parsed out of the Rust,
so a green build cannot produce a deb whose capture can never start.

* drm: fix the ABI cross-check's path, and stop panicking on a failed spawn

The ABI cross-check added in the previous commit could never run: both callers
of stage_libdrmtap_into_deb chdir into flutter/ first, and the check opened
drmtap_dl.rs by a path relative to the cwd, so every --drm packaging run died
with FileNotFoundError. CI caught it. It is anchored on __file__ now, and read
through a context manager.

Worth naming why the test missed it: the check was exercised from the repository
root, which is the one directory where the bug is invisible. A control that does
not reproduce the call site's conditions is not a control.

Three more, all the same class the previous commit was already fixing - a
hazard closed at one site and left at its siblings:

- `std:🧵:spawn` panics when the thread cannot be created, and the panic
  unwinds into whoever called it. The two hardened workers used Builder; the
  five remaining DRM threads did not. The startup ones now log and degrade (a
  lost pre-warm costs one cold probe, a lost udev listener costs the mid-session
  push, a lost warm costs the first session), and the two per-session ones live
  in functions that already return ResultType, so they fail that one connection
  cleanly instead of unwinding through the handler.
- The wire descriptor's `num_planes` was clamped to 1..=4 here while
  `drm_render::convert` rejects an out-of-range count on purpose, so that the
  count the C reads is the count this side validated. Clamping made that reject
  unreachable: a descriptor claiming 7 planes arrived as 4 and passed. The two
  guards were added by different review rounds and had been quietly cancelling
  each other. The raw value is passed through now, leaving one validation site,
  next to the code that dereferences it.
- A SAFETY comment claimed the cursor is released only on success. It is
  released on every path after a successful get_cursor; only a failed get_cursor
  returns without releasing, because then there is nothing to release. The
  release protocol is the reason that block is unsafe, so the comment describing
  it has to be right.

* drm: convert the last panicking spawn, and resolve geometry outside the lock

The spawn conversion in the previous commit missed one. `query_displays` still
used `std:🧵:spawn`, which panics when a thread cannot be created, and it
is reached from both `get_capturer_info` and `warm_availability` - so the panic
would land on the capture-build path rather than being reported as the failed
probe every caller already handles. There are now none left in the two DRM
files.

Worth writing down how it survived a pass whose whole purpose was to find it:
the previous commit enumerated the siblings with a grep piped through `head`,
there were eleven matches, and `head` printed ten. The one it cut is the one
that was missed. Same shape as a build log read through `tail` and a `find`
given `-xdev`: the tool truncated the survey and the survey looked complete.
When enumerating sites for a class fix, do not pipe the enumeration.

Also, `get_capturer_for_display` resolved the advertised DRM geometry while
holding the `CAP_DISPLAY_INFO` read guard. That lookup runs a compositor output
roundtrip, and `clear()` takes the write guard on every capturer teardown -
which is what is happening when a display is demoted or flapping, i.e. exactly
when this path runs. The value does not depend on anything inside the guard, so
it is resolved before taking it.

And the security doc listed the unattended package's `Conflicts`/`Replaces` but
not its `Provides: rustdesk`, which is the field that lets a third-party package
depending on `rustdesk` be satisfied by the consent-free variant. An operator
auditing that metadata needs all three.

* drm: test that a delivered frame keeps the cadence and the convert verdict

The guard this locks in could never fire before: a delivered frame dropped the
whole DisplayHealth entry, which took last_build/rapid_builds with it, and those
exist precisely for a display that delivers a first frame and then fails
downstream every cycle. prefer_cpu went the same way, erased by the first frame
it had made possible.

The test drives the real frame() path through the existing harness rather than
simulating the bookkeeping, and it was checked against the old behaviour: with
the entry removed again it fails on "the entry must SURVIVE a delivered frame".
A test that has not been seen failing is not evidence.

* drm: bound the two waits a peer could hold open in the root service

A review pass over the privileged side, reading src/ipc/drm.rs as a local
unprivileged attacker. Two findings, both confirmed by tracing every link.

The wire had a deadline in one direction only. Every read has been bounded since
the beginning, and next_raw_into even carries the argument for it: a peer that
writes a header and then stops pins the other end forever on a readiness wait.
The write side had no deadline at all. That asymmetry costs more here, because
the parked task is in the root service: a peer that simply stops reading - a
kill -STOP on its own --server, a ptrace stop, a frozen cgroup - leaves the send
blocked inside the forward loop, so the loop top is never reached again. The
credit stall, the per-frame reauthorization and the topology-generation check
all live at that loop top, and the connection slot, the worker thread and its
DRM context stay pinned until the peer chooses to resume. drm_write_all is the
single funnel for both directions, so one deadline there covers every send; the
consumer's frame-ack write had the same shape and gets the same bound.

And drain_frame_acks looped until WouldBlock, which is a promise the peer gets
to keep. It is synchronous on the single-threaded _drm runtime, so a peer that
writes a continuous stream instead of one ack byte per frame keeps the receive
queue non-empty, never yields, and pins that thread at 100% CPU - starving every
other stream on it, which on a multi-monitor client means one connection wedging
its own siblings. Capped per call, with an early return once the credit budget
is full; anything left stays queued for the next pass.

Three comments were describing a mechanism that no longer exists. Two still said
a delivered frame drops the whole health entry, which stopped being true when
that was narrowed to zeroing the streak; the third, written in that same change,
pointed at drm_clear_prefer_cpu, a function deleted several commits earlier. The
convert verdict having no clearing site is correct and now says why: it is keyed
by connector identity, so a monitor that moves to another GPU arrives under a new
key and starts clean.

Also, the new regression test held the process-wide health mutex across its
assertions, so the one failure it exists to report would have poisoned that mutex
and buried itself under unrelated PoisonErrors in its sibling tests. It copies
the record out and releases the guard first, as the module's own helper does.

* drm: clear the stale _drm entry by fd, and fix three comments that argue backwards

new_drm_listener cleared the stale socket with std::fs::remove_file, which is
unlink(2). Against a directory-typed squatter that returns EISDIR and leaves the
entry in place, and endpoint.incoming() then fails EADDRINUSE, so DRM capture
falls back to the portal for the rest of the boot over an entry we could have
removed. The _service listener has never had that hole: it removes entries
through a no-follow fd on the parent directory, fstatting the entry first and
choosing AT_REMOVEDIR when it needs to. That helper now takes a path instead of
a postfix, so the _drm listener - which deliberately stays outside hbb_common's
postfix machinery - can use the same one on the directory it just hardened. The
precondition is narrow (an unprivileged process has to win the creation race
before the root service first hardens the dir on a fresh boot), which is why the
failure is a warn and not a bail.

Three comments stated their reason backwards or more strongly than the code
supports. None of them changes behaviour; all three would send the next reader
to verify the wrong thing.

The wake's 20 s rate limit was justified as being short enough to be useless as
a way to keep a screen lit. That is inverted: a shorter gap would make relighting
easier, not harder, and 20 s is below every idle period we have measured (30.3 s
at a greeter, 70.3 s in a session). What actually bounds it is that the wake is
one-shot, which the next sentence of the same doc already says. Fixed at both
sites, the constant and the security doc.

The doc block above drm_enumerate_settled reads as one paragraph but spans a cfg
split, so its shared contract and the wake-less specialisation looked like one
statement about the arm below it. Marked explicitly.

And get_primary_index claimed its answer agrees with the advertised geometry by
construction, which is true only where augment_with_wayland_geometry runs the
same assignment - it declines below two connectors or two outputs, and in that
band the two functions run different code. The answer is still never worse than
the documented fallback there, and now the comment says which.

* drm: test that the fd-based removal clears a directory squatter

The regression this pins is the one the previous commit fixed: a stale entry in
the IPC parent directory is not necessarily a socket, and unlink(2) refuses a
directory. The test asserts remove_file fails on it FIRST, so a passing run
cannot be vacuous, and it checks the second call succeeds too, since this runs
before every bind.

Confirmed red against a neutralised helper before being kept.

* drm: fix what the previous commit's own comments got wrong

A review pass over 08d311d60 - the commit whose stated job was correcting three
comments that argued backwards - found that four of its replacements were wrong
in turn. Two independent passes agreed on each. This is the correction.

The 20 s gap paragraph was never attached to the constant. It is the first
paragraph of a doc block that runs on to OPTION_ENABLE_DRM_DISPLAY_WAKE, so it
documented a config-key string, while DRM_WAKE_MIN_GAP three lines below had no
doc at all. That misplacement predates the previous commit; expanding the
paragraph from one line to five without noticing does not. Moved onto the
constant.

Its content was also wrong for the second time. Saying the limit is not what
stops a screen being held on was right; naming the one-shot property as the
thing that does bound it was not. One-shot cannot bound a repeated relight when
the permitted repeat interval is shorter than the idle period, which is exactly
what the sentence before it establishes: 20 s against a measured 30 s. An
authorized peer that keeps reconnecting can have the panel relit shortly after
each idle-off, and what makes that acceptable is the authorization itself - root
or the active session's own uid, who can hold their screen on with
systemd-inhibit and need nothing from us. Both the constant and the security doc
now say that, and the constant carries a note not to write the old claim a third
time.

The shared contract of drm_enumerate_settled sat on the arm the shipped build
compiles out. build.py --drm adds drm-wake, so a maintainer opening the real
function found it undocumented while a doc comment marked "shared" hung off its
dead twin. A doc comment cannot attach to two cfg arms, so the shared part is
now a plain comment above both and each arm keeps a short doc of its own.

get_primary_index claimed a sole compositor output is matched to the lowest
connector. It is not: pass 1 matches by normalised name and by unique resolution
before any layout-order fallback, so the answer in that band can be any index.
The conclusion survives - a name match is better evidence than a blind 0 - but
the reason given for it was false, and the reason is what the next reader uses.

And the directory case is narrower than it was written. AT_REMOVEDIR is rmdir,
so what the previous commit closes is the EMPTY squatter; a non-empty one still
returns ENOTEMPTY and still blocks the bind. Left that way on purpose - the cure
would be root recursively deleting a tree an unprivileged process planted in a
world-writable directory - and now stated at all three sites plus pinned by the
test, which also stops claiming to cover the call site it does not reach.

* drm: say less in these comments, since saying more keeps being wrong

Third pass over the same comments, and the third set of errors in them. The
pattern is not that any one sentence was careless, it is that every additional
explanatory sentence is another falsifiable claim, and the ones that keep
failing are the ones that reach past what the file can support. So this is
mostly deletion: net fifteen lines fewer.

The "SHARED CONTRACT" header was wrong about its own first paragraph. That
paragraph describes waking, waiting and a rate-limit race, none of which the
wake-less arm does - and the previous commit went further and pointed the
wake-less arm's own doc at it, so that arm now claimed to do the thing the very
next line said it does not. Only the second paragraph, on why an idle-disabled
output is the trigger, is genuinely common to both. That stays above the pair as
a plain comment; the wake behaviour moves onto the wake arm, where it is true.

DRM_WAKE_MIN_GAP no longer argues about why unbounded relighting is acceptable.
It named the wrong actor: the _drm peer is always our own unprivileged --server,
while the party whose reconnects drive the relight is the remote client, which
is neither root nor the local uid and cannot inhibit anything. The constant now
states what it bounds and what it does not, and stops there. The security
document makes the acceptability argument instead, and makes it about the right
party: a peer already authorized to watch that screen gets it lit, which is
visible to a person standing there, not additional access.

Two narrower ones. The helper said a non-empty squatter yields a named error
"instead of" EADDRINUSE; the caller gets both, and the sibling comment in the
listener already said "ahead of", so the same commit disagreed with itself. And
get_primary_index claimed the two functions disagree across the whole band where
augmentation declines, which is false for zero outputs and for a single
connector - it now names the one case that matters.

Not touched, and pre-existing: MAX_DRM_CONNS's doc block has the same wrong-item
defect (it opens on a function and ends on the cap), and drm_enumerate_all_displays
runs two paragraphs together. Both predate this branch's comment work and neither
belongs in a commit about it.

* drm: give the send deadline one budget for the whole write, not one per wait

The earlier commit put the timeout inside the loop, so the budget restarted on
every iteration. A peer that accepts a byte just inside each window, or that
keeps the socket flapping back to WouldBlock, re-arms it forever and the root
task stays parked exactly as it did before - which is the stall the constant's
own doc says it bounds. The diagnosis was right and the fix did not implement
it. Both send paths now take one deadline before the loop and wait with
timeout_at.

Swept the rest of the file for the same shape. The credit wait re-arms a 1 s
poll on purpose and is fine: its total bound is CREDIT_STALL, measured at the
loop top from credit_since, and its comment already says the deadline is
enforced there and not in the poll. That is the pattern the write path was
missing. The read paths are single-shot bounded, not loops.

Not covered by a test. Reproducing it needs a peer that accepts a little data
just inside each window, so the scenario runs longer than the 5 s budget itself
and a no-progress peer - the case a simple test would build - times out
correctly under both the old code and the new.

* drm: stop claiming the wake-less build cannot inject input

It can. Dropping drm-wake removes injection from the CAPTURE path and nothing
else: start_os_service calls start_uinput_service unconditionally, with no
feature gate, so the root service runs RustDesk's keyboard and mouse uinput
backends on every build, drm or not. That is how remote control works on
Wayland and is not ours to change - but a maintainer auditing "is the injection
path present in this build?" was being told no by a comment in the file most
likely to be read for that question. The line now says what is actually true of
the capture path and points at the ungated call, so the next reader is not sent
to verify the wrong claim.

The sentence is inherited: it came in with 2648ad0a2 and survived two review
rounds because both were reading the comments I had just CHANGED, and this one
I only re-wrapped. Re-wrapping is re-asserting.

Also narrowed the wake arm's "the wait applies to every handshake that saw an
undriven display": four early returns skip it - option off, nothing wakeable, no
uinput, no recent wake to settle - and the same block asserts the first of them
four lines later, so the paragraph contradicted itself. And "the trigger" in the
shared block lost its antecedent when the wake paragraph moved onto the wake
arm; it is "the signal" now, which is true for both arms.

* drm: put two doc blocks on the items they describe

Both pre-existing, both found by walking every doc run in the file down to the
item it attaches to rather than by reading prose.

handle_drm_conn's description was stranded: the block opened on the function and
ended on the connection cap, so it attached to MAX_DRM_CONNS while the function
itself had no doc at all. Moved the function's paragraph onto the function; the
cap keeps its own.

And drm_enumerate_all_displays ran its enumeration paragraph and its return-value
paragraph together with no separator, so they read as one. Blank doc line between
them. No text changed in either case - this is placement only.

* drm: pin the send deadline with a test, and close five review findings

The send deadline had no test, and I had written down that it could not have
one: a peer that never reads times out correctly under the broken per-wait form
too, so the obvious test proves nothing. That is true and it is not the whole
answer. A peer that DRIPS separates them, and the first version I wrote still
did not - draining a kilobyte at a time never makes the socket writable again,
because Linux asserts POLLOUT on a stream socket only once a decent fraction of
the send buffer is free, so the sender saw one long readiness wait and both
forms timed out identically. At 64 KiB the socket really does re-arm and the two
diverge. Measured both ways: the test passes in five seconds against the fix and
fails at twenty against the per-wait form, with the message it exists to print.
The chunk size is documented in the test for exactly that reason.

Four more, all verified against the code before touching it:

grab()'s SAFETY block claimed the frame is "released on every path". The ret < 0
arm returns without releasing, because a failed grab_mapped leaves nothing to
release. Its two siblings, grab_desc and cursor, already state the distinction
precisely; this was the loose copy, and the release protocol is the reason the
block is unsafe in the first place.

drmtap_dl.rs still said minor bumps are additive and compatible. abi_accepted
requires an exact minor match and the block below it explains why, so the file
argued both sides and the stale half is an invitation to widen the gate.

grab_desc validated width, height and plane count but not pitch or offset, while
the converter bounds pitch * height + offset per plane. Same bound on the export
side now, so both halves refuse the same descriptors - the principle grab()
already states. No pixel access happens there, so this is not an out-of-bounds
fix; it keeps a bogus pitch off the wire and puts the rejection on the side that
can name the device.

And the deb staging interpolated so_path unquoted, which breaks on a path with a
space (DRMTAP_PREBUILT_DIR is user-supplied).

Also covers the regular-file case through the new removal helper - the stale
socket every restart hits, which the existing file test reaches by another path.

* build: quote the rest of the path interpolations, not just the two that were named

The previous commit quoted so_path and stopped there, which left the six shell
commands that build libdrmtap interpolating src and build_dir bare. Both derive
from repo_root, which is built from __file__, so a checkout under a path with a
space splits the argument and git init, git remote add, git fetch, git checkout,
meson setup and meson compile all fail with an error that says nothing about the
real cause. Same defect, same fix, and quoting one pair while leaving its
siblings is the shape a reviewer finds next.

* fix(drm): close the review items on the capture backend

Guard the producer thread, surface a swallowed spawn error, stop the CI
feature list from drifting from build.py, and four smaller ones.

Should-fix:

- `start_os_service` started the DRM producer with a bare `thread::spawn`,
  the one spawn in this feature that was not built with `thread::Builder`.
  `spawn` panics if the thread cannot be created (EAGAIN under a thread or
  memory limit), and that panic unwinds out of `start_os_service` and takes
  the root service with it -- for a feature whose failure should only cost
  DRM capture. Builder + warn, like the other four.

- `refresh_available_async` dropped the spawn result on the floor. There is
  no wedge (the single-flight guard moved into the closure and is dropped
  with it), but a refresh that can never start was invisible: the cached
  verdict just keeps being served past its TTL. The sibling spawn already
  logged; now both do.

- The drm workflow hardcoded the cargo feature list because it packages with
  `--skip-cargo`, so `get_features()` in build.py and the CI line were two
  definitions of the same thing and only the drm/drm-wake half was asserted
  afterwards. Adds `build.py --print-features`, which prints the list those
  flags select and exits, so CI asks instead of repeating; the same flags now
  drive the compile and the packaging. The step asserts the answer really is
  a drm build before handing it to cargo, matching whole comma-separated
  tokens so a future feature merely containing "drm" cannot satisfy it.

Smaller:

- The ENOTSUP fallback in `drm_capture_worker` switched to the CPU path
  without clearing `stalled`, so stalls charged to the dma-buf path could
  trip MAX_STALLED early and close a connection the fallback was about to
  serve.

- `FrameSlot` kept one recycled buffer and claimed at most one is idle at a
  time, which does not hold: the receive path supersedes an unconsumed frame
  while the encoder returns its borrow, and those two writers do not even
  share a lock, since the receive path takes a buffer and publishes in two
  separate acquisitions. The later write freed a scanout-sized allocation the
  recycler exists to keep. Two slots is the exact bound for three in-flight
  buffers. The existing test passed against this, so the new one counts the
  offers rather than asking whether any came back.

- `get_cursor`/`get_cursor_data` use the memoised `is_x11()` while the
  capture path deliberately uses the unmemoised `scrap::is_x11()`. That is
  the right trade at cursor cadence, since the unmemoised form forks
  `loginctl` per call -- say so, because the surrounding code argues the
  opposite for its own callers.

* docs(drm): cut the changelog prose out of the comments

Removes passages that document this patch's own revision history rather
than the code, including the four quoted in review. Deletions and one
misplaced comment moved to the field it describes; no comment was
reworded, so nothing here can state something new.

- `drm_capturer.rs`: the `drm_clear_prefer_cpu` parenthetical (that
  function does not exist), "same mistake, same shape, as the two flags
  before it" (it names no identifier, and both sites it gestures at carry
  their own hazard comments), and "the comment was right and the code used
  the probing accessor anyway".
- `drmtap_dl.rs`: "this test replaces one that asserted the opposite", and
  "that sentence used to live here" -- the instruction not to widen the
  gate on the strength of "minor bumps are additive" stays, since that is a
  live constraint rather than history.
- `platform/linux.rs`: the "NOT REPRODUCIBLE ON OUR HARDWARE" provenance
  label. What it introduced survives and is the better form of the same
  warning: on the test host `is_gdm_user` does not match `gdm-greeter`, so
  that branch is dead there and the code is for display managers whose
  greeter user does match.
- `ipc/drm.rs`: "and that sentence has already been wrong here twice". The
  warning it trailed stays, because a shorter gap really would make
  relighting easier and the constant should not be described as bounding
  how long a screen stays lit.
- `build.py`: "the answer to an objection is one word, not a revert".

Also moves the comment describing `cur` off `display`, where a field
reorder had left it sitting above that field's own comment.

Most of the remaining density is mechanism, measurement or a hazard, and
is left alone: the pipe/SIGPIPE analysis, the physical-vs-logical rect
comparison, the `wire_idx` vs `display` argument, the wake measurements
(REL_X alone did not wake the panel; the device bind window), the
F_DUPFD_CLOEXEC privilege-leak argument, and the SAFETY blocks.

* docs(drm): condense the capture comments from 35% of lines to 6%

The five DRM files were 2319 comment lines against 4181 of code. The rest
of this repository runs at 3%, so they were roughly twelve times the
surrounding density, and that was the fair reading of the review: the
volume itself is what makes an 8k-line addition hard to review.

They are now 302 lines. What went is rationale: alternatives considered
and rejected, arguments for why a design is acceptable, restatements of
what the next line of code plainly says, and the same fact repeated at
several sites.

What stayed is what a reader cannot recover from the code, kept to one or
two lines each:

- every SAFETY comment on an unsafe block (none was dropped)
- ownership and release contracts with the libdrmtap C API, including
  which grabs own a frame and which must not release it
- ordering requirements: announce a pending refresh before claiming the
  single-flight slot, take the busy flag before the spawn rather than
  inside the closure, never hold DRM_STATE while taking a per-display map
- the flow-control protocol, both ends of it
- wire-format and units conventions, and the cmsghdr alignment the
  control-buffer type exists to provide
- measured facts, reduced to the measurement: which synthetic events wake
  an idle panel and which do not, and the device bind window
- hazards on the world-connectable listener, including why the rejection
  paths log at debug or not at all

No code changed: with comments and blank lines stripped, all five files
are byte-identical to their previous contents. Tests are 111 in the
rustdesk crate and 20 in scrap.

* docs(drm): restore the wire_idx argument on the hotplug guard

The condensation cut this one too far. Within minutes of the shortened
version going up for review, a reviewer read the remaining line and
proposed changing the probe from `display` to `wire_idx` -- which is the
change that was already tried here and was wrong.

So the argument is not rationale prose, it is what stops a plausible and
incorrect edit to a guard in the capture path, and it goes back in at six
lines: `bound_to` is an identity rather than a position, the swap below
installs this list as the client-space DRM_STATE, and probing `wire_idx`
would go quiet in precisely the case the guard exists to catch.

* docs(drm): correct what an empty render_node means on the wire

The condensed doc said "Empty = auto-select", which is false on the host
that field exists for. `drm_capture_worker` computes
`ambiguous_gpu = render_node.is_empty() && render_node_count() > 1` and
folds it into `force_cpu`, so an unnamed exporter on a machine with
several render nodes takes the CPU path rather than auto-selecting. It
auto-selects only where there is a single node.

* docs(drm): fix comment claims that do not match the code

An audit that verified every comment claim against the CODE (rather than
against the pre-condensation text, which is what the earlier pass did)
found twenty that were false or unqualified. Some came from the
condensation dropping a qualifier; several predate it.

The ones that mattered most:

- `drm_render.rs` said libEGL/libGLESv2 are loaded "never in the
  privileged root service". That is true of the split path only: the CPU
  fallback calls `drmtap_grab_mapped`, whose auto-process step reaches
  `drmtap_gpu_egl_convert` in the CALLING process. `DRM_CAPTURE_SECURITY.md`
  already documents this precisely, and `drm_reader.rs` already said "on
  this path"; this one comment had lost the qualifier.
- "A miss is fail-closed" on the per-frame reauthorization: true for a
  non-root peer only, since `drm_peer_authorized` returns true for uid 0
  before it compares against the active session.
- The cursor body check was described as a no-op because the hidden
  sentinel supposedly arrives 0x0 with an empty body. It arrives 1x1 with
  four bytes, so the check is live.
- "EVERY write to DRM_STATE goes through here": the TTL restamp writes
  directly, and the comment on that arm says so.
- `open(crtc=0)` was described as selecting the "primary" CRTC; libdrmtap
  picks the first CRTC with a valid mode, and in that library "primary"
  names a plane.
- `list_devices() == None` was described as leaving the caller on
  single-device auto-detect; the caller scans /dev/dri/card* itself.
- The framing note claimed the whole channel is length-prefixed; the
  reverse-direction frame acks are bare bytes.

Also corrects `buffer_id`, which was documented as the producer's stable
pool key: it is fb_id tagged with a per-connection epoch and no consumer
reads it today.

No behaviour changes. One executable line is touched: the message string
of a unit-test `assert!` that asserted the auto-select claim being
corrected here.

* docs(drm): fix the second primary-CRTC occurrence the audit flagged

Same correction as the enumeration-side comment: libdrmtap auto-selects
the first CRTC with a valid mode, and primary names a plane there. The
audit had flagged both sites and only one was fixed.

* feat(drm): move the libdrmtap pin to 0.5.2 and the ABI gate with it

libdrmtap 0.5.2 is now on rustdesk-org, so the pin can move. It fixes the
padded-framebuffer read: a scanout whose pitch exceeds width*bpp was
decoded at the wrong stride, which is why the Touch Bar strip on an Apple
T2 produced no image and was listed as a known limitation.

The three parts have to land together, and build.py enforces it: the
staged .so is cross-checked against the ABI constants parsed out of
drmtap_dl.rs, so a pin without the gate (or a gate without the pin) fails
the build rather than producing a deb whose capture can never start.

- pin: cbc5e6af5 (0.4.15) -> 653de8c (0.5.2), in build.py, which is the
  single source of truth, plus the informational version comment in
  libs/scrap/Cargo.toml.
- gate: DRMTAP_ABI_MINOR 4 -> 5 and the patch floor (4, 10) -> (5, 0).
  0.4.x is now refused even though it carries the whole split API, because
  of the stride bug above.
- the newer-minor rejection test now derives its cases from
  DRMTAP_ABI_MINOR rather than hardcoding 5, so the next bump cannot leave
  it asserting that the newly verified minor must be refused. That is
  exactly what the hardcoded list would have done here.
- DRM_CAPTURE_SECURITY.md: the vetted window is now 0.5.x with x >= 0.

Verified: the build fetches 653de8c by sha and meson produces
libdrmtap.so.0.5.2, which the runtime gate accepts. Tests 111 in the
rustdesk crate, 20 in scrap.

* fix(drm): refuse --drm on the packaging paths that cannot honour it

Blocking finding from review. `get_features()` gated only on `windows or
osx`, but Linux has four packaging branches and only the deb one is
drm-aware. On a host with pacman, yum or zypper, `--drm` compiled in
`drm,drm-wake` and then packaged through a path that does not bundle
libdrmtap, does not rename, adds no Conflicts/Provides and never runs
`assert_staged_binary_is_drm()` -- emitting a package NAMED `rustdesk`
carrying the consent-bypass backend and the root-side uinput injection.

The distinctly named package is the informed consent this feature rests
on, so those branches now refuse the flag instead. `linux_packaging_branch()`
mirrors the elif chain in main() and is the single place that decides,
so the check cannot silently disagree with the branch actually taken.

Also from the same review:

- the bare-soname dlopen fallback is no longer offered when running as
  root. It exists so an unpackaged development build can load a locally
  built .so, but it was also the one place where which file happens to be
  on the ld.so path decided what gets mapped into the CAP_SYS_ADMIN
  process. The packaged service finds the absolute path first regardless,
  and a root process that reaches the fallback has no bundled library at
  all, which is the PipeWire-fallback case rather than a reason to search.
- `rm -f {so}` is quoted, like the neighbouring `cp` already was.
- `Cargo.lock` is dropped as a CI path trigger. Measured over the last 100
  commits it alone would have fired this workflow 13 times and the pair 24
  times, each about two job-hours of vcpkg + flutter release build, almost
  always for a dependency the drm path never touches.
- `abi_gate_rejects_a_library_from_before_the_split` no longer implies the
  patch floor is what refuses those versions; the minor mismatch is. The
  floor is vacuous by construction while it sits at patch 0 of the
  verified minor, so a second test asserts exactly that and turns into a
  tripwire the next time a floor lands mid-minor, as (4, 10) did.
2026-08-06 12:20:57 +08:00
.cargo Add Windows arm64 support (#15139) 2026-06-18 22:37:15 +08:00
.github feat(linux): DRM/KMS direct capture for Wayland — no portal consent required (#15420) 2026-08-06 12:20:57 +08:00
appimage bump to 1.4.9 2026-07-06 18:00:39 +08:00
docs feat(linux): DRM/KMS direct capture for Wayland — no portal consent required (#15420) 2026-08-06 12:20:57 +08:00
examples ipc example for test (#11127) 2025-03-14 00:21:05 +08:00
fastlane/metadata/android Revert "Translations update from Toolate (#11510)" (#11535) 2025-04-22 16:53:38 +08:00
flatpak Propose fix some typos (#14857) 2026-04-21 16:27:39 +08:00
flutter refact(oidc): manually open the browser (#15706) 2026-08-04 12:35:04 +08:00
libs feat(linux): DRM/KMS direct capture for Wayland — no portal consent required (#15420) 2026-08-06 12:20:57 +08:00
res Fix default Android API version mismatch between vcpkg and rest of build (for working on android 6) (#14850) 2026-07-10 11:38:43 +08:00
src feat(linux): DRM/KMS direct capture for Wayland — no portal consent required (#15420) 2026-08-06 12:20:57 +08:00
.gitattributes .gitattributes 2021-08-05 11:27:56 +08:00
.gitignore feat(linux): DRM/KMS direct capture for Wayland — no portal consent required (#15420) 2026-08-06 12:20:57 +08:00
.gitmodules fix submodule repository (#13975) 2026-01-07 14:11:20 +08:00
AGENTS.md fix(windows): prevent ghost and duplicate tray icons (#15689) (#15690) 2026-07-29 12:18:57 +08:00
build.py feat(linux): DRM/KMS direct capture for Wayland — no portal consent required (#15420) 2026-08-06 12:20:57 +08:00
build.rs webrtc 2025-11-28 10:45:48 +08:00
Cargo.lock fix: Harden Windows installer temp command scripts (#15634) 2026-08-04 14:29:04 +08:00
Cargo.toml feat(linux): DRM/KMS direct capture for Wayland — no portal consent required (#15420) 2026-08-06 12:20:57 +08:00
CLAUDE.md improve agent md 2026-04-09 15:12:57 +08:00
Dockerfile Fix for compilation due to minimum Cmake version update and arm based compilation of vcpkg (#10297) 2024-12-17 10:37:57 +08:00
entrypoint.sh more "cargo build --locked" 2026-05-26 11:45:15 +08:00
GEMINI.md improve agent md 2026-04-09 15:12:57 +08:00
LICENCE Create LICENCE 2022-05-29 23:01:09 +08:00
README.md Add Romanian Locale (#13270) 2025-10-27 16:52:36 +08:00
vcpkg.json Fix default Android API version mismatch between vcpkg and rest of build (for working on android 6) (#14850) 2026-07-10 11:38:43 +08:00

RustDesk - Your remote desktop
BuildDockerStructureSnapshot
[Українська] | [česky] | [中文] | [Magyar] | [Español] | [فارسی] | [Français] | [Deutsch] | [Polski] | [Indonesian] | [Suomi] | [മലയാളം] | [日本語] | [Nederlands] | [Italiano] | [Русский] | [Português (Brasil)] | [Esperanto] | [한국어] | [العربي] | [Tiếng Việt] | [Dansk] | [Ελληνικά] | [Türkçe] | [Norsk] | [Română]
We need your help to translate this README, RustDesk UI and RustDesk Doc to your native language

Caution

Misuse Disclaimer:
The developers of RustDesk do not condone or support any unethical or illegal use of this software. Misuse, such as unauthorized access, control or invasion of privacy, is strictly against our guidelines. The authors are not responsible for any misuse of the application.

Chat with us: Discord | Twitter | Reddit | YouTube

RustDesk Server Pro

Yet another remote desktop solution, written in Rust. Works out of the box with no configuration required. You have full control of your data, with no concerns about security. You can use our rendezvous/relay server, set up your own, or write your own rendezvous/relay server.

image

RustDesk welcomes contribution from everyone. See CONTRIBUTING.md for help getting started.

FAQ

BINARY DOWNLOAD

NIGHTLY BUILD

Get it on F-Droid Get it on Flathub

Dependencies

Desktop versions use Flutter or Sciter (deprecated) for GUI, this tutorial is for Sciter only, since it is easier and more friendly to start. Check out our CI for building Flutter version.

Please download Sciter dynamic library yourself.

Windows | Linux | macOS

Raw Steps to build

  • Prepare your Rust development env and C++ build env

  • Install vcpkg, and set VCPKG_ROOT env variable correctly

    • Windows: vcpkg install libvpx:x64-windows-static libyuv:x64-windows-static opus:x64-windows-static aom:x64-windows-static
    • Linux/macOS: vcpkg install libvpx libyuv opus aom
  • run cargo run

Build

How to Build on Linux

Ubuntu 18 (Debian 10)

sudo apt install -y zip g++ gcc git curl wget nasm yasm libgtk-3-dev clang libxcb-randr0-dev libxdo-dev \
        libxfixes-dev libxcb-shape0-dev libxcb-xfixes0-dev libasound2-dev libpulse-dev cmake make \
        libclang-dev ninja-build libgstreamer1.0-dev libgstreamer-plugins-base1.0-dev libpam0g-dev

openSUSE Tumbleweed

sudo zypper install gcc-c++ git curl wget nasm yasm gcc gtk3-devel clang libxcb-devel libXfixes-devel cmake alsa-lib-devel gstreamer-devel gstreamer-plugins-base-devel xdotool-devel pam-devel

Fedora 28 (CentOS 8)

sudo yum -y install gcc-c++ git curl wget nasm yasm gcc gtk3-devel clang libxcb-devel libxdo-devel libXfixes-devel pulseaudio-libs-devel cmake alsa-lib-devel gstreamer1-devel gstreamer1-plugins-base-devel pam-devel

Arch (Manjaro)

sudo pacman -Syu --needed unzip git cmake gcc curl wget yasm nasm zip make pkg-config clang gtk3 xdotool libxcb libxfixes alsa-lib pipewire

Install vcpkg

git clone https://github.com/microsoft/vcpkg
cd vcpkg
git checkout 2023.04.15
cd ..
vcpkg/bootstrap-vcpkg.sh
export VCPKG_ROOT=$HOME/vcpkg
vcpkg/vcpkg install libvpx libyuv opus aom

Fix libvpx (For Fedora)

cd vcpkg/buildtrees/libvpx/src
cd *
./configure
sed -i 's/CFLAGS+=-I/CFLAGS+=-fPIC -I/g' Makefile
sed -i 's/CXXFLAGS+=-I/CXXFLAGS+=-fPIC -I/g' Makefile
make
cp libvpx.a $HOME/vcpkg/installed/x64-linux/lib/
cd

Build

curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
source $HOME/.cargo/env
git clone --recurse-submodules https://github.com/rustdesk/rustdesk
cd rustdesk
mkdir -p target/debug
wget https://raw.githubusercontent.com/c-smile/sciter-sdk/master/bin.lnx/x64/libsciter-gtk.so
mv libsciter-gtk.so target/debug
VCPKG_ROOT=$HOME/vcpkg cargo run

How to build with Docker

Begin by cloning the repository and building the Docker container:

git clone https://github.com/rustdesk/rustdesk
cd rustdesk
git submodule update --init --recursive
docker build -t "rustdesk-builder" .

Then, each time you need to build the application, run the following command:

docker run --rm -it -v $PWD:/home/user/rustdesk -v rustdesk-git-cache:/home/user/.cargo/git -v rustdesk-registry-cache:/home/user/.cargo/registry -e PUID="$(id -u)" -e PGID="$(id -g)" rustdesk-builder

Note that the first build may take longer before dependencies are cached, subsequent builds will be faster. Additionally, if you need to specify different arguments to the build command, you may do so at the end of the command in the <OPTIONAL-ARGS> position. For instance, if you wanted to build an optimized release version, you would run the command above followed by --release. The resulting executable will be available in the target folder on your system, and can be run with:

target/debug/rustdesk

Or, if you're running a release executable:

target/release/rustdesk

Please ensure that you run these commands from the root of the RustDesk repository, or the application may not find the required resources. Also note that other cargo subcommands such as install or run are not currently supported via this method as they would install or run the program inside the container instead of the host.

File Structure

Screenshots

Connection Manager

Connected to a Windows PC

File Transfer

TCP Tunneling