Skip to main content

rtci_sdp/attribute/
validate.rs

1//! Checking a whole description: [`SessionDescription::validate`].
2
3use shared::error::{Error, Result};
4
5use super::mux::{self, AttributeLevel};
6use super::*;
7use crate::description::common::Attribute;
8use crate::description::media::MediaDescription;
9use crate::description::session::*;
10use crate::extmap::ExtMap;
11use crate::grammar;
12
13/// Property attributes: the ones that take no value.
14const FLAGS: [&str; 12] = [
15    ATTR_KEY_SEND_RECV,
16    ATTR_KEY_SEND_ONLY,
17    ATTR_KEY_RECV_ONLY,
18    ATTR_KEY_INACTIVE,
19    ATTR_KEY_RTCPMUX,
20    ATTR_KEY_RTCPMUX_ONLY,
21    ATTR_KEY_RTCPRSIZE,
22    ATTR_KEY_ICELITE,
23    ATTR_KEY_END_OF_CANDIDATES,
24    ATTR_KEY_BUNDLE_ONLY,
25    ATTR_KEY_EXTMAP_ALLOW_MIXED,
26    ATTR_KEY_CRYPTEX,
27];
28
29/// Parses `value` when the grammar of the attribute `name` is known; an unknown attribute
30/// is fine as it is.
31fn check_value(name: &str, value: Option<&str>) -> Result<()> {
32    fn check<T: TypedAttribute>(value: Option<&str>) -> Result<()> {
33        let value = value
34            .ok_or_else(|| Error::SdpInvalidSyntax(format!("`a={}` has no value", T::NAME)))?;
35        T::parse(value).map(|_| ())
36    }
37
38    if FLAGS.contains(&name) {
39        return match value {
40            None => Ok(()),
41            Some(_) => Err(Error::SdpInvalidSyntax(format!(
42                "`a={name}` takes no value"
43            ))),
44        };
45    }
46    match name {
47        "group" => check::<Group>(value),
48        "mid" => check::<Mid>(value),
49        "msid" => check::<Msid>(value),
50        "msid-semantic" => check::<MsidSemantic>(value),
51        "ssrc" => check::<Ssrc>(value),
52        "ssrc-group" => check::<SsrcGroup>(value),
53        "rid" => check::<Rid>(value),
54        "simulcast" => check::<Simulcast>(value),
55        "extmap" => check::<ExtMap>(value),
56        "rtcp" => check::<Rtcp>(value),
57        "rtcp-fb" => check::<RtcpFb>(value),
58        // RFC 3611 section 5.1: `"a=" "rtcp-xr" [":" xr-format *(SP xr-format)]`, the value
59        // is optional.
60        "rtcp-xr" => value.map_or(Ok(()), |v| RtcpXr::parse(v).map(|_| ())),
61        "rtpmap" => check::<RtpMap>(value),
62        "fmtp" => check::<Fmtp>(value),
63        "ptime" => check::<Ptime>(value),
64        "maxptime" => check::<MaxPtime>(value),
65        "framerate" => check::<FrameRate>(value),
66        "imageattr" => check::<ImageAttr>(value),
67        "content" => check::<Content>(value),
68        "candidate" => check::<Candidate>(value),
69        "remote-candidates" => check::<RemoteCandidates>(value),
70        "ice-ufrag" => check::<IceUfrag>(value),
71        "ice-pwd" => check::<IcePwd>(value),
72        "ice-options" => check::<IceOptions>(value),
73        "ice-pacing" => check::<IcePacing>(value),
74        "fingerprint" => check::<Fingerprint>(value),
75        "setup" => check::<Setup>(value),
76        "tls-id" => check::<TlsId>(value),
77        "identity" => check::<Identity>(value),
78        "sctp-port" => check::<SctpPort>(value),
79        "max-message-size" => check::<MaxMessageSize>(value),
80        "sctpmap" => check::<SctpMap>(value),
81        // RFC 8866 section 5.13: an attribute that is not understood is ignored. What is
82        // left to check is that its name is a token and its value has no NUL, CR or LF,
83        // which matters for a description that was built and not parsed.
84        _ => {
85            if grammar::is_token(name)
86                && value.is_none_or(|v| v.is_empty() || grammar::is_byte_string(v))
87            {
88                Ok(())
89            } else {
90                Err(Error::SdpInvalidSyntax(format!(
91                    "attribute `{}`",
92                    name.escape_debug()
93                )))
94            }
95        }
96    }
97}
98
99/// Checks one attribute's value against the grammar of its name (RFC 9429 section 5.8: a
100/// line that is not well formed rejects the description "even if the value is to be
101/// discarded"): a known attribute's value must parse as its type, a property attribute
102/// (`rtcp-mux`, `sendrecv`, ...) must have none, and an unknown one needs only a token name
103/// and a value without NUL, CR or LF (RFC 8866 section 5.13). The checks across lines and
104/// levels of [`SessionDescription::validate`] are not made.
105pub fn check_attribute(attribute: &Attribute) -> Result<()> {
106    let (name, value) = attribute.parts();
107    check_value(name, value)
108}
109
110fn check_level(name: &str, media: bool) -> Result<()> {
111    let Some(level) = mux::attribute(name).and_then(|row| row.level) else {
112        return Ok(());
113    };
114    let allowed = match (level, media) {
115        (AttributeLevel::Source, _) => false,
116        (level, true) => level.allows_media(),
117        (level, false) => level.allows_session(),
118    };
119    if allowed {
120        Ok(())
121    } else {
122        Err(Error::SdpInvalidValue(format!(
123            "`a={name}` at the {} level",
124            if media { "media" } else { "session" }
125        )))
126    }
127}
128
129/// The attributes a level holds at most once (RFC 8866 section 6.7 for the direction,
130/// RFC 5888 section 4 for `mid`, and so on): a second one makes the level ambiguous.
131const SINGLE: [&str; 15] = [
132    "mid",
133    "setup",
134    "ice-ufrag",
135    "ice-pwd",
136    "ice-options",
137    "ice-pacing",
138    "tls-id",
139    "simulcast",
140    "sctp-port",
141    "max-message-size",
142    "rtcp",
143    "ptime",
144    "maxptime",
145    "framerate",
146    "remote-candidates",
147];
148
149fn check_attributes(attributes: &[Attribute], media: bool) -> Result<()> {
150    let mut directions = 0usize;
151    for (index, attribute) in attributes.iter().enumerate() {
152        let (name, value) = attribute.parts();
153        check_value(name, value)?;
154        check_level(name, media)?;
155        if matches!(
156            name,
157            ATTR_KEY_SEND_RECV | ATTR_KEY_SEND_ONLY | ATTR_KEY_RECV_ONLY | ATTR_KEY_INACTIVE
158        ) {
159            directions += 1;
160        }
161        if SINGLE.contains(&name) && attributes[..index].iter().any(|a| a.parts().0 == name) {
162            return Err(Error::SdpInvalidValue(format!(
163                "more than one `a={name}` at one level"
164            )));
165        }
166    }
167    if directions > 1 {
168        return Err(Error::SdpInvalidValue(
169            "more than one direction attribute at one level".to_owned(),
170        ));
171    }
172    Ok(())
173}
174
175fn check_media(media: &MediaDescription, session_has_connection: bool) -> Result<()> {
176    // RFC 8866 section 5.7: "A session description MUST contain either at least one 'c='
177    // line in each media description or a single 'c=' line at the session level."
178    if media.connection_information.is_none() && !session_has_connection {
179        return Err(Error::SdpInvalidSyntax(format!(
180            "the `m={}` section has no `c=` line and the session has none",
181            media.media_name.media
182        )));
183    }
184    check_attributes(&media.attributes, true)?;
185
186    // Every rid an a=simulcast line names is one of the section's a=rid lines, and a rid-id
187    // names one a=rid line (RFC 8853 section 5.2, RFC 8851 section 4).
188    let rids = media.rids()?;
189    for (index, rid) in rids.iter().enumerate() {
190        if rids[..index].iter().any(|other| other.id == rid.id) {
191            return Err(Error::SdpInvalidValue(format!(
192                "`a=rid:{}` occurs twice in one media section",
193                rid.id
194            )));
195        }
196    }
197    if let Some(simulcast) = media.simulcast()? {
198        for id in simulcast.rids() {
199            if !rids.iter().any(|rid| rid.id == id) {
200                return Err(Error::SdpInvalidValue(format!(
201                    "`a=simulcast` names the rid `{id}`, which has no `a=rid` line"
202                )));
203            }
204        }
205    }
206
207    // RFC 8866 section 5.14: with an RTP profile, the formats are RTP payload type numbers.
208    if media.media_name.protos.iter().any(|p| p == "RTP") {
209        for format in &media.media_name.formats {
210            if !grammar::is_digits(format) || !format.parse::<u8>().is_ok_and(|pt| pt <= 127) {
211                return Err(Error::SdpInvalidValue(format!(
212                    "`{format}` is not an RTP payload type"
213                )));
214            }
215        }
216    }
217    Ok(())
218}
219
220impl SessionDescription {
221    /// Checks what [`SessionDescription::unmarshal`] leaves unchecked: everything that
222    /// takes more than one line to judge, and the value of every attribute this crate has a
223    /// type for.
224    ///
225    /// RFC 9429 section 5.8 has a description rejected when a line is not well formed "even
226    /// if its value is discarded"; this is that check for the `a=` lines. It returns the
227    /// first problem found:
228    ///
229    /// * a media description without `c=` when the session has none (RFC 8866 section 5.7);
230    /// * a known attribute whose value does not match its grammar, or a property attribute
231    ///   (`rtcp-mux`, `sendrecv`, ...) that carries a value;
232    /// * an attribute at a level it is not defined for (`a=group` in a media description,
233    ///   `a=rtcp-mux` at the session level, ...), per the levels of [`mux`];
234    /// * more than one direction attribute at one level (RFC 8866 section 6.7), or more
235    ///   than one of an attribute that a level holds once (`mid`, `setup`, `ice-ufrag`,
236    ///   `ice-pwd`, `simulcast`, ...);
237    /// * two `a=mid` with the same tag (RFC 5888 section 4);
238    /// * two `a=rid` with one id in a section, an `a=simulcast` naming a rid without an
239    ///   `a=rid` line;
240    /// * in a section with an RTP profile, a format that is not a payload type (RFC 8866
241    ///   section 5.14).
242    ///
243    /// An attribute this crate does not know is not an error (RFC 8866 section 5.13).
244    /// Negotiation rules (what an answer may contain given an offer, which tags a group may
245    /// name, BUNDLE consistency across sections) are not checked here: they belong to the
246    /// layer that negotiates.
247    pub fn validate(&self) -> Result<()> {
248        check_attributes(&self.attributes, false)?;
249
250        let mut mids: Vec<String> = Vec::with_capacity(self.media_descriptions.len());
251        for media in &self.media_descriptions {
252            check_media(media, self.connection_information.is_some())?;
253            if let Some(mid) = media.mid()? {
254                if mids.iter().any(|m| m == mid.as_str()) {
255                    return Err(Error::SdpInvalidValue(format!(
256                        "`a=mid:{mid}` occurs twice"
257                    )));
258                }
259                mids.push(mid.as_str().to_owned());
260            }
261        }
262
263        Ok(())
264    }
265}