Compare commits

..

42 Commits

Author SHA1 Message Date
rustdesk
c2927046f8 port forward: a channel id still live when the counter comes round is skipped
The controller handed out `next_id` unchecked. 2^32 opens later it lands
on a channel still up: the entry here was replaced, while the peer,
which ignores an `open` for a live id, kept routing that id to the old
socket, so the new local connection's bytes went into the old target
connection. The id is now taken under the map's lock and advanced past
any id in use.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab
2026-09-05 14:29:52 +08:00
rustdesk
c794bee3c5 port forward: a tunnel's TCP stream refuses packets over twice MAX_FRAME
The codec takes a header declaring up to 1 GiB and hands the packet up
only once it has all arrived, so the channel window bounded what the
peer may send, not what this side buffers. Both sides now cap the codec
at 2 * MAX_FRAME as soon as multiplexing is agreed: a data frame with
its envelope and MAC fits with room to spare, and a header over the cap
ends the tunnel before a byte of payload is read. TCP only; the
WebSocket and WebRTC codecs carry caps of their own.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab
2026-09-05 14:03:41 +08:00
rustdesk
163cdb91b2 Urdu: the two terminal clipboard keys master added
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab
2026-09-05 13:47:42 +08:00
rustdesk
de052b2aaf port forward: the connect guard counts a live tunnel as connected
`connect_port_forward_if_needed` returned early only for a raw-pipe
socket; called again with a tunnel up it would have built a second
`PortForwardMux` and dropped every channel of the first. Not reachable
today, since the logon response is sent once, but the other checks in
this change already read `is_port_forward()`.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab
2026-09-05 13:40:20 +08:00
rustdesk
89b3f88286 port forward: a channel opened as its tunnel closes still gets the teardown
`open` can straddle `close_all`: the claim passed, the frame receiver was
still alive, and the channel subscribed after the signal had gone out.
`watch::subscribe` marks earlier sends as seen, and the entry sits in a
map that was already cleared, so nothing would ever end it. The signal is
now a level: `close_all` raises it with `send_replace`, which stores even
with no channel live, and `run_channel` waits for the value rather than
for a change.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab
2026-09-05 13:40:20 +08:00
rustdesk
7587cf514a port forward: a mapping latched to the raw pipe logs in without asking for the tunnel
The login copied the window's `port_forward_mux` into `multiplex`, so a
mapping that had latched to the raw pipe on an old peer kept asking for
the tunnel. Once that peer was upgraded it answered with a tunnel while
the controller switched to raw framing, and every later connection on
the mapping was dead until it was re-added. The login now carries its
own `port_forward_multiplex`, filled with the target under the turn
lock: the probe asks, the raw pipe does not.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab
2026-09-05 13:40:20 +08:00
rustdesk
1bb4db9484 port forward: closing the tunnel reaches channels parked on their socket
A channel whose far end neither reads nor writes has both relays parked
on the socket, not on the inbound queue, so `close_all` dropping the
queue's sender woke neither: the socket and both tasks lived on until
the far end hung up. Both sides now hold a per-tunnel teardown signal
that `run_channel` selects on beside its own cancel, and `close_all`
sends it after clearing the map.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab
2026-09-05 13:40:20 +08:00
rustdesk
21b4e04e52 Urdu: drop the keys template.rs no longer lists
The twenty keys removed here are absent from template.rs and from every
other language file; ur.rs was the only one still carrying them, eight
of them with no value at all. They are leftovers of features that are
gone: the plugin menu, the OS-account login prompts, the Xorg and
no-desktop errors.

ur.rs now holds exactly the template's key set, all of it translated.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab
2026-09-05 13:40:20 +08:00
rustdesk
c5dd8f1e23 Urdu: fill the backlog of empty and missing translations
ur.rs had fallen behind: 104 keys carried an empty value and 35 keys the
other languages have were absent altogether. Both are filled in, the
missing ones in the order template.rs lists them.

Eight entries stay empty on purpose. They are keys that only ur.rs still
carries, absent from template.rs and from every other language, so their
English source cannot be recovered and nothing reads them:
remember_account_tip, os_account_desk_tip, another_user_login_*_tip,
xorg_not_found_*_tip and no_desktop_*_tip. Twelve more dead keys keep
the values they have; removing either group is a separate decision.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab
2026-09-05 13:38:31 +08:00
rustdesk
2a1b1c8cba port forward: the off switch gets a checkbox in Settings → General
`enable-port-forward-mux` was readable only by editing the config file.
It is a local setting of the controlling side, so it sits with the other
outgoing ones, after "Open connection in new tab", with a tooltip saying
what it does.

The two new keys are translated in every language. The three that the
mobile file manager added, "Export", "Export Logs" and "Import Folder",
were empty everywhere but five languages; they are filled in too, and
Korean's "xdp-portal-unavailable" with them.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab
2026-09-05 13:37:49 +08:00
rustdesk
1a8c47f541 hbb_common: bump to main with rustdesk/hbb_common#595 merged
840c8ec..f94e3fe is that one merge: the five local settings custom
clients could not preset.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab
2026-09-05 13:36:13 +08:00
rustdesk
46a35faf04 port forward: the tunnel's login is the raw pipe's, asked for by a window flag
Master's fix for the shared login slots (#16069) keeps the target and
the challenge in the window's `LoginConfigHandler` and serializes the
mappings' logins with a turn lock, all inside `port_forward.rs`. This
branch had carried a broader shape of the same fix, a `with_port_forward`
on `Interface` and the target and `Hash` as parameters through the login
functions, which every caller had to follow. That is gone: `Interface`,
`Session`, `create_login_msg`, `send_login`, `handle_hash` and
`handle_login_from_ui` are as on master.

What the tunnel needs on top is one bit in the login, `multiplex`. It is
a window flag beside `port_forward` in the handler, set once in `io_loop`
before the window's mappings start, so an accept's claim and its login
read the same value; the setting takes effect for windows opened after
it changes. `connect_and_login_mux` is now master's `connect_and_login`
with the tunnel's three differences and the same `hash_arrived` and
`login_from_ui` calls. The raw pipe is master's, line for line.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab
2026-09-05 13:36:13 +08:00
rustdesk
39a388cf50 port forward: a mapping without its hash waits for it before answering the prompt
The window's password prompt is broadcast to every mapping, and can
reach one whose own connection has not received its `Hash` yet. That
mapping used to answer anyway, with a digest over an empty challenge:
the peer refused it and counted a failed attempt, and the empty-salt
result was written into the shared `lc.password`, where the mapping that
prompted had just stored the right one and the next `handle_peer_info`
would persist whatever was there.

The connection's challenge is now `Option<Hash>`, `None` until
`handle_hash` runs, and `handle_login_from_ui` sends nothing without it.
The mapping that prompted stores the salted password in the shared
handler, and the waiting one logs in with that against its own challenge
when its `Hash` arrives, without prompting again.

Test: A answers its prompt, the same broadcast reaches B before its
hash, B sends nothing, B's hash arrives and its login carries B's
challenge and B's target with no dialog. It runs the real `handle_hash`
for B.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab
2026-09-05 13:36:13 +08:00
rustdesk
eb404d01f9 port forward: a UI login answers the challenge its own connection was given
`handle_login_from_ui` hashed the typed password against `lc.hash`, the
window's shared handler field, and the window's password prompt is
broadcast to every listener. With two mappings both waiting on that
prompt, the `Hash` that arrived last had overwritten the other's, so
one of the two answered the wrong challenge and failed to log in.
Master shares the same state and broadcasts the same way.

The `Hash` is now a parameter of the login; `Session` keeps it beside
the connection it belongs to, and the per-accept clone that
`with_port_forward` makes gets a slot of its own. `lc.hash` stays for
`handle_peer_info`, which only needs the salt, and that is per peer.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab
2026-09-05 13:36:13 +08:00
rustdesk
d52a6647b8 port forward: the raw pipe runs the code it always ran
The multiplexed login had replaced `connect_and_login`, so a mapping
with the setting off, a peer without the feature, or a listener latched
`Legacy` still went through the tunnel's state machine, the capped
pre-read and the changed local-EOF rule. Feature off now means the old
code: `listen()` keeps its accept arm and `connect_and_login` as they
were, and the tunnel is a branch taken only when the setting is on, in
`establish_tunnel` with its own `connect_and_login_mux`. The one line
the raw path does differently is the target riding with the accept's
interface clone instead of the shared handler.

`get_port_forward_mux_enabled` had one caller and moves in here, so
`common.rs` is untouched.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab
2026-09-05 13:36:13 +08:00
rustdesk
8376431a19 port forward: the legacy comment names re-adding the mapping only
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab
2026-09-05 13:36:13 +08:00
rustdesk
054d863a6a port_forward_mux: pin permission revocation and whole-tunnel failure in tests
Both already hold; the review asked for them to be stated. `enable-tunnel`
turned off mid-session refuses the next `open` while the live channel
keeps relaying, and a dead tunnel ends every channel on it together,
after which the next accept establishes again on the same `Tunnel`.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab
2026-09-05 13:36:13 +08:00
rustdesk
0fcba29eb5 port forward: the login's target travels with the accept, not the handler
`listen()` wrote `lc.port_forward` (and, on this branch, `port_forward_mux`)
into the window's shared `LoginConfigHandler` before connecting, and
`create_login_msg` read them back only when the peer's `Hash` arrived.
Two mappings logging in at the same time could therefore swap targets:
on master that bridged a local socket to the wrong target, and with a
tunnel bound to its login's target it also left the mapping refusing
every later accept until it was recreated.

The target is now a `PortForward` carried by the interface clone that
handles one accept, passed explicitly down to `create_login_msg`; the
handler no longer has a field to race on. No lock spans the login.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab
2026-09-05 13:36:13 +08:00
rustdesk
b610b9250c port_forward_mux: a window violation drops the channel on the spot
Both demultiplexers only queued a `Violation` and left the entry until
the channel task woke and exited, so a peer that kept sending past the
window queued one more entry per frame in the meantime, bounded by
nothing. The entry now goes the moment `accept` fails; later frames for
that id are unknown-channel noise.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab
2026-09-05 13:36:13 +08:00
rustdesk
b0f26aabc3 port forward: the legacy comment names the mapping, not the window
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab
2026-09-05 13:36:13 +08:00
rustdesk
c109145c54 port forward: one tunnel per mapping, bound to the authenticated target
The login latches `PortForward.host`/`port` into the session scope and
approval is shown that target, but a window-wide tunnel let any later
`open` name another target with only `enable-tunnel` rechecked. A
tunnel now belongs to one listener and serves the one target its login
authenticated: the controlled side refuses an `open` for any other
target, and a window with several targets uses one connection each,
approved on its own.

With one owner per tunnel the claim needs no waiters: `Establishing`,
`Claim::Wait` and `wait_ready` go, and `try_claim` becomes a plain
read. The CM label that followed a tunnel's targets goes with them; a
row shows its mapping's target, as before.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab
2026-09-05 13:36:13 +08:00
rustdesk
babac46999 port_forward_mux: a tunnel ends when its window drops the Tunnel
The loop held its own handle and state sender, so once the window
closed nothing was left to stop it: it kept answering TestDelay and the
peer connection, CM row included, lived on until the peer went away.
`Tunnel` now owns a watch sender nobody sends on; the loop's receiver
errors when the last `Tunnel` drops, and the loop ends.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab
2026-09-05 13:36:13 +08:00
rustdesk
5693435f7a server: admit only INITIAL_WINDOW on a channel before opened
The demultiplexer accepted CHANNEL_WINDOW into a pending channel's
unbounded queue, four times the bound the channel task enforces once
it polls. The window now starts at INITIAL_WINDOW and is widened right
before `opened` advertises the rest.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab
2026-09-05 13:36:13 +08:00
rustdesk
9c8e5dbb98 hbb_common: bump to main with rustdesk/hbb_common#594 merged
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab
2026-09-05 13:36:13 +08:00
rustdesk
18e07563e2 port forward: a legacy window stays legacy until it is reopened
Review: the merged `Claimed | Legacy` arm gave a legacy window a hot
transition to a tunnel — every accept re-negotiated, and a peer upgraded
while the window stayed open was promoted underneath live connections.
The product does not need a mode switch inside a window's lifetime, and
the transition was extra state-machine surface for nothing: reopening
the window picks up an upgraded peer.

The two arms are separate again. `Claimed` negotiates once and the
peer's answer fixes the window's mode. `Legacy` logs in for every accept
as before, asks for no tunnel — `LoginConfigHandler::port_forward_mux`
carries the request per login, so the raw pipe never has to talk to a
peer that thinks it agreed to multiplex — and ignores what the peer
reports. Both arms keep skipping a local socket that hung up during
login.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab
2026-09-05 13:36:13 +08:00
rustdesk
fee3efcd8f port forward: apply the whole-branch review
Correctness:
- listen(): the Legacy arm is merged with the Claimed arm. On its own it
  ignored outcome.local_eof, so a client that hung up during login still
  got a target connect, an audit record and a CM row on the controlled
  side, and ignored outcome.mux, so a peer upgraded while a legacy window
  stayed open answered as a tunnel while the controller went raw.
- Refusal dialogs are deduplicated per quiet spell (10 s) rather than per
  tunnel lifetime; the lifetime set went silent for the rest of a
  long-lived window after the first burst.
- Android's CM listener handles UpdatePortForward; it fell into `_ => {}`.
- relay_socket_to_tunnel reads into one scratch buffer per channel and
  sends an exact-size copy. A frame owning its 64 KiB read allocation
  pinned it until sent, once per byte on interactive traffic.

Consistency and cleanups:
- The controlled side's refusal text is the raw pipe's wording, RDP
  substitution included.
- connection.rs: the PortForwardChannel arm is a one-line hook, the CM
  label is pushed from the 1 s tick alone, and the unreachable inner.tx
  fall-through is gone.
- The Ready enum is removed; wait_ready() returns Option<Claim>.
- SendCredit::add wakes with notify_one alone.
- on_ui_command() replaces the two ui_receiver handlers in listen().
- TunnelHandle is no longer re-exported (unused-import warning).

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab
2026-09-05 13:36:13 +08:00
rustdesk
de46cac9a7 Use on_error for refused-channel dialog in tunnel_loop
Redirect the refused-channel error through the standard on_error path
instead of calling msgbox directly, for consistency with other errors
in the port-forward flow.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab
2026-09-05 13:36:13 +08:00
rustdesk
7b901de8ff port_forward_mux: report a refused channel's reason as an error dialog
The controlled side already answers a refused port-forward channel with
opened { success: false, message }; on the multiplexed path TunnelHandle::
on_frame only logged that message at debug and closed the channel, so the
user saw a closed connection with no explanation, worst on the RDP path
where only the RDP client's own error remained. on_frame now returns the
message the window should show, deduplicated per distinct reason (capped
at MAX_REPORTED_OPEN_ERRORS) so one page load's dozen refused connections
surface one dialog per reason instead of a dozen.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab
2026-09-05 13:36:13 +08:00
rustdesk
52baf741fb port_forward_mux: cap send credit and other final review fixes
Fix 1 (critical): clamp SendCredit to MAX_SEND_CREDIT (= CHANNEL_WINDOW)
in both new() and add(), so a peer with tunnel permission can no longer
advertise an unbounded window and force the controlled side's unbounded
FrameSink::Direct sink to buffer unlimited target data per channel.

Fix 2: rename the "starve" test to many_channels_echo_concurrently and
drop its (untrue) starvation claim, since it opens every channel before
the bulk transfer starts. Add a_channel_opened_during_a_bulk_transfer_
is_served_promptly, which opens the small channel while the bulk one is
demonstrably mid-flight.

Fix 3: only look up the tunnel permission for `open` frames in the
PortForwardChannel arm of on_message, instead of once per data frame.

Fix 4: two rustfmt deviations in connection.rs (matches! wrapping and a
tuple literal), fixed by hand without a blanket cargo fmt run.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab
2026-09-05 13:36:13 +08:00
rustdesk
66d66bf1a6 port_forward_mux: fix bulk test's premature half-close, pin the half-close limitation
many_channels_echo_concurrently_and_a_bulk_one_does_not_starve_them dropped
its bulk write half as soon as writing finished, which shuts down the write
side of the socket and, by design (see the design doc's TCP half-close
non-goal; today's run_forward does the same), ends the whole channel. Keep
the write half alive until the reader is done so the test measures
starvation, not half-close. Add a_local_half_close_ends_the_whole_channel to
pin that limitation in code.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab
2026-09-05 13:36:13 +08:00
rustdesk
85805c41b1 port_forward_mux: end-to-end tests over a loopback tunnel
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab
2026-09-05 13:36:13 +08:00
rustdesk
216b1d99e6 port forward: fix round 1 review findings
Drop the mux default-false assignment now that definite-assignment proves
every path that reads it has set it; the enable-port-forward-mux config
commit picks up the missing attribution trailers; the default-on test
pins the enable- prefix itself rather than option2bool's weaker fallback.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab
2026-09-05 13:36:13 +08:00
rustdesk
85b1986df4 port forward: share one multiplexed tunnel across a window's listeners
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab
2026-09-05 13:36:13 +08:00
rustdesk
0978786c7e port_forward_mux: publish Muxed before spawning the tunnel loop
Publishing after spawn let a loop that dies immediately reset the state
first, so the later publish pinned it at Muxed with a dead handle
forever. Also adds a test pinning open-before-data ordering across many
concurrently opened channels, and drops an unused Clone derive.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab
2026-09-05 13:36:13 +08:00
rustdesk
0bf7b0cd26 port_forward_mux: controller tunnel with a single-writer stream loop
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab
2026-09-05 13:36:13 +08:00
rustdesk
83933e0242 cm: update a port-forward row's targets as tunnel channels come and go
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab
2026-09-05 13:36:13 +08:00
rustdesk
4b708edba6 server: multiplexed port-forward connections stay in the protobuf loop
Wire PortForwardMux into Connection: take the multiplexed path at login
when the controller sets PortForward.multiplex, route
PortForwardChannel frames to it from on_message, sweep the channel
table's targets after open/close, and clean it up on connection close.

Introduce is_port_forward() (socket-based or multiplexed) and use it
at the four sites that classify the connection, so a multiplexed
connection stays in the message loop, gets TestDelay keepalives, and
reports features.port_forward_mux in PeerInfo. The three sites that
break into the raw pipe loop or gate the keepalive still check
port_forward_socket specifically, since a multiplexed connection must
not take that path.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab
2026-09-05 13:36:13 +08:00
rustdesk
cc9343e3d3 server: PortForwardMux channel table and per-channel tasks
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab
2026-09-05 13:36:13 +08:00
rustdesk
8101bd2303 port_forward_mux: credit-windowed relay halves and channel coordinator
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab
2026-09-05 13:36:13 +08:00
rustdesk
247acc1c97 port_forward_mux: fix RecvWindow counter overflow on long transfers
Replace cumulative accounting (granted/received) with remaining credit
tracking to prevent u32 overflow after 4 GiB of data on a single channel.
Wire behavior is identical, but the fix allows large file transfers
without mid-stream channel closure.

Add regression test for 8 GiB transfer to verify fix.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab
2026-09-05 13:36:12 +08:00
rustdesk
798c8b22ae port_forward_mux: window accounting and channel frame builders
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab
2026-09-05 13:36:12 +08:00
rustdesk
350ad893f8 hbb_common: bump to the port-forward-mux proto
Also latches PortForward.multiplex into login_scope_digest, which
destructures PortForward's fields exhaustively by design (a new field
must be latched or deliberately ignored to compile).

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab
2026-09-05 13:36:12 +08:00
71 changed files with 539 additions and 3109 deletions

300
Cargo.lock generated
View File

