sctp_data_channel.h 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  1. /*
  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. #ifndef PC_SCTP_DATA_CHANNEL_H_
  11. #define PC_SCTP_DATA_CHANNEL_H_
  12. #include <memory>
  13. #include <set>
  14. #include <string>
  15. #include "api/data_channel_interface.h"
  16. #include "api/priority.h"
  17. #include "api/scoped_refptr.h"
  18. #include "api/transport/data_channel_transport_interface.h"
  19. #include "media/base/media_channel.h"
  20. #include "pc/data_channel_utils.h"
  21. #include "rtc_base/ssl_stream_adapter.h" // For SSLRole
  22. #include "rtc_base/third_party/sigslot/sigslot.h"
  23. namespace webrtc {
  24. class SctpDataChannel;
  25. // TODO(deadbeef): Get rid of this and have SctpDataChannel depend on
  26. // SctpTransportInternal (pure virtual SctpTransport interface) instead.
  27. class SctpDataChannelProviderInterface {
  28. public:
  29. // Sends the data to the transport.
  30. virtual bool SendData(const cricket::SendDataParams& params,
  31. const rtc::CopyOnWriteBuffer& payload,
  32. cricket::SendDataResult* result) = 0;
  33. // Connects to the transport signals.
  34. virtual bool ConnectDataChannel(SctpDataChannel* data_channel) = 0;
  35. // Disconnects from the transport signals.
  36. virtual void DisconnectDataChannel(SctpDataChannel* data_channel) = 0;
  37. // Adds the data channel SID to the transport for SCTP.
  38. virtual void AddSctpDataStream(int sid) = 0;
  39. // Begins the closing procedure by sending an outgoing stream reset. Still
  40. // need to wait for callbacks to tell when this completes.
  41. virtual void RemoveSctpDataStream(int sid) = 0;
  42. // Returns true if the transport channel is ready to send data.
  43. virtual bool ReadyToSendData() const = 0;
  44. protected:
  45. virtual ~SctpDataChannelProviderInterface() {}
  46. };
  47. // TODO(tommi): Change to not inherit from DataChannelInit but to have it as
  48. // a const member. Block access to the 'id' member since it cannot be const.
  49. struct InternalDataChannelInit : public DataChannelInit {
  50. enum OpenHandshakeRole { kOpener, kAcker, kNone };
  51. // The default role is kOpener because the default |negotiated| is false.
  52. InternalDataChannelInit() : open_handshake_role(kOpener) {}
  53. explicit InternalDataChannelInit(const DataChannelInit& base);
  54. OpenHandshakeRole open_handshake_role;
  55. };
  56. // Helper class to allocate unique IDs for SCTP DataChannels.
  57. class SctpSidAllocator {
  58. public:
  59. // Gets the first unused odd/even id based on the DTLS role. If |role| is
  60. // SSL_CLIENT, the allocated id starts from 0 and takes even numbers;
  61. // otherwise, the id starts from 1 and takes odd numbers.
  62. // Returns false if no ID can be allocated.
  63. bool AllocateSid(rtc::SSLRole role, int* sid);
  64. // Attempts to reserve a specific sid. Returns false if it's unavailable.
  65. bool ReserveSid(int sid);
  66. // Indicates that |sid| isn't in use any more, and is thus available again.
  67. void ReleaseSid(int sid);
  68. private:
  69. // Checks if |sid| is available to be assigned to a new SCTP data channel.
  70. bool IsSidAvailable(int sid) const;
  71. std::set<int> used_sids_;
  72. };
  73. // SctpDataChannel is an implementation of the DataChannelInterface based on
  74. // SctpTransport. It provides an implementation of unreliable or
  75. // reliabledata channels.
  76. // DataChannel states:
  77. // kConnecting: The channel has been created the transport might not yet be
  78. // ready.
  79. // kOpen: The open handshake has been performed (if relevant) and the data
  80. // channel is able to send messages.
  81. // kClosing: DataChannelInterface::Close has been called, or the remote side
  82. // initiated the closing procedure, but the closing procedure has not
  83. // yet finished.
  84. // kClosed: The closing handshake is finished (possibly initiated from this,
  85. // side, possibly from the peer).
  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.
  94. // 6. Alice receives incoming reset, Bob receives acknowledgement. Both receive
  95. // OnClosingProcedureComplete callback and transition to kClosed.
  96. class SctpDataChannel : public DataChannelInterface,
  97. public sigslot::has_slots<> {
  98. public:
  99. static rtc::scoped_refptr<SctpDataChannel> Create(
  100. SctpDataChannelProviderInterface* provider,
  101. const std::string& label,
  102. const InternalDataChannelInit& config,
  103. rtc::Thread* signaling_thread,
  104. rtc::Thread* network_thread);
  105. // Instantiates an API proxy for a SctpDataChannel instance that will be
  106. // handed out to external callers.
  107. static rtc::scoped_refptr<DataChannelInterface> CreateProxy(
  108. rtc::scoped_refptr<SctpDataChannel> channel);
  109. void RegisterObserver(DataChannelObserver* observer) override;
  110. void UnregisterObserver() override;
  111. std::string label() const override { return label_; }
  112. bool reliable() const override;
  113. bool ordered() const override { return config_.ordered; }
  114. // Backwards compatible accessors
  115. uint16_t maxRetransmitTime() const override {
  116. return config_.maxRetransmitTime ? *config_.maxRetransmitTime
  117. : static_cast<uint16_t>(-1);
  118. }
  119. uint16_t maxRetransmits() const override {
  120. return config_.maxRetransmits ? *config_.maxRetransmits
  121. : static_cast<uint16_t>(-1);
  122. }
  123. absl::optional<int> maxPacketLifeTime() const override {
  124. return config_.maxRetransmitTime;
  125. }
  126. absl::optional<int> maxRetransmitsOpt() const override {
  127. return config_.maxRetransmits;
  128. }
  129. std::string protocol() const override { return config_.protocol; }
  130. bool negotiated() const override { return config_.negotiated; }
  131. int id() const override { return config_.id; }
  132. Priority priority() const override {
  133. return config_.priority ? *config_.priority : Priority::kLow;
  134. }
  135. virtual int internal_id() const { return internal_id_; }
  136. uint64_t buffered_amount() const override;
  137. void Close() override;
  138. DataState state() const override;
  139. RTCError error() const override;
  140. uint32_t messages_sent() const override;
  141. uint64_t bytes_sent() const override;
  142. uint32_t messages_received() const override;
  143. uint64_t bytes_received() const override;
  144. bool Send(const DataBuffer& buffer) override;
  145. // Close immediately, ignoring any queued data or closing procedure.
  146. // This is called when the underlying SctpTransport is being destroyed.
  147. // It is also called by the PeerConnection if SCTP ID assignment fails.
  148. void CloseAbruptlyWithError(RTCError error);
  149. // Specializations of CloseAbruptlyWithError
  150. void CloseAbruptlyWithDataChannelFailure(const std::string& message);
  151. void CloseAbruptlyWithSctpCauseCode(const std::string& message,
  152. uint16_t cause_code);
  153. // Slots for provider to connect signals to.
  154. //
  155. // TODO(deadbeef): Make these private once we're hooking up signals ourselves,
  156. // instead of relying on SctpDataChannelProviderInterface.
  157. // Called when the SctpTransport's ready to use. That can happen when we've
  158. // finished negotiation, or if the channel was created after negotiation has
  159. // already finished.
  160. void OnTransportReady(bool writable);
  161. void OnDataReceived(const cricket::ReceiveDataParams& params,
  162. const rtc::CopyOnWriteBuffer& payload);
  163. // Sets the SCTP sid and adds to transport layer if not set yet. Should only
  164. // be called once.
  165. void SetSctpSid(int sid);
  166. // The remote side started the closing procedure by resetting its outgoing
  167. // stream (our incoming stream). Sets state to kClosing.
  168. void OnClosingProcedureStartedRemotely(int sid);
  169. // The closing procedure is complete; both incoming and outgoing stream
  170. // resets are done and the channel can transition to kClosed. Called
  171. // asynchronously after RemoveSctpDataStream.
  172. void OnClosingProcedureComplete(int sid);
  173. // Called when the transport channel is created.
  174. // Only needs to be called for SCTP data channels.
  175. void OnTransportChannelCreated();
  176. // Called when the transport channel is unusable.
  177. // This method makes sure the DataChannel is disconnected and changes state
  178. // to kClosed.
  179. void OnTransportChannelClosed();
  180. DataChannelStats GetStats() const;
  181. // Emitted when state transitions to kOpen.
  182. sigslot::signal1<DataChannelInterface*> SignalOpened;
  183. // Emitted when state transitions to kClosed.
  184. // This signal can be used to tell when the channel's sid is free.
  185. sigslot::signal1<DataChannelInterface*> SignalClosed;
  186. // Reset the allocator for internal ID values for testing, so that
  187. // the internal IDs generated are predictable. Test only.
  188. static void ResetInternalIdAllocatorForTesting(int new_value);
  189. protected:
  190. SctpDataChannel(const InternalDataChannelInit& config,
  191. SctpDataChannelProviderInterface* client,
  192. const std::string& label,
  193. rtc::Thread* signaling_thread,
  194. rtc::Thread* network_thread);
  195. ~SctpDataChannel() override;
  196. private:
  197. // The OPEN(_ACK) signaling state.
  198. enum HandshakeState {
  199. kHandshakeInit,
  200. kHandshakeShouldSendOpen,
  201. kHandshakeShouldSendAck,
  202. kHandshakeWaitingForAck,
  203. kHandshakeReady
  204. };
  205. bool Init();
  206. void UpdateState();
  207. void SetState(DataState state);
  208. void DisconnectFromProvider();
  209. void DeliverQueuedReceivedData();
  210. void SendQueuedDataMessages();
  211. bool SendDataMessage(const DataBuffer& buffer, bool queue_if_blocked);
  212. bool QueueSendDataMessage(const DataBuffer& buffer);
  213. void SendQueuedControlMessages();
  214. void QueueControlMessage(const rtc::CopyOnWriteBuffer& buffer);
  215. bool SendControlMessage(const rtc::CopyOnWriteBuffer& buffer);
  216. rtc::Thread* const signaling_thread_;
  217. rtc::Thread* const network_thread_;
  218. const int internal_id_;
  219. const std::string label_;
  220. const InternalDataChannelInit config_;
  221. DataChannelObserver* observer_ RTC_GUARDED_BY(signaling_thread_) = nullptr;
  222. DataState state_ RTC_GUARDED_BY(signaling_thread_) = kConnecting;
  223. RTCError error_ RTC_GUARDED_BY(signaling_thread_);
  224. uint32_t messages_sent_ RTC_GUARDED_BY(signaling_thread_) = 0;
  225. uint64_t bytes_sent_ RTC_GUARDED_BY(signaling_thread_) = 0;
  226. uint32_t messages_received_ RTC_GUARDED_BY(signaling_thread_) = 0;
  227. uint64_t bytes_received_ RTC_GUARDED_BY(signaling_thread_) = 0;
  228. // Number of bytes of data that have been queued using Send(). Increased
  229. // before each transport send and decreased after each successful send.
  230. uint64_t buffered_amount_ RTC_GUARDED_BY(signaling_thread_) = 0;
  231. SctpDataChannelProviderInterface* const provider_
  232. RTC_GUARDED_BY(signaling_thread_);
  233. HandshakeState handshake_state_ RTC_GUARDED_BY(signaling_thread_) =
  234. kHandshakeInit;
  235. bool connected_to_provider_ RTC_GUARDED_BY(signaling_thread_) = false;
  236. bool writable_ RTC_GUARDED_BY(signaling_thread_) = false;
  237. // Did we already start the graceful SCTP closing procedure?
  238. bool started_closing_procedure_ RTC_GUARDED_BY(signaling_thread_) = false;
  239. // Control messages that always have to get sent out before any queued
  240. // data.
  241. PacketQueue queued_control_data_ RTC_GUARDED_BY(signaling_thread_);
  242. PacketQueue queued_received_data_ RTC_GUARDED_BY(signaling_thread_);
  243. PacketQueue queued_send_data_ RTC_GUARDED_BY(signaling_thread_);
  244. };
  245. } // namespace webrtc
  246. #endif // PC_SCTP_DATA_CHANNEL_H_