Files
rustdesk/src/ui_session_interface.rs
T
RustDeskandClaude Fable 5.1 ae6af2de43 Webrtc (#15684)
* feat: add rendezvous WebRTC signaling fields

* feat: route WebRTC ICE on controlled side

* feat: race WebRTC as a direct transport enhancement

* fix: route WebRTC ICE through rendezvous paths

* feat: WebRTC transport racing, DTLS identity binding, and pc-leak fixes

- prefer-P2P racing (race_transports_prefer_webrtc) across punch and RelayResponse; ICE bridge with 400ms candidate resend
- controlled-side answerer and ICE routing; sign local DTLS fingerprint into SignedId, controller verifies the binding fail-closed
- fix pc leaks: close_webrtc() on insecure-decline paths (io_loop, port_forward); compute direct before disarming the offerer guard
- point hbb_common to the WebRTC data-plane commit 9f5a296

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

* fix: preserve WebRTC transport preference

* feat: decouple WebRTC from UDP punch, route controlled signaling over TCP

- the WebRTC offer now rides any punch request; only an offer-less request
  may close and reuse the rendezvous socket for TCP punching
  (request_allows_tcp_punch replaces the udp_port-based invariant), with a
  separate offer-less request racing as the TCP fallback
- WebSocket mode no longer disables WebRTC — ws only tunnels the
  signaling/relay legs while ICE stays the only P2P path there; SOCKS proxy
  still disables it (ICE would bypass the proxy and leak the real IP)
- controlled side: WebRTC-only punch replies and trickled ICE candidates go
  over dedicated TCP connections to the rendezvous server instead of the UDP
  mediator channel, for ws/TCP-only hbbs deployments; drop the now-redundant
  rz_sender plumbing and the 400ms candidate re-send on that leg
- guard is_udp handling against responses to requests that advertised no
  udp_port; skip the IPv6 socket bind under force-relay
- test_udp_uat: drop the STUN port race — the punch port must come from the
  rendezvous server's TestNatResponse observing this socket's mapping, a
  STUN probe from another socket can advertise an unreachable port
- bump hbb_common (webrtc 0.13 MSRV pin rationale + upgrade checklist docs)

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

* fix: KCP/UDP resilience to ICMP resets; optional KCP congestion control

- treat ICMP-driven UDP socket errors (WSAECONNRESET 10054 on Windows,
  ECONNREFUSED on Linux) as packet loss in punch_udp and the KCP pump
  instead of tearing the session down; KCP retransmits through them and a
  truly dead link is still reaped by the pong/app-level timeouts
- resolve STUN hostnames via tokio::net::lookup_host so DNS never blocks a
  runtime worker; fix the inverted non-IPv4 error message
- add enable-kcp-congestion-control option (default on): switch the turbo
  profile to nc=0 so brief loss on constrained links no longer spirals into
  stalls; sender-side only, no wire negotiation
- pin kcp-sys to the rustdesk-patches branch: upstream main lost the
  RustDesk patches on the EasyTier sync, and this branch also wires
  set_kcp_config_factory into connection setup, making the option effective

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

* fix: carry switch_code through WebRTC relay fallbacks after rebase

The rebase onto master (switch-code feature) added an 8th request_relay
parameter; pass the interface's switch code from both WebRTC->relay
fallback paths so a role-swap session survives the fallback. Also drop
a duplicate bindgen 0.72.1 entry the Cargo.lock merge produced.

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

* fix: don't let the preferred branch's own relay preempt a direct fallback

race_transports_prefer_webrtc committed any success from its first argument
outright, on the assumption that it is the WebRTC connect. It is not: the call
site passes a whole punch attempt, which internally falls back to request_relay
when its direct transports fail. That relay was therefore committed instantly
while the offer-less fallback's TCP punch was still in flight — inverting the
preference this function exists to enforce, since the is_p2p predicate the
caller already supplies was applied only to the `others` branch.

Apply it to both branches: a direct result from either side still commits
immediately, and a relayed result from either side is held for the window so
the other side can land something direct. Also commit a held connection when
the surviving branch errors, which the previous code only did on the first
branch's failure path.

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

* fix: evict the oldest pending ICE candidate, not the newest

Candidates arrive in gathering order — host, then srflx, then relay — so a
full buffer was discarding exactly the ones that traverse NAT while keeping
host ones that only work on a shared LAN. Evict from the front instead.

Also document why the controller's ICE bridge must not reconnect on error, in
contrast to the controlled side's per-candidate retry: its socket address is
the return route itself (mangled into PunchHole.socket_addr, echoed back in
IceCandidate.socket_addr, resolved through tcp_punch), so a reconnect would
arrive from an address no route points at, and the server drops the old entry
when the connection closes. Once it dies both directions are dead, and
abandoning WebRTC is the correct response rather than retrying.

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

* fix: bound log volume on sites whose rate a peer or retry loop controls

Debug output goes to the log file, so a site that fires per received message
or per retry lets someone else decide how much a machine writes to disk. The
WebRTC work added the first such sites.

- KCP io loop: absorbing ICMP errors as packet loss made a broken socket write
  ~100 lines a second for the 60s until the pong timeout reaps it. Log by run
  instead: one line when a run starts, one per ~5s while it persists so a stuck
  socket stays visible, and one on recovery with the total.
- punch_udp: the recv error retries every 10ms for up to MAX_TIME, so one line
  per occurrence wrote thousands per punch. Log the first, report the count in
  the timeout message.
- ICE candidate paths (client, mediator): the peer sets the candidate rate and
  the rendezvous route carrying them needs no prior punch, so throttle to one
  line a minute each with the suppressed count.

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

* fix: the KCP io throttle reset itself every cycle, so it never throttled

The send and recv arms shared one counter, and an ICMP error on a connected
socket is reported once and then cleared — so the steady state is an
alternation: the send succeeds and clears the counter, the next recv reports
the error and finds the counter at 1, and logs. Every error still wrote a
line, at the ~100/s the previous commit set out to stop, while the
persistent-failure and recovery branches were unreachable.

Use one LogThrottle per direction instead of a hand-rolled counter. That
removes the shared state the bug lived in, drops a third throttling mechanism
in favour of the one already added, and leaves the surrounding `if let Err`
untouched rather than reshaping it into a match.

Also fix test_udp_uat's socket-error arm, the untreated twin of the punch_udp
site: it had no backoff at all, so a persistent error re-armed recv
immediately and spun the loop at CPU speed, one warn line per iteration.

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

* bump kcp-sys: 14 review fixes on rustdesk-patches (6e44b93 -> fa51c15)

Picks up the handshake-recovery work plus the review round on top of it:
ABBA deadlock between the endpoint's two DashMaps, graceful-close tail
truncation, mid-stream hole on ikcp_send failure, FIN retransmission for
lost-FIN half-open hangs, SYN-ACK budget burned on dropped packets,
spurious ConnectTimeout after a completed handshake, accept-backlog
overflow stranding conns, aliasing UB in the output callback, and the
log-facade/throttling cleanup (per-packet sites no longer reach the
debug-level file logger, peer-rate warns throttled).

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ExUfAkYbq8UC9pQCiLy8TQ

* ws: decouple ICE policy from force_relay — full-ICE WebRTC over WebSocket

WebSocket support folds into force_relay because a ws tunnel kills
classic TCP/UDP punching — but that conflated transport necessity with
relay policy, and the WebRTC decisions keyed off the merged flag: a ws
client built no offerer at all without TURN, and only a Relay-only-ICE
one with it. ws deployments could never reach a direct WebRTC
connection, which is exactly the path they are supposed to live on.

Split the flag. LoginConfigHandler now tracks policy_relay (the
force-always-relay option, an explicit relay request — /r ids and
retry-via-relay included — and proxy) separately; force_relay stays
policy_relay || use_ws() and keeps governing the classic paths, so
non-ws behavior is unchanged everywhere:

- the offerer's existence and ICE policy follow policy_relay: under
  pure ws the offer gathers every candidate type and may go direct;
  under relay-by-policy it stays Relay-only ICE, TURN-gated, exactly
  as before;
- the RelayResponse race applies the prefer-P2P window under ws (a
  direct ICE path is worth delaying an already-ready relay for) while
  policy relay keeps first-success semantics;
- the request carries webrtc_all_ice (hbb_common 64b54ab) so the
  controlled side knows the offer is full-ICE: it answers with full ICE
  and no TURN requirement, while offers without the bit keep today's
  relay-only answer path on every version-skew combination.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ExUfAkYbq8UC9pQCiLy8TQ

* bump kcp-sys: 7 review fixes on rustdesk-patches (fa51c15 -> 023a006)

Reverts the connect/accept/add_conn changes that regressed concurrent
connects (the state_map guard held across add_conn is load-bearing), states
the single-conn contract on KcpEndpoint so shared-endpoint behaviour stops
consuming review effort, pins the two invariants that keep truncated input
from aborting under panic='abort', and fixes three findings from external
review: sendwnd() echoing raw config instead of KCP's effective window (a
non-positive factory value stalled sending forever), the passive closer's
lost final FIN delaying EOF by up to ~20s, and the doubled window
overflowing for extreme factory values.

Lock-only change: cargo update -p kcp-sys also re-picked libloading's
windows-targets between two versions already present in the lock; that was
reverted to keep this commit to the one line it is about. cargo metadata
--locked passes on the result.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* ws: read the all-ICE declaration from the offer envelope, drop the proto field

Companion to hbb_common 68d2729: the full-ICE declaration now lives as
an `ice_policy: "all"` key inside the webrtc:// envelope, so the request
assembly no longer sets webrtc_all_ice and the controlled side asks the
envelope (endpoint_declares_all_ice) instead of a PunchHole field. The
rendezvous server carries the offer opaquely — no forwarding to keep in
sync. Skew behavior is unchanged: an unmarked or unparseable envelope
reads as the old Relay-only semantics.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ExUfAkYbq8UC9pQCiLy8TQ

* add enable-webrtc option; gate test_ipv6 under forced relay

OPTION_ENABLE_WEBRTC (hbb_common 48c2d4d) follows the udp/ipv6 punch
options end to end: default on against the public server, off against
private ones, same settings UI placement on desktop and mobile, and the
same bool2option local-option handling. Gates:

- controller: should_create_webrtc_offerer checks it first — no pc, no
  STUN/TURN gathering, no offer in the request;
- controlled: unlike the udp/ipv6 legs, which deliberately follow the
  request, answering builds a pc that gathers ICE from this host, so
  the answerer honors this machine's own switch too.

Translations for "Enable WebRTC P2P connection" added to all 50 lang
files next to the IPv6 entry (IPv6 and WebRTC are invariant terms in
the same grammatical slot in every one of them).

Also stop probing v6 reachability (test_ipv6) under any forced relay:
the v6 punch socket is never bound there, so the probe was wasted work
on every ws/proxy/relay connection.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ExUfAkYbq8UC9pQCiLy8TQ

* kcp: client-side integration tests over real loopback sockets

kcp-sys has been through two review rounds of behavioral fixes; the
client wrapper (kcp_io pumps, connect/accept deadlines, framed-stream
adaptation, guard lifetimes) had no tests pinning what rustdesk actually
relies on. Four now do, each through real 127.0.0.1 UDP sockets and the
BytesCodec framing sessions use:

- handshake + bidirectional framed roundtrip + graceful close: the peer
  observes end-of-stream instead of hanging (guard outlives the framed
  stream so the FIN goes out);
- a writer that queues 50 frames and closes immediately loses none of
  them - the client-side pin for the close-tail-drain semantics;
- socket errors after the peer vanishes are treated as loss: writes keep
  succeeding, nothing tears down (ICMP is advisory on connected UDP);
- the connect deadline holds when nothing answers.

Mutation-checked: dropping inbound forwarding in kcp_io reddens exactly
the three tests that need the pump, and the timeout test alone stays
green.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ExUfAkYbq8UC9pQCiLy8TQ

* ipc/auth: replace the local throttle with the shared throttled_log!

auth.rs predated hbb_common's LogThrottle and grew its own equivalent:
same shape (last_log_at + suppressed), same 5s interval, plus a helper
and three OnceLock<Mutex<..>> statics. It also counted the other way -
excluding the event being reported - so each of the three sites carried
two near-identical log::warn! arms to avoid printing "suppressed 0".

The shared macro covers all of it: one static per call site declared by
the expansion, and the multiplicity suffix appears only when there is
one, which is what those duplicated arms were for. 102 lines out, 27 in.

Behavior difference, deliberate: a burst now reads "(x47)" - the total
including this line - instead of "(suppressed 46 similar events)". One
number, no arithmetic, and one convention across the codebase.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ExUfAkYbq8UC9pQCiLy8TQ

* kcp: make the congestion-control profile opt-in, not the default

The branch had flipped KCP to nc=0 (built-in congestion window) for
every session. That is a transport-behavior change for all users made on
reasoning alone, and the reasoning does not decide it: which profile wins
depends on why packets are being lost.

