rtci-stream-driver
A socket driver for a sans-I/O WebRTC engine (ICE-TCP, TURN over TCP and TLS, whole peer connections) on an async runtime of your choice. 6 public modules, 82 items at 0.5.0.
cargo add [email protected] · crates.io · docs.rs · README on GitHub· MSRV 1.89
README
The reference driver for the stream half of the rtci engine's sans-I/O interface: it owns the TCP sockets, on the async runtime it is given, and carries out what the engine asks (listen, connect, close, reset, resolve a name or SRV / NAPTR records), and reports back what happened. The engine decides everything else: which ICE-TCP candidates exist (RFC 6544), RFC 4571 framing, TURN over TCP and TLS, the Happy Eyeballs race (RFC 8305).
It also has what a server decides and the engine does not (sockets): port ranges, which local addresses get candidates, one UDP port and one passive ICE-TCP port shared by many peer connections; and an opt-in PCP / NAT-PMP client for NAT-assisted candidates (nat_mapping, RFC 6887, RFC 6886).
Use
while let Some(command) = pc.poll_stream_command() { driver.execute(command) }
while let Some(transmit) = pc.poll_stream_transmit() { driver.write(transmit) }
match driver.next().await {
DriverInput::Event(event) => pc.handle_stream_event(now, event)?,
DriverInput::Read { id, data } => pc.handle_stream_read(now, id, &data)?,
DriverInput::Accepted(accepted) => { /* pc.handle_stream_accepted, then driver.adopt */ }
}
The crate documentation has the command table and the complete loop; the root crate's stream-driver-loopback example runs two peer connections over loopback TCP through it. Feature dns-records adds SRV / NAPTR lookups and per-family answers to TokioRuntime through hickory-resolver (0.26.2 or later, which has no open RustSec advisory; the lookups are those of a stub resolver asking the system's name servers, without DNSSEC validation); without it, records are answered as none and names through the system resolver.
A whole peer connection
peer::PeerDriver (feature peer, on by default, which depends on rtci) drives an rtci peer connection over sockets it owns, its UDP host sockets included: it gathers when a transport begins gathering, and again by itself when the engine says a transport needs new local candidates (OnLocalCandidatesNeeded: a new DTLS association runs on a new 3-tuple, RFC 8842 section 5.1), binding new ports in its range and closing the previous sockets once a pair on the new ones is selected. The application only signals.
A connection with mDNS on gets its mDNS carried too: at its first mDNS datagram the driver binds the host's mDNS sockets (port 5353, the IPv4 and, where available, IPv6 groups), and every driver of the process sends its mDNS within one message budget (peer::process_mdns_rate_limit), the implementation-wide rate limit of draft-ietf-mmusic-mdns-ice-candidates section 7.1.
I/O, and bringing your own runtime
Unlike the other crates of the workspace this one does I/O. The engine itself still never touches a socket or a clock; the driver does, through the async runtime it is given.
Everything that touches a reactor or a clock goes through one object-safe trait, runtime::Runtime, given to each driver as an Arc<dyn Runtime>:
Injected (Runtime) | Not injected |
|---|---|
spawn (a JoinHandle trait object; dropping it detaches) | channels and wake-ups between the driver's tasks (async-channel, executor-agnostic) |
now, sleep_until: the clock every time given to the engine comes from | runtime::sleep, timeout, timeout_at, yield_now: free functions on top |
bind_udp, bind_udp_multicast (AsyncUdpSocket: poll form, batched receive, per-datagram traffic class) | |
listen_tcp, connect_tcp (AsyncTcpListener, AsyncTcpStream) | |
resolve_host, and the optional resolve_family / resolve_records | |
block_on (a future that need not be Send) |
There is no global or default runtime, and none can be set: StreamDriver::with_runtime and PeerDriver::with_runtime take one. With the default feature runtime-tokio, StreamDriver::new, StreamDriver::default and PeerDriver::new use TokioRuntime::new() (the tokio runtime of the calling code, as tokio::spawn does). The one process-wide state the crate keeps is the mDNS budget above: the mDNS draft requires an implementation-wide rate limit, and it is a budget, not a runtime.
| Feature | Gives |
|---|---|
runtime-tokio (default) | TokioRuntime, and StreamDriver::new / default, PeerDriver::new |
runtime-smol | SmolRuntime |
runtime-mock | MockRuntime: virtual time and an in-memory network |
peer (default) | peer::PeerDriver (depends on rtci) |
dns-records | hickory lookups in TokioRuntime (turns runtime-tokio on) |
Features only decide which runtime types exist; several can be on at once, and with default-features = false and none of them the crate builds without any async runtime in its dependency tree (CI checks it). Your own runtime implements Runtime; the workspace's examples/custom-runtime does it over async-executor and async-io in about 300 lines, with the helpers runtime::{std_udp, std_multicast, std_tcp_listener, std_tcp_connect_start, TrafficClassMarker, ...} for runtimes whose sockets are real ones.
MockRuntime runs drivers on virtual time: its clock moves when told (MockClock::advance) or, inside MockRuntime::run, to the next timer whenever nothing can run; its network (MockNet) carries UDP, multicast and TCP between mock sockets with per-link delay, seeded loss and blocking, a datagram filter and a log. Two PeerDrivers connect on it with no socket, and a 30-second ICE consent expiry takes no wall time (tests/virtual_time.rs).
The design follows the upstream project's "Bring Your Own Async Runtime" (webrtc.rs, 2026-07-30, <https://webrtc.rs/blog/2026/07/30/pluggable-async-runtime.html>); where it differs (the clock is injected, sockets are bound by address, the socket types are the crate's own), the crate documentation of runtime says why.
Licence
Licensed under either of the MIT licence or the Apache License, Version 2.0, at your option.
This crate is part of the rtci workspace, which descends from webrtc-rs/rtc and is developed independently; FORK.md lists what it carries over upstream. Upstream's licence and copyright notices are retained.
rtci_stream_driver
The reference driver for the stream half of WebRTC.rs's sans-I/O engine (rtci_shared::stream): it owns the TCP sockets, on the async runtime it is given (runtime), and does what the engine asks.
- mod
nat_mappingNAT-assisted candidates (RFC 6544 section 5.3, RFC 8445 section 5.1.1.2): an opt-in client of the Port Control Protocol (PCP, RFC 6887) with a fallback to NAT-PMP (RFC 6886), asking the gateway for a port mapping. Nothing here runs unless the application calls it, and it adds no dependency: one UDP socket of the driver'sRuntime. - mod
peercfg(feature = "peer")A whole peer connection driven over sockets the driver owns (featurepeer, on by default): its UDP sockets for the ICE host candidates, and the TCP sockets of the engine's stream interface through aStreamDriver. - mod
runtimeThe async runtime a driver runs on, injected per driver. - mod
socketsServer-side socket choices, which belong to the driver and not to the engine: port ranges, which local addresses get candidates, and one UDP port or one ICE-TCP listening port shared by many peer connections. - struct
AcceptedA connection accepted on a listener, waiting for its id. - struct
DriverConfigThe driver's settings. - struct
StreamDriverOwns the sockets of one engine (see the crate documentation). - enum
DriverInputWhat the driver has for the engine.
rtci_stream_driver::nat_mapping
NAT-assisted candidates (RFC 6544 section 5.3, RFC 8445 section 5.1.1.2): an opt-in client of the Port Control Protocol (PCP, RFC 6887) with a fallback to NAT-PMP (RFC 6886), asking the gateway for a port mapping. Nothing here runs unless the application calls it, and it adds no dependency: one UDP socket of the driver's Runtime.
- struct
MappingA mapping the gateway granted. - struct
MappingConfigHowmap_portasks. - enum
MappingProtocolWhich protocol answered. - enum
NatPmpAnswerA NAT-PMP answer. - enum
PcpAnswerWhat a PCP response says. - enum
ProtocolThe transport a mapping is for. - fn
candidate_lineThe NAT-assisted candidate ofmappingfor the localbase(RFC 6544 sections 4.2 and 5.3): a server-reflexive candidate with the type preference 105, for the application to add withadd_local_candidate. Over TCPtcp_typenames its direction (RFC 6544 section 4.2: for NAT-assisted candidates simultaneous-open 6, active 4, passive 2; an active one is signalled on port 9). - fn
map_portAsks the gateway atgatewayfor a mapping ofinternal_portonlocal_ip(the interface the gateway is reached from): PCP first, NAT-PMP when the gateway does not speak PCP.Ok(None)when no gateway answered; an error when it refused. - fn
nat_pmp_address_requestA NAT-PMP external address request (RFC 6886 section 3.2). - fn
nat_pmp_map_requestA NAT-PMP mapping request (RFC 6886 section 3.3). - fn
parse_nat_pmp_responseParses a NAT-PMP response toopcode(RFC 6886 sections 3.2, 3.3, 3.5). - fn
parse_pcp_map_responseParses a PCP MAP response to the request withnonce(RFC 6887 sections 7.2 and 11.1).Nonefor anything else (not PCP, not a MAP response, another nonce). - fn
pcp_map_requestA PCP MAP request (RFC 6887 sections 7.1 and 11.1): 24-byte header, 36-byte MAP opcode. - const
SERVER_PORTThe port PCP and NAT-PMP servers listen on (RFC 6887 section 19.1, RFC 6886 section 3).
rtci_stream_driver::peercfg(feature = "peer")
A whole peer connection driven over sockets the driver owns (feature peer, on by default): its UDP sockets for the ICE host candidates, and the TCP sockets of the engine's stream interface through a StreamDriver.
- struct
MdnsFailureWhy the driver's mDNS of one address family stopped: whatPeerDriverEvent::MdnsUnavailabletells the application. - struct
PeerDriverDrives anRTCPeerConnectionover sockets of its own (see the module documentation). - struct
PeerDriverConfigWhat aPeerDriverbinds. - enum
MdnsStageWhat failed in aMdnsFailure. - enum
PeerDriverEventSomething the driver itself reports to the application (PeerDriver::poll_driver_event), beside the connection's own events. - fn
process_mdns_rate_limitfromcrate::mdns_io::process_mdns_rate_limitThe message budget everyPeerDriverof this process takes its mDNS from, unless its configuration names another (PeerDriverConfig::mdns_rate_limit): 40 messages at once, then 10 a second (MdnsRateLimit::default). One budget for the process is draft-ietf-mmusic-mdns-ice-candidates section 7.1's "implementation-wide rate limit". The returned value is a handle: every clone takes from the … - fn
set_process_mdns_rate_limitfromcrate::mdns_io::set_process_mdns_rate_limitSets the process's mDNS budget (process_mdns_rate_limit) instead of the default, once, before its first use (the first driver that sends mDNS uses it). - const
MDNS_MULTICAST_IPV6fromcrate::mdns_io::MDNS_MULTICAST_IPV6The mDNS IPv6 link-local group (RFC 6762 section 3).
rtci_stream_driver::runtime
The async runtime a driver runs on, injected per driver.
- mod
mockcfg(feature = "runtime-mock")MockRuntime(featureruntime-mock): virtual time and an in-memory network, so that driven connections run deterministically and a 30-second timeout takes no wall time. - struct
Elapsedtimeoutran out. - struct
MulticastConfigWhat a multicast socket is bound and joined to. - struct
MulticastInterfaceSelectorApplies aTransmit::sourceto a real multicast socket bound to the unspecified address: before a datagram to a multicast group, it sets the interface the datagram leaves by (IP_MULTICAST_IFto the source address,IPV6_MULTICAST_IFto the index of the interface that holds it) when it differs from the last one set. The system then sends from that interface's address: on Linux exactly the … - struct
RecvMetaWhatAsyncUdpSocket::poll_recvsays about one buffer it filled. - struct
SmolRuntimecfg(feature = "runtime-smol")fromsmol_runtime::SmolRuntimeThe smol runtime: tasks on smol's global executor, timers and sockets onasync-io's reactor, name lookups on smol's thread pool. It needs no setup and can be used from any thread, inside or outsidesmol::block_on. - struct
TokioRuntimecfg(feature = "runtime-tokio")fromtokio_runtime::TokioRuntimeThe tokio runtime. - struct
TrafficClassMarkerApplies aTransmit::traffic_classto a real socket: setsIP_TOS/IPV6_TCLASSwhen the value differs from the last one set, and stops asking once the platform refused (its datagrams then leave unmarked,AsyncUdpSocket::unmarked). For built-in and third-party runtimes whose sockets have a file descriptor. - struct
TransmitOne datagram (or, withsegment_size, several of one size back to back) to send. - trait
AsyncTcpListenerA TCP listener of a runtime. - trait
AsyncTcpStreamA TCP connection of a runtime.&selfmethods: the driver's reader and writer tasks share oneArc. - trait
AsyncUdpSocketA UDP socket of a runtime, in the poll form of quinn-udp's so that batched send and receive (sendmmsg,recvmmsg, GSO, GRO) fit. - trait
JoinHandleA task spawned withRuntime::spawn. Dropping it detaches the task. - trait
RuntimeWhat a driver needs from an async runtime: the primitives that touch a reactor or a clock. - fn
interface_indexThe index of the interface that holds the IPv6 addressip(whatIPV6_MULTICAST_IFand an IPv6 group membership name an interface by),Nonewhen no interface of the host holds it. - fn
interface_nameThe name of the interface that holdsip,Nonewhen no interface of the host holds it. - fn
reset_on_closeMakessocket's close abortive (SO_LINGER0: RST instead of FIN), forAsyncTcpStream::reset_on_close. - fn
set_and_read_traffic_classSetssocket's TOS / Traffic Class and reads it back (forAsyncTcpStream::set_traffic_class). - fn
sleepWaitsdurationonruntime's clock. - fn
std_multicastA non-blocking std UDP socket joined asconfigsays: for IPv4 what rtci-mdns'MulticastSocketbuilds (bound to the group on Linux, to 0.0.0.0 elsewhere), for IPv6[::]:port, IPv6 only; a membership of the group on every interface ofMulticastConfig::interfaces(the default interface when there is none). - fn
std_tcp_boundA non-blocking TCP socket bound tolocal, for a runtime to connect to a peer. - fn
std_tcp_connect_startStarts a non-blocking TCP connection fromlocaltoremote: the socket is bound, and the handshake runs. A runtime waits for it to become writable, then readstake_errorandpeer_addr(what async-io's ownconnectdoes), for runtimes whose connect cannot bind a local address first. - fn
std_tcp_listenerA non-blocking std TCP listener onlocal, backlog 128. - fn
std_udpA non-blocking std UDP socket onlocal: what the built-in runtimes wrap. - fn
timeoutfuture's output, orElapsedifdurationofruntime's clock passes first. - fn
timeout_atfuture's output, orElapsedifruntime's clock reachesdeadlinefirst. - fn
yield_nowGives other tasks a turn: pending once, with the task woken at once. - type
BoxFutureA boxed future that can move between threads. - use
MockClockcfg(feature = "runtime-mock")frommock::MockClockThe virtual clock of aMockRuntime. - use
MockNetcfg(feature = "runtime-mock")frommock::MockNetThe in-memory network of aMockRuntime. - use
MockRuntimecfg(feature = "runtime-mock")frommock::MockRuntimeA runtime on virtual time with an in-memory network (see the module documentation).
rtci_stream_driver::runtime::mockcfg(feature = "runtime-mock")
MockRuntime (feature runtime-mock): virtual time and an in-memory network, so that driven connections run deterministically and a 30-second timeout takes no wall time.
- struct
DatagramRecordOne datagram of theMockNet::log. - struct
LinkConfigOne direction between two IP addresses of theMockNet. - struct
MockClockThe virtual clock of aMockRuntime. - struct
MockDatagramA datagram as theMockNetsees it, for a filter. - struct
MockNetThe in-memory network of aMockRuntime. - struct
MockRuntimeA runtime on virtual time with an in-memory network (see the module documentation). - enum
FateWhat became of a datagram. - type
DatagramFilterA filter of theMockNet:falsedrops the datagram.
rtci_stream_driver::sockets
Server-side socket choices, which belong to the driver and not to the engine: port ranges, which local addresses get candidates, and one UDP port or one ICE-TCP listening port shared by many peer connections.
- struct
AddressFilterWhich local addresses get host candidates. - struct
PortRangeAn inclusive range of ports for the sockets a peer connection gets. - struct
UfragMuxRoutes what arrives on a shared port to the peer connection it is for: by the receiver's ufrag of the first Binding request from an address, then by that address. - fn
accept_by_ufragAccepts the next connection on a shared ICE-TCP port and reads its first RFC 4571 frame (fortimeoutat most) to learn which peer connection it is for. Connections whose first frame is not a Binding request with a USERNAME are dropped and the next one is awaited. - fn
bind_runtime_udp_in_rangeA UDP socket ofruntimeonip, on a free port ofrange, skipping refused ports asbind_udp_in_rangedoes. - fn
bind_tcp_listener_in_rangeA TCP listener ofruntimeonip, on a free port ofrange. - fn
bind_udp_in_rangeA UDP socket onip, on a free port ofrange. Ports the host refuses (an excluded port range on Windows, a privileged port) are skipped like ports in use. - fn
binding_request_ufragsThe ufrags of a STUN Binding request:(receiver, sender)from its USERNAME (RFC 8445 section 7.2.2).Nonefor anything else. - fn
set_traffic_classSets the byte the socket's packets carry in the IPv4 TOS / IPv6 Traffic Class field: the DSCP in its upper six bits (RFC 2474 section 3), the ECN codepoint in the lower two (RFC 3168 section 5).ipv6says which option (IPV6_TCLASSorIP_TOS) the socket's family takes. - fn
traffic_classThe byte the socket's packets carry in the IPv4 TOS / IPv6 Traffic Class field, as the operating system reports it (getsockoptofIP_TOS/IPV6_TCLASS). - type
InterfaceFilterKeeps an interface by name. - type
IpFilterKeeps an address.
Generated from the sources of rtci-stream-driver 0.5.0 at its release tag. Items made by macros and methods are on docs.rs.