1use 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
29pub const ATTR_KEY_CANDIDATE: &str = "candidate";
31pub const ATTR_KEY_END_OF_CANDIDATES: &str = "end-of-candidates";
33pub const ATTR_KEY_IDENTITY: &str = "identity";
35pub const ATTR_KEY_GROUP: &str = "group";
37pub const ATTR_KEY_SSRC: &str = "ssrc";
39pub const ATTR_KEY_SSRC_GROUP: &str = "ssrc-group";
41pub const ATTR_KEY_MSID: &str = "msid";
43pub const ATTR_KEY_MSID_SEMANTIC: &str = "msid-semantic";
45pub const ATTR_KEY_CONNECTION_SETUP: &str = "setup";
47pub const ATTR_KEY_MID: &str = "mid";
49pub const ATTR_KEY_ICELITE: &str = "ice-lite";
51pub const ATTR_KEY_RTCPMUX: &str = "rtcp-mux";
53pub const ATTR_KEY_RTCPRSIZE: &str = "rtcp-rsize";
55pub const ATTR_KEY_INACTIVE: &str = "inactive";
57pub const ATTR_KEY_RECV_ONLY: &str = "recvonly";
59pub const ATTR_KEY_SEND_ONLY: &str = "sendonly";
61pub const ATTR_KEY_SEND_RECV: &str = "sendrecv";
63pub const ATTR_KEY_EXT_MAP: &str = "extmap";
65pub const ATTR_KEY_EXTMAP_ALLOW_MIXED: &str = "extmap-allow-mixed";
67pub const ATTR_KEY_MAX_MESSAGE_SIZE: &str = "max-message-size";
69pub const ATTR_KEY_RTCPMUX_ONLY: &str = "rtcp-mux-only";
71pub const ATTR_KEY_RTCP: &str = "rtcp";
73pub const ATTR_KEY_RTCP_FB: &str = "rtcp-fb";
75pub const ATTR_KEY_RTCP_XR: &str = "rtcp-xr";
77pub const ATTR_KEY_RTPMAP: &str = "rtpmap";
79pub const ATTR_KEY_FMTP: &str = "fmtp";
81pub const ATTR_KEY_PTIME: &str = "ptime";
83pub const ATTR_KEY_MAXPTIME: &str = "maxptime";
85pub const ATTR_KEY_FRAMERATE: &str = "framerate";
87pub const ATTR_KEY_IMAGEATTR: &str = "imageattr";
89pub const ATTR_KEY_CONTENT: &str = "content";
91pub const ATTR_KEY_RID: &str = "rid";
93pub const ATTR_KEY_SIMULCAST: &str = "simulcast";
95pub const ATTR_KEY_ICE_UFRAG: &str = "ice-ufrag";
97pub const ATTR_KEY_ICE_PWD: &str = "ice-pwd";
99pub const ATTR_KEY_ICE_OPTIONS: &str = "ice-options";
101pub const ATTR_KEY_ICE_PACING: &str = "ice-pacing";
103pub const ATTR_KEY_REMOTE_CANDIDATES: &str = "remote-candidates";
105pub const ATTR_KEY_FINGERPRINT: &str = "fingerprint";
107pub const ATTR_KEY_TLS_ID: &str = "tls-id";
109pub const ATTR_KEY_SCTP_PORT: &str = "sctp-port";
111pub const ATTR_KEY_SCTPMAP: &str = "sctpmap";
114pub const ATTR_KEY_BUNDLE_ONLY: &str = "bundle-only";
116pub const ATTR_KEY_CRYPTEX: &str = "cryptex";
118pub const SEMANTIC_TOKEN_BUNDLE: &str = "BUNDLE";
120
121pub const SEMANTIC_TOKEN_LIP_SYNCHRONIZATION: &str = "LS";
123pub const SEMANTIC_TOKEN_FLOW_IDENTIFICATION: &str = "FID";
125pub const SEMANTIC_TOKEN_FORWARD_ERROR_CORRECTION: &str = "FEC";
127pub const SEMANTIC_TOKEN_FORWARD_ERROR_CORRECTION_FRAMEWORK: &str = "FEC-FR";
130pub const SEMANTIC_TOKEN_WEBRTC_MEDIA_STREAMS: &str = "WMS";
132
133pub const MAX_SDP_SIZE: usize = 1 << 20;
136pub const MAX_SDP_LINES: usize = 65_536;
138pub const MAX_MEDIA_DESCRIPTIONS: usize = 1024;
140pub const MAX_ATTRIBUTES_PER_SECTION: usize = 4096;
143pub 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
151pub type Version = isize;
154
155#[derive(Debug, Clone)]
164pub struct SdpDecimal(String);
165
166impl SdpDecimal {
167 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 pub fn as_str(&self) -> &str {
175 &self.0
176 }
177
178 pub fn to_u64(&self) -> Option<u64> {
180 self.0.parse().ok()
181 }
182
183 fn significant(&self) -> &str {
185 let trimmed = self.0.trim_start_matches('0');
186 if trimmed.is_empty() { "0" } else { trimmed }
187 }
188
189 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#[derive(Debug, Default, Clone)]
273pub struct Origin {
274 pub username: String,
276 pub session_id: SdpDecimal,
278 pub session_version: SdpDecimal,
281 pub network_type: String,
283 pub address_type: String,
285 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
304pub const NTP_UNIX_EPOCH_OFFSET_SECS: u64 = 2_208_988_800;
308
309impl Origin {
310 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 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
336pub type SessionName = String;
339
340pub type EmailAddress = String;
344
345pub type PhoneNumber = String;
349
350#[derive(Debug, Default, Clone, PartialEq, Eq)]
353pub struct TimeZone {
354 pub adjustment_time: u64,
356 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#[derive(Debug, Default, Clone)]
373pub struct TimeDescription {
374 pub timing: Timing,
378
379 pub repeat_times: Vec<RepeatTime>,
383
384 pub time_zones: Vec<TimeZone>,
391}
392
393#[derive(Debug, Default, Clone, PartialEq, Eq)]
396pub struct Timing {
397 pub start_time: u64,
399 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#[derive(Debug, Default, Clone, PartialEq, Eq)]
412pub struct RepeatTime {
413 pub interval: i64,
415 pub duration: i64,
417 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#[derive(Debug, Default, Clone)]
435pub struct SessionDescription {
436 pub version: Version,
440
441 pub origin: Origin,
445
446 pub session_name: SessionName,
452
453 pub session_information: Option<Information>,
457
458 pub uri: Option<String>,
463
464 pub email_addresses: Vec<EmailAddress>,
468
469 pub phone_numbers: Vec<PhoneNumber>,
473
474 pub connection_information: Option<ConnectionInformation>,
478
479 pub bandwidth: Vec<Bandwidth>,
483
484 pub time_descriptions: Vec<TimeDescription>,
489
490 pub encryption_key: Option<EncryptionKey>,
494
495 pub attributes: Vec<Attribute>,
501
502 pub media_descriptions: Vec<MediaDescription>,
504}
505
506impl 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 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 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
608pub struct ParseOptions {
609 pub blank_lines: bool,
611 pub unordered_media_lines: bool,
614 pub loose_fields: bool,
620}
621
622impl ParseOptions {
623 pub const fn strict() -> Self {
625 ParseOptions {
626 blank_lines: false,
627 unordered_media_lines: false,
628 loose_fields: false,
629 }
630 }
631
632 pub const fn lenient() -> Self {
634 ParseOptions {
635 blank_lines: true,
636 unordered_media_lines: true,
637 loose_fields: true,
638 }
639 }
640}
641
642impl SessionDescription {
644 pub fn new_jsep_session_description(_identity: bool) -> Self {
653 let since_unix_epoch = SystemTime::now() .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 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 pub fn with_property_attribute(mut self, key: String) -> Self {
693 self.attributes.push(Attribute::new(key, None));
694 self
695 }
696
697 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 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 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 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 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 pub fn has_attribute(&self, key: &str) -> bool {
751 self.attributes.iter().any(|a| a.key == key)
752 }
753
754 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 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 pub fn marshal(&self) -> String {
804 self.to_string()
805 }
806
807 pub fn marshal_bytes(&self) -> Result<Vec<u8>> {
822 let text = self.marshal();
823 let charset = declared_charset(text.as_bytes()).unwrap_or(Charset::Utf8);
824 let bytes = encode(&text, &charset)?;
825 let read_as = declared_charset(&bytes).unwrap_or(Charset::Utf8);
828 if std::mem::discriminant(&read_as) != std::mem::discriminant(&charset) {
829 return Err(Error::SdpInvalidValue(format!(
830 "a=charset:{charset:?} cannot be written so that it still names that set"
831 )));
832 }
833 Ok(bytes)
834 }
835
836 pub fn unmarshal<R: io::BufRead + io::Seek>(reader: &mut R) -> Result<Self> {
848 Self::unmarshal_with_options(reader, &ParseOptions::strict())
849 }
850
851 pub fn unmarshal_with_options<R: io::BufRead + io::Seek>(
853 reader: &mut R,
854 options: &ParseOptions,
855 ) -> Result<Self> {
856 let start = reader.stream_position()?;
857 let end = reader.seek(io::SeekFrom::End(0))?;
858 reader.seek(io::SeekFrom::Start(start))?;
859 if end.saturating_sub(start) > MAX_SDP_SIZE as u64 {
860 return Err(over_limit("bytes", MAX_SDP_SIZE));
861 }
862
863 let mut bytes = Vec::with_capacity(end.saturating_sub(start) as usize);
864 io::Read::take(&mut *reader, MAX_SDP_SIZE as u64 + 1).read_to_end(&mut bytes)?;
865 if bytes.len() > MAX_SDP_SIZE {
866 return Err(over_limit("bytes", MAX_SDP_SIZE));
867 }
868 let text = decode(&bytes)?;
869 Self::parse_with_options(&text, options)
870 }
871
872 pub fn charset(&self) -> Charset {
875 self.attribute(ATTR_KEY_CHARSET)
876 .map_or(Charset::Utf8, |name| Charset::named(name))
877 }
878
879 pub fn parse_with_options(text: &str, options: &ParseOptions) -> Result<Self> {
881 Self::parse_located(text, options).map_err(|err| err.error)
882 }
883
884 pub fn parse_located(
893 text: &str,
894 options: &ParseOptions,
895 ) -> std::result::Result<Self, SdpParseError> {
896 let unlocated = |error| SdpParseError {
897 line_number: None,
898 error,
899 };
900 if text.len() > MAX_SDP_SIZE {
901 return Err(unlocated(over_limit("bytes", MAX_SDP_SIZE)));
902 }
903 let mut parser = Parser::new(*options);
904 let lines = lines_located(text, options.blank_lines, MAX_SDP_LINES).map_err(
905 |(number, error)| SdpParseError {
906 line_number: Some(number),
907 error,
908 },
909 )?;
910 for line in lines {
911 let number = line.number;
912 parser.line(line).map_err(|error| SdpParseError {
913 line_number: Some(number),
914 error,
915 })?;
916 }
917 parser.finish().map_err(unlocated)
918 }
919}
920
921fn is_uri_reference(value: &str) -> bool {
926 if value.is_empty() {
927 return false;
928 }
929 let bytes = value.as_bytes();
930 let mut i = 0;
931 while i < bytes.len() {
932 let b = bytes[i];
933 let ok = b.is_ascii_alphanumeric() || b"-._~!$&'()*+,;=:@/?#[]".contains(&b);
934 if b == b'%' {
935 if !bytes.get(i + 1).is_some_and(u8::is_ascii_hexdigit)
936 || !bytes.get(i + 2).is_some_and(u8::is_ascii_hexdigit)
937 {
938 return false;
939 }
940 i += 3;
941 continue;
942 }
943 if !ok {
944 return false;
945 }
946 i += 1;
947 }
948 let first_segment = value.split(['/', '?', '#']).next().unwrap_or_default();
949 match first_segment.split_once(':') {
950 Some((scheme, _)) => {
952 scheme
953 .bytes()
954 .next()
955 .is_some_and(|b| b.is_ascii_alphabetic())
956 && scheme
957 .bytes()
958 .all(|b| b.is_ascii_alphanumeric() || b"+-.".contains(&b))
959 && Url::parse(value).is_ok()
960 }
961 None => true,
962 }
963}
964
965pub const ATTR_KEY_CHARSET: &str = "charset";
967
968#[derive(Debug, Clone, PartialEq, Eq)]
971pub enum Charset {
972 Utf8,
974 Latin1,
976 Ascii,
978 Other(String),
983}
984
985impl Charset {
986 pub fn named(name: &str) -> Self {
991 const UTF8: [&str; 2] = ["UTF-8", "csUTF8"];
992 const LATIN1: [&str; 10] = [
993 "ISO-8859-1",
994 "ISO_8859-1:1987",
995 "ISO_8859-1",
996 "iso-ir-100",
997 "latin1",
998 "l1",
999 "IBM819",
1000 "CP819",
1001 "csISOLatin1",
1002 "ISO-8859-1:1987",
1003 ];
1004 const ASCII: [&str; 11] = [
1005 "US-ASCII",
1006 "ANSI_X3.4-1968",
1007 "iso-ir-6",
1008 "ANSI_X3.4-1986",
1009 "ISO_646.irv:1991",
1010 "ISO646-US",
1011 "us",
1012 "IBM367",
1013 "cp367",
1014 "csASCII",
1015 "ASCII",
1016 ];
1017 let name = name.trim();
1018 let is = |names: &[&str]| names.iter().any(|n| n.eq_ignore_ascii_case(name));
1019 if is(&UTF8) {
1020 Charset::Utf8
1021 } else if is(&LATIN1) {
1022 Charset::Latin1
1023 } else if is(&ASCII) {
1024 Charset::Ascii
1025 } else {
1026 Charset::Other(name.to_owned())
1027 }
1028 }
1029}
1030
1031fn declared_charset(bytes: &[u8]) -> Option<Charset> {
1034 for line in bytes.split(|&b| b == b'\n') {
1035 let line = line.strip_suffix(b"\r").unwrap_or(line);
1036 if line.starts_with(b"m=") {
1037 return None;
1038 }
1039 if let Some(value) = line.strip_prefix(b"a=charset:") {
1040 return core::str::from_utf8(value).ok().map(Charset::named);
1041 }
1042 }
1043 None
1044}
1045
1046fn decode(bytes: &[u8]) -> Result<std::borrow::Cow<'_, str>> {
1052 match declared_charset(bytes) {
1053 None | Some(Charset::Utf8) => core::str::from_utf8(bytes)
1054 .map(std::borrow::Cow::Borrowed)
1055 .map_err(|_| Error::SdpInvalidSyntax("the description is not UTF-8".to_owned())),
1056 Some(Charset::Ascii) => {
1057 if bytes.is_ascii() {
1058 Ok(std::borrow::Cow::Owned(
1059 bytes.iter().map(|&b| char::from(b)).collect(),
1060 ))
1061 } else {
1062 Err(Error::SdpInvalidSyntax(
1063 "a=charset:US-ASCII and a byte above 127 (RFC 8866 section 6.10)".to_owned(),
1064 ))
1065 }
1066 }
1067 Some(Charset::Latin1 | Charset::Other(_)) => Ok(std::borrow::Cow::Owned(
1068 bytes.iter().map(|&b| char::from(b)).collect(),
1069 )),
1070 }
1071}
1072
1073fn encode(text: &str, charset: &Charset) -> Result<Vec<u8>> {
1075 let limit = match charset {
1076 Charset::Utf8 => return Ok(text.as_bytes().to_vec()),
1077 Charset::Ascii => 0x7f,
1078 Charset::Latin1 | Charset::Other(_) => 0xff,
1079 };
1080 text.chars()
1081 .map(|c| {
1082 u8::try_from(u32::from(c))
1083 .ok()
1084 .filter(|&b| u32::from(b) <= limit)
1085 .ok_or_else(|| {
1086 Error::SdpInvalidValue(format!(
1087 "{c:?} cannot be written in a=charset {charset:?} (RFC 8866 section 6.10)"
1088 ))
1089 })
1090 })
1091 .collect()
1092}
1093
1094#[derive(Debug, PartialEq)]
1097pub struct SdpParseError {
1098 pub line_number: Option<usize>,
1101 pub error: Error,
1103}
1104
1105impl From<SessionDescription> for String {
1106 fn from(sdp: SessionDescription) -> String {
1107 sdp.marshal()
1108 }
1109}
1110
1111impl TryFrom<String> for SessionDescription {
1112 type Error = Error;
1113 fn try_from(sdp_string: String) -> Result<Self> {
1114 SessionDescription::parse_with_options(&sdp_string, &ParseOptions::strict())
1115 }
1116}
1117
1118impl FromStr for SessionDescription {
1119 type Err = Error;
1120 fn from_str(sdp: &str) -> Result<Self> {
1121 SessionDescription::parse_with_options(sdp, &ParseOptions::strict())
1122 }
1123}
1124
1125#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
1128enum SessionRank {
1129 Version,
1130 Origin,
1131 Name,
1132 Information,
1133 Uri,
1134 Email,
1135 Phone,
1136 Connection,
1137 Bandwidth,
1138 Time,
1139 Key,
1140 Attribute,
1141}
1142
1143#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1145enum TimeState {
1146 Outside,
1148 Timing,
1150 Repeat,
1152 Zone,
1154}
1155
1156#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
1158enum MediaRank {
1159 Information,
1160 Connection,
1161 Bandwidth,
1162 Key,
1163 Attribute,
1164}
1165
1166struct Parser {
1167 options: ParseOptions,
1168 desc: SessionDescription,
1169 rank: SessionRank,
1170 time: TimeState,
1171 media: Option<MediaState>,
1173}
1174
1175struct MediaState {
1176 rank: MediaRank,
1177 has_title: bool,
1178 has_key: bool,
1179}
1180
1181fn out_of_order(kind: u8) -> Error {
1182 Error::SdpInvalidSyntax(format!(
1183 "a `{}=` line where the grammar has none",
1184 kind as char
1185 ))
1186}
1187
1188impl Parser {
1189 fn new(options: ParseOptions) -> Self {
1190 Parser {
1191 options,
1192 desc: SessionDescription::default(),
1193 rank: SessionRank::Version,
1194 time: TimeState::Outside,
1195 media: None,
1196 }
1197 }
1198
1199 fn finish(self) -> Result<SessionDescription> {
1200 if self.desc.time_descriptions.is_empty() {
1202 return Err(Error::SdpInvalidSyntax(
1203 "the description ends before its `t=` line".to_owned(),
1204 ));
1205 }
1206 Ok(self.desc)
1207 }
1208
1209 fn fields<'a>(&self, what: &str, value: &'a str) -> Result<Vec<&'a str>> {
1212 if self.options.loose_fields {
1213 let fields: Vec<&str> = value.split_whitespace().collect();
1214 if fields.is_empty() {
1215 return Err(syntax(what, value));
1216 }
1217 Ok(fields)
1218 } else {
1219 grammar::fields(what, value)
1220 }
1221 }
1222
1223 fn line(&mut self, line: Line<'_>) -> Result<()> {
1224 if !matches!(
1225 line.kind,
1226 b'v' | b'o'
1227 | b's'
1228 | b'i'
1229 | b'u'
1230 | b'e'
1231 | b'p'
1232 | b'c'
1233 | b'b'
1234 | b't'
1235 | b'r'
1236 | b'z'
1237 | b'k'
1238 | b'a'
1239 | b'm'
1240 ) {
1241 return Err(Error::SdpInvalidSyntax(format!(
1244 "unknown line type `{}=`",
1245 line.kind.escape_ascii()
1246 )));
1247 }
1248
1249 if line.kind == b'm' {
1250 if self.desc.time_descriptions.is_empty() {
1252 return Err(out_of_order(line.kind));
1253 }
1254 self.media_line(line.value)?;
1255 self.media = Some(MediaState {
1256 rank: MediaRank::Information,
1257 has_title: false,
1258 has_key: false,
1259 });
1260 return Ok(());
1261 }
1262
1263 if self.media.is_some() {
1264 self.media_level(line)
1265 } else {
1266 self.session_level(line)
1267 }
1268 }
1269
1270 fn session_level(&mut self, line: Line<'_>) -> Result<()> {
1271 use SessionRank as R;
1272
1273 let value = line.value;
1274 let was_time = self.time;
1275 if !matches!(line.kind, b'r' | b'z') {
1276 self.time = TimeState::Outside;
1277 }
1278
1279 let (rank, next) = match line.kind {
1281 b'v' => (R::Version, R::Origin),
1282 b'o' => (R::Origin, R::Name),
1283 b's' => (R::Name, R::Information),
1284 b'i' => (R::Information, R::Uri),
1285 b'u' => (R::Uri, R::Email),
1286 b'e' => (R::Email, R::Email),
1287 b'p' => (R::Phone, R::Phone),
1288 b'c' => (R::Connection, R::Bandwidth),
1289 b'b' => (R::Bandwidth, R::Bandwidth),
1290 b't' | b'r' | b'z' => (R::Time, R::Time),
1291 b'k' => (R::Key, R::Attribute),
1292 b'a' => (R::Attribute, R::Attribute),
1293 _ => return Err(out_of_order(line.kind)),
1294 };
1295
1296 let allowed = match self.rank {
1299 R::Version | R::Origin | R::Name => rank == self.rank,
1300 earliest => {
1301 rank >= earliest && (rank <= R::Time || !self.desc.time_descriptions.is_empty())
1302 }
1303 };
1304 if !allowed {
1305 return Err(out_of_order(line.kind));
1306 }
1307
1308 match line.kind {
1309 b'v' => {
1310 if grammar::digits::<u32>("v=", value)? != 0 {
1312 return Err(syntax("v=", value));
1313 }
1314 self.desc.version = 0;
1315 }
1316 b'o' => self.desc.origin = self.origin(value)?,
1317 b's' => {
1318 if !(grammar::is_byte_string(value)
1319 || (value.is_empty() && self.options.loose_fields))
1320 {
1321 return Err(syntax("s=", value));
1322 }
1323 self.desc.session_name = value.to_owned();
1324 }
1325 b'i' => self.desc.session_information = Some(self.text("i=", value)?),
1326 b'u' => {
1327 if !is_uri_reference(value) {
1328 return Err(syntax("u=", value));
1329 }
1330 self.desc.uri = Some(value.to_owned());
1331 }
1332 b'e' => {
1333 if !self.options.loose_fields && !is_email_address(value) {
1334 return Err(syntax("e=", value));
1335 }
1336 self.desc.email_addresses.push(value.to_owned());
1337 }
1338 b'p' => {
1339 if !self.options.loose_fields && !is_phone_number(value) {
1340 return Err(syntax("p=", value));
1341 }
1342 self.desc.phone_numbers.push(value.to_owned());
1343 }
1344 b'c' => self.desc.connection_information = Some(self.connection(value)?),
1345 b'b' => self.desc.bandwidth.push(self.bandwidth(value)?),
1346 b't' => {
1347 let timing = self.timing(value)?;
1348 self.desc.time_descriptions.push(TimeDescription {
1349 timing,
1350 repeat_times: vec![],
1351 time_zones: vec![],
1352 });
1353 self.time = TimeState::Timing;
1354 }
1355 b'r' => {
1356 if !matches!(was_time, TimeState::Timing | TimeState::Repeat) {
1357 return Err(out_of_order(line.kind));
1358 }
1359 let repeat = self.repeat(value)?;
1360 if let Some(last) = self.desc.time_descriptions.last_mut() {
1362 last.repeat_times.push(repeat);
1363 }
1364 self.time = TimeState::Repeat;
1365 }
1366 b'z' => {
1367 if !matches!(was_time, TimeState::Timing | TimeState::Repeat) {
1368 return Err(out_of_order(line.kind));
1369 }
1370 let zones = self.zones(value)?;
1371 if let Some(last) = self.desc.time_descriptions.last_mut() {
1372 last.time_zones = zones;
1373 }
1374 self.time = TimeState::Zone;
1375 }
1376 b'k' => check_key(value)?,
1377 _ => {
1378 if self.desc.attributes.len() >= MAX_ATTRIBUTES_PER_SECTION {
1379 return Err(over_limit("session attributes", MAX_ATTRIBUTES_PER_SECTION));
1380 }
1381 self.desc.attributes.push(parse_attribute(value)?);
1382 }
1383 }
1384
1385 self.rank = next;
1386 Ok(())
1387 }
1388
1389 fn media_level(&mut self, line: Line<'_>) -> Result<()> {
1390 use MediaRank as M;
1391
1392 let value = line.value;
1393 let (rank, next) = match line.kind {
1394 b'i' => (M::Information, M::Connection),
1395 b'c' => (M::Connection, M::Connection),
1396 b'b' => (M::Bandwidth, M::Bandwidth),
1397 b'k' => (M::Key, M::Attribute),
1398 b'a' => (M::Attribute, M::Attribute),
1399 _ => return Err(out_of_order(line.kind)),
1400 };
1401
1402 let unordered = self.options.unordered_media_lines;
1403 let Some(state) = self.media.as_mut() else {
1404 return Err(out_of_order(line.kind));
1405 };
1406 if !unordered && rank < state.rank {
1407 return Err(out_of_order(line.kind));
1408 }
1409 match line.kind {
1411 b'i' if std::mem::replace(&mut state.has_title, true) => {
1412 return Err(out_of_order(line.kind));
1413 }
1414 b'k' if std::mem::replace(&mut state.has_key, true) => {
1415 return Err(out_of_order(line.kind));
1416 }
1417 _ => {}
1418 }
1419 state.rank = state.rank.max(next);
1420
1421 match line.kind {
1422 b'i' => {
1423 let title = self.text("i=", value)?;
1424 self.last_media()?.media_title = Some(title);
1425 }
1426 b'c' => {
1427 let connection = self.connection(value)?;
1428 self.last_media()?.connection_information.push(connection);
1429 }
1430 b'b' => {
1431 let bandwidth = self.bandwidth(value)?;
1432 self.last_media()?.bandwidth.push(bandwidth);
1433 }
1434 b'k' => check_key(value)?,
1435 _ => {
1436 let attribute = parse_attribute(value)?;
1437 let media = self.last_media()?;
1438 if media.attributes.len() >= MAX_ATTRIBUTES_PER_SECTION {
1439 return Err(over_limit(
1440 "attributes in one media section",
1441 MAX_ATTRIBUTES_PER_SECTION,
1442 ));
1443 }
1444 media.attributes.push(attribute);
1445 }
1446 }
1447 Ok(())
1448 }
1449
1450 fn last_media(&mut self) -> Result<&mut MediaDescription> {
1451 self.desc
1452 .media_descriptions
1453 .last_mut()
1454 .ok_or(Error::SdpEmptyTimeDescription)
1455 }
1456
1457 fn text(&self, what: &str, value: &str) -> Result<String> {
1459 if !(grammar::is_byte_string(value) || self.options.loose_fields) {
1460 return Err(syntax(what, value));
1461 }
1462 Ok(value.to_owned())
1463 }
1464
1465 fn origin(&self, value: &str) -> Result<Origin> {
1467 let fields = self.fields("o=", value)?;
1468 let [
1469 username,
1470 session_id,
1471 session_version,
1472 network_type,
1473 address_type,
1474 address,
1475 ] = fields[..]
1476 else {
1477 return Err(syntax("o=", value));
1478 };
1479 if !grammar::is_non_ws_string(username)
1480 || !grammar::is_token(network_type)
1481 || !grammar::is_token(address_type)
1482 {
1483 return Err(syntax("o=", value));
1484 }
1485 let address_ok = if self.options.loose_fields {
1486 grammar::is_non_ws_string(address)
1487 } else {
1488 grammar::is_unicast_address(address_type, address)
1489 };
1490 if !address_ok {
1491 return Err(syntax("o= unicast-address", value));
1492 }
1493 Ok(Origin {
1494 username: username.to_owned(),
1495 session_id: SdpDecimal::parse(session_id)
1499 .ok_or_else(|| syntax("o= sess-id", session_id))?,
1500 session_version: SdpDecimal::parse(session_version)
1501 .ok_or_else(|| syntax("o= sess-version", session_version))?,
1502 network_type: network_type.to_owned(),
1503 address_type: address_type.to_owned(),
1504 unicast_address: address.to_owned(),
1505 })
1506 }
1507
1508 fn connection(&self, value: &str) -> Result<ConnectionInformation> {
1509 let fields = self.fields("c=", value)?;
1510 if !self.options.loose_fields {
1511 return ConnectionInformation::parse_fields(&fields, value);
1512 }
1513 if !(2..=3).contains(&fields.len())
1514 || !grammar::is_token(fields[0])
1515 || !grammar::is_token(fields[1])
1516 {
1517 return Err(syntax("c=", value));
1518 }
1519 Ok(ConnectionInformation {
1520 network_type: fields[0].to_owned(),
1521 address_type: fields[1].to_owned(),
1522 address: fields.get(2).map(|address| {
1523 Address::parse(fields[1], address).unwrap_or_else(|_| Address {
1525 address: (*address).to_owned(),
1526 ttl: None,
1527 range: None,
1528 })
1529 }),
1530 })
1531 }
1532
1533 fn bandwidth(&self, value: &str) -> Result<Bandwidth> {
1534 if self.options.loose_fields {
1535 Bandwidth::parse(value.trim())
1536 } else {
1537 Bandwidth::parse(value)
1538 }
1539 }
1540
1541 fn timing(&self, value: &str) -> Result<Timing> {
1543 let fields = self.fields("t=", value)?;
1544 let loose = self.options.loose_fields;
1545 if fields.len() < 2 || (fields.len() > 2 && !loose) {
1546 return Err(syntax("t=", value));
1547 }
1548 let time = |field: &str| -> Result<u64> {
1549 if !(loose || field == "0" || (grammar::is_integer(field) && field.len() >= 10)) {
1550 return Err(syntax("t=", value));
1551 }
1552 grammar::digits("t=", field)
1553 };
1554 Ok(Timing {
1555 start_time: time(fields[0])?,
1556 stop_time: time(fields[1])?,
1557 })
1558 }
1559
1560 fn repeat(&self, value: &str) -> Result<RepeatTime> {
1562 let fields = self.fields("r=", value)?;
1563 if fields.len() < 3 {
1564 return Err(syntax("r=", value));
1565 }
1566 if fields[0].starts_with('0') {
1568 return Err(syntax("r= repeat-interval", value));
1569 }
1570 let interval = parse_typed_time(fields[0])?;
1571 let duration = parse_typed_time(fields[1])?;
1572 let mut offsets = Vec::with_capacity(fields.len() - 2);
1573 for field in &fields[2..] {
1574 offsets.push(parse_typed_time(field)?);
1575 }
1576 Ok(RepeatTime {
1577 interval,
1578 duration,
1579 offsets,
1580 })
1581 }
1582
1583 fn zones(&self, value: &str) -> Result<Vec<TimeZone>> {
1585 let fields = self.fields("z=", value)?;
1586 if !fields.len().is_multiple_of(2) {
1587 return Err(syntax("z=", value));
1588 }
1589 let mut zones = Vec::with_capacity(fields.len() / 2);
1590 for pair in fields.chunks(2) {
1591 let time = pair[0];
1592 if !(self.options.loose_fields || (grammar::is_integer(time) && time.len() >= 10)) {
1593 return Err(syntax("z= adjustment time", value));
1594 }
1595 let adjustment_time = grammar::digits("z= adjustment time", time)?;
1596 let offset = match pair[1].strip_prefix('-') {
1597 Some(positive) => parse_typed_time(positive)?
1598 .checked_neg()
1599 .ok_or_else(|| invalid("z= offset", value))?,
1600 None => parse_typed_time(pair[1])?,
1601 };
1602 zones.push(TimeZone {
1603 adjustment_time,
1604 offset,
1605 });
1606 }
1607 Ok(zones)
1608 }
1609
1610 fn media_line(&mut self, value: &str) -> Result<()> {
1612 if self.desc.media_descriptions.len() >= MAX_MEDIA_DESCRIPTIONS {
1613 return Err(over_limit("media sections", MAX_MEDIA_DESCRIPTIONS));
1614 }
1615
1616 let fields = self.fields("m=", value)?;
1617 if fields.len() < 4 {
1618 return Err(syntax("m=", value));
1619 }
1620 if fields.len() - 3 > MAX_FORMATS_PER_MEDIA {
1621 return Err(over_limit("formats on one m= line", MAX_FORMATS_PER_MEDIA));
1622 }
1623
1624 if !grammar::is_token(fields[0]) {
1631 return Err(Error::SdpInvalidValue(fields[0].to_owned()));
1632 }
1633
1634 let (port, count) = match fields[1].split_once('/') {
1636 Some((port, count)) => (port, Some(count)),
1637 None => (fields[1], None),
1638 };
1639 let port_value = grammar::port(port)? as isize;
1640 let port_range = match count {
1641 Some(count) => {
1642 if !grammar::is_integer(count) {
1643 return Err(syntax("m= number of ports", value));
1644 }
1645 Some(
1646 count
1647 .parse::<u16>()
1648 .map_err(|_| invalid("m= number of ports", value))?
1649 as isize,
1650 )
1651 }
1652 None => None,
1653 };
1654
1655 let mut protos = vec![];
1662 for proto in fields[2].split('/') {
1663 if !grammar::is_token(proto) {
1664 return Err(Error::SdpInvalidValue(fields[2].to_owned()));
1665 }
1666 protos.push(proto.to_owned());
1667 }
1668
1669 let mut formats = Vec::with_capacity(fields.len() - 3);
1671 for field in &fields[3..] {
1672 if !grammar::is_token(field) {
1673 return Err(syntax("m= fmt", value));
1674 }
1675 formats.push((*field).to_owned());
1676 }
1677
1678 self.desc.media_descriptions.push(MediaDescription {
1679 media_name: MediaName {
1680 media: fields[0].to_owned(),
1681 port: RangedPort {
1682 value: port_value,
1683 range: port_range,
1684 },
1685 protos,
1686 formats,
1687 },
1688 media_title: None,
1689 connection_information: vec![],
1690 bandwidth: vec![],
1691 encryption_key: None,
1692 attributes: vec![],
1693 });
1694 Ok(())
1695 }
1696}
1697
1698pub(crate) fn parse_attribute(value: &str) -> Result<Attribute> {
1702 let (key, value) = match value.split_once(':') {
1703 Some((key, value)) => (key, Some(value)),
1704 None => (value, None),
1705 };
1706 if !grammar::is_token(key) {
1707 return Err(syntax("attribute name", key));
1708 }
1709 Ok(Attribute {
1710 key: key.to_owned(),
1711 value: value.map(str::to_owned),
1712 })
1713}
1714
1715fn check_key(value: &str) -> Result<()> {
1718 let ok = if value == "prompt" {
1719 true
1720 } else if let Some(text) = value.strip_prefix("clear:") {
1721 grammar::is_byte_string(text)
1722 } else if let Some(key) = value.strip_prefix("base64:") {
1723 grammar::is_base64(key)
1724 } else if let Some(uri) = value.strip_prefix("uri:") {
1725 grammar::is_non_ws_string(uri)
1726 } else {
1727 false
1728 };
1729 if ok {
1730 Ok(())
1731 } else {
1732 Err(Error::SdpInvalidSyntax("k= line".to_owned()))
1734 }
1735}
1736
1737fn is_email_safe(value: &str) -> bool {
1739 !value.is_empty()
1740 && !value
1741 .bytes()
1742 .any(|b| matches!(b, 0 | b'\r' | b'\n' | b'(' | b')' | b'<' | b'>'))
1743}
1744
1745fn is_atext(b: u8) -> bool {
1747 b.is_ascii_alphanumeric() || b"!#$%&'*+-/=?^_`{|}~".contains(&b)
1748}
1749
1750fn is_dot_atom(value: &str) -> bool {
1752 !value.is_empty()
1753 && value
1754 .split('.')
1755 .all(|atom| !atom.is_empty() && atom.bytes().all(is_atext))
1756}
1757
1758fn is_addr_spec(value: &str) -> bool {
1762 let bytes = value.as_bytes();
1763 let at = if bytes.first() == Some(&b'"') {
1764 let mut i = 1;
1766 loop {
1767 match bytes.get(i) {
1768 Some(b'"') => break i + 1,
1769 Some(b'\\') if matches!(bytes.get(i + 1), Some(0x20..=0x7e | b'\t')) => i += 2,
1770 Some(b' ' | b'\t' | 0x21 | 0x23..=0x5b | 0x5d..=0x7e) => i += 1,
1771 _ => return false,
1772 }
1773 }
1774 } else {
1775 match value.find('@') {
1776 Some(at) if is_dot_atom(&value[..at]) => at,
1777 _ => return false,
1778 }
1779 };
1780 if bytes.get(at) != Some(&b'@') {
1781 return false;
1782 }
1783 let domain = &value[at + 1..];
1784 match domain.strip_prefix('[').and_then(|d| d.strip_suffix(']')) {
1785 Some(literal) => literal
1787 .bytes()
1788 .all(|b| matches!(b, 0x21..=0x5a | 0x5e..=0x7e)),
1789 None => is_dot_atom(domain),
1790 }
1791}
1792
1793fn is_email_address(value: &str) -> bool {
1795 if let Some(rest) = value.strip_suffix(')') {
1796 let Some((address, comment)) = rest.split_once('(') else {
1798 return false;
1799 };
1800 let spec = address.trim_end_matches(' ');
1801 return spec.len() < address.len() && is_addr_spec(spec) && is_email_safe(comment);
1802 }
1803 if let Some(rest) = value.strip_suffix('>') {
1804 let Some((name, address)) = rest.split_once('<') else {
1806 return false;
1807 };
1808 return name.ends_with(' ')
1809 && is_email_safe(name.trim_end_matches(' '))
1810 && is_addr_spec(address);
1811 }
1812 is_addr_spec(value)
1813}
1814
1815fn is_phone(value: &str) -> bool {
1817 let digits = value.strip_prefix('+').unwrap_or(value).as_bytes();
1818 digits.len() >= 2
1819 && digits[0].is_ascii_digit()
1820 && digits[1..]
1821 .iter()
1822 .all(|b| b.is_ascii_digit() || *b == b' ' || *b == b'-')
1823}
1824
1825fn is_phone_number(value: &str) -> bool {
1827 if let Some(rest) = value.strip_suffix(')') {
1828 let Some((phone, comment)) = rest.split_once('(') else {
1829 return false;
1830 };
1831 return is_phone(phone) && is_email_safe(comment);
1833 }
1834 if let Some(rest) = value.strip_suffix('>') {
1835 let Some((name, phone)) = rest.split_once('<') else {
1836 return false;
1837 };
1838 return is_email_safe(name) && is_phone(phone);
1839 }
1840 is_phone(value)
1841}
1842
1843fn parse_typed_time(value: &str) -> Result<i64> {
1847 let (number, factor) = match value.as_bytes().last() {
1848 Some(b'd') => (&value[..value.len() - 1], 86400),
1849 Some(b'h') => (&value[..value.len() - 1], 3600),
1850 Some(b'm') => (&value[..value.len() - 1], 60),
1851 Some(b's') => (&value[..value.len() - 1], 1),
1852 _ => (value, 1),
1853 };
1854 grammar::digits::<i64>("typed-time", number)?
1855 .checked_mul(factor)
1856 .ok_or_else(|| invalid("typed-time", value))
1857}