Compare commits

..
Author SHA1 Message Date
rustdeskandClaude Opus 5.5 7871c64804 docs(agents): handle corner cases raised in review with small fixes or docs
A refactor added to cover a corner case rarely converges: new counters,
timestamps and expiry rules interact with state existing code relies on,
and the next review round finds the problems they introduced. Fix a corner
case when the fix is a few lines with no new state; otherwise document it
as a known limit, and ask before anything larger.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-25 15:36:05 +08:00
rustdeskandClaude Opus 5.5 00613bcabe fix(clipboard): drop read-time refresh, idle expiry and rebuild reuse; tighten checks
Remove the read-time recency and the 5-minute idle expiry on both owners,
and the unix reuse of an unchanged rebuild (has_same_files). They covered
corner cases, added state, and each brought regressions of its own. Kept
lists are again evicted oldest first (unix) or least recently sent
(Windows), 4 at most; a transfer that outlives 4 newer lists fails cleanly.

Windows: serve kept lists after the existing ownership check again, so a
request carrying a list id no longer bypasses it while the host clipboard
holds files from another session. Refuse request types other than size or
range before allocating.

unix: a retired list's file must still match the size and modified time it
was listed with, checked on the handle the read uses; a file replaced at
its path before its read now fails instead of being served.

Tests: drop the four tests of the removed behavior, add
a_retired_list_refuses_a_file_replaced_before_its_read.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-25 15:36:05 +08:00
rustdeskandClaude Opus 5.5 9be47e9a38 test(clipboard): unix, check list expiry without backdating an Instant
an_idle_retired_list_expires backdated a timestamp with
Instant::now().checked_sub(TTL + 1s), which is None while the monotonic
clock is under about five minutes, as on a freshly booted CI machine; the
list then never expired and the test failed. expire_retired now takes the
current time, and the test passes a later one instead. Callers pass
Instant::now(), so behavior is unchanged.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-25 13:51:22 +08:00
rustdeskandClaude Opus 5.5 dbad8948f2 fix(clipboard): cap Windows ranges, expire idle kept lists, check file identity
Windows owner: refuse every FILECONTENTS_RANGE over 16 MiB before
allocating. Only the served-list branch was capped; requests without an id
still allocated whatever the peer asked for, up to 4 GiB.

Both owners: a kept (retired / non-current) file list that nobody has read
for 5 minutes is dropped, with its open files; its transfer is over or its
peer gone. The current list never expires, as before. On Windows, reads of
the current list through the existing path now also refresh its kept copy,
so a long transfer does not lose its list once a newer one is sent.

Windows owner: old-list reads compare the file's size and last-write time
with the descriptor that was sent, on the handle they read from, and fail
on a mismatch instead of reading whatever file now has that path.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-25 13:25:30 +08:00
rustdeskandClaude Opus 5.5 6231589fef fix(clipboard): unix, keep files being read open when their list is retired
Retiring a list closed every file handle, so the next read of a file part-way
through reopened it by path. If that path had been replaced meanwhile (an
editor saving over it), the rest of the transfer came from the replacement:
AAAABBBB arrived as AAAADDDD. Close only files that are not being read, such
as the preloaded next file; a file part-way through keeps its handle and
offset, and so its identity.

Tests read two files of one list alternately, retire the list, replace both
paths by rename, and check each file continues with its original bytes.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-25 01:13:56 +08:00
rustdeskandClaude Opus 5.5 31fd4e3744 fix(clipboard): unix, keep retired lists in the order they were sent
A peer that sends no list id is served the list last sent to its
connection, found by searching the retired queue from the back. That only
holds while the queue stays in retirement order, which is the order lists
were sent. The previous commit moved a list to the back on every read, so
another connection reading an older list could make a peer's next chunk
come from that list: a transfer of B continued with A's bytes.

Keep the queue in retirement order and track recency in a separate
last_used stamp, set on retirement and on each read. A full queue evicts the
list with the lowest stamp, so a list still being read is kept.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-24 23:22:13 +08:00
rustdeskandClaude Opus 5.5 98a7df06cb fix(clipboard): keep a file list while it is being read, throttle read errors
A unix paste side fetches every new file list as soon as the host copies,
so each copy retires the previous list, and four copies during one long
transfer evicted the list it was still reading. A kept list that serves a
read now becomes the most recent (unix: back of the retired queue, Windows:
last_served), so the next eviction takes a list nobody is reading.

A failed file-contents read logged an error per request, and peers can now
trigger new ones (an unknown list id, an over-limit range). Log it through
throttled_log! instead.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-24 21:19:13 +08:00
rustdeskandClaude Opus 5.5 f72946d71c fix(clipboard,enigo): bound served-list reads, clamp absolute moves
wf_cliprdr: the served-list branch runs before the ownership check, yet it
allocated the peer's cbRequested (up to 4 GiB) before looking the list up.
Accept only FILECONTENTS_SIZE or a range of at most 16 MiB there, which is
all that clients sending an id ever request, and fail anything else before
allocating.

enigo: clamp the scaled absolute coordinate to 0..=65535, the range
MOUSEEVENTF_ABSOLUTE takes, instead of to the i32 range. Coordinates on the
virtual desktop give the same result as before; off-desktop ones now land on
its edge.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-24 18:01:24 +08:00
rustdeskandClaude Opus 5.5 4b5b3bc497 fix(clipboard): give each copied file list its own id
The list id hashed only the descriptors, so two copies with identical
names, sizes and times (the same file in two folders) shared an id and a
transfer could read the other copy's files. Each owner now writes a random
nonce into the first descriptor's clsid, inside the reserved bytes every
peer skips; no owner sets FD_CLSID. The paste side hashes what it received,
so it needs no change, and older peers ignore the bytes. Re-sending the same
paths with the same descriptors keeps the nonce, and the id.

Windows owner:
- Serve a request from its list before the ownership check when the list is
  no longer current or the host clipboard now holds files from a peer, so
  another controller copying onto the host no longer fails in-flight
  transfers. Only lists sent to that connection are served.
- Evict the list sent least recently instead of in insertion order.

unix owner: take everything from the crate in one use block.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-24 17:25:47 +08:00
rustdeskandClaude Opus 5.5 6cf799cb8e fix(clipboard): review fixes for the file lists kept per transfer
unix owner:
- A retired list closes its files and 8 MiB read buffers; they reopen,
  from offset 0, on the next read.
- The new list is built aside and swapped in only on success, so a failed
  rebuild leaves the current list in place.
- A rebuild with an unchanged id keeps its peers on the new list instead of
  retiring a duplicate, so re-copying a directory no longer pushes out a
  list that a transfer is still reading.

Windows:
- One served-list slot per list, recording every connection it was sent
  to, so pastes of the same list do not use up slots.
- A request for an earlier list is served before OleGetClipboard, so a busy
  clipboard cannot fail it.
- An IStream read over 16 MiB is split into requests the unix file server
  accepts. Reads up to 16 MiB take the unchanged path.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-24 15:57:38 +08:00
rustdeskandClaude Opus 5.5 aec5229a11 fix(enigo): win, warn (throttled) when a mouse move is skipped
A missing virtual screen size is a fault that should show up in a user's
log, but mouse_move_to runs per input event. Log it at warn at most once a
minute via throttled_log! instead of at trace.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-24 15:05:54 +08:00
rustdeskandClaude Opus 5.5 daff54387b fix(clipboard): unix file server, cap a single range read at 16 MiB
A peer could still make the server allocate and read up to the 1 GiB frame
limit per request. Cap the data a single range read returns at 16 MiB. The
read is clamped to the rest of the file first, and a larger one is refused
rather than shortened: a short response reads as end of file to IStream
callers on Windows and would silently truncate the copy.

macOS requests 4 MiB per range (BLOCK_SIZE) and FUSE reads are smaller. A
Windows client forwards the application's IStream::Read size, so only an
application reading more than 16 MiB in one call is affected.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-24 15:05:54 +08:00
rustdeskandClaude Opus 5.5 a93d0756ff fix(clipboard): keep file transfers on the file list they started from
A file-contents request names a file only by its index, and the side that
owns the files resolved it against whatever it held at that moment. On
Windows 10+ Explorer's clipboard also offers FileContents, which the owner
re-read from the live clipboard for every chunk, so copying another file
mid-transfer spliced the new file into the one being pasted (#16332). A
second paste, or another connection's paste, replaced the list the same
way, and on macOS/Linux sync_files replaced CLIP_FILES on every host copy.

Each request now names its list in the existing clip_data_id field: an
FNV-1a hash of the file-descriptor PDU, which both sides already hold.
Owners keep the last 4 lists they sent and serve a request from the list
it names; an unknown id fails instead of reading another file. Peers that
send no id read the list last sent to their connection, and a Windows
owner stops reading the live clipboard once it has changed since the list
was built.

Tests cover a host copy and a second paste during a transfer, a list id
sent to another connection, and the hash's reference vectors.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-24 15:03:25 +08:00
rustdeskandClaude Opus 5.5 8cf2c74a76 fix(clipboard): unix file server, reject range reads over the frame limit
A response larger than MAX_FRAME_LENGTH (1 GiB) cannot be encoded for
sending, yet the server allocated and read it first, then failed the send.
Reject such requests before allocating, so a peer can no longer make the
server allocate more than 1 GiB per request. Requests that work today are
unaffected.

Drop the extra allocation-failure log; the caller already logs the error.

Tests cover the wire decoding through read_file_contents (negative
cbRequested, nPositionLow past 2 GiB) and the frame-limit rejection. Tests
that use the global CLIP_FILES now take a shared lock.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-24 10:23:27 +08:00
rustdeskandClaude Opus 5.5 c8a80ec74b docs(agents): avoid unthrottled high-frequency debug logs
Debug output is written to the log file, so per-packet / per-event log sites
must use trace or hbb_common's throttled_log!.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-24 10:03:30 +08:00
rustdeskandClaude Opus 5.5 640fb32c3c fix(enigo): win, scale absolute mouse moves without overflow
mouse_move_to multiplied the peer-supplied coordinate by 65535 in i32,
which overflows for large values, and divided by the virtual screen size,
which panics if the metrics come back as 0. Scale in i64, clamp to i32,
and skip the move when the virtual screen size is unavailable. Results
for inputs that did not overflow are unchanged.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-24 09:59:26 +08:00
rustdeskandClaude Opus 5.5 cccf9019e0 fix(clipboard): unix file server, bound range reads
The Range request fields nPositionLow and cbRequested are UINT32s carried
in i32 fields, but were sign-extended to u64. A negative cbRequested
became a near-u64::MAX length, `offset + length` wrapped past the clamp,
and the server tried to allocate a u64::MAX buffer, aborting the process.
Sign-extending nPositionLow also rejected offsets whose low word is
>= 2 GiB, breaking reads past 2 GiB in large files.

- decode nPositionLow and cbRequested as u32
- clamp with `length > file.size - offset` (offset <= size is checked above)
- allocate the read buffer fallibly and return an error instead of aborting

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-24 09:59:26 +08:00
58ff78a823 Hdr tonemap (#16033)
* scrap: tone-map HDR desktops to SDR in the Windows capturer

With HDR enabled, Windows composes the desktop as linear scRGB in
R16G16B16A16_FLOAT and places SDR white at the user's "SDR content
brightness" (DISPLAYCONFIG_SDR_WHITE_LEVEL / 1000, e.g. 2.5 for 200
nits) rather than at 1.0. The legacy IDXGIOutput1::DuplicateOutput we
used always converts that surface to BGRA8, and it does so by clipping,
so everything above ~40% linear brightness lands on white. That is the
washed-out / overexposed / high-contrast picture reported for HDR hosts
in #5368, #9951, #12707 and discussion #7652.

Ask for the desktop with IDXGIOutput5::DuplicateOutput1 and the format
list [R16G16B16A16_FLOAT, B8G8R8A8_UNORM]. An SDR desktop still yields
BGRA8 and takes the unchanged path. A float frame is converted on the
GPU by a small pixel shader: divide by the SDR white level, clamp, apply
the sRGB transfer. SDR content round-trips exactly, HDR highlights clip
at white, the same result the local user sees. The white level is read
per output through DisplayConfigGetDeviceInfo and refreshed once a
second, so dragging the Windows slider tracks remotely. The converted
BGRA8 texture feeds both the staging-copy (CPU) path and the vram
(hwcodec texture) path; rotation is unchanged. Toggling HDR mid-session
invalidates the duplication as before, and the recreated capturer
re-detects the format.

The shaders are compiled at runtime from a dynamically loaded
d3dcompiler_47.dll so no new import is added to the binary. If the DLL,
the compile or any D3D object creation fails, a process-wide flag makes
later capturers fall back to the legacy DuplicateOutput, i.e. today's
behaviour.

This deliberately stops at SDR on the controlled side, with no option
and no protocol change, which is how OBS, Sunshine (client without HDR)
and macOS screen capture handle it. Real HDR pass-through would need
10-bit capture, Main10/AV1-10 encoders in the hwcodec fork, colour
metadata on the wire and, decisively, an HDR output path on the
controller: Flutter's desktop external textures are BGRA8888/RGBA8888
only on every platform, so nothing would be visible. When that changes
it should follow the Sunshine/Moonlight pattern: an hdr capability bit
advertised by the controller behind an explicit user toggle, negotiated
like i444.

Type-checked against x86_64-pc-windows-msvc (with and without the vram
feature); not yet run on an HDR machine, which needs Windows 10 1703+
with HDR on.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RLb1dNdhFqUQExJPANjo1F
(cherry picked from commit ca3c2f8ac7d1549a40855411b0539a69c82d7223)

* scrap: stay on DXGI when the HDR conversion fails, load the compiler once

Review follow-up:

- A tone-map failure surfaced as a capture error, and the capture loop
  answers any DXGI error by switching the capturer to GDI for the rest
  of its life. The capturer now drops the tone-map, re-creates the
  duplication with the legacy DuplicateOutput (DXGI's clipped BGRA8,
  the pre-HDR behaviour) and returns WouldBlock, so the session stays
  on DXGI and simply fetches the next frame.

- Only failures that cannot succeed anywhere in the process (no
  d3dcompiler_47.dll, shaders that do not compile) set the global
  UNAVAILABLE flag; D3D object creation failures stay with the capturer
  that hit them, so another adapter or a recreated capturer tries again.

- D3DCompile is resolved once through a OnceLock instead of a
  LoadLibrary per capturer that was never freed.

- The module doc now states what this pass is: normalization of an HDR
  desktop to SDR, with everything above SDR white clipping, not a tone
  map, and why a roll-off is deliberately not applied. The earlier
  claim that clipping matches what the local user sees was wrong for
  HDR content on an HDR display.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RLb1dNdhFqUQExJPANjo1F

* scrap: only apply the SDR white level to outputs DXGI reports as HDR

Review follow-up:

- An FP16 desktop is not necessarily HDR. Since Windows 11 22H2 an
  Advanced Color (WCG) SDR display is composed in FP16 scRGB too, and
  there 1.0 is the display's reference white, not 80 nits, so the
  SDRWhiteLevel scaling does not apply (Microsoft: "Reference white
  applies only to HDR displays"). Query IDXGIOutput6::GetDesc1 and treat
  the output as HDR only for DXGI_COLOR_SPACE_RGB_FULL_G2084_NONE_P2020,
  the documented Win32 check; a non-HDR FP16 frame now gets just the
  scRGB -> sRGB transfer. Without IDXGIOutput6 (before Windows 10 1803)
  FP16 can only mean HDR.

- The SDR white level is now Option: a failed query or a reported 0 is
  "unknown" on both the initial and the refresh path, an HDR output with
  an unknown level logs a warning and keeps the 80-nit assumption until
  the periodic re-query succeeds. DISPLAYCONFIG_DEVICE_INFO_GET_SDR_WHITE_LEVEL
  needs Windows 10 1709, not 1703 as an earlier message said.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RLb1dNdhFqUQExJPANjo1F

* scrap: re-read the Advanced Color state while capturing, gate FP16 on IDXGIOutput6

Review follow-up:

- The HDR/WCG decision was taken once when the conversion was created.
  HDR can be switched on or off, and a WCG desktop can turn into an HDR
  one, without the duplication being invalidated, so the choice between
  "divide by the SDR white level" and "no scaling" could go stale. The
  once-a-second refresh now re-reads it: it keeps an IDXGIFactory1,
  and when IsCurrent reports FALSE it creates a fresh factory and
  re-finds the output by GDI name, since a stale factory's outputs keep
  stale descriptions (this is the procedure the GetDesc1 docs require).
  On a change it switches modes, re-reads the white level and updates
  the shader constant; an unreadable level keeps the last known one.

- Float frames are only requested when IDXGIOutput6 exists, as
  Microsoft's duplication sample does. That interface is also what tells
  HDR from WCG, so there is no longer a state where FP16 is requested
  without being able to interpret it. IDXGIOutput6 dates from Windows 10
  1703, not 1803 as the previous commit said; 1803 added IDXGIFactory6.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RLb1dNdhFqUQExJPANjo1F

* scrap: replace the DXGI factory and output together when re-reading HDR state

Review follow-up: when the fresh factory did not find the output by name,
the refresh kept the new, current factory next to the old output, and
because IsCurrent then reported TRUE it never enumerated again, so the
stale output could stay forever. enumerate_output6 now returns both or
neither, and the refresh only replaces the pair together; a null factory
forces another enumeration on the next refresh while the old output is
still read in the meantime. The constructor gets the same guarantee for
free, since a failed lookup leaves the factory null there too.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RLb1dNdhFqUQExJPANjo1F

* scrap: keep enumerate_output6's both-or-neither promise when IDXGIOutput6 is missing

Review nit: a matched output whose IDXGIOutput6 query fails returned the
fresh factory next to a null output, which let the constructor pair a
current factory with the capturer's fallback output. Return neither in
that case so the next refresh enumerates again.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RLb1dNdhFqUQExJPANjo1F

* scrap: log DuplicateOutput1 failures before fallback

Signed-off-by: 21pages <sunboeasy@gmail.com>

* scrap: avoid null duplication after HDR fallback failure

Signed-off-by: 21pages <sunboeasy@gmail.com>

* scrap: load the D3D compiler securely from System32

Signed-off-by: 21pages <sunboeasy@gmail.com>

* scrap: release the frame through the state machine when abandoning the tone-map

master's FrameState machine is left at Acquired by the raw ReleaseFrame(),
so the next release_frame() hits DXGI_ERROR_INVALID_CALL on the fresh
duplication and the capture loop falls back to GDI -- the outcome the
fallback exists to avoid.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

---------

Signed-off-by: 21pages <sunboeasy@gmail.com>
Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
Co-authored-by: 21pages <sunboeasy@gmail.com>
2026-09-23 18:40:49 +08:00
Ricardo Simõesgreptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
a8ae0d6d66 Review and complete pt_PT.rs translation (European Portuguese) (#16311)
* Update pt_PT.rs

* Update pt_PT.rs

* Update src/lang/pt_PT.rs fiz misspelling of "Apenas"

Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>

* Fix config_screen: replace trailing slash with period

Per CodeRabbit's suggestion — the slash was rendered directly in the
permission prompt text, not as a line continuation, so it read as a
stray character instead of proper punctuation.

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>

* Fix terminal-clipboard-write-tip: translate full 3-sentence source text

Per Greptile's review — the previous translation for this key only
covered a short summary (matching an equally incomplete ptbr.rs entry),
not the full English source defined in en.rs, which explains the
permission's scope (persists across all connections until disabled in
Settings) and that manual copy/paste is unaffected. Translated from the
actual en.rs source text as required by AGENTS.md's localization
guidelines.

---------

Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
2026-09-23 17:31:06 +08:00
asereze 2e333f64a4 Update sc.rs (#16314)
* Update sc.rs

* Update sc.rs
2026-09-23 17:30:47 +08:00
RustDeskandClaude Opus 5.5 e424b57fca Kx v1 (#16326)
* key exchange version 1 on the rendezvous and peer handshakes

Bump hbb_common for key exchange version 1, one stream key per direction,
and negotiate it on both handshakes.

Rendezvous: `secure_tcp` reads the version the server advertises in
`KeyExchange.version`, answers with the highest both speak, splits the key
when that is at least 1, and arms the check of the server's echo on its first
encrypted message.

Peer: the controlled side advertises `KX_VERSION_LATEST` inside the signed
`IdPk`, the controller answers in `PublicKey.kx_version` and both split the
key when the pick is at least 1. A pick above what was offered is refused as
a bug or tampering. `decode_id_pk_dtls` returns the advertised version along
with the fingerprint.

An absent field on either side is version 0, so any old peer or server keeps
today's stream byte for byte.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019aokqJuhjvB3kijXtAg5Ns

* bump hbb_common: keep the advertisement check armed until an echo arrives

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab

* bump hbb_common: drop box_pk_of until something calls it

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab

* key exchange: say 0 on WebRTC, where no stream key applies

A WebRTC stream is encrypted by DTLS and `set_key_split` collapses to
`set_key` on it, which sets nothing but `peer_verified`. Both sides still
put 1 on the wire, the controlled peer in its signed identity and the
controller in its pick, and agreed on a version neither applied. That held
only because both fell into the same branch: the day one side splits keys
on WebRTC and the other does not, they would agree on 1, derive different
keys, and have no version mismatch to point at.

The controlled peer now advertises 0 on WebRTC and refuses a pick above
what it advertised rather than above the newest it speaks anywhere; the
controller picks 0 there. What is on the wire is what runs.

Also bumps hbb_common for the echo contract: the server tags every
message after the exchange, not the first alone, so dropping one frame at
a known position does not rid an attacker of the downgrade check.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab

* key exchange: verify the server's signed version before trusting it

bump hbb_common d9f519e: KeyExchange.signed_version

A server that signs its version sets bit 255 of the ephemeral key inside
the signed keys[0]. A client that sees that bit, or the field itself,
verifies sign("rdkx-ver" || key || version LE) under the server's signing
key before picking a version and refuses the exchange otherwise, so a
version lowered in the clear is caught at the handshake rather than one
frame pair later by the echo. A legacy server sends canonical keys and no
field and takes the unchanged path; the echo still checks its version.

Tests: version 1 keys match the server both ways; an advertisement
lowered in transit is refused at the first echo; legacy, signed-1 and
signed-3 servers each exchange application data; nine tamperings of the
signed version are refused before the client replies.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019aokqJuhjvB3kijXtAg5Ns

* key exchange: comments say what the fields and functions are

bump hbb_common e3452ac: the same on the shared side.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019aokqJuhjvB3kijXtAg5Ns

* key exchange: drop the advertisement echo

bump hbb_common 5194159: RendezvousMessage.kx_advertised and the check on
decrypted frames are gone. signed_version settles the version inside the
exchange, so the client arms nothing after it; the stub in the tests
stops tagging its frames and the test of a lowered advertisement goes,
the signed-version cases covering that refusal before any reply.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019aokqJuhjvB3kijXtAg5Ns

* key exchange: verify KxParams, the server's signed structure

bump hbb_common e74a188: KeyExchange.signed_params and KxParams.

The client parses the signed bytes as KxParams and compares its fields
to the key it verified and the version it was shown, rather than
matching a fixed byte string, so a field added to KxParams later parses
past an older client. The tamper cases now include a payload signed as
the old byte string.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019aokqJuhjvB3kijXtAg5Ns

* key exchange: require the KxParams signing prefix before parsing

bump hbb_common 26582e1: KX_PARAMS_DOMAIN.

Without it a signed IdPk, which the server signs with the same key,
parsed as a KxParams whose pk was the id and whose version was 0, so an
id registered with the bytes of a marked ephemeral key could stand in
for the params at version 0. Two tamper cases pin this: params signed
without the prefix, and a signed IdPk in their place.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019aokqJuhjvB3kijXtAg5Ns

* key exchange: one call sets the negotiated key

bump hbb_common cbc8772: Stream::set_negotiated_key.

The rendezvous client, the controller and the controlled side each
branched on the picked version to choose between split and single keys.
They now hand the transcript to Stream, which makes that choice once.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019aokqJuhjvB3kijXtAg5Ns

* Update hbb_common: refuse unknown key exchange versions, pin wire vectors

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019aokqJuhjvB3kijXtAg5Ns

* client: prove the peer handshake picks its version and encrypts under it

The rendezvous exchange had tests against a stub server; the peer
handshake had none, so a controller that fell back to version 0 would
still connect, still report secured, and pass every test. These run
Client::secure_connection against a stub controlled peer and check
the pick it sees and the application data both ways: new peers pick 1,
a peer without versions gets 0, and a pick lowered in transit leaves
the two sides unable to read each other.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019aokqJuhjvB3kijXtAg5Ns

* Update hbb_common: pin the subkeys for an advertisement above the pick

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019aokqJuhjvB3kijXtAg5Ns

* Update hbb_common to main, with #614 merged

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019aokqJuhjvB3kijXtAg5Ns

* key exchange: name the picked version, say why the marker bit is safe

Review follow-ups with no change in behaviour: the rendezvous pick is
called picked, as in the peer handshake and KxTranscript; the marker
comment says X25519 ignores the bit and the bytes stay as signed; the
controlled side's refusal names the version it offered.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019aokqJuhjvB3kijXtAg5Ns

---------

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-23 17:30:22 +08:00
21pages b30f781fd6 fix: restrict VRAM stall detection to AMD SDK (#16319) 2026-09-23 14:20:42 +08:00
RustDesk 68a35e65f2 fix(unix): ignore SIGPIPE in native Flutter entry (#16322)
* fix(linux): ignore SIGPIPE in Flutter runner

Initialize SIGPIPE before entering the Rust core so writes to closed IPC peers return EPIPE instead of terminating the server. Add a native-entry regression test for the failure reported in #16297.

* test(linux): remove SIGPIPE runner test

* fix(flutter): initialize SIGPIPE in the Rust native entry

Share SIGPIPE initialization between the Linux and macOS native runners before core startup. Remove the Linux C++ initialization.

* fix: share SIGPIPE initialization with Sciter startup

Initialize SIGPIPE before global_init in core_main, shared by Flutter and Sciter on Linux and macOS.

* fix(flutter): keep SIGPIPE setup in the native FFI entry

Sciter already receives SIGPIPE initialization from the Rust runtime. Scope the missing startup initialization to native Flutter runners on Linux and macOS.
2026-09-23 14:05:15 +08:00
Mariano Abad 7c21b4569c test(drm): bound the excused shapes at their worst angle, not only on average (#16320)
Both of the review follow-ups on rustdesk#16242.

One comment still said alias was 0.11 px worse than master. That was the
number before the directional rule; it is 0.51.

And the exemption for help and alias was bounded only on the average over the
angles master handles. The worst single angle is the larger number and the one
that would be felt - help is 8.00 px under master at 270 and 21.54 here - so
leaving it unbounded let the exemption widen quietly. Both directions are
bounded now, at the measured values: alias 0.51 mean and 8.94 at 90, help 4.73
mean and 13.54 at 270.

Tests only.
2026-09-23 10:39:10 +08:00
Ricardo Simões c6a358afbe Update lang.rs - Splits ambiguous pt into pt-pt and pt-br (#16155)
* Update lang.rs - Splits ambiguous pt into pt-pt and pt-br

Splits the ambiguous "Português" entry into two explicit options: Português (Portugal) [pt-pt] and Português (Brasil) [pt-br]. The pt_PT.rs translation file already existed in the repo (fully translated, key-complete) but was never wired into lang.rs. Kept the old "pt" and "br" locale codes mapped to ptbr::T for backward compatibility with existing user configs.

* Preserve pt-PT/pt-BR region in automatic locale resolution

Preserve pt-PT/pt-BR region in automatic locale resolution

* Fix pt-pt detection: check region suffix instead of redundant "pt" substring

Fix pt-pt detection: check region suffix instead of redundant "pt" substring

* Normalize legacy pt/br saved lang option to pt-br

Normalize legacy pt/br saved lang option to pt-br

* Normalize legacy pt/br lang option on Web client

* Add regression tests for pt-pt/pt-br locale resolution

* Follow CLDR inheritance for Portuguese regional locales (pt-AO, pt-MZ, etc.)
2026-09-22 16:31:23 +08:00
Dmytro 458ffe44c6 Update Ukrainian README (#16309)
* Start Ukrainian README terminology update

Signed-off-by: Dmytro <dmitriy.gaponuk@gmail.com>

* Synchronize Ukrainian README with current documentation

Update content, terminology, build instructions, badges, and project structure to match the current English README.

Signed-off-by: Dmytro <dmitriy.gaponuk@gmail.com>

* Polish Ukrainian README dependency wording

Signed-off-by: Dmytro <dmitriy.gaponuk@gmail.com>

* Clarify Docker build argument placement

Address review feedback by explaining where optional build arguments should be appended to the docker run command.

Signed-off-by: Dmytro <dmitriy.gaponuk@gmail.com>

---------

Signed-off-by: Dmytro <dmitriy.gaponuk@gmail.com>
2026-09-22 16:12:11 +08:00
21pages 2e7255f083 fix: suppress heartbeat HTTP retry and TCP proxy logs (#16273)
* fix: suppress heartbeat HTTP retry and TCP proxy logs

Signed-off-by: 21pages <sunboeasy@gmail.com>

* refactor: move API log interval to common module

---------

Signed-off-by: 21pages <sunboeasy@gmail.com>
2026-09-22 16:04:22 +08:00
fufesouandMariano Abad 12f61b1fda Fix/drm rotated cursor (#16242)
* fix(drm): turn the cursor by the output's real angle, and guess its hotspot upright

Two things were wrong with a rotated output's cursor, and the maintainer's
physical test found both.

The bare-metal hotspot is a guess - the top-left of the sprite's opaque box,
since HOTSPOT_X/Y only exist on para-virtualised drivers - and it was guessed on
the sprite as scanned out, then mapped as if it were a point on it. A turned
arrow's tip is never in that corner: at 90 the guess is off by the arrow's width
along x, small enough to pass as fine, and at 270 by its height along y, which
is what was noticed. Measured on an i915 box with a 64x64 Adwaita arrow, hotspot
against tip: +11,0 at 90 and 0,+18 at 270 before, 0,0 at every angle after. A
guessed hotspot is now guessed on the upright sprite, in the consumer, and the
wire says whether the driver measured it so a real one still maps as a point.

And 180 was clamped to 0 for the whole session because a hardware-rotated
primary plane scans out upright. That holds for the frame and not for the
cursor: the compositor pre-rotates the sprite in software either way, so it
arrived upside down. The frame keeps the clamp; the cursor gets the real angle.

(cherry picked from commit 6a73100b4783fbf9c8f43e0dc7651b7568db9ea9)

* test(drm): drive the cursor path, and drop the field nothing reads

The two tests called the helpers, so nothing pinned the production
decision: restore master's `t == 90 || t == 270` in deliver_drm_cursor
and both still pass while the 180 sprite goes back to upside down. The
new test drives deliver_drm_cursor and reads back what it published,
and it fails under exactly that mutation.

The other way to reintroduce the bug was to point the receive thread at
`Shared::transform` again. That field had no readers left once both
gates moved to `cursor_transform` - it was stored and never loaded - so
it is gone, and the doc above TRANSFORM_PENDING now names the field
that actually holds a racing cursor back.

Also four comments that said more than the code does: the sprite is
treated as pre-rotated at every angle because wl_output cannot say
otherwise, not because the compositor provably always does it; the old
flow was off at every angle, not just at one of 90/270; the 180
symptom had its own cause, the clamp, rather than all of it coming out
of the hotspot guess; and the test arrow's opaque box is its left three
columns, not the whole bitmap.

* docs(drm): say what the 180 measurement actually showed

The loop asserts the old mapping was wrong at 180 too, and that is true
of the mapping, but master never ran it there: the clamp sent 180 down
the untouched branch, so guess and sprite turned together and the
hotspot landed on the tip. The bench measured exactly that - (0,0) at
180, with only the sprite upside down. The comment said the old flow was
wrong at every angle without that distinction, which is the kind of gap
between a claim and a measurement worth closing before someone else
finds it.

* fix(drm): centre the guessed hotspot of an I-beam lying either way

The bounding-box guess only centred TALL shapes, so a HORIZONTAL I-beam was
handed the top-left corner of its box. Adwaita's `vertical-text` is exactly that
shape: at 24 px its opaque box is 20x9 and the theme's own hotspot is (12, 11),
its centre. The corner guess lands 11.2 px away; the centre lands 1.4 px away.

It matters more since this branch turns the sprite upright before guessing. Such
a cursor used to reach a quarter-turned output as a TALL bitmap, where the
tall-only rule centred it by accident; guessing on the upright bitmap - correct in
itself, and what fixes arrows at every angle - is what exposed the asymmetry.

Found by fufesou at pixel level on rustdesk#16242, and reproduced here against the
installed theme before changing anything: same declared hotspot, same bounding
box, same two errors. Then checked across ALL 35 shapes of that theme at 24 px:
making the aspect test symmetric moves exactly one of them, `vertical-text`, from
11.2 px to 1.4 px, and leaves the other 34 byte-identical.

The old flow is not the fix. It was right for this one shape and wrong for arrows
at every angle, which is what `a_guessed_hotspot_is_guessed_on_the_upright_sprite`
pins; the fix belongs in the guess, not in the order of operations.

The regression test that missed this used only `arrow()`, as fufesou pointed out.
Three things the first version of the replacement got wrong, all of them in what
it CLAIMED rather than in the fix:

- Its expected point was the centre of the BITMAP, which equals the centre of the
  opaque box only because the fixtures filled their bitmaps symmetrically. Both
  I-beam fixtures are now off-centre in their buffers, the way a sprite sits in a
  64x64 hardware cursor, and the test asserts up front that the two centres differ
  so the fixture cannot quietly stop discriminating.
- It called the arrow's box "elongated by less than the factor of two", when 3x6
  IS the factor of two and the arrow keeps its tip only because the comparison is
  strict. That makes the arrow the control for one side of the threshold, and it
  is now described as such.
- It said the case was driven "through the whole delivery path" while chaining the
  helpers itself. It now calls `deliver_drm_cursor` and reads the published
  hotspot back out of DRM_CURSOR, at 0, 90, 180 and 270, feeding it what the
  producer really sends for a guessed hotspot: the producer's own guess, made on
  the sprite as scanned out.

And the threshold was pinned from one side only. A third fixture carries the real
2.22:1 aspect of the shape that was wrong, so a stricter rule cannot pass on 6:1
bars while silently un-centring the actual cursor.

Mutations, each restored byte-for-byte afterwards: back to tall-only, the bitmap
centre instead of the box centre, the threshold loosened to one and tightened to
three. All four fail the test.

* build(drm): point the pin at the synced mirror and drop the helper fallback

The mirror is synced, so the pin moves from 5da68a3a (libdrmtap 0.5.4) to
49b204f (0.5.6), which is what rustdesk-org/libdrmtap now carries.

-Dhelper=disabled, as the maintainer asked on #16242. rustdesk never uses the
privileged helper: every drmtap_open lives in src/ipc/drm.rs, i.e. the root
service, which already holds CAP_SYS_ADMIN, and the unprivileged side opens a
render node instead. What the library carries without the option is a fallback
that walks six hardcoded paths, two of them under /usr/local, and execs the
first one that passes access(X_OK) -- no check of its owner, no check of its
mode -- from inside the ROOT process. The option compiles that path out.

Asserted on the artifact as well as passed as a flag, for the same reason the
EGL check is: a flag cannot notice a stale build-pkg or an object substituted
by hand, and meson accepts an unknown -D silently on versions predating the
option. Measured on the produced .so: socketpair 4 -> 0, the helper search
paths 3 -> 0, and nm -D shows no fork, execl or socketpair import. The check
fails as it should when pointed at a .so built with the helper.

* fix(drm): use the library's hotspot provenance, and keep legacy IPC meaning

Answers the two blockers in the maintainer's review of 9acb37a9d, plus the
three he marked should-fix.

hot_measured no longer guesses. The pinned libdrmtap 0.5.6 exports
drmtap_cursor_hotspot_valid, and the old test -- hot_x != 0 || hot_y != 0 --
cannot separate the two things a (0, 0) hotspot means: no HOTSPOT_X/Y on the
plane, or a driver whose answer really is the corner. The symbol is resolved
OPTIONALLY, the way drmtap_render_node and drmtap_list_devices already are,
with the same version-aware warning when a library that reports 0.5.6 or newer
does not carry it. An older deployed .so keeps the previous behaviour instead
of the ABI floor moving under it and refusing to load.

The IPC default is corrected. Data is JSON over a unix socket between two
processes upgraded separately, so an old root service can be streaming to a
freshly started --server and its DrmCursor has no hot_measured at all. Read as
bool::default() the new consumer discards a hotspot the producer measured and
re-infers one from the upright bitmap, moving the cursor on a rotated display
for the length of the upgrade. The default is now true, which is not a claim
that the value was measured: it means "no provenance available, so behave as
the old protocol did". A new producer that wants re-inference sends false
explicitly, which serializes, so new-to-new is unchanged.

hot_measured is folded into the cursor id. It is not metadata about the cursor,
it selects what the consumer does with it, so a sample whose pixels and (0, 0)
hotspot are unchanged but whose provenance flipped is a different cursor and
must not be deduped away by the producer.

build.py reconfigures an existing meson build dir with -Dhelper=disabled
instead of only configuring a fresh one; a directory from before the option
kept its old configuration and the artifact assertion then failed the build.

And the drm CI job now runs the drm-gated tests. It built the feature without
ever executing them, so every cursor rotation and hotspot test had no
continuous coverage. A cargo test filter that matches nothing exits 0, so the
step also asserts it actually ran some.

Verified by mutation, each caught by its own test and no other: ignoring the
library's answer fails the two provenance tests; the serde default back to
false fails the legacy-deserialization test; dropping hot_measured from the id
fails the identity test.

* feat(drm): say once where the cursor hotspot came from

The provenance decision was unverifiable anywhere but a unit test: nothing on
a running box distinguishes the three states, so a deploy proved nothing. One
info line does, and with it all three are measured -- Some(false) on i915,
None with a 0.5.4 library swapped in behind the soname, and Some(true) via a
C probe on virtio-gpu, where no rustdesk build runs.

Once per state, not once per sample. A cursor is read on every capture
iteration and its provenance changes approximately never; a per-frame log line
here is the same defect libdrmtap already shipped once. Measured on Sigma-26:
one line across a whole session. The should-we-log decision is its own
function so it cannot quietly become per-sample again.

* test(drm): drive a legacy cursor message from the wire, not from a literal

The upgrade window is the one thing in this round that could not be staged
with two live processes: a --server from one build does not run inside the
other's tree, so the old service respawns it and it dies with exit 127. Tried
on two boxes, with two files swapped and with the whole tree.

This is the honest form of that test and it runs in CI rather than once on a
desk. It takes the exact bytes an old producer puts on the socket -- no
hot_measured key at all, adjacently tagged as Data really is -- deserializes
them the way the receive loop does, drives the real delivery path, and reads
back what was published. The transform is non-zero on purpose: at 0 the path
never consults hot_measured, so a test there could not tell the branches
apart, and the fixture is asserted to make mapping and re-inferring disagree
before anything is concluded from them.

Verified by mutation: restoring #[serde(default)] -- the reported bug -- fails
it, and so does a delivery path that ignores hot_measured.

* fix(drm): run the tests that matter in ci, and keep provenance state per stream

Answers the review of 7dc6817 plus the CI failure fufesou reported on 401c2f7.

The drm test step was broken three ways and none of them showed up as a red
test: it reused the production $FEATURES, so the test binary failed to LINK
(undefined reference to fcntl64 from hwcodec) and the tests never ran; it
summed the counts with bc, which the ubuntu18.04 container does not install;
and `cargo test --lib` at the repo root builds the ROOT package only, so the
provenance tests in libs/scrap were never selected -- the "at least one test
ran" guard passed on the root filters and hid it. Now: --features drm rather
than the production set, awk instead of bc, and an explicit `-p scrap` run
with the same assertion. Locally 36, 9 and 5 tests, and a bogus filter still
fails the step.

Provenance logging state was process-global on both sides. DRM runs one
reader per captured display, and two outputs with different but STABLE
provenance -- one publishing HOTSPOT_X/Y and one not, which is an ordinary
multi-GPU host -- would overwrite each other and make every message look like
a change, i.e. exactly the per-frame logging the one-shot was written to
avoid. The producer's state moves into DrmReader, the consumer's is keyed by
display. The hidden-cursor sentinel is no longer recorded: it carries
hot_measured=false because it has no hotspot, so counting it turned every
hide and show into a provenance transition.

The 180 test is renamed to say what it pins -- i915 advertising rotate-180
with mutter -- and its comment says plainly that it is not a general contract,
that Plasma is still wrong there, and that changing it means re-measuring.

Verified by mutation: restoring the global slot fails the new per-display
test, and so does recording the hidden sentinel.

* fix(drm): centre the guessed hotspot on the axes a cursor mirrors about

The guess put the click point at the top-left corner of the opaque box unless
the box was more than twice as long as it is wide. That corner is where an
arrow's tip is, because cursors are drawn pointing up and to the left, but a
shape that mirrors onto itself has no tip to point with: a crosshair, a
two-headed resize arrow, a cell marker. Those got a corner where the theme puts
the middle, and the error is about half the glyph.

So: centre the axis the shape is symmetric about, and keep the corner
everywhere else. Measured against the hotspots the theme declares, which is the
value a compositor programs into HOTSPOT_X/Y where the property exists:

  adwaita-icon-theme 50, 35 shapes at six nominal sizes, 210 cases
    mean error 0.43 -> 0.27 of the cursor size, 17 shapes improve, none worse
  adwaita-icon-theme 46, 34 shapes at five sizes, 170 more cases
    better at every size, none worse

The threshold is not fitted: from 90 to 98 percent agreement nothing regresses,
and below 90 three shapes do.

The corpus is carried as fixtures so the expected value comes from the theme
author rather than from our own heuristic, and two tests read it: the published
hotspot must not move when the output turns, with the old flow's 15 px average
movement as the control, and the guess must stay inside the measured bounds
with the old rule frozen as the baseline.

The elongation test stays ahead of the mirror test so an elongated shape that
is not symmetric still keeps its centre.

* fix(drm): put a directional cursor's hotspot on the edge it resizes

The mirror rule centred the axes a shape is symmetric about and left the
other axis on the top-left corner. That is right for an arrow, whose tip is
that corner, and wrong for the resize cursors: those are a pointer plus the
marker of the edge being resized, the theme puts the click point on the
marker, and the marker is at whichever end the cursor names. Always taking
the corner therefore had to be wrong for one of every mirrored pair, since
e-resize and w-resize are the same picture reflected.

So an axis is read as directional when the perpendicular axis mirrors, which
is the n/e/s/w family, or when the shape mirrors about a diagonal, which is
the corner family. A directional axis takes the heavier end.

A diagonal reflection only lines up inside a square, and these boxes are not
square, so where the box sits in that square decides the answer: ne-resize
scores 0.62 anchored one way and 0.98 the other, and nw-resize is the reverse.
Both anchorings are tried and the better answer wins.

Measured against MASTER now, not against this PR's previous revision, which
is what the maintainer asked for. Over the angles master handles (0, 90, 270),
adwaita-icon-theme 50 at 24 px:

  mean error per shape   12.08 px -> 4.20
  (shape, angle) cases   83 better, 18 the same, 4 worse of 105
  shapes worse than master   help (+4.73) and alias (+0.51)

Both of those are semantic: the theme puts help's click point on the dot of
its question mark. The same holds at 48 px and on adwaita-icon-theme 46,
where ne-resize is also 1.34 px worse because its glyph is drawn differently
there.

The test baseline was wrong and is fixed here: it froze this PR's earlier
symmetric aspect test rather than master's tall-only one, so it could only
show that the new rule does not regress the old rule. It now freezes master's
guess AND master's delivery, and names the two shapes it excuses with the
measured size of each.

The mirror threshold moves from 95 to 88, the middle of the 86 to 91 interval
that regresses nothing on either theme version.

---------

Co-authored-by: Mariano Abad <weimaraner@gmail.com>
2026-09-22 15:18:10 +08:00
rustdesk 6a0eb9a1fd fix(terminal): preserve trackpad scrolling in alternate screen
Prevent the inner terminal scrollable from accepting user scrolling in the alternate buffer, so xterm's existing outer handler receives trackpad gestures after main-screen history.

Keep wheel encoding and drag reporting unchanged. Cover trackpad forwarding, subsequent drag coordinates, arrow fallback, and return to local scrollback.
2026-09-22 11:45:05 +08:00
rustdeskandClaude Fable 5.1 763d4eeb05 bump hbb_common: tungstenite 0.29 forks, read buffer grown as bytes arrive
hbb_common 7dc56d6..d9895ff, one commit: tokio-tungstenite and tungstenite
up from 0.26 to rustdesk-org's rustdesk-patches-0.29 branches. The
tungstenite fork grows the read buffer a read_buffer_size chunk at a time
as bytes arrive, where upstream reserved the whole length a frame header
declared. It is pinned here at the workspace root, the one place cargo
reads [patch], so hbb_common's copy and tokio-tungstenite's resolve to
the same one. The lockfile moves only those two crates and drops utf-8,
which 0.29 no longer pulls.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab
2026-09-21 17:58:35 +08:00
fufesou a5d4ef97e8 fix(ws): reject text frames after encryption is enabled (#16295)
Signed-off-by: fufesou <linlong1266@gmail.com>
2026-09-20 18:21:15 +08:00
RustDeskandClaude Fable 5.1 dd9b21cf86 server: hold an unauthenticated connection to a small message (#16254)
* server: hold an unauthenticated connection to a small message

Until a peer authorizes it sends only a public key, a login request, a test delay
and a close reason, none of them large. Nothing said so: a frame header could
declare up to whatever the transport allowed, 1 GiB on TCP and WebRTC, and a
connection holds its place for up to LOGIN_GRACE before it has to authorize. With
MAX_UNAUTHORIZED_CONNS places to fill, that is 64 GiB of header-declared payload
one peer could make us hold - or, on WebSocket, 1 GiB bought outright with a few
hundred bytes of frame headers, because tungstenite reserves a frame's declared
payload as soon as it passes max_frame_size.

The cap goes on in create_tcp_connection, before the identity handshake, so that
read is bounded too, and comes off once the login is settled. It comes off before
connect_port_forward_if_needed rather than beside the rest of authorization: a
multiplexed tunnel narrows the same knob again for its own framing and has to have
the last word.

128 KiB is several times the largest login request anyone sends - a long hostname,
an os_login, an avatar URL, a file-transfer path - and is also the read buffer
tungstenite allocates per WebSocket connection whatever we do, so on that transport
the bound costs nothing beyond a floor already paid. A server hands that avatar
out as a URL; only a custom client that inlines an image into the avatar option
instead can reach the bound at all. Together with
MAX_UNAUTHORIZED_CONNS it holds every unauthorized connection to 8 MiB. Redis
answered this same shape in CVE-2021-32675 with 16 KiB, tighter because a
per-message bound is the only one it has; here the connection count is the other.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab

* server: test that the unauthenticated cap is on before the handshake reads

hbb_common covers each transport's cap; nothing covered where the connection
layer puts it. A header one byte over MAX_UNAUTHORIZED_MESSAGE, written to a
connection stalled in the identity handshake, has to end the handshake on the
header alone and release the connection's place: the test fails with the cap
moved past the handshake or dropped.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab

* client: hold the clipboard until this round's login is accepted

The clipboard listener is one per process, started by the first session to
log in, and its broadcast went to every session - one whose login was still
waiting on a password, 2FA or the peer's consent included. What the user
copied meanwhile went to a machine that had not admitted them; the peer
drops it unread before authorization, but it is in that peer's hands.

The check goes on the round, not the session: a session-level one reads a
state and later a sender that a reconnect can have swapped in between, so a
broadcast that passed for the round before could still queue on the next.
Remote is the round - its queue, and is_connected set once its own PeerInfo
is in - so a Clipboard or MultiClipboards that reaches handle_msg_from_ui
before then is dropped there, on the line before it would go out. What the
login itself sends through the same queue, Auth2FA among it, goes as before.

The unauthenticated cap on the other side is how this came up: a clipboard
over 128 KiB ended such a login with "Reset by the peer". The small case had
always gone through quietly.

A test drives a round's Remote over a loopback pair before any login: a
clipboard does not reach the far end, a 2FA code does, and once the round is
connected the clipboard does too.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab

---------

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-09-20 14:26:42 +08:00
Alex Rijckaert 97811acbdd Update Dutch translation (#16284) 2026-09-19 16:05:18 +08:00
RustDeskandClaude Fable 5.1 7a367f7cc6 bump webrtc fork: one IPv6 host candidate per interface and prefix (#16263)
* bump webrtc fork: one IPv6 host candidate per interface and prefix

ICE gathered every IPv6 address on every interface. Beside the temporary
address that privacy extensions rotate, a prefix usually carries a stable
one, often derived from the MAC, that the OS never picks as a source: a host
candidate for it hands the peer an identifier that outlives every rotation
and that nothing else this machine sends out ever shows.

RFC 8445 §5.1.1.1 has the trackable addresses of an interface and prefix
left out once a privacy one is gathered. There is no portable way to tell
the two apart, so the fork's `local_interfaces` stands in for that rule
with a best-effort approximation: of an interface's addresses in one
prefix, it asks the OS which one it sends from - a UDP `connect` inside the
group's own prefix, nothing sent, nothing outside this machine's own
prefixes involved - and if the answer is one of them, keeps that one alone.
If the answer is none of them, the whole group is kept, as it was: the
probe is bound to no interface, so where Ethernet and Wi-Fi share a LAN the
route picks one of them and the answer for the other is an address it does
not hold, and the enumeration order would be no better a guess - on macOS
its first address is the stable one. Every other interface and prefix keeps
its address, a VPN's unique-local one among them. Two static addresses in
one prefix keep one, the recorded price of the stand-in; the interface a
shared prefix's route bypasses keeps both of its addresses, a gap the
stand-in leaves open rather than a regression.

The Windows enumeration, which named every adapter "" with no mask, now
carries the adapter's name and on-link prefix, without which Ethernet and
Wi-Fi on one LAN would have been a single group. That reaches IPv4 too:
its addresses carry the adapter's name and mask where they were "" at /32,
so the candidates gathered are the same but `interface_filter` sees the
real names. hbb_common is untouched: its fe80::/10 filter still applies to
what the fork keeps.

Two more fork commits ride along, found by the same review. SCTP never
reported a DATA chunk received again: `handle_data` asks `can_push` before
`push`, and `push` was where a duplicate was noted, so the no-cwnd sender's
reordering window, which widens on reported duplicates, never heard of one
from another of these endpoints; and the SACK, its gap blocks and now its
duplicates unbounded, could outgrow the MTU the DATA chunks keep to under a
thousand chunks in flight with holes among them. Duplicates are now listed
and SACKed at once (RFC 9260 §6.2), and the SACK reports the lowest gap
blocks that fit (§6.7). And the Windows adapter struct, split into nested
parts, read `Ipv6IfIndex` eight bytes late on x64 - only into a scope id
that `Interface::convert` drops, so nothing gathered wrongly, but the field
an interface-bound probe would need; it is flat now, with a compile-time
check written for Rust 1.75, the version this crate builds with -
`offset_of!` would have wanted 1.77.

rustdesk-org/webrtc 80d5a20..49c89bd8, six commits: the heuristic, the
fail-open it grew in review, its comments brought in line with that, the
SCTP duplicates and SACK bound, the flat Windows adapter struct, and its
check made to build on 1.75.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019aokqJuhjvB3kijXtAg5Ns

* pin hbb_common to main 7a5ad52

0eb1759..7a5ad52, six commits: the message cap's tests on WebSocket and
WebRTC with the fragmented WebSocket message bounded too (e999dce,
f0f1548); hyper_util's debug logs out of the default filters (#608); and
`new_direct_udp_for_unverified`, the controller's UDP socket on the
resolver's preferred address for the rendezvous server, with a second for
the lookup and without the TCP connection `test_target` opens and drops to
prove it - while `new_direct_udp_for`, `new_udp_for` and `rebind_udp_for`,
which the controlled side's punch reply and its registration live on, keep
that proof (f688d41, 0bc8336, 7a5ad52).

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019aokqJuhjvB3kijXtAg5Ns

* ipv6 punch: ask the kernel for the route without resolving a name first

`test_ipv6` is awaited on the connection path by both sides of a punch, and
before it looked for a public IPv6 address in the background it resolved
the STUN hosts' names inline - racing the four, so that one resolver that
hangs would not decide. It could still: `select_ok` returns the first
success or the last failure, so with no resolver answering the probe waits
for the slowest lookup to give up, as long as the system resolver takes,
once a minute, on the first connection of that minute.

The name was never needed. `connect` on a UDP socket sends nothing; it has
the kernel pick a route and a source address for the destination, and any
global address serves, so the probe now names one - the one libwebrtc's
QueryDefaultLocalAddress asks for - and touches no network at all: a bind,
a connect, a local_addr. A machine without an IPv6 route learns so from the
connect's error, at once, as before.

Two smaller things beside it. The minute's gate read the timestamp under
one lock and set it under another, so two connections arriving together
both found it over and both probed; it is one critical section now. And the
background STUN probe, bounded so far by the STUN client's own ten seconds
and the resolver's, has a deadline of its own, five seconds: a probe that
outlived the minute could write an earlier network's address over a later
probe's.

Test: the route probe completes within a second, an address found or not.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019aokqJuhjvB3kijXtAg5Ns

* controller: the NAT test takes the resolver's address for the server

`new_direct_udp_for` learned which address to send the UDP NAT test to by
opening a TCP connection to the rendezvous server and dropping it - a
handshake, one round trip, on every connection the controller starts,
right before `_start_inner` opens the connection it keeps to the same
host. The NAT test now takes the resolver's preferred address,
`new_direct_udp_for_unverified`, which spends no round trip proving it and
gives its lookup a second: an address the server does not answer on costs
this connection its UDP punch, which the TCP punch and the relay cover, as
they do whenever the test finds no port. The controlled side's punch reply
keeps `new_direct_udp_for` and its proof - a reply sent to such an address
is a device online and unreachable.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019aokqJuhjvB3kijXtAg5Ns

---------

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-19 11:20:23 +08:00
RustDeskandClaude Opus 5 ea04f04f9d add hide-elevate-button-in-accept-window (#16271)
A portable client handed to standard users offers them "Accept and Elevate",
which they have no credentials to complete. The builtin option takes that
button out of the accept window and leaves elevation to the controlling
side's "Request Elevation" during the session.

https://github.com/rustdesk/rustdesk-server-pro/discussions/1016


Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-09-18 16:54:11 +08:00
Dmytro ef00ed78a7 Update missing Ukrainian UI translations (#16272)
* Update Ukrainian translations

Signed-off-by: Dmytro <dmitriy.gaponuk@gmail.com>

* Complete Ukrainian voice call translation

Signed-off-by: Dmytro <dmitriy.gaponuk@gmail.com>

---------

Signed-off-by: Dmytro <dmitriy.gaponuk@gmail.com>
2026-09-18 16:27:34 +08:00
5278fcab68 fix(cursor): correct native cursor sizing and validate received images (#16213)
* fix(flutter): shrink the unzoomed remote cursor by DPR on macOS and Linux

With "Zoom cursor" off in Adaptive or Custom view, the remote cursor
bitmap was registered at scale 1.0. NSCursor and GdkCursor treat the
bitmap size as logical pixels, so on a HiDPI controller the cursor was
drawn DPR times larger than in Original view (which already passes
1/DPR) and than on Windows (whose cursor path is in physical pixels).
A HiDPI remote such as KDE Wayland sends a 48-64 px bitmap, which then
showed up 3-4x too big on a Retina Mac.

Scale the bitmap by 1/DPR in that case, and scale the Flutter-painted
cursor used while the peer moves the mouse the same way so its size
does not jump. The new branch is an identity at DPR 1 and the Windows
paths are untouched.

Fixes https://github.com/rustdesk/rustdesk/discussions/15363

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01K8HSHTEHo27mDcJXVyVfSP

* fix(flutter): check the cursor height against the min cursor size

`_checkUpdateScale` computed the scaled height from `width`, so the
min-size clamp never looked at the height.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01K8HSHTEHo27mDcJXVyVfSP

* fix(flutter): keep the painted cursor hotspot in place when zoom cursor is off

`CursorPaint` subtracted the hotspot in remote pixels and then scaled it
by the canvas scale, but drew the image at scale 1.0, so the hotspot
landed hotx * (1 - scale) logical pixels away from the remote cursor
position. Cursors with a centered hotspot (I-beam, crosshair) were off
by up to half their size in Adaptive view. Subtract the hotspot after
scaling the position instead.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01K8HSHTEHo27mDcJXVyVfSP

* fix(flutter): read the live DPR and clamp the painted cursor like the native one

CanvasModel caches devicePixelRatio and only refreshes it when the view
style changes, so after the window moves to a monitor with a different
DPR the unzoomed cursor kept the previous monitor's scale. Read it from
MediaQuery instead, which also rebuilds the cursor when it changes.

The native path clamps the scaled bitmap to kMinCursorSize; apply the
same clamp to the painted cursor so a small cursor does not change size
when the peer moves the mouse.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01K8HSHTEHo27mDcJXVyVfSP

* build(cursor): declare existing Zstd dependency for bounded decoding

* fix(cursor): validate and bound received cursor images

* fix(cursor): preserve thin cursor sizes when scaling

* fix(cursor): limit view changes to native cursor sizing

* fix(cursor): apply long-edge minimum to Web cursor sizing

* fix: preserve Linux cursor alpha and match Windows Custom scale

* fix(cursor): keep scaled buffers and raster dimensions in sync

* fix(cursor): preserve Windows peer alpha when resizing

* fix(cursor): preserve mixed alpha during downsampling

* comments

Signed-off-by: fufesou <linlong1266@gmail.com>

* fix(cursor): match desktop cursor size to peer display density

* refactor(cursor): clarify desktop and web scale branches

* fix(cursor): correct adaptive display scaling and fixed cursor size

* fix(cursor): apply all-display adaptive density on every desktop

* fix(cursor): normalize unzoomed all-display cursor density

* fix(cursor): synchronize original view on DPR changes

* fix(cursor): match original zoom to the active renderer

* fix: align Wayland software scrolling with input coordinates

* fix: preserve scroll offsets when switching scrolling modes

* fix: correct cursor size and pointer mapping with custom scale

Apply the hovered Linux display density to Custom cursor zoom in All Displays. Refresh scroll fractions after layout so changing the Custom percentage uses current scrollbar extents and detached controllers.

Validated with macOS and Windows component tests, formatting, and static analysis.

* fix(linux): pad tall native cursors to prevent clipping

* fix(cursor): preserve macOS point size in unzoomed views

* fix(linux): pad rectangular cursors to square canvases

* fix(cursor): divide dpr on Linux -> macOS

Signed-off-by: fufesou <linlong1266@gmail.com>

* fix: cursor size test

Signed-off-by: fufesou <linlong1266@gmail.com>

* fix(cursor): cursor size of controlled side macOS

Signed-off-by: fufesou <linlong1266@gmail.com>

* fix(cursor): limit received cursor allocations

* test(cursor): retain reverse raster transition coverage

* fix(cursor): bound compressed cursor input

* fix(cursor): restrict the scaled size of the cursor

Signed-off-by: fufesou <linlong1266@gmail.com>

* fix(cursor): align hotspots with resized raster dimensions

Calculate each hotspot axis from the actual raster-to-source ratio.
Update existing boundary tests and run cursor tests in Flutter CI.

Signed-off-by: fufesou <linlong1266@gmail.com>

* fix(cursor): align Sciter hotspots with raster dimensions

Calculate native and overlay hotspots from the final raster size.
Preserve input coordinate scaling and cursor refresh order.

Signed-off-by: fufesou <linlong1266@gmail.com>

* fix(cursor): use `1.0` instead of `1.0/dpr` on Linux -> macOS, Zoom off, Scale adaptive

The mouse cursor currently appears somewhat large.
However, this is difficult to adjust because the cursor size
is fixed while the window size varies; its relative size
depends on the specific desktop environment.

We can modify it if users actually provide feedback.
Ideally, we should check the "Zoom cursor" option.

Further adjustments may also be needed later based on cursor density.

Signed-off-by: fufesou <linlong1266@gmail.com>

---------

Signed-off-by: fufesou <linlong1266@gmail.com>
Co-authored-by: rustdesk <info@rustdesk.com>
Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-18 12:43:07 +08:00
memory_clear 53ec874c39 Translate terminal clipboard tips to Chinese (#16266) 2026-09-18 11:45:10 +08:00
Maison da Silva 04974591b8 Refine Portuguese translations for user options (#16264)
Updated Portuguese translations for clarity and conciseness.
2026-09-18 11:05:52 +08:00
Abdullah Hüseyin Efe 4da167517e Turkish: translate the three empty entries (#16261)
terminal-clipboard-write-tip, "Allow terminal apps to copy to clipboard" and the
voice-call hint were empty, so Turkish users saw the English text.
2026-09-18 09:59:45 +08:00
RustDeskandClaude Fable 5.1 d4ac2c07b7 temporary password: rotate when a peer is let in, not when it leaves (#16080)
The one-time password was regenerated after the connection loop exited,
so a remote desktop session kept it valid for hours and a port-forward
tunnel for as long as its mapping lived. It now rotates the moment a
connection becomes authorized. Reconnects and windows opened from a
live session are unaffected: they log in on the password the session
remembers, for 30 seconds past its last activity.


Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-18 09:15:44 +08:00
RustDeskandClaude Fable 5.1 0b3a1ddd80 rendezvous: cap unauthenticated punches in flight (#16256)
A PunchHole needs no authentication: anyone who knows this id can ask hbbs
to have us open a punch, and each one hbbs sends is spawned without a limit.
Every punch pays per request. punch_udp_hole binds a socket of its own and
start_ipv6 another; the TCP punch opens a listener on the ephemeral port of
its own connection to hbbs, with a punch of its own in flight beside it -
`reuse` sets the socket flags, it shares no fd - and the LAN listen a
FetchLocalAddr opens is that listener again. All of them then wait up to
CONNECT_TIMEOUT for the peer, so a stream of requests holds as many sockets
as it likes for as long as it keeps sending.

Each takes a place in one of two pools of 32 - UDP over v4 and v6 in one,
the TCP punch and the LAN listen in the other - and gives it back the
moment the peer's session is up - the KCP accept, the TCP stream in hand -
or when the wait ends without one: a place stands for a socket waiting for
its peer and nothing past it, and from the session on the connection layer's
own limits apply, the same handoff the WebRTC answerer's slot makes at its
open data channel. At the limit an arrival is declined rather than an older
punch cut short, since the places turn over on their own, within
CONNECT_TIMEOUT and the few seconds the punch phases add to it, and cutting
one short would drop a socket that may be a moment from carrying a session. Two pools rather than one, so that neither
transport pays for the other's crowd: a connection costs a place in each,
the controller's preferred request punching UDP and its TCP fallback
request punching TCP, and the transports that lose the race hold theirs for
the whole wait, so one pool of 32 would be about ten connections setting up
at once and a crowd of UDP punches would decline a TCP punch that had
nothing to do with it. A place is taken only for a punch that will
be made: whether the v4 legs relay is decided first, since the relay branch
runs the whole session and a place held across it would let ordinary relay
traffic use the pool up. A declined LAN listen falls to the relay, as one
that fails for any other reason does.

Declined is the listen alone, never the reply. One PunchHoleSent carries the
WebRTC answer, the v6 address and the relay server along with the v4 punch,
and the controller sends one request for all of them and retries it three
times before it fails outright, so a reply withheld for want of a v4 place
would lose the transports that needed none. The reply goes out as before, on
a socket that then goes at once, resends and all - a declined request is not
worth a socket kept for its reply's sake, and the controller re-asks on its
own - and what the controller loses is its v4 attempt at a mapping that no
longer answers; its others go on.

A request that carries a v6 address costs two places, and the v4 one is
taken first: the v6 punch starts before the v4 one does, and taken in that
order the last place would go to the transport the peer may have no route
for and leave the one it can count on with none. A declined v6 punch leaves
the v4 path to carry the connection, as it already does wherever this
machine has no public IPv6 address. Each kind logs at most one line a
minute, carrying the number of requests it stands for, since the peer
decides how often it asks.

Tests: the places are the bound and come back on drop; a full UDP pool
leaves the TCP places alone; at the last place it
is the v6 punch that goes without; a declined UDP punch still sends its
PunchHoleSent, answer and v6 address intact, to a loopback stand-in for
hbbs; a listen whose peer never probes gives its place back.


Claude-Session: https://claude.ai/code/session_019aokqJuhjvB3kijXtAg5Ns

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-17 18:21:27 +08:00
fufesou 01e3917390 fix(ci): restore global configurations (#16257)
Signed-off-by: fufesou <linlong1266@gmail.com>
2026-09-17 16:59:00 +08:00
55 changed files with 5417 additions and 405 deletions
+43
View File
@@ -871,6 +871,11 @@ jobs:
name: bridge-artifact
path: ./
- name: Test cursor sizing
if: ${{ !inputs.upload-artifact && matrix.job.arch == 'aarch64' }}
working-directory: flutter
run: flutter test --timeout 60s test/cursor_size_test.dart
- name: Setup vcpkg with Github Actions binary cache
uses: lukka/run-vcpkg@b1a0dd252f06b9e25b3c022a9a03bd7a427fb6a2 # v11
with:
@@ -2041,6 +2046,44 @@ jobs:
*) echo "::error::build.py returned no '$want' feature: $FEATURES"; exit 1 ;;
esac
done
# Run the drm-gated unit tests HERE, because nowhere else does. The ordinary linux CI
# runs the suite, but `drm` is opt-in, so every test behind that feature -- the cursor
# rotation and hotspot ones especially -- has no continuous coverage at all otherwise.
# Debug rather than --release: these are pure logic tests and the release build is
# already the slow part of this job.
# A MINIMAL feature set, not the production $FEATURES: these are pure logic tests of
# the drm paths, and pulling hwcodec in makes the test binary fail to link at all
# (undefined reference to fcntl64 in this container), so the tests never run.
#
# Two packages, because `cargo test --lib` at the root builds the ROOT package only:
# the provenance tests live in libs/scrap and would never be selected from here. The
# ordinary linux CI runs --workspace but without the drm feature, so these are not
# covered there either.
#
# awk sums the counts rather than bc, which this container does not install.
#
# A cargo test FILTER that matches nothing exits 0, so a rename would turn this into a
# green no-op. Assert each command actually ran something.
run_drm_tests() {
local desc="$1"; shift
local out
out=$("$@" 2>&1) || { echo "$out"; echo "::error::drm tests failed: $desc"; exit 1; }
local ran
ran=$(echo "$out" | awk '/^running [0-9]+ tests?$/ { n += $2 } END { print n+0 }')
echo "$desc ran $ran tests"
if [ "$ran" -lt 1 ]; then
echo "::error::$desc selected no tests; it was renamed or removed"
exit 1
fi
}
run_drm_tests "rustdesk drm_capturer_tests" \
cargo test --locked --lib --features drm drm_capturer_tests
run_drm_tests "rustdesk ipc::test" \
cargo test --locked --lib --features drm ipc::test
run_drm_tests "scrap hotspot_provenance_tests" \
cargo test --locked -p scrap --features drm hotspot_provenance_tests
run_drm_tests "scrap hotspot_guess_tests" \
cargo test --locked -p scrap --features drm hotspot_guess_tests
cargo build --locked --lib --features "$FEATURES" --release
rm -rf target/release/deps target/release/build
rm -rf ~/.cargo
+23
View File
@@ -48,6 +48,20 @@ workspace member. `base::config::keys` re-exports the handful of keys
* Do not add dependencies unless needed.
* Keep code simple and idiomatic.
### Logging
* `debug` and above are written to the log file. A log call that can fire
repeatedly (per packet, frame, input event, or loop iteration, or at a rate a
peer controls) must not use `debug` or higher unthrottled.
* For such a site, pick one:
* `log::trace!` when the event is expected and the line only helps while
actively debugging;
* `hbb_common::throttled_log!(interval, level, ...)` when it signals a fault
that should still show up in a user's log. It keeps one line per interval
with a count of the rest. Use `hbb_common::log_throttle::LogThrottle`
directly only when the decision drives more than one log call.
## Tokio Rules
* Assume a Tokio runtime already exists.
@@ -127,6 +141,15 @@ Before considering any implementation complete, perform a minimization pass over
* Before finalizing, explicitly report the regression surface: list the existing files and existing runtime paths whose behavior changed, and explain why each change is unavoidable.
* During review, treat an unnecessarily modified legacy path as a review finding even if tests pass and the rewritten behavior appears equivalent.
### Corner cases raised in review
A refactor added to cover a corner case rarely converges. Each new counter, timestamp, cache or eviction/expiry rule interacts with state that existing code relies on, and the next review round finds the problems it introduced.
* A corner case is still worth fixing when the fix is easy and low-risk: a local change of a few lines that adds no state and changes no existing lookup, such as moving a check or refusing bad input earlier.
* When the only fix needs new state, a new lifecycle rule or a restructure, and the code already fails cleanly there or behaves as master does, document it as a known limit in the PR instead. Anything beyond the easy fix needs the maintainer's explicit go-ahead first.
* Before adding state that reorders, expires or reuses existing data, list every lookup that reads that data and check each one still holds.
* Prefer a clean failure, where the operation reports an error, over machinery that tries to make a rare case succeed.
## Reviewing a PR
* Review only what the diff introduces. Verify ownership with `gh pr diff` before reporting a finding — if the offending lines are untouched context, it is a pre-existing problem, not this PR's.
Generated
+21 -27
View File
@@ -4121,7 +4121,7 @@ dependencies = [
[[package]]
name = "interceptor"
version = "0.14.0"
source = "git+https://github.com/rustdesk-org/webrtc?rev=80d5a20532cf58f5d4d237c437a98ceb85ee40dc#80d5a20532cf58f5d4d237c437a98ceb85ee40dc"
source = "git+https://github.com/rustdesk-org/webrtc?rev=49c89bd8d30e6e62e4c1a96cee38fdc11f79ef63#49c89bd8d30e6e62e4c1a96cee38fdc11f79ef63"
dependencies = [
"async-trait",
"bytes",
@@ -7007,7 +7007,7 @@ dependencies = [
[[package]]
name = "rtcp"
version = "0.13.0"
source = "git+https://github.com/rustdesk-org/webrtc?rev=80d5a20532cf58f5d4d237c437a98ceb85ee40dc#80d5a20532cf58f5d4d237c437a98ceb85ee40dc"
source = "git+https://github.com/rustdesk-org/webrtc?rev=49c89bd8d30e6e62e4c1a96cee38fdc11f79ef63#49c89bd8d30e6e62e4c1a96cee38fdc11f79ef63"
dependencies = [
"bytes",
"thiserror 1.0.61",
@@ -7017,7 +7017,7 @@ dependencies = [
[[package]]
name = "rtp"
version = "0.13.0"
source = "git+https://github.com/rustdesk-org/webrtc?rev=80d5a20532cf58f5d4d237c437a98ceb85ee40dc#80d5a20532cf58f5d4d237c437a98ceb85ee40dc"
source = "git+https://github.com/rustdesk-org/webrtc?rev=49c89bd8d30e6e62e4c1a96cee38fdc11f79ef63#49c89bd8d30e6e62e4c1a96cee38fdc11f79ef63"
dependencies = [
"bytes",
"memchr",
@@ -7196,6 +7196,7 @@ dependencies = [
"wol-rs",
"x11-clipboard 0.8.1",
"x11rb 0.12.0",
"zstd",
]
[[package]]
@@ -7462,7 +7463,7 @@ dependencies = [
[[package]]
name = "sdp"
version = "0.8.0"
source = "git+https://github.com/rustdesk-org/webrtc?rev=80d5a20532cf58f5d4d237c437a98ceb85ee40dc#80d5a20532cf58f5d4d237c437a98ceb85ee40dc"
source = "git+https://github.com/rustdesk-org/webrtc?rev=49c89bd8d30e6e62e4c1a96cee38fdc11f79ef63#49c89bd8d30e6e62e4c1a96cee38fdc11f79ef63"
dependencies = [
"rand 0.8.5",
"substring",
@@ -8034,7 +8035,7 @@ dependencies = [
[[package]]
name = "stun"
version = "0.8.0"
source = "git+https://github.com/rustdesk-org/webrtc?rev=80d5a20532cf58f5d4d237c437a98ceb85ee40dc#80d5a20532cf58f5d4d237c437a98ceb85ee40dc"
source = "git+https://github.com/rustdesk-org/webrtc?rev=49c89bd8d30e6e62e4c1a96cee38fdc11f79ef63#49c89bd8d30e6e62e4c1a96cee38fdc11f79ef63"
dependencies = [
"base64 0.22.1",
"crc",
@@ -8608,8 +8609,8 @@ dependencies = [
[[package]]
name = "tokio-tungstenite"
version = "0.26.2"
source = "git+https://github.com/rustdesk-org/tokio-tungstenite?rev=9c320de8e7c546cb654b017b7f4cbb4a5cc09cd9#9c320de8e7c546cb654b017b7f4cbb4a5cc09cd9"
version = "0.29.0"
source = "git+https://github.com/rustdesk-org/tokio-tungstenite?rev=c241b11b03de4881faf1ecd2fe6e867c92f3013b#c241b11b03de4881faf1ecd2fe6e867c92f3013b"
dependencies = [
"futures-util",
"log",
@@ -8892,9 +8893,8 @@ dependencies = [
[[package]]
name = "tungstenite"
version = "0.26.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4793cb5e56680ecbb1d843515b23b6de9a75eb04b66643e256a396d43be33c13"
version = "0.29.0"
source = "git+https://github.com/rustdesk-org/tungstenite-rs?rev=efce47e5364f00a63302cf07ab1fb13ded478914#efce47e5364f00a63302cf07ab1fb13ded478914"
dependencies = [
"bytes",
"data-encoding",
@@ -8908,14 +8908,13 @@ dependencies = [
"rustls-pki-types",
"sha1",
"thiserror 2.0.17",
"utf-8",
"webpki-roots 0.26.11",
]
[[package]]
name = "turn"
version = "0.10.0"
source = "git+https://github.com/rustdesk-org/webrtc?rev=80d5a20532cf58f5d4d237c437a98ceb85ee40dc#80d5a20532cf58f5d4d237c437a98ceb85ee40dc"
source = "git+https://github.com/rustdesk-org/webrtc?rev=49c89bd8d30e6e62e4c1a96cee38fdc11f79ef63#49c89bd8d30e6e62e4c1a96cee38fdc11f79ef63"
dependencies = [
"async-trait",
"base64 0.22.1",
@@ -9138,12 +9137,6 @@ dependencies = [
"log",
]
[[package]]
name = "utf-8"
version = "0.7.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "09cc8ee72d2a9becf2f2febe0205bbed8fc6615b7cb429ad062dc7b7ddd036a9"
[[package]]
name = "utf16string"
version = "0.2.0"
@@ -9578,7 +9571,7 @@ dependencies = [
[[package]]
name = "webrtc"
version = "0.13.0"
source = "git+https://github.com/rustdesk-org/webrtc?rev=80d5a20532cf58f5d4d237c437a98ceb85ee40dc#80d5a20532cf58f5d4d237c437a98ceb85ee40dc"
source = "git+https://github.com/rustdesk-org/webrtc?rev=49c89bd8d30e6e62e4c1a96cee38fdc11f79ef63#49c89bd8d30e6e62e4c1a96cee38fdc11f79ef63"
dependencies = [
"arc-swap",
"async-trait",
@@ -9621,7 +9614,7 @@ dependencies = [
[[package]]
name = "webrtc-data"
version = "0.11.0"
source = "git+https://github.com/rustdesk-org/webrtc?rev=80d5a20532cf58f5d4d237c437a98ceb85ee40dc#80d5a20532cf58f5d4d237c437a98ceb85ee40dc"
source = "git+https://github.com/rustdesk-org/webrtc?rev=49c89bd8d30e6e62e4c1a96cee38fdc11f79ef63#49c89bd8d30e6e62e4c1a96cee38fdc11f79ef63"
dependencies = [
"bytes",
"log",
@@ -9635,7 +9628,7 @@ dependencies = [
[[package]]
name = "webrtc-dtls"
version = "0.12.0"
source = "git+https://github.com/rustdesk-org/webrtc?rev=80d5a20532cf58f5d4d237c437a98ceb85ee40dc#80d5a20532cf58f5d4d237c437a98ceb85ee40dc"
source = "git+https://github.com/rustdesk-org/webrtc?rev=49c89bd8d30e6e62e4c1a96cee38fdc11f79ef63#49c89bd8d30e6e62e4c1a96cee38fdc11f79ef63"
dependencies = [
"aes",
"aes-gcm",
@@ -9671,11 +9664,12 @@ dependencies = [
[[package]]
name = "webrtc-ice"
version = "0.13.0"
source = "git+https://github.com/rustdesk-org/webrtc?rev=80d5a20532cf58f5d4d237c437a98ceb85ee40dc#80d5a20532cf58f5d4d237c437a98ceb85ee40dc"
source = "git+https://github.com/rustdesk-org/webrtc?rev=49c89bd8d30e6e62e4c1a96cee38fdc11f79ef63#49c89bd8d30e6e62e4c1a96cee38fdc11f79ef63"
dependencies = [
"arc-swap",
"async-trait",
"crc",
"ipnet",
"log",
"portable-atomic",
"rand 0.8.5",
@@ -9695,7 +9689,7 @@ dependencies = [
[[package]]
name = "webrtc-mdns"
version = "0.9.0"
source = "git+https://github.com/rustdesk-org/webrtc?rev=80d5a20532cf58f5d4d237c437a98ceb85ee40dc#80d5a20532cf58f5d4d237c437a98ceb85ee40dc"
source = "git+https://github.com/rustdesk-org/webrtc?rev=49c89bd8d30e6e62e4c1a96cee38fdc11f79ef63#49c89bd8d30e6e62e4c1a96cee38fdc11f79ef63"
dependencies = [
"log",
"socket2 0.5.10",
@@ -9707,7 +9701,7 @@ dependencies = [
[[package]]
name = "webrtc-media"
version = "0.10.0"
source = "git+https://github.com/rustdesk-org/webrtc?rev=80d5a20532cf58f5d4d237c437a98ceb85ee40dc#80d5a20532cf58f5d4d237c437a98ceb85ee40dc"
source = "git+https://github.com/rustdesk-org/webrtc?rev=49c89bd8d30e6e62e4c1a96cee38fdc11f79ef63#49c89bd8d30e6e62e4c1a96cee38fdc11f79ef63"
dependencies = [
"byteorder",
"bytes",
@@ -9719,7 +9713,7 @@ dependencies = [
[[package]]
name = "webrtc-sctp"
version = "0.12.0"
source = "git+https://github.com/rustdesk-org/webrtc?rev=80d5a20532cf58f5d4d237c437a98ceb85ee40dc#80d5a20532cf58f5d4d237c437a98ceb85ee40dc"
source = "git+https://github.com/rustdesk-org/webrtc?rev=49c89bd8d30e6e62e4c1a96cee38fdc11f79ef63#49c89bd8d30e6e62e4c1a96cee38fdc11f79ef63"
dependencies = [
"arc-swap",
"async-trait",
@@ -9736,7 +9730,7 @@ dependencies = [
[[package]]
name = "webrtc-srtp"
version = "0.15.0"
source = "git+https://github.com/rustdesk-org/webrtc?rev=80d5a20532cf58f5d4d237c437a98ceb85ee40dc#80d5a20532cf58f5d4d237c437a98ceb85ee40dc"
source = "git+https://github.com/rustdesk-org/webrtc?rev=49c89bd8d30e6e62e4c1a96cee38fdc11f79ef63#49c89bd8d30e6e62e4c1a96cee38fdc11f79ef63"
dependencies = [
"aead",
"aes",
@@ -9758,7 +9752,7 @@ dependencies = [
[[package]]
name = "webrtc-util"
version = "0.11.0"
source = "git+https://github.com/rustdesk-org/webrtc?rev=80d5a20532cf58f5d4d237c437a98ceb85ee40dc#80d5a20532cf58f5d4d237c437a98ceb85ee40dc"
source = "git+https://github.com/rustdesk-org/webrtc?rev=49c89bd8d30e6e62e4c1a96cee38fdc11f79ef63#49c89bd8d30e6e62e4c1a96cee38fdc11f79ef63"
dependencies = [
"async-trait",
"bitflags 1.3.2",
+20 -5
View File
@@ -62,6 +62,7 @@ cfg-if = "1.0"
lazy_static = "1.4"
sha2 = "0.10"
repng = "0.2"
zstd = "0.13"
parity-tokio-ipc = { git = "https://github.com/rustdesk-org/parity-tokio-ipc" }
magnum-opus = { git = "https://github.com/rustdesk-org/magnum-opus" }
dasp = { version = "0.11", features = ["signal", "interpolate-linear", "interpolate"], optional = true }
@@ -217,9 +218,21 @@ exclude = ["vdi/host"]
# This allows building and running on systems without libxdo installed (e.g., Wayland-only)
[patch.crates-io]
libxdo-sys = { path = "libs/libxdo-sys-stub" }
# Upstream reserves a frame's whole declared length as soon as its header is in, so a header alone
# buys an allocation the size it names, bounded only by max_frame_size. This fork grows the read
# buffer one read_buffer_size chunk at a time as the bytes actually arrive. Patched rather than
# depended on directly, so tokio-tungstenite's own tungstenite resolves to the same copy.
tungstenite = { git = "https://github.com/rustdesk-org/tungstenite-rs", rev = "efce47e5364f00a63302cf07ab1fb13ded478914" }
# One branch off upstream v0.13.0, the tag whose crate versions match this stack.
# webrtc-util: reads the Windows adapter list's IPv6 addresses as host-order u16 groups, so every
# one comes out byte-swapped, fails to bind, and ICE gathers no IPv6 host candidate on Windows.
# one comes out byte-swapped, fails to bind, and ICE gathers no IPv6 host candidate on Windows;
# and names every Windows adapter "" with no mask, so ICE cannot tell one adapter's addresses
# from another's; and lays the adapter struct out in nested parts, whose padding on x64 shifts
# every field after OperStatus, Ipv6IfIndex first.
# webrtc-ice: best effort, one IPv6 host candidate per interface and prefix - the one the OS
# sends from when that is one of the group's, else all of them - since the stable address beside
# the temporary one is an identifier that outlives every rotation and that nothing else this
# machine sends out ever shows.
# webrtc-sctp: RFC 4960's 1s RTO floor makes a single loss cost 1-3s on a link whose RTT is 24-64ms,
# and fast retransmit cannot cover a request/response exchange; INITIAL_MTU 1228 also fragments on
# IPv6; and its AIMD pins a lossy long-haul link to MSS/(RTT*sqrt(p)), so a switch sends without
@@ -229,13 +242,15 @@ libxdo-sys = { path = "libs/libxdo-sys-stub" }
# RTT at KCP's RTO floors, and bundles of small chunks stay within the MTU. A T3-rtx resends
# everything outstanding when it packs into four packets and otherwise probes with one and lets
# the SACK settle the rest (F-RTO), timed from the latest send, so a stall no longer resends the
# whole backlog behind itself while a short lost tail still comes back at once.
# whole backlog behind itself while a short lost tail still comes back at once. A DATA chunk
# received again is listed in the SACK, which never happened - the sender widens its reordering
# window on that - and the SACK keeps to the MTU too, the lowest gap blocks first.
# Pinned by rev, not branch: a fork branch can be rewritten out from under the lockfile.
# webrtc: SettingEngine cannot reach the ICE agent's max_binding_requests, which decides how
# long the answerer keeps checking a pair that has not answered yet.
webrtc = { git = "https://github.com/rustdesk-org/webrtc", rev = "80d5a20532cf58f5d4d237c437a98ceb85ee40dc" }
webrtc-util = { git = "https://github.com/rustdesk-org/webrtc", rev = "80d5a20532cf58f5d4d237c437a98ceb85ee40dc" }
webrtc-sctp = { git = "https://github.com/rustdesk-org/webrtc", rev = "80d5a20532cf58f5d4d237c437a98ceb85ee40dc" }
webrtc = { git = "https://github.com/rustdesk-org/webrtc", rev = "49c89bd8d30e6e62e4c1a96cee38fdc11f79ef63" }
webrtc-util = { git = "https://github.com/rustdesk-org/webrtc", rev = "49c89bd8d30e6e62e4c1a96cee38fdc11f79ef63" }
webrtc-sctp = { git = "https://github.com/rustdesk-org/webrtc", rev = "49c89bd8d30e6e62e4c1a96cee38fdc11f79ef63" }
[package.metadata.winres]
LegalCopyright = "Copyright © 2026 Purslane Tech Pte. Ltd. All rights reserved."
+45 -5
View File
@@ -390,9 +390,9 @@ def ffi_bindgen_function_refactor():
# The commit is fetched directly by sha, so no branch or tag name takes part in the build: see
# build_libdrmtap_so(). This is the SINGLE source of truth for the pin, deliberately not duplicated in
# any workflow, so a bump is one edit here (plus the informational version comment in
# libs/scrap/Cargo.toml). This commit is libdrmtap v0.5.4.
# libs/scrap/Cargo.toml). This commit is libdrmtap v0.5.6.
LIBDRMTAP_REPO_PINNED = 'https://github.com/rustdesk-org/libdrmtap'
LIBDRMTAP_SHA_PINNED = '5da68a3a368db569716d0d0f11cefacbb11b2290'
LIBDRMTAP_SHA_PINNED = '49b204f275af1a2d6dfead94effb4036c7d50a3a'
LIBDRMTAP_REPO = os.environ.get('DRMTAP_REPO', LIBDRMTAP_REPO_PINNED)
LIBDRMTAP_SHA = os.environ.get('DRMTAP_SHA', LIBDRMTAP_SHA_PINNED)
# Every way of getting a different .so than the pin needs the same explicit opt-in. Otherwise the
@@ -489,8 +489,10 @@ def build_libdrmtap_so():
# override of the three -- no fetch, no sha verification, an object built by something this
# script cannot see -- so it is the likeliest to hand over a CPU-only build, and skipping the
# assertion on exactly this path would leave the check guarding only the case that was
# already trustworthy.
# already trustworthy. The helper check rides along for the same reason, and it matters
# more here than anywhere: this is the branch the packaging workflow takes.
_assert_so_has_egl(so)
_assert_so_has_no_helper(so)
return so
# Fetch the pinned source if it is not already present. third_party/libdrmtap is not a submodule
# anymore; it is git-ignored. The commit is fetched BY SHA rather than by cloning a branch:
@@ -521,8 +523,22 @@ def build_libdrmtap_so():
f'libdrmtap at {src} is {got_sha}, expected {LIBDRMTAP_SHA} '
f'(stale checkout from a different pin; removed, re-run to re-fetch)')
build_dir = os.path.join(src, 'build-pkg')
# Configure a fresh dir, or RE-configure one an earlier build left behind. Without the second
# branch a build-pkg created before this option was added keeps its old configuration, meson
# skips setup, and the compile produces a helper-enabled .so. The assertion below then fails
# the build rather than shipping it, so this is a developer-build correctness fix and not a
# security one -- but it turns a confusing failure into no failure at all.
if not os.path.exists(os.path.join(build_dir, 'build.ninja')):
system2(f'meson setup "{build_dir}" "{src}" --buildtype=release')
# -Dhelper=disabled: rustdesk never uses the privileged helper. The capture context is
# opened only in the root service (every drmtap_open lives in src/ipc/drm.rs), which
# already has CAP_SYS_ADMIN, and the unprivileged side opens a render node instead. Without
# this the library still carries the fallback: a fork/exec that walks six hardcoded paths,
# two of them under /usr/local, and execs the first that passes access(X_OK) with no check
# of its owner or mode -- inside the ROOT process. The option compiles that path out
# entirely. Requested by the maintainer on rustdesk#16242.
system2(f'meson setup "{build_dir}" "{src}" --buildtype=release -Dhelper=disabled')
else:
system2(f'meson configure "{build_dir}" -Dhelper=disabled')
# Build only the shared library, not the bundled helper binary or the static archive. Since
# libdrmtap 0.4.11 the project is `both_libraries` (a version-scripted .so + a static .a), so the
# bare `drmtap` target is ambiguous ("drmtap:shared_library" vs "drmtap:static_library"); ask for
@@ -533,9 +549,31 @@ def build_libdrmtap_so():
# require exactly one so a stale object from an earlier build is never silently picked.
so = _single_real_so(sos, f'the libdrmtap meson build dir {build_dir}')
_assert_so_has_egl(so)
_assert_so_has_no_helper(so)
return so
def _assert_so_has_no_helper(so_path):
# Asserted on the ARTIFACT for the same reason the EGL check is: a build flag cannot notice a
# stale object left by an earlier build, or one substituted by hand, and `-Dhelper=disabled` is
# silently accepted by meson versions that predate the option. What the option removes is the
# whole fork/exec path, so the produced .so imports no socketpair and carries none of the
# helper search paths; both go to zero, measured on libdrmtap 0.5.6 (4 -> 0 and 3 -> 0).
#
# This matters because the object is loaded by the ROOT service. With the path compiled in, a
# caller that ever lost CAP_SYS_ADMIN would exec whatever sits at the first of six hardcoded
# locations that passes access(X_OK), without checking its owner or its mode.
with open(so_path, 'rb') as f:
blob = f.read()
found = [m.decode() for m in (b'socketpair', b'/usr/libexec/drmtap-helper') if m in blob]
if found:
raise Exception(
f'{so_path} still carries the privileged-helper fallback ({", ".join(found)}). '
f'It must be built with -Dhelper=disabled: rustdesk captures as root and never uses '
f'the helper, so this is a fork/exec path in the privileged process that nothing '
f'reaches. Delete third_party/libdrmtap/build-pkg and rebuild.')
def _assert_so_has_egl(so_path):
# libdrmtap treats egl/glesv2 as OPTIONAL dependencies: without their headers and pkg-config
# files, meson silently builds a CPU-only stub. That stub still exports every symbol the loader
@@ -863,8 +901,10 @@ def build_deb_from_folder(version, binary_folder, want_drm=False):
# takes the .so straight out of a bundle somebody else produced, so it has the same
# exposure as DRMTAP_PREBUILT_DIR (see the comment on that branch). A CPU-only stub
# would ship, the loader would accept it, and capture would degrade to PipeWire
# without a word.
# without a word. A bundle produced before the helper was disabled is caught here too,
# which is the point: it must not be repackaged into a deb.
_assert_so_has_egl(so)
_assert_so_has_no_helper(so)
stage_libdrmtap_into_deb(so)
system2(f'rm -f "{so}"')
system2('rm -f tmpdeb/usr/share/rustdesk/libdrmtap.so tmpdeb/usr/share/rustdesk/libdrmtap.so.0')
+43 -35
View File
@@ -1,39 +1,45 @@
<p align="center">
<img src="../res/logo-header.svg" alt="RustDesk - Ваша віддалена стільниця"><br>
<a href="#публічні-сервери">Сервери</a> •
<a href="#кроки-для-збірки">Збирання</a> •
<img src="../res/logo-header.svg" alt="RustDesk - Ваш віддалений робочий стіл"><br>
<a href="#кроки-для-збірки">Збірка</a> •
<a href="#як-зібрати-за-допомогою-docker">Docker</a> •
<a href="#структура-файлів">Структура</a> •
<a href="#знімки-екрана">Знімки екрана</a><br>
[<a href="../README.md">English</a>] | [<a href="README-CS.md">česky</a>] | [<a href="README-ZH.md">中文</a>] | [<a href="README-HU.md">Magyar</a>] | [<a href="README-ES.md">Español</a>] | [<a href="README-FA.md">فارسی</a>] | [<a href="README-FR.md">Français</a>] | [<a href="README-DE.md">Deutsch</a>] | [<a href="README-PL.md">Polski</a>] | [<a href="README-ID.md">Indonesian</a>] | [<a href="README-FI.md">Suomi</a>] | [<a href="README-ML.md">മലയാളം</a>] | [<a href="README-JP.md">日本語</a>] | [<a href="README-NL.md">Nederlands</a>] | [<a href="README-IT.md">Italiano</a>] | [<a href="README-RU.md">Русский</a>] | [<a href="README-PTBR.md">Português (Brasil)</a>] | [<a href="README-EO.md">Esperanto</a>] | [<a href="README-KR.md">한국어</a>] | [<a href="README-AR.md">العربي</a>] | [<a href="README-VN.md">Tiếng Việt</a>] | [<a href="README-DA.md">Dansk</a>] | [<a href="README-GR.md">Ελληνικά</a>] | [<a href="README-TR.md">Türkçe</a>]<br>
<b>Нам потрібна ваша допомога для перекладу цього README, <a href="https://github.com/rustdesk/rustdesk/tree/master/src/lang">інтерфейсу</a> та <a href="https://github.com/rustdesk/doc.rustdesk.com">документації</a> RustDesk вашою рідною мовою</B>
[<a href="../README.md">English</a>] | [<a href="README-CS.md">česky</a>] | [<a href="README-ZH.md">中文</a>] | [<a href="README-HU.md">Magyar</a>] | [<a href="README-ES.md">Español</a>] | [<a href="README-FA.md">فارسی</a>] | [<a href="README-FR.md">Français</a>] | [<a href="README-DE.md">Deutsch</a>] | [<a href="README-PL.md">Polski</a>] | [<a href="README-ID.md">Indonesian</a>] | [<a href="README-FI.md">Suomi</a>] | [<a href="README-ML.md">മലയാളം</a>] | [<a href="README-JP.md">日本語</a>] | [<a href="README-NL.md">Nederlands</a>] | [<a href="README-IT.md">Italiano</a>] | [<a href="README-RU.md">Русский</a>] | [<a href="README-PTBR.md">Português (Brasil)</a>] | [<a href="README-EO.md">Esperanto</a>] | [<a href="README-KR.md">한국어</a>] | [<a href="README-AR.md">العربي</a>] | [<a href="README-VN.md">Tiếng Việt</a>] | [<a href="README-DA.md">Dansk</a>] | [<a href="README-GR.md">Ελληνικά</a>] | [<a href="README-TR.md">Türkçe</a>] | [<a href="README-NO.md">Norsk</a>] | [<a href="README-RO.md">Română</a>]<br>
<b>Нам потрібна ваша допомога з перекладом цього README, <a href="https://github.com/rustdesk/rustdesk/tree/master/src/lang">інтерфейсу RustDesk</a> та <a href="https://github.com/rustdesk/doc.rustdesk.com">документації RustDesk</a> вашою рідною мовою</b>
</p>
Спілкування з нами: [Discord](https://discord.gg/nDceKgxnkV) | [Twitter](https://twitter.com/rustdesk) | [Reddit](https://www.reddit.com/r/rustdesk) | [YouTube](https://www.youtube.com/@rustdesk)
> [!CAUTION]
> **Застереження щодо неналежного використання:** <br>
> Розробники RustDesk не схвалюють і не підтримують неетичне або незаконне використання цього програмного забезпечення. Неналежне використання, зокрема несанкціонований доступ, керування або втручання в приватність, суворо суперечить нашим правилам. Автори не несуть відповідальності за неналежне використання застосунку.
[![RustDesk Server Pro](https://img.shields.io/badge/RustDesk%20Server%20Pro-%D0%A0%D0%BE%D0%B7%D1%88%D0%B8%D1%80%D0%B5%D0%BD%D1%96%20%D0%A4%D1%83%D0%BD%D0%BA%D1%86%D1%96%D1%97-blue)](https://rustdesk.com/pricing.html)
Спілкуйтеся з нами: [Discord](https://discord.gg/nDceKgxnkV) | [Twitter](https://twitter.com/rustdesk) | [Reddit](https://www.reddit.com/r/rustdesk) | [YouTube](https://www.youtube.com/@rustdesk)
Ще один застосунок для віддаленого керування стільницею, написаний на Rust. Працює з коробки, не потребує налаштування. Ви повністю контролюєте свої дані, не турбуючись про безпеку. Ви можете використовувати наш сервер ретрансляції, [налаштувати свій власний](https://rustdesk.com/server), або [написати свій власний сервер ретрансляції](https://github.com/rustdesk/rustdesk-server-demo).
[![RustDesk Server Pro](https://img.shields.io/badge/RustDesk%20Server%20Pro-Advanced%20Features-blue)](https://rustdesk.com/pricing.html)
RustDesk — ще одне рішення для віддаленого робочого столу, написане на Rust. Працює одразу після запуску й не потребує налаштування. Ви повністю контролюєте свої дані та їхню безпеку. Можна використовувати наш rendezvous/relay-сервер, [налаштувати власний](https://rustdesk.com/server) або [написати власний rendezvous/relay-сервер](https://github.com/rustdesk/rustdesk-server-demo).
![image](https://user-images.githubusercontent.com/71636191/171661982-430285f0-2e12-4b1d-9957-4a58e375304d.png)
RustDesk вітає внесок кожного. Ознайомтеся з [CONTRIBUTING.md](CONTRIBUTING.md), щоб отримати допомогу на початковому етапі.
RustDesk вітає внески від усіх охочих. Дивіться [CONTRIBUTING.md](CONTRIBUTING.md), щоб дізнатися, з чого почати.
[**ЧаПи**](https://github.com/rustdesk/rustdesk/wiki/FAQ)
[**FAQ**](https://github.com/rustdesk/rustdesk/wiki/FAQ)
[**ЗАВАНТАЖЕННЯ ЗАСТОСУНКУ**](https://github.com/rustdesk/rustdesk/releases)
[**ЗАВАНТАЖИТИ ГОТОВУ ЗБІРКУ**](https://github.com/rustdesk/rustdesk/releases)
[**НІЧНІ ЗБІРКИ**](https://github.com/rustdesk/rustdesk/releases/tag/nightly)
[<img src="https://fdroid.gitlab.io/artwork/badge/get-it-on.png"
[<img src="https://f-droid.org/badge/get-it-on.png"
alt="Get it on F-Droid"
height="80">](https://f-droid.org/en/packages/com.carriez.flutter_hbb)
[<img src="https://flathub.org/api/badge?svg&locale=en"
alt="Get it on Flathub"
height="80">](https://flathub.org/apps/com.rustdesk.RustDesk)
## Залежності
Стільничні версії використовують Flutter чи Sciter (застаріле) для графічного інтерфейсу. Ця інструкція лише для Sciter, оскільки він є більш простим та дружнім для початківців. Перегляньте [CI](https://github.com/rustdesk/rustdesk/blob/master/.github/workflows/flutter-build.yml) для збірки версії на Flutter.
Версії для настільних ОС використовують Flutter або Sciter (застарілий) для графічного інтерфейсу. Ця інструкція стосується лише Sciter, оскільки з ним простіше почати. Для збірки версії на Flutter дивіться наш [CI](https://github.com/rustdesk/rustdesk/blob/master/.github/workflows/flutter-build.yml).
Будь ласка, завантажте динамічну бібліотеку Sciter самостійно.
Динамічну бібліотеку Sciter потрібно завантажити окремо.
[Windows](https://raw.githubusercontent.com/c-smile/sciter-sdk/master/bin.win/x64/sciter.dll) |
[Linux](https://raw.githubusercontent.com/c-smile/sciter-sdk/master/bin.lnx/x64/libsciter-gtk.so) |
@@ -41,14 +47,14 @@ RustDesk вітає внесок кожного. Ознайомтеся з [CONT
## Кроки для збірки
- Підготуйте середовище розробки Rust і середовище збирання C++.
- Підготуйте середовище розробки Rust і середовище для збирання C++.
- Встановіть [vcpkg](https://github.com/microsoft/vcpkg), і правильно встановіть змінну `VCPKG_ROOT`.
- Встановіть [vcpkg](https://github.com/microsoft/vcpkg) і правильно задайте змінну середовища `VCPKG_ROOT`.
- 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
- Запустіть `cargo run`
- Запустіть `cargo run`.
## [Збирання](https://rustdesk.com/docs/en/dev/build/)
@@ -110,7 +116,7 @@ cd
```sh
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
source $HOME/.cargo/env
git clone https://github.com/rustdesk/rustdesk
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
@@ -120,54 +126,56 @@ VCPKG_ROOT=$HOME/vcpkg cargo run
## Як зібрати за допомогою Docker
Почніть з клонування сховища та створення docker-контейнера:
Спочатку клонуйте репозиторій і зберіть Docker-контейнер:
```sh
git clone https://github.com/rustdesk/rustdesk
cd rustdesk
git submodule update --init --recursive
docker build -t "rustdesk-builder" .
```
Надалі щоразу, коли вам буде потрібно зібрати застосунок, запускайте таку команду:
Після цього щоразу, коли потрібно зібрати застосунок, запускайте таку команду:
```sh
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
```
Зверніть увагу, що перша збірка може зайняти більше часу, перш ніж залежності будуть кешовані, але наступні збірки будуть виконуватися швидше. Крім того, якщо вам потрібно вказати інші аргументи для команди збірки, ви можете зробити це в кінці команди у змінній `<OPTIONAL-ARGS>`. Наприклад, якщо ви хочете створити оптимізовану версію, ви маєте запустити наведену вище команду і в кінці рядка додати `--release`. Отриманий виконуваний файл буде доступний у цільовій папці вашої системи і може бути запущений за допомогою:
Перша збірка може тривати довше, доки залежності не буде кешовано. Наступні збірки виконуватимуться швидше. Якщо потрібно передати додаткові аргументи команді збірки, додайте їх після `rustdesk-builder` у кінці команди `docker run`. Наприклад, для оптимізованої release-збірки додайте `--release`. Отриманий виконуваний файл буде доступний у каталозі `target` вашої системи та його можна запустити так:
```sh
target/debug/rustdesk
```
Або, якщо ви використовуєте виконуваний файл релізу:
Або, якщо використовується release-збірка:
```sh
target/release/rustdesk
```
Будь ласка, переконайтеся, що ви запускаєте ці команди з кореня сховища RustDesk, інакше додаток не зможе знайти необхідні ресурси. Також зверніть увагу, що інші cargo підкоманди, такі як `install` або `run`, наразі не підтримуються цим методом, оскільки вони будуть встановлювати або запускати програму всередині контейнера, а не на хості.
Запускайте ці команди з кореневого каталогу репозиторію RustDesk, інакше застосунок може не знайти потрібні ресурси. Також зверніть увагу, що інші підкоманди cargo, наприклад `install` або `run`, наразі не підтримуються цим способом, оскільки вони встановлюватимуть або запускатимуть програму всередині контейнера, а не на хост-системі.
## Структура файлів
- **[libs/hbb_common](https://github.com/rustdesk/rustdesk/tree/master/libs/hbb_common)**: відеокодек, конфіг, обгортка tcp/udp, protobuf, функції fs для передавання файлів і деякі інші службові функції
- **[libs/hbb_common](https://github.com/rustdesk/rustdesk/tree/master/libs/hbb_common)**: відеокодек, конфігурація, обгортка tcp/udp та інші допоміжні функції, спільні із сервером
- **[libs/base](https://github.com/rustdesk/rustdesk/tree/master/libs/base)**: protobuf, функції файлової системи для передавання файлів, код клавіатури та платформоспецифічний код, що використовуються лише цим застосунком
- **[libs/scrap](https://github.com/rustdesk/rustdesk/tree/master/libs/scrap)**: захоплення екрана
- **[libs/enigo](https://github.com/rustdesk/rustdesk/tree/master/libs/enigo)**: специфічне для платформи керування клавіатурою/мишею
- **[libs/clipboard](https://github.com/rustdesk/rustdesk/tree/master/libs/clipboard)**: реалізація копіювання та вставлення файлів для Windows, Linux, macOS.
- **[src/ui](https://github.com/rustdesk/rustdesk/tree/master/src/ui)**: графічний інтерфейс користувача
- **[src/server](https://github.com/rustdesk/rustdesk/tree/master/src/server)**: сервіси аудіо/буфера обміну/вводу/відео та мережевих підключень
- **[src/client.rs](https://github.com/rustdesk/rustdesk/tree/master/src/client.rs)**: однорангове зʼєднання
- **[src/rendezvous_mediator.rs](https://github.com/rustdesk/rustdesk/tree/master/src/rendezvous_mediator.rs)**: комунікація з [rustdesk-server](https://github.com/rustdesk/rustdesk-server), очікування віддаленого прямого (обхід TCP NAT) або ретрансльованого зʼєднання
- **[src/platform](https://github.com/rustdesk/rustdesk/tree/master/src/platform)**: специфічний для платформи код
- **[flutter](https://github.com/rustdesk/rustdesk/tree/master/flutter)**: код Flutter для мобільних пристроїв
- **[libs/enigo](https://github.com/rustdesk/rustdesk/tree/master/libs/enigo)**: платформоспецифічне керування клавіатурою та мишею
- **[libs/clipboard](https://github.com/rustdesk/rustdesk/tree/master/libs/clipboard)**: реалізація копіювання та вставлення файлів для Windows, Linux і macOS
- **[src/ui](https://github.com/rustdesk/rustdesk/tree/master/src/ui)**: застарілий інтерфейс Sciter (deprecated)
- **[src/server](https://github.com/rustdesk/rustdesk/tree/master/src/server)**: служби аудіо, буфера обміну, введення та відео, а також мережеві з'єднання
- **[src/client.rs](https://github.com/rustdesk/rustdesk/tree/master/src/client.rs)**: встановлення однорангового з'єднання
- **[src/rendezvous_mediator.rs](https://github.com/rustdesk/rustdesk/tree/master/src/rendezvous_mediator.rs)**: зв'язок із [rustdesk-server](https://github.com/rustdesk/rustdesk-server), очікування прямого віддаленого з'єднання (TCP hole punching) або з'єднання через ретранслятор
- **[src/platform](https://github.com/rustdesk/rustdesk/tree/master/src/platform)**: платформоспецифічний код
- **[flutter](https://github.com/rustdesk/rustdesk/tree/master/flutter)**: код Flutter для настільних і мобільних платформ
## Знімки екрана
![Менеджер зʼєднань](https://github.com/rustdesk/rustdesk/assets/28412477/db82d4e7-c4bc-4823-8e6f-6af7eadf7651)
![Менеджер підключень](https://github.com/rustdesk/rustdesk/assets/28412477/db82d4e7-c4bc-4823-8e6f-6af7eadf7651)
![Підключення до ПК з Windows](https://github.com/rustdesk/rustdesk/assets/28412477/9baa91e9-3362-4d06-aa1a-7518edcbd7ea)
![Передача файлів](https://github.com/rustdesk/rustdesk/assets/28412477/39511ad3-aa9a-4f8c-8947-1cce286a46ad)
![Передавання файлів](https://github.com/rustdesk/rustdesk/assets/28412477/39511ad3-aa9a-4f8c-8947-1cce286a46ad)
![Тунелювання TCP](https://github.com/rustdesk/rustdesk/assets/28412477/78e8708f-e87e-4570-8373-1360033ea6c5)
![TCP-тунелювання](https://github.com/rustdesk/rustdesk/assets/28412477/78e8708f-e87e-4570-8373-1360033ea6c5)
+2
View File
@@ -126,6 +126,8 @@ const String kOptionEnableBlockInput = "enable-block-input";
const String kOptionEnablePrivacyMode = "enable-privacy-mode";
const String kOptionEnablePermChangeInAcceptWindow =
"enable-perm-change-in-accept-window";
const String kOptionHideElevateButtonInAcceptWindow =
"hide-elevate-button-in-accept-window";
const String kOptionAllowRemoteConfigModification =
"allow-remote-config-modification";
const String kOptionVerificationMethod = "verification-method";
+94 -20
View File
@@ -1005,8 +1005,8 @@ class _RemotePageState extends State<RemotePage>
bool get wantKeepAlive => true;
}
/// A widget that tracks the view size and updates CanvasModel.updateViewStyle()
/// and InputModel.updateImageWidgetSize() only when size actually changes.
/// Tracks view size and DPR to update CanvasModel.updateViewStyle()
/// and InputModel.updateImageWidgetSize() only when either changes.
/// This avoids scheduling post-frame callbacks on every LayoutBuilder rebuild.
class _ViewStyleUpdater extends StatefulWidget {
final CanvasModel canvasModel;
@@ -1026,10 +1026,12 @@ class _ViewStyleUpdater extends StatefulWidget {
class _ViewStyleUpdaterState extends State<_ViewStyleUpdater> {
Size? _lastSize;
double? _lastDevicePixelRatio;
bool _callbackScheduled = false;
@override
Widget build(BuildContext context) {
final devicePixelRatio = MediaQuery.devicePixelRatioOf(context);
return LayoutBuilder(
builder: (context, constraints) {
final maxWidth = constraints.maxWidth;
@@ -1039,8 +1041,9 @@ class _ViewStyleUpdaterState extends State<_ViewStyleUpdater> {
return widget.child;
}
final newSize = Size(maxWidth, maxHeight);
if (_lastSize != newSize) {
if (_lastSize != newSize || _lastDevicePixelRatio != devicePixelRatio) {
_lastSize = newSize;
_lastDevicePixelRatio = devicePixelRatio;
// Schedule the update for after the current frame to avoid setState during build.
// Use _callbackScheduled flag to prevent accumulating multiple callbacks
// when size changes rapidly before any callback executes.
@@ -1088,6 +1091,7 @@ class ImagePaint extends StatefulWidget {
class _ImagePaintState extends State<ImagePaint> {
bool _lastRemoteCursorMoved = false;
final _cursorDisplayScale = 1.0.obs;
String get id => widget.id;
RxBool get zoomCursor => widget.zoomCursor;
@@ -1101,25 +1105,19 @@ class _ImagePaintState extends State<ImagePaint> {
final m = Provider.of<ImageModel>(context);
var c = Provider.of<CanvasModel>(context);
final s = c.scale;
// Read the live DPR while the canvas's post-frame update is pending.
final dpr = MediaQuery.devicePixelRatioOf(context);
bool isViewAdaptive() => c.viewStyle.style == kRemoteViewStyleAdaptive;
bool isViewOriginal() => c.viewStyle.style == kRemoteViewStyleOriginal;
mouseRegion({child}) => Obx(() {
double getCursorScale() {
var c = Provider.of<CanvasModel>(context);
var cursorScale = 1.0;
if (isWindows) {
// debug win10
if (zoomCursor.value && isViewAdaptive()) {
cursorScale = s * c.devicePixelRatio;
}
if (isDesktop) {
return _getDesktopCursorScale(c, dpr);
} else {
if (zoomCursor.value || isViewOriginal()) {
cursorScale = s;
}
return zoomCursor.value || isViewOriginal() ? s : 1.0;
}
return cursorScale;
}
return MouseRegion(
@@ -1193,11 +1191,70 @@ class _ImagePaintState extends State<ImagePaint> {
}
}
/// Matches desktop cursors to the rendered image and native pixel units.
///
/// Windows cursor pixels are physical; NSCursor/GdkCursor use logical pixels.
/// Unzoomed Adaptive/Custom views preserve macOS cursors' point dimensions.
double _getDesktopCursorScale(CanvasModel c, double dpr) {
final peer = widget.ffi.ffiModel;
if (!zoomCursor.value &&
peer.pi.platform == kPeerPlatformMacOS &&
(c.viewStyle.style == kRemoteViewStyleAdaptive ||
c.viewStyle.style == kRemoteViewStyleCustom)) {
return isWindows ? dpr : 1.0;
}
if (peer.isPeerLinux && peer.pi.currentDisplay == kAllDisplayValue) {
if (!zoomCursor.value || c.viewStyle.style == kRemoteViewStyleOriginal) {
// Remove the host output's density without applying canvas zoom.
final scale = 1.0 / _cursorDisplayScale.value;
return isWindows ? scale : scale / dpr;
}
final scale = c.scale / _cursorDisplayScale.value;
return isWindows ? scale * dpr : scale;
}
if (!zoomCursor.value || c.viewStyle.style == kRemoteViewStyleOriginal) {
// Original and unzoomed views do not apply canvas zoom.
final scale = _getCursorScaleForDisplay(1.0);
return isWindows ? scale : scale / dpr;
}
final scale = _getCursorScaleForDisplay(c.scale);
return isWindows ? scale * dpr : scale;
}
double _getCursorScaleForDisplay(double scale) {
final peer = widget.ffi.ffiModel;
// All Displays can mix densities; no single display scale applies.
if (peer.pi.currentDisplay == kAllDisplayValue) return scale;
final displays = peer.pi.getCurDisplays();
if (displays.isEmpty) return scale;
if (peer.pi.platform == kPeerPlatformMacOS) {
// macOS sends NSImage.size in points (src/platform/macos.rs:640,682),
// while HiDPI screen frames use backing pixels (libs/scrap/src/quartz/display.rs:37).
return scale * displays.first.scale;
}
if (!peer.isPeerLinux) return scale;
// Match rendering when a Wayland host
// with multiple outputs reports a display scale > 1.
// A single-output host keeps scale at 1.0 to preserve physical uinput
// coordinates, even with OS scaling enabled. This counts host outputs,
// not the selected displays.length.
// See src/server/display_service.rs:650 (update_sync_displays) and
// src/server/drm_capturer.rs:1523 (DRM's matching convention).
return scale / displays.first.scale;
}
Widget _buildScrollbarNonTextureRender(
ImageModel m, Size imageSize, double s) {
double sizeScale = s;
if (widget.ffi.ffiModel.isPeerLinux) {
final displays = widget.ffi.ffiModel.pi.getCurDisplays();
if (displays.isNotEmpty) {
sizeScale = s / displays[0].scale;
}
}
return CustomPaint(
size: imageSize,
painter: ImagePainter(image: m.image, x: 0, y: 0, scale: s),
painter: ImagePainter(image: m.image, x: 0, y: 0, scale: sizeScale),
);
}
@@ -1242,11 +1299,14 @@ class _ImagePaintState extends State<ImagePaint> {
top: (displays[i].y - rect.top) * s + offset.dy,
width: displays[i].width * sizeScale,
height: displays[i].height * sizeScale,
child: Obx(() => Texture(
textureId: textureId.value,
filterQuality:
isViewOriginal ? FilterQuality.none : FilterQuality.low,
)),
child: _trackCursorDisplay(
Obx(() => Texture(
textureId: textureId.value,
filterQuality:
isViewOriginal ? FilterQuality.none : FilterQuality.low,
)),
displays[i],
),
));
}
}
@@ -1257,6 +1317,20 @@ class _ImagePaintState extends State<ImagePaint> {
);
}
Widget _trackCursorDisplay(Widget child, Display display) {
final peer = widget.ffi.ffiModel;
if (!isDesktop ||
!peer.isPeerLinux ||
peer.pi.currentDisplay != kAllDisplayValue) {
return child;
}
return MouseRegion(
onEnter: (_) => _cursorDisplayScale.value = display.scale,
onHover: (_) => _cursorDisplayScale.value = display.scale,
child: child,
);
}
MouseCursor _buildCustomCursor(BuildContext context, double scale) {
final cursor = Provider.of<CursorModel>(context);
final cache = cursor.cache ?? preDefaultCursor.cache;
+4 -1
View File
@@ -1073,7 +1073,10 @@ class _CmControlPanel extends StatelessWidget {
final model = Provider.of<ServerModel>(context);
final showElevation = canElevate &&
model.showElevation &&
client.type_() == ClientType.remote;
client.type_() == ClientType.remote &&
bind.mainGetBuildinOption(
key: kOptionHideElevateButtonInAcceptWindow) !=
'Y';
final showAccept = model.approveMode != 'password';
return Column(
mainAxisAlignment: MainAxisAlignment.end,
+98 -20
View File
@@ -166,6 +166,7 @@ class FfiModel with ChangeNotifier {
bool get isPeerMobile => isPeerAndroid;
bool get isPeerLinux => _pi.platform == kPeerPlatformLinux;
bool get isPeerWindows => _pi.platform == kPeerPlatformWindows;
bool get viewOnly => _viewOnly;
bool get showMyCursor => _showMyCursor;
@@ -2401,7 +2402,9 @@ class CanvasModel with ChangeNotifier {
// ViewStyle fields and is not captured by the equality check. Therefore, we must
// allow updates to proceed when style == kRemoteViewStyleCustom, even if the
// rest of the ViewStyle fields are unchanged.
if (_lastViewStyle == viewStyle && style != kRemoteViewStyleCustom) {
if (_lastViewStyle == viewStyle &&
_devicePixelRatio == ui.window.devicePixelRatio &&
style != kRemoteViewStyleCustom) {
return;
}
if (_lastViewStyle.style != viewStyle.style) {
@@ -2461,6 +2464,8 @@ class CanvasModel with ChangeNotifier {
_resetScroll();
Future.delayed(duration, () async {
// Layout updates scroll extents and detaches scrollbars no longer needed.
await SchedulerBinding.instance.endOfFrame;
updateScrollPercent();
});
}
@@ -2472,7 +2477,8 @@ class CanvasModel with ChangeNotifier {
style != null ? ScrollStyle.fromString(style) : ScrollStyle.scrollauto;
if (_scrollStyle != ScrollStyle.scrollauto) {
_resetScroll();
// Scrollbar and Scroll Edge share controllers and retain their positions.
updateScrollPercent();
}
notifyListeners();
@@ -2852,6 +2858,9 @@ class CanvasModel with ChangeNotifier {
// data for cursor
class CursorData {
// At most 4 MiB of RGBA, including Linux's square cursor padding.
static const _maxRasterSize = 1024;
final String peerId;
final String id;
final img2.Image image;
@@ -2863,6 +2872,12 @@ class CursorData {
double hoty;
final int width;
final int height;
int _rasterWidth;
int _rasterHeight;
bool _scaleLimitReported = false;
int get rasterWidth => _rasterWidth;
int get rasterHeight => _rasterHeight;
CursorData({
required this.peerId,
@@ -2874,57 +2889,109 @@ class CursorData {
required this.hotyOrigin,
required this.width,
required this.height,
}) : hotx = hotxOrigin * scale,
}) : _rasterWidth = (width * scale).ceil(),
_rasterHeight = (height * scale).ceil(),
hotx = hotxOrigin * scale,
hoty = hotyOrigin * scale;
int _doubleToInt(double v) => (v * 10e6).round().toInt();
double _limitScale(double requestedScale) {
final valid = requestedScale.isFinite && requestedScale > 0;
// Invalid requests retain the last valid raster and hotspot.
final limitedScale = valid
? min(requestedScale, _maxRasterSize / max(width, height))
: scale;
final limited = !valid || limitedScale != requestedScale;
if (limited && !_scaleLimitReported) {
debugPrint(
'Cursor $id: rejected scale $requestedScale for ${width}x$height; '
'using $limitedScale (maximum raster side $_maxRasterSize).');
}
_scaleLimitReported = limited;
return limitedScale;
}
double _checkUpdateScale(double scale) {
double oldScale = this.scale;
scale = _limitScale(scale);
if (scale != 1.0) {
// Update data if scale changed.
final tgtWidth = (width * scale).toInt();
final tgtHeight = (width * scale).toInt();
if (tgtWidth < kMinCursorSize || tgtHeight < kMinCursorSize) {
double sw = kMinCursorSize.toDouble() / width;
double sh = kMinCursorSize.toDouble() / height;
scale = sw < sh ? sh : sw;
}
// A thin cursor must not grow just to make its short edge reach the minimum.
scale = max(scale, kMinCursorSize / max(width, height));
}
if (_doubleToInt(oldScale) != _doubleToInt(scale)) {
final targetWidth = (width * scale).ceil();
final targetHeight = (height * scale).ceil();
if (_rasterWidth != targetWidth || _rasterHeight != targetHeight) {
if (isWindows) {
data = img2
.copyResize(
image,
width: (width * scale).toInt(),
height: (height * scale).toInt(),
width: targetWidth,
height: targetHeight,
interpolation: img2.Interpolation.average,
)
.getBytes(order: img2.ChannelOrder.bgra);
} else if (isDesktop && scale < 1.0 && !image.hasPalette) {
data = Uint8List.fromList(
img2.encodePng(_resizeWithAlpha(targetWidth, targetHeight)));
} else {
data = Uint8List.fromList(
img2.encodePng(
img2.copyResize(
image,
width: (width * scale).toInt(),
height: (height * scale).toInt(),
width: targetWidth,
height: targetHeight,
interpolation: img2.Interpolation.average,
),
),
);
}
_rasterWidth = targetWidth;
_rasterHeight = targetHeight;
}
this.scale = scale;
hotx = hotxOrigin * scale;
hoty = hotyOrigin * scale;
hotx = hotxOrigin * _rasterWidth / width;
hoty = hotyOrigin * _rasterHeight / height;
return scale;
}
img2.Image _resizeWithAlpha(int targetWidth, int targetHeight) {
final resized =
img2.Image.fromResized(image, width: targetWidth, height: targetHeight);
final dx = image.width / targetWidth;
final dy = image.height / targetHeight;
// Use the average filter's sample area, but weight RGB by alpha so
// transparent pixels do not darken visible edges in the straight-alpha PNG.
for (final pixel in resized) {
final x = (pixel.x * dx).toInt();
final y = (pixel.y * dy).toInt();
final sampleWidth = ((pixel.x + 1) * dx).toInt() - x;
final sampleHeight = ((pixel.y + 1) * dy).toInt() - y;
final samples = image.getRange(x, y, sampleWidth, sampleHeight);
num r = 0;
num g = 0;
num b = 0;
num a = 0;
while (samples.moveNext()) {
final sample = samples.current;
r += sample.r * sample.a;
g += sample.g * sample.a;
b += sample.b * sample.a;
a += sample.a;
}
if (a == 0) {
pixel.setRgba(0, 0, 0, 0);
continue;
}
pixel.setRgba(r / a, g / a, b / a, a / (sampleWidth * sampleHeight));
}
return resized;
}
String updateGetKey(double scale) {
scale = _checkUpdateScale(scale);
return '${peerId}_${id}_${_doubleToInt(width * scale)}_${_doubleToInt(height * scale)}';
return '${peerId}_${id}_${_doubleToInt(width * scale)}_${_doubleToInt(height * scale)}_${rasterWidth}_$rasterHeight';
}
}
@@ -3466,6 +3533,17 @@ class CursorModel with ChangeNotifier {
return false;
}
data = imgBytes.buffer.asUint8List();
if (isDesktop &&
(parent.target?.ffiModel.isPeerLinux == true ||
parent.target?.ffiModel.isPeerWindows == true)) {
// PNG decoding supplies straight alpha for Linux/Windows cursor resizing.
final decoded = img2.decodePng(data);
if (decoded == null) {
debugPrint('Unable to decode cursor $id PNG for resizing');
return false;
}
imgOrigin = decoded;
}
}
final cache = CursorData(
peerId: peerId,
@@ -9,6 +9,7 @@ import 'platform_model.dart';
import 'rustdesk_terminal.dart';
import 'terminal_copy_shortcut.dart';
import 'terminal_mouse_drag_reporter.dart';
import 'terminal_scroll_controller.dart';
part 'terminal_mouse_handler_input.dart';
part 'terminal_web_clipboard_gesture.dart';
@@ -55,7 +56,7 @@ class _TerminalMouseInteractionState extends State<TerminalMouseInteraction> {
static const _scrollDown = 1;
final _terminalViewKey = GlobalKey<TerminalViewState>();
final _scrollController = ScrollController();
late final _scrollController = TerminalScrollController(() => widget.terminal);
final _mouseDrag = TerminalMouseDragReporter();
late final WheelButtonFixMouseHandler _mouseHandler;
TerminalMouseHandler? _previousMouseHandler;
@@ -0,0 +1,36 @@
import 'package:flutter/widgets.dart';
import 'package:xterm/xterm.dart';
class TerminalScrollController extends ScrollController {
TerminalScrollController(this.terminal);
final Terminal Function() terminal;
@override
ScrollPosition createScrollPosition(ScrollPhysics physics,
ScrollContext context, ScrollPosition? oldPosition) {
return super.createScrollPosition(
_TerminalScrollPhysics(terminal, parent: physics),
context,
oldPosition,
);
}
}
class _TerminalScrollPhysics extends ScrollPhysics {
const _TerminalScrollPhysics(this.terminal, {super.parent});
final Terminal Function() terminal;
@override
_TerminalScrollPhysics applyTo(ScrollPhysics? ancestor) =>
_TerminalScrollPhysics(terminal, parent: buildParent(ancestor));
@override
bool shouldAcceptUserOffset(ScrollMetrics position) {
// A retained main-screen offset can make this inner scrollable win the
// trackpad gesture, starving xterm's outer alternate-screen scroll handler.
if (terminal().isUsingAltBuffer) return false;
return super.shouldAcceptUserOffset(position);
}
}
+26 -3
View File
@@ -5,7 +5,9 @@ import 'package:flutter_custom_cursor/flutter_custom_cursor.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:flutter_hbb/common.dart' show isLinux;
import 'package:flutter_hbb/models/model.dart';
import 'package:image/image.dart' as img;
deleteCustomCursor(String key) =>
custom_cursor_manager.CursorManager.instance.deleteCursor(key);
@@ -23,6 +25,11 @@ MouseCursor buildCursorOfCache(
if (data == null) {
return MouseCursor.defer;
}
// Square canvases avoid clipping or stray edge pixels on Linux.
final width = isLinux && cache.rasterWidth < cache.rasterHeight
? cache.rasterHeight
: cache.rasterWidth;
final height = isLinux ? width : cache.rasterHeight;
debugPrint(
"Register custom cursor with key $key (${cache.hotx},${cache.hoty})");
// [Safety]
@@ -32,9 +39,12 @@ MouseCursor buildCursorOfCache(
custom_cursor_manager.CursorManager.instance
.registerCursor(custom_cursor_manager.CursorData()
..name = key
..buffer = data
..width = (cache.width * cache.scale).toInt()
..height = (cache.height * cache.scale).toInt()
..buffer =
width == cache.rasterWidth && height == cache.rasterHeight
? data
: _padCursor(data, width)
..width = width
..height = height
..hotX = cache.hotx
..hotY = cache.hoty);
cursor.addKey(key);
@@ -42,3 +52,16 @@ MouseCursor buildCursorOfCache(
return FlutterCustomMemoryImageCursor(key: key);
}
}
Uint8List _padCursor(Uint8List data, int size) {
final bitmap = img.decodePng(data);
if (bitmap == null) {
throw const FormatException('Invalid native cursor PNG');
}
final padded = img.copyExpandCanvas(bitmap,
newWidth: size,
newHeight: size,
position: img.ExpandCanvasPosition.topLeft,
toImage: img.Image(width: size, height: size, numChannels: 4));
return Uint8List.fromList(img.encodePng(padded));
}
+5 -1
View File
@@ -901,7 +901,11 @@ class RustdeskImpl {
}
String mainGetLocalOption({required String key, dynamic hint}) {
return js.context.callMethod('getByName', ['option:local', key]);
final v = js.context.callMethod('getByName', ['option:local', key]);
if (key == 'lang' && (v == 'pt' || v == 'br')) {
return 'pt-br';
}
return v;
}
// Do not return the real environment variables.
+368
View File
@@ -0,0 +1,368 @@
import 'dart:convert';
import 'dart:io';
import 'dart:ui' as ui;
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_hbb/consts.dart';
import 'package:flutter_hbb/desktop/pages/remote_page.dart';
import 'package:flutter_hbb/models/input_model.dart';
import 'package:flutter_hbb/models/model.dart';
import 'package:flutter_hbb/native/custom_cursor.dart';
import 'package:flutter_hbb/utils/image.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:get/get.dart';
import 'package:image/image.dart' as img;
import 'package:provider/provider.dart';
class _Canvas extends ChangeNotifier implements CanvasModel {
_Canvas(String style)
: viewStyle = ViewStyle(
style: style,
width: 200,
height: 160,
displayWidth: 400,
displayHeight: 320);
@override
final ViewStyle viewStyle;
@override
final devicePixelRatio = 1.0;
@override
double scale = 0.25;
@override
final imageOverflow = false.obs;
@override
bool get cursorEmbedded => false;
@override
Size get size => const Size(200, 160);
@override
double get x => 0;
@override
double get y => 0;
@override
dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation);
}
class _Image extends ChangeNotifier implements ImageModel {
@override
bool get useTextureRender => false;
@override
ui.Image? get image => null;
@override
dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation);
}
class _Input extends Fake implements InputModel {
@override
final relativeMouseMode = false.obs;
}
class _Display extends Display {
@override
double scale = 1.0;
}
class _Peer extends Fake implements FfiModel {
@override
final pi = PeerInfo();
@override
bool get isPeerLinux => pi.platform == kPeerPlatformLinux;
@override
bool get isPeerWindows => pi.platform == kPeerPlatformWindows;
}
class _FFI extends Fake implements FFI {
_FFI(this.canvasModel);
@override
final CanvasModel canvasModel;
@override
final ffiModel = _Peer();
@override
final inputModel = _Input();
}
class _Cursor extends CursorModel {
_Cursor(this.cache, FFI ffi) : super(WeakReference(ffi));
@override
final CursorData cache;
}
void main() {
final binding = TestWidgetsFlutterBinding.ensureInitialized();
final channel = Platform.isWindows
? SystemChannels.mouseCursor
: const MethodChannel('flutter_custom_cursor');
final registrations = <Map<dynamic, dynamic>>[];
setUp(() {
registrations.clear();
binding.defaultBinaryMessenger.setMockMethodCallHandler(channel,
(call) async {
if (!call.method.startsWith('createCustomCursor')) return null;
final args = call.arguments as Map<dynamic, dynamic>;
registrations.add(args);
return args['name'];
});
});
tearDown(() =>
binding.defaultBinaryMessenger.setMockMethodCallHandler(channel, null));
for (final scenario in [
((4, 64), 0.5, (2, 32)),
((64, 4), 0.5, (32, 2)),
((1, 64), 0.25, (1, 16)),
((8, 8), 0.5, (12, 12)),
((4, 64), 1.0, (4, 64)),
((1, 512), 10.0, (2, 1024)),
]) {
test('native cursor size $scenario',
() => _checkSize(scenario, registrations));
}
test('native raster boundaries rebuild buffers and distinguish cache keys',
() => _checkRasterTransitions(registrations));
test('cursor resize limits preserve the last valid raster', () async {
for (final size in [(30, 20), (20, 30)]) {
await _checkResizeLimits(size, registrations);
registrations.clear();
}
});
for (final pattern in [
([128, 0, 0, 128], 128),
([255, 0, 0, 255, 0, 0, 0, 0], 127),
]) {
test('Windows peer cursor alpha survives resizing $pattern',
() => _checkWindowsPeerAlpha(pattern, registrations));
}
for (final style in [
kRemoteViewStyleOriginal,
kRemoteViewStyleAdaptive,
kRemoteViewStyleCustom
]) {
for (final zoom in [false, true]) {
testWidgets('$style zoom=$zoom follows the live DPR and peer scale',
(tester) => _checkView(tester, (style, zoom), registrations));
}
}
}
CursorData _data((int, int) size, {Offset hotspot = Offset.zero}) {
final image = img.Image(width: size.$1, height: size.$2, numChannels: 4);
for (final pixel in image) {
pixel.setRgba(64, 32, 16, 255);
}
image.getPixel(0, 0).setRgba(255, 0, 0, 128);
return CursorData(
peerId: 'size',
id: '$size',
image: image,
scale: 1,
data: Platform.isWindows
? image.getBytes(order: img.ChannelOrder.bgra)
: Uint8List.fromList(img.encodePng(image)),
hotxOrigin: hotspot.dx,
hotyOrigin: hotspot.dy,
width: size.$1,
height: size.$2);
}
Future<void> _dispose(CursorModel cursor) async {
for (final key in cursor.cachedKeys) {
await deleteCustomCursor(key);
}
cursor.dispose();
}
Future<void> _checkWindowsPeerAlpha(
(List<int>, int) pattern, List<Map<dynamic, dynamic>> registrations) async {
const sourceSize = 64;
const dpr = 2.0;
const channels = 4;
final ffi = _FFI(_Canvas(kRemoteViewStyleAdaptive));
ffi.ffiModel.pi.platform = kPeerPlatformWindows;
final cursor = CursorModel(WeakReference<FFI>(ffi))..id = 'alpha';
addTearDown(() => _dispose(cursor));
addTearDown(cursor.disposeImages);
addTearDown(ffi.canvasModel.dispose);
await cursor.updateCursorData({
'id': 'alpha',
'hotx': '0',
'hoty': '0',
'width': '$sourceSize',
'height': '$sourceSize',
'colors': jsonEncode(List.generate(sourceSize * sourceSize * channels,
(i) => pattern.$1[i % pattern.$1.length])),
});
buildCursorOfCache(cursor, 1.0 / dpr, cursor.cache);
await Future<void>.delayed(Duration.zero);
final args = registrations.single;
final targetSize = (sourceSize / dpr).ceil();
_expectSize(args, (targetSize, targetSize));
final bytes = args['buffer'] as Uint8List;
if (Platform.isWindows) {
expect(bytes.sublist(0, channels), [0, 0, pattern.$2, pattern.$2]);
} else {
final pixel = img.decodePng(bytes)!.getPixel(0, 0);
expect([pixel.r, pixel.g, pixel.b, pixel.a], [255, 0, 0, pattern.$2]);
}
}
Future<void> _checkSize(((int, int), double, (int, int)) scenario,
List<Map<dynamic, dynamic>> registrations) async {
final ffi = _FFI(_Canvas(kRemoteViewStyleAdaptive));
final cursor = _Cursor(_data(scenario.$1), ffi);
addTearDown(() => _dispose(cursor));
addTearDown(ffi.canvasModel.dispose);
buildCursorOfCache(cursor, scenario.$2, cursor.cache);
await Future<void>.delayed(Duration.zero);
final (width, height) = scenario.$3;
expect(
(cursor.cache.rasterWidth, cursor.cache.rasterHeight), (width, height));
final args = registrations.single;
final padded = Platform.isLinux && width != height;
final side = width > height ? width : height;
_expectSize(args, (padded ? side : width, padded ? side : height));
if (padded) {
final bitmap = img.decodePng(args['buffer'] as Uint8List)!;
final artwork =
img.copyCrop(bitmap, x: 0, y: 0, width: width, height: height);
expect(artwork.getBytes(), img.decodePng(cursor.cache.data!)!.getBytes());
expect(bitmap.where((p) => p.x >= width || p.y >= height).map((p) => p.a),
everyElement(0));
}
}
void _expectSize(Map<dynamic, dynamic> args, (int, int) expected) {
expect((args['width'], args['height']), expected);
final bytes = args['buffer'] as Uint8List;
if (Platform.isWindows) {
const channels = 4;
expect(bytes.length, expected.$1 * expected.$2 * channels);
} else {
final bitmap = img.decodePng(bytes)!;
expect((bitmap.width, bitmap.height), expected);
}
}
Future<void> _checkRasterTransitions(
List<Map<dynamic, dynamic>> registrations) async {
const delta = 3e-8;
const scaleAboveOne = (2.25 / 1.75) / 2.25 * 1.75;
final ffi = _FFI(_Canvas(kRemoteViewStyleAdaptive));
final cursor = _Cursor(_data((64, 64)), ffi);
addTearDown(() => _dispose(cursor));
addTearDown(ffi.canvasModel.dispose);
for (final (scale, expected) in [
(scaleAboveOne, (65, 65)),
(0.5 - delta, (32, 32)),
(0.5 + delta, (33, 33)),
(1.0, (64, 64)),
(scaleAboveOne, (65, 65)),
(1.0, (64, 64)),
]) {
buildCursorOfCache(cursor, scale, cursor.cache);
await Future<void>.delayed(Duration.zero);
final key = cursor.cache.updateGetKey(scale);
_expectSize(
registrations.singleWhere((args) => args['name'] == key), expected);
}
expect(registrations.length, 4);
}
Future<void> _checkResizeLimits(
(int, int) size, List<Map<dynamic, dynamic>> registrations) async {
const maxSide = 1024;
const sourceLongEdge = 30;
const validScale = maxSide / sourceLongEdge;
final ffi = _FFI(_Canvas(kRemoteViewStyleAdaptive));
const hotspot = Offset(4, 7);
final cursor = _Cursor(_data(size, hotspot: hotspot), ffi);
addTearDown(() => _dispose(cursor));
addTearDown(ffi.canvasModel.dispose);
buildCursorOfCache(cursor, validScale, cursor.cache);
await Future<void>.delayed(Duration.zero);
final raster = ((size.$1 * validScale).ceil(), (size.$2 * validScale).ceil());
final expectedHotspot =
(hotspot.dx * raster.$1 / size.$1, hotspot.dy * raster.$2 / size.$2);
_expectSize(
registrations.single, Platform.isLinux ? (maxSide, maxSide) : raster);
expect((registrations.single['hotX'], registrations.single['hotY']),
expectedHotspot);
// Fail on a small allocation before reaching unsafe sizes without the guard.
for (final scale in [
(maxSide + 1) / sourceLongEdge,
double.maxFinite,
double.infinity,
double.nan,
0.0,
-1.0,
]) {
buildCursorOfCache(cursor, scale, cursor.cache);
await Future<void>.delayed(Duration.zero);
expect(cursor.cache.scale, validScale);
expect((cursor.cache.rasterWidth, cursor.cache.rasterHeight), raster);
expect((cursor.cache.hotx, cursor.cache.hoty), expectedHotspot);
}
buildCursorOfCache(cursor, 1.0, cursor.cache);
await Future<void>.delayed(Duration.zero);
expect(cursor.cache.scale, 1.0);
_expectSize(registrations.last,
Platform.isLinux ? (sourceLongEdge, sourceLongEdge) : size);
}
const _viewCases = [
(1.0, kPeerPlatformMacOS, 2.0),
(1.25, kPeerPlatformLinux, 2.0),
(2.0, kPeerPlatformMacOS, 1.0),
];
Future<void> _checkView(WidgetTester tester, (String, bool) mode,
List<Map<dynamic, dynamic>> registrations) async {
const sourceSize = 64, customScale = 4.0;
final canvas = _Canvas(mode.$1);
final ffi = _FFI(canvas);
final display = _Display();
ffi.ffiModel.pi.displays.addAll([Display(), display]);
ffi.ffiModel.pi.currentDisplay = 1;
final cursor = _Cursor(_data((sourceSize, sourceSize)), ffi);
addTearDown(() => _dispose(cursor));
addTearDown(canvas.dispose);
addTearDown(tester.view.resetDevicePixelRatio);
for (final (dpr, peer, peerScale) in _viewCases) {
ffi.ffiModel.pi.platform = peer;
display.scale = peerScale;
canvas.scale = mode.$1 == kRemoteViewStyleCustom
? customScale / dpr
: mode.$1 == kRemoteViewStyleOriginal
? 1.0 / dpr
: canvas.viewStyle.scale;
tester.view.devicePixelRatio = dpr;
await tester.pumpWidget(MediaQuery(
data: MediaQueryData(devicePixelRatio: dpr),
child: MultiProvider(
providers: [
ChangeNotifierProvider<ImageModel>(create: (_) => _Image()),
ChangeNotifierProvider<CanvasModel>.value(value: canvas),
ChangeNotifierProvider<CursorModel>.value(value: cursor),
],
child: ImagePaint(
ffi: ffi,
id: 'size',
zoomCursor: mode.$2.obs,
cursorOverImage: true.obs,
keyboardEnabled: true.obs,
remoteCursorMoved: false.obs,
),
),
));
final video = tester.widget<CustomPaint>(find.byType(CustomPaint)).painter
as ImagePainter;
final scale = video.scale * (mode.$2 ? 1.0 : 1.0 / (canvas.scale * dpr));
final size = sourceSize * (peer == kPeerPlatformMacOS ? peerScale : 1.0);
final w = peer == kPeerPlatformMacOS &&
!mode.$2 &&
mode.$1 != kRemoteViewStyleOriginal
? (sourceSize * (Platform.isWindows ? dpr : 1.0)).ceil()
: (size * scale * (Platform.isWindows ? dpr : 1.0)).ceil();
final key = cursor.cache.updateGetKey(cursor.cache.scale);
_expectSize(registrations.singleWhere((v) => v['name'] == key), (w, w));
}
await tester.pumpWidget(const SizedBox.shrink());
}
@@ -0,0 +1,130 @@
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter_hbb/models/terminal_mouse_handler.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:xterm/xterm.dart';
const _captureMouse = '\x1b[?1007l\x1b[?1000h\x1b[?1002h\x1b[?1006h\x1b[?1003h';
void main() {
late Terminal terminal;
late TerminalController controller;
late List<String> output;
setUp(() {
output = [];
terminal = Terminal()..onOutput = output.add;
controller = TerminalController();
});
Future<TerminalViewState> mount(WidgetTester tester) async {
await tester.pumpWidget(MaterialApp(
home: Align(
alignment: Alignment.topLeft,
child: Padding(
padding: const EdgeInsets.only(left: 30, top: 50),
child: SizedBox(
width: 400,
height: 120,
child: TerminalMouseInteraction(terminal, controller: controller),
),
),
),
));
terminal.write(List.generate(80, (i) => 'line $i\r\n').join());
await tester.pump();
final view = tester.state<TerminalViewState>(find.byType(TerminalView));
expect(view.widget.scrollController!.offset, greaterThan(0));
return view;
}
Future<void> scrollTrackpad(
WidgetTester tester, Offset point, double distance) async {
final pointer = TestPointer(2, PointerDeviceKind.trackpad);
await tester.sendEventToBinding(pointer.panZoomStart(point));
await tester.sendEventToBinding(
pointer.panZoomUpdate(point, pan: Offset(0, distance)));
await tester.sendEventToBinding(
pointer.panZoomUpdate(point, pan: Offset(0, distance * 2)));
await tester.sendEventToBinding(pointer.panZoomEnd());
await tester.pump();
}
for (final trackpad in [false, true]) {
final device = trackpad ? 'trackpad' : 'wheel';
testWidgets('alternate screen reports $device after main-screen history',
(tester) async {
final view = await mount(tester);
terminal.write('\x1b[?1049h$_captureMouse');
await tester.pump();
final render = view.renderTerminal;
final point = render.localToGlobal(
Offset(render.cellSize.width * 2.5, render.lineHeight * 1.5));
if (trackpad) {
await scrollTrackpad(tester, point, render.lineHeight * 3);
} else {
await tester.sendEventToBinding(PointerScrollEvent(
position: point,
scrollDelta: Offset(0, -render.lineHeight * 3),
));
await tester.pump();
}
expect(output, isNotEmpty);
expect(output, everyElement('\x1b[<64;3;2M'));
expect(view.widget.scrollController!.offset, 0);
expect(controller.selection, isNull);
}, variant: TargetPlatformVariant.only(TargetPlatform.macOS));
}
testWidgets('trackpad scrolling keeps subsequent drag coordinates aligned',
(tester) async {
final view = await mount(tester);
terminal.write('\x1b[?1049h$_captureMouse');
await tester.pump();
final render = view.renderTerminal;
final start = render.localToGlobal(
Offset(render.cellSize.width * 2.5, render.lineHeight * 1.5));
final end = render.localToGlobal(
Offset(render.cellSize.width * 6.5, render.lineHeight * 2.5));
await scrollTrackpad(tester, start, render.lineHeight * 3);
output.clear();
final mouse = await tester.createGesture(kind: PointerDeviceKind.mouse);
await mouse.down(start);
await mouse.moveTo(end);
await mouse.up();
await tester.pump(kDoubleTapTimeout);
expect(output, ['\x1b[<0;3;2M', '\x1b[<32;7;3M', '\x1b[<0;7;3m']);
expect(controller.selection, isNull);
expect(controller.suspendedPointerInputs, isFalse);
}, variant: TargetPlatformVariant.only(TargetPlatform.macOS));
testWidgets('leaving alternate screen restores local trackpad scrollback',
(tester) async {
final view = await mount(tester);
terminal.write('\x1b[?1049h$_captureMouse');
await tester.pump();
terminal.write('\x1b[?1003l\x1b[?1002l\x1b[?1000l\x1b[?1006l\x1b[?1049l');
await tester.pump();
final before = view.widget.scrollController!.offset;
await scrollTrackpad(
tester, view.renderTerminal.localToGlobal(const Offset(40, 40)), 48);
expect(output, isEmpty);
expect(view.widget.scrollController!.offset, lessThan(before));
}, variant: TargetPlatformVariant.only(TargetPlatform.macOS));
testWidgets('alternate screen without mouse capture still simulates arrows',
(tester) async {
final view = await mount(tester);
terminal.write('\x1b[?1049h');
await tester.pump();
await scrollTrackpad(
tester, view.renderTerminal.localToGlobal(const Offset(40, 40)), -48);
expect(output, isNotEmpty);
expect(output, everyElement('\x1b[B'));
expect(view.widget.scrollController!.offset, 0);
}, variant: TargetPlatformVariant.only(TargetPlatform.macOS));
}
+3
View File
@@ -705,6 +705,9 @@ message TestDelay {
message PublicKey {
bytes asymmetric_value = 1;
bytes symmetric_value = 2;
// The key exchange version the controller picked, the highest both sides speak; absent,
// i.e. 0, is the original scheme.
uint32 kx_version = 3;
}
message SignedId { bytes id = 1; }
+3
View File
@@ -48,6 +48,8 @@ pub const OPTION_ENABLE_RECORD_SESSION: &str = "enable-record-session";
pub const OPTION_ENABLE_BLOCK_INPUT: &str = "enable-block-input";
pub const OPTION_ENABLE_PRIVACY_MODE: &str = "enable-privacy-mode";
pub const OPTION_ENABLE_PERM_CHANGE_IN_ACCEPT_WINDOW: &str = "enable-perm-change-in-accept-window";
pub const OPTION_HIDE_ELEVATE_BUTTON_IN_ACCEPT_WINDOW: &str =
"hide-elevate-button-in-accept-window";
pub const OPTION_ALLOW_SCOPE_VIOLATION_CLOSE: &str = "allow-scope-violation-close";
pub const OPTION_ALLOW_SCOPE_VIOLATION_ALARM: &str = "allow-scope-violation-alarm";
pub const OPTION_ALLOW_REMOTE_CONFIG_MODIFICATION: &str = "allow-remote-config-modification";
@@ -366,6 +368,7 @@ pub const KEYS_BUILDIN_SETTINGS: &[&str] = &[
OPTION_DISABLE_UNLOCK_PIN,
OPTION_USE_RAW_TCP_FOR_API,
OPTION_ENABLE_PERM_CHANGE_IN_ACCEPT_WINDOW,
OPTION_HIDE_ELEVATE_BUTTON_IN_ACCEPT_WINDOW,
OPTION_ALLOW_COMMAND_LINE_SETTINGS_WHEN_SETTINGS_DISABLED,
];
+33 -1
View File
@@ -48,6 +48,19 @@ pub struct FileDescription {
pub creation_time: SystemTime,
pub size: u64,
pub perm: u16,
/// `file_list_id()` of the list this file came from, sent back in file contents requests
#[serde(default)]
pub clip_data_id: i32,
}
/// Identifies a file list by its descriptor PDU, which both peers hold, so file contents
/// requests can name the list they read from. FNV-1a, same as `wf_cliprdr_file_list_id()`.
pub fn file_list_id(file_descriptor_pdu: &[u8]) -> i32 {
file_descriptor_pdu
.iter()
.fold(0x811c_9dc5_u32, |id, byte| {
(id ^ *byte as u32).wrapping_mul(0x0100_0193)
}) as i32
}
pub(super) fn validate_file_name(name: &str) -> Result<(), CliprdrError> {
@@ -69,6 +82,7 @@ impl FileDescription {
fn parse_file_descriptor(
bytes: &mut Bytes,
conn_id: i32,
clip_data_id: i32,
) -> Result<FileDescription, CliprdrError> {
let flags = bytes.get_u32_le();
// skip reserved 32 bytes
@@ -175,6 +189,7 @@ impl FileDescription {
creation_time: last_modified,
size,
perm,
clip_data_id,
};
Ok(desc)
@@ -186,6 +201,7 @@ impl FileDescription {
file_descriptor_pdu: Vec<u8>,
conn_id: i32,
) -> Result<Vec<Self>, CliprdrError> {
let clip_data_id = file_list_id(&file_descriptor_pdu);
let mut data = Bytes::from(file_descriptor_pdu);
if data.remaining() < 4 {
return Err(CliprdrError::InvalidRequest {
@@ -206,7 +222,7 @@ impl FileDescription {
let mut files = Vec::with_capacity(count);
for _ in 0..count {
let desc = Self::parse_file_descriptor(&mut data, conn_id)?;
let desc = Self::parse_file_descriptor(&mut data, conn_id, clip_data_id)?;
files.push(desc);
}
@@ -282,6 +298,22 @@ mod tests {
assert_eq!(files[0].name, PathBuf::from("file.txt"));
}
#[test]
fn file_list_id_is_fnv1a() {
// Reference vectors; the Windows side computes the same id in C.
assert_eq!(file_list_id(b"") as u32, 0x811c_9dc5);
assert_eq!(file_list_id(b"a") as u32, 0xe40c_292c);
assert_eq!(file_list_id(b"foobar") as u32, 0xbf9c_f968);
}
#[test]
fn parsed_files_carry_their_list_id() {
let pdu = descriptor_pdu("file.txt");
let id = file_list_id(&pdu);
let files = FileDescription::parse_file_descriptors(pdu, 0).unwrap();
assert_eq!(files[0].clip_data_id, id);
}
#[test]
fn rejects_non_terminated_file_name() {
let name = "a".repeat(FILE_NAME_CODE_UNITS);
+8 -2
View File
@@ -549,8 +549,8 @@ impl FuseServer {
n_position_low,
n_position_high,
cb_requested,
have_clip_data_id: false,
clip_data_id: 0,
have_clip_data_id: true,
clip_data_id: node.clip_data_id,
};
send_data(node.conn_id, request.clone()).map_err(|e| {
@@ -611,6 +611,9 @@ struct FuseNode {
/// connection id
pub conn_id: i32,
/// id of the peer's file list this node came from
pub clip_data_id: i32,
/// file index in peer's file list
/// NOTE:
/// it is NOT the same as inode, this is the index in the file list
@@ -634,6 +637,7 @@ impl FuseNode {
pub fn from_description(inode: Inode, desc: FileDescription) -> Self {
Self {
conn_id: desc.conn_id,
clip_data_id: desc.clip_data_id,
index: inode as usize - 2,
name: desc
.name
@@ -650,6 +654,7 @@ impl FuseNode {
pub fn new_root() -> Self {
Self {
conn_id: 0,
clip_data_id: 0,
index: 0,
name: String::from("/"),
parent: None,
@@ -898,6 +903,7 @@ mod fuse_test {
size: 0,
perm: 0,
clip_data_id: 0,
}
}
fn generate_descriptions(prefix: &str) -> Vec<FileDescription> {
@@ -617,6 +617,7 @@ impl PasteTaskHandle {
};
let cb_requested = min(BLOCK_SIZE as u64, file.size - self.progress.offset);
let conn_id = file.conn_id;
let clip_data_id = file.clip_data_id;
let (n_position_high, n_position_low) = (
(self.progress.offset >> 32) as i32,
@@ -629,8 +630,8 @@ impl PasteTaskHandle {
n_position_low,
n_position_high,
cb_requested: cb_requested as _,
have_clip_data_id: false,
clip_data_id: 0,
have_clip_data_id: true,
clip_data_id,
};
allow_err!(send_data(conn_id, request));
self.progress.last_sent_time = Instant::now();
@@ -703,6 +704,7 @@ mod tests {
creation_time: SystemTime::UNIX_EPOCH,
size,
perm: 0,
clip_data_id: 0,
}
}
+515 -12
View File
@@ -1,11 +1,27 @@
use super::local_file::LocalFile;
use crate::{platform::unix::local_file::construct_file_list, ClipboardFile, CliprdrError};
use crate::{
platform::unix::{
filetype::file_list_id,
local_file::{construct_file_list, LocalFile},
},
ClipboardFile, CliprdrError,
};
use hbb_common::{
bytes::{BufMut, BytesMut},
log,
};
use parking_lot::Mutex;
use std::{path::PathBuf, sync::Arc, time::SystemTime, usize};
use std::{
collections::VecDeque,
path::PathBuf,
sync::{atomic::Ordering, Arc},
time::SystemTime,
usize,
};
// Our clients request at most this much per range: macOS 4 MiB, FUSE less, and Windows
// splits larger reads (WF_CLIPRDR_MAX_RANGE_READ). A larger read is refused, not shortened:
// a short response reads as end of file to IStream callers on Windows.
const MAX_RANGE_READ: u64 = 16 * 1024 * 1024;
lazy_static::lazy_static! {
// local files are cached, this value should not be changed when copying files
@@ -13,8 +29,18 @@ lazy_static::lazy_static! {
// We need to keep the file list in the same order as the remote side.
// We may add a `FileId` field to `CliprdrFileContentsRequest` in the future.
static ref CLIP_FILES: Arc<Mutex<ClipFiles>> = Default::default();
// Lists replaced by a newer copy after a peer was sent them, oldest first. The peer's
// streams keep reading the list they came from. Lock after `CLIP_FILES`.
static ref RETIRED_CLIP_FILES: Mutex<VecDeque<ClipFiles>> = Default::default();
}
const MAX_RETIRED_CLIP_FILES: usize = 4;
// The first descriptor's `clsid`, inside the 32 reserved bytes every peer skips. A random
// nonce there makes each copy's list id distinct, even when two copies have identical
// names, sizes and times (the same file in two folders).
const LIST_NONCE: std::ops::Range<usize> = 8..24;
#[derive(Debug)]
enum FileContentsRequest {
Size {
@@ -62,6 +88,10 @@ struct ClipFiles {
file_list: Vec<LocalFile>,
first_file_index: usize,
files_pdu: Vec<u8>,
// `file_list_id(files_pdu)`, which peers send back as `clip_data_id`.
id: i32,
// Connections that were sent `files_pdu`.
served_to: Vec<i32>,
}
impl ClipFiles {
@@ -71,6 +101,8 @@ impl ClipFiles {
self.file_list.clear();
self.first_file_index = usize::MAX;
self.files_pdu.clear();
self.id = 0;
self.served_to.clear();
}
fn sync_files(
@@ -100,9 +132,54 @@ impl ClipFiles {
data.put(file.as_bin()?.as_slice());
}
self.files_pdu = data.to_vec();
if let Some(nonce) = self.files_pdu.get_mut(LIST_NONCE) {
nonce.copy_from_slice(&rand::random::<[u8; 16]>());
}
self.id = file_list_id(&self.files_pdu);
Ok(())
}
// Close files that are not being read, such as the preloaded next file; `read_exact_at`
// reopens them on the next read. A file part-way through keeps its handle and offset, so
// its remaining bytes come from the same file even if its path is replaced meanwhile.
fn release_handles(&mut self) {
for file in self.file_list.iter_mut() {
if file.offset.load(Ordering::Relaxed) == 0 {
file.handle = None;
}
}
}
// A retired list's file is reopened by path once its handle was closed, and the path may now
// name a replacement. Check size and modified time on the handle the read will use, and refuse
// a file that no longer matches the list.
fn check_retired_file(&mut self, request: &FileContentsRequest) -> Result<(), CliprdrError> {
let FileContentsRequest::Range { file_idx, .. } = request else {
return Ok(());
};
let Some(file) = self.file_list.get_mut(*file_idx) else {
return Ok(());
};
if file.is_dir {
return Ok(());
}
file.load_handle()?;
let unchanged = file
.handle
.as_ref()
.and_then(|handle| handle.get_ref().metadata().ok())
.map_or(false, |md| {
md.len() == file.size && md.modified().ok() == Some(file.last_write_time)
});
if unchanged {
Ok(())
} else {
Err(CliprdrError::InvalidRequest {
description: format!("file {} changed since its list was sent", file.name),
})
}
}
fn get_files_for_audit(&self, request: &FileContentsRequest) -> Option<ClipboardFile> {
if let FileContentsRequest::Range {
file_idx, offset, ..
@@ -213,12 +290,21 @@ impl ClipFiles {
),
});
}
let read_size = if offset + length > file.size {
let read_size = if length > file.size - offset {
file.size - offset
} else {
length
};
if read_size > MAX_RANGE_READ {
return Err(CliprdrError::InvalidRequest {
description: format!(
"file contents request of {} bytes exceeds the {} byte limit, conn: {}",
read_size, MAX_RANGE_READ, conn_id
),
});
}
let mut buf = vec![0u8; read_size as usize];
file.read_exact_at(&mut buf, offset)?;
@@ -249,6 +335,44 @@ impl ClipFiles {
#[inline]
pub fn clear_files() {
CLIP_FILES.lock().clear();
RETIRED_CLIP_FILES.lock().clear();
}
// The list a request reads from: the one its `clip_data_id` names, else the one last sent to
// the connection. A named list that is gone yields `None`. A peer that sends no id and was
// never sent a list reads the current one, as before.
fn select_clip_files<'a>(
current: &'a mut ClipFiles,
retired: &'a mut VecDeque<ClipFiles>,
conn_id: i32,
clip_data_id: Option<i32>,
) -> Option<&'a mut ClipFiles> {
match clip_data_id {
Some(id) if current.id == id => Some(current),
Some(id) => retired
.iter_mut()
.rev()
.find(|files| files.id == id && files.served_to.contains(&conn_id)),
None if current.served_to.contains(&conn_id) => Some(current),
None => retired
.iter_mut()
.rev()
.find(|files| files.served_to.contains(&conn_id))
.or(Some(current)),
}
}
// Keep a list a peer was sent, so its streams do not read the new copy at the same indexes.
fn retire_if_served(mut replaced: ClipFiles) {
if replaced.served_to.is_empty() {
return;
}
replaced.release_handles();
let mut retired = RETIRED_CLIP_FILES.lock();
if retired.len() == MAX_RETIRED_CLIP_FILES {
retired.pop_front();
}
retired.push_back(replaced);
}
pub fn read_file_contents(
@@ -259,6 +383,7 @@ pub fn read_file_contents(
n_position_low: i32,
n_position_high: i32,
cb_requested: i32,
clip_data_id: Option<i32>,
) -> Vec<Result<ClipboardFile, CliprdrError>> {
let fcr = if dw_flags == 0x1 {
FileContentsRequest::Size {
@@ -266,8 +391,11 @@ pub fn read_file_contents(
file_idx: list_index as usize,
}
} else if dw_flags == 0x2 {
let offset = (n_position_high as u64) << 32 | n_position_low as u64;
let length = cb_requested as u64;
// nPositionLow and cbRequested are UINT32s carried in i32 fields. Sign-extending
// them rejects offsets whose low word is >= 2 GiB and turns a negative length
// into a near-u64::MAX read.
let offset = (n_position_high as u64) << 32 | n_position_low as u32 as u64;
let length = cb_requested as u32 as u64;
FileContentsRequest::Range {
stream_id,
@@ -281,7 +409,23 @@ pub fn read_file_contents(
})];
};
let mut clip_files = CLIP_FILES.lock();
let mut current = CLIP_FILES.lock();
let mut retired = RETIRED_CLIP_FILES.lock();
let current_ptr: *const ClipFiles = &*current;
let Some(clip_files) = select_clip_files(&mut current, &mut retired, conn_id, clip_data_id)
else {
return vec![Err(CliprdrError::InvalidRequest {
description: format!(
"file list {:?} is not available to conn: {}",
clip_data_id, conn_id
),
})];
};
if !std::ptr::eq(&*clip_files, current_ptr) {
if let Err(e) = clip_files.check_retired_file(&fcr) {
return vec![Err(e)];
}
}
let mut res = vec![];
if let Some(files_res) = clip_files.get_files_for_audit(&fcr) {
res.push(Ok(files_res));
@@ -301,12 +445,21 @@ pub fn sync_files(files: &[String]) -> Result<(), CliprdrError> {
{
return Ok(());
}
files_lock.sync_files(files, current)?;
files_lock.build_file_list_pdu()
// Build aside, so a failure leaves the current list in place.
let mut next = ClipFiles::default();
next.sync_files(files, current)?;
next.build_file_list_pdu()?;
let replaced = std::mem::replace(&mut *files_lock, next);
retire_if_served(replaced);
Ok(())
}
pub fn get_file_list_pdu() -> Vec<u8> {
CLIP_FILES.lock().files_pdu.clone()
pub fn get_file_list_pdu(conn_id: i32) -> Vec<u8> {
let mut clip_files = CLIP_FILES.lock();
if !clip_files.files_pdu.is_empty() && !clip_files.served_to.contains(&conn_id) {
clip_files.served_to.push(conn_id);
}
clip_files.files_pdu.clone()
}
#[cfg(test)]
@@ -343,6 +496,30 @@ mod sig_test {
p.to_string_lossy().to_string()
}
// Tests that drive the global CLIP_FILES must not interleave.
static CLIP_FILES_TEST_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
fn lock_clip_files() -> std::sync::MutexGuard<'static, ()> {
CLIP_FILES_TEST_LOCK
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner())
}
// Sparse, so a multi-GiB file costs no disk space.
fn write_at(path: &PathBuf, offset: u64, data: &[u8]) {
use std::io::{Seek, SeekFrom, Write};
let mut f = fs::File::create(path).unwrap();
f.seek(SeekFrom::Start(offset)).unwrap();
f.write_all(data).unwrap();
}
fn range_data(res: Vec<Result<ClipboardFile, CliprdrError>>) -> Vec<u8> {
match res.into_iter().last() {
Some(Ok(ClipboardFile::FileContentsResponse { requested_data, .. })) => requested_data,
other => panic!("unexpected response: {:?}", other),
}
}
#[test]
fn fingerprint_missing_path_is_default() {
let tmp = TmpDir::new("missing");
@@ -393,7 +570,8 @@ mod sig_test {
let files = vec![path_str(&file)];
// Drive the public, guarded `sync_files` over the global CLIP_FILES;
// reset first (this is the only test that touches the global).
// reset first.
let _guard = lock_clip_files();
clear_files();
sync_files(&files).unwrap();
@@ -415,4 +593,329 @@ mod sig_test {
clear_files(); // leave the global clean for other tests
}
#[test]
fn range_request_huge_length_is_clamped() {
let tmp = TmpDir::new("range");
let file = tmp.join("data.bin");
fs::write(&file, b"0123456789").unwrap();
let files = vec![path_str(&file)];
let mut clip = ClipFiles::default();
clip.sync_files(&files, fingerprint(&files)).unwrap();
let file_idx = clip.first_file_index;
// offset + length used to wrap to 0, skip the clamp and ask for a u64::MAX buffer.
let resp = clip
.serve_file_contents(
0,
FileContentsRequest::Range {
stream_id: 0,
file_idx,
offset: 1,
length: u64::MAX,
},
)
.unwrap();
match resp {
ClipboardFile::FileContentsResponse { requested_data, .. } => {
assert_eq!(requested_data, b"123456789");
}
_ => panic!("unexpected response"),
}
}
#[test]
fn range_request_decodes_wire_fields_as_u32() {
let tmp = TmpDir::new("decode");
let small = tmp.join("small.bin");
fs::write(&small, b"0123456789").unwrap();
let large = tmp.join("large.bin");
write_at(&large, 0x8000_0000, b"tail");
let _guard = lock_clip_files();
clear_files();
sync_files(&[path_str(&small), path_str(&large)]).unwrap();
let small_idx = CLIP_FILES.lock().first_file_index as i32;
let large_idx = small_idx + 1;
// A negative cbRequested is a UINT32 length, clamped to the rest of the file.
let res = read_file_contents(0, 0, small_idx, 0x2, 1, 0, -1, None);
assert_eq!(range_data(res), b"123456789");
// An nPositionLow with bit 31 set is an offset past 2 GiB, not a huge one.
let res = read_file_contents(0, 0, large_idx, 0x2, 0x8000_0000u32 as i32, 0, 4, None);
assert_eq!(range_data(res), b"tail");
clear_files();
}
#[test]
fn range_request_over_limit_is_rejected() {
let tmp = TmpDir::new("limit");
let file = tmp.join("big.bin");
let size = MAX_RANGE_READ + 1;
write_at(&file, size - 1, b"x");
let files = vec![path_str(&file)];
let mut clip = ClipFiles::default();
clip.sync_files(&files, fingerprint(&files)).unwrap();
let file_idx = clip.first_file_index;
let res = clip.serve_file_contents(
0,
FileContentsRequest::Range {
stream_id: 0,
file_idx,
offset: 0,
length: u32::MAX as u64,
},
);
assert!(matches!(res, Err(CliprdrError::InvalidRequest { .. })));
}
#[test]
fn host_copy_during_transfer_keeps_serving_the_sent_list() {
let tmp = TmpDir::new("recopy_in_flight");
let first = tmp.join("first.bin");
fs::write(&first, b"AAAAAAAA").unwrap();
let second = tmp.join("second.bin");
fs::write(&second, b"BBBBBBBB").unwrap();
let _guard = lock_clip_files();
clear_files();
sync_files(&[path_str(&first)]).unwrap();
get_file_list_pdu(1);
let idx = CLIP_FILES.lock().first_file_index as i32;
let read = |offset| range_data(read_file_contents(1, 7, idx, 0x2, offset, 0, 4, None));
assert_eq!(read(0), b"AAAA");
// Copying another file on this side must not redirect the peer's stream.
sync_files(&[path_str(&second)]).unwrap();
assert_eq!(read(4), b"AAAA");
clear_files();
}
#[test]
fn stream_keeps_its_list_after_a_second_paste() {
let tmp = TmpDir::new("repaste_in_flight");
let first = tmp.join("first.bin");
fs::write(&first, b"AAAAAAAA").unwrap();
let second = tmp.join("second.bin");
fs::write(&second, b"BBBBBBBB").unwrap();
let _guard = lock_clip_files();
clear_files();
sync_files(&[path_str(&first)]).unwrap();
let first_id = file_list_id(&get_file_list_pdu(1));
let idx = CLIP_FILES.lock().first_file_index as i32;
// The peer copies the second file on this side and pastes it while the first
// transfer is still reading.
sync_files(&[path_str(&second)]).unwrap();
let second_id = file_list_id(&get_file_list_pdu(1));
assert_ne!(first_id, second_id);
let read = |id| range_data(read_file_contents(1, 7, idx, 0x2, 4, 0, 4, Some(id)));
assert_eq!(read(first_id), b"AAAA");
assert_eq!(read(second_id), b"BBBB");
clear_files();
}
#[test]
fn named_list_must_have_been_sent_to_the_conn() {
let tmp = TmpDir::new("foreign_list");
let first = tmp.join("first.bin");
fs::write(&first, b"AAAAAAAA").unwrap();
let second = tmp.join("second.bin");
fs::write(&second, b"BBBBBBBB").unwrap();
let _guard = lock_clip_files();
clear_files();
sync_files(&[path_str(&first)]).unwrap();
let first_id = file_list_id(&get_file_list_pdu(1));
let idx = CLIP_FILES.lock().first_file_index as i32;
sync_files(&[path_str(&second)]).unwrap();
let refused = |conn_id, id| {
matches!(
read_file_contents(conn_id, 7, idx, 0x2, 0, 0, 4, Some(id)).last(),
Some(Err(CliprdrError::InvalidRequest { .. }))
)
};
// Retired list, asked for by a connection it was never sent to.
assert!(refused(2, first_id));
// A list id this side never sent.
assert!(refused(1, first_id ^ 1));
clear_files();
}
#[test]
fn failed_recopy_keeps_the_current_list() {
let tmp = TmpDir::new("failed_recopy");
let first = tmp.join("first.bin");
fs::write(&first, b"AAAAAAAA").unwrap();
let missing = tmp.join("missing.bin");
let _guard = lock_clip_files();
clear_files();
sync_files(&[path_str(&first)]).unwrap();
let pdu = get_file_list_pdu(1);
assert!(sync_files(&[path_str(&missing)]).is_err());
assert_eq!(get_file_list_pdu(1), pdu);
clear_files();
}
fn file_index(path: &PathBuf) -> i32 {
let files = CLIP_FILES.lock();
files
.file_list
.iter()
.position(|f| &f.path == path)
.unwrap() as i32
}
// Replaces `path` the way editors save: write aside, then rename over it.
fn replace_atomically(path: &PathBuf, data: &[u8]) {
let aside = path.with_extension("new");
fs::write(&aside, data).unwrap();
fs::rename(&aside, path).unwrap();
}
#[test]
fn retired_list_closes_only_files_not_being_read() {
let tmp = TmpDir::new("retired_handles");
let first = tmp.join("first.bin");
fs::write(&first, b"AAAABBBB").unwrap();
let next = tmp.join("next.bin");
fs::write(&next, b"CCCCDDDD").unwrap();
let other = tmp.join("other.bin");
fs::write(&other, b"EEEEEEEE").unwrap();
let _guard = lock_clip_files();
clear_files();
sync_files(&[path_str(&first), path_str(&next)]).unwrap();
let id = file_list_id(&get_file_list_pdu(1));
let (first_idx, next_idx) = (file_index(&first), file_index(&next));
let read =
|idx, offset| range_data(read_file_contents(1, 7, idx, 0x2, offset, 0, 4, Some(id)));
// Leaves `first` open at offset 4, and preloads `next`.
assert_eq!(read(first_idx, 0), b"AAAA");
sync_files(&[path_str(&other)]).unwrap();
{
let retired = RETIRED_CLIP_FILES.lock();
let open = |idx: i32| retired[0].file_list[idx as usize].handle.is_some();
assert!(open(first_idx));
assert!(!open(next_idx));
}
assert_eq!(read(first_idx, 4), b"BBBB");
assert_eq!(read(next_idx, 0), b"CCCC");
clear_files();
}
#[test]
fn files_being_read_keep_their_content_when_their_paths_are_replaced() {
let tmp = TmpDir::new("replaced_paths");
let first = tmp.join("first.bin");
fs::write(&first, b"1111aaaa").unwrap();
let second = tmp.join("second.bin");
fs::write(&second, b"2222bbbb").unwrap();
let other = tmp.join("other.bin");
fs::write(&other, b"EEEEEEEE").unwrap();
let _guard = lock_clip_files();
clear_files();
sync_files(&[path_str(&first), path_str(&second)]).unwrap();
let id = file_list_id(&get_file_list_pdu(1));
let (first_idx, second_idx) = (file_index(&first), file_index(&second));
let read =
|idx, offset| range_data(read_file_contents(1, 7, idx, 0x2, offset, 0, 4, Some(id)));
// Two files part-way through at once.
assert_eq!(read(first_idx, 0), b"1111");
assert_eq!(read(second_idx, 0), b"2222");
sync_files(&[path_str(&other)]).unwrap();
replace_atomically(&first, b"3333cccc");
replace_atomically(&second, b"4444dddd");
assert_eq!(read(first_idx, 4), b"aaaa");
assert_eq!(read(second_idx, 4), b"bbbb");
clear_files();
}
#[test]
fn same_file_metadata_in_another_folder_is_another_list() {
let tmp = TmpDir::new("same_metadata");
let (dir_a, dir_b) = (tmp.join("a"), tmp.join("b"));
fs::create_dir_all(&dir_a).unwrap();
fs::create_dir_all(&dir_b).unwrap();
let (first, second) = (dir_a.join("report.bin"), dir_b.join("report.bin"));
fs::write(&first, b"AAAAAAAA").unwrap();
fs::write(&second, b"BBBBBBBB").unwrap();
// Same name, size and mtime: the descriptors differ only by the nonce.
let mtime = SystemTime::UNIX_EPOCH + std::time::Duration::from_secs(1_700_000_000);
for path in [&first, &second] {
fs::File::options()
.write(true)
.open(path)
.unwrap()
.set_modified(mtime)
.unwrap();
}
let _guard = lock_clip_files();
clear_files();
sync_files(&[path_str(&first)]).unwrap();
let first_id = file_list_id(&get_file_list_pdu(1));
let idx = CLIP_FILES.lock().first_file_index as i32;
sync_files(&[path_str(&second)]).unwrap();
let second_id = file_list_id(&get_file_list_pdu(1));
assert_ne!(first_id, second_id);
let read = |id| range_data(read_file_contents(1, 7, idx, 0x2, 4, 0, 4, Some(id)));
assert_eq!(read(first_id), b"AAAA");
assert_eq!(read(second_id), b"BBBB");
clear_files();
}
#[test]
fn a_retired_list_refuses_a_file_replaced_before_its_read() {
let tmp = TmpDir::new("replaced_unread");
let first = tmp.join("first.bin");
fs::write(&first, b"AAAAAAAA").unwrap();
let second = tmp.join("second.bin");
fs::write(&second, b"BBBBBBBB").unwrap();
let other = tmp.join("other.bin");
fs::write(&other, b"EEEEEEEE").unwrap();
let _guard = lock_clip_files();
clear_files();
sync_files(&[path_str(&first), path_str(&second)]).unwrap();
let id = file_list_id(&get_file_list_pdu(1));
let (first_idx, second_idx) = (file_index(&first), file_index(&second));
let read = |idx, offset| read_file_contents(1, 7, idx, 0x2, offset, 0, 4, Some(id));
assert_eq!(range_data(read(first_idx, 0)), b"AAAA");
// Retiring closes `second`, which has not been read yet; it is then replaced.
sync_files(&[path_str(&other)]).unwrap();
replace_atomically(&second, b"CCCCCCCCCC");
assert!(matches!(
read(second_idx, 0).last(),
Some(Err(CliprdrError::InvalidRequest { .. }))
));
// The file part-way through is unaffected.
assert_eq!(range_data(read(first_idx, 4)), b"AAAA");
clear_files();
}
}
+369 -54
View File
@@ -54,6 +54,12 @@
/* File clipboard redirection always advertises the descriptor and contents formats. */
#define WF_CLIPRDR_FILE_FORMAT_COUNT 2u
#define WF_CLIPRDR_COM_LPT_PREFIX_LENGTH 3u
/* File lists kept after they were sent, so a transfer still in flight keeps reading its own
* files after a later copy or paste replaces them. */
#define WF_CLIPRDR_SERVED_FILE_LISTS 4u
/* Largest range served in one request, here and by the unix file server (MAX_RANGE_READ in
* serv_files.rs). Larger IStream reads are split into requests of this size. */
#define WF_CLIPRDR_MAX_RANGE_READ (16u * 1024u * 1024u)
static const WCHAR WF_CLIPRDR_SUPERSCRIPT_DIGITS[] = L"\x00B9\x00B2\x00B3";
static const WCHAR WF_CLIPRDR_INVALID_FILE_NAME_CHARS[] = L"<>:\"|?*";
@@ -213,6 +219,21 @@ static BOOL wf_cliprdr_bounded_strlen(const char *value, size_t max_len, size_t
return FALSE;
}
/* Identifies a file list by its FILEGROUPDESCRIPTORW bytes, which both peers hold, and is
* carried as FileContentsRequest.clipDataId. FNV-1a, same as `file_list_id()` on unix. */
static UINT32 wf_cliprdr_file_list_id(const BYTE *data, SIZE_T size)
{
UINT32 id = 2166136261u;
SIZE_T i;
for (i = 0; i < size; i++)
{
id ^= data[i];
id *= 16777619u;
}
return id;
}
/**
* Clipboard Formats
*/
@@ -358,6 +379,7 @@ struct _CliprdrStream
void *m_pData;
UINT32 m_connID;
UINT32 m_streamId; // unique CLIPRDR streamId; avoids leaking a heap pointer
UINT32 m_clipDataId; // id of the file list this stream was created from
};
typedef struct _CliprdrStream CliprdrStream;
@@ -377,6 +399,21 @@ struct _CliprdrDataObject
};
typedef struct _CliprdrDataObject CliprdrDataObject;
struct wf_served_file_list
{
UINT32 id;
UINT32 *connIDs; // connections the list was sent to
size_t nConnIDs;
UINT64 last_served; // served_file_list_seq when last sent; the lowest is evicted first
size_t nFiles;
size_t first_file_index;
WCHAR **file_names;
UINT64 *file_sizes;
BYTE *descriptors; // the FILEGROUPDESCRIPTORW sent, nonce included
SIZE_T descriptorsSize;
};
typedef struct wf_served_file_list wfServedFileList;
struct wf_clipboard
{
// wfContext* wfc;
@@ -424,6 +461,10 @@ struct wf_clipboard
WCHAR **file_names;
size_t first_file_index;
FILEDESCRIPTORW **fileDescriptor;
DWORD file_list_seq; // clipboard sequence number the file list was read at
UINT32 file_list_id; // wf_cliprdr_file_list_id() of the file list, 0 while none is valid
wfServedFileList served_file_lists[WF_CLIPRDR_SERVED_FILE_LISTS];
UINT64 served_file_list_seq;
BOOL legacyApi;
HMODULE hUser32;
@@ -451,8 +492,8 @@ static UINT cliprdr_send_data_request(UINT32 connID, wfClipboard *clipboard, UIN
static UINT cliprdr_send_lock(wfClipboard *clipboard);
static UINT cliprdr_send_unlock(wfClipboard *clipboard);
static UINT cliprdr_send_request_filecontents(wfClipboard *clipboard, UINT32 connID, UINT32 streamId,
ULONG index, UINT32 flag, DWORD positionhigh,
DWORD positionlow, ULONG request);
UINT32 clipDataId, ULONG index, UINT32 flag,
DWORD positionhigh, DWORD positionlow, ULONG request);
static BOOL is_file_descriptor_from_remote();
static BOOL is_set_by_instance(wfClipboard *clipboard);
@@ -464,6 +505,7 @@ static HRESULT CliprdrEnumFORMATETC_New(ULONG nFormats, FORMATETC *pFormatEtc,
static void CliprdrEnumFORMATETC_Delete(CliprdrEnumFORMATETC *instance);
static void CliprdrStream_Delete(CliprdrStream *instance);
static HRESULT wf_cliprdr_stream_read_split(IStream *This, BYTE *pv, ULONG cb, ULONG *pcbRead);
static BOOL try_open_clipboard(HWND hwnd)
{
@@ -550,7 +592,11 @@ static HRESULT STDMETHODCALLTYPE CliprdrStream_Read(IStream *This, void *pv, ULO
if (instance->m_lOffset.QuadPart >= instance->m_lSize.QuadPart)
return S_FALSE;
ret = cliprdr_send_request_filecontents(clipboard, instance->m_connID, instance->m_streamId, instance->m_lIndex,
if (cb > WF_CLIPRDR_MAX_RANGE_READ)
return wf_cliprdr_stream_read_split(This, (BYTE *)pv, cb, pcbRead);
ret = cliprdr_send_request_filecontents(clipboard, instance->m_connID, instance->m_streamId,
instance->m_clipDataId, instance->m_lIndex,
FILECONTENTS_RANGE, instance->m_lOffset.HighPart,
instance->m_lOffset.LowPart, cb);
@@ -591,6 +637,26 @@ static HRESULT STDMETHODCALLTYPE CliprdrStream_Read(IStream *This, void *pv, ULO
return S_OK;
}
static HRESULT wf_cliprdr_stream_read_split(IStream *This, BYTE *pv, ULONG cb, ULONG *pcbRead)
{
HRESULT hr = S_OK;
ULONG total = 0;
ULONG chunk;
ULONG n;
while (total < cb && hr == S_OK)
{
chunk = cb - total < WF_CLIPRDR_MAX_RANGE_READ ? cb - total : WF_CLIPRDR_MAX_RANGE_READ;
n = 0;
hr = CliprdrStream_Read(This, pv + total, chunk, &n);
total += n;
}
*pcbRead = total;
if (FAILED(hr))
return hr;
return total < cb ? S_FALSE : S_OK;
}
static HRESULT STDMETHODCALLTYPE CliprdrStream_Write(IStream *This, const void *pv, ULONG cb,
ULONG *pcbWritten)
{
@@ -736,7 +802,8 @@ static HRESULT STDMETHODCALLTYPE CliprdrStream_Clone(IStream *This, IStream **pp
return E_NOTIMPL;
}
static CliprdrStream *CliprdrStream_New(UINT32 connID, ULONG index, void *pData, const FILEDESCRIPTORW *dsc)
static CliprdrStream *CliprdrStream_New(UINT32 connID, ULONG index, void *pData, const FILEDESCRIPTORW *dsc,
UINT32 clipDataId)
{
IStream *iStream = NULL;
BOOL success = FALSE;
@@ -779,6 +846,7 @@ static CliprdrStream *CliprdrStream_New(UINT32 connID, ULONG index, void *pData,
instance->m_lOffset.QuadPart = 0;
instance->m_connID = connID;
instance->m_streamId = (UINT32)InterlockedIncrement(&clipboard->req_f_stream_id_seq);
instance->m_clipDataId = clipDataId;
if (instance->m_Dsc.dwFlags & FD_ATTRIBUTES)
{
@@ -790,8 +858,8 @@ static CliprdrStream *CliprdrStream_New(UINT32 connID, ULONG index, void *pData,
{
/* get content size of this stream */
if (cliprdr_send_request_filecontents(clipboard, instance->m_connID, instance->m_streamId,
instance->m_lIndex, FILECONTENTS_SIZE, 0, 0,
8) == CHANNEL_RC_OK)
instance->m_clipDataId, instance->m_lIndex,
FILECONTENTS_SIZE, 0, 0, 8) == CHANNEL_RC_OK)
{
success = TRUE;
}
@@ -1007,6 +1075,7 @@ static HRESULT STDMETHODCALLTYPE CliprdrDataObject_GetData(IDataObject *This, FO
IStream **streams = NULL;
UINT stream_count = 0;
SIZE_T hmem_size;
UINT32 clipDataId;
// DWORD remote_format_id = get_remote_format_id(clipboard, instance->m_pFormatEtc[idx].cfFormat);
// FIXME: origin code may be failed here???
if (cliprdr_send_data_request(instance->m_connID, clipboard, instance->m_pFormatEtc[idx].cfFormat) != 0)
@@ -1053,10 +1122,11 @@ static HRESULT STDMETHODCALLTYPE CliprdrDataObject_GetData(IDataObject *This, FO
return wf_cliprdr_fail_locked_file_descriptor_data(
clipboard, pMedium, instance, NULL, 0, E_OUTOFMEMORY);
clipDataId = wf_cliprdr_file_list_id((const BYTE *)dsc, hmem_size);
for (i = 0; i < stream_count; i++)
{
streams[i] =
(IStream *)CliprdrStream_New(instance->m_connID, i, clipboard, &dsc->fgd[i]);
streams[i] = (IStream *)CliprdrStream_New(instance->m_connID, i, clipboard,
&dsc->fgd[i], clipDataId);
if (!streams[i])
{
return wf_cliprdr_fail_locked_file_descriptor_data(
@@ -1996,9 +2066,9 @@ static UINT cliprdr_send_data_request(UINT32 connID, wfClipboard *clipboard, UIN
return wait_response_event(connID, clipboard, clipboard->formatDataRespEvent, &clipboard->formatDataRespReceived, &clipboard->hmem);
}
static UINT cliprdr_send_request_filecontents(wfClipboard *clipboard, UINT32 connID, UINT32 streamId, ULONG index,
UINT32 flag, DWORD positionhigh, DWORD positionlow,
ULONG nreq)
static UINT cliprdr_send_request_filecontents(wfClipboard *clipboard, UINT32 connID, UINT32 streamId,
UINT32 clipDataId, ULONG index, UINT32 flag,
DWORD positionhigh, DWORD positionlow, ULONG nreq)
{
UINT rc;
CLIPRDR_FILE_CONTENTS_REQUEST fileContentsRequest = { 0 };
@@ -2023,7 +2093,8 @@ static UINT cliprdr_send_request_filecontents(wfClipboard *clipboard, UINT32 con
fileContentsRequest.nPositionLow = positionlow;
fileContentsRequest.nPositionHigh = positionhigh;
fileContentsRequest.cbRequested = nreq;
fileContentsRequest.clipDataId = 0;
fileContentsRequest.haveClipDataId = TRUE;
fileContentsRequest.clipDataId = clipDataId;
fileContentsRequest.msgFlags = 0;
rc = clipboard->context->ClientFileContentsRequest(clipboard->context, &fileContentsRequest);
if (rc != ERROR_SUCCESS)
@@ -2424,6 +2495,242 @@ error:
return res;
}
static void wf_cliprdr_free_served_file_list(wfServedFileList *list)
{
size_t i;
if (list->file_names)
{
for (i = 0; i < list->nFiles; i++)
free(list->file_names[i]);
free(list->file_names);
}
free(list->file_sizes);
free(list->connIDs);
free(list->descriptors);
ZeroMemory(list, sizeof(*list));
}
static BOOL wf_cliprdr_served_to(const wfServedFileList *list, UINT32 connID)
{
size_t i;
for (i = 0; i < list->nConnIDs; i++)
{
if (list->connIDs[i] == connID)
return TRUE;
}
return FALSE;
}
static void wf_cliprdr_forget_served_file_lists(wfClipboard *clipboard)
{
size_t i;
for (i = 0; i < WF_CLIPRDR_SERVED_FILE_LISTS; i++)
wf_cliprdr_free_served_file_list(&clipboard->served_file_lists[i]);
}
/* Whether a kept list has the current file_names and the same descriptors as dsc, apart
* from the nonce in fgd[0].clsid. */
static BOOL wf_cliprdr_is_same_file_list(wfClipboard *clipboard, const wfServedFileList *list,
const FILEGROUPDESCRIPTORW *dsc, SIZE_T size)
{
SIZE_T nonce_start = offsetof(FILEGROUPDESCRIPTORW, fgd) + offsetof(FILEDESCRIPTORW, clsid);
SIZE_T nonce_end = nonce_start + sizeof(CLSID);
size_t i;
if (!list->file_names || list->nFiles != clipboard->nFiles ||
list->descriptorsSize != size || size < nonce_end)
return FALSE;
for (i = 0; i < list->nFiles; i++)
{
if (!clipboard->file_names[i] || wcscmp(list->file_names[i], clipboard->file_names[i]) != 0)
return FALSE;
}
return memcmp(list->descriptors, dsc, nonce_start) == 0 &&
memcmp(list->descriptors + nonce_end, (const BYTE *)dsc + nonce_end,
size - nonce_end) == 0;
}
/* Puts a nonce in fgd[0].clsid, which peers ignore without FD_CLSID. The list id hashes it,
* so each copy gets its own id even when two copies have identical names, sizes and times
* (the same file in two folders). Re-sending unchanged files keeps their nonce, and id. */
static void wf_cliprdr_stamp_file_list(wfClipboard *clipboard, FILEGROUPDESCRIPTORW *dsc,
SIZE_T size)
{
size_t i;
for (i = 0; i < WF_CLIPRDR_SERVED_FILE_LISTS; i++)
{
if (wf_cliprdr_is_same_file_list(clipboard, &clipboard->served_file_lists[i], dsc, size))
{
dsc->fgd[0].clsid =
((const FILEGROUPDESCRIPTORW *)clipboard->served_file_lists[i].descriptors)
->fgd[0]
.clsid;
return;
}
}
if (FAILED(CoCreateGuid(&dsc->fgd[0].clsid)))
ZeroMemory(&dsc->fgd[0].clsid, sizeof(CLSID));
}
static BOOL wf_cliprdr_copy_file_list(wfClipboard *clipboard, wfServedFileList *list,
const FILEGROUPDESCRIPTORW *dsc, SIZE_T size)
{
size_t i;
list->file_names = (WCHAR **)calloc(clipboard->nFiles, sizeof(WCHAR *));
list->file_sizes = (UINT64 *)calloc(clipboard->nFiles, sizeof(UINT64));
list->descriptors = (BYTE *)malloc(size);
if (!list->file_names || !list->file_sizes || !list->descriptors)
return FALSE;
CopyMemory(list->descriptors, dsc, size);
list->descriptorsSize = size;
list->nFiles = clipboard->nFiles;
for (i = 0; i < clipboard->nFiles; i++)
{
if (!clipboard->file_names[i] ||
!(list->file_names[i] = _wcsdup(clipboard->file_names[i])))
return FALSE;
if (clipboard->fileDescriptor[i])
list->file_sizes[i] = ((UINT64)clipboard->fileDescriptor[i]->nFileSizeHigh << 32) |
clipboard->fileDescriptor[i]->nFileSizeLow;
}
list->id = clipboard->file_list_id;
list->first_file_index = clipboard->first_file_index;
return TRUE;
}
/* One slot per list, shared by every connection it was sent to. A full table evicts the list
* sent least recently, so a list a transfer has just started on is kept. */
static void wf_cliprdr_remember_served_file_list(wfClipboard *clipboard, UINT32 connID,
const FILEGROUPDESCRIPTORW *dsc, SIZE_T size)
{
wfServedFileList *list = NULL;
UINT32 *connIDs;
size_t i;
for (i = 0; i < WF_CLIPRDR_SERVED_FILE_LISTS; i++)
{
if (clipboard->served_file_lists[i].file_names &&
clipboard->served_file_lists[i].id == clipboard->file_list_id)
{
list = &clipboard->served_file_lists[i];
break;
}
}
if (!list)
{
// An empty slot has last_served 0, so it is taken first.
list = &clipboard->served_file_lists[0];
for (i = 1; i < WF_CLIPRDR_SERVED_FILE_LISTS; i++)
{
if (clipboard->served_file_lists[i].last_served < list->last_served)
list = &clipboard->served_file_lists[i];
}
wf_cliprdr_free_served_file_list(list);
if (!wf_cliprdr_copy_file_list(clipboard, list, dsc, size))
{
wf_cliprdr_free_served_file_list(list);
return;
}
}
list->last_served = ++clipboard->served_file_list_seq;
if (wf_cliprdr_served_to(list, connID))
return;
connIDs = (UINT32 *)realloc(list->connIDs, (list->nConnIDs + 1) * sizeof(UINT32));
if (!connIDs)
return;
connIDs[list->nConnIDs++] = connID;
list->connIDs = connIDs;
}
/* Reads like wf_cliprdr_get_file_contents, but only from the file the list was sent with: a
* different size or last-write time means the path now names another file, and the read fails
* rather than continuing a transfer with its bytes. */
static BOOL wf_cliprdr_get_served_file_contents(const WCHAR *file_name, const FILEDESCRIPTORW *dsc,
BYTE *buffer, DWORD positionLow, DWORD positionHigh,
DWORD nRequested, DWORD *puSize)
{
BOOL res = FALSE;
HANDLE hFile;
LARGE_INTEGER size;
LARGE_INTEGER position;
FILETIME lastWrite;
DWORD nGet;
hFile = CreateFileW(file_name, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL | FILE_FLAG_BACKUP_SEMANTICS, NULL);
if (hFile == INVALID_HANDLE_VALUE)
return FALSE;
if (GetFileSizeEx(hFile, &size) &&
(UINT64)size.QuadPart == (((UINT64)dsc->nFileSizeHigh << 32) | dsc->nFileSizeLow) &&
(!(dsc->dwFlags & FD_WRITESTIME) ||
(GetFileTime(hFile, NULL, NULL, &lastWrite) &&
CompareFileTime(&lastWrite, &dsc->ftLastWriteTime) == 0)))
{
position.LowPart = positionLow;
position.HighPart = (LONG)positionHigh;
if (SetFilePointerEx(hFile, position, NULL, FILE_BEGIN) &&
ReadFile(hFile, buffer, nRequested, &nGet, NULL))
{
*puSize = nGet;
res = TRUE;
}
}
CloseHandle(hFile);
return res;
}
/* Serves a request by path from the file list it names, if that list was sent to the same
* connection. An unknown list fails the request rather than falling back to other files. */
static BOOL wf_cliprdr_read_served_file_list(wfClipboard *clipboard,
const CLIPRDR_FILE_CONTENTS_REQUEST *request,
BYTE *data, UINT32 cbRequested, DWORD *puSize)
{
wfServedFileList *list = NULL;
size_t i;
for (i = 0; i < WF_CLIPRDR_SERVED_FILE_LISTS; i++)
{
if (clipboard->served_file_lists[i].file_names &&
clipboard->served_file_lists[i].id == request->clipDataId &&
wf_cliprdr_served_to(&clipboard->served_file_lists[i], request->connID))
{
list = &clipboard->served_file_lists[i];
break;
}
}
if (!list || request->listIndex >= list->nFiles)
return FALSE;
if (request->dwFlags == FILECONTENTS_SIZE)
{
CopyMemory(data, &list->file_sizes[request->listIndex], sizeof(UINT64));
*puSize = sizeof(UINT64);
return TRUE;
}
if (request->dwFlags != FILECONTENTS_RANGE)
return FALSE;
if (clipboard->context->HandleClipboardFiles &&
request->listIndex == (UINT32)list->first_file_index &&
request->nPositionLow == 0 && request->nPositionHigh == 0)
{
clipboard->context->HandleClipboardFiles(request->connID, list->nFiles, list->file_names);
}
return wf_cliprdr_get_served_file_contents(
list->file_names[request->listIndex],
&((const FILEGROUPDESCRIPTORW *)list->descriptors)->fgd[request->listIndex], data,
request->nPositionLow, request->nPositionHigh, cbRequested, puSize);
}
/* path_name has a '\' at the end. e.g. c:\newfolder\, file_name is c:\newfolder\new.txt */
static FILEDESCRIPTORW *wf_cliprdr_get_file_descriptor(WCHAR *file_name, size_t pathLen)
{
@@ -2443,6 +2750,9 @@ static FILEDESCRIPTORW *wf_cliprdr_get_file_descriptor(WCHAR *file_name, size_t
return NULL;
}
// to-do: use `fd->dwFlags = FD_ATTRIBUTES | FD_FILESIZE | FD_WRITESTIME | FD_PROGRESSUI`.
// We keep `fd->dwFlags = FD_ATTRIBUTES | FD_WRITESTIME | FD_PROGRESSUI` for compatibility.
// fd->dwFlags = FD_ATTRIBUTES | FD_FILESIZE | FD_WRITESTIME | FD_PROGRESSUI;
fd->dwFlags = FD_ATTRIBUTES | FD_WRITESTIME | FD_PROGRESSUI;
fd->dwFileAttributes = GetFileAttributesW(file_name);
if (fd->dwFileAttributes == INVALID_FILE_ATTRIBUTES)
@@ -2455,34 +2765,7 @@ static FILEDESCRIPTORW *wf_cliprdr_get_file_descriptor(WCHAR *file_name, size_t
fd->dwFlags &= ~FD_WRITESTIME;
}
// Announce the size in the file list. Without FD_FILESIZE the receiving side cannot
// trust the size fields, so CliprdrStream_New() asks for each file's size with its own
// FILECONTENTS_SIZE request and blocks on the reply. Those requests are made for every
// entry up front, while the shell is inside IDataObject::GetData(), so the cost grows
// with the number of files and not with their size.
//
// GetFileSize() reports failure as INVALID_FILE_SIZE, which cannot be told apart from a
// genuine 4GB-1 file without GetLastError(), and it fails outright on the directory
// handles FILE_FLAG_BACKUP_SEMANTICS lets us open above. A directory gets no size. A
// file whose size cannot be read is rejected rather than sent with the flag off: the
// Unix receiver reads the size fields whether or not the flag is set, for compatibility
// with older Windows senders, and would take the zero for an empty file.
if ((fd->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == 0)
{
LARGE_INTEGER file_size = {0};
if (!GetFileSizeEx(hFile, &file_size) || file_size.QuadPart < 0)
{
CloseHandle(hFile);
free(fd);
return NULL;
}
fd->nFileSizeLow = file_size.LowPart;
fd->nFileSizeHigh = (DWORD)file_size.HighPart;
fd->dwFlags |= FD_FILESIZE;
}
fd->nFileSizeLow = GetFileSize(hFile, &fd->nFileSizeHigh);
if ((wcslen(file_name + pathLen) + 1) > sizeof(fd->cFileName) / sizeof(fd->cFileName[0]))
{
// The file name is too long, which is not a normal case.
@@ -3052,6 +3335,8 @@ wf_cliprdr_server_format_data_request(CliprdrClientContext *context,
STGMEDIUM stg_medium;
DROPFILES *dropFiles;
FILEGROUPDESCRIPTORW *groupDsc;
clipboard->file_list_seq = GetClipboardSequenceNumber();
clipboard->file_list_id = 0;
result = OleGetClipboard(&dataObj);
if (FAILED(result))
@@ -3188,6 +3473,10 @@ wf_cliprdr_server_format_data_request(CliprdrClientContext *context,
buff = groupDsc;
rc = ERROR_SUCCESS;
wf_cliprdr_stamp_file_list(clipboard, groupDsc, size);
clipboard->file_list_id = wf_cliprdr_file_list_id((const BYTE *)groupDsc, size);
wf_cliprdr_remember_served_file_list(clipboard, formatDataRequest->connID, groupDsc,
size);
}
else
{
@@ -3400,6 +3689,18 @@ wf_cliprdr_server_file_contents_request(CliprdrClientContext *context,
return ERROR_INTERNAL_ERROR;
}
// Refuse an unknown request type, or a range over the cap, before allocating for it. Clients
// of this version split larger reads; an older Windows client reading more in one
// IStream::Read fails, as with unix owners.
if ((fileContentsRequest->dwFlags != FILECONTENTS_SIZE &&
fileContentsRequest->dwFlags != FILECONTENTS_RANGE) ||
(fileContentsRequest->dwFlags == FILECONTENTS_RANGE &&
fileContentsRequest->cbRequested > WF_CLIPRDR_MAX_RANGE_READ))
{
ZeroMemory(&vStgMedium, sizeof(STGMEDIUM)); // read at exit
goto exit;
}
// If the clipboard is set by the instance, or the file descriptor is from remote,
// we should not process the request.
// Because this may be the following cases:
@@ -3425,6 +3726,22 @@ wf_cliprdr_server_file_contents_request(CliprdrClientContext *context,
goto exit;
}
// A stream whose list is no longer the current one reads by path from the list it came from.
// Only lists sent to this connection are served.
if (fileContentsRequest->haveClipDataId &&
fileContentsRequest->clipDataId != clipboard->file_list_id)
{
ZeroMemory(&vStgMedium, sizeof(STGMEDIUM)); // read at exit
cbRequested = fileContentsRequest->dwFlags == FILECONTENTS_SIZE
? sizeof(UINT64)
: fileContentsRequest->cbRequested;
pData = (BYTE *)calloc(1, cbRequested);
if (pData && wf_cliprdr_read_served_file_list(clipboard, fileContentsRequest, pData,
cbRequested, &uSize))
rc = CHANNEL_RC_OK;
goto exit;
}
cbRequested = fileContentsRequest->cbRequested;
if (fileContentsRequest->dwFlags == FILECONTENTS_SIZE)
cbRequested = sizeof(UINT64);
@@ -3454,7 +3771,13 @@ wf_cliprdr_server_file_contents_request(CliprdrClientContext *context,
vFormatEtc.lindex = fileContentsRequest->listIndex;
vFormatEtc.ptd = NULL;
if ((uStreamIdStc != fileContentsRequest->streamId) ||
if (GetClipboardSequenceNumber() != clipboard->file_list_seq)
{
// The clipboard changed after the peer got its file list. The live FileContents
// belongs to the new copy, so reading it would splice another file into this one.
bIsStreamFile = FALSE;
}
else if ((uStreamIdStc != fileContentsRequest->streamId) ||
(uConnIdStc != fileContentsRequest->connID) || !pStreamStc)
{
LPENUMFORMATETC pEnumFormatEtc;
@@ -3539,24 +3862,15 @@ wf_cliprdr_server_file_contents_request(CliprdrClientContext *context,
{
if (fileContentsRequest->dwFlags == FILECONTENTS_SIZE)
{
FILEDESCRIPTORW *fd;
if (clipboard->nFiles <= fileContentsRequest->listIndex)
{
rc = ERROR_INTERNAL_ERROR;
goto exit;
}
fd = clipboard->fileDescriptor[fileContentsRequest->listIndex];
// The size fields only mean anything when FD_FILESIZE says so. Answering with
// them regardless would describe an entry whose size could not be read as empty.
if ((fd->dwFlags & FD_FILESIZE) == 0)
{
rc = ERROR_INTERNAL_ERROR;
goto exit;
}
*((UINT32 *)&pData[0]) = fd->nFileSizeLow;
*((UINT32 *)&pData[4]) = fd->nFileSizeHigh;
*((UINT32 *)&pData[0]) =
clipboard->fileDescriptor[fileContentsRequest->listIndex]->nFileSizeLow;
*((UINT32 *)&pData[4]) =
clipboard->fileDescriptor[fileContentsRequest->listIndex]->nFileSizeHigh;
uSize = cbRequested;
}
else if (fileContentsRequest->dwFlags == FILECONTENTS_RANGE)
@@ -3875,6 +4189,7 @@ BOOL wf_cliprdr_uninit(wfClipboard *clipboard, CliprdrClientContext *cliprdr)
CloseHandle(clipboard->req_fevent);
clear_file_array(clipboard);
wf_cliprdr_forget_served_file_lists(clipboard);
clear_format_map(clipboard);
free(clipboard->format_mappings);
return TRUE;
+30 -4
View File
@@ -39,6 +39,17 @@ fn mouse_event(flags: u32, data: u32, dx: i32, dy: i32) -> DWORD {
unsafe { SendInput(1, &mut input as LPINPUT, size_of::<INPUT>() as c_int) }
}
// `v` comes from the remote peer unchecked, so scale in i64 to avoid overflow, and clamp to
// the 0..=65535 range MOUSEEVENTF_ABSOLUTE takes.
// `extent` is 0 when the virtual screen metrics are unavailable.
fn to_absolute(v: i32, origin: i32, extent: i32) -> Option<i32> {
if extent <= 0 {
return None;
}
let abs = (v as i64 - origin as i64) * 65535 / extent as i64;
Some(abs.clamp(0, 65535) as i32)
}
fn keybd_event(mut flags: u32, vk: u16, scan: u16) -> DWORD {
let mut scan = scan;
unsafe {
@@ -126,13 +137,28 @@ impl MouseControllable for Enigo {
}
fn mouse_move_to(&mut self, x: i32, y: i32) {
let (left, top, width, height) = unsafe {
(
GetSystemMetrics(SM_XVIRTUALSCREEN),
GetSystemMetrics(SM_YVIRTUALSCREEN),
GetSystemMetrics(SM_CXVIRTUALSCREEN),
GetSystemMetrics(SM_CYVIRTUALSCREEN),
)
};
let (Some(dx), Some(dy)) = (to_absolute(x, left, width), to_absolute(y, top, height))
else {
hbb_common::throttled_log!(
std::time::Duration::from_secs(60),
warn,
"mouse_move_to skipped: virtual screen size unavailable"
);
return;
};
mouse_event(
MOUSEEVENTF_MOVE | MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_VIRTUALDESK,
0,
(x - unsafe { GetSystemMetrics(SM_XVIRTUALSCREEN) }) * 65535
/ unsafe { GetSystemMetrics(SM_CXVIRTUALSCREEN) },
(y - unsafe { GetSystemMetrics(SM_YVIRTUALSCREEN) }) * 65535
/ unsafe { GetSystemMetrics(SM_CYVIRTUALSCREEN) },
dx,
dy,
);
}
+2 -2
View File
@@ -14,7 +14,7 @@ wayland = ["gstreamer", "gstreamer-app", "gstreamer-video", "dbus", "tracing", "
# `drm` is a pure runtime-dlopen backend: rustdesk loads `libdrmtap.so.0` at runtime (`drmtap_dl.rs`)
# and NEVER link-time links it, so the graceful PipeWire fallback when the .so or EGL is absent is
# preserved and the drm build pulls in no libdrm/seccomp/cap/EGL link-time deps. The .so is pinned by
# `DRMTAP_SHA` in build.py, which fetches that exact commit (libdrmtap v0.5.4). We deliberately do
# `DRMTAP_SHA` in build.py, which fetches that exact commit (libdrmtap v0.5.6). We deliberately do
# NOT depend on the `libdrmtap-sys` crate: its build.rs statically compiles the whole libdrmtap C tree
# and a CAP_SYS_ADMIN helper and emits `-ldrm -lseccomp -lcap`, which would defeat the dlopen model.
# Depends on `wayland`: the three drm modules live inside the `#[cfg(feature = "wayland")]` arm of
@@ -38,7 +38,7 @@ serde = {version="1.0", features=["derive"]}
[dependencies.winapi]
version = "0.3"
default-features = true
features = ["dxgi", "dxgi1_2", "dxgi1_5", "d3d11", "winuser", "winerror", "errhandlingapi", "libloaderapi"]
features = ["dxgi", "dxgi1_2", "dxgi1_5", "dxgi1_6", "d3d11", "winuser", "winerror", "errhandlingapi", "libloaderapi"]
[target.'cfg(target_os = "macos")'.dependencies]
block = "0.1"
+535 -32
View File
@@ -8,6 +8,7 @@ use hbb_common::log;
use std::ffi::CString;
use std::io;
use std::os::fd::{FromRawFd, OwnedFd};
use std::os::raw::c_int;
// Trust-boundary limits and formats `drm_render` (the unprivileged converter) imports: two copies that drift apart would weaken one side.
// 16384 covers 8K+ with headroom; anything larger is rejected as a bogus/hostile geometry.
@@ -29,9 +30,274 @@ pub struct CursorSnapshot {
pub height: u32,
pub hotx: i32,
pub hoty: i32,
/// Whether the hotspot came from the plane's HOTSPOT_X/Y properties. Those exist on
/// para-virtualised drivers only; on bare metal it is `infer_hotspot`'s guess, made on the
/// bitmap as scanned out - which on a rotated output is the compositor's pre-rotated sprite,
/// so the consumer must re-guess on the upright one.
pub hot_measured: bool,
pub colors: Vec<u8>,
}
/// Fold everything that makes a cursor a DIFFERENT cursor into its id.
///
/// The producer dedupes by comparing this against the last one it sent, so anything left out is
/// something a change in which the consumer will never be told about. Geometry and the hotspot are
/// the obvious ones: identical pixels at a new size or hotspot are a new shape.
///
/// `hot_measured` belongs here too, and that is less obvious. It is not metadata about the cursor,
/// it selects what the consumer DOES with it: false means rotate the bitmap and re-infer a
/// hotspot, true means map the supplied point. So a sample whose pixels and `(0, 0)` hotspot are
/// unchanged but whose provenance flipped is a different cursor as far as the client is concerned,
/// and without this it would be deduped away and never sent.
fn cursor_id(hash: u64, width: u32, height: u32, hotx: i32, hoty: i32, hot_measured: bool) -> u64 {
let mut id = hash;
for v in [
width as u64,
height as u64,
hotx as u32 as u64,
hoty as u32 as u64,
hot_measured as u64,
] {
id ^= v;
id = id.wrapping_mul(1099511628211);
}
id
}
/// Encodes a provenance answer for the one-shot log below. -1 is "nothing reported yet".
fn provenance_code(answered: Option<bool>) -> i8 {
match answered {
None => 0,
Some(false) => 1,
Some(true) => 2,
}
}
/// Whether this sample's provenance is worth a log line, given what was last reported.
///
/// Its own function because the obvious version of this is a line per cursor read, and a cursor is
/// read far more often than it changes. A per-sample log here was a real defect in libdrmtap for
/// the same reason. So: the first sample of a run, and thereafter only a genuine change of state.
fn provenance_is_news(last: i8, now: i8) -> bool {
last != now
}
impl DrmReader {
/// Say once, and again only if it changes, where the hotspot is coming from. Without this the
/// three states are indistinguishable on a running box, which makes the decision unverifiable
/// anywhere but a unit test.
fn note_hotspot_provenance(&mut self, answered: Option<bool>, hot_measured: bool) {
let now = provenance_code(answered);
let last = std::mem::replace(&mut self.last_provenance, now);
if !provenance_is_news(last, now) {
return;
}
match answered {
Some(true) => log::info!(
"drm: cursor hotspot provenance: the driver published HOTSPOT_X/Y, using its value"
),
Some(false) => log::info!(
"drm: cursor hotspot provenance: the plane exposes no HOTSPOT_X/Y, inferring the \
hotspot from the bitmap"
),
None => log::info!(
"drm: cursor hotspot provenance: unavailable (libdrmtap older than 0.5.6, or a \
pre-0.5.6 privileged helper); falling back to the coordinate heuristic, which says \
hot_measured={hot_measured}"
),
}
}
}
/// Whether `hot_x`/`hot_y` are the driver's answer rather than a guess.
///
/// `answered` is what `drmtap_cursor_hotspot_valid` said: `Some(v)` when it answered, `None` when
/// the symbol is absent (a library older than 0.5.6) or it reported that nothing recorded an
/// answer for this sample.
///
/// When it answered, that is the answer, full stop - including `Some(true)` on a `(0, 0)` hotspot,
/// which is the whole reason the entry point exists: a para-virtualized driver really can put the
/// hotspot at the top-left corner, and the coordinates alone cannot tell that apart from a plane
/// that exposes no HOTSPOT_X/Y at all. When it could not answer, fall back to the old test. That
/// test is wrong in both directions, but it is what this code did before, and it keeps a deployed
/// older `.so` behaving exactly as it used to instead of changing under it.
fn hot_measured_from(answered: Option<bool>, hot_x: i32, hot_y: i32) -> bool {
match answered {
Some(measured) => measured,
None => hot_x != 0 || hot_y != 0,
}
}
/// A mirror has to agree on this many of every 100 pixels of the union to count as symmetry.
/// Swept against master over two theme versions: below 86 the rule starts moving shapes whose
/// corner guess was already right (`grabbing`), and from 92 up the directional cursors of the
/// older theme stop being recognised and regress. 86 to 91 is the interval that holds on both,
/// so this sits in the middle of it.
const MIRROR_AGREEMENT_PERCENT: u64 = 88;
/// Guess the click point of a cursor bitmap, for the drivers that publish no hotspot.
///
/// Three facts drive it, in order of how much of the shape they read.
///
/// A shape that is mirror symmetric about one of the box's mid-lines has no distinguished end on
/// that axis: a crosshair, an I-beam, a two-headed resize arrow. On such an axis the click point
/// is the middle.
///
/// A shape that mirrors onto itself only under a half turn or about a DIAGONAL is a two-headed or
/// corner resize cursor. Those are a pointer plus the marker of the edge being resized, and the
/// theme puts the click point on that marker, which is the heavier end. The heavier end is also
/// the only thing that separates `e-resize` from `w-resize`: they are the same picture reflected.
///
/// Everything else keeps the top-left corner of the opaque box, because cursors are DRAWN
/// pointing up and to the left, so that corner is where an arrow's tip is. That is a fact about
/// the sprite in its own upright frame, and the reason this guess is only meaningful when taken
/// there rather than on a sprite the compositor pre-rotated.
///
/// Measured against the hotspots the theme declares, which is the value a compositor programs
/// into HOTSPOT_X/Y where the property exists, and against what master delivers over the angles
/// master handles (0, 90, 270). adwaita-icon-theme 50 at 24 px: mean error per shape 12.08 px
/// down to 4.20, better on 83 of the 105 (shape, angle) cases and worse on 4. The same holds at
/// 48 px and on adwaita-icon-theme 46.
///
/// Two shapes stay further out than master and no bitmap rule reaches them: `help`, whose click
/// point the theme puts on the dot of its question mark, and `alias` by half a pixel. That is why
/// a hotspot the driver publishes is always preferred to this, and why rustdesk#16122 recovers it
/// exactly from the injected pointer instead of guessing.
pub fn infer_hotspot(rgba: &[u8], w: usize, h: usize) -> (i32, i32) {
let (mut minx, mut miny, mut maxx, mut maxy) = (w as i32, h as i32, -1i32, -1i32);
for (i, px) in rgba.chunks_exact(4).take(w * h).enumerate() {
if px[3] >= 128 {
let (x, y) = ((i % w) as i32, (i / w) as i32);
minx = minx.min(x);
maxx = maxx.max(x);
miny = miny.min(y);
maxy = maxy.max(y);
}
}
if maxx < minx || maxy < miny {
return (0, 0);
}
let (bw, bh) = (maxx - minx + 1, maxy - miny + 1);
let (cx, cy) = ((minx + maxx) / 2, (miny + maxy) / 2);
// An elongated box keeps its centre whichever way it lies (rustdesk#16242): a bar has no
// corner to speak of. Kept ahead of the mirror test so it still covers an elongated shape
// that is NOT symmetric, which the theme happens not to contain but a custom cursor can.
if bh > bw * 2 || bw > bh * 2 {
return (cx, cy);
}
let opaque = |x: i32, y: i32| {
rgba.get((y as usize * w + x as usize) * 4 + 3)
.is_some_and(|&a| a >= 128)
};
let agrees = |i: u64, u: u64| u == 0 || i * 100 >= u * MIRROR_AGREEMENT_PERCENT;
// One pass over the opaque box, comparing it with its own three mirrors, and the mass of each
// half while we are here.
let (mut ix, mut ux) = (0u64, 0u64);
let (mut iy, mut uy) = (0u64, 0u64);
let (mut ih, mut uh) = (0u64, 0u64);
let (mut left, mut right, mut top, mut bottom) = (0u64, 0u64, 0u64, 0u64);
let (half_w, half_h) = (bw / 2, bh / 2);
for y in miny..=maxy {
for x in minx..=maxx {
let (fx, fy) = (maxx - (x - minx), maxy - (y - miny));
let here = opaque(x, y);
for (other, (i, u)) in [
(opaque(fx, y), (&mut ix, &mut ux)),
(opaque(x, fy), (&mut iy, &mut uy)),
(opaque(fx, fy), (&mut ih, &mut uh)),
] {
*i += u64::from(here && other);
*u += u64::from(here || other);
}
if here {
if x - minx < half_w {
left += 1;
} else if maxx - x < half_w {
right += 1;
}
if y - miny < half_h {
top += 1;
} else if maxy - y < half_h {
bottom += 1;
}
}
}
}
// Symmetric under a half turn and the centre is the only point the shape cannot tell from
// itself, whichever the per-axis answers are: a two-headed diagonal arrow mirrors to the
// other diagonal on each axis alone, so neither axis reads as symmetric.
if agrees(ih, uh) {
return (cx, cy);
}
let diagonal = mirrors_about_a_diagonal(&opaque, minx, miny, bw, bh, &agrees);
// An axis is DIRECTIONAL when the shape is a pointer plus an edge marker rather than a plain
// arrow: the perpendicular axis mirrors (the n/e/s/w resize cursors), or the shape mirrors
// about a diagonal (the corner ones). The marker is the end the click point belongs to, and
// it is the heavier end, which is the only thing that tells `e-resize` from `w-resize` - they
// are the same picture reflected. Everything else keeps the up-left corner.
let side = |heavier_is_max: bool, lo: i32, hi: i32| if heavier_is_max { hi } else { lo };
(
if agrees(ix, ux) {
cx
} else if agrees(iy, uy) || diagonal {
side(right > left, minx, maxx)
} else {
minx
},
if agrees(iy, uy) {
cy
} else if agrees(ix, ux) || diagonal {
side(bottom > top, miny, maxy)
} else {
miny
},
)
}
/// Whether the opaque box mirrors onto itself about either of its diagonals.
///
/// A diagonal reflection of a `bw x bh` box is a `bh x bw` box, so the two can only be compared
/// inside a square, and where the box is not square the answer depends on where in that square it
/// is placed: the corner resize cursors are drawn against one corner, and padding away from that
/// corner moves the shape off the diagonal it is symmetric about. `ne-resize` scores 0.62 anchored
/// top-left and 0.98 anchored bottom-right; `nw-resize` is the other way round. So both anchorings
/// are tried and the best answer wins, which is what "the shape is symmetric" means once the
/// reflection is allowed to be shifted back into place.
fn mirrors_about_a_diagonal(
opaque: &impl Fn(i32, i32) -> bool,
minx: i32,
miny: i32,
bw: i32,
bh: i32,
agrees: &impl Fn(u64, u64) -> bool,
) -> bool {
let k = bw.max(bh);
for (dx, dy) in [(0, 0), (k - bw, k - bh)] {
// The box placed at (dx, dy) inside a k x k square, empty everywhere else.
let cell = |r: i32, c: i32| {
let (x, y) = (c - dx, r - dy);
(0..bw).contains(&x) && (0..bh).contains(&y) && opaque(minx + x, miny + y)
};
let (mut id, mut ud, mut ia, mut ua) = (0u64, 0u64, 0u64, 0u64);
for r in 0..k {
for c in 0..k {
let here = cell(r, c);
for (other, (i, u)) in [
(cell(c, r), (&mut id, &mut ud)),
(cell(k - 1 - c, k - 1 - r), (&mut ia, &mut ua)),
] {
*i += u64::from(here && other);
*u += u64::from(here || other);
}
}
}
if agrees(id, ud) || agrees(ia, ua) {
return true;
}
}
false
}
/// One enumerated DRM display, physical geometry only (the server overlays the Wayland logical origin/scale where it can match one).
pub struct DisplaySnapshot {
pub name: String,
@@ -101,6 +367,13 @@ pub struct DrmReader {
lib: &'static DrmtapLib,
ctx: *mut drmtap_ctx,
buf: Vec<u8>,
/// Last provenance reported by THIS reader, for the one-shot log. Per reader and not global:
/// several readers run at once, one per captured display, and their provenance can legitimately
/// differ and be stable -- a virtio-gpu output publishes HOTSPOT_X/Y while an i915 one on the
/// same host does not. A single global would read those two steady streams as an endless
/// alternation and log on every sample, which is the per-frame logging this was written to
/// avoid. -1 is "nothing reported yet".
last_provenance: i8,
}
impl DrmReader {
@@ -134,6 +407,7 @@ impl DrmReader {
return None;
}
Some(DrmReader {
last_provenance: -1,
lib,
ctx,
buf: Vec::new(),
@@ -363,6 +637,7 @@ impl DrmReader {
height: 1,
hotx: 0,
hoty: 0,
hot_measured: false,
colors: vec![0, 0, 0, 0],
})
} else if !c.pixels.is_null()
@@ -376,53 +651,45 @@ impl DrmReader {
let src = std::slice::from_raw_parts(c.pixels, n);
let mut hash: u64 = 1469598103934665603;
let mut colors = Vec::with_capacity(n * 4);
let (mut minx, mut miny, mut maxx, mut maxy) = (cw, ch, -1i32, -1i32);
for (i, &p) in src.iter().enumerate() {
let a = ((p >> 24) & 0xff) as u8;
let r = ((p >> 16) & 0xff) as u8;
let g = ((p >> 8) & 0xff) as u8;
let b = (p & 0xff) as u8;
colors.push(r);
colors.push(g);
colors.push(b);
colors.push(a);
for &p in src.iter() {
colors.push(((p >> 16) & 0xff) as u8);
colors.push(((p >> 8) & 0xff) as u8);
colors.push((p & 0xff) as u8);
colors.push(((p >> 24) & 0xff) as u8);
hash ^= p as u64;
hash = hash.wrapping_mul(1099511628211);
if a >= 128 {
let x = (i as i32) % cw;
let y = (i as i32) / cw;
if x < minx { minx = x; }
if x > maxx { maxx = x; }
if y < miny { miny = y; }
if y > maxy { maxy = y; }
}
}
let (hotx, hoty) = if c.hot_x != 0 || c.hot_y != 0 {
// Ask the library where the hotspot came from instead of guessing from the
// coordinates. `hot_x/hot_y == (0, 0)` means two opposite things - the plane
// exposes no HOTSPOT_X/Y (every bare-metal driver), or it exposes them and the
// driver's answer IS the top-left corner - and the old test below cannot separate
// them: it overrides a real (0, 0) measurement with a guess from the bitmap, and
// on a driver without the properties it would trust a hotspot nobody published.
// Asked BEFORE cursor_release, which is what owns this sample.
let answered = self.lib.cursor_hotspot_valid.and_then(|f| {
let mut valid: c_int = 0;
// 0 = answered; -ENOTSUP = nothing recorded an answer for this sample, which
// is what a cursor read through a pre-0.5.6 privileged helper produces.
(f(&c, &mut valid) == 0).then(|| valid != 0)
});
let hot_measured = hot_measured_from(answered, c.hot_x, c.hot_y);
self.note_hotspot_provenance(answered, hot_measured);
let (hotx, hoty) = if hot_measured {
(c.hot_x, c.hot_y)
} else if maxx >= minx && maxy >= miny {
let (bw, bh) = (maxx - minx + 1, maxy - miny + 1);
if bh > bw * 2 {
((minx + maxx) / 2, (miny + maxy) / 2)
} else {
(minx, miny)
}
} else {
(0, 0)
infer_hotspot(&colors, cw as usize, ch as usize)
};
// Fold geometry + hotspot into the id: identical pixels with a changed size or
// hotspot must count as a new shape, otherwise drm_capture_worker suppresses the
// update (it dedupes by id) and the client keeps rendering the stale cursor.
let mut id = hash;
for v in [cw as u32 as u64, ch as u32 as u64, hotx as u32 as u64, hoty as u32 as u64] {
id ^= v;
id = id.wrapping_mul(1099511628211);
}
let id = cursor_id(hash, cw as u32, ch as u32, hotx, hoty, hot_measured);
Some(CursorSnapshot {
id,
width: cw as u32,
height: ch as u32,
hotx,
hoty,
hot_measured,
colors,
})
} else {
@@ -475,3 +742,239 @@ impl Drop for DrmReader {
}
}
}
#[cfg(test)]
mod hotspot_provenance_tests {
use super::{cursor_id, hot_measured_from, provenance_code, provenance_is_news};
/// The log this makes observable is one line per CHANGE, not one per cursor read. A cursor is
/// read far more often than its provenance changes, and a per-sample line here would be the
/// same defect libdrmtap already had once.
#[test]
fn provenance_is_logged_once_and_then_only_on_a_change() {
let (none, guessed, measured) = (
provenance_code(None),
provenance_code(Some(false)),
provenance_code(Some(true)),
);
assert_ne!(none, guessed);
assert_ne!(guessed, measured);
assert_ne!(none, measured);
// First sample of a run: -1 is the unset sentinel, so anything is news.
assert!(provenance_is_news(-1, measured));
// The same state again is not.
assert!(!provenance_is_news(measured, measured));
assert!(!provenance_is_news(guessed, guessed));
// A real transition is.
assert!(provenance_is_news(guessed, measured));
assert!(provenance_is_news(measured, none));
}
/// The dedup key has to move when the provenance does, or the consumer is never told that the
/// same picture now means something different. This is the transition that produces it: the
/// properties become readable, the driver's answer is the corner, and the bitmap is unchanged.
#[test]
fn provenance_changes_the_cursor_identity() {
let guessed = cursor_id(0xabc, 24, 24, 0, 0, false);
let measured = cursor_id(0xabc, 24, 24, 0, 0, true);
assert_ne!(
guessed, measured,
"same pixels, same (0, 0), different meaning: the producer must not dedupe this away"
);
// And the pre-existing parts still count, so this did not trade one blind spot for another.
assert_ne!(cursor_id(0xabc, 24, 24, 0, 0, true), cursor_id(0xabc, 32, 24, 0, 0, true));
assert_ne!(cursor_id(0xabc, 24, 24, 0, 0, true), cursor_id(0xabc, 24, 24, 1, 0, true));
assert_ne!(cursor_id(0xabc, 24, 24, 0, 0, true), cursor_id(0xdef, 24, 24, 0, 0, true));
}
/// The case the whole entry point exists for, and the one the old heuristic got backwards: a
/// para-virtualized driver that really publishes the hotspot at the image's top-left corner.
/// `(0, 0)` measured is still measured, and re-inferring one from the bitmap would move a
/// cursor the driver had already placed.
#[test]
fn a_measured_zero_hotspot_is_measured() {
assert!(hot_measured_from(Some(true), 0, 0));
}
/// And the mirror: when the library says it was NOT measured, that is the answer even if the
/// coordinates happen to be non-zero. The old test would have trusted them.
#[test]
fn the_librarys_no_beats_the_coordinates() {
assert!(!hot_measured_from(Some(false), 12, 11));
assert!(!hot_measured_from(Some(false), 0, 0));
}
/// No answer available: either the symbol is absent (a library older than 0.5.6) or nothing
/// recorded one for this sample (a cursor read through an older privileged helper). Neither
/// is "it was a guess", so the pre-existing behaviour is kept rather than resolved either way
/// -- an older deployed .so must keep behaving as it used to.
#[test]
fn without_an_answer_the_old_heuristic_stands() {
assert!(!hot_measured_from(None, 0, 0));
assert!(hot_measured_from(None, 12, 11));
assert!(hot_measured_from(None, 0, 5));
}
}
#[cfg(test)]
mod hotspot_guess_tests {
use super::infer_hotspot;
/// A sprite from an ASCII picture: `#` is opaque, anything else transparent. Written this way
/// because every case here is about a SHAPE, and a shape is unreadable as a byte array.
fn sprite(rows: &[&str]) -> (Vec<u8>, usize, usize) {
let (h, w) = (rows.len(), rows[0].len());
let mut px = vec![0u8; w * h * 4];
for (y, row) in rows.iter().enumerate() {
assert_eq!(row.len(), w, "ragged picture");
for (x, c) in row.bytes().enumerate() {
if c == b'#' {
px[(y * w + x) * 4 + 3] = 255;
}
}
}
(px, w, h)
}
/// An arrow keeps the top-left corner of its box. Cursors are drawn pointing up and left, so
/// that corner IS the tip - and it is a fact about the sprite upright, which is why the
/// consumer re-takes this guess after turning a rotated sprite back.
#[test]
fn an_arrow_points_at_the_corner_of_its_box() {
let (px, w, h) = sprite(&[
".........",
".#.......",
".##......",
".###.....",
".####....",
".#####...",
".###.....",
".#..##...",
"......##.",
]);
assert_eq!(infer_hotspot(&px, w, h), (1, 1));
}
/// A shape that mirrors onto itself about the box's mid-lines has no tip to point with, so
/// the corner names nothing and the middle is the only answer the shape supports. This is the
/// crosshair/cell/resize family, 17 of the installed theme's 35 shapes.
#[test]
fn a_symmetric_shape_is_held_by_its_middle() {
let (px, w, h) = sprite(&[
"....#....",
"....#....",
"....#....",
"....#....",
"#########",
"....#....",
"....#....",
"....#....",
"....#....",
]);
assert_eq!(infer_hotspot(&px, w, h), (4, 4));
}
/// Each axis is decided by its OWN mirror. This shape is symmetric left-to-right and not
/// top-to-bottom, which is the single-direction resize family: the click point is centred
/// across the axis that mirrors and stays at the edge on the axis that does not.
#[test]
fn one_symmetric_axis_centres_that_axis_only() {
let (px, w, h) = sprite(&[
"....#....",
"...###...",
"..#####..",
".#######.",
"....#....",
"....#....",
"....#....",
"....#....",
"....#....",
]);
assert_eq!(infer_hotspot(&px, w, h), (4, 0));
}
/// A two-headed DIAGONAL arrow mirrors onto the other diagonal about either axis alone, so
/// neither axis reads as symmetric - and it is still a shape with no tip. The half turn is
/// what catches it.
#[test]
fn a_diagonal_two_headed_arrow_is_held_by_its_middle_too() {
let (px, w, h) = sprite(&[
"###......",
"##.......",
"#.#......",
"...#.....",
"....#....",
".....#...",
"......#.#",
".......##",
"......###",
]);
let (hx, hy) = infer_hotspot(&px, w, h);
assert_eq!((hx, hy), (4, 4), "a half turn maps this shape onto itself");
}
/// A single-direction resize cursor is an arrow plus the bar of the edge it resizes, and the
/// theme puts the click point on the BAR. The bar is the heavy end, and it is the only thing
/// that separates `e-resize` from `w-resize`: they are the same picture reflected, so a rule
/// that always took the up-left corner had to be wrong for one of the two.
#[test]
fn a_directional_resize_cursor_is_held_by_its_bar() {
let (px, w, h) = sprite(&[
"......####",
"..##..####",
".###..####",
"####..####",
".###..####",
"..##..####",
"......####",
]);
assert_eq!(infer_hotspot(&px, w, h), (9, 3));
// The mirror image has to answer the other side, or the rule is not reading the shape.
let (px, w, h) = sprite(&[
"####......",
"####..##..",
"####..###.",
"####..####",
"####..###.",
"####..##..",
"####......",
]);
assert_eq!(infer_hotspot(&px, w, h), (0, 3));
}
/// A corner resize cursor is a bracket hugging one corner, and it mirrors onto itself about a
/// DIAGONAL rather than about either axis, so neither per-axis test sees it. The click point
/// is the inner corner of the bracket, which is the heavy end on both axes.
///
/// A real one's box is usually not square, and a diagonal reflection only lines up inside a
/// square, so which corner of that square the box is placed against decides the answer:
/// `ne-resize` scores 0.62 anchored one way and 0.98 the other, and `nw-resize` is the
/// reverse. Both anchorings are therefore tried. That case cannot be built as a small
/// picture - a non-square box can never be exactly diagonal-symmetric - so it is covered by
/// the theme corpus instead, where dropping the second anchoring sends `ne-resize` back past
/// master.
#[test]
fn a_corner_bracket_is_held_by_its_inner_corner() {
let (px, w, h) = sprite(&[
".....##", ".....##", ".....##", ".....##", ".....##", "#######", "#######",
]);
assert_eq!(infer_hotspot(&px, w, h), (6, 6));
}
/// The elongation rule stays ahead of the mirror test, so a bar that is NOT symmetric still
/// keeps its centre. Nothing in the installed theme is shaped like this - its two I-beams are
/// both symmetric - but a custom cursor can be, and this is the rustdesk#16242 round-one fix.
#[test]
fn an_elongated_shape_keeps_its_centre_even_when_it_is_lopsided() {
let (px, w, h) = sprite(&["##########.", "#####......", "##########."]);
assert_eq!(infer_hotspot(&px, w, h), (4, 1));
}
/// Nothing opaque is not a shape, and must not read as a box at the origin with a hotspot in
/// the middle of it.
#[test]
fn a_blank_sprite_has_no_hotspot_to_guess() {
let (px, w, h) = sprite(&["...", "...", "..."]);
assert_eq!(infer_hotspot(&px, w, h), (0, 0));
}
}
+25
View File
@@ -127,6 +127,12 @@ type FnGrabMapped = unsafe extern "C" fn(*mut drmtap_ctx, *mut drmtap_frame_info
type FnFrameRelease = unsafe extern "C" fn(*mut drmtap_ctx, *mut drmtap_frame_info);
type FnGetCursor = unsafe extern "C" fn(*mut drmtap_ctx, *mut drmtap_cursor_info) -> c_int;
type FnCursorRelease = unsafe extern "C" fn(*mut drmtap_ctx, *mut drmtap_cursor_info);
/// `drmtap_cursor_hotspot_valid`, added in libdrmtap 0.5.6. Answers, for the sample in hand,
/// whether `hot_x`/`hot_y` were read from the driver's HOTSPOT_X/Y plane properties: 0 with
/// `*valid` set, `-EINVAL` on a null argument, and `-ENOTSUP` when nothing recorded an answer,
/// which is what a cursor read through an older privileged helper produces.
type FnCursorHotspotValid =
unsafe extern "C" fn(*const drmtap_cursor_info, *mut c_int) -> c_int;
// Split-capture entry points (libdrmtap >= 0.4.10), required: `grab_desc` runs on the privileged
// export side, `open_render`/`convert_dmabuf` on the unprivileged converter side.
type FnGrabDesc =
@@ -148,6 +154,10 @@ pub struct DrmtapLib {
pub frame_release: FnFrameRelease,
pub get_cursor: FnGetCursor,
pub cursor_release: FnCursorRelease,
/// Optional: it only exists from libdrmtap 0.5.6. Absent means the library cannot say where a
/// hotspot came from, NOT that it was a guess; `drm_reader` keeps the old heuristic for that
/// case and nothing else changes.
pub cursor_hotspot_valid: Option<FnCursorHotspotValid>,
pub grab_desc: FnGrabDesc,
pub open_render: FnOpenRender,
pub convert_dmabuf: FnConvertDmabuf,
@@ -278,6 +288,8 @@ impl DrmtapLib {
};
let render_node: Option<FnRenderNode> =
lib.get(b"drmtap_render_node").ok().map(|s| *s);
let cursor_hotspot_valid: Option<FnCursorHotspotValid> =
lib.get(b"drmtap_cursor_hotspot_valid").ok().map(|s| *s);
// Log the load only now that every required symbol resolved: this fn still returns None on a missing one.
let loaded_from = real
.as_ref()
@@ -309,6 +321,18 @@ impl DrmtapLib {
points at and remove any leftover libdrmtap.so.0* beside it. {effect}"
);
}
// Same shape as the check above, and for the same reason: a library that REPORTS a
// version which exports the symbol and then does not have it is a stale or
// hand-substituted object, and saying so beats silently taking the legacy path.
if (minor, patch) >= (5, 6) && cursor_hotspot_valid.is_none() {
log::warn!(
"libdrmtap at {loaded_from} reports v{major}.{minor}.{patch} but is missing \
drmtap_cursor_hotspot_valid: it is a stale or pre-release build. Check what \
the soname symlink points at. Cursor hotspot provenance falls back to \
guessing from the coordinates, which cannot tell an absent HOTSPOT_X/Y from \
a driver that really puts the hotspot at (0, 0)."
);
}
Some(DrmtapLib {
_lib: lib,
open,
@@ -319,6 +343,7 @@ impl DrmtapLib {
frame_release,
get_cursor,
cursor_release,
cursor_hotspot_valid,
grab_desc,
open_render,
convert_dmabuf,
+5 -2
View File
@@ -118,12 +118,15 @@ impl EncoderApi for VRamEncoder {
});
}
if frames.len() > 0 {
// This kind of problem is occurred after a period of time when using AMD encoding,
// This kind of problem is occurred after a period of time when using the AMD SDK,
// the encoding length is fixed at about 40, and the picture is still
const MIN_BAD_LEN: usize = 100;
const MAX_BAD_COUNTER: usize = 30;
let this_frame_len = frames[0].data.len();
if this_frame_len < MIN_BAD_LEN && this_frame_len == self.last_frame_len {
if self.ctx.f.driver == Driver::AMF
&& this_frame_len < MIN_BAD_LEN
&& this_frame_len == self.last_frame_len
{
self.same_bad_len_counter += 1;
if self.same_bad_len_counter >= MAX_BAD_COUNTER {
log::info!(
+629
View File
@@ -0,0 +1,629 @@
//! HDR desktop -> SDR normalization for Desktop Duplication frames.
//!
//! With HDR enabled Windows composes the desktop as linear scRGB in
//! R16G16B16A16_FLOAT, and SDR "white" sits at the user's SDR content
//! brightness (DISPLAYCONFIG_SDR_WHITE_LEVEL) rather than at 1.0. The legacy
//! DuplicateOutput converts that to BGRA8 by clipping, which is the washed-out
//! picture reported for HDR hosts. This pass divides by the SDR white level,
//! clamps, and applies the sRGB transfer, so SDR content comes out exactly as
//! it would from an SDR desktop.
//!
//! It is a normalization, not a tone map: anything brighter than SDR white
//! (HDR video, HDR games) clips to white on the SDR viewer, where the local
//! HDR display would show it brighter than white. A roll-off would have to
//! move SDR white below 1.0 to make headroom, trading the accuracy of the SDR
//! content this pass exists for, so it is deliberately not done.
//!
//! Windows 11 22H2 also composes Advanced Color SDR (WCG) desktops in FP16,
//! but there 1.0 is the display's reference white rather than 80 nits and no
//! SDR white level applies. IDXGIOutput6 tells the two apart, and for a
//! non-HDR output the pass only applies the scRGB -> sRGB transfer.
//!
//! The conversion is automatic and stays on the controlled side on purpose:
//! the controller renders through Flutter external textures, which are 8-bit
//! on every desktop platform, so there is nothing to gain from sending HDR.
//! Real HDR pass-through, if the renderer ever supports it, should follow the
//! Sunshine/Moonlight pattern instead: an `hdr` capability bit advertised by
//! the controller behind an explicit user toggle, negotiated like i444.
use super::ComPtr;
use hbb_common::log;
use std::{
io, mem, ptr,
sync::{atomic::AtomicBool, OnceLock},
time::{Duration, Instant},
};
use winapi::{
ctypes::c_void,
shared::{
basetsd::SIZE_T,
dxgi::{CreateDXGIFactory1, IDXGIFactory1, IID_IDXGIFactory1, DXGI_OUTPUT_DESC},
dxgi1_2::IDXGIOutput1,
dxgi1_6::{IDXGIOutput6, IID_IDXGIOutput6, DXGI_OUTPUT_DESC1},
dxgiformat::DXGI_FORMAT_B8G8R8A8_UNORM,
dxgitype::{DXGI_COLOR_SPACE_RGB_FULL_G2084_NONE_P2020, DXGI_SAMPLE_DESC},
minwindef::{FALSE, LPCVOID, UINT, ULONG},
ntdef::{LONG, LPCSTR, WCHAR},
winerror::S_OK,
},
um::{
d3d11::*,
d3dcommon::{ID3DBlob, ID3DInclude, D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST, D3D_SHADER_MACRO},
libloaderapi::{GetProcAddress, LoadLibraryExW, LOAD_LIBRARY_SEARCH_SYSTEM32},
unknwnbase::IUnknown,
wingdi::{
DISPLAYCONFIG_DEVICE_INFO_GET_SOURCE_NAME, DISPLAYCONFIG_DEVICE_INFO_HEADER,
DISPLAYCONFIG_MODE_INFO, DISPLAYCONFIG_PATH_INFO, DISPLAYCONFIG_SOURCE_DEVICE_NAME,
DISPLAYCONFIG_TOPOLOGY_ID,
},
winnt::HRESULT,
},
};
/// Set once the tone-map can never work in this process (no d3dcompiler, the
/// shaders do not compile). Capturers then stop asking DXGI for float frames.
/// Device-specific failures are not recorded here; the capturer that hit one
/// re-duplicates without the tone-map on its own.
pub static UNAVAILABLE: AtomicBool = AtomicBool::new(false);
/// Failures no capturer on this machine can recover from, as opposed to
/// device-specific ones that a recreated capturer may not hit again.
pub fn is_permanent(err: &io::Error) -> bool {
err.kind() == io::ErrorKind::Unsupported
}
const VS_SRC: &str = "\
float4 main(uint id : SV_VertexID) : SV_Position {
float2 uv = float2((id << 1) & 2, id & 2);
return float4(uv * float2(2.0, -2.0) + float2(-1.0, 1.0), 0.0, 1.0);
}";
const PS_SRC: &str = "\
Texture2D<float4> src : register(t0);
cbuffer Params : register(b0) { float inv_sdr_white; float3 pad; };
float4 main(float4 pos : SV_Position) : SV_Target {
float3 lin = saturate(src.Load(int3(pos.xy, 0)).rgb * inv_sdr_white);
float3 lo = lin * 12.92;
float3 hi = 1.055 * pow(lin, 1.0 / 2.4) - 0.055;
return float4(lerp(hi, lo, step(lin, 0.0031308)), 1.0);
}";
const OUTPUT_STATE_REFRESH: Duration = Duration::from_secs(1);
pub struct HdrToSdr {
device: ComPtr<ID3D11Device>,
context: ComPtr<ID3D11DeviceContext>,
vs: ComPtr<ID3D11VertexShader>,
ps: ComPtr<ID3D11PixelShader>,
params: ComPtr<ID3D11Buffer>,
target: ComPtr<ID3D11Texture2D>,
rtv: ComPtr<ID3D11RenderTargetView>,
srv: ComPtr<ID3D11ShaderResourceView>,
// Texture `srv` was created for. The view keeps it alive, so the address
// cannot be recycled behind our back.
srv_source: *mut ID3D11Texture2D,
width: u32,
height: u32,
device_name: [WCHAR; 32],
// Advanced Color state is read from `output6`, which is re-enumerated from a
// fresh factory whenever `factory` stops being current.
factory: ComPtr<IDXGIFactory1>,
output6: ComPtr<IDXGIOutput6>,
is_hdr: bool,
// DISPLAYCONFIG units (1000 == 80 nits == scRGB 1.0). `None` when it could
// not be read, in which case 80 nits is assumed until it can.
sdr_white_level: Option<u32>,
queried_at: Instant,
}
impl HdrToSdr {
pub fn new(
device: *mut ID3D11Device,
context: *mut ID3D11DeviceContext,
output: *mut IDXGIOutput1,
device_name: &[WCHAR; 32],
) -> io::Result<Self> {
unsafe {
if device.is_null() || context.is_null() {
return Err(other("no d3d11 device"));
}
(*device).AddRef();
let device = ComPtr(device);
(*context).AddRef();
let context = ComPtr(context);
let compile = load_d3d_compile()?;
let vs_code = compile_shader(compile, VS_SRC, b"vs_4_0\0")?;
let ps_code = compile_shader(compile, PS_SRC, b"ps_4_0\0")?;
let mut vs = ptr::null_mut();
check(
(*device.0).CreateVertexShader(
(*vs_code.0).GetBufferPointer(),
(*vs_code.0).GetBufferSize(),
ptr::null_mut(),
&mut vs,
),
"CreateVertexShader",
)?;
let vs = ComPtr(vs);
let mut ps = ptr::null_mut();
check(
(*device.0).CreatePixelShader(
(*ps_code.0).GetBufferPointer(),
(*ps_code.0).GetBufferSize(),
ptr::null_mut(),
&mut ps,
),
"CreatePixelShader",
)?;
let ps = ComPtr(ps);
// Not found leaves the factory null, so the first refresh enumerates
// again instead of trusting the capturer's possibly stale output.
let (factory, mut output6) = enumerate_output6(device_name);
if output6.is_null() {
output6 = query_output6(output as *mut IUnknown);
}
// Float frames are only requested where IDXGIOutput6 exists, so an
// unreadable description still comes from an HDR-capable stack.
let is_hdr = output_is_hdr(output6.0).unwrap_or(true);
let sdr_white_level = if is_hdr {
query_sdr_white_level(device_name)
} else {
None
};
if is_hdr && sdr_white_level.is_none() {
log::warn!(
"HDR output but the SDR white level cannot be read (needs Windows 10 1709+), \
assuming 80 nits until it can"
);
}
let init = params_data(sdr_white_level);
let desc = D3D11_BUFFER_DESC {
ByteWidth: mem::size_of_val(&init) as _,
Usage: D3D11_USAGE_DEFAULT,
BindFlags: D3D11_BIND_CONSTANT_BUFFER,
CPUAccessFlags: 0,
MiscFlags: 0,
StructureByteStride: 0,
};
let data = D3D11_SUBRESOURCE_DATA {
pSysMem: init.as_ptr() as _,
SysMemPitch: 0,
SysMemSlicePitch: 0,
};
let mut params = ptr::null_mut();
check(
(*device.0).CreateBuffer(&desc, &data, &mut params),
"CreateBuffer",
)?;
let params = ComPtr(params);
log::info!(
"scRGB desktop conversion ready, hdr {is_hdr}, sdr white level {sdr_white_level:?}"
);
Ok(Self {
device,
context,
vs,
ps,
params,
target: ComPtr(ptr::null_mut()),
rtv: ComPtr(ptr::null_mut()),
srv: ComPtr(ptr::null_mut()),
srv_source: ptr::null_mut(),
width: 0,
height: 0,
device_name: *device_name,
factory,
output6,
is_hdr,
sdr_white_level,
queried_at: Instant::now(),
})
}
}
/// Renders `source` (R16G16B16A16_FLOAT) into an owned B8G8R8A8_UNORM
/// texture of the same size and returns it. The texture stays valid until
/// the next call.
pub fn convert(
&mut self,
source: *mut ID3D11Texture2D,
desc: &D3D11_TEXTURE2D_DESC,
) -> io::Result<*mut ID3D11Texture2D> {
unsafe {
self.refresh_output_state();
self.ensure_target(desc.Width, desc.Height)?;
self.ensure_source_view(source)?;
let ctx = self.context.0;
let rtv = self.rtv.0;
let srv = self.srv.0;
let params = self.params.0;
let viewport = D3D11_VIEWPORT {
TopLeftX: 0.0,
TopLeftY: 0.0,
Width: self.width as f32,
Height: self.height as f32,
MinDepth: 0.0,
MaxDepth: 1.0,
};
(*ctx).OMSetRenderTargets(1, &rtv, ptr::null_mut());
(*ctx).OMSetBlendState(ptr::null_mut(), &[0.0; 4], 0xffff_ffff);
(*ctx).OMSetDepthStencilState(ptr::null_mut(), 0);
(*ctx).RSSetState(ptr::null_mut());
(*ctx).RSSetViewports(1, &viewport);
(*ctx).IASetInputLayout(ptr::null_mut());
(*ctx).IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
(*ctx).VSSetShader(self.vs.0, ptr::null(), 0);
(*ctx).PSSetShader(self.ps.0, ptr::null(), 0);
(*ctx).PSSetConstantBuffers(0, 1, &params);
(*ctx).PSSetShaderResources(0, 1, &srv);
(*ctx).Draw(3, 0);
// Unbind so the next frame's copy and the encoder never see the
// target as a live render target or the desktop image as a bound
// shader input.
let no_srv: *mut ID3D11ShaderResourceView = ptr::null_mut();
(*ctx).PSSetShaderResources(0, 1, &no_srv);
(*ctx).OMSetRenderTargets(0, ptr::null(), ptr::null_mut());
Ok(self.target.0)
}
}
unsafe fn ensure_target(&mut self, width: u32, height: u32) -> io::Result<()> {
if !self.target.is_null() && self.width == width && self.height == height {
return Ok(());
}
let desc = D3D11_TEXTURE2D_DESC {
Width: width,
Height: height,
MipLevels: 1,
ArraySize: 1,
Format: DXGI_FORMAT_B8G8R8A8_UNORM,
SampleDesc: DXGI_SAMPLE_DESC {
Count: 1,
Quality: 0,
},
Usage: D3D11_USAGE_DEFAULT,
BindFlags: D3D11_BIND_RENDER_TARGET | D3D11_BIND_SHADER_RESOURCE,
CPUAccessFlags: 0,
MiscFlags: D3D11_RESOURCE_MISC_SHARED,
};
let mut target = ptr::null_mut();
check(
(*self.device.0).CreateTexture2D(&desc, ptr::null(), &mut target),
"CreateTexture2D",
)?;
let target = ComPtr(target);
let mut rtv = ptr::null_mut();
check(
(*self.device.0).CreateRenderTargetView(target.0 as *mut _, ptr::null(), &mut rtv),
"CreateRenderTargetView",
)?;
self.rtv = ComPtr(rtv);
self.target = target;
self.width = width;
self.height = height;
Ok(())
}
unsafe fn ensure_source_view(&mut self, source: *mut ID3D11Texture2D) -> io::Result<()> {
if !self.srv.is_null() && self.srv_source == source {
return Ok(());
}
let mut srv = ptr::null_mut();
check(
(*self.device.0).CreateShaderResourceView(source as *mut _, ptr::null(), &mut srv),
"CreateShaderResourceView",
)?;
self.srv = ComPtr(srv);
self.srv_source = source;
Ok(())
}
// Advanced Color state is dynamic: HDR can be switched on or off, or a WCG
// desktop can turn into an HDR one, without the duplication being lost. An
// output's description is a snapshot, so once the factory is no longer
// current a new factory and output are needed to see the new state, as the
// GetDesc1 docs require.
unsafe fn refresh_output_state(&mut self) {
if self.queried_at.elapsed() < OUTPUT_STATE_REFRESH {
return;
}
self.queried_at = Instant::now();
if self.factory.is_null() || (*self.factory.0).IsCurrent() == FALSE {
let (factory, output6) = enumerate_output6(&self.device_name);
if !output6.is_null() {
self.factory = factory;
self.output6 = output6;
} else {
// Keep reading the old output, but enumerate again next time.
self.factory = ComPtr(ptr::null_mut());
}
}
let is_hdr = output_is_hdr(self.output6.0).unwrap_or(self.is_hdr);
let level = if is_hdr {
query_sdr_white_level(&self.device_name)
} else {
None
};
// A transiently unreadable level keeps the last known one.
if is_hdr == self.is_hdr && (level.is_none() || level == self.sdr_white_level) {
return;
}
log::info!(
"output changed: hdr {} -> {is_hdr}, sdr white level {:?} -> {level:?}",
self.is_hdr,
self.sdr_white_level
);
if is_hdr && level.is_none() {
log::warn!(
"HDR output but the SDR white level cannot be read, assuming 80 nits until it can"
);
}
self.is_hdr = is_hdr;
self.sdr_white_level = level;
let data = params_data(level);
(*self.context.0).UpdateSubresource(
self.params.0 as *mut _,
0,
ptr::null(),
data.as_ptr() as _,
0,
0,
);
}
}
// `None` is either a non-HDR (WCG) output, where 1.0 already is the display's
// reference white, or an HDR output whose level is unknown; both use 1.0.
fn params_data(sdr_white_level: Option<u32>) -> [f32; 4] {
[
1000.0 / sdr_white_level.unwrap_or(1000) as f32,
0.0,
0.0,
0.0,
]
}
// FP16 desktop composition means either HDR (scene-referred, 1.0 == 80 nits)
// or, since Windows 11 22H2, Advanced Color SDR (display-referred), and only
// IDXGIOutput6 (Windows 10 1703) tells them apart. `None` when it cannot be
// read right now.
unsafe fn output_is_hdr(output6: *mut IDXGIOutput6) -> Option<bool> {
if output6.is_null() {
return None;
}
let mut desc: DXGI_OUTPUT_DESC1 = mem::zeroed();
if (*output6).GetDesc1(&mut desc) != S_OK {
return None;
}
Some(desc.ColorSpace == DXGI_COLOR_SPACE_RGB_FULL_G2084_NONE_P2020)
}
unsafe fn query_output6(object: *mut IUnknown) -> ComPtr<IDXGIOutput6> {
let mut output6: *mut IDXGIOutput6 = ptr::null_mut();
if !object.is_null() {
(*object).QueryInterface(
&IID_IDXGIOutput6,
&mut output6 as *mut *mut _ as *mut *mut _,
);
}
ComPtr(output6)
}
// A fresh factory sees the current display configuration; the output is found
// by its GDI name because the outputs of a stale factory keep stale descriptions.
// Returns both or neither: a non-null factory guarantees the output came from
// its topology, so a caller that sees a null factory knows to enumerate again.
unsafe fn enumerate_output6(
device_name: &[WCHAR; 32],
) -> (ComPtr<IDXGIFactory1>, ComPtr<IDXGIOutput6>) {
let mut factory: *mut c_void = ptr::null_mut();
if CreateDXGIFactory1(&IID_IDXGIFactory1, &mut factory) != S_OK {
return (ComPtr(ptr::null_mut()), ComPtr(ptr::null_mut()));
}
let factory = ComPtr(factory as *mut IDXGIFactory1);
let mut adapter_index = 0;
loop {
let mut adapter = ptr::null_mut();
if (*factory.0).EnumAdapters1(adapter_index, &mut adapter) != S_OK {
break;
}
let adapter = ComPtr(adapter);
adapter_index += 1;
let mut output_index = 0;
loop {
let mut output = ptr::null_mut();
if (*adapter.0).EnumOutputs(output_index, &mut output) != S_OK {
break;
}
let output = ComPtr(output);
output_index += 1;
let mut desc: DXGI_OUTPUT_DESC = mem::zeroed();
if (*output.0).GetDesc(&mut desc) == S_OK && wide_eq(&desc.DeviceName, device_name) {
let output6 = query_output6(output.0 as *mut IUnknown);
if output6.is_null() {
return (ComPtr(ptr::null_mut()), ComPtr(ptr::null_mut()));
}
return (factory, output6);
}
}
}
(ComPtr(ptr::null_mut()), ComPtr(ptr::null_mut()))
}
fn other(msg: impl Into<String>) -> io::Error {
io::Error::new(io::ErrorKind::Other, msg.into())
}
fn check(hr: HRESULT, what: &str) -> io::Result<()> {
if hr == S_OK {
Ok(())
} else {
Err(other(format!("{what} failed: {hr:#x}")))
}
}
// D3DCompile(pSrcData, SrcDataSize, pSourceName, pDefines, pInclude,
// pEntrypoint, pTarget, Flags1, Flags2, ppCode, ppErrorMsgs)
type D3DCompileFn = unsafe extern "system" fn(
LPCVOID,
SIZE_T,
LPCSTR,
*const D3D_SHADER_MACRO,
*mut ID3DInclude,
LPCSTR,
LPCSTR,
UINT,
UINT,
*mut *mut ID3DBlob,
*mut *mut ID3DBlob,
) -> HRESULT;
static D3D_COMPILE: OnceLock<Result<D3DCompileFn, String>> = OnceLock::new();
// Loaded once per process and kept: the compiler DLL is only needed on HDR
// desktops, and an import-time link would make every install depend on it.
fn load_d3d_compile() -> io::Result<D3DCompileFn> {
D3D_COMPILE
.get_or_init(|| unsafe { find_d3d_compile() })
.clone()
.map_err(|e| io::Error::new(io::ErrorKind::Unsupported, e))
}
unsafe fn find_d3d_compile() -> Result<D3DCompileFn, String> {
let name: Vec<u16> = "d3dcompiler_47.dll\0".encode_utf16().collect();
let module = LoadLibraryExW(name.as_ptr(), ptr::null_mut(), LOAD_LIBRARY_SEARCH_SYSTEM32);
if module.is_null() {
return Err("d3dcompiler_47.dll not available".into());
}
let f = GetProcAddress(module, b"D3DCompile\0".as_ptr() as _);
if f.is_null() {
return Err("D3DCompile not exported".into());
}
Ok(mem::transmute::<_, D3DCompileFn>(f))
}
unsafe fn compile_shader(
compile: D3DCompileFn,
src: &str,
target: &[u8],
) -> io::Result<ComPtr<ID3DBlob>> {
let mut code = ptr::null_mut();
let mut errors = ptr::null_mut();
let hr = compile(
src.as_ptr() as _,
src.len(),
ptr::null(),
ptr::null(),
ptr::null_mut(),
b"main\0".as_ptr() as _,
target.as_ptr() as _,
0,
0,
&mut code,
&mut errors,
);
let errors = ComPtr(errors);
if hr != S_OK || code.is_null() {
let msg = if errors.is_null() {
String::new()
} else {
let bytes = std::slice::from_raw_parts(
(*errors.0).GetBufferPointer() as *const u8,
(*errors.0).GetBufferSize(),
);
String::from_utf8_lossy(bytes).into_owned()
};
if !code.is_null() {
(*(code as *mut IUnknown)).Release();
}
return Err(io::Error::new(
io::ErrorKind::Unsupported,
format!("D3DCompile failed: {hr:#x} {msg}"),
));
}
Ok(ComPtr(code))
}
const DISPLAYCONFIG_DEVICE_INFO_GET_SDR_WHITE_LEVEL: u32 = 11;
const QDC_ONLY_ACTIVE_PATHS: u32 = 2;
#[repr(C)]
#[allow(non_snake_case)]
struct DISPLAYCONFIG_SDR_WHITE_LEVEL {
header: DISPLAYCONFIG_DEVICE_INFO_HEADER,
SDRWhiteLevel: ULONG,
}
#[link(name = "user32")]
extern "system" {
fn GetDisplayConfigBufferSizes(
flags: u32,
numPathArrayElements: *mut u32,
numModeInfoArrayElements: *mut u32,
) -> LONG;
fn QueryDisplayConfig(
flags: u32,
numPathArrayElements: *mut u32,
pathArray: *mut DISPLAYCONFIG_PATH_INFO,
numModeInfoArrayElements: *mut u32,
modeInfoArray: *mut DISPLAYCONFIG_MODE_INFO,
currentTopologyId: *mut DISPLAYCONFIG_TOPOLOGY_ID,
) -> LONG;
fn DisplayConfigGetDeviceInfo(requestPacket: *mut DISPLAYCONFIG_DEVICE_INFO_HEADER) -> LONG;
}
/// SDR white level of the output whose GDI name is `device_name`
/// (e.g. `\\.\DISPLAY1`), in DISPLAYCONFIG units (1000 == 80 nits). `None`
/// when the query fails (before Windows 10 1709) or reports 0.
fn query_sdr_white_level(device_name: &[WCHAR; 32]) -> Option<u32> {
unsafe {
let mut n_paths = 0u32;
let mut n_modes = 0u32;
if GetDisplayConfigBufferSizes(QDC_ONLY_ACTIVE_PATHS, &mut n_paths, &mut n_modes) != 0 {
return None;
}
let mut paths: Vec<DISPLAYCONFIG_PATH_INFO> = vec![mem::zeroed(); n_paths as usize];
let mut modes: Vec<DISPLAYCONFIG_MODE_INFO> = vec![mem::zeroed(); n_modes as usize];
if QueryDisplayConfig(
QDC_ONLY_ACTIVE_PATHS,
&mut n_paths,
paths.as_mut_ptr(),
&mut n_modes,
modes.as_mut_ptr(),
ptr::null_mut(),
) != 0
{
return None;
}
for path in &paths[..n_paths as usize] {
let mut source: DISPLAYCONFIG_SOURCE_DEVICE_NAME = mem::zeroed();
source.header._type = DISPLAYCONFIG_DEVICE_INFO_GET_SOURCE_NAME;
source.header.size = mem::size_of::<DISPLAYCONFIG_SOURCE_DEVICE_NAME>() as _;
source.header.adapterId = path.sourceInfo.adapterId;
source.header.id = path.sourceInfo.id;
if DisplayConfigGetDeviceInfo(&mut source.header) != 0
|| !wide_eq(&source.viewGdiDeviceName, device_name)
{
continue;
}
let mut white: DISPLAYCONFIG_SDR_WHITE_LEVEL = mem::zeroed();
white.header._type = DISPLAYCONFIG_DEVICE_INFO_GET_SDR_WHITE_LEVEL;
white.header.size = mem::size_of::<DISPLAYCONFIG_SDR_WHITE_LEVEL>() as _;
white.header.adapterId = path.targetInfo.adapterId;
white.header.id = path.targetInfo.id;
if DisplayConfigGetDeviceInfo(&mut white.header) == 0 && white.SDRWhiteLevel != 0 {
return Some(white.SDRWhiteLevel);
}
}
None
}
}
fn wide_eq(a: &[WCHAR], b: &[WCHAR]) -> bool {
let end = |s: &[WCHAR]| s.iter().position(|&c| c == 0).unwrap_or(s.len());
a[..end(a)] == b[..end(b)]
}
+120 -4
View File
@@ -1,18 +1,20 @@
use std::{io, mem, ptr, slice};
pub mod gdi;
pub use gdi::CapturerGDI;
pub mod hdr;
pub mod mag;
use winapi::{
shared::{
dxgi::*,
dxgi1_2::*,
dxgi1_6::*,
dxgiformat::{DXGI_FORMAT_B8G8R8A8_UNORM, DXGI_FORMAT_R16G16B16A16_FLOAT},
dxgitype::*,
minwindef::{DWORD, FALSE, TRUE, UINT},
ntdef::LONG,
windef::{HMONITOR, RECT},
winerror::*,
// dxgiformat::{DXGI_FORMAT, DXGI_FORMAT_B8G8R8A8_UNORM, DXGI_FORMAT_420_OPAQUE},
},
um::{
d3d11::*, d3dcommon::D3D_DRIVER_TYPE_UNKNOWN, unknwnbase::IUnknown, wingdi::*,
@@ -66,6 +68,7 @@ pub struct Capturer {
adapter_desc1: DXGI_ADAPTER_DESC1,
rotate: Rotate,
frame_state: FrameState,
hdr: Option<hdr::HdrToSdr>,
}
impl Capturer {
@@ -113,7 +116,7 @@ impl Capturer {
}
} else {
res = wrap_hresult(unsafe {
let hres = (*display.inner.0).DuplicateOutput(device.0 as *mut _, &mut duplication);
let hres = Self::duplicate_output(&display, device.0, &mut duplication);
if hres != S_OK {
gdi_capturer = display.create_gdi();
println!("Fallback to GDI");
@@ -169,7 +172,8 @@ impl Capturer {
device,
context,
duplication: ComPtr(duplication),
fastlane: desc.DesktopImageInSystemMemory == TRUE,
fastlane: desc.DesktopImageInSystemMemory == TRUE
&& desc.ModeDesc.Format != DXGI_FORMAT_R16G16B16A16_FLOAT,
surface: ComPtr(ptr::null_mut()),
texture: ComPtr(ptr::null_mut()),
width: display.width() as usize,
@@ -183,9 +187,104 @@ impl Capturer {
adapter_desc1,
rotate,
frame_state: FrameState::Idle,
hdr: None,
})
}
// Asks for the float desktop that HDR mode composes so it can be tone-mapped;
// the legacy call would hand back DXGI's clipped BGRA8 conversion instead.
// Only where IDXGIOutput6 (Windows 10 1703) exists, since that is what later
// tells an HDR desktop from a WCG one; Microsoft's duplication sample gates
// the float request the same way.
unsafe fn duplicate_output(
display: &Display,
device: *mut ID3D11Device,
duplication: &mut *mut IDXGIOutputDuplication,
) -> HRESULT {
if !hdr::UNAVAILABLE.load(std::sync::atomic::Ordering::Relaxed) {
let mut output6: *mut IDXGIOutput6 = ptr::null_mut();
(*display.inner.0).QueryInterface(
&IID_IDXGIOutput6,
&mut output6 as *mut *mut _ as *mut *mut _,
);
if !output6.is_null() {
let output6 = ComPtr(output6);
let formats = [DXGI_FORMAT_R16G16B16A16_FLOAT, DXGI_FORMAT_B8G8R8A8_UNORM];
let hres = (*output6.0).DuplicateOutput1(
device as *mut _,
0,
formats.len() as UINT,
formats.as_ptr(),
duplication,
);
if hres == S_OK {
return hres;
}
hbb_common::log::warn!(
"HDR DuplicateOutput1 failed: hr={:#x}, fallback=DuplicateOutput",
hres as u32
);
}
}
(*display.inner.0).DuplicateOutput(device as *mut _, duplication)
}
unsafe fn tonemap(
&mut self,
source: *mut ID3D11Texture2D,
desc: &D3D11_TEXTURE2D_DESC,
) -> io::Result<*mut ID3D11Texture2D> {
if self.hdr.is_none() {
match hdr::HdrToSdr::new(
self.device.0,
self.context.0,
self.display.inner.0,
&self.display.desc.DeviceName,
) {
Ok(hdr) => self.hdr = Some(hdr),
Err(err) => return self.abandon_tonemap(err),
}
}
let converted = match self.hdr.as_mut() {
Some(hdr) => hdr.convert(source, desc),
None => Err(io::Error::new(io::ErrorKind::Other, "no tone-map")),
};
match converted {
Ok(texture) => Ok(texture),
Err(err) => self.abandon_tonemap(err),
}
}
// Drops the tone-map and re-duplicates the output the legacy way, so DXGI
// hands over clipped BGRA8 (the pre-HDR behaviour). If re-duplication fails,
// switch to GDI before returning. The caller sees WouldBlock and asks again.
unsafe fn abandon_tonemap<T>(&mut self, err: io::Error) -> io::Result<T> {
if hdr::is_permanent(&err) {
hdr::UNAVAILABLE.store(true, std::sync::atomic::Ordering::Relaxed);
}
hbb_common::log::error!("HDR tone-map failed, re-duplicating without it: {err}");
self.hdr = None;
if let Err(release_err) = self.release_frame() {
hbb_common::log::warn!("DXGI frame cleanup failed while disabling HDR: {release_err}");
}
self.duplication = ComPtr(ptr::null_mut());
let mut duplication = ptr::null_mut();
let result = wrap_hresult(
(*self.display.inner.0).DuplicateOutput(self.device.0 as *mut _, &mut duplication),
);
if let Err(err) = result {
if self.set_gdi() {
return Err(io::ErrorKind::WouldBlock.into());
}
return Err(err);
}
self.duplication = ComPtr(duplication);
let mut desc: DXGI_OUTDUPL_DESC = mem::zeroed();
(*duplication).GetDesc(&mut desc);
self.fastlane = desc.DesktopImageInSystemMemory == TRUE;
Err(io::ErrorKind::WouldBlock.into())
}
fn create_rotations(
device: *mut ID3D11Device,
context: *mut ID3D11DeviceContext,
@@ -339,6 +438,9 @@ impl Capturer {
}
unsafe fn load_frame(&mut self, timeout: UINT) -> io::Result<(*const u8, i32)> {
if self.duplication.0.is_null() {
return Err(io::ErrorKind::AddrNotAvailable.into());
}
let mut frame = ptr::null_mut();
#[allow(invalid_value)]
let mut info = mem::MaybeUninit::uninit().assume_init();
@@ -377,6 +479,12 @@ impl Capturer {
let mut texture_desc = mem::MaybeUninit::uninit().assume_init();
(*texture.0).GetDesc(&mut texture_desc);
let mut source = texture.0;
if texture_desc.Format == DXGI_FORMAT_R16G16B16A16_FLOAT {
source = self.tonemap(texture.0, &texture_desc)?;
(*source).GetDesc(&mut texture_desc);
}
texture_desc.Usage = D3D11_USAGE_STAGING;
texture_desc.BindFlags = 0;
texture_desc.CPUAccessFlags = D3D11_CPU_ACCESS_READ;
@@ -397,7 +505,7 @@ impl Capturer {
&mut surface as *mut *mut _ as *mut *mut _,
);
(*self.context.0).CopyResource(readable.0 as *mut _, texture.0 as *mut _);
(*self.context.0).CopyResource(readable.0 as *mut _, source as *mut _);
Ok(surface)
}
@@ -505,6 +613,14 @@ impl Capturer {
let texture = ComPtr(texture);
self.texture = texture;
let mut frame_desc: D3D11_TEXTURE2D_DESC = mem::zeroed();
(*self.texture.0).GetDesc(&mut frame_desc);
if frame_desc.Format == DXGI_FORMAT_R16G16B16A16_FLOAT {
let converted = self.tonemap(self.texture.0, &frame_desc)?;
(*converted).AddRef();
self.texture = ComPtr(converted);
}
let mut final_texture = self.texture.0 as *mut c_void;
let mut rotation = match self.display.rotation() {
DXGI_MODE_ROTATION_ROTATE90 => 90,
+163 -5
View File
@@ -57,7 +57,7 @@ use hbb_common::{
rand,
rendezvous_proto::*,
sha2::{Digest, Sha256},
socket_client::{connect_tcp, connect_tcp_local, ipv4_to_ipv6, new_direct_udp_for},
socket_client::{connect_tcp, connect_tcp_local, ipv4_to_ipv6, new_direct_udp_for_unverified},
sodiumoxide::{base64, crypto::sign},
timeout,
tokio::{
@@ -490,7 +490,7 @@ impl Client {
// no need to care about multiple rendezvous servers case, since it is acutally not used any more.
// Shared state for UDP NAT test result
if crate::get_udp_punch_enabled() && !interface.is_force_relay() {
if let Ok((socket, addr)) = new_direct_udp_for(&rendezvous_server).await {
if let Ok((socket, addr)) = new_direct_udp_for_unverified(&rendezvous_server).await {
let udp_port = Arc::new(Mutex::new(0));
let up_cloned = udp_port.clone();
let socket_cloned = socket.clone();
@@ -1694,7 +1694,9 @@ impl Client {
let bytes = res?;
if let Ok(msg_in) = Message::parse_from_bytes(&bytes) {
if let Some(message::Union::SignedId(si)) = msg_in.union {
if let Ok((id, their_pk_b, signed_fp)) = decode_id_pk_dtls(&si.id, &sign_pk) {
if let Ok((id, their_pk_b, signed_fp, kx_version)) =
decode_id_pk_dtls(&si.id, &sign_pk)
{
if id == peer_id {
// WebRTC only: bind the DTLS channel to the verified peer identity.
// webrtc-rs already bound the certificate to the remote SDP, so
@@ -1710,14 +1712,31 @@ impl Client {
}
let (asymmetric_value, symmetric_value, key) =
create_symmetric_key_msg(their_pk_b);
// A WebRTC stream is encrypted by DTLS and takes no stream
// key of its own, split or not, so the pick says what runs: 0.
let picked = if is_webrtc {
0
} else {
hbb_common::tcp::kx_version_for(kx_version)
};
let mut msg_out = Message::new();
msg_out.set_public_key(PublicKey {
asymmetric_value,
asymmetric_value: asymmetric_value.clone(),
symmetric_value,
kx_version: picked,
..Default::default()
});
timeout(CONNECT_TIMEOUT, conn.send(&msg_out)).await??;
conn.set_key(key);
conn.set_negotiated_key(
key,
true,
&hbb_common::tcp::KxTranscript {
initiator_pk: &asymmetric_value,
responder_pk: &their_pk_b,
advertised: kx_version,
picked,
},
)?;
} else {
if is_webrtc {
bail!("WebRTC handshake id mismatch (possible MITM)");
@@ -5795,3 +5814,142 @@ mod webrtc_race_tests {
assert!(err.contains("webrtc dead") && err.contains("relay dead"), "{}", err);
}
}
#[cfg(test)]
mod kx_tests {
use super::*;
use hbb_common::{
sodiumoxide::crypto::box_,
tcp::{Encrypt, FramedStream, KxTranscript, KX_VERSION_LATEST},
};
const PEER_ID: &str = "123456789";
/// What the stand-in controlled peer saw: the version the controller picked, and whether the
/// controller's first application message decrypted.
struct Seen {
picked: u32,
decrypted: bool,
}
fn test_delay(time: i64) -> Message {
let mut msg = Message::new();
msg.set_test_delay(TestDelay {
time,
..Default::default()
});
msg
}
fn delay_in(bytes: &[u8]) -> Option<i64> {
match Message::parse_from_bytes(bytes).ok()?.union? {
message::Union::TestDelay(t) => Some(t.time),
_ => None,
}
}
/// A stand-in controlled peer on loopback. It advertises `advertised` in its signed identity
/// and runs the key under `run`, or under the version the controller picked when `run` is
/// `None`, then sends one message and reads one. Returns the host, its identity as the
/// rendezvous server would sign it, and what it saw.
async fn controlled_stub(
advertised: u32,
run: Option<u32>,
rs_sk: sign::SecretKey,
) -> (String, Vec<u8>, oneshot::Receiver<Seen>) {
let (sign_pk, sign_sk) = sign::gen_keypair();
let id_pk = |pk: &[u8], kx_version| {
IdPk {
id: PEER_ID.to_owned(),
pk: pk.to_vec().into(),
kx_version,
..Default::default()
}
.write_to_bytes()
.unwrap()
};
let signed_id_pk = sign::sign(&id_pk(&sign_pk.0, 0), &rs_sk);
let listener = hbb_common::tcp::new_listener("127.0.0.1:0", false)
.await
.unwrap();
let host = listener.local_addr().unwrap().to_string();
let (tx, rx) = oneshot::channel();
tokio::spawn(async move {
let (stream, addr) = listener.accept().await.unwrap();
let mut s = FramedStream::from(stream, addr);
let (our_pk_b, our_sk_b) = box_::gen_keypair();
let mut msg = Message::new();
msg.set_signed_id(SignedId {
id: sign::sign(&id_pk(&our_pk_b.0, advertised), &sign_sk).into(),
..Default::default()
});
s.send(&msg).await.unwrap();
let bytes = s.next().await.unwrap().unwrap();
let Some(message::Union::PublicKey(pk)) =
Message::parse_from_bytes(&bytes).unwrap().union
else {
panic!("expected the controller's public key");
};
let key =
Encrypt::decode(&pk.symmetric_value, &pk.asymmetric_value, &our_sk_b).unwrap();
let t = KxTranscript {
initiator_pk: &pk.asymmetric_value,
responder_pk: &our_pk_b.0,
advertised,
picked: run.unwrap_or(pk.kx_version),
};
if t.picked == 0 {
s.set_key(key);
} else {
s.set_key_split(key, false, &t).unwrap();
}
s.send(&test_delay(2)).await.unwrap();
let decrypted = matches!(s.next().await, Some(Ok(b)) if delay_in(&b) == Some(1));
tx.send(Seen {
picked: pk.kx_version,
decrypted,
})
.ok();
});
(host, signed_id_pk, rx)
}
/// The controller's handshake against the stub, then one application message each way.
/// Returns what the stub saw and whether the stub's message decrypted on this side.
async fn handshake(advertised: u32, run: Option<u32>) -> (Seen, bool) {
let (rs_pk, rs_sk) = sign::gen_keypair();
let (host, signed_id_pk, seen) = controlled_stub(advertised, run, rs_sk).await;
let mut conn = connect_tcp(host, 3000).await.unwrap();
let pk =
Client::secure_connection(PEER_ID, signed_id_pk, &crate::encode64(rs_pk.0), &mut conn)
.await
.unwrap();
assert!(pk.is_some() && conn.is_secured());
conn.send(&test_delay(1)).await.unwrap();
let decrypted = matches!(conn.next().await, Some(Ok(b)) if delay_in(&b) == Some(2));
(seen.await.unwrap(), decrypted)
}
#[tokio::test]
async fn test_new_peers_pick_version_1_and_exchange_application_data() {
let (seen, decrypted) = handshake(KX_VERSION_LATEST, None).await;
assert_eq!(seen.picked, 1);
assert!(seen.decrypted && decrypted);
}
#[tokio::test]
async fn test_a_peer_without_versions_gets_version_0() {
let (seen, decrypted) = handshake(0, Some(0)).await;
assert_eq!(seen.picked, 0);
assert!(seen.decrypted && decrypted);
}
#[tokio::test]
async fn test_a_pick_lowered_in_transit_decrypts_nothing() {
// The controlled side takes 0 from a controller without versions, so a lowered pick is
// caught by the keys disagreeing on the first application message, not before.
let (seen, decrypted) = handshake(KX_VERSION_LATEST, Some(0)).await;
assert_eq!(seen.picked, 1);
assert!(!seen.decrypted && !decrypted);
}
}
+128 -1
View File
@@ -641,6 +641,19 @@ impl<T: InvokeUiSession> Remote<T> {
self.check_clipboard_file_context();
}
Data::Message(msg) => {
// The Flutter clipboard broadcast is process-wide, so a clipboard can reach this
// round's queue before the round has logged in; it is dropped here, on the round
// itself.
#[cfg(feature = "flutter")]
if !self.is_connected
&& matches!(
msg.union.as_ref(),
Some(message::Union::Clipboard(_))
| Some(message::Union::MultiClipboards(_))
)
{
return true;
}
match &msg.union {
Some(message::Union::Misc(misc)) => match misc.union {
Some(misc::Union::RefreshVideo(_)) => {
@@ -1511,7 +1524,11 @@ impl<T: InvokeUiSession> Remote<T> {
_ => {}
},
Some(message::Union::CursorData(cd)) => {
self.handler.set_cursor_data(cd);
let id = cd.id;
match decode_cursor_data(cd) {
Ok(cd) => self.handler.set_cursor_data(cd),
Err(err) => log::warn!("Rejected cursor {id}: {err}"),
}
}
Some(message::Union::CursorId(id)) => {
self.handler.set_cursor_id(id.to_string());
@@ -2545,6 +2562,47 @@ impl<T: InvokeUiSession> Remote<T> {
}
}
// Both UI handlers receive validated, uncompressed RGBA from the receive loop.
fn decode_cursor_data(data: CursorData) -> hbb_common::ResultType<CursorData> {
use hbb_common::{anyhow::anyhow, bail};
// Limit decoded cursor data to 1 MiB before JSON serialization.
const MAX_CURSOR_SIZE: i32 = 512;
const RGBA_CHANNELS: usize = 4;
let mut cd = data;
if !(1..=MAX_CURSOR_SIZE).contains(&cd.width) || !(1..=MAX_CURSOR_SIZE).contains(&cd.height) {
bail!("invalid source size {}x{}", cd.width, cd.height);
}
if !(0..cd.width).contains(&cd.hotx) || !(0..cd.height).contains(&cd.hoty) {
bail!(
"hotspot ({},{}) is outside the cursor image",
cd.hotx,
cd.hoty
);
}
let expected = (cd.width as usize)
.checked_mul(cd.height as usize)
.and_then(|pixels| pixels.checked_mul(RGBA_CHANNELS))
.ok_or_else(|| anyhow!("cursor RGBA size overflow"))?;
let max_compressed_size = zstd::zstd_safe::compress_bound(expected);
if cd.colors.len() > max_compressed_size {
bail!(
"compressed cursor data too large: {} bytes (limit {max_compressed_size})",
cd.colors.len()
);
}
let colors = zstd::bulk::decompress(&cd.colors, expected)?;
if colors.len() != expected {
bail!(
"invalid RGBA length: expected {expected}, got {}",
colors.len()
);
}
cd.colors = colors.into();
Ok(cd)
}
struct RemoveJob {
files: Vec<FileEntry>,
path: String,
@@ -2598,3 +2656,72 @@ impl Drop for VideoThread {
*self.discard_queue.write().unwrap() = true;
}
}
#[cfg(test)]
#[cfg(feature = "flutter")]
mod tests {
use super::*;
use crate::flutter::FlutterHandler;
/// A round's `Remote` over a loopback pair, before any login: what it sends to `peer`
/// arrives at `far`.
async fn remote_and_peer() -> (Remote<FlutterHandler>, Stream, Stream) {
let listener = hbb_common::tcp::new_listener("127.0.0.1:0", false)
.await
.unwrap();
let addr = listener.local_addr().unwrap();
let (peer, accepted) = tokio::join!(
hbb_common::socket_client::connect_tcp(addr.to_string(), 3000),
listener.accept()
);
let (accepted, far_addr) = accepted.unwrap();
let far = Stream::Tcp(hbb_common::tcp::FramedStream::from(accepted, far_addr));
let (sender, receiver) = mpsc::unbounded_channel::<Data>();
let remote = Remote::new(Session::<FlutterHandler>::default(), receiver, sender);
(remote, peer.unwrap(), far)
}
async fn arrives(far: &mut Stream) -> bool {
matches!(hbb_common::timeout(300, far.next()).await, Ok(Some(Ok(_))))
}
fn clipboard() -> Data {
let mut msg = Message::new();
msg.set_clipboard(Clipboard {
content: b"copied while this login was pending".to_vec().into(),
..Default::default()
});
Data::Message(msg)
}
fn auth_2fa() -> Data {
let mut msg = Message::new();
msg.set_auth_2fa(Auth2FA {
code: "123456".to_owned(),
..Default::default()
});
Data::Message(msg)
}
// A clipboard queued before this round's login stays here; what the login itself sends
// through the same queue does not.
#[tokio::test]
async fn a_clipboard_queued_before_this_rounds_login_is_dropped() {
let (mut remote, mut peer, mut far) = remote_and_peer().await;
assert!(!remote.is_connected);
assert!(remote.handle_msg_from_ui(clipboard(), &mut peer).await);
assert!(
!arrives(&mut far).await,
"a clipboard went out before the login"
);
assert!(remote.handle_msg_from_ui(auth_2fa(), &mut peer).await);
assert!(arrives(&mut far).await, "the 2FA code was held back");
remote.is_connected = true;
assert!(remote.handle_msg_from_ui(clipboard(), &mut peer).await);
assert!(
arrives(&mut far).await,
"a clipboard after the login was held back"
);
}
}
+10 -3
View File
@@ -314,7 +314,7 @@ pub mod unix_file_clip {
requested_format_id: _requested_format_id,
} => {
log::debug!("requested format id: {}", _requested_format_id);
let format_data = serv_files::get_file_list_pdu();
let format_data = serv_files::get_file_list_pdu(conn_id);
if !format_data.is_empty() {
return vec![clip_2_msg(ClipboardFile::FormatDataResponse {
msg_flags: 1,
@@ -365,7 +365,8 @@ pub mod unix_file_clip {
n_position_low,
n_position_high,
cb_requested,
..
have_clip_data_id,
clip_data_id,
} => {
log::debug!("file contents request: stream_id: {}, list_index: {}, dw_flags: {}, n_position_low: {}, n_position_high: {}, cb_requested: {}", stream_id, list_index, dw_flags, n_position_low, n_position_high, cb_requested);
return serv_files::read_file_contents(
@@ -376,12 +377,18 @@ pub mod unix_file_clip {
n_position_low,
n_position_high,
cb_requested,
have_clip_data_id.then_some(clip_data_id),
)
.into_iter()
.map(|res| match res {
Ok(data) => clip_2_msg(data),
Err(e) => {
log::error!("failed to read file contents: {:?}", e);
hbb_common::throttled_log!(
std::time::Duration::from_secs(5),
error,
"failed to read file contents: {:?}",
e
);
resp_file_contents_fail(stream_id)
}
})
+417 -51
View File
@@ -59,6 +59,7 @@ pub const PLATFORM_MACOS: &str = "Mac OS";
pub const PLATFORM_ANDROID: &str = "Android";
pub const TIMER_OUT: Duration = Duration::from_secs(1);
pub(crate) const API_LOG_INTERVAL: Duration = Duration::from_secs(600);
pub const DEFAULT_KEEP_ALIVE: i32 = 60_000;
const MIN_VER_MULTI_UI_SESSION: &str = "1.2.4";
@@ -1196,6 +1197,9 @@ pub fn get_local_option(key: &str) -> String {
}
}
}
if key == "lang" && (v == "pt" || v == "br") {
return "pt-br".to_owned();
}
v
}
@@ -1244,6 +1248,23 @@ fn is_tcp_proxy_api_target(url: &str) -> bool {
should_use_tcp_proxy_for_api_url(url, &ui_get_api_server())
}
#[inline]
fn should_throttle_log(url: &str) -> bool {
url::Url::parse(url)
.map(|parsed| parsed.path().ends_with("/api/heartbeat"))
.unwrap_or(false)
}
macro_rules! api_log {
($level:ident, $url:expr, $interval:expr, $($arg:tt)+) => {{
if should_throttle_log($url) {
hbb_common::throttled_log!($interval, $level, $($arg)+);
} else {
log::$level!($($arg)+);
}
}};
}
fn tcp_proxy_log_target(url: &str) -> String {
url::Url::parse(url)
.ok()
@@ -1293,7 +1314,10 @@ async fn tcp_proxy_request(
parsed.path().to_string()
};
log::debug!(
api_log!(
debug,
url,
API_LOG_INTERVAL,
"Sending {} {} via TCP proxy to {}",
method,
parsed.path(),
@@ -1453,7 +1477,10 @@ where
};
if should_fallback && can_fallback_to_raw_tcp(url) {
log::warn!(
api_log!(
warn,
url,
API_LOG_INTERVAL,
"HTTP {} to {} failed or 5xx (result: {:?}), trying TCP proxy fallback",
method,
tcp_proxy_log_target(url),
@@ -1465,7 +1492,13 @@ where
match tcp_fn.await {
Ok(resp) => return Ok(resp),
Err(tcp_err) => {
log::warn!("TCP proxy fallback also failed: {:?}", tcp_err);
api_log!(
warn,
url,
API_LOG_INTERVAL,
"TCP proxy fallback also failed: {:?}",
tcp_err
);
}
}
}
@@ -1523,7 +1556,10 @@ pub async fn post_request_with_status(
Ok((status, _)) => *status >= 500,
};
if should_fallback && can_fallback_to_raw_tcp(&url) {
log::warn!(
api_log!(
warn,
&url,
API_LOG_INTERVAL,
"HTTP POST to {} failed or 5xx (result: {:?}), trying TCP proxy fallback",
tcp_proxy_log_target(&url),
http_result
@@ -1534,7 +1570,13 @@ pub async fn post_request_with_status(
match post_request_via_tcp_proxy_status(&url, &body, header).await {
Ok(resp) => return Ok(resp),
Err(tcp_err) => {
log::warn!("TCP proxy fallback also failed: {:?}", tcp_err);
api_log!(
warn,
&url,
API_LOG_INTERVAL,
"TCP proxy fallback also failed: {:?}",
tcp_err
);
}
}
}
@@ -1591,7 +1633,10 @@ async fn post_request_(
Err(e) => {
if (tls_type.is_none() || danger_accept_invalid_cert.is_none()) && e.is_request() {
if danger_accept_invalid_cert.is_none() {
log::warn!(
api_log!(
warn,
url,
API_LOG_INTERVAL,
"HTTP request failed: {:?}, try again, danger accept invalid cert",
e
);
@@ -1606,7 +1651,13 @@ async fn post_request_(
)
.await
} else {
log::warn!("HTTP request failed: {:?}, try again with native-tls", e);
api_log!(
warn,
url,
API_LOG_INTERVAL,
"HTTP request failed: {:?}, try again with native-tls",
e
);
post_request_(
url,
tls_url,
@@ -2100,17 +2151,46 @@ async fn key_exchange(conn: &mut Stream, key: &str, log_on_success: bool) -> Res
}
let their_pk_b = sign::verify(&ex.keys[0], &rs_pk)
.map_err(|_| anyhow!("Signature mismatch in key exchange"))?;
let (asymmetric_value, symmetric_value, key) = create_symmetric_key_msg(
get_pk(&their_pk_b)
.context("Wrong their public length in key exchange")?,
);
let their_pk_b = get_pk(&their_pk_b)
.context("Wrong their public length in key exchange")?;
// The signed X25519 high bit marks servers that sign their parameters.
// X25519 ignores that bit, so old clients use the key unchanged; keep
// the bytes as signed, since the transcript and KxParams carry them so.
if their_pk_b[31] & 0x80 != 0 || !ex.signed_params.is_empty() {
let params = sign::verify(&ex.signed_params, &rs_pk)
.ok()
.and_then(|signed| {
let params =
signed.strip_prefix(hbb_common::tcp::KX_PARAMS_DOMAIN)?;
KxParams::parse_from_bytes(params).ok()
})
.ok_or_else(|| {
anyhow!("Missing or invalid signed key exchange parameters")
})?;
if params.pk[..] != their_pk_b[..] || params.version != ex.version {
bail!("Key exchange version or public key does not match its signature");
}
}
let (asymmetric_value, symmetric_value, key) =
create_symmetric_key_msg(their_pk_b);
let picked = hbb_common::tcp::kx_version_for(ex.version);
let mut msg_out = RendezvousMessage::new();
msg_out.set_key_exchange(KeyExchange {
keys: vec![asymmetric_value, symmetric_value],
keys: vec![asymmetric_value.clone(), symmetric_value],
version: picked,
..Default::default()
});
timeout(CONNECT_TIMEOUT, conn.send(&msg_out)).await??;
conn.set_key(key);
conn.set_negotiated_key(
key,
true,
&hbb_common::tcp::KxTranscript {
initiator_pk: &asymmetric_value,
responder_pk: &their_pk_b,
advertised: ex.version,
picked,
},
)?;
if log_on_success {
log::info!("Connection secured");
}
@@ -2170,21 +2250,23 @@ pub fn get_rs_pk(str_base64: &str) -> Option<sign::PublicKey> {
}
pub fn decode_id_pk(signed: &[u8], key: &sign::PublicKey) -> ResultType<(String, [u8; 32])> {
let (id, pk, _) = decode_id_pk_dtls(signed, key)?;
let (id, pk, _, _) = decode_id_pk_dtls(signed, key)?;
Ok((id, pk))
}
/// Like [`decode_id_pk`] but also returns the signed DTLS certificate fingerprint (empty string
/// for non-WebRTC peers), used to bind a WebRTC DTLS channel to the verified peer identity.
/// for non-WebRTC peers), used to bind a WebRTC DTLS channel to the verified peer identity, and
/// the newest key exchange version the peer speaks (0, the original scheme, for a peer from
/// before versions).
pub fn decode_id_pk_dtls(
signed: &[u8],
key: &sign::PublicKey,
) -> ResultType<(String, [u8; 32], String)> {
) -> ResultType<(String, [u8; 32], String, u32)> {
let res = IdPk::parse_from_bytes(
&sign::verify(signed, key).map_err(|_| anyhow!("Signature mismatch"))?,
)?;
if let Some(pk) = get_pk(&res.pk) {
Ok((res.id, pk, res.dtls_fingerprint))
Ok((res.id, pk, res.dtls_fingerprint, res.kx_version))
} else {
bail!("Wrong their public length");
}
@@ -2528,45 +2610,42 @@ async fn stun_ipv6_test(stun_server: String) -> ResultType<(SocketAddr, String)>
})
}
/// A global address to ask the kernel for a route to; libwebrtc's QueryDefaultLocalAddress asks
/// for the same one. Nothing is ever sent to it.
const IPV6_ROUTE_PROBE: std::net::Ipv6Addr =
std::net::Ipv6Addr::new(0x2001, 0x4860, 0x4860, 0, 0, 0, 0, 0x8888);
/// The public IPv6 address the STUN servers report is looked for in the background, and for no
/// longer than this: a probe that outlived the minute could write an earlier network's address
/// over a later probe's.
const STUN_IPV6_TIMEOUT_MS: u64 = 5_000;
async fn test_bind_ipv6() -> ResultType<SocketAddr> {
use hbb_common::futures::future::FutureExt;
let local_addr = SocketAddr::from(([0u16; 8], 0)); // [::]:0
let socket = UdpSocket::bind(local_addr).await?;
// Nothing is sent - `connect` only makes the kernel pick a route and a source address - so any
// resolvable target answers equally and the whole cost is DNS. Race the lookups rather than
// walk them: this is awaited inline on the connection path, not every STUN host publishes a
// AAAA, and one resolver that hangs must not decide whether this host has v6.
let lookups = hbb_common::webrtc::WebRTCStream::default_stun_servers()
.into_iter()
.map(|stun| {
(async move {
let addr = tokio::net::lookup_host(&stun)
.await?
.find(|x| x.is_ipv6())
.ok_or_else(|| {
anyhow!("Failed to resolve STUN ipv6 server address: {}", stun)
})?;
Ok::<SocketAddr, hbb_common::anyhow::Error>(addr)
})
.boxed()
})
.collect::<Vec<_>>();
let (addr, _) = hbb_common::futures::future::select_ok(lookups).await?;
socket.connect(addr).await?;
// Nothing is sent - `connect` only makes the kernel pick a route and a source address - so
// the target can be any global address, and given as a number it is: this is awaited on the
// connection path, and resolving a STUN host's name first was the one thing on it that
// could wait on the network - for as long as the resolver takes, when there is none.
socket
.connect(SocketAddr::from((IPV6_ROUTE_PROBE, 53)))
.await?;
Ok(socket.local_addr()?)
}
pub async fn test_ipv6() -> Option<tokio::task::JoinHandle<()>> {
if PUBLIC_IPV6_ADDR
.lock()
.unwrap()
.1
.map(|x| x.elapsed().as_secs() < 60)
.unwrap_or(false)
{
return None;
// One look and one claim of the minute, under one lock: two connections arriving
// together would otherwise both find it over and both probe.
let mut cached = PUBLIC_IPV6_ADDR.lock().unwrap();
if cached
.1
.map(|x| x.elapsed().as_secs() < 60)
.unwrap_or(false)
{
return None;
}
cached.1 = Some(Instant::now());
}
PUBLIC_IPV6_ADDR.lock().unwrap().1 = Some(Instant::now());
match test_bind_ipv6().await {
Ok(mut addr) => {
@@ -2623,8 +2702,8 @@ pub async fn test_ipv6() -> Option<tokio::task::JoinHandle<()>> {
.map(|stun| stun_ipv6_test(stun).boxed())
.collect::<Vec<_>>();
match select_ok(tests).await {
Ok(res) => {
match hbb_common::timeout(STUN_IPV6_TIMEOUT_MS, select_ok(tests)).await {
Ok(Ok(res)) => {
let mut addr = res.0 .0;
addr.set_port(0); // Set port to 0 to avoid conflicts
PUBLIC_IPV6_ADDR.lock().unwrap().0 = Some(addr);
@@ -2634,9 +2713,12 @@ pub async fn test_ipv6() -> Option<tokio::task::JoinHandle<()>> {
addr
);
}
Err(e) => {
Ok(Err(e)) => {
log::error!("Failed to get public IPv6 address: {}", e);
}
Err(_) => {
log::warn!("No STUN server answered for IPv6 within {STUN_IPV6_TIMEOUT_MS}ms");
}
};
}))
}
@@ -3104,6 +3186,21 @@ mod tests {
));
}
#[test]
fn test_should_throttle_log() {
assert!(should_throttle_log("https://example.com/api/heartbeat"));
assert!(should_throttle_log(
"https://example.com/api/heartbeat?token=secret"
));
assert!(should_throttle_log("https://example.com/prefix/api/heartbeat"));
assert!(!should_throttle_log("https://example.com/api/heartbeat2"));
assert!(!should_throttle_log("https://example.com/api/sysinfo"));
assert!(!should_throttle_log(
"https://example.com/api/sysinfo?next=/api/heartbeat"
));
assert!(!should_throttle_log("not a url"));
}
#[test]
fn test_get_tcp_proxy_addr_normalizes_bare_ipv6_host() {
struct RestoreCustomRendezvousServer(String);
@@ -3318,6 +3415,26 @@ mod tests {
(encode64(pk.0), sk)
}
fn signed_key_exchange(
pk: &box_::PublicKey,
sk: &sign::SecretKey,
version: u32,
) -> KeyExchange {
let params = KxParams {
pk: pk.0.to_vec().into(),
version,
..Default::default()
};
let mut payload = hbb_common::tcp::KX_PARAMS_DOMAIN.to_vec();
payload.extend_from_slice(&params.write_to_bytes().unwrap());
KeyExchange {
keys: vec![sign::sign(&pk.0, sk).into()],
version,
signed_params: sign::sign(&payload, sk).into(),
..Default::default()
}
}
async fn connect(host: &str) -> Stream {
hbb_common::socket_client::connect_tcp(host.to_owned(), 3000)
.await
@@ -3379,6 +3496,248 @@ mod tests {
assert!(conn.is_secured());
}
// The stand-in does what hbbs does at version 1: advertises it and splits the exchanged key
// over the same transcript. Neither side's unit tests can catch a client that puts a
// different byte string into the transcript than the server does; only a frame crossing
// between the two can.
#[tokio::test]
async fn test_secure_tcp_version_1_keys_match_the_server_both_ways() {
let (key, sk) = server_key();
let host = rendezvous_stub(move |mut s| async move {
let (eph_pk, eph_sk) = box_::gen_keypair();
let mut msg = RendezvousMessage::new();
msg.set_key_exchange(KeyExchange {
keys: vec![sign::sign(&eph_pk.0, &sk).into()],
version: 1,
..Default::default()
});
s.send(&msg).await.unwrap();
let reply = s.next_timeout(3000).await.unwrap().unwrap();
let reply = RendezvousMessage::parse_from_bytes(&reply).unwrap();
let Some(rendezvous_message::Union::KeyExchange(ex)) = reply.union else {
panic!("expected the client's key exchange");
};
let shared =
hbb_common::tcp::Encrypt::decode(&ex.keys[1], &ex.keys[0], &eph_sk).unwrap();
s.set_key_split(
shared,
false,
&hbb_common::tcp::KxTranscript {
initiator_pk: &ex.keys[0],
responder_pk: &eph_pk.0,
advertised: 1,
picked: ex.version,
},
)
.unwrap();
// Answers with the request's serial, so the client learns from its own reply that
// the request was read under the right key.
let request = s.next_timeout(3000).await.unwrap().unwrap();
let request = RendezvousMessage::parse_from_bytes(&request).unwrap();
let Some(rendezvous_message::Union::TestNatRequest(nat)) = request.union else {
panic!("expected the client's nat request");
};
let mut msg = RendezvousMessage::new();
msg.set_test_nat_response(TestNatResponse {
port: nat.serial,
..Default::default()
});
s.send(&msg).await.unwrap();
})
.await;
let mut conn = connect(&host).await;
secure_tcp_required(&mut conn, &key).await.unwrap();
let mut msg = RendezvousMessage::new();
msg.set_test_nat_request(TestNatRequest {
serial: 7,
..Default::default()
});
conn.send(&msg).await.unwrap();
let reply = conn.next_timeout(3000).await.unwrap().unwrap();
let reply = RendezvousMessage::parse_from_bytes(&reply).unwrap();
let Some(rendezvous_message::Union::TestNatResponse(nat)) = reply.union else {
panic!("expected the server's nat response");
};
assert_eq!(nat.port, 7);
}
#[tokio::test]
async fn test_secure_tcp_legacy_and_signed_servers_exchange_application_data() {
for (advertised, signed) in [(0, false), (1, true), (3, true)] {
for required in [false, true] {
let (key, sk) = server_key();
let host = rendezvous_stub(move |mut s| async move {
let (mut eph_pk, eph_sk) = box_::gen_keypair();
let mut msg = RendezvousMessage::new();
let ex = if signed {
eph_pk.0[31] |= 0x80;
signed_key_exchange(&eph_pk, &sk, advertised)
} else {
KeyExchange {
keys: vec![sign::sign(&eph_pk.0, &sk).into()],
..Default::default()
}
};
msg.set_key_exchange(ex);
s.send(&msg).await.unwrap();
let reply = s.next_timeout(3000).await.unwrap().unwrap();
let reply = RendezvousMessage::parse_from_bytes(&reply).unwrap();
let Some(rendezvous_message::Union::KeyExchange(ex)) = reply.union else {
panic!("expected the client's key exchange");
};
assert_eq!(ex.keys.len(), 2);
assert_eq!(ex.version, hbb_common::tcp::kx_version_for(advertised));
let shared =
hbb_common::tcp::Encrypt::decode(&ex.keys[1], &ex.keys[0], &eph_sk)
.unwrap();
if ex.version >= 1 {
s.set_key_split(
shared,
false,
&hbb_common::tcp::KxTranscript {
initiator_pk: &ex.keys[0],
responder_pk: &eph_pk.0,
advertised,
picked: ex.version,
},
)
.unwrap();
} else {
s.set_key(shared);
}
let request = s.next_timeout(3000).await.unwrap().unwrap();
let request = RendezvousMessage::parse_from_bytes(&request).unwrap();
let Some(rendezvous_message::Union::TestNatRequest(nat)) = request.union else {
panic!("expected the client's nat request");
};
let mut msg = RendezvousMessage::new();
msg.set_test_nat_response(TestNatResponse {
port: nat.serial,
..Default::default()
});
s.send(&msg).await.unwrap();
})
.await;
let mut conn = connect(&host).await;
if required {
secure_tcp_required(&mut conn, &key).await.unwrap();
} else {
secure_tcp(&mut conn, &key).await.unwrap();
}
assert!(conn.is_secured());
let mut msg = RendezvousMessage::new();
msg.set_test_nat_request(TestNatRequest {
serial: 7,
..Default::default()
});
conn.send(&msg).await.unwrap();
let reply = conn.next_timeout(3000).await.unwrap().unwrap();
let reply = RendezvousMessage::parse_from_bytes(&reply).unwrap();
let Some(rendezvous_message::Union::TestNatResponse(nat)) = reply.union else {
panic!("expected the server's nat response");
};
assert_eq!(nat.port, 7);
}
}
}
#[tokio::test]
async fn test_secure_tcp_rejects_unverified_versions_before_reply() {
let (key, sk) = server_key();
let (mut eph_pk, _) = box_::gen_keypair();
eph_pk.0[31] |= 0x80;
let (other_pk, _) = box_::gen_keypair();
let (_, other_sk) = sign::gen_keypair();
for case in [
"missing_signature",
"stripped_version_and_signature",
"cleared_marker_and_stripped_fields",
"lowered_version",
"raised_version",
"replaced_public_key",
"invalid_signature",
"wrong_signer",
"unstructured_payload",
"undomained_params",
"signed_id_pk_as_params",
] {
let mut ex = signed_key_exchange(&eph_pk, &sk, 1);
match case {
"missing_signature" => ex.signed_params = Bytes::new(),
"stripped_version_and_signature" => {
ex.signed_params = Bytes::new();
ex.version = 0;
}
"cleared_marker_and_stripped_fields" => {
let mut signed_pk = ex.keys[0].to_vec();
*signed_pk.last_mut().unwrap() &= 0x7f;
ex.keys[0] = signed_pk.into();
ex.signed_params = Bytes::new();
ex.version = 0;
}
"lowered_version" => ex.version = 0,
"raised_version" => ex.version = 2,
"replaced_public_key" => ex.keys[0] = sign::sign(&other_pk.0, &sk).into(),
"invalid_signature" => {
let mut signed = ex.signed_params.to_vec();
signed[0] ^= 1;
ex.signed_params = signed.into();
}
"wrong_signer" => {
ex.signed_params = signed_key_exchange(&eph_pk, &other_sk, 1).signed_params;
}
"unstructured_payload" => {
let mut payload = eph_pk.0.to_vec();
payload.extend_from_slice(&1u32.to_le_bytes());
ex.signed_params = sign::sign(&payload, &sk).into();
}
"undomained_params" => {
let params = KxParams {
pk: eph_pk.0.to_vec().into(),
version: 1,
..Default::default()
};
ex.signed_params = sign::sign(&params.write_to_bytes().unwrap(), &sk).into();
}
"signed_id_pk_as_params" => {
// The server signs IdPk with the same key; its `id` sits where `pk` does.
let mut pk = [0x2au8; box_::PUBLICKEYBYTES];
pk[30] = 0xc2;
pk[31] = 0xaa;
let id_pk = IdPk {
id: String::from_utf8(pk.to_vec()).unwrap(),
pk: vec![7u8; box_::PUBLICKEYBYTES].into(),
..Default::default()
};
ex.keys[0] = sign::sign(&pk, &sk).into();
ex.version = 0;
ex.signed_params = sign::sign(&id_pk.write_to_bytes().unwrap(), &sk).into();
}
_ => unreachable!(),
}
for required in [false, true] {
let mut msg = RendezvousMessage::new();
msg.set_key_exchange(ex.clone());
let (tx, rx) = tokio::sync::oneshot::channel();
let host = rendezvous_stub(move |mut s| async move {
s.send(&msg).await.unwrap();
tx.send(s.next_timeout(3000).await.is_none()).unwrap();
})
.await;
let mut conn = connect(&host).await;
let result = if required {
secure_tcp_required(&mut conn, &key).await
} else {
secure_tcp(&mut conn, &key).await
};
assert!(result.is_err(), "accepted {case}, required={required}");
assert!(!conn.is_secured());
drop(conn);
assert!(rx.await.unwrap(), "replied to {case}, required={required}");
}
}
}
#[test]
fn test_dtls_fingerprint_travels_signed_and_binds() {
let (pk, sk) = sign::gen_keypair();
@@ -3395,7 +3754,7 @@ mod tests {
&sk,
);
let (id, their_pk, signed_fp) = decode_id_pk_dtls(&signed, &pk).unwrap();
let (id, their_pk, signed_fp, _) = decode_id_pk_dtls(&signed, &pk).unwrap();
assert_eq!(id, "123456789");
assert_eq!(their_pk, [7u8; 32]);
assert_eq!(signed_fp, fp);
@@ -3416,4 +3775,11 @@ mod tests {
// non-WebRTC handshakes.
assert_eq!(decode_id_pk(&signed, &pk).unwrap(), (id, their_pk));
}
// The route probe is awaited on the connection path, so whatever it finds - an address, or
// no IPv6 route on this machine - it finds without waiting on the network.
#[tokio::test]
async fn test_ipv6_route_probe_does_not_wait_on_the_network() {
assert!(hbb_common::timeout(1_000, test_bind_ipv6()).await.is_ok());
}
}
+11 -1
View File
@@ -105,6 +105,16 @@ fn load_plugin_in_app_path(dll_name: &str) -> Result<Library, LibError> {
#[cfg(not(windows))]
#[no_mangle]
pub extern "C" fn rustdesk_core_main() -> bool {
#[cfg(any(target_os = "linux", target_os = "macos"))]
{
use hbb_common::libc;
// Native runners bypass Rust's startup, which normally ignores SIGPIPE.
if unsafe { libc::signal(libc::SIGPIPE, libc::SIG_IGN) } == libc::SIG_ERR {
eprintln!("Failed to ignore SIGPIPE: {}", std::io::Error::last_os_error());
std::process::exit(1);
}
}
#[cfg(not(any(target_os = "android", target_os = "ios")))]
if crate::core_main::core_main().is_some() {
return true;
@@ -642,7 +652,7 @@ impl FlutterHandler {
impl InvokeUiSession for FlutterHandler {
fn set_cursor_data(&self, cd: CursorData) {
let colors = hbb_common::compress::decompress(&cd.colors);
let colors = &cd.colors;
self.push_event(
"cursor_data",
&[
+6 -2
View File
@@ -5,7 +5,7 @@ use std::{
};
#[cfg(not(any(target_os = "ios")))]
use crate::{ui_interface::get_builtin_option, Connection};
use crate::{common::API_LOG_INTERVAL, ui_interface::get_builtin_option, Connection};
use hbb_common::{
config::{self, Config, LocalConfig},
log,
@@ -242,7 +242,11 @@ async fn start_hbbs_sync_async() {
}
let modified_at = LocalConfig::get_option("strategy_timestamp").parse::<i64>().unwrap_or(0);
v["modified_at"] = json!(modified_at);
if let Ok(s) = crate::post_request(url.clone(), v.to_string(), "").await {
let response = crate::post_request(url.clone(), v.to_string(), "").await;
if let Err(err) = &response {
hbb_common::throttled_log!(API_LOG_INTERVAL, warn, "Heartbeat failed: {err:?}");
}
if let Ok(s) = response {
if let Ok(mut rsp) = serde_json::from_str::<HashMap::<&str, Value>>(&s) {
if rsp.remove("sysinfo").is_some() {
info_uploaded.uploaded = false;
+59
View File
@@ -555,9 +555,29 @@ pub enum Data {
height: u32,
hotx: i32,
hoty: i32,
/// Whether the hotspot came from the driver, or was inferred from the bitmap.
///
/// Absent means the producer predates the field, and the default must then be TRUE, not
/// `bool::default()`. These messages are JSON over a unix socket between two processes
/// that are upgraded separately: an old root service can be streaming to a freshly
/// started `--server`, and its `{"hotx": 12, "hoty": 11}` carries no provenance. Read as
/// `false`, the new consumer would throw that hotspot away and re-infer one from the
/// upright bitmap, moving the cursor on a rotated display for the length of the upgrade.
/// Defaulting to true means "no provenance available, so behave as the old protocol did"
/// -- use the point the producer sent. It is not a claim that the value was measured; a
/// new producer that wants re-inference says `hot_measured: false` explicitly, which
/// serializes, so new-to-new is unaffected.
#[serde(default = "legacy_hot_measured")]
hot_measured: bool,
},
}
/// The default for a `hot_measured` that is not on the wire at all; see the field's docs.
#[cfg(all(target_os = "linux", feature = "drm"))]
fn legacy_hot_measured() -> bool {
true
}
#[tokio::main(flavor = "current_thread")]
pub async fn start(postfix: &str) -> ResultType<()> {
let mut incoming = new_listener(postfix).await?;
@@ -2310,4 +2330,43 @@ mod test {
fn test_select_server_uid_fails_when_multiple_servers_are_ambiguous() {
assert!(select_server_uid_for_user_main_ipc(&[501, 502], None, false).is_err());
}
/// The upgrade window: an old root service is still streaming when a new `--server` starts,
/// and its DrmCursor carries no `hot_measured` at all. Read as `false` the consumer would
/// discard a hotspot the producer did measure and re-infer one from the bitmap, which moves
/// the cursor on a rotated display until the old process is replaced. `bool::default()` is
/// the wrong default here; the right one preserves what the old protocol meant.
#[cfg(all(target_os = "linux", feature = "drm"))]
#[test]
fn a_drm_cursor_without_provenance_keeps_the_hotspot_the_producer_sent() {
// `Data` is adjacently tagged (`tag = "t", content = "c"`), so this is the real shape on
// the socket, not a simplified one.
let legacy =
r#"{"t":"DrmCursor","c":{"id":7,"width":24,"height":24,"hotx":12,"hoty":11}}"#;
let msg: Data = serde_json::from_str(legacy).expect("legacy DrmCursor must deserialize");
match msg {
Data::DrmCursor {
hotx,
hoty,
hot_measured,
..
} => {
assert_eq!((hotx, hoty), (12, 11));
assert!(
hot_measured,
"a message with no provenance field must be treated as the old protocol did, \
i.e. use the hotspot as sent, not re-infer it"
);
}
other => panic!("expected DrmCursor, got {other:?}"),
}
// And a NEW producer that really wants re-inference says so, which serializes: the
// default must not swallow an explicit false.
let modern = r#"{"t":"DrmCursor","c":{"id":7,"width":24,"height":24,"hotx":0,"hoty":0,"hot_measured":false}}"#;
match serde_json::from_str::<Data>(modern).expect("modern DrmCursor must deserialize") {
Data::DrmCursor { hot_measured, .. } => assert!(!hot_measured),
other => panic!("expected DrmCursor, got {other:?}"),
}
}
}
+4
View File
@@ -107,6 +107,7 @@ enum DrmProducerMsg {
height: u32,
hotx: i32,
hoty: i32,
hot_measured: bool,
colors: Vec<u8>,
},
}
@@ -915,6 +916,7 @@ async fn handle_drm_conn(stream: Connection) -> ResultType<()> {
height,
hotx,
hoty,
hot_measured,
colors,
} => {
conn.send_msg(
@@ -924,6 +926,7 @@ async fn handle_drm_conn(stream: Connection) -> ResultType<()> {
height,
hotx,
hoty,
hot_measured,
},
None,
)
@@ -1115,6 +1118,7 @@ fn drm_capture_worker(
height: c.height,
hotx: c.hotx,
hoty: c.hoty,
hot_measured: c.hot_measured,
colors: c.colors,
})
.is_err()
+40 -1
View File
@@ -34,6 +34,7 @@ mod nb;
mod nl;
mod pl;
mod ptbr;
mod pt_PT;
mod ro;
mod ru;
mod sc;
@@ -63,7 +64,8 @@ pub const LANGS: &[(&str, &str)] = &[
("nb", "Norsk bokmål"),
("zh-cn", "简体中文"),
("zh-tw", "繁體中文"),
("pt", "Português"),
("pt-pt", "Português (Portugal)"),
("pt-br", "Português (Brasil)"),
("es", "Español"),
("et", "Eesti keel"),
("eu", "Euskara"),
@@ -143,6 +145,21 @@ fn resolve_lang(saved_lang: &str, locale: &str, cjk_fallback: bool) -> String {
.to_owned();
}
}
if lang.is_empty() {
// pt_PT on Linux, pt-PT on mac, pt_PT on Android.
// Per CLDR locale inheritance, every Portuguese-speaking locale
// besides bare "pt" and Brazil's own variants (pt-BR/pt_BR) has
// pt-PT as its parent (Angola, Mozambique, Cape Verde, etc.),
// so it should resolve to European Portuguese.
if locale.starts_with("pt") {
lang = (if locale == "pt" || locale.starts_with("pt-br") || locale.starts_with("pt_br") {
"pt-br"
} else {
"pt-pt"
})
.to_owned();
}
}
if lang.is_empty() {
lang = locale
.split("-")
@@ -187,6 +204,8 @@ pub fn translate_locale(name: String, locale: &str) -> String {
"id" => id::T.deref(),
"br" => ptbr::T.deref(),
"pt" => ptbr::T.deref(),
"pt-br" => ptbr::T.deref(),
"pt-pt" => pt_PT::T.deref(),
"tr" => tr::T.deref(),
"cs" => cs::T.deref(),
"da" => da::T.deref(),
@@ -344,4 +363,24 @@ mod test {
assert_eq!(f("", "zh_TW", false), "zh-tw");
assert_eq!(f("", "ja-JP", false), "ja");
}
#[test]
fn test_resolve_lang_detects_pt_pt_and_pt_br_from_locale() {
use super::resolve_lang as f;
assert_eq!(f("", "pt-PT", false), "pt-pt");
assert_eq!(f("", "pt_PT", false), "pt-pt");
assert_eq!(f("", "pt-BR", false), "pt-br");
assert_eq!(f("", "pt_BR", false), "pt-br");
assert_eq!(f("", "pt-AO", false), "pt-pt");
assert_eq!(f("", "pt-MZ", false), "pt-pt");
}
#[test]
fn test_resolve_lang_saved_lang_takes_precedence_over_locale() {
use super::resolve_lang as f;
assert_eq!(f("pt-br", "pt-PT", false), "pt-br");
assert_eq!(f("pt-pt", "pt-BR", false), "pt-pt");
}
}
+2 -2
View File
@@ -763,7 +763,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("Lock canvas", "锁定画布"),
("Sync clipboard between sessions", "在会话间同步剪贴板"),
("sync-clipboard-between-sessions-tip", "在一个远程会话中复制的文本或图片也会发送到其他已连接会话的剪贴板。"),
("terminal-clipboard-write-tip", ""),
("terminal-clipboard-write-tip", "终端中的一个应用希望将文本复制到此设备的剪贴板。如果授权,此权限将适用于所有连接中的终端应用,直到您在设置中关闭为止。手动复制和粘贴不受影响。"),
("Allow terminal apps to copy to clipboard", "允许终端应用复制到剪贴板"),
("Enable", "启用"),
("Reuse one connection for port forwarding", "端口转发复用同一条连接"),
@@ -780,6 +780,6 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("RustDesk could not load a GStreamer component needed for screen capture ({})", "RustDesk 无法加载屏幕捕获所需的 GStreamer 组件 ({})"),
("Relay fallback delay in seconds", "回落到中继前的等待时间(秒)"),
("relay-fallback-delay-tip", "已经建立的中继连接会等待直连的 WebRTC 多久,超过这个时间就改用中继。调大可以让较慢的直连有更多机会胜出;调小则在无法直连的网络上更快回落到中继。留空表示使用默认值 2.5 秒。"),
("To start a voice call, enable \"Audio capture\" on the \"Screen share\" page.", "")
("To start a voice call, enable \"Audio capture\" on the \"Screen share\" page.", "开始语音通话前请在\"仅共享屏幕\"页面启用\"音频录制\"。")
].iter().cloned().collect();
}
+1 -1
View File
@@ -780,6 +780,6 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("RustDesk could not load a GStreamer component needed for screen capture ({})", "RustDesk kon een GStreamer-component die nodig is voor schermopname niet laden ({})"),
("Relay fallback delay in seconds", "Vertraging voordat relay wordt gebruikt in seconden"),
("relay-fallback-delay-tip", "Hoe lang een al tot stand gekomen relayverbinding wacht op de directe WebRTC-verbinding voordat deze in plaats daarvan wordt gebruikt. Verhoog de waarde om een trage directe verbinding meer tijd te geven; verlaag deze om op netwerken waar een directe verbinding niet mogelijk is sneller op de relay terug te vallen. Laat leeg voor de standaardwaarde van 2.5 seconden."),
("To start a voice call, enable \"Audio capture\" on the \"Screen share\" page.", "")
("To start a voice call, enable \"Audio capture\" on the \"Screen share\" page.", "Om een spraakgesprek te starten, schakel je \"Audio-opname\" in op de pagina \"Scherm delen\".")
].iter().cloned().collect();
}
+42 -42
View File
@@ -4,7 +4,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("Status", "Estado"),
("Your Desktop", "Ambiente de Trabalho"),
("desk_tip", "O seu Ambiente de Trabalho pode ser acedido com este ID e palavra-passe."),
("Password", "Senha"),
("Password", "Palavra-passe"),
("Ready", "Pronto"),
("Established", "Estabelecido"),
("connecting_status", "A ligar à rede do RustDesk..."),
@@ -21,7 +21,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("Confirmation", "Confirmação"),
("TCP tunneling", "Túnel TCP"),
("Remove", "Remover"),
("Refresh random password", "Actualizar palavra-chave"),
("Refresh random password", "Actualizar palavra-passe"),
("Set your own password", "Configure a sua palavra-passe"),
("Enable keyboard/mouse", "Activar Teclado/Rato"),
("Enable clipboard", "Activar Área de Transferência"),
@@ -68,10 +68,10 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("Close", "Fechar"),
("Retry", "Tentar novamente"),
("OK", "Confirmar"),
("Password Required", "Palavra-chave Necessária"),
("Please enter your password", "Por favor introduza a sua palavra-chave"),
("Remember password", "Memorizar palavra-chave"),
("Wrong Password", "Palavra-chave inválida"),
("Password Required", "Palavra-passe Necessária"),
("Please enter your password", "Por favor introduza a sua palavra-passe"),
("Remember password", "Memorizar palavra-passe"),
("Wrong Password", "Palavra-passe inválida"),
("Do you want to enter again?", "Deseja tentar novamente??"),
("Connection Error", "Erro de Ligação"),
("Error", "Erro"),
@@ -102,9 +102,9 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("Unselect All", "Desmarcar todos"),
("Empty Directory", "Directório Vazio"),
("Not an empty directory", "Directório não está vazio"),
("Are you sure you want to delete this file?", "Tem certeza que deseja apagar este ficheiro?"),
("Are you sure you want to delete this empty directory?", "Tem certeza que deseja apagar este directório vazio?"),
("Are you sure you want to delete the file of this directory?", "Tem certeza que deseja apagar este ficheiro deste directório?"),
("Are you sure you want to delete this file?", "Tem a certeza que deseja apagar este ficheiro?"),
("Are you sure you want to delete this empty directory?", "Tem a certeza que deseja apagar este diretório vazio?"),
("Are you sure you want to delete the file of this directory?", "Tem a certeza que deseja apagar este ficheiro deste diretório?"),
("Do this for all conflicts", "Fazer isto para todos os conflictos"),
("This is irreversible!", "Isto é irreversível!"),
("Deleting", "A apagar"),
@@ -142,21 +142,21 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("Failed to connect to relay server", "Falha ao ligar ao servidor de relay"),
("Failed to connect via rendezvous server", "Falha ao ligar ao servidor de rendezvous"),
("Failed to connect via relay server", "Falha ao ligar através do servidor de relay"),
("Failed to make direct connection to remote desktop", "Falha ao fazer ligação directa ao desktop remoto"),
("Set Password", "Definir palavra-chave"),
("OS Password", "Senha do SO"),
("Failed to make direct connection to remote desktop", "Falha ao fazer ligação directa ao ambiente de trabalho remoto"),
("Set Password", "Definir palavra-passe"),
("OS Password", "Palavra-Passe do SO"),
("install_tip", "Devido ao UAC, o RustDesk não funciona correctamente em alguns casos. Para evitar o UAC, por favor clique no botão abaixo para instalar o RustDesk no sistema."),
("Click to upgrade", "Clique para atualizar"),
("Configure", "Configurar"),
("config_acc", "Para controlar o seu Ambiente de Trabalho remotamente, é preciso conceder ao RustDesk permissões de \"Acessibilidade\"."),
("config_screen", "Para aceder ao seu Ambiente de Trabalho remotamente, é preciso conceder ao RustDesk permissões de \"Gravar a Tela\"/"),
("config_screen", "Para aceder ao seu Ambiente de Trabalho remotamente, é preciso conceder ao RustDesk permissões de \"Gravar o Ecrã\"."),
("Installing ...", "A Instalar ..."),
("Install", "Instalar"),
("Installation", "Instalação"),
("Installation Path", "Caminho da Instalação"),
("Create start menu shortcuts", "Criar atalhos no menu iniciar"),
("Create desktop icon", "Criar ícone no ambiente de trabalho"),
("agreement_tip", "Ao iniciar a instalação, você concorda com o acordo de licença."),
("agreement_tip", "Ao iniciar a instalação, está a concordar com o acordo de licença."),
("Accept and Install", "Aceitar e Instalar"),
("End-user license agreement", "Acordo de licença do utilizador final"),
("Generating ...", "A Gerar ..."),
@@ -170,13 +170,13 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("Local Port", "Porta Local"),
("Local Address", "Endereço local"),
("Change Local Port", "Alterar porta local"),
("setup_server_tip", "Para uma ligação mais rápida, por favor configure seu próprio servidor"),
("setup_server_tip", "Para uma ligação mais rápida, por favor configure o seu próprio servidor"),
("Too short, at least 6 characters.", "Muito curto, pelo menos 6 caracteres."),
("The confirmation is not identical.", "A confirmação não é idêntica."),
("Permissions", "Permissões"),
("Accept", "Aceitar"),
("Dismiss", "Dispensar"),
("Disconnect", "Desconectar"),
("Disconnect", "Desligar"),
("Enable file copy and paste", "Permitir copiar e mover ficheiros"),
("Connected", "Ligado"),
("Direct and encrypted connection", "Ligação directa e encriptada"),
@@ -184,10 +184,10 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("Direct and unencrypted connection", "Ligação direta e não encriptada"),
("Relayed and unencrypted connection", "Ligação via relay e não encriptada"),
("Enter Remote ID", "Introduza o ID Remoto"),
("Enter your password", "Introduza a sua palavra-chave"),
("Enter your password", "Introduza a sua palavra-passe"),
("Logging in...", "A efectuar Login..."),
("Enable RDP session sharing", "Activar partilha de sessão RDP"),
("Auto Login", "Login Automático (Somente válido se você activou \"Bloquear após o fim da sessão\")"),
("Auto Login", "Login Automático (Apenas válido se tiver activado \"Bloquear após o fim da sessão\")"),
("Enable direct IP access", "Activar Acesso IP Directo"),
("Rename", "Renomear"),
("Space", "Espaço"),
@@ -197,7 +197,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("Please enter the folder name", "Por favor introduza o nome do diretório"),
("Fix it", "Reparar"),
("Warning", "Aviso"),
("Login screen using Wayland is not supported", "Tela de Login com Wayland não é suportada"),
("Login screen using Wayland is not supported", "Ecrã de Início de Sessão com Wayland não é suportado"),
("Reboot required", "Reinicialização necessária"),
("Unsupported display server", "Servidor de display não suportado"),
("x11 expected", "x11 em falha"),
@@ -209,7 +209,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("Enable remote configuration modification", "Habilitar modificações de configuração remotas"),
("Run without install", "Executar sem instalar"),
("Connect via relay", "Ligar via relay"),
("Always connect via relay", "Sempre conectar via relay"),
("Always connect via relay", "Ligar sempre via relay"),
("whitelist_tip", "Somente IPs na whitelist podem me acessar"),
("Login", "Login"),
("Verify", "Verificar"),
@@ -226,11 +226,11 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("Unselect all tags", "Desselecionar todas as tags"),
("Network error", "Erro de rede"),
("Username missed", "Nome de utilizador em falta"),
("Password missed", "Palavra-chave em falta"),
("Wrong credentials", "Nome de utilizador ou palavra-chave incorrectos"),
("Password missed", "Palavra-passe em falta"),
("Wrong credentials", "Nome de utilizador ou palavra-passe incorrectos"),
("The verification code is incorrect or has expired", "O código de verificação está incorreto ou expirou"),
("Edit Tag", "Editar Tag"),
("Forget Password", "Esquecer Palavra-chave"),
("Forget Password", "Esquecer Palavra-passe"),
("Favorites", "Favoritos"),
("Add to Favorites", "Adicionar aos Favoritos"),
("Remove from Favorites", "Remover dos Favoritos"),
@@ -243,7 +243,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("Remote ID", "ID Remoto"),
("Paste", "Colar"),
("Paste here?", "Colar aqui?"),
("Are you sure to close the connection?", "Tem certeza que deseja fechar a ligação?"),
("Are you sure to close the connection?", "Tem a certeza que deseja fechar a ligação?"),
("Download new version", "Transferir nova versão"),
("Touch mode", "Modo toque"),
("Mouse mode", "Modo rato"),
@@ -258,10 +258,10 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("Three-Finger vertically", "Três dedos verticalmente"),
("Mouse Wheel", "Roda do rato"),
("Two-Finger Move", "Mover com dois dedos"),
("Canvas Move", "Mover Tela"),
("Canvas Move", "Mover Ecrã"),
("Pinch to Zoom", "Clique para ampliar"),
("Canvas Zoom", "Zoom na Tela"),
("Reset canvas", "Reiniciar tela"),
("Canvas Zoom", "Zoom no Ecrã"),
("Reset canvas", "Reiniciar ecrã"),
("No permission of file transfer", "Sem permissões de transferência de ficheiro"),
("Note", "Nota"),
("Connection", "Ligação"),
@@ -276,7 +276,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("Do you accept?", "Aceita?"),
("Open System Setting", "Abrir Configurações do Sistema"),
("How to get Android input permission?", "Como activar a permissão de entrada do Android?"),
("android_input_permission_tip1", "Para que um dispositivo remoto controle o seu dispositivo Android via rato ou toque, você precisa permitir que o RustDesk use o serviço \"Acessibilidade\"."),
("android_input_permission_tip1", "Para que um dispositivo remoto controle o seu dispositivo Android via rato ou toque, é necessário permitir que o RustDesk use o serviço \"Acessibilidade\"."),
("android_input_permission_tip2", "Por favor vá para a próxima página de configuração do sistema, encontre e entre [Serviços Instalados], ACTIVE o serviço [RustDesk Input]."),
("android_new_connection_tip", "Nova requisição de controle recebida, solicita o controle do seu dispositivo atual."),
("android_service_will_start_tip", "Activar a Captura de Ecran irá automaticamente inicializar o serviço, permitindo que outros dispositivos solicitem uma ligação deste dispositivo."),
@@ -307,18 +307,18 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("Legacy mode", "Modo antigo"),
("Map mode", "Modo de mapeamento"),
("Translate mode", "Modo de tradução"),
("Use permanent password", "Utilizar palavra-chave permanente"),
("Use permanent password", "Utilizar palavra-passe permanente"),
("Use both passwords", "Utilizar ambas as palavras-chave"),
("Set permanent password", "Definir palavra-chave permanente"),
("Set permanent password", "Definir palavra-passe permanente"),
("Enable remote restart", "Activar reiniciar remoto"),
("Restart remote device", "Reiniciar Dispositivo Remoto"),
("Are you sure you want to restart", "Tem a certeza que pretende reiniciar"),
("Restarting remote device", "A reiniciar sistema remoto"),
("remote_restarting_tip", "O dispositivo remoto está a reiniciar, feche esta caixa de mensagem e volte a ligar com a palavra-passe permanente daqui a momentos"),
("Copied", "Copiado"),
("Exit Fullscreen", "Sair da tela cheia"),
("Fullscreen", "Tela cheia"),
("Mobile Actions", "Ações para celular"),
("Exit Fullscreen", "Sair do Ecrã Inteiro"),
("Fullscreen", "Ecrã Inteiro"),
("Mobile Actions", "Ações para telemóvel"),
("Select Monitor", "Selecionar monitor"),
("Control Actions", "Ações de controle"),
("Display Settings", "Configurações do visor"),
@@ -327,10 +327,10 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("Scroll Style", "Estilo de rolagem"),
("Show Toolbar", "Mostrar barra de ferramentas"),
("Hide Toolbar", "Ocultar barra de ferramentas"),
("Direct Connection", "Conexão direta"),
("Relay Connection", "Conexão de relé"),
("Secure Connection", "Conexão segura"),
("Insecure Connection", "Conexão insegura"),
("Direct Connection", "Ligação direta"),
("Relay Connection", "Ligação de relay"),
("Secure Connection", "Ligação segura"),
("Insecure Connection", "Ligação insegura"),
("Scale original", "Escala original"),
("Scale adaptive", "Escala adaptável"),
("General", "Geral"),
@@ -377,10 +377,10 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("Full Access", "Controlo total"),
("Screen Share", "Partilha de ecrã"),
("ubuntu-21-04-required", "Wayland requer Ubuntu 21.04 ou versão superior."),
("wayland-requires-higher-linux-version", "Wayland requer uma versão superior da distribuição linux. Por favor, tente o desktop X11 ou mude seu sistema operacional."),
("wayland-requires-higher-linux-version", "Wayland requer uma versão superior da distribuição Linux. Por favor, tente o ambiente de trabalho X11 ou mude o seu sistema operativo."),
("xdp-portal-unavailable", "A captura de ecrã do Wayland falhou. O XDG Desktop Portal poderá ter falhado ou estar indisponível. Tente reiniciá-lo com `systemctl --user restart xdg-desktop-portal`."),
("JumpLink", "View"),
("Please Select the screen to be shared(Operate on the peer side).", "Por favor, selecione a tela a ser compartilhada (operar no lado do peer)."),
("Please Select the screen to be shared(Operate on the peer side).", "Por favor, selecione o ecrã a partilhar (operar no lado do par)."),
("Show RustDesk", "Mostrar RustDesk"),
("This PC", "Este PC"),
("or", "ou"),
@@ -760,11 +760,11 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("whitelist_cidr_tip", "A notação CIDR é suportada, por exemplo 192.168.1.0/24"),
("Continue", "Continuar"),
("Browser didn't open? Use the url below to sign in.", "O navegador não abriu? Utilize o URL abaixo para iniciar sessão."),
("Lock canvas", "Bloquear tela"),
("Lock canvas", "Bloquear ecrã"),
("Sync clipboard between sessions", "Sincronizar área de transferência entre sessões"),
("sync-clipboard-between-sessions-tip", "O texto ou as imagens copiados numa sessão remota também são enviados para a área de transferência das suas outras sessões ligadas."),
("terminal-clipboard-write-tip", ""),
("Allow terminal apps to copy to clipboard", ""),
("terminal-clipboard-write-tip", "Uma aplicação no terminal pretende copiar texto para a área de transferência deste dispositivo. Se autorizada, esta permissão aplica-se a aplicações de terminal em todas as ligações até a desativar nas Configurações. A cópia e colagem manuais não são afetadas."),
("Allow terminal apps to copy to clipboard", "Permitir cópia do terminal para a área de transferência"),
("Enable", "Ativar"),
("Reuse one connection for port forwarding", "Reutilizar uma ligação para o reencaminhamento de portas"),
("port-forward-mux-tip", "Encaminhar todas as ligações de um reencaminhamento de portas por uma única ligação ao outro computador, em vez de ligar e iniciar sessão novamente para cada uma."),
+2 -2
View File
@@ -519,7 +519,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("I Agree", "Eu concordo"),
("Decline", "Recusar"),
("Timeout in minutes", "Tempo limite em minutos"),
("auto_disconnect_option_tip", "Encerrar sessões entrantes automaticamente por inatividade do usuário."),
("auto_disconnect_option_tip", "Encerrar sessões entrantes automaticamente por inatividade."),
("Connection failed due to inactivity", "Conexão encerrada automaticamente por inatividade."),
("Check for software update on startup", "Verificar atualizações do software ao iniciar"),
("upgrade_rustdesk_server_pro_to_{}_tip", "Atualize o RustDesk Server Pro para a versão {} ou superior."),
@@ -576,7 +576,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("share_warning_tip", "Os campos mostrados acima são compartilhados e visíveis por outras pessoas."),
("Everyone", "Todos"),
("ab_web_console_tip", "Mais opções no console web"),
("allow-only-conn-window-open-tip", "Permitir conexões apenas quando a janela do RustDesk estiver aberta"),
("allow-only-conn-window-open-tip", "Permitir conexões somente com o RustDesk aberto"),
("no_need_privacy_mode_no_physical_displays_tip", "Sem telas físicas, o modo privado não é necessário"),
("Follow remote cursor", "Seguir cursor remoto"),
("Follow remote window focus", "Seguir janela remota ativa"),
+3 -3
View File
@@ -763,8 +763,8 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("Lock canvas", "Bloca sa tela"),
("Sync clipboard between sessions", "Sincroniza sa punta de billete intre is sessiones"),
("sync-clipboard-between-sessions-tip", "Su testu o is immàgines copiadas in una sessione remota sunt imbiadas fintzas a sa punta de billete de is àteras sessiones connètidas."),
("terminal-clipboard-write-tip", ""),
("Allow terminal apps to copy to clipboard", ""),
("terminal-clipboard-write-tip", "Un’aplicatzione in su terminale bolet copiare testu in sa punta de billete de custu dispositivu. Si benit frunidu, custu permissu s’àplicat a sas aplicatziones de terminale in totu sas connessiones finas a cando non nche l’istudas in sas Impostatziones. Sas operatziones de còpia e incolla manuales non benint influentzadas."),
("Allow terminal apps to copy to clipboard", "Permite a sas aplicatziones de terminale de copiare in punta de billete"),
("Enable", "Abìlita"),
("Reuse one connection for port forwarding", "Torra a impreare una connessione pro s'imbiu de is portas"),
("port-forward-mux-tip", "Totu is connessiones de un'imbiu de portas passant in una connessione ebbia a s'àteru computadore, in logu de si connètere e intrare torra pro dontzi una."),
@@ -780,6 +780,6 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("RustDesk could not load a GStreamer component needed for screen capture ({})", "RustDesk no at pòdidu carrigare unu cumponente de GStreamer netzessàriu pro registrare sa schermada ({})"),
("Relay fallback delay in seconds", "Tardu prima de impreare su relè in segundos"),
("relay-fallback-delay-tip", "Cantu tempus una connessione de relè giai istabilida abetat sa connessione direta WebRTC prima de èssere impreada in su postu suo. Aumenta pro dare prus tempus a una connessione direta lenta; diminuì pro colare prima a su relè in sas retes in ue non si podet fàghere una connessione direta. Lassa bòidu pro su valore predefinidu de 2.5 segundos."),
("To start a voice call, enable \"Audio capture\" on the \"Screen share\" page.", "")
("To start a voice call, enable \"Audio capture\" on the \"Screen share\" page.", "Pro aviare una mutida de boghe, ativa in sa pàgina \"Cumpartzidura de ischermu\" s’elementu \"Catura de s’àudio\".")
].iter().cloned().collect();
}
+3 -3
View File
@@ -763,8 +763,8 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("Lock canvas", "Tuvali kilitle"),
("Sync clipboard between sessions", "Oturumlar arasında panoyu senkronize et"),
("sync-clipboard-between-sessions-tip", "Bir uzak oturumda kopyalanan metin veya görseller, bağlı diğer oturumlarınızın panosuna da gönderilir."),
("terminal-clipboard-write-tip", ""),
("Allow terminal apps to copy to clipboard", ""),
("terminal-clipboard-write-tip", "Terminaldeki bir uygulama bu cihazın panosuna metin kopyalamak istiyor. İzin verirseniz bu izin, Ayarlar'dan kapatana kadar tüm bağlantılardaki terminal uygulamaları için geçerli olur. Elle kopyalama ve yapıştırma bundan etkilenmez."),
("Allow terminal apps to copy to clipboard", "Terminal uygulamalarının panoya kopyalamasına izin ver"),
("Enable", "Etkinleştir"),
("Reuse one connection for port forwarding", "Port yönlendirme için tek bağlantıyı yeniden kullan"),
("port-forward-mux-tip", "Bir port yönlendirmesindeki tüm bağlantıları, her biri için yeniden bağlanıp oturum açmak yerine karşı tarafa açılan tek bir bağlantı üzerinden taşır."),
@@ -780,6 +780,6 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("RustDesk could not load a GStreamer component needed for screen capture ({})", "RustDesk ekran yakalama için gereken GStreamer bileşenini yükleyemedi ({})"),
("Relay fallback delay in seconds", "Aktarıcıya geçiş gecikmesi (saniye)"),
("relay-fallback-delay-tip", "Zaten kurulmuş bir aktarıcı bağlantısının, onun yerine kullanılmadan önce doğrudan WebRTC bağlantısını ne kadar beklediğidir. Yavaş bir doğrudan bağlantıya daha fazla süre tanımak için artırın; doğrudan bağlantının kurulamadığı ağlarda aktarıcıya daha erken geçmek için azaltın. Varsayılan 2.5 saniye için boş bırakın."),
("To start a voice call, enable \"Audio capture\" on the \"Screen share\" page.", "")
("To start a voice call, enable \"Audio capture\" on the \"Screen share\" page.", "Sesli arama başlatmak için \"Ekran paylaşımı\" sayfasındaki \"Ses yakalama\" seçeneğini açın.")
].iter().cloned().collect();
}
+3 -3
View File
@@ -763,8 +763,8 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("Lock canvas", "Блокування полотна"),
("Sync clipboard between sessions", "Синхронізувати буфер обміну між сеансами"),
("sync-clipboard-between-sessions-tip", "Текст або зображення, скопійовані в одному віддаленому сеансі, також надсилаються до буфера обміну інших підключених сеансів."),
("terminal-clipboard-write-tip", ""),
("Allow terminal apps to copy to clipboard", ""),
("terminal-clipboard-write-tip", "Застосунок у терміналі хоче скопіювати текст до буфера обміну цього пристрою. Якщо надати дозвіл, він застосовуватиметься до термінальних застосунків у всіх підключеннях, доки ви не вимкнете його в налаштуваннях. Ручне копіювання та вставлення працюватимуть як і раніше."),
("Allow terminal apps to copy to clipboard", "Дозволити термінальним застосункам копіювати до буфера обміну"),
("Enable", "Увімкнути"),
("Reuse one connection for port forwarding", "Використовувати одне з'єднання для перенаправлення портів"),
("port-forward-mux-tip", "Передавати всі з'єднання одного перенаправлення портів через одне з'єднання з віддаленим пристроєм замість повторного під'єднання та входу для кожного з них."),
@@ -780,6 +780,6 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("RustDesk could not load a GStreamer component needed for screen capture ({})", "RustDesk не вдалося завантажити компонент GStreamer, потрібний для захоплення екрана ({})"),
("Relay fallback delay in seconds", "Затримка перед переходом на ретранслятор у секундах"),
("relay-fallback-delay-tip", "Скільки часу вже встановлене з'єднання через ретранслятор чекає на пряме з'єднання WebRTC, перш ніж буде використане замість нього. Збільште, щоб дати повільному прямому з'єднанню більше часу; зменште, щоб швидше переходити на ретранслятор у мережах, де пряме з'єднання неможливе. Залиште порожнім для типового значення 2.5 секунди."),
("To start a voice call, enable \"Audio capture\" on the \"Screen share\" page.", "")
("To start a voice call, enable \"Audio capture\" on the \"Screen share\" page.", "Щоб розпочати голосовий виклик, увімкніть «Захоплення аудіо» на сторінці «Демонстрація екрана»."),
].iter().cloned().collect();
}
+303 -17
View File
@@ -93,10 +93,73 @@ impl Drop for AnswererSlot {
WEBRTC_ANSWERERS.fetch_sub(1, Ordering::AcqRel);
}
}
/// Punches in flight: each holds a socket of its own and waits up to `CONNECT_TIMEOUT` for the
/// peer, and neither request behind them needs authentication, anyone who knows this id can ask
/// hbbs to have us open one. A place is given up the moment the peer's session is up, so it
/// stands for that wait and nothing past it: the places turn over on their own, within
/// `CONNECT_TIMEOUT` and the few seconds a punch's phases add to it, and at the limit an arrival
/// is declined rather than an older punch cut short. Declined is the listen alone, never the
/// reply: that carries the WebRTC answer and the v6 address as well, and those go on without a
/// v4 punch.
///
/// Two pools, so that neither transport pays for the other's crowd: a connection costs a place in
/// each, the controller's preferred request punching UDP and its TCP fallback request punching
/// TCP, and the transports that lose the race hold theirs for the whole wait.
struct PunchPool {
places: AtomicUsize,
max: usize,
}
/// UDP over v4 and v6. A request that carries a v6 address costs two, until the one the peer
/// does not use times out.
static UDP_PUNCHES: PunchPool = PunchPool::new(32);
/// The TCP punch's listener, and the LAN listen a FetchLocalAddr opens, which is that listener
/// again.
static TCP_PUNCHES: PunchPool = PunchPool::new(32);
impl PunchPool {
const fn new(max: usize) -> Self {
Self {
places: AtomicUsize::new(0),
max,
}
}
fn take(&'static self) -> Option<PunchSlot> {
self.places
.fetch_update(Ordering::AcqRel, Ordering::Acquire, |n| {
(n < self.max).then(|| n + 1)
})
.ok()
.map(|_| PunchSlot(self))
}
/// For a request that punches over both, v4 first: at the last place it is then the v6
/// punch that goes without, whatever order the two listens start in - v4 is the one the
/// peer can count on, v6 the one it may have no route for.
fn take_pair(&'static self, v4: bool, v6: bool) -> (Option<PunchSlot>, Option<PunchSlot>) {
let v4 = v4.then(|| self.take()).flatten();
let v6 = v6.then(|| self.take()).flatten();
(v4, v6)
}
}
/// One of a pool's places, given back on drop.
pub(crate) struct PunchSlot(&'static PunchPool);
impl Drop for PunchSlot {
fn drop(&mut self) {
self.0.places.fetch_sub(1, Ordering::AcqRel);
}
}
// The rendezvous ICE route is reachable without a prior punch and the peer decides how many
// candidates it sends, so these sites would let someone else set how much this machine writes to
// its log file. One line a minute each, carrying the suppressed count.
const ICE_LOG_INTERVAL: std::time::Duration = std::time::Duration::from_secs(60);
/// A declined punch is one line a minute, carrying the number it stands for, for the same
/// reason: the peer decides how often it asks.
const PUNCH_LOG_INTERVAL: std::time::Duration = std::time::Duration::from_secs(60);
static UNKNOWN_ICE_SESSION_LOG: hbb_common::log_throttle::LogThrottle =
hbb_common::log_throttle::LogThrottle::new(ICE_LOG_INTERVAL);
static REJECTED_REMOTE_ICE_LOG: hbb_common::log_throttle::LogThrottle =
@@ -715,7 +778,14 @@ impl RendezvousMediator {
fla.controlled_context.clone().into_option(),
);
if peer_addr_v6.port() > 0 && !relay {
socket_addr_v6 = start_ipv6(peer_addr_v6, addr, server.clone(), meta.clone()).await;
socket_addr_v6 = start_ipv6(
peer_addr_v6,
addr,
server.clone(),
meta.clone(),
UDP_PUNCHES.take(),
)
.await;
}
if is_ipv4(&self.addr) && !relay && !config::is_disable_tcp_listen() {
if let Err(err) = self
@@ -758,6 +828,17 @@ impl RendezvousMediator {
) -> ResultType<()> {
let peer_addr = AddrMangle::decode(&fla.socket_addr);
log::debug!("Handle intranet from {:?}", peer_addr);
// The listen this opens waits for the peer like a TCP punch and is declined like one; the
// caller then relays, as it does when the listen fails for any other reason.
let Some(slot) = TCP_PUNCHES.take() else {
hbb_common::throttled_log!(
PUNCH_LOG_INTERVAL,
warn,
"declined a LAN listen: {} TCP punches already in flight",
TCP_PUNCHES.max
);
bail!("no place among the punches in flight");
};
let mut socket = connect_tcp(&*self.host, CONNECT_TIMEOUT).await?;
let local_addr = socket.local_addr();
// we saw invalid local_addr while using proxy, local_addr.ip() == "::1"
@@ -775,7 +856,7 @@ impl RendezvousMediator {
});
let bytes = msg_out.write_to_bytes()?;
socket.send_raw(bytes).await?;
crate::accept_connection(server.clone(), socket, peer_addr, true, meta).await;
crate::accept_connection(server.clone(), socket, peer_addr, true, meta, slot).await;
Ok(())
}
@@ -1013,9 +1094,29 @@ impl RendezvousMediator {
} else {
String::new()
};
if peer_addr_v6.port() > 0 && !relay {
socket_addr_v6 =
start_ipv6(peer_addr_v6, peer_addr, server.clone(), meta.clone()).await;
// Whether the v4 legs relay is known here, and decides whether a v4 place is taken at
// all: the relay branch below runs the whole session, and a place held across it would
// let ordinary relay traffic use the pool up. The v6 punch is not relayed with them - a
// symmetric NAT on v4 says nothing about v6 - and its place is taken after the v4 one,
// or it could be the last and leave the punch the peer counts on with none.
let relay_v4 = ph.nat_type.enum_value() == Ok(NatType::SYMMETRIC)
|| Config::get_nat_type() == NatType::SYMMETRIC as i32
|| relay
|| (config::is_disable_tcp_listen() && ph.udp_port <= 0);
let punch_udp = !relay_v4 && ph.udp_port > 0;
let punch_tcp = !relay_v4 && ph.udp_port <= 0 && ph.webrtc_sdp_offer.is_empty();
let punch_v6 = peer_addr_v6.port() > 0 && !relay;
let (slot_udp, slot_v6) = UDP_PUNCHES.take_pair(punch_udp, punch_v6);
let slot_tcp = punch_tcp.then(|| TCP_PUNCHES.take()).flatten();
if punch_v6 {
socket_addr_v6 = start_ipv6(
peer_addr_v6,
peer_addr,
server.clone(),
meta.clone(),
slot_v6,
)
.await;
}
let relay_server = self.get_relay_server(ph.relay_server);
// for ensure, websocket go relay directly
@@ -1024,11 +1125,7 @@ impl RendezvousMediator {
// than trusting this classification, so a direct WebRTC pair can still form on a
// connection this branch has already called relay-only. Do not gate the answerer on
// nat_type to make the two agree.
if ph.nat_type.enum_value() == Ok(NatType::SYMMETRIC)
|| Config::get_nat_type() == NatType::SYMMETRIC as i32
|| relay
|| (config::is_disable_tcp_listen() && ph.udp_port <= 0)
{
if relay_v4 {
let uuid = Uuid::new_v4().to_string();
return self
.create_relay(
@@ -1058,7 +1155,7 @@ impl RendezvousMediator {
};
if ph.udp_port > 0 {
peer_addr.set_port(ph.udp_port as u16);
self.punch_udp_hole(peer_addr, server, msg_punch, meta)
self.punch_udp_hole(peer_addr, server, msg_punch, meta, slot_udp)
.await?;
return Ok(());
}
@@ -1094,7 +1191,18 @@ impl RendezvousMediator {
let local_addr = socket.local_addr();
// The listener inside takes this address over, so the mediator's socket goes first.
drop(socket);
punch_tcp_until_connected(server, peer_addr, local_addr, meta).await;
// The reply went out above: declined is the listen alone, so the controller's TCP attempt
// meets nothing and its v6 one goes on.
let Some(slot) = slot_tcp else {
hbb_common::throttled_log!(
PUNCH_LOG_INTERVAL,
warn,
"declined a TCP punch: {} TCP punches already in flight",
TCP_PUNCHES.max
);
return Ok(());
};
punch_tcp_until_connected(server, peer_addr, local_addr, meta, slot).await;
Ok(())
}
@@ -1104,12 +1212,26 @@ impl RendezvousMediator {
server: ServerPtr,
msg_punch: PunchHoleSent,
meta: ConnectionMeta,
slot: Option<PunchSlot>,
) -> ResultType<()> {
let mut msg_out = Message::new();
msg_out.set_punch_hole_sent(msg_punch);
let (socket, addr) = new_direct_udp_for(&self.host).await?;
let data = msg_out.write_to_bytes()?;
socket.send_to(&data, addr).await?;
// The reply is out, and with it the answer and the v6 address: declined is the listen
// alone, and the socket goes at once - a declined request is not worth one kept for its
// resends, and the controller re-asks on its own. Its v4 attempt at a mapping that no
// longer answers fails on its own while its other transports go on.
let Some(slot) = slot else {
hbb_common::throttled_log!(
PUNCH_LOG_INTERVAL,
warn,
"declined a UDP punch: {} UDP punches already in flight",
UDP_PUNCHES.max
);
return Ok(());
};
let socket_cloned = socket.clone();
tokio::spawn(async move {
for _ in 0..2 {
@@ -1118,7 +1240,15 @@ impl RendezvousMediator {
socket.send_to(&data, addr).await.ok();
}
});
udp_nat_listen(socket_cloned.clone(), peer_addr, peer_addr, server, meta).await?;
udp_nat_listen(
socket_cloned.clone(),
peer_addr,
peer_addr,
server,
meta,
slot,
)
.await?;
Ok(())
}
@@ -1308,13 +1438,33 @@ async fn start_ipv6(
peer_addr_v4: SocketAddr,
server: ServerPtr,
meta: ConnectionMeta,
slot: Option<PunchSlot>,
) -> bytes::Bytes {
// Declining leaves the v4 path to carry the connection, as it already does wherever this
// machine has no public IPv6 address.
let Some(slot) = slot else {
hbb_common::throttled_log!(
PUNCH_LOG_INTERVAL,
warn,
"declined an IPv6 punch: {} UDP punches already in flight",
UDP_PUNCHES.max
);
return Default::default();
};
crate::test_ipv6().await;
if let Some((socket, local_addr_v6)) = crate::get_ipv6_socket().await {
let server = server.clone();
tokio::spawn(async move {
allow_err!(
udp_nat_listen(socket.clone(), peer_addr_v6, peer_addr_v4, server, meta).await
udp_nat_listen(
socket.clone(),
peer_addr_v6,
peer_addr_v4,
server,
meta,
slot
)
.await
);
});
return local_addr_v6;
@@ -1328,6 +1478,7 @@ async fn udp_nat_listen(
peer_addr_v4: SocketAddr,
server: ServerPtr,
meta: ConnectionMeta,
slot: PunchSlot,
) -> ResultType<()> {
let tm = Instant::now();
let socket_cloned = socket.clone();
@@ -1340,6 +1491,9 @@ async fn udp_nat_listen(
init_packet,
)
.await?;
// The KCP session is up: from here it is a connection like any other and the connection
// layer's own limits apply to it, so the place goes back for the next punch.
drop(slot);
crate::server::create_tcp_connection(server, stream.1, peer_addr_v4, true, meta).await?;
Ok(())
};
@@ -1383,11 +1537,15 @@ const PUNCH_GRACE: u64 = 3000;
/// a hole that no longer exists. Punching again across the window in which the controller dials
/// rebuilds it, and once the controller sits in SYN_SENT one of those punches meets its SYN and
/// completes as a simultaneous open: a second way in, which a single punch never had.
///
/// `slot` is this punch's place among `TCP_PUNCHES`, given back the moment a connection is in
/// hand and before the session runs on it: from there the connection layer's own limits apply.
async fn punch_tcp_until_connected(
server: ServerPtr,
peer_addr: SocketAddr,
local_addr: SocketAddr,
meta: ConnectionMeta,
slot: PunchSlot,
) {
use hbb_common::tcp::new_listener;
// Shadows the module's `std::time::Instant`: the deadline is held against tokio's sleeps and
@@ -1414,6 +1572,7 @@ async fn punch_tcp_until_connected(
});
let Some(listener) = listener else {
if let Some(stream) = punch.await {
drop(slot);
serve_punched(server, stream, peer_addr, meta).await;
}
return;
@@ -1458,10 +1617,12 @@ async fn punch_tcp_until_connected(
biased;
Some(stream) = punch => stream,
Some((stream, addr)) = accept => {
drop(slot);
return accept_punched_connection(server, stream, addr, meta).await;
}
else => return,
};
drop(slot);
serve_punched(server, punched, peer_addr, meta).await;
}
@@ -1569,12 +1730,137 @@ impl Drop for CheckIfResendPk {
#[cfg(test)]
mod tests {
use super::{
mpsc, socket_client, tokio, AnswererSlot, IceRoute, ICE_DEDUP_WINDOW,
MAX_PENDING_REMOTE_ICE, MAX_WEBRTC_ANSWERERS,
connection_meta, mpsc, socket_client, tokio, udp_nat_listen, AnswererSlot, Arc, IceRoute,
IntoTargetAddr, Ordering, PunchHoleSent, RendezvousMediator, RendezvousMessage,
ICE_DEDUP_WINDOW, MAX_PENDING_REMOTE_ICE, MAX_WEBRTC_ANSWERERS, TCP_PUNCHES, UDP_PUNCHES,
};
use hbb_common::tcp::new_listener;
use hbb_common::{protobuf::Message as _, tcp::new_listener};
use std::net::SocketAddr;
// The pools are statics and the tests run in parallel: the ones that count them take turns.
static POOLS: std::sync::Mutex<()> = std::sync::Mutex::new(());
fn pools() -> std::sync::MutexGuard<'static, ()> {
POOLS.lock().unwrap_or_else(|e| e.into_inner())
}
// The places are the bound and they come back on drop: a punch past the limit is declined
// while the ones in flight are left alone, and the next one in is admitted only once a
// place has actually been given back.
#[test]
fn test_punch_slots_cap_and_release() {
let _pools = pools();
for pool in [&UDP_PUNCHES, &TCP_PUNCHES] {
let held: Vec<_> = (0..pool.max)
.map(|_| pool.take().expect("a place up to the limit"))
.collect();
assert!(pool.take().is_none(), "the limit is the limit");
drop(held);
assert!(pool.take().is_some(), "a place comes back on drop");
}
}
// Neither transport pays for the other's crowd: a full UDP pool leaves the TCP places alone.
#[test]
fn a_full_udp_pool_leaves_the_tcp_places_alone() {
let _pools = pools();
let held: Vec<_> = (0..UDP_PUNCHES.max)
.map(|_| UDP_PUNCHES.take().expect("a place up to the limit"))
.collect();
assert!(UDP_PUNCHES.take().is_none(), "the UDP pool is full");
assert!(
TCP_PUNCHES.take().is_some(),
"a TCP punch must not wait on the UDP pool"
);
drop(held);
}
// At the last place it is the v6 punch that goes without, never the v4 one the peer counts on.
#[test]
fn the_last_place_goes_to_the_v4_punch() {
let _pools = pools();
let held: Vec<_> = (0..UDP_PUNCHES.max - 1)
.map(|_| UDP_PUNCHES.take().expect("a place up to the last"))
.collect();
let (v4, v6) = UDP_PUNCHES.take_pair(true, true);
assert!(v4.is_some(), "the last place goes to the v4 punch");
assert!(v6.is_none(), "and the v6 punch goes without");
drop(held);
}
// Declined is the listen, never the reply: with no place the PunchHoleSent still goes out,
// carrying the answer and the v6 address the controller's other transports run on, and the
// call returns at once - a listen would have waited for the peer's probe and failed without.
#[tokio::test]
async fn a_declined_udp_punch_still_replies() {
let hbbs = tokio::net::UdpSocket::bind("127.0.0.1:0").await.unwrap();
let host = hbbs.local_addr().unwrap();
let mediator = RendezvousMediator {
addr: host.into_target_addr().unwrap(),
host: host.to_string(),
host_prefix: String::new(),
keep_alive: 0,
};
let msg_punch = PunchHoleSent {
webrtc_sdp_answer: "answer".to_owned(),
socket_addr_v6: bytes::Bytes::from_static(b"v6"),
..Default::default()
};
mediator
.punch_udp_hole(
host,
crate::server::new_for_test(),
msg_punch,
connection_meta(None, None),
None,
)
.await
.expect("declined is not an error, and not a listen");
let mut buf = [0u8; 4096];
let (n, _) = hbb_common::timeout(3000, hbbs.recv_from(&mut buf))
.await
.expect("the reply must reach hbbs")
.unwrap();
let sent = RendezvousMessage::parse_from_bytes(&buf[..n]).unwrap();
let sent = sent.punch_hole_sent();
assert_eq!(sent.webrtc_sdp_answer, "answer");
assert_eq!(&sent.socket_addr_v6[..], b"v6");
}
// The place is the wait: a listen that ends without a peer gives it back on its own. The end
// a test can reach is the peer's probe never coming, which `punch_udp` gives up on.
#[test]
fn a_listen_that_finds_no_peer_gives_its_place_back() {
let _pools = pools();
let rt = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.unwrap();
rt.block_on(async {
let socket = tokio::net::UdpSocket::bind("127.0.0.1:0").await.unwrap();
let silent = tokio::net::UdpSocket::bind("127.0.0.1:0").await.unwrap();
let peer = silent.local_addr().unwrap();
let before = UDP_PUNCHES.places.load(Ordering::Acquire);
let slot = UDP_PUNCHES.take().expect("a place");
assert_eq!(UDP_PUNCHES.places.load(Ordering::Acquire), before + 1);
let listened = udp_nat_listen(
Arc::new(socket),
peer,
peer,
crate::server::new_for_test(),
connection_meta(None, None),
slot,
)
.await;
assert!(listened.is_err(), "no peer, no session");
assert_eq!(
UDP_PUNCHES.places.load(Ordering::Acquire),
before,
"the place must come back with the wait"
);
});
}
// A SOCKS proxy makes `connect_tcp_local` dial the proxy and ignore the local address, so
// nothing these two assert can hold. Read once, from the same global config production reads.
fn proxied() -> bool {
+36 -4
View File
@@ -182,6 +182,7 @@ async fn accept_connection_(
socket: Stream,
secure: bool,
meta: ConnectionMeta,
slot: crate::rendezvous_mediator::PunchSlot,
) -> ResultType<()> {
let local_addr = socket.local_addr();
drop(socket);
@@ -191,6 +192,8 @@ async fn accept_connection_(
let listener = new_listener(local_addr, true).await?;
log::info!("Server listening on: {}", &listener.local_addr()?);
if let Ok((stream, addr)) = timeout(CONNECT_TIMEOUT, listener.accept()).await? {
// The peer is in: the place goes back before the session runs, as every punch's does.
drop(slot);
stream.set_nodelay(true).ok();
let stream_addr = stream.local_addr()?;
create_tcp_connection(
@@ -221,6 +224,8 @@ pub async fn create_tcp_connection(
let Some(unauthorized) = admit_unauthorized(id, addr.ip()) else {
bail!("too many unauthenticated connections from {}", addr.ip());
};
// Before the handshake, so its read is bounded too; lifted again at authorization.
stream.set_max_packet_length(MAX_UNAUTHORIZED_MESSAGE);
tokio::select! {
handshake = identity_handshake(&mut stream, secure) => handshake?,
_ = unauthorized.evicted() => {
@@ -271,12 +276,21 @@ async fn identity_handshake(stream: &mut Stream, secure: bool) -> ResultType<()>
if stream.is_webrtc() && dtls_fingerprint.is_empty() {
bail!("WebRTC local DTLS fingerprint unavailable");
}
// A WebRTC stream is encrypted by DTLS and takes no stream key of its own, split or
// not, so what it advertises is what it runs: 0. Saying 1 there would have a future
// controller that splits keys on WebRTC agree on a version this side never applies.
let advertised = if stream.is_webrtc() {
0
} else {
tcp::KX_VERSION_LATEST
};
msg_out.set_signed_id(SignedId {
id: sign::sign(
&IdPk {
id: Config::get_id(),
pk: Bytes::from(our_pk_b.0.to_vec()),
dtls_fingerprint,
kx_version: advertised,
..Default::default()
}
.write_to_bytes()
@@ -293,11 +307,28 @@ async fn identity_handshake(stream: &mut Stream, secure: bool) -> ResultType<()>
if let Ok(msg_in) = Message::parse_from_bytes(&bytes) {
if let Some(message::Union::PublicKey(pk)) = msg_in.union {
if pk.asymmetric_value.len() == box_::PUBLICKEYBYTES {
stream.set_key(tcp::Encrypt::decode(
let key = tcp::Encrypt::decode(
&pk.symmetric_value,
&pk.asymmetric_value,
&our_sk_b,
)?);
)?;
if pk.kx_version > advertised {
bail!(
"Handshake failed: key exchange version {} not offered, {} was",
pk.kx_version,
advertised
);
}
stream.set_negotiated_key(
key,
false,
&tcp::KxTranscript {
initiator_pk: &pk.asymmetric_value,
responder_pk: &our_pk_b.0,
advertised,
picked: pk.kx_version,
},
)?;
} else if pk.asymmetric_value.is_empty() {
Config::set_key_confirmed(false);
log::info!("Force to update pk");
@@ -320,14 +351,15 @@ async fn identity_handshake(stream: &mut Stream, secure: bool) -> ResultType<()>
Ok(())
}
pub async fn accept_connection(
pub(crate) async fn accept_connection(
server: ServerPtr,
socket: Stream,
peer_addr: SocketAddr,
secure: bool,
meta: ConnectionMeta,
slot: crate::rendezvous_mediator::PunchSlot,
) {
if let Err(err) = accept_connection_(server, socket, secure, meta).await {
if let Err(err) = accept_connection_(server, socket, secure, meta, slot).await {
log::warn!("Failed to accept connection from {}: {}", peer_addr, err);
}
}
+51 -3
View File
@@ -93,6 +93,14 @@ const MAX_UNAUTHORIZED_CONNS: usize = 64;
/// of addresses passes it, and the bound above is what holds. Meaningful only while the
/// address is the controller's own, which punch and relay messages carry today.
const MAX_UNAUTHORIZED_CONNS_PER_ADDR: usize = 16;
/// The largest message a connection may send before it authorizes. Until then a peer sends only
/// a public key, a login request, a test delay and a close reason, none of which carries an
/// unbounded field - a server hands the login request's avatar out as a URL, and only a custom
/// client that inlines an image into the avatar option instead reaches this. Sized to the read
/// buffer tungstenite allocates per WebSocket connection regardless, so there the cap costs
/// nothing beyond a floor already paid; with MAX_UNAUTHORIZED_CONNS it holds them to 8 MiB in
/// all, against the 1 GiB a single one could make us hold before.
pub const MAX_UNAUTHORIZED_MESSAGE: usize = 128 * 1024;
/// A place among the unauthorized connections, taken before the identity handshake and given
/// back on drop: at authorization, or when the connection ends first. The count of live
@@ -1206,9 +1214,6 @@ impl Connection {
}
}
video_service::notify_video_frame_fetched_by_conn_id(id, None);
if conn.authorized {
password::update_temporary_password();
}
if let Err(err) = conn.try_port_forward_loop(&mut rx_from_cm).await {
conn.on_close(&err.to_string(), false).await;
raii::AuthedConnID::check_remove_session(conn.inner.id(), conn.session_key());
@@ -1871,11 +1876,19 @@ impl Connection {
if let Some(keep_alive) = self.prepare_terminal_login_for_authorization().await {
return keep_alive;
}
// Lifted here rather than below with the rest of authorization: a multiplexed tunnel
// narrows it again for its own framing (`port_forward_mux::cap_packet_size`), so that
// call has to come after this one, not before.
self.stream.set_max_packet_length(usize::MAX);
if !self.connect_port_forward_if_needed().await {
return false;
}
self.authorized = true;
self.unauthorized_id = None;
// One-time means gone once it has let a peer in, not once that peer
// leaves. This session's later logins come in on the password the
// session remembers, so they are not affected.
password::update_temporary_password();
// Releases the budget `check_id_whitelist` charges against this address: only a peer
// that got this far proved more than a self-reported id.
self.clear_id_whitelist_failures();
@@ -7239,6 +7252,41 @@ mod test {
assert_eq!(unauthorized_count(), 0, "no handshake outlives the test");
}
// The cap is on before the identity handshake reads. A header declaring one byte over it,
// written to the wire as the codec would read it, ends the handshake on the header alone -
// the payload is neither waited for nor read - and releases the place the connection held.
#[tokio::test]
async fn test_unauthorized_frame_is_refused_on_its_header() {
use hbb_common::tokio::io::AsyncWriteExt;
let _serial = UNAUTHORIZED_TESTS.lock().unwrap_or_else(|e| e.into_inner());
let server = crate::server::new_for_test();
let listener = hbb_common::tcp::new_listener("127.0.0.1:0", false)
.await
.unwrap();
let (controller, accepted) = tokio::join!(
tokio::net::TcpStream::connect(listener.local_addr().unwrap()),
listener.accept()
);
let (mut controller, (accepted, addr)) = (controller.unwrap(), accepted.unwrap());
let served = Stream::Tcp(hbb_common::tcp::FramedStream::from(accepted, addr));
let handshake = tokio::spawn(async move {
crate::server::create_tcp_connection(server, served, addr, true, Default::default())
.await
});
let n = MAX_UNAUTHORIZED_MESSAGE + 1;
controller
.write_all(&(((n << 2) | 0x3) as u32).to_le_bytes())
.await
.unwrap();
match hbb_common::timeout(2000, handshake).await {
Ok(Ok(Err(e))) => assert!(e.to_string().contains("Too big packet"), "{}", e),
Ok(Ok(Ok(_))) => panic!("a frame over the cap was accepted"),
Ok(Err(e)) => panic!("the handshake task panicked: {}", e),
Err(_) => panic!("the handshake waited for a payload the header should have refused"),
}
assert_eq!(unauthorized_count(), 0);
}
#[cfg(feature = "flutter")]
#[cfg(not(any(target_os = "android", target_os = "ios")))]
#[test]
+804 -24
View File
@@ -53,17 +53,22 @@ impl FrameSlot {
}
}
/// `Shared.transform` before new() stores the real value: a cursor arriving this early is held
/// back and replayed once the session transform is in, because the producer will not resend it
/// until the shape changes.
/// `Shared.cursor_transform` before new() stores the real value: a cursor arriving this early is
/// held back and replayed once the session transform is in, because the producer will not resend
/// it until the shape changes.
const TRANSFORM_PENDING: i32 = i32::MIN;
struct Shared {
slot: Mutex<FrameSlot>,
cv: Condvar,
// Session transform, TRANSFORM_PENDING until new() stores it post-handshake; the receive
// thread turns cursor bitmaps with it and defers any cursor that races the store.
transform: std::sync::atomic::AtomicI32,
// The output's real transform, TRANSFORM_PENDING until new() stores it post-handshake. Only
// the cursor needs it across threads: it differs from the angle the FRAME is turned by on a
// hardware-rotated 180 output, where the primary plane scans out upright but the compositor
// still pre-rotates the sprite (measured on i915 + mutter: the frame arrived upright and the
// sprite upside down). The frame's own angle is not shared - it is fixed for the session and
// lives on the capturer that uses it. The receive thread defers any cursor that races the
// store.
cursor_transform: std::sync::atomic::AtomicI32,
}
pub struct IpcDrmCapturer {
@@ -177,10 +182,6 @@ fn transform_and_origin(
.copied()
.flatten()
.map(|j| wl.displays[j].transform)
// Hardware-rotated 180 scans out already upright (i915 advertises rotate-180 and
// mutter uses it), and wl_output cannot tell hardware from software rotation, so 180
// keeps master behavior until the plane rotation property travels the wire.
.map(|t| if t == 90 || t == 270 { t } else { 0 })
.unwrap_or(0);
let origin = augment_with_wayland_geometry_from(drm, wl, &assignment)
.get(wire_idx)
@@ -188,6 +189,18 @@ fn transform_and_origin(
(transform, origin)
}
/// The angle the FRAME has to be turned back by. Hardware-rotated 180 scans out already upright
/// (i915 advertises rotate-180 and mutter uses it), and wl_output cannot tell hardware from
/// software rotation, so 180 keeps master behavior until the plane rotation property travels
/// the wire. The cursor does not go through this: see `Shared::cursor_transform`.
fn frame_transform(wl_transform: i32) -> i32 {
if wl_transform == 90 || wl_transform == 270 {
wl_transform
} else {
0
}
}
/// Takes DRM_STATE: never call it while holding one of the per-display maps below.
fn display_info_of(display: i32) -> Option<DrmDisplayInfo> {
match &*DRM_STATE.lock().unwrap() {
@@ -325,7 +338,7 @@ impl IpcDrmCapturer {
ended: None,
}),
cv: Condvar::new(),
transform: std::sync::atomic::AtomicI32::new(TRANSFORM_PENDING),
cursor_transform: std::sync::atomic::AtomicI32::new(TRANSFORM_PENDING),
});
let stop = Arc::new(AtomicBool::new(false));
let (tx, rx) = std::sync::mpsc::channel::<ResultType<(Vec<DrmDisplayInfo>, usize)>>();
@@ -350,13 +363,14 @@ impl IpcDrmCapturer {
// clear racing the build rebuilds once instead of running a session on stale geometry.
let snapshot_gen = scrap::wayland::display::wayland_snapshot_generation();
let wl = scrap::wayland::display::get_displays();
let (transform, origin) = transform_and_origin(&displays, wire_idx, &wl);
let (wl_transform, origin) = transform_and_origin(&displays, wire_idx, &wl);
let transform = frame_transform(wl_transform);
// This capturer now shows that layout. If the session init's own wayland query failed it
// saved an empty baseline, so this is the only record of what the stream is built on.
super::display_service::note_capturer_layout(&wl.displays, snapshot_gen);
shared
.transform
.store(transform, std::sync::atomic::Ordering::Release);
.cursor_transform
.store(wl_transform, std::sync::atomic::Ordering::Release);
Ok((
IpcDrmCapturer {
shared,
@@ -634,16 +648,18 @@ async fn recv_thread(
// A cursor that arrived before new() stored the session transform, held for replay. Only the
// newest matters; the 200 ms recv timeout guarantees this is retried even on an idle wire.
let mut pending_cursor: Option<(u64, u32, u32, i32, i32, Vec<u8>)> = None;
let mut pending_cursor: Option<(u64, u32, u32, i32, i32, bool, Vec<u8>)> = None;
let end_reason = loop {
if stop.load(Ordering::SeqCst) {
break "stopped".to_owned();
}
if pending_cursor.is_some() {
let t = shared.transform.load(std::sync::atomic::Ordering::Acquire);
let t = shared.cursor_transform.load(std::sync::atomic::Ordering::Acquire);
if t != TRANSFORM_PENDING {
if let Some((id, width, height, hotx, hoty, raw)) = pending_cursor.take() {
deliver_drm_cursor(display, cursor_epoch, id, width, height, hotx, hoty, raw, t);
if let Some((id, width, height, hotx, hoty, hot_measured, raw)) = pending_cursor.take() {
deliver_drm_cursor(
display, cursor_epoch, id, width, height, hotx, hoty, hot_measured, raw, t,
);
}
}
}
@@ -745,6 +761,7 @@ async fn recv_thread(
height,
hotx,
hoty,
hot_measured,
} => {
// get_cursor_data() hands `colors` straight to the client, which renders
// width*height*4 RGBA bytes: a short body would make it READ PAST THE BUFFER. A
@@ -763,9 +780,9 @@ async fn recv_thread(
raw.len()
);
}
let t = shared.transform.load(std::sync::atomic::Ordering::Acquire);
let t = shared.cursor_transform.load(std::sync::atomic::Ordering::Acquire);
if t == TRANSFORM_PENDING {
pending_cursor = Some((id, width, height, hotx, hoty, raw));
pending_cursor = Some((id, width, height, hotx, hoty, hot_measured, raw));
} else {
pending_cursor = None;
deliver_drm_cursor(
@@ -776,6 +793,7 @@ async fn recv_thread(
height,
hotx,
hoty,
hot_measured,
raw,
t,
);
@@ -921,17 +939,34 @@ fn deliver_drm_cursor(
height: u32,
hotx: i32,
hoty: i32,
hot_measured: bool,
raw: Vec<u8>,
t: i32,
) {
let (width, height, hotx, hoty, colors) = if t == 90 || t == 270 {
// Every non-zero angle, 180 included. Measured on i915 + mutter with the output at 180: the
// frame arrived upright and the sprite upside down, so the compositor had pre-rotated the
// sprite by the full transform while the plane scanned out already turned. wl_output cannot
// say which of the two happened - the same blindness `frame_transform` defers to - so the
// sprite is treated as pre-rotated at every angle.
let (width, height, hotx, hoty, colors) = if t != 0 {
let mut turned = Vec::new();
unrotate_bgra(&raw, width as usize, height as usize, t, &mut turned);
let (hx, hy) = unrotate_hotspot(t, width as i32, height as i32, hotx, hoty);
(height as i32, width as i32, hx, hy, turned)
let (dw, dh) = rotated_dims(t, width as usize, height as usize);
// A hotspot the driver measured is a point on the scanout sprite and maps like a pixel.
// A guessed one was guessed on the ROTATED sprite - top-left of an arrow's box - and
// the tip of a turned arrow is some other corner, so it is guessed again on the upright
// one. The old flow was off at every angle; what differs is the size of the error, which
// is why only one of them got reported (see the test below).
let (hx, hy) = if hot_measured {
unrotate_hotspot(t, width as i32, height as i32, hotx, hoty)
} else {
scrap::drm_reader::infer_hotspot(&turned, dw, dh)
};
(dw as i32, dh as i32, hx, hy, turned)
} else {
(width as i32, height as i32, hotx, hoty, raw)
};
note_received_provenance(display, id, hot_measured);
let id = fold_cursor_id(id, t);
set_drm_cursor(
display,
@@ -947,6 +982,50 @@ fn deliver_drm_cursor(
);
}
/// Last provenance seen PER DISPLAY. Not one global: several streams run at once and their
/// provenance can differ and still be stable -- one output publishing HOTSPOT_X/Y while another
/// does not is a normal multi-GPU host -- and a single slot would read that as an endless
/// alternation and log on every cursor message.
static LAST_RECEIVED_PROVENANCE: Mutex<BTreeMap<i32, bool>> = Mutex::new(BTreeMap::new());
/// Whether this display's provenance changed, recording the new value. Its own function so the
/// per-display behaviour can be asserted without reading a log.
fn provenance_is_news_for(display: i32, hot_measured: bool) -> bool {
LAST_RECEIVED_PROVENANCE
.lock()
.unwrap()
.insert(display, hot_measured)
!= Some(hot_measured)
}
/// Say once per display, and again only on a change, what the producer told us about the hotspot.
///
/// The counterpart of the producer's own provenance line, and it exists for the case that line
/// cannot cover: a message that arrives with no `hot_measured` field at all, where what happens is
/// decided by the field's serde default and is otherwise invisible on a running box.
///
/// The hidden-cursor sentinel is skipped. It is sent with `hot_measured: false` because there is no
/// hotspot to describe, so recording it would make every hide/show look like a provenance change.
fn note_received_provenance(display: i32, id: u64, hot_measured: bool) {
if id == scrap::drm_reader::HIDDEN_CURSOR_ID {
return;
}
if !provenance_is_news_for(display, hot_measured) {
return;
}
if hot_measured {
log::info!(
"drm: cursor hotspots arrive MEASURED; mapping the point the producer sent. \
(a producer that predates the field reads as measured too, on purpose: that \
preserves what the old protocol meant)"
);
} else {
log::info!(
"drm: cursor hotspots arrive as a GUESS; re-inferring from the upright bitmap"
);
}
}
fn fold_cursor_id(id: u64, t: i32) -> u64 {
if id == scrap::drm_reader::HIDDEN_CURSOR_ID {
id
@@ -1783,7 +1862,7 @@ mod drm_capturer_tests {
ended: None,
}),
cv: Condvar::new(),
transform: std::sync::atomic::AtomicI32::new(0),
cursor_transform: std::sync::atomic::AtomicI32::new(0),
}),
stop: Arc::new(AtomicBool::new(false)),
display: 0,
@@ -1922,6 +2001,362 @@ mod drm_capturer_tests {
assert_eq!(back, src);
}
/// An upright arrow, tip at (0,0): a 4x6 bitmap, every pixel with x <= y/2 opaque, so the
/// opaque box is the left 3 columns. Its top-left corner IS the tip - which is exactly why
/// the bare-metal guess works when the sprite is upright, and only then.
fn arrow() -> (Vec<u8>, usize, usize) {
let (w, h) = (4usize, 6usize);
let mut px = vec![0u8; w * h * 4];
for y in 0..h {
for x in 0..w {
if x <= y / 2 {
px[(y * w + x) * 4 + 3] = 255;
}
}
}
(px, w, h)
}
/// An I-beam lying along x, deliberately NOT centred in its bitmap: 16x8, opaque rows 2..4 and
/// columns 1..13, so the opaque box is (1,2)-(12,3), 12x2 - elongated, which is what Adwaita's
/// `vertical-text` shape is. Its click point is the centre of that BOX, (6,2), while the centre
/// of the bitmap is (7,3). The offset is the point: a real sprite sits somewhere inside a
/// 64x64 hardware buffer (the adwaita box above is (2,6)-(21,14) in a 24x24 one), and a fixture
/// centred in its bitmap would let an implementation that returns the bitmap centre pass a test
/// claiming to check the box centre.
fn ibeam_horizontal() -> (Vec<u8>, usize, usize, (i32, i32)) {
let (w, h) = (16usize, 8usize);
let mut px = vec![0u8; w * h * 4];
for y in 2..4 {
for x in 1..13 {
px[(y * w + x) * 4 + 3] = 255;
}
}
(px, w, h, (6, 2))
}
/// The shape at the aspect ratio that actually matters: a 20x9 opaque box, which is what the
/// installed Adwaita `vertical-text` measures at 24 px. 2.22:1, only just past the rule's
/// factor of two, so it pins the threshold from ABOVE: a stricter rule (say `bw > bh * 3`)
/// leaves the 6:1 bars below centred and silently un-centres the real cursor. Placed
/// off-centre in a 24x24 buffer like the real one, box (2,6)-(21,14), centre (11,10) - the
/// same numbers the theme file gives, against its declared hotspot of (12,11).
fn ibeam_theme_aspect() -> (Vec<u8>, usize, usize, (i32, i32)) {
let (w, h) = (24usize, 24usize);
let mut px = vec![0u8; w * h * 4];
for y in 6..15 {
for x in 2..22 {
px[(y * w + x) * 4 + 3] = 255;
}
}
(px, w, h, (11, 10))
}
/// The same shape standing up and equally off-centre: 8x16, opaque columns 2..4 and rows 1..13,
/// box (2,1)-(3,12), centre (2,6) against a bitmap centre of (3,7). The tall case the guess
/// already handled, kept so the symmetric rule cannot pass by breaking it.
fn ibeam_vertical() -> (Vec<u8>, usize, usize, (i32, i32)) {
let (w, h) = (8usize, 16usize);
let mut px = vec![0u8; w * h * 4];
for y in 1..13 {
for x in 2..4 {
px[(y * w + x) * 4 + 3] = 255;
}
}
(px, w, h, (2, 6))
}
/// What the compositor puts in the cursor plane on an output rotated by `t`: the upright sprite
/// rotated forward by t, which is what turning it back by (360 - t) degrees produces.
fn as_scanned_out(upright: &[u8], w: usize, h: usize, t: i32) -> (Vec<u8>, usize, usize) {
let mut out = Vec::new();
unrotate_bgra(upright, w, h, (360 - t) % 360, &mut out);
let (dw, dh) = rotated_dims(t, w, h);
(out, dw, dh)
}
// rustdesk#15886, the maintainer's physical test: the cursor looked right at 0 and 90, drawn
// above the click point at 270, and upside down at 180. Two causes, not one. The sprite came
// out upside down at 180 because master turned it only at 90 and 270, so a 180 sprite was
// never turned back at all. And at every angle the hotspot was GUESSED on the sprite as
// scanned out and only afterwards mapped as if it were a point on it: the guess picks the
// top-left of the opaque box, and a turned arrow's tip is not in that corner - at 90 the
// error is the arrow's WIDTH along x, small enough to pass as fine; at 270 it is its HEIGHT
// along y, which is the one that got reported.
//
// The 180 entry below is about that mapping, not about what was seen: on master the clamp sent
// 180 down the untouched branch, so the guess and the sprite were turned together and the
// hotspot landed on the tip anyway - measured as (0,0) there, with only the sprite wrong. What
// the loop shows is that the guess is not a point that survives being mapped, at any angle.
// This test covers the mapping; the sprite is covered by the two below.
#[test]
fn a_guessed_hotspot_is_guessed_on_the_upright_sprite() {
use scrap::drm_reader::infer_hotspot;
let (up, w, h) = arrow();
let tip = infer_hotspot(&up, w, h);
assert_eq!(tip, (0, 0));
let mut old_wrong_at = Vec::new();
for t in [90, 180, 270] {
let (scan, sw, sh) = as_scanned_out(&up, w, h, t);
// The old flow: guess on the scanned-out sprite, then map the point.
let (gx, gy) = infer_hotspot(&scan, sw, sh);
let old = unrotate_hotspot(t, sw as i32, sh as i32, gx, gy);
// The new flow: turn the sprite back first, then guess.
let mut turned = Vec::new();
unrotate_bgra(&scan, sw, sh, t, &mut turned);
let (dw, dh) = rotated_dims(t, sw, sh);
assert_eq!(turned, up, "the sprite turns back to upright at {t}");
assert_eq!(infer_hotspot(&turned, dw, dh), tip, "the tip is found again at {t}");
if old != tip {
old_wrong_at.push(t);
}
}
// The old flow is wrong at every angle, not only the one that was noticed.
assert_eq!(old_wrong_at, vec![90, 180, 270]);
}
// rustdesk#16242, the maintainer's pixel-level finding: the guess only centred TALL shapes, so
// a horizontal I-beam got the corner of its box. Before the rotation rework such a cursor
// reached a quarter-turned output as a tall bitmap and the same rule centred it by accident, so
// turning the sprite upright first - correct in itself - turned a nearly right hotspot into one
// about 11 px out. Measured on the installed Adwaita `vertical-text` at 24 px: theme hotspot
// (12, 11), opaque box 20x9, corner guess (2, 6) = 11.2 px away, centre guess (11, 10) = 1.4 px.
//
// The old flow is not the fix: it was right for this one shape and wrong for arrows at every
// angle, which is what the test above pins. The fix is for the guess to centre an elongated box
// whichever way it lies, and that is what this checks - for both orientations and at the real
// 2.22:1 aspect of the shape that was wrong - by driving `deliver_drm_cursor` and reading the
// published hotspot back, not by chaining the helpers itself.
/// The upgrade window, end to end from the WIRE rather than from a struct literal.
///
/// An old root service can be streaming to a freshly started `--server`, and its `DrmCursor`
/// carries no `hot_measured` at all. This takes the exact bytes such a producer puts on the
/// socket, deserializes them the way the consumer's receive loop does, and drives the real
/// delivery path, then reads back what was published. Staging it with two live processes is
/// not possible with how the package is built - a `--server` from one build will not run
/// inside the other's tree - so this is the honest form of that test, and it runs in CI
/// instead of once on somebody's desk.
///
/// The transform must be non-zero: at 0 the delivery path never consults `hot_measured`, so a
/// test at 0 could not tell the two branches apart.
/// Two streams with different but STABLE provenance must not read as a change on every
/// message. A single global slot did exactly that: display A measured and display B inferred,
/// alternating forever, is a normal multi-GPU host and would have logged per cursor message -
/// the per-frame logging this was written to avoid. And the hidden-cursor sentinel carries
/// `hot_measured: false` because it has no hotspot, so recording it would turn every hide and
/// show into a provenance transition.
#[test]
fn provenance_is_tracked_per_display_and_ignores_the_hidden_cursor() {
let (a, b) = (9_510, 9_511);
LAST_RECEIVED_PROVENANCE.lock().unwrap().remove(&a);
LAST_RECEIVED_PROVENANCE.lock().unwrap().remove(&b);
// First sighting of each is news; the same value again is not.
assert!(provenance_is_news_for(a, true));
assert!(!provenance_is_news_for(a, true));
assert!(provenance_is_news_for(b, false));
assert!(!provenance_is_news_for(b, false));
// The interleaving that a single global slot could not survive.
for _ in 0..4 {
assert!(!provenance_is_news_for(a, true), "display A is stable");
assert!(!provenance_is_news_for(b, false), "display B is stable");
}
// A real change on one display is still reported, and does not disturb the other.
assert!(provenance_is_news_for(a, false));
assert!(!provenance_is_news_for(b, false));
// The hidden sentinel is not recorded at all: it would otherwise look like B flipping.
note_received_provenance(b, scrap::drm_reader::HIDDEN_CURSOR_ID, true);
assert!(
!provenance_is_news_for(b, false),
"the hidden cursor must not count as a provenance change"
);
LAST_RECEIVED_PROVENANCE.lock().unwrap().remove(&a);
LAST_RECEIVED_PROVENANCE.lock().unwrap().remove(&b);
}
#[test]
fn a_legacy_cursor_message_keeps_the_hotspot_the_old_protocol_meant() {
use crate::ipc::Data;
let (up, w, h, _box_centre) = ibeam_theme_aspect();
let t = 90;
let (scan, sw, sh) = as_scanned_out(&up, w, h, t);
// A hotspot the old producer measured and sent as a point on the scanned-out sprite.
let (hotx, hoty) = (3, 5);
// Exactly what an old producer writes: `Data` is adjacently tagged, and there is no
// `hot_measured` key because that build has no such field.
let legacy = format!(
r#"{{"t":"DrmCursor","c":{{"id":11,"width":{sw},"height":{sh},"hotx":{hotx},"hoty":{hoty}}}}}"#
);
let (id, mw, mh, mx, my, measured) =
match serde_json::from_str::<Data>(&legacy).expect("a legacy DrmCursor must parse") {
Data::DrmCursor { id, width, height, hotx, hoty, hot_measured } => {
(id, width, height, hotx, hoty, hot_measured)
}
other => panic!("expected DrmCursor, got {other:?}"),
};
assert!(measured, "no provenance on the wire must mean what the old protocol meant");
// The two branches must disagree here, or the assertion below proves nothing.
let mapped = unrotate_hotspot(t, mw as i32, mh as i32, mx, my);
let mut turned = Vec::new();
unrotate_bgra(&scan, sw, sh, t, &mut turned);
let (dw, dh) = rotated_dims(t, sw, sh);
let reinferred = scrap::drm_reader::infer_hotspot(&turned, dw, dh);
assert_ne!(
mapped, reinferred,
"fixture cannot discriminate: mapping and re-inferring give the same point"
);
let display = 9_400;
deliver_drm_cursor(display, 1, id, mw, mh, mx, my, measured, scan, t);
let published = {
let map = DRM_CURSOR.lock().unwrap();
let (_, c) = map.get(&display).expect("the delivery path published nothing");
(c.hotx, c.hoty)
};
assert_eq!(
published, mapped,
"a legacy message must keep the hotspot the producer sent, transformed as a point; \
re-inferring it would move the cursor for the length of an upgrade"
);
// The control: a NEW producer asking for re-inference says so explicitly, and that must
// not be swallowed by the default.
let modern = format!(
r#"{{"t":"DrmCursor","c":{{"id":12,"width":{sw},"height":{sh},"hotx":{hotx},"hoty":{hoty},"hot_measured":false}}}}"#
);
let Data::DrmCursor { hot_measured, .. } =
serde_json::from_str::<Data>(&modern).expect("a modern DrmCursor must parse")
else {
panic!("expected DrmCursor")
};
assert!(!hot_measured);
let (scan2, _, _) = as_scanned_out(&up, w, h, t);
deliver_drm_cursor(display + 1, 1, 12, sw as u32, sh as u32, hotx, hoty, false, scan2, t);
let published2 = {
let map = DRM_CURSOR.lock().unwrap();
let (_, c) = map.get(&(display + 1)).expect("nothing published for the control");
(c.hotx, c.hoty)
};
assert_eq!(
published2, reinferred,
"an explicit false must still re-infer, or the legacy default has eaten the new \
producer's request"
);
}
#[test]
fn an_ibeam_keeps_its_centre_whichever_way_it_lies() {
use scrap::drm_reader::infer_hotspot;
for (i, (name, (up, w, h, box_centre))) in [
("horizontal", ibeam_horizontal()),
("vertical", ibeam_vertical()),
("theme-aspect", ibeam_theme_aspect()),
]
.into_iter()
.enumerate()
{
// The fixture must not be centred in its own bitmap, or this test cannot tell the
// centre of the opaque BOX - which is what the guess computes and what a cursor's
// click point is - from the centre of the buffer the sprite happens to sit in.
let bitmap_centre = (((w - 1) / 2) as i32, ((h - 1) / 2) as i32);
assert_ne!(
box_centre, bitmap_centre,
"the {name} fixture is centred in its bitmap, so it cannot discriminate"
);
// The upright guess is the centre of the opaque box, not its corner.
let guess = infer_hotspot(&up, w, h);
assert_eq!(guess, box_centre, "the {name} I-beam is centred, not cornered");
// And it is what the delivery path PUBLISHES, not just what the helper computes:
// `deliver_drm_cursor` is where the guessed branch is chosen and where the sprite is
// turned back, so the sprite is handed over pre-rotated exactly as the compositor
// scans it out, and the published hotspot is read back out of DRM_CURSOR.
for (j, t) in [0, 90, 180, 270].into_iter().enumerate() {
let display = 9_300 + (i * 8 + j) as i32;
let (scan, sw, sh) = as_scanned_out(&up, w, h, t);
// What the producer actually sends for a guessed hotspot: its own guess, made on
// the sprite AS SCANNED OUT (drm_reader does exactly that). At 0 the delivery path
// publishes it unchanged, which is why it has to be the real value and not a
// placeholder; at every other angle the path discards it and guesses again.
let (phx, phy) = scrap::drm_reader::infer_hotspot(&scan, sw, sh);
deliver_drm_cursor(display, 1, 7, sw as u32, sh as u32, phx, phy, false, scan, t);
let map = DRM_CURSOR.lock().unwrap();
let (_, c) = map.get(&display).expect("the cursor path published nothing");
assert_eq!(
(c.width as usize, c.height as usize),
(w, h),
"the published {name} sprite is upright-sized at {t}"
);
assert_eq!(c.colors, up, "the published {name} sprite is upright at {t}");
assert_eq!(
(c.hotx, c.hoty),
box_centre,
"the published {name} hotspot is the box centre at {t}"
);
}
}
// The arrow is untouched, and it sits exactly ON the boundary rather than safely inside
// it: its box is 3x6, which is the factor of two itself, so it keeps its tip only because
// the comparison is strict. That makes it the control for the other side of the threshold
// - loosen the rule to `* 1` and this line fails, tighten it past 2.22 and the
// theme-aspect case above fails. The two together pin where the boundary is.
let (arrow_px, aw, ah) = arrow();
assert_eq!(infer_hotspot(&arrow_px, aw, ah), (0, 0));
}
/// NOT a general DRM/Wayland contract, and should not be read as one. This pins the behaviour
/// MEASURED on i915 advertising rotate-180 with mutter: the primary plane scans out already
/// upright while the compositor pre-rotates the cursor sprite, and `wl_output` cannot tell
/// hardware rotation from compositor rotation, so the frame is left alone and the sprite is
/// turned. Arch with KDE Plasma is still wrong at 180, which is exactly why this is scoped to
/// what was measured rather than stated as a rule. The robust fix is to propagate the actual
/// KMS plane rotation instead of inferring both from the `wl_output` transform; until then,
/// changing this test means re-measuring on the compositor in question, not reasoning from it.
#[test]
fn a_180_output_turns_the_cursor_but_not_the_frame_on_i915_plus_mutter() {
assert_eq!(frame_transform(180), 0);
assert_eq!(frame_transform(90), 90);
assert_eq!(frame_transform(270), 270);
let (up, w, h) = arrow();
let (scan, sw, sh) = as_scanned_out(&up, w, h, 180);
let mut turned = Vec::new();
unrotate_bgra(&scan, sw, sh, 180, &mut turned);
assert_eq!(turned, up);
}
// The two above exercise the helpers, which cannot see WHICH angle the cursor path is handed
// or whether it turns 180 at all - the line that decides both is `if t != 0` in
// `deliver_drm_cursor`, and reverting it to master's `t == 90 || t == 270` leaves every helper
// assertion above still passing. So this drives the real path and reads back what it published.
#[test]
fn the_cursor_path_publishes_an_upright_sprite_at_every_angle() {
let (up, w, h) = arrow();
for (i, t) in [0, 90, 180, 270].into_iter().enumerate() {
// A display id of its own per angle: DRM_CURSOR is process-wide and keyed by display.
let display = 9_100 + i as i32;
let (scan, sw, sh) = as_scanned_out(&up, w, h, t);
deliver_drm_cursor(display, 1, 7, sw as u32, sh as u32, 0, 0, false, scan, t);
let map = DRM_CURSOR.lock().unwrap();
let (_, c) = map.get(&display).expect("the cursor path published nothing");
assert_eq!(
(c.width as usize, c.height as usize),
(w, h),
"the published sprite is upright-sized at {t}"
);
assert_eq!(c.colors, up, "the published sprite is upright at {t}");
assert_eq!((c.hotx, c.hoty), (0, 0), "the tip is the hotspot at {t}");
}
}
#[test]
fn unrotate_180_reverses_both_axes() {
let (src, w, h) = px_frame(&[&[1, 2, 3], &[4, 5, 6]], 0);
@@ -2390,4 +2825,349 @@ mod drm_capturer_tests {
assert!(demote_cooldown(1) + burn < Duration::from_secs(40));
assert!(demote_cooldown(5) + burn > Duration::from_secs(8 * 60));
}
// ---------------------------------------------------------------------------------------
// rustdesk#16242 round 2: the measurement behind the inference model.
//
// The question a synthetic fixture cannot answer: when the driver publishes no hotspot and
// the sprite has to be turned upright before guessing, how far from the THEME's real click
// point does each flow land? Both flows are driven here, per shape and per angle, against
// the hotspot the theme author wrote into the cursor file. It reads the installed Adwaita
// theme, so it prints instead of asserting and is ignored by default:
//
// cargo test --features drm --lib drm_capturer_tests::adwaita -- --ignored --nocapture
// ---------------------------------------------------------------------------------------
/// Minimal Xcursor reader. The format is a 16-byte header, a table of contents of 12-byte
/// entries, and one chunk per (nominal size, animation frame); an image chunk is 36 bytes of
/// header followed by width*height little-endian ARGB words, so byte 3 of each pixel is the
/// alpha `infer_hotspot` reads. Only the FIRST frame of each nominal size is taken.
fn xcursor_images(path: &std::path::Path) -> Vec<(u32, usize, usize, i32, i32, Vec<u8>)> {
let b = match std::fs::read(path) {
Ok(b) => b,
Err(_) => return Vec::new(),
};
let u32at = |o: usize| -> u32 {
if o + 4 > b.len() {
0
} else {
u32::from_le_bytes([b[o], b[o + 1], b[o + 2], b[o + 3]])
}
};
if b.len() < 16 || &b[0..4] != b"Xcur" {
return Vec::new();
}
let (hdr, ntoc) = (u32at(4) as usize, u32at(12) as usize);
let mut out: Vec<(u32, usize, usize, i32, i32, Vec<u8>)> = Vec::new();
for i in 0..ntoc {
let e = hdr + i * 12;
if u32at(e) != 0xfffd_0002 {
continue;
}
let nominal = u32at(e + 4);
if out.iter().any(|(n, ..)| *n == nominal) {
continue;
}
let p = u32at(e + 8) as usize;
let (w, h) = (u32at(p + 16) as usize, u32at(p + 20) as usize);
let (xhot, yhot) = (u32at(p + 24) as i32, u32at(p + 28) as i32);
let px = p + 36;
if w == 0 || h == 0 || px.saturating_add(w * h * 4) > b.len() {
continue;
}
out.push((nominal, w, h, xhot, yhot, b[px..px + w * h * 4].to_vec()));
}
out
}
fn dist(a: (i32, i32), b: (i32, i32)) -> f64 {
let (dx, dy) = ((a.0 - b.0) as f64, (a.1 - b.1) as f64);
(dx * dx + dy * dy).sqrt()
}
#[test]
#[ignore]
fn adwaita_hotspot_survey() {
let dir = std::env::var("SURVEY_DIR")
.unwrap_or_else(|_| "/usr/share/icons/Adwaita/cursors".to_owned());
let dir = std::path::Path::new(&dir);
let mut names: Vec<String> = std::fs::read_dir(dir)
.expect("no installed Adwaita cursors to measure")
.filter_map(|e| e.ok())
.filter(|e| e.file_type().map(|t| t.is_file()).unwrap_or(false))
.map(|e| e.file_name().to_string_lossy().into_owned())
.collect();
names.sort();
let want: u32 = std::env::var("SURVEY_SIZE")
.ok()
.and_then(|s| s.parse().ok())
.unwrap_or(24);
let mut display = 20_000;
println!("SURVEY size={want}");
println!("shape,size,w,h,truth_x,truth_y,box,t,sent_x,sent_y,base_x,base_y,base_err,head_x,head_y,head_err,master_x,master_y,master_err");
for name in &names {
let imgs = xcursor_images(&dir.join(name));
let Some((n, w, h, tx, ty, up)) = imgs.into_iter().find(|(n, ..)| *n == want) else {
println!("# {name}: no {want} px image");
continue;
};
// The opaque box, to tell the shapes apart afterwards.
let (mut minx, mut miny, mut maxx, mut maxy) = (w as i32, h as i32, -1i32, -1i32);
for (i, px) in up.chunks_exact(4).take(w * h).enumerate() {
if px[3] >= 128 {
let (x, y) = ((i % w) as i32, (i / w) as i32);
minx = minx.min(x);
maxx = maxx.max(x);
miny = miny.min(y);
maxy = maxy.max(y);
}
}
let bx = format!("{}x{}+{}+{}", maxx - minx + 1, maxy - miny + 1, minx, miny);
for t in [0, 90, 180, 270] {
let (scan, sw, sh) = as_scanned_out(&up, w, h, t);
// What the producer puts on the wire: the guess taken on the sprite as the plane
// holds it, with hot_measured false.
let sent = scrap::drm_reader::infer_hotspot(&scan, sw, sh);
// The flow before this PR: map that point back as if it were a pixel.
let base = unrotate_hotspot(t, sw as i32, sh as i32, sent.0, sent.1);
// The flow in this PR, read back from the real delivery path.
display += 1;
deliver_drm_cursor(display, 1, 1, sw as u32, sh as u32, sent.0, sent.1, false, scan, t);
let head = {
let map = DRM_CURSOR.lock().unwrap();
let (_, c) = map.get(&display).expect("nothing published");
(c.hotx, c.hoty)
};
let m = master_delivered(&up, w, h, t);
println!(
"{name},{n},{w},{h},{tx},{ty},{bx},{t},{},{},{},{},{:.2},{},{},{:.2},{},{},{:.2}",
sent.0, sent.1, base.0, base.1, dist(base, (tx, ty)),
head.0, head.1, dist(head, (tx, ty)),
m.0, m.1, dist(m, (tx, ty))
);
}
}
}
// -----------------------------------------------------------------------------------------
// rustdesk#16242 round 2: the guess measured against the hotspots a THEME declares.
//
// Every test above builds its own sprite, so all of them compare the guess with the guess.
// That can pin a mapping but it cannot say whether the guess is any good. These two read the
// expected value from the cursor theme instead - the click point its author wrote into the
// file, which is exactly what a compositor programs into HOTSPOT_X/Y when it has the
// property to program.
// -----------------------------------------------------------------------------------------
include!("drm_cursor_theme.rs");
/// Expand a fixture's packed alpha mask into the sprite the delivery path takes. Only alpha
/// is set: the guess reads nothing else.
fn theme_sprite(mask_hex: &str, w: usize, h: usize) -> Vec<u8> {
let bytes: Vec<u8> = (0..mask_hex.len() / 2)
.map(|i| u8::from_str_radix(&mask_hex[i * 2..i * 2 + 2], 16).expect("fixture hex"))
.collect();
let mut px = vec![0u8; w * h * 4];
for i in 0..w * h {
if bytes[i / 8] & (0x80 >> (i % 8)) != 0 {
px[i * 4 + 3] = 255;
}
}
px
}
/// The guess MASTER ships, frozen. Only a TALL box is centred there: the symmetric aspect
/// test came later, in this PR, so freezing that instead would measure this PR against its own
/// earlier revision rather than against what is merged.
fn master_guess(rgba: &[u8], w: usize, h: usize) -> (i32, i32) {
let (mut minx, mut miny, mut maxx, mut maxy) = (w as i32, h as i32, -1i32, -1i32);
for (i, px) in rgba.chunks_exact(4).take(w * h).enumerate() {
if px[3] >= 128 {
let (x, y) = ((i % w) as i32, (i / w) as i32);
minx = minx.min(x);
maxx = maxx.max(x);
miny = miny.min(y);
maxy = maxy.max(y);
}
}
if maxx < minx || maxy < miny {
return (0, 0);
}
let (bw, bh) = (maxx - minx + 1, maxy - miny + 1);
if bh > bw * 2 {
((minx + maxx) / 2, (miny + maxy) / 2)
} else {
(minx, miny)
}
}
/// What master DELIVERS for an upright sprite on an output turned by `t`: it guesses on the
/// sprite as the plane holds it and then maps that point as if it were a pixel, and it does
/// that only at 90 and 270 - 0 and 180 pass through untouched.
fn master_delivered(up: &[u8], w: usize, h: usize, t: i32) -> (i32, i32) {
let (scan, sw, sh) = as_scanned_out(up, w, h, t);
let (gx, gy) = master_guess(&scan, sw, sh);
if t == 90 || t == 270 {
unrotate_hotspot(t, sw as i32, sh as i32, gx, gy)
} else {
(gx, gy)
}
}
fn away(a: (i32, i32), b: (i32, i32)) -> f64 {
(((a.0 - b.0) as f64).powi(2) + ((a.1 - b.1) as f64).powi(2)).sqrt()
}
/// A hotspot names a point on the SHAPE, so the same sprite has to get the same click point
/// whatever angle the output happens to sit at. This drives the real delivery path for every
/// shape in the theme at all four angles and demands exactly that.
///
/// The maintainer's objection on this PR was a table of four shapes where the old flow landed
/// closer than the new one. It did, at some angles - and 16 to 19 px out at the others, which
/// is what the second half of this test measures: with the old flow not one of the 35 shapes
/// keeps its hotspot across the four angles, and the point moves by 15 px on average. That
/// number is also the control. Without it the first assertion would still pass on a revert,
/// since a flow that is wrong the same way at every angle is consistent too.
#[test]
fn a_published_hotspot_does_not_move_when_the_output_turns() {
let mut display = 21_000;
let (mut spread_sum, mut spread_max, mut spread_zero) = (0f64, 0f64, 0usize);
for &(name, w, h, _, _, mask) in THEME_SHAPES {
let (w, h) = (w as usize, h as usize);
let up = theme_sprite(mask, w, h);
let (mut published, mut mapped) = (Vec::new(), Vec::new());
for t in [0, 90, 180, 270] {
let (scan, sw, sh) = as_scanned_out(&up, w, h, t);
// What the producer puts on the wire: the guess taken on the sprite as the plane
// holds it, with no provenance behind it.
let sent = scrap::drm_reader::infer_hotspot(&scan, sw, sh);
mapped.push(unrotate_hotspot(t, sw as i32, sh as i32, sent.0, sent.1));
display += 1;
deliver_drm_cursor(
display, 1, 1, sw as u32, sh as u32, sent.0, sent.1, false, scan, t,
);
let map = DRM_CURSOR.lock().unwrap();
let (_, c) = map.get(&display).expect("the delivery path published nothing");
published.push((c.hotx, c.hoty));
}
assert!(
published.windows(2).all(|p| p[0] == p[1]),
"{name}: the published hotspot follows the output angle: {published:?}"
);
let spread = mapped
.iter()
.flat_map(|a| mapped.iter().map(move |b| away(*a, *b)))
.fold(0f64, f64::max);
spread_sum += spread;
spread_max = spread_max.max(spread);
if spread == 0.0 {
spread_zero += 1;
}
}
// The control, and it has to be read with the guess this PR now makes. A box centre and a
// heavier-half extreme both map like a pixel, so for the 16 shapes that land on one the
// old flow happens to be angle-independent too. The other 19 move, by up to 26.87 px on a
// 24 px sprite. Without this the assertion above would also pass on a revert: a flow that
// is wrong the same way at every angle is consistent too.
let n = THEME_SHAPES.len();
assert!(
n - spread_zero >= 15,
"the control has gone vacuous: the old flow now keeps {spread_zero} of {n} shapes \
stable, so the assertion above no longer separates the two flows"
);
assert!(
spread_sum / n as f64 > 5.0 && spread_max > 20.0,
"the control is weak: old-flow spread mean {:.2} max {:.2} over {n} shapes",
spread_sum / n as f64,
spread_max
);
}
/// How far the delivered hotspot lands from the click point the theme declares, per shape,
/// measured against MASTER and not against an earlier revision of this PR.
///
/// Master handles 0, 90 and 270 for the cursor (180 passes through untouched there), so the
/// comparison is over those three angles, which is the set master actually covers.
///
/// Two shapes stay further out than master and they are named rather than averaged away.
/// `help` is the honest limit of any bitmap rule: the theme puts its click point on the dot of
/// its question mark, which is not recoverable from alpha. `alias` is 0.51 px. Everything else
/// is equal or better, and the mean over the corpus falls from 12.08 px to 4.20.
#[test]
fn no_shape_lands_further_from_the_theme_than_master_except_the_two_no_bitmap_can_reach() {
const NOT_INFERABLE: [&str; 2] = ["help", "alias"];
let (mut sum_master, mut sum_now) = (0f64, 0f64);
let mut regressed = Vec::new();
for &(name, w, h, hx, hy, mask) in THEME_SHAPES {
let (w, h) = (w as usize, h as usize);
let up = theme_sprite(mask, w, h);
let truth = (hx, hy);
let angles = [0, 90, 270];
let mut e_master = 0f64;
let mut e_now = 0f64;
for t in angles {
e_master += away(master_delivered(&up, w, h, t), truth);
// The upright inference answers the same at every angle by construction; the
// angle-independence test above is what pins that.
e_now += away(scrap::drm_reader::infer_hotspot(&up, w, h), truth);
}
let (e_master, e_now) = (e_master / angles.len() as f64, e_now / angles.len() as f64);
sum_master += e_master;
sum_now += e_now;
if e_now > e_master + 0.005 && !NOT_INFERABLE.contains(&name) {
regressed.push((name, e_master, e_now));
}
}
let n = THEME_SHAPES.len() as f64;
assert!(
regressed.is_empty(),
"further from the theme hotspot than master, averaged over 0/90/270: {regressed:?}"
);
assert!(
sum_now / n <= 4.5 && sum_master / n >= 11.0,
"mean error over {n} shapes: master {:.2}, this pr {:.2} (measured 12.08 and 4.20)",
sum_master / n,
sum_now / n
);
}
/// The two shapes the test above excuses are excused for a measured reason, not because they
/// were in the way, and the excuse is bounded in BOTH directions it could grow: the average
/// over the angles master handles, and the worst single angle. The worst angle is the bigger
/// number and the one that would be felt - `help` at 270 is 8.00 px under master and 21.54
/// here - so leaving it unbounded would let the exemption widen quietly.
#[test]
fn the_two_excused_shapes_are_excused_by_how_much() {
// (shape, mean excess allowed, worst single-angle excess allowed). Measured: alias 0.51
// mean and 8.94 at 90; help 4.73 mean and 13.54 at 270.
for (name, mean_bound, angle_bound) in [("alias", 0.75f64, 9.5f64), ("help", 5.5, 14.5)] {
let &(_, w, h, hx, hy, mask) = THEME_SHAPES
.iter()
.find(|s| s.0 == name)
.expect("the corpus must carry the excused shapes");
let (w, h) = (w as usize, h as usize);
let up = theme_sprite(mask, w, h);
let truth = (hx, hy);
let now = away(scrap::drm_reader::infer_hotspot(&up, w, h), truth);
let angles = [0, 90, 270];
let mut worst = f64::MIN;
let mut total = 0f64;
for t in angles {
let m = away(master_delivered(&up, w, h, t), truth);
total += m;
worst = worst.max(now - m);
}
let mean_excess = now - total / angles.len() as f64;
assert!(
mean_excess <= mean_bound,
"{name} averages {mean_excess:.2} px worse than master, over the {mean_bound} \
this excuses"
);
assert!(
worst <= angle_bound,
"{name} is {worst:.2} px worse than master at its worst angle, over the \
{angle_bound} this excuses"
);
}
}
}
+48
View File
@@ -0,0 +1,48 @@
// Generated from the installed cursor theme by `adwaita_hotspot_survey` (the ignored test in
// `drm_capturer.rs`); see its doc comment for the command. adwaita-icon-theme 50.0-1, every shape
// the theme ships as a real file, at its 24 px nominal size - the GNOME default cursor size.
//
// Each entry is the shape name, the hotspot the THEME declares, and the sprite's alpha mask: one
// bit per pixel, row-major, most significant bit first, set where alpha >= 128. The mask is all
// the hotspot guess reads, and rotating a mask is exact, so it is the whole fixture.
//
// The point of carrying these is that the expected value comes from the theme author, not from
// our own heuristic: a test that compares the guess against the guess cannot say whether the
// guess is right.
const THEME_SHAPES: &[(&str, u32, u32, i32, i32, &str)] = &[
("X_cursor", 24, 24, 11, 12, "00000000000000000000000000000001830003c78007ffc007ffc007ffc003ff8001ff0001ff8003ff8007ffc007ffc003ef8003c780000000000000000000000000000000000000"),
("alias", 24, 24, 18, 5, "00000000000000000001ffc000ffc0007fc0003fc0007fc0007fc000ffc000ffc001fdc001f8c001f04001e00001e00001e00000e00000e000007000003000000000000000000000"),
("all-resize", 24, 24, 12, 11, "001800003c00007e0000ff0001ff8003ffc007ffe00f3cf01f3cf83ffffc7ffffe7ffffe3ffffc1f3cf80f3cf007ffe003ffc001ff8000ff00007e00003c00001800000000000000"),
("all-scroll", 24, 24, 11, 11, "00000000300000780000fc0001fe0003ff0007ff800e01c01e79e03efdf07efdf87efdf83efdf01e79e00e01c007ff8003ff0001fe0000fc00007800003000000000000000000000"),
("cell", 24, 24, 11, 11, "0000000078000078000078000078000078000078000078000030007f03f87f87f87f87f87f03f8003000007800007800007800007800007800007800007800000000000000000000"),
("col-resize", 24, 24, 12, 12, "0000000038000038000038000038000139000339800739c00f39e01ffff03ffff87ffffc3ffff83ffff80f39f00739e00739c0013900003800003800003800003800000000000000"),
("context-menu", 24, 24, 3, 1, "0000000000001000001800001c00001e00001f00001f80001fc0001fe7fe1ff7fe1ffffe1ffffe1ffffe1fe7fe1fe7fe1ff7fe1df7fe10fffe00fffe007ffe007800000000000000"),
("copy", 24, 24, 3, 1, "0000000000000000001000001800001c00001e00001f00001f80001fc0001fe3c01ffff01ffff81ffff81ffffc1f3ffc1e3ffc1c3ffc183ffc101ff8000ff00007e0000000000000"),
("crosshair", 24, 24, 11, 11, "0000000078000078000078000078000078000078000078000078007ffff87ffff87ffff87ffff8007800007800007800007800007800007800007800007800000000000000000000"),
("default", 24, 24, 3, 1, "0000000000001000001800001c00001e00001f00001f80001fc0001fe0001ff0001ff8001ffc001ffe001fe0001fe0001ff0001df00010f80000f800007800007800000000000000"),
("e-resize", 24, 24, 19, 13, "000000000000000000000000000078001078001878001c78001e78001f781ffff81ffff81ffff81ffff81ffff8001ff8001e78001c78001878001078000078000000000000000000"),
("ew-resize", 24, 24, 12, 12, "0000000000000000000000000000000081000181800381c00781e00ffff01ffff83ffffc1ffff81ffff80781f00381e00381c0008100000000000000000000000000000000000000"),
("grab", 24, 24, 11, 2, "000000000000001800003c0000ff0001ff8001ffe001fff001fff001fff001fff001fff00dfff01ffff01ffff00ffff00ffff007fff007fff003fff001fff000ffe0000000000000"),
("grabbing", 24, 24, 9, 5, "000000000000000000000000000000001f0000ff8001ffe001fff007fff00ffff00ffff00ffff00ffff007fff007fff003fff003fff001ffe0000000000000000000000000000000"),
("help", 24, 24, 12, 21, "000000007e0001ff8003ffc007ffc007ffe00fc7e00fc7e00fc7e0000fe0003fc0003f80007f00007e00007c00007c00000000007c00007c00007c00007c00007c00000000000000"),
("n-resize", 24, 24, 13, 6, "0000000000000000000ffff80ffff80ffff80ffff8007f00007f0000ff8001ffc003ffe007fff0003e00003e00003e00003e00003e00003e00003e00003e00000000000000000000"),
("ne-resize", 24, 24, 15, 10, "0000000000000000000000001ffff01ffff01ffff01ffff00000f00ffef007fef003fef001fef001fef003fef007fef00ffef01fcef01f86f01f02f01e00f00c0000000000000000"),
("nesw-resize", 24, 24, 11, 11, "00000000000000000000ffc0007fc0003fc0003fc0003fc0107fc018ffc01dffc01ff9c01ff0401fe0001fe0001fe0001ff0001ff800000000000000000000000000000000000000"),
("no-drop", 24, 24, 3, 1, "0000000000000000001000001800001c00001e00001f00001f80001fc0001fe3c01ffff01ffff81ffff81ffffc1f3ffc1e3ffc1c3ffc183ffc101ff8000ff00007e0000000000000"),
("not-allowed", 24, 24, 12, 12, "000000000000000000007e0001ff8003ffc007ffe00ffff00ffff01ffff81ffff81ffff81ffff81ffff81ffff80ffff00ffff007ffe003ffc001ff8000ff00000000000000000000"),
("ns-resize", 24, 24, 12, 13, "000000000000001000003800007c0000fe0001ff0003ff8007ffc0007c00007c00007c00007c00007c00007c0007ffc003ff8001ff8001ff0000fe00007c00003800000000000000"),
("nw-resize", 24, 24, 10, 10, "0000000000000000000000000ffff80ffff80ffff80ffff80f00000f7ff00f7fe00f7fc00f7f800f7f800f7fc00f7fe00f7ff00f73f80f61f80f40f80f0078000030000000000000"),
("nwse-resize", 24, 24, 11, 11, "0000000000000000001ff8001ff0001ff0001fe0001fe0001ff0401ff8c01ffdc01cffc0107fc0003fc0003fc0003fc0007fc000ffc0000000000000000000000000000000000000"),
("pointer", 24, 24, 7, 5, "00000000000000000000000000c00001e00001e00001e00001e00001ff0001ffe001fff001fff01dfff03ffff03ffff01ffff00ffff007fff003fff001fff000ffe0000000000000"),
("progress", 24, 24, 3, 1, "0000000000001000001800001c00001e00001f3e001fff801fffc01fffc01fffe01fffe01fffe01fffe01fffe01fffc01fffc01cff80103f00000000000000000000000000000000"),
("row-resize", 24, 24, 12, 13, "000000001000003800007c0000fe0001ff0003ff8007ffc0007c00007c007ffffc7ffffc7ffffc007c00007c0007ffc003ff8001ff8000ff00007e00007c00003800000000000000"),
("s-resize", 24, 24, 13, 18, "000000000000003e00003e00003e00003e00003e00003e00003e00003e0007fff003ffe001ffc000ff80007f00003e000ffff80ffff80ffff80ffff8000000000000000000000000"),
("se-resize", 24, 24, 15, 15, "0000000000000000001e00f01f02f01f86f01fcef00ffef007fef003fef001fef001fef003fef007fef00ffef00000f01ffff01ffff01ffff01ffff0000000000000000000000000"),
("sw-resize", 24, 24, 10, 15, "0000000000000000000f00780f40f80f61f80f73f80f7ff00f7fe00f7fc00f7f800f7f800f7fc00f7fe00f7ff00f00000ffff80ffff80ffff80ffff8000000000000000000000000"),
("text", 24, 24, 11, 12, "00000000000003de0003fe0003fe0000700000700000700000700000700000700000700000700000700000700000700000700000700000700003fe0003fe0003fe00000000000000"),
("vertical-text", 24, 24, 12, 11, "00000000000000000000000000000000000038001c38001c38001c3ffffc3ffffc3ffffc38001c38001c38001c000000000000000000000000000000000000000000000000000000"),
("w-resize", 24, 24, 6, 13, "0000000000000000000000001e00001e08001e18001e38001e78001ef8001ffff81ffff81ffff81ffff81ffff81ff8001e78001e38001e18001e08001e0000000000000000000000"),
("wait", 24, 24, 11, 11, "000000000000000000007e0001ff8003ffc007ffe00ffff00ffff01ffff81ffff81ffff81ffff81ffff81ffff80ffff00ffff007ffe003ffc001ff8000ff00000000000000000000"),
("zoom-in", 24, 24, 11, 10, "00000000000000000000fc0003ff0007ff800fffc00fffc01fffe01fffe01fffe01fffe01fffe01fffe00fffc00fffc007ffe003ffe000fff00000f80000f8000078000000000000"),
("zoom-out", 24, 24, 11, 10, "000000000000000000007e0001ff8003ffc007ffe007ffe00ffff00ffff00ffff00ffff00ffff00ffff007ffe007ffe003fff001fff0007ff800007c00007c00003c000000000000"),
];
+3 -1
View File
@@ -7,6 +7,8 @@ var show_elevation = true;
var is_privacy_mode_supported = handler.get_supported_privacy_mode_impls() != '[]';
var allow_perm_change_in_accept_window =
handler.get_builtin_option('enable-perm-change-in-accept-window') != 'N';
var hide_elevate_button_in_accept_window =
handler.get_builtin_option('hide-elevate-button-in-accept-window') == 'Y';
var svg_elevate = <svg t="1667992597853" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="1850" width="16" height="16" xmlns:xlink="http://www.w3.org/1999/xlink"><path d="M892.761 160.724v426.504c0 25.588-6.419 51.036-19.177 76.339-12.798 25.336-29.547 49.86-50.254 73.627-20.707 23.79-44.372 46.296-70.97 67.516-26.589 21.244-53.543 40.177-80.921 56.768-27.363 16.623-53.968 30.461-79.801 41.438-25.809 11.008-48.433 18.547-67.871 22.64l-9.203 1.53-8.43-1.53c-19.958-4.093-43.094-11.632-69.432-22.64-26.337-10.969-53.708-24.816-82.080-41.438-28.388-16.591-56.256-35.524-83.618-56.768-27.378-21.219-51.776-43.725-73.265-67.516-21.488-23.759-38.868-48.291-52.155-73.627-13.319-25.305-19.974-50.759-19.974-76.339v-426.504l31.455-4.629 352.892-65.97 359.784 65.97 23.017 4.629zM510.028 151.884l-4.211-0.844-302.89 51.476v269.101h307.102v-319.734zM815.434 471.634h-305.406v383.031c19.682-4.51 41.052-11.411 64.141-20.692 23.033-9.249 45.815-20.234 68.304-32.867 22.513-12.672 44.159-26.739 64.969-42.203 20.818-15.472 39.23-32.047 55.277-49.797 16.024-17.703 28.822-36.131 38.386-55.222 9.549-19.131 14.328-38.553 14.328-58.235v-124.015z" p-id="1851" fill="#ffffff"></path></svg>;
var hide_cm = undefined;
@@ -80,7 +82,7 @@ class Body: Reactor.Component
{c.port_forward ? <div>Port Forwarding: {c.port_forward}</div> : ""}
<div style="size:*"/>
<div .outer_buttons>
{!auth && !disconnected && show_elevation_btn && show_accept_btn ? <button #elevate_accept .control .elevate .button><span><span><span>{svg_elevate}</span><span>{translate('Accept')}</span></span></span></button> : "" }
{!auth && !disconnected && show_elevation_btn && show_accept_btn && !hide_elevate_button_in_accept_window ? <button #elevate_accept .control .elevate .button><span><span><span>{svg_elevate}</span><span>{translate('Accept')}</span></span></span></button> : "" }
{auth && !disconnected && show_elevation_btn ? <button #elevate .control .elevate .button><span><span><span>{svg_elevate}</span><span>{translate('Elevate')}</span></span></span></button> : "" }
<div .inner_buttons style={auth ? "display:none;":""}>
{!auth && show_accept_btn ? <button #accept .control .button>{translate('Accept')}</button> : "" }
+1 -1
View File
@@ -122,7 +122,7 @@ impl SciterHandler {
impl InvokeUiSession for SciterHandler {
fn set_cursor_data(&self, cd: CursorData) {
let mut colors = hbb_common::compress::decompress(&cd.colors);
let mut colors: Vec<u8> = cd.colors.into();
if colors.iter().filter(|x| **x != 0).next().is_none() {
log::info!("Fix transparent");
// somehow all 0 images shows black rect, here is a workaround
+35 -1
View File
@@ -386,14 +386,35 @@ var cur_local_x = 0;
var cur_local_y = 0;
var cursors = {};
var image_binded;
const MAX_CURSOR_RASTER_SIZE = 1024;
var cursor_scale_limited = false;
function limitCursorImageScale(img, factor) {
// Subtraction rejects NaN and Infinity without converting them to integers.
var valid = factor > 0 && factor - factor == 0;
var side = img.width > img.height ? img.width : img.height;
var max_factor = MAX_CURSOR_RASTER_SIZE.toFloat() / side;
// Invalid factors use the validated source image at its original size.
var limited_factor = valid ? (factor > max_factor ? max_factor : factor) : 1.;
var limited = !valid || limited_factor != factor;
if (limited && !cursor_scale_limited) {
stdout.println("Cursor image scale " + factor + " limited to " + limited_factor
+ " (maximum raster side " + MAX_CURSOR_RASTER_SIZE + ")");
}
cursor_scale_limited = limited;
return limited_factor;
}
function scaleCursorImage(img) {
var factor = cursor_scale;
if (cursor_img.style#display != 'none') {
factor /= scaleFactor;
}
factor = limitCursorImageScale(img, factor);
var w = (img.width * factor).toInteger();
var h = (img.height * factor).toInteger();
if (w < 1) w = 1;
if (h < 1) h = 1;
cursor_img.style.set {
width: w + "px",
height: h + "px",
@@ -413,7 +434,10 @@ function updateCursor(system=false) {
if (system) {
handler.style#cursor = undefined;
} else if (cur_img) {
handler.style.cursor(cur_img, (cur_hotx * cursor_scale).toInteger(), (cur_hoty * cursor_scale).toInteger());
var img = cursors[cur_id][0];
handler.style.cursor(cur_img,
(cur_hotx * cur_img.width.toFloat() / img.width).toInteger(),
(cur_hoty * cur_img.height.toFloat() / img.height).toInteger());
}
}
@@ -468,6 +492,16 @@ handler.setCursorPosition = function(x, y) {
var y = cur_y - cur_hoty;
x *= cursor_scale / scaleFactor;
y *= cursor_scale / scaleFactor;
// The overlay may still be hidden, so compute its raster before refreshCursor().
// Keep screen coordinates on the video scale and only adjust the hotspot.
var img = cursors[cur_id][0];
var hotspot_scale = limitCursorImageScale(img, cursor_scale / scaleFactor);
var w = (img.width * hotspot_scale).toInteger();
var h = (img.height * hotspot_scale).toInteger();
if (w < 1) w = 1;
if (h < 1) h = 1;
x += cur_hotx * (cursor_scale / scaleFactor - w.toFloat() / img.width);
y += cur_hoty * (cursor_scale / scaleFactor - h.toFloat() / img.height);
cursor_img.style.set {
left: x + "px",
top: y + "px",