Skip to main content

rtci_sdp/description/
session.rs

1//! The session description — a whole SDP document.
2//!
3//! A [`SessionDescription`](crate::description::session::SessionDescription) is the session-level fields (`v=`, `o=`, `s=`, `t=`, …) followed by
4//! any number of [`MediaDescription`](crate::description::media::MediaDescription)s. `unmarshal` parses one
5//! from a string and `marshal` prints it back; the round trip is faithful, including attributes
6//! this crate does not interpret.
7//!
8//! The `ATTR_KEY_*` constants name the `a=` attributes WebRTC relies on — `mid`, `msid`,
9//! `setup`, `rtcp-mux`, `extmap` and the direction flags — and the `SEMANTIC_TOKEN_*` constants
10//! name the grouping semantics used with `a=group` and `a=msid-semantic`.
11
12use std::collections::HashMap;
13use std::convert::TryFrom;
14use std::io::Read;
15use std::str::FromStr;
16use std::time::{Duration, SystemTime, UNIX_EPOCH};
17use std::{fmt, io};
18
19use url::Url;
20
21use crate::grammar::{self, invalid, syntax};
22use crate::lexer::*;
23use crate::util::*;
24use shared::error::{Error, Result};
25
26use super::common::*;
27use super::media::*;
28
29/// Constants for SDP attributes used in JSEP
30pub const ATTR_KEY_CANDIDATE: &str = "candidate";
31/// `a=end-of-candidates`: ICE gathering for this section is complete.
32pub const ATTR_KEY_END_OF_CANDIDATES: &str = "end-of-candidates";
33/// `a=identity`: an identity assertion for the session.
34pub const ATTR_KEY_IDENTITY: &str = "identity";
35/// `a=group`: groups m-lines, as BUNDLE does.
36pub const ATTR_KEY_GROUP: &str = "group";
37/// `a=ssrc`: declares an SSRC and its attributes.
38pub const ATTR_KEY_SSRC: &str = "ssrc";
39/// `a=ssrc-group`: relates SSRCs, such as an RTX stream to its primary.
40pub const ATTR_KEY_SSRC_GROUP: &str = "ssrc-group";
41/// `a=msid`: associates a track with a media stream.
42pub const ATTR_KEY_MSID: &str = "msid";
43/// `a=msid-semantic`: declares the semantics used by `a=msid`.
44pub const ATTR_KEY_MSID_SEMANTIC: &str = "msid-semantic";
45/// `a=setup`: the DTLS role — `active`, `passive` or `actpass`.
46pub const ATTR_KEY_CONNECTION_SETUP: &str = "setup";
47/// `a=mid`: the media identification tag that names this m-line.
48pub const ATTR_KEY_MID: &str = "mid";
49/// `a=ice-lite`: the endpoint is an ICE-lite implementation.
50pub const ATTR_KEY_ICELITE: &str = "ice-lite";
51/// `a=rtcp-mux`: RTP and RTCP share one port.
52pub const ATTR_KEY_RTCPMUX: &str = "rtcp-mux";
53/// `a=rtcp-rsize`: reduced-size RTCP is supported.
54pub const ATTR_KEY_RTCPRSIZE: &str = "rtcp-rsize";
55/// `a=inactive`: neither send nor receive.
56pub const ATTR_KEY_INACTIVE: &str = "inactive";
57/// `a=recvonly`: receive only.
58pub const ATTR_KEY_RECV_ONLY: &str = "recvonly";
59/// `a=sendonly`: send only.
60pub const ATTR_KEY_SEND_ONLY: &str = "sendonly";
61/// `a=sendrecv`: send and receive.
62pub const ATTR_KEY_SEND_RECV: &str = "sendrecv";
63/// `a=extmap`: maps an RTP header-extension URI to an id.
64pub const ATTR_KEY_EXT_MAP: &str = "extmap";
65/// `a=extmap-allow-mixed`: one- and two-byte header extensions may be mixed.
66pub const ATTR_KEY_EXTMAP_ALLOW_MIXED: &str = "extmap-allow-mixed";
67/// `a=max-message-size`: the largest SCTP message this endpoint accepts.
68pub const ATTR_KEY_MAX_MESSAGE_SIZE: &str = "max-message-size";
69/// `a=rtcp-mux-only`: RTP and RTCP share one port and nothing else is supported (RFC 8858).
70pub const ATTR_KEY_RTCPMUX_ONLY: &str = "rtcp-mux-only";
71/// `a=rtcp`: the RTCP port and address (RFC 3605).
72pub const ATTR_KEY_RTCP: &str = "rtcp";
73/// `a=rtcp-fb`: an RTCP feedback capability (RFC 4585).
74pub const ATTR_KEY_RTCP_FB: &str = "rtcp-fb";
75/// `a=rtcp-xr`: RTCP extended reports (RFC 3611).
76pub const ATTR_KEY_RTCP_XR: &str = "rtcp-xr";
77/// `a=rtpmap`: the codec of a payload type.
78pub const ATTR_KEY_RTPMAP: &str = "rtpmap";
79/// `a=fmtp`: format-specific parameters.
80pub const ATTR_KEY_FMTP: &str = "fmtp";
81/// `a=ptime`: the preferred packet duration, in milliseconds.
82pub const ATTR_KEY_PTIME: &str = "ptime";
83/// `a=maxptime`: the longest packet duration, in milliseconds.
84pub const ATTR_KEY_MAXPTIME: &str = "maxptime";
85/// `a=framerate`: the maximum video frame rate.
86pub const ATTR_KEY_FRAMERATE: &str = "framerate";
87/// `a=imageattr`: image sizes a payload type sends or receives (RFC 6236).
88pub const ATTR_KEY_IMAGEATTR: &str = "imageattr";
89/// `a=content`: what a media stream shows (RFC 4796).
90pub const ATTR_KEY_CONTENT: &str = "content";
91/// `a=rid`: an RTP stream identifier and its restrictions (RFC 8851).
92pub const ATTR_KEY_RID: &str = "rid";
93/// `a=simulcast`: the simulcast streams of a media section (RFC 8853).
94pub const ATTR_KEY_SIMULCAST: &str = "simulcast";
95/// `a=ice-ufrag`: the ICE user name fragment.
96pub const ATTR_KEY_ICE_UFRAG: &str = "ice-ufrag";
97/// `a=ice-pwd`: the ICE password.
98pub const ATTR_KEY_ICE_PWD: &str = "ice-pwd";
99/// `a=ice-options`: the ICE options the agent supports.
100pub const ATTR_KEY_ICE_OPTIONS: &str = "ice-options";
101/// `a=ice-pacing`: the ICE pacing interval, in milliseconds.
102pub const ATTR_KEY_ICE_PACING: &str = "ice-pacing";
103/// `a=remote-candidates`: the remote candidates the controlling agent selected.
104pub const ATTR_KEY_REMOTE_CANDIDATES: &str = "remote-candidates";
105/// `a=fingerprint`: a certificate fingerprint (RFC 8122).
106pub const ATTR_KEY_FINGERPRINT: &str = "fingerprint";
107/// `a=tls-id`: the DTLS association identifier (RFC 8842).
108pub const ATTR_KEY_TLS_ID: &str = "tls-id";
109/// `a=sctp-port`: the SCTP port (RFC 8841).
110pub const ATTR_KEY_SCTP_PORT: &str = "sctp-port";
111/// `a=sctpmap`: the SCTP association of an old-style data section
112/// (draft-ietf-mmusic-sctp-sdp-05; replaced by `a=sctp-port`).
113pub const ATTR_KEY_SCTPMAP: &str = "sctpmap";
114/// `a=bundle-only`: the section is used only inside its BUNDLE group (RFC 9143).
115pub const ATTR_KEY_BUNDLE_ONLY: &str = "bundle-only";
116/// `a=cryptex`: RTP header extensions and CSRCs are encrypted (RFC 9335).
117pub const ATTR_KEY_CRYPTEX: &str = "cryptex";
118/// `BUNDLE`: the m= sections share one transport (RFC 9143).
119pub const SEMANTIC_TOKEN_BUNDLE: &str = "BUNDLE";
120
121/// Constants for semantic tokens used in JSEP
122pub const SEMANTIC_TOKEN_LIP_SYNCHRONIZATION: &str = "LS";
123/// `FID`: flow identification — the SSRCs carry the same content, as RTX does.
124pub const SEMANTIC_TOKEN_FLOW_IDENTIFICATION: &str = "FID";
125/// `FEC`: one SSRC carries error-correction data for another.
126pub const SEMANTIC_TOKEN_FORWARD_ERROR_CORRECTION: &str = "FEC";
127// https://datatracker.ietf.org/doc/html/rfc5956#section-4.1
128/// `FEC-FR`: the FEC framework grouping semantic.
129pub const SEMANTIC_TOKEN_FORWARD_ERROR_CORRECTION_FRAMEWORK: &str = "FEC-FR";
130/// `WMS`: WebRTC media streams, used with `a=msid-semantic`.
131pub const SEMANTIC_TOKEN_WEBRTC_MEDIA_STREAMS: &str = "WMS";
132
133/// The largest session description, in bytes, [`SessionDescription::unmarshal`] accepts. Real
134/// offers and answers are a few to a few hundred kilobytes.
135pub const MAX_SDP_SIZE: usize = 1 << 20;
136/// The most lines [`SessionDescription::unmarshal`] accepts in one session description.
137pub const MAX_SDP_LINES: usize = 65_536;
138/// The most `m=` sections [`SessionDescription::unmarshal`] accepts in one session description.
139pub const MAX_MEDIA_DESCRIPTIONS: usize = 1024;
140/// The most `a=` lines [`SessionDescription::unmarshal`] accepts at the session level, and in
141/// each `m=` section.
142pub const MAX_ATTRIBUTES_PER_SECTION: usize = 4096;
143/// The most formats [`SessionDescription::unmarshal`] accepts on one `m=` line. RTP payload
144/// types are 7 bits, so 128 distinct values exist.
145pub const MAX_FORMATS_PER_MEDIA: usize = 256;
146
147fn over_limit(what: &str, limit: usize) -> Error {
148    Error::SdpInvalidValue(format!("session description has more than {limit} {what}"))
149}
150
151/// Version describes the value provided by the "v=" field which gives
152/// the version of the Session Description Protocol.
153pub type Version = isize;
154
155/// A decimal number of any length, `1*DIGIT`: the `<sess-id>` and `<sess-version>` of an
156/// `o=` line (RFC 8866 section 9). The grammar sets no upper bound, so a compliant
157/// description may carry values beyond 64 bits (RFC 9429 section 5.2.1 has a JSEP endpoint
158/// generate them within 64 bits, and section 5.8 has it accept compliant SDP that does not
159/// follow its generation rules).
160///
161/// It keeps the digits as written, leading zeros included, so a description is written back
162/// as it was read; equality and order are those of the numbers.
163#[derive(Debug, Clone)]
164pub struct SdpDecimal(String);
165
166impl SdpDecimal {
167    /// `value` when it is `1*DIGIT`.
168    pub fn parse(value: &str) -> Option<Self> {
169        (!value.is_empty() && value.bytes().all(|b| b.is_ascii_digit()))
170            .then(|| SdpDecimal(value.to_owned()))
171    }
172
173    /// The digits as written.
174    pub fn as_str(&self) -> &str {
175        &self.0
176    }
177
178    /// The number, when it fits 64 bits.
179    pub fn to_u64(&self) -> Option<u64> {
180        self.0.parse().ok()
181    }
182
183    /// The digits without leading zeros ("0" for zero).
184    fn significant(&self) -> &str {
185        let trimmed = self.0.trim_start_matches('0');
186        if trimmed.is_empty() { "0" } else { trimmed }
187    }
188
189    /// The number plus one (RFC 3264 section 8: the version "MUST increment by one"), with
190    /// no upper bound.
191    pub fn incremented(&self) -> Self {
192        let mut digits: Vec<u8> = self.significant().bytes().collect();
193        let mut i = digits.len();
194        loop {
195            if i == 0 {
196                digits.insert(0, b'1');
197                break;
198            }
199            i -= 1;
200            if digits[i] == b'9' {
201                digits[i] = b'0';
202            } else {
203                digits[i] += 1;
204                break;
205            }
206        }
207        SdpDecimal(String::from_utf8(digits).unwrap_or_default())
208    }
209}
210
211impl Default for SdpDecimal {
212    fn default() -> Self {
213        SdpDecimal("0".to_owned())
214    }
215}
216
217impl From<u64> for SdpDecimal {
218    fn from(value: u64) -> Self {
219        SdpDecimal(value.to_string())
220    }
221}
222
223impl FromStr for SdpDecimal {
224    type Err = Error;
225
226    fn from_str(value: &str) -> Result<Self> {
227        SdpDecimal::parse(value).ok_or_else(|| syntax("1*DIGIT", value))
228    }
229}
230
231impl fmt::Display for SdpDecimal {
232    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
233        f.write_str(&self.0)
234    }
235}
236
237impl PartialEq for SdpDecimal {
238    fn eq(&self, other: &Self) -> bool {
239        self.significant() == other.significant()
240    }
241}
242
243impl Eq for SdpDecimal {}
244
245impl std::hash::Hash for SdpDecimal {
246    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
247        self.significant().hash(state);
248    }
249}
250
251impl PartialOrd for SdpDecimal {
252    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
253        Some(self.cmp(other))
254    }
255}
256
257impl Ord for SdpDecimal {
258    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
259        let (a, b) = (self.significant(), other.significant());
260        a.len().cmp(&b.len()).then_with(|| a.cmp(b))
261    }
262}
263
264impl PartialEq<u64> for SdpDecimal {
265    fn eq(&self, other: &u64) -> bool {
266        self.to_u64() == Some(*other)
267    }
268}
269
270/// Origin defines the structure for the "o=" field which provides the
271/// originator of the session plus a session identifier and version number.
272#[derive(Debug, Default, Clone)]
273pub struct Origin {
274    /// The originator's user name, or `-` when withheld.
275    pub username: String,
276    /// A globally unique session identifier, `1*DIGIT` of any length.
277    pub session_id: SdpDecimal,
278    /// Incremented on each modification of the session description; `1*DIGIT` of any
279    /// length.
280    pub session_version: SdpDecimal,
281    /// The network type, always `IN` in practice.
282    pub network_type: String,
283    /// The address type, `IP4` or `IP6`.
284    pub address_type: String,
285    /// The originator's address. WebRTC does not use it and sends a placeholder.
286    pub unicast_address: String,
287}
288
289impl fmt::Display for Origin {
290    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
291        write!(
292            f,
293            "{} {} {} {} {} {}",
294            self.username,
295            self.session_id,
296            self.session_version,
297            self.network_type,
298            self.address_type,
299            self.unicast_address,
300        )
301    }
302}
303
304/// The seconds from the NTP epoch (1900-01-01 UTC) to the Unix epoch: RFC 8866 section 5.2
305/// recommends "a timestamp, in seconds since January 1, 1900 UTC" for `<sess-id>` and, "as
306/// with <sess-id>", for `<sess-version>`.
307pub const NTP_UNIX_EPOCH_OFFSET_SECS: u64 = 2_208_988_800;
308
309impl Origin {
310    /// The `o=` line RFC 9429 section 5.2.1 gives an offer: `<username>` `-`, the given
311    /// session id and version, and the non-meaningful address `IN IP4 0.0.0.0`.
312    pub fn jsep(session_id: u64, session_version: u64) -> Self {
313        Origin {
314            username: "-".to_owned(),
315            session_id: session_id.into(),
316            session_version: session_version.into(),
317            network_type: "IN".to_owned(),
318            address_type: "IP4".to_owned(),
319            unicast_address: "0.0.0.0".to_owned(),
320        }
321    }
322
323    /// An empty session description with SDP version 0.
324    pub fn new() -> Self {
325        Origin {
326            username: "".to_owned(),
327            session_id: SdpDecimal::default(),
328            session_version: SdpDecimal::default(),
329            network_type: "".to_owned(),
330            address_type: "".to_owned(),
331            unicast_address: "".to_owned(),
332        }
333    }
334}
335
336/// SessionName describes a structured representations for the "s=" field
337/// and is the textual session name.
338pub type SessionName = String;
339
340/// EmailAddress describes a structured representations for the "e=" line
341/// which specifies email contact information for the person responsible for
342/// the conference.
343pub type EmailAddress = String;
344
345/// PhoneNumber describes a structured representations for the "p=" line
346/// specify phone contact information for the person responsible for the
347/// conference.
348pub type PhoneNumber = String;
349
350/// TimeZone is one `<adjustment time> <offset>` pair of a "z=" line, which describes
351/// repeated sessions scheduling.
352#[derive(Debug, Default, Clone, PartialEq, Eq)]
353pub struct TimeZone {
354    /// The time at which the offset takes effect.
355    pub adjustment_time: u64,
356    /// The offset from the session's base time, in seconds.
357    pub offset: i64,
358}
359
360impl fmt::Display for TimeZone {
361    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
362        write!(f, "{} {}", self.adjustment_time, self.offset)
363    }
364}
365
366/// TimeDescription describes the "t=", "r=" and "z=" fields of the session description,
367/// which specify the start and stop times of a session, its repeat intervals and durations,
368/// and the time zone adjustments of those repetitions.
369///
370/// RFC 8866 section 9: `time-description = time-field [repeat-description]`,
371/// `repeat-description = 1*repeat-field [zone-field]`.
372#[derive(Debug, Default, Clone)]
373pub struct TimeDescription {
374    /// `t=<start-time> <stop-time>`
375    ///
376    /// <https://www.rfc-editor.org/rfc/rfc8866#section-5.9>
377    pub timing: Timing,
378
379    /// `r=<repeat interval> <active duration> <offsets from start-time>`
380    ///
381    /// <https://www.rfc-editor.org/rfc/rfc8866#section-5.10>
382    pub repeat_times: Vec<RepeatTime>,
383
384    /// `z=<adjustment time> <offset> <adjustment time> <offset> ...`
385    ///
386    /// The zone adjustments of this time description's repetitions. Written after the `r=`
387    /// lines.
388    ///
389    /// <https://www.rfc-editor.org/rfc/rfc8866#section-5.11>
390    pub time_zones: Vec<TimeZone>,
391}
392
393/// Timing defines the "t=" field's structured representation for the start and
394/// stop times.
395#[derive(Debug, Default, Clone, PartialEq, Eq)]
396pub struct Timing {
397    /// Session start time in NTP seconds; `0` means unbounded.
398    pub start_time: u64,
399    /// Session stop time in NTP seconds; `0` means unbounded.
400    pub stop_time: u64,
401}
402
403impl fmt::Display for Timing {
404    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
405        write!(f, "{} {}", self.start_time, self.stop_time)
406    }
407}
408
409/// RepeatTime describes the "r=" fields of the session description which
410/// represents the intervals and durations for repeated scheduled sessions.
411#[derive(Debug, Default, Clone, PartialEq, Eq)]
412pub struct RepeatTime {
413    /// How often the session repeats, in seconds.
414    pub interval: i64,
415    /// How long each repetition lasts, in seconds.
416    pub duration: i64,
417    /// Offsets from the start time at which the session repeats.
418    pub offsets: Vec<i64>,
419}
420
421impl fmt::Display for RepeatTime {
422    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
423        write!(f, "{} {}", self.interval, self.duration)?;
424
425        for value in &self.offsets {
426            write!(f, " {value}")?;
427        }
428        Ok(())
429    }
430}
431
432/// SessionDescription is a a well-defined format for conveying sufficient
433/// information to discover and participate in a multimedia session.
434#[derive(Debug, Default, Clone)]
435pub struct SessionDescription {
436    /// `v=0`
437    ///
438    /// <https://www.rfc-editor.org/rfc/rfc8866#section-5.1>
439    pub version: Version,
440
441    /// `o=<username> <sess-id> <sess-version> <nettype> <addrtype> <unicast-address>`
442    ///
443    /// <https://www.rfc-editor.org/rfc/rfc8866#section-5.2>
444    pub origin: Origin,
445
446    /// `s=<session name>`
447    ///
448    /// Never empty in SDP: an empty name is written as `-`.
449    ///
450    /// <https://www.rfc-editor.org/rfc/rfc8866#section-5.3>
451    pub session_name: SessionName,
452
453    /// `i=<session description>`
454    ///
455    /// <https://www.rfc-editor.org/rfc/rfc8866#section-5.4>
456    pub session_information: Option<Information>,
457
458    /// `u=<uri>`: an RFC 3986 `URI-reference`, absolute or relative (RFC 8866 section 9:
459    /// `uri-field = %x75 "=" uri CRLF`, `uri = URI-reference`).
460    ///
461    /// <https://www.rfc-editor.org/rfc/rfc8866#section-5.5>
462    pub uri: Option<String>,
463
464    /// `e=<email-address>`, any number of lines.
465    ///
466    /// <https://www.rfc-editor.org/rfc/rfc8866#section-5.6>
467    pub email_addresses: Vec<EmailAddress>,
468
469    /// `p=<phone-number>`, any number of lines.
470    ///
471    /// <https://www.rfc-editor.org/rfc/rfc8866#section-5.6>
472    pub phone_numbers: Vec<PhoneNumber>,
473
474    /// `c=<nettype> <addrtype> <connection-address>`
475    ///
476    /// <https://www.rfc-editor.org/rfc/rfc8866#section-5.7>
477    pub connection_information: Option<ConnectionInformation>,
478
479    /// `b=<bwtype>:<bandwidth>`
480    ///
481    /// <https://www.rfc-editor.org/rfc/rfc8866#section-5.8>
482    pub bandwidth: Vec<Bandwidth>,
483
484    /// The time descriptions: `t=`, each with its `r=` and `z=` lines. SDP needs at least
485    /// one: an empty list is written as `t=0 0`.
486    ///
487    /// <https://www.rfc-editor.org/rfc/rfc8866#section-5.9>
488    pub time_descriptions: Vec<TimeDescription>,
489
490    /// Obsolete. RFC 8866 section 5.12: a `k=` line "MUST NOT be included in an SDP
491    /// description and MUST be discarded if received". The parser never sets this field
492    /// and nothing writes it; it is kept so that code naming it still builds.
493    pub encryption_key: Option<EncryptionKey>,
494
495    /// `a=<attribute>`
496    ///
497    /// `a=<attribute>:<value>`
498    ///
499    /// <https://www.rfc-editor.org/rfc/rfc8866#section-5.13>
500    pub attributes: Vec<Attribute>,
501
502    /// <https://www.rfc-editor.org/rfc/rfc8866#section-5.14>
503    pub media_descriptions: Vec<MediaDescription>,
504}
505
506/// Writes the description in the order RFC 8866 section 9 requires, whatever order its
507/// parts were set in: `v o s i u e* p* c b* (t r* z)+ a*`, then for each media description
508/// `m i c b* a*`.
509impl fmt::Display for SessionDescription {
510    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
511        write_key_value(f, "v=", Some(&self.version))?;
512        write_key_value(f, "o=", Some(&self.origin))?;
513        if self.session_name.is_empty() {
514            // Section 5.3: "The 's=' line MUST NOT be empty"; `s=-` names a nameless session.
515            write_key_value(f, "s=", Some("-"))?;
516        } else {
517            write_key_value(f, "s=", Some(&self.session_name))?;
518        }
519
520        write_key_value(f, "i=", self.session_information.as_ref())?;
521
522        if let Some(uri) = &self.uri {
523            write_key_value(f, "u=", Some(uri))?;
524        }
525        for email_address in &self.email_addresses {
526            write_key_value(f, "e=", Some(email_address))?;
527        }
528        for phone_number in &self.phone_numbers {
529            write_key_value(f, "p=", Some(phone_number))?;
530        }
531        if let Some(connection_information) = &self.connection_information {
532            write_key_value(f, "c=", Some(&connection_information))?;
533        }
534
535        for bandwidth in &self.bandwidth {
536            write_key_value(f, "b=", Some(&bandwidth))?;
537        }
538        if self.time_descriptions.is_empty() {
539            // Section 9: `1*time-description`.
540            write_key_value(f, "t=", Some("0 0"))?;
541        }
542        for time_description in &self.time_descriptions {
543            write_key_value(f, "t=", Some(&time_description.timing))?;
544            for repeat_time in &time_description.repeat_times {
545                write_key_value(f, "r=", Some(&repeat_time))?;
546            }
547            write_key_slice_of_values(f, "z=", &time_description.time_zones)?;
548        }
549
550        for attribute in &self.attributes {
551            write_key_value(f, "a=", Some(&attribute))?;
552        }
553
554        for media_description in &self.media_descriptions {
555            write_key_value(f, "m=", Some(&media_description.media_name))?;
556            write_key_value(f, "i=", media_description.media_title.as_ref())?;
557            for connection_information in &media_description.connection_information {
558                write_key_value(f, "c=", Some(connection_information))?;
559            }
560            for bandwidth in &media_description.bandwidth {
561                write_key_value(f, "b=", Some(&bandwidth))?;
562            }
563            for attribute in &media_description.attributes {
564                write_key_value(f, "a=", Some(&attribute))?;
565            }
566        }
567
568        Ok(())
569    }
570}
571
572/// What [`SessionDescription::unmarshal_with_options`] accepts beyond the RFC 8866 grammar.
573///
574/// [`SessionDescription::unmarshal`] parses with [`ParseOptions::strict`]: RFC 9429 section
575/// 5.8 has a description that is not well formed rejected, so the engine's own parsing is
576/// the grammar and nothing else. An application that has to read what other software calls
577/// SDP can ask for each leniency by name, or for all of them with
578/// [`ParseOptions::lenient`].
579///
580/// # What is accepted in every mode
581///
582/// These are the places where the parser is deliberately wider than the grammar, each for
583/// a reason:
584///
585/// * A line may end in a bare LF instead of CRLF. RFC 8866 section 5: "parsers SHOULD be
586///   tolerant and also accept lines terminated with a single newline character".
587/// * The last line may have no line ending, and empty lines may follow it. Descriptions
588///   that went through a text field or a `trim()` look like this.
589/// * `z=` may follow a `t=` line that has no `r=` line. RFC 4566 allowed it, and RFC 8866
590///   moved `z=` into the repeat description; a description written to RFC 4566 still parses.
591/// * `k=` lines are checked for syntax and dropped (RFC 8866 section 5.12: "MUST be
592///   discarded if received").
593/// * `a=name:` with an empty value is kept as an attribute whose value is the empty string.
594///   RFC 3611 defines one (`a=rtcp-xr:`), although the RFC 8866 `byte-string` is never empty.
595/// * An attribute this crate does not know is kept as it is, at either level (RFC 8866
596///   section 5.13: "an attribute that is not understood MUST be ignored"). The typed
597///   accessors are where the value of a known attribute is checked.
598/// * Several `c=` lines in one media description are accepted; the last one is kept.
599///
600/// # What is always refused
601///
602/// A type letter RFC 8866 does not define (section 5: such a description is ignored or
603/// rejected whole), a line that is not `<type>=<value>`, NUL, a bare CR, text that is not
604/// UTF-8 when the description names no other set with `a=charset` (`unmarshal`, from bytes),
605/// session-level lines out of order, and a
606/// description without `v=`, `o=`, `s=` or `t=`.
607#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
608pub struct ParseOptions {
609    /// Skip empty lines before and between lines, as some media players accept.
610    pub blank_lines: bool,
611    /// Accept `i=`, `c=`, `b=` and `k=` after `a=` lines inside a media description. Some
612    /// gateways write them so; RFC 8866 section 5 has them "in exactly the order given".
613    pub unordered_media_lines: bool,
614    /// Do not check what the fields of a line contain beyond what the parser needs:
615    /// fields may be separated and surrounded by any run of spaces and tabs; `t=` times may
616    /// be any number; addresses in `o=` and `c=` need only be free of white space (and `c=`
617    /// may lack one); `i=`, `e=` and `p=` text is kept unchecked; `s=` may be empty; extra
618    /// fields after the stop time of `t=` are ignored.
619    pub loose_fields: bool,
620}
621
622impl ParseOptions {
623    /// The RFC 8866 grammar, with only the tolerance every mode has. The default.
624    pub const fn strict() -> Self {
625        ParseOptions {
626            blank_lines: false,
627            unordered_media_lines: false,
628            loose_fields: false,
629        }
630    }
631
632    /// Every leniency.
633    pub const fn lenient() -> Self {
634        ParseOptions {
635            blank_lines: true,
636            unordered_media_lines: true,
637            loose_fields: true,
638        }
639    }
640}
641
642/// Reset cleans the SessionDescription, and sets all fields back to their default values
643impl SessionDescription {
644    /// A session description with the session-level lines RFC 9429 section 5.2.1 gives an
645    /// offer: `v=0`, `o=- <sess-id> <sess-version> IN IP4 0.0.0.0` with a random 63-bit
646    /// session id and, for the session version, the system clock's seconds since 1900 (RFC
647    /// 8866 section 5.2: "it is RECOMMENDED that a timestamp be used"), `s=-` and `t=0 0`.
648    ///
649    /// `_identity` is ignored. It used to add a bare `a=identity`, which is not SDP: the
650    /// attribute carries an assertion (RFC 8827 section 5). An application that has one
651    /// adds it with `with_typed(&Identity)`.
652    pub fn new_jsep_session_description(_identity: bool) -> Self {
653        let since_unix_epoch = SystemTime::now() // Exemption: wall-clock is correct here: RFC 8866 section 5.2 recommends a timestamp for the session version
654            .duration_since(UNIX_EPOCH)
655            .unwrap_or_else(|_| Duration::from_secs(0));
656        Self::new_jsep_session_description_with_origin(Origin::jsep(
657            new_session_id(),
658            since_unix_epoch.as_secs() + NTP_UNIX_EPOCH_OFFSET_SECS,
659        ))
660    }
661
662    /// [`new_jsep_session_description`](Self::new_jsep_session_description) with the `o=`
663    /// line the caller gives, for a session whose origin is kept across descriptions (RFC
664    /// 9429 section 5.2.2: "The fields of the "o=" line MUST stay the same except for the
665    /// <session-version> field") or drawn from sources the caller controls.
666    pub fn new_jsep_session_description_with_origin(origin: Origin) -> Self {
667        SessionDescription {
668            version: 0,
669            origin,
670            session_name: "-".to_string(),
671            session_information: None,
672            uri: None,
673            email_addresses: vec![],
674            phone_numbers: vec![],
675            connection_information: None,
676            bandwidth: vec![],
677            time_descriptions: vec![TimeDescription {
678                timing: Timing {
679                    start_time: 0,
680                    stop_time: 0,
681                },
682                repeat_times: vec![],
683                time_zones: vec![],
684            }],
685            encryption_key: None,
686            attributes: vec![],
687            media_descriptions: vec![],
688        }
689    }
690
691    /// WithPropertyAttribute adds a property attribute 'a=key' to the session description
692    pub fn with_property_attribute(mut self, key: String) -> Self {
693        self.attributes.push(Attribute::new(key, None));
694        self
695    }
696
697    /// WithValueAttribute adds a value attribute 'a=key:value' to the session description
698    pub fn with_value_attribute(mut self, key: String, value: String) -> Self {
699        self.attributes.push(Attribute::new(key, Some(value)));
700        self
701    }
702
703    /// WithFingerprint adds a fingerprint to the session description
704    pub fn with_fingerprint(self, algorithm: String, value: String) -> Self {
705        self.with_value_attribute("fingerprint".to_string(), algorithm + " " + value.as_str())
706    }
707
708    /// WithMedia adds a media description to the session description
709    pub fn with_media(mut self, md: MediaDescription) -> Self {
710        self.media_descriptions.push(md);
711        self
712    }
713
714    fn build_codec_map(&self) -> HashMap<u8, Codec> {
715        let mut codecs: HashMap<u8, Codec> = HashMap::new();
716
717        for m in &self.media_descriptions {
718            codecs.extend(m.codecs());
719        }
720
721        codecs
722    }
723
724    /// get_codec_for_payload_type scans the SessionDescription for the given payload type and returns the codec
725    pub fn get_codec_for_payload_type(&self, payload_type: u8) -> Result<Codec> {
726        let codecs = self.build_codec_map();
727
728        if let Some(codec) = codecs.get(&payload_type) {
729            Ok(codec.clone())
730        } else {
731            Err(Error::PayloadTypeNotFound)
732        }
733    }
734
735    /// get_payload_type_for_codec scans the SessionDescription for a codec that matches the provided codec
736    /// as closely as possible and returns its payload type
737    pub fn get_payload_type_for_codec(&self, wanted: &Codec) -> Result<u8> {
738        let codecs = self.build_codec_map();
739
740        for (payload_type, codec) in codecs.iter() {
741            if codecs_match(wanted, codec) {
742                return Ok(*payload_type);
743            }
744        }
745
746        Err(Error::CodecNotFound)
747    }
748
749    /// Returns whether an attribute exists
750    pub fn has_attribute(&self, key: &str) -> bool {
751        self.attributes.iter().any(|a| a.key == key)
752    }
753
754    /// Attribute returns the value of an attribute and if it exists
755    pub fn attribute(&self, key: &str) -> Option<&String> {
756        for a in &self.attributes {
757            if a.key == key {
758                return a.value.as_ref();
759            }
760        }
761        None
762    }
763
764    /// The value of the first session-level `b=` line of `kind`, in the unit of that
765    /// modifier.
766    pub fn bandwidth_of(&self, kind: BandwidthKind) -> Option<u64> {
767        find_bandwidth(&self.bandwidth, kind)
768    }
769
770    crate::attribute::common_accessors!();
771    crate::attribute::session_accessors!();
772
773    /// Marshal takes a SDP struct to text, in the order RFC 8866 section 9 gives:
774    ///
775    /// ```text
776    /// Session description
777    ///    v=  (protocol version)
778    ///    o=  (originator and session identifier)
779    ///    s=  (session name)
780    ///    i=* (session information)
781    ///    u=* (URI of description)
782    ///    e=* (zero or more email address lines)
783    ///    p=* (zero or more phone number lines)
784    ///    c=* (connection information -- not required if included in all media)
785    ///    b=* (zero or more bandwidth information lines)
786    ///    One or more time descriptions:
787    ///       t=  (time the session is active)
788    ///       r=* (zero or more repeat times)
789    ///       z=* (time zone adjustments of those repeat times)
790    ///    a=* (zero or more session attribute lines)
791    ///    Zero or more media descriptions:
792    ///       m=  (media name and transport address)
793    ///       i=* (media title)
794    ///       c=* (connection information -- optional if included at session level)
795    ///       b=* (zero or more bandwidth information lines)
796    ///       a=* (zero or more media attribute lines)
797    /// ```
798    ///
799    /// `k=` is never written (section 5.12). An empty session name is written as `s=-` and
800    /// an empty list of time descriptions as `t=0 0`, so that what comes out has the
801    /// required lines. Field values are written as they are: build them from parsed or
802    /// checked input.
803    pub fn marshal(&self) -> String {
804        self.to_string()
805    }
806
807    /// Unmarshal deserializes a session description, with [`ParseOptions::strict`]: the
808    /// RFC 8866 section 9 grammar, line by line and in its order.
809    ///
810    /// See [`ParseOptions`] for what is accepted beyond the grammar, and for what is
811    /// refused. Attribute values are kept as text: use the typed accessors
812    /// (`mid()`, `rtpmaps()`, `candidates()`, ...) or [`SessionDescription::validate`] to
813    /// check them.
814    ///
815    /// The input is bounded: [`MAX_SDP_SIZE`] bytes, [`MAX_SDP_LINES`] lines,
816    /// [`MAX_MEDIA_DESCRIPTIONS`] media descriptions, [`MAX_ATTRIBUTES_PER_SECTION`]
817    /// attributes at each level and [`MAX_FORMATS_PER_MEDIA`] formats on an `m=` line.
818    pub fn unmarshal<R: io::BufRead + io::Seek>(reader: &mut R) -> Result<Self> {
819        Self::unmarshal_with_options(reader, &ParseOptions::strict())
820    }
821
822    /// [`SessionDescription::unmarshal`] with the leniencies `options` names.
823    pub fn unmarshal_with_options<R: io::BufRead + io::Seek>(
824        reader: &mut R,
825        options: &ParseOptions,
826    ) -> Result<Self> {
827        let start = reader.stream_position()?;
828        let end = reader.seek(io::SeekFrom::End(0))?;
829        reader.seek(io::SeekFrom::Start(start))?;
830        if end.saturating_sub(start) > MAX_SDP_SIZE as u64 {
831            return Err(over_limit("bytes", MAX_SDP_SIZE));
832        }
833
834        let mut bytes = Vec::with_capacity(end.saturating_sub(start) as usize);
835        io::Read::take(&mut *reader, MAX_SDP_SIZE as u64 + 1).read_to_end(&mut bytes)?;
836        if bytes.len() > MAX_SDP_SIZE {
837            return Err(over_limit("bytes", MAX_SDP_SIZE));
838        }
839        let text = decode(&bytes)?;
840        Self::parse_with_options(&text, options)
841    }
842
843    /// The character set the session name and information are in (RFC 8866 section 6.10,
844    /// `a=charset`): UTF-8 when the description names none.
845    pub fn charset(&self) -> Charset {
846        self.attribute(ATTR_KEY_CHARSET)
847            .map_or(Charset::Utf8, |name| Charset::named(name))
848    }
849
850    /// Parses a session description from text, with the leniencies `options` names.
851    pub fn parse_with_options(text: &str, options: &ParseOptions) -> Result<Self> {
852        Self::parse_located(text, options).map_err(|err| err.error)
853    }
854
855    /// [`Self::parse_with_options`], saying which line a syntax error is on (W3C webrtc-pc
856    /// section 11.1: an `sdp-syntax-error` carries its `sdpLineNumber`).
857    ///
858    /// # Errors
859    ///
860    /// The error [`Self::parse_with_options`] returns, with the number (from 1, blank lines
861    /// counted) of the line it is about; `None` for an error about the description as a whole
862    /// (its size, or a missing `t=` line at its end).
863    pub fn parse_located(
864        text: &str,
865        options: &ParseOptions,
866    ) -> std::result::Result<Self, SdpParseError> {
867        let unlocated = |error| SdpParseError {
868            line_number: None,
869            error,
870        };
871        if text.len() > MAX_SDP_SIZE {
872            return Err(unlocated(over_limit("bytes", MAX_SDP_SIZE)));
873        }
874        let mut parser = Parser::new(*options);
875        let lines = lines_located(text, options.blank_lines, MAX_SDP_LINES).map_err(
876            |(number, error)| SdpParseError {
877                line_number: Some(number),
878                error,
879            },
880        )?;
881        for line in lines {
882            let number = line.number;
883            parser.line(line).map_err(|error| SdpParseError {
884                line_number: Some(number),
885                error,
886            })?;
887        }
888        parser.finish().map_err(unlocated)
889    }
890}
891
892/// RFC 3986 section 4.1 `URI-reference`: a URI, or a relative reference (RFC 8866 section
893/// 9 has `uri = URI-reference`). An absolute one is what the `url` crate parses; a relative
894/// one has only the characters of the grammar (unreserved, sub-delims, `:` `@` `/` `?` `#`
895/// `[` `]`, and `%` with two hex digits) and no `:` in its first segment (`path-noscheme`).
896fn is_uri_reference(value: &str) -> bool {
897    if value.is_empty() {
898        return false;
899    }
900    let bytes = value.as_bytes();
901    let mut i = 0;
902    while i < bytes.len() {
903        let b = bytes[i];
904        let ok = b.is_ascii_alphanumeric() || b"-._~!$&'()*+,;=:@/?#[]".contains(&b);
905        if b == b'%' {
906            if !bytes.get(i + 1).is_some_and(u8::is_ascii_hexdigit)
907                || !bytes.get(i + 2).is_some_and(u8::is_ascii_hexdigit)
908            {
909                return false;
910            }
911            i += 3;
912            continue;
913        }
914        if !ok {
915            return false;
916        }
917        i += 1;
918    }
919    let first_segment = value.split(['/', '?', '#']).next().unwrap_or_default();
920    match first_segment.split_once(':') {
921        // A scheme: the reference is a URI.
922        Some((scheme, _)) => {
923            scheme
924                .bytes()
925                .next()
926                .is_some_and(|b| b.is_ascii_alphabetic())
927                && scheme
928                    .bytes()
929                    .all(|b| b.is_ascii_alphanumeric() || b"+-.".contains(&b))
930                && Url::parse(value).is_ok()
931        }
932        None => true,
933    }
934}
935
936/// The `a=charset` attribute (RFC 8866 section 6.10).
937pub const ATTR_KEY_CHARSET: &str = "charset";
938
939/// The character set of a description's charset-dependent fields (`s=`, `i=`), from its
940/// `a=charset` (RFC 8866 section 6.10).
941#[derive(Debug, Clone, PartialEq, Eq)]
942pub enum Charset {
943    /// ISO-10646 in UTF-8, the default.
944    Utf8,
945    /// ISO-8859-1.
946    Latin1,
947    /// US-ASCII.
948    Ascii,
949    /// A character set this crate does not support (or not a registered one): its strings
950    /// are octet strings (RFC 8866 section 6.10: "If the identifier is not recognized or not
951    /// supported, all strings that are affected by it SHOULD be regarded as octet strings"),
952    /// each octet read as the character of that code point.
953    Other(String),
954}
955
956impl Charset {
957    /// The character set `name` identifies. RFC 8866 section 6.10: the identifier "MUST be
958    /// compared against identifiers from the 'Name' or 'Preferred MIME Name' field of the
959    /// registry using a case-insensitive comparison"; the aliases of the IANA Character Sets
960    /// registry for the three sets are recognised too.
961    pub fn named(name: &str) -> Self {
962        const UTF8: [&str; 2] = ["UTF-8", "csUTF8"];
963        const LATIN1: [&str; 10] = [
964            "ISO-8859-1",
965            "ISO_8859-1:1987",
966            "ISO_8859-1",
967            "iso-ir-100",
968            "latin1",
969            "l1",
970            "IBM819",
971            "CP819",
972            "csISOLatin1",
973            "ISO-8859-1:1987",
974        ];
975        const ASCII: [&str; 11] = [
976            "US-ASCII",
977            "ANSI_X3.4-1968",
978            "iso-ir-6",
979            "ANSI_X3.4-1986",
980            "ISO_646.irv:1991",
981            "ISO646-US",
982            "us",
983            "IBM367",
984            "cp367",
985            "csASCII",
986            "ASCII",
987        ];
988        let name = name.trim();
989        let is = |names: &[&str]| names.iter().any(|n| n.eq_ignore_ascii_case(name));
990        if is(&UTF8) {
991            Charset::Utf8
992        } else if is(&LATIN1) {
993            Charset::Latin1
994        } else if is(&ASCII) {
995            Charset::Ascii
996        } else {
997            Charset::Other(name.to_owned())
998        }
999    }
1000}
1001
1002/// The `a=charset` value of a description's session part, read from its bytes (the
1003/// attribute is ASCII, whatever set it names).
1004fn declared_charset(bytes: &[u8]) -> Option<Charset> {
1005    for line in bytes.split(|&b| b == b'\n') {
1006        let line = line.strip_suffix(b"\r").unwrap_or(line);
1007        if line.starts_with(b"m=") {
1008            return None;
1009        }
1010        if let Some(value) = line.strip_prefix(b"a=charset:") {
1011            return core::str::from_utf8(value).ok().map(Charset::named);
1012        }
1013    }
1014    None
1015}
1016
1017/// The text of a description given as bytes. RFC 8866 section 5: "the 'a=charset' attribute
1018/// ... is used to specify the character set"; without one, or with UTF-8, the text is UTF-8
1019/// and other bytes refuse it. ISO-8859-1 is decoded as such, US-ASCII must be 7-bit, and an
1020/// unsupported set's text is kept as octets (each byte the character of its code point; RFC
1021/// 8866 section 6.10). Every other field is ASCII in all of these.
1022fn decode(bytes: &[u8]) -> Result<std::borrow::Cow<'_, str>> {
1023    match declared_charset(bytes) {
1024        None | Some(Charset::Utf8) => core::str::from_utf8(bytes)
1025            .map(std::borrow::Cow::Borrowed)
1026            .map_err(|_| Error::SdpInvalidSyntax("the description is not UTF-8".to_owned())),
1027        Some(Charset::Ascii) => {
1028            if bytes.is_ascii() {
1029                Ok(std::borrow::Cow::Owned(
1030                    bytes.iter().map(|&b| char::from(b)).collect(),
1031                ))
1032            } else {
1033                Err(Error::SdpInvalidSyntax(
1034                    "a=charset:US-ASCII and a byte above 127 (RFC 8866 section 6.10)".to_owned(),
1035                ))
1036            }
1037        }
1038        Some(Charset::Latin1 | Charset::Other(_)) => Ok(std::borrow::Cow::Owned(
1039            bytes.iter().map(|&b| char::from(b)).collect(),
1040        )),
1041    }
1042}
1043
1044/// A description that does not parse, and where: what
1045/// [`SessionDescription::parse_located`] returns.
1046#[derive(Debug, PartialEq)]
1047pub struct SdpParseError {
1048    /// The line the error is about, from 1 (blank lines counted); `None` when it is about the
1049    /// description as a whole.
1050    pub line_number: Option<usize>,
1051    /// What is wrong.
1052    pub error: Error,
1053}
1054
1055impl From<SessionDescription> for String {
1056    fn from(sdp: SessionDescription) -> String {
1057        sdp.marshal()
1058    }
1059}
1060
1061impl TryFrom<String> for SessionDescription {
1062    type Error = Error;
1063    fn try_from(sdp_string: String) -> Result<Self> {
1064        SessionDescription::parse_with_options(&sdp_string, &ParseOptions::strict())
1065    }
1066}
1067
1068impl FromStr for SessionDescription {
1069    type Err = Error;
1070    fn from_str(sdp: &str) -> Result<Self> {
1071        SessionDescription::parse_with_options(sdp, &ParseOptions::strict())
1072    }
1073}
1074
1075/// Where the parser is in `v o s i u e* p* c b* (t r* z)+ k a* m*`: the rank of the
1076/// earliest line type that may still come.
1077#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
1078enum SessionRank {
1079    Version,
1080    Origin,
1081    Name,
1082    Information,
1083    Uri,
1084    Email,
1085    Phone,
1086    Connection,
1087    Bandwidth,
1088    Time,
1089    Key,
1090    Attribute,
1091}
1092
1093/// Where the parser is inside a time description.
1094#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1095enum TimeState {
1096    /// No `t=` line yet, or a line that is not part of a time description came since.
1097    Outside,
1098    /// The last line was `t=`.
1099    Timing,
1100    /// The last line was `r=`.
1101    Repeat,
1102    /// The last line was `z=`.
1103    Zone,
1104}
1105
1106/// Where the parser is in `m i c* b* k a*`.
1107#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
1108enum MediaRank {
1109    Information,
1110    Connection,
1111    Bandwidth,
1112    Key,
1113    Attribute,
1114}
1115
1116struct Parser {
1117    options: ParseOptions,
1118    desc: SessionDescription,
1119    rank: SessionRank,
1120    time: TimeState,
1121    /// `Some` once the first `m=` line was read.
1122    media: Option<MediaState>,
1123}
1124
1125struct MediaState {
1126    rank: MediaRank,
1127    has_title: bool,
1128    has_key: bool,
1129}
1130
1131fn out_of_order(kind: u8) -> Error {
1132    Error::SdpInvalidSyntax(format!(
1133        "a `{}=` line where the grammar has none",
1134        kind as char
1135    ))
1136}
1137
1138impl Parser {
1139    fn new(options: ParseOptions) -> Self {
1140        Parser {
1141            options,
1142            desc: SessionDescription::default(),
1143            rank: SessionRank::Version,
1144            time: TimeState::Outside,
1145            media: None,
1146        }
1147    }
1148
1149    fn finish(self) -> Result<SessionDescription> {
1150        // v=, o=, s= and one t= are required, in that order: a t= line means all four.
1151        if self.desc.time_descriptions.is_empty() {
1152            return Err(Error::SdpInvalidSyntax(
1153                "the description ends before its `t=` line".to_owned(),
1154            ));
1155        }
1156        Ok(self.desc)
1157    }
1158
1159    /// The fields of a structured line: separated by one space, or by any white space when
1160    /// `loose_fields` is set.
1161    fn fields<'a>(&self, what: &str, value: &'a str) -> Result<Vec<&'a str>> {
1162        if self.options.loose_fields {
1163            let fields: Vec<&str> = value.split_whitespace().collect();
1164            if fields.is_empty() {
1165                return Err(syntax(what, value));
1166            }
1167            Ok(fields)
1168        } else {
1169            grammar::fields(what, value)
1170        }
1171    }
1172
1173    fn line(&mut self, line: Line<'_>) -> Result<()> {
1174        if !matches!(
1175            line.kind,
1176            b'v' | b'o'
1177                | b's'
1178                | b'i'
1179                | b'u'
1180                | b'e'
1181                | b'p'
1182                | b'c'
1183                | b'b'
1184                | b't'
1185                | b'r'
1186                | b'z'
1187                | b'k'
1188                | b'a'
1189                | b'm'
1190        ) {
1191            // RFC 8866 section 5: a parser "MUST completely ignore or reject any session
1192            // description that contains a type letter that it does not understand".
1193            return Err(Error::SdpInvalidSyntax(format!(
1194                "unknown line type `{}=`",
1195                line.kind.escape_ascii()
1196            )));
1197        }
1198
1199        if line.kind == b'm' {
1200            // A media description may only start once the session level is complete.
1201            if self.desc.time_descriptions.is_empty() {
1202                return Err(out_of_order(line.kind));
1203            }
1204            self.media_line(line.value)?;
1205            self.media = Some(MediaState {
1206                rank: MediaRank::Information,
1207                has_title: false,
1208                has_key: false,
1209            });
1210            return Ok(());
1211        }
1212
1213        if self.media.is_some() {
1214            self.media_level(line)
1215        } else {
1216            self.session_level(line)
1217        }
1218    }
1219
1220    fn session_level(&mut self, line: Line<'_>) -> Result<()> {
1221        use SessionRank as R;
1222
1223        let value = line.value;
1224        let was_time = self.time;
1225        if !matches!(line.kind, b'r' | b'z') {
1226            self.time = TimeState::Outside;
1227        }
1228
1229        // (rank of this line, rank of the earliest line that may follow it)
1230        let (rank, next) = match line.kind {
1231            b'v' => (R::Version, R::Origin),
1232            b'o' => (R::Origin, R::Name),
1233            b's' => (R::Name, R::Information),
1234            b'i' => (R::Information, R::Uri),
1235            b'u' => (R::Uri, R::Email),
1236            b'e' => (R::Email, R::Email),
1237            b'p' => (R::Phone, R::Phone),
1238            b'c' => (R::Connection, R::Bandwidth),
1239            b'b' => (R::Bandwidth, R::Bandwidth),
1240            b't' | b'r' | b'z' => (R::Time, R::Time),
1241            b'k' => (R::Key, R::Attribute),
1242            b'a' => (R::Attribute, R::Attribute),
1243            _ => return Err(out_of_order(line.kind)),
1244        };
1245
1246        // v=, o= and s= are required and come first, in that order; a t= line is required
1247        // before anything that follows the time descriptions.
1248        let allowed = match self.rank {
1249            R::Version | R::Origin | R::Name => rank == self.rank,
1250            earliest => {
1251                rank >= earliest && (rank <= R::Time || !self.desc.time_descriptions.is_empty())
1252            }
1253        };
1254        if !allowed {
1255            return Err(out_of_order(line.kind));
1256        }
1257
1258        match line.kind {
1259            b'v' => {
1260                // `1*DIGIT`, and RFC 9429 section 5.8.1: the version is 0.
1261                if grammar::digits::<u32>("v=", value)? != 0 {
1262                    return Err(syntax("v=", value));
1263                }
1264                self.desc.version = 0;
1265            }
1266            b'o' => self.desc.origin = self.origin(value)?,
1267            b's' => {
1268                if !(grammar::is_byte_string(value)
1269                    || (value.is_empty() && self.options.loose_fields))
1270                {
1271                    return Err(syntax("s=", value));
1272                }
1273                self.desc.session_name = value.to_owned();
1274            }
1275            b'i' => self.desc.session_information = Some(self.text("i=", value)?),
1276            b'u' => {
1277                if !is_uri_reference(value) {
1278                    return Err(syntax("u=", value));
1279                }
1280                self.desc.uri = Some(value.to_owned());
1281            }
1282            b'e' => {
1283                if !self.options.loose_fields && !is_email_address(value) {
1284                    return Err(syntax("e=", value));
1285                }
1286                self.desc.email_addresses.push(value.to_owned());
1287            }
1288            b'p' => {
1289                if !self.options.loose_fields && !is_phone_number(value) {
1290                    return Err(syntax("p=", value));
1291                }
1292                self.desc.phone_numbers.push(value.to_owned());
1293            }
1294            b'c' => self.desc.connection_information = Some(self.connection(value)?),
1295            b'b' => self.desc.bandwidth.push(self.bandwidth(value)?),
1296            b't' => {
1297                let timing = self.timing(value)?;
1298                self.desc.time_descriptions.push(TimeDescription {
1299                    timing,
1300                    repeat_times: vec![],
1301                    time_zones: vec![],
1302                });
1303                self.time = TimeState::Timing;
1304            }
1305            b'r' => {
1306                if !matches!(was_time, TimeState::Timing | TimeState::Repeat) {
1307                    return Err(out_of_order(line.kind));
1308                }
1309                let repeat = self.repeat(value)?;
1310                // `was_time` is not `Outside`, so a time description exists.
1311                if let Some(last) = self.desc.time_descriptions.last_mut() {
1312                    last.repeat_times.push(repeat);
1313                }
1314                self.time = TimeState::Repeat;
1315            }
1316            b'z' => {
1317                if !matches!(was_time, TimeState::Timing | TimeState::Repeat) {
1318                    return Err(out_of_order(line.kind));
1319                }
1320                let zones = self.zones(value)?;
1321                if let Some(last) = self.desc.time_descriptions.last_mut() {
1322                    last.time_zones = zones;
1323                }
1324                self.time = TimeState::Zone;
1325            }
1326            b'k' => check_key(value)?,
1327            _ => {
1328                if self.desc.attributes.len() >= MAX_ATTRIBUTES_PER_SECTION {
1329                    return Err(over_limit("session attributes", MAX_ATTRIBUTES_PER_SECTION));
1330                }
1331                self.desc.attributes.push(parse_attribute(value)?);
1332            }
1333        }
1334
1335        self.rank = next;
1336        Ok(())
1337    }
1338
1339    fn media_level(&mut self, line: Line<'_>) -> Result<()> {
1340        use MediaRank as M;
1341
1342        let value = line.value;
1343        let (rank, next) = match line.kind {
1344            b'i' => (M::Information, M::Connection),
1345            b'c' => (M::Connection, M::Connection),
1346            b'b' => (M::Bandwidth, M::Bandwidth),
1347            b'k' => (M::Key, M::Attribute),
1348            b'a' => (M::Attribute, M::Attribute),
1349            _ => return Err(out_of_order(line.kind)),
1350        };
1351
1352        let unordered = self.options.unordered_media_lines;
1353        let Some(state) = self.media.as_mut() else {
1354            return Err(out_of_order(line.kind));
1355        };
1356        if !unordered && rank < state.rank {
1357            return Err(out_of_order(line.kind));
1358        }
1359        // One i= and one k= at most, in any mode.
1360        match line.kind {
1361            b'i' if std::mem::replace(&mut state.has_title, true) => {
1362                return Err(out_of_order(line.kind));
1363            }
1364            b'k' if std::mem::replace(&mut state.has_key, true) => {
1365                return Err(out_of_order(line.kind));
1366            }
1367            _ => {}
1368        }
1369        state.rank = state.rank.max(next);
1370
1371        match line.kind {
1372            b'i' => {
1373                let title = self.text("i=", value)?;
1374                self.last_media()?.media_title = Some(title);
1375            }
1376            b'c' => {
1377                let connection = self.connection(value)?;
1378                self.last_media()?.connection_information.push(connection);
1379            }
1380            b'b' => {
1381                let bandwidth = self.bandwidth(value)?;
1382                self.last_media()?.bandwidth.push(bandwidth);
1383            }
1384            b'k' => check_key(value)?,
1385            _ => {
1386                let attribute = parse_attribute(value)?;
1387                let media = self.last_media()?;
1388                if media.attributes.len() >= MAX_ATTRIBUTES_PER_SECTION {
1389                    return Err(over_limit(
1390                        "attributes in one media section",
1391                        MAX_ATTRIBUTES_PER_SECTION,
1392                    ));
1393                }
1394                media.attributes.push(attribute);
1395            }
1396        }
1397        Ok(())
1398    }
1399
1400    fn last_media(&mut self) -> Result<&mut MediaDescription> {
1401        self.desc
1402            .media_descriptions
1403            .last_mut()
1404            .ok_or(Error::SdpEmptyTimeDescription)
1405    }
1406
1407    /// `text = byte-string`.
1408    fn text(&self, what: &str, value: &str) -> Result<String> {
1409        if !(grammar::is_byte_string(value) || self.options.loose_fields) {
1410            return Err(syntax(what, value));
1411        }
1412        Ok(value.to_owned())
1413    }
1414
1415    /// `username SP sess-id SP sess-version SP nettype SP addrtype SP unicast-address`.
1416    fn origin(&self, value: &str) -> Result<Origin> {
1417        let fields = self.fields("o=", value)?;
1418        let [
1419            username,
1420            session_id,
1421            session_version,
1422            network_type,
1423            address_type,
1424            address,
1425        ] = fields[..]
1426        else {
1427            return Err(syntax("o=", value));
1428        };
1429        if !grammar::is_non_ws_string(username)
1430            || !grammar::is_token(network_type)
1431            || !grammar::is_token(address_type)
1432        {
1433            return Err(syntax("o=", value));
1434        }
1435        let address_ok = if self.options.loose_fields {
1436            grammar::is_non_ws_string(address)
1437        } else {
1438            grammar::is_unicast_address(address_type, address)
1439        };
1440        if !address_ok {
1441            return Err(syntax("o= unicast-address", value));
1442        }
1443        Ok(Origin {
1444            username: username.to_owned(),
1445            // The grammar has no upper bound (RFC 8866 section 9: `1*DIGIT`), and nor has
1446            // this type: RFC 9429 section 5.8 accepts compliant SDP beyond the 64 bits
1447            // section 5.2.1 generates.
1448            session_id: SdpDecimal::parse(session_id)
1449                .ok_or_else(|| syntax("o= sess-id", session_id))?,
1450            session_version: SdpDecimal::parse(session_version)
1451                .ok_or_else(|| syntax("o= sess-version", session_version))?,
1452            network_type: network_type.to_owned(),
1453            address_type: address_type.to_owned(),
1454            unicast_address: address.to_owned(),
1455        })
1456    }
1457
1458    fn connection(&self, value: &str) -> Result<ConnectionInformation> {
1459        let fields = self.fields("c=", value)?;
1460        if !self.options.loose_fields {
1461            return ConnectionInformation::parse_fields(&fields, value);
1462        }
1463        if !(2..=3).contains(&fields.len())
1464            || !grammar::is_token(fields[0])
1465            || !grammar::is_token(fields[1])
1466        {
1467            return Err(syntax("c=", value));
1468        }
1469        Ok(ConnectionInformation {
1470            network_type: fields[0].to_owned(),
1471            address_type: fields[1].to_owned(),
1472            address: fields.get(2).map(|address| {
1473                // Kept whole when it is not an address the grammar knows.
1474                Address::parse(fields[1], address).unwrap_or_else(|_| Address {
1475                    address: (*address).to_owned(),
1476                    ttl: None,
1477                    range: None,
1478                })
1479            }),
1480        })
1481    }
1482
1483    fn bandwidth(&self, value: &str) -> Result<Bandwidth> {
1484        if self.options.loose_fields {
1485            Bandwidth::parse(value.trim())
1486        } else {
1487            Bandwidth::parse(value)
1488        }
1489    }
1490
1491    /// `start-time SP stop-time`, each `time / "0"`, `time = POS-DIGIT 9*DIGIT`.
1492    fn timing(&self, value: &str) -> Result<Timing> {
1493        let fields = self.fields("t=", value)?;
1494        let loose = self.options.loose_fields;
1495        if fields.len() < 2 || (fields.len() > 2 && !loose) {
1496            return Err(syntax("t=", value));
1497        }
1498        let time = |field: &str| -> Result<u64> {
1499            if !(loose || field == "0" || (grammar::is_integer(field) && field.len() >= 10)) {
1500                return Err(syntax("t=", value));
1501            }
1502            grammar::digits("t=", field)
1503        };
1504        Ok(Timing {
1505            start_time: time(fields[0])?,
1506            stop_time: time(fields[1])?,
1507        })
1508    }
1509
1510    /// `repeat-interval SP typed-time 1*(SP typed-time)`.
1511    fn repeat(&self, value: &str) -> Result<RepeatTime> {
1512        let fields = self.fields("r=", value)?;
1513        if fields.len() < 3 {
1514            return Err(syntax("r=", value));
1515        }
1516        // repeat-interval = POS-DIGIT *DIGIT [fixed-len-time-unit]
1517        if fields[0].starts_with('0') {
1518            return Err(syntax("r= repeat-interval", value));
1519        }
1520        let interval = parse_typed_time(fields[0])?;
1521        let duration = parse_typed_time(fields[1])?;
1522        let mut offsets = Vec::with_capacity(fields.len() - 2);
1523        for field in &fields[2..] {
1524            offsets.push(parse_typed_time(field)?);
1525        }
1526        Ok(RepeatTime {
1527            interval,
1528            duration,
1529            offsets,
1530        })
1531    }
1532
1533    /// `time SP ["-"] typed-time *(SP time SP ["-"] typed-time)`.
1534    fn zones(&self, value: &str) -> Result<Vec<TimeZone>> {
1535        let fields = self.fields("z=", value)?;
1536        if !fields.len().is_multiple_of(2) {
1537            return Err(syntax("z=", value));
1538        }
1539        let mut zones = Vec::with_capacity(fields.len() / 2);
1540        for pair in fields.chunks(2) {
1541            let time = pair[0];
1542            if !(self.options.loose_fields || (grammar::is_integer(time) && time.len() >= 10)) {
1543                return Err(syntax("z= adjustment time", value));
1544            }
1545            let adjustment_time = grammar::digits("z= adjustment time", time)?;
1546            let offset = match pair[1].strip_prefix('-') {
1547                Some(positive) => parse_typed_time(positive)?
1548                    .checked_neg()
1549                    .ok_or_else(|| invalid("z= offset", value))?,
1550                None => parse_typed_time(pair[1])?,
1551            };
1552            zones.push(TimeZone {
1553                adjustment_time,
1554                offset,
1555            });
1556        }
1557        Ok(zones)
1558    }
1559
1560    /// `media SP port ["/" integer] SP proto 1*(SP fmt)`.
1561    fn media_line(&mut self, value: &str) -> Result<()> {
1562        if self.desc.media_descriptions.len() >= MAX_MEDIA_DESCRIPTIONS {
1563            return Err(over_limit("media sections", MAX_MEDIA_DESCRIPTIONS));
1564        }
1565
1566        let fields = self.fields("m=", value)?;
1567        if fields.len() < 4 {
1568            return Err(syntax("m=", value));
1569        }
1570        if fields.len() - 3 > MAX_FORMATS_PER_MEDIA {
1571            return Err(over_limit("formats on one m= line", MAX_FORMATS_PER_MEDIA));
1572        }
1573
1574        // <media>
1575        // RFC 8866 section 5.14: <media> is a token ("audio", "video", "text",
1576        // "application", "message", "image" are registered, and new media types
1577        // may be), so an unknown one is parsed: it is the offer/answer layer that
1578        // rejects a media type it doesn't know (RFC 9429 section 5.3.1 answers
1579        // it with port 0), not the parser.
1580        if !grammar::is_token(fields[0]) {
1581            return Err(Error::SdpInvalidValue(fields[0].to_owned()));
1582        }
1583
1584        // <port> ["/" integer]
1585        let (port, count) = match fields[1].split_once('/') {
1586            Some((port, count)) => (port, Some(count)),
1587            None => (fields[1], None),
1588        };
1589        let port_value = grammar::port(port)? as isize;
1590        let port_range = match count {
1591            Some(count) => {
1592                if !grammar::is_integer(count) {
1593                    return Err(syntax("m= number of ports", value));
1594                }
1595                Some(
1596                    count
1597                        .parse::<u16>()
1598                        .map_err(|_| invalid("m= number of ports", value))?
1599                        as isize,
1600                )
1601            }
1602            None => None,
1603        };
1604
1605        // <proto>
1606        // RFC 8866 section 5.14: <proto> is the media transport protocol and is
1607        // extensible -- "New transport protocols MAY be defined, and MUST be
1608        // registered with IANA." Any `token *("/" token)` is accepted instead of a fixed
1609        // list, so IANA-registered transports beyond the RTP/SAVPF set interoperate, e.g.
1610        // UDP/BFCP (RFC 8856), TCP/DTLS/SCTP (RFC 8841) or TCP/MRCPv2.
1611        let mut protos = vec![];
1612        for proto in fields[2].split('/') {
1613            if !grammar::is_token(proto) {
1614                return Err(Error::SdpInvalidValue(fields[2].to_owned()));
1615            }
1616            protos.push(proto.to_owned());
1617        }
1618
1619        // <fmt>...
1620        let mut formats = Vec::with_capacity(fields.len() - 3);
1621        for field in &fields[3..] {
1622            if !grammar::is_token(field) {
1623                return Err(syntax("m= fmt", value));
1624            }
1625            formats.push((*field).to_owned());
1626        }
1627
1628        self.desc.media_descriptions.push(MediaDescription {
1629            media_name: MediaName {
1630                media: fields[0].to_owned(),
1631                port: RangedPort {
1632                    value: port_value,
1633                    range: port_range,
1634                },
1635                protos,
1636                formats,
1637            },
1638            media_title: None,
1639            connection_information: vec![],
1640            bandwidth: vec![],
1641            encryption_key: None,
1642            attributes: vec![],
1643        });
1644        Ok(())
1645    }
1646}
1647
1648/// `attribute = (attribute-name ":" attribute-value) / attribute-name`, the name a token.
1649///
1650/// The value starts after the first colon and is kept whole.
1651pub(crate) fn parse_attribute(value: &str) -> Result<Attribute> {
1652    let (key, value) = match value.split_once(':') {
1653        Some((key, value)) => (key, Some(value)),
1654        None => (value, None),
1655    };
1656    if !grammar::is_token(key) {
1657        return Err(syntax("attribute name", key));
1658    }
1659    Ok(Attribute {
1660        key: key.to_owned(),
1661        value: value.map(str::to_owned),
1662    })
1663}
1664
1665/// `key-type = "prompt" / "clear:" text / "base64:" base64 / "uri:" uri`. The line is
1666/// obsolete and its content is not kept (RFC 8866 section 5.12).
1667fn check_key(value: &str) -> Result<()> {
1668    let ok = if value == "prompt" {
1669        true
1670    } else if let Some(text) = value.strip_prefix("clear:") {
1671        grammar::is_byte_string(text)
1672    } else if let Some(key) = value.strip_prefix("base64:") {
1673        grammar::is_base64(key)
1674    } else if let Some(uri) = value.strip_prefix("uri:") {
1675        grammar::is_non_ws_string(uri)
1676    } else {
1677        false
1678    };
1679    if ok {
1680        Ok(())
1681    } else {
1682        // The key is not quoted in the error: it may be one.
1683        Err(Error::SdpInvalidSyntax("k= line".to_owned()))
1684    }
1685}
1686
1687/// `email-safe`: any byte except NUL, CR, LF and the quoting characters `()<>`.
1688fn is_email_safe(value: &str) -> bool {
1689    !value.is_empty()
1690        && !value
1691            .bytes()
1692            .any(|b| matches!(b, 0 | b'\r' | b'\n' | b'(' | b')' | b'<' | b'>'))
1693}
1694
1695/// RFC 5322 `atext`.
1696fn is_atext(b: u8) -> bool {
1697    b.is_ascii_alphanumeric() || b"!#$%&'*+-/=?^_`{|}~".contains(&b)
1698}
1699
1700/// RFC 5322 `dot-atom-text = 1*atext *("." 1*atext)`.
1701fn is_dot_atom(value: &str) -> bool {
1702    !value.is_empty()
1703        && value
1704            .split('.')
1705            .all(|atom| !atom.is_empty() && atom.bytes().all(is_atext))
1706}
1707
1708/// RFC 5322 `addr-spec = local-part "@" domain`, without comments, folding white space or
1709/// the obsolete forms: the local part is a dot-atom or a quoted string, the domain a
1710/// dot-atom or a domain literal.
1711fn is_addr_spec(value: &str) -> bool {
1712    let bytes = value.as_bytes();
1713    let at = if bytes.first() == Some(&b'"') {
1714        // quoted-string: DQUOTE *(qtext / quoted-pair / WSP) DQUOTE
1715        let mut i = 1;
1716        loop {
1717            match bytes.get(i) {
1718                Some(b'"') => break i + 1,
1719                Some(b'\\') if matches!(bytes.get(i + 1), Some(0x20..=0x7e | b'\t')) => i += 2,
1720                Some(b' ' | b'\t' | 0x21 | 0x23..=0x5b | 0x5d..=0x7e) => i += 1,
1721                _ => return false,
1722            }
1723        }
1724    } else {
1725        match value.find('@') {
1726            Some(at) if is_dot_atom(&value[..at]) => at,
1727            _ => return false,
1728        }
1729    };
1730    if bytes.get(at) != Some(&b'@') {
1731        return false;
1732    }
1733    let domain = &value[at + 1..];
1734    match domain.strip_prefix('[').and_then(|d| d.strip_suffix(']')) {
1735        // domain-literal: "[" *dtext "]"
1736        Some(literal) => literal
1737            .bytes()
1738            .all(|b| matches!(b, 0x21..=0x5a | 0x5e..=0x7e)),
1739        None => is_dot_atom(domain),
1740    }
1741}
1742
1743/// `email-address = address-and-comment / dispname-and-address / addr-spec`.
1744fn is_email_address(value: &str) -> bool {
1745    if let Some(rest) = value.strip_suffix(')') {
1746        // addr-spec 1*SP "(" 1*email-safe ")"
1747        let Some((address, comment)) = rest.split_once('(') else {
1748            return false;
1749        };
1750        let spec = address.trim_end_matches(' ');
1751        return spec.len() < address.len() && is_addr_spec(spec) && is_email_safe(comment);
1752    }
1753    if let Some(rest) = value.strip_suffix('>') {
1754        // 1*email-safe 1*SP "<" addr-spec ">"
1755        let Some((name, address)) = rest.split_once('<') else {
1756            return false;
1757        };
1758        return name.ends_with(' ')
1759            && is_email_safe(name.trim_end_matches(' '))
1760            && is_addr_spec(address);
1761    }
1762    is_addr_spec(value)
1763}
1764
1765/// `phone = ["+"] DIGIT 1*(SP / "-" / DIGIT)`.
1766fn is_phone(value: &str) -> bool {
1767    let digits = value.strip_prefix('+').unwrap_or(value).as_bytes();
1768    digits.len() >= 2
1769        && digits[0].is_ascii_digit()
1770        && digits[1..]
1771            .iter()
1772            .all(|b| b.is_ascii_digit() || *b == b' ' || *b == b'-')
1773}
1774
1775/// `phone-number = phone *SP "(" 1*email-safe ")" / 1*email-safe "<" phone ">" / phone`.
1776fn is_phone_number(value: &str) -> bool {
1777    if let Some(rest) = value.strip_suffix(')') {
1778        let Some((phone, comment)) = rest.split_once('(') else {
1779            return false;
1780        };
1781        // `phone` itself may end in spaces: `*SP` adds nothing to check.
1782        return is_phone(phone) && is_email_safe(comment);
1783    }
1784    if let Some(rest) = value.strip_suffix('>') {
1785        let Some((name, phone)) = rest.split_once('<') else {
1786            return false;
1787        };
1788        return is_email_safe(name) && is_phone(phone);
1789    }
1790    is_phone(value)
1791}
1792
1793/// `typed-time = 1*DIGIT [fixed-len-time-unit]`, in seconds.
1794///
1795/// The units are `d`, `h`, `m` and `s`, case-sensitive.
1796fn parse_typed_time(value: &str) -> Result<i64> {
1797    let (number, factor) = match value.as_bytes().last() {
1798        Some(b'd') => (&value[..value.len() - 1], 86400),
1799        Some(b'h') => (&value[..value.len() - 1], 3600),
1800        Some(b'm') => (&value[..value.len() - 1], 60),
1801        Some(b's') => (&value[..value.len() - 1], 1),
1802        _ => (value, 1),
1803    };
1804    grammar::digits::<i64>("typed-time", number)?
1805        .checked_mul(factor)
1806        .ok_or_else(|| invalid("typed-time", value))
1807}