Add ENABLE_MEDIA_ROUTER define to builds other than Android and iOS.
[chromium-blink-merge.git] / net / quic / reliable_quic_stream.cc
blob97ad6e138bfc6702feb514e75541b0835da46e86
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "net/quic/reliable_quic_stream.h"
7 #include "base/logging.h"
8 #include "net/quic/iovector.h"
9 #include "net/quic/quic_flow_controller.h"
10 #include "net/quic/quic_session.h"
11 #include "net/quic/quic_write_blocked_list.h"
13 using base::StringPiece;
14 using std::min;
15 using std::string;
17 namespace net {
19 #define ENDPOINT \
20 (perspective_ == Perspective::IS_SERVER ? "Server: " : "Client: ")
22 namespace {
24 struct iovec MakeIovec(StringPiece data) {
25 struct iovec iov = {const_cast<char*>(data.data()),
26 static_cast<size_t>(data.size())};
27 return iov;
30 size_t GetInitialStreamFlowControlWindowToSend(QuicSession* session) {
31 return session->config()->GetInitialStreamFlowControlWindowToSend();
34 size_t GetReceivedFlowControlWindow(QuicSession* session) {
35 if (session->config()->HasReceivedInitialStreamFlowControlWindowBytes()) {
36 return session->config()->ReceivedInitialStreamFlowControlWindowBytes();
39 return kMinimumFlowControlSendWindow;
42 } // namespace
44 // Wrapper that aggregates OnAckNotifications for packets sent using
45 // WriteOrBufferData and delivers them to the original
46 // QuicAckNotifier::DelegateInterface after all bytes written using
47 // WriteOrBufferData are acked. This level of indirection is
48 // necessary because the delegate interface provides no mechanism that
49 // WriteOrBufferData can use to inform it that the write required
50 // multiple WritevData calls or that only part of the data has been
51 // sent out by the time ACKs start arriving.
52 class ReliableQuicStream::ProxyAckNotifierDelegate
53 : public QuicAckNotifier::DelegateInterface {
54 public:
55 explicit ProxyAckNotifierDelegate(DelegateInterface* delegate)
56 : delegate_(delegate),
57 pending_acks_(0),
58 wrote_last_data_(false),
59 num_retransmitted_packets_(0),
60 num_retransmitted_bytes_(0) {
63 void OnAckNotification(int num_retransmitted_packets,
64 int num_retransmitted_bytes,
65 QuicTime::Delta delta_largest_observed) override {
66 DCHECK_LT(0, pending_acks_);
67 --pending_acks_;
68 num_retransmitted_packets_ += num_retransmitted_packets;
69 num_retransmitted_bytes_ += num_retransmitted_bytes;
71 if (wrote_last_data_ && pending_acks_ == 0) {
72 delegate_->OnAckNotification(num_retransmitted_packets_,
73 num_retransmitted_bytes_,
74 delta_largest_observed);
78 void WroteData(bool last_data) {
79 DCHECK(!wrote_last_data_);
80 ++pending_acks_;
81 wrote_last_data_ = last_data;
84 protected:
85 // Delegates are ref counted.
86 ~ProxyAckNotifierDelegate() override {}
88 private:
89 // Original delegate. delegate_->OnAckNotification will be called when:
90 // wrote_last_data_ == true and pending_acks_ == 0
91 scoped_refptr<DelegateInterface> delegate_;
93 // Number of outstanding acks.
94 int pending_acks_;
96 // True if no pending writes remain.
97 bool wrote_last_data_;
99 int num_retransmitted_packets_;
100 int num_retransmitted_bytes_;
102 DISALLOW_COPY_AND_ASSIGN(ProxyAckNotifierDelegate);
105 ReliableQuicStream::PendingData::PendingData(
106 string data_in, scoped_refptr<ProxyAckNotifierDelegate> delegate_in)
107 : data(data_in), delegate(delegate_in) {
110 ReliableQuicStream::PendingData::~PendingData() {
113 ReliableQuicStream::ReliableQuicStream(QuicStreamId id, QuicSession* session)
114 : sequencer_(this),
115 id_(id),
116 session_(session),
117 stream_bytes_read_(0),
118 stream_bytes_written_(0),
119 stream_error_(QUIC_STREAM_NO_ERROR),
120 connection_error_(QUIC_NO_ERROR),
121 read_side_closed_(false),
122 write_side_closed_(false),
123 fin_buffered_(false),
124 fin_sent_(false),
125 fin_received_(false),
126 rst_sent_(false),
127 rst_received_(false),
128 fec_policy_(FEC_PROTECT_OPTIONAL),
129 perspective_(session_->perspective()),
130 flow_controller_(session_->connection(),
131 id_,
132 perspective_,
133 GetReceivedFlowControlWindow(session),
134 GetInitialStreamFlowControlWindowToSend(session),
135 GetInitialStreamFlowControlWindowToSend(session)),
136 connection_flow_controller_(session_->flow_controller()),
137 stream_contributes_to_connection_flow_control_(true) {
140 ReliableQuicStream::~ReliableQuicStream() {
143 void ReliableQuicStream::OnStreamFrame(const QuicStreamFrame& frame) {
144 if (read_side_closed_) {
145 DVLOG(1) << ENDPOINT << "Ignoring frame " << frame.stream_id;
146 // We don't want to be reading: blackhole the data.
147 return;
150 if (frame.stream_id != id_) {
151 session_->connection()->SendConnectionClose(QUIC_INTERNAL_ERROR);
152 return;
155 if (frame.fin) {
156 fin_received_ = true;
159 // This count include duplicate data received.
160 size_t frame_payload_size = frame.data.TotalBufferSize();
161 stream_bytes_read_ += frame_payload_size;
163 // Flow control is interested in tracking highest received offset.
164 if (MaybeIncreaseHighestReceivedOffset(frame.offset + frame_payload_size)) {
165 // As the highest received offset has changed, we should check to see if
166 // this is a violation of flow control.
167 if (flow_controller_.FlowControlViolation() ||
168 connection_flow_controller_->FlowControlViolation()) {
169 session_->connection()->SendConnectionClose(
170 QUIC_FLOW_CONTROL_RECEIVED_TOO_MUCH_DATA);
171 return;
175 sequencer_.OnStreamFrame(frame);
178 int ReliableQuicStream::num_frames_received() const {
179 return sequencer_.num_frames_received();
182 int ReliableQuicStream::num_early_frames_received() const {
183 return sequencer_.num_early_frames_received();
186 int ReliableQuicStream::num_duplicate_frames_received() const {
187 return sequencer_.num_duplicate_frames_received();
190 void ReliableQuicStream::OnStreamReset(const QuicRstStreamFrame& frame) {
191 rst_received_ = true;
192 MaybeIncreaseHighestReceivedOffset(frame.byte_offset);
194 stream_error_ = frame.error_code;
195 CloseWriteSide();
196 CloseReadSide();
199 void ReliableQuicStream::OnConnectionClosed(QuicErrorCode error,
200 bool from_peer) {
201 if (read_side_closed_ && write_side_closed_) {
202 return;
204 if (error != QUIC_NO_ERROR) {
205 stream_error_ = QUIC_STREAM_CONNECTION_ERROR;
206 connection_error_ = error;
209 CloseWriteSide();
210 CloseReadSide();
213 void ReliableQuicStream::OnFinRead() {
214 DCHECK(sequencer_.IsClosed());
215 fin_received_ = true;
216 CloseReadSide();
219 void ReliableQuicStream::Reset(QuicRstStreamErrorCode error) {
220 DCHECK_NE(QUIC_STREAM_NO_ERROR, error);
221 stream_error_ = error;
222 // Sending a RstStream results in calling CloseStream.
223 session()->SendRstStream(id(), error, stream_bytes_written_);
224 rst_sent_ = true;
227 void ReliableQuicStream::CloseConnection(QuicErrorCode error) {
228 session()->connection()->SendConnectionClose(error);
231 void ReliableQuicStream::CloseConnectionWithDetails(QuicErrorCode error,
232 const string& details) {
233 session()->connection()->SendConnectionCloseWithDetails(error, details);
236 void ReliableQuicStream::WriteOrBufferData(
237 StringPiece data,
238 bool fin,
239 QuicAckNotifier::DelegateInterface* ack_notifier_delegate) {
240 if (data.empty() && !fin) {
241 LOG(DFATAL) << "data.empty() && !fin";
242 return;
245 if (fin_buffered_) {
246 LOG(DFATAL) << "Fin already buffered";
247 return;
250 scoped_refptr<ProxyAckNotifierDelegate> proxy_delegate;
251 if (ack_notifier_delegate != nullptr) {
252 proxy_delegate = new ProxyAckNotifierDelegate(ack_notifier_delegate);
255 QuicConsumedData consumed_data(0, false);
256 fin_buffered_ = fin;
258 if (queued_data_.empty()) {
259 struct iovec iov(MakeIovec(data));
260 consumed_data = WritevData(&iov, 1, fin, proxy_delegate.get());
261 DCHECK_LE(consumed_data.bytes_consumed, data.length());
264 bool write_completed;
265 // If there's unconsumed data or an unconsumed fin, queue it.
266 if (consumed_data.bytes_consumed < data.length() ||
267 (fin && !consumed_data.fin_consumed)) {
268 StringPiece remainder(data.substr(consumed_data.bytes_consumed));
269 queued_data_.push_back(PendingData(remainder.as_string(), proxy_delegate));
270 write_completed = false;
271 } else {
272 write_completed = true;
275 if ((proxy_delegate.get() != nullptr) &&
276 (consumed_data.bytes_consumed > 0 || consumed_data.fin_consumed)) {
277 proxy_delegate->WroteData(write_completed);
281 void ReliableQuicStream::OnCanWrite() {
282 bool fin = false;
283 while (!queued_data_.empty()) {
284 PendingData* pending_data = &queued_data_.front();
285 ProxyAckNotifierDelegate* delegate = pending_data->delegate.get();
286 if (queued_data_.size() == 1 && fin_buffered_) {
287 fin = true;
289 struct iovec iov(MakeIovec(pending_data->data));
290 QuicConsumedData consumed_data = WritevData(&iov, 1, fin, delegate);
291 if (consumed_data.bytes_consumed == pending_data->data.size() &&
292 fin == consumed_data.fin_consumed) {
293 queued_data_.pop_front();
294 if (delegate != nullptr) {
295 delegate->WroteData(true);
297 } else {
298 if (consumed_data.bytes_consumed > 0) {
299 pending_data->data.erase(0, consumed_data.bytes_consumed);
300 if (delegate != nullptr) {
301 delegate->WroteData(false);
304 break;
309 void ReliableQuicStream::MaybeSendBlocked() {
310 flow_controller_.MaybeSendBlocked();
311 if (!stream_contributes_to_connection_flow_control_) {
312 return;
314 connection_flow_controller_->MaybeSendBlocked();
315 // If we are connection level flow control blocked, then add the stream
316 // to the write blocked list. It will be given a chance to write when a
317 // connection level WINDOW_UPDATE arrives.
318 if (connection_flow_controller_->IsBlocked() &&
319 !flow_controller_.IsBlocked()) {
320 session_->MarkWriteBlocked(id(), EffectivePriority());
324 QuicConsumedData ReliableQuicStream::WritevData(
325 const struct iovec* iov,
326 int iov_count,
327 bool fin,
328 QuicAckNotifier::DelegateInterface* ack_notifier_delegate) {
329 if (write_side_closed_) {
330 DLOG(ERROR) << ENDPOINT << "Attempt to write when the write side is closed";
331 return QuicConsumedData(0, false);
334 // How much data we want to write.
335 size_t write_length = TotalIovecLength(iov, iov_count);
337 // A FIN with zero data payload should not be flow control blocked.
338 bool fin_with_zero_data = (fin && write_length == 0);
340 // How much data we are allowed to write from flow control.
341 QuicByteCount send_window = flow_controller_.SendWindowSize();
342 if (stream_contributes_to_connection_flow_control_) {
343 send_window =
344 min(send_window, connection_flow_controller_->SendWindowSize());
347 if (send_window == 0 && !fin_with_zero_data) {
348 // Quick return if we can't send anything.
349 MaybeSendBlocked();
350 return QuicConsumedData(0, false);
353 if (write_length > send_window) {
354 // Don't send the FIN if we aren't going to send all the data.
355 fin = false;
357 // Writing more data would be a violation of flow control.
358 write_length = static_cast<size_t>(send_window);
361 // Fill an IOVector with bytes from the iovec.
362 IOVector data;
363 data.AppendIovecAtMostBytes(iov, iov_count, write_length);
365 QuicConsumedData consumed_data = session()->WritevData(
366 id(), data, stream_bytes_written_, fin, GetFecProtection(),
367 ack_notifier_delegate);
368 stream_bytes_written_ += consumed_data.bytes_consumed;
370 AddBytesSent(consumed_data.bytes_consumed);
372 if (consumed_data.bytes_consumed == write_length) {
373 if (!fin_with_zero_data) {
374 MaybeSendBlocked();
376 if (fin && consumed_data.fin_consumed) {
377 fin_sent_ = true;
378 CloseWriteSide();
379 } else if (fin && !consumed_data.fin_consumed) {
380 session_->MarkWriteBlocked(id(), EffectivePriority());
382 } else {
383 session_->MarkWriteBlocked(id(), EffectivePriority());
385 return consumed_data;
388 FecProtection ReliableQuicStream::GetFecProtection() {
389 return fec_policy_ == FEC_PROTECT_ALWAYS ? MUST_FEC_PROTECT : MAY_FEC_PROTECT;
392 void ReliableQuicStream::CloseReadSide() {
393 if (read_side_closed_) {
394 return;
396 DVLOG(1) << ENDPOINT << "Done reading from stream " << id();
398 read_side_closed_ = true;
399 if (write_side_closed_) {
400 DVLOG(1) << ENDPOINT << "Closing stream: " << id();
401 session_->CloseStream(id());
405 void ReliableQuicStream::CloseWriteSide() {
406 if (write_side_closed_) {
407 return;
409 DVLOG(1) << ENDPOINT << "Done writing to stream " << id();
411 write_side_closed_ = true;
412 if (read_side_closed_) {
413 DVLOG(1) << ENDPOINT << "Closing stream: " << id();
414 session_->CloseStream(id());
418 bool ReliableQuicStream::HasBufferedData() const {
419 return !queued_data_.empty();
422 void ReliableQuicStream::OnClose() {
423 CloseReadSide();
424 CloseWriteSide();
426 if (!fin_sent_ && !rst_sent_) {
427 // For flow control accounting, we must tell the peer how many bytes we have
428 // written on this stream before termination. Done here if needed, using a
429 // RST frame.
430 DVLOG(1) << ENDPOINT << "Sending RST in OnClose: " << id();
431 session_->SendRstStream(id(), QUIC_RST_ACKNOWLEDGEMENT,
432 stream_bytes_written_);
433 rst_sent_ = true;
436 // We are closing the stream and will not process any further incoming bytes.
437 // As there may be more bytes in flight and we need to ensure that both
438 // endpoints have the same connection level flow control state, mark all
439 // unreceived or buffered bytes as consumed.
440 QuicByteCount bytes_to_consume =
441 flow_controller_.highest_received_byte_offset() -
442 flow_controller_.bytes_consumed();
443 AddBytesConsumed(bytes_to_consume);
446 void ReliableQuicStream::OnWindowUpdateFrame(
447 const QuicWindowUpdateFrame& frame) {
448 if (flow_controller_.UpdateSendWindowOffset(frame.byte_offset)) {
449 // We can write again!
450 // TODO(rjshade): This does not respect priorities (e.g. multiple
451 // outstanding POSTs are unblocked on arrival of
452 // SHLO with initial window).
453 // As long as the connection is not flow control blocked, we can write!
454 OnCanWrite();
458 bool ReliableQuicStream::MaybeIncreaseHighestReceivedOffset(
459 QuicStreamOffset new_offset) {
460 uint64 increment =
461 new_offset - flow_controller_.highest_received_byte_offset();
462 if (!flow_controller_.UpdateHighestReceivedOffset(new_offset)) {
463 return false;
466 // If |new_offset| increased the stream flow controller's highest received
467 // offset, then we need to increase the connection flow controller's value
468 // by the incremental difference.
469 if (stream_contributes_to_connection_flow_control_) {
470 connection_flow_controller_->UpdateHighestReceivedOffset(
471 connection_flow_controller_->highest_received_byte_offset() +
472 increment);
474 return true;
477 void ReliableQuicStream::AddBytesSent(QuicByteCount bytes) {
478 flow_controller_.AddBytesSent(bytes);
479 if (stream_contributes_to_connection_flow_control_) {
480 connection_flow_controller_->AddBytesSent(bytes);
484 void ReliableQuicStream::AddBytesConsumed(QuicByteCount bytes) {
485 // Only adjust stream level flow controller if we are still reading.
486 if (!read_side_closed_) {
487 flow_controller_.AddBytesConsumed(bytes);
490 if (stream_contributes_to_connection_flow_control_) {
491 connection_flow_controller_->AddBytesConsumed(bytes);
495 void ReliableQuicStream::UpdateSendWindowOffset(QuicStreamOffset new_window) {
496 if (flow_controller_.UpdateSendWindowOffset(new_window)) {
497 OnCanWrite();
501 } // namespace net