rtci-sctp 0.5.0

Sans-I/O SCTP (RFC 9260) with partial reliability and stream reconfiguration, for WebRTC data channels
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
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;

/// The smallest a_rwnd an INIT or INIT ACK may carry (RFC 9260 3.3.2, 3.3.3).
pub(crate) const MIN_ADVERTISED_RECEIVER_WINDOW: u32 = 1500;

/// MTU for inbound packet (from DTLS)
pub(crate) const RECEIVE_MTU: usize = 8192;
/// Initial MTU for outgoing packets (to DTLS): bounds the assembled SCTP
/// packet (common header + bundled chunks). Each SCTP packet becomes one
/// DTLS record carried in one UDP datagram, so the wire size is roughly
/// `INITIAL_MTU` + ~37 bytes of DTLS record overhead + 48 bytes of IPv6/UDP
/// headers. 1191 keeps that within the 1280-byte IPv6 minimum MTU advertised
/// by common tunnel paths (WireGuard, Tailscale); the previous 1228
/// overflowed it (~1313 wire bytes), and because retransmissions re-bundle
/// to the same oversized packet, a dropped flight stalled forever with no
/// surfaced error. 1191 is the exact TURN-relayed IPv6 budget
/// (1280 - 40 IPv6 - 8 UDP - 4 TURN ChannelData - 37 DTLS), the derivation
/// from pion/sctp#476, adopted by webrtc-rs/webrtc#807 (webrtc v0.17.2).
pub(crate) const INITIAL_MTU: u32 = 1191;

/// The longest a FORWARD TSN is held back for DATA (RFC 3758 3.5 F3: "SHOULD NOT exceed
/// 200ms").
pub(crate) const MAX_FORWARD_TSN_DELAY: Duration = Duration::from_millis(200);
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;
/// Floor for [`max_payload_size_for_mtu`]: the smallest representable padded
/// DATA packet — the 12-byte common header, the 16-byte DATA chunk header, and
/// a 1..=4-byte payload padded to the 4-byte chunk boundary.
pub const MIN_DATA_PACKET_MTU: u32 = COMMON_HEADER_SIZE + DATA_CHUNK_HEADER_SIZE + 4;

/// Derive an [`EndpointConfig::max_payload_size`] value from an outbound
/// DATA-packet budget: the largest DATA packet (common header plus bundled
/// DATA chunks) associations may emit, in bytes. Control packets (INIT,
/// INIT ACK, SACK, RECONFIG, FORWARD TSN, shutdown) marshal without
/// consulting this value.
///
/// This is the inverse of the default derivation: `mtu` minus the two fixed
/// headers, rounded down to the SCTP 4-byte chunk-padding boundary, so a
/// single maximum-size DATA chunk always marshals to at most `mtu` bytes —
/// exactly as the default budget does for `INITIAL_MTU` (1191, the
/// TURN-relayed IPv6 minimum-MTU budget). Budgets below
/// [`MIN_DATA_PACKET_MTU`] cannot satisfy that promise and are raised to it
/// with a warning.
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;

/// How an association picks the stream whose data it sends next: the stream schedulers of
/// RFC 8260 section 3.
///
/// Without user message interleaving a message that is part sent is finished before another
/// stream is served, so a scheduler chooses between messages. With interleaving
/// ([`TransportConfig::with_message_interleaving`], when the peer supports it too) it chooses
/// for every chunk, and a large message no longer holds the others up.
///
/// A stream's priority is set with [`Stream::set_priority`](crate::Stream::set_priority).
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum StreamScheduler {
    /// Messages leave in the order they were written, whatever their stream (RFC 8260
    /// section 3.1).
    #[default]
    FirstComeFirstServed,
    /// The streams with something to send take turns: a message each, or a chunk each when
    /// interleaving (section 3.2).
    RoundRobin,
    /// Round robin that changes stream only when a new packet is started, so a packet
    /// carries the data of one stream and its loss holds up that stream alone (section 3.3).
    RoundRobinPerPacket,
    /// The stream with the highest priority goes first, as long as it has something to send;
    /// streams of equal priority take turns (section 3.4).
    Priority,
    /// Each stream gets the same share of the bytes sent (section 3.5).
    FairCapacity,
    /// Each stream gets a share of the bytes sent in proportion to its priority, taken as
    /// its weight (section 3.6, which RFC 8831 section 6.4 asks of WebRTC).
    WeightedFairQueueing,
}

/// Config collects the arguments to create_association construction into
/// a single structure
#[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,
    send_buffer_size: Option<u32>,
    data_in_cookie_echo: bool,
    forward_tsn_delay: Option<Duration>,
    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,
            send_buffer_size: None,
            data_in_cookie_echo: false,
            forward_tsn_delay: None,
            partial_delivery_point: None,
            no_fragmentation: false,
            handshake_timers_back_off_rto: true,
        }
    }
}