nc=1 - what RustDesk has always shipped - never shrinks the send window,
so on a genuinely congested uplink it deepens the loss it is reacting to.
But nc=0's backoff is blunt: a fast retransmit halves the window while an
RTO sets cwnd = 1 outright (ikcp.c) and recovery slow-starts from one
packet, so on a link with random loss and no congestion - Wi-Fi
interference, a long-haul path - it reads loss as congestion and can
stall an interactive stream for seconds. That failure mode is also the
more visible one to a remote-desktop user.

No benchmark settles this either: a loopback A/B has no bottleneck queue,
hence no congestion to control, and would flatter nc=1 by construction.
Deciding it needs a shaped link or field data.

So keep the profile users already run and let the other one be asked for
("enable-kcp-congestion-control" = "Y"). Flipping the default later is a
one-line change once there is evidence. kcp-sys keeps its own test
covering the nc=0 path.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ExUfAkYbq8UC9pQCiLy8TQ

* android: define getifaddrs/freeifaddrs for the api-21 sysroot

Turning on hbb_common's "webrtc" feature pulls webrtc-util into the android
link, and its ifaces() -- reached from vnet::Net::new() on every ICE gather --
calls getifaddrs(). bionic exports getifaddrs/freeifaddrs only from API 24,
while flutter/ndk_*.sh builds against --platform 21, so every abi failed to
link on the undefined symbols.

Raising the platform to 24 would have to drag minSdkVersion 22 with it and
turn the link error into a load-time one on Android 5.1/6.0, so define the
two symbols instead, using the RTM_GETLINK + RTM_GETADDR netlink dump bionic
itself uses. The definition also shadows bionic's on API >= 24 rather than
delegating to it, so the path that ships is the path every test device runs.

Checked against synthesised netlink dumps on the host -- link/address parsing,
prefix masks, point-to-point, ipv6 scope ids, malformed and truncated messages
-- under UBSan and byte-exact guard malloc, with a deliberately unsigned
remainder as the negative control.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix three ways ws + WebRTC could not work in practice

Review of #15684 and hbb_common#579. Each of these left the code reading
correct while the feature did not function.

- The RelayResponse race classified P2P with `result.2 == "IPv6"`, but
  that site's futures are only ever the relay ("Relay"/"WebSocket") and
  the WebRTC branch's own "WebRTC" — so the predicate was constantly
  false. When the relay landed first the result was still right (the
  webrtc arm's `others_fut.is_none()` fallback), but when WebRTC
  connected FIRST it was parked as if it were a relay and the relay was
  committed on arrival, discarding a live direct connection. That is the
  LAN case: the better the network, the worse the outcome. Classify by
  what the label means, via is_direct_transport, and test both orderings
  — only the relay-first one was covered.

- handle_peer_info wrote "force-always-relay=Y" into the peer's saved
  config whenever force_relay was set, which now includes the WebSocket
  transport. One ws session therefore turned the peer into a permanent
  relay-by-policy peer, and relay-by-policy means Relay-only ICE, so
  WebRTC could never go direct to it again — the flagship path worked
  exactly once. Persist policy_relay, which is the user's choice; the
  transport is a property of this client, not of the peer.

- The answerer gated on this machine's enable-webrtc option, but that is
  LocalConfig: the UI process writes it and never syncs it over IPC,
  while handle_punch_hole runs in the server process, which on Windows
  resolves LocalConfig under a different profile and reads the
  private-server default of "N". The gate refused to answer in exactly
  the self-hosted deployments the transport exists for. Drop it: the
  answerer follows the request, like the udp/ipv6 legs, and the option
  still gates the feature where it can — an offer only exists because
  some controller had it enabled.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ExUfAkYbq8UC9pQCiLy8TQ

* webrtc: close without an await point; do not report an unknown path as direct

- close_webrtc is no longer async (hbb_common 88f965f), so the ten call
  sites in port_forward and io_loop - all inside select! arms or futures
  the UI can abandon - can no longer be cancelled mid-teardown, which
  left the pc unclosable and its session entry stranded. Client's own
  spawn_close_webrtc went with it: the runtime-teardown guard it existed
  for now lives in close_detached, so both Drop paths share one
  implementation.

- webrtc_relayed() returns None when no candidate pair is selected or
  the pc closed under a concurrent teardown, and both call sites read
  that as "not relayed", i.e. direct. A TURN-relayed session could
  therefore be shown to the user as peer-to-peer. Claiming a direct path
  needs evidence of one, so an unknown answer now counts as relayed.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ExUfAkYbq8UC9pQCiLy8TQ

* scrap/benchmark: give the Duration divisor an explicit u32

The webrtc feature pulls time 0.3 into scrap's graph (hbb_common ->
webrtc -> webrtc-dtls -> der-parser -> asn1-rs), and that crate carries
an `impl Div<time::Duration> for std::time::Duration`. Orphan rules
allow it because the RHS is its own type, and trait impls are visible
across the whole dependency graph without a use, so std::time::Duration
now has two Div candidates. `yuv_count as _` casts to a plain inference
variable, which both candidates fit, so it stops resolving:

  error[E0282]: type annotations needed
    --> libs/scrap/examples/benchmark.rs:146:33

Only two of the four sites are reported - rustc emits one E0282 per
function body - so all four are annotated. The already-explicit
`as u32` at the hwcodec site and `start.elapsed() / cnt` are unaffected,
the latter because an integer literal's variable can only unify with an
integral type and rules the time impl out on its own.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* webrtc: judge the race by the resolved path, not the label; bound the ICE queue

Third review round. Two of these are regressions from the previous one.

- The RelayResponse race predicate was `is_direct_transport(result.2)`,
  which answers true for the label "WebRTC" - but WebRTC is only a
  direct path when ICE nominated a non-TURN pair. A TURN-relayed WebRTC
  result therefore committed instantly and cancelled the IPv6 attempt
  racing beside it, which is the same inversion the previous fix removed
  in the other direction. (That fix was also argued from a wrong premise:
  the site does carry an IPv6 future, pushed ~50 lines earlier than the
  relay one.) Each future now resolves whether its path is direct and
  the predicate reads that bool, matching the outer race, and the
  downstream recomputation goes away.

- policy_relay still folded in Config::is_proxy(), and that is what gets
  persisted into the peer's config as force-always-relay - so one
  session through a proxy pinned the peer to relay forever and disabled
  WebRTC for it, exactly the latch the previous round fixed for
  WebSocket. Split out peer_relay: the saved option or an explicit
  request for THIS peer, and the only part written back.

- The controlled side buffered remote ICE candidates in an unbounded
  channel while the controller caps the same buffer at 64, and draining
  one costs a JSON parse plus the ICE agent's lock. Whoever can reach a
  session's route could grow it without limit inside the long-lived
  service process. Bounded, with the overflow logged through the
  existing throttle.

- That route was also removed by key alone when an answerer finished, so
  a punch retry that built a fresh answerer under the same fingerprint
  had its live sender deleted by the previous one's cleanup - after
  which it received no candidates at all. Evict only our own sender, the
  way the session cache already guards the analogous case.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ExUfAkYbq8UC9pQCiLy8TQ

* webrtc: trim the comments to AGENTS.md length; drop is_direct_transport

386 added comment lines down to 287 across client, mediator, kcp_stream
and common. Same rule as hbb_common 3d64e43: out go past-bug narration,
rejected alternatives, measurements and restatements of the code; the
non-derivable why stays.

is_direct_transport goes with them. Judging the race by a transport
label was replaced by the resolved direct flag, leaving it used only by
its own test — and, having been inserted between the doc comment and
race_transports_prefer_webrtc, it had also taken that function's
contract with it. Removing it reattaches the doc where it belongs.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ExUfAkYbq8UC9pQCiLy8TQ

* webrtc: fix race edge cases that discard or mislabel a direct connection

Three correctness fixes in the transport race, plus three convention
cleanups.

- race_transports_prefer_webrtc committed a relayed result while a direct
  attempt was still in flight: the others arm returned on
  webrtc_fut.is_none() even with an unfinished direct future, and the
  WebRTC-error arm returned a held relay without checking others_fut. A
  relay is now committed only when nothing direct can still arrive (or
  the window expires); a parked relay is also preferred over composing
  an error when both sides fail. Three regression tests, mutation-checked.

- connect()'s plain select_ok let a TURN-relayed WebRTC win as "first
  success", dropping still-racing UDP/IPv6 direct attempts and reporting
  the relayed pair as direct. It now runs through the same prefer-P2P
  race with each attempt carrying whether its path is direct, and the
  WebRTC future resolves is_relayed() so a TURN win is held behind
  direct attempts, not committed as one.

- The RelayResponse path kept direct == true when a WebRTC win's DTLS
  handshake failed and it fell back to relay, so the relay was reported
  P2P. Clear the flag with the transport switch.

- Trim the OffererGuard doc to the three-line max; move the new
  enable-webrtc localization key to the end of every lang list; the KCP
  option constant moved to hbb_common config::keys (0f663aa).

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ExUfAkYbq8UC9pQCiLy8TQ

* bump hbb_common: WebRTC peer connections own their I/O runtime

Closing the controlling window left the controlled side waiting out
ICE decay — ~25-30s in the peer's log, its disconnected/failed ladder
running to completion — where TCP delivers a FIN at once. The session
end closed the pc by spawning onto io_loop's own
`#[tokio::main(flavor = "current_thread")]` runtime, which is dropped
the moment io_loop returns, and nothing after that call yields: the
task was never polled even once, so no DTLS close_notify ever left.

Every attempt to fix that on the caller's side failed the same way,
because the mismatch was never about where the close ran: a pc's UDP
sockets register with the reactor, and its ICE/DTLS/SCTP pumps spawn
on the runtime, that is current while it is built — so a pc created
by a session outlives the only runtime that can drive its I/O, and a
close driven anywhere else completes without reaching the wire.

The bump homes them where they can outlive any caller: WebRTCStream
builds on a process-lifetime runtime and every detached close runs
there as its own never-cancelled task. io_loop keeps its plain
close_webrtc() calls and only documents why nothing here may spawn or
await the teardown on the dying session runtime.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016HV43uh1ztv6Wm5qi3Y1ne

* fix: give the UDP NAT test a real window when the TCP clock is faked

The punch request carries udp_port only if the rendezvous server's
TestNatResponse has arrived, and the wait for it was bounded by
rtt / 2 — half the TCP connect time, on the assumption that TCP and
UDP round trips are comparable and the test, started earlier, has
already answered.

A transparent TCP proxy breaks that assumption: a TUN-mode VPN on the
host, or a redirect-mode proxy on the LAN gateway serving every device
behind it, completes the handshake locally in ~3ms while the real UDP
round trip is hundreds of ms. Log-confirmed against 5.161.65.208: ping
341ms, TCP connect 3.7ms, connect to a dead port there "succeeds" just
as fast. The window collapsed to ~1.5ms, udp_port stayed 0 on every
attempt, and UDP punch was never even requested — although UDP itself
passes such gateways untouched.

So use the TCP clock only when it is believable: below a plausible WAN
round trip it says nothing about the UDP path, and a flat ceiling
applies instead. The loop still exits the moment the port arrives, so
a genuinely nearby server pays nothing and only a UDP-dead network
waits out the ceiling — on the udp-carrying round alone, while the
parallel pure-TCP round is unaffected.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016HV43uh1ztv6Wm5qi3Y1ne

* feat: make the TCP punch a user option, with TCP as the backstop

TCP punching was the one direct transport without a switch, while UDP,
IPv6 and WebRTC each had one. Add "Enable TCP hole punching" above the
UDP toggle on both desktop and mobile, default on — including on
self-hosted servers, since unlike the other three (whose default-off
there guards against an hbbs that cannot forward their fields) TCP
punching has always been supported by every server.

Turning all four off would leave no way to punch at all, so TCP runs
regardless in that case. That backstop keys off the switches alone: a
transport that is enabled but fails to materialize — no public v6
address, no NAT port, a failed offerer — is already covered by the
relay fallback for a round that ends up with no usable direct
transport. With the TCP punch off, the fallback request is skipped
too: it exists only to carry that punch, and would otherwise reach
connect() with nothing to try and merely open a second relay.

Known cost, unchanged behavior for the peer: the request carries no
field for this choice, so a peer that receives one with no udp_port and
no offer still punches a TCP hole and listens for a connection the
controller will not make. Representing the transport choice on the
wire needs a proto field and the server forwarding it.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016HV43uh1ztv6Wm5qi3Y1ne

* bump hbb_common: name the punch by every transport it carries

`get_local_endpoint_trickle` became `local_endpoint() -> &str`, which
cannot fail, so both call sites lose an unreachable error arm — the
mediator's closed a pc against a failure that no longer exists.

`punch_type` named one transport, and picked it off `allow_tcp_punch`.
A round carries several at once — a NAT port and a v6 address and an
offer — and since the TCP punch became a switch it can carry none, so
one name had to misreport both: the logs of the round that broke WebRTC
read "#1 UDP punch attempt" while the request also carried the v6
address and the offer that was actually failing, and a round with
nothing to punch with was labelled "WebRTC". List them instead —
"UDP+IPv6+WebRTC" — and call the empty round "Relay", which is what it
can still end as and what `typ` prints for it.