@@ -753,6 +753,24 @@ dependencies = [
"syn 2.0.98",
]
[[package]]
name = "bindgen"
version = "0.71.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5f58bf3d7db68cfbac37cfc485a8d711e87e064c3d0fe0435b92f7a407f9d6b3"
dependencies = [
"bitflags 2.9.1",
"cexpr",
"clang-sys",
"itertools 0.12.1",
"proc-macro2 1.0.93",
"quote 1.0.36",
"regex",
"rustc-hash 2.1.1",
"shlex",
"syn 2.0.98",
]
[[package]]
name = "bindgen"
version = "0.72.1"
@@ -1143,6 +1161,30 @@ version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "613afe47fcd5fac7ccf1db93babcb082c5994d996f20b8b159f2ad1658eb5724"
[[package]]
name = "chacha20"
version = "0.9.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c3613f74bd2eac03dad61bd53dbe620703d4371614fe0bc3b9f04dd36fe4e818"
dependencies = [
"cfg-if 1.0.0",
"cipher",
"cpufeatures",
]
[[package]]
name = "chacha20poly1305"
version = "0.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "10cd79432192d1c0f4e1a0fef9527696cc039165d729fb41b3f4f4f354c2dc35"
dependencies = [
"aead",
"chacha20",
"cipher",
"poly1305",
"zeroize",
]
[[package]]
name = "chrono"
version = "0.4.41"
@@ -1192,6 +1234,7 @@ checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad"
dependencies = [
"crypto-common",
"inout",
"zeroize",
]
[[package]]
@@ -2281,7 +2324,7 @@ version = "0.5.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "330c60081dcc4c72131f8eb70510f1ac07223e5d4163db481a04a0befcffa412"
dependencies = [
"libloading 0.7.4",
"libloading 0.8.4",
]
[[package]]
@@ -2399,6 +2442,42 @@ dependencies = [
"linux-raw-sys 0.6.5",
]
[[package]]
name = "dtls"
version = "0.13.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f531dd7c181beaf3cebab3716afa4d0d41ab888be85232583f56bbaf07ca208a"
dependencies = [
"aes",
"aes-gcm",
"async-trait",
"bincode",
"byteorder",
"cbc",
"ccm",
"chacha20poly1305",
"der-parser",
"hmac",
"log",
"p256",
"p384",
"portable-atomic",
"rand 0.9.2",
"rand_core 0.6.4",
"rcgen",
"ring",
"rustls",
"sec1",
"serde 1.0.228",
"sha1",
"sha2",
"thiserror 1.0.61",
"tokio",
"webrtc-util",
"x25519-dalek",
"x509-parser",
]
[[package]]
name = "dtoa"
version = "0.4.8"
@@ -2784,7 +2863,7 @@ dependencies = [
"is-terminal",
"lazy_static",
"log",
"nu-ansi-term",
"nu-ansi-term 0.49.0",
"regex",
"thiserror 1.0.61",
]
@@ -3687,7 +3766,6 @@ dependencies = [
"mac_address",
"machine-uid",
"osascript",
"percent-encoding",
"protobuf",
"protobuf-codegen",
"rand 0.8.5",
@@ -4099,15 +4177,16 @@ dependencies = [
[[package]]
name = "interceptor"
version = "0.14.0"
version = "0.15.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1ac0781c825d602095113772e389ef0607afcb869ae0e68a590d8e0799cdcef8"
checksum = "ea51375727680dc15f06e8ad90fa31df75d79dd030100e8ad60eef1c27fe2c98"
dependencies = [
"async-trait",
"bytes",
"futures",
"log",
"portable-atomic",
"rand 0.8.5",
"rand 0.9.2",
"rtcp",
"rtp",
"thiserror 1.0.61",
@@ -4259,11 +4338,11 @@ dependencies = [
[[package]]
name = "kcp-sys"
version = "0.1.0"
source = "git+https://github.com/rustdesk-org/kcp-sys?branch=rustdesk-patches#023a0065398968989f2ddfcf5cc72bb886d02675"
source = "git+https://github.com/rustdesk-org/kcp-sys#32a6c09fc6223f54aea83981a6aa8995931d29be"
dependencies = [
"anyhow",
"auto_impl",
"bindgen 0.72.1",
"bindgen 0.71.1",
"bitflags 2.9.1",
"bytes",
"cc",
@@ -4274,6 +4353,8 @@ dependencies = [
"thiserror 2.0.17",
"tokio",
"tokio-util",
"tracing",
"tracing-subscriber",
"zerocopy 0.7.34",
]
@@ -4407,7 +4488,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e310b3a6b5907f99202fcdb4960ff45b93735d7c7d96b760fcff8db2dc0e103d"
dependencies = [
"cfg-if 1.0.0",
"windows-targets 0.48.5",
"windows-targets 0.52.6",
]
[[package]]
@@ -5129,6 +5210,16 @@ dependencies = [
"winapi 0.3.9",
]
[[package]]
name = "nu-ansi-term"
version = "0.46.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "77a8165726e8236064dbb45459242600304b42a5ea24ee2948e18e023bf7ba84"
dependencies = [
"overload",
"winapi 0.3.9",
]
[[package]]
name = "nu-ansi-term"
version = "0.49.0"
@@ -5792,6 +5883,12 @@ dependencies = [
"serde_json 1.0.118",
]
[[package]]
name = "overload"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b15813163c1d831bf4a13c3610c05c0d03b39feb07f7e09fa234dac9b15aaf39"
[[package]]
name = "owned_ttf_parser"
version = "0.25.1"
@@ -6180,6 +6277,17 @@ dependencies = [
"windows-sys 0.52.0",
]
[[package]]
name = "poly1305"
version = "0.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8159bd90725d2df49889a078b54f4f79e87f1f8a8444194cdca81d38f5393abf"
dependencies = [
"cpufeatures",
"opaque-debug",
"universal-hash",
]
[[package]]
name = "polyval"
version = "0.6.2"
@@ -6986,9 +7094,9 @@ dependencies = [
[[package]]
name = "rtcp"
version = "0.13.0"
version = "0.14.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e9689528bf3a9eb311fd938d05516dd546412f9ce4fffc8acfc1db27cc3dbf72"
checksum = "81d30d1c4091644431c22acf9f8be6191b56805e0e977f15ca7104b4a6d6eaec"
dependencies = [
"bytes",
"thiserror 1.0.61",
@@ -6997,14 +7105,14 @@ dependencies = [
[[package]]
name = "rtp"
version = "0.13.0"
version = "0.14.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c54733451a67d76caf9caa07a7a2cec6871ea9dda92a7847f98063d459200f4b"
checksum = "2f126f38ea84c02480e32e547c1459a939052f74fb92117ac3eef23fdac6b023"
dependencies = [
"bytes",
"memchr",
"portable-atomic",
"rand 0.8.5",
"rand 0.9.2",
"serde 1.0.228",
"thiserror 1.0.61",
"webrtc-util",
@@ -7159,7 +7267,6 @@ dependencies = [
"terminfo",
"termios 0.3.3",
"tiny-skia",
"tokio",
"totp-rs",
"tray-icon",
"ttf-parser",
@@ -7440,11 +7547,11 @@ dependencies = [
[[package]]
name = "sdp"
version = "0.8.0"
version = "0.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4cd277015eada44a0bb810a4b84d3bf6e810573fa62fb442f457edf6a1087a69"
checksum = "32c374dceda16965d541c8800ce9cc4e1c14acfd661ddf7952feeedc3411e5c6"
dependencies = [
"rand 0.8.5",
"rand 0.9.2",
"substring",
"thiserror 1.0.61",
"url",
@@ -7674,6 +7781,15 @@ dependencies = [
"tzdb 0.5.10",
]
[[package]]
name = "sharded-slab"
version = "0.1.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f40ca3c46823713e0d4209592e8d6e826aa57e928f09752619fc696c499637f6"
dependencies = [
"lazy_static",
]
[[package]]
name = "shared_library"
version = "0.1.9"
@@ -8013,15 +8129,15 @@ dependencies = [
[[package]]
name = "stun"
version = "0.8.0"
version = "0.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7dbc2bab375524093c143dc362a03fb6a1fb79e938391cdb21665688f88a088a"
checksum = "1a512c5d501e3e3b5a4bb3e8e31462d56d54a66b95a28b8596e14422bf21c32b"
dependencies = [
"base64 0.22.1",
"crc",
"lazy_static",
"md-5",
"rand 0.8.5",
"rand 0.9.2",
"ring",
"subtle",
"thiserror 1.0.61",
@@ -8403,6 +8519,16 @@ dependencies = [
"syn 2.0.98",
]
[[package]]
name = "thread_local"
version = "1.1.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8b9ef9bad013ada3808854ceac7b46812a6465ba368859a37e2100283d2d719c"
dependencies = [
"cfg-if 1.0.0",
"once_cell",
]
[[package]]
name = "threadpool"
version = "1.8.1"
@@ -8782,6 +8908,32 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b9d12581f227e93f094d3af2ae690a574abb8a2b9b7a96e7cfe9647b2b617678"
dependencies = [
"once_cell",
"valuable",
]
[[package]]
name = "tracing-log"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ee855f1f400bd0e5c02d150ae5de3840039a3f54b025156404e34c23c03f47c3"
dependencies = [
"log",
"once_cell",
"tracing-core",
]
[[package]]
name = "tracing-subscriber"
version = "0.3.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e8189decb5ac0fa7bc8b96b7cb9b2701d60d48805aca84a238004d665fcc4008"
dependencies = [
"nu-ansi-term 0.46.0",
"sharded-slab",
"smallvec",
"thread_local",
"tracing-core",
"tracing-log",
]
[[package]]
@@ -8896,9 +9048,9 @@ dependencies = [
[[package]]
name = "turn"
version = "0.10.0"
version = "0.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3f5aea1116456e1da71c45586b87c72e3b43164fbf435eb93ff6aa475416a9a4"
checksum = "5ed995882f66ab94238de77c62e5e778389698ab700afa4696f4754da8f457cb"
dependencies = [
"async-trait",
"base64 0.22.1",
@@ -8906,7 +9058,7 @@ dependencies = [
"log",
"md-5",
"portable-atomic",
"rand 0.8.5",
"rand 0.9.2",
"ring",
"stun",
"thiserror 1.0.61",
@@ -9032,6 +9184,12 @@ dependencies = [
"unic-common",
]
[[package]]
name = "unicase"
version = "2.8.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "75b844d17643ee918803943289730bec8aac480150456169e647ed0b576ba539"
[[package]]
name = "unicode-bidi"
version = "0.3.15"
@@ -9177,6 +9335,12 @@ dependencies = [
"bindgen 0.65.1",
]
[[package]]
name = "valuable"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65"
[[package]]
name = "vcpkg"
version = "0.2.15"
@@ -9560,26 +9724,25 @@ dependencies = [
[[package]]
name = "webrtc"
version = "0.13.0"
version = "0.14.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "24bab7195998d605c862772f90a452ba655b90a2f463c850ac032038890e367a"
checksum = "08fd686c0920ac08f3a57eacc48e31f0e4ca1ffefba4478784606f78c14e83ad"
dependencies = [
"arc-swap",
"async-trait",
"bytes",
"cfg-if 1.0.0",
"dtls",
"hex",
"interceptor",
"lazy_static",
"log",
"portable-atomic",
"rand 0.8.5",
"rand 0.9.2",
"rcgen",
"regex",
"ring",
"rtcp",
"rtp",
"rustls",
"sdp",
"serde 1.0.228",
"serde_json 1.0.118",
@@ -9587,13 +9750,12 @@ dependencies = [
"smol_str",
"stun",
"thiserror 1.0.61",
"time 0.3.36",
"tokio",
"turn",
"unicase",
"url",
"waitgroup",
"webrtc-data",
"webrtc-dtls",
"webrtc-ice",
"webrtc-mdns",
"webrtc-media",
@@ -9604,9 +9766,9 @@ dependencies = [
[[package]]
name = "webrtc-data"
version = "0.11.0"
version = "0.12.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4e97b932854da633a767eff0cc805425a2222fc6481e96f463e57b015d949d1d"
checksum = "062a5438d63bb0756a221693d76cc0dd6119affee1dfdfe57abe3a2a8c8b3eea"
dependencies = [
"bytes",
"log",
@@ -9617,55 +9779,18 @@ dependencies = [
"webrtc-util",
]
[[package]]
name = "webrtc-dtls"
version = "0.12.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5ccbe4d9049390ab52695c3646c1395c877e16c15fb05d3bda8eee0c7351711c"
dependencies = [
"aes",
"aes-gcm",
"async-trait",
"bincode",
"byteorder",
"cbc",
"ccm",
"der-parser",
"hkdf",
"hmac",
"log",
"p256",
"p384",
"portable-atomic",
"rand 0.8.5",
"rand_core 0.6.4",
"rcgen",
"ring",
"rustls",
"sec1",
"serde 1.0.228",
"sha1",
"sha2",
"subtle",
"thiserror 1.0.61",
"tokio",
"webrtc-util",
"x25519-dalek",
"x509-parser",
]
[[package]]
name = "webrtc-ice"
version = "0.13.0"
version = "0.14.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "eb51bde0d790f109a15bfe4d04f1b56fb51d567da231643cb3f21bb74d678997"
checksum = "69cb13fd1a373e68addc4bba0c8ca058627518e54342583d024bdcbb8ae5d97d"
dependencies = [
"arc-swap",
"async-trait",
"crc",
"log",
"portable-atomic",
"rand 0.8.5",
"rand 0.9.2",
"serde 1.0.228",
"serde_json 1.0.118",
"stun",
@@ -9681,9 +9806,9 @@ dependencies = [
[[package]]
name = "webrtc-mdns"
version = "0.9.0"
version = "0.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "979cc85259c53b7b620803509d10d35e2546fa505d228850cbe3f08765ea6ea8"
checksum = "a17279a067e75df72ce923fdeb7f04cd808f6f5aa4910dc6bcb4fbe66b396ace"
dependencies = [
"log",
"socket2 0.5.10",
@@ -9694,21 +9819,22 @@ dependencies = [
[[package]]
name = "webrtc-media"
version = "0.10.0"
version = "0.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "80041211deccda758a3e19aa93d6b10bc1d37c9183b519054b40a83691d13810"
checksum = "94a84c910fec0848fd5a0d8a5651e0ddbdedaf25a7d3ae3f0b15f71ac73a1773"
dependencies = [
"byteorder",
"bytes",
"rand 0.8.5",
"rand 0.9.2",
"rtp",
"thiserror 1.0.61",
]
[[package]]
name = "webrtc-sctp"
version = "0.12.0"
source = "git+https://github.com/rustdesk-org/webrtc?rev=48100bf13e694d7e5bbb49b9a753dbad1c359d0c#48100bf13e694d7e5bbb49b9a753dbad1c359d0c"
version = "0.13.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f985465467d8910c1f8ac4382cd64f83b1f6a1a75021a82b221546f6fb3b856f"
dependencies = [
"arc-swap",
"async-trait",
@@ -9716,7 +9842,7 @@ dependencies = [
"crc",
"log",
"portable-atomic",
"rand 0.8.5",
"rand 0.9.2",
"thiserror 1.0.61",
"tokio",
"webrtc-util",
@@ -9724,9 +9850,9 @@ dependencies = [
[[package]]
name = "webrtc-srtp"
version = "0.15.0"
version = "0.16.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "01e773f79b09b057ffbda6b03fe7b43403b012a240cf8d05d630674c3723b5bb"
checksum = "66d8cdc33413f1d0192670a80ce93d17cb78d57fe3a2414be30d6f6dff121123"
dependencies = [
"aead",
"aes",
@@ -9747,19 +9873,19 @@ dependencies = [
[[package]]
name = "webrtc-util"
version = "0.11.0"
source = "git+https://github.com/rustdesk-org/webrtc?rev=48100bf13e694d7e5bbb49b9a753dbad1c359d0c#48100bf13e694d7e5bbb49b9a753dbad1c359d0c"
version = "0.12.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d1c0c7e0c8f280f2bbfae442701465777ac07adaf46ce0c5863cd58e13fe472a"
dependencies = [
"async-trait",
"bitflags 1.3.2",
"bytes",
"ipnet",
"lazy_static",
"libc",
"log",
"nix 0.26.4",
"portable-atomic",
"rand 0.8.5",
"rand 0.9.2",
"thiserror 1.0.61",
"tokio",
"winapi 0.3.9",

View File

@@ -52,7 +52,7 @@ screencapturekit = ["cpal/screencapturekit"]
[dependencies]
async-trait = "0.1"
scrap = { path = "libs/scrap", features = ["wayland"] }
hbb_common = { path = "libs/hbb_common", features = ["webrtc"] }
hbb_common = { path = "libs/hbb_common" }
serde_derive = "1.0"
serde = "1.0"
serde_json = "1.0"
@@ -83,7 +83,7 @@ fon = "0.6"
shutdown_hooks = "0.1"
totp-rs = { version = "5.4", default-features = false, features = ["gen_secret", "otpauth"] }
stunclient = "0.4"
kcp-sys= { git = "https://github.com/rustdesk-org/kcp-sys", branch = "rustdesk-patches" }
kcp-sys= { git = "https://github.com/rustdesk-org/kcp-sys"}
reqwest = { version = "0.12", features = ["blocking", "socks", "json", "native-tls", "rustls-tls", "rustls-tls-native-roots", "gzip", "zstd"], default-features=false }
[target.'cfg(not(target_os = "linux"))'.dependencies]
@@ -215,19 +215,6 @@ exclude = ["vdi/host"]
# This allows building and running on systems without libxdo installed (e.g., Wayland-only)
[patch.crates-io]
libxdo-sys = { path = "libs/libxdo-sys-stub" }
# One branch off upstream v0.13.0, the tag whose crate versions match this stack.
# webrtc-util: reads the Windows adapter list's IPv6 addresses as host-order u16 groups, so every
# one comes out byte-swapped, fails to bind, and ICE gathers no IPv6 host candidate on Windows.
# webrtc-sctp: RFC 4960's 1s RTO floor makes a single loss cost 1-3s on a link whose RTT is 24-64ms,
# and fast retransmit cannot cover a request/response exchange; INITIAL_MTU 1228 also fragments on
# IPv6; and its AIMD pins a lossy long-haul link to MSS/(RTT*sqrt(p)), so a switch sends without
# a congestion window, as KCP does - on by default, `allow-webrtc-congestion-control` opts back in.
# Sending that way, a reordering window keeps a chunk that is merely late from being resent on a
# path that jitters, every DATA chunk asks for its SACK at once so a lost tail is back within an
# RTT at KCP's RTO floors, and bundles of small chunks stay within the MTU.
# Pinned by rev, not branch: a fork branch can be rewritten out from under the lockfile.
webrtc-util = { git = "https://github.com/rustdesk-org/webrtc", rev = "48100bf13e694d7e5bbb49b9a753dbad1c359d0c" }
webrtc-sctp = { git = "https://github.com/rustdesk-org/webrtc", rev = "48100bf13e694d7e5bbb49b9a753dbad1c359d0c" }
[package.metadata.winres]
LegalCopyright = "Copyright © 2026 Purslane Tech Pte. Ltd. All rights reserved."
@@ -247,7 +234,6 @@ os-version = "0.2"
[dev-dependencies]
hound = "3.5"
docopt = "1.1"
tokio = { version = "1.44", features = ["test-util"] }
[package.metadata.bundle]
name = "RustDesk"

View File

@@ -43,15 +43,6 @@ fn build_manifest() {
}
}
// bionic only exports getifaddrs()/freeifaddrs() from API 24, while the jniLibs
// are built against the API 21 sysroot (flutter/ndk_*.sh). webrtc-util calls
// them, so without this the android link fails on undefined symbols.
fn build_android_ifaddrs() {
let file = "src/platform/android_ifaddrs.c";
cc::Build::new().file(file).compile("android_ifaddrs");
println!("cargo:rerun-if-changed={}", file);
}
fn install_android_deps() {
let target_os = std::env::var("CARGO_CFG_TARGET_OS").unwrap();
if target_os != "android" {
@@ -98,8 +89,5 @@ fn main() {
build_mac();
println!("cargo:rustc-link-lib=framework=ApplicationServices");
}
if target_os == "android" {
build_android_ifaddrs();
}
println!("cargo:rerun-if-changed=build.rs");
}

View File

@@ -1633,8 +1633,7 @@ String bool2option(String option, bool b) {
String res;
if (option.startsWith('enable-') &&
option != kOptionEnableUdpPunch &&
option != kOptionEnableIpv6Punch &&
option != kOptionEnableWebrtc) {
option != kOptionEnableIpv6Punch) {
res = b ? defaultOptionYes : 'N';
} else if (option.startsWith('allow-') ||
option == kOptionStopService ||

View File

@@ -606,9 +606,6 @@ class QualityMonitor extends StatelessWidget {
_row(
"Codec", qualityMonitorModel.data.codecFormat ?? '-'),
_row("Chroma", qualityMonitorModel.data.chroma ?? '-'),
if (qualityMonitorModel.webrtcTransport != null)
_row("Transport",
qualityMonitorModel.webrtcTransport!),
],
),
)

View File

@@ -172,12 +172,10 @@ const String kOptionAllowRemoveWallpaper = "allow-remove-wallpaper";
const String kOptionStopService = "stop-service";
const String kOptionDirectxCapture = "enable-directx-capture";
const String kOptionAllowRemoteCmModification = "allow-remote-cm-modification";
const String kOptionEnableTcpPunch = "enable-tcp-punch";
const String kOptionEnableUdpPunch = "enable-udp-punch";
const String kOptionEnableIpv6Punch = "enable-ipv6-punch";
const String kOptionAllowSyncClipboardBetweenSessions =
"allow-sync-clipboard-between-sessions";
const String kOptionEnableWebrtc = "enable-webrtc";
const String kOptionEnableTrustedDevices = "enable-trusted-devices";
const String kOptionShowVirtualMouse = "show-virtual-mouse";
const String kOptionVirtualMouseScale = "virtual-mouse-scale";

View File

@@ -572,12 +572,6 @@ class _GeneralState extends State<_General> {
kOptionDirectxCapture,
),
if (!isWeb && !incomingOnly) ...[
_OptionCheckBox(
context,
'Enable TCP hole punching',
kOptionEnableTcpPunch,
isServer: false,
),
_OptionCheckBox(
context,
'Enable UDP hole punching',
@@ -590,15 +584,6 @@ class _GeneralState extends State<_General> {
kOptionEnableIpv6Punch,
isServer: false,
),
],
if (!incomingOnly)
_OptionCheckBox(
context,
'Enable WebRTC P2P connection',
kOptionEnableWebrtc,
isServer: false,
),
if (!isWeb && !incomingOnly)
Tooltip(
message: translate('sync-clipboard-between-sessions-tip'),
child: _OptionCheckBox(
@@ -608,6 +593,7 @@ class _GeneralState extends State<_General> {
isServer: false,
),
),
],
];
// Add client-side wakelock option for desktop platforms

View File

@@ -97,12 +97,10 @@ class _SettingsState extends State<SettingsPage> with WidgetsBindingObserver {
var _hideNetwork = false;
var _hideWebSocket = false;
var _enableTrustedDevices = false;
var _enableTcpPunch = false;
var _enableUdpPunch = false;
var _allowInsecureTlsFallback = false;
var _disableUdp = false;
var _enableIpv6Punch = false;
var _enableWebrtc = false;
var _isUsingPublicServer = false;
var _allowAskForNoteAtEndOfConnection = false;
var _preventSleepWhileConnected = true;
@@ -143,10 +141,8 @@ class _SettingsState extends State<SettingsPage> with WidgetsBindingObserver {
bind.mainGetBuildinOption(key: kOptionHideWebSocketSetting) == 'Y' ||
isWeb;
_enableTrustedDevices = mainGetBoolOptionSync(kOptionEnableTrustedDevices);
_enableTcpPunch = mainGetLocalBoolOptionSync(kOptionEnableTcpPunch);
_enableUdpPunch = mainGetLocalBoolOptionSync(kOptionEnableUdpPunch);
_enableIpv6Punch = mainGetLocalBoolOptionSync(kOptionEnableIpv6Punch);
_enableWebrtc = mainGetLocalBoolOptionSync(kOptionEnableWebrtc);
_allowAskForNoteAtEndOfConnection =
mainGetLocalBoolOptionSync(kOptionAllowAskForNoteAtEndOfConnection);
_preventSleepWhileConnected =
@@ -819,65 +815,31 @@ class _SettingsState extends State<SettingsPage> with WidgetsBindingObserver {
});
},
),
if (!incomingOnly)
SettingsTile.switchTile(
title: Text(translate('Enable TCP hole punching')),
initialValue: _enableTcpPunch,
onToggle: isOptionFixed(kOptionEnableTcpPunch)
? null
: (v) async {
await mainSetLocalBoolOption(kOptionEnableTcpPunch, v);
final newValue =
mainGetLocalBoolOptionSync(kOptionEnableTcpPunch);
setState(() {
_enableTcpPunch = newValue;
});
},
),
if (!incomingOnly)
SettingsTile.switchTile(
title: Text(translate('Enable UDP hole punching')),
initialValue: _enableUdpPunch,
onToggle: isOptionFixed(kOptionEnableUdpPunch)
? null
: (v) async {
await mainSetLocalBoolOption(kOptionEnableUdpPunch, v);
final newValue =
mainGetLocalBoolOptionSync(kOptionEnableUdpPunch);
setState(() {
_enableUdpPunch = newValue;
});
},
onToggle: (v) async {
await mainSetLocalBoolOption(kOptionEnableUdpPunch, v);
final newValue =
mainGetLocalBoolOptionSync(kOptionEnableUdpPunch);
setState(() {
_enableUdpPunch = newValue;
});
},
),
if (!incomingOnly)
SettingsTile.switchTile(
title: Text(translate('Enable IPv6 P2P connection')),
initialValue: _enableIpv6Punch,
onToggle: isOptionFixed(kOptionEnableIpv6Punch)
? null
: (v) async {
await mainSetLocalBoolOption(kOptionEnableIpv6Punch, v);
final newValue =
mainGetLocalBoolOptionSync(kOptionEnableIpv6Punch);
setState(() {
_enableIpv6Punch = newValue;
});
},
),
if (!incomingOnly)
SettingsTile.switchTile(
title: Text(translate('Enable WebRTC P2P connection')),
initialValue: _enableWebrtc,
onToggle: isOptionFixed(kOptionEnableWebrtc)
? null
: (v) async {
await mainSetLocalBoolOption(kOptionEnableWebrtc, v);
final newValue =
mainGetLocalBoolOptionSync(kOptionEnableWebrtc);
setState(() {
_enableWebrtc = newValue;
});
},
onToggle: (v) async {
await mainSetLocalBoolOption(kOptionEnableIpv6Punch, v);
final newValue =
mainGetLocalBoolOptionSync(kOptionEnableIpv6Punch);
setState(() {
_enableIpv6Punch = newValue;
});
},
),
SettingsTile(
title: Text(translate('Language')),

View File

@@ -3597,16 +3597,6 @@ class QualityMonitorModel with ChangeNotifier {
bool get show => _show;
QualityMonitorData get data => _data;
// Only a WebRTC session names its transport here: web has no session tab
// to show it on, and WebRTC is the one path that can be direct or TURN.
String? get webrtcTransport {
final ffiModel = parent.target?.ffiModel;
if (ffiModel == null) return null;
final streamType = ffiModel.cachedPeerData.streamType;
if (!streamType.startsWith('WebRTC')) return null;
return ffiModel.direct == false ? '$streamType (TURN)' : streamType;
}
checkShowQualityMonitor(SessionID sessionId) async {
final show = await bind.sessionGetToggleOption(
sessionId: sessionId, arg: 'show-quality-monitor') ==

View File

@@ -143,7 +143,7 @@ fn test_vpx(
println!(
"{:?} encode: {:?}, {} byte",
codec_id,
time_sum / yuv_count as u32,
time_sum / yuv_count as _,
size / yuv_count
);
@@ -156,7 +156,7 @@ fn test_vpx(
println!(
"{:?} decode: {:?}",
codec_id,
start.elapsed() / yuv_count as u32
start.elapsed() / yuv_count as _
);
}
@@ -212,7 +212,7 @@ fn test_av1(
assert_eq!(av1s.len(), yuv_count);
println!(
"AV1 encode: {:?}, {} byte",
time_sum / yuv_count as u32,
time_sum / yuv_count as _,
size / yuv_count
);
let mut decoder = AomDecoder::new().unwrap();
@@ -221,7 +221,7 @@ fn test_av1(
let _ = decoder.decode(&av1);
let _ = decoder.flush();
}
println!("AV1 decode: {:?}", start.elapsed() / yuv_count as u32);
println!("AV1 decode: {:?}", start.elapsed() / yuv_count as _);
}
#[cfg(feature = "hwcodec")]

File diff suppressed because it is too large Load Diff

View File

@@ -185,14 +185,6 @@ impl<T: InvokeUiSession> Remote<T> {
.unwrap()
.set_connected();
let is_secured = peer.is_secured();
// Only WebRTC needs refining: its label names the transport that won the race,
// not the family ICE ended up nominating, and it is the one path where the two
// can disagree with the address the rendezvous observed.
let stream_type = if peer.webrtc_remote_ipv6().await.unwrap_or(false) {
"WebRTC/IPv6"
} else {
stream_type
};
self.handler
.set_connection_type(is_secured, direct, stream_type); // flutter -> connection_ready
if !is_secured

View File

@@ -1,7 +1,7 @@
use std::{
collections::HashMap,
future::Future,
net::SocketAddr,
net::{SocketAddr, ToSocketAddrs},
sync::{Arc, Mutex, RwLock},
task::Poll,
};
@@ -1153,13 +1153,6 @@ pub fn is_public(url: &str) -> bool {
host == "rustdesk.com" || host.ends_with(".rustdesk.com")
}
pub fn get_tcp_punch_enabled() -> bool {
config::option2bool(
keys::OPTION_ENABLE_TCP_PUNCH,
&get_local_option(keys::OPTION_ENABLE_TCP_PUNCH),
)
}
pub fn get_udp_punch_enabled() -> bool {
config::option2bool(
keys::OPTION_ENABLE_UDP_PUNCH,
@@ -1174,19 +1167,9 @@ pub fn get_ipv6_punch_enabled() -> bool {
)
}
pub fn get_webrtc_enabled() -> bool {
config::option2bool(
keys::OPTION_ENABLE_WEBRTC,
&get_local_option(keys::OPTION_ENABLE_WEBRTC),
)
}
pub fn get_local_option(key: &str) -> String {
let v = LocalConfig::get_option(key);
if key == keys::OPTION_ENABLE_UDP_PUNCH
|| key == keys::OPTION_ENABLE_IPV6_PUNCH
|| key == keys::OPTION_ENABLE_WEBRTC
{
if key == keys::OPTION_ENABLE_UDP_PUNCH || key == keys::OPTION_ENABLE_IPV6_PUNCH {
if v.is_empty() {
if !is_public(&Config::get_rendezvous_server()) {
return "N".to_owned();
@@ -2143,21 +2126,11 @@ pub fn get_rs_pk(str_base64: &str) -> Option<sign::PublicKey> {
}
pub fn decode_id_pk(signed: &[u8], key: &sign::PublicKey) -> ResultType<(String, [u8; 32])> {
let (id, pk, _) = decode_id_pk_dtls(signed, key)?;
Ok((id, pk))
}
/// Like [`decode_id_pk`] but also returns the signed DTLS certificate fingerprint (empty string
/// for non-WebRTC peers), used to bind a WebRTC DTLS channel to the verified peer identity.
pub fn decode_id_pk_dtls(
signed: &[u8],
key: &sign::PublicKey,
) -> ResultType<(String, [u8; 32], String)> {
let res = IdPk::parse_from_bytes(
&sign::verify(signed, key).map_err(|_| anyhow!("Signature mismatch"))?,
)?;
if let Some(pk) = get_pk(&res.pk) {
Ok((res.id, pk, res.dtls_fingerprint))
Ok((res.id, pk))
} else {
bail!("Wrong their public length");
}
@@ -2459,26 +2432,16 @@ pub fn is_udp_disabled() -> bool {
Config::get_option(keys::OPTION_DISABLE_UDP) == "Y"
}
/// Run KCP with its congestion window (nc=0) instead of the turbo profile it has always shipped.
///
/// Opt-in: which profile wins depends on why packets are lost — nc=1 deepens real congestion,
/// while nc=0 reads random loss as congestion and its RTO backoff drops cwnd to 1. Undecidable
/// without a shaped link, so keep what users run today.
#[inline]
pub fn get_kcp_cc_enabled() -> bool {
let k = keys::OPTION_ALLOW_KCP_CC;
config::option2bool(k, &Config::get_option(k))
}
// this crate https://github.com/yoshd/stun-client supports nat type
async fn stun_ipv6_test(stun_server: String) -> ResultType<(SocketAddr, String)> {
async fn stun_ipv6_test(stun_server: &str) -> ResultType<(SocketAddr, String)> {
use std::net::ToSocketAddrs;
use stunclient::StunClient;
let local_addr = SocketAddr::from(([0u16; 8], 0)); // [::]:0
let socket = UdpSocket::bind(&local_addr).await?;
// Resolve via tokio so DNS never blocks the async runtime worker.
let Some(stun_addr) = tokio::net::lookup_host(&stun_server)
.await?
.find(|x| x.is_ipv6())
let Some(stun_addr) = stun_server
.to_socket_addrs()?
.filter(|x| x.is_ipv6())
.next()
else {
bail!(
"Failed to resolve STUN ipv6 server address: {}",
@@ -2488,36 +2451,81 @@ async fn stun_ipv6_test(stun_server: String) -> ResultType<(SocketAddr, String)>
let client = StunClient::new(stun_addr);
let addr = client.query_external_address_async(&socket).await?;
Ok(if addr.ip().is_ipv6() {
(addr, stun_server)
(addr, stun_server.to_owned())
} else {
bail!("STUN server returned non-IPv6 address: {}", addr)
})
}
async fn stun_ipv4_test(stun_server: &str) -> ResultType<(SocketAddr, String)> {
use std::net::ToSocketAddrs;
use stunclient::StunClient;
let local_addr = SocketAddr::from(([0u8; 4], 0));
let socket = UdpSocket::bind(&local_addr).await?;
let Some(stun_addr) = stun_server
.to_socket_addrs()?
.filter(|x| x.is_ipv4())
.next()
else {
bail!(
"Failed to resolve STUN ipv4 server address: {}",
stun_server
);
};
let client = StunClient::new(stun_addr);
let addr = client.query_external_address_async(&socket).await?;
Ok(if addr.ip().is_ipv4() {
(addr, stun_server.to_owned())
} else {
bail!("STUN server returned non-IPv6 address: {}", addr)
})
}
static STUNS_V4: [&str; 3] = [
"stun.l.google.com:19302",
"stun.cloudflare.com:3478",
"stun.nextcloud.com:3478",
];
static STUNS_V6: [&str; 3] = [
"stun.l.google.com:19302",
"stun.cloudflare.com:3478",
"stun.nextcloud.com:3478",
];
pub async fn test_nat_ipv4() -> ResultType<(SocketAddr, String)> {
use hbb_common::futures::future::{select_ok, FutureExt};
let tests = STUNS_V4
.iter()
.map(|&stun| stun_ipv4_test(stun).boxed())
.collect::<Vec<_>>();
match select_ok(tests).await {
Ok(res) => {
return Ok(res.0);
}
Err(e) => {
bail!(
"Failed to get public IPv4 address via public STUN servers: {}",
e
);
}
};
}
async fn test_bind_ipv6() -> ResultType<SocketAddr> {
use hbb_common::futures::future::FutureExt;
let local_addr = SocketAddr::from(([0u16; 8], 0)); // [::]:0
let socket = UdpSocket::bind(local_addr).await?;
// Nothing is sent - `connect` only makes the kernel pick a route and a source address - so any
// resolvable target answers equally and the whole cost is DNS. Race the lookups rather than
// walk them: this is awaited inline on the connection path, not every STUN host publishes a
// AAAA, and one resolver that hangs must not decide whether this host has v6.
let lookups = hbb_common::webrtc::WebRTCStream::default_stun_servers()
.into_iter()
.map(|stun| {
(async move {
let addr = tokio::net::lookup_host(&stun)
.await?
.find(|x| x.is_ipv6())
.ok_or_else(|| {
anyhow!("Failed to resolve STUN ipv6 server address: {}", stun)
})?;
Ok::<SocketAddr, hbb_common::anyhow::Error>(addr)
})
.boxed()
})
.collect::<Vec<_>>();
let (addr, _) = hbb_common::futures::future::select_ok(lookups).await?;
let addr = STUNS_V6[0]
.to_socket_addrs()?
.filter(|x| x.is_ipv6())
.next()
.ok_or_else(|| {
anyhow!(
"Failed to resolve STUN ipv6 server address: {}",
STUNS_V6[0]
)
})?;
socket.connect(addr).await?;
Ok(socket.local_addr()?)
}
@@ -2584,9 +2592,9 @@ pub async fn test_ipv6() -> Option<tokio::task::JoinHandle<()>> {
Some(tokio::spawn(async {
use hbb_common::futures::future::{select_ok, FutureExt};
let tests = hbb_common::webrtc::WebRTCStream::default_stun_servers()
.into_iter()
.map(|stun| stun_ipv6_test(stun).boxed())
let tests = STUNS_V6
.iter()
.map(|&stun| stun_ipv6_test(stun).boxed())
.collect::<Vec<_>>();
match select_ok(tests).await {
@@ -2607,117 +2615,51 @@ pub async fn test_ipv6() -> Option<tokio::task::JoinHandle<()>> {
}))
}
// A punch packet carries a magic and a transaction id so a reply can be *proven* to answer this
// probe. The punch it replaces sent a zero-length datagram and called the hole open on whatever
// arrived next - which the rendezvous NAT test's own leftover replies satisfied instantly, so the
// retry loop below never actually ran and its success meant nothing.
const PUNCH_PROBE: [u8; 4] = *b"RDP?";
const PUNCH_ACK: [u8; 4] = *b"RDP!";
const PUNCH_PACKET_LEN: usize = 12;
fn punch_packet(tag: &[u8; 4], tid: u64) -> [u8; PUNCH_PACKET_LEN] {
let mut packet = [0u8; PUNCH_PACKET_LEN];
packet[..4].copy_from_slice(tag);
packet[4..].copy_from_slice(&tid.to_le_bytes());
packet
}
fn punch_tid(packet: &[u8], tag: &[u8; 4]) -> Option<u64> {
if packet.len() != PUNCH_PACKET_LEN || packet[..4] != tag[..] {
return None;
}
packet[4..].try_into().ok().map(u64::from_le_bytes)
}
/// Punch until one of our own probes is acknowledged. Both ends run this identically - each
/// probes, each answers the other's probes - and each returns only once a reply carrying its own
/// transaction id comes back, the one thing that proves the pair carries traffic both ways.
///
/// Returning is therefore a fact rather than a guess, which is what lets the caller stop instead
/// of handing a dead socket to a transport whose only way to discover the truth is to time out.
///
/// A datagram that is neither probe nor acknowledgement is returned rather than dropped: it means
/// the peer finished first and is already speaking KCP, whose SYN is never retransmitted.
///
/// 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 this returns nothing answers probes any more, since KCP's io loop drops anything
/// shorter than its header. A listener that stopped here would go mute while a peer whose own
/// probe or answer was lost - the normal state of a hole that is still opening - kept probing an
/// endpoint that works, until it timed out. So the listener stops on the peer's first real packet.
pub async fn punch_udp(
socket: Arc<UdpSocket>,
listen: bool,
) -> ResultType<Option<bytes::BytesMut>> {
let tid = ((hbb_common::time_based_rand() as u64) << 32) | hbb_common::time_based_rand() as u64;
let probe = punch_packet(&PUNCH_PROBE, tid);
let mut data = [0u8; 1500];
// `connect` does not flush the receive queue, so the NAT test's extra replies are still in it.
while socket.try_recv(&mut data).is_ok() {}
let mut retry_interval = Duration::from_millis(20);
const MAX_INTERVAL: Duration = Duration::from_millis(200);
// Both ends start within one rendezvous round trip of each other and the acknowledgement is
// one peer round trip, so a pair that has not answered in this long is not going to. The old
// 20s came from having no way to tell "not yet" from "never".
const MAX_TIME: Duration = Duration::from_secs(3);
let mut probes_sent = 0u32;
let mut probes_seen = 0u32;
let mut acked = false;
let mut recv_errors = 0u32;
socket.send(&probe).await.ok();
probes_sent += 1;
const MAX_TIME: Duration = Duration::from_secs(20);
let mut packets_sent = 0;
socket.send(&[]).await.ok();
packets_sent += 1;
let mut last_send_time = Instant::now();
let tm = Instant::now();
// Absolute instants, not relative sleeps: `select!` rebuilds every arm each iteration, so a
// peer that keeps the receive side ready restarts a relative timer before it can fire. That
// both defeats MAX_TIME and starves the retransmit, and the peer decides the rate - an
// old-build peer's empty datagrams match no arm below and loop without even a pause.
let deadline = tm + MAX_TIME;
let mut next_probe = tm + retry_interval;
let mut data = [0u8; 1500];
loop {
tokio::select! {
_ = tokio::time::sleep_until(deadline) => {
bail!("UDP punch is timed out, {probes_sent} probes sent, {probes_seen} probes received, acked: {acked}, {recv_errors} recv errors absorbed");
}
_ = tokio::time::sleep_until(next_probe) => {
socket.send(&probe).await.ok();
probes_sent += 1;
retry_interval = std::cmp::min(retry_interval.mul_f64(1.5), MAX_INTERVAL);
next_probe = Instant::now() + retry_interval;
_ = hbb_common::sleep(retry_interval.as_secs_f32()) => {
if tm.elapsed() > MAX_TIME {
bail!("UDP punch is timed out, stop sending packets after {:?} packets", packets_sent);
}
let elapsed = last_send_time.elapsed();
if elapsed >= retry_interval {
socket.send(&[]).await.ok();
packets_sent += 1;
// Exponentially increase interval to reduce network pressure
retry_interval = std::cmp::min(
Duration::from_millis((retry_interval.as_millis() as f64 * 1.5) as u64),
MAX_INTERVAL
);
last_send_time = Instant::now();
}
}
res = socket.recv(&mut data) => match res {
Err(e) => {
// ICMP unreachable from the peer's NAT is expected while the hole forms and
// surfaces here as ConnectionReset/Refused; treat it as loss, MAX_TIME bounds
// the attempt. Log only the first - this retries every 10ms.
recv_errors += 1;
if recv_errors == 1 {
log::debug!("UDP punch recv error (treated as loss): {e}");
}
hbb_common::sleep(0.01).await;
}
Err(e) => bail!("UDP punch failed, {packets_sent} packets sent: {e}"),
Ok(n) => {
let ack = punch_tid(&data[..n], &PUNCH_ACK);
if ack == Some(tid) {
if !listen {
log::debug!(
"UDP punch confirmed in {:?}, {probes_sent} probes sent, {probes_seen} received",
tm.elapsed()
);
return Ok(None);
// log::debug!("UDP punch succeeded after sending {} packets after {:?}", packets_sent, tm.elapsed());
if listen {
if n == 0 {
continue;
}
acked = true;
} else if let Some(peer_tid) = punch_tid(&data[..n], &PUNCH_PROBE) {
probes_seen += 1;
socket.send(&punch_packet(&PUNCH_ACK, peer_tid)).await.ok();
} else if ack.is_none() && n > 0 {
log::debug!(
"UDP punch confirmed by {n} bytes of peer data in {:?}, {probes_sent} probes sent",
tm.elapsed()
);
return Ok(Some(bytes::BytesMut::from(&data[..n])));
}
return Ok(None);
}
}
}
@@ -2841,38 +2783,6 @@ mod tests {
)
}
// The deadline must hold against a peer that keeps the receive side ready. `select!` rebuilds
// its arms every iteration, so a relative sleep would be restarted by every datagram and the
// punch would run for as long as the peer keeps talking, with no outer timeout to stop it.
#[tokio::test]
async fn test_udp_punch_deadline_survives_a_talkative_peer() {
let a = UdpSocket::bind("127.0.0.1:0").await.unwrap();
let b = UdpSocket::bind("127.0.0.1:0").await.unwrap();
let (a_addr, b_addr) = (a.local_addr().unwrap(), b.local_addr().unwrap());
a.connect(b_addr).await.unwrap();
b.connect(a_addr).await.unwrap();
// Empty datagrams answer no probe and match no return branch, so they only feed the loop.
// Sent well past the punch deadline so a restarted timer would show up as a long run.
let flooder = tokio::spawn(async move {
let end = Instant::now() + Duration::from_secs(12);
while Instant::now() < end {
if b.send(&[]).await.is_err() {
break;
}
sleep(Duration::from_millis(5)).await;
}
});
let start = Instant::now();
let res = punch_udp(Arc::new(a), false).await;
let elapsed = start.elapsed();
flooder.abort();
assert!(res.is_err(), "the punch should have timed out");
assert!(
elapsed < Duration::from_secs(6),
"the punch ran for {elapsed:?}; its deadline did not hold"
);
}
#[test]
fn untrusted_peer_id_validation() {
let cases = [

View File

@@ -24,6 +24,7 @@ use std::os::windows::io::AsRawHandle;
use std::{
fs,
path::{Path, PathBuf},
sync::{Mutex, OnceLock},
};
#[cfg(windows)]
use windows::Win32::{Foundation::HANDLE, System::Pipes::GetNamedPipeClientProcessId};
@@ -519,17 +520,66 @@ pub(crate) fn ensure_peer_executable_matches_current_by_fd(
#[cfg(any(target_os = "windows", target_os = "linux", target_os = "macos"))]
const UNAUTHORIZED_IPC_LOG_INTERVAL: std::time::Duration = std::time::Duration::from_secs(5);
#[cfg(any(target_os = "windows", target_os = "linux", target_os = "macos"))]
#[derive(Default)]
struct UnauthorizedIpcLogThrottle {
last_log_at: Option<std::time::Instant>,
suppressed: u64,
}
#[cfg(any(target_os = "windows", target_os = "linux", target_os = "macos"))]
impl UnauthorizedIpcLogThrottle {
#[inline]
fn on_reject(&mut self, now: std::time::Instant) -> Option<u64> {
if let Some(last) = self.last_log_at {
if now.saturating_duration_since(last) < UNAUTHORIZED_IPC_LOG_INTERVAL {
self.suppressed += 1;
return None;
}
}
self.last_log_at = Some(now);
Some(std::mem::take(&mut self.suppressed))
}
}
#[cfg(any(target_os = "windows", target_os = "linux", target_os = "macos"))]
#[inline]
fn throttled_unauthorized_ipc_log(
throttle_cell: &OnceLock<Mutex<UnauthorizedIpcLogThrottle>>,
emit: impl FnOnce(u64),
) {
let throttle = throttle_cell.get_or_init(|| Mutex::new(UnauthorizedIpcLogThrottle::default()));
let should_log = match throttle.lock() {
Ok(mut throttle) => throttle.on_reject(std::time::Instant::now()),
Err(_) => Some(0),
};
if let Some(suppressed) = should_log {
emit(suppressed);
}
}
#[cfg(any(target_os = "linux", target_os = "macos"))]
#[inline]
fn log_rejected_service_connection(postfix: &str, peer_uid: Option<u32>, active_uid: Option<u32>) {
hbb_common::throttled_log!(
UNAUTHORIZED_IPC_LOG_INTERVAL,
warn,
"Rejected unauthorized connection on protected service-scoped IPC channel: postfix={}, peer_uid={:?}, active_uid={:?}",
postfix,
peer_uid,
active_uid
);
static LOG_THROTTLE: OnceLock<Mutex<UnauthorizedIpcLogThrottle>> = OnceLock::new();
throttled_unauthorized_ipc_log(&LOG_THROTTLE, |suppressed| {
if suppressed > 0 {
log::warn!(
"Rejected unauthorized connection on protected service-scoped IPC channel: postfix={}, peer_uid={:?}, active_uid={:?} (suppressed {} similar events)",
postfix,
peer_uid,
active_uid,
suppressed
);
} else {
log::warn!(
"Rejected unauthorized connection on protected service-scoped IPC channel: postfix={}, peer_uid={:?}, active_uid={:?}",
postfix,
peer_uid,
active_uid
);
}
});
}
#[cfg(target_os = "linux")]
@@ -539,14 +589,25 @@ pub(crate) fn log_rejected_uinput_connection(
peer_uid: Option<u32>,
active_uid: Option<u32>,
) {
hbb_common::throttled_log!(
UNAUTHORIZED_IPC_LOG_INTERVAL,
warn,
"Rejected unauthorized connection on uinput ipc channel: postfix={}, peer_uid={:?}, active_uid={:?}",
postfix,
peer_uid,
active_uid
);
static LOG_THROTTLE: OnceLock<Mutex<UnauthorizedIpcLogThrottle>> = OnceLock::new();
throttled_unauthorized_ipc_log(&LOG_THROTTLE, |suppressed| {
if suppressed > 0 {
log::warn!(
"Rejected unauthorized connection on uinput ipc channel: postfix={}, peer_uid={:?}, active_uid={:?} (suppressed {} similar events)",
postfix,
peer_uid,
active_uid,
suppressed
);
} else {
log::warn!(
"Rejected unauthorized connection on uinput ipc channel: postfix={}, peer_uid={:?}, active_uid={:?}",
postfix,
peer_uid,
active_uid
);
}
});
}
#[cfg(windows)]
@@ -559,17 +620,31 @@ pub(crate) fn log_rejected_windows_ipc_connection(
peer_is_system: Option<bool>,
peer_is_elevated: Option<bool>,
) {
hbb_common::throttled_log!(
UNAUTHORIZED_IPC_LOG_INTERVAL,
warn,
"Rejected unauthorized connection on ipc channel: postfix={}, peer_pid={:?}, peer_session_id={:?}, expected_session_id={:?}, peer_is_system={:?}, peer_is_elevated={:?}",
postfix,
peer_pid,
peer_session_id,
expected_session_id,
peer_is_system,
peer_is_elevated
);
static LOG_THROTTLE: OnceLock<Mutex<UnauthorizedIpcLogThrottle>> = OnceLock::new();
throttled_unauthorized_ipc_log(&LOG_THROTTLE, |suppressed| {
if suppressed > 0 {
log::warn!(
"Rejected unauthorized connection on ipc channel: postfix={}, peer_pid={:?}, peer_session_id={:?}, expected_session_id={:?}, peer_is_system={:?}, peer_is_elevated={:?} (suppressed {} similar events)",
postfix,
peer_pid,
peer_session_id,
expected_session_id,
peer_is_system,
peer_is_elevated,
suppressed
);
} else {
log::warn!(
"Rejected unauthorized connection on ipc channel: postfix={}, peer_pid={:?}, peer_session_id={:?}, expected_session_id={:?}, peer_is_system={:?}, peer_is_elevated={:?}",
postfix,
peer_pid,
peer_session_id,
expected_session_id,
peer_is_system,
peer_is_elevated
);
}
});
}
#[cfg(any(target_os = "linux", target_os = "macos"))]

View File

@@ -19,28 +19,7 @@ pub struct KcpStream {
stop_sender: Option<oneshot::Sender<()>>,
}
const KCP_IO_ERR_LOG_INTERVAL: std::time::Duration = std::time::Duration::from_secs(5);
static KCP_SEND_ERR_LOG: hbb_common::log_throttle::LogThrottle =
hbb_common::log_throttle::LogThrottle::new(KCP_IO_ERR_LOG_INTERVAL);
static KCP_RECV_ERR_LOG: hbb_common::log_throttle::LogThrottle =
hbb_common::log_throttle::LogThrottle::new(KCP_IO_ERR_LOG_INTERVAL);
impl KcpStream {
// Opt in to KCP's built-in congestion window (nc=0) instead of the pure turbo profile
// (nc=1) that has always shipped; see `get_kcp_cc_enabled` for why this is not the default.
// Sender-side only, so no wire negotiation is needed and either peer may run either profile.
// Requires kcp-sys from the `rustdesk-patches` branch, which wires the config factory into
// connection setup (on older revs the factory was stored but never consulted).
fn apply_kcp_config(endpoint: &mut KcpEndpoint) {
if crate::get_kcp_cc_enabled() {
endpoint.set_kcp_config_factory(Box::new(|conv| {
let mut config = kcp_sys::ffi_safe::KcpConfig::new_turbo(conv);
config.nc = Some(0);
config
}));
}
}
fn create_framed(stream: stream::KcpStream, local_addr: Option<SocketAddr>) -> Stream {
Stream::Tcp(FramedStream(
tokio_util::codec::Framed::new(DynTcpStream(Box::new(stream)), BytesCodec::new()),
@@ -56,7 +35,6 @@ impl KcpStream {
init_packet: Option<BytesMut>,
) -> ResultType<(Self, Stream)> {
let mut endpoint = KcpEndpoint::new();
Self::apply_kcp_config(&mut endpoint);
endpoint.run().await;
let (input, output) = (
@@ -92,7 +70,6 @@ impl KcpStream {
timeout: std::time::Duration,
) -> ResultType<(Self, Stream)> {
let mut endpoint = KcpEndpoint::new();
Self::apply_kcp_config(&mut endpoint);
endpoint.run().await;
let (input, output) = (
@@ -127,10 +104,6 @@ impl KcpStream {
let udp = udp_socket.clone();
tokio::spawn(async move {
let mut buf = vec![0; 1500];
// Socket errors are ICMP unreachable on a connected UDP socket — advisory, and
// routine while a hole forms — so treat them as loss and let KCP's pong timeout reap
// a link that is really dead. One throttle PER DIRECTION: the error is reported once
// and cleared, so send-ok/recv-err alternates and a shared counter never fires.
loop {
tokio::select! {
_ = &mut stop_receiver => {
@@ -139,10 +112,8 @@ impl KcpStream {
}
Some(data) = output.recv() => {
if let Err(e) = udp.send(&data.inner()).await {
if let Some(n) = KCP_SEND_ERR_LOG.due() {
log::debug!("KCP send error x{n} (treated as loss), last: {e}");
}
tokio::time::sleep(std::time::Duration::from_millis(10)).await;
log::debug!("KCP send error: {:?}", e);
break;
}
}
result = udp.recv_from(&mut buf) => {
@@ -156,10 +127,8 @@ impl KcpStream {
.await.ok();
}
Err(e) => {
if let Some(n) = KCP_RECV_ERR_LOG.due() {
log::debug!("KCP recv error x{n} (treated as loss), last: {e}");
}
tokio::time::sleep(std::time::Duration::from_millis(10)).await;
log::debug!("KCP recv_from error: {:?}", e);
break;
}
}
}
@@ -180,124 +149,3 @@ impl Drop for KcpStream {
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::time::Duration;
async fn connected_pair() -> (Arc<UdpSocket>, Arc<UdpSocket>) {
let a = UdpSocket::bind("127.0.0.1:0").await.unwrap();
let b = UdpSocket::bind("127.0.0.1:0").await.unwrap();
a.connect(b.local_addr().unwrap()).await.unwrap();
b.connect(a.local_addr().unwrap()).await.unwrap();
(Arc::new(a), Arc::new(b))
}
async fn establish() -> ((KcpStream, Stream), (KcpStream, Stream)) {
let (a, b) = connected_pair().await;
let (accept_res, connect_res) = tokio::join!(
KcpStream::accept(b, Duration::from_secs(5), None),
KcpStream::connect(a, Duration::from_secs(5))
);
(
connect_res.expect("connect over loopback"),
accept_res.expect("accept over loopback"),
)
}
// The full client path over real loopback sockets: handshake through the kcp_io
// pumps, framed data both ways, then a graceful close. The endpoint guard stays
// alive across the stream drop so the FIN can go out, and the peer's framed
// stream must end (BrokenPipe from the kcp reader) instead of hanging.
#[tokio::test]
async fn test_kcp_stream_loopback_roundtrip_and_close() {
let ((_guard_a, mut stream_a), (_guard_b, mut stream_b)) = establish().await;
stream_a
.send_bytes(Bytes::from_static(b"ping"))
.await
.unwrap();
let got = stream_b.next_timeout(5000).await.unwrap().unwrap();
assert_eq!(&got[..], b"ping");
stream_b
.send_bytes(Bytes::from_static(b"pong"))
.await
.unwrap();
let got = stream_a.next_timeout(5000).await.unwrap().unwrap();
assert_eq!(&got[..], b"pong");
drop(stream_a);
match stream_b.next_timeout(10_000).await {
None | Some(Err(_)) => {}
Some(Ok(data)) => panic!("unexpected data after close: {:?}", data),
}
}
// A writer that queues many frames and closes immediately must not cost the
// reader any of them: every frame arrives intact, in order, before end-of-stream.
// This is the client-side pin for the kcp-sys close-tail-drain semantics, through
// the real BytesCodec framing rustdesk sessions use.
#[tokio::test]
async fn test_kcp_stream_close_delivers_all_frames() {
let ((_guard_a, mut tx), (_guard_b, mut rx)) = establish().await;
const N: usize = 50;
let payload = vec![7u8; 32 * 1024];
for _ in 0..N {
tx.send_bytes(Bytes::from(payload.clone())).await.unwrap();
}
drop(tx);
let mut got = 0usize;
loop {
match rx.next_timeout(10_000).await {
Some(Ok(data)) => {
assert_eq!(data.len(), payload.len(), "frame boundary broken");
assert!(data.iter().all(|&b| b == 7), "frame content corrupted");
got += 1;
}
// BrokenPipe (kcp reader end) or timeout-None both end the stream.
None | Some(Err(_)) => break,
}
}
assert_eq!(got, N, "graceful close lost frames");
}
// Socket errors on the connected UDP socket (ICMP unreachable after the peer
// vanishes) are advisory: the io loop must treat them as loss - keep accepting
// writes, keep running - rather than tearing the session down. Whether the OS
// actually surfaces ECONNREFUSED here is platform-dependent; either way the
// session must stay alive for this window.
#[tokio::test]
async fn test_kcp_io_treats_socket_errors_as_loss() {
let ((_guard_a, mut stream_a), (guard_b, stream_b)) = establish().await;
// Kill the peer entirely: endpoint stops, socket closes.
drop(stream_b);
drop(guard_b);
tokio::time::sleep(Duration::from_millis(50)).await;
for _ in 0..10 {
stream_a
.send_bytes(Bytes::from_static(b"into the void"))
.await
.expect("socket errors must be treated as loss, not stream failure");
tokio::time::sleep(Duration::from_millis(20)).await;
}
}
// The connect deadline must hold when nothing answers: no hang, prompt error.
#[tokio::test]
async fn test_kcp_connect_timeout_without_peer() {
let (a, _b) = connected_pair().await;
let start = tokio::time::Instant::now();
let res = KcpStream::connect(a, Duration::from_millis(600)).await;
assert!(res.is_err(), "connect must fail with no peer endpoint");
assert!(
start.elapsed() < Duration::from_secs(5),
"connect did not honor its deadline"
);
}
}

View File

@@ -768,7 +768,5 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("Enable", "تفعيل"),
("Reuse one connection for port forwarding", "إعادة استخدام اتصال واحد لإعادة توجيه المنافذ"),
("port-forward-mux-tip", "تمرير جميع اتصالات إعادة توجيه المنافذ عبر اتصال واحد بالجهاز الآخر، بدلاً من الاتصال وتسجيل الدخول من جديد لكل اتصال."),
("Enable WebRTC P2P connection", "تمكين اتصال نظير إلى نظير عبر WebRTC"),
("Enable TCP hole punching", "تمكين تقنية حفر الثغرات عبر TCP"),
].iter().cloned().collect();
}

View File

@@ -768,7 +768,5 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("Enable", "Уключыць"),
("Reuse one connection for port forwarding", "Выкарыстоўваць адно злучэнне для перанакіравання партоў"),
("port-forward-mux-tip", "Перадаваць усе злучэнні аднаго перанакіравання партоў праз адно злучэнне з аддаленай прыладай замест паўторнага падлучэння і ўваходу для кожнага з іх."),
("Enable WebRTC P2P connection", "Выкарыстоўваць падключэнне WebRTC P2P"),
("Enable TCP hole punching", "Выкарыстоўваць TCP hole punching"),
].iter().cloned().collect();
}

View File

@@ -768,7 +768,5 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("Enable", "Активирай"),
("Reuse one connection for port forwarding", "Използване на една връзка за пренасочване на портове"),
("port-forward-mux-tip", "Всички връзки на едно пренасочване на портове минават през една връзка към отсрещния компютър, вместо да се свързвате и влизате отново за всяка от тях."),
("Enable WebRTC P2P connection", "Позволяване на WebRTC P2P връзка"),
("Enable TCP hole punching", "Позволяване на TCP hole punching"),
].iter().cloned().collect();
}

View File

@@ -768,7 +768,5 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("Enable", "Habilita"),
("Reuse one connection for port forwarding", "Reutilitza una connexió per a la redirecció de ports"),
("port-forward-mux-tip", "Fa passar totes les connexions d'una redirecció de ports per una única connexió amb l'altre equip, en lloc de connectar i iniciar la sessió de nou per a cadascuna."),
("Enable WebRTC P2P connection", "Habilita la connexió WebRTC P2P"),
("Enable TCP hole punching", "Activa la perforació TCP"),
].iter().cloned().collect();
}

View File

@@ -768,7 +768,5 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("Enable", "启用"),
("Reuse one connection for port forwarding", "端口转发复用同一条连接"),
("port-forward-mux-tip", "同一条端口转发规则上的所有连接共用一条到对方的连接,而不是每条连接都重新连接并登录一次。"),
("Enable WebRTC P2P connection", "启用 WebRTC P2P 连接"),
("Enable TCP hole punching", "启用 TCP 打洞"),
].iter().cloned().collect();
}

View File

@@ -768,7 +768,5 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("Enable", "Povolit"),
("Reuse one connection for port forwarding", "Znovu použít jedno připojení pro přesměrování portů"),
("port-forward-mux-tip", "Vede všechna připojení jednoho přesměrování portů přes jediné připojení k protějšku místo opakovaného připojování a přihlašování pro každé z nich."),
("Enable WebRTC P2P connection", "Povolit připojení WebRTC P2P"),
("Enable TCP hole punching", "Povolit TCP hole punching"),
].iter().cloned().collect();
}

View File

@@ -768,7 +768,5 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("Enable", "Aktivér"),
("Reuse one connection for port forwarding", "Genbrug én forbindelse til portvideresendelse"),
("port-forward-mux-tip", "Fører alle forbindelser i en portvideresendelse gennem én enkelt forbindelse til modparten i stedet for at forbinde og logge ind igen for hver enkelt."),
("Enable WebRTC P2P connection", "Aktivér WebRTC P2P-forbindelse"),
("Enable TCP hole punching", "Aktivér TCP hole punching"),
].iter().cloned().collect();
}

View File

@@ -768,7 +768,5 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("Enable", "Aktivieren"),
("Reuse one connection for port forwarding", "Eine Verbindung für die Portweiterleitung wiederverwenden"),
("port-forward-mux-tip", "Alle Verbindungen einer Portweiterleitung über eine einzige Verbindung zur Gegenstelle führen, statt sich für jede einzelne neu zu verbinden und anzumelden."),
("Enable WebRTC P2P connection", "WebRTC-P2P-Verbindung aktivieren"),
("Enable TCP hole punching", "TCP-Hole-Punching aktivieren"),
].iter().cloned().collect();
}

View File

@@ -768,7 +768,5 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("Enable", "Ενεργοποίηση"),
("Reuse one connection for port forwarding", "Επαναχρησιμοποίηση μίας σύνδεσης για την προώθηση θυρών"),
("port-forward-mux-tip", "Όλες οι συνδέσεις μιας προώθησης θυρών περνούν από μία μόνο σύνδεση προς τον απομακρυσμένο υπολογιστή, αντί να πραγματοποιείται νέα σύνδεση και ταυτοποίηση για κάθε μία."),
("Enable WebRTC P2P connection", "Ενεργοποίηση σύνδεσης WebRTC P2P"),
("Enable TCP hole punching", "Ενεργοποίηση διάτρησης οπών TCP"),
].iter().cloned().collect();
}

View File

@@ -768,7 +768,5 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("Enable", "Ebligi"),
("Reuse one connection for port forwarding", "Reuzi unu konekton por pordo-plusendado"),
("port-forward-mux-tip", "Ĉiuj konektoj de unu pordo-plusendado iras tra unu sola konekto al la alia komputilo, anstataŭ konekti kaj ensaluti denove por ĉiu el ili."),
("Enable WebRTC P2P connection", "Ebligi WebRTC P2P-konekton"),
("Enable TCP hole punching", "Ebligi TCP-trapikadon"),
].iter().cloned().collect();
}

View File

@@ -768,7 +768,5 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("Enable", "Habilitar"),
("Reuse one connection for port forwarding", "Reutilizar una conexión para la redirección de puertos"),
("port-forward-mux-tip", "Llevar todas las conexiones de una redirección de puertos por una única conexión con el otro equipo, en lugar de conectar e iniciar sesión de nuevo para cada una."),
("Enable WebRTC P2P connection", "Habilitar conexión WebRTC P2P"),
("Enable TCP hole punching", "Habilitar perforación de agujero TCP"),
].iter().cloned().collect();
}

View File

@@ -768,7 +768,5 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("Enable", "Luba"),
("Reuse one connection for port forwarding", "Kasuta pordi suunamiseks üht ühendust"),
("port-forward-mux-tip", "Juhib ühe pordisuunamise kõik ühendused ühe teise arvutiga loodud ühenduse kaudu, selle asemel et iga ühenduse jaoks uuesti ühenduda ja sisse logida."),
("Enable WebRTC P2P connection", "Luba WebRTC P2P-ühendus"),
("Enable TCP hole punching", "Luba TCP-augustamine"),
].iter().cloned().collect();
}

View File

@@ -768,7 +768,5 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("Enable", "Gaitu"),
("Reuse one connection for port forwarding", "Berrerabili konexio bakarra portuen birbideratzerako"),
("port-forward-mux-tip", "Portu-birbideratze baten konexio guztiak beste ordenagailurako konexio bakar batetik eramaten ditu, bakoitzerako berriro konektatu eta saioa hasi beharrean."),
("Enable WebRTC P2P connection", "Gaitu WebRTC P2P konexioa"),
("Enable TCP hole punching", "Gaitu TCP zulo-egitea"),
].iter().cloned().collect();
}

View File

@@ -768,7 +768,5 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("Enable", "فعال‌سازی"),
("Reuse one connection for port forwarding", "استفاده مجدد از یک اتصال برای هدایت پورت"),
("port-forward-mux-tip", "همه اتصال‌های یک هدایت پورت از یک اتصال واحد به دستگاه مقابل عبور می‌کنند، به‌جای اتصال و ورود دوباره برای هر کدام."),
("Enable WebRTC P2P connection", "فعال‌سازی اتصال همتا‌به‌همتای WebRTC"),
("Enable TCP hole punching", "فعال‌سازی تکنیک TCP hole punching"),
].iter().cloned().collect();
}

View File

@@ -768,7 +768,5 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("Enable", "Ota käyttöön"),
("Reuse one connection for port forwarding", "Käytä yhtä yhteyttä portin edelleenohjaukseen"),
("port-forward-mux-tip", "Välittää kaikki yhden portin edelleenohjauksen yhteydet yhden vastapuoleen avatun yhteyden kautta sen sijaan, että jokaista varten muodostettaisiin yhteys ja kirjauduttaisiin uudelleen."),
("Enable WebRTC P2P connection", "Ota WebRTC P2P yhteys käyttöön"),
("Enable TCP hole punching", "Ota käyttöön TCP hole punching tekniikka"),
].iter().cloned().collect();
}

View File

@@ -768,7 +768,5 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("Enable", "Activer"),
("Reuse one connection for port forwarding", "Réutiliser une seule connexion pour la redirection de ports"),
("port-forward-mux-tip", "Faire passer toutes les connexions d'une redirection de ports par une seule connexion vers le pair, au lieu de se connecter et de s'authentifier à nouveau pour chacune."),
("Enable WebRTC P2P connection", "Activer la connexion P2P WebRTC"),
("Enable TCP hole punching", "Activer le « hole punching » TCP"),
].iter().cloned().collect();
}

View File

@@ -768,7 +768,5 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("Enable", "ჩართვა"),
("Reuse one connection for port forwarding", "პორტის გადამისამართებისთვის ერთი კავშირის ხელახლა გამოყენება"),
("port-forward-mux-tip", "ერთი პორტის გადამისამართების ყველა კავშირი გადის მეორე კომპიუტერთან დამყარებული ერთი კავშირით, ნაცვლად იმისა, რომ თითოეულისთვის თავიდან დაუკავშირდეს და შევიდეს სისტემაში."),
("Enable WebRTC P2P connection", "WebRTC P2P კავშირის ჩართვა"),
("Enable TCP hole punching", "TCP hole punching-ის ჩართვა"),
].iter().cloned().collect();
}

View File

@@ -768,7 +768,5 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("Enable", "સક્ષમ કરો"),
("Reuse one connection for port forwarding", "પોર્ટ ફોરવર્ડિંગ માટે એક જ કનેક્શન ફરી વાપરો"),
("port-forward-mux-tip", "એક પોર્ટ ફોરવર્ડિંગનાં બધાં કનેક્શન સામેના કમ્પ્યુટર સાથેના એક જ કનેક્શન મારફતે જાય છે, દરેક માટે ફરીથી કનેક્ટ અને લોગિન કરવાને બદલે."),
("Enable WebRTC P2P connection", "WebRTC P2P કનેક્શન સક્ષમ કરો"),
("Enable TCP hole punching", "TCP હોલ પંચિંગ સક્ષમ કરો"),
].iter().cloned().collect();
}

View File

@@ -768,7 +768,5 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("Enable", "הפעל"),
("Reuse one connection for port forwarding", "שימוש חוזר בחיבור אחד להעברת פורטים"),
("port-forward-mux-tip", "כל החיבורים של העברת פורטים אחת עוברים דרך חיבור יחיד למחשב המרוחק, במקום ליצור חיבור חדש ולהיכנס מחדש עבור כל אחד מהם."),
("Enable WebRTC P2P connection", "אפשר חיבור WebRTC P2P"),
("Enable TCP hole punching", "אפשר TCP hole punching"),
].iter().cloned().collect();
}

View File

@@ -768,7 +768,5 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("Enable", "सक्षम करें"),
("Reuse one connection for port forwarding", "पोर्ट फ़ॉरवर्डिंग के लिए एक ही कनेक्शन दोबारा उपयोग करें"),
("port-forward-mux-tip", "एक पोर्ट फ़ॉरवर्डिंग के सभी कनेक्शन दूसरे कंप्यूटर से बने एक ही कनेक्शन से होकर जाते हैं, हर एक के लिए दोबारा कनेक्ट और लॉगिन करने के बजाय।"),
("Enable WebRTC P2P connection", "WebRTC P2P कनेक्शन सक्षम करें"),
("Enable TCP hole punching", "TCP होल पंचिंग सक्षम करें"),
].iter().cloned().collect();
}

View File

@@ -768,7 +768,5 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("Enable", "Omogući"),
("Reuse one connection for port forwarding", "Ponovno koristi jednu vezu za prosljeđivanje portova"),
("port-forward-mux-tip", "Sve veze jednog prosljeđivanja portova idu kroz jednu vezu prema drugoj strani, umjesto ponovnog povezivanja i prijave za svaku od njih."),
("Enable WebRTC P2P connection", "Omogući WebRTC P2P vezu"),
("Enable TCP hole punching", "Omogući TCP hole punching"),
].iter().cloned().collect();
}

View File

@@ -768,7 +768,5 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("Enable", "Engedélyezés"),
("Reuse one connection for port forwarding", "Egyetlen kapcsolat újrafelhasználása a portátirányításhoz"),
("port-forward-mux-tip", "Egy portátirányítás összes kapcsolatát egyetlen, a másik géppel létesített kapcsolaton vezeti át, ahelyett hogy mindegyikhez újra csatlakozna és bejelentkezne."),
("Enable WebRTC P2P connection", "WebRTC P2P kapcsolat engedélyezése"),
("Enable TCP hole punching", "TCP résszűrés engedélyezése"),
].iter().cloned().collect();
}

View File

@@ -768,7 +768,5 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("Enable", "Aktifkan"),
("Reuse one connection for port forwarding", "Gunakan ulang satu koneksi untuk penerusan port"),
("port-forward-mux-tip", "Menyalurkan semua koneksi dari satu penerusan port melalui satu koneksi ke perangkat lain, alih-alih menyambung dan masuk lagi untuk setiap koneksi."),
("Enable WebRTC P2P connection", "Aktifkan koneksi P2P WebRTC"),
("Enable TCP hole punching", "Aktifkan TCP hole punching"),
].iter().cloned().collect();
}

View File

@@ -768,7 +768,5 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("Enable", "Abilita"),
("Reuse one connection for port forwarding", "Riutilizza una sola connessione per l'inoltro delle porte"),
("port-forward-mux-tip", "Fa passare tutte le connessioni di un inoltro di porte su un'unica connessione verso il dispositivo remoto, invece di connettersi e autenticarsi di nuovo per ognuna."),
("Enable WebRTC P2P connection", "Abilita connessione P2P WebRTC"),
("Enable TCP hole punching", "Abilita hole punching TCP"),
].iter().cloned().collect();
}

View File

@@ -768,7 +768,5 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("Enable", "有効にする"),
("Reuse one connection for port forwarding", "ポート転送で 1 つの接続を再利用する"),
("port-forward-mux-tip", "1 つのポート転送のすべての接続を、相手への 1 本の接続にまとめます。接続ごとに接続とログインをやり直しません。"),
("Enable WebRTC P2P connection", "WebRTC P2P 接続を有効化する"),
("Enable TCP hole punching", "TCP ホールパンチを有効化する"),
].iter().cloned().collect();
}

View File

@@ -768,7 +768,5 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("Enable", "활성화"),
("Reuse one connection for port forwarding", "포트 포워딩에 연결 하나를 재사용"),
("port-forward-mux-tip", "포트 포워딩 하나의 모든 연결을 상대방과의 단일 연결로 전달합니다. 연결마다 다시 접속하고 로그인하지 않습니다."),
("Enable WebRTC P2P connection", "WebRTC P2P 연결 사용"),
("Enable TCP hole punching", "TCP 홀 펀칭 사용"),
].iter().cloned().collect();
}

View File

@@ -768,7 +768,5 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("Enable", "Қосу"),
("Reuse one connection for port forwarding", "Порт бағыттау үшін бір қосылымды қайта пайдалану"),
("port-forward-mux-tip", "Бір порт бағыттаудың барлық қосылымдары әрқайсысы үшін қайта қосылып кірудің орнына қарсы құрылғымен орнатылған бір қосылым арқылы өтеді."),
("Enable WebRTC P2P connection", "WebRTC P2P қосылымын іске қосу"),
("Enable TCP hole punching", "TCP hole punching'ті іске қосу"),
].iter().cloned().collect();
}

View File

@@ -768,7 +768,5 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("Enable", "Įgalinti"),
("Reuse one connection for port forwarding", "Prievadų peradresavimui naudoti vieną ryšį"),
("port-forward-mux-tip", "Visi vieno prievadų peradresavimo ryšiai eina per vieną ryšį su kitu kompiuteriu, užuot kiekvienam iš jų jungiantis ir prisijungiant iš naujo."),
("Enable WebRTC P2P connection", "Įgalinti WebRTC P2P ryšį"),
("Enable TCP hole punching", "Įgalinti TCP gręžimą (hole punching)"),
].iter().cloned().collect();
}

View File

@@ -768,7 +768,5 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("Enable", "Iespējot"),
("Reuse one connection for port forwarding", "Atkārtoti izmantot vienu savienojumu portu pārsūtīšanai"),
("port-forward-mux-tip", "Visi viena portu pārsūtījuma savienojumi tiek novadīti pa vienu savienojumu ar otru datoru, nevis katram no tiem izveidojot jaunu savienojumu un pieteikšanos."),
("Enable WebRTC P2P connection", "Iespējot WebRTC P2P savienojumu"),
("Enable TCP hole punching", "Iespējot TCP caurumu veidošanu"),
].iter().cloned().collect();
}

View File

@@ -768,7 +768,5 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("Enable", "അനുവദിക്കുക"),
("Reuse one connection for port forwarding", "പോർട്ട് ഫോർവേഡിംഗിന് ഒരേ കണക്ഷൻ വീണ്ടും ഉപയോഗിക്കുക"),
("port-forward-mux-tip", "ഒരു പോർട്ട് ഫോർവേഡിംഗിന്റെ എല്ലാ കണക്ഷനുകളും മറ്റേ കമ്പ്യൂട്ടറിലേക്കുള്ള ഒരൊറ്റ കണക്ഷനിലൂടെ കടന്നുപോകുന്നു, ഓരോന്നിനും വീണ്ടും കണക്റ്റ് ചെയ്ത് ലോഗിൻ ചെയ്യുന്നതിനു പകരം."),
("Enable WebRTC P2P connection", "WebRTC P2P കണക്ഷൻ അനുവദിക്കുക"),
("Enable TCP hole punching", "TCP ഹോൾ പഞ്ചിംഗ് അനുവദിക്കുക"),
].iter().cloned().collect();
}

View File

@@ -768,7 +768,5 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("Enable", "Aktiver"),
("Reuse one connection for port forwarding", "Gjenbruk én tilkobling for portvideresending"),
("port-forward-mux-tip", "Fører alle tilkoblinger i en portvideresending gjennom én enkelt tilkobling til motparten i stedet for å koble til og logge inn på nytt for hver enkelt."),
("Enable WebRTC P2P connection", "Aktiver WebRTC P2P-tilkobling"),
("Enable TCP hole punching", "Aktiver TCP hole punching"),
].iter().cloned().collect();
}

View File

@@ -768,7 +768,5 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("Enable", "Inschakelen"),
("Reuse one connection for port forwarding", "Eén verbinding hergebruiken voor poortdoorschakeling"),
("port-forward-mux-tip", "Alle verbindingen van een poortdoorschakeling via één enkele verbinding met de andere computer laten lopen, in plaats van voor elke verbinding opnieuw verbinding te maken en in te loggen."),
("Enable WebRTC P2P connection", "WebRTC P2P-verbinding inschakelen"),
("Enable TCP hole punching", "TCP-hole punching inschakelen"),
].iter().cloned().collect();
}

View File

@@ -768,7 +768,5 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("Enable", "Włącz"),
("Reuse one connection for port forwarding", "Użyj ponownie jednego połączenia do przekierowania portów"),
("port-forward-mux-tip", "Przekazuj wszystkie połączenia jednego przekierowania portów przez jedno połączenie ze zdalnym komputerem, zamiast łączyć się i logować od nowa dla każdego z nich."),
("Enable WebRTC P2P connection", "Włącz połączenie P2P WebRTC"),
("Enable TCP hole punching", "Włącz tworzenie tunelu TCP"),
].iter().cloned().collect();
}

View File

@@ -768,7 +768,5 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("Enable", "Ativar"),
("Reuse one connection for port forwarding", "Reutilizar uma ligação para o reencaminhamento de portas"),
("port-forward-mux-tip", "Encaminhar todas as ligações de um reencaminhamento de portas por uma única ligação ao outro computador, em vez de ligar e iniciar sessão novamente para cada uma."),
("Enable WebRTC P2P connection", "Ativar ligação P2P por WebRTC"),
("Enable TCP hole punching", "Ativar TCP hole punching"),
].iter().cloned().collect();
}

