Compare commits

...
Author SHA1 Message Date
fufesou e1ca09766c refact(update): change the pub key for metadata (#16758)
Signed-off-by: fufesou <linlong1266@gmail.com>
2026-10-30 02:29:40 +08:00
rustdesk 0aaf3a02bf finish translations 2026-10-29 23:15:12 +08:00
fufesou eba0a6e552 fix(web): preserve peer card clicks with semantics enabled (#16709)
* fix(web): preserve peer card clicks with semantics enabled

Give the More menu semantic tap and double-click actions, and expose multi-selection through separate checkboxes. Exclude redundant outer desktop web tap semantics while preserving card-body double-click connections.

Cover mouse single/double clicks and semantic activation under the parent card gesture detector.

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

* fix(web): reuse accessible More control in portrait cards

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

* fix(web): keep peer More taps immediate and cancellable

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

* fix(web): keep keyboard wrapper out of accessibility focus

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

---------

Signed-off-by: fufesou <linlong1266@gmail.com>
2026-10-29 19:30:58 +08:00
Raz AsheriandRustDesk 3cb027a372 Update Hebrew translation (#16690)
* Add missing Hebrew translations

Signed-off-by: Raz Asheri <37867699+RazAsheri@users.noreply.github.com>

* Fix a few Hebrew translations

Signed-off-by: Raz Asheri <37867699+RazAsheri@users.noreply.github.com>

* Fix wording for fullscreen toggle

Signed-off-by: Raz Asheri <37867699+RazAsheri@users.noreply.github.com>

---------

Signed-off-by: Raz Asheri <37867699+RazAsheri@users.noreply.github.com>
Co-authored-by: RustDesk <71636191+rustdesk@users.noreply.github.com>
2026-10-29 11:02:20 +08:00
Maison da Silva 5217f32a12 Improve Portuguese translations in pt_BR.rs (#16752)
Updated Portuguese translations for API server tips and RustDesk storage.
2026-10-29 10:11:04 +08:00
VenusGirl❤ c8cb6fb509 Update ko.rs (#16749)
* Update ko.rs

Update Korean

* Fix Korean translation

Update Korean
2026-10-29 10:00:55 +08:00
Ricardo Simõesandgreptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com> df9df7e914 Update pt_PT.rs (#16748)
* Update pt_PT.rs

* Update src/lang/pt_PT.rs

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

* Update src/lang/pt_PT.rs

fixed "dispostivos" typo

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

---------

Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>
2026-10-29 10:00:45 +08:00
bovirus acda5a73e2 Update Italian language (#16747) 2026-10-29 10:00:36 +08:00
Alex Rijckaert 04360797ad Update Dutch translations in nl.rs (#16739) 2026-10-28 16:28:02 +08:00
fufesou bb8083cb2f udpate hbb_common (#16737)
Signed-off-by: fufesou <linlong1266@gmail.com>
2026-10-28 16:27:44 +08:00
fufesou 350966b331 Add trusted-device V2 with legacy upgrade compatibility (#16548)
* fix: secure trusted devices with host-issued V2 tokens

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

* fix: preserve trusted-device management and ordinary authentication

Restore selected-device deletion using nonsecret record identifiers and acknowledged V2 revocation errors.

Preserve password and TOTP authentication when the V2 authority or cached controller credentials are unavailable. Disable V2 for the affected attempt while retaining authentication, configuration, and revocation rejection.

Validation: 20 selected Rust tests, Flutter-feature Rust compilation, focused Dart analysis, formatting, and whitespace checks passed.
Signed-off-by: fufesou <linlong1266@gmail.com>

* fix: simplify trusted-device caching and stabilize tests

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

* fix: persist trusted-device grants in host configuration

Store host grants in RustDesk2.toml and preserve revocation across configuration writes and service transitions. Use local authority on macOS when no background service is installed.

Preserve both configuration imports by checking Config2 eligibility before revocation writes. Cover the password and 2FA import regression alongside the existing trusted-device tests.

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

* fix: store trusted-device credentials in peer configuration

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

* fix: minimize trusted-device persistence changes

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

* refactor: minimize trusted-device integration changes

Keep ordinary policy writes on the generic configuration path and document authentication updates. Restore the macOS installer to master, rename the V2 version gate, and relocate the existing client regression test.

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

* fix: harden trusted-device revocation and persistence

Recover corrupt grant data without skipping authentication-write validation, and avoid revoking trust when IPC synchronizes an unchanged salt. Make desktop management IPC async and keep runtime creation at the Flutter worker boundary.

Update hbb_common to preserve V2 credentials when configuration reads fail, and extend existing regressions for clear, salt synchronization, and persistence failures.

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

* fix: preserve trusted-device validation and no-op settings

Validate trust before connection side effects and retain tickets for the final check when the authority is unavailable after TOTP. Disable enrollment on that path.

Skip revocation for password operations that the existing setter treats as no-ops, extend the existing IPC regression, and clean up client state on initialization or credential errors.

Validation: 36 targeted native tests, Flutter-feature Rust check, formatting, and git diff --check passed.
Signed-off-by: fufesou <linlong1266@gmail.com>

* feat: add trusted-device expiry and per-device renewal

Keep legacy records for password-and-TOTP migration, encrypt host grant storage, and add configurable trust periods that revoke grants when changed. Allow renewing individual unexpired devices from the manager, hide renewal for never-expiring grants, and preserve the mobile table height constraints.

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

* fix(macos): report trusted-device cleanup failure before uninstall

Revoke local trusted-device grants before dispatching the uninstall closure so cleanup failures return false without starting the uninstall script. Keep the existing synchronous and asynchronous script execution paths.

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

* fix: preserve trusted-device settings and revoke macOS service grants

Default unsupported expiration values on read while keeping explicit edits strict. Allow password/TOTP when stored grants are out of sync, after validating the authentication scope.

Revoke root-owned grants during macOS service removal. Bump hbb_common for malformed-file recovery and legacy-record preservation, and retain the reviewed regression coverage.

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

* fix: avoid duplicate trusted-device revocation during config sync

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

* fix: preserve trusted-device revocation during config mismatches

Allow grant clearing when authentication snapshots are unavailable and validate existing snapshots before applying authentication updates. Restore optimistic caching for non-auth bulk options and restrict the trusted-device IPC helper to desktop targets.

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

* feat: preserve trusted devices when trust duration changes

Adjust existing grant deadlines for duration changes and startup policy overrides, support 90 days, and use an adaptive inline duration selector without the obsolete revocation warning.

Consolidate management IPC and trim redundant tests while retaining authentication and revocation coverage.

Validation: four existing focused Rust tests and the startup override reproduction passed; Windows default/service and Flutter-feature cargo checks passed.
Signed-off-by: fufesou <linlong1266@gmail.com>

* fix: finish trusted-device notice cleanup and duration sync

Remove the recurring legacy notice, unused response metadata and translation key. Allow duration-only saves with a readable inactive grant scope while preserving storage and authentication errors.

Update hbb_common to 040bf3f662ae7422f2f9570701cc8451f7bb1d59, which removes the unused legacy detector.

Validation: four existing focused Rust tests passed; Windows default/service and Flutter-feature cargo checks passed. No new tests were added.
Signed-off-by: fufesou <linlong1266@gmail.com>

* fix: refine trusted-device duration layout

Indent the duration row beneath the trusted-device option, add vertical spacing, and compact the desktop selector. Mobile sizing and other dropdowns remain unchanged.

Validation: targeted Dart analysis passed with existing informational diagnostics. Actual window rendering was not exercised.
Signed-off-by: fufesou <linlong1266@gmail.com>

* refact: adjust indentation

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

* fix: preserve trusted devices across version upgrades

Honor existing legacy trust without creating new legacy registrations. Import live records into encrypted grants, apply the current expiration policy, and migrate consenting controllers to V2 tokens while retaining grouped revocation.

Advertise V2 capability explicitly and hide enrollment for mixed-version sessions. Update existing coverage and use the paired hbb_common migration API.

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

* fix: translations

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

* Align the compact trusted-device duration selector on mobile

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

* Default trusted devices to 90 days and drop unreleased V2 migrations

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

* Avoid masking macOS daemon stop failures during uninstall

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

* restore uninstall.scpt, do not clear trusted devices on uninstall

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

* Preserve trusted devices when uninstalling services

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

* Preserve trusted devices when importing host configuration

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

* Recover from unreadable trusted-device grants

Log and persistently revoke invalid or undecryptable V2 payloads so password and TOTP can enroll a new device. Keep configuration read and write errors explicit and extend existing tests to cover recovery and rejection of old tokens.

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

* Preserve trusted devices across service transitions

Run grant operations in the accepting server and synchronize current grants and revocations through the existing service configuration channel. Keep ordinary settings saves from restoring stale credentials and retain root peer verification.

Recognize explicit configuration errors as live service responses during IPC probing, so duplicate startup does not remove the active socket.

Validated with five trusted-device tests, seven Linux IPC filesystem tests, an isolated IPC regression probe, and Windows Flutter and Linux compilation checks. Installed-service transitions and macOS runtime behavior remain untested.

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

* Keep trusted-device grants under the service authority

Preserve root-owned grants when copying service configuration and route installed-host trust operations through the root service. Keep local authentication edits available when the Linux service is explicitly stopped, then synchronize pending revocation before using service grants.

Serialize pending revocation synchronization and cover service copies, stale user snapshots, and stopped-service authentication updates with the existing focused tests.

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

* Replace same-ID grants when enrolling trusted devices

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

* Allow macOS security edits after service removal

Reuse pending trusted-device revocation for offline password and 2FA changes. Honor pending revocation during installation copies and before root-authority requests and configuration synchronization.

Validation: five focused macOS tests, macOS and Windows cargo checks, and targeted formatting checks.
Signed-off-by: fufesou <linlong1266@gmail.com>

* Allow macOS security edits before daemon reinstallation

Detect an absent daemon using retained service ownership instead of the incoming-connections stop flag. General Start resumes connections without reinstalling the daemon, so local authentication edits must continue using pending revocation until installation.

Adjust the existing recovery test to check that toggling incoming connections does not make a standalone profile service-owned.

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

* Allow re-enrollment after invalid controller credentials

Ignore malformed or undecryptable stored token payloads with a throttled warning while preserving file access errors and host identity checks. Fresh authorized enrollment can replace the unusable credential.

Restore logged, non-propagating IPC errors for non-authentication option changes and extend the existing credential recovery test.

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

* Update hbb_common to serialize peer deletion

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

* fix(macos): preserve trusted devices across service removal

Hand off the current root grant store to the removing user and restore that user's latest grants on reinstallation. Keep other retained profiles from becoming authoritative, and preserve user settings when the service has no optional configuration.

Validate the macOS build, five trusted-device tests, isolated headless transfer cases, and AppleScript syntax. Real privileged service transitions remain untested.

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

* refactor(trusted-devices): use local grants and existing config sync

Keep grant decisions in the accepting host process and transfer grants and removals through the existing background configuration sync. Remove root-only grant RPC, ownership handoff, pending revocation, and dedicated copy commands; restore the master service lifecycle on Linux and macOS.

Preserve V2 credentials, authentication revocation, and ordinary-save protections. Accept the existing asynchronous sync and multiple-user limitations.

Validated Windows and macOS Flutter checks, the Linux library/tests/service check, four macOS trusted-device tests, and AppleScript syntax. Real service transitions remain untested.

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

* fix(trusted-devices): preserve migrated tokens at capacity

Raise the shared V2 token limit to 128 and order newly migrated tokens by issuance time without extending their legacy expiration. Extend the existing migration regression coverage to verify token reuse and expiry preservation at capacity.

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

* fix(windows): preserve trust across service stop and start

Export current on-disk grants and explicitly synchronize them into the GUI configuration at startup and before stopping a running service. Abort the stop if synchronization fails so the next service import cannot use a stale local copy.

Extend the existing synchronization regression coverage to check revoked, retained and newly enrolled devices and the actual import-source file. Remove unrelated import logging changes.

Validation: trusted-device tests passed on Windows and macOS (4 each); changed-line formatting and git diff --check passed. Real Windows GUI/UAC service transitions remain untested.
Signed-off-by: fufesou <linlong1266@gmail.com>

* refactor(trusted-devices): simplify local authorization

Replace local authorization envelopes with typed operations while retaining locked authentication checks and persistence. Remove redundant configuration and Dart wrappers without changing credential formats or management requests.

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

* fix(windows): allow service removal when host is unavailable

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

* fix(windows): preserve trust revocations before full uninstall

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

* fix(windows): sync trust changes to the retained user config

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

* fix(windows): sync trust after security setting changes

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

---------

Signed-off-by: fufesou <linlong1266@gmail.com>
2026-10-28 10:27:44 +08:00
fufesou d0a1af8c51 feat(android): transfer files directly through SAF folders (#16644)
* feat(android): transfer files directly through SAF folders

Let Android users choose folders in the existing file-transfer browser
and stream documents through provider descriptors without workspace copies.
Keep local browsing separate from host sharing, and restrict new peer
document requests to the current shared folder.

Preserve traversal checks, overwrite protection, cancellation, empty files,
and provider errors through completion. Run Android provider IO on blocking
workers and reuse the native directory-listing bridge. Retain the existing
workspace import/export flow and non-Android file-transfer behavior.

Validation: all 11 base tests pass, including shared-root confinement,
document IO, cancellation, provider failures, and resume cleanup. macOS Rust
checking and isolated Kotlin compilation pass. Flutter analysis reports no
errors, with existing warnings. Full Android builds and device tests remain
unperformed.

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

* fix(android): group storage locations in the file menu

Replace the standalone folder icon and ambiguous RustDesk entry with adjacent RustDesk storage and Other folders actions in the existing menu. Reuse the current storage handlers and register the two localized labels.

Validation: targeted Flutter analysis reports no errors and six existing diagnostics. Translation consistency and git diff checks pass. Android device interaction was not tested.
Signed-off-by: fufesou <linlong1266@gmail.com>

* fix(file-transfer): keep batch deletion running across refreshes

Snapshot selected files before awaiting deletion confirmations so directory refreshes cannot invalidate the batch iterator. Defer refreshes for awaited file deletions until the batch finishes, while retaining refreshes for late completions.

Retain one regression test for completing all three confirmations after selection reconciliation. All nine file-model tests pass; focused analysis reports no errors and one existing informational diagnostic. Android visual behavior was not tested on a device.

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

* refactor(android): narrow SAF scope and move folder selection to settings

Move shared-folder selection from Share screen permissions to Settings > Transfer file, preserving live connection locking and managed settings visibility.

Trim optional SAF resume and thread-identity assertions while retaining transfer and authorization regressions. Split the independent batch-deletion fix into commit 06313a9aa on fix/file-transfer-batch-deletion.

Validation: 19 base unit tests and 11 Flutter file-model/download-path tests passed. Focused Flutter analysis reports only existing informational diagnostics.
Signed-off-by: fufesou <linlong1266@gmail.com>

* fix(android): clean up failed SAF transfers and reset navigation

Cancel pending SAF writes when the client receives a transfer error or the connection manager handles WriteError. Log cleanup failures without replacing the original transfer error or discarding data retained after publication fails.

Clear local navigation history after successfully selecting a storage root, so Back does not attempt to return to the previous workspace.

Validation: 19 base unit tests and 11 Flutter file-model/download-path tests passed. macOS cargo check passed; focused Flutter analysis reports only existing diagnostics. Android build and device validation were not performed.
Signed-off-by: fufesou <linlong1266@gmail.com>

* fix(android): guard SAF overwrites and clean up interrupted receives

Require matching per-file confirmation before SAF downloads replace an
existing destination, including transfers from peers without overwrite
detection. Enforce the policy before creating a temporary document.

Cancel unfinished SAF receives when the Android client session exits.
Delete newly created temporary documents if opening them fails, preserving
the original error and reporting cleanup failures. Keep publication-failure
recovery and non-Android transfer paths unchanged.

Validation: 19 base unit tests and macOS cargo check --lib --features flutter
passed. The document storage Kotlin modules compiled against Android SDK 35.
Full Android builds and device validation were not performed.

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

* fix(android): clean up SAF uploads on host disconnect

Cancel pending SAF receives after the Android connection manager removes
a closed connection, including receiver EOF. Log cleanup failures without
preventing cleanup of other jobs. Preserve publication-failure recovery.

Validation: 19 base unit tests and macOS cargo check --lib --features flutter
passed. Android host disconnect behavior still requires device validation.

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

* fix(android): restore storage root after failed folder selection

Restore the previous local home when opening a selected SAF folder or the
RustDesk workspace fails or throws. Preserve navigation history on failure
and retain existing error reporting.

Keep the home assignment before the asynchronous read so superseded read
completions cannot overwrite a newer storage selection.

Validation: 11 existing file-model/download-path Flutter tests passed.
Focused analysis reports no errors and six pre-existing diagnostics.
Changed-method formatting and whitespace checks passed. Android device
validation of overlapping storage switches remains pending.

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

* fix(android): enforce shared storage and protect SAF overwrites

Authorize peer filesystem requests against the currently shared root so
remembered workspace paths cannot bypass a selected SAF folder. Offer
text-only RustDesk storage and Other folders choices under Change path,
including an explicit switch back to the application workspace.

Reject SAF host overwrites from peers without overwrite-detection support,
while preserving modern senders' existing confirmation flow. Cover legacy
creation, rejected replacement, and modern replacement in the Rust fixture.

Validation: 19 base tests, 11 Flutter tests, focused Dart analysis, Android
Rust/APK builds, and whitespace checks passed. Device checks verified
storage switching, cancellation, old-path rejection, and Android-initiated
three-file overwrite/Skip batches against macOS. The separate legacy-host
overwrite guard was verified by Rust tests and was not in the device APK.

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

* fix(android): reject partial SAF listings and restore folder roots

Reject provider cursors reporting loading or errors before using their
cached rows as a complete directory listing. Propagate the error through
the existing folder-transfer initialization and browsing paths.

After restoring a local SAF directory, derive its navigation root from
the displayed document path so Home and breadcrumbs use the selected
tree independently of the host's shared-folder setting.

Validation: Kotlin storage modules compile; an Android runtime cursor
check covers complete, loading, and error results. Eleven existing
Flutter tests and three temporary reconnect checks pass. Focused Dart
analysis reports only the existing setter lint; diff checks pass.
Cloud-provider transfers and navigation in a rebuilt APK were not tested.

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

* fix(android): discard pending SAF writes after block errors

Cancel pending document receives when a data-block write fails, removing
temporary data before cancellation or disconnect. Preserve the original
write error and throttle cleanup-error logging. Keep publication-failure
retention unchanged.

Extend the existing provider tests with a real descriptor I/O failure
and a cleanup-failure case.

Validation:
- Regression failed before the fix.
- cargo test --offline -p base --lib: 19 passed within 60 seconds.
- Rustfmt and git diff --check passed.
- No Android build or on-device storage-exhaustion test was performed.

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

* feat(android): guide first-time file transfer folder setup

Prompt users to choose the folder remote devices may access when first
opening File transfer, manually starting the service, or enabling file
transfer. Offer RustDesk storage and the existing SAF picker, and explain
where to change the shared folder later in Settings.

Remember successful setup or explicit Skip, while allowing canceled setup
to be retried. Honor existing settings and permission restrictions. Use
the native translation placeholder convention for the settings path.

Validation:
- Two onboarding widget tests pass, including the breadcrumb regression.
- Flutter analysis and Dart formatting checks pass for the new files.
- Staged diff whitespace checks pass.

Android system-picker and service integration were not tested on a device.

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

* fix(android): group file transfer folder choices

Replace plain list rows with an indented group of full-width outlined
buttons. Tighten spacing while preserving the standard Android touch
target and allowing labels to wrap.

Validation: both existing onboarding widget tests, scoped Flutter
analysis, Dart formatting, and diff whitespace checks pass.
Android visual validation was not performed on a device.

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

* fix(android): clean up SAF finalization and guard source resume

Discard temporary documents when flushing, syncing, or closing a receive
fails before publication. Attempt discard even when cancellation cannot
close the descriptor, and retain both errors when cleanup also fails.
Keep recovery documents after publication failures.

Reject nonzero source offsets when the SAF modification time is unknown,
so same-size changes cannot combine with a previous partial download.
Report that the transfer must restart; fresh sends remain supported.

Validation: all 19 base library tests pass, including finalization and
cancellation cleanup, combined provider errors, unknown-timestamp resume,
fresh sends, and failed-publication retention. Tests used a 60-second
limit. Rustfmt and diff whitespace checks pass. Android device/provider
failure testing and a rebuilt APK were not performed.

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

* fix(file-transfer): restore reliable batch deletion

Snapshot selected entries before awaiting deletion confirmations so
refreshes cannot invalidate the batch iterator. Defer refreshes for
awaited file deletions until the batch finishes, while preserving
refreshes for late completions.

Completing the batch lets the existing mobile delete handler clear the
selection and exit selection mode. Restore the previously split fix on
the SAF branch with one five-file regression test.

Validation: all nine file-model tests pass. The regression reproduced
Concurrent modification during iteration before the fix. Focused Flutter
analysis has no errors or warnings, with one existing setter-style
informational diagnostic. Formatting and diff checks pass. Android device
deletion and selection-mode rendering were not tested.

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

* feat(android): store logs in app media storage

Write release logs to Android/media/com.carriez.flutter_hbb/RustDesk,
using Android's package-specific media directory and the existing logger.
Include this directory in Export Logs alongside legacy logs and recordings,
and restrict the added export access to the canonical log directory.

Suggest Android/media for the first SAF folder selection on API 26+.

Validation: Android ARM64 release cargo check and Kotlin compilation passed.
Focused Flutter analysis found no new diagnostics; git diff --check passed.
Full APK linking is blocked by missing libvpx.a in the build environment.
On-device log writing, export, and initial picker location remain unverified.

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

* feat(android): keep logs in a user-authorized shared folder

Write release logs through SAF in Android/media/RustDesk instead of the
package-owned media directory. Require the independent log-folder grant
before starting the service, and include these logs in Export Logs while
retaining export of existing logs and recordings.

Keep daily/size rotation and bounded retention within the log backend.
Report provider failures explicitly and route JNI lifetime diagnostics
directly to logcat to avoid re-entering JNI during native thread teardown.
Allow a deleted log folder to be selected and created again.

Validation: Android ARM64 release cargo check, Kotlin compilation, and two
existing Flutter setup tests passed. A temporary real-JVM reproduction
using the production writer passed native thread exit at debug and trace
levels after reproducing the earlier crash. Full Rust/APK builds passed
before the final JNI and missing-folder fixes; those fixes passed Rust and
Kotlin checks. The final APK and folder authorization, rotation, export,
and uninstall retention have not been tested on an Android device.

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

* fix(android): validate SAF parent names and restore workspace navigation

Reject a newly created SAF parent when the provider changes its display
name, before receiving data into that directory. This prevents sanitized
names from splitting one source folder into multiple destination folders
while reporting success. An adjusted empty directory can remain.

Restore the local navigation root for saved paths inside the actual app
workspace before checking the saved directory. Keep that choice separate
from the host's shared SAF root and leave peer access checks unchanged.

Validation: 12 tracked Flutter file-model/download-path tests passed.
Three temporary controller tests passed for workspace root/subfolder
restoration, local SAF restoration, and workspace-prefix rejection; the
workspace case failed before the fix. Kotlin compilation, focused Dart
analysis, and diff checks passed, with one existing analysis info.
No rebuilt APK or device provider-name/navigation test was performed.

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

* fix(android): authorize log storage before outgoing connections

Require the existing log-folder authorization before opening an Android remote-control, file-transfer, camera, or terminal session. Canceling or failing authorization leaves the connection unstarted; check that the page is still mounted before navigation.

Validation: two temporary authorization regression tests and two existing setup widget tests passed. Focused analysis reported only unchanged diagnostics, and git diff --check passed. No rebuilt APK or device validation.
Signed-off-by: fufesou <linlong1266@gmail.com>

* fix(android): clear terminal admin intent on canceled log setup

Clear IS_TERMINAL_ADMIN when the Android log-folder authorization guard aborts a terminal launch. A canceled administrator-terminal attempt can no longer pass its one-shot intent to a later ordinary terminal connection. Successful authorization keeps the existing session initialization behavior.

Validation: the temporary regression test reproduced the stale flag before the fix; all three temporary widget tests pass after it, including successful administrator intent preservation. Focused Dart analysis reports only unchanged diagnostics, and git diff --check passes. Android authentication dialogs were not tested on a device.
Signed-off-by: fufesou <linlong1266@gmail.com>

* fix(android): clarify log setup and default folder selection

Show a concise log-directory prompt before opening the picker, and skip
the prompt when existing log access is ready. Start first file-transfer
folder selection in Documents, excluding the separate log grant from
the check for previous transfer-folder selections.

Validation:
- Focused Flutter analysis, locale consistency, and diff checks passed.
- Six temporary authorization/dialog tests passed during implementation.
- The review rerun of existing setup tests timed out while loading (60s).
- Kotlin/APK builds and Android device validation were not performed.

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

* fix(android): check log readiness before boot hosting

Run the log-directory preflight off the receiver thread before creating
the hosting service. Abort startup with an explicit error when logging
is unavailable, and finish the asynchronous broadcast on every path.

Validation: four temporary JVM startup tests, Android Kotlin compilation,
and git diff --check passed. Release APK reboot and provider validation
were not performed.

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

* fix(android): simplify log setup and preserve reconnect paths

Use a single Choose folder action with clearer log-storage guidance and
request Android/media/RustDesk as the initial picker location. Reuse the
existing directory ID and add the button label to the locale maps.

Restore the workspace root before opening each Android local reconnect
candidate, preserving the currently browsed directory ahead of saved
locations while retaining the existing fallback order.

Validation: 14 existing Flutter tests and two temporary Android-controller
regression tests passed. Scoped Dart analysis and git diff --check passed,
with only the existing setter-style informational diagnostic.

Android compilation and device validation were not performed for these
changes. The initial picker location remains a system hint and can be
ignored if the directory does not exist.

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

* fix(android): prioritize log setup and separate picker defaults

Authorize log storage before showing first-use file-transfer setup.
Always request Documents for transfer folder selection, independently
of previously granted folders.

Request Android/media/RustDesk for logs when accessible, otherwise use
Android/media so the existing authorization flow can create the child.
Remove the obsolete log-grant classifier.

Validation: two temporary setup-order tests, three temporary JVM picker
tests, and two existing Flutter setup tests passed. Scoped Dart analysis,
Android Kotlin compilation, and git diff --check passed.

Actual picker behavior was not tested on a device. Initial locations
remain system hints supported from API 26.

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

* refact: translation

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

* fix(android): preserve default logs and simplify folder setup

Limit folder setup prompts to hosting startup and remember successful
manual shared-folder selections. Outgoing sessions and file-transfer
permission toggles no longer request folder configuration.

Keep release logs in Config::log_path() until public storage is authorized,
and use that original directory when public writes fail. A failed default
writer must not prevent logging to a working public folder. Report the
fallback explicitly and retain both errors when neither destination works.

Use Android/media/<installed AppName>/Logs for public logs. Resolve and
create only authorized descendants, verify provider-created directory
names, and update picker and startup messages. Keep hosting authorization
and the Documents transfer-picker default unchanged.

Validation:
- Two focused Rust regressions using the real writer and flexi_logger with
  a supplied Android bridge: default/public routing, fallback and failures.
- Five temporary Flutter checks and two existing folder-setup widget tests.
- Two temporary Kotlin checks for standard/custom app names, authorized
  directory creation and independent picker defaults.
- Android :app:compileDebugKotlin -Ptarget-platform=android-arm64 passed.
- Scoped Dart analysis matches HEAD's existing diagnostics; rustfmt and
  git diff --check passed.

The temporary checks supply Android APIs; release APK logging, permission
revocation, fallback and reboot behavior have not been verified on device.

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

* fix(android): simplify log folder selection errors

Show "Please select Android/media." when a log-folder selection is invalid.
Display the platform error message instead of the full PlatformException,
while keeping the complete error in debug output. Directory validation and
permission handling are unchanged.

Validation: scoped Dart analysis, both existing folder-setup widget tests,
and git diff --check passed. No APK rebuild or device verification.

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

* fix(android): simplify the log folder picker location

Always request Android/media as the initial log authorization location
and show the same short path in the picker title. Keep creating and
using <AppName>/Logs internally.

Remove the obsolete filesystem probe for an existing Logs directory.
Preserve accepted grants, logging policy and the Documents default for
the separate file-transfer picker.

Validation: two temporary picker checks with supplied Android APIs,
Android :app:compileDebugKotlin -Ptarget-platform=android-arm64, and
git diff --check passed. Actual system-picker positioning has not
been verified on a device.

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

* fix(android): keep hosting independent of log access

Restore boot and native service startup without requiring public log
folder authorization. The existing logger uses the original directory
when public logging is unconfigured or fails. Removing the early service
stops also avoids the foreground-service startup failure path.

Keep log and shared-folder setup on deliberate hosting startup, but allow
hosting confirmation after cancellation or setup failure. Request log
setup once, before shared-folder setup.

Route Android SAF AllFiles requests through the existing CM enumeration
and result channel so the connection loop can continue processing messages.
Preserve path validation, file-count limits and ordinary filesystem paths.

Validation:
- Android Kotlin compilation and ARM64 release cargo check passed.
- Focused Dart analysis and both existing folder-setup tests passed.
- Temporary source-based startup, cancellation, log fallback and SAF
  dispatch checks passed using supplied platform/provider APIs.
- git diff --check passed; no new rustfmt differences from HEAD.

The CM unit test timed out during dependency compilation at the 60-second
limit and did not execute. No APK/device reboot, revocation or slow-provider
validation was performed.

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

* fix(android): reject SAF root deletion before traversal

Reject the selected SAF tree root before recursive enumeration or deletion,
so a failed root-deletion request cannot remove its empty subdirectories.
Keep ordinary subdirectory deletion on the existing path and strengthen
one existing root-rejection assertion.

Validation:
- cargo test -p base --lib fs::android (2 passed)
- Three temporary source-backed filesystem checks passed for root
  preservation, ordinary subtree deletion and nonempty subtree rejection
- rustfmt --check and git diff --check passed
- No Android device validation performed

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

* fix(android): reject stale SAF source metadata

Check provider size and modification time after opening a SAF source against
its listed metadata. Reject changed sources before advertising a stale digest,
preventing resumed downloads from combining old and new file contents.

Treat negative provider timestamps as unknown instead of rejecting the entire
listing. Offset resume remains disallowed for sources with unknown timestamps.

Validation:
- cargo test -p base --lib: 20 tests passed.
- Standalone Rust transfer checks: reject a changed source, restart with the
  current contents, and preserve resume for an unchanged source.
- rustfmt --check and git diff --check passed.
- No Android APK build or device validation performed.

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

* fix(android): move shared folder selection under permissions

Place Change Path below Transfer file on the Share screen page, retaining
custom-client visibility and active-session permission restrictions.
Remove the Settings entry and shorten the first-use sharing prompt.

Keep the existing translation key and update its English and Chinese
display text. Adjust the existing setup widget test to match.

Validation:
- Existing setup widget tests: 2 passed.
- Focused Dart analysis: no errors or warnings; existing page deprecation
  notices remain.
- Locale consistency, Dart formatting, and git diff --check passed.
- No Android APK build or device layout validation.

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

* fix(android): tidy shared folder option layout

Render Change Path as a compact, full-width sub-option below Transfer
file, with one directional inset and a trailing chevron. This removes
the extra mobile text-button padding while preserving permission locking.

Validation:
- Focused Dart analysis: no errors or warnings; three existing deprecation
  notices remain.
- Dart formatting and git diff --check passed.
- No new tests for this presentation-only change; updated device layout
  has not been validated on Android.

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

* fix(android): authorize legacy public logs without a folder picker

On Android versions below 8, request the system storage permission and
write configured public logs to Android/media/<AppName>/Logs. Limit
WRITE_EXTERNAL_STORAGE to API 25; keep the existing SAF flow on newer
Android versions. General storage permission alone does not redirect logs
before explicit setup.

Keep the original log destination before setup and on public-write errors.
Permission denial completes promptly and does not prevent hosting. Retain
log rotation and export, and reopen the writer during readiness checks if
the fixed directory has been moved or removed.

Validation:
- Nox Android 7.1.2: permission grant/denial, original-log fallback, fixed
  public destination, persisted setup, and actual Rust logs after restart.
- Isolated device regression: exported public logs match the source bytes;
  moved-directory readiness fails before the fix and passes afterward.
- Full ARMv7 Flutter debug APK with the release Rust library built and
  installed successfully.
- Two Flutter setup tests, scoped Dart analysis, whitespace checks, and
  a fresh CodeRabbit review passed.

Android 5/6 and Android 8+ device testing was not performed.

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

* fix(android): restore SAF log setup and surface folder errors

Use SAF for public logs on all supported Android versions. Remove the
legacy direct writer and WRITE_EXTERNAL_STORAGE permission, preserving
the original logging fallback and normal picker cancellation.

Keep log-folder errors visible until acknowledged, then exit the current
manual hosting setup instead of advancing to file-transfer setup. Translate
the error text, add Chinese translations, and register the missing key in
the language catalogs. Boot startup and existing services are unchanged.

Validation:
- Two existing Flutter file-transfer setup tests passed.
- Focused Flutter analysis and git diff --check passed.
- Built the release ARMv7 Rust library and Flutter debug APK.
- On Nox Android 7.1.2, invalid-root selection showed the persistent Chinese
  error; acknowledgement exited setup without starting hosting.
- Ordinary picker cancellation continued the existing optional setup flow.
- APK inspection found no READ_EXTERNAL_STORAGE, WRITE_EXTERNAL_STORAGE,
  or MANAGE_EXTERNAL_STORAGE permissions.

Device validation used the debug APK on Nox; other Android versions and
a full release APK were not device-tested for this change.

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

* fix(android): bind SAF digests to opened files and simplify setup

Read size and modification time from the opened document descriptor so
replacing a source path cannot pair old data with a newer resume digest.
Refresh stale metadata for regular files and keep streams non-resumable
while preserving fresh sequential sends.

Shorten the shared-folder setup prompt and direct log-folder selection to
Android/media. Remove obsolete app-media log-directory queries and export
allowances; retain SAF logs, original app-data logs, and recordings export.

Validation:
- Focused base Android tests: 3 passed; the replacement regression failed
  before the descriptor fix and passed afterward.
- Existing Flutter setup and file-model tests: 11 passed.
- ARMv7 release Rust library and Flutter debug APK builds passed.
- Scoped CodeRabbit re-review: 0 findings; git diff --check passed.

No Android device validation was performed for this revision.

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

* fix(android): avoid blocking log callers during folder setup

Bypass per-record JSON/JNI dispatch after discovering that public logging
is unconfigured. Publish routing changes from the application-owned Kotlin
logger so a late fallback response cannot undo successful folder setup.

Return contended public writes to the existing original-directory writer
instead of waiting for provider operations. Keep the JNI callback available
in debug Android builds without changing their logcat logger, and remove
the unused English tree-picker title.

Validation:
- ARMv7 release Rust build and full Flutter debug APK packaging passed.
- Android 7 provider contention check reproduced the wait before the fix
  and passed with the rebuilt Kotlin code and native library.
- Temporary native routing test passed: one initial backend lookup,
  subsequent bypass, re-enabling, and all records in the fallback file.
- Formatting and diff checks passed; scoped CodeRabbit findings were
  reviewed against the Rust fallback and picker callers.

The full APK was built but not installed for this change. Device checks
used the existing isolated probe; full release-app end-to-end validation
remains pending. No permanent test infrastructure was added.

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

* fix(android): allow slower SAF empty-directory scans

Use the existing 30-second remote-directory timeout only for SAF scans. Ordinary filesystem scans keep the two-second timeout, and the request lifecycle is unchanged.

Add a regression for a SAF response arriving after three seconds. The file-model suite passes all 10 tests. Targeted analysis reports only the existing setter lint; Android device validation was not performed. Scans exceeding 30 seconds can still time out.

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

* fix(android): isolate SAF empty-directory scan lifecycles

Only remove an empty-directory request when its timeout still owns the registered completer. Cancel pending SAF scans when the remote session changes so the same directory can be retried immediately. Ordinary filesystem reconnect behavior and timeout durations remain unchanged.

Share regression coverage for completed and reconnected scans, keeping each retry pending across the previous timer deadline without adding production state.

Validation: all 11 file-model tests pass. Test-file analysis and whitespace checks pass; targeted production analysis reports only the existing setter lint. No Android build or device validation was performed for this change.
Signed-off-by: fufesou <linlong1266@gmail.com>

* refactor(android): deduplicate SAF helpers and test setup

Share local storage navigation, tree-picker Intent construction, and
provider listing readiness checks. Preserve independent picker defaults,
error messages, failed-navigation rollback, and authorization lifecycles.

Reuse Rust transfer-test fixtures and remove text-only setup assertions
while retaining behavioral regression coverage. Reduce the branch diff
by 78 lines without changing transfer or logging policy.

Validation:
- Focused Rust SAF tests: 3 passed.
- Four focused Flutter suites: 20 passed; the two setup tests were rerun
  successfully after removing text-only assertions.
- Kotlin 2.1.21 / Android SDK 36 compilation passed for all six document
  integration sources in an isolated Linux directory.
- git diff --check passed. No APK build or device validation this round.

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

* chore(android): organize SAF tests and complete zh-TW label

Move the two SAF test files into libs/base/src/fs/tests and update the
module path, preserving their contents and module hierarchy. Fill the
missing Traditional Chinese translation for Choose folder.

Validation: cargo test -p base --lib fs::android passed (3 tests).
Verified both moved files are byte-identical and all six new SAF/logging
keys have nonempty Traditional Chinese translations. Diff check passed.

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

* fix(android): keep hosting available and reject stale SAF scans

Keep the log-folder error dialog, skip remaining folder setup after an
error, and continue to the existing hosting confirmation. Public-log
failures retain the existing default-directory logging fallback.

Reject remote SAF empty-directory requests if the session changes while
awaiting bridge dispatch. Reuse the existing session generation and leave
ordinary filesystem requests unchanged. Extend the existing lifecycle
test to cover reconnecting during dispatch.

Validation: 21 focused Flutter tests passed. A temporary startup-flow
check passed for setup error, success and cancellation. Analysis reports
only the existing setter-return-type info. Diff check passed; CodeRabbit
review completed with no findings. No Android device validation.

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

* fix(android): avoid logging raw folder setup errors

Log fixed status messages for Android log-folder setup failures instead
of provider-derived exception text. Preserve detailed errors in the
dialog and keep the existing folder setup and hosting flow unchanged.

Validation: focused Flutter analysis and both existing folder-setup
widget tests passed. Diff check passed. No Android device validation.

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

* fix(android): offload access checks and restore identical-file hints

Run Android peer-path authorization on blocking workers for initial
folders, file actions and rename destinations. Preserve fail-closed
access decisions and the existing non-Android path.

Set the SAF identical-file hint only for matching sizes and known,
matching modification times. Keep overwrite confirmation and reject
receive resume. Extend the existing transfer test to cover the hint.

Validation:
- cargo test -p base --lib fs::android: 3 passed.
- Android ARMv7 API 21 release cargo check with flutter,hwcodec passed
  using an isolated copy of HEAD plus these changes, verified by SHA256.
- macOS cargo check --lib --features flutter passed for the access fix.
- Temporary scheduling check failed before the fix and passed afterward.
- Scoped CodeRabbit reviews and diff checks passed.
No APK build or device testing was performed for this follow-up.

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

* fix(android): limit SAF dispatch and clarify log exports

Use blocking workers only for document-backed file operations. Keep
ordinary Android filesystem calls on their original execution path and
retain asynchronous peer-path authorization checks.

Report success and failure counts when log export succeeds only partly.
Skip the destination picker when there are no default log sources and no
public-folder permission. Preserve public-log permission errors.

Validation:
- cargo test -p base --lib fs::: 19 passed.
- Flutter file-model and Android setup suites: 14 passed.
- Android ARMv7 API 21 release cargo check with flutter,hwcodec passed
  against an isolated source copy, verified by SHA256.
- Temporary Dart feedback and Kotlin export-handler checks failed before
  the fix and passed afterward.
- Focused Dart analysis found only existing diagnostics; diff checks passed.
No APK build or device testing was performed for this follow-up.

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

* fix(android): allow longer SAF deletion scans

Use the existing 30-second deadline when recursively scanning SAF folders
before deletion. Keep the two-second timeout for ordinary filesystem
paths, with request handling and deletion behavior unchanged.

Validation:
- Existing Flutter file-model and Android setup suites: 14 passed.
- Targeted Dart analysis found no new diagnostics.
- git diff --check passed.
No Android APK build or device testing was performed for this fix.

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

* fix(android): keep public logging active after cleanup failures

Log a warning when deleting an expired log fails, and continue writing to
the newly opened public log. Keep creation, open, and write failures on
the existing fallback path. Failed deletions may leave extra old logs.

Validation:
- Four temporary Kotlin checks passed: deletion false/exception, normal
  rotation, and propagation of a genuine log-open failure.
- Actual document-storage Kotlin sources compiled against Android API 36.
- git diff --check passed. No APK build or device test performed.

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

* fix(android): keep accepted SAF download file lists immutable

Reject replacement of an accepted generic SAF download file list before
any mutation, so per-file overwrite approval cannot be redirected to a
different destination. Preserve the ordinary download and upload paths.

Extend the existing overwrite test and construct each receive fixture
with its initial file list only once.

Validation:
- The added assertion failed before the fix; all 19 filesystem tests
  passed afterward: cargo test --offline -p base --lib fs::.
- Scoped CodeRabbit review completed with no findings.
- No new rustfmt differences; git diff --check passed.
- No Android build or device test performed for this fix.

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

* fix(android): preserve secondary document-transfer exceptions

Attach cleanup and backup-restore exceptions to the original error before
wrapping it in IOException. Preserve the existing error messages, primary
cause, and transfer control flow.

Validation:
- Confirmed the diff contains only the two addSuppressed calls.
- git diff --check passed.
- No Android build or device test performed for this diagnostic change.

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

* fix(android): log authorization failures with throttling

Report document access-check errors at warning level and blocking-task
failures at error level. Throttle each site to one record per minute while
preserving existing deny decisions and failure messages.

Validation:
- Existing hbb_common log_throttle tests: 4 passed.
- Rust formatting and git diff --check passed.
- Android target build and device testing not performed.

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

---------

Signed-off-by: fufesou <linlong1266@gmail.com>
2026-10-28 10:03:43 +08:00
Maison da Silva 894f532835 Update API server connection tips in Portuguese (#16734) 2026-10-28 08:58:27 +08:00
Lukas eb23902450 fix(lang): keep the {} value and the meaning in four translations (#16701)
* fix(lang): keep the {} value and the meaning in four translations

* test(lang): check that the fixed translations keep their key's {}

translate() replaces {} with the value from the call. The test checks that no non-empty ru, sc or vi translation of a key with {} drops it; on master it fails with "Downloading {}" => "Скачивание".
2026-10-27 16:27:53 +08:00
Minh Nguyen 59f2953c94 fix(windows): name the privacy window executable explicitly (#16711)
Turning on privacy mode 1 could fail with `os error 193`, "%1 is not a valid
Win32 application", naming a broker executable that is perfectly intact.

`CreateProcessAsUserW` was given a NULL `lpApplicationName` and the unquoted
broker path as `lpCommandLine`. With no application name Windows has to work
out the image from the command line, and it does so by trying each
whitespace-delimited prefix in turn. The default install path is
`C:\Program Files\RustDesk\...`, so the first candidate is `C:\Program`. On a
machine where a file by that name happens to exist, Windows loads it, fails to
read it as a PE image, and returns ERROR_BAD_EXE_FORMAT. The path in the error
message is the command line that was intended, not the file Windows tried.

Pass the path as `lpApplicationName`, which removes the guessing entirely, and
quote the copy that goes in as `lpCommandLine` so the child still sees a
well-formed `argv[0]`. Bind that buffer mutably while here: the API declares it
as an in/out `LPWSTR` the Unicode implementation may rewrite, so handing over a
const pointer cast to mutable was the wrong interface for the call.

Both other `CreateProcess` call sites in the tree already name the executable
explicitly, one of them with a comment giving this exact reason, so this brings
the third into line rather than introducing a pattern.

Refs #16705
2026-10-26 17:23:08 +08:00
Alex Rijckaert a5e986401c Update Dutch translations (#16702) 2026-10-26 16:43:04 +08:00
Minh Nguyen 182356ee8b fix(linux): load peers when the app dir is unset (#16698)
Recent sessions and Favorites load only when `APP_DIR` is non-empty. That
precondition belongs to mobile alone: `Config::path` resolves through `APP_DIR`
on Android and iOS, so reading peers before it is set would look in the wrong
place there, but on desktop the peer path never consults it.

On Linux the Flutter side fills `APP_DIR` from
`getApplicationDocumentsDirectory()`, which shells out to `xdg-user-dir`. When
that executable is absent, as in a minimal Debian install or a container, the
call throws, the exception is only `debugPrint`ed, and `APP_DIR` stays empty.
All three loaders then skip their work, so both lists stay empty for good while
`~/.config/rustdesk/peers/*.toml` sit there unread and nothing in the log says
why. Windows and macOS carry the same trap, merely with a lookup that is far
less likely to fail.

Move the predicate into one helper that applies it only where the path actually
depends on it. Mobile keeps the existing check; everywhere else the peers load.

Refs #16622
2026-10-26 15:45:14 +08:00
github-actions[bot]andgithub-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> f96a44a019 chore: update webpki-roots to latest Mozilla root store (#16713)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-10-26 15:11:58 +08:00
VenusGirl❤ 1297da6d18 Update Korean language (#16687)
Update ko.rs
2026-10-24 17:28:24 +08:00
Lukas 8814503e06 fix(linux): pick up pulsectl's default source fix for voice calls (#16685) 2026-10-24 15:32:24 +08:00
Lukas c8a4e0680c fix(linux): capture the default output's monitor for remote audio (#16681)
* fix(linux): capture the default output's monitor for remote audio

With no audio input chosen, the _pa service recorded the first source whose name contains "monitor". Sources are listed in creation order, so on a host with more than one output, such as onboard audio plus HDMI, a USB headset or a Bluetooth speaker, that monitor can belong to an output the desktop does not play to, and the controlling side hears silence. Ask the server for the default sink and record its monitor, keeping the first monitor as the fallback.

* fix(linux): log the lookups that fall back to the first monitor

* fix(linux): fall back to the first monitor when the default sink has no monitor name

* fix(linux): throttle the default monitor lookup warnings
2026-10-24 14:56:09 +08:00
Cody SwartzandClaude Opus 5.5 ed6a1acce8 feat(address-book): add a toolbar button to open the web console (#16680)
The web console is only reachable from the "More on web console" item
in the menu beside the Tags heading, which is easy to miss and hidden
when the tags panel is turned off.

Add a button to the Address Book toolbar that opens the same URL and
reuses the same tooltip text. It shows under the same conditions as the
menu item: logged in, not in legacy address book mode, and write access
to the current book.

Signed-off-by: Cody Swartz <ctsstc@gmail.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-24 10:41:57 +08:00
21pages 4d37f00af9 fix(client): invalidate auto FPS state when updating FPS limits (#16283)
* fix(client): sync FPS control and reset limits on quality changes

  Track the last sent FPS across manual and automatic updates.
  Reset the FPS limit to 30 when leaving custom image quality,
  while preserving lower automatic limits when already capped at 30.

 fix(client): reset last sent FPS state on reconnect

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

fix(client): invalidate auto FPS state when updating FPS limits

  Clear last_auto_fps when setting custom FPS so the controller recomputes
  on its next tick. Restore the 30 FPS cap when switching to preset quality
  while preserving the saved custom FPS setting.

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

fix(client): reset auto FPS state after successful login

  Move last_auto_fps invalidation from login send paths to
  handle_peer_info, covering both normal and switch-side logins.

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

fix(client): scope auto FPS state to each connection

Keep automatic FPS state in the connection loop and invalidate it when processing manual FPS updates or successful login.

Validate queued automatic updates against the current FPS cap and record the value only after a successful send.

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

* test(client): cover FPS adjustment after manual updates

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

---------

Signed-off-by: 21pages <sunboeasy@gmail.com>
2026-10-23 19:13:39 +08:00
Lukas 21c488b6ce fix(linux): recognize a login screen whose greeter uses another nologin path (#16675)
* fix(linux): recognize a login screen whose greeter uses another nologin path

is_prelogin() reads the active user's passwd entry and treats /bin/false or /usr/sbin/nologin as a greeter account. Greeter accounts on Arch use /usr/bin/nologin (gdm, sddm and lightdm) and others /sbin/nologin, so there a login screen was not detected: the audio service kept retrying the _pa ipc every second, which #16390 stopped at a login screen, and file transfer used the greeter's name. Match any nologin path.

* fix(linux): match nologin only in the shell field of the passwd entry

Checking the whole getent line also matched a home directory such as /home/nologin-test. Read the last field of each line and require it to end in /false or /nologin. Output with several lines, as getent prints for an empty name, still counts if any entry has such a shell, as before.

* fix(linux): compare the greeter shell with the known paths only

Match the shell field against /bin/false, /usr/bin/false, /usr/sbin/nologin, /sbin/nologin and /usr/bin/nologin instead of any path that ends in /false or /nologin, so a custom shell elsewhere is not taken for a login screen.
2026-10-23 18:09:08 +08:00
Lukas 01e1323e51 fix(linux): keep listing resolutions after an interlaced xrandr mode (#16672)
* fix(linux): keep listing resolutions after an interlaced xrandr mode

resolutions() reads the mode lines below an output with (\s*\d+x\d+\s+\d+.*\n)+, which needs whitespace right after the size. A TV usually lists 1920x1080i right after 1920x1080, so the list ended there and the resolution menu offered only the current mode. Allow a suffix after the size; the per-mode pattern still skips the interlaced lines, so only the following progressive modes are added.

* test(linux): check the resolutions parsed from xrandr output

Move the parsing of resolutions() into resolutions_from_xrandr(), which takes the xrandr output, so the test asserts the returned list instead of the captured mode lines. resolutions() runs xrandr and calls it; the parsing is unchanged.

* Revert "test(linux): check the resolutions parsed from xrandr output"

This reverts commit 854beb1. AGENTS.md asks not to reshape existing code only to enable a test, so resolutions() keeps its structure and the test checks the captured mode lines, as output_name_does_not_match_inside_another_name checks get_xrandr_conn_pat.
2026-10-23 17:23:02 +08:00
Lukas 106f700be4 fix(linux): read Debian's GDM config when checking for a Wayland login screen (#16674)
is_login_wayland() looks for WaylandEnable in /etc/gdm3/custom.conf and /etc/gdm/custom.conf. Debian's gdm3 package ships /etc/gdm3/daemon.conf instead (bookworm and trixie), whose default has '#WaylandEnable=false', so on Debian the function always returned false and the 'Login screen using Wayland is not supported' card never appeared. Read daemon.conf after the two custom.conf paths.
2026-10-23 16:58:52 +08:00
Lukas f7b0af78cb fix(lang): pick Traditional Chinese for Hong Kong and Macao system locales (#16671)
* fix(lang): pick Traditional Chinese for Hong Kong and Macao system locales

With no language chosen in Settings, resolve_lang picks zh-tw only when the system locale contains tw. Hong Kong and Macao locales (zh_HK, zh-Hant-HK, zh_HK_#Hant, zh_MO) and a bare zh-Hant got Simplified Chinese, although they write Traditional Chinese. Pick zh-tw for them too, unless the locale names the Hans script.

* test(lang): cover a bare zh-Hant locale
2026-10-23 16:49:51 +08:00
Lukas 25d2742273 fix(lang): pick the Kazakh and Georgian translations from the system locale (#16670)
With no language chosen in Settings, resolve_lang takes the language from the system locale prefix. Kazakh locales are kk_* and Georgian locales are ka_*, but their translation tables are keyed kz and ge, so both fell through to English. Map kk to kz and ka to ge for the locale-derived language. A language saved in Settings is unchanged.
2026-10-23 15:56:15 +08:00
Hüseyin Durna eb6c32bd57 l10n(tr): fill missing shortcut and API server translations (#16669)
Signed-off-by: Hüseyin Durna <76519526+husodrn46@users.noreply.github.com>
2026-10-23 15:48:35 +08:00
Rafał Sikora 398364fa18 fix(ios): keep background music playing during remote sessions (#16660)
Configure the iOS audio session with the ambient category so remote
playback mixes with other apps while respecting Silent mode and lock.
Log configuration errors and leave audio activation to playback.

Signed-off-by: Rafal <mrsikorarafal@gmail.com>
2026-10-23 11:23:08 +08:00
rustdeskandClaude Opus 5.5 828d1101af chore(deps): pin hwcodec to rustdesk-org/hwcodec#47
Move the locked hwcodec revision from febec27 to ec38eba, the merge of
rustdesk-org/hwcodec#47: GPU query failure handling, Windows resource
handling and recoverable fragmented MP4 recording. hwcodec's own
dependencies are unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 18:48:28 +08:00
RustDeskandClaude Opus 5.5 3ec041644d fix(linux): gtk sudo shows no false "Sorry, try again." and retries with sudo-rs (#16652)
* fix(linux): no false "Sorry, try again." in gtk sudo after a PAM info line

The gtk sudo dialog takes the password before sudo starts and drops it
when sudo prints a non-prompt line first, such as pam_fprintd's "Place
your finger on the fingerprint reader". The real password prompt then
came up labelled as a retry, "Sorry, try again.", although no password
had been sent, so users took it as a rejected password.

Treat the next prompt as a first prompt when the typed password is
dropped. The dialog comes back prefilled and without the error.

Keeping the password and sending it to the next prompt instead is not
safe: when sudo authenticates without a prompt (fingerprint, NOPASSWD),
use_pty, the default since sudo 1.9.14, holds the tty in raw mode while
the command runs, so any output line ending in ':' would receive it.

Fixes #16647

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(linux): let gtk sudo retry after sudo-rs rejects a password

sudo-rs reports a rejected password with "sudo: Authentication failed,
try again." and then asks again. The line starts with "sudo:", so
ui_parent treated it as fatal: it showed it in an error dialog and
exited instead of offering a retry, as it does after classic sudo's
"Sorry, try again." (the second log in #16647).

Exempt exactly that line from the fatal check. It then goes through
the ordinary non-prompt branch, so the held-password drop rule still
applies. sudo-rs's final "maximum N incorrect authentication attempts"
stays fatal, and so does every other sudo:/su: line.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 18:27:35 +08:00
RustDeskandClaude Opus 5.5 d97351ad73 Custom websocket port (#16658)
* feat: let custom client settings set websocket-port

A domain endpoint becomes ws(s)://<domain>/ws/id with no port, so a
WebSocket reverse proxy that cannot listen on 443 (or 80) is
unreachable. hbb_common adds websocket-port for that; list it in
KEYS_SETTINGS so default-settings and override-settings carry it.

The hbb_common bump also brings in 20d5019 (quiets smithay client
toolkit logs, rustdesk/hbb_common#620).

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

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Update hbb_common for the websocket-port warning throttle

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Update hbb_common: match websocket-port only against configured servers

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Pin hbb_common to the merged websocket-port change

rustdesk/hbb_common#626 is merged as edefa08. The range from master's
pin 5d52530 also includes 20d5019 (quiets smithay client toolkit logs,
rustdesk/hbb_common#620).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 17:58:00 +08:00
fufesou 2b6fedfc8e fix(windows): protect installer handoff and use native service control (#16562)
* fix(windows): use native APIs for manual service control

rustdesk/rustdesk#16557

Replace elevated service-control batch scripts with SCM operations
and native tray shortcuts. Preserve SYSTEM configuration import
and propagate helper failures.

* fix(windows): preserve service state during manual control

Keep existing service registration and synchronize failed operations with SCM state. Run the installed legacy importer directly as SYSTEM, bound its exit waits, and keep auxiliary cleanup errors separate from service lifecycle results.

* fix(windows): preserve legacy service import without debug privilege

* fix(windows): replace installer certutil and findstr

Use native SHA-256 verification and shortcut decoding, and execute the protected batch script in a single cmd process. Preserve protected staging, verification receipts and failure exit codes.

Restore the master service-control flow and remove the separate SCM and Task Scheduler implementation to keep the antivirus fix focused and preserve legacy configuration import.

Validation: Windows Rust library build, nine focused tests, and isolated single-cmd success, failure, tamper rejection and cleanup checks passed. Bitdefender validation remains pending.

* fix(windows): preserve installer helper path compatibility

* fix(windows): preserve caret-only installer helper paths

* fix(windows): protect installer data and use native service control

Stage installer scripts, shortcuts and verified updates with restricted ACLs
before elevation. Remove the elevated portable-verifier launch while keeping
certutil and findstr out of the shared installer handoff.

Use the installed Flutter runner for native normal-service create/start and
stop/delete operations. Preserve existing registrations on repeated setup,
legacy configuration import, and compatibility with older installed runners.
Report installer failures and document the security and compatibility reasons.

Validation: Windows Rust test build and Release runner build passed; six
isolated service checks and runner exit-code checks passed. Focused Rust
installer/update tests passed 8/9; the directory-cleanup ACL test also fails in
the earlier binary. Final service lifecycle and Bitdefender testing is pending.

* fix(windows): clean staged installer files on UAC cancellation

Retain DELETE handles until the elevated cmd connects to a local pipe, then
release the handles before allowing the BAT to run. This preserves protected
staging while allowing cancellation cleanup and cmd file access.

Handle interrupted handoffs, supply the byte-count pointer required on
Windows 7, and explain early service dispatch in the C++ runner. Keep the
staging tests inline with their implementation.

Validation: Windows Rust test build, focused installer-file and handoff
tests, rustfmt, and staged diff checks passed. The pre-existing directory
ACL test failure is unchanged. Actual UAC cancellation, Windows 7 runtime,
and final-build Bitdefender validation remain pending.

* fix(windows): roll back new service registration on start failure

Delete a registration created by this attempt if startup fails, while preserving existing services and already-running success. Keep the original startup error and report rollback failures separately.

Validation: eight isolated service checks and the Release Flutter runner build passed. Real service startup failure and final-build Bitdefender validation remain pending.

* fix(windows): continue uninstall after service stop errors

Log an unsuccessful stop and still request deletion so the uninstall
script can reach its existing taskkill and cleanup commands. Treat an
already marked service as a satisfied deletion request, while preserving
other deletion errors and the normal stop wait.

Validation: all twelve isolated service-control checks passed, including
already-marked, stop-rejected, stop-timeout and deletion-denied cases.
The Release Flutter runner build and existing argument/exit-code checks
passed. Real SCM failure scenarios and Bitdefender remain unverified.

* fix(windows): finish installer setup before service startup

Complete SAS policy and printer setup before native service activation so a startup failure cannot skip independent installation steps. Preserve the startup error, rollback and legacy command sequences, and document uninstall_service's continuation result.

Validation: Windows Rust test compilation, four isolated command cases and two existing installer handoff tests passed. CodeRabbit completed with no findings. Actual installer, SCM and Bitdefender validation remains pending.

* fix(windows): use native service control for Sciter

Share the existing native service operations with Sciter and dispatch
--service-control before UI initialization. Keep Flutter's entry point and
the legacy commands for a different installed executable unchanged.

Validated the Windows x64 Sciter build, Flutter-feature test build,
x86 C++ bridge compilation, and real EXE/BAT error propagation. Final
Bitdefender installation and service lifecycle validation remain pending.

* fix(windows): propagate negative service-control exit codes

Treat every nonzero service-control exit status as a failure so crash and loader error codes cannot be reported as success. Verified six real cmd.exe exit-code cases; CodeRabbit review completed with no findings. Actual service crashes were not exercised.

* fix(windows): handle UAC cancellation and scope service rollback

Preserve the typed elevation error and its diagnostic details so canceled UAC prompts do not show an installation-failure dialog.

Use create-service for normal installation and create-service-with-rollback for manual Start Service. Retain a new registration after a normal installation startup error; roll back only the manual path that restores stop-service=Y.

Validation: Windows Rust test compilation, Release Flutter runner and Sciter builds, cancellation/error-chain checks, isolated service-result cases, and real executable argument/exit propagation checks passed. Actual UAC cancellation and Bitdefender were not rerun.
2026-10-22 13:34:49 +08:00
CatzTimesandCatzTimes f010d33ca6 fix(android): wheel scrolling from the controller does not reach Android peers (#16409)
The controller sends a wheel tick as a MouseEvent whose type bits are
MOUSE_TYPE_WHEEL (src/common.rs) with the scroll delta in y, but
InputService only handles the legacy WHEEL_DOWN/WHEEL_UP masks
(523331/963) that current controllers never send. As a result the
mouse wheel does nothing on every Android controlled device.

Handle MOUSE_TYPE_WHEEL with the same stroke emulation the legacy
masks use, as a purely additive branch: a 90px vertical stroke
(MOUSE_WHEEL_STEP, three quarters of the legacy WHEEL_STEP - the full
120px felt too far per tick to reviewers on real devices) over
WHEEL_DURATION at the current cursor position, with the same top-edge
guard and queue consumption, mapped with the controller's sign
convention (y < 0 = wheel down; y == 0, a horizontal tick, is
ignored). The branch is gated to API 24+ like the rest of the gesture
path - below that, legacy devices take the Shizuku backend or a
no-op, not this class. The legacy WHEEL_DOWN/WHEEL_UP implementations
are untouched.

Community reports matching this gap on modern devices: #9321 (Pixel
8, Android 14) and #1466 (Android tablet).

Signed-off-by: CatzTimes <CatzTimes@users.noreply.github.com>
Co-authored-by: CatzTimes <CatzTimes@users.noreply.github.com>
2026-10-22 11:41:56 +08:00
Leo Camus bd92623972 fix(linux): match the xrandr output name at the start of its line (#16590)
The pattern resolutions() and current_resolution() build from the
output name is not anchored, so DP-1 also matches the eDP-1 line. On a
laptop where xrandr lists eDP-1 first, the external DP-1 reports the
built-in panel's current mode and mode list.
2026-10-21 18:59:13 +08:00
21pages 4e93a41ecc Tune MediaCodec static refresh budgets (#16579)
* Tune MediaCodec static refresh budgets

Use H.264 budgets 50/20/20/10 and H.265 budgets 90/20/20/20 from MT6855 1080p measurements with early stopping at 80% of observed-best improvement, not full convergence.

Retain the existing H.265 low-quality budget because the line-pattern sample did not confirm convergence within 150 repeat calls. Keep the existing ten latency-draining repeats, other backends, and refresh timing unchanged.

Extend output-budget and backend-selection regression coverage. Static refresh tests pass with hwcodec (17 tests) and default features (16 tests).

* fix(video): retain the largest static refresh budget per frame
2026-10-21 16:02:32 +08:00
21pages ce54e33c71 fix(ffmpeg): handle QSV encoder stalls and undersized buffers (#16303)
* fix(ffmpeg): bound QSV encoder retries

Limit QSV frame submission to 100 retries and synchronization to 10
retries so persistent SDK warnings return an error to the caller. Retain
queued buffers when synchronization reaches its retry limit, and allow
later calls to retry without latching an error.

Wait 1 ms between retryable submission warnings on Windows: the original
av_usleep(500) becomes Sleep(0), exhausting the retry budget before even
a brief device-busy interval can end. Preserve non-Windows wait behavior
and the existing negative SDK result handling.

Validated against FFmpeg 7.1.1 on Intel UHD 730 with 42 fault/control
cases, synchronization-timeout recovery and close cleanup, real H.264
and HEVC encoding, and separate QSV hardware decoding. Four concurrent
1080p encoders completed 2400 frames without errors.

* fix(ffmpeg): handle undersized QSV HEVC buffers

Reserve at least three bytes per aligned pixel for HEVC output, following
Intel's documented workaround for underestimated bitstream capacity. Check
the size before assigning it to AVPacket's integer capacity.

Report negative synchronization results before reading output metadata or
draining the FIFO, keeping failed tasks owned until encoder close.

On Intel UHD 730, the existing code fails at input 242 with real desktop
captures; the patched code encodes and decodes all 1,200 inputs. Inputs and
PTS match, and the first 241 encoded frames are byte-identical. H.264 also
passes 300 frames, and restoring the small buffer verifies error handling.

* fix(ffmpeg): refresh QSV HEVC capacity after reset and shorten sync waits

* fix(ffmpeg): apply QSV buffer sizing to H.264

* fix: backport FFmpeg hybrid MP4 finalization fix

Backport FFmpeg commit 36896af64a9ecf6835758186e7161a2e954c364d so hybrid MP4 finalization writes the final moov before hiding the original fragmented index. Preserve recoverable fragments when the final index cannot be written.
2026-10-21 16:00:34 +08:00
RustDeskandClaude Opus 5.5 2016f48dd7 fix(file-transfer): keyboard navigation in the desktop file list (#16642)
* fix(file-transfer): keyboard navigation in the desktop file list

Up/Down never moved the selection in the desktop file transfer list. The
arrow keys fell through to directional focus traversal instead, which
moved focus out of the list and stopped type-to-search until the mouse
entered the list again.

Handle the navigation keys on the list, as the Sciter grid did:
- Up/Down move the selection one row; Shift extends or shrinks a range
  from its anchor.
- PageUp/PageDown go to the edge of the visible rows first, then a page
  further; Home/End go to the first/last row. Shift extends with each.
- Enter/numpad Enter opens the selected folder, like a double click.
- Left/Right are consumed so focus does not jump to the other pane.

Type-to-search now ignores control characters. On macOS and Linux Enter
carries "\r", which matched no name and cleared the selection before
Enter could open it.

Fixes #16635

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(file-transfer): keep default keys on focused file list children

The navigation bindings wrapped the whole file list, sort headers
included, so a header focused with Tab lost Enter to sort and the arrow
keys to move between headers: Enter ran the open-folder binding instead.

Handle the bindings only while the list itself has primary focus and let
keys on a focused child take their default path.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(file-transfer): focus the file list when a row is clicked

The navigation keys only act while the file list holds primary focus.
Keyboard focus was handed to the list only when the mouse entered it,
so after Tab moved focus to a sort header, clicking a row left the
arrow keys inert until the mouse left and re-entered the list.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 15:50:38 +08:00
fufesou b44b71cfab Fix/download path validation (#16601)
* fix: validate download destinations and peer filename rules

Reject unsafe or linked download destinations and validate empty-directory
paths before creating them. Bind overwrite approval to accepted transfer
entries and propagate receiver errors to the UI.

Validate remote listings using the peer's filename rules so Unix names
remain browsable on Windows. Reject locally unsafe basenames before
starting downloads from either the Flutter or legacy UI.

Finish the previous file before validating the next digest so rejecting
the next destination preserves the file already received.

Require confirmation before restarting interrupted downloads with stale
staging files. Preserve matching resumes and cover receiver recovery.

Retain explicit overwrite rejection for peers older than 1.1.10 that
cannot negotiate confirmation.

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

* comments

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

* fix: use async I/O for download preparation and resume

Use Tokio filesystem APIs for download setup and resume metadata checks. Run the Windows link-count query on the blocking pool and flush digest writes before returning.

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

---------

Signed-off-by: fufesou <linlong1266@gmail.com>
2026-10-21 11:55:00 +08:00
mvtbh eef1096395 Update fa.rs (#16587) 2026-10-21 11:45:01 +08:00
Andrzej Rudnikgreptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>RustDesk
8b61033178 Update pl.rs (#16588)
* Update pl.rs

Update Polish language (shortcuts screen).

* Update src/lang/pl.rs

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

* Update src/lang/pl.rs

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

* Update pl.rs

* Update pl.rs

Corrected typo.

---------

Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>
Co-authored-by: RustDesk <71636191+rustdesk@users.noreply.github.com>
2026-10-21 11:44:46 +08:00
Alex Rijckaert c29bef18bb Update Dutch translations for keyboard shortcuts (#16625) 2026-10-21 11:43:30 +08:00
fathur c6258f4166 Fix typo in Indonesian translation (#16630)
* docs(id): translate misuse disclaimer section

* docs(id): add Flathub download badge

* i18n(id): fix typo in Indonesian translation

* fix broken translation tuple in id.rs

* i18n(id): fix typo in Indonesian translation
2026-10-21 11:43:15 +08:00
bovirus 989beee17f Update Italian language (#16633) 2026-10-21 11:42:56 +08:00
Ricardo Simõesandgreptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com> 4b1821d1ff Update pt pt translation + README.md to include Portuguese (Portugal) (docs/README-PTPT.md) (#16634)
* Update pt_PT.rs

* Add files via upload

* Update README-PTPT.md

* Update README-PTPT.md

* Update README.md to include new pt-PT (docs/README-PTPT.md)

* Update docs/README-PTPT.md

Corrected link libs/base

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

* Update docs/README-PTPT.md

Corrected "área de trabalho" to "área de transferência"

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

* Update pt_PT.rs

Fix api_server_connection_tip and api_server_empty_tip: translate from en.rs source

* Fix relative links in README-PTPT.md (remove extra docs/ prefix)

* Fix section anchors in README-PTPT.md to match PT-PT headings

* Fix typos and gender agreement in README-PTPT.md disclaimer

* Use European Portuguese terms in README-PTPT.md screenshot alt text

* Translate shortcut instructions from en.rs source

* Update pt_PT.rs

Align shortcut and API server strings with en.rs source (keep {} placeholders)

* Revert JumpLink to original value (out of scope for this PR

* Replace remaining Brazilian Portuguese terms in README-PTPT.md

Replaces leftover Brazilian Portuguese wording with European Portuguese
equivalents (e.g. "conosco" -> "connosco", "controle" -> "controlo",
"conexão" -> "ligação", "Você tem" -> "Tem", "amigável" -> "acessível",
"desktop" -> "ambiente de trabalho"), consistent with the terminology
already used in src/lang/pt_PT.rs.

---------

Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>
2026-10-21 11:42:44 +08:00
Shaan Majid 3202d1764c chore(deps): update webpki-roots and rustls-webpki in Cargo.lock (#16639)
webpki-roots and webpki-root-certs 1.0.10 drop emSign ECC Root CA - G3, whose
eMudhra intermediates had their private keys compromised. rustls-webpki
0.103.16 rejects chains through those intermediates (RUSTSEC-2026-0382,
RUSTSEC-2026-0383); it needs rustls-pki-types >= 1.12.

Signed-off-by: Shaan Majid <70789625+shaanmajid@users.noreply.github.com>
2026-10-21 11:42:17 +08:00
fufesou c7f212df2c fix: warn about insecure custom API server connections (#16616)
* fix: warn about insecure custom API server connections

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

* fix: limit API server warning to HTTP addresses

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

* fix: resolve API warnings against effective server configuration

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

* fix: reuse common sync for API server previews

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

* fix: keep server settings usable on API preview errors

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

---------

Signed-off-by: fufesou <linlong1266@gmail.com>
2026-10-20 22:52:48 +08:00
fathur 7f5a401947 Update README-ID translations (#16626)
* docs(id): translate misuse disclaimer section

* docs(id): add Flathub download badge
2026-10-20 22:50:42 +08:00
Leo Camus bbffc1de5a fix: bracket a bare IPv6 ID server when deriving the API server (#16624)
With the API server field empty, get_api_server_ builds the URL from the
ID server as "http://{host}:21114". For an ID server entered as a bare
IPv6 address such as 2001:db8::1, which test_if_valid_server accepts,
increase_port leaves it unchanged and the result is
http://2001:db8::1:21114. That does not parse as a URL (InvalidPort), so
login and every other API request fail.

Wrap the address in brackets in that branch only. Hostnames, IPv4 and
"[addr]:port" take the same path as before.
2026-10-20 22:12:00 +08:00
Leo Camus 4b92080e3e fix(x11): keep the RandR monitors reply alive while iterating it (#16595)
DisplayIter::next_screen built the monitor iterator from the
xcb_randr_get_monitors reply and freed the reply on the next line.
The iterator's data pointer points into that reply, so next() read
every monitor's name atom, position and size from freed memory, and
xcb_randr_monitor_info_next() walked it too.

Keep the reply with the iterator and free it when moving to the next
screen or when the DisplayIter is dropped.
2026-10-20 17:29:30 +08:00
Chris21xandchg 0cbeb04730 Forward audio latency environment to Linux user server (#16597)
* Forward audio latency environment to Linux user server

Preserve PULSE_LATENCY_MSEC and PIPEWIRE_LATENCY when the root service spawns the per-user RustDesk server.

The systemd service defines these variables, but they were not included in the explicit environment passed to run_as_user(), causing the user server and connection manager to fall back to higher audio latency.

Forward the existing values without changing their defaults.

* Add regression test for Linux audio latency forwarding

---------

Co-authored-by: chg <chg@vis-ag.ch>
2026-10-20 17:13:11 +08:00
fathur 1042a26deb Add Flutter code section to README-ID (#16600)
* Add Flutter code section to README-ID

Added a section for Flutter code related to desktop and mobile platforms.

* Fix link formatting for Flutter code section
2026-10-20 16:13:13 +08:00
solokot 53996e3c40 Update ru.rs (#16570) 2026-10-16 11:18:21 +08:00
RustDesk e400bb7554 Enforce lockfile during pub get in build script 2026-10-15 22:39:27 +08:00
21pages 392188596c fix(video): improve clarity after scrolling by re-encoding static frames (#16128)
* fix(video): re-encode static frames for up to 10 seconds to improve clarity

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

fix(video): limit static re-encoding to 300 frames instead of 10 seconds

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

refactor(video): move static frame refresh into a dedicated module

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

fix(video): preserve stuck-encoder detection state across static repeats

test(video): cover cached texture lifetime across capture restarts

fix(video): reduce static re-encoding limit to 100 frames

fix(qos): lower qos_trace logging to trace level

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

fix(video): skip static frame re-encoding for AV1

perf(video): reuse VRAM encoder input for static refresh

Remove the DXGI repeat texture cache and use hwcodec's repeat entry point to avoid copying each captured frame. Isolate static refresh failures, pause after three errors, and resume after a real frame is sent successfully.

Cover cached input ownership, repeat failure recovery, refresh limits, and normal encoder failover with regression tests.

fix(vram): ignore cached SDK codec backends

chore(deps): temporarily use hwcodec re-encode branch

perf(video): wait 200ms before starting static refresh

chore(deps): update hwcodec for FFI exception handling

chore(deps): update hwcodec to 0.8.0

perf(video): start static refresh after 100ms

chore(deps): update hwcodec for exception-safe cleanup

chore(deps): update hwcodec for device-loss handling and noexcept FFI

chore(deps): update hwcodec to bbfc306

chore(qos): remove verbose diagnostics while retaining trace logs

* update hwcodec

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

* refactor(scrap): keep repeat encoding in the vram module

* perf(vram): avoid intermediate frame vectors

  - Drain normal and repeated encode output into protobuf messages.
  - Cover null-texture encoding failures.
  - Clarify the count-based static refresh budget.
  - Update hwcodec to fix RAM decode buffers on resolution changes.

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

* fix(scrap): preserve hardware encoder error codes

* test(video): remove uptime dependency from static refresh tests

* feat(video): configure static repeat limits by codec and quality

* fix(video): exempt VPx and AV1 from static repeat failure limit

* fix(video): count only successful static repeat frames

* fix(video): refine static repeat scheduling and VPx frame handling

Allow static refinement after a VP8/VP9 captured frame produces no output
without enabling it after a genuine encoding error. Carry this distinction
alongside the send result so the latest cached frame can still be sent when
capture becomes idle.

Keep VP8/VP9 repeats at a minimum of 100ms. Other codecs wait at least 100ms
initially, then follow the QoS frame interval aligned with the capture loop.
Use four quality bands, with VP8/VP9 limits of 30/20/20/0 and the tuned
H264/H265 limits. Include only production behavior and regression tests.

Validation: 16 static_refresh tests passed with hwcodec,vram,flutter enabled,
covering latest-frame recovery, genuine errors, timing, and repeat budgets.

* fix(video): tune static repeat limits by codec and backend

Use the measured obvious-improvement checkpoints for VP8/VP9 and separate
NVENC, QSV, and AMF H.264/HEVC limits for each quality tier. The checkpoints
recover 80% of the observed error improvement across the tested inputs.

Resolve the hardware backend from EncoderCfg during StaticRefresh
construction, including the VRAM adapter vendor. Keep the existing limits
for other hardware backends.

Validation: 19 static_refresh tests passed with hwcodec,vram,flutter.
The repeat measurements cover 192 series with no encode/decode errors.

* fix(video): refine static refresh budgets and cap repeat FPS

Add VideoToolbox HEVC budgets and tune quality bands from repeat-frame comparisons. Cap static refresh at 30 FPS and use the speed preset consistently at quality 0.5.

* remove unused variables

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

* fix(video): repair static refresh tests and throttle repeat logs

---------

Signed-off-by: 21pages <sunboeasy@gmail.com>
2026-10-15 20:17:49 +08:00
RustDeskandClaude Opus 5.5 c0750fb50c fix(client): report one error when both WebRTC race legs fail (#16563)
Both legs of race_transports_prefer_webrtc send their own punch request
to the same rendezvous server for the same peer, so a refusal there
(offline, unknown ID, key mismatch, a server-supplied other_failure)
fails both with the same text. Joining them as "WebRTC failed: X;
fallback failed: X" showed it twice and broke the UI's whole-string
matching: the offline auto-retry needs exactly "Remote desktop is
offline", the message box translates the text as one string, and
check_if_retry hides the retry button for any text containing "failed".

Return the error of the leg that failed last, as select_ok did before
the race existed, and log the other one once.


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

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 19:52:19 +08:00
fufesou f705902ec3 fix(windows): move installer scripts into protected temp directories (#16554)
* fix(windows): move installer scripts into protected temp directories

Create a private directory under Windows Temp with its final DACL in
CreateDirectoryW. Grant Administrators and SYSTEM full access and use
OWNER RIGHTS to suppress the ordinary creator's implicit WRITE_DAC.

Keep the existing elevated system-cmd copy and SHA-256 verification flow.
Keep auxiliary files in the same directory, report cleanup failures, and
check command length before creating the directory.

This avoids PowerShell, helper executables, and application startup or DLL
linking changes. The Windows Temp parent must retain its standard protection
against deletion by unprivileged users. UAC cancellation can leave an empty
protected directory; the error reports its path.

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

* fix(windows): preserve installer results when cleanup fails

Keep the original installer exit code and report remaining temporary directories or inspection errors as warnings with their paths. Include the directory path in creation errors.

Restore the existing handoff assertions in a separate test module, add a locked-directory regression for successful and failed installers, and remove the unrelated ERRORLEVEL environment change.

Validation: scoped formatting and whitespace checks passed. Native cmd probes reproduced the failure before the fix and preserved both exit codes afterwards. No project build or Rust test execution was performed.
Signed-off-by: fufesou <linlong1266@gmail.com>

* fix(windows): clarify installer cleanup warnings

Describe protected directories as possibly remaining when cleanup cannot be verified. Remove the cleanup-only test added during review while retaining existing handoff coverage.

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

* test(windows): keep installer handoff tests inline

Restore the inline test module and original helper order to reduce the diff against master. Keep the directory cleanup assertions and original bootstrap checks.

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

* fix(windows): include paths in installer directory check errors

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

* fix(windows): clear inherited ERRORLEVEL before installation

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

* fix(windows): avoid duplicate directory error messages

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

* test(windows): verify installer directory permissions

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

---------

Signed-off-by: fufesou <linlong1266@gmail.com>
2026-10-15 17:33:35 +08:00
RustDeskandClaude Opus 5.5 0d36ac0cba fix(linux): stop using the window in onWindowClose once GTK destroyed it (#16561)
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


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

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 15:33:42 +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
250 changed files with 14579 additions and 12075 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;
+28 -2
View File
@@ -366,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
@@ -965,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
@@ -1022,6 +1033,16 @@ jobs:
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: |
@@ -2354,6 +2375,11 @@ jobs:
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
+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
+16 -15
View File
@@ -3737,7 +3737,7 @@ dependencies = [
"url",
"users",
"uuid",
"webpki-roots 1.0.9",
"webpki-roots 1.0.11",
"webrtc",
"whoami",
"x11 2.21.0",
@@ -3888,8 +3888,8 @@ checksum = "9a3a5bfb195931eeb336b2a7b4d761daec841b97f947d34394601737a7bba5e4"
[[package]]
name = "hwcodec"
version = "0.7.1"
source = "git+https://github.com/rustdesk-org/hwcodec#778df1f99597722473b29443bac22ae6c23946fe"
version = "0.8.0"
source = "git+https://github.com/rustdesk-org/hwcodec#ec38ebaf2454269d4c5668a57e3813c6e5541be7"
dependencies = [
"bindgen 0.59.2",
"cc",
@@ -3935,7 +3935,7 @@ dependencies = [
"tokio",
"tokio-rustls",
"tower-service",
"webpki-roots 1.0.9",
"webpki-roots 1.0.11",
]
[[package]]
@@ -6930,7 +6930,7 @@ dependencies = [
"wasm-bindgen",
"wasm-bindgen-futures",
"web-sys",
"webpki-roots 1.0.9",
"webpki-roots 1.0.11",
]
[[package]]
@@ -7041,7 +7041,7 @@ dependencies = [
[[package]]
name = "rust-pulsectl"
version = "0.2.12"
source = "git+https://github.com/rustdesk-org/pulsectl#aa34dde499aa912a3abc5289cc0b547bd07dd6e2"
source = "git+https://github.com/rustdesk-org/pulsectl#d2ec086b5770dce934a66956364d09df8cc9484c"
dependencies = [
"libpulse-binding",
]
@@ -7296,11 +7296,12 @@ dependencies = [
[[package]]
name = "rustls-pki-types"
version = "1.11.0"
version = "1.15.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "917ce264624a4b4db1c364dcc35bfca9ded014d0a958cd47ad3e960e988ea51c"
checksum = "2f4925028c7eb5d1fcdaf196971378ed9d2c1c4efc7dc5d011256f76c99c0a96"
dependencies = [
"web-time",
"zeroize",
]
[[package]]
@@ -7332,9 +7333,9 @@ checksum = "f87165f0995f63a9fbeea62b64d10b4d9d8e78ec6d7d51fb2125fda7bb36788f"
[[package]]
name = "rustls-webpki"
version = "0.103.3"
version = "0.103.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e4a72fe2bcf7a6ac6fd7d0b9e5cb68aeb7d4c0a0271730218b3e92d43b4eb435"
checksum = "4443b1b6d39d7c663139942cc4558262562d2c84123bb6282ef177009ca8b281"
dependencies = [
"ring",
"rustls-pki-types",
@@ -9539,9 +9540,9 @@ dependencies = [
[[package]]
name = "webpki-root-certs"
version = "1.0.3"
version = "1.0.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "05d651ec480de84b762e7be71e6efa7461699c19d9e2c272c8d93455f567786e"
checksum = "58ec80e73fd8baf57bf0d9615554c75348bda990d6d5bbeab964dd068319fecb"
dependencies = [
"rustls-pki-types",
]
@@ -9552,14 +9553,14 @@ version = "0.26.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "521bc38abb08001b01866da9f51eb7c5d647a19260e00054a8c7fd5f9e57f7a9"
dependencies = [
"webpki-roots 1.0.9",
"webpki-roots 1.0.11",
]
[[package]]
name = "webpki-roots"
version = "1.0.9"
version = "1.0.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7dcd9d09a39985f5344844e66b0c530a33843579125f23e21e9f0f220850f22a"
checksum = "f5f280bbb2b287bc8e7de7e3852945a0ff50d1bbcb5ed42b6c7a568c546df171"
dependencies = [
"rustls-pki-types",
]
+1 -1
View File
@@ -273,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
@@ -4,7 +4,7 @@
<a href="#how-to-build-with-docker">Docker</a> •
<a href="#file-structure">Structure</a> •
<a href="#screenshots">Screenshots</a><br>
[<a href="docs/README-UA.md">Українська</a>] | [<a href="docs/README-CS.md">česky</a>] | [<a href="docs/README-ZH.md">中文</a>] | [<a href="docs/README-HU.md">Magyar</a>] | [<a href="docs/README-ES.md">Español</a>] | [<a href="docs/README-FA.md">فارسی</a>] | [<a href="docs/README-FR.md">Français</a>] | [<a href="docs/README-DE.md">Deutsch</a>] | [<a href="docs/README-PL.md">Polski</a>] | [<a href="docs/README-ID.md">Indonesian</a>] | [<a href="docs/README-FI.md">Suomi</a>] | [<a href="docs/README-ML.md">മലയാളം</a>] | [<a href="docs/README-JP.md">日本語</a>] | [<a href="docs/README-NL.md">Nederlands</a>] | [<a href="docs/README-IT.md">Italiano</a>] | [<a href="docs/README-RU.md">Русский</a>] | [<a href="docs/README-PTBR.md">Português (Brasil)</a>] | [<a href="docs/README-EO.md">Esperanto</a>] | [<a href="docs/README-KR.md">한국어</a>] | [<a href="docs/README-AR.md">العربي</a>] | [<a href="docs/README-VN.md">Tiếng Việt</a>] | [<a href="docs/README-DA.md">Dansk</a>] | [<a href="docs/README-GR.md">Ελληνικά</a>] | [<a href="docs/README-TR.md">Türkçe</a>] | [<a href="docs/README-NO.md">Norsk</a>] | [<a href="docs/README-RO.md">Română</a>]<br>
[<a href="docs/README-UA.md">Українська</a>] | [<a href="docs/README-CS.md">česky</a>] | [<a href="docs/README-ZH.md">中文</a>] | [<a href="docs/README-HU.md">Magyar</a>] | [<a href="docs/README-ES.md">Español</a>] | [<a href="docs/README-FA.md">فارسی</a>] | [<a href="docs/README-FR.md">Français</a>] | [<a href="docs/README-DE.md">Deutsch</a>] | [<a href="docs/README-PL.md">Polski</a>] | [<a href="docs/README-ID.md">Indonesian</a>] | [<a href="docs/README-FI.md">Suomi</a>] | [<a href="docs/README-ML.md">മലയാളം</a>] | [<a href="docs/README-JP.md">日本語</a>] | [<a href="docs/README-NL.md">Nederlands</a>] | [<a href="docs/README-IT.md">Italiano</a>] | [<a href="docs/README-RU.md">Русский</a>] | [<a href="docs/README-PTPT.md">Português (Portugal)</a>] | [<a href="docs/README-PTBR.md">Português (Brasil)</a>] | [<a href="docs/README-EO.md">Esperanto</a>] | [<a href="docs/README-KR.md">한국어</a>] | [<a href="docs/README-AR.md">العربي</a>] | [<a href="docs/README-VN.md">Tiếng Việt</a>] | [<a href="docs/README-DA.md">Dansk</a>] | [<a href="docs/README-GR.md">Ελληνικά</a>] | [<a href="docs/README-TR.md">Türkçe</a>] | [<a href="docs/README-NO.md">Norsk</a>] | [<a href="docs/README-RO.md">Română</a>]<br>
<b>We need your help to translate this README, <a href="https://github.com/rustdesk/rustdesk/tree/master/src/lang">RustDesk UI</a> and <a href="https://github.com/rustdesk/doc.rustdesk.com">RustDesk Doc</a> to your native language</b>
</p>
+6 -1
View File
@@ -2,7 +2,12 @@
fn build_windows() {
let file = "src/platform/windows.cc";
let file2 = "src/platform/windows_delete_test_cert.cc";
cc::Build::new().file(file).file(file2).compile("windows");
let mut build = cc::Build::new();
if !cfg!(feature = "flutter") {
build.cpp(true).std("c++17").define("RUSTDESK_SCITER", None);
println!("cargo:rerun-if-changed=flutter/windows/runner/service_control.h");
}
build.file(file).file(file2).compile("windows");
println!("cargo:rustc-link-lib=WtsApi32");
println!("cargo:rerun-if-changed={}", file);
println!("cargo:rerun-if-changed={}", file2);
+8 -1
View File
@@ -9,6 +9,10 @@
<b>Kami membutuhkan bantuanmu untuk menterjemahkan file README dan <a href="https://github.com/rustdesk/rustdesk/tree/master/src/lang">RustDesk UI</a> ke Bahasa Indonesia</b>
</p>
> [!Caution]
> **Peringatan Penyalahgunaan:** <br>
> Pengembang RustDesk tidak membenarkan atau mendukung penggunaan perangkat lunak ini yang tidak etis atau melanggar hukum. Penyalahgunaan, seperti akses tanpa izin, pengambilalihan kendali, atau pelanggaran privasi, sangat dilarang berdasarkan pedoman kami. Para pengembang tidak bertanggung jawab atas penyalahgunaan aplikasi ini.
Mari mengobrol bersama kami: [Discord](https://discord.gg/nDceKgxnkV) | [Twitter](https://twitter.com/rustdesk) | [Reddit](https://www.reddit.com/r/rustdesk) | [YouTube](https://www.youtube.com/@rustdesk)
[![RustDesk Server Pro](https://img.shields.io/badge/RustDesk%20Server%20Pro-Fitur%20Lanjutan-blue)](https://rustdesk.com/pricing.html)
@@ -30,6 +34,9 @@ RustDesk mengajak semua orang untuk ikut berkontribusi. Lihat [`docs/CONTRIBUTIN
[<img src="https://fdroid.gitlab.io/artwork/badge/get-it-on.png"
alt="Get it on F-Droid"
height="80">](https://f-droid.org/en/packages/com.carriez.flutter_hbb)
[<img src="https://flathub.org/api/badge?svg&locale=en"
alt="Get it on Flathub"
height="80">](https://flathub.org/apps/com.rustdesk.RustDesk)
## Dependensi
@@ -154,7 +161,7 @@ Harap pastikan bahwa kamu menjalankan perintah ini dari repositori root RustDesk
- **[src/client.rs](https://github.com/rustdesk/rustdesk/tree/master/src/client.rs)**: start a peer connection
- **[src/rendezvous_mediator.rs](https://github.com/rustdesk/rustdesk/tree/master/src/rendezvous_mediator.rs)**: Komunikasi dengan [rustdesk-server](https://github.com/rustdesk/rustdesk-server), menunggu untuk remote direct (TCP hole punching) atau relayed connection
- **[src/platform](https://github.com/rustdesk/rustdesk/tree/master/src/platform)**: kode khusus platform
- **[flutter](https://github.com/rustdesk/rustdesk/tree/master/flutter)**: kode Flutter untuk platform desktop dan perangkat seluler
## Snapshots
![image](https://user-images.githubusercontent.com/71636191/113112362-ae4deb80-923b-11eb-957d-ff88daad4f06.png)
+179
View File
@@ -0,0 +1,179 @@
<p align="center">
<img src="../res/logo-header.svg" alt="RustDesk - O seu ambiente de trabalho remoto"><br>
<a href="#compilar">Compilar</a> •
<a href="#como-compilar-com-o-docker">Docker</a> •
<a href="#estrutura-de-ficheiros">Estrutura</a> •
<a href="#capturas-de-ecrã">Capturas de Ecrã</a><br>
[<a href="../README.md">Inglês</a>] | [<a href="README-UA.md">Ucraniano</a>] | [<a href="README-CS.md">Checo</a>] | [<a href="README-ZH.md">Chinês</a>] | [<a href="README-HU.md">Húngaro</a>] | [<a href="README-ES.md">Espanhol</a>] | [<a href="README-FA.md">Persa</a>] | [<a href="README-FR.md">Francês</a>] | [<a href="README-DE.md">Alemão</a>] | [<a href="README-PL.md">Polaco</a>] | [<a href="README-ID.md">Indonésio</a>] | [<a href="README-FI.md">Finlandês</a>] | [<a href="README-ML.md">Malaiala</a>] | [<a href="README-JP.md">Japonês</a>] | [<a href="README-NL.md">Holandês</a>] | [<a href="README-IT.md">Italiano</a>] | [<a href="README-RU.md">Russo</a>] | [<a href="README-EO.md">Esperanto</a>] | [<a href="README-KR.md">Coreano</a>] | [<a href="README-AR.md">Árabe</a>] | [<a href="README-VN.md">Vietnamita</a>] | [<a href="README-DA.md">Dinamarquês</a>] | [<a href="README-GR.md">Grego</a>] | [<a href="README-TR.md">Turco</a>] | [<a href="README-NO.md">Norueguês</a>] | [<a href="README-RO.md">Romeno</a>]<br>
<b>Precisamos da sua ajuda para traduzir este README, a <a href="https://github.com/rustdesk/rustdesk/tree/master/src/lang">Interface do RustDesk</a> e a <a href="https://github.com/rustdesk/doc.rustdesk.com">Documentação do RustDesk</a> para o seu idioma nativo</b>
</p>
> [!Caution]
> **Aviso de Isenção de Responsabilidade por Uso Indevido:** <br>
> Os programadores do RustDesk não toleram ou apoiam qualquer uso antiético ou ilegal deste software. O uso indevido, como acesso não autorizado, controlo ou invasão de privacidade, é estritamente contrário às nossas diretrizes. Os autores não se responsabilizam por qualquer uso indevido da aplicação.
Converse connosco: [Discord](https://discord.gg/nDceKgxnkV) | [Twitter](https://twitter.com/rustdesk) | [Reddit](https://www.reddit.com/r/rustdesk) | [YouTube](https://www.youtube.com/@rustdesk)
[![RustDesk Server Pro](https://img.shields.io/badge/RustDesk%20Server%20Pro-Advanced%20Features-blue)](https://rustdesk.com/pricing.html)
Mais uma solução de ambiente de trabalho remoto, escrita em Rust. Funciona imediatamente, sem necessidade de configuração. Tem controlo total dos seus dados, sem preocupações com a segurança. Pode usar o nosso servidor de ligação/retransmissão (rendezvous/relay), [configurar o seu próprio](https://rustdesk.com/server) ou [escrever o seu próprio servidor de ligação/retransmissão](https://github.com/rustdesk/rustdesk-server-demo).
![image](https://user-images.githubusercontent.com/71636191/171661982-430285f0-2e12-4b1d-9957-4a58e375304d.png)
O RustDesk agradece as contribuições de todos. Veja [CONTRIBUTING.md](CONTRIBUTING.md) para obter ajuda para começar.
[**Perguntas Frequentes (FAQ)**](https://github.com/rustdesk/rustdesk/wiki/FAQ)
[**DOWNLOAD DOS BINÁRIOS**](https://github.com/rustdesk/rustdesk/releases)
[**VERSÕES NIGHTLY (EM DESENVOLVIMENTO)**](https://github.com/rustdesk/rustdesk/releases/tag/nightly)
[<img src="https://f-droid.org/badge/get-it-on.png"
alt="Transfira no F-Droid"
height="80">](https://f-droid.org/en/packages/com.carriez.flutter_hbb)
[<img src="https://flathub.org/api/badge?svg&locale=en"
alt="Transfira no Flathub"
height="80">](https://flathub.org/apps/com.rustdesk.RustDesk)
## Dependências
As versões para ambiente de trabalho usam Flutter ou Sciter (descontinuado) para a interface gráfica (GUI). Este tutorial é apenas para o Sciter, por ser mais fácil e acessível para começar. Consulte o nosso [CI](https://github.com/rustdesk/rustdesk/blob/master/.github/workflows/flutter-build.yml) para instruções de compilação da versão Flutter.
Por favor transfira a biblioteca dinâmica do Sciter por conta própria.
[Windows](https://raw.githubusercontent.com/c-smile/sciter-sdk/master/bin.win/x64/sciter.dll) |
[Linux](https://raw.githubusercontent.com/c-smile/sciter-sdk/master/bin.lnx/x64/libsciter-gtk.so) |
[macOS](https://raw.githubusercontent.com/c-smile/sciter-sdk/master/bin.osx/libsciter.dylib)
## Passos básicos para compilar
- Prepare o seu ambiente de desenvolvimento Rust e o ambiente de compilação C++
- Instale o [vcpkg](https://github.com/microsoft/vcpkg) e configure a variável de ambiente `VCPKG_ROOT` corretamente
- Windows: `vcpkg install libvpx:x64-windows-static libyuv:x64-windows-static opus:x64-windows-static aom:x64-windows-static`
- Linux/macOS: `vcpkg install libvpx libyuv opus aom`
- Execute `cargo run`
## [Compilar](https://rustdesk.com/docs/en/dev/build/)
## Como Compilar no Linux
### Ubuntu 18 (Debian 10)
```sh
sudo apt install -y zip g++ gcc git curl wget nasm yasm libgtk-3-dev clang libxcb-randr0-dev libxdo-dev libxfixes-dev libxcb-shape0-dev libxcb-xfixes0-dev libasound2-dev libpulse-dev cmake make libclang-dev ninja-build libgstreamer1.0-dev libgstreamer-plugins-base1.0-dev
```
### openSUSE Tumbleweed
```sh
sudo zypper install gcc-c++ git curl wget nasm yasm gcc gtk3-devel clang libxcb-devel libXfixes-devel cmake alsa-lib-devel gstreamer-devel gstreamer-plugins-base-devel xdotool-devel
```
### Fedora 28 (CentOS 8)
```sh
sudo yum -y install gcc-c++ git curl wget nasm yasm gcc gtk3-devel clang libxcb-devel libxdo-devel libXfixes-devel pulseaudio-libs-devel cmake alsa-lib-devel gstreamer1-devel gstreamer1-plugins-base-devel
```
### Arch (Manjaro)
```sh
sudo pacman -Syu --needed unzip git cmake gcc curl wget yasm nasm zip make pkg-config clang gtk3 xdotool libxcb libxfixes alsa-lib pipewire
```
### Instalar o vcpkg
```sh
git clone https://github.com/microsoft/vcpkg
cd vcpkg
git checkout 2023.04.15
cd ..
vcpkg/bootstrap-vcpkg.sh
export VCPKG_ROOT=$HOME/vcpkg
vcpkg/vcpkg install libvpx libyuv opus aom
```
### Corrigir o libvpx (Para Fedora)
```sh
cd vcpkg/buildtrees/libvpx/src
cd *
./configure
sed -i 's/CFLAGS+=-I/CFLAGS+=-fPIC -I/g' Makefile
sed -i 's/CXXFLAGS+=-I/CXXFLAGS+=-fPIC -I/g' Makefile
make
cp libvpx.a $HOME/vcpkg/installed/x64-linux/lib/
cd
```
### Compilar
```sh
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
source $HOME/.cargo/env
git clone --recurse-submodules https://github.com/rustdesk/rustdesk
cd rustdesk
mkdir -p target/debug
wget https://raw.githubusercontent.com/c-smile/sciter-sdk/master/bin.lnx/x64/libsciter-gtk.so
mv libsciter-gtk.so target/debug
VCPKG_ROOT=$HOME/vcpkg cargo run
```
## Como compilar com o Docker
Comece por clonar o repositório e construir o contentor Docker:
```sh
git clone https://github.com/rustdesk/rustdesk
cd rustdesk
git submodule update --init --recursive
docker build -t "rustdesk-builder" .
```
Depois, cada vez que precisar de compilar a aplicação, execute o seguinte comando:
```sh
docker run --rm -it -v $PWD:/home/user/rustdesk -v rustdesk-git-cache:/home/user/.cargo/git -v rustdesk-registry-cache:/home/user/.cargo/registry -e PUID="$(id -u)" -e PGID="$(id -g)" rustdesk-builder
```
Note que a primeira compilação pode demorar mais até que as dependências sejam armazenadas em cache, as compilações subsequentes serão mais rápidas. Além disso, se precisar especificar argumentos diferentes para o comando de compilação, poderá fazê-lo no final do comando na posição `<ARGUMENTOS-OPCIONAIS>`. Por exemplo, se quiser compilar uma versão de lançamento (release) otimizada, executaria o comando acima seguido de `--release`. O executável resultante estará disponível na pasta `target` do seu sistema e pode ser executado com:
```sh
target/debug/rustdesk
```
Ou, se estiver a correr o executável de lançamento:
```sh
target/release/rustdesk
```
Certifique-se de que executa estes comandos a partir da raiz do repositório do RustDesk, caso contrário a aplicação poderá não encontrar os recursos necessários. Note também que outros subcomandos do cargo, como `install` ou `run`, não são suportados atualmente por este método, pois instalariam ou executariam o programa dentro do contentor em vez de o fazerem no host.
## Estrutura de Ficheiros
- **[libs/hbb_common](https://github.com/rustdesk/rustdesk/tree/master/libs/hbb_common)**: codec de vídeo, configuração, wrapper TCP/UDP e algumas outras funções utilitárias partilhadas com o servidor
- **[libs/base](https://github.com/rustdesk/rustdesk/tree/master/libs/base)**: protobuf, funções fs para transferência de ficheiros, código relacionado com o teclado e com a plataforma utilizado exclusivamente por esta aplicação
- **[libs/scrap](https://github.com/rustdesk/rustdesk/tree/master/libs/scrap)**: captura de ecrã
- **[libs/enigo](https://github.com/rustdesk/rustdesk/tree/master/libs/enigo)**: controlo de teclado/rato específico da plataforma.
- **[libs/clipboard](https://github.com/rustdesk/rustdesk/tree/master/libs/clipboard)**: implementação de copiar e colar ficheiros para Windows, Linux e macOS.
- **[src/ui](https://github.com/rustdesk/rustdesk/tree/master/src/ui)**: interface Sciter obsoleta (descontinuada).
- **[src/server](https://github.com/rustdesk/rustdesk/tree/master/src/server)**: serviços de áudio, área de transferência, entrada e vídeo, e ligações de rede
- **[src/client.rs](https://github.com/rustdesk/rustdesk/tree/master/src/client.rs)**: inicia uma ligação entre pares
- **[src/rendezvous_mediator.rs](https://github.com/rustdesk/rustdesk/tree/master/src/rendezvous_mediator.rs)**: Comunica com o [rustdesk-server](https://github.com/rustdesk/rustdesk-server), aguarda por uma ligação direta remota (TCP hole punching) ou uma ligação retransmitida
- **[src/platform](https://github.com/rustdesk/rustdesk/tree/master/src/platform)**: código específico da plataforma
- **[flutter](https://github.com/rustdesk/rustdesk/tree/master/flutter)**: código Flutter para ambiente de trabalho e dispositivos móveis
## Capturas de Ecrã
![Gestor de Ligações](https://github.com/rustdesk/rustdesk/assets/28412477/db82d4e7-c4bc-4823-8e6f-6af7eadf7651)
![Ligado a um PC Windows](https://github.com/rustdesk/rustdesk/assets/28412477/9baa91e9-3362-4d06-aa1a-7518edcbd7ea)
![Transferência de Ficheiros](https://github.com/rustdesk/rustdesk/assets/28412477/39511ad3-aa9a-4f8c-8947-1cce286a46ad)
![Túnel TCP](https://github.com/rustdesk/rustdesk/assets/28412477/78e8708f-e87e-4570-8373-1360033ea6c5)
@@ -0,0 +1,41 @@
package com.carriez.flutter_hbb
import android.os.ParcelFileDescriptor
import org.json.JSONObject
import java.io.IOException
import java.util.UUID
import java.util.concurrent.ConcurrentHashMap
internal class DocumentDescriptors {
private val descriptors = ConcurrentHashMap<String, ParcelFileDescriptor>()
fun open(descriptor: ParcelFileDescriptor): JSONObject {
val id = UUID.randomUUID().toString()
try {
// Only detach the duplicate: the original carries the provider's close/error channel.
val duplicate = ParcelFileDescriptor.dup(descriptor.fileDescriptor)
descriptors[id] = descriptor
return JSONObject().put("fd", duplicate.detachFd()).put("descriptor", id)
} catch (error: Exception) {
descriptors.remove(id)
try {
descriptor.closeWithError(error.message ?: "Unable to open document")
} catch (closeError: Exception) {
error.addSuppressed(closeError)
}
throw error
}
}
fun close(request: JSONObject): Boolean {
val descriptor = descriptors.remove(request.getString("descriptor"))
?: throw IOException("Document descriptor was already closed")
val error = request.optString("error", "")
if (error.isNotEmpty()) {
descriptor.closeWithError(error)
} else {
descriptor.use { if (it.canDetectErrors()) it.checkError() }
}
return true
}
}
@@ -0,0 +1,261 @@
package com.carriez.flutter_hbb
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.ParcelFileDescriptor
import android.provider.DocumentsContract
import android.provider.DocumentsContract.Document
import android.util.Log
import java.io.FileNotFoundException
import java.io.IOException
import java.util.UUID
import java.util.concurrent.TimeUnit
import java.util.concurrent.locks.ReentrantLock
import kotlin.concurrent.withLock
internal class DocumentLogs(private val context: Context) {
private val resolver = context.contentResolver
private val prefs = context.getSharedPreferences(DOCUMENT_PREFS, Context.MODE_PRIVATE)
private val appName = context.applicationInfo.loadLabel(context.packageManager).toString()
private val appDirectoryId = "$PARENT_ID/$appName"
private val directoryId = "$appDirectoryId/Logs"
val directoryPath = directoryId.substringAfter(':')
private var output: ParcelFileDescriptor.AutoCloseOutputStream? = null
private var written = 0L
private var openedDay = 0L
private var failure: Exception? = null
private val lock = ReentrantLock()
init {
setEnabled(grant() != null)
}
@androidx.annotation.Keep
private external fun setEnabled(enabled: Boolean)
private fun grant(): Uri? = prefs.getString(LOG_GRANT, null)?.let(Uri::parse)
fun hasPermission(): Boolean {
val uri = grant() ?: return false
if (!isLogGrant(uri)) return false
return resolver.persistedUriPermissions.any {
it.uri == uri && it.isReadPermission && it.isWritePermission
}
}
private fun isLogGrant(uri: Uri): Boolean =
uri.authority == AUTHORITY && DocumentsContract.isTreeUri(uri) &&
DocumentsContract.getTreeDocumentId(uri) in listOf(PARENT_ID, appDirectoryId, directoryId)
private fun isDirectory(uri: Uri): Boolean = try {
resolver.query(uri, arrayOf(Document.COLUMN_MIME_TYPE), null, null, null)?.use {
it.moveToFirst() && it.getString(it.getColumnIndexOrThrow(
Document.COLUMN_MIME_TYPE)) == Document.MIME_TYPE_DIR
} ?: false
} catch (_: FileNotFoundException) {
false
}
private fun containsDirectory(grant: Uri, parentId: String, id: String): Boolean {
val children = DocumentsContract.buildChildDocumentsUriUsingTree(grant, parentId)
val columns = arrayOf(Document.COLUMN_DOCUMENT_ID, Document.COLUMN_MIME_TYPE)
return resolver.query(children, columns, null, null, null)?.use { cursor ->
checkDocumentListing(cursor, "Unable to list ${parentId.substringAfter(':')}",
"${parentId.substringAfter(':')} is still loading")
while (cursor.moveToNext()) {
if (cursor.getString(cursor.getColumnIndexOrThrow(Document.COLUMN_DOCUMENT_ID)) != id) continue
check(cursor.getString(cursor.getColumnIndexOrThrow(Document.COLUMN_MIME_TYPE)) ==
Document.MIME_TYPE_DIR) { "${id.substringAfter(':')} is not a directory" }
return@use true
}
false
} ?: throw IOException("Unable to list ${parentId.substringAfter(':')}")
}
private fun ensureDirectory(grant: Uri): Uri {
checkDocumentName(appName)
val rootId = DocumentsContract.getTreeDocumentId(grant)
var parent = DocumentsContract.buildDocumentUriUsingTree(grant, rootId)
check(isDirectory(parent)) { "The authorized log folder is unavailable" }
val children = when (rootId) {
PARENT_ID -> listOf(appDirectoryId, directoryId)
appDirectoryId -> listOf(directoryId)
directoryId -> emptyList()
else -> throw IOException("The selected folder does not contain $directoryPath")
}
for (id in children) {
val child = DocumentsContract.buildDocumentUriUsingTree(grant, id)
if (!containsDirectory(grant, DocumentsContract.getDocumentId(parent), id)) {
closeOutput()
val created = DocumentsContract.createDocument(
resolver, parent, Document.MIME_TYPE_DIR, id.substringAfterLast('/'))
?: throw IOException("Unable to create ${id.substringAfter(':')}")
check(DocumentsContract.getDocumentId(created) == id) {
"${id.substringAfter(':')} is not available as a directory"
}
}
parent = child
}
return parent
}
fun select(uri: Uri, flags: Int) = lock.withLock {
require(isLogGrant(uri)) {
"Please select Android → media."
}
val permissions = flags and GRANT_FLAGS
require(permissions == GRANT_FLAGS) { "Read and write access is required for logs" }
setEnabled(false)
resolver.takePersistableUriPermission(uri, permissions)
ensureDirectory(uri)
closeOutput()
check(prefs.edit().putString(LOG_GRANT, uri.toString()).commit()) {
"Unable to remember the log directory"
}
check(ensureReady()) { "Log directory access was revoked" }
}
fun ensureReady(): Boolean = lock.withLock {
setEnabled(false)
if (!hasPermission()) return false
val uri = grant() ?: return false
val root = DocumentsContract.buildDocumentUriUsingTree(uri, DocumentsContract.getTreeDocumentId(uri))
if (!isDirectory(root)) return false
ensureDirectory(uri)
failure = null
if (output == null) openNext(uri)
setEnabled(true)
return true
}
fun write(message: String): Boolean {
if (!lock.tryLock()) return false
return try {
writeLocked(message)
} finally {
lock.unlock()
}
}
private fun writeLocked(message: String): Boolean {
val uri = grant() ?: return false
failure?.let { throw IOException("File logging stopped: ${it.message}", it) }
try {
if (output == null && !hasPermission()) {
throw IOException("Log directory access was revoked")
}
if (output == null || written >= MAX_LOG_BYTES || openedDay != currentDay()) {
openNext(uri)
}
val bytes = message.toByteArray(Charsets.UTF_8)
val stream = output ?: throw IOException("The log file is not open")
stream.write(bytes)
written += bytes.size
return true
} catch (error: Exception) {
setEnabled(false)
failure = error
try {
closeOutput()
} catch (closeError: Exception) {
error.addSuppressed(closeError)
}
Log.e("DocumentLogs", "File logging stopped", error)
throw error
}
}
private fun closeOutput() {
val stream = output
output = null
stream?.close()
}
private fun openNext(grant: Uri) {
closeOutput()
val name = "rustdesk-${System.currentTimeMillis()}-${UUID.randomUUID()}.txt"
val document = DocumentsContract.createDocument(
resolver, ensureDirectory(grant), "text/plain", name)
?: throw IOException("Unable to create a log file")
try {
val descriptor = resolver.openFileDescriptor(document, "w")
?: throw IOException("Unable to open the log file")
output = ParcelFileDescriptor.AutoCloseOutputStream(descriptor)
} catch (error: Exception) {
try {
if (!DocumentsContract.deleteDocument(resolver, document)) {
throw IOException("Unable to remove the unopened log file")
}
} catch (cleanupError: Exception) {
error.addSuppressed(cleanupError)
}
throw error
}
written = 0L
openedDay = currentDay()
val logs = files(grant).sortedBy { it.second }
for ((uri, _) in logs.filter { it.first != document }
.take((logs.size - MAX_LOG_FILES).coerceAtLeast(0))) {
try {
if (!DocumentsContract.deleteDocument(resolver, uri)) {
throw IOException("Unable to remove an expired log file")
}
} catch (error: Exception) {
Log.w("DocumentLogs", "Unable to remove an expired log file", error)
}
}
}
private fun files(grant: Uri): List<Pair<Uri, String>> {
val children = DocumentsContract.buildChildDocumentsUriUsingTree(grant, directoryId)
val columns = arrayOf(Document.COLUMN_DOCUMENT_ID, Document.COLUMN_DISPLAY_NAME,
Document.COLUMN_MIME_TYPE)
return resolver.query(children, columns, null, null, null)?.use { cursor ->
checkDocumentListing(cursor, "Unable to list logs", "The log directory is still loading")
val entries = mutableListOf<Pair<Uri, String>>()
while (cursor.moveToNext()) {
if (cursor.getString(cursor.getColumnIndexOrThrow(Document.COLUMN_MIME_TYPE)) ==
Document.MIME_TYPE_DIR) continue
val name = cursor.getString(cursor.getColumnIndexOrThrow(Document.COLUMN_DISPLAY_NAME))
if (!LOG_NAME.matches(name)) continue
val id = cursor.getString(cursor.getColumnIndexOrThrow(Document.COLUMN_DOCUMENT_ID))
entries.add(DocumentsContract.buildDocumentUriUsingTree(grant, id) to name)
}
entries
} ?: throw IOException("Unable to list logs")
}
fun exportTo(destination: Uri): Int {
val uri = grant() ?: return 0
check(hasPermission()) { "Log directory access was revoked" }
val parent = DocumentsContract.buildDocumentUriUsingTree(
destination, DocumentsContract.getTreeDocumentId(destination))
val logs = files(uri)
for ((source, name) in logs) {
val target = DocumentsContract.createDocument(resolver, parent, "text/plain", name)
?: throw IOException("Unable to create an exported log")
val input = resolver.openInputStream(source)
?: throw IOException("Unable to read log $name")
input.use {
val output = resolver.openOutputStream(target, "w")
?: throw IOException("Unable to write log $name")
output.use { destinationStream -> it.copyTo(destinationStream) }
}
}
return logs.size
}
private fun currentDay(): Long = System.currentTimeMillis() / TimeUnit.DAYS.toMillis(1)
companion object {
const val AUTHORITY = "com.android.externalstorage.documents"
const val PARENT_ID = "primary:Android/media"
private const val LOG_GRANT = "log-folder"
private const val GRANT_FLAGS = Intent.FLAG_GRANT_READ_URI_PERMISSION or
Intent.FLAG_GRANT_WRITE_URI_PERMISSION
private const val MAX_LOG_BYTES = 16L * 1024 * 1024
private const val MAX_LOG_FILES = 90
private val LOG_NAME = Regex("rustdesk-[0-9]+-[0-9a-f-]{36}\\.txt")
}
}
@@ -0,0 +1,143 @@
package com.carriez.flutter_hbb
import android.app.Activity
import android.content.Intent
import android.os.Build
import android.provider.DocumentsContract
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import kotlin.concurrent.thread
internal class DocumentPicker(private val activity: Activity) {
private var pending: Pair<MethodChannel.Result, Boolean>? = null
private var pendingLogFolder: MethodChannel.Result? = null
private val storage = (activity.application as MainApplication).documentStorage
fun handle(call: MethodCall, result: MethodChannel.Result): Boolean {
when (call.method) {
"document_require_log_folder" ->
requireLogFolder(result, call.argument<Boolean>("checkOnly") == true)
"document_workspace" -> if (call.argument<Boolean>("share") == true) {
run(result) { storage.shareWorkspace() }
} else {
result.success((activity.getExternalFilesDir(null) ?: activity.filesDir).path)
}
"document_folder" -> pick(result, call.argument<Boolean>("share") == true)
else -> return false
}
return true
}
private fun pick(result: MethodChannel.Result, share: Boolean) {
if (pending != null || pendingLogFolder != null) {
result.error("picker_in_progress", "Another document picker is already open", null)
return
}
try {
val intent = treePickerIntent("primary:Documents")
pending = result to share
activity.startActivityForResult(intent, REQUEST_DOCUMENT)
} catch (error: Exception) {
pending = null
result.error("picker_unavailable", error.message, null)
}
}
fun onResult(requestCode: Int, resultCode: Int, data: Intent?): Boolean {
if (requestCode == REQUEST_LOG_FOLDER) {
val result = pendingLogFolder ?: return true
pendingLogFolder = null
if (resultCode != Activity.RESULT_OK || data?.data == null) {
result.success(false)
} else {
run(result) {
storage.logs.select(requireNotNull(data.data), data.flags)
true
}
}
return true
}
if (requestCode != REQUEST_DOCUMENT) return false
val (result, share) = pending ?: return true
pending = null
if (resultCode != Activity.RESULT_OK || data == null) {
result.success(null)
return true
}
run(result) {
storage.select(requireNotNull(data.data), data.flags, share).toString()
}
return true
}
fun close() {
pendingLogFolder?.error("picker_closed", "Log directory selection was interrupted", null)
pendingLogFolder = null
pending?.first?.error("picker_closed", "Document selection was interrupted", null)
pending = null
}
private fun run(result: MethodChannel.Result, action: () -> Any?) {
thread {
try {
val value = action()
activity.runOnUiThread { result.success(value) }
} catch (error: Exception) {
activity.runOnUiThread { result.error("document_failed", error.message, null) }
}
}
}
private fun requireLogFolder(result: MethodChannel.Result, checkOnly: Boolean) {
if (pending != null || pendingLogFolder != null) {
result.error("picker_in_progress", "Another document picker is already open", null)
return
}
pendingLogFolder = result
thread {
val ready = runCatching { storage.logs.ensureReady() }
activity.runOnUiThread { completeLogFolderCheck(result, ready, checkOnly) }
}
}
private fun completeLogFolderCheck(
result: MethodChannel.Result, ready: Result<Boolean>, checkOnly: Boolean
) {
if (pendingLogFolder !== result) return
ready.fold(onSuccess = {
if (it || checkOnly) {
pendingLogFolder = null
result.success(it)
} else {
pickLogFolder(result)
}
}, onFailure = {
pendingLogFolder = null
result.error("log_directory_failed", it.message, null)
})
}
private fun treePickerIntent(initialId: String): Intent =
Intent(Intent.ACTION_OPEN_DOCUMENT_TREE).apply {
addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION or
Intent.FLAG_GRANT_WRITE_URI_PERMISSION or Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
putExtra(DocumentsContract.EXTRA_INITIAL_URI,
DocumentsContract.buildDocumentUri(DocumentLogs.AUTHORITY, initialId))
}
}
private fun pickLogFolder(result: MethodChannel.Result) {
try {
activity.startActivityForResult(treePickerIntent(DocumentLogs.PARENT_ID), REQUEST_LOG_FOLDER)
} catch (error: Exception) {
pendingLogFolder = null
result.error("picker_unavailable", error.message, null)
}
}
companion object {
private const val REQUEST_DOCUMENT = 4251
private const val REQUEST_LOG_FOLDER = 4252
}
}
@@ -0,0 +1,124 @@
package com.carriez.flutter_hbb
import android.content.Context
import android.content.Intent
import android.database.Cursor
import android.net.Uri
import android.provider.DocumentsContract
import android.util.Base64
import org.json.JSONObject
import java.io.IOException
private const val TREE_ROOT = "/@rustdesk/tree/"
internal const val DOCUMENT_PREFS = "document-storage"
internal const val DEFAULT_LOCATION = "default-location"
private const val URI_FLAGS = Base64.URL_SAFE or Base64.NO_WRAP or Base64.NO_PADDING
private const val MIN_LOCATION_COMPONENTS = 2
internal fun documentRoot(uri: Uri): String =
"$TREE_ROOT${Base64.encodeToString(uri.toString().toByteArray(Charsets.UTF_8), URI_FLAGS)}"
internal fun checkDocumentName(name: String): String {
require(name.isNotEmpty() && name != "." && name != ".." &&
!name.contains('/') && !name.contains('\\') && !name.contains('\u0000')) {
"Invalid document name"
}
return name
}
internal fun checkDocumentListing(cursor: Cursor, errorMessage: String, loadingMessage: String) {
val extras = cursor.extras
extras.getString(DocumentsContract.EXTRA_ERROR)?.let {
throw IOException("$errorMessage: $it")
}
if (extras.getBoolean(DocumentsContract.EXTRA_LOADING)) {
throw IOException(loadingMessage)
}
}
internal fun documentEntry(name: String, directory: Boolean, size: Long = 0): JSONObject =
JSONObject().put("name", name).put("directory", directory)
.put("size", size).put("modified", 0)
internal class DocumentStorage(private val context: Context) {
private val prefs = context.getSharedPreferences(DOCUMENT_PREFS, Context.MODE_PRIVATE)
private val descriptors = DocumentDescriptors()
val logs = DocumentLogs(context)
fun home(): String? = prefs.getString(DEFAULT_LOCATION, null)
fun shareWorkspace(): String {
check(prefs.edit().remove(DEFAULT_LOCATION).commit()) {
"Unable to remember the shared folder"
}
return (context.getExternalFilesDir(null) ?: context.filesDir).path
}
fun select(uri: Uri, flags: Int, share: Boolean): JSONObject {
require(uri.scheme == "content") { "Invalid document selection" }
val grants = flags and (Intent.FLAG_GRANT_READ_URI_PERMISSION or
Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
require(grants != 0) { "The selected location has no access grant" }
context.contentResolver.takePersistableUriPermission(uri, grants)
val root = documentRoot(uri)
val backend = DocumentTree(context, uri, descriptors)
val name = checkDocumentName(backend.rootName())
val path = "$root/$name"
if (share) {
check(prefs.edit().putString(DEFAULT_LOCATION, path).commit()) {
"Unable to remember the shared folder"
}
}
return JSONObject().put("path", path).put("name", name)
}
fun backend(path: String): DocumentTree {
require(path.startsWith(TREE_ROOT)) { "Invalid document location" }
val parts = path.removePrefix(TREE_ROOT).split('/')
require(parts.size >= MIN_LOCATION_COMPONENTS) { "Invalid document location" }
parts.forEach(::checkDocumentName)
val uri = Uri.parse(String(Base64.decode(parts.first(), URI_FLAGS), Charsets.UTF_8))
require(uri.scheme == "content") { "Invalid document URI" }
val authorized =
context.contentResolver.persistedUriPermissions.any { it.uri == uri && it.isReadPermission }
check(authorized) {
"Access to this location was revoked. Select it again on the Android device."
}
return DocumentTree(context, uri, descriptors)
}
fun request(request: String): String = try {
JSONObject().put("value", execute(JSONObject(request)) ?: JSONObject.NULL).toString()
} catch (error: Exception) {
JSONObject().put("error", error.message ?: error.javaClass.simpleName).toString()
}
private fun execute(request: JSONObject): Any? {
val operation = request.getString("op")
if (operation == "home") return home()
if (operation == "log_write") return logs.write(request.getString("message"))
if (operation == "close") return descriptors.close(request)
val path = request.getString("path")
val backend = backend(path)
return when (operation) {
"allowed" -> true
"list" -> backend.list(path)
"stat" -> backend.stat(path)
"open" -> backend.open(path)
else -> mutate(request, backend)
}
}
private fun mutate(request: JSONObject, backend: DocumentTree): Any {
val path = request.getString("path")
return when (val operation = request.getString("op")) {
"begin" -> backend.begin(path, request.getBoolean("overwrite"))
"finish" -> backend.finish(request.getJSONObject("token")).let { true }
"discard" -> backend.discard(request.getJSONObject("token")).let { true }
"delete" -> backend.delete(path).let { true }
"mkdir" -> backend.mkdir(path).let { true }
"rename" -> backend.rename(path, checkDocumentName(request.getString("name"))).let { true }
else -> throw IOException("Unsupported document operation: $operation")
}
}
}
@@ -0,0 +1,197 @@
package com.carriez.flutter_hbb
import android.content.Context
import android.net.Uri
import android.provider.DocumentsContract
import android.provider.DocumentsContract.Document
import android.webkit.MimeTypeMap
import org.json.JSONArray
import org.json.JSONObject
import java.io.FileNotFoundException
import java.io.IOException
import java.util.UUID
internal class DocumentTree(
context: Context,
private val grant: Uri,
private val descriptors: DocumentDescriptors
) {
private val root = documentRoot(grant)
private val resolver = context.contentResolver
private val rootUri: Uri get() = DocumentsContract.buildDocumentUriUsingTree(
grant, DocumentsContract.getTreeDocumentId(grant))
private val projection = arrayOf(Document.COLUMN_DOCUMENT_ID, Document.COLUMN_DISPLAY_NAME,
Document.COLUMN_MIME_TYPE, Document.COLUMN_SIZE, Document.COLUMN_LAST_MODIFIED)
fun rootName(): String = metadata(rootUri)?.getString("name")
?: throw FileNotFoundException("The selected document no longer exists")
private fun metadata(uri: Uri): JSONObject? = resolver.query(uri, projection, null, null, null)?.use {
if (!it.moveToFirst()) return@use null
val directory = it.getString(MIME_COLUMN) == Document.MIME_TYPE_DIR
val size = if (it.isNull(SIZE_COLUMN)) -1 else it.getLong(SIZE_COLUMN)
documentEntry(it.getString(NAME_COLUMN), directory, size)
.put("modified", it.getLong(MODIFIED_COLUMN) / MILLIS_PER_SECOND).put("uri", uri.toString())
} ?: throw IOException("Unable to query the selected document")
private fun children(uri: Uri): List<Pair<Uri, JSONObject>> {
val query = DocumentsContract.buildChildDocumentsUriUsingTree(
grant, DocumentsContract.getDocumentId(uri))
return resolver.query(query, projection, null, null, null)?.use { cursor ->
checkDocumentListing(cursor, "Unable to list the selected folder",
"The selected folder is still loading. Try again.")
val entries = mutableListOf<Pair<Uri, JSONObject>>()
while (cursor.moveToNext()) {
val child = DocumentsContract.buildDocumentUriUsingTree(grant, cursor.getString(ID_COLUMN))
val name = checkDocumentName(cursor.getString(NAME_COLUMN))
val entry = documentEntry(name, cursor.getString(MIME_COLUMN) == Document.MIME_TYPE_DIR,
if (cursor.isNull(SIZE_COLUMN)) -1 else cursor.getLong(SIZE_COLUMN))
.put("modified", cursor.getLong(MODIFIED_COLUMN) / MILLIS_PER_SECOND)
.put("uri", child.toString())
entries.add(child to entry)
}
entries
} ?: throw IOException("Unable to list the selected folder")
}
private fun relative(path: String): List<String> {
val parts = path.removePrefix("$root/").split('/')
require(path.startsWith("$root/") && parts.first() == rootName()) {
"The selected document was moved or renamed. Select it again."
}
parts.forEach(::checkDocumentName)
return parts.drop(1)
}
private fun resolve(path: String, createParents: Boolean = false): Uri? {
var current = rootUri
for (name in relative(path)) {
val matches = children(current).filter { it.second.getString("name") == name }
check(matches.size <= 1) { "The provider returned multiple documents named $name" }
val child = matches.singleOrNull()
current = child?.first ?: if (createParents) {
val created = DocumentsContract.createDocument(resolver, current, Document.MIME_TYPE_DIR, name)
?: throw IOException("Unable to create folder $name")
check(metadata(created)?.getString("name") == name) {
"The provider cannot preserve folder name: $name"
}
created
} else return null
}
return current
}
fun uri(path: String): Uri = resolve(path)
?: throw FileNotFoundException("Document does not exist: $path")
fun list(path: String): JSONArray = JSONArray(children(uri(path)).map { it.second })
fun stat(path: String): JSONObject? = resolve(path)?.let(::metadata)
fun open(path: String): JSONObject = descriptors.open(
resolver.openFileDescriptor(uri(path), "r") ?: throw IOException("Unable to open document"))
fun begin(path: String, overwrite: Boolean): JSONObject {
val original = resolve(path)
check(original == null || overwrite) { "Document overwrite requires confirmation" }
require(original == null || metadata(original)?.getBoolean("directory") == false) {
"Cannot replace a folder with a file"
}
val parent = resolve(path.substringBeforeLast('/'), true)
?: throw FileNotFoundException("Destination folder no longer exists")
val name = checkDocumentName(path.substringAfterLast('/'))
val temporary = DocumentsContract.createDocument(resolver, parent, mime(name),
temporaryName(name, "download"))
?: throw IOException("Unable to create the receiving file")
try {
val descriptor = resolver.openFileDescriptor(temporary, "rw")
?: throw IOException("Unable to open the receiving file")
return descriptors.open(descriptor).put("uri", temporary.toString())
.put("path", path).put("original", original?.toString() ?: JSONObject.NULL)
} catch (error: Exception) {
try {
check(DocumentsContract.deleteDocument(resolver, temporary)) {
"Unable to remove the receiving file"
}
} catch (cleanup: Exception) {
error.addSuppressed(cleanup)
throw IOException("${error.message ?: error.javaClass.simpleName}; " +
"temporary file cleanup failed: ${cleanup.message}", error)
}
throw error
}
}
fun finish(token: JSONObject) {
val path = token.getString("path")
val name = checkDocumentName(path.substringAfterLast('/'))
val original = resolve(path)
val expected = if (token.isNull("original")) null else token.getString("original")
check(original?.toString() == expected) {
"The destination changed during the transfer; the received data was retained"
}
val backup = original?.let { renameChecked(it, temporaryName(name, "backup")) }
try {
renameChecked(Uri.parse(token.getString("uri")), name)
} catch (error: Exception) {
if (backup != null) {
try { renameChecked(backup, name) } catch (restore: Exception) {
error.addSuppressed(restore)
throw IOException("Publishing failed and the original remains in $backup: ${restore.message}", error)
}
}
throw error
}
if (backup != null && !DocumentsContract.deleteDocument(resolver, backup)) {
throw IOException("File saved, but the previous copy could not be removed: $backup")
}
}
private fun renameChecked(uri: Uri, name: String): Uri {
val renamed = DocumentsContract.renameDocument(resolver, uri, name)
?: throw IOException("Unable to publish the received file; the partial file was retained")
check(metadata(renamed)?.getString("name") == name) { "The provider changed the saved filename" }
return renamed
}
fun discard(token: JSONObject) {
check(DocumentsContract.deleteDocument(resolver, Uri.parse(token.getString("uri")))) {
"Unable to remove the canceled transfer"
}
}
fun delete(path: String) {
require(relative(path).isNotEmpty()) { "Cannot delete a shared root" }
check(DocumentsContract.deleteDocument(resolver, uri(path))) { "Unable to delete document" }
}
fun mkdir(path: String) {
val created = resolve(path, true) ?: throw IOException("Unable to create folder")
check(metadata(created)?.getBoolean("directory") == true) { "The destination is not a folder" }
}
fun rename(path: String, name: String) {
require(relative(path).isNotEmpty()) { "Cannot rename a shared root" }
if (resolve(path.substringBeforeLast('/') + "/" + name) != null) throw IOException(EXISTS_MESSAGE)
renameChecked(uri(path), name)
}
companion object {
private const val ID_COLUMN = 0
private const val NAME_COLUMN = 1
private const val MIME_COLUMN = 2
private const val SIZE_COLUMN = 3
private const val MODIFIED_COLUMN = 4
private const val MILLIS_PER_SECOND = 1000L
const val EXISTS_MESSAGE = "A file already exists at the destination. Rename the file or select another folder."
fun temporaryName(name: String, purpose: String): String {
// Providers can append the MIME extension when renaming; preserve it for temporary files.
val extension = name.substringAfterLast('.', "").let { if (it.isEmpty()) "" else ".$it" }
return ".rustdesk-${UUID.randomUUID()}.$purpose$extension"
}
fun mime(name: String): String = MimeTypeMap.getSingleton()
.getMimeTypeFromExtension(name.substringAfterLast('.', "").lowercase())
?: "application/octet-stream"
}
}
@@ -50,6 +50,15 @@ const val WHEEL_BUTTON_UP = 34
const val WHEEL_DOWN = 523331
const val WHEEL_UP = 963
// src/common.rs MOUSE_TYPE_WHEEL: the controller sends a wheel tick as a
// MouseEvent with these type bits and the scroll delta in y (y < 0 = down).
const val MOUSE_TYPE_WHEEL = 3
// Wheel-tick travel for MOUSE_TYPE_WHEEL events. Three quarters of the legacy
// WHEEL_STEP; tuned on real devices during review (the full 120px felt too
// far per tick).
const val MOUSE_WHEEL_STEP = 90
const val TOUCH_SCALE_START = 1
const val TOUCH_SCALE = 2
const val TOUCH_SCALE_END = 3
@@ -102,6 +111,12 @@ class InputService : AccessibilityService() {
private val volumeController: VolumeController by lazy { VolumeController(applicationContext.getSystemService(AUDIO_SERVICE) as AudioManager) }
/**
* Handles a remote mouse event on the gesture path. [mask] is the
* button/phase mask of the mouse protocol ([MOUSE_TYPE_WHEEL] ticks carry
* the scroll delta in [_y] instead of a position), x/y the screen-space
* position. Requires API 24 for the gesture APIs.
*/
@RequiresApi(Build.VERSION_CODES.N)
fun onMouseInput(mask: Int, _x: Int, _y: Int) {
val x = max(0, _x)
@@ -184,6 +199,38 @@ class InputService : AccessibilityService() {
return
}
// The controller sends a wheel tick as a MouseEvent with the type bits
// MOUSE_TYPE_WHEEL (src/common.rs) and the scroll delta in _y
// (y < 0 = wheel down); the WHEEL_DOWN/WHEEL_UP masks below are legacy
// values that current controllers never send. Gated to API 24+ like
// the rest of the gesture path - below that, legacy devices take the
// Shizuku backend or a no-op, not this class.
if (mask == MOUSE_TYPE_WHEEL && Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
// A horizontal tick (the controller sends y = 0 when the
// horizontal delta dominates) or a delta truncated to zero is not
// a vertical swipe.
if (_y == 0) {
return
}
if (mouseY < MOUSE_WHEEL_STEP) {
return
}
val path = Path()
path.moveTo(mouseX.toFloat(), mouseY.toFloat())
val deltaY = if (_y < 0) -MOUSE_WHEEL_STEP else MOUSE_WHEEL_STEP
path.lineTo(mouseX.toFloat(), (mouseY + deltaY).toFloat())
val stroke = GestureDescription.StrokeDescription(
path,
0,
WHEEL_DURATION
)
val builder = GestureDescription.Builder()
builder.addStroke(stroke)
wheelActionsQueue.offer(builder.build())
consumeWheelActions()
return
}
if (mask == WHEEL_DOWN) {
if (mouseY < WHEEL_STEP) {
return
@@ -63,7 +63,8 @@ class MainActivity : FlutterActivity() {
data class ExportFiles(
val sources: List<File>,
val rejected: Int,
val result: MethodChannel.Result
val result: MethodChannel.Result,
val documentLogs: Boolean = false
) : PendingPicker()
}
@@ -73,6 +74,7 @@ class MainActivity : FlutterActivity() {
)
private var pendingPicker: PendingPicker? = null
private val documentPicker by lazy { DocumentPicker(this) }
private var isAudioStart = false
private val audioRecordHandle = AudioRecordHandle(this, { false }, { isAudioStart })
@@ -127,6 +129,7 @@ class MainActivity : FlutterActivity() {
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (documentPicker.onResult(requestCode, resultCode, data)) return
if (requestCode == REQ_IMPORT_FILES) {
val pending = pendingPicker as? PendingPicker.ImportFiles ?: return
pendingPicker = null
@@ -223,6 +226,14 @@ class MainActivity : FlutterActivity() {
Log.e(logTag, "Failed to export selected files", e)
failed += pending.sources.size - processed
}
if (pending.documentLogs) {
try {
exported += (application as MainApplication).documentStorage.logs.exportTo(treeUri)
} catch (error: Exception) {
Log.e(logTag, "Failed to export document logs", error)
failed++
}
}
runOnUiThread {
pending.result.success(mapOf("exported" to exported, "failed" to failed))
}
@@ -243,6 +254,7 @@ class MainActivity : FlutterActivity() {
}
override fun onDestroy() {
documentPicker.close()
Log.e(logTag, "onDestroy")
// The process can outlive the UI whenever something keeps it alive:
// MainService, or the accessibility InputService on its own. Only the
@@ -275,6 +287,7 @@ class MainActivity : FlutterActivity() {
private fun initFlutterChannel(flutterMethodChannel: MethodChannel) {
flutterMethodChannel.setMethodCallHandler { call, result ->
if (documentPicker.handle(call, result)) return@setMethodCallHandler
// make sure result will be invoked, otherwise flutter will await forever
when (call.method) {
"init_service" -> {
@@ -614,19 +627,22 @@ class MainActivity : FlutterActivity() {
}
EXPORT_FILES -> {
val paths = (call.arguments as? Map<*, *>)?.get("paths") as? List<*>
if (paths.isNullOrEmpty()) {
val documentLogs = (call.arguments as? Map<*, *>)?.get("documentLogs") == true
if (paths == null || (paths.isEmpty() && !documentLogs)) {
result.error("invalid_source", "The selected files are outside app-scoped storage", null)
} else {
val sources = paths.mapNotNull {
(it as? String)?.let(::canonicalExportSource)
}
val rejected = paths.size - sources.size
if (sources.isEmpty()) {
if (sources.isEmpty() && (!documentLogs ||
!(application as MainApplication).documentStorage.logs.hasPermission())) {
result.success(mapOf("exported" to 0, "failed" to rejected))
} else if (pendingPicker != null) {
result.error("picker_in_progress", "Another document picker is already open", null)
} else {
pendingPicker = PendingPicker.ExportFiles(sources, rejected, result)
pendingPicker = PendingPicker.ExportFiles(
sources, rejected, result, documentLogs = documentLogs)
try {
startActivityForResult(
Intent(Intent.ACTION_OPEN_DOCUMENT_TREE).apply {
@@ -5,6 +5,11 @@ import android.util.Log
import ffi.FFI
class MainApplication : Application() {
internal val documentStorage by lazy { DocumentStorage(this) }
@androidx.annotation.Keep
fun rustDocumentStorage(request: String): String = documentStorage.request(request)
companion object {
private const val TAG = "MainApplication"
}
+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 --enforce-lockfile
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 \
+7
View File
@@ -1,5 +1,6 @@
import UIKit
import Flutter
import AVFoundation
@main
@objc class AppDelegate: FlutterAppDelegate {
@@ -8,6 +9,12 @@ import Flutter
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
GeneratedPluginRegistrant.register(with: self)
do {
// Mix remote audio with other apps while still respecting silent mode.
try AVAudioSession.sharedInstance().setCategory(.ambient)
} catch {
NSLog("Failed to configure audio mixing: %@", error.localizedDescription)
}
dummyMethodToEnforceBundling();
return super.application(application, didFinishLaunchingWithOptions: launchOptions)
}
@@ -0,0 +1,72 @@
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter_hbb/models/platform_model.dart';
String _resolveApiServer({required String api, required String custom}) {
final key = 'resolve-api-server:${jsonEncode([api, custom])}';
final response = jsonDecode(bind.mainGetCommonSync(key: key));
if (response['error'] != null) {
throw FormatException('Failed to resolve API server: ${response['error']}');
}
return response['url'] as String;
}
bool shouldWarnApiServer(String? apiServer) {
final uri = Uri.tryParse(apiServer?.trim() ?? '');
if (uri == null || uri.host.isEmpty || uri.scheme != 'http') {
return false;
}
return !const {'localhost', '127.0.0.1', '::1'}.contains(uri.host);
}
class ApiServerWarning extends StatelessWidget {
final TextEditingController controller;
final TextEditingController idController;
final String message;
final String emptyMessage;
final String Function({required String api, required String custom})
resolveApiServer;
const ApiServerWarning({
super.key,
required this.controller,
required this.idController,
required this.message,
required this.emptyMessage,
this.resolveApiServer = _resolveApiServer,
});
@override
Widget build(BuildContext context) {
return ListenableBuilder(
listenable: Listenable.merge([controller, idController]),
builder: (context, child) {
final apiServer = controller.text;
final idServer = idController.text;
final String effectiveApiServer;
try {
effectiveApiServer =
resolveApiServer(api: apiServer.trim(), custom: idServer.trim());
} catch (error, stack) {
FlutterError.reportError(FlutterErrorDetails(
exception: error,
stack: stack,
context: ErrorDescription('while resolving the API server warning'),
));
return const SizedBox.shrink();
}
if (!shouldWarnApiServer(effectiveApiServer)) {
return const SizedBox.shrink();
}
return Align(
alignment: AlignmentDirectional.centerStart,
child: Text(
controller.text.trim().isEmpty ? emptyMessage : message,
style: TextStyle(color: Colors.orange.shade700),
),
);
},
);
}
}
@@ -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 {
+110 -38
View File
@@ -2278,9 +2278,12 @@ void changeBot({Function()? callback}) async {
void change2fa({Function()? callback}) async {
if (bind.mainHasValid2FaSync()) {
await bind.mainSetOption(key: "2fa", value: "");
await bind.mainClearTrustedDevices();
callback?.call();
try {
await bind.mainSetOption(key: "2fa", value: "");
callback?.call();
} catch (error) {
showToast(error.toString());
}
return;
}
var new2fa = (await bind.mainGenerate2Fa());
@@ -2795,23 +2798,48 @@ void confrimDeleteTrustedDevicesDialog(
CommonConfirmDialog(gFFI.dialogManager, '${translate('Confirm Delete')}?',
() async {
if (selectedDevices.isEmpty) return;
if (selectedDevices.length == trustedDevices.length) {
await bind.mainClearTrustedDevices();
trustedDevices.clear();
selectedDevices.clear();
} else {
final json = jsonEncode(selectedDevices.map((e) => e.toList()).toList());
await bind.mainRemoveTrustedDevices(json: json);
trustedDevices.removeWhere((element) {
return selectedDevices.contains(element.hwid);
});
selectedDevices.clear();
try {
if (selectedDevices.length == trustedDevices.length) {
await bind.mainClearTrustedDevices();
trustedDevices.clear();
selectedDevices.clear();
} else {
final json = jsonEncode(selectedDevices.map((e) => e.toList()).toList());
await bind.mainRemoveTrustedDevices(json: json);
trustedDevices.removeWhere((element) {
return selectedDevices.contains(element.recordId);
});
selectedDevices.clear();
}
} catch (error) {
showToast(error.toString());
}
});
}
Future<void> renewTrustedDevice(
TrustedDevice device,
RxList<TrustedDevice> trustedDevices,
RxList<Uint8List> selectedDevices) async {
try {
final json = jsonEncode([device.recordId.toList()]);
await bind.mainRenewTrustedDevices(json: json);
final result = await TrustedDevice.get();
selectedDevices.clear();
trustedDevices.assignAll(result);
} catch (error) {
showToast(error.toString());
}
}
void manageTrustedDeviceDialog() async {
RxList<TrustedDevice> trustedDevices = (await TrustedDevice.get()).obs;
late final RxList<TrustedDevice> trustedDevices;
try {
trustedDevices = (await TrustedDevice.get()).obs;
} catch (error) {
showToast(error.toString());
return;
}
RxList<Uint8List> selectedDevices = RxList.empty();
gFFI.dialogManager.show((setState, close, context) {
return CustomAlertDialog(
@@ -2837,25 +2865,67 @@ void manageTrustedDeviceDialog() async {
});
}
Widget trustedDeviceExpiration({
required bool enabled,
required VoidCallback onChanged,
bool showLabel = true,
}) {
final period = bind.mainGetOptionSync(key: kOptionTrustedDeviceExpiration);
const periods = ['1', '7', '30', '90', '0'];
const dropdownHeight = 36.0;
return Align(
alignment: AlignmentDirectional.centerStart,
child: Wrap(
spacing: 12,
runSpacing: 8,
crossAxisAlignment: WrapCrossAlignment.center,
children: [
if (showLabel) Text(translate('Trust duration (days)')),
SizedBox(
width: isDesktop || isWebDesktop ? 140 : 100,
height: dropdownHeight,
child: ComboBox(
keys: periods,
values: ['1', '7', '30', '90', translate('Never')],
initialKey: periods.contains(period) ? period : '90',
enabled: enabled && !isOptionFixed(kOptionTrustedDeviceExpiration),
onChanged: (value) async {
try {
await bind.mainSetOption(
key: kOptionTrustedDeviceExpiration, value: value);
} catch (error) {
showToast(error.toString());
}
onChanged();
},
),
),
],
),
);
}
class TrustedDevice {
late final Uint8List hwid;
late final Uint8List recordId;
late final int time;
late final int expiresAt;
late final String id;
late final String name;
late final String platform;
TrustedDevice.fromJson(Map<String, dynamic> json) {
final hwidList = json['hwid'] as List<dynamic>;
hwid = Uint8List.fromList(hwidList.cast<int>());
final recordIdList = json['record_id'] as List<dynamic>;
recordId = Uint8List.fromList(recordIdList.cast<int>());
time = json['time'];
expiresAt = json['expires_at'];
id = json['id'];
name = json['name'];
platform = json['platform'];
}
String daysRemaining() {
final expiry = time + 90 * 24 * 60 * 60 * 1000;
final remaining = expiry - DateTime.now().millisecondsSinceEpoch;
if (expiresAt == 0) return translate('Never');
final remaining = expiresAt - DateTime.now().millisecondsSinceEpoch;
if (remaining < 0) {
return '0';
}
@@ -2864,18 +2934,11 @@ class TrustedDevice {
static Future<List<TrustedDevice>> get() async {
final List<TrustedDevice> devices = List.empty(growable: true);
try {
final devicesJson = await bind.mainGetTrustedDevices();
if (devicesJson.isNotEmpty) {
final devicesList = json.decode(devicesJson);
if (devicesList is List) {
for (var device in devicesList) {
devices.add(TrustedDevice.fromJson(device));
}
}
}
} catch (e) {
print(e.toString());
final devicesJson = await bind.mainGetTrustedDevices();
final result = json.decode(devicesJson) as Map<String, dynamic>;
final devicesList = result['devices'] as List;
for (final device in devicesList) {
devices.add(TrustedDevice.fromJson(device));
}
devices.sort((a, b) => b.time.compareTo(a.time));
return devices;
@@ -2909,7 +2972,7 @@ Widget trustedDevicesTable(
onChanged: (value) {
if (value == true) {
selectedDevices.clear();
selectedDevices.addAll(devices.map((e) => e.hwid));
selectedDevices.addAll(devices.map((e) => e.recordId));
} else {
selectedDevices.clear();
}
@@ -2923,21 +2986,30 @@ Widget trustedDevicesTable(
rows: devices.map((device) {
return DataRow(cells: [
DataCell(Checkbox(
value: selectedDevices.contains(device.hwid),
value: selectedDevices.contains(device.recordId),
onChanged: (value) {
if (value == null) return;
if (value) {
selectedDevices.remove(device.hwid);
selectedDevices.add(device.hwid);
selectedDevices.remove(device.recordId);
selectedDevices.add(device.recordId);
} else {
selectedDevices.remove(device.hwid);
selectedDevices.remove(device.recordId);
}
},
)),
DataCell(Text(device.platform)),
DataCell(Text(device.id)),
DataCell(Text(device.name)),
DataCell(Text(device.daysRemaining())),
DataCell(Row(mainAxisSize: MainAxisSize.min, children: [
Text(device.daysRemaining()),
if (device.expiresAt != 0)
IconButton(
icon: Icon(Icons.refresh),
tooltip: translate('Renew trust'),
onPressed: () =>
renewTrustedDevice(device, devices, selectedDevices),
),
])),
]);
}).toList(),
)),
+55 -7
View File
@@ -1,4 +1,5 @@
import 'package:bot_toast/bot_toast.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_hbb/common/widgets/dialog.dart';
@@ -62,6 +63,8 @@ class _PeerCardState extends State<_PeerCard>
final PeerTabModel peerTabModel = Provider.of(context);
final peer = super.widget.peer;
return GestureDetector(
// Web card actions have their own semantics; preserve pointer double-clicks.
excludeFromSemantics: isWebDesktop,
onDoubleTap: peerTabModel.multiSelectionMode
? null
: () => widget.connect(context, peer.id),
@@ -423,7 +426,7 @@ class _PeerCardState extends State<_PeerCard>
final PeerTabModel peerTabModel = Provider.of(context);
final selected = peerTabModel.isPeerSelected(peer.id);
if (peerTabModel.multiSelectionMode) {
return Padding(
final checkbox = Padding(
padding: const EdgeInsets.all(12),
child: selected
? Icon(
@@ -432,7 +435,16 @@ class _PeerCardState extends State<_PeerCard>
)
: Icon(Icons.check_box_outline_blank),
);
return isWebDesktop
? Semantics(
container: true,
label: formatID(peer.id),
checked: selected,
onTap: () => peerTabModel.select(peer),
child: checkbox)
: checkbox;
} else {
if (isWebDesktop) return _actionMoreWeb(peer);
return InkWell(
child: const Padding(
padding: EdgeInsets.all(12), child: Icon(Icons.more_vert)),
@@ -457,19 +469,27 @@ class _PeerCardState extends State<_PeerCard>
color: MyTheme.accent,
)
: Icon(Icons.check_box_outline_blank);
final checkbox = isWebDesktop
? Semantics(
container: true,
label: formatID(peer.id),
checked: selected,
onTap: () => peerTabModel.select(peer),
child: icon)
: icon;
bool last = peerTabModel.isShiftDown && peer.id == peerTabModel.lastId;
double right = isTile ? 4 : 0;
if (last) {
return Container(
decoration: BoxDecoration(
border: Border.all(color: MyTheme.accent, width: 1)),
child: icon,
child: checkbox,
).marginOnly(right: right);
} else {
return icon.marginOnly(right: right);
return checkbox.marginOnly(right: right);
}
} else {
return _actionMore(peer);
return isWebDesktop ? _actionMoreWeb(peer) : _actionMore(peer);
}
}
@@ -482,6 +502,20 @@ class _PeerCardState extends State<_PeerCard>
onPointerUp: (_) => _showPeerMenu(peer.id),
child: build_more(context));
Widget _actionMoreWeb(Peer peer) => Semantics(
container: true,
button: true,
label: translate('More'),
child: Builder(
builder: (context) => build_more(context, onTap: () {
final box = context.findRenderObject() as RenderBox;
final position =
box.localToGlobal(box.size.center(Offset.zero));
_menuPos = RelativeRect.fromLTRB(
position.dx, position.dy, position.dx, position.dy);
_showPeerMenu(peer.id);
})));
bool _shouldBuildPasswordIcon(Peer peer) {
if (gFFI.peerTabModel.currentTab != PeerTabIndex.ab.index) return false;
if (gFFI.abModel.current.isPersonal()) return false;
@@ -1474,11 +1508,12 @@ Widget getOnline(double rightPadding, bool online) {
radius: 3, backgroundColor: online ? Colors.green : kColorWarn)));
}
Widget build_more(BuildContext context, {bool invert = false}) {
Widget build_more(BuildContext context,
{bool invert = false, VoidCallback? onTap}) {
final RxBool hover = false.obs;
return InkWell(
final button = InkWell(
borderRadius: BorderRadius.circular(14),
onTap: () {},
onTap: onTap ?? () {},
onHover: (value) => hover.value = value,
child: Obx(() => CircleAvatar(
radius: 14,
@@ -1498,6 +1533,19 @@ Widget build_more(BuildContext context, {bool invert = false}) {
.titleLarge
?.color
?.withOpacity(0.5)))));
if (onTap == null) return button;
// Serial taps preserve cancellation without waiting for the card's double tap.
return RawGestureDetector(
excludeFromSemantics: true,
gestures: {
SerialTapGestureRecognizer:
GestureRecognizerFactoryWithHandlers<SerialTapGestureRecognizer>(
() => SerialTapGestureRecognizer(
allowedButtonsFilter: (buttons) =>
buttons == kPrimaryButton),
(recognizer) => recognizer.onSerialTapUp = (_) => onTap()),
},
child: button);
}
class TagPainter extends CustomPainter {
@@ -21,6 +21,7 @@ import 'package:flutter_svg/flutter_svg.dart';
import 'package:get/get.dart';
import 'package:provider/provider.dart';
import 'package:pull_down_button/pull_down_button.dart';
import 'package:url_launcher/url_launcher_string.dart';
import '../../common.dart';
import '../../models/platform_model.dart';
@@ -549,6 +550,28 @@ class _PeerTabPageState extends State<PeerTabPage>
});
}
Widget _openWebConsole() {
return _hoverAction(
context: context,
toolTip: translate('ab_web_console_tip'),
child: Icon(
Icons.open_in_new,
size: 18,
),
onTap: () async {
final url = await bind.mainGetApiServer();
if (await canLaunchUrlString(url)) {
launchUrlString(url);
}
});
}
bool _showWebConsole(PeerTabModel model) =>
model.currentTab == PeerTabIndex.ab.index &&
gFFI.userModel.isLogin &&
!gFFI.abModel.legacyMode.value &&
gFFI.abModel.current.canWrite();
List<Widget> _landscapeRightActions(BuildContext context) {
final model = Provider.of<PeerTabModel>(context);
return [
@@ -566,6 +589,10 @@ class _PeerTabPageState extends State<PeerTabPage>
offstage: model.currentTab == PeerTabIndex.recent.index,
child: PeerSortDropdown(),
),
Offstage(
offstage: !_showWebConsole(model),
child: _openWebConsole(),
),
Offstage(
offstage: model.currentTab != PeerTabIndex.ab.index,
child: _toggleTags(),
@@ -630,6 +657,7 @@ class _PeerTabPageState extends State<PeerTabPage>
final List<Widget> dynamicActions = [
if (model.currentTabCachedPeers.isNotEmpty) _createMultiSelection(),
if (model.currentTab != PeerTabIndex.recent.index) PeerSortDropdown(),
if (_showWebConsole(model)) _openWebConsole(),
if (model.currentTab == PeerTabIndex.ab.index) _toggleTags()
];
final rightWidth = availableWidth -
+1
View File
@@ -184,6 +184,7 @@ const String kOptionAllowSyncClipboardBetweenSessions =
const String kOptionEnableWebrtc = "enable-webrtc";
const String kOptionRelayFallbackDelay = "relay-fallback-delay";
const String kOptionEnableTrustedDevices = "enable-trusted-devices";
const String kOptionTrustedDeviceExpiration = "trusted-device-expiration-days";
const String kOptionShowVirtualMouse = "show-virtual-mouse";
const String kOptionVirtualMouseScale = "virtual-mouse-scale";
const String kOptionShowVirtualJoystick = "show-virtual-joystick";
@@ -1144,6 +1144,13 @@ class _SafetyState extends State<_Safety> with AutomaticKeepAliveClientMixin {
message: translate("enable-trusted-devices-tip"),
child: _OptionCheckBox(context, "Enable trusted devices",
kOptionEnableTrustedDevices,
optSetter: (key, value) async {
try {
await mainSetBoolOption(key, value);
} catch (error) {
showToast(error.toString());
}
},
enabled: !locked, update: (v) {
setState(() {});
}),
@@ -1161,7 +1168,21 @@ class _SafetyState extends State<_Safety> with AutomaticKeepAliveClientMixin {
).marginOnly(left: 30);
return Column(
children: [tfa, bot, trust],
children: [
tfa,
bot,
trust,
if (mainGetBoolOptionSync(kOptionEnableTrustedDevices))
trustedDeviceExpiration(
enabled: !locked,
onChanged: () {
if (mounted) setState(() {});
},
).marginOnly(
left: _kCheckBoxLeftMargin + 20 + _kContentHSubMargin,
top: _kContentHMargin,
),
],
);
}
@@ -497,7 +497,12 @@ class _FileManagerViewState extends State<FileManagerView> {
},
onExit: (evt) =>
widget._mouseFocusScope.value = MouseFocusScope.none,
child: _buildFileList(context, _fileListScrollController),
child: Focus(
canRequestFocus: false,
skipTraversal: true,
onKeyEvent: _onFileListKeyEvent,
child: _buildFileList(context, _fileListScrollController),
),
))
],
),
@@ -1135,6 +1140,7 @@ class _FileManagerViewState extends State<FileManagerView> {
: "${entry.lastModified().toString().replaceAll(".000", "")} ";
var secondaryPosition = RelativeRect.fromLTRB(0, 0, 0, 0);
onTap() {
_keyboardNode.requestFocus();
final items = selectedItems;
// handle double click
if (_checkDoubleClick(entry)) {
@@ -1363,6 +1369,102 @@ class _FileManagerViewState extends State<FileManagerView> {
debugPrint("focused on ${searchResult.first.name}");
}
KeyEventResult _onFileListKeyEvent(FocusNode node, KeyEvent event) {
// A focused child such as a sort header keeps its default keys, e.g.
// Enter to sort.
if (!_keyboardNode.hasPrimaryFocus) return KeyEventResult.ignored;
for (final binding in _fileListKeyBindings().entries) {
if (binding.key.accepts(event, HardwareKeyboard.instance)) {
binding.value();
return KeyEventResult.handled;
}
}
return KeyEventResult.ignored;
}
Map<ShortcutActivator, VoidCallback> _fileListKeyBindings() {
int all() => controller.directory.value.entries.length;
return {
const SingleActivator(LogicalKeyboardKey.arrowUp): () =>
_moveSelectionByKey(-1, false),
const SingleActivator(LogicalKeyboardKey.arrowDown): () =>
_moveSelectionByKey(1, false),
const SingleActivator(LogicalKeyboardKey.arrowUp, shift: true): () =>
_moveSelectionByKey(-1, true),
const SingleActivator(LogicalKeyboardKey.arrowDown, shift: true): () =>
_moveSelectionByKey(1, true),
// Unhandled, they would move keyboard focus to the other pane.
const SingleActivator(LogicalKeyboardKey.arrowLeft): () {},
const SingleActivator(LogicalKeyboardKey.arrowRight): () {},
const SingleActivator(LogicalKeyboardKey.pageUp): () =>
_moveSelectionByKey(_pageDelta(false), false),
const SingleActivator(LogicalKeyboardKey.pageDown): () =>
_moveSelectionByKey(_pageDelta(true), false),
const SingleActivator(LogicalKeyboardKey.home): () =>
_moveSelectionByKey(-all(), false),
const SingleActivator(LogicalKeyboardKey.end): () =>
_moveSelectionByKey(all(), false),
const SingleActivator(LogicalKeyboardKey.pageUp, shift: true): () =>
_moveSelectionByKey(_pageDelta(false), true),
const SingleActivator(LogicalKeyboardKey.pageDown, shift: true): () =>
_moveSelectionByKey(_pageDelta(true), true),
const SingleActivator(LogicalKeyboardKey.home, shift: true): () =>
_moveSelectionByKey(-all(), true),
const SingleActivator(LogicalKeyboardKey.end, shift: true): () =>
_moveSelectionByKey(all(), true),
const SingleActivator(LogicalKeyboardKey.enter): _openSelectedDirectory,
const SingleActivator(LogicalKeyboardKey.numpadEnter):
_openSelectedDirectory,
};
}
void _openSelectedDirectory() {
final items = selectedItems.items;
if (items.length != 1 || items.first.isFile) return;
controller.openDirectory(items.first.path);
selectedItems.clear();
}
List<Entry> _filteredEntries() {
final entries = controller.directory.value.entries;
return _searchText.isNotEmpty
? entries.where((element) {
return element.name.contains(_searchText.value);
}).toList(growable: false)
: entries;
}
int _pageDelta(bool down) {
final entries = _filteredEntries();
final items = selectedItems.items;
final index = items.isEmpty ? -1 : entries.indexOf(items.last);
final position = _fileListScrollController.position;
final first = (position.pixels / kDesktopFileTransferRowHeight).ceil();
final last = ((position.pixels + position.viewportDimension) /
kDesktopFileTransferRowHeight)
.floor() -
1;
return pageDelta(
index >= 0 ? index : (down ? -1 : entries.length), first, last, down);
}
void _moveSelectionByKey(int delta, bool extend) {
final filteredEntries = _filteredEntries();
final selection =
navigateSelection(filteredEntries, selectedItems.items, delta, extend);
if (selection.isEmpty) return;
selectedItems.items.assignAll(selection.where((e) => !e.isDrive));
final position = _fileListScrollController.position;
final top =
filteredEntries.indexOf(selection.last) * kDesktopFileTransferRowHeight;
final bottom = top + kDesktopFileTransferRowHeight;
if (top < position.pixels) {
_fileListScrollController.jumpTo(top);
} else if (bottom > position.pixels + position.viewportDimension) {
_fileListScrollController.jumpTo(bottom - position.viewportDimension);
}
}
void _onSelectedChanged(SelectedItems selectedItems, List<Entry> entries,
Entry entry, bool isLocal) {
final isCtrlDown = RawKeyboard.instance.keysPressed
@@ -1717,6 +1819,36 @@ class _FileManagerViewState extends State<FileManagerView> {
// }
}
/// Selection after a navigation key moves it by [delta] rows. A shift range is
/// returned ordered from its anchor to the moved end, so the first and last
/// items of [selected] stand for those two ends on the next press without
/// separate state.
@visibleForTesting
List<Entry> navigateSelection(
List<Entry> entries, List<Entry> selected, int delta, bool extend) {
if (entries.isEmpty) return [];
final current = selected.isEmpty ? -1 : entries.indexOf(selected.last);
// With nothing selected, moving down starts above the first row and moving
// up below the last one, as the Sciter grid did.
final lead = current >= 0 ? current : (delta > 0 ? -1 : entries.length);
final next = (lead + delta).clamp(0, entries.length - 1);
if (!extend || current < 0) return [entries[next]];
final first = entries.indexOf(selected.first);
final anchor = first < 0 ? current : first;
final step = next < anchor ? -1 : 1;
return [for (var i = anchor; i != next + step; i += step) entries[i]];
}
/// Rows a PageUp/PageDown press moves from [lead] while rows [first]..[last]
/// are fully visible: to that edge first, then a page further, as list views
/// do.
@visibleForTesting
int pageDelta(int lead, int first, int last, bool down) {
final page = max(1, last - first);
if (down) return lead < last ? last - lead : page;
return lead > first ? first - lead : -page;
}
Widget buildWindowsThisPC(BuildContext context, [TextStyle? textStyle]) {
final color = Theme.of(context).iconTheme.color?.withOpacity(0.7);
return Row(children: [
@@ -1,4 +1,5 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
class ListSearchActionListener extends StatelessWidget {
final FocusNode node;
@@ -22,7 +23,7 @@ class ListSearchActionListener extends StatelessWidget {
autofocus: true,
onKeyEvent: (kv) {
final ch = kv.character;
if (ch == null) {
if (ch == null || LogicalKeyboardKey.isControlCharacter(ch)) {
return;
}
final action = buffer.input(ch);
@@ -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);
+2
View File
@@ -577,6 +577,8 @@ _registerEventHandler() {
Widget keyListenerBuilder(BuildContext context, Widget? child) {
return RawKeyboardListener(
// Keep this keyboard-only wrapper from taking focus away from web inputs.
includeSemantics: !isWeb,
// `skipTraversal: isWeb` is to fix "Bad state: RenderBox was not laid out: minified:aeL#c19e4"
focusNode: FocusNode(skipTraversal: isWeb),
child: child ?? Container(),
+74 -17
View File
@@ -10,6 +10,7 @@ import 'package:toggle_switch/toggle_switch.dart';
import '../../common.dart';
import '../../common/widgets/dialog.dart';
import '../../consts.dart';
import '../../utils/android_documents.dart';
class FileManagerPage extends StatefulWidget {
FileManagerPage(
@@ -142,6 +143,29 @@ class _FileManagerPageState extends State<FileManagerPage> {
}
}
Future<void> _changeLocalStorage({required bool workspace}) async {
try {
final path = workspace
? await AndroidDocuments.workspace()
: (await AndroidDocuments.selectFolder())?['path'] as String?;
if (path == null || !mounted) return;
final previousHome = model.localController.homePath;
model.localController.homePath = path;
try {
if (await model.localController.openDirectory(path, isBack: true)) {
model.localController.history.clear();
} else {
model.localController.homePath = previousHome;
}
} catch (_) {
model.localController.homePath = previousHome;
rethrow;
}
} catch (error) {
showToast(error.toString());
}
}
Future<void> _exportFile(Entry entry) async {
try {
final exported = await _runAndroidDocumentPicker(() => gFFI
@@ -206,9 +230,11 @@ class _FileManagerPageState extends State<FileManagerPage> {
}
Future<void> _exportLogs() async {
final home = currentFileController.homePath;
if (home.isEmpty) {
showToast(translate('Failed'));
final String home;
try {
home = await AndroidDocuments.workspace();
} catch (error) {
showToast(error.toString());
return;
}
final appDir = PathUtil.join(home, appName, false);
@@ -216,22 +242,25 @@ class _FileManagerPageState extends State<FileManagerPage> {
PathUtil.join(appDir, 'Logs', false),
PathUtil.join(appDir, 'ScreenRecord', false),
].where((p) => File(p).existsSync() || Directory(p).existsSync()).toList();
if (paths.isEmpty) {
showToast(translate('Failed'));
return;
}
await _exportPaths(paths);
await _exportPaths(paths, includeDocumentLogs: true);
}
Future<void> _exportPaths(Iterable<String> paths) async {
Future<void> _exportPaths(Iterable<String> paths,
{bool includeDocumentLogs = false}) async {
try {
final result = await _runAndroidDocumentPicker(() =>
gFFI.invokeMethodWithResult<Map<dynamic, dynamic>>(
AndroidChannel.kExportFiles, {'paths': paths.toList()}));
final result = await _runAndroidDocumentPicker(() => gFFI
.invokeMethodWithResult<Map<dynamic, dynamic>>(
AndroidChannel.kExportFiles, {
'paths': paths.toList(),
if (includeDocumentLogs) 'documentLogs': true,
}));
if (result == null) return;
final exported = result['exported'] as int? ?? 0;
final failed = result['failed'] as int? ?? 0;
if (failed > 0) {
if (includeDocumentLogs && exported > 0 && failed > 0) {
showToast('${translate('Successful')}: $exported, '
'${translate('Failed')}: $failed');
} else if (failed > 0 || (includeDocumentLogs && exported == 0)) {
showToast(translate('Failed'));
} else if (exported > 0) {
showToast(translate('Successful'));
@@ -317,6 +346,31 @@ class _FileManagerPageState extends State<FileManagerPage> {
icon: Icon(Icons.more_vert),
itemBuilder: (context) {
return [
if (isAndroid && showLocal) ...[
PopupMenuItem(
value: 'workspace',
child: Row(
children: [
Icon(Icons.storage_outlined,
color: Theme.of(context).iconTheme.color),
SizedBox(width: 5),
Text(translate('RustDesk storage')),
],
),
),
PopupMenuItem(
value: 'choose_folder',
child: Row(
children: [
Icon(Icons.folder_open_outlined,
color: Theme.of(context).iconTheme.color),
SizedBox(width: 5),
Text('${translate('Other folders')}…'),
],
),
),
const PopupMenuDivider(),
],
PopupMenuItem(
child: Row(
children: [
@@ -328,7 +382,7 @@ class _FileManagerPageState extends State<FileManagerPage> {
),
value: "refresh",
),
if (isAndroid)
if (isAndroid && !AndroidDocuments.isPath(currentDir.path))
PopupMenuItem(
enabled: showLocal && currentDir.path.isNotEmpty,
value: "import",
@@ -341,7 +395,7 @@ class _FileManagerPageState extends State<FileManagerPage> {
],
),
),
if (isAndroid)
if (isAndroid && !AndroidDocuments.isPath(currentDir.path))
PopupMenuItem(
enabled: showLocal && currentDir.path.isNotEmpty,
value: "import_folder",
@@ -409,7 +463,9 @@ class _FileManagerPageState extends State<FileManagerPage> {
];
},
onSelected: (v) {
if (v == "refresh") {
if (v == 'workspace' || v == 'choose_folder') {
_changeLocalStorage(workspace: v == 'workspace');
} else if (v == "refresh") {
currentFileController.refresh();
} else if (v == "import") {
_importFiles();
@@ -515,6 +571,7 @@ class _FileManagerPageState extends State<FileManagerPage> {
},
actions: [
if (isAndroid &&
!AndroidDocuments.isPath(currentDir.path) &&
selectedItems?.isLocal == true &&
selectedItems?.items.isNotEmpty == true) ...[
if (selectedItems!.items.length == 1 &&
@@ -900,7 +957,7 @@ class _FileManagerViewState extends State<FileManagerView> {
Padding(
padding: EdgeInsets.fromLTRB(30, 5, 30, 0),
child: Text(
controller.directory.value.path,
AndroidDocuments.displayPath(controller.directory.value.path),
style: TextStyle(color: MyTheme.darkGray),
),
),
+52
View File
@@ -13,6 +13,7 @@ import '../../common/widgets/dialog.dart';
import '../../consts.dart';
import '../../models/platform_model.dart';
import '../../models/server_model.dart';
import '../../utils/android_documents.dart';
import 'home_page.dart';
class ServerPage extends StatefulWidget implements PageShape {
@@ -573,6 +574,44 @@ class PermissionChecker extends StatefulWidget {
}
class _PermissionCheckerState extends State<PermissionChecker> {
static const _folderOptionIndent = 16.0;
Future<void> _selectFolder() async {
try {
final workspace = await gFFI.dialogManager.show<bool>(
(_, close, __) => CustomAlertDialog(
title: Text(translate('Change Path')),
content: Column(mainAxisSize: MainAxisSize.min, children: [
ListTile(
title: Text(translate('RustDesk storage')),
onTap: () => close(true),
),
ListTile(
title: Text('${translate('Other folders')}…'),
onTap: () => close(false),
),
]),
),
backDismiss: true,
clickMaskDismiss: true);
if (workspace == null) return;
if (workspace) {
showToast(await AndroidDocuments.workspace(share: true));
await bind.setLocalFlutterOption(
k: 'android-file-transfer-folder-setup', v: 'Y');
return;
}
final selected = await AndroidDocuments.selectFolder(share: true);
if (selected != null) {
await bind.setLocalFlutterOption(
k: 'android-file-transfer-folder-setup', v: 'Y');
showToast(AndroidDocuments.displayPath(selected['path'] as String));
}
} catch (error) {
showToast(error.toString());
}
}
@override
Widget build(BuildContext context) {
final serverModel = Provider.of<ServerModel>(context);
@@ -620,6 +659,19 @@ class _PermissionCheckerState extends State<PermissionChecker> {
serverModel.toggleFile,
enabled: !permissionChangeLocked,
),
if (isAndroid &&
!bind.isDisableSettings() &&
!bind.isOutgoingOnly() &&
bind.mainGetBuildinOption(key: kOptionHideSecuritySetting) != 'Y')
ListTile(
dense: true,
contentPadding:
const EdgeInsetsDirectional.only(start: _folderOptionIndent),
title: Text(translate('Change Path')),
trailing: const Icon(Icons.chevron_right),
enabled: !permissionChangeLocked,
onTap: _selectFolder,
),
hasAudioPermission
? PermissionRow(translate("Audio Capture"), serverModel.audioOk,
serverModel.toggleAudio,
+20 -4
View File
@@ -359,12 +359,28 @@ class _SettingsState extends State<SettingsPage> with WidgetsBindingObserver {
onToggle: isOptionFixed(kOptionEnableTrustedDevices)
? null
: (v) async {
mainSetBoolOption(kOptionEnableTrustedDevices, v);
setState(() {
_enableTrustedDevices = v;
});
try {
await mainSetBoolOption(kOptionEnableTrustedDevices, v);
if (!mounted) return;
setState(() {
_enableTrustedDevices = v;
});
} catch (error) {
showToast(error.toString());
}
},
),
if (enable2fa && _enableTrustedDevices)
SettingsTile(
title: Text(translate('Trust duration (days)')),
trailing: trustedDeviceExpiration(
enabled: true,
showLabel: false,
onChanged: () {
if (mounted) setState(() {});
},
),
),
if (enable2fa && _enableTrustedDevices)
SettingsTile(
title: Text(translate('Manage trusted devices')),
@@ -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;
}
@@ -0,0 +1,100 @@
import 'package:flutter/material.dart';
import '../../common.dart';
import '../../consts.dart';
import '../../models/model.dart';
import '../../models/platform_model.dart';
import '../../utils/android_documents.dart';
const _setupOption = 'android-file-transfer-folder-setup';
const _folderChoicePadding = EdgeInsets.fromLTRB(12, 12, 12, 0);
const _folderChoiceSpacing = 4.0;
enum _FolderChoice { workspace, other, skip }
Future<bool> showAndroidFileTransferSetup(FFI ffi) async {
if (bind.getLocalFlutterOption(k: _setupOption) == 'Y' ||
!_canConfigureSharedFolder(ffi)) {
return true;
}
try {
final choice = await ffi.dialogManager.show<_FolderChoice>(
(_, close, __) => _setupDialog(close),
backDismiss: true,
forceGlobal: true,
);
if (choice == null) return false;
switch (choice) {
case _FolderChoice.workspace:
await AndroidDocuments.workspace(share: true);
break;
case _FolderChoice.other:
if (await AndroidDocuments.selectFolder(share: true) == null) {
return false;
}
break;
case _FolderChoice.skip:
break;
}
await bind.setLocalFlutterOption(k: _setupOption, v: 'Y');
return true;
} catch (error) {
showToast(error.toString());
return false;
}
}
bool _canConfigureSharedFolder(FFI ffi) =>
!bind.isOutgoingOnly() &&
!bind.isDisableSettings() &&
bind.mainGetBuildinOption(key: kOptionHideSecuritySetting) != 'Y' &&
(!ffi.serverModel.clients.any((client) => !client.disconnected) ||
option2bool(
kOptionEnablePermChangeInAcceptWindow,
bind.mainGetBuildinOption(
key: kOptionEnablePermChangeInAcceptWindow)));
CustomAlertDialog _setupDialog(void Function([dynamic]) close) {
final choiceStyle = OutlinedButton.styleFrom(
alignment: AlignmentDirectional.centerStart,
minimumSize: const Size(0, kMinInteractiveDimension),
);
return CustomAlertDialog(
title: Text(translate('Transfer file')),
content: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(translate('Choose which folder remote devices can access.')),
Padding(
padding: _folderChoicePadding,
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
OutlinedButton(
style: choiceStyle,
onPressed: () => close(_FolderChoice.workspace),
child: Text(translate('RustDesk storage')),
),
const SizedBox(height: _folderChoiceSpacing),
OutlinedButton(
style: choiceStyle,
onPressed: () => close(_FolderChoice.other),
child: Text('${translate('Other folders')}…'),
),
],
),
),
],
),
actions: [
TextButton(
onPressed: () => close(_FolderChoice.skip),
child: Text(translate('Skip')),
),
],
onCancel: close,
);
}
+16 -2
View File
@@ -1,6 +1,7 @@
import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter_hbb/common/widgets/api_server_warning.dart';
import 'package:flutter_hbb/common/widgets/setting_widgets.dart';
import 'package:flutter_hbb/common/widgets/toolbar.dart';
import 'package:get/get.dart';
@@ -69,6 +70,8 @@ void showServerSettingsWithValue(
ServerConfig serverConfig,
OverlayDialogManager dialogManager,
void Function(VoidCallback)? upSetState) async {
const labelWidth = 120.0;
const labelSpacing = 8.0;
var isInProgress = false;
final idCtrl = TextEditingController(text: serverConfig.idServer);
final relayCtrl = TextEditingController(text: serverConfig.relayServer);
@@ -112,10 +115,10 @@ void showServerSettingsWithValue(
return Row(
children: [
SizedBox(
width: 120,
width: labelWidth,
child: Text(label),
),
SizedBox(width: 8),
SizedBox(width: labelSpacing),
Expanded(
child: serverSettingsTextFormField(
label: label,
@@ -175,6 +178,17 @@ void showServerSettingsWithValue(
return null;
},
),
Padding(
padding: EdgeInsetsDirectional.only(
start: isDesktop || isWeb ? labelWidth + labelSpacing : 0,
),
child: ApiServerWarning(
controller: apiCtrl,
idController: idCtrl,
message: translate('api_server_connection_tip'),
emptyMessage: translate('api_server_empty_tip'),
),
),
SizedBox(height: 8),
buildField('Key', keyCtrl, ''),
if (isInProgress)
+111 -8
View File
@@ -4,6 +4,7 @@ import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter_hbb/common.dart';
import 'package:flutter_hbb/common/widgets/dialog.dart';
import 'package:flutter_hbb/utils/download_paths.dart';
import 'package:flutter_hbb/utils/event_loop.dart';
import 'package:get/get.dart';
import 'package:path/path.dart' as path;
@@ -11,6 +12,7 @@ import 'package:flutter_hbb/web/dummy.dart'
if (dart.library.html) 'package:flutter_hbb/web/web_unique.dart';
import '../consts.dart';
import '../utils/android_documents.dart';
import 'model.dart';
import 'platform_model.dart';
@@ -383,6 +385,7 @@ class FileController {
bool _isPathAllowed(String candidate) {
if (!isAndroid || !isLocal) return true;
if (AndroidDocuments.isPath(candidate)) return true;
if (homePath.isEmpty || candidate.isEmpty) return false;
final home = PathUtil.posixContext.normalize(homePath);
final target = PathUtil.posixContext.normalize(candidate);
@@ -408,6 +411,15 @@ class FileController {
return DirectoryData(directory.value, options.value);
}
Future<void> _restoreWorkspaceHome(String savedDir) async {
if (savedDir.isEmpty || AndroidDocuments.isPath(savedDir)) return;
final workspace = await AndroidDocuments.workspace();
if (PathUtil.posixContext.equals(workspace, savedDir) ||
PathUtil.posixContext.isWithin(workspace, savedDir)) {
homePath = workspace;
}
}
Future<void> onReady() async {
if (isLocal) {
options.value.home = await bind.mainGetHomeDir();
@@ -424,6 +436,7 @@ class FileController {
var savedDir = (await bind.sessionGetPeerOption(
sessionId: sessionId, name: isLocal ? "local_dir" : "remote_dir"));
if (isAndroid && isLocal) await _restoreWorkspaceHome(savedDir);
if (savedDir.isNotEmpty && !_isPathAllowed(savedDir)) {
savedDir = options.value.home;
await bind.sessionPeerOption(
@@ -436,7 +449,13 @@ class FileController {
options.value.home,
};
for (final dir in dirs) {
if (isAndroid && isLocal) await _restoreWorkspaceHome(dir);
if (await _openDirectoryPath(dir, isBack: true)) {
final documentRoot = RegExp(r'^/@rustdesk/tree/[^/]+/[^/]+')
.stringMatch(directory.value.path);
if (isLocal && documentRoot != null) {
homePath = documentRoot;
}
return true;
}
}
@@ -528,6 +547,9 @@ class FileController {
return true;
}
debugPrint("Failed to openDirectory $path: $e");
if (isAndroid && isLocal && AndroidDocuments.isPath(path)) {
showToast(e.toString());
}
return false;
}
}
@@ -564,6 +586,9 @@ class FileController {
}
Future<bool> _goToParentDirectory({bool isBack = false}) async {
if (AndroidDocuments.isRoot(directory.value.path)) {
return false;
}
final isWindows = options.value.isWindows;
final dirPath = directory.value.path;
var parent = PathUtil.dirname(dirPath, isWindows);
@@ -627,6 +652,17 @@ class FileController {
final transferJobIds = <int>[];
for (var from in items.items) {
final jobID = jobController.addTransferJob(from, isRemoteToLocal);
// Keep this check before PathUtil.join: Rust does not receive the selected
// root separately, and Web transfers bypass Rust validation.
if (isRemoteToLocal &&
!DownloadPaths.validName(from.name, windows: isWindows)) {
jobController.jobError({
'id': '$jobID',
'file_num': '0',
'err': 'Invalid file name: ${from.name}',
});
continue;
}
transferJobs.add((from, jobID));
transferJobIds.add(jobID);
}
@@ -651,6 +687,15 @@ class FileController {
return;
}
if (isRemoteToLocal) {
for (final (entry, jobID) in transferJobs) {
if (entry.isDirectory) {
await _downloadEmptyDirectories(entry, jobID, otherSideData);
}
}
return;
}
final List<Entry> entrys = items.items.toList();
var isRemote = isLocal == true ? true : false;
@@ -683,6 +728,35 @@ class FileController {
});
}
Future<void> _downloadEmptyDirectories(
Entry entry, int jobID, DirectoryData destination) async {
try {
final emptyDirs = await fileFetcher.readEmptyDirs(
entry.path, false, destination.options.showHidden);
final localRoot = PathUtil.join(destination.directory.path, entry.name,
destination.options.isWindows);
final paths = emptyDirs
.map((dir) => DownloadPaths.mapDirectory(
entry.path, dir.path, localRoot,
remoteWindows: options.value.isWindows,
localWindows: destination.options.isWindows))
.toList();
for (final path in paths) {
await DownloadPaths.ensureNoLinks(destination.directory.path, path);
}
for (final path in paths) {
await createDirWithRemote(path, false);
}
} on FormatException catch (err) {
await bind.sessionCancelJob(sessionId: sessionId, actId: jobID);
jobController.jobError({
'id': '$jobID',
'file_num': '0',
'err': err.message,
});
}
}
bool _removeCheckboxRemember = false;
Future<void> removeAction(SelectedItems items) async {
@@ -692,7 +766,7 @@ class FileController {
return;
}
final isWindows = options.value.isWindows;
await Future.forEach(items.items, (Entry item) async {
await Future.forEach(items.items.toList(), (Entry item) async {
final jobID = JobController.jobID.next();
var title = "";
var content = "";
@@ -1104,7 +1178,8 @@ class JobController {
}
Future<bool> jobDone(Map<String, dynamic> evt) async {
if (jobResultListener.isListening) {
final waitingForResult = jobResultListener.isListening;
if (waitingForResult) {
jobResultListener.complete(evt);
// return;
}
@@ -1120,6 +1195,11 @@ class JobController {
return true;
}
final job = jobTable[jobIndex];
if (job.type == JobType.transfer &&
job.isRemoteToLocal &&
job.state == JobState.error) {
return true;
}
job.recvJobRes = true;
if (job.type == JobType.deleteFile) {
job.state = JobState.done;
@@ -1150,7 +1230,8 @@ class JobController {
if (job.type == JobType.deleteDir) {
return job.state == JobState.done;
} else {
return true;
// An awaiting file-deletion batch refreshes when removeAction finishes.
return job.type != JobType.deleteFile || !waitingForResult;
}
}
@@ -1448,6 +1529,12 @@ class FileFetcher {
if (!_removeRemoteReadTask(entry.key, task)) continue;
task.completer.completeError(StateError(_kRemoteSessionChangedError));
}
for (final path in remoteEmptyDirsTasks.keys.toList()) {
if (!AndroidDocuments.isPath(path)) continue;
remoteEmptyDirsTasks
.remove(path)
?.completeError(StateError(_kRemoteSessionChangedError));
}
}
_RemoteReadTask _registerRemoteReadTask(String path, bool includeHidden) {
@@ -1488,15 +1575,18 @@ class FileFetcher {
final c = Completer<List<FileDirectory>>();
tasks[path] = c;
Timer(Duration(seconds: 2), () {
final timeout = AndroidDocuments.isPath(path)
? _kRemoteReadDirTimeout
: const Duration(seconds: 2);
Timer(timeout, () {
if (!identical(tasks[path], c)) return;
tasks.remove(path);
if (c.isCompleted) return;
c.completeError("Failed to read empty dirs, timeout");
});
return c.future;
}
Future<FileDirectory> registerReadRecursiveTask(int actID) {
Future<FileDirectory> registerReadRecursiveTask(int actID, String path) {
final tasks = readRecursiveTasks;
if (tasks.containsKey(actID)) {
throw "Failed to registerRemoveTask, already have same ReadRecursive job";
@@ -1504,7 +1594,10 @@ class FileFetcher {
final c = Completer<FileDirectory>();
tasks[actID] = c;
Timer(Duration(seconds: 2), () {
final timeout = AndroidDocuments.isPath(path)
? _kRemoteReadDirTimeout
: const Duration(seconds: 2);
Timer(timeout, () {
tasks.remove(actID);
if (c.isCompleted) return;
c.completeError("Failed to read dir, timeout");
@@ -1586,8 +1679,13 @@ class FileFetcher {
fdJsons.map((fdJson) => FileDirectory.fromJson(fdJson)).toList();
return fds;
} else {
final generation = _remoteSessionGeneration;
await bind.sessionReadRemoteEmptyDirsRecursiveSync(
sessionId: sessionId, path: path, includeHidden: showHidden);
if (AndroidDocuments.isPath(path) &&
generation != _remoteSessionGeneration) {
throw StateError(_kRemoteSessionChangedError);
}
return registerReadEmptyDirsTask(isLocal, path);
}
} catch (e) {
@@ -1601,6 +1699,11 @@ class FileFetcher {
if (isLocal) {
final res = await bind.sessionReadLocalDirSync(
sessionId: sessionId, path: path, showHidden: showHidden);
if (isAndroid && AndroidDocuments.isPath(path)) {
final data = jsonDecode(res);
if (data['error'] != null) throw StateError(data['error'] as String);
return FileDirectory.fromJson(data);
}
final fd = FileDirectory.fromJson(jsonDecode(res));
return fd;
} else {
@@ -1640,7 +1743,7 @@ class FileFetcher {
path: path,
isRemote: !isLocal,
showHidden: showHidden);
return registerReadRecursiveTask(actID);
return registerReadRecursiveTask(actID, path);
} catch (e) {
return Future.error(e);
}
+10
View File
@@ -15,6 +15,8 @@ import '../common/formatter/id_formatter.dart';
import '../desktop/pages/server_page.dart' as desktop;
import '../desktop/widgets/tabbar_widget.dart';
import '../mobile/pages/server_page.dart';
import '../mobile/widgets/android_file_transfer_setup.dart';
import '../utils/android_documents.dart';
import 'model.dart';
const kLoginDialogTag = "LOGIN";
@@ -399,6 +401,14 @@ class ServerModel with ChangeNotifier {
stopService();
}
} else {
if (isAndroid) {
try {
await AndroidDocuments.requireLogFolder();
await showAndroidFileTransferSetup(gFFI);
} catch (_) {
debugPrint('Folder setup failed; continuing service startup');
}
}
await checkRequestNotificationPermission();
if (bind.mainGetLocalOption(key: kOptionDisableFloatingWindow) != 'Y') {
await checkFloatingWindowPermission();
-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>[];
+98
View File
@@ -0,0 +1,98 @@
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../common.dart';
class AndroidDocuments {
static const root = '/@rustdesk/';
static bool isPath(String path) => path.startsWith(root);
static bool isRoot(String path) =>
RegExp(r'^/@rustdesk/tree/[^/]+/[^/]+$').hasMatch(path);
static String displayPath(String path) {
if (!isPath(path)) return path;
return path.replaceFirst(RegExp(r'^/@rustdesk/tree/[^/]+/'), '');
}
static Future<Map<String, dynamic>?> selectFolder({bool share = false}) async {
gFFI.ffiModel.beginAndroidDocumentPicker();
try {
final result = await gFFI.invokeMethodWithResult<String>(
'document_folder', {'share': share});
return result == null ? null : jsonDecode(result) as Map<String, dynamic>;
} finally {
gFFI.ffiModel.endAndroidDocumentPicker();
}
}
static Future<String> workspace({bool share = false}) async {
final path = await gFFI
.invokeMethodWithResult<String>('document_workspace', {'share': share});
if (path == null || path.isEmpty) {
throw StateError('App workspace is unavailable');
}
return path;
}
static Future<bool> requireLogFolder() async {
gFFI.ffiModel.beginAndroidDocumentPicker();
try {
final ready = await gFFI.invokeMethodWithResult<bool>(
'document_require_log_folder', {'checkOnly': true});
if (ready == null) {
throw StateError('Log directory setup did not complete');
}
if (ready) return true;
if (!await _confirmLogFolder()) return false;
final selected = await gFFI
.invokeMethodWithResult<bool>('document_require_log_folder');
if (selected == null) {
throw StateError('Log directory setup did not complete');
}
return selected;
} catch (error) {
debugPrint('Log directory setup failed');
await gFFI.dialogManager.show<void>(
(_, close, __) => CustomAlertDialog(
title: Text(translate('Error')),
content: Text(error is PlatformException
? translate(error.message ?? 'Failed')
: error.toString()),
actions: [
TextButton(onPressed: close, child: Text(translate('OK'))),
],
onSubmit: close,
onCancel: close,
),
backDismiss: true,
forceGlobal: true,
);
rethrow;
} finally {
gFFI.ffiModel.endAndroidDocumentPicker();
}
}
static Future<bool> _confirmLogFolder() async =>
await gFFI.dialogManager.show<bool>(
(_, close, __) => CustomAlertDialog(
title: Text(translate('Permissions')),
content: Text(
'${translate('android-logs-folder-tip')}\n'),
actions: [
TextButton(
onPressed: () => close(true),
child: Text(translate('Choose folder')),
),
],
onCancel: () => close(false),
),
backDismiss: true,
forceGlobal: true,
) ==
true;
}
+52
View File
@@ -0,0 +1,52 @@
import 'dart:io';
import 'package:path/path.dart' as path;
class DownloadPaths {
static Future<void> ensureNoLinks(String root, String destination) async {
if (!path.isWithin(root, destination)) {
throw FormatException('Invalid download directory: $destination');
}
var current = root;
for (final name in path.split(path.relative(destination, from: root))) {
current = path.join(current, name);
if (await FileSystemEntity.type(current, followLinks: false) ==
FileSystemEntityType.link) {
throw FormatException('Download directory contains a link: $current');
}
}
}
static bool validName(String name, {required bool windows}) {
if (name.isEmpty || name == '.' || name == '..' || name.contains('\x00')) {
return false;
}
if (name.contains('/')) return false;
return !windows ||
(!name.contains(RegExp(r'[<>:"\\|?*]')) &&
!name.endsWith('.') &&
!name.endsWith(' '));
}
static String mapDirectory(
String remoteRoot, String remotePath, String localRoot,
{required bool remoteWindows, required bool localWindows}) {
final remote = path.Context(
style: remoteWindows ? path.Style.windows : path.Style.posix);
final local = path.Context(
style: localWindows ? path.Style.windows : path.Style.posix);
if (remotePath.contains('\x00') ||
remote.split(remotePath).contains('..') ||
(!remote.equals(remoteRoot, remotePath) &&
!remote.isWithin(remoteRoot, remotePath))) {
throw FormatException('Invalid download directory: $remotePath');
}
final relative = remote.relative(remotePath, from: remoteRoot);
if (relative == '.') return localRoot;
final names = remote.split(relative);
if (names.any((name) => !validName(name, windows: localWindows))) {
throw FormatException('Invalid download directory: $remotePath');
}
return local.joinAll([localRoot, ...names]);
}
}
+9
View File
@@ -1834,6 +1834,10 @@ class RustdeskImpl {
throw UnimplementedError("mainRemoveTrustedDevices");
}
Future<void> mainRenewTrustedDevices({required String json, dynamic hint}) {
throw UnimplementedError("mainRenewTrustedDevices");
}
Future<void> mainClearTrustedDevices({dynamic hint}) {
throw UnimplementedError("mainClearTrustedDevices");
}
@@ -1928,6 +1932,11 @@ class RustdeskImpl {
}
String mainGetCommonSync({required String key, dynamic hint}) {
const prefix = 'resolve-api-server:';
if (key.startsWith(prefix)) {
return js.context
.callMethod('getByName', ['api_server', key.substring(prefix.length)]);
}
throw UnimplementedError("mainGetCommonSync");
}
@@ -0,0 +1,92 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_hbb/common.dart';
import 'package:flutter_hbb/generated_bridge.dart';
import 'package:flutter_hbb/mobile/widgets/android_file_transfer_setup.dart';
import 'package:flutter_hbb/models/model.dart';
import 'package:flutter_hbb/models/platform_model.dart';
import 'package:flutter_hbb/models/server_model.dart';
import 'package:flutter_test/flutter_test.dart';
class _Binding extends Fake implements RustdeskImpl {
final options = <String, String>{};
@override
String translate(
{required String name, required String locale, dynamic hint}) =>
name;
@override
String getLocalFlutterOption({required String k, dynamic hint}) =>
options[k] ?? '';
@override
Future<void> setLocalFlutterOption(
{required String k, required String v, dynamic hint}) async {
options[k] = v;
}
@override
bool isDisableSettings({dynamic hint}) => false;
@override
bool isOutgoingOnly({dynamic hint}) => false;
@override
String mainGetBuildinOption({required String key, dynamic hint}) => '';
}
class _Server extends Fake implements ServerModel {
@override
List<Client> get clients => [];
}
class _Session extends Fake implements FFI {
@override
final dialogManager = OverlayDialogManager();
@override
final serverModel = _Server();
}
void main() {
late _Session session;
setUp(() {
platformFFI.setBindingForTesting(_Binding());
session = _Session();
});
Future<void> openApp(WidgetTester tester) => tester.pumpWidget(MaterialApp(
navigatorKey: globalKey,
home: const Scaffold(),
));
testWidgets('skipping folder setup suppresses later prompts', (tester) async {
await openApp(tester);
final first = showAndroidFileTransferSetup(session);
await tester.pumpAndSettle();
await tester.tap(find.text('Skip'));
await tester.pumpAndSettle();
expect(await first, isTrue);
expect(await showAndroidFileTransferSetup(_Session()), isTrue);
expect(find.byType(CustomAlertDialog), findsNothing);
});
testWidgets('canceling setup leaves it available at the next entry',
(tester) async {
await openApp(tester);
final first = showAndroidFileTransferSetup(session);
await tester.pumpAndSettle();
await tester.sendKeyEvent(LogicalKeyboardKey.escape);
await tester.pumpAndSettle();
expect(await first, isFalse);
final retry = showAndroidFileTransferSetup(session);
await tester.pumpAndSettle();
expect(find.byType(CustomAlertDialog), findsOneWidget);
await tester.tap(find.text('Skip'));
await tester.pumpAndSettle();
expect(await retry, isTrue);
});
}
+80
View File
@@ -0,0 +1,80 @@
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:flutter_hbb/common/widgets/api_server_warning.dart';
void main() {
test('warns only for remote HTTP endpoints', () {
final cases = <String?, bool>{
null: false,
'': false,
'https://api.example.com': false,
'http://api.example.com': true,
'http://192.168.1.13:13000': true,
'http://localhost:21114': false,
'http://127.0.0.1:21114': false,
'http://[::1]:21114': false,
};
for (final entry in cases.entries) {
expect(shouldWarnApiServer(entry.key), entry.value, reason: entry.key);
}
});
testWidgets('warning follows API and ID changes using the resolved endpoint',
(tester) async {
final api = TextEditingController();
final id = TextEditingController(text: 'id.example.com');
addTearDown(api.dispose);
addTearDown(id.dispose);
await tester.pumpWidget(MaterialApp(
home: ApiServerWarning(
controller: api,
idController: id,
message: 'HTTP warning',
emptyMessage: 'Default HTTP warning',
resolveApiServer: ({required api, required custom}) =>
api.isNotEmpty ? api : 'http://$custom',
),
));
expect(find.text('Default HTTP warning'), findsOneWidget);
id.text = 'localhost';
await tester.pump();
expect(find.text('Default HTTP warning'), findsNothing);
api.text = 'http://api.example.com';
await tester.pump();
expect(find.text('HTTP warning'), findsOneWidget);
api.text = 'https://api.example.com';
await tester.pump();
expect(find.text('HTTP warning'), findsNothing);
});
testWidgets('resolver failures are reported without breaking the server form',
(tester) async {
final api = TextEditingController();
final id = TextEditingController();
addTearDown(api.dispose);
addTearDown(id.dispose);
await tester.pumpWidget(MaterialApp(
home: Scaffold(
body: Column(children: [
TextField(controller: api),
Expanded(
child: ApiServerWarning(
controller: api,
idController: id,
message: 'HTTP warning',
emptyMessage: 'Default HTTP warning',
resolveApiServer: ({required api, required custom}) =>
throw const FormatException('API preview failed'),
)),
]),
),
));
expect(tester.takeException(), isA<FormatException>());
expect(find.byType(ErrorWidget), findsNothing);
expect(find.text('Default HTTP warning'), findsNothing);
expect(find.byType(TextField), findsOneWidget);
});
}
@@ -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;
+174
View File
@@ -0,0 +1,174 @@
import 'dart:io';
import 'package:flutter_hbb/generated_bridge.dart';
import 'package:flutter_hbb/models/file_model.dart';
import 'package:flutter_hbb/models/model.dart';
import 'package:flutter_hbb/models/platform_model.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:uuid/uuid.dart';
final _sessionId = UuidValue('00000000-0000-4000-8000-000000000001');
class _Binding extends Fake implements RustdeskImpl {
final sent = <String>[];
final created = <String>[];
int nextId = 0;
@override
String mainGetCommonSync({required String key, dynamic hint}) =>
'${++nextId}';
@override
int versionToNumber({required String v, dynamic hint}) =>
v == '1.3.3' ? 1 : 2;
@override
Future<void> sessionSendFiles({
required UuidValue sessionId,
required int actId,
required String path,
required String to,
required int fileNum,
required bool includeHidden,
required bool isRemote,
required bool isDir,
dynamic hint,
}) async {
expect(isRemote, isTrue);
sent.add(to);
}
@override
Future<void> sessionCreateDir({
required UuidValue sessionId,
required int actId,
required String path,
required bool isRemote,
dynamic hint,
}) async {
expect(isRemote, isFalse);
created.add(path);
}
@override
Future<void> sessionCancelJob({
required UuidValue sessionId,
required int actId,
dynamic hint,
}) async {}
}
class _Session extends Fake implements FFI {
@override
final String id = 'download-test';
@override
UuidValue get sessionId => _sessionId;
@override
late final ffiModel = FfiModel(WeakReference(this));
}
class _Fetcher extends FileFetcher {
_Fetcher() : super(() => _sessionId);
List<String> emptyDirectories = [];
@override
Future<List<FileDirectory>> readEmptyDirs(
String path, bool isLocal, bool showHidden) async =>
emptyDirectories.map((path) => FileDirectory()..path = path).toList();
}
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
late _Binding binding;
late _Session session;
late _Fetcher fetcher;
late FileController controller;
late DirectoryData destination;
setUp(() {
binding = _Binding();
platformFFI.setBindingForTesting(binding);
session = _Session();
session.ffiModel.pi.version = '1.5.1';
fetcher = _Fetcher();
destination =
DirectoryData(FileDirectory()..path = '/downloads', DirectoryOptions());
controller = FileController(
isLocal: false,
getSessionID: () => _sessionId,
rootState: WeakReference(session),
jobController: JobController(() => _sessionId, () => null),
fileFetcher: fetcher,
getOtherSideDirectoryData: () => destination,
);
controller.directory.value.path = '/remote';
});
tearDown(() => session.ffiModel.dispose());
Future<void> download(String name, {bool directory = false}) async {
final entry = Entry()
..name = name
..path = '/remote/$name'
..entryType = directory ? 0 : 4;
final items = SelectedItems(isLocal: false)..add(entry);
await controller.sendFiles(items, destination);
}
test('downloads refuse peer listing names that escape the local folder',
() async {
await download('report.txt');
expect(binding.sent, ['/downloads/report.txt']);
binding.sent.clear();
for (final windows in [false, true]) {
destination.options.isWindows = windows;
destination.directory.path = windows ? r'C:\downloads' : '/downloads';
for (final name in [
'../outside.txt',
'/outside.txt',
'.',
'..',
'',
'bad\x00name',
if (windows) ...[r'..\outside.txt', r'C:\outside.txt', r'\\host\share'],
]) {
await download(name);
expect(binding.sent, isEmpty, reason: name);
expect(controller.jobController.jobTable.last.state, JobState.error);
}
}
await controller.jobController.jobDone({
'id': '${controller.jobController.jobTable.last.id}',
'file_num': '0',
});
expect(controller.jobController.jobTable.last.state, JobState.error);
});
test('empty-directory downloads reject paths outside the selected folder',
() async {
for (final path in ['/remote/other/empty', '/remote/docs/../out']) {
fetcher.emptyDirectories = ['/remote/docs/ok', path];
await download('docs', directory: true);
expect(binding.created, isEmpty, reason: path);
expect(controller.jobController.jobTable.last.state, JobState.error);
}
fetcher.emptyDirectories = ['/remote/docs', '/remote/docs/sub/empty'];
await download('docs', directory: true);
expect(binding.created, ['/downloads/docs', '/downloads/docs/sub/empty']);
});
test('empty-directory downloads refuse existing local links', () async {
final temporary =
await Directory.systemTemp.createTemp('rustdesk_download_');
addTearDown(() => temporary.delete(recursive: true));
final outside = await Directory('${temporary.path}/outside').create();
final downloads = await Directory('${temporary.path}/downloads').create();
await Link('${downloads.path}/docs').create(outside.path);
destination.directory.path = downloads.path;
destination.options.isWindows = Platform.isWindows;
fetcher.emptyDirectories = ['/remote/docs/empty'];
await download('docs', directory: true);
expect(binding.created, isEmpty);
expect(controller.jobController.jobTable.last.state, JobState.error);
});
}
@@ -0,0 +1,71 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_hbb/desktop/pages/file_manager_page.dart';
import 'package:flutter_hbb/desktop/widgets/list_search_action_listener.dart';
import 'package:flutter_hbb/models/file_model.dart';
import 'package:flutter_test/flutter_test.dart';
List<Entry> _entries(int count) => [
for (var i = 0; i < count; i++)
Entry()
..name = 'f$i'
..path = '/f$i'
];
List<String> _names(List<Entry> entries) =>
entries.map((e) => e.name).toList()..sort();
void main() {
test('navigation keys move the selection and stop at the ends', () {
final entries = _entries(5);
expect(_names(navigateSelection(entries, [], 1, false)), ['f0']);
expect(_names(navigateSelection(entries, [], -1, false)), ['f4']);
var selected = navigateSelection(entries, [entries[1]], 1, false);
expect(_names(selected), ['f2']);
selected = navigateSelection(entries, selected, -1, false);
expect(_names(selected), ['f1']);
expect(_names(navigateSelection(entries, selected, -3, false)), ['f0']);
expect(_names(navigateSelection(entries, selected, 5, false)), ['f4']);
});
test('shift extends and shrinks the range from the anchor', () {
final entries = _entries(5);
var selected = [entries[2]];
selected = navigateSelection(entries, selected, 1, true);
selected = navigateSelection(entries, selected, 1, true);
expect(_names(selected), ['f2', 'f3', 'f4']);
selected = navigateSelection(entries, selected, -1, true);
selected = navigateSelection(entries, selected, -1, true);
selected = navigateSelection(entries, selected, -1, true);
expect(_names(selected), ['f1', 'f2']);
selected = navigateSelection(entries, selected, 1, false);
expect(_names(selected), ['f2']);
});
test('page keys go to the visible edge before paging', () {
// Rows 10..19 are fully visible.
expect(pageDelta(12, 10, 19, true), 7);
expect(pageDelta(19, 10, 19, true), 9);
expect(pageDelta(12, 10, 19, false), -2);
expect(pageDelta(10, 10, 19, false), -9);
});
testWidgets('Enter does not reach type-to-search', (tester) async {
final node = FocusNode();
addTearDown(node.dispose);
final searched = <String>[];
await tester.pumpWidget(MaterialApp(
home: ListSearchActionListener(
node: node,
buffer: TimeoutStringBuffer(),
onNext: searched.add,
onSearch: searched.add,
child: const SizedBox(),
),
));
node.requestFocus();
await tester.pump();
await tester.sendKeyEvent(LogicalKeyboardKey.enter, character: '\r');
expect(searched, isEmpty);
});
}
+119 -71
View File
@@ -1,8 +1,10 @@
import 'dart:async';
import 'dart:convert';
import 'package:flutter_hbb/generated_bridge.dart';
import 'package:flutter_hbb/models/file_model.dart';
import 'package:flutter_hbb/models/model.dart';
import 'package:flutter_hbb/models/platform_model.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:uuid/uuid.dart';
@@ -48,7 +50,124 @@ class _SentRead {
const _SentRead(this.path, this.includeHidden);
}
class _FileBinding extends Fake implements RustdeskImpl {
int _jobId = 0;
final emptyDirsDispatch = Completer<void>();
@override
Future<void> sessionReadRemoteEmptyDirsRecursiveSync(
{required UuidValue sessionId,
required String path,
required bool includeHidden,
dynamic hint}) =>
emptyDirsDispatch.future;
@override
String translate(
{required String name, required String locale, dynamic hint}) =>
name;
@override
String mainGetCommonSync({required String key, dynamic hint}) =>
'${++_jobId}';
}
class _DeletingController extends FileController {
final confirmations = <String>[];
_DeletingController()
: super(
isLocal: false,
getSessionID: () => _sessionId,
rootState: WeakReference(_FakeFFI()),
jobController: JobController(() => _sessionId, () => null),
fileFetcher: FileFetcher(() => _sessionId),
getOtherSideDirectoryData: () =>
DirectoryData(FileDirectory(), DirectoryOptions()),
);
@override
Future<bool?> showRemoveDialog(
String title, String content, bool showCheckbox) async {
confirmations.add(content);
return true;
}
@override
void sendRemoveFile(String path, int fileNum, int actId) {
scheduleMicrotask(() {
selectedItems.reconcile(
selectedItems.items.where((entry) => entry.path != path).toList());
unawaited(
jobController.jobDone({'id': '$actId', 'file_num': '$fileNum'}));
});
}
@override
Future<bool> refresh() async => true;
}
void main() {
for (final scenario in ['completion', 'reconnect', 'dispatch reconnect']) {
testWidgets('SAF retry after $scenario', (tester) async {
const path = '/@rustdesk/tree/grant/root';
final response = jsonEncode({
'path': path,
'empty_dirs': [jsonDecode(_directoryJson('$path/empty'))],
});
final binding = _FileBinding();
platformFFI.setBindingForTesting(binding);
final fetcher = FileFetcher(() => _sessionId);
final first = expectLater(
fetcher.readEmptyDirs(path, false, false),
scenario == 'completion'
? completion(isNotEmpty)
: throwsA(isA<StateError>()));
try {
if (scenario != 'dispatch reconnect')
binding.emptyDirsDispatch.complete();
await tester.pump(const Duration(seconds: 3));
if (scenario != 'completion') {
fetcher.beginRemoteSession();
} else {
fetcher.tryCompleteEmptyDirsTask(response, 'false');
}
if (scenario == 'dispatch reconnect')
binding.emptyDirsDispatch.complete();
await tester.pump();
final retry = expectLater(
fetcher.readEmptyDirs(path, false, false).then((directories) =>
directories.map((directory) => directory.path)),
completion(['$path/empty']));
await tester.pump();
await tester.pump(const Duration(seconds: 28));
fetcher.tryCompleteEmptyDirsTask(response, 'false');
await tester.pump(const Duration(seconds: 2));
await retry;
} finally {
await tester.pump(const Duration(seconds: 30));
}
await first;
});
}
test('deletion confirms all five files despite refreshed selection',
() async {
platformFFI.setBindingForTesting(_FileBinding());
final controller = _DeletingController();
final files = ['a.txt', 'b.txt', 'c.txt', 'd.txt', 'e.txt']
.map((name) => Entry()
..name = name
..path = '/selected/$name')
.toList();
controller.selectedItems.selectAll(files);
await controller.removeAction(controller.selectedItems);
expect(controller.confirmations, files.map((file) => file.path));
expect(controller.selectedItems.items, isEmpty);
});
test('a fast remote response is matched after registration', () async {
late final FileFetcher fileFetcher;
fileFetcher = FileFetcher(
@@ -62,19 +181,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 +213,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 +307,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,
+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,
);
});
});
}
@@ -0,0 +1,71 @@
import 'dart:ui' show PointerDeviceKind, SemanticsAction;
import 'package:flutter/gestures.dart' show kSecondaryMouseButton;
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_hbb/common/widgets/peer_card.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
const doubleClickInterval = Duration(milliseconds: 75);
const dragOffset = Offset(150, 0);
// Keep pointer cases semantics-off to cover parent/child gesture competition.
// VM taps bypass browser click-to-semantics conversion; verify that in a browser.
for (final action in ['physical clicks', 'semantic tap', 'keyboard']) {
testWidgets('More $action opens once without connecting the card',
(tester) async {
var opened = 0;
var connected = 0;
await tester.pumpWidget(MaterialApp(
home: Material(
child: GestureDetector(
excludeFromSemantics: true,
onTap: () {},
onDoubleTap: () => connected++,
onLongPress: () {},
child: Builder(builder: (context) {
return Center(
child: build_more(context, onTap: () {
opened++;
showMenu<void>(
context: context,
position: RelativeRect.fill,
items: const [PopupMenuItem(child: Text('Connect'))],
);
}));
}),
),
),
));
final button = find.byIcon(Icons.more_vert);
final position = tester.getCenter(button);
if (action == 'semantic tap') {
final node = tester.getSemantics(button);
node.owner!.performAction(node.id, SemanticsAction.tap);
} else if (action == 'keyboard') {
await tester.sendKeyEvent(LogicalKeyboardKey.tab);
await tester.sendKeyEvent(LogicalKeyboardKey.enter);
} else {
await tester.tapAt(position,
kind: PointerDeviceKind.mouse, buttons: kSecondaryMouseButton);
await tester.pumpAndSettle();
expect(opened, 0, reason: 'A secondary click must not open More');
await tester.dragFrom(position, dragOffset,
kind: PointerDeviceKind.mouse);
await tester.pumpAndSettle();
expect(opened, 0, reason: 'Dragging out must cancel the More tap');
await tester.tapAt(position, kind: PointerDeviceKind.mouse);
}
expect(opened, 1,
reason: 'More must not wait for a possible double click');
await tester.pump();
if (action == 'physical clicks') {
await tester.pump(doubleClickInterval);
await tester.tapAt(position, kind: PointerDeviceKind.mouse);
}
await tester.pumpAndSettle();
expect({'menu': opened, 'connection': connected},
{'menu': 1, 'connection': 0});
}, semanticsEnabled: action != 'physical clicks');
}
}
@@ -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);
});
}
+4
View File
@@ -10,6 +10,7 @@
#include "win32_desktop.h"
#include "flutter_window.h"
#include "utils.h"
#include "service_control.h"
typedef char** (*FUNC_RUSTDESK_CORE_MAIN)(int*);
typedef void (*FUNC_RUSTDESK_FREE_ARGS)( char**, int);
@@ -23,6 +24,9 @@ const wchar_t* getWindowClassName();
int APIENTRY wWinMain(_In_ HINSTANCE instance, _In_opt_ HINSTANCE prev,
_In_ wchar_t *command_line, _In_ int show_command)
{
if (auto result = service_control::HandleCommand(command_line)) {
return static_cast<int>(*result);
}
HINSTANCE hInstance = LoadLibraryA("librustdesk.dll");
if (!hInstance)
{
+183
View File
@@ -0,0 +1,183 @@
#ifndef RUSTDESK_RUNNER_SERVICE_CONTROL_H_
#define RUSTDESK_RUNNER_SERVICE_CONTROL_H_
#include <windows.h>
#include <shellapi.h>
#include <winsvc.h>
#include <cstdio>
#include <cwchar>
#include <memory>
#include <optional>
#include <string>
#include <string_view>
#include <type_traits>
namespace service_control {
using ServiceHandle = std::unique_ptr<std::remove_pointer_t<SC_HANDLE>,
decltype(&CloseServiceHandle)>;
constexpr DWORD kStopTimeoutMilliseconds = 30000;
constexpr DWORD kPollIntervalMilliseconds = 100;
inline DWORD StopService(SC_HANDLE service) {
SERVICE_STATUS_PROCESS status{};
DWORD bytes_needed = 0;
if (!QueryServiceStatusEx(service, SC_STATUS_PROCESS_INFO,
reinterpret_cast<BYTE*>(&status), sizeof(status),
&bytes_needed)) {
return GetLastError();
}
if (status.dwCurrentState == SERVICE_STOPPED) {
return ERROR_SUCCESS;
}
if (status.dwCurrentState != SERVICE_STOP_PENDING) {
SERVICE_STATUS stopped{};
if (!ControlService(service, SERVICE_CONTROL_STOP, &stopped)) {
const DWORD error = GetLastError();
return error == ERROR_SERVICE_NOT_ACTIVE ? ERROR_SUCCESS : error;
}
}
// The installer may remove files next; accepting STOP alone does not mean
// the service has reached SERVICE_STOPPED.
const ULONGLONG started = GetTickCount64();
while (status.dwCurrentState != SERVICE_STOPPED) {
if (GetTickCount64() - started >= kStopTimeoutMilliseconds) {
return ERROR_TIMEOUT;
}
Sleep(kPollIntervalMilliseconds);
if (!QueryServiceStatusEx(service, SC_STATUS_PROCESS_INFO,
reinterpret_cast<BYTE*>(&status), sizeof(status),
&bytes_needed)) {
return GetLastError();
}
}
return ERROR_SUCCESS;
}
inline DWORD RemoveService(const wchar_t* name) {
ServiceHandle manager(OpenSCManagerW(nullptr, nullptr, SC_MANAGER_CONNECT),
CloseServiceHandle);
if (!manager) {
return GetLastError();
}
ServiceHandle service(
OpenServiceW(manager.get(), name,
SERVICE_STOP | SERVICE_QUERY_STATUS | DELETE),
CloseServiceHandle);
if (!service) {
const DWORD error = GetLastError();
return error == ERROR_SERVICE_DOES_NOT_EXIST ? ERROR_SUCCESS : error;
}
const DWORD stopped = StopService(service.get());
if (stopped != ERROR_SUCCESS) {
// The uninstall script must still reach its taskkill cleanup.
std::fwprintf(stderr,
L"Service did not stop cleanly: Windows error %lu\n", stopped);
}
if (DeleteService(service.get())) {
return ERROR_SUCCESS;
}
const DWORD error = GetLastError();
return error == ERROR_SERVICE_MARKED_FOR_DELETE ? ERROR_SUCCESS : error;
}
inline DWORD InstallService(const wchar_t* name, const wchar_t* executable,
bool rollback_on_failure) {
if (!*executable || wcschr(executable, L'"')) {
return ERROR_INVALID_PARAMETER;
}
const std::wstring binary_path =
L"\"" + std::wstring(executable) + L"\" --service";
const std::wstring display_name = std::wstring(name) + L" Service";
ServiceHandle manager(
OpenSCManagerW(nullptr, nullptr,
SC_MANAGER_CONNECT | SC_MANAGER_CREATE_SERVICE),
CloseServiceHandle);
if (!manager) {
return GetLastError();
}
ServiceHandle service(
CreateServiceW(manager.get(), name, display_name.c_str(),
SERVICE_START | DELETE, SERVICE_WIN32_OWN_PROCESS,
SERVICE_AUTO_START, SERVICE_ERROR_NORMAL,
binary_path.c_str(), nullptr,
nullptr, nullptr, nullptr, nullptr),
CloseServiceHandle);
const bool created = service != nullptr;
// --after-install can reuse a registration. Preserve its executable and
// account, as the previous create-then-start script did.
if (!service && GetLastError() == ERROR_SERVICE_EXISTS) {
service.reset(OpenServiceW(manager.get(), name, SERVICE_START));
}
if (!service) {
return GetLastError();
}
if (StartServiceW(service.get(), 0, nullptr)) {
return ERROR_SUCCESS;
}
const DWORD error = GetLastError();
// Only manual Start Service restores stop-service=Y on failure. Other
// installation paths retain the registration for a later startup attempt.
if (rollback_on_failure && created && error != ERROR_SERVICE_ALREADY_RUNNING &&
!DeleteService(service.get())) {
const DWORD rollback_error = GetLastError();
std::fwprintf(stderr,
L"Failed to roll back newly created service: Windows error %lu\n",
rollback_error);
}
return error == ERROR_SERVICE_ALREADY_RUNNING ? ERROR_SUCCESS : error;
}
inline DWORD RunCommand(int count, wchar_t** args) {
constexpr int kRemoveArgumentCount = 4;
constexpr int kInstallArgumentCount = 5;
if (count < kRemoveArgumentCount) {
return ERROR_BAD_ARGUMENTS;
}
if (!*args[3]) {
return ERROR_INVALID_PARAMETER;
}
const std::wstring_view operation(args[2]);
const bool rollback_on_failure = operation == L"create-service-with-rollback";
if ((operation == L"create-service" || rollback_on_failure) &&
count == kInstallArgumentCount) {
return InstallService(args[3], args[4], rollback_on_failure);
}
if (operation == L"remove" && count == kRemoveArgumentCount) {
return RemoveService(args[3]);
}
return ERROR_BAD_ARGUMENTS;
}
// Keep these commands in the existing runner so installation/removal can control
// services before loading librustdesk.dll or initializing the UI. A Rust-side
// handler would first require that DLL to load. The header-only implementation
// keeps main.cpp as a dispatch hook without adding a CMake source entry; it is
// compiled into the existing EXE, not a separately packaged helper.
inline std::optional<DWORD> HandleCommand(const wchar_t* command_line) {
constexpr std::wstring_view option = L"--service-control";
const std::wstring_view arguments(command_line);
if (arguments.compare(0, option.size(), option) != 0 ||
(arguments.size() > option.size() && arguments[option.size()] != L' ' &&
arguments[option.size()] != L'\t')) {
return std::nullopt;
}
int count = 0;
wchar_t** args = CommandLineToArgvW(GetCommandLineW(), &count);
if (!args) {
return GetLastError();
}
const DWORD result = RunCommand(count, args);
LocalFree(args);
if (result != ERROR_SUCCESS) {
std::fwprintf(stderr,
L"RustDesk service control failed with Windows error %lu\n",
result);
}
return result;
}
} // namespace service_control
#endif // RUSTDESK_RUNNER_SERVICE_CONTROL_H_
+5
View File
@@ -84,6 +84,8 @@ message LoginRequest {
string my_platform = 13;
bytes hwid = 14;
string avatar = 17;
bytes trusted_device_v2_token = 18;
bool trusted_device_v2_supported = 19;
}
message Terminal {
@@ -93,6 +95,7 @@ message Terminal {
message Auth2FA {
string code = 1;
bytes hwid = 2;
bool trust_this_device = 3;
}
message ChatMessage { string text = 1; }
@@ -147,6 +150,8 @@ message LoginResponse {
PeerInfo peer_info = 2;
}
bool enable_trusted_devices = 3;
bool trusted_device_v2_supported = 4;
bytes trusted_device_v2_token = 5;
}
message TouchScaleUpdate {
+3
View File
@@ -88,6 +88,7 @@ pub const OPTION_ENABLE_DIRECTX_CAPTURE: &str = "enable-directx-capture";
pub const OPTION_ENABLE_ANDROID_SOFTWARE_ENCODING_HALF_SCALE: &str =
"enable-android-software-encoding-half-scale";
pub const OPTION_ENABLE_TRUSTED_DEVICES: &str = "enable-trusted-devices";
pub const OPTION_TRUSTED_DEVICE_EXPIRATION: &str = "trusted-device-expiration-days";
pub const OPTION_AV1_TEST: &str = "av1-test";
/// Maximum number of files allowed during a single file transfer request.
///
@@ -311,6 +312,7 @@ pub const KEYS_SETTINGS: &[&str] = &[
OPTION_API_SERVER,
OPTION_KEY,
OPTION_ALLOW_WEBSOCKET,
OPTION_WEBSOCKET_PORT,
OPTION_PRESET_ADDRESS_BOOK_NAME,
OPTION_PRESET_ADDRESS_BOOK_TAG,
OPTION_PRESET_ADDRESS_BOOK_ALIAS,
@@ -322,6 +324,7 @@ pub const KEYS_SETTINGS: &[&str] = &[
OPTION_ENABLE_DIRECTX_CAPTURE,
OPTION_ENABLE_ANDROID_SOFTWARE_ENCODING_HALF_SCALE,
OPTION_ENABLE_TRUSTED_DEVICES,
OPTION_TRUSTED_DEVICE_EXPIRATION,
OPTION_RELAY_SERVER,
OPTION_ICE_SERVERS,
OPTION_DISABLE_UDP,
+170 -63
View File
@@ -27,6 +27,21 @@ use hbb_common::{
static NEXT_JOB_ID: AtomicI32 = AtomicI32::new(1);
#[cfg(any(target_os = "android", test))]
pub mod android;
#[cfg(any(target_os = "android", all(test, unix)))]
mod android_transfer;
#[cfg(any(target_os = "android", all(test, unix)))]
mod android_descriptor;
pub mod download;
#[cfg(test)]
#[path = "fs/download_tests.rs"]
mod download_tests;
pub fn get_next_job_id() -> i32 {
NEXT_JOB_ID.fetch_add(1, Ordering::SeqCst)
}
@@ -36,6 +51,10 @@ pub fn update_next_job_id(id: i32) {
}
pub fn read_dir(path: &Path, include_hidden: bool) -> ResultType<FileDirectory> {
#[cfg(any(target_os = "android", test))]
if android::is_path(path) {
return android::read_dir(&get_string(path), include_hidden);
}
let mut dir = FileDirectory {
path: get_string(path),
..Default::default()
@@ -140,6 +159,15 @@ pub fn get_path(path: &str) -> PathBuf {
#[inline]
pub fn get_home_as_string() -> String {
#[cfg(target_os = "android")]
match android::home() {
Ok(Some(path)) => return path,
Ok(None) => {}
Err(error) => {
log::trace!("Unable to load the selected document location: {}", error);
return android::ROOT.trim_end_matches('/').to_owned();
}
}
get_string(&Config::get_home())
}
@@ -203,6 +231,10 @@ fn read_dir_recursive(
}
pub fn get_recursive_files(path: &str, include_hidden: bool) -> ResultType<Vec<FileEntry>> {
#[cfg(any(target_os = "android", test))]
if android::is_path(Path::new(path)) {
return android::recursive_files(path, include_hidden);
}
read_dir_recursive(&get_path(path), &get_path(""), include_hidden)
}
@@ -248,6 +280,10 @@ pub fn get_empty_dirs_recursive(
path: &str,
include_hidden: bool,
) -> ResultType<Vec<FileDirectory>> {
#[cfg(any(target_os = "android", test))]
if android::is_path(Path::new(path)) {
return android::empty_dirs(path, include_hidden);
}
read_empty_dirs_recursive(&get_path(path), &get_path(""), include_hidden)
}
@@ -391,6 +427,9 @@ pub struct FileDigest {
#[derive(Default, Serialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct TransferJob {
#[cfg(any(target_os = "android", all(test, unix)))]
#[serde(skip)]
document_transfer: android_transfer::DocumentTransfer,
pub id: i32,
pub r#type: JobType,
pub remote: String,
@@ -417,6 +456,8 @@ pub struct TransferJob {
default_overwrite_strategy: Option<bool>,
#[serde(skip_serializing)]
digest: FileDigest,
#[serde(skip)]
download: Option<download::DownloadState>,
}
#[derive(Debug, Default, Serialize, Deserialize, Clone)]
@@ -517,6 +558,11 @@ fn validate_fs_path_argument(path: &str, arg_name: &str) -> ResultType<()> {
}
fn validate_no_symlink_components(base: &PathBuf, name: &str) -> ResultType<()> {
#[cfg(any(target_os = "android", test))]
if android::is_path(base) {
// Document IDs are resolved and confined to their grant by Android, not the OS filesystem.
return Ok(());
}
if name.is_empty() {
return Ok(());
}
@@ -576,6 +622,10 @@ impl TransferJob {
enable_overwrite_detection: bool,
) -> Self {
log::info!("new write {}", data_source);
let is_download = is_remote && r#type == JobType::Generic;
#[cfg(any(target_os = "android", all(test, unix)))]
let is_download = is_download
&& !matches!(&data_source, DataSource::FilePath(path) if android::is_path(path));
Self {
id,
r#type,
@@ -587,6 +637,7 @@ impl TransferJob {
files: Vec::new(),
total_size: 0,
enable_overwrite_detection,
download: is_download.then(Default::default),
..Default::default()
}
}
@@ -648,6 +699,17 @@ impl TransferJob {
#[inline]
pub fn set_files(&mut self, files: Vec<FileEntry>) -> ResultType<()> {
if self.is_download() && !self.files.is_empty() {
bail!("cannot replace an accepted download file list");
}
#[cfg(any(target_os = "android", all(test, unix)))]
if self.is_remote
&& self.r#type == JobType::Generic
&& self.is_document()
&& !self.files.is_empty()
{
bail!("cannot replace an accepted download file list");
}
validate_transfer_file_names(&files)?;
if let DataSource::FilePath(base) = &self.data_source {
for file in &files {
@@ -692,7 +754,12 @@ impl TransferJob {
fn resolve_entry_path(&self, base: &PathBuf, name: &str) -> Option<PathBuf> {
if self.r#type == JobType::Generic {
match join_validated_path(base, name) {
let result = if self.is_download() {
download::validated_target(base, name)
} else {
join_validated_path(base, name)
};
match result {
Ok(path) => Some(path),
Err(err) => {
log::error!("Invalid file name in transfer job {}: {}", self.id, err);
@@ -705,6 +772,16 @@ impl TransferJob {
}
pub fn modify_time(&self) {
#[cfg(any(target_os = "android", all(test, unix)))]
if self.is_document() {
return;
}
if self.is_download() {
if let Err(err) = self.finish_download() {
log::error!("Failed to finish download {}: {}", self.id, err);
}
return;
}
if self.r#type == JobType::Printer {
return;
}
@@ -729,6 +806,13 @@ impl TransferJob {
}
pub fn remove_download_file(&self) {
#[cfg(any(target_os = "android", all(test, unix)))]
if self.is_document() {
return;
}
if self.is_download() && self.data_stream.is_none() {
return;
}
if self.r#type == JobType::Printer {
return;
}
@@ -761,9 +845,16 @@ impl TransferJob {
}
pub async fn write(&mut self, block: FileTransferBlock) -> ResultType<()> {
if self.is_download() {
return self.write_download(block).await;
}
if block.id != self.id {
bail!("Wrong id");
}
#[cfg(any(target_os = "android", all(test, unix)))]
if self.is_document() {
return self.write_document(block).await;
}
match &self.data_source {
DataSource::FilePath(p) => {
let file_num = block.file_num as usize;
@@ -843,6 +934,10 @@ impl TransferJob {
/// Open the data stream for the current file.
/// Returns Ok(true) if job is done, Ok(false) otherwise.
async fn open_data_stream(&mut self) -> ResultType<bool> {
#[cfg(any(target_os = "android", all(test, unix)))]
if self.is_document() {
return self.open_document_stream().await;
}
let file_num = self.file_num as usize;
match &mut self.data_source {
DataSource::FilePath(p) => {
@@ -882,6 +977,14 @@ impl TransferJob {
/// Get current file's digest (last_modified, file_size) for overwrite detection.
async fn get_current_digest(&self) -> ResultType<(u64, u64)> {
#[cfg(any(target_os = "android", all(test, unix)))]
if self.is_document() {
let entry = self
.files
.get(self.file_num as usize)
.ok_or(anyhow!("Wrong file number"))?;
return Ok((entry.modified_time, entry.size));
}
let meta = match self.data_stream.as_ref().ok_or(anyhow!("file is None"))? {
DataStream::FileStream(file) => file.metadata().await?,
DataStream::BufStream(_) => bail!("No digest for buf stream"),
@@ -970,6 +1073,10 @@ impl TransferJob {
self.data_stream = None;
self.file_confirmed = false;
self.file_is_waiting = false;
#[cfg(any(target_os = "android", all(test, unix)))]
if self.is_document() {
self.fail_document_read(err.to_string());
}
return Err(err.into());
}
Ok(n) => {
@@ -982,6 +1089,10 @@ impl TransferJob {
}
unsafe { buf.set_len(offset) };
if offset == 0 {
#[cfg(any(target_os = "android", all(test, unix)))]
if self.is_document() {
self.finish_document_read().await?;
}
if matches!(self.data_source, DataSource::MemoryCursor(_)) {
self.data_stream.take();
return Ok(None);
@@ -1089,6 +1200,10 @@ impl TransferJob {
/// Get job error message, useful for getting status when job had finished
pub fn job_error(&self) -> Option<String> {
#[cfg(any(target_os = "android", all(test, unix)))]
if let Some(error) = &self.document_transfer.error {
return Some(error.clone());
}
if self.job_skipped() {
return Some("skipped".to_string());
}
@@ -1106,6 +1221,13 @@ impl TransferJob {
}
async fn set_stream_offset(&mut self, file_num: usize, offset: u64) {
#[cfg(any(target_os = "android", all(test, unix)))]
if self.is_document() {
if let Err(error) = self.seek_document(offset).await {
self.fail_document_read(error.to_string());
}
return;
}
if file_num >= self.files.len() {
return;
}
@@ -1160,6 +1282,17 @@ impl TransferJob {
}
pub async fn confirm(&mut self, r: &FileTransferSendConfirmRequest) -> bool {
#[cfg(any(target_os = "android", all(test, unix)))]
if self.is_document() && self.is_remote {
self.confirm_document(r);
}
if self.is_download() {
self.confirm_download(r);
// Open receiver resume streams in write() so validation errors reach the caller.
if matches!(r.union, Some(file_transfer_send_confirm_request::Union::OffsetBlk(offset)) if offset > 0) {
return true;
}
}
if self.file_num() != r.file_num {
// This branch will always be hit if:
// 1. `confirm()` is called in `ui_cm_interface.rs`
@@ -1388,6 +1521,10 @@ pub async fn handle_read_jobs(
}
pub fn remove_all_empty_dir(path: &Path) -> ResultType<()> {
#[cfg(any(target_os = "android", test))]
if android::is_path(path) {
return android::remove_empty_tree(&get_string(path));
}
let fd = read_dir(path, true)?;
for entry in fd.entries.iter() {
match entry.entry_type.enum_value() {
@@ -1406,6 +1543,10 @@ pub fn remove_all_empty_dir(path: &Path) -> ResultType<()> {
#[inline]
pub fn remove_file(file: &str) -> ResultType<()> {
#[cfg(any(target_os = "android", test))]
if android::is_path(Path::new(file)) {
return android::remove_file(file);
}
validate_fs_path_argument(file, "file path")?;
std::fs::remove_file(get_path(file))?;
Ok(())
@@ -1413,6 +1554,10 @@ pub fn remove_file(file: &str) -> ResultType<()> {
#[inline]
pub fn create_dir(dir: &str) -> ResultType<()> {
#[cfg(any(target_os = "android", test))]
if android::is_path(Path::new(dir)) {
return android::operation("mkdir", dir);
}
validate_fs_path_argument(dir, "directory path")?;
std::fs::create_dir_all(get_path(dir))?;
Ok(())
@@ -1420,6 +1565,10 @@ pub fn create_dir(dir: &str) -> ResultType<()> {
#[inline]
pub fn rename_file(path: &str, new_name: &str) -> ResultType<()> {
#[cfg(any(target_os = "android", test))]
if android::is_path(Path::new(path)) {
return android::rename(path, new_name);
}
validate_fs_path_argument(path, "path")?;
if new_name.is_empty() {
bail!("new file name cannot be empty");
@@ -1457,6 +1606,26 @@ pub fn is_write_need_confirmation(
file_path: &str,
digest: &FileTransferDigest,
) -> ResultType<DigestCheckResult> {
#[cfg(any(target_os = "android", test))]
if android::is_path(Path::new(file_path)) {
android::validate(file_path)?;
if is_resume {
bail!("Document transfers must be restarted after interruption");
}
return match android::stat(file_path)? {
Some(entry) => Ok(DigestCheckResult::NeedConfirm(FileTransferDigest {
id: digest.id,
file_num: digest.file_num,
last_modified: entry.modified_time,
file_size: entry.size,
is_identical: entry.modified_time != 0
&& entry.modified_time == digest.last_modified
&& entry.size == digest.file_size,
..Default::default()
})),
None => Ok(DigestCheckResult::NoSuchFile),
};
}
let path = Path::new(file_path);
let digest_file = format!("{}.digest", file_path);
let download_file = format!("{}.download", file_path);
@@ -1677,15 +1846,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 +1868,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 +1917,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");
}
}
+280
View File
@@ -0,0 +1,280 @@
use super::{FileDirectory, FileEntry, FileType};
use hbb_common::{anyhow::anyhow, bail, ResultType};
use serde_derive::Deserialize;
use serde_json::{json, Value};
use std::{path::Path, sync::OnceLock};
pub const ROOT: &str = "/@rustdesk/";
type Request = Box<dyn Fn(&str) -> ResultType<String> + Send + Sync>;
static BACKEND: OnceLock<Request> = OnceLock::new();
pub fn initialize(
request: impl Fn(&str) -> ResultType<String> + Send + Sync + 'static,
) -> ResultType<()> {
BACKEND
.set(Box::new(request))
.map_err(|_| anyhow!("Document storage already initialized"))
}
pub fn is_path(path: &Path) -> bool {
path.to_str().map_or(false, |p| {
p == ROOT.trim_end_matches('/') || p.starts_with(ROOT)
})
}
pub(super) fn validate(path: &str) -> ResultType<()> {
let relative = path
.strip_prefix(ROOT)
.and_then(|path| path.strip_prefix("tree/"))
.ok_or(anyhow!("Invalid document path"))?;
if relative
.split('/')
.any(|p| p.is_empty() || p == "." || p == ".." || p.contains(['\\', '\0']))
{
bail!("Invalid document path");
}
Ok(())
}
pub fn request(value: Value) -> ResultType<Value> {
if let Some(path) = value.get("path").and_then(Value::as_str) {
validate(path)?;
}
let backend = BACKEND
.get()
.ok_or(anyhow!("Android document storage is unavailable"))?;
let response: Value = serde_json::from_str(&backend(&value.to_string())?)?;
if let Some(error) = response.get("error").and_then(Value::as_str) {
bail!("{}", error);
}
response
.get("value")
.cloned()
.ok_or(anyhow!("Invalid document provider response"))
}
pub fn home() -> ResultType<Option<String>> {
let value = request(json!({"op": "home"}))?;
if value.is_null() {
return Ok(None);
}
let path = value.as_str().ok_or(anyhow!("Invalid document home"))?;
validate(path)?;
Ok(Some(path.to_owned()))
}
pub fn allowed(path: &str) -> ResultType<bool> {
if !home()?.map_or(false, |home| Path::new(path).starts_with(home)) {
return Ok(false);
}
request(json!({"op": "allowed", "path": path}))?
.as_bool()
.ok_or(anyhow!("Invalid document permission response"))
}
#[derive(Deserialize)]
struct Metadata {
name: String,
directory: bool,
size: i64,
modified: i64,
}
fn entry(value: Value) -> ResultType<FileEntry> {
let meta: Metadata = serde_json::from_value(value)?;
super::validate_file_name_no_traversal(&meta.name)?;
if meta.name.contains('/') || (!meta.directory && meta.size < 0) {
bail!("The provider did not supply a transferable file name or size");
}
Ok(FileEntry {
entry_type: if meta.directory {
FileType::Dir
} else {
FileType::File
}
.into(),
is_hidden: meta.name.starts_with('.'),
name: meta.name,
size: if meta.directory { 0 } else { meta.size as u64 },
modified_time: meta.modified.max(0) as u64,
..Default::default()
})
}
pub fn stat(path: &str) -> ResultType<Option<FileEntry>> {
let value = request(json!({"op": "stat", "path": path}))?;
if value.is_null() {
Ok(None)
} else {
entry(value).map(Some)
}
}
pub fn read_dir(path: &str, hidden: bool) -> ResultType<FileDirectory> {
let values: Vec<Value> = serde_json::from_value(request(json!({"op": "list", "path": path}))?)?;
let mut entries = Vec::new();
for value in values {
let entry = entry(value)?;
if hidden || !entry.is_hidden {
entries.push(entry);
}
}
Ok(FileDirectory {
path: path.to_owned(),
entries,
..Default::default()
})
}
pub fn recursive_files(path: &str, hidden: bool) -> ResultType<Vec<FileEntry>> {
let meta = stat(path)?.ok_or(anyhow!("Document does not exist"))?;
if meta.entry_type.enum_value() == Ok(FileType::File) {
return Ok(vec![FileEntry {
name: String::new(),
..meta
}]);
}
let mut files = Vec::new();
let mut pending = vec![(path.to_owned(), String::new())];
while let Some((directory, prefix)) = pending.pop() {
for mut entry in read_dir(&directory, hidden)?.entries {
let path = format!("{}/{}", directory, entry.name);
entry.name = if prefix.is_empty() {
entry.name
} else {
format!("{}/{}", prefix, entry.name)
};
if entry.entry_type.enum_value() == Ok(FileType::Dir) {
pending.push((path, entry.name));
} else {
files.push(entry);
}
}
}
Ok(files)
}
pub fn empty_dirs(path: &str, hidden: bool) -> ResultType<Vec<FileDirectory>> {
let mut result = Vec::new();
let mut pending = vec![path.to_owned()];
while let Some(path) = pending.pop() {
let directory = read_dir(&path, hidden)?;
if directory.entries.is_empty() {
result.push(directory);
continue;
}
for entry in directory.entries {
if entry.entry_type.enum_value() == Ok(FileType::Dir) {
pending.push(format!("{}/{}", path, entry.name));
}
}
}
Ok(result)
}
pub fn operation(op: &str, path: &str) -> ResultType<()> {
request(json!({"op": op, "path": path}))?;
Ok(())
}
pub fn remove_empty_dir(path: &str) -> ResultType<()> {
if !read_dir(path, true)?.entries.is_empty() {
bail!("Directory is not empty");
}
operation("delete", path)
}
pub fn remove_file(path: &str) -> ResultType<()> {
let entry = stat(path)?.ok_or(anyhow!("Document does not exist"))?;
if entry.entry_type.enum_value() != Ok(FileType::File) {
bail!("Cannot remove a directory as a file");
}
operation("delete", path)
}
pub fn remove_empty_tree(path: &str) -> ResultType<()> {
validate(path)?;
let tree_prefix = Path::new(ROOT).join("tree");
if Path::new(path).parent().and_then(Path::parent) == Some(tree_prefix.as_path()) {
bail!("Cannot delete a shared root");
}
let mut directories = vec![path.to_owned()];
let mut index = 0;
while index < directories.len() {
for entry in read_dir(&directories[index], true)?.entries {
if entry.entry_type.enum_value() != Ok(FileType::Dir) {
bail!("Directory is not empty");
}
directories.push(format!("{}/{}", directories[index], entry.name));
}
index += 1;
}
for directory in directories.into_iter().rev() {
remove_empty_dir(&directory)?;
}
Ok(())
}
pub fn rename(path: &str, name: &str) -> ResultType<()> {
super::validate_file_name_no_traversal(name)?;
request(json!({"op": "rename", "path": path, "name": name}))?;
Ok(())
}
#[cfg(any(target_os = "android", all(test, unix)))]
pub fn take_file(value: &Value) -> ResultType<std::fs::File> {
use std::convert::TryFrom;
use std::os::fd::FromRawFd;
let fd = value
.as_i64()
.and_then(|fd| i32::try_from(fd).ok())
.filter(|fd| *fd >= 0)
.ok_or(anyhow!("Invalid document descriptor"))?;
// Android hands off a duplicate; Java retains the provider's close/error channel.
Ok(unsafe { std::fs::File::from_raw_fd(fd) })
}
#[cfg(any(target_os = "android", all(test, unix)))]
pub(super) async fn open(
path: String,
) -> ResultType<(
tokio::fs::File,
super::android_descriptor::DocumentDescriptor,
Option<(u64, u64)>,
)> {
use std::os::unix::fs::MetadataExt;
let (file, descriptor, digest) = tokio::task::spawn_blocking(move || {
let token = request(json!({"op": "open", "path": path}))?;
let file = take_file(&token["fd"])?;
let descriptor = super::android_descriptor::DocumentDescriptor::new(&token)?;
let metadata = file.metadata()?;
// Stream inode timestamps do not identify the source document's version.
let digest = metadata
.is_file()
.then(|| (metadata.mtime().max(0) as u64, metadata.len()));
Ok::<_, hbb_common::anyhow::Error>((file, descriptor, digest))
})
.await??;
Ok((tokio::fs::File::from_std(file), descriptor, digest))
}
#[cfg(test)]
#[path = "tests/android_tests.rs"]
mod tests;
#[cfg(test)]
mod metadata_tests {
use super::*;
#[test]
fn negative_modification_time_is_unknown() {
for modified in [-1, 0, 1] {
let metadata = entry(json!({
"name": "notes.txt", "directory": false, "size": 12, "modified": modified
}))
.unwrap();
assert_eq!(metadata.modified_time, modified.max(0) as u64);
}
}
}
+55
View File
@@ -0,0 +1,55 @@
use super::android;
use hbb_common::{anyhow::anyhow, ResultType};
use serde_json::{json, Value};
use std::time::Duration;
const CLOSE_ERROR_LOG_INTERVAL: Duration = Duration::from_secs(60);
#[derive(Debug)]
pub(super) struct DocumentDescriptor {
id: Option<String>,
}
impl DocumentDescriptor {
pub(super) fn new(token: &Value) -> ResultType<Self> {
let id = token["descriptor"]
.as_str()
.ok_or(anyhow!("Missing document descriptor"))?;
Ok(Self {
id: Some(id.to_owned()),
})
}
pub(super) async fn close(mut self, error: &str) -> ResultType<()> {
let id = self.id.take().ok_or(anyhow!("Document already closed"))?;
let error = error.to_owned();
tokio::task::spawn_blocking(move || {
android::request(json!({
"op": "close", "descriptor": id, "error": error
}))
})
.await??;
Ok(())
}
}
impl Drop for DocumentDescriptor {
fn drop(&mut self) {
let Some(id) = self.id.take() else {
return;
};
// Aborted jobs must also release the provider's retained descriptor.
tokio::task::spawn_blocking(move || {
if let Err(error) = android::request(json!({
"op": "close", "descriptor": id, "error": "Document transfer interrupted"
})) {
hbb_common::throttled_log!(
CLOSE_ERROR_LOG_INTERVAL,
warn,
"Unable to release document descriptor: {}",
error
);
}
});
}
}
+296
View File
@@ -0,0 +1,296 @@
use super::{
android, android_descriptor::DocumentDescriptor, file_transfer_send_confirm_request,
DataSource, DataStream, FileTransferBlock, FileTransferSendConfirmRequest, TransferJob,
};
use hbb_common::{anyhow::anyhow, bail, compress::decompress, ResultType};
use serde_json::{json, Value};
use tokio::{
fs::File,
io::{AsyncSeekExt, AsyncWriteExt},
task::spawn_blocking,
};
#[derive(Debug, Default)]
pub(super) struct DocumentTransfer {
reader: Option<DocumentDescriptor>,
pending: Option<PendingWrite>,
confirmed_file: Option<i32>,
pub error: Option<String>,
}
#[derive(Debug)]
struct PendingWrite {
file: File,
descriptor: DocumentDescriptor,
token: Value,
path: String,
}
impl TransferJob {
pub fn is_document(&self) -> bool {
matches!(&self.data_source, DataSource::FilePath(path) if android::is_path(path))
}
pub(super) fn confirm_document(&mut self, request: &FileTransferSendConfirmRequest) {
if request.id != self.id {
return;
}
let overwrite = matches!(
request.union,
Some(file_transfer_send_confirm_request::Union::OffsetBlk(0))
| Some(file_transfer_send_confirm_request::Union::Skip(false))
);
self.document_transfer.confirmed_file = (overwrite
&& self.files.get(request.file_num as usize).is_some())
.then_some(request.file_num);
}
fn document_path(&self, file_num: usize) -> ResultType<String> {
let DataSource::FilePath(base) = &self.data_source else {
bail!("Not a document transfer");
};
let entry = self
.files
.get(file_num)
.ok_or(anyhow!("Wrong file number"))?;
super::validate_file_name_no_traversal(&entry.name)?;
Ok(Self::join(base, &entry.name).to_string_lossy().into_owned())
}
pub(super) async fn open_document_stream(&mut self) -> ResultType<bool> {
if let Some(error) = &self.document_transfer.error {
self.file_num = self.files.len() as i32;
self.data_stream.take();
bail!("{}", error);
}
if self.file_num as usize >= self.files.len() {
self.data_stream.take();
return Ok(true);
}
if self.data_stream.is_some() {
return Ok(false);
}
let result = android::open(self.document_path(self.file_num as usize)?).await;
self.file_confirmed = false;
self.file_is_waiting = false;
match result {
Ok((file, descriptor, digest)) => {
let entry = self
.files
.get_mut(self.file_num as usize)
.ok_or(anyhow!("Wrong file number"))?;
entry.modified_time = digest.map_or(0, |(modified, _)| modified);
entry.size = digest.map_or(entry.size, |(_, size)| size);
self.data_stream = Some(DataStream::FileStream(file));
self.document_transfer.reader = Some(descriptor);
}
Err(error) => {
self.fail_document_read(error.to_string());
return Err(error);
}
}
Ok(false)
}
pub(super) async fn finish_document_read(&mut self) -> ResultType<()> {
self.data_stream.take();
let descriptor = self
.document_transfer
.reader
.take()
.ok_or(anyhow!("No open document reader"))?;
let result = descriptor.close("").await;
if let Err(error) = &result {
self.fail_document_read(error.to_string());
}
result
}
pub(super) fn fail_document_read(&mut self, error: String) {
self.document_transfer.error = Some(error);
self.file_num = self.files.len() as i32;
self.file_confirmed = false;
self.file_is_waiting = false;
self.document_transfer.reader.take();
}
pub(super) async fn write_document(&mut self, block: FileTransferBlock) -> ResultType<()> {
if let Some(error) = &self.document_transfer.error {
bail!("{}", error);
}
let result = self.write_document_block(&block).await;
if let Err(error) = &result {
self.document_transfer.error = Some(error.to_string());
if let Err(cleanup_error) = self.cancel_document().await {
const CLEANUP_ERROR_LOG_INTERVAL: std::time::Duration =
std::time::Duration::from_secs(60);
hbb_common::throttled_log!(
CLEANUP_ERROR_LOG_INTERVAL,
warn,
"Failed to clean up document transfer {}: {}",
self.id,
cleanup_error
);
}
}
result
}
async fn write_document_block(&mut self, block: &FileTransferBlock) -> ResultType<()> {
if self.is_resume {
bail!("Document transfers must be restarted after interruption");
}
let path = self.document_path(block.file_num as usize)?;
if self.document_transfer.pending.as_ref().map(|p| &p.path) != Some(&path) {
self.finish_document().await?;
// Upload senders handle confirmation when overwrite detection is supported.
let overwrite = (!self.is_remote && self.enable_overwrite_detection)
|| self.document_transfer.confirmed_file.take() == Some(block.file_num);
self.document_transfer.pending = Some(begin_write(path, overwrite).await?);
self.file_num = block.file_num;
}
let pending = self
.document_transfer
.pending
.as_mut()
.ok_or(anyhow!("No open document"))?;
let data = if block.compressed {
std::borrow::Cow::Owned(decompress(&block.data))
} else {
std::borrow::Cow::Borrowed(block.data.as_ref())
};
pending.file.write_all(&data).await?;
self.finished_size += data.len() as u64;
self.transferred += block.data.len() as u64;
if block.data.is_empty() {
self.finish_document().await?;
}
Ok(())
}
pub async fn finish_document(&mut self) -> ResultType<()> {
if let Some(error) = &self.document_transfer.error {
bail!("{}", error);
}
let Some(pending) = self.document_transfer.pending.take() else {
return Ok(());
};
let result = finish_write(pending).await;
if let Err(error) = &result {
self.document_transfer.error = Some(error.to_string());
}
result
}
pub async fn cancel_document(&mut self) -> ResultType<()> {
let Some(pending) = self.document_transfer.pending.take() else {
return Ok(());
};
let PendingWrite {
file,
descriptor,
path,
token,
} = pending;
drop(file);
let result = descriptor.close("Document transfer canceled").await;
discard_write(path, token, result).await
}
pub(super) async fn seek_document(&mut self, offset: u64) -> ResultType<()> {
let Some(DataStream::FileStream(file)) = self.data_stream.as_mut() else {
bail!("Document receives must be restarted after interruption");
};
let entry = self
.files
.get(self.file_num as usize)
.ok_or(anyhow!("Wrong file number"))?;
if offset > 0 && entry.modified_time == 0 {
bail!(
"Cannot resume a document with an unknown modification time; restart the transfer"
);
}
file.seek(std::io::SeekFrom::Start(offset)).await?;
self.finished_size += offset;
self.transferred += offset;
Ok(())
}
}
async fn begin_write(path: String, overwrite: bool) -> ResultType<PendingWrite> {
spawn_blocking(move || {
let token = android::request(json!({
"op": "begin", "path": path, "overwrite": overwrite
}))?;
let file = android::take_file(&token["fd"])?;
let descriptor = DocumentDescriptor::new(&token)?;
Ok(PendingWrite {
file: File::from_std(file),
descriptor,
token,
path,
})
})
.await?
}
async fn finish_write(pending: PendingWrite) -> ResultType<()> {
let PendingWrite {
mut file,
descriptor,
path,
token,
} = pending;
let written: ResultType<()> = async {
file.flush().await?;
file.sync_all().await?;
Ok(())
}
.await;
drop(file);
let message = written
.as_ref()
.err()
.map(ToString::to_string)
.unwrap_or_default();
let closed = descriptor.close(&message).await;
let result = match (written, closed) {
(Err(error), Err(close_error)) => Err(anyhow!(
"{}; closing document failed: {}",
error,
close_error
)),
(Err(error), _) | (_, Err(error)) => Err(error),
_ => Ok(()),
};
if result.is_err() {
return discard_write(path, token, result).await;
}
spawn_blocking(move || {
android::request(json!({
"op": "finish", "path": path, "token": token
}))
})
.await??;
Ok(())
}
async fn discard_write(path: String, token: Value, result: ResultType<()>) -> ResultType<()> {
let cleanup: ResultType<()> = async {
spawn_blocking(move || {
android::request(json!({
"op": "discard", "path": path, "token": token
}))
})
.await??;
Ok(())
}
.await;
match (result, cleanup) {
(Err(error), Err(cleanup)) => {
bail!("{}; temporary document cleanup failed: {}", error, cleanup)
}
(Err(error), _) | (_, Err(error)) => Err(error),
_ => Ok(()),
}
}
+331
View File
@@ -0,0 +1,331 @@
use super::{
get_string, is_write_need_confirmation, join_validated_path, validate_file_name_no_traversal,
validate_no_symlink_components, DataSource, DataStream, DigestCheckResult, TransferJob,
};
use crate::message_proto::{
file_transfer_send_confirm_request, FileEntry, FileTransferBlock, FileTransferDigest,
FileTransferSendConfirmRequest, FileType,
};
use hbb_common::{anyhow::anyhow, bail, compress::decompress, ResultType};
use std::{
borrow::Cow,
io::ErrorKind,
path::{Path, PathBuf},
};
use tokio::{
fs::{self, OpenOptions},
io::{AsyncSeekExt, AsyncWriteExt},
};
const SINGLE_LINK_COUNT: u64 = 1;
#[derive(Default, Debug)]
pub(super) struct DownloadState {
pub(super) confirmation: Option<(i32, u32)>,
}
pub fn validate_listing(entries: &[FileEntry], peer_windows: bool) -> ResultType<()> {
for entry in entries {
let name = &entry.name;
if entry.entry_type.enum_value() == Ok(FileType::DirDrive)
&& matches!(name.as_bytes(), [drive, b':'] if drive.is_ascii_alphabetic())
{
continue;
}
if name.is_empty()
|| name == "."
|| name == ".."
|| name.contains('\0')
|| name.contains('/')
|| (peer_windows
&& (name.contains('\\')
|| matches!(name.as_bytes(), [drive, b':', ..] if drive.is_ascii_alphabetic())))
{
bail!("invalid file name in remote directory listing: {name}");
}
}
Ok(())
}
pub fn validate_download_name(path: &str, peer_windows: bool) -> ResultType<()> {
let separator = |c| c == '/' || (peer_windows && c == '\\');
let path = path.trim_end_matches(separator);
validate_component(path.rsplit(separator).next().unwrap_or(""))
}
fn validate_component(name: &str) -> ResultType<()> {
validate_file_name_no_traversal(name)?;
if name.is_empty() || name == "." || name.contains('/') {
bail!("invalid download file name: {name}");
}
#[cfg(windows)]
if name.contains(['\\', ':', '<', '>', '"', '|', '?', '*'])
|| name.ends_with('.')
|| name.ends_with(' ')
{
bail!("invalid Windows download file name: {name}");
}
Ok(())
}
pub(super) fn validated_target(base: &PathBuf, name: &str) -> ResultType<PathBuf> {
let parent = base
.parent()
.ok_or_else(|| anyhow!("download destination has no parent"))?;
let leaf = base
.file_name()
.and_then(|name| name.to_str())
.ok_or_else(|| anyhow!("invalid download destination"))?;
validate_component(leaf)?;
#[cfg(windows)]
for component in name.split(['/', '\\']).filter(|part| !part.is_empty()) {
validate_component(component)?;
}
validate_no_symlink_components(&parent.to_path_buf(), leaf)?;
let target = join_validated_path(base, name)?;
let parent = target
.parent()
.ok_or_else(|| anyhow!("download file has no parent"))?;
let leaf = target
.file_name()
.and_then(|name| name.to_str())
.ok_or_else(|| anyhow!("invalid download file name"))?;
for suffix in ["download", "digest"] {
validate_no_symlink_components(&parent.to_path_buf(), &format!("{leaf}.{suffix}"))?;
}
Ok(target)
}
fn remove_if_exists(path: &Path) -> ResultType<()> {
match std::fs::remove_file(path) {
Ok(()) => Ok(()),
Err(err) if err.kind() == ErrorKind::NotFound => Ok(()),
Err(err) => Err(err.into()),
}
}
async fn remove_if_exists_async(path: &Path) -> ResultType<()> {
match fs::remove_file(path).await {
Ok(()) => Ok(()),
Err(err) if err.kind() == ErrorKind::NotFound => Ok(()),
Err(err) => Err(err.into()),
}
}
async fn validate_resume_file(file: &tokio::fs::File) -> ResultType<()> {
let metadata = file.metadata().await?;
if !metadata.is_file() {
bail!("download resume staging path is not a regular file");
}
#[cfg(unix)]
let links = std::os::unix::fs::MetadataExt::nlink(&metadata);
#[cfg(windows)]
let links = {
use std::{mem::MaybeUninit, os::windows::io::AsRawHandle};
use winapi::{
shared::minwindef::FALSE,
um::fileapi::{GetFileInformationByHandle, BY_HANDLE_FILE_INFORMATION},
};
let file = file.try_clone().await?;
tokio::task::spawn_blocking(move || -> ResultType<u64> {
let mut information = MaybeUninit::<BY_HANDLE_FILE_INFORMATION>::uninit();
if unsafe {
GetFileInformationByHandle(file.as_raw_handle() as _, information.as_mut_ptr())
} == FALSE
{
return Err(std::io::Error::last_os_error().into());
}
Ok(u64::from(
unsafe { information.assume_init() }.nNumberOfLinks,
))
})
.await??
};
if links != SINGLE_LINK_COUNT {
bail!("hard-linked download resume staging file is not allowed");
}
Ok(())
}
impl TransferJob {
pub(super) fn is_download(&self) -> bool {
self.download.is_some()
}
pub fn download_target(&self, file_num: i32) -> ResultType<PathBuf> {
let entry = self
.files
.get(file_num as usize)
.ok_or_else(|| anyhow!("Wrong file number"))?;
let DataSource::FilePath(base) = &self.data_source else {
bail!("download destination is not a file path");
};
validated_target(base, &entry.name)
}
pub fn download_digest(
&mut self,
can_resume: bool,
digest: &FileTransferDigest,
) -> ResultType<DigestCheckResult> {
if self.file_num != digest.file_num && self.data_stream.is_some() {
let result = self.finish_download();
self.data_stream.take();
result?;
}
let target = self.download_target(digest.file_num)?;
let resume = can_resume && self.is_resume && !target.try_exists()?;
let result = is_write_need_confirmation(resume, &get_string(&target), digest)?;
if matches!(result, DigestCheckResult::NoSuchFile)
&& (Path::new(&format!("{}.download", target.display())).try_exists()?
|| Path::new(&format!("{}.digest", target.display())).try_exists()?)
{
return Ok(DigestCheckResult::NeedConfirm(FileTransferDigest {
id: digest.id,
file_num: digest.file_num,
..Default::default()
}));
}
Ok(result)
}
pub(super) fn confirm_download(&mut self, request: &FileTransferSendConfirmRequest) {
if request.id != self.id {
return;
}
let Some(download) = self.download.as_mut() else {
return;
};
download.confirmation = self.files.get(request.file_num as usize).and_then(|_| {
let offset = match request.union {
Some(file_transfer_send_confirm_request::Union::OffsetBlk(offset)) => offset,
Some(file_transfer_send_confirm_request::Union::Skip(false)) => 0,
_ => return None,
};
Some((request.file_num, offset))
});
}
fn download_confirmation_offset(&self, file_num: i32) -> Option<u32> {
let (confirmed, offset) = self.download.as_ref()?.confirmation.as_ref()?;
(*confirmed == file_num).then_some(*offset)
}
async fn start_download_file(&mut self, file_num: i32) -> ResultType<()> {
let result = self.finish_download();
self.data_stream.take();
result?;
let target = self.download_target(file_num)?;
let staging = PathBuf::from(format!("{}.download", target.display()));
let digest = PathBuf::from(format!("{}.digest", target.display()));
let confirmation = self.download_confirmation_offset(file_num);
if (fs::try_exists(&target).await?
|| fs::try_exists(&staging).await?
|| fs::try_exists(&digest).await?)
&& confirmation.is_none()
{
bail!("download overwrite requires confirmation");
}
if let Some(offset) = confirmation.filter(|offset| *offset > 0) {
return self.resume_download(file_num, offset).await;
}
if let Some(parent) = target.parent() {
fs::create_dir_all(parent).await?;
}
remove_if_exists_async(&staging).await?;
let file = OpenOptions::new()
.write(true)
.create_new(true)
.open(&staging)
.await?;
self.file_num = file_num;
self.data_stream = Some(DataStream::FileStream(file));
remove_if_exists_async(&digest).await?;
let mut metadata = OpenOptions::new()
.write(true)
.create_new(true)
.open(&digest)
.await?;
metadata
.write_all(serde_json::to_string(&self.digest)?.as_bytes())
.await?;
metadata.flush().await?;
Ok(())
}
async fn resume_download(&mut self, file_num: i32, offset: u32) -> ResultType<()> {
let target = self.download_target(file_num)?;
if fs::try_exists(&target).await? {
bail!("download overwrite requires confirmation");
}
let digest = fs::metadata(format!("{}.digest", target.display())).await?;
if !digest.is_file() {
bail!("download resume metadata is not a regular file");
}
let mut file = OpenOptions::new()
.write(true)
.open(format!("{}.download", target.display()))
.await?;
validate_resume_file(&file).await?;
if file.metadata().await?.len() != u64::from(offset) {
bail!("download resume offset does not match staging file size");
}
file.seek(std::io::SeekFrom::Start(u64::from(offset)))
.await?;
self.file_num = file_num;
self.data_stream = Some(DataStream::FileStream(file));
self.transferred += u64::from(offset);
self.finished_size += u64::from(offset);
Ok(())
}
pub(super) async fn write_download(&mut self, block: FileTransferBlock) -> ResultType<()> {
if block.id != self.id {
bail!("Wrong id");
}
if block.file_num as usize >= self.files.len() {
bail!("Wrong file number");
}
if block.file_num != self.file_num || self.data_stream.is_none() {
self.start_download_file(block.file_num).await?;
}
let data = if block.compressed {
Cow::Owned(decompress(&block.data))
} else {
Cow::Borrowed(block.data.as_ref())
};
let Some(DataStream::FileStream(stream)) = self.data_stream.as_mut() else {
bail!("download file stream is missing");
};
stream.write_all(&data).await?;
stream.flush().await?;
self.finished_size += data.len() as u64;
self.transferred += block.data.len() as u64;
Ok(())
}
pub fn finish_download(&self) -> ResultType<()> {
if !self.is_download() {
self.modify_time();
return Ok(());
}
if self.data_stream.is_none() {
return Ok(());
}
let target = self.download_target(self.file_num)?;
if target.try_exists()? && self.download_confirmation_offset(self.file_num) != Some(0) {
bail!("download overwrite requires confirmation");
}
std::fs::rename(format!("{}.download", target.display()), &target)?;
remove_if_exists(&PathBuf::from(format!("{}.digest", target.display())))?;
let entry = self
.files
.get(self.file_num as usize)
.ok_or_else(|| anyhow!("Wrong file number"))?;
filetime::set_file_mtime(
&target,
filetime::FileTime::from_unix_time(entry.modified_time as _, 0),
)?;
Ok(())
}
}
+324
View File
@@ -0,0 +1,324 @@
use super::*;
struct DownloadDir(PathBuf);
impl DownloadDir {
fn new() -> Self {
static NEXT_DIRECTORY: AtomicI32 = AtomicI32::new(1);
let sequence = NEXT_DIRECTORY.fetch_add(1, Ordering::Relaxed);
let nonce = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_nanos();
let path = std::env::temp_dir().join(format!(
"rustdesk_download_{}_{nonce}_{sequence}",
std::process::id()
));
std::fs::create_dir(&path).unwrap();
Self(path)
}
fn job(&self) -> TransferJob {
self.job_with_files(vec![FileEntry::default()])
}
fn job_with_files(&self, files: Vec<FileEntry>) -> TransferJob {
TransferJob::new_write(
1,
JobType::Generic,
"/remote/file.txt".into(),
DataSource::FilePath(self.0.join("file.txt")),
0,
false,
true,
true,
)
.with_files(files)
.unwrap()
}
}
impl Drop for DownloadDir {
fn drop(&mut self) {
std::fs::remove_dir_all(&self.0).unwrap();
}
}
fn block() -> FileTransferBlock {
FileTransferBlock {
id: 1,
file_num: 0,
data: b"received".to_vec().into(),
..Default::default()
}
}
fn approval(file_num: i32, offset: u32) -> FileTransferSendConfirmRequest {
FileTransferSendConfirmRequest {
id: 1,
file_num,
union: Some(file_transfer_send_confirm_request::Union::OffsetBlk(offset)),
..Default::default()
}
}
#[test]
fn download_listing_rejects_unsafe_names_and_keeps_drive_rows() {
for name in ["../outside", "/outside", ".", "..", "", "dir/file"] {
let entry = FileEntry {
name: name.into(),
..Default::default()
};
assert!(
download::validate_listing(&[entry], false).is_err(),
"{}",
name
);
}
let entries = [
FileEntry {
name: "report.txt".into(),
..Default::default()
},
FileEntry {
name: "report:notes".into(),
..Default::default()
},
FileEntry {
name: "C:".into(),
entry_type: FileType::DirDrive.into(),
..Default::default()
},
];
download::validate_listing(&entries, true).unwrap();
}
#[tokio::test]
async fn download_requires_confirmation_to_overwrite() {
let dir = DownloadDir::new();
let target = dir.0.join("file.txt");
std::fs::write(&target, b"original").unwrap();
let mut job = dir.job();
assert!(job.write(block()).await.is_err());
assert_eq!(std::fs::read(&target).unwrap(), b"original");
assert!(!dir.0.join("file.txt.download").exists());
job.confirm(&approval(0, 0)).await;
job.write(block()).await.unwrap();
assert!(job.set_files(vec![FileEntry::default()]).is_err());
job.finish_download().unwrap();
assert_eq!(std::fs::read(&target).unwrap(), b"received");
}
#[tokio::test]
async fn download_requires_separate_confirmation_for_each_existing_file() {
let dir = DownloadDir::new();
let mut job = dir.job_with_files(vec![
FileEntry {
name: "first.txt".into(),
..Default::default()
},
FileEntry {
name: "second.txt".into(),
..Default::default()
},
]);
job.write(block()).await.unwrap();
let second = dir.0.join("file.txt/second.txt");
std::fs::write(&second, b"original").unwrap();
assert!(job
.write(FileTransferBlock {
file_num: 1,
..block()
})
.await
.is_err());
assert_eq!(std::fs::read(&second).unwrap(), b"original");
assert_eq!(
std::fs::read(dir.0.join("file.txt/first.txt")).unwrap(),
b"received"
);
job.confirm(&approval(1, 0)).await;
job.write(FileTransferBlock {
file_num: 1,
..block()
})
.await
.unwrap();
job.finish_download().unwrap();
assert_eq!(std::fs::read(&second).unwrap(), b"received");
}
#[tokio::test]
async fn download_preserves_received_files_when_publication_fails() {
for next_is_digest in [false, true] {
let dir = DownloadDir::new();
let files = ["first.txt", "second.txt"]
.iter()
.map(|&name| FileEntry {
name: name.into(),
..Default::default()
})
.collect();
let mut job = dir.job_with_files(files);
job.write(block()).await.unwrap();
let target = dir.0.join("file.txt/first.txt");
std::fs::write(&target, b"existing").unwrap();
if next_is_digest {
assert!(job
.download_digest(
true,
&FileTransferDigest {
id: 1,
file_num: 1,
..Default::default()
},
)
.is_err());
} else {
assert!(job
.write(FileTransferBlock {
file_num: 1,
..block()
})
.await
.is_err());
}
job.remove_download_file();
assert_eq!(std::fs::read(target).unwrap(), b"existing");
assert_eq!(
std::fs::read(dir.0.join("file.txt/first.txt.download")).unwrap(),
b"received"
);
assert!(dir.0.join("file.txt/first.txt.digest").exists());
}
}
#[tokio::test]
async fn download_recovers_interrupted_transfer() {
for (resuming, changed) in [(false, false), (true, true), (true, false)] {
let dir = DownloadDir::new();
let mut digest = FileTransferDigest {
id: 1,
file_size: block().data.len() as _,
last_modified: 1,
..Default::default()
};
let mut interrupted = dir.job();
interrupted.set_digest(digest.file_size, digest.last_modified);
let partial = FileTransferBlock {
data: b"rec".to_vec().into(),
..block()
};
interrupted.write(partial).await.unwrap();
drop(interrupted);
let mut job = dir.job();
job.is_resume = resuming;
digest.last_modified += u64::from(changed);
job.set_digest(digest.file_size, digest.last_modified);
let confirmation = match job.download_digest(true, &digest).unwrap() {
DigestCheckResult::NeedConfirm(confirmation) => confirmation,
_ => panic!("interrupted download must require confirmation"),
};
let offset = if resuming && !changed {
b"rec".len()
} else {
0
};
assert_eq!(confirmation.is_identical, offset > 0);
assert_eq!(confirmation.transferred_size, offset as u64);
assert!(job.write(block()).await.is_err());
assert_eq!(
std::fs::read(dir.0.join("file.txt.download")).unwrap(),
b"rec"
);
job.confirm(&approval(0, offset as _)).await;
job.write(FileTransferBlock {
data: block().data.slice(offset..),
..block()
})
.await
.unwrap();
job.finish_download().unwrap();
assert_eq!(std::fs::read(dir.0.join("file.txt")).unwrap(), b"received");
}
}
#[tokio::test]
async fn download_does_not_publish_or_remove_unreceived_staging_files() {
let dir = DownloadDir::new();
let target = dir.0.join("file.txt");
let staging = dir.0.join("file.txt.download");
std::fs::write(&target, b"original").unwrap();
std::fs::write(&staging, b"another transfer").unwrap();
let job = dir.job();
job.modify_time();
job.remove_download_file();
assert_eq!(std::fs::read(&target).unwrap(), b"original");
assert_eq!(std::fs::read(&staging).unwrap(), b"another transfer");
let metadata_only = DownloadDir::new();
let metadata = metadata_only.0.join("file.txt.digest");
std::fs::write(&metadata, b"unrelated file").unwrap();
assert!(metadata_only.job().write(block()).await.is_err());
assert_eq!(std::fs::read(metadata).unwrap(), b"unrelated file");
}
#[test]
#[cfg(windows)]
fn download_rejects_windows_streams_and_ambiguous_components() {
let dir = DownloadDir::new();
for name in ["nested/file:stream", "nested/.. /outside", "nested/file."] {
assert!(
download::validated_target(&dir.0.join("docs"), name).is_err(),
"{}",
name
);
}
}
#[tokio::test]
#[cfg_attr(windows, ignore = "requires symlink privilege")]
async fn download_refuses_symlink_destination_directory() {
let dir = DownloadDir::new();
let outside = dir.0.join("outside");
let link = dir.0.join("file.txt");
std::fs::create_dir_all(&outside).unwrap();
#[cfg(unix)]
std::os::unix::fs::symlink(&outside, &link).unwrap();
#[cfg(windows)]
std::os::windows::fs::symlink_dir(&outside, &link).unwrap();
let mut job = dir.job_with_files(vec![FileEntry {
name: "child.txt".into(),
..Default::default()
}]);
assert!(job.write(block()).await.is_err());
job.modify_time();
assert!(!outside.join("child.txt").exists());
assert!(!outside.join("child.txt.download").exists());
}
#[tokio::test]
#[cfg_attr(windows, ignore = "requires symlink privilege")]
async fn download_refuses_linked_target_and_staging_files() {
for suffix in ["", ".download", ".digest"] {
let dir = DownloadDir::new();
let outside = dir.0.join("outside.txt");
let link = dir.0.join(format!("file.txt{suffix}"));
std::fs::write(&outside, b"original").unwrap();
#[cfg(unix)]
std::os::unix::fs::symlink(&outside, &link).unwrap();
#[cfg(windows)]
std::os::windows::fs::symlink_file(&outside, &link).unwrap();
let mut job = dir.job();
assert!(job.write(block()).await.is_err());
job.modify_time();
job.remove_download_file();
assert_eq!(std::fs::read(&outside).unwrap(), b"original");
assert!(std::fs::symlink_metadata(link)
.unwrap()
.file_type()
.is_symlink());
}
}
+288
View File
@@ -0,0 +1,288 @@
use super::*;
#[cfg(unix)]
#[path = "android_write_tests.rs"]
mod write_tests;
#[cfg(unix)]
use super::super::{
DataSource, FileTransferBlock, FileTransferSendConfirmRequest, JobType, TransferJob,
};
#[cfg(unix)]
fn provider(output: &Path, request: &str) -> ResultType<String> {
use std::{fs::File, os::fd::IntoRawFd};
let request: Value = serde_json::from_str(request)?;
let modified = output.metadata().map_or(0, |m| std::os::unix::fs::MetadataExt::mtime(&m));
let metadata = json!({"name": "notes.txt", "directory": false, "size": 12, "modified": modified});
let value = match request["op"].as_str() {
Some("home") => json!("/@rustdesk/tree/selected/Documents"),
Some("allowed") => json!(true),
Some("list") => json!([metadata]),
Some("stat") if request["path"].as_str().unwrap().ends_with(".txt") => metadata,
Some("stat") => json!({"name": "Documents", "directory": true, "size": 0, "modified": 0}),
Some("begin") if request["path"].as_str().unwrap().contains("write-error") => {
std::fs::write(output, b"partial")?;
json!({"fd": File::open(output)?.into_raw_fd(), "descriptor": request["path"]})
}
Some("begin") => {
if output.exists() && request["overwrite"].as_bool() == Some(false) {
return Ok(json!({"error": "Document overwrite requires confirmation"}).to_string());
}
json!({"fd": File::create(output)?.into_raw_fd(), "descriptor": request["path"]})
}
Some("open") => write_tests::open_source(output, &request)?,
Some("close")
if request["descriptor"]
.as_str()
.unwrap()
.ends_with("broken.txt") =>
{
return Ok(json!({"error": "Provider read failed"}).to_string())
}
Some("close") => json!(true),
Some("finish") if request["path"].as_str().unwrap().ends_with("failed.txt") => {
return Ok(json!({"error": "Publishing failed"}).to_string())
}
Some("finish") => json!(true),
Some("discard") => {
if request["path"].as_str().unwrap().contains("discard-error") {
bail!("Provider cleanup failed");
}
std::fs::remove_file(output)?;
json!(true)
}
_ => bail!("Unexpected operation"),
};
Ok(json!({"value": value}).to_string())
}
#[cfg(unix)]
fn receiving(path: &str) -> TransferJob {
receiving_files(path, vec![FileEntry::default()])
}
#[cfg(unix)]
fn receiving_files(path: &str, files: Vec<FileEntry>) -> TransferJob {
TransferJob::new_write(
1,
JobType::Generic,
String::new(),
DataSource::FilePath(path.into()),
0,
false,
true,
false,
)
.with_files(files)
.unwrap()
}
#[cfg(unix)]
fn block(file_num: i32, data: &[u8]) -> FileTransferBlock {
FileTransferBlock {
id: 1,
file_num,
data: data.to_vec().into(),
..Default::default()
}
}
#[cfg(unix)]
fn sending(path: &str, overwrite_detection: bool) -> TransferJob {
TransferJob::new_read(
2,
JobType::Generic,
String::new(),
DataSource::FilePath(path.into()),
0,
false,
false,
overwrite_detection,
)
.unwrap()
}
#[cfg(unix)]
async fn receive(path: &str, succeeds: bool, output: &Path) {
let mut job = receiving(path);
confirm_overwrite(&mut job, 0).await;
job.write(block(0, b"hello, world")).await.unwrap();
let eof = job.write(block(0, b"")).await;
assert_eq!(eof.is_ok(), succeeds);
assert_eq!(job.finish_document().await.is_ok(), succeeds);
assert_eq!(job.job_error().is_some(), !succeeds);
job.cancel_document().await.unwrap();
assert_eq!(std::fs::read(output).unwrap(), b"hello, world");
}
#[cfg(unix)]
async fn confirm_overwrite(job: &mut TransferJob, file_num: i32) {
let mut confirmation = FileTransferSendConfirmRequest {
id: job.id(),
file_num,
..Default::default()
};
confirmation.set_offset_blk(0);
job.confirm(&confirmation).await;
}
#[cfg(unix)]
async fn overwrite_requires_matching_confirmation(path: &str, output: &Path) {
std::fs::write(output, b"original").unwrap();
let mut job = receiving(&format!("{path}/notes.txt"));
assert!(job.write(block(0, b"")).await.is_err());
assert_eq!(std::fs::read(output).unwrap(), b"original");
let files = ["first.txt", "second.txt"]
.map(|name| FileEntry {
name: name.into(),
..Default::default()
})
.to_vec();
let mut job = receiving_files(path, files.clone());
confirm_overwrite(&mut job, 0).await;
assert!(job.set_files(vec![files[1].clone()]).is_err());
assert_eq!(job.files(), &files);
job.write(block(0, b"")).await.unwrap();
std::fs::write(output, b"second original").unwrap();
assert!(job.write(block(1, b"")).await.is_err());
assert_eq!(std::fs::read(output).unwrap(), b"second original");
let mut job = receiving_files(path, files);
confirm_overwrite(&mut job, 1).await;
job.write(block(1, b"")).await.unwrap();
assert!(std::fs::read(output).unwrap().is_empty());
}
#[cfg(unix)]
async fn host_upload_respects_overwrite_support(path: &str, output: &Path) {
for (overwrite_detection, exists) in [(false, false), (false, true), (true, true)] {
if exists {
std::fs::write(output, b"original").unwrap();
}
let mut job = TransferJob::new_write(
1,
JobType::Generic,
String::new(),
DataSource::FilePath(format!("{path}/notes.txt").into()),
0,
false,
false,
overwrite_detection,
)
.with_files(vec![FileEntry::default()])
.unwrap();
let result = job.write(block(0, b"replacement")).await;
if exists && !overwrite_detection {
assert_eq!(
result.unwrap_err().to_string(),
"Document overwrite requires confirmation"
);
assert_eq!(std::fs::read(output).unwrap(), b"original");
} else {
result.unwrap();
job.finish_document().await.unwrap();
assert_eq!(std::fs::read(output).unwrap(), b"replacement");
}
}
}
#[cfg(unix)]
#[tokio::test]
async fn selected_folder_transfers_directly_and_preserves_data_on_publish_failure() {
use std::time::{SystemTime, UNIX_EPOCH};
let output = std::env::temp_dir().join(format!(
"rustdesk-documents-{}",
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_nanos()
));
let provider_output = output.clone();
initialize(move |request| provider(&provider_output, request)).unwrap();
let path = "/@rustdesk/tree/selected/Documents";
assert!(allowed(path).unwrap() && allowed(&format!("{path}/notes.txt")).unwrap());
assert!(!allowed(&format!("{path}-private/notes.txt")).unwrap());
assert!(!allowed("/@rustdesk/tree/previous/Documents/notes.txt").unwrap());
let directory = super::super::read_dir(Path::new(path), false).unwrap();
assert_eq!(directory.path, path);
assert_eq!(directory.entries[0].name, "notes.txt");
let files = super::super::get_recursive_files(path, false).unwrap();
assert_eq!(files[0].name, "notes.txt");
assert_eq!(files[0].size, 12);
assert!(remove_empty_tree(path).unwrap_err().to_string() == "Cannot delete a shared root");
assert!(super::super::remove_file(path).is_err());
host_upload_respects_overwrite_support(path, &output).await;
overwrite_requires_matching_confirmation(path, &output).await;
for (name, succeeds) in [("notes.txt", true), ("failed.txt", false)] {
receive(&format!("{path}/{name}"), succeeds, &output).await;
}
let destination = format!("{path}/notes.txt");
let entry = stat(&destination).unwrap().unwrap();
let digest = super::super::FileTransferDigest {
file_size: entry.size,
last_modified: entry.modified_time,
..Default::default()
};
assert!(matches!(
super::super::is_write_need_confirmation(false, &destination, &digest).unwrap(),
super::super::DigestCheckResult::NeedConfirm(digest) if digest.is_identical
));
provider_error_at_eof(path).await;
send_and_cancel(path, &output).await;
write_tests::failed_block_cleans_pending_receive(path, &output).await;
write_tests::failed_finalization_discards_partial_data(path, &output).await;
write_tests::replacement_preserves_opened_digest(path, &output).await;
write_tests::changed_source_without_timestamp_rejects_resume(path, &output).await;
let mut empty = receiving(&format!("{path}/empty.txt"));
empty.write(block(0, b"")).await.unwrap();
assert_eq!(std::fs::metadata(&output).unwrap().len(), 0);
std::fs::remove_file(output).unwrap();
}
#[cfg(unix)]
async fn send_and_cancel(path: &str, output: &Path) {
let mut sender = sending(&format!("{path}/notes.txt"), false);
sender.init_data_stream_for_cm().await.unwrap();
assert_eq!(
sender.read().await.unwrap().unwrap().data.as_ref(),
b"hello, world"
);
assert!(sender.read().await.unwrap().unwrap().data.is_empty());
let mut canceled = receiving(&format!("{path}/canceled.txt"));
confirm_overwrite(&mut canceled, 0).await;
canceled.write(block(0, b"partial")).await.unwrap();
canceled.cancel_document().await.unwrap();
assert!(!output.exists());
}
#[cfg(unix)]
async fn provider_error_at_eof(path: &str) {
let mut sender = sending(&format!("{path}/broken.txt"), true);
assert!(sender.init_data_stream_for_cm().await.unwrap().is_some());
confirm_overwrite(&mut sender, 0).await;
assert!(sender.read().await.unwrap().is_some());
assert!(sender.read().await.is_err());
assert!(sender.init_data_stream_for_cm().await.is_err());
assert!(sender.read().await.unwrap().is_none());
assert!(sender.job_completed());
assert_eq!(sender.job_error().as_deref(), Some("Provider read failed"));
}
#[test]
fn document_paths_cannot_escape_the_selected_location() {
for path in [
"/@rustdesk/tree/id/folder/../secret",
"/@rustdesk//Download",
"/@rustdesk/tree/id/a\\b",
"/@rustdesk/file/id/report.txt",
"/@rustdesk/save/id/report.txt",
"/@rustdesk/Download/report.txt",
] {
assert!(validate(path).is_err(), "{}", path);
}
assert!(validate("/@rustdesk/tree/id/folder/report.txt").is_ok());
}
@@ -0,0 +1,153 @@
use super::*;
pub(super) fn open_source(output: &Path, request: &Value) -> ResultType<Value> {
use std::{fs::File, io::Write, os::fd::IntoRawFd};
let fd = if request["path"].as_str().unwrap().ends_with("stream.txt") {
let (reader, mut writer) = std::os::unix::net::UnixStream::pair()?;
writer.write_all(&std::fs::read(output)?)?;
reader.into_raw_fd()
} else {
let file = File::open(output)?;
let replacement = output.with_extension("replacement");
if replacement.exists() {
std::fs::rename(replacement, output)?;
}
file.into_raw_fd()
};
Ok(json!({"fd": fd, "descriptor": request["path"]}))
}
pub(super) async fn replacement_preserves_opened_digest(path: &str, output: &Path) {
use filetime::{set_file_mtime, FileTime};
std::fs::write(output, b"old contents").unwrap();
set_file_mtime(output, FileTime::from_unix_time(1, 0)).unwrap();
let replacement = output.with_extension("replacement");
std::fs::write(&replacement, b"new contents").unwrap();
set_file_mtime(&replacement, FileTime::from_unix_time(2, 0)).unwrap();
let path = format!("{path}/notes.txt");
let mut sender = sending(&path, true);
assert_eq!(
sender.init_data_stream_for_cm().await.unwrap(),
Some((1, 12))
);
confirm_overwrite(&mut sender, 0).await;
assert_eq!(
sender.read().await.unwrap().unwrap().data.as_ref(),
b"old contents"
);
assert!(sender.read().await.unwrap().unwrap().data.is_empty());
let mut next = sending(&path, true);
assert_eq!(next.init_data_stream_for_cm().await.unwrap(), Some((2, 12)));
}
pub(super) async fn failed_block_cleans_pending_receive(path: &str, output: &Path) {
for name in ["write-error.txt", "write-error-broken.txt"] {
let mut job = receiving(&format!("{path}/{name}"));
job.is_remote = false;
let block = block(0, b"more data");
// Tokio queues the first write and reports its I/O failure on the next block.
job.write(block.clone()).await.unwrap();
assert_eq!(std::fs::read(output).unwrap(), b"partial");
let error = job.write(block).await.unwrap_err();
assert!(error.downcast_ref::<std::io::Error>().is_some());
assert_eq!(job.job_error(), Some(error.to_string()));
assert!(
!output.exists(),
"A failed receive must discard partial data"
);
}
}
pub(super) async fn failed_finalization_discards_partial_data(path: &str, output: &Path) {
for name in ["write-error.txt", "broken.txt", "discard-error-broken.txt"] {
let mut job = receiving(&format!("{path}/{name}"));
confirm_overwrite(&mut job, 0).await;
job.write(block(0, b"partial data")).await.unwrap();
let error = job.finish_document().await.unwrap_err();
assert_eq!(job.job_error(), Some(error.to_string()));
if name.ends_with("broken.txt") {
assert!(error.to_string().contains("Provider read failed"));
} else {
assert!(error.downcast_ref::<std::io::Error>().is_some());
}
if name.starts_with("discard-error") {
assert!(error.to_string().contains("Provider cleanup failed"));
assert!(output.exists());
std::fs::remove_file(output).unwrap();
} else {
assert!(
!output.exists(),
"A failed finalization must discard partial data"
);
}
}
}
pub(super) async fn changed_source_without_timestamp_rejects_resume(path: &str, output: &Path) {
std::fs::write(output, b"old contents").unwrap();
filetime::set_file_mtime(output, filetime::FileTime::from_unix_time(0, 0)).unwrap();
stale_metadata_uses_current_digest(&format!("{path}/notes.txt")).await;
let path = format!("{path}/stream.txt");
let mut sender = sending(&path, true);
let original_digest = sender.init_data_stream_for_cm().await.unwrap();
assert_eq!(original_digest, Some((0, b"old contents".len() as u64)));
confirm_overwrite(&mut sender, 0).await;
assert_eq!(
sender.read().await.unwrap().unwrap().data.as_ref(),
b"old contents"
);
drop(sender);
std::fs::write(output, b"new contents").unwrap();
let mut resumed = sending(&path, true);
assert_eq!(
resumed.init_data_stream_for_cm().await.unwrap(),
original_digest
);
let mut confirmation = FileTransferSendConfirmRequest {
id: resumed.id(),
..Default::default()
};
confirmation.set_offset_blk(b"old ".len() as u32);
resumed.confirm(&confirmation).await;
assert_eq!(
resumed.job_error().as_deref(),
Some("Cannot resume a document with an unknown modification time; restart the transfer")
);
assert!(resumed.read().await.unwrap().is_none());
assert!(resumed.job_completed());
let mut fresh = sending(&path, true);
fresh.init_data_stream_for_cm().await.unwrap();
confirm_overwrite(&mut fresh, 0).await;
assert_eq!(
fresh.read().await.unwrap().unwrap().data.as_ref(),
b"new contents"
);
assert!(fresh.read().await.unwrap().unwrap().data.is_empty());
std::fs::remove_file(output).unwrap();
}
async fn stale_metadata_uses_current_digest(path: &str) {
for (size, modified_time) in [(12, 1), (13, 0)] {
let mut sender = sending(path, true)
.with_files(vec![FileEntry {
size,
modified_time,
..Default::default()
}])
.unwrap();
assert_eq!(
sender.init_data_stream_for_cm().await.unwrap(),
Some((0, b"old contents".len() as u64))
);
confirm_overwrite(&mut sender, 0).await;
assert_eq!(
sender.read().await.unwrap().unwrap().data.as_ref(),
b"old contents"
);
assert!(sender.read().await.unwrap().unwrap().data.is_empty());
}
}
-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() {
-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
@@ -506,7 +506,43 @@ pub extern "system" fn Java_ffi_FFI_onAppStart(mut env: JNIEnv, _class: JClass,
let java_vm = jvm.get_java_vm_pointer() as *mut c_void;
let context_jobject = context.as_obj().as_raw() as *mut c_void;
*APPLICATION_CONTEXT.write().unwrap() = Some(context);
*JVM.write().unwrap() = Some(jvm);
if let Err(error) = base::fs::android::initialize(call_document_storage) {
log::error!("Unable to initialize document storage: {}", error);
}
try_init_rustls_platform_verifier(&mut env, context_jobject);
}
}
}
fn call_document_storage(request: &str) -> hbb_common::ResultType<String> {
use hbb_common::anyhow::anyhow;
const LOCAL_REFS: i32 = 4;
let context = APPLICATION_CONTEXT
.read()
.unwrap()
.clone()
.ok_or(anyhow!("Android application context is unavailable"))?;
let jvm = JVM.read().unwrap();
let jvm = jvm.as_ref().ok_or(anyhow!("Android VM is unavailable"))?;
let mut env = jvm.attach_current_thread_as_daemon()?;
let result = env.with_local_frame(LOCAL_REFS, |env| -> JniResult<String> {
let request = env.new_string(request)?;
let value = env
.call_method(
&context,
"rustDocumentStorage",
"(Ljava/lang/String;)Ljava/lang/String;",
&[JValue::Object(&JObject::from(request))],
)?
.l()?;
let value = JString::from(value);
let value = env.get_string(&value)?;
Ok(value.into())
});
if result.is_err() && env.exception_check()? {
env.exception_clear()?;
}
Ok(result?)
}
-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 {
+1 -187
View File
@@ -795,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.
@@ -845,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)]
@@ -924,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
@@ -992,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.
@@ -1019,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.
@@ -1050,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() {
@@ -1062,65 +935,6 @@ 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];
unsafe extern "C" fn plane_rotation(_: *mut drmtap_ctx, rotation: *mut u32) -> c_int {
*rotation = PLANE.load(Ordering::SeqCst);
0
}
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_desc(
_: *mut drmtap_ctx,
d: *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
}
#[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,
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");
}
}
#[cfg(test)]
-41
View File
@@ -464,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;
@@ -528,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));
}
}
+4 -1
View File
@@ -25,6 +25,9 @@ use hwcodec::{
},
};
#[cfg(all(test, windows, feature = "vram"))]
mod tests;
const DEFAULT_PIXFMT: AVPixelFormat = AVPixelFormat::AV_PIX_FMT_NV12;
pub const DEFAULT_FPS: i32 = 30;
const DEFAULT_GOP: i32 = i32::MAX;
@@ -236,7 +239,7 @@ impl HwRamEncoder {
data.append(v);
Ok(data)
}
Err(_) => Ok(Vec::<EncodeFrame>::new()),
Err(code) => Err(anyhow!("RAM encode failed: {}", code)),
}
}
+130
View File
@@ -0,0 +1,130 @@
use super::{CodecInfo, HwCodecConfig, CONFIG, CONFIG_SET_BY_IPC};
use crate::{
codec::enable_vram_option,
vram::{VRamDecoder, VRamEncoder},
AdapterDevice, CodecFormat,
};
use base::config::keys::{OPTION_ALLOW_D3D_RENDER, OPTION_ENABLE_HWCODEC};
use hbb_common::config::{OVERWRITE_LOCAL_SETTINGS, OVERWRITE_SETTINGS};
use hwcodec::{
common::{DataFormat, Driver},
vram::{DecodeContext, FeatureContext},
};
use std::{collections::HashMap, mem};
struct RestoreConfig {
config: Option<HwCodecConfig>,
set_by_ipc: bool,
options: HashMap<String, String>,
local_options: HashMap<String, String>,
}
impl Drop for RestoreConfig {
fn drop(&mut self) {
*CONFIG.lock().unwrap() = self.config.take();
*CONFIG_SET_BY_IPC.lock().unwrap() = self.set_by_ipc;
*OVERWRITE_SETTINGS.write().unwrap() = mem::take(&mut self.options);
*OVERWRITE_LOCAL_SETTINGS.write().unwrap() = mem::take(&mut self.local_options);
}
}
fn add_backend(config: &mut HwCodecConfig, driver: Driver, vendor: Driver, format: DataFormat) {
let luid = match vendor {
Driver::NV => 1,
Driver::MFX => 2,
Driver::AMF => 3,
_ => unreachable!(),
};
config.vram_encode.push(FeatureContext {
driver: driver.clone(),
vendor: vendor.clone(),
luid,
data_format: format,
});
config.vram_decode.push(DecodeContext {
device: None,
driver,
vendor,
luid,
data_format: format,
});
}
#[test]
fn cached_sdk_entries_are_ignored_before_check_completes() {
let _restore = RestoreConfig {
config: CONFIG.lock().unwrap().take(),
set_by_ipc: mem::replace(&mut *CONFIG_SET_BY_IPC.lock().unwrap(), false),
options: mem::take(&mut *OVERWRITE_SETTINGS.write().unwrap()),
local_options: mem::take(&mut *OVERWRITE_LOCAL_SETTINGS.write().unwrap()),
};
OVERWRITE_SETTINGS
.write()
.unwrap()
.insert(OPTION_ENABLE_HWCODEC.into(), "Y".into());
OVERWRITE_LOCAL_SETTINGS
.write()
.unwrap()
.insert(OPTION_ALLOW_D3D_RENDER.into(), "Y".into());
assert!(enable_vram_option(false));
let formats = [
(CodecFormat::H264, DataFormat::H264),
(CodecFormat::H265, DataFormat::H265),
];
let mut cached = HwCodecConfig::default();
for (_, format) in formats {
// A RAM fallback keeps this selection test independent of attached displays.
cached.ram_encode.push(CodecInfo {
format,
..Default::default()
});
for vendor in [Driver::NV, Driver::MFX, Driver::AMF] {
add_backend(&mut cached, vendor.clone(), vendor, format);
}
}
*CONFIG.lock().unwrap() = Some(cached.clone());
assert!(!HwCodecConfig::already_set());
for (format, _) in formats {
assert!(VRamEncoder::available(format).is_empty());
for luid in 1..=3 {
assert!(VRamDecoder::try_get(format, Some(luid)).is_none());
}
}
assert_eq!(
VRamDecoder::possible_available_without_check(),
(false, false)
);
for (index, &(format, data_format)) in formats.iter().enumerate() {
for vendor in [Driver::NV, Driver::MFX, Driver::AMF] {
add_backend(&mut cached, Driver::FFMPEG, vendor, data_format);
}
*CONFIG.lock().unwrap() = Some(cached.clone());
let encoders = VRamEncoder::available(format);
assert_eq!(encoders.len(), 3);
for encoder in encoders {
assert_eq!(encoder.driver, Driver::FFMPEG);
let device = AdapterDevice {
luid: encoder.luid,
..Default::default()
};
assert_eq!(VRamEncoder::try_get(&device, format), Some(encoder.clone()));
let decoder = VRamDecoder::try_get(format, Some(encoder.luid)).unwrap();
assert_eq!(decoder.driver, Driver::FFMPEG);
assert_eq!(decoder.vendor, encoder.vendor);
assert_eq!(decoder.data_format, data_format);
}
assert!(VRamDecoder::available(format, Some(99)).is_empty());
assert!(VRamDecoder::available(format, None).is_empty());
assert_eq!(
VRamDecoder::possible_available_without_check(),
(true, index == 1)
);
}
assert!(!HwCodecConfig::already_set());
assert_eq!(
HwCodecConfig::get().vram_encode.len(),
cached.vram_encode.len()
);
}
+2
View File
@@ -209,6 +209,8 @@ impl Frame<'_> {
pub enum EncodeInput<'a> {
YUV(&'a [u8]),
Texture((*mut c_void, usize)),
#[cfg(all(windows, feature = "vram"))]
Repeat,
}
impl<'a> EncodeInput<'a> {
+12 -1
View File
@@ -20,6 +20,17 @@ use std::{ptr, slice};
generate_call_macro!(call_vpx, false);
generate_call_ptr_macro!(call_vpx_ptr);
#[derive(Debug)]
pub struct VpxNoOutput;
impl std::fmt::Display for VpxNoOutput {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("no valid frame")
}
}
impl std::error::Error for VpxNoOutput {}
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
pub enum VpxVideoCodecId {
VP8,
@@ -187,7 +198,7 @@ impl EncoderApi for VpxEncoder {
if frames.len() > 0 {
Ok(VpxEncoder::create_video_frame(self.id, frames))
} else {
Err(anyhow!("no valid frame"))
Err(VpxNoOutput.into())
}
}
+43 -41
View File
@@ -15,8 +15,9 @@ use hbb_common::{
bytes::Bytes,
log, ResultType,
};
pub use hwcodec::common::Driver;
use hwcodec::{
common::{DataFormat, Driver, MAX_GOP},
common::{DataFormat, MAX_GOP},
vram::{
decode::{self, DecodeFrame, Decoder},
encode::{self, EncodeFrame, Encoder},
@@ -24,6 +25,9 @@ use hwcodec::{
},
};
#[cfg(test)]
mod repeat_tests;
// https://www.reddit.com/r/buildapc/comments/d2m4ny/two_graphics_cards_two_monitors/
// https://www.reddit.com/r/techsupport/comments/t2v9u6/dual_monitor_setup_with_dual_gpu/
// https://cybersided.com/two-monitors-two-gpus/
@@ -48,8 +52,6 @@ pub struct VRamEncoder {
pub format: DataFormat,
ctx: EncodeContext,
bitrate: u32,
last_frame_len: usize,
same_bad_len_counter: usize,
}
impl EncoderApi for VRamEncoder {
@@ -83,8 +85,6 @@ impl EncoderApi for VRamEncoder {
ctx,
format: config.feature.data_format,
bitrate,
last_frame_len: 0,
same_bad_len_counter: 0,
}),
Err(_) => Err(anyhow!(format!("Failed to create encoder"))),
}
@@ -98,7 +98,15 @@ impl EncoderApi for VRamEncoder {
frame: EncodeInput,
ms: i64,
) -> ResultType<base::message_proto::VideoFrame> {
let (texture, rotation) = frame.texture()?;
#[cfg(all(windows, feature = "vram"))]
let repeated = matches!(&frame, EncodeInput::Repeat);
#[cfg(not(all(windows, feature = "vram")))]
let repeated = false;
let (texture, rotation) = if repeated {
(std::ptr::null_mut(), 0)
} else {
frame.texture()?
};
if rotation != 0 {
// to-do: support rotation
// Both the encoder and display(w,h) information need to be changed.
@@ -106,10 +114,12 @@ impl EncoderApi for VRamEncoder {
}
let mut vf = VideoFrame::new();
let mut frames = Vec::new();
for frame in self
.encode(texture, ms)
.with_context(|| "Failed to encode")?
{
let result = if repeated {
self.encode_repeat(ms)
} else {
self.encode(texture, ms)
};
for frame in result.with_context(|| "Failed to encode")? {
frames.push(EncodedVideoFrame {
data: Bytes::from(frame.data),
pts: frame.pts,
@@ -117,29 +127,10 @@ impl EncoderApi for VRamEncoder {
..Default::default()
});
}
if repeated && frames.is_empty() {
return Ok(vf);
}
if frames.len() > 0 {
// This kind of problem is occurred after a period of time when using the AMD SDK,
// the encoding length is fixed at about 40, and the picture is still
const MIN_BAD_LEN: usize = 100;
const MAX_BAD_COUNTER: usize = 30;
let this_frame_len = frames[0].data.len();
if self.ctx.f.driver == Driver::AMF
&& this_frame_len < MIN_BAD_LEN
&& this_frame_len == self.last_frame_len
{
self.same_bad_len_counter += 1;
if self.same_bad_len_counter >= MAX_BAD_COUNTER {
log::info!(
"{} times encoding len is {}, switch",
self.same_bad_len_counter,
self.last_frame_len
);
bail!(crate::codec::ENCODE_NEED_SWITCH);
}
} else {
self.same_bad_len_counter = 0;
}
self.last_frame_len = this_frame_len;
let frames = EncodedVideoFrames {
frames: frames.into(),
..Default::default()
@@ -244,6 +235,7 @@ impl VRamEncoder {
let v: Vec<_> = crate::hwcodec::HwCodecConfig::get()
.vram_encode
.drain(..)
.filter(|c| c.driver == Driver::FFMPEG)
.filter(|c| c.data_format == data_format)
.collect();
if crate::hwcodec::HwRamEncoder::try_get(format).is_some() {
@@ -274,14 +266,21 @@ impl VRamEncoder {
}
}
pub fn encode(&mut self, texture: *mut c_void, ms: i64) -> ResultType<Vec<EncodeFrame>> {
pub fn encode(
&mut self,
texture: *mut c_void,
ms: i64,
) -> ResultType<std::vec::Drain<'_, EncodeFrame>> {
match self.encoder.encode(texture, ms) {
Ok(v) => {
let mut data = Vec::<EncodeFrame>::new();
data.append(v);
Ok(data)
}
Err(_) => Ok(Vec::<EncodeFrame>::new()),
Ok(frames) => Ok(frames.drain(..)),
Err(code) => Err(anyhow!("VRAM encode failed: {}", code)),
}
}
fn encode_repeat(&mut self, ms: i64) -> ResultType<std::vec::Drain<'_, EncodeFrame>> {
match self.encoder.encode_repeat(ms) {
Ok(frames) => Ok(frames.drain(..)),
Err(code) => Err(anyhow!("VRAM repeat encode failed: {}", code)),
}
}
@@ -340,6 +339,7 @@ impl VRamDecoder {
crate::hwcodec::HwCodecConfig::get()
.vram_decode
.drain(..)
.filter(|c| c.driver == Driver::FFMPEG)
.filter(|c| c.data_format == data_format && c.luid == luid && luid != 0)
.collect()
}
@@ -350,8 +350,10 @@ impl VRamDecoder {
}
let v = crate::hwcodec::HwCodecConfig::get().vram_decode;
(
v.iter().any(|d| d.data_format == DataFormat::H264),
v.iter().any(|d| d.data_format == DataFormat::H265),
v.iter()
.any(|d| d.driver == Driver::FFMPEG && d.data_format == DataFormat::H264),
v.iter()
.any(|d| d.driver == Driver::FFMPEG && d.data_format == DataFormat::H265),
)
}
+244
View File
@@ -0,0 +1,244 @@
use super::VRamEncoder;
use crate::{codec::EncoderApi, EncodeInput};
use base::message_proto::{video_frame, VideoFrame};
use hwcodec::{
common::{DataFormat, Driver, MAX_GOP},
ffmpeg::AVHWDeviceType,
ffmpeg_ram::decode::{DecodeContext, Decoder},
vram::{encode::Encoder, DynamicContext, EncodeContext, FeatureContext},
};
use std::{mem, ptr};
use winapi::{
shared::{
dxgi::{CreateDXGIFactory1, IDXGIFactory1},
dxgiformat::DXGI_FORMAT_B8G8R8A8_UNORM,
dxgitype::DXGI_SAMPLE_DESC,
winerror::DXGI_ERROR_NOT_FOUND,
},
um::{d3d11::*, d3dcommon::D3D_DRIVER_TYPE_UNKNOWN, unknwnbase::IUnknown},
Interface,
};
struct Com<T>(*mut T);
impl<T> Drop for Com<T> {
fn drop(&mut self) {
if !self.0.is_null() {
unsafe { (*(self.0 as *mut IUnknown)).Release() };
}
}
}
unsafe fn texture(
device: *mut ID3D11Device,
width: u32,
height: u32,
shade: u8,
) -> Com<ID3D11Texture2D> {
let pixels = pixels(width, height, shade);
let desc = D3D11_TEXTURE2D_DESC {
Width: width,
Height: height,
MipLevels: 1,
ArraySize: 1,
Format: DXGI_FORMAT_B8G8R8A8_UNORM,
SampleDesc: DXGI_SAMPLE_DESC {
Count: 1,
Quality: 0,
},
Usage: D3D11_USAGE_DEFAULT,
BindFlags: D3D11_BIND_SHADER_RESOURCE | D3D11_BIND_RENDER_TARGET,
CPUAccessFlags: 0,
MiscFlags: D3D11_RESOURCE_MISC_SHARED,
};
let data = D3D11_SUBRESOURCE_DATA {
pSysMem: pixels.as_ptr() as _,
SysMemPitch: width * 4,
SysMemSlicePitch: 0,
};
let mut raw = ptr::null_mut();
assert_eq!((*device).CreateTexture2D(&desc, &data, &mut raw), 0);
Com(raw)
}
fn pixels(width: u32, height: u32, shade: u8) -> Vec<u8> {
[shade, shade, shade, 255].repeat((width * height) as usize)
}
fn check_picture(
decoder: &mut Decoder,
frame: VideoFrame,
width: u32,
height: u32,
bright: bool,
pts: i64,
) {
let frames = match frame.union.unwrap() {
video_frame::Union::H264s(frames) | video_frame::Union::H265s(frames) => frames,
_ => panic!("unexpected codec"),
};
let mut decoded = 0;
for packet in frames.frames {
assert_eq!(packet.pts, pts);
for picture in decoder.decode(&packet.data).unwrap() {
assert_eq!((picture.width, picture.height), (width as _, height as _));
let center = (height as usize / 2) * picture.linesize[0] as usize + width as usize / 2;
let y = picture.data[0][center];
assert!(
if bright { y > 160 } else { y < 90 },
"stale or overwritten pixels: expected bright={}, got Y={}",
bright,
y
);
decoded += 1;
}
}
assert!(decoded > 0, "encoder output did not decode to a picture");
}
#[test]
#[ignore = "requires hardware H.264/H.265 encoders; run explicitly on GPU hosts"]
fn hardware_repeats_own_pixels_and_reset_on_recreation() {
unsafe {
let mut raw_factory = ptr::null_mut();
assert_eq!(
CreateDXGIFactory1(&IDXGIFactory1::uuidof(), &mut raw_factory),
0
);
let factory = Com(raw_factory as *mut IDXGIFactory1);
let mut tested = 0;
for index in 0.. {
let mut raw_adapter = ptr::null_mut();
let result = (*factory.0).EnumAdapters1(index, &mut raw_adapter);
if result == DXGI_ERROR_NOT_FOUND {
break;
}
assert_eq!(result, 0);
let adapter = Com(raw_adapter);
let mut desc = mem::zeroed();
assert_eq!((*adapter.0).GetDesc1(&mut desc), 0);
let vendor = match desc.VendorId {
0x10de => Driver::NV,
0x1002 => Driver::AMF,
0x8086 => Driver::MFX,
_ => continue,
};
let luid = ((desc.AdapterLuid.HighPart as i64) << 32) | desc.AdapterLuid.LowPart as i64;
let mut raw_device = ptr::null_mut();
let mut raw_context = ptr::null_mut();
assert_eq!(
D3D11CreateDevice(
adapter.0 as _,
D3D_DRIVER_TYPE_UNKNOWN,
ptr::null_mut(),
D3D11_CREATE_DEVICE_BGRA_SUPPORT | D3D11_CREATE_DEVICE_VIDEO_SUPPORT,
ptr::null(),
0,
D3D11_SDK_VERSION,
&mut raw_device,
ptr::null_mut(),
&mut raw_context,
),
0
);
let device = Com(raw_device);
let context = Com(raw_context);
for driver in [Driver::FFMPEG, vendor.clone()] {
for format in [DataFormat::H264, DataFormat::H265] {
for (width, height) in [(320, 240), (640, 360)] {
let ctx = EncodeContext {
f: FeatureContext {
driver: driver.clone(),
vendor: vendor.clone(),
luid,
data_format: format,
},
d: DynamicContext {
device: Some(device.0 as _),
width: width as _,
height: height as _,
kbitrate: 1000,
framerate: 30,
gop: MAX_GOP as _,
},
};
let native = match Encoder::new(ctx.clone()) {
Ok(encoder) => encoder,
Err(()) => {
eprintln!(
"SKIP unavailable {:?} {:?} {:?} adapter={luid:#x}",
vendor, driver, format
);
continue;
}
};
let mut encoder = VRamEncoder {
encoder: native,
format,
ctx,
bitrate: 1000,
};
assert!(encoder.encode_to_message(EncodeInput::Repeat, 0).is_err());
assert!(encoder
.encode_to_message(EncodeInput::Texture((ptr::null_mut(), 0)), 0)
.is_err());
let mut decoder = Decoder::new(DecodeContext {
name: if format == DataFormat::H264 {
"h264"
} else {
"hevc"
}
.into(),
device_type: AVHWDeviceType::AV_HWDEVICE_TYPE_NONE,
thread_count: 1,
})
.unwrap();
let source = texture(device.0, width, height, 32);
let frame = encoder
.encode_to_message(EncodeInput::Texture((source.0 as _, 0)), 0)
.unwrap();
check_picture(&mut decoder, frame, width, height, false, 0);
// Overwrite and release the capture resource before any repeats.
let overwritten = pixels(width, height, 224);
(*context.0).UpdateSubresource(
source.0 as _,
0,
ptr::null(),
overwritten.as_ptr() as _,
width * 4,
0,
);
(*context.0).Flush();
drop(source);
for count in 1..=100 {
let pts = count * 100;
let frame =
encoder.encode_to_message(EncodeInput::Repeat, pts).unwrap();
check_picture(&mut decoder, frame, width, height, false, pts);
}
let source = texture(device.0, width, height, 224);
let frame = encoder
.encode_to_message(EncodeInput::Texture((source.0 as _, 0)), 10100)
.unwrap();
check_picture(&mut decoder, frame, width, height, true, 10100);
drop(source);
encoder.encoder.set_bitrate(1500).unwrap();
let frame = encoder
.encode_to_message(EncodeInput::Repeat, 10200)
.unwrap();
check_picture(&mut decoder, frame, width, height, true, 10200);
eprintln!(
"PASS {:?} {:?} {:?} {width}x{height} adapter={luid:#x}",
vendor, driver, format
);
tested += 1;
}
}
}
}
assert!(tested > 0, "no hardware encoders were tested");
eprintln!("Validated {tested} encoder/codec/resolution combinations");
}
}
-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)]
);
}
}
+4 -41
View File
@@ -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() {
@@ -1802,7 +1804,7 @@ fn sort_streams(
#[cfg(test)]
mod tests {
use super::{corrected_origin, reconciled_origin, stage_err, WaylandDisplayInfo};
use super::{corrected_origin, WaylandDisplayInfo};
fn output(x: i32, y: i32, mode: (i32, i32)) -> WaylandDisplayInfo {
WaylandDisplayInfo {
@@ -1867,43 +1869,4 @@ mod tests {
Some((2560, 0))
);
}
#[test]
fn a_cached_position_is_not_overridden_by_an_unmeasured_size() {
let outputs = [output(0, 0, (1440, 900)), output(1920, 0, (2880, 1800))];
// Restored from the cache, or sent by the portal: get_res() failed, so the size is the
// portal size, here the mode of the other output, and it moves nothing.
assert_eq!(
reconciled_origin((1920, 0), (1440, 900), false, &outputs),
None
);
// A measured size still moves a position that names no output of that size: xdph sends
// (0, 0) for every stream.
let pair = [output(0, 0, (1920, 1080)), output(1920, 0, (2880, 1800))];
assert_eq!(
reconciled_origin((0, 0), (2880, 1800), true, &pair),
Some((1920, 0))
);
}
#[test]
fn stage_err_keeps_the_detail_safe_for_a_placeholder() {
assert_eq!(
stage_err("start", "declined", ""),
"wl-stage:start:declined:"
);
// Braces of its own would break the placeholder lookup on the peer.
assert_eq!(
stage_err("create-session", "dbus", "org.freedesktop.{Error}"),
"wl-stage:create-session:dbus:org.freedesktop.Error"
);
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))
);
}
}
+28 -5
View File
@@ -12,7 +12,12 @@ use super::{Display, Rect, Server};
pub struct DisplayIter {
outer: xcb_screen_iterator_t,
inner: Option<(xcb_randr_monitor_info_iterator_t, xcb_window_t)>,
// The monitor iterator points into the reply, so the reply is freed only when moving on.
inner: Option<(
xcb_randr_monitor_info_iterator_t,
xcb_window_t,
*mut xcb_randr_get_monitors_reply_t,
)>,
server: Rc<Server>,
}
@@ -30,7 +35,11 @@ impl DisplayIter {
fn next_screen(
outer: &mut xcb_screen_iterator_t,
server: &Server,
) -> Option<(xcb_randr_monitor_info_iterator_t, xcb_window_t)> {
) -> Option<(
xcb_randr_monitor_info_iterator_t,
xcb_window_t,
*mut xcb_randr_get_monitors_reply_t,
)> {
if outer.rem == 0 {
return None;
}
@@ -48,10 +57,17 @@ impl DisplayIter {
let inner = xcb_randr_get_monitors_monitors_iterator(response);
libc::free(response as *mut _);
xcb_screen_next(outer);
Some((inner, root))
Some((inner, root, response))
}
}
fn free_reply(&mut self) {
if let Some((_, _, response)) = self.inner.take() {
unsafe {
libc::free(response as *mut _);
}
}
}
}
@@ -61,7 +77,7 @@ impl Iterator for DisplayIter {
fn next(&mut self) -> Option<Display> {
loop {
if let Some((ref mut inner, root)) = self.inner {
if let Some((ref mut inner, root, _)) = self.inner {
// If there is something in the current screen, return that.
if inner.rem != 0 {
unsafe {
@@ -92,11 +108,18 @@ impl Iterator for DisplayIter {
}
// The current screen was empty, so try the next screen.
self.free_reply();
self.inner = Self::next_screen(&mut self.outer, &self.server);
}
}
}
impl Drop for DisplayIter {
fn drop(&mut self) {
self.free_reply();
}
}
fn get_atom_name(conn: *mut xcb_connection_t, atom: xcb_atom_t) -> String {
let empty = "".to_owned();
if atom == 0 {
@@ -0,0 +1,67 @@
diff --git a/libavcodec/qsvenc.c b/libavcodec/qsvenc.c
--- a/libavcodec/qsvenc.c
+++ b/libavcodec/qsvenc.c
@@ -43,6 +43,9 @@
#include "qsv_internal.h"
#include "qsvenc.h"
#include "refstruct.h"
+
+#define QSV_MAX_ENCODE_RETRIES 100
+#define QSV_SYNC_TIMEOUT_US 2000000
struct profile_names {
mfxU16 profile;
@@ -2468,6 +2471,7 @@
QSVFrame *qsv_frame = NULL;
mfxEncodeCtrl* enc_ctrl = NULL;
int ret;
+ int retries = 0;
if (frame) {
ret = submit_frame(q, frame, &qsv_frame);
@@ -2538,6 +2542,18 @@
do {
ret = MFXVideoENCODE_EncodeFrameAsync(q->session, enc_ctrl, surf, pkt.bs, pkt.sync);
+ if ((ret == MFX_WRN_DEVICE_BUSY || ret == MFX_WRN_IN_EXECUTION) &&
+ retries++ >= QSV_MAX_ENCODE_RETRIES) {
+ av_log(avctx, AV_LOG_ERROR, "QSV encoder submission retry limit exceeded\n");
+ ret = AVERROR_EXTERNAL;
+ goto free;
+ }
+#ifdef _WIN32
+ // Sub-millisecond waits become Sleep(0) on Windows.
+ if (ret == MFX_WRN_DEVICE_BUSY || ret == MFX_WRN_IN_EXECUTION)
+ av_usleep(1000);
+#else
if (ret == MFX_WRN_DEVICE_BUSY)
av_usleep(500);
+#endif
} while (ret == MFX_WRN_DEVICE_BUSY || ret == MFX_WRN_IN_EXECUTION);
@@ -2656,12 +2672,23 @@
mfxExtAVCEncodedFrameInfo *enc_info;
mfxExtBuffer **enc_buf;
enum AVPictureType pict_type;
-
- av_fifo_read(q->async_fifo, &qpkt, 1);
+ int64_t sync_deadline = av_gettime_relative() + QSV_SYNC_TIMEOUT_US;
+
+ // The SDK may still use these buffers after a synchronization timeout.
+ av_fifo_peek(q->async_fifo, &qpkt, 1, 0);
do {
- ret = MFXVideoCORE_SyncOperation(q->session, *qpkt.sync, 1000);
+ int64_t remaining = sync_deadline - av_gettime_relative();
+ if (remaining <= 0) {
+ av_log(avctx, AV_LOG_ERROR, "QSV encoder synchronization timed out\n");
+ return AVERROR_EXTERNAL;
+ }
+ ret = MFXVideoCORE_SyncOperation(q->session, *qpkt.sync,
+ FFMIN(1000, (remaining + 999) / 1000));
+ if (ret == MFX_WRN_IN_EXECUTION)
+ av_usleep(1000);
} while (ret == MFX_WRN_IN_EXECUTION);
+ av_fifo_drain2(q->async_fifo, 1);
qpkt.pkt.dts = av_rescale_q(qpkt.bs->DecodeTimeStamp, (AVRational){1, 90000}, avctx->time_base);
qpkt.pkt.pts = av_rescale_q(qpkt.bs->TimeStamp, (AVRational){1, 90000}, avctx->time_base);
@@ -0,0 +1,64 @@
diff --git a/libavcodec/qsvenc.c b/libavcodec/qsvenc.c
--- a/libavcodec/qsvenc.c
+++ b/libavcodec/qsvenc.c
@@ -1419,6 +1419,18 @@
return 0;
}
+static int qsv_update_packet_size(QSVEncContext *q, const mfxInfoMFX *mfx)
+{
+ // Intel documents a larger buffer for complex CQP frames.
+ // https://github.com/Intel-Media-SDK/MediaSDK/blob/master/doc/mediasdk_release_notes.md
+ int64_t packet_size = (int64_t)mfx->BufferSizeInKB * mfx->BRCParamMultiplier * 1000 * 4;
+
+ if (packet_size > INT_MAX - AV_INPUT_BUFFER_PADDING_SIZE)
+ return AVERROR(ENOMEM);
+ q->packet_size = FFMAX(q->packet_size, packet_size);
+ return 0;
+}
+
static int qsv_retrieve_enc_params(AVCodecContext *avctx, QSVEncContext *q)
{
AVCPBProperties *cpb_props;
@@ -1508,7 +1520,13 @@
return ff_qsv_print_error(avctx, ret,
"Error calling GetVideoParam");
- q->packet_size = q->param.mfx.BufferSizeInKB * q->param.mfx.BRCParamMultiplier * 1000;
+ if (avctx->codec_id == AV_CODEC_ID_H264 || avctx->codec_id == AV_CODEC_ID_HEVC) {
+ ret = qsv_update_packet_size(q, &q->param.mfx);
+ if (ret < 0)
+ return ret;
+ } else {
+ q->packet_size = q->param.mfx.BufferSizeInKB * q->param.mfx.BRCParamMultiplier * 1000;
+ }
if (!extradata.SPSBufSize || (need_pps && !extradata.PPSBufSize)
|| (q->hevc_vps && !extradata_vps.VPSBufSize)
@@ -2650,6 +2668,17 @@
if (ret < 0)
return ff_qsv_print_error(avctx, ret, "Error during resetting");
+ if (avctx->codec_id == AV_CODEC_ID_H264 || avctx->codec_id == AV_CODEC_ID_HEVC) {
+ mfxVideoParam param = { 0 };
+
+ ret = MFXVideoENCODE_GetVideoParam(q->session, &param);
+ if (ret < 0)
+ return ff_qsv_print_error(avctx, ret, "Error querying parameters after reset");
+ ret = qsv_update_packet_size(q, &param.mfx);
+ if (ret < 0)
+ return ret;
+ }
+
return 0;
}
@@ -2688,6 +2717,8 @@
if (ret == MFX_WRN_IN_EXECUTION)
av_usleep(1000);
} while (ret == MFX_WRN_IN_EXECUTION);
+ if (ret < 0)
+ return ff_qsv_print_error(avctx, ret, "Error synchronizing encoded frame");
av_fifo_drain2(q->async_fifo, 1);
qpkt.pkt.dts = av_rescale_q(qpkt.bs->DecodeTimeStamp, (AVRational){1, 90000}, avctx->time_base);
@@ -0,0 +1,89 @@
From: Martin Storsjö
Subject: movenc: Make the hybrid_fragmented mode more robust
Source: https://github.com/FFmpeg/FFmpeg/commit/36896af64a9ecf6835758186e7161a2e954c364d
movenc: Make the hybrid_fragmented mode more robust
Write the moov tag at the end first, before overwriting the mdat size
at the start of the file.
In case writing the final moov box fails (e.g. due to being out
of disk), we haven't broken the initial moov box yet.
Thus if writing stops between these steps, we could end up with
a file with two moov boxes - which arguably is more feasible to
recover from, than from a file with no moov boxes at all.
diff --git a/libavformat/movenc.c b/libavformat/movenc.c
--- a/libavformat/movenc.c
+++ b/libavformat/movenc.c
@@ -8546,6 +8546,28 @@ static int shift_data(AVFormatContext *s)
return ff_format_shift_data(s, mov->reserved_header_pos, moov_size);
}
+static void mov_write_mdat_size(AVFormatContext *s)
+{
+ MOVMuxContext *mov = s->priv_data;
+ AVIOContext *pb = s->pb;
+
+ /* Write size of mdat tag */
+ if (mov->mdat_size + 8 <= UINT32_MAX) {
+ avio_seek(pb, mov->mdat_pos, SEEK_SET);
+ avio_wb32(pb, mov->mdat_size + 8);
+ if (mov->flags & FF_MOV_FLAG_HYBRID_FRAGMENTED)
+ ffio_wfourcc(pb, "mdat"); // overwrite the original moov into a mdat
+ } else {
+ /* overwrite 'wide' placeholder atom */
+ avio_seek(pb, mov->mdat_pos - 8, SEEK_SET);
+ /* special value: real atom size will be 64 bit value after
+ * tag field */
+ avio_wb32(pb, 1);
+ ffio_wfourcc(pb, "mdat");
+ avio_wb64(pb, mov->mdat_size + 16);
+ }
+}
+
static int mov_write_trailer(AVFormatContext *s)
{
MOVMuxContext *mov = s->priv_data;
@@ -8605,21 +8627,9 @@ static int mov_write_trailer(AVFormatContext *s)
moov_pos = avio_tell(pb);
- /* Write size of mdat tag */
- if (mov->mdat_size + 8 <= UINT32_MAX) {
- avio_seek(pb, mov->mdat_pos, SEEK_SET);
- avio_wb32(pb, mov->mdat_size + 8);
- if (mov->flags & FF_MOV_FLAG_HYBRID_FRAGMENTED)
- ffio_wfourcc(pb, "mdat"); // overwrite the original moov into a mdat
- } else {
- /* overwrite 'wide' placeholder atom */
- avio_seek(pb, mov->mdat_pos - 8, SEEK_SET);
- /* special value: real atom size will be 64 bit value after
- * tag field */
- avio_wb32(pb, 1);
- ffio_wfourcc(pb, "mdat");
- avio_wb64(pb, mov->mdat_size + 16);
- }
+ if (!(mov->flags & FF_MOV_FLAG_HYBRID_FRAGMENTED))
+ mov_write_mdat_size(s);
+
avio_seek(pb, mov->reserved_moov_size > 0 ? mov->reserved_header_pos : moov_pos, SEEK_SET);
if (mov->flags & FF_MOV_FLAG_FASTSTART) {
@@ -8647,6 +8657,15 @@ static int mov_write_trailer(AVFormatContext *s)
if ((res = mov_write_moov_tag(pb, mov, s)) < 0)
return res;
}
+
+ if (mov->flags & FF_MOV_FLAG_HYBRID_FRAGMENTED) {
+ // With hybrid fragmentation, only write the mdat size (hiding
+ // the original moov and all the fragments within the mdat)
+ // after we've successfully written the complete moov, to avoid
+ // risk for an unreadable file if writing the final moov fails.
+ mov_write_mdat_size(s);
+ }
+
res = 0;
} else {
mov_auto_flush_fragment(s, 1);

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