data_channel.h 14 KB

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