blob: d8efb56b32e1b54f8a742cbf3ef67aa18f6eb944 [file] [log] [blame]
Taylor Brandstetter3a034e12020-07-09 22:32:341/*
2 * Copyright 2020 The WebRTC project authors. All Rights Reserved.
3 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
11#include "pc/sctp_data_channel.h"
12
Florent Castelli5183f002021-05-07 11:52:4413#include <limits>
Taylor Brandstetter3a034e12020-07-09 22:32:3414#include <memory>
15#include <string>
16#include <utility>
17
Danil Chapovalova30439b2022-07-07 08:08:4918#include "absl/cleanup/cleanup.h"
Taylor Brandstetter3a034e12020-07-09 22:32:3419#include "media/sctp/sctp_transport_internal.h"
Markus Handella1b82012021-05-26 16:56:3020#include "pc/proxy.h"
Taylor Brandstetter3a034e12020-07-09 22:32:3421#include "pc/sctp_utils.h"
22#include "rtc_base/checks.h"
Taylor Brandstetter3a034e12020-07-09 22:32:3423#include "rtc_base/logging.h"
Florent Castellidcb9ffc2021-06-29 12:58:2324#include "rtc_base/system/unused.h"
Taylor Brandstetter3a034e12020-07-09 22:32:3425#include "rtc_base/thread.h"
26
27namespace webrtc {
28
29namespace {
30
31static size_t kMaxQueuedReceivedDataBytes = 16 * 1024 * 1024;
Taylor Brandstetter3a034e12020-07-09 22:32:3432
33static std::atomic<int> g_unique_id{0};
34
35int GenerateUniqueId() {
36 return ++g_unique_id;
37}
38
39// Define proxy for DataChannelInterface.
Mirko Bonadei9d9b8de2021-02-26 08:51:2640BEGIN_PRIMARY_PROXY_MAP(DataChannel)
41PROXY_PRIMARY_THREAD_DESTRUCTOR()
Taylor Brandstetter3a034e12020-07-09 22:32:3442PROXY_METHOD1(void, RegisterObserver, DataChannelObserver*)
43PROXY_METHOD0(void, UnregisterObserver)
44BYPASS_PROXY_CONSTMETHOD0(std::string, label)
45BYPASS_PROXY_CONSTMETHOD0(bool, reliable)
46BYPASS_PROXY_CONSTMETHOD0(bool, ordered)
47BYPASS_PROXY_CONSTMETHOD0(uint16_t, maxRetransmitTime)
48BYPASS_PROXY_CONSTMETHOD0(uint16_t, maxRetransmits)
49BYPASS_PROXY_CONSTMETHOD0(absl::optional<int>, maxRetransmitsOpt)
50BYPASS_PROXY_CONSTMETHOD0(absl::optional<int>, maxPacketLifeTime)
51BYPASS_PROXY_CONSTMETHOD0(std::string, protocol)
52BYPASS_PROXY_CONSTMETHOD0(bool, negotiated)
53// Can't bypass the proxy since the id may change.
54PROXY_CONSTMETHOD0(int, id)
55BYPASS_PROXY_CONSTMETHOD0(Priority, priority)
56PROXY_CONSTMETHOD0(DataState, state)
57PROXY_CONSTMETHOD0(RTCError, error)
58PROXY_CONSTMETHOD0(uint32_t, messages_sent)
59PROXY_CONSTMETHOD0(uint64_t, bytes_sent)
60PROXY_CONSTMETHOD0(uint32_t, messages_received)
61PROXY_CONSTMETHOD0(uint64_t, bytes_received)
62PROXY_CONSTMETHOD0(uint64_t, buffered_amount)
63PROXY_METHOD0(void, Close)
64// TODO(bugs.webrtc.org/11547): Change to run on the network thread.
65PROXY_METHOD1(bool, Send, const DataBuffer&)
Markus Handell3d46d0b2021-05-27 19:42:5766END_PROXY_MAP(DataChannel)
Taylor Brandstetter3a034e12020-07-09 22:32:3467
68} // namespace
69
70InternalDataChannelInit::InternalDataChannelInit(const DataChannelInit& base)
71 : DataChannelInit(base), open_handshake_role(kOpener) {
72 // If the channel is externally negotiated, do not send the OPEN message.
73 if (base.negotiated) {
74 open_handshake_role = kNone;
75 } else {
76 // Datachannel is externally negotiated. Ignore the id value.
77 // Specified in createDataChannel, WebRTC spec section 6.1 bullet 13.
78 id = -1;
79 }
Florent Castelli5183f002021-05-07 11:52:4480 // Backwards compatibility: If maxRetransmits or maxRetransmitTime
81 // are negative, the feature is not enabled.
82 // Values are clamped to a 16bit range.
83 if (maxRetransmits) {
84 if (*maxRetransmits < 0) {
85 RTC_LOG(LS_ERROR)
86 << "Accepting maxRetransmits < 0 for backwards compatibility";
87 maxRetransmits = absl::nullopt;
88 } else if (*maxRetransmits > std::numeric_limits<uint16_t>::max()) {
89 maxRetransmits = std::numeric_limits<uint16_t>::max();
90 }
Taylor Brandstetter3a034e12020-07-09 22:32:3491 }
Florent Castelli5183f002021-05-07 11:52:4492
93 if (maxRetransmitTime) {
94 if (*maxRetransmitTime < 0) {
95 RTC_LOG(LS_ERROR)
96 << "Accepting maxRetransmitTime < 0 for backwards compatibility";
97 maxRetransmitTime = absl::nullopt;
98 } else if (*maxRetransmitTime > std::numeric_limits<uint16_t>::max()) {
99 maxRetransmitTime = std::numeric_limits<uint16_t>::max();
100 }
Taylor Brandstetter3a034e12020-07-09 22:32:34101 }
102}
103
104bool SctpSidAllocator::AllocateSid(rtc::SSLRole role, int* sid) {
105 int potential_sid = (role == rtc::SSL_CLIENT) ? 0 : 1;
106 while (!IsSidAvailable(potential_sid)) {
107 potential_sid += 2;
108 if (potential_sid > static_cast<int>(cricket::kMaxSctpSid)) {
109 return false;
110 }
111 }
112
113 *sid = potential_sid;
114 used_sids_.insert(potential_sid);
115 return true;
116}
117
118bool SctpSidAllocator::ReserveSid(int sid) {
119 if (!IsSidAvailable(sid)) {
120 return false;
121 }
122 used_sids_.insert(sid);
123 return true;
124}
125
126void SctpSidAllocator::ReleaseSid(int sid) {
127 auto it = used_sids_.find(sid);
128 if (it != used_sids_.end()) {
129 used_sids_.erase(it);
130 }
131}
132
133bool SctpSidAllocator::IsSidAvailable(int sid) const {
134 if (sid < static_cast<int>(cricket::kMinSctpSid) ||
135 sid > static_cast<int>(cricket::kMaxSctpSid)) {
136 return false;
137 }
138 return used_sids_.find(sid) == used_sids_.end();
139}
140
141rtc::scoped_refptr<SctpDataChannel> SctpDataChannel::Create(
Harald Alvestrand9e5aeb92022-05-11 09:35:36142 SctpDataChannelControllerInterface* controller,
Taylor Brandstetter3a034e12020-07-09 22:32:34143 const std::string& label,
144 const InternalDataChannelInit& config,
145 rtc::Thread* signaling_thread,
146 rtc::Thread* network_thread) {
Tommi87f70902021-04-27 12:43:08147 auto channel = rtc::make_ref_counted<SctpDataChannel>(
Harald Alvestrand9e5aeb92022-05-11 09:35:36148 config, controller, label, signaling_thread, network_thread);
Taylor Brandstetter3a034e12020-07-09 22:32:34149 if (!channel->Init()) {
150 return nullptr;
151 }
152 return channel;
153}
154
155// static
156rtc::scoped_refptr<DataChannelInterface> SctpDataChannel::CreateProxy(
157 rtc::scoped_refptr<SctpDataChannel> channel) {
158 // TODO(bugs.webrtc.org/11547): incorporate the network thread in the proxy.
Tomas Gunnarsson0d5ce622022-03-18 14:57:15159 auto* signaling_thread = channel->signaling_thread_;
160 return DataChannelProxy::Create(signaling_thread, std::move(channel));
Taylor Brandstetter3a034e12020-07-09 22:32:34161}
162
163SctpDataChannel::SctpDataChannel(const InternalDataChannelInit& config,
Harald Alvestrand9e5aeb92022-05-11 09:35:36164 SctpDataChannelControllerInterface* controller,
Taylor Brandstetter3a034e12020-07-09 22:32:34165 const std::string& label,
166 rtc::Thread* signaling_thread,
167 rtc::Thread* network_thread)
168 : signaling_thread_(signaling_thread),
169 network_thread_(network_thread),
170 internal_id_(GenerateUniqueId()),
171 label_(label),
172 config_(config),
173 observer_(nullptr),
Harald Alvestrand9e5aeb92022-05-11 09:35:36174 controller_(controller) {
Taylor Brandstetter3a034e12020-07-09 22:32:34175 RTC_DCHECK_RUN_ON(signaling_thread_);
Florent Castellidcb9ffc2021-06-29 12:58:23176 RTC_UNUSED(network_thread_);
Taylor Brandstetter3a034e12020-07-09 22:32:34177}
178
Harald Alvestrand9e5aeb92022-05-11 09:35:36179void SctpDataChannel::DetachFromController() {
180 RTC_DCHECK_RUN_ON(signaling_thread_);
181 controller_detached_ = true;
182}
183
Taylor Brandstetter3a034e12020-07-09 22:32:34184bool SctpDataChannel::Init() {
185 RTC_DCHECK_RUN_ON(signaling_thread_);
186 if (config_.id < -1 ||
187 (config_.maxRetransmits && *config_.maxRetransmits < 0) ||
188 (config_.maxRetransmitTime && *config_.maxRetransmitTime < 0)) {
189 RTC_LOG(LS_ERROR) << "Failed to initialize the SCTP data channel due to "
190 "invalid DataChannelInit.";
191 return false;
192 }
193 if (config_.maxRetransmits && config_.maxRetransmitTime) {
194 RTC_LOG(LS_ERROR)
195 << "maxRetransmits and maxRetransmitTime should not be both set.";
196 return false;
197 }
198
199 switch (config_.open_handshake_role) {
200 case webrtc::InternalDataChannelInit::kNone: // pre-negotiated
201 handshake_state_ = kHandshakeReady;
202 break;
203 case webrtc::InternalDataChannelInit::kOpener:
204 handshake_state_ = kHandshakeShouldSendOpen;
205 break;
206 case webrtc::InternalDataChannelInit::kAcker:
207 handshake_state_ = kHandshakeShouldSendAck;
208 break;
209 }
210
211 // Try to connect to the transport in case the transport channel already
212 // exists.
213 OnTransportChannelCreated();
214
215 // Checks if the transport is ready to send because the initial channel
216 // ready signal may have been sent before the DataChannel creation.
217 // This has to be done async because the upper layer objects (e.g.
218 // Chrome glue and WebKit) are not wired up properly until after this
219 // function returns.
Harald Alvestrand9e5aeb92022-05-11 09:35:36220 RTC_DCHECK(!controller_detached_);
221 if (controller_->ReadyToSendData()) {
Tomas Gunnarssonb774d382020-09-20 21:56:24222 AddRef();
Danil Chapovalova30439b2022-07-07 08:08:49223 absl::Cleanup release = [this] { Release(); };
224 rtc::Thread::Current()->PostTask([this, release = std::move(release)] {
225 RTC_DCHECK_RUN_ON(signaling_thread_);
226 if (state_ != kClosed)
227 OnTransportReady(true);
228 });
Taylor Brandstetter3a034e12020-07-09 22:32:34229 }
230
231 return true;
232}
233
234SctpDataChannel::~SctpDataChannel() {
235 RTC_DCHECK_RUN_ON(signaling_thread_);
236}
237
238void SctpDataChannel::RegisterObserver(DataChannelObserver* observer) {
239 RTC_DCHECK_RUN_ON(signaling_thread_);
240 observer_ = observer;
241 DeliverQueuedReceivedData();
242}
243
244void SctpDataChannel::UnregisterObserver() {
245 RTC_DCHECK_RUN_ON(signaling_thread_);
246 observer_ = nullptr;
247}
248
249bool SctpDataChannel::reliable() const {
250 // May be called on any thread.
251 return !config_.maxRetransmits && !config_.maxRetransmitTime;
252}
253
254uint64_t SctpDataChannel::buffered_amount() const {
255 RTC_DCHECK_RUN_ON(signaling_thread_);
Florent Castelli65956852021-10-18 09:13:22256 return queued_send_data_.byte_count();
Taylor Brandstetter3a034e12020-07-09 22:32:34257}
258
259void SctpDataChannel::Close() {
260 RTC_DCHECK_RUN_ON(signaling_thread_);
Florent Castelli8f04c7c2022-05-05 21:43:44261 if (state_ == kClosing || state_ == kClosed)
Taylor Brandstetter3a034e12020-07-09 22:32:34262 return;
263 SetState(kClosing);
264 // Will send queued data before beginning the underlying closing procedure.
265 UpdateState();
266}
267
268SctpDataChannel::DataState SctpDataChannel::state() const {
269 RTC_DCHECK_RUN_ON(signaling_thread_);
270 return state_;
271}
272
273RTCError SctpDataChannel::error() const {
274 RTC_DCHECK_RUN_ON(signaling_thread_);
275 return error_;
276}
277
278uint32_t SctpDataChannel::messages_sent() const {
279 RTC_DCHECK_RUN_ON(signaling_thread_);
280 return messages_sent_;
281}
282
283uint64_t SctpDataChannel::bytes_sent() const {
284 RTC_DCHECK_RUN_ON(signaling_thread_);
285 return bytes_sent_;
286}
287
288uint32_t SctpDataChannel::messages_received() const {
289 RTC_DCHECK_RUN_ON(signaling_thread_);
290 return messages_received_;
291}
292
293uint64_t SctpDataChannel::bytes_received() const {
294 RTC_DCHECK_RUN_ON(signaling_thread_);
295 return bytes_received_;
296}
297
298bool SctpDataChannel::Send(const DataBuffer& buffer) {
299 RTC_DCHECK_RUN_ON(signaling_thread_);
300 // TODO(bugs.webrtc.org/11547): Expect this method to be called on the network
301 // thread. Bring buffer management etc to the network thread and keep the
302 // operational state management on the signaling thread.
303
304 if (state_ != kOpen) {
305 return false;
306 }
307
Taylor Brandstetter3a034e12020-07-09 22:32:34308 // If the queue is non-empty, we're waiting for SignalReadyToSend,
309 // so just add to the end of the queue and keep waiting.
310 if (!queued_send_data_.Empty()) {
311 if (!QueueSendDataMessage(buffer)) {
Florent Castelli01343032021-11-03 15:09:46312 // Queue is full
313 return false;
Taylor Brandstetter3a034e12020-07-09 22:32:34314 }
315 return true;
316 }
317
318 SendDataMessage(buffer, true);
319
320 // Always return true for SCTP DataChannel per the spec.
321 return true;
322}
323
324void SctpDataChannel::SetSctpSid(int sid) {
325 RTC_DCHECK_RUN_ON(signaling_thread_);
326 RTC_DCHECK_LT(config_.id, 0);
327 RTC_DCHECK_GE(sid, 0);
328 RTC_DCHECK_NE(handshake_state_, kHandshakeWaitingForAck);
329 RTC_DCHECK_EQ(state_, kConnecting);
330
331 if (config_.id == sid) {
332 return;
333 }
334
335 const_cast<InternalDataChannelInit&>(config_).id = sid;
Harald Alvestrand9e5aeb92022-05-11 09:35:36336 RTC_DCHECK(!controller_detached_);
337 controller_->AddSctpDataStream(sid);
Taylor Brandstetter3a034e12020-07-09 22:32:34338}
339
340void SctpDataChannel::OnClosingProcedureStartedRemotely(int sid) {
341 RTC_DCHECK_RUN_ON(signaling_thread_);
342 if (sid == config_.id && state_ != kClosing && state_ != kClosed) {
343 // Don't bother sending queued data since the side that initiated the
344 // closure wouldn't receive it anyway. See crbug.com/559394 for a lengthy
345 // discussion about this.
346 queued_send_data_.Clear();
347 queued_control_data_.Clear();
348 // Just need to change state to kClosing, SctpTransport will handle the
349 // rest of the closing procedure and OnClosingProcedureComplete will be
350 // called later.
351 started_closing_procedure_ = true;
352 SetState(kClosing);
353 }
354}
355
356void SctpDataChannel::OnClosingProcedureComplete(int sid) {
357 RTC_DCHECK_RUN_ON(signaling_thread_);
358 if (sid == config_.id) {
359 // If the closing procedure is complete, we should have finished sending
360 // all pending data and transitioned to kClosing already.
361 RTC_DCHECK_EQ(state_, kClosing);
362 RTC_DCHECK(queued_send_data_.Empty());
Harald Alvestrand9e5aeb92022-05-11 09:35:36363 DisconnectFromTransport();
Taylor Brandstetter3a034e12020-07-09 22:32:34364 SetState(kClosed);
365 }
366}
367
368void SctpDataChannel::OnTransportChannelCreated() {
369 RTC_DCHECK_RUN_ON(signaling_thread_);
Harald Alvestrand9e5aeb92022-05-11 09:35:36370 if (controller_detached_) {
371 return;
Taylor Brandstetter3a034e12020-07-09 22:32:34372 }
Harald Alvestrand9e5aeb92022-05-11 09:35:36373 if (!connected_to_transport_) {
374 connected_to_transport_ = controller_->ConnectDataChannel(this);
375 }
376 // The sid may have been unassigned when controller_->ConnectDataChannel was
377 // done. So always add the streams even if connected_to_transport_ is true.
Taylor Brandstetter3a034e12020-07-09 22:32:34378 if (config_.id >= 0) {
Harald Alvestrand9e5aeb92022-05-11 09:35:36379 controller_->AddSctpDataStream(config_.id);
Taylor Brandstetter3a034e12020-07-09 22:32:34380 }
381}
382
Florent Castellidcb9ffc2021-06-29 12:58:23383void SctpDataChannel::OnTransportChannelClosed(RTCError error) {
384 // The SctpTransport is unusable, which could come from multiplie reasons:
385 // - the SCTP m= section was rejected
386 // - the DTLS transport is closed
387 // - the SCTP transport is closed
Taylor Brandstetter3a034e12020-07-09 22:32:34388 CloseAbruptlyWithError(std::move(error));
389}
390
391DataChannelStats SctpDataChannel::GetStats() const {
392 RTC_DCHECK_RUN_ON(signaling_thread_);
393 DataChannelStats stats{internal_id_, id(), label(),
394 protocol(), state(), messages_sent(),
395 messages_received(), bytes_sent(), bytes_received()};
396 return stats;
397}
398
399void SctpDataChannel::OnDataReceived(const cricket::ReceiveDataParams& params,
400 const rtc::CopyOnWriteBuffer& payload) {
401 RTC_DCHECK_RUN_ON(signaling_thread_);
402 if (params.sid != config_.id) {
403 return;
404 }
405
Florent Castellid95b1492021-05-10 09:29:56406 if (params.type == DataMessageType::kControl) {
Taylor Brandstetter3a034e12020-07-09 22:32:34407 if (handshake_state_ != kHandshakeWaitingForAck) {
408 // Ignore it if we are not expecting an ACK message.
409 RTC_LOG(LS_WARNING)
410 << "DataChannel received unexpected CONTROL message, sid = "
411 << params.sid;
412 return;
413 }
414 if (ParseDataChannelOpenAckMessage(payload)) {
415 // We can send unordered as soon as we receive the ACK message.
416 handshake_state_ = kHandshakeReady;
417 RTC_LOG(LS_INFO) << "DataChannel received OPEN_ACK message, sid = "
418 << params.sid;
419 } else {
420 RTC_LOG(LS_WARNING)
421 << "DataChannel failed to parse OPEN_ACK message, sid = "
422 << params.sid;
423 }
424 return;
425 }
426
Florent Castellid95b1492021-05-10 09:29:56427 RTC_DCHECK(params.type == DataMessageType::kBinary ||
428 params.type == DataMessageType::kText);
Taylor Brandstetter3a034e12020-07-09 22:32:34429
430 RTC_LOG(LS_VERBOSE) << "DataChannel received DATA message, sid = "
431 << params.sid;
432 // We can send unordered as soon as we receive any DATA message since the
433 // remote side must have received the OPEN (and old clients do not send
434 // OPEN_ACK).
435 if (handshake_state_ == kHandshakeWaitingForAck) {
436 handshake_state_ = kHandshakeReady;
437 }
438
Florent Castellid95b1492021-05-10 09:29:56439 bool binary = (params.type == webrtc::DataMessageType::kBinary);
Taylor Brandstetter3a034e12020-07-09 22:32:34440 auto buffer = std::make_unique<DataBuffer>(payload, binary);
441 if (state_ == kOpen && observer_) {
442 ++messages_received_;
443 bytes_received_ += buffer->size();
444 observer_->OnMessage(*buffer.get());
445 } else {
446 if (queued_received_data_.byte_count() + payload.size() >
447 kMaxQueuedReceivedDataBytes) {
448 RTC_LOG(LS_ERROR) << "Queued received data exceeds the max buffer size.";
449
450 queued_received_data_.Clear();
451 CloseAbruptlyWithError(
452 RTCError(RTCErrorType::RESOURCE_EXHAUSTED,
453 "Queued received data exceeds the max buffer size."));
454
455 return;
456 }
457 queued_received_data_.PushBack(std::move(buffer));
458 }
459}
460
461void SctpDataChannel::OnTransportReady(bool writable) {
462 RTC_DCHECK_RUN_ON(signaling_thread_);
463
464 writable_ = writable;
465 if (!writable) {
466 return;
467 }
468
469 SendQueuedControlMessages();
470 SendQueuedDataMessages();
471
472 UpdateState();
473}
474
475void SctpDataChannel::CloseAbruptlyWithError(RTCError error) {
476 RTC_DCHECK_RUN_ON(signaling_thread_);
477
478 if (state_ == kClosed) {
479 return;
480 }
481
Harald Alvestrand9e5aeb92022-05-11 09:35:36482 if (connected_to_transport_) {
483 DisconnectFromTransport();
Taylor Brandstetter3a034e12020-07-09 22:32:34484 }
485
486 // Closing abruptly means any queued data gets thrown away.
Taylor Brandstetter3a034e12020-07-09 22:32:34487 queued_send_data_.Clear();
488 queued_control_data_.Clear();
489
490 // Still go to "kClosing" before "kClosed", since observers may be expecting
491 // that.
492 SetState(kClosing);
493 error_ = std::move(error);
494 SetState(kClosed);
495}
496
497void SctpDataChannel::CloseAbruptlyWithDataChannelFailure(
498 const std::string& message) {
499 RTCError error(RTCErrorType::OPERATION_ERROR_WITH_DATA, message);
500 error.set_error_detail(RTCErrorDetailType::DATA_CHANNEL_FAILURE);
501 CloseAbruptlyWithError(std::move(error));
502}
503
504void SctpDataChannel::UpdateState() {
505 RTC_DCHECK_RUN_ON(signaling_thread_);
506 // UpdateState determines what to do from a few state variables. Include
507 // all conditions required for each state transition here for
508 // clarity. OnTransportReady(true) will send any queued data and then invoke
509 // UpdateState().
510
511 switch (state_) {
512 case kConnecting: {
Harald Alvestrand9e5aeb92022-05-11 09:35:36513 if (connected_to_transport_) {
Taylor Brandstetter3a034e12020-07-09 22:32:34514 if (handshake_state_ == kHandshakeShouldSendOpen) {
515 rtc::CopyOnWriteBuffer payload;
516 WriteDataChannelOpenMessage(label_, config_, &payload);
517 SendControlMessage(payload);
518 } else if (handshake_state_ == kHandshakeShouldSendAck) {
519 rtc::CopyOnWriteBuffer payload;
520 WriteDataChannelOpenAckMessage(&payload);
521 SendControlMessage(payload);
522 }
523 if (writable_ && (handshake_state_ == kHandshakeReady ||
524 handshake_state_ == kHandshakeWaitingForAck)) {
525 SetState(kOpen);
526 // If we have received buffers before the channel got writable.
527 // Deliver them now.
528 DeliverQueuedReceivedData();
529 }
530 }
531 break;
532 }
533 case kOpen: {
534 break;
535 }
536 case kClosing: {
537 // Wait for all queued data to be sent before beginning the closing
538 // procedure.
539 if (queued_send_data_.Empty() && queued_control_data_.Empty()) {
540 // For SCTP data channels, we need to wait for the closing procedure
541 // to complete; after calling RemoveSctpDataStream,
542 // OnClosingProcedureComplete will end up called asynchronously
543 // afterwards.
Harald Alvestrand9e5aeb92022-05-11 09:35:36544 if (connected_to_transport_ && !started_closing_procedure_ &&
545 !controller_detached_ && config_.id >= 0) {
Taylor Brandstetter3a034e12020-07-09 22:32:34546 started_closing_procedure_ = true;
Harald Alvestrand9e5aeb92022-05-11 09:35:36547 controller_->RemoveSctpDataStream(config_.id);
Taylor Brandstetter3a034e12020-07-09 22:32:34548 }
549 }
550 break;
551 }
552 case kClosed:
553 break;
554 }
555}
556
557void SctpDataChannel::SetState(DataState state) {
558 RTC_DCHECK_RUN_ON(signaling_thread_);
559 if (state_ == state) {
560 return;
561 }
562
563 state_ = state;
564 if (observer_) {
565 observer_->OnStateChange();
566 }
Tommid2afbaf2023-03-02 09:51:16567
568 if (!controller_detached_)
569 controller_->OnChannelStateChanged(this, state_);
Taylor Brandstetter3a034e12020-07-09 22:32:34570}
571
Harald Alvestrand9e5aeb92022-05-11 09:35:36572void SctpDataChannel::DisconnectFromTransport() {
Taylor Brandstetter3a034e12020-07-09 22:32:34573 RTC_DCHECK_RUN_ON(signaling_thread_);
Harald Alvestrand9e5aeb92022-05-11 09:35:36574 if (!connected_to_transport_ || controller_detached_)
Taylor Brandstetter3a034e12020-07-09 22:32:34575 return;
576
Harald Alvestrand9e5aeb92022-05-11 09:35:36577 controller_->DisconnectDataChannel(this);
578 connected_to_transport_ = false;
Taylor Brandstetter3a034e12020-07-09 22:32:34579}
580
581void SctpDataChannel::DeliverQueuedReceivedData() {
582 RTC_DCHECK_RUN_ON(signaling_thread_);
583 if (!observer_) {
584 return;
585 }
586
587 while (!queued_received_data_.Empty()) {
588 std::unique_ptr<DataBuffer> buffer = queued_received_data_.PopFront();
589 ++messages_received_;
590 bytes_received_ += buffer->size();
591 observer_->OnMessage(*buffer);
592 }
593}
594
595void SctpDataChannel::SendQueuedDataMessages() {
596 RTC_DCHECK_RUN_ON(signaling_thread_);
597 if (queued_send_data_.Empty()) {
598 return;
599 }
600
601 RTC_DCHECK(state_ == kOpen || state_ == kClosing);
602
603 while (!queued_send_data_.Empty()) {
604 std::unique_ptr<DataBuffer> buffer = queued_send_data_.PopFront();
605 if (!SendDataMessage(*buffer, false)) {
606 // Return the message to the front of the queue if sending is aborted.
607 queued_send_data_.PushFront(std::move(buffer));
608 break;
609 }
610 }
611}
612
613bool SctpDataChannel::SendDataMessage(const DataBuffer& buffer,
614 bool queue_if_blocked) {
615 RTC_DCHECK_RUN_ON(signaling_thread_);
Florent Castellid95b1492021-05-10 09:29:56616 SendDataParams send_params;
Harald Alvestrand9e5aeb92022-05-11 09:35:36617 if (controller_detached_) {
618 return false;
619 }
Taylor Brandstetter3a034e12020-07-09 22:32:34620
621 send_params.ordered = config_.ordered;
622 // Send as ordered if it is still going through OPEN/ACK signaling.
623 if (handshake_state_ != kHandshakeReady && !config_.ordered) {
624 send_params.ordered = true;
625 RTC_LOG(LS_VERBOSE)
626 << "Sending data as ordered for unordered DataChannel "
627 "because the OPEN_ACK message has not been received.";
628 }
629
Florent Castelli5183f002021-05-07 11:52:44630 send_params.max_rtx_count = config_.maxRetransmits;
631 send_params.max_rtx_ms = config_.maxRetransmitTime;
Florent Castellid95b1492021-05-10 09:29:56632 send_params.type =
633 buffer.binary ? DataMessageType::kBinary : DataMessageType::kText;
Taylor Brandstetter3a034e12020-07-09 22:32:34634
635 cricket::SendDataResult send_result = cricket::SDR_SUCCESS;
Florent Castellid95b1492021-05-10 09:29:56636 bool success =
Harald Alvestrand9e5aeb92022-05-11 09:35:36637 controller_->SendData(config_.id, send_params, buffer.data, &send_result);
Taylor Brandstetter3a034e12020-07-09 22:32:34638
639 if (success) {
640 ++messages_sent_;
641 bytes_sent_ += buffer.size();
642
Taylor Brandstetter3a034e12020-07-09 22:32:34643 if (observer_ && buffer.size() > 0) {
644 observer_->OnBufferedAmountChange(buffer.size());
645 }
646 return true;
647 }
648
649 if (send_result == cricket::SDR_BLOCK) {
650 if (!queue_if_blocked || QueueSendDataMessage(buffer)) {
651 return false;
652 }
653 }
654 // Close the channel if the error is not SDR_BLOCK, or if queuing the
655 // message failed.
656 RTC_LOG(LS_ERROR) << "Closing the DataChannel due to a failure to send data, "
657 "send_result = "
658 << send_result;
659 CloseAbruptlyWithError(
660 RTCError(RTCErrorType::NETWORK_ERROR, "Failure to send data"));
661
662 return false;
663}
664
665bool SctpDataChannel::QueueSendDataMessage(const DataBuffer& buffer) {
666 RTC_DCHECK_RUN_ON(signaling_thread_);
667 size_t start_buffered_amount = queued_send_data_.byte_count();
Florent Castellia563a2a2021-10-18 09:46:21668 if (start_buffered_amount + buffer.size() >
669 DataChannelInterface::MaxSendQueueSize()) {
Taylor Brandstetter3a034e12020-07-09 22:32:34670 RTC_LOG(LS_ERROR) << "Can't buffer any more data for the data channel.";
671 return false;
672 }
673 queued_send_data_.PushBack(std::make_unique<DataBuffer>(buffer));
674 return true;
675}
676
677void SctpDataChannel::SendQueuedControlMessages() {
678 RTC_DCHECK_RUN_ON(signaling_thread_);
679 PacketQueue control_packets;
680 control_packets.Swap(&queued_control_data_);
681
682 while (!control_packets.Empty()) {
683 std::unique_ptr<DataBuffer> buf = control_packets.PopFront();
684 SendControlMessage(buf->data);
685 }
686}
687
688void SctpDataChannel::QueueControlMessage(
689 const rtc::CopyOnWriteBuffer& buffer) {
690 RTC_DCHECK_RUN_ON(signaling_thread_);
691 queued_control_data_.PushBack(std::make_unique<DataBuffer>(buffer, true));
692}
693
694bool SctpDataChannel::SendControlMessage(const rtc::CopyOnWriteBuffer& buffer) {
695 RTC_DCHECK_RUN_ON(signaling_thread_);
696 RTC_DCHECK(writable_);
697 RTC_DCHECK_GE(config_.id, 0);
698
Harald Alvestrand9e5aeb92022-05-11 09:35:36699 if (controller_detached_) {
700 return false;
701 }
Taylor Brandstetter3a034e12020-07-09 22:32:34702 bool is_open_message = handshake_state_ == kHandshakeShouldSendOpen;
703 RTC_DCHECK(!is_open_message || !config_.negotiated);
704
Florent Castellid95b1492021-05-10 09:29:56705 SendDataParams send_params;
Taylor Brandstetter3a034e12020-07-09 22:32:34706 // Send data as ordered before we receive any message from the remote peer to
707 // make sure the remote peer will not receive any data before it receives the
708 // OPEN message.
709 send_params.ordered = config_.ordered || is_open_message;
Florent Castellid95b1492021-05-10 09:29:56710 send_params.type = DataMessageType::kControl;
Taylor Brandstetter3a034e12020-07-09 22:32:34711
712 cricket::SendDataResult send_result = cricket::SDR_SUCCESS;
Florent Castellid95b1492021-05-10 09:29:56713 bool retval =
Harald Alvestrand9e5aeb92022-05-11 09:35:36714 controller_->SendData(config_.id, send_params, buffer, &send_result);
Taylor Brandstetter3a034e12020-07-09 22:32:34715 if (retval) {
716 RTC_LOG(LS_VERBOSE) << "Sent CONTROL message on channel " << config_.id;
717
718 if (handshake_state_ == kHandshakeShouldSendAck) {
719 handshake_state_ = kHandshakeReady;
720 } else if (handshake_state_ == kHandshakeShouldSendOpen) {
721 handshake_state_ = kHandshakeWaitingForAck;
722 }
723 } else if (send_result == cricket::SDR_BLOCK) {
724 QueueControlMessage(buffer);
725 } else {
726 RTC_LOG(LS_ERROR) << "Closing the DataChannel due to a failure to send"
727 " the CONTROL message, send_result = "
728 << send_result;
729 CloseAbruptlyWithError(RTCError(RTCErrorType::NETWORK_ERROR,
730 "Failed to send a CONTROL message"));
731 }
732 return retval;
733}
734
735// static
736void SctpDataChannel::ResetInternalIdAllocatorForTesting(int new_value) {
737 g_unique_id = new_value;
738}
739
Harald Alvestrand9e5aeb92022-05-11 09:35:36740SctpDataChannel* DowncastProxiedDataChannelInterfaceToSctpDataChannelForTesting(
741 DataChannelInterface* channel) {
742 return static_cast<SctpDataChannel*>(
743 static_cast<DataChannelProxy*>(channel)->internal());
744}
745
Taylor Brandstetter3a034e12020-07-09 22:32:34746} // namespace webrtc