use crate::util::{
AssociationIdGenerator, RandomAssociationIdGenerator, RandomSource,
SourcedAssociationIdGenerator,
};
use crate::association::pmtud::PathMtuDiscoveryConfig;
use crate::{RtoConfig, TimerConfig};
use std::fmt;
use std::sync::Arc;
use std::time::Duration;
pub(crate) const MIN_ADVERTISED_RECEIVER_WINDOW: u32 = 1500;
pub(crate) const RECEIVE_MTU: usize = 8192;
pub(crate) const INITIAL_MTU: u32 = 1191;
pub(crate) const INITIAL_RECV_BUF_SIZE: u32 = 1024 * 1024;
pub(crate) const COMMON_HEADER_SIZE: u32 = 12;
pub(crate) const DATA_CHUNK_HEADER_SIZE: u32 = 16;
pub const MIN_DATA_PACKET_MTU: u32 = COMMON_HEADER_SIZE + DATA_CHUNK_HEADER_SIZE + 4;
pub fn max_payload_size_for_mtu(mtu: u32) -> u32 {
if mtu < MIN_DATA_PACKET_MTU {
log::warn!(
"sctp mtu {mtu} is below the smallest representable DATA packet; raising to \
{MIN_DATA_PACKET_MTU} bytes"
);
}
let mtu = mtu.max(MIN_DATA_PACKET_MTU);
(mtu - (COMMON_HEADER_SIZE + DATA_CHUNK_HEADER_SIZE)) & !3
}
pub(crate) const DEFAULT_MAX_MESSAGE_SIZE: u32 = 262144;
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum StreamScheduler {
#[default]
FirstComeFirstServed,
RoundRobin,
RoundRobinPerPacket,
Priority,
FairCapacity,
WeightedFairQueueing,
}
#[derive(Debug, Clone)]
pub struct TransportConfig {
sctp_port: u16,
remote_sctp_port: u16,
max_receive_buffer_size: u32,
max_message_size: u32,
max_receive_message_size: Option<u32>,
max_num_outbound_streams: u16,
max_num_inbound_streams: u16,
timer_config: TimerConfig,
rto_config: RtoConfig,
stream_scheduler: StreamScheduler,
valid_cookie_life: Duration,
heartbeat_interval: Option<Duration>,
slow_start_growth_limit: u32,
max_burst: Option<u32>,
sack_delay: Duration,
partial_reliability: bool,
message_interleaving: bool,
zero_checksum: bool,
path_mtu_discovery: Option<PathMtuDiscoveryConfig>,
zero_window_overcommit: bool,
zero_window_renege: bool,
partial_delivery_point: Option<u32>,
no_fragmentation: bool,
handshake_timers_back_off_rto: bool,
}
impl Default for TransportConfig {
fn default() -> Self {
TransportConfig {
sctp_port: 5000,
remote_sctp_port: 5000,
max_receive_buffer_size: INITIAL_RECV_BUF_SIZE,
max_message_size: DEFAULT_MAX_MESSAGE_SIZE,
max_receive_message_size: None,
max_num_outbound_streams: u16::MAX,
max_num_inbound_streams: u16::MAX,
timer_config: TimerConfig::default(),
rto_config: RtoConfig::default(),
stream_scheduler: StreamScheduler::default(),
valid_cookie_life: Duration::from_secs(60),
heartbeat_interval: Some(Duration::from_secs(30)),
slow_start_growth_limit: 1,
max_burst: Some(4),
sack_delay: Duration::from_millis(200),
partial_reliability: true,
message_interleaving: false,
zero_checksum: false,
path_mtu_discovery: None,
zero_window_overcommit: false,
zero_window_renege: false,
partial_delivery_point: None,
no_fragmentation: false,
handshake_timers_back_off_rto: true,
}
}
}
impl TransportConfig {
pub fn with_zero_window_overcommit(mut self, value: bool) -> Self {
self.zero_window_overcommit = value;
self
}
pub fn zero_window_overcommit(&self) -> bool {
self.zero_window_overcommit
}
pub fn with_zero_window_renege(mut self, value: bool) -> Self {
self.zero_window_renege = value;
self
}
pub fn zero_window_renege(&self) -> bool {
self.zero_window_renege
}
pub fn with_partial_delivery_point(mut self, value: u32) -> Self {
self.partial_delivery_point = Some(value);
self
}
pub fn with_fragmentation(mut self, enabled: bool) -> Self {
self.no_fragmentation = !enabled;
self
}
pub fn fragmentation(&self) -> bool {
!self.no_fragmentation
}
pub fn partial_delivery_point(&self) -> u32 {
self.partial_delivery_point
.unwrap_or(self.max_receive_buffer_size / 2)
.clamp(1, self.max_receive_buffer_size.max(1))
}
pub fn with_path_mtu_discovery(mut self, value: Option<PathMtuDiscoveryConfig>) -> Self {
self.path_mtu_discovery = value;
self
}
pub fn path_mtu_discovery(&self) -> Option<PathMtuDiscoveryConfig> {
self.path_mtu_discovery
}
pub fn with_slow_start_growth_limit(mut self, value: u32) -> Self {
self.slow_start_growth_limit = value.max(1);
self
}
pub fn slow_start_growth_limit(&self) -> u32 {
self.slow_start_growth_limit
}
pub fn with_partial_reliability(mut self, value: bool) -> Self {
self.partial_reliability = value;
self
}
pub fn partial_reliability(&self) -> bool {
self.partial_reliability
}
pub fn with_message_interleaving(mut self, value: bool) -> Self {
self.message_interleaving = value;
self
}
pub fn message_interleaving(&self) -> bool {
self.message_interleaving
}
pub fn with_zero_checksum(mut self, value: bool) -> Self {
self.zero_checksum = value;
self
}
pub fn zero_checksum(&self) -> bool {
self.zero_checksum
}
pub fn with_sack_delay(mut self, value: Duration) -> Self {
self.sack_delay = value.min(Duration::from_millis(500));
self
}
pub fn sack_delay(&self) -> Duration {
self.sack_delay
}
pub fn with_max_burst(mut self, value: Option<u32>) -> Self {
self.max_burst = value;
self
}
pub fn max_burst(&self) -> Option<u32> {
self.max_burst
}
pub fn with_heartbeat_interval(mut self, value: Option<Duration>) -> Self {
self.heartbeat_interval = value;
self
}
pub fn heartbeat_interval(&self) -> Option<Duration> {
self.heartbeat_interval
}
pub fn with_valid_cookie_life(mut self, value: Duration) -> Self {
self.valid_cookie_life = value;
self
}
pub fn valid_cookie_life(&self) -> Duration {
self.valid_cookie_life
}
pub fn with_sctp_port(mut self, value: u16) -> Self {
self.sctp_port = value;
self
}
pub fn with_remote_sctp_port(mut self, value: u16) -> Self {
self.remote_sctp_port = value;
self
}
pub fn with_max_receive_buffer_size(mut self, value: u32) -> Self {
self.max_receive_buffer_size = value.max(MIN_ADVERTISED_RECEIVER_WINDOW);
self
}
pub fn with_max_message_size(mut self, value: u32) -> Self {
self.max_message_size = value;
self
}
pub fn with_max_receive_message_size(mut self, value: u32) -> Self {
self.max_receive_message_size = Some(value);
self
}
pub fn with_max_num_outbound_streams(mut self, value: u16) -> Self {
self.max_num_outbound_streams = value.max(1);
self
}
pub fn with_max_num_inbound_streams(mut self, value: u16) -> Self {
self.max_num_inbound_streams = value.max(1);
self
}
pub fn with_handshake_timers_back_off_rto(mut self, value: bool) -> Self {
self.handshake_timers_back_off_rto = value;
self
}
pub fn handshake_timers_back_off_rto(&self) -> bool {
self.handshake_timers_back_off_rto
}
pub fn with_timer_config(mut self, value: TimerConfig) -> Self {
self.timer_config = value;
self
}
pub fn with_rto_config(mut self, value: RtoConfig) -> Self {
self.rto_config = value;
self
}
pub fn with_stream_scheduler(mut self, value: StreamScheduler) -> Self {
self.stream_scheduler = value;
self
}
pub fn sctp_port(&self) -> u16 {
self.sctp_port
}
pub fn remote_sctp_port(&self) -> u16 {
self.remote_sctp_port
}
pub fn max_receive_buffer_size(&self) -> u32 {
self.max_receive_buffer_size
}
pub fn max_message_size(&self) -> u32 {
self.max_message_size
}
pub fn max_receive_message_size(&self) -> u32 {
self.max_receive_message_size
.unwrap_or(self.max_message_size)
}
pub fn max_num_outbound_streams(&self) -> u16 {
self.max_num_outbound_streams
}
pub fn max_num_inbound_streams(&self) -> u16 {
self.max_num_inbound_streams
}
pub fn timer_config(&self) -> TimerConfig {
self.timer_config
}
pub fn rto_config(&self) -> RtoConfig {
self.rto_config
}
pub fn stream_scheduler(&self) -> StreamScheduler {
self.stream_scheduler
}
}
#[derive(Clone)]
pub struct EndpointConfig {
pub(crate) max_payload_size: u32,
pub(crate) aid_generator_factory:
Arc<dyn (Fn() -> Box<dyn AssociationIdGenerator + Send>) + Send + Sync>,
pub(crate) random: RandomSource,
}
impl Default for EndpointConfig {
fn default() -> Self {
Self::new()
}
}
impl EndpointConfig {
pub fn new() -> Self {
let aid_factory: fn() -> Box<dyn AssociationIdGenerator + Send> =
|| Box::<RandomAssociationIdGenerator>::default();
Self {
max_payload_size: max_payload_size_for_mtu(INITIAL_MTU),
aid_generator_factory: Arc::new(aid_factory),
random: RandomSource::default(),
}
}
pub fn random_source(&mut self, provider: Arc<dyn crypto::RTCCryptoProvider>) -> &mut Self {
let random = RandomSource::new(Some(provider));
self.random = random.clone();
self.aid_generator_factory = Arc::new(move || {
Box::new(SourcedAssociationIdGenerator(random.clone()))
as Box<dyn AssociationIdGenerator + Send>
});
self
}
pub fn aid_generator<
F: Fn() -> Box<dyn AssociationIdGenerator + Send> + Send + Sync + 'static,
>(
&mut self,
factory: F,
) -> &mut Self {
self.aid_generator_factory = Arc::new(factory);
self
}
pub fn max_payload_size(&mut self, value: u32) -> &mut Self {
self.max_payload_size = value;
self
}
pub fn get_max_payload_size(&self) -> u32 {
self.max_payload_size
}
}
impl fmt::Debug for EndpointConfig {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt.debug_struct("EndpointConfig")
.field("max_payload_size", &self.max_payload_size)
.field("aid_generator_factory", &"[ elided ]")
.field("random", &self.random)
.finish()
}
}
#[derive(Clone)]
pub struct ServerConfig {
pub transport: Arc<TransportConfig>,
pub(crate) concurrent_associations: u32,
pub(crate) cookie_provider: Option<Arc<dyn crypto::RTCCryptoProvider>>,
}
impl fmt::Debug for ServerConfig {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt.debug_struct("ServerConfig")
.field("transport", &self.transport)
.field("concurrent_associations", &self.concurrent_associations)
.field("cookie_authentication", &self.cookie_provider.is_some())
.finish()
}
}
impl Default for ServerConfig {
fn default() -> Self {
ServerConfig {
transport: Arc::new(TransportConfig::default()),
concurrent_associations: 100_000,
cookie_provider: None,
}
}
}
impl ServerConfig {
pub fn new(transport: TransportConfig) -> Self {
ServerConfig {
transport: Arc::new(transport),
concurrent_associations: 100_000,
cookie_provider: None,
}
}
pub fn cookie_authentication(
&mut self,
provider: Arc<dyn crypto::RTCCryptoProvider>,
) -> &mut Self {
self.cookie_provider = Some(provider);
self
}
pub fn concurrent_associations(&mut self, value: u32) -> &mut Self {
self.concurrent_associations = value;
self
}
}
#[derive(Debug, Clone)]
pub struct ClientConfig {
pub transport: Arc<TransportConfig>,
}
impl Default for ClientConfig {
fn default() -> Self {
ClientConfig {
transport: Arc::new(TransportConfig::default()),
}
}
}
impl ClientConfig {
pub fn new(transport: TransportConfig) -> Self {
ClientConfig {
transport: Arc::new(transport),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn default_max_payload_size_fits_ipv6_min_mtu() {
assert_eq!(INITIAL_MTU, 1280 - 40 - 8 - 4 - 37);
let config = EndpointConfig::default();
assert_eq!(
config.get_max_payload_size(),
(INITIAL_MTU - (COMMON_HEADER_SIZE + DATA_CHUNK_HEADER_SIZE)) & !3
);
let padded_chunk =
(DATA_CHUNK_HEADER_SIZE + config.get_max_payload_size()).next_multiple_of(4);
assert!(COMMON_HEADER_SIZE + padded_chunk <= INITIAL_MTU);
}
#[test]
fn max_payload_size_for_mtu_derives_the_payload_budget() {
assert_eq!(
max_payload_size_for_mtu(INITIAL_MTU),
EndpointConfig::default().get_max_payload_size()
);
assert_eq!(max_payload_size_for_mtu(1203), 1172);
assert_eq!(max_payload_size_for_mtu(1204), 1176);
for mtu in [0, 31, 32] {
assert_eq!(max_payload_size_for_mtu(mtu), 4, "mtu {mtu}");
}
assert_eq!(
max_payload_size_for_mtu(u32::MAX),
(u32::MAX - (COMMON_HEADER_SIZE + DATA_CHUNK_HEADER_SIZE)) & !3
);
}
}