Skip to main content

rtci_stream_driver/
peer.rs

1//! A whole peer connection driven over sockets the driver owns (feature `peer`, on by
2//! default): its UDP sockets for the ICE host candidates, and the TCP sockets of the engine's
3//! stream interface through a [`StreamDriver`].
4//!
5//! [`PeerDriver`] gathers for the application and keeps the gathering right across what makes
6//! a transport lose its candidates. The engine has no sockets, so it tells the application
7//! with `RTCPeerConnectionEvent::OnLocalCandidatesNeeded` when a transport needs a new set of
8//! local candidates: a new DTLS association over UDP runs on a new 3-tuple (RFC 8842 section
9//! 5.1), so after an ICE restart for a new association (automatic SRTP re-keying included) or
10//! on the transport that replaced one an answer closed, the transport's previous UDP addresses
11//! are refused. The driver reacts by itself: it binds new UDP ports (inside
12//! [`PeerDriverConfig::udp_port_range`], skipping ports the host refuses), adds their host
13//! candidates for the event's section, ends the generation, and closes the previous sockets
14//! only once a candidate pair on a new one is selected for that transport (and then after
15//! [`PeerDriverConfig::retired_socket_linger`], for what the peer still sends there before its
16//! own selection switches), or the transport is closed: until then the previous path keeps
17//! carrying the transport's packets. The engine's
18//! ICE-TCP listener is kept (RFC 8842 asks a new 3-tuple of unordered transports only), and
19//! its server-reflexive and TURN gathering follow the new host candidates by themselves.
20//!
21//! With `SettingEngineBuilder::with_dtls_new_association_on_previous_addresses(true)` the
22//! engine keeps the candidates and fires no event: the driver keeps its sockets and gives their
23//! candidates to each new ICE generation again.
24//!
25//! # The loop
26//!
27//! ```text
28//! let mut driver = PeerDriver::new(pc, PeerDriverConfig::on(vec![ip]));
29//! // offer / answer through the application's signalling, on driver.pc_mut();
30//! // after the first local description, the driver gathers by itself;
31//! loop {
32//!     driver.step(Duration::from_millis(20)).await?;
33//!     while let Some(event) = driver.poll_event() {
34//!         // signal OnIceCandidateEvent candidates to the peer, answer negotiation-needed, ...
35//!     }
36//!     while let Some(read) = driver.pc_mut().poll_read() { /* media, data channels */ }
37//! }
38//! ```
39
40use crate::sockets::{self, PortRange};
41use crate::{DriverConfig, DriverInput, StreamDriver};
42use bytes::BytesMut;
43use rtci::peer_connection::RTCPeerConnection;
44use rtci::peer_connection::event::{
45    RTCLocalCandidatesNeededEvent, RTCLocalCandidatesNeededReason, RTCPeerConnectionEvent,
46    RTCTransportEventKind,
47};
48use rtci::peer_connection::state::{RTCIceGatheringState, RTCSignalingState};
49use rtci::peer_connection::transport::{
50    CandidateConfig, CandidateHostConfig, RTCIceCandidate, RTCIceCandidateInit, RTCIceProtocol,
51    RTCIceTransportState, RTCTransportId,
52};
53use rtci::sansio::Protocol;
54use rtci::shared::error::{Error, IoError, Result};
55use rtci::shared::{TaggedBytesMut, TransportContext, TransportProtocol};
56use std::collections::{HashSet, VecDeque};
57use std::io;
58use std::net::{IpAddr, SocketAddr};
59use std::sync::Arc;
60use std::time::{Duration, Instant};
61use tokio::net::UdpSocket;
62use tokio::sync::mpsc;
63use tokio::task::JoinHandle;
64
65/// What a [`PeerDriver`] binds.
66#[derive(Debug, Clone)]
67pub struct PeerDriverConfig {
68    /// The local addresses that get a host candidate: one UDP socket per address for each
69    /// transport.
70    pub addresses: Vec<IpAddr>,
71    /// The UDP sockets take a port of this range (any free port without one). A port the
72    /// host refuses to applications is skipped like a port in use
73    /// ([`sockets::bind_udp_in_range`]).
74    pub udp_port_range: Option<PortRange>,
75    /// The engine's TCP sockets (ICE-TCP, TURN over TCP and TLS), with their port range.
76    pub streams: DriverConfig,
77    /// How long a previous socket stays open after its transport selected a pair on a new one:
78    /// the peer may still send to the previous address until its own selection switches
79    /// (each side selects on its own), and those packets must not be lost. 5 seconds by
80    /// default.
81    pub retired_socket_linger: Duration,
82}
83
84impl PeerDriverConfig {
85    /// Host candidates on `addresses`, any free port.
86    pub fn on(addresses: Vec<IpAddr>) -> Self {
87        Self {
88            addresses,
89            udp_port_range: None,
90            streams: DriverConfig::default(),
91            retired_socket_linger: Duration::from_secs(5),
92        }
93    }
94}
95
96/// One UDP socket of the connection, with the reader that hands its datagrams to the driver.
97struct HostSocket {
98    socket: Arc<UdpSocket>,
99    local: SocketAddr,
100    /// The section its candidate was added for.
101    mid: String,
102    /// Set when the engine refused its address for `transport` (`OnLocalCandidatesNeeded`):
103    /// it is closed once that transport has selected a pair on another socket, or closed.
104    retired_for: Option<RTCTransportId>,
105    /// Once its transport selected a pair on another socket: when it is closed.
106    close_at: Option<Instant>,
107    reader: JoinHandle<()>,
108}
109
110impl Drop for HostSocket {
111    fn drop(&mut self) {
112        self.reader.abort();
113    }
114}
115
116/// Drives an `RTCPeerConnection` over sockets of its own (see the [module documentation](self)).
117pub struct PeerDriver {
118    pc: RTCPeerConnection,
119    streams: StreamDriver,
120    config: PeerDriverConfig,
121    sockets: Vec<HostSocket>,
122    datagrams_tx: mpsc::UnboundedSender<(SocketAddr, SocketAddr, Vec<u8>)>,
123    datagrams: mpsc::UnboundedReceiver<(SocketAddr, SocketAddr, Vec<u8>)>,
124    /// The engine's events, for the application, after the driver had its look.
125    events: VecDeque<RTCPeerConnectionEvent>,
126    /// The transports whose generation the driver gathered for on an
127    /// `OnLocalCandidatesNeeded`: their `gatheringstatechange` that follows needs nothing.
128    gathered: HashSet<RTCTransportId>,
129    /// Datagrams the engine wrote that no socket sent ([`Self::unsent_datagrams`]).
130    unsent: u64,
131}
132
133impl PeerDriver {
134    /// A driver for `pc`, with no socket yet: it binds when the connection's first local
135    /// description begins gathering. Must be used inside a tokio runtime.
136    pub fn new(pc: RTCPeerConnection, config: PeerDriverConfig) -> Self {
137        let (datagrams_tx, datagrams) = mpsc::unbounded_channel();
138        Self {
139            pc,
140            streams: StreamDriver::new(config.streams),
141            config,
142            sockets: Vec::new(),
143            datagrams_tx,
144            datagrams,
145            events: VecDeque::new(),
146            gathered: HashSet::new(),
147            unsent: 0,
148        }
149    }
150
151    /// The peer connection.
152    pub fn pc(&self) -> &RTCPeerConnection {
153        &self.pc
154    }
155
156    /// The peer connection, for signalling, media and data channels. Call
157    /// [`flush`](Self::flush) (or [`step`](Self::step)) after changing it, so that what it
158    /// wants to send leaves and the driver sees its events.
159    pub fn pc_mut(&mut self) -> &mut RTCPeerConnection {
160        &mut self.pc
161    }
162
163    /// The local addresses of the UDP sockets open, the previous ones still waiting for a new
164    /// pair included.
165    pub fn local_addresses(&self) -> Vec<SocketAddr> {
166        self.sockets.iter().map(|s| s.local).collect()
167    }
168
169    /// How many datagrams the connection wrote that were not sent: from a local address with
170    /// no open socket (one closed already), or refused by the socket (its send buffer full:
171    /// UDP drops them, as the wire would). Counted so that none is lost unseen.
172    pub fn unsent_datagrams(&self) -> u64 {
173        self.unsent
174    }
175
176    /// The next event of the connection. The driver has already done what is its to do
177    /// (gathering on `OnLocalCandidatesNeeded` and when a transport begins gathering, closing
178    /// the previous sockets on a new selected pair); the application signals the candidates
179    /// of `OnIceCandidateEvent` to the peer and handles the rest.
180    pub fn poll_event(&mut self) -> Option<RTCPeerConnectionEvent> {
181        self.events.pop_front()
182    }
183
184    /// Hands what the connection wants to send to the sockets and the stream driver, and
185    /// reacts to its events, until nothing is left.
186    ///
187    /// # Errors
188    ///
189    /// A socket that cannot be bound for a transport that needs one, or a candidate the
190    /// connection refuses.
191    pub fn flush(&mut self) -> Result<()> {
192        loop {
193            let mut progress = false;
194            while let Some(command) = self.pc.poll_stream_command() {
195                self.streams.execute(command);
196                progress = true;
197            }
198            while let Some(transmit) = self.pc.poll_stream_transmit() {
199                self.streams.write(transmit);
200                progress = true;
201            }
202            while let Some(datagram) = self.pc.poll_write() {
203                self.send(datagram);
204                progress = true;
205            }
206            while let Some(event) = self.pc.poll_event() {
207                self.on_event(&event)?;
208                self.events.push_back(event);
209                progress = true;
210            }
211            if !progress {
212                return Ok(());
213            }
214        }
215    }
216
217    /// One round: flushes, then waits up to `wait` (less when a timer of the connection is due
218    /// first) for a datagram, a stream input or the timer, hands it over, and flushes again.
219    ///
220    /// # Errors
221    ///
222    /// As [`flush`](Self::flush).
223    pub async fn step(&mut self, wait: Duration) -> Result<()> {
224        self.flush()?;
225        let now = Instant::now();
226        let deadline = self
227            .pc
228            .poll_timeout()
229            .map_or(now + wait, |due| due.min(now + wait))
230            .max(now);
231        tokio::select! {
232            Some((local, peer, data)) = self.datagrams.recv() => {
233                self.feed(local, peer, data);
234                while let Ok((local, peer, data)) = self.datagrams.try_recv() {
235                    self.feed(local, peer, data);
236                }
237            }
238            input = self.streams.next() => self.feed_stream(input),
239            _ = tokio::time::sleep_until(deadline.into()) => {}
240        }
241        // The engine's timers; one that fails is the connection's to report (its states).
242        let now = Instant::now();
243        let _ = self.pc.handle_timeout(now);
244        self.sockets
245            .retain(|s| s.close_at.is_none_or(|close_at| close_at > now));
246        self.flush()
247    }
248
249    fn feed(&mut self, local: SocketAddr, peer: SocketAddr, data: Vec<u8>) {
250        // A datagram the engine cannot take (a stray, a late one) is its business, not the
251        // driver's: it goes on.
252        let _ = self.pc.handle_read(TaggedBytesMut {
253            now: Instant::now(),
254            transport: TransportContext {
255                local_addr: local,
256                peer_addr: peer,
257                ecn: None,
258                transport_protocol: TransportProtocol::UDP,
259            },
260            message: BytesMut::from(&data[..]),
261        });
262    }
263
264    fn feed_stream(&mut self, input: DriverInput) {
265        let now = Instant::now();
266        match input {
267            DriverInput::Event(event) => {
268                let _ = self.pc.handle_stream_event(now, event);
269            }
270            DriverInput::Read { id, data } => {
271                let _ = self.pc.handle_stream_read(now, id, &data);
272            }
273            DriverInput::Accepted(accepted) => {
274                if let Some(id) = self.pc.handle_stream_accepted(
275                    now,
276                    accepted.listener,
277                    accepted.local,
278                    accepted.remote,
279                ) {
280                    self.streams.adopt(id, accepted);
281                }
282            }
283        }
284    }
285
286    fn send(&mut self, datagram: TaggedBytesMut) {
287        if datagram.transport.transport_protocol != TransportProtocol::UDP {
288            return;
289        }
290        let sent = self
291            .sockets
292            .iter()
293            .find(|s| s.local == datagram.transport.local_addr)
294            .is_some_and(|host| {
295                // UDP: a datagram the socket cannot take now is lost, as on the wire.
296                host.socket
297                    .try_send_to(&datagram.message, datagram.transport.peer_addr)
298                    .is_ok()
299            });
300        if !sent {
301            self.unsent += 1;
302        }
303    }
304
305    fn on_event(&mut self, event: &RTCPeerConnectionEvent) -> Result<()> {
306        match event {
307            RTCPeerConnectionEvent::OnLocalCandidatesNeeded(needed) => {
308                self.on_candidates_needed(needed)
309            }
310            RTCPeerConnectionEvent::OnSignalingStateChangeEvent(RTCSignalingState::Stable) => {
311                self.match_sockets_to_candidates();
312                Ok(())
313            }
314            RTCPeerConnectionEvent::OnTransportEvent(event) => match &event.event {
315                RTCTransportEventKind::GatheringStateChange(RTCIceGatheringState::Gathering) => {
316                    self.on_gathering_begins(event.ice_transport, event.dtls_transport)
317                }
318                RTCTransportEventKind::SelectedCandidatePairChange(pair) => {
319                    let local = pair.local();
320                    let on_retired = self.sockets.iter().any(|s| {
321                        s.retired_for.is_some()
322                            && s.local.port() == local.port
323                            && s.local.ip().to_string() == local.address
324                    });
325                    if !on_retired {
326                        self.release_after_linger(event.ice_transport);
327                    }
328                    Ok(())
329                }
330                RTCTransportEventKind::IceStateChange(RTCIceTransportState::Closed) => {
331                    self.release(event.ice_transport);
332                    Ok(())
333                }
334                _ => Ok(()),
335            },
336            _ => Ok(()),
337        }
338    }
339
340    /// `OnLocalCandidatesNeeded`: new sockets for the transport, or (`DiscardedBySetting`,
341    /// no address refused) the same sockets' candidates again.
342    fn on_candidates_needed(&mut self, needed: &RTCLocalCandidatesNeededEvent) -> Result<()> {
343        let Some(mid) = needed.mids.first().cloned() else {
344            return Ok(());
345        };
346        let index = needed.sdp_mline_index;
347        self.gathered.insert(needed.ice_transport);
348        if !needed.reason.needs_new_addresses() {
349            let on: Vec<SocketAddr> = self
350                .sockets
351                .iter()
352                .filter(|s| s.retired_for.is_none() && needed.mids.contains(&s.mid))
353                .map(|s| s.local)
354                .collect();
355            if !on.is_empty() {
356                for local in on {
357                    self.pc
358                        .add_local_candidate(host_candidate(local, &mid, index)?)?;
359                }
360                return self.end_of_candidates(&mid, index);
361            }
362            return self.gather_section(&mid, index);
363        }
364        for host in self
365            .sockets
366            .iter_mut()
367            .filter(|s| needed.refused_addresses.contains(&s.local))
368        {
369            host.retired_for = Some(needed.ice_transport);
370        }
371        if needed.reason == RTCLocalCandidatesNeededReason::TransportReplaced {
372            // The transport they served is closed: nothing travels over them any more.
373            self.release(needed.ice_transport);
374        }
375        self.gather_section(&mid, index)
376    }
377
378    /// Back in the stable state, the sockets are matched against the candidates the
379    /// transports hold. A local offer that is rolled back takes its ICE restart back (RFC
380    /// 9429 section 5.7: "any resources or candidates that were allocated by the abandoned
381    /// local description are discarded"), the `OnLocalCandidatesNeeded` it fired included: a
382    /// socket retired for it whose candidate the transport holds again carries the
383    /// transport's packets as before (it is no longer retired), and a socket bound for the
384    /// abandoned generation, whose candidate the transport dropped, is closed. The answer to
385    /// the peer's colliding offer, if it sets up a new association, fires its own event.
386    fn match_sockets_to_candidates(&mut self) {
387        let held: Vec<(String, u16)> = self
388            .pc
389            .dtls_transports()
390            .iter()
391            .flat_map(|t| t.ice_transport().get_local_candidates())
392            .filter(|c| c.protocol == RTCIceProtocol::Udp)
393            .map(|c| (c.address, c.port))
394            .collect();
395        let holds = |local: &SocketAddr| {
396            held.iter()
397                .any(|(address, port)| *port == local.port() && *address == local.ip().to_string())
398        };
399        for host in self.sockets.iter_mut() {
400            if host.retired_for.is_some() && holds(&host.local) {
401                host.retired_for = None;
402                host.close_at = None;
403            }
404        }
405        self.sockets
406            .retain(|s| s.retired_for.is_some() || holds(&s.local));
407    }
408
409    /// A transport begins gathering an ICE generation the driver was not told about: the
410    /// first one (no socket of the transport yet: every section without one gets them), or a
411    /// restart that kept the candidates (each is given to the new generation again).
412    fn on_gathering_begins(
413        &mut self,
414        ice_transport: RTCTransportId,
415        dtls_transport: RTCTransportId,
416    ) -> Result<()> {
417        if self.gathered.remove(&ice_transport) {
418            return Ok(());
419        }
420        let Some(held) = self.pc.dtls_transport_by_id(dtls_transport).and_then(|t| {
421            let ice = t.ice_transport();
422            (ice.gathering_state() == RTCIceGatheringState::Gathering)
423                .then(|| ice.get_local_candidates())
424        }) else {
425            return Ok(());
426        };
427        let kept: Vec<(SocketAddr, String)> = self
428            .sockets
429            .iter()
430            .filter(|s| s.retired_for.is_none())
431            .filter(|s| {
432                held.iter()
433                    .any(|c| c.port == s.local.port() && c.address == s.local.ip().to_string())
434            })
435            .map(|s| (s.local, s.mid.clone()))
436            .collect();
437        if kept.is_empty() {
438            return self.gather();
439        }
440        let mid = kept[0].1.clone();
441        for (local, _) in &kept {
442            self.pc
443                .add_local_candidate(host_candidate(*local, &mid, None)?)?;
444        }
445        self.end_of_candidates(&mid, None)
446    }
447
448    /// Host candidates for every transport section (`ice_transport_sections`) that has no
449    /// socket of its own yet, each ended with the end of its generation.
450    ///
451    /// # Errors
452    ///
453    /// As [`flush`](Self::flush).
454    pub fn gather(&mut self) -> Result<()> {
455        for (mid, index) in self.pc.ice_transport_sections() {
456            if self
457                .sockets
458                .iter()
459                .any(|s| s.retired_for.is_none() && s.mid == mid)
460            {
461                continue;
462            }
463            self.gather_section(&mid, Some(index))?;
464        }
465        Ok(())
466    }
467
468    /// New sockets, one per configured address, for the transport of section `mid`: their
469    /// host candidates, then the end of the generation.
470    fn gather_section(&mut self, mid: &str, index: Option<u16>) -> Result<()> {
471        for ip in self.config.addresses.clone() {
472            let socket = match self.config.udp_port_range {
473                Some(range) => sockets::bind_udp_in_range(ip, range),
474                None => std::net::UdpSocket::bind(SocketAddr::new(ip, 0)),
475            }
476            .and_then(|socket| {
477                socket.set_nonblocking(true)?;
478                UdpSocket::from_std(socket)
479            })
480            .map_err(io_error)?;
481            let local = socket.local_addr().map_err(io_error)?;
482            let socket = Arc::new(socket);
483            let reader = tokio::spawn(read_loop(socket.clone(), local, self.datagrams_tx.clone()));
484            self.sockets.push(HostSocket {
485                socket,
486                local,
487                mid: mid.to_owned(),
488                retired_for: None,
489                close_at: None,
490                reader,
491            });
492            self.pc
493                .add_local_candidate(host_candidate(local, mid, index)?)?;
494        }
495        self.end_of_candidates(mid, index)
496    }
497
498    fn end_of_candidates(&mut self, mid: &str, index: Option<u16>) -> Result<()> {
499        self.pc.add_local_candidate(RTCIceCandidateInit {
500            sdp_mid: Some(mid.to_owned()),
501            sdp_mline_index: index,
502            ..Default::default()
503        })
504    }
505
506    /// Closes the sockets retired for `transport` (it is closed: nothing travels over them).
507    fn release(&mut self, transport: RTCTransportId) {
508        self.sockets.retain(|s| s.retired_for != Some(transport));
509    }
510
511    /// `transport` selected a pair on a new socket: its retired sockets are closed after
512    /// [`PeerDriverConfig::retired_socket_linger`], for what the peer still sends to them.
513    fn release_after_linger(&mut self, transport: RTCTransportId) {
514        let close_at = Instant::now() + self.config.retired_socket_linger;
515        for host in self
516            .sockets
517            .iter_mut()
518            .filter(|s| s.retired_for == Some(transport) && s.close_at.is_none())
519        {
520            host.close_at = Some(close_at);
521        }
522    }
523}
524
525fn io_error(e: io::Error) -> Error {
526    Error::Io(IoError(e))
527}
528
529/// The host candidate of `local` for section `mid`.
530fn host_candidate(local: SocketAddr, mid: &str, index: Option<u16>) -> Result<RTCIceCandidateInit> {
531    let candidate = CandidateHostConfig {
532        base_config: CandidateConfig {
533            network: "udp".to_owned(),
534            address: local.ip().to_string(),
535            port: local.port(),
536            component: 1,
537            ..Default::default()
538        },
539        ..Default::default()
540    }
541    .new_candidate_host()?;
542    let mut init = RTCIceCandidate::from(&candidate).to_json()?;
543    init.sdp_mid = Some(mid.to_owned());
544    init.sdp_mline_index = index;
545    Ok(init)
546}
547
548async fn read_loop(
549    socket: Arc<UdpSocket>,
550    local: SocketAddr,
551    tx: mpsc::UnboundedSender<(SocketAddr, SocketAddr, Vec<u8>)>,
552) {
553    let mut buf = vec![0u8; 2048];
554    loop {
555        match socket.recv_from(&mut buf).await {
556            Ok((n, peer)) => {
557                if tx.send((local, peer, buf[..n].to_vec())).is_err() {
558                    return;
559                }
560            }
561            // An ICMP error reported on the socket (Windows: a port unreachable) is not the
562            // end of it.
563            Err(_) => tokio::task::yield_now().await,
564        }
565    }
566}