use crate::peer_connection::certificate::RTCCertificate;
pub use crate::peer_connection::transport::ice::server::RTCIceServer;
use serde::{Deserialize, Serialize};
use shared::error::{Error, Result};
use std::time::SystemTime;
pub mod behaviour_profile;
pub(crate) mod bundle_policy;
pub(crate) mod ice_transport_policy;
pub mod interceptor_registry;
pub mod media_engine;
pub(crate) mod offer_answer_options;
pub mod remote_bitrate_limit;
pub(crate) mod rtcp_mux_policy;
pub(crate) mod sdp_semantics;
pub mod setting_engine;
pub use behaviour_profile::BehaviourProfile;
pub use bundle_policy::RTCBundlePolicy;
pub use ice_transport_policy::{ICEGatherPolicy, RTCIceTransportPolicy};
pub use offer_answer_options::{RTCAnswerOptions, RTCOfferOptions};
pub use rtcp_mux_policy::RTCRtcpMuxPolicy;
pub use sdp_semantics::RTCSdpSemantics;
pub(crate) const UNSPECIFIED_STR: &str = "Unspecified";
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
#[serde(default, rename_all = "camelCase")]
pub struct RTCConfiguration {
pub(crate) ice_servers: Vec<RTCIceServer>,
pub(crate) ice_transport_policy: RTCIceTransportPolicy,
pub(crate) bundle_policy: RTCBundlePolicy,
pub(crate) rtcp_mux_policy: RTCRtcpMuxPolicy,
pub(crate) peer_identity: String,
#[serde(skip)]
pub(crate) certificates: Vec<RTCCertificate>,
pub(crate) ice_candidate_pool_size: u8,
pub(crate) rtp_header_encryption_policy:
crate::peer_connection::cryptex::RTCRtpHeaderEncryptionPolicy,
pub(crate) always_negotiate_data_channels: bool,
}
impl RTCConfiguration {
pub fn ice_servers(&self) -> &[RTCIceServer] {
&self.ice_servers
}
pub fn ice_transport_policy(&self) -> RTCIceTransportPolicy {
self.ice_transport_policy
}
pub fn bundle_policy(&self) -> RTCBundlePolicy {
self.bundle_policy
}
pub fn rtcp_mux_policy(&self) -> RTCRtcpMuxPolicy {
self.rtcp_mux_policy
}
pub fn rtp_header_encryption_policy(
&self,
) -> crate::peer_connection::cryptex::RTCRtpHeaderEncryptionPolicy {
self.rtp_header_encryption_policy
}
pub fn always_negotiate_data_channels(&self) -> bool {
self.always_negotiate_data_channels
}
pub fn peer_identity(&self) -> &str {
&self.peer_identity
}
pub fn certificates(&self) -> &[RTCCertificate] {
&self.certificates
}
pub fn ice_candidate_pool_size(&self) -> u8 {
self.ice_candidate_pool_size
}
#[allow(clippy::assigning_clones)]
fn get_ice_servers(&self) -> Vec<RTCIceServer> {
let mut ice_servers = self.ice_servers.clone();
for ice_server in &mut ice_servers {
for raw_url in &mut ice_server.urls {
if raw_url.starts_with("stun") {
let parts: Vec<&str> = raw_url.split('?').collect();
*raw_url = parts[0].to_owned();
}
}
}
ice_servers
}
pub(crate) fn validate(&mut self) -> Result<()> {
if !self.certificates.is_empty() {
let now = SystemTime::now(); for cert in &self.certificates {
cert.expires
.duration_since(now)
.map_err(|_| Error::ErrCertificateExpired)?;
}
}
self.set_the_configuration(None, false)
}
pub(crate) fn set_the_configuration(
&mut self,
old: Option<&RTCConfiguration>,
local_description_was_set: bool,
) -> Result<()> {
if let Some(old) = old {
if self.certificates.len() != old.certificates.len()
|| self
.certificates
.iter()
.zip(&old.certificates)
.any(|(new, old)| new != old || new.expires != old.expires)
{
return Err(Error::ErrModifyingCertificates);
}
if self.bundle_policy != old.bundle_policy {
return Err(Error::ErrModifyingBundlePolicy);
}
if self.rtcp_mux_policy != old.rtcp_mux_policy {
return Err(Error::ErrModifyingRTCPMuxPolicy);
}
if self.rtp_header_encryption_policy != old.rtp_header_encryption_policy
|| self.always_negotiate_data_channels != old.always_negotiate_data_channels
{
return Err(Error::InvalidModificationError);
}
if self.ice_candidate_pool_size != old.ice_candidate_pool_size
&& local_description_was_set
{
return Err(Error::ErrModifyingICECandidatePoolSize);
}
}
self.ice_servers.truncate(MAX_ICE_SERVERS);
for server in &self.ice_servers {
server.validate()?;
}
if self.ice_transport_policy == RTCIceTransportPolicy::Relay {
let mut has_turn = false;
for server in &self.get_ice_servers() {
if server.urls()?.iter().any(|url| {
url.scheme == ice::url::SchemeType::Turn
|| url.scheme == ice::url::SchemeType::Turns
}) {
has_turn = true;
break;
}
}
if !has_turn {
log::warn!(
"Relay-only ICE transport policy configured, but no TURN/TURNS servers are \
available; only relay candidates the application adds itself can be used"
);
}
}
Ok(())
}
}
pub const MAX_ICE_SERVERS: usize = 32;
#[derive(Default)]
pub struct RTCConfigurationBuilder(RTCConfiguration);
impl RTCConfigurationBuilder {
pub fn new() -> Self {
Self::default()
}
pub fn with_ice_servers(mut self, ice_servers: Vec<RTCIceServer>) -> Self {
self.0.ice_servers = ice_servers;
self
}
pub fn with_ice_transport_policy(
mut self,
ice_transport_policy: RTCIceTransportPolicy,
) -> Self {
self.0.ice_transport_policy = ice_transport_policy;
self
}
pub fn with_bundle_policy(mut self, bundle_policy: RTCBundlePolicy) -> Self {
self.0.bundle_policy = bundle_policy;
self
}
pub fn with_rtcp_mux_policy(mut self, rtcp_mux_policy: RTCRtcpMuxPolicy) -> Self {
self.0.rtcp_mux_policy = rtcp_mux_policy;
self
}
pub fn with_peer_identitys(mut self, peer_identity: String) -> Self {
self.0.peer_identity = peer_identity;
self
}
pub fn with_certificates(mut self, certificates: Vec<RTCCertificate>) -> Self {
self.0.certificates = certificates;
self
}
pub fn with_ice_candidate_pool_size(mut self, ice_candidate_pool_size: u8) -> Self {
self.0.ice_candidate_pool_size = ice_candidate_pool_size;
self
}
pub fn with_rtp_header_encryption_policy(
mut self,
policy: crate::peer_connection::cryptex::RTCRtpHeaderEncryptionPolicy,
) -> Self {
self.0.rtp_header_encryption_policy = policy;
self
}
pub fn with_always_negotiate_data_channels(mut self, always: bool) -> Self {
self.0.always_negotiate_data_channels = always;
self
}
pub fn build(self) -> RTCConfiguration {
self.0
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_configuration_get_iceservers() {
{
let expected_server_str = "stun:stun.l.google.com:19302";
let cfg = RTCConfigurationBuilder::new()
.with_ice_servers(vec![RTCIceServer {
urls: vec![expected_server_str.to_owned()],
..Default::default()
}])
.build();
let parsed_urls = cfg.get_ice_servers();
assert_eq!(parsed_urls[0].urls[0], expected_server_str);
}
{
let server_str = "stun:global.stun.twilio.com:3478?transport=udp";
let expected_server_str = "stun:global.stun.twilio.com:3478";
let cfg = RTCConfigurationBuilder::new()
.with_ice_servers(vec![RTCIceServer {
urls: vec![server_str.to_owned()],
..Default::default()
}])
.build();
let parsed_urls = cfg.get_ice_servers();
assert_eq!(parsed_urls[0].urls[0], expected_server_str);
}
}
#[test]
fn test_configuration_validate_relay_policy() {
let mut cfg = RTCConfigurationBuilder::new()
.with_ice_transport_policy(RTCIceTransportPolicy::Relay)
.build();
assert!(cfg.validate().is_ok());
let mut cfg = RTCConfigurationBuilder::new()
.with_ice_transport_policy(RTCIceTransportPolicy::Relay)
.with_ice_servers(vec![RTCIceServer {
urls: vec!["stun:stun.l.google.com:19302".to_owned()],
..Default::default()
}])
.build();
assert!(cfg.validate().is_ok());
let mut cfg = RTCConfigurationBuilder::new()
.with_ice_transport_policy(RTCIceTransportPolicy::Relay)
.with_ice_servers(vec![RTCIceServer {
urls: vec!["turn:turn.example.com:3478".to_owned()],
username: "user".to_owned(),
credential: "pass".to_owned(),
}])
.build();
assert!(cfg.validate().is_ok());
}
#[test]
fn test_configuration_json_round_trip() {
let kp = rcgen::KeyPair::generate_for(&rcgen::PKCS_ECDSA_P256_SHA256)
.expect("generate key pair");
let cert = RTCCertificate::from_key_pair(kp).expect("create certificate");
let original = RTCConfigurationBuilder::new()
.with_ice_servers(vec![RTCIceServer {
urls: vec!["stun:stun.l.google.com:19302".to_owned()],
..Default::default()
}])
.with_ice_transport_policy(RTCIceTransportPolicy::All)
.with_bundle_policy(RTCBundlePolicy::MaxBundle)
.with_rtcp_mux_policy(RTCRtcpMuxPolicy::Require)
.with_certificates(vec![cert])
.build();
assert_eq!(original.certificates.len(), 1);
let json = serde_json::to_string(&original).expect("serialize");
let value: serde_json::Value = serde_json::from_str(&json).expect("parse json");
assert_eq!(
value["iceServers"][0]["urls"][0],
serde_json::Value::String("stun:stun.l.google.com:19302".to_owned())
);
assert_eq!(
value["iceTransportPolicy"],
serde_json::Value::String("all".to_owned())
);
assert_eq!(
value["bundlePolicy"],
serde_json::Value::String("max-bundle".to_owned())
);
assert_eq!(
value["rtcpMuxPolicy"],
serde_json::Value::String("require".to_owned())
);
assert!(
value.get("certificates").is_none(),
"certificates should be omitted from JSON (serde skip)"
);
let restored: RTCConfiguration = serde_json::from_str(&json).expect("deserialize");
assert_eq!(restored.ice_servers.len(), 1);
assert_eq!(
restored.ice_servers[0].urls[0],
"stun:stun.l.google.com:19302"
);
assert_eq!(restored.ice_transport_policy, RTCIceTransportPolicy::All);
assert_eq!(restored.bundle_policy, RTCBundlePolicy::MaxBundle);
assert_eq!(restored.rtcp_mux_policy, RTCRtcpMuxPolicy::Require);
assert!(restored.certificates.is_empty());
}
#[test]
fn test_configuration_json_partial_deserialize() {
let json = r#"{"iceServers":[{"urls":["stun:stun.l.google.com:19302"]}]}"#;
let config: RTCConfiguration = serde_json::from_str(json).expect("partial deserialize");
assert_eq!(config.ice_servers.len(), 1);
assert_eq!(
config.ice_servers[0].urls[0],
"stun:stun.l.google.com:19302"
);
assert_eq!(config.ice_transport_policy, RTCIceTransportPolicy::All);
assert_eq!(config.bundle_policy, RTCBundlePolicy::Balanced);
assert_eq!(config.rtcp_mux_policy, RTCRtcpMuxPolicy::Require);
let json = serde_json::to_value(RTCConfigurationBuilder::new().build()).expect("json");
assert_eq!(json["iceTransportPolicy"], "all");
assert_eq!(json["bundlePolicy"], "balanced");
assert_eq!(json["rtcpMuxPolicy"], "require");
assert!(config.certificates.is_empty());
assert_eq!(config.ice_candidate_pool_size, 0);
}
}