impl TransportConfig {
    /// Whether a receiver that advertised a closed window (a_rwnd 0) still takes the next
    /// in-sequence DATA chunk when nothing is readable: the chunk that would complete a
    /// message the full buffer holds the start of (webrtc-rs/webrtc#822), up to one message
    /// beyond the buffer. Off by default: RFC 9260 section 6.2, "When the receiver's
    /// advertised window is 0, the receiver MUST drop any new incoming DATA chunk with a TSN
    /// larger than the largest TSN received so far". While the advertised window is open, a
    /// full buffer takes that chunk either way (the RFC rule binds a closed advertised window
    /// only).
    ///
    /// An application that reads with [`Stream::read_part`](crate::Stream::read_part) does
    /// not need it: partial delivery (RFC 9260 6.9) empties a buffer full of incomplete
    /// messages, so the window opens again and the drop never stops a message. It is for an
    /// application that reads whole messages only
    /// ([`read_sctp`](crate::Stream::read_sctp)) and accepts messages larger than its
    /// receive buffer, or negotiates user message interleaving (RFC 8260), where several
    /// part-received messages, each smaller than the buffer, can fill it together with none
    /// of them complete. Without it such a reader can deadlock: nothing is readable, so the
    /// application frees nothing, and the chunk that would complete a message is dropped on
    /// every retransmission.
    pub fn with_zero_window_overcommit(mut self, value: bool) -> Self {
        self.zero_window_overcommit = value;
        self
    }

    /// See [`with_zero_window_overcommit`](Self::with_zero_window_overcommit).
    pub fn zero_window_overcommit(&self) -> bool {
        self.zero_window_overcommit
    }

    /// Whether a receiver that advertised a closed window (a_rwnd 0) and receives a DATA chunk
    /// filling a gap below the largest TSN it holds makes room for it by dropping the largest
    /// TSN held for reordering: RFC 9260 section 6.2, "if the new incoming DATA chunk holds a
    /// TSN value less than the largest TSN received so far, then the receiver SHOULD drop the
    /// largest TSN held for reordering and accept the new incoming DATA chunk". Off by
    /// default: the gap filler is then taken with nothing dropped, up to one message beyond
    /// the buffer.
    ///
    /// The chunk dropped was reported in a Gap Ack Block, so dropping it is a renege (RFC
    /// 9260 6.2.1 D iii): it is no longer reported (6.2: "MUST NOT include" it), and the
    /// sender has to send it again. libwebrtc's dcSCTP sender never sends again a chunk a Gap
    /// Ack Block acknowledged (net/dcsctp/tx/outstanding_data.cc @ a222406d, `NackItem` returns
    /// for an acknowledged item and `NackAll` skips them), so a reliable channel from a
    /// browser stops for good at the dropped chunk: dcSCTP is the SCTP stack of Chromium, of
    /// WebKit's libwebrtc and, since Firefox 146 (Mozilla bug 1997590), of Firefox. This crate
    /// sends it again. A chunk is dropped only when its message is still held for
    /// reordering: not readable whole, and not in partial delivery (RFC 9260 6.9). When no
    /// held chunk is such, the gap filler is taken as without the setting.
    pub fn with_zero_window_renege(mut self, value: bool) -> Self {
        self.zero_window_renege = value;
        self
    }

    /// See [`with_zero_window_renege`](Self::with_zero_window_renege).
    pub fn zero_window_renege(&self) -> bool {
        self.zero_window_renege
    }

    /// The size of the association's send buffer: the bytes of user data written and not yet
    /// acknowledged (queued, or sent and outstanding), over every stream. A write that would
    /// take the buffer past it fails with [`Error::ErrBufferFull`](shared::error::Error::ErrBufferFull) and
    /// queues nothing, unless the priority policy makes room for it (below). `None`, the
    /// default, sets no limit.
    ///
    /// The priority policy of RFC 7496 section 3.2: "When storing a user message in the send
    /// buffer while there is not enough available space, the SCTP stack at the sender side MAY
    /// abandon other user message(s) of the same SCTP association (with the same or a
    /// different stream) with a priority lower than the provided one. User messages sent
    /// reliably are considered to have a priority higher than all messages sent with the
    /// Priority Policy." A stream sends with the policy after
    /// [`Stream::set_reliability_params`](crate::Stream::set_reliability_params) with
    /// [`ReliabilityType::Priority`](crate::ReliabilityType::Priority) and the priority (section
    /// 4.2: 0 is the highest, a larger value a lower priority). When a write does not fit,
    /// the messages of that policy with a lower priority than the one written are abandoned,
    /// the lowest priority first and, among equal ones, the one written first, until it fits;
    /// a message written without the policy (reliable, or with a lifetime or a retransmission
    /// limit) ranks above all of them. Only messages none of which has been sent are
    /// abandoned: that takes no TSN and needs no FORWARD TSN, so the peer sees nothing of it.
    /// Each is reported as [`StreamEvent::MessageAbandoned`](crate::StreamEvent::MessageAbandoned) with
    /// `transmitted: false`. When abandoning every such message would not make room, none is
    /// abandoned and the write fails. A message of the policy that has been sent is
    /// retransmitted as a reliable one is.
    ///
    /// WebRTC has no use for it: a data channel's priority (RFC 8831 section 6.4, RFC 8832
    /// section 5.1) is the weight of the stream scheduler
    /// ([`Stream::set_priority`](crate::Stream::set_priority)), and neither the Data Channel
    /// Establishment Protocol nor `RTCDataChannelInit` has a way to ask for this policy.
    pub fn with_send_buffer_size(mut self, value: Option<u32>) -> Self {
        self.send_buffer_size = value;
        self
    }

