rtci_sdp/attribute/mod.rs
1//! Typed, validated access to the attributes the WebRTC specifications use.
2//!
3//! [`SessionDescription::unmarshal`] keeps every `a=`
4//! line as a name and a value: RFC 8866 section 5.13 has an attribute that is not understood
5//! ignored, and the parser cannot know which ones its caller understands. This module is
6//! where a value gets its grammar. Each type parses the value of one attribute against the
7//! ABNF of the RFC that defines it and prints it back in the form that RFC gives.
8//!
9//! There are three ways in:
10//!
11//! * The accessors on [`SessionDescription`] and
12//! [`MediaDescription`]: `mid()`, `rtpmaps()`, `candidates()`,
13//! `fingerprints()`, `simulcast()` and so on. Each returns `Err` when the attribute is
14//! present and malformed, so a caller can tell "absent" from "broken".
15//! * The generic `typed::<T>()` / `typed_all::<T>()` for any [`TypedAttribute`](crate::attribute::TypedAttribute).
16//! * [`SessionDescription::validate`], which checks every
17//! known attribute of a description at once, together with the level each may appear at.
18//!
19//! | Attribute | Type | Defined in |
20//! |---|---|---|
21//! | `group` | [`Group`](crate::attribute::Group) | RFC 5888, RFC 9143 |
22//! | `mid` | [`Mid`](crate::attribute::Mid) | RFC 5888 |
23//! | `msid`, `msid-semantic` | [`Msid`](crate::attribute::Msid), [`MsidSemantic`](crate::attribute::MsidSemantic) | RFC 8830 |
24//! | `ssrc`, `ssrc-group` | [`Ssrc`](crate::attribute::Ssrc), [`SsrcGroup`](crate::attribute::SsrcGroup) | RFC 5576 |
25//! | `rid` | [`Rid`](crate::attribute::Rid) | RFC 8851 |
26//! | `simulcast` | [`Simulcast`](crate::attribute::Simulcast) | RFC 8853 |
27//! | `extmap` | [`ExtMap`](crate::extmap::ExtMap) | RFC 8285 |
28//! | `rtcp`, `rtcp-fb`, `rtcp-xr` | [`Rtcp`](crate::attribute::Rtcp), [`RtcpFb`](crate::attribute::RtcpFb), [`RtcpXr`](crate::attribute::RtcpXr) | RFC 3605, RFC 4585 / 5104, RFC 3611 |
29//! | `rtpmap`, `fmtp` | [`RtpMap`](crate::attribute::RtpMap), [`Fmtp`](crate::attribute::Fmtp) | RFC 8866 |
30//! | `ptime`, `maxptime`, `framerate` | [`Ptime`](crate::attribute::Ptime), [`MaxPtime`](crate::attribute::MaxPtime), [`FrameRate`](crate::attribute::FrameRate) | RFC 8866 |
31//! | `imageattr` | [`ImageAttr`](crate::attribute::ImageAttr) | RFC 6236 |
32//! | `content` | [`Content`](crate::attribute::Content) | RFC 4796 |
33//! | `candidate`, `remote-candidates` | [`Candidate`](crate::attribute::Candidate), [`RemoteCandidates`](crate::attribute::RemoteCandidates) | RFC 8839 |
34//! | `ice-ufrag`, `ice-pwd`, `ice-options`, `ice-pacing` | [`IceUfrag`](crate::attribute::IceUfrag), [`IcePwd`](crate::attribute::IcePwd), [`IceOptions`](crate::attribute::IceOptions), [`IcePacing`](crate::attribute::IcePacing) | RFC 8839 |
35//! | `fingerprint` | [`Fingerprint`](crate::attribute::Fingerprint) | RFC 8122 |
36//! | `setup` | [`Setup`](crate::attribute::Setup) | RFC 4145, RFC 8842 |
37//! | `tls-id` | [`TlsId`](crate::attribute::TlsId) | RFC 8842 |
38//! | `identity` | [`Identity`](crate::attribute::Identity) | RFC 8827 |
39//! | `tool`, `type`, `orient`, `quality` | [`Tool`](crate::attribute::Tool), [`ConferenceType`](crate::attribute::ConferenceType), [`Orient`](crate::attribute::Orient), [`Quality`](crate::attribute::Quality) | RFC 8866 |
40//! | `sctp-port`, `max-message-size`, `sctpmap` | [`SctpPort`](crate::attribute::SctpPort), [`MaxMessageSize`](crate::attribute::MaxMessageSize), [`SctpMap`](crate::attribute::SctpMap) | RFC 8841 |
41//!
42//! Attributes without a value (`rtcp-mux`, `rtcp-mux-only`, `rtcp-rsize`, `ice-lite`,
43//! `end-of-candidates`, `bundle-only`, `extmap-allow-mixed`, `cryptex` and the four
44//! directions) are read with `flag()` or their named accessor, which refuses one that
45//! carries a value.
46//!
47//! [`mux`](crate::attribute::mux) holds the RFC 8859 multiplexing category of every attribute.
48
49use std::fmt;
50
51use shared::error::{Error, Result};
52
53use crate::description::common::Attribute;
54
55mod grouping;
56mod ice;
57mod informational;
58pub mod mux;
59mod rtcp;
60mod rtp;
61mod sctp;
62mod security;
63mod simulcast;
64mod source;
65mod validate;
66
67#[cfg(test)]
68mod attribute_test;
69
70pub use grouping::{Depend, Dependency, DependencyType, Group, Mid, Msid, MsidSemantic};
71pub use ice::{
72 Candidate, IceOptions, IcePacing, IcePwd, IceUfrag, RemoteCandidate, RemoteCandidates,
73};
74pub use informational::{ConferenceType, Orient, Quality, Tool};
75pub use rtcp::{
76 Rtcp, RtcpAddress, RtcpFb, RtcpFbKind, RtcpFbPayloadType, RtcpXr, RtcpXrFormat, RtcpXrRttMode,
77 RtcpXrStatFlag,
78};
79pub use rtp::{
80 Content, Fmtp, FrameRate, ImageAttr, ImageAttrList, ImageAttrRange, ImageAttrSet, MaxPtime,
81 Ptime, RtpMap,
82};
83pub use sctp::{MaxMessageSize, SctpMap, SctpPort};
84pub use security::{Fingerprint, Identity, Setup, TlsId};
85pub use simulcast::{Rid, RidDirection, Simulcast, SimulcastId};
86pub use source::{Ssrc, SsrcGroup};
87pub use validate::check_attribute;
88
89/// An attribute with a value whose grammar this crate knows.
90///
91/// `parse` takes the text after `a=<name>:` and checks all of it; `Display` writes that text
92/// back in the form the defining RFC gives.
93pub trait TypedAttribute: Sized + fmt::Display {
94 /// The attribute name, as it follows `a=`.
95 const NAME: &'static str;
96
97 /// Parses the value: everything after `a=<name>:`.
98 fn parse(value: &str) -> Result<Self>;
99
100 /// The `a=` line this value makes.
101 fn to_attribute(&self) -> Attribute {
102 Attribute::new(Self::NAME.to_owned(), Some(self.to_string()))
103 }
104}
105
106fn no_value(name: &str) -> Error {
107 Error::SdpInvalidSyntax(format!("`a={name}` has no value"))
108}
109
110/// The first `a=<T::NAME>` line of `attributes`, parsed; `Ok(None)` when there is none.
111pub(crate) fn first<T: TypedAttribute>(attributes: &[Attribute]) -> Result<Option<T>> {
112 attributes
113 .iter()
114 .map(Attribute::parts)
115 .find(|(name, _)| *name == T::NAME)
116 .map(|(_, value)| T::parse(value.ok_or_else(|| no_value(T::NAME))?))
117 .transpose()
118}
119
120/// Every `a=<T::NAME>` line of `attributes`, parsed, in order. The first malformed one is
121/// the error.
122pub(crate) fn all<T: TypedAttribute>(attributes: &[Attribute]) -> Result<Vec<T>> {
123 attributes
124 .iter()
125 .map(Attribute::parts)
126 .filter(|(name, _)| *name == T::NAME)
127 .map(|(_, value)| T::parse(value.ok_or_else(|| no_value(T::NAME))?))
128 .collect()
129}
130
131/// Whether the property attribute `name` is present. One that carries a value is malformed.
132pub(crate) fn flag(attributes: &[Attribute], name: &str) -> Result<bool> {
133 match attributes
134 .iter()
135 .map(Attribute::parts)
136 .find(|(n, _)| *n == name)
137 {
138 None => Ok(false),
139 Some((_, None)) => Ok(true),
140 Some(_) => Err(Error::SdpInvalidSyntax(format!(
141 "`a={name}` takes no value"
142 ))),
143 }
144}
145
146/// A value attribute whose whole value is one checked string.
147macro_rules! string_attribute {
148 ($(#[$doc:meta])* $name:ident, $key:literal, $what:literal, |$v:ident| $check:expr) => {
149 $(#[$doc])*
150 #[derive(Debug, Clone, PartialEq, Eq, Hash)]
151 pub struct $name(String);
152
153 impl $name {
154 /// Checks `value` against the grammar and wraps it.
155 pub fn new(value: impl Into<String>) -> shared::error::Result<Self> {
156 let value = value.into();
157 <Self as $crate::attribute::TypedAttribute>::parse(&value)
158 }
159
160 /// The value.
161 pub fn as_str(&self) -> &str {
162 &self.0
163 }
164 }
165
166 impl $crate::attribute::TypedAttribute for $name {
167 const NAME: &'static str = $key;
168
169 fn parse(value: &str) -> shared::error::Result<Self> {
170 let $v = value;
171 if $check {
172 Ok($name(value.to_owned()))
173 } else {
174 Err($crate::grammar::syntax($what, value))
175 }
176 }
177 }
178
179 impl std::fmt::Display for $name {
180 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
181 f.write_str(&self.0)
182 }
183 }
184 };
185}
186pub(crate) use string_attribute;
187
188/// The typed accessors both description levels share.
189macro_rules! common_accessors {
190 () => {
191 /// The first `a=<T::NAME>` attribute at this level, parsed. `Ok(None)` when there is
192 /// none, `Err` when it is malformed.
193 pub fn typed<T: $crate::attribute::TypedAttribute>(
194 &self,
195 ) -> shared::error::Result<Option<T>> {
196 $crate::attribute::first(&self.attributes)
197 }
198
199 /// Every `a=<T::NAME>` attribute at this level, parsed, in order.
200 pub fn typed_all<T: $crate::attribute::TypedAttribute>(
201 &self,
202 ) -> shared::error::Result<Vec<T>> {
203 $crate::attribute::all(&self.attributes)
204 }
205
206 /// Whether the property attribute `name` (one without a value, such as
207 /// `rtcp-mux`) is present at this level. `Err` when it carries a value.
208 pub fn flag(&self, name: &str) -> shared::error::Result<bool> {
209 $crate::attribute::flag(&self.attributes, name)
210 }
211
212 /// Appends the `a=` line of a typed attribute.
213 pub fn with_typed<T: $crate::attribute::TypedAttribute>(mut self, value: &T) -> Self {
214 self.attributes.push(value.to_attribute());
215 self
216 }
217
218 /// The direction attribute at this level (`sendrecv`, `sendonly`, `recvonly`,
219 /// `inactive`). `Ok(None)` when there is none; `Err` when there are several
220 /// (RFC 8866 section 6.7: at most one per level) or when one carries a value.
221 pub fn direction(&self) -> shared::error::Result<Option<$crate::direction::Direction>> {
222 let mut found = None;
223 for attribute in &self.attributes {
224 let (name, value) = attribute.parts();
225 let direction = $crate::direction::Direction::new(name);
226 if direction == $crate::direction::Direction::Unspecified {
227 continue;
228 }
229 if value.is_some() || found.is_some() {
230 return Err(shared::error::Error::SdpInvalidSyntax(format!(
231 "direction attribute `{name}`"
232 )));
233 }
234 found = Some(direction);
235 }
236 Ok(found)
237 }
238
239 /// `a=extmap` lines at this level (RFC 8285).
240 pub fn extmaps(&self) -> shared::error::Result<Vec<$crate::extmap::ExtMap>> {
241 self.typed_all()
242 }
243
244 /// Whether `a=extmap-allow-mixed` is present at this level (RFC 8285 section 6).
245 pub fn extmap_allow_mixed(&self) -> shared::error::Result<bool> {
246 self.flag($crate::description::session::ATTR_KEY_EXTMAP_ALLOW_MIXED)
247 }
248
249 /// `a=ice-ufrag` at this level (RFC 8839 section 5.4).
250 pub fn ice_ufrag(&self) -> shared::error::Result<Option<$crate::attribute::IceUfrag>> {
251 self.typed()
252 }
253
254 /// `a=ice-pwd` at this level (RFC 8839 section 5.4).
255 pub fn ice_pwd(&self) -> shared::error::Result<Option<$crate::attribute::IcePwd>> {
256 self.typed()
257 }
258
259 /// `a=ice-options` at this level (RFC 8839 section 5.6).
260 pub fn ice_options(&self) -> shared::error::Result<Option<$crate::attribute::IceOptions>> {
261 self.typed()
262 }
263
264 /// `a=fingerprint` lines at this level (RFC 8122 section 5).
265 pub fn fingerprints(&self) -> shared::error::Result<Vec<$crate::attribute::Fingerprint>> {
266 self.typed_all()
267 }
268
269 /// `a=setup` at this level (RFC 4145 section 4, RFC 8842).
270 pub fn setup(&self) -> shared::error::Result<Option<$crate::attribute::Setup>> {
271 self.typed()
272 }
273
274 /// `a=tls-id` at this level (RFC 8842 section 4).
275 pub fn tls_id(&self) -> shared::error::Result<Option<$crate::attribute::TlsId>> {
276 self.typed()
277 }
278
279 /// `a=rtcp-xr` at this level (RFC 3611 section 5.1).
280 pub fn rtcp_xr(&self) -> shared::error::Result<Option<$crate::attribute::RtcpXr>> {
281 self.typed()
282 }
283
284 /// Whether `a=cryptex` is present at this level (RFC 9335 section 4).
285 pub fn cryptex(&self) -> shared::error::Result<bool> {
286 self.flag($crate::description::session::ATTR_KEY_CRYPTEX)
287 }
288 };
289}
290pub(crate) use common_accessors;
291
292/// The typed accessors of the session level.
293macro_rules! session_accessors {
294 () => {
295 /// `a=group` lines (RFC 5888 section 5), every semantics.
296 pub fn groups(&self) -> shared::error::Result<Vec<$crate::attribute::Group>> {
297 self.typed_all()
298 }
299
300 /// The `a=group:BUNDLE` lines (RFC 9143 section 5).
301 pub fn bundle_groups(&self) -> shared::error::Result<Vec<$crate::attribute::Group>> {
302 Ok(self
303 .groups()?
304 .into_iter()
305 .filter(|g| g.is_bundle())
306 .collect())
307 }
308
309 /// Whether `a=ice-lite` is present (RFC 8839 section 5.3).
310 pub fn ice_lite(&self) -> shared::error::Result<bool> {
311 self.flag($crate::description::session::ATTR_KEY_ICELITE)
312 }
313
314 /// `a=ice-pacing` (RFC 8839 section 5.5).
315 pub fn ice_pacing(&self) -> shared::error::Result<Option<$crate::attribute::IcePacing>> {
316 self.typed()
317 }
318
319 /// `a=identity` (RFC 8827 section 5). Only the first one counts.
320 pub fn identity(&self) -> shared::error::Result<Option<$crate::attribute::Identity>> {
321 self.typed()
322 }
323
324 /// `a=tool` (RFC 8866 section 6.3).
325 pub fn tool(&self) -> shared::error::Result<Option<$crate::attribute::Tool>> {
326 self.typed()
327 }
328
329 /// `a=type`, the conference type (RFC 8866 section 6.9).
330 pub fn conference_type(
331 &self,
332 ) -> shared::error::Result<Option<$crate::attribute::ConferenceType>> {
333 self.typed()
334 }
335
336 /// `a=msid-semantic` (draft-ietf-mmusic-msid; browsers still write it).
337 pub fn msid_semantic(
338 &self,
339 ) -> shared::error::Result<Option<$crate::attribute::MsidSemantic>> {
340 self.typed()
341 }
342 };
343}
344pub(crate) use session_accessors;
345
346/// The typed accessors of a media description.
347macro_rules! media_accessors {
348 () => {
349 /// `a=mid` (RFC 5888 section 4).
350 pub fn mid(&self) -> shared::error::Result<Option<$crate::attribute::Mid>> {
351 self.typed()
352 }
353
354 /// `a=msid` lines (RFC 8830 section 2): one per MediaStream the track is in.
355 pub fn msids(&self) -> shared::error::Result<Vec<$crate::attribute::Msid>> {
356 self.typed_all()
357 }
358
359 /// `a=ssrc` lines (RFC 5576 section 4.1), one per source attribute.
360 pub fn ssrcs(&self) -> shared::error::Result<Vec<$crate::attribute::Ssrc>> {
361 self.typed_all()
362 }
363
364 /// `a=ssrc-group` lines (RFC 5576 section 4.2).
365 pub fn ssrc_groups(&self) -> shared::error::Result<Vec<$crate::attribute::SsrcGroup>> {
366 self.typed_all()
367 }
368
369 /// `a=rid` lines (RFC 8851 section 10).
370 pub fn rids(&self) -> shared::error::Result<Vec<$crate::attribute::Rid>> {
371 self.typed_all()
372 }
373
374 /// `a=simulcast` (RFC 8853 section 5.1).
375 pub fn simulcast(&self) -> shared::error::Result<Option<$crate::attribute::Simulcast>> {
376 self.typed()
377 }
378
379 /// `a=rtcp` (RFC 3605 section 2.1).
380 pub fn rtcp(&self) -> shared::error::Result<Option<$crate::attribute::Rtcp>> {
381 self.typed()
382 }
383
384 /// Whether `a=rtcp-mux` is present (RFC 5761 section 5.1.1).
385 pub fn rtcp_mux(&self) -> shared::error::Result<bool> {
386 self.flag($crate::description::session::ATTR_KEY_RTCPMUX)
387 }
388
389 /// Whether `a=rtcp-mux-only` is present (RFC 8858 section 3).
390 pub fn rtcp_mux_only(&self) -> shared::error::Result<bool> {
391 self.flag($crate::description::session::ATTR_KEY_RTCPMUX_ONLY)
392 }
393
394 /// Whether `a=rtcp-rsize` is present (RFC 5506 section 5).
395 pub fn rtcp_rsize(&self) -> shared::error::Result<bool> {
396 self.flag($crate::description::session::ATTR_KEY_RTCPRSIZE)
397 }
398
399 /// `a=rtcp-fb` lines (RFC 4585 section 4.2), the wildcard ones included.
400 pub fn rtcp_fbs(&self) -> shared::error::Result<Vec<$crate::attribute::RtcpFb>> {
401 self.typed_all()
402 }
403
404 /// `a=rtpmap` lines (RFC 8866 section 6.6).
405 pub fn rtpmaps(&self) -> shared::error::Result<Vec<$crate::attribute::RtpMap>> {
406 self.typed_all()
407 }
408
409 /// `a=fmtp` lines (RFC 8866 section 6.15).
410 pub fn fmtps(&self) -> shared::error::Result<Vec<$crate::attribute::Fmtp>> {
411 self.typed_all()
412 }
413
414 /// `a=ptime` (RFC 8866 section 6.4).
415 pub fn ptime(&self) -> shared::error::Result<Option<$crate::attribute::Ptime>> {
416 self.typed()
417 }
418
419 /// `a=maxptime` (RFC 8866 section 6.5).
420 pub fn maxptime(&self) -> shared::error::Result<Option<$crate::attribute::MaxPtime>> {
421 self.typed()
422 }
423
424 /// `a=framerate` (RFC 8866 section 6.13).
425 pub fn framerate(&self) -> shared::error::Result<Option<$crate::attribute::FrameRate>> {
426 self.typed()
427 }
428
429 /// `a=imageattr` lines (RFC 6236 section 3.1).
430 pub fn imageattrs(&self) -> shared::error::Result<Vec<$crate::attribute::ImageAttr>> {
431 self.typed_all()
432 }
433
434 /// `a=content` (RFC 4796 section 5).
435 pub fn content(&self) -> shared::error::Result<Option<$crate::attribute::Content>> {
436 self.typed()
437 }
438
439 /// `a=candidate` lines (RFC 8839 section 5.1).
440 pub fn candidates(&self) -> shared::error::Result<Vec<$crate::attribute::Candidate>> {
441 self.typed_all()
442 }
443
444 /// Whether `a=end-of-candidates` is present (RFC 8840).
445 pub fn end_of_candidates(&self) -> shared::error::Result<bool> {
446 self.flag($crate::description::session::ATTR_KEY_END_OF_CANDIDATES)
447 }
448
449 /// `a=remote-candidates` (RFC 8839 section 5.2).
450 pub fn remote_candidates(
451 &self,
452 ) -> shared::error::Result<Option<$crate::attribute::RemoteCandidates>> {
453 self.typed()
454 }
455
456 /// `a=sctp-port` (RFC 8841 section 5).
457 pub fn sctp_port(&self) -> shared::error::Result<Option<$crate::attribute::SctpPort>> {
458 self.typed()
459 }
460
461 /// `a=max-message-size` (RFC 8841 section 6).
462 pub fn max_message_size(
463 &self,
464 ) -> shared::error::Result<Option<$crate::attribute::MaxMessageSize>> {
465 self.typed()
466 }
467
468 /// `a=sctpmap`, the form `a=sctp-port` replaced (draft-ietf-mmusic-sctp-sdp-05).
469 pub fn sctpmap(&self) -> shared::error::Result<Option<$crate::attribute::SctpMap>> {
470 self.typed()
471 }
472
473 /// `a=orient` (RFC 8866 section 6.8).
474 pub fn orient(&self) -> shared::error::Result<Option<$crate::attribute::Orient>> {
475 self.typed()
476 }
477
478 /// `a=quality` (RFC 8866 section 6.14).
479 pub fn quality(&self) -> shared::error::Result<Option<$crate::attribute::Quality>> {
480 self.typed()
481 }
482
483 /// Whether `a=bundle-only` is present (RFC 9143 section 6).
484 pub fn bundle_only(&self) -> shared::error::Result<bool> {
485 self.flag($crate::description::session::ATTR_KEY_BUNDLE_ONLY)
486 }
487 };
488}
489pub(crate) use media_accessors;