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/spdy/spdy_stream.h"
8 #include "base/compiler_specific.h"
9 #include "base/location.h"
10 #include "base/logging.h"
11 #include "base/metrics/histogram_macros.h"
12 #include "base/single_thread_task_runner.h"
13 #include "base/strings/string_number_conversions.h"
14 #include "base/strings/stringprintf.h"
15 #include "base/thread_task_runner_handle.h"
16 #include "base/values.h"
17 #include "net/spdy/spdy_buffer_producer.h"
18 #include "net/spdy/spdy_http_utils.h"
19 #include "net/spdy/spdy_session.h"
25 scoped_ptr
<base::Value
> NetLogSpdyStreamErrorCallback(
26 SpdyStreamId stream_id
,
28 const std::string
* description
,
29 NetLogCaptureMode
/* capture_mode */) {
30 scoped_ptr
<base::DictionaryValue
> dict(new base::DictionaryValue());
31 dict
->SetInteger("stream_id", static_cast<int>(stream_id
));
32 dict
->SetInteger("status", status
);
33 dict
->SetString("description", *description
);
37 scoped_ptr
<base::Value
> NetLogSpdyStreamWindowUpdateCallback(
38 SpdyStreamId stream_id
,
41 NetLogCaptureMode
/* capture_mode */) {
42 scoped_ptr
<base::DictionaryValue
> dict(new base::DictionaryValue());
43 dict
->SetInteger("stream_id", stream_id
);
44 dict
->SetInteger("delta", delta
);
45 dict
->SetInteger("window_size", window_size
);
49 bool ContainsUppercaseAscii(const std::string
& str
) {
50 for (std::string::const_iterator
i(str
.begin()); i
!= str
.end(); ++i
) {
51 if (*i
>= 'A' && *i
<= 'Z') {
60 // A wrapper around a stream that calls into ProduceSynStreamFrame().
61 class SpdyStream::SynStreamBufferProducer
: public SpdyBufferProducer
{
63 SynStreamBufferProducer(const base::WeakPtr
<SpdyStream
>& stream
)
65 DCHECK(stream_
.get());
68 ~SynStreamBufferProducer() override
{}
70 scoped_ptr
<SpdyBuffer
> ProduceBuffer() override
{
73 return scoped_ptr
<SpdyBuffer
>();
75 DCHECK_GT(stream_
->stream_id(), 0u);
76 return scoped_ptr
<SpdyBuffer
>(
77 new SpdyBuffer(stream_
->ProduceSynStreamFrame()));
81 const base::WeakPtr
<SpdyStream
> stream_
;
84 SpdyStream::SpdyStream(SpdyStreamType type
,
85 const base::WeakPtr
<SpdySession
>& session
,
87 RequestPriority priority
,
88 int32 initial_send_window_size
,
89 int32 max_recv_window_size
,
90 const BoundNetLog
& net_log
)
95 send_stalled_by_flow_control_(false),
96 send_window_size_(initial_send_window_size
),
97 max_recv_window_size_(max_recv_window_size
),
98 recv_window_size_(max_recv_window_size
),
99 unacked_recv_window_bytes_(0),
102 pending_send_status_(MORE_DATA_TO_SEND
),
103 request_time_(base::Time::Now()),
104 response_headers_status_(RESPONSE_HEADERS_ARE_INCOMPLETE
),
105 io_state_(STATE_IDLE
),
106 response_status_(OK
),
108 raw_received_bytes_(0),
111 write_handler_guard_(false),
112 weak_ptr_factory_(this) {
113 CHECK(type_
== SPDY_BIDIRECTIONAL_STREAM
||
114 type_
== SPDY_REQUEST_RESPONSE_STREAM
||
115 type_
== SPDY_PUSH_STREAM
);
116 CHECK_GE(priority_
, MINIMUM_PRIORITY
);
117 CHECK_LE(priority_
, MAXIMUM_PRIORITY
);
120 SpdyStream::~SpdyStream() {
121 CHECK(!write_handler_guard_
);
125 void SpdyStream::SetDelegate(Delegate
* delegate
) {
128 delegate_
= delegate
;
130 CHECK(io_state_
== STATE_IDLE
||
131 io_state_
== STATE_HALF_CLOSED_LOCAL_UNCLAIMED
||
132 io_state_
== STATE_RESERVED_REMOTE
);
134 if (io_state_
== STATE_HALF_CLOSED_LOCAL_UNCLAIMED
) {
135 DCHECK_EQ(type_
, SPDY_PUSH_STREAM
);
136 base::ThreadTaskRunnerHandle::Get()->PostTask(
137 FROM_HERE
, base::Bind(&SpdyStream::PushedStreamReplay
, GetWeakPtr()));
141 void SpdyStream::PushedStreamReplay() {
142 DCHECK_EQ(type_
, SPDY_PUSH_STREAM
);
143 DCHECK_NE(stream_id_
, 0u);
144 CHECK_EQ(stream_id_
% 2, 0u);
146 CHECK_EQ(io_state_
, STATE_HALF_CLOSED_LOCAL_UNCLAIMED
);
147 io_state_
= STATE_HALF_CLOSED_LOCAL
;
149 // The delegate methods called below may delete |this|, so use
150 // |weak_this| to detect that.
151 base::WeakPtr
<SpdyStream
> weak_this
= GetWeakPtr();
154 SpdyResponseHeadersStatus status
=
155 delegate_
->OnResponseHeadersUpdated(response_headers_
);
156 if (status
== RESPONSE_HEADERS_ARE_INCOMPLETE
) {
157 // Since RESPONSE_HEADERS_ARE_INCOMPLETE was returned, we must not
158 // have been closed. Since we don't have complete headers, assume
159 // we're waiting for another HEADERS frame, and we had better not
160 // have any pending data frames.
162 if (!pending_recv_data_
.empty()) {
163 LogStreamError(ERR_SPDY_PROTOCOL_ERROR
,
164 "Data received with incomplete headers.");
165 session_
->CloseActiveStream(stream_id_
, ERR_SPDY_PROTOCOL_ERROR
);
170 // OnResponseHeadersUpdated() may have closed |this|.
174 response_headers_status_
= RESPONSE_HEADERS_ARE_COMPLETE
;
176 while (!pending_recv_data_
.empty()) {
177 // Take ownership of the first element of |pending_recv_data_|.
178 scoped_ptr
<SpdyBuffer
> buffer(pending_recv_data_
.front());
179 pending_recv_data_
.weak_erase(pending_recv_data_
.begin());
181 bool eof
= (buffer
== NULL
);
184 delegate_
->OnDataReceived(buffer
.Pass());
186 // OnDataReceived() may have closed |this|.
191 DCHECK(pending_recv_data_
.empty());
192 session_
->CloseActiveStream(stream_id_
, OK
);
194 // |pending_recv_data_| is invalid at this point.
200 scoped_ptr
<SpdyFrame
> SpdyStream::ProduceSynStreamFrame() {
201 CHECK_EQ(io_state_
, STATE_IDLE
);
202 CHECK(request_headers_
);
203 CHECK_GT(stream_id_
, 0u);
205 SpdyControlFlags flags
=
206 (pending_send_status_
== NO_MORE_DATA_TO_SEND
) ?
207 CONTROL_FLAG_FIN
: CONTROL_FLAG_NONE
;
208 scoped_ptr
<SpdyFrame
> frame(session_
->CreateSynStream(
209 stream_id_
, priority_
, flags
, *request_headers_
));
210 send_time_
= base::TimeTicks::Now();
214 void SpdyStream::DetachDelegate() {
220 void SpdyStream::AdjustSendWindowSize(int32 delta_window_size
) {
221 DCHECK_GE(session_
->flow_control_state(), SpdySession::FLOW_CONTROL_STREAM
);
226 // Check for wraparound.
227 if (send_window_size_
> 0) {
228 DCHECK_LE(delta_window_size
, kint32max
- send_window_size_
);
230 if (send_window_size_
< 0) {
231 DCHECK_GE(delta_window_size
, kint32min
- send_window_size_
);
233 send_window_size_
+= delta_window_size
;
234 PossiblyResumeIfSendStalled();
237 void SpdyStream::OnWriteBufferConsumed(
238 size_t frame_payload_size
,
240 SpdyBuffer::ConsumeSource consume_source
) {
241 DCHECK_GE(session_
->flow_control_state(), SpdySession::FLOW_CONTROL_STREAM
);
242 if (consume_source
== SpdyBuffer::DISCARD
) {
243 // If we're discarding a frame or part of it, increase the send
244 // window by the number of discarded bytes. (Although if we're
245 // discarding part of a frame, it's probably because of a write
246 // error and we'll be tearing down the stream soon.)
247 size_t remaining_payload_bytes
= std::min(consume_size
, frame_payload_size
);
248 DCHECK_GT(remaining_payload_bytes
, 0u);
249 IncreaseSendWindowSize(static_cast<int32
>(remaining_payload_bytes
));
251 // For consumed bytes, the send window is increased when we receive
252 // a WINDOW_UPDATE frame.
255 void SpdyStream::IncreaseSendWindowSize(int32 delta_window_size
) {
256 DCHECK_GE(session_
->flow_control_state(), SpdySession::FLOW_CONTROL_STREAM
);
257 DCHECK_GE(delta_window_size
, 1);
259 // Ignore late WINDOW_UPDATEs.
263 if (send_window_size_
> 0) {
264 // Check for overflow.
265 int32 max_delta_window_size
= kint32max
- send_window_size_
;
266 if (delta_window_size
> max_delta_window_size
) {
267 std::string desc
= base::StringPrintf(
268 "Received WINDOW_UPDATE [delta: %d] for stream %d overflows "
269 "send_window_size_ [current: %d]", delta_window_size
, stream_id_
,
271 session_
->ResetStream(stream_id_
, RST_STREAM_FLOW_CONTROL_ERROR
, desc
);
276 send_window_size_
+= delta_window_size
;
279 NetLog::TYPE_HTTP2_STREAM_UPDATE_SEND_WINDOW
,
280 base::Bind(&NetLogSpdyStreamWindowUpdateCallback
, stream_id_
,
281 delta_window_size
, send_window_size_
));
283 PossiblyResumeIfSendStalled();
286 void SpdyStream::DecreaseSendWindowSize(int32 delta_window_size
) {
287 DCHECK_GE(session_
->flow_control_state(), SpdySession::FLOW_CONTROL_STREAM
);
292 // We only call this method when sending a frame. Therefore,
293 // |delta_window_size| should be within the valid frame size range.
294 DCHECK_GE(delta_window_size
, 1);
295 DCHECK_LE(delta_window_size
, kMaxSpdyFrameChunkSize
);
297 // |send_window_size_| should have been at least |delta_window_size| for
298 // this call to happen.
299 DCHECK_GE(send_window_size_
, delta_window_size
);
301 send_window_size_
-= delta_window_size
;
304 NetLog::TYPE_HTTP2_STREAM_UPDATE_SEND_WINDOW
,
305 base::Bind(&NetLogSpdyStreamWindowUpdateCallback
, stream_id_
,
306 -delta_window_size
, send_window_size_
));
309 void SpdyStream::OnReadBufferConsumed(
311 SpdyBuffer::ConsumeSource consume_source
) {
312 DCHECK_GE(session_
->flow_control_state(), SpdySession::FLOW_CONTROL_STREAM
);
313 DCHECK_GE(consume_size
, 1u);
314 DCHECK_LE(consume_size
, static_cast<size_t>(kint32max
));
315 IncreaseRecvWindowSize(static_cast<int32
>(consume_size
));
318 void SpdyStream::IncreaseRecvWindowSize(int32 delta_window_size
) {
319 DCHECK_GE(session_
->flow_control_state(), SpdySession::FLOW_CONTROL_STREAM
);
321 // By the time a read is processed by the delegate, this stream may
322 // already be inactive.
323 if (!session_
->IsStreamActive(stream_id_
))
326 DCHECK_GE(unacked_recv_window_bytes_
, 0);
327 DCHECK_GE(recv_window_size_
, unacked_recv_window_bytes_
);
328 DCHECK_GE(delta_window_size
, 1);
329 // Check for overflow.
330 DCHECK_LE(delta_window_size
, kint32max
- recv_window_size_
);
332 recv_window_size_
+= delta_window_size
;
334 NetLog::TYPE_HTTP2_STREAM_UPDATE_RECV_WINDOW
,
335 base::Bind(&NetLogSpdyStreamWindowUpdateCallback
, stream_id_
,
336 delta_window_size
, recv_window_size_
));
338 unacked_recv_window_bytes_
+= delta_window_size
;
339 if (unacked_recv_window_bytes_
> max_recv_window_size_
/ 2) {
340 session_
->SendStreamWindowUpdate(
341 stream_id_
, static_cast<uint32
>(unacked_recv_window_bytes_
));
342 unacked_recv_window_bytes_
= 0;
346 void SpdyStream::DecreaseRecvWindowSize(int32 delta_window_size
) {
347 DCHECK(session_
->IsStreamActive(stream_id_
));
348 DCHECK_GE(session_
->flow_control_state(), SpdySession::FLOW_CONTROL_STREAM
);
349 DCHECK_GE(delta_window_size
, 1);
351 // The receiving window size as the peer knows it is
352 // |recv_window_size_ - unacked_recv_window_bytes_|, if more data are sent by
353 // the peer, that means that the receive window is not being respected.
354 if (delta_window_size
> recv_window_size_
- unacked_recv_window_bytes_
) {
355 session_
->ResetStream(
356 stream_id_
, RST_STREAM_FLOW_CONTROL_ERROR
,
357 "delta_window_size is " + base::IntToString(delta_window_size
) +
358 " in DecreaseRecvWindowSize, which is larger than the receive " +
359 "window size of " + base::IntToString(recv_window_size_
));
363 recv_window_size_
-= delta_window_size
;
365 NetLog::TYPE_HTTP2_STREAM_UPDATE_RECV_WINDOW
,
366 base::Bind(&NetLogSpdyStreamWindowUpdateCallback
, stream_id_
,
367 -delta_window_size
, recv_window_size_
));
370 int SpdyStream::GetPeerAddress(IPEndPoint
* address
) const {
371 return session_
->GetPeerAddress(address
);
374 int SpdyStream::GetLocalAddress(IPEndPoint
* address
) const {
375 return session_
->GetLocalAddress(address
);
378 bool SpdyStream::WasEverUsed() const {
379 return session_
->WasEverUsed();
382 base::Time
SpdyStream::GetRequestTime() const {
383 return request_time_
;
386 void SpdyStream::SetRequestTime(base::Time t
) {
390 int SpdyStream::OnInitialResponseHeadersReceived(
391 const SpdyHeaderBlock
& initial_response_headers
,
392 base::Time response_time
,
393 base::TimeTicks recv_first_byte_time
) {
394 // SpdySession guarantees that this is called at most once.
395 CHECK(response_headers_
.empty());
397 // Check to make sure that we don't receive the response headers
398 // before we're ready for it.
400 case SPDY_BIDIRECTIONAL_STREAM
:
401 // For a bidirectional stream, we're ready for the response
402 // headers once we've finished sending the request headers.
403 if (io_state_
== STATE_IDLE
) {
404 session_
->ResetStream(stream_id_
, RST_STREAM_PROTOCOL_ERROR
,
405 "Response received before request sent");
406 return ERR_SPDY_PROTOCOL_ERROR
;
410 case SPDY_REQUEST_RESPONSE_STREAM
:
411 // For a request/response stream, we're ready for the response
412 // headers once we've finished sending the request headers.
413 if (io_state_
== STATE_IDLE
) {
414 session_
->ResetStream(stream_id_
, RST_STREAM_PROTOCOL_ERROR
,
415 "Response received before request sent");
416 return ERR_SPDY_PROTOCOL_ERROR
;
420 case SPDY_PUSH_STREAM
:
421 // Push streams transition to a locally half-closed state upon headers.
422 // We must continue to buffer data while waiting for a call to
423 // SetDelegate() (which may not ever happen).
424 CHECK_EQ(io_state_
, STATE_RESERVED_REMOTE
);
426 io_state_
= STATE_HALF_CLOSED_LOCAL_UNCLAIMED
;
428 io_state_
= STATE_HALF_CLOSED_LOCAL
;
433 DCHECK_NE(io_state_
, STATE_IDLE
);
435 response_time_
= response_time
;
436 recv_first_byte_time_
= recv_first_byte_time
;
437 return MergeWithResponseHeaders(initial_response_headers
);
440 int SpdyStream::OnAdditionalResponseHeadersReceived(
441 const SpdyHeaderBlock
& additional_response_headers
) {
442 if (type_
== SPDY_REQUEST_RESPONSE_STREAM
) {
443 session_
->ResetStream(
444 stream_id_
, RST_STREAM_PROTOCOL_ERROR
,
445 "Additional headers received for request/response stream");
446 return ERR_SPDY_PROTOCOL_ERROR
;
447 } else if (type_
== SPDY_PUSH_STREAM
&&
448 response_headers_status_
== RESPONSE_HEADERS_ARE_COMPLETE
) {
449 session_
->ResetStream(
450 stream_id_
, RST_STREAM_PROTOCOL_ERROR
,
451 "Additional headers received for push stream");
452 return ERR_SPDY_PROTOCOL_ERROR
;
454 return MergeWithResponseHeaders(additional_response_headers
);
457 void SpdyStream::OnPushPromiseHeadersReceived(const SpdyHeaderBlock
& headers
) {
458 CHECK(!request_headers_
.get());
459 CHECK_EQ(io_state_
, STATE_IDLE
);
460 CHECK_EQ(type_
, SPDY_PUSH_STREAM
);
463 io_state_
= STATE_RESERVED_REMOTE
;
464 request_headers_
.reset(new SpdyHeaderBlock(headers
));
467 void SpdyStream::OnDataReceived(scoped_ptr
<SpdyBuffer
> buffer
) {
468 DCHECK(session_
->IsStreamActive(stream_id_
));
470 // If we're still buffering data for a push stream, we will do the
471 // check for data received with incomplete headers in
472 // PushedStreamReplayData().
473 if (io_state_
== STATE_HALF_CLOSED_LOCAL_UNCLAIMED
) {
474 DCHECK_EQ(type_
, SPDY_PUSH_STREAM
);
475 // It should be valid for this to happen in the server push case.
476 // We'll return received data when delegate gets attached to the stream.
478 pending_recv_data_
.push_back(buffer
.Pass());
480 pending_recv_data_
.push_back(NULL
);
481 // Note: we leave the stream open in the session until the stream
487 // If we have response headers but the delegate has indicated that
488 // it's still incomplete, then that's a protocol error.
489 if (response_headers_status_
== RESPONSE_HEADERS_ARE_INCOMPLETE
) {
490 LogStreamError(ERR_SPDY_PROTOCOL_ERROR
,
491 "Data received with incomplete headers.");
492 session_
->CloseActiveStream(stream_id_
, ERR_SPDY_PROTOCOL_ERROR
);
499 if (io_state_
== STATE_OPEN
) {
500 io_state_
= STATE_HALF_CLOSED_REMOTE
;
501 } else if (io_state_
== STATE_HALF_CLOSED_LOCAL
) {
502 io_state_
= STATE_CLOSED
;
504 session_
->CloseActiveStream(stream_id_
, OK
);
506 NOTREACHED() << io_state_
;
511 size_t length
= buffer
->GetRemainingSize();
512 DCHECK_LE(length
, session_
->GetDataFrameMaximumPayload());
513 if (session_
->flow_control_state() >= SpdySession::FLOW_CONTROL_STREAM
) {
514 base::WeakPtr
<SpdyStream
> weak_this
= GetWeakPtr();
515 // May close the stream.
516 DecreaseRecvWindowSize(static_cast<int32
>(length
));
519 buffer
->AddConsumeCallback(
520 base::Bind(&SpdyStream::OnReadBufferConsumed
, GetWeakPtr()));
523 // Track our bandwidth.
524 recv_bytes_
+= length
;
525 recv_last_byte_time_
= base::TimeTicks::Now();
528 delegate_
->OnDataReceived(buffer
.Pass());
531 void SpdyStream::OnPaddingConsumed(size_t len
) {
532 if (session_
->flow_control_state() >= SpdySession::FLOW_CONTROL_STREAM
) {
533 // Decrease window size because padding bytes are received.
534 // Increase window size because padding bytes are consumed (by discarding).
535 // Net result: |unacked_recv_window_bytes_| increases by |len|,
536 // |recv_window_size_| does not change.
537 base::WeakPtr
<SpdyStream
> weak_this
= GetWeakPtr();
538 // May close the stream.
539 DecreaseRecvWindowSize(static_cast<int32
>(len
));
542 IncreaseRecvWindowSize(static_cast<int32
>(len
));
546 void SpdyStream::OnFrameWriteComplete(SpdyFrameType frame_type
,
548 DCHECK_NE(type_
, SPDY_PUSH_STREAM
);
549 CHECK(frame_type
== SYN_STREAM
||
550 frame_type
== DATA
) << frame_type
;
552 int result
= (frame_type
== SYN_STREAM
) ?
553 OnRequestHeadersSent() : OnDataSent(frame_size
);
554 if (result
== ERR_IO_PENDING
) {
555 // The write operation hasn't completed yet.
559 if (pending_send_status_
== NO_MORE_DATA_TO_SEND
) {
560 if(io_state_
== STATE_OPEN
) {
561 io_state_
= STATE_HALF_CLOSED_LOCAL
;
562 } else if(io_state_
== STATE_HALF_CLOSED_REMOTE
) {
563 io_state_
= STATE_CLOSED
;
565 NOTREACHED() << io_state_
;
568 // Notify delegate of write completion. Must not destroy |this|.
571 base::WeakPtr
<SpdyStream
> weak_this
= GetWeakPtr();
572 write_handler_guard_
= true;
573 if (frame_type
== SYN_STREAM
) {
574 delegate_
->OnRequestHeadersSent();
576 delegate_
->OnDataSent();
579 write_handler_guard_
= false;
582 if (io_state_
== STATE_CLOSED
) {
584 session_
->CloseActiveStream(stream_id_
, OK
);
588 int SpdyStream::OnRequestHeadersSent() {
589 CHECK_EQ(io_state_
, STATE_IDLE
);
590 CHECK_NE(stream_id_
, 0u);
592 io_state_
= STATE_OPEN
;
596 int SpdyStream::OnDataSent(size_t frame_size
) {
597 CHECK(io_state_
== STATE_OPEN
||
598 io_state_
== STATE_HALF_CLOSED_REMOTE
) << io_state_
;
600 size_t frame_payload_size
= frame_size
- session_
->GetDataFrameMinimumSize();
602 CHECK_GE(frame_size
, session_
->GetDataFrameMinimumSize());
603 CHECK_LE(frame_payload_size
, session_
->GetDataFrameMaximumPayload());
605 send_bytes_
+= frame_payload_size
;
607 // If more data is available to send, dispatch it and
608 // return that the write operation is still ongoing.
609 pending_send_data_
->DidConsume(frame_payload_size
);
610 if (pending_send_data_
->BytesRemaining() > 0) {
611 QueueNextDataFrame();
612 return ERR_IO_PENDING
;
614 pending_send_data_
= NULL
;
619 SpdyMajorVersion
SpdyStream::GetProtocolVersion() const {
620 return session_
->GetProtocolVersion();
623 void SpdyStream::LogStreamError(int status
, const std::string
& description
) {
624 net_log_
.AddEvent(NetLog::TYPE_HTTP2_STREAM_ERROR
,
625 base::Bind(&NetLogSpdyStreamErrorCallback
, stream_id_
,
626 status
, &description
));
629 void SpdyStream::OnClose(int status
) {
630 // In most cases, the stream should already be CLOSED. The exception is when a
631 // SpdySession is shutting down while the stream is in an intermediate state.
632 io_state_
= STATE_CLOSED
;
633 response_status_
= status
;
634 Delegate
* delegate
= delegate_
;
637 delegate
->OnClose(status
);
638 // Unset |stream_id_| last so that the delegate can look it up.
642 void SpdyStream::Cancel() {
643 // We may be called again from a delegate's OnClose().
644 if (io_state_
== STATE_CLOSED
)
647 if (stream_id_
!= 0) {
648 session_
->ResetStream(stream_id_
, RST_STREAM_CANCEL
, std::string());
650 session_
->CloseCreatedStream(GetWeakPtr(), RST_STREAM_CANCEL
);
652 // |this| is invalid at this point.
655 void SpdyStream::Close() {
656 // We may be called again from a delegate's OnClose().
657 if (io_state_
== STATE_CLOSED
)
660 if (stream_id_
!= 0) {
661 session_
->CloseActiveStream(stream_id_
, OK
);
663 session_
->CloseCreatedStream(GetWeakPtr(), OK
);
665 // |this| is invalid at this point.
668 base::WeakPtr
<SpdyStream
> SpdyStream::GetWeakPtr() {
669 return weak_ptr_factory_
.GetWeakPtr();
672 int SpdyStream::SendRequestHeaders(scoped_ptr
<SpdyHeaderBlock
> request_headers
,
673 SpdySendStatus send_status
) {
674 CHECK_NE(type_
, SPDY_PUSH_STREAM
);
675 CHECK_EQ(pending_send_status_
, MORE_DATA_TO_SEND
);
676 CHECK(!request_headers_
);
677 CHECK(!pending_send_data_
.get());
678 CHECK_EQ(io_state_
, STATE_IDLE
);
679 request_headers_
= request_headers
.Pass();
680 pending_send_status_
= send_status
;
681 session_
->EnqueueStreamWrite(
682 GetWeakPtr(), SYN_STREAM
,
683 scoped_ptr
<SpdyBufferProducer
>(
684 new SynStreamBufferProducer(GetWeakPtr())));
685 return ERR_IO_PENDING
;
688 void SpdyStream::SendData(IOBuffer
* data
,
690 SpdySendStatus send_status
) {
691 CHECK_NE(type_
, SPDY_PUSH_STREAM
);
692 CHECK_EQ(pending_send_status_
, MORE_DATA_TO_SEND
);
693 CHECK(io_state_
== STATE_OPEN
||
694 io_state_
== STATE_HALF_CLOSED_REMOTE
) << io_state_
;
695 CHECK(!pending_send_data_
.get());
696 pending_send_data_
= new DrainableIOBuffer(data
, length
);
697 pending_send_status_
= send_status
;
698 QueueNextDataFrame();
701 bool SpdyStream::GetSSLInfo(SSLInfo
* ssl_info
,
702 bool* was_npn_negotiated
,
703 NextProto
* protocol_negotiated
) {
704 return session_
->GetSSLInfo(
705 ssl_info
, was_npn_negotiated
, protocol_negotiated
);
708 void SpdyStream::PossiblyResumeIfSendStalled() {
709 if (IsLocallyClosed()) {
712 if (send_stalled_by_flow_control_
&& !session_
->IsSendStalled() &&
713 send_window_size_
> 0) {
714 net_log_
.AddEvent(NetLog::TYPE_HTTP2_STREAM_FLOW_CONTROL_UNSTALLED
,
715 NetLog::IntegerCallback("stream_id", stream_id_
));
716 send_stalled_by_flow_control_
= false;
717 QueueNextDataFrame();
721 bool SpdyStream::IsClosed() const {
722 return io_state_
== STATE_CLOSED
;
725 bool SpdyStream::IsLocallyClosed() const {
726 return io_state_
== STATE_HALF_CLOSED_LOCAL_UNCLAIMED
||
727 io_state_
== STATE_HALF_CLOSED_LOCAL
||
728 io_state_
== STATE_CLOSED
;
731 bool SpdyStream::IsIdle() const {
732 return io_state_
== STATE_IDLE
;
735 bool SpdyStream::IsOpen() const {
736 return io_state_
== STATE_OPEN
;
739 bool SpdyStream::IsReservedRemote() const {
740 return io_state_
== STATE_RESERVED_REMOTE
;
743 NextProto
SpdyStream::GetProtocol() const {
744 return session_
->protocol();
747 bool SpdyStream::GetLoadTimingInfo(LoadTimingInfo
* load_timing_info
) const {
751 return session_
->GetLoadTimingInfo(stream_id_
, load_timing_info
);
754 GURL
SpdyStream::GetUrlFromHeaders() const {
755 if (!request_headers_
)
758 return GetUrlFromHeaderBlock(
759 *request_headers_
, GetProtocolVersion(), type_
== SPDY_PUSH_STREAM
);
762 bool SpdyStream::HasUrlFromHeaders() const {
763 return !GetUrlFromHeaders().is_empty();
766 void SpdyStream::UpdateHistograms() {
767 // We need at least the receive timers to be filled in, as otherwise
768 // metrics can be bogus.
769 if (recv_first_byte_time_
.is_null() || recv_last_byte_time_
.is_null())
772 base::TimeTicks effective_send_time
;
773 if (type_
== SPDY_PUSH_STREAM
) {
774 // Push streams shouldn't have |send_time_| filled in.
775 DCHECK(send_time_
.is_null());
776 effective_send_time
= recv_first_byte_time_
;
778 // For non-push streams, we also need |send_time_| to be filled
780 if (send_time_
.is_null())
782 effective_send_time
= send_time_
;
785 UMA_HISTOGRAM_TIMES("Net.SpdyStreamTimeToFirstByte",
786 recv_first_byte_time_
- effective_send_time
);
787 UMA_HISTOGRAM_TIMES("Net.SpdyStreamDownloadTime",
788 recv_last_byte_time_
- recv_first_byte_time_
);
789 UMA_HISTOGRAM_TIMES("Net.SpdyStreamTime",
790 recv_last_byte_time_
- effective_send_time
);
792 UMA_HISTOGRAM_COUNTS("Net.SpdySendBytes", send_bytes_
);
793 UMA_HISTOGRAM_COUNTS("Net.SpdyRecvBytes", recv_bytes_
);
796 void SpdyStream::QueueNextDataFrame() {
797 // Until the request has been completely sent, we cannot be sure
798 // that our stream_id is correct.
799 CHECK(io_state_
== STATE_OPEN
||
800 io_state_
== STATE_HALF_CLOSED_REMOTE
) << io_state_
;
801 CHECK_GT(stream_id_
, 0u);
802 CHECK(pending_send_data_
.get());
803 // Only the final fame may have a length of 0.
804 if (pending_send_status_
== NO_MORE_DATA_TO_SEND
) {
805 CHECK_GE(pending_send_data_
->BytesRemaining(), 0);
807 CHECK_GT(pending_send_data_
->BytesRemaining(), 0);
810 SpdyDataFlags flags
=
811 (pending_send_status_
== NO_MORE_DATA_TO_SEND
) ?
812 DATA_FLAG_FIN
: DATA_FLAG_NONE
;
813 scoped_ptr
<SpdyBuffer
> data_buffer(
814 session_
->CreateDataBuffer(stream_id_
,
815 pending_send_data_
.get(),
816 pending_send_data_
->BytesRemaining(),
818 // We'll get called again by PossiblyResumeIfSendStalled().
822 if (session_
->flow_control_state() >= SpdySession::FLOW_CONTROL_STREAM
) {
823 DCHECK_GE(data_buffer
->GetRemainingSize(),
824 session_
->GetDataFrameMinimumSize());
825 size_t payload_size
=
826 data_buffer
->GetRemainingSize() - session_
->GetDataFrameMinimumSize();
827 DCHECK_LE(payload_size
, session_
->GetDataFrameMaximumPayload());
829 // Send window size is based on payload size, so nothing to do if this is
830 // just a FIN with no payload.
831 if (payload_size
!= 0) {
832 DecreaseSendWindowSize(static_cast<int32
>(payload_size
));
833 // This currently isn't strictly needed, since write frames are
834 // discarded only if the stream is about to be closed. But have it
835 // here anyway just in case this changes.
836 data_buffer
->AddConsumeCallback(
837 base::Bind(&SpdyStream::OnWriteBufferConsumed
,
838 GetWeakPtr(), payload_size
));
842 session_
->EnqueueStreamWrite(
844 scoped_ptr
<SpdyBufferProducer
>(
845 new SimpleBufferProducer(data_buffer
.Pass())));
848 int SpdyStream::MergeWithResponseHeaders(
849 const SpdyHeaderBlock
& new_response_headers
) {
850 if (new_response_headers
.find("transfer-encoding") !=
851 new_response_headers
.end()) {
852 session_
->ResetStream(stream_id_
, RST_STREAM_PROTOCOL_ERROR
,
853 "Received transfer-encoding header");
854 return ERR_SPDY_PROTOCOL_ERROR
;
857 for (SpdyHeaderBlock::const_iterator it
= new_response_headers
.begin();
858 it
!= new_response_headers
.end(); ++it
) {
859 // Disallow uppercase headers.
860 if (ContainsUppercaseAscii(it
->first
)) {
861 session_
->ResetStream(stream_id_
, RST_STREAM_PROTOCOL_ERROR
,
862 "Upper case characters in header: " + it
->first
);
863 return ERR_SPDY_PROTOCOL_ERROR
;
866 SpdyHeaderBlock::iterator it2
= response_headers_
.lower_bound(it
->first
);
867 // Disallow duplicate headers. This is just to be conservative.
868 if (it2
!= response_headers_
.end() && it2
->first
== it
->first
) {
869 session_
->ResetStream(stream_id_
, RST_STREAM_PROTOCOL_ERROR
,
870 "Duplicate header: " + it
->first
);
871 return ERR_SPDY_PROTOCOL_ERROR
;
874 response_headers_
.insert(it2
, *it
);
877 // If delegate_ is not yet attached, we'll call
878 // OnResponseHeadersUpdated() after the delegate gets attached to
881 // The call to OnResponseHeadersUpdated() below may delete |this|,
882 // so use |weak_this| to detect that.
883 base::WeakPtr
<SpdyStream
> weak_this
= GetWeakPtr();
885 SpdyResponseHeadersStatus status
=
886 delegate_
->OnResponseHeadersUpdated(response_headers_
);
887 if (status
== RESPONSE_HEADERS_ARE_INCOMPLETE
) {
888 // Since RESPONSE_HEADERS_ARE_INCOMPLETE was returned, we must not
891 // Incomplete headers are OK only for push streams.
892 if (type_
!= SPDY_PUSH_STREAM
) {
893 session_
->ResetStream(stream_id_
, RST_STREAM_PROTOCOL_ERROR
,
894 "Incomplete headers");
895 return ERR_INCOMPLETE_SPDY_HEADERS
;
897 } else if (weak_this
) {
898 response_headers_status_
= RESPONSE_HEADERS_ARE_COMPLETE
;
905 #define STATE_CASE(s) \
907 description = base::StringPrintf("%s (0x%08X)", #s, s); \
910 std::string
SpdyStream::DescribeState(State state
) {
911 std::string description
;
913 STATE_CASE(STATE_IDLE
);
914 STATE_CASE(STATE_OPEN
);
915 STATE_CASE(STATE_HALF_CLOSED_LOCAL_UNCLAIMED
);
916 STATE_CASE(STATE_HALF_CLOSED_LOCAL
);
917 STATE_CASE(STATE_CLOSED
);
919 description
= base::StringPrintf("Unknown state 0x%08X (%u)", state
,