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