The offer is moved into the request rather than cloned into it; that
was its last use.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019UzcMTdYTEv2QbMHcTSUy3

* bump hbb_common: drop link-local IPv6 from ICE gathering

Also pin webrtc-util to a fork of 0.11.0 carrying a Windows IPv6 enumeration fix.
`ifaces` reads the adapter list's on-wire IPv6 bytes as host-order `[u16; 8]`, so on a
little-endian host every group comes out byte-swapped and unbindable: a peer's real
240e:369:9606:4600:f52a:7a8d:2530:4de0 is enumerated as e24:6903:696:46:2af5:8d7a:3025:e04d,
::1 as ::100 and fe80:: as 80fe::. Each fails to bind with WSAEADDRNOTAVAIL, so ICE gathers
no IPv6 host candidate at all on Windows - where a globally routable address is the one
NAT-free path a CGNAT'd peer has.

Never reported upstream; the unix twin of the same bug was fixed in webrtc-rs#475 (2023).
Fork: rustdesk-org/webrtc, branch rustdesk-patches, tag webrtc-util-0.11.0-win-ipv6.

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

* bump hbb_common: name the family a WebRTC session runs over

`stream_type` reaches the UI as the transport that won the race, and every other transport
already carries the family in that label - the v6 punch reports `IPv6`. WebRTC does not: one
label covers both families, and it is the one path whose real remote address can differ from
the rendezvous-observed one the session is identified by.

Refine it at the hand-off to the UI rather than at the source: five sites in client.rs
compare `typ == "WebRTC"`, so widening the label there would silently move control flow.

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

* bump hbb_common: one STUN list, and drop the dead IPv4 half

`test_ipv6` kept its own hand-written copy of the STUN servers. It now reads
`WebRTCStream::stun_servers()`, so an operator who points OPTION_ICE_SERVERS at their own
server gets it on both paths instead of one.

`test_bind_ipv6` sends nothing - `connect` only makes the kernel pick a route and a source
address - so the whole cost is DNS. It races the lookups rather than betting this host's
IPv6 support on whether the first entry happens to publish a AAAA where the user resolves
from; google's does not, from a Chinese resolver, and it was the entry being bet on.

`stun_ipv4_test`, `STUNS_V4` and `test_nat_ipv4` have had no callers since the punch stopped
taking its port from a second socket, and go.

`get_kcp_cc_enabled` reads the renamed option through `option2bool`, like every other one.

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

* webrtc: take dcsctp's retransmission timings and IPv6-safe MTU

webrtc-sctp ships RFC 4960's RTO.Initial/RTO.Min (3000/1000), TCP's values for
arbitrary public paths. On this workload they set the recovery time outright:
a request/response exchange keeps one chunk in flight, so no later SACK ever
raises miss_indicator to the 3 that arms fast retransmit, and the T3 floor is
the only way back. A single loss during a handshake or a first keyframe
therefore costs whole seconds.

The fork now carries dcsctp's numbers instead - the SCTP implementation Google
wrote to replace usrsctp for Chrome's WebRTC data channels, the same realtime
workload: rto_initial 500, rto_min 400, a 220ms floor under the RTT variance,
and mtu 1191. INITIAL_MTU 1228 plus DTLS/UDP/IPv6 overhead is 1313, past the
1280 minimum, so every full-size chunk fragmented on an IPv6 path.

Both patch entries move to the new branch, which also carries the Windows IPv6
byte-swap fix, so one rev matches the whole webrtc 0.13 stack.

* udp: make the punch prove itself, and keep the listener answering

punch_udp sent a zero-length datagram and called the hole open on whatever
arrived next. The rendezvous NAT test's own leftover replies satisfy that
immediately - connect() does not flush the receive queue - so the retry loop
never ran and success meant nothing. The dead socket then cost KCP its full
timeout to rediscover, which is how a failed punch came to take 18 seconds.

Probes now carry a magic and a 64-bit transaction id, and both ends answer
each other's probes, so returning is a fact: a reply echoing our own id is the
one thing that proves the pair carries traffic both ways. With failure now
distinguishable from 'not yet', the window drops from 20s to 3s.

Two asymmetries fall out of that:

Only the connector stops on its own acknowledgement, because only it has
something to send next. An acknowledgement proves our probe came back, not
that the peer's probe was answered - and after punch_udp returns nothing
answers probes any more, since KCP's io loop drops anything shorter than its
header. A listener that stopped there would go mute while a peer whose own
probe or answer was lost - the normal state of a hole still opening - kept
probing an endpoint that works, until it timed out.

So the listener stops on the peer's first real packet instead, and hands that
packet to KcpStream::accept as its init_packet: its arrival proves the pair as
well as an acknowledgement would, and KCP never retransmits its SYN.

* webrtc: correct the RTT variance floor to dcsctp's scaling

The earlier commit took dcsctp's min_rtt_variance = 220 as a raw floor under
rttvar. dcsctp divides the option by kHeuristicVarianceAdjustment = 8.0 first,
a historical accident it kept because downstream users had measured good
values with it, so the intended floor is 27.5ms of variance contributing 110ms
to RTO. Flooring at 220 contributed 880ms instead, which on a 50ms path left
RTO within 7% of the 1000ms default this change exists to escape.

The fork also now records why T1/T2 share T3's RTO manager here, unlike
dcsctp's separate control timers: RTO_INITIAL is the T3 value for the first
DATA chunk, since no RTT sample exists before the first SACK.

* webrtc: skip the controller's ICE re-send instead of queueing it twice

The controller sends every candidate twice, because the server's hop to a
peer registered over UDP can lose one. The ICE agent that dedups repeats
sits downstream of the answerer's queue, so the answerer paid for both
copies: a slot, a JSON parse, and the ICE agent's lock, once per repeat.

Remember a digest of what was queued and skip the repeat. Recorded only
once queued, so a candidate a full queue refused stays repairable by the
re-send.

The queue's depth is unchanged. A real peer gathers well under it - four
STUN servers, link-local IPv6 filtered, one component - and the drain
empties it as candidates trickle in, so what this removes is the redundant
work, not an overflow.

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

* tcp: repeat the punch across the controller's dial window

The single punch leaves before hbbs has told the controller where to dial, so
it is never in flight at the same time as the controller's SYN: it opens our
NAT, meets nothing, and a gateway that answers it with RST takes the mapping
down with it, leaving the listener waiting on a hole that no longer exists.

Punch again while the controller may still be dialing, and race those punches
against the accept. That is two ways in where there was one: the mapping is
rebuilt if a RST took it, and once the controller sits in SYN_SENT one of the
punches meets its SYN and completes as a simultaneous open - which a punch sent
before the controller had been told anything never could. The crossing reaches
the punch rather than the listener because the two sockets share the address
but only the punch matches the four-tuple, which the tests now pin down.

There is no instant to aim at, and no window either. `Client::connect` sizes
the controller's dial only after our PunchHoleSent, from its own rendezvous
time and the direct failures it has recorded for us: CONNECT_TIMEOUT between
two known-asymmetric NATs that never failed, punch_time_used times three or
six otherwise, floored at a second - so a peer that failed once dials for a
second or two from then on, and none of that reaches this side. The repeats
therefore cover our own ceiling instead, CONNECT_TIMEOUT, which is exactly as
long as the accept has always been willing to take a connection through the
hole, and back off across it: dense at the start, where every window begins
and the short ones end, sparse afterwards, which is `punch_udp`'s shape for
the same reason. A window past that ceiling was lost before this change too,
and mostly to the controller's own kernel - Windows gives a SYN up at 21s,
Linux's next re-send after 15s is at 31s; a window short of it costs a few
SYNs to a port already closed.

No punch is cut on a per-attempt timeout; one in flight is bounded only by
the shared deadline plus PUNCH_GRACE. A punch is cancel-safe only while it is
still in SYN_SENT; once the controller's SYN has crossed it the socket is half
way through a handshake, and cutting it there cuts the connection the
controller is opening - whose `connect` has already returned, so that attempt
fails outright, there being no relay fallback after a failed TCP handshake. A
timer cannot tell the two states apart, and none is needed: a gateway that
answers with RST fails the connect at once and the loop punches again, while
one that drops the SYN in silence leaves the socket in SYN_SENT, holding the
mapping open while the kernel re-sends, which any SYN of the controller's then
crosses - a second punch has nothing to add. The deadline decides whether
another punch starts; one in flight runs a grace past it, enough for a
crossing begun just before it to complete. The last sleep is cut at the
deadline rather than run out past it, so the window ends on a punch given
that grace and not on a gap of up to the backoff ceiling: the controller's
window opened after ours, on the PunchHoleSent hbbs relayed, so one as long
as ours is still open through our tail.

Only the accept races the punch, never `accept_connection`: that one does not
return until the session it goes on to run has ended, so racing it would tear a
live session down.

Whichever arrives first is the one connection the request produces. `meta`
carries the control permissions hbbs granted for this one controller, so
serving the loser as well would hand them to a second peer - and nothing about
a connection tells the two apart before `create_tcp_connection` has spoken to
it, least of all its address: a carrier NAT shares one between subscribers,
and a NAT that pools its external addresses may dial us from a different one
than hbbs saw the controller through. So the address is not checked, as
`accept_connection` never checked it; the handshake says who arrived, and what
holds the invariant is that there is no second serve. Those
permissions are a ceiling and not a grant either way: `Connection` gates every
message on `authorized`, and latches the login scope of the first request it
accepts, so a peer that reached the hole still arrives with nothing.

The accept loops rather than taking a single connection, so that a transient
accept error does not spend the window the controller still has to arrive in.

libp2p's DCUtR reaches the same place by having both peers dial at one instant
agreed over the relay. Nothing we send reaches the controller directly, so we
cover its dial window rather than name an instant inside it.

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

* hbb_common: bump to the webrtc branch rebased on main

Picks up upstream's session-cache eviction by pc identity (#589, adopted without its
unused insert-path helper), the 90-day log retention, and the wlroots output fixes.

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

* webrtc: send over SCTP without a congestion window, as KCP does

The same link that streams over KCP crawls over WebRTC. webrtc-sctp runs
RFC 4960's AIMD: a fast retransmit halves cwnd, a T3 drops it to one MTU, and
slow start only rebuilds it while data is queued behind it. Where the loss is
random rather than congestion - a lossy long-haul link - the rate settles at
the Mathis ceiling MSS/(RTT*sqrt(p)) however idle the link is: about 1.3 Mbps
at 70ms RTT and 1% loss, 0.6 Mbps at 5%, while 1080p wants 2-5 Mbps. KCP's
turbo profile (nc=1) has no congestion window at all.

The fork now carries a switch that bypasses the two places gating sends on
cwnd, and hbb_common turns it on for every peer connection unless
`allow-webrtc-congestion-control` is set - the same opt-in KCP has in
`allow-kcp-congestion-control`, for the reason at `get_kcp_cc_enabled`.
Sender-side only; a browser or an older build on the other end interoperates.

Measured over a simulated link (35ms one-way, random loss both ways, 12 KB
frames at 30fps, 300 frames): at 1% loss the window stretches 9.9s of video to
20.7s with a mean latency of 5.5s; without it the stream stays realtime at a
mean of 113ms. At 3%: 47s and 15s against 10.2s and 290ms.

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

* webrtc: take the fork's loss recovery for sending without a congestion window

rustdesk-org/webrtc 825a0a48: without a congestion window a chunk is lost
once three chunks sent after its latest transmission are acked, counted in
send order so retransmitted chunks are covered too, and the fast retransmit
sends every lost chunk at once, as KCP nc=1 does; before, a lost
retransmission waited for T3-rtx. Also fixes the delayed SACK timer never
re-arming, the switch applying to established associations, T3-rtx
resending one chunk when the peer's window is full, and bounds new data to
1 MiB / 1024 chunks in flight like KCP's snd_wnd.

Simulated 35ms one-way, random loss both ways, 30 fps, frames later than
200ms out of 1200: 12 KB at 5% loss 996 -> 55 (KCP 61); 40 KB at 2% loss
1183 -> 20 (KCP 39).

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

* bump hbb_common: decode TURN userinfo, add the webrtc_echo example

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

* web: show the WebRTC toggle and transport in the web UI

The web client now speaks WebRTC, but the desktop settings page hides
the punch options on web and the remote page opens without the session
tab that carries the transport name. Let the existing "Enable WebRTC P2P
connection" checkbox through on web (the other punch options stay
native-only), and add a Transport row to the quality monitor for WebRTC
sessions only (with "(TURN)" when ICE relayed), on every platform.

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

* bump hbb_common: end the ICE forwarder at gathering complete, drop the closes Drop covers

hbb_common now closes the local-candidate channel when gathering
completes, so the controlled side's forwarder in spawn_webrtc_answerer
ends there, and its signaling connection to hbbs with it, instead of
sitting on a socket hbbs closed at 90s idle for the rest of the session.
It also keeps the reassembly buffer across fragmented frames.