View File

@@ -768,7 +768,5 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("Enable", "Habilitar"),
("Reuse one connection for port forwarding", "Reutilizar uma conexão para encaminhamento de portas"),
("port-forward-mux-tip", "Levar todas as conexões de um encaminhamento de portas por uma única conexão com o outro computador, em vez de conectar e fazer login novamente para cada uma."),
("Enable WebRTC P2P connection", "Habilitar conexão WebRTC P2P"),
("Enable TCP hole punching", "Habilitar TCP hole punching"),
].iter().cloned().collect();
}

View File

@@ -768,7 +768,5 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("Enable", "Activează"),
("Reuse one connection for port forwarding", "Reutilizează o singură conexiune pentru redirecționarea porturilor"),
("port-forward-mux-tip", "Trece toate conexiunile unei redirecționări de porturi printr-o singură conexiune către celălalt calculator, în loc să se conecteze și să se autentifice din nou pentru fiecare."),
("Enable WebRTC P2P connection", "Activează conexiunea P2P prin WebRTC"),
("Enable TCP hole punching", "Activează traversarea TCP (hole punching)"),
].iter().cloned().collect();
}

View File

@@ -768,7 +768,5 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("Enable", "Включить"),
("Reuse one connection for port forwarding", "Использовать одно подключение для перенаправления портов"),
("port-forward-mux-tip", "Передавать все соединения одного перенаправления портов через одно подключение к удалённому устройству вместо повторного подключения и входа для каждого из них."),
("Enable WebRTC P2P connection", "Использовать подключение WebRTC P2P"),
("Enable TCP hole punching", "Использовать TCP hole punching"),
].iter().cloned().collect();
}

