Skip to content

TURN over TCP in the relayer (#848) - #907

Open
mnaza wants to merge 8 commits into
webrtc-rs:masterfrom
mnaza:turn-over-tcp
Open

mnaza wants to merge 8 commits into
webrtc-rs:masterfrom
mnaza:turn-over-tcp

Conversation

@mnaza

@mnaza mnaza commented Sep 22, 2026 •

Copy link
Copy Markdown

Closes the TCP half of #848. turn:…?transport=tcp now gathers a relay candidate. The connection to the TURN server is TCP and the allocation is still UDP. turns: is still skipped, for the TLS follow-up.

Builds on webrtc-rs/rtc#254 (merged); the rtc submodule points at that merge, 7b7aeb5.

How it's shaped

As you suggested, it goes through RTCTcpTransport:

  • Framing per stream. register_stream keeps RFC 4571 for ICE-TCP. register_turn_stream splits with TurnStreamDecoder and writes messages without a prefix. The ICE-TCP peer-address fallback never picks a TURN connection.
  • Connecting. For a TCP URL the relayer asks the host for a connection: one per server and address family, since the source address is the kernel's and unrelated to the UDP sockets. The driver opens it off the event loop with a 5 s bound, the same way active ICE-TCP connects already work. on_tcp_connected then creates the client over TCP, asking for a UDP relay.
  • Gathering waits for pending connects. A refused or timed-out connect ends that server's part in it. Connect ids come from a process-wide counter, so a connect that finishes after an ICE restart or a reconfiguration matches nothing and its stream is dropped.
  • Loss and release. A TURN connection that ends (EOF, a read error, or bytes that are not TURN) reaches the relayer through the existing SocketWriteFailure path. After that, a write to it is an error rather than Ok(0). A client the relayer lets go of on reconfiguration releases its connection.
  • Routing. Inbound matching checks the transport, so a datagram is never taken for a stream client's traffic.
  • Credential rotation. A TCP connect still in flight counts as a client mid-Allocate, so a credential-only change regathers instead of re-signing, and the connect can't come up on the old password.

Write routing needed no change: relayer output already carries its client's transport, and handle_write already sends TCP-tagged messages to RTCTcpTransport first.

Known limits

  • A released TURN stream is dropped from the transport at once, but its socket closes only when its pending read resolves. AsyncTcpStream has no shutdown, and a single future in the FuturesUnordered cannot be cancelled. In practice the server closes it when the allocation lapses.
  • connect_tcp takes no local address, so the TCP connection's source interface is the kernel's choice. Changing that is public API, and I've left it alone.
  • On smol, connect_tcp is a blocking std connect inside the async block. That was already true and is unchanged here.

Tests

  • Unit tests for the transport, on real loopback sockets: TURN framing both ways, ICE-TCP keeping its prefix, loss reported and later writes failing, a stream that isn't TURN being closed, release not being reported as loss, and no fallback onto a TURN stream.
  • Unit tests for the relayer: a TCP URL asks for a connection and holds gathering open; once connected, the Allocate goes over TCP and asks for UDP; a failed connect completes gathering and a stale one is ignored; UDP traffic never routes to a TCP client; turns: is still skipped; reconfiguration releases the connection; a credential change during a connect regathers.
  • tests/ice_test.rs gets a TCP twin of run_mock_turn_server. With it, a relay-only peer gathers a relay candidate over TCP (the server sees REQUESTED-TRANSPORT 17), and a refused TCP port completes gathering without one.
  • tests/turn_over_tcp.rs (separate commit, env-gated like turn_credential_rotation) connects two relay-only peers through a real TURN server — one over TCP, one over UDP — and a data-channel message crosses. It passes against coturn 4.6 and fails with TCP URLs skipped. The module docs give the coturn command.

Each new test was also run against the relayer or transport broken the way it guards, and failed. The full suite passes: 167 tests across 46 targets, 1 ignored (a doc example that was already ignore). turn_over_tcp skips without its env var; set, against coturn, it passes.

Refs #848.

mnaza added a commit to mnaza/relaysight that referenced this pull request Sep 22, 2026
…, install gateways from signed releases

Everything since the last sync, in one commit; this clone keeps its own
history.

A revoked gateway's cameras can be retired from the roster: a tombstone
rather than a delete, so recordings still play and a gateway reporting the
camera again brings it back with its history. The action refuses while
the gateway is still in service.

Each camera can have its own credentials, encrypted on the gateway under
the same key as its identity and entered with `vms-gateway credentials`,
which reads the password from stdin. The shared CAMERA_USERNAME and
CAMERA_PASSWORD stay as the fallback.

Gateways install on a site box from a signed release: install.sh verifies
the Ed25519-signed manifest before touching anything and sets up a
hardened systemd service with a daily self-update. An update keeps a new
binary only once the API has accepted a heartbeat from it, and rolls back
otherwise. make check-installer runs all of it on a real systemd.
Retina now comes from a pinned fork carrying the fix for decimal SSRCs,
until upstream releases it. docs/INSTALL-GATEWAY.md says what is checked
and what is not; no release has been cut yet, because the release key
does not exist yet.

Plus the upstream design for TURN over TCP in webrtc-rs, which is open as
webrtc-rs/rtc#254 and webrtc-rs/webrtc#907.
@codecov

codecov Bot commented Oct 4, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 84.32990% with 152 lines in your changes missing coverage. Please review.
✅ Project coverage is 86.53%. Comparing base (f6b017b) to head (8220b52).
⚠️ Report is 2 commits behind head on master.

Files with missing lines Patch % Lines
tests/turn_over_tcp.rs 4.34% 110 Missing ⚠️
src/peer_connection/transport/turn_relayer.rs 96.00% 16 Missing ⚠️
src/peer_connection/driver.rs 70.83% 14 Missing ⚠️
tests/ice_test.rs 95.27% 6 Missing ⚠️
src/peer_connection/transport/tcp_transport.rs 98.34% 4 Missing ⚠️
src/runtime/mod.rs 85.71% 2 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master     #907      +/-   ##
==========================================
+ Coverage   86.36%   86.53%   +0.17%     
==========================================
  Files          66       67       +1     
  Lines       14315    15245     +930     
==========================================
+ Hits        12363    13193     +830     
- Misses       1952     2052     +100     
Flag Coverage Δ
smol 86.16% <78.53%> (-0.14%) ⬇️
tokio 86.34% <84.18%> (+0.19%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@mnaza
mnaza marked this pull request as ready for review October 5, 2026 06:09
@mnaza

mnaza commented Oct 5, 2026

Copy link
Copy Markdown
Author

@rainliu thanks for merging webrtc-rs/rtc#254. This is now ready for review: rebased on master at 7dba253, with the rtc submodule pointing at the merge (7b7aeb5) instead of my fork's branch, so CI can check it out.

Three things changed in the rebase:

  • requested_transport is gone here too. Both TurnClientConfig literals (the UDP one and the TCP one) set it; the field no longer exists after your change to [DTLS] Add NamedCurve::P384 #254, so I removed it in the two commits that introduced it rather than in a fix-up on top. Every commit in the series builds on its own.
  • One interaction with fix: release TURN allocations on close() on both runtimes (#903) #911 worth your eye. fix: release TURN allocations on close() on both runtimes (#903) #911 makes remove_client queue a Refresh(LIFETIME=0) in retirement_wouts when it releases an allocation. This PR, in the same function, hands a TCP client's connection back to the transport for closing, and release_turn_stream marks the stream dead at once — a write to it fails from then on. So if the connection were handed back before the Refresh went out, the release would be lost and the allocation would sit on the server until it expired. Today the driver happens to avoid it, because poll_writes runs before poll_events in each pass. I didn't want that to depend on loop order: take_released_tcp_streams now holds back any connection that still has a queued Refresh, and hands it over on a later pass once the Refresh has been written. There's a unit test for it (a_released_connection_waits_for_its_refresh_to_go_out).
  • Nothing else in the series changed.

cargo test --all-targets passes on the rebased branch, cargo fmt --check is clean, and clippy reports nothing in the files this touches.

@rainliu rainliu left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There are also robustness gaps (fine as follow-ups)

  1. A stalled TURN TCP connection freezes the whole driver. poll_writes awaits tcp_transport.write(), which awaits write_all and so waits for the socket to become writable.

    • If the connection is black-holed (network handover, middlebox), the send buffer fills and the event loop stops: no reads, no timers, no ICE restart, no close().
    • The stall lasts until the kernel gives up, which can be many minutes.
    • The pattern already exists for ICE-TCP, but this PR makes it the primary path on exactly the networks where TCP stalls happen.
    • A fix would be a write deadline, or a bounded per-stream queue with a non-blocking write that drops on overflow, treating a stuck stream as lost.
  2. A server that accepts TCP but never answers holds gathering for 39.5 s. The connect is bounded at 5 s, but after rtc#254 the Allocate over TCP waits the full Ti (UDP gives up after about 8 s). A captive proxy that accepts any TCP connection would do this, and a 401 retry could double it. Non-trickle apps waiting for Complete will stall. I'd add a gathering deadline for the TCP Allocate that marks gather_finished without killing the client.

  3. No TURN-over-TCP at all when there are no UDP sockets. gather() derives the address families to connect from self.local_addrs, which are the UDP sockets. A peer built with only with_tcp_addrs gets zero connects, even though the code comment says the TCP source address "has nothing to do with the UDP sockets". Either derive families from the resolved server addresses or document the limit.


/// The outcome of a [`ConnectTcp`](RTCTurnRelayEventOut::ConnectTcp). Returns the
/// four-tuple to register as a TURN stream, or `None` when there is nothing to keep.
pub(crate) fn on_tcp_connected(

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Gathering can hang if on_tcp_connected errors (turn_relayer.rs, the TurnClient::new(...)? and client.allocate(...)? lines). The pending entry is already removed, but the ? returns skip maybe_emit_gathering_complete(). If that was the last pending item, the relayer stays in Gathering forever; the driver only logs "TURN over TCP could not start". This is unlikely to trigger, and the fix is to call maybe_emit_gathering_complete() on the error path.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 0ef9faf. Both ? paths now settle gathering before returning the error, like the connect failure and the collision above them.

The test drives it through the constructor rather than asserting on the code: a four-tuple whose ends disagree on address family makes TurnClient::new refuse (it resolves the server for the local family), the error still reaches the caller, and TurnGatheringComplete is emitted instead of the relayer waiting for a candidate that is never coming.

let result = match crate::runtime::timeout(
&*runtime,
TURN_TCP_CONNECT_TIMEOUT,
runtime.connect_tcp(server),

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No TCP_NODELAY on the TURN connection. connect_tcp (tokio and smol) never sets it. This stream now carries every media and data packet as a separate small write, so Nagle plus delayed ACK will add latency spikes of tens of milliseconds. ICE-TCP already had this gap, but it matters far more here. A set_nodelay(true) in connect_tcp would fix it.

The set_nodelay(true) should be added inside runtime implementations

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 8220b52, in both runtimes: set_nodelay(true) right after the connect, inside connect_tcp, so ICE-TCP gets it as well.

The test reads the option off the socket rather than off the code that sets it: it finds this process's socket by the local address the stream reports (/proc/self/fd, Linux-only like the existing connect_tcp_does_not_block_the_executor) and asks the kernel. It failed before the change on the tokio runtime and passes on both now.

@mnaza

mnaza commented Oct 18, 2026

Copy link
Copy Markdown
Author

@rainliu thanks for the review — all of it is fair. Pushed, and rebased on master: the rtc bump is gone from this branch because the merge carried it, so the submodule is now master's own pointer (07423df2, which contains #254).

Addressed here:

  • Gathering can hang if on_tcp_connected errors — 0ef9faf. Both ? paths settle gathering first.
  • No TCP_NODELAY — 8220b52, in both runtimes, inside connect_tcp, so ICE-TCP benefits too. The test asks the kernel for the option rather than trusting the call site.
  • No TURN over TCP without UDP sockets (your gap 3) — 0905875. Small enough to do now rather than defer: the UDP sockets still decide the families when there are any, and when there are none the server's resolved addresses do. A peer built with with_tcp_addrs alone now gets a connect. The comment that claimed the source address has nothing to do with the UDP sockets says what the code actually does.

Taking you up on follow-ups for the two that are real work:

  • A stalled TCP connection freezes the driver. You are right that this PR makes it the primary path on the networks where it happens. I'd rather do it as a bounded per-stream queue with a non-blocking write that drops on overflow and treats a stuck stream as lost, than a write deadline — a deadline still leaves the driver parked for its duration, and the queue gives ICE something to fail over from. It touches ICE-TCP equally, so it wants its own PR and its own test for the black-holed case.
  • 39.5 s gathering hold against a server that accepts and never answers. A gathering deadline for the TCP Allocate that marks gather_finished without killing the client, as you describe. The 401 retry doubling it is the part worth a test.

I'll open both unless you would rather they land here first.

@mnaza

mnaza commented Oct 18, 2026

Copy link
Copy Markdown
Author

Both robustness follow-ups are written and tested. They sit on a branch stacked on this one
rather than in it, so nothing moves under your review:
mnaza:turn-tcp-gathering-deadline.
Say the word and I'll either fold the two commits into this PR or open them as a PR once this
one lands — whichever you prefer.

Bounding the Allocate over TCP (b7855e73). A TCP client now carries a gathering deadline
of 8 s, which is what UDP's own schedule spends on a silent server (200 ms doubling to a
1600 ms cap, seven requests = 7.8 s), so a TURN URL costs gathering the same either way. It
bounds the allocation rather than each transaction, so the authenticated Allocate a 401
starts cannot double the wait, and it only marks the client finished for gathering — the
client lives on, and an answer that does arrive late still emits its relay candidate.

Queueing writes (047cf22c). Each stream gets a bounded queue (256 KiB) and at most one
write in flight, completing through the driver's select! loop like reads and accepts, so
nothing on the write path is awaited inline any more. Past the cap the connection is carrying
nothing, so the stream is dropped and reported lost — which for a TURN stream ends the client
using it and lets ICE fail over instead of waiting. One wrinkle worth naming: a stream the
relayer has released is held open until its queue drains, because the last thing on it is the
Refresh(LIFETIME=0) that releases the allocation; close() gives that 200 ms and then goes,
since a stream that is not draining is exactly what the queue exists to survive. The
turn_release_on_close tests still pass, including the stuck-driver one.

While writing the test for this, something bigger turned up, and it isn't TCP's

The new integration test uses a TURN server that accepts the connection and then says
nothing. I expected gathering to end at Ti, 39.5 s. It never ended — not in 60 s. And not
over UDP either: 30 s with a silent UDP server, no TurnGatheringComplete.

rtc_turn::Client::allocate() returns the id of the authenticated retry, because the
anonymous request is answered with 401; Event::AllocateResponse follows that convention.
But an exhausted transaction was reported under the id it was stored with — the anonymous
request's — so tid == managed_client.allocate_tid in poll_event never matched,
gather_finished was never set, and gathering waited on an allocation that was never coming.
On master, over either transport. Fixed in webrtc-rs/rtc#281, with the measurement: the same
silent server now releases gathering in 7.81 s over UDP.

So the deadline in b7855e73 is not redundant with it — over TCP the alternative is Ti's
39.5 s against UDP's 7.8 s — but it is no longer the only thing that ends gathering here, and
I thought you'd want to know the UDP path had the same hole.

Numbers

Against the silent TCP server: gathering 8.003 s, close() 0.6 ms. 69 lib tests on
tokio, 71 on smol, and the full integration sweep green — no failures in any target,
turn_release_on_close and the ICE-TCP tests included. cargo fmt clean, no new clippy
warnings.

@rainliu

rainliu commented Oct 25, 2026

Copy link
Copy Markdown
Member

Please rebase it to resolve conflicts

mnaza added 8 commits October 31, 2026 13:55
…hen they end

RTCTcpTransport framed every stream with RFC 4571's length prefix, which is
ICE-TCP's framing. A connection to a TURN server carries STUN and
ChannelData back to back with no prefix (RFC 8656 §12.5), so it could not
share that path.

Streams now carry their framing from registration: register_stream keeps
RFC 4571 for ICE-TCP, register_turn_stream splits with TurnStreamDecoder and
writes messages as they are. Around that:

- The peer-address fallback that ICE-TCP writes rely on never picks a TURN
  connection, so ICE traffic cannot land on one.
- A TURN connection that ends — EOF, a read error, or bytes that are not
  TURN — is removed and queued for take_closed_turn_streams, and a later
  write to it is an error rather than Ok(0), so the relayer's existing
  write-failure path runs. A reset ends a TURN connection instead of
  re-arming a read on it.
- ICE-TCP behaviour is unchanged: test_ice_tcp_only_connection passes, and a
  unit test pins its length prefix.

Refs webrtc-rs#848.
The relayer skipped every turn: URL that was not UDP, so a peer whose
network lets TCP out but not UDP gathered no relay candidate at all.
turn:…?transport=tcp is now used; turns: is still skipped, for the TLS
change that follows.

For a TCP URL the relayer does not create a client straight away. It asks
the host for a connection — one per server and address family, since the
connection's source address is the kernel's and unrelated to the UDP
sockets — and the driver opens it off the event loop with a 5 s bound, the
way active ICE-TCP connects already work. on_tcp_connected then creates the
client over TCP, asking for a UDP relay (RFC 8656 §7.1), and the driver
registers the stream with TURN framing. Around that:

- Gathering does not complete while a connect is pending, and a failed or
  timed-out connect ends that server's part in it.
- Connect ids come from a process-wide counter, so one that finishes after
  an ICE restart or a reconfiguration matches nothing and its stream is
  dropped.
- A TURN connection that ends is reported to the relayer through the
  existing SocketWriteFailure path, and a client the relayer lets go of on
  reconfiguration releases its connection.
- Inbound matching checks the transport, so a datagram can never be taken
  for a stream client's traffic even when a TCP source port equals a UDP
  socket's.

Refs webrtc-rs#848.
A TCP twin of run_mock_turn_server: the same answers, on a stream, split
with TurnStreamDecoder. Two tests on it:

- a relay-only peer connection given turn:…?transport=tcp gathers a relay
  candidate and no host candidate, and the server sees REQUESTED-TRANSPORT
  17 — the connection is TCP, the relay is UDP;
- a TURN server whose TCP port refuses the connection costs it its relay but
  lets gathering complete, promptly, without one.

Each was run against a relayer broken the way it guards — TCP URLs skipped
again, and a failed connect that never lets go of gathering — and failed.

Refs webrtc-rs#848.
…al server

The mock proves gathering; this proves the data path. Two relay-only peers
connect through one TURN server — the offerer reaching it over TCP, the
answerer over UDP — and a data-channel message crosses. With the offerer
limited to relay candidates and given only a transport=tcp URL, there is no
way across but a relay allocated, refreshed and permitted over TCP.

Skips unless WEBRTC_TURN_TCP_SERVER is set, like turn_credential_rotation;
the module docs give the coturn command it was run against. Against coturn
4.6 it passes, and with TCP URLs skipped again it fails at the offerer's
gathering.

Kept as its own commit, to drop if an env-gated test is not wanted here.

Refs webrtc-rs#848.
Review follow-ups to TURN over TCP.

A credential-only change re-signs established allocations instead of
regathering them, and a client still mid-Allocate already makes it fall
through to the full teardown. A TCP connect in flight is the same thing —
its client does not exist yet — but was not counted, so beside an
established UDP client it would come up on the old password. It now counts.

A connected stream that cannot report its peer address is treated as a
failed connect rather than given the resolved address, which may not be
the one it reached.

Refs webrtc-rs#848.
Everything after the pending entry is removed is a way out of
on_tcp_connected, and two of those ways were an early `?`: a client
whose constructor refuses the connection, and an Allocate that cannot
be started. The pending entry is gone by then, so the relayer never
reaches maybe_emit_gathering_complete and stays in Gathering for good,
leaving one line in the log to explain a peer that never finishes.

Both failures now settle gathering before returning the error, like the
connect failure and the collision above them.
gather derived the address families to connect from self.local_addrs,
which are the UDP sockets, while the comment beside it said the TCP
source address has nothing to do with them. Both cannot be true: a peer
built with with_tcp_addrs alone got zero connects and no relay
candidate, which is exactly the TLS-only egress this path is for.

The UDP sockets still say which families the host has, so they are kept
as the answer when there are any. When there are none, the server's own
resolved addresses are the only word on what is worth trying.
connect_tcp never set it, in either runtime. ICE-TCP has always had the
gap; with TURN over TCP this stream carries every media and data packet
as its own small write, so Nagle holds each one until the last is
acknowledged — tens of milliseconds of added latency, on exactly the
networks that forced TCP in the first place.

The test reads the option off the socket rather than off the code that
sets it: it finds this process's socket by the local address the stream
reports and asks the kernel.
@mnaza

mnaza commented Nov 8, 2026 •

Copy link
Copy Markdown
Author

Rebased onto current master (1c07e9f), head is now 483eb7e. Six of the eight commits are unchanged; two needed resolving against #928 in turn_relayer.rs:

  • rotate_credentials is gone, as on master. My hunk only carried it as context; on_tcp_connected and take_released_tcp_streams stay. Master's new credential_rotation_preserves_existing_allocation_authentication test is kept intact above the TCP test helpers.
  • The pending-TCP check in is_credential_only_change is kept. A TCP connect still in flight has no client yet and would come up on the old password, so it is treated like a client still mid-Allocate: not a credential-only change. The comment is reworded to say that.

Verified locally after the rebase: fmt clean, relayer + tcp_transport lib tests, ice_test 10/10, turn_credential_rotation, turn_release_on_close, clippy on the lib, and turn_over_tcp against a local coturn 4.6 (WEBRTC_TURN_TCP_SERVER set; the data channel message crosses the TCP-reached relay in 6.7 s). Correction to the first version of this comment: that last run had been skipped, not passed — the variable was not set. It has been run since. The workflow runs on this head are waiting for approval.

On the review's follow-ups: the TCP gathering deadline (2) and a bounded write queue so a stalled stream cannot freeze the driver (1) are done on a branch on top of this one; I will open them as a separate PR once this lands, or fold them in here if you would rather review them together.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants