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
use crate::data_channel::RTCDataChannelId;
use crate::data_channel::parameters::DataChannelParameters;
use crate::data_channel::state::RTCDataChannelState;
use datachannel::data_channel::DataChannelConfig;
use sansio::Protocol;
use sctp::{PayloadProtocolIdentifier, ReliabilityType, StreamId};
use shared::error::{Error, Result};
use std::time::Instant;
#[derive(Clone)]
pub(crate) struct RTCDataChannelInternal {
/// Connection-local handle. Assigned by `DataChannelRegistry::insert`, stable for the
/// channel's lifetime, and the key this channel lives under. NOT the wire value — the
/// differing widths (`usize` vs `StreamId`) are what stop the two being confused.
///
/// Carried on the value as well as the key so the close and assignment paths can read it
/// back without a reverse lookup.
pub(crate) id: RTCDataChannelId,
/// The RFC 8832 §6 SCTP stream identifier.
///
/// `None` until the SCTP connected procedure assigns it, which cannot happen before the
/// DTLS role is resolved because the role decides the parity: even for the client, odd for
/// the server. Out-of-band (`negotiated`) channels and channels accepted from the peer
/// have it from birth, since their id is already fixed by the application or the wire.
pub(crate) stream_id: Option<StreamId>,
/// Read through [`Self::label`]: empty for a channel the peer opened, whose label is held
/// once, by the DCEP channel.
pub(crate) label: String,
pub(crate) ordered: bool,
pub(crate) max_packet_life_time: Option<u16>,
pub(crate) max_retransmits: Option<u16>,
/// Read through [`Self::protocol`], like `label`.
pub(crate) protocol: String,
pub(crate) negotiated: bool,
/// The DCEP priority (RFC 8832 §5.1): what this side's `DATA_CHANNEL_OPEN` carries, or
/// what the peer's carried for a channel it opened.
pub(crate) priority: u16,
pub(crate) ready_state: RTCDataChannelState,
pub(crate) buffered_amount_high_threshold: u32,
pub(crate) buffered_amount_low_threshold: u32,
/// User payload bytes handed to `send()`/`send_text()` that SCTP has not yet
/// released (acknowledged or abandoned). Incremented synchronously at the app
/// send boundary and decremented on SCTP buffer-release events, so it accounts
/// for bytes still in the app→core→SCTP send pipeline — not just the SCTP
/// stream's own `buffered_amount`, which counts only post-packetization. Used
/// for synchronous send back-pressure.
pub(crate) outstanding_bytes: usize,
/// Application bytes `send()` queued, over the channel's life: W3C `bufferedAmount` is
/// this less what SCTP has taken from the stream's queue.
pub(crate) bytes_queued: u64,
/// What SCTP had taken from the stream's queue when the stream was closed or lost
/// (`SCTPStreamDequeued`); `None` while the stream is live or before it had one.
pub(crate) bytes_dequeued_at_close: Option<u64>,
/// Deadline by which an in-band channel's DCEP handshake must complete.
/// Set when the channel is dialed; cleared on handshake completion or close.
pub(crate) handshake_deadline: Option<Instant>,
/// Set when the DCEP handshake times out and `OnClose` has already been
/// emitted. Prevents `SCTPStreamClosed` from emitting/counting a second close.
pub(crate) close_emitted: bool,
/// Set when the association under the channel was lost to an error and `OnError` has
/// been emitted: its close is not the remote's closing procedure, so no `OnClosing`.
pub(crate) failed: bool,
pub(crate) data_channel: Option<::datachannel::data_channel::DataChannel>,
}
impl Default for RTCDataChannelInternal {
fn default() -> Self {
Self {
id: 0,
stream_id: None,
label: "".to_string(),
ordered: false,
max_packet_life_time: None,
max_retransmits: None,
protocol: "".to_string(),
negotiated: false,
priority: ::datachannel::message::message_channel_open::CHANNEL_PRIORITY_NORMAL,
ready_state: RTCDataChannelState::default(),
buffered_amount_high_threshold: u32::MAX,
buffered_amount_low_threshold: 0,
outstanding_bytes: 0,
bytes_queued: 0,
bytes_dequeued_at_close: None,
handshake_deadline: None,
close_emitted: false,
failed: false,
data_channel: None,
}
}
}
impl RTCDataChannelInternal {
/// Creates the DataChannel object before the networking is set up.
///
/// The handle is left at its placeholder; [`DataChannelRegistry::insert`] assigns the real
/// one. The stream id comes from `params.negotiated` — `Some` for an out-of-band channel,
/// whose id the application already fixed, and `None` for an in-band one, whose id has to
/// wait for the DTLS role.
///
/// [`DataChannelRegistry::insert`]: crate::data_channel::registry::DataChannelRegistry::insert
pub(crate) fn new(params: DataChannelParameters) -> Self {
Self {
id: 0,
stream_id: params.negotiated,
label: params.label,
protocol: params.protocol,
negotiated: params.negotiated.is_some(),
ordered: params.ordered,
max_packet_life_time: params.max_packet_life_time,
max_retransmits: params.max_retransmits,
priority: ::datachannel::message::message_channel_open::CHANNEL_PRIORITY_NORMAL,
ready_state: RTCDataChannelState::Connecting,
buffered_amount_high_threshold: u32::MAX,
buffered_amount_low_threshold: 0,
outstanding_bytes: 0,
bytes_queued: 0,
bytes_dequeued_at_close: None,
handshake_deadline: None,
close_emitted: false,
failed: false,
data_channel: None,
}
}
/// The channel's label: the DCEP channel's once it exists, else the one given at creation.
pub(crate) fn label(&self) -> &str {
match &self.data_channel {
Some(data_channel) => &data_channel.config().label,
None => &self.label,
}
}
/// The channel's sub-protocol, resolved like [`Self::label`].
pub(crate) fn protocol(&self) -> &str {
match &self.data_channel {
Some(data_channel) => &data_channel.config().protocol,
None => &self.protocol,
}
}
pub(crate) fn dial(&mut self, association_handle: usize) -> Result<()> {
// A channel cannot be dialed before its stream id exists, and the stream id cannot
// exist before the DTLS role does. Making that an error rather than a fallback is the
// whole point: guessing a parity here is what issue #199 was.
let stream_id = self
.stream_id
.ok_or(Error::ErrDataChannelStreamIdNotAssigned)?;
let (channel_type, reliability_parameter) =
::datachannel::data_channel::DataChannel::get_channel_type_and_reliability_parameter(
self.ordered,
self.max_retransmits,
self.max_packet_life_time,
);
let config = ::datachannel::data_channel::DataChannelConfig {
channel_type,
priority: self.priority,
reliability_parameter,
label: self.label.clone(),
protocol: self.protocol.clone(),
negotiated: self.negotiated,
};
let mut data_channel =
::datachannel::data_channel::DataChannel::dial(config, association_handle, stream_id)?;
data_channel.set_buffered_amount_low_threshold(self.buffered_amount_low_threshold)?;
data_channel.set_buffered_amount_high_threshold(self.buffered_amount_high_threshold)?;
self.data_channel = Some(data_channel);
// An in-band channel stays `Connecting` until the peer's `DATA_CHANNEL_ACK`
// is processed in `DataChannelHandler::handle_read`. An out-of-band
// `negotiated` channel has no DCEP handshake, so it is open immediately.
self.ready_state = if self.negotiated {
RTCDataChannelState::Open
} else {
RTCDataChannelState::Connecting
};
Ok(())
}
pub(crate) fn accept(
association_handle: usize,
stream_id: StreamId,
ppi: PayloadProtocolIdentifier,
buf: &[u8],
) -> Result<Self> {
let data_channel = ::datachannel::data_channel::DataChannel::accept(
DataChannelConfig::default(),
association_handle,
stream_id,
ppi,
buf,
)?;
let data_channel_config = data_channel.config();
let (unordered, reliability_type) =
::datachannel::data_channel::DataChannel::get_reliability_params(
data_channel_config.channel_type,
);
// RFC 8832 §5.1: the Reliability Parameter is the retransmission limit of a
// PartialReliableRexmit channel and the lifetime in milliseconds of a
// PartialReliableTimed one, and carries nothing for the reliable types. Recording it
// here is what lets `max_retransmits()` and `max_packet_life_time()` report the
// channel the peer opened. The wire field is 32 bits but the W3C attributes are
// `unsigned short`, so a larger value saturates; the SCTP stream itself is configured
// with the full value.
let reliability_parameter =
u16::try_from(data_channel_config.reliability_parameter).unwrap_or(u16::MAX);
let (max_retransmits, max_packet_life_time) = match reliability_type {
ReliabilityType::Rexmit => (Some(reliability_parameter), None),
ReliabilityType::Timed => (None, Some(reliability_parameter)),
_ => (None, None),
};
// `negotiated: None` — the peer opened this channel in-band over DCEP, so it is not an
// out-of-band channel however well-known its stream id now is. The stream id is set
// below instead of through `negotiated`, which would also flip the `negotiated` flag.
// Label and protocol stay with the DCEP channel (see `label()`): a peer's, up to 64 KiB
// each, is not copied.
let mut data_channel_internal = RTCDataChannelInternal::new(DataChannelParameters {
label: String::new(),
protocol: String::new(),
ordered: !unordered,
max_packet_life_time,
max_retransmits,
negotiated: None,
});
// Known from the wire: no deferral needed, and it must be registered so locally
// generated ids cannot collide with it.
data_channel_internal.stream_id = Some(stream_id);
data_channel_internal.priority = data_channel_config.priority;
data_channel_internal.data_channel = Some(data_channel);
data_channel_internal.ready_state = RTCDataChannelState::Open;
Ok(data_channel_internal)
}
pub(crate) fn close(&mut self) -> Result<()> {
if let Some(data_channel) = self.data_channel.as_mut() {
data_channel.close()?;
}
self.handshake_deadline = None;
self.ready_state = RTCDataChannelState::Closed;
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
use datachannel::message::Message;
use datachannel::message::message_channel_open::{
CHANNEL_PRIORITY_NORMAL, ChannelType, DataChannelOpen,
};
use shared::marshal::Marshal;
const PEER_STREAM: StreamId = 3;
fn accept_open(
channel_type: ChannelType,
reliability_parameter: u32,
) -> RTCDataChannelInternal {
let open = Message::DataChannelOpen(DataChannelOpen {
channel_type,
priority: CHANNEL_PRIORITY_NORMAL,
reliability_parameter,
label: b"peer".to_vec(),
protocol: b"proto".to_vec(),
})
.marshal()
.expect("DCEP OPEN");
RTCDataChannelInternal::accept(0, PEER_STREAM, PayloadProtocolIdentifier::Dcep, &open)
.expect("accept the peer's OPEN")
}
/// `(ordered, max_retransmits, max_packet_life_time)` — what the W3C getters report.
fn getters(dc: &RTCDataChannelInternal) -> (bool, Option<u16>, Option<u16>) {
(dc.ordered, dc.max_retransmits, dc.max_packet_life_time)
}
/// RFC 8832 §5.1: the Reliability Parameter is the retransmission limit of a Rexmit channel
/// and the lifetime in milliseconds of a Timed one.
#[test]
fn an_accepted_channel_reports_the_peers_channel_type_and_reliability() {
let cases = [
(ChannelType::Reliable, 0, (true, None, None)),
(ChannelType::ReliableUnordered, 0, (false, None, None)),
(ChannelType::PartialReliableRexmit, 3, (true, Some(3), None)),
(
ChannelType::PartialReliableRexmitUnordered,
0,
(false, Some(0), None),
),
(
ChannelType::PartialReliableTimed,
1500,
(true, None, Some(1500)),
),
(
ChannelType::PartialReliableTimedUnordered,
250,
(false, None, Some(250)),
),
];
for (channel_type, reliability_parameter, expected) in cases {
let dc = accept_open(channel_type, reliability_parameter);
assert_eq!(
getters(&dc),
expected,
"{channel_type:?} with reliability parameter {reliability_parameter}"
);
assert!(!dc.negotiated, "{channel_type:?}: opened in-band");
assert_eq!(dc.stream_id, Some(PEER_STREAM));
assert_eq!(dc.ready_state, RTCDataChannelState::Open);
assert_eq!((dc.label(), dc.protocol()), ("peer", "proto"));
}
}
/// The wire field is 32 bits and the W3C attributes are `unsigned short`: a larger value
/// saturates rather than wrapping.
#[test]
fn a_reliability_parameter_beyond_u16_saturates() {
for (reliability_parameter, reported) in [
(u16::MAX as u32, u16::MAX),
(u16::MAX as u32 + 1, u16::MAX),
(70_000, u16::MAX),
(u32::MAX, u16::MAX),
] {
assert_eq!(
getters(&accept_open(
ChannelType::PartialReliableRexmit,
reliability_parameter
)),
(true, Some(reported), None),
"maxRetransmits from {reliability_parameter}"
);
assert_eq!(
getters(&accept_open(
ChannelType::PartialReliableTimedUnordered,
reliability_parameter
)),
(false, None, Some(reported)),
"maxPacketLifeTime from {reliability_parameter}"
);
}
}
/// The reliable types carry nothing in the Reliability Parameter, whatever the peer put
/// there.
#[test]
fn a_reliable_channel_ignores_its_reliability_parameter() {
for channel_type in [ChannelType::Reliable, ChannelType::ReliableUnordered] {
for reliability_parameter in [5, 70_000] {
let (_, max_retransmits, max_packet_life_time) =
getters(&accept_open(channel_type, reliability_parameter));
assert_eq!(
(max_retransmits, max_packet_life_time),
(None, None),
"{channel_type:?} with reliability parameter {reliability_parameter}"
);
}
}
}
/// WebRTC Priority Control API 4.3: a channel the peer opened has the priority its
/// `DATA_CHANNEL_OPEN` carried; a local one has 256 (low) until it is given another.
#[test]
fn an_accepted_channel_reports_the_peers_priority() {
for priority in [0u16, 128, 256, 512, 1024, 3893] {
let open = Message::DataChannelOpen(DataChannelOpen {
channel_type: ChannelType::Reliable,
priority,
reliability_parameter: 0,
label: b"peer".to_vec(),
protocol: Vec::new(),
})
.marshal()
.expect("DCEP OPEN");
let dc = RTCDataChannelInternal::accept(
0,
PEER_STREAM,
PayloadProtocolIdentifier::Dcep,
&open,
)
.expect("accept the peer's OPEN");
assert_eq!(dc.priority, priority);
}
let local = RTCDataChannelInternal::new(DataChannelParameters::default());
assert_eq!(local.priority, CHANNEL_PRIORITY_NORMAL);
}
}