use std::fmt;
use sdp::description::session::SessionDescription;
use sdp::util::ConnectionRole;
use serde::{Deserialize, Serialize};
use shared::error::{Error, Result};
#[derive(Default, Debug, Copy, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub enum RTCDtlsRole {
#[default]
Unspecified = 0,
#[serde(rename = "auto")]
Auto = 1,
#[serde(rename = "client")]
Client = 2,
#[serde(rename = "server")]
Server = 3,
}
pub(crate) const DEFAULT_DTLS_ROLE_ANSWER: RTCDtlsRole = RTCDtlsRole::Client;
pub(crate) const DEFAULT_DTLS_ROLE_OFFER: RTCDtlsRole = RTCDtlsRole::Auto;
impl fmt::Display for RTCDtlsRole {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match *self {
RTCDtlsRole::Auto => write!(f, "auto"),
RTCDtlsRole::Client => write!(f, "client"),
RTCDtlsRole::Server => write!(f, "server"),
_ => write!(
f,
"{}",
crate::peer_connection::configuration::UNSPECIFIED_STR
),
}
}
}
impl From<&SessionDescription> for RTCDtlsRole {
fn from(session_description: &SessionDescription) -> Self {
let tagged = session_description
.media_descriptions
.iter()
.find_map(|media| {
crate::peer_connection::sdp::tagged_section(session_description, media)
})
.and_then(|tagged| tagged.attributes.iter().find(|a| a.key == "setup"));
let media_level = tagged.or_else(|| {
session_description
.media_descriptions
.iter()
.flat_map(|media_section| media_section.attributes.iter())
.find(|attribute| attribute.key == "setup")
});
let session_level = session_description
.attributes
.iter()
.find(|attribute| attribute.key == "setup");
match media_level
.or(session_level)
.and_then(|attribute| attribute.value.as_deref())
{
Some("active") => RTCDtlsRole::Client,
Some("passive") => RTCDtlsRole::Server,
_ => RTCDtlsRole::Auto,
}
}
}
pub(crate) fn validate_setup_attributes(session_description: &SessionDescription) -> Result<()> {
let check = |attributes: &[sdp::description::common::Attribute]| -> Result<()> {
let mut stated = None;
for attribute in attributes.iter().filter(|a| a.key == "setup") {
let value = attribute.value.as_deref();
if !matches!(value, Some("active" | "passive" | "actpass"))
|| stated.is_some_and(|stated| stated != value)
{
return Err(Error::ErrSessionDescriptionInvalidSetup);
}
stated = Some(value);
}
Ok(())
};
check(&session_description.attributes)?;
session_description
.media_descriptions
.iter()
.try_for_each(|media_section| check(&media_section.attributes))
}
impl RTCDtlsRole {
pub(crate) fn to_connection_role(self) -> ConnectionRole {
match self {
RTCDtlsRole::Client => ConnectionRole::Active,
RTCDtlsRole::Server => ConnectionRole::Passive,
RTCDtlsRole::Auto => ConnectionRole::Actpass,
_ => ConnectionRole::Unspecified,
}
}
}
#[cfg(test)]
mod test {
use std::io::Cursor;
use super::*;
#[test]
fn test_dtls_role_string() {
let tests = vec![
(RTCDtlsRole::Unspecified, "Unspecified"),
(RTCDtlsRole::Auto, "auto"),
(RTCDtlsRole::Client, "client"),
(RTCDtlsRole::Server, "server"),
];
for (role, expected_string) in tests {
assert_eq!(role.to_string(), expected_string)
}
}
#[test]
fn with_bundle_the_tagged_sections_setup_is_the_role() -> Result<()> {
let head = "v=0\r\no=- 1 2 IN IP4 0.0.0.0\r\ns=-\r\nt=0 0\r\n";
let section = |port: u16, mid: &str, setup: &str| {
format!(
"m=audio {port} UDP/TLS/RTP/SAVPF 111\r\nc=IN IP4 0.0.0.0\r\na=mid:{mid}\r\n\
a=setup:{setup}\r\n"
)
};
let role = |sdp: String| -> Result<RTCDtlsRole> {
let mut reader = Cursor::new(sdp.into_bytes());
Ok(RTCDtlsRole::from(&SessionDescription::unmarshal(
&mut reader,
)?))
};
assert_eq!(
role(format!(
"{head}a=group:BUNDLE 1 0\r\n{}{}",
section(9, "0", "active"),
section(9, "1", "passive")
))?,
RTCDtlsRole::Server
);
assert_eq!(
role(format!(
"{head}a=group:BUNDLE 1 0\r\n{}{}",
section(9, "0", "active"),
section(0, "1", "passive")
))?,
RTCDtlsRole::Client,
"a rejected tag is not the tagged section"
);
assert_eq!(
role(format!(
"{head}a=group:BUNDLE 1\r\n{}{}",
section(9, "0", "active"),
section(9, "1", "passive")
))?,
RTCDtlsRole::Server,
"the section outside the group does not decide"
);
Ok(())
}
#[test]
fn test_dtls_role_from_remote_sdp() -> Result<()> {
const NO_MEDIA: &str = "v=0
o=- 4596489990601351948 2 IN IP4 127.0.0.1
s=-
t=0 0
";
const MEDIA_NO_SETUP: &str = "v=0
o=- 4596489990601351948 2 IN IP4 127.0.0.1
s=-
t=0 0
m=application 47299 DTLS/SCTP 5000
c=IN IP4 192.168.20.129
";
const MEDIA_SETUP_DECLARED: &str = "v=0
o=- 4596489990601351948 2 IN IP4 127.0.0.1
s=-
t=0 0
m=application 47299 DTLS/SCTP 5000
c=IN IP4 192.168.20.129
a=setup:";
const SESSION_SETUP_PASSIVE: &str = "v=0
o=- 4596489990601351948 2 IN IP4 127.0.0.1
s=-
t=0 0
a=setup:passive
m=application 47299 DTLS/SCTP 5000
c=IN IP4 192.168.20.129
";
let tests = vec![
(
"No MediaDescriptions",
NO_MEDIA.to_owned(),
RTCDtlsRole::Auto,
),
(
"MediaDescription, no setup",
MEDIA_NO_SETUP.to_owned(),
RTCDtlsRole::Auto,
),
(
"MediaDescription, setup:actpass",
format!("{}{}\n", MEDIA_SETUP_DECLARED, "actpass"),
RTCDtlsRole::Auto,
),
(
"MediaDescription, setup:passive",
format!("{}{}\n", MEDIA_SETUP_DECLARED, "passive"),
RTCDtlsRole::Server,
),
(
"MediaDescription, setup:active",
format!("{}{}\n", MEDIA_SETUP_DECLARED, "active"),
RTCDtlsRole::Client,
),
(
"Session-level setup:passive",
SESSION_SETUP_PASSIVE.to_owned(),
RTCDtlsRole::Server,
),
(
"Session-level setup:passive, no MediaDescriptions",
format!("{NO_MEDIA}a=setup:passive\n"),
RTCDtlsRole::Server,
),
(
"Session-level setup:passive, MediaDescription setup:active",
format!("{SESSION_SETUP_PASSIVE}a=setup:active\n"),
RTCDtlsRole::Client,
),
];
for (name, session_description_str, expected_role) in tests {
let mut reader = Cursor::new(session_description_str.as_bytes());
let session_description = SessionDescription::unmarshal(&mut reader)?;
assert_eq!(
RTCDtlsRole::from(&session_description),
expected_role,
"{name} failed"
);
}
Ok(())
}
fn parse(sdp: &str) -> SessionDescription {
SessionDescription::unmarshal(&mut Cursor::new(sdp.as_bytes())).unwrap()
}
const TWO_SECTIONS: &str = "v=0
o=- 4596489990601351948 2 IN IP4 127.0.0.1
s=-
t=0 0
SESSION
m=audio 9 UDP/TLS/RTP/SAVPF 111
c=IN IP4 0.0.0.0
FIRST
m=application 9 UDP/DTLS/SCTP webrtc-datachannel
c=IN IP4 0.0.0.0
SECOND
";
fn with_lines(session: &str, first: &str, second: &str) -> SessionDescription {
parse(
&TWO_SECTIONS
.replace("SESSION\n", session)
.replace("FIRST\n", first)
.replace("SECOND\n", second),
)
}
fn two_sections(session: &str, first: &str, second: &str) -> SessionDescription {
let line = |value: &str| {
if value.is_empty() {
String::new()
} else {
format!("a=setup:{value}\n")
}
};
with_lines(&line(session), &line(first), &line(second))
}
#[test]
fn setup_holdconn_and_unknown_values_are_refused() {
for (session, first, second) in [
("", "holdconn", ""),
("holdconn", "", ""),
("holdconn", "active", "active"),
("", "active", "holdconn"),
("", "both", ""),
("", "ACTIVE", ""),
] {
assert_eq!(
validate_setup_attributes(&two_sections(session, first, second)),
Err(Error::ErrSessionDescriptionInvalidSetup),
"session {session:?}, sections {first:?} / {second:?}"
);
}
let valueless = with_lines("a=setup\n", "", "");
assert_eq!(
validate_setup_attributes(&valueless),
Err(Error::ErrSessionDescriptionInvalidSetup)
);
}
#[test]
fn valid_setup_values_are_accepted() {
for (session, first, second) in [
("", "", ""),
("", "actpass", "actpass"),
("", "active", "active"),
("", "passive", ""),
("passive", "", ""),
("passive", "active", "active"),
("actpass", "", "passive"),
] {
assert_eq!(
validate_setup_attributes(&two_sections(session, first, second)),
Ok(()),
"session {session:?}, sections {first:?} / {second:?}"
);
}
let twice = with_lines("", "a=setup:active\na=setup:passive\n", "");
assert_eq!(
validate_setup_attributes(&twice),
Err(Error::ErrSessionDescriptionInvalidSetup)
);
}
}