Skip to main content

rtci_sctp/association/
stream.rs

1use crate::association::Association;
2use crate::association::state::AssociationState;
3use crate::chunk::chunk_payload_data::{
4    ChunkPayloadData, MessageReliability, PayloadProtocolIdentifier,
5};
6use crate::queue::reassembly_queue::{Chunks, MessagePart, ReassemblyQueue};
7use crate::{ErrorCauseCode, Event, Side};
8use shared::error::{Error, Result};
9
10use crate::util::{ByteSlice, BytesArray, BytesChunk, BytesSource};
11use bytes::Bytes;
12use log::{debug, error, trace};
13use std::fmt;
14use std::time::{Duration, Instant};
15
16/// Identifier for a stream within a particular association
17pub type StreamId = u16;
18
19/// Application events about streams
20#[derive(Debug, PartialEq, Eq)]
21#[non_exhaustive]
22pub enum StreamEvent {
23    /// One or more new streams has been opened
24    Opened {
25        /// Which stream was opened.
26        id: StreamId,
27    },
28    /// A currently open stream has data or errors waiting to be read
29    Readable {
30        /// Which stream is now readable
31        id: StreamId,
32    },
33    /// A formerly write-blocked stream might be ready for a write or have been stopped
34    ///
35    /// Only generated for streams that are currently open.
36    Writable {
37        /// Which stream is now writable
38        id: StreamId,
39    },
40    /// A finished stream has been fully acknowledged or stopped
41    Finished {
42        /// Which stream has been finished
43        id: StreamId,
44    },
45    /// The peer asked us to stop sending on an outgoing stream
46    Stopped {
47        /// Which stream has been stopped
48        id: StreamId,
49        /// Error code supplied by the peer
50        error_code: ErrorCauseCode,
51    },
52    /// At least one new stream of a certain directionality may be opened
53    Available,
54    /// The number of bytes of outgoing data buffered is lower than the threshold.
55    BufferedAmountLow {
56        /// Which stream is now readable
57        id: StreamId,
58    },
59    /// The number of bytes of outgoing data buffered is higher than the threshold.
60    BufferedAmountHigh {
61        /// Which stream is now readable
62        id: StreamId,
63    },
64    /// Outgoing buffered data was released (acknowledged OR abandoned), carrying
65    /// the exact number of user payload bytes freed for this stream. Unlike the
66    /// edge-triggered [`StreamEvent::BufferedAmountLow`], this fires on every
67    /// release with the byte delta, so upper layers can keep their own
68    /// send-buffer accounting (e.g. a synchronous back-pressure counter) exact.
69    BufferedAmountReleased {
70        /// Which stream released buffered bytes
71        id: StreamId,
72        /// User payload bytes released
73        n_bytes: usize,
74    },
75    /// A message of a partially reliable stream was abandoned (RFC 3758 section 3.5, 4.1):
76    /// its lifetime or its number of retransmissions ran out, and the peer will not get it.
77    MessageAbandoned {
78        /// The stream the message was written to
79        id: StreamId,
80        /// Whether any of it had been sent. A message that expired before its first
81        /// transmission (RFC 3758 4.1 TR3) took no TSN and no stream sequence number.
82        transmitted: bool,
83    },
84    /// The message of this stream that was being read in parts ([`Stream::read_part`]) will
85    /// not be completed: the sender abandoned it (a FORWARD TSN or I-FORWARD-TSN skipped the
86    /// rest of it, RFC 3758 section 3.6, RFC 8260 section 2.3.1) or the stream's sequence
87    /// numbers were reset (RFC 6525). No part with `end_of_record` follows; the parts already
88    /// read are all there is of it. RFC 6458 section 6.1.7, `SCTP_PARTIAL_DELIVERY_ABORTED`.
89    PartialDeliveryAborted {
90        /// The stream the message was on
91        id: StreamId,
92        /// Whether it was an unordered message
93        unordered: bool,
94        /// Its Stream Sequence Number (DATA) or Message Identifier (I-DATA, RFC 8260)
95        sequence: u32,
96    },
97}
98
99/// Reliability type for stream
100#[derive(Default, Debug, Copy, Clone, PartialEq)]
101#[non_exhaustive]
102pub enum ReliabilityType {
103    /// ReliabilityTypeReliable is used for reliable transmission
104    #[default]
105    Reliable = 0,
106    /// ReliabilityTypeRexmit is used for partial reliability by retransmission count
107    Rexmit = 1,
108    /// ReliabilityTypeTimed is used for partial reliability by retransmission duration
109    Timed = 2,
110    /// The priority policy of RFC 7496 section 3.2: the reliability value is the messages'
111    /// priority (section 4.2: 0 is the highest, a larger value a lower priority). When the send
112    /// buffer has no room for a message
113    /// ([`TransportConfig::with_send_buffer_size`](crate::TransportConfig::with_send_buffer_size)),
114    /// unsent messages of this policy with a lower priority are abandoned to make room;
115    /// otherwise the messages are sent, and retransmitted, as reliable ones.
116    Priority = 3,
117}
118
119impl fmt::Display for ReliabilityType {
120    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
121        let s = match *self {
122            ReliabilityType::Reliable => "Reliable",
123            ReliabilityType::Rexmit => "Rexmit",
124            ReliabilityType::Timed => "Timed",
125            ReliabilityType::Priority => "Priority",
126        };
127        write!(f, "{}", s)
128    }
129}
130
131impl From<u8> for ReliabilityType {
132    fn from(v: u8) -> ReliabilityType {
133        match v {
134            1 => ReliabilityType::Rexmit,
135            2 => ReliabilityType::Timed,
136            3 => ReliabilityType::Priority,
137            _ => ReliabilityType::Reliable,
138        }
139    }
140}
141
142/// Stream represents an SCTP stream
143pub struct Stream<'a> {
144    pub(crate) stream_identifier: StreamId,
145    pub(crate) association: &'a mut Association,
146}
147
148impl Stream<'_> {
149    /// read reads a packet of len(p) bytes, dropping the Payload Protocol Identifier.
150    /// Returns EOF when the stream is reset or an error if the stream is closed
151    /// otherwise.
152    pub fn read(&mut self) -> Result<Option<Chunks>> {
153        self.read_sctp()
154    }
155
156    /// read_sctp reads a packet of len(p) bytes and returns the associated Payload
157    /// Protocol Identifier.
158    /// Returns EOF when the stream is reset or an error if the stream is closed
159    /// otherwise.
160    pub fn read_sctp(&mut self) -> Result<Option<Chunks>> {
161        if let Some(s) = self.association.streams.get_mut(&self.stream_identifier)
162            && (s.state == RecvSendState::ReadWritable || s.state == RecvSendState::Readable)
163        {
164            let bytes_before = s.get_num_bytes_in_reassembly_queue();
165            let chunks = s.reassembly_queue.read();
166            let drained = !s.reassembly_queue.is_readable();
167            self.association
168                .reindex_stream(self.stream_identifier, bytes_before);
169            if chunks.is_some() {
170                self.association.on_receive_buffer_drained();
171                // What is left may be all incomplete, with the window still closed.
172                self.association.offer_partial_delivery();
173            }
174            if drained {
175                self.association
176                    .retry_deferred_resets(self.stream_identifier);
177            }
178            Ok(chunks)
179        } else {
180            Err(Error::ErrStreamClosed)
181        }
182    }
183
184    /// Reads the next part of a message: the partial delivery API of RFC 9260 section 6.9
185    /// (the RECEIVE primitive with its "partial flag", 11.1.7; RFC 6458 `MSG_EOR`).
186    ///
187    /// A complete message comes whole, as one part with
188    /// [`end_of_record`](MessagePart::end_of_record) set, just as [`read_sctp`](Self::read_sctp)
189    /// gives it. A message that has not all arrived is given out in parts once the fragments
190    /// of it held from the first on come to the partial delivery point
191    /// ([`TransportConfig::with_partial_delivery_point`](crate::TransportConfig::with_partial_delivery_point)),
192    /// or whatever their size when the receive buffer is out of space (a window that would be
193    /// advertised as closed, with nothing readable whole). Its first part has
194    /// [`first`](MessagePart::first) set, and its last `end_of_record`; until then nothing else
195    /// of this stream is read, by either method. What is read leaves the receive buffer at
196    /// once, and a window that was closed is announced open again (RFC 9260 6.2).
197    ///
198    /// Without this, a message larger than the receive buffer, or interleaved messages
199    /// (RFC 8260) that fill it together, cannot arrive under the rule of RFC 9260 section 6.2
200    /// ("When the receiver's advertised window is 0, the receiver MUST drop any new incoming
201    /// DATA chunk with a TSN larger than the largest TSN received so far").
202    ///
203    /// Returns `Ok(None)` when the stream has nothing to read in this way, and an error if the
204    /// stream is closed.
205    pub fn read_part(&mut self) -> Result<Option<MessagePart>> {
206        let threshold = self.association.partial_delivery_threshold();
207        if let Some(s) = self.association.streams.get_mut(&self.stream_identifier)
208            && (s.state == RecvSendState::ReadWritable || s.state == RecvSendState::Readable)
209        {
210            let bytes_before = s.get_num_bytes_in_reassembly_queue();
211            let part = s.reassembly_queue.read_part(threshold);
212            let drained = !s.reassembly_queue.holds_whole_message();
213            self.association
214                .reindex_stream(self.stream_identifier, bytes_before);
215            if part.is_some() {
216                self.association.on_receive_buffer_drained();
217                self.association.offer_partial_delivery();
218            }
219            if drained {
220                self.association
221                    .retry_deferred_resets(self.stream_identifier);
222            }
223            Ok(part)
224        } else {
225            Err(Error::ErrStreamClosed)
226        }
227    }
228
229    /// Whether a message of this stream is being read in parts: its first part was read
230    /// with [`read_part`](Self::read_part) and its last not yet.
231    pub fn in_partial_delivery(&self) -> bool {
232        self.association
233            .streams
234            .get(&self.stream_identifier)
235            .is_some_and(|s| s.reassembly_queue.in_partial_delivery())
236    }
237
238    /// write_sctp writes len(p) bytes from p to the DTLS connection
239    ///
240    /// `now` is the instant the message is handed to the stack. See the note on
241    /// [`Stream`] for why it is a parameter.
242    pub fn write_sctp(
243        &mut self,
244        now: Instant,
245        p: &Bytes,
246        ppi: PayloadProtocolIdentifier,
247    ) -> Result<usize> {
248        self.write_source(now, &mut BytesChunk::new(p), ppi, ppi.number())
249    }
250
251    /// Sends a message with any Payload Protocol Identifier (RFC 9260 section 3.3.1: the
252    /// value is the application's and SCTP passes it through unchanged). The receiver reads
253    /// it from [`Chunks::ppid`].
254    ///
255    /// [`PayloadProtocolIdentifier`] names only the WebRTC values; this takes the number.
256    pub fn write_sctp_with_ppid(&mut self, now: Instant, p: &Bytes, ppid: u32) -> Result<usize> {
257        self.write_source(now, &mut BytesChunk::new(p), ppid.into(), ppid)
258    }
259
260    /// Send data on the given stream.
261    ///
262    /// Uses the deafult payload protocol (PPI).
263    ///
264    /// Returns the number of bytes successfully written.
265    pub fn write(&mut self, now: Instant, data: &[u8]) -> Result<usize> {
266        self.write_with_ppi(now, data, self.get_default_payload_type()?)
267    }
268
269    /// Send data on the given stream, with a specific payload protocol.
270    ///
271    /// Returns the number of bytes successfully written.
272    pub fn write_with_ppi(
273        &mut self,
274        now: Instant,
275        data: &[u8],
276        ppi: PayloadProtocolIdentifier,
277    ) -> Result<usize> {
278        self.write_source(now, &mut ByteSlice::from_slice(data), ppi, ppi.number())
279    }
280
281    /// write writes len(p) bytes from p with the default Payload Protocol Identifier
282    pub fn write_chunk(&mut self, now: Instant, p: &Bytes) -> Result<usize> {
283        let ppi = self.get_default_payload_type()?;
284        self.write_source(now, &mut BytesChunk::new(p), ppi, ppi.number())
285    }
286
287    /// Send an owned [`Bytes`] on the stream with a specific payload protocol.
288    ///
289    /// Unlike [`write_with_ppi`](Self::write_with_ppi), which takes a `&[u8]` and
290    /// must copy it into a freshly allocated buffer, this enqueues the payload
291    /// zero-copy: each fragment is a refcounted slice of `data`. Prefer this on the
292    /// hot send path when the caller already owns the payload as `Bytes`.
293    ///
294    /// Returns the number of bytes successfully written.
295    pub fn write_chunk_with_ppi(
296        &mut self,
297        now: Instant,
298        data: &Bytes,
299        ppi: PayloadProtocolIdentifier,
300    ) -> Result<usize> {
301        self.write_source(now, &mut BytesChunk::new(data), ppi, ppi.number())
302    }
303
304    /// Send data on the given stream
305    ///
306    /// Returns the number of bytes and chunks successfully written.
307    /// Note that this method might also write a partial chunk. In this case
308    /// it will not count this chunk as fully written. However
309    /// the chunk will be advanced and contain only non-written data after the call.
310    pub fn write_chunks(&mut self, now: Instant, data: &mut [Bytes]) -> Result<usize> {
311        let ppi = self.get_default_payload_type()?;
312        self.write_source(now, &mut BytesArray::from_chunks(data), ppi, ppi.number())
313    }
314
315    /// write_source writes BytesSource to the DTLS connection
316    fn write_source<B: BytesSource>(
317        &mut self,
318        now: Instant,
319        source: &mut B,
320        ppi: PayloadProtocolIdentifier,
321        ppid: u32,
322    ) -> Result<usize> {
323        if !self.is_writable() {
324            return Err(Error::ErrStreamClosed);
325        }
326
327        // RFC 9260 3.3.1: a DATA chunk carries at least one byte of user data, so there is no
328        // empty user message. Refused before anything is consumed: an empty write used to
329        // take a Stream Sequence Number and send nothing, and the receiver waited for that
330        // number for ever.
331        if source.remaining() == 0 {
332            return Err(Error::OtherSctpErr(
333                "an empty user message cannot be sent (RFC 9260 3.3.1)".into(),
334            ));
335        }
336
337        if source.remaining() > self.association.max_message_size() as usize {
338            return Err(Error::ErrOutboundPacketTooLarge);
339        }
340
341        // RFC 9260 6.9: with fragmentation turned off, "it MUST reject sends that exceed the
342        // current PMDCS".
343        if !self.association.fragmentation()
344            && source.remaining() > self.association.fragment_size() as usize
345        {
346            return Err(Error::ErrOutboundPacketTooLarge);
347        }
348
349        let state: AssociationState = self.association.state();
350        match state {
351            AssociationState::ShutdownSent
352            | AssociationState::ShutdownAckSent
353            | AssociationState::ShutdownPending
354            | AssociationState::ShutdownReceived => return Err(Error::ErrStreamClosed),
355            _ => {}
356        };
357
358        let id = self.association.allocate_message_id()?;
359        // RFC 7496 3.2: a send buffer of a set size takes the message only if it has room, which
360        // the priority policy can make.
361        let reliability = self
362            .association
363            .streams
364            .get(&self.stream_identifier)
365            .ok_or(Error::ErrStreamClosed)?
366            .message_reliability(now, ppi);
367        self.association
368            .make_room_in_send_buffer(source.remaining(), reliability)?;
369        let fragment_size = self.association.fragment_size() as usize;
370        let i_data = self.association.message_interleaving();
371        let (p, _) = source.pop_chunk(self.association.max_message_size() as usize);
372
373        if let Some(s) = self.association.streams.get_mut(&self.stream_identifier) {
374            let (is_buffered_amount_high, mut chunks) =
375                s.packetize(now, &p, ppi, ppid, fragment_size, i_data);
376            // RFC 6525 5.1.2 A1: while a reset of this outgoing stream is not answered, new
377            // data gets no Stream Sequence Number and is queued. It goes out when the answer
378            // is in: numbered from 0 if the peer performed the reset, and on from where the
379            // stream was if it did not.
380            let held = s.outgoing_reset_pending;
381            if held {
382                for c in &mut chunks {
383                    c.message_id = Some(id);
384                }
385                s.held_writes.push(chunks);
386                chunks = vec![];
387            }
388
389            if is_buffered_amount_high {
390                trace!("StreamEvent::BufferedAmountHigh");
391                self.association
392                    .events
393                    .push_back(Event::Stream(StreamEvent::BufferedAmountHigh {
394                        id: self.stream_identifier,
395                    }))
396            }
397
398            if held {
399                self.association.held_write_count += 1;
400            } else {
401                self.association.send_payload_data(id, chunks);
402            }
403
404            Ok(p.len())
405        } else {
406            Err(Error::ErrStreamClosed)
407        }
408    }
409
410    /// Whether this stream has data or an error waiting to be read.
411    pub fn is_readable(&self) -> bool {
412        if let Some(s) = self.association.streams.get(&self.stream_identifier) {
413            s.state == RecvSendState::Readable || s.state == RecvSendState::ReadWritable
414        } else {
415            false
416        }
417    }
418
419    /// Whether this stream can currently accept more data.
420    pub fn is_writable(&self) -> bool {
421        if let Some(s) = self.association.streams.get(&self.stream_identifier) {
422            s.state == RecvSendState::Writable || s.state == RecvSendState::ReadWritable
423        } else {
424            false
425        }
426    }
427
428    /// stop closes the read-direction of the stream.
429    /// Future calls to read are not permitted after calling stop.
430    ///
431    /// `now` is the instant the caller is acting at: resetting the stream queues an outgoing
432    /// chunk, so it is on the same write path as [`write_sctp`](Self::write_sctp).
433    pub fn stop(&mut self, now: Instant) -> Result<()> {
434        let (mut reset, mut abandon) = (false, false);
435        if let Some(s) = self.association.streams.get_mut(&self.stream_identifier) {
436            // This side's direction is reset once: not again when the peer's Incoming SSN Reset
437            // Request has reset it already.
438            reset = !s.outgoing_reset_started;
439            abandon = !s.reads_stopped;
440            s.outgoing_reset_started = true;
441            s.state = ((s.state as u8) & 0x2).into();
442        }
443
444        if abandon {
445            // Nothing reads the stream from now on: what it holds, and what still arrives on it
446            // until the peer resets its direction, is abandoned. Held, it would take the
447            // receive window for good (a peer that sends the data it had queued on the stream
448            // before its reset, as RFC 6525 5.1.2 A3 asks, could fill it and never send that
449            // reset), and hold the peer's reset "In progress" (`streams_awaiting_drain`).
450            self.abandon_incoming();
451        }
452        if reset {
453            // Reset the outgoing stream
454            // https://tools.ietf.org/html/rfc6525
455            self.association
456                .send_reset_request(now, self.stream_identifier)?;
457        }
458
459        Ok(())
460    }
461
462    /// Drops what the stream holds of incoming data, and what arrives on it from now on.
463    fn abandon_incoming(&mut self) {
464        let id = self.stream_identifier;
465        let Some(s) = self.association.streams.get_mut(&id) else {
466            return;
467        };
468        s.reads_stopped = true;
469        let bytes_before = s.get_num_bytes_in_reassembly_queue();
470        if s.reassembly_queue.is_empty() {
471            return;
472        }
473        let mut emptied = ReassemblyQueue::new(id);
474        emptied.interleaved = s.reassembly_queue.interleaved;
475        s.reassembly_queue = emptied;
476        self.association.reindex_stream(id, bytes_before);
477        self.association.on_receive_buffer_drained();
478    }
479
480    /// finish closes the write-direction of the stream.
481    /// Future calls to write are not permitted after calling Close.
482    pub fn finish(&mut self) -> Result<()> {
483        if let Some(s) = self.association.streams.get_mut(&self.stream_identifier) {
484            s.state = ((s.state as u8) & 0x1).into();
485        }
486        Ok(())
487    }
488
489    /// Shuts down the read, write, or both halves of this stream.
490    ///
491    /// This function will cause all pending and future I/O on the specified portions to return
492    /// immediately with an appropriate value (see the documentation of `Shutdown`).
493    ///
494    /// Resets the stream when both halves of this stream are shutdown.
495    pub fn close(&mut self, now: Instant) -> Result<()> {
496        self.finish()?;
497        self.stop(now)
498    }
499
500    /// stream_identifier returns the Stream identifier associated to the stream.
501    pub fn stream_identifier(&self) -> StreamId {
502        self.stream_identifier
503    }
504
505    /// Sets this stream's priority, in data channel priority units (RFC 8832 section 5.1:
506    /// 128 below normal, 256 normal, 512 high, 1024 extra high; any value is taken). The
507    /// default is 256.
508    ///
509    /// It is the input of two [stream schedulers](crate::StreamScheduler): under
510    /// `WeightedFairQueueing` it is the stream's weight (a stream with n times the priority
511    /// gets n times the capacity, RFC 8260 section 3.6), under `Priority` its rank (the
512    /// higher value is served first, section 3.4). The other schedulers do not look at it.
513    /// It applies from the next scheduling decision on, to what the stream has queued too,
514    /// and lasts until the stream is reset.
515    ///
516    /// RFC 8831 section 6.4 has a data channel's priority drive the scheduler: the data
517    /// channel layer calls this with the priority of the channel (from `RTCDataChannelInit`
518    /// or the DATA_CHANNEL_OPEN message) when it opens or accepts the stream.
519    pub fn set_priority(&mut self, priority: u16) -> Result<()> {
520        if !self
521            .association
522            .streams
523            .contains_key(&self.stream_identifier)
524        {
525            return Err(Error::ErrStreamClosed);
526        }
527        self.association
528            .pending_queue
529            .set_weight(self.stream_identifier, priority);
530        Ok(())
531    }
532
533    /// set_default_payload_type sets the default payload type used by write.
534    pub fn set_default_payload_type(
535        &mut self,
536        default_payload_type: PayloadProtocolIdentifier,
537    ) -> Result<()> {
538        if let Some(s) = self.association.streams.get_mut(&self.stream_identifier) {
539            s.default_payload_type = default_payload_type;
540            Ok(())
541        } else {
542            Err(Error::ErrStreamClosed)
543        }
544    }
545
546    /// get_default_payload_type returns the payload type associated to the stream.
547    pub fn get_default_payload_type(&self) -> Result<PayloadProtocolIdentifier> {
548        if let Some(s) = self.association.streams.get(&self.stream_identifier) {
549            Ok(s.default_payload_type)
550        } else {
551            Err(Error::ErrStreamClosed)
552        }
553    }
554
555    /// set_reliability_params sets reliability parameters for this stream.
556    pub fn set_reliability_params(
557        &mut self,
558        unordered: bool,
559        rel_type: ReliabilityType,
560        rel_val: u32,
561    ) -> Result<()> {
562        if let Some(s) = self.association.streams.get_mut(&self.stream_identifier) {
563            debug!(
564                "[{}] reliability params: ordered={} type={} value={}",
565                s.side, !unordered, rel_type, rel_val
566            );
567            s.unordered = unordered;
568            s.reliability_type = rel_type;
569            s.reliability_value = rel_val;
570            Ok(())
571        } else {
572            Err(Error::ErrStreamClosed)
573        }
574    }
575
576    /// Application bytes of this stream that have left the send queue (transmitted, or
577    /// abandoned before their first transmission): W3C `bufferedAmount` decreases by what
578    /// "the underlying data transport sends ... from its queue", not by what the peer
579    /// acknowledges.
580    pub fn bytes_dequeued(&self) -> Result<u64> {
581        if let Some(s) = self.association.streams.get(&self.stream_identifier) {
582            Ok(s.bytes_dequeued)
583        } else {
584            Err(Error::ErrStreamClosed)
585        }
586    }
587
588    /// buffered_amount returns the number of bytes of data currently queued to be sent over this stream.
589    pub fn buffered_amount(&self) -> Result<usize> {
590        if let Some(s) = self.association.streams.get(&self.stream_identifier) {
591            Ok(s.buffered_amount)
592        } else {
593            Err(Error::ErrStreamClosed)
594        }
595    }
596
597    /// buffered_amount_low_threshold returns the number of bytes of buffered outgoing data that is
598    /// considered "low" Defaults to 0.
599    pub fn buffered_amount_low_threshold(&self) -> Result<usize> {
600        if let Some(s) = self.association.streams.get(&self.stream_identifier) {
601            Ok(s.buffered_amount_low)
602        } else {
603            Err(Error::ErrStreamClosed)
604        }
605    }
606
607    /// set_buffered_amount_low_threshold is used to update the threshold.
608    /// See buffered_amount_low_threshold().
609    pub fn set_buffered_amount_low_threshold(&mut self, th: usize) -> Result<()> {
610        if let Some(s) = self.association.streams.get_mut(&self.stream_identifier) {
611            s.buffered_amount_low = th;
612            Ok(())
613        } else {
614            Err(Error::ErrStreamClosed)
615        }
616    }
617
618    /// buffered_amount_high_threshold returns the number of bytes of buffered outgoing data that is
619    /// considered "high" Defaults to u32::MAX.
620    pub fn buffered_amount_high_threshold(&self) -> Result<usize> {
621        if let Some(s) = self.association.streams.get(&self.stream_identifier) {
622            Ok(s.buffered_amount_high)
623        } else {
624            Err(Error::ErrStreamClosed)
625        }
626    }
627
628    /// set_buffered_amount_high_threshold is used to update the threshold.
629    /// See buffered_amount_high_threshold().
630    pub fn set_buffered_amount_high_threshold(&mut self, th: usize) -> Result<()> {
631        if let Some(s) = self.association.streams.get_mut(&self.stream_identifier) {
632            s.buffered_amount_high = th;
633            Ok(())
634        } else {
635            Err(Error::ErrStreamClosed)
636        }
637    }
638}
639
640#[derive(Default, Debug, Copy, Clone, Eq, PartialEq)]
641#[non_exhaustive]
642pub enum RecvSendState {
643    #[default]
644    Closed = 0,
645    Readable = 1,
646    Writable = 2,
647    ReadWritable = 3,
648}
649
650impl From<u8> for RecvSendState {
651    fn from(v: u8) -> Self {
652        match v {
653            1 => RecvSendState::Readable,
654            2 => RecvSendState::Writable,
655            3 => RecvSendState::ReadWritable,
656            _ => RecvSendState::Closed,
657        }
658    }
659}
660
661/// StreamState represents the state of an SCTP stream
662#[derive(Default, Debug)]
663pub struct StreamState {
664    pub(crate) side: Side,
665    pub(crate) max_payload_size: u32,
666    pub(crate) stream_identifier: StreamId,
667    pub(crate) generation: u64,
668    pub(crate) default_payload_type: PayloadProtocolIdentifier,
669    pub(crate) reassembly_queue: ReassemblyQueue,
670    pub(crate) sequence_number: u16,
671    pub(crate) state: RecvSendState,
672    pub(crate) unordered: bool,
673    pub(crate) reliability_type: ReliabilityType,
674    pub(crate) reliability_value: u32,
675    pub(crate) buffered_amount: usize,
676    /// Application bytes that have left the send queue: transmitted for the first time, or
677    /// abandoned before that. DCEP messages and the placeholder byte of an empty message
678    /// are not counted.
679    pub(crate) bytes_dequeued: u64,
680    pub(crate) buffered_amount_low: usize,
681    pub(crate) buffered_amount_high: usize,
682    /// A reset of this outgoing stream was asked for and is not answered yet (RFC 6525
683    /// 5.1.2 A1).
684    pub(crate) outgoing_reset_pending: bool,
685    /// This side has reset its outgoing direction of the stream: at the application's close
686    /// (`Stream::stop`), or at the peer's Incoming SSN Reset Request. The peer's reset of its
687    /// own direction then completes the close and is not answered with another reset (RFC 8831
688    /// 6.7), which would reach the next channel to take the id. Kept apart from the
689    /// `RecvSendState` bits: the peer's direction stays readable until the peer resets it.
690    pub(crate) outgoing_reset_started: bool,
691    /// The application stopped reading the stream (`Stream::stop`, `Stream::close`): what
692    /// arrives on it is dropped, since nothing will read it (RFC 8831 6.7: the messages of a
693    /// closed channel are "delivered (or abandoned)").
694    pub(crate) reads_stopped: bool,
695    /// The messages written while the reset is pending, each as its fragments, without a
696    /// Stream Sequence Number.
697    pub(crate) held_writes: Vec<Vec<ChunkPayloadData>>,
698    /// The Message Identifiers of the next ordered and the next unordered message (RFC 8260
699    /// 2.1: two counters for each outgoing stream, both starting at 0).
700    pub(crate) ordered_mid: u32,
701    pub(crate) unordered_mid: u32,
702}
703impl StreamState {
704    pub(crate) fn new(
705        side: Side,
706        stream_identifier: StreamId,
707        max_payload_size: u32,
708        default_payload_type: PayloadProtocolIdentifier,
709    ) -> Self {
710        StreamState {
711            side,
712            stream_identifier,
713            generation: 0,
714            max_payload_size,
715            default_payload_type,
716            reassembly_queue: ReassemblyQueue::new(stream_identifier),
717            sequence_number: 0,
718            state: RecvSendState::ReadWritable,
719            unordered: false,
720            reliability_type: ReliabilityType::Reliable,
721            reliability_value: 0,
722            buffered_amount: 0,
723            bytes_dequeued: 0,
724            buffered_amount_low: 0,
725            buffered_amount_high: u32::MAX as usize,
726            outgoing_reset_pending: false,
727            outgoing_reset_started: false,
728            reads_stopped: false,
729            held_writes: vec![],
730            ordered_mid: 0,
731            unordered_mid: 0,
732        }
733    }
734
735    /// The numbers of the next message of this stream: its Stream Sequence Number (the
736    /// stream's current one for an unordered message, which does not use it up) and its
737    /// Message Identifier.
738    pub(crate) fn next_message_numbers(&mut self, unordered: bool) -> (u16, u32) {
739        if unordered {
740            let mid = self.unordered_mid;
741            self.unordered_mid = self.unordered_mid.wrapping_add(1);
742            (self.sequence_number, mid)
743        } else {
744            let (ssn, mid) = (self.sequence_number, self.ordered_mid);
745            // RFC 9260 6.6: the Stream Sequence Number is not incremented for a message
746            // with the U flag.
747            self.sequence_number = self.sequence_number.wrapping_add(1);
748            self.ordered_mid = self.ordered_mid.wrapping_add(1);
749            (ssn, mid)
750        }
751    }
752
753    /// The stream's outgoing direction was reset: its numbers start over (RFC 6525 5.2.7
754    /// H4; RFC 8260 2.3.2 for the two Message Identifier counters).
755    pub(crate) fn reset_outgoing_numbers(&mut self) {
756        self.sequence_number = 0;
757        self.ordered_mid = 0;
758        self.unordered_mid = 0;
759    }
760
761    pub(crate) fn handle_data(&mut self, pd: &ChunkPayloadData) -> bool {
762        self.reassembly_queue.push(pd.clone())
763    }
764
765    /// Queues a received DATA chunk for reassembly. `cumulative_tsn` is the receiver's
766    /// cumulative TSN before it, which tells a fragment that can never be part of a complete
767    /// message (`ReassemblyQueue::discard_orphans`).
768    pub(crate) fn handle_received(&mut self, pd: &ChunkPayloadData, cumulative_tsn: u32) -> bool {
769        self.reassembly_queue
770            .push_received(pd.clone(), Some(cumulative_tsn))
771    }
772
773    /// RFC 3758 3.6: what the peer's FORWARD TSN says is applied whatever this side's own
774    /// setting for the stream: `unordered` is how this side sends, not how the peer does.
775    pub(crate) fn handle_forward_tsn_for_ordered(&mut self, ssn: u16) {
776        // Remove all chunks older than or equal to the new TSN from
777        // the reassembly_queue.
778        self.reassembly_queue.forward_tsn_for_ordered(ssn);
779    }
780
781    pub(crate) fn handle_forward_tsn_for_unordered(&mut self, new_cumulative_tsn: u32) {
782        // Remove all chunks older than or equal to the new TSN from
783        // the reassembly_queue.
784        self.reassembly_queue
785            .forward_tsn_for_unordered(new_cumulative_tsn);
786    }
787
788    /// The policy a message written now with `ppi` is sent with.
789    pub(crate) fn message_reliability(
790        &self,
791        now: Instant,
792        ppi: PayloadProtocolIdentifier,
793    ) -> MessageReliability {
794        if ppi == PayloadProtocolIdentifier::Dcep {
795            return MessageReliability::Reliable;
796        }
797        match self.reliability_type {
798            ReliabilityType::Reliable => MessageReliability::Reliable,
799            ReliabilityType::Rexmit => MessageReliability::Rexmit {
800                max_retransmits: self.reliability_value,
801            },
802            ReliabilityType::Timed => MessageReliability::Timed {
803                deadline: now + Duration::from_millis(self.reliability_value as u64),
804            },
805            ReliabilityType::Priority => MessageReliability::Priority {
806                priority: self.reliability_value,
807            },
808        }
809    }
810
811    fn packetize(
812        &mut self,
813        now: Instant,
814        raw: &Bytes,
815        ppi: PayloadProtocolIdentifier,
816        ppid: u32,
817        fragment_size: usize,
818        i_data: bool,
819    ) -> (bool, Vec<ChunkPayloadData>) {
820        let mut i = 0;
821        let mut remaining = raw.len();
822        let fragment_size = fragment_size.clamp(1, self.max_payload_size.max(1) as usize);
823
824        // From draft-ietf-rtcweb-data-protocol-09, section 6:
825        //   All Data Channel Establishment Protocol messages MUST be sent using
826        //   ordered delivery and reliable transmission.
827        let unordered = ppi != PayloadProtocolIdentifier::Dcep && self.unordered;
828        let reliability = self.message_reliability(now, ppi);
829
830        let mut chunks = vec![];
831        // The message takes its Stream Sequence Number and Message Identifier when its first
832        // fragment leaves the pending queue (`Association::number_next_message`): one that is
833        // abandoned before that uses up neither (RFC 3758 4.1 TR3), and one written while a
834        // reset of the stream is pending is numbered after the reset (RFC 6525 5.1.2 A1).
835        let (ssn, mid) = (0, 0);
836        let mut fsn = 0u32;
837
838        while remaining != 0 {
839            let fragment_size = std::cmp::min(fragment_size, remaining);
840
841            // Copy the userdata since we'll have to store it until acked
842            // and the caller may re-use the buffer in the mean time
843            let user_data = raw.slice(i..i + fragment_size);
844
845            let chunk = ChunkPayloadData {
846                // Timed reliability measures a message's age from here, so that
847                // a long wait for cwnd or rwnd counts against maxPacketLifeTime.
848                created_at: Some(now),
849                reliability,
850                stream_generation: self.generation,
851                stream_identifier: self.stream_identifier,
852                user_data,
853                unordered,
854                beginning_fragment: i == 0,
855                ending_fragment: remaining - fragment_size == 0,
856                immediate_sack: false,
857                payload_type: ppi,
858                payload_protocol_id: ppid,
859                stream_sequence_number: ssn,
860                i_data,
861                mid,
862                fsn,
863                numbers_pending: true,
864                ..Default::default()
865            };
866
867            chunks.push(chunk);
868            fsn = fsn.wrapping_add(1);
869
870            remaining -= fragment_size;
871            i += fragment_size;
872        }
873
874        let old_amount = self.buffered_amount;
875        let n_bytes_added = raw.len();
876        self.buffered_amount += raw.len();
877        let new_amount = self.buffered_amount;
878
879        trace!(
880            "[{}] new_amount = {}, old_amount = {}, buffered_amount_high = {}, n_bytes_added = {}",
881            self.side, new_amount, old_amount, self.buffered_amount_high, n_bytes_added,
882        );
883
884        let is_buffered_amount_high =
885            old_amount < self.buffered_amount_high && new_amount >= self.buffered_amount_high;
886
887        (is_buffered_amount_high, chunks)
888    }
889
890    /// This method is called by association to notify this stream
891    /// of the specified amount of outgoing data has been delivered to the peer.
892    pub(crate) fn on_buffer_released(&mut self, n_bytes_released: i64) -> bool {
893        if n_bytes_released <= 0 {
894            return false;
895        }
896
897        let old_amount = self.buffered_amount;
898        let new_amount = if old_amount < n_bytes_released as usize {
899            self.buffered_amount = 0;
900            error!(
901                "[{}] released buffer size {} should be <= {}",
902                self.side, n_bytes_released, 0,
903            );
904            0
905        } else {
906            self.buffered_amount -= n_bytes_released as usize;
907
908            old_amount - n_bytes_released as usize
909        };
910
911        trace!(
912            "[{}] new_amount = {}, old_amount = {}, buffered_amount_low = {}, n_bytes_released = {}",
913            self.side, new_amount, old_amount, self.buffered_amount_low, n_bytes_released,
914        );
915
916        old_amount > self.buffered_amount_low && new_amount <= self.buffered_amount_low
917    }
918
919    pub(crate) fn get_num_bytes_in_reassembly_queue(&self) -> usize {
920        // No lock is required as it reads the size with atomic load function.
921        self.reassembly_queue.get_num_bytes()
922    }
923}
924
925#[cfg(test)]
926#[path = "stream_test.rs"]
927mod stream_test;