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/metrics/stats_counters.h"
19 #include "base/profiler/scoped_tracker.h"
20 #include "base/stl_util.h"
21 #include "base/strings/string_number_conversions.h"
22 #include "base/strings/string_util.h"
23 #include "base/strings/stringprintf.h"
24 #include "base/strings/utf_string_conversions.h"
25 #include "base/time/time.h"
26 #include "base/values.h"
27 #include "crypto/ec_private_key.h"
28 #include "crypto/ec_signature_creator.h"
29 #include "net/base/connection_type_histograms.h"
30 #include "net/base/net_log.h"
31 #include "net/base/net_util.h"
32 #include "net/cert/asn1_util.h"
33 #include "net/cert/cert_verify_result.h"
34 #include "net/http/http_log_util.h"
35 #include "net/http/http_network_session.h"
36 #include "net/http/http_server_properties.h"
37 #include "net/http/http_util.h"
38 #include "net/http/transport_security_state.h"
39 #include "net/socket/ssl_client_socket.h"
40 #include "net/spdy/spdy_buffer_producer.h"
41 #include "net/spdy/spdy_frame_builder.h"
42 #include "net/spdy/spdy_http_utils.h"
43 #include "net/spdy/spdy_protocol.h"
44 #include "net/spdy/spdy_session_pool.h"
45 #include "net/spdy/spdy_stream.h"
46 #include "net/ssl/channel_id_service.h"
47 #include "net/ssl/ssl_cipher_suite_names.h"
48 #include "net/ssl/ssl_connection_status_flags.h"
54 const int kReadBufferSize
= 8 * 1024;
55 const int kDefaultConnectionAtRiskOfLossSeconds
= 10;
56 const int kHungIntervalSeconds
= 10;
58 // Minimum seconds that unclaimed pushed streams will be kept in memory.
59 const int kMinPushedStreamLifetimeSeconds
= 300;
61 scoped_ptr
<base::ListValue
> SpdyHeaderBlockToListValue(
62 const SpdyHeaderBlock
& headers
,
63 net::NetLog::LogLevel log_level
) {
64 scoped_ptr
<base::ListValue
> headers_list(new base::ListValue());
65 for (SpdyHeaderBlock::const_iterator it
= headers
.begin();
66 it
!= headers
.end(); ++it
) {
67 headers_list
->AppendString(
69 ElideHeaderValueForNetLog(log_level
, it
->first
, it
->second
));
71 return headers_list
.Pass();
74 base::Value
* NetLogSpdySynStreamSentCallback(const SpdyHeaderBlock
* headers
,
77 SpdyPriority spdy_priority
,
78 SpdyStreamId stream_id
,
79 NetLog::LogLevel log_level
) {
80 base::DictionaryValue
* dict
= new base::DictionaryValue();
82 SpdyHeaderBlockToListValue(*headers
, log_level
).release());
83 dict
->SetBoolean("fin", fin
);
84 dict
->SetBoolean("unidirectional", unidirectional
);
85 dict
->SetInteger("spdy_priority", static_cast<int>(spdy_priority
));
86 dict
->SetInteger("stream_id", stream_id
);
90 base::Value
* NetLogSpdySynStreamReceivedCallback(
91 const SpdyHeaderBlock
* headers
,
94 SpdyPriority spdy_priority
,
95 SpdyStreamId stream_id
,
96 SpdyStreamId associated_stream
,
97 NetLog::LogLevel log_level
) {
98 base::DictionaryValue
* dict
= new base::DictionaryValue();
100 SpdyHeaderBlockToListValue(*headers
, log_level
).release());
101 dict
->SetBoolean("fin", fin
);
102 dict
->SetBoolean("unidirectional", unidirectional
);
103 dict
->SetInteger("spdy_priority", static_cast<int>(spdy_priority
));
104 dict
->SetInteger("stream_id", stream_id
);
105 dict
->SetInteger("associated_stream", associated_stream
);
109 base::Value
* NetLogSpdySynReplyOrHeadersReceivedCallback(
110 const SpdyHeaderBlock
* headers
,
112 SpdyStreamId stream_id
,
113 NetLog::LogLevel log_level
) {
114 base::DictionaryValue
* dict
= new base::DictionaryValue();
116 SpdyHeaderBlockToListValue(*headers
, log_level
).release());
117 dict
->SetBoolean("fin", fin
);
118 dict
->SetInteger("stream_id", stream_id
);
122 base::Value
* NetLogSpdySessionCloseCallback(int net_error
,
123 const std::string
* description
,
124 NetLog::LogLevel
/* log_level */) {
125 base::DictionaryValue
* dict
= new base::DictionaryValue();
126 dict
->SetInteger("net_error", net_error
);
127 dict
->SetString("description", *description
);
131 base::Value
* NetLogSpdySessionCallback(const HostPortProxyPair
* host_pair
,
132 NetLog::LogLevel
/* log_level */) {
133 base::DictionaryValue
* dict
= new base::DictionaryValue();
134 dict
->SetString("host", host_pair
->first
.ToString());
135 dict
->SetString("proxy", host_pair
->second
.ToPacString());
139 base::Value
* NetLogSpdyInitializedCallback(NetLog::Source source
,
140 const NextProto protocol_version
,
141 NetLog::LogLevel
/* log_level */) {
142 base::DictionaryValue
* dict
= new base::DictionaryValue();
143 if (source
.IsValid()) {
144 source
.AddToEventParameters(dict
);
146 dict
->SetString("protocol",
147 SSLClientSocket::NextProtoToString(protocol_version
));
151 base::Value
* NetLogSpdySettingsCallback(const HostPortPair
& host_port_pair
,
152 bool clear_persisted
,
153 NetLog::LogLevel
/* log_level */) {
154 base::DictionaryValue
* dict
= new base::DictionaryValue();
155 dict
->SetString("host", host_port_pair
.ToString());
156 dict
->SetBoolean("clear_persisted", clear_persisted
);
160 base::Value
* NetLogSpdySettingCallback(SpdySettingsIds id
,
161 const SpdyMajorVersion protocol_version
,
162 SpdySettingsFlags flags
,
164 NetLog::LogLevel
/* log_level */) {
165 base::DictionaryValue
* dict
= new base::DictionaryValue();
166 dict
->SetInteger("id",
167 SpdyConstants::SerializeSettingId(protocol_version
, id
));
168 dict
->SetInteger("flags", flags
);
169 dict
->SetInteger("value", value
);
173 base::Value
* NetLogSpdySendSettingsCallback(
174 const SettingsMap
* settings
,
175 const SpdyMajorVersion protocol_version
,
176 NetLog::LogLevel
/* log_level */) {
177 base::DictionaryValue
* dict
= new base::DictionaryValue();
178 base::ListValue
* settings_list
= new base::ListValue();
179 for (SettingsMap::const_iterator it
= settings
->begin();
180 it
!= settings
->end(); ++it
) {
181 const SpdySettingsIds id
= it
->first
;
182 const SpdySettingsFlags flags
= it
->second
.first
;
183 const uint32 value
= it
->second
.second
;
184 settings_list
->Append(new base::StringValue(base::StringPrintf(
185 "[id:%u flags:%u value:%u]",
186 SpdyConstants::SerializeSettingId(protocol_version
, id
),
190 dict
->Set("settings", settings_list
);
194 base::Value
* NetLogSpdyWindowUpdateFrameCallback(
195 SpdyStreamId stream_id
,
197 NetLog::LogLevel
/* log_level */) {
198 base::DictionaryValue
* dict
= new base::DictionaryValue();
199 dict
->SetInteger("stream_id", static_cast<int>(stream_id
));
200 dict
->SetInteger("delta", delta
);
204 base::Value
* NetLogSpdySessionWindowUpdateCallback(
207 NetLog::LogLevel
/* log_level */) {
208 base::DictionaryValue
* dict
= new base::DictionaryValue();
209 dict
->SetInteger("delta", delta
);
210 dict
->SetInteger("window_size", window_size
);
214 base::Value
* NetLogSpdyDataCallback(SpdyStreamId stream_id
,
217 NetLog::LogLevel
/* log_level */) {
218 base::DictionaryValue
* dict
= new base::DictionaryValue();
219 dict
->SetInteger("stream_id", static_cast<int>(stream_id
));
220 dict
->SetInteger("size", size
);
221 dict
->SetBoolean("fin", fin
);
225 base::Value
* NetLogSpdyRstCallback(SpdyStreamId stream_id
,
227 const std::string
* description
,
228 NetLog::LogLevel
/* log_level */) {
229 base::DictionaryValue
* dict
= new base::DictionaryValue();
230 dict
->SetInteger("stream_id", static_cast<int>(stream_id
));
231 dict
->SetInteger("status", status
);
232 dict
->SetString("description", *description
);
236 base::Value
* NetLogSpdyPingCallback(SpdyPingId unique_id
,
239 NetLog::LogLevel
/* log_level */) {
240 base::DictionaryValue
* dict
= new base::DictionaryValue();
241 dict
->SetInteger("unique_id", static_cast<int>(unique_id
));
242 dict
->SetString("type", type
);
243 dict
->SetBoolean("is_ack", is_ack
);
247 base::Value
* NetLogSpdyGoAwayCallback(SpdyStreamId last_stream_id
,
249 int unclaimed_streams
,
250 SpdyGoAwayStatus status
,
251 NetLog::LogLevel
/* log_level */) {
252 base::DictionaryValue
* dict
= new base::DictionaryValue();
253 dict
->SetInteger("last_accepted_stream_id",
254 static_cast<int>(last_stream_id
));
255 dict
->SetInteger("active_streams", active_streams
);
256 dict
->SetInteger("unclaimed_streams", unclaimed_streams
);
257 dict
->SetInteger("status", static_cast<int>(status
));
261 base::Value
* NetLogSpdyPushPromiseReceivedCallback(
262 const SpdyHeaderBlock
* headers
,
263 SpdyStreamId stream_id
,
264 SpdyStreamId promised_stream_id
,
265 NetLog::LogLevel log_level
) {
266 base::DictionaryValue
* dict
= new base::DictionaryValue();
268 SpdyHeaderBlockToListValue(*headers
, log_level
).release());
269 dict
->SetInteger("id", stream_id
);
270 dict
->SetInteger("promised_stream_id", promised_stream_id
);
274 base::Value
* NetLogSpdyAdoptedPushStreamCallback(
275 SpdyStreamId stream_id
, const GURL
* url
, NetLog::LogLevel log_level
) {
276 base::DictionaryValue
* dict
= new base::DictionaryValue();
277 dict
->SetInteger("stream_id", stream_id
);
278 dict
->SetString("url", url
->spec());
282 // Helper function to return the total size of an array of objects
283 // with .size() member functions.
284 template <typename T
, size_t N
> size_t GetTotalSize(const T (&arr
)[N
]) {
285 size_t total_size
= 0;
286 for (size_t i
= 0; i
< N
; ++i
) {
287 total_size
+= arr
[i
].size();
292 // Helper class for std:find_if on STL container containing
293 // SpdyStreamRequest weak pointers.
294 class RequestEquals
{
296 RequestEquals(const base::WeakPtr
<SpdyStreamRequest
>& request
)
297 : request_(request
) {}
299 bool operator()(const base::WeakPtr
<SpdyStreamRequest
>& request
) const {
300 return request_
.get() == request
.get();
304 const base::WeakPtr
<SpdyStreamRequest
> request_
;
307 // The maximum number of concurrent streams we will ever create. Even if
308 // the server permits more, we will never exceed this limit.
309 const size_t kMaxConcurrentStreamLimit
= 256;
313 SpdyProtocolErrorDetails
MapFramerErrorToProtocolError(
314 SpdyFramer::SpdyError err
) {
316 case SpdyFramer::SPDY_NO_ERROR
:
317 return SPDY_ERROR_NO_ERROR
;
318 case SpdyFramer::SPDY_INVALID_CONTROL_FRAME
:
319 return SPDY_ERROR_INVALID_CONTROL_FRAME
;
320 case SpdyFramer::SPDY_CONTROL_PAYLOAD_TOO_LARGE
:
321 return SPDY_ERROR_CONTROL_PAYLOAD_TOO_LARGE
;
322 case SpdyFramer::SPDY_ZLIB_INIT_FAILURE
:
323 return SPDY_ERROR_ZLIB_INIT_FAILURE
;
324 case SpdyFramer::SPDY_UNSUPPORTED_VERSION
:
325 return SPDY_ERROR_UNSUPPORTED_VERSION
;
326 case SpdyFramer::SPDY_DECOMPRESS_FAILURE
:
327 return SPDY_ERROR_DECOMPRESS_FAILURE
;
328 case SpdyFramer::SPDY_COMPRESS_FAILURE
:
329 return SPDY_ERROR_COMPRESS_FAILURE
;
330 case SpdyFramer::SPDY_GOAWAY_FRAME_CORRUPT
:
331 return SPDY_ERROR_GOAWAY_FRAME_CORRUPT
;
332 case SpdyFramer::SPDY_RST_STREAM_FRAME_CORRUPT
:
333 return SPDY_ERROR_RST_STREAM_FRAME_CORRUPT
;
334 case SpdyFramer::SPDY_INVALID_DATA_FRAME_FLAGS
:
335 return SPDY_ERROR_INVALID_DATA_FRAME_FLAGS
;
336 case SpdyFramer::SPDY_INVALID_CONTROL_FRAME_FLAGS
:
337 return SPDY_ERROR_INVALID_CONTROL_FRAME_FLAGS
;
338 case SpdyFramer::SPDY_UNEXPECTED_FRAME
:
339 return SPDY_ERROR_UNEXPECTED_FRAME
;
342 return static_cast<SpdyProtocolErrorDetails
>(-1);
346 Error
MapFramerErrorToNetError(SpdyFramer::SpdyError err
) {
348 case SpdyFramer::SPDY_NO_ERROR
:
350 case SpdyFramer::SPDY_INVALID_CONTROL_FRAME
:
351 return ERR_SPDY_PROTOCOL_ERROR
;
352 case SpdyFramer::SPDY_CONTROL_PAYLOAD_TOO_LARGE
:
353 return ERR_SPDY_FRAME_SIZE_ERROR
;
354 case SpdyFramer::SPDY_ZLIB_INIT_FAILURE
:
355 return ERR_SPDY_COMPRESSION_ERROR
;
356 case SpdyFramer::SPDY_UNSUPPORTED_VERSION
:
357 return ERR_SPDY_PROTOCOL_ERROR
;
358 case SpdyFramer::SPDY_DECOMPRESS_FAILURE
:
359 return ERR_SPDY_COMPRESSION_ERROR
;
360 case SpdyFramer::SPDY_COMPRESS_FAILURE
:
361 return ERR_SPDY_COMPRESSION_ERROR
;
362 case SpdyFramer::SPDY_GOAWAY_FRAME_CORRUPT
:
363 return ERR_SPDY_PROTOCOL_ERROR
;
364 case SpdyFramer::SPDY_RST_STREAM_FRAME_CORRUPT
:
365 return ERR_SPDY_PROTOCOL_ERROR
;
366 case SpdyFramer::SPDY_INVALID_DATA_FRAME_FLAGS
:
367 return ERR_SPDY_PROTOCOL_ERROR
;
368 case SpdyFramer::SPDY_INVALID_CONTROL_FRAME_FLAGS
:
369 return ERR_SPDY_PROTOCOL_ERROR
;
370 case SpdyFramer::SPDY_UNEXPECTED_FRAME
:
371 return ERR_SPDY_PROTOCOL_ERROR
;
374 return ERR_SPDY_PROTOCOL_ERROR
;
378 SpdyProtocolErrorDetails
MapRstStreamStatusToProtocolError(
379 SpdyRstStreamStatus status
) {
381 case RST_STREAM_PROTOCOL_ERROR
:
382 return STATUS_CODE_PROTOCOL_ERROR
;
383 case RST_STREAM_INVALID_STREAM
:
384 return STATUS_CODE_INVALID_STREAM
;
385 case RST_STREAM_REFUSED_STREAM
:
386 return STATUS_CODE_REFUSED_STREAM
;
387 case RST_STREAM_UNSUPPORTED_VERSION
:
388 return STATUS_CODE_UNSUPPORTED_VERSION
;
389 case RST_STREAM_CANCEL
:
390 return STATUS_CODE_CANCEL
;
391 case RST_STREAM_INTERNAL_ERROR
:
392 return STATUS_CODE_INTERNAL_ERROR
;
393 case RST_STREAM_FLOW_CONTROL_ERROR
:
394 return STATUS_CODE_FLOW_CONTROL_ERROR
;
395 case RST_STREAM_STREAM_IN_USE
:
396 return STATUS_CODE_STREAM_IN_USE
;
397 case RST_STREAM_STREAM_ALREADY_CLOSED
:
398 return STATUS_CODE_STREAM_ALREADY_CLOSED
;
399 case RST_STREAM_INVALID_CREDENTIALS
:
400 return STATUS_CODE_INVALID_CREDENTIALS
;
401 case RST_STREAM_FRAME_SIZE_ERROR
:
402 return STATUS_CODE_FRAME_SIZE_ERROR
;
403 case RST_STREAM_SETTINGS_TIMEOUT
:
404 return STATUS_CODE_SETTINGS_TIMEOUT
;
405 case RST_STREAM_CONNECT_ERROR
:
406 return STATUS_CODE_CONNECT_ERROR
;
407 case RST_STREAM_ENHANCE_YOUR_CALM
:
408 return STATUS_CODE_ENHANCE_YOUR_CALM
;
409 case RST_STREAM_INADEQUATE_SECURITY
:
410 return STATUS_CODE_INADEQUATE_SECURITY
;
411 case RST_STREAM_HTTP_1_1_REQUIRED
:
412 return STATUS_CODE_HTTP_1_1_REQUIRED
;
415 return static_cast<SpdyProtocolErrorDetails
>(-1);
419 SpdyGoAwayStatus
MapNetErrorToGoAwayStatus(Error err
) {
422 return GOAWAY_NO_ERROR
;
423 case ERR_SPDY_PROTOCOL_ERROR
:
424 return GOAWAY_PROTOCOL_ERROR
;
425 case ERR_SPDY_FLOW_CONTROL_ERROR
:
426 return GOAWAY_FLOW_CONTROL_ERROR
;
427 case ERR_SPDY_FRAME_SIZE_ERROR
:
428 return GOAWAY_FRAME_SIZE_ERROR
;
429 case ERR_SPDY_COMPRESSION_ERROR
:
430 return GOAWAY_COMPRESSION_ERROR
;
431 case ERR_SPDY_INADEQUATE_TRANSPORT_SECURITY
:
432 return GOAWAY_INADEQUATE_SECURITY
;
434 return GOAWAY_PROTOCOL_ERROR
;
438 void SplitPushedHeadersToRequestAndResponse(const SpdyHeaderBlock
& headers
,
439 SpdyMajorVersion protocol_version
,
440 SpdyHeaderBlock
* request_headers
,
441 SpdyHeaderBlock
* response_headers
) {
442 DCHECK(response_headers
);
443 DCHECK(request_headers
);
444 for (SpdyHeaderBlock::const_iterator it
= headers
.begin();
447 SpdyHeaderBlock
* to_insert
= response_headers
;
448 if (protocol_version
== SPDY2
) {
449 if (it
->first
== "url")
450 to_insert
= request_headers
;
452 const char* host
= protocol_version
>= SPDY4
? ":authority" : ":host";
453 static const char* scheme
= ":scheme";
454 static const char* path
= ":path";
455 if (it
->first
== host
|| it
->first
== scheme
|| it
->first
== path
)
456 to_insert
= request_headers
;
458 to_insert
->insert(*it
);
462 SpdyStreamRequest::SpdyStreamRequest() : weak_ptr_factory_(this) {
466 SpdyStreamRequest::~SpdyStreamRequest() {
470 int SpdyStreamRequest::StartRequest(
472 const base::WeakPtr
<SpdySession
>& session
,
474 RequestPriority priority
,
475 const BoundNetLog
& net_log
,
476 const CompletionCallback
& callback
) {
480 DCHECK(callback_
.is_null());
485 priority_
= priority
;
487 callback_
= callback
;
489 base::WeakPtr
<SpdyStream
> stream
;
490 int rv
= session
->TryCreateStream(weak_ptr_factory_
.GetWeakPtr(), &stream
);
498 void SpdyStreamRequest::CancelRequest() {
500 session_
->CancelStreamRequest(weak_ptr_factory_
.GetWeakPtr());
502 // Do this to cancel any pending CompleteStreamRequest() tasks.
503 weak_ptr_factory_
.InvalidateWeakPtrs();
506 base::WeakPtr
<SpdyStream
> SpdyStreamRequest::ReleaseStream() {
508 base::WeakPtr
<SpdyStream
> stream
= stream_
;
514 void SpdyStreamRequest::OnRequestCompleteSuccess(
515 const base::WeakPtr
<SpdyStream
>& stream
) {
518 DCHECK(!callback_
.is_null());
519 CompletionCallback callback
= callback_
;
526 void SpdyStreamRequest::OnRequestCompleteFailure(int rv
) {
529 DCHECK(!callback_
.is_null());
530 CompletionCallback callback
= callback_
;
536 void SpdyStreamRequest::Reset() {
537 type_
= SPDY_BIDIRECTIONAL_STREAM
;
541 priority_
= MINIMUM_PRIORITY
;
542 net_log_
= BoundNetLog();
546 SpdySession::ActiveStreamInfo::ActiveStreamInfo()
548 waiting_for_syn_reply(false) {}
550 SpdySession::ActiveStreamInfo::ActiveStreamInfo(SpdyStream
* stream
)
552 waiting_for_syn_reply(stream
->type() != SPDY_PUSH_STREAM
) {
555 SpdySession::ActiveStreamInfo::~ActiveStreamInfo() {}
557 SpdySession::PushedStreamInfo::PushedStreamInfo() : stream_id(0) {}
559 SpdySession::PushedStreamInfo::PushedStreamInfo(
560 SpdyStreamId stream_id
,
561 base::TimeTicks creation_time
)
562 : stream_id(stream_id
),
563 creation_time(creation_time
) {}
565 SpdySession::PushedStreamInfo::~PushedStreamInfo() {}
568 bool SpdySession::CanPool(TransportSecurityState
* transport_security_state
,
569 const SSLInfo
& ssl_info
,
570 const std::string
& old_hostname
,
571 const std::string
& new_hostname
) {
572 // Pooling is prohibited if the server cert is not valid for the new domain,
573 // and for connections on which client certs were sent. It is also prohibited
574 // when channel ID was sent if the hosts are from different eTLDs+1.
575 if (IsCertStatusError(ssl_info
.cert_status
))
578 if (ssl_info
.client_cert_sent
)
581 if (ssl_info
.channel_id_sent
&&
582 ChannelIDService::GetDomainForHost(new_hostname
) !=
583 ChannelIDService::GetDomainForHost(old_hostname
)) {
588 if (!ssl_info
.cert
->VerifyNameMatch(new_hostname
, &unused
))
591 std::string pinning_failure_log
;
592 if (!transport_security_state
->CheckPublicKeyPins(
594 ssl_info
.is_issued_by_known_root
,
595 ssl_info
.public_key_hashes
,
596 &pinning_failure_log
)) {
603 SpdySession::SpdySession(
604 const SpdySessionKey
& spdy_session_key
,
605 const base::WeakPtr
<HttpServerProperties
>& http_server_properties
,
606 TransportSecurityState
* transport_security_state
,
607 bool verify_domain_authentication
,
608 bool enable_sending_initial_data
,
609 bool enable_compression
,
610 bool enable_ping_based_connection_checking
,
611 NextProto default_protocol
,
612 size_t stream_initial_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 stream_initial_send_window_size_(GetInitialWindowSize(default_protocol
)),
659 stream_initial_recv_window_size_(stream_initial_recv_window_size
== 0
660 ? kDefaultInitialRecvWindowSize
661 : stream_initial_recv_window_size
),
662 session_send_window_size_(0),
663 session_recv_window_size_(0),
664 session_unacked_recv_window_bytes_(0),
665 net_log_(BoundNetLog::Make(net_log
, NetLog::SOURCE_SPDY_SESSION
)),
666 verify_domain_authentication_(verify_domain_authentication
),
667 enable_sending_initial_data_(enable_sending_initial_data
),
668 enable_compression_(enable_compression
),
669 enable_ping_based_connection_checking_(
670 enable_ping_based_connection_checking
),
671 protocol_(default_protocol
),
672 connection_at_risk_of_loss_time_(
673 base::TimeDelta::FromSeconds(kDefaultConnectionAtRiskOfLossSeconds
)),
674 hung_interval_(base::TimeDelta::FromSeconds(kHungIntervalSeconds
)),
675 trusted_spdy_proxy_(trusted_spdy_proxy
),
676 time_func_(time_func
),
677 weak_factory_(this) {
678 DCHECK_GE(protocol_
, kProtoSPDYMinimumVersion
);
679 DCHECK_LE(protocol_
, kProtoSPDYMaximumVersion
);
680 DCHECK(HttpStreamFactory::spdy_enabled());
682 NetLog::TYPE_SPDY_SESSION
,
683 base::Bind(&NetLogSpdySessionCallback
, &host_port_proxy_pair()));
684 next_unclaimed_push_stream_sweep_time_
= time_func_() +
685 base::TimeDelta::FromSeconds(kMinPushedStreamLifetimeSeconds
);
686 // TODO(mbelshe): consider randomization of the stream_hi_water_mark.
689 SpdySession::~SpdySession() {
693 // TODO(akalin): Check connection->is_initialized() instead. This
694 // requires re-working CreateFakeSpdySession(), though.
695 DCHECK(connection_
->socket());
696 // With SPDY we can't recycle sockets.
697 connection_
->socket()->Disconnect();
701 net_log_
.EndEvent(NetLog::TYPE_SPDY_SESSION
);
704 void SpdySession::InitializeWithSocket(
705 scoped_ptr
<ClientSocketHandle
> connection
,
706 SpdySessionPool
* pool
,
708 int certificate_error_code
) {
710 DCHECK_EQ(availability_state_
, STATE_AVAILABLE
);
711 DCHECK_EQ(read_state_
, READ_STATE_DO_READ
);
712 DCHECK_EQ(write_state_
, WRITE_STATE_IDLE
);
713 DCHECK(!connection_
);
715 DCHECK(certificate_error_code
== OK
||
716 certificate_error_code
< ERR_IO_PENDING
);
717 // TODO(akalin): Check connection->is_initialized() instead. This
718 // requires re-working CreateFakeSpdySession(), though.
719 DCHECK(connection
->socket());
721 base::StatsCounter
spdy_sessions("spdy.sessions");
722 spdy_sessions
.Increment();
724 connection_
= connection
.Pass();
725 is_secure_
= is_secure
;
726 certificate_error_code_
= certificate_error_code
;
728 NextProto protocol_negotiated
=
729 connection_
->socket()->GetNegotiatedProtocol();
730 if (protocol_negotiated
!= kProtoUnknown
) {
731 protocol_
= protocol_negotiated
;
732 stream_initial_send_window_size_
= GetInitialWindowSize(protocol_
);
734 DCHECK_GE(protocol_
, kProtoSPDYMinimumVersion
);
735 DCHECK_LE(protocol_
, kProtoSPDYMaximumVersion
);
737 if ((protocol_
>= kProtoSPDY4MinimumVersion
) &&
738 (protocol_
<= kProtoSPDY4MaximumVersion
))
739 send_connection_header_prefix_
= true;
741 if (protocol_
>= kProtoSPDY31
) {
742 flow_control_state_
= FLOW_CONTROL_STREAM_AND_SESSION
;
743 session_send_window_size_
= GetInitialWindowSize(protocol_
);
744 session_recv_window_size_
= GetInitialWindowSize(protocol_
);
745 } else if (protocol_
>= kProtoSPDY3
) {
746 flow_control_state_
= FLOW_CONTROL_STREAM
;
748 flow_control_state_
= FLOW_CONTROL_NONE
;
751 buffered_spdy_framer_
.reset(
752 new BufferedSpdyFramer(NextProtoToSpdyMajorVersion(protocol_
),
753 enable_compression_
));
754 buffered_spdy_framer_
->set_visitor(this);
755 buffered_spdy_framer_
->set_debug_visitor(this);
756 UMA_HISTOGRAM_ENUMERATION(
758 protocol_
- kProtoSPDYHistogramOffset
,
759 kProtoSPDYMaximumVersion
- kProtoSPDYMinimumVersion
+ 1);
761 net_log_
.AddEvent(NetLog::TYPE_SPDY_SESSION_INITIALIZED
,
762 base::Bind(&NetLogSpdyInitializedCallback
,
763 connection_
->socket()->NetLog().source(),
766 DCHECK_EQ(availability_state_
, STATE_AVAILABLE
);
767 connection_
->AddHigherLayeredPool(this);
768 if (enable_sending_initial_data_
)
772 // Bootstrap the read loop.
773 base::MessageLoop::current()->PostTask(
775 base::Bind(&SpdySession::PumpReadLoop
,
776 weak_factory_
.GetWeakPtr(), READ_STATE_DO_READ
, OK
));
779 bool SpdySession::VerifyDomainAuthentication(const std::string
& domain
) {
780 if (!verify_domain_authentication_
)
783 if (availability_state_
== STATE_DRAINING
)
787 bool was_npn_negotiated
;
788 NextProto protocol_negotiated
= kProtoUnknown
;
789 if (!GetSSLInfo(&ssl_info
, &was_npn_negotiated
, &protocol_negotiated
))
790 return true; // This is not a secure session, so all domains are okay.
792 return CanPool(transport_security_state_
, ssl_info
,
793 host_port_pair().host(), domain
);
796 int SpdySession::GetPushStream(
798 base::WeakPtr
<SpdyStream
>* stream
,
799 const BoundNetLog
& stream_net_log
) {
804 if (availability_state_
== STATE_DRAINING
)
805 return ERR_CONNECTION_CLOSED
;
807 Error err
= TryAccessStream(url
);
811 *stream
= GetActivePushStream(url
);
813 DCHECK_LT(streams_pushed_and_claimed_count_
, streams_pushed_count_
);
814 streams_pushed_and_claimed_count_
++;
819 // {,Try}CreateStream() and TryAccessStream() can be called with
820 // |in_io_loop_| set if a stream is being created in response to
821 // another being closed due to received data.
823 Error
SpdySession::TryAccessStream(const GURL
& url
) {
824 if (is_secure_
&& certificate_error_code_
!= OK
&&
825 (url
.SchemeIs("https") || url
.SchemeIs("wss"))) {
826 RecordProtocolErrorHistogram(
827 PROTOCOL_ERROR_REQUEST_FOR_SECURE_CONTENT_OVER_INSECURE_SESSION
);
829 static_cast<Error
>(certificate_error_code_
),
830 "Tried to get SPDY stream for secure content over an unauthenticated "
832 return ERR_SPDY_PROTOCOL_ERROR
;
837 int SpdySession::TryCreateStream(
838 const base::WeakPtr
<SpdyStreamRequest
>& request
,
839 base::WeakPtr
<SpdyStream
>* stream
) {
842 if (availability_state_
== STATE_GOING_AWAY
)
845 if (availability_state_
== STATE_DRAINING
)
846 return ERR_CONNECTION_CLOSED
;
848 Error err
= TryAccessStream(request
->url());
852 if (!max_concurrent_streams_
||
853 (active_streams_
.size() + created_streams_
.size() - num_pushed_streams_
<
854 max_concurrent_streams_
)) {
855 return CreateStream(*request
, stream
);
859 net_log().AddEvent(NetLog::TYPE_SPDY_SESSION_STALLED_MAX_STREAMS
);
860 RequestPriority priority
= request
->priority();
861 CHECK_GE(priority
, MINIMUM_PRIORITY
);
862 CHECK_LE(priority
, MAXIMUM_PRIORITY
);
863 pending_create_stream_queues_
[priority
].push_back(request
);
864 return ERR_IO_PENDING
;
867 int SpdySession::CreateStream(const SpdyStreamRequest
& request
,
868 base::WeakPtr
<SpdyStream
>* stream
) {
869 DCHECK_GE(request
.priority(), MINIMUM_PRIORITY
);
870 DCHECK_LE(request
.priority(), MAXIMUM_PRIORITY
);
872 if (availability_state_
== STATE_GOING_AWAY
)
875 if (availability_state_
== STATE_DRAINING
)
876 return ERR_CONNECTION_CLOSED
;
878 Error err
= TryAccessStream(request
.url());
880 // This should have been caught in TryCreateStream().
885 DCHECK(connection_
->socket());
886 DCHECK(connection_
->socket()->IsConnected());
887 if (connection_
->socket()) {
888 UMA_HISTOGRAM_BOOLEAN("Net.SpdySession.CreateStreamWithSocketConnected",
889 connection_
->socket()->IsConnected());
890 if (!connection_
->socket()->IsConnected()) {
892 ERR_CONNECTION_CLOSED
,
893 "Tried to create SPDY stream for a closed socket connection.");
894 return ERR_CONNECTION_CLOSED
;
898 scoped_ptr
<SpdyStream
> new_stream(
899 new SpdyStream(request
.type(), GetWeakPtr(), request
.url(),
901 stream_initial_send_window_size_
,
902 stream_initial_recv_window_size_
,
904 *stream
= new_stream
->GetWeakPtr();
905 InsertCreatedStream(new_stream
.Pass());
907 UMA_HISTOGRAM_CUSTOM_COUNTS(
908 "Net.SpdyPriorityCount",
909 static_cast<int>(request
.priority()), 0, 10, 11);
914 void SpdySession::CancelStreamRequest(
915 const base::WeakPtr
<SpdyStreamRequest
>& request
) {
917 RequestPriority priority
= request
->priority();
918 CHECK_GE(priority
, MINIMUM_PRIORITY
);
919 CHECK_LE(priority
, MAXIMUM_PRIORITY
);
922 // |request| should not be in a queue not matching its priority.
923 for (int i
= MINIMUM_PRIORITY
; i
<= MAXIMUM_PRIORITY
; ++i
) {
926 PendingStreamRequestQueue
* queue
= &pending_create_stream_queues_
[i
];
927 DCHECK(std::find_if(queue
->begin(),
929 RequestEquals(request
)) == queue
->end());
933 PendingStreamRequestQueue
* queue
=
934 &pending_create_stream_queues_
[priority
];
935 // Remove |request| from |queue| while preserving the order of the
937 PendingStreamRequestQueue::iterator it
=
938 std::find_if(queue
->begin(), queue
->end(), RequestEquals(request
));
939 // The request may already be removed if there's a
940 // CompleteStreamRequest() in flight.
941 if (it
!= queue
->end()) {
942 it
= queue
->erase(it
);
943 // |request| should be in the queue at most once, and if it is
944 // present, should not be pending completion.
945 DCHECK(std::find_if(it
, queue
->end(), RequestEquals(request
)) ==
950 base::WeakPtr
<SpdyStreamRequest
> SpdySession::GetNextPendingStreamRequest() {
951 for (int j
= MAXIMUM_PRIORITY
; j
>= MINIMUM_PRIORITY
; --j
) {
952 if (pending_create_stream_queues_
[j
].empty())
955 base::WeakPtr
<SpdyStreamRequest
> pending_request
=
956 pending_create_stream_queues_
[j
].front();
957 DCHECK(pending_request
);
958 pending_create_stream_queues_
[j
].pop_front();
959 return pending_request
;
961 return base::WeakPtr
<SpdyStreamRequest
>();
964 void SpdySession::ProcessPendingStreamRequests() {
965 // Like |max_concurrent_streams_|, 0 means infinite for
966 // |max_requests_to_process|.
967 size_t max_requests_to_process
= 0;
968 if (max_concurrent_streams_
!= 0) {
969 max_requests_to_process
=
970 max_concurrent_streams_
-
971 (active_streams_
.size() + created_streams_
.size());
974 max_requests_to_process
== 0 || i
< max_requests_to_process
; ++i
) {
975 base::WeakPtr
<SpdyStreamRequest
> pending_request
=
976 GetNextPendingStreamRequest();
977 if (!pending_request
)
980 // Note that this post can race with other stream creations, and it's
981 // possible that the un-stalled stream will be stalled again if it loses.
982 // TODO(jgraettinger): Provide stronger ordering guarantees.
983 base::MessageLoop::current()->PostTask(
985 base::Bind(&SpdySession::CompleteStreamRequest
,
986 weak_factory_
.GetWeakPtr(),
991 void SpdySession::AddPooledAlias(const SpdySessionKey
& alias_key
) {
992 pooled_aliases_
.insert(alias_key
);
995 SpdyMajorVersion
SpdySession::GetProtocolVersion() const {
996 DCHECK(buffered_spdy_framer_
.get());
997 return buffered_spdy_framer_
->protocol_version();
1000 bool SpdySession::HasAcceptableTransportSecurity() const {
1001 // If we're not even using TLS, we have no standards to meet.
1006 // We don't enforce transport security standards for older SPDY versions.
1007 if (GetProtocolVersion() < SPDY4
) {
1012 CHECK(connection_
->socket()->GetSSLInfo(&ssl_info
));
1014 // HTTP/2 requires TLS 1.2+
1015 if (SSLConnectionStatusToVersion(ssl_info
.connection_status
) <
1016 SSL_CONNECTION_VERSION_TLS1_2
) {
1020 if (!IsSecureTLSCipherSuite(
1021 SSLConnectionStatusToCipherSuite(ssl_info
.connection_status
))) {
1028 base::WeakPtr
<SpdySession
> SpdySession::GetWeakPtr() {
1029 return weak_factory_
.GetWeakPtr();
1032 bool SpdySession::CloseOneIdleConnection() {
1033 CHECK(!in_io_loop_
);
1035 if (active_streams_
.empty()) {
1036 DoDrainSession(ERR_CONNECTION_CLOSED
, "Closing idle connection.");
1038 // Return false as the socket wasn't immediately closed.
1042 void SpdySession::EnqueueStreamWrite(
1043 const base::WeakPtr
<SpdyStream
>& stream
,
1044 SpdyFrameType frame_type
,
1045 scoped_ptr
<SpdyBufferProducer
> producer
) {
1046 DCHECK(frame_type
== HEADERS
||
1047 frame_type
== DATA
||
1048 frame_type
== CREDENTIAL
||
1049 frame_type
== SYN_STREAM
);
1050 EnqueueWrite(stream
->priority(), frame_type
, producer
.Pass(), stream
);
1053 scoped_ptr
<SpdyFrame
> SpdySession::CreateSynStream(
1054 SpdyStreamId stream_id
,
1055 RequestPriority priority
,
1056 SpdyControlFlags flags
,
1057 const SpdyHeaderBlock
& block
) {
1058 ActiveStreamMap::const_iterator it
= active_streams_
.find(stream_id
);
1059 CHECK(it
!= active_streams_
.end());
1060 CHECK_EQ(it
->second
.stream
->stream_id(), stream_id
);
1062 SendPrefacePingIfNoneInFlight();
1064 DCHECK(buffered_spdy_framer_
.get());
1065 SpdyPriority spdy_priority
=
1066 ConvertRequestPriorityToSpdyPriority(priority
, GetProtocolVersion());
1068 scoped_ptr
<SpdyFrame
> syn_frame
;
1069 // TODO(hkhalil): Avoid copy of |block|.
1070 if (GetProtocolVersion() <= SPDY3
) {
1071 SpdySynStreamIR
syn_stream(stream_id
);
1072 syn_stream
.set_associated_to_stream_id(0);
1073 syn_stream
.set_priority(spdy_priority
);
1074 syn_stream
.set_fin((flags
& CONTROL_FLAG_FIN
) != 0);
1075 syn_stream
.set_unidirectional((flags
& CONTROL_FLAG_UNIDIRECTIONAL
) != 0);
1076 syn_stream
.set_name_value_block(block
);
1077 syn_frame
.reset(buffered_spdy_framer_
->SerializeFrame(syn_stream
));
1079 SpdyHeadersIR
headers(stream_id
);
1080 headers
.set_priority(spdy_priority
);
1081 headers
.set_has_priority(true);
1082 headers
.set_fin((flags
& CONTROL_FLAG_FIN
) != 0);
1083 headers
.set_name_value_block(block
);
1084 syn_frame
.reset(buffered_spdy_framer_
->SerializeFrame(headers
));
1087 base::StatsCounter
spdy_requests("spdy.requests");
1088 spdy_requests
.Increment();
1089 streams_initiated_count_
++;
1091 if (net_log().IsLogging()) {
1092 net_log().AddEvent(NetLog::TYPE_SPDY_SESSION_SYN_STREAM
,
1093 base::Bind(&NetLogSpdySynStreamSentCallback
,
1095 (flags
& CONTROL_FLAG_FIN
) != 0,
1096 (flags
& CONTROL_FLAG_UNIDIRECTIONAL
) != 0,
1101 return syn_frame
.Pass();
1104 scoped_ptr
<SpdyBuffer
> SpdySession::CreateDataBuffer(SpdyStreamId stream_id
,
1107 SpdyDataFlags flags
) {
1108 if (availability_state_
== STATE_DRAINING
) {
1109 return scoped_ptr
<SpdyBuffer
>();
1112 ActiveStreamMap::const_iterator it
= active_streams_
.find(stream_id
);
1113 CHECK(it
!= active_streams_
.end());
1114 SpdyStream
* stream
= it
->second
.stream
;
1115 CHECK_EQ(stream
->stream_id(), stream_id
);
1119 return scoped_ptr
<SpdyBuffer
>();
1122 int effective_len
= std::min(len
, kMaxSpdyFrameChunkSize
);
1124 bool send_stalled_by_stream
=
1125 (flow_control_state_
>= FLOW_CONTROL_STREAM
) &&
1126 (stream
->send_window_size() <= 0);
1127 bool send_stalled_by_session
= IsSendStalled();
1129 // NOTE: There's an enum of the same name in histograms.xml.
1130 enum SpdyFrameFlowControlState
{
1132 SEND_STALLED_BY_STREAM
,
1133 SEND_STALLED_BY_SESSION
,
1134 SEND_STALLED_BY_STREAM_AND_SESSION
,
1137 SpdyFrameFlowControlState frame_flow_control_state
= SEND_NOT_STALLED
;
1138 if (send_stalled_by_stream
) {
1139 if (send_stalled_by_session
) {
1140 frame_flow_control_state
= SEND_STALLED_BY_STREAM_AND_SESSION
;
1142 frame_flow_control_state
= SEND_STALLED_BY_STREAM
;
1144 } else if (send_stalled_by_session
) {
1145 frame_flow_control_state
= SEND_STALLED_BY_SESSION
;
1148 if (flow_control_state_
== FLOW_CONTROL_STREAM
) {
1149 UMA_HISTOGRAM_ENUMERATION(
1150 "Net.SpdyFrameStreamFlowControlState",
1151 frame_flow_control_state
,
1152 SEND_STALLED_BY_STREAM
+ 1);
1153 } else if (flow_control_state_
== FLOW_CONTROL_STREAM_AND_SESSION
) {
1154 UMA_HISTOGRAM_ENUMERATION(
1155 "Net.SpdyFrameStreamAndSessionFlowControlState",
1156 frame_flow_control_state
,
1157 SEND_STALLED_BY_STREAM_AND_SESSION
+ 1);
1160 // Obey send window size of the stream if stream flow control is
1162 if (flow_control_state_
>= FLOW_CONTROL_STREAM
) {
1163 if (send_stalled_by_stream
) {
1164 stream
->set_send_stalled_by_flow_control(true);
1165 // Even though we're currently stalled only by the stream, we
1166 // might end up being stalled by the session also.
1167 QueueSendStalledStream(*stream
);
1169 NetLog::TYPE_SPDY_SESSION_STREAM_STALLED_BY_STREAM_SEND_WINDOW
,
1170 NetLog::IntegerCallback("stream_id", stream_id
));
1171 return scoped_ptr
<SpdyBuffer
>();
1174 effective_len
= std::min(effective_len
, stream
->send_window_size());
1177 // Obey send window size of the session if session flow control is
1179 if (flow_control_state_
== FLOW_CONTROL_STREAM_AND_SESSION
) {
1180 if (send_stalled_by_session
) {
1181 stream
->set_send_stalled_by_flow_control(true);
1182 QueueSendStalledStream(*stream
);
1184 NetLog::TYPE_SPDY_SESSION_STREAM_STALLED_BY_SESSION_SEND_WINDOW
,
1185 NetLog::IntegerCallback("stream_id", stream_id
));
1186 return scoped_ptr
<SpdyBuffer
>();
1189 effective_len
= std::min(effective_len
, session_send_window_size_
);
1192 DCHECK_GE(effective_len
, 0);
1194 // Clear FIN flag if only some of the data will be in the data
1196 if (effective_len
< len
)
1197 flags
= static_cast<SpdyDataFlags
>(flags
& ~DATA_FLAG_FIN
);
1199 if (net_log().IsLogging()) {
1201 NetLog::TYPE_SPDY_SESSION_SEND_DATA
,
1202 base::Bind(&NetLogSpdyDataCallback
, stream_id
, effective_len
,
1203 (flags
& DATA_FLAG_FIN
) != 0));
1206 // Send PrefacePing for DATA_FRAMEs with nonzero payload size.
1207 if (effective_len
> 0)
1208 SendPrefacePingIfNoneInFlight();
1210 // TODO(mbelshe): reduce memory copies here.
1211 DCHECK(buffered_spdy_framer_
.get());
1212 scoped_ptr
<SpdyFrame
> frame(
1213 buffered_spdy_framer_
->CreateDataFrame(
1214 stream_id
, data
->data(),
1215 static_cast<uint32
>(effective_len
), flags
));
1217 scoped_ptr
<SpdyBuffer
> data_buffer(new SpdyBuffer(frame
.Pass()));
1219 // Send window size is based on payload size, so nothing to do if this is
1220 // just a FIN with no payload.
1221 if (flow_control_state_
== FLOW_CONTROL_STREAM_AND_SESSION
&&
1222 effective_len
!= 0) {
1223 DecreaseSendWindowSize(static_cast<int32
>(effective_len
));
1224 data_buffer
->AddConsumeCallback(
1225 base::Bind(&SpdySession::OnWriteBufferConsumed
,
1226 weak_factory_
.GetWeakPtr(),
1227 static_cast<size_t>(effective_len
)));
1230 return data_buffer
.Pass();
1233 void SpdySession::CloseActiveStream(SpdyStreamId stream_id
, int status
) {
1234 DCHECK_NE(stream_id
, 0u);
1236 ActiveStreamMap::iterator it
= active_streams_
.find(stream_id
);
1237 if (it
== active_streams_
.end()) {
1242 CloseActiveStreamIterator(it
, status
);
1245 void SpdySession::CloseCreatedStream(
1246 const base::WeakPtr
<SpdyStream
>& stream
, int status
) {
1247 DCHECK_EQ(stream
->stream_id(), 0u);
1249 CreatedStreamSet::iterator it
= created_streams_
.find(stream
.get());
1250 if (it
== created_streams_
.end()) {
1255 CloseCreatedStreamIterator(it
, status
);
1258 void SpdySession::ResetStream(SpdyStreamId stream_id
,
1259 SpdyRstStreamStatus status
,
1260 const std::string
& description
) {
1261 DCHECK_NE(stream_id
, 0u);
1263 ActiveStreamMap::iterator it
= active_streams_
.find(stream_id
);
1264 if (it
== active_streams_
.end()) {
1269 ResetStreamIterator(it
, status
, description
);
1272 bool SpdySession::IsStreamActive(SpdyStreamId stream_id
) const {
1273 return ContainsKey(active_streams_
, stream_id
);
1276 LoadState
SpdySession::GetLoadState() const {
1277 // Just report that we're idle since the session could be doing
1278 // many things concurrently.
1279 return LOAD_STATE_IDLE
;
1282 void SpdySession::CloseActiveStreamIterator(ActiveStreamMap::iterator it
,
1284 // TODO(mbelshe): We should send a RST_STREAM control frame here
1285 // so that the server can cancel a large send.
1287 scoped_ptr
<SpdyStream
> owned_stream(it
->second
.stream
);
1288 active_streams_
.erase(it
);
1290 // TODO(akalin): When SpdyStream was ref-counted (and
1291 // |unclaimed_pushed_streams_| held scoped_refptr<SpdyStream>), this
1292 // was only done when status was not OK. This meant that pushed
1293 // streams can still be claimed after they're closed. This is
1294 // probably something that we still want to support, although server
1295 // push is hardly used. Write tests for this and fix this. (See
1296 // http://crbug.com/261712 .)
1297 if (owned_stream
->type() == SPDY_PUSH_STREAM
) {
1298 unclaimed_pushed_streams_
.erase(owned_stream
->url());
1299 num_pushed_streams_
--;
1300 if (!owned_stream
->IsReservedRemote())
1301 num_active_pushed_streams_
--;
1304 DeleteStream(owned_stream
.Pass(), status
);
1305 MaybeFinishGoingAway();
1307 // If there are no active streams and the socket pool is stalled, close the
1308 // session to free up a socket slot.
1309 if (active_streams_
.empty() && connection_
->IsPoolStalled()) {
1310 DoDrainSession(ERR_CONNECTION_CLOSED
, "Closing idle connection.");
1314 void SpdySession::CloseCreatedStreamIterator(CreatedStreamSet::iterator it
,
1316 scoped_ptr
<SpdyStream
> owned_stream(*it
);
1317 created_streams_
.erase(it
);
1318 DeleteStream(owned_stream
.Pass(), status
);
1321 void SpdySession::ResetStreamIterator(ActiveStreamMap::iterator it
,
1322 SpdyRstStreamStatus status
,
1323 const std::string
& description
) {
1324 // Send the RST_STREAM frame first as CloseActiveStreamIterator()
1326 SpdyStreamId stream_id
= it
->first
;
1327 RequestPriority priority
= it
->second
.stream
->priority();
1328 EnqueueResetStreamFrame(stream_id
, priority
, status
, description
);
1330 // Removes any pending writes for the stream except for possibly an
1332 CloseActiveStreamIterator(it
, ERR_SPDY_PROTOCOL_ERROR
);
1335 void SpdySession::EnqueueResetStreamFrame(SpdyStreamId stream_id
,
1336 RequestPriority priority
,
1337 SpdyRstStreamStatus status
,
1338 const std::string
& description
) {
1339 DCHECK_NE(stream_id
, 0u);
1342 NetLog::TYPE_SPDY_SESSION_SEND_RST_STREAM
,
1343 base::Bind(&NetLogSpdyRstCallback
, stream_id
, status
, &description
));
1345 DCHECK(buffered_spdy_framer_
.get());
1346 scoped_ptr
<SpdyFrame
> rst_frame(
1347 buffered_spdy_framer_
->CreateRstStream(stream_id
, status
));
1349 EnqueueSessionWrite(priority
, RST_STREAM
, rst_frame
.Pass());
1350 RecordProtocolErrorHistogram(MapRstStreamStatusToProtocolError(status
));
1353 void SpdySession::PumpReadLoop(ReadState expected_read_state
, int result
) {
1354 // TODO(vadimt): Remove ScopedTracker below once crbug.com/418183 is fixed.
1355 tracked_objects::ScopedTracker
tracking_profile(
1356 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1357 "418183 DoReadCallback => SpdySession::PumpReadLoop"));
1359 CHECK(!in_io_loop_
);
1360 if (availability_state_
== STATE_DRAINING
) {
1363 ignore_result(DoReadLoop(expected_read_state
, result
));
1366 int SpdySession::DoReadLoop(ReadState expected_read_state
, int result
) {
1367 CHECK(!in_io_loop_
);
1368 CHECK_EQ(read_state_
, expected_read_state
);
1372 int bytes_read_without_yielding
= 0;
1374 // Loop until the session is draining, the read becomes blocked, or
1375 // the read limit is exceeded.
1377 switch (read_state_
) {
1378 case READ_STATE_DO_READ
:
1379 CHECK_EQ(result
, OK
);
1382 case READ_STATE_DO_READ_COMPLETE
:
1384 bytes_read_without_yielding
+= result
;
1385 result
= DoReadComplete(result
);
1388 NOTREACHED() << "read_state_: " << read_state_
;
1392 if (availability_state_
== STATE_DRAINING
)
1395 if (result
== ERR_IO_PENDING
)
1398 if (bytes_read_without_yielding
> kMaxReadBytesWithoutYielding
) {
1399 read_state_
= READ_STATE_DO_READ
;
1400 base::MessageLoop::current()->PostTask(
1402 base::Bind(&SpdySession::PumpReadLoop
,
1403 weak_factory_
.GetWeakPtr(), READ_STATE_DO_READ
, OK
));
1404 result
= ERR_IO_PENDING
;
1410 in_io_loop_
= false;
1415 int SpdySession::DoRead() {
1419 CHECK(connection_
->socket());
1420 read_state_
= READ_STATE_DO_READ_COMPLETE
;
1421 return connection_
->socket()->Read(
1424 base::Bind(&SpdySession::PumpReadLoop
,
1425 weak_factory_
.GetWeakPtr(), READ_STATE_DO_READ_COMPLETE
));
1428 int SpdySession::DoReadComplete(int result
) {
1431 // Parse a frame. For now this code requires that the frame fit into our
1432 // buffer (kReadBufferSize).
1433 // TODO(mbelshe): support arbitrarily large frames!
1436 UMA_HISTOGRAM_CUSTOM_COUNTS("Net.SpdySession.BytesRead.EOF",
1437 total_bytes_received_
, 1, 100000000, 50);
1438 DoDrainSession(ERR_CONNECTION_CLOSED
, "Connection closed");
1440 return ERR_CONNECTION_CLOSED
;
1444 DoDrainSession(static_cast<Error
>(result
), "result is < 0.");
1447 CHECK_LE(result
, kReadBufferSize
);
1448 total_bytes_received_
+= result
;
1450 last_activity_time_
= time_func_();
1452 DCHECK(buffered_spdy_framer_
.get());
1453 char* data
= read_buffer_
->data();
1454 while (result
> 0) {
1455 uint32 bytes_processed
= buffered_spdy_framer_
->ProcessInput(data
, result
);
1456 result
-= bytes_processed
;
1457 data
+= bytes_processed
;
1459 if (availability_state_
== STATE_DRAINING
) {
1460 return ERR_CONNECTION_CLOSED
;
1463 DCHECK_EQ(buffered_spdy_framer_
->error_code(), SpdyFramer::SPDY_NO_ERROR
);
1466 read_state_
= READ_STATE_DO_READ
;
1470 void SpdySession::PumpWriteLoop(WriteState expected_write_state
, int result
) {
1471 CHECK(!in_io_loop_
);
1472 DCHECK_EQ(write_state_
, expected_write_state
);
1474 DoWriteLoop(expected_write_state
, result
);
1476 if (availability_state_
== STATE_DRAINING
&& !in_flight_write_
&&
1477 write_queue_
.IsEmpty()) {
1478 pool_
->RemoveUnavailableSession(GetWeakPtr()); // Destroys |this|.
1483 int SpdySession::DoWriteLoop(WriteState expected_write_state
, int result
) {
1484 CHECK(!in_io_loop_
);
1485 DCHECK_NE(write_state_
, WRITE_STATE_IDLE
);
1486 DCHECK_EQ(write_state_
, expected_write_state
);
1490 // Loop until the session is closed or the write becomes blocked.
1492 switch (write_state_
) {
1493 case WRITE_STATE_DO_WRITE
:
1494 DCHECK_EQ(result
, OK
);
1497 case WRITE_STATE_DO_WRITE_COMPLETE
:
1498 result
= DoWriteComplete(result
);
1500 case WRITE_STATE_IDLE
:
1502 NOTREACHED() << "write_state_: " << write_state_
;
1506 if (write_state_
== WRITE_STATE_IDLE
) {
1507 DCHECK_EQ(result
, ERR_IO_PENDING
);
1511 if (result
== ERR_IO_PENDING
)
1516 in_io_loop_
= false;
1521 int SpdySession::DoWrite() {
1524 DCHECK(buffered_spdy_framer_
);
1525 if (in_flight_write_
) {
1526 DCHECK_GT(in_flight_write_
->GetRemainingSize(), 0u);
1528 // Grab the next frame to send.
1529 SpdyFrameType frame_type
= DATA
;
1530 scoped_ptr
<SpdyBufferProducer
> producer
;
1531 base::WeakPtr
<SpdyStream
> stream
;
1532 if (!write_queue_
.Dequeue(&frame_type
, &producer
, &stream
)) {
1533 write_state_
= WRITE_STATE_IDLE
;
1534 return ERR_IO_PENDING
;
1538 CHECK(!stream
->IsClosed());
1540 // Activate the stream only when sending the SYN_STREAM frame to
1541 // guarantee monotonically-increasing stream IDs.
1542 if (frame_type
== SYN_STREAM
) {
1543 CHECK(stream
.get());
1544 CHECK_EQ(stream
->stream_id(), 0u);
1545 scoped_ptr
<SpdyStream
> owned_stream
=
1546 ActivateCreatedStream(stream
.get());
1547 InsertActivatedStream(owned_stream
.Pass());
1549 if (stream_hi_water_mark_
> kLastStreamId
) {
1550 CHECK_EQ(stream
->stream_id(), kLastStreamId
);
1551 // We've exhausted the stream ID space, and no new streams may be
1552 // created after this one.
1554 StartGoingAway(kLastStreamId
, ERR_ABORTED
);
1558 in_flight_write_
= producer
->ProduceBuffer();
1559 if (!in_flight_write_
) {
1561 return ERR_UNEXPECTED
;
1563 in_flight_write_frame_type_
= frame_type
;
1564 in_flight_write_frame_size_
= in_flight_write_
->GetRemainingSize();
1565 DCHECK_GE(in_flight_write_frame_size_
,
1566 buffered_spdy_framer_
->GetFrameMinimumSize());
1567 in_flight_write_stream_
= stream
;
1570 write_state_
= WRITE_STATE_DO_WRITE_COMPLETE
;
1572 // Explicitly store in a scoped_refptr<IOBuffer> to avoid problems
1573 // with Socket implementations that don't store their IOBuffer
1574 // argument in a scoped_refptr<IOBuffer> (see crbug.com/232345).
1575 scoped_refptr
<IOBuffer
> write_io_buffer
=
1576 in_flight_write_
->GetIOBufferForRemainingData();
1577 return connection_
->socket()->Write(
1578 write_io_buffer
.get(),
1579 in_flight_write_
->GetRemainingSize(),
1580 base::Bind(&SpdySession::PumpWriteLoop
,
1581 weak_factory_
.GetWeakPtr(), WRITE_STATE_DO_WRITE_COMPLETE
));
1584 int SpdySession::DoWriteComplete(int result
) {
1586 DCHECK_NE(result
, ERR_IO_PENDING
);
1587 DCHECK_GT(in_flight_write_
->GetRemainingSize(), 0u);
1589 last_activity_time_
= time_func_();
1592 DCHECK_NE(result
, ERR_IO_PENDING
);
1593 in_flight_write_
.reset();
1594 in_flight_write_frame_type_
= DATA
;
1595 in_flight_write_frame_size_
= 0;
1596 in_flight_write_stream_
.reset();
1597 write_state_
= WRITE_STATE_DO_WRITE
;
1598 DoDrainSession(static_cast<Error
>(result
), "Write error");
1602 // It should not be possible to have written more bytes than our
1603 // in_flight_write_.
1604 DCHECK_LE(static_cast<size_t>(result
),
1605 in_flight_write_
->GetRemainingSize());
1608 in_flight_write_
->Consume(static_cast<size_t>(result
));
1610 // We only notify the stream when we've fully written the pending frame.
1611 if (in_flight_write_
->GetRemainingSize() == 0) {
1612 // It is possible that the stream was cancelled while we were
1613 // writing to the socket.
1614 if (in_flight_write_stream_
.get()) {
1615 DCHECK_GT(in_flight_write_frame_size_
, 0u);
1616 in_flight_write_stream_
->OnFrameWriteComplete(
1617 in_flight_write_frame_type_
,
1618 in_flight_write_frame_size_
);
1621 // Cleanup the write which just completed.
1622 in_flight_write_
.reset();
1623 in_flight_write_frame_type_
= DATA
;
1624 in_flight_write_frame_size_
= 0;
1625 in_flight_write_stream_
.reset();
1629 write_state_
= WRITE_STATE_DO_WRITE
;
1633 void SpdySession::DcheckGoingAway() const {
1635 DCHECK_GE(availability_state_
, STATE_GOING_AWAY
);
1636 for (int i
= MINIMUM_PRIORITY
; i
<= MAXIMUM_PRIORITY
; ++i
) {
1637 DCHECK(pending_create_stream_queues_
[i
].empty());
1639 DCHECK(created_streams_
.empty());
1643 void SpdySession::DcheckDraining() const {
1645 DCHECK_EQ(availability_state_
, STATE_DRAINING
);
1646 DCHECK(active_streams_
.empty());
1647 DCHECK(unclaimed_pushed_streams_
.empty());
1650 void SpdySession::StartGoingAway(SpdyStreamId last_good_stream_id
,
1652 DCHECK_GE(availability_state_
, STATE_GOING_AWAY
);
1654 // The loops below are carefully written to avoid reentrancy problems.
1657 size_t old_size
= GetTotalSize(pending_create_stream_queues_
);
1658 base::WeakPtr
<SpdyStreamRequest
> pending_request
=
1659 GetNextPendingStreamRequest();
1660 if (!pending_request
)
1662 // No new stream requests should be added while the session is
1664 DCHECK_GT(old_size
, GetTotalSize(pending_create_stream_queues_
));
1665 pending_request
->OnRequestCompleteFailure(ERR_ABORTED
);
1669 size_t old_size
= active_streams_
.size();
1670 ActiveStreamMap::iterator it
=
1671 active_streams_
.lower_bound(last_good_stream_id
+ 1);
1672 if (it
== active_streams_
.end())
1674 LogAbandonedActiveStream(it
, status
);
1675 CloseActiveStreamIterator(it
, status
);
1676 // No new streams should be activated while the session is going
1678 DCHECK_GT(old_size
, active_streams_
.size());
1681 while (!created_streams_
.empty()) {
1682 size_t old_size
= created_streams_
.size();
1683 CreatedStreamSet::iterator it
= created_streams_
.begin();
1684 LogAbandonedStream(*it
, status
);
1685 CloseCreatedStreamIterator(it
, status
);
1686 // No new streams should be created while the session is going
1688 DCHECK_GT(old_size
, created_streams_
.size());
1691 write_queue_
.RemovePendingWritesForStreamsAfter(last_good_stream_id
);
1696 void SpdySession::MaybeFinishGoingAway() {
1697 if (active_streams_
.empty() && availability_state_
== STATE_GOING_AWAY
) {
1698 DoDrainSession(OK
, "Finished going away");
1702 void SpdySession::DoDrainSession(Error err
, const std::string
& description
) {
1703 if (availability_state_
== STATE_DRAINING
) {
1708 // If |err| indicates an error occurred, inform the peer that we're closing
1709 // and why. Don't GOAWAY on a graceful or idle close, as that may
1710 // unnecessarily wake the radio. We could technically GOAWAY on network errors
1711 // (we'll probably fail to actually write it, but that's okay), however many
1712 // unit-tests would need to be updated.
1714 err
!= ERR_ABORTED
&& // Used by SpdySessionPool to close idle sessions.
1715 err
!= ERR_NETWORK_CHANGED
&& // Used to deprecate sessions on IP change.
1716 err
!= ERR_SOCKET_NOT_CONNECTED
&&
1717 err
!= ERR_CONNECTION_CLOSED
&& err
!= ERR_CONNECTION_RESET
) {
1718 // Enqueue a GOAWAY to inform the peer of why we're closing the connection.
1719 SpdyGoAwayIR
goaway_ir(last_accepted_push_stream_id_
,
1720 MapNetErrorToGoAwayStatus(err
),
1722 EnqueueSessionWrite(HIGHEST
,
1724 scoped_ptr
<SpdyFrame
>(
1725 buffered_spdy_framer_
->SerializeFrame(goaway_ir
)));
1728 availability_state_
= STATE_DRAINING
;
1729 error_on_close_
= err
;
1732 NetLog::TYPE_SPDY_SESSION_CLOSE
,
1733 base::Bind(&NetLogSpdySessionCloseCallback
, err
, &description
));
1735 UMA_HISTOGRAM_SPARSE_SLOWLY("Net.SpdySession.ClosedOnError", -err
);
1736 UMA_HISTOGRAM_CUSTOM_COUNTS("Net.SpdySession.BytesRead.OtherErrors",
1737 total_bytes_received_
, 1, 100000000, 50);
1740 // We ought to be going away already, as this is a graceful close.
1743 StartGoingAway(0, err
);
1746 MaybePostWriteLoop();
1749 void SpdySession::LogAbandonedStream(SpdyStream
* stream
, Error status
) {
1751 std::string description
= base::StringPrintf(
1752 "ABANDONED (stream_id=%d): ", stream
->stream_id()) +
1753 stream
->url().spec();
1754 stream
->LogStreamError(status
, description
);
1755 // We don't increment the streams abandoned counter here. If the
1756 // stream isn't active (i.e., it hasn't written anything to the wire
1757 // yet) then it's as if it never existed. If it is active, then
1758 // LogAbandonedActiveStream() will increment the counters.
1761 void SpdySession::LogAbandonedActiveStream(ActiveStreamMap::const_iterator it
,
1763 DCHECK_GT(it
->first
, 0u);
1764 LogAbandonedStream(it
->second
.stream
, status
);
1765 ++streams_abandoned_count_
;
1766 base::StatsCounter
abandoned_streams("spdy.abandoned_streams");
1767 abandoned_streams
.Increment();
1768 if (it
->second
.stream
->type() == SPDY_PUSH_STREAM
&&
1769 unclaimed_pushed_streams_
.find(it
->second
.stream
->url()) !=
1770 unclaimed_pushed_streams_
.end()) {
1771 base::StatsCounter
abandoned_push_streams("spdy.abandoned_push_streams");
1772 abandoned_push_streams
.Increment();
1776 SpdyStreamId
SpdySession::GetNewStreamId() {
1777 CHECK_LE(stream_hi_water_mark_
, kLastStreamId
);
1778 SpdyStreamId id
= stream_hi_water_mark_
;
1779 stream_hi_water_mark_
+= 2;
1783 void SpdySession::CloseSessionOnError(Error err
,
1784 const std::string
& description
) {
1785 DCHECK_LT(err
, ERR_IO_PENDING
);
1786 DoDrainSession(err
, description
);
1789 void SpdySession::MakeUnavailable() {
1790 if (availability_state_
== STATE_AVAILABLE
) {
1791 availability_state_
= STATE_GOING_AWAY
;
1792 pool_
->MakeSessionUnavailable(GetWeakPtr());
1796 base::Value
* SpdySession::GetInfoAsValue() const {
1797 base::DictionaryValue
* dict
= new base::DictionaryValue();
1799 dict
->SetInteger("source_id", net_log_
.source().id
);
1801 dict
->SetString("host_port_pair", host_port_pair().ToString());
1802 if (!pooled_aliases_
.empty()) {
1803 base::ListValue
* alias_list
= new base::ListValue();
1804 for (std::set
<SpdySessionKey
>::const_iterator it
=
1805 pooled_aliases_
.begin();
1806 it
!= pooled_aliases_
.end(); it
++) {
1807 alias_list
->Append(new base::StringValue(
1808 it
->host_port_pair().ToString()));
1810 dict
->Set("aliases", alias_list
);
1812 dict
->SetString("proxy", host_port_proxy_pair().second
.ToURI());
1814 dict
->SetInteger("active_streams", active_streams_
.size());
1816 dict
->SetInteger("unclaimed_pushed_streams",
1817 unclaimed_pushed_streams_
.size());
1819 dict
->SetBoolean("is_secure", is_secure_
);
1821 dict
->SetString("protocol_negotiated",
1822 SSLClientSocket::NextProtoToString(
1823 connection_
->socket()->GetNegotiatedProtocol()));
1825 dict
->SetInteger("error", error_on_close_
);
1826 dict
->SetInteger("max_concurrent_streams", max_concurrent_streams_
);
1828 dict
->SetInteger("streams_initiated_count", streams_initiated_count_
);
1829 dict
->SetInteger("streams_pushed_count", streams_pushed_count_
);
1830 dict
->SetInteger("streams_pushed_and_claimed_count",
1831 streams_pushed_and_claimed_count_
);
1832 dict
->SetInteger("streams_abandoned_count", streams_abandoned_count_
);
1833 DCHECK(buffered_spdy_framer_
.get());
1834 dict
->SetInteger("frames_received", buffered_spdy_framer_
->frames_received());
1836 dict
->SetBoolean("sent_settings", sent_settings_
);
1837 dict
->SetBoolean("received_settings", received_settings_
);
1839 dict
->SetInteger("send_window_size", session_send_window_size_
);
1840 dict
->SetInteger("recv_window_size", session_recv_window_size_
);
1841 dict
->SetInteger("unacked_recv_window_bytes",
1842 session_unacked_recv_window_bytes_
);
1846 bool SpdySession::IsReused() const {
1847 return buffered_spdy_framer_
->frames_received() > 0 ||
1848 connection_
->reuse_type() == ClientSocketHandle::UNUSED_IDLE
;
1851 bool SpdySession::GetLoadTimingInfo(SpdyStreamId stream_id
,
1852 LoadTimingInfo
* load_timing_info
) const {
1853 return connection_
->GetLoadTimingInfo(stream_id
!= kFirstStreamId
,
1857 int SpdySession::GetPeerAddress(IPEndPoint
* address
) const {
1858 int rv
= ERR_SOCKET_NOT_CONNECTED
;
1859 if (connection_
->socket()) {
1860 rv
= connection_
->socket()->GetPeerAddress(address
);
1863 UMA_HISTOGRAM_BOOLEAN("Net.SpdySessionSocketNotConnectedGetPeerAddress",
1864 rv
== ERR_SOCKET_NOT_CONNECTED
);
1869 int SpdySession::GetLocalAddress(IPEndPoint
* address
) const {
1870 int rv
= ERR_SOCKET_NOT_CONNECTED
;
1871 if (connection_
->socket()) {
1872 rv
= connection_
->socket()->GetLocalAddress(address
);
1875 UMA_HISTOGRAM_BOOLEAN("Net.SpdySessionSocketNotConnectedGetLocalAddress",
1876 rv
== ERR_SOCKET_NOT_CONNECTED
);
1881 void SpdySession::EnqueueSessionWrite(RequestPriority priority
,
1882 SpdyFrameType frame_type
,
1883 scoped_ptr
<SpdyFrame
> frame
) {
1884 DCHECK(frame_type
== RST_STREAM
|| frame_type
== SETTINGS
||
1885 frame_type
== WINDOW_UPDATE
|| frame_type
== PING
||
1886 frame_type
== GOAWAY
);
1888 priority
, frame_type
,
1889 scoped_ptr
<SpdyBufferProducer
>(
1890 new SimpleBufferProducer(
1891 scoped_ptr
<SpdyBuffer
>(new SpdyBuffer(frame
.Pass())))),
1892 base::WeakPtr
<SpdyStream
>());
1895 void SpdySession::EnqueueWrite(RequestPriority priority
,
1896 SpdyFrameType frame_type
,
1897 scoped_ptr
<SpdyBufferProducer
> producer
,
1898 const base::WeakPtr
<SpdyStream
>& stream
) {
1899 if (availability_state_
== STATE_DRAINING
)
1902 write_queue_
.Enqueue(priority
, frame_type
, producer
.Pass(), stream
);
1903 MaybePostWriteLoop();
1906 void SpdySession::MaybePostWriteLoop() {
1907 if (write_state_
== WRITE_STATE_IDLE
) {
1908 CHECK(!in_flight_write_
);
1909 write_state_
= WRITE_STATE_DO_WRITE
;
1910 base::MessageLoop::current()->PostTask(
1912 base::Bind(&SpdySession::PumpWriteLoop
,
1913 weak_factory_
.GetWeakPtr(), WRITE_STATE_DO_WRITE
, OK
));
1917 void SpdySession::InsertCreatedStream(scoped_ptr
<SpdyStream
> stream
) {
1918 CHECK_EQ(stream
->stream_id(), 0u);
1919 CHECK(created_streams_
.find(stream
.get()) == created_streams_
.end());
1920 created_streams_
.insert(stream
.release());
1923 scoped_ptr
<SpdyStream
> SpdySession::ActivateCreatedStream(SpdyStream
* stream
) {
1924 CHECK_EQ(stream
->stream_id(), 0u);
1925 CHECK(created_streams_
.find(stream
) != created_streams_
.end());
1926 stream
->set_stream_id(GetNewStreamId());
1927 scoped_ptr
<SpdyStream
> owned_stream(stream
);
1928 created_streams_
.erase(stream
);
1929 return owned_stream
.Pass();
1932 void SpdySession::InsertActivatedStream(scoped_ptr
<SpdyStream
> stream
) {
1933 SpdyStreamId stream_id
= stream
->stream_id();
1934 CHECK_NE(stream_id
, 0u);
1935 std::pair
<ActiveStreamMap::iterator
, bool> result
=
1936 active_streams_
.insert(
1937 std::make_pair(stream_id
, ActiveStreamInfo(stream
.get())));
1938 CHECK(result
.second
);
1939 ignore_result(stream
.release());
1942 void SpdySession::DeleteStream(scoped_ptr
<SpdyStream
> stream
, int status
) {
1943 if (in_flight_write_stream_
.get() == stream
.get()) {
1944 // If we're deleting the stream for the in-flight write, we still
1945 // need to let the write complete, so we clear
1946 // |in_flight_write_stream_| and let the write finish on its own
1947 // without notifying |in_flight_write_stream_|.
1948 in_flight_write_stream_
.reset();
1951 write_queue_
.RemovePendingWritesForStream(stream
->GetWeakPtr());
1952 stream
->OnClose(status
);
1954 if (availability_state_
== STATE_AVAILABLE
) {
1955 ProcessPendingStreamRequests();
1959 base::WeakPtr
<SpdyStream
> SpdySession::GetActivePushStream(const GURL
& url
) {
1960 base::StatsCounter
used_push_streams("spdy.claimed_push_streams");
1962 PushedStreamMap::iterator unclaimed_it
= unclaimed_pushed_streams_
.find(url
);
1963 if (unclaimed_it
== unclaimed_pushed_streams_
.end())
1964 return base::WeakPtr
<SpdyStream
>();
1966 SpdyStreamId stream_id
= unclaimed_it
->second
.stream_id
;
1967 unclaimed_pushed_streams_
.erase(unclaimed_it
);
1969 ActiveStreamMap::iterator active_it
= active_streams_
.find(stream_id
);
1970 if (active_it
== active_streams_
.end()) {
1972 return base::WeakPtr
<SpdyStream
>();
1975 net_log_
.AddEvent(NetLog::TYPE_SPDY_STREAM_ADOPTED_PUSH_STREAM
,
1976 base::Bind(&NetLogSpdyAdoptedPushStreamCallback
,
1977 active_it
->second
.stream
->stream_id(), &url
));
1978 used_push_streams
.Increment();
1979 return active_it
->second
.stream
->GetWeakPtr();
1982 bool SpdySession::GetSSLInfo(SSLInfo
* ssl_info
,
1983 bool* was_npn_negotiated
,
1984 NextProto
* protocol_negotiated
) {
1985 *was_npn_negotiated
= connection_
->socket()->WasNpnNegotiated();
1986 *protocol_negotiated
= connection_
->socket()->GetNegotiatedProtocol();
1987 return connection_
->socket()->GetSSLInfo(ssl_info
);
1990 bool SpdySession::GetSSLCertRequestInfo(
1991 SSLCertRequestInfo
* cert_request_info
) {
1994 GetSSLClientSocket()->GetSSLCertRequestInfo(cert_request_info
);
1998 void SpdySession::OnError(SpdyFramer::SpdyError error_code
) {
2001 RecordProtocolErrorHistogram(MapFramerErrorToProtocolError(error_code
));
2002 std::string description
=
2003 base::StringPrintf("Framer error: %d (%s).",
2005 SpdyFramer::ErrorCodeToString(error_code
));
2006 DoDrainSession(MapFramerErrorToNetError(error_code
), description
);
2009 void SpdySession::OnStreamError(SpdyStreamId stream_id
,
2010 const std::string
& description
) {
2013 ActiveStreamMap::iterator it
= active_streams_
.find(stream_id
);
2014 if (it
== active_streams_
.end()) {
2015 // We still want to send a frame to reset the stream even if we
2016 // don't know anything about it.
2017 EnqueueResetStreamFrame(
2018 stream_id
, IDLE
, RST_STREAM_PROTOCOL_ERROR
, description
);
2022 ResetStreamIterator(it
, RST_STREAM_PROTOCOL_ERROR
, description
);
2025 void SpdySession::OnDataFrameHeader(SpdyStreamId stream_id
,
2030 ActiveStreamMap::iterator it
= active_streams_
.find(stream_id
);
2032 // By the time data comes in, the stream may already be inactive.
2033 if (it
== active_streams_
.end())
2036 SpdyStream
* stream
= it
->second
.stream
;
2037 CHECK_EQ(stream
->stream_id(), stream_id
);
2039 DCHECK(buffered_spdy_framer_
);
2040 size_t header_len
= buffered_spdy_framer_
->GetDataFrameMinimumSize();
2041 stream
->IncrementRawReceivedBytes(header_len
);
2044 void SpdySession::OnStreamFrameData(SpdyStreamId stream_id
,
2050 if (data
== NULL
&& len
!= 0) {
2051 // This is notification of consumed data padding.
2052 // TODO(jgraettinger): Properly flow padding into WINDOW_UPDATE frames.
2053 // See crbug.com/353012.
2057 DCHECK_LT(len
, 1u << 24);
2058 if (net_log().IsLogging()) {
2060 NetLog::TYPE_SPDY_SESSION_RECV_DATA
,
2061 base::Bind(&NetLogSpdyDataCallback
, stream_id
, len
, fin
));
2064 // Build the buffer as early as possible so that we go through the
2065 // session flow control checks and update
2066 // |unacked_recv_window_bytes_| properly even when the stream is
2067 // inactive (since the other side has still reduced its session send
2069 scoped_ptr
<SpdyBuffer
> buffer
;
2072 CHECK_LE(len
, static_cast<size_t>(kReadBufferSize
));
2073 buffer
.reset(new SpdyBuffer(data
, len
));
2075 if (flow_control_state_
== FLOW_CONTROL_STREAM_AND_SESSION
) {
2076 DecreaseRecvWindowSize(static_cast<int32
>(len
));
2077 buffer
->AddConsumeCallback(
2078 base::Bind(&SpdySession::OnReadBufferConsumed
,
2079 weak_factory_
.GetWeakPtr()));
2085 ActiveStreamMap::iterator it
= active_streams_
.find(stream_id
);
2087 // By the time data comes in, the stream may already be inactive.
2088 if (it
== active_streams_
.end())
2091 SpdyStream
* stream
= it
->second
.stream
;
2092 CHECK_EQ(stream
->stream_id(), stream_id
);
2094 stream
->IncrementRawReceivedBytes(len
);
2096 if (it
->second
.waiting_for_syn_reply
) {
2097 const std::string
& error
= "Data received before SYN_REPLY.";
2098 stream
->LogStreamError(ERR_SPDY_PROTOCOL_ERROR
, error
);
2099 ResetStreamIterator(it
, RST_STREAM_PROTOCOL_ERROR
, error
);
2103 stream
->OnDataReceived(buffer
.Pass());
2106 void SpdySession::OnSettings(bool clear_persisted
) {
2109 if (clear_persisted
)
2110 http_server_properties_
->ClearSpdySettings(host_port_pair());
2112 if (net_log_
.IsLogging()) {
2114 NetLog::TYPE_SPDY_SESSION_RECV_SETTINGS
,
2115 base::Bind(&NetLogSpdySettingsCallback
, host_port_pair(),
2119 if (GetProtocolVersion() >= SPDY4
) {
2120 // Send an acknowledgment of the setting.
2121 SpdySettingsIR settings_ir
;
2122 settings_ir
.set_is_ack(true);
2123 EnqueueSessionWrite(
2126 scoped_ptr
<SpdyFrame
>(
2127 buffered_spdy_framer_
->SerializeFrame(settings_ir
)));
2131 void SpdySession::OnSetting(SpdySettingsIds id
,
2136 HandleSetting(id
, value
);
2137 http_server_properties_
->SetSpdySetting(
2140 static_cast<SpdySettingsFlags
>(flags
),
2142 received_settings_
= true;
2145 const SpdyMajorVersion protocol_version
= GetProtocolVersion();
2146 net_log_
.AddEvent(NetLog::TYPE_SPDY_SESSION_RECV_SETTING
,
2147 base::Bind(&NetLogSpdySettingCallback
,
2150 static_cast<SpdySettingsFlags
>(flags
),
2154 void SpdySession::OnSendCompressedFrame(
2155 SpdyStreamId stream_id
,
2159 if (type
!= SYN_STREAM
&& type
!= HEADERS
)
2162 DCHECK(buffered_spdy_framer_
.get());
2163 size_t compressed_len
=
2164 frame_len
- buffered_spdy_framer_
->GetSynStreamMinimumSize();
2167 // Make sure we avoid early decimal truncation.
2168 int compression_pct
= 100 - (100 * compressed_len
) / payload_len
;
2169 UMA_HISTOGRAM_PERCENTAGE("Net.SpdySynStreamCompressionPercentage",
2174 void SpdySession::OnReceiveCompressedFrame(
2175 SpdyStreamId stream_id
,
2178 last_compressed_frame_len_
= frame_len
;
2181 int SpdySession::OnInitialResponseHeadersReceived(
2182 const SpdyHeaderBlock
& response_headers
,
2183 base::Time response_time
,
2184 base::TimeTicks recv_first_byte_time
,
2185 SpdyStream
* stream
) {
2187 SpdyStreamId stream_id
= stream
->stream_id();
2189 if (stream
->type() == SPDY_PUSH_STREAM
) {
2190 DCHECK(stream
->IsReservedRemote());
2191 if (max_concurrent_pushed_streams_
&&
2192 num_active_pushed_streams_
>= max_concurrent_pushed_streams_
) {
2193 ResetStream(stream_id
,
2194 RST_STREAM_REFUSED_STREAM
,
2195 "Stream concurrency limit reached.");
2196 return STATUS_CODE_REFUSED_STREAM
;
2200 if (stream
->type() == SPDY_PUSH_STREAM
) {
2201 // Will be balanced in DeleteStream.
2202 num_active_pushed_streams_
++;
2205 // May invalidate |stream|.
2206 int rv
= stream
->OnInitialResponseHeadersReceived(
2207 response_headers
, response_time
, recv_first_byte_time
);
2209 DCHECK_NE(rv
, ERR_IO_PENDING
);
2210 DCHECK(active_streams_
.find(stream_id
) == active_streams_
.end());
2216 void SpdySession::OnSynStream(SpdyStreamId stream_id
,
2217 SpdyStreamId associated_stream_id
,
2218 SpdyPriority priority
,
2220 bool unidirectional
,
2221 const SpdyHeaderBlock
& headers
) {
2224 DCHECK_LE(GetProtocolVersion(), SPDY3
);
2226 base::Time response_time
= base::Time::Now();
2227 base::TimeTicks recv_first_byte_time
= time_func_();
2229 if (net_log_
.IsLogging()) {
2231 NetLog::TYPE_SPDY_SESSION_PUSHED_SYN_STREAM
,
2232 base::Bind(&NetLogSpdySynStreamReceivedCallback
,
2233 &headers
, fin
, unidirectional
, priority
,
2234 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 if (OnInitialResponseHeadersReceived(response_headers
,
2255 recv_first_byte_time
,
2256 active_it
->second
.stream
) != OK
)
2259 base::StatsCounter
push_requests("spdy.pushed_streams");
2260 push_requests
.Increment();
2263 void SpdySession::DeleteExpiredPushedStreams() {
2264 if (unclaimed_pushed_streams_
.empty())
2267 // Check that adequate time has elapsed since the last sweep.
2268 if (time_func_() < next_unclaimed_push_stream_sweep_time_
)
2271 // Gather old streams to delete.
2272 base::TimeTicks minimum_freshness
= time_func_() -
2273 base::TimeDelta::FromSeconds(kMinPushedStreamLifetimeSeconds
);
2274 std::vector
<SpdyStreamId
> streams_to_close
;
2275 for (PushedStreamMap::iterator it
= unclaimed_pushed_streams_
.begin();
2276 it
!= unclaimed_pushed_streams_
.end(); ++it
) {
2277 if (minimum_freshness
> it
->second
.creation_time
)
2278 streams_to_close
.push_back(it
->second
.stream_id
);
2281 for (std::vector
<SpdyStreamId
>::const_iterator to_close_it
=
2282 streams_to_close
.begin();
2283 to_close_it
!= streams_to_close
.end(); ++to_close_it
) {
2284 ActiveStreamMap::iterator active_it
= active_streams_
.find(*to_close_it
);
2285 if (active_it
== active_streams_
.end())
2288 LogAbandonedActiveStream(active_it
, ERR_INVALID_SPDY_STREAM
);
2289 // CloseActiveStreamIterator() will remove the stream from
2290 // |unclaimed_pushed_streams_|.
2291 ResetStreamIterator(
2292 active_it
, RST_STREAM_REFUSED_STREAM
, "Stream not claimed.");
2295 next_unclaimed_push_stream_sweep_time_
= time_func_() +
2296 base::TimeDelta::FromSeconds(kMinPushedStreamLifetimeSeconds
);
2299 void SpdySession::OnSynReply(SpdyStreamId stream_id
,
2301 const SpdyHeaderBlock
& headers
) {
2304 base::Time response_time
= base::Time::Now();
2305 base::TimeTicks recv_first_byte_time
= time_func_();
2307 if (net_log().IsLogging()) {
2309 NetLog::TYPE_SPDY_SESSION_SYN_REPLY
,
2310 base::Bind(&NetLogSpdySynReplyOrHeadersReceivedCallback
,
2311 &headers
, fin
, stream_id
));
2314 ActiveStreamMap::iterator it
= active_streams_
.find(stream_id
);
2315 if (it
== active_streams_
.end()) {
2316 // NOTE: it may just be that the stream was cancelled.
2320 SpdyStream
* stream
= it
->second
.stream
;
2321 CHECK_EQ(stream
->stream_id(), stream_id
);
2323 stream
->IncrementRawReceivedBytes(last_compressed_frame_len_
);
2324 last_compressed_frame_len_
= 0;
2326 if (GetProtocolVersion() >= SPDY4
) {
2327 const std::string
& error
=
2328 "SPDY4 wasn't expecting SYN_REPLY.";
2329 stream
->LogStreamError(ERR_SPDY_PROTOCOL_ERROR
, error
);
2330 ResetStreamIterator(it
, RST_STREAM_PROTOCOL_ERROR
, error
);
2333 if (!it
->second
.waiting_for_syn_reply
) {
2334 const std::string
& error
=
2335 "Received duplicate SYN_REPLY for stream.";
2336 stream
->LogStreamError(ERR_SPDY_PROTOCOL_ERROR
, error
);
2337 ResetStreamIterator(it
, RST_STREAM_PROTOCOL_ERROR
, error
);
2340 it
->second
.waiting_for_syn_reply
= false;
2342 ignore_result(OnInitialResponseHeadersReceived(
2343 headers
, response_time
, recv_first_byte_time
, stream
));
2346 void SpdySession::OnHeaders(SpdyStreamId stream_id
,
2348 SpdyPriority priority
,
2350 const SpdyHeaderBlock
& headers
) {
2353 if (net_log().IsLogging()) {
2355 NetLog::TYPE_SPDY_SESSION_RECV_HEADERS
,
2356 base::Bind(&NetLogSpdySynReplyOrHeadersReceivedCallback
,
2357 &headers
, fin
, stream_id
));
2360 ActiveStreamMap::iterator it
= active_streams_
.find(stream_id
);
2361 if (it
== active_streams_
.end()) {
2362 // NOTE: it may just be that the stream was cancelled.
2363 LOG(WARNING
) << "Received HEADERS for invalid stream " << stream_id
;
2367 SpdyStream
* stream
= it
->second
.stream
;
2368 CHECK_EQ(stream
->stream_id(), stream_id
);
2370 stream
->IncrementRawReceivedBytes(last_compressed_frame_len_
);
2371 last_compressed_frame_len_
= 0;
2373 base::Time response_time
= base::Time::Now();
2374 base::TimeTicks recv_first_byte_time
= time_func_();
2376 if (it
->second
.waiting_for_syn_reply
) {
2377 if (GetProtocolVersion() < SPDY4
) {
2378 const std::string
& error
=
2379 "Was expecting SYN_REPLY, not HEADERS.";
2380 stream
->LogStreamError(ERR_SPDY_PROTOCOL_ERROR
, error
);
2381 ResetStreamIterator(it
, RST_STREAM_PROTOCOL_ERROR
, error
);
2385 it
->second
.waiting_for_syn_reply
= false;
2386 ignore_result(OnInitialResponseHeadersReceived(
2387 headers
, response_time
, recv_first_byte_time
, stream
));
2388 } else if (it
->second
.stream
->IsReservedRemote()) {
2389 ignore_result(OnInitialResponseHeadersReceived(
2390 headers
, response_time
, recv_first_byte_time
, stream
));
2392 int rv
= stream
->OnAdditionalResponseHeadersReceived(headers
);
2394 DCHECK_NE(rv
, ERR_IO_PENDING
);
2395 DCHECK(active_streams_
.find(stream_id
) == active_streams_
.end());
2400 bool SpdySession::OnUnknownFrame(SpdyStreamId stream_id
, int frame_type
) {
2401 // Validate stream id.
2402 // Was the frame sent on a stream id that has not been used in this session?
2403 if (stream_id
% 2 == 1 && stream_id
> stream_hi_water_mark_
)
2406 if (stream_id
% 2 == 0 && stream_id
> last_accepted_push_stream_id_
)
2412 void SpdySession::OnRstStream(SpdyStreamId stream_id
,
2413 SpdyRstStreamStatus status
) {
2416 std::string description
;
2418 NetLog::TYPE_SPDY_SESSION_RST_STREAM
,
2419 base::Bind(&NetLogSpdyRstCallback
,
2420 stream_id
, status
, &description
));
2422 ActiveStreamMap::iterator it
= active_streams_
.find(stream_id
);
2423 if (it
== active_streams_
.end()) {
2424 // NOTE: it may just be that the stream was cancelled.
2425 LOG(WARNING
) << "Received RST for invalid stream" << stream_id
;
2429 CHECK_EQ(it
->second
.stream
->stream_id(), stream_id
);
2432 it
->second
.stream
->OnDataReceived(scoped_ptr
<SpdyBuffer
>());
2433 } else if (status
== RST_STREAM_REFUSED_STREAM
) {
2434 CloseActiveStreamIterator(it
, ERR_SPDY_SERVER_REFUSED_STREAM
);
2436 RecordProtocolErrorHistogram(
2437 PROTOCOL_ERROR_RST_STREAM_FOR_NON_ACTIVE_STREAM
);
2438 it
->second
.stream
->LogStreamError(
2439 ERR_SPDY_PROTOCOL_ERROR
,
2440 base::StringPrintf("SPDY stream closed with status: %d", status
));
2441 // TODO(mbelshe): Map from Spdy-protocol errors to something sensical.
2442 // For now, it doesn't matter much - it is a protocol error.
2443 CloseActiveStreamIterator(it
, ERR_SPDY_PROTOCOL_ERROR
);
2447 void SpdySession::OnGoAway(SpdyStreamId last_accepted_stream_id
,
2448 SpdyGoAwayStatus status
) {
2451 // TODO(jgraettinger): UMA histogram on |status|.
2453 net_log_
.AddEvent(NetLog::TYPE_SPDY_SESSION_GOAWAY
,
2454 base::Bind(&NetLogSpdyGoAwayCallback
,
2455 last_accepted_stream_id
,
2456 active_streams_
.size(),
2457 unclaimed_pushed_streams_
.size(),
2460 StartGoingAway(last_accepted_stream_id
, ERR_ABORTED
);
2461 // This is to handle the case when we already don't have any active
2462 // streams (i.e., StartGoingAway() did nothing). Otherwise, we have
2463 // active streams and so the last one being closed will finish the
2464 // going away process (see DeleteStream()).
2465 MaybeFinishGoingAway();
2468 void SpdySession::OnPing(SpdyPingId unique_id
, bool is_ack
) {
2472 NetLog::TYPE_SPDY_SESSION_PING
,
2473 base::Bind(&NetLogSpdyPingCallback
, unique_id
, is_ack
, "received"));
2475 // Send response to a PING from server.
2476 if ((protocol_
>= kProtoSPDY4MinimumVersion
&& !is_ack
) ||
2477 (protocol_
< kProtoSPDY4MinimumVersion
&& unique_id
% 2 == 0)) {
2478 WritePingFrame(unique_id
, true);
2483 if (pings_in_flight_
< 0) {
2484 RecordProtocolErrorHistogram(PROTOCOL_ERROR_UNEXPECTED_PING
);
2485 DoDrainSession(ERR_SPDY_PROTOCOL_ERROR
, "pings_in_flight_ is < 0.");
2486 pings_in_flight_
= 0;
2490 if (pings_in_flight_
> 0)
2493 // We will record RTT in histogram when there are no more client sent
2494 // pings_in_flight_.
2495 RecordPingRTTHistogram(time_func_() - last_ping_sent_time_
);
2498 void SpdySession::OnWindowUpdate(SpdyStreamId stream_id
,
2499 uint32 delta_window_size
) {
2502 DCHECK_LE(delta_window_size
, static_cast<uint32
>(kint32max
));
2504 NetLog::TYPE_SPDY_SESSION_RECEIVED_WINDOW_UPDATE_FRAME
,
2505 base::Bind(&NetLogSpdyWindowUpdateFrameCallback
,
2506 stream_id
, delta_window_size
));
2508 if (stream_id
== kSessionFlowControlStreamId
) {
2509 // WINDOW_UPDATE for the session.
2510 if (flow_control_state_
< FLOW_CONTROL_STREAM_AND_SESSION
) {
2511 LOG(WARNING
) << "Received WINDOW_UPDATE for session when "
2512 << "session flow control is not turned on";
2513 // TODO(akalin): Record an error and close the session.
2517 if (delta_window_size
< 1u) {
2518 RecordProtocolErrorHistogram(PROTOCOL_ERROR_INVALID_WINDOW_UPDATE_SIZE
);
2520 ERR_SPDY_PROTOCOL_ERROR
,
2521 "Received WINDOW_UPDATE with an invalid delta_window_size " +
2522 base::UintToString(delta_window_size
));
2526 IncreaseSendWindowSize(static_cast<int32
>(delta_window_size
));
2528 // WINDOW_UPDATE for a stream.
2529 if (flow_control_state_
< FLOW_CONTROL_STREAM
) {
2530 // TODO(akalin): Record an error and close the session.
2531 LOG(WARNING
) << "Received WINDOW_UPDATE for stream " << stream_id
2532 << " when flow control is not turned on";
2536 ActiveStreamMap::iterator it
= active_streams_
.find(stream_id
);
2538 if (it
== active_streams_
.end()) {
2539 // NOTE: it may just be that the stream was cancelled.
2540 LOG(WARNING
) << "Received WINDOW_UPDATE for invalid stream " << stream_id
;
2544 SpdyStream
* stream
= it
->second
.stream
;
2545 CHECK_EQ(stream
->stream_id(), stream_id
);
2547 if (delta_window_size
< 1u) {
2548 ResetStreamIterator(it
,
2549 RST_STREAM_FLOW_CONTROL_ERROR
,
2551 "Received WINDOW_UPDATE with an invalid "
2552 "delta_window_size %ud", delta_window_size
));
2556 CHECK_EQ(it
->second
.stream
->stream_id(), stream_id
);
2557 it
->second
.stream
->IncreaseSendWindowSize(
2558 static_cast<int32
>(delta_window_size
));
2562 bool SpdySession::TryCreatePushStream(SpdyStreamId stream_id
,
2563 SpdyStreamId associated_stream_id
,
2564 SpdyPriority priority
,
2565 const SpdyHeaderBlock
& headers
) {
2566 // Server-initiated streams should have even sequence numbers.
2567 if ((stream_id
& 0x1) != 0) {
2568 LOG(WARNING
) << "Received invalid push stream id " << stream_id
;
2569 if (GetProtocolVersion() > SPDY2
)
2570 CloseSessionOnError(ERR_SPDY_PROTOCOL_ERROR
, "Odd push stream id.");
2574 if (GetProtocolVersion() > SPDY2
) {
2575 if (stream_id
<= last_accepted_push_stream_id_
) {
2576 LOG(WARNING
) << "Received push stream id lesser or equal to the last "
2577 << "accepted before " << stream_id
;
2578 CloseSessionOnError(
2579 ERR_SPDY_PROTOCOL_ERROR
,
2580 "New push stream id must be greater than the last accepted.");
2585 if (IsStreamActive(stream_id
)) {
2586 // For SPDY3 and higher we should not get here, we'll start going away
2587 // earlier on |last_seen_push_stream_id_| check.
2588 CHECK_GT(SPDY3
, GetProtocolVersion());
2589 LOG(WARNING
) << "Received push for active stream " << stream_id
;
2593 last_accepted_push_stream_id_
= stream_id
;
2595 RequestPriority request_priority
=
2596 ConvertSpdyPriorityToRequestPriority(priority
, GetProtocolVersion());
2598 if (availability_state_
== STATE_GOING_AWAY
) {
2599 // TODO(akalin): This behavior isn't in the SPDY spec, although it
2600 // probably should be.
2601 EnqueueResetStreamFrame(stream_id
,
2603 RST_STREAM_REFUSED_STREAM
,
2604 "push stream request received when going away");
2608 if (associated_stream_id
== 0) {
2609 // In SPDY4 0 stream id in PUSH_PROMISE frame leads to framer error and
2610 // session going away. We should never get here.
2611 CHECK_GT(SPDY4
, GetProtocolVersion());
2612 std::string description
= base::StringPrintf(
2613 "Received invalid associated stream id %d for pushed stream %d",
2614 associated_stream_id
,
2616 EnqueueResetStreamFrame(
2617 stream_id
, request_priority
, RST_STREAM_REFUSED_STREAM
, description
);
2621 streams_pushed_count_
++;
2623 // TODO(mbelshe): DCHECK that this is a GET method?
2625 // Verify that the response had a URL for us.
2626 GURL gurl
= GetUrlFromHeaderBlock(headers
, GetProtocolVersion(), true);
2627 if (!gurl
.is_valid()) {
2628 EnqueueResetStreamFrame(stream_id
,
2630 RST_STREAM_PROTOCOL_ERROR
,
2631 "Pushed stream url was invalid: " + gurl
.spec());
2635 // Verify we have a valid stream association.
2636 ActiveStreamMap::iterator associated_it
=
2637 active_streams_
.find(associated_stream_id
);
2638 if (associated_it
== active_streams_
.end()) {
2639 EnqueueResetStreamFrame(
2642 RST_STREAM_INVALID_STREAM
,
2643 base::StringPrintf("Received push for inactive associated stream %d",
2644 associated_stream_id
));
2648 // Check that the pushed stream advertises the same origin as its associated
2649 // stream. Bypass this check if and only if this session is with a SPDY proxy
2650 // that is trusted explicitly via the --trusted-spdy-proxy switch.
2651 if (trusted_spdy_proxy_
.Equals(host_port_pair())) {
2652 // Disallow pushing of HTTPS content.
2653 if (gurl
.SchemeIs("https")) {
2654 EnqueueResetStreamFrame(
2657 RST_STREAM_REFUSED_STREAM
,
2658 base::StringPrintf("Rejected push of Cross Origin HTTPS content %d",
2659 associated_stream_id
));
2662 GURL
associated_url(associated_it
->second
.stream
->GetUrlFromHeaders());
2663 if (associated_url
.GetOrigin() != gurl
.GetOrigin()) {
2664 EnqueueResetStreamFrame(
2667 RST_STREAM_REFUSED_STREAM
,
2668 base::StringPrintf("Rejected Cross Origin Push Stream %d",
2669 associated_stream_id
));
2674 // There should not be an existing pushed stream with the same path.
2675 PushedStreamMap::iterator pushed_it
=
2676 unclaimed_pushed_streams_
.lower_bound(gurl
);
2677 if (pushed_it
!= unclaimed_pushed_streams_
.end() &&
2678 pushed_it
->first
== gurl
) {
2679 EnqueueResetStreamFrame(
2682 RST_STREAM_PROTOCOL_ERROR
,
2683 "Received duplicate pushed stream with url: " + gurl
.spec());
2687 scoped_ptr
<SpdyStream
> stream(new SpdyStream(SPDY_PUSH_STREAM
,
2691 stream_initial_send_window_size_
,
2692 stream_initial_recv_window_size_
,
2694 stream
->set_stream_id(stream_id
);
2696 // In spdy4/http2 PUSH_PROMISE arrives on associated stream.
2697 if (associated_it
!= active_streams_
.end() && GetProtocolVersion() >= SPDY4
) {
2698 associated_it
->second
.stream
->IncrementRawReceivedBytes(
2699 last_compressed_frame_len_
);
2701 stream
->IncrementRawReceivedBytes(last_compressed_frame_len_
);
2704 last_compressed_frame_len_
= 0;
2706 DeleteExpiredPushedStreams();
2707 PushedStreamMap::iterator inserted_pushed_it
=
2708 unclaimed_pushed_streams_
.insert(
2710 std::make_pair(gurl
, PushedStreamInfo(stream_id
, time_func_())));
2711 DCHECK(inserted_pushed_it
!= pushed_it
);
2713 InsertActivatedStream(stream
.Pass());
2715 ActiveStreamMap::iterator active_it
= active_streams_
.find(stream_id
);
2716 if (active_it
== active_streams_
.end()) {
2721 active_it
->second
.stream
->OnPushPromiseHeadersReceived(headers
);
2722 DCHECK(active_it
->second
.stream
->IsReservedRemote());
2723 num_pushed_streams_
++;
2727 void SpdySession::OnPushPromise(SpdyStreamId stream_id
,
2728 SpdyStreamId promised_stream_id
,
2729 const SpdyHeaderBlock
& headers
) {
2732 if (net_log_
.IsLogging()) {
2733 net_log_
.AddEvent(NetLog::TYPE_SPDY_SESSION_RECV_PUSH_PROMISE
,
2734 base::Bind(&NetLogSpdyPushPromiseReceivedCallback
,
2737 promised_stream_id
));
2740 // Any priority will do.
2741 // TODO(baranovich): pass parent stream id priority?
2742 if (!TryCreatePushStream(promised_stream_id
, stream_id
, 0, headers
))
2745 base::StatsCounter
push_requests("spdy.pushed_streams");
2746 push_requests
.Increment();
2749 void SpdySession::SendStreamWindowUpdate(SpdyStreamId stream_id
,
2750 uint32 delta_window_size
) {
2751 CHECK_GE(flow_control_state_
, FLOW_CONTROL_STREAM
);
2752 ActiveStreamMap::const_iterator it
= active_streams_
.find(stream_id
);
2753 CHECK(it
!= active_streams_
.end());
2754 CHECK_EQ(it
->second
.stream
->stream_id(), stream_id
);
2755 SendWindowUpdateFrame(
2756 stream_id
, delta_window_size
, it
->second
.stream
->priority());
2759 void SpdySession::SendInitialData() {
2760 DCHECK(enable_sending_initial_data_
);
2762 if (send_connection_header_prefix_
) {
2763 DCHECK_GE(protocol_
, kProtoSPDY4MinimumVersion
);
2764 DCHECK_LE(protocol_
, kProtoSPDY4MaximumVersion
);
2765 scoped_ptr
<SpdyFrame
> connection_header_prefix_frame(
2766 new SpdyFrame(const_cast<char*>(kHttp2ConnectionHeaderPrefix
),
2767 kHttp2ConnectionHeaderPrefixSize
,
2768 false /* take_ownership */));
2769 // Count the prefix as part of the subsequent SETTINGS frame.
2770 EnqueueSessionWrite(HIGHEST
, SETTINGS
,
2771 connection_header_prefix_frame
.Pass());
2774 // First, notify the server about the settings they should use when
2775 // communicating with us.
2776 SettingsMap settings_map
;
2777 // Create a new settings frame notifying the server of our
2778 // max concurrent streams and initial window size.
2779 settings_map
[SETTINGS_MAX_CONCURRENT_STREAMS
] =
2780 SettingsFlagsAndValue(SETTINGS_FLAG_NONE
, kMaxConcurrentPushedStreams
);
2781 if (flow_control_state_
>= FLOW_CONTROL_STREAM
&&
2782 stream_initial_recv_window_size_
!= GetInitialWindowSize(protocol_
)) {
2783 settings_map
[SETTINGS_INITIAL_WINDOW_SIZE
] =
2784 SettingsFlagsAndValue(SETTINGS_FLAG_NONE
,
2785 stream_initial_recv_window_size_
);
2787 SendSettings(settings_map
);
2789 // Next, notify the server about our initial recv window size.
2790 if (flow_control_state_
== FLOW_CONTROL_STREAM_AND_SESSION
) {
2791 // Bump up the receive window size to the real initial value. This
2792 // has to go here since the WINDOW_UPDATE frame sent by
2793 // IncreaseRecvWindowSize() call uses |buffered_spdy_framer_|.
2794 DCHECK_GT(kDefaultInitialRecvWindowSize
, session_recv_window_size_
);
2795 // This condition implies that |kDefaultInitialRecvWindowSize| -
2796 // |session_recv_window_size_| doesn't overflow.
2797 DCHECK_GT(session_recv_window_size_
, 0);
2798 IncreaseRecvWindowSize(
2799 kDefaultInitialRecvWindowSize
- session_recv_window_size_
);
2802 if (protocol_
<= kProtoSPDY31
) {
2803 // Finally, notify the server about the settings they have
2804 // previously told us to use when communicating with them (after
2806 const SettingsMap
& server_settings_map
=
2807 http_server_properties_
->GetSpdySettings(host_port_pair());
2808 if (server_settings_map
.empty())
2811 SettingsMap::const_iterator it
=
2812 server_settings_map
.find(SETTINGS_CURRENT_CWND
);
2813 uint32 cwnd
= (it
!= server_settings_map
.end()) ? it
->second
.second
: 0;
2814 UMA_HISTOGRAM_CUSTOM_COUNTS("Net.SpdySettingsCwndSent", cwnd
, 1, 200, 100);
2816 for (SettingsMap::const_iterator it
= server_settings_map
.begin();
2817 it
!= server_settings_map
.end(); ++it
) {
2818 const SpdySettingsIds new_id
= it
->first
;
2819 const uint32 new_val
= it
->second
.second
;
2820 HandleSetting(new_id
, new_val
);
2823 SendSettings(server_settings_map
);
2828 void SpdySession::SendSettings(const SettingsMap
& settings
) {
2829 const SpdyMajorVersion protocol_version
= GetProtocolVersion();
2831 NetLog::TYPE_SPDY_SESSION_SEND_SETTINGS
,
2832 base::Bind(&NetLogSpdySendSettingsCallback
, &settings
, protocol_version
));
2833 // Create the SETTINGS frame and send it.
2834 DCHECK(buffered_spdy_framer_
.get());
2835 scoped_ptr
<SpdyFrame
> settings_frame(
2836 buffered_spdy_framer_
->CreateSettings(settings
));
2837 sent_settings_
= true;
2838 EnqueueSessionWrite(HIGHEST
, SETTINGS
, settings_frame
.Pass());
2841 void SpdySession::HandleSetting(uint32 id
, uint32 value
) {
2843 case SETTINGS_MAX_CONCURRENT_STREAMS
:
2844 max_concurrent_streams_
= std::min(static_cast<size_t>(value
),
2845 kMaxConcurrentStreamLimit
);
2846 ProcessPendingStreamRequests();
2848 case SETTINGS_INITIAL_WINDOW_SIZE
: {
2849 if (flow_control_state_
< FLOW_CONTROL_STREAM
) {
2851 NetLog::TYPE_SPDY_SESSION_INITIAL_WINDOW_SIZE_NO_FLOW_CONTROL
);
2855 if (value
> static_cast<uint32
>(kint32max
)) {
2857 NetLog::TYPE_SPDY_SESSION_INITIAL_WINDOW_SIZE_OUT_OF_RANGE
,
2858 NetLog::IntegerCallback("initial_window_size", value
));
2862 // SETTINGS_INITIAL_WINDOW_SIZE updates initial_send_window_size_ only.
2863 int32 delta_window_size
=
2864 static_cast<int32
>(value
) - stream_initial_send_window_size_
;
2865 stream_initial_send_window_size_
= static_cast<int32
>(value
);
2866 UpdateStreamsSendWindowSize(delta_window_size
);
2868 NetLog::TYPE_SPDY_SESSION_UPDATE_STREAMS_SEND_WINDOW_SIZE
,
2869 NetLog::IntegerCallback("delta_window_size", delta_window_size
));
2875 void SpdySession::UpdateStreamsSendWindowSize(int32 delta_window_size
) {
2876 DCHECK_GE(flow_control_state_
, FLOW_CONTROL_STREAM
);
2877 for (ActiveStreamMap::iterator it
= active_streams_
.begin();
2878 it
!= active_streams_
.end(); ++it
) {
2879 it
->second
.stream
->AdjustSendWindowSize(delta_window_size
);
2882 for (CreatedStreamSet::const_iterator it
= created_streams_
.begin();
2883 it
!= created_streams_
.end(); it
++) {
2884 (*it
)->AdjustSendWindowSize(delta_window_size
);
2888 void SpdySession::SendPrefacePingIfNoneInFlight() {
2889 if (pings_in_flight_
|| !enable_ping_based_connection_checking_
)
2892 base::TimeTicks now
= time_func_();
2893 // If there is no activity in the session, then send a preface-PING.
2894 if ((now
- last_activity_time_
) > connection_at_risk_of_loss_time_
)
2898 void SpdySession::SendPrefacePing() {
2899 WritePingFrame(next_ping_id_
, false);
2902 void SpdySession::SendWindowUpdateFrame(SpdyStreamId stream_id
,
2903 uint32 delta_window_size
,
2904 RequestPriority priority
) {
2905 CHECK_GE(flow_control_state_
, FLOW_CONTROL_STREAM
);
2906 ActiveStreamMap::const_iterator it
= active_streams_
.find(stream_id
);
2907 if (it
!= active_streams_
.end()) {
2908 CHECK_EQ(it
->second
.stream
->stream_id(), stream_id
);
2910 CHECK_EQ(flow_control_state_
, FLOW_CONTROL_STREAM_AND_SESSION
);
2911 CHECK_EQ(stream_id
, kSessionFlowControlStreamId
);
2915 NetLog::TYPE_SPDY_SESSION_SENT_WINDOW_UPDATE_FRAME
,
2916 base::Bind(&NetLogSpdyWindowUpdateFrameCallback
,
2917 stream_id
, delta_window_size
));
2919 DCHECK(buffered_spdy_framer_
.get());
2920 scoped_ptr
<SpdyFrame
> window_update_frame(
2921 buffered_spdy_framer_
->CreateWindowUpdate(stream_id
, delta_window_size
));
2922 EnqueueSessionWrite(priority
, WINDOW_UPDATE
, window_update_frame
.Pass());
2925 void SpdySession::WritePingFrame(SpdyPingId unique_id
, bool is_ack
) {
2926 DCHECK(buffered_spdy_framer_
.get());
2927 scoped_ptr
<SpdyFrame
> ping_frame(
2928 buffered_spdy_framer_
->CreatePingFrame(unique_id
, is_ack
));
2929 EnqueueSessionWrite(HIGHEST
, PING
, ping_frame
.Pass());
2931 if (net_log().IsLogging()) {
2933 NetLog::TYPE_SPDY_SESSION_PING
,
2934 base::Bind(&NetLogSpdyPingCallback
, unique_id
, is_ack
, "sent"));
2939 PlanToCheckPingStatus();
2940 last_ping_sent_time_
= time_func_();
2944 void SpdySession::PlanToCheckPingStatus() {
2945 if (check_ping_status_pending_
)
2948 check_ping_status_pending_
= true;
2949 base::MessageLoop::current()->PostDelayedTask(
2951 base::Bind(&SpdySession::CheckPingStatus
, weak_factory_
.GetWeakPtr(),
2952 time_func_()), hung_interval_
);
2955 void SpdySession::CheckPingStatus(base::TimeTicks last_check_time
) {
2956 CHECK(!in_io_loop_
);
2958 // Check if we got a response back for all PINGs we had sent.
2959 if (pings_in_flight_
== 0) {
2960 check_ping_status_pending_
= false;
2964 DCHECK(check_ping_status_pending_
);
2966 base::TimeTicks now
= time_func_();
2967 base::TimeDelta delay
= hung_interval_
- (now
- last_activity_time_
);
2969 if (delay
.InMilliseconds() < 0 || last_activity_time_
< last_check_time
) {
2970 // Track all failed PING messages in a separate bucket.
2971 RecordPingRTTHistogram(base::TimeDelta::Max());
2972 DoDrainSession(ERR_SPDY_PING_FAILED
, "Failed ping.");
2976 // Check the status of connection after a delay.
2977 base::MessageLoop::current()->PostDelayedTask(
2979 base::Bind(&SpdySession::CheckPingStatus
, weak_factory_
.GetWeakPtr(),
2984 void SpdySession::RecordPingRTTHistogram(base::TimeDelta duration
) {
2985 UMA_HISTOGRAM_TIMES("Net.SpdyPing.RTT", duration
);
2988 void SpdySession::RecordProtocolErrorHistogram(
2989 SpdyProtocolErrorDetails details
) {
2990 UMA_HISTOGRAM_ENUMERATION("Net.SpdySessionErrorDetails2", details
,
2991 NUM_SPDY_PROTOCOL_ERROR_DETAILS
);
2992 if (EndsWith(host_port_pair().host(), "google.com", false)) {
2993 UMA_HISTOGRAM_ENUMERATION("Net.SpdySessionErrorDetails_Google2", details
,
2994 NUM_SPDY_PROTOCOL_ERROR_DETAILS
);
2998 void SpdySession::RecordHistograms() {
2999 UMA_HISTOGRAM_CUSTOM_COUNTS("Net.SpdyStreamsPerSession",
3000 streams_initiated_count_
,
3002 UMA_HISTOGRAM_CUSTOM_COUNTS("Net.SpdyStreamsPushedPerSession",
3003 streams_pushed_count_
,
3005 UMA_HISTOGRAM_CUSTOM_COUNTS("Net.SpdyStreamsPushedAndClaimedPerSession",
3006 streams_pushed_and_claimed_count_
,
3008 UMA_HISTOGRAM_CUSTOM_COUNTS("Net.SpdyStreamsAbandonedPerSession",
3009 streams_abandoned_count_
,
3011 UMA_HISTOGRAM_ENUMERATION("Net.SpdySettingsSent",
3012 sent_settings_
? 1 : 0, 2);
3013 UMA_HISTOGRAM_ENUMERATION("Net.SpdySettingsReceived",
3014 received_settings_
? 1 : 0, 2);
3015 UMA_HISTOGRAM_CUSTOM_COUNTS("Net.SpdyStreamStallsPerSession",
3018 UMA_HISTOGRAM_ENUMERATION("Net.SpdySessionsWithStalls",
3019 stalled_streams_
> 0 ? 1 : 0, 2);
3021 if (received_settings_
) {
3022 // Enumerate the saved settings, and set histograms for it.
3023 const SettingsMap
& settings_map
=
3024 http_server_properties_
->GetSpdySettings(host_port_pair());
3026 SettingsMap::const_iterator it
;
3027 for (it
= settings_map
.begin(); it
!= settings_map
.end(); ++it
) {
3028 const SpdySettingsIds id
= it
->first
;
3029 const uint32 val
= it
->second
.second
;
3031 case SETTINGS_CURRENT_CWND
:
3032 // Record several different histograms to see if cwnd converges
3033 // for larger volumes of data being sent.
3034 UMA_HISTOGRAM_CUSTOM_COUNTS("Net.SpdySettingsCwnd",
3036 if (total_bytes_received_
> 10 * 1024) {
3037 UMA_HISTOGRAM_CUSTOM_COUNTS("Net.SpdySettingsCwnd10K",
3039 if (total_bytes_received_
> 25 * 1024) {
3040 UMA_HISTOGRAM_CUSTOM_COUNTS("Net.SpdySettingsCwnd25K",
3042 if (total_bytes_received_
> 50 * 1024) {
3043 UMA_HISTOGRAM_CUSTOM_COUNTS("Net.SpdySettingsCwnd50K",
3045 if (total_bytes_received_
> 100 * 1024) {
3046 UMA_HISTOGRAM_CUSTOM_COUNTS("Net.SpdySettingsCwnd100K",
3053 case SETTINGS_ROUND_TRIP_TIME
:
3054 UMA_HISTOGRAM_CUSTOM_COUNTS("Net.SpdySettingsRTT",
3057 case SETTINGS_DOWNLOAD_RETRANS_RATE
:
3058 UMA_HISTOGRAM_CUSTOM_COUNTS("Net.SpdySettingsRetransRate",
3068 void SpdySession::CompleteStreamRequest(
3069 const base::WeakPtr
<SpdyStreamRequest
>& pending_request
) {
3070 // Abort if the request has already been cancelled.
3071 if (!pending_request
)
3074 base::WeakPtr
<SpdyStream
> stream
;
3075 int rv
= TryCreateStream(pending_request
, &stream
);
3079 pending_request
->OnRequestCompleteSuccess(stream
);
3084 if (rv
!= ERR_IO_PENDING
) {
3085 pending_request
->OnRequestCompleteFailure(rv
);
3089 SSLClientSocket
* SpdySession::GetSSLClientSocket() const {
3092 SSLClientSocket
* ssl_socket
=
3093 reinterpret_cast<SSLClientSocket
*>(connection_
->socket());
3098 void SpdySession::OnWriteBufferConsumed(
3099 size_t frame_payload_size
,
3100 size_t consume_size
,
3101 SpdyBuffer::ConsumeSource consume_source
) {
3102 // We can be called with |in_io_loop_| set if a write SpdyBuffer is
3103 // deleted (e.g., a stream is closed due to incoming data).
3105 DCHECK_EQ(flow_control_state_
, FLOW_CONTROL_STREAM_AND_SESSION
);
3107 if (consume_source
== SpdyBuffer::DISCARD
) {
3108 // If we're discarding a frame or part of it, increase the send
3109 // window by the number of discarded bytes. (Although if we're
3110 // discarding part of a frame, it's probably because of a write
3111 // error and we'll be tearing down the session soon.)
3112 size_t remaining_payload_bytes
= std::min(consume_size
, frame_payload_size
);
3113 DCHECK_GT(remaining_payload_bytes
, 0u);
3114 IncreaseSendWindowSize(static_cast<int32
>(remaining_payload_bytes
));
3116 // For consumed bytes, the send window is increased when we receive
3117 // a WINDOW_UPDATE frame.
3120 void SpdySession::IncreaseSendWindowSize(int32 delta_window_size
) {
3121 // We can be called with |in_io_loop_| set if a SpdyBuffer is
3122 // deleted (e.g., a stream is closed due to incoming data).
3124 DCHECK_EQ(flow_control_state_
, FLOW_CONTROL_STREAM_AND_SESSION
);
3125 DCHECK_GE(delta_window_size
, 1);
3127 // Check for overflow.
3128 int32 max_delta_window_size
= kint32max
- session_send_window_size_
;
3129 if (delta_window_size
> max_delta_window_size
) {
3130 RecordProtocolErrorHistogram(PROTOCOL_ERROR_INVALID_WINDOW_UPDATE_SIZE
);
3132 ERR_SPDY_PROTOCOL_ERROR
,
3133 "Received WINDOW_UPDATE [delta: " +
3134 base::IntToString(delta_window_size
) +
3135 "] for session overflows session_send_window_size_ [current: " +
3136 base::IntToString(session_send_window_size_
) + "]");
3140 session_send_window_size_
+= delta_window_size
;
3143 NetLog::TYPE_SPDY_SESSION_UPDATE_SEND_WINDOW
,
3144 base::Bind(&NetLogSpdySessionWindowUpdateCallback
,
3145 delta_window_size
, session_send_window_size_
));
3147 DCHECK(!IsSendStalled());
3148 ResumeSendStalledStreams();
3151 void SpdySession::DecreaseSendWindowSize(int32 delta_window_size
) {
3152 DCHECK_EQ(flow_control_state_
, FLOW_CONTROL_STREAM_AND_SESSION
);
3154 // We only call this method when sending a frame. Therefore,
3155 // |delta_window_size| should be within the valid frame size range.
3156 DCHECK_GE(delta_window_size
, 1);
3157 DCHECK_LE(delta_window_size
, kMaxSpdyFrameChunkSize
);
3159 // |send_window_size_| should have been at least |delta_window_size| for
3160 // this call to happen.
3161 DCHECK_GE(session_send_window_size_
, delta_window_size
);
3163 session_send_window_size_
-= delta_window_size
;
3166 NetLog::TYPE_SPDY_SESSION_UPDATE_SEND_WINDOW
,
3167 base::Bind(&NetLogSpdySessionWindowUpdateCallback
,
3168 -delta_window_size
, session_send_window_size_
));
3171 void SpdySession::OnReadBufferConsumed(
3172 size_t consume_size
,
3173 SpdyBuffer::ConsumeSource consume_source
) {
3174 // We can be called with |in_io_loop_| set if a read SpdyBuffer is
3175 // deleted (e.g., discarded by a SpdyReadQueue).
3177 DCHECK_EQ(flow_control_state_
, FLOW_CONTROL_STREAM_AND_SESSION
);
3178 DCHECK_GE(consume_size
, 1u);
3179 DCHECK_LE(consume_size
, static_cast<size_t>(kint32max
));
3181 IncreaseRecvWindowSize(static_cast<int32
>(consume_size
));
3184 void SpdySession::IncreaseRecvWindowSize(int32 delta_window_size
) {
3185 DCHECK_EQ(flow_control_state_
, FLOW_CONTROL_STREAM_AND_SESSION
);
3186 DCHECK_GE(session_unacked_recv_window_bytes_
, 0);
3187 DCHECK_GE(session_recv_window_size_
, session_unacked_recv_window_bytes_
);
3188 DCHECK_GE(delta_window_size
, 1);
3189 // Check for overflow.
3190 DCHECK_LE(delta_window_size
, kint32max
- session_recv_window_size_
);
3192 session_recv_window_size_
+= delta_window_size
;
3194 NetLog::TYPE_SPDY_STREAM_UPDATE_RECV_WINDOW
,
3195 base::Bind(&NetLogSpdySessionWindowUpdateCallback
,
3196 delta_window_size
, session_recv_window_size_
));
3198 session_unacked_recv_window_bytes_
+= delta_window_size
;
3199 if (session_unacked_recv_window_bytes_
>
3200 GetInitialWindowSize(protocol_
) / 2) {
3201 SendWindowUpdateFrame(kSessionFlowControlStreamId
,
3202 session_unacked_recv_window_bytes_
,
3204 session_unacked_recv_window_bytes_
= 0;
3208 void SpdySession::DecreaseRecvWindowSize(int32 delta_window_size
) {
3210 DCHECK_EQ(flow_control_state_
, FLOW_CONTROL_STREAM_AND_SESSION
);
3211 DCHECK_GE(delta_window_size
, 1);
3213 // Since we never decrease the initial receive window size,
3214 // |delta_window_size| should never cause |recv_window_size_| to go
3215 // negative. If we do, the receive window isn't being respected.
3216 if (delta_window_size
> session_recv_window_size_
) {
3217 RecordProtocolErrorHistogram(PROTOCOL_ERROR_RECEIVE_WINDOW_VIOLATION
);
3219 ERR_SPDY_FLOW_CONTROL_ERROR
,
3220 "delta_window_size is " + base::IntToString(delta_window_size
) +
3221 " in DecreaseRecvWindowSize, which is larger than the receive " +
3222 "window size of " + base::IntToString(session_recv_window_size_
));
3226 session_recv_window_size_
-= delta_window_size
;
3228 NetLog::TYPE_SPDY_SESSION_UPDATE_RECV_WINDOW
,
3229 base::Bind(&NetLogSpdySessionWindowUpdateCallback
,
3230 -delta_window_size
, session_recv_window_size_
));
3233 void SpdySession::QueueSendStalledStream(const SpdyStream
& stream
) {
3234 DCHECK(stream
.send_stalled_by_flow_control());
3235 RequestPriority priority
= stream
.priority();
3236 CHECK_GE(priority
, MINIMUM_PRIORITY
);
3237 CHECK_LE(priority
, MAXIMUM_PRIORITY
);
3238 stream_send_unstall_queue_
[priority
].push_back(stream
.stream_id());
3241 void SpdySession::ResumeSendStalledStreams() {
3242 DCHECK_EQ(flow_control_state_
, FLOW_CONTROL_STREAM_AND_SESSION
);
3244 // We don't have to worry about new streams being queued, since
3245 // doing so would cause IsSendStalled() to return true. But we do
3246 // have to worry about streams being closed, as well as ourselves
3249 while (!IsSendStalled()) {
3250 size_t old_size
= 0;
3252 old_size
= GetTotalSize(stream_send_unstall_queue_
);
3255 SpdyStreamId stream_id
= PopStreamToPossiblyResume();
3258 ActiveStreamMap::const_iterator it
= active_streams_
.find(stream_id
);
3259 // The stream may actually still be send-stalled after this (due
3260 // to its own send window) but that's okay -- it'll then be
3261 // resumed once its send window increases.
3262 if (it
!= active_streams_
.end())
3263 it
->second
.stream
->PossiblyResumeIfSendStalled();
3265 // The size should decrease unless we got send-stalled again.
3266 if (!IsSendStalled())
3267 DCHECK_LT(GetTotalSize(stream_send_unstall_queue_
), old_size
);
3271 SpdyStreamId
SpdySession::PopStreamToPossiblyResume() {
3272 for (int i
= MAXIMUM_PRIORITY
; i
>= MINIMUM_PRIORITY
; --i
) {
3273 std::deque
<SpdyStreamId
>* queue
= &stream_send_unstall_queue_
[i
];
3274 if (!queue
->empty()) {
3275 SpdyStreamId stream_id
= queue
->front();