Stream closes the WebRTC peer connection on drop (hbb_common b0b624d),
so the close_webrtc() calls in port_forward and io_loop that sat
immediately before a return or the end of scope did nothing Drop was
not about to do, while the comments beside them still said a bare drop
leaked the pc. Remove both.

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

* bump hbb_common: quiet the webrtc-rs warnings that describe the race's normal outcome

Cancelling the transport that lost the race, and trickle checking before it
holds a pair, are what the design does on every session that connects - and
webrtc-rs reports both at warn, 90 lines of a 386-line controlled-side log,
beside connections that succeeded. agent_internal and peer_connection drop to
error; agent_gather keeps warn, since an unreachable STUN server is the one
upstream signal that explains a session which never connected.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01M54JAqUK4RynudFou89hod

* port_forward: restore the `?` the close removal left as a match

Dropping the explicit close_webrtc() from the parse-error arm left a match
that only re-spells `?`; master just reworked this function, so the branch
now leaves port_forward.rs untouched.

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

* l10n: the two WebRTC keys were missing from Urdu

Every other lang file on the branch carries them; ur.rs was skipped when
they were added.

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

* udp: make the punch deadline absolute, so a talking peer cannot defer it

`select!` rebuilds every arm each iteration, so the relative retry sleep was
restarted by each datagram that arrived before it fired. The peer sets that
rate, and an old-build peer's empty datagrams match no arm and loop without
even the recv-error pause, so MAX_TIME went unchecked and the retransmit was
starved with it. `udp_nat_connect` awaits the punch ahead of the KCP timeout
and nothing above it bounds the phase, so the punch held the direct race open
and the relay fallback out of reach for as long as the peer kept sending.

Absolute instants for both clocks. The new test floods empty datagrams for
four times the deadline: the punch now ends at 3s where it ran the full 12s.

Also note at the symmetric-NAT branch that WebRTC not following the legacy
relay decision there is deliberate, so it is not later "fixed" into agreement.

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

* bump webrtc fork: MTU-safe bundles, a reordering window, tail loss within the RTT

rustdesk-org/webrtc cc6633bc, three commits on 825a0a48, all on the path
that sends without a congestion window:

Both bundlers counted a DATA chunk by its payload alone; with the header and
padding counted, bundles of small chunks stay within the MTU, and the fragment
payload rounds down to 1160 so a full chunk does too. A chunk is fast
retransmitted at most five times, KCP's IKCP_FASTACK_LIMIT.

A frame's chunks go out within microseconds of each other, so on a path that
jitters the send-order rule resent every chunk that landed behind three of
its siblings: 2.7x the payload on the wire at 10ms of jitter, and on a link
without the room for that, a queue that fed on itself. A reordering window,
RACK's, makes evidence count only from what was sent a quarter of an srtt
after the chunk once the path is seen to reorder, widening on the duplicate
TSNs the receiver reports. 5 Mbps, 1% loss, 20ms jitter: 600 of 600 frames
at a 98ms mean where 290 arrived at 6.2s.

A chunk lost at the tail of a burst has only T3-rtx, which ran from floors
sized for a 200ms delayed ack and restarted only on the tail's predecessor's
ack: 600ms and more. Every DATA chunk now carries the I bit, the floors are
KCP's shape, and a fast retransmission restarts the timer. One 200-byte
message per frame at 5% loss: 9 of 600 later than 200ms, from 42.

Random loss without jitter is unchanged at every rate and frame size.

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

* bump webrtc fork: T3-rtx restarts only for the earliest chunk's fast retransmission

rustdesk-org/webrtc 2b8e55bc. Sending without a congestion window, a fast
retransmission of any chunk restarted T3-rtx, so a chunk past the fast
retransmission cap - left to that timer - never reached it while later
chunks kept being resent, which a lossy stream does every couple of frames.
The timer is the earliest in-flight chunk's, and only its resend restarts
it now. Nothing else changes; the benchmark is unchanged.

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

* bump webrtc fork: T3-rtx restart on fast retransmission while shutting down too

rustdesk-org/webrtc 48100bf1. The restart for the earliest chunk's fast
retransmission reached only the Established branch of the write loop; the
shutdown states still carry data in flight and recover it the same way, so a
closing association could still resend everything on a loss its fast
retransmit had already recovered. Both branches share one helper now.

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

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-09-06 00:21:28 +08:00

2077 lines
69 KiB
Rust

