Skip to main content

rtci_ice/agent/
restart_undo.rs

1//! An ICE restart that can be taken back: the local offer that asked for it was rolled back
2//! (RFC 9429 section 5.7).
3
4use super::*;
5
6/// What [`Agent::apply_restart`] replaced, kept by [`Agent::apply_restart_revertible`] until
7/// the restart is committed ([`Agent::commit_restart`]) or taken back
8/// ([`Agent::revert_restart`]).
9#[derive(Clone)]
10pub(crate) struct RestartUndo {
11    connection_state: ConnectionState,
12    local_credentials: Credentials,
13    remote_credentials: Option<Credentials>,
14    local_candidates: Vec<Candidate>,
15    remote_candidates: Vec<Candidate>,
16    candidate_pairs: Vec<CandidatePair>,
17    nominated_pair: Option<usize>,
18    selected_pair: Option<usize>,
19    previous_media_path: Option<MediaPath>,
20    previous_generation: Option<PreviousGeneration>,
21    pending_binding_requests: Vec<BindingRequest>,
22    early_requests: Vec<EarlyRequest>,
23    triggered_queue: VecDeque<(usize, usize)>,
24    remote_end_of_candidates: bool,
25    local_gathering_complete: bool,
26    lite_update_raised: bool,
27    next_check_at: Instant,
28    next_consent_at: Option<Instant>,
29    consent_unanswered_since: Option<Instant>,
30    checking_duration: Instant,
31    last_checking_time: Instant,
32}
33
34impl Agent {
35    /// [`Agent::apply_restart`], remembering the session it replaces so that
36    /// [`Agent::revert_restart`] can bring it back: the restart belongs to a local offer that
37    /// may still be rolled back (RFC 9429 section 5.7: "any resources allocated by the
38    /// abandoned local description are discarded"). A second restart before the first is
39    /// committed keeps the session the first one replaced.
40    pub fn apply_restart_revertible(
41        &mut self,
42        now: Instant,
43        keep_local_candidates: bool,
44    ) -> Result<()> {
45        let undo = match self.restart_undo.take() {
46            Some(undo) => undo,
47            None => Box::new(RestartUndo {
48                connection_state: self.connection_state,
49                local_credentials: self.ufrag_pwd.local_credentials.clone(),
50                remote_credentials: self.ufrag_pwd.remote_credentials.clone(),
51                local_candidates: self.local_candidates.clone(),
52                remote_candidates: self.remote_candidates.clone(),
53                candidate_pairs: self.candidate_pairs.clone(),
54                nominated_pair: self.nominated_pair,
55                selected_pair: self.selected_pair,
56                previous_media_path: self.previous_media_path,
57                previous_generation: self.previous_generation.clone(),
58                pending_binding_requests: self.pending_binding_requests.clone(),
59                early_requests: self.early_requests.clone(),
60                triggered_queue: self.triggered_queue.clone(),
61                remote_end_of_candidates: self.remote_end_of_candidates,
62                local_gathering_complete: self.local_gathering_complete,
63                lite_update_raised: self.lite_update_raised,
64                next_check_at: self.next_check_at,
65                next_consent_at: self.next_consent_at,
66                consent_unanswered_since: self.consent_unanswered_since,
67                checking_duration: self.checking_duration,
68                last_checking_time: self.last_checking_time,
69            }),
70        };
71        self.apply_restart(now, keep_local_candidates)?;
72        self.restart_undo = Some(undo);
73        Ok(())
74    }
75
76    /// Whether a restart applied by [`Agent::apply_restart_revertible`] can still be taken
77    /// back.
78    pub fn has_revertible_restart(&self) -> bool {
79        self.restart_undo.is_some()
80    }
81
82    /// Keeps the restart [`Agent::apply_restart_revertible`] applied: the answer to its offer
83    /// arrived. A no-op without one.
84    pub fn commit_restart(&mut self) {
85        self.restart_undo = None;
86    }
87
88    /// Takes back the restart [`Agent::apply_restart_revertible`] applied: the local offer was
89    /// rolled back, so the agent goes on with the session it had (RFC 9429 section 5.7),
90    /// its credentials, candidates, pairs and selected pair, and what the new generation
91    /// gathered or learned is dropped. Consent on the selected pair carries over what the
92    /// previous-generation checks of the meantime established (RFC 7675). Returns whether there
93    /// was a restart to take back; a closed agent stays closed.
94    pub fn revert_restart(&mut self, now: Instant) -> bool {
95        let Some(undo) = self.restart_undo.take() else {
96            return false;
97        };
98        if self.connection_state == ConnectionState::Closed {
99            return false;
100        }
101        let undo = *undo;
102        // The consent the old path kept in the meantime.
103        let kept_consent = self
104            .previous_generation
105            .as_ref()
106            .map(|previous| (previous.last_consent, previous.next_consent_at));
107
108        self.announce_all_pairs_removed();
109        self.ufrag_pwd.local_credentials = undo.local_credentials;
110        self.ufrag_pwd.remote_credentials = undo.remote_credentials;
111        self.ufrag_pwd.pending_local_credentials = None;
112        self.local_candidates = undo.local_candidates;
113        // The snapshot was taken while the restart was staged: what was gathered for it
114        // belongs to no generation now.
115        for c in &mut self.local_candidates {
116            c.restart_generation = false;
117        }
118        self.remote_candidates = undo.remote_candidates;
119        self.candidate_pairs = undo.candidate_pairs;
120        self.nominated_pair = undo.nominated_pair;
121        self.selected_pair = undo.selected_pair;
122        self.previous_media_path = undo.previous_media_path;
123        self.previous_generation = undo.previous_generation;
124        self.pending_binding_requests = undo.pending_binding_requests;
125        self.early_requests = undo.early_requests;
126        self.triggered_queue = undo.triggered_queue;
127        self.remote_end_of_candidates = undo.remote_end_of_candidates;
128        self.local_gathering_complete = undo.local_gathering_complete;
129        self.lite_update_raised = undo.lite_update_raised;
130        self.next_check_at = undo.next_check_at.max(now);
131        self.next_consent_at = undo.next_consent_at;
132        self.consent_unanswered_since = undo.consent_unanswered_since;
133        self.checking_duration = undo.checking_duration;
134        self.last_checking_time = undo.last_checking_time;
135
136        if let (Some(pair_index), Some((last_consent, next_consent_at))) =
137            (self.selected_pair, kept_consent)
138        {
139            let remote_index = self.candidate_pairs[pair_index].remote_index;
140            let remote = &mut self.remote_candidates[remote_index];
141            if self.lite {
142                if remote.last_authenticated.is_none_or(|t| t < last_consent) {
143                    remote.last_authenticated = Some(last_consent);
144                }
145            } else if remote.last_consent.is_none_or(|t| t < last_consent) {
146                remote.last_consent = Some(last_consent);
147            }
148            self.next_consent_at = Some(next_consent_at);
149        }
150
151        for index in 0..self.candidate_pairs.len() {
152            self.announce_pair(index, true);
153        }
154        if let Some(pair_index) = self.selected_pair {
155            let pair = self.candidate_pairs[pair_index];
156            self.event_outs.push_back(TaggedEvent {
157                now,
158                event: Event::SelectedCandidatePairChange(
159                    Box::new(self.local_candidates[pair.local_index].clone()),
160                    Box::new(self.remote_candidates[pair.remote_index].clone()),
161                ),
162            });
163        }
164        self.update_connection_state(Some(now), undo.connection_state);
165        true
166    }
167}