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
304impl Origin {
305 pub fn new() -> Self {
307 Origin {
308 username: "".to_owned(),
309 session_id: SdpDecimal::default(),
310 session_version: SdpDecimal::default(),
311 network_type: "".to_owned(),
312 address_type: "".to_owned(),
313 unicast_address: "".to_owned(),
314 }
315 }
316}
317
318pub type SessionName = String;
321
322pub type EmailAddress = String;
326
327pub type PhoneNumber = String;
331
332#[derive(Debug, Default, Clone, PartialEq, Eq)]
335pub struct TimeZone {
336 pub adjustment_time: u64,
338 pub offset: i64,
340}
341
342impl fmt::Display for TimeZone {
343 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
344 write!(f, "{} {}", self.adjustment_time, self.offset)
345 }
346}
347
348#[derive(Debug, Default, Clone)]
355pub struct TimeDescription {
356 pub timing: Timing,
360
361 pub repeat_times: Vec<RepeatTime>,
365
366 pub time_zones: Vec<TimeZone>,
373}
374
375#[derive(Debug, Default, Clone, PartialEq, Eq)]
378pub struct Timing {
379 pub start_time: u64,
381 pub stop_time: u64,
383}
384
385impl fmt::Display for Timing {
386 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
387 write!(f, "{} {}", self.start_time, self.stop_time)
388 }
389}
390
391#[derive(Debug, Default, Clone, PartialEq, Eq)]
394pub struct RepeatTime {
395 pub interval: i64,
397 pub duration: i64,
399 pub offsets: Vec<i64>,
401}
402
403impl fmt::Display for RepeatTime {
404 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
405 write!(f, "{} {}", self.interval, self.duration)?;
406
407 for value in &self.offsets {
408 write!(f, " {value}")?;
409 }
410 Ok(())
411 }
412}
413
414#[derive(Debug, Default, Clone)]
417pub struct SessionDescription {
418 pub version: Version,
422
423 pub origin: Origin,
427
428 pub session_name: SessionName,
434
435 pub session_information: Option<Information>,
439
440 pub uri: Option<String>,
445
446 pub email_addresses: Vec<EmailAddress>,
450
451 pub phone_numbers: Vec<PhoneNumber>,
455
456 pub connection_information: Option<ConnectionInformation>,
460
461 pub bandwidth: Vec<Bandwidth>,
465
466 pub time_descriptions: Vec<TimeDescription>,
471
472 pub encryption_key: Option<EncryptionKey>,
476
477 pub attributes: Vec<Attribute>,
483
484 pub media_descriptions: Vec<MediaDescription>,
486}
487
488impl fmt::Display for SessionDescription {
492 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
493 write_key_value(f, "v=", Some(&self.version))?;
494 write_key_value(f, "o=", Some(&self.origin))?;
495 if self.session_name.is_empty() {
496 write_key_value(f, "s=", Some("-"))?;
498 } else {
499 write_key_value(f, "s=", Some(&self.session_name))?;
500 }
501
502 write_key_value(f, "i=", self.session_information.as_ref())?;
503
504 if let Some(uri) = &self.uri {
505 write_key_value(f, "u=", Some(uri))?;
506 }
507 for email_address in &self.email_addresses {
508 write_key_value(f, "e=", Some(email_address))?;
509 }
510 for phone_number in &self.phone_numbers {
511 write_key_value(f, "p=", Some(phone_number))?;
512 }
513 if let Some(connection_information) = &self.connection_information {
514 write_key_value(f, "c=", Some(&connection_information))?;
515 }
516
517 for bandwidth in &self.bandwidth {
518 write_key_value(f, "b=", Some(&bandwidth))?;
519 }
520 if self.time_descriptions.is_empty() {
521 write_key_value(f, "t=", Some("0 0"))?;
523 }
524 for time_description in &self.time_descriptions {
525 write_key_value(f, "t=", Some(&time_description.timing))?;
526 for repeat_time in &time_description.repeat_times {
527 write_key_value(f, "r=", Some(&repeat_time))?;
528 }
529 write_key_slice_of_values(f, "z=", &time_description.time_zones)?;
530 }
531
532 for attribute in &self.attributes {
533 write_key_value(f, "a=", Some(&attribute))?;
534 }
535
536 for media_description in &self.media_descriptions {
537 write_key_value(f, "m=", Some(&media_description.media_name))?;
538 write_key_value(f, "i=", media_description.media_title.as_ref())?;
539 if let Some(connection_information) = &media_description.connection_information {
540 write_key_value(f, "c=", Some(&connection_information))?;
541 }
542 for bandwidth in &media_description.bandwidth {
543 write_key_value(f, "b=", Some(&bandwidth))?;
544 }
545 for attribute in &media_description.attributes {
546 write_key_value(f, "a=", Some(&attribute))?;
547 }
548 }
549
550 Ok(())
551 }
552}
553
554#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
590pub struct ParseOptions {
591 pub blank_lines: bool,
593 pub unordered_media_lines: bool,
596 pub loose_fields: bool,
602}
603
604impl ParseOptions {
605 pub const fn strict() -> Self {
607 ParseOptions {
608 blank_lines: false,
609 unordered_media_lines: false,
610 loose_fields: false,
611 }
612 }
613
614 pub const fn lenient() -> Self {
616 ParseOptions {
617 blank_lines: true,
618 unordered_media_lines: true,
619 loose_fields: true,
620 }
621 }
622}
623
624impl SessionDescription {
626 pub fn new_jsep_session_description(_identity: bool) -> Self {
634 SessionDescription {
635 version: 0,
636 origin: Origin {
637 username: "-".to_string(),
638 session_id: new_session_id().into(),
639 session_version: u64::from(
640 SystemTime::now() .duration_since(UNIX_EPOCH)
642 .unwrap_or_else(|_| Duration::from_secs(0))
643 .subsec_nanos(),
644 )
645 .into(),
646 network_type: "IN".to_string(),
647 address_type: "IP4".to_string(),
648 unicast_address: "0.0.0.0".to_string(),
649 },
650 session_name: "-".to_string(),
651 session_information: None,
652 uri: None,
653 email_addresses: vec![],
654 phone_numbers: vec![],
655 connection_information: None,
656 bandwidth: vec![],
657 time_descriptions: vec![TimeDescription {
658 timing: Timing {
659 start_time: 0,
660 stop_time: 0,
661 },
662 repeat_times: vec![],
663 time_zones: vec![],
664 }],
665 encryption_key: None,
666 attributes: vec![],
667 media_descriptions: vec![],
668 }
669 }
670
671 pub fn with_property_attribute(mut self, key: String) -> Self {
673 self.attributes.push(Attribute::new(key, None));
674 self
675 }
676
677 pub fn with_value_attribute(mut self, key: String, value: String) -> Self {
679 self.attributes.push(Attribute::new(key, Some(value)));
680 self
681 }
682
683 pub fn with_fingerprint(self, algorithm: String, value: String) -> Self {
685 self.with_value_attribute("fingerprint".to_string(), algorithm + " " + value.as_str())
686 }
687
688 pub fn with_media(mut self, md: MediaDescription) -> Self {
690 self.media_descriptions.push(md);
691 self
692 }
693
694 fn build_codec_map(&self) -> HashMap<u8, Codec> {
695 let mut codecs: HashMap<u8, Codec> = HashMap::new();
696
697 for m in &self.media_descriptions {
698 codecs.extend(m.codecs());
699 }
700
701 codecs
702 }
703
704 pub fn get_codec_for_payload_type(&self, payload_type: u8) -> Result<Codec> {
706 let codecs = self.build_codec_map();
707
708 if let Some(codec) = codecs.get(&payload_type) {
709 Ok(codec.clone())
710 } else {
711 Err(Error::PayloadTypeNotFound)
712 }
713 }
714
715 pub fn get_payload_type_for_codec(&self, wanted: &Codec) -> Result<u8> {
718 let codecs = self.build_codec_map();
719
720 for (payload_type, codec) in codecs.iter() {
721 if codecs_match(wanted, codec) {
722 return Ok(*payload_type);
723 }
724 }
725
726 Err(Error::CodecNotFound)
727 }
728
729 pub fn has_attribute(&self, key: &str) -> bool {
731 self.attributes.iter().any(|a| a.key == key)
732 }
733
734 pub fn attribute(&self, key: &str) -> Option<&String> {
736 for a in &self.attributes {
737 if a.key == key {
738 return a.value.as_ref();
739 }
740 }
741 None
742 }
743
744 pub fn bandwidth_of(&self, kind: BandwidthKind) -> Option<u64> {
747 find_bandwidth(&self.bandwidth, kind)
748 }
749
750 crate::attribute::common_accessors!();
751 crate::attribute::session_accessors!();
752
753 pub fn marshal(&self) -> String {
784 self.to_string()
785 }
786
787 pub fn unmarshal<R: io::BufRead + io::Seek>(reader: &mut R) -> Result<Self> {
799 Self::unmarshal_with_options(reader, &ParseOptions::strict())
800 }
801
802 pub fn unmarshal_with_options<R: io::BufRead + io::Seek>(
804 reader: &mut R,
805 options: &ParseOptions,
806 ) -> Result<Self> {
807 let start = reader.stream_position()?;
808 let end = reader.seek(io::SeekFrom::End(0))?;
809 reader.seek(io::SeekFrom::Start(start))?;
810 if end.saturating_sub(start) > MAX_SDP_SIZE as u64 {
811 return Err(over_limit("bytes", MAX_SDP_SIZE));
812 }
813
814 let mut bytes = Vec::with_capacity(end.saturating_sub(start) as usize);
815 io::Read::take(&mut *reader, MAX_SDP_SIZE as u64 + 1).read_to_end(&mut bytes)?;
816 if bytes.len() > MAX_SDP_SIZE {
817 return Err(over_limit("bytes", MAX_SDP_SIZE));
818 }
819 let text = decode(&bytes)?;
820 Self::parse_with_options(&text, options)
821 }
822
823 pub fn charset(&self) -> Charset {
826 self.attribute(ATTR_KEY_CHARSET)
827 .map_or(Charset::Utf8, |name| Charset::named(name))
828 }
829
830 pub fn parse_with_options(text: &str, options: &ParseOptions) -> Result<Self> {
832 Self::parse_located(text, options).map_err(|err| err.error)
833 }
834
835 pub fn parse_located(
844 text: &str,
845 options: &ParseOptions,
846 ) -> std::result::Result<Self, SdpParseError> {
847 let unlocated = |error| SdpParseError {
848 line_number: None,
849 error,
850 };
851 if text.len() > MAX_SDP_SIZE {
852 return Err(unlocated(over_limit("bytes", MAX_SDP_SIZE)));
853 }
854 let mut parser = Parser::new(*options);
855 let lines = lines_located(text, options.blank_lines, MAX_SDP_LINES).map_err(
856 |(number, error)| SdpParseError {
857 line_number: Some(number),
858 error,
859 },
860 )?;
861 for line in lines {
862 let number = line.number;
863 parser.line(line).map_err(|error| SdpParseError {
864 line_number: Some(number),
865 error,
866 })?;
867 }
868 parser.finish().map_err(unlocated)
869 }
870}
871
872fn is_uri_reference(value: &str) -> bool {
877 if value.is_empty() {
878 return false;
879 }
880 let bytes = value.as_bytes();
881 let mut i = 0;
882 while i < bytes.len() {
883 let b = bytes[i];
884 let ok = b.is_ascii_alphanumeric() || b"-._~!$&'()*+,;=:@/?#[]".contains(&b);
885 if b == b'%' {
886 if !bytes.get(i + 1).is_some_and(u8::is_ascii_hexdigit)
887 || !bytes.get(i + 2).is_some_and(u8::is_ascii_hexdigit)
888 {
889 return false;
890 }
891 i += 3;
892 continue;
893 }
894 if !ok {
895 return false;
896 }
897 i += 1;
898 }
899 let first_segment = value.split(['/', '?', '#']).next().unwrap_or_default();
900 match first_segment.split_once(':') {
901 Some((scheme, _)) => {
903 scheme
904 .bytes()
905 .next()
906 .is_some_and(|b| b.is_ascii_alphabetic())
907 && scheme
908 .bytes()
909 .all(|b| b.is_ascii_alphanumeric() || b"+-.".contains(&b))
910 && Url::parse(value).is_ok()
911 }
912 None => true,
913 }
914}
915
916pub const ATTR_KEY_CHARSET: &str = "charset";
918
919#[derive(Debug, Clone, PartialEq, Eq)]
922pub enum Charset {
923 Utf8,
925 Latin1,
927 Ascii,
929 Other(String),
934}
935
936impl Charset {
937 pub fn named(name: &str) -> Self {
942 const UTF8: [&str; 2] = ["UTF-8", "csUTF8"];
943 const LATIN1: [&str; 10] = [
944 "ISO-8859-1",
945 "ISO_8859-1:1987",
946 "ISO_8859-1",
947 "iso-ir-100",
948 "latin1",
949 "l1",
950 "IBM819",
951 "CP819",
952 "csISOLatin1",
953 "ISO-8859-1:1987",
954 ];
955 const ASCII: [&str; 11] = [
956 "US-ASCII",
957 "ANSI_X3.4-1968",
958 "iso-ir-6",
959 "ANSI_X3.4-1986",
960 "ISO_646.irv:1991",
961 "ISO646-US",
962 "us",
963 "IBM367",
964 "cp367",
965 "csASCII",
966 "ASCII",
967 ];
968 let name = name.trim();
969 let is = |names: &[&str]| names.iter().any(|n| n.eq_ignore_ascii_case(name));
970 if is(&UTF8) {
971 Charset::Utf8
972 } else if is(&LATIN1) {
973 Charset::Latin1
974 } else if is(&ASCII) {
975 Charset::Ascii
976 } else {
977 Charset::Other(name.to_owned())
978 }
979 }
980}
981
982fn declared_charset(bytes: &[u8]) -> Option<Charset> {
985 for line in bytes.split(|&b| b == b'\n') {
986 let line = line.strip_suffix(b"\r").unwrap_or(line);
987 if line.starts_with(b"m=") {
988 return None;
989 }
990 if let Some(value) = line.strip_prefix(b"a=charset:") {
991 return core::str::from_utf8(value).ok().map(Charset::named);
992 }
993 }
994 None
995}
996
997fn decode(bytes: &[u8]) -> Result<std::borrow::Cow<'_, str>> {
1003 match declared_charset(bytes) {
1004 None | Some(Charset::Utf8) => core::str::from_utf8(bytes)
1005 .map(std::borrow::Cow::Borrowed)
1006 .map_err(|_| Error::SdpInvalidSyntax("the description is not UTF-8".to_owned())),
1007 Some(Charset::Ascii) => {
1008 if bytes.is_ascii() {
1009 Ok(std::borrow::Cow::Owned(
1010 bytes.iter().map(|&b| char::from(b)).collect(),
1011 ))
1012 } else {
1013 Err(Error::SdpInvalidSyntax(
1014 "a=charset:US-ASCII and a byte above 127 (RFC 8866 section 6.10)".to_owned(),
1015 ))
1016 }
1017 }
1018 Some(Charset::Latin1 | Charset::Other(_)) => Ok(std::borrow::Cow::Owned(
1019 bytes.iter().map(|&b| char::from(b)).collect(),
1020 )),
1021 }
1022}
1023
1024#[derive(Debug, PartialEq)]
1027pub struct SdpParseError {
1028 pub line_number: Option<usize>,
1031 pub error: Error,
1033}
1034
1035impl From<SessionDescription> for String {
1036 fn from(sdp: SessionDescription) -> String {
1037 sdp.marshal()
1038 }
1039}
1040
1041impl TryFrom<String> for SessionDescription {
1042 type Error = Error;
1043 fn try_from(sdp_string: String) -> Result<Self> {
1044 SessionDescription::parse_with_options(&sdp_string, &ParseOptions::strict())
1045 }
1046}
1047
1048impl FromStr for SessionDescription {
1049 type Err = Error;
1050 fn from_str(sdp: &str) -> Result<Self> {
1051 SessionDescription::parse_with_options(sdp, &ParseOptions::strict())
1052 }
1053}
1054
1055#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
1058enum SessionRank {
1059 Version,
1060 Origin,
1061 Name,
1062 Information,
1063 Uri,
1064 Email,
1065 Phone,
1066 Connection,
1067 Bandwidth,
1068 Time,
1069 Key,
1070 Attribute,
1071}
1072
1073#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1075enum TimeState {
1076 Outside,
1078 Timing,
1080 Repeat,
1082 Zone,
1084}
1085
1086#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
1088enum MediaRank {
1089 Information,
1090 Connection,
1091 Bandwidth,
1092 Key,
1093 Attribute,
1094}
1095
1096struct Parser {
1097 options: ParseOptions,
1098 desc: SessionDescription,
1099 rank: SessionRank,
1100 time: TimeState,
1101 media: Option<MediaState>,
1103}
1104
1105struct MediaState {
1106 rank: MediaRank,
1107 has_title: bool,
1108 has_key: bool,
1109}
1110
1111fn out_of_order(kind: u8) -> Error {
1112 Error::SdpInvalidSyntax(format!(
1113 "a `{}=` line where the grammar has none",
1114 kind as char
1115 ))
1116}
1117
1118impl Parser {
1119 fn new(options: ParseOptions) -> Self {
1120 Parser {
1121 options,
1122 desc: SessionDescription::default(),
1123 rank: SessionRank::Version,
1124 time: TimeState::Outside,
1125 media: None,
1126 }
1127 }
1128
1129 fn finish(self) -> Result<SessionDescription> {
1130 if self.desc.time_descriptions.is_empty() {
1132 return Err(Error::SdpInvalidSyntax(
1133 "the description ends before its `t=` line".to_owned(),
1134 ));
1135 }
1136 Ok(self.desc)
1137 }
1138
1139 fn fields<'a>(&self, what: &str, value: &'a str) -> Result<Vec<&'a str>> {
1142 if self.options.loose_fields {
1143 let fields: Vec<&str> = value.split_whitespace().collect();
1144 if fields.is_empty() {
1145 return Err(syntax(what, value));
1146 }
1147 Ok(fields)
1148 } else {
1149 grammar::fields(what, value)
1150 }
1151 }
1152
1153 fn line(&mut self, line: Line<'_>) -> Result<()> {
1154 if !matches!(
1155 line.kind,
1156 b'v' | b'o'
1157 | b's'
1158 | b'i'
1159 | b'u'
1160 | b'e'
1161 | b'p'
1162 | b'c'
1163 | b'b'
1164 | b't'
1165 | b'r'
1166 | b'z'
1167 | b'k'
1168 | b'a'
1169 | b'm'
1170 ) {
1171 return Err(Error::SdpInvalidSyntax(format!(
1174 "unknown line type `{}=`",
1175 line.kind.escape_ascii()
1176 )));
1177 }
1178
1179 if line.kind == b'm' {
1180 if self.desc.time_descriptions.is_empty() {
1182 return Err(out_of_order(line.kind));
1183 }
1184 self.media_line(line.value)?;
1185 self.media = Some(MediaState {
1186 rank: MediaRank::Information,
1187 has_title: false,
1188 has_key: false,
1189 });
1190 return Ok(());
1191 }
1192
1193 if self.media.is_some() {
1194 self.media_level(line)
1195 } else {
1196 self.session_level(line)
1197 }
1198 }
1199
1200 fn session_level(&mut self, line: Line<'_>) -> Result<()> {
1201 use SessionRank as R;
1202
1203 let value = line.value;
1204 let was_time = self.time;
1205 if !matches!(line.kind, b'r' | b'z') {
1206 self.time = TimeState::Outside;
1207 }
1208
1209 let (rank, next) = match line.kind {
1211 b'v' => (R::Version, R::Origin),
1212 b'o' => (R::Origin, R::Name),
1213 b's' => (R::Name, R::Information),
1214 b'i' => (R::Information, R::Uri),
1215 b'u' => (R::Uri, R::Email),
1216 b'e' => (R::Email, R::Email),
1217 b'p' => (R::Phone, R::Phone),
1218 b'c' => (R::Connection, R::Bandwidth),
1219 b'b' => (R::Bandwidth, R::Bandwidth),
1220 b't' | b'r' | b'z' => (R::Time, R::Time),
1221 b'k' => (R::Key, R::Attribute),
1222 b'a' => (R::Attribute, R::Attribute),
1223 _ => return Err(out_of_order(line.kind)),
1224 };
1225
1226 let allowed = match self.rank {
1229 R::Version | R::Origin | R::Name => rank == self.rank,
1230 earliest => {
1231 rank >= earliest && (rank <= R::Time || !self.desc.time_descriptions.is_empty())
1232 }
1233 };
1234 if !allowed {
1235 return Err(out_of_order(line.kind));
1236 }
1237
1238 match line.kind {
1239 b'v' => {
1240 if grammar::digits::<u32>("v=", value)? != 0 {
1242 return Err(syntax("v=", value));
1243 }
1244 self.desc.version = 0;
1245 }
1246 b'o' => self.desc.origin = self.origin(value)?,
1247 b's' => {
1248 if !(grammar::is_byte_string(value)
1249 || (value.is_empty() && self.options.loose_fields))
1250 {
1251 return Err(syntax("s=", value));
1252 }
1253 self.desc.session_name = value.to_owned();
1254 }
1255 b'i' => self.desc.session_information = Some(self.text("i=", value)?),
1256 b'u' => {
1257 if !is_uri_reference(value) {
1258 return Err(syntax("u=", value));
1259 }
1260 self.desc.uri = Some(value.to_owned());
1261 }
1262 b'e' => {
1263 if !self.options.loose_fields && !is_email_address(value) {
1264 return Err(syntax("e=", value));
1265 }
1266 self.desc.email_addresses.push(value.to_owned());
1267 }
1268 b'p' => {
1269 if !self.options.loose_fields && !is_phone_number(value) {
1270 return Err(syntax("p=", value));
1271 }
1272 self.desc.phone_numbers.push(value.to_owned());
1273 }
1274 b'c' => self.desc.connection_information = Some(self.connection(value)?),
1275 b'b' => self.desc.bandwidth.push(self.bandwidth(value)?),
1276 b't' => {
1277 let timing = self.timing(value)?;
1278 self.desc.time_descriptions.push(TimeDescription {
1279 timing,
1280 repeat_times: vec![],
1281 time_zones: vec![],
1282 });
1283 self.time = TimeState::Timing;
1284 }
1285 b'r' => {
1286 if !matches!(was_time, TimeState::Timing | TimeState::Repeat) {
1287 return Err(out_of_order(line.kind));
1288 }
1289 let repeat = self.repeat(value)?;
1290 if let Some(last) = self.desc.time_descriptions.last_mut() {
1292 last.repeat_times.push(repeat);
1293 }
1294 self.time = TimeState::Repeat;
1295 }
1296 b'z' => {
1297 if !matches!(was_time, TimeState::Timing | TimeState::Repeat) {
1298 return Err(out_of_order(line.kind));
1299 }
1300 let zones = self.zones(value)?;
1301 if let Some(last) = self.desc.time_descriptions.last_mut() {
1302 last.time_zones = zones;
1303 }
1304 self.time = TimeState::Zone;
1305 }
1306 b'k' => check_key(value)?,
1307 _ => {
1308 if self.desc.attributes.len() >= MAX_ATTRIBUTES_PER_SECTION {
1309 return Err(over_limit("session attributes", MAX_ATTRIBUTES_PER_SECTION));
1310 }
1311 self.desc.attributes.push(parse_attribute(value)?);
1312 }
1313 }
1314
1315 self.rank = next;
1316 Ok(())
1317 }
1318
1319 fn media_level(&mut self, line: Line<'_>) -> Result<()> {
1320 use MediaRank as M;
1321
1322 let value = line.value;
1323 let (rank, next) = match line.kind {
1324 b'i' => (M::Information, M::Connection),
1325 b'c' => (M::Connection, M::Connection),
1326 b'b' => (M::Bandwidth, M::Bandwidth),
1327 b'k' => (M::Key, M::Attribute),
1328 b'a' => (M::Attribute, M::Attribute),
1329 _ => return Err(out_of_order(line.kind)),
1330 };
1331
1332 let unordered = self.options.unordered_media_lines;
1333 let Some(state) = self.media.as_mut() else {
1334 return Err(out_of_order(line.kind));
1335 };
1336 if !unordered && rank < state.rank {
1337 return Err(out_of_order(line.kind));
1338 }
1339 match line.kind {
1341 b'i' if std::mem::replace(&mut state.has_title, true) => {
1342 return Err(out_of_order(line.kind));
1343 }
1344 b'k' if std::mem::replace(&mut state.has_key, true) => {
1345 return Err(out_of_order(line.kind));
1346 }
1347 _ => {}
1348 }
1349 state.rank = state.rank.max(next);
1350
1351 match line.kind {
1352 b'i' => {
1353 let title = self.text("i=", value)?;
1354 self.last_media()?.media_title = Some(title);
1355 }
1356 b'c' => {
1357 let connection = self.connection(value)?;
1358 self.last_media()?.connection_information = Some(connection);
1359 }
1360 b'b' => {
1361 let bandwidth = self.bandwidth(value)?;
1362 self.last_media()?.bandwidth.push(bandwidth);
1363 }
1364 b'k' => check_key(value)?,
1365 _ => {
1366 let attribute = parse_attribute(value)?;
1367 let media = self.last_media()?;
1368 if media.attributes.len() >= MAX_ATTRIBUTES_PER_SECTION {
1369 return Err(over_limit(
1370 "attributes in one media section",
1371 MAX_ATTRIBUTES_PER_SECTION,
1372 ));
1373 }
1374 media.attributes.push(attribute);
1375 }
1376 }
1377 Ok(())
1378 }
1379
1380 fn last_media(&mut self) -> Result<&mut MediaDescription> {
1381 self.desc
1382 .media_descriptions
1383 .last_mut()
1384 .ok_or(Error::SdpEmptyTimeDescription)
1385 }
1386
1387 fn text(&self, what: &str, value: &str) -> Result<String> {
1389 if !(grammar::is_byte_string(value) || self.options.loose_fields) {
1390 return Err(syntax(what, value));
1391 }
1392 Ok(value.to_owned())
1393 }
1394
1395 fn origin(&self, value: &str) -> Result<Origin> {
1397 let fields = self.fields("o=", value)?;
1398 let [
1399 username,
1400 session_id,
1401 session_version,
1402 network_type,
1403 address_type,
1404 address,
1405 ] = fields[..]
1406 else {
1407 return Err(syntax("o=", value));
1408 };
1409 if !grammar::is_non_ws_string(username)
1410 || !grammar::is_token(network_type)
1411 || !grammar::is_token(address_type)
1412 {
1413 return Err(syntax("o=", value));
1414 }
1415 let address_ok = if self.options.loose_fields {
1416 grammar::is_non_ws_string(address)
1417 } else {
1418 grammar::is_unicast_address(address_type, address)
1419 };
1420 if !address_ok {
1421 return Err(syntax("o= unicast-address", value));
1422 }
1423 Ok(Origin {
1424 username: username.to_owned(),
1425 session_id: SdpDecimal::parse(session_id)
1429 .ok_or_else(|| syntax("o= sess-id", session_id))?,
1430 session_version: SdpDecimal::parse(session_version)
1431 .ok_or_else(|| syntax("o= sess-version", session_version))?,
1432 network_type: network_type.to_owned(),
1433 address_type: address_type.to_owned(),
1434 unicast_address: address.to_owned(),
1435 })
1436 }
1437
1438 fn connection(&self, value: &str) -> Result<ConnectionInformation> {
1439 let fields = self.fields("c=", value)?;
1440 if !self.options.loose_fields {
1441 return ConnectionInformation::parse_fields(&fields, value);
1442 }
1443 if !(2..=3).contains(&fields.len())
1444 || !grammar::is_token(fields[0])
1445 || !grammar::is_token(fields[1])
1446 {
1447 return Err(syntax("c=", value));
1448 }
1449 Ok(ConnectionInformation {
1450 network_type: fields[0].to_owned(),
1451 address_type: fields[1].to_owned(),
1452 address: fields.get(2).map(|address| {
1453 Address::parse(fields[1], address).unwrap_or_else(|_| Address {
1455 address: (*address).to_owned(),
1456 ttl: None,
1457 range: None,
1458 })
1459 }),
1460 })
1461 }
1462
1463 fn bandwidth(&self, value: &str) -> Result<Bandwidth> {
1464 if self.options.loose_fields {
1465 Bandwidth::parse(value.trim())
1466 } else {
1467 Bandwidth::parse(value)
1468 }
1469 }
1470
1471 fn timing(&self, value: &str) -> Result<Timing> {
1473 let fields = self.fields("t=", value)?;
1474 let loose = self.options.loose_fields;
1475 if fields.len() < 2 || (fields.len() > 2 && !loose) {
1476 return Err(syntax("t=", value));
1477 }
1478 let time = |field: &str| -> Result<u64> {
1479 if !(loose || field == "0" || (grammar::is_integer(field) && field.len() >= 10)) {
1480 return Err(syntax("t=", value));
1481 }
1482 grammar::digits("t=", field)
1483 };
1484 Ok(Timing {
1485 start_time: time(fields[0])?,
1486 stop_time: time(fields[1])?,
1487 })
1488 }
1489
1490 fn repeat(&self, value: &str) -> Result<RepeatTime> {
1492 let fields = self.fields("r=", value)?;
1493 if fields.len() < 3 {
1494 return Err(syntax("r=", value));
1495 }
1496 if fields[0].starts_with('0') {
1498 return Err(syntax("r= repeat-interval", value));
1499 }
1500 let interval = parse_typed_time(fields[0])?;
1501 let duration = parse_typed_time(fields[1])?;
1502 let mut offsets = Vec::with_capacity(fields.len() - 2);
1503 for field in &fields[2..] {
1504 offsets.push(parse_typed_time(field)?);
1505 }
1506 Ok(RepeatTime {
1507 interval,
1508 duration,
1509 offsets,
1510 })
1511 }
1512
1513 fn zones(&self, value: &str) -> Result<Vec<TimeZone>> {
1515 let fields = self.fields("z=", value)?;
1516 if !fields.len().is_multiple_of(2) {
1517 return Err(syntax("z=", value));
1518 }
1519 let mut zones = Vec::with_capacity(fields.len() / 2);
1520 for pair in fields.chunks(2) {
1521 let time = pair[0];
1522 if !(self.options.loose_fields || (grammar::is_integer(time) && time.len() >= 10)) {
1523 return Err(syntax("z= adjustment time", value));
1524 }
1525 let adjustment_time = grammar::digits("z= adjustment time", time)?;
1526 let offset = match pair[1].strip_prefix('-') {
1527 Some(positive) => parse_typed_time(positive)?
1528 .checked_neg()
1529 .ok_or_else(|| invalid("z= offset", value))?,
1530 None => parse_typed_time(pair[1])?,
1531 };
1532 zones.push(TimeZone {
1533 adjustment_time,
1534 offset,
1535 });
1536 }
1537 Ok(zones)
1538 }
1539
1540 fn media_line(&mut self, value: &str) -> Result<()> {
1542 if self.desc.media_descriptions.len() >= MAX_MEDIA_DESCRIPTIONS {
1543 return Err(over_limit("media sections", MAX_MEDIA_DESCRIPTIONS));
1544 }
1545
1546 let fields = self.fields("m=", value)?;
1547 if fields.len() < 4 {
1548 return Err(syntax("m=", value));
1549 }
1550 if fields.len() - 3 > MAX_FORMATS_PER_MEDIA {
1551 return Err(over_limit("formats on one m= line", MAX_FORMATS_PER_MEDIA));
1552 }
1553
1554 if !grammar::is_token(fields[0]) {
1561 return Err(Error::SdpInvalidValue(fields[0].to_owned()));
1562 }
1563
1564 let (port, count) = match fields[1].split_once('/') {
1566 Some((port, count)) => (port, Some(count)),
1567 None => (fields[1], None),
1568 };
1569 let port_value = grammar::port(port)? as isize;
1570 let port_range = match count {
1571 Some(count) => {
1572 if !grammar::is_integer(count) {
1573 return Err(syntax("m= number of ports", value));
1574 }
1575 Some(
1576 count
1577 .parse::<u16>()
1578 .map_err(|_| invalid("m= number of ports", value))?
1579 as isize,
1580 )
1581 }
1582 None => None,
1583 };
1584
1585 let mut protos = vec![];
1592 for proto in fields[2].split('/') {
1593 if !grammar::is_token(proto) {
1594 return Err(Error::SdpInvalidValue(fields[2].to_owned()));
1595 }
1596 protos.push(proto.to_owned());
1597 }
1598
1599 let mut formats = Vec::with_capacity(fields.len() - 3);
1601 for field in &fields[3..] {
1602 if !grammar::is_token(field) {
1603 return Err(syntax("m= fmt", value));
1604 }
1605 formats.push((*field).to_owned());
1606 }
1607
1608 self.desc.media_descriptions.push(MediaDescription {
1609 media_name: MediaName {
1610 media: fields[0].to_owned(),
1611 port: RangedPort {
1612 value: port_value,
1613 range: port_range,
1614 },
1615 protos,
1616 formats,
1617 },
1618 media_title: None,
1619 connection_information: None,
1620 bandwidth: vec![],
1621 encryption_key: None,
1622 attributes: vec![],
1623 });
1624 Ok(())
1625 }
1626}
1627
1628pub(crate) fn parse_attribute(value: &str) -> Result<Attribute> {
1632 let (key, value) = match value.split_once(':') {
1633 Some((key, value)) => (key, Some(value)),
1634 None => (value, None),
1635 };
1636 if !grammar::is_token(key) {
1637 return Err(syntax("attribute name", key));
1638 }
1639 Ok(Attribute {
1640 key: key.to_owned(),
1641 value: value.map(str::to_owned),
1642 })
1643}
1644
1645fn check_key(value: &str) -> Result<()> {
1648 let ok = if value == "prompt" {
1649 true
1650 } else if let Some(text) = value.strip_prefix("clear:") {
1651 grammar::is_byte_string(text)
1652 } else if let Some(key) = value.strip_prefix("base64:") {
1653 grammar::is_base64(key)
1654 } else if let Some(uri) = value.strip_prefix("uri:") {
1655 grammar::is_non_ws_string(uri)
1656 } else {
1657 false
1658 };
1659 if ok {
1660 Ok(())
1661 } else {
1662 Err(Error::SdpInvalidSyntax("k= line".to_owned()))
1664 }
1665}
1666
1667fn is_email_safe(value: &str) -> bool {
1669 !value.is_empty()
1670 && !value
1671 .bytes()
1672 .any(|b| matches!(b, 0 | b'\r' | b'\n' | b'(' | b')' | b'<' | b'>'))
1673}
1674
1675fn is_atext(b: u8) -> bool {
1677 b.is_ascii_alphanumeric() || b"!#$%&'*+-/=?^_`{|}~".contains(&b)
1678}
1679
1680fn is_dot_atom(value: &str) -> bool {
1682 !value.is_empty()
1683 && value
1684 .split('.')
1685 .all(|atom| !atom.is_empty() && atom.bytes().all(is_atext))
1686}
1687
1688fn is_addr_spec(value: &str) -> bool {
1692 let bytes = value.as_bytes();
1693 let at = if bytes.first() == Some(&b'"') {
1694 let mut i = 1;
1696 loop {
1697 match bytes.get(i) {
1698 Some(b'"') => break i + 1,
1699 Some(b'\\') if matches!(bytes.get(i + 1), Some(0x20..=0x7e | b'\t')) => i += 2,
1700 Some(b' ' | b'\t' | 0x21 | 0x23..=0x5b | 0x5d..=0x7e) => i += 1,
1701 _ => return false,
1702 }
1703 }
1704 } else {
1705 match value.find('@') {
1706 Some(at) if is_dot_atom(&value[..at]) => at,
1707 _ => return false,
1708 }
1709 };
1710 if bytes.get(at) != Some(&b'@') {
1711 return false;
1712 }
1713 let domain = &value[at + 1..];
1714 match domain.strip_prefix('[').and_then(|d| d.strip_suffix(']')) {
1715 Some(literal) => literal
1717 .bytes()
1718 .all(|b| matches!(b, 0x21..=0x5a | 0x5e..=0x7e)),
1719 None => is_dot_atom(domain),
1720 }
1721}
1722
1723fn is_email_address(value: &str) -> bool {
1725 if let Some(rest) = value.strip_suffix(')') {
1726 let Some((address, comment)) = rest.split_once('(') else {
1728 return false;
1729 };
1730 let spec = address.trim_end_matches(' ');
1731 return spec.len() < address.len() && is_addr_spec(spec) && is_email_safe(comment);
1732 }
1733 if let Some(rest) = value.strip_suffix('>') {
1734 let Some((name, address)) = rest.split_once('<') else {
1736 return false;
1737 };
1738 return name.ends_with(' ')
1739 && is_email_safe(name.trim_end_matches(' '))
1740 && is_addr_spec(address);
1741 }
1742 is_addr_spec(value)
1743}
1744
1745fn is_phone(value: &str) -> bool {
1747 let digits = value.strip_prefix('+').unwrap_or(value).as_bytes();
1748 digits.len() >= 2
1749 && digits[0].is_ascii_digit()
1750 && digits[1..]
1751 .iter()
1752 .all(|b| b.is_ascii_digit() || *b == b' ' || *b == b'-')
1753}
1754
1755fn is_phone_number(value: &str) -> bool {
1757 if let Some(rest) = value.strip_suffix(')') {
1758 let Some((phone, comment)) = rest.split_once('(') else {
1759 return false;
1760 };
1761 return is_phone(phone) && is_email_safe(comment);
1763 }
1764 if let Some(rest) = value.strip_suffix('>') {
1765 let Some((name, phone)) = rest.split_once('<') else {
1766 return false;
1767 };
1768 return is_email_safe(name) && is_phone(phone);
1769 }
1770 is_phone(value)
1771}
1772
1773fn parse_typed_time(value: &str) -> Result<i64> {
1777 let (number, factor) = match value.as_bytes().last() {
1778 Some(b'd') => (&value[..value.len() - 1], 86400),
1779 Some(b'h') => (&value[..value.len() - 1], 3600),
1780 Some(b'm') => (&value[..value.len() - 1], 60),
1781 Some(b's') => (&value[..value.len() - 1], 1),
1782 _ => (value, 1),
1783 };
1784 grammar::digits::<i64>("typed-time", number)?
1785 .checked_mul(factor)
1786 .ok_or_else(|| invalid("typed-time", value))
1787}