rtci 0.5.0

A sans-I/O WebRTC implementation: peer connections with ICE, DTLS-SRTP, SCTP data channels, RTP/RTCP and JSEP negotiation
Documentation
//! webrtc-extensions 7: the candidate pairs removed when the engine frees an unused candidate
//! once ICE completed (RFC 8445 section 8.3; the extension's "free"): "Let cancelable be true
//! if the candidate pair is being removed in order to free an unused candidate", and "If
//! accepted is false, instruct the ICE agent to not remove the candidate pair indicated by
//! candidatePair, and instead continue to send and respond to ICE connectivity checks on the
//! candidate pair as before."
//!
//! The engine frees two kinds of resource after completion: the TURN link of a relayed
//! candidate the selected pair does not use (`close_settled_turn_links`), and the ICE-TCP
//! connections that carry no selected pair (`close_unused_tcp_connections`). Before it does,
//! the pairs the resource carries leave the agent's list:
//!
//! - by default, at once, each announced with `OnIceCandidatePairRemove` (an event no listener
//!   cancels is accepted);
//! - with `SettingEngineBuilder::with_candidate_pair_proposals(true)`, one at a time as a
//!   cancelable `OnIceCandidatePairRemoveProposal`, answered by
//!   [`RTCPeerConnection::resolve_candidate_pair_removal`]: accepted, the pair leaves the list
//!   and, once none of its pairs is left, the resource is freed; cancelled, the pair and the
//!   resource stay until the next ICE restart.

use super::RTCPeerConnection;
use super::event::{RTCPeerConnectionEvent, RTCTransportEventKind};
use super::handler::transport_set::TransportId;
use ice::candidate::Candidate;

/// A pair whose removal was proposed, or cancelled: by transport, the local ufrag of its ICE
/// generation, and the two candidates.
#[derive(Clone)]
pub(crate) struct ProposedRemoval {
    transport: TransportId,
    ufrag: String,
    local: Candidate,
    remote: Candidate,
}

/// The removal proposals of the connection.
#[derive(Default)]
pub(crate) struct PairRemovals {
    /// The proposal the application has not answered (`[[ProposalPending]]`).
    pub(crate) pending: Option<ProposedRemoval>,
    /// Removals the application cancelled.
    kept: Vec<ProposedRemoval>,
}

impl RTCPeerConnection {
    /// Removes, before a resource of transport `transport` is freed, the listed pairs it
    /// carries (`carries`), the selected one excepted; returns whether the resource may be
    /// freed now (no such pair is left).
    pub(crate) fn remove_freed_pairs(
        &mut self,
        transport: TransportId,
        carries: impl Fn(&Candidate, &Candidate) -> bool,
    ) -> bool {
        let now = self.pipeline_context.now;
        let agent = &self.ice_transport_of(transport).agent;
        let ufrag = agent.get_local_credentials().ufrag.clone();
        let selected = agent.get_selected_candidate_pair();
        let pairs: Vec<(Candidate, Candidate)> = agent
            .get_candidate_pairs()
            .into_iter()
            .filter(|(local, remote)| carries(local, remote))
            .filter(|(local, remote)| {
                !selected
                    .as_ref()
                    .is_some_and(|(l, r)| l.equal(local) && r.equal(remote))
            })
            .collect();
        if pairs.is_empty() {
            return true;
        }
        if !self.setting_engine.candidates.candidate_pair_proposals {
            self.with_transport(transport, |pc| {
                for (local, remote) in &pairs {
                    let _ = pc
                        .ice_transport_mut()
                        .agent
                        .remove_candidate_pair(now, local, remote);
                }
            });
            return true;
        }
        // Cancelled removals of an earlier ICE generation no longer bind.
        let live: Vec<(TransportId, String)> = self
            .pipeline_context
            .transports
            .ids()
            .into_iter()
            .map(|id| {
                (
                    id,
                    self.ice_transport_of(id)
                        .agent
                        .get_local_credentials()
                        .ufrag
                        .clone(),
                )
            })
            .collect();
        self.pair_removals.kept.retain(|k| {
            live.iter()
                .any(|(id, u)| *id == k.transport && *u == k.ufrag)
        });
        let is = |k: &ProposedRemoval, local: &Candidate, remote: &Candidate| {
            k.transport == transport && k.local.equal(local) && k.remote.equal(remote)
        };
        if pairs
            .iter()
            .any(|(l, r)| self.pair_removals.kept.iter().any(|k| is(k, l, r)))
        {
            return false;
        }
        if self.pair_removals.pending.is_some()
            || self.ice_transport_of(transport).agent.proposal_pending()
        {
            return false;
        }
        let (local, remote) = pairs[0].clone();
        let pair = self
            .ice_transport_of(transport)
            .exposed_pair(&local, &remote);
        self.pair_removals.pending = Some(ProposedRemoval {
            transport,
            ufrag,
            local,
            remote,
        });
        self.with_transport(transport, |pc| {
            pc.fire_transport_event(
                RTCPeerConnectionEvent::OnIceCandidatePairRemoveProposal(pair.clone()),
                RTCTransportEventKind::CandidatePairRemoveProposal(pair),
            );
        });
        false
    }

    /// webrtc-extensions 7: answers the `OnIceCandidatePairRemoveProposal` (with
    /// `SettingEngineBuilder::with_candidate_pair_proposals(true)`): `accept` removes the pair
    /// from the agent's list (no further `OnIceCandidatePairRemove`), and the resource it was
    /// on is freed once none of its pairs is left; `false` is a cancelled event: the pair
    /// stays and its checks go on, and the resource is kept until the next ICE restart.
    /// `[[ProposalPending]]` ends either way. A no-op without a pending proposal.
    pub fn resolve_candidate_pair_removal(&mut self, now: std::time::Instant, accept: bool) {
        let Some(proposal) = self.pair_removals.pending.take() else {
            return;
        };
        if self.is_closed() {
            return;
        }
        if accept {
            self.with_transport(proposal.transport, |pc| {
                let _ = pc.ice_transport_mut().agent.remove_proposed_candidate_pair(
                    now,
                    &proposal.local,
                    &proposal.remote,
                );
            });
        } else {
            self.pair_removals.kept.push(proposal);
        }
    }

    /// Whether a removal proposal waits for [`Self::resolve_candidate_pair_removal`].
    pub(crate) fn removal_proposal_pending(&self) -> bool {
        self.pair_removals.pending.is_some()
    }
}