    /// See [`with_send_buffer_size`](Self::with_send_buffer_size).
    pub fn send_buffer_size(&self) -> Option<u32> {
        self.send_buffer_size
    }

    /// Whether DATA goes in the packet of the COOKIE ECHO: RFC 9260 section 5.1 C, "The
    /// COOKIE ECHO chunk MAY be bundled with any pending outbound DATA chunks, but it MUST be
    /// the first chunk in the packet and, until the COOKIE ACK chunk is returned, the sender
    /// MUST NOT send any other packets to the peer" (and 3.3.11: the COOKIE ECHO "MAY be
    /// bundled with one or more DATA chunks in the same packet"). Off by default.
    ///
    /// On, a stream takes writes in COOKIE-ECHOED (the INIT ACK has told what the peer
    /// accepts; in COOKIE-WAIT writes are refused as before), and the packet of each COOKIE
    /// ECHO, the first and every T1-cookie retransmission, carries after it the DATA that fits
    /// the path MTU: the DATA sent with an earlier COOKIE ECHO again first (counted as
    /// retransmissions, no round trip measured with them, RFC 9260 6.3.1 C5), then DATA
    /// written since, as far as the peer's a_rwnd and the congestion window allow. DATA
    /// written after a COOKIE ECHO has left waits for the COOKIE ACK, or for the next
    /// retransmission. The first DATA then reaches the peer one round trip earlier. The
    /// receiver takes the COOKIE ECHO first (RFC 9260 5.1 D), so the DATA arrives on an
    /// ESTABLISHED association. libwebrtc's dcSCTP, the SCTP stack of the browsers, sends its
    /// own DATA so (`TransmissionControlBlock::SendBufferedPackets` in
    /// net/dcsctp/socket/transmission_control_block.cc puts the COOKIE ECHO first in a packet
    /// of DATA and sends no other packet until the COOKIE ACK).
    ///
    /// Off by default because WebRTC never has DATA to bundle: the data channel layer writes
    /// nothing before the association is up (`Event::Connected`, which follows the COOKIE
    /// ACK), so the setting would not change what a peer connection sends.
    pub fn with_data_in_cookie_echo(mut self, value: bool) -> Self {
        self.data_in_cookie_echo = value;
        self
    }

    /// See [`with_data_in_cookie_echo`](Self::with_data_in_cookie_echo).
    pub fn data_in_cookie_echo(&self) -> bool {
        self.data_in_cookie_echo
    }

    /// How long a FORWARD TSN (RFC 3758) or I-FORWARD-TSN (RFC 8260) that finds no DATA to go
    /// with may wait for some. RFC 3758 3.5 F2: "The data sender SHOULD always attempt to
    /// bundle an outgoing FORWARD TSN with outbound DATA chunks for efficiency. A sender MAY
    /// even choose to delay the sending of the FORWARD TSN in the hope of bundling it with an
    /// outbound DATA chunk." F3: "Any delay applied to the sending of FORWARD TSN chunk SHOULD
    /// NOT exceed 200ms and MUST NOT exceed 500ms", so a longer value is taken as 200 ms.
    ///
    /// `None`, the default, does not wait: a FORWARD TSN goes with DATA sent at the same time
    /// when a packet has room for it, and alone otherwise, at the instant the
    /// Advanced.Peer.Ack.Point moves. With a delay, a FORWARD TSN that would go alone is held:
    /// the first DATA sent in the delay carries it, and at the end of the delay, counted from
    /// when it was first due, it goes alone. A SACK that catches up with the
    /// Advanced.Peer.Ack.Point in the meantime makes it unnecessary, and it is not sent. The
    /// T3-rtx timer runs throughout (RFC 3758 3.5 C5). The delay holds back the receiver's
    /// delivery of what it keeps for reordering behind the abandoned message (F3's NOTE).
    pub fn with_forward_tsn_delay(mut self, value: Option<Duration>) -> Self {
        self.forward_tsn_delay = value.map(|delay| delay.min(MAX_FORWARD_TSN_DELAY));
        self
    }

