blob: f4f573276c11711ce64db03a71c7c2ab5018afa8 [file] [log] [blame]
mikescarlett9bc517f2016-04-30 01:30:551/*
2 * Copyright 2016 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#include "webrtc/api/quicdatachannel.h"
12
13#include "webrtc/base/bind.h"
14#include "webrtc/base/bytebuffer.h"
15#include "webrtc/base/copyonwritebuffer.h"
16#include "webrtc/base/logging.h"
17#include "webrtc/p2p/quic/quictransportchannel.h"
18#include "webrtc/p2p/quic/reliablequicstream.h"
19
20namespace webrtc {
21
22void WriteQuicDataChannelMessageHeader(int data_channel_id,
23 uint64_t message_id,
24 rtc::CopyOnWriteBuffer* header) {
25 RTC_DCHECK(header);
26 // 64-bit varints require at most 10 bytes (7*10 == 70), and 32-bit varints
27 // require at most 5 bytes (7*5 == 35).
28 size_t max_length = 15;
29 rtc::ByteBufferWriter byte_buffer(nullptr, max_length,
30 rtc::ByteBuffer::ByteOrder::ORDER_HOST);
31 byte_buffer.WriteUVarint(data_channel_id);
32 byte_buffer.WriteUVarint(message_id);
33 header->SetData(byte_buffer.Data(), byte_buffer.Length());
34}
35
36bool ParseQuicDataMessageHeader(const char* data,
37 size_t len,
38 int* data_channel_id,
39 uint64_t* message_id,
40 size_t* bytes_read) {
41 RTC_DCHECK(data_channel_id);
42 RTC_DCHECK(message_id);
43 RTC_DCHECK(bytes_read);
44
45 rtc::ByteBufferReader byte_buffer(data, len, rtc::ByteBuffer::ORDER_HOST);
46 uint64_t dcid;
47 if (!byte_buffer.ReadUVarint(&dcid)) {
48 LOG(LS_ERROR) << "Could not read the data channel ID";
49 return false;
50 }
51 *data_channel_id = dcid;
52 if (!byte_buffer.ReadUVarint(message_id)) {
53 LOG(LS_ERROR) << "Could not read message ID for data channel "
54 << *data_channel_id;
55 return false;
56 }
57 size_t remaining_bytes = byte_buffer.Length();
58 *bytes_read = len - remaining_bytes;
59 return true;
60}
61
62QuicDataChannel::QuicDataChannel(rtc::Thread* signaling_thread,
63 rtc::Thread* worker_thread,
64 const std::string& label,
65 const DataChannelInit& config)
66 : signaling_thread_(signaling_thread),
67 worker_thread_(worker_thread),
68 id_(config.id),
69 state_(kConnecting),
70 buffered_amount_(0),
71 next_message_id_(0),
72 label_(label),
73 protocol_(config.protocol) {}
74
75QuicDataChannel::~QuicDataChannel() {}
76
77void QuicDataChannel::RegisterObserver(DataChannelObserver* observer) {
78 RTC_DCHECK(signaling_thread_->IsCurrent());
79 observer_ = observer;
80}
81
82void QuicDataChannel::UnregisterObserver() {
83 RTC_DCHECK(signaling_thread_->IsCurrent());
84 observer_ = nullptr;
85}
86
87bool QuicDataChannel::Send(const DataBuffer& buffer) {
88 RTC_DCHECK(signaling_thread_->IsCurrent());
89 if (state_ != kOpen) {
90 LOG(LS_ERROR) << "QUIC data channel " << id_
91 << " is not open so cannot send.";
92 return false;
93 }
94 return worker_thread_->Invoke<bool>(
Taylor Brandstetter5d97a9a2016-06-10 21:17:2795 RTC_FROM_HERE, rtc::Bind(&QuicDataChannel::Send_w, this, buffer));
mikescarlett9bc517f2016-04-30 01:30:5596}
97
98bool QuicDataChannel::Send_w(const DataBuffer& buffer) {
99 RTC_DCHECK(worker_thread_->IsCurrent());
100
101 // Encode and send the header containing the data channel ID and message ID.
102 rtc::CopyOnWriteBuffer header;
103 WriteQuicDataChannelMessageHeader(id_, ++next_message_id_, &header);
104 RTC_DCHECK(quic_transport_channel_);
105 cricket::ReliableQuicStream* stream =
106 quic_transport_channel_->CreateQuicStream();
107 RTC_DCHECK(stream);
108
109 // Send the header with a FIN if the message is empty.
110 bool header_fin = (buffer.size() == 0);
111 rtc::StreamResult header_result =
112 stream->Write(header.data<char>(), header.size(), header_fin);
113
114 if (header_result == rtc::SR_BLOCK) {
115 // The header is write blocked but we should try sending the message. Since
116 // the ReliableQuicStream queues data in order, if the header is write
117 // blocked then the message will be write blocked. Otherwise if the message
118 // is sent then the header is sent.
119 LOG(LS_INFO) << "Stream " << stream->id()
120 << " header is write blocked for QUIC data channel " << id_;
121 } else if (header_result != rtc::SR_SUCCESS) {
122 LOG(LS_ERROR) << "Stream " << stream->id()
123 << " failed to write header for QUIC data channel " << id_
124 << ". Unexpected error " << header_result;
125 return false;
126 }
127
128 // If the message is not empty, then send the message with a FIN.
129 bool message_fin = true;
130 rtc::StreamResult message_result =
131 header_fin ? header_result : stream->Write(buffer.data.data<char>(),
132 buffer.size(), message_fin);
133
134 if (message_result == rtc::SR_SUCCESS) {
135 // The message is sent and we don't need this QUIC stream.
136 LOG(LS_INFO) << "Stream " << stream->id()
137 << " successfully wrote message for QUIC data channel " << id_;
138 stream->Close();
139 return true;
140 }
141 // TODO(mikescarlett): Register the ReliableQuicStream's priority to the
142 // QuicWriteBlockedList so that the QUIC session doesn't drop messages when
143 // the QUIC transport channel becomes unwritable.
144 if (message_result == rtc::SR_BLOCK) {
145 // The QUIC stream is write blocked, so the message is queued by the QUIC
146 // session. If this is due to the QUIC not being writable, it will be sent
147 // once QUIC becomes writable again. Otherwise it may be due to exceeding
148 // the QUIC flow control limit, in which case the remote peer's QUIC session
149 // will tell the QUIC stream to send more data.
150 LOG(LS_INFO) << "Stream " << stream->id()
151 << " message is write blocked for QUIC data channel " << id_;
152 SetBufferedAmount_w(buffered_amount_ + stream->queued_data_bytes());
153 stream->SignalQueuedBytesWritten.connect(
154 this, &QuicDataChannel::OnQueuedBytesWritten);
155 write_blocked_quic_streams_[stream->id()] = stream;
156 // The QUIC stream will be removed from |write_blocked_quic_streams_| once
157 // it closes.
158 stream->SignalClosed.connect(this,
159 &QuicDataChannel::OnWriteBlockedStreamClosed);
160 return true;
161 }
162 LOG(LS_ERROR) << "Stream " << stream->id()
163 << " failed to write message for QUIC data channel " << id_
164 << ". Unexpected error: " << message_result;
165 return false;
166}
167
168void QuicDataChannel::OnQueuedBytesWritten(net::QuicStreamId stream_id,
169 uint64_t queued_bytes_written) {
170 RTC_DCHECK(worker_thread_->IsCurrent());
171 SetBufferedAmount_w(buffered_amount_ - queued_bytes_written);
172 const auto& kv = write_blocked_quic_streams_.find(stream_id);
173 if (kv == write_blocked_quic_streams_.end()) {
174 RTC_DCHECK(false);
175 return;
176 }
177 cricket::ReliableQuicStream* stream = kv->second;
178 // True if the QUIC stream is done sending data.
179 if (stream->fin_sent()) {
180 LOG(LS_INFO) << "Stream " << stream->id()
181 << " successfully wrote data for QUIC data channel " << id_;
182 stream->Close();
183 }
184}
185
186void QuicDataChannel::SetBufferedAmount_w(uint64_t buffered_amount) {
187 RTC_DCHECK(worker_thread_->IsCurrent());
188 buffered_amount_ = buffered_amount;
189 invoker_.AsyncInvoke<void>(
Taylor Brandstetter5d97a9a2016-06-10 21:17:27190 RTC_FROM_HERE, signaling_thread_,
191 rtc::Bind(&QuicDataChannel::OnBufferedAmountChange_s, this,
192 buffered_amount));
mikescarlett9bc517f2016-04-30 01:30:55193}
194
195void QuicDataChannel::Close() {
196 RTC_DCHECK(signaling_thread_->IsCurrent());
197 if (state_ == kClosed || state_ == kClosing) {
198 return;
199 }
200 LOG(LS_INFO) << "Closing QUIC data channel.";
201 SetState_s(kClosing);
Taylor Brandstetter5d97a9a2016-06-10 21:17:27202 worker_thread_->Invoke<void>(RTC_FROM_HERE,
203 rtc::Bind(&QuicDataChannel::Close_w, this));
mikescarlett9bc517f2016-04-30 01:30:55204 SetState_s(kClosed);
205}
206
207void QuicDataChannel::Close_w() {
208 RTC_DCHECK(worker_thread_->IsCurrent());
209 for (auto& kv : incoming_quic_messages_) {
210 Message& message = kv.second;
211 cricket::ReliableQuicStream* stream = message.stream;
212 stream->Close();
213 }
214
215 for (auto& kv : write_blocked_quic_streams_) {
216 cricket::ReliableQuicStream* stream = kv.second;
217 stream->Close();
218 }
219}
220
221bool QuicDataChannel::SetTransportChannel(
222 cricket::QuicTransportChannel* channel) {
223 RTC_DCHECK(signaling_thread_->IsCurrent());
224
225 if (!channel) {
226 LOG(LS_ERROR) << "|channel| is NULL. Cannot set transport channel.";
227 return false;
228 }
229 if (quic_transport_channel_) {
230 if (channel == quic_transport_channel_) {
231 LOG(LS_WARNING) << "Ignoring duplicate transport channel.";
232 return true;
233 }
234 LOG(LS_ERROR) << "|channel| does not match existing transport channel.";
235 return false;
236 }
237
238 quic_transport_channel_ = channel;
239 LOG(LS_INFO) << "Setting QuicTransportChannel for QUIC data channel " << id_;
240 DataState data_channel_state = worker_thread_->Invoke<DataState>(
Taylor Brandstetter5d97a9a2016-06-10 21:17:27241 RTC_FROM_HERE, rtc::Bind(&QuicDataChannel::SetTransportChannel_w, this));
mikescarlett9bc517f2016-04-30 01:30:55242 SetState_s(data_channel_state);
243 return true;
244}
245
246DataChannelInterface::DataState QuicDataChannel::SetTransportChannel_w() {
247 RTC_DCHECK(worker_thread_->IsCurrent());
248 quic_transport_channel_->SignalReadyToSend.connect(
249 this, &QuicDataChannel::OnReadyToSend);
250 quic_transport_channel_->SignalClosed.connect(
251 this, &QuicDataChannel::OnConnectionClosed);
252 if (quic_transport_channel_->writable()) {
253 return kOpen;
254 }
255 return kConnecting;
256}
257
258void QuicDataChannel::OnIncomingMessage(Message&& message) {
259 RTC_DCHECK(worker_thread_->IsCurrent());
260 RTC_DCHECK(message.stream);
261 if (!observer_) {
262 LOG(LS_WARNING) << "QUIC data channel " << id_
263 << " received a message but has no observer.";
264 message.stream->Close();
265 return;
266 }
267 // A FIN is received if the message fits into a single QUIC stream frame and
268 // the remote peer is done sending.
269 if (message.stream->fin_received()) {
270 LOG(LS_INFO) << "Stream " << message.stream->id()
271 << " has finished receiving data for QUIC data channel "
272 << id_;
273 DataBuffer final_message(message.buffer, false);
Taylor Brandstetter5d97a9a2016-06-10 21:17:27274 invoker_.AsyncInvoke<void>(RTC_FROM_HERE, signaling_thread_,
mikescarlett9bc517f2016-04-30 01:30:55275 rtc::Bind(&QuicDataChannel::OnMessage_s, this,
276 std::move(final_message)));
277 message.stream->Close();
278 return;
279 }
280 // Otherwise the message is divided across multiple QUIC stream frames, so
281 // queue the data. OnDataReceived() will be called each time the remaining
282 // QUIC stream frames arrive.
283 LOG(LS_INFO) << "QUIC data channel " << id_
284 << " is queuing incoming data for stream "
285 << message.stream->id();
286 incoming_quic_messages_[message.stream->id()] = std::move(message);
287 message.stream->SignalDataReceived.connect(this,
288 &QuicDataChannel::OnDataReceived);
289 // The QUIC stream will be removed from |incoming_quic_messages_| once it
290 // closes.
291 message.stream->SignalClosed.connect(
292 this, &QuicDataChannel::OnIncomingQueuedStreamClosed);
293}
294
295void QuicDataChannel::OnDataReceived(net::QuicStreamId stream_id,
296 const char* data,
297 size_t len) {
298 RTC_DCHECK(worker_thread_->IsCurrent());
299 RTC_DCHECK(data);
300 const auto& kv = incoming_quic_messages_.find(stream_id);
301 if (kv == incoming_quic_messages_.end()) {
302 RTC_DCHECK(false);
303 return;
304 }
305 Message& message = kv->second;
306 cricket::ReliableQuicStream* stream = message.stream;
307 rtc::CopyOnWriteBuffer& received_data = message.buffer;
308 // If the QUIC stream has not received a FIN, then the remote peer is not
309 // finished sending data.
310 if (!stream->fin_received()) {
311 received_data.AppendData(data, len);
312 return;
313 }
314 // Otherwise we are done receiving and can provide the data channel observer
315 // with the message.
316 LOG(LS_INFO) << "Stream " << stream_id
317 << " has finished receiving data for QUIC data channel " << id_;
318 received_data.AppendData(data, len);
319 DataBuffer final_message(std::move(received_data), false);
320 invoker_.AsyncInvoke<void>(
Taylor Brandstetter5d97a9a2016-06-10 21:17:27321 RTC_FROM_HERE, signaling_thread_,
mikescarlett9bc517f2016-04-30 01:30:55322 rtc::Bind(&QuicDataChannel::OnMessage_s, this, std::move(final_message)));
323 // Once the stream is closed, OnDataReceived will not fire for the stream.
324 stream->Close();
325}
326
327void QuicDataChannel::OnReadyToSend(cricket::TransportChannel* channel) {
328 RTC_DCHECK(worker_thread_->IsCurrent());
329 RTC_DCHECK(channel == quic_transport_channel_);
330 LOG(LS_INFO) << "QuicTransportChannel is ready to send";
331 invoker_.AsyncInvoke<void>(
Taylor Brandstetter5d97a9a2016-06-10 21:17:27332 RTC_FROM_HERE, signaling_thread_,
333 rtc::Bind(&QuicDataChannel::SetState_s, this, kOpen));
mikescarlett9bc517f2016-04-30 01:30:55334}
335
336void QuicDataChannel::OnWriteBlockedStreamClosed(net::QuicStreamId stream_id,
337 int error) {
338 RTC_DCHECK(worker_thread_->IsCurrent());
339 LOG(LS_VERBOSE) << "Write blocked stream " << stream_id << " is closed.";
340 write_blocked_quic_streams_.erase(stream_id);
341}
342
343void QuicDataChannel::OnIncomingQueuedStreamClosed(net::QuicStreamId stream_id,
344 int error) {
345 RTC_DCHECK(worker_thread_->IsCurrent());
346 LOG(LS_VERBOSE) << "Incoming queued stream " << stream_id << " is closed.";
347 incoming_quic_messages_.erase(stream_id);
348}
349
350void QuicDataChannel::OnConnectionClosed() {
351 RTC_DCHECK(worker_thread_->IsCurrent());
Taylor Brandstetter5d97a9a2016-06-10 21:17:27352 invoker_.AsyncInvoke<void>(RTC_FROM_HERE, signaling_thread_,
mikescarlett9bc517f2016-04-30 01:30:55353 rtc::Bind(&QuicDataChannel::Close, this));
354}
355
356void QuicDataChannel::OnMessage_s(const DataBuffer& received_data) {
357 RTC_DCHECK(signaling_thread_->IsCurrent());
358 if (observer_) {
359 observer_->OnMessage(received_data);
360 }
361}
362
363void QuicDataChannel::SetState_s(DataState state) {
364 RTC_DCHECK(signaling_thread_->IsCurrent());
365 if (state_ == state || state_ == kClosed) {
366 return;
367 }
368 if (state_ == kClosing && state != kClosed) {
369 return;
370 }
371 LOG(LS_INFO) << "Setting state to " << state << " for QUIC data channel "
372 << id_;
373 state_ = state;
374 if (observer_) {
375 observer_->OnStateChange();
376 }
377}
378
379void QuicDataChannel::OnBufferedAmountChange_s(uint64_t buffered_amount) {
380 RTC_DCHECK(signaling_thread_->IsCurrent());
381 if (observer_) {
382 observer_->OnBufferedAmountChange(buffered_amount);
383 }
384}
385
386size_t QuicDataChannel::GetNumWriteBlockedStreams() const {
387 return write_blocked_quic_streams_.size();
388}
389
390size_t QuicDataChannel::GetNumIncomingStreams() const {
391 return incoming_quic_messages_.size();
392}
393
394} // namespace webrtc