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_session.h"
10 #include "base/basictypes.h"
11 #include "base/bind.h"
12 #include "base/compiler_specific.h"
13 #include "base/logging.h"
14 #include "base/message_loop/message_loop.h"
15 #include "base/metrics/field_trial.h"
16 #include "base/metrics/histogram.h"
17 #include "base/metrics/sparse_histogram.h"
18 #include "base/profiler/scoped_tracker.h"
19 #include "base/stl_util.h"
20 #include "base/strings/string_number_conversions.h"
21 #include "base/strings/string_util.h"
22 #include "base/strings/stringprintf.h"
23 #include "base/strings/utf_string_conversions.h"
24 #include "base/time/time.h"
25 #include "base/values.h"
26 #include "crypto/ec_private_key.h"
27 #include "crypto/ec_signature_creator.h"
28 #include "net/base/connection_type_histograms.h"
29 #include "net/base/net_util.h"
30 #include "net/cert/asn1_util.h"
31 #include "net/cert/cert_verify_result.h"
32 #include "net/http/http_log_util.h"
33 #include "net/http/http_network_session.h"
34 #include "net/http/http_server_properties.h"
35 #include "net/http/http_util.h"
36 #include "net/http/transport_security_state.h"
37 #include "net/log/net_log.h"
38 #include "net/socket/ssl_client_socket.h"
39 #include "net/spdy/spdy_buffer_producer.h"
40 #include "net/spdy/spdy_frame_builder.h"
41 #include "net/spdy/spdy_http_utils.h"
42 #include "net/spdy/spdy_protocol.h"
43 #include "net/spdy/spdy_session_pool.h"
44 #include "net/spdy/spdy_stream.h"
45 #include "net/ssl/channel_id_service.h"
46 #include "net/ssl/ssl_cipher_suite_names.h"
47 #include "net/ssl/ssl_connection_status_flags.h"
53 const int kReadBufferSize
= 8 * 1024;
54 const int kDefaultConnectionAtRiskOfLossSeconds
= 10;
55 const int kHungIntervalSeconds
= 10;
57 // Minimum seconds that unclaimed pushed streams will be kept in memory.
58 const int kMinPushedStreamLifetimeSeconds
= 300;
60 scoped_ptr
<base::ListValue
> SpdyHeaderBlockToListValue(
61 const SpdyHeaderBlock
& headers
,
62 net::NetLog::LogLevel log_level
) {
63 scoped_ptr
<base::ListValue
> headers_list(new base::ListValue());
64 for (SpdyHeaderBlock::const_iterator it
= headers
.begin();
65 it
!= headers
.end(); ++it
) {
66 headers_list
->AppendString(
68 ElideHeaderValueForNetLog(log_level
, it
->first
, it
->second
));
70 return headers_list
.Pass();
73 base::Value
* NetLogSpdySynStreamSentCallback(const SpdyHeaderBlock
* headers
,
76 SpdyPriority spdy_priority
,
77 SpdyStreamId stream_id
,
78 NetLog::LogLevel log_level
) {
79 base::DictionaryValue
* dict
= new base::DictionaryValue();
81 SpdyHeaderBlockToListValue(*headers
, log_level
).release());
82 dict
->SetBoolean("fin", fin
);
83 dict
->SetBoolean("unidirectional", unidirectional
);
84 dict
->SetInteger("priority", static_cast<int>(spdy_priority
));
85 dict
->SetInteger("stream_id", stream_id
);
89 base::Value
* NetLogSpdySynStreamReceivedCallback(
90 const SpdyHeaderBlock
* headers
,
93 SpdyPriority spdy_priority
,
94 SpdyStreamId stream_id
,
95 SpdyStreamId associated_stream
,
96 NetLog::LogLevel log_level
) {
97 base::DictionaryValue
* dict
= new base::DictionaryValue();
99 SpdyHeaderBlockToListValue(*headers
, log_level
).release());
100 dict
->SetBoolean("fin", fin
);
101 dict
->SetBoolean("unidirectional", unidirectional
);
102 dict
->SetInteger("priority", static_cast<int>(spdy_priority
));
103 dict
->SetInteger("stream_id", stream_id
);
104 dict
->SetInteger("associated_stream", associated_stream
);
108 base::Value
* NetLogSpdySynReplyOrHeadersReceivedCallback(
109 const SpdyHeaderBlock
* headers
,
111 SpdyStreamId stream_id
,
112 NetLog::LogLevel log_level
) {
113 base::DictionaryValue
* dict
= new base::DictionaryValue();
115 SpdyHeaderBlockToListValue(*headers
, log_level
).release());
116 dict
->SetBoolean("fin", fin
);
117 dict
->SetInteger("stream_id", stream_id
);
121 base::Value
* NetLogSpdySessionCloseCallback(int net_error
,
122 const std::string
* description
,
123 NetLog::LogLevel
/* log_level */) {
124 base::DictionaryValue
* dict
= new base::DictionaryValue();
125 dict
->SetInteger("net_error", net_error
);
126 dict
->SetString("description", *description
);
130 base::Value
* NetLogSpdySessionCallback(const HostPortProxyPair
* host_pair
,
131 NetLog::LogLevel
/* log_level */) {
132 base::DictionaryValue
* dict
= new base::DictionaryValue();
133 dict
->SetString("host", host_pair
->first
.ToString());
134 dict
->SetString("proxy", host_pair
->second
.ToPacString());
138 base::Value
* NetLogSpdyInitializedCallback(NetLog::Source source
,
139 const NextProto protocol_version
,
140 NetLog::LogLevel
/* log_level */) {
141 base::DictionaryValue
* dict
= new base::DictionaryValue();
142 if (source
.IsValid()) {
143 source
.AddToEventParameters(dict
);
145 dict
->SetString("protocol",
146 SSLClientSocket::NextProtoToString(protocol_version
));
150 base::Value
* NetLogSpdySettingsCallback(const HostPortPair
& host_port_pair
,
151 bool clear_persisted
,
152 NetLog::LogLevel
/* log_level */) {
153 base::DictionaryValue
* dict
= new base::DictionaryValue();
154 dict
->SetString("host", host_port_pair
.ToString());
155 dict
->SetBoolean("clear_persisted", clear_persisted
);
159 base::Value
* NetLogSpdySettingCallback(SpdySettingsIds id
,
160 const SpdyMajorVersion protocol_version
,
161 SpdySettingsFlags flags
,
163 NetLog::LogLevel
/* log_level */) {
164 base::DictionaryValue
* dict
= new base::DictionaryValue();
165 dict
->SetInteger("id",
166 SpdyConstants::SerializeSettingId(protocol_version
, id
));
167 dict
->SetInteger("flags", flags
);
168 dict
->SetInteger("value", value
);
172 base::Value
* NetLogSpdySendSettingsCallback(
173 const SettingsMap
* settings
,
174 const SpdyMajorVersion protocol_version
,
175 NetLog::LogLevel
/* log_level */) {
176 base::DictionaryValue
* dict
= new base::DictionaryValue();
177 base::ListValue
* settings_list
= new base::ListValue();
178 for (SettingsMap::const_iterator it
= settings
->begin();
179 it
!= settings
->end(); ++it
) {
180 const SpdySettingsIds id
= it
->first
;
181 const SpdySettingsFlags flags
= it
->second
.first
;
182 const uint32 value
= it
->second
.second
;
183 settings_list
->Append(new base::StringValue(base::StringPrintf(
184 "[id:%u flags:%u value:%u]",
185 SpdyConstants::SerializeSettingId(protocol_version
, id
),
189 dict
->Set("settings", settings_list
);
193 base::Value
* NetLogSpdyWindowUpdateFrameCallback(
194 SpdyStreamId stream_id
,
196 NetLog::LogLevel
/* log_level */) {
197 base::DictionaryValue
* dict
= new base::DictionaryValue();
198 dict
->SetInteger("stream_id", static_cast<int>(stream_id
));
199 dict
->SetInteger("delta", delta
);
203 base::Value
* NetLogSpdySessionWindowUpdateCallback(
206 NetLog::LogLevel
/* log_level */) {
207 base::DictionaryValue
* dict
= new base::DictionaryValue();
208 dict
->SetInteger("delta", delta
);
209 dict
->SetInteger("window_size", window_size
);
213 base::Value
* NetLogSpdyDataCallback(SpdyStreamId stream_id
,
216 NetLog::LogLevel
/* log_level */) {
217 base::DictionaryValue
* dict
= new base::DictionaryValue();
218 dict
->SetInteger("stream_id", static_cast<int>(stream_id
));
219 dict
->SetInteger("size", size
);
220 dict
->SetBoolean("fin", fin
);
224 base::Value
* NetLogSpdyRstCallback(SpdyStreamId stream_id
,
226 const std::string
* description
,
227 NetLog::LogLevel
/* log_level */) {
228 base::DictionaryValue
* dict
= new base::DictionaryValue();
229 dict
->SetInteger("stream_id", static_cast<int>(stream_id
));
230 dict
->SetInteger("status", status
);
231 dict
->SetString("description", *description
);
235 base::Value
* NetLogSpdyPingCallback(SpdyPingId unique_id
,
238 NetLog::LogLevel
/* log_level */) {
239 base::DictionaryValue
* dict
= new base::DictionaryValue();
240 dict
->SetInteger("unique_id", static_cast<int>(unique_id
));
241 dict
->SetString("type", type
);
242 dict
->SetBoolean("is_ack", is_ack
);
246 base::Value
* NetLogSpdyGoAwayCallback(SpdyStreamId last_stream_id
,
248 int unclaimed_streams
,
249 SpdyGoAwayStatus status
,
250 NetLog::LogLevel
/* log_level */) {
251 base::DictionaryValue
* dict
= new base::DictionaryValue();
252 dict
->SetInteger("last_accepted_stream_id",
253 static_cast<int>(last_stream_id
));
254 dict
->SetInteger("active_streams", active_streams
);
255 dict
->SetInteger("unclaimed_streams", unclaimed_streams
);
256 dict
->SetInteger("status", static_cast<int>(status
));
260 base::Value
* NetLogSpdyPushPromiseReceivedCallback(
261 const SpdyHeaderBlock
* headers
,
262 SpdyStreamId stream_id
,
263 SpdyStreamId promised_stream_id
,
264 NetLog::LogLevel log_level
) {
265 base::DictionaryValue
* dict
= new base::DictionaryValue();
267 SpdyHeaderBlockToListValue(*headers
, log_level
).release());
268 dict
->SetInteger("id", stream_id
);
269 dict
->SetInteger("promised_stream_id", promised_stream_id
);
273 base::Value
* NetLogSpdyAdoptedPushStreamCallback(
274 SpdyStreamId stream_id
, const GURL
* url
, NetLog::LogLevel log_level
) {
275 base::DictionaryValue
* dict
= new base::DictionaryValue();
276 dict
->SetInteger("stream_id", stream_id
);
277 dict
->SetString("url", url
->spec());
281 // Helper function to return the total size of an array of objects
282 // with .size() member functions.
283 template <typename T
, size_t N
> size_t GetTotalSize(const T (&arr
)[N
]) {
284 size_t total_size
= 0;
285 for (size_t i
= 0; i
< N
; ++i
) {
286 total_size
+= arr
[i
].size();
291 // Helper class for std:find_if on STL container containing
292 // SpdyStreamRequest weak pointers.
293 class RequestEquals
{
295 RequestEquals(const base::WeakPtr
<SpdyStreamRequest
>& request
)
296 : request_(request
) {}
298 bool operator()(const base::WeakPtr
<SpdyStreamRequest
>& request
) const {
299 return request_
.get() == request
.get();
303 const base::WeakPtr
<SpdyStreamRequest
> request_
;
306 // The maximum number of concurrent streams we will ever create. Even if
307 // the server permits more, we will never exceed this limit.
308 const size_t kMaxConcurrentStreamLimit
= 256;
312 SpdyProtocolErrorDetails
MapFramerErrorToProtocolError(
313 SpdyFramer::SpdyError err
) {
315 case SpdyFramer::SPDY_NO_ERROR
:
316 return SPDY_ERROR_NO_ERROR
;
317 case SpdyFramer::SPDY_INVALID_CONTROL_FRAME
:
318 return SPDY_ERROR_INVALID_CONTROL_FRAME
;
319 case SpdyFramer::SPDY_CONTROL_PAYLOAD_TOO_LARGE
:
320 return SPDY_ERROR_CONTROL_PAYLOAD_TOO_LARGE
;
321 case SpdyFramer::SPDY_ZLIB_INIT_FAILURE
:
322 return SPDY_ERROR_ZLIB_INIT_FAILURE
;
323 case SpdyFramer::SPDY_UNSUPPORTED_VERSION
:
324 return SPDY_ERROR_UNSUPPORTED_VERSION
;
325 case SpdyFramer::SPDY_DECOMPRESS_FAILURE
:
326 return SPDY_ERROR_DECOMPRESS_FAILURE
;
327 case SpdyFramer::SPDY_COMPRESS_FAILURE
:
328 return SPDY_ERROR_COMPRESS_FAILURE
;
329 case SpdyFramer::SPDY_GOAWAY_FRAME_CORRUPT
:
330 return SPDY_ERROR_GOAWAY_FRAME_CORRUPT
;
331 case SpdyFramer::SPDY_RST_STREAM_FRAME_CORRUPT
:
332 return SPDY_ERROR_RST_STREAM_FRAME_CORRUPT
;
333 case SpdyFramer::SPDY_INVALID_DATA_FRAME_FLAGS
:
334 return SPDY_ERROR_INVALID_DATA_FRAME_FLAGS
;
335 case SpdyFramer::SPDY_INVALID_CONTROL_FRAME_FLAGS
:
336 return SPDY_ERROR_INVALID_CONTROL_FRAME_FLAGS
;
337 case SpdyFramer::SPDY_UNEXPECTED_FRAME
:
338 return SPDY_ERROR_UNEXPECTED_FRAME
;
341 return static_cast<SpdyProtocolErrorDetails
>(-1);
345 Error
MapFramerErrorToNetError(SpdyFramer::SpdyError err
) {
347 case SpdyFramer::SPDY_NO_ERROR
:
349 case SpdyFramer::SPDY_INVALID_CONTROL_FRAME
:
350 return ERR_SPDY_PROTOCOL_ERROR
;
351 case SpdyFramer::SPDY_CONTROL_PAYLOAD_TOO_LARGE
:
352 return ERR_SPDY_FRAME_SIZE_ERROR
;
353 case SpdyFramer::SPDY_ZLIB_INIT_FAILURE
:
354 return ERR_SPDY_COMPRESSION_ERROR
;
355 case SpdyFramer::SPDY_UNSUPPORTED_VERSION
:
356 return ERR_SPDY_PROTOCOL_ERROR
;
357 case SpdyFramer::SPDY_DECOMPRESS_FAILURE
:
358 return ERR_SPDY_COMPRESSION_ERROR
;
359 case SpdyFramer::SPDY_COMPRESS_FAILURE
:
360 return ERR_SPDY_COMPRESSION_ERROR
;
361 case SpdyFramer::SPDY_GOAWAY_FRAME_CORRUPT
:
362 return ERR_SPDY_PROTOCOL_ERROR
;
363 case SpdyFramer::SPDY_RST_STREAM_FRAME_CORRUPT
:
364 return ERR_SPDY_PROTOCOL_ERROR
;
365 case SpdyFramer::SPDY_INVALID_DATA_FRAME_FLAGS
:
366 return ERR_SPDY_PROTOCOL_ERROR
;
367 case SpdyFramer::SPDY_INVALID_CONTROL_FRAME_FLAGS
:
368 return ERR_SPDY_PROTOCOL_ERROR
;
369 case SpdyFramer::SPDY_UNEXPECTED_FRAME
:
370 return ERR_SPDY_PROTOCOL_ERROR
;
373 return ERR_SPDY_PROTOCOL_ERROR
;
377 SpdyProtocolErrorDetails
MapRstStreamStatusToProtocolError(
378 SpdyRstStreamStatus status
) {
380 case RST_STREAM_PROTOCOL_ERROR
:
381 return STATUS_CODE_PROTOCOL_ERROR
;
382 case RST_STREAM_INVALID_STREAM
:
383 return STATUS_CODE_INVALID_STREAM
;
384 case RST_STREAM_REFUSED_STREAM
:
385 return STATUS_CODE_REFUSED_STREAM
;
386 case RST_STREAM_UNSUPPORTED_VERSION
:
387 return STATUS_CODE_UNSUPPORTED_VERSION
;
388 case RST_STREAM_CANCEL
:
389 return STATUS_CODE_CANCEL
;
390 case RST_STREAM_INTERNAL_ERROR
:
391 return STATUS_CODE_INTERNAL_ERROR
;
392 case RST_STREAM_FLOW_CONTROL_ERROR
:
393 return STATUS_CODE_FLOW_CONTROL_ERROR
;
394 case RST_STREAM_STREAM_IN_USE
:
395 return STATUS_CODE_STREAM_IN_USE
;
396 case RST_STREAM_STREAM_ALREADY_CLOSED
:
397 return STATUS_CODE_STREAM_ALREADY_CLOSED
;
398 case RST_STREAM_INVALID_CREDENTIALS
:
399 return STATUS_CODE_INVALID_CREDENTIALS
;
400 case RST_STREAM_FRAME_SIZE_ERROR
:
401 return STATUS_CODE_FRAME_SIZE_ERROR
;
402 case RST_STREAM_SETTINGS_TIMEOUT
:
403 return STATUS_CODE_SETTINGS_TIMEOUT
;
404 case RST_STREAM_CONNECT_ERROR
:
405 return STATUS_CODE_CONNECT_ERROR
;
406 case RST_STREAM_ENHANCE_YOUR_CALM
:
407 return STATUS_CODE_ENHANCE_YOUR_CALM
;
408 case RST_STREAM_INADEQUATE_SECURITY
:
409 return STATUS_CODE_INADEQUATE_SECURITY
;
410 case RST_STREAM_HTTP_1_1_REQUIRED
:
411 return STATUS_CODE_HTTP_1_1_REQUIRED
;
414 return static_cast<SpdyProtocolErrorDetails
>(-1);
418 SpdyGoAwayStatus
MapNetErrorToGoAwayStatus(Error err
) {
421 return GOAWAY_NO_ERROR
;
422 case ERR_SPDY_PROTOCOL_ERROR
:
423 return GOAWAY_PROTOCOL_ERROR
;
424 case ERR_SPDY_FLOW_CONTROL_ERROR
:
425 return GOAWAY_FLOW_CONTROL_ERROR
;
426 case ERR_SPDY_FRAME_SIZE_ERROR
:
427 return GOAWAY_FRAME_SIZE_ERROR
;
428 case ERR_SPDY_COMPRESSION_ERROR
:
429 return GOAWAY_COMPRESSION_ERROR
;
430 case ERR_SPDY_INADEQUATE_TRANSPORT_SECURITY
:
431 return GOAWAY_INADEQUATE_SECURITY
;
433 return GOAWAY_PROTOCOL_ERROR
;
437 void SplitPushedHeadersToRequestAndResponse(const SpdyHeaderBlock
& headers
,
438 SpdyMajorVersion protocol_version
,
439 SpdyHeaderBlock
* request_headers
,
440 SpdyHeaderBlock
* response_headers
) {
441 DCHECK(response_headers
);
442 DCHECK(request_headers
);
443 for (SpdyHeaderBlock::const_iterator it
= headers
.begin();
446 SpdyHeaderBlock
* to_insert
= response_headers
;
447 if (protocol_version
== SPDY2
) {
448 if (it
->first
== "url")
449 to_insert
= request_headers
;
451 const char* host
= protocol_version
>= SPDY4
? ":authority" : ":host";
452 static const char scheme
[] = ":scheme";
453 static const char path
[] = ":path";
454 if (it
->first
== host
|| it
->first
== scheme
|| it
->first
== path
)
455 to_insert
= request_headers
;
457 to_insert
->insert(*it
);
461 SpdyStreamRequest::SpdyStreamRequest() : weak_ptr_factory_(this) {
465 SpdyStreamRequest::~SpdyStreamRequest() {
469 int SpdyStreamRequest::StartRequest(
471 const base::WeakPtr
<SpdySession
>& session
,
473 RequestPriority priority
,
474 const BoundNetLog
& net_log
,
475 const CompletionCallback
& callback
) {
479 DCHECK(callback_
.is_null());
484 priority_
= priority
;
486 callback_
= callback
;
488 base::WeakPtr
<SpdyStream
> stream
;
489 int rv
= session
->TryCreateStream(weak_ptr_factory_
.GetWeakPtr(), &stream
);
497 void SpdyStreamRequest::CancelRequest() {
499 session_
->CancelStreamRequest(weak_ptr_factory_
.GetWeakPtr());
501 // Do this to cancel any pending CompleteStreamRequest() tasks.
502 weak_ptr_factory_
.InvalidateWeakPtrs();
505 base::WeakPtr
<SpdyStream
> SpdyStreamRequest::ReleaseStream() {
507 base::WeakPtr
<SpdyStream
> stream
= stream_
;
513 void SpdyStreamRequest::OnRequestCompleteSuccess(
514 const base::WeakPtr
<SpdyStream
>& stream
) {
517 DCHECK(!callback_
.is_null());
518 CompletionCallback callback
= callback_
;
525 void SpdyStreamRequest::OnRequestCompleteFailure(int rv
) {
528 DCHECK(!callback_
.is_null());
529 CompletionCallback callback
= callback_
;
535 void SpdyStreamRequest::Reset() {
536 type_
= SPDY_BIDIRECTIONAL_STREAM
;
540 priority_
= MINIMUM_PRIORITY
;
541 net_log_
= BoundNetLog();
545 SpdySession::ActiveStreamInfo::ActiveStreamInfo()
547 waiting_for_syn_reply(false) {}
549 SpdySession::ActiveStreamInfo::ActiveStreamInfo(SpdyStream
* stream
)
551 waiting_for_syn_reply(stream
->type() != SPDY_PUSH_STREAM
) {
554 SpdySession::ActiveStreamInfo::~ActiveStreamInfo() {}
556 SpdySession::PushedStreamInfo::PushedStreamInfo() : stream_id(0) {}
558 SpdySession::PushedStreamInfo::PushedStreamInfo(
559 SpdyStreamId stream_id
,
560 base::TimeTicks creation_time
)
561 : stream_id(stream_id
),
562 creation_time(creation_time
) {}
564 SpdySession::PushedStreamInfo::~PushedStreamInfo() {}
567 bool SpdySession::CanPool(TransportSecurityState
* transport_security_state
,
568 const SSLInfo
& ssl_info
,
569 const std::string
& old_hostname
,
570 const std::string
& new_hostname
) {
571 // Pooling is prohibited if the server cert is not valid for the new domain,
572 // and for connections on which client certs were sent. It is also prohibited
573 // when channel ID was sent if the hosts are from different eTLDs+1.
574 if (IsCertStatusError(ssl_info
.cert_status
))
577 if (ssl_info
.client_cert_sent
)
580 if (ssl_info
.channel_id_sent
&&
581 ChannelIDService::GetDomainForHost(new_hostname
) !=
582 ChannelIDService::GetDomainForHost(old_hostname
)) {
587 if (!ssl_info
.cert
->VerifyNameMatch(new_hostname
, &unused
))
590 std::string pinning_failure_log
;
591 if (!transport_security_state
->CheckPublicKeyPins(
593 ssl_info
.is_issued_by_known_root
,
594 ssl_info
.public_key_hashes
,
595 &pinning_failure_log
)) {
602 SpdySession::SpdySession(
603 const SpdySessionKey
& spdy_session_key
,
604 const base::WeakPtr
<HttpServerProperties
>& http_server_properties
,
605 TransportSecurityState
* transport_security_state
,
606 bool verify_domain_authentication
,
607 bool enable_sending_initial_data
,
608 bool enable_compression
,
609 bool enable_ping_based_connection_checking
,
610 NextProto default_protocol
,
611 size_t session_max_recv_window_size
,
612 size_t stream_max_recv_window_size
,
613 size_t initial_max_concurrent_streams
,
614 size_t max_concurrent_streams_limit
,
616 const HostPortPair
& trusted_spdy_proxy
,
618 : in_io_loop_(false),
619 spdy_session_key_(spdy_session_key
),
621 http_server_properties_(http_server_properties
),
622 transport_security_state_(transport_security_state
),
623 read_buffer_(new IOBuffer(kReadBufferSize
)),
624 stream_hi_water_mark_(kFirstStreamId
),
625 last_accepted_push_stream_id_(0),
626 num_pushed_streams_(0u),
627 num_active_pushed_streams_(0u),
628 in_flight_write_frame_type_(DATA
),
629 in_flight_write_frame_size_(0),
631 certificate_error_code_(OK
),
632 availability_state_(STATE_AVAILABLE
),
633 read_state_(READ_STATE_DO_READ
),
634 write_state_(WRITE_STATE_IDLE
),
636 max_concurrent_streams_(initial_max_concurrent_streams
== 0
637 ? kInitialMaxConcurrentStreams
638 : initial_max_concurrent_streams
),
639 max_concurrent_streams_limit_(max_concurrent_streams_limit
== 0
640 ? kMaxConcurrentStreamLimit
641 : max_concurrent_streams_limit
),
642 max_concurrent_pushed_streams_(kMaxConcurrentPushedStreams
),
643 streams_initiated_count_(0),
644 streams_pushed_count_(0),
645 streams_pushed_and_claimed_count_(0),
646 streams_abandoned_count_(0),
647 total_bytes_received_(0),
648 sent_settings_(false),
649 received_settings_(false),
653 last_activity_time_(time_func()),
654 last_compressed_frame_len_(0),
655 check_ping_status_pending_(false),
656 send_connection_header_prefix_(false),
657 flow_control_state_(FLOW_CONTROL_NONE
),
658 session_send_window_size_(0),
659 session_max_recv_window_size_(session_max_recv_window_size
),
660 session_recv_window_size_(0),
661 session_unacked_recv_window_bytes_(0),
662 stream_initial_send_window_size_(GetInitialWindowSize(default_protocol
)),
663 stream_max_recv_window_size_(stream_max_recv_window_size
),
664 net_log_(BoundNetLog::Make(net_log
, NetLog::SOURCE_HTTP2_SESSION
)),
665 verify_domain_authentication_(verify_domain_authentication
),
666 enable_sending_initial_data_(enable_sending_initial_data
),
667 enable_compression_(enable_compression
),
668 enable_ping_based_connection_checking_(
669 enable_ping_based_connection_checking
),
670 protocol_(default_protocol
),
671 connection_at_risk_of_loss_time_(
672 base::TimeDelta::FromSeconds(kDefaultConnectionAtRiskOfLossSeconds
)),
673 hung_interval_(base::TimeDelta::FromSeconds(kHungIntervalSeconds
)),
674 trusted_spdy_proxy_(trusted_spdy_proxy
),
675 time_func_(time_func
),
676 weak_factory_(this) {
677 DCHECK_GE(protocol_
, kProtoSPDYMinimumVersion
);
678 DCHECK_LE(protocol_
, kProtoSPDYMaximumVersion
);
679 DCHECK(HttpStreamFactory::spdy_enabled());
681 NetLog::TYPE_HTTP2_SESSION
,
682 base::Bind(&NetLogSpdySessionCallback
, &host_port_proxy_pair()));
683 next_unclaimed_push_stream_sweep_time_
= time_func_() +
684 base::TimeDelta::FromSeconds(kMinPushedStreamLifetimeSeconds
);
685 // TODO(mbelshe): consider randomization of the stream_hi_water_mark.
688 SpdySession::~SpdySession() {
692 // TODO(akalin): Check connection->is_initialized() instead. This
693 // requires re-working CreateFakeSpdySession(), though.
694 DCHECK(connection_
->socket());
695 // With SPDY we can't recycle sockets.
696 connection_
->socket()->Disconnect();
700 net_log_
.EndEvent(NetLog::TYPE_HTTP2_SESSION
);
703 void SpdySession::InitializeWithSocket(
704 scoped_ptr
<ClientSocketHandle
> connection
,
705 SpdySessionPool
* pool
,
707 int certificate_error_code
) {
709 DCHECK_EQ(availability_state_
, STATE_AVAILABLE
);
710 DCHECK_EQ(read_state_
, READ_STATE_DO_READ
);
711 DCHECK_EQ(write_state_
, WRITE_STATE_IDLE
);
712 DCHECK(!connection_
);
714 DCHECK(certificate_error_code
== OK
||
715 certificate_error_code
< ERR_IO_PENDING
);
716 // TODO(akalin): Check connection->is_initialized() instead. This
717 // requires re-working CreateFakeSpdySession(), though.
718 DCHECK(connection
->socket());
720 connection_
= connection
.Pass();
721 is_secure_
= is_secure
;
722 certificate_error_code_
= certificate_error_code
;
724 NextProto protocol_negotiated
=
725 connection_
->socket()->GetNegotiatedProtocol();
726 if (protocol_negotiated
!= kProtoUnknown
) {
727 protocol_
= protocol_negotiated
;
728 stream_initial_send_window_size_
= GetInitialWindowSize(protocol_
);
730 DCHECK_GE(protocol_
, kProtoSPDYMinimumVersion
);
731 DCHECK_LE(protocol_
, kProtoSPDYMaximumVersion
);
733 if ((protocol_
>= kProtoSPDY4MinimumVersion
) &&
734 (protocol_
<= kProtoSPDY4MaximumVersion
))
735 send_connection_header_prefix_
= true;
737 if (protocol_
>= kProtoSPDY31
) {
738 flow_control_state_
= FLOW_CONTROL_STREAM_AND_SESSION
;
739 session_send_window_size_
= GetInitialWindowSize(protocol_
);
740 session_recv_window_size_
= GetInitialWindowSize(protocol_
);
741 } else if (protocol_
>= kProtoSPDY3
) {
742 flow_control_state_
= FLOW_CONTROL_STREAM
;
744 flow_control_state_
= FLOW_CONTROL_NONE
;
747 buffered_spdy_framer_
.reset(
748 new BufferedSpdyFramer(NextProtoToSpdyMajorVersion(protocol_
),
749 enable_compression_
));
750 buffered_spdy_framer_
->set_visitor(this);
751 buffered_spdy_framer_
->set_debug_visitor(this);
752 UMA_HISTOGRAM_ENUMERATION(
754 protocol_
- kProtoSPDYHistogramOffset
,
755 kProtoSPDYMaximumVersion
- kProtoSPDYMinimumVersion
+ 1);
758 NetLog::TYPE_HTTP2_SESSION_INITIALIZED
,
759 base::Bind(&NetLogSpdyInitializedCallback
,
760 connection_
->socket()->NetLog().source(), protocol_
));
762 DCHECK_EQ(availability_state_
, STATE_AVAILABLE
);
763 connection_
->AddHigherLayeredPool(this);
764 if (enable_sending_initial_data_
)
768 // Bootstrap the read loop.
769 base::MessageLoop::current()->PostTask(
771 base::Bind(&SpdySession::PumpReadLoop
,
772 weak_factory_
.GetWeakPtr(), READ_STATE_DO_READ
, OK
));
775 bool SpdySession::VerifyDomainAuthentication(const std::string
& domain
) {
776 if (!verify_domain_authentication_
)
779 if (availability_state_
== STATE_DRAINING
)
783 bool was_npn_negotiated
;
784 NextProto protocol_negotiated
= kProtoUnknown
;
785 if (!GetSSLInfo(&ssl_info
, &was_npn_negotiated
, &protocol_negotiated
))
786 return true; // This is not a secure session, so all domains are okay.
788 return CanPool(transport_security_state_
, ssl_info
,
789 host_port_pair().host(), domain
);
792 int SpdySession::GetPushStream(
794 base::WeakPtr
<SpdyStream
>* stream
,
795 const BoundNetLog
& stream_net_log
) {
800 if (availability_state_
== STATE_DRAINING
)
801 return ERR_CONNECTION_CLOSED
;
803 Error err
= TryAccessStream(url
);
807 *stream
= GetActivePushStream(url
);
809 DCHECK_LT(streams_pushed_and_claimed_count_
, streams_pushed_count_
);
810 streams_pushed_and_claimed_count_
++;
815 // {,Try}CreateStream() and TryAccessStream() can be called with
816 // |in_io_loop_| set if a stream is being created in response to
817 // another being closed due to received data.
819 Error
SpdySession::TryAccessStream(const GURL
& url
) {
820 if (is_secure_
&& certificate_error_code_
!= OK
&&
821 (url
.SchemeIs("https") || url
.SchemeIs("wss"))) {
822 RecordProtocolErrorHistogram(
823 PROTOCOL_ERROR_REQUEST_FOR_SECURE_CONTENT_OVER_INSECURE_SESSION
);
825 static_cast<Error
>(certificate_error_code_
),
826 "Tried to get SPDY stream for secure content over an unauthenticated "
828 return ERR_SPDY_PROTOCOL_ERROR
;
833 int SpdySession::TryCreateStream(
834 const base::WeakPtr
<SpdyStreamRequest
>& request
,
835 base::WeakPtr
<SpdyStream
>* stream
) {
838 if (availability_state_
== STATE_GOING_AWAY
)
841 if (availability_state_
== STATE_DRAINING
)
842 return ERR_CONNECTION_CLOSED
;
844 Error err
= TryAccessStream(request
->url());
848 if (!max_concurrent_streams_
||
849 (active_streams_
.size() + created_streams_
.size() - num_pushed_streams_
<
850 max_concurrent_streams_
)) {
851 return CreateStream(*request
, stream
);
855 net_log().AddEvent(NetLog::TYPE_HTTP2_SESSION_STALLED_MAX_STREAMS
);
856 RequestPriority priority
= request
->priority();
857 CHECK_GE(priority
, MINIMUM_PRIORITY
);
858 CHECK_LE(priority
, MAXIMUM_PRIORITY
);
859 pending_create_stream_queues_
[priority
].push_back(request
);
860 return ERR_IO_PENDING
;
863 int SpdySession::CreateStream(const SpdyStreamRequest
& request
,
864 base::WeakPtr
<SpdyStream
>* stream
) {
865 DCHECK_GE(request
.priority(), MINIMUM_PRIORITY
);
866 DCHECK_LE(request
.priority(), MAXIMUM_PRIORITY
);
868 if (availability_state_
== STATE_GOING_AWAY
)
871 if (availability_state_
== STATE_DRAINING
)
872 return ERR_CONNECTION_CLOSED
;
874 Error err
= TryAccessStream(request
.url());
876 // This should have been caught in TryCreateStream().
881 DCHECK(connection_
->socket());
882 UMA_HISTOGRAM_BOOLEAN("Net.SpdySession.CreateStreamWithSocketConnected",
883 connection_
->socket()->IsConnected());
884 if (!connection_
->socket()->IsConnected()) {
886 ERR_CONNECTION_CLOSED
,
887 "Tried to create SPDY stream for a closed socket connection.");
888 return ERR_CONNECTION_CLOSED
;
891 scoped_ptr
<SpdyStream
> new_stream(
892 new SpdyStream(request
.type(), GetWeakPtr(), request
.url(),
893 request
.priority(), stream_initial_send_window_size_
,
894 stream_max_recv_window_size_
, request
.net_log()));
895 *stream
= new_stream
->GetWeakPtr();
896 InsertCreatedStream(new_stream
.Pass());
898 UMA_HISTOGRAM_CUSTOM_COUNTS(
899 "Net.SpdyPriorityCount",
900 static_cast<int>(request
.priority()), 0, 10, 11);
905 void SpdySession::CancelStreamRequest(
906 const base::WeakPtr
<SpdyStreamRequest
>& request
) {
908 RequestPriority priority
= request
->priority();
909 CHECK_GE(priority
, MINIMUM_PRIORITY
);
910 CHECK_LE(priority
, MAXIMUM_PRIORITY
);
913 // |request| should not be in a queue not matching its priority.
914 for (int i
= MINIMUM_PRIORITY
; i
<= MAXIMUM_PRIORITY
; ++i
) {
917 PendingStreamRequestQueue
* queue
= &pending_create_stream_queues_
[i
];
918 DCHECK(std::find_if(queue
->begin(),
920 RequestEquals(request
)) == queue
->end());
924 PendingStreamRequestQueue
* queue
=
925 &pending_create_stream_queues_
[priority
];
926 // Remove |request| from |queue| while preserving the order of the
928 PendingStreamRequestQueue::iterator it
=
929 std::find_if(queue
->begin(), queue
->end(), RequestEquals(request
));
930 // The request may already be removed if there's a
931 // CompleteStreamRequest() in flight.
932 if (it
!= queue
->end()) {
933 it
= queue
->erase(it
);
934 // |request| should be in the queue at most once, and if it is
935 // present, should not be pending completion.
936 DCHECK(std::find_if(it
, queue
->end(), RequestEquals(request
)) ==
941 base::WeakPtr
<SpdyStreamRequest
> SpdySession::GetNextPendingStreamRequest() {
942 for (int j
= MAXIMUM_PRIORITY
; j
>= MINIMUM_PRIORITY
; --j
) {
943 if (pending_create_stream_queues_
[j
].empty())
946 base::WeakPtr
<SpdyStreamRequest
> pending_request
=
947 pending_create_stream_queues_
[j
].front();
948 DCHECK(pending_request
);
949 pending_create_stream_queues_
[j
].pop_front();
950 return pending_request
;
952 return base::WeakPtr
<SpdyStreamRequest
>();
955 void SpdySession::ProcessPendingStreamRequests() {
956 // Like |max_concurrent_streams_|, 0 means infinite for
957 // |max_requests_to_process|.
958 size_t max_requests_to_process
= 0;
959 if (max_concurrent_streams_
!= 0) {
960 max_requests_to_process
=
961 max_concurrent_streams_
-
962 (active_streams_
.size() + created_streams_
.size());
965 max_requests_to_process
== 0 || i
< max_requests_to_process
; ++i
) {
966 base::WeakPtr
<SpdyStreamRequest
> pending_request
=
967 GetNextPendingStreamRequest();
968 if (!pending_request
)
971 // Note that this post can race with other stream creations, and it's
972 // possible that the un-stalled stream will be stalled again if it loses.
973 // TODO(jgraettinger): Provide stronger ordering guarantees.
974 base::MessageLoop::current()->PostTask(
976 base::Bind(&SpdySession::CompleteStreamRequest
,
977 weak_factory_
.GetWeakPtr(),
982 void SpdySession::AddPooledAlias(const SpdySessionKey
& alias_key
) {
983 pooled_aliases_
.insert(alias_key
);
986 SpdyMajorVersion
SpdySession::GetProtocolVersion() const {
987 DCHECK(buffered_spdy_framer_
.get());
988 return buffered_spdy_framer_
->protocol_version();
991 bool SpdySession::HasAcceptableTransportSecurity() const {
992 // If we're not even using TLS, we have no standards to meet.
997 // We don't enforce transport security standards for older SPDY versions.
998 if (GetProtocolVersion() < SPDY4
) {
1003 CHECK(connection_
->socket()->GetSSLInfo(&ssl_info
));
1005 // HTTP/2 requires TLS 1.2+
1006 if (SSLConnectionStatusToVersion(ssl_info
.connection_status
) <
1007 SSL_CONNECTION_VERSION_TLS1_2
) {
1011 if (!IsSecureTLSCipherSuite(
1012 SSLConnectionStatusToCipherSuite(ssl_info
.connection_status
))) {
1019 base::WeakPtr
<SpdySession
> SpdySession::GetWeakPtr() {
1020 return weak_factory_
.GetWeakPtr();
1023 bool SpdySession::CloseOneIdleConnection() {
1024 CHECK(!in_io_loop_
);
1026 if (active_streams_
.empty()) {
1027 DoDrainSession(ERR_CONNECTION_CLOSED
, "Closing idle connection.");
1029 // Return false as the socket wasn't immediately closed.
1033 void SpdySession::EnqueueStreamWrite(
1034 const base::WeakPtr
<SpdyStream
>& stream
,
1035 SpdyFrameType frame_type
,
1036 scoped_ptr
<SpdyBufferProducer
> producer
) {
1037 DCHECK(frame_type
== HEADERS
||
1038 frame_type
== DATA
||
1039 frame_type
== CREDENTIAL
||
1040 frame_type
== SYN_STREAM
);
1041 EnqueueWrite(stream
->priority(), frame_type
, producer
.Pass(), stream
);
1044 scoped_ptr
<SpdyFrame
> SpdySession::CreateSynStream(
1045 SpdyStreamId stream_id
,
1046 RequestPriority priority
,
1047 SpdyControlFlags flags
,
1048 const SpdyHeaderBlock
& block
) {
1049 ActiveStreamMap::const_iterator it
= active_streams_
.find(stream_id
);
1050 CHECK(it
!= active_streams_
.end());
1051 CHECK_EQ(it
->second
.stream
->stream_id(), stream_id
);
1053 SendPrefacePingIfNoneInFlight();
1055 DCHECK(buffered_spdy_framer_
.get());
1056 SpdyPriority spdy_priority
=
1057 ConvertRequestPriorityToSpdyPriority(priority
, GetProtocolVersion());
1059 scoped_ptr
<SpdyFrame
> syn_frame
;
1060 // TODO(hkhalil): Avoid copy of |block|.
1061 if (GetProtocolVersion() <= SPDY3
) {
1062 SpdySynStreamIR
syn_stream(stream_id
);
1063 syn_stream
.set_associated_to_stream_id(0);
1064 syn_stream
.set_priority(spdy_priority
);
1065 syn_stream
.set_fin((flags
& CONTROL_FLAG_FIN
) != 0);
1066 syn_stream
.set_unidirectional((flags
& CONTROL_FLAG_UNIDIRECTIONAL
) != 0);
1067 syn_stream
.set_name_value_block(block
);
1068 syn_frame
.reset(buffered_spdy_framer_
->SerializeFrame(syn_stream
));
1070 SpdyHeadersIR
headers(stream_id
);
1071 headers
.set_priority(spdy_priority
);
1072 headers
.set_has_priority(true);
1073 headers
.set_fin((flags
& CONTROL_FLAG_FIN
) != 0);
1074 headers
.set_name_value_block(block
);
1075 syn_frame
.reset(buffered_spdy_framer_
->SerializeFrame(headers
));
1078 streams_initiated_count_
++;
1080 if (net_log().IsLogging()) {
1081 const NetLog::EventType type
=
1082 (GetProtocolVersion() <= SPDY3
)
1083 ? NetLog::TYPE_HTTP2_SESSION_SYN_STREAM
1084 : NetLog::TYPE_HTTP2_SESSION_SEND_HEADERS
;
1085 net_log().AddEvent(type
,
1086 base::Bind(&NetLogSpdySynStreamSentCallback
, &block
,
1087 (flags
& CONTROL_FLAG_FIN
) != 0,
1088 (flags
& CONTROL_FLAG_UNIDIRECTIONAL
) != 0,
1089 spdy_priority
, stream_id
));
1092 return syn_frame
.Pass();
1095 scoped_ptr
<SpdyBuffer
> SpdySession::CreateDataBuffer(SpdyStreamId stream_id
,
1098 SpdyDataFlags flags
) {
1099 if (availability_state_
== STATE_DRAINING
) {
1100 return scoped_ptr
<SpdyBuffer
>();
1103 ActiveStreamMap::const_iterator it
= active_streams_
.find(stream_id
);
1104 CHECK(it
!= active_streams_
.end());
1105 SpdyStream
* stream
= it
->second
.stream
;
1106 CHECK_EQ(stream
->stream_id(), stream_id
);
1110 return scoped_ptr
<SpdyBuffer
>();
1113 int effective_len
= std::min(len
, kMaxSpdyFrameChunkSize
);
1115 bool send_stalled_by_stream
=
1116 (flow_control_state_
>= FLOW_CONTROL_STREAM
) &&
1117 (stream
->send_window_size() <= 0);
1118 bool send_stalled_by_session
= IsSendStalled();
1120 // NOTE: There's an enum of the same name in histograms.xml.
1121 enum SpdyFrameFlowControlState
{
1123 SEND_STALLED_BY_STREAM
,
1124 SEND_STALLED_BY_SESSION
,
1125 SEND_STALLED_BY_STREAM_AND_SESSION
,
1128 SpdyFrameFlowControlState frame_flow_control_state
= SEND_NOT_STALLED
;
1129 if (send_stalled_by_stream
) {
1130 if (send_stalled_by_session
) {
1131 frame_flow_control_state
= SEND_STALLED_BY_STREAM_AND_SESSION
;
1133 frame_flow_control_state
= SEND_STALLED_BY_STREAM
;
1135 } else if (send_stalled_by_session
) {
1136 frame_flow_control_state
= SEND_STALLED_BY_SESSION
;
1139 if (flow_control_state_
== FLOW_CONTROL_STREAM
) {
1140 UMA_HISTOGRAM_ENUMERATION(
1141 "Net.SpdyFrameStreamFlowControlState",
1142 frame_flow_control_state
,
1143 SEND_STALLED_BY_STREAM
+ 1);
1144 } else if (flow_control_state_
== FLOW_CONTROL_STREAM_AND_SESSION
) {
1145 UMA_HISTOGRAM_ENUMERATION(
1146 "Net.SpdyFrameStreamAndSessionFlowControlState",
1147 frame_flow_control_state
,
1148 SEND_STALLED_BY_STREAM_AND_SESSION
+ 1);
1151 // Obey send window size of the stream if stream flow control is
1153 if (flow_control_state_
>= FLOW_CONTROL_STREAM
) {
1154 if (send_stalled_by_stream
) {
1155 stream
->set_send_stalled_by_flow_control(true);
1156 // Even though we're currently stalled only by the stream, we
1157 // might end up being stalled by the session also.
1158 QueueSendStalledStream(*stream
);
1160 NetLog::TYPE_HTTP2_SESSION_STREAM_STALLED_BY_STREAM_SEND_WINDOW
,
1161 NetLog::IntegerCallback("stream_id", stream_id
));
1162 return scoped_ptr
<SpdyBuffer
>();
1165 effective_len
= std::min(effective_len
, stream
->send_window_size());
1168 // Obey send window size of the session if session flow control is
1170 if (flow_control_state_
== FLOW_CONTROL_STREAM_AND_SESSION
) {
1171 if (send_stalled_by_session
) {
1172 stream
->set_send_stalled_by_flow_control(true);
1173 QueueSendStalledStream(*stream
);
1175 NetLog::TYPE_HTTP2_SESSION_STREAM_STALLED_BY_SESSION_SEND_WINDOW
,
1176 NetLog::IntegerCallback("stream_id", stream_id
));
1177 return scoped_ptr
<SpdyBuffer
>();
1180 effective_len
= std::min(effective_len
, session_send_window_size_
);
1183 DCHECK_GE(effective_len
, 0);
1185 // Clear FIN flag if only some of the data will be in the data
1187 if (effective_len
< len
)
1188 flags
= static_cast<SpdyDataFlags
>(flags
& ~DATA_FLAG_FIN
);
1190 if (net_log().IsLogging()) {
1191 net_log().AddEvent(NetLog::TYPE_HTTP2_SESSION_SEND_DATA
,
1192 base::Bind(&NetLogSpdyDataCallback
, stream_id
,
1193 effective_len
, (flags
& DATA_FLAG_FIN
) != 0));
1196 // Send PrefacePing for DATA_FRAMEs with nonzero payload size.
1197 if (effective_len
> 0)
1198 SendPrefacePingIfNoneInFlight();
1200 // TODO(mbelshe): reduce memory copies here.
1201 DCHECK(buffered_spdy_framer_
.get());
1202 scoped_ptr
<SpdyFrame
> frame(
1203 buffered_spdy_framer_
->CreateDataFrame(
1204 stream_id
, data
->data(),
1205 static_cast<uint32
>(effective_len
), flags
));
1207 scoped_ptr
<SpdyBuffer
> data_buffer(new SpdyBuffer(frame
.Pass()));
1209 // Send window size is based on payload size, so nothing to do if this is
1210 // just a FIN with no payload.
1211 if (flow_control_state_
== FLOW_CONTROL_STREAM_AND_SESSION
&&
1212 effective_len
!= 0) {
1213 DecreaseSendWindowSize(static_cast<int32
>(effective_len
));
1214 data_buffer
->AddConsumeCallback(
1215 base::Bind(&SpdySession::OnWriteBufferConsumed
,
1216 weak_factory_
.GetWeakPtr(),
1217 static_cast<size_t>(effective_len
)));
1220 return data_buffer
.Pass();
1223 void SpdySession::CloseActiveStream(SpdyStreamId stream_id
, int status
) {
1224 DCHECK_NE(stream_id
, 0u);
1226 ActiveStreamMap::iterator it
= active_streams_
.find(stream_id
);
1227 if (it
== active_streams_
.end()) {
1232 CloseActiveStreamIterator(it
, status
);
1235 void SpdySession::CloseCreatedStream(
1236 const base::WeakPtr
<SpdyStream
>& stream
, int status
) {
1237 DCHECK_EQ(stream
->stream_id(), 0u);
1239 CreatedStreamSet::iterator it
= created_streams_
.find(stream
.get());
1240 if (it
== created_streams_
.end()) {
1245 CloseCreatedStreamIterator(it
, status
);
1248 void SpdySession::ResetStream(SpdyStreamId stream_id
,
1249 SpdyRstStreamStatus status
,
1250 const std::string
& description
) {
1251 DCHECK_NE(stream_id
, 0u);
1253 ActiveStreamMap::iterator it
= active_streams_
.find(stream_id
);
1254 if (it
== active_streams_
.end()) {
1259 ResetStreamIterator(it
, status
, description
);
1262 bool SpdySession::IsStreamActive(SpdyStreamId stream_id
) const {
1263 return ContainsKey(active_streams_
, stream_id
);
1266 LoadState
SpdySession::GetLoadState() const {
1267 // Just report that we're idle since the session could be doing
1268 // many things concurrently.
1269 return LOAD_STATE_IDLE
;
1272 void SpdySession::CloseActiveStreamIterator(ActiveStreamMap::iterator it
,
1274 // TODO(mbelshe): We should send a RST_STREAM control frame here
1275 // so that the server can cancel a large send.
1277 scoped_ptr
<SpdyStream
> owned_stream(it
->second
.stream
);
1278 active_streams_
.erase(it
);
1280 // TODO(akalin): When SpdyStream was ref-counted (and
1281 // |unclaimed_pushed_streams_| held scoped_refptr<SpdyStream>), this
1282 // was only done when status was not OK. This meant that pushed
1283 // streams can still be claimed after they're closed. This is
1284 // probably something that we still want to support, although server
1285 // push is hardly used. Write tests for this and fix this. (See
1286 // http://crbug.com/261712 .)
1287 if (owned_stream
->type() == SPDY_PUSH_STREAM
) {
1288 unclaimed_pushed_streams_
.erase(owned_stream
->url());
1289 num_pushed_streams_
--;
1290 if (!owned_stream
->IsReservedRemote())
1291 num_active_pushed_streams_
--;
1294 DeleteStream(owned_stream
.Pass(), status
);
1295 MaybeFinishGoingAway();
1297 // If there are no active streams and the socket pool is stalled, close the
1298 // session to free up a socket slot.
1299 if (active_streams_
.empty() && connection_
->IsPoolStalled()) {
1300 DoDrainSession(ERR_CONNECTION_CLOSED
, "Closing idle connection.");
1304 void SpdySession::CloseCreatedStreamIterator(CreatedStreamSet::iterator it
,
1306 scoped_ptr
<SpdyStream
> owned_stream(*it
);
1307 created_streams_
.erase(it
);
1308 DeleteStream(owned_stream
.Pass(), status
);
1311 void SpdySession::ResetStreamIterator(ActiveStreamMap::iterator it
,
1312 SpdyRstStreamStatus status
,
1313 const std::string
& description
) {
1314 // Send the RST_STREAM frame first as CloseActiveStreamIterator()
1316 SpdyStreamId stream_id
= it
->first
;
1317 RequestPriority priority
= it
->second
.stream
->priority();
1318 EnqueueResetStreamFrame(stream_id
, priority
, status
, description
);
1320 // Removes any pending writes for the stream except for possibly an
1322 CloseActiveStreamIterator(it
, ERR_SPDY_PROTOCOL_ERROR
);
1325 void SpdySession::EnqueueResetStreamFrame(SpdyStreamId stream_id
,
1326 RequestPriority priority
,
1327 SpdyRstStreamStatus status
,
1328 const std::string
& description
) {
1329 DCHECK_NE(stream_id
, 0u);
1332 NetLog::TYPE_HTTP2_SESSION_SEND_RST_STREAM
,
1333 base::Bind(&NetLogSpdyRstCallback
, stream_id
, status
, &description
));
1335 DCHECK(buffered_spdy_framer_
.get());
1336 scoped_ptr
<SpdyFrame
> rst_frame(
1337 buffered_spdy_framer_
->CreateRstStream(stream_id
, status
));
1339 EnqueueSessionWrite(priority
, RST_STREAM
, rst_frame
.Pass());
1340 RecordProtocolErrorHistogram(MapRstStreamStatusToProtocolError(status
));
1343 void SpdySession::PumpReadLoop(ReadState expected_read_state
, int result
) {
1344 // TODO(pkasting): Remove ScopedTracker below once crbug.com/462774 is fixed.
1345 tracked_objects::ScopedTracker
tracking_profile(
1346 FROM_HERE_WITH_EXPLICIT_FUNCTION("462774 SpdySession::PumpReadLoop"));
1348 CHECK(!in_io_loop_
);
1349 if (availability_state_
== STATE_DRAINING
) {
1352 ignore_result(DoReadLoop(expected_read_state
, result
));
1355 int SpdySession::DoReadLoop(ReadState expected_read_state
, int result
) {
1356 CHECK(!in_io_loop_
);
1357 CHECK_EQ(read_state_
, expected_read_state
);
1361 int bytes_read_without_yielding
= 0;
1363 // Loop until the session is draining, the read becomes blocked, or
1364 // the read limit is exceeded.
1366 switch (read_state_
) {
1367 case READ_STATE_DO_READ
:
1368 CHECK_EQ(result
, OK
);
1371 case READ_STATE_DO_READ_COMPLETE
:
1373 bytes_read_without_yielding
+= result
;
1374 result
= DoReadComplete(result
);
1377 NOTREACHED() << "read_state_: " << read_state_
;
1381 if (availability_state_
== STATE_DRAINING
)
1384 if (result
== ERR_IO_PENDING
)
1387 if (bytes_read_without_yielding
> kMaxReadBytesWithoutYielding
) {
1388 read_state_
= READ_STATE_DO_READ
;
1389 base::MessageLoop::current()->PostTask(
1391 base::Bind(&SpdySession::PumpReadLoop
,
1392 weak_factory_
.GetWeakPtr(), READ_STATE_DO_READ
, OK
));
1393 result
= ERR_IO_PENDING
;
1399 in_io_loop_
= false;
1404 int SpdySession::DoRead() {
1408 CHECK(connection_
->socket());
1409 read_state_
= READ_STATE_DO_READ_COMPLETE
;
1410 return connection_
->socket()->Read(
1413 base::Bind(&SpdySession::PumpReadLoop
,
1414 weak_factory_
.GetWeakPtr(), READ_STATE_DO_READ_COMPLETE
));
1417 int SpdySession::DoReadComplete(int result
) {
1420 // Parse a frame. For now this code requires that the frame fit into our
1421 // buffer (kReadBufferSize).
1422 // TODO(mbelshe): support arbitrarily large frames!
1425 UMA_HISTOGRAM_CUSTOM_COUNTS("Net.SpdySession.BytesRead.EOF",
1426 total_bytes_received_
, 1, 100000000, 50);
1427 DoDrainSession(ERR_CONNECTION_CLOSED
, "Connection closed");
1429 return ERR_CONNECTION_CLOSED
;
1433 DoDrainSession(static_cast<Error
>(result
), "result is < 0.");
1436 CHECK_LE(result
, kReadBufferSize
);
1437 total_bytes_received_
+= result
;
1439 last_activity_time_
= time_func_();
1441 DCHECK(buffered_spdy_framer_
.get());
1442 char* data
= read_buffer_
->data();
1443 while (result
> 0) {
1444 uint32 bytes_processed
= buffered_spdy_framer_
->ProcessInput(data
, result
);
1445 result
-= bytes_processed
;
1446 data
+= bytes_processed
;
1448 if (availability_state_
== STATE_DRAINING
) {
1449 return ERR_CONNECTION_CLOSED
;
1452 DCHECK_EQ(buffered_spdy_framer_
->error_code(), SpdyFramer::SPDY_NO_ERROR
);
1455 read_state_
= READ_STATE_DO_READ
;
1459 void SpdySession::PumpWriteLoop(WriteState expected_write_state
, int result
) {
1460 CHECK(!in_io_loop_
);
1461 DCHECK_EQ(write_state_
, expected_write_state
);
1463 DoWriteLoop(expected_write_state
, result
);
1465 if (availability_state_
== STATE_DRAINING
&& !in_flight_write_
&&
1466 write_queue_
.IsEmpty()) {
1467 pool_
->RemoveUnavailableSession(GetWeakPtr()); // Destroys |this|.
1472 int SpdySession::DoWriteLoop(WriteState expected_write_state
, int result
) {
1473 CHECK(!in_io_loop_
);
1474 DCHECK_NE(write_state_
, WRITE_STATE_IDLE
);
1475 DCHECK_EQ(write_state_
, expected_write_state
);
1479 // Loop until the session is closed or the write becomes blocked.
1481 switch (write_state_
) {
1482 case WRITE_STATE_DO_WRITE
:
1483 DCHECK_EQ(result
, OK
);
1486 case WRITE_STATE_DO_WRITE_COMPLETE
:
1487 result
= DoWriteComplete(result
);
1489 case WRITE_STATE_IDLE
:
1491 NOTREACHED() << "write_state_: " << write_state_
;
1495 if (write_state_
== WRITE_STATE_IDLE
) {
1496 DCHECK_EQ(result
, ERR_IO_PENDING
);
1500 if (result
== ERR_IO_PENDING
)
1505 in_io_loop_
= false;
1510 int SpdySession::DoWrite() {
1513 DCHECK(buffered_spdy_framer_
);
1514 if (in_flight_write_
) {
1515 DCHECK_GT(in_flight_write_
->GetRemainingSize(), 0u);
1517 // Grab the next frame to send.
1518 SpdyFrameType frame_type
= DATA
;
1519 scoped_ptr
<SpdyBufferProducer
> producer
;
1520 base::WeakPtr
<SpdyStream
> stream
;
1521 if (!write_queue_
.Dequeue(&frame_type
, &producer
, &stream
)) {
1522 write_state_
= WRITE_STATE_IDLE
;
1523 return ERR_IO_PENDING
;
1527 CHECK(!stream
->IsClosed());
1529 // Activate the stream only when sending the SYN_STREAM frame to
1530 // guarantee monotonically-increasing stream IDs.
1531 if (frame_type
== SYN_STREAM
) {
1532 CHECK(stream
.get());
1533 CHECK_EQ(stream
->stream_id(), 0u);
1534 scoped_ptr
<SpdyStream
> owned_stream
=
1535 ActivateCreatedStream(stream
.get());
1536 InsertActivatedStream(owned_stream
.Pass());
1538 if (stream_hi_water_mark_
> kLastStreamId
) {
1539 CHECK_EQ(stream
->stream_id(), kLastStreamId
);
1540 // We've exhausted the stream ID space, and no new streams may be
1541 // created after this one.
1543 StartGoingAway(kLastStreamId
, ERR_ABORTED
);
1547 // TODO(pkasting): Remove ScopedTracker below once crbug.com/457517 is
1549 tracked_objects::ScopedTracker
tracking_profile1(
1550 FROM_HERE_WITH_EXPLICIT_FUNCTION("457517 SpdySession::DoWrite1"));
1551 in_flight_write_
= producer
->ProduceBuffer();
1552 if (!in_flight_write_
) {
1554 return ERR_UNEXPECTED
;
1556 in_flight_write_frame_type_
= frame_type
;
1557 in_flight_write_frame_size_
= in_flight_write_
->GetRemainingSize();
1558 DCHECK_GE(in_flight_write_frame_size_
,
1559 buffered_spdy_framer_
->GetFrameMinimumSize());
1560 in_flight_write_stream_
= stream
;
1563 write_state_
= WRITE_STATE_DO_WRITE_COMPLETE
;
1565 // Explicitly store in a scoped_refptr<IOBuffer> to avoid problems
1566 // with Socket implementations that don't store their IOBuffer
1567 // argument in a scoped_refptr<IOBuffer> (see crbug.com/232345).
1568 // TODO(pkasting): Remove ScopedTracker below once crbug.com/457517 is fixed.
1569 tracked_objects::ScopedTracker
tracking_profile2(
1570 FROM_HERE_WITH_EXPLICIT_FUNCTION("457517 SpdySession::DoWrite2"));
1571 scoped_refptr
<IOBuffer
> write_io_buffer
=
1572 in_flight_write_
->GetIOBufferForRemainingData();
1573 return connection_
->socket()->Write(
1574 write_io_buffer
.get(),
1575 in_flight_write_
->GetRemainingSize(),
1576 base::Bind(&SpdySession::PumpWriteLoop
,
1577 weak_factory_
.GetWeakPtr(), WRITE_STATE_DO_WRITE_COMPLETE
));
1580 int SpdySession::DoWriteComplete(int result
) {
1582 DCHECK_NE(result
, ERR_IO_PENDING
);
1583 DCHECK_GT(in_flight_write_
->GetRemainingSize(), 0u);
1585 last_activity_time_
= time_func_();
1588 DCHECK_NE(result
, ERR_IO_PENDING
);
1589 in_flight_write_
.reset();
1590 in_flight_write_frame_type_
= DATA
;
1591 in_flight_write_frame_size_
= 0;
1592 in_flight_write_stream_
.reset();
1593 write_state_
= WRITE_STATE_DO_WRITE
;
1594 DoDrainSession(static_cast<Error
>(result
), "Write error");
1598 // It should not be possible to have written more bytes than our
1599 // in_flight_write_.
1600 DCHECK_LE(static_cast<size_t>(result
),
1601 in_flight_write_
->GetRemainingSize());
1604 in_flight_write_
->Consume(static_cast<size_t>(result
));
1606 // We only notify the stream when we've fully written the pending frame.
1607 if (in_flight_write_
->GetRemainingSize() == 0) {
1608 // It is possible that the stream was cancelled while we were
1609 // writing to the socket.
1610 if (in_flight_write_stream_
.get()) {
1611 DCHECK_GT(in_flight_write_frame_size_
, 0u);
1612 in_flight_write_stream_
->OnFrameWriteComplete(
1613 in_flight_write_frame_type_
,
1614 in_flight_write_frame_size_
);
1617 // Cleanup the write which just completed.
1618 in_flight_write_
.reset();
1619 in_flight_write_frame_type_
= DATA
;
1620 in_flight_write_frame_size_
= 0;
1621 in_flight_write_stream_
.reset();
1625 write_state_
= WRITE_STATE_DO_WRITE
;
1629 void SpdySession::DcheckGoingAway() const {
1631 DCHECK_GE(availability_state_
, STATE_GOING_AWAY
);
1632 for (int i
= MINIMUM_PRIORITY
; i
<= MAXIMUM_PRIORITY
; ++i
) {
1633 DCHECK(pending_create_stream_queues_
[i
].empty());
1635 DCHECK(created_streams_
.empty());
1639 void SpdySession::DcheckDraining() const {
1641 DCHECK_EQ(availability_state_
, STATE_DRAINING
);
1642 DCHECK(active_streams_
.empty());
1643 DCHECK(unclaimed_pushed_streams_
.empty());
1646 void SpdySession::StartGoingAway(SpdyStreamId last_good_stream_id
,
1648 DCHECK_GE(availability_state_
, STATE_GOING_AWAY
);
1650 // The loops below are carefully written to avoid reentrancy problems.
1653 size_t old_size
= GetTotalSize(pending_create_stream_queues_
);
1654 base::WeakPtr
<SpdyStreamRequest
> pending_request
=
1655 GetNextPendingStreamRequest();
1656 if (!pending_request
)
1658 // No new stream requests should be added while the session is
1660 DCHECK_GT(old_size
, GetTotalSize(pending_create_stream_queues_
));
1661 pending_request
->OnRequestCompleteFailure(ERR_ABORTED
);
1665 size_t old_size
= active_streams_
.size();
1666 ActiveStreamMap::iterator it
=
1667 active_streams_
.lower_bound(last_good_stream_id
+ 1);
1668 if (it
== active_streams_
.end())
1670 LogAbandonedActiveStream(it
, status
);
1671 CloseActiveStreamIterator(it
, status
);
1672 // No new streams should be activated while the session is going
1674 DCHECK_GT(old_size
, active_streams_
.size());
1677 while (!created_streams_
.empty()) {
1678 size_t old_size
= created_streams_
.size();
1679 CreatedStreamSet::iterator it
= created_streams_
.begin();
1680 LogAbandonedStream(*it
, status
);
1681 CloseCreatedStreamIterator(it
, status
);
1682 // No new streams should be created while the session is going
1684 DCHECK_GT(old_size
, created_streams_
.size());
1687 write_queue_
.RemovePendingWritesForStreamsAfter(last_good_stream_id
);
1692 void SpdySession::MaybeFinishGoingAway() {
1693 if (active_streams_
.empty() && availability_state_
== STATE_GOING_AWAY
) {
1694 DoDrainSession(OK
, "Finished going away");
1698 void SpdySession::DoDrainSession(Error err
, const std::string
& description
) {
1699 if (availability_state_
== STATE_DRAINING
) {
1704 // Mark host_port_pair requiring HTTP/1.1 for subsequent connections.
1705 if (err
== ERR_HTTP_1_1_REQUIRED
) {
1706 http_server_properties_
->SetHTTP11Required(host_port_pair());
1709 // If |err| indicates an error occurred, inform the peer that we're closing
1710 // and why. Don't GOAWAY on a graceful or idle close, as that may
1711 // unnecessarily wake the radio. We could technically GOAWAY on network errors
1712 // (we'll probably fail to actually write it, but that's okay), however many
1713 // unit-tests would need to be updated.
1715 err
!= ERR_ABORTED
&& // Used by SpdySessionPool to close idle sessions.
1716 err
!= ERR_NETWORK_CHANGED
&& // Used to deprecate sessions on IP change.
1717 err
!= ERR_SOCKET_NOT_CONNECTED
&& err
!= ERR_HTTP_1_1_REQUIRED
&&
1718 err
!= ERR_CONNECTION_CLOSED
&& err
!= ERR_CONNECTION_RESET
) {
1719 // Enqueue a GOAWAY to inform the peer of why we're closing the connection.
1720 SpdyGoAwayIR
goaway_ir(last_accepted_push_stream_id_
,
1721 MapNetErrorToGoAwayStatus(err
),
1723 EnqueueSessionWrite(HIGHEST
,
1725 scoped_ptr
<SpdyFrame
>(
1726 buffered_spdy_framer_
->SerializeFrame(goaway_ir
)));
1729 availability_state_
= STATE_DRAINING
;
1730 error_on_close_
= err
;
1733 NetLog::TYPE_HTTP2_SESSION_CLOSE
,
1734 base::Bind(&NetLogSpdySessionCloseCallback
, err
, &description
));
1736 UMA_HISTOGRAM_SPARSE_SLOWLY("Net.SpdySession.ClosedOnError", -err
);
1737 UMA_HISTOGRAM_CUSTOM_COUNTS("Net.SpdySession.BytesRead.OtherErrors",
1738 total_bytes_received_
, 1, 100000000, 50);
1741 // We ought to be going away already, as this is a graceful close.
1744 StartGoingAway(0, err
);
1747 MaybePostWriteLoop();
1750 void SpdySession::LogAbandonedStream(SpdyStream
* stream
, Error status
) {
1752 std::string description
= base::StringPrintf(
1753 "ABANDONED (stream_id=%d): ", stream
->stream_id()) +
1754 stream
->url().spec();
1755 stream
->LogStreamError(status
, description
);
1756 // We don't increment the streams abandoned counter here. If the
1757 // stream isn't active (i.e., it hasn't written anything to the wire
1758 // yet) then it's as if it never existed. If it is active, then
1759 // LogAbandonedActiveStream() will increment the counters.
1762 void SpdySession::LogAbandonedActiveStream(ActiveStreamMap::const_iterator it
,
1764 DCHECK_GT(it
->first
, 0u);
1765 LogAbandonedStream(it
->second
.stream
, status
);
1766 ++streams_abandoned_count_
;
1767 if (it
->second
.stream
->type() == SPDY_PUSH_STREAM
&&
1768 unclaimed_pushed_streams_
.find(it
->second
.stream
->url()) !=
1769 unclaimed_pushed_streams_
.end()) {
1773 SpdyStreamId
SpdySession::GetNewStreamId() {
1774 CHECK_LE(stream_hi_water_mark_
, kLastStreamId
);
1775 SpdyStreamId id
= stream_hi_water_mark_
;
1776 stream_hi_water_mark_
+= 2;
1780 void SpdySession::CloseSessionOnError(Error err
,
1781 const std::string
& description
) {
1782 DCHECK_LT(err
, ERR_IO_PENDING
);
1783 DoDrainSession(err
, description
);
1786 void SpdySession::MakeUnavailable() {
1787 if (availability_state_
== STATE_AVAILABLE
) {
1788 availability_state_
= STATE_GOING_AWAY
;
1789 pool_
->MakeSessionUnavailable(GetWeakPtr());
1793 base::Value
* SpdySession::GetInfoAsValue() const {
1794 base::DictionaryValue
* dict
= new base::DictionaryValue();
1796 dict
->SetInteger("source_id", net_log_
.source().id
);
1798 dict
->SetString("host_port_pair", host_port_pair().ToString());
1799 if (!pooled_aliases_
.empty()) {
1800 base::ListValue
* alias_list
= new base::ListValue();
1801 for (std::set
<SpdySessionKey
>::const_iterator it
=
1802 pooled_aliases_
.begin();
1803 it
!= pooled_aliases_
.end(); it
++) {
1804 alias_list
->Append(new base::StringValue(
1805 it
->host_port_pair().ToString()));
1807 dict
->Set("aliases", alias_list
);
1809 dict
->SetString("proxy", host_port_proxy_pair().second
.ToURI());
1811 dict
->SetInteger("active_streams", active_streams_
.size());
1813 dict
->SetInteger("unclaimed_pushed_streams",
1814 unclaimed_pushed_streams_
.size());
1816 dict
->SetBoolean("is_secure", is_secure_
);
1818 dict
->SetString("protocol_negotiated",
1819 SSLClientSocket::NextProtoToString(
1820 connection_
->socket()->GetNegotiatedProtocol()));
1822 dict
->SetInteger("error", error_on_close_
);
1823 dict
->SetInteger("max_concurrent_streams", max_concurrent_streams_
);
1825 dict
->SetInteger("streams_initiated_count", streams_initiated_count_
);
1826 dict
->SetInteger("streams_pushed_count", streams_pushed_count_
);
1827 dict
->SetInteger("streams_pushed_and_claimed_count",
1828 streams_pushed_and_claimed_count_
);
1829 dict
->SetInteger("streams_abandoned_count", streams_abandoned_count_
);
1830 DCHECK(buffered_spdy_framer_
.get());
1831 dict
->SetInteger("frames_received", buffered_spdy_framer_
->frames_received());
1833 dict
->SetBoolean("sent_settings", sent_settings_
);
1834 dict
->SetBoolean("received_settings", received_settings_
);
1836 dict
->SetInteger("send_window_size", session_send_window_size_
);
1837 dict
->SetInteger("recv_window_size", session_recv_window_size_
);
1838 dict
->SetInteger("unacked_recv_window_bytes",
1839 session_unacked_recv_window_bytes_
);
1843 bool SpdySession::IsReused() const {
1844 return buffered_spdy_framer_
->frames_received() > 0 ||
1845 connection_
->reuse_type() == ClientSocketHandle::UNUSED_IDLE
;
1848 bool SpdySession::GetLoadTimingInfo(SpdyStreamId stream_id
,
1849 LoadTimingInfo
* load_timing_info
) const {
1850 return connection_
->GetLoadTimingInfo(stream_id
!= kFirstStreamId
,
1854 int SpdySession::GetPeerAddress(IPEndPoint
* address
) const {
1855 int rv
= ERR_SOCKET_NOT_CONNECTED
;
1856 if (connection_
->socket()) {
1857 rv
= connection_
->socket()->GetPeerAddress(address
);
1860 UMA_HISTOGRAM_BOOLEAN("Net.SpdySessionSocketNotConnectedGetPeerAddress",
1861 rv
== ERR_SOCKET_NOT_CONNECTED
);
1866 int SpdySession::GetLocalAddress(IPEndPoint
* address
) const {
1867 int rv
= ERR_SOCKET_NOT_CONNECTED
;
1868 if (connection_
->socket()) {
1869 rv
= connection_
->socket()->GetLocalAddress(address
);
1872 UMA_HISTOGRAM_BOOLEAN("Net.SpdySessionSocketNotConnectedGetLocalAddress",
1873 rv
== ERR_SOCKET_NOT_CONNECTED
);
1878 void SpdySession::EnqueueSessionWrite(RequestPriority priority
,
1879 SpdyFrameType frame_type
,
1880 scoped_ptr
<SpdyFrame
> frame
) {
1881 DCHECK(frame_type
== RST_STREAM
|| frame_type
== SETTINGS
||
1882 frame_type
== WINDOW_UPDATE
|| frame_type
== PING
||
1883 frame_type
== GOAWAY
);
1885 priority
, frame_type
,
1886 scoped_ptr
<SpdyBufferProducer
>(
1887 new SimpleBufferProducer(
1888 scoped_ptr
<SpdyBuffer
>(new SpdyBuffer(frame
.Pass())))),
1889 base::WeakPtr
<SpdyStream
>());
1892 void SpdySession::EnqueueWrite(RequestPriority priority
,
1893 SpdyFrameType frame_type
,
1894 scoped_ptr
<SpdyBufferProducer
> producer
,
1895 const base::WeakPtr
<SpdyStream
>& stream
) {
1896 if (availability_state_
== STATE_DRAINING
)
1899 write_queue_
.Enqueue(priority
, frame_type
, producer
.Pass(), stream
);
1900 MaybePostWriteLoop();
1903 void SpdySession::MaybePostWriteLoop() {
1904 if (write_state_
== WRITE_STATE_IDLE
) {
1905 CHECK(!in_flight_write_
);
1906 write_state_
= WRITE_STATE_DO_WRITE
;
1907 base::MessageLoop::current()->PostTask(
1909 base::Bind(&SpdySession::PumpWriteLoop
,
1910 weak_factory_
.GetWeakPtr(), WRITE_STATE_DO_WRITE
, OK
));
1914 void SpdySession::InsertCreatedStream(scoped_ptr
<SpdyStream
> stream
) {
1915 CHECK_EQ(stream
->stream_id(), 0u);
1916 CHECK(created_streams_
.find(stream
.get()) == created_streams_
.end());
1917 created_streams_
.insert(stream
.release());
1920 scoped_ptr
<SpdyStream
> SpdySession::ActivateCreatedStream(SpdyStream
* stream
) {
1921 CHECK_EQ(stream
->stream_id(), 0u);
1922 CHECK(created_streams_
.find(stream
) != created_streams_
.end());
1923 stream
->set_stream_id(GetNewStreamId());
1924 scoped_ptr
<SpdyStream
> owned_stream(stream
);
1925 created_streams_
.erase(stream
);
1926 return owned_stream
.Pass();
1929 void SpdySession::InsertActivatedStream(scoped_ptr
<SpdyStream
> stream
) {
1930 SpdyStreamId stream_id
= stream
->stream_id();
1931 CHECK_NE(stream_id
, 0u);
1932 std::pair
<ActiveStreamMap::iterator
, bool> result
=
1933 active_streams_
.insert(
1934 std::make_pair(stream_id
, ActiveStreamInfo(stream
.get())));
1935 CHECK(result
.second
);
1936 ignore_result(stream
.release());
1939 void SpdySession::DeleteStream(scoped_ptr
<SpdyStream
> stream
, int status
) {
1940 if (in_flight_write_stream_
.get() == stream
.get()) {
1941 // If we're deleting the stream for the in-flight write, we still
1942 // need to let the write complete, so we clear
1943 // |in_flight_write_stream_| and let the write finish on its own
1944 // without notifying |in_flight_write_stream_|.
1945 in_flight_write_stream_
.reset();
1948 write_queue_
.RemovePendingWritesForStream(stream
->GetWeakPtr());
1949 stream
->OnClose(status
);
1951 if (availability_state_
== STATE_AVAILABLE
) {
1952 ProcessPendingStreamRequests();
1956 base::WeakPtr
<SpdyStream
> SpdySession::GetActivePushStream(const GURL
& url
) {
1957 PushedStreamMap::iterator unclaimed_it
= unclaimed_pushed_streams_
.find(url
);
1958 if (unclaimed_it
== unclaimed_pushed_streams_
.end())
1959 return base::WeakPtr
<SpdyStream
>();
1961 SpdyStreamId stream_id
= unclaimed_it
->second
.stream_id
;
1962 unclaimed_pushed_streams_
.erase(unclaimed_it
);
1964 ActiveStreamMap::iterator active_it
= active_streams_
.find(stream_id
);
1965 if (active_it
== active_streams_
.end()) {
1967 return base::WeakPtr
<SpdyStream
>();
1970 net_log_
.AddEvent(NetLog::TYPE_HTTP2_STREAM_ADOPTED_PUSH_STREAM
,
1971 base::Bind(&NetLogSpdyAdoptedPushStreamCallback
,
1972 active_it
->second
.stream
->stream_id(), &url
));
1973 return active_it
->second
.stream
->GetWeakPtr();
1976 bool SpdySession::GetSSLInfo(SSLInfo
* ssl_info
,
1977 bool* was_npn_negotiated
,
1978 NextProto
* protocol_negotiated
) {
1979 *was_npn_negotiated
= connection_
->socket()->WasNpnNegotiated();
1980 *protocol_negotiated
= connection_
->socket()->GetNegotiatedProtocol();
1981 return connection_
->socket()->GetSSLInfo(ssl_info
);
1984 bool SpdySession::GetSSLCertRequestInfo(
1985 SSLCertRequestInfo
* cert_request_info
) {
1988 GetSSLClientSocket()->GetSSLCertRequestInfo(cert_request_info
);
1992 void SpdySession::OnError(SpdyFramer::SpdyError error_code
) {
1995 RecordProtocolErrorHistogram(MapFramerErrorToProtocolError(error_code
));
1996 std::string description
=
1997 base::StringPrintf("Framer error: %d (%s).",
1999 SpdyFramer::ErrorCodeToString(error_code
));
2000 DoDrainSession(MapFramerErrorToNetError(error_code
), description
);
2003 void SpdySession::OnStreamError(SpdyStreamId stream_id
,
2004 const std::string
& description
) {
2007 ActiveStreamMap::iterator it
= active_streams_
.find(stream_id
);
2008 if (it
== active_streams_
.end()) {
2009 // We still want to send a frame to reset the stream even if we
2010 // don't know anything about it.
2011 EnqueueResetStreamFrame(
2012 stream_id
, IDLE
, RST_STREAM_PROTOCOL_ERROR
, description
);
2016 ResetStreamIterator(it
, RST_STREAM_PROTOCOL_ERROR
, description
);
2019 void SpdySession::OnDataFrameHeader(SpdyStreamId stream_id
,
2024 ActiveStreamMap::iterator it
= active_streams_
.find(stream_id
);
2026 // By the time data comes in, the stream may already be inactive.
2027 if (it
== active_streams_
.end())
2030 SpdyStream
* stream
= it
->second
.stream
;
2031 CHECK_EQ(stream
->stream_id(), stream_id
);
2033 DCHECK(buffered_spdy_framer_
);
2034 size_t header_len
= buffered_spdy_framer_
->GetDataFrameMinimumSize();
2035 stream
->IncrementRawReceivedBytes(header_len
);
2038 void SpdySession::OnStreamFrameData(SpdyStreamId stream_id
,
2043 DCHECK_LT(len
, 1u << 24);
2044 if (net_log().IsLogging()) {
2046 NetLog::TYPE_HTTP2_SESSION_RECV_DATA
,
2047 base::Bind(&NetLogSpdyDataCallback
, stream_id
, len
, fin
));
2050 // Build the buffer as early as possible so that we go through the
2051 // session flow control checks and update
2052 // |unacked_recv_window_bytes_| properly even when the stream is
2053 // inactive (since the other side has still reduced its session send
2055 scoped_ptr
<SpdyBuffer
> buffer
;
2058 CHECK_LE(len
, static_cast<size_t>(kReadBufferSize
));
2059 buffer
.reset(new SpdyBuffer(data
, len
));
2061 if (flow_control_state_
== FLOW_CONTROL_STREAM_AND_SESSION
) {
2062 DecreaseRecvWindowSize(static_cast<int32
>(len
));
2063 buffer
->AddConsumeCallback(
2064 base::Bind(&SpdySession::OnReadBufferConsumed
,
2065 weak_factory_
.GetWeakPtr()));
2071 ActiveStreamMap::iterator it
= active_streams_
.find(stream_id
);
2073 // By the time data comes in, the stream may already be inactive.
2074 if (it
== active_streams_
.end())
2077 SpdyStream
* stream
= it
->second
.stream
;
2078 CHECK_EQ(stream
->stream_id(), stream_id
);
2080 stream
->IncrementRawReceivedBytes(len
);
2082 if (it
->second
.waiting_for_syn_reply
) {
2083 const std::string
& error
= "Data received before SYN_REPLY.";
2084 stream
->LogStreamError(ERR_SPDY_PROTOCOL_ERROR
, error
);
2085 ResetStreamIterator(it
, RST_STREAM_PROTOCOL_ERROR
, error
);
2089 stream
->OnDataReceived(buffer
.Pass());
2092 void SpdySession::OnStreamPadding(SpdyStreamId stream_id
, size_t len
) {
2095 if (flow_control_state_
!= FLOW_CONTROL_STREAM_AND_SESSION
)
2098 // Decrease window size because padding bytes are received.
2099 // Increase window size because padding bytes are consumed (by discarding).
2100 // Net result: |session_unacked_recv_window_bytes_| increases by |len|,
2101 // |session_recv_window_size_| does not change.
2102 DecreaseRecvWindowSize(static_cast<int32
>(len
));
2103 IncreaseRecvWindowSize(static_cast<int32
>(len
));
2105 ActiveStreamMap::iterator it
= active_streams_
.find(stream_id
);
2106 if (it
== active_streams_
.end())
2108 it
->second
.stream
->OnPaddingConsumed(len
);
2111 void SpdySession::OnSettings(bool clear_persisted
) {
2114 if (clear_persisted
)
2115 http_server_properties_
->ClearSpdySettings(host_port_pair());
2117 if (net_log_
.IsLogging()) {
2118 net_log_
.AddEvent(NetLog::TYPE_HTTP2_SESSION_RECV_SETTINGS
,
2119 base::Bind(&NetLogSpdySettingsCallback
, host_port_pair(),
2123 if (GetProtocolVersion() >= SPDY4
) {
2124 // Send an acknowledgment of the setting.
2125 SpdySettingsIR settings_ir
;
2126 settings_ir
.set_is_ack(true);
2127 EnqueueSessionWrite(
2130 scoped_ptr
<SpdyFrame
>(
2131 buffered_spdy_framer_
->SerializeFrame(settings_ir
)));
2135 void SpdySession::OnSetting(SpdySettingsIds id
,
2140 HandleSetting(id
, value
);
2141 http_server_properties_
->SetSpdySetting(
2144 static_cast<SpdySettingsFlags
>(flags
),
2146 received_settings_
= true;
2149 const SpdyMajorVersion protocol_version
= GetProtocolVersion();
2150 net_log_
.AddEvent(NetLog::TYPE_HTTP2_SESSION_RECV_SETTING
,
2151 base::Bind(&NetLogSpdySettingCallback
, id
, protocol_version
,
2152 static_cast<SpdySettingsFlags
>(flags
), value
));
2155 void SpdySession::OnSendCompressedFrame(
2156 SpdyStreamId stream_id
,
2160 if (type
!= SYN_STREAM
&& type
!= HEADERS
)
2163 DCHECK(buffered_spdy_framer_
.get());
2164 size_t compressed_len
=
2165 frame_len
- buffered_spdy_framer_
->GetSynStreamMinimumSize();
2168 // Make sure we avoid early decimal truncation.
2169 int compression_pct
= 100 - (100 * compressed_len
) / payload_len
;
2170 UMA_HISTOGRAM_PERCENTAGE("Net.SpdySynStreamCompressionPercentage",
2175 void SpdySession::OnReceiveCompressedFrame(
2176 SpdyStreamId stream_id
,
2179 last_compressed_frame_len_
= frame_len
;
2182 int SpdySession::OnInitialResponseHeadersReceived(
2183 const SpdyHeaderBlock
& response_headers
,
2184 base::Time response_time
,
2185 base::TimeTicks recv_first_byte_time
,
2186 SpdyStream
* stream
) {
2188 SpdyStreamId stream_id
= stream
->stream_id();
2190 if (stream
->type() == SPDY_PUSH_STREAM
) {
2191 DCHECK(stream
->IsReservedRemote());
2192 if (max_concurrent_pushed_streams_
&&
2193 num_active_pushed_streams_
>= max_concurrent_pushed_streams_
) {
2194 ResetStream(stream_id
,
2195 RST_STREAM_REFUSED_STREAM
,
2196 "Stream concurrency limit reached.");
2197 return STATUS_CODE_REFUSED_STREAM
;
2201 if (stream
->type() == SPDY_PUSH_STREAM
) {
2202 // Will be balanced in DeleteStream.
2203 num_active_pushed_streams_
++;
2206 // May invalidate |stream|.
2207 int rv
= stream
->OnInitialResponseHeadersReceived(
2208 response_headers
, response_time
, recv_first_byte_time
);
2210 DCHECK_NE(rv
, ERR_IO_PENDING
);
2211 DCHECK(active_streams_
.find(stream_id
) == active_streams_
.end());
2217 void SpdySession::OnSynStream(SpdyStreamId stream_id
,
2218 SpdyStreamId associated_stream_id
,
2219 SpdyPriority priority
,
2221 bool unidirectional
,
2222 const SpdyHeaderBlock
& headers
) {
2225 DCHECK_LE(GetProtocolVersion(), SPDY3
);
2227 base::Time response_time
= base::Time::Now();
2228 base::TimeTicks recv_first_byte_time
= time_func_();
2230 if (net_log_
.IsLogging()) {
2232 NetLog::TYPE_HTTP2_SESSION_PUSHED_SYN_STREAM
,
2233 base::Bind(&NetLogSpdySynStreamReceivedCallback
, &headers
, fin
,
2234 unidirectional
, priority
, stream_id
, associated_stream_id
));
2237 // Split headers to simulate push promise and response.
2238 SpdyHeaderBlock request_headers
;
2239 SpdyHeaderBlock response_headers
;
2240 SplitPushedHeadersToRequestAndResponse(
2241 headers
, GetProtocolVersion(), &request_headers
, &response_headers
);
2243 if (!TryCreatePushStream(
2244 stream_id
, associated_stream_id
, priority
, request_headers
))
2247 ActiveStreamMap::iterator active_it
= active_streams_
.find(stream_id
);
2248 if (active_it
== active_streams_
.end()) {
2253 OnInitialResponseHeadersReceived(response_headers
, response_time
,
2254 recv_first_byte_time
,
2255 active_it
->second
.stream
);
2258 void SpdySession::DeleteExpiredPushedStreams() {
2259 if (unclaimed_pushed_streams_
.empty())
2262 // Check that adequate time has elapsed since the last sweep.
2263 if (time_func_() < next_unclaimed_push_stream_sweep_time_
)
2266 // Gather old streams to delete.
2267 base::TimeTicks minimum_freshness
= time_func_() -
2268 base::TimeDelta::FromSeconds(kMinPushedStreamLifetimeSeconds
);
2269 std::vector
<SpdyStreamId
> streams_to_close
;
2270 for (PushedStreamMap::iterator it
= unclaimed_pushed_streams_
.begin();
2271 it
!= unclaimed_pushed_streams_
.end(); ++it
) {
2272 if (minimum_freshness
> it
->second
.creation_time
)
2273 streams_to_close
.push_back(it
->second
.stream_id
);
2276 for (std::vector
<SpdyStreamId
>::const_iterator to_close_it
=
2277 streams_to_close
.begin();
2278 to_close_it
!= streams_to_close
.end(); ++to_close_it
) {
2279 ActiveStreamMap::iterator active_it
= active_streams_
.find(*to_close_it
);
2280 if (active_it
== active_streams_
.end())
2283 LogAbandonedActiveStream(active_it
, ERR_INVALID_SPDY_STREAM
);
2284 // CloseActiveStreamIterator() will remove the stream from
2285 // |unclaimed_pushed_streams_|.
2286 ResetStreamIterator(
2287 active_it
, RST_STREAM_REFUSED_STREAM
, "Stream not claimed.");
2290 next_unclaimed_push_stream_sweep_time_
= time_func_() +
2291 base::TimeDelta::FromSeconds(kMinPushedStreamLifetimeSeconds
);
2294 void SpdySession::OnSynReply(SpdyStreamId stream_id
,
2296 const SpdyHeaderBlock
& headers
) {
2299 base::Time response_time
= base::Time::Now();
2300 base::TimeTicks recv_first_byte_time
= time_func_();
2302 if (net_log().IsLogging()) {
2303 net_log().AddEvent(NetLog::TYPE_HTTP2_SESSION_SYN_REPLY
,
2304 base::Bind(&NetLogSpdySynReplyOrHeadersReceivedCallback
,
2305 &headers
, fin
, stream_id
));
2308 ActiveStreamMap::iterator it
= active_streams_
.find(stream_id
);
2309 if (it
== active_streams_
.end()) {
2310 // NOTE: it may just be that the stream was cancelled.
2314 SpdyStream
* stream
= it
->second
.stream
;
2315 CHECK_EQ(stream
->stream_id(), stream_id
);
2317 stream
->IncrementRawReceivedBytes(last_compressed_frame_len_
);
2318 last_compressed_frame_len_
= 0;
2320 if (GetProtocolVersion() >= SPDY4
) {
2321 const std::string
& error
=
2322 "SPDY4 wasn't expecting SYN_REPLY.";
2323 stream
->LogStreamError(ERR_SPDY_PROTOCOL_ERROR
, error
);
2324 ResetStreamIterator(it
, RST_STREAM_PROTOCOL_ERROR
, error
);
2327 if (!it
->second
.waiting_for_syn_reply
) {
2328 const std::string
& error
=
2329 "Received duplicate SYN_REPLY for stream.";
2330 stream
->LogStreamError(ERR_SPDY_PROTOCOL_ERROR
, error
);
2331 ResetStreamIterator(it
, RST_STREAM_PROTOCOL_ERROR
, error
);
2334 it
->second
.waiting_for_syn_reply
= false;
2336 ignore_result(OnInitialResponseHeadersReceived(
2337 headers
, response_time
, recv_first_byte_time
, stream
));
2340 void SpdySession::OnHeaders(SpdyStreamId stream_id
,
2342 SpdyPriority priority
,
2344 const SpdyHeaderBlock
& headers
) {
2347 if (net_log().IsLogging()) {
2348 net_log().AddEvent(NetLog::TYPE_HTTP2_SESSION_RECV_HEADERS
,
2349 base::Bind(&NetLogSpdySynReplyOrHeadersReceivedCallback
,
2350 &headers
, fin
, stream_id
));
2353 ActiveStreamMap::iterator it
= active_streams_
.find(stream_id
);
2354 if (it
== active_streams_
.end()) {
2355 // NOTE: it may just be that the stream was cancelled.
2356 LOG(WARNING
) << "Received HEADERS for invalid stream " << stream_id
;
2360 SpdyStream
* stream
= it
->second
.stream
;
2361 CHECK_EQ(stream
->stream_id(), stream_id
);
2363 stream
->IncrementRawReceivedBytes(last_compressed_frame_len_
);
2364 last_compressed_frame_len_
= 0;
2366 base::Time response_time
= base::Time::Now();
2367 base::TimeTicks recv_first_byte_time
= time_func_();
2369 if (it
->second
.waiting_for_syn_reply
) {
2370 if (GetProtocolVersion() < SPDY4
) {
2371 const std::string
& error
=
2372 "Was expecting SYN_REPLY, not HEADERS.";
2373 stream
->LogStreamError(ERR_SPDY_PROTOCOL_ERROR
, error
);
2374 ResetStreamIterator(it
, RST_STREAM_PROTOCOL_ERROR
, error
);
2378 it
->second
.waiting_for_syn_reply
= false;
2379 ignore_result(OnInitialResponseHeadersReceived(
2380 headers
, response_time
, recv_first_byte_time
, stream
));
2381 } else if (it
->second
.stream
->IsReservedRemote()) {
2382 ignore_result(OnInitialResponseHeadersReceived(
2383 headers
, response_time
, recv_first_byte_time
, stream
));
2385 int rv
= stream
->OnAdditionalResponseHeadersReceived(headers
);
2387 DCHECK_NE(rv
, ERR_IO_PENDING
);
2388 DCHECK(active_streams_
.find(stream_id
) == active_streams_
.end());
2393 bool SpdySession::OnUnknownFrame(SpdyStreamId stream_id
, int frame_type
) {
2394 // Validate stream id.
2395 // Was the frame sent on a stream id that has not been used in this session?
2396 if (stream_id
% 2 == 1 && stream_id
> stream_hi_water_mark_
)
2399 if (stream_id
% 2 == 0 && stream_id
> last_accepted_push_stream_id_
)
2405 void SpdySession::OnRstStream(SpdyStreamId stream_id
,
2406 SpdyRstStreamStatus status
) {
2409 std::string description
;
2411 NetLog::TYPE_HTTP2_SESSION_RST_STREAM
,
2412 base::Bind(&NetLogSpdyRstCallback
, stream_id
, status
, &description
));
2414 ActiveStreamMap::iterator it
= active_streams_
.find(stream_id
);
2415 if (it
== active_streams_
.end()) {
2416 // NOTE: it may just be that the stream was cancelled.
2417 LOG(WARNING
) << "Received RST for invalid stream" << stream_id
;
2421 CHECK_EQ(it
->second
.stream
->stream_id(), stream_id
);
2424 it
->second
.stream
->OnDataReceived(scoped_ptr
<SpdyBuffer
>());
2425 } else if (status
== RST_STREAM_REFUSED_STREAM
) {
2426 CloseActiveStreamIterator(it
, ERR_SPDY_SERVER_REFUSED_STREAM
);
2427 } else if (status
== RST_STREAM_HTTP_1_1_REQUIRED
) {
2428 // TODO(bnc): Record histogram with number of open streams capped at 50.
2429 it
->second
.stream
->LogStreamError(
2430 ERR_HTTP_1_1_REQUIRED
,
2432 "SPDY session closed because of stream with status: %d", status
));
2433 DoDrainSession(ERR_HTTP_1_1_REQUIRED
, "HTTP_1_1_REQUIRED for stream.");
2435 RecordProtocolErrorHistogram(
2436 PROTOCOL_ERROR_RST_STREAM_FOR_NON_ACTIVE_STREAM
);
2437 it
->second
.stream
->LogStreamError(
2438 ERR_SPDY_PROTOCOL_ERROR
,
2439 base::StringPrintf("SPDY stream closed with status: %d", status
));
2440 // TODO(mbelshe): Map from Spdy-protocol errors to something sensical.
2441 // For now, it doesn't matter much - it is a protocol error.
2442 CloseActiveStreamIterator(it
, ERR_SPDY_PROTOCOL_ERROR
);
2446 void SpdySession::OnGoAway(SpdyStreamId last_accepted_stream_id
,
2447 SpdyGoAwayStatus status
) {
2450 // TODO(jgraettinger): UMA histogram on |status|.
2452 net_log_
.AddEvent(NetLog::TYPE_HTTP2_SESSION_GOAWAY
,
2453 base::Bind(&NetLogSpdyGoAwayCallback
,
2454 last_accepted_stream_id
, active_streams_
.size(),
2455 unclaimed_pushed_streams_
.size(), status
));
2457 if (status
== GOAWAY_HTTP_1_1_REQUIRED
) {
2458 // TODO(bnc): Record histogram with number of open streams capped at 50.
2459 DoDrainSession(ERR_HTTP_1_1_REQUIRED
, "HTTP_1_1_REQUIRED for stream.");
2461 StartGoingAway(last_accepted_stream_id
, ERR_ABORTED
);
2463 // This is to handle the case when we already don't have any active
2464 // streams (i.e., StartGoingAway() did nothing). Otherwise, we have
2465 // active streams and so the last one being closed will finish the
2466 // going away process (see DeleteStream()).
2467 MaybeFinishGoingAway();
2470 void SpdySession::OnPing(SpdyPingId unique_id
, bool is_ack
) {
2474 NetLog::TYPE_HTTP2_SESSION_PING
,
2475 base::Bind(&NetLogSpdyPingCallback
, unique_id
, is_ack
, "received"));
2477 // Send response to a PING from server.
2478 if ((protocol_
>= kProtoSPDY4MinimumVersion
&& !is_ack
) ||
2479 (protocol_
< kProtoSPDY4MinimumVersion
&& unique_id
% 2 == 0)) {
2480 WritePingFrame(unique_id
, true);
2485 if (pings_in_flight_
< 0) {
2486 RecordProtocolErrorHistogram(PROTOCOL_ERROR_UNEXPECTED_PING
);
2487 DoDrainSession(ERR_SPDY_PROTOCOL_ERROR
, "pings_in_flight_ is < 0.");
2488 pings_in_flight_
= 0;
2492 if (pings_in_flight_
> 0)
2495 // We will record RTT in histogram when there are no more client sent
2496 // pings_in_flight_.
2497 RecordPingRTTHistogram(time_func_() - last_ping_sent_time_
);
2500 void SpdySession::OnWindowUpdate(SpdyStreamId stream_id
,
2501 uint32 delta_window_size
) {
2504 DCHECK_LE(delta_window_size
, static_cast<uint32
>(kint32max
));
2505 net_log_
.AddEvent(NetLog::TYPE_HTTP2_SESSION_RECEIVED_WINDOW_UPDATE_FRAME
,
2506 base::Bind(&NetLogSpdyWindowUpdateFrameCallback
, stream_id
,
2507 delta_window_size
));
2509 if (stream_id
== kSessionFlowControlStreamId
) {
2510 // WINDOW_UPDATE for the session.
2511 if (flow_control_state_
< FLOW_CONTROL_STREAM_AND_SESSION
) {
2512 LOG(WARNING
) << "Received WINDOW_UPDATE for session when "
2513 << "session flow control is not turned on";
2514 // TODO(akalin): Record an error and close the session.
2518 if (delta_window_size
< 1u) {
2519 RecordProtocolErrorHistogram(PROTOCOL_ERROR_INVALID_WINDOW_UPDATE_SIZE
);
2521 ERR_SPDY_PROTOCOL_ERROR
,
2522 "Received WINDOW_UPDATE with an invalid delta_window_size " +
2523 base::UintToString(delta_window_size
));
2527 IncreaseSendWindowSize(static_cast<int32
>(delta_window_size
));
2529 // WINDOW_UPDATE for a stream.
2530 if (flow_control_state_
< FLOW_CONTROL_STREAM
) {
2531 // TODO(akalin): Record an error and close the session.
2532 LOG(WARNING
) << "Received WINDOW_UPDATE for stream " << stream_id
2533 << " when flow control is not turned on";
2537 ActiveStreamMap::iterator it
= active_streams_
.find(stream_id
);
2539 if (it
== active_streams_
.end()) {
2540 // NOTE: it may just be that the stream was cancelled.
2541 LOG(WARNING
) << "Received WINDOW_UPDATE for invalid stream " << stream_id
;
2545 SpdyStream
* stream
= it
->second
.stream
;
2546 CHECK_EQ(stream
->stream_id(), stream_id
);
2548 if (delta_window_size
< 1u) {
2549 ResetStreamIterator(it
,
2550 RST_STREAM_FLOW_CONTROL_ERROR
,
2552 "Received WINDOW_UPDATE with an invalid "
2553 "delta_window_size %ud", delta_window_size
));
2557 CHECK_EQ(it
->second
.stream
->stream_id(), stream_id
);
2558 it
->second
.stream
->IncreaseSendWindowSize(
2559 static_cast<int32
>(delta_window_size
));
2563 bool SpdySession::TryCreatePushStream(SpdyStreamId stream_id
,
2564 SpdyStreamId associated_stream_id
,
2565 SpdyPriority priority
,
2566 const SpdyHeaderBlock
& headers
) {
2567 // Server-initiated streams should have even sequence numbers.
2568 if ((stream_id
& 0x1) != 0) {
2569 LOG(WARNING
) << "Received invalid push stream id " << stream_id
;
2570 if (GetProtocolVersion() > SPDY2
)
2571 CloseSessionOnError(ERR_SPDY_PROTOCOL_ERROR
, "Odd push stream id.");
2575 if (GetProtocolVersion() > SPDY2
) {
2576 if (stream_id
<= last_accepted_push_stream_id_
) {
2577 LOG(WARNING
) << "Received push stream id lesser or equal to the last "
2578 << "accepted before " << stream_id
;
2579 CloseSessionOnError(
2580 ERR_SPDY_PROTOCOL_ERROR
,
2581 "New push stream id must be greater than the last accepted.");
2586 if (IsStreamActive(stream_id
)) {
2587 // For SPDY3 and higher we should not get here, we'll start going away
2588 // earlier on |last_seen_push_stream_id_| check.
2589 CHECK_GT(SPDY3
, GetProtocolVersion());
2590 LOG(WARNING
) << "Received push for active stream " << stream_id
;
2594 last_accepted_push_stream_id_
= stream_id
;
2596 RequestPriority request_priority
=
2597 ConvertSpdyPriorityToRequestPriority(priority
, GetProtocolVersion());
2599 if (availability_state_
== STATE_GOING_AWAY
) {
2600 // TODO(akalin): This behavior isn't in the SPDY spec, although it
2601 // probably should be.
2602 EnqueueResetStreamFrame(stream_id
,
2604 RST_STREAM_REFUSED_STREAM
,
2605 "push stream request received when going away");
2609 if (associated_stream_id
== 0) {
2610 // In SPDY4 0 stream id in PUSH_PROMISE frame leads to framer error and
2611 // session going away. We should never get here.
2612 CHECK_GT(SPDY4
, GetProtocolVersion());
2613 std::string description
= base::StringPrintf(
2614 "Received invalid associated stream id %d for pushed stream %d",
2615 associated_stream_id
,
2617 EnqueueResetStreamFrame(
2618 stream_id
, request_priority
, RST_STREAM_REFUSED_STREAM
, description
);
2622 streams_pushed_count_
++;
2624 // TODO(mbelshe): DCHECK that this is a GET method?
2626 // Verify that the response had a URL for us.
2627 GURL gurl
= GetUrlFromHeaderBlock(headers
, GetProtocolVersion(), true);
2628 if (!gurl
.is_valid()) {
2629 EnqueueResetStreamFrame(stream_id
,
2631 RST_STREAM_PROTOCOL_ERROR
,
2632 "Pushed stream url was invalid: " + gurl
.spec());
2636 // Verify we have a valid stream association.
2637 ActiveStreamMap::iterator associated_it
=
2638 active_streams_
.find(associated_stream_id
);
2639 if (associated_it
== active_streams_
.end()) {
2640 EnqueueResetStreamFrame(
2643 RST_STREAM_INVALID_STREAM
,
2644 base::StringPrintf("Received push for inactive associated stream %d",
2645 associated_stream_id
));
2649 // Check that the pushed stream advertises the same origin as its associated
2650 // stream. Bypass this check if and only if this session is with a SPDY proxy
2651 // that is trusted explicitly via the --trusted-spdy-proxy switch.
2652 if (trusted_spdy_proxy_
.Equals(host_port_pair())) {
2653 // Disallow pushing of HTTPS content.
2654 if (gurl
.SchemeIs("https")) {
2655 EnqueueResetStreamFrame(
2658 RST_STREAM_REFUSED_STREAM
,
2659 base::StringPrintf("Rejected push of Cross Origin HTTPS content %d",
2660 associated_stream_id
));
2663 GURL
associated_url(associated_it
->second
.stream
->GetUrlFromHeaders());
2664 if (associated_url
.GetOrigin() != gurl
.GetOrigin()) {
2665 EnqueueResetStreamFrame(
2668 RST_STREAM_REFUSED_STREAM
,
2669 base::StringPrintf("Rejected Cross Origin Push Stream %d",
2670 associated_stream_id
));
2675 // There should not be an existing pushed stream with the same path.
2676 PushedStreamMap::iterator pushed_it
=
2677 unclaimed_pushed_streams_
.lower_bound(gurl
);
2678 if (pushed_it
!= unclaimed_pushed_streams_
.end() &&
2679 pushed_it
->first
== gurl
) {
2680 EnqueueResetStreamFrame(
2683 RST_STREAM_PROTOCOL_ERROR
,
2684 "Received duplicate pushed stream with url: " + gurl
.spec());
2688 scoped_ptr
<SpdyStream
> stream(
2689 new SpdyStream(SPDY_PUSH_STREAM
, GetWeakPtr(), gurl
, request_priority
,
2690 stream_initial_send_window_size_
,
2691 stream_max_recv_window_size_
, net_log_
));
2692 stream
->set_stream_id(stream_id
);
2694 // In spdy4/http2 PUSH_PROMISE arrives on associated stream.
2695 if (associated_it
!= active_streams_
.end() && GetProtocolVersion() >= SPDY4
) {
2696 associated_it
->second
.stream
->IncrementRawReceivedBytes(
2697 last_compressed_frame_len_
);
2699 stream
->IncrementRawReceivedBytes(last_compressed_frame_len_
);
2702 last_compressed_frame_len_
= 0;
2704 PushedStreamMap::iterator inserted_pushed_it
=
2705 unclaimed_pushed_streams_
.insert(
2707 std::make_pair(gurl
, PushedStreamInfo(stream_id
, time_func_())));
2708 DCHECK(inserted_pushed_it
!= pushed_it
);
2709 DeleteExpiredPushedStreams();
2711 InsertActivatedStream(stream
.Pass());
2713 ActiveStreamMap::iterator active_it
= active_streams_
.find(stream_id
);
2714 if (active_it
== active_streams_
.end()) {
2719 active_it
->second
.stream
->OnPushPromiseHeadersReceived(headers
);
2720 DCHECK(active_it
->second
.stream
->IsReservedRemote());
2721 num_pushed_streams_
++;
2725 void SpdySession::OnPushPromise(SpdyStreamId stream_id
,
2726 SpdyStreamId promised_stream_id
,
2727 const SpdyHeaderBlock
& headers
) {
2730 if (net_log_
.IsLogging()) {
2731 net_log_
.AddEvent(NetLog::TYPE_HTTP2_SESSION_RECV_PUSH_PROMISE
,
2732 base::Bind(&NetLogSpdyPushPromiseReceivedCallback
,
2733 &headers
, stream_id
, promised_stream_id
));
2736 // Any priority will do.
2737 // TODO(baranovich): pass parent stream id priority?
2738 if (!TryCreatePushStream(promised_stream_id
, stream_id
, 0, headers
))
2742 void SpdySession::SendStreamWindowUpdate(SpdyStreamId stream_id
,
2743 uint32 delta_window_size
) {
2744 CHECK_GE(flow_control_state_
, FLOW_CONTROL_STREAM
);
2745 ActiveStreamMap::const_iterator it
= active_streams_
.find(stream_id
);
2746 CHECK(it
!= active_streams_
.end());
2747 CHECK_EQ(it
->second
.stream
->stream_id(), stream_id
);
2748 SendWindowUpdateFrame(
2749 stream_id
, delta_window_size
, it
->second
.stream
->priority());
2752 void SpdySession::SendInitialData() {
2753 DCHECK(enable_sending_initial_data_
);
2755 if (send_connection_header_prefix_
) {
2756 DCHECK_GE(protocol_
, kProtoSPDY4MinimumVersion
);
2757 DCHECK_LE(protocol_
, kProtoSPDY4MaximumVersion
);
2758 scoped_ptr
<SpdyFrame
> connection_header_prefix_frame(
2759 new SpdyFrame(const_cast<char*>(kHttp2ConnectionHeaderPrefix
),
2760 kHttp2ConnectionHeaderPrefixSize
,
2761 false /* take_ownership */));
2762 // Count the prefix as part of the subsequent SETTINGS frame.
2763 EnqueueSessionWrite(HIGHEST
, SETTINGS
,
2764 connection_header_prefix_frame
.Pass());
2767 // First, notify the server about the settings they should use when
2768 // communicating with us.
2769 SettingsMap settings_map
;
2770 // Create a new settings frame notifying the server of our
2771 // max concurrent streams and initial window size.
2772 settings_map
[SETTINGS_MAX_CONCURRENT_STREAMS
] =
2773 SettingsFlagsAndValue(SETTINGS_FLAG_NONE
, kMaxConcurrentPushedStreams
);
2774 if (flow_control_state_
>= FLOW_CONTROL_STREAM
&&
2775 stream_max_recv_window_size_
!= GetInitialWindowSize(protocol_
)) {
2776 settings_map
[SETTINGS_INITIAL_WINDOW_SIZE
] =
2777 SettingsFlagsAndValue(SETTINGS_FLAG_NONE
, stream_max_recv_window_size_
);
2779 SendSettings(settings_map
);
2781 // Next, notify the server about our initial recv window size.
2782 if (flow_control_state_
== FLOW_CONTROL_STREAM_AND_SESSION
) {
2783 // Bump up the receive window size to the real initial value. This
2784 // has to go here since the WINDOW_UPDATE frame sent by
2785 // IncreaseRecvWindowSize() call uses |buffered_spdy_framer_|.
2786 // This condition implies that |session_max_recv_window_size_| -
2787 // |session_recv_window_size_| doesn't overflow.
2788 DCHECK_GE(session_max_recv_window_size_
, session_recv_window_size_
);
2789 DCHECK_GE(session_recv_window_size_
, 0);
2790 if (session_max_recv_window_size_
> session_recv_window_size_
) {
2791 IncreaseRecvWindowSize(session_max_recv_window_size_
-
2792 session_recv_window_size_
);
2796 if (protocol_
<= kProtoSPDY31
) {
2797 // Finally, notify the server about the settings they have
2798 // previously told us to use when communicating with them (after
2800 const SettingsMap
& server_settings_map
=
2801 http_server_properties_
->GetSpdySettings(host_port_pair());
2802 if (server_settings_map
.empty())
2805 SettingsMap::const_iterator it
=
2806 server_settings_map
.find(SETTINGS_CURRENT_CWND
);
2807 uint32 cwnd
= (it
!= server_settings_map
.end()) ? it
->second
.second
: 0;
2808 UMA_HISTOGRAM_CUSTOM_COUNTS("Net.SpdySettingsCwndSent", cwnd
, 1, 200, 100);
2810 for (SettingsMap::const_iterator it
= server_settings_map
.begin();
2811 it
!= server_settings_map
.end(); ++it
) {
2812 const SpdySettingsIds new_id
= it
->first
;
2813 const uint32 new_val
= it
->second
.second
;
2814 HandleSetting(new_id
, new_val
);
2817 SendSettings(server_settings_map
);
2822 void SpdySession::SendSettings(const SettingsMap
& settings
) {
2823 const SpdyMajorVersion protocol_version
= GetProtocolVersion();
2825 NetLog::TYPE_HTTP2_SESSION_SEND_SETTINGS
,
2826 base::Bind(&NetLogSpdySendSettingsCallback
, &settings
, protocol_version
));
2827 // Create the SETTINGS frame and send it.
2828 DCHECK(buffered_spdy_framer_
.get());
2829 scoped_ptr
<SpdyFrame
> settings_frame(
2830 buffered_spdy_framer_
->CreateSettings(settings
));
2831 sent_settings_
= true;
2832 EnqueueSessionWrite(HIGHEST
, SETTINGS
, settings_frame
.Pass());
2835 void SpdySession::HandleSetting(uint32 id
, uint32 value
) {
2837 case SETTINGS_MAX_CONCURRENT_STREAMS
:
2838 max_concurrent_streams_
= std::min(static_cast<size_t>(value
),
2839 kMaxConcurrentStreamLimit
);
2840 ProcessPendingStreamRequests();
2842 case SETTINGS_INITIAL_WINDOW_SIZE
: {
2843 if (flow_control_state_
< FLOW_CONTROL_STREAM
) {
2845 NetLog::TYPE_HTTP2_SESSION_INITIAL_WINDOW_SIZE_NO_FLOW_CONTROL
);
2849 if (value
> static_cast<uint32
>(kint32max
)) {
2851 NetLog::TYPE_HTTP2_SESSION_INITIAL_WINDOW_SIZE_OUT_OF_RANGE
,
2852 NetLog::IntegerCallback("initial_window_size", value
));
2856 // SETTINGS_INITIAL_WINDOW_SIZE updates initial_send_window_size_ only.
2857 int32 delta_window_size
=
2858 static_cast<int32
>(value
) - stream_initial_send_window_size_
;
2859 stream_initial_send_window_size_
= static_cast<int32
>(value
);
2860 UpdateStreamsSendWindowSize(delta_window_size
);
2862 NetLog::TYPE_HTTP2_SESSION_UPDATE_STREAMS_SEND_WINDOW_SIZE
,
2863 NetLog::IntegerCallback("delta_window_size", delta_window_size
));
2869 void SpdySession::UpdateStreamsSendWindowSize(int32 delta_window_size
) {
2870 DCHECK_GE(flow_control_state_
, FLOW_CONTROL_STREAM
);
2871 for (ActiveStreamMap::iterator it
= active_streams_
.begin();
2872 it
!= active_streams_
.end(); ++it
) {
2873 it
->second
.stream
->AdjustSendWindowSize(delta_window_size
);
2876 for (CreatedStreamSet::const_iterator it
= created_streams_
.begin();
2877 it
!= created_streams_
.end(); it
++) {
2878 (*it
)->AdjustSendWindowSize(delta_window_size
);
2882 void SpdySession::SendPrefacePingIfNoneInFlight() {
2883 if (pings_in_flight_
|| !enable_ping_based_connection_checking_
)
2886 base::TimeTicks now
= time_func_();
2887 // If there is no activity in the session, then send a preface-PING.
2888 if ((now
- last_activity_time_
) > connection_at_risk_of_loss_time_
)
2892 void SpdySession::SendPrefacePing() {
2893 WritePingFrame(next_ping_id_
, false);
2896 void SpdySession::SendWindowUpdateFrame(SpdyStreamId stream_id
,
2897 uint32 delta_window_size
,
2898 RequestPriority priority
) {
2899 CHECK_GE(flow_control_state_
, FLOW_CONTROL_STREAM
);
2900 ActiveStreamMap::const_iterator it
= active_streams_
.find(stream_id
);
2901 if (it
!= active_streams_
.end()) {
2902 CHECK_EQ(it
->second
.stream
->stream_id(), stream_id
);
2904 CHECK_EQ(flow_control_state_
, FLOW_CONTROL_STREAM_AND_SESSION
);
2905 CHECK_EQ(stream_id
, kSessionFlowControlStreamId
);
2908 net_log_
.AddEvent(NetLog::TYPE_HTTP2_SESSION_SENT_WINDOW_UPDATE_FRAME
,
2909 base::Bind(&NetLogSpdyWindowUpdateFrameCallback
, stream_id
,
2910 delta_window_size
));
2912 DCHECK(buffered_spdy_framer_
.get());
2913 scoped_ptr
<SpdyFrame
> window_update_frame(
2914 buffered_spdy_framer_
->CreateWindowUpdate(stream_id
, delta_window_size
));
2915 EnqueueSessionWrite(priority
, WINDOW_UPDATE
, window_update_frame
.Pass());
2918 void SpdySession::WritePingFrame(SpdyPingId unique_id
, bool is_ack
) {
2919 DCHECK(buffered_spdy_framer_
.get());
2920 scoped_ptr
<SpdyFrame
> ping_frame(
2921 buffered_spdy_framer_
->CreatePingFrame(unique_id
, is_ack
));
2922 EnqueueSessionWrite(HIGHEST
, PING
, ping_frame
.Pass());
2924 if (net_log().IsLogging()) {
2926 NetLog::TYPE_HTTP2_SESSION_PING
,
2927 base::Bind(&NetLogSpdyPingCallback
, unique_id
, is_ack
, "sent"));
2932 PlanToCheckPingStatus();
2933 last_ping_sent_time_
= time_func_();
2937 void SpdySession::PlanToCheckPingStatus() {
2938 if (check_ping_status_pending_
)
2941 check_ping_status_pending_
= true;
2942 base::MessageLoop::current()->PostDelayedTask(
2944 base::Bind(&SpdySession::CheckPingStatus
, weak_factory_
.GetWeakPtr(),
2945 time_func_()), hung_interval_
);
2948 void SpdySession::CheckPingStatus(base::TimeTicks last_check_time
) {
2949 CHECK(!in_io_loop_
);
2951 // Check if we got a response back for all PINGs we had sent.
2952 if (pings_in_flight_
== 0) {
2953 check_ping_status_pending_
= false;
2957 DCHECK(check_ping_status_pending_
);
2959 base::TimeTicks now
= time_func_();
2960 base::TimeDelta delay
= hung_interval_
- (now
- last_activity_time_
);
2962 if (delay
.InMilliseconds() < 0 || last_activity_time_
< last_check_time
) {
2963 // Track all failed PING messages in a separate bucket.
2964 RecordPingRTTHistogram(base::TimeDelta::Max());
2965 DoDrainSession(ERR_SPDY_PING_FAILED
, "Failed ping.");
2969 // Check the status of connection after a delay.
2970 base::MessageLoop::current()->PostDelayedTask(
2972 base::Bind(&SpdySession::CheckPingStatus
, weak_factory_
.GetWeakPtr(),
2977 void SpdySession::RecordPingRTTHistogram(base::TimeDelta duration
) {
2978 UMA_HISTOGRAM_TIMES("Net.SpdyPing.RTT", duration
);
2981 void SpdySession::RecordProtocolErrorHistogram(
2982 SpdyProtocolErrorDetails details
) {
2983 UMA_HISTOGRAM_ENUMERATION("Net.SpdySessionErrorDetails2", details
,
2984 NUM_SPDY_PROTOCOL_ERROR_DETAILS
);
2985 if (EndsWith(host_port_pair().host(), "google.com", false)) {
2986 UMA_HISTOGRAM_ENUMERATION("Net.SpdySessionErrorDetails_Google2", details
,
2987 NUM_SPDY_PROTOCOL_ERROR_DETAILS
);
2991 void SpdySession::RecordHistograms() {
2992 UMA_HISTOGRAM_CUSTOM_COUNTS("Net.SpdyStreamsPerSession",
2993 streams_initiated_count_
,
2995 UMA_HISTOGRAM_CUSTOM_COUNTS("Net.SpdyStreamsPushedPerSession",
2996 streams_pushed_count_
,
2998 UMA_HISTOGRAM_CUSTOM_COUNTS("Net.SpdyStreamsPushedAndClaimedPerSession",
2999 streams_pushed_and_claimed_count_
,
3001 UMA_HISTOGRAM_CUSTOM_COUNTS("Net.SpdyStreamsAbandonedPerSession",
3002 streams_abandoned_count_
,
3004 UMA_HISTOGRAM_ENUMERATION("Net.SpdySettingsSent",
3005 sent_settings_
? 1 : 0, 2);
3006 UMA_HISTOGRAM_ENUMERATION("Net.SpdySettingsReceived",
3007 received_settings_
? 1 : 0, 2);
3008 UMA_HISTOGRAM_CUSTOM_COUNTS("Net.SpdyStreamStallsPerSession",
3011 UMA_HISTOGRAM_ENUMERATION("Net.SpdySessionsWithStalls",
3012 stalled_streams_
> 0 ? 1 : 0, 2);
3014 if (received_settings_
) {
3015 // Enumerate the saved settings, and set histograms for it.
3016 const SettingsMap
& settings_map
=
3017 http_server_properties_
->GetSpdySettings(host_port_pair());
3019 SettingsMap::const_iterator it
;
3020 for (it
= settings_map
.begin(); it
!= settings_map
.end(); ++it
) {
3021 const SpdySettingsIds id
= it
->first
;
3022 const uint32 val
= it
->second
.second
;
3024 case SETTINGS_CURRENT_CWND
:
3025 // Record several different histograms to see if cwnd converges
3026 // for larger volumes of data being sent.
3027 UMA_HISTOGRAM_CUSTOM_COUNTS("Net.SpdySettingsCwnd",
3029 if (total_bytes_received_
> 10 * 1024) {
3030 UMA_HISTOGRAM_CUSTOM_COUNTS("Net.SpdySettingsCwnd10K",
3032 if (total_bytes_received_
> 25 * 1024) {
3033 UMA_HISTOGRAM_CUSTOM_COUNTS("Net.SpdySettingsCwnd25K",
3035 if (total_bytes_received_
> 50 * 1024) {
3036 UMA_HISTOGRAM_CUSTOM_COUNTS("Net.SpdySettingsCwnd50K",
3038 if (total_bytes_received_
> 100 * 1024) {
3039 UMA_HISTOGRAM_CUSTOM_COUNTS("Net.SpdySettingsCwnd100K",
3046 case SETTINGS_ROUND_TRIP_TIME
:
3047 UMA_HISTOGRAM_CUSTOM_COUNTS("Net.SpdySettingsRTT",
3050 case SETTINGS_DOWNLOAD_RETRANS_RATE
:
3051 UMA_HISTOGRAM_CUSTOM_COUNTS("Net.SpdySettingsRetransRate",
3061 void SpdySession::CompleteStreamRequest(
3062 const base::WeakPtr
<SpdyStreamRequest
>& pending_request
) {
3063 // Abort if the request has already been cancelled.
3064 if (!pending_request
)
3067 base::WeakPtr
<SpdyStream
> stream
;
3068 int rv
= TryCreateStream(pending_request
, &stream
);
3072 pending_request
->OnRequestCompleteSuccess(stream
);
3077 if (rv
!= ERR_IO_PENDING
) {
3078 pending_request
->OnRequestCompleteFailure(rv
);
3082 SSLClientSocket
* SpdySession::GetSSLClientSocket() const {
3085 SSLClientSocket
* ssl_socket
=
3086 reinterpret_cast<SSLClientSocket
*>(connection_
->socket());
3091 void SpdySession::OnWriteBufferConsumed(
3092 size_t frame_payload_size
,
3093 size_t consume_size
,
3094 SpdyBuffer::ConsumeSource consume_source
) {
3095 // We can be called with |in_io_loop_| set if a write SpdyBuffer is
3096 // deleted (e.g., a stream is closed due to incoming data).
3098 DCHECK_EQ(flow_control_state_
, FLOW_CONTROL_STREAM_AND_SESSION
);
3100 if (consume_source
== SpdyBuffer::DISCARD
) {
3101 // If we're discarding a frame or part of it, increase the send
3102 // window by the number of discarded bytes. (Although if we're
3103 // discarding part of a frame, it's probably because of a write
3104 // error and we'll be tearing down the session soon.)
3105 size_t remaining_payload_bytes
= std::min(consume_size
, frame_payload_size
);
3106 DCHECK_GT(remaining_payload_bytes
, 0u);
3107 IncreaseSendWindowSize(static_cast<int32
>(remaining_payload_bytes
));
3109 // For consumed bytes, the send window is increased when we receive
3110 // a WINDOW_UPDATE frame.
3113 void SpdySession::IncreaseSendWindowSize(int32 delta_window_size
) {
3114 // We can be called with |in_io_loop_| set if a SpdyBuffer is
3115 // deleted (e.g., a stream is closed due to incoming data).
3117 DCHECK_EQ(flow_control_state_
, FLOW_CONTROL_STREAM_AND_SESSION
);
3118 DCHECK_GE(delta_window_size
, 1);
3120 // Check for overflow.
3121 int32 max_delta_window_size
= kint32max
- session_send_window_size_
;
3122 if (delta_window_size
> max_delta_window_size
) {
3123 RecordProtocolErrorHistogram(PROTOCOL_ERROR_INVALID_WINDOW_UPDATE_SIZE
);
3125 ERR_SPDY_PROTOCOL_ERROR
,
3126 "Received WINDOW_UPDATE [delta: " +
3127 base::IntToString(delta_window_size
) +
3128 "] for session overflows session_send_window_size_ [current: " +
3129 base::IntToString(session_send_window_size_
) + "]");
3133 session_send_window_size_
+= delta_window_size
;
3135 net_log_
.AddEvent(NetLog::TYPE_HTTP2_SESSION_UPDATE_SEND_WINDOW
,
3136 base::Bind(&NetLogSpdySessionWindowUpdateCallback
,
3137 delta_window_size
, session_send_window_size_
));
3139 DCHECK(!IsSendStalled());
3140 ResumeSendStalledStreams();
3143 void SpdySession::DecreaseSendWindowSize(int32 delta_window_size
) {
3144 DCHECK_EQ(flow_control_state_
, FLOW_CONTROL_STREAM_AND_SESSION
);
3146 // We only call this method when sending a frame. Therefore,
3147 // |delta_window_size| should be within the valid frame size range.
3148 DCHECK_GE(delta_window_size
, 1);
3149 DCHECK_LE(delta_window_size
, kMaxSpdyFrameChunkSize
);
3151 // |send_window_size_| should have been at least |delta_window_size| for
3152 // this call to happen.
3153 DCHECK_GE(session_send_window_size_
, delta_window_size
);
3155 session_send_window_size_
-= delta_window_size
;
3157 net_log_
.AddEvent(NetLog::TYPE_HTTP2_SESSION_UPDATE_SEND_WINDOW
,
3158 base::Bind(&NetLogSpdySessionWindowUpdateCallback
,
3159 -delta_window_size
, session_send_window_size_
));
3162 void SpdySession::OnReadBufferConsumed(
3163 size_t consume_size
,
3164 SpdyBuffer::ConsumeSource consume_source
) {
3165 // We can be called with |in_io_loop_| set if a read SpdyBuffer is
3166 // deleted (e.g., discarded by a SpdyReadQueue).
3168 DCHECK_EQ(flow_control_state_
, FLOW_CONTROL_STREAM_AND_SESSION
);
3169 DCHECK_GE(consume_size
, 1u);
3170 DCHECK_LE(consume_size
, static_cast<size_t>(kint32max
));
3172 IncreaseRecvWindowSize(static_cast<int32
>(consume_size
));
3175 void SpdySession::IncreaseRecvWindowSize(int32 delta_window_size
) {
3176 DCHECK_EQ(flow_control_state_
, FLOW_CONTROL_STREAM_AND_SESSION
);
3177 DCHECK_GE(session_unacked_recv_window_bytes_
, 0);
3178 DCHECK_GE(session_recv_window_size_
, session_unacked_recv_window_bytes_
);
3179 DCHECK_GE(delta_window_size
, 1);
3180 // Check for overflow.
3181 DCHECK_LE(delta_window_size
, kint32max
- session_recv_window_size_
);
3183 session_recv_window_size_
+= delta_window_size
;
3184 net_log_
.AddEvent(NetLog::TYPE_HTTP2_STREAM_UPDATE_RECV_WINDOW
,
3185 base::Bind(&NetLogSpdySessionWindowUpdateCallback
,
3186 delta_window_size
, session_recv_window_size_
));
3188 session_unacked_recv_window_bytes_
+= delta_window_size
;
3189 if (session_unacked_recv_window_bytes_
> session_max_recv_window_size_
/ 2) {
3190 SendWindowUpdateFrame(kSessionFlowControlStreamId
,
3191 session_unacked_recv_window_bytes_
,
3193 session_unacked_recv_window_bytes_
= 0;
3197 void SpdySession::DecreaseRecvWindowSize(int32 delta_window_size
) {
3199 DCHECK_EQ(flow_control_state_
, FLOW_CONTROL_STREAM_AND_SESSION
);
3200 DCHECK_GE(delta_window_size
, 1);
3202 // Since we never decrease the initial receive window size,
3203 // |delta_window_size| should never cause |recv_window_size_| to go
3204 // negative. If we do, the receive window isn't being respected.
3205 if (delta_window_size
> session_recv_window_size_
) {
3206 RecordProtocolErrorHistogram(PROTOCOL_ERROR_RECEIVE_WINDOW_VIOLATION
);
3208 ERR_SPDY_FLOW_CONTROL_ERROR
,
3209 "delta_window_size is " + base::IntToString(delta_window_size
) +
3210 " in DecreaseRecvWindowSize, which is larger than the receive " +
3211 "window size of " + base::IntToString(session_recv_window_size_
));
3215 session_recv_window_size_
-= delta_window_size
;
3216 net_log_
.AddEvent(NetLog::TYPE_HTTP2_SESSION_UPDATE_RECV_WINDOW
,
3217 base::Bind(&NetLogSpdySessionWindowUpdateCallback
,
3218 -delta_window_size
, session_recv_window_size_
));
3221 void SpdySession::QueueSendStalledStream(const SpdyStream
& stream
) {
3222 DCHECK(stream
.send_stalled_by_flow_control());
3223 RequestPriority priority
= stream
.priority();
3224 CHECK_GE(priority
, MINIMUM_PRIORITY
);
3225 CHECK_LE(priority
, MAXIMUM_PRIORITY
);
3226 stream_send_unstall_queue_
[priority
].push_back(stream
.stream_id());
3229 void SpdySession::ResumeSendStalledStreams() {
3230 DCHECK_EQ(flow_control_state_
, FLOW_CONTROL_STREAM_AND_SESSION
);
3232 // We don't have to worry about new streams being queued, since
3233 // doing so would cause IsSendStalled() to return true. But we do
3234 // have to worry about streams being closed, as well as ourselves
3237 while (!IsSendStalled()) {
3238 size_t old_size
= 0;
3240 old_size
= GetTotalSize(stream_send_unstall_queue_
);
3243 SpdyStreamId stream_id
= PopStreamToPossiblyResume();
3246 ActiveStreamMap::const_iterator it
= active_streams_
.find(stream_id
);
3247 // The stream may actually still be send-stalled after this (due
3248 // to its own send window) but that's okay -- it'll then be
3249 // resumed once its send window increases.
3250 if (it
!= active_streams_
.end())
3251 it
->second
.stream
->PossiblyResumeIfSendStalled();
3253 // The size should decrease unless we got send-stalled again.
3254 if (!IsSendStalled())
3255 DCHECK_LT(GetTotalSize(stream_send_unstall_queue_
), old_size
);
3259 SpdyStreamId
SpdySession::PopStreamToPossiblyResume() {
3260 for (int i
= MAXIMUM_PRIORITY
; i
>= MINIMUM_PRIORITY
; --i
) {
3261 std::deque
<SpdyStreamId
>* queue
= &stream_send_unstall_queue_
[i
];
3262 if (!queue
->empty()) {
3263 SpdyStreamId stream_id
= queue
->front();