blob: c1de7c7a7ae6ba36ca4746c018c09f89fca01c8a [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"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020020#include "api/proxy.h"
Mirko Bonadeid9708072019-01-25 20:26:48 +010021#include "api/scoped_refptr.h"
Steve Anton10542f22019-01-11 09:11:00 -080022#include "media/base/media_channel.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020023#include "pc/channel.h"
Steve Anton10542f22019-01-11 09:11:00 -080024#include "rtc_base/async_invoker.h"
Artem Titove41c4332018-07-25 15:04:28 +020025#include "rtc_base/third_party/sigslot/sigslot.h"
ossu7bb87ee2017-01-23 04:56:25 -080026
27namespace webrtc {
28
29class DataChannel;
30
Taylor Brandstettercdd05f02018-05-31 13:23:32 -070031// TODO(deadbeef): Once RTP data channels go away, get rid of this and have
32// DataChannel depend on SctpTransportInternal (pure virtual SctpTransport
33// interface) instead.
ossu7bb87ee2017-01-23 04:56:25 -080034class DataChannelProviderInterface {
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(DataChannel* data_channel) = 0;
42 // Disconnects from the transport signals.
43 virtual void DisconnectDataChannel(DataChannel* data_channel) = 0;
44 // Adds the data channel SID to the transport for SCTP.
45 virtual void AddSctpDataStream(int sid) = 0;
Taylor Brandstettercdd05f02018-05-31 13:23:32 -070046 // Begins the closing procedure by sending an outgoing stream reset. Still
47 // need to wait for callbacks to tell when this completes.
ossu7bb87ee2017-01-23 04:56:25 -080048 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:
53 virtual ~DataChannelProviderInterface() {}
54};
55
56struct InternalDataChannelInit : public DataChannelInit {
Yves Gerey665174f2018-06-19 15:03:05 +020057 enum OpenHandshakeRole { kOpener, kAcker, kNone };
ossu7bb87ee2017-01-23 04:56:25 -080058 // The default role is kOpener because the default |negotiated| is false.
59 InternalDataChannelInit() : open_handshake_role(kOpener) {}
Harald Alvestrandf3736ed2019-04-08 13:09:30 +020060 explicit InternalDataChannelInit(const DataChannelInit& base);
ossu7bb87ee2017-01-23 04:56:25 -080061 OpenHandshakeRole open_handshake_role;
62};
63
64// Helper class to allocate unique IDs for SCTP DataChannels
65class SctpSidAllocator {
66 public:
67 // Gets the first unused odd/even id based on the DTLS role. If |role| is
68 // SSL_CLIENT, the allocated id starts from 0 and takes even numbers;
69 // otherwise, the id starts from 1 and takes odd numbers.
Taylor Brandstettercdd05f02018-05-31 13:23:32 -070070 // Returns false if no ID can be allocated.
ossu7bb87ee2017-01-23 04:56:25 -080071 bool AllocateSid(rtc::SSLRole role, int* sid);
72
73 // Attempts to reserve a specific sid. Returns false if it's unavailable.
74 bool ReserveSid(int sid);
75
76 // Indicates that |sid| isn't in use any more, and is thus available again.
77 void ReleaseSid(int sid);
78
79 private:
80 // Checks if |sid| is available to be assigned to a new SCTP data channel.
81 bool IsSidAvailable(int sid) const;
82
83 std::set<int> used_sids_;
84};
85
86// DataChannel is a an implementation of the DataChannelInterface based on
87// libjingle's data engine. It provides an implementation of unreliable or
88// reliabledata channels. Currently this class is specifically designed to use
Taylor Brandstettercdd05f02018-05-31 13:23:32 -070089// both RtpDataChannel and SctpTransport.
ossu7bb87ee2017-01-23 04:56:25 -080090
91// DataChannel states:
92// kConnecting: The channel has been created the transport might not yet be
93// ready.
94// kOpen: The channel have a local SSRC set by a call to UpdateSendSsrc
95// and a remote SSRC set by call to UpdateReceiveSsrc and the transport
96// has been writable once.
97// kClosing: DataChannelInterface::Close has been called or UpdateReceiveSsrc
98// has been called with SSRC==0
99// kClosed: Both UpdateReceiveSsrc and UpdateSendSsrc has been called with
100// SSRC==0.
Taylor Brandstettercdd05f02018-05-31 13:23:32 -0700101//
102// How the closing procedure works for SCTP:
103// 1. Alice calls Close(), state changes to kClosing.
104// 2. Alice finishes sending any queued data.
105// 3. Alice calls RemoveSctpDataStream, sends outgoing stream reset.
106// 4. Bob receives incoming stream reset; OnClosingProcedureStartedRemotely
107// called.
108// 5. Bob sends outgoing stream reset. 6. Alice receives incoming reset,
109// Bob receives acknowledgement. Both receive OnClosingProcedureComplete
110// callback and transition to kClosed.
Steve Anton044a04d2018-08-31 13:51:19 -0700111class DataChannel : public DataChannelInterface, public sigslot::has_slots<> {
ossu7bb87ee2017-01-23 04:56:25 -0800112 public:
113 static rtc::scoped_refptr<DataChannel> Create(
114 DataChannelProviderInterface* provider,
115 cricket::DataChannelType dct,
116 const std::string& label,
117 const InternalDataChannelInit& config);
118
Bjorn Mellem175aa2e2018-11-08 11:23:22 -0800119 static bool IsSctpLike(cricket::DataChannelType type);
120
ossu7bb87ee2017-01-23 04:56:25 -0800121 virtual void RegisterObserver(DataChannelObserver* observer);
122 virtual void UnregisterObserver();
123
124 virtual std::string label() const { return label_; }
125 virtual bool reliable() const;
126 virtual bool ordered() const { return config_.ordered; }
Harald Alvestrandf3736ed2019-04-08 13:09:30 +0200127 // Backwards compatible accessors
ossu7bb87ee2017-01-23 04:56:25 -0800128 virtual uint16_t maxRetransmitTime() const {
Harald Alvestrandf3736ed2019-04-08 13:09:30 +0200129 return config_.maxRetransmitTime ? *config_.maxRetransmitTime
130 : static_cast<uint16_t>(-1);
131 }
132 virtual uint16_t maxRetransmits() const {
133 return config_.maxRetransmits ? *config_.maxRetransmits
134 : static_cast<uint16_t>(-1);
135 }
136 virtual absl::optional<int> maxPacketLifeTime() const {
ossu7bb87ee2017-01-23 04:56:25 -0800137 return config_.maxRetransmitTime;
138 }
Harald Alvestrandf3736ed2019-04-08 13:09:30 +0200139 virtual absl::optional<int> maxRetransmitsOpt() const {
140 return config_.maxRetransmits;
141 }
ossu7bb87ee2017-01-23 04:56:25 -0800142 virtual std::string protocol() const { return config_.protocol; }
143 virtual bool negotiated() const { return config_.negotiated; }
144 virtual int id() const { return config_.id; }
Harald Alvestrand928e7a32019-07-31 07:16:45 -0400145 virtual int internal_id() const { return internal_id_; }
ossu7bb87ee2017-01-23 04:56:25 -0800146 virtual uint64_t buffered_amount() const;
147 virtual void Close();
148 virtual DataState state() const { return state_; }
Harald Alvestranddfbfb462019-12-08 05:55:43 +0100149 virtual RTCError error() const;
ossu7bb87ee2017-01-23 04:56:25 -0800150 virtual uint32_t messages_sent() const { return messages_sent_; }
151 virtual uint64_t bytes_sent() const { return bytes_sent_; }
152 virtual uint32_t messages_received() const { return messages_received_; }
153 virtual uint64_t bytes_received() const { return bytes_received_; }
154 virtual bool Send(const DataBuffer& buffer);
155
Harald Alvestrand1f928d32019-03-28 11:29:38 +0100156 // 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.
Harald Alvestranddfbfb462019-12-08 05:55:43 +0100161 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);
Harald Alvestrand1f928d32019-03-28 11:29:38 +0100166
ossu7bb87ee2017-01-23 04:56:25 -0800167 // Called when the channel's ready to use. That can happen when the
168 // underlying DataMediaChannel becomes ready, or when this channel is a new
169 // stream on an existing DataMediaChannel, and we've finished negotiation.
170 void OnChannelReady(bool writable);
171
172 // Slots for provider to connect signals to.
173 void OnDataReceived(const cricket::ReceiveDataParams& params,
174 const rtc::CopyOnWriteBuffer& payload);
ossu7bb87ee2017-01-23 04:56:25 -0800175
Taylor Brandstettercdd05f02018-05-31 13:23:32 -0700176 /********************************************
177 * The following methods are for SCTP only. *
178 ********************************************/
ossu7bb87ee2017-01-23 04:56:25 -0800179
180 // Sets the SCTP sid and adds to transport layer if not set yet. Should only
181 // be called once.
182 void SetSctpSid(int sid);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -0700183 // The remote side started the closing procedure by resetting its outgoing
184 // stream (our incoming stream). Sets state to kClosing.
185 void OnClosingProcedureStartedRemotely(int sid);
186 // The closing procedure is complete; both incoming and outgoing stream
187 // resets are done and the channel can transition to kClosed. Called
188 // asynchronously after RemoveSctpDataStream.
189 void OnClosingProcedureComplete(int sid);
ossu7bb87ee2017-01-23 04:56:25 -0800190 // Called when the transport channel is created.
191 // Only needs to be called for SCTP data channels.
192 void OnTransportChannelCreated();
Harald Alvestrand408cb4b2019-11-16 12:09:08 +0100193 // Called when the transport channel is unusable.
ossu7bb87ee2017-01-23 04:56:25 -0800194 // This method makes sure the DataChannel is disconnected and changes state
195 // to kClosed.
Harald Alvestrand408cb4b2019-11-16 12:09:08 +0100196 void OnTransportChannelClosed();
ossu7bb87ee2017-01-23 04:56:25 -0800197
Taylor Brandstettercdd05f02018-05-31 13:23:32 -0700198 /*******************************************
199 * The following methods are for RTP only. *
200 *******************************************/
ossu7bb87ee2017-01-23 04:56:25 -0800201
Taylor Brandstettercdd05f02018-05-31 13:23:32 -0700202 // The remote peer requested that this channel should be closed.
203 void RemotePeerRequestClose();
ossu7bb87ee2017-01-23 04:56:25 -0800204 // Set the SSRC this channel should use to send data on the
205 // underlying data engine. |send_ssrc| == 0 means that the channel is no
206 // longer part of the session negotiation.
207 void SetSendSsrc(uint32_t send_ssrc);
208 // Set the SSRC this channel should use to receive data from the
209 // underlying data engine.
210 void SetReceiveSsrc(uint32_t receive_ssrc);
211
212 cricket::DataChannelType data_channel_type() const {
213 return data_channel_type_;
214 }
215
216 // Emitted when state transitions to kOpen.
217 sigslot::signal1<DataChannel*> SignalOpened;
218 // Emitted when state transitions to kClosed.
219 // In the case of SCTP channels, this signal can be used to tell when the
220 // channel's sid is free.
221 sigslot::signal1<DataChannel*> SignalClosed;
222
Harald Alvestrand928e7a32019-07-31 07:16:45 -0400223 // Reset the allocator for internal ID values for testing, so that
224 // the internal IDs generated are predictable. Test only.
225 static void ResetInternalIdAllocatorForTesting(int new_value);
226
ossu7bb87ee2017-01-23 04:56:25 -0800227 protected:
228 DataChannel(DataChannelProviderInterface* client,
229 cricket::DataChannelType dct,
230 const std::string& label);
231 virtual ~DataChannel();
232
233 private:
234 // A packet queue which tracks the total queued bytes. Queued packets are
235 // owned by this class.
Steve Anton944c7552018-12-13 14:19:10 -0800236 class PacketQueue final {
ossu7bb87ee2017-01-23 04:56:25 -0800237 public:
Yves Gerey665174f2018-06-19 15:03:05 +0200238 size_t byte_count() const { return byte_count_; }
ossu7bb87ee2017-01-23 04:56:25 -0800239
240 bool Empty() const;
241
Steve Anton944c7552018-12-13 14:19:10 -0800242 std::unique_ptr<DataBuffer> PopFront();
ossu7bb87ee2017-01-23 04:56:25 -0800243
Steve Anton944c7552018-12-13 14:19:10 -0800244 void PushFront(std::unique_ptr<DataBuffer> packet);
245 void PushBack(std::unique_ptr<DataBuffer> packet);
ossu7bb87ee2017-01-23 04:56:25 -0800246
247 void Clear();
248
249 void Swap(PacketQueue* other);
250
251 private:
Steve Anton944c7552018-12-13 14:19:10 -0800252 std::deque<std::unique_ptr<DataBuffer>> packets_;
253 size_t byte_count_ = 0;
ossu7bb87ee2017-01-23 04:56:25 -0800254 };
255
256 // The OPEN(_ACK) signaling state.
257 enum HandshakeState {
258 kHandshakeInit,
259 kHandshakeShouldSendOpen,
260 kHandshakeShouldSendAck,
261 kHandshakeWaitingForAck,
262 kHandshakeReady
263 };
264
265 bool Init(const InternalDataChannelInit& config);
ossu7bb87ee2017-01-23 04:56:25 -0800266 void UpdateState();
267 void SetState(DataState state);
268 void DisconnectFromProvider();
269
270 void DeliverQueuedReceivedData();
271
272 void SendQueuedDataMessages();
273 bool SendDataMessage(const DataBuffer& buffer, bool queue_if_blocked);
274 bool QueueSendDataMessage(const DataBuffer& buffer);
275
276 void SendQueuedControlMessages();
277 void QueueControlMessage(const rtc::CopyOnWriteBuffer& buffer);
278 bool SendControlMessage(const rtc::CopyOnWriteBuffer& buffer);
279
Harald Alvestrand928e7a32019-07-31 07:16:45 -0400280 const int internal_id_;
ossu7bb87ee2017-01-23 04:56:25 -0800281 std::string label_;
282 InternalDataChannelInit config_;
283 DataChannelObserver* observer_;
284 DataState state_;
Harald Alvestranddfbfb462019-12-08 05:55:43 +0100285 RTCError error_;
ossu7bb87ee2017-01-23 04:56:25 -0800286 uint32_t messages_sent_;
287 uint64_t bytes_sent_;
288 uint32_t messages_received_;
289 uint64_t bytes_received_;
Marina Cioceae448a3f2019-03-04 15:52:21 +0100290 // Number of bytes of data that have been queued using Send(). Increased
291 // before each transport send and decreased after each successful send.
292 uint64_t buffered_amount_;
ossu7bb87ee2017-01-23 04:56:25 -0800293 cricket::DataChannelType data_channel_type_;
294 DataChannelProviderInterface* provider_;
295 HandshakeState handshake_state_;
296 bool connected_to_provider_;
297 bool send_ssrc_set_;
298 bool receive_ssrc_set_;
299 bool writable_;
Taylor Brandstettercdd05f02018-05-31 13:23:32 -0700300 // Did we already start the graceful SCTP closing procedure?
301 bool started_closing_procedure_ = false;
ossu7bb87ee2017-01-23 04:56:25 -0800302 uint32_t send_ssrc_;
303 uint32_t receive_ssrc_;
304 // Control messages that always have to get sent out before any queued
305 // data.
306 PacketQueue queued_control_data_;
307 PacketQueue queued_received_data_;
308 PacketQueue queued_send_data_;
Steve Anton044a04d2018-08-31 13:51:19 -0700309 rtc::AsyncInvoker invoker_;
ossu7bb87ee2017-01-23 04:56:25 -0800310};
311
312// Define proxy for DataChannelInterface.
313BEGIN_SIGNALING_PROXY_MAP(DataChannel)
Yves Gerey665174f2018-06-19 15:03:05 +0200314PROXY_SIGNALING_THREAD_DESTRUCTOR()
315PROXY_METHOD1(void, RegisterObserver, DataChannelObserver*)
316PROXY_METHOD0(void, UnregisterObserver)
317PROXY_CONSTMETHOD0(std::string, label)
318PROXY_CONSTMETHOD0(bool, reliable)
319PROXY_CONSTMETHOD0(bool, ordered)
320PROXY_CONSTMETHOD0(uint16_t, maxRetransmitTime)
321PROXY_CONSTMETHOD0(uint16_t, maxRetransmits)
Harald Alvestrandf3736ed2019-04-08 13:09:30 +0200322PROXY_CONSTMETHOD0(absl::optional<int>, maxRetransmitsOpt)
323PROXY_CONSTMETHOD0(absl::optional<int>, maxPacketLifeTime)
Yves Gerey665174f2018-06-19 15:03:05 +0200324PROXY_CONSTMETHOD0(std::string, protocol)
325PROXY_CONSTMETHOD0(bool, negotiated)
326PROXY_CONSTMETHOD0(int, id)
327PROXY_CONSTMETHOD0(DataState, state)
Harald Alvestranddfbfb462019-12-08 05:55:43 +0100328PROXY_CONSTMETHOD0(RTCError, error)
Yves Gerey665174f2018-06-19 15:03:05 +0200329PROXY_CONSTMETHOD0(uint32_t, messages_sent)
330PROXY_CONSTMETHOD0(uint64_t, bytes_sent)
331PROXY_CONSTMETHOD0(uint32_t, messages_received)
332PROXY_CONSTMETHOD0(uint64_t, bytes_received)
333PROXY_CONSTMETHOD0(uint64_t, buffered_amount)
334PROXY_METHOD0(void, Close)
335PROXY_METHOD1(bool, Send, const DataBuffer&)
ossu7bb87ee2017-01-23 04:56:25 -0800336END_PROXY_MAP()
337
338} // namespace webrtc
339
Steve Anton10542f22019-01-11 09:11:00 -0800340#endif // PC_DATA_CHANNEL_H_