blob: e995a0e9a6559b130126ff59995a7368e3c8632a [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
Taylor Brandstetter3a034e12020-07-09 22:32:3418#include "media/sctp/sctp_transport_internal.h"
Markus Handella1b82012021-05-26 16:56:3019#include "pc/proxy.h"
Taylor Brandstetter3a034e12020-07-09 22:32:3420#include "pc/sctp_utils.h"
21#include "rtc_base/checks.h"
22#include "rtc_base/location.h"
23#include "rtc_base/logging.h"
24#include "rtc_base/ref_counted_object.h"
Florent Castellidcb9ffc2021-06-29 12:58:2325#include "rtc_base/system/unused.h"
Tomas Gunnarssonb774d382020-09-20 21:56:2426#include "rtc_base/task_utils/to_queued_task.h"
Taylor Brandstetter3a034e12020-07-09 22:32:3427#include "rtc_base/thread.h"
28
29namespace webrtc {
30
31namespace {
32
33static size_t kMaxQueuedReceivedDataBytes = 16 * 1024 * 1024;
Taylor Brandstetter3a034e12020-07-09 22:32:3434
35static std::atomic<int> g_unique_id{0};
36
37int GenerateUniqueId() {
38 return ++g_unique_id;
39}
40
41// Define proxy for DataChannelInterface.
Mirko Bonadei9d9b8de2021-02-26 08:51:2642BEGIN_PRIMARY_PROXY_MAP(DataChannel)
43PROXY_PRIMARY_THREAD_DESTRUCTOR()
Taylor Brandstetter3a034e12020-07-09 22:32:3444PROXY_METHOD1(void, RegisterObserver, DataChannelObserver*)
45PROXY_METHOD0(void, UnregisterObserver)
46BYPASS_PROXY_CONSTMETHOD0(std::string, label)
47BYPASS_PROXY_CONSTMETHOD0(bool, reliable)
48BYPASS_PROXY_CONSTMETHOD0(bool, ordered)
49BYPASS_PROXY_CONSTMETHOD0(uint16_t, maxRetransmitTime)
50BYPASS_PROXY_CONSTMETHOD0(uint16_t, maxRetransmits)
51BYPASS_PROXY_CONSTMETHOD0(absl::optional<int>, maxRetransmitsOpt)
52BYPASS_PROXY_CONSTMETHOD0(absl::optional<int>, maxPacketLifeTime)
53BYPASS_PROXY_CONSTMETHOD0(std::string, protocol)
54BYPASS_PROXY_CONSTMETHOD0(bool, negotiated)
55// Can't bypass the proxy since the id may change.
56PROXY_CONSTMETHOD0(int, id)
57BYPASS_PROXY_CONSTMETHOD0(Priority, priority)
58PROXY_CONSTMETHOD0(DataState, state)
59PROXY_CONSTMETHOD0(RTCError, error)
60PROXY_CONSTMETHOD0(uint32_t, messages_sent)
61PROXY_CONSTMETHOD0(uint64_t, bytes_sent)
62PROXY_CONSTMETHOD0(uint32_t, messages_received)
63PROXY_CONSTMETHOD0(uint64_t, bytes_received)
64PROXY_CONSTMETHOD0(uint64_t, buffered_amount)
65PROXY_METHOD0(void, Close)
66// TODO(bugs.webrtc.org/11547): Change to run on the network thread.
67PROXY_METHOD1(bool, Send, const DataBuffer&)
Markus Handell3d46d0b2021-05-27 19:42:5768END_PROXY_MAP(DataChannel)
Taylor Brandstetter3a034e12020-07-09 22:32:3469
70} // namespace
71
72InternalDataChannelInit::InternalDataChannelInit(const DataChannelInit& base)
73 : DataChannelInit(base), open_handshake_role(kOpener) {
74 // If the channel is externally negotiated, do not send the OPEN message.
75 if (base.negotiated) {
76 open_handshake_role = kNone;
77 } else {
78 // Datachannel is externally negotiated. Ignore the id value.
79 // Specified in createDataChannel, WebRTC spec section 6.1 bullet 13.
80 id = -1;
81 }
Florent Castelli5183f002021-05-07 11:52:4482 // Backwards compatibility: If maxRetransmits or maxRetransmitTime
83 // are negative, the feature is not enabled.
84 // Values are clamped to a 16bit range.
85 if (maxRetransmits) {
86 if (*maxRetransmits < 0) {
87 RTC_LOG(LS_ERROR)
88 << "Accepting maxRetransmits < 0 for backwards compatibility";
89 maxRetransmits = absl::nullopt;
90 } else if (*maxRetransmits > std::numeric_limits<uint16_t>::max()) {
91 maxRetransmits = std::numeric_limits<uint16_t>::max();
92 }
Taylor Brandstetter3a034e12020-07-09 22:32:3493 }
Florent Castelli5183f002021-05-07 11:52:4494
95 if (maxRetransmitTime) {
96 if (*maxRetransmitTime < 0) {
97 RTC_LOG(LS_ERROR)
98 << "Accepting maxRetransmitTime < 0 for backwards compatibility";
99 maxRetransmitTime = absl::nullopt;
100 } else if (*maxRetransmitTime > std::numeric_limits<uint16_t>::max()) {
101 maxRetransmitTime = std::numeric_limits<uint16_t>::max();
102 }
Taylor Brandstetter3a034e12020-07-09 22:32:34103 }
104}
105
106bool SctpSidAllocator::AllocateSid(rtc::SSLRole role, int* sid) {
107 int potential_sid = (role == rtc::SSL_CLIENT) ? 0 : 1;
108 while (!IsSidAvailable(potential_sid)) {
109 potential_sid += 2;
110 if (potential_sid > static_cast<int>(cricket::kMaxSctpSid)) {
111 return false;
112 }
113 }
114
115 *sid = potential_sid;
116 used_sids_.insert(potential_sid);
117 return true;
118}
119
120bool SctpSidAllocator::ReserveSid(int sid) {
121 if (!IsSidAvailable(sid)) {
122 return false;
123 }
124 used_sids_.insert(sid);
125 return true;
126}
127
128void SctpSidAllocator::ReleaseSid(int sid) {
129 auto it = used_sids_.find(sid);
130 if (it != used_sids_.end()) {
131 used_sids_.erase(it);
132 }
133}
134
135bool SctpSidAllocator::IsSidAvailable(int sid) const {
136 if (sid < static_cast<int>(cricket::kMinSctpSid) ||
137 sid > static_cast<int>(cricket::kMaxSctpSid)) {
138 return false;
139 }
140 return used_sids_.find(sid) == used_sids_.end();
141}
142
143rtc::scoped_refptr<SctpDataChannel> SctpDataChannel::Create(
Harald Alvestrand9e5aeb92022-05-11 09:35:36144 SctpDataChannelControllerInterface* controller,
Taylor Brandstetter3a034e12020-07-09 22:32:34145 const std::string& label,
146 const InternalDataChannelInit& config,
147 rtc::Thread* signaling_thread,
148 rtc::Thread* network_thread) {
Tommi87f70902021-04-27 12:43:08149 auto channel = rtc::make_ref_counted<SctpDataChannel>(
Harald Alvestrand9e5aeb92022-05-11 09:35:36150 config, controller, label, signaling_thread, network_thread);
Taylor Brandstetter3a034e12020-07-09 22:32:34151 if (!channel->Init()) {
152 return nullptr;
153 }
154 return channel;
155}
156
157// static
158rtc::scoped_refptr<DataChannelInterface> SctpDataChannel::CreateProxy(
159 rtc::scoped_refptr<SctpDataChannel> channel) {
160 // TODO(bugs.webrtc.org/11547): incorporate the network thread in the proxy.
Tomas Gunnarsson0d5ce622022-03-18 14:57:15161 auto* signaling_thread = channel->signaling_thread_;
162 return DataChannelProxy::Create(signaling_thread, std::move(channel));
Taylor Brandstetter3a034e12020-07-09 22:32:34163}
164
165SctpDataChannel::SctpDataChannel(const InternalDataChannelInit& config,
Harald Alvestrand9e5aeb92022-05-11 09:35:36166 SctpDataChannelControllerInterface* controller,
Taylor Brandstetter3a034e12020-07-09 22:32:34167 const std::string& label,
168 rtc::Thread* signaling_thread,
169 rtc::Thread* network_thread)
170 : signaling_thread_(signaling_thread),
171 network_thread_(network_thread),
172 internal_id_(GenerateUniqueId()),
173 label_(label),
174 config_(config),
175 observer_(nullptr),
Harald Alvestrand9e5aeb92022-05-11 09:35:36176 controller_(controller) {
Taylor Brandstetter3a034e12020-07-09 22:32:34177 RTC_DCHECK_RUN_ON(signaling_thread_);
Florent Castellidcb9ffc2021-06-29 12:58:23178 RTC_UNUSED(network_thread_);
Taylor Brandstetter3a034e12020-07-09 22:32:34179}
180
Harald Alvestrand9e5aeb92022-05-11 09:35:36181void SctpDataChannel::DetachFromController() {
182 RTC_DCHECK_RUN_ON(signaling_thread_);
183 controller_detached_ = true;
184}
185
Taylor Brandstetter3a034e12020-07-09 22:32:34186bool SctpDataChannel::Init() {
187 RTC_DCHECK_RUN_ON(signaling_thread_);
188 if (config_.id < -1 ||
189 (config_.maxRetransmits && *config_.maxRetransmits < 0) ||
190 (config_.maxRetransmitTime && *config_.maxRetransmitTime < 0)) {
191 RTC_LOG(LS_ERROR) << "Failed to initialize the SCTP data channel due to "
192 "invalid DataChannelInit.";
193 return false;
194 }
195 if (config_.maxRetransmits && config_.maxRetransmitTime) {
196 RTC_LOG(LS_ERROR)
197 << "maxRetransmits and maxRetransmitTime should not be both set.";
198 return false;
199 }
200
201 switch (config_.open_handshake_role) {
202 case webrtc::InternalDataChannelInit::kNone: // pre-negotiated
203 handshake_state_ = kHandshakeReady;
204 break;
205 case webrtc::InternalDataChannelInit::kOpener:
206 handshake_state_ = kHandshakeShouldSendOpen;
207 break;
208 case webrtc::InternalDataChannelInit::kAcker:
209 handshake_state_ = kHandshakeShouldSendAck;
210 break;
211 }
212
213 // Try to connect to the transport in case the transport channel already
214 // exists.
215 OnTransportChannelCreated();
216
217 // Checks if the transport is ready to send because the initial channel
218 // ready signal may have been sent before the DataChannel creation.
219 // This has to be done async because the upper layer objects (e.g.
220 // Chrome glue and WebKit) are not wired up properly until after this
221 // function returns.
Harald Alvestrand9e5aeb92022-05-11 09:35:36222 RTC_DCHECK(!controller_detached_);
223 if (controller_->ReadyToSendData()) {
Tomas Gunnarssonb774d382020-09-20 21:56:24224 AddRef();
225 rtc::Thread::Current()->PostTask(ToQueuedTask(
226 [this] {
227 RTC_DCHECK_RUN_ON(signaling_thread_);
228 if (state_ != kClosed)
229 OnTransportReady(true);
230 },
231 [this] { Release(); }));
Taylor Brandstetter3a034e12020-07-09 22:32:34232 }
233
234 return true;
235}
236
237SctpDataChannel::~SctpDataChannel() {
238 RTC_DCHECK_RUN_ON(signaling_thread_);
239}
240
241void SctpDataChannel::RegisterObserver(DataChannelObserver* observer) {
242 RTC_DCHECK_RUN_ON(signaling_thread_);
243 observer_ = observer;
244 DeliverQueuedReceivedData();
245}
246
247void SctpDataChannel::UnregisterObserver() {
248 RTC_DCHECK_RUN_ON(signaling_thread_);
249 observer_ = nullptr;
250}
251
252bool SctpDataChannel::reliable() const {
253 // May be called on any thread.
254 return !config_.maxRetransmits && !config_.maxRetransmitTime;
255}
256
257uint64_t SctpDataChannel::buffered_amount() const {
258 RTC_DCHECK_RUN_ON(signaling_thread_);
Florent Castelli65956852021-10-18 09:13:22259 return queued_send_data_.byte_count();
Taylor Brandstetter3a034e12020-07-09 22:32:34260}
261
262void SctpDataChannel::Close() {
263 RTC_DCHECK_RUN_ON(signaling_thread_);
Florent Castelli8f04c7c2022-05-05 21:43:44264 if (state_ == kClosing || state_ == kClosed)
Taylor Brandstetter3a034e12020-07-09 22:32:34265 return;
266 SetState(kClosing);
267 // Will send queued data before beginning the underlying closing procedure.
268 UpdateState();
269}
270
271SctpDataChannel::DataState SctpDataChannel::state() const {
272 RTC_DCHECK_RUN_ON(signaling_thread_);
273 return state_;
274}
275
276RTCError SctpDataChannel::error() const {
277 RTC_DCHECK_RUN_ON(signaling_thread_);
278 return error_;
279}
280
281uint32_t SctpDataChannel::messages_sent() const {
282 RTC_DCHECK_RUN_ON(signaling_thread_);
283 return messages_sent_;
284}
285
286uint64_t SctpDataChannel::bytes_sent() const {
287 RTC_DCHECK_RUN_ON(signaling_thread_);
288 return bytes_sent_;
289}
290
291uint32_t SctpDataChannel::messages_received() const {
292 RTC_DCHECK_RUN_ON(signaling_thread_);
293 return messages_received_;
294}
295
296uint64_t SctpDataChannel::bytes_received() const {
297 RTC_DCHECK_RUN_ON(signaling_thread_);
298 return bytes_received_;
299}
300
301bool SctpDataChannel::Send(const DataBuffer& buffer) {
302 RTC_DCHECK_RUN_ON(signaling_thread_);
303 // TODO(bugs.webrtc.org/11547): Expect this method to be called on the network
304 // thread. Bring buffer management etc to the network thread and keep the
305 // operational state management on the signaling thread.
306
307 if (state_ != kOpen) {
308 return false;
309 }
310
Taylor Brandstetter3a034e12020-07-09 22:32:34311 // If the queue is non-empty, we're waiting for SignalReadyToSend,
312 // so just add to the end of the queue and keep waiting.
313 if (!queued_send_data_.Empty()) {
314 if (!QueueSendDataMessage(buffer)) {
Florent Castelli01343032021-11-03 15:09:46315 // Queue is full
316 return false;
Taylor Brandstetter3a034e12020-07-09 22:32:34317 }
318 return true;
319 }
320
321 SendDataMessage(buffer, true);
322
323 // Always return true for SCTP DataChannel per the spec.
324 return true;
325}
326
327void SctpDataChannel::SetSctpSid(int sid) {
328 RTC_DCHECK_RUN_ON(signaling_thread_);
329 RTC_DCHECK_LT(config_.id, 0);
330 RTC_DCHECK_GE(sid, 0);
331 RTC_DCHECK_NE(handshake_state_, kHandshakeWaitingForAck);
332 RTC_DCHECK_EQ(state_, kConnecting);
333
334 if (config_.id == sid) {
335 return;
336 }
337
338 const_cast<InternalDataChannelInit&>(config_).id = sid;
Harald Alvestrand9e5aeb92022-05-11 09:35:36339 RTC_DCHECK(!controller_detached_);
340 controller_->AddSctpDataStream(sid);
Taylor Brandstetter3a034e12020-07-09 22:32:34341}
342
343void SctpDataChannel::OnClosingProcedureStartedRemotely(int sid) {
344 RTC_DCHECK_RUN_ON(signaling_thread_);
345 if (sid == config_.id && state_ != kClosing && state_ != kClosed) {
346 // Don't bother sending queued data since the side that initiated the
347 // closure wouldn't receive it anyway. See crbug.com/559394 for a lengthy
348 // discussion about this.
349 queued_send_data_.Clear();
350 queued_control_data_.Clear();
351 // Just need to change state to kClosing, SctpTransport will handle the
352 // rest of the closing procedure and OnClosingProcedureComplete will be
353 // called later.
354 started_closing_procedure_ = true;
355 SetState(kClosing);
356 }
357}
358
359void SctpDataChannel::OnClosingProcedureComplete(int sid) {
360 RTC_DCHECK_RUN_ON(signaling_thread_);
361 if (sid == config_.id) {
362 // If the closing procedure is complete, we should have finished sending
363 // all pending data and transitioned to kClosing already.
364 RTC_DCHECK_EQ(state_, kClosing);
365 RTC_DCHECK(queued_send_data_.Empty());
Harald Alvestrand9e5aeb92022-05-11 09:35:36366 DisconnectFromTransport();
Taylor Brandstetter3a034e12020-07-09 22:32:34367 SetState(kClosed);
368 }
369}
370
371void SctpDataChannel::OnTransportChannelCreated() {
372 RTC_DCHECK_RUN_ON(signaling_thread_);
Harald Alvestrand9e5aeb92022-05-11 09:35:36373 if (controller_detached_) {
374 return;
Taylor Brandstetter3a034e12020-07-09 22:32:34375 }
Harald Alvestrand9e5aeb92022-05-11 09:35:36376 if (!connected_to_transport_) {
377 connected_to_transport_ = controller_->ConnectDataChannel(this);
378 }
379 // The sid may have been unassigned when controller_->ConnectDataChannel was
380 // done. So always add the streams even if connected_to_transport_ is true.
Taylor Brandstetter3a034e12020-07-09 22:32:34381 if (config_.id >= 0) {
Harald Alvestrand9e5aeb92022-05-11 09:35:36382 controller_->AddSctpDataStream(config_.id);
Taylor Brandstetter3a034e12020-07-09 22:32:34383 }
384}
385
Florent Castellidcb9ffc2021-06-29 12:58:23386void SctpDataChannel::OnTransportChannelClosed(RTCError error) {
387 // The SctpTransport is unusable, which could come from multiplie reasons:
388 // - the SCTP m= section was rejected
389 // - the DTLS transport is closed
390 // - the SCTP transport is closed
Taylor Brandstetter3a034e12020-07-09 22:32:34391 CloseAbruptlyWithError(std::move(error));
392}
393
394DataChannelStats SctpDataChannel::GetStats() const {
395 RTC_DCHECK_RUN_ON(signaling_thread_);
396 DataChannelStats stats{internal_id_, id(), label(),
397 protocol(), state(), messages_sent(),
398 messages_received(), bytes_sent(), bytes_received()};
399 return stats;
400}
401
402void SctpDataChannel::OnDataReceived(const cricket::ReceiveDataParams& params,
403 const rtc::CopyOnWriteBuffer& payload) {
404 RTC_DCHECK_RUN_ON(signaling_thread_);
405 if (params.sid != config_.id) {
406 return;
407 }
408
Florent Castellid95b1492021-05-10 09:29:56409 if (params.type == DataMessageType::kControl) {
Taylor Brandstetter3a034e12020-07-09 22:32:34410 if (handshake_state_ != kHandshakeWaitingForAck) {
411 // Ignore it if we are not expecting an ACK message.
412 RTC_LOG(LS_WARNING)
413 << "DataChannel received unexpected CONTROL message, sid = "
414 << params.sid;
415 return;
416 }
417 if (ParseDataChannelOpenAckMessage(payload)) {
418 // We can send unordered as soon as we receive the ACK message.
419 handshake_state_ = kHandshakeReady;
420 RTC_LOG(LS_INFO) << "DataChannel received OPEN_ACK message, sid = "
421 << params.sid;
422 } else {
423 RTC_LOG(LS_WARNING)
424 << "DataChannel failed to parse OPEN_ACK message, sid = "
425 << params.sid;
426 }
427 return;
428 }
429
Florent Castellid95b1492021-05-10 09:29:56430 RTC_DCHECK(params.type == DataMessageType::kBinary ||
431 params.type == DataMessageType::kText);
Taylor Brandstetter3a034e12020-07-09 22:32:34432
433 RTC_LOG(LS_VERBOSE) << "DataChannel received DATA message, sid = "
434 << params.sid;
435 // We can send unordered as soon as we receive any DATA message since the
436 // remote side must have received the OPEN (and old clients do not send
437 // OPEN_ACK).
438 if (handshake_state_ == kHandshakeWaitingForAck) {
439 handshake_state_ = kHandshakeReady;
440 }
441
Florent Castellid95b1492021-05-10 09:29:56442 bool binary = (params.type == webrtc::DataMessageType::kBinary);
Taylor Brandstetter3a034e12020-07-09 22:32:34443 auto buffer = std::make_unique<DataBuffer>(payload, binary);
444 if (state_ == kOpen && observer_) {
445 ++messages_received_;
446 bytes_received_ += buffer->size();
447 observer_->OnMessage(*buffer.get());
448 } else {
449 if (queued_received_data_.byte_count() + payload.size() >
450 kMaxQueuedReceivedDataBytes) {
451 RTC_LOG(LS_ERROR) << "Queued received data exceeds the max buffer size.";
452
453 queued_received_data_.Clear();
454 CloseAbruptlyWithError(
455 RTCError(RTCErrorType::RESOURCE_EXHAUSTED,
456 "Queued received data exceeds the max buffer size."));
457
458 return;
459 }
460 queued_received_data_.PushBack(std::move(buffer));
461 }
462}
463
464void SctpDataChannel::OnTransportReady(bool writable) {
465 RTC_DCHECK_RUN_ON(signaling_thread_);
466
467 writable_ = writable;
468 if (!writable) {
469 return;
470 }
471
472 SendQueuedControlMessages();
473 SendQueuedDataMessages();
474
475 UpdateState();
476}
477
478void SctpDataChannel::CloseAbruptlyWithError(RTCError error) {
479 RTC_DCHECK_RUN_ON(signaling_thread_);
480
481 if (state_ == kClosed) {
482 return;
483 }
484
Harald Alvestrand9e5aeb92022-05-11 09:35:36485 if (connected_to_transport_) {
486 DisconnectFromTransport();
Taylor Brandstetter3a034e12020-07-09 22:32:34487 }
488
489 // Closing abruptly means any queued data gets thrown away.
Taylor Brandstetter3a034e12020-07-09 22:32:34490 queued_send_data_.Clear();
491 queued_control_data_.Clear();
492
493 // Still go to "kClosing" before "kClosed", since observers may be expecting
494 // that.
495 SetState(kClosing);
496 error_ = std::move(error);
497 SetState(kClosed);
498}
499
500void SctpDataChannel::CloseAbruptlyWithDataChannelFailure(
501 const std::string& message) {
502 RTCError error(RTCErrorType::OPERATION_ERROR_WITH_DATA, message);
503 error.set_error_detail(RTCErrorDetailType::DATA_CHANNEL_FAILURE);
504 CloseAbruptlyWithError(std::move(error));
505}
506
507void SctpDataChannel::UpdateState() {
508 RTC_DCHECK_RUN_ON(signaling_thread_);
509 // UpdateState determines what to do from a few state variables. Include
510 // all conditions required for each state transition here for
511 // clarity. OnTransportReady(true) will send any queued data and then invoke
512 // UpdateState().
513
514 switch (state_) {
515 case kConnecting: {
Harald Alvestrand9e5aeb92022-05-11 09:35:36516 if (connected_to_transport_) {
Taylor Brandstetter3a034e12020-07-09 22:32:34517 if (handshake_state_ == kHandshakeShouldSendOpen) {
518 rtc::CopyOnWriteBuffer payload;
519 WriteDataChannelOpenMessage(label_, config_, &payload);
520 SendControlMessage(payload);
521 } else if (handshake_state_ == kHandshakeShouldSendAck) {
522 rtc::CopyOnWriteBuffer payload;
523 WriteDataChannelOpenAckMessage(&payload);
524 SendControlMessage(payload);
525 }
526 if (writable_ && (handshake_state_ == kHandshakeReady ||
527 handshake_state_ == kHandshakeWaitingForAck)) {
528 SetState(kOpen);
529 // If we have received buffers before the channel got writable.
530 // Deliver them now.
531 DeliverQueuedReceivedData();
532 }
533 }
534 break;
535 }
536 case kOpen: {
537 break;
538 }
539 case kClosing: {
540 // Wait for all queued data to be sent before beginning the closing
541 // procedure.
542 if (queued_send_data_.Empty() && queued_control_data_.Empty()) {
543 // For SCTP data channels, we need to wait for the closing procedure
544 // to complete; after calling RemoveSctpDataStream,
545 // OnClosingProcedureComplete will end up called asynchronously
546 // afterwards.
Harald Alvestrand9e5aeb92022-05-11 09:35:36547 if (connected_to_transport_ && !started_closing_procedure_ &&
548 !controller_detached_ && config_.id >= 0) {
Taylor Brandstetter3a034e12020-07-09 22:32:34549 started_closing_procedure_ = true;
Harald Alvestrand9e5aeb92022-05-11 09:35:36550 controller_->RemoveSctpDataStream(config_.id);
Taylor Brandstetter3a034e12020-07-09 22:32:34551 }
552 }
553 break;
554 }
555 case kClosed:
556 break;
557 }
558}
559
560void SctpDataChannel::SetState(DataState state) {
561 RTC_DCHECK_RUN_ON(signaling_thread_);
562 if (state_ == state) {
563 return;
564 }
565
566 state_ = state;
567 if (observer_) {
568 observer_->OnStateChange();
569 }
570 if (state_ == kOpen) {
571 SignalOpened(this);
572 } else if (state_ == kClosed) {
573 SignalClosed(this);
574 }
575}
576
Harald Alvestrand9e5aeb92022-05-11 09:35:36577void SctpDataChannel::DisconnectFromTransport() {
Taylor Brandstetter3a034e12020-07-09 22:32:34578 RTC_DCHECK_RUN_ON(signaling_thread_);
Harald Alvestrand9e5aeb92022-05-11 09:35:36579 if (!connected_to_transport_ || controller_detached_)
Taylor Brandstetter3a034e12020-07-09 22:32:34580 return;
581
Harald Alvestrand9e5aeb92022-05-11 09:35:36582 controller_->DisconnectDataChannel(this);
583 connected_to_transport_ = false;
Taylor Brandstetter3a034e12020-07-09 22:32:34584}
585
586void SctpDataChannel::DeliverQueuedReceivedData() {
587 RTC_DCHECK_RUN_ON(signaling_thread_);
588 if (!observer_) {
589 return;
590 }
591
592 while (!queued_received_data_.Empty()) {
593 std::unique_ptr<DataBuffer> buffer = queued_received_data_.PopFront();
594 ++messages_received_;
595 bytes_received_ += buffer->size();
596 observer_->OnMessage(*buffer);
597 }
598}
599
600void SctpDataChannel::SendQueuedDataMessages() {
601 RTC_DCHECK_RUN_ON(signaling_thread_);
602 if (queued_send_data_.Empty()) {
603 return;
604 }
605
606 RTC_DCHECK(state_ == kOpen || state_ == kClosing);
607
608 while (!queued_send_data_.Empty()) {
609 std::unique_ptr<DataBuffer> buffer = queued_send_data_.PopFront();
610 if (!SendDataMessage(*buffer, false)) {
611 // Return the message to the front of the queue if sending is aborted.
612 queued_send_data_.PushFront(std::move(buffer));
613 break;
614 }
615 }
616}
617
618bool SctpDataChannel::SendDataMessage(const DataBuffer& buffer,
619 bool queue_if_blocked) {
620 RTC_DCHECK_RUN_ON(signaling_thread_);
Florent Castellid95b1492021-05-10 09:29:56621 SendDataParams send_params;
Harald Alvestrand9e5aeb92022-05-11 09:35:36622 if (controller_detached_) {
623 return false;
624 }
Taylor Brandstetter3a034e12020-07-09 22:32:34625
626 send_params.ordered = config_.ordered;
627 // Send as ordered if it is still going through OPEN/ACK signaling.
628 if (handshake_state_ != kHandshakeReady && !config_.ordered) {
629 send_params.ordered = true;
630 RTC_LOG(LS_VERBOSE)
631 << "Sending data as ordered for unordered DataChannel "
632 "because the OPEN_ACK message has not been received.";
633 }
634
Florent Castelli5183f002021-05-07 11:52:44635 send_params.max_rtx_count = config_.maxRetransmits;
636 send_params.max_rtx_ms = config_.maxRetransmitTime;
Florent Castellid95b1492021-05-10 09:29:56637 send_params.type =
638 buffer.binary ? DataMessageType::kBinary : DataMessageType::kText;
Taylor Brandstetter3a034e12020-07-09 22:32:34639
640 cricket::SendDataResult send_result = cricket::SDR_SUCCESS;
Florent Castellid95b1492021-05-10 09:29:56641 bool success =
Harald Alvestrand9e5aeb92022-05-11 09:35:36642 controller_->SendData(config_.id, send_params, buffer.data, &send_result);
Taylor Brandstetter3a034e12020-07-09 22:32:34643
644 if (success) {
645 ++messages_sent_;
646 bytes_sent_ += buffer.size();
647
Taylor Brandstetter3a034e12020-07-09 22:32:34648 if (observer_ && buffer.size() > 0) {
649 observer_->OnBufferedAmountChange(buffer.size());
650 }
651 return true;
652 }
653
654 if (send_result == cricket::SDR_BLOCK) {
655 if (!queue_if_blocked || QueueSendDataMessage(buffer)) {
656 return false;
657 }
658 }
659 // Close the channel if the error is not SDR_BLOCK, or if queuing the
660 // message failed.
661 RTC_LOG(LS_ERROR) << "Closing the DataChannel due to a failure to send data, "
662 "send_result = "
663 << send_result;
664 CloseAbruptlyWithError(
665 RTCError(RTCErrorType::NETWORK_ERROR, "Failure to send data"));
666
667 return false;
668}
669
670bool SctpDataChannel::QueueSendDataMessage(const DataBuffer& buffer) {
671 RTC_DCHECK_RUN_ON(signaling_thread_);
672 size_t start_buffered_amount = queued_send_data_.byte_count();
Florent Castellia563a2a2021-10-18 09:46:21673 if (start_buffered_amount + buffer.size() >
674 DataChannelInterface::MaxSendQueueSize()) {
Taylor Brandstetter3a034e12020-07-09 22:32:34675 RTC_LOG(LS_ERROR) << "Can't buffer any more data for the data channel.";
676 return false;
677 }
678 queued_send_data_.PushBack(std::make_unique<DataBuffer>(buffer));
679 return true;
680}
681
682void SctpDataChannel::SendQueuedControlMessages() {
683 RTC_DCHECK_RUN_ON(signaling_thread_);
684 PacketQueue control_packets;
685 control_packets.Swap(&queued_control_data_);
686
687 while (!control_packets.Empty()) {
688 std::unique_ptr<DataBuffer> buf = control_packets.PopFront();
689 SendControlMessage(buf->data);
690 }
691}
692
693void SctpDataChannel::QueueControlMessage(
694 const rtc::CopyOnWriteBuffer& buffer) {
695 RTC_DCHECK_RUN_ON(signaling_thread_);
696 queued_control_data_.PushBack(std::make_unique<DataBuffer>(buffer, true));
697}
698
699bool SctpDataChannel::SendControlMessage(const rtc::CopyOnWriteBuffer& buffer) {
700 RTC_DCHECK_RUN_ON(signaling_thread_);
701 RTC_DCHECK(writable_);
702 RTC_DCHECK_GE(config_.id, 0);
703
Harald Alvestrand9e5aeb92022-05-11 09:35:36704 if (controller_detached_) {
705 return false;
706 }
Taylor Brandstetter3a034e12020-07-09 22:32:34707 bool is_open_message = handshake_state_ == kHandshakeShouldSendOpen;
708 RTC_DCHECK(!is_open_message || !config_.negotiated);
709
Florent Castellid95b1492021-05-10 09:29:56710 SendDataParams send_params;
Taylor Brandstetter3a034e12020-07-09 22:32:34711 // Send data as ordered before we receive any message from the remote peer to
712 // make sure the remote peer will not receive any data before it receives the
713 // OPEN message.
714 send_params.ordered = config_.ordered || is_open_message;
Florent Castellid95b1492021-05-10 09:29:56715 send_params.type = DataMessageType::kControl;
Taylor Brandstetter3a034e12020-07-09 22:32:34716
717 cricket::SendDataResult send_result = cricket::SDR_SUCCESS;
Florent Castellid95b1492021-05-10 09:29:56718 bool retval =
Harald Alvestrand9e5aeb92022-05-11 09:35:36719 controller_->SendData(config_.id, send_params, buffer, &send_result);
Taylor Brandstetter3a034e12020-07-09 22:32:34720 if (retval) {
721 RTC_LOG(LS_VERBOSE) << "Sent CONTROL message on channel " << config_.id;
722
723 if (handshake_state_ == kHandshakeShouldSendAck) {
724 handshake_state_ = kHandshakeReady;
725 } else if (handshake_state_ == kHandshakeShouldSendOpen) {
726 handshake_state_ = kHandshakeWaitingForAck;
727 }
728 } else if (send_result == cricket::SDR_BLOCK) {
729 QueueControlMessage(buffer);
730 } else {
731 RTC_LOG(LS_ERROR) << "Closing the DataChannel due to a failure to send"
732 " the CONTROL message, send_result = "
733 << send_result;
734 CloseAbruptlyWithError(RTCError(RTCErrorType::NETWORK_ERROR,
735 "Failed to send a CONTROL message"));
736 }
737 return retval;
738}
739
740// static
741void SctpDataChannel::ResetInternalIdAllocatorForTesting(int new_value) {
742 g_unique_id = new_value;
743}
744
Harald Alvestrand9e5aeb92022-05-11 09:35:36745SctpDataChannel* DowncastProxiedDataChannelInterfaceToSctpDataChannelForTesting(
746 DataChannelInterface* channel) {
747 return static_cast<SctpDataChannel*>(
748 static_cast<DataChannelProxy*>(channel)->internal());
749}
750
Taylor Brandstetter3a034e12020-07-09 22:32:34751} // namespace webrtc