Skip to main content

rtci_sctp/
config.rs

1use crate::util::{
2    AssociationIdGenerator, RandomAssociationIdGenerator, RandomSource,
3    SourcedAssociationIdGenerator,
4};
5
6use crate::association::pmtud::PathMtuDiscoveryConfig;
7use crate::{RtoConfig, TimerConfig};
8use std::fmt;
9use std::sync::Arc;
10use std::time::Duration;
11
12/// The smallest a_rwnd an INIT or INIT ACK may carry (RFC 9260 3.3.2, 3.3.3).
13pub(crate) const MIN_ADVERTISED_RECEIVER_WINDOW: u32 = 1500;
14
15/// MTU for inbound packet (from DTLS)
16pub(crate) const RECEIVE_MTU: usize = 8192;
17/// Initial MTU for outgoing packets (to DTLS): bounds the assembled SCTP
18/// packet (common header + bundled chunks). Each SCTP packet becomes one
19/// DTLS record carried in one UDP datagram, so the wire size is roughly
20/// `INITIAL_MTU` + ~37 bytes of DTLS record overhead + 48 bytes of IPv6/UDP
21/// headers. 1191 keeps that within the 1280-byte IPv6 minimum MTU advertised
22/// by common tunnel paths (WireGuard, Tailscale); the previous 1228
23/// overflowed it (~1313 wire bytes), and because retransmissions re-bundle
24/// to the same oversized packet, a dropped flight stalled forever with no
25/// surfaced error. 1191 is the exact TURN-relayed IPv6 budget
26/// (1280 - 40 IPv6 - 8 UDP - 4 TURN ChannelData - 37 DTLS), the derivation
27/// from pion/sctp#476, adopted by webrtc-rs/webrtc#807 (webrtc v0.17.2).
28pub(crate) const INITIAL_MTU: u32 = 1191;
29
30/// The longest a FORWARD TSN is held back for DATA (RFC 3758 3.5 F3: "SHOULD NOT exceed
31/// 200ms").
32pub(crate) const MAX_FORWARD_TSN_DELAY: Duration = Duration::from_millis(200);
33pub(crate) const INITIAL_RECV_BUF_SIZE: u32 = 1024 * 1024;
34pub(crate) const COMMON_HEADER_SIZE: u32 = 12;
35pub(crate) const DATA_CHUNK_HEADER_SIZE: u32 = 16;
36/// Floor for [`max_payload_size_for_mtu`]: the smallest representable padded
37/// DATA packet — the 12-byte common header, the 16-byte DATA chunk header, and
38/// a 1..=4-byte payload padded to the 4-byte chunk boundary.
39pub const MIN_DATA_PACKET_MTU: u32 = COMMON_HEADER_SIZE + DATA_CHUNK_HEADER_SIZE + 4;
40
41/// Derive an [`EndpointConfig::max_payload_size`] value from an outbound
42/// DATA-packet budget: the largest DATA packet (common header plus bundled
43/// DATA chunks) associations may emit, in bytes. Control packets (INIT,
44/// INIT ACK, SACK, RECONFIG, FORWARD TSN, shutdown) marshal without
45/// consulting this value.
46///
47/// This is the inverse of the default derivation: `mtu` minus the two fixed
48/// headers, rounded down to the SCTP 4-byte chunk-padding boundary, so a
49/// single maximum-size DATA chunk always marshals to at most `mtu` bytes —
50/// exactly as the default budget does for `INITIAL_MTU` (1191, the
51/// TURN-relayed IPv6 minimum-MTU budget). Budgets below
52/// [`MIN_DATA_PACKET_MTU`] cannot satisfy that promise and are raised to it
53/// with a warning.
54pub fn max_payload_size_for_mtu(mtu: u32) -> u32 {
55    if mtu < MIN_DATA_PACKET_MTU {
56        log::warn!(
57            "sctp mtu {mtu} is below the smallest representable DATA packet; raising to \
58             {MIN_DATA_PACKET_MTU} bytes"
59        );
60    }
61    let mtu = mtu.max(MIN_DATA_PACKET_MTU);
62    (mtu - (COMMON_HEADER_SIZE + DATA_CHUNK_HEADER_SIZE)) & !3
63}
64pub(crate) const DEFAULT_MAX_MESSAGE_SIZE: u32 = 262144;
65
66/// How an association picks the stream whose data it sends next: the stream schedulers of
67/// RFC 8260 section 3.
68///
69/// Without user message interleaving a message that is part sent is finished before another
70/// stream is served, so a scheduler chooses between messages. With interleaving
71/// ([`TransportConfig::with_message_interleaving`], when the peer supports it too) it chooses
72/// for every chunk, and a large message no longer holds the others up.
73///
74/// A stream's priority is set with [`Stream::set_priority`](crate::Stream::set_priority).
75#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
76#[non_exhaustive]
77pub enum StreamScheduler {
78    /// Messages leave in the order they were written, whatever their stream (RFC 8260
79    /// section 3.1).
80    #[default]
81    FirstComeFirstServed,
82    /// The streams with something to send take turns: a message each, or a chunk each when
83    /// interleaving (section 3.2).
84    RoundRobin,
85    /// Round robin that changes stream only when a new packet is started, so a packet
86    /// carries the data of one stream and its loss holds up that stream alone (section 3.3).
87    RoundRobinPerPacket,
88    /// The stream with the highest priority goes first, as long as it has something to send;
89    /// streams of equal priority take turns (section 3.4).
90    Priority,
91    /// Each stream gets the same share of the bytes sent (section 3.5).
92    FairCapacity,
93    /// Each stream gets a share of the bytes sent in proportion to its priority, taken as
94    /// its weight (section 3.6, which RFC 8831 section 6.4 asks of WebRTC).
95    WeightedFairQueueing,
96}
97
98/// Config collects the arguments to create_association construction into
99/// a single structure
100#[derive(Debug, Clone)]
101pub struct TransportConfig {
102    sctp_port: u16,
103    remote_sctp_port: u16,
104    max_receive_buffer_size: u32,
105    max_message_size: u32,
106    max_receive_message_size: Option<u32>,
107    max_num_outbound_streams: u16,
108    max_num_inbound_streams: u16,
109    timer_config: TimerConfig,
110    rto_config: RtoConfig,
111    stream_scheduler: StreamScheduler,
112    valid_cookie_life: Duration,
113    heartbeat_interval: Option<Duration>,
114    slow_start_growth_limit: u32,
115    max_burst: Option<u32>,
116    sack_delay: Duration,
117    partial_reliability: bool,
118    message_interleaving: bool,
119    zero_checksum: bool,
120    path_mtu_discovery: Option<PathMtuDiscoveryConfig>,
121    zero_window_overcommit: bool,
122    zero_window_renege: bool,
123    send_buffer_size: Option<u32>,
124    data_in_cookie_echo: bool,
125    forward_tsn_delay: Option<Duration>,
126    partial_delivery_point: Option<u32>,
127    no_fragmentation: bool,
128    handshake_timers_back_off_rto: bool,
129}
130
131impl Default for TransportConfig {
132    fn default() -> Self {
133        TransportConfig {
134            sctp_port: 5000,
135            remote_sctp_port: 5000,
136            max_receive_buffer_size: INITIAL_RECV_BUF_SIZE,
137            max_message_size: DEFAULT_MAX_MESSAGE_SIZE,
138            max_receive_message_size: None,
139            max_num_outbound_streams: u16::MAX,
140            max_num_inbound_streams: u16::MAX,
141            timer_config: TimerConfig::default(),
142            rto_config: RtoConfig::default(),
143            stream_scheduler: StreamScheduler::default(),
144            valid_cookie_life: Duration::from_secs(60),
145            heartbeat_interval: Some(Duration::from_secs(30)),
146            slow_start_growth_limit: 1,
147            max_burst: Some(4),
148            sack_delay: Duration::from_millis(200),
149            partial_reliability: true,
150            message_interleaving: false,
151            zero_checksum: false,
152            path_mtu_discovery: None,
153            zero_window_overcommit: false,
154            zero_window_renege: false,
155            send_buffer_size: None,
156            data_in_cookie_echo: false,
157            forward_tsn_delay: None,
158            partial_delivery_point: None,
159            no_fragmentation: false,
160            handshake_timers_back_off_rto: true,
161        }
162    }
163}
164
165impl TransportConfig {
166    /// Whether a receiver that advertised a closed window (a_rwnd 0) still takes the next
167    /// in-sequence DATA chunk when nothing is readable: the chunk that would complete a
168    /// message the full buffer holds the start of (webrtc-rs/webrtc#822), up to one message
169    /// beyond the buffer. Off by default: RFC 9260 section 6.2, "When the receiver's
170    /// advertised window is 0, the receiver MUST drop any new incoming DATA chunk with a TSN
171    /// larger than the largest TSN received so far". While the advertised window is open, a
172    /// full buffer takes that chunk either way (the RFC rule binds a closed advertised window
173    /// only).
174    ///
175    /// An application that reads with [`Stream::read_part`](crate::Stream::read_part) does
176    /// not need it: partial delivery (RFC 9260 6.9) empties a buffer full of incomplete
177    /// messages, so the window opens again and the drop never stops a message. It is for an
178    /// application that reads whole messages only
179    /// ([`read_sctp`](crate::Stream::read_sctp)) and accepts messages larger than its
180    /// receive buffer, or negotiates user message interleaving (RFC 8260), where several
181    /// part-received messages, each smaller than the buffer, can fill it together with none
182    /// of them complete. Without it such a reader can deadlock: nothing is readable, so the
183    /// application frees nothing, and the chunk that would complete a message is dropped on
184    /// every retransmission.
185    pub fn with_zero_window_overcommit(mut self, value: bool) -> Self {
186        self.zero_window_overcommit = value;
187        self
188    }
189
190    /// See [`with_zero_window_overcommit`](Self::with_zero_window_overcommit).
191    pub fn zero_window_overcommit(&self) -> bool {
192        self.zero_window_overcommit
193    }
194
195    /// Whether a receiver that advertised a closed window (a_rwnd 0) and receives a DATA chunk
196    /// filling a gap below the largest TSN it holds makes room for it by dropping the largest
197    /// TSN held for reordering: RFC 9260 section 6.2, "if the new incoming DATA chunk holds a
198    /// TSN value less than the largest TSN received so far, then the receiver SHOULD drop the
199    /// largest TSN held for reordering and accept the new incoming DATA chunk". Off by
200    /// default: the gap filler is then taken with nothing dropped, up to one message beyond
201    /// the buffer.
202    ///
203    /// The chunk dropped was reported in a Gap Ack Block, so dropping it is a renege (RFC
204    /// 9260 6.2.1 D iii): it is no longer reported (6.2: "MUST NOT include" it), and the
205    /// sender has to send it again. libwebrtc's dcSCTP sender never sends again a chunk a Gap
206    /// Ack Block acknowledged (net/dcsctp/tx/outstanding_data.cc @ a222406d, `NackItem` returns
207    /// for an acknowledged item and `NackAll` skips them), so a reliable channel from a
208    /// browser stops for good at the dropped chunk: dcSCTP is the SCTP stack of Chromium, of
209    /// WebKit's libwebrtc and, since Firefox 146 (Mozilla bug 1997590), of Firefox. This crate
210    /// sends it again. A chunk is dropped only when its message is still held for
211    /// reordering: not readable whole, and not in partial delivery (RFC 9260 6.9). When no
212    /// held chunk is such, the gap filler is taken as without the setting.
213    pub fn with_zero_window_renege(mut self, value: bool) -> Self {
214        self.zero_window_renege = value;
215        self
216    }
217
218    /// See [`with_zero_window_renege`](Self::with_zero_window_renege).
219    pub fn zero_window_renege(&self) -> bool {
220        self.zero_window_renege
221    }
222
223    /// The size of the association's send buffer: the bytes of user data written and not yet
224    /// acknowledged (queued, or sent and outstanding), over every stream. A write that would
225    /// take the buffer past it fails with [`Error::ErrBufferFull`](shared::error::Error::ErrBufferFull) and
226    /// queues nothing, unless the priority policy makes room for it (below). `None`, the
227    /// default, sets no limit.
228    ///
229    /// The priority policy of RFC 7496 section 3.2: "When storing a user message in the send
230    /// buffer while there is not enough available space, the SCTP stack at the sender side MAY
231    /// abandon other user message(s) of the same SCTP association (with the same or a
232    /// different stream) with a priority lower than the provided one. User messages sent
233    /// reliably are considered to have a priority higher than all messages sent with the
234    /// Priority Policy." A stream sends with the policy after
235    /// [`Stream::set_reliability_params`](crate::Stream::set_reliability_params) with
236    /// [`ReliabilityType::Priority`](crate::ReliabilityType::Priority) and the priority (section
237    /// 4.2: 0 is the highest, a larger value a lower priority). When a write does not fit,
238    /// the messages of that policy with a lower priority than the one written are abandoned,
239    /// the lowest priority first and, among equal ones, the one written first, until it fits;
240    /// a message written without the policy (reliable, or with a lifetime or a retransmission
241    /// limit) ranks above all of them. Only messages none of which has been sent are
242    /// abandoned: that takes no TSN and needs no FORWARD TSN, so the peer sees nothing of it.
243    /// Each is reported as [`StreamEvent::MessageAbandoned`](crate::StreamEvent::MessageAbandoned) with
244    /// `transmitted: false`. When abandoning every such message would not make room, none is
245    /// abandoned and the write fails. A message of the policy that has been sent is
246    /// retransmitted as a reliable one is.
247    ///
248    /// WebRTC has no use for it: a data channel's priority (RFC 8831 section 6.4, RFC 8832
249    /// section 5.1) is the weight of the stream scheduler
250    /// ([`Stream::set_priority`](crate::Stream::set_priority)), and neither the Data Channel
251    /// Establishment Protocol nor `RTCDataChannelInit` has a way to ask for this policy.
252    pub fn with_send_buffer_size(mut self, value: Option<u32>) -> Self {
253        self.send_buffer_size = value;
254        self
255    }
256
257    /// See [`with_send_buffer_size`](Self::with_send_buffer_size).
258    pub fn send_buffer_size(&self) -> Option<u32> {
259        self.send_buffer_size
260    }
261
262    /// Whether DATA goes in the packet of the COOKIE ECHO: RFC 9260 section 5.1 C, "The
263    /// COOKIE ECHO chunk MAY be bundled with any pending outbound DATA chunks, but it MUST be
264    /// the first chunk in the packet and, until the COOKIE ACK chunk is returned, the sender
265    /// MUST NOT send any other packets to the peer" (and 3.3.11: the COOKIE ECHO "MAY be
266    /// bundled with one or more DATA chunks in the same packet"). Off by default.
267    ///
268    /// On, a stream takes writes in COOKIE-ECHOED (the INIT ACK has told what the peer
269    /// accepts; in COOKIE-WAIT writes are refused as before), and the packet of each COOKIE
270    /// ECHO, the first and every T1-cookie retransmission, carries after it the DATA that fits
271    /// the path MTU: the DATA sent with an earlier COOKIE ECHO again first (counted as
272    /// retransmissions, no round trip measured with them, RFC 9260 6.3.1 C5), then DATA
273    /// written since, as far as the peer's a_rwnd and the congestion window allow. DATA
274    /// written after a COOKIE ECHO has left waits for the COOKIE ACK, or for the next
275    /// retransmission. The first DATA then reaches the peer one round trip earlier. The
276    /// receiver takes the COOKIE ECHO first (RFC 9260 5.1 D), so the DATA arrives on an
277    /// ESTABLISHED association. libwebrtc's dcSCTP, the SCTP stack of the browsers, sends its
278    /// own DATA so (`TransmissionControlBlock::SendBufferedPackets` in
279    /// net/dcsctp/socket/transmission_control_block.cc puts the COOKIE ECHO first in a packet
280    /// of DATA and sends no other packet until the COOKIE ACK).
281    ///
282    /// Off by default because WebRTC never has DATA to bundle: the data channel layer writes
283    /// nothing before the association is up (`Event::Connected`, which follows the COOKIE
284    /// ACK), so the setting would not change what a peer connection sends.
285    pub fn with_data_in_cookie_echo(mut self, value: bool) -> Self {
286        self.data_in_cookie_echo = value;
287        self
288    }
289
290    /// See [`with_data_in_cookie_echo`](Self::with_data_in_cookie_echo).
291    pub fn data_in_cookie_echo(&self) -> bool {
292        self.data_in_cookie_echo
293    }
294
295    /// How long a FORWARD TSN (RFC 3758) or I-FORWARD-TSN (RFC 8260) that finds no DATA to go
296    /// with may wait for some. RFC 3758 3.5 F2: "The data sender SHOULD always attempt to
297    /// bundle an outgoing FORWARD TSN with outbound DATA chunks for efficiency. A sender MAY
298    /// even choose to delay the sending of the FORWARD TSN in the hope of bundling it with an
299    /// outbound DATA chunk." F3: "Any delay applied to the sending of FORWARD TSN chunk SHOULD
300    /// NOT exceed 200ms and MUST NOT exceed 500ms", so a longer value is taken as 200 ms.
301    ///
302    /// `None`, the default, does not wait: a FORWARD TSN goes with DATA sent at the same time
303    /// when a packet has room for it, and alone otherwise, at the instant the
304    /// Advanced.Peer.Ack.Point moves. With a delay, a FORWARD TSN that would go alone is held:
305    /// the first DATA sent in the delay carries it, and at the end of the delay, counted from
306    /// when it was first due, it goes alone. A SACK that catches up with the
307    /// Advanced.Peer.Ack.Point in the meantime makes it unnecessary, and it is not sent. The
308    /// T3-rtx timer runs throughout (RFC 3758 3.5 C5). The delay holds back the receiver's
309    /// delivery of what it keeps for reordering behind the abandoned message (F3's NOTE).
310    pub fn with_forward_tsn_delay(mut self, value: Option<Duration>) -> Self {
311        self.forward_tsn_delay = value.map(|delay| delay.min(MAX_FORWARD_TSN_DELAY));
312        self
313    }
314
315    /// See [`with_forward_tsn_delay`](Self::with_forward_tsn_delay).
316    pub fn forward_tsn_delay(&self) -> Option<Duration> {
317        self.forward_tsn_delay
318    }
319
320    /// The partial delivery point (RFC 6458 section 8.1.21, `SCTP_PARTIAL_DELIVERY_POINT`):
321    /// once the fragments of a message held from its first one on, without a gap, come to
322    /// this many bytes, [`Stream::read_part`](crate::Stream::read_part) gives them out before
323    /// the message is complete (RFC 9260 section 6.9). A message no larger than this is read
324    /// whole, unless the receive buffer runs out of space with nothing readable whole: then
325    /// RFC 9260 6.9's "it SHOULD dispatch part of its inbound message" applies to a message
326    /// of any size. Taken as at least 1 and at most the receive buffer size (RFC 6458: the
327    /// point may not be set "larger than the socket receive buffer size").
328    ///
329    /// The default is half the receive buffer
330    /// ([`with_max_receive_buffer_size`](Self::with_max_receive_buffer_size)); the RFCs give
331    /// none. From there a single message never closes the window by itself: when it starts
332    /// partial delivery at least half the buffer is free, which is at or above the window
333    /// silly window avoidance advertises as closed (`min(buffer / 2, one full chunk)`, RFC 9260
334    /// 6.2), so RFC 9260 6.2's drop never meets it. And every message up to half the buffer
335    /// (512 KiB with the default 1 MiB, above any `max-message-size` a data channel offers by
336    /// default) is still read whole.
337    ///
338    /// [`read_sctp`](crate::Stream::read_sctp) reads whole messages only; an application that
339    /// reads with it alone does not use partial delivery.
340    pub fn with_partial_delivery_point(mut self, value: u32) -> Self {
341        self.partial_delivery_point = Some(value);
342        self
343    }
344
345    /// Turns fragmentation of user messages off (RFC 9260 6.9: "An implementation MAY allow the
346    /// upper layer to disable fragmentation"). The association then acts "just like an
347    /// implementation that does NOT support fragmentation": a message that does not fit in one
348    /// DATA chunk of a full-sized packet (the PMDCS less the chunk header) is refused with
349    /// `Error::ErrOutboundPacketTooLarge` instead of being sent in fragments. Off by default.
350    pub fn with_fragmentation(mut self, enabled: bool) -> Self {
351        self.no_fragmentation = !enabled;
352        self
353    }
354
355    /// Whether user messages are fragmented: see [`with_fragmentation`](Self::with_fragmentation).
356    pub fn fragmentation(&self) -> bool {
357        !self.no_fragmentation
358    }
359
360    /// The partial delivery point in effect: see
361    /// [`with_partial_delivery_point`](Self::with_partial_delivery_point).
362    pub fn partial_delivery_point(&self) -> u32 {
363        self.partial_delivery_point
364            .unwrap_or(self.max_receive_buffer_size / 2)
365            .clamp(1, self.max_receive_buffer_size.max(1))
366    }
367
368    /// Path MTU discovery (DPLPMTUD, RFC 8899 section 6.2, with the PAD chunk of RFC 4820):
369    /// once established, the association confirms its packet size (what
370    /// [`Association::set_path_mtu`](crate::Association::set_path_mtu) set, else the
371    /// default) with a probe, searches for a larger one up to
372    /// [`PathMtuDiscoveryConfig::with_max_path_mtu`], and falls back to it when the path
373    /// stops carrying the larger size (RFC 9260 section 7.3; RFC 8261 section 4: SCTP over
374    /// DTLS "MUST implement and use" a discovery method that works without ICMP). `None`, the
375    /// crate's default, keeps the packet size where the transport sets it: the transport
376    /// knows the largest packet worth probing for, so it turns discovery on. The `rtci` peer
377    /// connection does, by default (`SettingEngineBuilder::with_sctp_path_mtu_discovery`).
378    pub fn with_path_mtu_discovery(mut self, value: Option<PathMtuDiscoveryConfig>) -> Self {
379        self.path_mtu_discovery = value;
380        self
381    }
382
383    /// The path MTU discovery settings, see
384    /// [`with_path_mtu_discovery`](Self::with_path_mtu_discovery).
385    pub fn path_mtu_discovery(&self) -> Option<PathMtuDiscoveryConfig> {
386        self.path_mtu_discovery
387    }
388
389    /// Sets L of RFC 9260 section 7.2.1: in slow start one SACK grows the congestion window
390    /// by at most the bytes it acknowledges and at most L packets (L x PMDCS). The RFC says L
391    /// SHOULD be 1 and MAY be larger (RFC 3465 discusses the choice): 1 is the default. A
392    /// receiver that acknowledges many packets with one SACK, as one that reads its socket in
393    /// batches does, makes a sender with L = 1 leave slow start slowly; a larger L restores
394    /// the faster ramp at the price the RFC names (a burst after such a SACK, and trust in
395    /// the receiver not to split its acknowledgements). Zero counts as one.
396    pub fn with_slow_start_growth_limit(mut self, value: u32) -> Self {
397        self.slow_start_growth_limit = value.max(1);
398        self
399    }
400
401    /// L, see [`with_slow_start_growth_limit`](Self::with_slow_start_growth_limit).
402    pub fn slow_start_growth_limit(&self) -> u32 {
403        self.slow_start_growth_limit
404    }
405
406    /// Whether PR-SCTP (RFC 3758) is announced to the peer and used. On by default, as WebRTC
407    /// data channels need it (RFC 8831 section 6.1). Off, neither chunk 192 nor the
408    /// Forward-TSN-Supported parameter is announced, no message is ever abandoned, and a
409    /// FORWARD TSN from the peer is answered as an unrecognized chunk.
410    pub fn with_partial_reliability(mut self, value: bool) -> Self {
411        self.partial_reliability = value;
412        self
413    }
414
415    /// See [`with_partial_reliability`](Self::with_partial_reliability).
416    pub fn partial_reliability(&self) -> bool {
417        self.partial_reliability
418    }
419
420    /// Whether user message interleaving (RFC 8260) is announced to the peer. When the peer
421    /// announces it too, user data travels in I-DATA chunks: the fragments of messages on
422    /// different streams may be interleaved, so a large message on one stream no longer
423    /// holds up the others, and the [stream scheduler](Self::with_stream_scheduler) chooses
424    /// the stream for every chunk. RFC 8831 section 6.1 says WebRTC data channels SHOULD use
425    /// it. Off by default; an application reads whole messages either way, so it needs no
426    /// change to turn it on.
427    pub fn with_message_interleaving(mut self, value: bool) -> Self {
428        self.message_interleaving = value;
429        self
430    }
431
432    /// See [`with_message_interleaving`](Self::with_message_interleaving).
433    pub fn message_interleaving(&self) -> bool {
434        self.message_interleaving
435    }
436
437    /// Says that the association runs over DTLS (RFC 8261), which detects errors better than
438    /// SCTP's CRC32c does, and so allows the zero checksum of RFC 9653 with the "SCTP over
439    /// DTLS" error detection method (section 6):
440    ///
441    /// - the INIT or INIT ACK carries the Zero Checksum Acceptable parameter, and packets
442    ///   that arrive with a checksum of zero are taken, their CRC32c not computed;
443    /// - when the peer announces the same, packets are sent with a checksum of zero and
444    ///   their CRC32c is not computed either. The packets RFC 9653 section 5.2 excepts keep
445    ///   a correct one: an INIT, a COOKIE ECHO, an answer to an out-of-the-blue packet.
446    ///
447    /// Off by default: every packet carries its CRC32c and one without is dropped. It MUST
448    /// NOT be turned on for an association that does not run over DTLS; a WebRTC data
449    /// channel transport always does.
450    pub fn with_zero_checksum(mut self, value: bool) -> Self {
451        self.zero_checksum = value;
452        self
453    }
454
455    /// See [`with_zero_checksum`](Self::with_zero_checksum).
456    pub fn zero_checksum(&self) -> bool {
457        self.zero_checksum
458    }
459
460    /// Sets SACK.Delay (RFC 9260 sections 6.2 and 16): how long the acknowledgement of a DATA
461    /// chunk may wait for a second one. Defaults to 200 ms. The RFC forbids more than 500 ms,
462    /// so a longer delay is taken as 500 ms.
463    pub fn with_sack_delay(mut self, value: Duration) -> Self {
464        self.sack_delay = value.min(Duration::from_millis(500));
465        self
466    }
467
468    /// SACK.Delay, see [`with_sack_delay`](Self::with_sack_delay).
469    pub fn sack_delay(&self) -> Duration {
470        self.sack_delay
471    }
472
473    /// Sets Max.Burst (RFC 9260 sections 6.1 D and 16): before DATA is sent the congestion
474    /// window is brought down to what is outstanding plus this many packets, so that one
475    /// SACK for many packets does not release as many at once. Defaults to 4, the value the
476    /// RFC recommends. `None` applies no limit: a peer that acknowledges in batches (one that
477    /// reads its socket in bursts) otherwise has this side's window cut back on every SACK.
478    pub fn with_max_burst(mut self, value: Option<u32>) -> Self {
479        self.max_burst = value;
480        self
481    }
482
483    /// Max.Burst, see [`with_max_burst`](Self::with_max_burst).
484    pub fn max_burst(&self) -> Option<u32> {
485        self.max_burst
486    }
487
488    /// Sets HB.interval (RFC 9260 8.3, 16): an association whose path has been idle for an RTO
489    /// plus this long sends a HEARTBEAT, which measures the round trip and shows that the peer
490    /// is still there. One left unanswered counts toward
491    /// [`TimerConfig::max_t3_rtx_retrans`](crate::TimerConfig). Defaults to 30 seconds; `None`
492    /// sends no HEARTBEAT.
493    pub fn with_heartbeat_interval(mut self, value: Option<Duration>) -> Self {
494        self.heartbeat_interval = value;
495        self
496    }
497
498    /// HB.interval, see [`with_heartbeat_interval`](Self::with_heartbeat_interval).
499    pub fn heartbeat_interval(&self) -> Option<Duration> {
500        self.heartbeat_interval
501    }
502
503    /// Sets Valid.Cookie.Life: how long after an INIT ACK its State Cookie is accepted in a
504    /// COOKIE ECHO (RFC 9260 5.1.3, 16). Later it is refused with a "Stale Cookie" error and
505    /// the peer starts again. Defaults to 60 seconds.
506    pub fn with_valid_cookie_life(mut self, value: Duration) -> Self {
507        self.valid_cookie_life = value;
508        self
509    }
510
511    /// Valid.Cookie.Life, see [`with_valid_cookie_life`](Self::with_valid_cookie_life).
512    pub fn valid_cookie_life(&self) -> Duration {
513        self.valid_cookie_life
514    }
515
516    /// Sets this endpoint's SCTP port, the source port of what it sends (RFC 8841 5: its own
517    /// `a=sctp-port`). Defaults to 5000. Port 0 MUST NOT be used (RFC 9260 section 3.1):
518    /// [`Endpoint::connect`](crate::Endpoint::connect) refuses a configuration with it
519    /// (`ConnectError::ZeroSctpPort`), and an accepting endpoint answers on the INIT's ports.
520    pub fn with_sctp_port(mut self, value: u16) -> Self {
521        self.sctp_port = value;
522        self
523    }
524
525    /// Sets the peer's SCTP port, the destination port of the INIT this endpoint sends when it
526    /// initiates (RFC 8841 5: the remote `a=sctp-port`). Defaults to 5000. An endpoint that
527    /// accepts an association answers on the ports of the INIT it received. Port 0 is refused
528    /// by [`Endpoint::connect`](crate::Endpoint::connect) (RFC 9260 section 3.1).
529    pub fn with_remote_sctp_port(mut self, value: u16) -> Self {
530        self.remote_sctp_port = value;
531        self
532    }
533
534    /// Sets the advertised receive window (a_rwnd), bounding how much unacknowledged data a peer
535    /// may have in flight toward this endpoint. At least 1500: RFC 9260 3.3.2 and 3.3.3 forbid
536    /// a smaller a_rwnd in the INIT and INIT ACK, so a smaller value is raised to it.
537    pub fn with_max_receive_buffer_size(mut self, value: u32) -> Self {
538        self.max_receive_buffer_size = value.max(MIN_ADVERTISED_RECEIVER_WINDOW);
539        self
540    }
541
542    /// Sets the largest message this endpoint will send, which is the peer's limit (RFC 8841
543    /// 6.1: the remote `max-message-size`). Also the largest it will accept unless
544    /// [`with_max_receive_message_size`](Self::with_max_receive_message_size) sets that apart.
545    pub fn with_max_message_size(mut self, value: u32) -> Self {
546        self.max_message_size = value;
547        self
548    }
549
550    /// Sets the largest message this endpoint will accept, which is the limit it advertised
551    /// itself (RFC 8841 6.1: the local `max-message-size`). Each direction has its own limit;
552    /// the receive buffer keeps room for one message of this size beyond its bound, so a
553    /// message larger than the buffer can still be reassembled.
554    pub fn with_max_receive_message_size(mut self, value: u32) -> Self {
555        self.max_receive_message_size = Some(value);
556        self
557    }
558
559    /// Sets how many outbound streams to request during the handshake. At least 1: RFC 9260
560    /// 3.3.2 and 3.3.3 forbid 0 in the INIT and INIT ACK.
561    pub fn with_max_num_outbound_streams(mut self, value: u16) -> Self {
562        self.max_num_outbound_streams = value.max(1);
563        self
564    }
565
566    /// Sets how many inbound streams this endpoint will accept. At least 1, as for the
567    /// outbound streams.
568    pub fn with_max_num_inbound_streams(mut self, value: u16) -> Self {
569        self.max_num_inbound_streams = value.max(1);
570        self
571    }
572
573    /// Whether an expiry of T1-init or T1-cookie backs off the RTO of the path, as a T3-rtx
574    /// expiry does. On by default: RFC 9260 section 5.1, "The T1-init timer and T1-cookie
575    /// timer SHOULD follow the same rules given in Section 6.3", whose rule E2 (6.3.3) is "set
576    /// RTO = RTO * 2 ('back off the timer')" for the destination, bounded by RTO.Max. Each
577    /// timer is started with the path's RTO, so T1-cookie starts where T1-init's backoff
578    /// left the RTO, and the first DATA after the handshake does too, until a round trip is
579    /// measured (6.3.1 C2).
580    ///
581    /// `false` is what libwebrtc's dcSCTP does (`t1_init_` and `t1_cookie_` in
582    /// `net/dcsctp/socket/dcsctp_socket.cc`: each timer starts at its own 1 s and doubles by
583    /// itself): each timer starts at RTO.Initial and doubles on its own expiries, and the RTO
584    /// the data transfer uses is left alone, so the first DATA after a handshake that lost
585    /// packets is retransmitted an RTO.Initial after it is sent.
586    pub fn with_handshake_timers_back_off_rto(mut self, value: bool) -> Self {
587        self.handshake_timers_back_off_rto = value;
588        self
589    }
590
591    /// See [`with_handshake_timers_back_off_rto`](Self::with_handshake_timers_back_off_rto).
592    pub fn handshake_timers_back_off_rto(&self) -> bool {
593        self.handshake_timers_back_off_rto
594    }
595
596    /// Overrides the retransmission limits; see [`TimerConfig`].
597    pub fn with_timer_config(mut self, value: TimerConfig) -> Self {
598        self.timer_config = value;
599        self
600    }
601
602    /// Sets RTO.Initial, RTO.Min and RTO.Max (RFC 9260 sections 6.3.1 and 16); see
603    /// [`RtoConfig`]. The defaults are the RFC's: 1, 1 and 60 seconds. With
604    /// [`TimerConfig::max_t3_rtx_retrans`] (Association.Max.Retrans) they bound how long an
605    /// unanswered peer is retransmitted to before the association fails.
606    pub fn with_rto_config(mut self, value: RtoConfig) -> Self {
607        self.rto_config = value;
608        self
609    }
610
611    /// Chooses how the next message to send is picked among the streams.
612    pub fn with_stream_scheduler(mut self, value: StreamScheduler) -> Self {
613        self.stream_scheduler = value;
614        self
615    }
616
617    /// The configured SCTP port.
618    pub fn sctp_port(&self) -> u16 {
619        self.sctp_port
620    }
621
622    /// The configured SCTP port of the peer.
623    pub fn remote_sctp_port(&self) -> u16 {
624        self.remote_sctp_port
625    }
626
627    /// The configured receive window in bytes.
628    pub fn max_receive_buffer_size(&self) -> u32 {
629        self.max_receive_buffer_size
630    }
631
632    /// The configured maximum message size to send, in bytes.
633    pub fn max_message_size(&self) -> u32 {
634        self.max_message_size
635    }
636
637    /// The configured maximum message size to accept, in bytes: the send limit unless set
638    /// apart with [`with_max_receive_message_size`](Self::with_max_receive_message_size).
639    pub fn max_receive_message_size(&self) -> u32 {
640        self.max_receive_message_size
641            .unwrap_or(self.max_message_size)
642    }
643
644    /// The configured outbound stream count.
645    pub fn max_num_outbound_streams(&self) -> u16 {
646        self.max_num_outbound_streams
647    }
648
649    /// The configured inbound stream count.
650    pub fn max_num_inbound_streams(&self) -> u16 {
651        self.max_num_inbound_streams
652    }
653
654    /// The configured retransmission limits.
655    pub fn timer_config(&self) -> TimerConfig {
656        self.timer_config
657    }
658
659    /// The configured RTO bounds.
660    pub fn rto_config(&self) -> RtoConfig {
661        self.rto_config
662    }
663
664    /// The configured stream scheduler.
665    pub fn stream_scheduler(&self) -> StreamScheduler {
666        self.stream_scheduler
667    }
668}
669
670/// Global configuration for the endpoint, affecting all associations
671///
672/// Default values should be suitable for most internet applications.
673#[derive(Clone)]
674pub struct EndpointConfig {
675    pub(crate) max_payload_size: u32,
676
677    /// AID generator factory
678    ///
679    /// Create a aid generator for local aid in Endpoint struct
680    pub(crate) aid_generator_factory:
681        Arc<dyn (Fn() -> Box<dyn AssociationIdGenerator + Send>) + Send + Sync>,
682
683    /// Where the endpoint's associations draw their random values from.
684    pub(crate) random: RandomSource,
685}
686
687impl Default for EndpointConfig {
688    fn default() -> Self {
689        Self::new()
690    }
691}
692
693impl EndpointConfig {
694    /// Create a default configuration
695    pub fn new() -> Self {
696        let aid_factory: fn() -> Box<dyn AssociationIdGenerator + Send> =
697            || Box::<RandomAssociationIdGenerator>::default();
698        Self {
699            max_payload_size: max_payload_size_for_mtu(INITIAL_MTU),
700            aid_generator_factory: Arc::new(aid_factory),
701            random: RandomSource::default(),
702        }
703    }
704
705    /// Draws every random value of the endpoint and its associations from `provider`'s
706    /// `random()`: the verification tags (with the default generator, which this replaces;
707    /// set [`Self::aid_generator`] after this call for another), the initial TSNs, the State
708    /// Cookies made without [`ServerConfig::cookie_authentication`], the Initiate Tag of an
709    /// INIT ACK for an existing association, HEARTBEAT nonces and the HEARTBEAT timer's
710    /// jitter.
711    ///
712    /// Without it (the default) they come from `rand`'s thread-local CSPRNG. This is how the
713    /// other crates of the workspace take their randomness (`docs/randomness-audit.md`), and
714    /// what lets a test that seeds the provider replay a run exactly.
715    pub fn random_source(&mut self, provider: Arc<dyn crypto::RTCCryptoProvider>) -> &mut Self {
716        let random = RandomSource::new(Some(provider));
717        self.random = random.clone();
718        self.aid_generator_factory = Arc::new(move || {
719            Box::new(SourcedAssociationIdGenerator(random.clone()))
720                as Box<dyn AssociationIdGenerator + Send>
721        });
722        self
723    }
724
725    /// Supply a custom Association ID generator factory
726    ///
727    /// Called once by each `Endpoint` constructed from this configuration to obtain the AID
728    /// generator which will be used to generate the AIDs used for incoming packets on all
729    /// associations involving that  `Endpoint`. A custom AID generator allows applications to embed
730    /// information in local association IDs, e.g. to support stateless packet-level load balancers.
731    ///
732    /// `EndpointConfig::new()` applies a default random AID generator factory. This functions
733    /// accepts any customized AID generator to reset AID generator factory that implements
734    /// the `AssociationIdGenerator` trait.
735    pub fn aid_generator<
736        F: Fn() -> Box<dyn AssociationIdGenerator + Send> + Send + Sync + 'static,
737    >(
738        &mut self,
739        factory: F,
740    ) -> &mut Self {
741        self.aid_generator_factory = Arc::new(factory);
742        self
743    }
744
745    /// Maximum payload size accepted from peers.
746    ///
747    /// The default is suitable for typical internet applications. Applications which expect to run
748    /// on networks supporting Ethernet jumbo frames or similar should set this appropriately.
749    pub fn max_payload_size(&mut self, value: u32) -> &mut Self {
750        self.max_payload_size = value;
751        self
752    }
753
754    /// Get the current value of `max_payload_size`
755    ///
756    /// While most parameters don't need to be readable, this must be exposed to allow higher-level
757    /// layers to determine how large a receive buffer to allocate to
758    /// support an externally-defined `EndpointConfig`.
759    ///
760    /// While `get_` accessors are typically unidiomatic in Rust, we favor concision for setters,
761    /// which will be used far more heavily.
762    pub fn get_max_payload_size(&self) -> u32 {
763        self.max_payload_size
764    }
765}
766
767impl fmt::Debug for EndpointConfig {
768    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
769        fmt.debug_struct("EndpointConfig")
770            .field("max_payload_size", &self.max_payload_size)
771            .field("aid_generator_factory", &"[ elided ]")
772            .field("random", &self.random)
773            .finish()
774    }
775}
776
777/// Parameters governing incoming associations
778///
779/// Default values should be suitable for most internet applications.
780#[derive(Clone)]
781pub struct ServerConfig {
782    /// Transport configuration to use for incoming associations
783    pub transport: Arc<TransportConfig>,
784
785    /// Maximum number of concurrent associations
786    pub(crate) concurrent_associations: u32,
787
788    /// The crypto provider State Cookies are authenticated with, when one was given.
789    pub(crate) cookie_provider: Option<Arc<dyn crypto::RTCCryptoProvider>>,
790}
791
792impl fmt::Debug for ServerConfig {
793    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
794        fmt.debug_struct("ServerConfig")
795            .field("transport", &self.transport)
796            .field("concurrent_associations", &self.concurrent_associations)
797            .field("cookie_authentication", &self.cookie_provider.is_some())
798            .finish()
799    }
800}
801
802impl Default for ServerConfig {
803    fn default() -> Self {
804        ServerConfig {
805            transport: Arc::new(TransportConfig::default()),
806            concurrent_associations: 100_000,
807            cookie_provider: None,
808        }
809    }
810}
811
812impl ServerConfig {
813    /// Create a default configuration with a particular handshake token key
814    pub fn new(transport: TransportConfig) -> Self {
815        ServerConfig {
816            transport: Arc::new(transport),
817            concurrent_associations: 100_000,
818            cookie_provider: None,
819        }
820    }
821
822    /// Gives the endpoint a crypto provider to authenticate State Cookies with, and makes
823    /// the handshake stateless on the accepting side, as RFC 9260 sections 5.1 and 5.1.3
824    /// have it.
825    ///
826    /// With a provider, the State Cookie of an INIT ACK holds everything the association is
827    /// made from, the time it was made, and an HMAC-SHA-256 over them under a random key of
828    /// the endpoint's (replaced every hour). The endpoint answers an INIT and keeps nothing:
829    /// [`Endpoint::handle`](crate::Endpoint::handle) returns `None` for it and the INIT ACK
830    /// leaves by [`Endpoint::poll_transmit`](crate::Endpoint::poll_transmit). The
831    /// association is made, and returned as
832    /// [`DatagramEvent::NewAssociation`](crate::DatagramEvent::NewAssociation), when a
833    /// COOKIE ECHO brings back a cookie whose MAC verifies and which is no older than
834    /// [`TransportConfig::with_valid_cookie_life`]; it is established at once.
835    ///
836    /// Without a provider (the default) the cookie is 32 random bytes and the endpoint makes
837    /// the association when the INIT arrives, remembering the cookie to compare it with the
838    /// one echoed. `rtci-sctp` names no cryptographic implementation of its own, so the MAC
839    /// is there only when the application supplies the provider.
840    pub fn cookie_authentication(
841        &mut self,
842        provider: Arc<dyn crypto::RTCCryptoProvider>,
843    ) -> &mut Self {
844        self.cookie_provider = Some(provider);
845        self
846    }
847
848    /// Maximum number of associations the endpoint holds at once. An INIT that would start
849    /// one more is refused.
850    ///
851    /// A transport that carries a single association, such as WebRTC's SCTP over one DTLS
852    /// transport (RFC 8261), should set this to 1.
853    pub fn concurrent_associations(&mut self, value: u32) -> &mut Self {
854        self.concurrent_associations = value;
855        self
856    }
857}
858
859/// Configuration for outgoing associations
860///
861/// Default values should be suitable for most internet applications.
862#[derive(Debug, Clone)]
863pub struct ClientConfig {
864    /// Transport configuration to use
865    pub transport: Arc<TransportConfig>,
866}
867
868impl Default for ClientConfig {
869    fn default() -> Self {
870        ClientConfig {
871            transport: Arc::new(TransportConfig::default()),
872        }
873    }
874}
875
876impl ClientConfig {
877    /// Create a default configuration with a particular cryptographic configuration
878    pub fn new(transport: TransportConfig) -> Self {
879        ClientConfig {
880            transport: Arc::new(transport),
881        }
882    }
883}
884
885#[cfg(test)]
886mod tests {
887    use super::*;
888
889    #[test]
890    fn default_max_payload_size_fits_ipv6_min_mtu() {
891        // INITIAL_MTU bounds the assembled SCTP packet. The default is the
892        // exact TURN-relayed IPv6 budget (pion/sctp#476, webrtc-rs/webrtc#807):
893        // the 1280-byte IPv6 minimum MTU (RFC 8200) minus IPv6, UDP, and TURN
894        // ChannelData headers and DTLS record overhead.
895        assert_eq!(INITIAL_MTU, 1280 - 40 - 8 - 4 - 37);
896        let config = EndpointConfig::default();
897        assert_eq!(
898            config.get_max_payload_size(),
899            (INITIAL_MTU - (COMMON_HEADER_SIZE + DATA_CHUNK_HEADER_SIZE)) & !3
900        );
901        // A single maximum-size DATA chunk must marshal within INITIAL_MTU:
902        // common header + the chunk header and payload, padded to 4 bytes.
903        let padded_chunk =
904            (DATA_CHUNK_HEADER_SIZE + config.get_max_payload_size()).next_multiple_of(4);
905        assert!(COMMON_HEADER_SIZE + padded_chunk <= INITIAL_MTU);
906    }
907
908    #[test]
909    fn max_payload_size_for_mtu_derives_the_payload_budget() {
910        // `max_payload_size_for_mtu(INITIAL_MTU)` must reproduce the default
911        // payload budget exactly.
912        assert_eq!(
913            max_payload_size_for_mtu(INITIAL_MTU),
914            EndpointConfig::default().get_max_payload_size()
915        );
916
917        // Rounded down to the 4-byte padding boundary: the last MTU of one
918        // padding window and the first of the next straddle a 4-byte step.
919        assert_eq!(max_payload_size_for_mtu(1203), 1172);
920        assert_eq!(max_payload_size_for_mtu(1204), 1176);
921
922        // Values below MIN_DATA_PACKET_MTU behave exactly as the 32-byte
923        // floor: the smallest representable padded DATA packet, a 4-byte
924        // payload budget.
925        for mtu in [0, 31, 32] {
926            assert_eq!(max_payload_size_for_mtu(mtu), 4, "mtu {mtu}");
927        }
928
929        // Upper edge: the derivation must not overflow.
930        assert_eq!(
931            max_payload_size_for_mtu(u32::MAX),
932            (u32::MAX - (COMMON_HEADER_SIZE + DATA_CHUNK_HEADER_SIZE)) & !3
933        );
934    }
935}