use crate::{
common::{get_supported_keyboard_modes, is_keyboard_mode_supported},
input::{
MOUSE_BUTTON_LEFT, MOUSE_BUTTON_RIGHT, MOUSE_TYPE_DOWN, MOUSE_TYPE_MASK,
MOUSE_TYPE_TRACKPAD, MOUSE_TYPE_UP, MOUSE_TYPE_WHEEL,
},
ui_interface::use_texture_render,
};
use async_trait::async_trait;
use bytes::Bytes;
#[cfg(all(target_os = "windows", not(feature = "flutter")))]
use hbb_common::config::keys;
#[cfg(not(feature = "flutter"))]
use hbb_common::fs;
use hbb_common::{
allow_err,
config::{Config, LocalConfig, PeerConfig},
get_version_number, log,
message_proto::*,
rendezvous_proto::ConnType,
tokio::{
self,
sync::mpsc,
time::{Duration as TokioDuration, Instant},
},
whoami, Stream,
};
use rdev::{Event, EventType::*, KeyCode};
#[cfg(all(feature = "vram", feature = "flutter"))]
use std::ffi::c_void;
use std::{
collections::HashMap,
ops::{Deref, DerefMut},
str::FromStr,
sync::{
atomic::{AtomicUsize, Ordering},
Arc, Mutex, RwLock,
},
time::SystemTime,
};
use uuid::Uuid;
use crate::client::io_loop::Remote;
use crate::client::{
check_if_retry, handle_hash, handle_login_error, handle_login_from_ui, handle_test_delay,
input_os_password, send_mouse, send_pointer_device_event, FileManager, Key, LoginConfigHandler,
QualityStatus, KEY_MAP,
};
#[cfg(not(any(target_os = "android", target_os = "ios")))]
use crate::common::GrabState;
use crate::keyboard;
use crate::{client::Data, client::Interface};
const CHANGE_RESOLUTION_VALID_TIMEOUT_SECS: u64 = 15;
#[derive(Clone, Default)]
pub struct Session<T: InvokeUiSession> {
pub password: String,
pub args: Vec<String>,
pub lc: Arc<RwLock<LoginConfigHandler>>,
pub sender: Arc<RwLock<Option<mpsc::UnboundedSender<Data>>>>,
pub thread: Arc<Mutex<Option<std::thread::JoinHandle<()>>>>,
pub ui_handler: T,
pub server_keyboard_enabled: Arc<RwLock<bool>>,
pub server_file_transfer_enabled: Arc<RwLock<bool>>,
pub server_clipboard_enabled: Arc<RwLock<bool>>,
pub last_change_display: Arc<Mutex<ChangeDisplayRecord>>,
pub connection_round_state: Arc<Mutex<ConnectionRoundState>>,
pub printer_names: Arc<RwLock<HashMap<i32, String>>>,
// Indicate whether the session is reconnected.
// Used to auto start file transfer after reconnection.
pub reconnect_count: Arc<AtomicUsize>,
pub last_audit_note: Arc<Mutex<String>>,
pub audit_guid: Arc<Mutex<String>>,
}
#[derive(Clone)]
pub struct SessionPermissionConfig {
pub lc: Arc<RwLock<LoginConfigHandler>>,
pub server_keyboard_enabled: Arc<RwLock<bool>>,
pub server_file_transfer_enabled: Arc<RwLock<bool>>,
pub server_clipboard_enabled: Arc<RwLock<bool>>,
}
pub struct ChangeDisplayRecord {
time: Instant,
display: i32,
width: i32,
height: i32,
}
enum ConnectionState {
Connecting,
Connected,
Disconnected,
}
/// ConnectionRoundState is used to control the reconnecting logic.
pub struct ConnectionRoundState {
round: u32,
state: ConnectionState,
}
impl ConnectionRoundState {
pub fn new_round(&mut self) -> u32 {
self.round += 1;
self.state = ConnectionState::Connecting;
self.round
}
pub fn set_connected(&mut self) {
self.state = ConnectionState::Connected;
}
pub fn is_round_gt(&self, round: u32) -> bool {
if round == u32::MAX && self.round == 0 {
true
} else {
round < self.round
}
}
pub fn set_disconnected(&mut self, round: u32) -> bool {
if self.is_round_gt(round) {
false
} else {
self.state = ConnectionState::Disconnected;
true
}
}
pub fn is_connected(&self) -> bool {
matches!(self.state, ConnectionState::Connected)
}
}
impl Default for ConnectionRoundState {
fn default() -> Self {
Self {
round: 0,
state: ConnectionState::Connecting,
}
}
}
impl Default for ChangeDisplayRecord {
fn default() -> Self {
Self {
time: Instant::now()
- TokioDuration::from_secs(CHANGE_RESOLUTION_VALID_TIMEOUT_SECS + 1),
display: 0,
width: 0,
height: 0,
}
}
}
impl ChangeDisplayRecord {
fn new(display: i32, width: i32, height: i32) -> Self {
Self {
time: Instant::now(),
display,
width,
height,
}
}
pub fn is_the_same_record(&self, display: i32, width: i32, height: i32) -> bool {
self.time.elapsed().as_secs() < CHANGE_RESOLUTION_VALID_TIMEOUT_SECS
&& self.display == display
&& self.width == width
&& self.height == height
}
}
#[cfg(not(any(target_os = "android", target_os = "ios")))]
impl SessionPermissionConfig {
pub fn is_text_clipboard_required(&self) -> bool {
*self.server_clipboard_enabled.read().unwrap()
&& *self.server_keyboard_enabled.read().unwrap()
&& !self.lc.read().unwrap().disable_clipboard.v
&& !self.lc.read().unwrap().view_only.v
}
#[cfg(feature = "unix-file-copy-paste")]
pub fn is_file_clipboard_required(&self) -> bool {
let lc = self.lc.read().unwrap();
*self.server_keyboard_enabled.read().unwrap()
&& *self.server_file_transfer_enabled.read().unwrap()
&& lc.enable_file_copy_paste.v
&& !lc.view_only.v
}
}
impl<T: InvokeUiSession> Session<T> {
#[cfg(not(any(target_os = "android", target_os = "ios")))]
pub fn get_permission_config(&self) -> SessionPermissionConfig {
SessionPermissionConfig {
lc: self.lc.clone(),
server_keyboard_enabled: self.server_keyboard_enabled.clone(),
server_file_transfer_enabled: self.server_file_transfer_enabled.clone(),
server_clipboard_enabled: self.server_clipboard_enabled.clone(),
}
}
pub fn is_file_transfer(&self) -> bool {
self.lc
.read()
.unwrap()
.conn_type
.eq(&ConnType::FILE_TRANSFER)
}
pub fn is_default(&self) -> bool {
self.lc
.read()
.unwrap()
.conn_type
.eq(&ConnType::DEFAULT_CONN)
}
pub fn is_view_camera(&self) -> bool {
self.lc.read().unwrap().conn_type.eq(&ConnType::VIEW_CAMERA)
}
pub fn is_terminal(&self) -> bool {
self.lc.read().unwrap().conn_type.eq(&ConnType::TERMINAL)
}
pub fn is_port_forward(&self) -> bool {
let conn_type = self.lc.read().unwrap().conn_type;
conn_type == ConnType::PORT_FORWARD || conn_type == ConnType::RDP
}
#[cfg(not(any(target_os = "android", target_os = "ios")))]
pub fn is_rdp(&self) -> bool {
self.lc.read().unwrap().conn_type.eq(&ConnType::RDP)
}
#[cfg(feature = "flutter")]
pub fn is_multi_ui_session(&self) -> bool {
self.ui_handler.is_multi_ui_session()
}
pub fn get_view_style(&self) -> String {
self.lc.read().unwrap().view_style.clone()
}
pub fn get_scroll_style(&self) -> String {
self.lc.read().unwrap().scroll_style.clone()
}
pub fn get_edge_scroll_edge_thickness(&self) -> i32 {
self.lc.read().unwrap().edge_scroll_edge_thickness
}
pub fn get_image_quality(&self) -> String {
self.lc.read().unwrap().image_quality.clone()
}
pub fn get_custom_image_quality(&self) -> Vec<i32> {
self.lc.read().unwrap().custom_image_quality.clone()
}
pub fn get_peer_version(&self) -> i64 {
self.lc.read().unwrap().version.clone()
}
pub fn get_trackpad_speed(&self) -> i32 {
self.lc.read().unwrap().trackpad_speed
}
pub fn fallback_keyboard_mode(&self) -> String {
let peer_version = self.get_peer_version();
let platform = self.peer_platform();
let supported_modes = get_supported_keyboard_modes(peer_version, &platform);
if let Some(mode) = supported_modes.first() {
return mode.to_string();
} else {
if self.get_peer_version() >= get_version_number("1.2.0") {
return KeyboardMode::Map.to_string();
} else {
return KeyboardMode::Legacy.to_string();
}
}
}
// Caution: This function must be called after peer info is received.
pub fn get_keyboard_mode(&self) -> String {
let mode = self.lc.read().unwrap().keyboard_mode.clone();
let keyboard_mode = KeyboardMode::from_str(&mode);
// Note: peer_version is 0 before peer info is received.
let peer_version = self.get_peer_version();
let platform = self.peer_platform();
// Saved keyboard mode still exists in this version.
if let Ok(mode) = keyboard_mode {
if is_keyboard_mode_supported(&mode, peer_version, &platform) {
return mode.to_string();
}
}
self.fallback_keyboard_mode()
}
pub fn is_keyboard_mode_supported(&self, mode: String) -> bool {
if let Ok(mode) = KeyboardMode::from_str(&mode[..]) {
crate::common::is_keyboard_mode_supported(
&mode,
self.get_peer_version(),
&self.peer_platform(),
)
} else {
false
}
}
pub fn save_keyboard_mode(&self, value: String) {
self.lc.write().unwrap().save_keyboard_mode(value);
}
pub fn get_reverse_mouse_wheel(&self) -> String {
self.lc.read().unwrap().reverse_mouse_wheel.clone()
}
pub fn get_displays_as_individual_windows(&self) -> String {
self.lc
.read()
.unwrap()
.displays_as_individual_windows
.clone()
}
pub fn get_use_all_my_displays_for_the_remote_session(&self) -> String {
self.lc
.read()
.unwrap()
.use_all_my_displays_for_the_remote_session
.clone()
}
pub fn save_reverse_mouse_wheel(&self, value: String) {
self.lc.write().unwrap().save_reverse_mouse_wheel(value);
}
pub fn save_displays_as_individual_windows(&self, value: String) {
self.lc
.write()
.unwrap()
.save_displays_as_individual_windows(value);
}
pub fn save_use_all_my_displays_for_the_remote_session(&self, value: String) {
self.lc
.write()
.unwrap()
.save_use_all_my_displays_for_the_remote_session(value);
}
pub fn save_view_style(&self, value: String) {
self.lc.write().unwrap().save_view_style(value);
}
pub fn save_scroll_style(&self, value: String) {
self.lc.write().unwrap().save_scroll_style(value);
}
pub fn save_edge_scroll_edge_thickness(&self, value: i32) {
self.lc
.write()
.unwrap()
.save_edge_scroll_edge_thickness(value);
}
pub fn save_flutter_option(&self, k: String, v: String) {
self.lc.write().unwrap().save_ui_flutter(k, v);
}
pub fn get_flutter_option(&self, k: String) -> String {
self.lc.read().unwrap().get_ui_flutter(&k)
}
pub fn toggle_option(&self, name: String) {
let msg = self.lc.write().unwrap().toggle_option(name.clone());
#[cfg(all(target_os = "windows", not(feature = "flutter")))]
if name == keys::OPTION_ENABLE_FILE_COPY_PASTE {
self.send(Data::ToggleClipboardFile);
}
if let Some(msg) = msg {
self.send(Data::Message(msg));
}
}
pub fn toggle_privacy_mode(&self, impl_key: String, on: bool) {
let mut misc = Misc::new();
misc.set_toggle_privacy_mode(TogglePrivacyMode {
impl_key,
on,
..Default::default()
});
let mut msg_out = Message::new();
msg_out.set_misc(misc);
self.send(Data::Message(msg_out));
}
pub fn get_toggle_option(&self, name: String) -> bool {
self.lc.read().unwrap().get_toggle_option(&name)
}
#[cfg(not(feature = "flutter"))]
pub fn is_privacy_mode_supported(&self) -> bool {
self.lc.read().unwrap().is_privacy_mode_supported()
}
#[cfg(not(target_os = "ios"))]
pub fn is_text_clipboard_required(&self) -> bool {
*self.server_clipboard_enabled.read().unwrap()
&& *self.server_keyboard_enabled.read().unwrap()
&& !self.lc.read().unwrap().disable_clipboard.v
&& !self.lc.read().unwrap().view_only.v
}
#[cfg(any(target_os = "windows", feature = "unix-file-copy-paste"))]
pub fn is_file_clipboard_required(&self) -> bool {
let lc = self.lc.read().unwrap();
*self.server_keyboard_enabled.read().unwrap()
&& *self.server_file_transfer_enabled.read().unwrap()
&& lc.enable_file_copy_paste.v
&& !lc.view_only.v
}
#[cfg(feature = "flutter")]
pub fn refresh_video(&self, display: i32) {
if crate::common::is_support_multi_ui_session_num(self.lc.read().unwrap().version) {
self.send(Data::Message(LoginConfigHandler::refresh_display(
display as _,
)));
} else {
self.send(Data::Message(LoginConfigHandler::refresh()));
}
}
pub fn toggle_virtual_display(&self, index: i32, on: bool) {
let mut misc = Misc::new();
misc.set_toggle_virtual_display(ToggleVirtualDisplay {
display: index,
on,
..Default::default()
});
let mut msg_out = Message::new();
msg_out.set_misc(misc);
self.send(Data::Message(msg_out));
}
#[cfg(not(feature = "flutter"))]
pub fn refresh_video(&self, _display: i32) {
self.send(Data::Message(LoginConfigHandler::refresh()));
}
pub fn record_screen(&self, start: bool) {
self.send(Data::RecordScreen(start));
}
pub fn is_screenshot_supported(&self) -> bool {
crate::common::is_support_screenshot_num(self.lc.read().unwrap().version)
}
pub fn take_screenshot(&self, display: i32, sid: String) {
self.send(Data::TakeScreenshot((display, sid)));
}
pub fn is_recording(&self) -> bool {
self.lc.read().unwrap().record_state
}
pub fn save_custom_image_quality(&self, custom_image_quality: i32) {
let msg = self
.lc
.write()
.unwrap()
.save_custom_image_quality(custom_image_quality);
self.send(Data::Message(msg));
}
pub fn save_image_quality(&self, value: String) {
let msg = self.lc.write().unwrap().save_image_quality(value.clone());
if let Some(msg) = msg {
self.send(Data::Message(msg));
}
if value != "custom" {
let last_auto_fps = self.lc.read().unwrap().last_auto_fps;
if last_auto_fps.unwrap_or(usize::MAX) >= 30 {
// non custom quality use 30 fps
let msg = self.lc.write().unwrap().set_custom_fps(30, false);
self.send(Data::Message(msg));
}
}
}
pub fn save_trackpad_speed(&self, trackpad_speed: i32) {
self.lc.write().unwrap().save_trackpad_speed(trackpad_speed);
}
pub fn set_custom_fps(&self, custom_fps: i32) {
let msg = self.lc.write().unwrap().set_custom_fps(custom_fps, true);
self.send(Data::Message(msg));
}
pub fn get_remember(&self) -> bool {
self.lc.read().unwrap().remember
}
#[cfg(not(feature = "flutter"))]
pub fn set_write_override(
&mut self,
job_id: i32,
file_num: i32,
is_override: bool,
remember: bool,
is_upload: bool,
) -> bool {
self.send(Data::SetConfirmOverrideFile((
job_id,
file_num,
is_override,
remember,
is_upload,
)));
true
}
pub fn alternative_codecs(&self) -> (bool, bool, bool, bool) {
let luid = self.lc.read().unwrap().adapter_luid;
let mark_unsupported = self.lc.read().unwrap().mark_unsupported.clone();
let decoder = scrap::codec::Decoder::supported_decodings(
None,
use_texture_render(),
luid,
&mark_unsupported,
);
let mut vp8 = decoder.ability_vp8 > 0;
let mut av1 = decoder.ability_av1 > 0;
let mut h264 = decoder.ability_h264 > 0;
let mut h265 = decoder.ability_h265 > 0;
let enc = &self.lc.read().unwrap().supported_encoding;
vp8 = vp8 && enc.vp8;
av1 = av1 && enc.av1;
h264 = h264 && enc.h264;
h265 = h265 && enc.h265;
(vp8, av1, h264, h265)
}
pub fn update_supported_decodings(&self) {
let msg = self.lc.write().unwrap().update_supported_decodings();
self.send(Data::Message(msg));
}
pub fn use_texture_render_changed(&self) {
self.send(Data::ResetDecoder(None));
self.update_supported_decodings();
self.send(Data::Message(LoginConfigHandler::refresh()));
}
pub fn restart_remote_device(&self) {
let mut lc = self.lc.write().unwrap();
lc.mark_restarting_remote_device();
let msg = lc.restart_remote_device();
self.send(Data::Message(msg));
}
pub fn get_audit_server(&self, typ: String) -> String {
if LocalConfig::get_option("access_token").is_empty() {
return "".to_owned();
}
crate::get_audit_server(
Config::get_option("api-server"),
Config::get_option("custom-rendezvous-server"),
typ,
)
}
pub fn send_note(&self, note: String) {
let url = self.get_audit_server("conn".to_string());
let id = self.get_id();
let session_id = self.lc.read().unwrap().session_id;
*self.last_audit_note.lock().unwrap() = note.clone();
std::thread::spawn(move || {
send_note(url, id, session_id, note);
});
}
#[cfg(not(feature = "flutter"))]
#[cfg(not(any(target_os = "android", target_os = "ios")))]
pub fn is_xfce(&self) -> bool {
crate::platform::is_xfce()
}
pub fn remove_port_forward(&self, port: i32) {
let mut config = self.load_config();
config.port_forwards = config
.port_forwards
.drain(..)
.filter(|x| x.0 != port)
.collect();
self.save_config(config);
self.send(Data::RemovePortForward(port));
}
pub fn add_port_forward(&self, port: i32, remote_host: String, remote_port: i32) {
let mut config = self.load_config();
if config
.port_forwards
.iter()
.filter(|x| x.0 == port)
.next()
.is_some()
{
return;
}
let pf = (port, remote_host, remote_port);
config.port_forwards.push(pf.clone());
self.save_config(config);
self.send(Data::AddPortForward(pf));
}
pub fn get_option(&self, k: String) -> String {
if k.eq("remote_dir") {
return self.lc.read().unwrap().get_remote_dir();
}
self.lc.read().unwrap().get_option(&k)
}
pub fn set_option(&self, k: String, mut v: String) {
let mut lc = self.lc.write().unwrap();
if k.eq("remote_dir") {
v = lc.get_all_remote_dir(v);
}
lc.set_option(k, v);
}
#[inline]
pub fn load_config(&self) -> PeerConfig {
self.lc.read().unwrap().load_config()
}
#[inline]
pub(super) fn save_config(&self, config: PeerConfig) {
self.lc.write().unwrap().save_config(config);
}
pub fn is_restarting_remote_device(&self) -> bool {
self.lc.read().unwrap().is_restarting_remote_device()
}
#[inline]
pub fn peer_platform(&self) -> String {
self.lc.read().unwrap().info.platform.clone()
}
pub fn get_platform(&self, is_remote: bool) -> String {
if is_remote {
self.peer_platform()
} else {
whoami::platform().to_string()
}
}
pub fn get_path_sep(&self, is_remote: bool) -> &'static str {
let p = self.get_platform(is_remote);
if &p == crate::PLATFORM_WINDOWS {
return "\\";
} else {
return "/";
}
}
pub fn input_os_password(&self, pass: String, activate: bool) {
input_os_password(pass, activate, self.clone());
}
#[cfg(not(feature = "flutter"))]
pub fn get_chatbox(&self) -> String {
#[cfg(feature = "inline")]
return crate::ui::inline::get_chatbox();
#[cfg(not(feature = "inline"))]
return "".to_owned();
}
pub fn swap_modifier_key(&self, msg: &mut KeyEvent) {
let allow_swap_key = self.get_toggle_option("allow_swap_key".to_string());
if allow_swap_key {
if let Some(key_event::Union::ControlKey(ck)) = msg.union {
let ck = ck.enum_value_or_default();
let ck = match ck {
ControlKey::Control => ControlKey::Meta,
ControlKey::Meta => ControlKey::Control,
ControlKey::RControl => ControlKey::Meta,
ControlKey::RWin => ControlKey::Control,
_ => ck,
};
msg.set_control_key(ck);
}
msg.modifiers = msg
.modifiers
.iter()
.map(|ck| {
let ck = ck.enum_value_or_default();
let ck = match ck {
ControlKey::Control => ControlKey::Meta,
ControlKey::Meta => ControlKey::Control,
ControlKey::RControl => ControlKey::Meta,
ControlKey::RWin => ControlKey::Control,
_ => ck,
};
hbb_common::protobuf::EnumOrUnknown::new(ck)
})
.collect();
let code = msg.chr();
if code != 0 {
let mut peer = self.peer_platform().to_lowercase();
peer.retain(|c| !c.is_whitespace());
let key = match peer.as_str() {
"windows" => {
let key = rdev::win_key_from_scancode(code);
let key = match key {
rdev::Key::ControlLeft => rdev::Key::MetaLeft,
rdev::Key::MetaLeft => rdev::Key::ControlLeft,
rdev::Key::ControlRight => rdev::Key::MetaLeft,
rdev::Key::MetaRight => rdev::Key::ControlLeft,
_ => key,
};
rdev::win_scancode_from_key(key).unwrap_or_default()
}
"macos" => {
let key = rdev::macos_key_from_code(code as _);
let key = match key {
rdev::Key::ControlLeft => rdev::Key::MetaLeft,
rdev::Key::MetaLeft => rdev::Key::ControlLeft,
rdev::Key::ControlRight => rdev::Key::MetaLeft,
rdev::Key::MetaRight => rdev::Key::ControlLeft,
_ => key,
};
rdev::macos_keycode_from_key(key).unwrap_or_default() as _
}
_ => {
let key = rdev::linux_key_from_code(code);
let key = match key {
rdev::Key::ControlLeft => rdev::Key::MetaLeft,
rdev::Key::MetaLeft => rdev::Key::ControlLeft,
rdev::Key::ControlRight => rdev::Key::MetaLeft,
rdev::Key::MetaRight => rdev::Key::ControlLeft,
_ => key,
};
rdev::linux_keycode_from_key(key).unwrap_or_default()
}
};
msg.set_chr(key);
}
}
}
pub fn send_key_event(&self, evt: &KeyEvent) {
// mode: legacy(0), map(1), translate(2), auto(3)
let mut msg = evt.clone();
self.swap_modifier_key(&mut msg);
let mut msg_out = Message::new();
msg_out.set_key_event(msg);
self.send(Data::Message(msg_out));
}
pub fn send_chat(&self, text: String) {
let mut misc = Misc::new();
misc.set_chat_message(ChatMessage {
text,
..Default::default()
});
let mut msg_out = Message::new();
msg_out.set_misc(misc);
self.send(Data::Message(msg_out));
}
// Terminal methods
pub fn open_terminal(&self, terminal_id: i32, rows: u32, cols: u32) {
let mut action = TerminalAction::new();
action.set_open(OpenTerminal {
terminal_id,
rows,
cols,
..Default::default()
});
let mut msg_out = Message::new();
msg_out.set_terminal_action(action);
self.send(Data::Message(msg_out));
}
pub fn send_terminal_input(&self, terminal_id: i32, data: String) {
let mut action = TerminalAction::new();
action.set_data(TerminalData {
terminal_id,
data: bytes::Bytes::from(data.into_bytes()),
..Default::default()
});
let mut msg_out = Message::new();
msg_out.set_terminal_action(action);
self.send(Data::Message(msg_out));
}
pub fn resize_terminal(&self, terminal_id: i32, rows: u32, cols: u32) {
let mut action = TerminalAction::new();
action.set_resize(ResizeTerminal {
terminal_id,
rows,
cols,
..Default::default()
});
let mut msg_out = Message::new();
msg_out.set_terminal_action(action);
self.send(Data::Message(msg_out));
}
pub fn close_terminal(&self, terminal_id: i32) {
let mut action = TerminalAction::new();
action.set_close(CloseTerminal {
terminal_id,
..Default::default()
});
let mut msg_out = Message::new();
msg_out.set_terminal_action(action);
self.send(Data::Message(msg_out));
}
pub fn capture_displays(&self, add: Vec<i32>, sub: Vec<i32>, set: Vec<i32>) {
let mut misc = Misc::new();
misc.set_capture_displays(CaptureDisplays {
add,
sub,
set,
..Default::default()
});
let mut msg_out = Message::new();
msg_out.set_misc(misc);
self.send(Data::Message(msg_out));
}
pub fn switch_display(&self, display: i32) {
let (w, h) = match self.lc.read().unwrap().get_custom_resolution(display) {
Some((w, h)) => (w, h),
None => (0, 0),
};
let mut misc = Misc::new();
misc.set_switch_display(SwitchDisplay {
display,
width: w,
height: h,
..Default::default()
});
let mut msg_out = Message::new();
msg_out.set_misc(misc);
self.send(Data::Message(msg_out));
if !use_texture_render() {
self.capture_displays(vec![], vec![], vec![display]);
}
}
#[cfg(not(any(target_os = "android", target_os = "ios")))]
pub fn enter(&self, keyboard_mode: String) {
let session_id = self.lc.read().unwrap().session_id as u128;
keyboard::client::change_grab_status(GrabState::Run, &keyboard_mode, session_id);
}
#[cfg(not(any(target_os = "android", target_os = "ios")))]
pub fn leave(&self, keyboard_mode: String) {
let session_id = self.lc.read().unwrap().session_id as u128;
keyboard::client::change_grab_status(GrabState::Wait, &keyboard_mode, session_id);
}
// flutter only TODO new input
pub fn input_key(
&self,
name: &str,
down: bool,
press: bool,
alt: bool,
ctrl: bool,
shift: bool,
command: bool,
) {
let chars: Vec<char> = name.chars().collect();
if chars.len() == 1 {
let key = Key::_Raw(chars[0] as _);
self._input_key(key, down, press, alt, ctrl, shift, command);
} else {
if let Some(key) = KEY_MAP.get(name) {
self._input_key(key.clone(), down, press, alt, ctrl, shift, command);
}
}
}
pub fn input_string(&self, value: &str) {
let mut key_event = KeyEvent::new();
key_event.set_seq(value.to_owned());
let mut msg_out = Message::new();
msg_out.set_key_event(key_event);
self.send(Data::Message(msg_out));
}
#[cfg(any(target_os = "ios"))]
pub fn handle_flutter_raw_key_event(
&self,
_keyboard_mode: &str,
_name: &str,
_platform_code: i32,
_position_code: i32,
_lock_modes: i32,
_down_or_up: bool,
) {
}
#[cfg(not(any(target_os = "ios")))]
pub fn handle_flutter_raw_key_event(
&self,
keyboard_mode: &str,
name: &str,
platform_code: i32,
position_code: i32,
lock_modes: i32,
down_or_up: bool,
) {
if name == "flutter_key" {
self._handle_key_flutter_simulation(keyboard_mode, platform_code, down_or_up);
} else {
self._handle_raw_key_non_flutter_simulation(
keyboard_mode,
platform_code,
position_code,
lock_modes,
down_or_up,
);
}
}
#[cfg(not(any(target_os = "ios")))]
fn _handle_raw_key_non_flutter_simulation(
&self,
keyboard_mode: &str,
platform_code: i32,
position_code: i32,
lock_modes: i32,
down_or_up: bool,
) {
if position_code < 0 || platform_code < 0 {
return;
}
let platform_code: u32 = platform_code as _;
let position_code: KeyCode = position_code as _;
#[cfg(not(target_os = "windows"))]
let key = rdev::key_from_code(position_code) as rdev::Key;
// Windows requires special handling
#[cfg(target_os = "windows")]
let key = rdev::get_win_key(platform_code, position_code);
let event_type = if down_or_up {
KeyPress(key)
} else {
KeyRelease(key)
};
let event = Event {
time: SystemTime::now(),
unicode: None,
platform_code,
position_code: position_code as _,
event_type,
usb_hid: 0,
#[cfg(any(target_os = "windows", target_os = "macos"))]
extra_data: 0,
};
keyboard::client::process_event_with_session(keyboard_mode, &event, Some(lock_modes), self);
}
pub fn handle_flutter_key_event(
&self,
keyboard_mode: &str,
character: &str,
usb_hid: i32,
lock_modes: i32,
down_or_up: bool,
) {
if character == "flutter_key" {
self._handle_key_flutter_simulation(keyboard_mode, usb_hid, down_or_up);
} else {
self._handle_key_non_flutter_simulation(
keyboard_mode,
character,
usb_hid,
lock_modes,
down_or_up,
);
}
}
fn _handle_key_flutter_simulation(
&self,
_keyboard_mode: &str,
platform_code: i32,
down_or_up: bool,
) {
// https://github.com/flutter/flutter/blob/master/packages/flutter/lib/src/services/keyboard_key.g.dart#L4356
let ctrl_key = match platform_code {
0x007f => Some(ControlKey::VolumeMute),
0x0080 => Some(ControlKey::VolumeUp),
0x0081 => Some(ControlKey::VolumeDown),
0x0066 => Some(ControlKey::Power),
_ => None,
};
let Some(ctrl_key) = ctrl_key else { return };
let mut key_event = KeyEvent {
mode: KeyboardMode::Translate.into(),
down: down_or_up,
..Default::default()
};
key_event.set_control_key(ctrl_key);
self.send_key_event(&key_event);
}
fn _handle_key_non_flutter_simulation(
&self,
keyboard_mode: &str,
character: &str,
usb_hid: i32,
lock_modes: i32,
down_or_up: bool,
) {
let key = rdev::usb_hid_key_from_code(usb_hid as _);
#[cfg(any(target_os = "android", target_os = "ios"))]
let position_code: KeyCode = 0;
#[cfg(any(target_os = "android", target_os = "ios"))]
let platform_code: KeyCode = 0;
#[cfg(target_os = "windows")]
let platform_code: u32 = rdev::win_code_from_key(key).unwrap_or(0);
#[cfg(target_os = "windows")]
let position_code: KeyCode = rdev::win_scancode_from_key(key).unwrap_or(0) as _;
#[cfg(not(any(target_os = "windows", target_os = "android", target_os = "ios")))]
let position_code: KeyCode = rdev::code_from_key(key).unwrap_or(0) as _;
#[cfg(not(any(
target_os = "windows",
target_os = "android",
target_os = "ios",
target_os = "linux"
)))]
let platform_code: u32 = position_code as _;
// For translate mode.
// We need to set the platform code (keysym) if is AltGr.
// https://github.com/rustdesk/rustdesk/blob/07cf1b4db5ef2f925efd3b16b87c33ce03c94809/src/keyboard.rs#L1029
// https://github.com/flutter/flutter/issues/153811
#[cfg(target_os = "linux")]
let platform_code: u32 = position_code as _;
let event_type = if down_or_up {
KeyPress(key)
} else {
KeyRelease(key)
};
let event = Event {
time: SystemTime::now(),
unicode: if character.is_empty() {
None
} else {
Some(rdev::UnicodeInfo {
name: Some(character.to_string()),
unicode: character.encode_utf16().collect(),
// is_dead: is not correct here, because flutter cannot detect deadcode for now.
is_dead: false,
})
},
platform_code,
position_code: position_code as _,
event_type,
#[cfg(any(target_os = "android", target_os = "ios"))]
usb_hid: usb_hid as _,
#[cfg(not(any(target_os = "android", target_os = "ios")))]
usb_hid: 0,
#[cfg(any(target_os = "windows", target_os = "macos"))]
extra_data: 0,
};
keyboard::client::process_event_with_session(keyboard_mode, &event, Some(lock_modes), self);
}
// flutter only TODO new input
fn _input_key(
&self,
key: Key,
down: bool,
press: bool,
alt: bool,
ctrl: bool,
shift: bool,
command: bool,
) {
let v = if press {
3
} else if down {
1
} else {
0
};
let mut key_event = KeyEvent::new();
match key {
Key::Chr(chr) => {
key_event.set_chr(chr);
}
Key::ControlKey(key) => {
key_event.set_control_key(key.clone());
}
Key::_Raw(raw) => {
key_event.set_chr(raw);
}
}
if v == 1 {
key_event.down = true;
} else if v == 3 {
key_event.press = true;
}
keyboard::client::legacy_modifiers(&mut key_event, alt, ctrl, shift, command);
key_event.mode = KeyboardMode::Legacy.into();
self.send_key_event(&key_event);
}
pub fn send_touch_scale(&self, scale: i32, alt: bool, ctrl: bool, shift: bool, command: bool) {
let scale_evt = TouchScaleUpdate {
scale,
..Default::default()
};
let mut touch_evt = TouchEvent::new();
touch_evt.set_scale_update(scale_evt);
let mut evt = PointerDeviceEvent::new();
evt.set_touch_event(touch_evt);
send_pointer_device_event(evt, alt, ctrl, shift, command, self);
}
pub fn send_touch_pan_event(
&self,
event: &str,
x: i32,
y: i32,
alt: bool,
ctrl: bool,
shift: bool,
command: bool,
) {
let mut touch_evt = TouchEvent::new();
match event {
"pan_start" => {
touch_evt.set_pan_start(TouchPanStart {
x,
y,
..Default::default()
});
}
"pan_update" => {
let (x, y) = self.get_scroll_xy((x, y));
touch_evt.set_pan_update(TouchPanUpdate {
x,
y,
..Default::default()
});
}
"pan_end" => {
touch_evt.set_pan_end(TouchPanEnd {
x,
y,
..Default::default()
});
}
_ => {
log::warn!("unknown touch pan event: {}", event);
return;
}
};
let mut evt = PointerDeviceEvent::new();
evt.set_touch_event(touch_evt);
send_pointer_device_event(evt, alt, ctrl, shift, command, self);
}
#[inline]
#[cfg(not(any(target_os = "android", target_os = "ios")))]
fn is_scroll_reverse_mode(&self) -> bool {
self.lc.read().unwrap().reverse_mouse_wheel.eq("Y")
}
#[inline]
fn get_scroll_xy(&self, xy: (i32, i32)) -> (i32, i32) {
#[cfg(not(any(target_os = "android", target_os = "ios")))]
if self.is_scroll_reverse_mode() {
return (-xy.0, -xy.1);
}
xy
}
pub fn send_mouse(
&self,
mut mask: i32,
x: i32,
y: i32,
alt: bool,
ctrl: bool,
shift: bool,
command: bool,
) {
#[allow(unused_mut)]
let mut command = command;
#[cfg(windows)]
{
if !command && crate::platform::windows::get_win_key_state() {
command = true;
}
}
// Compute event type once using MOUSE_TYPE_MASK for reuse
let event_type = mask & MOUSE_TYPE_MASK;
let (x, y) = if event_type == MOUSE_TYPE_WHEEL || event_type == MOUSE_TYPE_TRACKPAD {
self.get_scroll_xy((x, y))
} else {
(x, y)
};
// #[cfg(not(any(target_os = "android", target_os = "ios")))]
let (alt, ctrl, shift, command) =
keyboard::client::get_modifiers_state(alt, ctrl, shift, command);
let is_left = (mask & (MOUSE_BUTTON_LEFT << 3)) > 0;
let is_right = (mask & (MOUSE_BUTTON_RIGHT << 3)) > 0;
if is_left ^ is_right {
let swap_lr = self.get_toggle_option("swap-left-right-mouse".to_string());
if swap_lr {
if is_left {
mask = (mask & (!(MOUSE_BUTTON_LEFT << 3))) | (MOUSE_BUTTON_RIGHT << 3);
} else {
mask = (mask & (!(MOUSE_BUTTON_RIGHT << 3))) | (MOUSE_BUTTON_LEFT << 3);
}
}
}
send_mouse(mask, x, y, alt, ctrl, shift, command, self);
// on macos, ctrl + left button down = right button down, up won't emit, so we need to
// emit up myself if peer is not macos
// to-do: how about ctrl + left from win to macos
if cfg!(target_os = "macos") {
let buttons = mask >> 3;
if buttons == MOUSE_BUTTON_LEFT
&& event_type == MOUSE_TYPE_DOWN
&& ctrl
&& self.peer_platform() != "Mac OS"
{
self.send_mouse(
(MOUSE_BUTTON_LEFT << 3 | MOUSE_TYPE_UP) as _,
x,
y,
alt,
ctrl,
shift,
command,
);
}
}
}
pub fn reconnect(&self, force_relay: bool) {
// 1. If current session is connecting, do not reconnect.
// 2. If the connection is established, send `Data::Close`.
// 3. If the connection is disconnected, do nothing.
let mut connection_round_state_lock = self.connection_round_state.lock().unwrap();
if self.thread.lock().unwrap().is_some() {
match connection_round_state_lock.state {
ConnectionState::Connecting => return,
ConnectionState::Connected => self.send(Data::Close),
ConnectionState::Disconnected => {}
}
}
let round = connection_round_state_lock.new_round();
drop(connection_round_state_lock);
let cloned = self.clone();
// override only if true
if true == force_relay {
let mut lc = self.lc.write().unwrap();
lc.force_relay = true;
// An explicit retry-via-relay is a decision about this peer, not transport
// necessity: Relay-only ICE for this round like any force-always-relay session,
// and it is the one kind of relay that belongs in the peer's saved config.
lc.policy_relay = true;
lc.peer_relay = true;
}
self.lc.write().unwrap().peer_info = None;
self.reconnect_count.fetch_add(1, Ordering::SeqCst);
let mut lock = self.thread.lock().unwrap();
// No need to join the previous thread, because it will exit automatically.
// And the previous thread will not change important states.
*lock = Some(std::thread::spawn(move || {
io_loop(cloned, round);
}));
}
#[cfg(not(feature = "flutter"))]
pub fn get_icon_path(&self, file_type: i32, ext: String) -> String {
let mut path = Config::icon_path();
if file_type == FileType::DirLink as i32 {
let new_path = path.join("dir_link");
if !std::fs::metadata(&new_path).is_ok() {
#[cfg(windows)]
allow_err!(std::os::windows::fs::symlink_file(&path, &new_path));
#[cfg(not(windows))]
allow_err!(std::os::unix::fs::symlink(&path, &new_path));
}
path = new_path;
} else if file_type == FileType::File as i32 {
if !ext.is_empty() {
path = path.join(format!("file.{}", ext));
} else {
path = path.join("file");
}
if !std::fs::metadata(&path).is_ok() {
allow_err!(std::fs::File::create(&path));
}
} else if file_type == FileType::FileLink as i32 {
let new_path = path.join("file_link");
if !std::fs::metadata(&new_path).is_ok() {
path = path.join("file");
if !std::fs::metadata(&path).is_ok() {
allow_err!(std::fs::File::create(&path));
}
#[cfg(windows)]
allow_err!(std::os::windows::fs::symlink_file(&path, &new_path));
#[cfg(not(windows))]
allow_err!(std::os::unix::fs::symlink(&path, &new_path));
}
path = new_path;
} else if file_type == FileType::DirDrive as i32 {
if cfg!(windows) {
path = fs::get_path("C:");
} else if cfg!(target_os = "macos") {
if let Ok(entries) = fs::get_path("/Volumes/").read_dir() {
for entry in entries {
if let Ok(entry) = entry {
path = entry.path();
break;
}
}
}
}
}
fs::get_string(&path)
}
pub fn login(
&self,
os_username: String,
os_password: String,
password: String,
remember: bool,
) {
self.send(Data::Login((os_username, os_password, password, remember)));
}
pub fn send2fa(&self, code: String, trust_this_device: bool) {
let mut msg_out = Message::new();
let hwid = if trust_this_device {
crate::get_hwid()
} else {
Bytes::new()
};
self.lc.write().unwrap().set_option(
"trust-this-device".to_string(),
if trust_this_device { "Y" } else { "" }.to_string(),
);
msg_out.set_auth_2fa(Auth2FA {
code,
hwid,
..Default::default()
});
self.send(Data::Message(msg_out));
}
pub fn get_enable_trusted_devices(&self) -> bool {
self.lc.read().unwrap().enable_trusted_devices
}
pub fn new_rdp(&self) {
self.send(Data::NewRDP);
}
pub fn close(&self) {
self.send(Data::Close);
}
pub fn continue_insecure_connection(&self, continue_insecure: bool) {
let data = if continue_insecure {
Data::ContinueInsecureConnection
} else {
Data::RejectInsecureConnection
};
self.send(data);
}
fn try_auto_start_job_str(is_reconnected: bool, job_str: &str) -> Option<String> {
if is_reconnected {
let job_str = job_str.trim();
if let Some(stripped) = job_str.strip_suffix('}') {
format!(r#"{},"auto_start": true}}"#, stripped).into()
} else {
// unreachable in normal cases
log::warn!(
"The last character is not '}}': {}, auto start is ignored on flutter",
job_str
);
Some(job_str.to_owned())
}
} else {
None
}
}
pub fn load_last_jobs(&self) {
self.clear_all_jobs();
let pc = self.load_config();
if pc.transfer.write_jobs.is_empty() && pc.transfer.read_jobs.is_empty() {
// no last jobs
return;
}
let reconnect_count_thr = if cfg!(feature = "flutter") { 0 } else { 1 };
let is_reconnected = self.reconnect_count.load(Ordering::SeqCst) > reconnect_count_thr;
// TODO: can add a confirm dialog
let mut cnt = 1;
for job_str in pc.transfer.read_jobs.iter() {
if !job_str.is_empty() {
self.load_last_job(
cnt,
Self::try_auto_start_job_str(is_reconnected, job_str)
.as_deref()
.unwrap_or(job_str),
is_reconnected,
);
cnt += 1;
log::info!("restore read_job: {:?}", job_str);
}
}
for job_str in pc.transfer.write_jobs.iter() {
if !job_str.is_empty() {
self.load_last_job(
cnt,
Self::try_auto_start_job_str(is_reconnected, job_str)
.as_deref()
.unwrap_or(job_str),
is_reconnected,
);
cnt += 1;
log::info!("restore write_job: {:?}", job_str);
}
}
self.update_transfer_list();
}
pub fn elevate_direct(&self) {
self.send(Data::ElevateDirect);
}
pub fn elevate_with_logon(&self, username: String, password: String) {
self.send(Data::ElevateWithLogon(username, password));
}
#[cfg(any(target_os = "android", target_os = "ios", not(feature = "flutter")))]
pub fn switch_sides(&self) {}
#[cfg(feature = "flutter")]
#[cfg(not(any(target_os = "android", target_os = "ios")))]
#[tokio::main(flavor = "current_thread")]
pub async fn switch_sides(&self) {
match crate::ipc::connect(1000, "").await {
Ok(mut conn) => {
if conn
.send(&crate::ipc::Data::SwitchSidesRequest(self.get_id()))
.await
.is_ok()
{
if let Ok(Some(data)) = conn.next_timeout(1000).await {
match data {
crate::ipc::Data::SwitchSidesRequest(str_uuid) => {
if let Ok(uuid) = Uuid::from_str(&str_uuid) {
let mut misc = Misc::new();
misc.set_switch_sides_request(SwitchSidesRequest {
uuid: Bytes::from(uuid.as_bytes().to_vec()),
..Default::default()
});
let mut msg_out = Message::new();
msg_out.set_misc(misc);
self.send(Data::Message(msg_out));
}
}
_ => {}
}
}
}
}
Err(err) => {
log::info!("server not started (will try to start): {}", err);
}
}
}
fn set_custom_resolution(&self, display: &SwitchDisplay) {
if display.width == display.original_resolution.width
&& display.height == display.original_resolution.height
{
self.lc
.write()
.unwrap()
.set_custom_resolution(display.display, None);
} else {
let last_change_display = self.last_change_display.lock().unwrap();
if last_change_display.display == display.display {
let wh = if last_change_display.is_the_same_record(
display.display,
display.width,
display.height,
) {
Some((display.width, display.height))
} else {
// display origin is changed, or some other events.
None
};
self.lc
.write()
.unwrap()
.set_custom_resolution(display.display, wh);
}
}
}
#[inline]
pub fn handle_peer_switch_display(&self, display: &SwitchDisplay) {
self.ui_handler.switch_display(display);
self.set_custom_resolution(display);
}
#[inline]
pub fn change_resolution(&self, display: i32, width: i32, height: i32) {
*self.last_change_display.lock().unwrap() =
ChangeDisplayRecord::new(display, width, height);
self.do_change_resolution(display, width, height);
}
#[inline]
fn try_change_init_resolution(&self, display: i32) {
let Some((w, h)) = self.lc.read().unwrap().get_custom_resolution(display) else {
return;
};
self.change_resolution(display, w, h);
}
fn do_change_resolution(&self, display: i32, width: i32, height: i32) {
let mut misc = Misc::new();
let resolution = Resolution {
width,
height,
..Default::default()
};
if crate::common::is_support_multi_ui_session_num(self.lc.read().unwrap().version) {
misc.set_change_display_resolution(DisplayResolution {
display,
resolution: Some(resolution).into(),
..Default::default()
});
} else {
misc.set_change_resolution(resolution);
}
let mut msg = Message::new();
msg.set_misc(misc);
self.send(Data::Message(msg));
}
#[inline]
pub fn request_voice_call(&self) {
#[cfg(target_os = "linux")]
std::thread::spawn(crate::ipc::start_pa);
self.send(Data::NewVoiceCall);
}
#[inline]
pub fn close_voice_call(&self) {
self.send(Data::CloseVoiceCall);
}
pub fn send_selected_session_id(&self, sid: String) {
if let Ok(sid) = sid.parse::<u32>() {
self.lc.write().unwrap().selected_windows_session_id = Some(sid);
let mut misc = Misc::new();
misc.set_selected_sid(sid);
let mut msg = Message::new();
msg.set_misc(misc);
self.send(Data::Message(msg));
let pi = self.lc.read().unwrap().peer_info.clone();
if let Some(pi) = pi {
if pi.windows_sessions.current_sid == sid {
if self.is_file_transfer() {
if pi.username.is_empty() {
self.on_error(
"No active console user logged on, please connect and logon first.",
);
} else {
#[cfg(not(feature = "flutter"))]
{
let remote_dir = self.get_option("remote_dir".to_string());
let show_hidden =
!self.get_option("remote_show_hidden".to_string()).is_empty();
self.read_remote_dir(remote_dir, show_hidden);
}
}
} else if !self.is_terminal() {
self.msgbox(
"success",
"Successful",
"Connected, waiting for image...",
"",
);
}
}
}
} else {
log::error!("selected invalid sid: {}", sid);
}
}
#[inline]
pub fn request_init_msgs(&self, display: usize) {
self.send_message_query(display);
}
fn send_message_query(&self, display: usize) {
let mut misc = Misc::new();
misc.set_message_query(MessageQuery {
switch_display: display as _,
..Default::default()
});
let mut msg = Message::new();
msg.set_misc(misc);
self.send(Data::Message(msg));
}
pub fn get_conn_token(&self) -> Option<String> {
self.lc.read().unwrap().get_conn_token()
}
pub fn printer_response(&self, id: i32, path: String, printer_name: String) {
self.printer_names.write().unwrap().insert(id, printer_name);
let to = std::env::temp_dir().join(format!("rustdesk_printer_{id}"));
self.send(Data::SendFiles((
id,
hbb_common::fs::JobType::Printer,
path,
to.to_string_lossy().to_string(),
0,
false,
true,
)));
}
}
pub trait InvokeUiSession: Send + Sync + Clone + 'static + Sized + Default {
fn set_cursor_data(&self, cd: CursorData);
fn set_cursor_id(&self, id: String);
fn set_cursor_position(&self, cp: CursorPosition);
fn set_display(&self, x: i32, y: i32, w: i32, h: i32, cursor_embedded: bool, scale: f64);
fn switch_display(&self, display: &SwitchDisplay);
fn set_peer_info(&self, peer_info: &PeerInfo); // flutter
fn set_displays(&self, displays: &Vec<DisplayInfo>);
fn set_platform_additions(&self, data: &str);
fn on_connected(&self, conn_type: ConnType);
fn update_privacy_mode(&self);
fn set_permission(&self, name: &str, value: bool);
fn close_success(&self);
fn update_quality_status(&self, qs: QualityStatus);
fn set_connection_type(&self, is_secured: bool, direct: bool, stream_type: &str);
fn set_fingerprint(&self, fingerprint: String);
fn job_error(&self, id: i32, err: String, file_num: i32);
fn job_done(&self, id: i32, file_num: i32);
fn clear_all_jobs(&self);
fn new_message(&self, msg: String);
fn update_transfer_list(&self);
fn load_last_job(&self, cnt: i32, job_json: &str, auto_start: bool);
fn update_folder_files(
&self,
id: i32,
entries: &Vec<FileEntry>,
path: String,
is_local: bool,
only_count: bool,
);
fn confirm_delete_files(&self, id: i32, i: i32, name: String);
fn override_file_confirm(
&self,
id: i32,
file_num: i32,
to: String,
is_upload: bool,
is_identical: bool,
);
fn update_block_input_state(&self, on: bool);
fn job_progress(&self, id: i32, file_num: i32, speed: f64, finished_size: f64);
fn adapt_size(&self);
fn on_rgba(&self, display: usize, rgba: &mut scrap::ImageRgb);
fn msgbox(&self, msgtype: &str, title: &str, text: &str, link: &str, retry: bool);
#[cfg(any(target_os = "android", target_os = "ios"))]
fn clipboard(&self, content: String);
fn cancel_msgbox(&self, tag: &str);
fn switch_back(&self, id: &str);
fn portable_service_running(&self, running: bool);
fn on_voice_call_started(&self);
fn on_voice_call_closed(&self, reason: &str);
fn on_voice_call_waiting(&self);
fn on_voice_call_incoming(&self);
fn get_rgba(&self, display: usize) -> *const u8;
fn next_rgba(&self, display: usize);
#[cfg(all(feature = "vram", feature = "flutter"))]
fn on_texture(&self, display: usize, texture: *mut c_void);
fn set_multiple_windows_session(&self, sessions: Vec<WindowsSession>);
fn set_current_display(&self, disp_idx: i32);
#[cfg(feature = "flutter")]
fn is_multi_ui_session(&self) -> bool;
fn update_record_status(&self, start: bool);
fn update_empty_dirs(&self, _res: ReadEmptyDirsResponse) {}
fn printer_request(&self, id: i32, path: String);
fn handle_screenshot_resp(&self, sid: String, msg: String);
fn handle_terminal_response(&self, response: TerminalResponse);
}
impl<T: InvokeUiSession> Deref for Session<T> {
type Target = T;
fn deref(&self) -> &Self::Target {
&self.ui_handler
}
}
impl<T: InvokeUiSession> DerefMut for Session<T> {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.ui_handler
}
}
impl<T: InvokeUiSession> FileManager for Session<T> {}
#[async_trait]
impl<T: InvokeUiSession> Interface for Session<T> {
fn get_lch(&self) -> Arc<RwLock<LoginConfigHandler>> {
return self.lc.clone();
}
fn send(&self, data: Data) {
if let Some(sender) = self.sender.read().unwrap().as_ref() {
sender.send(data).ok();
}
}
fn msgbox(&self, msgtype: &str, title: &str, text: &str, link: &str) {
let direct = self.lc.read().unwrap().direct;
let received = self.lc.read().unwrap().received;
let retry_for_relay = direct == Some(true) && !received;
let retry = check_if_retry(msgtype, title, text, retry_for_relay);
self.ui_handler.msgbox(msgtype, title, text, link, retry);
}
fn handle_login_error(&self, err: &str) -> bool {
handle_login_error(self.lc.clone(), err, self)
}
fn set_multiple_windows_session(&self, sessions: Vec<WindowsSession>) {
self.ui_handler.set_multiple_windows_session(sessions);
}
fn handle_peer_info(&self, mut pi: PeerInfo) {
log::debug!("handle_peer_info :{:?}", pi);
self.lc.write().unwrap().peer_info = Some(pi.clone());
if pi.current_display as usize >= pi.displays.len() {
pi.current_display = 0;
}
if get_version_number(&pi.version) < get_version_number("1.1.10") {
self.set_permission("restart", false);
}
if self.is_file_transfer() {
if pi.username.is_empty() && pi.windows_sessions.sessions.is_empty() {
self.on_error("No active console user logged on, please connect and logon first.");
return;
}
} else if !self.is_port_forward() && !self.is_terminal() {
if pi.displays.is_empty() {
self.lc.write().unwrap().handle_peer_info(&pi);
self.update_privacy_mode();
let msg = if self.is_view_camera() {
"No cameras"
} else {
"No displays"
};
self.msgbox("error", "Error", msg, "");
return;
}
if !self.is_view_camera() {
self.try_change_init_resolution(pi.current_display);
let p = self.lc.read().unwrap().should_auto_login();
if !p.is_empty() {
input_os_password(p, true, self.clone());
}
}
let current = &pi.displays[pi.current_display as usize];
self.set_display(
current.x,
current.y,
current.width,
current.height,
current.cursor_embedded,
current.scale,
);
}
self.update_privacy_mode();
// Clear audit_guid when connection is established successfully
*self.audit_guid.lock().unwrap() = String::new();
*self.last_audit_note.lock().unwrap() = String::new();
// Save recent peers, then push event to flutter. So flutter can refresh peer page.
self.lc.write().unwrap().handle_peer_info(&pi);
self.set_peer_info(&pi);
if self.is_file_transfer() {
self.close_success();
} else if !self.is_port_forward() && !self.is_terminal() {
self.msgbox(
"success",
"Successful",
"Connected, waiting for image...",
"",
);
}
self.on_connected(self.lc.read().unwrap().conn_type);
#[cfg(windows)]
{
let mut path = std::env::temp_dir();
path.push(self.get_id());
let path = path.with_extension(crate::get_app_name().to_lowercase());
std::fs::File::create(&path).ok();
if let Some(path) = path.to_str() {
crate::platform::windows::add_recent_document(&path);
}
}
if !pi.windows_sessions.sessions.is_empty() {
let selected = self
.lc
.read()
.unwrap()
.selected_windows_session_id
.to_owned();
if selected == Some(pi.windows_sessions.current_sid) {
self.send_selected_session_id(pi.windows_sessions.current_sid.to_string());
} else {
self.set_multiple_windows_session(pi.windows_sessions.sessions.clone());
}
}
}
async fn handle_hash(&self, pass: &str, hash: Hash, peer: &mut Stream) -> bool {
handle_hash(self.lc.clone(), pass, hash, self, peer).await
}
async fn handle_login_from_ui(
&self,
os_username: String,
os_password: String,
password: String,
remember: bool,
peer: &mut Stream,
) {
handle_login_from_ui(
self.lc.clone(),
os_username,
os_password,
password,
remember,
peer,
)
.await;
}
async fn handle_test_delay(&self, t: TestDelay, peer: &mut Stream) {
if !t.from_client {
self.update_quality_status(QualityStatus {
delay: Some(t.last_delay as _),
target_bitrate: Some(t.target_bitrate as _),
..Default::default()
});
handle_test_delay(t, peer).await;
}
}
fn swap_modifier_mouse(&self, msg: &mut hbb_common::protos::message::MouseEvent) {
let allow_swap_key = self.get_toggle_option("allow_swap_key".to_string());
if allow_swap_key {
msg.modifiers = msg
.modifiers
.iter()
.map(|ck| {
let ck = ck.enum_value_or_default();
let ck = match ck {
ControlKey::Control => ControlKey::Meta,
ControlKey::Meta => ControlKey::Control,
ControlKey::RControl => ControlKey::Meta,
ControlKey::RWin => ControlKey::Control,
_ => ck,
};
hbb_common::protobuf::EnumOrUnknown::new(ck)
})
.collect();
};
}
}
impl<T: InvokeUiSession> Session<T> {
pub fn lock_screen(&self) {
self.send_key_event(&crate::keyboard::client::event_lock_screen());
}
pub fn ctrl_alt_del(&self) {
self.send_key_event(&crate::keyboard::client::event_ctrl_alt_del());
}
}
#[tokio::main(flavor = "current_thread")]
pub async fn io_loop<T: InvokeUiSession>(handler: Session<T>, round: u32) {
#[cfg(any(target_os = "android", target_os = "ios"))]
let (sender, receiver) = mpsc::unbounded_channel::<Data>();
#[cfg(not(any(target_os = "android", target_os = "ios")))]
let (sender, mut receiver) = mpsc::unbounded_channel::<Data>();
*handler.sender.write().unwrap() = Some(sender.clone());
let token = LocalConfig::get_option("access_token");
let key = crate::get_key(false).await;
#[cfg(not(any(target_os = "android", target_os = "ios")))]
if handler.is_port_forward() {
handler.lc.write().unwrap().port_forward_mux = crate::port_forward::mux_enabled();
if handler.is_rdp() {
let port = handler
.get_option("rdp_port".to_owned())
.parse::<i32>()
.unwrap_or(3389);
std::env::set_var(
"rdp_username",
handler.get_option("rdp_username".to_owned()),
);
std::env::set_var(
"rdp_password",
handler.get_option("rdp_password".to_owned()),
);
log::info!("Remote rdp port: {}", port);
start_one_port_forward(handler, 0, "".to_owned(), port, receiver, &key, &token).await;
} else if handler.args.len() == 0 {
let pfs = handler.lc.read().unwrap().port_forwards.clone();
let mut queues = HashMap::<i32, mpsc::UnboundedSender<Data>>::new();
for d in pfs {
sender.send(Data::AddPortForward(d)).ok();
}
loop {
match receiver.recv().await {
Some(Data::AddPortForward((port, remote_host, remote_port))) => {
if port <= 0 || remote_port <= 0 {
continue;
}
let (sender, receiver) = mpsc::unbounded_channel::<Data>();
queues.insert(port, sender);
let handler = handler.clone();
let key = key.clone();
let token = token.clone();
tokio::spawn(async move {
start_one_port_forward(
handler,
port,
remote_host,
remote_port,
receiver,
&key,
&token,
)
.await;
});
}
Some(Data::RemovePortForward(port)) => {
if let Some(s) = queues.remove(&port) {
s.send(Data::Close).ok();
}
}
Some(Data::Close) => {
break;
}
Some(d) => {
for (_, s) in queues.iter() {
s.send(d.clone()).ok();
}
}
_ => {}
}
}
} else {
let port = handler.args[0].parse::<i32>().unwrap_or(0);
if handler.args.len() != 3
|| handler.args[2].parse::<i32>().unwrap_or(0) <= 0
|| port <= 0
{
handler.on_error("Invalid arguments, usage:<br><br> rustdesk --port-forward remote-id listen-port remote-host remote-port");
}
let remote_host = handler.args[1].clone();
let remote_port = handler.args[2].parse::<i32>().unwrap_or(0);
start_one_port_forward(
handler,
port,
remote_host,
remote_port,
receiver,
&key,
&token,
)
.await;
}
return;
}
let mut remote = Remote::new(handler, receiver, sender);
remote.io_loop(&key, &token, round).await;
let _ = remote.sync_jobs_status_to_local().await;
}
#[cfg(not(any(target_os = "android", target_os = "ios")))]
async fn start_one_port_forward<T: InvokeUiSession>(
handler: Session<T>,
port: i32,
remote_host: String,
remote_port: i32,
receiver: mpsc::UnboundedReceiver<Data>,
key: &str,
token: &str,
) {
if let Err(err) = crate::port_forward::listen(
handler.get_id(),
handler.password.clone(),
port,
handler.clone(),
receiver,
key,
token,
handler.lc.clone(),
remote_host,
remote_port,
)
.await
{
handler.on_error(&format!("Failed to listen on {}: {}", port, err));
}
log::info!("port forward (:{}) exit", port);
}
#[tokio::main(flavor = "current_thread")]
async fn send_note(url: String, id: String, sid: u64, note: String) {
let body = serde_json::json!({ "id": id, "session_id": sid, "note": note });
allow_err!(crate::post_request(url, body.to_string(), "").await);
}