View File

@@ -768,7 +768,5 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("Enable", "Abìlita"),
("Reuse one connection for port forwarding", "Torra a impreare una connessione pro s'imbiu de is portas"),
("port-forward-mux-tip", "Totu is connessiones de un'imbiu de portas passant in una connessione ebbia a s'àteru computadore, in logu de si connètere e intrare torra pro dontzi una."),
("Enable WebRTC P2P connection", "Abìlita connessione P2P WebRTC"),
("Enable TCP hole punching", "Abìlita s'istampadura TCP"),
].iter().cloned().collect();
}

View File

@@ -768,7 +768,5 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("Enable", "Povoliť"),
("Reuse one connection for port forwarding", "Znovu použiť jedno pripojenie na presmerovanie portov"),
("port-forward-mux-tip", "Vedie všetky pripojenia jedného presmerovania portov cez jediné pripojenie k druhej strane namiesto opakovaného pripájania a prihlasovania pre každé z nich."),
("Enable WebRTC P2P connection", "Povoliť pripojenie WebRTC P2P"),
("Enable TCP hole punching", "Povoliť TCP hole punching"),
].iter().cloned().collect();
}

View File

@@ -768,7 +768,5 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("Enable", "Omogoči"),
("Reuse one connection for port forwarding", "Ponovno uporabi eno povezavo za posredovanje vrat"),
("port-forward-mux-tip", "Vse povezave enega posredovanja vrat potekajo prek ene same povezave do druge strani, namesto ponovnega povezovanja in prijave za vsako od njih."),
("Enable WebRTC P2P connection", "Omogoči povezavo WebRTC P2P"),
("Enable TCP hole punching", "Omogoči preboj lukenj TCP"),
].iter().cloned().collect();
}

