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/logging.h"
10 #include "base/message_loop/message_loop.h"
11 #include "base/metrics/histogram_macros.h"
12 #include "base/strings/string_number_conversions.h"
13 #include "base/strings/stringprintf.h"
14 #include "base/values.h"
15 #include "net/spdy/spdy_buffer_producer.h"
16 #include "net/spdy/spdy_http_utils.h"
17 #include "net/spdy/spdy_session.h"
23 base::Value
* NetLogSpdyStreamErrorCallback(
24 SpdyStreamId stream_id
,
26 const std::string
* description
,
27 NetLogCaptureMode
/* capture_mode */) {
28 base::DictionaryValue
* dict
= new base::DictionaryValue();
29 dict
->SetInteger("stream_id", static_cast<int>(stream_id
));
30 dict
->SetInteger("status", status
);
31 dict
->SetString("description", *description
);
35 base::Value
* NetLogSpdyStreamWindowUpdateCallback(
36 SpdyStreamId stream_id
,
39 NetLogCaptureMode
/* capture_mode */) {
40 base::DictionaryValue
* dict
= new base::DictionaryValue();
41 dict
->SetInteger("stream_id", stream_id
);
42 dict
->SetInteger("delta", delta
);
43 dict
->SetInteger("window_size", window_size
);
47 bool ContainsUppercaseAscii(const std::string
& str
) {
48 for (std::string::const_iterator
i(str
.begin()); i
!= str
.end(); ++i
) {
49 if (*i
>= 'A' && *i
<= 'Z') {
58 // A wrapper around a stream that calls into ProduceSynStreamFrame().
59 class SpdyStream::SynStreamBufferProducer
: public SpdyBufferProducer
{
61 SynStreamBufferProducer(const base::WeakPtr
<SpdyStream
>& stream
)
63 DCHECK(stream_
.get());
66 ~SynStreamBufferProducer() override
{}
68 scoped_ptr
<SpdyBuffer
> ProduceBuffer() override
{
71 return scoped_ptr
<SpdyBuffer
>();
73 DCHECK_GT(stream_
->stream_id(), 0u);
74 return scoped_ptr
<SpdyBuffer
>(
75 new SpdyBuffer(stream_
->ProduceSynStreamFrame()));
79 const base::WeakPtr
<SpdyStream
> stream_
;
82 SpdyStream::SpdyStream(SpdyStreamType type
,
83 const base::WeakPtr
<SpdySession
>& session
,
85 RequestPriority priority
,
86 int32 initial_send_window_size
,
87 int32 max_recv_window_size
,
88 const BoundNetLog
& net_log
)
93 send_stalled_by_flow_control_(false),
94 send_window_size_(initial_send_window_size
),
95 max_recv_window_size_(max_recv_window_size
),
96 recv_window_size_(max_recv_window_size
),
97 unacked_recv_window_bytes_(0),
100 pending_send_status_(MORE_DATA_TO_SEND
),
101 request_time_(base::Time::Now()),
102 response_headers_status_(RESPONSE_HEADERS_ARE_INCOMPLETE
),
103 io_state_(STATE_IDLE
),
104 response_status_(OK
),
106 raw_received_bytes_(0),
109 write_handler_guard_(false),
110 weak_ptr_factory_(this) {
111 CHECK(type_
== SPDY_BIDIRECTIONAL_STREAM
||
112 type_
== SPDY_REQUEST_RESPONSE_STREAM
||
113 type_
== SPDY_PUSH_STREAM
);
114 CHECK_GE(priority_
, MINIMUM_PRIORITY
);
115 CHECK_LE(priority_
, MAXIMUM_PRIORITY
);
118 SpdyStream::~SpdyStream() {
119 CHECK(!write_handler_guard_
);
123 void SpdyStream::SetDelegate(Delegate
* delegate
) {
126 delegate_
= delegate
;
128 CHECK(io_state_
== STATE_IDLE
||
129 io_state_
== STATE_HALF_CLOSED_LOCAL_UNCLAIMED
||
130 io_state_
== STATE_RESERVED_REMOTE
);
132 if (io_state_
== STATE_HALF_CLOSED_LOCAL_UNCLAIMED
) {
133 DCHECK_EQ(type_
, SPDY_PUSH_STREAM
);
134 base::MessageLoop::current()->PostTask(
136 base::Bind(&SpdyStream::PushedStreamReplay
, GetWeakPtr()));
140 void SpdyStream::PushedStreamReplay() {
141 DCHECK_EQ(type_
, SPDY_PUSH_STREAM
);
142 DCHECK_NE(stream_id_
, 0u);
143 CHECK_EQ(stream_id_
% 2, 0u);
145 CHECK_EQ(io_state_
, STATE_HALF_CLOSED_LOCAL_UNCLAIMED
);
146 io_state_
= STATE_HALF_CLOSED_LOCAL
;
148 // The delegate methods called below may delete |this|, so use
149 // |weak_this| to detect that.
150 base::WeakPtr
<SpdyStream
> weak_this
= GetWeakPtr();
153 SpdyResponseHeadersStatus status
=
154 delegate_
->OnResponseHeadersUpdated(response_headers_
);
155 if (status
== RESPONSE_HEADERS_ARE_INCOMPLETE
) {
156 // Since RESPONSE_HEADERS_ARE_INCOMPLETE was returned, we must not
157 // have been closed. Since we don't have complete headers, assume
158 // we're waiting for another HEADERS frame, and we had better not
159 // have any pending data frames.
161 if (!pending_recv_data_
.empty()) {
162 LogStreamError(ERR_SPDY_PROTOCOL_ERROR
,
163 "Data received with incomplete headers.");
164 session_
->CloseActiveStream(stream_id_
, ERR_SPDY_PROTOCOL_ERROR
);
169 // OnResponseHeadersUpdated() may have closed |this|.
173 response_headers_status_
= RESPONSE_HEADERS_ARE_COMPLETE
;
175 while (!pending_recv_data_
.empty()) {
176 // Take ownership of the first element of |pending_recv_data_|.
177 scoped_ptr
<SpdyBuffer
> buffer(pending_recv_data_
.front());
178 pending_recv_data_
.weak_erase(pending_recv_data_
.begin());
180 bool eof
= (buffer
== NULL
);
183 delegate_
->OnDataReceived(buffer
.Pass());
185 // OnDataReceived() may have closed |this|.
190 DCHECK(pending_recv_data_
.empty());
191 session_
->CloseActiveStream(stream_id_
, OK
);
193 // |pending_recv_data_| is invalid at this point.
199 scoped_ptr
<SpdyFrame
> SpdyStream::ProduceSynStreamFrame() {
200 CHECK_EQ(io_state_
, STATE_IDLE
);
201 CHECK(request_headers_
);
202 CHECK_GT(stream_id_
, 0u);
204 SpdyControlFlags flags
=
205 (pending_send_status_
== NO_MORE_DATA_TO_SEND
) ?
206 CONTROL_FLAG_FIN
: CONTROL_FLAG_NONE
;
207 scoped_ptr
<SpdyFrame
> frame(session_
->CreateSynStream(
208 stream_id_
, priority_
, flags
, *request_headers_
));
209 send_time_
= base::TimeTicks::Now();
213 void SpdyStream::DetachDelegate() {
219 void SpdyStream::AdjustSendWindowSize(int32 delta_window_size
) {
220 DCHECK_GE(session_
->flow_control_state(), SpdySession::FLOW_CONTROL_STREAM
);
225 // Check for wraparound.
226 if (send_window_size_
> 0) {
227 DCHECK_LE(delta_window_size
, kint32max
- send_window_size_
);
229 if (send_window_size_
< 0) {
230 DCHECK_GE(delta_window_size
, kint32min
- send_window_size_
);
232 send_window_size_
+= delta_window_size
;
233 PossiblyResumeIfSendStalled();
236 void SpdyStream::OnWriteBufferConsumed(
237 size_t frame_payload_size
,
239 SpdyBuffer::ConsumeSource consume_source
) {
240 DCHECK_GE(session_
->flow_control_state(), SpdySession::FLOW_CONTROL_STREAM
);
241 if (consume_source
== SpdyBuffer::DISCARD
) {
242 // If we're discarding a frame or part of it, increase the send
243 // window by the number of discarded bytes. (Although if we're
244 // discarding part of a frame, it's probably because of a write
245 // error and we'll be tearing down the stream soon.)
246 size_t remaining_payload_bytes
= std::min(consume_size
, frame_payload_size
);
247 DCHECK_GT(remaining_payload_bytes
, 0u);
248 IncreaseSendWindowSize(static_cast<int32
>(remaining_payload_bytes
));
250 // For consumed bytes, the send window is increased when we receive
251 // a WINDOW_UPDATE frame.
254 void SpdyStream::IncreaseSendWindowSize(int32 delta_window_size
) {
255 DCHECK_GE(session_
->flow_control_state(), SpdySession::FLOW_CONTROL_STREAM
);
256 DCHECK_GE(delta_window_size
, 1);
258 // Ignore late WINDOW_UPDATEs.
262 if (send_window_size_
> 0) {
263 // Check for overflow.
264 int32 max_delta_window_size
= kint32max
- send_window_size_
;
265 if (delta_window_size
> max_delta_window_size
) {
266 std::string desc
= base::StringPrintf(
267 "Received WINDOW_UPDATE [delta: %d] for stream %d overflows "
268 "send_window_size_ [current: %d]", delta_window_size
, stream_id_
,
270 session_
->ResetStream(stream_id_
, RST_STREAM_FLOW_CONTROL_ERROR
, desc
);
275 send_window_size_
+= delta_window_size
;
278 NetLog::TYPE_HTTP2_STREAM_UPDATE_SEND_WINDOW
,
279 base::Bind(&NetLogSpdyStreamWindowUpdateCallback
, stream_id_
,
280 delta_window_size
, send_window_size_
));
282 PossiblyResumeIfSendStalled();
285 void SpdyStream::DecreaseSendWindowSize(int32 delta_window_size
) {
286 DCHECK_GE(session_
->flow_control_state(), SpdySession::FLOW_CONTROL_STREAM
);
291 // We only call this method when sending a frame. Therefore,
292 // |delta_window_size| should be within the valid frame size range.
293 DCHECK_GE(delta_window_size
, 1);
294 DCHECK_LE(delta_window_size
, kMaxSpdyFrameChunkSize
);
296 // |send_window_size_| should have been at least |delta_window_size| for
297 // this call to happen.
298 DCHECK_GE(send_window_size_
, delta_window_size
);
300 send_window_size_
-= delta_window_size
;
303 NetLog::TYPE_HTTP2_STREAM_UPDATE_SEND_WINDOW
,
304 base::Bind(&NetLogSpdyStreamWindowUpdateCallback
, stream_id_
,
305 -delta_window_size
, send_window_size_
));
308 void SpdyStream::OnReadBufferConsumed(
310 SpdyBuffer::ConsumeSource consume_source
) {
311 DCHECK_GE(session_
->flow_control_state(), SpdySession::FLOW_CONTROL_STREAM
);
312 DCHECK_GE(consume_size
, 1u);
313 DCHECK_LE(consume_size
, static_cast<size_t>(kint32max
));
314 IncreaseRecvWindowSize(static_cast<int32
>(consume_size
));
317 void SpdyStream::IncreaseRecvWindowSize(int32 delta_window_size
) {
318 DCHECK_GE(session_
->flow_control_state(), SpdySession::FLOW_CONTROL_STREAM
);
320 // By the time a read is processed by the delegate, this stream may
321 // already be inactive.
322 if (!session_
->IsStreamActive(stream_id_
))
325 DCHECK_GE(unacked_recv_window_bytes_
, 0);
326 DCHECK_GE(recv_window_size_
, unacked_recv_window_bytes_
);
327 DCHECK_GE(delta_window_size
, 1);
328 // Check for overflow.
329 DCHECK_LE(delta_window_size
, kint32max
- recv_window_size_
);
331 recv_window_size_
+= delta_window_size
;
333 NetLog::TYPE_HTTP2_STREAM_UPDATE_RECV_WINDOW
,
334 base::Bind(&NetLogSpdyStreamWindowUpdateCallback
, stream_id_
,
335 delta_window_size
, recv_window_size_
));
337 unacked_recv_window_bytes_
+= delta_window_size
;
338 if (unacked_recv_window_bytes_
> max_recv_window_size_
/ 2) {
339 session_
->SendStreamWindowUpdate(
340 stream_id_
, static_cast<uint32
>(unacked_recv_window_bytes_
));
341 unacked_recv_window_bytes_
= 0;
345 void SpdyStream::DecreaseRecvWindowSize(int32 delta_window_size
) {
346 DCHECK(session_
->IsStreamActive(stream_id_
));
347 DCHECK_GE(session_
->flow_control_state(), SpdySession::FLOW_CONTROL_STREAM
);
348 DCHECK_GE(delta_window_size
, 1);
350 // Since we never decrease the initial receive window size,
351 // |delta_window_size| should never cause |recv_window_size_| to go
352 // negative. If we do, the receive window isn't being respected.
353 if (delta_window_size
> recv_window_size_
) {
354 session_
->ResetStream(
355 stream_id_
, RST_STREAM_PROTOCOL_ERROR
,
356 "delta_window_size is " + base::IntToString(delta_window_size
) +
357 " in DecreaseRecvWindowSize, which is larger than the receive " +
358 "window size of " + base::IntToString(recv_window_size_
));
362 recv_window_size_
-= delta_window_size
;
364 NetLog::TYPE_HTTP2_STREAM_UPDATE_RECV_WINDOW
,
365 base::Bind(&NetLogSpdyStreamWindowUpdateCallback
, stream_id_
,
366 -delta_window_size
, recv_window_size_
));
369 int SpdyStream::GetPeerAddress(IPEndPoint
* address
) const {
370 return session_
->GetPeerAddress(address
);
373 int SpdyStream::GetLocalAddress(IPEndPoint
* address
) const {
374 return session_
->GetLocalAddress(address
);
377 bool SpdyStream::WasEverUsed() const {
378 return session_
->WasEverUsed();
381 base::Time
SpdyStream::GetRequestTime() const {
382 return request_time_
;
385 void SpdyStream::SetRequestTime(base::Time t
) {
389 int SpdyStream::OnInitialResponseHeadersReceived(
390 const SpdyHeaderBlock
& initial_response_headers
,
391 base::Time response_time
,
392 base::TimeTicks recv_first_byte_time
) {
393 // SpdySession guarantees that this is called at most once.
394 CHECK(response_headers_
.empty());
396 // Check to make sure that we don't receive the response headers
397 // before we're ready for it.
399 case SPDY_BIDIRECTIONAL_STREAM
:
400 // For a bidirectional stream, we're ready for the response
401 // headers once we've finished sending the request headers.
402 if (io_state_
== STATE_IDLE
) {
403 session_
->ResetStream(stream_id_
, RST_STREAM_PROTOCOL_ERROR
,
404 "Response received before request sent");
405 return ERR_SPDY_PROTOCOL_ERROR
;
409 case SPDY_REQUEST_RESPONSE_STREAM
:
410 // For a request/response stream, we're ready for the response
411 // headers once we've finished sending the request headers.
412 if (io_state_
== STATE_IDLE
) {
413 session_
->ResetStream(stream_id_
, RST_STREAM_PROTOCOL_ERROR
,
414 "Response received before request sent");
415 return ERR_SPDY_PROTOCOL_ERROR
;
419 case SPDY_PUSH_STREAM
:
420 // Push streams transition to a locally half-closed state upon headers.
421 // We must continue to buffer data while waiting for a call to
422 // SetDelegate() (which may not ever happen).
423 CHECK_EQ(io_state_
, STATE_RESERVED_REMOTE
);
425 io_state_
= STATE_HALF_CLOSED_LOCAL_UNCLAIMED
;
427 io_state_
= STATE_HALF_CLOSED_LOCAL
;
432 DCHECK_NE(io_state_
, STATE_IDLE
);
434 response_time_
= response_time
;
435 recv_first_byte_time_
= recv_first_byte_time
;
436 return MergeWithResponseHeaders(initial_response_headers
);
439 int SpdyStream::OnAdditionalResponseHeadersReceived(
440 const SpdyHeaderBlock
& additional_response_headers
) {
441 if (type_
== SPDY_REQUEST_RESPONSE_STREAM
) {
442 session_
->ResetStream(
443 stream_id_
, RST_STREAM_PROTOCOL_ERROR
,
444 "Additional headers received for request/response stream");
445 return ERR_SPDY_PROTOCOL_ERROR
;
446 } else if (type_
== SPDY_PUSH_STREAM
&&
447 response_headers_status_
== RESPONSE_HEADERS_ARE_COMPLETE
) {
448 session_
->ResetStream(
449 stream_id_
, RST_STREAM_PROTOCOL_ERROR
,
450 "Additional headers received for push stream");
451 return ERR_SPDY_PROTOCOL_ERROR
;
453 return MergeWithResponseHeaders(additional_response_headers
);
456 void SpdyStream::OnPushPromiseHeadersReceived(const SpdyHeaderBlock
& headers
) {
457 CHECK(!request_headers_
.get());
458 CHECK_EQ(io_state_
, STATE_IDLE
);
459 CHECK_EQ(type_
, SPDY_PUSH_STREAM
);
462 io_state_
= STATE_RESERVED_REMOTE
;
463 request_headers_
.reset(new SpdyHeaderBlock(headers
));
466 void SpdyStream::OnDataReceived(scoped_ptr
<SpdyBuffer
> buffer
) {
467 DCHECK(session_
->IsStreamActive(stream_id_
));
469 // If we're still buffering data for a push stream, we will do the
470 // check for data received with incomplete headers in
471 // PushedStreamReplayData().
472 if (io_state_
== STATE_HALF_CLOSED_LOCAL_UNCLAIMED
) {
473 DCHECK_EQ(type_
, SPDY_PUSH_STREAM
);
474 // It should be valid for this to happen in the server push case.
475 // We'll return received data when delegate gets attached to the stream.
477 pending_recv_data_
.push_back(buffer
.release());
479 pending_recv_data_
.push_back(NULL
);
480 // Note: we leave the stream open in the session until the stream
486 // If we have response headers but the delegate has indicated that
487 // it's still incomplete, then that's a protocol error.
488 if (response_headers_status_
== RESPONSE_HEADERS_ARE_INCOMPLETE
) {
489 LogStreamError(ERR_SPDY_PROTOCOL_ERROR
,
490 "Data received with incomplete headers.");
491 session_
->CloseActiveStream(stream_id_
, ERR_SPDY_PROTOCOL_ERROR
);
498 if (io_state_
== STATE_OPEN
) {
499 io_state_
= STATE_HALF_CLOSED_REMOTE
;
500 } else if (io_state_
== STATE_HALF_CLOSED_LOCAL
) {
501 io_state_
= STATE_CLOSED
;
503 session_
->CloseActiveStream(stream_id_
, OK
);
505 NOTREACHED() << io_state_
;
510 size_t length
= buffer
->GetRemainingSize();
511 DCHECK_LE(length
, session_
->GetDataFrameMaximumPayload());
512 if (session_
->flow_control_state() >= SpdySession::FLOW_CONTROL_STREAM
) {
513 DecreaseRecvWindowSize(static_cast<int32
>(length
));
514 buffer
->AddConsumeCallback(
515 base::Bind(&SpdyStream::OnReadBufferConsumed
, GetWeakPtr()));
518 // Track our bandwidth.
519 recv_bytes_
+= length
;
520 recv_last_byte_time_
= base::TimeTicks::Now();
523 delegate_
->OnDataReceived(buffer
.Pass());
526 void SpdyStream::OnPaddingConsumed(size_t len
) {
527 if (session_
->flow_control_state() >= SpdySession::FLOW_CONTROL_STREAM
) {
528 // Decrease window size because padding bytes are received.
529 // Increase window size because padding bytes are consumed (by discarding).
530 // Net result: |unacked_recv_window_bytes_| increases by |len|,
531 // |recv_window_size_| does not change.
532 DecreaseRecvWindowSize(static_cast<int32
>(len
));
533 IncreaseRecvWindowSize(static_cast<int32
>(len
));
537 void SpdyStream::OnFrameWriteComplete(SpdyFrameType frame_type
,
539 DCHECK_NE(type_
, SPDY_PUSH_STREAM
);
541 if (frame_size
< session_
->GetFrameMinimumSize() ||
542 frame_size
> session_
->GetFrameMaximumSize()) {
546 CHECK(frame_type
== SYN_STREAM
||
547 frame_type
== DATA
) << frame_type
;
549 int result
= (frame_type
== SYN_STREAM
) ?
550 OnRequestHeadersSent() : OnDataSent(frame_size
);
551 if (result
== ERR_IO_PENDING
) {
552 // The write operation hasn't completed yet.
556 if (pending_send_status_
== NO_MORE_DATA_TO_SEND
) {
557 if(io_state_
== STATE_OPEN
) {
558 io_state_
= STATE_HALF_CLOSED_LOCAL
;
559 } else if(io_state_
== STATE_HALF_CLOSED_REMOTE
) {
560 io_state_
= STATE_CLOSED
;
562 NOTREACHED() << io_state_
;
565 // Notify delegate of write completion. Must not destroy |this|.
568 base::WeakPtr
<SpdyStream
> weak_this
= GetWeakPtr();
569 write_handler_guard_
= true;
570 if (frame_type
== SYN_STREAM
) {
571 delegate_
->OnRequestHeadersSent();
573 delegate_
->OnDataSent();
576 write_handler_guard_
= false;
579 if (io_state_
== STATE_CLOSED
) {
581 session_
->CloseActiveStream(stream_id_
, OK
);
585 int SpdyStream::OnRequestHeadersSent() {
586 CHECK_EQ(io_state_
, STATE_IDLE
);
587 CHECK_NE(stream_id_
, 0u);
589 io_state_
= STATE_OPEN
;
593 int SpdyStream::OnDataSent(size_t frame_size
) {
594 CHECK(io_state_
== STATE_OPEN
||
595 io_state_
== STATE_HALF_CLOSED_REMOTE
) << io_state_
;
597 size_t frame_payload_size
= frame_size
- session_
->GetDataFrameMinimumSize();
599 CHECK_GE(frame_size
, session_
->GetDataFrameMinimumSize());
600 CHECK_LE(frame_payload_size
, session_
->GetDataFrameMaximumPayload());
602 send_bytes_
+= frame_payload_size
;
604 // If more data is available to send, dispatch it and
605 // return that the write operation is still ongoing.
606 pending_send_data_
->DidConsume(frame_payload_size
);
607 if (pending_send_data_
->BytesRemaining() > 0) {
608 QueueNextDataFrame();
609 return ERR_IO_PENDING
;
611 pending_send_data_
= NULL
;
616 SpdyMajorVersion
SpdyStream::GetProtocolVersion() const {
617 return session_
->GetProtocolVersion();
620 void SpdyStream::LogStreamError(int status
, const std::string
& description
) {
621 net_log_
.AddEvent(NetLog::TYPE_HTTP2_STREAM_ERROR
,
622 base::Bind(&NetLogSpdyStreamErrorCallback
, stream_id_
,
623 status
, &description
));
626 void SpdyStream::OnClose(int status
) {
627 // In most cases, the stream should already be CLOSED. The exception is when a
628 // SpdySession is shutting down while the stream is in an intermediate state.
629 io_state_
= STATE_CLOSED
;
630 response_status_
= status
;
631 Delegate
* delegate
= delegate_
;
634 delegate
->OnClose(status
);
635 // Unset |stream_id_| last so that the delegate can look it up.
639 void SpdyStream::Cancel() {
640 // We may be called again from a delegate's OnClose().
641 if (io_state_
== STATE_CLOSED
)
644 if (stream_id_
!= 0) {
645 session_
->ResetStream(stream_id_
, RST_STREAM_CANCEL
, std::string());
647 session_
->CloseCreatedStream(GetWeakPtr(), RST_STREAM_CANCEL
);
649 // |this| is invalid at this point.
652 void SpdyStream::Close() {
653 // We may be called again from a delegate's OnClose().
654 if (io_state_
== STATE_CLOSED
)
657 if (stream_id_
!= 0) {
658 session_
->CloseActiveStream(stream_id_
, OK
);
660 session_
->CloseCreatedStream(GetWeakPtr(), OK
);
662 // |this| is invalid at this point.
665 base::WeakPtr
<SpdyStream
> SpdyStream::GetWeakPtr() {
666 return weak_ptr_factory_
.GetWeakPtr();
669 int SpdyStream::SendRequestHeaders(scoped_ptr
<SpdyHeaderBlock
> request_headers
,
670 SpdySendStatus send_status
) {
671 CHECK_NE(type_
, SPDY_PUSH_STREAM
);
672 CHECK_EQ(pending_send_status_
, MORE_DATA_TO_SEND
);
673 CHECK(!request_headers_
);
674 CHECK(!pending_send_data_
.get());
675 CHECK_EQ(io_state_
, STATE_IDLE
);
676 request_headers_
= request_headers
.Pass();
677 pending_send_status_
= send_status
;
678 session_
->EnqueueStreamWrite(
679 GetWeakPtr(), SYN_STREAM
,
680 scoped_ptr
<SpdyBufferProducer
>(
681 new SynStreamBufferProducer(GetWeakPtr())));
682 return ERR_IO_PENDING
;
685 void SpdyStream::SendData(IOBuffer
* data
,
687 SpdySendStatus send_status
) {
688 CHECK_NE(type_
, SPDY_PUSH_STREAM
);
689 CHECK_EQ(pending_send_status_
, MORE_DATA_TO_SEND
);
690 CHECK(io_state_
== STATE_OPEN
||
691 io_state_
== STATE_HALF_CLOSED_REMOTE
) << io_state_
;
692 CHECK(!pending_send_data_
.get());
693 pending_send_data_
= new DrainableIOBuffer(data
, length
);
694 pending_send_status_
= send_status
;
695 QueueNextDataFrame();
698 bool SpdyStream::GetSSLInfo(SSLInfo
* ssl_info
,
699 bool* was_npn_negotiated
,
700 NextProto
* protocol_negotiated
) {
701 return session_
->GetSSLInfo(
702 ssl_info
, was_npn_negotiated
, protocol_negotiated
);
705 bool SpdyStream::GetSSLCertRequestInfo(SSLCertRequestInfo
* cert_request_info
) {
706 return session_
->GetSSLCertRequestInfo(cert_request_info
);
709 void SpdyStream::PossiblyResumeIfSendStalled() {
710 if (IsLocallyClosed()) {
713 if (send_stalled_by_flow_control_
&& !session_
->IsSendStalled() &&
714 send_window_size_
> 0) {
715 net_log_
.AddEvent(NetLog::TYPE_HTTP2_STREAM_FLOW_CONTROL_UNSTALLED
,
716 NetLog::IntegerCallback("stream_id", stream_id_
));
717 send_stalled_by_flow_control_
= false;
718 QueueNextDataFrame();
722 bool SpdyStream::IsClosed() const {
723 return io_state_
== STATE_CLOSED
;
726 bool SpdyStream::IsLocallyClosed() const {
727 return io_state_
== STATE_HALF_CLOSED_LOCAL_UNCLAIMED
||
728 io_state_
== STATE_HALF_CLOSED_LOCAL
||
729 io_state_
== STATE_CLOSED
;
732 bool SpdyStream::IsIdle() const {
733 return io_state_
== STATE_IDLE
;
736 bool SpdyStream::IsOpen() const {
737 return io_state_
== STATE_OPEN
;
740 bool SpdyStream::IsReservedRemote() const {
741 return io_state_
== STATE_RESERVED_REMOTE
;
744 NextProto
SpdyStream::GetProtocol() const {
745 return session_
->protocol();
748 bool SpdyStream::GetLoadTimingInfo(LoadTimingInfo
* load_timing_info
) const {
752 return session_
->GetLoadTimingInfo(stream_id_
, load_timing_info
);
755 GURL
SpdyStream::GetUrlFromHeaders() const {
756 if (!request_headers_
)
759 return GetUrlFromHeaderBlock(
760 *request_headers_
, GetProtocolVersion(), type_
== SPDY_PUSH_STREAM
);
763 bool SpdyStream::HasUrlFromHeaders() const {
764 return !GetUrlFromHeaders().is_empty();
767 void SpdyStream::UpdateHistograms() {
768 // We need at least the receive timers to be filled in, as otherwise
769 // metrics can be bogus.
770 if (recv_first_byte_time_
.is_null() || recv_last_byte_time_
.is_null())
773 base::TimeTicks effective_send_time
;
774 if (type_
== SPDY_PUSH_STREAM
) {
775 // Push streams shouldn't have |send_time_| filled in.
776 DCHECK(send_time_
.is_null());
777 effective_send_time
= recv_first_byte_time_
;
779 // For non-push streams, we also need |send_time_| to be filled
781 if (send_time_
.is_null())
783 effective_send_time
= send_time_
;
786 UMA_HISTOGRAM_TIMES("Net.SpdyStreamTimeToFirstByte",
787 recv_first_byte_time_
- effective_send_time
);
788 UMA_HISTOGRAM_TIMES("Net.SpdyStreamDownloadTime",
789 recv_last_byte_time_
- recv_first_byte_time_
);
790 UMA_HISTOGRAM_TIMES("Net.SpdyStreamTime",
791 recv_last_byte_time_
- effective_send_time
);
793 UMA_HISTOGRAM_COUNTS("Net.SpdySendBytes", send_bytes_
);
794 UMA_HISTOGRAM_COUNTS("Net.SpdyRecvBytes", recv_bytes_
);
797 void SpdyStream::QueueNextDataFrame() {
798 // Until the request has been completely sent, we cannot be sure
799 // that our stream_id is correct.
800 CHECK(io_state_
== STATE_OPEN
||
801 io_state_
== STATE_HALF_CLOSED_REMOTE
) << io_state_
;
802 CHECK_GT(stream_id_
, 0u);
803 CHECK(pending_send_data_
.get());
804 // Only the final fame may have a length of 0.
805 if (pending_send_status_
== NO_MORE_DATA_TO_SEND
) {
806 CHECK_GE(pending_send_data_
->BytesRemaining(), 0);
808 CHECK_GT(pending_send_data_
->BytesRemaining(), 0);
811 SpdyDataFlags flags
=
812 (pending_send_status_
== NO_MORE_DATA_TO_SEND
) ?
813 DATA_FLAG_FIN
: DATA_FLAG_NONE
;
814 scoped_ptr
<SpdyBuffer
> data_buffer(
815 session_
->CreateDataBuffer(stream_id_
,
816 pending_send_data_
.get(),
817 pending_send_data_
->BytesRemaining(),
819 // We'll get called again by PossiblyResumeIfSendStalled().
823 if (session_
->flow_control_state() >= SpdySession::FLOW_CONTROL_STREAM
) {
824 DCHECK_GE(data_buffer
->GetRemainingSize(),
825 session_
->GetDataFrameMinimumSize());
826 size_t payload_size
=
827 data_buffer
->GetRemainingSize() - session_
->GetDataFrameMinimumSize();
828 DCHECK_LE(payload_size
, session_
->GetDataFrameMaximumPayload());
830 // Send window size is based on payload size, so nothing to do if this is
831 // just a FIN with no payload.
832 if (payload_size
!= 0) {
833 DecreaseSendWindowSize(static_cast<int32
>(payload_size
));
834 // This currently isn't strictly needed, since write frames are
835 // discarded only if the stream is about to be closed. But have it
836 // here anyway just in case this changes.
837 data_buffer
->AddConsumeCallback(
838 base::Bind(&SpdyStream::OnWriteBufferConsumed
,
839 GetWeakPtr(), payload_size
));
843 session_
->EnqueueStreamWrite(
845 scoped_ptr
<SpdyBufferProducer
>(
846 new SimpleBufferProducer(data_buffer
.Pass())));
849 int SpdyStream::MergeWithResponseHeaders(
850 const SpdyHeaderBlock
& new_response_headers
) {
851 if (new_response_headers
.find("transfer-encoding") !=
852 new_response_headers
.end()) {
853 session_
->ResetStream(stream_id_
, RST_STREAM_PROTOCOL_ERROR
,
854 "Received transfer-encoding header");
855 return ERR_SPDY_PROTOCOL_ERROR
;
858 for (SpdyHeaderBlock::const_iterator it
= new_response_headers
.begin();
859 it
!= new_response_headers
.end(); ++it
) {
860 // Disallow uppercase headers.
861 if (ContainsUppercaseAscii(it
->first
)) {
862 session_
->ResetStream(stream_id_
, RST_STREAM_PROTOCOL_ERROR
,
863 "Upper case characters in header: " + it
->first
);
864 return ERR_SPDY_PROTOCOL_ERROR
;
867 SpdyHeaderBlock::iterator it2
= response_headers_
.lower_bound(it
->first
);
868 // Disallow duplicate headers. This is just to be conservative.
869 if (it2
!= response_headers_
.end() && it2
->first
== it
->first
) {
870 session_
->ResetStream(stream_id_
, RST_STREAM_PROTOCOL_ERROR
,
871 "Duplicate header: " + it
->first
);
872 return ERR_SPDY_PROTOCOL_ERROR
;
875 response_headers_
.insert(it2
, *it
);
878 // If delegate_ is not yet attached, we'll call
879 // OnResponseHeadersUpdated() after the delegate gets attached to
882 // The call to OnResponseHeadersUpdated() below may delete |this|,
883 // so use |weak_this| to detect that.
884 base::WeakPtr
<SpdyStream
> weak_this
= GetWeakPtr();
886 SpdyResponseHeadersStatus status
=
887 delegate_
->OnResponseHeadersUpdated(response_headers_
);
888 if (status
== RESPONSE_HEADERS_ARE_INCOMPLETE
) {
889 // Since RESPONSE_HEADERS_ARE_INCOMPLETE was returned, we must not
892 // Incomplete headers are OK only for push streams.
893 if (type_
!= SPDY_PUSH_STREAM
) {
894 session_
->ResetStream(stream_id_
, RST_STREAM_PROTOCOL_ERROR
,
895 "Incomplete headers");
896 return ERR_INCOMPLETE_SPDY_HEADERS
;
898 } else if (weak_this
) {
899 response_headers_status_
= RESPONSE_HEADERS_ARE_COMPLETE
;
906 #define STATE_CASE(s) \
908 description = base::StringPrintf("%s (0x%08X)", #s, s); \
911 std::string
SpdyStream::DescribeState(State state
) {
912 std::string description
;
914 STATE_CASE(STATE_IDLE
);
915 STATE_CASE(STATE_OPEN
);
916 STATE_CASE(STATE_HALF_CLOSED_LOCAL_UNCLAIMED
);
917 STATE_CASE(STATE_HALF_CLOSED_LOCAL
);
918 STATE_CASE(STATE_CLOSED
);
920 description
= base::StringPrintf("Unknown state 0x%08X (%u)", state
,