Skip to main content

rtci_datachannel/data_channel/
mod.rs

1//! One data channel over an SCTP stream.
2//!
3//! A [`DataChannel`](crate::data_channel::DataChannel) is opened either by the DCEP handshake (`DATA_CHANNEL_OPEN`, then
4//! `DATA_CHANNEL_ACK`) or out of band when [`DataChannelConfig::negotiated`](crate::data_channel::DataChannelConfig::negotiated) is set and both
5//! sides already agreed the stream id through signalling.
6//!
7//! The reliability the channel is opened with maps onto SCTP send parameters:
8//! [`get_reliability_params`](crate::data_channel::DataChannel::get_reliability_params) turns a
9//! [`ChannelType`](crate::message::message_channel_open::ChannelType) into the ordered flag and
10//! partial-reliability setting SCTP needs, and
11//! [`get_channel_type_and_reliability_parameter`](crate::data_channel::DataChannel::get_channel_type_and_reliability_parameter)
12//! goes the other way from the W3C `maxPacketLifeTime`/`maxRetransmits` pair.
13#[cfg(test)]
14mod data_channel_test;
15#[cfg(test)]
16mod sctp_link_test;
17
18use crate::message::message_type::{MESSAGE_TYPE_CLOSE, MESSAGE_TYPE_THRESHOLD};
19use crate::message::{
20    message_channel_ack::*, message_channel_close::*, message_channel_open::*,
21    message_channel_threshold::*, *,
22};
23use bytes::{Buf, BytesMut};
24use log::debug;
25use sctp::{PayloadProtocolIdentifier, ReliabilityType};
26use shared::error::{Error, Result};
27use shared::marshal::*;
28use std::collections::VecDeque;
29
30const RECEIVE_MTU: usize = 8192;
31
32/// DataChannelConfig is used to configure the data channel.
33#[derive(Eq, PartialEq, Default, Clone, Debug)]
34pub struct DataChannelConfig {
35    /// The reliability and ordering guarantees to request.
36    pub channel_type: ChannelType,
37    /// Whether the channel was negotiated out of band.
38    ///
39    /// When `true` no DCEP `DATA_CHANNEL_OPEN` is sent — both sides are assumed to have agreed
40    /// the stream id and parameters through signalling instead.
41    pub negotiated: bool,
42    /// The channel's relative priority; see the `CHANNEL_PRIORITY_*` constants.
43    pub priority: u16,
44    /// The retransmission count or message lifetime, interpreted according to
45    /// [`Self::channel_type`].
46    pub reliability_parameter: u32,
47    /// The channel label, used to distinguish channels on the same association.
48    pub label: String,
49    /// The subprotocol name, or empty if none.
50    pub protocol: String,
51}
52
53/// DataChannelMessage is used for data sent over SCTP.
54#[derive(Debug, Default, Clone)]
55pub struct DataChannelMessage {
56    /// Identifies the SCTP association this message belongs to.
57    pub association_handle: usize,
58    /// The SCTP stream the message arrived on or should be sent on.
59    pub stream_id: u16,
60    /// The payload protocol identifier, which distinguishes DCEP control messages from string
61    /// and binary user data.
62    pub ppi: PayloadProtocolIdentifier,
63    /// The message bytes.
64    pub payload: BytesMut,
65
66    /// Marks a `DATA_CHANNEL_OPEN` that belongs to an out-of-band *negotiated*
67    /// channel (W3C WebRTC `RTCDataChannelInit.negotiated`). Such a message is
68    /// only used to open and configure the local SCTP stream and must not be
69    /// transmitted to the peer, which already created its own channel with the
70    /// pre-agreed stream id. Ignored for every other message.
71    pub negotiated: bool,
72}
73
74impl DataChannelMessage {
75    /// Creates a new `DataChannelMessage` with all fields specified.
76    pub fn new(
77        association_handle: usize,
78        stream_id: u16,
79        ppi: PayloadProtocolIdentifier,
80        payload: BytesMut,
81        negotiated: bool,
82    ) -> Self {
83        Self {
84            association_handle,
85            stream_id,
86            ppi,
87            payload,
88            negotiated,
89        }
90    }
91}
92
93/// DataChannel represents a data channel
94#[derive(Debug, Default, Clone)]
95pub struct DataChannel {
96    config: DataChannelConfig,
97    association_handle: usize,
98    stream_id: u16,
99
100    read_outs: VecDeque<DataChannelMessage>,
101    write_outs: VecDeque<DataChannelMessage>,
102
103    /// Whether the DCEP handshake for this channel has completed.
104    handshake_complete: bool,
105
106    // stats
107    messages_sent: usize,
108    messages_received: usize,
109    bytes_sent: usize,
110    bytes_received: usize,
111}
112
113impl DataChannel {
114    /// Creates a new `DataChannel` with the given configuration, association
115    /// handle, and SCTP stream identifier.  Counters start at zero.
116    fn new(config: DataChannelConfig, association_handle: usize, stream_id: u16) -> Self {
117        Self {
118            config,
119            association_handle,
120            stream_id,
121            read_outs: VecDeque::new(),
122            write_outs: VecDeque::new(),
123            ..Default::default()
124        }
125    }
126
127    /// Dial opens a data channel over SCTP.
128    ///
129    /// A DCEP `DataChannelOpen` message is always constructed so that the SCTP
130    /// handler registers the underlying stream.  For **in-band** channels the
131    /// message is also sent over the wire (RFC 8832 sec. 3); for
132    /// **pre-negotiated** channels it stays internal-only (see issue #61).
133    pub fn dial(
134        config: DataChannelConfig,
135        association_handle: usize,
136        stream_id: u16,
137    ) -> Result<Self> {
138        let mut data_channel = DataChannel::new(config.clone(), association_handle, stream_id);
139
140        // Both in-band and out-of-band (negotiated) channels emit a
141        // DATA_CHANNEL_OPEN so the underlying SCTP stream gets opened and its
142        // reliability parameters configured (the Channel Type / Reliability
143        // Parameter mapping in RFC 8832 section 5.1). For a negotiated channel
144        // the message is flagged so the transport opens the stream locally
145        // without sending the DCEP handshake to the peer; that suppression is
146        // required by the W3C WebRTC `negotiated` semantics, not by DCEP.
147        let msg = Message::DataChannelOpen(DataChannelOpen {
148            channel_type: config.channel_type,
149            priority: config.priority,
150            reliability_parameter: config.reliability_parameter,
151            label: config.label.bytes().collect(),
152            protocol: config.protocol.bytes().collect(),
153        })
154        .marshal()?;
155
156        data_channel.write_outs.push_back(DataChannelMessage {
157            association_handle,
158            stream_id,
159            ppi: PayloadProtocolIdentifier::Dcep,
160            payload: msg,
161            negotiated: config.negotiated,
162        });
163
164        // Out-of-band `negotiated` channels have no handshake, so they are
165        // handshake-complete immediately. In-band channels stay incomplete until
166        // `handle_dcep` processes the peer's `DATA_CHANNEL_ACK`.
167        data_channel.handshake_complete = config.negotiated;
168
169        Ok(data_channel)
170    }
171
172    /// Accept is used to accept incoming data channels over SCTP
173    pub fn accept(
174        mut config: DataChannelConfig,
175        association_handle: usize,
176        stream_id: u16,
177        ppi: PayloadProtocolIdentifier,
178        buf: &[u8],
179    ) -> Result<Self> {
180        if ppi != PayloadProtocolIdentifier::Dcep {
181            return Err(Error::InvalidPayloadProtocolIdentifier(ppi as u8));
182        }
183
184        let mut read_buf = buf;
185        let msg = unmarshal_from_peer(&mut read_buf)?;
186
187        if let Message::DataChannelOpen(dco) = msg {
188            config.channel_type = dco.channel_type;
189            config.priority = dco.priority;
190            config.reliability_parameter = dco.reliability_parameter;
191            config.label = String::from_utf8(dco.label)?;
192            config.protocol = String::from_utf8(dco.protocol)?;
193        } else {
194            return Err(Error::InvalidMessageType(msg.message_type() as u8));
195        };
196
197        let mut data_channel = DataChannel::new(config, association_handle, stream_id);
198
199        data_channel.write_data_channel_ack()?;
200
201        // The remote side's OPEN has been processed and the ACK is written out,
202        // so the handshake is complete.
203        data_channel.handshake_complete = true;
204
205        Ok(data_channel)
206    }
207
208    /// MessagesSent returns the number of messages sent
209    pub fn messages_sent(&self) -> usize {
210        self.messages_sent
211    }
212
213    /// MessagesReceived returns the number of messages received
214    pub fn messages_received(&self) -> usize {
215        self.messages_received
216    }
217
218    /// BytesSent returns the number of bytes sent
219    pub fn bytes_sent(&self) -> usize {
220        self.bytes_sent
221    }
222
223    /// BytesReceived returns the number of bytes received
224    pub fn bytes_received(&self) -> usize {
225        self.bytes_received
226    }
227
228    /// association_handle returns the association handle
229    pub fn association_handle(&self) -> usize {
230        self.association_handle
231    }
232
233    /// StreamIdentifier returns the Stream identifier associated to the stream.
234    pub fn stream_identifier(&self) -> u16 {
235        self.stream_id
236    }
237
238    /// The configuration this channel was opened with.
239    pub fn config(&self) -> &DataChannelConfig {
240        &self.config
241    }
242
243    /// Whether the DCEP handshake for this channel has completed.
244    ///
245    /// For a locally-created in-band channel this becomes `true` only when the peer's
246    /// `DATA_CHANNEL_ACK` is received; for a remote channel it is `true` from `accept()`;
247    /// for an out-of-band `negotiated` channel it is `true` from `dial()`.
248    pub fn is_handshake_complete(&self) -> bool {
249        self.handshake_complete
250    }
251
252    fn handle_dcep<B>(&mut self, data: &mut B) -> Result<()>
253    where
254        B: Buf,
255    {
256        let msg = unmarshal_from_peer(data)?;
257
258        match msg {
259            Message::DataChannelOpen(_) => {
260                // RFC 8832 section 6: a DATA_CHANNEL_OPEN "received on an already used stream"
261                // gets no DATA_CHANNEL_ACK and closes the channel, which is the caller's to
262                // do (it owns the stream). The OPEN that opens a channel goes to `accept`.
263                debug!("Received DATA_CHANNEL_OPEN on a stream in use");
264                return Err(Error::ErrStreamAlreadyExist);
265            }
266            Message::DataChannelAck(_) => {
267                debug!("Received DATA_CHANNEL_ACK");
268                // The initiator's DCEP handshake is complete.
269                self.handshake_complete = true;
270            }
271            _ => {
272                return Err(Error::InvalidMessageType(msg.message_type() as u8));
273            }
274        };
275
276        Ok(())
277    }
278
279    fn write_data_channel_ack(&mut self) -> Result<()> {
280        let ack = Message::DataChannelAck(DataChannelAck {}).marshal()?;
281        self.write_outs.push_back(DataChannelMessage {
282            association_handle: self.association_handle,
283            stream_id: self.stream_id,
284            ppi: PayloadProtocolIdentifier::Dcep,
285            payload: ack,
286            negotiated: false,
287        });
288        Ok(())
289    }
290
291    fn write_data_channel_close(&mut self) -> Result<()> {
292        let close = Message::DataChannelClose(DataChannelClose {}).marshal()?;
293        self.write_outs.push_back(DataChannelMessage {
294            association_handle: self.association_handle,
295            stream_id: self.stream_id,
296            ppi: PayloadProtocolIdentifier::Dcep,
297            payload: close,
298            negotiated: false,
299        });
300        Ok(())
301    }
302
303    fn write_data_channel_high_threshold(&mut self, threshold: u32) -> Result<()> {
304        let low_threshold =
305            Message::DataChannelThreshold(DataChannelThreshold::High(threshold)).marshal()?;
306        self.write_outs.push_back(DataChannelMessage {
307            association_handle: self.association_handle,
308            stream_id: self.stream_id,
309            ppi: PayloadProtocolIdentifier::Dcep,
310            payload: low_threshold,
311            negotiated: false,
312        });
313        Ok(())
314    }
315
316    fn write_data_channel_low_threshold(&mut self, threshold: u32) -> Result<()> {
317        let low_threshold =
318            Message::DataChannelThreshold(DataChannelThreshold::Low(threshold)).marshal()?;
319        self.write_outs.push_back(DataChannelMessage {
320            association_handle: self.association_handle,
321            stream_id: self.stream_id,
322            ppi: PayloadProtocolIdentifier::Dcep,
323            payload: low_threshold,
324            negotiated: false,
325        });
326        Ok(())
327    }
328
329    /// SetBufferedAmountHighThreshold is used to update the threshold.
330    /// See BufferedAmountHighThreshold().
331    pub fn set_buffered_amount_high_threshold(&mut self, threshold: u32) -> Result<()> {
332        self.write_data_channel_high_threshold(threshold)
333    }
334
335    /// SetBufferedAmountLowThreshold is used to update the threshold.
336    /// See BufferedAmountLowThreshold().
337    pub fn set_buffered_amount_low_threshold(&mut self, threshold: u32) -> Result<()> {
338        self.write_data_channel_low_threshold(threshold)
339    }
340
341    /*
342    /// OnBufferedAmountLow sets the callback handler which would be called when the
343    /// number of bytes of outgoing data buffered is lower than the threshold.
344    pub fn on_buffered_amount_low(&self, f: OnBufferedAmountLowFn) {
345        self.stream.on_buffered_amount_low(f)
346    }*/
347
348    /// Decomposes a [`ChannelType`] into the SCTP send parameters it implies.
349    ///
350    /// Returns whether delivery is unordered, together with the reliability type and value SCTP
351    /// needs for partial reliability.
352    pub fn get_reliability_params(channel_type: ChannelType) -> (bool, ReliabilityType) {
353        match channel_type {
354            ChannelType::Reliable => (false, ReliabilityType::Reliable),
355            ChannelType::ReliableUnordered => (true, ReliabilityType::Reliable),
356            ChannelType::PartialReliableRexmit => (false, ReliabilityType::Rexmit),
357            ChannelType::PartialReliableRexmitUnordered => (true, ReliabilityType::Rexmit),
358            ChannelType::PartialReliableTimed => (false, ReliabilityType::Timed),
359            ChannelType::PartialReliableTimedUnordered => (true, ReliabilityType::Timed),
360        }
361    }
362
363    /// Derives the [`ChannelType`] and reliability parameter from the `maxPacketLifeTime` /
364    /// `maxRetransmits` pair the W3C API exposes.
365    ///
366    /// The two are mutually exclusive; supplying neither yields a fully reliable channel.
367    pub fn get_channel_type_and_reliability_parameter(
368        ordered: bool,
369        max_retransmits: Option<u16>,
370        max_packet_life_time: Option<u16>,
371    ) -> (ChannelType, u32) {
372        let channel_type;
373        let reliability_parameter;
374
375        match (max_retransmits, max_packet_life_time) {
376            (None, None) => {
377                reliability_parameter = 0u32;
378                if ordered {
379                    channel_type = ChannelType::Reliable;
380                } else {
381                    channel_type = ChannelType::ReliableUnordered;
382                }
383            }
384
385            (Some(max_retransmits), _) => {
386                reliability_parameter = max_retransmits as u32;
387                if ordered {
388                    channel_type = ChannelType::PartialReliableRexmit;
389                } else {
390                    channel_type = ChannelType::PartialReliableRexmitUnordered;
391                }
392            }
393
394            (None, Some(max_packet_lifetime)) => {
395                reliability_parameter = max_packet_lifetime as u32;
396                if ordered {
397                    channel_type = ChannelType::PartialReliableTimed;
398                } else {
399                    channel_type = ChannelType::PartialReliableTimedUnordered;
400                }
401            }
402        }
403
404        (channel_type, reliability_parameter)
405    }
406
407    /// Builds the payload protocol identifier and payload for a user message.
408    ///
409    /// Empty messages get their own identifiers (`StringEmpty`/`BinaryEmpty`) because SCTP
410    /// cannot carry a zero-length payload.
411    pub fn get_data_channel_message(is_string: bool, data: BytesMut) -> DataChannelMessage {
412        // https://tools.ietf.org/html/draft-ietf-rtcweb-data-channel-12#section-6.6
413        // SCTP does not support the sending of empty user messages.  Therefore,
414        // if an empty message has to be sent, the appropriate PPID (WebRTC
415        // String Empty or WebRTC Binary Empty) is used and the SCTP user
416        // message of one zero byte is sent.  When receiving an SCTP user
417        // message with one of these PPIDs, the receiver MUST ignore the SCTP
418        // user message and process it as an empty message.
419        let ppi = match (is_string, data.len()) {
420            (false, 0) => PayloadProtocolIdentifier::BinaryEmpty,
421            (false, _) => PayloadProtocolIdentifier::Binary,
422            (true, 0) => PayloadProtocolIdentifier::StringEmpty,
423            (true, _) => PayloadProtocolIdentifier::String,
424        };
425
426        if data.is_empty() {
427            DataChannelMessage {
428                ppi,
429                payload: BytesMut::from(&[0][..]),
430                ..Default::default()
431            }
432        } else {
433            DataChannelMessage {
434                ppi,
435                payload: data,
436                ..Default::default()
437            }
438        }
439    }
440}
441
442impl sansio::Protocol<DataChannelMessage, DataChannelMessage, ()> for DataChannel {
443    type Rout = DataChannelMessage;
444    type Wout = DataChannelMessage;
445    type Eout = ();
446    type Error = Error;
447    type Time = ();
448
449    /// Takes one message the peer sent on this channel's stream: a DCEP message is processed
450    /// here, and a user message is queued for `poll_read`.
451    ///
452    /// An error means the peer broke the protocol on this channel (a `DATA_CHANNEL_OPEN` on a
453    /// stream in use, a DCEP message that does not parse, an unsupported PPID): RFC 8832
454    /// section 6 and RFC 8831 section 6.6 have the receiver close the channel. Such a message
455    /// is neither delivered nor counted.
456    fn handle_read(&mut self, msg: DataChannelMessage) -> Result<()> {
457        match msg.ppi {
458            PayloadProtocolIdentifier::Dcep => {
459                let mut data_buf = &msg.payload[..];
460                self.handle_dcep(&mut data_buf)?;
461            }
462            PayloadProtocolIdentifier::String
463            | PayloadProtocolIdentifier::Binary
464            | PayloadProtocolIdentifier::StringEmpty
465            | PayloadProtocolIdentifier::BinaryEmpty => {
466                // RFC 8832 section 6: "After the DATA_CHANNEL_ACK or any other message has
467                // been received on the data channel", the channel is set up: the peer only
468                // sends user data once it took the OPEN, so a message ahead of a delayed (or
469                // lost) ACK completes the opener's handshake as the ACK would.
470                self.handshake_complete = true;
471            }
472            // RFC 8831 section 6.6: the PPID is what says how the payload is to be read, so
473            // a message under any other one (the deprecated partial PPIDs 52 and 54 among
474            // them) has no interpretation. It is an error for the caller to close the
475            // channel on, never binary data.
476            other => return Err(Error::InvalidPayloadProtocolIdentifier(other as u8)),
477        }
478
479        self.messages_received += 1;
480        self.bytes_received += user_bytes(&msg);
481        if msg.ppi != PayloadProtocolIdentifier::Dcep {
482            self.read_outs.push_back(msg);
483        }
484        Ok(())
485    }
486
487    fn poll_read(&mut self) -> Option<DataChannelMessage> {
488        self.read_outs.pop_front()
489    }
490
491    /// handle_write writes len(p) bytes from p
492    fn handle_write(&mut self, mut msg: DataChannelMessage) -> Result<()> {
493        self.messages_sent += 1;
494        self.bytes_sent += user_bytes(&msg);
495
496        msg.association_handle = self.association_handle;
497        msg.stream_id = self.stream_id;
498        self.write_outs.push_back(msg);
499
500        Ok(())
501    }
502
503    /// Returns packets to transmit
504    fn poll_write(&mut self) -> Option<DataChannelMessage> {
505        self.write_outs.pop_front()
506    }
507
508    /// Close closes the DataChannel and the underlying SCTP stream.
509    fn close(&mut self) -> Result<()> {
510        // https://tools.ietf.org/html/draft-ietf-rtcweb-data-channel-13#section-6.7
511        // Closing of a data channel MUST be signaled by resetting the
512        // corresponding outgoing streams [RFC6525].  This means that if one
513        // side decides to close the data channel, it resets the corresponding
514        // outgoing stream.  When the peer sees that an incoming stream was
515        // reset, it also resets its corresponding outgoing stream.  Once this
516        // is completed, the data channel is closed.  Resetting a stream sets
517        // the Stream Sequence Numbers (SSNs) of the stream back to 'zero' with
518        // a corresponding notification to the application layer that the reset
519        // has been performed.  Streams are available for reuse after a reset
520        // has been performed.
521        // Closing resets the handshake-complete flag.
522        self.handshake_complete = false;
523        self.write_data_channel_close()
524    }
525}
526
527/// The application bytes a message carries: none for an empty message, whose one byte on the
528/// wire is only the placeholder SCTP needs (RFC 8831 6.6).
529fn user_bytes(msg: &DataChannelMessage) -> usize {
530    match msg.ppi {
531        PayloadProtocolIdentifier::StringEmpty | PayloadProtocolIdentifier::BinaryEmpty => 0,
532        _ => msg.payload.len(),
533    }
534}
535
536/// Parses a DCEP message the peer sent.
537///
538/// Types 0x00 (threshold) and 0x01 (close) are this crate's own: they travel from a data channel
539/// to the SCTP layer on the write path and are never put on the wire. One that arrives from the
540/// peer is refused by its type byte, before any of its body is read.
541fn unmarshal_from_peer<B: Buf>(buf: &mut B) -> Result<Message> {
542    if let Some(&message_type) = buf.chunk().first()
543        && (message_type == MESSAGE_TYPE_THRESHOLD || message_type == MESSAGE_TYPE_CLOSE)
544    {
545        return Err(Error::InvalidMessageType(message_type));
546    }
547    Message::unmarshal(buf)
548}