Compare commits

..
Author SHA1 Message Date
rustdeskandClaude Opus 5.5 071d9b1eff fix(linux): stop using the window in onWindowClose once GTK destroyed it
On Linux, GTK destroys the window on a close request unless prevent-close
is on. When the main window is the last active one, onActiveWindowChanged()
turns prevent-close off and calls close(), yet onWindowClose() still went
on to hide() the destroyed window, and the close event that close() emits
re-entered onWindowClose() to save the frame through isMaximized(). The cm
and install windows never turn prevent-close on, so their window is always
gone by the time onWindowClose() runs.

With window_manager before cf4aef05 those calls segfaulted in
gtk_window_is_maximized; since then they fail with an unhandled
PlatformException(window_destroyed). Return early in both places instead.
Other platforms and sub windows keep the old path.

Fixes #16512

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WS1HTjp6UQuG43KEcQPq1R
2026-10-15 15:01:40 +08:00
RustDeskandClaude Opus 5.5 f1fa432bc8 Fix fdroid bridge version (#16560)
* fix(fdroid): generate the bridge with the Flutter version bridge.yml uses

#15139 moved the bridge Flutter version from bridge.yml's env into its
job matrix, so build_fdroid.sh read `.env.FLUTTER_VERSION` as "null".
The F-Droid recipe worked around that by pinning it to 3.24.5, which
equals ANDROID_FLUTTER_VERSION, and the script only generated the bridge
when the two versions differed, so the build failed on the missing
src/bridge_generated.rs.

Read the version from the default bridge-artifact matrix entry (3.22.3),
and always generate the bridge: the build needs it whether or not the
two Flutter versions match.

Fixes #16549

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

* fix(fdroid): keep the recipe's version sed from overriding the bridge Flutter

The F-Droid recipe works around the old "null" read with
`sed 's/${FLUTTER_BRIDGE_VERSION}/<version>/'`, and its auto-update
copies that line into every new version. The 1.5.0 recipe pinned 3.24.5
and then 3.47.7, but flutter_rust_bridge codegen only works with the
Flutter version bridge.yml uses (3.22.3). Pass the unbraced variable to
prepare_flutter so that sed no longer matches the call.

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

* fix(fdroid): raise the Gradle heap for the AGP 8 build

#15603 moved the Android build to Gradle 8.11.1 / AGP 8.10.1 with
compileSdk 36 and desugaring. The first F-Droid 1.5.0 build got past the
bridge and the Rust library, then failed in assembleRelease with "Gradle
build daemon has been stopped: since the JVM garbage collector is
thrashing", because gradle.properties still caps the heap at 1 GiB. CI
has long raised it to 2g; do the same here. A recipe that already
rewrites the -Xmx1024M setting keeps its own value.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 14:42:39 +08:00
Maison da Silva 538126d42c Update Portuguese translations for keyboard shortcuts (#16555) 2026-10-15 12:06:47 +08:00
bovirus 9c6d3fcb4f Update Italian language (#16551)
* Update Italian language

* Update Italian language
2026-10-15 12:06:36 +08:00
Alex Rijckaert c230c57139 Update Dutch translation (#16540) 2026-10-15 12:05:52 +08:00
Leo Camus e614de83fc fix: read host= from an exe path with non-ASCII characters (#16556)
get_custom_server_from_string located "host=" in s.to_lowercase() and
sliced s with that byte index. Lowercasing can change a character's byte
length ("İ" is 2 bytes, "i̇" is 3), and on Windows the string is the full
exe path, so a profile such as C:\Users\İsmail shifted the slice past the
"h" and host came back empty. The client then fell back to the default
rendezvous server.

"host=" is ASCII, so search s.to_ascii_lowercase(), which keeps byte
offsets.
2026-10-15 10:30:06 +08:00
21pages e910029f51 feat: use the configured proxy for WebSocket connections (#16386)
* feat: add opt-in WebSocket proxy support

Add a WebSocket proxy option to the proxy dialog and custom client settings.
Keep WebSocket connections direct by default and use the configured proxy
without direct fallback when enabled.

Preserve relay targets regardless of the proxy address family and restart
connections when the option changes. Update hbb_common for proxy support.

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

* update hbb_common

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

* fix: remove WebSocket proxy opt-in

* chore: restore proxy settings UI and translations

* fix: update hbb_common for proxy read progress

* fix: update hbb_common proxy connections and IPv6 parsing

* fix: update hbb_common WebSocket local address

* update to rustdesk/hbb_common

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

---------

Signed-off-by: 21pages <sunboeasy@gmail.com>
2026-10-14 22:49:35 +08:00
rustdeskandClaude Opus 5.5 256dc9bc12 docs: scope the -p rule to macOS and Windows
Linux CI runs cargo test --workspace, so a Linux-gated test in another
crate already runs there.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WS1HTjp6UQuG43KEcQPq1R
2026-10-14 16:39:57 +08:00
RustDeskandClaude Opus 5.5 b1761ee676 Ci run all dart tests (#16328)
* ci: run every Dart test, not three files

The step ran only the three cursor test files, so the other nine files
under flutter/test (terminal, file model, autocomplete, ...) never ran
on any pull request. With no path the runner takes the whole directory.

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

* ci: run the Rust tests CI could not reach

cargo test --workspace runs with the default features on x86_64 Linux
only, so the tests behind `windows`, `not(target_os = "linux")`,
`unix-file-copy-paste` and drmtap_dl's `tests` module never ran: the
platform, portable-service and audio tests, the clipboard crate's file
copy-paste and Windows file-name tests, and the drmtap loader's.

The macOS and Windows build jobs now run `cargo test --lib` after the
build with the build's own feature set, plus the clipboard crate. The
Linux job's list of named test runs gains drmtap_dl and the clipboard
feature. AGENTS.md says where tests go and what CI runs.

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

* ci: drop the skips for tests that no longer exist

#16539 removed test_get_cursor_pos and test_get_key_state, the only
tests these skips matched.

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

---------

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-14 16:31:58 +08:00
Mariano Abad d011aa3ea6 fix(wayland): a pending portal request no longer stalls the server (#16542)
* fix(wayland): a pending portal request no longer stalls the server

The screencast portal waits for the user while its picker is open, up to
three minutes. check_init waited under the CAP_DISPLAY_INFO write lock on
a tokio worker and get_capturables under RDP_SESSION_INFO. Every desktop
login read the display state on a worker behind them, and the session
close when the last connection went waited for the slot on a worker too.
With the server on 4 cpus a second login was enough: new connections
were accepted by the kernel and not served until the request ended
(#15973).

The locks keep their role: the write lock still serializes inits and
orders them with clear(), and the slot still orders the session close
calls after a pending request. What changes is where the waiting happens.
The part of check_init under the write lock moves, as is, to
init_displays(), run in spawn_blocking. is_inited and the first look in
check_init use try_read; when a writer holds the lock, is_inited answers
not inited yet and check_init redoes its look in spawn_blocking, then
goes on as before. get_displays_and_primary takes its read guard in
spawn_blocking, is_rdp_session_hold uses try_lock, close_session from the
ipc listener runs in spawn_blocking, and try_close_session from
AuthedConnID::drop on its own thread.

* fix(wayland): throttle the log when the session close thread cannot start

A peer can drop connections at any rate, so the error logged when
AuthedConnID::drop cannot spawn the thread for try_close_session goes
through throttled_log!, once a minute, like the auto-login logs of this
file (greptile on #16542).

* fix(wayland): count the remote connections again in the close thread

The session close moved to its own thread in this pr, so a remote that
comes in after the count and before the thread runs could have the
session it reuses closed under it. The thread counts the remote
connections again right before try_close_session, which brings the
window back to the one the close had on the dropping thread (coderabbit
on #16542).

* fix(wayland): one portal session close at a time, for remote and camera connections only

The close that AuthedConnID::drop runs off the dropping thread spawned one
OS thread per drop that left no remote connection, whatever the connection
type, and while a portal request waits for the user each of those threads
waited for the session slot. Now only a remote or view camera connection
leaving asks for the close (their video service is the one that opens the
portal session), no thread starts when the slot is free and empty (drm,
x11, nothing left to close), and one close runs at a time: a close asked
while one runs is left to it. The logic moves to wayland.rs; connection.rs
keeps a hook.
2026-10-14 16:26:46 +08:00
RustDeskandClaude Opus 5.5 9997b7a3b8 test: remove tests that do not pin user-visible behavior (#16539)
* test: remove tests that do not pin user-visible behavior

Apply the AGENTS.md test rules to the existing Rust and Flutter suites.
A test is kept when it is the only coverage of user- or API-visible
behavior, the regression test of a reported or fixed bug, a security
boundary (one test per rejection class), or a check against an external
reference. Tests that assert private state or the order of internal
steps, pin review-round corner cases, or repeat what a kept test already
covers are removed.

Rust: 679 -> 298 tests. Dart: 118 -> 45 tests.

Test-only helpers left without callers go with them
(applyLastOnlineStateForTesting, terminalKeyboardRowWidth,
debugBufferedInputCount, tokio's test-util dev feature), and cfg gates
and visibility that existed only for the deleted tests are narrowed.
Runtime behavior is unchanged.

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

* test: keep tests that pin security and user-visible behavior

Restore six tests that review showed are the only coverage of their
behavior:

- update metadata rejects an artifact file name with path components;
- ICE candidates from another session are dropped;
- KCP delivers every multi-segment frame queued before a close;
- set_files rejects an empty name in a multi-file transfer;
- a lopsided elongated cursor keeps its centre hotspot (#16242);
- toggling Show hidden during a pending same-path read issues a new read.

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

* test: keep offline update and key-exchange downgrade rejections

Restore three tests that are the only coverage of their rejection class:

- offline update metadata rejects a signed artifact with an http or
  credential-bearing URL;
- offline verification rejects a renamed local file and a version that
  does not match the release;
- a key-exchange pick lowered in transit leaves both sides unable to
  decrypt, so a v0 fallback after a failed v1 decrypt cannot pass
  unnoticed.

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

* test: keep the decomposed-grapheme and reconnect-cancel tests

Each catches a plausible wrong change that passes every kept test:
mapping the first scalar under a locked Ctrl turns é into \x05,
and a reconnect that does not fail pending reads leaves them hanging
until the 30 s timeout.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 14:45:22 +08:00
Leo Camus 76ab280ae9 fix(terminal): trim the replay buffer when output has no newline (#16545)
* fix(terminal): trim the replay buffer when output has no newline

OutputBuffer::append returned early when the last line was incomplete
and the new chunk had no newline, so the trim loop never ran. A program
that writes without newlines (a minified file through cat, a \r
progress bar) grew the replay buffer past MAX_OUTPUT_BUFFER_SIZE
without bound, one 4 KiB PTY read at a time, until a newline arrived.

Signed-off-by: leoca <leo.camus23@gmail.com>

* fix(terminal): keep recent output when trimming a line without newline

Trimming popped the whole incomplete line once it passed
MAX_OUTPUT_BUFFER_SIZE, so the reconnect replay could come back empty.
Newline-free output now goes into a new chunk once the incomplete one
holds DEFAULT_RECONNECT_BUFFER_BYTES, and trimming drops the oldest
chunks while the newest bytes stay. The test checks get_recent.

Signed-off-by: leoca <leo.camus23@gmail.com>

* fix(terminal): trim an oversized incomplete line to its newest half

Splitting the incomplete line into chunks made get_recent return whole
chunks only, so a reconnect could replay as little as the newest read.
Keep one line and, when it alone is over MAX_OUTPUT_BUFFER_SIZE, drop
its oldest bytes down to half the cap. The copy then happens once per
half buffer instead of on every append, and the replay keeps the
newest DEFAULT_RECONNECT_BUFFER_BYTES.

Signed-off-by: leoca <leo.camus23@gmail.com>

---------

Signed-off-by: leoca <leo.camus23@gmail.com>
2026-10-14 12:35:53 +08:00
HeZheng 29a160fc7e fix(mobile): prevent late mouse-down after floating button release (#16541)
Signed-off-by: zhenghe <zhenghe2009@gmail.com>
2026-10-14 11:26:13 +08:00
Mariano Abad 49a9574f97 fix(drm): pace the producer to the rate the encoder takes, with the panel refresh as floor (#16423)
* fix(drm): pace the producer to the rate the encoder takes, with the panel refresh as floor

The root producer slept a fixed 33 ms after every grab, so every DRM stream topped
out at 30 fps whatever the client asked (rustdesk#16175). Measured on a
1920x1080@60 i915 box with the client at Custom 60 and QoS settled at 60: 30
grabs, 30 converted, 29.8 sent. A shorter fixed interval reaches the rate but
oversamples: at 8 ms the same box grabbed and converted 117/s for 60 sent.

The consumer now tells the producer the rate it encodes at, in the ack byte it
already sends per converted frame: 0x01 as before, or 0x80|fps. Every producer
counts ack bytes and never read their value, so an older service sees exactly
the same credit and keeps its 33 ms; the JSON handshake and the ack count and
timing do not change. The rate is the encoder's spf (what frame() is called
with), lowered to what the encoder achieves when it is busy longer than spf per
frame: the time from one frame() call to the next, less what the call spent
waiting for a frame, so a late producer cannot talk its own demand down.

The producer replaces the post-work sleep with a deadline: the encoder's period
above 30 fps, the old 33 ms from 30 down to 15, and half the encoder's period
below 15, never faster than the panel (the exact CRTC refresh from libdrmtap
0.5.9's drmtap_crtc_refresh, re-read once a second; with an older library the
whole-hertz refresh the enumeration already read, so no extra connector probe).
The worker still wakes at least every 33 ms, because each tick also reads the
cursor and a slow frame rate must not slow the cursor down. Without a demand (an
older consumer, or before the first frame() call) the old 33 ms sleep stays.
MAX_STALLED and the WouldBlock retry keep their 5 s budget, pinned by a const
assertion.

Tests: the ack byte round trip and that it is one byte on the wire, the drain
(seeded byte streams: every byte one credit, the newest demand wins), the pacing
interval table (panel floor, below 30 and below 15, a 23.976 Hz panel), the panel
period rounded up, the deadline and its overrun, the wake that keeps the cursor
at 33 ms, the demand from spf and from a busy encoder, the busy time without the
wait (pure and through frame()), the demand log once per connection, the
whole-hertz fallback, and the reader's refresh answer. Each rule has a mutation
that turns its test red.

* ci: run the drm pacing tests in the drm step

drm_pacing_tests (src/ipc/drm.rs) and crtc_refresh_tests (libs/scrap
drm_reader.rs) match none of the existing filters.

* test(drm): keep three tests, on outputs and not on internal state

Per AGENTS.md (Tests), keep one to three tests, on outputs and not on internal
state: the demand ack as it goes on the wire, the producer interval for a
demand and a panel, and the exact refresh the reader returns.

* test(drm): the ack test goes through the producer drain

Per review: send_frame_ack(60) read back through drain_frame_acks gives one
credit and a demand of 60, so dropping the demand read in the producer turns
the test red. The interval test also pins drm_panel_period(148352, 2475) to
16_683_294 ns.

* fix(drm): time the encoder only after a frame() call that returned a frame

Since #16450 frame() drops a repeat as WouldBlock. The time after such a
call is video_service sleeping out its spf, and after a timeout it is
about zero once the wait is subtracted. Neither follows an encode, so
neither is a sample of the encoder pace now. Uses returned_at from #16450;
no new state.

* fix(drm): ask for the old 33 ms tick while the screen is still

Since #16450 a still screen is grabbed at the demand and dropped in
frame(), twice as often as master at 60. After 100 ms without a new
frame the demand is capped at 30, the old producer tick, and the next
new frame lifts it. 100 ms is three of those ticks, so a producer paced
at 30 in motion never reads as still. Uses returned_at; no new state.

* test(drm): a dropped repeat or timeout is no encoder time; a still screen asks for the old tick

Per review: the demand frame() reports stays with a 50 ms encoder through
a still screen of repeats and timeouts, and a still screen asks for 30
after STILL_AFTER until a new frame brings back 60.

* fix(drm): start the encoder average over when the rate goes up

Per review: the samples hold the sleep video_service paces itself with, so
after a rate increase (custom fps 1 -> 60, or QoS recovering) an average
taken at the old rate kept the demand low and the producer slow. A
shorter spf than the last now starts the average over and drops the
sample that spans the change. The demand is computed in one method that
takes its time as input, the still cap included.

* test(drm): drop the two pacing tests of the last round

Per review: they read shared.demand_fps and slept for real. The three
tests stay.

* build: pin libdrmtap 0.5.12 (rustdesk-org/libdrmtap 5936a7a88)

The panel floor of the pacing reads drmtap_crtc_refresh(), added in
libdrmtap 0.5.9. The mirror carries v0.5.12 since 2026-10-13, so the pin
moves there.

The rest of the range from 0.5.8 changes no struct in drmtap.h: 0.5.10
reads its environment through secure_getenv and loads no GL in a setuid,
setgid or file-capability process, which rustdesk does not run; 0.5.11
makes drmtap_deswizzle, also the CPU fallback of a tiled grab, refuse a
destination stride narrower than its rows instead of writing past it,
and exports drmtap_frame_owns_data, unused here; 0.5.12 changes only
docs and the version.
2026-10-14 10:44:43 +08:00
0740063863 Keyboard shortcuts (#14933)
* fix web break introduced in 38f130071 fix(linux): enable mouse side buttons in remote sessions (#14848)

* feat(shortcuts): user-configurable keyboard shortcuts for session actions

  Adds a keyboard shortcut feature (Rust matcher + Dart UI + cross-language
  parity tests) that lets users bind combinations like Ctrl+Alt+Shift+P to
  session actions. Bindings are stored in LocalConfig under
  `keyboard-shortcuts`; the matcher gates dispatch on `enabled` and
  `pass_through` flags so flipping the master switch off is a hard stop.

  Wire-up summary:
  - src/keyboard/shortcuts.rs: matcher, default bindings, parity test against
    flutter/test/fixtures/default_keyboard_shortcuts.json
  - src/keyboard.rs: shortcut intercept in process_event{,_with_session},
    feature-gated to `flutter`; runs before key swapping so users bind to
    physical keys
  - src/flutter_ffi.rs: main_reload_keyboard_shortcuts +
    main_get_default_keyboard_shortcuts; reload_from_config seeded in main_init
  - flutter/lib/common/widgets/keyboard_shortcuts/: shared config page body,
    recording dialog, shortcut display formatter, action group registry
  - flutter/lib/desktop/pages/desktop_keyboard_shortcuts_page.dart and
    flutter/lib/mobile/pages/mobile_keyboard_shortcuts_page.dart: platform
    shells around the shared body
  - flutter/lib/models/shortcut_model.dart: per-session ShortcutModel +
    registerSessionShortcutActions for actions with no toolbar TToggleMenu /
    TRadioMenu (fullscreen, switch display/tab, close tab, voice call, etc.)
  - flutter/lib/common/widgets/toolbar.dart: optional `actionId` field on
    TToggleMenu / TRadioMenu, plus per-helper auto-register pass that wires
    tagged entries' existing onChanged into the ShortcutModel
  - flutter/test/keyboard_shortcuts_test.dart + fixtures: cross-language
    parity (default bindings, supported key vocabulary)

  Design principles applied during review:

  1. Additions are fine; modifications to original logic must be deliberate.
     Tagging an existing TToggleMenu entry with `actionId:` is an addition.
     Rewriting its onChanged to satisfy a new contract is a modification —
     and was reverted for every case where the original click behavior was
     working. Four closures were touched and then reverted (mobile View
     Mode, Privacy mode multi-impl, Relative mouse mode, Reverse mouse
     wheel); their shortcuts are wired via standalone closures in
     shortcut_model.dart instead.

  2. Toolbar auto-register is reserved for entries whose onChanged is
     inherently self-flipping — typically `sessionToggleOption(name)` where
     the named option is flipped in place and the input bool is unused. The
     register pass passes `!menu.value` from registration time, which is
     harmless under self-flipping but wrong for closures that consume the
     input bool directly. Tagging a non-self-flipping entry forces a closure
     rewrite; choose non-toolbar registration in that case.

  3. When shortcuts are disabled, toolbar behavior must be bit-for-bit
     unchanged. The matcher's `enabled`-gate already guarantees no
     dispatch; the auto-register pass is left unconditional (its only effect
     is HashMap operations on a separate ShortcutModel) so mid-session
     enable works without a reconnect. The trade-off is intentional and
     documented at the top of toolbarControls.

  4. Comments stay terse. Rationale lives in one place — the doc comment of
     the helper or registration site, not duplicated at every call site.

  5. Where an existing helper needs a new optional behavior (e.g.
     `_OptionCheckBox` gaining a tooltip slot), the new branch must reduce
     to byte-identical output for existing callers (`trailing == null`
     case → original `Expanded(Text)` layout). Verified.

  6. Action IDs and labels stay consistent. Renamed `reset_cursor` →
     `reset_canvas` so the action ID matches its user-facing label
     ("Reset canvas") and capability flag.

  Out-of-scope but included:
  - AGENTS.md: documents flutter_rust_bridge no-codegen workflow and the
    Web target's hand-written TS client, since both are load-bearing for
    any new FFI work.
  - remote_toolbar.dart: i18n fix for the per-monitor tooltip ("All
    monitors" / "Monitor #N"), unrelated to shortcuts but kept here.

* langs

* fix(keyboard): shortcuts, harden config and callback lifecycle

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

* feat(keyboard): shortcuts, color of "Reset to defaults"

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

* feat(keyboard): shortcuts, release keys before shortcut callback

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

* feat(keyboard): shortcuts, debug web

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

* fix(keyboard): iPad, icon

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

* langs: add shortcut keys to az, gl, ur

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

* fix(keyboard): shortcuts, keep local modifiers and release keys on the right session

When a chord fired, the shortcut path reused release_remote_keys(), which
replays synthetic releases through process_event(). That cleared the local
MODIFIERS_STATE while the user still held the modifiers, so the next key of
a held chord no longer matched and leaked to the remote, and it sent the
releases to the globally current session instead of the one that typed the
chord.

The shortcut path now releases the remote keys itself: it sends through the
caller's session, and restores the modifiers it released on the remote as
still held locally. The press that fired is remembered until its release,
so its auto repeats and its release are consumed instead of reaching the
remote.

Also state the contract for unavailable actions: a bound chord always
belongs to RustDesk and is a no-op when the session has no handler.

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

* fix(keyboard): shortcuts, record the physical key

The recording dialog and the Web Flutter matcher named keys by
LogicalKeyboardKey, while the native matcher sees the physical key through
its USB HID usage and the Web JS matcher through KeyboardEvent.code. On
AZERTY, QWERTZ, Dvorak and similar layouts a recorded binding then did not
fire, or fired from another key.

Name keys by their physical position everywhere: physicalKeyName maps the
USB HID usage to the stored name. A new fixture pins every name to its USB
HID usage, checked on the Dart side and against rdev::usb_hid_key_from_code
on the Rust side, and a test covers AZERTY and QWERTZ events.

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

* fix(keyboard): shortcuts, keep an empty binding list on re-enable

setEnabled seeded the defaults whenever the binding list was empty, so a
user who cleared every binding got all defaults back after disable and
enable. Seed only when the config has never held a bindings list.

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

* fix(keyboard): shortcuts, track every fired key until its release

FIRED_KEY held a single key, so overlapping shortcut keys broke it: with the
chord held, P then C overwrote P, P's release reached the remote, and a P
repeat could fire the screenshot again. A repeat after the modifiers were
released was also treated as a new press and leaked to the remote.

Keep a set of fired keys instead. Once a press fires, every event of that
key belongs to RustDesk until its release: repeats are consumed without
dispatching, whatever the modifiers do, and the release removes the key.
Entries whose release never arrives are dropped when a session view is
entered or a session is closed, not by guessing from the modifiers.

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

* fix(keyboard): shortcuts, keep fired keys per session

FIRED_KEYS was process-global while dispatch is per session. Closing or
entering any session cleared the fired keys of all of them, so a key still
held in another session leaked its release to that remote, and a key fired
in one session made the same key in another session look like a repeat.

Key the fired set by session: try_dispatch resolves the session first and
only looks at that session's keys, and session_close clears only the
closing session. Entering a session view no longer clears anything: it is
a pointer enter, and a fired key may still be physically held across it.
A key whose release is missed otherwise heals itself: its next press is
consumed as a repeat and that release removes it.

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

* fix(shortcuts): preserve input state and refresh action availability

* fix(keyboard): shortcuts, keep a fired key owned across session close

Close tab is itself a shortcut, so the session that consumed the key press
is gone before the key is released. Both matchers dropped the key with the
session: the Flutter dispatcher removed its own entries in clear(), and the
Rust set was keyed by session and cleared in session_close. The release,
and the repeats while the key stayed held, then reached the next session's
remote as ordinary input.

Ownership of a fired key is physical, so it is now one set shared by every
session on each side, and closing a session no longer touches it: clear()
only drops the pending action and modifier replay, and the Rust session
state only tracks released modifiers. A key whose release is missed heals
itself on its next press. Entering view-only with the Flutter input source
still clears the Rust set, since that source stops routing key events to it.

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

* fix(keyboard): shortcuts, drop the Toggle Input Source action

The action switches the key capture backend between key down and key up.
Fired-key ownership lives in whichever matcher saw the press, the Flutter
dispatcher or the Rust set, and there is no handoff between them: after the
switch the repeats and the release of the held key reach the other backend,
which forwards them to the remote and, while the chord is held, matches the
action again and toggles the source back. Remove the shortcut instead of
building a handoff for one action. The toolbar radio menu is unchanged.

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

* perf(keyboard): shortcuts, parse the config once per stored value

The Flutter matcher read the local config three times and parsed its JSON
three times on every key press in legacy mode, on Web and in view-only.
Keep one parsed snapshot keyed by the raw stored string, so a key press
costs one config read and no parsing while the config is unchanged. The
existing readers are thin views of the same snapshot.

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

* fix(keyboard): shortcuts, run focus-changing actions on key release

Close tab and tab switching move keyboard focus to another session before
the key that fired them is released. On Linux the Flutter input source
routes map-mode sessions through the Rust matcher and legacy-mode sessions
through the Dart matcher, and neither knows the other's fired keys, so
after such an action the repeats and the release of the held key reached
the next session's remote, and the key stayed recorded as fired in the
matcher that saw the press.

Routing Linux legacy mode through the Rust FFI path instead is not a drop-in
change: the raw key handler builds its event with no unicode, so Rust's
legacy mode would fall back to US key names and lose the layout-aware
characters the Dart path sends today, and it would take modifiers from the
X11 key state instead of Flutter's.

Run these three actions when the fired key is released. The matcher that
consumed the press then also sees the repeats and the release, the remote
modifiers are still released on the press, and a session that closes drops
the action it owed. Both matchers keep the same list of actions.

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

* test(keyboard): shortcuts, pin the key-up action list on both sides

kShortcutActionsRunOnKeyUp and runs_on_release are two hand-kept lists of
the actions that run on key release. Add a shared fixture and check each
side against it, the way the key vocabulary and the default bindings are
already checked, so adding a focus-changing action on one side breaks a
test until the other side follows. The Dart test also checks that every
listed id is a configurable action.

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

* fix: prevent lost input after remote session shortcuts

Avoid synthetic Alt presses that activate the Windows system menu
and swallow the next character.

Trigger restart, switch-sides, and chat actions on key release so
focus changes cannot leave subsequent shortcut presses ignored.

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

* fix(mobile): correct Chat keyboard and input helper behavior

- Keep soft keyboard and helper hidden when Chat opens via shortcut
- Restore soft input on touch and remote focus after Chat closes
- Handle modifier releases while Chat owns focus
- Clear hidden virtual modifiers while preserving held keys and Pin behavior

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

* fix(shortcuts): prevent recording non-simultaneous key combinations

Build new captures from currently held keys instead of reusing released
letters. Preserve the last valid chord after release so it can be saved.

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

* fix(shortcuts): isolate window actions and prevent duplicate Alt presses

- Dispatch shortcut actions only to the originating session window.
- Clear local modifier state on focus loss without resending modifiers
  already released to Windows peers, preventing lost following input.
- Strengthen the regression assertion against extra Alt keydown events

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

* refact(shortcuts): empty default shortcuts for Cmd+Option+Shift+Del on macOS and iOS

Because Del may be ambiguous for new macOS users.
Cmd+Option+Shift+Backspace is "Empty Trash without confirmation" shortcut on macOS.

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

* fix: use session peer platform for Ctrl+Alt+Del events

Fix Android-to-Linux Ctrl+Alt+Del delivery by using the session's peer
platform instead of the desktop global session, which defaults to Windows

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

* fix: hide relative mouse mode shortcuts on Wayland

Separate relative mouse mode availability from screenshot support.
Filter unsupported actions and defaults while preserving saved bindings

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

* fix: align shortcut availability with platform support

- Hide unsupported mobile and web shortcut actions
- Enable mobile scaling and Android voice call shortcuts
- Use openMonitorInTheSameTab() for display switching
- Preserve cursor position when switching displays on desktop and web

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

* fix: prevent held-key shortcut recording bypass

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

* fix: preserve keyboard input after shortcut dialogs

Run native clipboard shortcuts on key release and wait for remote modifier releases before dispatching.

Release remote modifiers when mobile local UI takes focus, and document the tested iPad Bluetooth Mute shortcut limitation.

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

* fix: preserve remote key state during local shortcuts

Keep unrelated held keys pressed for session actions that retain input. Preserve key release when focus or input handling changes, and avoid synthetic Alt taps during shortcut dispatch.

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

* fix: suspend saved relative mouse shortcuts on Wayland

Filter the native active binding cache without changing stored configuration, so the binding becomes available again under X11.

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

* fix: exclude unsupported Wayland shortcuts from Flutter matching

Keep saved bindings intact while filtering the active config used by the Flutter matcher. Cover stored bindings and enable/pass-through flags in the existing shortcut tests.

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

* fix: retain forwarded key ownership across shortcut repeats

Ignore repeat presses for keys already forwarded to the peer, and release ordinary held keys before Show My Cursor enables view-only. Cover both paths with converter-level regressions.

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

* fix: release Flutter-held keys before view-only shortcuts

Track ordinary keys forwarded by the Dart matcher paths and await their releases before View Only or Show My Cursor disables input. Keep Mute key ownership and existing empty-cleanup timing unchanged.

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

* fix: filter active Flutter shortcuts by platform capabilities

Reuse the Settings action filter for saved bindings while preserving storage, default-seeding behavior and configurable Apple Ctrl+Alt+Del bindings.

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

* fix: filter native shortcut caches for mobile controllers

Suspend saved desktop-only actions on Android and iOS and hide unavailable iOS actions without changing persisted bindings. Keep native cache filtering aligned with Flutter platform capabilities.

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

* fix: share filtered shortcut bindings with the Web matcher

Pass the active platform config to JavaScript at startup and after settings changes, preserving unsupported saved bindings in local storage.

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

* fix: release Flutter-held keys before focus-changing shortcuts

Drain ordinary keys owned by the original session before run-on-key-up
actions and native clipboard callbacks. Preserve Mute holds, pending-action
cancellation and Web clipboard key-down activation.

Document the required Web matcher counterpart in the bridge:
rustdesk/rustdesk-web-js@94abe431d6

Validation: 61 native Flutter tests, 32 Chrome/HTML tests, targeted analysis
and Windows debug build.

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

* refact: remove the useless comments

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

* fix: prevent Windows menu activation from Alt-only shortcuts

Neutralize the forwarded Alt with a balanced temporary Ctrl press when a consumed local shortcut releases its only modifier in Windows Map mode. Keep physical modifier tracking and normal Alt pass-through unchanged.

Add a regression covering both Alt keys, trigger repeats and the eventual physical release. Verified with 36 native shortcut tests and real Windows menu/input checks.

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

* fix: prevent Alt menu activation in all keyboard modes

Extend Windows Alt-only shortcut neutralization to Translate and Legacy. Keep the temporary Ctrl packets in Map mode so Legacy modifier synchronization cannot release Alt before Ctrl.

Extend the existing regression across keyboard modes and decode scan, virtual and control-key events. Verify 36 native tests and 34 Windows menu replay cases.

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

* fix: initialize outgoing chat before shortcut dispatch

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

* fix: guard Windows Alt release in Flutter legacy shortcuts

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

* fix: coordinate Web shortcut dispatch and Alt modifier cleanup

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

* fix: distinguish AltGraph from ordinary Alt shortcuts

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

* fix: dispatch macOS Web shortcuts without waiting for keyup

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

* fix: support legacy peers in privacy mode shortcut

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

* fix: exclude AltGraph from Flutter shortcut matching

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

* fix: exclude GTK AltGr input from raw shortcut matching

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

* test: trim redundant keyboard shortcut coverage

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

* fix(keyboard): prevent Cmd shortcuts from opening remote Start

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

* fix(shortcuts): guard Windows menu keys after Ctrl/Cmd swapping

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

* fix(shortcuts): align recording and display routing

Reject non-Apple AltGraph captures to match runtime filtering. Honor individual-display windows for next, previous, and all-display shortcuts.

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

* fix(shortcuts): reject GTK AltGr chords in recorder

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

* fix(android): restore keyboard focus for modifier-first input

Focus the existing FlutterView when a modifier is pressed without native view focus. This restores shortcut-first input after returning to RustDesk while preserving focused inputs and normal key dispatch.

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

* fix(shortcuts): release held keys before keyboard mode changes

Drain Flutter-forwarded keys before keyboard-mode shortcut actions so releases use the original encoding. This prevents held keys from remaining down after a Web Input source 2 mode change.

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

* fix(i18n): use sentence case for shortcut labels

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

* fix(mobile): preserve touch modifiers in the input helper

Keep touch-selected modifiers visible after hiding the keyboard. Clear physical modifier releases locally in view-only mode so they do not reopen the helper.

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

* fix(web): preserve modifiers across Legacy-to-Map shortcuts

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

* fix(shortcuts): check support before registering all displays view

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

---------

Signed-off-by: fufesou <linlong1266@gmail.com>
Co-authored-by: fufesou <linlong1266@gmail.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 21:31:44 +08:00
RustDeskandClaude Opus 5.5 13e1278b4c fix: auto-login types the OS password only at the logon or lock screen (#16520)
* fix: auto-login types the OS password only at the logon or lock screen

A remote-control login on Windows and macOS now reports is_logon_screen
in platform_additions, and the client skips auto-login when the peer
reports false. Peers that don't report it (older ones, Linux) keep
today's behaviour, so this narrows the leak into the focused window
without closing it: the value is a snapshot taken at login.

Windows 7 and Server 2008 R2 report the WTS lock flag reversed, so
there only LogonUI.exe tells the lock screen apart.

Refs #16510, #15261

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

* windows: drop the LogonUI.exe check from is_logon_screen

LogonUI.exe can outlive the unlock and is matched by name only, so its
presence reported a lock screen on an unlocked desktop and let the
password through. Only the WTS lock flag decides now; on Windows 7 and
Server 2008 R2, which report it reversed, the result is inverted.

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

* windows: count only a confirmed logon or lock screen for auto-login

is_prelogin() reads a failed WTS user-name query as no user signed in,
and on Windows 7 the inverted is_locked() read a failed lock-flag query
as locked, so either failure let the password through. is_logon_screen
now uses its own queries that keep a failed read apart, and reads LOCK
and UNLOCK the other way round on Windows 7 and Server 2008 R2. The
existing functions stay as they are for their callers.

If the check task itself fails, the server reports false instead of
leaving the key out, which old clients' peers would mean.

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

* auto-login: ask the peer with a protobuf field instead of a JSON key

The client sets the new LoginRequest.auto_login only when Auto Login
would type the OS password, and the server runs the logon-screen check
only then, so nothing new runs for any other login. The answer is the
new PeerInfo.skip_auto_login: its default, false, is what an old or
Linux server means, so those peers keep typing as before, and neither
field is encoded unless set. The is_logon_screen key in
platform_additions is gone.

Windows is_locked() now reads the lock flag through
is_session_locked_flag(), which handles the reversed LOCK/UNLOCK of
Windows 7 and Server 2008 R2. Its only caller is the
allow-logon-screen-password check, which on those systems accepted the
permanent password on an unlocked desktop. Windows 8 and later read the
same as before. The C is_session_locked() is removed and its
WTS_CURRENT_SESSION guard moves into get_session_flags().

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

* auto-login: let the peer type the password, after checking its screen

The login-time check left the whole time until the password arrived
open: the screen could be unlocked during the click, the 1.2 s wait and
two network trips, a second client's password landed on the desktop the
first one had just unlocked, and turning Auto Login on mid-login skipped
the check.

Now the client still clicks and waits, then sends the password in a new
Message.os_login (reusing OSLogin) to a Windows or macOS peer from 1.5.1.
The peer checks for its logon or lock screen right then and types the
password and Return only if it finds one; otherwise it drops them. Other
peers get the keys as before, and the OS Password menu item is
unchanged. The password goes out only after login, never in the login
request. LoginRequest.auto_login and PeerInfo.skip_auto_login are
removed, so nothing new runs unless os_login arrives.

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

* server: name os_login in scope-violation logs

A rejected os_login was logged as message.other.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 12:06:15 +08:00
rustdesk 0b5a3d74de 1.5.1 2026-10-12 17:08:40 +08:00
Mariano Abad 109c39bccb fix(drm): drop a frame equal to the previous one, as the other capturers do (#16450)
* fix(drm): drop a frame equal to the previous one, as the other capturers do

The producer grabs on a timer, so a still screen reached the encoder as the
same frame every tick and the client decoded about 30 frames per second of
nothing new (rustdesk#16449). The x11, pipewire and quartz capturers drop a
repeat with would_block_if_equal; the drm capturer now does the same.

A regression test checks that a repeat is not encoded again and that the next
new frame is. The frame helper of the tests now differs per call, and the 180
test forgets the frame its last case repeats on purpose.

* fix(drm): a frame whose encode failed is not dropped as a repeat

The capturer marked a frame as seen when it returned it, so when its encode
failed and the screen then stayed still, every later grab compared equal to
it and it was never sent: the client kept the previous image, and a hardware
encoder never reached its failure count to switch away.

handle_one_frame now also says whether the frame was encoded, and when it was
not the loop calls TraitCapturer::forget_last_frame(), a new method whose
default does nothing. The DRM capturer then returns the next repeat instead of
dropping it.

The DRM capturer also stops keeping a copy of the last frame: it compares the
new buffer with the one it returned last before replacing it, and a turned
frame is turned into a spare buffer first.

* fix(linux): x11 and pipewire do not drop a failed frame as a repeat either

Both capturers drop a frame equal to the one they returned last, so they had
the same hole as the drm one: a frame whose encode failed was not sent again
while the screen stayed still. They now forget it when the loop says so.

* fix(linux): every video run starts by forgetting the last frame

A pipewire recorder outlives a restarted run while another display keeps the
session open, and so did the frame it returned last. A run restarted by an
encoder switch or a new subscriber then dropped the first repeat and sent
nothing until the screen changed. The capturers of the other paths are built
fresh for each run, so for them the call does nothing.

* fix(drm): keep the repeat drop in the drm capturer, with one repeat a second

The shared part of the three commits before is reverted: TraitCapturer,
the video_service loop, x11 and pipewire are as on master again. So is the
restructure of frame() from the second commit: the drop is again the one
of the first commit, would_block_if_equal on the frame returned last, as
the other capturers do.

A repeat is dropped until a second has passed since frame() last returned
a frame, so a frame whose encode failed reaches the encoder again a second
later even if the screen stays still. The tests check the drop, the repeat
a second later, and that the second starts over after it.

* fix(drm): a frame is a repeat only when its format matches too

The same bytes as BGRA and as RGBA are two pictures when red and blue
differ, and the convert path can return either, so a change of format
clears the saved frame and the new one goes out. The 180 test no longer
checks a turned repeat: nothing reported asked for it.

* fix(drm): compare a frame with cur before replacing it, without a copy

saved_raw_data copied every changed frame (8 MB at 1080p). The previous
frame is still in cur when a new one arrives, so the bytes and the
format are compared with it before the swap; a rotated output turns the
frame into a spare buffer first. The 180 test checks the turned repeat
again, since that path compares on its own now.
2026-10-12 11:29:57 +08:00
Henrik Fransson ccfa714d2e Fix Swedish translation typo (#16529)
Signed-off-by: Henrik Fransson <hmf.hmf.hmf@gmail.com>
2026-10-12 10:57:11 +08:00
fufesou 0921a7432f feat(update): verify signed update metadata (#15914)
* feat(update): verify signed update metadata

* fix(update): harden metadata publishing and app names

- share strict app-name validation across Windows and macOS
- preserve published sidecars until replacements are ready
- select macOS test features by target architecture
- update the signing dependency and URL validation coverage

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

* fix(update): prevent replacing published release assets

- block reruns after signed update metadata is published
- clarify the security rationale for app-name validation

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

* fix(update): cache TLS responses and avoid double translations

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

* refact: reduce the diffs

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

* refact(update): remove obsolete update paths

- remove unused FFI update branches
- delete legacy Windows and macOS update helpers
- simplify macOS daemon updates and redundant gating

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

* feat(update): secure same-identity macOS offline updates

- verify DMGs using signed metadata, size, and SHA-256
- enforce package and bundle identity plus macOS signature checks
- support custom release policies and propagate manual update failures

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

* fix(update): verify Windows installers with Authenticode

Reject unsigned or untrusted EXE/MSI updates
before elevation, clean up failed verified copies,
and fix the macOS manual updater logging import.

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

* fix(update): clear stale URL on response body errors

Keep body-read failures in the common cleanup path and document the
cache-only Authenticode verification policy.

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

* refactor(update): remove OS signature sanity checks

Remove Windows Authenticode and macOS codesign/Gatekeeper verification.
Keep metadata, artifact integrity, bundle identity, and transaction checks.

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

* refact(update): move update scripts into res/update

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

* fix(update): secure Windows MSI handoff against junction races

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

* fix(update): secure Windows EXE handoff against junction races

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

* fix(update): preserve legacy custom client app names

- allow names starting with digits or underscores
- preserve leading hyphens on Windows for compatibility
- reject leading hyphens on macOS to avoid pgrep option parsing

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

* refact(update): remove some simple wrappers

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

* refact(update): simple refactor

* refact(update): comments on update.scpt

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

* refact(update): comments

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

* fix(update): create download destinations exclusively

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

* fix(macos): roll back updates when final readiness checks fail

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

* fix(msi): propagate MSI installation failures

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

* chore

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

* fix(macos): reject stale IPC sockets during updates

Require open IPC sockets in addition to launchd running state before committing the privileged update transaction. Inspect sockets with lsof to avoid triggering IPC authentication.

Add native socket regression coverage to macOS CI. Remove the unused Windows helper, combine offline metadata exports, and restore unrelated formatting changed by the PR.

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

* fix(macos): allow offline updates without an installed bundle

Validate app-only updates against the running client's bundle identifier and check the destination identity when it exists. Replace source-text assertions with behavioral identity tests and run the macOS update tests in CI.

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

* ci, gate test with PUBLISH_UPDATE_METADATA == 'true'

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

---------

Signed-off-by: fufesou <linlong1266@gmail.com>
2026-10-12 10:56:50 +08:00
fufesou c8532719c0 Fix/macos mouse release (#16516)
* fix(macos): preserve mouse-up through cursor protection

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

* fix(macos): clear tracked presses released in relative mode

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

* fix(input): preserve desktop mouse releases through cursor protection

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

* fix(input): preserve button state when mouse-up is rejected

Clear tracked buttons only after coordinate validation succeeds.

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

---------

Signed-off-by: fufesou <linlong1266@gmail.com>
2026-10-10 19:05:45 +08:00
RustDeskandClaude Opus 5.5 4411d10f45 fix(linux): report the process user as the active user under Flatpak (#16519)
File transfer to a Flatpak peer always failed with "No active console
user logged on", because PeerInfo.username came from loginctl, which the
sandbox cannot reach: Flathub builds lack the org.freedesktop.Flatpak
talk-name, so `flatpak-spawn --host` fails. A Flatpak instance only runs
inside the logged-in user's own session, so that user is the active one.

Fixes #16506


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

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 16:44:10 +08:00
67090d3aa1 fix: a refused privacy-mode request no longer turns off another connection's (#16507)
* fix: a refused privacy-mode request no longer turns off another connection's

`Connection::turn_on_privacy`'s error arm tore down whatever privacy mode was
active, whoever owned it. With connection A in privacy mode, connection B's
request is correctly refused with OCCUPIED, and the error arm then called
`turn_off_privacy_to_msg(INVALID_PRIVACY_MODE_CONN_ID, ..)`. That id bypasses
the ownership check in `check_off_conn_id`, so A's privacy mode went away: the
screen was un-blanked and local input un-hooked. The call passes `state: None`,
so no `set_privacy_mode_state` goes out either and A was never told, leaving its
client showing privacy mode as on. `check_privacy_mode_changed` doesn't cover
it, as it only sends PrvOnByOther while a privacy mode is still active.

Pass `self.inner.id`, as the sibling error path above already does.
`check_off_conn_id` then cleans up after this connection when it owns privacy
mode, and refuses when another connection does.

The bypass itself stays: `ipc::Data::Close`, `reset_all` and `TurnOnGuard` need
an unconditional teardown. Its contract is now noted on `check_off_conn_id`,
since that is what the buggy call site got wrong.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Signed-off-by: Steven Storie <sstangle73@gmail.com>

* fix: disconnect other remote sessions when privacy mode starts

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

* fix: exclude privacy disconnect hook from iOS builds

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

* fix: validate privacy mode before disconnecting other sessions

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

* chore

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

---------

Signed-off-by: Steven Storie <sstangle73@gmail.com>
Signed-off-by: fufesou <linlong1266@gmail.com>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
Co-authored-by: fufesou <linlong1266@gmail.com>
2026-10-10 16:02:29 +08:00
fufesou 001b0e9617 Fix/preserve deleted printer (#16500)
* fix(windows): preserve manually deleted printers

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

* fix(windows): distinguish printer detection failures

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

* fix(windows): skip printer detection when disabled

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

* fix(flutter): load printer status asynchronously

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

* refactor(flutter): remove printer status mounted checks

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

* fix(msi): preserve deleted printers in direct upgrades

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

* fix(windows): preserve deleted printers in silent EXE installs

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

* fix(windows): skip printer installation when detection fails

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

* fix(installer): default printer off when detection fails

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

* fix(printer): limit checked enumeration to presence queries

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

* fix(installer): allow cancellation during printer detection

Inline MSI update command construction without changing its arguments.

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

* fix(flutter): time out installer printer detection

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

* chore

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

* test(windows): cover multilingual install app names

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

---------

Signed-off-by: fufesou <linlong1266@gmail.com>
2026-10-10 00:21:17 +08:00
Hintay 0bc2473ffe fix(drm): size a plane-rotated scanout as the mode transposed (#16444) 2026-10-09 14:11:42 +08:00
fufesou 3f4bfe535e Fix/wayland input keyboard layout (#16462)
* fix(linux): respect Wayland keyboard layouts for uinput

Resolve printable keys from GNOME input sources or the Wayland keymap and KDE active layout group. Refresh layout metadata on input at most once per second, and preserve the keycode and owned modifiers until release.

Preserve the original Legacy character on client key release and handle Caps Lock shortcuts without introducing an unwanted Shift modifier.

Validated with GNOME/KDE full-service input and disconnect checks, plus Windows/Linux native keyboard capture and release checks.

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

* fix(linux): harden Wayland keyboard layout detection

Keep the last usable map on transient discovery failures and preserve the
legacy character path when no map is available, with explicit warnings.
Retain each injected key representation through release and handle IBus
default layout and variant metadata without compiling a layout named default.

Use native GNOME and Plasma sources, including KWin sessions without the
optional layout service. Read the Xwayland keymap and effective group from
the same keyboard on other desktops. Load XCB/XKB libraries dynamically and
accept the unix/:N local display spelling.

Validation: 24/24 temporary Linux production-module and IPC checks passed,
including an actual read-only Xwayland query. The two latest routing/display
regressions failed before their fixes. Rustfmt and git diff --check passed.
No Cargo/Flutter commands or full remote application tests were rerun.

Xwayland state freshness and synchronous desktop I/O remain known limits.

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

* fix(linux): bound input waits for layout refresh

Run throttled Wayland layout discovery in a single background worker and give the triggering input a 25 ms wait budget. Later input uses the existing map without waiting or queuing more queries. Preserve source error handling and skip known Legacy clipboard-only text.

Document Xwayland freshness and per-character modifier ownership limits. Desktop calls remain uncancelled; the budget bounds input waiting, subject to OS scheduling.

Validation: Linux module compilation with cached dependencies, 23 existing temporary module/IPC checks, and stalled-XCB timing probes passed. Rechecked cache/error/release cases after the final lock-scope change. No permanent regression tests or Cargo/Flutter commands.
Signed-off-by: fufesou <linlong1266@gmail.com>

* docs(linux): record layout query latency measurements

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

* fix(linux): reply to failed uinput key state queries

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

* fix(linux): prefer non-keypad character mappings

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

* fix(linux): preserve text after unmappable uinput characters

Continue processing a text sequence when one character cannot be resolved
in the host layout. Return the first mapping error after the supported
characters are injected, so the existing throttled log still reports failure.

Keep modifier-query, injection and release errors fail-fast. This fixes
German a^bc losing bc without adding clipboard or fixed-US fallback.
The unsupported caret remains an explicit mapping error.

Validation: three temporary Linux checks (nine inputs) passed using the
production resolver and sequence methods, real framed IPC and native XKB
decoding. The suffix check failed before the fix. Formatting and diff checks
passed; no permanent tests, Cargo/Flutter commands or full app build added.

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

* fix(linux): preserve Latin shortcuts on non-Latin layouts

Detect Ctrl/Alt/Meta independently of CapsLock. If the active XKB map lacks
an ASCII shortcut letter, reuse the existing physical letter mapping while
preserving explicit Shift and the press-time key for release. Existing
layout mappings and unsupported ordinary text retain their behavior.

Honor disable-uinput-layout-fallback and log this compatibility path with
the existing throttle.

Validation: 12 temporary Linux production-module/IPC checks passed,
including 43 non-Latin shortcut/layout/lock/Shift cases. The new checks
failed before the fix. Formatting and git diff --check passed. No real
mobile/compositor session or Cargo/Flutter build was run.

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

* fix(linux): preserve missing punctuation shortcuts

Allow missing ASCII graphic shortcuts to reuse the existing physical key
table when Ctrl, Alt or Meta is active. This restores Ctrl+[ and Ctrl+]
with a valid Russian layout instead of discarding their character events.

Retain the table's Shift requirement for punctuation and use existing
modifier ownership and press-time release tracking. Uppercase letters do
not synthesize Shift. Active-layout mappings, ordinary text errors and
disable-uinput-layout-fallback retain their behavior.

Validation: 14 temporary Linux production-module/IPC checks passed after
recompiling the final source with rustc and cached dependencies. Includes
19 punctuation/lock/Shift combinations and 43 existing Latin-shortcut
cases. The two new checks failed before the fix. Formatting and
git diff --check passed. No Cargo/Flutter build or real mobile/native
Wayland session was run.

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

* fix(linux): respect held Shift when resolving shortcuts

Derive Shift-held candidates from the same XKB keymap and query the
caller's Shift state for character shortcuts. On US layouts, Ctrl+Shift+<
now uses the comma key instead of the extra ISO key that produces >.

Keep caller-held Shift out of synthesized modifier ownership. Preserve
ordinary input and letter-shortcut identity, and do not replace an
ordinary shortcut with a keypad alias to satisfy the held-Shift lookup.

Validation: 16 temporary Linux production-module/IPC checks passed with
native XKB event replay and cached dependencies via rustc. Includes
30 US text/shortcut cases and 40 UK/DE/FR character/lock cases. The new
Ctrl+Shift+< check failed before the fix. Changed sections pass formatting
and git diff --check. No Cargo/Flutter build or real mobile/native Wayland
session was run; device-state and packet-modifier handling use fixtures.

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

* docs(android): document paired-punctuation input limitation

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

* docs(linux): explain Xwayland layout synchronization limits

Document the focus-scoped modifier updates observed on GNOME and KWin. Core and physical X11 keyboards can retain an old layout group while native Wayland windows have focus; reconnecting or waiting cannot request the missing update.

Validation: 16 existing module/IPC probes and the live GNOME mapping probe passed. Live KDE queries reproduced native French versus stale Xwayland US. Formatting and diff checks passed. This is a comment-only change; strict Xwayland-only behavior is preserved.
Signed-off-by: fufesou <linlong1266@gmail.com>

* fix(linux): query native Sway and Hyprland keyboard layouts

Read the uinput keyboard's active layout through compositor IPC and
validate its group against the native Wayland keymap. Match the IPC
server to the Wayland session, and accept numbered Hyprland device
names while rejecting ambiguous keyboard selections.

Validation: 21 temporary production-module and framed-IPC checks passed.
Live Sway US/FR group and a/q mapping checks passed with Xwayland disabled;
the GNOME French layout probe also passed. Formatting checks passed.
A live Hyprland session and a full application build were not tested.

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

* fix(linux): defer unverified native compositor layout queries

Remove the Sway/Hyprland adapter that paired a uinput device's layout
group with a seat keymap based only on matching layout names. Different
device options can make a synthesized AltGr key toggle CapsLock instead.

Restore the existing best-effort Xwayland source for other desktops and
document the device-keymap information missing from the examined native
queries. GNOME/KDE discovery and injection/cache behavior are unchanged.

Validation: 16 temporary production-module/IPC checks passed after the
removal, plus read-only GNOME French and Xwayland mapping checks. Rust
formatting and diff checks passed. No full application build or mobile
end-to-end test was run for this follow-up.

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

* fix(linux): reject unreliable GNOME per-window layout sources

GNOME restores per-window layouts without persisting MRU. Reject MRU
selection when per-window input sources are enabled with multiple sources,
and invalidate the cached map and source identity for this typed error.
Transient discovery failures still retain the last valid mapping.

Reuse the existing logged/disableable compatibility policy. This contains
stale-map acceptance; it does not add effective per-window layout discovery.
Single-source and global-source GNOME configurations retain their path.

Validation: the old code failed the temporary stale-cache regression.
All 3 focused production-module checks pass after the fix, covering cache
invalidation/recovery, compatibility modes, single/default source mapping,
UK punctuation, and last-good retention after an IBus connection failure.
Compiled with rustc and cached Linux dependencies; formatting/diff checks
passed. No permanent tests, Cargo/Flutter build or mobile session added.

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

* fix(linux): reject inactive IBus layout sources

Read the current GlobalEngine description instead of looking up the
persisted MRU engine by name. GNOME can suppress IBus for password entry
without updating MRU, leaving the old engine's layout valid but inactive.

Report an engine-ID mismatch as UnreliableSource so the existing cache
invalidation path drops that mapping. Keep transient query-error handling
and layout/variant normalization. Do not infer a US compositor layout from
GNOME's xkb:us::eng echo engine.

Validation: the old code failed the inactive-engine cache and default-layout
checks. All 3 temporary production-module/D-Bus checks pass with this fix,
covering invalidation/recovery, compatibility policies, metadata sentinels,
query failures and ordinary French XKB selection. Compiled with rustc and
cached Linux dependencies; formatting/diff checks pass. No permanent tests,
Cargo/Flutter build or live password/mobile session added.

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

* fix(linux): prewarm uinput layout discovery at startup

Start the existing layout worker when the uinput keyboard client connects,
before the server accepts remote input. Reuse its throttle and single-worker
logic; keep the existing 25 ms input wait and background completion policy.
Prewarming reduces cold-start fallback without introducing input queues or
promising readiness while a desktop query remains outstanding.

Verified with three temporary Linux production-module checks using cached
dependencies: a 125 ms query resolves UK @ before first input, a 200 ms
outstanding query stays nonblocking and publishes its map, and a failed
startup query retries successfully. All three fail their startup assertions
before the change. No permanent tests or Cargo/Flutter builds were added.

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

* fix(linux): preserve first input wait during layout prewarming

Keep the startup query's completion receiver until the first relevant input
takes it. That input can wait for the already-running query within the
existing 25 ms deadline, without holding the receiver handoff lock. Later
input remains nonblocking and the existing single-worker guard is unchanged.
Prefer a due refresh to an old completed startup notification.

Verified with four temporary Linux production-module checks compiled with
rustc -C opt-level=3 and cached dependencies: joining a pending UK query,
one bounded wait followed by nonblocking input, due refresh after prewarm,
and recovery after query failure. Both lost-wait checks fail before the fix.
Formatting and git diff --check pass. No permanent tests or full build added.

An unoptimized delayed-query probe still exceeded 25 ms and used fallback;
this restores the wait opportunity, not an initial-readiness guarantee.

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

* fix(uinput): remove unnecessary change

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

* refactor(linux): simplify uinput character releases

Release the mapping stored for the same character. Linux character input already pairs down/up events, so opposite-case matching is unnecessary.

Validation: git diff --check passed. Static comparisons confirmed that Map-mode dispatch, raw-key injection and keycode offsets match the PR base. No Cargo/Flutter commands or live-session tests were run.
Signed-off-by: fufesou <linlong1266@gmail.com>

* fix(linux): normalize Unicode CapsLock shortcuts

Normalize single-scalar Unicode lowercase for CapsLock shortcuts without adding Shift. For lowercase expansions, resolve the original symbol with the actual CapsLock state instead of truncating it. Document the existing first-seat discovery limitation.

Validation: two temporary Rust context checks against lookup fixtures failed before the fix and passed afterward. No Cargo/Flutter build or end-to-end input test was run.
Signed-off-by: fufesou <linlong1266@gmail.com>

* fix(linux): derive CapsLock shortcut keys from XKB

Keep the actual CapsLock state when resolving shortcut characters. Use the existing Caps-off and Caps+Shift mappings to omit generated Shift only when XKB confirms the same physical key and remaining modifiers, preserving the Turkish I/ı and İ/i key identities.

Validation: three temporary production-module checks passed on 192.168.5.32 with native libxkbcommon; two failed before this fix. Covered Turkish, German, Cyrillic and ASCII shortcuts, explicit Shift, ordinary text and UK punctuation. No full application build, IPC or end-to-end input test was run.
Signed-off-by: fufesou <linlong1266@gmail.com>

* refactor(linux): remove CapsLock shortcut special cases

Use the existing lock-state synchronization and ordinary XKB mappings for mobile soft-keyboard input. Remove CapsLock-specific shortcut remapping and compatibility-path lowercasing while retaining held-Shift punctuation handling.

Validation: rebuilt the Linux Rust library and reused the unchanged Flutter UI. Actual Android Gboard input matched UK punctuation on GNOME and KDE; French/German switching on KDE passed after the refresh interval. The user confirmed real iPad input on both hosts, including smart quotes. Formatting and whitespace checks passed. The optional Ctrl/Shift toolbar automation was inconclusive and is not counted as passing coverage.
Signed-off-by: fufesou <linlong1266@gmail.com>

* fix(linux): press Level3 before Shift for uinput characters

Preserve mapping candidate preference while storing generated modifiers in Level3-before-Shift order. This avoids activating Compose with lv3:ralt_switch_multikey; releases retain their existing reverse order.

Verified on Linux with temporary production-mapper/libxkbcommon tests: Lithuanian ! fails before this change and passes afterward; all 24 UK punctuation/lock-state cases pass with released modifiers and unchanged lock state. Formatting and diff checks pass. No full application build or mobile end-to-end test was run for this change.

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

* fix(linux): preserve legacy uinput IPC without a keymap

Send sequences and character clicks through their original IPC messages when the layout cache is unavailable, avoiding unnecessary synchronous key-state queries. Keep throttled fallback warnings and leave layout discovery, retry policy, and key-down/up pairing unchanged.

Verified with three temporary production-method checks on Linux using a recording transport and injected query errors. The unavailable-map routing check fails before the fix and passes afterward; raw-click routing and available-map query-error handling remain unchanged. Changed-code formatting and diff checks pass. No full application build or end-to-end input test was run.

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

* fix(linux): skip layout queries for legacy uinput fallback

When no keymap is available, single-character input must use the legacy
KeyDown/KeyUp path without querying lock or modifier state first. Retain
the legacy key in the existing press record so discovery completing
before a repeat or release cannot change the selected representation.

Validated with four temporary production-method checks on Linux using a
controlled cache/resolver and recording transport: missing-map fallback
with query failures, press/release across cache transitions, unchanged
raw-key dispatch, and Ctrl+C without extra Shift or queries. The initial
fallback check failed before this change. Valid-map errors still surface.

Changed-code formatting and git diff --check pass. No full Cargo/Flutter
build or live service/mobile test was run for this change.

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

---------

Signed-off-by: fufesou <linlong1266@gmail.com>
2026-10-09 11:17:04 +08:00
Mariano Abad 9b9e5f113a fix(wayland): place a portal stream at the only output of its size (#16451)
* fix(wayland): place a portal stream at the only output of its size

xdg-desktop-portal-hyprland reports every stream at (0, 0). With no output at
the origin, sort_streams dropped the stream; with an output of another size
there, the stream took its origin and skipped try_fix_logical_size, so the
client sent physical pixels from the wrong origin and the pointer landed on
another output.

With more than one output, a stream whose position is not the origin of an
output of its size (a rotated output counts in either orientation) now takes
the origin of the only output of that size; with several outputs of that size,
or none, the position is kept. A position found by try_fill_positions names an
output of its size, or no output has its size, so later calls keep it while the
outputs and the measured size do not change.

Refs #15731

* fix(wayland): reconcile portal positions with measured sizes only

The first commit corrected any position that named no output of the stream
size, trusting the size. That size is the portal size when get_res() fails,
and it can be the mode of another output, so a correct portal position could
move onto the wrong output. A stream now records whether its position came from
the portal and whether its resolution was measured, and a portal position is
overridden only by a measured size.

Streams without a portal position go through try_fill_positions as before; one
it leaves unresolved, such as a rotated output whose transposed size no mode
matches, now takes the origin of the only output of its size.

Refs #15731

* fix(wayland): only a measured size moves a stream position

The reconciliation after try_fill_positions let a position through to
corrected_origin unless the portal had sent it. A position that
try_fill_positions restored from its cache is not from the portal, so when
get_res() failed and the size was the portal size, a cached (1920, 0) with a
1440x900 portal size moved to the 1440x900 output at (0, 0), and with both
outputs shared sort_streams dropped one of the streams. Only a measured size
moves a position now, whatever its source, so position_from_portal goes away.
2026-10-09 11:15:16 +08:00
21pages 1d4abd0258 fix: resolve HTTP API 407 errors through HTTPS proxies (#16496)
Upgrade reqwest to 0.12.28 to include the fix for missing
Proxy-Authorization headers when forwarding HTTP requests
through HTTPS proxies.

Signed-off-by: 21pages <sunboeasy@gmail.com>
2026-10-08 17:55:59 +08:00
NetViperandRustDesk 6da7977a94 fix(video): defer refresh teardown until hw encoder warms up (#16459)
* fix(video): defer refresh teardown until hw encoder warms up

On macOS, hevc_videotoolbox (the only encoder there reporting
!latency_free()) can return no packet for its first encode call. The
OPTION_REFRESH check in run() tore the encoder down with
bail!("SWITCH") inside that window, so each new encoder was destroyed
before producing a frame and rebuilt about once a second. With H265
selected on macOS 27 / Apple silicon, the picture froze or the session
dropped every 1-3 minutes.

On macOS, once the encoder has been fed a frame, defer the refresh
until it emits its first packet. Before that there is no warm-up to
lose, so a refresh can still restart a stalled capturer. Other
platforms and every latency-free encoder behave as before. An encoder
that never emits is still switched away from by the unchanged
max_fail_times path. The only new state is one flag.

Verified on macOS 27.0 / 27.0.1, M5 Pro, 2560x1440 H265. Soaked for two
weeks on a 1.4.9-based build carrying this deferral:
- before: ~40 "no valid frame" and ~27 refresh teardowns per 60s
- after:  37 sessions, every "no valid frame" at times:1, so
          max_fail_times was never approached; H265 never lost

Fixes #16457

Signed-off-by: David Riding <48262524+dmriding@users.noreply.github.com>

* Update video_service.rs

---------

Signed-off-by: David Riding <48262524+dmriding@users.noreply.github.com>
Co-authored-by: RustDesk <71636191+rustdesk@users.noreply.github.com>
2026-10-08 11:14:56 +08:00
fufesou 25d2c6db55 log key-up and text injection failures (#16455)
* fix(macos): log key-up and text injection failures

Report failed key releases through the rdev input path and
missing sources, mappings, or events in the Enigo keyboard path.
Throttle repeated failures without logging text contents or changing input behavior.

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

* fix(macos): refine keyboard failure diagnostics

Remove key identities from virtual-input and Enigo failure logs while preserving operation and failure details. Also report key-down event creation failures in key_click with the existing throttle, without changing event posting or error propagation.

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

* refact(logs): update rdev, add diagnostic logs

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

---------

Signed-off-by: fufesou <linlong1266@gmail.com>
2026-10-08 00:23:14 +08:00
Stephan Paternotte f0bd880fe7 Update nl.rs (#16485)
lang: Dutch language file updated
- various consistency fixes
- ... -> …
- empty values translated
2026-10-07 21:33:18 +08:00
164 changed files with 8274 additions and 10309 deletions
+1 -1
View File
@@ -234,7 +234,7 @@ jobs:
CARGO_TEST_OPTIONS="--lib --bin ${PROJECT_NAME}"
;;
*)
CARGO_TEST_OPTIONS="--workspace --no-fail-fast -- --skip test_get_cursor_pos --skip test_get_key_state"
CARGO_TEST_OPTIONS="--workspace --no-fail-fast"
;;
esac;
+299 -9
View File
@@ -9,6 +9,9 @@ on:
upload-tag:
type: string
default: "nightly"
publish-update-metadata:
type: boolean
default: false
# NOTE: F-Droid builder script 'flutter/build_fdroid.sh' reads environment
# variables from this workflow!
@@ -45,16 +48,54 @@ env:
VCPKG_COMMIT_ID: "9e593bb18ea69cc5095e012465dcd675a822ed0d"
VCPKG_CMAKE_VERSION: "4.3.0"
ARMV7_VCPKG_COMMIT_ID: "6f29f12e82a8293156836ad81cc9bf5af41fe836" # 2025.01.13, got "/opt/artifacts/vcpkg/vcpkg: No such file or directory" with latest version
VERSION: "1.5.0"
VERSION: "1.5.1"
NDK_VERSION: "r28c"
#signing keys env variable checks
ANDROID_SIGNING_KEY: "${{ secrets.ANDROID_SIGNING_KEY }}"
MACOS_P12_BASE64: "${{ secrets.MACOS_P12_BASE64 }}"
UPLOAD_ARTIFACT: "${{ inputs.upload-artifact }}"
PUBLISH_UPDATE_METADATA: "${{ inputs.publish-update-metadata }}"
SIGN_BASE_URL: "${{ secrets.SIGN_BASE_URL }}-2"
jobs:
validate-update-metadata-keys:
runs-on: ubuntu-22.04
permissions:
contents: read
steps:
- name: Checkout source code
if: ${{ inputs.publish-update-metadata }}
uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
with:
persist-credentials: false
- name: Install Python
if: ${{ inputs.publish-update-metadata }}
uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5
with:
python-version: "3.12"
- name: Install Python dependencies
if: ${{ inputs.publish-update-metadata }}
run: 'python -m pip install --only-binary=:all: --require-hashes -r res/update/update_metadata_requirements.txt'
- name: Test update metadata signer
if: ${{ inputs.publish-update-metadata }}
run: |
python -m unittest \
res/update/test_generate_update_metadata.py \
res/update/test_update_metadata_cli.py \
res/update/test_macos_update_scripts.py
- name: Validate update metadata keys
if: ${{ inputs.publish-update-metadata }}
env:
RUSTDESK_UPDATE_ED25519_SEED: ${{ secrets.RUSTDESK_UPDATE_ED25519_SEED }}
RUSTDESK_UPDATE_ED25519_PUBLIC_KEY: ${{ vars.RUSTDESK_UPDATE_ED25519_PUBLIC_KEY }}
run: python res/update/generate_update_metadata.py check-key
generate-sbom:
needs: [validate-update-metadata-keys]
runs-on: ubuntu-latest
permissions:
@@ -83,9 +124,11 @@ jobs:
rustdesk.sbom.json
generate-bridge:
needs: [validate-update-metadata-keys]
uses: ./.github/workflows/bridge.yml
build-RustDeskTempTopMostWindow:
needs: [validate-update-metadata-keys]
uses: ./.github/workflows/third-party-RustDeskTempTopMostWindow.yml
strategy:
fail-fast: false
@@ -323,6 +366,17 @@ jobs:
Write-Host "Ingore the printer driver error."
}
- name: Run the Rust tests
# x86_64 only: the tests are the same code on arm64, and that runner is the slow one.
if: ${{ !inputs.upload-artifact && matrix.job.arch == 'x86_64' }}
shell: bash
run: |
# The build's own features, so the tests see the code that ships.
FEATURES=$(python3 ./build.py --portable --flutter --skip-portable-pack --hwcodec ${{ matrix.job.build-args }} --print-features)
cargo test --locked --release --lib --features "$FEATURES"
# Its Windows tests run nowhere else.
cargo test --locked --release -p clipboard
- name: find Runner.res
# Windows: find Runner.res (compiled from ./flutter/windows/runner/Runner.rc), copy to ./Runner.res
# Runner.rc does not contain actual version, but Runner.res does
@@ -360,6 +414,18 @@ jobs:
pip3 install requests argparse
BASE_URL=${{ env.SIGN_BASE_URL }} SECRET_KEY=${{ secrets.SIGN_SECRET_KEY }} python3 res/job.py sign_files ./rustdesk/
- name: Verify Windows Flutter version
if: env.UPLOAD_ARTIFACT == 'true' && env.PUBLISH_UPDATE_METADATA == 'true'
shell: powershell
run: |
$reportedVersion = (& ".\rustdesk\rustdesk.exe" --version | Out-String).Trim()
if ($LASTEXITCODE -ne 0) {
throw "rustdesk --version exited with $LASTEXITCODE"
}
if ($reportedVersion -cne $env:VERSION) {
throw "RustDesk reports version '$reportedVersion', expected '$env:VERSION'"
}
- name: Build self-extracted executable
shell: bash
if: env.UPLOAD_ARTIFACT == 'true'
@@ -450,9 +516,25 @@ jobs:
run: |
BASE_URL=${{ env.SIGN_BASE_URL }} SECRET_KEY=${{ secrets.SIGN_SECRET_KEY }} python3 res/job.py sign_files ./SignOutput
- name: Upload signed Windows Flutter EXE
if: env.UPLOAD_ARTIFACT == 'true' && env.PUBLISH_UPDATE_METADATA == 'true' && env.SIGN_BASE_URL != '-2'
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
with:
name: windows-flutter-${{ matrix.job.arch }}-exe
path: ./SignOutput/rustdesk-${{ env.VERSION }}-${{ matrix.job.arch }}.exe
if-no-files-found: error
- name: Upload signed Windows Flutter MSI
if: env.UPLOAD_ARTIFACT == 'true' && env.PUBLISH_UPDATE_METADATA == 'true' && env.SIGN_BASE_URL != '-2'
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
with:
name: windows-flutter-${{ matrix.job.arch }}-msi
path: ./SignOutput/rustdesk-${{ env.VERSION }}-${{ matrix.job.arch }}.msi
if-no-files-found: error
- name: Publish Release
uses: softprops/action-gh-release@de2c0eb89ae2a093876385947365aca7b0e5f844 # v1
if: env.UPLOAD_ARTIFACT == 'true'
if: env.UPLOAD_ARTIFACT == 'true' && env.PUBLISH_UPDATE_METADATA != 'true'
with:
prerelease: true
tag_name: ${{ env.TAG_NAME }}
@@ -463,6 +545,7 @@ jobs:
# The fallback for the flutter version, we use Sciter for 32bit Windows.
build-for-windows-sciter:
name: ${{ matrix.job.target }} (${{ matrix.job.os }})
needs: [validate-update-metadata-keys]
runs-on: ${{ matrix.job.os }}
# Temporarily disable this action due to additional test is needed.
# if: false
@@ -595,6 +678,18 @@ jobs:
pip3 install requests argparse
BASE_URL=${{ env.SIGN_BASE_URL }} SECRET_KEY=${{ secrets.SIGN_SECRET_KEY }} python3 res/job.py sign_files ./Release/
- name: Verify Windows Sciter version
if: env.UPLOAD_ARTIFACT == 'true' && env.PUBLISH_UPDATE_METADATA == 'true'
shell: powershell
run: |
$reportedVersion = (& ".\Release\rustdesk.exe" --version | Out-String).Trim()
if ($LASTEXITCODE -ne 0) {
throw "rustdesk --version exited with $LASTEXITCODE"
}
if ($reportedVersion -cne $env:VERSION) {
throw "RustDesk reports version '$reportedVersion', expected '$env:VERSION'"
}
- name: Build self-extracted executable
shell: bash
run: |
@@ -612,9 +707,17 @@ jobs:
run: |
BASE_URL=${{ env.SIGN_BASE_URL }} SECRET_KEY=${{ secrets.SIGN_SECRET_KEY }} python3 res/job.py sign_files ./SignOutput/
- name: Upload signed Windows Sciter EXE
if: env.UPLOAD_ARTIFACT == 'true' && env.PUBLISH_UPDATE_METADATA == 'true' && env.SIGN_BASE_URL != '-2'
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
with:
name: windows-sciter-x86-exe
path: ./SignOutput/rustdesk-${{ env.VERSION }}-${{ matrix.job.arch }}-sciter.exe
if-no-files-found: error
- name: Publish Release
uses: softprops/action-gh-release@de2c0eb89ae2a093876385947365aca7b0e5f844 # v1
if: env.UPLOAD_ARTIFACT == 'true'
if: env.UPLOAD_ARTIFACT == 'true' && env.PUBLISH_UPDATE_METADATA != 'true'
with:
prerelease: true
tag_name: ${{ env.TAG_NAME }}
@@ -755,6 +858,7 @@ jobs:
target: x86_64-apple-darwin,
os: macos-15-intel, #macos-latest or macos-14 use M1 now, https://docs.github.com/en/actions/using-github-hosted-runners/about-github-hosted-runners/about-github-hosted-runners#:~:text=14%20GB-,macos%2Dlatest%20or%20macos%2D14,-The%20macos%2Dlatestlabel
extra-build-args: "",
extra-cargo-features: "",
arch: x86_64,
vcpkg-triplet: x64-osx,
}
@@ -763,6 +867,7 @@ jobs:
os: macos-14,
# extra-build-args: "--disable-flutter-texture-render", # disable this for mac, because we see a lot of users reporting flickering both on arm and x64, and we can not confirm if texture rendering has better performance if htere is no vram, https://github.com/rustdesk/rustdesk/issues/6296
extra-build-args: "--screencapturekit",
extra-cargo-features: ",screencapturekit",
arch: aarch64,
vcpkg-triplet: arm64-osx,
}
@@ -871,10 +976,10 @@ jobs:
name: bridge-artifact
path: ./
- name: Test cursor sizing
- name: Run the Dart tests
if: ${{ !inputs.upload-artifact && matrix.job.arch == 'aarch64' }}
working-directory: flutter
run: flutter test --timeout 60s test/cursor_size_test.dart test/cursor_replay_test.dart test/cursor_default_test.dart
run: flutter test --timeout 60s
- name: Setup vcpkg with Github Actions binary cache
uses: lukka/run-vcpkg@b1a0dd252f06b9e25b3c022a9a03bd7a427fb6a2 # v11
@@ -916,9 +1021,28 @@ jobs:
sed -i -e "s/platform :osx, '.*'/platform :osx, '${MIN_MACOS_VERSION}'/" flutter/macos/Podfile
sed -i -e "s/osx_minimum_system_version = \"[0-9]*.[0-9]*\"/osx_minimum_system_version = \"${MIN_MACOS_VERSION}\"/" Cargo.toml
sed -i -e "s/MACOSX_DEPLOYMENT_TARGET = [0-9]*.[0-9]*;/MACOSX_DEPLOYMENT_TARGET = ${MIN_MACOS_VERSION};/" flutter/macos/Runner.xcodeproj/project.pbxproj
echo "MACOSX_DEPLOYMENT_TARGET=${MIN_MACOS_VERSION}" >> "$GITHUB_ENV"
fi
./build.py --flutter --hwcodec --unix-file-copy-paste ${{ matrix.job.extra-build-args }}
- name: Test verified updates
if: env.PUBLISH_UPDATE_METADATA == 'true'
run: |
python3 -m unittest res/update/test_macos_update_scripts.py
cargo test --locked --release --lib platform::macos::update_tests --features "flutter,hwcodec,unix-file-copy-paste${{ matrix.job.extra-cargo-features }}"
cargo test --locked --release --lib verified_dmg_tests --features "flutter,hwcodec,unix-file-copy-paste${{ matrix.job.extra-cargo-features }}"
cargo test --locked --release --lib update_metadata::tests --features "flutter,hwcodec,unix-file-copy-paste${{ matrix.job.extra-cargo-features }}"
- name: Run the Rust tests
if: ${{ !inputs.upload-artifact && matrix.job.arch == 'aarch64' }}
run: |
# The build's own features, so the tests see the code that ships. MACOSX_DEPLOYMENT_TARGET
# comes from the build step's export.
FEATURES=$(./build.py --flutter --hwcodec --unix-file-copy-paste ${{ matrix.job.extra-build-args }} --print-features)
cargo test --locked --release --lib --features "$FEATURES"
# Opt-in, and its macOS tests run nowhere else.
cargo test --locked --release -p clipboard --features unix-file-copy-paste
- name: create unsigned dmg
if: env.UPLOAD_ARTIFACT == 'true'
run: |
@@ -951,6 +1075,13 @@ jobs:
./flutter/build/macos/Build/Products/Release/RustDesk.app \
${{ secrets.MACOS_CODESIGN_IDENTITY }} \
./flutter/macos/Runner/Release.entitlements
if [ "$PUBLISH_UPDATE_METADATA" = "true" ]; then
reported_version="$(./flutter/build/macos/Build/Products/Release/RustDesk.app/Contents/MacOS/RustDesk --version)"
if [ "$reported_version" != "$VERSION" ]; then
echo "::error::RustDesk reports version '$reported_version', expected '$VERSION'"
exit 1
fi
fi
create-dmg --icon "RustDesk.app" 200 190 --hide-extension "RustDesk.app" --window-size 800 400 --app-drop-link 600 185 rustdesk-${{ env.VERSION }}.dmg ./flutter/build/macos/Build/Products/Release/RustDesk.app
codesign --force --options runtime -s ${{ secrets.MACOS_CODESIGN_IDENTITY }} --deep --strict rustdesk-${{ env.VERSION }}.dmg -vvv
# notarize the rustdesk-${{ env.VERSION }}.dmg
@@ -958,13 +1089,26 @@ jobs:
- name: Rename rustdesk
if: env.UPLOAD_ARTIFACT == 'true'
shell: bash
env:
VERSION: ${{ env.VERSION }}
ARCH: ${{ matrix.job.arch }}
run: |
for name in rustdesk*??.dmg; do
mv "$name" "${name%%.dmg}-${{ matrix.job.arch }}.dmg"
done
if [ -f "rustdesk-${VERSION}.dmg" ]; then
mv "rustdesk-${VERSION}.dmg" "rustdesk-${VERSION}-${ARCH}.dmg"
fi
test -f "rustdesk-${VERSION}-${ARCH}.dmg"
- name: Upload signed macOS DMG
if: env.UPLOAD_ARTIFACT == 'true' && env.PUBLISH_UPDATE_METADATA == 'true' && env.MACOS_P12_BASE64 != null
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
with:
name: macos-${{ matrix.job.arch }}-dmg
path: ./rustdesk-${{ env.VERSION }}-${{ matrix.job.arch }}.dmg
if-no-files-found: error
- name: Publish DMG package
if: env.UPLOAD_ARTIFACT == 'true'
if: env.UPLOAD_ARTIFACT == 'true' && env.PUBLISH_UPDATE_METADATA != 'true'
uses: softprops/action-gh-release@de2c0eb89ae2a093876385947365aca7b0e5f844 # v1
with:
prerelease: true
@@ -972,6 +1116,141 @@ jobs:
files: |
rustdesk*-${{ matrix.job.arch }}.dmg
publish-signed-update-metadata:
needs: [build-for-windows-flutter, build-for-windows-sciter, build-for-macOS]
runs-on: ubuntu-22.04
if: ${{ inputs.upload-artifact && inputs.publish-update-metadata && github.repository == 'rustdesk/rustdesk' }}
concurrency:
group: signed-update-${{ inputs.upload-tag }}
cancel-in-progress: false
permissions:
# Required to inspect and publish signed release assets for the target tag.
contents: write
steps:
- name: Refuse to replace published update metadata
shell: bash
env:
GH_TOKEN: ${{ github.token }}
TAG_NAME: ${{ env.TAG_NAME }}
run: |
set -euo pipefail
releases="$(gh api --paginate --slurp "repos/${GITHUB_REPOSITORY}/releases?per_page=100")"
release_id="$(
jq -r --arg tag "$TAG_NAME" '
[.[][] | select(.tag_name == $tag)] |
if length == 0 then ""
elif length == 1 then .[0].id
else error("multiple releases found for tag")
end
' <<<"$releases"
)"
if [ -z "$release_id" ]; then
exit 0
fi
assets="$(gh api --paginate --slurp "repos/${GITHUB_REPOSITORY}/releases/${release_id}/assets?per_page=100")"
if jq -e 'any(.[][]; .name == "rustdesk-update.json")' <<<"$assets" >/dev/null; then
echo "::error::Signed update metadata is already published for ${TAG_NAME}; use a new release tag for corrected artifacts."
exit 1
fi
- name: Checkout source code
uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
with:
persist-credentials: false
- name: Install Python
uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5
with:
python-version: "3.12"
- name: Install Python dependencies
run: 'python -m pip install --only-binary=:all: --require-hashes -r res/update/update_metadata_requirements.txt'
- name: Download Windows artifacts
uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
with:
pattern: windows-*
path: ./artifacts/
merge-multiple: true
- name: Download macOS artifacts
uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
with:
pattern: macos-*
path: ./artifacts/
merge-multiple: true
- name: Sign update metadata
env:
RUSTDESK_UPDATE_ED25519_SEED: ${{ secrets.RUSTDESK_UPDATE_ED25519_SEED }}
run: |
python res/update/generate_update_metadata.py sign \
--artifact windows x86_64 exe "./artifacts/rustdesk-${VERSION}-x86_64.exe" \
--artifact windows x86_64 msi "./artifacts/rustdesk-${VERSION}-x86_64.msi" \
--artifact windows aarch64 exe "./artifacts/rustdesk-${VERSION}-aarch64.exe" \
--artifact windows aarch64 msi "./artifacts/rustdesk-${VERSION}-aarch64.msi" \
--artifact windows x86 exe "./artifacts/rustdesk-${VERSION}-x86-sciter.exe" \
--artifact macos aarch64 dmg "./artifacts/rustdesk-${VERSION}-aarch64.dmg" \
--artifact macos x86_64 dmg "./artifacts/rustdesk-${VERSION}-x86_64.dmg" \
--version "$VERSION" --release-id "$TAG_NAME" \
--package-id rustdesk \
--release-base-url https://github.com/rustdesk/rustdesk/releases/download \
--published-at "$(git log -1 --format=%cI)" \
--metadata-out ./rustdesk-update.json \
--signature-out ./rustdesk-update.json.sig
- name: Verify update metadata
env:
RUSTDESK_UPDATE_ED25519_PUBLIC_KEY: ${{ vars.RUSTDESK_UPDATE_ED25519_PUBLIC_KEY }}
run: |
python res/update/generate_update_metadata.py verify \
--metadata ./rustdesk-update.json \
--signature ./rustdesk-update.json.sig \
--artifact "./artifacts/rustdesk-${VERSION}-x86_64.exe" \
--artifact "./artifacts/rustdesk-${VERSION}-x86_64.msi" \
--artifact "./artifacts/rustdesk-${VERSION}-aarch64.exe" \
--artifact "./artifacts/rustdesk-${VERSION}-aarch64.msi" \
--artifact "./artifacts/rustdesk-${VERSION}-x86-sciter.exe" \
--artifact "./artifacts/rustdesk-${VERSION}-aarch64.dmg" \
--artifact "./artifacts/rustdesk-${VERSION}-x86_64.dmg" \
--version "$VERSION" --release-id "$TAG_NAME" \
--package-id rustdesk \
--release-base-url https://github.com/rustdesk/rustdesk/releases/download
- name: Upload signed update artifacts
uses: softprops/action-gh-release@de2c0eb89ae2a093876385947365aca7b0e5f844 # v1
with:
prerelease: true
fail_on_unmatched_files: true
tag_name: ${{ env.TAG_NAME }}
files: |
./artifacts/rustdesk-${{ env.VERSION }}-x86_64.exe
./artifacts/rustdesk-${{ env.VERSION }}-x86_64.msi
./artifacts/rustdesk-${{ env.VERSION }}-aarch64.exe
./artifacts/rustdesk-${{ env.VERSION }}-aarch64.msi
./artifacts/rustdesk-${{ env.VERSION }}-x86-sciter.exe
./artifacts/rustdesk-${{ env.VERSION }}-aarch64.dmg
./artifacts/rustdesk-${{ env.VERSION }}-x86_64.dmg
# The release action replaces same-name assets, so keep published sidecars
# until replacements are ready.
- name: Upload signed update metadata signature
uses: softprops/action-gh-release@de2c0eb89ae2a093876385947365aca7b0e5f844 # v1
with:
prerelease: true
fail_on_unmatched_files: true
tag_name: ${{ env.TAG_NAME }}
files: ./rustdesk-update.json.sig
# Clients discover the release through metadata, so publish it only after every referenced asset.
- name: Publish signed update metadata
uses: softprops/action-gh-release@de2c0eb89ae2a093876385947365aca7b0e5f844 # v1
with:
prerelease: true
fail_on_unmatched_files: true
tag_name: ${{ env.TAG_NAME }}
files: ./rustdesk-update.json
publish_unsigned:
needs:
- build-for-macOS
@@ -2086,12 +2365,21 @@ jobs:
cargo test --locked --lib --features drm peer_abs_sample_tests
run_drm_tests "rustdesk input_map_tests" \
cargo test --locked --lib --features drm input_map_tests
run_drm_tests "rustdesk drm_pacing_tests" \
cargo test --locked --lib --features drm drm_pacing_tests
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
run_drm_tests "scrap crtc_refresh_tests" \
cargo test --locked -p scrap --features drm crtc_refresh_tests
run_drm_tests "scrap plane_rotation_tests" \
cargo test --locked -p scrap --features drm plane_rotation_tests
run_drm_tests "scrap drmtap_dl::tests" \
cargo test --locked -p scrap --features drm drmtap_dl::tests
# Opt-in like drm, and this container already builds with it.
run_drm_tests "clipboard unix-file-copy-paste" \
cargo test --locked -p clipboard --features unix-file-copy-paste
cargo build --locked --lib --features "$FEATURES" --release
rm -rf target/release/deps target/release/build
rm -rf ~/.cargo
@@ -2172,6 +2460,7 @@ jobs:
build-rustdesk-linux-sciter:
if: ${{ inputs.upload-artifact }}
needs: [validate-update-metadata-keys]
runs-on: ${{ matrix.job.on }}
name: build-rustdesk-linux-sciter ${{ matrix.job.target }}
strategy:
@@ -2552,6 +2841,7 @@ jobs:
build-rustdesk-web:
if: False
needs: [validate-update-metadata-keys]
name: build-rustdesk-web
runs-on: ubuntu-22.04
permissions:
+2 -1
View File
@@ -15,4 +15,5 @@ jobs:
secrets: inherit
with:
upload-artifact: true
upload-tag: ${{ github.ref_name }}
upload-tag: ${{ github.ref_name }}
publish-update-metadata: ${{ github.repository == 'rustdesk/rustdesk' }}
+1 -1
View File
@@ -17,7 +17,7 @@ env:
TAG_NAME: "nightly"
VCPKG_BINARY_SOURCES: "clear;x-gha,readwrite"
VCPKG_COMMIT_ID: "9e593bb18ea69cc5095e012465dcd675a822ed0d"
VERSION: "1.5.0"
VERSION: "1.5.1"
NDK_VERSION: "r26d"
#signing keys env variable checks
ANDROID_SIGNING_KEY: "${{ secrets.ANDROID_SIGNING_KEY }}"
+4
View File
@@ -186,6 +186,10 @@ A refactor added to cover a corner case rarely converges. Each new counter, time
* Do not add test infrastructure (browser runners, golden/screenshot harnesses, new mock layers, test-only hooks in production code) for a bug fix unless the maintainer asks.
* If the test diff is more than twice the fix, cut it back to the tests that pin the reported behavior. A state that needs long setup to reach is usually too rare to fix.
* When the number of tests needed to describe the behavior keeps growing, the implementation is too complex: simplify it instead of adding tests.
* Dart tests go in `flutter/test/*_test.dart`, nowhere else: CI runs `flutter test` over that directory and nothing outside it. It runs on the VM, so a `@TestOn('browser')` suite runs in no CI job.
* Rust unit tests go in a `#[cfg(test)]` module beside the code. CI runs `cargo test --workspace` with the default features on x86_64 Linux, `cargo test --lib` on the root package with the release feature set on macOS and Windows plus `-p clipboard` there, and on Linux the `drm` test modules by name plus the `clipboard` package with `unix-file-copy-paste`. On macOS and Windows, a platform-gated test in another workspace crate runs only if that platform's job names the crate with `-p`. Gate a test module on a feature or `target_os` only when the code under test is gated; a pure helper that only a gated path calls gets `#[cfg(any(feature = "...", test))]`, so its tests run everywhere.
* A test behind a feature that no CI build enables needs a `cargo test` line in `.github/workflows/flutter-build.yml` that names it. In the Linux drm job, wrap it in `run_drm_tests` so a filter that matches nothing fails instead of passing.
* Web core tests are `flutter/web/js/src/*.test.ts`, run by jest in that repository's own CI.
## Reviewing a PR
Generated
+15 -20
View File
@@ -4163,16 +4163,6 @@ version = "2.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "469fb0b9cefa57e3ef31275ee7cacb78f2fdca44e4765491884a2b119d4eb130"
[[package]]
name = "iri-string"
version = "0.7.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dbc5ebe9c3a1a7a5127f920a418f7585e9e758e911d0466ed004f393b0e380b2"
dependencies = [
"memchr",
"serde 1.0.228",
]
[[package]]
name = "is-terminal"
version = "0.4.16"
@@ -6772,7 +6762,7 @@ dependencies = [
[[package]]
name = "rdev"
version = "0.5.0-2"
source = "git+https://github.com/rustdesk-org/rdev#a361d86a8b0245f3618a9efb375c149530a6b599"
source = "git+https://github.com/rustdesk-org/rdev#0904f23ce496e255461a98848b85c11fa5a62eab"
dependencies = [
"cocoa 0.24.1",
"core-foundation 0.9.4",
@@ -6901,11 +6891,10 @@ dependencies = [
[[package]]
name = "reqwest"
version = "0.12.24"
version = "0.12.28"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9d0946410b9f7b082a427e4ef5c8ff541a88b357bc6c637c40db3a68ac70a36f"
checksum = "eddd3ca559203180a307f12d114c268abf583f59b03cb906fd0b3ff8646c1147"
dependencies = [
"async-compression",
"base64 0.22.1",
"bytes",
"futures-channel",
@@ -6934,7 +6923,6 @@ dependencies = [
"tokio",
"tokio-native-tls",
"tokio-rustls",
"tokio-util",
"tower",
"tower-http",
"tower-service",
@@ -7087,7 +7075,7 @@ dependencies = [
[[package]]
name = "rustdesk"
version = "1.5.0"
version = "1.5.1"
dependencies = [
"android-wakelock",
"android_logger",
@@ -7187,6 +7175,7 @@ dependencies = [
"uuid",
"virtual_display",
"wallpaper",
"wayland-client",
"winapi 0.3.9",
"windows 0.61.1",
"windows-service",
@@ -7196,13 +7185,14 @@ dependencies = [
"wol-rs",
"x11-clipboard 0.8.1",
"x11rb 0.12.0",
"xkbcommon-dl",
"xxhash-rust",
"zstd",
]
[[package]]
name = "rustdesk-portable-packer"
version = "1.5.0"
version = "1.5.1"
dependencies = [
"brotli",
"dirs 5.0.1",
@@ -8744,20 +8734,25 @@ dependencies = [
[[package]]
name = "tower-http"
version = "0.6.6"
version = "0.6.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "adc82fd73de2a9722ac5da747f12383d2bfdb93591ee6c58486e0097890f05f2"
checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840"
dependencies = [
"async-compression",
"bitflags 2.9.1",
"bytes",
"futures-core",
"futures-util",
"http",
"http-body",
"iri-string",
"http-body-util",
"pin-project-lite",
"tokio",
"tokio-util",
"tower",
"tower-layer",
"tower-service",
"url",
]
[[package]]
+4 -2
View File
@@ -1,6 +1,6 @@
[package]
name = "rustdesk"
version = "1.5.0"
version = "1.5.1"
authors = ["rustdesk <info@rustdesk.com>"]
edition = "2021"
build= "build.rs"
@@ -202,6 +202,8 @@ gtk = "0.18"
termios = "0.3"
terminfo = "0.8"
winit = "0.30"
wayland-client = "0.31"
xkbcommon-dl = { version = "0.4", features = ["x11"] }
[target.'cfg(any(target_os = "linux", target_os = "android"))'.dependencies]
openssl = { version = "0.10", features = ["vendored"] }
@@ -271,7 +273,7 @@ os-version = "0.2"
[dev-dependencies]
hound = "3.5"
docopt = "1.1"
tokio = { version = "1.44", features = ["test-util"] }
tokio = "1.44"
[package.metadata.bundle]
name = "RustDesk"
+1 -1
View File
@@ -18,7 +18,7 @@ AppDir:
id: rustdesk
name: rustdesk
icon: rustdesk
version: 1.5.0
version: 1.5.1
exec: usr/share/rustdesk/rustdesk
exec_args: $@
apt:
+1 -1
View File
@@ -18,7 +18,7 @@ AppDir:
id: rustdesk
name: rustdesk
icon: rustdesk
version: 1.5.0
version: 1.5.1
exec: usr/share/rustdesk/rustdesk
exec_args: $@
apt:
+2 -2
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.8.
# libs/scrap/Cargo.toml). This commit is libdrmtap v0.5.12.
LIBDRMTAP_REPO_PINNED = 'https://github.com/rustdesk-org/libdrmtap'
LIBDRMTAP_SHA_PINNED = '95d4d74549631aa5c39461300acfd2e106583cc9'
LIBDRMTAP_SHA_PINNED = '5936a7a88b94aa43516a3dd0eb509d2383f31e2d'
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
+66 -57
View File
@@ -154,7 +154,7 @@ prebuild)
.github/workflows/bridge.yml)"
FLUTTER_BRIDGE_VERSION="$(yq -r \
.env.FLUTTER_VERSION \
'.jobs.generate_bridge.strategy.matrix.job[] | select(.["artifact-name"] == "bridge-artifact") | .["flutter-version"]' \
.github/workflows/bridge.yml)"
FLUTTER_RUST_BRIDGE_VERSION="$(yq -r \
@@ -306,67 +306,69 @@ prebuild)
git apply res/fdroid/patches/*.patch
# If Flutter version used to generate bridge files differs from Flutter
# version used to compile Rustdesk library, generate bridge using the
# `FLUTTER_BRIDGE_VERSION` an restore the pubspec later
# Generate bridge files using `FLUTTER_BRIDGE_VERSION`, which may differ
# from the Flutter version used to compile RustDesk library, and restore
# the pubspec later
if [ "${FLUTTER_VERSION}" != "${FLUTTER_BRIDGE_VERSION}" ]; then
# Find first libclang.so and set BRIDGE_LLVM_PATH
# Find first libclang.so and set BRIDGE_LLVM_PATH
BRIDGE_LLVM_PATH="$(find /usr/lib/ -name libclang.so | head -n1)"
BRIDGE_LLVM_PATH="$(find /usr/lib/ -name libclang.so | head -n1)"
if [ -z "${BRIDGE_LLVM_PATH}" ]; then
echo 'ERROR: Can not find libclang.so for bridge generator!' >&2
exit 1
fi
BRIDGE_LLVM_PATH="$(dirname "${BRIDGE_LLVM_PATH}")"
BRIDGE_LLVM_PATH="$(dirname "${BRIDGE_LLVM_PATH}")"
# Install Flutter bridge version
prepare_flutter "${FLUTTER_BRIDGE_VERSION}" "${HOME}/flutter"
# Save changes
git add .
# Edit pubspec to make flutter bridge version work
sed \
-i \
-e 's/extended_text: 14.0.0/extended_text: 13.0.0/g' \
flutter/pubspec.yaml
# Download Flutter dependencies
pushd flutter
flutter clean
flutter packages pub get
popd # flutter
# Generate FFI bindings
flutter_rust_bridge_codegen \
--rust-input ./src/flutter_ffi.rs \
--dart-output ./flutter/lib/generated_bridge.dart \
--llvm-path "${BRIDGE_LLVM_PATH}"
# Add bridge files to save-list
git add -f ./flutter/lib/generated_bridge.* ./src/bridge_generated.*
# Restore everything
git checkout '*'
git clean -dffx
git reset
unset BRIDGE_LLVM_PATH
if [ -z "${BRIDGE_LLVM_PATH}" ]; then
echo 'ERROR: Can not find libclang.so for bridge generator!' >&2
exit 1
fi
BRIDGE_LLVM_PATH="$(dirname "${BRIDGE_LLVM_PATH}")"
BRIDGE_LLVM_PATH="$(dirname "${BRIDGE_LLVM_PATH}")"
# Install Flutter bridge version
# Unbraced on purpose: F-Droid recipes rewrite the braced form with sed to
# pin a version, but the bridge generator only works with the Flutter
# version bridge.yml uses
prepare_flutter "$FLUTTER_BRIDGE_VERSION" "${HOME}/flutter"
# Save changes
git add .
# Edit pubspec to make flutter bridge version work
sed \
-i \
-e 's/extended_text: 14.0.0/extended_text: 13.0.0/g' \
flutter/pubspec.yaml
# Download Flutter dependencies
pushd flutter
flutter clean
flutter packages pub get
popd # flutter
# Generate FFI bindings
flutter_rust_bridge_codegen \
--rust-input ./src/flutter_ffi.rs \
--dart-output ./flutter/lib/generated_bridge.dart \
--llvm-path "${BRIDGE_LLVM_PATH}"
# Add bridge files to save-list
git add -f ./flutter/lib/generated_bridge.* ./src/bridge_generated.*
# Restore everything
git checkout '*'
git clean -dffx
git reset
unset BRIDGE_LLVM_PATH
# Install Flutter version for RustDesk library build
prepare_flutter "${FLUTTER_VERSION}" "${HOME}/flutter"
@@ -379,6 +381,13 @@ prebuild)
flutter/android/build.gradle \
flutter/android/app/build.gradle
# Gradle 8 / AGP 8 thrash in the default 1 GiB heap; raise it as CI does
sed \
-i \
-e 's/org.gradle.jvmargs=-Xmx1024M/org.gradle.jvmargs=-Xmx2g/g' \
flutter/android/gradle.properties
# `firebase_analytics` is not in these files now, but we still keep the following lines.
sed \
@@ -271,11 +271,6 @@ class AllPeersLoader {
void updateOnlineStateForTesting(Map<String, dynamic> evt) {
_updateOnlineState(evt);
}
@visibleForTesting
bool applyLastOnlineStateForTesting(List<Peer> peers) {
return _applyLastOnlineState(peers);
}
}
class AutocompletePeerTile extends StatefulWidget {
+30 -2
View File
@@ -62,12 +62,15 @@ class _InstallPageBody extends StatefulWidget {
class _InstallPageBodyState extends State<_InstallPageBody>
with WindowListener {
static const _printerStatusTimeout = Duration(seconds: 5);
late final TextEditingController controller;
final RxBool startmenu = true.obs;
final RxBool desktopicon = true.obs;
final RxBool printer = false.obs;
final RxBool showProgress = false.obs;
final RxBool btnEnabled = true.obs;
final RxBool cancelEnabled = true.obs;
// todo move to theme.
final buttonStyle = OutlinedButton.styleFrom(
@@ -83,10 +86,33 @@ class _InstallPageBodyState extends State<_InstallPageBody>
printer.value = installOptions['PRINTER'] == '1';
}
Future<void> _loadPrinterStatus() async {
btnEnabled.value = false;
showProgress.value = true;
try {
final status = await bind
.mainGetCommon(key: 'is-printer-installed')
.timeout(_printerStatusTimeout);
printer.value = status == 'true';
if (status != 'true' && status != 'false') {
debugPrint('Failed to check printer installation status: $status');
}
} catch (e) {
printer.value = false;
debugPrint('Failed to check printer installation status: $e');
} finally {
showProgress.value = false;
btnEnabled.value = true;
}
}
@override
void initState() {
windowManager.addListener(this);
super.initState();
if (printer.value) {
_loadPrinterStatus();
}
}
@override
@@ -217,8 +243,9 @@ class _InstallPageBodyState extends State<_InstallPageBody>
() => OutlinedButton.icon(
icon: Icon(Icons.close_rounded, size: 16),
label: Text(translate('Cancel')),
onPressed:
btnEnabled.value ? () => windowManager.close() : null,
onPressed: cancelEnabled.value
? () => windowManager.close()
: null,
style: buttonStyle,
).marginOnly(right: 10),
),
@@ -253,6 +280,7 @@ class _InstallPageBodyState extends State<_InstallPageBody>
void install() {
do_install() {
btnEnabled.value = false;
cancelEnabled.value = false;
showProgress.value = true;
String args = '';
if (startmenu.value) args += ' startmenu';
@@ -418,6 +418,13 @@ class _DesktopTabState extends State<DesktopTab>
}
}
// On Linux, GTK destroys the window on a close request unless prevent-close
// is on. It is off for the cm and install windows, and onActiveWindowChanged()
// turns it off to quit, so the window can no longer be saved or hidden.
// https://github.com/rustdesk/rustdesk/issues/16512
Future<bool> _isLinuxWindowClosed() async =>
isLinux && isMainWindow && !await windowManager.isPreventClose();
@override
void onWindowMoved() {
_saveFrame();
@@ -465,6 +472,8 @@ class _DesktopTabState extends State<DesktopTab>
});
}
if (await _isLinuxWindowClosed()) return;
await _saveFrame(flush: true);
// hide window on close
@@ -472,6 +481,7 @@ class _DesktopTabState extends State<DesktopTab>
if (rustDeskWinManager.getActiveWindows().contains(kMainWindowId)) {
await rustDeskWinManager.unregisterActiveWindow(kMainWindowId);
}
if (await _isLinuxWindowClosed()) return;
// macOS specific workaround, the window is not hiding when in fullscreen.
if (isMacOS && await windowManager.isFullScreen()) {
await windowManager.setFullScreen(false);
@@ -7,36 +7,49 @@ import 'package:flutter_hbb/models/platform_model.dart';
import 'package:get/get.dart';
import 'package:url_launcher/url_launcher.dart';
final _isExtracting = false.obs;
const _eventKeyUpdateMe = 'update-me';
void handleUpdate(String releasePageUrl) {
_isExtracting.value = false;
String downloadUrl = releasePageUrl.replaceAll('tag', 'download');
String version = downloadUrl.substring(downloadUrl.lastIndexOf('/') + 1);
final String downloadFile =
bind.mainGetCommonSync(key: 'download-file-$version');
if (downloadFile.startsWith('error:')) {
final error = downloadFile.replaceFirst('error:', '');
msgBox(gFFI.sessionId, 'custom-nocancel-nook-hasclose', 'Error', error,
releasePageUrl, gFFI.dialogManager);
Future<void> _handleUpdateMe(
String releasePageUrl, Map<String, dynamic> evt) async {
platformFFI.unregisterEventHandler(_eventKeyUpdateMe, _eventKeyUpdateMe);
if (evt.containsKey('error')) {
_showUpdateError(releasePageUrl, evt['error'] as String);
}
}
Future<void> handleUpdate(String releasePageUrl) async {
final dialogClosed = _showVerifyingUpdate();
final String? downloadUrl;
try {
downloadUrl = await waitForUpdateVerification(
bind.mainGetCommon(key: 'verified-download-url-$releasePageUrl'),
dialogClosed,
);
} catch (error) {
_showUpdateError(releasePageUrl, error.toString());
return;
}
if (downloadUrl == null) {
return;
}
final verifiedDownloadUrl = downloadUrl;
if (downloadUrl.startsWith('error:')) {
_showUpdateError(releasePageUrl, downloadUrl.replaceFirst('error:', ''));
return;
}
downloadUrl = '$downloadUrl/$downloadFile';
SimpleWrapper downloadId = SimpleWrapper('');
SimpleWrapper<VoidCallback> onCanceled = SimpleWrapper(() {});
gFFI.dialogManager.dismissAll();
gFFI.dialogManager.show((setState, close, context) {
return CustomAlertDialog(
title: Obx(() => Text(translate(_isExtracting.isTrue
? 'Preparing for installation ...'
: 'Downloading {$appName}'))),
content:
UpdateProgress(releasePageUrl, downloadUrl, downloadId, onCanceled)
.marginSymmetric(horizontal: 8)
.paddingOnly(top: 12),
title: Text(translate('Downloading {$appName}')),
content: UpdateProgress(
releasePageUrl, verifiedDownloadUrl, downloadId, onCanceled)
.marginSymmetric(horizontal: 8)
.paddingOnly(top: 12),
actions: [
if (_isExtracting.isFalse) dialogButton(translate('Cancel'), onPressed: () async {
dialogButton('Cancel', onPressed: () async {
onCanceled.value();
await bind.mainSetCommon(
key: 'cancel-downloader', value: downloadId.value);
@@ -56,6 +69,40 @@ void handleUpdate(String releasePageUrl) {
});
}
Future<T?> waitForUpdateVerification<T extends Object>(
Future<T> verification,
Future<void> dialogClosed,
) async {
final dialogClosedMarker = Object();
final result = await Future.any<Object>([
verification.then<Object>((value) => value),
dialogClosed.then<Object>((_) => dialogClosedMarker),
]);
return identical(result, dialogClosedMarker) ? null : result as T;
}
Future<void> _showVerifyingUpdate() async {
gFFI.dialogManager.dismissAll();
await gFFI.dialogManager.show<void>(
(setState, close, context) => CustomAlertDialog(
title: Text(translate('Preparing for installation ...')),
content: const LinearProgressIndicator(),
actions: [
dialogButton('Close', onPressed: close, isOutline: true),
],
onCancel: close,
),
tag: 'verifying-update',
);
}
void _showUpdateError(String releasePageUrl, String error) {
debugPrint('Update error: $error');
gFFI.dialogManager.dismissAll();
msgBox(gFFI.sessionId, 'custom-nocancel-nook-hasclose', 'Error', error,
releasePageUrl, gFFI.dialogManager);
}
class UpdateProgress extends StatefulWidget {
final String releasePageUrl;
final String downloadUrl;
@@ -74,9 +121,9 @@ class UpdateProgressState extends State<UpdateProgress> {
Timer? _timer;
int? _totalSize;
int _downloadedSize = 0;
bool _downloadFinished = false;
int _getDataFailedCount = 0;
final String _eventKeyDownloadNewVersion = 'download-new-version';
final String _eventKeyExtractUpdateDmg = 'extract-update-dmg';
@override
void initState() {
@@ -88,11 +135,6 @@ class UpdateProgressState extends State<UpdateProgress> {
_eventKeyDownloadNewVersion, handleDownloadNewVersion,
replace: true);
bind.mainSetCommon(key: 'download-new-version', value: widget.downloadUrl);
if (isMacOS) {
platformFFI.registerEventHandler(_eventKeyExtractUpdateDmg,
_eventKeyExtractUpdateDmg, handleExtractUpdateDmg,
replace: true);
}
}
@override
@@ -100,10 +142,7 @@ class UpdateProgressState extends State<UpdateProgress> {
cancelQueryTimer();
platformFFI.unregisterEventHandler(
_eventKeyDownloadNewVersion, _eventKeyDownloadNewVersion);
if (isMacOS) {
platformFFI.unregisterEventHandler(
_eventKeyExtractUpdateDmg, _eventKeyExtractUpdateDmg);
}
platformFFI.unregisterEventHandler(_eventKeyUpdateMe, _eventKeyUpdateMe);
super.dispose();
}
@@ -128,35 +167,33 @@ class UpdateProgressState extends State<UpdateProgress> {
}
}
// `isExtractDmg` is true when handling extract-update-dmg event.
// It's a rare case that the dmg file is corrupted and cannot be extracted.
void _onError(String error, {bool isExtractDmg = false}) {
void _onError(String error) {
cancelQueryTimer();
debugPrint(
'${isExtractDmg ? "Extract" : "Download"} new version error: $error');
debugPrint('Download new version error: $error');
final msgBoxType = 'custom-nocancel-nook-hasclose';
final msgBoxTitle = 'Error';
final msgBoxText = 'download-new-version-failed-tip';
final dialogManager = gFFI.dialogManager;
final releasePageUrl = widget.releasePageUrl;
close() {
dialogManager.dismissAll();
}
jumplink() {
launchUrl(Uri.parse(widget.releasePageUrl));
launchUrl(Uri.parse(releasePageUrl));
dialogManager.dismissAll();
}
retry() {
dialogManager.dismissAll();
handleUpdate(widget.releasePageUrl);
handleUpdate(releasePageUrl);
}
final List<Widget> buttons = [
dialogButton('Download', onPressed: jumplink),
if (!isExtractDmg) dialogButton('Retry', onPressed: retry),
dialogButton('Retry', onPressed: retry),
dialogButton('Close', onPressed: close),
];
dialogManager.dismissAll();
@@ -186,6 +223,8 @@ class UpdateProgressState extends State<UpdateProgress> {
}
} else if (key == 'downloaded_size') {
_downloadedSize = value as int;
} else if (key == 'finished') {
_downloadFinished = value as bool;
} else if (key == 'error') {
if (value != null) {
err = value.toString();
@@ -204,7 +243,9 @@ class UpdateProgressState extends State<UpdateProgress> {
if (err != '') {
_onError(err);
} else {
if (_totalSize != null && _downloadedSize >= _totalSize!) {
if (_downloadFinished &&
_totalSize != null &&
_downloadedSize >= _totalSize!) {
cancelQueryTimer();
bind.mainSetCommon(
key: 'remove-downloader', value: widget.downloadId.value);
@@ -212,13 +253,7 @@ class UpdateProgressState extends State<UpdateProgress> {
_onError('The download file size is 0.');
} else {
setState(() {});
if (isMacOS) {
bind.mainSetCommon(
key: 'extract-update-dmg', value: widget.downloadUrl);
_isExtracting.value = true;
} else {
updateMsgBox();
}
updateMsgBox();
}
} else {
setState(() {});
@@ -227,6 +262,8 @@ class UpdateProgressState extends State<UpdateProgress> {
}
void updateMsgBox() {
final releasePageUrl = widget.releasePageUrl;
final downloadUrl = widget.downloadUrl;
msgBox(
gFFI.sessionId,
'custom-nocancel',
@@ -234,30 +271,30 @@ class UpdateProgressState extends State<UpdateProgress> {
'{$appName}-to-update-tip',
'',
gFFI.dialogManager,
onSubmit: () {
onSubmit: () async {
debugPrint('Downloaded, update to new version now');
bind.mainSetCommon(key: 'update-me', value: widget.downloadUrl);
platformFFI.registerEventHandler(_eventKeyUpdateMe, _eventKeyUpdateMe,
(evt) => _handleUpdateMe(releasePageUrl, evt),
replace: true);
try {
await bind.mainSetCommon(key: 'update-me', value: downloadUrl);
} catch (error) {
platformFFI.unregisterEventHandler(
_eventKeyUpdateMe, _eventKeyUpdateMe);
_showUpdateError(releasePageUrl, error.toString());
}
},
submitTimeout: 5,
);
}
Future<void> handleExtractUpdateDmg(Map<String, dynamic> evt) async {
_isExtracting.value = false;
if (evt.containsKey('err') && (evt['err'] as String).isNotEmpty) {
_onError(evt['err'] as String, isExtractDmg: true);
} else {
updateMsgBox();
}
}
@override
Widget build(BuildContext context) {
getValue() => _totalSize == null
? 0.0
: (_totalSize == 0 ? 1.0 : _downloadedSize / _totalSize!);
return LinearProgressIndicator(
value: _isExtracting.isTrue ? null : getValue(),
value: getValue(),
minHeight: 20,
borderRadius: BorderRadius.circular(5),
backgroundColor: Colors.grey[300],
@@ -377,6 +377,10 @@ class _RemotePageState extends State<RemotePage> with WidgetsBindingObserver {
// clipboard
oldValue = '';
}
// This length-only diff assumes the IME appends at the end. If an IME
// leaves the caret inside paired punctuation, later insertions can replay
// the closing symbol: "()" -> "(a)" sends ")" instead of "a". This is a
// client text-diff issue, independent of the host keyboard layout.
if (newValue.length == oldValue.length) {
// ?
} else if (newValue.length < oldValue.length) {
@@ -11,10 +11,3 @@ const terminalKeyboardKeySpacing = 2.0;
/// Empty 48dp slots keep expanded Row3 aligned with the two rows above it.
const terminalKeyboardRow3TrailingPlaceholderCount = 2;
/// Returns the fixed width occupied by a row of equally sized key slots.
double terminalKeyboardRowWidth(int slotCount) {
if (slotCount <= 0) return 0;
return slotCount * terminalKeyboardKeyWidth +
(slotCount - 1) * terminalKeyboardKeySpacing;
}
@@ -372,6 +372,8 @@ class _FloatingLeftRightButtonState extends State<FloatingLeftRightButton> {
Offset _position = Offset.zero;
bool _isInitialized = false;
bool _isDown = false;
Object? _activePress;
bool _remoteButtonDown = false;
Rect? _lastBlockedRect;
Orientation? _previousOrientation;
@@ -398,6 +400,11 @@ class _FloatingLeftRightButtonState extends State<FloatingLeftRightButton> {
@override
void dispose() {
_activePress = null;
if (_remoteButtonDown) {
_remoteButtonDown = false;
_inputModel.tapUp(_isLeft ? MouseButtons.left : MouseButtons.right);
}
if (_lastBlockedRect != null) {
_cursorModel.removeBlockedRect(_lastBlockedRect!);
}
@@ -569,6 +576,8 @@ class _FloatingLeftRightButtonState extends State<FloatingLeftRightButton> {
child: Listener(
onPointerMove: _onBodyPointerMoveUpdate,
onPointerDown: (event) async {
final press = Object();
_activePress = press;
_isDragging = false;
setState(() {
_isDown = true;
@@ -579,6 +588,8 @@ class _FloatingLeftRightButtonState extends State<FloatingLeftRightButton> {
isSpecialHoldDragActive = true;
() async {
await _cursorModel.syncCursorPosition();
if (!mounted || !identical(_activePress, press)) return;
_remoteButtonDown = true;
await _inputModel
.tapDown(_isLeft ? MouseButtons.left : MouseButtons.right);
}();
@@ -586,6 +597,8 @@ class _FloatingLeftRightButtonState extends State<FloatingLeftRightButton> {
});
},
onPointerUp: (event) {
if (!mounted) return;
_activePress = null;
_cursorModel.blockEvents = false;
setState(() {
_isDown = false;
@@ -604,8 +617,8 @@ class _FloatingLeftRightButtonState extends State<FloatingLeftRightButton> {
}));
} else {
// If it's not a quick tap, it could be a hold or drag.
// If it was a hold, isSpecialHoldDragActive is true.
if (isSpecialHoldDragActive) {
if (_remoteButtonDown) {
_remoteButtonDown = false;
_inputModel
.tapUp(_isLeft ? MouseButtons.left : MouseButtons.right);
}
@@ -617,13 +630,16 @@ class _FloatingLeftRightButtonState extends State<FloatingLeftRightButton> {
isSpecialHoldDragActive = false;
},
onPointerCancel: (event) {
if (!mounted) return;
_activePress = null;
_cursorModel.blockEvents = false;
setState(() {
_isDown = false;
});
_tapDownTimer?.cancel();
_tapDownTimer = null;
if (isSpecialHoldDragActive) {
if (_remoteButtonDown) {
_remoteButtonDown = false;
_inputModel.tapUp(_isLeft ? MouseButtons.left : MouseButtons.right);
}
isSpecialHoldDragActive = false;
+21 -2
View File
@@ -459,6 +459,7 @@ class InputModel {
// mouse
final isPhysicalMouse = false.obs;
int _lastButtons = 0;
int _pressedMouseButtons = 0;
Offset lastMousePos = Offset.zero;
int _lastWheelTsUs = 0;
@@ -1388,6 +1389,10 @@ class InputModel {
}
}
_lastButtons = hasStaleButtonsOnMouseUp ? 0 : evt.buttons;
if (isDesktop && _relativeMouse.enabled.value && type == _kMouseEventUp) {
// A relative up can finish a press sent before the mode switch.
_pressedMouseButtons &= ~buttons;
}
out['buttons'] = buttons;
out['type'] = type;
@@ -2134,9 +2139,16 @@ class InputModel {
bool edgeScroll = false,
}) {
if (isViewCamera) return null;
final buttons = evt['buttons'];
final isMatchingMouseUp = (isDesktop || isWebDesktop) &&
evt['type'] == _kMouseEventUp &&
buttons is int &&
mouseButtonsToPeer(buttons).isNotEmpty &&
_pressedMouseButtons & buttons != 0;
double x = offset.dx;
double y = max(0.0, offset.dy);
if (_checkPeerControlProtected(x, y)) {
// Cursor ownership may change between a forwarded down and its up.
if (_checkPeerControlProtected(x, y) && !isMatchingMouseUp) {
return null;
}
@@ -2178,6 +2190,9 @@ class InputModel {
if (pos == null) {
return null;
}
if (isMatchingMouseUp) {
_pressedMouseButtons &= ~buttons;
}
if (type != '') {
evt['x'] = '0';
evt['y'] = '0';
@@ -2186,9 +2201,13 @@ class InputModel {
evt['y'] = '${pos.y.toInt()}';
}
final buttons = evt['buttons'];
if (buttons is int) {
evt['buttons'] = mouseButtonsToPeer(buttons);
if ((isDesktop || isWebDesktop) &&
type == kMouseEventTypeDown &&
evt['buttons'] != '') {
_pressedMouseButtons |= buttons;
}
} else {
// Log warning if buttons exists but is not an int (unexpected caller).
// Keep empty string fallback for missing buttons to preserve move/hover behavior.
-4
View File
@@ -70,10 +70,6 @@ class TerminalModel with ChangeNotifier {
final _inputBuffer = <String>[];
/// Exposes buffered input only for lifecycle regression tests.
@visibleForTesting
int get debugBufferedInputCount => _inputBuffer.length;
// Buffer for output data received before terminal view has valid dimensions.
// This prevents NaN errors when writing to terminal before layout is complete.
final _pendingOutputChunks = <String>[];
+1 -1
View File
@@ -16,7 +16,7 @@ publish_to: "none" # Remove this line if you wish to publish to pub.dev
# Read more about iOS versioning at
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
# 1.1.9-1 works for android, but for ios it becomes 1.1.91, need to set it to 1.1.9-a.1 for iOS, will get 1.1.9.1, but iOS store not allow 4 numbers
version: 1.5.0+68
version: 1.5.1+68
environment:
sdk: '^3.1.0'
@@ -48,74 +48,6 @@ void main() {
expect(peers.single.online, isTrue);
});
test('peer copies preserve online state', () {
final peer = _peer(id: '987654321', online: true);
expect(Peer.copy(peer).online, isTrue);
});
test('online callbacks update autocomplete-only peers', () {
final peers = mergeAutocompletePeers(restRecentPeerIds: ['112233445']);
final changed = updateAutocompletePeerOnlineStates(
peers,
onlines: {'112233445'},
offlines: {},
);
expect(changed, isTrue);
expect(peers.single.online, isTrue);
});
test('online query ids are deduplicated and limited', () {
final peers = List.generate(
25,
(index) => _peer(id: index.toString()),
)..insert(1, _peer(id: '0'));
final ids = autocompleteOnlineQueryIds(peers, limit: 20);
expect(ids, hasLength(20));
expect(ids.first, '0');
expect(ids.where((id) => id == '0'), hasLength(1));
expect(ids.last, '19');
});
test('empty online query ids cancel pending debounce', () async {
final queriedIds = <List<String>>[];
final loader = AllPeersLoader(
queryOnlines: (ids) async {
queriedIds.add(ids);
},
queryOnlineDebounce: Duration(milliseconds: 1),
);
loader.queryOnlines([_peer(id: '123456789')]);
loader.queryOnlines([]);
await Future.delayed(Duration(milliseconds: 2));
expect(queriedIds, isEmpty);
});
test('failed online query enqueue does not suppress retry', () async {
var queryCount = 0;
final loader = AllPeersLoader(
queryOnlines: (ids) {
queryCount += 1;
return Future<void>.error(Exception('queue full'));
},
queryOnlineDebounce: Duration(milliseconds: 1),
);
loader.queryOnlines([_peer(id: '123456789')]);
await Future.delayed(Duration(milliseconds: 2));
loader.queryOnlines([_peer(id: '123456789')]);
await Future.delayed(Duration(milliseconds: 2));
expect(queryCount, 2);
});
test('online callback updates currently displayed options', () async {
final loader = AllPeersLoader(
queryOnlines: (ids) async {},
@@ -132,17 +64,4 @@ void main() {
expect(displayedOptions.single.online, isTrue);
await Future.delayed(Duration(milliseconds: 2));
});
test('cached online callback state is reapplied after peers merge', () {
final loader = AllPeersLoader();
loader.updateOnlineStateForTesting({
'onlines': '123456789',
'offlines': '',
});
final mergedPeers = [_peer(id: '123456789')];
loader.applyLastOnlineStateForTesting(mergedPeers);
expect(mergedPeers.single.online, isTrue);
});
}
-20
View File
@@ -1,20 +0,0 @@
import 'package:flutter_test/flutter_test.dart';
import 'cm_demo.dart' as cm_demo;
void main() {
test('connection manager demo clients match the current Client API', () {
expect(cm_demo.testClients, hasLength(4));
expect(cm_demo.testClients.map((client) => client.name), [
'UserAAAAAA',
'UserBBBBB',
'UserC',
'UserDDDDDDDDDDDd',
]);
expect(
cm_demo.testClients.every(
(client) => client.keyboard && !client.clipboard && !client.audio),
isTrue,
);
});
}
+2 -460
View File
@@ -1,4 +1,3 @@
import 'dart:async';
import 'dart:io';
import 'package:flutter/services.dart';
@@ -15,36 +14,14 @@ class _Cursor extends CursorModel {
_Cursor(FFI ffi) : super(WeakReference(ffi));
final core = <String, CursorShape>{};
final fetched = <String>[];
// While set, a fetch answers only when [answerFetches] is called.
bool holdFetches = false;
// While set, a fetch throws before it returns a future.
bool throwAtOnce = false;
final _held = <Completer<CursorShape?>, String>{};
@override
Future<CursorShape?> fetchCursorShape(String id) {
fetched.add(id);
if (throwAtOnce) throw StateError('no core');
if (!holdFetches) return Future.value(core[id]);
final answer = Completer<CursorShape?>();
_held[answer] = id;
return answer.future;
return Future.value(core[id]);
}
void answerFetches() {
final held = Map.of(_held);
_held.clear();
held.forEach((answer, id) => answer.complete(core[id]));
}
void failFetches() {
final held = Map.of(_held);
_held.clear();
held.forEach((answer, _) => answer.completeError(StateError('failed')));
}
bool showRemoteCursor = false;
@override
bool get showsRemoteCursor => showRemoteCursor;
bool get showsRemoteCursor => false;
}
String? _key(MouseCursor cursor) =>
@@ -181,28 +158,6 @@ void main() {
expect(registered.length, 100);
});
test(
'a raster made before is found again after the shape was switched away from',
() async {
final cursor = ffi.cursorModel;
await _feed(ffi, 'A', size: 32);
buildCursorOfCache(cursor, 1.0, cursor.cache);
await _settle();
final first = registered.single;
buildCursorOfCache(cursor, 0.5, cursor.cache);
await _settle();
await _feed(ffi, 'B');
buildCursorOfCache(cursor, 1.0, cursor.cache);
await _settle();
final count = registered.length;
_select(ffi, 'A'); // its pixels went; its cursors at both rasters stay
expect(_key(buildCursorOfCache(cursor, 1.0, cursor.cache)), first);
await _settle();
expect(ffi.cursor.fetched, isEmpty);
expect(registered.length, count);
});
test('a new raster of a shape without pixels keeps the cursor shown before',
() async {
final cursor = ffi.cursorModel;
@@ -220,134 +175,6 @@ void main() {
cursor.nativeKey(cursor.cache!, 0.5));
});
test('shapes that keep decoding late still get their native cursors',
() async {
final cursor = ffi.cursorModel;
await _feed(ffi, 'arrow');
buildCursorOfCache(cursor, 1.0, cursor.cache);
await _settle();
// A and B arrive, each decoding only after the peer moved on.
for (final (id, seed) in [('A', 1), ('B', 2)]) {
final pixels = _pixels(8, seed);
ffi.cursor.core[id] =
CursorShape(hotx: 0, hoty: 0, width: 8, height: 8, colors: pixels);
final decoding = ffi.ffiModel.handleCursorData(id, 0, 0, 8, 8, pixels);
_select(ffi, 'arrow');
await decoding;
}
// Each fetch answers only after the next switch.
ffi.cursor.holdFetches = true;
for (var i = 0; i < 6; i++) {
_select(ffi, i.isEven ? 'A' : 'B');
ffi.cursor.answerFetches();
await _settle();
buildCursorOfCache(cursor, 1.0, cursor.cache);
await _settle();
}
expect(registered.where((key) => key.contains('_A_')), isNotEmpty);
expect(registered.where((key) => key.contains('_B_')), isNotEmpty);
});
test('a zoom still gets native cursors for shapes that keep decoding late',
() async {
final cursor = ffi.cursorModel;
// An animation whose frames have native cursors at 1.0 only.
for (final (id, seed) in [('A', 1), ('B', 2)]) {
await _feed(ffi, id, size: 32, seed: seed);
buildCursorOfCache(cursor, 1.0, cursor.cache);
await _settle();
}
// At 0.5 each frame is fetched again, and each fetch answers after the next switch.
ffi.cursor.holdFetches = true;
for (var i = 0; i < 6; i++) {
_select(ffi, i.isEven ? 'A' : 'B');
ffi.cursor.answerFetches();
await _settle();
buildCursorOfCache(cursor, 0.5, cursor.cache);
await _settle();
}
expect(
registered
.where((key) => key.contains('_A_') && key.endsWith('_16_16')),
isNotEmpty);
expect(
registered
.where((key) => key.contains('_B_') && key.endsWith('_16_16')),
isNotEmpty);
});
test(
'a raster still missing keeps a late restore, whatever was shown meanwhile',
() async {
final cursor = ffi.cursorModel;
await _feed(ffi, 'A', size: 32);
buildCursorOfCache(cursor, 1.0, cursor.cache);
await _settle();
await _feed(ffi, 'B');
buildCursorOfCache(cursor, 1.0, cursor.cache);
await _settle();
_select(ffi, 'A');
ffi.cursor.holdFetches = true;
buildCursorOfCache(cursor, 0.5, cursor.cache); // no cursor at 0.5: fetched
buildCursorOfCache(cursor, 1.0, cursor.cache); // 1.0 has one meanwhile
_select(ffi, 'B');
ffi.cursor.answerFetches();
await _settle();
ffi.cursor.fetched.clear();
_select(ffi, 'A');
buildCursorOfCache(cursor, 0.5, cursor.cache);
await _settle();
expect(ffi.cursor.fetched, isEmpty,
reason: 'its pixels waited for the cursor at 0.5');
expect(
registered
.where((key) => key.contains('_A_') && key.endsWith('_16_16')),
isNotEmpty);
});
test('shapes waiting for a native cursor keep their pixels, within the limit',
() async {
const max = CursorModel.kRecentShapes;
for (var i = 0; i <= max + 1; i++) {
await _feed(ffi, '$i');
}
expect(ffi.cursorModel.cachedShape('0')!.hasPixels, isFalse,
reason: 'the one waiting longest is let go');
expect(ffi.cursorModel.cachedShape('1')!.hasPixels, isTrue);
expect(ffi.cursorModel.cachedShape('$max')!.hasPixels, isTrue);
});
test('two animated cursors and the everyday set keep their native cursors',
() async {
// Each frame is a shape of its own: 18 for the Windows busy cursor, 23 for
// KDE Breeze's wait and progress cursors on X11.
const frames = 23;
const statics = 12;
final cursor = ffi.cursorModel;
final shapes = [
for (var i = 0; i < statics; i++) 's$i',
for (var i = 0; i < frames; i++) 'wait$i',
for (var i = 0; i < frames; i++) 'progress$i',
];
for (var i = 0; i < shapes.length; i++) {
await _feed(ffi, shapes[i], seed: i);
buildCursorOfCache(cursor, 1.0, cursor.cache);
await _settle();
}
ffi.cursor.fetched.clear();
for (final id in shapes) {
_select(ffi, id);
buildCursorOfCache(cursor, 1.0, cursor.cache);
await _settle();
}
expect(ffi.cursor.fetched, isEmpty,
reason: 'every shape kept its native cursor');
expect(registered.length, shapes.length);
expect(deleted, isEmpty);
});
test('a shape painted again is decoded again, the last one shown meanwhile',
() async {
await _feed(ffi, '1', size: 16);
@@ -360,89 +187,6 @@ void main() {
expect(ffi.cursorModel.shapeIds, ['1']);
});
test('a shape the core gives but that does not decode is asked for once',
() async {
await _feed(ffi, '1');
await _feed(ffi, '2');
ffi.cursor.core['1'] = CursorShape(
hotx: 0, hoty: 0, width: 8, height: 8, colors: Uint8List(3));
_select(ffi, '1');
for (var i = 0; i < 5; i++) {
ffi.cursorModel.image;
await _settle();
}
expect(ffi.cursor.fetched, ['1']);
});
test('a shape switched away from while it decoded is asked for again',
() async {
await _feed(ffi, '1', size: 16);
await _feed(ffi, '2');
_select(ffi, '1');
ffi.cursorModel.image; // asks the core
// The core has answered and the shape is decoding when the peer moves on.
await Future<void>.delayed(Duration.zero);
_select(ffi, '2');
await _settle();
expect(ffi.cursorModel.cachedShape('1')!.hasPixels, isTrue,
reason:
'decoded after the peer moved on, it waits for its native cursor');
_select(ffi, '1');
ffi.cursorModel.image;
await _settle();
expect(ffi.cursor.fetched, ['1', '1']);
expect(ffi.cursorModel.image?.width, 16);
});
test('a shape decoded after the session was cleared is not kept', () async {
await _feed(ffi, '1', size: 16);
await _feed(ffi, '2');
_select(ffi, '1');
ffi.cursorModel.image; // asks the core
ffi.cursorModel.clear();
await _settle();
expect(ffi.cursorModel.shapeIds, isEmpty);
expect(ffi.cursorModel.cache, isNull);
});
test('a shape the core does not have is asked for once', () async {
await _feed(ffi, '1');
await _feed(ffi, '2');
ffi.cursor.core.remove('1');
_select(ffi, '1');
for (var i = 0; i < 5; i++) {
ffi.cursorModel.image;
await _settle();
}
expect(ffi.cursor.fetched, ['1']);
});
test('a shape the core lacks is remembered only while it is in use',
() async {
await _feed(ffi, '1');
for (var i = 0; i < 1000; i++) {
_select(ffi, 'missing$i');
ffi.cursorModel.image;
}
await _settle();
expect(ffi.cursor.fetched.length, 1000, reason: 'each is asked for once');
_select(ffi, 'missing0');
await _settle();
expect(ffi.cursor.fetched.length, 1001,
reason: 'nothing is kept for a shape no longer in use');
});
test('a shape the core lacks is asked for again after another was in use',
() async {
await _feed(ffi, '1');
_select(ffi, 'missing0');
await _settle();
_select(ffi, '1');
_select(ffi, 'missing0');
await _settle();
expect(ffi.cursor.fetched, ['missing0', 'missing0']);
});
test('a moved tab carries the id in use, and its window asks the core',
() async {
await _feed(ffi, '1', size: 16);
@@ -463,30 +207,6 @@ void main() {
expect(moved.cursorModel.image?.width, 16);
});
test('a shape keeps a native cursor for each raster it was shown at',
() async {
final cursor = ffi.cursorModel;
await _feed(ffi, '1', size: 32);
for (final scale in [1.0, 0.5, 1.0, 0.5]) {
buildCursorOfCache(cursor, scale, cursor.cache);
await _settle();
}
expect(registered.length, 2, reason: 'a raster returned to is reused');
expect(deleted, isEmpty);
expect(cursor.cachedKeys, registered.toSet());
});
test('a cleared session forgets the native cursors it deleted', () async {
final cursor = ffi.cursorModel;
await _feed(ffi, '1');
buildCursorOfCache(cursor, 1.0, cursor.cache);
await _settle();
cursor.clear();
await _settle();
expect(deleted, registered);
expect(cursor.cachedKeys, isEmpty);
});
test('a tab closing does not delete the cursors of another tab', () async {
final other = _FFI();
addTearDown(other.cursorModel.disposeImages);
@@ -502,182 +222,4 @@ void main() {
await _settle();
expect(other.cursorModel.cachedKeys.single, isNot(isIn(deleted)));
});
test('a shape given as a view into a larger buffer is read from the view',
() async {
final pixels = _pixels(8, 3);
final padded = Uint8List(16 + pixels.length)
..setRange(16, 16 + pixels.length, pixels);
await ffi.ffiModel
.handleCursorData('1', 0, 0, 8, 8, Uint8List.sublistView(padded, 16));
final p = ffi.cursorModel.cache!.image.getPixel(0, 0);
expect([p.r, p.g, p.b, p.a], [3, 4, 5, 6]);
});
test('a shape still decoding leaves the one shown before in place', () async {
final cursor = ffi.cursorModel;
await _feed(ffi, '1');
final shown = _key(buildCursorOfCache(cursor, 1.0, cursor.cache));
await _settle();
_select(ffi, '2'); // its shape has not decoded yet
expect(cursor.cache?.id, '1');
expect(_key(buildCursorOfCache(cursor, 1.0, cursor.cache)), shown);
expect(cursor.image, isNotNull);
await _feed(ffi, '2');
expect(cursor.cache?.id, '2');
});
for (final how in ['does not have', 'cannot decode']) {
test('a shape the core $how leaves the default cursor, not the one before',
() async {
final cursor = ffi.cursorModel;
await _feed(ffi, '1');
if (how == 'cannot decode') {
ffi.cursor.core['2'] = CursorShape(
hotx: 0, hoty: 0, width: 8, height: 8, colors: Uint8List(3));
}
_select(ffi, '2');
expect(cursor.cache?.id, '1', reason: 'kept while the shape may come');
var notified = 0;
cursor.addListener(() => notified++);
await _settle();
expect(cursor.cache, isNull,
reason: 'the desktop shows preDefaultCursor');
expect(cursor.image, isNull, reason: 'and so does a painted cursor');
expect(notified, greaterThan(0));
});
}
test('a shape sent that does not decode leaves the default cursor', () async {
final cursor = ffi.cursorModel;
await _feed(ffi, '1');
ffi.cursor.core['2'] = CursorShape(
hotx: 0, hoty: 0, width: 8, height: 8, colors: Uint8List(3));
await ffi.ffiModel.handleCursorData('2', 0, 0, 8, 8, Uint8List(3));
expect(cursor.cache, isNull);
expect(cursor.image, isNull);
_select(ffi, '2');
await _settle();
expect(ffi.cursor.fetched, isEmpty, reason: 'it is not asked for either');
});
test('a fetch failing after the session was cleared marks nothing in it',
() async {
final cursor = ffi.cursorModel;
ffi.cursor.holdFetches = true;
_select(ffi, '1'); // not decoded here yet, so it is asked for
cursor.clear();
ffi.cursor.failFetches();
await _settle();
ffi.cursor.holdFetches = false;
_select(ffi, '1'); // the same id, now in the new session
await _settle();
expect(ffi.cursor.fetched, ['1', '1']);
});
test('a fetch that throws at once tells the listeners after the build',
() async {
final cursor = ffi.cursorModel;
await _feed(ffi, '1');
ffi.cursor.throwAtOnce = true;
cursor.id = '2';
var notified = 0;
cursor.addListener(() => notified++);
cursor.restorePixels('2');
expect(notified, 0, reason: 'a build may be what asked');
await _settle();
expect(notified, greaterThan(0));
expect(cursor.cache, isNull);
});
test('a raster still being made falls back to a shape, not the forbidden one',
() async {
final cursor = ffi.cursorModel;
for (var i = 0; preForbiddenCursor.cache == null && i < 100; i++) {
await _settle();
}
expect(preForbiddenCursor.cache, isNotNull);
await _feed(ffi, '1', size: 32);
buildCursorOfCache(cursor, 1.0, cursor.cache);
await _settle();
await _feed(ffi, '2', size: 32);
final shown = _key(buildCursorOfCache(cursor, 1.0, cursor.cache));
await _settle();
buildCursorOfCache(cursor, 1.0, preForbiddenCursor.cache); // input disabled
_select(ffi, '1'); // its native cursor held its pixels, so they went
expect(_key(buildCursorOfCache(cursor, 0.5, cursor.cache)), shown);
});
group('a painted cursor', () {
void painted(String how) {
if (how == 'mobile') {
final was = isMobile;
isMobile = true;
addTearDown(() => isMobile = was);
} else {
ffi.cursor.showRemoteCursor = true;
}
}
for (final how in ['mobile', 'remote cursor shown']) {
test('keeps the images of two animations and the everyday set ($how)',
() async {
painted(how);
final cursor = ffi.cursorModel;
final shapes = [
for (var i = 0; i < 12; i++) 's$i',
for (var i = 0; i < 23; i++) 'wait$i',
for (var i = 0; i < 23; i++) 'progress$i',
];
for (var i = 0; i < shapes.length; i++) {
await _feed(ffi, shapes[i], seed: i);
}
for (final id in shapes) {
_select(ffi, id);
expect(cursor.shapeIds.last, id, reason: 'its image is at hand');
}
await _settle();
expect(ffi.cursor.fetched, isEmpty);
});
}
test('keeps the images used last, and decodes the others again', () async {
painted('mobile');
const max = CursorModel.kRecentShapes;
final cursor = ffi.cursorModel;
for (var i = 0; i <= max; i++) {
await _feed(ffi, '$i');
}
expect(cursor.shapeIds.length, max);
_select(ffi, '$max');
_select(ffi, '1');
await _settle();
expect(ffi.cursor.fetched, isEmpty, reason: 'shape 1 was used lately');
_select(ffi, '0');
expect(cursor.image, isNotNull, reason: 'shape 1 until 0 is back');
await _settle();
expect(ffi.cursor.fetched, ['0']);
expect(cursor.shapeIds.length, max);
});
test('keeps a shape that finished decoding after the peer moved on',
() async {
painted('mobile');
const max = CursorModel.kRecentShapes;
final cursor = ffi.cursorModel;
for (var i = 0; i <= max; i++) {
await _feed(ffi, '$i');
}
_select(ffi, '0');
cursor.image; // let go, so it is asked for
await Future<void>.delayed(Duration.zero);
_select(ffi, '1');
await _settle();
_select(ffi, '0');
cursor.image;
await _settle();
expect(ffi.cursor.fetched, ['0'], reason: 'the late one was kept');
expect(cursor.shapeIds.last, '0');
});
});
}
+8 -39
View File
@@ -108,17 +108,11 @@ void main() {
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, (1, 512)),
]) {
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);
@@ -132,15 +126,15 @@ void main() {
test('Windows peer cursor alpha survives resizing $pattern',
() => _checkWindowsPeerAlpha(pattern, registrations));
}
for (final style in [
kRemoteViewStyleOriginal,
kRemoteViewStyleAdaptive,
kRemoteViewStyleCustom
for (final (style, zoom) in [
(kRemoteViewStyleOriginal, false),
(kRemoteViewStyleAdaptive, false),
(kRemoteViewStyleAdaptive, true),
(kRemoteViewStyleCustom, false),
(kRemoteViewStyleCustom, true),
]) {
for (final zoom in [false, true]) {
testWidgets('$style zoom=$zoom follows the live DPR and peer scale',
(tester) => _checkView(tester, (style, zoom), registrations));
}
testWidgets('$style zoom=$zoom follows the live DPR and peer scale',
(tester) => _checkView(tester, (style, zoom), registrations));
}
}
@@ -241,31 +235,6 @@ void _expectSize(Map<dynamic, dynamic> args, (int, int) 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.nativeKey(cursor.cache, 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 = 512;
-72
View File
@@ -1,4 +1,3 @@
import 'dart:async';
import 'dart:convert';
import 'package:flutter_hbb/models/file_model.dart';
@@ -62,19 +61,6 @@ void main() {
expect(directory.path, '/fast');
});
test('a send failure fails and removes its registered task', () async {
final failure = StateError('send failed');
final fileFetcher = FileFetcher(
() => _sessionId,
readRemoteDirectory: (_, __, ___) => Future<void>.error(failure),
);
await expectLater(
fileFetcher.fetchDirectory('/failed', false, false),
throwsA(same(failure)),
);
expect(fileFetcher.hasPendingRemoteRead('/failed'), isFalse);
});
test('a resolved Home path completes the sole empty-path request', () async {
final sent = <_SentRead>[];
final fileFetcher = FileFetcher(
@@ -107,35 +93,6 @@ void main() {
expect(controller.directory.value.path, '/home/user');
});
test('an exact path response is not taken by a pending Home request',
() async {
final sent = <_SentRead>[];
final fileFetcher = FileFetcher(
() => _sessionId,
readRemoteDirectory: (_, path, includeHidden) async {
sent.add(_SentRead(path, includeHidden));
},
);
final home = fileFetcher.fetchDirectory('', false, false);
final regular = fileFetcher.fetchDirectory('/regular', false, false);
await Future<void>.delayed(Duration.zero);
var homeCompleted = false;
home.then<void>((_) => homeCompleted = true);
fileFetcher.tryCompleteTask(_directoryJson('/unmatched'), 'false');
await Future<void>.delayed(Duration.zero);
expect(homeCompleted, isFalse);
fileFetcher.tryCompleteTask(_directoryJson('/regular'), 'false');
expect((await regular).path, '/regular');
await Future<void>.delayed(Duration.zero);
expect(homeCompleted, isFalse);
fileFetcher.tryCompleteTask(_directoryJson('/home/user'), 'false');
expect((await home).path, '/home/user');
expect(sent.map((request) => request.path), ['', '/regular']);
});
test('a read error completes the sole pending request', () async {
final fileFetcher = FileFetcher(
() => _sessionId,
@@ -230,35 +187,6 @@ void main() {
expect((await replacement).path, '/same');
});
test('a late dispatch failure cannot remove a replacement task', () async {
final dispatches = <Completer<void>>[];
final fileFetcher = FileFetcher(
() => _sessionId,
readRemoteDirectory: (_, __, ___) {
final dispatch = Completer<void>();
dispatches.add(dispatch);
return dispatch.future;
},
);
final first = fileFetcher.fetchDirectory('/same', false, false);
await Future<void>.delayed(Duration.zero);
final firstError = expectLater(first, throwsA(isA<StateError>()));
fileFetcher.beginRemoteSession();
await firstError;
final replacement = fileFetcher.fetchDirectory('/same', false, false);
await Future<void>.delayed(Duration.zero);
expect(dispatches, hasLength(2));
dispatches.first.completeError(StateError('late dispatch failure'));
await Future<void>.delayed(Duration.zero);
expect(fileFetcher.hasPendingRemoteRead('/same'), isTrue);
fileFetcher.tryCompleteTask(_directoryJson('/same'), 'false');
expect((await replacement).path, '/same');
dispatches.last.complete();
await Future<void>.delayed(Duration.zero);
});
test('navigation ignores stale directory responses', () async {
final fileFetcher = FileFetcher(
() => _sessionId,
@@ -0,0 +1,99 @@
@TestOn('browser')
import 'dart:async';
import 'dart:js' as js;
import 'package:flutter/material.dart';
import 'package:flutter_hbb/common/widgets/remote_input.dart';
import 'package:flutter_hbb/mobile/widgets/floating_mouse_widgets.dart';
import 'package:flutter_hbb/models/input_model.dart';
import 'package:flutter_hbb/models/model.dart';
import 'package:flutter_test/flutter_test.dart';
class _Input extends Fake implements InputModel {
final events = <(String, MouseButtons)>[];
@override
Future<void> tapDown(MouseButtons button) async =>
events.add(('down', button));
@override
Future<void> tapUp(MouseButtons button) async => events.add(('up', button));
}
class _FFI extends Fake implements FFI {}
class _Cursor extends CursorModel {
_Cursor(FFI ffi) : super(WeakReference(ffi));
final syncs = <Completer<void>>[];
@override
Future<void> syncCursorPosition() {
final sync = Completer<void>();
syncs.add(sync);
return sync.future;
}
}
void main() {
setUp(() {
isSpecialHoldDragActive = false;
js.context['isMobile'] = js.allowInterop(() => true);
js.context['getByName'] =
js.allowInterop((String name, [String? key]) => '');
js.context['setByName'] = js.allowInterop((String name, dynamic value) {});
});
tearDown(() {
isSpecialHoldDragActive = false;
for (final name in ['isMobile', 'getByName', 'setByName']) {
js.context.deleteProperty(name);
}
});
for (final end in ['release', 'cancel', 'dispose']) {
testWidgets('pending hold cannot press after $end', (tester) async {
final cancel = end == 'cancel';
final ffi = _FFI();
final input = _Input();
final cursor = _Cursor(ffi);
final button = cancel ? MouseButtons.right : MouseButtons.left;
await tester.pumpWidget(MaterialApp(
home: Stack(children: [
FloatingLeftRightButton(
isLeft: !cancel, inputModel: input, cursorModel: cursor),
]),
));
await tester.pump();
final target = find.byType(FloatingLeftRightButton);
final first = await tester.startGesture(tester.getCenter(target));
await tester.pump(const Duration(milliseconds: 201));
expect(cursor.syncs, hasLength(1));
if (end == 'dispose') {
await tester.pumpWidget(const SizedBox());
cursor.syncs.single.complete();
await tester.pump(const Duration(milliseconds: 1));
expect(input.events, isEmpty);
return;
}
if (cancel) {
await first.cancel();
} else {
await first.up();
}
// A new press must not make the old synchronization valid again.
final second = await tester.startGesture(tester.getCenter(target));
await tester.pump(const Duration(milliseconds: 201));
cursor.syncs.first.complete();
await tester.pump();
expect(input.events, isEmpty);
cursor.syncs.last.complete();
await tester.pump();
expect(input.events, [('down', button)]);
await second.up();
expect(input.events, [('down', button), ('up', button)]);
await tester.pumpWidget(const SizedBox());
await tester.pump(const Duration(milliseconds: 1));
expect(input.events, [('down', button), ('up', button)]);
});
}
}
+1 -319
View File
@@ -4,19 +4,6 @@ import 'package:flutter_hbb/models/input_modifier_utils.dart';
void main() {
group('shouldReleaseStaleMobileShift', () {
test('does not release when cached shift is already false', () {
expect(
shouldReleaseStaleMobileShift(
isMobile: true,
cachedShiftPressed: false,
actualShiftPressed: false,
logicalKey: LogicalKeyboardKey.keyD,
hasTrackedShiftKeyDown: true,
),
isFalse,
);
});
test('releases one-shot mobile shift after a text key', () {
expect(
shouldReleaseStaleMobileShift(
@@ -30,20 +17,6 @@ void main() {
);
});
test('does not release manually toggled shift without tracked key down',
() {
expect(
shouldReleaseStaleMobileShift(
isMobile: true,
cachedShiftPressed: true,
actualShiftPressed: false,
logicalKey: LogicalKeyboardKey.keyD,
hasTrackedShiftKeyDown: false,
),
isFalse,
);
});
test('does not release when shift is still physically pressed', () {
expect(
shouldReleaseStaleMobileShift(
@@ -56,84 +29,9 @@ void main() {
isFalse,
);
});
test('does not release on non-mobile platforms', () {
expect(
shouldReleaseStaleMobileShift(
isMobile: false,
cachedShiftPressed: true,
actualShiftPressed: false,
logicalKey: LogicalKeyboardKey.keyD,
hasTrackedShiftKeyDown: true,
),
isFalse,
);
});
test('releases on enter key', () {
expect(
shouldReleaseStaleMobileShift(
isMobile: true,
cachedShiftPressed: true,
actualShiftPressed: false,
logicalKey: LogicalKeyboardKey.enter,
hasTrackedShiftKeyDown: true,
),
isTrue,
);
});
test('releases on arrow key', () {
expect(
shouldReleaseStaleMobileShift(
isMobile: true,
cachedShiftPressed: true,
actualShiftPressed: false,
logicalKey: LogicalKeyboardKey.arrowLeft,
hasTrackedShiftKeyDown: true,
),
isTrue,
);
});
test('does not release on modifier events', () {
expect(
shouldReleaseStaleMobileShift(
isMobile: true,
cachedShiftPressed: true,
actualShiftPressed: false,
logicalKey: LogicalKeyboardKey.shiftLeft,
hasTrackedShiftKeyDown: true,
),
isFalse,
);
});
test('does not release on shiftRight modifier events', () {
expect(
shouldReleaseStaleMobileShift(
isMobile: true,
cachedShiftPressed: true,
actualShiftPressed: false,
logicalKey: LogicalKeyboardKey.shiftRight,
hasTrackedShiftKeyDown: true,
),
isFalse,
);
});
});
group('shouldApplyTerminalInputModifiers', () {
test('accepts ordinary single-character keyboard input', () {
expect(shouldApplyTerminalInputModifiers('a'), isTrue);
expect(shouldApplyTerminalInputModifiers(' '), isTrue);
expect(shouldApplyTerminalInputModifiers('/'), isTrue);
});
test('accepts supplementary-plane single-character keyboard input', () {
expect(shouldApplyTerminalInputModifiers('😀'), isTrue);
});
test('rejects terminal control bytes and multi-character sequences', () {
for (final input in ['\x00', '\x03', '\t', '\n', '\r', '\x1B', '\x7F']) {
expect(
@@ -147,43 +45,6 @@ void main() {
});
group('applyTerminalInputModifiers', () {
test('keeps decomposed graphemes intact under Ctrl', () {
const decomposedEAcute = 'e\u0301';
expect(
applyTerminalInputModifiers(
decomposedEAcute,
ctrlLocked: true,
altLocked: false,
),
decomposedEAcute,
);
});
test('keeps non-ASCII graphemes intact under Ctrl', () {
for (final input in ['é', '😀']) {
expect(
applyTerminalInputModifiers(
input,
ctrlLocked: true,
altLocked: false,
),
input,
);
}
});
test('maps Ctrl underscore to unit separator', () {
expect(
applyTerminalInputModifiers(
'_',
ctrlLocked: true,
altLocked: false,
),
'\x1F',
);
});
test('maps the complete Ctrl symbol range', () {
const mappings = {
'[': '\x1B',
@@ -219,22 +80,6 @@ void main() {
});
});
group('terminalPastePayload', () {
test('wraps paste text when bracketed paste mode is active', () {
expect(
terminalPastePayload('d', bracketedPasteMode: true),
'\x1B[200~d\x1B[201~',
);
});
test('keeps a lone newline unchanged when bracketed paste is disabled', () {
expect(
terminalPastePayload('\n', bracketedPasteMode: false),
'\n',
);
});
});
group('prepareTerminalInputPayload', () {
test('normalizes a mobile keyboard Enter to carriage return', () {
expect(
@@ -278,26 +123,9 @@ void main() {
);
});
test('keeps large keyboard payloads unchanged when modifiers are inactive',
() {
final payload = 'd' * (1024 * 1024);
expect(
prepareTerminalInputPayload(
payload,
source: TerminalInputSource.keyboard,
isMobileOrWebMobile: false,
bracketedPasteMode: false,
ctrlLocked: false,
altLocked: false,
),
payload,
);
});
test('keeps decomposed graphemes intact with locked keyboard modifiers',
() {
const decomposedEAcute = 'e\u0301';
const decomposedEAcute = 'é';
expect(
prepareTerminalInputPayload(
@@ -312,20 +140,6 @@ void main() {
);
});
test('preserves a lone pasted newline when modifiers are locked', () {
expect(
prepareTerminalInputPayload(
'\n',
source: TerminalInputSource.paste,
isMobileOrWebMobile: true,
bracketedPasteMode: false,
ctrlLocked: true,
altLocked: true,
),
'\n',
);
});
test('wraps paste without applying locked modifiers', () {
expect(
prepareTerminalInputPayload(
@@ -373,25 +187,6 @@ void main() {
);
});
test(
'keeps default xterm paste behavior when virtual modifiers are inactive',
() {
expect(
shouldHandleTerminalPasteShortcut(
platform: TargetPlatform.windows,
logicalKey: LogicalKeyboardKey.keyV,
isKeyDown: true,
isKeyRepeat: false,
controlPressed: true,
metaPressed: false,
altPressed: false,
shiftPressed: false,
modifierLockActive: false,
),
isFalse,
);
});
test('handles Ctrl+V and Meta+V when a virtual modifier lock is active',
() {
expect(
@@ -423,95 +218,6 @@ void main() {
isTrue,
);
});
test('handles paste shortcut repeats while a virtual lock is active', () {
expect(
shouldHandleTerminalPasteShortcut(
platform: TargetPlatform.windows,
logicalKey: LogicalKeyboardKey.keyV,
isKeyDown: false,
isKeyRepeat: true,
controlPressed: true,
metaPressed: false,
altPressed: false,
shiftPressed: false,
modifierLockActive: true,
),
isTrue,
);
});
test('ignores key-up and unmodified V events', () {
expect(
shouldHandleTerminalPasteShortcut(
platform: TargetPlatform.windows,
logicalKey: LogicalKeyboardKey.keyV,
isKeyDown: false,
isKeyRepeat: false,
controlPressed: true,
metaPressed: false,
altPressed: false,
shiftPressed: false,
modifierLockActive: true,
),
isFalse,
);
expect(
shouldHandleTerminalPasteShortcut(
platform: TargetPlatform.windows,
logicalKey: LogicalKeyboardKey.keyV,
isKeyDown: true,
isKeyRepeat: false,
controlPressed: false,
metaPressed: false,
altPressed: false,
shiftPressed: false,
modifierLockActive: true,
),
isFalse,
);
});
test('ignores paste shortcuts with extra modifiers', () {
for (final state in [
(control: true, meta: false, alt: true, shift: false),
(control: true, meta: false, alt: false, shift: true),
(control: false, meta: true, alt: false, shift: true),
(control: true, meta: true, alt: false, shift: false),
]) {
expect(
shouldHandleTerminalPasteShortcut(
platform: TargetPlatform.windows,
logicalKey: LogicalKeyboardKey.keyV,
isKeyDown: true,
isKeyRepeat: false,
controlPressed: state.control,
metaPressed: state.meta,
altPressed: state.alt,
shiftPressed: state.shift,
modifierLockActive: true,
),
isFalse,
);
}
});
test('ignores non-V key events', () {
expect(
shouldHandleTerminalPasteShortcut(
platform: TargetPlatform.windows,
logicalKey: LogicalKeyboardKey.keyC,
isKeyDown: true,
isKeyRepeat: false,
controlPressed: true,
metaPressed: false,
altPressed: false,
shiftPressed: false,
modifierLockActive: true,
),
isFalse,
);
});
});
group('shouldClearTerminalModifiersWhenRow3Collapses', () {
@@ -526,29 +232,5 @@ void main() {
isTrue,
);
});
test('does not clear modifiers when row expands', () {
expect(
shouldClearTerminalModifiersWhenRow3Collapses(
wasExpanded: false,
willExpand: true,
ctrlLocked: true,
altLocked: true,
),
isFalse,
);
});
test('clears Alt state when expanded row is collapsed', () {
expect(
shouldClearTerminalModifiersWhenRow3Collapses(
wasExpanded: true,
willExpand: false,
ctrlLocked: false,
altLocked: true,
),
isTrue,
);
});
});
}
@@ -50,54 +50,20 @@ void main() {
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',
testWidgets('alternate screen reports trackpad after main-screen history',
(tester) async {
final view = await mount(tester);
terminal.write('\x1b[?1049h$_captureMouse');
await tester.pump();
final render = view.renderTerminal;
final start = render.localToGlobal(
final point = 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);
await scrollTrackpad(tester, point, render.lineHeight * 3);
expect(output, ['\x1b[<0;3;2M', '\x1b[<32;7;3M', '\x1b[<0;7;3m']);
expect(output, isNotEmpty);
expect(output, everyElement('\x1b[<64;3;2M'));
expect(view.widget.scrollController!.offset, 0);
expect(controller.selection, isNull);
expect(controller.suspendedPointerInputs, isFalse);
}, variant: TargetPlatformVariant.only(TargetPlatform.macOS));
testWidgets('leaving alternate screen restores local trackpad scrollback',
@@ -17,24 +17,5 @@ void main() {
['Ctrl', 'Alt', '-', 'PgUp', 'PgDn'],
);
});
test('keeps two trailing Row3 placeholders for row alignment', () {
expect(terminalKeyboardRow3TrailingPlaceholderCount, 2);
});
test('keeps every expanded row aligned at 348dp', () {
final rowWidths = [
terminalKeyboardRowWidth(terminalKeyboardRow1Keys.length),
terminalKeyboardRowWidth(terminalKeyboardRow2Keys.length + 1),
terminalKeyboardRowWidth(
terminalKeyboardRow3Keys.length +
terminalKeyboardRow3TrailingPlaceholderCount,
),
];
expect(terminalKeyboardKeyWidth, 48);
expect(terminalKeyboardKeySpacing, 2);
expect(rowWidths, everyElement(348));
});
});
}
@@ -1,5 +1,3 @@
import 'dart:async';
import 'package:flutter_hbb/models/model.dart';
import 'package:flutter_hbb/models/terminal_model.dart';
import 'package:flutter_test/flutter_test.dart';
@@ -14,42 +12,6 @@ class _FakeFFI implements FFI {
}
void main() {
test('ignores paste that completes after the terminal model is disposed',
() async {
final model = TerminalModel(_FakeFFI());
final delayedClipboardText = Completer<String>();
// This mirrors Ctrl/Cmd+V: clipboard access starts first, then the page and
// model are disposed before the asynchronous read supplies its text.
final paste = delayedClipboardText.future.then(model.pasteText);
model.dispose();
delayedClipboardText.complete('late clipboard text');
await paste;
expect(model.debugBufferedInputCount, 0);
});
test('ignores terminal text input after the terminal model is disposed', () {
final model = TerminalModel(_FakeFFI());
var checkedCtrlLock = false;
var clearedCtrlLock = false;
model.isCtrlLocked = () {
checkedCtrlLock = true;
return true;
};
model.clearCtrlLock = () {
clearedCtrlLock = true;
};
model.dispose();
model.terminal.textInput('d');
expect(checkedCtrlLock, isFalse);
expect(clearedCtrlLock, isFalse);
expect(model.debugBufferedInputCount, 0);
});
test('builds its terminal with the wheel button fix', () {
final model = TerminalModel(_FakeFFI());
addTearDown(model.dispose);
+1 -95
View File
@@ -71,10 +71,9 @@ void main() {
String? report(
TerminalMouseButton button, [
TerminalMouseButtonState state = TerminalMouseButtonState.down,
CellOffset position = const CellOffset(10, 5),
]) {
output.clear();
terminal.mouseInput(button, state, position);
terminal.mouseInput(button, state, const CellOffset(10, 5));
return output.isEmpty ? null : output.single;
}
@@ -102,40 +101,6 @@ void main() {
);
});
test('reports utf-encoding wheel buttons beyond the normal-mode range', () {
terminal.write('\x1b[?1000h\x1b[?1005h');
expect(
report(
TerminalMouseButton.wheelDown,
TerminalMouseButtonState.down,
const CellOffset(400, 300),
),
'\x1b[M${String.fromCharCode(32 + 65)}'
'${String.fromCharCode(32 + 401)}${String.fromCharCode(32 + 301)}',
);
});
test('reports urxvt-encoding wheel buttons shifted by 32', () {
terminal.write('\x1b[?1000h\x1b[?1015h');
expect(report(TerminalMouseButton.wheelUp), '\x1b[96;11;6M');
expect(report(TerminalMouseButton.wheelDown), '\x1b[97;11;6M');
});
test('sends a null byte for coordinates past the encoding limit', () {
terminal.write('\x1b[?1000h');
expect(
report(
TerminalMouseButton.wheelUp,
TerminalMouseButtonState.down,
const CellOffset(300, 300),
),
'\x1b[M${String.fromCharCode(32 + 64)}\x00\x00',
);
});
test('leaves non-wheel buttons to the upstream handler', () {
terminal.write('\x1b[?1000h\x1b[?1006h');
@@ -147,27 +112,6 @@ void main() {
);
});
test('stays silent when the peer has not enabled mouse reporting', () {
expect(report(TerminalMouseButton.wheelDown), isNull);
expect(report(TerminalMouseButton.left), isNull);
});
test('stays silent for the wheel in click-only mode', () {
terminal.write('\x1b[?9h\x1b[?1006h');
expect(report(TerminalMouseButton.wheelDown), isNull);
expect(report(TerminalMouseButton.left), '\x1b[<0;11;6M');
});
test('does not report wheel button releases', () {
terminal.write('\x1b[?1000h\x1b[?1006h');
expect(
report(TerminalMouseButton.wheelDown, TerminalMouseButtonState.up),
isNull,
);
});
testWidgets('dragging below scrolls and extends selection', (tester) async {
final controller = TerminalController();
_writeLines(terminal, 80);
@@ -258,42 +202,4 @@ void main() {
expect(output.last, '\x1b[<0;${endCell.x + 1};${endCell.y + 1}m');
expect(controller.suspendedPointerInputs, isFalse);
});
testWidgets('tmux drag stays suppressed after mouse mode is disabled',
(tester) async {
final controller = TerminalController();
terminal.write('\x1b[?1049h\x1b[?1002h\x1b[?1006hword');
await tester.pumpWidget(_terminalHarness(terminal, controller));
final renderTerminal = tester
.state<TerminalViewState>(find.byType(TerminalView))
.renderTerminal;
final mouse = await tester.createGesture(kind: PointerDeviceKind.mouse);
final start = renderTerminal.localToGlobal(const Offset(40, 40));
final end = renderTerminal.localToGlobal(const Offset(240, 80));
await mouse.down(start);
output.clear();
terminal.write('\x1b[?1002l');
await mouse.moveTo(end);
expect(output, isEmpty);
expect(controller.selection, isNull);
expect(controller.suspendedPointerInputs, isTrue);
terminal.write('\x1b[?1002h');
await mouse.moveTo(start);
expect(output, isEmpty);
expect(controller.selection, isNull);
await mouse.up();
expect(output, isEmpty);
expect(controller.suspendedPointerInputs, isFalse);
await mouse.down(start);
output.clear();
terminal.write('\x1b[?1002l');
await mouse.up();
await tester.pump(kDoubleTapTimeout);
expect(output, isEmpty);
expect(controller.selection, isNull);
expect(controller.suspendedPointerInputs, isFalse);
});
}
+2
View File
@@ -1030,5 +1030,7 @@ message Message {
TerminalAction terminal_action = 31;
TerminalResponse terminal_response = 32;
PortForwardChannel port_forward_channel = 33;
// Auto Login: the peer types the password only if it is at its logon or lock screen.
OSLogin os_login = 34;
}
}
-62
View File
@@ -1677,15 +1677,6 @@ mod tests {
assert_err_contains(err, "empty file name");
}
#[test]
fn set_files_rejects_null_byte_name() {
let mut job = new_validation_job(103);
let err = job
.set_files(vec![new_file_entry("bad\0name.txt")])
.expect_err("null byte in file name must be rejected");
assert_err_contains(err, "null bytes");
}
#[test]
fn set_files_rejects_mixed_entries_when_one_is_traversal() {
let mut job = new_validation_job(104);
@@ -1708,39 +1699,6 @@ mod tests {
assert_err_contains(err, "absolute path");
}
#[cfg(not(windows))]
#[test]
fn set_files_allows_backslash_prefixed_name_on_unix() {
let mut job = new_validation_job(105);
assert!(job
.set_files(vec![new_file_entry("\\\\server\\share\\payload.txt")])
.is_ok());
}
#[test]
fn remove_file_rejects_empty_path() {
let err = remove_file("").expect_err("empty file path must be rejected");
assert_err_contains(err, "cannot be empty");
}
#[test]
fn remove_file_rejects_null_byte_path() {
let err = remove_file("bad\0path").expect_err("null byte path must be rejected");
assert_err_contains(err, "null bytes");
}
#[test]
fn create_dir_rejects_empty_path() {
let err = create_dir("").expect_err("empty directory path must be rejected");
assert_err_contains(err, "cannot be empty");
}
#[test]
fn create_dir_rejects_null_byte_path() {
let err = create_dir("bad\0path").expect_err("null byte path must be rejected");
assert_err_contains(err, "null bytes");
}
#[test]
fn rename_file_rejects_invalid_new_name() {
let tmp_root = TestTempDir::new("rustdesk_rename_invalid");
@@ -1790,24 +1748,4 @@ mod tests {
assert!(!src.exists());
assert!(dst.exists());
}
#[cfg(windows)]
#[test]
fn set_files_rejects_windows_drive_absolute_path() {
let mut job = new_validation_job(106);
let err = job
.set_files(vec![new_file_entry("C:\\Windows\\Temp\\payload.txt")])
.expect_err("drive-letter absolute path must be rejected");
assert_err_contains(err, "absolute path");
}
#[cfg(windows)]
#[test]
fn set_files_rejects_windows_verbatim_drive_absolute_path() {
let mut job = new_validation_job(1061);
let err = job
.set_files(vec![new_file_entry(r"\\?\C:\Windows\Temp\x.txt")])
.expect_err("verbatim drive absolute path must be rejected");
assert_err_contains(err, "absolute path");
}
}
-56
View File
@@ -515,48 +515,6 @@ pub fn get_home_dir_trusted() -> Option<PathBuf> {
mod tests {
use super::*;
#[test]
fn test_transform_degrees_maps_all_eight_variants() {
use sctk::reexports::client::protocol::wl_output::Transform;
// Flipped variants report their rotation: the frame still needs that turn to read
// upright, and the mirror half has no producer among desktop compositors to test.
for (t, deg) in [
(Transform::Normal, 0),
(Transform::_90, 90),
(Transform::_180, 180),
(Transform::_270, 270),
(Transform::Flipped, 0),
(Transform::Flipped90, 90),
(Transform::Flipped180, 180),
(Transform::Flipped270, 270),
] {
assert_eq!(transform_degrees(t), deg, "{t:?}");
}
}
#[test]
fn test_display_info_without_transform_defaults_to_zero() {
// A snapshot serialized by an older probe child carries no transform field; it must
// deserialize with 0 rather than fail, or a greeter-side child update becomes a
// lockstep upgrade.
let old = r#"{"name":"HDMI-1","x":0,"y":0,"width":1920,"height":1080,"logical_size":null,"refresh_rate":60}"#;
let info: WaylandDisplayInfo = serde_json::from_str(old).unwrap();
assert_eq!(info.transform, 0);
let roundtrip: WaylandDisplayInfo =
serde_json::from_str(&serde_json::to_string(&info).unwrap()).unwrap();
assert_eq!(roundtrip.transform, 0);
}
#[test]
fn test_run_cmds_trim_newline() {
assert_eq!(run_cmds_trim_newline("echo -n 123").unwrap(), "123");
assert_eq!(run_cmds_trim_newline("echo 123").unwrap(), "123");
assert_eq!(
run_cmds_trim_newline("whoami").unwrap() + "\n",
run_cmds("whoami").unwrap()
);
}
/// Test get_home_dir_trusted: returns valid path and ignores HOME env var
#[test]
fn test_get_home_dir_trusted() {
@@ -584,20 +542,6 @@ mod tests {
}
}
/// Test shell_quote with normal strings
#[test]
fn test_shell_quote_normal() {
assert_eq!(shell_quote("hello"), "'hello'");
assert_eq!(shell_quote("/home/user"), "'/home/user'");
}
/// Test shell_quote with spaces
#[test]
fn test_shell_quote_spaces() {
assert_eq!(shell_quote("/home/my user/file"), "'/home/my user/file'");
assert_eq!(shell_quote("path with spaces"), "'path with spaces'");
}
/// Test shell_quote with single quotes (the tricky case)
#[test]
fn test_shell_quote_single_quotes() {
-8
View File
@@ -288,11 +288,3 @@ fn send_data_to_all(data: ClipboardFile) {
allow_err!(msg_channel.sender.send(data.clone()));
}
}
#[cfg(test)]
mod tests {
// #[test]
// fn test_cliprdr_run() {
// super::cliprdr_run();
// }
}
@@ -244,8 +244,6 @@ mod tests {
const ATTRIBUTES_OFFSET: usize = PDU_HEADER_SIZE + 36;
const LAST_WRITE_TIME_OFFSET: usize = PDU_HEADER_SIZE + 56;
const NAME_OFFSET: usize = PDU_HEADER_SIZE + 72;
const FILE_NAME_CODE_UNITS: usize = 260;
const INVALID_UTF16_UNIT: u16 = 0xdc00;
const FILE_ATTRIBUTE_NORMAL: u32 = 0x80;
fn descriptor_pdu(name: &str) -> Vec<u8> {
@@ -291,18 +289,6 @@ mod tests {
assert_eq!(files[0].name, PathBuf::from("folder/nested/file.txt"));
}
#[test]
fn ignores_data_after_null_terminator() {
let name = "file.txt";
let mut pdu = descriptor_pdu(name);
let padding_offset = NAME_OFFSET + (name.encode_utf16().count() + 1) * size_of::<u16>();
pdu[padding_offset..padding_offset + size_of::<u16>()]
.copy_from_slice(&INVALID_UTF16_UNIT.to_le_bytes());
let files = FileDescription::parse_file_descriptors(pdu, 0).unwrap();
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.
@@ -319,15 +305,6 @@ mod tests {
assert_eq!(files[0].clip_data_id, id);
}
#[test]
fn rejects_non_terminated_file_name() {
let name = "a".repeat(FILE_NAME_CODE_UNITS);
assert!(matches!(
parse_name(&name),
Err(CliprdrError::InvalidRequest { .. })
));
}
fn parse_perm(attributes: u32) -> u16 {
let mut pdu = descriptor_pdu("folder");
pdu[ATTRIBUTES_OFFSET..ATTRIBUTES_OFFSET + size_of::<u32>()]
@@ -966,35 +966,6 @@ mod fuse_test {
}
}
fn build_single_file(prefix: &str) {
let raw_name = "simple_test_file.txt";
let f_name = if prefix == "" {
raw_name.to_string()
} else {
prefix.to_string() + "/" + raw_name
};
let desc = desc_gen(&f_name, FileType::File);
let tree = FuseNode::build_tree(vec![desc]).unwrap();
assert_eq!(tree.len(), 2);
assert_eq!(tree[0].name, "/");
assert_eq!(tree[0].children, vec![2]);
assert_eq!(tree[1].name, raw_name);
assert_eq!(tree[1].index, 0);
assert_eq!(tree[1].attributes.kind, FileType::File);
}
#[test]
fn test_parse_single() {
build_single_file("");
build_single_file("/");
build_single_file("test");
build_single_file("/test");
build_single_file("🗂");
build_single_file("/🗂");
}
#[test]
fn test_parse_tree() {
build_tree("");
+1 -41
View File
@@ -322,7 +322,7 @@ pub(super) fn construct_file_list(paths: &[PathBuf]) -> Result<Vec<LocalFile>, C
mod file_list_test {
use std::{
path::{Path, PathBuf},
sync::atomic::{AtomicU64, Ordering},
sync::atomic::AtomicU64,
time::{Duration, SystemTime},
};
@@ -466,32 +466,6 @@ mod file_list_test {
Ok(())
}
#[test]
fn read_exact_at_reopens_after_read_failure() -> Result<(), Box<dyn std::error::Error>> {
let file_path = std::env::temp_dir().join(format!(
"rustdesk-clipboard-local-file-{}",
std::process::id()
));
std::fs::write(&file_path, b"")?;
let mut file = LocalFile::try_open(&std::env::temp_dir(), &file_path)?;
file.size = 1;
let mut buf = [0u8; 1];
assert!(file.read_exact_at(&mut buf, 0).is_err());
assert!(file.handle.is_none());
assert_eq!(file.offset.load(Ordering::Relaxed), 0);
std::fs::write(&file_path, [42u8])?;
file.read_exact_at(&mut buf, 0)?;
assert_eq!(buf, [42u8]);
assert!(file.handle.is_none());
std::fs::remove_file(file_path)?;
Ok(())
}
const LAST_WRITE_TIME_OFFSET: usize = 56;
fn file_with_last_write_time(last_write_time: SystemTime) -> LocalFile {
@@ -519,18 +493,4 @@ mod file_list_test {
assert_eq!(encoded_last_write_time(time)?, 116_444_736_000_000_000);
Ok(())
}
#[test]
fn last_write_time_round_trips() -> Result<(), CliprdrError> {
let file = file_with_last_write_time(
SystemTime::UNIX_EPOCH + Duration::new(1_700_000_000, 123_456_700),
);
let mut pdu = BytesMut::with_capacity(4 + FILE_DESCRIPTOR_SIZE);
pdu.put_u32_le(1);
pdu.put(file.as_bin()?.as_slice());
let parsed = FileDescription::parse_file_descriptors(pdu.to_vec(), 0)?;
assert_eq!(parsed[0].last_modified, file.last_write_time);
Ok(())
}
}
@@ -809,18 +809,6 @@ mod tests {
assert!(!Path::new(&task.progress.download_file_path).exists());
}
#[test]
fn finder_progress_rejects_unrepresentable_byte_count() {
let (_temp, target, _) = test_directories();
let file = file_description("large.bin", FileType::File, i64::MAX as u64 + 1);
let mut task = paste_task_handle(target.clone(), vec![file]);
let error = task.update_next(0).expect_err("byte count must not wrap");
assert!(matches!(&error, CliprdrError::InvalidRequest { .. }));
task.on_error(error);
assert!(task.progress.finder_progress.is_none());
assert!(std::fs::read_dir(target).unwrap().next().is_none());
}
#[test]
fn validates_all_paths_before_creating_files() {
let (_temp, target, outside) = test_directories();
@@ -866,18 +854,4 @@ mod tests {
assert!(!download_path.exists());
assert!(!outside.join("file.txt").exists());
}
#[test]
fn rejects_symlink_component_when_creating_directory() {
let (_temp, target, outside) = test_directories();
symlink(&outside, target.join("link")).unwrap();
let directory = file_description("link/escaped", FileType::Directory, 0);
let mut task = paste_task_handle(target, vec![directory]);
assert!(matches!(
task.update_next(0),
Err(CliprdrError::InvalidRequest { .. })
));
assert!(!outside.join("escaped").exists());
}
}
@@ -430,31 +430,3 @@ pub fn create_pasteboard_context() -> ResultType<Box<PasteboardContext>> {
context.init();
Ok(context)
}
#[cfg(test)]
mod tests {
#[test]
fn test_temp_files_count() {
let mut c = super::PasteboardContext::temp_files_count();
let mut created_files = vec![];
for _ in 0..10 {
let path = format!(
"/tmp/{}{}",
super::TEMP_FILE_PREFIX,
uuid::Uuid::new_v4().to_string()
);
if std::fs::File::create(&path).is_ok() {
created_files.push(path);
c += 1;
}
}
assert_eq!(c, super::PasteboardContext::temp_files_count());
// Clean up the created files.
for file in created_files {
std::fs::remove_file(&file).ok();
}
}
}
@@ -523,48 +523,6 @@ mod sig_test {
}
}
#[test]
fn fingerprint_missing_path_is_default() {
let tmp = TmpDir::new("missing");
let missing = path_str(&tmp.join("does_not_exist.bin"));
let sigs = fingerprint(&[missing]);
assert_eq!(sigs.len(), 1);
// A path that can't be stat'd -> default sig, which forces a rebuild.
assert_eq!(sigs[0], FileSig::default());
assert_eq!(sigs[0].mtime, None);
}
#[test]
fn fingerprint_detects_inplace_edit() {
let tmp = TmpDir::new("edit");
let file = tmp.join("a.bin");
fs::write(&file, b"small").unwrap();
let p = path_str(&file);
let before = fingerprint(&[p.clone()]);
// Same content, same path: fingerprint must be stable.
let again = fingerprint(&[p.clone()]);
assert_eq!(before, again);
assert_eq!(before[0].size, 5);
assert!(!before[0].is_dir);
// Edit in place so the file grows.
fs::write(&file, b"much larger contents than before").unwrap();
let after = fingerprint(&[p]);
assert_ne!(before, after);
assert!(after[0].size > before[0].size);
}
#[test]
fn fingerprint_flags_directory() {
let tmp = TmpDir::new("dir");
let sub = tmp.join("subdir");
fs::create_dir_all(&sub).unwrap();
let sigs = fingerprint(&[path_str(&sub)]);
assert_eq!(sigs.len(), 1);
assert!(sigs[0].is_dir);
}
#[test]
fn recopy_after_edit_refreshes_cached_size() {
let tmp = TmpDir::new("recopy");
@@ -597,37 +555,6 @@ 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");
@@ -756,172 +683,6 @@ mod sig_test {
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();
}
fn list_files(selection: &[&PathBuf]) -> ClipFiles {
let files: Vec<String> = selection.iter().map(|p| path_str(p)).collect();
let mut clip = ClipFiles::default();
@@ -975,23 +736,6 @@ mod sig_test {
assert_only_its_own_requests_fail(&mut clip, &second);
}
#[test]
fn an_unreadable_next_file_fails_only_its_own_requests() {
use std::os::unix::fs::PermissionsExt;
let tmp = TmpDir::new("next_unreadable");
let (first, second) = (tmp.join("first.bin"), tmp.join("second.bin"));
fs::write(&first, b"AAAAAAAA").unwrap();
fs::write(&second, b"BBBBBBBB").unwrap();
let mut clip = list_files(&[&first, &second]);
fs::set_permissions(&second, fs::Permissions::from_mode(0o000)).unwrap();
// Root opens it regardless of its mode.
if fs::File::open(&second).is_ok() {
return;
}
assert_only_its_own_requests_fail(&mut clip, &second);
}
#[test]
fn the_next_file_is_preloaded_past_a_directory() {
let tmp = TmpDir::new("next_preloaded");
-36
View File
@@ -146,39 +146,3 @@ fn tokenize(input: &str) -> Result<Vec<Token>, ParseError> {
Ok(tokens)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn success() {
assert_eq!(
tokenize("{{Hello World!}} {+CTRL}hi{-CTRL}"),
Ok(vec![
Token::Sequence("{Hello World!} ".into()),
Token::KeyDown(Key::Control),
Token::Sequence("hi".into()),
Token::KeyUp(Key::Control)
])
);
}
#[test]
fn unexpected_open() {
assert_eq!(tokenize("{hello{}world}"), Err(ParseError::UnexpectedOpen));
}
#[test]
fn unmatched_open() {
assert_eq!(
tokenize("{this is going to fail"),
Err(ParseError::UnmatchedOpen)
);
}
#[test]
fn unmatched_close() {
assert_eq!(
tokenize("{+CTRL}{{this}} is going to fail}"),
Err(ParseError::UnmatchedClose)
);
}
}
-25
View File
@@ -525,28 +525,3 @@ impl fmt::Debug for Enigo {
write!(f, "Enigo")
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_get_key_state() {
let mut enigo = Enigo::new();
let keys = [Key::CapsLock, Key::NumLock];
for k in keys.iter() {
enigo.key_click(k.clone());
let a = enigo.get_key_state(k.clone());
enigo.key_click(k.clone());
let b = enigo.get_key_state(k.clone());
assert!(a != b);
}
let keys = [Key::Control, Key::Alt, Key::Shift];
for k in keys.iter() {
enigo.key_down(k.clone()).ok();
let a = enigo.get_key_state(k.clone());
enigo.key_up(k.clone());
let b = enigo.get_key_state(k.clone());
assert!(a != b);
}
}
}
-7
View File
@@ -391,13 +391,6 @@ fn convert_to_tfc_key(key: Key) -> Option<TFC_Key> {
Some(key)
}
#[test]
fn test_key_seq() {
// Get 6^ in French.
let mut en = Enigo::new();
en.key_sequence("^^");
}
/// Both directions: the failure is silent, so a one-directional test passes against the bug.
#[test]
fn test_custom_mouse_dispatch_follows_is_x11() {
+55
View File
@@ -36,6 +36,7 @@ const kUCKeyActionDisplay: u16 = 3;
#[allow(non_upper_case_globals)]
const kUCKeyTranslateDeadKeysBit: OptionBits = 1 << 31;
const BUF_LEN: usize = 4;
const KEYBOARD_ERROR_LOG_INTERVAL: std::time::Duration = std::time::Duration::from_secs(5);
const MOUSE_EVENT_BUTTON_NUMBER_BACK: i64 = 3;
const MOUSE_EVENT_BUTTON_NUMBER_FORWARD: i64 = 4;
@@ -428,7 +429,19 @@ impl KeyboardControllable for Enigo {
if let Ok(event) = CGEvent::new_keyboard_event(src.clone(), 0, true) {
event.set_string(cluster);
self.post(event, None);
} else {
hbb_common::throttled_log!(
KEYBOARD_ERROR_LOG_INTERVAL,
error,
"Failed to inject macOS Enigo key-sequence: could not create keyboard event"
);
}
} else {
hbb_common::throttled_log!(
KEYBOARD_ERROR_LOG_INTERVAL,
error,
"Failed to inject macOS Enigo key-sequence: event source is not initialized"
);
}
}
}
@@ -436,17 +449,40 @@ impl KeyboardControllable for Enigo {
fn key_click(&mut self, key: Key) {
let keycode = self.key_to_keycode(key);
if keycode == u16::MAX {
hbb_common::throttled_log!(
KEYBOARD_ERROR_LOG_INTERVAL,
error,
"Failed to inject macOS Enigo key-click: keycode mapping is unavailable"
);
return;
}
if let Some(src) = self.event_source.as_ref() {
if let Ok(event) = CGEvent::new_keyboard_event(src.clone(), keycode, true) {
self.post(event, Some(keycode));
} else {
hbb_common::throttled_log!(
KEYBOARD_ERROR_LOG_INTERVAL,
error,
"Failed to inject macOS Enigo key-down in key-click: could not create keyboard event"
);
}
if let Ok(event) = CGEvent::new_keyboard_event(src.clone(), keycode, false) {
self.post(event, Some(keycode));
} else {
hbb_common::throttled_log!(
KEYBOARD_ERROR_LOG_INTERVAL,
error,
"Failed to inject macOS Enigo key-up in key-click: could not create keyboard event"
);
}
} else {
hbb_common::throttled_log!(
KEYBOARD_ERROR_LOG_INTERVAL,
error,
"Failed to inject macOS Enigo key-click: event source is not initialized"
);
}
}
@@ -465,10 +501,29 @@ impl KeyboardControllable for Enigo {
fn key_up(&mut self, key: Key) {
let code = self.key_to_keycode(key);
if code == u16::MAX {
hbb_common::throttled_log!(
KEYBOARD_ERROR_LOG_INTERVAL,
error,
"Cannot map macOS Enigo key-up to a keycode"
);
}
if let Some(src) = self.event_source.as_ref() {
if let Ok(event) = CGEvent::new_keyboard_event(src.clone(), code, false) {
self.post(event, Some(code));
} else {
hbb_common::throttled_log!(
KEYBOARD_ERROR_LOG_INTERVAL,
error,
"Failed to inject macOS Enigo key-up: could not create keyboard event"
);
}
} else {
hbb_common::throttled_log!(
KEYBOARD_ERROR_LOG_INTERVAL,
error,
"Failed to inject macOS Enigo key-up: event source is not initialized"
);
}
}
+2 -2
View File
@@ -1,6 +1,6 @@
[package]
name = "rustdesk-portable-packer"
version = "1.5.0"
version = "1.5.1"
edition = "2021"
description = "RustDesk Remote Desktop"
@@ -20,6 +20,7 @@ windows = { version = "0.61", features = [
"Wdk_System",
"Wdk_System_SystemServices",
"Win32",
"Win32_Storage_FileSystem",
"Win32_System",
"Win32_System_SystemInformation",
] }
@@ -36,4 +37,3 @@ FileDescription = "RustDesk Remote Desktop"
winres = "0.1"
winapi = { version = "0.3", features = [ "winnt", "pdh", "synchapi" ] }
-50
View File
@@ -279,26 +279,6 @@ mod tests {
.find(|file| normalize_path(&file.path) == normalize_path(path))
}
#[test]
fn parses_the_generate_py_layout() {
let (files, exe) = parse(blob(
&[("./rustdesk.exe", b"app"), ("./custom.txt", b"cfg")],
"./rustdesk.exe",
))
.unwrap();
assert_eq!(exe, "./rustdesk.exe");
assert_eq!(files.len(), 2);
assert_eq!(entry(&files, "./custom.txt").unwrap().raw, b"cfg");
}
#[test]
fn rejects_malformed_blobs() {
assert!(parse(b"".as_slice()).is_none());
assert!(parse(b"notrustd".as_slice()).is_none());
// Truncated mid-record rather than panicking on a slice out of range.
assert!(parse(b"rustdesk\x00\x00\x00\x40partial".as_slice()).is_none());
}
#[test]
fn distinguishes_an_absent_package_from_a_malformed_one() {
assert!(parse_package_blob(None).unwrap().0.is_empty());
@@ -372,34 +352,4 @@ mod tests {
);
assert_eq!(entry(&files, "./librustdesk.dll").unwrap().raw, b"core");
}
#[test]
fn package_paths_are_recorded_for_the_dropped_file_sweep() {
let package = parse(blob(
&[("./custom.txt", b"cfg"), ("./data/logo.png", b"img")],
"./acme.exe",
))
.unwrap();
let mut paths: Vec<String> = package.0.iter().map(|f| f.path.clone()).collect();
paths.sort();
assert_eq!(paths, vec!["./custom.txt", "./data/logo.png"]);
// Merging must not disturb them: the generic payload contributes none.
let embedded = parse(blob(&[("./librustdesk.dll", b"core")], "./rustdesk.exe")).unwrap();
let (files, _) = merge(embedded, package);
assert!(entry(&files, "./data/logo.png").is_some());
}
#[test]
fn matches_paths_across_separator_styles() {
// generate.py emits backslashes when it runs on Windows.
let embedded = parse(blob(&[(".\\rustdesk.exe", b"app")], ".\\rustdesk.exe")).unwrap();
let package = parse(blob(&[("./custom.txt", b"cfg")], "./acme.exe")).unwrap();
let (files, exe) = merge(embedded, package);
assert_eq!(exe, "./acme.exe");
assert!(entry(&files, "./acme.exe").is_some());
assert!(entry(&files, ".\\rustdesk.exe").is_none());
}
}
+36
View File
@@ -19,6 +19,8 @@ const APP_METADATA_CONFIG: &str = "meta.toml";
const META_LINE_PREFIX_TIMESTAMP: &str = "timestamp = ";
const META_LINE_PREFIX_FILE: &str = "file = ";
const APP_PREFIX: &str = "rustdesk";
#[cfg(windows)]
const VERIFIED_UPDATE_FILE_PREFIX: &str = "rustdesk-verified-";
const APPNAME_RUNTIME_ENV_KEY: &str = "RUSTDESK_APPNAME";
#[cfg(windows)]
const SET_FOREGROUND_WINDOW_ENV_KEY: &str = "SET_FOREGROUND_WINDOW";
@@ -287,6 +289,13 @@ fn main() -> Result<(), String> {
#[cfg(not(windows))]
let quick_support = false;
#[cfg(windows)]
if args.first().is_some_and(|arg| arg == "--update") {
if let Err(err) = win::schedule_verified_update_cleanup() {
eprintln!("Failed to schedule verified update file cleanup: {}", err);
}
}
let mut ui = false;
let reader = BinaryReader::new()?;
if let Some(exe) = setup(
@@ -314,6 +323,33 @@ mod win {
pub const RUNTIME_BROKER_EXE: &'static str = "C:\\Windows\\System32\\RuntimeBroker.exe";
pub const WIN_TOPMOST_INJECTED_PROCESS_EXE: &'static str = "RuntimeBroker_rustdesk.exe";
pub(super) fn schedule_verified_update_cleanup() -> std::io::Result<()> {
use windows::{
core::{HSTRING, PCWSTR},
Win32::Storage::FileSystem::{MoveFileExW, MOVEFILE_DELAY_UNTIL_REBOOT},
};
let current_exe = std::env::current_exe()?;
let is_verified_update = current_exe
.file_name()
.and_then(|name| name.to_str())
.is_some_and(|name| {
name.starts_with(super::VERIFIED_UPDATE_FILE_PREFIX) && name.ends_with(".exe")
});
if !is_verified_update {
return Ok(());
}
unsafe {
MoveFileExW(
&HSTRING::from(current_exe.as_path()),
PCWSTR::null(),
MOVEFILE_DELAY_UNTIL_REBOOT,
)
}
.map_err(std::io::Error::other)
}
pub(super) fn copy_runtime_broker(dir: &Path) {
let src = RUNTIME_BROKER_EXE;
let tgt = WIN_TOPMOST_INJECTED_PROCESS_EXE;
+44 -15
View File
@@ -5,7 +5,7 @@ use winapi::{
shared::{
minwindef::{BOOL, DWORD, FALSE, LPBYTE, LPDWORD},
ntdef::HANDLE,
winerror::ERROR_INVALID_PRINTER_NAME,
winerror::{ERROR_INSUFFICIENT_BUFFER, ERROR_INVALID_PRINTER_NAME},
},
um::winspool::{
AddPrinterW, ClosePrinter, DeletePrinter, EnumPrintersW, OpenPrinterW, SetPrinterW,
@@ -42,20 +42,49 @@ fn enum_local_printer(
#[inline]
pub fn is_printer_added(name: &PCWSTR) -> ResultType<bool> {
let r = common_enum(
"EnumPrintersW",
enum_local_printer,
1,
|info: &PRINTER_INFO_1W| {
if is_name_equal(name, info.pName) {
Some(true)
} else {
None
}
},
|| None,
)?;
Ok(r.unwrap_or(false))
const PRINTER_INFO_LEVEL: DWORD = 1;
let mut needed = 0;
let mut returned = 0;
if enum_local_printer(
PRINTER_INFO_LEVEL,
null_mut(),
0,
&mut needed,
&mut returned,
) == FALSE
{
let error = io::Error::last_os_error();
if error.raw_os_error() != Some(ERROR_INSUFFICIENT_BUFFER as i32) || needed == 0 {
bail!("Failed to query EnumPrintersW buffer size: {error}");
}
}
if needed == 0 {
return Ok(false);
}
let mut buffer = vec![0u8; needed as usize];
if enum_local_printer(
PRINTER_INFO_LEVEL,
buffer.as_mut_ptr(),
needed,
&mut needed,
&mut returned,
) == FALSE
{
bail!(
"Failed to call EnumPrintersW, error: {}",
io::Error::last_os_error()
);
}
let printers = buffer.as_ptr() as *const PRINTER_INFO_1W;
for index in 0..returned {
let printer = unsafe { &*printers.add(index as usize) };
if is_name_equal(name, printer.pName) {
return Ok(true);
}
}
Ok(false)
}
// Only return the first matched printer
+1 -1
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.8). We deliberately do
# `DRMTAP_SHA` in build.py, which fetches that exact commit (libdrmtap v0.5.12). 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
-17
View File
@@ -199,23 +199,6 @@ mod webrtc {
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use std::os::raw::c_uint;
#[test]
fn tile_log2_uses_c_uint_and_rounds_up() {
let one_thread: c_uint = tile_log2(1);
let three_threads: c_uint = tile_log2(3);
let max_threads: c_uint = tile_log2(64);
assert_eq!(one_thread, 0);
assert_eq!(three_threads, 2);
assert_eq!(max_threads, 6);
}
}
}
impl EncoderApi for AomEncoder {
+66 -172
View File
@@ -309,6 +309,8 @@ pub struct DisplaySnapshot {
pub y: i32,
pub width: u32,
pub height: u32,
/// The kernel's whole-hertz vrefresh: 59.94 reads 60. `DrmReader::crtc_refresh` is exact.
pub refresh_hz: u32,
pub active: bool,
}
@@ -545,6 +547,17 @@ impl DrmReader {
self.last_plane_rotation
}
/// The refresh of the captured CRTC in hertz as the reduced fraction `(num, den)` of its
/// current mode, read now. `None` when the library predates the call (0.5.9) or the CRTC has
/// no mode.
pub fn crtc_refresh(&mut self) -> Option<(u64, u64)> {
let f = self.lib.crtc_refresh?;
let (mut num, mut den) = (0u64, 0u64);
// SAFETY: self.ctx is a live context and both outputs outlive the call.
let rc = unsafe { f(self.ctx, &mut num, &mut den) };
(rc == 0 && num != 0 && den != 0).then_some((num, den))
}
fn read_plane_rotation(&mut self) -> Option<u32> {
let f = self.lib.plane_rotation?;
let mut rotation: u32 = 0;
@@ -553,6 +566,12 @@ impl DrmReader {
plane_rotation_answer(rc, rotation)
}
/// The primary plane's rotation read NOW, for a caller that has not grabbed (enumeration):
/// `plane_rotation()` only reflects the last grab.
pub fn query_plane_rotation(&mut self) -> Option<u32> {
self.read_plane_rotation()
}
/// Zero-copy EXPORT grab: fills a `drmtap_dmabuf_desc` (dma-buf fd, plane layout, HDR metadata) WITHOUT mapping, detiling or copying pixels, so on this
/// path the root process never loads libEGL/libGLESv2. The exported fd is READ-ONLY (libdrmtap drops `DRM_RDWR` and `dup` shares that open file
/// description), so the `--server` that receives it can map the scanout but never write the live framebuffer. Validation here is METADATA ONLY.
@@ -755,6 +774,7 @@ impl DrmReader {
y: raw[i].y as i32,
width: raw[i].width,
height: raw[i].height,
refresh_hz: raw[i].refresh_hz,
active: raw[i].active != 0,
}
})
@@ -775,47 +795,7 @@ 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));
}
use super::hot_measured_from;
/// 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.
@@ -825,25 +805,6 @@ mod hotspot_provenance_tests {
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)]
@@ -904,45 +865,6 @@ mod hotspot_guess_tests {
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
@@ -972,25 +894,6 @@ mod hotspot_guess_tests {
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.
@@ -999,14 +902,6 @@ mod hotspot_guess_tests {
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));
}
}
/// DRM_MODE_ROTATE_0: the `rotation` bitmask of a plane that turned nothing.
@@ -1030,8 +925,6 @@ fn plane_rotation_answer(rc: c_int, rotation: u32) -> Option<u32> {
#[cfg(test)]
mod plane_rotation_tests {
use super::*;
use std::os::fd::AsRawFd;
use std::sync::atomic::{AtomicI32, AtomicU32, Ordering};
#[test]
fn a_plane_without_the_property_turned_nothing() {
@@ -1042,63 +935,64 @@ mod plane_rotation_tests {
assert_eq!(plane_rotation_answer(-hbb_common::libc::EINVAL, 0), None);
assert_eq!(plane_rotation_answer(-hbb_common::libc::EIO, 7), None);
}
}
// What the plane answers whenever it is asked. The fake release turns it, the way a compositor
// may once the frame is out, so a read taken after the release or outside the grab sees 0x1.
static PLANE: AtomicU32 = AtomicU32::new(0x1);
static FD: AtomicI32 = AtomicI32::new(-1);
static PIXELS: [u8; 16] = [0; 16];
#[cfg(test)]
mod crtc_refresh_tests {
use super::*;
use std::sync::atomic::{AtomicI32, AtomicU64, Ordering};
unsafe extern "C" fn plane_rotation(_: *mut drmtap_ctx, rotation: *mut u32) -> c_int {
*rotation = PLANE.load(Ordering::SeqCst);
0
static RC: AtomicI32 = AtomicI32::new(0);
static NUM: AtomicU64 = AtomicU64::new(0);
static DEN: AtomicU64 = AtomicU64::new(0);
unsafe extern "C" fn crtc_refresh(_: *mut drmtap_ctx, num: *mut u64, den: *mut u64) -> c_int {
*num = NUM.load(Ordering::SeqCst);
*den = DEN.load(Ordering::SeqCst);
RC.load(Ordering::SeqCst)
}
unsafe extern "C" fn frame_release(_: *mut drmtap_ctx, _: *mut drmtap_frame_info) {
PLANE.store(0x1, Ordering::SeqCst);
}
unsafe extern "C" fn grab_mapped(_: *mut drmtap_ctx, f: *mut drmtap_frame_info) -> c_int {
(*f).data = PIXELS.as_ptr() as *mut _;
(*f).width = 2;
(*f).height = 2;
(*f).stride = 8;
(*f).format = DRM_FORMAT_XRGB8888;
0
unsafe extern "C" fn grab_mapped(_: *mut drmtap_ctx, _: *mut drmtap_frame_info) -> c_int {
-1
}
unsafe extern "C" fn frame_release(_: *mut drmtap_ctx, _: *mut drmtap_frame_info) {}
unsafe extern "C" fn grab_desc(
_: *mut drmtap_ctx,
d: *mut drmtap_dmabuf_desc,
_: *mut drmtap_dmabuf_desc,
_: *mut drmtap_frame_info,
) -> c_int {
(*d).dma_buf_fd = FD.load(Ordering::SeqCst);
(*d).width = 2;
(*d).height = 2;
(*d).num_planes = 1;
(*d).pitches[0] = 8;
0
-1
}
unsafe extern "C" fn plane_rotation(_: *mut drmtap_ctx, _: *mut u32) -> c_int {
-1
}
#[test]
fn a_frame_keeps_the_rotation_its_plane_had_when_it_was_grabbed() {
let lib: &'static DrmtapLib = Box::leak(Box::new(DrmtapLib::fake(
grab_mapped,
frame_release,
grab_desc,
plane_rotation,
)));
let mut r = DrmReader {
lib,
fn reader(with_call: bool) -> DrmReader {
let mut lib = DrmtapLib::fake(grab_mapped, frame_release, grab_desc, plane_rotation);
if with_call {
lib.crtc_refresh = Some(crtc_refresh);
}
DrmReader {
lib: Box::leak(Box::new(lib)),
ctx: std::ptr::null_mut(),
buf: Vec::new(),
last_provenance: -1,
last_plane_rotation: None,
};
PLANE.store(0x4, Ordering::SeqCst);
r.grab().expect("the fake grab succeeds");
assert_eq!(r.plane_rotation(), Some(0x4), "cpu grab");
let (fd, _peer) = std::os::unix::net::UnixStream::pair().unwrap();
FD.store(fd.as_raw_fd(), Ordering::SeqCst);
PLANE.store(0x8, Ordering::SeqCst);
r.grab_desc().expect("the fake export succeeds");
assert_eq!(r.plane_rotation(), Some(0x8), "dma-buf export");
}
}
/// rustdesk#16175: the exact refresh paces the producer; an older library has no answer.
#[test]
fn the_crtc_refresh_is_a_fraction_or_nothing() {
assert_eq!(reader(false).crtc_refresh(), None, "a library before 0.5.9");
let mut r = reader(true);
RC.store(0, Ordering::SeqCst);
NUM.store(148352, Ordering::SeqCst);
DEN.store(2475, Ordering::SeqCst);
assert_eq!(r.crtc_refresh(), Some((148352, 2475)));
RC.store(-hbb_common::libc::ENODATA, Ordering::SeqCst);
assert_eq!(r.crtc_refresh(), None, "a CRTC with no mode");
RC.store(0, Ordering::SeqCst);
DEN.store(0, Ordering::SeqCst);
assert_eq!(r.crtc_refresh(), None, "a zero denominator is no answer");
}
}
+19 -41
View File
@@ -146,6 +146,10 @@ type FnRenderNode = unsafe extern "C" fn(*mut drmtap_ctx) -> *const c_char;
/// means the compositor can only have rotated in software; `-ENOENT` with no plane bound;
/// `-EINVAL` on a null argument.
type FnPlaneRotation = unsafe extern "C" fn(*mut drmtap_ctx, *mut u32) -> c_int;
/// `drmtap_crtc_refresh`, added in libdrmtap 0.5.9: the refresh of the captured CRTC in hertz as
/// the reduced fraction `*num / *den` of its current mode. 0 on success; `-ENODATA` for a CRTC
/// with no mode; `-ENOENT` with none to pick; `-EINVAL` on a null argument.
type FnCrtcRefresh = unsafe extern "C" fn(*mut drmtap_ctx, *mut u64, *mut u64) -> c_int;
type FnConvertDmabuf =
unsafe extern "C" fn(*mut drmtap_ctx, *const drmtap_dmabuf_desc, *mut drmtap_frame_info) -> c_int;
@@ -171,6 +175,9 @@ pub struct DrmtapLib {
/// Optional: it only exists from libdrmtap 0.5.8. Absent means the library cannot say whether
/// the plane rotated the scanout, and the consumer keeps the pre-0.5.8 rule for that case.
pub plane_rotation: Option<FnPlaneRotation>,
/// Optional: it only exists from libdrmtap 0.5.9. Absent means the producer takes the
/// whole-hertz refresh of the enumeration as its pacing floor.
pub crtc_refresh: Option<FnCrtcRefresh>,
pub version: (c_int, c_int, c_int),
}
@@ -221,6 +228,7 @@ impl DrmtapLib {
convert_dmabuf,
render_node: None,
plane_rotation: Some(plane_rotation),
crtc_refresh: None,
version: (0, 5, 8),
}
}
@@ -353,6 +361,8 @@ impl DrmtapLib {
lib.get(b"drmtap_cursor_hotspot_valid").ok().map(|s| *s);
let plane_rotation: Option<FnPlaneRotation> =
lib.get(b"drmtap_plane_rotation").ok().map(|s| *s);
let crtc_refresh: Option<FnCrtcRefresh> =
lib.get(b"drmtap_crtc_refresh").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()
@@ -404,6 +414,14 @@ impl DrmtapLib {
software will be captured upside down."
);
}
if (minor, patch) >= (5, 9) && crtc_refresh.is_none() {
log::warn!(
"libdrmtap at {loaded_from} reports v{major}.{minor}.{patch} but is missing \
drmtap_crtc_refresh: it is a stale or pre-release build. Check what the \
soname symlink points at. Capture paces to the whole-hertz refresh, so a \
59.94 Hz panel is sampled as if it were 60."
);
}
Some(DrmtapLib {
_lib: lib,
open,
@@ -420,6 +438,7 @@ impl DrmtapLib {
convert_dmabuf,
render_node,
plane_rotation,
crtc_refresh,
version: (major, minor, patch),
})
}
@@ -445,41 +464,6 @@ pub fn get() -> Option<&'static DrmtapLib> {
mod tests {
use super::{abi_accepted, DRMTAP_ABI_MAJOR, DRMTAP_ABI_MINOR, DRMTAP_MIN_MINOR_PATCH};
#[test]
fn abi_gate_rejects_a_library_from_before_the_split() {
// These are refused because their MINOR differs from the verified one, which is the only
// reason the gate needs. Naming the pre-split releases keeps the intent readable, but do
// not read this as the floor doing the work: see the test below.
for (minor, patch) in [(3, 3), (4, 0), (4, 8), (4, 9)] {
assert!(
!abi_accepted(DRMTAP_ABI_MAJOR, minor, patch),
"v0.{minor}.{patch} is not the verified minor and must be refused"
);
}
}
#[test]
fn the_patch_floor_is_currently_vacuous_and_that_is_deliberate() {
// With MIN_MINOR_PATCH.0 == DRMTAP_ABI_MINOR the floor can never reject anything: the
// minor equality already forces `(minor, patch) >= (minor, 0)`. It is kept because it is
// the mechanism that WOULD do the work the next time a floor lands mid-minor, as (4, 10)
// did for the split API. This test exists so nobody reads the pre-split test above as
// evidence that the floor is live -- if that ever matters, this assert is the tripwire.
let (floor_minor, floor_patch) = DRMTAP_MIN_MINOR_PATCH;
assert_eq!(
floor_minor, DRMTAP_ABI_MINOR,
"the floor is inside the verified minor; a floor in a DIFFERENT minor is unreachable"
);
if floor_patch == 0 {
assert!(
abi_accepted(DRMTAP_ABI_MAJOR, DRMTAP_ABI_MINOR, 0),
"patch 0 of the verified minor must be accepted while the floor is 0"
);
} else {
assert!(!abi_accepted(DRMTAP_ABI_MAJOR, DRMTAP_ABI_MINOR, floor_patch - 1));
}
}
#[test]
fn abi_gate_accepts_the_floor_and_later_patches_of_the_same_minor() {
let (min_minor, min_patch) = DRMTAP_MIN_MINOR_PATCH;
@@ -509,10 +493,4 @@ mod tests {
);
}
}
#[test]
fn abi_gate_rejects_another_major_in_both_directions() {
assert!(!abi_accepted(DRMTAP_ABI_MAJOR + 1, 0, 0));
assert!(!abi_accepted(DRMTAP_ABI_MAJOR + 1, 99, 99));
}
}
-35
View File
@@ -176,38 +176,3 @@ impl Drop for CapturerGDI {
}
}
}
#[cfg(test)]
mod tests {
use super::super::*;
use super::*;
#[test]
fn test() {
match Displays::new().unwrap().next() {
Some(d) => {
let w = d.width();
let h = d.height();
let c = CapturerGDI::new(d.name(), w, h).unwrap();
let mut data = Vec::new();
c.frame(&mut data).unwrap();
let mut bitflipped = Vec::with_capacity((w * h * 4) as usize);
for y in 0..h {
for x in 0..w {
let i = (w * 4 * y + 4 * x) as usize;
bitflipped.extend_from_slice(&[data[i + 2], data[i + 1], data[i], 255]);
}
}
repng::encode(
std::fs::File::create("gdi_screen.png").unwrap(),
d.width() as u32,
d.height() as u32,
&bitflipped,
)
.unwrap();
}
_ => {
assert!(false);
}
}
}
}
-14
View File
@@ -692,17 +692,3 @@ impl CapturerMag {
TRUE
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test() {
let mut capture_mag = CapturerMag::new((0, 0), 1920, 1080).unwrap();
capture_mag.exclude("", "RustDeskPrivacyWindow").unwrap();
std::thread::sleep(std::time::Duration::from_millis(1000 * 10));
let mut data = Vec::new();
capture_mag.frame(&mut data).unwrap();
println!("capture data len: {}", data.len());
}
}
+5 -152
View File
@@ -21,10 +21,10 @@ const COMMAND_TIMEOUT: Duration = Duration::from_millis(1000);
// drm builds only: an unnamed-endpoint failure there forks the probe child, and the pollers
// turn every few hundred milliseconds. Every other failure is one cheap in-process error.
#[cfg(any(test, feature = "drm"))]
#[cfg(feature = "drm")]
const FAILED_LOOKUP_BACKOFF: Duration = Duration::from_secs(5);
#[cfg(any(test, feature = "drm"))]
#[cfg(feature = "drm")]
static LAST_FAILED_LOOKUP: Mutex<Option<Instant>> = Mutex::new(None);
#[cfg(feature = "drm")]
@@ -183,8 +183,7 @@ fn get_primary_monitor() -> Option<String> {
.or_else(try_gdbus_primary)
}
// Pure, so the backoff policy is testable without a compositor.
#[cfg(any(test, feature = "drm"))]
#[cfg(feature = "drm")]
fn lookup_allowed(failed_at: Option<Instant>, now: Instant) -> bool {
failed_at.map_or(true, |at| {
now.saturating_duration_since(at) >= FAILED_LOOKUP_BACKOFF
@@ -302,6 +301,7 @@ pub fn clear_wayland_displays_cache() {
// every OTHER live capturer on a multi-display session. A capturer records this at build and
// treats a later bump as "the layout changed under me, rebuild" — the only trigger a rotation
// has, since it changes neither the CRTC mode nor the framebuffer size (rustdesk#15886).
#[cfg(feature = "drm")]
static SNAPSHOT_GENERATION: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
/// Whether no snapshot has been cached: the signature of an enumeration that failed at session
@@ -311,7 +311,7 @@ pub fn wayland_snapshot_missing() -> bool {
DISPLAYS.lock().unwrap().is_none()
}
#[cfg(any(test, feature = "drm"))]
#[cfg(feature = "drm")]
pub fn bump_layout_generation() {
SNAPSHOT_GENERATION.fetch_add(1, std::sync::atomic::Ordering::Release);
}
@@ -516,40 +516,6 @@ fn map_axis(v: i32, base_origin: i32, base_extent: i32, live_origin: i32, live_e
mod tests {
use super::*;
#[test]
fn test_lookup_backoff_boundaries() {
// Future `now`s sidestep Instant subtraction, which can panic near boot.
let failed_at = Instant::now();
assert!(lookup_allowed(None, failed_at));
assert!(!lookup_allowed(
Some(failed_at),
failed_at + FAILED_LOOKUP_BACKOFF / 2
));
assert!(lookup_allowed(
Some(failed_at),
failed_at + FAILED_LOOKUP_BACKOFF
));
}
#[test]
fn test_lookup_stamp_from_the_future_only_waits() {
// saturating_duration_since answers zero rather than underflowing.
let now = Instant::now();
assert!(!lookup_allowed(Some(now + FAILED_LOOKUP_BACKOFF), now));
}
#[test]
fn test_clear_keeps_the_failure_stamp() {
// The stamp describes the seat, not the cache: the ~1/s capturer rebuild loop clears,
// and dropping the stamp with it would defeat the backoff. The generation test also
// calls clear now; both only assert monotonic/unchanged state, so they can interleave.
*LAST_FAILED_LOOKUP.lock().unwrap() = Some(Instant::now());
clear_wayland_displays_cache();
let stamp = *LAST_FAILED_LOOKUP.lock().unwrap();
assert!(stamp.is_some());
*LAST_FAILED_LOOKUP.lock().unwrap() = None;
}
fn display(
x: i32,
y: i32,
@@ -569,11 +535,6 @@ mod tests {
}
}
#[test]
fn test_desktop_rect_empty() {
assert_eq!(desktop_rect_of(&[]), None);
}
#[test]
fn test_desktop_rect_single_display_uses_physical_size() {
let displays = [display(0, 0, 2880, 1800, Some((1859, 1162)))];
@@ -591,15 +552,6 @@ mod tests {
assert_eq!(desktop_rect_of(&displays), Some((0, 3779, 0, 2160)));
}
#[test]
fn test_desktop_rect_missing_logical_size_falls_back_to_physical() {
let displays = [
display(0, 0, 2560, 1440, None),
display(2560, 0, 2560, 1440, Some((2560, 1440))),
];
assert_eq!(desktop_rect_of(&displays), Some((0, 5120, 0, 1440)));
}
#[test]
fn a_single_rotated_display_swaps_the_uinput_rect() {
// Review finding 1 on rustdesk#15889: the single-display branch served the unrotated
@@ -611,31 +563,6 @@ mod tests {
assert_eq!((rects[0].w, rects[0].h), (1080, 1920));
}
#[test]
fn a_transform_flip_is_visible_to_the_drift_comparison() {
// Review finding 5: 0<->180 and 90<->270 leave every rect identical; the transform
// field is what lets `baseline != live` fire on them.
let mut a = display(0, 0, 1920, 1080, Some((1920, 1080)));
let mut b = a.clone();
a.transform = 90;
b.transform = 270;
assert_ne!(logical_rects_of(&[a.clone(), a.clone()]), logical_rects_of(&[b.clone(), b]));
}
#[test]
fn only_the_explicit_bump_moves_the_generation() {
// A cache clear must NOT bump: session inits clear too, and a bump there rebuilds
// every other live capturer (adversarial finding on the first version of this).
let before = SNAPSHOT_GENERATION.load(std::sync::atomic::Ordering::Acquire);
clear_wayland_displays_cache();
assert_eq!(
SNAPSHOT_GENERATION.load(std::sync::atomic::Ordering::Acquire),
before
);
bump_layout_generation();
assert!(SNAPSHOT_GENERATION.load(std::sync::atomic::Ordering::Acquire) > before);
}
fn rect(name: &str, x: i32, y: i32, w: i32, h: i32) -> DisplayRect {
DisplayRect {
name: name.to_owned(),
@@ -671,16 +598,6 @@ mod tests {
);
}
// A point on the rescaled display itself is squeezed to its new logical width.
#[test]
fn test_remap_scales_within_resized_display() {
let baseline = [rect("DP-1", 0, 0, 2560, 1440), rect("DP-2", 2560, 0, 2560, 1440)];
let live = [rect("DP-1", 0, 0, 2048, 1440), rect("DP-2", 2048, 0, 2560, 1440)];
// x=1280 across the 2560-wide baseline DP-1 -> proportionally across the 2048-wide
// live DP-1 (endpoint-preserving scale, so ~1px off the naive midpoint).
assert_eq!(remap_to_live_layout(1280, 500, &baseline, &live), (1023, 500));
}
// The far edge of the followed display stays reachable when it is enlarged, so hot
// corners keep working. Baseline DP-1 is 2048 wide, live DP-1 is 2560 wide; the
// client's last column (2047) must map to the live last column (2559), not 2558.
@@ -692,57 +609,6 @@ mod tests {
assert_eq!(remap_to_live_layout(0, 0, &baseline, &live), (0, 0));
}
// No drift: identical layouts map every point to itself.
#[test]
fn test_remap_identity_when_unchanged() {
let layout = [rect("DP-1", 0, 0, 2560, 1440), rect("DP-2", 2560, 0, 2560, 1440)];
assert_eq!(remap_to_live_layout(3000, 700, &layout, &layout), (3000, 700));
}
// Point outside every baseline display is left untouched.
#[test]
fn test_remap_point_outside_all_displays_unchanged() {
let baseline = [rect("DP-1", 0, 0, 2560, 1440)];
let live = [rect("DP-1", 0, 0, 2048, 1440)];
assert_eq!(remap_to_live_layout(9000, 9000, &baseline, &live), (9000, 9000));
}
// Matched display gone from the live layout (e.g. unplugged): leave the point be
// rather than mapping it somewhere wrong.
#[test]
fn test_remap_display_removed_unchanged() {
let baseline = [rect("DP-1", 0, 0, 2560, 1440), rect("DP-2", 2560, 0, 2560, 1440)];
let live = [rect("DP-1", 0, 0, 2560, 1440)];
assert_eq!(remap_to_live_layout(2600, 100, &baseline, &live), (2600, 100));
}
// Nameless compositor: fall back to index matching while the count is unchanged.
#[test]
fn test_remap_nameless_index_fallback() {
let baseline = [rect("", 0, 0, 2560, 1440), rect("", 2560, 0, 2560, 1440)];
let live = [rect("", 0, 0, 2048, 1440), rect("", 2048, 0, 2560, 1440)];
assert_eq!(remap_to_live_layout(2560, 0, &baseline, &live), (2048, 0));
}
// Nameless compositor with a changed count: cannot index-match safely, so no-op.
#[test]
fn test_remap_nameless_count_changed_unchanged() {
let baseline = [rect("", 0, 0, 2560, 1440), rect("", 2560, 0, 2560, 1440)];
let live = [rect("", 0, 0, 2048, 1440)];
assert_eq!(remap_to_live_layout(2560, 0, &baseline, &live), (2560, 0));
}
// A named display absent from the live layout, but the count is unchanged (e.g. a
// monitor was swapped for a different one at the same index): the index fallback is
// for nameless layouts only, so a named miss stays unchanged rather than mapping to
// whatever now occupies that index.
#[test]
fn test_remap_named_miss_equal_count_unchanged() {
let baseline = [rect("DP-1", 0, 0, 2560, 1440), rect("DP-2", 2560, 0, 2560, 1440)];
let live = [rect("DP-1", 0, 0, 2048, 1440), rect("HDMI-1", 2048, 0, 1920, 1080)];
assert_eq!(remap_to_live_layout(2600, 100, &baseline, &live), (2600, 100));
}
// A single display uses physical size in both baseline and live (scale reported as
// 1.0), so it never drifts and the remap is a no-op even across a rescale.
#[test]
@@ -753,17 +619,4 @@ mod tests {
vec![rect("", 0, 0, 2560, 1440)]
);
}
// Multiple displays use logical size, falling back to physical when absent.
#[test]
fn test_logical_rects_multi_display_uses_logical() {
let displays = [
display(0, 0, 2560, 1440, Some((2048, 1152))),
display(2048, 0, 1920, 1080, None),
];
assert_eq!(
logical_rects_of(&displays),
vec![rect("", 0, 0, 2048, 1152), rect("", 2048, 0, 1920, 1080)]
);
}
}
+134 -18
View File
@@ -23,7 +23,7 @@ use gstreamer_app::AppSink;
use lazy_static::lazy_static;
use serde::{Deserialize, Serialize};
use base::platform::linux::CMD_SH;
use base::platform::linux::{WaylandDisplayInfo, CMD_SH};
use hbb_common::{anyhow::anyhow, bail, config, serde_json, tokio, ResultType};
use super::capturable::PixelProvider;
@@ -77,7 +77,9 @@ pub fn close_session() {
#[inline]
pub fn is_rdp_session_hold() -> bool {
RDP_SESSION_INFO.lock().unwrap().is_some()
// try_lock: a request waiting for the user holds the slot (no session yet), and so do the short
// looks while a session is set up. Busy answers no session rather than wait.
matches!(RDP_SESSION_INFO.try_lock(), Ok(info) if info.is_some())
}
pub fn try_close_session() {
@@ -157,6 +159,9 @@ pub struct PipeWireCapturable {
pub position: (i32, i32),
pub logical_size: (usize, usize),
pub physical_size: (usize, usize),
// False when `physical_size` is the portal size standing in for a resolution get_res() could
// not read.
physical_size_measured: bool,
}
impl PipeWireCapturable {
@@ -168,7 +173,7 @@ impl PipeWireCapturable {
) -> Self {
// alternative to get screen resolution as stream.size is not always correct ex: on fractional scaling
// https://github.com/rustdesk/rustdesk/issues/6116#issuecomment-1817724244
let physical_size = get_res(Self {
let measured = get_res(Self {
dbus_conn: conn.clone(),
fd: fd.clone(),
path: stream.path,
@@ -177,8 +182,10 @@ impl PipeWireCapturable {
position: stream.position,
logical_size: stream.size,
physical_size: (0, 0),
})
.unwrap_or(stream.size);
physical_size_measured: false,
});
let physical_size_measured = measured.is_ok();
let physical_size = measured.unwrap_or(stream.size);
*resolution.lock().unwrap() = Some(physical_size);
Self {
dbus_conn: conn,
@@ -189,6 +196,7 @@ impl PipeWireCapturable {
position: stream.position,
logical_size: stream.size,
physical_size,
physical_size_measured,
}
}
}
@@ -1291,6 +1299,26 @@ pub fn fill_displays(
}
if all_displays.displays.len() > 1 {
for (i, sd) in shared_displays.iter_mut().enumerate() {
if let crate::Display::WAYLAND(d) = sd {
let capturable = &mut d.0;
if let Some(origin) = reconciled_origin(
capturable.position,
capturable.physical_size,
capturable.physical_size_measured,
&all_displays.displays,
) {
warn!(
"Position {:?} names no output of size {:?}, using {:?}.",
capturable.position, capturable.physical_size, origin
);
capturable.position = origin;
if let Some(pw_stream) = rdp_info.streams.get_mut(i) {
pw_stream.position = origin;
}
}
}
}
sort_streams(&all_displays, shared_displays, &mut rdp_info.streams);
}
@@ -1303,6 +1331,50 @@ pub fn fill_displays(
Ok(())
}
// The origin a stream takes when its position names no output of its size. Only a measured size
// moves a position: when get_res() failed, the size is the portal size, which can be the mode of
// another output and says less than the position does, whether the portal sent that position or
// try_fill_positions restored it from its cache.
fn reconciled_origin(
position: (i32, i32),
size: (usize, usize),
size_measured: bool,
outputs: &[WaylandDisplayInfo],
) -> Option<(i32, i32)> {
if !size_measured {
return None;
}
corrected_origin(position, size, outputs)
}
// The origin for a stream whose position names no output of the stream's size (a rotated output
// counts in either orientation), when exactly one output has that size. xdg-desktop-portal-hyprland reports every stream at (0, 0):
// with no output there `sort_streams` dropped the stream, and with another output there the
// stream took its origin and missed `try_fix_logical_size`, so the pointer landed on the wrong
// output (#15731). With several outputs of that size the position is kept.
fn corrected_origin(
position: (i32, i32),
size: (usize, usize),
outputs: &[WaylandDisplayInfo],
) -> Option<(i32, i32)> {
let has_size = |o: &&WaylandDisplayInfo| {
let mode = (o.width as usize, o.height as usize);
mode == size || (o.transform % 180 != 0 && (mode.1, mode.0) == size)
};
if outputs
.iter()
.filter(has_size)
.any(|o| (o.x, o.y) == position)
{
return None;
}
let mut same_size = outputs.iter().filter(has_size);
match (same_size.next(), same_size.next()) {
(Some(o), None) => Some((o.x, o.y)),
_ => None,
}
}
fn try_fill_positions(
mouse_move_to: impl Fn(i32, i32),
get_cursor_pos: fn() -> Option<(i32, i32)>,
@@ -1605,6 +1677,7 @@ fn fill_multi_matched_positions_cursor(
position: pw_stream_with_cursor.position,
logical_size: pw_stream_with_cursor.size,
physical_size: (0, 0),
physical_size_measured: false,
})?;
// Take first frame and copy owned buffer to avoid borrow across second capture
let (is_bgr, w, first_buf): (bool, usize, Vec<u8>) =
@@ -1731,26 +1804,69 @@ fn sort_streams(
#[cfg(test)]
mod tests {
use super::stage_err;
use super::{corrected_origin, WaylandDisplayInfo};
fn output(x: i32, y: i32, mode: (i32, i32)) -> WaylandDisplayInfo {
WaylandDisplayInfo {
name: String::new(),
x,
y,
width: mode.0,
height: mode.1,
logical_size: None,
refresh_rate: 60,
transform: 0,
}
}
#[test]
fn stage_err_keeps_the_detail_safe_for_a_placeholder() {
fn a_portal_position_naming_no_output_of_its_size_moves_to_the_only_one() {
// 1920x1080 at the origin, 2880x1800 to its right: xdph puts the right one at (0, 0).
let pair = [output(0, 0, (1920, 1080)), output(1920, 0, (2880, 1800))];
assert_eq!(
stage_err("start", "declined", ""),
"wl-stage:start:declined:"
corrected_origin((0, 0), (2880, 1800), &pair),
Some((1920, 0))
);
// Braces of its own would break the placeholder lookup on the peer.
// A real origin is kept.
assert_eq!(corrected_origin((1920, 0), (2880, 1800), &pair), None);
// Nothing starts at the origin (the hyprland layout in #15731).
let three = [
output(0, 120, (1920, 1200)),
output(1920, 0, (3440, 1440)),
output(5360, 180, (1920, 1080)),
];
assert_eq!(
stage_err("create-session", "dbus", "org.freedesktop.{Error}"),
"wl-stage:create-session:dbus:org.freedesktop.Error"
corrected_origin((0, 0), (3440, 1440), &three),
Some((1920, 0))
);
// Two outputs of that size cannot be told apart: the position is kept.
let twins = [
output(0, 0, (2560, 1600)),
output(2560, 0, (1920, 1080)),
output(4480, 0, (1920, 1080)),
];
assert_eq!(corrected_origin((0, 0), (1920, 1080), &twins), None);
// A portrait panel turned to landscape keeps its position next to a 1920x1080 output.
let turned = [
WaylandDisplayInfo {
transform: 90,
..output(0, 0, (1080, 1920))
},
output(1920, 0, (1920, 1080)),
];
assert_eq!(corrected_origin((0, 0), (1920, 1080), &turned), None);
// A rotated output that try_fill_positions could not match by its mode is found in its
// delivered orientation.
let turned_right = [
output(0, 0, (2560, 1440)),
WaylandDisplayInfo {
transform: 90,
..output(2560, 0, (1080, 1920))
},
];
assert_eq!(
stage_err("select-sources", "internal", "one\ntwo"),
"wl-stage:select-sources:internal:one two"
);
assert_eq!(
stage_err("start", "internal", &"x".repeat(300)),
format!("wl-stage:start:internal:{}", "x".repeat(200))
corrected_origin((0, 0), (1920, 1080), &turned_right),
Some((2560, 0))
);
}
}
+1 -1
View File
@@ -1,5 +1,5 @@
pkgname=rustdesk
pkgver=1.5.0
pkgver=1.5.1
pkgrel=0
epoch=
pkgdesc=""
+1
View File
@@ -14,3 +14,4 @@ EXPORTS
RemoveAmyuniIdd
InstallPrinter
UninstallPrinter
SetPrinterInstallDefault
+66
View File
@@ -3,6 +3,7 @@
#include <Windows.h>
#include <winspool.h>
#include <setupapi.h>
#include <strutil.h>
#include <memory>
#include <string>
#include <functional>
@@ -356,6 +357,42 @@ namespace RemotePrinter
return EnumPrintersW(PRINTER_ENUM_LOCAL, NULL, level, pPrinterInfo, cbBuf, pcbNeeded, pcReturned);
}
static HRESULT queryPrinterPresence(LPCWSTR name)
{
constexpr DWORD printerInfoLevel = 1;
DWORD needed = 0;
DWORD returned = 0;
if (!enumLocalPrinter(printerInfoLevel, NULL, 0, &needed, &returned))
{
const DWORD error = GetLastError();
if (error != ERROR_INSUFFICIENT_BUFFER || needed == 0)
{
return error == ERROR_SUCCESS ? E_FAIL : HRESULT_FROM_WIN32(error);
}
}
if (needed == 0)
{
return S_FALSE;
}
std::vector<BYTE> buffer(needed);
if (!enumLocalPrinter(printerInfoLevel, buffer.data(), needed, &needed, &returned))
{
const DWORD error = GetLastError();
return error == ERROR_SUCCESS ? E_FAIL : HRESULT_FROM_WIN32(error);
}
const auto printers = reinterpret_cast<const PRINTER_INFO_1W *>(buffer.data());
for (DWORD i = 0; i < returned; i++)
{
if (isNameEqual(name, printers[i].pName))
{
return S_OK;
}
}
return S_FALSE;
}
BOOL isPrinterAdded(LPCWSTR name)
{
auto onData = [name](const PRINTER_INFO_1W &info)
@@ -528,3 +565,32 @@ namespace RemotePrinter
WcaLog(LOGMSG_STANDARD, "Deleted the local port\n");
}
}
extern "C" UINT __stdcall SetPrinterInstallDefault(__in MSIHANDLE hInstall)
{
HRESULT hr = S_OK;
LPWSTR appName = NULL;
hr = WcaInitialize(hInstall, "SetPrinterInstallDefault");
ExitOnFailure(hr, "Failed to initialize printer detection");
hr = WcaGetProperty(L"ProductName", &appName);
ExitOnFailure(hr, "Failed to get the printer's application name");
hr = RemotePrinter::queryPrinterPresence(RemotePrinter::printerNameOf(appName).c_str());
if (FAILED(hr))
{
WcaLog(LOGMSG_STANDARD, "Failed to detect the existing printer (0x%08X); skipping printer installation.", static_cast<UINT>(hr));
}
if (hr != S_OK)
{
hr = WcaSetProperty(L"INSTALLPRINTER", L"0");
ExitOnFailure(hr, "Failed to disable printer installation");
WcaLog(LOGMSG_STANDARD, "The application's printer was not confirmed present; leaving printer installation disabled by default.");
}
LExit:
ReleaseStr(appName);
return WcaFinalize(SUCCEEDED(hr) ? ERROR_SUCCESS : ERROR_INSTALL_FAILURE);
}
@@ -74,13 +74,22 @@
<SetProperty Action="RestoreSavedDesktopShortcutsValue" Id="CREATEDESKTOPSHORTCUTS" Value="[SavedDesktopShortcutsCmdLineValue]" After="AppSearch" Sequence="first" Condition="SavedDesktopShortcutsCmdLineValue" />
<SetProperty Action="RestoreSavedPrinterValue" Id="INSTALLPRINTER" Value="[SavedPrinterCmdLineValue]" After="AppSearch" Sequence="first" Condition="SavedPrinterCmdLineValue" />
<!-- Check before the old product removes its printer. firstSequence preserves later UI choices. -->
<CustomAction Id="SetPrinterInstallDefault" DllEntry="SetPrinterInstallDefault" Execute="firstSequence" Return="check" BinaryRef="Custom_Actions_Dll" />
<InstallUISequence>
<Custom Action="SetPrinterInstallDefault" After="RestoreSavedPrinterValue" Condition="WIX_UPGRADE_DETECTED AND NOT SavedPrinterCmdLineValue AND (INSTALLPRINTER = 1 OR INSTALLPRINTER = &quot;Y&quot; OR INSTALLPRINTER = &quot;y&quot;)" />
</InstallUISequence>
<InstallExecuteSequence>
<Custom Action="SetPrinterInstallDefault" After="RestoreSavedPrinterValue" Condition="WIX_UPGRADE_DETECTED AND NOT SavedPrinterCmdLineValue AND (INSTALLPRINTER = 1 OR INSTALLPRINTER = &quot;Y&quot; OR INSTALLPRINTER = &quot;y&quot;)" />
</InstallExecuteSequence>
<!-- If a command line value or registry value was set, update the main properties with the value -->
<SetProperty Id="STARTMENUSHORTCUTS" Value="" After="RestoreSavedStartMenuShortcutsValue" Sequence="first" Condition="CREATESTARTMENUSHORTCUTS AND NOT (CREATESTARTMENUSHORTCUTS = 1 OR CREATESTARTMENUSHORTCUTS = &quot;Y&quot; OR CREATESTARTMENUSHORTCUTS = &quot;y&quot;)" />
<SetProperty Id="DESKTOPSHORTCUTS" Value="" After="RestoreSavedDesktopShortcutsValue" Sequence="first" Condition="CREATEDESKTOPSHORTCUTS AND NOT (CREATEDESKTOPSHORTCUTS = 1 OR CREATEDESKTOPSHORTCUTS = &quot;Y&quot; OR CREATEDESKTOPSHORTCUTS = &quot;y&quot;)" />
<!-- PRINTER defaults to empty now, so a saved or command-line INSTALLPRINTER=1
must explicitly enable the main PRINTER property. Non-truthy INSTALLPRINTER
values still clear PRINTER so upgrades preserve an explicit disabled choice. -->
<SetProperty Action="SetPrinterValueEnabled" Id="PRINTER" Value="1" After="RestoreSavedPrinterValue" Sequence="first" Condition="INSTALLPRINTER = 1 OR INSTALLPRINTER = &quot;Y&quot; OR INSTALLPRINTER = &quot;y&quot;" />
<SetProperty Action="SetPrinterValueEnabled" Id="PRINTER" Value="1" After="SetPrinterInstallDefault" Sequence="first" Condition="INSTALLPRINTER = 1 OR INSTALLPRINTER = &quot;Y&quot; OR INSTALLPRINTER = &quot;y&quot;" />
<SetProperty Action="SetPrinterValueDisabled" Id="PRINTER" Value="" After="SetPrinterValueEnabled" Sequence="first" Condition="INSTALLPRINTER AND NOT (INSTALLPRINTER = 1 OR INSTALLPRINTER = &quot;Y&quot; OR INSTALLPRINTER = &quot;y&quot;)" />
</Fragment>
+1 -1
View File
@@ -1,5 +1,5 @@
Name: rustdesk
Version: 1.5.0
Version: 1.5.1
Release: 0
Summary: RPM package
License: GPL-3.0
+1 -1
View File
@@ -1,5 +1,5 @@
Name: rustdesk
Version: 1.5.0
Version: 1.5.1
Release: 0
Summary: RPM package
License: GPL-3.0
+1 -1
View File
@@ -1,5 +1,5 @@
Name: rustdesk
Version: 1.5.0
Version: 1.5.1
Release: 0
Summary: RPM package
License: GPL-3.0
+297
View File
@@ -0,0 +1,297 @@
#!/usr/bin/env python3
import argparse
import base64
import binascii
import hashlib
import json
import os
import re
from pathlib import Path
from cryptography.exceptions import InvalidSignature
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import ed25519
from update_metadata_policy import (
release_artifact_url,
validate_artifact_file_name,
validate_package_id,
validate_published_at,
validate_release,
validate_release_base_url,
)
APP_NAME = "rustdesk"
SCHEMA_VERSION = 1
SIGNATURE_ALGORITHM = "ed25519"
SIGNATURE_CONTEXT = b"RustDesk update metadata v1\n"
KEY_ID = "2026-ed25519-main"
SEED_ENV = "RUSTDESK_UPDATE_ED25519_SEED"
PUBLIC_KEY_ENV = "RUSTDESK_UPDATE_ED25519_PUBLIC_KEY"
def fail(message):
raise SystemExit(message)
def stable_json(value):
return json.dumps(value, separators=(",", ":"), sort_keys=True).encode("utf-8")
def write_bytes(path, data):
output = Path(path)
output.parent.mkdir(parents=True, exist_ok=True)
output.write_bytes(data)
def sha256_hex(path):
hasher = hashlib.sha256()
with Path(path).open("rb") as handle:
for chunk in iter(lambda: handle.read(1024 * 1024), b""):
hasher.update(chunk)
return hasher.hexdigest()
def decode_env(name, expected_size):
encoded = os.environ.get(name)
if not encoded:
fail(f"missing environment variable: {name}")
try:
value = base64.b64decode(encoded, validate=True)
except (ValueError, binascii.Error) as error:
fail(f"invalid base64 in {name}: {error}")
if len(value) != expected_size:
fail(f"{name} must decode to {expected_size} bytes")
if base64.b64encode(value).decode("ascii") != encoded:
fail(f"{name} must use canonical base64")
return value
def validate_or_fail(function, *args):
try:
return function(*args)
except ValueError as error:
fail(str(error))
def artifact_metadata(spec, release_id, release_base_url):
platform, arch, file_format, raw_path = spec
if not all(value.strip() for value in (platform, arch, file_format)):
fail("artifact selector fields must not be empty")
path = Path(raw_path)
file_name = path.name
validate_or_fail(validate_artifact_file_name, file_name)
size = path.stat().st_size
if size == 0:
fail(f"artifact must not be empty: {file_name}")
return {
"platform": platform,
"arch": arch,
"format": file_format,
"url": release_artifact_url(release_base_url, release_id, file_name),
"file_name": file_name,
"size": size,
"sha256": sha256_hex(path),
}
def command_sign(args):
metadata_out = Path(args.metadata_out).resolve()
signature_out = Path(args.signature_out).resolve()
if metadata_out == signature_out:
fail("metadata and signature outputs must be different files")
validate_or_fail(validate_release, args.release_id, args.version)
validate_or_fail(validate_published_at, args.published_at)
package_id = validate_or_fail(validate_package_id, args.package_id)
release_base_url = validate_or_fail(
validate_release_base_url, args.release_base_url
)
artifacts = [
artifact_metadata(spec, args.release_id, release_base_url)
for spec in args.artifact
]
selectors = [(item["platform"], item["arch"], item["format"]) for item in artifacts]
names = [item["file_name"] for item in artifacts]
if len(set(selectors)) != len(selectors):
fail("duplicate artifact selector")
if len(set(names)) != len(names):
fail("duplicate artifact file name")
artifacts.sort(key=lambda item: (item["platform"], item["arch"], item["format"]))
metadata = {
"schema_version": SCHEMA_VERSION,
"app": APP_NAME,
"package_id": package_id,
"version": args.version,
"release_id": args.release_id,
"published_at": args.published_at,
"signature_key_id": KEY_ID,
"artifacts": artifacts,
}
private_key = ed25519.Ed25519PrivateKey.from_private_bytes(decode_env(SEED_ENV, 32))
metadata_bytes = stable_json(metadata)
signature = {
"schema_version": SCHEMA_VERSION,
"algorithm": SIGNATURE_ALGORITHM,
"key_id": KEY_ID,
"signature": base64.b64encode(
private_key.sign(SIGNATURE_CONTEXT + metadata_bytes)
).decode("ascii"),
}
write_bytes(metadata_out, metadata_bytes)
write_bytes(signature_out, stable_json(signature))
def verify_metadata_signature(metadata_bytes, signature):
if (
signature.get("schema_version") != SCHEMA_VERSION
or signature.get("algorithm") != SIGNATURE_ALGORITHM
or signature.get("key_id") != KEY_ID
):
fail("invalid signature metadata")
public_key = ed25519.Ed25519PublicKey.from_public_bytes(decode_env(PUBLIC_KEY_ENV, 32))
try:
public_key.verify(
base64.b64decode(signature["signature"], validate=True),
SIGNATURE_CONTEXT + metadata_bytes,
)
except (InvalidSignature, ValueError, binascii.Error):
fail("invalid metadata signature")
def validated_artifacts(metadata, local_artifacts):
artifacts = metadata.get("artifacts")
if not isinstance(artifacts, list) or not artifacts:
fail("metadata must contain artifacts")
selector_fields = ("platform", "arch", "format")
required_fields = selector_fields + ("file_name", "url", "size", "sha256")
if any(
not isinstance(artifact, dict)
or any(field not in artifact for field in required_fields)
for artifact in artifacts
):
fail("artifact metadata is missing required fields")
names = [artifact.get("file_name") for artifact in artifacts]
for file_name in names:
validate_or_fail(validate_artifact_file_name, file_name)
selectors = [
tuple(artifact[field] for field in selector_fields)
for artifact in artifacts
]
if any(
not all(isinstance(value, str) and value.strip() for value in selector)
for selector in selectors
):
fail("artifact selector fields must be non-empty strings")
if len(set(names)) != len(names) or set(names) != set(local_artifacts):
fail("artifact file set mismatch")
if len(set(selectors)) != len(selectors):
fail("duplicate artifact selector")
return artifacts
def command_verify(args):
metadata_bytes = Path(args.metadata).read_bytes()
metadata = json.loads(metadata_bytes)
signature = json.loads(Path(args.signature).read_bytes())
verify_metadata_signature(metadata_bytes, signature)
package_id = validate_or_fail(validate_package_id, args.package_id)
release_base_url = validate_or_fail(
validate_release_base_url, args.release_base_url
)
expected_fields = {
"schema_version": SCHEMA_VERSION,
"app": APP_NAME,
"package_id": package_id,
"version": args.version,
"release_id": args.release_id,
"signature_key_id": KEY_ID,
}
if any(metadata.get(key) != value for key, value in expected_fields.items()):
fail("metadata does not match the release")
validate_or_fail(validate_release, args.release_id, args.version)
validate_or_fail(validate_published_at, metadata.get("published_at", ""))
local_paths = [Path(path) for path in args.artifact]
local_artifacts = {path.name: path for path in local_paths}
if len(local_artifacts) != len(local_paths):
fail("duplicate local artifact file name")
artifacts = validated_artifacts(metadata, local_artifacts)
for artifact in artifacts:
file_name = artifact["file_name"]
expected_url = release_artifact_url(
release_base_url, args.release_id, file_name
)
if artifact["url"] != expected_url:
fail(f"artifact URL mismatch for {file_name}")
path = local_artifacts[file_name]
if path.stat().st_size != artifact["size"]:
fail(f"artifact size mismatch for {file_name}")
if sha256_hex(path) != artifact["sha256"]:
fail(f"artifact sha256 mismatch for {file_name}")
def command_check_key(args):
seed = decode_env(SEED_ENV, 32)
configured_key = decode_env(PUBLIC_KEY_ENV, 32)
derived_key = ed25519.Ed25519PrivateKey.from_private_bytes(seed).public_key()
derived_key_bytes = derived_key.public_bytes(
serialization.Encoding.Raw,
serialization.PublicFormat.Raw,
)
if derived_key_bytes != configured_key:
fail(f"{SEED_ENV} does not match {PUBLIC_KEY_ENV}")
source = Path(args.rust_source).read_text(encoding="utf-8")
match = re.search(
rf'TrustedUpdateKey\s*\{{[^{{}}]*key_id:\s*"{KEY_ID}"[^{{}}]*public_key:\s*\[([^\]]+)\]',
source,
re.S,
)
if not match:
fail("failed to find embedded update public key")
try:
embedded_key = bytes(
int(part) for part in match.group(1).split(",") if part.strip()
)
except ValueError as error:
fail(f"invalid embedded update public key: {error}")
if embedded_key != configured_key:
fail(f"embedded update public key does not match {PUBLIC_KEY_ENV}")
def build_parser():
parser = argparse.ArgumentParser()
commands = parser.add_subparsers(dest="command", required=True)
sign = commands.add_parser("sign")
sign.add_argument("--artifact", action="append", nargs=4, required=True)
sign.add_argument("--version", required=True)
sign.add_argument("--release-id", required=True)
sign.add_argument("--package-id", required=True)
sign.add_argument("--release-base-url", required=True)
sign.add_argument("--published-at", required=True)
sign.add_argument("--metadata-out", required=True)
sign.add_argument("--signature-out", required=True)
sign.set_defaults(func=command_sign)
verify = commands.add_parser("verify")
verify.add_argument("--metadata", required=True)
verify.add_argument("--signature", required=True)
verify.add_argument("--artifact", action="append", required=True)
verify.add_argument("--version", required=True)
verify.add_argument("--release-id", required=True)
verify.add_argument("--package-id", required=True)
verify.add_argument("--release-base-url", required=True)
verify.set_defaults(func=command_verify)
check_key = commands.add_parser("check-key")
check_key.add_argument(
"--rust-source", default="src/update_metadata.rs"
)
check_key.set_defaults(func=command_check_key)
return parser
def main():
args = build_parser().parse_args()
args.func(args)
if __name__ == "__main__":
main()
+300
View File
@@ -0,0 +1,300 @@
import base64
import json
import os
import subprocess
import sys
import tempfile
import unittest
from pathlib import Path
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import ed25519
SCRIPT = Path(__file__).with_name("generate_update_metadata.py")
OFFICIAL_RELEASE_BASE_URL = "https://github.com/rustdesk/rustdesk/releases/download"
class GenerateUpdateMetadataTest(unittest.TestCase):
def setUp(self):
self.temp_dir = tempfile.TemporaryDirectory()
self.root = Path(self.temp_dir.name)
private_key = ed25519.Ed25519PrivateKey.generate()
seed = private_key.private_bytes(
serialization.Encoding.Raw,
serialization.PrivateFormat.Raw,
serialization.NoEncryption(),
)
public_key = private_key.public_key().public_bytes(
serialization.Encoding.Raw,
serialization.PublicFormat.Raw,
)
self.seed = base64.b64encode(seed).decode("ascii")
self.public_key = base64.b64encode(public_key).decode("ascii")
def tearDown(self):
self.temp_dir.cleanup()
def run_script(self, *args, seed=None, public_key=None):
env = os.environ.copy()
env.pop("RUSTDESK_UPDATE_ED25519_SEED", None)
env.pop("RUSTDESK_UPDATE_ED25519_PUBLIC_KEY", None)
if seed is not None:
env["RUSTDESK_UPDATE_ED25519_SEED"] = seed
if public_key is not None:
env["RUSTDESK_UPDATE_ED25519_PUBLIC_KEY"] = public_key
return subprocess.run(
[sys.executable, str(SCRIPT), *args],
cwd=SCRIPT.parents[2],
env=env,
text=True,
capture_output=True,
)
def artifact(self, name="rustdesk-1.4.6-x86_64.exe", data=b"rustdesk"):
path = self.root / name
path.write_bytes(data)
return path
def sign(
self,
artifacts,
*,
version="1.4.6",
release_id="v1.4.6",
package_id="rustdesk",
release_base_url=OFFICIAL_RELEASE_BASE_URL,
seed=None,
):
metadata = self.root / "rustdesk-update.json"
signature = self.root / "rustdesk-update.json.sig"
args = ["sign"]
for platform, arch, file_format, path in artifacts:
args.extend(["--artifact", platform, arch, file_format, str(path)])
args.extend(
[
"--version",
version,
"--release-id",
release_id,
"--package-id",
package_id,
"--release-base-url",
release_base_url,
"--published-at",
"2026-05-14T00:00:00Z",
"--metadata-out",
str(metadata),
"--signature-out",
str(signature),
]
)
result = self.run_script(*args, seed=self.seed if seed is None else seed)
return metadata, signature, result
def verify(
self,
metadata,
signature,
artifacts,
*,
public_key=None,
package_id="rustdesk",
release_base_url=OFFICIAL_RELEASE_BASE_URL,
):
args = [
"verify",
"--metadata",
str(metadata),
"--signature",
str(signature),
"--version",
"1.4.6",
"--release-id",
"v1.4.6",
"--package-id",
package_id,
"--release-base-url",
release_base_url,
]
for artifact in artifacts:
args.extend(["--artifact", str(artifact)])
return self.run_script(
*args,
public_key=public_key or self.public_key,
)
def rust_source(self, public_key=None):
key_bytes = base64.b64decode(public_key or self.public_key)
source = self.root / "update_metadata.rs"
source.write_text(
'TrustedUpdateKey { key_id: "2026-ed25519-main", public_key: ['
+ ",".join(str(byte) for byte in key_bytes)
+ "] }",
encoding="utf-8",
)
return source
def test_signs_and_verifies_release_artifacts(self):
exe = self.artifact()
dmg = self.artifact("rustdesk-1.4.6-aarch64.dmg", b"dmg")
specs = [("windows", "x86_64", "exe", exe), ("macos", "aarch64", "dmg", dmg)]
metadata, signature, signed = self.sign(specs)
verified = self.verify(metadata, signature, [exe, dmg])
self.assertEqual(signed.returncode, 0, signed.stderr)
self.assertEqual(verified.returncode, 0, verified.stderr)
data = json.loads(metadata.read_text(encoding="utf-8"))
self.assertEqual(data["release_id"], "v1.4.6")
self.assertEqual({item["file_name"] for item in data["artifacts"]}, {exe.name, dmg.name})
def test_verification_rejects_tampering(self):
artifact = self.artifact()
metadata, signature, _ = self.sign([("windows", "x86_64", "exe", artifact)])
artifact.write_bytes(b"tampered")
self.assertNotEqual(self.verify(metadata, signature, [artifact]).returncode, 0)
artifact.write_bytes(b"rustdesk")
data = json.loads(metadata.read_text(encoding="utf-8"))
data["published_at"] = "2026-05-15T00:00:00Z"
metadata.write_text(json.dumps(data), encoding="utf-8")
self.assertNotEqual(self.verify(metadata, signature, [artifact]).returncode, 0)
def test_verification_rejects_wrong_public_key(self):
artifact = self.artifact()
metadata, signature, _ = self.sign([("windows", "x86_64", "exe", artifact)])
wrong_key = base64.b64encode(b"x" * 32).decode("ascii")
self.assertNotEqual(
self.verify(
metadata,
signature,
[artifact],
public_key=wrong_key,
).returncode,
0,
)
def test_sign_rejects_invalid_release_inputs(self):
artifact = self.artifact()
spec = [("windows", "x86_64", "exe", artifact)]
self.assertNotEqual(self.sign(spec, version="1.4.7")[2].returncode, 0)
for release_id in ("bad/tag", "bad\tid", "bad%zz"):
self.assertNotEqual(self.sign(spec, release_id=release_id)[2].returncode, 0)
self.assertNotEqual(self.sign(spec, seed="invalid")[2].returncode, 0)
duplicate = spec + [("windows", "x86_64", "exe", artifact)]
self.assertNotEqual(self.sign(duplicate)[2].returncode, 0)
def test_signs_and_verifies_custom_release_identity(self):
package_id = "com.example.rustdesk-custom"
release_base_url = "https://updates.example.com/releases/download"
artifact = self.artifact("rustdesk-custom-1.4.6-aarch64.dmg", b"dmg")
metadata, signature, signed = self.sign(
[("macos", "aarch64", "dmg", artifact)],
package_id=package_id,
release_base_url=release_base_url,
)
verified = self.verify(
metadata,
signature,
[artifact],
package_id=package_id,
release_base_url=release_base_url,
)
self.assertEqual(signed.returncode, 0, signed.stderr)
self.assertEqual(verified.returncode, 0, verified.stderr)
data = json.loads(metadata.read_text(encoding="utf-8"))
self.assertEqual(data["package_id"], package_id)
self.assertEqual(
data["artifacts"][0]["url"],
f"{release_base_url}/v1.4.6/{artifact.name}",
)
def test_rejects_unsafe_custom_release_policy(self):
artifact = self.artifact("rustdesk-custom-1.4.6-aarch64.dmg", b"dmg")
spec = [("macos", "aarch64", "dmg", artifact)]
for package_id in ("", "com.example/custom", "com.example custom"):
with self.subTest(package_id=package_id):
self.assertNotEqual(
self.sign(spec, package_id=package_id)[2].returncode,
0,
)
for release_base_url in (
"http://updates.example.com/releases",
"https://user@updates.example.com/releases",
"https://updates.example.com/releases/",
"https://updates.example.com/releases?channel=stable",
"https://updates.example.com/relea\nses",
):
with self.subTest(release_base_url=release_base_url):
self.assertNotEqual(
self.sign(spec, release_base_url=release_base_url)[2].returncode,
0,
)
def test_checks_embedded_public_key(self):
source = self.rust_source()
result = self.run_script(
"check-key",
"--rust-source",
str(source),
seed=self.seed,
public_key=self.public_key,
)
self.assertEqual(result.returncode, 0, result.stderr)
def test_check_key_rejects_invalid_or_mismatched_seed(self):
source = self.rust_source()
invalid_seeds = [
None,
"invalid",
base64.b64encode(b"x" * 31).decode("ascii"),
base64.b64encode(b"x" * 32).decode("ascii"),
]
for seed in invalid_seeds:
with self.subTest(seed=seed):
result = self.run_script(
"check-key",
"--rust-source",
str(source),
seed=seed,
public_key=self.public_key,
)
self.assertNotEqual(result.returncode, 0)
def test_check_key_rejects_invalid_public_key(self):
source = self.rust_source()
invalid_keys = [
None,
"invalid",
base64.b64encode(b"x" * 31).decode("ascii"),
]
for public_key in invalid_keys:
with self.subTest(public_key=public_key):
result = self.run_script(
"check-key",
"--rust-source",
str(source),
seed=self.seed,
public_key=public_key,
)
self.assertNotEqual(result.returncode, 0)
def test_check_key_rejects_mismatched_embedded_key(self):
embedded_key = base64.b64encode(b"x" * 32).decode("ascii")
result = self.run_script(
"check-key",
"--rust-source",
str(self.rust_source(embedded_key)),
seed=self.seed,
public_key=self.public_key,
)
self.assertNotEqual(result.returncode, 0)
if __name__ == "__main__":
unittest.main()
+104
View File
@@ -0,0 +1,104 @@
import plistlib
import socket
import subprocess
import sys
import tempfile
import unittest
from pathlib import Path
REPOSITORY_ROOT = Path(__file__).resolve().parents[2]
MACOS_SOURCE = (REPOSITORY_ROOT / "src/platform/macos.rs").read_text(
encoding="utf-8"
)
DAEMON_SCRIPT = (
REPOSITORY_ROOT / "src/platform/privileges_scripts/update.scpt"
).read_text(encoding="utf-8")
MANUAL_SCRIPT = MACOS_SOURCE.split(
'const PRIVILEGED_UPDATE_BODY: &str = r#"', 1
)[1].split('"#;', 1)[0]
def write_bundle_id(app, bundle_id):
if bundle_id is None:
return
info = app / "Contents/Info.plist"
info.parent.mkdir(parents=True)
info.write_bytes(plistlib.dumps({"CFBundleIdentifier": bundle_id}))
class MacosUpdateScriptTests(unittest.TestCase):
@unittest.skipUnless(sys.platform == "darwin", "requires macOS AppleScript")
def test_daemon_update_rejects_stale_ipc_sockets(self):
with tempfile.TemporaryDirectory(dir="/tmp") as directory:
for check in ("check_service", "check_agent"):
with self.subTest(check=check), socket.socket(
socket.AF_UNIX, socket.SOCK_STREAM
) as listener:
path = str(Path(directory) / check)
listener.bind(path)
listener.listen(1)
script = DAEMON_SCRIPT.split(" set sh to", 1)[0]
script += f" return {check}\nend run\n"
script = script.replace("/tmp/RustDesk-service/ipc_service", path)
script = script.replace("/tmp/RustDesk-$uid/ipc", path)
command = subprocess.check_output(
["osascript", "-e", script, "test", "0", "", ""],
text=True,
timeout=10,
)
command = "launchctl() { echo 'state = running'; }; " + command
args = ["/bin/sh", "-c", command]
self.assertEqual(subprocess.call(args, timeout=10), 0)
listener.setblocking(False)
with self.assertRaises(BlockingIOError):
connection, _ = listener.accept()
connection.close()
listener.close()
self.assertNotEqual(subprocess.call(args, timeout=10), 0)
@unittest.skipUnless(sys.platform == "darwin", "requires macOS AppleScript")
def test_manual_update_requires_matching_bundle_identity(self):
validation = next(
line for line in MANUAL_SCRIPT.splitlines()
if "set validate_verified_app" in line
)
script = "\n".join([
"on run {app_bundle, expected_bundle_id}",
"set app_bundle_q to quoted form of app_bundle",
'set installed_info_q to quoted form of (app_bundle & "/Contents/Info.plist")',
"set expected_bundle_id_q to quoted form of expected_bundle_id",
validation,
"return validate_verified_app",
"end run",
])
directory = tempfile.TemporaryDirectory()
self.addCleanup(directory.cleanup)
root = Path(directory.name)
bundle_id = "com.carriez.rustdesk"
cases = (
("new", None, bundle_id, 0),
("installed", bundle_id, bundle_id, 0),
("wrong_candidate", None, "example.other", 1),
("wrong_destination", "example.other", bundle_id, 1),
)
for name, installed_id, candidate_id, exit_code in cases:
with self.subTest(case=name):
installed = root / name / "installed.app"
candidate = root / name / "candidate.app"
write_bundle_id(installed, installed_id)
write_bundle_id(candidate, candidate_id)
command = subprocess.check_output(
["osascript", "-e", script, str(installed), bundle_id],
text=True, timeout=10,
)
result = subprocess.run(
["/bin/sh", "-c", 'set -e; verified_app="$1"; ' + command,
"update-test", str(candidate)],
text=True, capture_output=True, timeout=10,
)
self.assertEqual(result.returncode, exit_code, result.stderr)
if __name__ == "__main__":
unittest.main()
+74
View File
@@ -0,0 +1,74 @@
import os
import subprocess
import sys
import tempfile
import unittest
from pathlib import Path
SCRIPT = Path(__file__).with_name("generate_update_metadata.py")
class UpdateMetadataCliTests(unittest.TestCase):
def test_sign_and_verify_require_update_identity_policy(self):
commands = (
[
"sign",
"--artifact", "macos", "aarch64", "dmg", "missing.dmg",
"--version", "1.4.6",
"--release-id", "v1.4.6",
"--published-at", "invalid",
"--metadata-out", "metadata.json",
"--signature-out", "signature.json",
],
[
"verify",
"--metadata", "missing.json",
"--signature", "missing.sig",
"--artifact", "missing.dmg",
"--version", "1.4.6",
"--release-id", "v1.4.6",
],
)
for command in commands:
with self.subTest(command=command[0]):
result = subprocess.run(
[sys.executable, str(SCRIPT), *command],
text=True,
capture_output=True,
)
self.assertIn("the following arguments are required", result.stderr)
self.assertIn("--package-id", result.stderr)
self.assertIn("--release-base-url", result.stderr)
def test_sign_rejects_empty_artifact(self):
with tempfile.TemporaryDirectory() as directory:
artifact = Path(directory) / "rustdesk-1.4.6-aarch64.dmg"
artifact.touch()
result = subprocess.run(
[
sys.executable,
str(SCRIPT),
"sign",
"--artifact", "macos", "aarch64", "dmg", str(artifact),
"--version", "1.4.6",
"--release-id", "v1.4.6",
"--package-id", "rustdesk",
"--release-base-url",
"https://github.com/rustdesk/rustdesk/releases/download",
"--published-at", "2026-05-14T00:00:00Z",
"--metadata-out", str(Path(directory) / "metadata.json"),
"--signature-out", str(Path(directory) / "metadata.json.sig"),
],
env=os.environ.copy(),
text=True,
capture_output=True,
)
self.assertNotEqual(0, result.returncode)
self.assertIn("artifact must not be empty", result.stderr)
if __name__ == "__main__":
unittest.main()
+100
View File
@@ -0,0 +1,100 @@
import re
from datetime import datetime
from string import ascii_letters, digits
from urllib.parse import urlsplit
PACKAGE_ID_CHARACTERS = frozenset(ascii_letters + digits + ".-")
RFC3339_TIMESTAMP = re.compile(
r"[0-9]{4}-[0-9]{2}-[0-9]{2}[Tt][0-9]{2}:[0-9]{2}:[0-9]{2}(?:\.[0-9]+)?(?:[Zz]|[+-][0-9]{2}:[0-9]{2})"
)
ARTIFACT_FILE_NAME_PATTERN = re.compile(r"[A-Za-z0-9._-]+")
def validate_release(release_id, version):
if (
not release_id
or not release_id.isascii()
or release_id in {".", ".."}
or any(
char.isspace() or not char.isprintable() or char in "/\\?%#"
for char in release_id
)
):
raise ValueError(f"invalid release id: {release_id}")
match = re.fullmatch(r"v?([0-9]+)\.([0-9]+)\.([0-9]+)", release_id)
if not match:
return
segments = [int(part) for part in match.groups()]
if any(part > 65535 for part in segments) or not any(segments):
raise ValueError(f"invalid release version: {release_id}")
display_version = ".".join(match.groups())
if display_version != version:
raise ValueError(
f"release id {release_id} maps to {display_version}, not {version}"
)
def validate_published_at(value):
if not RFC3339_TIMESTAMP.fullmatch(value):
raise ValueError("published_at must be an RFC 3339 timestamp")
normalized = value[:-1] + "+00:00" if value[-1] in "Zz" else value
try:
datetime.fromisoformat(normalized)
except ValueError as error:
raise ValueError(
"published_at must be an RFC 3339 timestamp"
) from error
def validate_artifact_file_name(file_name):
if (
not isinstance(file_name, str)
or file_name in {".", ".."}
or not ARTIFACT_FILE_NAME_PATTERN.fullmatch(file_name)
):
raise ValueError(f"invalid artifact file name: {file_name}")
def validate_package_id(value):
if (
not isinstance(value, str)
or not value
or not value.isascii()
or any(char not in PACKAGE_ID_CHARACTERS for char in value)
or not any(char.isalnum() for char in value)
):
raise ValueError(f"invalid package id: {value}")
return value
def validate_release_base_url(value):
if (
not isinstance(value, str)
or not value
or not value.isascii()
or any(char.isspace() or not char.isprintable() for char in value)
or value.endswith("/")
or "\\" in value
or "?" in value
or "#" in value
):
raise ValueError(f"invalid release base URL: {value}")
try:
parsed = urlsplit(value)
parsed.port
except ValueError as error:
raise ValueError(f"invalid release base URL: {value}") from error
if (
parsed.scheme != "https"
or parsed.hostname is None
or parsed.username is not None
or parsed.password is not None
):
raise ValueError(
"release base URL must be HTTPS and must not contain credentials"
)
return value
def release_artifact_url(release_base_url, release_id, file_name):
return f"{release_base_url}/{release_id}/{file_name}"
@@ -0,0 +1,7 @@
# Locked for the CPython 3.12 Linux x86_64 release-signing runner.
cryptography==50.0.0 \
--hash=sha256:82148ec5bddac30b51a5b3c1945075f896fa022cb93f8e4a01e9f6ee95292c5f
cffi==2.1.0 \
--hash=sha256:1e9f50d192a3e525b15a75ab5114e442d83d657b7ec29182a991bc9a88fd3a66
pycparser==3.0 \
--hash=sha256:b727414169a36b7d524c1c3e31839a521725078d7b2ff038656844266160a992
-3
View File
@@ -237,6 +237,3 @@ fn validate_input(input: &[f32], channels: usize) -> Result<(), AudioResamplerEr
#[cfg(all(test, not(all(feature = "use_samplerate", not(feature = "use_dasp")))))]
mod tests;
#[cfg(all(test, feature = "use_samplerate", not(feature = "use_dasp")))]
mod samplerate_tests;
-157
View File
@@ -1,157 +0,0 @@
use super::{AudioResampler, AudioResamplerConfig, AudioResamplerError, FixedFrameAudioResampler};
const INPUT_RATE: u32 = 44_100;
const OUTPUT_RATE: u32 = 48_000;
const CHANNELS: u16 = 2;
const INPUT_PACKET_FRAMES: usize = INPUT_RATE as usize / PACKETS_PER_SECOND;
const OUTPUT_PACKET_FRAMES: usize = OUTPUT_RATE as usize / PACKETS_PER_SECOND;
const PACKET_COUNT: usize = 20;
const PACKETS_PER_SECOND: usize = 100;
const MIN_CONTINUITY_PACKETS: usize = 2;
const TONE_FREQUENCY_HZ: f32 = 997.0;
const TONE_AMPLITUDE: f32 = 0.5;
const MAX_BOUNDARY_RESIDUAL: f32 = 0.02;
const INCOMPLETE_SAMPLE_COUNT: usize = 1;
const DOWNSAMPLE_RATE: u32 = 24_000;
const REJECTED_TONE_HZ: f64 = 18_000.0;
const MAX_ALIAS_RMS: f64 = 0.01;
const MIN_PASSBAND_RMS: f64 = 0.3;
fn stereo_tone(frames: usize) -> Vec<f32> {
(0..frames)
.flat_map(|frame| {
let phase =
std::f32::consts::TAU * TONE_FREQUENCY_HZ * frame as f32 / INPUT_RATE as f32;
let sample = TONE_AMPLITUDE * phase.sin();
[sample, sample]
})
.collect()
}
fn maximum_boundary_residual(packets: &[Vec<f32>]) -> f32 {
packets.windows(2).fold(0.0, |maximum, pair| {
let previous = &pair[0];
let current = &pair[1];
let last = previous.len() - CHANNELS as usize;
let penultimate = last - CHANNELS as usize;
(0..CHANNELS as usize).fold(maximum, |maximum, channel| {
let predicted = previous[last + channel]
+ (previous[last + channel] - previous[penultimate + channel]);
maximum.max((current[channel] - predicted).abs())
})
})
}
fn stereo_config() -> AudioResamplerConfig {
AudioResamplerConfig {
input_rate: INPUT_RATE,
output_rate: OUTPUT_RATE,
channels: CHANNELS,
}
}
#[test]
fn moving_capture_resampler_preserves_pending_audio() {
let input = stereo_tone(INPUT_PACKET_FRAMES * PACKET_COUNT);
let packet_samples = INPUT_PACKET_FRAMES * CHANNELS as usize;
let mut expected_resampler =
FixedFrameAudioResampler::new(stereo_config(), OUTPUT_PACKET_FRAMES).unwrap();
let expected: Vec<_> = input
.chunks(packet_samples)
.flat_map(|packet| expected_resampler.process(packet).unwrap())
.collect();
let mut moved_resampler =
FixedFrameAudioResampler::new(stereo_config(), OUTPUT_PACKET_FRAMES).unwrap();
let mut output = moved_resampler.process(&input[..packet_samples]).unwrap();
let remaining = std::thread::spawn(move || {
input[packet_samples..]
.chunks(packet_samples)
.flat_map(|packet| moved_resampler.process(packet).unwrap())
.collect::<Vec<_>>()
})
.join()
.unwrap();
output.extend(remaining);
assert!(output.len() >= MIN_CONTINUITY_PACKETS);
assert!(output
.iter()
.all(|packet| packet.len() == OUTPUT_PACKET_FRAMES * CHANNELS as usize));
assert!(maximum_boundary_residual(&output) <= MAX_BOUNDARY_RESIDUAL);
assert_eq!(output, expected);
}
fn downsampled_rms(input: &[f32]) -> f64 {
let config = AudioResamplerConfig {
output_rate: DOWNSAMPLE_RATE,
..stereo_config()
};
let output_frames = DOWNSAMPLE_RATE as usize / PACKETS_PER_SECOND;
let mut resampler = FixedFrameAudioResampler::new(config, output_frames).unwrap();
let output: Vec<f32> = input
.chunks(INPUT_PACKET_FRAMES * CHANNELS as usize)
.flat_map(|packet| resampler.process(packet).unwrap().into_iter().flatten())
.collect();
assert!(output.len() >= output_frames * CHANNELS as usize * MIN_CONTINUITY_PACKETS);
let mean_square = output
.iter()
.map(|sample| f64::from(*sample).powi(2))
.sum::<f64>()
/ output.len() as f64;
mean_square.sqrt()
}
#[test]
fn capture_downsampling_filters_out_of_band_audio() {
let input: Vec<_> = (0..INPUT_PACKET_FRAMES * PACKET_COUNT)
.flat_map(|frame| {
let phase =
std::f64::consts::TAU * REJECTED_TONE_HZ * frame as f64 / f64::from(INPUT_RATE);
let sample = (f64::from(TONE_AMPLITUDE) * phase.sin()) as f32;
[sample, sample]
})
.collect();
let rms = downsampled_rms(&input);
assert!(
rms < MAX_ALIAS_RMS,
"out-of-band output RMS {rms} exceeded {MAX_ALIAS_RMS}"
);
let input = stereo_tone(INPUT_PACKET_FRAMES * PACKET_COUNT);
let rms = downsampled_rms(&input);
assert!(
rms > MIN_PASSBAND_RMS,
"in-band output RMS {rms} fell below {MIN_PASSBAND_RMS}"
);
}
#[test]
fn samplerate_backend_preserves_streaming_continuity() {
let input = stereo_tone(INPUT_PACKET_FRAMES * PACKET_COUNT);
let mut resampler = AudioResampler::new(stereo_config()).unwrap();
let packets: Vec<_> = input
.chunks(INPUT_PACKET_FRAMES * CHANNELS as usize)
.map(|packet| resampler.process(packet).unwrap())
.filter(|packet| !packet.is_empty())
.collect();
assert!(packets.len() >= MIN_CONTINUITY_PACKETS);
assert!(packets
.iter()
.all(|packet| packet.len() % CHANNELS as usize == 0));
assert!(maximum_boundary_residual(&packets) <= MAX_BOUNDARY_RESIDUAL);
}
#[test]
fn samplerate_backend_reports_incomplete_frame_context() {
let mut resampler = AudioResampler::new(stereo_config()).unwrap();
assert_eq!(
resampler.process(&[0.0]).unwrap_err(),
AudioResamplerError::IncompleteFrame {
samples: INCOMPLETE_SAMPLE_COUNT,
channels: CHANNELS as usize,
}
);
}
-64
View File
@@ -18,8 +18,6 @@ const SECOND_DOWNSAMPLE_PACKET: [f32; 4] = [3.0, 4.0, 5.0, 6.0];
const EXPECTED_DOWNSAMPLED_OUTPUT: [f32; 4] = [0.0, 2.0, 4.0, 6.0];
const PACKETS_PER_SECOND: usize = 100;
const OUTPUT_PACKET_FRAMES: usize = OUTPUT_RATE as usize / PACKETS_PER_SECOND;
const RATE_44_1_KHZ: u32 = 44_100;
const FLOAT_TOLERANCE: f32 = 0.000_001;
const MIN_CONTINUITY_PACKETS: usize = 2;
fn stereo_tone_at_rate(frames: usize, sample_rate: u32) -> Vec<f32> {
@@ -37,11 +35,6 @@ fn stereo_tone(frames: usize) -> Vec<f32> {
stereo_tone_at_rate(frames, INPUT_RATE)
}
fn maximum_tone_prediction_residual(sample_rate: u32) -> f32 {
let half_step = std::f32::consts::PI * TONE_FREQUENCY_HZ / sample_rate as f32;
4.0 * TONE_AMPLITUDE * half_step.sin().powi(2)
}
fn maximum_boundary_residual(chunks: &[Vec<f32>]) -> f32 {
chunks.windows(2).fold(0.0, |maximum, pair| {
let previous = &pair[0];
@@ -89,39 +82,6 @@ fn preserves_decoded_packet_continuity_and_output_ratio() {
}
}
#[test]
fn rejects_incomplete_interleaved_frames() {
let mut resampler = AudioResampler::new(stereo_config()).unwrap();
assert!(resampler.process(&[TONE_AMPLITUDE]).is_err());
}
#[test]
fn interpolates_mono_samples() {
let config = AudioResamplerConfig {
input_rate: UNIT_RATE,
output_rate: DOUBLE_RATE,
channels: MONO_CHANNELS,
};
let mut resampler = AudioResampler::new(config).unwrap();
assert_eq!(
resampler.process(&[0.0, 1.0, 2.0]).unwrap(),
[0.0, 0.5, 1.0, 1.5, 2.0]
);
}
#[test]
fn rejects_zero_rate_configuration() {
let config = AudioResamplerConfig {
input_rate: 0,
output_rate: OUTPUT_RATE,
channels: CHANNELS,
};
assert!(AudioResampler::new(config).is_err());
}
#[test]
fn downsamples_across_packet_boundaries() {
let config = AudioResamplerConfig {
@@ -152,27 +112,3 @@ fn sender_resampler_emits_only_complete_continuous_frames() {
.all(|packet| packet.len() == OUTPUT_PACKET_FRAMES * CHANNELS as usize));
assert!(maximum_boundary_residual(&output) <= MAX_BOUNDARY_RESIDUAL);
}
#[test]
fn sender_downsampling_preserves_packet_continuity() {
let input_packet_frames = RATE_44_1_KHZ as usize / PACKETS_PER_SECOND;
let input = stereo_tone_at_rate(input_packet_frames * CHUNK_COUNT, RATE_44_1_KHZ);
let config = AudioResamplerConfig {
input_rate: RATE_44_1_KHZ,
output_rate: INPUT_RATE,
channels: CHANNELS,
};
let mut resampler =
FixedFrameAudioResampler::new(config, INPUT_RATE as usize / PACKETS_PER_SECOND).unwrap();
let packets: Vec<_> = input
.chunks(input_packet_frames * CHANNELS as usize)
.flat_map(|packet| resampler.process(packet).unwrap())
.collect();
let residual = maximum_boundary_residual(&packets);
assert_eq!(packets.len(), CHUNK_COUNT);
assert!(
residual <= maximum_tone_prediction_residual(INPUT_RATE) + FLOAT_TOLERANCE,
"sender packet boundary residual {residual} exceeded the tone curvature"
);
}
+32 -150
View File
@@ -68,6 +68,7 @@ use hbb_common::{
time::{interval, Duration, Instant},
},
webrtc::WebRTCStream,
websocket::{check_ws, is_ws_endpoint},
AddrMangle, ResultType, Stream,
};
use base::{
@@ -1848,8 +1849,11 @@ impl Client {
conn_type: ConnType,
ipv4: bool,
) -> ResultType<Stream> {
// The proxy's address family does not constrain the relay target.
let relay_server = check_port(relay_server, RELAY_PORT);
let use_ws_proxy = Config::is_proxy() && is_ws_endpoint(&check_ws(&relay_server));
let mut conn = connect_tcp(
ipv4_to_ipv6(check_port(relay_server, RELAY_PORT), ipv4),
ipv4_to_ipv6(relay_server, ipv4 || use_ws_proxy),
CONNECT_TIMEOUT,
)
.await
@@ -2328,41 +2332,6 @@ impl AudioBuffer {
}
}
#[cfg(all(test, not(target_os = "linux")))]
mod audio_buffer_discontinuity_tests {
use super::AudioBuffer;
use std::sync::{
atomic::{AtomicUsize, Ordering},
Arc, Mutex,
};
const BUFFER_CAPACITY: usize = 4;
const BUFFER_LEVELS: usize = 30;
const FIRST_INPUT: [f32; 2] = [0.1, 0.2];
const OVERFLOWING_INPUT: [f32; 3] = [0.3, 0.4, 0.5];
const OVERSIZED_INPUT: [f32; 5] = [0.6, 0.7, 0.8, 0.9, 1.0];
#[test]
fn capacity_discards_signal_discontinuities() {
let audio_buffer = AudioBuffer(
Arc::new(Mutex::new(ringbuf::HeapRb::new(BUFFER_CAPACITY))),
BUFFER_CAPACITY,
[0; BUFFER_LEVELS],
Arc::new(AtomicUsize::new(0)),
);
assert_eq!(audio_buffer.append_pcm2(&FIRST_INPUT), FIRST_INPUT.len());
assert_eq!(audio_buffer.3.load(Ordering::Relaxed), 0);
assert_eq!(
audio_buffer.append_pcm2(&OVERFLOWING_INPUT),
BUFFER_CAPACITY
);
assert_eq!(audio_buffer.3.load(Ordering::Relaxed), 1);
assert_eq!(audio_buffer.append_pcm2(&OVERSIZED_INPUT), BUFFER_CAPACITY);
assert_eq!(audio_buffer.3.load(Ordering::Relaxed), 2);
}
}
impl AudioHandler {
#[cfg(target_os = "linux")]
fn start_audio(&mut self, format0: AudioFormat) -> ResultType<()> {
@@ -4467,6 +4436,32 @@ fn _input_os_password(p: String, activate: bool, interface: impl Interface) {
interface.send(Data::Message(msg_out));
}
/// Auto Login. A peer that can check for its logon or lock screen gets the password and types it
/// itself, only if it is there right then. Keys typed from here land in whatever has focus if the
/// screen is not locked by the time they arrive.
pub fn auto_login(p: String, pi: &PeerInfo, interface: impl Interface) {
if !is_peer_handling_os_login(pi) {
input_os_password(p, true, interface);
return;
}
std::thread::spawn(move || {
activate_os(&interface, true);
std::thread::sleep(Duration::from_millis(1200));
let mut msg_out = Message::new();
msg_out.set_os_login(OSLogin {
password: p,
..Default::default()
});
interface.send(Data::Message(msg_out));
});
}
/// Windows and macOS peers from the 1.5.1 release handle `os_login`.
fn is_peer_handling_os_login(pi: &PeerInfo) -> bool {
(pi.platform == crate::common::PLATFORM_WINDOWS || pi.platform == crate::common::PLATFORM_MACOS)
&& hbb_common::get_version_number(&pi.version) >= hbb_common::get_version_number("1.5.1")
}
#[derive(Copy, Clone)]
struct LoginErrorMsgBox {
msgtype: &'static str,
@@ -5201,26 +5196,6 @@ mod retry_tests {
}
}
#[cfg(test)]
mod port_forward_mux_tests {
use super::*;
#[test]
fn a_login_asks_for_the_tunnel_when_its_mapping_probes() {
let mut lc = LoginConfigHandler::default();
lc.conn_type = ConnType::PORT_FORWARD;
let asks = |lc: &LoginConfigHandler| {
lc.create_login_msg(String::new(), String::new(), vec![])
.login_request()
.port_forward()
.multiplex
};
assert!(!asks(&lc));
lc.port_forward_multiplex = true;
assert!(asks(&lc));
}
}
pub async fn hc_connection(
feedback: i32,
rendezvous_server: String,
@@ -5413,7 +5388,6 @@ pub mod peer_online {
mod tests {
use crate::client::Client;
use hbb_common::rendezvous_proto::IceCandidate;
use hbb_common::tokio;
#[test]
fn accepts_webrtc_ice_by_session_key_only() {
@@ -5426,22 +5400,6 @@ pub mod peer_online {
assert!(Client::is_expected_webrtc_ice_candidate(&ice, "session-a"));
assert!(!Client::is_expected_webrtc_ice_candidate(&ice, "session-b"));
}
#[tokio::test]
async fn test_query_onlines() {
super::query_online_states(
vec![
"152183996".to_owned(),
"165782066".to_owned(),
"155323351".to_owned(),
"460952777".to_owned(),
],
|onlines: Vec<String>, offlines: Vec<String>| {
println!("onlines: {:?}, offlines: {:?}", &onlines, &offlines);
},
)
.await;
}
}
}
@@ -5567,7 +5525,7 @@ async fn udp_nat_connect(
#[cfg(test)]
mod webrtc_race_tests {
use super::{race_transports_prefer_webrtc, request_allows_tcp_punch};
use super::race_transports_prefer_webrtc;
use hbb_common::{
anyhow::anyhow,
futures::future::{BoxFuture, FutureExt},
@@ -5594,12 +5552,6 @@ mod webrtc_race_tests {
const NOT_P2P: fn(&&'static str) -> bool = |_| false;
#[test]
fn webrtc_request_never_reuses_its_signaling_socket_for_tcp_punch() {
assert!(request_allows_tcp_punch(""));
assert!(!request_allows_tcp_punch("webrtc://offer"));
}
// A direct result must win even when it lands first — the LAN ordering, where ICE beats the
// relay's TCP connect. Parking it as if it were a relay commits the relay on arrival.
#[tokio::test]
@@ -5657,32 +5609,6 @@ mod webrtc_race_tests {
assert_eq!(got, "preferred-relay");
}
#[tokio::test]
async fn relay_from_preferred_branch_committed_when_window_expires() {
let got = race_transports_prefer_webrtc(
ok_after(10, "preferred-relay"),
vec![ok_after(60_000, "too-slow")],
100,
NOT_P2P,
)
.await
.unwrap();
assert_eq!(got, "preferred-relay");
}
#[tokio::test]
async fn preference_window_starts_when_relay_is_ready() {
let got = race_transports_prefer_webrtc(
ok_after(350, "webrtc"),
vec![ok_after(250, "relay")],
200,
NOT_P2P,
)
.await
.unwrap();
assert_eq!(got, "webrtc");
}
#[tokio::test]
async fn unfinished_ipv6_still_beats_held_relay() {
let start = Instant::now();
@@ -5713,36 +5639,6 @@ mod webrtc_race_tests {
assert_eq!(got, "ipv6");
}
// A relay is held with a direct attempt racing behind it, then WebRTC fails. The held relay
// must not be committed while the direct attempt is still in flight.
#[tokio::test]
async fn held_relay_waits_for_racing_direct_when_webrtc_fails() {
let got = race_transports_prefer_webrtc(
err_after(50, "webrtc dead"),
vec![ok_after(10, "relay"), ok_after(100, "ipv6")],
60_000,
|t| *t == "ipv6",
)
.await
.unwrap();
assert_eq!(got, "ipv6");
}
// Both attempts error, but a relay was parked before they did — it is the outcome, not a
// composed error.
#[tokio::test]
async fn held_relay_survives_both_errors() {
let got = race_transports_prefer_webrtc(
err_after(50, "webrtc dead"),
vec![ok_after(10, "relay"), err_after(100, "ipv6 dead")],
60_000,
|t| *t == "ipv6",
)
.await
.unwrap();
assert_eq!(got, "relay");
}
#[tokio::test]
async fn held_relay_committed_when_window_expires() {
let start = Instant::now();
@@ -5813,20 +5709,6 @@ mod webrtc_race_tests {
assert_eq!(got, "ipv6");
assert!(start.elapsed() < Duration::from_secs(5));
}
#[tokio::test]
async fn both_failing_compose_error() {
let err = race_transports_prefer_webrtc(
err_after(10, "webrtc dead"),
vec![err_after(20, "relay dead")],
1_000,
NOT_P2P,
)
.await
.unwrap_err()
.to_string();
assert!(err.contains("webrtc dead") && err.contains("relay dead"), "{}", err);
}
}
#[cfg(test)]
+1 -102
View File
@@ -1,7 +1,4 @@
use super::{
AudioPlaybackConfig, AudioPlaybackError, AudioPlaybackRecovery, AudioPlaybackStatus,
AudioPlaybackWriter,
};
use super::{AudioPlaybackConfig, AudioPlaybackRecovery, AudioPlaybackWriter};
use ringbuf::{ring_buffer::RbBase, Rb};
use std::{
sync::{atomic::Ordering, mpsc, Arc, Mutex},
@@ -93,31 +90,6 @@ fn smooths_underflow_and_explicit_audio_discontinuities() {
}
}
#[test]
fn validates_configuration_and_frame_size() {
let invalid_config = AudioPlaybackConfig {
sample_rate: 0,
channels: CHANNELS,
};
assert_eq!(
AudioPlaybackRecovery::new(invalid_config).err(),
Some(AudioPlaybackError::InvalidConfig(invalid_config))
);
let config = AudioPlaybackConfig {
sample_rate: SAMPLE_RATE,
channels: CHANNELS,
};
let mut recovery = AudioPlaybackRecovery::new(config).unwrap();
assert_eq!(
recovery.process_frame(Some(&[0.5])).err(),
Some(AudioPlaybackError::IncompleteFrame {
samples: 1,
channels: CHANNELS,
})
);
}
const CALLBACK_SAMPLES: usize = 64;
const CALLBACK_TIMEOUT: Duration = Duration::from_secs(2);
const DISCARD_GENERATION: usize = 1;
@@ -187,76 +159,3 @@ fn playback_contention_preserves_queued_audio_and_recovers_after_release() {
assert_eq!(&output[samples - CHANNELS..], &OPPOSITE_ACTIVE_FRAME);
assert_eq!(buffer.lock().unwrap().occupied_len(), 0);
}
#[test]
fn poisoned_playback_buffer_reports_once_without_panicking_in_the_callback() {
let buffer = Arc::new(Mutex::new(ringbuf::HeapRb::new(CALLBACK_SAMPLES)));
let config = AudioPlaybackConfig {
sample_rate: SAMPLE_RATE,
channels: CHANNELS,
};
let mut writer =
AudioPlaybackWriter::new(config, buffer.clone(), Arc::new(super::AtomicUsize::new(0)))
.unwrap();
assert!(std::thread::spawn(move || {
let _guard = buffer.lock().unwrap();
panic!("Injected PCM buffer failure");
})
.join()
.is_err());
let mut output = [ACTIVE_FRAME[0]; CALLBACK_SAMPLES];
crate::audio_resampler::allocation_tests::assert_no_allocations(|| {
writer.write_output(&mut output);
});
assert_eq!(output, [0.0; CALLBACK_SAMPLES]);
assert!(!writer.status.ready.load(Ordering::Acquire));
assert!(writer.status.buffer_poisoned.load(Ordering::Relaxed));
writer.status.report_errors();
writer.write_output(&mut output);
assert!(!writer.status.buffer_poisoned.load(Ordering::Relaxed));
assert_eq!(writer.status.contentions.load(Ordering::Relaxed), 0);
assert!(!writer.status.ready.load(Ordering::Acquire));
}
#[test]
fn contention_counts_accumulate_until_the_next_report() {
let status = AudioPlaybackStatus::default();
status.report_errors();
status.contentions.fetch_add(1, Ordering::Relaxed);
status.report_errors();
assert_eq!(status.contentions.load(Ordering::Relaxed), 0);
let mut total = 0;
for callbacks in [3, 7, 2] {
total += callbacks;
status.contentions.fetch_add(callbacks, Ordering::Relaxed);
status.report_errors();
assert_eq!(status.contentions.load(Ordering::Relaxed), total);
}
status.buffer_poisoned.store(true, Ordering::Relaxed);
status.report_errors();
assert!(!status.buffer_poisoned.load(Ordering::Relaxed));
assert_eq!(status.contentions.load(Ordering::Relaxed), total);
std::thread::sleep(super::AUDIO_PLAYBACK_LOG_INTERVAL);
status.report_errors();
assert_eq!(status.contentions.load(Ordering::Relaxed), 0);
}
#[test]
fn contention_reporting_is_independent_between_playbacks() {
let first = AudioPlaybackStatus::default();
let second = AudioPlaybackStatus::default();
for status in [&first, &second] {
status.contentions.fetch_add(1, Ordering::Relaxed);
status.report_errors();
assert_eq!(status.contentions.load(Ordering::Relaxed), 0);
}
for status in [&first, &second] {
status.contentions.fetch_add(1, Ordering::Relaxed);
status.report_errors();
assert_eq!(status.contentions.load(Ordering::Relaxed), 1);
}
}
+1 -84
View File
@@ -2767,7 +2767,7 @@ impl<T: InvokeUiSession> Remote<T> {
/// A shape that decoded, still compressed, under the id the UI knows it by. Copied once it
/// decoded: the message's colors may be a slice of a larger received buffer, which a clone
/// would keep alive.
#[cfg(any(feature = "flutter", test))]
#[cfg(feature = "flutter")]
fn cursor_shape(id: u64, cd: &CursorData, compressed: &[u8]) -> CursorData {
CursorData {
id,
@@ -3022,74 +3022,6 @@ mod cursor_dedupe_tests {
assert_eq!(dedupe.id(2), first);
assert_eq!(dedupe.id(1), first);
}
#[test]
fn the_hotspot_is_part_of_the_shape() {
let a = CursorDedupe::name(&shape(1, 0, b"arrow"));
let b = CursorDedupe::name(&shape(2, 1, b"arrow"));
assert_ne!(a, b);
}
#[test]
fn a_reused_handle_names_its_latest_shape() {
let mut dedupe = CursorDedupe::default();
dedupe.record(1, CursorDedupe::name(&shape(1, 0, b"arrow")));
let beam = CursorDedupe::name(&shape(1, 0, b"beam"));
dedupe.record(1, beam);
assert_eq!(dedupe.id(1), beam);
}
#[test]
fn a_rejected_shape_names_its_handle_and_is_never_decoded() {
let mut dedupe = CursorDedupe::default();
let arrow = CursorDedupe::name(&shape(7, 0, b"arrow"));
dedupe.record(7, arrow);
let beam = CursorDedupe::name(&shape(8, 0, b"beam"));
dedupe.record(8, beam);
let broken = CursorDedupe::name(&shape(7, 0, b"broken"));
assert_eq!(
dedupe.rejected(7, broken),
broken,
"not the shape it named before"
);
assert_eq!(
dedupe.id(7),
broken,
"nor when the handle is selected again"
);
assert_eq!(dedupe.id(8), beam, "another handle keeps its shape");
assert!(!dedupe.has_decoded(broken));
assert!(
dedupe.has_decoded(arrow),
"kept for a handle that brings it again"
);
dedupe.record(7, arrow);
assert_eq!(dedupe.id(7), arrow);
}
#[test]
fn a_shape_rejected_under_handles_never_seen_files_nothing() {
let mut dedupe = CursorDedupe::default();
let broken = CursorDedupe::name(&shape(0, 0, b"broken"));
for handle in 0..1000 {
assert_eq!(dedupe.rejected(handle, broken), broken);
}
assert!(dedupe.ids.is_empty());
assert!(!dedupe.has_decoded(broken));
}
#[test]
fn an_id_the_peer_never_sent_is_passed_on() {
assert_eq!(CursorDedupe::default().id(7), 7);
}
#[test]
fn peers_from_1_5_0_name_cursors_by_content() {
use hbb_common::get_version_number as v;
assert!(!crate::is_peer_naming_cursors_by_content(v("1.4.9")));
assert!(crate::is_peer_naming_cursors_by_content(v("1.5.0")));
assert!(crate::is_peer_naming_cursors_by_content(v("1.5.1")));
}
}
#[cfg(test)]
@@ -3107,21 +3039,6 @@ mod kept_cursor_tests {
}
}
#[test]
fn a_kept_shape_is_a_copy_under_the_ui_id() {
let mut cd = compressed(4, 4);
cd.hotx = 1;
let kept = cursor_shape(42, &cd, &cd.colors);
assert_eq!(kept.id, 42);
assert_eq!((kept.hotx, kept.width, kept.height), (1, 4, 4));
assert_eq!(kept.colors, cd.colors);
assert_ne!(
kept.colors.as_ptr(),
cd.colors.as_ptr(),
"not a view of the received buffer"
);
}
#[test]
fn a_kept_shape_is_checked_again_when_it_is_read() {
assert_eq!(kept_cursor_rgba(compressed(4, 4)).unwrap().colors.len(), 64);
@@ -5,9 +5,6 @@ use crate::client::{
use cpal::StreamError;
use crossbeam_queue::SegQueue;
use hbb_common::tokio::time::Instant;
use std::time::Duration;
const AFTER_COOLDOWN: Duration = Duration::from_secs(2);
type PendingOutput = (
Arc<AtomicBool>,
@@ -82,27 +79,6 @@ fn unconfirmed_start_retries_without_callback_or_error() {
});
}
#[test]
fn already_terminal_candidate_cannot_replace_compatible_output() {
let (mut handler, dropped) = recovery_handler();
let candidate_dropped = Arc::new(AtomicBool::new(false));
let old_buffer = handler.audio_buffer.0.clone();
handler.handle_format_with_start(format(INPUT_RATE, CHANNELS), |candidate, _| {
install_output(candidate, candidate_dropped.clone());
candidate
.playback_recovery
.errors
.push(StreamError::DeviceNotAvailable);
Ok(())
});
assert!(!dropped.load(Ordering::SeqCst));
assert!(candidate_dropped.load(Ordering::SeqCst));
assert!(Arc::ptr_eq(&old_buffer, &handler.audio_buffer.0));
handler.recover_playback_with(Instant::now() + AFTER_COOLDOWN, |_, _| {
panic!("Compatible active output must not be reopened")
});
}
#[test]
fn pending_output_keeps_playing_and_transfers_decoder_history_on_commit() {
let (mut handler, old_dropped) = recovery_handler();
@@ -157,23 +133,6 @@ fn rollback_keeps_the_restarted_decoders_accumulated_history() {
);
}
#[test]
fn later_compatible_format_retires_only_the_pending_attempt() {
let (mut handler, old_dropped) = recovery_handler();
let (first_dropped, _, first_errors) = begin_pending(&mut handler);
let (second_dropped, second_status, _) = begin_pending(&mut handler);
assert!(first_dropped.load(Ordering::SeqCst));
assert!(!old_dropped.load(Ordering::SeqCst));
first_errors.push(StreamError::DeviceNotAvailable);
second_status.ready.store(true, Ordering::Release);
handler.recover_playback_with(Instant::now(), |_, _| {
panic!("Retired attempt affected current output")
});
assert!(old_dropped.load(Ordering::SeqCst));
assert!(!second_dropped.load(Ordering::SeqCst));
assert!(Arc::ptr_eq(&second_status, &handler.playback_status));
}
#[test]
fn both_outputs_failing_retains_format_and_paces_recovery() {
let (mut handler, old_dropped) = recovery_handler();
@@ -194,33 +153,3 @@ fn both_outputs_failing_retains_format_and_paces_recovery() {
});
assert_eq!(attempts, 1);
}
#[test]
fn superseding_format_keeps_ready_candidate_when_active_output_failed() {
let (mut handler, old_dropped) = recovery_handler();
let old_errors = handler.playback_recovery.errors.clone();
let (candidate_dropped, candidate_status, _) = begin_pending(&mut handler);
candidate_status.ready.store(true, Ordering::Release);
old_errors.push(StreamError::DeviceNotAvailable);
handler.handle_format_with_start(format(INPUT_RATE, CHANNELS), failed_output);
assert!(!candidate_dropped.load(Ordering::SeqCst));
assert!(old_dropped.load(Ordering::SeqCst));
assert!(Arc::ptr_eq(&candidate_status, &handler.playback_status));
assert!(handler.audio_decoder.is_some());
assert!(handler.playback_recovery.retry_at.is_none());
}
#[test]
fn superseding_format_preserves_failure_when_both_outputs_failed() {
let (mut handler, old_dropped) = recovery_handler();
let old_errors = handler.playback_recovery.errors.clone();
let (candidate_dropped, status, errors) = begin_pending(&mut handler);
status.ready.store(true, Ordering::Release);
old_errors.push(StreamError::DeviceNotAvailable);
errors.push(StreamError::DeviceNotAvailable);
handler.handle_format_with_start(format(INPUT_RATE, CHANNELS), failed_output);
assert!(candidate_dropped.load(Ordering::SeqCst));
assert!(old_dropped.load(Ordering::SeqCst));
assert!(handler.audio_stream.is_none());
assert!(handler.playback_recovery.retry_at.is_some());
}
+172 -402
View File
@@ -37,7 +37,7 @@ use hbb_common::{
use crate::{
hbbs_http::{create_http_client_async, get_url_for_tls},
ui_interface::{get_api_server as ui_get_api_server, get_option, is_installed, set_option},
ui_interface::{get_api_server as ui_get_api_server, get_option, set_option},
};
#[derive(Debug, Eq, PartialEq)]
@@ -1020,39 +1020,94 @@ pub fn check_software_update() {
}
}
// No need to check `danger_accept_invalid_cert` for now.
// Because the url is always `https://api.rustdesk.com/version/latest`.
#[tokio::main(flavor = "current_thread")]
pub async fn do_check_software_update() -> hbb_common::ResultType<()> {
let (request, url) =
hbb_common::version_check_request(hbb_common::VER_TYPE_RUSTDESK_CLIENT.to_string());
let proxy_conf = Config::get_socks();
let tls_url = get_url_for_tls(&url, &proxy_conf);
let tls_type = get_cached_tls_type(tls_url);
let is_tls_not_cached = tls_type.is_none();
let tls_type = tls_type.unwrap_or(TlsType::Rustls);
let client = create_http_client_async(tls_type, false);
let latest_release_response = match client.post(&url).json(&request).send().await {
Ok(resp) => {
upsert_tls_cache(tls_url, tls_type, false);
resp
}
Err(err) => {
if is_tls_not_cached && err.is_request() {
let tls_type = TlsType::NativeTls;
let client = create_http_client_async(tls_type, false);
let resp = client.post(&url).json(&request).send().await?;
upsert_tls_cache(tls_url, tls_type, false);
resp
} else {
return Err(err.into());
}
}
pub(crate) fn release_id_from_update_url(update_url: &str) -> ResultType<String> {
let url = url::Url::parse(update_url)?;
if url.scheme() != "https" || url.host_str() != Some("github.com") {
bail!(
"Update URL is not a GitHub HTTPS release URL: {}",
update_url
);
}
if url_has_explicit_port(update_url)
|| url.port().is_some()
|| !url.username().is_empty()
|| url.password().is_some()
{
bail!(
"Update URL must not contain credentials or an explicit port: {}",
update_url
);
}
if url.query().is_some() || url.fragment().is_some() {
bail!(
"Update URL must not contain query or fragment: {}",
update_url
);
}
let Some(segments) = url.path_segments() else {
bail!("Update URL has no path: {}", update_url);
};
let bytes = latest_release_response.bytes().await?;
let segments = segments.collect::<Vec<_>>();
let release_id = match segments.as_slice() {
["rustdesk", "rustdesk", "releases", "tag", release_id] => *release_id,
["rustdesk", "rustdesk", "releases", "tag", release_id, ""] => *release_id,
_ => bail!(
"Update URL is not a RustDesk release tag URL: {}",
update_url
),
};
if release_id.is_empty()
|| release_id == "."
|| release_id == ".."
|| release_id.contains([' ', '/', '\\', '?', '#'])
|| release_id.contains('%')
{
bail!("Update URL has no release id: {}", update_url);
}
Ok(release_id.to_owned())
}
pub(crate) fn url_has_explicit_port(raw_url: &str) -> bool {
let Some((_, rest)) = raw_url.split_once("://") else {
return false;
};
let authority = rest
.split(|c| matches!(c, '/' | '?' | '#'))
.next()
.unwrap_or_default();
let host_port = authority.rsplit('@').next().unwrap_or(authority);
host_port.rsplit_once(':').is_some()
}
pub(crate) fn display_version_from_release_id(release_id: &str) -> ResultType<String> {
let display_version = release_id.strip_prefix('v').unwrap_or(release_id);
let segments = display_version.split('.').collect::<Vec<_>>();
if segments.len() != 3
|| segments.iter().any(|segment| {
segment.is_empty()
|| !segment.chars().all(|c| c.is_ascii_digit())
|| segment.parse::<u16>().is_err()
})
{
bail!("Release id is not a stable display version: {}", release_id);
}
if get_version_number(display_version) <= 0 {
bail!("Release id has invalid display version: {}", release_id);
}
Ok(display_version.to_owned())
}
fn clear_software_update_url() {
let mut update_url = SOFTWARE_UPDATE_URL.lock().unwrap();
*update_url = String::new();
}
fn process_software_update_check_response(bytes: Bytes) -> ResultType<()> {
let resp: hbb_common::VersionCheckResponse = serde_json::from_slice(&bytes)?;
let response_url = resp.url;
let latest_release_version = response_url.rsplit('/').next().unwrap_or_default();
let release_id = release_id_from_update_url(&response_url)?;
let latest_release_version = display_version_from_release_id(&release_id)?;
if get_version_number(&latest_release_version) > get_version_number(crate::VERSION) {
#[cfg(feature = "flutter")]
@@ -1066,11 +1121,60 @@ pub async fn do_check_software_update() -> hbb_common::ResultType<()> {
}
*SOFTWARE_UPDATE_URL.lock().unwrap() = response_url;
} else {
*SOFTWARE_UPDATE_URL.lock().unwrap() = "".to_string();
clear_software_update_url();
}
Ok(())
}
// No need to check `danger_accept_invalid_cert` for now.
// Because the url is always `https://api.rustdesk.com/version/latest`.
#[tokio::main(flavor = "current_thread")]
pub async fn do_check_software_update() -> hbb_common::ResultType<()> {
let (request, url) =
hbb_common::version_check_request(hbb_common::VER_TYPE_RUSTDESK_CLIENT.to_string());
let proxy_conf = Config::get_socks();
let tls_url = get_url_for_tls(&url, &proxy_conf);
let tls_type = get_cached_tls_type(tls_url);
let is_tls_not_cached = tls_type.is_none();
let tls_type = tls_type.unwrap_or(TlsType::Rustls);
let client = create_http_client_async(tls_type, false);
let latest_release_response: ResultType<_> = match client.post(&url).json(&request).send().await
{
Ok(resp) => Ok((tls_type, resp)),
Err(err) => {
if is_tls_not_cached && err.is_request() {
let tls_type = TlsType::NativeTls;
let client = create_http_client_async(tls_type, false);
match client.post(&url).json(&request).send().await {
Ok(resp) => Ok((tls_type, resp)),
Err(err) => Err(err.into()),
}
} else {
Err(err.into())
}
}
};
let response_bytes = match latest_release_response {
Ok((used_tls_type, response)) => {
upsert_tls_cache(tls_url, used_tls_type, false);
let status = response.status();
if !status.is_success() {
Err(anyhow!(
"Software update check failed with HTTP status: {status}"
))
} else {
response.bytes().await.map_err(|err| err.into())
}
}
Err(err) => Err(err),
};
let result = response_bytes.and_then(process_software_update_check_response);
if result.is_err() {
clear_software_update_url();
}
result
}
#[inline]
pub fn get_app_name() -> String {
hbb_common::config::APP_NAME.read().unwrap().clone()
@@ -2947,6 +3051,42 @@ mod tests {
};
use std::collections::HashSet;
#[test]
fn parses_stable_rustdesk_release_url() {
let update_url = "https://github.com/rustdesk/rustdesk/releases/tag/v1.4.6";
assert_eq!(release_id_from_update_url(update_url).unwrap(), "v1.4.6");
assert_eq!(display_version_from_release_id("v1.4.6").unwrap(), "1.4.6");
assert_eq!(
release_id_from_update_url(&format!("{update_url}/")).unwrap(),
"v1.4.6"
);
}
#[test]
fn rejects_untrusted_release_urls_and_unstable_versions() {
for update_url in [
"http://github.com/rustdesk/rustdesk/releases/tag/v1.4.6",
"https://github.com:8443/rustdesk/rustdesk/releases/tag/v1.4.6",
"https://github.com:443/rustdesk/rustdesk/releases/tag/v1.4.6",
"https://user@github.com/rustdesk/rustdesk/releases/tag/v1.4.6",
"https://example.com/rustdesk/rustdesk/releases/tag/v1.4.6",
"https://github.com/other/rustdesk/releases/tag/v1.4.6",
"https://github.com/rustdesk/other/releases/tag/v1.4.6",
"https://github.com/rustdesk/rustdesk/releases/download/v1.4.6/rustdesk.exe",
"https://github.com/rustdesk/rustdesk/releases/tag/v1.4.6?x=1",
"https://github.com/rustdesk/rustdesk/releases/tag/v1.4.6#asset",
"https://github.com/rustdesk/rustdesk/releases/tag/v1.4.6/extra",
"https://github.com/rustdesk/rustdesk/releases/tag/v1%2F4%2F6",
"https://github.com/rustdesk/rustdesk/releases/tag/%2e%2e",
] {
assert!(release_id_from_update_url(update_url).is_err());
}
for release_id in ["v1.4.6-rc1", "nightly", "v9223372036854775807.1.1"] {
assert!(display_version_from_release_id(release_id).is_err());
}
}
#[test]
fn a_cursor_content_id_fits_a_web_client_number() {
const MAX_SAFE_INTEGER: u64 = (1 << 53) - 1;
@@ -3033,55 +3173,6 @@ mod tests {
}
}
// ThrottledInterval tick at the same time as tokio interval, if no sleeps
#[allow(non_snake_case)]
#[tokio::test]
async fn test_RustDesk_interval() {
let base_intervals = [interval_maker, interval_at_maker];
for maker in base_intervals.into_iter() {
let mut tokio_timer = maker();
let mut tokio_times = Vec::new();
let mut timer = rustdesk_interval(maker());
let mut times = Vec::new();
loop {
tokio::select! {
_ = timer.tick() => {
if tokio_times.len() >= 10 && times.len() >= 10 {
break;
}
times.push(get_timestamp_secs());
}
_ = tokio_timer.tick() => {
if tokio_times.len() >= 10 && times.len() >= 10 {
break;
}
tokio_times.push(get_timestamp_secs());
}
}
}
assert_eq!(times, tokio_times);
}
}
#[tokio::test]
async fn test_tokio_time_interval_sleep() {
let mut timer = interval_maker();
let mut times = Vec::new();
sleep(Duration::from_secs(3)).await;
loop {
tokio::select! {
_ = timer.tick() => {
times.push(get_timestamp_secs());
if times.len() == 5 {
break;
}
}
}
}
let times2: HashSet<u128> = HashSet::from_iter(times.clone());
assert_eq!(times.len(), times2.len() + 3);
}
// ThrottledInterval tick less times than tokio interval, if there're sleeps
#[allow(non_snake_case)]
#[tokio::test]
@@ -3103,72 +3194,11 @@ mod tests {
}
// No multiple ticks in the `interval` time.
// Values in "times" are unique and are less than normal tokio interval.
// See previous test (test_tokio_time_interval_sleep) for comparison.
let times2: HashSet<u128> = HashSet::from_iter(times.clone());
assert_eq!(times.len(), times2.len(), "test: {}", i);
}
}
#[test]
fn test_duration_multiplication() {
let dur = Duration::from_secs(1);
assert_eq!(dur * 2, Duration::from_secs(2));
assert_eq!(
Duration::from_secs_f64(dur.as_secs_f64() * 0.9),
Duration::from_millis(900)
);
assert_eq!(
Duration::from_secs_f64(dur.as_secs_f64() * 0.923),
Duration::from_millis(923)
);
assert_eq!(
Duration::from_secs_f64(dur.as_secs_f64() * 0.923 * 1e-3),
Duration::from_micros(923)
);
assert_eq!(
Duration::from_secs_f64(dur.as_secs_f64() * 0.923 * 1e-6),
Duration::from_nanos(923)
);
assert_eq!(
Duration::from_secs_f64(dur.as_secs_f64() * 0.923 * 1e-9),
Duration::from_nanos(1)
);
assert_eq!(
Duration::from_secs_f64(dur.as_secs_f64() * 0.5 * 1e-9),
Duration::from_nanos(1)
);
assert_eq!(
Duration::from_secs_f64(dur.as_secs_f64() * 0.499 * 1e-9),
Duration::from_nanos(0)
);
}
#[test]
fn test_is_public() {
// Test URLs containing "rustdesk.com/"
assert!(is_public("https://rustdesk.com/"));
assert!(is_public("https://www.rustdesk.com/"));
assert!(is_public("https://api.rustdesk.com/v1"));
assert!(is_public("https://API.RUSTDESK.COM/v1"));
assert!(is_public("https://rustdesk.com/path"));
// Test URLs ending with "rustdesk.com"
assert!(is_public("rustdesk.com"));
assert!(is_public("https://rustdesk.com"));
assert!(is_public("https://RustDesk.com"));
assert!(is_public("http://www.rustdesk.com"));
assert!(is_public("https://api.rustdesk.com"));
// Test non-public URLs
assert!(!is_public("https://example.com"));
assert!(!is_public("https://custom-server.com"));
assert!(!is_public("http://192.168.1.1"));
assert!(!is_public("localhost"));
assert!(!is_public("https://rustdesk.computer.com"));
assert!(!is_public("rustdesk.comhello.com"));
}
#[test]
fn test_is_public_matches_rustdesk_root_domain() {
assert!(is_public("rustdesk.com/"));
@@ -3207,112 +3237,6 @@ 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);
impl Drop for RestoreCustomRendezvousServer {
fn drop(&mut self) {
Config::set_option(
keys::OPTION_CUSTOM_RENDEZVOUS_SERVER.to_string(),
self.0.clone(),
);
}
}
let _restore = RestoreCustomRendezvousServer(Config::get_option(
keys::OPTION_CUSTOM_RENDEZVOUS_SERVER,
));
Config::set_option(
keys::OPTION_CUSTOM_RENDEZVOUS_SERVER.to_string(),
"1:2".to_string(),
);
assert_eq!(get_tcp_proxy_addr(), format!("[1:2]:{RENDEZVOUS_PORT}"));
}
#[tokio::test]
async fn test_http_request_via_tcp_proxy_rejects_invalid_header_json() {
let result = http_request_via_tcp_proxy("not a url", "get", None, "{").await;
assert!(result.is_err());
}
#[tokio::test]
async fn test_http_request_via_tcp_proxy_rejects_non_object_header_json() {
let err = http_request_via_tcp_proxy("not a url", "get", None, "[]")
.await
.unwrap_err()
.to_string();
assert!(err.contains("HTTP header information parsing failed!"));
}
#[test]
fn test_parse_json_header_entries_preserves_single_content_type() {
let headers = parse_json_header_entries(
r#"{"Content-Type":"text/plain","Authorization":"Bearer token"}"#,
)
.unwrap();
assert_eq!(
headers
.iter()
.filter(|entry| entry.name.eq_ignore_ascii_case("Content-Type"))
.count(),
1
);
assert_eq!(
headers
.iter()
.find(|entry| entry.name.eq_ignore_ascii_case("Content-Type"))
.map(|entry| entry.value.as_str()),
Some("text/plain")
);
}
#[test]
fn test_parse_json_header_entries_does_not_add_default_content_type() {
let headers = parse_json_header_entries(r#"{"Authorization":"Bearer token"}"#).unwrap();
assert!(!headers
.iter()
.any(|entry| entry.name.eq_ignore_ascii_case("Content-Type")));
}
#[test]
fn test_parse_simple_header_respects_custom_content_type() {
let headers = parse_simple_header("Content-Type: text/plain");
assert_eq!(
headers
.iter()
.filter(|entry| entry.name.eq_ignore_ascii_case("Content-Type"))
.count(),
1
);
assert_eq!(
headers
.iter()
.find(|entry| entry.name.eq_ignore_ascii_case("Content-Type"))
.map(|entry| entry.value.as_str()),
Some("text/plain")
);
}
#[test]
fn test_parse_simple_header_preserves_non_content_type_header() {
let headers = parse_simple_header("Authorization: Bearer token");
@@ -3337,22 +3261,6 @@ mod tests {
);
}
#[test]
fn test_tcp_proxy_log_target_redacts_query_only() {
assert_eq!(
tcp_proxy_log_target("https://example.com/api/heartbeat?token=secret"),
"https://example.com/api/heartbeat"
);
}
#[test]
fn test_tcp_proxy_log_target_brackets_ipv6_host_with_port() {
assert_eq!(
tcp_proxy_log_target("https://[2001:db8::1]:21114/api/heartbeat?token=secret"),
"https://[2001:db8::1]:21114/api/heartbeat"
);
}
#[test]
fn test_http_proxy_response_to_json() {
let mut resp = HttpProxyResponse {
@@ -3381,38 +3289,6 @@ mod tests {
assert!(err.contains("TCP proxy error: dial failed"));
}
#[test]
fn test_mouse_event_constants_and_mask_layout() {
use super::input::*;
// Verify MOUSE_TYPE constants are unique and within the mask range.
let types = [
MOUSE_TYPE_MOVE,
MOUSE_TYPE_DOWN,
MOUSE_TYPE_UP,
MOUSE_TYPE_WHEEL,
MOUSE_TYPE_TRACKPAD,
MOUSE_TYPE_MOVE_RELATIVE,
];
let mut seen = std::collections::HashSet::new();
for t in types.iter() {
assert!(seen.insert(*t), "Duplicate mouse type: {}", t);
assert_eq!(
*t & MOUSE_TYPE_MASK,
*t,
"Mouse type {} exceeds mask {}",
t,
MOUSE_TYPE_MASK
);
}
// The mask layout is: lower 3 bits for type, upper bits for buttons (shifted by 3).
let combined_mask = MOUSE_TYPE_DOWN | ((MOUSE_BUTTON_LEFT | MOUSE_BUTTON_RIGHT) << 3);
assert_eq!(combined_mask & MOUSE_TYPE_MASK, MOUSE_TYPE_DOWN);
assert_eq!(combined_mask >> 3, MOUSE_BUTTON_LEFT | MOUSE_BUTTON_RIGHT);
}
/// A stand-in rendezvous server on loopback: accepts one connection and hands it to `serve`.
async fn rendezvous_stub<F, Fut>(serve: F) -> String
where
@@ -3483,105 +3359,6 @@ mod tests {
assert!(!conn.is_secured());
}
#[tokio::test]
async fn test_secure_tcp_required_refuses_a_closed_connection() {
let (key, _) = server_key();
let host = rendezvous_stub(|s| async move { drop(s) }).await;
let mut conn = connect(&host).await;
assert!(secure_tcp_required(&mut conn, &key).await.is_err());
assert!(!conn.is_secured());
}
#[tokio::test]
async fn test_secure_tcp_required_accepts_a_completed_exchange() {
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()],
..Default::default()
});
s.send(&msg).await.unwrap();
// The client's reply must decode to a key with the ephemeral secret half.
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");
};
hbb_common::tcp::Encrypt::decode(&ex.keys[1], &ex.keys[0], &eph_sk).unwrap();
})
.await;
let mut conn = connect(&host).await;
secure_tcp_required(&mut conn, &key).await.unwrap();
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)] {
@@ -3796,11 +3573,4 @@ 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());
}
}
+26 -75
View File
@@ -1,4 +1,4 @@
#[cfg(any(target_os = "windows", target_os = "macos"))]
#[cfg(target_os = "windows")]
use crate::client::translate;
#[cfg(not(debug_assertions))]
#[cfg(not(any(target_os = "android", target_os = "ios")))]
@@ -23,13 +23,26 @@ macro_rules! my_println{
};
}
pub enum CoreMainAction {
StartUi(Vec<String>),
ExitFailure(hbb_common::anyhow::Error),
}
#[cfg(target_os = "macos")]
fn finish_macos_update(result: hbb_common::ResultType<()>) -> Option<CoreMainAction> {
match result {
Ok(()) => None,
Err(err) => Some(CoreMainAction::ExitFailure(err)),
}
}
/// shared by flutter and sciter main function
///
/// [Note]
/// If it returns [`None`], then the process will terminate, and flutter gui will not be started.
/// If it returns [`Some`], then the process will continue, and flutter gui will be started.
/// If it returns [`Some`], the action determines whether to start the UI or report failure.
#[cfg(not(any(target_os = "android", target_os = "ios")))]
pub fn core_main() -> Option<Vec<String>> {
pub fn core_main() -> Option<CoreMainAction> {
if !crate::common::global_init() {
return None;
}
@@ -118,7 +131,7 @@ pub fn core_main() -> Option<Vec<String>> {
}
#[cfg(feature = "flutter")]
if _is_flutter_invoke_new_connection {
return core_main_invoke_new_connection(std::env::args());
return core_main_invoke_new_connection(std::env::args()).map(CoreMainAction::StartUi);
}
let click_setup = cfg!(windows) && args.is_empty() && crate::common::is_setup(&arg_exe);
if click_setup && !config::is_disable_installation() {
@@ -171,7 +184,7 @@ pub fn core_main() -> Option<Vec<String>> {
// linux uni (url) go here.
#[cfg(all(target_os = "linux", feature = "flutter"))]
if args.len() > 0 && args[0].starts_with(&crate::get_uri_prefix()) {
return try_send_by_dbus(args[0].clone());
return try_send_by_dbus(args[0].clone()).map(CoreMainAction::StartUi);
}
#[cfg(windows)]
@@ -227,6 +240,10 @@ pub fn core_main() -> Option<Vec<String>> {
}
return None;
} else if args[0] == "--update" {
// The elevated updater cannot delete its running verified copy.
if let Err(err) = platform::schedule_current_verified_update_file_cleanup() {
log::warn!("Failed to schedule verified update file cleanup: {}", err);
}
if config::is_disable_installation() {
return None;
}
@@ -336,38 +353,8 @@ pub fn core_main() -> Option<Vec<String>> {
}
#[cfg(target_os = "macos")]
{
use crate::platform;
if args[0] == "--update" {
if args.len() > 1 && args[1].ends_with(".dmg") {
// Version check is unnecessary unless downgrading to an older version
// that lacks "update dmg" support. This is a special case since we cannot
// detect the version before extracting the DMG, so we skip the check.
let dmg_path = &args[1];
println!("Updating from DMG: {}", dmg_path);
match platform::update_from_dmg(dmg_path) {
Ok(_) => {
println!("Update process from DMG started successfully.");
// The new process will handle the rest. We can exit.
}
Err(err) => {
eprintln!("Failed to start update from DMG: {}", err);
}
}
} else {
println!("Starting update process...");
log::info!("Starting update process...");
let _text = match platform::update_me() {
Ok(_) => {
println!("{}", translate("Updated successfully!".to_string()));
log::info!("Updated successfully!");
}
Err(err) => {
eprintln!("Update failed with error: {}", err);
log::error!("Update failed with error: {err}");
}
};
}
return None;
return finish_macos_update(crate::manual_update::execute_macos_update(&args));
}
}
if args[0] == "--remove" {
@@ -731,9 +718,9 @@ pub fn core_main() -> Option<Vec<String>> {
}
//_async_logger_holder.map(|x| x.flush());
#[cfg(feature = "flutter")]
return Some(flutter_args);
return Some(CoreMainAction::StartUi(flutter_args));
#[cfg(not(feature = "flutter"))]
return Some(args);
return Some(CoreMainAction::StartUi(args));
}
fn import_config(path: &str) {
@@ -873,7 +860,7 @@ fn is_root() -> bool {
crate::platform::is_root()
}
#[cfg(any(target_os = "linux", target_os = "macos", test))]
#[cfg(any(target_os = "linux", target_os = "macos"))]
fn is_user_main_ipc_scope_cli_command(args: &[String]) -> bool {
matches!(
args.first().map(String::as_str),
@@ -913,42 +900,6 @@ fn parse_silent_install_args(args: &[String]) -> (Option<bool>, bool) {
(printer_override, debug)
}
#[cfg(test)]
mod tests {
use super::*;
fn args(values: &[&str]) -> Vec<String> {
values.iter().map(|value| value.to_string()).collect()
}
#[test]
fn user_main_ipc_scope_cli_command_matches_management_commands_only() {
for command in [
"--password",
"--set-unlock-pin",
"--get-id",
"--set-id",
"--config",
"--option",
"--assign",
"--deploy",
] {
assert!(is_user_main_ipc_scope_cli_command(&args(&[command])));
}
for command in [
"--service",
"--server",
"--tray",
"--cm",
"--check-hwcodec-config",
"--connect",
] {
assert!(!is_user_main_ipc_scope_cli_command(&args(&[command])));
}
}
}
/// Check if the executable is a Quick Support version.
/// Note: This function must be kept in sync with `libs/portable/src/main.rs`.
#[cfg(windows)]
+18 -1
View File
@@ -62,7 +62,7 @@ pub fn get_custom_server_from_string(s: &str) -> ResultType<CustomServer> {
* This allows using a ',' (comma) symbol as a final delimiter.
*/
if s.to_lowercase().contains("host=") {
let stripped = &s[s.to_lowercase().find("host=").unwrap_or(0)..s.len()];
let stripped = &s[s.to_ascii_lowercase().find("host=").unwrap_or(0)..s.len()];
let strs: Vec<&str> = stripped.split(",").collect();
let mut host = String::default();
let mut key = String::default();
@@ -232,4 +232,21 @@ mod test {
get_custom_server_from_string("=0nI900VsFHZVBVdIlncwpHS4V0bOZ0dtVldrpVO4JHdCp0YV5WdzUGZzdnYRVjI6ISeltmIsISMuEjLx4SMiojI0N3boJye.exe")
.unwrap(), lic);
}
#[test]
fn test_filename_license_string_in_non_ascii_path() {
// Windows passes the full exe path, and `İ` grows from 2 to 3 bytes when lowercased.
assert_eq!(
get_custom_server_from_string(
r"C:\Users\İsmail\Downloads\rustdesk-host=server.example.net,key=Zm9vYmFyLiwyCg==.exe"
)
.unwrap(),
CustomServer {
host: "server.example.net".to_owned(),
key: "Zm9vYmFyLiwyCg==".to_owned(),
api: "".to_owned(),
relay: "".to_owned(),
}
);
}
}
+27 -7
View File
@@ -37,6 +37,11 @@ pub(crate) const APP_TYPE_CM: &str = "cm";
#[cfg(any(target_os = "android", target_os = "ios"))]
pub(crate) const APP_TYPE_CM: &str = "main";
#[cfg(target_os = "macos")]
const CORE_MAIN_EXIT_SUCCESS: i32 = 0;
#[cfg(target_os = "macos")]
const CORE_MAIN_EXIT_FAILURE: i32 = 1;
// Do not remove the following constants.
// Uncomment them when they are used.
// pub(crate) const APP_TYPE_DESKTOP_REMOTE: &str = "remote";
@@ -102,6 +107,8 @@ fn load_plugin_in_app_path(dll_name: &str) -> Result<Library, LibError> {
/// FFI for rustdesk core's main entry.
/// Return true if the app should continue running with UI(possibly Flutter), false if the app should exit.
/// On macOS, command-only paths exit here because the Swift caller ignores
/// the return value; update failures must therefore use a non-zero exit status.
#[cfg(not(windows))]
#[no_mangle]
pub extern "C" fn rustdesk_core_main() -> bool {
@@ -116,11 +123,18 @@ pub extern "C" fn rustdesk_core_main() -> bool {
}
}
#[cfg(not(any(target_os = "android", target_os = "ios")))]
if crate::core_main::core_main().is_some() {
return true;
} else {
#[cfg(target_os = "macos")]
std::process::exit(0);
match crate::core_main::core_main() {
Some(crate::core_main::CoreMainAction::StartUi(_)) => return true,
Some(crate::core_main::CoreMainAction::ExitFailure(err)) => {
eprintln!("Command failed: {err}");
log::error!("Command failed: {err}");
#[cfg(target_os = "macos")]
std::process::exit(CORE_MAIN_EXIT_FAILURE);
}
None => {
#[cfg(target_os = "macos")]
std::process::exit(CORE_MAIN_EXIT_SUCCESS);
}
}
#[cfg(not(target_os = "macos"))]
false
@@ -138,8 +152,14 @@ pub extern "C" fn rustdesk_core_main_args(args_len: *mut c_int) -> *mut *mut c_c
unsafe { std::ptr::write(args_len, 0) };
#[cfg(not(any(target_os = "android", target_os = "ios")))]
{
if let Some(args) = crate::core_main::core_main() {
return rust_args_to_c_args(args, args_len);
match crate::core_main::core_main() {
Some(crate::core_main::CoreMainAction::StartUi(args)) => {
return rust_args_to_c_args(args, args_len);
}
Some(crate::core_main::CoreMainAction::ExitFailure(err)) => {
log::error!("Command failed: {err}");
}
None => {}
}
return std::ptr::null_mut() as _;
}
+111 -81
View File
@@ -24,12 +24,11 @@ use base::{
};
use std::{
collections::HashMap,
path::PathBuf,
sync::{
atomic::{AtomicI32, Ordering},
Arc,
},
time::{Duration, SystemTime},
time::SystemTime,
};
pub type SessionID = uuid::Uuid;
@@ -2745,36 +2744,12 @@ pub fn main_get_common(key: String) -> String {
format!("error:{}", e)
}
}
} else if key.starts_with("download-file-") {
let _version = key.replace("download-file-", "");
#[cfg(target_os = "windows")]
return match (
crate::platform::windows::is_msi_installed(),
crate::common::is_custom_client(),
) {
(Ok(true), false) => match crate::platform::windows::release_arch_suffix() {
Some(arch) => format!("rustdesk-{_version}-{arch}.msi"),
None => "error:unsupported".to_owned(),
},
(Ok(true), true) | (Ok(false), _) => {
match crate::platform::windows::release_arch_suffix() {
Some(arch) => format!("rustdesk-{_version}-{arch}.exe"),
None => "error:unsupported".to_owned(),
}
}
(Err(e), _) => {
log::error!("Failed to check if is msi: {}", e);
format!("error:update-failed-check-msi-tip")
}
};
#[cfg(target_os = "macos")]
} else if let Some(release_page_url) = key.strip_prefix("verified-download-url-") {
#[cfg(any(target_os = "windows", target_os = "macos"))]
{
return if cfg!(target_arch = "x86_64") {
format!("rustdesk-{_version}-x86_64.dmg")
} else if cfg!(target_arch = "aarch64") {
format!("rustdesk-{_version}-aarch64.dmg")
} else {
"error:unsupported".to_owned()
return match verified_update_artifact_for_release_page_url(release_page_url) {
Ok(artifact) => artifact.url,
Err(e) => format!("error:{}", e),
};
}
#[cfg(not(any(target_os = "windows", target_os = "macos")))]
@@ -2788,9 +2763,35 @@ pub fn main_get_common(key: String) -> String {
}
pub fn main_get_common_sync(key: String) -> SyncReturn<String> {
// Metadata verification performs blocking network requests. Keep this key on
// the asynchronous FFI path to avoid blocking the calling Flutter isolate.
if key.starts_with("verified-download-url-") {
return SyncReturn("error:unsupported".to_owned());
}
SyncReturn(main_get_common(key))
}
#[cfg(any(target_os = "windows", target_os = "macos"))]
fn push_update_me_error(error: String) {
let data = HashMap::from([("name", "update-me".to_owned()), ("error", error)]);
let _res = flutter::push_global_event(
flutter::APP_TYPE_MAIN,
serde_json::ser::to_string(&data).unwrap_or("".to_owned()),
);
}
#[cfg(any(target_os = "windows", target_os = "macos"))]
fn verified_update_artifact_for_release_page_url(
release_page_url: &str,
) -> ResultType<crate::update_metadata::VerifiedUpdateArtifact> {
#[cfg(target_os = "windows")]
let update_msi = crate::platform::windows::is_msi_installed()? && !crate::is_custom_client();
#[cfg(target_os = "macos")]
let update_msi = false;
let query = crate::updater::current_update_artifact_query(update_msi);
crate::updater::verified_update_artifact_for_release_page_url(release_page_url, query)
}
pub fn main_set_common(_key: String, _value: String) {
#[cfg(target_os = "windows")]
if _key == "install-printer" && crate::platform::is_win_10_or_greater() {
@@ -2826,65 +2827,94 @@ pub fn main_set_common(_key: String, _value: String) {
}
#[cfg(any(target_os = "windows", target_os = "macos"))]
{
use crate::updater::get_download_file_from_url;
use crate::updater::get_update_download_file_from_url;
if _key == "download-new-version" {
let download_url = _value.clone();
let event_key = "download-new-version".to_owned();
let data = if let Some(download_file) = get_download_file_from_url(&download_url) {
std::fs::remove_file(&download_file).ok();
match crate::hbbs_http::downloader::download_file(
download_url,
Some(PathBuf::from(download_file)),
Some(Duration::from_secs(3)),
) {
Ok(id) => HashMap::from([("name", event_key), ("id", id)]),
Err(e) => HashMap::from([("name", event_key), ("error", e.to_string())]),
}
} else {
HashMap::from([
("name", event_key),
("error", "Invalid download url".to_string()),
])
};
let data =
match crate::updater::verified_update_artifact_for_download_url(&download_url) {
Ok(artifact) => {
if let Some(download_file) =
get_update_download_file_from_url(&artifact.url)
{
let options = crate::hbbs_http::downloader::DownloadOptions {
expected_size: artifact.size,
artifact_sha256: artifact.sha256,
};
match crate::hbbs_http::downloader::download_file(
artifact.url,
Some(download_file),
options,
) {
Ok(id) => HashMap::from([("name", event_key), ("id", id)]),
Err(e) => {
HashMap::from([("name", event_key), ("error", e.to_string())])
}
}
} else {
HashMap::from([
("name", event_key),
("error", "Invalid download url".to_owned()),
])
}
}
Err(e) => HashMap::from([
("name", event_key),
("error", format!("Failed to verify update metadata, {}", e)),
]),
};
let _res = flutter::push_global_event(
flutter::APP_TYPE_MAIN,
serde_json::ser::to_string(&data).unwrap_or("".to_owned()),
);
} else if _key == "update-me" {
if let Some(new_version_file) = get_download_file_from_url(&_value) {
log::debug!(
"New version file is downloaded, update begin, {:?}",
new_version_file.to_str()
);
if let Some(f) = new_version_file.to_str() {
// 1.4.0 does not support "--update"
// But we can assume that the new version supports it.
#[cfg(any(target_os = "windows", target_os = "macos"))]
match crate::platform::update_to(f) {
Ok(_) => {
log::info!("Update process is launched successfully!");
}
Err(e) => {
log::error!("Failed to update to new version, {}", e);
fs::remove_file(f).ok();
}
}
}
}
} else if _key == "extract-update-dmg" {
#[cfg(target_os = "macos")]
let artifact = match crate::updater::verified_update_artifact_for_download_url(&_value)
{
if let Some(new_version_file) = get_download_file_from_url(&_value) {
if let Some(f) = new_version_file.to_str() {
crate::platform::macos::extract_update_dmg(f);
} else {
// unreachable!()
log::error!("Failed to get the new version file path");
}
} else {
// unreachable!()
log::error!("Failed to get the new version file from url: {}", _value);
Ok(artifact) => artifact,
Err(e) => {
let error = format!("Failed to verify update metadata, {}", e);
log::error!("{}", error);
push_update_me_error(error);
return;
}
};
let Some(new_version_file) = get_update_download_file_from_url(&artifact.url) else {
let error = "Failed to resolve downloaded update file path".to_owned();
log::error!("{}", error);
push_update_me_error(error);
return;
};
let Some(new_version_file_str) = new_version_file.to_str() else {
let error = "Invalid UTF-8 path for downloaded update file".to_owned();
log::error!("{}", error);
push_update_me_error(error);
return;
};
log::debug!(
"New version file is downloaded, update begin, {:?}",
new_version_file_str
);
#[cfg(target_os = "windows")]
let update_res = crate::platform::update_to_verified(
new_version_file_str,
&artifact.sha256,
artifact.size,
);
#[cfg(target_os = "macos")]
let update_res = crate::platform::macos::update_to_verified_dmg(
new_version_file_str,
&artifact.sha256,
Some(artifact.size),
);
if update_res.is_err() {
crate::updater::remove_update_file(&new_version_file);
}
match update_res {
Ok(_) => log::info!("Update process is launched successfully!"),
Err(e) => {
let error = format!("Failed to update to new version, {}", e);
log::error!("{}", error);
push_update_me_error(error);
}
}
}
+177 -158
View File
@@ -5,14 +5,14 @@ use hbb_common::{
log,
tokio::{
self,
fs::File,
fs::{File, OpenOptions},
io::AsyncWriteExt,
sync::mpsc::{unbounded_channel, UnboundedReceiver, UnboundedSender},
},
ResultType,
};
use serde_derive::Serialize;
use std::{collections::HashMap, path::PathBuf, sync::Mutex, time::Duration};
use std::{collections::HashMap, path::PathBuf, sync::Mutex};
lazy_static! {
static ref DOWNLOADERS: Mutex<HashMap<String, Downloader>> = Default::default();
@@ -31,6 +31,7 @@ pub struct DownloadData {
#[serde(skip_serializing_if = "Option::is_none")]
pub total_size: Option<u64>,
pub downloaded_size: u64,
pub finished: bool,
#[serde(skip_serializing_if = "Option::is_none")]
pub error: Option<String>,
}
@@ -38,181 +39,187 @@ pub struct DownloadData {
struct Downloader {
data: Vec<u8>,
path: Option<PathBuf>,
// Some file may be empty, so we use Option<u64> to indicate if the size is known
total_size: Option<u64>,
total_size: u64,
artifact_sha256: String,
downloaded_size: u64,
error: Option<String>,
finished: bool,
tx_cancel: UnboundedSender<()>,
}
impl Downloader {
fn matches_request(&self, path: &Option<PathBuf>, options: &DownloadOptions) -> bool {
self.path.as_ref() == path.as_ref()
&& self.total_size == options.expected_size
&& self.artifact_sha256 == options.artifact_sha256
}
}
pub struct DownloadOptions {
pub expected_size: u64,
pub artifact_sha256: String,
}
struct DownloadRequest {
id: String,
url: String,
path: Option<PathBuf>,
expected_size: u64,
}
// The caller should check if the file is downloaded successfully and remove the job from the map.
pub fn download_file(
url: String,
path: Option<PathBuf>,
auto_del_dur: Option<Duration>,
options: DownloadOptions,
) -> ResultType<String> {
let id = url.clone();
// First pass: if a non-error downloader exists for this URL, reuse it.
// If an errored downloader exists, remove it so this call can retry.
let mut stale_path = None;
{
let mut downloaders = DOWNLOADERS.lock().unwrap();
if let Some(downloader) = downloaders.get(&id) {
if downloader.error.is_none() {
return Ok(id);
}
stale_path = downloader.path.clone();
downloaders.remove(&id);
}
}
if let Some(p) = stale_path {
if p.exists() {
if let Err(e) = std::fs::remove_file(&p) {
log::warn!("Failed to remove stale download file {}: {}", p.display(), e);
}
}
}
if let Some(path) = path.as_ref() {
if path.exists() {
bail!("File {} already exists", path.display());
}
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent)?;
}
}
let (tx, rx) = unbounded_channel();
let downloader = Downloader {
data: Vec::new(),
path: path.clone(),
total_size: None,
downloaded_size: 0,
error: None,
tx_cancel: tx,
finished: false,
};
// Second pass (atomic with insert) to avoid race with another concurrent caller.
let mut stale_path_after_check = None;
{
let mut downloaders = DOWNLOADERS.lock().unwrap();
if let Some(existing) = downloaders.get(&id) {
if existing.error.is_none() {
return Ok(id);
}
stale_path_after_check = existing.path.clone();
downloaders.remove(&id);
}
downloaders.insert(id.clone(), downloader);
}
if let Some(p) = stale_path_after_check {
if p.exists() {
if let Err(e) = std::fs::remove_file(&p) {
log::warn!("Failed to remove stale download file {}: {}", p.display(), e);
if existing.matches_request(&path, &options) {
return Ok(id);
}
bail!("Existing download job does not match requested artifact");
}
}
}
let id2 = id.clone();
std::thread::spawn(
move || match do_download(&id2, url, path, auto_del_dur, rx) {
Ok(is_all_downloaded) => {
let mut downloaded_size = 0;
let mut total_size = 0;
DOWNLOADERS.lock().unwrap().get_mut(&id2).map(|downloader| {
downloaded_size = downloader.downloaded_size;
total_size = downloader.total_size.unwrap_or(0);
});
log::info!(
"Download {} end, {}/{}, {:.2} %",
&id2,
downloaded_size,
total_size,
if total_size == 0 {
0.0
} else {
downloaded_size as f64 / total_size as f64 * 100.0
let stale_path = downloaders
.remove(&id)
.and_then(|downloader| downloader.path);
if stale_path.as_ref() != path.as_ref() {
if let Some(p) = stale_path {
if p.exists() {
if let Err(e) = std::fs::remove_file(&p) {
log::warn!(
"Failed to remove stale download file {}: {}",
p.display(),
e
);
}
);
}
}
}
let is_canceled = !is_all_downloaded;
if is_canceled {
if let Some(downloader) = DOWNLOADERS.lock().unwrap().remove(&id2) {
if let Some(p) = downloader.path {
if p.exists() {
std::fs::remove_file(p).ok();
}
if let Some(path) = path.as_ref() {
prepare_download_path(path)?;
}
downloaders.insert(
id.clone(),
Downloader {
data: Vec::new(),
path: path.clone(),
total_size: options.expected_size,
artifact_sha256: options.artifact_sha256,
downloaded_size: 0,
error: None,
tx_cancel: tx,
finished: false,
},
);
}
let request = DownloadRequest {
id: id.clone(),
url,
path,
expected_size: options.expected_size,
};
let worker_id = id.clone();
std::thread::spawn(move || match do_download(request, rx) {
Ok(is_all_downloaded) => {
let mut downloaded_size = 0;
let mut total_size = 0;
DOWNLOADERS
.lock()
.unwrap()
.get_mut(&worker_id)
.map(|downloader| {
downloaded_size = downloader.downloaded_size;
total_size = downloader.total_size;
});
log::info!(
"Download {} end, {}/{}, {:.2} %",
&worker_id,
downloaded_size,
total_size,
if total_size == 0 {
0.0
} else {
downloaded_size as f64 / total_size as f64 * 100.0
}
);
let is_canceled = !is_all_downloaded;
if is_canceled {
if let Some(downloader) = DOWNLOADERS.lock().unwrap().remove(&worker_id) {
if let Some(p) = downloader.path {
if p.exists() {
std::fs::remove_file(p).ok();
}
}
}
}
Err(e) => {
let err = e.to_string();
log::error!("Download {}, failed: {}", &id2, &err);
DOWNLOADERS.lock().unwrap().get_mut(&id2).map(|downloader| {
}
Err(e) => {
let err = e.to_string();
log::error!("Download {}, failed: {}", &worker_id, &err);
DOWNLOADERS
.lock()
.unwrap()
.get_mut(&worker_id)
.map(|downloader| {
downloader.error = Some(err);
});
}
},
);
}
});
Ok(id)
}
fn prepare_download_path(path: &PathBuf) -> ResultType<()> {
match std::fs::remove_file(path) {
Ok(()) => {}
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
Err(e) => return Err(e.into()),
}
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent)?;
}
Ok(())
}
#[tokio::main(flavor = "current_thread")]
async fn do_download(
id: &str,
url: String,
path: Option<PathBuf>,
auto_del_dur: Option<Duration>,
request: DownloadRequest,
mut rx_cancel: UnboundedReceiver<()>,
) -> ResultType<bool> {
let client = create_http_client_async_with_url_strict(&url).await?;
let client = create_http_client_async_with_url_strict(&request.url).await?;
let mut is_all_downloaded = false;
tokio::select! {
_ = rx_cancel.recv() => {
return Ok(is_all_downloaded);
}
head_resp = client.head(&url).send() => {
match head_resp {
Ok(resp) => {
if resp.status().is_success() {
let total_size = resp
.headers()
.get(reqwest::header::CONTENT_LENGTH)
.and_then(|ct_len| ct_len.to_str().ok())
.and_then(|ct_len| ct_len.parse::<u64>().ok());
let Some(total_size) = total_size else {
bail!("Failed to get content length");
};
DOWNLOADERS.lock().unwrap().get_mut(id).map(|downloader| {
downloader.total_size = Some(total_size);
});
} else {
bail!("Failed to get content length: {}", resp.status());
}
}
Err(e) => {
return Err(e.into());
}
}
}
}
let mut downloaded_size = 0_u64;
let mut response;
tokio::select! {
_ = rx_cancel.recv() => {
return Ok(is_all_downloaded);
}
resp = client.get(url).send() => {
response = resp?;
resp = client.get(request.url).send() => {
response = resp?.error_for_status()?;
}
}
let mut dest: Option<File> = None;
if let Some(p) = path {
dest = Some(File::create(p).await?);
if let Some(p) = request.path {
dest = Some(
OpenOptions::new()
.write(true)
.create_new(true)
.open(p)
.await?,
);
}
loop {
@@ -223,28 +230,42 @@ async fn do_download(
chunk = response.chunk() => {
match chunk {
Ok(Some(chunk)) => {
let next_size = downloaded_size
.checked_add(chunk.len() as u64)
.ok_or_else(|| hbb_common::anyhow::anyhow!("Download size overflow"))?;
if next_size > request.expected_size {
bail!(
"Download size exceeds expected size: expected {}, got {}",
request.expected_size,
next_size
);
}
match dest {
Some(ref mut f) => {
f.write_all(&chunk).await?;
f.flush().await?;
DOWNLOADERS.lock().unwrap().get_mut(id).map(|downloader| {
downloader.downloaded_size += chunk.len() as u64;
});
}
None => {
DOWNLOADERS.lock().unwrap().get_mut(id).map(|downloader| {
downloader.data.extend_from_slice(&chunk);
downloader.downloaded_size += chunk.len() as u64;
});
let mut downloaders = DOWNLOADERS.lock().unwrap();
let Some(downloader) = downloaders.get_mut(&request.id) else {
bail!("Downloader not found");
};
downloader.data.extend_from_slice(&chunk);
}
}
downloaded_size = next_size;
let mut downloaders = DOWNLOADERS.lock().unwrap();
let Some(downloader) = downloaders.get_mut(&request.id) else {
bail!("Downloader not found");
};
downloader.downloaded_size = downloaded_size;
}
Ok(None) => {
is_all_downloaded = true;
break;
},
Err(e) => {
log::error!("Download {} failed: {}", id, e);
log::error!("Download {} failed: {}", request.id, e);
return Err(e.into());
}
}
@@ -256,17 +277,19 @@ async fn do_download(
f.flush().await?;
}
if let Some(ref mut downloader) = DOWNLOADERS.lock().unwrap().get_mut(id) {
downloader.finished = true;
if is_all_downloaded && downloaded_size != request.expected_size {
bail!(
"Download size mismatch: expected {}, got {}",
request.expected_size,
downloaded_size
);
}
if is_all_downloaded {
let id_del = id.to_string();
if let Some(dur) = auto_del_dur {
tokio::spawn(async move {
tokio::time::sleep(dur).await;
DOWNLOADERS.lock().unwrap().remove(&id_del);
});
}
let mut downloaders = DOWNLOADERS.lock().unwrap();
let Some(downloader) = downloaders.get_mut(&request.id) else {
bail!("Downloader not found");
};
downloader.finished = true;
}
Ok(is_all_downloaded)
}
@@ -274,21 +297,18 @@ async fn do_download(
pub fn get_download_data(id: &str) -> ResultType<DownloadData> {
let downloaders = DOWNLOADERS.lock().unwrap();
if let Some(downloader) = downloaders.get(id) {
let downloaded_size = downloader.downloaded_size;
let total_size = downloader.total_size.clone();
let error = downloader.error.clone();
let data = if total_size.unwrap_or(0) == downloaded_size && downloader.path.is_none() {
let data = if downloader.finished && downloader.path.is_none() {
downloader.data.clone()
} else {
Vec::new()
};
let path = downloader.path.clone();
let download_data = DownloadData {
data,
path,
total_size,
downloaded_size,
error,
path: downloader.path.clone(),
total_size: Some(downloader.total_size),
downloaded_size: downloader.downloaded_size,
finished: downloader.finished,
error: downloader.error.clone(),
};
Ok(download_data)
} else {
@@ -298,8 +318,7 @@ pub fn get_download_data(id: &str) -> ResultType<DownloadData> {
pub fn cancel(id: &str) {
if let Some(downloader) = DOWNLOADERS.lock().unwrap().get(id) {
// downloader.is_canceled.store(true, Ordering::SeqCst);
// The receiver may not be able to receive the cancel signal, so we also set the atomic bool to true
// The receiver may not be able to receive the cancel signal, so keep the job until it exits.
let _ = downloader.tx_cancel.send(());
}
}
+12 -140
View File
@@ -267,6 +267,8 @@ pub enum DataKeyboard {
#[serde(tag = "t", content = "c")]
pub enum DataKeyboardResponse {
GetKeyState(bool),
#[cfg(target_os = "linux")]
GetKeyStateError(String),
}
#[cfg(not(any(target_os = "android", target_os = "ios")))]
@@ -1190,8 +1192,16 @@ async fn handle(data: Data, stream: &mut Connection) {
}
} else if value == "clear" {
set_local_option(key.clone(), "".to_owned());
// The session slot is held while a portal request waits for the user, and this ipc
// listener runs on one thread: wait for the slot off it, then close what the
// request brings back.
#[cfg(target_os = "linux")]
scrap::wayland::pipewire::close_session();
allow_err!(
hbb_common::tokio::task::spawn_blocking(
scrap::wayland::pipewire::close_session
)
.await
);
Some("".to_owned())
} else {
None
@@ -2266,43 +2276,9 @@ pub async fn set_install_option(k: String, v: String) -> ResultType<()> {
#[cfg(test)]
mod test {
#[cfg(any(target_os = "linux", target_os = "macos"))]
use super::*;
#[test]
fn verify_ffi_enum_data_size() {
println!("{}", std::mem::size_of::<Data>());
assert!(std::mem::size_of::<Data>() <= 120);
}
#[cfg(any(target_os = "linux", target_os = "macos"))]
#[test]
fn test_service_ipc_path_is_shared_across_uids() {
assert_eq!(
Config::ipc_path_for_uid(0, crate::POSTFIX_SERVICE),
Config::ipc_path_for_uid(501, crate::POSTFIX_SERVICE)
);
}
#[cfg(any(target_os = "linux", target_os = "macos"))]
#[test]
fn test_ipc_path_differs_by_uid_for_cm() {
let effective_uid = unsafe { hbb_common::libc::geteuid() as u32 };
let other_uid = effective_uid.saturating_add(1);
let postfix = "_cm";
// Default connect path targets the current effective uid.
assert_eq!(
Config::ipc_path(postfix),
Config::ipc_path_for_uid(effective_uid, postfix)
);
// A different uid yields a different socket path - this is the root cause of the
// cross-user regression when root spawns a user process but still connects as uid 0.
assert_ne!(
Config::ipc_path(postfix),
Config::ipc_path_for_uid(other_uid, postfix)
);
}
#[cfg(any(target_os = "linux", target_os = "macos"))]
#[test]
fn test_select_server_uid_uses_active_uid_when_no_server_found() {
@@ -2344,108 +2320,4 @@ 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:?}"),
}
}
/// A frame from a producer that predates the plane rotation reads as `None`, in the cpu frame
/// header and in the dma-buf descriptor: the root service and the `--server` are upgraded
/// separately, and `None` keeps the previous rule.
#[cfg(all(target_os = "linux", feature = "drm"))]
#[test]
fn a_frame_without_a_plane_rotation_reads_as_none() {
let legacy = r#"{"t":"DrmFrame","c":{"width":8,"height":8}}"#;
match serde_json::from_str::<Data>(legacy).expect("legacy DrmFrame must deserialize") {
Data::DrmFrame { plane_rotation, .. } => assert_eq!(plane_rotation, None),
other => panic!("expected DrmFrame, got {other:?}"),
}
let modern = r#"{"t":"DrmFrame","c":{"width":8,"height":8,"plane_rotation":4}}"#;
match serde_json::from_str::<Data>(modern).expect("modern DrmFrame must deserialize") {
Data::DrmFrame { plane_rotation, .. } => assert_eq!(plane_rotation, Some(4)),
other => panic!("expected DrmFrame, got {other:?}"),
}
let desc = DmabufDesc {
buffer_id: 0,
width: 4,
height: 4,
format: 0,
modifier: 0,
fb_id: 0,
num_planes: 1,
offsets: [0; 4],
pitches: [16, 0, 0, 0],
hdr_eotf: 0,
hdr_max_nits: 0,
has_fd: false,
plane_rotation: Some(4),
cursor_pos: None,
};
let mut value = serde_json::to_value(&desc).unwrap();
assert!(value.as_object_mut().unwrap().remove("plane_rotation").is_some());
let legacy: DmabufDesc =
serde_json::from_value(value).expect("legacy DmabufDesc must deserialize");
assert_eq!(legacy.plane_rotation, None);
}
/// A frame header from a producer that predates the cursor plane position reads as `None`;
/// a producer that sends one is read back exactly. A pin, not a gate: the consumer only ever
/// measures against `Some`.
#[cfg(all(target_os = "linux", feature = "drm"))]
#[test]
fn a_drm_frame_without_a_cursor_position_reads_as_none() {
let legacy = r#"{"t":"DrmFrame","c":{"width":8,"height":8}}"#;
match serde_json::from_str::<Data>(legacy).expect("legacy DrmFrame must deserialize") {
Data::DrmFrame {
width,
height,
cursor_pos,
..
} => {
assert_eq!((width, height), (8, 8));
assert_eq!(cursor_pos, None);
}
other => panic!("expected DrmFrame, got {other:?}"),
}
let modern = r#"{"t":"DrmFrame","c":{"width":8,"height":8,"cursor_pos":[3,4]}}"#;
match serde_json::from_str::<Data>(modern).expect("modern DrmFrame must deserialize") {
Data::DrmFrame { cursor_pos, .. } => assert_eq!(cursor_pos, Some((3, 4))),
other => panic!("expected DrmFrame, got {other:?}"),
}
}
}
-71
View File
@@ -928,37 +928,6 @@ mod tests {
));
}
#[test]
#[cfg(windows)]
fn test_should_allow_everyone_create_on_windows_policy() {
assert!(super::should_allow_everyone_create_on_windows(""));
assert!(super::should_allow_everyone_create_on_windows("_service"));
assert!(!super::should_allow_everyone_create_on_windows(
"_portable_service"
));
}
#[test]
#[cfg(windows)]
fn test_executable_paths_match_windows_normalization() {
let left = std::path::PathBuf::from(r"\\?\C:\Program Files\RustDesk\RustDesk.exe");
let right = std::path::PathBuf::from(r"c:\program files\rustdesk\rustdesk.exe");
assert!(super::executable_paths_match(&left, &right));
}
#[test]
#[cfg(target_os = "macos")]
fn test_os_str_eq_ignore_ascii_case_for_process_names() {
assert!(super::os_str_eq_ignore_ascii_case(
Some(std::ffi::OsStr::new("RustDesk")),
Some(std::ffi::OsStr::new("rustdesk"))
));
assert!(!super::os_str_eq_ignore_ascii_case(
Some(std::ffi::OsStr::new("RustDesk")),
Some(std::ffi::OsStr::new("service"))
));
}
#[cfg(all(windows, not(feature = "flutter")))]
struct TempDirGuard(std::path::PathBuf);
@@ -994,44 +963,4 @@ mod tests {
"helper trust check must reject path-match-only binaries with mismatched content"
);
}
#[test]
#[cfg(all(windows, not(feature = "flutter")))]
fn test_portable_service_helper_trust_accepts_matching_content() {
let unique = format!(
"rustdesk-portable-helper-trust-match-test-{}-{}",
std::process::id(),
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap_or_default()
.as_nanos()
);
let base = std::env::temp_dir().join(unique);
std::fs::create_dir_all(&base).unwrap();
let _cleanup = TempDirGuard(base.clone());
let current_exe = base.join("current.exe");
let helper_exe = base.join("helper.exe");
std::fs::write(&current_exe, b"trusted-binary").unwrap();
std::fs::write(&helper_exe, b"trusted-binary").unwrap();
assert!(super::portable_service_helper_is_trusted(
&helper_exe,
&helper_exe,
&current_exe
));
}
#[cfg(target_os = "macos")]
#[test]
fn test_console_owner_uid_matches_get_active_userid() {
let console_uid =
super::console_owner_uid().expect("/dev/console must have a resolvable uid");
let raw_uid = crate::platform::macos::get_active_userid();
let parsed_uid: u32 = raw_uid
.trim()
.parse()
.unwrap_or_else(|_| panic!("failed to parse get_active_userid() output: '{raw_uid}'"));
assert_eq!(parsed_uid, console_uid);
}
}
+250 -253
View File
@@ -23,6 +23,10 @@ pub struct DrmDisplayInfo {
/// alone is ambiguous across cards. Empty = the single auto-detected device.
#[serde(default)]
pub device: String,
/// The primary plane rotates its framebuffer by 90/270 in hardware, so every frame is this
/// mode TRANSPOSED whatever the compositor reports (gamescope's wl_output has no transform).
#[serde(default)]
pub plane_transposed: bool,
}
/// Mirrors `scrap::drm_reader::drmtap_dmabuf_desc` except `dma_buf_fd` (never serializes — it rides
@@ -215,22 +219,6 @@ mod cursor_pos_tests {
stamp_cursor_pos(&mut shape, Some(&visible));
assert!(matches!(&shape, DrmProducerMsg::Cursor { hotx: 1, hoty: 1, .. }));
}
// A producer that predates the field: the descriptor arrives without it and reads as None.
#[test]
fn a_descriptor_without_a_cursor_position_reads_as_none() {
let mut v = serde_json::to_value(desc()).unwrap();
v.as_object_mut().unwrap().remove("cursor_pos").expect("the field is serialized");
let d: DmabufDesc = serde_json::from_value(v).expect("a legacy descriptor must deserialize");
assert_eq!(d.cursor_pos, None);
let d: DmabufDesc = serde_json::from_value(serde_json::to_value(DmabufDesc {
cursor_pos: Some((3, 4)),
..desc()
})
.unwrap())
.unwrap();
assert_eq!(d.cursor_pos, Some((3, 4)));
}
}
struct DrmStopGuard(std::sync::Arc<std::sync::atomic::AtomicBool>);
@@ -260,6 +248,11 @@ static DRM_DISPLAY_CACHE: std::sync::Mutex<Vec<DrmDisplayInfo>> = std::sync::Mut
/// Bumped only when a change altered `DRM_DISPLAY_CACHE`; Release orders it after the cache write.
static DRM_DISPLAY_GENERATION: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
/// The whole-hertz refresh of every driven CRTC the last enumeration saw, by (device, crtc), for
/// a producer whose library cannot read the exact one: it then needs no connector probe of its own.
static DRM_WHOLE_HZ: std::sync::Mutex<std::collections::BTreeMap<(String, u32), u32>> =
std::sync::Mutex::new(std::collections::BTreeMap::new());
/// Displays this reader serves, plus the identity (`device:connector`) of each undriven output.
fn drm_displays_from_reader(
reader: &mut scrap::drm_reader::DrmReader,
@@ -267,8 +260,13 @@ fn drm_displays_from_reader(
) -> (Vec<DrmDisplayInfo>, Vec<String>) {
let render_node = reader.render_node().unwrap_or_default();
let mut undriven = Vec::new();
let displays: Vec<DrmDisplayInfo> = reader
.displays()
let snapshots = reader.displays();
if let Ok(mut hz) = DRM_WHOLE_HZ.lock() {
for d in snapshots.iter().filter(|d| d.active && d.crtc_id != 0) {
hz.insert((device.to_owned(), d.crtc_id), d.refresh_hz);
}
}
let displays: Vec<DrmDisplayInfo> = snapshots
.into_iter()
// Only outputs bound to a CRTC: a CONNECTED-but-unbound connector enumerates with
// `crtc_id == 0`, and `open(crtc=0)` auto-selects the FIRST ACTIVE CRTC and streams ITS frames.
@@ -280,6 +278,7 @@ fn drm_displays_from_reader(
true
})
.map(|d| DrmDisplayInfo {
plane_transposed: plane_transposed(device, d.crtc_id),
name: d.name,
crtc_id: d.crtc_id,
x: d.x,
@@ -294,6 +293,33 @@ fn drm_displays_from_reader(
(displays, undriven)
}
const DRM_MODE_ROTATE_90: u32 = 0x2;
const DRM_MODE_ROTATE_270: u32 = 0x8;
/// Through a reader bound to `crtc_id`: the enumerating reader is bound to whichever crtc
/// auto-select picked.
fn plane_transposed(device: &str, crtc_id: u32) -> bool {
let dev = (!device.is_empty()).then_some(device);
let Some(mut r) = scrap::drm_reader::DrmReader::open(dev, crtc_id) else {
return false;
};
let transposed = match r.query_plane_rotation() {
Some(m) => m & (DRM_MODE_ROTATE_90 | DRM_MODE_ROTATE_270) != 0,
None => {
hbb_common::throttled_log!(
std::time::Duration::from_secs(600),
debug,
"drm: crtc {crtc_id} ({device:?}): plane rotation unreadable; sized as unrotated"
);
false
}
};
if transposed {
log::trace!("drm: crtc {crtc_id} ({device:?}) is rotated 90/270 by its plane");
}
transposed
}
/// Active displays of every DRM device + the connected-but-undriven identities, from ONE look.
fn drm_enumerate_all_displays() -> (Vec<DrmDisplayInfo>, Vec<String>) {
if let Some(devices) = scrap::drm_reader::list_devices() {
@@ -935,9 +961,20 @@ async fn handle_drm_conn(stream: Connection) -> ResultType<()> {
let worker_stop = stop.clone();
let frames_gated = Arc::new(AtomicBool::new(false));
let worker_gate = frames_gated.clone();
let demand_fps = Arc::new(std::sync::atomic::AtomicU8::new(0));
let worker_demand = demand_fps.clone();
std::thread::Builder::new()
.name("drm-capture".into())
.spawn(move || drm_capture_worker(frame_tx, crtc_rx, worker_stop, worker_gate, wake))
.spawn(move || {
drm_capture_worker(
frame_tx,
crtc_rx,
worker_stop,
worker_gate,
worker_demand,
wake,
)
})
.map_err(|err| anyhow::anyhow!("could not spawn the drm capture worker: {err}"))?;
let displays = match frame_rx.recv().await {
@@ -977,10 +1014,13 @@ async fn handle_drm_conn(stream: Connection) -> ResultType<()> {
let mut seen_gen = DRM_DISPLAY_GENERATION.load(Ordering::Acquire);
const DRM_FRAME_CREDIT: i32 = 2;
let mut credit: i32 = DRM_FRAME_CREDIT;
let mut demand: u8 = 0;
let mut demand_logged: Option<(u8, std::time::Instant)> = None;
let mut credit_since = std::time::Instant::now();
let mut held_frame: Option<DrmProducerMsg> = None;
loop {
conn.drain_frame_acks(&mut credit, DRM_FRAME_CREDIT)?;
conn.drain_frame_acks(&mut credit, DRM_FRAME_CREDIT, &mut demand)?;
note_drm_demand(&demand_fps, demand, target_crtc, &mut demand_logged);
// While gated the worker does not grab, so it cannot advance its own MAX_STALLED watchdog: a
// consumer that stops acking without closing the socket would otherwise hold this connection,
// its worker thread and the privileged DRM context open indefinitely.
@@ -1072,7 +1112,8 @@ async fn handle_drm_conn(stream: Connection) -> ResultType<()> {
}
msg = frame_rx.try_recv().ok();
}
conn.drain_frame_acks(&mut credit, DRM_FRAME_CREDIT)?;
conn.drain_frame_acks(&mut credit, DRM_FRAME_CREDIT, &mut demand)?;
note_drm_demand(&demand_fps, demand, target_crtc, &mut demand_logged);
if credit <= 0 {
held_frame = latest_frame;
continue;
@@ -1117,18 +1158,109 @@ async fn handle_drm_conn(stream: Connection) -> ResultType<()> {
Ok(())
}
/// The producer's tick when the consumer has not said its rate, and the WouldBlock retry period.
const FRAME_INTERVAL: std::time::Duration = std::time::Duration::from_millis(33);
/// Bound continuous no-frame (WouldBlock) time so a wedged device ends the stream (~5 s).
const MAX_STALLED: u32 = 150;
const _: () = assert!(
FRAME_INTERVAL.as_millis() * MAX_STALLED as u128 >= 4_500
&& FRAME_INTERVAL.as_millis() * MAX_STALLED as u128 <= 5_500
);
/// A frame ack is one byte and every producer counts bytes, never their value, so a byte that
/// also carries the consumer's encode rate is still exactly one credit to an older producer.
const DRM_ACK_PLAIN: u8 = 0x01;
const DRM_ACK_FPS_FLAG: u8 = 0x80;
/// video_qos's ceiling; it fits the seven low bits.
const DRM_MAX_DEMAND_FPS: u8 = 120;
fn drm_ack_byte(fps: u8) -> u8 {
if fps == 0 {
DRM_ACK_PLAIN
} else {
DRM_ACK_FPS_FLAG | fps.min(DRM_MAX_DEMAND_FPS)
}
}
fn drm_ack_demand(b: u8) -> Option<u8> {
let fps = b & !DRM_ACK_FPS_FLAG;
(b & DRM_ACK_FPS_FLAG != 0 && (1..=DRM_MAX_DEMAND_FPS).contains(&fps)).then_some(fps)
}
/// One period of a panel refreshing at `num/den` Hz, rounded up so pacing never outruns it.
fn drm_panel_period(num: u64, den: u64) -> std::time::Duration {
if num == 0 || den == 0 {
return std::time::Duration::ZERO;
}
let nanos = (u128::from(den) * 1_000_000_000).div_ceil(u128::from(num));
std::time::Duration::from_nanos(u64::try_from(nanos).unwrap_or(u64::MAX))
}
/// Grab period for a consumer encoding at `demand_fps`, never faster than the panel: its own
/// period above 30 fps, the old 33 ms tick from 30 down to 15, and below 15 half its period, so a
/// slow consumer's frame is at most half its period old.
fn drm_pacing_interval(demand_fps: u8, panel: std::time::Duration) -> std::time::Duration {
if demand_fps == 0 {
return FRAME_INTERVAL;
}
let want = std::time::Duration::from_secs(1) / u32::from(demand_fps);
want.min((want / 2).max(FRAME_INTERVAL)).max(panel)
}
/// When the worker's next tick starts. Without a demand it is the old sleep after the work;
/// with one it is a deadline phased on the previous tick, and `now` after an overrun.
fn drm_next_tick(
prev: std::time::Instant,
now: std::time::Instant,
demand_fps: u8,
panel: std::time::Duration,
) -> std::time::Instant {
if demand_fps == 0 {
return now + FRAME_INTERVAL;
}
(prev + drm_pacing_interval(demand_fps, panel)).max(now)
}
/// Hands the consumer's rate to the worker. The measured part of it moves with almost every frame:
/// this connection logs its first rate, then a different one at most every ten seconds.
fn note_drm_demand(
shared: &std::sync::atomic::AtomicU8,
demand: u8,
crtc: u32,
logged: &mut Option<(u8, std::time::Instant)>,
) {
shared.store(demand, std::sync::atomic::Ordering::Relaxed);
if drm_demand_log_due(*logged, demand, std::time::Instant::now()) {
log::debug!("drm: crtc {crtc}: the consumer encodes at {demand} fps");
*logged = Some((demand, std::time::Instant::now()));
}
}
fn drm_demand_log_due(
logged: Option<(u8, std::time::Instant)>,
demand: u8,
now: std::time::Instant,
) -> bool {
demand != 0
&& logged.map_or(true, |(v, at)| {
v != demand && now.saturating_duration_since(at) >= std::time::Duration::from_secs(10)
})
}
/// When the worker wakes: for the next frame, and at least every FRAME_INTERVAL, because each
/// tick also reads the cursor and a slow frame rate must not slow the cursor down.
fn drm_worker_wake(now: std::time::Instant, next_frame: std::time::Instant) -> std::time::Instant {
next_frame.min(now + FRAME_INTERVAL)
}
fn drm_capture_worker(
frame_tx: tokio::sync::mpsc::Sender<DrmProducerMsg>,
crtc_rx: std::sync::mpsc::Receiver<(String, u32, bool)>,
stop: std::sync::Arc<std::sync::atomic::AtomicBool>,
frames_gated: std::sync::Arc<std::sync::atomic::AtomicBool>,
demand_fps: std::sync::Arc<std::sync::atomic::AtomicU8>,
wake: bool,
) {
use std::sync::atomic::Ordering;
use std::time::Duration;
const FRAME_INTERVAL: Duration = Duration::from_millis(33);
// Bound continuous no-frame (WouldBlock) time so a wedged device ends the stream (~5 s).
const MAX_STALLED: u32 = 150;
let t_conn = std::time::Instant::now();
@@ -1175,6 +1307,8 @@ fn drm_capture_worker(
"drm: capture reader for crtc {target_crtc} opened in {:?}",
t_open.elapsed()
);
let mut panel = drm_read_panel_period(&mut reader, &target_device, target_crtc, None);
let mut panel_read_at = std::time::Instant::now();
static DRM_CONN_EPOCH: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
let conn_epoch = DRM_CONN_EPOCH.fetch_add(1, Ordering::Relaxed);
@@ -1184,8 +1318,11 @@ fn drm_capture_worker(
let mut last_cursor_id: u64 = 0;
let mut stalled: u32 = 0;
let mut logged_first = false;
let mut next_frame = std::time::Instant::now();
while !stop.load(Ordering::Relaxed) {
let mut grabbed: Option<std::io::Result<DrmProducerMsg>> = if frames_gated.load(Ordering::Relaxed)
let frame_due = std::time::Instant::now() >= next_frame;
let mut grabbed: Option<std::io::Result<DrmProducerMsg>> = if !frame_due
|| frames_gated.load(Ordering::Relaxed)
{
// `stalled` is left untouched because the device is healthy -- the task bounds this
// state itself (CREDIT_STALL) since our watchdog cannot advance.
@@ -1262,6 +1399,8 @@ fn drm_capture_worker(
break;
}
std::thread::sleep(FRAME_INTERVAL);
// Or the first good grab after the stall finds its deadline gone and grabs twice.
next_frame = std::time::Instant::now();
continue;
}
Some(Err(err)) if use_dmabuf && err.kind() == std::io::ErrorKind::Unsupported => {
@@ -1301,10 +1440,49 @@ fn drm_capture_worker(
}
}
std::thread::sleep(FRAME_INTERVAL);
if panel_read_at.elapsed() >= std::time::Duration::from_secs(1) {
panel = drm_read_panel_period(&mut reader, &target_device, target_crtc, Some(panel));
panel_read_at = std::time::Instant::now();
}
let now = std::time::Instant::now();
// A frame tick the credit held back is retried one pacing interval later.
if frame_due {
next_frame = drm_next_tick(next_frame, now, demand_fps.load(Ordering::Relaxed), panel);
}
std::thread::sleep(drm_worker_wake(now, next_frame).saturating_duration_since(now));
}
}
/// The panel period of `crtc`, exact when the library can say (libdrmtap 0.5.9, one GETCRTC), else
/// the whole-hertz refresh the last enumeration saw; zero when neither is known, which leaves the
/// pacing to the demand.
fn drm_read_panel_period(
reader: &mut scrap::drm_reader::DrmReader,
device: &str,
crtc: u32,
prev: Option<std::time::Duration>,
) -> std::time::Duration {
let (period, how) = match reader.crtc_refresh() {
Some((num, den)) => (drm_panel_period(num, den), format!("{num}/{den} Hz")),
None => {
let hz = drm_whole_hz(device, crtc);
(drm_panel_period(u64::from(hz), 1), format!("{hz} Hz (whole hertz)"))
}
};
if prev != Some(period) {
log::debug!("drm: crtc {crtc} refreshes at {how}: grabs never outpace {period:?}");
}
period
}
fn drm_whole_hz(device: &str, crtc: u32) -> u32 {
DRM_WHOLE_HZ
.lock()
.ok()
.and_then(|hz| hz.get(&(device.to_owned(), crtc)).copied())
.unwrap_or(0)
}
/// Ancillary-fd transport for `_drm`: `Framed`/`BytesCodec` cannot carry an SCM_RIGHTS cmsg, so the
/// messages and raw bodies use a 4-byte big-endian length + payload, with any fd bound to the first
/// byte. The reverse-direction frame acks are bare bytes, not framed.
@@ -1533,7 +1711,7 @@ impl DrmConn {
drm_send_frame(&self.stream, &payload, pass_fd).await
}
pub async fn send_frame_ack(&self) -> ResultType<()> {
pub async fn send_frame_ack(&self, demand_fps: u8) -> ResultType<()> {
let deadline =
tokio::time::Instant::now() + std::time::Duration::from_millis(DRM_SEND_TIMEOUT_MS);
loop {
@@ -1543,7 +1721,7 @@ impl DrmConn {
"drm: _drm frame-ack was not accepted within {DRM_SEND_TIMEOUT_MS}ms; closing"
),
}
match self.stream.try_write(&[1u8]) {
match self.stream.try_write(&[drm_ack_byte(demand_fps)]) {
Ok(n) if n > 0 => return Ok(()),
Ok(_) => bail!("drm: _drm frame-ack write returned 0 (peer closed)"),
Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => continue,
@@ -1552,7 +1730,7 @@ impl DrmConn {
}
}
pub fn drain_frame_acks(&self, credit: &mut i32, max: i32) -> ResultType<()> {
pub fn drain_frame_acks(&self, credit: &mut i32, max: i32, demand: &mut u8) -> ResultType<()> {
let mut buf = [0u8; 64];
// BOUNDED: "until WouldBlock" is the peer's promise; a continuous writer would pin us.
const MAX_ACK_READS: usize = 64;
@@ -1561,6 +1739,9 @@ impl DrmConn {
Ok(0) => bail!("drm: _drm frame-ack peer closed"),
Ok(n) => {
*credit = (*credit + n as i32).min(max);
if let Some(d) = buf[..n].iter().rev().find_map(|&b| drm_ack_demand(b)) {
*demand = d;
}
if *credit >= max {
return Ok(());
}
@@ -1644,6 +1825,45 @@ impl DrmConn {
}
}
#[cfg(test)]
mod drm_pacing_tests {
use super::*;
use hbb_common::tokio;
/// An ack is one credit, as an older producer counts it, and a new one reads the demand from it.
#[tokio::test]
async fn a_demand_ack_is_one_credit_and_carries_the_demand() {
let (a, b) = tokio::net::UnixStream::pair().unwrap();
let tx = DrmConn::new(a);
let rx = DrmConn::new(b);
tx.send_frame_ack(60).await.unwrap();
rx.wait_readable().await.unwrap();
let (mut credit, mut demand) = (0, 0);
rx.drain_frame_acks(&mut credit, 2, &mut demand).unwrap();
assert_eq!((credit, demand), (1, 60));
}
#[test]
fn the_pacing_interval_follows_the_demand_with_the_panel_as_floor() {
let p60 = drm_panel_period(60, 1);
let p2998 = drm_panel_period(131375, 4382);
assert_eq!(
drm_panel_period(148352, 2475),
std::time::Duration::from_nanos(16_683_294),
"59.94 Hz, rounded up"
);
let cases = [
(0u8, p60, FRAME_INTERVAL, "no demand: the old tick"),
(60, p60, p60, "60 on a 60 Hz panel"),
(120, p60, p60, "more than the panel shows: the panel"),
(60, p2998, p2998, "a 29.98 Hz panel, exactly"),
];
for (demand, panel, want, why) in cases {
assert_eq!(drm_pacing_interval(demand, panel), want, "{why}");
}
}
}
#[cfg(test)]
mod drm_conn_tests {
use super::*;
@@ -1651,90 +1871,12 @@ mod drm_conn_tests {
use hbb_common::tokio::{self, io::AsyncWriteExt};
use std::os::fd::{AsFd, AsRawFd, FromRawFd, OwnedFd};
// Added to the wire later: an older peer's message must still decode.
#[test]
fn drm_display_info_decodes_without_render_node() {
let legacy = r#"{"name":"DP-1","crtc_id":386,"x":0,"y":0,
"width":3840,"height":2160,"active":true}"#;
let info: DrmDisplayInfo =
serde_json::from_str(legacy).expect("a pre-render_node payload must still decode");
assert_eq!(info.name, "DP-1");
assert_eq!(info.crtc_id, 386);
assert!(info.render_node.is_empty(), "missing node; the consumer auto-selects only where there is one render node");
assert!(info.device.is_empty(), "missing device means auto-detect");
let current = DrmDisplayInfo {
name: "DP-1".to_owned(),
crtc_id: 386,
x: 0,
y: 0,
width: 3840,
height: 2160,
active: true,
render_node: "/dev/dri/renderD129".to_owned(),
device: "/dev/dri/card2".to_owned(),
};
let wire = serde_json::to_vec(&current).unwrap();
let back: DrmDisplayInfo = serde_json::from_slice(&wire).unwrap();
assert_eq!(back, current);
}
fn pipe() -> (OwnedFd, OwnedFd) {
let mut fds = [0 as libc::c_int; 2];
assert_eq!(unsafe { libc::pipe(fds.as_mut_ptr()) }, 0, "pipe() failed");
unsafe { (OwnedFd::from_raw_fd(fds[0]), OwnedFd::from_raw_fd(fds[1])) }
}
unsafe fn send_with_fds(sock: libc::c_int, data: &[u8], fds: &[libc::c_int]) -> isize {
let mut iov = libc::iovec {
iov_base: data.as_ptr() as *mut libc::c_void,
iov_len: data.len(),
};
let fdbytes = fds.len() * std::mem::size_of::<libc::c_int>();
let space = libc::CMSG_SPACE(fdbytes as u32) as usize;
let mut cbuf = vec![0u8; space];
let mut msg: libc::msghdr = std::mem::zeroed();
msg.msg_iov = &mut iov;
msg.msg_iovlen = 1;
msg.msg_control = cbuf.as_mut_ptr() as *mut libc::c_void;
msg.msg_controllen = space as _;
let cmsg = libc::CMSG_FIRSTHDR(&msg);
(*cmsg).cmsg_level = libc::SOL_SOCKET;
(*cmsg).cmsg_type = libc::SCM_RIGHTS;
(*cmsg).cmsg_len = libc::CMSG_LEN(fdbytes as u32) as _;
std::ptr::copy_nonoverlapping(fds.as_ptr() as *const u8, libc::CMSG_DATA(cmsg), fdbytes);
libc::sendmsg(sock, &msg, 0)
}
#[tokio::test]
async fn roundtrip_msg_no_fd() {
let (a, b) = tokio::net::UnixStream::pair().unwrap();
let mut tx = DrmConn::new(a);
let mut rx = DrmConn::new(b);
tx.send_msg(
&Data::DrmFrame {
width: 1920,
height: 1080,
plane_rotation: None,
cursor_pos: None,
},
None,
)
.await
.unwrap();
let (data, fd) = rx.recv_msg().await.unwrap();
assert!(matches!(
data,
Data::DrmFrame {
width: 1920,
height: 1080,
plane_rotation: None,
cursor_pos: None
}
));
assert!(fd.is_none(), "no fd was sent, none must be reported");
}
#[tokio::test]
async fn roundtrip_msg_with_fd_identity() {
let (a, b) = tokio::net::UnixStream::pair().unwrap();
@@ -1800,131 +1942,6 @@ mod drm_conn_tests {
);
}
#[tokio::test]
async fn a_body_that_never_arrives_times_out() {
let (mut a, b) = tokio::net::UnixStream::pair().unwrap();
let mut rx = DrmConn::new(b);
a.write_all(&10u32.to_be_bytes()).await.unwrap();
let mut got = Vec::new();
let err = rx
.next_raw_into(&mut got)
.await
.err()
.expect("a body that never arrives must time out");
assert!(
err.to_string().contains("did not arrive"),
"unexpected error: {err}"
);
}
#[tokio::test]
async fn a_dripping_peer_cannot_re_arm_the_send_deadline() {
use tokio::io::AsyncReadExt;
let (mut reader, writer) = tokio::net::UnixStream::pair().unwrap();
let payload = vec![0u8; 32 * 1024 * 1024];
// Measured: 1 KiB drains do not re-assert POLLOUT; 64 KiB does, which separates the forms.
let drip = tokio::spawn(async move {
let mut sink = vec![0u8; 64 * 1024];
loop {
if reader.read(&mut sink).await.unwrap_or(0) == 0 {
break;
}
tokio::time::sleep(std::time::Duration::from_millis(250)).await;
}
});
let started = std::time::Instant::now();
let outcome = tokio::time::timeout(
std::time::Duration::from_millis(DRM_SEND_TIMEOUT_MS * 4),
drm_write_all(&writer, &payload, None),
)
.await;
drip.abort();
let inner = outcome.expect(
"the send deadline did not fire: the budget is being re-armed per readiness wait",
);
let err = inner.err().expect("a dripping peer must not complete the write");
assert!(
err.to_string().contains("did not accept the remaining"),
"unexpected error: {err}"
);
assert!(
started.elapsed() < std::time::Duration::from_millis(DRM_SEND_TIMEOUT_MS * 3),
"took {:?}, which is not the send deadline firing",
started.elapsed()
);
}
#[tokio::test]
async fn surplus_fds_keep_only_the_first() {
let (mut a, b) = tokio::net::UnixStream::pair().unwrap();
let mut rx = DrmConn::new(b);
let (rd, wr) = pipe();
let (rd2, _wr2) = pipe();
let payload = serde_json::to_vec(&Data::DrmFrame {
width: 8,
height: 8,
plane_rotation: None,
cursor_pos: None,
})
.unwrap();
let prefix = (payload.len() as u32).to_be_bytes();
let n = unsafe { send_with_fds(a.as_raw_fd(), &prefix, &[rd.as_raw_fd(), rd2.as_raw_fd()]) };
assert!(n >= 0, "sendmsg failed: {}", std::io::Error::last_os_error());
a.write_all(&payload).await.unwrap();
let (data, fd) = rx.recv_msg().await.unwrap();
assert!(matches!(
data,
Data::DrmFrame {
width: 8,
height: 8,
plane_rotation: None,
cursor_pos: None
}
));
let kept = fd.expect("the first surplus fd must be kept");
let sentinel = [0x5Au8];
assert_eq!(
unsafe { libc::write(wr.as_raw_fd(), sentinel.as_ptr() as *const libc::c_void, 1) },
1
);
let mut got = [0u8; 1];
assert_eq!(
unsafe { libc::read(kept.as_raw_fd(), got.as_mut_ptr() as *mut libc::c_void, 1) },
1
);
assert_eq!(got[0], 0x5A, "the kept fd must be the FIRST one sent");
}
// 16 fds need CMSG_LEN(64)=80 > the 64-byte DRM_CMSG_CAP, so the kernel sets MSG_CTRUNC.
#[tokio::test]
async fn rejects_truncated_control_message() {
let (a, b) = tokio::net::UnixStream::pair().unwrap();
let mut rx = DrmConn::new(b);
let (rd, _wr) = pipe();
let dups: Vec<OwnedFd> = (0..16).map(|_| rd.try_clone().unwrap()).collect();
let fds: Vec<libc::c_int> = dups.iter().map(|f| f.as_raw_fd()).collect();
let prefix = 0u32.to_be_bytes(); // the fds ride the prefix read; CTRUNC fires before any body
let n = unsafe { send_with_fds(a.as_raw_fd(), &prefix, &fds) };
assert!(n >= 0, "sendmsg failed: {}", std::io::Error::last_os_error());
let err = rx
.recv_msg()
.await
.err()
.expect("a truncated control message must be rejected");
let msg = err.to_string().to_lowercase();
assert!(
msg.contains("truncat") || msg.contains("ctrunc"),
"unexpected error: {err}"
);
}
#[test]
fn peer_uid_from_fd_reads_socket_peer() {
let (a, _b) = std::os::unix::net::UnixStream::pair().unwrap();
let euid = unsafe { libc::geteuid() };
assert_eq!(peer_uid_from_fd(a.as_raw_fd()), Some(euid));
}
#[test]
fn drm_peer_authorized_matrix() {
assert!(drm_peer_authorized(Some(0), Some(1000)));
@@ -1976,24 +1993,4 @@ mod drm_conn_tests {
assert!(super::ipc_auth::ensure_peer_executable_matches_current_by_pid_opt(None, "_drm").is_err());
}
#[test]
fn drm_conn_admission_bound() {
assert!(drm_conn_admitted(0));
assert!(drm_conn_admitted(MAX_DRM_CONNS - 1)); // last admitted slot
assert!(!drm_conn_admitted(MAX_DRM_CONNS)); // cap reached -> rejected
assert!(!drm_conn_admitted(MAX_DRM_CONNS + 5)); // over cap -> rejected
}
#[test]
fn drm_auth_admission_bound() {
assert!(drm_auth_admitted(0));
assert!(drm_auth_admitted(MAX_DRM_AUTH_IN_FLIGHT - 1)); // last admitted slot
assert!(!drm_auth_admitted(MAX_DRM_AUTH_IN_FLIGHT)); // cap reached -> rejected
assert!(!drm_auth_admitted(MAX_DRM_AUTH_IN_FLIGHT + 5)); // over cap -> rejected
assert!(
MAX_DRM_AUTH_IN_FLIGHT <= MAX_DRM_CONNS,
"the pre-auth bound must not be looser than the connection cap"
);
}
}
-44
View File
@@ -982,48 +982,4 @@ mod tests {
std::fs::remove_dir_all(&base).ok();
}
#[test]
fn test_ensure_secure_ipc_parent_dir_marks_non_service_mode_repair_for_scrub() {
use std::os::unix::fs::PermissionsExt;
let unique = format!(
"rustdesk-ipc-nonservice-mode-repair-test-{}-{}",
std::process::id(),
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap_or_default()
.as_nanos()
);
let base = std::env::temp_dir().join(unique);
std::fs::create_dir_all(&base).unwrap();
let parent_dir = base.join("non_service_parent");
std::fs::create_dir_all(&parent_dir).unwrap();
std::fs::set_permissions(&parent_dir, std::fs::Permissions::from_mode(0o755)).unwrap();
let ipc_file = parent_dir.join("ipc");
std::fs::write(&ipc_file, b"socket-placeholder").unwrap();
let res = super::ensure_secure_ipc_parent_dir(ipc_file.to_string_lossy().as_ref(), "");
assert_eq!(res.unwrap(), true);
std::fs::remove_dir_all(&base).ok();
}
#[test]
fn test_should_scrub_parent_entries_after_check_pid_only_when_requested_and_not_alive() {
assert!(!super::should_scrub_parent_entries_after_check_pid(
false, false
));
assert!(!super::should_scrub_parent_entries_after_check_pid(
false, true
));
assert!(super::should_scrub_parent_entries_after_check_pid(
true, false
));
assert!(!super::should_scrub_parent_entries_after_check_pid(
true, true
));
}
}
-36
View File
@@ -275,40 +275,4 @@ mod tests {
}
assert_eq!(got, N, "graceful close lost frames");
}
// Socket errors on the connected UDP socket (ICMP unreachable after the peer
// vanishes) are advisory: the io loop must treat them as loss - keep accepting
// writes, keep running - rather than tearing the session down. Whether the OS
// actually surfaces ECONNREFUSED here is platform-dependent; either way the
// session must stay alive for this window.
#[tokio::test]
async fn test_kcp_io_treats_socket_errors_as_loss() {
let ((_guard_a, mut stream_a), (guard_b, stream_b)) = establish().await;
// Kill the peer entirely: endpoint stops, socket closes.
drop(stream_b);
drop(guard_b);
tokio::time::sleep(Duration::from_millis(50)).await;
for _ in 0..10 {
stream_a
.send_bytes(Bytes::from_static(b"into the void"))
.await
.expect("socket errors must be treated as loss, not stream failure");
tokio::time::sleep(Duration::from_millis(20)).await;
}
}
// The connect deadline must hold when nothing answers: no hang, prompt error.
#[tokio::test]
async fn test_kcp_connect_timeout_without_peer() {
let (a, _b) = connected_pair().await;
let start = tokio::time::Instant::now();
let res = KcpStream::connect(a, Duration::from_millis(600)).await;
assert!(res.is_err(), "connect must fail with no peer endpoint");
assert!(
start.elapsed() < Duration::from_secs(5),
"connect did not honor its deadline"
);
}
}
-18
View File
@@ -336,16 +336,6 @@ mod test {
);
}
#[test]
fn test_resolve_lang_forces_english_for_saved_cjk_when_target_disables_cjk() {
use super::resolve_lang as f;
assert_eq!(f("zh-cn", "en-US", true), "en");
assert_eq!(f("zh-tw", "en-US", true), "en");
assert_eq!(f("ja", "en-US", true), "en");
assert_eq!(f("ko", "en-US", true), "en");
}
#[test]
fn test_resolve_lang_forces_english_for_cjk_locale_when_target_disables_cjk() {
use super::resolve_lang as f;
@@ -375,12 +365,4 @@ mod test {
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");
}
}
+32 -32
View File
@@ -781,37 +781,37 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("Relay fallback delay in seconds", "Ritardo fallback relay (secondi)"),
("relay-fallback-delay-tip", "Quanto tempo una connessione relay già attiva attende la connessione WebRTC diretta prima di essere usata. Aumentalo per dare a una connessione diretta lenta più tempo per funzionare; diminuiscilo per passare prima al relay sulle reti in cui non è possibile effettuare una connessione diretta. Lascia vuoto per il valore predefinito di 2,5 secondi."),
("To start a voice call, enable \"Audio capture\" on the \"Share screen\" page.", "Per avviare una chiamata vocale, attiva nella pagina 'Condividi schermo' la voce 'Cattura audio'."),
("Keyboard shortcuts", ""),
("Configure shortcuts...", ""),
("Enable keyboard shortcuts in remote session", ""),
("shortcut-page-description", ""),
("shortcut-passthrough-tip", ""),
("Pass-through to remote", ""),
("Reset to defaults", ""),
("shortcut-reset-confirm-tip", ""),
("Monitor", ""),
("Keyboard", ""),
("Toggle fullscreen", ""),
("Switch to next display", ""),
("Switch to previous display", ""),
("Switch to next tab", ""),
("Switch to previous tab", ""),
("Toggle session recording", ""),
("Close tab", ""),
("Toggle toolbar", ""),
("Toggle input source", ""),
("Edit", ""),
("Save", ""),
("Set shortcut", ""),
("shortcut-recording-instruction", ""),
("shortcut-recording-press-keys-tip", ""),
("shortcut-must-include-modifiers", ""),
("shortcut-already-bound-to", ""),
("Replace", ""),
("Valid", ""),
("shortcut-mobile-physical-keyboard-tip", ""),
("shortcut-key-not-supported", ""),
("On", ""),
("Off", ""),
("Keyboard shortcuts", "Scorciatoie da tastiera"),
("Configure shortcuts...", "Configura scorciatoie..."),
("Enable keyboard shortcuts in remote session", "Nella sessione remota abilita scorciatoie da tastiera"),
("shortcut-page-description", "Associa una combinazione di tasti a ciascuna azione della sessione riportata di seguito. Ogni associazione deve includere almeno un modificatore."),
("shortcut-passthrough-tip", "Quando è attiva, ogni combinazione associata viene inoltrata alla sessione remota. Utile quando un'associazione entra in conflitto con qualcosa di cui hai bisogno nella sessione remota."),
("Pass-through to remote", "Passa direttamente al remoto"),
("Reset to defaults", "Ripristina impostazioni predefinite"),
("shortcut-reset-confirm-tip", "Questo sostituirà tutti le associazioni attuali con quelle predefinite. Vuoi continuare?"),
("Monitor", "Monitor"),
("Keyboard", "Tastiera"),
("Toggle fullscreen", "Attiva/disattiva schermo pieno"),
("Switch to next display", "Passa allo schermo successivo"),
("Switch to previous display", "Passa allo schermo precedente"),
("Switch to next tab", "Passa alla scheda successiva"),
("Switch to previous tab", "Passa alla scheda precedente"),
("Toggle session recording", "Attiva/disattiva registrazione sessione"),
("Close tab", "Chiudi scheda"),
("Toggle toolbar", "Attiva/disattiva barra strumenti"),
("Toggle input source", "Attiva/disattiva sorgente input"),
("Edit", "Modifica"),
("Save", "Salva"),
("Set shortcut", "Imposta scorciatoia"),
("shortcut-recording-instruction", "Premi la combinazione di tasti che vuoi usare."),
("shortcut-recording-press-keys-tip", "Premi una combinazione di tasti..."),
("shortcut-must-include-modifiers", "Deve includere almeno un modificatore: {}"),
("shortcut-already-bound-to", "Già assegnato a"),
("Replace", "Sostituisci"),
("Valid", "Valido"),
("shortcut-mobile-physical-keyboard-tip", "La registrazione richiede una tastiera fisica. Le tastiere software non sono supportate."),
("shortcut-key-not-supported", "'{}' non può essere usato come scorciatoia."),
("On", "ON"),
("Off", "OFF"),
].iter().cloned().collect();
}
+51 -51
View File
@@ -7,11 +7,11 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("Password", "Wachtwoord"),
("Ready", "Gereed"),
("Established", "Opgezet"),
("connecting_status", "Verbinding maken met het RustDesk-netwerk..."),
("connecting_status", "Verbinding maken met het RustDesk-netwerk…"),
("Enable service", "Service inschakelen"),
("Start service", "Service starten"),
("Service is running", "De service loopt."),
("Service is not running", "De service loopt niet"),
("Service is running", "Service loopt."),
("Service is not running", "Service loopt niet"),
("not_ready_status", "Niet verbonden met de server, controleer de netwerkverbinding"),
("Control Remote Desktop", "Extern Bureaublad beheren"),
("Transfer file", "Bestand overzetten"),
@@ -76,12 +76,12 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("Connection Error", "Fout bij verbinding"),
("Error", "Fout"),
("Reset by the peer", "Door de peer gereset"),
("Connecting...", "Verbinding maken..."),
("Connecting...", "Verbinding maken…"),
("Connection in progress. Please wait.", "Verbinding wordt gemaakt. Even geduld."),
("Please try 1 minute later", "Probeer opnieuw over 1 minuut"),
("Login Error", "Loginfout"),
("Successful", "Geslaagd"),
("Connected, waiting for image...", "Verbonden, wachten op beeld..."),
("Connected, waiting for image...", "Verbonden, wachten op beeld…"),
("Name", "Naam"),
("Type", "Type"),
("Modified", "Gewijzigd"),
@@ -94,7 +94,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("Remote", "Op afstand"),
("Remote Computer", "Externe computer"),
("Local Computer", "Lokale computer"),
("Confirm Delete", "Verwijderen bevestigen"),
("Confirm Delete", "Verwijdering bevestigen"),
("Delete", "Verwijderen"),
("Properties", "Eigenschappen"),
("Multi Select", "Meervoudige selectie"),
@@ -127,7 +127,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("Optimize reaction time", "Responstijd optimaliseren"),
("Custom", "Aangepast"),
("Show remote cursor", "Cursor van extern bureaublad weergeven"),
("Show quality monitor", "Kwaliteitsmonitor tonen"),
("Show quality monitor", "Kwaliteitsmonitor weergeven"),
("Disable clipboard", "Klembord uitschakelen"),
("Lock after session end", "Vergrendelen na einde sessie"),
("Insert Ctrl + Alt + Del", "Ctrl + Alt + Del invoeren"),
@@ -150,7 +150,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("Configure", "Configureren"),
("config_acc", "Om uw apparaat op afstand te kunnen bedienen, moet u RustDesk toestemming geven voor Toegankelijkheid."),
("config_screen", "Om uw apparaat op afstand te kunnen bedienen, moet u RustDesk toestemming geven voor Schermopname."),
("Installing ...", "Installeren ..."),
("Installing ...", "Installeren…"),
("Install", "Installeren"),
("Installation", "Installatie"),
("Installation Path", "Locatie"),
@@ -159,10 +159,10 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("agreement_tip", "Het starten van de installatie betekent het accepteren van de licentieovereenkomst."),
("Accept and Install", "Accepteren en installeren"),
("End-user license agreement", "Eindgebruikerslicentieovereenkomst"),
("Generating ...", "Genereren ..."),
("Generating ...", "Genereren…"),
("Your installation is lower version.", "Uw installatie is een lagere versie."),
("not_close_tcp_tip", "Sluit dit venster niet zolang u de tunnel gebruikt"),
("Listening ...", "Luisteren ..."),
("Listening ...", "Luisteren…"),
("Remote Host", "Externe host"),
("Remote Port", "Externe poort"),
("Action", "Actie"),
@@ -185,7 +185,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("Relayed and unencrypted connection", "Doorgeschakelde en niet-versleutelde verbinding"),
("Enter Remote ID", "Extern ID invoeren"),
("Enter your password", "Wachtwoord invoeren"),
("Logging in...", "Aanmelden..."),
("Logging in...", "Aanmelden…"),
("Enable RDP session sharing", "Delen van RDP-sessie inschakelen"),
("Auto Login", "Automatisch aanmelden"),
("Enable direct IP access", "Directe IP-toegang inschakelen"),
@@ -368,11 +368,11 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("Deny LAN discovery", "LAN-detectie weigeren"),
("Write a message", "Schrijf een bericht"),
("Prompt", "Melding"),
("Please wait for confirmation of UAC...", "Wacht op UAC-bevestiging..."),
("Please wait for confirmation of UAC...", "Wacht op UAC-bevestiging…"),
("elevated_foreground_window_tip", "Het momenteel geopende venster van de op afstand bediende computer vereist hogere rechten. Daarom is het momenteel niet mogelijk de muis en het toetsenbord te gebruiken. Vraag de gebruiker wiens computer u op afstand bedient om het venster te minimaliseren of de rechten te verhogen. Om dit probleem in de toekomst te voorkomen, wordt aanbevolen de software te installeren op de op afstand bediende computer."),
("Disconnected", "Afgesloten"),
("Other", "Andere"),
("Confirm before closing multiple tabs", "Bevestig voordat u meerdere tabbladen sluit"),
("Confirm before closing multiple tabs", "Bevestiging geven bij sluiten van meerdere tabbladen"),
("Keyboard Settings", "Toetsenbordinstellingen"),
("Full Access", "Volledige toegang"),
("Screen Share", "Scherm delen"),
@@ -381,7 +381,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("xdp-portal-unavailable", "Wayland schermopname is mislukt. De XDG Desktop Portal kan gecrashed zijn of is onbeschikbaar. Probeer het opnieuw te starten met `systemctl --user restart xdg-desktop-portal`."),
("JumpLink", "JumpLink"),
("Please Select the screen to be shared(Operate on the peer side).", "Selecteer het scherm dat moet worden gedeeld (Bediening aan de kant van de peer)."),
("Show RustDesk", "Toon RustDesk"),
("Show RustDesk", "RustDesk weergeven"),
("This PC", "Deze PC"),
("or", "of"),
("Elevate", "Verhogen"),
@@ -389,7 +389,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("Accept sessions via password", "Sessies accepteren via wachtwoord"),
("Accept sessions via click", "Sessies accepteren via klik"),
("Accept sessions via both", "Accepteer sessies via klik of wachtwoord"),
("Please wait for the remote side to accept your session request...", "Wacht tot de andere kant uw sessieverzoek accepteert..."),
("Please wait for the remote side to accept your session request...", "Wacht tot de andere kant uw sessieverzoek accepteert…"),
("One-time Password", "Eenmalig wachtwoord"),
("Use one-time password", "Eenmalig wachtwoord gebruiken"),
("One-time password length", "Lengte eenmalig wachtwoord"),
@@ -428,7 +428,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("Medium", "Middelmatig"),
("Strong", "Sterk"),
("Switch Sides", "Van kant wisselen"),
("Please confirm if you want to share your desktop?", "Bevestig dat u uw bureaublad wilt delen?"),
("Please confirm if you want to share your desktop?", "Weet u zeker dat u uw bureaublad wilt delen?"),
("Display", "Weergave"),
("Default View Style", "Standaard Weergavestijl"),
("Default Scroll Style", "Standaard Scrollstijl"),
@@ -649,13 +649,13 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("use-the-default-printer-tip", "Standaard printer gebruiken"),
("use-the-selected-printer-tip", "Geselecteerde printer gebruiken"),
("auto-print-tip", "Automatisch afdrukken op de geselecteerde printer."),
("print-incoming-job-confirm-tip", "Er werd een afdruktaak ontvangen van een extern apparaat. Moet ik deze lokaal afdrukken?"),
("remote-printing-disallowed-tile-tip", "Afdruk op afstand is verboden"),
("print-incoming-job-confirm-tip", "Er werd een afdruktaak ontvangen van een extern apparaat. Moet deze lokaal worden afgedrukt?"),
("remote-printing-disallowed-tile-tip", "Afdruk op afstand is niet toegestaan"),
("remote-printing-disallowed-text-tip", "Machtigingsinstellingen aan beheerde zijde verhinderen afdrukken op afstand."),
("save-settings-tip", "Instellingen opslaan"),
("dont-show-again-tip", "Dit bericht wordt niet meer weergegeven"),
("Take screenshot", "Schermopname maken"),
("Taking screenshot", "Schermopname maken..."),
("Taking screenshot", "Schermopname maken…"),
("screenshot-merged-screen-not-supported-tip", "Schermopnames van meerdere schermen samenvoegen wordt momenteel niet ondersteund. Schakel over naar een enkel scherm en herhaal de actie."),
("screenshot-action-tip", "Kies wat je met de gemaakte schermopname wilt doen."),
("Save as", "Opslaan als"),
@@ -693,7 +693,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("Failed to check if the user is an administrator.", "Fout bij het controleren of de gebruiker een beheerder is."),
("Supported only in the installed version.", "Alleen ondersteund in de geïnstalleerde versie."),
("elevation_username_tip", "Voer je gebruikersnaam of domeinnaam in"),
("Preparing for installation ...", "Installatie voorbereiden ..."),
("Preparing for installation ...", "Installatie voorbereiden…"),
("Show my cursor", "Mijn cursor weergeven"),
("Scale custom", "Aangepaste schaal"),
("Custom scale slider", "Aangepaste schuifregelaar voor schaal"),
@@ -713,8 +713,8 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("disable-udp-tip", "Controleert of alleen TCP moet worden gebruikt. Als deze optie is ingeschakeld, gebruikt RustDesk niet langer UDP 21116, maar TCP 21116."),
("server-oss-not-support-tip", "Opmerking: Deze functie is niet beschikbaar in de open-sourceversie van de RustDesk-server."),
("input note here", "voeg hier een opmerking toe"),
("note-at-conn-end-tip", "Vraag om een opmerking aan het einde van de verbinding"),
("Show terminal extra keys", "Toon extra toetsen voor terminal"),
("note-at-conn-end-tip", "Om een opmerking vragen aan het einde van de verbinding"),
("Show terminal extra keys", "Extra toetsen voor terminal weergeven"),
("Relative mouse mode", "Relatieve muismodus"),
("rel-mouse-not-supported-peer-tip", "De relatieve muismodus wordt niet ondersteund door het externe apparaat."),
("rel-mouse-not-ready-tip", "De relatieve muismodus was nog niet klaar, probeer het later opnieuw."),
@@ -763,8 +763,8 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("Lock canvas", "Canvas vergrendelen"),
("Sync clipboard between sessions", "Klembord synchroniseren tussen sessies"),
("sync-clipboard-between-sessions-tip", "Tekst of afbeeldingen die in één externe sessie worden gekopieerd, worden ook naar het klembord van uw andere verbonden sessies gestuurd."),
("terminal-clipboard-write-tip", ""),
("Allow terminal apps to copy to clipboard", ""),
("terminal-clipboard-write-tip", "Een app in de terminal wil tekst naar het klembord van dit apparaat kopiëren. Indien verleend, is deze toestemming van toepassing op terminal-apps in alle verbindingen totdat u deze uitschakelt in Instellingen. Handmatig kopiëren en plakken wordt niet beïnvloed."),
("Allow terminal apps to copy to clipboard", "Terminal-apps toestaan om naar klembord te kopiëren"),
("Enable", "Inschakelen"),
("Reuse one connection for port forwarding", "Eén verbinding hergebruiken voor poortdoorschakeling"),
("port-forward-mux-tip", "Alle verbindingen van een poortdoorschakeling via één enkele verbinding met de andere computer laten lopen, in plaats van voor elke verbinding opnieuw verbinding te maken en in te loggen."),
@@ -781,37 +781,37 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("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 \"Share screen\" page.", "Om een spraakgesprek te starten, schakel je \"Audio-opname\" in op de pagina \"Scherm delen\"."),
("Keyboard shortcuts", ""),
("Configure shortcuts...", ""),
("Enable keyboard shortcuts in remote session", ""),
("shortcut-page-description", ""),
("Keyboard shortcuts", "Sneltoetsen"),
("Configure shortcuts...", "Sneltoetsen configureren..."),
("Enable keyboard shortcuts in remote session", "Sneltoetsen inschakelen in een sessie op afstand"),
("shortcut-page-description", "Beschrijving van sneltoetsenpagina"),
("shortcut-passthrough-tip", ""),
("Pass-through to remote", ""),
("Reset to defaults", ""),
("Pass-through to remote", "Doorsturen naar extern apparaat"),
("Reset to defaults", "Terugzetten naar standaardinstellingen"),
("shortcut-reset-confirm-tip", ""),
("Monitor", ""),
("Keyboard", ""),
("Toggle fullscreen", ""),
("Switch to next display", ""),
("Switch to previous display", ""),
("Switch to next tab", ""),
("Switch to previous tab", ""),
("Toggle session recording", ""),
("Close tab", ""),
("Toggle toolbar", ""),
("Toggle input source", ""),
("Edit", ""),
("Save", ""),
("Set shortcut", ""),
("Monitor", "Monitor"),
("Keyboard", "Toetsenbord"),
("Toggle fullscreen", "Volledig scherm wisselen"),
("Switch to next display", "Wisselen naar volgend scherm"),
("Switch to previous display", "Wisselen naar vorig scherm"),
("Switch to next tab", "Schakel naar volgende tabblad"),
("Switch to previous tab", "Schakel naar vorig tabblad"),
("Toggle session recording", "Sessie-opname wisselen"),
("Close tab", "Tabblad sluiten"),
("Toggle toolbar", "Werkbalk wisselen"),
("Toggle input source", "Invoerbron wisselen"),
("Edit", "Bewerken"),
("Save", "Opslaan"),
("Set shortcut", "Sneltoets toewijzen"),
("shortcut-recording-instruction", ""),
("shortcut-recording-press-keys-tip", ""),
("shortcut-must-include-modifiers", ""),
("shortcut-already-bound-to", ""),
("Replace", ""),
("Valid", ""),
("shortcut-must-include-modifiers", "Sneltoets moet een combinatietoets bevatten"),
("shortcut-already-bound-to", "Sneltoets is al toegewezen aan"),
("Replace", "Vervangen"),
("Valid", "Geldig"),
("shortcut-mobile-physical-keyboard-tip", ""),
("shortcut-key-not-supported", ""),
("On", ""),
("Off", ""),
("shortcut-key-not-supported", "Sneltoets wordt niet ondersteund"),
("On", "Aan"),
("Off", "Uit"),
].iter().cloned().collect();
}
+33 -33
View File
@@ -780,38 +780,38 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("RustDesk could not load a GStreamer component needed for screen capture ({})", "O RustDesk não conseguiu carregar um componente do GStreamer necessário para a captura de tela ({})."),
("Relay fallback delay in seconds", "Atraso antes de recorrer ao retransmissor em segundos"),
("relay-fallback-delay-tip", "Tempo que a conexão de retransmissão aguarda pela conexão direta WebRTC. Aumente para dar mais tempo a conexões lentas; diminua para usar o retransmissor mais cedo. Deixe vazio para usar o padrão de 2,5 segundos."),
("To start a voice call, enable \"Audio capture\" on the \"Share screen\" page.", "Para iniciar uma chamada de voz, ative \"Captura de áudio\" na página \"Compartilhar Tela\"."),
("Keyboard shortcuts", ""),
("Configure shortcuts...", ""),
("Enable keyboard shortcuts in remote session", ""),
("shortcut-page-description", ""),
("shortcut-passthrough-tip", ""),
("Pass-through to remote", ""),
("Reset to defaults", ""),
("shortcut-reset-confirm-tip", ""),
("Monitor", ""),
("Keyboard", ""),
("Toggle fullscreen", ""),
("Switch to next display", ""),
("Switch to previous display", ""),
("Switch to next tab", ""),
("Switch to previous tab", ""),
("Toggle session recording", ""),
("Close tab", ""),
("Toggle toolbar", ""),
("Toggle input source", ""),
("Edit", ""),
("Save", ""),
("Set shortcut", ""),
("shortcut-recording-instruction", ""),
("shortcut-recording-press-keys-tip", ""),
("shortcut-must-include-modifiers", ""),
("shortcut-already-bound-to", ""),
("Replace", ""),
("Valid", ""),
("shortcut-mobile-physical-keyboard-tip", ""),
("shortcut-key-not-supported", ""),
("On", ""),
("Off", ""),
("To start a voice call, enable \"Audio capture\" on the \"Share screen\" page.", "Para iniciar uma chamada de voz, ative \"Captura de áudio\" na página \"Compartilhar tela\"."),
("Keyboard shortcuts", "Atalhos de teclado"),
("Configure shortcuts...", "Configurar atalhos..."),
("Enable keyboard shortcuts in remote session", "Ativar atalhos de teclado na sessão remota"),
("shortcut-page-description", "Associe uma combinação de teclas a cada ação da sessão abaixo. Cada atalho deve incluir pelo menos uma tecla modificadora."),
("shortcut-passthrough-tip", "Quando ativado, os atalhos são enviados ao computador remoto, mesmo quando entram em conflito com combinações de teclas necessárias nele."),
("Pass-through to remote", "Encaminhar atalhos ao computador remoto"),
("Reset to defaults", "Restaurar padrões"),
("shortcut-reset-confirm-tip", "Todos os atalhos atuais serão substituídos pelos padrões. Deseja continuar?"),
("Monitor", "Monitor"),
("Keyboard", "Teclado"),
("Toggle fullscreen", "Alternar tela cheia"),
("Switch to next display", "Alternar para a próxima tela"),
("Switch to previous display", "Alternar para a tela anterior"),
("Switch to next tab", "Alternar para a próxima aba"),
("Switch to previous tab", "Alternar para a aba anterior"),
("Toggle session recording", "Iniciar/parar gravação da sessão"),
("Close tab", "Fechar aba"),
("Toggle toolbar", "Mostrar/ocultar barra de ferramentas"),
("Toggle input source", "Alternar fonte de entrada"),
("Edit", "Editar"),
("Save", "Salvar"),
("Set shortcut", "Definir atalho"),
("shortcut-recording-instruction", "Pressione a combinação de teclas que deseja usar."),
("shortcut-recording-press-keys-tip", "Pressione uma combinação de teclas..."),
("shortcut-must-include-modifiers", "Deve incluir pelo menos uma tecla modificadora: {}"),
("shortcut-already-bound-to", "Já atribuído a"),
("Replace", "Substituir"),
("Valid", "Válido"),
("shortcut-mobile-physical-keyboard-tip", "A gravação de atalhos requer um teclado físico. Teclados virtuais não são compatíveis."),
("shortcut-key-not-supported", "Não é possível usar \"{}\" como atalho."),
("On", "Ativado"),
("Off", "Desativado"),
].iter().cloned().collect();
}
+1 -1
View File
@@ -637,7 +637,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("upgrade_remote_rustdesk_client_to_{}_tip", "Uppgradera RustDesk-klienten till version {} eller senare på fjärrsidan!"),
("d3d_render_tip", "När D3D-rendering är aktiverat kan fjärrstyrningsskärmen vara svart på vissa maskiner."),
("Use D3D rendering", "Använd D3D rendering"),
("Printer", "Skrivarer"),
("Printer", "Skrivare"),
("printer-os-requirement-tip", "Funktionen för utgående utskrift kräver Windows 10 eller senare."),
("printer-requires-installed-{}-client-tip", "För att kunna använda fjärrutskrift måste {} vara installerat på den här enheten."),
("printer-{}-not-installed-tip", "Skrivaren {} är inte installerad."),
+4
View File
@@ -29,6 +29,10 @@ pub mod ipc;
feature = "flutter"
)))]
pub mod ui;
pub(crate) mod update_metadata;
pub(crate) mod update_hash;
#[cfg(target_os = "macos")]
mod manual_update;
mod version;
pub use version::*;
#[cfg(any(target_os = "android", target_os = "ios", feature = "flutter"))]
+17 -9
View File
@@ -16,18 +16,26 @@ fn main() {
common::global_clean();
}
#[cfg(not(any(
target_os = "android",
target_os = "ios",
feature = "flutter"
)))]
fn main() {
#[cfg(not(any(target_os = "android", target_os = "ios", feature = "flutter")))]
fn main() -> std::process::ExitCode {
#[cfg(all(windows, not(feature = "inline")))]
unsafe {
winapi::um::shellscalingapi::SetProcessDpiAwareness(2);
}
if let Some(args) = crate::core_main::core_main().as_mut() {
ui::start(args);
}
// Preserve command failures, notably verified macOS offline update failures,
// as a non-zero process exit status for CLI callers.
let exit_code = match crate::core_main::core_main() {
Some(crate::core_main::CoreMainAction::StartUi(mut args)) => {
ui::start(&mut args);
std::process::ExitCode::SUCCESS
}
Some(crate::core_main::CoreMainAction::ExitFailure(err)) => {
eprintln!("Command failed: {err}");
hbb_common::log::error!("Command failed: {err}");
std::process::ExitCode::FAILURE
}
None => std::process::ExitCode::SUCCESS,
};
common::global_clean();
exit_code
}
+210
View File
@@ -0,0 +1,210 @@
use hbb_common::{
anyhow::{anyhow, Context},
bail, log, ResultType,
};
use std::{io::Read, path::Path};
const UPDATE_SIDECAR_MAX_BYTES: u64 = 1024 * 1024;
const PUBLIC_MACOS_BUNDLE_ID: &str = "com.carriez.rustdesk";
const MACOS_UPDATE_USAGE: &str = "Usage: --update [update.dmg --metadata rustdesk-update.json --signature rustdesk-update.json.sig]";
const LEGACY_UPDATE_WARNING: &str =
"legacy offline update: signed metadata not found; release hash was not verified";
#[derive(Debug, Eq, PartialEq)]
enum MacosUpdateArguments<'a> {
CurrentApp,
LegacyDmg(&'a str),
VerifiedDmg {
dmg_path: &'a str,
metadata_path: &'a str,
signature_path: &'a str,
},
}
fn parse_macos_update_args(args: &[String]) -> ResultType<MacosUpdateArguments<'_>> {
match args {
[command] if command == "--update" => Ok(MacosUpdateArguments::CurrentApp),
[command, dmg_path] if command == "--update" && dmg_path.ends_with(".dmg") => {
Ok(MacosUpdateArguments::LegacyDmg(dmg_path))
}
[command, dmg_path, metadata_flag, metadata_path, signature_flag, signature_path]
if command == "--update"
&& dmg_path.ends_with(".dmg")
&& metadata_flag == "--metadata"
&& signature_flag == "--signature" =>
{
Ok(MacosUpdateArguments::VerifiedDmg {
dmg_path,
metadata_path,
signature_path,
})
}
_ => bail!(MACOS_UPDATE_USAGE),
}
}
fn expected_update_package_id(
is_custom_client: bool,
bundle_id: Option<String>,
) -> ResultType<String> {
let bundle_id = bundle_id
.filter(|value| !value.is_empty())
.ok_or_else(|| anyhow!("client bundle identifier is missing"))?;
if !is_custom_client && bundle_id == PUBLIC_MACOS_BUNDLE_ID {
return Ok(crate::update_metadata::PUBLIC_UPDATE_PACKAGE_ID.to_owned());
}
Ok(bundle_id)
}
fn installed_update_package_id() -> ResultType<String> {
expected_update_package_id(
crate::common::is_custom_client(),
crate::platform::macos::get_bundle_id(),
)
}
fn read_update_sidecar(path: &str) -> ResultType<Vec<u8>> {
let path_metadata = std::fs::symlink_metadata(path)
.with_context(|| format!("failed to inspect update sidecar {path}"))?;
if !path_metadata.file_type().is_file() {
bail!("update sidecar is not a regular file: {path}");
}
if path_metadata.len() > UPDATE_SIDECAR_MAX_BYTES {
bail!("update sidecar exceeds maximum size: {path}");
}
let file = std::fs::File::open(path)
.with_context(|| format!("failed to open update sidecar {path}"))?;
let mut bytes = Vec::new();
file.take(UPDATE_SIDECAR_MAX_BYTES.saturating_add(1))
.read_to_end(&mut bytes)?;
if bytes.len() as u64 > UPDATE_SIDECAR_MAX_BYTES {
bail!("update sidecar exceeds maximum size: {path}");
}
Ok(bytes)
}
fn update_current_app() -> ResultType<()> {
println!("Starting update process...");
log::info!("Starting update process...");
crate::platform::update_me()?;
println!(
"{}",
crate::client::translate("Updated successfully!".to_owned())
);
log::info!("Updated successfully!");
Ok(())
}
fn update_legacy_dmg(dmg_path: &str) -> ResultType<()> {
eprintln!("Warning: {LEGACY_UPDATE_WARNING}");
log::warn!("{LEGACY_UPDATE_WARNING}");
println!("Updating from DMG: {dmg_path}");
crate::platform::update_from_dmg(dmg_path)?;
println!("Update process from DMG started successfully.");
Ok(())
}
fn update_verified_dmg(
dmg_path: &str,
metadata_path: &str,
signature_path: &str,
) -> ResultType<()> {
let file_name = Path::new(dmg_path)
.file_name()
.and_then(|name| name.to_str())
.ok_or_else(|| anyhow!("invalid update DMG file name"))?;
let metadata = read_update_sidecar(metadata_path)?;
let signature = read_update_sidecar(signature_path)?;
let expected_package_id = installed_update_package_id()?;
let artifact = crate::update_metadata::verify_offline_update_metadata(
&metadata,
&signature,
crate::update_metadata::OfflineUpdateMetadataRequirements {
local_file_name: file_name,
expected_package_id: &expected_package_id,
artifact: crate::updater::current_update_artifact_query(false),
},
)?;
println!("Updating from DMG verified by signed metadata: {dmg_path}");
crate::platform::macos::update_to_verified_dmg(
dmg_path,
&artifact.sha256,
Some(artifact.size),
)?;
println!("Verified update process started");
Ok(())
}
pub(crate) fn execute_macos_update(args: &[String]) -> ResultType<()> {
match parse_macos_update_args(args)? {
MacosUpdateArguments::CurrentApp => update_current_app(),
MacosUpdateArguments::LegacyDmg(dmg_path) => update_legacy_dmg(dmg_path),
MacosUpdateArguments::VerifiedDmg {
dmg_path,
metadata_path,
signature_path,
} => update_verified_dmg(dmg_path, metadata_path, signature_path),
}
}
#[cfg(test)]
mod tests {
use super::*;
fn args(values: &[&str]) -> Vec<String> {
values.iter().map(|value| (*value).to_owned()).collect()
}
#[test]
fn parses_current_legacy_and_verified_macos_updates() {
assert_eq!(
MacosUpdateArguments::CurrentApp,
parse_macos_update_args(&args(&["--update"])).unwrap()
);
assert_eq!(
MacosUpdateArguments::LegacyDmg("update.dmg"),
parse_macos_update_args(&args(&["--update", "update.dmg"])).unwrap()
);
assert_eq!(
MacosUpdateArguments::VerifiedDmg {
dmg_path: "update.dmg",
metadata_path: "rustdesk-update.json",
signature_path: "rustdesk-update.json.sig",
},
parse_macos_update_args(&args(&[
"--update",
"update.dmg",
"--metadata",
"rustdesk-update.json",
"--signature",
"rustdesk-update.json.sig",
]))
.unwrap()
);
}
#[test]
fn resolves_public_and_custom_update_package_identity() {
assert_eq!(
"rustdesk",
expected_update_package_id(false, Some("com.carriez.rustdesk".to_owned())).unwrap()
);
assert_eq!(
"com.example.rustdesk-custom",
expected_update_package_id(true, Some("com.example.rustdesk-custom".to_owned()))
.unwrap()
);
assert_eq!(
"com.example.same-name-custom",
expected_update_package_id(false, Some("com.example.same-name-custom".to_owned()))
.unwrap()
);
assert_eq!(
"com.carriez.rustdesk",
expected_update_package_id(true, Some("com.carriez.rustdesk".to_owned())).unwrap()
);
assert!(expected_update_package_id(false, None).is_err());
assert!(expected_update_package_id(true, None).is_err());
assert!(expected_update_package_id(true, Some(String::new())).is_err());
}
}
+5 -36
View File
@@ -251,19 +251,6 @@ mod gnome_monitor_layout_tests {
Some(GnomeMonitorLayoutMode::Logical)
);
}
#[test]
fn maps_physical_layout() {
assert_eq!(
gnome_monitor_layout_mode_from_value(2),
Some(GnomeMonitorLayoutMode::Physical)
);
}
#[test]
fn rejects_unknown_layout() {
assert_eq!(gnome_monitor_layout_mode_from_value(4), None);
}
}
#[inline]
@@ -1331,6 +1318,11 @@ fn _get_display_manager() -> String {
/// Returns the cached active username when available.
/// Callers that require a fresh seat0 lookup should call `get_values_of_seat0` directly.
pub fn get_active_username() -> String {
// Flatpak runs only inside the logged-in user's session, and Flathub builds
// cannot reach the host's loginctl.
if is_flatpak() {
return crate::username();
}
if let Some((_, username)) = get_active_user_id_name_from_cache() {
return username;
}
@@ -2462,29 +2454,6 @@ mod desktop {
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_desktop_env() {
let mut d = Desktop::default();
d.refresh();
if d.username == "root" {
assert_eq!(d.home, "/root");
} else {
if !d.username.is_empty() {
let home = super::super::get_env_var("HOME");
if !home.is_empty() {
assert_eq!(d.home, home);
} else {
//
}
}
}
}
}
}
/// A session-bus idle-inhibit interface, tried in order; the first that answers wins.
+315 -216
View File
@@ -2,7 +2,14 @@
// https://github.com/servo/core-foundation-rs
// https://github.com/rust-windowing/winit
use super::{CursorData, ResultType};
mod update_temp;
mod verified_dmg;
#[cfg(test)]
#[path = "macos/verified_dmg_tests.rs"]
mod verified_dmg_tests;
use super::{validate_install_app_name, CursorData, ResultType};
use cocoa::{
appkit::{NSApp, NSApplication, NSApplicationActivationPolicy::*},
base::{id, nil, BOOL, NO, YES},
@@ -28,12 +35,17 @@ use objc::rc::autoreleasepool;
use objc::{class, msg_send, sel, sel_impl};
use scrap::{libc::c_void, quartz::ffi::*};
use std::{
collections::HashMap,
os::unix::process::CommandExt,
path::{Path, PathBuf},
process::{Command, Stdio},
sync::Mutex,
};
pub use update_temp::try_remove_temp_update_dir;
use update_temp::{copy_dmg_to_update_temp_file, get_update_temp_dir_string};
use verified_dmg::{
attach_dmg, copy_and_verify_dmg_file, extract_dmg_inner, verified_dmg_path, verify_stored_dmg,
VerifiedDmg,
};
// macOS boolean_t is defined as `int` in <mach/boolean.h>
type BooleanT = hbb_common::libc::c_int;
@@ -41,17 +53,42 @@ type BooleanT = hbb_common::libc::c_int;
static PRIVILEGES_SCRIPTS_DIR: Dir =
include_dir!("$CARGO_MANIFEST_DIR/src/platform/privileges_scripts");
static mut LATEST_SEED: i32 = 0;
const UPDATE_CLEANUP_FAILED_AFTER_COMMIT: &str = "UPDATE_CLEANUP_FAILED_AFTER_COMMIT";
// `kill -9` may not work without administrator privileges.
// App-only update transaction used when launchd jobs are absent or intentionally stopped.
// Keep its verification, staging, bundle rollback, and cleanup aligned with update.scpt.
const PRIVILEGED_UPDATE_BODY: &str = r#"
on run {app_name, cur_pid, source_path, user_name, restore_owner, expected_sha256, expected_bundle_id}
set app_bundle to "/Applications/" & app_name & ".app"
set app_bundle_q to quoted form of app_bundle
set installed_info_q to quoted form of (app_bundle & "/Contents/Info.plist")
set source_path_q to quoted form of source_path
set user_name_q to quoted form of user_name
set expected_sha256_q to quoted form of expected_sha256
set expected_bundle_id_q to quoted form of expected_bundle_id
#[inline]
fn get_update_temp_dir() -> PathBuf {
let euid = unsafe { hbb_common::libc::geteuid() };
Path::new("/tmp").join(format!(".rustdeskupdate-{}", euid))
}
set check_source to "if [ -n " & expected_sha256_q & " ]; then test -f " & source_path_q & "; else test -d " & source_path_q & "; fi;"
set kill_others to "pids=$(pgrep -x '" & app_name & "' | grep -vx " & cur_pid & " || true); if [ -n \"$pids\" ]; then echo \"$pids\" | xargs kill -9 || true; fi;"
-- Rehash the root-owned copy in a clean environment before staging bytes.
set prepare_verified to "verified_dir=$(/usr/bin/mktemp -d /tmp/.rustdeskupdate-verified.XXXXXX); /bin/chmod 0700 \"$verified_dir\"; verified_app=\"$verified_dir/" & app_name & ".app\"; dmg_attached=0; if [ -n " & expected_sha256_q & " ]; then verified_dmg=\"$verified_dir/update.dmg\"; /bin/cp " & source_path_q & " \"$verified_dmg\"; /usr/sbin/chown root:wheel \"$verified_dmg\"; /bin/chmod 0400 \"$verified_dmg\"; actual_sha256=$(/usr/bin/env -i /usr/bin/shasum -a 256 \"$verified_dmg\"); actual_sha256=${actual_sha256%% *}; if [ \"$actual_sha256\" != " & expected_sha256_q & " ]; then echo 'Update DMG SHA256 mismatch' >&2; exit 1; fi; dmg_mount=\"$verified_dir/mount\"; /bin/mkdir \"$dmg_mount\"; dmg_attached=1; /usr/bin/hdiutil attach -readonly -nobrowse -mountpoint \"$dmg_mount\" \"$verified_dmg\" >/dev/null; /usr/bin/ditto \"$dmg_mount/" & app_name & ".app\" \"$verified_app\"; /usr/bin/hdiutil detach \"$dmg_mount\" -force >/dev/null; dmg_attached=0; /bin/rm -f \"$verified_dmg\"; else /usr/bin/ditto " & source_path_q & " \"$verified_app\"; fi; /usr/sbin/chown -R root:wheel \"$verified_app\"; /bin/chmod -R go-w \"$verified_app\";"
set validate_verified_app to "candidate_bundle_id=$(/usr/libexec/PlistBuddy -c 'Print :CFBundleIdentifier' \"$verified_app/Contents/Info.plist\"); if [ -z " & expected_bundle_id_q & " ] || [ \"$candidate_bundle_id\" != " & expected_bundle_id_q & " ]; then echo 'Update app bundle identifier mismatch' >&2; exit 1; fi; if [ -e " & app_bundle_q & " ]; then installed_bundle_id=$(/usr/libexec/PlistBuddy -c 'Print :CFBundleIdentifier' " & installed_info_q & "); if [ \"$installed_bundle_id\" != " & expected_bundle_id_q & " ]; then echo 'Installed app bundle identifier mismatch' >&2; exit 1; fi; fi;"
set prepare_swap_paths to "temp_bundle=" & app_bundle_q & ".new.$$; old_bundle=" & app_bundle_q & ".old.$$;"
set cleanup_swap_paths to "rm -rf \"$temp_bundle\" \"$old_bundle\";"
set stage_bundle to "ditto \"$verified_app\" \"$temp_bundle\";"
set protect_staged_bundle to "chown -R root:wheel \"$temp_bundle\"; chmod -R go-w \"$temp_bundle\"; (xattr -r -d com.apple.quarantine \"$temp_bundle\" || true);"
set move_current_bundle to "if [ -e " & app_bundle_q & " ]; then mv " & app_bundle_q & " \"$old_bundle\"; bundle_backed_up=1; fi;"
set install_staged_bundle to "mv \"$temp_bundle\" " & app_bundle_q & "; bundle_swapped=1;"
set restore_installed_owner to "if [ " & quoted form of restore_owner & " = '1' ]; then chown -R " & user_name_q & ":staff " & app_bundle_q & "; fi;"
set rollback_bundle to "if [ \"${bundle_backed_up:-0}\" -eq 1 ]; then if [ ! -e \"$old_bundle\" ]; then rollback_status=1; elif ! rm -rf " & app_bundle_q & "; then rollback_status=1; elif ! mv \"$old_bundle\" " & app_bundle_q & "; then rollback_status=1; fi; elif [ \"${bundle_swapped:-0}\" -eq 1 ]; then rm -rf " & app_bundle_q & " || rollback_status=1; fi;"
set cleanup_verified to "if [ \"${dmg_attached:-0}\" -eq 1 ]; then /usr/bin/hdiutil detach \"$dmg_mount\" -force >/dev/null 2>&1 || cleanup_status=1; fi; if [ -n \"${temp_bundle:-}\" ]; then rm -rf \"$temp_bundle\" || cleanup_status=1; fi; if [ -n \"${verified_dir:-}\" ]; then rm -rf \"$verified_dir\" || cleanup_status=1; fi;"
set rollback_update to "status=$?; trap - EXIT; set +e; cleanup_status=0; if [ \"${transaction_started:-0}\" -eq 1 ] && [ \"${transaction_committed:-0}\" -ne 1 ]; then rollback_status=0;" & rollback_bundle & "if [ \"$rollback_status\" -ne 0 ]; then status=1; fi; fi; if [ \"${rollback_status:-0}\" -eq 0 ]; then " & cleanup_verified & "fi; if [ \"$cleanup_status\" -ne 0 ] && [ \"${transaction_committed:-0}\" -ne 1 ]; then status=1; elif [ \"$cleanup_status\" -ne 0 ]; then echo 'UPDATE_CLEANUP_FAILED_AFTER_COMMIT'; fi; exit \"$status\";"
set commit_update to "transaction_committed=1; if ! rm -rf \"$old_bundle\"; then echo 'UPDATE_CLEANUP_FAILED_AFTER_COMMIT'; fi;"
set copy_files to prepare_swap_paths & cleanup_swap_paths & stage_bundle & protect_staged_bundle & "transaction_started=1;" & move_current_bundle & install_staged_bundle & restore_installed_owner & commit_update
set sh to "set -e; transaction_started=0; transaction_committed=0; bundle_backed_up=0; bundle_swapped=0; trap " & quoted form of rollback_update & " EXIT;" & check_source & prepare_verified & validate_verified_app & kill_others & copy_files
#[inline]
fn get_update_temp_dir_string() -> String {
get_update_temp_dir().to_string_lossy().into_owned()
}
do shell script sh with prompt app_name & " wants to update itself" with administrator privileges
end run
"#;
/// Global mutex to serialize CoreGraphics cursor operations.
/// This prevents race conditions between cursor visibility (hide depth tracking)
@@ -250,56 +287,79 @@ pub fn is_installed_daemon(prompt: bool) -> bool {
false
}
fn update_daemon_agent(agent_plist_file: String, update_source_dir: String, sync: bool) {
enum UpdateSource {
AppDir(String),
VerifiedDmg {
path: String,
expected_sha256: String,
},
}
fn log_update_cleanup_warning(output: &std::process::Output) {
if String::from_utf8_lossy(&output.stdout).contains(UPDATE_CLEANUP_FAILED_AFTER_COMMIT) {
log::warn!("Update committed, but temporary update cleanup failed");
}
}
impl UpdateSource {
fn into_script_args(self) -> (String, String) {
match self {
Self::AppDir(path) => (path, String::new()),
Self::VerifiedDmg {
path,
expected_sha256,
} => (path, expected_sha256),
}
}
}
fn update_daemon_agent(agent_plist_file: String, update_source: UpdateSource) -> ResultType<()> {
let update_script_file = "update.scpt";
let Some(update_script) = PRIVILEGES_SCRIPTS_DIR.get_file(update_script_file) else {
return;
bail!("Failed to find {}", update_script_file);
};
let Some(update_script_body) = update_script.contents_utf8().map(correct_app_name) else {
return;
bail!("Failed to read {}", update_script_file);
};
let Some(daemon_plist) = PRIVILEGES_SCRIPTS_DIR.get_file("daemon.plist") else {
return;
};
let Some(daemon_plist_body) = daemon_plist.contents_utf8().map(correct_app_name) else {
return;
};
let Some(agent_plist) = PRIVILEGES_SCRIPTS_DIR.get_file("agent.plist") else {
return;
};
let Some(agent_plist_body) = agent_plist.contents_utf8().map(correct_app_name) else {
return;
};
let func = move || {
let current_pid = std::process::id().to_string();
let (update_source_path, expected_sha256) = update_source.into_script_args();
let func = move || -> ResultType<()> {
let mut binding = std::process::Command::new("osascript");
let cmd = binding
.arg("-e")
.arg(update_script_body)
.arg(daemon_plist_body)
.arg(agent_plist_body)
.arg(&get_active_username())
.arg(std::process::id().to_string())
.arg(update_source_dir);
match cmd.status() {
.arg(&current_pid)
.arg(update_source_path)
.arg(expected_sha256);
match cmd.output() {
Err(e) => {
log::error!("run osascript failed: {}", e);
bail!("run osascript failed: {}", e);
}
Ok(status) if !status.success() => {
log::warn!("run osascript failed with status: {}", status);
Ok(output) if !output.status.success() => {
let stderr = String::from_utf8_lossy(&output.stderr);
log::warn!(
"run osascript failed with status: {}, stderr: {}",
output.status,
stderr.trim()
);
bail!(
"run osascript failed with status: {}, stderr: {}",
output.status,
stderr.trim()
);
}
_ => {
Ok(output) => {
log_update_cleanup_warning(&output);
let installed = std::path::Path::new(&agent_plist_file).exists();
log::info!("Agent file {} installed: {}", &agent_plist_file, installed);
}
}
Ok(())
};
if sync {
func();
} else {
std::thread::spawn(func);
}
func()
}
fn correct_app_name(s: &str) -> String {
@@ -767,6 +827,10 @@ pub fn is_locked() -> bool {
}
}
pub fn is_logon_screen() -> bool {
is_prelogin() || is_locked()
}
pub fn is_root() -> bool {
crate::username() == "root"
}
@@ -882,23 +946,7 @@ pub fn quit_gui() {
};
}
#[inline]
pub fn try_remove_temp_update_dir(dir: Option<&str>) {
let target_path_buf = dir.map(PathBuf::from).unwrap_or_else(get_update_temp_dir);
let target_path = target_path_buf.as_path();
if target_path.exists() {
std::fs::remove_dir_all(target_path).ok();
}
}
pub fn update_me() -> ResultType<()> {
let is_installed_daemon = is_installed_daemon(false);
let option_stop_service = "stop-service";
let is_service_stopped = hbb_common::config::option2bool(
option_stop_service,
&crate::ui_interface::get_option(option_stop_service),
);
let cmd = std::env::current_exe()?;
// RustDesk.app/Contents/MacOS/RustDesk
let app_dir = cmd
@@ -909,53 +957,78 @@ pub fn update_me() -> ResultType<()> {
let Some(app_dir) = app_dir else {
bail!("Unknown app directory of current exe file: {:?}", cmd);
};
update_me_from_app_dir(app_dir)
}
fn update_me_from_app_dir(app_dir: String) -> ResultType<()> {
update_me_from_source(UpdateSource::AppDir(app_dir))
}
fn update_me_from_source(update_source: UpdateSource) -> ResultType<()> {
let app_name = crate::get_app_name();
validate_install_app_name(&app_name)?;
let is_installed_daemon = is_installed_daemon(false);
let option_stop_service = "stop-service";
let is_service_stopped = hbb_common::config::option2bool(
option_stop_service,
&crate::ui_interface::get_option(option_stop_service),
);
// Include launchd jobs in the transaction only while the installed service is enabled.
if is_installed_daemon && !is_service_stopped {
let agent = format!("{}_server.plist", crate::get_full_name());
let agent_plist_file = format!("/Library/LaunchAgents/{}", agent);
update_daemon_agent(agent_plist_file, app_dir, true);
update_daemon_agent(agent_plist_file, update_source)?;
} else {
// `kill -9` may not work without "administrator privileges"
let update_body = r#"
on run {app_name, cur_pid, app_dir, user_name}
set app_bundle to "/Applications/" & app_name & ".app"
set app_bundle_q to quoted form of app_bundle
set app_dir_q to quoted form of app_dir
set user_name_q to quoted form of user_name
set check_source to "test -d " & app_dir_q & " || exit 1;"
set kill_others to "pids=$(pgrep -x '" & app_name & "' | grep -vx " & cur_pid & " || true); if [ -n \"$pids\" ]; then echo \"$pids\" | xargs kill -9 || true; fi;"
set copy_files to "rm -rf " & app_bundle_q & " && ditto " & app_dir_q & " " & app_bundle_q & " && chown -R " & user_name_q & ":staff " & app_bundle_q & " && (xattr -r -d com.apple.quarantine " & app_bundle_q & " || true);"
set sh to "set -e;" & check_source & kill_others & copy_files
do shell script sh with prompt app_name & " wants to update itself" with administrator privileges
end run
"#;
let active_user = get_active_username();
let status = Command::new("osascript")
let (update_source_path, expected_sha256) = update_source.into_script_args();
let expected_bundle_id = get_bundle_id()
.filter(|value| !value.is_empty())
.ok_or_else(|| anyhow!("client bundle identifier is missing"))?;
let output = Command::new("osascript")
.arg("-e")
.arg(update_body)
.arg(PRIVILEGED_UPDATE_BODY)
.arg(app_name.to_string())
.arg(std::process::id().to_string())
.arg(app_dir)
.arg(active_user)
.status();
match status {
Ok(status) if !status.success() => {
log::error!("osascript execution failed with status: {}", status);
.arg(update_source_path)
.arg(get_active_username())
.arg(if is_installed_daemon { "0" } else { "1" })
.arg(expected_sha256)
.arg(expected_bundle_id)
.output();
match output {
Ok(output) if !output.status.success() => {
let stderr = String::from_utf8_lossy(&output.stderr);
log::error!(
"osascript execution failed with status: {}, stderr: {}",
output.status,
stderr.trim()
);
bail!(
"osascript execution failed with status: {}, stderr: {}",
output.status,
stderr.trim()
);
}
Err(e) => {
log::error!("run osascript failed: {}", e);
bail!("run osascript failed: {}", e);
}
_ => {}
Ok(output) => log_update_cleanup_warning(&output),
}
}
std::process::Command::new("open")
match Command::new("open")
.arg("-n")
.arg(&format!("/Applications/{}.app", app_name))
.spawn()
.ok();
.status()
{
Ok(status) if !status.success() => {
log::warn!("Failed to relaunch updated app: {}", status);
}
Err(err) => {
log::warn!("Failed to relaunch updated app: {}", err);
}
_ => {}
}
// leave open a little time
std::thread::sleep(std::time::Duration::from_millis(300));
Ok(())
@@ -964,16 +1037,38 @@ end run
pub fn update_from_dmg(dmg_path: &str) -> ResultType<()> {
let update_temp_dir = get_update_temp_dir_string();
println!("Starting update from DMG: {}", dmg_path);
extract_dmg(dmg_path, &update_temp_dir)?;
println!("DMG extracted");
update_extracted(&update_temp_dir)?;
let update_result = (|| {
let copied_dmg = copy_dmg_to_update_temp_file(dmg_path)?;
let guard = attach_dmg(&copied_dmg.to_string_lossy())?;
update_me_from_app_dir(format!(
"{}/{}.app",
guard.mount_point(),
crate::get_app_name()
))
})();
try_remove_temp_update_dir(Some(&update_temp_dir));
update_result?;
println!("Update process started");
Ok(())
}
pub fn update_to(_file: &str) -> ResultType<()> {
let update_temp_dir = get_update_temp_dir_string();
update_extracted(&update_temp_dir)?;
pub fn update_to_verified_dmg(
file: &str,
expected_sha256: &str,
expected_size: Option<u64>,
) -> ResultType<()> {
let verified_dmg = copy_and_verify_dmg_file(file, expected_sha256, expected_size)?;
update_from_verified_dmg(&verified_dmg)?;
// Remove the private DMG copy before this process exits.
drop(verified_dmg);
quit_gui();
Ok(())
}
fn update_from_verified_dmg(verified_dmg: &VerifiedDmg) -> ResultType<()> {
println!("Starting update from verified DMG");
update_me_from_source(verified_dmg_update_source(verified_dmg)?)?;
println!("Update process started");
Ok(())
}
@@ -1021,6 +1116,7 @@ fn validate_update_tree(path: &Path, framework_root: Option<&Path>) -> ResultTyp
.file_name()
.and_then(|name| name.to_str())
.is_some_and(|name| name.ends_with(".framework"))
&& std::fs::symlink_metadata(&child)?.file_type().is_dir()
{
Some(child.as_path())
} else {
@@ -1029,7 +1125,40 @@ fn validate_update_tree(path: &Path, framework_root: Option<&Path>) -> ResultTyp
validate_update_tree(&child, child_framework_root)?;
}
} else if !metadata.file_type().is_file() {
bail!("[root-update] unsupported file in update bundle: {}", path.display());
bail!(
"[root-update] unsupported file in update bundle: {}",
path.display()
);
}
Ok(())
}
fn read_bundle_plist_value(app: &Path, key: &str) -> ResultType<String> {
let info_plist = app.join("Contents/Info.plist");
let plist_command = format!("Print :{key}");
let output = Command::new("/usr/libexec/PlistBuddy")
.args(["-c", plist_command.as_str()])
.arg(info_plist)
.output()?;
if !output.status.success() {
bail!(
"[root-update] failed to read bundle plist value {key}: {}",
String::from_utf8_lossy(&output.stderr).trim()
);
}
let value = String::from_utf8(output.stdout)
.map_err(|err| anyhow!("[root-update] bundle plist value {key} is not UTF-8: {err}"))?;
if value.trim().is_empty() {
bail!("[root-update] bundle plist value {key} is empty");
}
Ok(value.trim().to_owned())
}
fn verify_update_app_identity(installed: &Path, candidate: &Path) -> ResultType<()> {
let installed_id = read_bundle_plist_value(installed, "CFBundleIdentifier")?;
let candidate_id = read_bundle_plist_value(candidate, "CFBundleIdentifier")?;
if installed_id != candidate_id {
bail!("[root-update] candidate bundle identifier mismatch");
}
Ok(())
}
@@ -1038,13 +1167,7 @@ fn validate_update_tree(path: &Path, framework_root: Option<&Path>) -> ResultTyp
/// Must be called from a process running as root (e.g. the service binary).
pub fn update_from_dmg_as_root(dmg_path: &str, expected_version: &str) -> ResultType<()> {
let app_name = crate::get_app_name();
if app_name.is_empty()
|| !app_name
.bytes()
.all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b'-'))
{
bail!("[root-update] unsafe application name");
}
validate_install_app_name(&app_name)?;
let app_bundle = format!("/Applications/{}.app", app_name);
let tmp_dir_output = std::process::Command::new("/usr/bin/mktemp")
.args(&["-d", "/tmp/.rustdeskupdate-root-XXXXXX"])
@@ -1073,6 +1196,7 @@ pub fn update_from_dmg_as_root(dmg_path: &str, expected_version: &str) -> Result
let src_app = format!("{}/{}.app", tmp_dir, app_name);
log::info!("[root-update] DMG extracted to {}", tmp_dir);
validate_update_tree(Path::new(&src_app), None)?;
verify_update_app_identity(Path::new(&app_bundle), Path::new(&src_app))?;
// Bind the downloaded asset to the version returned by the update
// service before changing plists or executing anything from the staged
@@ -1731,127 +1855,23 @@ rm -rf {tmp_dir}
Ok(())
}
pub fn extract_update_dmg(file: &str) {
let update_temp_dir = get_update_temp_dir_string();
let mut evt: HashMap<&str, String> =
HashMap::from([("name", "extract-update-dmg".to_string())]);
match extract_dmg(file, &update_temp_dir) {
Ok(_) => {
log::info!("Extracted dmg file to {}", update_temp_dir);
}
Err(e) => {
evt.insert("err", e.to_string());
log::error!("Failed to extract dmg file {}: {}", file, e);
}
}
let evt = serde_json::ser::to_string(&evt).unwrap_or("".to_owned());
#[cfg(feature = "flutter")]
crate::flutter::push_global_event(crate::flutter::APP_TYPE_MAIN, evt);
}
fn extract_dmg(dmg_path: &str, target_dir: &str) -> ResultType<()> {
let target_path = Path::new(target_dir);
if target_path.exists() {
std::fs::remove_dir_all(target_path)?;
}
std::fs::create_dir_all(target_path)?;
extract_dmg_inner(dmg_path, target_dir)
}
fn extract_dmg_into_existing_dir(dmg_path: &str, target_dir: &str) -> ResultType<()> {
let target_path = Path::new(target_dir);
if !target_path.exists() {
bail!("[root-update] Temp directory does not exist: {:?}", target_path);
bail!(
"[root-update] Temp directory does not exist: {:?}",
target_path
);
}
extract_dmg_inner(dmg_path, target_dir)
}
fn extract_dmg_inner(dmg_path: &str, target_dir: &str) -> ResultType<()> {
let mount_output = Command::new("/usr/bin/mktemp")
.args(["-d", "/tmp/.rustdeskmount-XXXXXX"])
.output()?;
if !mount_output.status.success() {
bail!("Failed to create a private DMG mount directory");
}
let mount_point = String::from_utf8(mount_output.stdout)
.map_err(|e| anyhow!("Invalid DMG mount directory: {}", e))?
.trim()
.to_owned();
if mount_point.is_empty() {
bail!("Failed to create a private DMG mount directory");
}
let status = Command::new("/usr/bin/hdiutil")
.args(["attach", "-nobrowse", "-mountpoint"])
.arg(&mount_point)
.arg(dmg_path)
.status()?;
if !status.success() {
let _ = std::fs::remove_dir(&mount_point);
bail!("Failed to attach DMG image at {}: {:?}", dmg_path, status);
}
struct DmgGuard(String);
impl Drop for DmgGuard {
fn drop(&mut self) {
let _ = Command::new("/usr/bin/hdiutil")
.args(["detach", self.0.as_str(), "-force"])
.status();
let _ = std::fs::remove_dir(&self.0);
}
}
let _guard = DmgGuard(mount_point.clone());
let app_name = format!("{}.app", crate::get_app_name());
let src_path = format!("{}/{}", mount_point, app_name);
let dest_path = format!("{}/{}", target_dir, app_name);
let copy_status = Command::new("/usr/bin/ditto")
.args(&[&src_path, &dest_path])
.status()?;
if !copy_status.success() {
bail!(
"Failed to copy application from {} to {}: {:?}",
src_path,
dest_path,
copy_status
);
}
if !Path::new(&dest_path).exists() {
bail!(
"Copy operation failed - destination not found at {}",
dest_path
);
}
Ok(())
}
fn update_extracted(target_dir: &str) -> ResultType<()> {
let app_name = crate::get_app_name();
let exe_path = format!(
"{}/{}.app/Contents/MacOS/{}",
target_dir, app_name, app_name
);
let _child = unsafe {
if let Err(e) = Command::new(&exe_path)
.arg("--update")
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
.pre_exec(|| {
hbb_common::libc::setsid();
Ok(())
})
.spawn()
{
try_remove_temp_update_dir(Some(target_dir));
bail!(e);
}
};
Ok(())
fn verified_dmg_update_source(verified_dmg: &VerifiedDmg) -> ResultType<UpdateSource> {
verify_stored_dmg(verified_dmg)?;
Ok(UpdateSource::VerifiedDmg {
path: verified_dmg_path(verified_dmg)?.to_owned(),
expected_sha256: verified_dmg.expected_sha256.clone(),
})
}
pub fn get_double_click_time() -> u32 {
@@ -2050,7 +2070,7 @@ impl WakeLock {
}
}
fn get_bundle_id() -> Option<String> {
pub(crate) fn get_bundle_id() -> Option<String> {
unsafe {
let bundle: id = msg_send![class!(NSBundle), mainBundle];
if bundle.is_null() {
@@ -2073,3 +2093,82 @@ fn get_bundle_id() -> Option<String> {
Some(bundle_id_str)
}
}
#[cfg(test)]
mod update_tests {
use super::*;
#[test]
fn update_tree_rejects_framework_root_symlink() {
let test_dir = std::env::temp_dir().join(format!(
"rustdesk-update-tree-framework-link-test-{}-{}",
std::process::id(),
hbb_common::rand::random::<u64>()
));
let app_dir = test_dir.join("RustDesk.app");
let frameworks_dir = app_dir.join("Contents/Frameworks");
let external_framework = test_dir.join("External.framework");
std::fs::create_dir_all(&frameworks_dir).unwrap();
std::fs::create_dir_all(&external_framework).unwrap();
std::os::unix::fs::symlink(
&external_framework,
frameworks_dir.join("External.framework"),
)
.unwrap();
let result = validate_update_tree(&app_dir, None);
std::fs::remove_dir_all(test_dir).unwrap();
assert!(result.is_err());
}
#[test]
fn update_tree_allows_internal_framework_symlink() {
let test_dir = std::env::temp_dir().join(format!(
"rustdesk-update-tree-internal-link-test-{}-{}",
std::process::id(),
hbb_common::rand::random::<u64>()
));
let framework_dir = test_dir.join("RustDesk.app/Contents/Frameworks/Test.framework");
let versions_dir = framework_dir.join("Versions");
std::fs::create_dir_all(versions_dir.join("A")).unwrap();
std::os::unix::fs::symlink("A", versions_dir.join("Current")).unwrap();
let result = validate_update_tree(&test_dir.join("RustDesk.app"), None);
std::fs::remove_dir_all(test_dir).unwrap();
assert!(result.is_ok());
}
#[test]
fn update_app_identity_requires_matching_bundles() {
let test_dir = std::env::temp_dir().join(format!(
"rustdesk-update-identity-test-{}-{}",
std::process::id(),
hbb_common::rand::random::<u64>()
));
let installed = test_dir.join("installed.app");
let candidate = test_dir.join("candidate.app");
let info = |bundle_id| {
format!("<plist version=\"1.0\"><dict><key>CFBundleIdentifier</key><string>{bundle_id}</string></dict></plist>")
};
for app in [&installed, &candidate] {
std::fs::create_dir_all(app.join("Contents")).unwrap();
}
std::fs::write(
installed.join("Contents/Info.plist"),
info("com.carriez.rustdesk"),
)
.unwrap();
for (bundle_id, accepted) in [("com.carriez.rustdesk", true), ("example.other", false)] {
std::fs::write(candidate.join("Contents/Info.plist"), info(bundle_id)).unwrap();
assert_eq!(
verify_update_app_identity(&installed, &candidate).is_ok(),
accepted
);
}
std::fs::remove_dir_all(test_dir).unwrap();
}
}

Some files were not shown because too many files have changed in this diff Show More