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 unmarshal<R: io::BufRead + io::Seek>(reader: &mut R) -> Result<Self> {
819 Self::unmarshal_with_options(reader, &ParseOptions::strict())
820 }
821
822 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 pub fn charset(&self) -> Charset {
846 self.attribute(ATTR_KEY_CHARSET)
847 .map_or(Charset::Utf8, |name| Charset::named(name))
848 }
849
850 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 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
892fn 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 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
936pub const ATTR_KEY_CHARSET: &str = "charset";
938
939#[derive(Debug, Clone, PartialEq, Eq)]
942pub enum Charset {
943 Utf8,
945 Latin1,
947 Ascii,
949 Other(String),
954}
955
956impl Charset {
957 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
1002fn 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
1017fn 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#[derive(Debug, PartialEq)]
1047pub struct SdpParseError {
1048 pub line_number: Option<usize>,
1051 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#[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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1095enum TimeState {
1096 Outside,
1098 Timing,
1100 Repeat,
1102 Zone,
1104}
1105
1106#[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 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 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 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 return Err(Error::SdpInvalidSyntax(format!(
1194 "unknown line type `{}=`",
1195 line.kind.escape_ascii()
1196 )));
1197 }
1198
1199 if line.kind == b'm' {
1200 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 if !grammar::is_token(fields[0]) {
1581 return Err(Error::SdpInvalidValue(fields[0].to_owned()));
1582 }
1583
1584 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 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 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
1648pub(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
1665fn 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 Err(Error::SdpInvalidSyntax("k= line".to_owned()))
1684 }
1685}
1686
1687fn 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
1695fn is_atext(b: u8) -> bool {
1697 b.is_ascii_alphanumeric() || b"!#$%&'*+-/=?^_`{|}~".contains(&b)
1698}
1699
1700fn 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
1708fn is_addr_spec(value: &str) -> bool {
1712 let bytes = value.as_bytes();
1713 let at = if bytes.first() == Some(&b'"') {
1714 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 Some(literal) => literal
1737 .bytes()
1738 .all(|b| matches!(b, 0x21..=0x5a | 0x5e..=0x7e)),
1739 None => is_dot_atom(domain),
1740 }
1741}
1742
1743fn is_email_address(value: &str) -> bool {
1745 if let Some(rest) = value.strip_suffix(')') {
1746 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 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
1765fn 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
1775fn 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 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
1793fn 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}