    /// See [`with_forward_tsn_delay`](Self::with_forward_tsn_delay).
    pub fn forward_tsn_delay(&self) -> Option<Duration> {
        self.forward_tsn_delay
    }

    /// The partial delivery point (RFC 6458 section 8.1.21, `SCTP_PARTIAL_DELIVERY_POINT`):
    /// once the fragments of a message held from its first one on, without a gap, come to
    /// this many bytes, [`Stream::read_part`](crate::Stream::read_part) gives them out before
    /// the message is complete (RFC 9260 section 6.9). A message no larger than this is read
    /// whole, unless the receive buffer runs out of space with nothing readable whole: then
    /// RFC 9260 6.9's "it SHOULD dispatch part of its inbound message" applies to a message
    /// of any size. Taken as at least 1 and at most the receive buffer size (RFC 6458: the
    /// point may not be set "larger than the socket receive buffer size").
    ///
    /// The default is half the receive buffer
    /// ([`with_max_receive_buffer_size`](Self::with_max_receive_buffer_size)); the RFCs give
    /// none. From there a single message never closes the window by itself: when it starts
    /// partial delivery at least half the buffer is free, which is at or above the window
    /// silly window avoidance advertises as closed (`min(buffer / 2, one full chunk)`, RFC 9260
    /// 6.2), so RFC 9260 6.2's drop never meets it. And every message up to half the buffer
    /// (512 KiB with the default 1 MiB, above any `max-message-size` a data channel offers by
    /// default) is still read whole.
    ///
    /// [`read_sctp`](crate::Stream::read_sctp) reads whole messages only; an application that
    /// reads with it alone does not use partial delivery.
    pub fn with_partial_delivery_point(mut self, value: u32) -> Self {
        self.partial_delivery_point = Some(value);
        self
    }

    /// Turns fragmentation of user messages off (RFC 9260 6.9: "An implementation MAY allow the
    /// upper layer to disable fragmentation"). The association then acts "just like an
    /// implementation that does NOT support fragmentation": a message that does not fit in one
    /// DATA chunk of a full-sized packet (the PMDCS less the chunk header) is refused with
    /// `Error::ErrOutboundPacketTooLarge` instead of being sent in fragments. Off by default.
    pub fn with_fragmentation(mut self, enabled: bool) -> Self {
        self.no_fragmentation = !enabled;
        self
    }

    /// Whether user messages are fragmented: see [`with_fragmentation`](Self::with_fragmentation).
    pub fn fragmentation(&self) -> bool {
        !self.no_fragmentation
    }

