Skip to main content

rtci_sdp/attribute/
ice.rs

1//! The ICE attributes of RFC 8839 section 5: `candidate`, `remote-candidates`,
2//! `ice-ufrag`, `ice-pwd`, `ice-options` and `ice-pacing`. (`ice-lite` and
3//! `end-of-candidates` have no value: see `flag()`.)
4
5use std::fmt;
6
7use shared::error::Result;
8
9use super::{TypedAttribute, string_attribute};
10use crate::grammar::{self, invalid, syntax};
11
12/// `component-id = 1*3DIGIT`, "a positive integer between 1 and 256".
13fn component_id(what: &str, value: &str) -> Result<u16> {
14    if value.len() > 3 {
15        return Err(syntax(what, value));
16    }
17    let id: u16 = grammar::digits(what, value)?;
18    if !(1..=256).contains(&id) {
19        return Err(invalid(what, value));
20    }
21    Ok(id)
22}
23
24/// `a=candidate:...` (RFC 8839 section 5.1).
25///
26/// ```text
27/// candidate-attribute = "candidate" ":" foundation SP component-id SP transport SP
28///                       priority SP connection-address SP port SP cand-type
29///                       [SP rel-addr] [SP rel-port] *(SP cand-extension)
30/// foundation          = 1*32ice-char
31/// component-id        = 1*3DIGIT
32/// transport           = "UDP" / transport-extension
33/// priority            = 1*10DIGIT
34/// cand-type           = "typ" SP candidate-types
35/// candidate-types     = "host" / "srflx" / "prflx" / "relay" / token
36/// rel-addr            = "raddr" SP connection-address
37/// rel-port            = "rport" SP port
38/// cand-extension      = extension-att-name SP extension-att-value
39/// ```
40///
41/// The address is an IPv4 address, an IPv6 address or a domain name (an mDNS name ends in
42/// `.local`). What follows the type is read as name and value pairs: `raddr` and `rport`
43/// fill [`Candidate::related_address`] and [`Candidate::related_port`], everything else
44/// (`tcptype`, `generation`, `ufrag`, `network-id`, `network-cost`, ...) is kept in
45/// [`Candidate::extensions`] in the order written.
46#[derive(Debug, Clone, PartialEq, Eq)]
47pub struct Candidate {
48    /// The foundation: 1 to 32 ice-chars.
49    pub foundation: String,
50    /// The component: 1 for RTP (and for everything when RTCP is multiplexed), 2 for RTCP.
51    pub component: u16,
52    /// The transport, as written: `UDP`, `udp`, `TCP`, ... Compare without regard to case.
53    pub transport: String,
54    /// The priority.
55    pub priority: u32,
56    /// The connection address.
57    pub address: String,
58    /// The port.
59    pub port: u16,
60    /// The candidate type: `host`, `srflx`, `prflx`, `relay`, or another token.
61    pub typ: String,
62    /// `raddr`: the related address (the base of a reflexive candidate, the mapped address
63    /// of a relayed one).
64    pub related_address: Option<String>,
65    /// `rport`: the related port.
66    pub related_port: Option<u16>,
67    /// The other extension attributes, as `(name, value)`, in order.
68    pub extensions: Vec<(String, String)>,
69}
70
71impl Candidate {
72    /// The value of the extension attribute `name`.
73    pub fn extension(&self, name: &str) -> Option<&str> {
74        self.extensions
75            .iter()
76            .find(|(n, _)| n == name)
77            .map(|(_, v)| v.as_str())
78    }
79}
80
81impl TypedAttribute for Candidate {
82    const NAME: &'static str = "candidate";
83
84    fn parse(value: &str) -> Result<Self> {
85        let fields = grammar::fields("a=candidate", value)?;
86        let [
87            foundation,
88            component,
89            transport,
90            priority,
91            address,
92            port,
93            typ_keyword,
94            typ,
95            rest @ ..,
96        ] = &fields[..]
97        else {
98            return Err(syntax("a=candidate", value));
99        };
100        if !grammar::is_ice_chars(foundation)
101            || foundation.len() > 32
102            || !grammar::is_token(transport)
103            || !grammar::is_candidate_address(address)
104            || *typ_keyword != "typ"
105            || !grammar::is_token(typ)
106            || priority.len() > 10
107            || !rest.len().is_multiple_of(2)
108        {
109            return Err(syntax("a=candidate", value));
110        }
111
112        let mut candidate = Candidate {
113            foundation: (*foundation).to_owned(),
114            component: component_id("a=candidate component", component)?,
115            transport: (*transport).to_owned(),
116            priority: grammar::digits("a=candidate priority", priority)?,
117            address: (*address).to_owned(),
118            port: grammar::port(port)?,
119            typ: (*typ).to_owned(),
120            related_address: None,
121            related_port: None,
122            extensions: Vec::with_capacity(rest.len() / 2),
123        };
124        for pair in rest.chunks(2) {
125            let (name, extension_value) = (pair[0], pair[1]);
126            match name {
127                "raddr" if candidate.related_address.is_none() => {
128                    if !grammar::is_candidate_address(extension_value) {
129                        return Err(syntax("a=candidate raddr", value));
130                    }
131                    candidate.related_address = Some(extension_value.to_owned());
132                }
133                "rport" if candidate.related_port.is_none() => {
134                    candidate.related_port = Some(grammar::port(extension_value)?);
135                }
136                "raddr" | "rport" => return Err(syntax("a=candidate", value)),
137                _ => {
138                    if !grammar::is_token(name) || !grammar::is_vchars(extension_value) {
139                        return Err(syntax("a=candidate extension", value));
140                    }
141                    candidate
142                        .extensions
143                        .push((name.to_owned(), extension_value.to_owned()));
144                }
145            }
146        }
147        Ok(candidate)
148    }
149}
150
151impl fmt::Display for Candidate {
152    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
153        write!(
154            f,
155            "{} {} {} {} {} {} typ {}",
156            self.foundation,
157            self.component,
158            self.transport,
159            self.priority,
160            self.address,
161            self.port,
162            self.typ
163        )?;
164        if let Some(address) = &self.related_address {
165            write!(f, " raddr {address}")?;
166        }
167        if let Some(port) = self.related_port {
168            write!(f, " rport {port}")?;
169        }
170        for (name, value) in &self.extensions {
171            write!(f, " {name} {value}")?;
172        }
173        Ok(())
174    }
175}
176
177/// One `component-id SP connection-address SP port` of an `a=remote-candidates` line.
178#[derive(Debug, Clone, PartialEq, Eq)]
179pub struct RemoteCandidate {
180    /// The component.
181    pub component: u16,
182    /// The address of the remote candidate.
183    pub address: String,
184    /// Its port.
185    pub port: u16,
186}
187
188/// `a=remote-candidates:<component> <address> <port> ...` (RFC 8839 section 5.2): the remote
189/// candidates the controlling agent uses, one per component.
190#[derive(Debug, Clone, PartialEq, Eq)]
191pub struct RemoteCandidates {
192    /// The remote candidates, in order. Never empty.
193    pub candidates: Vec<RemoteCandidate>,
194}
195
196impl TypedAttribute for RemoteCandidates {
197    const NAME: &'static str = "remote-candidates";
198
199    fn parse(value: &str) -> Result<Self> {
200        let fields = grammar::fields("a=remote-candidates", value)?;
201        if !fields.len().is_multiple_of(3) {
202            return Err(syntax("a=remote-candidates", value));
203        }
204        let mut candidates = Vec::with_capacity(fields.len() / 3);
205        for triple in fields.chunks(3) {
206            if !grammar::is_candidate_address(triple[1]) {
207                return Err(syntax("a=remote-candidates", value));
208            }
209            candidates.push(RemoteCandidate {
210                component: component_id("a=remote-candidates component", triple[0])?,
211                address: triple[1].to_owned(),
212                port: grammar::port(triple[2])?,
213            });
214        }
215        Ok(RemoteCandidates { candidates })
216    }
217}
218
219impl fmt::Display for RemoteCandidates {
220    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
221        for (i, c) in self.candidates.iter().enumerate() {
222            if i > 0 {
223                f.write_str(" ")?;
224            }
225            write!(f, "{} {} {}", c.component, c.address, c.port)?;
226        }
227        Ok(())
228    }
229}
230
231string_attribute!(
232    /// `a=ice-ufrag:<ufrag>` (RFC 8839 section 5.4): `4*256ice-char`.
233    IceUfrag,
234    "ice-ufrag",
235    "a=ice-ufrag",
236    |v| (4..=256).contains(&v.len()) && grammar::is_ice_chars(v)
237);
238
239string_attribute!(
240    /// `a=ice-pwd:<password>` (RFC 8839 section 5.4): `22*256ice-char`.
241    ///
242    /// `Debug` prints the password: do not log this type.
243    IcePwd,
244    "ice-pwd",
245    "a=ice-pwd",
246    |v| (22..=256).contains(&v.len()) && grammar::is_ice_chars(v)
247);
248
249/// `a=ice-options:<tag> *(SP <tag>)` (RFC 8839 section 5.6), each tag `1*ice-char`:
250/// `trickle` (RFC 8840), `ice2` (RFC 8445), `renomination`, ...
251#[derive(Debug, Clone, PartialEq, Eq)]
252pub struct IceOptions {
253    /// The option tags, in order. Never empty.
254    pub tags: Vec<String>,
255}
256
257impl IceOptions {
258    /// Whether the option `tag` is listed.
259    pub fn contains(&self, tag: &str) -> bool {
260        self.tags.iter().any(|t| t == tag)
261    }
262}
263
264impl TypedAttribute for IceOptions {
265    const NAME: &'static str = "ice-options";
266
267    fn parse(value: &str) -> Result<Self> {
268        let tags = grammar::fields("a=ice-options", value)?;
269        if !tags.iter().all(|tag| grammar::is_ice_chars(tag)) {
270            return Err(syntax("a=ice-options", value));
271        }
272        Ok(IceOptions {
273            tags: tags.into_iter().map(str::to_owned).collect(),
274        })
275    }
276}
277
278impl fmt::Display for IceOptions {
279    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
280        f.write_str(&self.tags.join(" "))
281    }
282}
283
284/// `a=ice-pacing:<ms>` (RFC 8839 section 5.5): `1*10DIGIT`, the pacing of connectivity
285/// checks in milliseconds; 50 when the attribute is absent.
286#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
287pub struct IcePacing(pub u64);
288
289impl TypedAttribute for IcePacing {
290    const NAME: &'static str = "ice-pacing";
291
292    fn parse(value: &str) -> Result<Self> {
293        if value.len() > 10 {
294            return Err(syntax("a=ice-pacing", value));
295        }
296        grammar::digits("a=ice-pacing", value).map(IcePacing)
297    }
298}
299
300impl fmt::Display for IcePacing {
301    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
302        write!(f, "{}", self.0)
303    }
304}