1use std::fmt;
6
7use shared::error::Result;
8
9use super::{TypedAttribute, string_attribute};
10use crate::grammar::{self, invalid, syntax};
11
12fn 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#[derive(Debug, Clone, PartialEq, Eq)]
47pub struct Candidate {
48 pub foundation: String,
50 pub component: u16,
52 pub transport: String,
54 pub priority: u32,
56 pub address: String,
58 pub port: u16,
60 pub typ: String,
62 pub related_address: Option<String>,
65 pub related_port: Option<u16>,
67 pub extensions: Vec<(String, String)>,
69}
70
71impl Candidate {
72 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#[derive(Debug, Clone, PartialEq, Eq)]
179pub struct RemoteCandidate {
180 pub component: u16,
182 pub address: String,
184 pub port: u16,
186}
187
188#[derive(Debug, Clone, PartialEq, Eq)]
191pub struct RemoteCandidates {
192 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 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 IcePwd,
244 "ice-pwd",
245 "a=ice-pwd",
246 |v| (22..=256).contains(&v.len()) && grammar::is_ice_chars(v)
247);
248
249#[derive(Debug, Clone, PartialEq, Eq)]
252pub struct IceOptions {
253 pub tags: Vec<String>,
255}
256
257impl IceOptions {
258 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#[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}