Compare commits

...
Author SHA1 Message Date
rustdeskandClaude Opus 5.5 ccdd537f6a 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>
2026-10-22 17:54:12 +08:00
rustdeskandClaude Opus 5.5 a79723bc4a Update hbb_common: match websocket-port only against configured servers
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 17:28:41 +08:00
rustdeskandClaude Opus 5.5 9bc28abb17 Update hbb_common for the websocket-port warning throttle
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 17:04:40 +08:00
rustdeskandClaude Opus 5.5 86d0199152 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>
2026-10-22 16:06:04 +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
110 changed files with 5645 additions and 743 deletions
Generated
+15 -14
View File
@@ -3737,7 +3737,7 @@ dependencies = [
"url",
"users",
"uuid",
"webpki-roots 1.0.9",
"webpki-roots 1.0.10",
"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#febec27e1b40bb9fbbae02e9c59b71ac824b9fe1"
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.10",
]
[[package]]
@@ -6930,7 +6930,7 @@ dependencies = [
"wasm-bindgen",
"wasm-bindgen-futures",
"web-sys",
"webpki-roots 1.0.9",
"webpki-roots 1.0.10",
]
[[package]]
@@ -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.10",
]
[[package]]
name = "webpki-roots"
version = "1.0.9"
version = "1.0.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7dcd9d09a39985f5344844e66b0c530a33843579125f23e21e9f0f220850f22a"
checksum = "1c1c8e20c8a38fc7d65abfe74eb7280e4aa667e8eec8bc84996d2874810748d9"
dependencies = [
"rustls-pki-types",
]
+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)
@@ -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
+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 \
@@ -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),
),
);
},
);
}
}
@@ -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);
+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)
+55
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;
@@ -627,6 +628,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 +663,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 +704,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 {
@@ -1120,6 +1170,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;
+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]);
}
}
+5
View File
@@ -1928,6 +1928,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");
}
+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);
});
}
+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);
});
}
+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_
+1
View File
@@ -311,6 +311,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,
+37 -1
View File
@@ -27,6 +27,12 @@ use hbb_common::{
static NEXT_JOB_ID: AtomicI32 = AtomicI32::new(1);
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)
}
@@ -417,6 +423,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)]
@@ -587,6 +595,7 @@ impl TransferJob {
files: Vec::new(),
total_size: 0,
enable_overwrite_detection,
download: (is_remote && r#type == JobType::Generic).then(Default::default),
..Default::default()
}
}
@@ -648,6 +657,9 @@ 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");
}
validate_transfer_file_names(&files)?;
if let DataSource::FilePath(base) = &self.data_source {
for file in &files {
@@ -692,7 +704,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 +722,12 @@ impl TransferJob {
}
pub fn modify_time(&self) {
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 +752,9 @@ impl TransferJob {
}
pub fn remove_download_file(&self) {
if self.is_download() && self.data_stream.is_none() {
return;
}
if self.r#type == JobType::Printer {
return;
}
@@ -761,6 +787,9 @@ 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");
}
@@ -1160,6 +1189,13 @@ impl TransferJob {
}
pub async fn confirm(&mut self, r: &FileTransferSendConfirmRequest) -> bool {
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`
+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());
}
}
+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");
}
}
+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);
+3
View File
@@ -30,6 +30,9 @@ vcpkg_from_github(
patch/0010.disable-loading-DLLs-from-app-dir.patch
patch/0011-android-mediacodec-encode-align-64.patch
patch/0012-fix-macos-big-sur-CVBufferCopyAttachments.patch
patch/0013-fix-qsv-encode-timeouts.patch
patch/0014-fix-qsv-encode-buffer.patch
patch/0015-fix-hybrid-mp4-finalization.patch
)
if(SOURCE_PATH MATCHES " ")
+33 -3
View File
@@ -68,6 +68,7 @@ use hbb_common::{
time::{interval, Duration, Instant},
},
webrtc::WebRTCStream,
websocket::{check_ws, is_ws_endpoint},
AddrMangle, ResultType, Stream,
};
use base::{
@@ -266,7 +267,13 @@ async fn race_transports_prefer_webrtc<'a, T: 'a>(
}
}
match others_err.take() {
Some(oe) => bail!("WebRTC failed: {}; fallback failed: {}", e, oe),
// Report one error, as `select_ok` does: the UI matches and translates
// the text whole (e.g. the offline auto-retry), and both legs often
// carry the same rendezvous refusal anyway.
Some(oe) => {
log::warn!("fallback leg also failed: {}", oe);
return Err(e);
}
None if others_fut.is_none() => bail!("WebRTC failed: {}", e),
None => webrtc_err = Some(e),
}
@@ -307,7 +314,10 @@ async fn race_transports_prefer_webrtc<'a, T: 'a>(
// it before failing the connection.
Some(we) => match held.take() {
Some(conn) => return Ok(conn),
None => bail!("WebRTC failed: {}; fallback failed: {}", we, e),
None => {
log::warn!("WebRTC leg also failed: {}", we);
return Err(e);
}
},
None if webrtc_fut.is_none() => match held.take() {
Some(conn) => return Ok(conn),
@@ -1848,8 +1858,11 @@ impl Client {
conn_type: ConnType,
ipv4: bool,
) -> ResultType<Stream> {
// The proxy's address family does not constrain the relay target.
let relay_server = check_port(relay_server, RELAY_PORT);
let use_ws_proxy = Config::is_proxy() && is_ws_endpoint(&check_ws(&relay_server));
let mut conn = connect_tcp(
ipv4_to_ipv6(check_port(relay_server, RELAY_PORT), ipv4),
ipv4_to_ipv6(relay_server, ipv4 || use_ws_proxy),
CONNECT_TIMEOUT,
)
.await
@@ -5705,6 +5718,23 @@ mod webrtc_race_tests {
assert_eq!(got, "ipv6");
assert!(start.elapsed() < Duration::from_secs(5));
}
// Both legs get the same rendezvous refusal; the UI needs the text verbatim, e.g. the
// offline auto-retry matches it whole. Either leg may fail last.
#[tokio::test]
async fn same_failure_on_both_legs_reported_once() {
for (webrtc_ms, fallback_ms) in [(10, 20), (20, 10)] {
let err = race_transports_prefer_webrtc(
err_after(webrtc_ms, "Remote desktop is offline"),
vec![err_after(fallback_ms, "Remote desktop is offline")],
60_000,
NOT_P2P,
)
.await
.unwrap_err();
assert_eq!(err.to_string(), "Remote desktop is offline");
}
}
}
#[cfg(test)]
+41 -13
View File
@@ -809,7 +809,16 @@ impl<T: InvokeUiSession> Remote<T> {
if is_remote {
log::debug!("New job {}, write to {} from remote {}", id, to, path);
let to = match r#type {
fs::JobType::Generic => fs::DataSource::FilePath(PathBuf::from(&to)),
fs::JobType::Generic => {
if let Err(err) = fs::download::validate_download_name(
&path,
self.handler.peer_platform() == "Windows",
) {
self.handle_job_status(id, -1, Some(err.to_string()));
return true;
}
fs::DataSource::FilePath(PathBuf::from(&to))
}
fs::JobType::Printer => {
fs::DataSource::MemoryCursor(std::io::Cursor::new(Vec::new()))
}
@@ -1782,6 +1791,15 @@ impl<T: InvokeUiSession> Remote<T> {
fs::transform_windows_path(&mut entries);
}
}
if fd.id <= 0 {
if let Err(err) = fs::download::validate_listing(
&entries,
self.handler.peer_platform() == "Windows",
) {
self.handle_job_status(fd.id, -1, Some(err.to_string()));
return true;
}
}
// We cannot call cancel_transfer_job/handle_job_status while holding
// a mutable borrow from fs::get_job(&mut self.write_jobs), so defer
// the error handling until after the borrow scope ends.
@@ -1877,11 +1895,7 @@ impl<T: InvokeUiSession> Remote<T> {
crate::is_support_file_transfer_resume_num(
peer_ver,
);
match fs::is_write_need_confirmation(
is_support_resume && job.is_resume,
&write_path,
&digest,
) {
match job.download_digest(is_support_resume, &digest) {
Ok(res) => match res {
DigestCheckResult::IsSame => {
let req = FileTransferSendConfirmRequest {
@@ -1938,13 +1952,19 @@ impl<T: InvokeUiSession> Remote<T> {
union: Some(file_transfer_send_confirm_request::Union::OffsetBlk(0)),
..Default::default()
};
job.confirm(&req).await;
// This did not approve replacing an existing local file.
let msg = new_send_confirm(req);
allow_err!(peer.send(&msg).await);
}
},
Err(err) => {
println!("error receiving digest: {}", err);
self.cancel_transfer_job(digest.id, peer).await;
self.handle_job_status(
digest.id,
-1,
Some(err.to_string()),
);
return true;
}
}
}
@@ -1953,22 +1973,30 @@ impl<T: InvokeUiSession> Remote<T> {
}
}
Some(file_response::Union::Block(block)) => {
let id = block.id;
let mut write_error = None;
if let Some(job) = fs::get_job(block.id, &mut self.write_jobs) {
if let Err(_err) = job.write(block).await {
// to-do: add "skip" for writing job
}
let result = job.write(block).await;
if job.r#type == fs::JobType::Generic {
write_error = result.err().map(|err| err.to_string());
self.update_jobs_status();
}
}
if let Some(err) = write_error {
self.cancel_transfer_job(id, peer).await;
self.handle_job_status(id, -1, Some(err));
}
}
Some(file_response::Union::Done(d)) => {
let mut err: Option<String> = None;
let mut job_type = fs::JobType::Generic;
let mut printer_data = None;
if let Some(job) = fs::remove_job(d.id, &mut self.write_jobs) {
job.modify_time();
err = job.job_error();
err = job
.finish_download()
.err()
.map(|err| err.to_string())
.or_else(|| job.job_error());
job_type = job.r#type;
printer_data = match job.get_buf_data().await {
Ok(d) => d,
+13
View File
@@ -1251,6 +1251,11 @@ fn get_api_server_(api: String, custom: String) -> String {
if !s0.is_empty() {
let s = crate::increase_port(&s0, -2);
if s == s0 {
let s = if hbb_common::is_ipv6_str(&s) && !s.starts_with('[') {
format!("[{s}]")
} else {
s
};
return format!("http://{}:{}", s, config::RENDEZVOUS_PORT - 2);
} else {
return format!("http://{}", s);
@@ -3209,6 +3214,14 @@ mod tests {
assert!(!is_public("https://rustdesk.com@evil.test"));
}
#[test]
fn test_api_server_from_bare_ipv6_rendezvous_server() {
assert_eq!(
get_api_server_("".to_owned(), "2001:db8::1".to_owned()),
"http://[2001:db8::1]:21114"
);
}
#[test]
fn test_should_use_tcp_proxy_for_api_url() {
assert!(should_use_tcp_proxy_for_api_url(
+18 -1
View File
@@ -62,7 +62,7 @@ pub fn get_custom_server_from_string(s: &str) -> ResultType<CustomServer> {
* This allows using a ',' (comma) symbol as a final delimiter.
*/
if s.to_lowercase().contains("host=") {
let stripped = &s[s.to_lowercase().find("host=").unwrap_or(0)..s.len()];
let stripped = &s[s.to_ascii_lowercase().find("host=").unwrap_or(0)..s.len()];
let strs: Vec<&str> = stripped.split(",").collect();
let mut host = String::default();
let mut key = String::default();
@@ -232,4 +232,21 @@ mod test {
get_custom_server_from_string("=0nI900VsFHZVBVdIlncwpHS4V0bOZ0dtVldrpVO4JHdCp0YV5WdzUGZzdnYRVjI6ISeltmIsISMuEjLx4SMiojI0N3boJye.exe")
.unwrap(), lic);
}
#[test]
fn test_filename_license_string_in_non_ascii_path() {
// Windows passes the full exe path, and `İ` grows from 2 to 3 bytes when lowercased.
assert_eq!(
get_custom_server_from_string(
r"C:\Users\İsmail\Downloads\rustdesk-host=server.example.net,key=Zm9vYmFyLiwyCg==.exe"
)
.unwrap(),
CustomServer {
host: "server.example.net".to_owned(),
key: "Zm9vYmFyLiwyCg==".to_owned(),
api: "".to_owned(),
relay: "".to_owned(),
}
);
}
}
+10
View File
@@ -2763,6 +2763,16 @@ pub fn main_get_common(key: String) -> String {
}
pub fn main_get_common_sync(key: String) -> SyncReturn<String> {
if let Some(args) = key.strip_prefix("resolve-api-server:") {
let response = match serde_json::from_str::<(String, String)>(args) {
Ok((api, custom)) => serde_json::json!({"url": crate::get_api_server(api, custom)}),
Err(err) => {
log::trace!("Invalid API server preview arguments: {err}");
serde_json::json!({"error": err.to_string()})
}
};
return SyncReturn(response.to_string());
}
// Metadata verification performs blocking network requests. Keep this key on
// the asynchronous FFI path to avoid blocking the calling Flutter isolate.
if key.starts_with("verified-download-url-") {
+2
View File
@@ -813,5 +813,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("shortcut-key-not-supported", ""),
("On", ""),
("Off", ""),
("api_server_connection_tip", ""),
("api_server_empty_tip", ""),
].iter().cloned().collect();
}
+2
View File
@@ -813,5 +813,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("shortcut-key-not-supported", ""),
("On", ""),
("Off", ""),
("api_server_connection_tip", ""),
("api_server_empty_tip", ""),
].iter().cloned().collect();
}
+2
View File
@@ -813,5 +813,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("shortcut-key-not-supported", ""),
("On", ""),
("Off", ""),
("api_server_connection_tip", ""),
("api_server_empty_tip", ""),
].iter().cloned().collect();
}
+2
View File
@@ -813,5 +813,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("shortcut-key-not-supported", ""),
("On", ""),
("Off", ""),
("api_server_connection_tip", ""),
("api_server_empty_tip", ""),
].iter().cloned().collect();
}
+2
View File
@@ -813,5 +813,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("shortcut-key-not-supported", ""),
("On", ""),
("Off", ""),
("api_server_connection_tip", ""),
("api_server_empty_tip", ""),
].iter().cloned().collect();
}
+2
View File
@@ -813,5 +813,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("shortcut-key-not-supported", "“{}” 不能用作快捷键。"),
("On", "开"),
("Off", "关"),
("api_server_connection_tip", "自定义服务器正在使用未加密的 HTTP。请联系管理员启用 HTTPS。"),
("api_server_empty_tip", "API 服务器留空时,自定义服务器默认使用 HTTP。请联系管理员启用 HTTPS。"),
].iter().cloned().collect();
}
+2
View File
@@ -813,5 +813,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("shortcut-key-not-supported", ""),
("On", ""),
("Off", ""),
("api_server_connection_tip", ""),
("api_server_empty_tip", ""),
].iter().cloned().collect();
}
+2
View File
@@ -813,5 +813,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("shortcut-key-not-supported", ""),
("On", ""),
("Off", ""),
("api_server_connection_tip", ""),
("api_server_empty_tip", ""),
].iter().cloned().collect();
}
+2
View File
@@ -813,5 +813,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("shortcut-key-not-supported", ""),
("On", ""),
("Off", ""),
("api_server_connection_tip", ""),
("api_server_empty_tip", ""),
].iter().cloned().collect();
}
+2
View File
@@ -813,5 +813,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("shortcut-key-not-supported", ""),
("On", ""),
("Off", ""),
("api_server_connection_tip", ""),
("api_server_empty_tip", ""),
].iter().cloned().collect();
}
+2
View File
@@ -288,5 +288,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("shortcut-already-bound-to", "Already bound to"),
("shortcut-mobile-physical-keyboard-tip", "Recording requires a physical keyboard. Soft keyboards are not supported."),
("shortcut-key-not-supported", "\"{}\" can't be used as a shortcut."),
("api_server_connection_tip", "Your custom server uses unencrypted HTTP. Contact your administrator to enable HTTPS."),
("api_server_empty_tip", "With API Server empty, your custom server defaults to HTTP. Contact your administrator to enable HTTPS."),
].iter().cloned().collect();
}
+2
View File
@@ -813,5 +813,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("shortcut-key-not-supported", ""),
("On", ""),
("Off", ""),
("api_server_connection_tip", ""),
("api_server_empty_tip", ""),
].iter().cloned().collect();
}
+2
View File
@@ -813,5 +813,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("shortcut-key-not-supported", ""),
("On", ""),
("Off", ""),
("api_server_connection_tip", ""),
("api_server_empty_tip", ""),
].iter().cloned().collect();
}
+2
View File
@@ -813,5 +813,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("shortcut-key-not-supported", ""),
("On", ""),
("Off", ""),
("api_server_connection_tip", ""),
("api_server_empty_tip", ""),
].iter().cloned().collect();
}
+2
View File
@@ -813,5 +813,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("shortcut-key-not-supported", ""),
("On", ""),
("Off", ""),
("api_server_connection_tip", ""),
("api_server_empty_tip", ""),
].iter().cloned().collect();
}
+33 -33
View File
@@ -780,38 +780,38 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("RustDesk could not load a GStreamer component needed for screen capture ({})", "RustDesk نتوانست مؤلفه GStreamer موردنیاز برای ضبط صفحه را بارگذاری کند ({})"),
("Relay fallback delay in seconds", "تأخیر بازگشت به رله بر حسب ثانیه"),
("relay-fallback-delay-tip", "یک اتصال رله که از قبل برقرار شده چقدر منتظر اتصال مستقیم WebRTC می ماند پیش از آنکه به جای آن استفاده شود. آن را افزایش دهید تا به اتصال مستقیم کند فرصت بیشتری داده شود؛ کاهش دهید تا در شبکه هایی که اتصال مستقیم ممکن نیست، زودتر به رله بازگردد. برای مقدار پیش فرض 2.5 ثانیه خالی بگذارید."),
("To start a voice call, enable \"Audio capture\" on the \"Share screen\" page.", ""),
("Keyboard shortcuts", ""),
("Configure shortcuts...", ""),
("Enable keyboard shortcuts in remote session", ""),
("shortcut-page-description", ""),
("shortcut-passthrough-tip", ""),
("Pass-through to remote", ""),
("Reset to defaults", ""),
("shortcut-reset-confirm-tip", ""),
("Monitor", ""),
("Keyboard", ""),
("Toggle fullscreen", ""),
("Switch to next display", ""),
("Switch to previous display", ""),
("Switch to next tab", ""),
("Switch to previous tab", ""),
("Toggle session recording", ""),
("Close tab", ""),
("Toggle toolbar", ""),
("Toggle input source", ""),
("Edit", ""),
("Save", ""),
("Set shortcut", ""),
("shortcut-recording-instruction", ""),
("shortcut-recording-press-keys-tip", ""),
("shortcut-must-include-modifiers", ""),
("shortcut-already-bound-to", ""),
("Replace", ""),
("Valid", ""),
("shortcut-mobile-physical-keyboard-tip", ""),
("shortcut-key-not-supported", ""),
("On", ""),
("Off", ""),
("To start a voice call, enable \"Audio capture\" on the \"Share screen\" page.", "برای شروع تماس صوتی، گزینه «ضبط صدا» را در صفحه «اشتراک‌گذاری صفحه» فعال کنید."),
("Keyboard shortcuts", "میانبرهای صفحه کلید"),
("Configure shortcuts...", "پیکربندی میانبرها..."),
("Enable keyboard shortcuts in remote session", "فعال‌سازی میانبرهای صفحه کلید در جلسه راه دور"),
("shortcut-page-description", "میانبرهای صفحه کلید را برای کارهای رایج در جلسه راه دور تنظیم کنید."),
("shortcut-passthrough-tip", "با فعال بودن ارسال مستقیم، میانبرهای فعال‌شده به جای دستگاه محلی به دستگاه راه دور ارسال می‌شوند."),
("Pass-through to remote", "ارسال مستقیم به راه دور"),
("Reset to defaults", "بازنشانی به پیش‌فرض"),
("shortcut-reset-confirm-tip", "همه میانبرها به مقادیر پیش‌فرض بازنشانی شوند؟"),
("Monitor", "نمایشگر"),
("Keyboard", "صفحه کلید"),
("Toggle fullscreen", "تغییر حالت تمام صفحه"),
("Switch to next display", "رفتن به نمایشگر بعدی"),
("Switch to previous display", "رفتن به نمایشگر قبلی"),
("Switch to next tab", "رفتن به زبانه بعدی"),
("Switch to previous tab", "رفتن به زبانه قبلی"),
("Toggle session recording", "تغییر وضعیت ضبط جلسه"),
("Close tab", "بستن زبانه"),
("Toggle toolbar", "نمایش/پنهان کردن نوار ابزار"),
("Toggle input source", "تغییر منبع ورودی"),
("Edit", "ویرایش"),
("Save", "ذخیره"),
("Set shortcut", "تنظیم میانبر"),
("shortcut-recording-instruction", "کلیدهای میانبر مورد نظر را فشار دهید."),
("shortcut-recording-press-keys-tip", "کلیدها را فشار دهید..."),
("shortcut-must-include-modifiers", "میانبر باید شامل حداقل یک کلید تغییردهنده (Ctrl، Alt، Shift یا Meta) باشد."),
("shortcut-already-bound-to", "این میانبر قبلاً به عملکرد دیگری اختصاص داده شده است."),
("Replace", "جایگزینی"),
("Valid", "معتبر"),
("shortcut-mobile-physical-keyboard-tip", "این میانبرها فقط با صفحه کلید فیزیکی متصل کار می‌کنند."),
("shortcut-key-not-supported", "این کلید برای میانبر پشتیبانی نمی‌شود."),
("On", "روشن"),
("Off", "خاموش"),
].iter().cloned().collect();
}
+2
View File
@@ -813,5 +813,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("shortcut-key-not-supported", ""),
("On", ""),
("Off", ""),
("api_server_connection_tip", ""),
("api_server_empty_tip", ""),
].iter().cloned().collect();
}
+2
View File
@@ -813,5 +813,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("shortcut-key-not-supported", ""),
("On", ""),
("Off", ""),
("api_server_connection_tip", ""),
("api_server_empty_tip", ""),
].iter().cloned().collect();
}
+2
View File
@@ -813,5 +813,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("shortcut-key-not-supported", ""),
("On", ""),
("Off", ""),
("api_server_connection_tip", ""),
("api_server_empty_tip", ""),
].iter().cloned().collect();
}
+2
View File
@@ -813,5 +813,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("shortcut-key-not-supported", ""),
("On", ""),
("Off", ""),
("api_server_connection_tip", ""),
("api_server_empty_tip", ""),
].iter().cloned().collect();
}
+2
View File
@@ -813,5 +813,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("shortcut-key-not-supported", ""),
("On", ""),
("Off", ""),
("api_server_connection_tip", ""),
("api_server_empty_tip", ""),
].iter().cloned().collect();
}
+2
View File
@@ -813,5 +813,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("shortcut-key-not-supported", ""),
("On", ""),
("Off", ""),
("api_server_connection_tip", ""),
("api_server_empty_tip", ""),
].iter().cloned().collect();
}
+2
View File
@@ -813,5 +813,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("shortcut-key-not-supported", ""),
("On", ""),
("Off", ""),
("api_server_connection_tip", ""),
("api_server_empty_tip", ""),
].iter().cloned().collect();
}
+2
View File
@@ -813,5 +813,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("shortcut-key-not-supported", ""),
("On", ""),
("Off", ""),
("api_server_connection_tip", ""),
("api_server_empty_tip", ""),
].iter().cloned().collect();
}
+2
View File
@@ -813,5 +813,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("shortcut-key-not-supported", ""),
("On", ""),
("Off", ""),
("api_server_connection_tip", ""),
("api_server_empty_tip", ""),
].iter().cloned().collect();
}
+23 -21
View File
@@ -69,7 +69,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("Retry", "Coba lagi"),
("OK", "Oke"),
("Password Required", "Kata sandi tidak boleh kosong"),
("Please enter your password", "Silahkan masukkan kata sandi"),
("Please enter your password", "Silakan masukkan kata sandi"),
("Remember password", "Ingat kata sandi"),
("Wrong Password", "Kata sandi Salah"),
("Do you want to enter again?", "Apakah kamu ingin mencoba lagi?"),
@@ -78,7 +78,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("Reset by the peer", "Direset oleh rekan"),
("Connecting...", "Menghubungkan..."),
("Connection in progress. Please wait.", "Koneksi sedang berlangsung. Mohon tunggu."),
("Please try 1 minute later", "Silahkan coba 1 menit lagi"),
("Please try 1 minute later", "Silakan coba 1 menit lagi"),
("Login Error", "Kesalahan Login"),
("Successful", "Berhasil"),
("Connected, waiting for image...", "Terhubung, menunggu gambar..."),
@@ -103,8 +103,8 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("Empty Directory", "Folder Kosong"),
("Not an empty directory", "Folder tidak kosong"),
("Are you sure you want to delete this file?", "Apakah kamu yakin untuk menghapus file ini?"),
("Are you sure you want to delete this empty directory?", "Apakah yakin yakin untuk menghapus folder ini?"),
("Are you sure you want to delete the file of this directory?", "Apakah yakin yakin untuk menghapus file dan folder ini?"),
("Are you sure you want to delete this empty directory?", "Apakah yakin untuk menghapus folder ini?"),
("Are you sure you want to delete the file of this directory?", "Apakah yakin untuk menghapus file dan folder ini?"),
("Do this for all conflicts", "Lakukan untuk semua konflik"),
("This is irreversible!", "Ini tidak dapat diubah!"),
("Deleting", "Menghapus"),
@@ -135,7 +135,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("Refresh", "Segarkan"),
("ID does not exist", "ID tidak ada"),
("Failed to connect to rendezvous server", "Gagal menghubungkan ke rendezvous server"),
("Please try later", "Silahkan coba lagi nanti"),
("Please try later", "Silakan coba lagi nanti"),
("Remote desktop is offline", "Remote desktop offline"),
("Key mismatch", "Ketidakcocokan kunci"),
("Timeout", "Waktu habis"),
@@ -150,14 +150,14 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("Configure", "Konfigurasi"),
("config_acc", "Agar bisa mengontrol Desktopmu dari jarak jauh, Kamu harus memberikan izin \"Aksesibilitas\" untuk RustDesk."),
("config_screen", "Agar bisa mengakses Desktopmu dari jarak jauh, kamu harus memberikan izin \"Perekaman Layar\" untuk RustDesk."),
("Installing ...", "Menginstall"),
("Installing ...", "Menginstal"),
("Install", "Instal"),
("Installation", "Instalasi"),
("Installation Path", "Direktori Instalasi"),
("Create start menu shortcuts", "Buat pintasan start menu"),
("Create desktop icon", "Buat icon desktop"),
("Create desktop icon", "Buat ikon desktop"),
("agreement_tip", "Dengan memulai proses instalasi, Kamu menerima perjanjian lisensi."),
("Accept and Install", "Terima dan Install"),
("Accept and Install", "Terima dan Instal"),
("End-user license agreement", "Perjanjian lisensi pengguna"),
("Generating ...", "Memproses..."),
("Your installation is lower version.", "Kamu menggunakan versi instalasi yang lebih rendah."),
@@ -171,7 +171,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("Local Address", "Alamat lokal"),
("Change Local Port", "Ubah Port Lokal"),
("setup_server_tip", "Untuk koneksi yang lebih baik, silakan konfigurasi di server pribadi"),
("Too short, at least 6 characters.", "Terlalu pendek, setidaknya 6 karekter."),
("Too short, at least 6 characters.", "Terlalu pendek, setidaknya 6 karakter."),
("The confirmation is not identical.", "Konfirmasi tidak identik."),
("Permissions", "Perizinan"),
("Accept", "Terima"),
@@ -194,7 +194,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("Create desktop shortcut", "Buat Pintasan Desktop"),
("Change Path", "Ubah Direktori"),
("Create Folder", "Buat Folder"),
("Please enter the folder name", "Silahkan masukkan nama folder"),
("Please enter the folder name", "Silakan masukkan nama folder"),
("Fix it", "Perbaiki"),
("Warning", "Peringatan"),
("Login screen using Wayland is not supported", "Login screen dengan Wayland tidak didukung"),
@@ -206,11 +206,11 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("Username", "Nama pengguna"),
("Invalid port", "Kesalahan port"),
("Closed manually by the peer", "Ditutup secara manual oleh rekan"),
("Enable remote configuration modification", "Aktifkan modifikasi konfigurasi remotE"),
("Enable remote configuration modification", "Aktifkan modifikasi konfigurasi remote"),
("Run without install", "Jalankan tanpa menginstal"),
("Connect via relay", "Sambungkan via relay"),
("Always connect via relay", "Selalu terhubung melalui relay"),
("whitelist_tip", "Hanya IP yang diizikan dapat mengakses"),
("whitelist_tip", "Hanya IP yang diizinkan dapat mengakses"),
("Login", "Masuk"),
("Verify", "Verifikasi"),
("Remember me", "Ingatkan saya"),
@@ -228,7 +228,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("Username missed", "Nama pengguna tidak sesuai"),
("Password missed", "Kata sandi tidak sesuai"),
("Wrong credentials", "Nama pengguna atau kata sandi salah"),
("The verification code is incorrect or has expired", "Kode verifikasi salah atau sudah kadaluarsa"),
("The verification code is incorrect or has expired", "Kode verifikasi salah atau sudah kadaluwarsa"),
("Edit Tag", "Ubah Tag"),
("Forget Password", "Lupakan Kata Sandi"),
("Favorites", "Favorit"),
@@ -303,11 +303,11 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("android_open_battery_optimizations_tip", "Jika anda ingin menonaktifkan fitur ini, buka halam pengaturan, cari dan pilih [Baterai], Uncheck [Tidak dibatasi]"),
("Start on boot", "Mulai saat dihidupkan"),
("Start the screen sharing service on boot, requires special permissions", "Mulai layanan berbagi layar saat sistem dinyalakan, memerlukan izin khusus."),
("Connection not allowed", "Koneksi tidak dizinkan"),
("Connection not allowed", "Koneksi tidak diizinkan"),
("Legacy mode", "Mode lawas"),
("Map mode", "Mode peta"),
("Translate mode", "Mode terjemahan"),
("Use permanent password", "Gunakan kata sandi permanaen"),
("Use permanent password", "Gunakan kata sandi permanen"),
("Use both passwords", "Gunakan kedua kata sandi"),
("Set permanent password", "Setel kata sandi permanen"),
("Enable remote restart", "Aktifkan Restart Secara Remote"),
@@ -385,7 +385,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("This PC", "PC ini"),
("or", "atau"),
("Elevate", "Elevasi"),
("Zoom cursor", "Perbersar Kursor"),
("Zoom cursor", "Perbesar Kursor"),
("Accept sessions via password", "Izinkan sesi dengan kata sandi"),
("Accept sessions via click", "Izinkan sesi dengan klik"),
("Accept sessions via both", "Izinkan sesi dengan keduanya"),
@@ -405,7 +405,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("Closed manually by web console", "Ditutup secara manual dari konsol web."),
("Local keyboard type", "Tipe papan ketik"),
("Select local keyboard type", "Pilih tipe papan ketik"),
("software_render_tip", "Jika anda menggunakan kartu grafis Nvidia pada sistem linux dan jendela windows ditutup secara instan setelah terhung, silahkan ubah ke driver open-source Nouveau, dibutukan untuk merestart aplikasi"),
("software_render_tip", "Jika anda menggunakan kartu grafis Nvidia pada sistem linux dan jendela windows ditutup secara instan setelah terhubung, silakan ubah ke driver open-source Nouveau, dibutuhkan untuk merestart aplikasi"),
("Always use software rendering", "Selalu gunakan software rendering"),
("config_input", "Untuk menggunakan input keyboard remote, anda perlu memberikan izin \"Pemantauan Input\" pada RustDesk"),
("config_microphone", "Untuk berbicara secara remote, anda perlu memberikan izin \"Rekam Audio\" pada RustDesk"),
@@ -441,7 +441,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("Voice call", "Panggilan suara"),
("Text chat", "Obrolan Teks"),
("Stop voice call", "Hentikan panggilan suara"),
("relay_hint_tip", "Tidak memungkinkan untuk terhubung secara langsung; anda bisa mencoba terhubung via relay. Selain itu, jika ingin menggunakan relay pada percobaan pertama, silahkan tambah akhiran \"/r\" pada ID atau pilih \"Selalu terhubung via relay\" di pilihan sesi terbaru."),
("relay_hint_tip", "Tidak memungkinkan untuk terhubung secara langsung; anda bisa mencoba terhubung via relay. Selain itu, jika ingin menggunakan relay pada percobaan pertama, silakan tambah akhiran \"/r\" pada ID atau pilih \"Selalu terhubung via relay\" di pilihan sesi terbaru."),
("Reconnect", "Sambungkan ulang"),
("Codec", "Kodek"),
("Resolution", "Resolusi"),
@@ -522,7 +522,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("auto_disconnect_option_tip", "Secara otomatis akan menutup sesi ketika tidak ada aktivitas"),
("Connection failed due to inactivity", "Secara otomatis akan terputus ketik tidak ada aktivitas."),
("Check for software update on startup", "Periksa pembaruan aplikasi saat sistem dinyalakan."),
("upgrade_rustdesk_server_pro_to_{}_tip", "Silahkan perbarui RustDesk Server Pro ke versi {} atau yang lebih baru!"),
("upgrade_rustdesk_server_pro_to_{}_tip", "Silakan perbarui RustDesk Server Pro ke versi {} atau yang lebih baru!"),
("pull_group_failed_tip", "Gagal memperbarui grup"),
("Filter by intersection", "Filter berdasarkan persilangan"),
("Remove wallpaper during incoming sessions", "Hilangkan latar dinding ketika ada sesi yang masuk"),
@@ -568,7 +568,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("My address book", "Daftar Kontak"),
("Personal", "Personal"),
("Owner", "Pemilik"),
("Set shared password", "Atus kata sandi kolaboratif"),
("Set shared password", "Atur kata sandi kolaboratif"),
("Exist in", "Ada di"),
("Read-only", "Hanya baca"),
("Read/Write", "Baca/Tulis"),
@@ -634,7 +634,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("Untagged", "Tanpa tag"),
("new-version-of-{}-tip", "Versi {} sudah tersedia."),
("Accessible devices", "Perangkat yang tersedia"),
("upgrade_remote_rustdesk_client_to_{}_tip", "Silahkan perbarui aplikasi RustDesk ke versi {} atau yang lebih baru pada komputer yang akan terhubung!"),
("upgrade_remote_rustdesk_client_to_{}_tip", "Silakan perbarui aplikasi RustDesk ke versi {} atau yang lebih baru pada komputer yang akan terhubung!"),
("d3d_render_tip", "Ketika rendering D3D diaktifkan, layar kontrol jarak jauh bisa tampak hitam di beberapa komputer"),
("Use D3D rendering", "Gunakan rendering D3D"),
("Printer", "Printer"),
@@ -813,5 +813,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("shortcut-key-not-supported", ""),
("On", ""),
("Off", ""),
("api_server_connection_tip", ""),
("api_server_empty_tip", ""),
].iter().cloned().collect();
}
+34 -32
View File
@@ -781,37 +781,39 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("Relay fallback delay in seconds", "Ritardo fallback relay (secondi)"),
("relay-fallback-delay-tip", "Quanto tempo una connessione relay già attiva attende la connessione WebRTC diretta prima di essere usata. Aumentalo per dare a una connessione diretta lenta più tempo per funzionare; diminuiscilo per passare prima al relay sulle reti in cui non è possibile effettuare una connessione diretta. Lascia vuoto per il valore predefinito di 2,5 secondi."),
("To start a voice call, enable \"Audio capture\" on the \"Share screen\" page.", "Per avviare una chiamata vocale, attiva nella pagina 'Condividi schermo' la voce 'Cattura audio'."),
("Keyboard shortcuts", ""),
("Configure shortcuts...", ""),
("Enable keyboard shortcuts in remote session", ""),
("shortcut-page-description", ""),
("shortcut-passthrough-tip", ""),
("Pass-through to remote", ""),
("Reset to defaults", ""),
("shortcut-reset-confirm-tip", ""),
("Monitor", ""),
("Keyboard", ""),
("Toggle fullscreen", ""),
("Switch to next display", ""),
("Switch to previous display", ""),
("Switch to next tab", ""),
("Switch to previous tab", ""),
("Toggle session recording", ""),
("Close tab", ""),
("Toggle toolbar", ""),
("Toggle input source", ""),
("Edit", ""),
("Save", ""),
("Set shortcut", ""),
("shortcut-recording-instruction", ""),
("shortcut-recording-press-keys-tip", ""),
("shortcut-must-include-modifiers", ""),
("shortcut-already-bound-to", ""),
("Replace", ""),
("Valid", ""),
("shortcut-mobile-physical-keyboard-tip", ""),
("shortcut-key-not-supported", ""),
("On", ""),
("Off", ""),
("Keyboard shortcuts", "Scorciatoie da tastiera"),
("Configure shortcuts...", "Configura scorciatoie..."),
("Enable keyboard shortcuts in remote session", "Nella sessione remota abilita scorciatoie da tastiera"),
("shortcut-page-description", "Associa una combinazione di tasti a ciascuna azione della sessione riportata di seguito. Ogni associazione deve includere almeno un modificatore."),
("shortcut-passthrough-tip", "Quando è attiva, ogni combinazione associata viene inoltrata alla sessione remota. Utile quando un'associazione entra in conflitto con qualcosa di cui hai bisogno nella sessione remota."),
("Pass-through to remote", "Passa direttamente al remoto"),
("Reset to defaults", "Ripristina impostazioni predefinite"),
("shortcut-reset-confirm-tip", "Questo sostituirà tutti le associazioni attuali con quelle predefinite. Vuoi continuare?"),
("Monitor", "Monitor"),
("Keyboard", "Tastiera"),
("Toggle fullscreen", "Attiva/disattiva schermo pieno"),
("Switch to next display", "Passa allo schermo successivo"),
("Switch to previous display", "Passa allo schermo precedente"),
("Switch to next tab", "Passa alla scheda successiva"),
("Switch to previous tab", "Passa alla scheda precedente"),
("Toggle session recording", "Attiva/disattiva registrazione sessione"),
("Close tab", "Chiudi scheda"),
("Toggle toolbar", "Attiva/disattiva barra strumenti"),
("Toggle input source", "Attiva/disattiva sorgente input"),
("Edit", "Modifica"),
("Save", "Salva"),
("Set shortcut", "Imposta scorciatoia"),
("shortcut-recording-instruction", "Premi la combinazione di tasti che vuoi usare."),
("shortcut-recording-press-keys-tip", "Premi una combinazione di tasti..."),
("shortcut-must-include-modifiers", "Deve includere almeno un modificatore: {}"),
("shortcut-already-bound-to", "Già assegnato a"),
("Replace", "Sostituisci"),
("Valid", "Valido"),
("shortcut-mobile-physical-keyboard-tip", "La registrazione richiede una tastiera fisica. Le tastiere software non sono supportate."),
("shortcut-key-not-supported", "'{}' non può essere usato come scorciatoia."),
("On", "ON"),
("Off", "OFF"),
("api_server_connection_tip", "Il server personalizzato usa 'HTTP non crittografato'. Per abilitare HTTPS contatta l'amministratore."),
("api_server_empty_tip", "Con 'Server API' vuoto, il server personalizzato predefinito è 'HTTP'. Per abilitare HTTPS contatta l'amministratore."),
].iter().cloned().collect();
}
+2
View File
@@ -813,5 +813,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("shortcut-key-not-supported", ""),
("On", ""),
("Off", ""),
("api_server_connection_tip", ""),
("api_server_empty_tip", ""),
].iter().cloned().collect();
}
+2
View File
@@ -813,5 +813,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("shortcut-key-not-supported", ""),
("On", ""),
("Off", ""),
("api_server_connection_tip", ""),
("api_server_empty_tip", ""),
].iter().cloned().collect();
}
+2
View File
@@ -813,5 +813,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("shortcut-key-not-supported", ""),
("On", ""),
("Off", ""),
("api_server_connection_tip", ""),
("api_server_empty_tip", ""),
].iter().cloned().collect();
}
+2
View File
@@ -813,5 +813,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("shortcut-key-not-supported", ""),
("On", ""),
("Off", ""),
("api_server_connection_tip", ""),
("api_server_empty_tip", ""),
].iter().cloned().collect();
}
+2
View File
@@ -813,5 +813,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("shortcut-key-not-supported", ""),
("On", ""),
("Off", ""),
("api_server_connection_tip", ""),
("api_server_empty_tip", ""),
].iter().cloned().collect();
}
+2
View File
@@ -813,5 +813,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("shortcut-key-not-supported", ""),
("On", ""),
("Off", ""),
("api_server_connection_tip", ""),
("api_server_empty_tip", ""),
].iter().cloned().collect();
}
+2
View File
@@ -813,5 +813,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("shortcut-key-not-supported", ""),
("On", ""),
("Off", ""),
("api_server_connection_tip", ""),
("api_server_empty_tip", ""),
].iter().cloned().collect();
}
+34 -32
View File
@@ -781,37 +781,39 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("Relay fallback delay in seconds", "Vertraging voordat relay wordt gebruikt in seconden"),
("relay-fallback-delay-tip", "Hoe lang een al tot stand gekomen relayverbinding wacht op de directe WebRTC-verbinding voordat deze in plaats daarvan wordt gebruikt. Verhoog de waarde om een trage directe verbinding meer tijd te geven; verlaag deze om op netwerken waar een directe verbinding niet mogelijk is sneller op de relay terug te vallen. Laat leeg voor de standaardwaarde van 2.5 seconden."),
("To start a voice call, enable \"Audio capture\" on the \"Share screen\" page.", "Om een spraakgesprek te starten, schakel je \"Audio-opname\" in op de pagina \"Scherm delen\"."),
("Keyboard shortcuts", ""),
("Configure shortcuts...", ""),
("Enable keyboard shortcuts in remote session", ""),
("shortcut-page-description", ""),
("shortcut-passthrough-tip", ""),
("Pass-through to remote", ""),
("Reset to defaults", ""),
("shortcut-reset-confirm-tip", ""),
("Monitor", ""),
("Keyboard", ""),
("Toggle fullscreen", ""),
("Switch to next display", ""),
("Switch to previous display", ""),
("Switch to next tab", ""),
("Switch to previous tab", ""),
("Toggle session recording", ""),
("Close tab", ""),
("Toggle toolbar", ""),
("Toggle input source", ""),
("Edit", ""),
("Save", ""),
("Set shortcut", ""),
("shortcut-recording-instruction", ""),
("shortcut-recording-press-keys-tip", ""),
("shortcut-must-include-modifiers", ""),
("shortcut-already-bound-to", ""),
("Replace", ""),
("Valid", ""),
("shortcut-mobile-physical-keyboard-tip", ""),
("shortcut-key-not-supported", ""),
("On", ""),
("Off", ""),
("Keyboard shortcuts", "Sneltoetsen"),
("Configure shortcuts...", "Sneltoetsen configureren..."),
("Enable keyboard shortcuts in remote session", "Sneltoetsen inschakelen in een sessie op afstand"),
("shortcut-page-description", "Beschrijving van sneltoetsenpagina"),
("shortcut-passthrough-tip", "Als deze optie is ingeschakeld, wordt elke geconfigureerde toetsencombinatie doorgestuurd naar het externe apparaat. Dit is handig als een geconfigureerde toetsencombinatie in conflict komt met een functie die op het externe apparaat nodig is."),
("Pass-through to remote", "Doorsturen naar extern apparaat"),
("Reset to defaults", "Terugzetten naar standaardinstellingen"),
("shortcut-reset-confirm-tip", "Alle huidige toetsencombinaties worden teruggezet naar de standaardinstellingen. Wil je doorgaan?"),
("Monitor", "Monitor"),
("Keyboard", "Toetsenbord"),
("Toggle fullscreen", "Volledig scherm wisselen"),
("Switch to next display", "Wisselen naar volgend scherm"),
("Switch to previous display", "Wisselen naar vorig scherm"),
("Switch to next tab", "Schakel naar volgende tabblad"),
("Switch to previous tab", "Schakel naar vorig tabblad"),
("Toggle session recording", "Sessie-opname wisselen"),
("Close tab", "Tabblad sluiten"),
("Toggle toolbar", "Werkbalk wisselen"),
("Toggle input source", "Invoerbron wisselen"),
("Edit", "Bewerken"),
("Save", "Opslaan"),
("Set shortcut", "Sneltoets toewijzen"),
("shortcut-recording-instruction", "Druk op de toetsencombinatie die je wilt gebruiken."),
("shortcut-recording-press-keys-tip", "Druk op de toetsencombinatie..."),
("shortcut-must-include-modifiers", "Sneltoets moet een combinatietoets bevatten"),
("shortcut-already-bound-to", "Sneltoets is al toegewezen aan"),
("Replace", "Vervangen"),
("Valid", "Geldig"),
("shortcut-mobile-physical-keyboard-tip", "Voor het opnemen is een fysiek toetsenbord vereist. Schermtoetsenborden worden niet ondersteund."),
("shortcut-key-not-supported", "Sneltoets wordt niet ondersteund"),
("On", "Aan"),
("Off", "Uit"),
("api_server_connection_tip", ""),
("api_server_empty_tip", ""),
].iter().cloned().collect();
}
+34 -32
View File
@@ -781,37 +781,39 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("Relay fallback delay in seconds", "Opóźnienie przed przejściem na przekaźnik w sekundach"),
("relay-fallback-delay-tip", "Jak długo nawiązane już połączenie przez przekaźnik czeka na bezpośrednie połączenie WebRTC, zanim zostanie użyte zamiast niego. Zwiększ, aby dać wolnemu połączeniu bezpośredniemu więcej czasu; zmniejsz, aby w sieciach, w których połączenie bezpośrednie jest niemożliwe, szybciej przechodzić na przekaźnik. Pozostaw puste, aby użyć wartości domyślnej 2.5 sekundy."),
("To start a voice call, enable \"Audio capture\" on the \"Share screen\" page.", "Aby rozpocząć połączenie głosowe, włącz opcję \"Przechwytywanie dźwięku\" na stronie \"Udostępnianie ekranu\"."),
("Keyboard shortcuts", ""),
("Configure shortcuts...", ""),
("Enable keyboard shortcuts in remote session", ""),
("shortcut-page-description", ""),
("shortcut-passthrough-tip", ""),
("Pass-through to remote", ""),
("Reset to defaults", ""),
("shortcut-reset-confirm-tip", ""),
("Monitor", ""),
("Keyboard", ""),
("Toggle fullscreen", ""),
("Switch to next display", ""),
("Switch to previous display", ""),
("Switch to next tab", ""),
("Switch to previous tab", ""),
("Toggle session recording", ""),
("Close tab", ""),
("Toggle toolbar", ""),
("Toggle input source", ""),
("Edit", ""),
("Save", ""),
("Set shortcut", ""),
("shortcut-recording-instruction", ""),
("shortcut-recording-press-keys-tip", ""),
("shortcut-must-include-modifiers", ""),
("shortcut-already-bound-to", ""),
("Replace", ""),
("Valid", ""),
("shortcut-mobile-physical-keyboard-tip", ""),
("shortcut-key-not-supported", ""),
("On", ""),
("Off", ""),
("Keyboard shortcuts", "Skróty klawiszowe"),
("Configure shortcuts...", "Skonfiguruj skróty"),
("Enable keyboard shortcuts in remote session", "Włącz skróty klawiszowe w zdalnych sesjach"),
("shortcut-page-description", "Przypisz kombinację klawiszy do każdej poniższej akcji sesji. Każde powiązanie musi zawierać co najmniej jeden modyfikator."),
("shortcut-passthrough-tip", "Po włączeniu wszystkie powiązane kombinacje są przekazywane do sesji zdalnej. Jest to przydatne, gdy powiązanie koliduje z czymś, czego potrzebujesz w sesji zdalnej."),
("Pass-through to remote", "Przenieś do zdalnej sesji"),
("Reset to defaults", "Przywróć domyślne"),
("shortcut-reset-confirm-tip", "Wszystkie obecne przypisania zostaną zastąpione domyślnymi. Kontynuować?"),
("Monitor", "Monitor"),
("Keyboard", "Klawiatura"),
("Toggle fullscreen", "Przełącz na pełny ekran"),
("Switch to next display", "Przełącz na następny ekran"),
("Switch to previous display", "Przełącz na poprzedni ekran"),
("Switch to next tab", "Przełącz na następną zakładkę"),
("Switch to previous tab", "Przełącz na poprzednią zakładkę"),
("Toggle session recording", "Włącz/wyłącz nagrywanie sesji"),
("Close tab", "Zamknij zakładkę"),
("Toggle toolbar", "Włącz/wyłącz pasek narzędziowy"),
("Toggle input source", "Włącz/wyłącz źródło wejściowe"),
("Edit", "Edytuj"),
("Save", "Zapisz"),
("Set shortcut", "Ustaw skrót"),
("shortcut-recording-instruction", "Naciśnij kombinację klawiszy, których chcesz użyć."),
("shortcut-recording-press-keys-tip", "Naciśnij kombinację klawiszy..."),
("shortcut-must-include-modifiers", "Musi zawierać co najmniej jeden modyfikator: {}"),
("shortcut-already-bound-to", "Już przypisano do"),
("Replace", "Zastąp"),
("Valid", "Poprawny"),
("shortcut-mobile-physical-keyboard-tip", "Do nagrywania potrzebna jest klawiatura fizyczna. Klawiatury programowe nie są obsługiwane."),
("shortcut-key-not-supported", "Znak '{}' nie może być użyty jako skrót."),
("On", "Włączone"),
("Off", "Wyłączone"),
("api_server_connection_tip", ""),
("api_server_empty_tip", ""),
].iter().cloned().collect();
}
+35 -33
View File
@@ -780,38 +780,40 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("RustDesk could not load a GStreamer component needed for screen capture ({})", "O RustDesk não conseguiu carregar um componente do GStreamer necessário para a captura de tela ({})."),
("Relay fallback delay in seconds", "Atraso antes de recorrer ao retransmissor em segundos"),
("relay-fallback-delay-tip", "Tempo que a conexão de retransmissão aguarda pela conexão direta WebRTC. Aumente para dar mais tempo a conexões lentas; diminua para usar o retransmissor mais cedo. Deixe vazio para usar o padrão de 2,5 segundos."),
("To start a voice call, enable \"Audio capture\" on the \"Share screen\" page.", "Para iniciar uma chamada de voz, ative \"Captura de áudio\" na página \"Compartilhar Tela\"."),
("Keyboard shortcuts", ""),
("Configure shortcuts...", ""),
("Enable keyboard shortcuts in remote session", ""),
("shortcut-page-description", ""),
("shortcut-passthrough-tip", ""),
("Pass-through to remote", ""),
("Reset to defaults", ""),
("shortcut-reset-confirm-tip", ""),
("Monitor", ""),
("Keyboard", ""),
("Toggle fullscreen", ""),
("Switch to next display", ""),
("Switch to previous display", ""),
("Switch to next tab", ""),
("Switch to previous tab", ""),
("Toggle session recording", ""),
("Close tab", ""),
("Toggle toolbar", ""),
("Toggle input source", ""),
("Edit", ""),
("Save", ""),
("Set shortcut", ""),
("shortcut-recording-instruction", ""),
("shortcut-recording-press-keys-tip", ""),
("shortcut-must-include-modifiers", ""),
("shortcut-already-bound-to", ""),
("Replace", ""),
("Valid", ""),
("shortcut-mobile-physical-keyboard-tip", ""),
("shortcut-key-not-supported", ""),
("On", ""),
("Off", ""),
("To start a voice call, enable \"Audio capture\" on the \"Share screen\" page.", "Para iniciar uma chamada de voz, ative \"Captura de áudio\" na página \"Compartilhar tela\"."),
("Keyboard shortcuts", "Atalhos de teclado"),
("Configure shortcuts...", "Configurar atalhos..."),
("Enable keyboard shortcuts in remote session", "Ativar atalhos de teclado na sessão remota"),
("shortcut-page-description", "Associe uma combinação de teclas a cada ação da sessão abaixo. Cada atalho deve incluir pelo menos uma tecla modificadora."),
("shortcut-passthrough-tip", "Quando ativado, os atalhos são enviados ao computador remoto, mesmo quando entram em conflito com combinações de teclas necessárias nele."),
("Pass-through to remote", "Encaminhar atalhos ao computador remoto"),
("Reset to defaults", "Restaurar padrões"),
("shortcut-reset-confirm-tip", "Todos os atalhos atuais serão substituídos pelos padrões. Deseja continuar?"),
("Monitor", "Monitor"),
("Keyboard", "Teclado"),
("Toggle fullscreen", "Alternar tela cheia"),
("Switch to next display", "Alternar para a próxima tela"),
("Switch to previous display", "Alternar para a tela anterior"),
("Switch to next tab", "Alternar para a próxima aba"),
("Switch to previous tab", "Alternar para a aba anterior"),
("Toggle session recording", "Iniciar/parar gravação da sessão"),
("Close tab", "Fechar aba"),
("Toggle toolbar", "Mostrar/ocultar barra de ferramentas"),
("Toggle input source", "Alternar fonte de entrada"),
("Edit", "Editar"),
("Save", "Salvar"),
("Set shortcut", "Definir atalho"),
("shortcut-recording-instruction", "Pressione a combinação de teclas que deseja usar."),
("shortcut-recording-press-keys-tip", "Pressione uma combinação de teclas..."),
("shortcut-must-include-modifiers", "Deve incluir pelo menos uma tecla modificadora: {}"),
("shortcut-already-bound-to", "Já atribuído a"),
("Replace", "Substituir"),
("Valid", "Válido"),
("shortcut-mobile-physical-keyboard-tip", "A gravação de atalhos requer um teclado físico. Teclados virtuais não são compatíveis."),
("shortcut-key-not-supported", "Não é possível usar \"{}\" como atalho."),
("On", "Ativado"),
("Off", "Desativado"),
("api_server_connection_tip", ""),
("api_server_empty_tip", ""),
].iter().cloned().collect();
}
+34 -32
View File
@@ -781,37 +781,39 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("Relay fallback delay in seconds", "Atraso antes de recorrer ao retransmissor em segundos"),
("relay-fallback-delay-tip", "Quanto tempo uma ligação de retransmissão já estabelecida aguarda pela ligação direta WebRTC antes de ser usada em vez dela. Aumente para dar mais tempo a uma ligação direta lenta; diminua para recorrer mais cedo ao retransmissor em redes onde não é possível uma ligação direta. Deixe vazio para o valor predefinido de 2.5 segundos."),
("To start a voice call, enable \"Audio capture\" on the \"Share screen\" page.", "Para iniciar uma chamada de voz, ative \"Captura de Áudio\" na página \"Partilhar ecrã\"."),
("Keyboard shortcuts", ""),
("Configure shortcuts...", ""),
("Enable keyboard shortcuts in remote session", ""),
("shortcut-page-description", ""),
("shortcut-passthrough-tip", ""),
("Pass-through to remote", ""),
("Reset to defaults", ""),
("shortcut-reset-confirm-tip", ""),
("Monitor", ""),
("Keyboard", ""),
("Toggle fullscreen", ""),
("Switch to next display", ""),
("Switch to previous display", ""),
("Switch to next tab", ""),
("Switch to previous tab", ""),
("Toggle session recording", ""),
("Close tab", ""),
("Toggle toolbar", ""),
("Toggle input source", ""),
("Edit", ""),
("Save", ""),
("Set shortcut", ""),
("shortcut-recording-instruction", ""),
("shortcut-recording-press-keys-tip", ""),
("shortcut-must-include-modifiers", ""),
("shortcut-already-bound-to", ""),
("Replace", ""),
("Valid", ""),
("shortcut-mobile-physical-keyboard-tip", ""),
("shortcut-key-not-supported", ""),
("On", ""),
("Off", ""),
("Keyboard shortcuts", "Atalhos de teclado"),
("Configure shortcuts...", "Configurar atalhos..."),
("Enable keyboard shortcuts in remote session", "Ativar atalhos de teclado na sessão remota"),
("shortcut-page-description", "Associe uma combinação de teclas a cada ação de sessão abaixo. Cada associação tem de incluir pelo menos uma tecla modificadora."),
("shortcut-passthrough-tip", "Quando ativado, todas as combinações associadas são reencaminhadas para o remoto. Útil quando uma associação colide com algo de que precisa no remoto."),
("Pass-through to remote", "Reencaminhar para o remoto"),
("Reset to defaults", "Repor predefinições"),
("shortcut-reset-confirm-tip", "Isto irá substituir todas as associações atuais pelo conjunto predefinido. Continuar?"),
("Monitor", "Monitor"),
("Keyboard", "Teclado"),
("Toggle fullscreen", "Alternar ecrã inteiro"),
("Switch to next display", "Mudar para o ecrã seguinte"),
("Switch to previous display", "Mudar para o ecrã anterior"),
("Switch to next tab", "Mudar para o separador seguinte"),
("Switch to previous tab", "Mudar para o separador anterior"),
("Toggle session recording", "Alternar gravação da sessão"),
("Close tab", "Fechar separador"),
("Toggle toolbar", "Alternar barra de ferramentas"),
("Toggle input source", "Alternar fonte de entrada"),
("Edit", "Editar"),
("Save", "Guardar"),
("Set shortcut", "Definir atalho"),
("shortcut-recording-instruction", "Prima a combinação de teclas que pretende utilizar."),
("shortcut-recording-press-keys-tip", "Prima uma combinação de teclas..."),
("shortcut-must-include-modifiers", "Tem de incluir pelo menos uma tecla modificadora: {}"),
("shortcut-already-bound-to", "Este atalho já está associado a"),
("Replace", "Substituir"),
("Valid", "Válido"),
("shortcut-mobile-physical-keyboard-tip", "A gravação requer um teclado físico. Os teclados virtuais não são suportados."),
("shortcut-key-not-supported", "\"{}\" não pode ser usado como atalho."),
("On", "Ligado"),
("Off", "Desligado"),
("api_server_connection_tip", "O seu servidor personalizado utiliza HTTP não encriptado. Contacte o seu administrador para ativar o HTTPS."),
("api_server_empty_tip", "Com o servidor da API vazio, o seu servidor personalizado utiliza HTTP por predefinição. Contacte o seu administrador para ativar o HTTPS."),
].iter().cloned().collect();
}
+2
View File
@@ -813,5 +813,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("shortcut-key-not-supported", ""),
("On", ""),
("Off", ""),
("api_server_connection_tip", ""),
("api_server_empty_tip", ""),
].iter().cloned().collect();
}
+34 -32
View File
@@ -781,37 +781,39 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("Relay fallback delay in seconds", "Задержка перед переходом на ретранслятор в секундах"),
("relay-fallback-delay-tip", "Сколько времени уже установленное соединение через ретранслятор ждёт прямое соединение WebRTC, прежде чем будет использовано вместо него. Увеличьте, чтобы дать медленному прямому соединению больше времени; уменьшите, чтобы быстрее переходить на ретранслятор в сетях, где прямое соединение невозможно. Оставьте пустым для значения по умолчанию 2.5 секунды."),
("To start a voice call, enable \"Audio capture\" on the \"Share screen\" page.", "Чтобы начать голосовой вызов, включите \"Захват аудио\" на странице \"Демонстрация экрана\"."),
("Keyboard shortcuts", ""),
("Configure shortcuts...", ""),
("Enable keyboard shortcuts in remote session", ""),
("shortcut-page-description", ""),
("shortcut-passthrough-tip", ""),
("Pass-through to remote", ""),
("Reset to defaults", ""),
("shortcut-reset-confirm-tip", ""),
("Monitor", ""),
("Keyboard", ""),
("Toggle fullscreen", ""),
("Switch to next display", ""),
("Switch to previous display", ""),
("Switch to next tab", ""),
("Switch to previous tab", ""),
("Toggle session recording", ""),
("Close tab", ""),
("Toggle toolbar", ""),
("Toggle input source", ""),
("Edit", ""),
("Save", ""),
("Set shortcut", ""),
("shortcut-recording-instruction", ""),
("shortcut-recording-press-keys-tip", ""),
("shortcut-must-include-modifiers", ""),
("shortcut-already-bound-to", ""),
("Replace", ""),
("Valid", ""),
("shortcut-mobile-physical-keyboard-tip", ""),
("shortcut-key-not-supported", ""),
("On", ""),
("Off", ""),
("Keyboard shortcuts", "Сочетания клавиш"),
("Configure shortcuts...", "Настроить сочетания клавиш..."),
("Enable keyboard shortcuts in remote session", "Использовать сочетания клавиш в удалённом сеансе"),
("shortcut-page-description", "Привязка сочетаний клавиш к действиям в сеансе. Каждое назначение должно включать хотя бы один модификатор."),
("shortcut-passthrough-tip", "Если включено, каждое настроенное сочетаний клавиш пересылается на удалённое устройство. Полезно, если настроенное сочетание клавиш конфликтует с чем-то нужным на удалённом устройстве."),
("Pass-through to remote", "Отправлять на удалённое устройство"),
("Reset to defaults", "Сбросить настройки по умолчанию"),
("shortcut-reset-confirm-tip", "Все текущие настроенные сочетания клавиш будут заменены на настройки по умолчанию. Продолжить?"),
("Monitor", "Монитор"),
("Keyboard", "Клавиатура"),
("Toggle fullscreen", "Переключить полноэкранный режим"),
("Switch to next display", "Переключиться на следующий дисплей"),
("Switch to previous display", "Переключиться на предыдущий дисплей"),
("Switch to next tab", "Переключиться на следующую вкладку"),
("Switch to previous tab", "Переключиться на предыдущую вкладку"),
("Toggle session recording", "Переключить запись сеанса"),
("Close tab", "Закрыть вкладку"),
("Toggle toolbar", "Переключить панель инструментов"),
("Toggle input source", "Переключить источник ввода"),
("Edit", "Изменить"),
("Save", "Сохранить"),
("Set shortcut", "Настроить сочетание клавиш"),
("shortcut-recording-instruction", "Нажмите сочетание клавиш, которое хотите использовать."),
("shortcut-recording-press-keys-tip", "Нажмите сочетание клавиш..."),
("shortcut-must-include-modifiers", "Необходимо использовать хотя бы один модификатор: {}"),
("shortcut-already-bound-to", "Уже привязано к"),
("Replace", "Заменить"),
("Valid", "Допустимо"),
("shortcut-mobile-physical-keyboard-tip", "Для записи требуется физическая клавиатура. Экранные клавиатуры не поддерживаются."),
("shortcut-key-not-supported", "\"{}\" невозможно использовать как сочетание клавиш."),
("On", "вкл"),
("Off", "откл"),
("api_server_connection_tip", ""),
("api_server_empty_tip", ""),
].iter().cloned().collect();
}
+2
View File
@@ -813,5 +813,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("shortcut-key-not-supported", ""),
("On", ""),
("Off", ""),
("api_server_connection_tip", ""),
("api_server_empty_tip", ""),
].iter().cloned().collect();
}
+2
View File
@@ -813,5 +813,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("shortcut-key-not-supported", ""),
("On", ""),
("Off", ""),
("api_server_connection_tip", ""),
("api_server_empty_tip", ""),
].iter().cloned().collect();
}
+2
View File
@@ -813,5 +813,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("shortcut-key-not-supported", ""),
("On", ""),
("Off", ""),
("api_server_connection_tip", ""),
("api_server_empty_tip", ""),
].iter().cloned().collect();
}
+2
View File
@@ -813,5 +813,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("shortcut-key-not-supported", ""),
("On", ""),
("Off", ""),
("api_server_connection_tip", ""),
("api_server_empty_tip", ""),
].iter().cloned().collect();
}
+2
View File
@@ -813,5 +813,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("shortcut-key-not-supported", ""),
("On", ""),
("Off", ""),
("api_server_connection_tip", ""),
("api_server_empty_tip", ""),
].iter().cloned().collect();
}
+2
View File
@@ -813,5 +813,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("shortcut-key-not-supported", ""),
("On", ""),
("Off", ""),
("api_server_connection_tip", ""),
("api_server_empty_tip", ""),
].iter().cloned().collect();
}
+2
View File
@@ -813,5 +813,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("shortcut-key-not-supported", ""),
("On", ""),
("Off", ""),
("api_server_connection_tip", ""),
("api_server_empty_tip", ""),
].iter().cloned().collect();
}
+2
View File
@@ -813,5 +813,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("shortcut-key-not-supported", ""),
("On", ""),
("Off", ""),
("api_server_connection_tip", ""),
("api_server_empty_tip", ""),
].iter().cloned().collect();
}
+2
View File
@@ -813,5 +813,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("shortcut-key-not-supported", ""),
("On", ""),
("Off", ""),
("api_server_connection_tip", ""),
("api_server_empty_tip", ""),
].iter().cloned().collect();
}
+2
View File
@@ -813,5 +813,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("shortcut-key-not-supported", ""),
("On", ""),
("Off", ""),
("api_server_connection_tip", ""),
("api_server_empty_tip", ""),
].iter().cloned().collect();
}
+2
View File
@@ -813,5 +813,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("shortcut-key-not-supported", ""),
("On", ""),
("Off", ""),
("api_server_connection_tip", "自訂伺服器正在使用未加密的 HTTP。請聯絡管理員啟用 HTTPS。"),
("api_server_empty_tip", "API 伺服器留空時,自訂伺服器預設使用 HTTP。請聯絡管理員啟用 HTTPS。"),
].iter().cloned().collect();
}
+2
View File
@@ -813,5 +813,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("shortcut-key-not-supported", ""),
("On", ""),
("Off", ""),
("api_server_connection_tip", ""),
("api_server_empty_tip", ""),
].iter().cloned().collect();
}
+2
View File
@@ -813,6 +813,8 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("shortcut-key-not-supported", ""),
("On", ""),
("Off", ""),
("api_server_connection_tip", ""),
("api_server_empty_tip", ""),
].iter().cloned().collect();
}
+2
View File
@@ -813,5 +813,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("shortcut-key-not-supported", ""),
("On", ""),
("Off", ""),
("api_server_connection_tip", ""),
("api_server_empty_tip", ""),
].iter().cloned().collect();
}
+4
View File
@@ -18,6 +18,10 @@ fn main() {
#[cfg(not(any(target_os = "android", target_os = "ios", feature = "flutter")))]
fn main() -> std::process::ExitCode {
#[cfg(windows)]
if let Some(exit_code) = platform::handle_service_control() {
return exit_code;
}
#[cfg(all(windows, not(feature = "inline")))]
unsafe {
winapi::um::shellscalingapi::SetProcessDpiAwareness(2);
+61 -1
View File
@@ -891,6 +891,43 @@ fn get_all_term_values(uid: &str) -> Vec<String> {
terms
}
fn append_audio_latency_envs(
envs: &mut Vec<(&'static str, String)>,
get_var: impl Fn(&str) -> Option<String>,
) {
for key in ["PULSE_LATENCY_MSEC", "PIPEWIRE_LATENCY"] {
if let Some(value) = get_var(key).filter(|value| !value.is_empty()) {
envs.push((key, value));
}
}
}
#[cfg(test)]
mod audio_latency_env_tests {
use super::append_audio_latency_envs;
#[test]
fn forwards_configured_values_without_creating_defaults() {
let mut envs = Vec::new();
append_audio_latency_envs(&mut envs, |key| match key {
"PULSE_LATENCY_MSEC" => Some("60".to_owned()),
"PIPEWIRE_LATENCY" => Some("1024/48000".to_owned()),
_ => None,
});
assert_eq!(
envs,
vec![
("PULSE_LATENCY_MSEC", "60".to_owned()),
("PIPEWIRE_LATENCY", "1024/48000".to_owned()),
]
);
envs.clear();
append_audio_latency_envs(&mut envs, |_| None);
assert!(envs.is_empty());
}
}
#[inline]
fn try_start_server_(desktop: Option<&Desktop>) -> ResultType<Option<Child>> {
match desktop {
@@ -921,6 +958,9 @@ fn try_start_server_(desktop: Option<&Desktop>) -> ResultType<Option<Child>> {
));
}
}
append_audio_latency_envs(&mut envs, |key| std::env::var(key).ok());
envs.push((
"TERM",
get_cur_term(&desktop.uid).unwrap_or_else(|| suggest_best_term()),
@@ -1895,7 +1935,7 @@ fn get_width_height_from_captures<'t>(caps: &Captures<'t>) -> Option<(i32, i32)>
#[inline]
fn get_xrandr_conn_pat(name: &str) -> String {
format!(
r"{}\s+connected.+?(?P<width>\d+)x(?P<height>\d+)\+(?P<x>\d+)\+(?P<y>\d+).*?\n",
r"(?m)^{}\s+connected.+?(?P<width>\d+)x(?P<height>\d+)\+(?P<x>\d+)\+(?P<y>\d+).*?\n",
name
)
}
@@ -1977,6 +2017,26 @@ pub fn current_resolution(name: &str) -> ResultType<Resolution> {
bail!("Failed to find current resolution for {}", name);
}
#[cfg(test)]
mod xrandr_tests {
use super::*;
#[test]
fn output_name_does_not_match_inside_another_name() {
let xrandr_output = "Screen 0: minimum 320 x 200, current 4480 x 1440, maximum 16384 x 16384
eDP-1 connected primary 1920x1080+0+0 (normal left inverted right x axis y axis) 309mm x 174mm
1920x1080 60.01*+ 59.97
1280x720 60.00
DP-1 connected 2560x1440+1920+0 (normal left inverted right x axis y axis) 597mm x 336mm
2560x1440 59.95*+
1920x1080 60.00
";
let re = Regex::new(&get_xrandr_conn_pat("DP-1")).unwrap();
let caps = re.captures(xrandr_output).unwrap();
assert_eq!(get_width_height_from_captures(&caps), Some((2560, 1440)));
}
}
pub fn change_resolution_directly(name: &str, width: usize, height: usize) -> ResultType<()> {
Command::new("xrandr")
.args(vec![
+17
View File
@@ -15,6 +15,23 @@
#include <sddl.h>
#include <memory>
#ifdef RUSTDESK_SCITER
// Share the runner's service operations without loading either UI framework.
#include "../../flutter/windows/runner/service_control.h"
extern "C" DWORD run_service_control()
{
int count = 0;
wchar_t** args = CommandLineToArgvW(GetCommandLineW(), &count);
if (!args) {
return GetLastError();
}
const DWORD result = service_control::RunCommand(count, args);
LocalFree(args);
return result;
}
#endif
extern "C" uint32_t get_session_user_info(PWSTR bufin, uint32_t nin, uint32_t id);
void flog(char const *fmt, ...)
+138 -35
View File
@@ -97,6 +97,7 @@ use windows_service::{
use winreg::{enums::*, RegKey};
mod acl;
pub(crate) mod installer_files;
mod installer_handoff;
mod installer_shell;
mod verified_update;
@@ -107,10 +108,10 @@ pub use acl::{
set_path_permission_for_portable_service_shmem_file,
validate_path_for_portable_service_shmem_dir,
};
use installer_handoff::run_cmds;
use installer_handoff::{run_cmds, InstallCommands};
use installer_shell::{
embedded_shortcut_commands, embedded_tray_shortcut_commands, escape_nested_cmd_ampersands,
shortcut_bytes, validate_install_value,
escape_nested_cmd_ampersands, shortcut_bytes, staged_shortcut_commands,
staged_tray_shortcut_commands, validate_install_value,
};
pub use verified_update::{
copy_and_verify_update_file_sha256, schedule_current_verified_update_file_cleanup,
@@ -1675,18 +1676,16 @@ pub fn install_me(options: &str, path: String, silent: bool, debug: bool) -> Res
// The elevated runner expands this to `%~f0.dir`, beside its protected copy.
// Do not stage privileged shortcut artifacts in the user-writable `%TEMP%`.
let tmp_path = "%RUSTDESK_OUTPUT_DIR%".to_owned();
let mk_shortcut_commands = embedded_shortcut_commands(
let (mk_shortcut_commands, mk_shortcut_file) = staged_shortcut_commands(
shortcut_bytes(&exe, None, shortcut_icon_location.as_deref())?,
&format!("{app_name}.lnk"),
"mk_shortcut",
);
let uninstall_shortcut_commands = embedded_shortcut_commands(
)?;
let (uninstall_shortcut_commands, uninstall_shortcut_file) = staged_shortcut_commands(
shortcut_bytes(&exe, Some("--uninstall"), Some("msiexec.exe"))?,
&format!("Uninstall {app_name}.lnk"),
"uninstall_shortcut",
);
let tray_shortcut_commands =
embedded_tray_shortcut_commands(&app_name, &exe, shortcut_icon_location.as_deref())?;
)?;
let (tray_shortcut_commands, tray_shortcut_file) =
staged_tray_shortcut_commands(&app_name, &exe, shortcut_icon_location.as_deref())?;
let mut reg_value_desktop_shortcuts = "0".to_owned();
let mut reg_value_start_menu_shortcuts = "0".to_owned();
let mut reg_value_printer = "0".to_owned();
@@ -1760,6 +1759,17 @@ copy /Y \"{tmp_path}\\{app_name} Tray.lnk\" \"%PROGRAMDATA%\\Microsoft\\Windows\
"".to_owned()
};
let after_install = get_after_install(
&exe,
Some(reg_value_start_menu_shortcuts),
Some(reg_value_desktop_shortcuts),
Some(reg_value_printer),
);
let after_install = native_after_install_commands(
format!("{after_install}\r\n{install_remote_printer}"),
&exe,
true,
)?;
// Remember to check if `update_me` need to be changed if changing the `cmds`.
// No need to merge the existing dup code, because the code in these two functions are too critical.
// New code should be written in a common function.
@@ -1791,25 +1801,25 @@ copy /Y \"{tmp_path}\\Uninstall {app_name}.lnk\" \"{path}\\\"
{dels}
{import_config}
{after_install}
{install_remote_printer}
{sleep}
",
display_icon = shortcut_icon_location.as_deref().unwrap_or(exe.as_str()),
nested_exe = escape_nested_cmd_ampersands(&exe),
version = crate::VERSION.replace("-", "."),
build_date = crate::BUILD_DATE,
after_install = get_after_install(
&exe,
Some(reg_value_start_menu_shortcuts),
Some(reg_value_desktop_shortcuts),
Some(reg_value_printer)
),
sleep = if debug { "timeout 300" } else { "" },
dels = if debug { "" } else { &dels },
copy_exe = copy_exe_cmd(&src_exe, &exe, &path)?,
import_config = get_import_config(&exe),
);
run_cmds(cmds, debug, "install")?;
run_cmds(
InstallCommands {
script: cmds,
files: vec![mk_shortcut_file, uninstall_shortcut_file, tray_shortcut_file],
},
debug,
"install",
)?;
run_after_run_cmds(silent);
Ok(())
}
@@ -1817,29 +1827,30 @@ copy /Y \"{tmp_path}\\Uninstall {app_name}.lnk\" \"{path}\\\"
pub fn run_after_install() -> ResultType<()> {
let (_, _, _, exe) = get_install_info();
run_cmds(
get_after_install(&exe, None, None, None),
native_after_install_commands(get_after_install(&exe, None, None, None), &exe, false)?,
true,
"after_install",
)
}
pub fn run_before_uninstall() -> ResultType<()> {
run_cmds(get_before_uninstall(true), true, "before_install")
run_cmds(get_before_uninstall(true)?, true, "before_install")
}
fn get_before_uninstall(kill_self: bool) -> String {
fn get_before_uninstall(kill_self: bool) -> ResultType<String> {
let app_name = crate::get_app_name();
let (_, _, _, exe) = get_install_info();
let remove_service = service_control_command("remove", &exe, false)?;
let ext = app_name.to_lowercase();
let filter = if kill_self {
"".to_string()
} else {
format!(" /FI \"PID ne {}\"", get_current_pid())
};
format!(
Ok(format!(
"
chcp 65001
sc stop {app_name}
sc delete {app_name}
{remove_service}
taskkill /F /IM {broker_exe}
taskkill /F /IM {app_name}.exe{filter}
reg delete HKEY_CLASSES_ROOT\\.{ext} /f
@@ -1847,7 +1858,7 @@ fn get_before_uninstall(kill_self: bool) -> String {
netsh advfirewall firewall delete rule name=\"{app_name} Service\"
",
broker_exe = WIN_TOPMOST_INJECTED_PROCESS_EXE,
)
))
}
/// Constructs the uninstall command string for the application.
@@ -1894,7 +1905,7 @@ fn get_uninstall(kill_self: bool, uninstall_printer: bool) -> ResultType<String>
if exist \"%PUBLIC%\\Desktop\\{app_name}.lnk\" del /f /q \"%PUBLIC%\\Desktop\\{app_name}.lnk\"
if exist \"%PROGRAMDATA%\\Microsoft\\Windows\\Start Menu\\Programs\\Startup\\{app_name} Tray.lnk\" del /f /q \"%PROGRAMDATA%\\Microsoft\\Windows\\Start Menu\\Programs\\Startup\\{app_name} Tray.lnk\"
",
before_uninstall=get_before_uninstall(kill_self),
before_uninstall=get_before_uninstall(kill_self)?,
uninstall_amyuni_idd=get_uninstall_amyuni_idd(),
app_name = crate::get_app_name(),
))
@@ -3323,15 +3334,24 @@ pub fn try_lock_tray_single_instance() -> bool {
}
}
/// Returns `true` on failure or cancellation so the caller keeps running.
/// Successful removal exits this process instead of returning.
pub fn uninstall_service(show_new_window: bool, _: bool) -> bool {
log::info!("Uninstalling service...");
let filter = format!(" /FI \"PID ne {}\"", get_current_pid());
let (_, _, _, exe) = get_install_info();
let remove_service = match service_control_command("remove", &exe, false) {
Ok(commands) => commands,
Err(err) => {
log::error!("Failed to prepare service removal: {err}");
return true;
}
};
Config::set_option("stop-service".into(), "Y".into());
let cmds = format!(
"
chcp 65001
sc stop {app_name}
sc delete {app_name}
{remove_service}
if exist \"%PROGRAMDATA%\\Microsoft\\Windows\\Start Menu\\Programs\\Startup\\{app_name} Tray.lnk\" del /f /q \"%PROGRAMDATA%\\Microsoft\\Windows\\Start Menu\\Programs\\Startup\\{app_name} Tray.lnk\"
taskkill /F /IM {broker_exe}
taskkill /F /IM {app_name}.exe{filter}
@@ -3348,7 +3368,7 @@ pub fn uninstall_service(show_new_window: bool, _: bool) -> bool {
std::process::exit(0);
}
fn get_install_service_commands(path: &str, exe: &str) -> ResultType<String> {
fn get_install_service_commands(path: &str, exe: &str) -> ResultType<InstallCommands> {
let app_name = crate::get_app_name();
for value in [path, exe] {
validate_install_value(value)?;
@@ -3363,10 +3383,10 @@ fn get_install_service_commands(path: &str, exe: &str) -> ResultType<String> {
if let Some(icon) = shortcut_icon_location.as_deref() {
validate_install_value(icon)?;
}
let tray_shortcut_commands =
embedded_tray_shortcut_commands(&app_name, exe, shortcut_icon_location.as_deref())?;
let (tray_shortcut_commands, tray_shortcut_file) =
staged_tray_shortcut_commands(&app_name, exe, shortcut_icon_location.as_deref())?;
let filter = format!(" /FI \"PID ne {}\"", get_current_pid());
Ok(format!(
let script = format!(
"
chcp 65001
taskkill /F /IM {app_name}.exe{filter}
@@ -3376,8 +3396,12 @@ copy /Y \"%RUSTDESK_OUTPUT_DIR%\\{app_name} Tray.lnk\" \"%PROGRAMDATA%\\Microsof
{create_service}
",
import_config = get_import_config(exe),
create_service = get_create_service(exe),
))
create_service = service_control_command("create-service-with-rollback", exe, false)?,
);
Ok(InstallCommands {
script,
files: vec![tray_shortcut_file],
})
}
pub fn install_service() -> bool {
@@ -3928,7 +3952,86 @@ pub fn update_me_msi(msi: &str, expected_sha256: &str, quiet: bool) -> ResultTyp
verified_update::install_verified_msi(msi, expected_sha256, quiet)
}
fn native_after_install_commands(
commands: String,
exe: &str,
installed_now: bool,
) -> ResultType<String> {
let service = get_create_service(exe);
if service.is_empty() {
return Ok(commands);
}
let native_service = service_control_command("create-service", exe, installed_now)?;
if native_service == service {
return Ok(commands);
}
// Complete independent setup before service-start errors can exit the BAT.
Ok(format!(
"{}\r\n{native_service}",
commands.replacen(&service, "", 1)
))
}
#[cfg(not(feature = "flutter"))]
pub fn handle_service_control() -> Option<std::process::ExitCode> {
if std::env::args_os().nth(1).as_deref() != Some(std::ffi::OsStr::new("--service-control")) {
return None;
}
extern "C" {
fn run_service_control() -> u32;
}
let error = unsafe { run_service_control() };
Some(if error == ERROR_SUCCESS {
std::process::ExitCode::SUCCESS
} else {
eprintln!(
"RustDesk service control failed: {}",
std::io::Error::from_raw_os_error(error as i32)
);
std::process::ExitCode::FAILURE
})
}
fn service_control_command(operation: &str, exe: &str, installed_now: bool) -> ResultType<String> {
let app_name = crate::get_app_name();
let is_create = matches!(operation, "create-service" | "create-service-with-rollback");
let legacy = match operation {
"create-service" | "create-service-with-rollback" => get_create_service(exe),
"remove" => format!("sc stop {app_name}\r\nsc delete {app_name}"),
_ => bail!("Unsupported service operation: {operation}"),
};
if legacy.is_empty() || (is_create && Config::get_option("stop-service") == "Y") {
return Ok(legacy);
}
// A fresh installation has just copied this runner. Otherwise only use the
// new command when the caller is the installed executable; other versions
// may not recognize it.
if !installed_now {
let current = std::env::current_exe()?;
let current = current
.to_str()
.ok_or_else(|| anyhow!("Current executable path is not valid Unicode"))?;
if !current.eq_ignore_ascii_case(exe) {
log::debug!("Keeping legacy service commands for a different installed executable");
return Ok(legacy);
}
}
validate_install_value(exe)?;
let executable_argument = if is_create {
format!(" \"{exe}\"")
} else {
String::new()
};
Ok(format!(
"start \"\" /b /wait \"{exe}\" --service-control {operation} \"{app_name}\"{executable_argument}\r\n\
if not \"%errorlevel%\"==\"0\" exit /b %errorlevel%"
))
}
fn get_import_config(exe: &str) -> String {
// --import-config does not register a service dispatcher, so SCM can report
// a start failure even when import runs. Preserve this legacy contract for
// older installed executables.
if config::is_outgoing_only() {
return "".to_string();
}
+373
View File
@@ -0,0 +1,373 @@
use super::{installer_handoff::directory, wide_string};
use hbb_common::{anyhow::anyhow, log, ResultType};
use std::{
fs::{self, File},
io::{self, Read},
os::windows::io::{AsRawHandle, FromRawHandle},
path::{Path, PathBuf},
};
use windows::{
core::{w, Owned, PCWSTR},
Win32::{
Foundation::{DuplicateHandle, GENERIC_READ, GENERIC_WRITE, HANDLE, HLOCAL},
Security::{
Authorization::{
ConvertStringSecurityDescriptorToSecurityDescriptorW, SDDL_REVISION_1,
},
PSECURITY_DESCRIPTOR, SECURITY_ATTRIBUTES,
},
Storage::FileSystem::{
CreateFileW, FileDispositionInfo, SetFileInformationByHandle, CREATE_NEW, DELETE,
FILE_ATTRIBUTE_NORMAL, FILE_DISPOSITION_INFO, FILE_SHARE_READ,
},
System::Threading::GetCurrentProcess,
},
};
// Stage data before elevation instead of relaunching a verifier from a portable
// directory whose executable or DLLs could be replaced while UAC is pending.
pub(super) struct ProtectedInstallFile {
path: PathBuf,
cleanup_handle: Option<Owned<HANDLE>>,
}
impl ProtectedInstallFile {
pub(super) fn new(path: &Path, bytes: &[u8]) -> ResultType<Self> {
Self::create(path, &mut io::Cursor::new(bytes), None)
}
pub(super) fn copy_verified(source: &Path, expected_sha256: &str) -> ResultType<Self> {
let mut source = File::open(source)?;
let path = directory::path()?.with_extension("tmp");
Self::create(&path, &mut source, Some(expected_sha256))
}
fn create(
path: &Path,
source: &mut impl Read,
expected_sha256: Option<&str>,
) -> ResultType<Self> {
let mut file = create_protected_file(path)?;
let result = (|| -> ResultType<Owned<HANDLE>> {
io::copy(source, &mut file)?;
file.sync_all()?;
if let Some(expected) = expected_sha256 {
crate::update_hash::verify_sha256_reader(&mut file, expected).map_err(|error| {
anyhow!(
"Failed to verify staged installer file {}: {error:?}",
path.display()
)
})?;
}
duplicate_cleanup_handle(&file)
})();
let cleanup_handle = result.map_err(|error| {
// The initial handle can remove an incomplete file without reopening its protected path.
if let Err(cleanup_error) = delete_staged_file(HANDLE(file.as_raw_handle())) {
log::warn!(
"Failed to remove incomplete installer file {}: {cleanup_error}",
path.display()
);
}
error
})?;
Ok(Self {
path: path.to_owned(),
cleanup_handle: Some(cleanup_handle),
})
}
pub(super) fn path(&self) -> &Path {
&self.path
}
pub(super) fn release(&mut self) {
// cmd.exe cannot read/copy these files while a DELETE handle is open.
// The handoff gate keeps it waiting until every staged handle is closed.
drop(self.cleanup_handle.take());
}
}
impl Drop for ProtectedInstallFile {
fn drop(&mut self) {
// Cancellation cannot reopen the protected path with DELETE permission.
let result = match &self.cleanup_handle {
Some(handle) => delete_staged_file(**handle),
None => match fs::remove_file(&self.path) {
Err(error) if error.kind() != io::ErrorKind::NotFound => Err(error.into()),
_ => Ok(()),
},
};
if let Err(error) = result {
log::warn!(
"Protected installer file may remain at {}: {error}",
self.path.display()
);
}
}
}
fn create_protected_file(path: &Path) -> ResultType<File> {
let mut descriptor = PSECURITY_DESCRIPTOR::default();
// Restrict OWNER RIGHTS at creation so the unelevated creator cannot reopen
// the file for writing or grant itself that permission after staging.
unsafe {
ConvertStringSecurityDescriptorToSecurityDescriptorW(
w!("D:P(A;;FA;;;SY)(A;;FA;;;BA)(A;;FRFX;;;OW)"),
SDDL_REVISION_1,
&mut descriptor,
None,
)?;
}
let _descriptor = unsafe { Owned::new(HLOCAL(descriptor.0)) };
let attributes = SECURITY_ATTRIBUTES {
nLength: std::mem::size_of::<SECURITY_ATTRIBUTES>() as u32,
lpSecurityDescriptor: descriptor.0,
bInheritHandle: false.into(),
};
let path_string = path
.to_str()
.ok_or_else(|| anyhow!("Invalid protected installer path"))?;
let path_string = wide_string(path_string);
let handle = unsafe {
CreateFileW(
PCWSTR(path_string.as_ptr()),
GENERIC_READ.0 | GENERIC_WRITE.0 | DELETE.0,
FILE_SHARE_READ,
Some(&attributes),
CREATE_NEW,
FILE_ATTRIBUTE_NORMAL,
None,
)
}
.map_err(|error| {
anyhow!(
"Failed to create protected installer file {}: {error}",
path.display()
)
})?;
Ok(unsafe { File::from_raw_handle(handle.0) })
}
fn duplicate_cleanup_handle(file: &File) -> ResultType<Owned<HANDLE>> {
let mut handle = HANDLE::default();
// Retain deletion capability, not a writable handle, while waiting for UAC.
unsafe {
let process = GetCurrentProcess();
DuplicateHandle(
process,
HANDLE(file.as_raw_handle()),
process,
&mut handle,
DELETE.0,
false,
Default::default(),
)?;
Ok(Owned::new(handle))
}
}
fn delete_staged_file(handle: HANDLE) -> ResultType<()> {
let disposition = FILE_DISPOSITION_INFO {
DeleteFile: true.into(),
};
unsafe {
SetFileInformationByHandle(
handle,
FileDispositionInfo,
&disposition as *const _ as *const _,
std::mem::size_of_val(&disposition) as u32,
)?;
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use windows::{
core::BOOL,
Win32::{
Foundation::HANDLE,
Security::{
AccessCheck,
Authorization::{GetNamedSecurityInfoW, SE_FILE_OBJECT},
CreateRestrictedToken, CreateWellKnownSid, DuplicateToken, SecurityImpersonation,
WinBuiltinAdministratorsSid, DACL_SECURITY_INFORMATION, DISABLE_MAX_PRIVILEGE,
GENERIC_MAPPING, GROUP_SECURITY_INFORMATION, OWNER_SECURITY_INFORMATION,
PRIVILEGE_SET, PSID, SECURITY_MAX_SID_SIZE, SID_AND_ATTRIBUTES, TOKEN_DUPLICATE,
TOKEN_QUERY,
},
Storage::FileSystem::{
FILE_ALL_ACCESS, FILE_GENERIC_EXECUTE, FILE_GENERIC_READ, FILE_GENERIC_WRITE,
},
System::Threading::{GetCurrentProcess, OpenProcessToken},
},
};
#[test]
fn cancelled_staging_removes_files_without_parent_delete_permission() {
use windows::Win32::Security::{ImpersonateLoggedOnUser, RevertToSelf};
let root = std::env::temp_dir().join(format!("rustdesk-cancel-{}", uuid::Uuid::new_v4()));
fs::create_dir(&root).unwrap();
let path = root.join("package.tmp");
let file = ProtectedInstallFile::new(&path, b"cancelled update").unwrap();
// Omit DELETE_CHILD as in Windows Temp, but retain fixture ACL control.
set_parent_acl(&root, w!("D:P(A;;0x1600af;;;OW)"));
unsafe {
let token = ordinary_owner_token();
ImpersonateLoggedOnUser(*token).unwrap();
drop(file);
RevertToSelf().unwrap();
}
set_parent_acl(&root, w!("D:P(A;;FA;;;OW)"));
let remaining = fs::symlink_metadata(&path);
fs::remove_dir_all(&root).unwrap();
assert!(
matches!(remaining, Err(error) if error.kind() == io::ErrorKind::NotFound),
"Cancelled staging must remove the protected package"
);
}
fn set_parent_acl(path: &Path, sddl: PCWSTR) {
use windows::Win32::Security::{SetFileSecurityW, PROTECTED_DACL_SECURITY_INFORMATION};
let path = wide_string(path.to_str().unwrap());
let mut descriptor = PSECURITY_DESCRIPTOR::default();
unsafe {
ConvertStringSecurityDescriptorToSecurityDescriptorW(
sddl,
SDDL_REVISION_1,
&mut descriptor,
None,
)
.unwrap();
let _descriptor = Owned::new(HLOCAL(descriptor.0));
assert!(SetFileSecurityW(
PCWSTR(path.as_ptr()),
DACL_SECURITY_INFORMATION | PROTECTED_DACL_SECURITY_INFORMATION,
descriptor
)
.as_bool());
}
}
#[test]
fn staged_files_protect_contents_and_remove_unverified_data() {
const HASH: &str = "304ca1638c5effa6832e0e15b958a8f74847efe4df9c3f3187216e921c168fed";
let root = std::env::temp_dir().join(format!("rustdesk-staging-{}", uuid::Uuid::new_v4()));
fs::create_dir(&root).unwrap();
let path = root.join("input.tmp");
let file =
ProtectedInstallFile::create(&path, &mut io::Cursor::new(b"rustdesk"), Some(HASH))
.unwrap();
assert_eq!(
ordinary_owner_access(file.path()),
(FILE_GENERIC_READ | FILE_GENERIC_EXECUTE).0
);
assert_eq!(fs::read(file.path()).unwrap(), b"rustdesk");
assert!(ProtectedInstallFile::new(&path, b"replacement").is_err());
let rejected = root.join("rejected.tmp");
assert!(ProtectedInstallFile::create(
&rejected,
&mut io::Cursor::new(b"changed"),
Some(HASH)
)
.is_err());
assert!(!rejected.exists());
drop(file);
fs::remove_dir(root).unwrap();
}
fn ordinary_owner_access(path: &Path) -> u32 {
let path = wide_string(path.to_str().unwrap());
let mut descriptor = PSECURITY_DESCRIPTOR::default();
unsafe {
GetNamedSecurityInfoW(
PCWSTR(path.as_ptr()),
SE_FILE_OBJECT,
OWNER_SECURITY_INFORMATION | GROUP_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION,
None,
None,
None,
None,
&mut descriptor,
)
.ok()
.unwrap();
}
let _descriptor = unsafe { Owned::new(HLOCAL(descriptor.0)) };
let token = ordinary_owner_token();
let mapping = GENERIC_MAPPING {
GenericRead: FILE_GENERIC_READ.0,
GenericWrite: FILE_GENERIC_WRITE.0,
GenericExecute: FILE_GENERIC_EXECUTE.0,
GenericAll: FILE_ALL_ACCESS.0,
};
let mut privileges = PRIVILEGE_SET::default();
let mut size = std::mem::size_of::<PRIVILEGE_SET>() as u32;
let mut granted = 0;
let mut allowed = BOOL::default();
unsafe {
AccessCheck(
descriptor,
*token,
winapi::um::winnt::MAXIMUM_ALLOWED,
&mapping,
Some(&mut privileges),
&mut size,
&mut granted,
&mut allowed,
)
.unwrap();
}
assert!(allowed.as_bool());
granted
}
fn ordinary_owner_token() -> Owned<HANDLE> {
let mut original = HANDLE::default();
unsafe {
OpenProcessToken(
GetCurrentProcess(),
TOKEN_QUERY | TOKEN_DUPLICATE,
&mut original,
)
.unwrap();
}
let original = unsafe { Owned::new(original) };
let mut sid = [0; SECURITY_MAX_SID_SIZE as usize];
let sid_pointer = PSID(sid.as_mut_ptr().cast());
let mut size = sid.len() as u32;
unsafe {
CreateWellKnownSid(
WinBuiltinAdministratorsSid,
None,
Some(sid_pointer),
&mut size,
)
.unwrap();
}
let disabled = [SID_AND_ATTRIBUTES {
Sid: sid_pointer,
Attributes: 0,
}];
let mut restricted = HANDLE::default();
unsafe {
CreateRestrictedToken(
*original,
DISABLE_MAX_PRIVILEGE,
Some(&disabled),
None,
None,
&mut restricted,
)
.unwrap();
}
let restricted = unsafe { Owned::new(restricted) };
let mut impersonation = HANDLE::default();
unsafe {
DuplicateToken(*restricted, SecurityImpersonation, &mut impersonation).unwrap();
}
unsafe { Owned::new(impersonation) }
}
}

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