Skip to main content

rtci_stun/
agent.rs

1//! STUN transaction tracking.
2//!
3//! [`Agent`](crate::agent::Agent) is the low-level bookkeeping: it matches a message to a
4//! transaction by id alone and applies none of the checks of RFC 8489 section 6.3 (class,
5//! method, source address, FINGERPRINT, unknown attributes). [`Client`](crate::client::Client)
6//! applies them, and is what talks to a server.
7//!
8//! The agent remembers which requests are outstanding and when each should be considered lost. It
9//! performs no I/O: the caller submits [`ClientAgent`](crate::agent::ClientAgent) commands — start a transaction, hand over
10//! an inbound message, advance time, stop or close — and polls for the resulting [`Event`](crate::agent::Event)s.
11//!
12//! This split is what lets the retransmission schedule be tested without a network, and lets ICE
13//! reuse the same transaction bookkeeping for its connectivity checks.
14#[cfg(test)]
15mod agent_test;
16
17use shared::error::*;
18use std::collections::{HashMap, VecDeque};
19use std::time::Instant;
20
21use crate::message::*;
22
23/// Agent is low-level abstraction over transaction list that
24/// handles concurrency and time outs (via Collect call).
25#[derive(Default)]
26pub struct Agent {
27    /// transactions is map of transactions that are currently
28    /// in progress. Event handling is done in such way when
29    /// transaction is unregistered before AgentTransaction access,
30    /// minimizing mux lock and protecting AgentTransaction from
31    /// data races via unexpected concurrent access.
32    transactions: HashMap<TransactionId, AgentTransaction>,
33    /// all calls are invalid if true
34    closed: bool,
35    /// events queue
36    events_queue: VecDeque<Event>,
37}
38
39/// Event is passed to Handler describing the transaction event.
40/// Do not reuse outside Handler.
41#[derive(Debug)] //Clone
42pub struct Event {
43    /// The transaction this event belongs to.
44    pub id: TransactionId,
45    /// What happened.
46    pub evt: StunEvent,
47}
48
49#[derive(Debug)] //Clone
50/// What became of a STUN transaction.
51#[non_exhaustive]
52pub enum StunEvent {
53    /// The agent was closed, abandoning this transaction.
54    AgentClosed,
55    /// The transaction was stopped by the caller.
56    TransactionStopped,
57    /// The transaction timed out with no response.
58    TransactionTimeOut,
59    /// A response arrived for this transaction.
60    Message(Message),
61    /// The transaction ended without a usable response, for a reason other than time.
62    TransactionFailed {
63        /// The transaction.
64        id: TransactionId,
65        /// Why it failed.
66        reason: TransactionFailure,
67    },
68}
69
70/// Why a transaction failed although the server answered.
71#[derive(Debug, Clone, PartialEq, Eq)]
72#[non_exhaustive]
73pub enum TransactionFailure {
74    /// The response carried comprehension-required attributes the client does not know (RFC
75    /// 8489 sections 6.3.3 and 6.3.4): it is discarded and the transaction has failed.
76    UnknownAttributes(Vec<crate::attributes::AttrType>),
77    /// An error response without a usable ERROR-CODE (RFC 8489 section 6.3.4).
78    MissingErrorCode,
79    /// Every response that arrived failed the integrity check, or, over a reliable transport,
80    /// one did (RFC 8489 sections 9.1.4 and 9.2.5).
81    IntegrityViolation,
82}
83
84/// AgentTransaction represents transaction in progress.
85/// Concurrent access is invalid.
86pub(crate) struct AgentTransaction {
87    id: TransactionId,
88    deadline: Instant,
89}
90
91/// AGENT_COLLECT_CAP is initial capacity for Agent.Collect slices,
92/// sufficient to make function zero-alloc in most cases.
93const AGENT_COLLECT_CAP: usize = 100;
94
95/// ClientAgent is Agent implementation that is used by Client to
96/// process transactions.
97#[derive(Debug)]
98#[non_exhaustive]
99pub enum ClientAgent {
100    /// Hand an inbound message to the agent for matching against a transaction.
101    Process(Message),
102    /// Advance time so the agent can expire transactions.
103    Collect(Instant),
104    /// Register a new transaction with its deadline.
105    Start(TransactionId, Instant),
106    /// Abandon a transaction without waiting for its deadline.
107    Stop(TransactionId),
108    /// Close the agent, abandoning every outstanding transaction.
109    Close,
110}
111
112impl Agent {
113    /// new initializes and returns new Agent with provided handler.
114    pub fn new() -> Self {
115        Agent {
116            transactions: HashMap::new(),
117            closed: false,
118            events_queue: VecDeque::new(),
119        }
120    }
121
122    /// Applies an agent command: start, stop, process a message, collect timeouts, or close.
123    ///
124    /// # Errors
125    ///
126    /// Fails if the agent is closed, or a transaction id is already in use.
127    pub fn handle_event(&mut self, client_agent: ClientAgent) -> Result<()> {
128        match client_agent {
129            ClientAgent::Process(message) => self.process(message),
130            ClientAgent::Collect(deadline) => self.collect(deadline),
131            ClientAgent::Start(tid, deadline) => self.start(tid, deadline),
132            ClientAgent::Stop(tid) => self.stop(tid),
133            ClientAgent::Close => self.close(),
134        }
135    }
136
137    /// When the agent next needs [`ClientAgent::Collect`], or `None` with nothing outstanding.
138    pub fn poll_timeout(&mut self) -> Option<Instant> {
139        let mut deadline = None;
140        for transaction in self.transactions.values() {
141            if deadline.is_none() || transaction.deadline < *deadline.as_ref().unwrap() {
142                deadline = Some(transaction.deadline);
143            }
144        }
145        deadline
146    }
147
148    /// The next transaction event, or `None` when there is nothing to report.
149    pub fn poll_event(&mut self) -> Option<Event> {
150        self.events_queue.pop_front()
151    }
152
153    /// process incoming message, synchronously passing it to handler.
154    fn process(&mut self, message: Message) -> Result<()> {
155        if self.closed {
156            return Err(Error::ErrAgentClosed);
157        }
158
159        self.transactions.remove(&message.transaction_id);
160
161        self.events_queue.push_back(Event {
162            id: message.transaction_id,
163            evt: StunEvent::Message(message),
164        });
165
166        Ok(())
167    }
168
169    /// close terminates all transactions with ErrAgentClosed and renders Agent to
170    /// closed state.
171    fn close(&mut self) -> Result<()> {
172        if self.closed {
173            return Err(Error::ErrAgentClosed);
174        }
175
176        for id in self.transactions.keys() {
177            self.events_queue.push_back(Event {
178                id: *id,
179                evt: StunEvent::AgentClosed,
180            });
181        }
182        self.transactions.clear();
183        self.closed = true;
184
185        Ok(())
186    }
187
188    /// start registers transaction with provided id and deadline.
189    /// Could return ErrAgentClosed, ErrTransactionExists.
190    ///
191    /// Agent handler is guaranteed to be eventually called.
192    fn start(&mut self, id: TransactionId, deadline: Instant) -> Result<()> {
193        if self.closed {
194            return Err(Error::ErrAgentClosed);
195        }
196        if self.transactions.contains_key(&id) {
197            return Err(Error::ErrTransactionExists);
198        }
199
200        self.transactions
201            .insert(id, AgentTransaction { id, deadline });
202
203        Ok(())
204    }
205
206    /// stop stops transaction by id with ErrTransactionStopped, blocking
207    /// until handler returns.
208    fn stop(&mut self, id: TransactionId) -> Result<()> {
209        if self.closed {
210            return Err(Error::ErrAgentClosed);
211        }
212
213        let v = self.transactions.remove(&id);
214        if let Some(t) = v {
215            self.events_queue.push_back(Event {
216                id: t.id,
217                evt: StunEvent::TransactionStopped,
218            });
219            Ok(())
220        } else {
221            Err(Error::ErrTransactionNotExists)
222        }
223    }
224
225    /// collect terminates all transactions that have deadline before provided
226    /// time, blocking until all handlers will process ErrTransactionTimeOut.
227    /// Will return ErrAgentClosed if agent is already closed.
228    ///
229    /// It is safe to call Collect concurrently but makes no sense.
230    fn collect(&mut self, deadline: Instant) -> Result<()> {
231        if self.closed {
232            // Doing nothing if agent is closed.
233            // All transactions should be already closed
234            // during Close() call.
235            return Err(Error::ErrAgentClosed);
236        }
237
238        let mut to_remove: Vec<TransactionId> = Vec::with_capacity(AGENT_COLLECT_CAP);
239
240        // Adding all transactions with deadline before gc_time
241        // to toCall and to_remove slices.
242        // No allocs if there are less than AGENT_COLLECT_CAP
243        // timed out transactions.
244        for (id, t) in &self.transactions {
245            if t.deadline < deadline {
246                to_remove.push(*id);
247            }
248        }
249        // Un-registering timed out transactions.
250        for id in &to_remove {
251            self.transactions.remove(id);
252        }
253
254        for id in to_remove {
255            self.events_queue.push_back(Event {
256                id,
257                evt: StunEvent::TransactionTimeOut,
258            });
259        }
260
261        Ok(())
262    }
263}