blob: 728226cc35d47cb186549ee458d2df24fd06157b [file] [log] [blame]
ossu7bb87ee2017-01-23 12:56:251/*
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 17:11:0011#ifndef PC_DATA_CHANNEL_H_
12#define PC_DATA_CHANNEL_H_
ossu7bb87ee2017-01-23 12:56:2513
14#include <deque>
Steve Anton944c7552018-12-13 22:19:1015#include <memory>
ossu7bb87ee2017-01-23 12:56:2516#include <set>
17#include <string>
18
Steve Anton10542f22019-01-11 17:11:0019#include "api/data_channel_interface.h"
Mirko Bonadei92ea95e2017-09-15 04:47:3120#include "api/proxy.h"
Mirko Bonadeid9708072019-01-25 19:26:4821#include "api/scoped_refptr.h"
Steve Anton10542f22019-01-11 17:11:0022#include "media/base/media_channel.h"
Mirko Bonadei92ea95e2017-09-15 04:47:3123#include "pc/channel.h"
Steve Anton10542f22019-01-11 17:11:0024#include "rtc_base/async_invoker.h"
Artem Titove41c4332018-07-25 13:04:2825#include "rtc_base/third_party/sigslot/sigslot.h"
ossu7bb87ee2017-01-23 12:56:2526
27namespace webrtc {
28
29class DataChannel;
30
Taylor Brandstettercdd05f02018-05-31 20:23:3231// 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 12:56:2534class 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 20:23:3246 // 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 12:56:2548 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 13:03:0557 enum OpenHandshakeRole { kOpener, kAcker, kNone };
ossu7bb87ee2017-01-23 12:56:2558 // The default role is kOpener because the default |negotiated| is false.
59 InternalDataChannelInit() : open_handshake_role(kOpener) {}
Harald Alvestrandf3736ed2019-04-08 11:09:3060 explicit InternalDataChannelInit(const DataChannelInit& base);
ossu7bb87ee2017-01-23 12:56:2561 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 20:23:3270 // Returns false if no ID can be allocated.
ossu7bb87ee2017-01-23 12:56:2571 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 20:23:3289// both RtpDataChannel and SctpTransport.
ossu7bb87ee2017-01-23 12:56:2590
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 20:23:32101//
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 20:51:19111class DataChannel : public DataChannelInterface, public sigslot::has_slots<> {
ossu7bb87ee2017-01-23 12:56:25112 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 19:23:22119 static bool IsSctpLike(cricket::DataChannelType type);
120
ossu7bb87ee2017-01-23 12:56:25121 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 11:09:30127 // Backwards compatible accessors
ossu7bb87ee2017-01-23 12:56:25128 virtual uint16_t maxRetransmitTime() const {
Harald Alvestrandf3736ed2019-04-08 11:09:30129 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 12:56:25137 return config_.maxRetransmitTime;
138 }
Harald Alvestrandf3736ed2019-04-08 11:09:30139 virtual absl::optional<int> maxRetransmitsOpt() const {
140 return config_.maxRetransmits;
141 }
ossu7bb87ee2017-01-23 12:56:25142 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 11:16:45145 virtual int internal_id() const { return internal_id_; }
ossu7bb87ee2017-01-23 12:56:25146 virtual uint64_t buffered_amount() const;
147 virtual void Close();
148 virtual DataState state() const { return state_; }
149 virtual uint32_t messages_sent() const { return messages_sent_; }
150 virtual uint64_t bytes_sent() const { return bytes_sent_; }
151 virtual uint32_t messages_received() const { return messages_received_; }
152 virtual uint64_t bytes_received() const { return bytes_received_; }
153 virtual bool Send(const DataBuffer& buffer);
154
Harald Alvestrand1f928d32019-03-28 10:29:38155 // Close immediately, ignoring any queued data or closing procedure.
156 // This is called for RTP data channels when SDP indicates a channel should
157 // be removed, or SCTP data channels when the underlying SctpTransport is
158 // being destroyed.
159 // It is also called by the PeerConnection if SCTP ID assignment fails.
160 void CloseAbruptly();
161
ossu7bb87ee2017-01-23 12:56:25162 // Called when the channel's ready to use. That can happen when the
163 // underlying DataMediaChannel becomes ready, or when this channel is a new
164 // stream on an existing DataMediaChannel, and we've finished negotiation.
165 void OnChannelReady(bool writable);
166
167 // Slots for provider to connect signals to.
168 void OnDataReceived(const cricket::ReceiveDataParams& params,
169 const rtc::CopyOnWriteBuffer& payload);
ossu7bb87ee2017-01-23 12:56:25170
Taylor Brandstettercdd05f02018-05-31 20:23:32171 /********************************************
172 * The following methods are for SCTP only. *
173 ********************************************/
ossu7bb87ee2017-01-23 12:56:25174
175 // Sets the SCTP sid and adds to transport layer if not set yet. Should only
176 // be called once.
177 void SetSctpSid(int sid);
Taylor Brandstettercdd05f02018-05-31 20:23:32178 // The remote side started the closing procedure by resetting its outgoing
179 // stream (our incoming stream). Sets state to kClosing.
180 void OnClosingProcedureStartedRemotely(int sid);
181 // The closing procedure is complete; both incoming and outgoing stream
182 // resets are done and the channel can transition to kClosed. Called
183 // asynchronously after RemoveSctpDataStream.
184 void OnClosingProcedureComplete(int sid);
ossu7bb87ee2017-01-23 12:56:25185 // Called when the transport channel is created.
186 // Only needs to be called for SCTP data channels.
187 void OnTransportChannelCreated();
188 // Called when the transport channel is destroyed.
189 // This method makes sure the DataChannel is disconnected and changes state
190 // to kClosed.
191 void OnTransportChannelDestroyed();
192
Taylor Brandstettercdd05f02018-05-31 20:23:32193 /*******************************************
194 * The following methods are for RTP only. *
195 *******************************************/
ossu7bb87ee2017-01-23 12:56:25196
Taylor Brandstettercdd05f02018-05-31 20:23:32197 // The remote peer requested that this channel should be closed.
198 void RemotePeerRequestClose();
ossu7bb87ee2017-01-23 12:56:25199 // 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
207 cricket::DataChannelType data_channel_type() const {
208 return data_channel_type_;
209 }
210
211 // Emitted when state transitions to kOpen.
212 sigslot::signal1<DataChannel*> SignalOpened;
213 // Emitted when state transitions to kClosed.
214 // In the case of SCTP channels, this signal can be used to tell when the
215 // channel's sid is free.
216 sigslot::signal1<DataChannel*> SignalClosed;
217
Harald Alvestrand928e7a32019-07-31 11:16:45218 // Reset the allocator for internal ID values for testing, so that
219 // the internal IDs generated are predictable. Test only.
220 static void ResetInternalIdAllocatorForTesting(int new_value);
221
ossu7bb87ee2017-01-23 12:56:25222 protected:
223 DataChannel(DataChannelProviderInterface* client,
224 cricket::DataChannelType dct,
225 const std::string& label);
226 virtual ~DataChannel();
227
228 private:
229 // A packet queue which tracks the total queued bytes. Queued packets are
230 // owned by this class.
Steve Anton944c7552018-12-13 22:19:10231 class PacketQueue final {
ossu7bb87ee2017-01-23 12:56:25232 public:
Yves Gerey665174f2018-06-19 13:03:05233 size_t byte_count() const { return byte_count_; }
ossu7bb87ee2017-01-23 12:56:25234
235 bool Empty() const;
236
Steve Anton944c7552018-12-13 22:19:10237 std::unique_ptr<DataBuffer> PopFront();
ossu7bb87ee2017-01-23 12:56:25238
Steve Anton944c7552018-12-13 22:19:10239 void PushFront(std::unique_ptr<DataBuffer> packet);
240 void PushBack(std::unique_ptr<DataBuffer> packet);
ossu7bb87ee2017-01-23 12:56:25241
242 void Clear();
243
244 void Swap(PacketQueue* other);
245
246 private:
Steve Anton944c7552018-12-13 22:19:10247 std::deque<std::unique_ptr<DataBuffer>> packets_;
248 size_t byte_count_ = 0;
ossu7bb87ee2017-01-23 12:56:25249 };
250
251 // The OPEN(_ACK) signaling state.
252 enum HandshakeState {
253 kHandshakeInit,
254 kHandshakeShouldSendOpen,
255 kHandshakeShouldSendAck,
256 kHandshakeWaitingForAck,
257 kHandshakeReady
258 };
259
260 bool Init(const InternalDataChannelInit& config);
ossu7bb87ee2017-01-23 12:56:25261 void UpdateState();
262 void SetState(DataState state);
263 void DisconnectFromProvider();
264
265 void DeliverQueuedReceivedData();
266
267 void SendQueuedDataMessages();
268 bool SendDataMessage(const DataBuffer& buffer, bool queue_if_blocked);
269 bool QueueSendDataMessage(const DataBuffer& buffer);
270
271 void SendQueuedControlMessages();
272 void QueueControlMessage(const rtc::CopyOnWriteBuffer& buffer);
273 bool SendControlMessage(const rtc::CopyOnWriteBuffer& buffer);
274
Harald Alvestrand928e7a32019-07-31 11:16:45275 const int internal_id_;
ossu7bb87ee2017-01-23 12:56:25276 std::string label_;
277 InternalDataChannelInit config_;
278 DataChannelObserver* observer_;
279 DataState state_;
280 uint32_t messages_sent_;
281 uint64_t bytes_sent_;
282 uint32_t messages_received_;
283 uint64_t bytes_received_;
Marina Cioceae448a3f2019-03-04 14:52:21284 // Number of bytes of data that have been queued using Send(). Increased
285 // before each transport send and decreased after each successful send.
286 uint64_t buffered_amount_;
ossu7bb87ee2017-01-23 12:56:25287 cricket::DataChannelType data_channel_type_;
288 DataChannelProviderInterface* provider_;
289 HandshakeState handshake_state_;
290 bool connected_to_provider_;
291 bool send_ssrc_set_;
292 bool receive_ssrc_set_;
293 bool writable_;
Taylor Brandstettercdd05f02018-05-31 20:23:32294 // Did we already start the graceful SCTP closing procedure?
295 bool started_closing_procedure_ = false;
ossu7bb87ee2017-01-23 12:56:25296 uint32_t send_ssrc_;
297 uint32_t receive_ssrc_;
298 // Control messages that always have to get sent out before any queued
299 // data.
300 PacketQueue queued_control_data_;
301 PacketQueue queued_received_data_;
302 PacketQueue queued_send_data_;
Steve Anton044a04d2018-08-31 20:51:19303 rtc::AsyncInvoker invoker_;
ossu7bb87ee2017-01-23 12:56:25304};
305
306// Define proxy for DataChannelInterface.
307BEGIN_SIGNALING_PROXY_MAP(DataChannel)
Yves Gerey665174f2018-06-19 13:03:05308PROXY_SIGNALING_THREAD_DESTRUCTOR()
309PROXY_METHOD1(void, RegisterObserver, DataChannelObserver*)
310PROXY_METHOD0(void, UnregisterObserver)
311PROXY_CONSTMETHOD0(std::string, label)
312PROXY_CONSTMETHOD0(bool, reliable)
313PROXY_CONSTMETHOD0(bool, ordered)
314PROXY_CONSTMETHOD0(uint16_t, maxRetransmitTime)
315PROXY_CONSTMETHOD0(uint16_t, maxRetransmits)
Harald Alvestrandf3736ed2019-04-08 11:09:30316PROXY_CONSTMETHOD0(absl::optional<int>, maxRetransmitsOpt)
317PROXY_CONSTMETHOD0(absl::optional<int>, maxPacketLifeTime)
Yves Gerey665174f2018-06-19 13:03:05318PROXY_CONSTMETHOD0(std::string, protocol)
319PROXY_CONSTMETHOD0(bool, negotiated)
320PROXY_CONSTMETHOD0(int, id)
321PROXY_CONSTMETHOD0(DataState, state)
322PROXY_CONSTMETHOD0(uint32_t, messages_sent)
323PROXY_CONSTMETHOD0(uint64_t, bytes_sent)
324PROXY_CONSTMETHOD0(uint32_t, messages_received)
325PROXY_CONSTMETHOD0(uint64_t, bytes_received)
326PROXY_CONSTMETHOD0(uint64_t, buffered_amount)
327PROXY_METHOD0(void, Close)
328PROXY_METHOD1(bool, Send, const DataBuffer&)
ossu7bb87ee2017-01-23 12:56:25329END_PROXY_MAP()
330
331} // namespace webrtc
332
Steve Anton10542f22019-01-11 17:11:00333#endif // PC_DATA_CHANNEL_H_