View File

@@ -768,7 +768,5 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("Enable", "Aktivizo"),
("Reuse one connection for port forwarding", "Ripërdor një lidhje për përcjelljen e porteve"),
("port-forward-mux-tip", "Të gjitha lidhjet e një përcjelljeje portesh kalojnë përmes një lidhjeje të vetme me kompjuterin tjetër, në vend që të lidhet dhe të hyjë sërish për secilën prej tyre."),
("Enable WebRTC P2P connection", "Aktivizo lidhjen WebRTC P2P"),
("Enable TCP hole punching", "Aktivizo TCP hole punching"),
].iter().cloned().collect();
}

View File

@@ -768,7 +768,5 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("Enable", "Omogući"),
("Reuse one connection for port forwarding", "Ponovo koristi jednu vezu za prosleđivanje portova"),
("port-forward-mux-tip", "Sve veze jednog prosleđivanja portova idu kroz jednu vezu ka drugoj strani, umesto povezivanja i prijavljivanja iznova za svaku od njih."),
("Enable WebRTC P2P connection", "Omogući WebRTC P2P konekciju"),
("Enable TCP hole punching", "Omogući TCP hole punching"),
].iter().cloned().collect();
}

View File

@@ -768,7 +768,5 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("Enable", "Aktivera"),
("Reuse one connection for port forwarding", "Återanvänd en anslutning för portvidarebefordran"),
("port-forward-mux-tip", "Låt alla anslutningar i en portvidarebefordran gå via en enda anslutning till motparten, i stället för att ansluta och logga in på nytt för varje anslutning."),
("Enable WebRTC P2P connection", "Aktivera WebRTC P2P anslutning"),
("Enable TCP hole punching", "Aktivera TCP hålslagning"),
].iter().cloned().collect();
}