    /// The partial delivery point in effect: see
    /// [`with_partial_delivery_point`](Self::with_partial_delivery_point).
    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))
    }

    /// Path MTU discovery (DPLPMTUD, RFC 8899 section 6.2, with the PAD chunk of RFC 4820):
    /// once established, the association confirms its packet size (what
    /// [`Association::set_path_mtu`](crate::Association::set_path_mtu) set, else the
    /// default) with a probe, searches for a larger one up to
    /// [`PathMtuDiscoveryConfig::with_max_path_mtu`], and falls back to it when the path
    /// stops carrying the larger size (RFC 9260 section 7.3; RFC 8261 section 4: SCTP over
    /// DTLS "MUST implement and use" a discovery method that works without ICMP). `None`, the
    /// crate's default, keeps the packet size where the transport sets it: the transport
    /// knows the largest packet worth probing for, so it turns discovery on. The `rtci` peer
    /// connection does, by default (`SettingEngineBuilder::with_sctp_path_mtu_discovery`).
    pub fn with_path_mtu_discovery(mut self, value: Option<PathMtuDiscoveryConfig>) -> Self {
        self.path_mtu_discovery = value;
        self
    }

    /// The path MTU discovery settings, see
    /// [`with_path_mtu_discovery`](Self::with_path_mtu_discovery).
    pub fn path_mtu_discovery(&self) -> Option<PathMtuDiscoveryConfig> {
        self.path_mtu_discovery
    }

    /// Sets L of RFC 9260 section 7.2.1: in slow start one SACK grows the congestion window
    /// by at most the bytes it acknowledges and at most L packets (L x PMDCS). The RFC says L
    /// SHOULD be 1 and MAY be larger (RFC 3465 discusses the choice): 1 is the default. A
    /// receiver that acknowledges many packets with one SACK, as one that reads its socket in
    /// batches does, makes a sender with L = 1 leave slow start slowly; a larger L restores
    /// the faster ramp at the price the RFC names (a burst after such a SACK, and trust in
    /// the receiver not to split its acknowledgements). Zero counts as one.
    pub fn with_slow_start_growth_limit(mut self, value: u32) -> Self {
        self.slow_start_growth_limit = value.max(1);
        self
    }

    /// L, see [`with_slow_start_growth_limit`](Self::with_slow_start_growth_limit).
    pub fn slow_start_growth_limit(&self) -> u32 {
        self.slow_start_growth_limit
    }

    /// Whether PR-SCTP (RFC 3758) is announced to the peer and used. On by default, as WebRTC
    /// data channels need it (RFC 8831 section 6.1). Off, neither chunk 192 nor the
    /// Forward-TSN-Supported parameter is announced, no message is ever abandoned, and a
    /// FORWARD TSN from the peer is answered as an unrecognized chunk.
    pub fn with_partial_reliability(mut self, value: bool) -> Self {
        self.partial_reliability = value;
        self
    }

    /// See [`with_partial_reliability`](Self::with_partial_reliability).
    pub fn partial_reliability(&self) -> bool {
        self.partial_reliability
    }

    /// Whether user message interleaving (RFC 8260) is announced to the peer. When the peer
    /// announces it too, user data travels in I-DATA chunks: the fragments of messages on
    /// different streams may be interleaved, so a large message on one stream no longer
    /// holds up the others, and the [stream scheduler](Self::with_stream_scheduler) chooses
    /// the stream for every chunk. RFC 8831 section 6.1 says WebRTC data channels SHOULD use
    /// it. Off by default; an application reads whole messages either way, so it needs no
    /// change to turn it on.
    pub fn with_message_interleaving(mut self, value: bool) -> Self {
        self.message_interleaving = value;
        self
    }

    /// See [`with_message_interleaving`](Self::with_message_interleaving).
    pub fn message_interleaving(&self) -> bool {
        self.message_interleaving
    }

    /// Says that the association runs over DTLS (RFC 8261), which detects errors better than
    /// SCTP's CRC32c does, and so allows the zero checksum of RFC 9653 with the "SCTP over
    /// DTLS" error detection method (section 6):
    ///
    /// - the INIT or INIT ACK carries the Zero Checksum Acceptable parameter, and packets
    ///   that arrive with a checksum of zero are taken, their CRC32c not computed;
    /// - when the peer announces the same, packets are sent with a checksum of zero and
    ///   their CRC32c is not computed either. The packets RFC 9653 section 5.2 excepts keep
    ///   a correct one: an INIT, a COOKIE ECHO, an answer to an out-of-the-blue packet.
    ///
    /// Off by default: every packet carries its CRC32c and one without is dropped. It MUST
    /// NOT be turned on for an association that does not run over DTLS; a WebRTC data
    /// channel transport always does.
    pub fn with_zero_checksum(mut self, value: bool) -> Self {
        self.zero_checksum = value;
        self
    }

    /// See [`with_zero_checksum`](Self::with_zero_checksum).
    pub fn zero_checksum(&self) -> bool {
        self.zero_checksum
    }

    /// Sets SACK.Delay (RFC 9260 sections 6.2 and 16): how long the acknowledgement of a DATA
    /// chunk may wait for a second one. Defaults to 200 ms. The RFC forbids more than 500 ms,
    /// so a longer delay is taken as 500 ms.
    pub fn with_sack_delay(mut self, value: Duration) -> Self {
        self.sack_delay = value.min(Duration::from_millis(500));
        self
    }

    /// SACK.Delay, see [`with_sack_delay`](Self::with_sack_delay).
    pub fn sack_delay(&self) -> Duration {
        self.sack_delay
    }

    /// Sets Max.Burst (RFC 9260 sections 6.1 D and 16): before DATA is sent the congestion
    /// window is brought down to what is outstanding plus this many packets, so that one
    /// SACK for many packets does not release as many at once. Defaults to 4, the value the
    /// RFC recommends. `None` applies no limit: a peer that acknowledges in batches (one that
    /// reads its socket in bursts) otherwise has this side's window cut back on every SACK.
    pub fn with_max_burst(mut self, value: Option<u32>) -> Self {
        self.max_burst = value;
        self
    }

    /// Max.Burst, see [`with_max_burst`](Self::with_max_burst).
    pub fn max_burst(&self) -> Option<u32> {
        self.max_burst
    }

    /// Sets HB.interval (RFC 9260 8.3, 16): an association whose path has been idle for an RTO
    /// plus this long sends a HEARTBEAT, which measures the round trip and shows that the peer
    /// is still there. One left unanswered counts toward
    /// [`TimerConfig::max_t3_rtx_retrans`](crate::TimerConfig). Defaults to 30 seconds; `None`
    /// sends no HEARTBEAT.
    pub fn with_heartbeat_interval(mut self, value: Option<Duration>) -> Self {
        self.heartbeat_interval = value;
        self
    }

    /// HB.interval, see [`with_heartbeat_interval`](Self::with_heartbeat_interval).
    pub fn heartbeat_interval(&self) -> Option<Duration> {
        self.heartbeat_interval
    }

    /// Sets Valid.Cookie.Life: how long after an INIT ACK its State Cookie is accepted in a
    /// COOKIE ECHO (RFC 9260 5.1.3, 16). Later it is refused with a "Stale Cookie" error and
    /// the peer starts again. Defaults to 60 seconds.
    pub fn with_valid_cookie_life(mut self, value: Duration) -> Self {
        self.valid_cookie_life = value;
        self
    }

    /// Valid.Cookie.Life, see [`with_valid_cookie_life`](Self::with_valid_cookie_life).
    pub fn valid_cookie_life(&self) -> Duration {
        self.valid_cookie_life
    }

    /// Sets this endpoint's SCTP port, the source port of what it sends (RFC 8841 5: its own
    /// `a=sctp-port`). Defaults to 5000. Port 0 MUST NOT be used (RFC 9260 section 3.1):
    /// [`Endpoint::connect`](crate::Endpoint::connect) refuses a configuration with it
    /// (`ConnectError::ZeroSctpPort`), and an accepting endpoint answers on the INIT's ports.
    pub fn with_sctp_port(mut self, value: u16) -> Self {
        self.sctp_port = value;
        self
    }

    /// Sets the peer's SCTP port, the destination port of the INIT this endpoint sends when it
    /// initiates (RFC 8841 5: the remote `a=sctp-port`). Defaults to 5000. An endpoint that
    /// accepts an association answers on the ports of the INIT it received. Port 0 is refused
    /// by [`Endpoint::connect`](crate::Endpoint::connect) (RFC 9260 section 3.1).
    pub fn with_remote_sctp_port(mut self, value: u16) -> Self {
        self.remote_sctp_port = value;
        self
    }

    /// Sets the advertised receive window (a_rwnd), bounding how much unacknowledged data a peer
    /// may have in flight toward this endpoint. At least 1500: RFC 9260 3.3.2 and 3.3.3 forbid
    /// a smaller a_rwnd in the INIT and INIT ACK, so a smaller value is raised to it.
    pub fn with_max_receive_buffer_size(mut self, value: u32) -> Self {
        self.max_receive_buffer_size = value.max(MIN_ADVERTISED_RECEIVER_WINDOW);
        self
    }

    /// Sets the largest message this endpoint will send, which is the peer's limit (RFC 8841
    /// 6.1: the remote `max-message-size`). Also the largest it will accept unless
    /// [`with_max_receive_message_size`](Self::with_max_receive_message_size) sets that apart.
    pub fn with_max_message_size(mut self, value: u32) -> Self {
        self.max_message_size = value;
        self
    }

    /// Sets the largest message this endpoint will accept, which is the limit it advertised
    /// itself (RFC 8841 6.1: the local `max-message-size`). Each direction has its own limit;
    /// the receive buffer keeps room for one message of this size beyond its bound, so a
    /// message larger than the buffer can still be reassembled.
    pub fn with_max_receive_message_size(mut self, value: u32) -> Self {
        self.max_receive_message_size = Some(value);
        self
    }

    /// Sets how many outbound streams to request during the handshake. At least 1: RFC 9260
    /// 3.3.2 and 3.3.3 forbid 0 in the INIT and INIT ACK.
    pub fn with_max_num_outbound_streams(mut self, value: u16) -> Self {
        self.max_num_outbound_streams = value.max(1);
        self
    }

    /// Sets how many inbound streams this endpoint will accept. At least 1, as for the
    /// outbound streams.
    pub fn with_max_num_inbound_streams(mut self, value: u16) -> Self {
        self.max_num_inbound_streams = value.max(1);
        self
    }

    /// Whether an expiry of T1-init or T1-cookie backs off the RTO of the path, as a T3-rtx
    /// expiry does. On by default: RFC 9260 section 5.1, "The T1-init timer and T1-cookie
    /// timer SHOULD follow the same rules given in Section 6.3", whose rule E2 (6.3.3) is "set
    /// RTO = RTO * 2 ('back off the timer')" for the destination, bounded by RTO.Max. Each
    /// timer is started with the path's RTO, so T1-cookie starts where T1-init's backoff
    /// left the RTO, and the first DATA after the handshake does too, until a round trip is
    /// measured (6.3.1 C2).
    ///
    /// `false` is what libwebrtc's dcSCTP does (`t1_init_` and `t1_cookie_` in
    /// `net/dcsctp/socket/dcsctp_socket.cc`: each timer starts at its own 1 s and doubles by
    /// itself): each timer starts at RTO.Initial and doubles on its own expiries, and the RTO
    /// the data transfer uses is left alone, so the first DATA after a handshake that lost
    /// packets is retransmitted an RTO.Initial after it is sent.
    pub fn with_handshake_timers_back_off_rto(mut self, value: bool) -> Self {
        self.handshake_timers_back_off_rto = value;
        self
    }

    /// See [`with_handshake_timers_back_off_rto`](Self::with_handshake_timers_back_off_rto).
    pub fn handshake_timers_back_off_rto(&self) -> bool {
        self.handshake_timers_back_off_rto
    }

    /// Overrides the retransmission limits; see [`TimerConfig`].
    pub fn with_timer_config(mut self, value: TimerConfig) -> Self {
        self.timer_config = value;
        self
    }

    /// Sets RTO.Initial, RTO.Min and RTO.Max (RFC 9260 sections 6.3.1 and 16); see
    /// [`RtoConfig`]. The defaults are the RFC's: 1, 1 and 60 seconds. With
    /// [`TimerConfig::max_t3_rtx_retrans`] (Association.Max.Retrans) they bound how long an
    /// unanswered peer is retransmitted to before the association fails.
    pub fn with_rto_config(mut self, value: RtoConfig) -> Self {
        self.rto_config = value;
        self
    }

    /// Chooses how the next message to send is picked among the streams.
    pub fn with_stream_scheduler(mut self, value: StreamScheduler) -> Self {
        self.stream_scheduler = value;
        self
    }

    /// The configured SCTP port.
    pub fn sctp_port(&self) -> u16 {
        self.sctp_port
    }

    /// The configured SCTP port of the peer.
    pub fn remote_sctp_port(&self) -> u16 {
        self.remote_sctp_port
    }

    /// The configured receive window in bytes.
    pub fn max_receive_buffer_size(&self) -> u32 {
        self.max_receive_buffer_size
    }

    /// The configured maximum message size to send, in bytes.
    pub fn max_message_size(&self) -> u32 {
        self.max_message_size
    }

    /// The configured maximum message size to accept, in bytes: the send limit unless set
    /// apart with [`with_max_receive_message_size`](Self::with_max_receive_message_size).
    pub fn max_receive_message_size(&self) -> u32 {
        self.max_receive_message_size
            .unwrap_or(self.max_message_size)
    }

    /// The configured outbound stream count.
    pub fn max_num_outbound_streams(&self) -> u16 {
        self.max_num_outbound_streams
    }

    /// The configured inbound stream count.
    pub fn max_num_inbound_streams(&self) -> u16 {
        self.max_num_inbound_streams
    }

    /// The configured retransmission limits.
    pub fn timer_config(&self) -> TimerConfig {
        self.timer_config
    }

    /// The configured RTO bounds.
    pub fn rto_config(&self) -> RtoConfig {
        self.rto_config
    }

    /// The configured stream scheduler.
    pub fn stream_scheduler(&self) -> StreamScheduler {
        self.stream_scheduler
    }
}

