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.

333 lines
12 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. #ifndef PC_DATA_CHANNEL_H_
  11. #define PC_DATA_CHANNEL_H_
  12. #include <deque>
  13. #include <memory>
  14. #include <set>
  15. #include <string>
  16. #include "api/data_channel_interface.h"
  17. #include "api/proxy.h"
  18. #include "api/scoped_refptr.h"
  19. #include "media/base/media_channel.h"
  20. #include "pc/channel.h"
  21. #include "rtc_base/async_invoker.h"
  22. #include "rtc_base/third_party/sigslot/sigslot.h"
  23. namespace webrtc {
  24. class DataChannel;
  25. // TODO(deadbeef): Once RTP data channels go away, get rid of this and have
  26. // DataChannel depend on SctpTransportInternal (pure virtual SctpTransport
  27. // interface) instead.
  28. class DataChannelProviderInterface {
  29. public:
  30. // Sends the data to the transport.
  31. virtual bool SendData(const cricket::SendDataParams& params,
  32. const rtc::CopyOnWriteBuffer& payload,
  33. cricket::SendDataResult* result) = 0;
  34. // Connects to the transport signals.
  35. virtual bool ConnectDataChannel(DataChannel* data_channel) = 0;
  36. // Disconnects from the transport signals.
  37. virtual void DisconnectDataChannel(DataChannel* data_channel) = 0;
  38. // Adds the data channel SID to the transport for SCTP.
  39. virtual void AddSctpDataStream(int sid) = 0;
  40. // Begins the closing procedure by sending an outgoing stream reset. Still
  41. // need to wait for callbacks to tell when this completes.
  42. virtual void RemoveSctpDataStream(int sid) = 0;
  43. // Returns true if the transport channel is ready to send data.
  44. virtual bool ReadyToSendData() const = 0;
  45. protected:
  46. virtual ~DataChannelProviderInterface() {}
  47. };
  48. struct InternalDataChannelInit : public DataChannelInit {
  49. enum OpenHandshakeRole { kOpener, kAcker, kNone };
  50. // The default role is kOpener because the default |negotiated| is false.
  51. InternalDataChannelInit() : open_handshake_role(kOpener) {}
  52. explicit InternalDataChannelInit(const DataChannelInit& base);
  53. OpenHandshakeRole open_handshake_role;
  54. };
  55. // Helper class to allocate unique IDs for SCTP DataChannels
  56. class SctpSidAllocator {
  57. public:
  58. // Gets the first unused odd/even id based on the DTLS role. If |role| is
  59. // SSL_CLIENT, the allocated id starts from 0 and takes even numbers;
  60. // otherwise, the id starts from 1 and takes odd numbers.
  61. // Returns false if no ID can be allocated.
  62. bool AllocateSid(rtc::SSLRole role, int* sid);
  63. // Attempts to reserve a specific sid. Returns false if it's unavailable.
  64. bool ReserveSid(int sid);
  65. // Indicates that |sid| isn't in use any more, and is thus available again.
  66. void ReleaseSid(int sid);
  67. private:
  68. // Checks if |sid| is available to be assigned to a new SCTP data channel.
  69. bool IsSidAvailable(int sid) const;
  70. std::set<int> used_sids_;
  71. };
  72. // DataChannel is a an implementation of the DataChannelInterface based on
  73. // libjingle's data engine. It provides an implementation of unreliable or
  74. // reliabledata channels. Currently this class is specifically designed to use
  75. // both RtpDataChannel and SctpTransport.
  76. // DataChannel states:
  77. // kConnecting: The channel has been created the transport might not yet be
  78. // ready.
  79. // kOpen: The channel have a local SSRC set by a call to UpdateSendSsrc
  80. // and a remote SSRC set by call to UpdateReceiveSsrc and the transport
  81. // has been writable once.
  82. // kClosing: DataChannelInterface::Close has been called or UpdateReceiveSsrc
  83. // has been called with SSRC==0
  84. // kClosed: Both UpdateReceiveSsrc and UpdateSendSsrc has been called with
  85. // SSRC==0.
  86. //
  87. // How the closing procedure works for SCTP:
  88. // 1. Alice calls Close(), state changes to kClosing.
  89. // 2. Alice finishes sending any queued data.
  90. // 3. Alice calls RemoveSctpDataStream, sends outgoing stream reset.
  91. // 4. Bob receives incoming stream reset; OnClosingProcedureStartedRemotely
  92. // called.
  93. // 5. Bob sends outgoing stream reset. 6. Alice receives incoming reset,
  94. // Bob receives acknowledgement. Both receive OnClosingProcedureComplete
  95. // callback and transition to kClosed.
  96. class DataChannel : public DataChannelInterface, public sigslot::has_slots<> {
  97. public:
  98. static rtc::scoped_refptr<DataChannel> Create(
  99. DataChannelProviderInterface* provider,
  100. cricket::DataChannelType dct,
  101. const std::string& label,
  102. const InternalDataChannelInit& config);
  103. static bool IsSctpLike(cricket::DataChannelType type);
  104. virtual void RegisterObserver(DataChannelObserver* observer);
  105. virtual void UnregisterObserver();
  106. virtual std::string label() const { return label_; }
  107. virtual bool reliable() const;
  108. virtual bool ordered() const { return config_.ordered; }
  109. // Backwards compatible accessors
  110. virtual uint16_t maxRetransmitTime() const {
  111. return config_.maxRetransmitTime ? *config_.maxRetransmitTime
  112. : static_cast<uint16_t>(-1);
  113. }
  114. virtual uint16_t maxRetransmits() const {
  115. return config_.maxRetransmits ? *config_.maxRetransmits
  116. : static_cast<uint16_t>(-1);
  117. }
  118. virtual absl::optional<int> maxPacketLifeTime() const {
  119. return config_.maxRetransmitTime;
  120. }
  121. virtual absl::optional<int> maxRetransmitsOpt() const {
  122. return config_.maxRetransmits;
  123. }
  124. virtual std::string protocol() const { return config_.protocol; }
  125. virtual bool negotiated() const { return config_.negotiated; }
  126. virtual int id() const { return config_.id; }
  127. virtual int internal_id() const { return internal_id_; }
  128. virtual uint64_t buffered_amount() const;
  129. virtual void Close();
  130. virtual DataState state() const { return state_; }
  131. virtual uint32_t messages_sent() const { return messages_sent_; }
  132. virtual uint64_t bytes_sent() const { return bytes_sent_; }
  133. virtual uint32_t messages_received() const { return messages_received_; }
  134. virtual uint64_t bytes_received() const { return bytes_received_; }
  135. virtual bool Send(const DataBuffer& buffer);
  136. // Close immediately, ignoring any queued data or closing procedure.
  137. // This is called for RTP data channels when SDP indicates a channel should
  138. // be removed, or SCTP data channels when the underlying SctpTransport is
  139. // being destroyed.
  140. // It is also called by the PeerConnection if SCTP ID assignment fails.
  141. void CloseAbruptly();
  142. // Called when the channel's ready to use. That can happen when the
  143. // underlying DataMediaChannel becomes ready, or when this channel is a new
  144. // stream on an existing DataMediaChannel, and we've finished negotiation.
  145. void OnChannelReady(bool writable);
  146. // Slots for provider to connect signals to.
  147. void OnDataReceived(const cricket::ReceiveDataParams& params,
  148. const rtc::CopyOnWriteBuffer& payload);
  149. /********************************************
  150. * The following methods are for SCTP only. *
  151. ********************************************/
  152. // Sets the SCTP sid and adds to transport layer if not set yet. Should only
  153. // be called once.
  154. void SetSctpSid(int sid);
  155. // The remote side started the closing procedure by resetting its outgoing
  156. // stream (our incoming stream). Sets state to kClosing.
  157. void OnClosingProcedureStartedRemotely(int sid);
  158. // The closing procedure is complete; both incoming and outgoing stream
  159. // resets are done and the channel can transition to kClosed. Called
  160. // asynchronously after RemoveSctpDataStream.
  161. void OnClosingProcedureComplete(int sid);
  162. // Called when the transport channel is created.
  163. // Only needs to be called for SCTP data channels.
  164. void OnTransportChannelCreated();
  165. // Called when the transport channel is destroyed.
  166. // This method makes sure the DataChannel is disconnected and changes state
  167. // to kClosed.
  168. void OnTransportChannelDestroyed();
  169. /*******************************************
  170. * The following methods are for RTP only. *
  171. *******************************************/
  172. // The remote peer requested that this channel should be closed.
  173. void RemotePeerRequestClose();
  174. // Set the SSRC this channel should use to send data on the
  175. // underlying data engine. |send_ssrc| == 0 means that the channel is no
  176. // longer part of the session negotiation.
  177. void SetSendSsrc(uint32_t send_ssrc);
  178. // Set the SSRC this channel should use to receive data from the
  179. // underlying data engine.
  180. void SetReceiveSsrc(uint32_t receive_ssrc);
  181. cricket::DataChannelType data_channel_type() const {
  182. return data_channel_type_;
  183. }
  184. // Emitted when state transitions to kOpen.
  185. sigslot::signal1<DataChannel*> SignalOpened;
  186. // Emitted when state transitions to kClosed.
  187. // In the case of SCTP channels, this signal can be used to tell when the
  188. // channel's sid is free.
  189. sigslot::signal1<DataChannel*> SignalClosed;
  190. // Reset the allocator for internal ID values for testing, so that
  191. // the internal IDs generated are predictable. Test only.
  192. static void ResetInternalIdAllocatorForTesting(int new_value);
  193. protected:
  194. DataChannel(DataChannelProviderInterface* client,
  195. cricket::DataChannelType dct,
  196. const std::string& label);
  197. virtual ~DataChannel();
  198. private:
  199. // A packet queue which tracks the total queued bytes. Queued packets are
  200. // owned by this class.
  201. class PacketQueue final {
  202. public:
  203. size_t byte_count() const { return byte_count_; }
  204. bool Empty() const;
  205. std::unique_ptr<DataBuffer> PopFront();
  206. void PushFront(std::unique_ptr<DataBuffer> packet);
  207. void PushBack(std::unique_ptr<DataBuffer> packet);
  208. void Clear();
  209. void Swap(PacketQueue* other);
  210. private:
  211. std::deque<std::unique_ptr<DataBuffer>> packets_;
  212. size_t byte_count_ = 0;
  213. };
  214. // The OPEN(_ACK) signaling state.
  215. enum HandshakeState {
  216. kHandshakeInit,
  217. kHandshakeShouldSendOpen,
  218. kHandshakeShouldSendAck,
  219. kHandshakeWaitingForAck,
  220. kHandshakeReady
  221. };
  222. bool Init(const InternalDataChannelInit& config);
  223. void UpdateState();
  224. void SetState(DataState state);
  225. void DisconnectFromProvider();
  226. void DeliverQueuedReceivedData();
  227. void SendQueuedDataMessages();
  228. bool SendDataMessage(const DataBuffer& buffer, bool queue_if_blocked);
  229. bool QueueSendDataMessage(const DataBuffer& buffer);
  230. void SendQueuedControlMessages();
  231. void QueueControlMessage(const rtc::CopyOnWriteBuffer& buffer);
  232. bool SendControlMessage(const rtc::CopyOnWriteBuffer& buffer);
  233. const int internal_id_;
  234. std::string label_;
  235. InternalDataChannelInit config_;
  236. DataChannelObserver* observer_;
  237. DataState state_;
  238. uint32_t messages_sent_;
  239. uint64_t bytes_sent_;
  240. uint32_t messages_received_;
  241. uint64_t bytes_received_;
  242. // Number of bytes of data that have been queued using Send(). Increased
  243. // before each transport send and decreased after each successful send.
  244. uint64_t buffered_amount_;
  245. cricket::DataChannelType data_channel_type_;
  246. DataChannelProviderInterface* provider_;
  247. HandshakeState handshake_state_;
  248. bool connected_to_provider_;
  249. bool send_ssrc_set_;
  250. bool receive_ssrc_set_;
  251. bool writable_;
  252. // Did we already start the graceful SCTP closing procedure?
  253. bool started_closing_procedure_ = false;
  254. uint32_t send_ssrc_;
  255. uint32_t receive_ssrc_;
  256. // Control messages that always have to get sent out before any queued
  257. // data.
  258. PacketQueue queued_control_data_;
  259. PacketQueue queued_received_data_;
  260. PacketQueue queued_send_data_;
  261. rtc::AsyncInvoker invoker_;
  262. };
  263. // Define proxy for DataChannelInterface.
  264. BEGIN_SIGNALING_PROXY_MAP(DataChannel)
  265. PROXY_SIGNALING_THREAD_DESTRUCTOR()
  266. PROXY_METHOD1(void, RegisterObserver, DataChannelObserver*)
  267. PROXY_METHOD0(void, UnregisterObserver)
  268. PROXY_CONSTMETHOD0(std::string, label)
  269. PROXY_CONSTMETHOD0(bool, reliable)
  270. PROXY_CONSTMETHOD0(bool, ordered)
  271. PROXY_CONSTMETHOD0(uint16_t, maxRetransmitTime)
  272. PROXY_CONSTMETHOD0(uint16_t, maxRetransmits)
  273. PROXY_CONSTMETHOD0(absl::optional<int>, maxRetransmitsOpt)
  274. PROXY_CONSTMETHOD0(absl::optional<int>, maxPacketLifeTime)
  275. PROXY_CONSTMETHOD0(std::string, protocol)
  276. PROXY_CONSTMETHOD0(bool, negotiated)
  277. PROXY_CONSTMETHOD0(int, id)
  278. PROXY_CONSTMETHOD0(DataState, state)
  279. PROXY_CONSTMETHOD0(uint32_t, messages_sent)
  280. PROXY_CONSTMETHOD0(uint64_t, bytes_sent)
  281. PROXY_CONSTMETHOD0(uint32_t, messages_received)
  282. PROXY_CONSTMETHOD0(uint64_t, bytes_received)
  283. PROXY_CONSTMETHOD0(uint64_t, buffered_amount)
  284. PROXY_METHOD0(void, Close)
  285. PROXY_METHOD1(bool, Send, const DataBuffer&)
  286. END_PROXY_MAP()
  287. } // namespace webrtc
  288. #endif // PC_DATA_CHANNEL_H_