View File

@@ -768,7 +768,5 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("Enable", "இயக்கு"),
("Reuse one connection for port forwarding", "போர்ட் ஃபார்வேர்டிங்கிற்கு ஒரே இணைப்பை மீண்டும் பயன்படுத்து"),
("port-forward-mux-tip", "ஒரு போர்ட் ஃபார்வேர்டிங்கின் அனைத்து இணைப்புகளும் மறுமுனைக்கான ஒரே இணைப்பின் வழியாகச் செல்லும், ஒவ்வொன்றுக்கும் மீண்டும் இணைந்து உள்நுழைவதற்குப் பதிலாக."),
("Enable WebRTC P2P connection", "WebRTC P2P இணைப்பு இயக்கு"),
("Enable TCP hole punching", "TCP hole punching இயக்கு"),
].iter().cloned().collect();
}

View File

@@ -768,7 +768,5 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("Enable", ""),
("Reuse one connection for port forwarding", ""),
("port-forward-mux-tip", ""),
("Enable WebRTC P2P connection", ""),
("Enable TCP hole punching", ""),
].iter().cloned().collect();
}

View File

@@ -768,7 +768,5 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("Enable", "เปิดใช้งาน"),
("Reuse one connection for port forwarding", "ใช้การเชื่อมต่อเดียวร่วมกันสำหรับการส่งต่อพอร์ต"),
("port-forward-mux-tip", "ส่งการเชื่อมต่อทั้งหมดของการส่งต่อพอร์ตหนึ่งรายการผ่านการเชื่อมต่อเดียวไปยังอีกฝ่าย แทนการเชื่อมต่อและเข้าสู่ระบบใหม่ทุกครั้ง"),
("Enable WebRTC P2P connection", "เปิดใช้งานการเชื่อมต่อ P2P แบบ WebRTC"),
("Enable TCP hole punching", "เปิดใช้งาน TCP hole punching"),
].iter().cloned().collect();
}

View File

@@ -768,7 +768,5 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("Enable", "Etkinleştir"),
("Reuse one connection for port forwarding", "Port yönlendirme için tek bağlantıyı yeniden kullan"),
("port-forward-mux-tip", "Bir port yönlendirmesindeki tüm bağlantıları, her biri için yeniden bağlanıp oturum açmak yerine karşı tarafa açılan tek bir bağlantı üzerinden taşır."),
("Enable WebRTC P2P connection", "WebRTC P2P bağlantısını etkinleştir"),
("Enable TCP hole punching", "TCP delik açmayı etkinleştir"),
].iter().cloned().collect();
}

View File

@@ -768,7 +768,5 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("Enable", "啟用"),
("Reuse one connection for port forwarding", "連接埠轉送重複使用同一條連線"),
("port-forward-mux-tip", "同一條連接埠轉送規則上的所有連線共用一條到對方的連線,而不是每條連線都重新連線並登入一次。"),
("Enable WebRTC P2P connection", "啟用 WebRTC P2P 連線"),
("Enable TCP hole punching", "啟用 TCP 打洞"),
].iter().cloned().collect();
}

View File

@@ -768,7 +768,5 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("Enable", "Увімкнути"),
("Reuse one connection for port forwarding", "Використовувати одне з'єднання для перенаправлення портів"),
("port-forward-mux-tip", "Передавати всі з'єднання одного перенаправлення портів через одне з'єднання з віддаленим пристроєм замість повторного під'єднання та входу для кожного з них."),
("Enable WebRTC P2P connection", "Увімкнути P2P-підключення через WebRTC"),
("Enable TCP hole punching", "Увімкнути TCP hole punching"),
].iter().cloned().collect();
}

View File

@@ -768,8 +768,6 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("sync-clipboard-between-sessions-tip", "ایک ریموٹ سیشن میں کاپی کیا گیا متن یا تصاویر آپ کے دیگر منسلک سیشنز کے کلپ بورڈ پر بھی بھیجی جاتی ہیں۔"),
("Reuse one connection for port forwarding", "پورٹ فارورڈنگ کے لیے ایک ہی کنکشن دوبارہ استعمال کریں"),
("port-forward-mux-tip", "ایک پورٹ فارورڈنگ کے تمام کنکشن دوسرے کمپیوٹر کے ساتھ بنے ایک ہی کنکشن سے گزرتے ہیں، ہر ایک کے لیے دوبارہ منسلک ہو کر لاگ اِن کرنے کے بجائے۔"),
("Enable WebRTC P2P connection", "WebRTC P2P کنکشن کو فعال کریں"),
("Enable TCP hole punching", "TCP ہول پنچنگ کو فعال کریں"),
].iter().cloned().collect();
}

View File

@@ -768,7 +768,5 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("Enable", "Bật"),
("Reuse one connection for port forwarding", "Dùng chung một kết nối cho chuyển tiếp cổng"),
("port-forward-mux-tip", "Chuyển toàn bộ kết nối của một quy tắc chuyển tiếp cổng qua một kết nối duy nhất tới máy đối phương, thay vì kết nối và đăng nhập lại cho từng kết nối."),
("Enable WebRTC P2P connection", "Cho phép kết nối WebRTC P2P"),
("Enable TCP hole punching", "Bật TCP Hole Punching"),
].iter().cloned().collect();
}

View File

@@ -1,404 +0,0 @@
/*
* getifaddrs()/freeifaddrs() for Android: bionic only exports them from API 24,
* while the jniLibs are built against the API 21 sysroot (flutter/ndk_*.sh) and
* webrtc-util calls them whenever WebRTC gathers ICE candidates.
*
* Only AF_INET and AF_INET6 entries are reported; the AF_PACKET ones the real
* getifaddrs() also returns have no reader in this build.
*/
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <ifaddrs.h>
#include <net/if.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <linux/netlink.h>
#include <linux/rtnetlink.h>
/* Refuse a single netlink datagram larger than this rather than grow forever. */
#define RD_NL_MAX_BUF (1024 * 1024)
/* A dump that never terminates must not hang the caller. */
#define RD_NL_MAX_DATAGRAMS 4096
typedef int (*rd_nl_cb)(struct nlmsghdr *nlh, void *ctx);
struct rd_link_info {
unsigned int index;
unsigned int flags;
char name[IFNAMSIZ + 1];
};
struct rd_link_table {
struct rd_link_info *items;
size_t len;
size_t cap;
};
/* One allocation per reported address; `ifa` first so freeifaddrs() can free
* the node it is handed. */
struct rd_ifaddrs_storage {
struct ifaddrs ifa;
struct sockaddr_storage addr;
struct sockaddr_storage netmask;
struct sockaddr_storage ifu;
char name[IFNAMSIZ + 1];
};
struct rd_addr_ctx {
const struct rd_link_table *links;
struct ifaddrs *head;
struct ifaddrs *tail;
};
static void rd_parse_rtattr(struct rtattr *rta, int len, struct rtattr **tb, int max)
{
memset(tb, 0, sizeof(*tb) * ((size_t)max + 1));
for (; RTA_OK(rta, len); rta = RTA_NEXT(rta, len)) {
if (rta->rta_type <= (unsigned short)max && tb[rta->rta_type] == NULL)
tb[rta->rta_type] = rta;
}
}
/* `len` must stay signed: NLMSG_NEXT subtracts the *aligned* length, which
* overshoots on an unaligned trailing message, and only a negative remainder
* stops NLMSG_OK from reading past the buffer. */
static int rd_nl_parse(char *buf, int len, unsigned short reply_type, unsigned int seq,
rd_nl_cb cb, void *ctx, int *done)
{
struct nlmsghdr *nlh = (struct nlmsghdr *)buf;
for (; NLMSG_OK(nlh, len); nlh = NLMSG_NEXT(nlh, len)) {
if (nlh->nlmsg_seq != seq)
continue;
if (nlh->nlmsg_type == NLMSG_DONE) {
*done = 1;
return 0;
}
if (nlh->nlmsg_type == NLMSG_ERROR) {
struct nlmsgerr *err = (struct nlmsgerr *)NLMSG_DATA(nlh);
if (nlh->nlmsg_len >= NLMSG_LENGTH(sizeof(*err)) && err->error != 0)
errno = -err->error;
else
errno = EIO;
return -1;
}
if (nlh->nlmsg_type != reply_type)
continue;
if (cb(nlh, ctx) != 0)
return -1;
/* A non-multipart reply is the whole answer; nothing follows it. */
if ((nlh->nlmsg_flags & NLM_F_MULTI) == 0) {
*done = 1;
return 0;
}
}
return 0;
}
static int rd_nl_dump(int fd, unsigned short request_type, unsigned short reply_type,
unsigned int seq, rd_nl_cb cb, void *ctx)
{
struct {
struct nlmsghdr nlh;
struct rtgenmsg gen;
} req;
struct sockaddr_nl kernel;
char *buf;
size_t cap = 8192;
int datagrams = 0;
int done = 0;
int rc = -1;
int saved;
memset(&req, 0, sizeof(req));
req.nlh.nlmsg_len = NLMSG_LENGTH(sizeof(req.gen));
req.nlh.nlmsg_type = request_type;
req.nlh.nlmsg_flags = NLM_F_REQUEST | NLM_F_DUMP;
req.nlh.nlmsg_seq = seq;
req.gen.rtgen_family = AF_UNSPEC;
memset(&kernel, 0, sizeof(kernel));
kernel.nl_family = AF_NETLINK;
for (;;) {
if (sendto(fd, &req, req.nlh.nlmsg_len, 0, (struct sockaddr *)&kernel,
sizeof(kernel)) >= 0)
break;
if (errno != EINTR)
return -1;
}
buf = (char *)malloc(cap);
if (buf == NULL) {
errno = ENOMEM;
return -1;
}
while (!done) {
/* MSG_PEEK|MSG_TRUNC reports the datagram's real size, so an
* undersized buffer costs a resize instead of a silent truncation. */
ssize_t n = recv(fd, buf, cap, MSG_PEEK | MSG_TRUNC);
if (n < 0) {
if (errno == EINTR)
continue;
goto out;
}
if ((size_t)n > cap) {
char *grown;
if ((size_t)n > RD_NL_MAX_BUF) {
errno = EMSGSIZE;
goto out;
}
grown = (char *)realloc(buf, (size_t)n);
if (grown == NULL) {
errno = ENOMEM;
goto out;
}
buf = grown;
cap = (size_t)n;
continue;
}
n = recv(fd, buf, cap, 0);
if (n < 0) {
if (errno == EINTR)
continue;
goto out;
}
if (n == 0 || ++datagrams > RD_NL_MAX_DATAGRAMS) {
errno = EIO;
goto out;
}
if (rd_nl_parse(buf, (int)n, reply_type, seq, cb, ctx, &done) != 0)
goto out;
}
rc = 0;
out:
saved = errno;
free(buf);
errno = saved;
return rc;
}
static int rd_link_cb(struct nlmsghdr *nlh, void *ctx)
{
struct rd_link_table *t = (struct rd_link_table *)ctx;
struct ifinfomsg *ifi;
struct rtattr *tb[IFLA_IFNAME + 1];
struct rd_link_info *slot;
int payload;
int namelen;
if (nlh->nlmsg_len < NLMSG_LENGTH(sizeof(*ifi)))
return 0;
ifi = (struct ifinfomsg *)NLMSG_DATA(nlh);
payload = (int)nlh->nlmsg_len - (int)NLMSG_SPACE(sizeof(*ifi));
if (payload < 0)
payload = 0;
rd_parse_rtattr(IFLA_RTA(ifi), payload, tb, IFLA_IFNAME);
/* An interface we cannot name is of no use: callers dereference ifa_name. */
if (tb[IFLA_IFNAME] == NULL || (int)RTA_PAYLOAD(tb[IFLA_IFNAME]) <= 0)
return 0;
if (t->len == t->cap) {
size_t ncap = t->cap ? t->cap * 2 : 16;
struct rd_link_info *items =
(struct rd_link_info *)realloc(t->items, ncap * sizeof(*items));
if (items == NULL) {
errno = ENOMEM;
return -1;
}
t->items = items;
t->cap = ncap;
}
slot = &t->items[t->len];
memset(slot, 0, sizeof(*slot));
slot->index = (unsigned int)ifi->ifi_index;
slot->flags = ifi->ifi_flags;
namelen = (int)RTA_PAYLOAD(tb[IFLA_IFNAME]);
if (namelen > IFNAMSIZ)
namelen = IFNAMSIZ;
memcpy(slot->name, RTA_DATA(tb[IFLA_IFNAME]), (size_t)namelen);
slot->name[namelen] = '\0';
t->len++;
return 0;
}
static const struct rd_link_info *rd_link_find(const struct rd_link_table *t,
unsigned int index)
{
size_t i;
for (i = 0; i < t->len; i++) {
if (t->items[i].index == index)
return &t->items[i];
}
return NULL;
}
static void rd_fill_mask(unsigned char *out, int len, unsigned int prefix)
{
int i;
if (prefix > (unsigned int)len * 8)
prefix = (unsigned int)len * 8;
for (i = 0; i < len; i++) {
if (prefix >= 8) {
out[i] = 0xff;
prefix -= 8;
} else if (prefix > 0) {
out[i] = (unsigned char)(0xff << (8 - prefix));
prefix = 0;
} else {
out[i] = 0;
}
}
}
static void rd_set_in(struct sockaddr_storage *ss, const void *addr)
{
struct sockaddr_in *sin = (struct sockaddr_in *)ss;
sin->sin_family = AF_INET;
memcpy(&sin->sin_addr, addr, 4);
}
static int rd_addr_cb(struct nlmsghdr *nlh, void *ctx)
{
struct rd_addr_ctx *c = (struct rd_addr_ctx *)ctx;
struct ifaddrmsg *ifa;
struct rtattr *tb[IFA_BROADCAST + 1];
struct rtattr *ra;
const struct rd_link_info *link;
struct rd_ifaddrs_storage *st;
int payload;
if (nlh->nlmsg_len < NLMSG_LENGTH(sizeof(*ifa)))
return 0;
ifa = (struct ifaddrmsg *)NLMSG_DATA(nlh);
if (ifa->ifa_family != AF_INET && ifa->ifa_family != AF_INET6)
return 0;
/* Without the link entry there is no name, and callers deref ifa_name. */
link = rd_link_find(c->links, ifa->ifa_index);
if (link == NULL)
return 0;
payload = (int)nlh->nlmsg_len - (int)NLMSG_SPACE(sizeof(*ifa));
if (payload < 0)
payload = 0;
rd_parse_rtattr(IFA_RTA(ifa), payload, tb, IFA_BROADCAST);
/* On a point-to-point link IFA_ADDRESS holds the peer and IFA_LOCAL the
* local address; ipv6 only ever sets IFA_ADDRESS. */
if (ifa->ifa_family == AF_INET)
ra = tb[IFA_LOCAL] ? tb[IFA_LOCAL] : tb[IFA_ADDRESS];
else
ra = tb[IFA_ADDRESS] ? tb[IFA_ADDRESS] : tb[IFA_LOCAL];
if (ra == NULL)
return 0;
if ((int)RTA_PAYLOAD(ra) < (ifa->ifa_family == AF_INET ? 4 : 16))
return 0;
st = (struct rd_ifaddrs_storage *)calloc(1, sizeof(*st));
if (st == NULL) {
errno = ENOMEM;
return -1;
}
memcpy(st->name, link->name, sizeof(st->name));
st->ifa.ifa_name = st->name;
st->ifa.ifa_flags = link->flags;
st->ifa.ifa_addr = (struct sockaddr *)&st->addr;
st->ifa.ifa_netmask = (struct sockaddr *)&st->netmask;
if (ifa->ifa_family == AF_INET) {
struct sockaddr_in *mask = (struct sockaddr_in *)&st->netmask;
rd_set_in(&st->addr, RTA_DATA(ra));
mask->sin_family = AF_INET;
rd_fill_mask((unsigned char *)&mask->sin_addr, 4, ifa->ifa_prefixlen);
if ((link->flags & IFF_POINTOPOINT) && tb[IFA_ADDRESS] && tb[IFA_LOCAL] &&
(int)RTA_PAYLOAD(tb[IFA_ADDRESS]) >= 4 &&
memcmp(RTA_DATA(tb[IFA_ADDRESS]), RTA_DATA(tb[IFA_LOCAL]), 4) != 0) {
rd_set_in(&st->ifu, RTA_DATA(tb[IFA_ADDRESS]));
st->ifa.ifa_dstaddr = (struct sockaddr *)&st->ifu;
} else if (tb[IFA_BROADCAST] && (int)RTA_PAYLOAD(tb[IFA_BROADCAST]) >= 4) {
rd_set_in(&st->ifu, RTA_DATA(tb[IFA_BROADCAST]));
st->ifa.ifa_broadaddr = (struct sockaddr *)&st->ifu;
}
} else {
struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)&st->addr;
struct sockaddr_in6 *mask = (struct sockaddr_in6 *)&st->netmask;
sin6->sin6_family = AF_INET6;
memcpy(&sin6->sin6_addr, RTA_DATA(ra), 16);
/* A link-local address is not routable without its scope id. */
if (IN6_IS_ADDR_LINKLOCAL(&sin6->sin6_addr) ||
IN6_IS_ADDR_MC_LINKLOCAL(&sin6->sin6_addr))
sin6->sin6_scope_id = ifa->ifa_index;
mask->sin6_family = AF_INET6;
rd_fill_mask((unsigned char *)&mask->sin6_addr, 16, ifa->ifa_prefixlen);
}
if (c->tail != NULL)
c->tail->ifa_next = &st->ifa;
else
c->head = &st->ifa;
c->tail = &st->ifa;
return 0;
}
void freeifaddrs(struct ifaddrs *ifa)
{
while (ifa != NULL) {
struct ifaddrs *next = ifa->ifa_next;
free(ifa);
ifa = next;
}
}
int getifaddrs(struct ifaddrs **ifap)
{
struct rd_link_table links;
struct rd_addr_ctx ctx;
int fd;
int saved;
if (ifap == NULL) {
errno = EINVAL;
return -1;
}
*ifap = NULL;
memset(&links, 0, sizeof(links));
memset(&ctx, 0, sizeof(ctx));
ctx.links = &links;
fd = socket(AF_NETLINK, SOCK_RAW | SOCK_CLOEXEC, NETLINK_ROUTE);
if (fd < 0)
return -1;
if (rd_nl_dump(fd, RTM_GETLINK, RTM_NEWLINK, 1, rd_link_cb, &links) != 0)
goto fail;
if (rd_nl_dump(fd, RTM_GETADDR, RTM_NEWADDR, 2, rd_addr_cb, &ctx) != 0)
goto fail;
close(fd);
free(links.items);
*ifap = ctx.head;
return 0;
fail:
saved = errno;
close(fd);
free(links.items);
freeifaddrs(ctx.head);
errno = saved;
return -1;
}