/// Global configuration for the endpoint, affecting all associations
///
/// Default values should be suitable for most internet applications.
#[derive(Clone)]
pub struct EndpointConfig {
    pub(crate) max_payload_size: u32,

    /// AID generator factory
    ///
    /// Create a aid generator for local aid in Endpoint struct
    pub(crate) aid_generator_factory:
        Arc<dyn (Fn() -> Box<dyn AssociationIdGenerator + Send>) + Send + Sync>,

    /// Where the endpoint's associations draw their random values from.
    pub(crate) random: RandomSource,
}

impl Default for EndpointConfig {
    fn default() -> Self {
        Self::new()
    }
}

impl EndpointConfig {
    /// Create a default configuration
    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(),
        }
    }

    /// Draws every random value of the endpoint and its associations from `provider`'s
    /// `random()`: the verification tags (with the default generator, which this replaces;
    /// set [`Self::aid_generator`] after this call for another), the initial TSNs, the State
    /// Cookies made without [`ServerConfig::cookie_authentication`], the Initiate Tag of an
    /// INIT ACK for an existing association, HEARTBEAT nonces and the HEARTBEAT timer's
    /// jitter.
    ///
    /// Without it (the default) they come from `rand`'s thread-local CSPRNG. This is how the
    /// other crates of the workspace take their randomness (`docs/randomness-audit.md`), and
    /// what lets a test that seeds the provider replay a run exactly.
    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
    }

    /// Supply a custom Association ID generator factory
    ///
    /// Called once by each `Endpoint` constructed from this configuration to obtain the AID
    /// generator which will be used to generate the AIDs used for incoming packets on all
    /// associations involving that  `Endpoint`. A custom AID generator allows applications to embed
    /// information in local association IDs, e.g. to support stateless packet-level load balancers.
    ///
    /// `EndpointConfig::new()` applies a default random AID generator factory. This functions
    /// accepts any customized AID generator to reset AID generator factory that implements
    /// the `AssociationIdGenerator` trait.
    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
    }

    /// Maximum payload size accepted from peers.
    ///
    /// The default is suitable for typical internet applications. Applications which expect to run
    /// on networks supporting Ethernet jumbo frames or similar should set this appropriately.
    pub fn max_payload_size(&mut self, value: u32) -> &mut Self {
        self.max_payload_size = value;
        self
    }

    /// Get the current value of `max_payload_size`
    ///
    /// While most parameters don't need to be readable, this must be exposed to allow higher-level
    /// layers to determine how large a receive buffer to allocate to
    /// support an externally-defined `EndpointConfig`.
    ///
    /// While `get_` accessors are typically unidiomatic in Rust, we favor concision for setters,
    /// which will be used far more heavily.
    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()
    }
}

