blob: bd7ea1a3d962c3723b5327ff0c598811a4a1efe0 [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
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020011#ifndef PC_DATACHANNEL_H_
12#define PC_DATACHANNEL_H_
ossu7bb87ee2017-01-23 04:56:25 -080013
14#include <deque>
15#include <set>
16#include <string>
17
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020018#include "api/datachannelinterface.h"
19#include "api/proxy.h"
20#include "media/base/mediachannel.h"
21#include "pc/channel.h"
22#include "rtc_base/messagehandler.h"
23#include "rtc_base/scoped_ref_ptr.h"
24#include "rtc_base/sigslot.h"
ossu7bb87ee2017-01-23 04:56:25 -080025
26namespace webrtc {
27
28class DataChannel;
29
Taylor Brandstettercdd05f02018-05-31 13:23:32 -070030// TODO(deadbeef): Once RTP data channels go away, get rid of this and have
31// DataChannel depend on SctpTransportInternal (pure virtual SctpTransport
32// interface) instead.
ossu7bb87ee2017-01-23 04:56:25 -080033class DataChannelProviderInterface {
34 public:
35 // Sends the data to the transport.
36 virtual bool SendData(const cricket::SendDataParams& params,
37 const rtc::CopyOnWriteBuffer& payload,
38 cricket::SendDataResult* result) = 0;
39 // Connects to the transport signals.
40 virtual bool ConnectDataChannel(DataChannel* data_channel) = 0;
41 // Disconnects from the transport signals.
42 virtual void DisconnectDataChannel(DataChannel* data_channel) = 0;
43 // Adds the data channel SID to the transport for SCTP.
44 virtual void AddSctpDataStream(int sid) = 0;
Taylor Brandstettercdd05f02018-05-31 13:23:32 -070045 // Begins the closing procedure by sending an outgoing stream reset. Still
46 // need to wait for callbacks to tell when this completes.
ossu7bb87ee2017-01-23 04:56:25 -080047 virtual void RemoveSctpDataStream(int sid) = 0;
48 // Returns true if the transport channel is ready to send data.
49 virtual bool ReadyToSendData() const = 0;
50
51 protected:
52 virtual ~DataChannelProviderInterface() {}
53};
54
55struct InternalDataChannelInit : public DataChannelInit {
56 enum OpenHandshakeRole {
57 kOpener,
58 kAcker,
59 kNone
60 };
61 // The default role is kOpener because the default |negotiated| is false.
62 InternalDataChannelInit() : open_handshake_role(kOpener) {}
63 explicit InternalDataChannelInit(const DataChannelInit& base)
64 : DataChannelInit(base), open_handshake_role(kOpener) {
65 // If the channel is externally negotiated, do not send the OPEN message.
66 if (base.negotiated) {
67 open_handshake_role = kNone;
68 }
69 }
70
71 OpenHandshakeRole open_handshake_role;
72};
73
74// Helper class to allocate unique IDs for SCTP DataChannels
75class SctpSidAllocator {
76 public:
77 // Gets the first unused odd/even id based on the DTLS role. If |role| is
78 // SSL_CLIENT, the allocated id starts from 0 and takes even numbers;
79 // otherwise, the id starts from 1 and takes odd numbers.
Taylor Brandstettercdd05f02018-05-31 13:23:32 -070080 // Returns false if no ID can be allocated.
ossu7bb87ee2017-01-23 04:56:25 -080081 bool AllocateSid(rtc::SSLRole role, int* sid);
82
83 // Attempts to reserve a specific sid. Returns false if it's unavailable.
84 bool ReserveSid(int sid);
85
86 // Indicates that |sid| isn't in use any more, and is thus available again.
87 void ReleaseSid(int sid);
88
89 private:
90 // Checks if |sid| is available to be assigned to a new SCTP data channel.
91 bool IsSidAvailable(int sid) const;
92
93 std::set<int> used_sids_;
94};
95
96// DataChannel is a an implementation of the DataChannelInterface based on
97// libjingle's data engine. It provides an implementation of unreliable or
98// reliabledata channels. Currently this class is specifically designed to use
Taylor Brandstettercdd05f02018-05-31 13:23:32 -070099// both RtpDataChannel and SctpTransport.
ossu7bb87ee2017-01-23 04:56:25 -0800100
101// DataChannel states:
102// kConnecting: The channel has been created the transport might not yet be
103// ready.
104// kOpen: The channel have a local SSRC set by a call to UpdateSendSsrc
105// and a remote SSRC set by call to UpdateReceiveSsrc and the transport
106// has been writable once.
107// kClosing: DataChannelInterface::Close has been called or UpdateReceiveSsrc
108// has been called with SSRC==0
109// kClosed: Both UpdateReceiveSsrc and UpdateSendSsrc has been called with
110// SSRC==0.
Taylor Brandstettercdd05f02018-05-31 13:23:32 -0700111//
112// How the closing procedure works for SCTP:
113// 1. Alice calls Close(), state changes to kClosing.
114// 2. Alice finishes sending any queued data.
115// 3. Alice calls RemoveSctpDataStream, sends outgoing stream reset.
116// 4. Bob receives incoming stream reset; OnClosingProcedureStartedRemotely
117// called.
118// 5. Bob sends outgoing stream reset. 6. Alice receives incoming reset,
119// Bob receives acknowledgement. Both receive OnClosingProcedureComplete
120// callback and transition to kClosed.
ossu7bb87ee2017-01-23 04:56:25 -0800121class DataChannel : public DataChannelInterface,
122 public sigslot::has_slots<>,
123 public rtc::MessageHandler {
124 public:
125 static rtc::scoped_refptr<DataChannel> Create(
126 DataChannelProviderInterface* provider,
127 cricket::DataChannelType dct,
128 const std::string& label,
129 const InternalDataChannelInit& config);
130
131 virtual void RegisterObserver(DataChannelObserver* observer);
132 virtual void UnregisterObserver();
133
134 virtual std::string label() const { return label_; }
135 virtual bool reliable() const;
136 virtual bool ordered() const { return config_.ordered; }
137 virtual uint16_t maxRetransmitTime() const {
138 return config_.maxRetransmitTime;
139 }
140 virtual uint16_t maxRetransmits() const { return config_.maxRetransmits; }
141 virtual std::string protocol() const { return config_.protocol; }
142 virtual bool negotiated() const { return config_.negotiated; }
143 virtual int id() const { return config_.id; }
144 virtual uint64_t buffered_amount() const;
145 virtual void Close();
146 virtual DataState state() const { return state_; }
147 virtual uint32_t messages_sent() const { return messages_sent_; }
148 virtual uint64_t bytes_sent() const { return bytes_sent_; }
149 virtual uint32_t messages_received() const { return messages_received_; }
150 virtual uint64_t bytes_received() const { return bytes_received_; }
151 virtual bool Send(const DataBuffer& buffer);
152
153 // rtc::MessageHandler override.
154 virtual void OnMessage(rtc::Message* msg);
155
156 // Called when the channel's ready to use. That can happen when the
157 // underlying DataMediaChannel becomes ready, or when this channel is a new
158 // stream on an existing DataMediaChannel, and we've finished negotiation.
159 void OnChannelReady(bool writable);
160
161 // Slots for provider to connect signals to.
162 void OnDataReceived(const cricket::ReceiveDataParams& params,
163 const rtc::CopyOnWriteBuffer& payload);
ossu7bb87ee2017-01-23 04:56:25 -0800164
Taylor Brandstettercdd05f02018-05-31 13:23:32 -0700165 /********************************************
166 * The following methods are for SCTP only. *
167 ********************************************/
ossu7bb87ee2017-01-23 04:56:25 -0800168
169 // Sets the SCTP sid and adds to transport layer if not set yet. Should only
170 // be called once.
171 void SetSctpSid(int sid);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -0700172 // The remote side started the closing procedure by resetting its outgoing
173 // stream (our incoming stream). Sets state to kClosing.
174 void OnClosingProcedureStartedRemotely(int sid);
175 // The closing procedure is complete; both incoming and outgoing stream
176 // resets are done and the channel can transition to kClosed. Called
177 // asynchronously after RemoveSctpDataStream.
178 void OnClosingProcedureComplete(int sid);
ossu7bb87ee2017-01-23 04:56:25 -0800179 // Called when the transport channel is created.
180 // Only needs to be called for SCTP data channels.
181 void OnTransportChannelCreated();
182 // Called when the transport channel is destroyed.
183 // This method makes sure the DataChannel is disconnected and changes state
184 // to kClosed.
185 void OnTransportChannelDestroyed();
186
Taylor Brandstettercdd05f02018-05-31 13:23:32 -0700187 /*******************************************
188 * The following methods are for RTP only. *
189 *******************************************/
ossu7bb87ee2017-01-23 04:56:25 -0800190
Taylor Brandstettercdd05f02018-05-31 13:23:32 -0700191 // The remote peer requested that this channel should be closed.
192 void RemotePeerRequestClose();
ossu7bb87ee2017-01-23 04:56:25 -0800193 // Set the SSRC this channel should use to send data on the
194 // underlying data engine. |send_ssrc| == 0 means that the channel is no
195 // longer part of the session negotiation.
196 void SetSendSsrc(uint32_t send_ssrc);
197 // Set the SSRC this channel should use to receive data from the
198 // underlying data engine.
199 void SetReceiveSsrc(uint32_t receive_ssrc);
200
201 cricket::DataChannelType data_channel_type() const {
202 return data_channel_type_;
203 }
204
205 // Emitted when state transitions to kOpen.
206 sigslot::signal1<DataChannel*> SignalOpened;
207 // Emitted when state transitions to kClosed.
208 // In the case of SCTP channels, this signal can be used to tell when the
209 // channel's sid is free.
210 sigslot::signal1<DataChannel*> SignalClosed;
211
212 protected:
213 DataChannel(DataChannelProviderInterface* client,
214 cricket::DataChannelType dct,
215 const std::string& label);
216 virtual ~DataChannel();
217
218 private:
219 // A packet queue which tracks the total queued bytes. Queued packets are
220 // owned by this class.
221 class PacketQueue {
222 public:
223 PacketQueue();
224 ~PacketQueue();
225
226 size_t byte_count() const {
227 return byte_count_;
228 }
229
230 bool Empty() const;
231
232 DataBuffer* Front();
233
234 void Pop();
235
236 void Push(DataBuffer* packet);
237
238 void Clear();
239
240 void Swap(PacketQueue* other);
241
242 private:
243 std::deque<DataBuffer*> packets_;
244 size_t byte_count_;
245 };
246
247 // The OPEN(_ACK) signaling state.
248 enum HandshakeState {
249 kHandshakeInit,
250 kHandshakeShouldSendOpen,
251 kHandshakeShouldSendAck,
252 kHandshakeWaitingForAck,
253 kHandshakeReady
254 };
255
256 bool Init(const InternalDataChannelInit& config);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -0700257 // Close immediately, ignoring any queued data or closing procedure.
258 // This is called for RTP data channels when SDP indicates a channel should
259 // be removed, or SCTP data channels when the underlying SctpTransport is
260 // being destroyed.
261 void CloseAbruptly();
ossu7bb87ee2017-01-23 04:56:25 -0800262 void UpdateState();
263 void SetState(DataState state);
264 void DisconnectFromProvider();
265
266 void DeliverQueuedReceivedData();
267
268 void SendQueuedDataMessages();
269 bool SendDataMessage(const DataBuffer& buffer, bool queue_if_blocked);
270 bool QueueSendDataMessage(const DataBuffer& buffer);
271
272 void SendQueuedControlMessages();
273 void QueueControlMessage(const rtc::CopyOnWriteBuffer& buffer);
274 bool SendControlMessage(const rtc::CopyOnWriteBuffer& buffer);
275
276 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_;
284 cricket::DataChannelType data_channel_type_;
285 DataChannelProviderInterface* provider_;
286 HandshakeState handshake_state_;
287 bool connected_to_provider_;
288 bool send_ssrc_set_;
289 bool receive_ssrc_set_;
290 bool writable_;
Taylor Brandstettercdd05f02018-05-31 13:23:32 -0700291 // Did we already start the graceful SCTP closing procedure?
292 bool started_closing_procedure_ = false;
ossu7bb87ee2017-01-23 04:56:25 -0800293 uint32_t send_ssrc_;
294 uint32_t receive_ssrc_;
295 // Control messages that always have to get sent out before any queued
296 // data.
297 PacketQueue queued_control_data_;
298 PacketQueue queued_received_data_;
299 PacketQueue queued_send_data_;
300};
301
302// Define proxy for DataChannelInterface.
303BEGIN_SIGNALING_PROXY_MAP(DataChannel)
304 PROXY_SIGNALING_THREAD_DESTRUCTOR()
305 PROXY_METHOD1(void, RegisterObserver, DataChannelObserver*)
306 PROXY_METHOD0(void, UnregisterObserver)
307 PROXY_CONSTMETHOD0(std::string, label)
308 PROXY_CONSTMETHOD0(bool, reliable)
309 PROXY_CONSTMETHOD0(bool, ordered)
310 PROXY_CONSTMETHOD0(uint16_t, maxRetransmitTime)
311 PROXY_CONSTMETHOD0(uint16_t, maxRetransmits)
312 PROXY_CONSTMETHOD0(std::string, protocol)
313 PROXY_CONSTMETHOD0(bool, negotiated)
314 PROXY_CONSTMETHOD0(int, id)
315 PROXY_CONSTMETHOD0(DataState, state)
316 PROXY_CONSTMETHOD0(uint32_t, messages_sent)
317 PROXY_CONSTMETHOD0(uint64_t, bytes_sent)
318 PROXY_CONSTMETHOD0(uint32_t, messages_received)
319 PROXY_CONSTMETHOD0(uint64_t, bytes_received)
320 PROXY_CONSTMETHOD0(uint64_t, buffered_amount)
321 PROXY_METHOD0(void, Close)
322 PROXY_METHOD1(bool, Send, const DataBuffer&)
323END_PROXY_MAP()
324
325} // namespace webrtc
326
Mirko Bonadei92ea95e2017-09-15 06:47:31 +0200327#endif // PC_DATACHANNEL_H_