View File

@@ -1,6 +1,4 @@
use std::{
collections::{hash_map::RandomState, HashMap, VecDeque},
hash::BuildHasher,
net::SocketAddr,
sync::{
atomic::{AtomicBool, Ordering},
@@ -23,13 +21,8 @@ use hbb_common::{
rendezvous_proto::*,
sleep,
socket_client::{self, connect_tcp, is_ipv4, new_direct_udp_for, new_udp_for},
tokio::{
self, select,
sync::{mpsc, Mutex},
time::interval,
},
tokio::{self, select, sync::Mutex, time::interval},
udp::FramedSocket,
webrtc::WebRTCStream,
AddrMangle, IntoTargetAddr, ResultType, Stream, TargetAddr,
};
@@ -54,66 +47,7 @@ lazy_static::lazy_static! {
static ref SOLVING_PK_MISMATCH: Mutex<String> = Default::default();
static ref LAST_MSG: Mutex<(SocketAddr, Instant)> = Mutex::new((SocketAddr::new([0; 4].into(), 0), Instant::now()));
static ref LAST_RELAY_MSG: Mutex<(SocketAddr, Instant)> = Mutex::new((SocketAddr::new([0; 4].into(), 0), Instant::now()));
static ref WEBRTC_ICE_TXS: Mutex<HashMap<String, IceRoute>> = Default::default();
static ref ICE_DIGEST_STATE: RandomState = Default::default();
}
/// Remote ICE candidates buffered per session while the answerer applies them. Same depth as the
/// controller's own buffer (`Client::MAX_PENDING_WEBRTC_ICE`), though that one evicts its oldest
/// where a full channel here refuses the newest.
const MAX_PENDING_REMOTE_ICE: usize = 64;
/// Queued candidates remembered so the controller's re-send is skipped instead of taking a slot
/// of its own. Far more than an honest peer gathers, at eight bytes each.
const ICE_DEDUP_WINDOW: usize = 256;
// The rendezvous ICE route is reachable without a prior punch and the peer decides how many
// candidates it sends, so these sites would let someone else set how much this machine writes to
// its log file. One line a minute each, carrying the suppressed count.
const ICE_LOG_INTERVAL: std::time::Duration = std::time::Duration::from_secs(60);
static UNKNOWN_ICE_SESSION_LOG: hbb_common::log_throttle::LogThrottle =
hbb_common::log_throttle::LogThrottle::new(ICE_LOG_INTERVAL);
static REJECTED_REMOTE_ICE_LOG: hbb_common::log_throttle::LogThrottle =
hbb_common::log_throttle::LogThrottle::new(ICE_LOG_INTERVAL);
static FULL_ICE_QUEUE_LOG: hbb_common::log_throttle::LogThrottle =
hbb_common::log_throttle::LogThrottle::new(ICE_LOG_INTERVAL);
struct IceRoute {
tx: mpsc::Sender<String>,
recent: VecDeque<u64>,
}
impl IceRoute {
fn new(tx: mpsc::Sender<String>) -> Self {
Self {
tx,
recent: VecDeque::new(),
}
}
/// Keeps `queue` the only way onto the channel, so nothing reaches it unrecorded.
fn is_same_channel(&self, other: &mpsc::Sender<String>) -> bool {
self.tx.same_channel(other)
}
/// Skip the controller's re-send of a candidate already queued: the ICE agent that dedups
/// repeats is downstream of this queue, so the copy would spend a slot of its own.
/// False means the candidate was dropped.
fn queue(&mut self, candidate: String) -> bool {
let digest = ICE_DIGEST_STATE.hash_one(candidate.as_str());
if self.recent.contains(&digest) {
// Only honest about the drop if the route is still alive to have taken it.
return !self.tx.is_closed();
}
// Recorded once queued, never before: a refused candidate stays repairable by the re-send.
if self.tx.try_send(candidate).is_err() {
return false;
}
if self.recent.len() >= ICE_DEDUP_WINDOW {
self.recent.pop_front();
}
self.recent.push_back(digest);
true
}
}
static SHOULD_EXIT: AtomicBool = AtomicBool::new(false);
static MANUAL_RESTARTED: AtomicBool = AtomicBool::new(false);
static SENT_REGISTER_PK: AtomicBool = AtomicBool::new(false);
@@ -465,30 +399,6 @@ impl RendezvousMediator {
allow_err!(rz.handle_intranet(fla, server).await);
});
}
Some(rendezvous_message::Union::IceCandidate(ice)) => {
let queued = {
let mut txs = WEBRTC_ICE_TXS.lock().await;
txs.get_mut(&ice.session_key)
.map(|route| route.queue(ice.candidate))
};
match queued {
Some(false) => {
if let Some(n) = FULL_ICE_QUEUE_LOG.due() {
log::debug!("dropped {} ICE candidate(s): queue full or closed", n);
}
}
None => {
if let Some(n) = UNKNOWN_ICE_SESSION_LOG.due() {
log::debug!(
"dropped {} ICE candidate(s) for unknown WebRTC session key, last: {}",
n,
ice.session_key
);
}
}
_ => {}
}
}
Some(rendezvous_message::Union::ConfigureUpdate(cu)) => {
let v0 = Config::get_rendezvous_servers();
Config::set_option(
@@ -598,7 +508,6 @@ impl RendezvousMediator {
rr.secure,
false,
Default::default(),
String::new(),
meta,
)
.await
@@ -613,7 +522,6 @@ impl RendezvousMediator {
secure: bool,
initiate: bool,
socket_addr_v6: bytes::Bytes,
webrtc_sdp_answer: String,
meta: ConnectionMeta,
) -> ResultType<()> {
let peer_addr = AddrMangle::decode(&socket_addr);
@@ -632,7 +540,6 @@ impl RendezvousMediator {
socket_addr: socket_addr.into(),
version: crate::VERSION.to_owned(),
socket_addr_v6,
webrtc_sdp_answer,
..Default::default()
};
if initiate {
@@ -699,7 +606,6 @@ impl RendezvousMediator {
true,
true,
socket_addr_v6,
String::new(),
meta,
)
.await
@@ -736,163 +642,6 @@ impl RendezvousMediator {
Ok(())
}
/// Build the WebRTC answerer for a punch-hole offer and return the SDP answer that rides in
/// the punch reply (PunchHoleSent / RelayResponse).
///
/// Awaited inline on the punch-reply path, which only holds because everything here is local
/// (pc + keygen + SDP; trickle means the answer carries no candidates). Keep network I/O out
/// — connection setup belongs in the detached task below.
async fn spawn_webrtc_answerer(
&self,
ph: &PunchHole,
relay_only_ice: bool,
server: ServerPtr,
peer_addr: SocketAddr,
meta: ConnectionMeta,
) -> ResultType<String> {
let mut stream =
WebRTCStream::new(&ph.webrtc_sdp_offer, relay_only_ice, CONNECT_TIMEOUT).await?;
let answer = stream.local_endpoint().to_owned();
let session_key = stream.session_key().to_owned();
let return_route = ph.socket_addr.clone();
// A duplicate PunchHole (the offerer re-sends the same request across punch attempts)
// resolves to the SESSIONS-cached stream. `take_local_ice_rx` yields the receiver
// exactly once per stream instance, so `None` here means an answerer was already
// spawned for this offer: return the (identical) cached answer without spawning a
// second connect task. Otherwise two `create_tcp_connection` tasks would detach and
// read the same data channel, interleaving the handshake and corrupting the session.
let Some(mut local_ice_rx) = stream.take_local_ice_rx() else {
return Ok(answer);
};
// Bounded: how many candidates arrive is the sender's choice, while draining one costs a
// JSON parse and the ICE agent's lock, so an unbounded queue lets whoever can reach this
// session's route grow it without limit inside a long-lived service process. A full queue
// drops the newest candidate, and the controller re-sends it once — the digests beside the
// sender are what keep that re-send from spending a slot of its own.
let (remote_ice_tx, mut remote_ice_rx) = mpsc::channel::<String>(MAX_PENDING_REMOTE_ICE);
let own_ice_tx = remote_ice_tx.clone();
WEBRTC_ICE_TXS
.lock()
.await
.insert(session_key.clone(), IceRoute::new(remote_ice_tx));
let stream_for_remote_ice = stream.clone();
tokio::spawn(async move {
while let Some(candidate) = remote_ice_rx.recv().await {
if let Err(err) = stream_for_remote_ice.add_remote_ice_candidate(&candidate).await
{
if let Some(n) = REJECTED_REMOTE_ICE_LOG.due() {
log::warn!(
"failed to add {} remote WebRTC ICE candidate(s), last: {}",
n,
err
);
}
}
}
});
{
let host = self.host.clone();
let socket_addr = return_route.clone();
let session_key_for_ice = session_key.clone();
tokio::spawn(async move {
// Candidates ride a dedicated TCP connection to the rendezvous server, like
// the answer, NOT the mediator channel: that channel is UDP in the default
// setup, and target deployments front hbbs with websocket/TCP only, where
// its UDP port is unreachable. The server keeps candidate-carrying TCP
// connections open, so one lazily-opened connection serves the whole
// trickle, and TCP reliability replaces the old 400ms duplicate re-send
// (the controller keeps its own re-send for the server->peer UDP downlink).
let mut conn = None;
while let Some(candidate) = local_ice_rx.recv().await {
let mut msg = Message::new();
msg.set_ice_candidate(IceCandidate {
socket_addr: socket_addr.clone(),
session_key: session_key_for_ice.clone(),
candidate,
..Default::default()
});
// One reconnect attempt per candidate: the first send after an hbbs
// restart or an idle-killed connection fails on the stale stream.
for _ in 0..2 {
if conn.is_none() {
match connect_tcp(&*host, CONNECT_TIMEOUT).await {
Ok(s) => conn = Some(s),
Err(err) => {
log::warn!(
"failed to connect for WebRTC ICE candidate: {}",
err
);
break;
}
}
}
if let Some(s) = conn.as_mut() {
match s.send(&msg).await {
Ok(()) => break,
Err(err) => {
log::debug!(
"WebRTC ICE candidate send failed, reconnecting: {}",
err
);
conn = None;
}
}
}
}
}
});
}
let session_key_for_cleanup = session_key.clone();
tokio::spawn(async move {
let result = stream.wait_connected(CONNECT_TIMEOUT).await;
// Only evict our own route. The key is the offer's DTLS fingerprint, identical across
// the controller's punch retries, so a retry that built a fresh answerer has already
// replaced this entry — removing it blindly would delete the live session's sender and
// leave it receiving no candidates at all.
{
let mut txs = WEBRTC_ICE_TXS.lock().await;
if txs
.get(&session_key_for_cleanup)
.is_some_and(|route| route.is_same_channel(&own_ice_tx))
{
txs.remove(&session_key_for_cleanup);
}
}
if let Err(err) = result {
log::warn!("webrtc wait_connected failed: {}", err);
// Release the pc now rather than waiting for the ICE agent to time out into a
// terminal state (~30s); this also drops the SESSIONS entry promptly.
stream.close().await;
return;
}
// create_tcp_connection takes ownership of the stream; keep a handle to close the pc
// once the session returns. It runs the whole session and returns Ok on normal end,
// Err on setup failure — either way the pc must be closed, else it lingers forever in
// SESSIONS (its state handler only fires on a terminal ICE state, which a cleanly
// closed session may never reach) leaking the pc, channels, and socket fds.
let stream_for_cleanup = stream.clone();
if let Err(err) = crate::server::create_tcp_connection(
server,
Stream::WebRTC(stream),
peer_addr,
true,
meta,
)
.await
{
log::warn!("failed to create WebRTC server connection: {}", err);
}
stream_for_cleanup.close().await;
});
Ok(answer)
}
async fn handle_punch_hole(&self, ph: PunchHole, server: ServerPtr) -> ResultType<()> {
let mut peer_addr = AddrMangle::decode(&ph.socket_addr);
let last = *LAST_MSG.lock().await;
@@ -902,52 +651,18 @@ impl RendezvousMediator {
return Ok(());
}
let peer_addr_v6 = hbb_common::AddrMangle::decode(&ph.socket_addr_v6);
let local_proxy = use_ws() || Config::is_proxy();
let relay = local_proxy || ph.force_relay;
let relay = use_ws() || Config::is_proxy() || ph.force_relay;
let mut socket_addr_v6 = Default::default();
let meta = connection_meta(
ph.control_permissions.clone().into_option(),
ph.controlled_context.clone().into_option(),
ph.control_permissions.into_option(),
ph.controlled_context.into_option(),
);
// The controller's force_relay alone does not say whether ICE must be Relay-only; its
// offer envelope does. `ice_policy: "all"` means the relay was forced by the transport
// (ws), so answer with full ICE and let a direct pair form.
let webrtc_relay_only =
ph.force_relay && !WebRTCStream::endpoint_declares_all_ice(&ph.webrtc_sdp_offer);
// No enable-webrtc check here: it is LocalConfig, which the UI process writes and never
// syncs over IPC, so this (server) process would read the private-server default of "N"
// and refuse to answer in exactly the self-hosted deployments the transport is for.
// A proxy still rules it out — ICE would bypass it and leak the real IP.
let webrtc_viable = !ph.webrtc_sdp_offer.is_empty()
&& !Config::is_proxy()
&& (!webrtc_relay_only || WebRTCStream::has_turn_server());
let webrtc_sdp_answer = if webrtc_viable {
self.spawn_webrtc_answerer(
&ph,
webrtc_relay_only,
server.clone(),
peer_addr,
meta.clone(),
)
.await
.unwrap_or_else(|err| {
log::warn!("failed to create WebRTC answer: {}", err);
String::new()
})
} else {
String::new()
};
if peer_addr_v6.port() > 0 && !relay {
socket_addr_v6 =
start_ipv6(peer_addr_v6, peer_addr, server.clone(), meta.clone()).await;
}
let relay_server = self.get_relay_server(ph.relay_server);
// for ensure, websocket go relay directly
// A symmetric NAT relays the legacy transports but deliberately not WebRTC: the answer
// built above rides along on the relay request, and ICE probes the candidate pairs rather
// than trusting this classification, so a direct WebRTC pair can still form on a
// connection this branch has already called relay-only. Do not gate the answerer on
// nat_type to make the two agree.
if ph.nat_type.enum_value() == Ok(NatType::SYMMETRIC)
|| Config::get_nat_type() == NatType::SYMMETRIC as i32
|| relay
@@ -963,7 +678,6 @@ impl RendezvousMediator {
true,
true,
socket_addr_v6.clone(),
webrtc_sdp_answer.clone(),
meta,
)
.await;
@@ -977,7 +691,6 @@ impl RendezvousMediator {
nat_type: nat_type.into(),
version: crate::VERSION.to_owned(),
socket_addr_v6,
webrtc_sdp_answer,
..Default::default()
};
if ph.udp_port > 0 {
@@ -986,25 +699,12 @@ impl RendezvousMediator {
.await?;
return Ok(());
}
if !ph.webrtc_sdp_offer.is_empty() {
// Return the answer over its own short-lived TCP connection rather than the mediator
// channel: that channel is UDP by default, and hbbs applies UDP-punch semantics
// (source-address observation) to a PunchHoleSent that arrives on it. No TCP punch
// is made — the controller keeps its request socket for trickled ICE.
let mut msg_out = Message::new();
msg_out.set_punch_hole_sent(msg_punch);
let mut socket = connect_tcp(&*self.host, CONNECT_TIMEOUT).await?;
socket.send(&msg_out).await?;
return Ok(());
}
log::debug!("Punch tcp hole to {:?}", peer_addr);
let mut socket = {
let socket = connect_tcp(&*self.host, CONNECT_TIMEOUT).await?;
let local_addr = socket.local_addr();
// key important here for punch hole to tell my gateway incoming peer is safe.
// Awaited rather than spawned so the mapping exists before `PunchHoleSent` goes out;
// `local_addr` itself is shared, not exclusive - every socket here binds it with the
// reuse flags `new_socket` sets.
// it can not be async here, because local_addr can not be reused, we must close the connection before use it again.
allow_err!(socket_client::connect_tcp_local(peer_addr, Some(local_addr), 30).await);
socket
};
@@ -1012,10 +712,7 @@ impl RendezvousMediator {
msg_out.set_punch_hole_sent(msg_punch);
let bytes = msg_out.write_to_bytes()?;
socket.send_raw(bytes).await?;
let local_addr = socket.local_addr();
// The listener inside takes this address over, so the mediator's socket goes first.
drop(socket);
punch_tcp_until_connected(server, peer_addr, local_addr, meta).await;
crate::accept_connection(server.clone(), socket, peer_addr, true, meta).await;
Ok(())
}
@@ -1254,11 +951,11 @@ async fn udp_nat_listen(
let socket_cloned = socket.clone();
let func = async {
socket.connect(peer_addr).await?;
let init_packet = crate::punch_udp(socket.clone(), true).await?;
let res = crate::punch_udp(socket.clone(), true).await?;
let stream = crate::kcp_stream::KcpStream::accept(
socket,
Duration::from_millis(CONNECT_TIMEOUT as _),
init_packet,
res,
)
.await?;
crate::server::create_tcp_connection(server, stream.1, peer_addr_v4, true, meta).await?;
@@ -1274,194 +971,6 @@ async fn udp_nat_listen(
Ok(())
}
/// Where the repeats start, and the factor they slow by. The controller's SYN arrives once, at an
/// instant we are never told, inside a window we are not told either: `Client::connect` sizes its
/// 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, as
/// little as a second once one has. So the repeats cover our own ceiling instead, `CONNECT_TIMEOUT`,
/// which is as long as the accept below has always been willing to take a connection, 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.
const PUNCH_INTERVAL: f32 = 0.15;
const PUNCH_BACKOFF: f32 = 1.5;
const PUNCH_MAX_INTERVAL: f32 = 2.0;
/// How long a punch in flight may run past the deadline, and the only timer it runs on. A punch
/// is cancel-safe while it is still in SYN_SENT and not once the controller's SYN has crossed it:
/// the socket is then half way through a handshake, and dropping it there cuts the connection the
/// controller is opening - which its `connect` has already returned, so that attempt fails
/// outright rather than falling back to relay. A timer cannot tell the two states apart, so no
/// punch is cut on a schedule of its own, and none needs to be. A gateway that answers with RST
/// fails the connect at once, and the loop punches again. One that drops the SYN in silence
/// leaves the socket in SYN_SENT, where it holds the mapping open and the kernel re-sends the
/// SYN, and any SYN of the controller's that arrives crosses it - a second punch has nothing to
/// add. That leaves the deadline, and this much past it lets a crossing begun just before it
/// complete; Windows gives a SYN up at about 21s anyway.
const PUNCH_GRACE: u64 = 3000;
/// The punch above 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 below waiting on
/// a hole that no longer exists. Punching again across the window in which the controller dials
/// rebuilds it, and once the controller sits in SYN_SENT one of those punches meets its SYN and
/// completes as a simultaneous open: a second way in, which a single punch never had.
async fn punch_tcp_until_connected(
server: ServerPtr,
peer_addr: SocketAddr,
local_addr: SocketAddr,
meta: ConnectionMeta,
) {
use hbb_common::tcp::new_listener;
// Shadows the module's `std::time::Instant`: the deadline is held against tokio's sleeps and
// timeouts, so it runs on their clock.
use hbb_common::tokio::time::Instant;
// Not fatal on its own - the punch below can still meet the controller's SYN without it, and
// that half is the one a listener the OS refused to bind could not have covered anyway.
let listener = match new_listener(local_addr, true).await {
Ok(listener) => {
log::info!("Server listening on: {local_addr}");
Some(listener)
}
Err(err) => {
log::warn!("Failed to listen on {local_addr} after punching: {err}");
None
}
};
// Bounds both halves: the punch keeps the mapping open only while the accept is still
// willing to take a connection through it.
let until = Instant::now() + Duration::from_millis(CONNECT_TIMEOUT);
let punch = punch_until(until, peer_addr, |ms| {
socket_client::connect_tcp_local(peer_addr, Some(local_addr), ms)
});
let Some(listener) = listener else {
if let Some(stream) = punch.await {
serve_punched(server, stream, peer_addr, meta).await;
}
return;
};
// Accepting in a loop, not once: a transient `accept` error must not spend the whole window
// the controller still has to arrive in.
let accept = async {
loop {
let left = until.saturating_duration_since(Instant::now()).as_millis() as u64;
if left == 0 {
break;
}
match hbb_common::timeout(left, listener.accept()).await {
// Not filtered by address, as `accept_connection` never did: hbbs saw the
// controller through one mapping and a NAT that pools its external addresses may
// dial us from another, and what keeps `meta`'s control permissions from a second
// peer is the handshake, plus that exactly one connection is ever served.
Ok(Ok(accepted)) => return Some(accepted),
Ok(Err(err)) => {
log::warn!("Failed to accept from {peer_addr}: {err}");
// One that persists - EMFILE, say - would otherwise spin here for the window.
sleep(1.).await;
}
Err(_) => break,
}
}
log::info!("Nothing connected to the hole punched to {peer_addr}");
None
};
// Only the accept races the punch. Racing `accept_connection` instead would race the whole
// session it goes on to run, so a punch landing mid-session would tear that session down.
//
// Whichever arrives first is the one connection this request produces. Serving the loser too
// would give a second peer the control permissions hbbs granted for this one controller, and
// no test on the connection itself can tell the two apart before `create_tcp_connection` has
// spoken to it - so the invariant is kept here, by there being no second serve.
let punched = select! {
// Both ready at once is two connections, not one seen twice - a crossing carries the
// punch's four-tuple, which the listener never matches - and the punch is the one kept:
// it is known to have met something at the address hbbs gave, where the accept takes
// any address, and dropping it would reset the connection the controller is opening.
biased;
Some(stream) = punch => stream,
Some((stream, addr)) = accept => {
return accept_punched_connection(server, stream, addr, meta).await;
}
else => return,
};
serve_punched(server, punched, peer_addr, meta).await;
}
/// The repeats of `punch_tcp_until_connected`, over any punch rather than `connect_tcp_local`
/// alone, so that a test can run the schedule against a paused clock - which no socket can be.
async fn punch_until<T, F, Fut>(
until: tokio::time::Instant,
peer_addr: SocketAddr,
mut punch: F,
) -> Option<T>
where
F: FnMut(u64) -> Fut,
Fut: std::future::Future<Output = ResultType<T>>,
{
use hbb_common::tokio::time::Instant;
let mut interval = PUNCH_INTERVAL;
let mut round = 0;
loop {
// The deadline decides whether another punch starts, never how long one already in
// flight may take: that one runs to PUNCH_GRACE past it.
let left = until.saturating_duration_since(Instant::now());
if left.is_zero() {
log::debug!("None of {round} punches to {peer_addr} was met");
return None;
}
// Cut at the deadline rather than slept out past it, so the window ends on a punch and
// not on a gap of up to PUNCH_MAX_INTERVAL: the controller's window opened after ours,
// on the PunchHoleSent hbbs relayed, so one as long as ours is still open through our tail.
tokio::time::sleep(Duration::from_secs_f32(interval).min(left)).await;
interval = (interval * PUNCH_BACKOFF).min(PUNCH_MAX_INTERVAL);
let ms = until.saturating_duration_since(Instant::now()).as_millis() as u64 + PUNCH_GRACE;
match punch(ms).await {
// The controller's SYN crossed this punch, so the stream is the connection it
// dialed, not a spare one: dropping it would reset that connection.
Ok(stream) => return Some(stream),
// Not logged one by one, but the count says which gateway it was: RST fails a
// punch at once and fits a dozen into the window, a silent drop holds the one
// punch for the whole of it. `connect_tcp_local` keeps no errno anyway.
Err(_) => round += 1,
}
}
}
async fn serve_punched(
server: ServerPtr,
stream: Stream,
peer_addr: SocketAddr,
meta: ConnectionMeta,
) {
log::info!("Punched tcp hole to {peer_addr}, connected on the punch itself");
if let Err(err) =
crate::server::create_tcp_connection(server, stream, peer_addr, true, meta).await
{
log::warn!("Failed to serve the connection punched to {peer_addr}: {err}");
}
}
/// The accept half of `accept_connection`, kept here because only the accept may race the punch.
async fn accept_punched_connection(
server: ServerPtr,
stream: tokio::net::TcpStream,
addr: SocketAddr,
meta: ConnectionMeta,
) {
use crate::server::create_tcp_connection;
stream.set_nodelay(true).ok();
match stream.local_addr() {
Ok(stream_addr) => {
let stream = Stream::from(stream, stream_addr);
if let Err(err) = create_tcp_connection(server, stream, addr, true, meta).await {
log::warn!("Failed to serve the connection from {addr}: {err}");
}
}
Err(err) => log::warn!("Failed to read the address accepted from {addr}: {err}"),
}
}
// When config is not yet synced from root, register_pk may have already been sent with a new generated pk.
// After config sync completes, the pk may change. This struct detects pk changes and triggers
// a re-registration by setting key_confirmed to false.
@@ -1486,255 +995,3 @@ impl Drop for CheckIfResendPk {
}
}
}
#[cfg(test)]
mod tests {
use super::{mpsc, socket_client, tokio, IceRoute, ICE_DEDUP_WINDOW, MAX_PENDING_REMOTE_ICE};
use hbb_common::tcp::new_listener;
use std::net::SocketAddr;
// A SOCKS proxy makes `connect_tcp_local` dial the proxy and ignore the local address, so
// nothing these two assert can hold. Read once, from the same global config production reads.
fn proxied() -> bool {
hbb_common::config::Config::get_socks().is_some()
}
/// Both held while their addresses are read, so the pair cannot be the same port - which
/// `SO_REUSEPORT` would let bind twice rather than refuse, leaving the tests degenerate.
async fn free_loopback_pair() -> (SocketAddr, SocketAddr) {
let (a, b) = (
tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(),
tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(),
);
(a.local_addr().unwrap(), b.local_addr().unwrap())
}
fn queue(route: &mut IceRoute, candidate: &str) -> bool {
route.queue(candidate.to_owned())
}
#[test]
fn the_re_sent_copy_does_not_spend_a_queue_slot() {
// Two slots, three sends: without the dedup the re-send takes the second and "relay",
// the one that traverses NAT, is the one refused.
let (tx, mut rx) = mpsc::channel::<String>(2);
let mut route = IceRoute::new(tx);
for _ in 0..2 {
assert!(queue(&mut route, "host"));
}
assert!(queue(&mut route, "relay"));
let mut queued = Vec::new();
while let Ok(candidate) = rx.try_recv() {
queued.push(candidate);
}
assert_eq!(queued, vec!["host".to_owned(), "relay".to_owned()]);
}
#[test]
fn a_candidate_the_full_queue_refused_is_not_remembered() {
let (tx, mut rx) = mpsc::channel::<String>(1);
let mut route = IceRoute::new(tx);
assert!(queue(&mut route, "host"));
assert!(!queue(&mut route, "relay"));
// The re-send is the only repair for a refused candidate; remembering it would swallow it.
assert_eq!(rx.try_recv().ok(), Some("host".to_owned()));
assert!(queue(&mut route, "relay"));
assert_eq!(rx.try_recv().ok(), Some("relay".to_owned()));
}
#[test]
fn a_re_send_is_skipped_while_the_original_is_still_queued() {
let (tx, mut rx) = mpsc::channel::<String>(MAX_PENDING_REMOTE_ICE);
let mut route = IceRoute::new(tx);
for i in 0..MAX_PENDING_REMOTE_ICE {
assert!(queue(&mut route, &format!("candidate-{}", i)));
}
assert!(queue(&mut route, "candidate-0"));
let mut queued = 0;
while rx.try_recv().is_ok() {
queued += 1;
}
assert_eq!(queued, MAX_PENDING_REMOTE_ICE);
}
#[test]
fn the_window_forgets_in_arrival_order() {
let (tx, mut rx) = mpsc::channel::<String>(MAX_PENDING_REMOTE_ICE);
let mut route = IceRoute::new(tx);
for i in 0..=ICE_DEDUP_WINDOW {
assert!(queue(&mut route, &format!("candidate-{}", i)));
assert!(rx.try_recv().is_ok());
}
// The oldest digest made room for the newest, so its re-send is admitted again.
assert!(queue(&mut route, "candidate-0"));
assert!(rx.try_recv().is_ok());
// A recent one is still skipped.
let recent = format!("candidate-{}", ICE_DEDUP_WINDOW);
assert!(queue(&mut route, &recent));
assert!(rx.try_recv().is_err());
}
// The second way in that the repeat punch opens: a punch reaching a peer already in SYN_SENT
// is answered by that socket rather than reset, and the two ends come up on one connection.
// A punch that misses the crossing is reset outright here, loopback having no NAT to absorb
// it and no round trip to hide behind - so a single punch lands only by luck, and repeating
// is what makes it land at all. That is the premise of the repeat, asserted directly. A round
// that misses costs one loopback RST, so rounds are cheap and there are many.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn a_punch_that_meets_the_peers_syn_connects_both_ends() {
// The crossing needs both connects genuinely in flight at once. Loopback answers a SYN to
// a port nobody is listening on with an instant RST, so on one CPU the first connect runs
// to completion before the second is scheduled and no round can ever cross - a property of
// the box, which this test cannot tell apart from a broken punch.
if proxied() || std::thread::available_parallelism().map_or(true, |cpus| cpus.get() < 2) {
return;
}
for _ in 0..256 {
let (a, b) = free_loopback_pair().await;
// Held for the whole crossing, because production always has one here and the design
// rests on which of the two the kernel hands the connection to: the punch and the
// peer's SYN share a four-tuple exactly, the listener only matches the address, and
// the punch has to win that or every crossing would be swallowed as a plain accept.
let listener = new_listener(a, true).await.unwrap();
let to_b = tokio::spawn(socket_client::connect_tcp_local(b, Some(a), 3000));
let to_a = tokio::spawn(socket_client::connect_tcp_local(a, Some(b), 3000));
let (at_a, at_b) = tokio::join!(to_b, to_a);
let (Ok(Ok(mut at_a)), Ok(Ok(mut at_b))) = (at_a, at_b) else {
continue;
};
at_a.send_bytes(bytes::Bytes::from_static(b"punch"))
.await
.unwrap();
let got = at_b.next_timeout(3000).await.unwrap().unwrap();
assert_eq!(&got[..], b"punch", "both ends must share one connection");
assert!(
hbb_common::timeout(200, listener.accept()).await.is_err(),
"the crossing must reach the punch, not be accepted as an inbound connection"
);
return;
}
panic!("no punch met the peer's SYN in 256 rounds on a machine that can cross them");
}
// The punch binds the address the listener already holds, so it has to go through the same
// `connect_tcp_local` production uses - a punch built by hand here would still pass if
// `new_socket` ever stopped setting the reuse flags, while every real punch failed to bind.
// The peer's view of the source port is what proves the bind took: a fallback to an ephemeral
// one would connect just as happily.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn a_punch_binds_the_address_the_listener_holds() {
if proxied() {
return;
}
// `free_loopback_pair` hands back ports it no longer holds, so another process can take
// one in between; retry rather than fail for something the punch had no part in.
for _ in 0..8 {
let (local, peer_addr) = free_loopback_pair().await;
let (Ok(listener), Ok(peer)) = (
new_listener(local, true).await,
new_listener(peer_addr, true).await,
) else {
continue;
};
let punch = tokio::spawn(socket_client::connect_tcp_local(
peer_addr,
Some(local),
1500,
));
let (_peer_side, seen_as) = hbb_common::timeout(3000, peer.accept())
.await
.expect("the punch must reach the peer")
.unwrap();
assert_eq!(
seen_as.port(),
local.port(),
"the punch must leave from the address the listener holds, not an ephemeral one"
);
// Held, not asserted and dropped: the coexistence below is only exercised while this
// socket is still on the address, which is the state production spends its window in.
let _punched = punch.await.unwrap().expect("the punch must connect");
let dialed = tokio::spawn(tokio::net::TcpStream::connect(local));
let accepted = hbb_common::timeout(3000, listener.accept()).await;
assert!(
matches!(accepted, Ok(Ok(_))),
"the listener must still take connections while a punch shares its address: {accepted:?}"
);
assert!(dialed.await.unwrap().is_ok());
return;
}
panic!("could not hold two free loopback addresses in 8 tries");
}
// The schedule on its own, against a paused clock: the window is CONNECT_TIMEOUT long, and
// what these pin is where inside it the punches fall, which no socket could show.
#[tokio::test(start_paused = true)]
async fn the_punches_end_on_one_at_the_deadline() {
use super::{punch_until, PUNCH_GRACE, PUNCH_INTERVAL, PUNCH_MAX_INTERVAL};
use hbb_common::{anyhow::anyhow, config::CONNECT_TIMEOUT};
use std::time::Duration;
use tokio::time::Instant;
let peer: SocketAddr = "127.0.0.1:1".parse().unwrap();
let start = Instant::now();
let until = start + Duration::from_millis(CONNECT_TIMEOUT);
let mut punches = Vec::new();
// A gateway that answers with RST: every punch fails the moment it is made.
let met = punch_until::<(), _, _>(until, peer, |ms| {
punches.push((Instant::now(), ms));
async { Err(anyhow!("RST")) }
})
.await;
assert!(met.is_none());
assert_eq!(
Instant::now(),
until,
"must return the moment the window closes, not a backoff later"
);
// Tokio rounds every sleep up to the next millisecond.
let slack = Duration::from_millis(1);
assert!(punches[0].0 - start <= Duration::from_secs_f32(PUNCH_INTERVAL) + slack);
for pair in punches.windows(2) {
assert!(
pair[1].0 - pair[0].0 <= Duration::from_secs_f32(PUNCH_MAX_INTERVAL) + slack,
"no gap in the window may exceed the backoff ceiling: {pair:?}"
);
}
assert_eq!(
*punches.last().unwrap(),
(until, PUNCH_GRACE),
"the window must end on a punch, given the whole grace"
);
}
#[tokio::test(start_paused = true)]
async fn a_punch_in_flight_runs_the_grace_past_the_deadline_and_no_further() {
use super::{punch_until, PUNCH_GRACE};
use hbb_common::{anyhow::anyhow, config::CONNECT_TIMEOUT};
use std::time::Duration;
use tokio::time::Instant;
let peer: SocketAddr = "127.0.0.1:1".parse().unwrap();
let until = Instant::now() + Duration::from_millis(CONNECT_TIMEOUT);
let mut punches = 0;
// A gateway that drops the SYN in silence: the punch sits in SYN_SENT for all it is given.
let met = punch_until::<(), _, _>(until, peer, |ms| {
punches += 1;
async move {
tokio::time::sleep(Duration::from_millis(ms)).await;
Err(anyhow!("timed out"))
}
})
.await;
assert!(met.is_none());
assert_eq!(
punches, 1,
"a punch held in SYN_SENT is the only one the window needs"
);
assert_eq!(
Instant::now(),
until + Duration::from_millis(PUNCH_GRACE),
"must return when the grace runs out, not a backoff later"
);
}
}

View File

@@ -212,21 +212,11 @@ pub async fn create_tcp_connection(
let sk = sign::SecretKey(sk_);
let mut msg_out = Message::new();
let (our_pk_b, our_sk_b) = box_::gen_keypair();
// On a WebRTC transport, bind our DTLS certificate fingerprint to our signed identity so
// the controller can verify the DTLS channel it negotiated actually terminates at us
// (not a rendezvous/relay that swapped the SDP fingerprint). Empty on other transports.
// Fail immediately on WebRTC if the local fingerprint is unavailable: signing "" would
// only make the client fail-closed after a wasted round-trip.
let dtls_fingerprint = stream.dtls_fingerprint(true).await.unwrap_or_default();
if stream.is_webrtc() && dtls_fingerprint.is_empty() {
bail!("WebRTC local DTLS fingerprint unavailable");
}
msg_out.set_signed_id(SignedId {
id: sign::sign(
&IdPk {
id: Config::get_id(),
pk: Bytes::from(our_pk_b.0.to_vec()),
dtls_fingerprint,
..Default::default()
}
.write_to_bytes()

View File

@@ -1294,13 +1294,7 @@ impl<T: InvokeUiSession> Session<T> {
// 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().force_relay = true;
}
self.lc.write().unwrap().peer_info = None;
self.reconnect_count.fetch_add(1, Ordering::SeqCst);