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        "tool" => check::<Tool>(value),
67        "type" => check::<ConferenceType>(value),
68        "orient" => check::<Orient>(value),
69        "quality" => check::<Quality>(value),
70        "imageattr" => check::<ImageAttr>(value),
71        "content" => check::<Content>(value),
72        "candidate" => check::<Candidate>(value),
73        "remote-candidates" => check::<RemoteCandidates>(value),
74        "ice-ufrag" => check::<IceUfrag>(value),
75        "ice-pwd" => check::<IcePwd>(value),
76        "ice-options" => check::<IceOptions>(value),
77        "ice-pacing" => check::<IcePacing>(value),
78        "fingerprint" => check::<Fingerprint>(value),
79        "setup" => check::<Setup>(value),
80        "tls-id" => check::<TlsId>(value),
81        "identity" => check::<Identity>(value),
82        "sctp-port" => check::<SctpPort>(value),
83        "max-message-size" => check::<MaxMessageSize>(value),
84        "sctpmap" => check::<SctpMap>(value),
85        // RFC 8866 section 5.13: an attribute that is not understood is ignored. What is
86        // left to check is that its name is a token and its value has no NUL, CR or LF,
87        // which matters for a description that was built and not parsed.
88        _ => {
89            if grammar::is_token(name)
90                && value.is_none_or(|v| v.is_empty() || grammar::is_byte_string(v))
91            {
92                Ok(())
93            } else {
94                Err(Error::SdpInvalidSyntax(format!(
95                    "attribute `{}`",
96                    name.escape_debug()
97                )))
98            }
99        }
100    }
101}
102
103/// Checks one attribute's value against the grammar of its name (RFC 9429 section 5.8: a
104/// line that is not well formed rejects the description "even if the value is to be
105/// discarded"): a known attribute's value must parse as its type, a property attribute
106/// (`rtcp-mux`, `sendrecv`, ...) must have none, and an unknown one needs only a token name
107/// and a value without NUL, CR or LF (RFC 8866 section 5.13). The checks across lines and
108/// levels of [`SessionDescription::validate`] are not made.
109pub fn check_attribute(attribute: &Attribute) -> Result<()> {
110    let (name, value) = attribute.parts();
111    check_value(name, value)
112}
113
114fn check_level(name: &str, media: bool) -> Result<()> {
115    let Some(level) = mux::attribute(name).and_then(|row| row.level) else {
116        return Ok(());
117    };
118    let allowed = match (level, media) {
119        (AttributeLevel::Source, _) => false,
120        (level, true) => level.allows_media(),
121        (level, false) => level.allows_session(),
122    };
123    if allowed {
124        Ok(())
125    } else {
126        Err(Error::SdpInvalidValue(format!(
127            "`a={name}` at the {} level",
128            if media { "media" } else { "session" }
129        )))
130    }
131}
132
133/// The attributes a level holds at most once (RFC 8866 section 6.7 for the direction,
134/// RFC 5888 section 4 for `mid`, and so on): a second one makes the level ambiguous.
135const SINGLE: [&str; 15] = [
136    "mid",
137    "setup",
138    "ice-ufrag",
139    "ice-pwd",
140    "ice-options",
141    "ice-pacing",
142    "tls-id",
143    "simulcast",
144    "sctp-port",
145    "max-message-size",
146    "rtcp",
147    "ptime",
148    "maxptime",
149    "framerate",
150    "remote-candidates",
151];
152
153fn check_attributes(attributes: &[Attribute], media: bool) -> Result<()> {
154    let mut directions = 0usize;
155    for (index, attribute) in attributes.iter().enumerate() {
156        let (name, value) = attribute.parts();
157        check_value(name, value)?;
158        check_level(name, media)?;
159        if matches!(
160            name,
161            ATTR_KEY_SEND_RECV | ATTR_KEY_SEND_ONLY | ATTR_KEY_RECV_ONLY | ATTR_KEY_INACTIVE
162        ) {
163            directions += 1;
164        }
165        if SINGLE.contains(&name) && attributes[..index].iter().any(|a| a.parts().0 == name) {
166            return Err(Error::SdpInvalidValue(format!(
167                "more than one `a={name}` at one level"
168            )));
169        }
170    }
171    if directions > 1 {
172        return Err(Error::SdpInvalidValue(
173            "more than one direction attribute at one level".to_owned(),
174        ));
175    }
176    Ok(())
177}
178
179fn check_media(media: &MediaDescription, session_has_connection: bool) -> Result<()> {
180    // RFC 8866 section 5.7: "A session description MUST contain either at least one 'c='
181    // line in each media description or a single 'c=' line at the session level."
182    if media.connection_information.is_empty() && !session_has_connection {
183        return Err(Error::SdpInvalidSyntax(format!(
184            "the `m={}` section has no `c=` line and the session has none",
185            media.media_name.media
186        )));
187    }
188    check_attributes(&media.attributes, true)?;
189
190    // Every rid an a=simulcast line names is one of the section's a=rid lines, and a rid-id
191    // names one a=rid line (RFC 8853 section 5.2, RFC 8851 section 4).
192    let rids = media.rids()?;
193    for (index, rid) in rids.iter().enumerate() {
194        if rids[..index].iter().any(|other| other.id == rid.id) {
195            return Err(Error::SdpInvalidValue(format!(
196                "`a=rid:{}` occurs twice in one media section",
197                rid.id
198            )));
199        }
200    }
201    if let Some(simulcast) = media.simulcast()? {
202        for id in simulcast.rids() {
203            if !rids.iter().any(|rid| rid.id == id) {
204                return Err(Error::SdpInvalidValue(format!(
205                    "`a=simulcast` names the rid `{id}`, which has no `a=rid` line"
206                )));
207            }
208        }
209    }
210
211    // RFC 8866 section 5.14: with an RTP profile, the formats are RTP payload type numbers.
212    if media.media_name.protos.iter().any(|p| p == "RTP") {
213        for format in &media.media_name.formats {
214            if !grammar::is_digits(format) || !format.parse::<u8>().is_ok_and(|pt| pt <= 127) {
215                return Err(Error::SdpInvalidValue(format!(
216                    "`{format}` is not an RTP payload type"
217                )));
218            }
219        }
220    }
221    Ok(())
222}
223
224impl SessionDescription {
225    /// Checks what [`SessionDescription::unmarshal`] leaves unchecked: everything that
226    /// takes more than one line to judge, and the value of every attribute this crate has a
227    /// type for.
228    ///
229    /// RFC 9429 section 5.8 has a description rejected when a line is not well formed "even
230    /// if its value is discarded"; this is that check for the `a=` lines. It returns the
231    /// first problem found:
232    ///
233    /// * a media description without `c=` when the session has none (RFC 8866 section 5.7);
234    /// * a known attribute whose value does not match its grammar, or a property attribute
235    ///   (`rtcp-mux`, `sendrecv`, ...) that carries a value;
236    /// * an attribute at a level it is not defined for (`a=group` in a media description,
237    ///   `a=rtcp-mux` at the session level, ...), per the levels of [`mux`];
238    /// * more than one direction attribute at one level (RFC 8866 section 6.7), or more
239    ///   than one of an attribute that a level holds once (`mid`, `setup`, `ice-ufrag`,
240    ///   `ice-pwd`, `simulcast`, ...);
241    /// * two `a=mid` with the same tag (RFC 5888 section 4);
242    /// * two `a=rid` with one id in a section, an `a=simulcast` naming a rid without an
243    ///   `a=rid` line;
244    /// * in a section with an RTP profile, a format that is not a payload type (RFC 8866
245    ///   section 5.14).
246    ///
247    /// An attribute this crate does not know is not an error (RFC 8866 section 5.13).
248    /// Negotiation rules (what an answer may contain given an offer, which tags a group may
249    /// name, BUNDLE consistency across sections) are not checked here: they belong to the
250    /// layer that negotiates.
251    pub fn validate(&self) -> Result<()> {
252        check_attributes(&self.attributes, false)?;
253
254        let mut mids: Vec<String> = Vec::with_capacity(self.media_descriptions.len());
255        for media in &self.media_descriptions {
256            check_media(media, self.connection_information.is_some())?;
257            if let Some(mid) = media.mid()? {
258                if mids.iter().any(|m| m == mid.as_str()) {
259                    return Err(Error::SdpInvalidValue(format!(
260                        "`a=mid:{mid}` occurs twice"
261                    )));
262                }
263                mids.push(mid.as_str().to_owned());
264            }
265        }
266
267        Ok(())
268    }
269}