Roll src/third_party/skia fd0ecf4:d803cda
[chromium-blink-merge.git] / net / spdy / spdy_stream.cc
blob7f2936424fc4cca0ad8b5849d1a3af01ed82fbe4
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"
7 #include "base/bind.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"
19 namespace net {
21 namespace {
23 base::Value* NetLogSpdyStreamErrorCallback(SpdyStreamId stream_id,
24 int status,
25 const std::string* description,
26 NetLog::LogLevel /* log_level */) {
27 base::DictionaryValue* dict = new base::DictionaryValue();
28 dict->SetInteger("stream_id", static_cast<int>(stream_id));
29 dict->SetInteger("status", status);
30 dict->SetString("description", *description);
31 return dict;
34 base::Value* NetLogSpdyStreamWindowUpdateCallback(
35 SpdyStreamId stream_id,
36 int32 delta,
37 int32 window_size,
38 NetLog::LogLevel /* log_level */) {
39 base::DictionaryValue* dict = new base::DictionaryValue();
40 dict->SetInteger("stream_id", stream_id);
41 dict->SetInteger("delta", delta);
42 dict->SetInteger("window_size", window_size);
43 return dict;
46 bool ContainsUppercaseAscii(const std::string& str) {
47 for (std::string::const_iterator i(str.begin()); i != str.end(); ++i) {
48 if (*i >= 'A' && *i <= 'Z') {
49 return true;
52 return false;
55 } // namespace
57 // A wrapper around a stream that calls into ProduceSynStreamFrame().
58 class SpdyStream::SynStreamBufferProducer : public SpdyBufferProducer {
59 public:
60 SynStreamBufferProducer(const base::WeakPtr<SpdyStream>& stream)
61 : stream_(stream) {
62 DCHECK(stream_.get());
65 ~SynStreamBufferProducer() override {}
67 scoped_ptr<SpdyBuffer> ProduceBuffer() override {
68 if (!stream_.get()) {
69 NOTREACHED();
70 return scoped_ptr<SpdyBuffer>();
72 DCHECK_GT(stream_->stream_id(), 0u);
73 return scoped_ptr<SpdyBuffer>(
74 new SpdyBuffer(stream_->ProduceSynStreamFrame()));
77 private:
78 const base::WeakPtr<SpdyStream> stream_;
81 SpdyStream::SpdyStream(SpdyStreamType type,
82 const base::WeakPtr<SpdySession>& session,
83 const GURL& url,
84 RequestPriority priority,
85 int32 initial_send_window_size,
86 int32 max_recv_window_size,
87 const BoundNetLog& net_log)
88 : type_(type),
89 stream_id_(0),
90 url_(url),
91 priority_(priority),
92 send_stalled_by_flow_control_(false),
93 send_window_size_(initial_send_window_size),
94 max_recv_window_size_(max_recv_window_size),
95 recv_window_size_(max_recv_window_size),
96 unacked_recv_window_bytes_(0),
97 session_(session),
98 delegate_(NULL),
99 pending_send_status_(MORE_DATA_TO_SEND),
100 request_time_(base::Time::Now()),
101 response_headers_status_(RESPONSE_HEADERS_ARE_INCOMPLETE),
102 io_state_(STATE_IDLE),
103 response_status_(OK),
104 net_log_(net_log),
105 raw_received_bytes_(0),
106 send_bytes_(0),
107 recv_bytes_(0),
108 write_handler_guard_(false),
109 weak_ptr_factory_(this) {
110 CHECK(type_ == SPDY_BIDIRECTIONAL_STREAM ||
111 type_ == SPDY_REQUEST_RESPONSE_STREAM ||
112 type_ == SPDY_PUSH_STREAM);
113 CHECK_GE(priority_, MINIMUM_PRIORITY);
114 CHECK_LE(priority_, MAXIMUM_PRIORITY);
117 SpdyStream::~SpdyStream() {
118 CHECK(!write_handler_guard_);
119 UpdateHistograms();
122 void SpdyStream::SetDelegate(Delegate* delegate) {
123 CHECK(!delegate_);
124 CHECK(delegate);
125 delegate_ = delegate;
127 CHECK(io_state_ == STATE_IDLE ||
128 io_state_ == STATE_HALF_CLOSED_LOCAL_UNCLAIMED ||
129 io_state_ == STATE_RESERVED_REMOTE);
131 if (io_state_ == STATE_HALF_CLOSED_LOCAL_UNCLAIMED) {
132 DCHECK_EQ(type_, SPDY_PUSH_STREAM);
133 base::MessageLoop::current()->PostTask(
134 FROM_HERE,
135 base::Bind(&SpdyStream::PushedStreamReplay, GetWeakPtr()));
139 void SpdyStream::PushedStreamReplay() {
140 DCHECK_EQ(type_, SPDY_PUSH_STREAM);
141 DCHECK_NE(stream_id_, 0u);
142 CHECK_EQ(stream_id_ % 2, 0u);
144 CHECK_EQ(io_state_, STATE_HALF_CLOSED_LOCAL_UNCLAIMED);
145 io_state_ = STATE_HALF_CLOSED_LOCAL;
147 // The delegate methods called below may delete |this|, so use
148 // |weak_this| to detect that.
149 base::WeakPtr<SpdyStream> weak_this = GetWeakPtr();
151 CHECK(delegate_);
152 SpdyResponseHeadersStatus status =
153 delegate_->OnResponseHeadersUpdated(response_headers_);
154 if (status == RESPONSE_HEADERS_ARE_INCOMPLETE) {
155 // Since RESPONSE_HEADERS_ARE_INCOMPLETE was returned, we must not
156 // have been closed. Since we don't have complete headers, assume
157 // we're waiting for another HEADERS frame, and we had better not
158 // have any pending data frames.
159 CHECK(weak_this);
160 if (!pending_recv_data_.empty()) {
161 LogStreamError(ERR_SPDY_PROTOCOL_ERROR,
162 "Data received with incomplete headers.");
163 session_->CloseActiveStream(stream_id_, ERR_SPDY_PROTOCOL_ERROR);
165 return;
168 // OnResponseHeadersUpdated() may have closed |this|.
169 if (!weak_this)
170 return;
172 response_headers_status_ = RESPONSE_HEADERS_ARE_COMPLETE;
174 while (!pending_recv_data_.empty()) {
175 // Take ownership of the first element of |pending_recv_data_|.
176 scoped_ptr<SpdyBuffer> buffer(pending_recv_data_.front());
177 pending_recv_data_.weak_erase(pending_recv_data_.begin());
179 bool eof = (buffer == NULL);
181 CHECK(delegate_);
182 delegate_->OnDataReceived(buffer.Pass());
184 // OnDataReceived() may have closed |this|.
185 if (!weak_this)
186 return;
188 if (eof) {
189 DCHECK(pending_recv_data_.empty());
190 session_->CloseActiveStream(stream_id_, OK);
191 DCHECK(!weak_this);
192 // |pending_recv_data_| is invalid at this point.
193 break;
198 scoped_ptr<SpdyFrame> SpdyStream::ProduceSynStreamFrame() {
199 CHECK_EQ(io_state_, STATE_IDLE);
200 CHECK(request_headers_);
201 CHECK_GT(stream_id_, 0u);
203 SpdyControlFlags flags =
204 (pending_send_status_ == NO_MORE_DATA_TO_SEND) ?
205 CONTROL_FLAG_FIN : CONTROL_FLAG_NONE;
206 scoped_ptr<SpdyFrame> frame(session_->CreateSynStream(
207 stream_id_, priority_, flags, *request_headers_));
208 send_time_ = base::TimeTicks::Now();
209 return frame.Pass();
212 void SpdyStream::DetachDelegate() {
213 DCHECK(!IsClosed());
214 delegate_ = NULL;
215 Cancel();
218 void SpdyStream::AdjustSendWindowSize(int32 delta_window_size) {
219 DCHECK_GE(session_->flow_control_state(), SpdySession::FLOW_CONTROL_STREAM);
221 if (IsClosed())
222 return;
224 // Check for wraparound.
225 if (send_window_size_ > 0) {
226 DCHECK_LE(delta_window_size, kint32max - send_window_size_);
228 if (send_window_size_ < 0) {
229 DCHECK_GE(delta_window_size, kint32min - send_window_size_);
231 send_window_size_ += delta_window_size;
232 PossiblyResumeIfSendStalled();
235 void SpdyStream::OnWriteBufferConsumed(
236 size_t frame_payload_size,
237 size_t consume_size,
238 SpdyBuffer::ConsumeSource consume_source) {
239 DCHECK_GE(session_->flow_control_state(), SpdySession::FLOW_CONTROL_STREAM);
240 if (consume_source == SpdyBuffer::DISCARD) {
241 // If we're discarding a frame or part of it, increase the send
242 // window by the number of discarded bytes. (Although if we're
243 // discarding part of a frame, it's probably because of a write
244 // error and we'll be tearing down the stream soon.)
245 size_t remaining_payload_bytes = std::min(consume_size, frame_payload_size);
246 DCHECK_GT(remaining_payload_bytes, 0u);
247 IncreaseSendWindowSize(static_cast<int32>(remaining_payload_bytes));
249 // For consumed bytes, the send window is increased when we receive
250 // a WINDOW_UPDATE frame.
253 void SpdyStream::IncreaseSendWindowSize(int32 delta_window_size) {
254 DCHECK_GE(session_->flow_control_state(), SpdySession::FLOW_CONTROL_STREAM);
255 DCHECK_GE(delta_window_size, 1);
257 // Ignore late WINDOW_UPDATEs.
258 if (IsClosed())
259 return;
261 if (send_window_size_ > 0) {
262 // Check for overflow.
263 int32 max_delta_window_size = kint32max - send_window_size_;
264 if (delta_window_size > max_delta_window_size) {
265 std::string desc = base::StringPrintf(
266 "Received WINDOW_UPDATE [delta: %d] for stream %d overflows "
267 "send_window_size_ [current: %d]", delta_window_size, stream_id_,
268 send_window_size_);
269 session_->ResetStream(stream_id_, RST_STREAM_FLOW_CONTROL_ERROR, desc);
270 return;
274 send_window_size_ += delta_window_size;
276 net_log_.AddEvent(
277 NetLog::TYPE_HTTP2_STREAM_UPDATE_SEND_WINDOW,
278 base::Bind(&NetLogSpdyStreamWindowUpdateCallback, stream_id_,
279 delta_window_size, send_window_size_));
281 PossiblyResumeIfSendStalled();
284 void SpdyStream::DecreaseSendWindowSize(int32 delta_window_size) {
285 DCHECK_GE(session_->flow_control_state(), SpdySession::FLOW_CONTROL_STREAM);
287 if (IsClosed())
288 return;
290 // We only call this method when sending a frame. Therefore,
291 // |delta_window_size| should be within the valid frame size range.
292 DCHECK_GE(delta_window_size, 1);
293 DCHECK_LE(delta_window_size, kMaxSpdyFrameChunkSize);
295 // |send_window_size_| should have been at least |delta_window_size| for
296 // this call to happen.
297 DCHECK_GE(send_window_size_, delta_window_size);
299 send_window_size_ -= delta_window_size;
301 net_log_.AddEvent(
302 NetLog::TYPE_HTTP2_STREAM_UPDATE_SEND_WINDOW,
303 base::Bind(&NetLogSpdyStreamWindowUpdateCallback, stream_id_,
304 -delta_window_size, send_window_size_));
307 void SpdyStream::OnReadBufferConsumed(
308 size_t consume_size,
309 SpdyBuffer::ConsumeSource consume_source) {
310 DCHECK_GE(session_->flow_control_state(), SpdySession::FLOW_CONTROL_STREAM);
311 DCHECK_GE(consume_size, 1u);
312 DCHECK_LE(consume_size, static_cast<size_t>(kint32max));
313 IncreaseRecvWindowSize(static_cast<int32>(consume_size));
316 void SpdyStream::IncreaseRecvWindowSize(int32 delta_window_size) {
317 DCHECK_GE(session_->flow_control_state(), SpdySession::FLOW_CONTROL_STREAM);
319 // By the time a read is processed by the delegate, this stream may
320 // already be inactive.
321 if (!session_->IsStreamActive(stream_id_))
322 return;
324 DCHECK_GE(unacked_recv_window_bytes_, 0);
325 DCHECK_GE(recv_window_size_, unacked_recv_window_bytes_);
326 DCHECK_GE(delta_window_size, 1);
327 // Check for overflow.
328 DCHECK_LE(delta_window_size, kint32max - recv_window_size_);
330 recv_window_size_ += delta_window_size;
331 net_log_.AddEvent(
332 NetLog::TYPE_HTTP2_STREAM_UPDATE_RECV_WINDOW,
333 base::Bind(&NetLogSpdyStreamWindowUpdateCallback, stream_id_,
334 delta_window_size, recv_window_size_));
336 unacked_recv_window_bytes_ += delta_window_size;
337 if (unacked_recv_window_bytes_ > max_recv_window_size_ / 2) {
338 session_->SendStreamWindowUpdate(
339 stream_id_, static_cast<uint32>(unacked_recv_window_bytes_));
340 unacked_recv_window_bytes_ = 0;
344 void SpdyStream::DecreaseRecvWindowSize(int32 delta_window_size) {
345 DCHECK(session_->IsStreamActive(stream_id_));
346 DCHECK_GE(session_->flow_control_state(), SpdySession::FLOW_CONTROL_STREAM);
347 DCHECK_GE(delta_window_size, 1);
349 // Since we never decrease the initial receive window size,
350 // |delta_window_size| should never cause |recv_window_size_| to go
351 // negative. If we do, the receive window isn't being respected.
352 if (delta_window_size > recv_window_size_) {
353 session_->ResetStream(
354 stream_id_, RST_STREAM_PROTOCOL_ERROR,
355 "delta_window_size is " + base::IntToString(delta_window_size) +
356 " in DecreaseRecvWindowSize, which is larger than the receive " +
357 "window size of " + base::IntToString(recv_window_size_));
358 return;
361 recv_window_size_ -= delta_window_size;
362 net_log_.AddEvent(
363 NetLog::TYPE_HTTP2_STREAM_UPDATE_RECV_WINDOW,
364 base::Bind(&NetLogSpdyStreamWindowUpdateCallback, stream_id_,
365 -delta_window_size, recv_window_size_));
368 int SpdyStream::GetPeerAddress(IPEndPoint* address) const {
369 return session_->GetPeerAddress(address);
372 int SpdyStream::GetLocalAddress(IPEndPoint* address) const {
373 return session_->GetLocalAddress(address);
376 bool SpdyStream::WasEverUsed() const {
377 return session_->WasEverUsed();
380 base::Time SpdyStream::GetRequestTime() const {
381 return request_time_;
384 void SpdyStream::SetRequestTime(base::Time t) {
385 request_time_ = t;
388 int SpdyStream::OnInitialResponseHeadersReceived(
389 const SpdyHeaderBlock& initial_response_headers,
390 base::Time response_time,
391 base::TimeTicks recv_first_byte_time) {
392 // SpdySession guarantees that this is called at most once.
393 CHECK(response_headers_.empty());
395 // Check to make sure that we don't receive the response headers
396 // before we're ready for it.
397 switch (type_) {
398 case SPDY_BIDIRECTIONAL_STREAM:
399 // For a bidirectional stream, we're ready for the response
400 // headers once we've finished sending the request headers.
401 if (io_state_ == STATE_IDLE) {
402 session_->ResetStream(stream_id_, RST_STREAM_PROTOCOL_ERROR,
403 "Response received before request sent");
404 return ERR_SPDY_PROTOCOL_ERROR;
406 break;
408 case SPDY_REQUEST_RESPONSE_STREAM:
409 // For a request/response stream, we're ready for the response
410 // headers once we've finished sending the request headers.
411 if (io_state_ == STATE_IDLE) {
412 session_->ResetStream(stream_id_, RST_STREAM_PROTOCOL_ERROR,
413 "Response received before request sent");
414 return ERR_SPDY_PROTOCOL_ERROR;
416 break;
418 case SPDY_PUSH_STREAM:
419 // Push streams transition to a locally half-closed state upon headers.
420 // We must continue to buffer data while waiting for a call to
421 // SetDelegate() (which may not ever happen).
422 CHECK_EQ(io_state_, STATE_RESERVED_REMOTE);
423 if (!delegate_) {
424 io_state_ = STATE_HALF_CLOSED_LOCAL_UNCLAIMED;
425 } else {
426 io_state_ = STATE_HALF_CLOSED_LOCAL;
428 break;
431 DCHECK_NE(io_state_, STATE_IDLE);
433 response_time_ = response_time;
434 recv_first_byte_time_ = recv_first_byte_time;
435 return MergeWithResponseHeaders(initial_response_headers);
438 int SpdyStream::OnAdditionalResponseHeadersReceived(
439 const SpdyHeaderBlock& additional_response_headers) {
440 if (type_ == SPDY_REQUEST_RESPONSE_STREAM) {
441 session_->ResetStream(
442 stream_id_, RST_STREAM_PROTOCOL_ERROR,
443 "Additional headers received for request/response stream");
444 return ERR_SPDY_PROTOCOL_ERROR;
445 } else if (type_ == SPDY_PUSH_STREAM &&
446 response_headers_status_ == RESPONSE_HEADERS_ARE_COMPLETE) {
447 session_->ResetStream(
448 stream_id_, RST_STREAM_PROTOCOL_ERROR,
449 "Additional headers received for push stream");
450 return ERR_SPDY_PROTOCOL_ERROR;
452 return MergeWithResponseHeaders(additional_response_headers);
455 void SpdyStream::OnPushPromiseHeadersReceived(const SpdyHeaderBlock& headers) {
456 CHECK(!request_headers_.get());
457 CHECK_EQ(io_state_, STATE_IDLE);
458 CHECK_EQ(type_, SPDY_PUSH_STREAM);
459 DCHECK(!delegate_);
461 io_state_ = STATE_RESERVED_REMOTE;
462 request_headers_.reset(new SpdyHeaderBlock(headers));
465 void SpdyStream::OnDataReceived(scoped_ptr<SpdyBuffer> buffer) {
466 DCHECK(session_->IsStreamActive(stream_id_));
468 // If we're still buffering data for a push stream, we will do the
469 // check for data received with incomplete headers in
470 // PushedStreamReplayData().
471 if (io_state_ == STATE_HALF_CLOSED_LOCAL_UNCLAIMED) {
472 DCHECK_EQ(type_, SPDY_PUSH_STREAM);
473 // It should be valid for this to happen in the server push case.
474 // We'll return received data when delegate gets attached to the stream.
475 if (buffer) {
476 pending_recv_data_.push_back(buffer.release());
477 } else {
478 pending_recv_data_.push_back(NULL);
479 // Note: we leave the stream open in the session until the stream
480 // is claimed.
482 return;
485 // If we have response headers but the delegate has indicated that
486 // it's still incomplete, then that's a protocol error.
487 if (response_headers_status_ == RESPONSE_HEADERS_ARE_INCOMPLETE) {
488 LogStreamError(ERR_SPDY_PROTOCOL_ERROR,
489 "Data received with incomplete headers.");
490 session_->CloseActiveStream(stream_id_, ERR_SPDY_PROTOCOL_ERROR);
491 return;
494 CHECK(!IsClosed());
496 if (!buffer) {
497 if (io_state_ == STATE_OPEN) {
498 io_state_ = STATE_HALF_CLOSED_REMOTE;
499 } else if (io_state_ == STATE_HALF_CLOSED_LOCAL) {
500 io_state_ = STATE_CLOSED;
501 // Deletes |this|.
502 session_->CloseActiveStream(stream_id_, OK);
503 } else {
504 NOTREACHED() << io_state_;
506 return;
509 size_t length = buffer->GetRemainingSize();
510 DCHECK_LE(length, session_->GetDataFrameMaximumPayload());
511 if (session_->flow_control_state() >= SpdySession::FLOW_CONTROL_STREAM) {
512 DecreaseRecvWindowSize(static_cast<int32>(length));
513 buffer->AddConsumeCallback(
514 base::Bind(&SpdyStream::OnReadBufferConsumed, GetWeakPtr()));
517 // Track our bandwidth.
518 recv_bytes_ += length;
519 recv_last_byte_time_ = base::TimeTicks::Now();
521 // May close |this|.
522 delegate_->OnDataReceived(buffer.Pass());
525 void SpdyStream::OnPaddingConsumed(size_t len) {
526 if (session_->flow_control_state() >= SpdySession::FLOW_CONTROL_STREAM) {
527 // Decrease window size because padding bytes are received.
528 // Increase window size because padding bytes are consumed (by discarding).
529 // Net result: |unacked_recv_window_bytes_| increases by |len|,
530 // |recv_window_size_| does not change.
531 DecreaseRecvWindowSize(static_cast<int32>(len));
532 IncreaseRecvWindowSize(static_cast<int32>(len));
536 void SpdyStream::OnFrameWriteComplete(SpdyFrameType frame_type,
537 size_t frame_size) {
538 DCHECK_NE(type_, SPDY_PUSH_STREAM);
540 if (frame_size < session_->GetFrameMinimumSize() ||
541 frame_size > session_->GetFrameMaximumSize()) {
542 NOTREACHED();
543 return;
545 CHECK(frame_type == SYN_STREAM ||
546 frame_type == DATA) << frame_type;
548 int result = (frame_type == SYN_STREAM) ?
549 OnRequestHeadersSent() : OnDataSent(frame_size);
550 if (result == ERR_IO_PENDING) {
551 // The write operation hasn't completed yet.
552 return;
555 if (pending_send_status_ == NO_MORE_DATA_TO_SEND) {
556 if(io_state_ == STATE_OPEN) {
557 io_state_ = STATE_HALF_CLOSED_LOCAL;
558 } else if(io_state_ == STATE_HALF_CLOSED_REMOTE) {
559 io_state_ = STATE_CLOSED;
560 } else {
561 NOTREACHED() << io_state_;
564 // Notify delegate of write completion. Must not destroy |this|.
565 CHECK(delegate_);
567 base::WeakPtr<SpdyStream> weak_this = GetWeakPtr();
568 write_handler_guard_ = true;
569 if (frame_type == SYN_STREAM) {
570 delegate_->OnRequestHeadersSent();
571 } else {
572 delegate_->OnDataSent();
574 CHECK(weak_this);
575 write_handler_guard_ = false;
578 if (io_state_ == STATE_CLOSED) {
579 // Deletes |this|.
580 session_->CloseActiveStream(stream_id_, OK);
584 int SpdyStream::OnRequestHeadersSent() {
585 CHECK_EQ(io_state_, STATE_IDLE);
586 CHECK_NE(stream_id_, 0u);
588 io_state_ = STATE_OPEN;
589 return OK;
592 int SpdyStream::OnDataSent(size_t frame_size) {
593 CHECK(io_state_ == STATE_OPEN ||
594 io_state_ == STATE_HALF_CLOSED_REMOTE) << io_state_;
596 size_t frame_payload_size = frame_size - session_->GetDataFrameMinimumSize();
598 CHECK_GE(frame_size, session_->GetDataFrameMinimumSize());
599 CHECK_LE(frame_payload_size, session_->GetDataFrameMaximumPayload());
601 send_bytes_ += frame_payload_size;
603 // If more data is available to send, dispatch it and
604 // return that the write operation is still ongoing.
605 pending_send_data_->DidConsume(frame_payload_size);
606 if (pending_send_data_->BytesRemaining() > 0) {
607 QueueNextDataFrame();
608 return ERR_IO_PENDING;
609 } else {
610 pending_send_data_ = NULL;
611 return OK;
615 SpdyMajorVersion SpdyStream::GetProtocolVersion() const {
616 return session_->GetProtocolVersion();
619 void SpdyStream::LogStreamError(int status, const std::string& description) {
620 net_log_.AddEvent(NetLog::TYPE_HTTP2_STREAM_ERROR,
621 base::Bind(&NetLogSpdyStreamErrorCallback, stream_id_,
622 status, &description));
625 void SpdyStream::OnClose(int status) {
626 // In most cases, the stream should already be CLOSED. The exception is when a
627 // SpdySession is shutting down while the stream is in an intermediate state.
628 io_state_ = STATE_CLOSED;
629 response_status_ = status;
630 Delegate* delegate = delegate_;
631 delegate_ = NULL;
632 if (delegate)
633 delegate->OnClose(status);
634 // Unset |stream_id_| last so that the delegate can look it up.
635 stream_id_ = 0;
638 void SpdyStream::Cancel() {
639 // We may be called again from a delegate's OnClose().
640 if (io_state_ == STATE_CLOSED)
641 return;
643 if (stream_id_ != 0) {
644 session_->ResetStream(stream_id_, RST_STREAM_CANCEL, std::string());
645 } else {
646 session_->CloseCreatedStream(GetWeakPtr(), RST_STREAM_CANCEL);
648 // |this| is invalid at this point.
651 void SpdyStream::Close() {
652 // We may be called again from a delegate's OnClose().
653 if (io_state_ == STATE_CLOSED)
654 return;
656 if (stream_id_ != 0) {
657 session_->CloseActiveStream(stream_id_, OK);
658 } else {
659 session_->CloseCreatedStream(GetWeakPtr(), OK);
661 // |this| is invalid at this point.
664 base::WeakPtr<SpdyStream> SpdyStream::GetWeakPtr() {
665 return weak_ptr_factory_.GetWeakPtr();
668 int SpdyStream::SendRequestHeaders(scoped_ptr<SpdyHeaderBlock> request_headers,
669 SpdySendStatus send_status) {
670 CHECK_NE(type_, SPDY_PUSH_STREAM);
671 CHECK_EQ(pending_send_status_, MORE_DATA_TO_SEND);
672 CHECK(!request_headers_);
673 CHECK(!pending_send_data_.get());
674 CHECK_EQ(io_state_, STATE_IDLE);
675 request_headers_ = request_headers.Pass();
676 pending_send_status_ = send_status;
677 session_->EnqueueStreamWrite(
678 GetWeakPtr(), SYN_STREAM,
679 scoped_ptr<SpdyBufferProducer>(
680 new SynStreamBufferProducer(GetWeakPtr())));
681 return ERR_IO_PENDING;
684 void SpdyStream::SendData(IOBuffer* data,
685 int length,
686 SpdySendStatus send_status) {
687 CHECK_NE(type_, SPDY_PUSH_STREAM);
688 CHECK_EQ(pending_send_status_, MORE_DATA_TO_SEND);
689 CHECK(io_state_ == STATE_OPEN ||
690 io_state_ == STATE_HALF_CLOSED_REMOTE) << io_state_;
691 CHECK(!pending_send_data_.get());
692 pending_send_data_ = new DrainableIOBuffer(data, length);
693 pending_send_status_ = send_status;
694 QueueNextDataFrame();
697 bool SpdyStream::GetSSLInfo(SSLInfo* ssl_info,
698 bool* was_npn_negotiated,
699 NextProto* protocol_negotiated) {
700 return session_->GetSSLInfo(
701 ssl_info, was_npn_negotiated, protocol_negotiated);
704 bool SpdyStream::GetSSLCertRequestInfo(SSLCertRequestInfo* cert_request_info) {
705 return session_->GetSSLCertRequestInfo(cert_request_info);
708 void SpdyStream::PossiblyResumeIfSendStalled() {
709 if (IsLocallyClosed()) {
710 return;
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 {
748 if (stream_id_ == 0)
749 return false;
751 return session_->GetLoadTimingInfo(stream_id_, load_timing_info);
754 GURL SpdyStream::GetUrlFromHeaders() const {
755 if (!request_headers_)
756 return GURL();
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())
770 return;
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_;
777 } else {
778 // For non-push streams, we also need |send_time_| to be filled
779 // in.
780 if (send_time_.is_null())
781 return;
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);
806 } else {
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(),
817 flags));
818 // We'll get called again by PossiblyResumeIfSendStalled().
819 if (!data_buffer)
820 return;
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(
843 GetWeakPtr(), DATA,
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
879 // the stream.
880 if (delegate_) {
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
889 // have been closed.
890 CHECK(weak_this);
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;
902 return OK;
905 #define STATE_CASE(s) \
906 case s: \
907 description = base::StringPrintf("%s (0x%08X)", #s, s); \
908 break
910 std::string SpdyStream::DescribeState(State state) {
911 std::string description;
912 switch (state) {
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);
918 default:
919 description = base::StringPrintf("Unknown state 0x%08X (%u)", state,
920 state);
921 break;
923 return description;
926 #undef STATE_CASE
928 } // namespace net