/// Parameters governing incoming associations
///
/// Default values should be suitable for most internet applications.
#[derive(Clone)]
pub struct ServerConfig {
    /// Transport configuration to use for incoming associations
    pub transport: Arc<TransportConfig>,

    /// Maximum number of concurrent associations
    pub(crate) concurrent_associations: u32,

    /// The crypto provider State Cookies are authenticated with, when one was given.
    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 {
    /// Create a default configuration with a particular handshake token key
    pub fn new(transport: TransportConfig) -> Self {
        ServerConfig {
            transport: Arc::new(transport),
            concurrent_associations: 100_000,
            cookie_provider: None,
        }
    }

    /// Gives the endpoint a crypto provider to authenticate State Cookies with, and makes
    /// the handshake stateless on the accepting side, as RFC 9260 sections 5.1 and 5.1.3
    /// have it.
    ///
    /// With a provider, the State Cookie of an INIT ACK holds everything the association is
    /// made from, the time it was made, and an HMAC-SHA-256 over them under a random key of
    /// the endpoint's (replaced every hour). The endpoint answers an INIT and keeps nothing:
    /// [`Endpoint::handle`](crate::Endpoint::handle) returns `None` for it and the INIT ACK
    /// leaves by [`Endpoint::poll_transmit`](crate::Endpoint::poll_transmit). The
    /// association is made, and returned as
    /// [`DatagramEvent::NewAssociation`](crate::DatagramEvent::NewAssociation), when a
    /// COOKIE ECHO brings back a cookie whose MAC verifies and which is no older than
    /// [`TransportConfig::with_valid_cookie_life`]; it is established at once.
    ///
    /// Without a provider (the default) the cookie is 32 random bytes and the endpoint makes
    /// the association when the INIT arrives, remembering the cookie to compare it with the
    /// one echoed. `rtci-sctp` names no cryptographic implementation of its own, so the MAC
    /// is there only when the application supplies the provider.
    pub fn cookie_authentication(
        &mut self,
        provider: Arc<dyn crypto::RTCCryptoProvider>,
    ) -> &mut Self {
        self.cookie_provider = Some(provider);
        self
    }

    /// Maximum number of associations the endpoint holds at once. An INIT that would start
    /// one more is refused.
    ///
    /// A transport that carries a single association, such as WebRTC's SCTP over one DTLS
    /// transport (RFC 8261), should set this to 1.
    pub fn concurrent_associations(&mut self, value: u32) -> &mut Self {
        self.concurrent_associations = value;
        self
    }
}

/// Configuration for outgoing associations
///
/// Default values should be suitable for most internet applications.
#[derive(Debug, Clone)]
pub struct ClientConfig {
    /// Transport configuration to use
    pub transport: Arc<TransportConfig>,
}

impl Default for ClientConfig {
    fn default() -> Self {
        ClientConfig {
            transport: Arc::new(TransportConfig::default()),
        }
    }
}

impl ClientConfig {
    /// Create a default configuration with a particular cryptographic configuration
    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() {
        // INITIAL_MTU bounds the assembled SCTP packet. The default is the
        // exact TURN-relayed IPv6 budget (pion/sctp#476, webrtc-rs/webrtc#807):
        // the 1280-byte IPv6 minimum MTU (RFC 8200) minus IPv6, UDP, and TURN
        // ChannelData headers and DTLS record overhead.
        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
        );
        // A single maximum-size DATA chunk must marshal within INITIAL_MTU:
        // common header + the chunk header and payload, padded to 4 bytes.
        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() {
        // `max_payload_size_for_mtu(INITIAL_MTU)` must reproduce the default
        // payload budget exactly.
        assert_eq!(
            max_payload_size_for_mtu(INITIAL_MTU),
            EndpointConfig::default().get_max_payload_size()
        );

        // Rounded down to the 4-byte padding boundary: the last MTU of one
        // padding window and the first of the next straddle a 4-byte step.
        assert_eq!(max_payload_size_for_mtu(1203), 1172);
        assert_eq!(max_payload_size_for_mtu(1204), 1176);

        // Values below MIN_DATA_PACKET_MTU behave exactly as the 32-byte
        // floor: the smallest representable padded DATA packet, a 4-byte
        // payload budget.
        for mtu in [0, 31, 32] {
            assert_eq!(max_payload_size_for_mtu(mtu), 4, "mtu {mtu}");
        }

        // Upper edge: the derivation must not overflow.
        assert_eq!(
            max_payload_size_for_mtu(u32::MAX),
            (u32::MAX - (COMMON_HEADER_SIZE + DATA_CHUNK_HEADER_SIZE)) & !3
        );
    }
}