From ae6af2de43f11a37bd6a5b25a7dd6aad1ada8c63 Mon Sep 17 00:00:00 2001 From: RustDesk <71636191+rustdesk@users.noreply.github.com> Date: Sun, 6 Sep 2026 00:21:28 +0800 Subject: [PATCH] Webrtc (#15684) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * feat: add rendezvous WebRTC signaling fields * feat: route WebRTC ICE on controlled side * feat: race WebRTC as a direct transport enhancement * fix: route WebRTC ICE through rendezvous paths * feat: WebRTC transport racing, DTLS identity binding, and pc-leak fixes - prefer-P2P racing (race_transports_prefer_webrtc) across punch and RelayResponse; ICE bridge with 400ms candidate resend - controlled-side answerer and ICE routing; sign local DTLS fingerprint into SignedId, controller verifies the binding fail-closed - fix pc leaks: close_webrtc() on insecure-decline paths (io_loop, port_forward); compute direct before disarming the offerer guard - point hbb_common to the WebRTC data-plane commit 9f5a296 Co-Authored-By: Claude Opus 4.8 * fix: preserve WebRTC transport preference * feat: decouple WebRTC from UDP punch, route controlled signaling over TCP - the WebRTC offer now rides any punch request; only an offer-less request may close and reuse the rendezvous socket for TCP punching (request_allows_tcp_punch replaces the udp_port-based invariant), with a separate offer-less request racing as the TCP fallback - WebSocket mode no longer disables WebRTC — ws only tunnels the signaling/relay legs while ICE stays the only P2P path there; SOCKS proxy still disables it (ICE would bypass the proxy and leak the real IP) - controlled side: WebRTC-only punch replies and trickled ICE candidates go over dedicated TCP connections to the rendezvous server instead of the UDP mediator channel, for ws/TCP-only hbbs deployments; drop the now-redundant rz_sender plumbing and the 400ms candidate re-send on that leg - guard is_udp handling against responses to requests that advertised no udp_port; skip the IPv6 socket bind under force-relay - test_udp_uat: drop the STUN port race — the punch port must come from the rendezvous server's TestNatResponse observing this socket's mapping, a STUN probe from another socket can advertise an unreachable port - bump hbb_common (webrtc 0.13 MSRV pin rationale + upgrade checklist docs) Co-Authored-By: Claude Fable 5 * fix: KCP/UDP resilience to ICMP resets; optional KCP congestion control - treat ICMP-driven UDP socket errors (WSAECONNRESET 10054 on Windows, ECONNREFUSED on Linux) as packet loss in punch_udp and the KCP pump instead of tearing the session down; KCP retransmits through them and a truly dead link is still reaped by the pong/app-level timeouts - resolve STUN hostnames via tokio::net::lookup_host so DNS never blocks a runtime worker; fix the inverted non-IPv4 error message - add enable-kcp-congestion-control option (default on): switch the turbo profile to nc=0 so brief loss on constrained links no longer spirals into stalls; sender-side only, no wire negotiation - pin kcp-sys to the rustdesk-patches branch: upstream main lost the RustDesk patches on the EasyTier sync, and this branch also wires set_kcp_config_factory into connection setup, making the option effective Co-Authored-By: Claude Fable 5 * fix: carry switch_code through WebRTC relay fallbacks after rebase The rebase onto master (switch-code feature) added an 8th request_relay parameter; pass the interface's switch code from both WebRTC->relay fallback paths so a role-swap session survives the fallback. Also drop a duplicate bindgen 0.72.1 entry the Cargo.lock merge produced. Co-Authored-By: Claude Fable 5 Claude-Session: https://claude.ai/code/session_01ExUfAkYbq8UC9pQCiLy8TQ * fix: don't let the preferred branch's own relay preempt a direct fallback race_transports_prefer_webrtc committed any success from its first argument outright, on the assumption that it is the WebRTC connect. It is not: the call site passes a whole punch attempt, which internally falls back to request_relay when its direct transports fail. That relay was therefore committed instantly while the offer-less fallback's TCP punch was still in flight — inverting the preference this function exists to enforce, since the is_p2p predicate the caller already supplies was applied only to the `others` branch. Apply it to both branches: a direct result from either side still commits immediately, and a relayed result from either side is held for the window so the other side can land something direct. Also commit a held connection when the surviving branch errors, which the previous code only did on the first branch's failure path. Co-Authored-By: Claude Fable 5 Claude-Session: https://claude.ai/code/session_01ExUfAkYbq8UC9pQCiLy8TQ * fix: evict the oldest pending ICE candidate, not the newest Candidates arrive in gathering order — host, then srflx, then relay — so a full buffer was discarding exactly the ones that traverse NAT while keeping host ones that only work on a shared LAN. Evict from the front instead. Also document why the controller's ICE bridge must not reconnect on error, in contrast to the controlled side's per-candidate retry: its socket address is the return route itself (mangled into PunchHole.socket_addr, echoed back in IceCandidate.socket_addr, resolved through tcp_punch), so a reconnect would arrive from an address no route points at, and the server drops the old entry when the connection closes. Once it dies both directions are dead, and abandoning WebRTC is the correct response rather than retrying. Co-Authored-By: Claude Fable 5 Claude-Session: https://claude.ai/code/session_01ExUfAkYbq8UC9pQCiLy8TQ * fix: bound log volume on sites whose rate a peer or retry loop controls Debug output goes to the log file, so a site that fires per received message or per retry lets someone else decide how much a machine writes to disk. The WebRTC work added the first such sites. - KCP io loop: absorbing ICMP errors as packet loss made a broken socket write ~100 lines a second for the 60s until the pong timeout reaps it. Log by run instead: one line when a run starts, one per ~5s while it persists so a stuck socket stays visible, and one on recovery with the total. - punch_udp: the recv error retries every 10ms for up to MAX_TIME, so one line per occurrence wrote thousands per punch. Log the first, report the count in the timeout message. - ICE candidate paths (client, mediator): the peer sets the candidate rate and the rendezvous route carrying them needs no prior punch, so throttle to one line a minute each with the suppressed count. Co-Authored-By: Claude Fable 5 Claude-Session: https://claude.ai/code/session_01ExUfAkYbq8UC9pQCiLy8TQ * fix: the KCP io throttle reset itself every cycle, so it never throttled The send and recv arms shared one counter, and an ICMP error on a connected socket is reported once and then cleared — so the steady state is an alternation: the send succeeds and clears the counter, the next recv reports the error and finds the counter at 1, and logs. Every error still wrote a line, at the ~100/s the previous commit set out to stop, while the persistent-failure and recovery branches were unreachable. Use one LogThrottle per direction instead of a hand-rolled counter. That removes the shared state the bug lived in, drops a third throttling mechanism in favour of the one already added, and leaves the surrounding `if let Err` untouched rather than reshaping it into a match. Also fix test_udp_uat's socket-error arm, the untreated twin of the punch_udp site: it had no backoff at all, so a persistent error re-armed recv immediately and spun the loop at CPU speed, one warn line per iteration. Co-Authored-By: Claude Fable 5 Claude-Session: https://claude.ai/code/session_01ExUfAkYbq8UC9pQCiLy8TQ * bump kcp-sys: 14 review fixes on rustdesk-patches (6e44b93 -> fa51c15) Picks up the handshake-recovery work plus the review round on top of it: ABBA deadlock between the endpoint's two DashMaps, graceful-close tail truncation, mid-stream hole on ikcp_send failure, FIN retransmission for lost-FIN half-open hangs, SYN-ACK budget burned on dropped packets, spurious ConnectTimeout after a completed handshake, accept-backlog overflow stranding conns, aliasing UB in the output callback, and the log-facade/throttling cleanup (per-packet sites no longer reach the debug-level file logger, peer-rate warns throttled). Co-Authored-By: Claude Opus 5 (1M context) Claude-Session: https://claude.ai/code/session_01ExUfAkYbq8UC9pQCiLy8TQ * ws: decouple ICE policy from force_relay — full-ICE WebRTC over WebSocket WebSocket support folds into force_relay because a ws tunnel kills classic TCP/UDP punching — but that conflated transport necessity with relay policy, and the WebRTC decisions keyed off the merged flag: a ws client built no offerer at all without TURN, and only a Relay-only-ICE one with it. ws deployments could never reach a direct WebRTC connection, which is exactly the path they are supposed to live on. Split the flag. LoginConfigHandler now tracks policy_relay (the force-always-relay option, an explicit relay request — /r ids and retry-via-relay included — and proxy) separately; force_relay stays policy_relay || use_ws() and keeps governing the classic paths, so non-ws behavior is unchanged everywhere: - the offerer's existence and ICE policy follow policy_relay: under pure ws the offer gathers every candidate type and may go direct; under relay-by-policy it stays Relay-only ICE, TURN-gated, exactly as before; - the RelayResponse race applies the prefer-P2P window under ws (a direct ICE path is worth delaying an already-ready relay for) while policy relay keeps first-success semantics; - the request carries webrtc_all_ice (hbb_common 64b54ab) so the controlled side knows the offer is full-ICE: it answers with full ICE and no TURN requirement, while offers without the bit keep today's relay-only answer path on every version-skew combination. Co-Authored-By: Claude Opus 5 (1M context) Claude-Session: https://claude.ai/code/session_01ExUfAkYbq8UC9pQCiLy8TQ * bump kcp-sys: 7 review fixes on rustdesk-patches (fa51c15 -> 023a006) Reverts the connect/accept/add_conn changes that regressed concurrent connects (the state_map guard held across add_conn is load-bearing), states the single-conn contract on KcpEndpoint so shared-endpoint behaviour stops consuming review effort, pins the two invariants that keep truncated input from aborting under panic='abort', and fixes three findings from external review: sendwnd() echoing raw config instead of KCP's effective window (a non-positive factory value stalled sending forever), the passive closer's lost final FIN delaying EOF by up to ~20s, and the doubled window overflowing for extreme factory values. Lock-only change: cargo update -p kcp-sys also re-picked libloading's windows-targets between two versions already present in the lock; that was reverted to keep this commit to the one line it is about. cargo metadata --locked passes on the result. Co-Authored-By: Claude Opus 5 (1M context) * ws: read the all-ICE declaration from the offer envelope, drop the proto field Companion to hbb_common 68d2729: the full-ICE declaration now lives as an `ice_policy: "all"` key inside the webrtc:// envelope, so the request assembly no longer sets webrtc_all_ice and the controlled side asks the envelope (endpoint_declares_all_ice) instead of a PunchHole field. The rendezvous server carries the offer opaquely — no forwarding to keep in sync. Skew behavior is unchanged: an unmarked or unparseable envelope reads as the old Relay-only semantics. Co-Authored-By: Claude Opus 5 (1M context) Claude-Session: https://claude.ai/code/session_01ExUfAkYbq8UC9pQCiLy8TQ * add enable-webrtc option; gate test_ipv6 under forced relay OPTION_ENABLE_WEBRTC (hbb_common 48c2d4d) follows the udp/ipv6 punch options end to end: default on against the public server, off against private ones, same settings UI placement on desktop and mobile, and the same bool2option local-option handling. Gates: - controller: should_create_webrtc_offerer checks it first — no pc, no STUN/TURN gathering, no offer in the request; - controlled: unlike the udp/ipv6 legs, which deliberately follow the request, answering builds a pc that gathers ICE from this host, so the answerer honors this machine's own switch too. Translations for "Enable WebRTC P2P connection" added to all 50 lang files next to the IPv6 entry (IPv6 and WebRTC are invariant terms in the same grammatical slot in every one of them). Also stop probing v6 reachability (test_ipv6) under any forced relay: the v6 punch socket is never bound there, so the probe was wasted work on every ws/proxy/relay connection. Co-Authored-By: Claude Opus 5 (1M context) Claude-Session: https://claude.ai/code/session_01ExUfAkYbq8UC9pQCiLy8TQ * kcp: client-side integration tests over real loopback sockets kcp-sys has been through two review rounds of behavioral fixes; the client wrapper (kcp_io pumps, connect/accept deadlines, framed-stream adaptation, guard lifetimes) had no tests pinning what rustdesk actually relies on. Four now do, each through real 127.0.0.1 UDP sockets and the BytesCodec framing sessions use: - handshake + bidirectional framed roundtrip + graceful close: the peer observes end-of-stream instead of hanging (guard outlives the framed stream so the FIN goes out); - a writer that queues 50 frames and closes immediately loses none of them - the client-side pin for the close-tail-drain semantics; - socket errors after the peer vanishes are treated as loss: writes keep succeeding, nothing tears down (ICMP is advisory on connected UDP); - the connect deadline holds when nothing answers. Mutation-checked: dropping inbound forwarding in kcp_io reddens exactly the three tests that need the pump, and the timeout test alone stays green. Co-Authored-By: Claude Opus 5 (1M context) Claude-Session: https://claude.ai/code/session_01ExUfAkYbq8UC9pQCiLy8TQ * ipc/auth: replace the local throttle with the shared throttled_log! auth.rs predated hbb_common's LogThrottle and grew its own equivalent: same shape (last_log_at + suppressed), same 5s interval, plus a helper and three OnceLock> statics. It also counted the other way - excluding the event being reported - so each of the three sites carried two near-identical log::warn! arms to avoid printing "suppressed 0". The shared macro covers all of it: one static per call site declared by the expansion, and the multiplicity suffix appears only when there is one, which is what those duplicated arms were for. 102 lines out, 27 in. Behavior difference, deliberate: a burst now reads "(x47)" - the total including this line - instead of "(suppressed 46 similar events)". One number, no arithmetic, and one convention across the codebase. Co-Authored-By: Claude Opus 5 (1M context) Claude-Session: https://claude.ai/code/session_01ExUfAkYbq8UC9pQCiLy8TQ * kcp: make the congestion-control profile opt-in, not the default The branch had flipped KCP to nc=0 (built-in congestion window) for every session. That is a transport-behavior change for all users made on reasoning alone, and the reasoning does not decide it: which profile wins depends on why packets are being lost. nc=1 - what RustDesk has always shipped - never shrinks the send window, so on a genuinely congested uplink it deepens the loss it is reacting to. But nc=0's backoff is blunt: a fast retransmit halves the window while an RTO sets cwnd = 1 outright (ikcp.c) and recovery slow-starts from one packet, so on a link with random loss and no congestion - Wi-Fi interference, a long-haul path - it reads loss as congestion and can stall an interactive stream for seconds. That failure mode is also the more visible one to a remote-desktop user. No benchmark settles this either: a loopback A/B has no bottleneck queue, hence no congestion to control, and would flatter nc=1 by construction. Deciding it needs a shaped link or field data. So keep the profile users already run and let the other one be asked for ("enable-kcp-congestion-control" = "Y"). Flipping the default later is a one-line change once there is evidence. kcp-sys keeps its own test covering the nc=0 path. Co-Authored-By: Claude Opus 5 (1M context) Claude-Session: https://claude.ai/code/session_01ExUfAkYbq8UC9pQCiLy8TQ * android: define getifaddrs/freeifaddrs for the api-21 sysroot Turning on hbb_common's "webrtc" feature pulls webrtc-util into the android link, and its ifaces() -- reached from vnet::Net::new() on every ICE gather -- calls getifaddrs(). bionic exports getifaddrs/freeifaddrs only from API 24, while flutter/ndk_*.sh builds against --platform 21, so every abi failed to link on the undefined symbols. Raising the platform to 24 would have to drag minSdkVersion 22 with it and turn the link error into a load-time one on Android 5.1/6.0, so define the two symbols instead, using the RTM_GETLINK + RTM_GETADDR netlink dump bionic itself uses. The definition also shadows bionic's on API >= 24 rather than delegating to it, so the path that ships is the path every test device runs. Checked against synthesised netlink dumps on the host -- link/address parsing, prefix masks, point-to-point, ipv6 scope ids, malformed and truncated messages -- under UBSan and byte-exact guard malloc, with a deliberately unsigned remainder as the negative control. Co-Authored-By: Claude Opus 5 (1M context) * fix three ways ws + WebRTC could not work in practice Review of #15684 and hbb_common#579. Each of these left the code reading correct while the feature did not function. - The RelayResponse race classified P2P with `result.2 == "IPv6"`, but that site's futures are only ever the relay ("Relay"/"WebSocket") and the WebRTC branch's own "WebRTC" — so the predicate was constantly false. When the relay landed first the result was still right (the webrtc arm's `others_fut.is_none()` fallback), but when WebRTC connected FIRST it was parked as if it were a relay and the relay was committed on arrival, discarding a live direct connection. That is the LAN case: the better the network, the worse the outcome. Classify by what the label means, via is_direct_transport, and test both orderings — only the relay-first one was covered. - handle_peer_info wrote "force-always-relay=Y" into the peer's saved config whenever force_relay was set, which now includes the WebSocket transport. One ws session therefore turned the peer into a permanent relay-by-policy peer, and relay-by-policy means Relay-only ICE, so WebRTC could never go direct to it again — the flagship path worked exactly once. Persist policy_relay, which is the user's choice; the transport is a property of this client, not of the peer. - The answerer gated on this machine's enable-webrtc option, but that is LocalConfig: the UI process writes it and never syncs it over IPC, while handle_punch_hole runs in the server process, which on Windows resolves LocalConfig under a different profile and reads the private-server default of "N". The gate refused to answer in exactly the self-hosted deployments the transport exists for. Drop it: the answerer follows the request, like the udp/ipv6 legs, and the option still gates the feature where it can — an offer only exists because some controller had it enabled. Co-Authored-By: Claude Opus 5 (1M context) Claude-Session: https://claude.ai/code/session_01ExUfAkYbq8UC9pQCiLy8TQ * webrtc: close without an await point; do not report an unknown path as direct - close_webrtc is no longer async (hbb_common 88f965f), so the ten call sites in port_forward and io_loop - all inside select! arms or futures the UI can abandon - can no longer be cancelled mid-teardown, which left the pc unclosable and its session entry stranded. Client's own spawn_close_webrtc went with it: the runtime-teardown guard it existed for now lives in close_detached, so both Drop paths share one implementation. - webrtc_relayed() returns None when no candidate pair is selected or the pc closed under a concurrent teardown, and both call sites read that as "not relayed", i.e. direct. A TURN-relayed session could therefore be shown to the user as peer-to-peer. Claiming a direct path needs evidence of one, so an unknown answer now counts as relayed. Co-Authored-By: Claude Opus 5 (1M context) Claude-Session: https://claude.ai/code/session_01ExUfAkYbq8UC9pQCiLy8TQ * scrap/benchmark: give the Duration divisor an explicit u32 The webrtc feature pulls time 0.3 into scrap's graph (hbb_common -> webrtc -> webrtc-dtls -> der-parser -> asn1-rs), and that crate carries an `impl Div for std::time::Duration`. Orphan rules allow it because the RHS is its own type, and trait impls are visible across the whole dependency graph without a use, so std::time::Duration now has two Div candidates. `yuv_count as _` casts to a plain inference variable, which both candidates fit, so it stops resolving: error[E0282]: type annotations needed --> libs/scrap/examples/benchmark.rs:146:33 Only two of the four sites are reported - rustc emits one E0282 per function body - so all four are annotated. The already-explicit `as u32` at the hwcodec site and `start.elapsed() / cnt` are unaffected, the latter because an integer literal's variable can only unify with an integral type and rules the time impl out on its own. Co-Authored-By: Claude Opus 5 (1M context) * webrtc: judge the race by the resolved path, not the label; bound the ICE queue Third review round. Two of these are regressions from the previous one. - The RelayResponse race predicate was `is_direct_transport(result.2)`, which answers true for the label "WebRTC" - but WebRTC is only a direct path when ICE nominated a non-TURN pair. A TURN-relayed WebRTC result therefore committed instantly and cancelled the IPv6 attempt racing beside it, which is the same inversion the previous fix removed in the other direction. (That fix was also argued from a wrong premise: the site does carry an IPv6 future, pushed ~50 lines earlier than the relay one.) Each future now resolves whether its path is direct and the predicate reads that bool, matching the outer race, and the downstream recomputation goes away. - policy_relay still folded in Config::is_proxy(), and that is what gets persisted into the peer's config as force-always-relay - so one session through a proxy pinned the peer to relay forever and disabled WebRTC for it, exactly the latch the previous round fixed for WebSocket. Split out peer_relay: the saved option or an explicit request for THIS peer, and the only part written back. - The controlled side buffered remote ICE candidates in an unbounded channel while the controller caps the same buffer at 64, and draining one costs a JSON parse plus the ICE agent's lock. Whoever can reach a session's route could grow it without limit inside the long-lived service process. Bounded, with the overflow logged through the existing throttle. - That route was also removed by key alone when an answerer finished, so a punch retry that built a fresh answerer under the same fingerprint had its live sender deleted by the previous one's cleanup - after which it received no candidates at all. Evict only our own sender, the way the session cache already guards the analogous case. Co-Authored-By: Claude Opus 5 (1M context) Claude-Session: https://claude.ai/code/session_01ExUfAkYbq8UC9pQCiLy8TQ * webrtc: trim the comments to AGENTS.md length; drop is_direct_transport 386 added comment lines down to 287 across client, mediator, kcp_stream and common. Same rule as hbb_common 3d64e43: out go past-bug narration, rejected alternatives, measurements and restatements of the code; the non-derivable why stays. is_direct_transport goes with them. Judging the race by a transport label was replaced by the resolved direct flag, leaving it used only by its own test — and, having been inserted between the doc comment and race_transports_prefer_webrtc, it had also taken that function's contract with it. Removing it reattaches the doc where it belongs. Co-Authored-By: Claude Opus 5 (1M context) Claude-Session: https://claude.ai/code/session_01ExUfAkYbq8UC9pQCiLy8TQ * webrtc: fix race edge cases that discard or mislabel a direct connection Three correctness fixes in the transport race, plus three convention cleanups. - race_transports_prefer_webrtc committed a relayed result while a direct attempt was still in flight: the others arm returned on webrtc_fut.is_none() even with an unfinished direct future, and the WebRTC-error arm returned a held relay without checking others_fut. A relay is now committed only when nothing direct can still arrive (or the window expires); a parked relay is also preferred over composing an error when both sides fail. Three regression tests, mutation-checked. - connect()'s plain select_ok let a TURN-relayed WebRTC win as "first success", dropping still-racing UDP/IPv6 direct attempts and reporting the relayed pair as direct. It now runs through the same prefer-P2P race with each attempt carrying whether its path is direct, and the WebRTC future resolves is_relayed() so a TURN win is held behind direct attempts, not committed as one. - The RelayResponse path kept direct == true when a WebRTC win's DTLS handshake failed and it fell back to relay, so the relay was reported P2P. Clear the flag with the transport switch. - Trim the OffererGuard doc to the three-line max; move the new enable-webrtc localization key to the end of every lang list; the KCP option constant moved to hbb_common config::keys (0f663aa). Co-Authored-By: Claude Opus 5 (1M context) Claude-Session: https://claude.ai/code/session_01ExUfAkYbq8UC9pQCiLy8TQ * bump hbb_common: WebRTC peer connections own their I/O runtime Closing the controlling window left the controlled side waiting out ICE decay — ~25-30s in the peer's log, its disconnected/failed ladder running to completion — where TCP delivers a FIN at once. The session end closed the pc by spawning onto io_loop's own `#[tokio::main(flavor = "current_thread")]` runtime, which is dropped the moment io_loop returns, and nothing after that call yields: the task was never polled even once, so no DTLS close_notify ever left. Every attempt to fix that on the caller's side failed the same way, because the mismatch was never about where the close ran: a pc's UDP sockets register with the reactor, and its ICE/DTLS/SCTP pumps spawn on the runtime, that is current while it is built — so a pc created by a session outlives the only runtime that can drive its I/O, and a close driven anywhere else completes without reaching the wire. The bump homes them where they can outlive any caller: WebRTCStream builds on a process-lifetime runtime and every detached close runs there as its own never-cancelled task. io_loop keeps its plain close_webrtc() calls and only documents why nothing here may spawn or await the teardown on the dying session runtime. Co-Authored-By: Claude Opus 5 (1M context) Claude-Session: https://claude.ai/code/session_016HV43uh1ztv6Wm5qi3Y1ne * fix: give the UDP NAT test a real window when the TCP clock is faked The punch request carries udp_port only if the rendezvous server's TestNatResponse has arrived, and the wait for it was bounded by rtt / 2 — half the TCP connect time, on the assumption that TCP and UDP round trips are comparable and the test, started earlier, has already answered. A transparent TCP proxy breaks that assumption: a TUN-mode VPN on the host, or a redirect-mode proxy on the LAN gateway serving every device behind it, completes the handshake locally in ~3ms while the real UDP round trip is hundreds of ms. Log-confirmed against 5.161.65.208: ping 341ms, TCP connect 3.7ms, connect to a dead port there "succeeds" just as fast. The window collapsed to ~1.5ms, udp_port stayed 0 on every attempt, and UDP punch was never even requested — although UDP itself passes such gateways untouched. So use the TCP clock only when it is believable: below a plausible WAN round trip it says nothing about the UDP path, and a flat ceiling applies instead. The loop still exits the moment the port arrives, so a genuinely nearby server pays nothing and only a UDP-dead network waits out the ceiling — on the udp-carrying round alone, while the parallel pure-TCP round is unaffected. Co-Authored-By: Claude Opus 5 (1M context) Claude-Session: https://claude.ai/code/session_016HV43uh1ztv6Wm5qi3Y1ne * feat: make the TCP punch a user option, with TCP as the backstop TCP punching was the one direct transport without a switch, while UDP, IPv6 and WebRTC each had one. Add "Enable TCP hole punching" above the UDP toggle on both desktop and mobile, default on — including on self-hosted servers, since unlike the other three (whose default-off there guards against an hbbs that cannot forward their fields) TCP punching has always been supported by every server. Turning all four off would leave no way to punch at all, so TCP runs regardless in that case. That backstop keys off the switches alone: a transport that is enabled but fails to materialize — no public v6 address, no NAT port, a failed offerer — is already covered by the relay fallback for a round that ends up with no usable direct transport. With the TCP punch off, the fallback request is skipped too: it exists only to carry that punch, and would otherwise reach connect() with nothing to try and merely open a second relay. Known cost, unchanged behavior for the peer: the request carries no field for this choice, so a peer that receives one with no udp_port and no offer still punches a TCP hole and listens for a connection the controller will not make. Representing the transport choice on the wire needs a proto field and the server forwarding it. Co-Authored-By: Claude Opus 5 (1M context) Claude-Session: https://claude.ai/code/session_016HV43uh1ztv6Wm5qi3Y1ne * bump hbb_common: name the punch by every transport it carries `get_local_endpoint_trickle` became `local_endpoint() -> &str`, which cannot fail, so both call sites lose an unreachable error arm — the mediator's closed a pc against a failure that no longer exists. `punch_type` named one transport, and picked it off `allow_tcp_punch`. A round carries several at once — a NAT port and a v6 address and an offer — and since the TCP punch became a switch it can carry none, so one name had to misreport both: the logs of the round that broke WebRTC read "#1 UDP punch attempt" while the request also carried the v6 address and the offer that was actually failing, and a round with nothing to punch with was labelled "WebRTC". List them instead — "UDP+IPv6+WebRTC" — and call the empty round "Relay", which is what it can still end as and what `typ` prints for it. The offer is moved into the request rather than cloned into it; that was its last use. Co-Authored-By: Claude Opus 5 (1M context) Claude-Session: https://claude.ai/code/session_019UzcMTdYTEv2QbMHcTSUy3 * bump hbb_common: drop link-local IPv6 from ICE gathering Also pin webrtc-util to a fork of 0.11.0 carrying a Windows IPv6 enumeration fix. `ifaces` reads the adapter list's on-wire IPv6 bytes as host-order `[u16; 8]`, so on a little-endian host every group comes out byte-swapped and unbindable: a peer's real 240e:369:9606:4600:f52a:7a8d:2530:4de0 is enumerated as e24:6903:696:46:2af5:8d7a:3025:e04d, ::1 as ::100 and fe80:: as 80fe::. Each fails to bind with WSAEADDRNOTAVAIL, so ICE gathers no IPv6 host candidate at all on Windows - where a globally routable address is the one NAT-free path a CGNAT'd peer has. Never reported upstream; the unix twin of the same bug was fixed in webrtc-rs#475 (2023). Fork: rustdesk-org/webrtc, branch rustdesk-patches, tag webrtc-util-0.11.0-win-ipv6. Co-Authored-By: Claude Opus 5 Claude-Session: https://claude.ai/code/session_019UzcMTdYTEv2QbMHcTSUy3 * bump hbb_common: name the family a WebRTC session runs over `stream_type` reaches the UI as the transport that won the race, and every other transport already carries the family in that label - the v6 punch reports `IPv6`. WebRTC does not: one label covers both families, and it is the one path whose real remote address can differ from the rendezvous-observed one the session is identified by. Refine it at the hand-off to the UI rather than at the source: five sites in client.rs compare `typ == "WebRTC"`, so widening the label there would silently move control flow. Co-Authored-By: Claude Opus 5 Claude-Session: https://claude.ai/code/session_019UzcMTdYTEv2QbMHcTSUy3 * bump hbb_common: one STUN list, and drop the dead IPv4 half `test_ipv6` kept its own hand-written copy of the STUN servers. It now reads `WebRTCStream::stun_servers()`, so an operator who points OPTION_ICE_SERVERS at their own server gets it on both paths instead of one. `test_bind_ipv6` sends nothing - `connect` only makes the kernel pick a route and a source address - so the whole cost is DNS. It races the lookups rather than betting this host's IPv6 support on whether the first entry happens to publish a AAAA where the user resolves from; google's does not, from a Chinese resolver, and it was the entry being bet on. `stun_ipv4_test`, `STUNS_V4` and `test_nat_ipv4` have had no callers since the punch stopped taking its port from a second socket, and go. `get_kcp_cc_enabled` reads the renamed option through `option2bool`, like every other one. Co-Authored-By: Claude Opus 5 Claude-Session: https://claude.ai/code/session_019UzcMTdYTEv2QbMHcTSUy3 * webrtc: take dcsctp's retransmission timings and IPv6-safe MTU webrtc-sctp ships RFC 4960's RTO.Initial/RTO.Min (3000/1000), TCP's values for arbitrary public paths. On this workload they set the recovery time outright: a request/response exchange keeps one chunk in flight, so no later SACK ever raises miss_indicator to the 3 that arms fast retransmit, and the T3 floor is the only way back. A single loss during a handshake or a first keyframe therefore costs whole seconds. The fork now carries dcsctp's numbers instead - the SCTP implementation Google wrote to replace usrsctp for Chrome's WebRTC data channels, the same realtime workload: rto_initial 500, rto_min 400, a 220ms floor under the RTT variance, and mtu 1191. INITIAL_MTU 1228 plus DTLS/UDP/IPv6 overhead is 1313, past the 1280 minimum, so every full-size chunk fragmented on an IPv6 path. Both patch entries move to the new branch, which also carries the Windows IPv6 byte-swap fix, so one rev matches the whole webrtc 0.13 stack. * udp: make the punch prove itself, and keep the listener answering punch_udp sent a zero-length datagram and called the hole open on whatever arrived next. The rendezvous NAT test's own leftover replies satisfy that immediately - connect() does not flush the receive queue - so the retry loop never ran and success meant nothing. The dead socket then cost KCP its full timeout to rediscover, which is how a failed punch came to take 18 seconds. Probes now carry a magic and a 64-bit transaction id, and both ends answer each other's probes, so returning is a fact: a reply echoing our own id is the one thing that proves the pair carries traffic both ways. With failure now distinguishable from 'not yet', the window drops from 20s to 3s. Two asymmetries fall out of that: Only the connector stops on its own acknowledgement, because only it has something to send next. An acknowledgement proves our probe came back, not that the peer's probe was answered - and after punch_udp returns nothing answers probes any more, since KCP's io loop drops anything shorter than its header. A listener that stopped there would go mute while a peer whose own probe or answer was lost - the normal state of a hole still opening - kept probing an endpoint that works, until it timed out. So the listener stops on the peer's first real packet instead, and hands that packet to KcpStream::accept as its init_packet: its arrival proves the pair as well as an acknowledgement would, and KCP never retransmits its SYN. * webrtc: correct the RTT variance floor to dcsctp's scaling The earlier commit took dcsctp's min_rtt_variance = 220 as a raw floor under rttvar. dcsctp divides the option by kHeuristicVarianceAdjustment = 8.0 first, a historical accident it kept because downstream users had measured good values with it, so the intended floor is 27.5ms of variance contributing 110ms to RTO. Flooring at 220 contributed 880ms instead, which on a 50ms path left RTO within 7% of the 1000ms default this change exists to escape. The fork also now records why T1/T2 share T3's RTO manager here, unlike dcsctp's separate control timers: RTO_INITIAL is the T3 value for the first DATA chunk, since no RTT sample exists before the first SACK. * webrtc: skip the controller's ICE re-send instead of queueing it twice The controller sends every candidate twice, because the server's hop to a peer registered over UDP can lose one. The ICE agent that dedups repeats sits downstream of the answerer's queue, so the answerer paid for both copies: a slot, a JSON parse, and the ICE agent's lock, once per repeat. Remember a digest of what was queued and skip the repeat. Recorded only once queued, so a candidate a full queue refused stays repairable by the re-send. The queue's depth is unchanged. A real peer gathers well under it - four STUN servers, link-local IPv6 filtered, one component - and the drain empties it as candidates trickle in, so what this removes is the redundant work, not an overflow. Co-Authored-By: Claude Opus 5 Claude-Session: https://claude.ai/code/session_019aokqJuhjvB3kijXtAg5Ns * tcp: repeat the punch across the controller's dial window The single punch leaves before hbbs has told the controller where to dial, so it is never in flight at the same time as the controller's SYN: it opens our NAT, meets nothing, and a gateway that answers it with RST takes the mapping down with it, leaving the listener waiting on a hole that no longer exists. Punch again while the controller may still be dialing, and race those punches against the accept. That is two ways in where there was one: the mapping is rebuilt if a RST took it, and once the controller sits in SYN_SENT one of the punches meets its SYN and completes as a simultaneous open - which a punch sent before the controller had been told anything never could. The crossing reaches the punch rather than the listener because the two sockets share the address but only the punch matches the four-tuple, which the tests now pin down. There is no instant to aim at, and no window either. `Client::connect` sizes the controller's dial only after our PunchHoleSent, from its own rendezvous time and the direct failures it has recorded for us: CONNECT_TIMEOUT between two known-asymmetric NATs that never failed, punch_time_used times three or six otherwise, floored at a second - so a peer that failed once dials for a second or two from then on, and none of that reaches this side. The repeats therefore cover our own ceiling instead, CONNECT_TIMEOUT, which is exactly as long as the accept has always been willing to take a connection through the hole, and back off across it: dense at the start, where every window begins and the short ones end, sparse afterwards, which is `punch_udp`'s shape for the same reason. A window past that ceiling was lost before this change too, and mostly to the controller's own kernel - Windows gives a SYN up at 21s, Linux's next re-send after 15s is at 31s; a window short of it costs a few SYNs to a port already closed. No punch is cut on a per-attempt timeout; one in flight is bounded only by the shared deadline plus PUNCH_GRACE. A punch is cancel-safe only while it is still in SYN_SENT; once the controller's SYN has crossed it the socket is half way through a handshake, and cutting it there cuts the connection the controller is opening - whose `connect` has already returned, so that attempt fails outright, there being no relay fallback after a failed TCP handshake. A timer cannot tell the two states apart, and none is needed: a gateway that answers with RST fails the connect at once and the loop punches again, while one that drops the SYN in silence leaves the socket in SYN_SENT, holding the mapping open while the kernel re-sends, which any SYN of the controller's then crosses - a second punch has nothing to add. The deadline decides whether another punch starts; one in flight runs a grace past it, enough for a crossing begun just before it to complete. The last sleep is cut at the deadline rather than run out past it, so the window ends on a punch given that grace and not on a gap of up to the backoff ceiling: the controller's window opened after ours, on the PunchHoleSent hbbs relayed, so one as long as ours is still open through our tail. Only the accept races the punch, never `accept_connection`: that one does not return until the session it goes on to run has ended, so racing it would tear a live session down. Whichever arrives first is the one connection the request produces. `meta` carries the control permissions hbbs granted for this one controller, so serving the loser as well would hand them to a second peer - and nothing about a connection tells the two apart before `create_tcp_connection` has spoken to it, least of all its address: a carrier NAT shares one between subscribers, and a NAT that pools its external addresses may dial us from a different one than hbbs saw the controller through. So the address is not checked, as `accept_connection` never checked it; the handshake says who arrived, and what holds the invariant is that there is no second serve. Those permissions are a ceiling and not a grant either way: `Connection` gates every message on `authorized`, and latches the login scope of the first request it accepts, so a peer that reached the hole still arrives with nothing. The accept loops rather than taking a single connection, so that a transient accept error does not spend the window the controller still has to arrive in. libp2p's DCUtR reaches the same place by having both peers dial at one instant agreed over the relay. Nothing we send reaches the controller directly, so we cover its dial window rather than name an instant inside it. Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_019aokqJuhjvB3kijXtAg5Ns * hbb_common: bump to the webrtc branch rebased on main Picks up upstream's session-cache eviction by pc identity (#589, adopted without its unused insert-path helper), the 90-day log retention, and the wlroots output fixes. Co-Authored-By: Claude Opus 5 Claude-Session: https://claude.ai/code/session_019aokqJuhjvB3kijXtAg5Ns * webrtc: send over SCTP without a congestion window, as KCP does The same link that streams over KCP crawls over WebRTC. webrtc-sctp runs RFC 4960's AIMD: a fast retransmit halves cwnd, a T3 drops it to one MTU, and slow start only rebuilds it while data is queued behind it. Where the loss is random rather than congestion - a lossy long-haul link - the rate settles at the Mathis ceiling MSS/(RTT*sqrt(p)) however idle the link is: about 1.3 Mbps at 70ms RTT and 1% loss, 0.6 Mbps at 5%, while 1080p wants 2-5 Mbps. KCP's turbo profile (nc=1) has no congestion window at all. The fork now carries a switch that bypasses the two places gating sends on cwnd, and hbb_common turns it on for every peer connection unless `allow-webrtc-congestion-control` is set - the same opt-in KCP has in `allow-kcp-congestion-control`, for the reason at `get_kcp_cc_enabled`. Sender-side only; a browser or an older build on the other end interoperates. Measured over a simulated link (35ms one-way, random loss both ways, 12 KB frames at 30fps, 300 frames): at 1% loss the window stretches 9.9s of video to 20.7s with a mean latency of 5.5s; without it the stream stays realtime at a mean of 113ms. At 3%: 47s and 15s against 10.2s and 290ms. Co-Authored-By: Claude Opus 5 Claude-Session: https://claude.ai/code/session_019aokqJuhjvB3kijXtAg5Ns * webrtc: take the fork's loss recovery for sending without a congestion window rustdesk-org/webrtc 825a0a48: without a congestion window a chunk is lost once three chunks sent after its latest transmission are acked, counted in send order so retransmitted chunks are covered too, and the fast retransmit sends every lost chunk at once, as KCP nc=1 does; before, a lost retransmission waited for T3-rtx. Also fixes the delayed SACK timer never re-arming, the switch applying to established associations, T3-rtx resending one chunk when the peer's window is full, and bounds new data to 1 MiB / 1024 chunks in flight like KCP's snd_wnd. Simulated 35ms one-way, random loss both ways, 30 fps, frames later than 200ms out of 1200: 12 KB at 5% loss 996 -> 55 (KCP 61); 40 KB at 2% loss 1183 -> 20 (KCP 39). Co-Authored-By: Claude Opus 5 Claude-Session: https://claude.ai/code/session_019aokqJuhjvB3kijXtAg5Ns * bump hbb_common: decode TURN userinfo, add the webrtc_echo example Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_01JXJJGEGdgu26wgCppvUXdZ * web: show the WebRTC toggle and transport in the web UI The web client now speaks WebRTC, but the desktop settings page hides the punch options on web and the remote page opens without the session tab that carries the transport name. Let the existing "Enable WebRTC P2P connection" checkbox through on web (the other punch options stay native-only), and add a Transport row to the quality monitor for WebRTC sessions only (with "(TURN)" when ICE relayed), on every platform. Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_01JXJJGEGdgu26wgCppvUXdZ * bump hbb_common: end the ICE forwarder at gathering complete, drop the closes Drop covers hbb_common now closes the local-candidate channel when gathering completes, so the controlled side's forwarder in spawn_webrtc_answerer ends there, and its signaling connection to hbbs with it, instead of sitting on a socket hbbs closed at 90s idle for the rest of the session. It also keeps the reassembly buffer across fragmented frames. Stream closes the WebRTC peer connection on drop (hbb_common b0b624d), so the close_webrtc() calls in port_forward and io_loop that sat immediately before a return or the end of scope did nothing Drop was not about to do, while the comments beside them still said a bare drop leaked the pc. Remove both. Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_019aokqJuhjvB3kijXtAg5Ns * bump hbb_common: quiet the webrtc-rs warnings that describe the race's normal outcome Cancelling the transport that lost the race, and trickle checking before it holds a pair, are what the design does on every session that connects - and webrtc-rs reports both at warn, 90 lines of a 386-line controlled-side log, beside connections that succeeded. agent_internal and peer_connection drop to error; agent_gather keeps warn, since an unreachable STUN server is the one upstream signal that explains a session which never connected. Co-Authored-By: Claude Opus 5 (1M context) Claude-Session: https://claude.ai/code/session_01M54JAqUK4RynudFou89hod * port_forward: restore the `?` the close removal left as a match Dropping the explicit close_webrtc() from the parse-error arm left a match that only re-spells `?`; master just reworked this function, so the branch now leaves port_forward.rs untouched. Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_019aokqJuhjvB3kijXtAg5Ns * l10n: the two WebRTC keys were missing from Urdu Every other lang file on the branch carries them; ur.rs was skipped when they were added. Co-Authored-By: Claude Opus 5 Claude-Session: https://claude.ai/code/session_019aokqJuhjvB3kijXtAg5Ns * udp: make the punch deadline absolute, so a talking peer cannot defer it `select!` rebuilds every arm each iteration, so the relative retry sleep was restarted by each datagram that arrived before it fired. The peer sets that rate, and an old-build peer's empty datagrams match no arm and loop without even the recv-error pause, so MAX_TIME went unchecked and the retransmit was starved with it. `udp_nat_connect` awaits the punch ahead of the KCP timeout and nothing above it bounds the phase, so the punch held the direct race open and the relay fallback out of reach for as long as the peer kept sending. Absolute instants for both clocks. The new test floods empty datagrams for four times the deadline: the punch now ends at 3s where it ran the full 12s. Also note at the symmetric-NAT branch that WebRTC not following the legacy relay decision there is deliberate, so it is not later "fixed" into agreement. Co-Authored-By: Claude Opus 5 Claude-Session: https://claude.ai/code/session_019aokqJuhjvB3kijXtAg5Ns * bump webrtc fork: MTU-safe bundles, a reordering window, tail loss within the RTT rustdesk-org/webrtc cc6633bc, three commits on 825a0a48, all on the path that sends without a congestion window: Both bundlers counted a DATA chunk by its payload alone; with the header and padding counted, bundles of small chunks stay within the MTU, and the fragment payload rounds down to 1160 so a full chunk does too. A chunk is fast retransmitted at most five times, KCP's IKCP_FASTACK_LIMIT. A frame's chunks go out within microseconds of each other, so on a path that jitters the send-order rule resent every chunk that landed behind three of its siblings: 2.7x the payload on the wire at 10ms of jitter, and on a link without the room for that, a queue that fed on itself. A reordering window, RACK's, makes evidence count only from what was sent a quarter of an srtt after the chunk once the path is seen to reorder, widening on the duplicate TSNs the receiver reports. 5 Mbps, 1% loss, 20ms jitter: 600 of 600 frames at a 98ms mean where 290 arrived at 6.2s. A chunk lost at the tail of a burst has only T3-rtx, which ran from floors sized for a 200ms delayed ack and restarted only on the tail's predecessor's ack: 600ms and more. Every DATA chunk now carries the I bit, the floors are KCP's shape, and a fast retransmission restarts the timer. One 200-byte message per frame at 5% loss: 9 of 600 later than 200ms, from 42. Random loss without jitter is unchanged at every rate and frame size. Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_019aokqJuhjvB3kijXtAg5Ns * bump webrtc fork: T3-rtx restarts only for the earliest chunk's fast retransmission rustdesk-org/webrtc 2b8e55bc. Sending without a congestion window, a fast retransmission of any chunk restarted T3-rtx, so a chunk past the fast retransmission cap - left to that timer - never reached it while later chunks kept being resent, which a lossy stream does every couple of frames. The timer is the earliest in-flight chunk's, and only its resend restarts it now. Nothing else changes; the benchmark is unchanged. Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_019aokqJuhjvB3kijXtAg5Ns * bump webrtc fork: T3-rtx restart on fast retransmission while shutting down too rustdesk-org/webrtc 48100bf1. The restart for the earliest chunk's fast retransmission reached only the Established branch of the write loop; the shutdown states still carry data in flight and recover it the same way, so a closing association could still resend everything on a loss its fast retransmit had already recovered. Both branches share one helper now. Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_019aokqJuhjvB3kijXtAg5Ns --------- Co-authored-by: Claude Opus 4.8 --- Cargo.lock | 302 ++-- Cargo.toml | 18 +- build.rs | 12 + flutter/lib/common.dart | 3 +- flutter/lib/common/widgets/overlay.dart | 3 + flutter/lib/consts.dart | 2 + .../desktop/pages/desktop_setting_page.dart | 16 +- flutter/lib/mobile/pages/settings_page.dart | 70 +- flutter/lib/models/model.dart | 10 + libs/hbb_common | 2 +- libs/scrap/examples/benchmark.rs | 8 +- src/client.rs | 1320 ++++++++++++++++- src/client/io_loop.rs | 8 + src/common.rs | 306 ++-- src/ipc/auth.rs | 129 +- src/kcp_stream.rs | 160 +- src/lang/ar.rs | 2 + src/lang/be.rs | 2 + src/lang/bg.rs | 2 + src/lang/ca.rs | 2 + src/lang/cn.rs | 2 + src/lang/cs.rs | 2 + src/lang/da.rs | 2 + src/lang/de.rs | 2 + src/lang/el.rs | 2 + src/lang/eo.rs | 2 + src/lang/es.rs | 2 + src/lang/et.rs | 2 + src/lang/eu.rs | 2 + src/lang/fa.rs | 2 + src/lang/fi.rs | 2 + src/lang/fr.rs | 2 + src/lang/ge.rs | 2 + src/lang/gu.rs | 2 + src/lang/he.rs | 2 + src/lang/hi.rs | 2 + src/lang/hr.rs | 2 + src/lang/hu.rs | 2 + src/lang/id.rs | 2 + src/lang/it.rs | 2 + src/lang/ja.rs | 2 + src/lang/ko.rs | 2 + src/lang/kz.rs | 2 + src/lang/lt.rs | 2 + src/lang/lv.rs | 2 + src/lang/ml.rs | 2 + src/lang/nb.rs | 2 + src/lang/nl.rs | 2 + src/lang/pl.rs | 2 + src/lang/pt_PT.rs | 2 + src/lang/ptbr.rs | 2 + src/lang/ro.rs | 2 + src/lang/ru.rs | 2 + src/lang/sc.rs | 2 + src/lang/sk.rs | 2 + src/lang/sl.rs | 2 + src/lang/sq.rs | 2 + src/lang/sr.rs | 2 + src/lang/sv.rs | 2 + src/lang/ta.rs | 2 + src/lang/template.rs | 2 + src/lang/th.rs | 2 + src/lang/tr.rs | 2 + src/lang/tw.rs | 2 + src/lang/uk.rs | 2 + src/lang/ur.rs | 2 + src/lang/vi.rs | 2 + src/platform/android_ifaddrs.c | 404 +++++ src/rendezvous_mediator.rs | 759 +++++++++- src/server.rs | 10 + src/ui_session_interface.rs | 8 +- 71 files changed, 3111 insertions(+), 541 deletions(-) create mode 100644 src/platform/android_ifaddrs.c diff --git a/Cargo.lock b/Cargo.lock index 1746adc00..98840e947 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -753,24 +753,6 @@ 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" @@ -1161,30 +1143,6 @@ 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" @@ -1234,7 +1192,6 @@ checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad" dependencies = [ "crypto-common", "inout", - "zeroize", ] [[package]] @@ -2324,7 +2281,7 @@ version = "0.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "330c60081dcc4c72131f8eb70510f1ac07223e5d4163db481a04a0befcffa412" dependencies = [ - "libloading 0.8.4", + "libloading 0.7.4", ] [[package]] @@ -2442,42 +2399,6 @@ 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" @@ -2863,7 +2784,7 @@ dependencies = [ "is-terminal", "lazy_static", "log", - "nu-ansi-term 0.49.0", + "nu-ansi-term", "regex", "thiserror 1.0.61", ] @@ -3766,6 +3687,7 @@ dependencies = [ "mac_address", "machine-uid", "osascript", + "percent-encoding", "protobuf", "protobuf-codegen", "rand 0.8.5", @@ -4177,16 +4099,15 @@ dependencies = [ [[package]] name = "interceptor" -version = "0.15.0" +version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ea51375727680dc15f06e8ad90fa31df75d79dd030100e8ad60eef1c27fe2c98" +checksum = "1ac0781c825d602095113772e389ef0607afcb869ae0e68a590d8e0799cdcef8" dependencies = [ "async-trait", "bytes", - "futures", "log", "portable-atomic", - "rand 0.9.2", + "rand 0.8.5", "rtcp", "rtp", "thiserror 1.0.61", @@ -4338,11 +4259,11 @@ dependencies = [ [[package]] name = "kcp-sys" version = "0.1.0" -source = "git+https://github.com/rustdesk-org/kcp-sys#32a6c09fc6223f54aea83981a6aa8995931d29be" +source = "git+https://github.com/rustdesk-org/kcp-sys?branch=rustdesk-patches#023a0065398968989f2ddfcf5cc72bb886d02675" dependencies = [ "anyhow", "auto_impl", - "bindgen 0.71.1", + "bindgen 0.72.1", "bitflags 2.9.1", "bytes", "cc", @@ -4353,8 +4274,6 @@ dependencies = [ "thiserror 2.0.17", "tokio", "tokio-util", - "tracing", - "tracing-subscriber", "zerocopy 0.7.34", ] @@ -4488,7 +4407,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e310b3a6b5907f99202fcdb4960ff45b93735d7c7d96b760fcff8db2dc0e103d" dependencies = [ "cfg-if 1.0.0", - "windows-targets 0.52.6", + "windows-targets 0.48.5", ] [[package]] @@ -5210,16 +5129,6 @@ 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" @@ -5883,12 +5792,6 @@ 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" @@ -6277,17 +6180,6 @@ 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" @@ -7094,9 +6986,9 @@ dependencies = [ [[package]] name = "rtcp" -version = "0.14.0" +version = "0.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "81d30d1c4091644431c22acf9f8be6191b56805e0e977f15ca7104b4a6d6eaec" +checksum = "e9689528bf3a9eb311fd938d05516dd546412f9ce4fffc8acfc1db27cc3dbf72" dependencies = [ "bytes", "thiserror 1.0.61", @@ -7105,14 +6997,14 @@ dependencies = [ [[package]] name = "rtp" -version = "0.14.0" +version = "0.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2f126f38ea84c02480e32e547c1459a939052f74fb92117ac3eef23fdac6b023" +checksum = "c54733451a67d76caf9caa07a7a2cec6871ea9dda92a7847f98063d459200f4b" dependencies = [ "bytes", "memchr", "portable-atomic", - "rand 0.9.2", + "rand 0.8.5", "serde 1.0.228", "thiserror 1.0.61", "webrtc-util", @@ -7267,6 +7159,7 @@ dependencies = [ "terminfo", "termios 0.3.3", "tiny-skia", + "tokio", "totp-rs", "tray-icon", "ttf-parser", @@ -7547,11 +7440,11 @@ dependencies = [ [[package]] name = "sdp" -version = "0.10.0" +version = "0.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "32c374dceda16965d541c8800ce9cc4e1c14acfd661ddf7952feeedc3411e5c6" +checksum = "4cd277015eada44a0bb810a4b84d3bf6e810573fa62fb442f457edf6a1087a69" dependencies = [ - "rand 0.9.2", + "rand 0.8.5", "substring", "thiserror 1.0.61", "url", @@ -7781,15 +7674,6 @@ 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" @@ -8129,15 +8013,15 @@ dependencies = [ [[package]] name = "stun" -version = "0.9.0" +version = "0.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1a512c5d501e3e3b5a4bb3e8e31462d56d54a66b95a28b8596e14422bf21c32b" +checksum = "7dbc2bab375524093c143dc362a03fb6a1fb79e938391cdb21665688f88a088a" dependencies = [ "base64 0.22.1", "crc", "lazy_static", "md-5", - "rand 0.9.2", + "rand 0.8.5", "ring", "subtle", "thiserror 1.0.61", @@ -8519,16 +8403,6 @@ 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" @@ -8908,32 +8782,6 @@ 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]] @@ -9048,9 +8896,9 @@ dependencies = [ [[package]] name = "turn" -version = "0.11.0" +version = "0.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5ed995882f66ab94238de77c62e5e778389698ab700afa4696f4754da8f457cb" +checksum = "3f5aea1116456e1da71c45586b87c72e3b43164fbf435eb93ff6aa475416a9a4" dependencies = [ "async-trait", "base64 0.22.1", @@ -9058,7 +8906,7 @@ dependencies = [ "log", "md-5", "portable-atomic", - "rand 0.9.2", + "rand 0.8.5", "ring", "stun", "thiserror 1.0.61", @@ -9184,12 +9032,6 @@ 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" @@ -9335,12 +9177,6 @@ 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" @@ -9724,25 +9560,26 @@ dependencies = [ [[package]] name = "webrtc" -version = "0.14.0" +version = "0.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "08fd686c0920ac08f3a57eacc48e31f0e4ca1ffefba4478784606f78c14e83ad" +checksum = "24bab7195998d605c862772f90a452ba655b90a2f463c850ac032038890e367a" dependencies = [ "arc-swap", "async-trait", "bytes", - "dtls", + "cfg-if 1.0.0", "hex", "interceptor", "lazy_static", "log", "portable-atomic", - "rand 0.9.2", + "rand 0.8.5", "rcgen", "regex", "ring", "rtcp", "rtp", + "rustls", "sdp", "serde 1.0.228", "serde_json 1.0.118", @@ -9750,12 +9587,13 @@ 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", @@ -9766,9 +9604,9 @@ dependencies = [ [[package]] name = "webrtc-data" -version = "0.12.0" +version = "0.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "062a5438d63bb0756a221693d76cc0dd6119affee1dfdfe57abe3a2a8c8b3eea" +checksum = "4e97b932854da633a767eff0cc805425a2222fc6481e96f463e57b015d949d1d" dependencies = [ "bytes", "log", @@ -9780,17 +9618,54 @@ dependencies = [ ] [[package]] -name = "webrtc-ice" -version = "0.14.0" +name = "webrtc-dtls" +version = "0.12.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "69cb13fd1a373e68addc4bba0c8ca058627518e54342583d024bdcbb8ae5d97d" +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" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eb51bde0d790f109a15bfe4d04f1b56fb51d567da231643cb3f21bb74d678997" dependencies = [ "arc-swap", "async-trait", "crc", "log", "portable-atomic", - "rand 0.9.2", + "rand 0.8.5", "serde 1.0.228", "serde_json 1.0.118", "stun", @@ -9806,9 +9681,9 @@ dependencies = [ [[package]] name = "webrtc-mdns" -version = "0.10.0" +version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a17279a067e75df72ce923fdeb7f04cd808f6f5aa4910dc6bcb4fbe66b396ace" +checksum = "979cc85259c53b7b620803509d10d35e2546fa505d228850cbe3f08765ea6ea8" dependencies = [ "log", "socket2 0.5.10", @@ -9819,22 +9694,21 @@ dependencies = [ [[package]] name = "webrtc-media" -version = "0.11.0" +version = "0.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "94a84c910fec0848fd5a0d8a5651e0ddbdedaf25a7d3ae3f0b15f71ac73a1773" +checksum = "80041211deccda758a3e19aa93d6b10bc1d37c9183b519054b40a83691d13810" dependencies = [ "byteorder", "bytes", - "rand 0.9.2", + "rand 0.8.5", "rtp", "thiserror 1.0.61", ] [[package]] name = "webrtc-sctp" -version = "0.13.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f985465467d8910c1f8ac4382cd64f83b1f6a1a75021a82b221546f6fb3b856f" +version = "0.12.0" +source = "git+https://github.com/rustdesk-org/webrtc?rev=48100bf13e694d7e5bbb49b9a753dbad1c359d0c#48100bf13e694d7e5bbb49b9a753dbad1c359d0c" dependencies = [ "arc-swap", "async-trait", @@ -9842,7 +9716,7 @@ dependencies = [ "crc", "log", "portable-atomic", - "rand 0.9.2", + "rand 0.8.5", "thiserror 1.0.61", "tokio", "webrtc-util", @@ -9850,9 +9724,9 @@ dependencies = [ [[package]] name = "webrtc-srtp" -version = "0.16.0" +version = "0.15.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "66d8cdc33413f1d0192670a80ce93d17cb78d57fe3a2414be30d6f6dff121123" +checksum = "01e773f79b09b057ffbda6b03fe7b43403b012a240cf8d05d630674c3723b5bb" dependencies = [ "aead", "aes", @@ -9873,19 +9747,19 @@ dependencies = [ [[package]] name = "webrtc-util" -version = "0.12.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d1c0c7e0c8f280f2bbfae442701465777ac07adaf46ce0c5863cd58e13fe472a" +version = "0.11.0" +source = "git+https://github.com/rustdesk-org/webrtc?rev=48100bf13e694d7e5bbb49b9a753dbad1c359d0c#48100bf13e694d7e5bbb49b9a753dbad1c359d0c" dependencies = [ "async-trait", "bitflags 1.3.2", "bytes", "ipnet", "lazy_static", + "libc", "log", "nix 0.26.4", "portable-atomic", - "rand 0.9.2", + "rand 0.8.5", "thiserror 1.0.61", "tokio", "winapi 0.3.9", diff --git a/Cargo.toml b/Cargo.toml index b1d9b7f91..980723873 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -52,7 +52,7 @@ screencapturekit = ["cpal/screencapturekit"] [dependencies] async-trait = "0.1" scrap = { path = "libs/scrap", features = ["wayland"] } -hbb_common = { path = "libs/hbb_common" } +hbb_common = { path = "libs/hbb_common", features = ["webrtc"] } 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"} +kcp-sys= { git = "https://github.com/rustdesk-org/kcp-sys", branch = "rustdesk-patches" } 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,6 +215,19 @@ 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." @@ -234,6 +247,7 @@ os-version = "0.2" [dev-dependencies] hound = "3.5" docopt = "1.1" +tokio = { version = "1.44", features = ["test-util"] } [package.metadata.bundle] name = "RustDesk" diff --git a/build.rs b/build.rs index ec87831c0..28a7a5e45 100644 --- a/build.rs +++ b/build.rs @@ -43,6 +43,15 @@ 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" { @@ -89,5 +98,8 @@ 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"); } diff --git a/flutter/lib/common.dart b/flutter/lib/common.dart index 25eed4259..b80e0b5f9 100644 --- a/flutter/lib/common.dart +++ b/flutter/lib/common.dart @@ -1633,7 +1633,8 @@ String bool2option(String option, bool b) { String res; if (option.startsWith('enable-') && option != kOptionEnableUdpPunch && - option != kOptionEnableIpv6Punch) { + option != kOptionEnableIpv6Punch && + option != kOptionEnableWebrtc) { res = b ? defaultOptionYes : 'N'; } else if (option.startsWith('allow-') || option == kOptionStopService || diff --git a/flutter/lib/common/widgets/overlay.dart b/flutter/lib/common/widgets/overlay.dart index 3fb63616d..fc21ef8a6 100644 --- a/flutter/lib/common/widgets/overlay.dart +++ b/flutter/lib/common/widgets/overlay.dart @@ -606,6 +606,9 @@ class QualityMonitor extends StatelessWidget { _row( "Codec", qualityMonitorModel.data.codecFormat ?? '-'), _row("Chroma", qualityMonitorModel.data.chroma ?? '-'), + if (qualityMonitorModel.webrtcTransport != null) + _row("Transport", + qualityMonitorModel.webrtcTransport!), ], ), ) diff --git a/flutter/lib/consts.dart b/flutter/lib/consts.dart index 2b4ada7c7..20f50d218 100644 --- a/flutter/lib/consts.dart +++ b/flutter/lib/consts.dart @@ -172,10 +172,12 @@ 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"; diff --git a/flutter/lib/desktop/pages/desktop_setting_page.dart b/flutter/lib/desktop/pages/desktop_setting_page.dart index b8dd80ba7..cb41d701e 100644 --- a/flutter/lib/desktop/pages/desktop_setting_page.dart +++ b/flutter/lib/desktop/pages/desktop_setting_page.dart @@ -572,6 +572,12 @@ class _GeneralState extends State<_General> { kOptionDirectxCapture, ), if (!isWeb && !incomingOnly) ...[ + _OptionCheckBox( + context, + 'Enable TCP hole punching', + kOptionEnableTcpPunch, + isServer: false, + ), _OptionCheckBox( context, 'Enable UDP hole punching', @@ -584,6 +590,15 @@ 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( @@ -593,7 +608,6 @@ class _GeneralState extends State<_General> { isServer: false, ), ), - ], ]; // Add client-side wakelock option for desktop platforms diff --git a/flutter/lib/mobile/pages/settings_page.dart b/flutter/lib/mobile/pages/settings_page.dart index 434cff501..198613a1b 100644 --- a/flutter/lib/mobile/pages/settings_page.dart +++ b/flutter/lib/mobile/pages/settings_page.dart @@ -97,10 +97,12 @@ class _SettingsState extends State 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; @@ -141,8 +143,10 @@ class _SettingsState extends State 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 = @@ -815,31 +819,65 @@ class _SettingsState extends State 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: (v) async { - await mainSetLocalBoolOption(kOptionEnableUdpPunch, v); - final newValue = - mainGetLocalBoolOptionSync(kOptionEnableUdpPunch); - setState(() { - _enableUdpPunch = newValue; - }); - }, + onToggle: isOptionFixed(kOptionEnableUdpPunch) + ? null + : (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: (v) async { - await mainSetLocalBoolOption(kOptionEnableIpv6Punch, v); - final newValue = - mainGetLocalBoolOptionSync(kOptionEnableIpv6Punch); - setState(() { - _enableIpv6Punch = newValue; - }); - }, + 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; + }); + }, ), SettingsTile( title: Text(translate('Language')), diff --git a/flutter/lib/models/model.dart b/flutter/lib/models/model.dart index e22782034..56c4462ca 100644 --- a/flutter/lib/models/model.dart +++ b/flutter/lib/models/model.dart @@ -3597,6 +3597,16 @@ 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') == diff --git a/libs/hbb_common b/libs/hbb_common index f94e3fef6..470612bdf 160000 --- a/libs/hbb_common +++ b/libs/hbb_common @@ -1 +1 @@ -Subproject commit f94e3fef6c962814e71b7547848e06526b235062 +Subproject commit 470612bdfb41471a60920002b9762853bf993716 diff --git a/libs/scrap/examples/benchmark.rs b/libs/scrap/examples/benchmark.rs index a867a2d3f..74b3b5b86 100644 --- a/libs/scrap/examples/benchmark.rs +++ b/libs/scrap/examples/benchmark.rs @@ -143,7 +143,7 @@ fn test_vpx( println!( "{:?} encode: {:?}, {} byte", codec_id, - time_sum / yuv_count as _, + time_sum / yuv_count as u32, size / yuv_count ); @@ -156,7 +156,7 @@ fn test_vpx( println!( "{:?} decode: {:?}", codec_id, - start.elapsed() / yuv_count as _ + start.elapsed() / yuv_count as u32 ); } @@ -212,7 +212,7 @@ fn test_av1( assert_eq!(av1s.len(), yuv_count); println!( "AV1 encode: {:?}, {} byte", - time_sum / yuv_count as _, + time_sum / yuv_count as u32, 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 _); + println!("AV1 decode: {:?}", start.elapsed() / yuv_count as u32); } #[cfg(feature = "hwcodec")] diff --git a/src/client.rs b/src/client.rs index 0cd70189c..ce5ab152e 100644 --- a/src/client.rs +++ b/src/client.rs @@ -30,7 +30,7 @@ use uuid::Uuid; use crate::{ check_port, common::input::{MOUSE_BUTTON_LEFT, MOUSE_BUTTON_RIGHT, MOUSE_TYPE_DOWN, MOUSE_TYPE_UP}, - create_symmetric_key_msg, decode_id_pk, get_rs_pk, is_keyboard_mode_supported, + create_symmetric_key_msg, decode_id_pk, decode_id_pk_dtls, get_rs_pk, is_keyboard_mode_supported, kcp_stream::KcpStream, secure_tcp, ui_interface::{get_builtin_option, resolve_avatar_url, use_texture_render}, @@ -51,7 +51,7 @@ use hbb_common::{ CONNECT_TIMEOUT, READ_TIMEOUT, RELAY_PORT, RENDEZVOUS_PORT, RENDEZVOUS_SERVERS, }, fs::JobType, - futures::future::{select_ok, FutureExt}, + futures::future::{select_ok, BoxFuture, FutureExt}, get_version_number, log, message_proto::{option_message::BoolOption, *}, protobuf::{Message as _, MessageField}, @@ -65,11 +65,12 @@ use hbb_common::{ self, net::UdpSocket, sync::{ - mpsc::{unbounded_channel, UnboundedReceiver}, + mpsc::{error::TryRecvError, unbounded_channel, UnboundedReceiver}, oneshot, }, time::{interval, Duration, Instant}, }, + webrtc::WebRTCStream, AddrMangle, ResultType, Stream, }; pub use helper::*; @@ -174,6 +175,177 @@ pub fn get_key_state(key: enigo::Key) -> bool { ENIGO.lock().unwrap().get_key_state(key) } +/// Closes an unadopted WebRTC offerer's pc on drop. Without an answer it stays in ICE `New` +/// forever, so its state handler never fires to self-remove it from `SESSIONS`; this covers the +/// early returns and cancelled races that would leak it. `into_inner` disarms on adoption. +struct OffererGuard(Option); + +impl OffererGuard { + fn new(stream: WebRTCStream) -> Self { + Self(Some(stream)) + } + + fn stream(&self) -> Option<&WebRTCStream> { + self.0.as_ref() + } + + fn into_inner(mut self) -> Option { + self.0.take() + } +} + +impl Drop for OffererGuard { + fn drop(&mut self) { + if let Some(stream) = self.0.take() { + stream.close_detached(); + } + } +} + +/// Race WebRTC against the other transports, preferring P2P: `select_ok` would always pick the +/// relay, whose TCP connect beats ICE + DTLS + SCTP by an order of magnitude. An `is_p2p` result +/// wins outright; a relayed one — from either side, since `webrtc_fut` is a whole punch attempt +/// that can also end in a relay — is held for `window_ms` to give the other side a chance. +/// +/// `others` must be non-empty (`select_ok` requires it). +async fn race_transports_prefer_webrtc<'a, T: 'a>( + webrtc_fut: BoxFuture<'a, ResultType>, + others: Vec>>, + window_ms: u64, + is_p2p: impl Fn(&T) -> bool, +) -> ResultType { + let mut webrtc_fut = Some(webrtc_fut); + let mut others_fut = Some(select_ok(others)); + let mut held: Option = None; + let mut webrtc_err: Option = None; + let mut others_err: Option = None; + let window = tokio::time::sleep(Duration::from_millis(window_ms)); + tokio::pin!(window); + let mut window_started = false; + loop { + tokio::select! { + res = async { + match webrtc_fut.as_mut() { + Some(fut) => fut.await, + None => std::future::pending().await, + } + }, if webrtc_fut.is_some() => { + webrtc_fut = None; + match res { + // A direct connection is the outcome this race exists to protect: commit it + // outright, and a held relay conn just drops. + Ok(conn) if is_p2p(&conn) || others_fut.is_none() => return Ok(conn), + // `webrtc_fut` is a whole punch attempt, not just the WebRTC connect, so it + // can end in a relay of its own. Committing that immediately would preempt a + // direct punch still in flight on the other branch — the exact inversion this + // function exists to prevent — so hold it on the same terms as any relay. + Ok(conn) => { + if held.is_none() { + held = Some(conn); + window.as_mut().reset( + Instant::now() + Duration::from_millis(window_ms), + ); + window_started = true; + } + } + Err(e) => { + // Commit a held relay only when nothing direct is still racing; otherwise + // keep it and let the survivor (or the window) decide. + if others_fut.is_none() { + if let Some(conn) = held.take() { + return Ok(conn); + } + } + match others_err.take() { + Some(oe) => bail!("WebRTC failed: {}; fallback failed: {}", e, oe), + None if others_fut.is_none() => bail!("WebRTC failed: {}", e), + None => webrtc_err = Some(e), + } + } + } + } + res = async { + match others_fut.as_mut() { + Some(fut) => fut.await, + None => std::future::pending().await, + } + }, if others_fut.is_some() => { + others_fut = None; + match res { + Ok((conn, unfinished)) => { + if is_p2p(&conn) { + return Ok(conn); + } + // Relayed: commit now only if nothing direct can still arrive. If a + // direct attempt is still in flight (here or in `unfinished`), hold it + // and keep racing for the preference window instead of discarding them. + if webrtc_fut.is_none() && unfinished.is_empty() { + return Ok(conn); + } + if held.is_none() { + held = Some(conn); + window.as_mut().reset( + Instant::now() + Duration::from_millis(window_ms), + ); + window_started = true; + } + if !unfinished.is_empty() { + others_fut = Some(select_ok(unfinished)); + } + } + Err(e) => match webrtc_err.take() { + // Nothing more can win, but a parked relay is still a valid outcome — take + // it before failing the connection. + Some(we) => match held.take() { + Some(conn) => return Ok(conn), + None => bail!("WebRTC failed: {}; fallback failed: {}", we, e), + }, + None if webrtc_fut.is_none() => match held.take() { + Some(conn) => return Ok(conn), + None => return Err(e), + }, + None => others_err = Some(e), + }, + } + } + _ = &mut window, if window_started => { + if let Some(conn) = held.take() { + return Ok(conn); + } + window_started = false; + } + } + } +} + +// A peer decides how many ICE candidates it sends, and the rendezvous route that carries them is +// reachable without a prior punch, so these sites would otherwise let someone else set how much +// this machine writes to its log file. One line a minute each, carrying the suppressed count. +use hbb_common::log_throttle::LogThrottle; +const ICE_LOG_INTERVAL: Duration = Duration::from_secs(60); +static REJECTED_ICE_LOG: LogThrottle = LogThrottle::new(ICE_LOG_INTERVAL); +static UDP_UAT_ERR_LOG: LogThrottle = LogThrottle::new(ICE_LOG_INTERVAL); +static UNEXPECTED_ICE_LOG: LogThrottle = LogThrottle::new(ICE_LOG_INTERVAL); +static PENDING_ICE_FULL_LOG: LogThrottle = LogThrottle::new(ICE_LOG_INTERVAL); + +fn request_allows_tcp_punch(webrtc_sdp_offer: &str) -> bool { + // WebRTC trickle ICE retains the rendezvous socket as its signaling bridge. Only a request + // without an offer may close that socket and reuse its local address for TCP punching. + webrtc_sdp_offer.is_empty() +} + +/// TCP punch is a user option like the other direct transports, but it is also the backstop: +/// with every direct transport switched off there would be nothing left to punch with, so it +/// runs regardless. Only the switches decide that — a transport that is enabled but fails to +/// materialize (no public v6 address, offerer setup error) leaves this alone, because the +/// relay fallback already covers a round that ends up with no usable direct transport. +fn tcp_punch_allowed() -> bool { + crate::get_tcp_punch_enabled() + || !(crate::get_udp_punch_enabled() + || crate::get_ipv6_punch_enabled() + || crate::get_webrtc_enabled()) +} + impl Client { const CLIENT_CLIPBOARD_NAME: &'static str = "client-clipboard"; @@ -296,7 +468,9 @@ impl Client { } }; - if crate::get_ipv6_punch_enabled() { + // Same relay gate as the v6 socket below: under any forced relay the v6 punch cannot + // be used, so probing v6 reachability is wasted work on every such connection. + if crate::get_ipv6_punch_enabled() && !interface.is_force_relay() { crate::test_ipv6().await; } @@ -320,6 +494,31 @@ impl Client { } else { (None, None) }; + // Under force-relay a direct IPv6 path is not allowed, so don't bind the v6 socket; + // the controlled side likewise skips v6 when relaying. + let ipv6 = if crate::get_ipv6_punch_enabled() && !interface.is_force_relay() { + crate::get_ipv6_socket().await + } else { + None + }; + // WebRTC uses its own ICE sockets and does not depend on the legacy UDP punch socket. + // When this request carries an offer, `_start_inner` keeps its rendezvous socket solely + // for trickle signaling; a separate offer-less request owns any TCP punch attempt. + let webrtc_offerer = if Self::should_create_webrtc_offerer(&interface) { + // ICE policy follows relay-by-POLICY, not force_relay: under WebSocket the + // latter is set for the classic paths, but ICE opens its own sockets and may + // still go direct - that is the only P2P path ws deployments have. + match WebRTCStream::new("", interface.is_policy_relay(), CONNECT_TIMEOUT).await { + Ok(stream) => Some(stream), + Err(err) => { + log::warn!("webrtc offerer setup failed: {}", err); + None + } + } + } else { + None + }; + let has_webrtc_offerer = webrtc_offerer.is_some(); let fut = Self::_start_inner( peer.to_owned(), key.to_owned(), @@ -328,16 +527,27 @@ impl Client { interface.clone(), udp.clone(), Some(stop_udp_tx), + ipv6, + webrtc_offerer, rendezvous_server.clone(), servers.clone(), contained, ); - if udp.0.is_none() { + // The fallback request exists only to carry a TCP punch, so it is pointless once TCP + // punch is off — it would reach `connect()` with nothing to try and just open a second + // relay. + if interface.is_force_relay() + || (udp.0.is_none() && !has_webrtc_offerer) + || !tcp_punch_allowed() + { return fut.await; } - let mut connect_futures = Vec::new(); - connect_futures.push(fut.boxed()); - let fut = Self::_start_inner( + let preferred_fut = fut.boxed(); + // This is deliberately a pure TCP punch request: its WebRTC argument must stay `None`. + // TCP punching closes the rendezvous socket before binding a new connection to the same + // local address; a WebRTC ICE bridge would retain that socket and break the port reuse. + // The preferred request retains its own socket for WebRTC signaling. + let fallback_fut = Self::_start_inner( peer.to_owned(), key.to_owned(), token.to_owned(), @@ -345,17 +555,208 @@ impl Client { interface, (None, None), None, + None, + None, rendezvous_server, servers, contained, - ); - connect_futures.push(fut.boxed()); + ) + .boxed(); + if has_webrtc_offerer { + return race_transports_prefer_webrtc( + preferred_fut, + vec![fallback_fut], + Self::WEBRTC_PREFER_WINDOW_MS, + |result| result.0 .1, + ) + .await; + } + let connect_futures = vec![preferred_fut, fallback_fut]; match select_ok(connect_futures).await { Ok(conn) => Ok((conn.0 .0, conn.0 .1, conn.0 .2)), Err(e) => Err(e), } } + fn is_expected_webrtc_ice_candidate(ice: &IceCandidate, session_key: &str) -> bool { + !session_key.is_empty() && ice.session_key == session_key && !ice.candidate.is_empty() + } + + /// Whether to build a WebRTC offerer for this connection. + /// + /// A SOCKS proxy rules it out: ICE binds its own UDP sockets and speaks STUN directly, past + /// the proxy and with the real IP. Relay-by-policy without TURN rules it out too, since + /// Relay-only ICE can then gather nothing. WebSocket does not: it tunnels only the signaling + /// and relay legs, so the offer keeps full ICE and direct is exactly what it is there for. + fn should_create_webrtc_offerer(interface: &impl Interface) -> bool { + if !crate::get_webrtc_enabled() { + return false; + } + if Config::is_proxy() { + return false; + } + if interface.is_policy_relay() && !WebRTCStream::has_turn_server() { + return false; + } + true + } + + /// Max ICE candidates buffered during the punch window before the answer is applied. + /// Bounds memory if a misbehaving rendezvous floods candidates. On overflow the oldest is + /// evicted: gathering order is host, then srflx, then relay, so the newest arrivals are the + /// ones that traverse NAT. + const MAX_PENDING_WEBRTC_ICE: usize = 64; + + /// Prefer-P2P window: how long a WebRTC attempt outranks an already-established relay + /// result, and the floor for a punch-path WebRTC attempt whose race timeout is tuned for a + /// raw TCP SYN. Long enough for candidate trickle + ICE checks + DTLS on high-latency + /// links; short enough that UDP-blocked networks settle on relay without a noticeable wait. + const WEBRTC_PREFER_WINDOW_MS: u64 = 2500; + + /// UDP-NAT-test wait when the TCP clock is implausible (see TCP_RTT_PLAUSIBLE_MIN). The + /// normal bound is `rtt / 2`: the test has been running since before the TCP connect, so on + /// a network where TCP RTT ~ UDP RTT its response has already landed. A transparent TCP + /// proxy — a TUN-mode VPN on the host, or a redirect-mode proxy on the LAN gateway (soft + /// router), which fakes the handshake for every device behind it — breaks that by answering + /// in ~3ms while the real UDP round trip is hundreds of ms: the window collapsed to ~1.5ms, + /// udp_port stayed 0, and UDP punch never ran on such networks. The wait still exits the instant the port + /// arrives, so a genuinely nearby server (LAN hbbs) pays nothing; only UDP-dead networks + /// wait out the full grace, and only on this round — the pure-TCP fallback round never + /// waits. Sized as a ceiling on real-world rendezvous RTTs plus one 20ms retransmit + /// (intercontinental ~300ms); paths slower than that lose UDP punch under a proxy, which + /// is today's behavior, not a regression. + const UDP_NAT_TEST_GRACE: Duration = Duration::from_millis(400); + + /// Below this, the measured TCP connect time is not a believable WAN round trip — it was + /// answered inside the LAN (host TUN proxy, gateway transparent proxy, or a genuinely local + /// server) — and must not be used to size the UDP window. + /// Generous on purpose: over-triggering costs nothing (the wait exits on arrival, and a + /// UDP-dead round loses to the racing fallback anyway), while a tight bound would let a + /// busy proxy's occasional ~80ms handshake slip through and silently drop UDP punch. + const TCP_RTT_PLAUSIBLE_MIN: Duration = Duration::from_millis(100); + + /// Delay before re-sending an ICE candidate over the rendezvous route once. The hop to the + /// peer can be UDP (the controlled side's mediator channel), so a candidate can be lost in + /// flight; the remote ICE agent dedups repeats, so the second copy is free. + const WEBRTC_ICE_RESEND_DELAY: Duration = Duration::from_millis(400); + + /// Bridge local ICE candidates to the peer over the punch socket, and feed the peer's back + /// into the pc. + /// + /// Never reconnect this socket: its address *is* the return route (the server mangles it into + /// `PunchHole.socket_addr` and resolves the echo through `tcp_punch`), so a new address is one + /// nothing points at. Once it dies, both directions are dead — abandon WebRTC, do not retry. + fn spawn_webrtc_ice_bridge( + mut socket: Stream, + mut local_ice_rx: Option>, + webrtc: WebRTCStream, + peer: String, + session_key: String, + ) -> oneshot::Sender<()> { + let (stop_tx, mut stop_rx) = oneshot::channel::<()>(); + tokio::spawn(async move { + let mut pending_resend: Vec<(Instant, RendezvousMessage)> = Vec::new(); + loop { + match stop_rx.try_recv() { + Ok(_) | Err(tokio::sync::oneshot::error::TryRecvError::Closed) => break, + Err(tokio::sync::oneshot::error::TryRecvError::Empty) => {} + } + + if let Some(rx) = local_ice_rx.as_mut() { + loop { + match rx.try_recv() { + Ok(candidate) => { + let mut msg = RendezvousMessage::new(); + msg.set_ice_candidate(IceCandidate { + id: peer.clone(), + session_key: session_key.clone(), + candidate, + ..Default::default() + }); + // Bound the send so a stalled rendezvous socket cannot block the + // bridge past its stop signal. + match timeout(3000, socket.send(&msg)).await { + Ok(Ok(())) => {} + Ok(Err(err)) => { + log::warn!("failed to send WebRTC ICE candidate: {}", err); + return; + } + Err(_) => { + log::warn!("WebRTC ICE candidate send timed out"); + return; + } + } + pending_resend.push((Instant::now(), msg)); + } + Err(TryRecvError::Empty) => break, + Err(TryRecvError::Disconnected) => { + local_ice_rx = None; + break; + } + } + } + } + + // Re-send each candidate once after a short delay: the rendezvous hop to the peer + // can be UDP, so the first copy may be lost; the remote ICE agent dedups repeats. + let mut i = 0; + while i < pending_resend.len() { + if pending_resend[i].0.elapsed() >= Self::WEBRTC_ICE_RESEND_DELAY { + let (_, msg) = pending_resend.swap_remove(i); + match timeout(3000, socket.send(&msg)).await { + Ok(Ok(())) => {} + Ok(Err(err)) => { + log::warn!("failed to re-send WebRTC ICE candidate: {}", err); + return; + } + Err(_) => { + log::warn!("WebRTC ICE candidate re-send timed out"); + return; + } + } + } else { + i += 1; + } + } + + // Read one incoming message, blocking up to the poll window. Distinguish a real + // timeout (keep looping to drain outbound candidates) from stream EOF/error: the + // rendezvous server closes the punch connection after the response, and an + // unrecognized-message server closes it on the first candidate we send. Without + // this, the collapsed None-on-EOF made the loop hot-spin a core until stop. + match timeout(100, socket.next()).await { + Err(_) => {} + Ok(None) => break, + Ok(Some(Ok(bytes))) => { + if let Ok(msg_in) = RendezvousMessage::parse_from_bytes(&bytes) { + if let Some(rendezvous_message::Union::IceCandidate(ice)) = msg_in.union + { + if Self::is_expected_webrtc_ice_candidate(&ice, &session_key) { + if let Err(err) = + webrtc.add_remote_ice_candidate(&ice.candidate).await + { + if let Some(n) = REJECTED_ICE_LOG.due() { + log::warn!( + "failed to add {} WebRTC ICE candidate(s), last: {}", + n, + err + ); + } + } + } + } + } + } + Ok(Some(Err(err))) => { + log::debug!("WebRTC ICE bridge socket read ended: {}", err); + break; + } + } + } + }); + stop_tx + } + async fn _start_inner( peer: String, key: String, @@ -364,6 +765,8 @@ impl Client { interface: impl Interface, mut udp: (Option>, Option>>), stop_udp_tx: Option>, + mut ipv6: Option<(Arc, bytes::Bytes)>, + webrtc_offerer: Option, mut rendezvous_server: String, servers: Vec, contained: bool, @@ -378,6 +781,10 @@ impl Client { (i32, String), bool, )> { + // Wrap the offerer so any early return below (?/bail) or cancellation of this future by + // the outer select_ok closes its pc instead of leaking it in SESSIONS. Disarmed via + // into_inner() once the stream is adopted into a connection attempt. + let mut webrtc_offerer = webrtc_offerer.map(OffererGuard::new); let mut start = Instant::now(); let mut socket = connect_tcp(&*rendezvous_server, CONNECT_TIMEOUT).await; debug_assert!(!servers.contains(&rendezvous_server)); @@ -421,13 +828,20 @@ impl Client { .map_err(|e| anyhow!("Failed to secure tcp: {}", e))?; } else if let Some(udp) = udp.1.as_ref() { let tm = Instant::now(); + // rtt is the TCP connect time. When it is too short to be a real WAN round trip it + // says nothing about the UDP path (a TUN VPN or the LAN gateway answered the + // handshake, not the server), so fall back to the flat grace; otherwise trust it. + let udp_nat_wait = if rtt < Self::TCP_RTT_PLAUSIBLE_MIN { + Self::UDP_NAT_TEST_GRACE + } else { + rtt / 2 + }; loop { let port = *udp.lock().unwrap(); if port > 0 { break; } - // await for 0.5 RTT - if tm.elapsed() > rtt / 2 { + if tm.elapsed() > udp_nat_wait { break; } hbb_common::sleep(0.001).await; @@ -436,17 +850,39 @@ impl Client { // Stop UDP NAT test task if still running stop_udp_tx.map(|tx| tx.send(())); let mut msg_out = RendezvousMessage::new(); - let mut ipv6 = if crate::get_ipv6_punch_enabled() { - if let Some((socket, addr)) = crate::get_ipv6_socket().await { - (Some(socket), Some(addr)) - } else { - (None, None) - } - } else { - (None, None) - }; + let mut ipv6 = ipv6 + .take() + .map(|(socket, addr)| (Some(socket), Some(addr))) + .unwrap_or((None, None)); let udp_nat_port = udp.1.map(|x| *x.lock().unwrap()).unwrap_or(0); - let punch_type = if udp_nat_port > 0 { "UDP" } else { "TCP" }; + let webrtc_sdp_offer = webrtc_offerer + .as_ref() + .and_then(|g| g.stream()) + .map(|stream| stream.local_endpoint().to_owned()) + .unwrap_or_default(); + let allow_tcp_punch = tcp_punch_allowed() && request_allows_tcp_punch(&webrtc_sdp_offer); + // Every direct transport this round carries, not one of them: a round can carry several + // at once (a NAT port and an offer and a v6 address), and since the TCP punch became a + // switch it can carry none — a single name had to misreport both. `relay` is not a punch, + // it is what a round with nothing to punch with can still end as. + let mut transports = Vec::new(); + if udp_nat_port > 0 { + transports.push("UDP"); + } + if allow_tcp_punch { + transports.push("TCP"); + } + if ipv6.1.is_some() { + transports.push("IPv6"); + } + if !webrtc_sdp_offer.is_empty() { + transports.push("WebRTC"); + } + let punch_type = if transports.is_empty() { + "Relay".to_owned() + } else { + transports.join("+") + }; msg_out.set_punch_hole_request(PunchHoleRequest { id: peer.to_owned(), token: token.to_owned(), @@ -458,9 +894,20 @@ impl Client { force_relay: interface.is_force_relay(), socket_addr_v6: ipv6.1.unwrap_or_default(), switch_code, + // The offer's envelope itself declares its ICE policy (`ice_policy: "all"` under + // pure ws), telling the controlled side its answer may gather every candidate + // type despite force_relay instead of requiring TURN. + webrtc_sdp_offer, ..Default::default() }); - for i in 1..=3 { + let webrtc_session_key = webrtc_offerer + .as_ref() + .and_then(|guard| guard.stream()) + .map(|stream| stream.session_key().to_owned()) + .unwrap_or_default(); + let mut webrtc_sdp_answer = String::new(); + let mut pending_webrtc_ice = Vec::::new(); + 'punch_attempts: for i in 1..=3 { log::info!( "#{} {} punch attempt with {}, id: {}", i, @@ -470,9 +917,20 @@ impl Client { ); socket.send(&msg_out).await?; // below timeout should not bigger than hbbs's connection timeout. - if let Some(msg_in) = - crate::get_next_nonkeyexchange_msg(&mut socket, Some(i * 3000)).await - { + let attempt_deadline = Instant::now() + Duration::from_millis((i * 3000) as u64); + loop { + let remaining = attempt_deadline.saturating_duration_since(Instant::now()); + if remaining.is_zero() { + break; + } + let timeout_ms = remaining + .as_millis() + .clamp(1, u64::MAX as u128) as u64; + let Some(msg_in) = + crate::get_next_nonkeyexchange_msg(&mut socket, Some(timeout_ms)).await + else { + break; + }; match msg_in.union { Some(rendezvous_message::Union::PunchHoleResponse(ph)) => { if ph.socket_addr.is_empty() { @@ -501,8 +959,9 @@ impl Client { relay_server = ph.relay_server; peer_addr = AddrMangle::decode(&ph.socket_addr); feedback = ph.feedback; + webrtc_sdp_answer = ph.webrtc_sdp_answer; let s = udp.0.take(); - if ph.is_udp && s.is_some() { + if udp_nat_port > 0 && ph.is_udp && s.is_some() { if let Some(s) = s { allow_err!(s.connect(peer_addr).await); udp.0 = Some(s); @@ -519,7 +978,7 @@ impl Client { } } log::info!("{} Hole Punched {} = {}", punch_type, peer, peer_addr); - break; + break 'punch_attempts; } } Some(rendezvous_message::Union::RelayResponse(rr)) => { @@ -534,12 +993,70 @@ impl Client { let addr = AddrMangle::decode(&rr.socket_addr_v6); if addr.port() > 0 { if s.connect(addr).await.is_ok() { - connect_futures - .push(udp_nat_connect(s, "IPv6", CONNECT_TIMEOUT).boxed()); + connect_futures.push( + async move { + let (conn, kcp, typ) = + udp_nat_connect(s, "IPv6", CONNECT_TIMEOUT).await?; + Ok((conn, kcp, typ, true)) + } + .boxed(), + ); } } } signed_id_pk = rr.pk().into(); + let mut webrtc_bridge_stop = None; + let mut webrtc_for_connect = None; + if !rr.webrtc_sdp_answer.is_empty() { + if let Some(guard) = webrtc_offerer.take() { + // Run the awaited setup on the guard's borrowed stream so a + // cancellation during these awaits still closes the pc via the + // guard's drop; take ownership only at the synchronous handoff. + let setup_ok = if let Some(webrtc) = guard.stream() { + if let Err(err) = + webrtc.set_remote_endpoint(&rr.webrtc_sdp_answer).await + { + log::warn!("failed to set WebRTC relay answer: {}", err); + false + } else { + for candidate in pending_webrtc_ice.drain(..) { + if let Err(err) = + webrtc.add_remote_ice_candidate(&candidate).await + { + log::warn!( + "failed to add buffered WebRTC ICE candidate: {}", + err + ); + } + } + true + } + } else { + false + }; + if let Some(webrtc) = setup_ok.then(|| guard.into_inner()).flatten() + { + let session_key = webrtc.session_key().to_owned(); + let local_ice_rx = webrtc.take_local_ice_rx(); + webrtc_bridge_stop = Some(Self::spawn_webrtc_ice_bridge( + socket, + local_ice_rx, + webrtc.clone(), + peer.clone(), + session_key, + )); + webrtc_for_connect = Some(webrtc); + } + // If setup failed, `guard` drops here and closes the pc. + } + } + // An offerer not adopted into the relay race (empty answer) is closed by + // the guard's drop here. + drop(webrtc_offerer.take()); + // Keep relay_server for a WebRTC secure-failure fallback: request_relay + // coordinates a FRESH uuid via the rendezvous server, so it works even if + // the raced create_relay already consumed the original uuid pairing. + let relay_server_rr = rr.relay_server.clone(); let fut = Self::create_relay( &peer, rr.uuid, @@ -551,35 +1068,221 @@ impl Client { connect_futures.push( async move { let conn = fut.await?; - Ok((conn, None, if use_ws() { "WebSocket" } else { "Relay" })) + Ok(( + conn, + None, + if use_ws() { "WebSocket" } else { "Relay" }, + false, + )) } .boxed(), ); - // Run all connection attempts concurrently, return the first successful one - let (conn, kcp, typ) = match select_ok(connect_futures).await { - Ok(conn) => (Ok(conn.0 .0), conn.0 .1, conn.0 .2), - - Err(e) => (Err(e), None, ""), + // Keep the adopted offerer in a guard that stays armed across the race AND + // secure_connection, so cancellation of this future by the outer race (or a + // secure-handshake failure) closes the pc instead of leaking it. It is + // disarmed only once WebRTC is confirmed the winning, secured transport. + let mut webrtc_guard = None; + let race_result = if let Some(webrtc) = webrtc_for_connect { + webrtc_guard = Some(OffererGuard::new(webrtc.clone())); + let mut raced = webrtc; + let webrtc_fut = async move { + raced.wait_connected(CONNECT_TIMEOUT).await?; + // Resolve relayed-ness here, not from the label: WebRTC is only a + // P2P path when ICE nominated a non-TURN pair, and the race has to + // know which it got. Committing a TURN pair as if it were direct + // cancels a genuine direct attempt still in flight — the same + // inversion the preference window exists to prevent, one level up. + let relayed = raced.is_relayed().await.unwrap_or(true); + Ok((Stream::WebRTC(raced), None, "WebRTC", !relayed)) + } + .boxed(); + if interface.is_policy_relay() { + // Relay-only WebRTC can use only TURN, so it has no P2P advantage + // over the RustDesk relay. Take the first successful relay instead + // of delaying an already-ready result for the preference window. + // Policy, not force_relay: under ws the offer is full ICE and a + // direct path is exactly what the preference window exists for. + connect_futures.push(webrtc_fut); + select_ok(connect_futures).await.map(|r| r.0) + } else { + // The peer answered WebRTC: prefer P2P. The relay result is held + // for the preference window so WebRTC can win even though a relay + // TCP connect completes much faster than ICE + DTLS setup. + race_transports_prefer_webrtc( + webrtc_fut, + connect_futures, + Self::WEBRTC_PREFER_WINDOW_MS, + |result| result.3, + ) + .await + } + } else { + // Run all connection attempts concurrently, take the first success. + select_ok(connect_futures).await.map(|r| r.0) }; - let mut conn = conn?; + if let Some(stop) = webrtc_bridge_stop { + let _ = stop.send(()); + } + // The ? / secure_connection failures below return early; webrtc_guard stays + // in scope and closes the offerer on any such exit (loss, error, cancellation). + let (mut conn, kcp, mut typ, mut direct) = race_result?; feedback = rr.feedback; log::info!("{:?} used to establish {typ} connection", start.elapsed()); - let pk = - Self::secure_connection(&peer, signed_id_pk, &key, &mut conn).await?; + let pk = match Self::secure_connection( + &peer, + signed_id_pk.clone(), + &key, + &mut conn, + ) + .await + { + Ok(pk) => pk, + Err(e) if typ == "WebRTC" => { + // WebRTC won the race but identity/DTLS binding failed. Fall back + // to a freshly-coordinated relay (request_relay negotiates a new + // uuid, immune to the raced create_relay having consumed the + // original pairing) so a bad WebRTC handshake does not kill the + // whole session when relay is available. + log::warn!( + "WebRTC secure handshake failed ({}), falling back to relay", + e + ); + drop(webrtc_guard.take()); + let mut relay_conn = Self::request_relay( + &peer, + relay_server_rr, + &rendezvous_server, + !signed_id_pk.is_empty(), + &key, + &token, + conn_type, + &interface.get_switch_code(), + ) + .await + .map_err(|relay_e| { + anyhow!( + "WebRTC secure failed ({}); relay fallback also failed: {}", + e, + relay_e + ) + })?; + let pk = Self::secure_connection( + &peer, + signed_id_pk, + &key, + &mut relay_conn, + ) + .await?; + conn = relay_conn; + typ = if use_ws() { "WebSocket" } else { "Relay" }; + // The transport is now a relay: the WebRTC win it replaced must + // not carry its direct flag into the return, or the relay is + // reported P2P and the outer race treats it as one. + direct = false; + pk + } + Err(e) => return Err(e), + }; + // `direct` came from the winning future, which resolved it while the pc was + // definitely alive — the race needed it to pick a winner at all. + // Secured and WebRTC won: disarm so the returned conn keeps the pc alive. + if typ == "WebRTC" { + if let Some(guard) = webrtc_guard.take() { + let _ = guard.into_inner(); + } + } return Ok(( - (conn, typ == "IPv6", pk, kcp, typ), + (conn, direct, pk, kcp, typ), (feedback, rendezvous_server), false, )); } + Some(rendezvous_message::Union::IceCandidate(ice)) => { + if Self::is_expected_webrtc_ice_candidate(&ice, &webrtc_session_key) { + // Evict the oldest, not the newest. Candidates arrive in gathering + // order — host first, then srflx, then relay — so dropping arrivals + // would discard exactly the ones that traverse NAT and keep the + // host ones that only work on a shared LAN. + if pending_webrtc_ice.len() >= Self::MAX_PENDING_WEBRTC_ICE { + if let Some(n) = PENDING_ICE_FULL_LOG.due() { + log::warn!( + "WebRTC ICE pending buffer full ({}), evicted {} oldest", + Self::MAX_PENDING_WEBRTC_ICE, + n + ); + } + pending_webrtc_ice.remove(0); + } + pending_webrtc_ice.push(ice.candidate); + } else if let Some(n) = UNEXPECTED_ICE_LOG.due() { + log::debug!( + "dropped {} ICE candidate(s) for unexpected WebRTC session key, last: {}", + n, + ice.session_key, + ); + } + } _ => { log::error!("Unexpected protobuf msg received: {:?}", msg_in); } } } } - drop(socket); + let mut webrtc_bridge_stop = None; + let mut webrtc_for_connect = None; + if !webrtc_sdp_answer.is_empty() { + if let Some(guard) = webrtc_offerer.take() { + // Run the awaited setup on the guard's borrowed stream so a cancellation during + // these awaits still closes the pc via the guard's drop; take ownership only at + // the synchronous handoff below. + let setup_ok = if let Some(webrtc) = guard.stream() { + if let Err(err) = webrtc.set_remote_endpoint(&webrtc_sdp_answer).await { + log::warn!("failed to set WebRTC answer: {}", err); + false + } else { + for candidate in pending_webrtc_ice.drain(..) { + if let Err(err) = webrtc.add_remote_ice_candidate(&candidate).await { + log::warn!("failed to add buffered WebRTC ICE candidate: {}", err); + } + } + true + } + } else { + false + }; + if let Some(webrtc) = setup_ok.then(|| guard.into_inner()).flatten() { + let session_key = webrtc.session_key().to_owned(); + let local_ice_rx = webrtc.take_local_ice_rx(); + webrtc_bridge_stop = Some(Self::spawn_webrtc_ice_bridge( + socket, + local_ice_rx, + webrtc.clone(), + peer.clone(), + session_key, + )); + webrtc_for_connect = Some(webrtc); + } else { + // setup failed (guard dropped -> pc closed) or no stream: release the socket. + drop(socket); + } + } else { + drop(socket); + } + } else { + drop(socket); + } + // An offerer never adopted into a connection attempt (e.g. the peer returned no WebRTC + // answer) is closed by the guard's drop here, so its pc does not linger in SESSIONS. + drop(webrtc_offerer.take()); if peer_addr.port() == 0 { + // Bailing before connect(): an offerer already adopted into webrtc_for_connect was + // disarmed out of its guard, so close it (and stop its bridge) explicitly here. + if let Some(webrtc) = webrtc_for_connect.take() { + webrtc.close_detached(); + } + if let Some(stop) = webrtc_bridge_stop.take() { + let _ = stop.send(()); + } bail!("Failed to connect via rendezvous server"); } let time_used = start.elapsed().as_millis() as u64; @@ -612,7 +1315,10 @@ impl Client { interface, udp.0, ipv6.0, - punch_type, + webrtc_for_connect, + webrtc_bridge_stop, + allow_tcp_punch, + &punch_type, ) .await?, (feedback, rendezvous_server), @@ -638,6 +1344,9 @@ impl Client { interface: impl Interface, udp_socket_nat: Option>, udp_socket_v6: Option>, + webrtc_offerer: Option, + webrtc_bridge_stop: Option>, + allow_tcp_punch: bool, punch_type: &str, ) -> ResultType<( Stream, @@ -646,6 +1355,10 @@ impl Client { Option, &'static str, )> { + // Guard the offerer for the whole of connect(): any early return — cancellation during the + // awaits below, the relay override, or a secure_connection failure — closes its pc via the + // guard's drop. Disarmed only once WebRTC is the confirmed winning, secured transport. + let mut webrtc_guard = webrtc_offerer.map(OffererGuard::new); let direct_failures = interface.get_lch().read().unwrap().direct_failures; let mut connect_timeout = 0; const MIN: u64 = 1000; @@ -681,29 +1394,93 @@ impl Client { log::info!("peer address: {}, timeout: {}", peer, connect_timeout); let start = std::time::Instant::now(); - let mut connect_futures = Vec::new(); - let fut = connect_tcp_local(peer, Some(local_addr), connect_timeout); - connect_futures.push( - async move { - let conn = fut.await?; - Ok((conn, None, "TCP")) - } - .boxed(), - ); + // Each attempt carries whether its path is direct (4th field). TCP/UDP/IPv6 punch are + // always direct; WebRTC is direct only when ICE nominated a non-TURN pair. + let mut direct_futures = Vec::new(); + if allow_tcp_punch { + let fut = connect_tcp_local(peer, Some(local_addr), connect_timeout); + direct_futures.push( + async move { + let conn = fut.await?; + Ok((conn, None, "TCP", true)) + } + .boxed(), + ); + } if let Some(udp_socket_nat) = udp_socket_nat { - connect_futures.push(udp_nat_connect(udp_socket_nat, "UDP", connect_timeout).boxed()); + direct_futures.push( + async move { + let (conn, kcp, typ) = + udp_nat_connect(udp_socket_nat, "UDP", connect_timeout).await?; + Ok((conn, kcp, typ, true)) + } + .boxed(), + ); } if let Some(udp_socket_v6) = udp_socket_v6 { - connect_futures.push(udp_nat_connect(udp_socket_v6, "IPv6", connect_timeout).boxed()); + direct_futures.push( + async move { + let (conn, kcp, typ) = + udp_nat_connect(udp_socket_v6, "IPv6", connect_timeout).await?; + Ok((conn, kcp, typ, true)) + } + .boxed(), + ); } - // Run all connection attempts concurrently, return the first successful one - let (mut conn, kcp, mut typ) = match select_ok(connect_futures).await { - Ok(conn) => (Ok(conn.0 .0), conn.0 .1, conn.0 .2), - Err(e) => (Err(e), None, ""), + // Race a clone of the offerer; the guard retains its own clone so a losing/cancelled race + // still closes the pc (select_ok drops the future's clone without closing). + let webrtc_fut = webrtc_guard + .as_ref() + .and_then(|g| g.stream()) + .map(|stream| { + let mut raced = stream.clone(); + // The punch-tuned timeout can be as low as 1s — enough for a raw TCP SYN but not + // for candidate trickle + ICE checks + DTLS. Give WebRTC its own floor (prefer-P2P) + // so a viable P2P path is not abandoned before it can complete; TCP/UDP keep the + // tighter timeout, so a working direct connection still wins immediately, and the + // relay fallback only waits the extra time when direct attempts all failed. + let webrtc_timeout = connect_timeout.max(Self::WEBRTC_PREFER_WINDOW_MS); + async move { + raced.wait_connected(webrtc_timeout).await?; + // Resolve the pair here: a TURN win is relayed, not direct, and must be held + // behind still-racing direct attempts rather than committed as P2P. + let relayed = raced.is_relayed().await.unwrap_or(true); + Ok((Stream::WebRTC(raced), None, "WebRTC", !relayed)) + } + .boxed() + }); + // Prefer P2P: a direct result wins outright, a relayed WebRTC (TURN) is held for the + // window so a direct punch can still land. Falls back to plain select_ok when only one + // kind is present. + let direct_result = match (webrtc_fut, direct_futures.is_empty()) { + (Some(webrtc_fut), false) => { + race_transports_prefer_webrtc( + webrtc_fut, + direct_futures, + Self::WEBRTC_PREFER_WINDOW_MS, + |r| r.3, + ) + .await + } + (Some(webrtc_fut), true) => webrtc_fut.await, + (None, false) => select_ok(direct_futures).await.map(|c| c.0), + (None, true) => Err(anyhow!("No direct transport available")), }; + let (mut conn, kcp, mut typ, mut direct) = match direct_result { + Ok((conn, kcp, typ, direct)) => (Ok(conn), kcp, typ, direct), + Err(e) => (Err(e), None, "", false), + }; + if let Some(stop) = webrtc_bridge_stop { + let _ = stop.send(()); + } + // webrtc_guard stays armed across the relay override and secure_connection below; it is + // disarmed only at the successful return when WebRTC is the kept transport. - let mut direct = !conn.is_err(); - if interface.is_force_relay() || conn.is_err() { + // Keep a WebRTC win instead of replacing it with the RustDesk relay: under relay-by- + // policy the pc was built with Relay-only ICE (TURN configured), which already honors + // the relay requirement, and under ws-forced relay a direct full-ICE connection is the + // preferred outcome, not a violation. + if (interface.is_force_relay() && typ != "WebRTC") || conn.is_err() { if !relay_server.is_empty() { let switch_code = interface.get_switch_code(); conn = Self::request_relay( @@ -734,15 +1511,73 @@ impl Client { start.elapsed(), punch_type ); - let res = Self::secure_connection(peer_id, signed_id_pk, key, &mut conn).await; + let res = Self::secure_connection(peer_id, signed_id_pk.clone(), key, &mut conn).await; let pk: Option> = match res { Ok(pk) => pk, + Err(e) if typ == "WebRTC" && !relay_server.is_empty() => { + // WebRTC won the race but identity/DTLS binding failed; fall back to a freshly + // coordinated relay instead of failing the whole attempt. The guard is dropped + // first so the bad pc is closed promptly. + log::warn!("WebRTC secure handshake failed ({}), falling back to relay", e); + drop(webrtc_guard.take()); + match Self::request_relay( + peer_id, + relay_server.to_owned(), + rendezvous_server, + !signed_id_pk.is_empty(), + key, + token, + conn_type, + &interface.get_switch_code(), + ) + .await + { + Ok(mut relay_conn) => { + match Self::secure_connection(peer_id, signed_id_pk, key, &mut relay_conn) + .await + { + Ok(pk) => { + conn = relay_conn; + typ = "Relay"; + direct = false; + pk + } + Err(e) => { + interface.update_direct(Some(false)); + bail!(e); + } + } + } + Err(relay_e) => { + interface.update_direct(Some(direct)); + bail!( + "WebRTC secure failed ({}); relay fallback also failed: {}", + e, + relay_e + ); + } + } + } Err(e) => { // this direct is mainly used by on_establish_connection_error, so we update it here before bail interface.update_direct(Some(direct)); + // webrtc_guard is still armed here, so a WebRTC winner whose secure handshake + // failed is closed by the guard's drop as we bail (no explicit close needed). bail!(e); } }; + if typ == "WebRTC" { + // WebRTC through a TURN server (force_relay, or a TURN pair winning under All + // policy) is relayed traffic; report the direct flag accordingly. An unknown answer + // counts as relayed — claiming a P2P path needs evidence of one. + if conn.webrtc_relayed().await.unwrap_or(true) { + direct = false; + } + // Secured: disarm so the returned conn keeps the pc alive. + if let Some(guard) = webrtc_guard.take() { + let _ = guard.into_inner(); + } + } log::debug!("{} punch secure_connection ok", punch_type); Ok((conn, direct, pk, kcp, typ)) } @@ -759,6 +1594,15 @@ impl Client { } else { key }); + // A WebRTC channel is peer-authenticated only once its DTLS fingerprint is bound to the + // verified peer identity below. Once a trusted identity IS established, every binding + // failure fails closed: any peer able to answer WebRTC also signs its fingerprint, so a + // mismatch is concrete evidence of a rendezvous/relay MITM (not a legacy peer), and + // callers fall back to a fresh relay connection rather than proceeding on that channel. + // Without a trusted identity (absent, or unverifiable under our configured root) no + // binding is possible at all; WebRTC then proceeds like TCP's non-secure fallback — + // DTLS-encrypted but reported unsecured. TCP/UDP/relay keep their existing behavior. + let is_webrtc = conn.is_webrtc(); let mut sign_pk = None; let mut option_pk = None; if !signed_id_pk.is_empty() { @@ -777,6 +1621,10 @@ impl Client { let sign_pk = match sign_pk { Some(v) => v, None => { + // No trusted peer identity (key-less deployment, or a blob that does not verify + // under our root), so no fingerprint binding is possible. Fall through like TCP's + // non-secure path with is_secured() false: bailing would only move the session to + // a relay that fails the same check and then runs in plaintext. // send an empty message out in case server is setting up secure and waiting for first message conn.send(&Message::new()).await?; return Ok(option_pk); @@ -787,8 +1635,20 @@ impl Client { let bytes = res?; if let Ok(msg_in) = Message::parse_from_bytes(&bytes) { if let Some(message::Union::SignedId(si)) = msg_in.union { - if let Ok((id, their_pk_b)) = decode_id_pk(&si.id, &sign_pk) { + if let Ok((id, their_pk_b, signed_fp)) = decode_id_pk_dtls(&si.id, &sign_pk) { if id == peer_id { + // WebRTC only: bind the DTLS channel to the verified peer identity. + // webrtc-rs already bound the certificate to the remote SDP, so + // requiring the peer to have SIGNED that fingerprint defeats a + // rendezvous/relay MITM that swaps SDPs. Fail closed. + if is_webrtc { + let actual_fp = conn.dtls_fingerprint(false).await.ok_or_else( + || anyhow!("WebRTC DTLS fingerprint unavailable"), + )?; + if signed_fp.is_empty() || signed_fp != actual_fp { + bail!("WebRTC DTLS fingerprint not bound to peer identity (possible MITM)"); + } + } let (asymmetric_value, symmetric_value, key) = create_symmetric_key_msg(their_pk_b); let mut msg_out = Message::new(); @@ -800,10 +1660,16 @@ impl Client { timeout(CONNECT_TIMEOUT, conn.send(&msg_out)).await??; conn.set_key(key); } else { + if is_webrtc { + bail!("WebRTC handshake id mismatch (possible MITM)"); + } log::error!("Handshake failed: sign failure"); conn.send(&Message::new()).await?; } } else { + if is_webrtc { + bail!("WebRTC peer identity could not be verified (refusing unbound channel)"); + } // fall back to non-secure connection in case pk mismatch log::info!("pk mismatch, fall back to non-secure"); let mut msg_out = Message::new(); @@ -811,10 +1677,16 @@ impl Client { conn.send(&msg_out).await?; } } else { + if is_webrtc { + bail!("WebRTC handshake received an unexpected message type"); + } log::error!("Handshake failed: invalid message type"); conn.send(&Message::new()).await?; } } else { + if is_webrtc { + bail!("WebRTC handshake received a malformed message"); + } log::error!("Handshake failed: invalid message format"); conn.send(&Message::new()).await?; } @@ -1774,6 +2646,12 @@ pub struct LoginConfigHandler { // reconnect before the real reboot disconnect. restart_remote_device_at: Option, pub force_relay: bool, + // force_relay minus the WebSocket transport. ws forces relay for classic punching but says + // nothing about ICE, so every WebRTC decision keys off this: policy means Relay-only ICE, + // transport may still go direct. + pub policy_relay: bool, + // The peer-scoped part of it, and the only part that may be written back to the peer. + pub peer_relay: bool, pub direct: Option, pub received: bool, switch_uuid: Option, @@ -1886,11 +2764,14 @@ impl LoginConfigHandler { self.session_id = sid; self.supported_encoding = Default::default(); self.clear_restarting_remote_device(); - self.force_relay = + // Three scopes: what was decided about this PEER, what this CLIENT is set up as (proxy), + // and what its TRANSPORT forces (ws). Only the first may be written back to the peer's + // config — persisting the others would make a local setup a permanent peer property. + self.peer_relay = config::option2bool("force-always-relay", &self.get_option("force-always-relay")) - || force_relay - || use_ws() - || Config::is_proxy(); + || force_relay; + self.policy_relay = self.peer_relay || Config::is_proxy(); + self.force_relay = self.policy_relay || use_ws(); if let Some((real_id, server, key)) = &self.other_server { let other_server_key = self.get_option("other-server-key"); if !other_server_key.is_empty() && key.is_empty() { @@ -2607,7 +3488,9 @@ impl LoginConfigHandler { .insert("other-server-key".to_owned(), c.clone()); } } - if self.force_relay { + // peer_relay only — see `initialize`: neither the proxy nor the WebSocket transport is a + // fact about this peer, and writing one here makes it permanent. + if self.peer_relay { config .options .insert("force-always-relay".to_owned(), "Y".to_owned()); @@ -3783,6 +4666,10 @@ pub trait Interface: Send + Clone + 'static + Sized { self.get_lch().read().unwrap().force_relay } + fn is_policy_relay(&self) -> bool { + self.get_lch().read().unwrap().policy_relay + } + fn get_switch_code(&self) -> String { match self.get_lch().read().unwrap().switch_uuid.clone() { Some(u) if !u.is_empty() => { @@ -4276,8 +5163,22 @@ pub mod peer_online { #[cfg(test)] mod tests { + use crate::client::Client; + use hbb_common::rendezvous_proto::IceCandidate; use hbb_common::tokio; + #[test] + fn accepts_webrtc_ice_by_session_key_only() { + let ice = IceCandidate { + session_key: "session-a".to_owned(), + candidate: "candidate-json".to_owned(), + ..Default::default() + }; + + assert!(Client::is_expected_webrtc_ice_candidate(&ice, "session-a")); + assert!(!Client::is_expected_webrtc_ice_candidate(&ice, "session-b")); + } + #[tokio::test] async fn test_query_onlines() { super::query_online_states( @@ -4302,13 +5203,10 @@ async fn test_udp_uat( udp_port: Arc>, mut stop_udp_rx: oneshot::Receiver<()>, ) -> ResultType<()> { - let (tx, mut rx) = oneshot::channel::<_>(); - tokio::spawn(async { - if let Ok(v) = crate::test_nat_ipv4().await { - tx.send(v).ok(); - } - }); - + // The punch port must come only from the rendezvous server's TestNatResponse, which + // observes THIS socket's public mapping. A STUN probe binds a different socket and reports + // a different NAT mapping, so racing it here could advertise a port the peer can never + // reach (and, on symmetric NAT, silently poison the whole UDP punch). let start = Instant::now(); let mut msg_out = RendezvousMessage::new(); msg_out.set_test_nat_request(TestNatRequest { @@ -4334,11 +5232,6 @@ async fn test_udp_uat( loop { tokio::select! { - Ok((addr, server)) = &mut rx => { - *udp_port.lock().unwrap() = addr.port(); - log::debug!("UDP NAT test received response from {}: {}", addr, server); - break; - } _ = &mut stop_udp_rx => { log::debug!("UDP NAT test received stop signal after {} packets", packets_sent); break; @@ -4379,7 +5272,12 @@ async fn test_udp_uat( } } Err(e) => { - log::warn!("UDP NAT test socket error: {}", e); + // Same ICMP-driven errors as punch_udp sees. Without a pause this arm + // re-arms recv immediately and spins the loop at CPU speed. + if let Some(n) = UDP_UAT_ERR_LOG.due() { + log::warn!("UDP NAT test socket error x{n}, last: {e}"); + } + hbb_common::sleep(0.01).await; } } } @@ -4418,3 +5316,267 @@ async fn udp_nat_connect( })?; Ok((res.1, Some(res.0), typ)) } + +#[cfg(test)] +mod webrtc_race_tests { + use super::{race_transports_prefer_webrtc, request_allows_tcp_punch}; + use hbb_common::{ + anyhow::anyhow, + futures::future::{BoxFuture, FutureExt}, + tokio, + tokio::time::{sleep, Duration, Instant}, + ResultType, + }; + + fn ok_after(ms: u64, tag: &'static str) -> BoxFuture<'static, ResultType<&'static str>> { + async move { + sleep(Duration::from_millis(ms)).await; + Ok(tag) + } + .boxed() + } + + fn err_after(ms: u64, what: &'static str) -> BoxFuture<'static, ResultType<&'static str>> { + async move { + sleep(Duration::from_millis(ms)).await; + Err(anyhow!(what)) + } + .boxed() + } + + const NOT_P2P: fn(&&'static str) -> bool = |_| false; + + #[test] + fn webrtc_request_never_reuses_its_signaling_socket_for_tcp_punch() { + assert!(request_allows_tcp_punch("")); + assert!(!request_allows_tcp_punch("webrtc://offer")); + } + + // A direct result must win even when it lands first — the LAN ordering, where ICE beats the + // relay's TCP connect. Parking it as if it were a relay commits the relay on arrival. + #[tokio::test] + async fn direct_result_wins_even_when_it_arrives_first() { + let got = race_transports_prefer_webrtc( + ok_after(10, "direct"), + vec![ok_after(120, "relay")], + 60_000, + |result| *result == "direct", + ) + .await + .unwrap(); + assert_eq!(got, "direct"); + } + + #[tokio::test] + async fn webrtc_preferred_over_faster_relay_within_window() { + let got = race_transports_prefer_webrtc( + ok_after(120, "webrtc"), + vec![ok_after(10, "relay")], + 60_000, + NOT_P2P, + ) + .await + .unwrap(); + assert_eq!(got, "webrtc"); + } + + // The preferred branch runs a whole punch attempt, so it can itself end in a relay. That must + // not preempt a direct punch still in flight on the fallback branch. + #[tokio::test] + async fn relay_from_preferred_branch_does_not_preempt_a_direct_fallback() { + let got = race_transports_prefer_webrtc( + ok_after(10, "preferred-relay"), + vec![ok_after(120, "direct")], + 60_000, + |tag| *tag == "direct", + ) + .await + .unwrap(); + assert_eq!(got, "direct"); + } + + // ...but it is still committed once nothing direct can arrive. + #[tokio::test] + async fn relay_from_preferred_branch_committed_when_fallback_fails() { + let got = race_transports_prefer_webrtc( + ok_after(10, "preferred-relay"), + vec![err_after(50, "punch failed")], + 60_000, + NOT_P2P, + ) + .await + .unwrap(); + assert_eq!(got, "preferred-relay"); + } + + #[tokio::test] + async fn relay_from_preferred_branch_committed_when_window_expires() { + let got = race_transports_prefer_webrtc( + ok_after(10, "preferred-relay"), + vec![ok_after(60_000, "too-slow")], + 100, + NOT_P2P, + ) + .await + .unwrap(); + assert_eq!(got, "preferred-relay"); + } + + #[tokio::test] + async fn preference_window_starts_when_relay_is_ready() { + let got = race_transports_prefer_webrtc( + ok_after(350, "webrtc"), + vec![ok_after(250, "relay")], + 200, + NOT_P2P, + ) + .await + .unwrap(); + assert_eq!(got, "webrtc"); + } + + #[tokio::test] + async fn unfinished_ipv6_still_beats_held_relay() { + let start = Instant::now(); + let got = race_transports_prefer_webrtc( + ok_after(60_000, "webrtc"), + vec![ok_after(10, "relay"), ok_after(100, "ipv6")], + 1_000, + |t| *t == "ipv6", + ) + .await + .unwrap(); + assert_eq!(got, "ipv6"); + assert!(start.elapsed() < Duration::from_secs(5)); + } + + // WebRTC fails first (others still racing), then a relay arrives with a direct attempt still + // unfinished behind it. The relay must not be committed while that direct attempt can win. + #[tokio::test] + async fn relay_does_not_preempt_unfinished_direct_after_webrtc_fails() { + let got = race_transports_prefer_webrtc( + err_after(5, "webrtc dead"), + vec![ok_after(10, "relay"), ok_after(100, "ipv6")], + 60_000, + |t| *t == "ipv6", + ) + .await + .unwrap(); + assert_eq!(got, "ipv6"); + } + + // A relay is held with a direct attempt racing behind it, then WebRTC fails. The held relay + // must not be committed while the direct attempt is still in flight. + #[tokio::test] + async fn held_relay_waits_for_racing_direct_when_webrtc_fails() { + let got = race_transports_prefer_webrtc( + err_after(50, "webrtc dead"), + vec![ok_after(10, "relay"), ok_after(100, "ipv6")], + 60_000, + |t| *t == "ipv6", + ) + .await + .unwrap(); + assert_eq!(got, "ipv6"); + } + + // Both attempts error, but a relay was parked before they did — it is the outcome, not a + // composed error. + #[tokio::test] + async fn held_relay_survives_both_errors() { + let got = race_transports_prefer_webrtc( + err_after(50, "webrtc dead"), + vec![ok_after(10, "relay"), err_after(100, "ipv6 dead")], + 60_000, + |t| *t == "ipv6", + ) + .await + .unwrap(); + assert_eq!(got, "relay"); + } + + #[tokio::test] + async fn held_relay_committed_when_window_expires() { + let start = Instant::now(); + let got = race_transports_prefer_webrtc( + ok_after(60_000, "webrtc"), + vec![ok_after(10, "relay")], + 150, + NOT_P2P, + ) + .await + .unwrap(); + assert_eq!(got, "relay"); + assert!(start.elapsed() < Duration::from_secs(5)); + } + + #[tokio::test] + async fn held_relay_committed_when_webrtc_fails() { + let start = Instant::now(); + let got = race_transports_prefer_webrtc( + err_after(50, "webrtc dead"), + vec![ok_after(10, "relay")], + 60_000, + NOT_P2P, + ) + .await + .unwrap(); + assert_eq!(got, "relay"); + assert!(start.elapsed() < Duration::from_secs(5)); + } + + #[tokio::test] + async fn relay_committed_directly_after_webrtc_failed() { + let got = race_transports_prefer_webrtc( + err_after(5, "webrtc dead"), + vec![ok_after(100, "relay")], + 60_000, + NOT_P2P, + ) + .await + .unwrap(); + assert_eq!(got, "relay"); + } + + #[tokio::test] + async fn webrtc_still_wins_past_window_when_relay_dead() { + let got = race_transports_prefer_webrtc( + ok_after(300, "webrtc"), + vec![err_after(10, "relay dead")], + 50, + NOT_P2P, + ) + .await + .unwrap(); + assert_eq!(got, "webrtc"); + } + + #[tokio::test] + async fn p2p_transport_committed_immediately() { + let start = Instant::now(); + let got = race_transports_prefer_webrtc( + ok_after(60_000, "webrtc"), + vec![ok_after(10, "ipv6")], + 60_000, + |t| *t == "ipv6", + ) + .await + .unwrap(); + assert_eq!(got, "ipv6"); + assert!(start.elapsed() < Duration::from_secs(5)); + } + + #[tokio::test] + async fn both_failing_compose_error() { + let err = race_transports_prefer_webrtc( + err_after(10, "webrtc dead"), + vec![err_after(20, "relay dead")], + 1_000, + NOT_P2P, + ) + .await + .unwrap_err() + .to_string(); + assert!(err.contains("webrtc dead") && err.contains("relay dead"), "{}", err); + } +} diff --git a/src/client/io_loop.rs b/src/client/io_loop.rs index d7a4f570f..34c462f4d 100644 --- a/src/client/io_loop.rs +++ b/src/client/io_loop.rs @@ -185,6 +185,14 @@ impl Remote { .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 diff --git a/src/common.rs b/src/common.rs index 648bc6b5c..ef9288f5f 100644 --- a/src/common.rs +++ b/src/common.rs @@ -1,7 +1,7 @@ use std::{ collections::HashMap, future::Future, - net::{SocketAddr, ToSocketAddrs}, + net::SocketAddr, sync::{Arc, Mutex, RwLock}, task::Poll, }; @@ -1153,6 +1153,13 @@ 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, @@ -1167,9 +1174,19 @@ 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 { + if key == keys::OPTION_ENABLE_UDP_PUNCH + || key == keys::OPTION_ENABLE_IPV6_PUNCH + || key == keys::OPTION_ENABLE_WEBRTC + { if v.is_empty() { if !is_public(&Config::get_rendezvous_server()) { return "N".to_owned(); @@ -2126,11 +2143,21 @@ pub fn get_rs_pk(str_base64: &str) -> Option { } 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)) + Ok((res.id, pk, res.dtls_fingerprint)) } else { bail!("Wrong their public length"); } @@ -2432,16 +2459,26 @@ 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: &str) -> ResultType<(SocketAddr, String)> { - use std::net::ToSocketAddrs; +async fn stun_ipv6_test(stun_server: String) -> ResultType<(SocketAddr, String)> { use stunclient::StunClient; let local_addr = SocketAddr::from(([0u16; 8], 0)); // [::]:0 let socket = UdpSocket::bind(&local_addr).await?; - let Some(stun_addr) = stun_server - .to_socket_addrs()? - .filter(|x| x.is_ipv6()) - .next() + // 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()) else { bail!( "Failed to resolve STUN ipv6 server address: {}", @@ -2451,81 +2488,36 @@ async fn stun_ipv6_test(stun_server: &str) -> 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.to_owned()) + (addr, stun_server) } 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::>(); - - 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 { + use hbb_common::futures::future::FutureExt; let local_addr = SocketAddr::from(([0u16; 8], 0)); // [::]:0 let socket = UdpSocket::bind(local_addr).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] - ) - })?; + // 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::(addr) + }) + .boxed() + }) + .collect::>(); + let (addr, _) = hbb_common::futures::future::select_ok(lookups).await?; socket.connect(addr).await?; Ok(socket.local_addr()?) } @@ -2592,9 +2584,9 @@ pub async fn test_ipv6() -> Option> { Some(tokio::spawn(async { use hbb_common::futures::future::{select_ok, FutureExt}; - let tests = STUNS_V6 - .iter() - .map(|&stun| stun_ipv6_test(stun).boxed()) + let tests = hbb_common::webrtc::WebRTCStream::default_stun_servers() + .into_iter() + .map(|stun| stun_ipv6_test(stun).boxed()) .collect::>(); match select_ok(tests).await { @@ -2615,51 +2607,117 @@ pub async fn test_ipv6() -> Option> { })) } +// 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 { + 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, listen: bool, ) -> ResultType> { + 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); - 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(); + // 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; let tm = Instant::now(); - let mut data = [0u8; 1500]; + // 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; loop { tokio::select! { - _ = 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(); - } + _ = 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; } res = socket.recv(&mut data) => match res { - Err(e) => bail!("UDP punch failed, {packets_sent} packets sent: {e}"), + 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; + } Ok(n) => { - // log::debug!("UDP punch succeeded after sending {} packets after {:?}", packets_sent, tm.elapsed()); - if listen { - if n == 0 { - continue; + 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); } + 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); } } } @@ -2783,6 +2841,38 @@ 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 = [ diff --git a/src/ipc/auth.rs b/src/ipc/auth.rs index 89beef072..6f40ab115 100644 --- a/src/ipc/auth.rs +++ b/src/ipc/auth.rs @@ -24,7 +24,6 @@ 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}; @@ -520,66 +519,17 @@ 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, - 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 { - 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>, - 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, active_uid: Option) { - static LOG_THROTTLE: OnceLock> = 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 - ); - } - }); + 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 + ); } #[cfg(target_os = "linux")] @@ -589,25 +539,14 @@ pub(crate) fn log_rejected_uinput_connection( peer_uid: Option, active_uid: Option, ) { - static LOG_THROTTLE: OnceLock> = 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 - ); - } - }); + 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 + ); } #[cfg(windows)] @@ -620,31 +559,17 @@ pub(crate) fn log_rejected_windows_ipc_connection( peer_is_system: Option, peer_is_elevated: Option, ) { - static LOG_THROTTLE: OnceLock> = 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 - ); - } - }); + 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 + ); } #[cfg(any(target_os = "linux", target_os = "macos"))] diff --git a/src/kcp_stream.rs b/src/kcp_stream.rs index 74bd84130..2c4cfe4bd 100644 --- a/src/kcp_stream.rs +++ b/src/kcp_stream.rs @@ -19,7 +19,28 @@ pub struct KcpStream { stop_sender: Option>, } +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) -> Stream { Stream::Tcp(FramedStream( tokio_util::codec::Framed::new(DynTcpStream(Box::new(stream)), BytesCodec::new()), @@ -35,6 +56,7 @@ impl KcpStream { init_packet: Option, ) -> ResultType<(Self, Stream)> { let mut endpoint = KcpEndpoint::new(); + Self::apply_kcp_config(&mut endpoint); endpoint.run().await; let (input, output) = ( @@ -70,6 +92,7 @@ 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) = ( @@ -104,6 +127,10 @@ 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 => { @@ -112,8 +139,10 @@ impl KcpStream { } Some(data) = output.recv() => { if let Err(e) = udp.send(&data.inner()).await { - log::debug!("KCP send error: {:?}", e); - break; + 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; } } result = udp.recv_from(&mut buf) => { @@ -127,8 +156,10 @@ impl KcpStream { .await.ok(); } Err(e) => { - log::debug!("KCP recv_from error: {:?}", e); - break; + 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; } } } @@ -149,3 +180,124 @@ impl Drop for KcpStream { } } } + +#[cfg(test)] +mod tests { + use super::*; + use std::time::Duration; + + async fn connected_pair() -> (Arc, Arc) { + 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" + ); + } +} diff --git a/src/lang/ar.rs b/src/lang/ar.rs index 47e93d5c5..5f7ee012b 100644 --- a/src/lang/ar.rs +++ b/src/lang/ar.rs @@ -768,5 +768,7 @@ 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(); } diff --git a/src/lang/be.rs b/src/lang/be.rs index 78cc5f455..5b079a640 100644 --- a/src/lang/be.rs +++ b/src/lang/be.rs @@ -768,5 +768,7 @@ 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(); } diff --git a/src/lang/bg.rs b/src/lang/bg.rs index effb91514..609a2de49 100644 --- a/src/lang/bg.rs +++ b/src/lang/bg.rs @@ -768,5 +768,7 @@ 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(); } diff --git a/src/lang/ca.rs b/src/lang/ca.rs index 9ac80dd8c..efdebf934 100644 --- a/src/lang/ca.rs +++ b/src/lang/ca.rs @@ -768,5 +768,7 @@ 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(); } diff --git a/src/lang/cn.rs b/src/lang/cn.rs index 9e2e3f991..b5f7da9d6 100644 --- a/src/lang/cn.rs +++ b/src/lang/cn.rs @@ -768,5 +768,7 @@ 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(); } diff --git a/src/lang/cs.rs b/src/lang/cs.rs index 5a7dabcb4..4db35ebfa 100644 --- a/src/lang/cs.rs +++ b/src/lang/cs.rs @@ -768,5 +768,7 @@ 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(); } diff --git a/src/lang/da.rs b/src/lang/da.rs index 1b96ead6b..d8223253e 100644 --- a/src/lang/da.rs +++ b/src/lang/da.rs @@ -768,5 +768,7 @@ 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(); } diff --git a/src/lang/de.rs b/src/lang/de.rs index 06d8eac45..b2973f440 100644 --- a/src/lang/de.rs +++ b/src/lang/de.rs @@ -768,5 +768,7 @@ 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(); } diff --git a/src/lang/el.rs b/src/lang/el.rs index 87a097898..3afe9430c 100644 --- a/src/lang/el.rs +++ b/src/lang/el.rs @@ -768,5 +768,7 @@ 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(); } diff --git a/src/lang/eo.rs b/src/lang/eo.rs index dbd4e5d0c..055e3926c 100644 --- a/src/lang/eo.rs +++ b/src/lang/eo.rs @@ -768,5 +768,7 @@ 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(); } diff --git a/src/lang/es.rs b/src/lang/es.rs index d36ee2281..10bcd9907 100644 --- a/src/lang/es.rs +++ b/src/lang/es.rs @@ -768,5 +768,7 @@ 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(); } diff --git a/src/lang/et.rs b/src/lang/et.rs index 792457cb3..874ea6c32 100644 --- a/src/lang/et.rs +++ b/src/lang/et.rs @@ -768,5 +768,7 @@ 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(); } diff --git a/src/lang/eu.rs b/src/lang/eu.rs index 322f2822d..c4cbafe1d 100644 --- a/src/lang/eu.rs +++ b/src/lang/eu.rs @@ -768,5 +768,7 @@ 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(); } diff --git a/src/lang/fa.rs b/src/lang/fa.rs index 5c46c5de3..07fc68d20 100644 --- a/src/lang/fa.rs +++ b/src/lang/fa.rs @@ -768,5 +768,7 @@ 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(); } diff --git a/src/lang/fi.rs b/src/lang/fi.rs index 96616fad3..5f330e991 100644 --- a/src/lang/fi.rs +++ b/src/lang/fi.rs @@ -768,5 +768,7 @@ 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(); } diff --git a/src/lang/fr.rs b/src/lang/fr.rs index 55872b320..e0e42b49d 100644 --- a/src/lang/fr.rs +++ b/src/lang/fr.rs @@ -768,5 +768,7 @@ 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(); } diff --git a/src/lang/ge.rs b/src/lang/ge.rs index 4f0e77606..0de75f954 100644 --- a/src/lang/ge.rs +++ b/src/lang/ge.rs @@ -768,5 +768,7 @@ 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(); } diff --git a/src/lang/gu.rs b/src/lang/gu.rs index 6f9282bb9..74f292e86 100644 --- a/src/lang/gu.rs +++ b/src/lang/gu.rs @@ -768,5 +768,7 @@ 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(); } diff --git a/src/lang/he.rs b/src/lang/he.rs index a69b49c82..e7ad5cf4f 100644 --- a/src/lang/he.rs +++ b/src/lang/he.rs @@ -768,5 +768,7 @@ 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(); } diff --git a/src/lang/hi.rs b/src/lang/hi.rs index cd7f46b0b..60c9288a4 100644 --- a/src/lang/hi.rs +++ b/src/lang/hi.rs @@ -768,5 +768,7 @@ 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(); } diff --git a/src/lang/hr.rs b/src/lang/hr.rs index a1118a1c3..19a959c60 100644 --- a/src/lang/hr.rs +++ b/src/lang/hr.rs @@ -768,5 +768,7 @@ 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(); } diff --git a/src/lang/hu.rs b/src/lang/hu.rs index 1fff7804d..4337f3368 100644 --- a/src/lang/hu.rs +++ b/src/lang/hu.rs @@ -768,5 +768,7 @@ 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(); } diff --git a/src/lang/id.rs b/src/lang/id.rs index e45b87472..d4993327c 100644 --- a/src/lang/id.rs +++ b/src/lang/id.rs @@ -768,5 +768,7 @@ 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(); } diff --git a/src/lang/it.rs b/src/lang/it.rs index a0017ce06..3e8d79be6 100644 --- a/src/lang/it.rs +++ b/src/lang/it.rs @@ -768,5 +768,7 @@ 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(); } diff --git a/src/lang/ja.rs b/src/lang/ja.rs index 0d41f3f85..f970f7751 100644 --- a/src/lang/ja.rs +++ b/src/lang/ja.rs @@ -768,5 +768,7 @@ 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(); } diff --git a/src/lang/ko.rs b/src/lang/ko.rs index 98b76cc6f..49b3b7d83 100644 --- a/src/lang/ko.rs +++ b/src/lang/ko.rs @@ -768,5 +768,7 @@ 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(); } diff --git a/src/lang/kz.rs b/src/lang/kz.rs index 1ca770788..486c40073 100644 --- a/src/lang/kz.rs +++ b/src/lang/kz.rs @@ -768,5 +768,7 @@ 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(); } diff --git a/src/lang/lt.rs b/src/lang/lt.rs index 1f3e0c83e..fb022ceea 100644 --- a/src/lang/lt.rs +++ b/src/lang/lt.rs @@ -768,5 +768,7 @@ 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(); } diff --git a/src/lang/lv.rs b/src/lang/lv.rs index 895957d2d..4d8cff70d 100644 --- a/src/lang/lv.rs +++ b/src/lang/lv.rs @@ -768,5 +768,7 @@ 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(); } diff --git a/src/lang/ml.rs b/src/lang/ml.rs index 1c7a72790..57b2c2ad1 100644 --- a/src/lang/ml.rs +++ b/src/lang/ml.rs @@ -768,5 +768,7 @@ 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(); } diff --git a/src/lang/nb.rs b/src/lang/nb.rs index 74e7c4202..d5c9544f4 100644 --- a/src/lang/nb.rs +++ b/src/lang/nb.rs @@ -768,5 +768,7 @@ 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(); } diff --git a/src/lang/nl.rs b/src/lang/nl.rs index de1197127..5b108bbdd 100644 --- a/src/lang/nl.rs +++ b/src/lang/nl.rs @@ -768,5 +768,7 @@ 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(); } diff --git a/src/lang/pl.rs b/src/lang/pl.rs index 3960f3f55..50ce862bc 100644 --- a/src/lang/pl.rs +++ b/src/lang/pl.rs @@ -768,5 +768,7 @@ 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(); } diff --git a/src/lang/pt_PT.rs b/src/lang/pt_PT.rs index ab4b8d805..955ce35f9 100644 --- a/src/lang/pt_PT.rs +++ b/src/lang/pt_PT.rs @@ -768,5 +768,7 @@ 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(); } diff --git a/src/lang/ptbr.rs b/src/lang/ptbr.rs index aa97c5d57..03e9104aa 100644 --- a/src/lang/ptbr.rs +++ b/src/lang/ptbr.rs @@ -768,5 +768,7 @@ 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(); } diff --git a/src/lang/ro.rs b/src/lang/ro.rs index 5d377ab35..255377f56 100644 --- a/src/lang/ro.rs +++ b/src/lang/ro.rs @@ -768,5 +768,7 @@ 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(); } diff --git a/src/lang/ru.rs b/src/lang/ru.rs index ecc9a78f8..25c922063 100644 --- a/src/lang/ru.rs +++ b/src/lang/ru.rs @@ -768,5 +768,7 @@ 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(); } diff --git a/src/lang/sc.rs b/src/lang/sc.rs index 62b248b8a..54f7cc081 100644 --- a/src/lang/sc.rs +++ b/src/lang/sc.rs @@ -768,5 +768,7 @@ 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(); } diff --git a/src/lang/sk.rs b/src/lang/sk.rs index 80674b5fb..db3918327 100644 --- a/src/lang/sk.rs +++ b/src/lang/sk.rs @@ -768,5 +768,7 @@ 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(); } diff --git a/src/lang/sl.rs b/src/lang/sl.rs index ec62c9cec..e3adad22d 100644 --- a/src/lang/sl.rs +++ b/src/lang/sl.rs @@ -768,5 +768,7 @@ 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(); } diff --git a/src/lang/sq.rs b/src/lang/sq.rs index c3e2a97be..ca7e6e1d3 100644 --- a/src/lang/sq.rs +++ b/src/lang/sq.rs @@ -768,5 +768,7 @@ 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(); } diff --git a/src/lang/sr.rs b/src/lang/sr.rs index 0429c34f9..8ecff5cf5 100644 --- a/src/lang/sr.rs +++ b/src/lang/sr.rs @@ -768,5 +768,7 @@ 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(); } diff --git a/src/lang/sv.rs b/src/lang/sv.rs index 0018572b2..d9f5b6121 100644 --- a/src/lang/sv.rs +++ b/src/lang/sv.rs @@ -768,5 +768,7 @@ 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(); } diff --git a/src/lang/ta.rs b/src/lang/ta.rs index e2903f0e8..246d01ae4 100644 --- a/src/lang/ta.rs +++ b/src/lang/ta.rs @@ -768,5 +768,7 @@ 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(); } diff --git a/src/lang/template.rs b/src/lang/template.rs index 6daa1f306..d60321b93 100644 --- a/src/lang/template.rs +++ b/src/lang/template.rs @@ -768,5 +768,7 @@ 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(); } diff --git a/src/lang/th.rs b/src/lang/th.rs index a067ba050..4605c2787 100644 --- a/src/lang/th.rs +++ b/src/lang/th.rs @@ -768,5 +768,7 @@ 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(); } diff --git a/src/lang/tr.rs b/src/lang/tr.rs index 63c8f6a40..6087e4b16 100644 --- a/src/lang/tr.rs +++ b/src/lang/tr.rs @@ -768,5 +768,7 @@ 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(); } diff --git a/src/lang/tw.rs b/src/lang/tw.rs index cdfe85fbc..c29424aa9 100644 --- a/src/lang/tw.rs +++ b/src/lang/tw.rs @@ -768,5 +768,7 @@ 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(); } diff --git a/src/lang/uk.rs b/src/lang/uk.rs index 9bb94d002..359dd5a5a 100644 --- a/src/lang/uk.rs +++ b/src/lang/uk.rs @@ -768,5 +768,7 @@ 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(); } diff --git a/src/lang/ur.rs b/src/lang/ur.rs index cb37b0bcf..fe74c9ce2 100644 --- a/src/lang/ur.rs +++ b/src/lang/ur.rs @@ -768,6 +768,8 @@ 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(); } diff --git a/src/lang/vi.rs b/src/lang/vi.rs index 59c94830e..f3b073a84 100644 --- a/src/lang/vi.rs +++ b/src/lang/vi.rs @@ -768,5 +768,7 @@ 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(); } diff --git a/src/platform/android_ifaddrs.c b/src/platform/android_ifaddrs.c new file mode 100644 index 000000000..b48c8ddbe --- /dev/null +++ b/src/platform/android_ifaddrs.c @@ -0,0 +1,404 @@ +/* + * 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 +#include +#include +#include + +#include +#include +#include +#include + +#include +#include + +/* 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; +} diff --git a/src/rendezvous_mediator.rs b/src/rendezvous_mediator.rs index 21a7e23f4..64eb72f37 100644 --- a/src/rendezvous_mediator.rs +++ b/src/rendezvous_mediator.rs @@ -1,4 +1,6 @@ use std::{ + collections::{hash_map::RandomState, HashMap, VecDeque}, + hash::BuildHasher, net::SocketAddr, sync::{ atomic::{AtomicBool, Ordering}, @@ -21,8 +23,13 @@ use hbb_common::{ rendezvous_proto::*, sleep, socket_client::{self, connect_tcp, is_ipv4, new_direct_udp_for, new_udp_for}, - tokio::{self, select, sync::Mutex, time::interval}, + tokio::{ + self, select, + sync::{mpsc, Mutex}, + time::interval, + }, udp::FramedSocket, + webrtc::WebRTCStream, AddrMangle, IntoTargetAddr, ResultType, Stream, TargetAddr, }; @@ -47,7 +54,66 @@ lazy_static::lazy_static! { static ref SOLVING_PK_MISMATCH: Mutex = 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> = 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, + recent: VecDeque, +} + +impl IceRoute { + fn new(tx: mpsc::Sender) -> 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) -> 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); @@ -399,6 +465,30 @@ 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( @@ -508,6 +598,7 @@ impl RendezvousMediator { rr.secure, false, Default::default(), + String::new(), meta, ) .await @@ -522,6 +613,7 @@ 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); @@ -540,6 +632,7 @@ impl RendezvousMediator { socket_addr: socket_addr.into(), version: crate::VERSION.to_owned(), socket_addr_v6, + webrtc_sdp_answer, ..Default::default() }; if initiate { @@ -606,6 +699,7 @@ impl RendezvousMediator { true, true, socket_addr_v6, + String::new(), meta, ) .await @@ -642,6 +736,163 @@ 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 { + 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::(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; @@ -651,18 +902,52 @@ impl RendezvousMediator { return Ok(()); } let peer_addr_v6 = hbb_common::AddrMangle::decode(&ph.socket_addr_v6); - let relay = use_ws() || Config::is_proxy() || ph.force_relay; + let local_proxy = use_ws() || Config::is_proxy(); + let relay = local_proxy || ph.force_relay; let mut socket_addr_v6 = Default::default(); let meta = connection_meta( - ph.control_permissions.into_option(), - ph.controlled_context.into_option(), + ph.control_permissions.clone().into_option(), + ph.controlled_context.clone().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 @@ -678,6 +963,7 @@ impl RendezvousMediator { true, true, socket_addr_v6.clone(), + webrtc_sdp_answer.clone(), meta, ) .await; @@ -691,6 +977,7 @@ 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 { @@ -699,12 +986,25 @@ 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. - // it can not be async here, because local_addr can not be reused, we must close the connection before use it again. + // 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. allow_err!(socket_client::connect_tcp_local(peer_addr, Some(local_addr), 30).await); socket }; @@ -712,7 +1012,10 @@ impl RendezvousMediator { msg_out.set_punch_hole_sent(msg_punch); let bytes = msg_out.write_to_bytes()?; socket.send_raw(bytes).await?; - crate::accept_connection(server.clone(), socket, peer_addr, true, meta).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; Ok(()) } @@ -951,11 +1254,11 @@ async fn udp_nat_listen( let socket_cloned = socket.clone(); let func = async { socket.connect(peer_addr).await?; - let res = crate::punch_udp(socket.clone(), true).await?; + let init_packet = crate::punch_udp(socket.clone(), true).await?; let stream = crate::kcp_stream::KcpStream::accept( socket, Duration::from_millis(CONNECT_TIMEOUT as _), - res, + init_packet, ) .await?; crate::server::create_tcp_connection(server, stream.1, peer_addr_v4, true, meta).await?; @@ -971,6 +1274,194 @@ 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( + until: tokio::time::Instant, + peer_addr: SocketAddr, + mut punch: F, +) -> Option +where + F: FnMut(u64) -> Fut, + Fut: std::future::Future>, +{ + 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. @@ -995,3 +1486,255 @@ 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::(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::(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::(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::(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" + ); + } +} diff --git a/src/server.rs b/src/server.rs index 753ad5903..c7cac086a 100644 --- a/src/server.rs +++ b/src/server.rs @@ -212,11 +212,21 @@ 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() diff --git a/src/ui_session_interface.rs b/src/ui_session_interface.rs index e7c8e7516..fc09ed5e0 100644 --- a/src/ui_session_interface.rs +++ b/src/ui_session_interface.rs @@ -1294,7 +1294,13 @@ impl Session { // override only if true if true == force_relay { - self.lc.write().unwrap().force_relay = true; + let mut lc = self.lc.write().unwrap(); + lc.force_relay = true; + // An explicit retry-via-relay is a decision about this peer, not transport + // necessity: Relay-only ICE for this round like any force-always-relay session, + // and it is the one kind of relay that belongs in the peer's saved config. + lc.policy_relay = true; + lc.peer_relay = true; } self.lc.write().unwrap().peer_info = None; self.reconnect_count.fetch_add(1, Ordering::SeqCst);