blob: 1ee267924a4c046d14d620a4d0964df7029af92a [file] [log] [blame]
ossu7bb87ee2017-01-23 04:56:25 -08001/*
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
Steve Anton10542f22019-01-11 09:11:00 -080011#ifndef PC_DATA_CHANNEL_H_
12#define PC_DATA_CHANNEL_H_
ossu7bb87ee2017-01-23 04:56:25 -080013
14#include <deque>
Steve Anton944c7552018-12-13 14:19:10 -080015#include <memory>
ossu7bb87ee2017-01-23 04:56:25 -080016#include <set>
17#include <string>
18
Steve Anton10542f22019-01-11 09:11:00 -080019#include "api/data_channel_interface.h"
Harald Alvestrandfd5ae7f2020-05-16 08:37:49 +020020#include "api/priority.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020021#include "api/proxy.h"
Mirko Bonadeid9708072019-01-25 20:26:48 +010022#include "api/scoped_refptr.h"
Steve Anton10542f22019-01-11 09:11:00 -080023#include "media/base/media_channel.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020024#include "pc/channel.h"
Steve Anton10542f22019-01-11 09:11:00 -080025#include "rtc_base/async_invoker.h"
Artem Titove41c4332018-07-25 15:04:28 +020026#include "rtc_base/third_party/sigslot/sigslot.h"
ossu7bb87ee2017-01-23 04:56:25 -080027
28namespace webrtc {
29
30class DataChannel;
31
Taylor Brandstettercdd05f02018-05-31 13:23:32 -070032// TODO(deadbeef): Once RTP data channels go away, get rid of this and have
33// DataChannel depend on SctpTransportInternal (pure virtual SctpTransport
34// interface) instead.
ossu7bb87ee2017-01-23 04:56:25 -080035class DataChannelProviderInterface {
36 public:
37 // Sends the data to the transport.
38 virtual bool SendData(const cricket::SendDataParams& params,
39 const rtc::CopyOnWriteBuffer& payload,
40 cricket::SendDataResult* result) = 0;
41 // Connects to the transport signals.
42 virtual bool ConnectDataChannel(DataChannel* data_channel) = 0;
43 // Disconnects from the transport signals.
44 virtual void DisconnectDataChannel(DataChannel* data_channel) = 0;
45 // Adds the data channel SID to the transport for SCTP.
46 virtual void AddSctpDataStream(int sid) = 0;
Taylor Brandstettercdd05f02018-05-31 13:23:32 -070047 // Begins the closing procedure by sending an outgoing stream reset. Still
48 // need to wait for callbacks to tell when this completes.
ossu7bb87ee2017-01-23 04:56:25 -080049 virtual void RemoveSctpDataStream(int sid) = 0;
50 // Returns true if the transport channel is ready to send data.
51 virtual bool ReadyToSendData() const = 0;
52
53 protected:
54 virtual ~DataChannelProviderInterface() {}
55};
56
Tomas Gunnarsson0ca13d92020-06-10 12:17:50 +020057// TODO(tommi): Change to not inherit from DataChannelInit but to have it as
58// a const member. Block access to the 'id' member since it cannot be const.
ossu7bb87ee2017-01-23 04:56:25 -080059struct InternalDataChannelInit : public DataChannelInit {
Yves Gerey665174f2018-06-19 15:03:05 +020060 enum OpenHandshakeRole { kOpener, kAcker, kNone };
ossu7bb87ee2017-01-23 04:56:25 -080061 // The default role is kOpener because the default |negotiated| is false.
62 InternalDataChannelInit() : open_handshake_role(kOpener) {}
Harald Alvestrandf3736ed2019-04-08 13:09:30 +020063 explicit InternalDataChannelInit(const DataChannelInit& base);
ossu7bb87ee2017-01-23 04:56:25 -080064 OpenHandshakeRole open_handshake_role;
65};
66
67// Helper class to allocate unique IDs for SCTP DataChannels
68class SctpSidAllocator {
69 public:
70 // Gets the first unused odd/even id based on the DTLS role. If |role| is
71 // SSL_CLIENT, the allocated id starts from 0 and takes even numbers;
72 // otherwise, the id starts from 1 and takes odd numbers.
Taylor Brandstettercdd05f02018-05-31 13:23:32 -070073 // Returns false if no ID can be allocated.
ossu7bb87ee2017-01-23 04:56:25 -080074 bool AllocateSid(rtc::SSLRole role, int* sid);
75
76 // Attempts to reserve a specific sid. Returns false if it's unavailable.
77 bool ReserveSid(int sid);
78
79 // Indicates that |sid| isn't in use any more, and is thus available again.
80 void ReleaseSid(int sid);
81
82 private:
83 // Checks if |sid| is available to be assigned to a new SCTP data channel.
84 bool IsSidAvailable(int sid) const;
85
86 std::set<int> used_sids_;
87};
88
Philipp Hancke1a497562020-05-26 19:12:31 +020089// DataChannel is an implementation of the DataChannelInterface based on
ossu7bb87ee2017-01-23 04:56:25 -080090// libjingle's data engine. It provides an implementation of unreliable or
91// reliabledata channels. Currently this class is specifically designed to use
Taylor Brandstettercdd05f02018-05-31 13:23:32 -070092// both RtpDataChannel and SctpTransport.
ossu7bb87ee2017-01-23 04:56:25 -080093
94// DataChannel states:
95// kConnecting: The channel has been created the transport might not yet be
96// ready.
97// kOpen: The channel have a local SSRC set by a call to UpdateSendSsrc
98// and a remote SSRC set by call to UpdateReceiveSsrc and the transport
99// has been writable once.
100// kClosing: DataChannelInterface::Close has been called or UpdateReceiveSsrc
101// has been called with SSRC==0
102// kClosed: Both UpdateReceiveSsrc and UpdateSendSsrc has been called with
103// SSRC==0.
Taylor Brandstettercdd05f02018-05-31 13:23:32 -0700104//
105// How the closing procedure works for SCTP:
106// 1. Alice calls Close(), state changes to kClosing.
107// 2. Alice finishes sending any queued data.
108// 3. Alice calls RemoveSctpDataStream, sends outgoing stream reset.
109// 4. Bob receives incoming stream reset; OnClosingProcedureStartedRemotely
110// called.
111// 5. Bob sends outgoing stream reset. 6. Alice receives incoming reset,
112// Bob receives acknowledgement. Both receive OnClosingProcedureComplete
113// callback and transition to kClosed.
Steve Anton044a04d2018-08-31 13:51:19 -0700114class DataChannel : public DataChannelInterface, public sigslot::has_slots<> {
ossu7bb87ee2017-01-23 04:56:25 -0800115 public:
116 static rtc::scoped_refptr<DataChannel> Create(
117 DataChannelProviderInterface* provider,
118 cricket::DataChannelType dct,
119 const std::string& label,
120 const InternalDataChannelInit& config);
121
Bjorn Mellem175aa2e2018-11-08 11:23:22 -0800122 static bool IsSctpLike(cricket::DataChannelType type);
123
ossu7bb87ee2017-01-23 04:56:25 -0800124 virtual void RegisterObserver(DataChannelObserver* observer);
125 virtual void UnregisterObserver();
126
127 virtual std::string label() const { return label_; }
128 virtual bool reliable() const;
129 virtual bool ordered() const { return config_.ordered; }
Harald Alvestrandf3736ed2019-04-08 13:09:30 +0200130 // Backwards compatible accessors
ossu7bb87ee2017-01-23 04:56:25 -0800131 virtual uint16_t maxRetransmitTime() const {
Harald Alvestrandf3736ed2019-04-08 13:09:30 +0200132 return config_.maxRetransmitTime ? *config_.maxRetransmitTime
133 : static_cast<uint16_t>(-1);
134 }
135 virtual uint16_t maxRetransmits() const {
136 return config_.maxRetransmits ? *config_.maxRetransmits
137 : static_cast<uint16_t>(-1);
138 }
139 virtual absl::optional<int> maxPacketLifeTime() const {
ossu7bb87ee2017-01-23 04:56:25 -0800140 return config_.maxRetransmitTime;
141 }
Harald Alvestrandf3736ed2019-04-08 13:09:30 +0200142 virtual absl::optional<int> maxRetransmitsOpt() const {
143 return config_.maxRetransmits;
144 }
ossu7bb87ee2017-01-23 04:56:25 -0800145 virtual std::string protocol() const { return config_.protocol; }
146 virtual bool negotiated() const { return config_.negotiated; }
147 virtual int id() const { return config_.id; }
Harald Alvestrandfd5ae7f2020-05-16 08:37:49 +0200148 virtual Priority priority() const {
149 return config_.priority ? *config_.priority : Priority::kLow;
150 }
Harald Alvestrand928e7a32019-07-31 07:16:45 -0400151 virtual int internal_id() const { return internal_id_; }
ossu7bb87ee2017-01-23 04:56:25 -0800152 virtual uint64_t buffered_amount() const;
153 virtual void Close();
154 virtual DataState state() const { return state_; }
Harald Alvestranddfbfb462019-12-08 05:55:43 +0100155 virtual RTCError error() const;
ossu7bb87ee2017-01-23 04:56:25 -0800156 virtual uint32_t messages_sent() const { return messages_sent_; }
157 virtual uint64_t bytes_sent() const { return bytes_sent_; }
158 virtual uint32_t messages_received() const { return messages_received_; }
159 virtual uint64_t bytes_received() const { return bytes_received_; }
160 virtual bool Send(const DataBuffer& buffer);
161
Harald Alvestrand1f928d32019-03-28 11:29:38 +0100162 // Close immediately, ignoring any queued data or closing procedure.
163 // This is called for RTP data channels when SDP indicates a channel should
164 // be removed, or SCTP data channels when the underlying SctpTransport is
165 // being destroyed.
166 // It is also called by the PeerConnection if SCTP ID assignment fails.
Harald Alvestranddfbfb462019-12-08 05:55:43 +0100167 void CloseAbruptlyWithError(RTCError error);
168 // Specializations of CloseAbruptlyWithError
169 void CloseAbruptlyWithDataChannelFailure(const std::string& message);
170 void CloseAbruptlyWithSctpCauseCode(const std::string& message,
171 uint16_t cause_code);
Harald Alvestrand1f928d32019-03-28 11:29:38 +0100172
ossu7bb87ee2017-01-23 04:56:25 -0800173 // Called when the channel's ready to use. That can happen when the
174 // underlying DataMediaChannel becomes ready, or when this channel is a new
175 // stream on an existing DataMediaChannel, and we've finished negotiation.
176 void OnChannelReady(bool writable);
177
178 // Slots for provider to connect signals to.
179 void OnDataReceived(const cricket::ReceiveDataParams& params,
180 const rtc::CopyOnWriteBuffer& payload);
ossu7bb87ee2017-01-23 04:56:25 -0800181
Taylor Brandstettercdd05f02018-05-31 13:23:32 -0700182 /********************************************
183 * The following methods are for SCTP only. *
184 ********************************************/
ossu7bb87ee2017-01-23 04:56:25 -0800185
186 // Sets the SCTP sid and adds to transport layer if not set yet. Should only
187 // be called once.
188 void SetSctpSid(int sid);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -0700189 // The remote side started the closing procedure by resetting its outgoing
190 // stream (our incoming stream). Sets state to kClosing.
191 void OnClosingProcedureStartedRemotely(int sid);
192 // The closing procedure is complete; both incoming and outgoing stream
193 // resets are done and the channel can transition to kClosed. Called
194 // asynchronously after RemoveSctpDataStream.
195 void OnClosingProcedureComplete(int sid);
ossu7bb87ee2017-01-23 04:56:25 -0800196 // Called when the transport channel is created.
197 // Only needs to be called for SCTP data channels.
198 void OnTransportChannelCreated();
Harald Alvestrand408cb4b2019-11-16 12:09:08 +0100199 // Called when the transport channel is unusable.
ossu7bb87ee2017-01-23 04:56:25 -0800200 // This method makes sure the DataChannel is disconnected and changes state
201 // to kClosed.
Harald Alvestrand408cb4b2019-11-16 12:09:08 +0100202 void OnTransportChannelClosed();
ossu7bb87ee2017-01-23 04:56:25 -0800203
Taylor Brandstettercdd05f02018-05-31 13:23:32 -0700204 /*******************************************
205 * The following methods are for RTP only. *
206 *******************************************/
ossu7bb87ee2017-01-23 04:56:25 -0800207
Taylor Brandstettercdd05f02018-05-31 13:23:32 -0700208 // The remote peer requested that this channel should be closed.
209 void RemotePeerRequestClose();
ossu7bb87ee2017-01-23 04:56:25 -0800210 // Set the SSRC this channel should use to send data on the
211 // underlying data engine. |send_ssrc| == 0 means that the channel is no
212 // longer part of the session negotiation.
213 void SetSendSsrc(uint32_t send_ssrc);
214 // Set the SSRC this channel should use to receive data from the
215 // underlying data engine.
216 void SetReceiveSsrc(uint32_t receive_ssrc);
217
218 cricket::DataChannelType data_channel_type() const {
219 return data_channel_type_;
220 }
221
222 // Emitted when state transitions to kOpen.
223 sigslot::signal1<DataChannel*> SignalOpened;
224 // Emitted when state transitions to kClosed.
225 // In the case of SCTP channels, this signal can be used to tell when the
226 // channel's sid is free.
227 sigslot::signal1<DataChannel*> SignalClosed;
228
Harald Alvestrand928e7a32019-07-31 07:16:45 -0400229 // Reset the allocator for internal ID values for testing, so that
230 // the internal IDs generated are predictable. Test only.
231 static void ResetInternalIdAllocatorForTesting(int new_value);
232
ossu7bb87ee2017-01-23 04:56:25 -0800233 protected:
Tomas Gunnarsson0ca13d92020-06-10 12:17:50 +0200234 DataChannel(const InternalDataChannelInit& config,
235 DataChannelProviderInterface* client,
ossu7bb87ee2017-01-23 04:56:25 -0800236 cricket::DataChannelType dct,
237 const std::string& label);
238 virtual ~DataChannel();
239
240 private:
241 // A packet queue which tracks the total queued bytes. Queued packets are
242 // owned by this class.
Steve Anton944c7552018-12-13 14:19:10 -0800243 class PacketQueue final {
ossu7bb87ee2017-01-23 04:56:25 -0800244 public:
Yves Gerey665174f2018-06-19 15:03:05 +0200245 size_t byte_count() const { return byte_count_; }
ossu7bb87ee2017-01-23 04:56:25 -0800246
247 bool Empty() const;
248
Steve Anton944c7552018-12-13 14:19:10 -0800249 std::unique_ptr<DataBuffer> PopFront();
ossu7bb87ee2017-01-23 04:56:25 -0800250
Steve Anton944c7552018-12-13 14:19:10 -0800251 void PushFront(std::unique_ptr<DataBuffer> packet);
252 void PushBack(std::unique_ptr<DataBuffer> packet);
ossu7bb87ee2017-01-23 04:56:25 -0800253
254 void Clear();
255
256 void Swap(PacketQueue* other);
257
258 private:
Steve Anton944c7552018-12-13 14:19:10 -0800259 std::deque<std::unique_ptr<DataBuffer>> packets_;
260 size_t byte_count_ = 0;
ossu7bb87ee2017-01-23 04:56:25 -0800261 };
262
263 // The OPEN(_ACK) signaling state.
264 enum HandshakeState {
265 kHandshakeInit,
266 kHandshakeShouldSendOpen,
267 kHandshakeShouldSendAck,
268 kHandshakeWaitingForAck,
269 kHandshakeReady
270 };
271
Tomas Gunnarsson0ca13d92020-06-10 12:17:50 +0200272 bool Init();
ossu7bb87ee2017-01-23 04:56:25 -0800273 void UpdateState();
274 void SetState(DataState state);
275 void DisconnectFromProvider();
276
277 void DeliverQueuedReceivedData();
278
279 void SendQueuedDataMessages();
280 bool SendDataMessage(const DataBuffer& buffer, bool queue_if_blocked);
281 bool QueueSendDataMessage(const DataBuffer& buffer);
282
283 void SendQueuedControlMessages();
284 void QueueControlMessage(const rtc::CopyOnWriteBuffer& buffer);
285 bool SendControlMessage(const rtc::CopyOnWriteBuffer& buffer);
286
Harald Alvestrand928e7a32019-07-31 07:16:45 -0400287 const int internal_id_;
Tomas Gunnarsson0ca13d92020-06-10 12:17:50 +0200288 const std::string label_;
289 const InternalDataChannelInit config_;
ossu7bb87ee2017-01-23 04:56:25 -0800290 DataChannelObserver* observer_;
291 DataState state_;
Harald Alvestranddfbfb462019-12-08 05:55:43 +0100292 RTCError error_;
ossu7bb87ee2017-01-23 04:56:25 -0800293 uint32_t messages_sent_;
294 uint64_t bytes_sent_;
295 uint32_t messages_received_;
296 uint64_t bytes_received_;
Marina Cioceae448a3f2019-03-04 15:52:21 +0100297 // Number of bytes of data that have been queued using Send(). Increased
298 // before each transport send and decreased after each successful send.
299 uint64_t buffered_amount_;
Tomas Gunnarsson0ca13d92020-06-10 12:17:50 +0200300 const cricket::DataChannelType data_channel_type_;
ossu7bb87ee2017-01-23 04:56:25 -0800301 DataChannelProviderInterface* provider_;
302 HandshakeState handshake_state_;
303 bool connected_to_provider_;
304 bool send_ssrc_set_;
305 bool receive_ssrc_set_;
306 bool writable_;
Taylor Brandstettercdd05f02018-05-31 13:23:32 -0700307 // Did we already start the graceful SCTP closing procedure?
308 bool started_closing_procedure_ = false;
ossu7bb87ee2017-01-23 04:56:25 -0800309 uint32_t send_ssrc_;
310 uint32_t receive_ssrc_;
311 // Control messages that always have to get sent out before any queued
312 // data.
313 PacketQueue queued_control_data_;
314 PacketQueue queued_received_data_;
315 PacketQueue queued_send_data_;
Steve Anton044a04d2018-08-31 13:51:19 -0700316 rtc::AsyncInvoker invoker_;
ossu7bb87ee2017-01-23 04:56:25 -0800317};
318
319// Define proxy for DataChannelInterface.
320BEGIN_SIGNALING_PROXY_MAP(DataChannel)
Yves Gerey665174f2018-06-19 15:03:05 +0200321PROXY_SIGNALING_THREAD_DESTRUCTOR()
322PROXY_METHOD1(void, RegisterObserver, DataChannelObserver*)
323PROXY_METHOD0(void, UnregisterObserver)
Tomas Gunnarsson0ca13d92020-06-10 12:17:50 +0200324BYPASS_PROXY_CONSTMETHOD0(std::string, label)
325BYPASS_PROXY_CONSTMETHOD0(bool, reliable)
326BYPASS_PROXY_CONSTMETHOD0(bool, ordered)
327BYPASS_PROXY_CONSTMETHOD0(uint16_t, maxRetransmitTime)
328BYPASS_PROXY_CONSTMETHOD0(uint16_t, maxRetransmits)
329BYPASS_PROXY_CONSTMETHOD0(absl::optional<int>, maxRetransmitsOpt)
330BYPASS_PROXY_CONSTMETHOD0(absl::optional<int>, maxPacketLifeTime)
331BYPASS_PROXY_CONSTMETHOD0(std::string, protocol)
332BYPASS_PROXY_CONSTMETHOD0(bool, negotiated)
333// Can't bypass the proxy since the id may change.
Yves Gerey665174f2018-06-19 15:03:05 +0200334PROXY_CONSTMETHOD0(int, id)
Tomas Gunnarsson0ca13d92020-06-10 12:17:50 +0200335BYPASS_PROXY_CONSTMETHOD0(Priority, priority)
Yves Gerey665174f2018-06-19 15:03:05 +0200336PROXY_CONSTMETHOD0(DataState, state)
Harald Alvestranddfbfb462019-12-08 05:55:43 +0100337PROXY_CONSTMETHOD0(RTCError, error)
Yves Gerey665174f2018-06-19 15:03:05 +0200338PROXY_CONSTMETHOD0(uint32_t, messages_sent)
339PROXY_CONSTMETHOD0(uint64_t, bytes_sent)
340PROXY_CONSTMETHOD0(uint32_t, messages_received)
341PROXY_CONSTMETHOD0(uint64_t, bytes_received)
342PROXY_CONSTMETHOD0(uint64_t, buffered_amount)
343PROXY_METHOD0(void, Close)
344PROXY_METHOD1(bool, Send, const DataBuffer&)
ossu7bb87ee2017-01-23 04:56:25 -0800345END_PROXY_MAP()
346
347} // namespace webrtc
348
Steve Anton10542f22019-01-11 09:11:00 -0800349#endif // PC_DATA_CHANNEL_H_