You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

725 lines
22 KiB

​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
  1. /*
  2. * Copyright 2012 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. #include "pc/data_channel.h"
  11. #include <memory>
  12. #include <string>
  13. #include <utility>
  14. #include "media/sctp/sctp_transport_internal.h"
  15. #include "pc/sctp_utils.h"
  16. #include "rtc_base/checks.h"
  17. #include "rtc_base/location.h"
  18. #include "rtc_base/logging.h"
  19. #include "rtc_base/ref_counted_object.h"
  20. #include "rtc_base/thread.h"
  21. namespace webrtc {
  22. static size_t kMaxQueuedReceivedDataBytes = 16 * 1024 * 1024;
  23. static size_t kMaxQueuedSendDataBytes = 16 * 1024 * 1024;
  24. namespace {
  25. static std::atomic<int> g_unique_id{0};
  26. int GenerateUniqueId() {
  27. return ++g_unique_id;
  28. }
  29. } // namespace
  30. InternalDataChannelInit::InternalDataChannelInit(const DataChannelInit& base)
  31. : DataChannelInit(base), open_handshake_role(kOpener) {
  32. // If the channel is externally negotiated, do not send the OPEN message.
  33. if (base.negotiated) {
  34. open_handshake_role = kNone;
  35. } else {
  36. // Datachannel is externally negotiated. Ignore the id value.
  37. // Specified in createDataChannel, WebRTC spec section 6.1 bullet 13.
  38. id = -1;
  39. }
  40. // Backwards compatibility: If base.maxRetransmits or base.maxRetransmitTime
  41. // have been set to -1, unset them.
  42. if (maxRetransmits && *maxRetransmits == -1) {
  43. RTC_LOG(LS_ERROR)
  44. << "Accepting maxRetransmits = -1 for backwards compatibility";
  45. maxRetransmits = absl::nullopt;
  46. }
  47. if (maxRetransmitTime && *maxRetransmitTime == -1) {
  48. RTC_LOG(LS_ERROR)
  49. << "Accepting maxRetransmitTime = -1 for backwards compatibility";
  50. maxRetransmitTime = absl::nullopt;
  51. }
  52. }
  53. bool SctpSidAllocator::AllocateSid(rtc::SSLRole role, int* sid) {
  54. int potential_sid = (role == rtc::SSL_CLIENT) ? 0 : 1;
  55. while (!IsSidAvailable(potential_sid)) {
  56. potential_sid += 2;
  57. if (potential_sid > static_cast<int>(cricket::kMaxSctpSid)) {
  58. return false;
  59. }
  60. }
  61. *sid = potential_sid;
  62. used_sids_.insert(potential_sid);
  63. return true;
  64. }
  65. bool SctpSidAllocator::ReserveSid(int sid) {
  66. if (!IsSidAvailable(sid)) {
  67. return false;
  68. }
  69. used_sids_.insert(sid);
  70. return true;
  71. }
  72. void SctpSidAllocator::ReleaseSid(int sid) {
  73. auto it = used_sids_.find(sid);
  74. if (it != used_sids_.end()) {
  75. used_sids_.erase(it);
  76. }
  77. }
  78. bool SctpSidAllocator::IsSidAvailable(int sid) const {
  79. if (sid < static_cast<int>(cricket::kMinSctpSid) ||
  80. sid > static_cast<int>(cricket::kMaxSctpSid)) {
  81. return false;
  82. }
  83. return used_sids_.find(sid) == used_sids_.end();
  84. }
  85. bool DataChannel::PacketQueue::Empty() const {
  86. return packets_.empty();
  87. }
  88. std::unique_ptr<DataBuffer> DataChannel::PacketQueue::PopFront() {
  89. RTC_DCHECK(!packets_.empty());
  90. byte_count_ -= packets_.front()->size();
  91. std::unique_ptr<DataBuffer> packet = std::move(packets_.front());
  92. packets_.pop_front();
  93. return packet;
  94. }
  95. void DataChannel::PacketQueue::PushFront(std::unique_ptr<DataBuffer> packet) {
  96. byte_count_ += packet->size();
  97. packets_.push_front(std::move(packet));
  98. }
  99. void DataChannel::PacketQueue::PushBack(std::unique_ptr<DataBuffer> packet) {
  100. byte_count_ += packet->size();
  101. packets_.push_back(std::move(packet));
  102. }
  103. void DataChannel::PacketQueue::Clear() {
  104. packets_.clear();
  105. byte_count_ = 0;
  106. }
  107. void DataChannel::PacketQueue::Swap(PacketQueue* other) {
  108. size_t other_byte_count = other->byte_count_;
  109. other->byte_count_ = byte_count_;
  110. byte_count_ = other_byte_count;
  111. other->packets_.swap(packets_);
  112. }
  113. rtc::scoped_refptr<DataChannel> DataChannel::Create(
  114. DataChannelProviderInterface* provider,
  115. cricket::DataChannelType dct,
  116. const std::string& label,
  117. const InternalDataChannelInit& config) {
  118. rtc::scoped_refptr<DataChannel> channel(
  119. new rtc::RefCountedObject<DataChannel>(provider, dct, label));
  120. if (!channel->Init(config)) {
  121. return NULL;
  122. }
  123. return channel;
  124. }
  125. bool DataChannel::IsSctpLike(cricket::DataChannelType type) {
  126. return type == cricket::DCT_SCTP || type == cricket::DCT_MEDIA_TRANSPORT ||
  127. type == cricket::DCT_DATA_CHANNEL_TRANSPORT ||
  128. type == cricket::DCT_DATA_CHANNEL_TRANSPORT_SCTP;
  129. }
  130. DataChannel::DataChannel(DataChannelProviderInterface* provider,
  131. cricket::DataChannelType dct,
  132. const std::string& label)
  133. : internal_id_(GenerateUniqueId()),
  134. label_(label),
  135. observer_(nullptr),
  136. state_(kConnecting),
  137. messages_sent_(0),
  138. bytes_sent_(0),
  139. messages_received_(0),
  140. bytes_received_(0),
  141. buffered_amount_(0),
  142. data_channel_type_(dct),
  143. provider_(provider),
  144. handshake_state_(kHandshakeInit),
  145. connected_to_provider_(false),
  146. send_ssrc_set_(false),
  147. receive_ssrc_set_(false),
  148. writable_(false),
  149. send_ssrc_(0),
  150. receive_ssrc_(0) {}
  151. bool DataChannel::Init(const InternalDataChannelInit& config) {
  152. if (data_channel_type_ == cricket::DCT_RTP) {
  153. if (config.reliable || config.id != -1 || config.maxRetransmits ||
  154. config.maxRetransmitTime) {
  155. RTC_LOG(LS_ERROR) << "Failed to initialize the RTP data channel due to "
  156. "invalid DataChannelInit.";
  157. return false;
  158. }
  159. handshake_state_ = kHandshakeReady;
  160. } else if (IsSctpLike(data_channel_type_)) {
  161. if (config.id < -1 ||
  162. (config.maxRetransmits && *config.maxRetransmits < 0) ||
  163. (config.maxRetransmitTime && *config.maxRetransmitTime < 0)) {
  164. RTC_LOG(LS_ERROR) << "Failed to initialize the SCTP data channel due to "
  165. "invalid DataChannelInit.";
  166. return false;
  167. }
  168. if (config.maxRetransmits && config.maxRetransmitTime) {
  169. RTC_LOG(LS_ERROR)
  170. << "maxRetransmits and maxRetransmitTime should not be both set.";
  171. return false;
  172. }
  173. config_ = config;
  174. switch (config_.open_handshake_role) {
  175. case webrtc::InternalDataChannelInit::kNone: // pre-negotiated
  176. handshake_state_ = kHandshakeReady;
  177. break;
  178. case webrtc::InternalDataChannelInit::kOpener:
  179. handshake_state_ = kHandshakeShouldSendOpen;
  180. break;
  181. case webrtc::InternalDataChannelInit::kAcker:
  182. handshake_state_ = kHandshakeShouldSendAck;
  183. break;
  184. }
  185. // Try to connect to the transport in case the transport channel already
  186. // exists.
  187. OnTransportChannelCreated();
  188. // Checks if the transport is ready to send because the initial channel
  189. // ready signal may have been sent before the DataChannel creation.
  190. // This has to be done async because the upper layer objects (e.g.
  191. // Chrome glue and WebKit) are not wired up properly until after this
  192. // function returns.
  193. if (provider_->ReadyToSendData()) {
  194. invoker_.AsyncInvoke<void>(RTC_FROM_HERE, rtc::Thread::Current(),
  195. [this] { OnChannelReady(true); });
  196. }
  197. }
  198. return true;
  199. }
  200. DataChannel::~DataChannel() {}
  201. void DataChannel::RegisterObserver(DataChannelObserver* observer) {
  202. observer_ = observer;
  203. DeliverQueuedReceivedData();
  204. }
  205. void DataChannel::UnregisterObserver() {
  206. observer_ = NULL;
  207. }
  208. bool DataChannel::reliable() const {
  209. if (data_channel_type_ == cricket::DCT_RTP) {
  210. return false;
  211. } else {
  212. return !config_.maxRetransmits && !config_.maxRetransmitTime;
  213. }
  214. }
  215. uint64_t DataChannel::buffered_amount() const {
  216. return buffered_amount_;
  217. }
  218. void DataChannel::Close() {
  219. if (state_ == kClosed)
  220. return;
  221. send_ssrc_ = 0;
  222. send_ssrc_set_ = false;
  223. SetState(kClosing);
  224. // Will send queued data before beginning the underlying closing procedure.
  225. UpdateState();
  226. }
  227. bool DataChannel::Send(const DataBuffer& buffer) {
  228. buffered_amount_ += buffer.size();
  229. if (state_ != kOpen) {
  230. return false;
  231. }
  232. // TODO(jiayl): the spec is unclear about if the remote side should get the
  233. // onmessage event. We need to figure out the expected behavior and change the
  234. // code accordingly.
  235. if (buffer.size() == 0) {
  236. return true;
  237. }
  238. // If the queue is non-empty, we're waiting for SignalReadyToSend,
  239. // so just add to the end of the queue and keep waiting.
  240. if (!queued_send_data_.Empty()) {
  241. // Only SCTP DataChannel queues the outgoing data when the transport is
  242. // blocked.
  243. RTC_DCHECK(IsSctpLike(data_channel_type_));
  244. if (!QueueSendDataMessage(buffer)) {
  245. RTC_LOG(LS_ERROR) << "Closing the DataChannel due to a failure to queue "
  246. "additional data.";
  247. CloseAbruptly();
  248. }
  249. return true;
  250. }
  251. bool success = SendDataMessage(buffer, true);
  252. if (data_channel_type_ == cricket::DCT_RTP) {
  253. return success;
  254. }
  255. // Always return true for SCTP DataChannel per the spec.
  256. return true;
  257. }
  258. void DataChannel::SetReceiveSsrc(uint32_t receive_ssrc) {
  259. RTC_DCHECK(data_channel_type_ == cricket::DCT_RTP);
  260. if (receive_ssrc_set_) {
  261. return;
  262. }
  263. receive_ssrc_ = receive_ssrc;
  264. receive_ssrc_set_ = true;
  265. UpdateState();
  266. }
  267. void DataChannel::SetSctpSid(int sid) {
  268. RTC_DCHECK_LT(config_.id, 0);
  269. RTC_DCHECK_GE(sid, 0);
  270. RTC_DCHECK(IsSctpLike(data_channel_type_));
  271. if (config_.id == sid) {
  272. return;
  273. }
  274. config_.id = sid;
  275. provider_->AddSctpDataStream(sid);
  276. }
  277. void DataChannel::OnClosingProcedureStartedRemotely(int sid) {
  278. if (IsSctpLike(data_channel_type_) && sid == config_.id &&
  279. state_ != kClosing && state_ != kClosed) {
  280. // Don't bother sending queued data since the side that initiated the
  281. // closure wouldn't receive it anyway. See crbug.com/559394 for a lengthy
  282. // discussion about this.
  283. queued_send_data_.Clear();
  284. queued_control_data_.Clear();
  285. // Just need to change state to kClosing, SctpTransport will handle the
  286. // rest of the closing procedure and OnClosingProcedureComplete will be
  287. // called later.
  288. started_closing_procedure_ = true;
  289. SetState(kClosing);
  290. }
  291. }
  292. void DataChannel::OnClosingProcedureComplete(int sid) {
  293. if (IsSctpLike(data_channel_type_) && sid == config_.id) {
  294. // If the closing procedure is complete, we should have finished sending
  295. // all pending data and transitioned to kClosing already.
  296. RTC_DCHECK_EQ(state_, kClosing);
  297. RTC_DCHECK(queued_send_data_.Empty());
  298. DisconnectFromProvider();
  299. SetState(kClosed);
  300. }
  301. }
  302. void DataChannel::OnTransportChannelCreated() {
  303. RTC_DCHECK(IsSctpLike(data_channel_type_));
  304. if (!connected_to_provider_) {
  305. connected_to_provider_ = provider_->ConnectDataChannel(this);
  306. }
  307. // The sid may have been unassigned when provider_->ConnectDataChannel was
  308. // done. So always add the streams even if connected_to_provider_ is true.
  309. if (config_.id >= 0) {
  310. provider_->AddSctpDataStream(config_.id);
  311. }
  312. }
  313. void DataChannel::OnTransportChannelDestroyed() {
  314. // The SctpTransport is going away (for example, because the SCTP m= section
  315. // was rejected), so we need to close abruptly.
  316. CloseAbruptly();
  317. }
  318. // The remote peer request that this channel shall be closed.
  319. void DataChannel::RemotePeerRequestClose() {
  320. RTC_DCHECK(data_channel_type_ == cricket::DCT_RTP);
  321. CloseAbruptly();
  322. }
  323. void DataChannel::SetSendSsrc(uint32_t send_ssrc) {
  324. RTC_DCHECK(data_channel_type_ == cricket::DCT_RTP);
  325. if (send_ssrc_set_) {
  326. return;
  327. }
  328. send_ssrc_ = send_ssrc;
  329. send_ssrc_set_ = true;
  330. UpdateState();
  331. }
  332. void DataChannel::OnDataReceived(const cricket::ReceiveDataParams& params,
  333. const rtc::CopyOnWriteBuffer& payload) {
  334. if (data_channel_type_ == cricket::DCT_RTP && params.ssrc != receive_ssrc_) {
  335. return;
  336. }
  337. if (IsSctpLike(data_channel_type_) && params.sid != config_.id) {
  338. return;
  339. }
  340. if (params.type == cricket::DMT_CONTROL) {
  341. RTC_DCHECK(IsSctpLike(data_channel_type_));
  342. if (handshake_state_ != kHandshakeWaitingForAck) {
  343. // Ignore it if we are not expecting an ACK message.
  344. RTC_LOG(LS_WARNING)
  345. << "DataChannel received unexpected CONTROL message, sid = "
  346. << params.sid;
  347. return;
  348. }
  349. if (ParseDataChannelOpenAckMessage(payload)) {
  350. // We can send unordered as soon as we receive the ACK message.
  351. handshake_state_ = kHandshakeReady;
  352. RTC_LOG(LS_INFO) << "DataChannel received OPEN_ACK message, sid = "
  353. << params.sid;
  354. } else {
  355. RTC_LOG(LS_WARNING)
  356. << "DataChannel failed to parse OPEN_ACK message, sid = "
  357. << params.sid;
  358. }
  359. return;
  360. }
  361. RTC_DCHECK(params.type == cricket::DMT_BINARY ||
  362. params.type == cricket::DMT_TEXT);
  363. RTC_LOG(LS_VERBOSE) << "DataChannel received DATA message, sid = "
  364. << params.sid;
  365. // We can send unordered as soon as we receive any DATA message since the
  366. // remote side must have received the OPEN (and old clients do not send
  367. // OPEN_ACK).
  368. if (handshake_state_ == kHandshakeWaitingForAck) {
  369. handshake_state_ = kHandshakeReady;
  370. }
  371. bool binary = (params.type == cricket::DMT_BINARY);
  372. auto buffer = std::make_unique<DataBuffer>(payload, binary);
  373. if (state_ == kOpen && observer_) {
  374. ++messages_received_;
  375. bytes_received_ += buffer->size();
  376. observer_->OnMessage(*buffer.get());
  377. } else {
  378. if (queued_received_data_.byte_count() + payload.size() >
  379. kMaxQueuedReceivedDataBytes) {
  380. RTC_LOG(LS_ERROR) << "Queued received data exceeds the max buffer size.";
  381. queued_received_data_.Clear();
  382. if (data_channel_type_ != cricket::DCT_RTP) {
  383. CloseAbruptly();
  384. }
  385. return;
  386. }
  387. queued_received_data_.PushBack(std::move(buffer));
  388. }
  389. }
  390. void DataChannel::OnChannelReady(bool writable) {
  391. writable_ = writable;
  392. if (!writable) {
  393. return;
  394. }
  395. SendQueuedControlMessages();
  396. SendQueuedDataMessages();
  397. UpdateState();
  398. }
  399. void DataChannel::CloseAbruptly() {
  400. if (state_ == kClosed) {
  401. return;
  402. }
  403. if (connected_to_provider_) {
  404. DisconnectFromProvider();
  405. }
  406. // Closing abruptly means any queued data gets thrown away.
  407. queued_send_data_.Clear();
  408. buffered_amount_ = 0;
  409. queued_control_data_.Clear();
  410. // Still go to "kClosing" before "kClosed", since observers may be expecting
  411. // that.
  412. SetState(kClosing);
  413. SetState(kClosed);
  414. }
  415. void DataChannel::UpdateState() {
  416. // UpdateState determines what to do from a few state variables. Include
  417. // all conditions required for each state transition here for
  418. // clarity. OnChannelReady(true) will send any queued data and then invoke
  419. // UpdateState().
  420. switch (state_) {
  421. case kConnecting: {
  422. if (send_ssrc_set_ == receive_ssrc_set_) {
  423. if (data_channel_type_ == cricket::DCT_RTP && !connected_to_provider_) {
  424. connected_to_provider_ = provider_->ConnectDataChannel(this);
  425. }
  426. if (connected_to_provider_) {
  427. if (handshake_state_ == kHandshakeShouldSendOpen) {
  428. rtc::CopyOnWriteBuffer payload;
  429. WriteDataChannelOpenMessage(label_, config_, &payload);
  430. SendControlMessage(payload);
  431. } else if (handshake_state_ == kHandshakeShouldSendAck) {
  432. rtc::CopyOnWriteBuffer payload;
  433. WriteDataChannelOpenAckMessage(&payload);
  434. SendControlMessage(payload);
  435. }
  436. if (writable_ && (handshake_state_ == kHandshakeReady ||
  437. handshake_state_ == kHandshakeWaitingForAck)) {
  438. SetState(kOpen);
  439. // If we have received buffers before the channel got writable.
  440. // Deliver them now.
  441. DeliverQueuedReceivedData();
  442. }
  443. }
  444. }
  445. break;
  446. }
  447. case kOpen: {
  448. break;
  449. }
  450. case kClosing: {
  451. // Wait for all queued data to be sent before beginning the closing
  452. // procedure.
  453. if (queued_send_data_.Empty() && queued_control_data_.Empty()) {
  454. if (data_channel_type_ == cricket::DCT_RTP) {
  455. // For RTP data channels, we can go to "closed" after we finish
  456. // sending data and the send/recv SSRCs are unset.
  457. if (connected_to_provider_) {
  458. DisconnectFromProvider();
  459. }
  460. if (!send_ssrc_set_ && !receive_ssrc_set_) {
  461. SetState(kClosed);
  462. }
  463. } else {
  464. // For SCTP data channels, we need to wait for the closing procedure
  465. // to complete; after calling RemoveSctpDataStream,
  466. // OnClosingProcedureComplete will end up called asynchronously
  467. // afterwards.
  468. if (connected_to_provider_ && !started_closing_procedure_ &&
  469. config_.id >= 0) {
  470. started_closing_procedure_ = true;
  471. provider_->RemoveSctpDataStream(config_.id);
  472. }
  473. }
  474. }
  475. break;
  476. }
  477. case kClosed:
  478. break;
  479. }
  480. }
  481. void DataChannel::SetState(DataState state) {
  482. if (state_ == state) {
  483. return;
  484. }
  485. state_ = state;
  486. if (observer_) {
  487. observer_->OnStateChange();
  488. }
  489. if (state_ == kOpen) {
  490. SignalOpened(this);
  491. } else if (state_ == kClosed) {
  492. SignalClosed(this);
  493. }
  494. }
  495. void DataChannel::DisconnectFromProvider() {
  496. if (!connected_to_provider_)
  497. return;
  498. provider_->DisconnectDataChannel(this);
  499. connected_to_provider_ = false;
  500. }
  501. void DataChannel::DeliverQueuedReceivedData() {
  502. if (!observer_) {
  503. return;
  504. }
  505. while (!queued_received_data_.Empty()) {
  506. std::unique_ptr<DataBuffer> buffer = queued_received_data_.PopFront();
  507. ++messages_received_;
  508. bytes_received_ += buffer->size();
  509. observer_->OnMessage(*buffer);
  510. }
  511. }
  512. void DataChannel::SendQueuedDataMessages() {
  513. if (queued_send_data_.Empty()) {
  514. return;
  515. }
  516. RTC_DCHECK(state_ == kOpen || state_ == kClosing);
  517. while (!queued_send_data_.Empty()) {
  518. std::unique_ptr<DataBuffer> buffer = queued_send_data_.PopFront();
  519. if (!SendDataMessage(*buffer, false)) {
  520. // Return the message to the front of the queue if sending is aborted.
  521. queued_send_data_.PushFront(std::move(buffer));
  522. break;
  523. }
  524. }
  525. }
  526. bool DataChannel::SendDataMessage(const DataBuffer& buffer,
  527. bool queue_if_blocked) {
  528. cricket::SendDataParams send_params;
  529. if (IsSctpLike(data_channel_type_)) {
  530. send_params.ordered = config_.ordered;
  531. // Send as ordered if it is still going through OPEN/ACK signaling.
  532. if (handshake_state_ != kHandshakeReady && !config_.ordered) {
  533. send_params.ordered = true;
  534. RTC_LOG(LS_VERBOSE)
  535. << "Sending data as ordered for unordered DataChannel "
  536. "because the OPEN_ACK message has not been received.";
  537. }
  538. send_params.max_rtx_count =
  539. config_.maxRetransmits ? *config_.maxRetransmits : -1;
  540. send_params.max_rtx_ms =
  541. config_.maxRetransmitTime ? *config_.maxRetransmitTime : -1;
  542. send_params.sid = config_.id;
  543. } else {
  544. send_params.ssrc = send_ssrc_;
  545. }
  546. send_params.type = buffer.binary ? cricket::DMT_BINARY : cricket::DMT_TEXT;
  547. cricket::SendDataResult send_result = cricket::SDR_SUCCESS;
  548. bool success = provider_->SendData(send_params, buffer.data, &send_result);
  549. if (success) {
  550. ++messages_sent_;
  551. bytes_sent_ += buffer.size();
  552. RTC_DCHECK(buffered_amount_ >= buffer.size());
  553. buffered_amount_ -= buffer.size();
  554. if (observer_ && buffer.size() > 0) {
  555. observer_->OnBufferedAmountChange(buffer.size());
  556. }
  557. return true;
  558. }
  559. if (!IsSctpLike(data_channel_type_)) {
  560. return false;
  561. }
  562. if (send_result == cricket::SDR_BLOCK) {
  563. if (!queue_if_blocked || QueueSendDataMessage(buffer)) {
  564. return false;
  565. }
  566. }
  567. // Close the channel if the error is not SDR_BLOCK, or if queuing the
  568. // message failed.
  569. RTC_LOG(LS_ERROR) << "Closing the DataChannel due to a failure to send data, "
  570. "send_result = "
  571. << send_result;
  572. CloseAbruptly();
  573. return false;
  574. }
  575. bool DataChannel::QueueSendDataMessage(const DataBuffer& buffer) {
  576. size_t start_buffered_amount = queued_send_data_.byte_count();
  577. if (start_buffered_amount + buffer.size() > kMaxQueuedSendDataBytes) {
  578. RTC_LOG(LS_ERROR) << "Can't buffer any more data for the data channel.";
  579. return false;
  580. }
  581. queued_send_data_.PushBack(std::make_unique<DataBuffer>(buffer));
  582. return true;
  583. }
  584. void DataChannel::SendQueuedControlMessages() {
  585. PacketQueue control_packets;
  586. control_packets.Swap(&queued_control_data_);
  587. while (!control_packets.Empty()) {
  588. std::unique_ptr<DataBuffer> buf = control_packets.PopFront();
  589. SendControlMessage(buf->data);
  590. }
  591. }
  592. void DataChannel::QueueControlMessage(const rtc::CopyOnWriteBuffer& buffer) {
  593. queued_control_data_.PushBack(std::make_unique<DataBuffer>(buffer, true));
  594. }
  595. bool DataChannel::SendControlMessage(const rtc::CopyOnWriteBuffer& buffer) {
  596. bool is_open_message = handshake_state_ == kHandshakeShouldSendOpen;
  597. RTC_DCHECK(IsSctpLike(data_channel_type_));
  598. RTC_DCHECK(writable_);
  599. RTC_DCHECK_GE(config_.id, 0);
  600. RTC_DCHECK(!is_open_message || !config_.negotiated);
  601. cricket::SendDataParams send_params;
  602. send_params.sid = config_.id;
  603. // Send data as ordered before we receive any message from the remote peer to
  604. // make sure the remote peer will not receive any data before it receives the
  605. // OPEN message.
  606. send_params.ordered = config_.ordered || is_open_message;
  607. send_params.type = cricket::DMT_CONTROL;
  608. cricket::SendDataResult send_result = cricket::SDR_SUCCESS;
  609. bool retval = provider_->SendData(send_params, buffer, &send_result);
  610. if (retval) {
  611. RTC_LOG(LS_INFO) << "Sent CONTROL message on channel " << config_.id;
  612. if (handshake_state_ == kHandshakeShouldSendAck) {
  613. handshake_state_ = kHandshakeReady;
  614. } else if (handshake_state_ == kHandshakeShouldSendOpen) {
  615. handshake_state_ = kHandshakeWaitingForAck;
  616. }
  617. } else if (send_result == cricket::SDR_BLOCK) {
  618. QueueControlMessage(buffer);
  619. } else {
  620. RTC_LOG(LS_ERROR) << "Closing the DataChannel due to a failure to send"
  621. " the CONTROL message, send_result = "
  622. << send_result;
  623. CloseAbruptly();
  624. }
  625. return retval;
  626. }
  627. // static
  628. void DataChannel::ResetInternalIdAllocatorForTesting(int new_value) {
  629. g_unique_id = new_value;
  630. }
  631. } // namespace webrtc