Add ENABLE_MEDIA_ROUTER define to builds other than Android and iOS.
[chromium-blink-merge.git] / net / spdy / spdy_session.cc
blobdb791e466b125387d1b4eb028e13d0de20803628
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"
7 #include <algorithm>
8 #include <map>
10 #include "base/basictypes.h"
11 #include "base/bind.h"
12 #include "base/compiler_specific.h"
13 #include "base/logging.h"
14 #include "base/message_loop/message_loop.h"
15 #include "base/metrics/field_trial.h"
16 #include "base/metrics/histogram.h"
17 #include "base/metrics/sparse_histogram.h"
18 #include "base/profiler/scoped_tracker.h"
19 #include "base/stl_util.h"
20 #include "base/strings/string_number_conversions.h"
21 #include "base/strings/string_util.h"
22 #include "base/strings/stringprintf.h"
23 #include "base/strings/utf_string_conversions.h"
24 #include "base/time/time.h"
25 #include "base/values.h"
26 #include "crypto/ec_private_key.h"
27 #include "crypto/ec_signature_creator.h"
28 #include "net/base/connection_type_histograms.h"
29 #include "net/base/net_util.h"
30 #include "net/cert/asn1_util.h"
31 #include "net/cert/cert_verify_result.h"
32 #include "net/http/http_log_util.h"
33 #include "net/http/http_network_session.h"
34 #include "net/http/http_server_properties.h"
35 #include "net/http/http_util.h"
36 #include "net/http/transport_security_state.h"
37 #include "net/log/net_log.h"
38 #include "net/socket/ssl_client_socket.h"
39 #include "net/spdy/spdy_buffer_producer.h"
40 #include "net/spdy/spdy_frame_builder.h"
41 #include "net/spdy/spdy_http_utils.h"
42 #include "net/spdy/spdy_protocol.h"
43 #include "net/spdy/spdy_session_pool.h"
44 #include "net/spdy/spdy_stream.h"
45 #include "net/ssl/channel_id_service.h"
46 #include "net/ssl/ssl_cipher_suite_names.h"
47 #include "net/ssl/ssl_connection_status_flags.h"
49 namespace net {
51 namespace {
53 const int kReadBufferSize = 8 * 1024;
54 const int kDefaultConnectionAtRiskOfLossSeconds = 10;
55 const int kHungIntervalSeconds = 10;
57 // Minimum seconds that unclaimed pushed streams will be kept in memory.
58 const int kMinPushedStreamLifetimeSeconds = 300;
60 scoped_ptr<base::ListValue> SpdyHeaderBlockToListValue(
61 const SpdyHeaderBlock& headers,
62 net::NetLog::LogLevel log_level) {
63 scoped_ptr<base::ListValue> headers_list(new base::ListValue());
64 for (SpdyHeaderBlock::const_iterator it = headers.begin();
65 it != headers.end(); ++it) {
66 headers_list->AppendString(
67 it->first + ": " +
68 ElideHeaderValueForNetLog(log_level, it->first, it->second));
70 return headers_list.Pass();
73 base::Value* NetLogSpdySynStreamSentCallback(const SpdyHeaderBlock* headers,
74 bool fin,
75 bool unidirectional,
76 SpdyPriority spdy_priority,
77 SpdyStreamId stream_id,
78 NetLog::LogLevel log_level) {
79 base::DictionaryValue* dict = new base::DictionaryValue();
80 dict->Set("headers",
81 SpdyHeaderBlockToListValue(*headers, log_level).release());
82 dict->SetBoolean("fin", fin);
83 dict->SetBoolean("unidirectional", unidirectional);
84 dict->SetInteger("priority", static_cast<int>(spdy_priority));
85 dict->SetInteger("stream_id", stream_id);
86 return dict;
89 base::Value* NetLogSpdySynStreamReceivedCallback(
90 const SpdyHeaderBlock* headers,
91 bool fin,
92 bool unidirectional,
93 SpdyPriority spdy_priority,
94 SpdyStreamId stream_id,
95 SpdyStreamId associated_stream,
96 NetLog::LogLevel log_level) {
97 base::DictionaryValue* dict = new base::DictionaryValue();
98 dict->Set("headers",
99 SpdyHeaderBlockToListValue(*headers, log_level).release());
100 dict->SetBoolean("fin", fin);
101 dict->SetBoolean("unidirectional", unidirectional);
102 dict->SetInteger("priority", static_cast<int>(spdy_priority));
103 dict->SetInteger("stream_id", stream_id);
104 dict->SetInteger("associated_stream", associated_stream);
105 return dict;
108 base::Value* NetLogSpdySynReplyOrHeadersReceivedCallback(
109 const SpdyHeaderBlock* headers,
110 bool fin,
111 SpdyStreamId stream_id,
112 NetLog::LogLevel log_level) {
113 base::DictionaryValue* dict = new base::DictionaryValue();
114 dict->Set("headers",
115 SpdyHeaderBlockToListValue(*headers, log_level).release());
116 dict->SetBoolean("fin", fin);
117 dict->SetInteger("stream_id", stream_id);
118 return dict;
121 base::Value* NetLogSpdySessionCloseCallback(int net_error,
122 const std::string* description,
123 NetLog::LogLevel /* log_level */) {
124 base::DictionaryValue* dict = new base::DictionaryValue();
125 dict->SetInteger("net_error", net_error);
126 dict->SetString("description", *description);
127 return dict;
130 base::Value* NetLogSpdySessionCallback(const HostPortProxyPair* host_pair,
131 NetLog::LogLevel /* log_level */) {
132 base::DictionaryValue* dict = new base::DictionaryValue();
133 dict->SetString("host", host_pair->first.ToString());
134 dict->SetString("proxy", host_pair->second.ToPacString());
135 return dict;
138 base::Value* NetLogSpdyInitializedCallback(NetLog::Source source,
139 const NextProto protocol_version,
140 NetLog::LogLevel /* log_level */) {
141 base::DictionaryValue* dict = new base::DictionaryValue();
142 if (source.IsValid()) {
143 source.AddToEventParameters(dict);
145 dict->SetString("protocol",
146 SSLClientSocket::NextProtoToString(protocol_version));
147 return dict;
150 base::Value* NetLogSpdySettingsCallback(const HostPortPair& host_port_pair,
151 bool clear_persisted,
152 NetLog::LogLevel /* log_level */) {
153 base::DictionaryValue* dict = new base::DictionaryValue();
154 dict->SetString("host", host_port_pair.ToString());
155 dict->SetBoolean("clear_persisted", clear_persisted);
156 return dict;
159 base::Value* NetLogSpdySettingCallback(SpdySettingsIds id,
160 const SpdyMajorVersion protocol_version,
161 SpdySettingsFlags flags,
162 uint32 value,
163 NetLog::LogLevel /* log_level */) {
164 base::DictionaryValue* dict = new base::DictionaryValue();
165 dict->SetInteger("id",
166 SpdyConstants::SerializeSettingId(protocol_version, id));
167 dict->SetInteger("flags", flags);
168 dict->SetInteger("value", value);
169 return dict;
172 base::Value* NetLogSpdySendSettingsCallback(
173 const SettingsMap* settings,
174 const SpdyMajorVersion protocol_version,
175 NetLog::LogLevel /* log_level */) {
176 base::DictionaryValue* dict = new base::DictionaryValue();
177 base::ListValue* settings_list = new base::ListValue();
178 for (SettingsMap::const_iterator it = settings->begin();
179 it != settings->end(); ++it) {
180 const SpdySettingsIds id = it->first;
181 const SpdySettingsFlags flags = it->second.first;
182 const uint32 value = it->second.second;
183 settings_list->Append(new base::StringValue(base::StringPrintf(
184 "[id:%u flags:%u value:%u]",
185 SpdyConstants::SerializeSettingId(protocol_version, id),
186 flags,
187 value)));
189 dict->Set("settings", settings_list);
190 return dict;
193 base::Value* NetLogSpdyWindowUpdateFrameCallback(
194 SpdyStreamId stream_id,
195 uint32 delta,
196 NetLog::LogLevel /* log_level */) {
197 base::DictionaryValue* dict = new base::DictionaryValue();
198 dict->SetInteger("stream_id", static_cast<int>(stream_id));
199 dict->SetInteger("delta", delta);
200 return dict;
203 base::Value* NetLogSpdySessionWindowUpdateCallback(
204 int32 delta,
205 int32 window_size,
206 NetLog::LogLevel /* log_level */) {
207 base::DictionaryValue* dict = new base::DictionaryValue();
208 dict->SetInteger("delta", delta);
209 dict->SetInteger("window_size", window_size);
210 return dict;
213 base::Value* NetLogSpdyDataCallback(SpdyStreamId stream_id,
214 int size,
215 bool fin,
216 NetLog::LogLevel /* log_level */) {
217 base::DictionaryValue* dict = new base::DictionaryValue();
218 dict->SetInteger("stream_id", static_cast<int>(stream_id));
219 dict->SetInteger("size", size);
220 dict->SetBoolean("fin", fin);
221 return dict;
224 base::Value* NetLogSpdyRstCallback(SpdyStreamId stream_id,
225 int status,
226 const std::string* description,
227 NetLog::LogLevel /* log_level */) {
228 base::DictionaryValue* dict = new base::DictionaryValue();
229 dict->SetInteger("stream_id", static_cast<int>(stream_id));
230 dict->SetInteger("status", status);
231 dict->SetString("description", *description);
232 return dict;
235 base::Value* NetLogSpdyPingCallback(SpdyPingId unique_id,
236 bool is_ack,
237 const char* type,
238 NetLog::LogLevel /* log_level */) {
239 base::DictionaryValue* dict = new base::DictionaryValue();
240 dict->SetInteger("unique_id", static_cast<int>(unique_id));
241 dict->SetString("type", type);
242 dict->SetBoolean("is_ack", is_ack);
243 return dict;
246 base::Value* NetLogSpdyGoAwayCallback(SpdyStreamId last_stream_id,
247 int active_streams,
248 int unclaimed_streams,
249 SpdyGoAwayStatus status,
250 NetLog::LogLevel /* log_level */) {
251 base::DictionaryValue* dict = new base::DictionaryValue();
252 dict->SetInteger("last_accepted_stream_id",
253 static_cast<int>(last_stream_id));
254 dict->SetInteger("active_streams", active_streams);
255 dict->SetInteger("unclaimed_streams", unclaimed_streams);
256 dict->SetInteger("status", static_cast<int>(status));
257 return dict;
260 base::Value* NetLogSpdyPushPromiseReceivedCallback(
261 const SpdyHeaderBlock* headers,
262 SpdyStreamId stream_id,
263 SpdyStreamId promised_stream_id,
264 NetLog::LogLevel log_level) {
265 base::DictionaryValue* dict = new base::DictionaryValue();
266 dict->Set("headers",
267 SpdyHeaderBlockToListValue(*headers, log_level).release());
268 dict->SetInteger("id", stream_id);
269 dict->SetInteger("promised_stream_id", promised_stream_id);
270 return dict;
273 base::Value* NetLogSpdyAdoptedPushStreamCallback(
274 SpdyStreamId stream_id, const GURL* url, NetLog::LogLevel log_level) {
275 base::DictionaryValue* dict = new base::DictionaryValue();
276 dict->SetInteger("stream_id", stream_id);
277 dict->SetString("url", url->spec());
278 return dict;
281 // Helper function to return the total size of an array of objects
282 // with .size() member functions.
283 template <typename T, size_t N> size_t GetTotalSize(const T (&arr)[N]) {
284 size_t total_size = 0;
285 for (size_t i = 0; i < N; ++i) {
286 total_size += arr[i].size();
288 return total_size;
291 // Helper class for std:find_if on STL container containing
292 // SpdyStreamRequest weak pointers.
293 class RequestEquals {
294 public:
295 RequestEquals(const base::WeakPtr<SpdyStreamRequest>& request)
296 : request_(request) {}
298 bool operator()(const base::WeakPtr<SpdyStreamRequest>& request) const {
299 return request_.get() == request.get();
302 private:
303 const base::WeakPtr<SpdyStreamRequest> request_;
306 // The maximum number of concurrent streams we will ever create. Even if
307 // the server permits more, we will never exceed this limit.
308 const size_t kMaxConcurrentStreamLimit = 256;
310 } // namespace
312 SpdyProtocolErrorDetails MapFramerErrorToProtocolError(
313 SpdyFramer::SpdyError err) {
314 switch(err) {
315 case SpdyFramer::SPDY_NO_ERROR:
316 return SPDY_ERROR_NO_ERROR;
317 case SpdyFramer::SPDY_INVALID_CONTROL_FRAME:
318 return SPDY_ERROR_INVALID_CONTROL_FRAME;
319 case SpdyFramer::SPDY_CONTROL_PAYLOAD_TOO_LARGE:
320 return SPDY_ERROR_CONTROL_PAYLOAD_TOO_LARGE;
321 case SpdyFramer::SPDY_ZLIB_INIT_FAILURE:
322 return SPDY_ERROR_ZLIB_INIT_FAILURE;
323 case SpdyFramer::SPDY_UNSUPPORTED_VERSION:
324 return SPDY_ERROR_UNSUPPORTED_VERSION;
325 case SpdyFramer::SPDY_DECOMPRESS_FAILURE:
326 return SPDY_ERROR_DECOMPRESS_FAILURE;
327 case SpdyFramer::SPDY_COMPRESS_FAILURE:
328 return SPDY_ERROR_COMPRESS_FAILURE;
329 case SpdyFramer::SPDY_GOAWAY_FRAME_CORRUPT:
330 return SPDY_ERROR_GOAWAY_FRAME_CORRUPT;
331 case SpdyFramer::SPDY_RST_STREAM_FRAME_CORRUPT:
332 return SPDY_ERROR_RST_STREAM_FRAME_CORRUPT;
333 case SpdyFramer::SPDY_INVALID_DATA_FRAME_FLAGS:
334 return SPDY_ERROR_INVALID_DATA_FRAME_FLAGS;
335 case SpdyFramer::SPDY_INVALID_CONTROL_FRAME_FLAGS:
336 return SPDY_ERROR_INVALID_CONTROL_FRAME_FLAGS;
337 case SpdyFramer::SPDY_UNEXPECTED_FRAME:
338 return SPDY_ERROR_UNEXPECTED_FRAME;
339 default:
340 NOTREACHED();
341 return static_cast<SpdyProtocolErrorDetails>(-1);
345 Error MapFramerErrorToNetError(SpdyFramer::SpdyError err) {
346 switch (err) {
347 case SpdyFramer::SPDY_NO_ERROR:
348 return OK;
349 case SpdyFramer::SPDY_INVALID_CONTROL_FRAME:
350 return ERR_SPDY_PROTOCOL_ERROR;
351 case SpdyFramer::SPDY_CONTROL_PAYLOAD_TOO_LARGE:
352 return ERR_SPDY_FRAME_SIZE_ERROR;
353 case SpdyFramer::SPDY_ZLIB_INIT_FAILURE:
354 return ERR_SPDY_COMPRESSION_ERROR;
355 case SpdyFramer::SPDY_UNSUPPORTED_VERSION:
356 return ERR_SPDY_PROTOCOL_ERROR;
357 case SpdyFramer::SPDY_DECOMPRESS_FAILURE:
358 return ERR_SPDY_COMPRESSION_ERROR;
359 case SpdyFramer::SPDY_COMPRESS_FAILURE:
360 return ERR_SPDY_COMPRESSION_ERROR;
361 case SpdyFramer::SPDY_GOAWAY_FRAME_CORRUPT:
362 return ERR_SPDY_PROTOCOL_ERROR;
363 case SpdyFramer::SPDY_RST_STREAM_FRAME_CORRUPT:
364 return ERR_SPDY_PROTOCOL_ERROR;
365 case SpdyFramer::SPDY_INVALID_DATA_FRAME_FLAGS:
366 return ERR_SPDY_PROTOCOL_ERROR;
367 case SpdyFramer::SPDY_INVALID_CONTROL_FRAME_FLAGS:
368 return ERR_SPDY_PROTOCOL_ERROR;
369 case SpdyFramer::SPDY_UNEXPECTED_FRAME:
370 return ERR_SPDY_PROTOCOL_ERROR;
371 default:
372 NOTREACHED();
373 return ERR_SPDY_PROTOCOL_ERROR;
377 SpdyProtocolErrorDetails MapRstStreamStatusToProtocolError(
378 SpdyRstStreamStatus status) {
379 switch(status) {
380 case RST_STREAM_PROTOCOL_ERROR:
381 return STATUS_CODE_PROTOCOL_ERROR;
382 case RST_STREAM_INVALID_STREAM:
383 return STATUS_CODE_INVALID_STREAM;
384 case RST_STREAM_REFUSED_STREAM:
385 return STATUS_CODE_REFUSED_STREAM;
386 case RST_STREAM_UNSUPPORTED_VERSION:
387 return STATUS_CODE_UNSUPPORTED_VERSION;
388 case RST_STREAM_CANCEL:
389 return STATUS_CODE_CANCEL;
390 case RST_STREAM_INTERNAL_ERROR:
391 return STATUS_CODE_INTERNAL_ERROR;
392 case RST_STREAM_FLOW_CONTROL_ERROR:
393 return STATUS_CODE_FLOW_CONTROL_ERROR;
394 case RST_STREAM_STREAM_IN_USE:
395 return STATUS_CODE_STREAM_IN_USE;
396 case RST_STREAM_STREAM_ALREADY_CLOSED:
397 return STATUS_CODE_STREAM_ALREADY_CLOSED;
398 case RST_STREAM_INVALID_CREDENTIALS:
399 return STATUS_CODE_INVALID_CREDENTIALS;
400 case RST_STREAM_FRAME_SIZE_ERROR:
401 return STATUS_CODE_FRAME_SIZE_ERROR;
402 case RST_STREAM_SETTINGS_TIMEOUT:
403 return STATUS_CODE_SETTINGS_TIMEOUT;
404 case RST_STREAM_CONNECT_ERROR:
405 return STATUS_CODE_CONNECT_ERROR;
406 case RST_STREAM_ENHANCE_YOUR_CALM:
407 return STATUS_CODE_ENHANCE_YOUR_CALM;
408 case RST_STREAM_INADEQUATE_SECURITY:
409 return STATUS_CODE_INADEQUATE_SECURITY;
410 case RST_STREAM_HTTP_1_1_REQUIRED:
411 return STATUS_CODE_HTTP_1_1_REQUIRED;
412 default:
413 NOTREACHED();
414 return static_cast<SpdyProtocolErrorDetails>(-1);
418 SpdyGoAwayStatus MapNetErrorToGoAwayStatus(Error err) {
419 switch (err) {
420 case OK:
421 return GOAWAY_NO_ERROR;
422 case ERR_SPDY_PROTOCOL_ERROR:
423 return GOAWAY_PROTOCOL_ERROR;
424 case ERR_SPDY_FLOW_CONTROL_ERROR:
425 return GOAWAY_FLOW_CONTROL_ERROR;
426 case ERR_SPDY_FRAME_SIZE_ERROR:
427 return GOAWAY_FRAME_SIZE_ERROR;
428 case ERR_SPDY_COMPRESSION_ERROR:
429 return GOAWAY_COMPRESSION_ERROR;
430 case ERR_SPDY_INADEQUATE_TRANSPORT_SECURITY:
431 return GOAWAY_INADEQUATE_SECURITY;
432 default:
433 return GOAWAY_PROTOCOL_ERROR;
437 void SplitPushedHeadersToRequestAndResponse(const SpdyHeaderBlock& headers,
438 SpdyMajorVersion protocol_version,
439 SpdyHeaderBlock* request_headers,
440 SpdyHeaderBlock* response_headers) {
441 DCHECK(response_headers);
442 DCHECK(request_headers);
443 for (SpdyHeaderBlock::const_iterator it = headers.begin();
444 it != headers.end();
445 ++it) {
446 SpdyHeaderBlock* to_insert = response_headers;
447 if (protocol_version == SPDY2) {
448 if (it->first == "url")
449 to_insert = request_headers;
450 } else {
451 const char* host = protocol_version >= SPDY4 ? ":authority" : ":host";
452 static const char scheme[] = ":scheme";
453 static const char path[] = ":path";
454 if (it->first == host || it->first == scheme || it->first == path)
455 to_insert = request_headers;
457 to_insert->insert(*it);
461 SpdyStreamRequest::SpdyStreamRequest() : weak_ptr_factory_(this) {
462 Reset();
465 SpdyStreamRequest::~SpdyStreamRequest() {
466 CancelRequest();
469 int SpdyStreamRequest::StartRequest(
470 SpdyStreamType type,
471 const base::WeakPtr<SpdySession>& session,
472 const GURL& url,
473 RequestPriority priority,
474 const BoundNetLog& net_log,
475 const CompletionCallback& callback) {
476 DCHECK(session);
477 DCHECK(!session_);
478 DCHECK(!stream_);
479 DCHECK(callback_.is_null());
481 type_ = type;
482 session_ = session;
483 url_ = url;
484 priority_ = priority;
485 net_log_ = net_log;
486 callback_ = callback;
488 base::WeakPtr<SpdyStream> stream;
489 int rv = session->TryCreateStream(weak_ptr_factory_.GetWeakPtr(), &stream);
490 if (rv == OK) {
491 Reset();
492 stream_ = stream;
494 return rv;
497 void SpdyStreamRequest::CancelRequest() {
498 if (session_)
499 session_->CancelStreamRequest(weak_ptr_factory_.GetWeakPtr());
500 Reset();
501 // Do this to cancel any pending CompleteStreamRequest() tasks.
502 weak_ptr_factory_.InvalidateWeakPtrs();
505 base::WeakPtr<SpdyStream> SpdyStreamRequest::ReleaseStream() {
506 DCHECK(!session_);
507 base::WeakPtr<SpdyStream> stream = stream_;
508 DCHECK(stream);
509 Reset();
510 return stream;
513 void SpdyStreamRequest::OnRequestCompleteSuccess(
514 const base::WeakPtr<SpdyStream>& stream) {
515 DCHECK(session_);
516 DCHECK(!stream_);
517 DCHECK(!callback_.is_null());
518 CompletionCallback callback = callback_;
519 Reset();
520 DCHECK(stream);
521 stream_ = stream;
522 callback.Run(OK);
525 void SpdyStreamRequest::OnRequestCompleteFailure(int rv) {
526 DCHECK(session_);
527 DCHECK(!stream_);
528 DCHECK(!callback_.is_null());
529 CompletionCallback callback = callback_;
530 Reset();
531 DCHECK_NE(rv, OK);
532 callback.Run(rv);
535 void SpdyStreamRequest::Reset() {
536 type_ = SPDY_BIDIRECTIONAL_STREAM;
537 session_.reset();
538 stream_.reset();
539 url_ = GURL();
540 priority_ = MINIMUM_PRIORITY;
541 net_log_ = BoundNetLog();
542 callback_.Reset();
545 SpdySession::ActiveStreamInfo::ActiveStreamInfo()
546 : stream(NULL),
547 waiting_for_syn_reply(false) {}
549 SpdySession::ActiveStreamInfo::ActiveStreamInfo(SpdyStream* stream)
550 : stream(stream),
551 waiting_for_syn_reply(stream->type() != SPDY_PUSH_STREAM) {
554 SpdySession::ActiveStreamInfo::~ActiveStreamInfo() {}
556 SpdySession::PushedStreamInfo::PushedStreamInfo() : stream_id(0) {}
558 SpdySession::PushedStreamInfo::PushedStreamInfo(
559 SpdyStreamId stream_id,
560 base::TimeTicks creation_time)
561 : stream_id(stream_id),
562 creation_time(creation_time) {}
564 SpdySession::PushedStreamInfo::~PushedStreamInfo() {}
566 // static
567 bool SpdySession::CanPool(TransportSecurityState* transport_security_state,
568 const SSLInfo& ssl_info,
569 const std::string& old_hostname,
570 const std::string& new_hostname) {
571 // Pooling is prohibited if the server cert is not valid for the new domain,
572 // and for connections on which client certs were sent. It is also prohibited
573 // when channel ID was sent if the hosts are from different eTLDs+1.
574 if (IsCertStatusError(ssl_info.cert_status))
575 return false;
577 if (ssl_info.client_cert_sent)
578 return false;
580 if (ssl_info.channel_id_sent &&
581 ChannelIDService::GetDomainForHost(new_hostname) !=
582 ChannelIDService::GetDomainForHost(old_hostname)) {
583 return false;
586 bool unused = false;
587 if (!ssl_info.cert->VerifyNameMatch(new_hostname, &unused))
588 return false;
590 std::string pinning_failure_log;
591 if (!transport_security_state->CheckPublicKeyPins(
592 new_hostname,
593 ssl_info.is_issued_by_known_root,
594 ssl_info.public_key_hashes,
595 &pinning_failure_log)) {
596 return false;
599 return true;
602 SpdySession::SpdySession(
603 const SpdySessionKey& spdy_session_key,
604 const base::WeakPtr<HttpServerProperties>& http_server_properties,
605 TransportSecurityState* transport_security_state,
606 bool verify_domain_authentication,
607 bool enable_sending_initial_data,
608 bool enable_compression,
609 bool enable_ping_based_connection_checking,
610 NextProto default_protocol,
611 size_t stream_initial_recv_window_size,
612 size_t initial_max_concurrent_streams,
613 size_t max_concurrent_streams_limit,
614 TimeFunc time_func,
615 const HostPortPair& trusted_spdy_proxy,
616 NetLog* net_log)
617 : in_io_loop_(false),
618 spdy_session_key_(spdy_session_key),
619 pool_(NULL),
620 http_server_properties_(http_server_properties),
621 transport_security_state_(transport_security_state),
622 read_buffer_(new IOBuffer(kReadBufferSize)),
623 stream_hi_water_mark_(kFirstStreamId),
624 last_accepted_push_stream_id_(0),
625 num_pushed_streams_(0u),
626 num_active_pushed_streams_(0u),
627 in_flight_write_frame_type_(DATA),
628 in_flight_write_frame_size_(0),
629 is_secure_(false),
630 certificate_error_code_(OK),
631 availability_state_(STATE_AVAILABLE),
632 read_state_(READ_STATE_DO_READ),
633 write_state_(WRITE_STATE_IDLE),
634 error_on_close_(OK),
635 max_concurrent_streams_(initial_max_concurrent_streams == 0
636 ? kInitialMaxConcurrentStreams
637 : initial_max_concurrent_streams),
638 max_concurrent_streams_limit_(max_concurrent_streams_limit == 0
639 ? kMaxConcurrentStreamLimit
640 : max_concurrent_streams_limit),
641 max_concurrent_pushed_streams_(kMaxConcurrentPushedStreams),
642 streams_initiated_count_(0),
643 streams_pushed_count_(0),
644 streams_pushed_and_claimed_count_(0),
645 streams_abandoned_count_(0),
646 total_bytes_received_(0),
647 sent_settings_(false),
648 received_settings_(false),
649 stalled_streams_(0),
650 pings_in_flight_(0),
651 next_ping_id_(1),
652 last_activity_time_(time_func()),
653 last_compressed_frame_len_(0),
654 check_ping_status_pending_(false),
655 send_connection_header_prefix_(false),
656 flow_control_state_(FLOW_CONTROL_NONE),
657 stream_initial_send_window_size_(GetInitialWindowSize(default_protocol)),
658 stream_initial_recv_window_size_(stream_initial_recv_window_size == 0
659 ? kDefaultInitialRecvWindowSize
660 : stream_initial_recv_window_size),
661 session_send_window_size_(0),
662 session_recv_window_size_(0),
663 session_unacked_recv_window_bytes_(0),
664 net_log_(BoundNetLog::Make(net_log, NetLog::SOURCE_HTTP2_SESSION)),
665 verify_domain_authentication_(verify_domain_authentication),
666 enable_sending_initial_data_(enable_sending_initial_data),
667 enable_compression_(enable_compression),
668 enable_ping_based_connection_checking_(
669 enable_ping_based_connection_checking),
670 protocol_(default_protocol),
671 connection_at_risk_of_loss_time_(
672 base::TimeDelta::FromSeconds(kDefaultConnectionAtRiskOfLossSeconds)),
673 hung_interval_(base::TimeDelta::FromSeconds(kHungIntervalSeconds)),
674 trusted_spdy_proxy_(trusted_spdy_proxy),
675 time_func_(time_func),
676 weak_factory_(this) {
677 DCHECK_GE(protocol_, kProtoSPDYMinimumVersion);
678 DCHECK_LE(protocol_, kProtoSPDYMaximumVersion);
679 DCHECK(HttpStreamFactory::spdy_enabled());
680 net_log_.BeginEvent(
681 NetLog::TYPE_HTTP2_SESSION,
682 base::Bind(&NetLogSpdySessionCallback, &host_port_proxy_pair()));
683 next_unclaimed_push_stream_sweep_time_ = time_func_() +
684 base::TimeDelta::FromSeconds(kMinPushedStreamLifetimeSeconds);
685 // TODO(mbelshe): consider randomization of the stream_hi_water_mark.
688 SpdySession::~SpdySession() {
689 CHECK(!in_io_loop_);
690 DcheckDraining();
692 // TODO(akalin): Check connection->is_initialized() instead. This
693 // requires re-working CreateFakeSpdySession(), though.
694 DCHECK(connection_->socket());
695 // With SPDY we can't recycle sockets.
696 connection_->socket()->Disconnect();
698 RecordHistograms();
700 net_log_.EndEvent(NetLog::TYPE_HTTP2_SESSION);
703 void SpdySession::InitializeWithSocket(
704 scoped_ptr<ClientSocketHandle> connection,
705 SpdySessionPool* pool,
706 bool is_secure,
707 int certificate_error_code) {
708 CHECK(!in_io_loop_);
709 DCHECK_EQ(availability_state_, STATE_AVAILABLE);
710 DCHECK_EQ(read_state_, READ_STATE_DO_READ);
711 DCHECK_EQ(write_state_, WRITE_STATE_IDLE);
712 DCHECK(!connection_);
714 DCHECK(certificate_error_code == OK ||
715 certificate_error_code < ERR_IO_PENDING);
716 // TODO(akalin): Check connection->is_initialized() instead. This
717 // requires re-working CreateFakeSpdySession(), though.
718 DCHECK(connection->socket());
720 connection_ = connection.Pass();
721 is_secure_ = is_secure;
722 certificate_error_code_ = certificate_error_code;
724 NextProto protocol_negotiated =
725 connection_->socket()->GetNegotiatedProtocol();
726 if (protocol_negotiated != kProtoUnknown) {
727 protocol_ = protocol_negotiated;
728 stream_initial_send_window_size_ = GetInitialWindowSize(protocol_);
730 DCHECK_GE(protocol_, kProtoSPDYMinimumVersion);
731 DCHECK_LE(protocol_, kProtoSPDYMaximumVersion);
733 if ((protocol_ >= kProtoSPDY4MinimumVersion) &&
734 (protocol_ <= kProtoSPDY4MaximumVersion))
735 send_connection_header_prefix_ = true;
737 if (protocol_ >= kProtoSPDY31) {
738 flow_control_state_ = FLOW_CONTROL_STREAM_AND_SESSION;
739 session_send_window_size_ = GetInitialWindowSize(protocol_);
740 session_recv_window_size_ = GetInitialWindowSize(protocol_);
741 } else if (protocol_ >= kProtoSPDY3) {
742 flow_control_state_ = FLOW_CONTROL_STREAM;
743 } else {
744 flow_control_state_ = FLOW_CONTROL_NONE;
747 buffered_spdy_framer_.reset(
748 new BufferedSpdyFramer(NextProtoToSpdyMajorVersion(protocol_),
749 enable_compression_));
750 buffered_spdy_framer_->set_visitor(this);
751 buffered_spdy_framer_->set_debug_visitor(this);
752 UMA_HISTOGRAM_ENUMERATION(
753 "Net.SpdyVersion2",
754 protocol_ - kProtoSPDYHistogramOffset,
755 kProtoSPDYMaximumVersion - kProtoSPDYMinimumVersion + 1);
757 net_log_.AddEvent(
758 NetLog::TYPE_HTTP2_SESSION_INITIALIZED,
759 base::Bind(&NetLogSpdyInitializedCallback,
760 connection_->socket()->NetLog().source(), protocol_));
762 DCHECK_EQ(availability_state_, STATE_AVAILABLE);
763 connection_->AddHigherLayeredPool(this);
764 if (enable_sending_initial_data_)
765 SendInitialData();
766 pool_ = pool;
768 // Bootstrap the read loop.
769 base::MessageLoop::current()->PostTask(
770 FROM_HERE,
771 base::Bind(&SpdySession::PumpReadLoop,
772 weak_factory_.GetWeakPtr(), READ_STATE_DO_READ, OK));
775 bool SpdySession::VerifyDomainAuthentication(const std::string& domain) {
776 if (!verify_domain_authentication_)
777 return true;
779 if (availability_state_ == STATE_DRAINING)
780 return false;
782 SSLInfo ssl_info;
783 bool was_npn_negotiated;
784 NextProto protocol_negotiated = kProtoUnknown;
785 if (!GetSSLInfo(&ssl_info, &was_npn_negotiated, &protocol_negotiated))
786 return true; // This is not a secure session, so all domains are okay.
788 return CanPool(transport_security_state_, ssl_info,
789 host_port_pair().host(), domain);
792 int SpdySession::GetPushStream(
793 const GURL& url,
794 base::WeakPtr<SpdyStream>* stream,
795 const BoundNetLog& stream_net_log) {
796 CHECK(!in_io_loop_);
798 stream->reset();
800 if (availability_state_ == STATE_DRAINING)
801 return ERR_CONNECTION_CLOSED;
803 Error err = TryAccessStream(url);
804 if (err != OK)
805 return err;
807 *stream = GetActivePushStream(url);
808 if (*stream) {
809 DCHECK_LT(streams_pushed_and_claimed_count_, streams_pushed_count_);
810 streams_pushed_and_claimed_count_++;
812 return OK;
815 // {,Try}CreateStream() and TryAccessStream() can be called with
816 // |in_io_loop_| set if a stream is being created in response to
817 // another being closed due to received data.
819 Error SpdySession::TryAccessStream(const GURL& url) {
820 if (is_secure_ && certificate_error_code_ != OK &&
821 (url.SchemeIs("https") || url.SchemeIs("wss"))) {
822 RecordProtocolErrorHistogram(
823 PROTOCOL_ERROR_REQUEST_FOR_SECURE_CONTENT_OVER_INSECURE_SESSION);
824 DoDrainSession(
825 static_cast<Error>(certificate_error_code_),
826 "Tried to get SPDY stream for secure content over an unauthenticated "
827 "session.");
828 return ERR_SPDY_PROTOCOL_ERROR;
830 return OK;
833 int SpdySession::TryCreateStream(
834 const base::WeakPtr<SpdyStreamRequest>& request,
835 base::WeakPtr<SpdyStream>* stream) {
836 DCHECK(request);
838 if (availability_state_ == STATE_GOING_AWAY)
839 return ERR_FAILED;
841 if (availability_state_ == STATE_DRAINING)
842 return ERR_CONNECTION_CLOSED;
844 Error err = TryAccessStream(request->url());
845 if (err != OK)
846 return err;
848 if (!max_concurrent_streams_ ||
849 (active_streams_.size() + created_streams_.size() - num_pushed_streams_ <
850 max_concurrent_streams_)) {
851 return CreateStream(*request, stream);
854 stalled_streams_++;
855 net_log().AddEvent(NetLog::TYPE_HTTP2_SESSION_STALLED_MAX_STREAMS);
856 RequestPriority priority = request->priority();
857 CHECK_GE(priority, MINIMUM_PRIORITY);
858 CHECK_LE(priority, MAXIMUM_PRIORITY);
859 pending_create_stream_queues_[priority].push_back(request);
860 return ERR_IO_PENDING;
863 int SpdySession::CreateStream(const SpdyStreamRequest& request,
864 base::WeakPtr<SpdyStream>* stream) {
865 DCHECK_GE(request.priority(), MINIMUM_PRIORITY);
866 DCHECK_LE(request.priority(), MAXIMUM_PRIORITY);
868 if (availability_state_ == STATE_GOING_AWAY)
869 return ERR_FAILED;
871 if (availability_state_ == STATE_DRAINING)
872 return ERR_CONNECTION_CLOSED;
874 Error err = TryAccessStream(request.url());
875 if (err != OK) {
876 // This should have been caught in TryCreateStream().
877 NOTREACHED();
878 return err;
881 DCHECK(connection_->socket());
882 UMA_HISTOGRAM_BOOLEAN("Net.SpdySession.CreateStreamWithSocketConnected",
883 connection_->socket()->IsConnected());
884 if (!connection_->socket()->IsConnected()) {
885 DoDrainSession(
886 ERR_CONNECTION_CLOSED,
887 "Tried to create SPDY stream for a closed socket connection.");
888 return ERR_CONNECTION_CLOSED;
891 scoped_ptr<SpdyStream> new_stream(
892 new SpdyStream(request.type(), GetWeakPtr(), request.url(),
893 request.priority(),
894 stream_initial_send_window_size_,
895 stream_initial_recv_window_size_,
896 request.net_log()));
897 *stream = new_stream->GetWeakPtr();
898 InsertCreatedStream(new_stream.Pass());
900 UMA_HISTOGRAM_CUSTOM_COUNTS(
901 "Net.SpdyPriorityCount",
902 static_cast<int>(request.priority()), 0, 10, 11);
904 return OK;
907 void SpdySession::CancelStreamRequest(
908 const base::WeakPtr<SpdyStreamRequest>& request) {
909 DCHECK(request);
910 RequestPriority priority = request->priority();
911 CHECK_GE(priority, MINIMUM_PRIORITY);
912 CHECK_LE(priority, MAXIMUM_PRIORITY);
914 #if DCHECK_IS_ON()
915 // |request| should not be in a queue not matching its priority.
916 for (int i = MINIMUM_PRIORITY; i <= MAXIMUM_PRIORITY; ++i) {
917 if (priority == i)
918 continue;
919 PendingStreamRequestQueue* queue = &pending_create_stream_queues_[i];
920 DCHECK(std::find_if(queue->begin(),
921 queue->end(),
922 RequestEquals(request)) == queue->end());
924 #endif
926 PendingStreamRequestQueue* queue =
927 &pending_create_stream_queues_[priority];
928 // Remove |request| from |queue| while preserving the order of the
929 // other elements.
930 PendingStreamRequestQueue::iterator it =
931 std::find_if(queue->begin(), queue->end(), RequestEquals(request));
932 // The request may already be removed if there's a
933 // CompleteStreamRequest() in flight.
934 if (it != queue->end()) {
935 it = queue->erase(it);
936 // |request| should be in the queue at most once, and if it is
937 // present, should not be pending completion.
938 DCHECK(std::find_if(it, queue->end(), RequestEquals(request)) ==
939 queue->end());
943 base::WeakPtr<SpdyStreamRequest> SpdySession::GetNextPendingStreamRequest() {
944 for (int j = MAXIMUM_PRIORITY; j >= MINIMUM_PRIORITY; --j) {
945 if (pending_create_stream_queues_[j].empty())
946 continue;
948 base::WeakPtr<SpdyStreamRequest> pending_request =
949 pending_create_stream_queues_[j].front();
950 DCHECK(pending_request);
951 pending_create_stream_queues_[j].pop_front();
952 return pending_request;
954 return base::WeakPtr<SpdyStreamRequest>();
957 void SpdySession::ProcessPendingStreamRequests() {
958 // Like |max_concurrent_streams_|, 0 means infinite for
959 // |max_requests_to_process|.
960 size_t max_requests_to_process = 0;
961 if (max_concurrent_streams_ != 0) {
962 max_requests_to_process =
963 max_concurrent_streams_ -
964 (active_streams_.size() + created_streams_.size());
966 for (size_t i = 0;
967 max_requests_to_process == 0 || i < max_requests_to_process; ++i) {
968 base::WeakPtr<SpdyStreamRequest> pending_request =
969 GetNextPendingStreamRequest();
970 if (!pending_request)
971 break;
973 // Note that this post can race with other stream creations, and it's
974 // possible that the un-stalled stream will be stalled again if it loses.
975 // TODO(jgraettinger): Provide stronger ordering guarantees.
976 base::MessageLoop::current()->PostTask(
977 FROM_HERE,
978 base::Bind(&SpdySession::CompleteStreamRequest,
979 weak_factory_.GetWeakPtr(),
980 pending_request));
984 void SpdySession::AddPooledAlias(const SpdySessionKey& alias_key) {
985 pooled_aliases_.insert(alias_key);
988 SpdyMajorVersion SpdySession::GetProtocolVersion() const {
989 DCHECK(buffered_spdy_framer_.get());
990 return buffered_spdy_framer_->protocol_version();
993 bool SpdySession::HasAcceptableTransportSecurity() const {
994 // If we're not even using TLS, we have no standards to meet.
995 if (!is_secure_) {
996 return true;
999 // We don't enforce transport security standards for older SPDY versions.
1000 if (GetProtocolVersion() < SPDY4) {
1001 return true;
1004 SSLInfo ssl_info;
1005 CHECK(connection_->socket()->GetSSLInfo(&ssl_info));
1007 // HTTP/2 requires TLS 1.2+
1008 if (SSLConnectionStatusToVersion(ssl_info.connection_status) <
1009 SSL_CONNECTION_VERSION_TLS1_2) {
1010 return false;
1013 if (!IsSecureTLSCipherSuite(
1014 SSLConnectionStatusToCipherSuite(ssl_info.connection_status))) {
1015 return false;
1018 return true;
1021 base::WeakPtr<SpdySession> SpdySession::GetWeakPtr() {
1022 return weak_factory_.GetWeakPtr();
1025 bool SpdySession::CloseOneIdleConnection() {
1026 CHECK(!in_io_loop_);
1027 DCHECK(pool_);
1028 if (active_streams_.empty()) {
1029 DoDrainSession(ERR_CONNECTION_CLOSED, "Closing idle connection.");
1031 // Return false as the socket wasn't immediately closed.
1032 return false;
1035 void SpdySession::EnqueueStreamWrite(
1036 const base::WeakPtr<SpdyStream>& stream,
1037 SpdyFrameType frame_type,
1038 scoped_ptr<SpdyBufferProducer> producer) {
1039 DCHECK(frame_type == HEADERS ||
1040 frame_type == DATA ||
1041 frame_type == CREDENTIAL ||
1042 frame_type == SYN_STREAM);
1043 EnqueueWrite(stream->priority(), frame_type, producer.Pass(), stream);
1046 scoped_ptr<SpdyFrame> SpdySession::CreateSynStream(
1047 SpdyStreamId stream_id,
1048 RequestPriority priority,
1049 SpdyControlFlags flags,
1050 const SpdyHeaderBlock& block) {
1051 ActiveStreamMap::const_iterator it = active_streams_.find(stream_id);
1052 CHECK(it != active_streams_.end());
1053 CHECK_EQ(it->second.stream->stream_id(), stream_id);
1055 SendPrefacePingIfNoneInFlight();
1057 DCHECK(buffered_spdy_framer_.get());
1058 SpdyPriority spdy_priority =
1059 ConvertRequestPriorityToSpdyPriority(priority, GetProtocolVersion());
1061 scoped_ptr<SpdyFrame> syn_frame;
1062 // TODO(hkhalil): Avoid copy of |block|.
1063 if (GetProtocolVersion() <= SPDY3) {
1064 SpdySynStreamIR syn_stream(stream_id);
1065 syn_stream.set_associated_to_stream_id(0);
1066 syn_stream.set_priority(spdy_priority);
1067 syn_stream.set_fin((flags & CONTROL_FLAG_FIN) != 0);
1068 syn_stream.set_unidirectional((flags & CONTROL_FLAG_UNIDIRECTIONAL) != 0);
1069 syn_stream.set_name_value_block(block);
1070 syn_frame.reset(buffered_spdy_framer_->SerializeFrame(syn_stream));
1071 } else {
1072 SpdyHeadersIR headers(stream_id);
1073 headers.set_priority(spdy_priority);
1074 headers.set_has_priority(true);
1075 headers.set_fin((flags & CONTROL_FLAG_FIN) != 0);
1076 headers.set_name_value_block(block);
1077 syn_frame.reset(buffered_spdy_framer_->SerializeFrame(headers));
1080 streams_initiated_count_++;
1082 if (net_log().IsLogging()) {
1083 const NetLog::EventType type =
1084 (GetProtocolVersion() <= SPDY3)
1085 ? NetLog::TYPE_HTTP2_SESSION_SYN_STREAM
1086 : NetLog::TYPE_HTTP2_SESSION_SEND_HEADERS;
1087 net_log().AddEvent(type,
1088 base::Bind(&NetLogSpdySynStreamSentCallback, &block,
1089 (flags & CONTROL_FLAG_FIN) != 0,
1090 (flags & CONTROL_FLAG_UNIDIRECTIONAL) != 0,
1091 spdy_priority, stream_id));
1094 return syn_frame.Pass();
1097 scoped_ptr<SpdyBuffer> SpdySession::CreateDataBuffer(SpdyStreamId stream_id,
1098 IOBuffer* data,
1099 int len,
1100 SpdyDataFlags flags) {
1101 if (availability_state_ == STATE_DRAINING) {
1102 return scoped_ptr<SpdyBuffer>();
1105 ActiveStreamMap::const_iterator it = active_streams_.find(stream_id);
1106 CHECK(it != active_streams_.end());
1107 SpdyStream* stream = it->second.stream;
1108 CHECK_EQ(stream->stream_id(), stream_id);
1110 if (len < 0) {
1111 NOTREACHED();
1112 return scoped_ptr<SpdyBuffer>();
1115 int effective_len = std::min(len, kMaxSpdyFrameChunkSize);
1117 bool send_stalled_by_stream =
1118 (flow_control_state_ >= FLOW_CONTROL_STREAM) &&
1119 (stream->send_window_size() <= 0);
1120 bool send_stalled_by_session = IsSendStalled();
1122 // NOTE: There's an enum of the same name in histograms.xml.
1123 enum SpdyFrameFlowControlState {
1124 SEND_NOT_STALLED,
1125 SEND_STALLED_BY_STREAM,
1126 SEND_STALLED_BY_SESSION,
1127 SEND_STALLED_BY_STREAM_AND_SESSION,
1130 SpdyFrameFlowControlState frame_flow_control_state = SEND_NOT_STALLED;
1131 if (send_stalled_by_stream) {
1132 if (send_stalled_by_session) {
1133 frame_flow_control_state = SEND_STALLED_BY_STREAM_AND_SESSION;
1134 } else {
1135 frame_flow_control_state = SEND_STALLED_BY_STREAM;
1137 } else if (send_stalled_by_session) {
1138 frame_flow_control_state = SEND_STALLED_BY_SESSION;
1141 if (flow_control_state_ == FLOW_CONTROL_STREAM) {
1142 UMA_HISTOGRAM_ENUMERATION(
1143 "Net.SpdyFrameStreamFlowControlState",
1144 frame_flow_control_state,
1145 SEND_STALLED_BY_STREAM + 1);
1146 } else if (flow_control_state_ == FLOW_CONTROL_STREAM_AND_SESSION) {
1147 UMA_HISTOGRAM_ENUMERATION(
1148 "Net.SpdyFrameStreamAndSessionFlowControlState",
1149 frame_flow_control_state,
1150 SEND_STALLED_BY_STREAM_AND_SESSION + 1);
1153 // Obey send window size of the stream if stream flow control is
1154 // enabled.
1155 if (flow_control_state_ >= FLOW_CONTROL_STREAM) {
1156 if (send_stalled_by_stream) {
1157 stream->set_send_stalled_by_flow_control(true);
1158 // Even though we're currently stalled only by the stream, we
1159 // might end up being stalled by the session also.
1160 QueueSendStalledStream(*stream);
1161 net_log().AddEvent(
1162 NetLog::TYPE_HTTP2_SESSION_STREAM_STALLED_BY_STREAM_SEND_WINDOW,
1163 NetLog::IntegerCallback("stream_id", stream_id));
1164 return scoped_ptr<SpdyBuffer>();
1167 effective_len = std::min(effective_len, stream->send_window_size());
1170 // Obey send window size of the session if session flow control is
1171 // enabled.
1172 if (flow_control_state_ == FLOW_CONTROL_STREAM_AND_SESSION) {
1173 if (send_stalled_by_session) {
1174 stream->set_send_stalled_by_flow_control(true);
1175 QueueSendStalledStream(*stream);
1176 net_log().AddEvent(
1177 NetLog::TYPE_HTTP2_SESSION_STREAM_STALLED_BY_SESSION_SEND_WINDOW,
1178 NetLog::IntegerCallback("stream_id", stream_id));
1179 return scoped_ptr<SpdyBuffer>();
1182 effective_len = std::min(effective_len, session_send_window_size_);
1185 DCHECK_GE(effective_len, 0);
1187 // Clear FIN flag if only some of the data will be in the data
1188 // frame.
1189 if (effective_len < len)
1190 flags = static_cast<SpdyDataFlags>(flags & ~DATA_FLAG_FIN);
1192 if (net_log().IsLogging()) {
1193 net_log().AddEvent(NetLog::TYPE_HTTP2_SESSION_SEND_DATA,
1194 base::Bind(&NetLogSpdyDataCallback, stream_id,
1195 effective_len, (flags & DATA_FLAG_FIN) != 0));
1198 // Send PrefacePing for DATA_FRAMEs with nonzero payload size.
1199 if (effective_len > 0)
1200 SendPrefacePingIfNoneInFlight();
1202 // TODO(mbelshe): reduce memory copies here.
1203 DCHECK(buffered_spdy_framer_.get());
1204 scoped_ptr<SpdyFrame> frame(
1205 buffered_spdy_framer_->CreateDataFrame(
1206 stream_id, data->data(),
1207 static_cast<uint32>(effective_len), flags));
1209 scoped_ptr<SpdyBuffer> data_buffer(new SpdyBuffer(frame.Pass()));
1211 // Send window size is based on payload size, so nothing to do if this is
1212 // just a FIN with no payload.
1213 if (flow_control_state_ == FLOW_CONTROL_STREAM_AND_SESSION &&
1214 effective_len != 0) {
1215 DecreaseSendWindowSize(static_cast<int32>(effective_len));
1216 data_buffer->AddConsumeCallback(
1217 base::Bind(&SpdySession::OnWriteBufferConsumed,
1218 weak_factory_.GetWeakPtr(),
1219 static_cast<size_t>(effective_len)));
1222 return data_buffer.Pass();
1225 void SpdySession::CloseActiveStream(SpdyStreamId stream_id, int status) {
1226 DCHECK_NE(stream_id, 0u);
1228 ActiveStreamMap::iterator it = active_streams_.find(stream_id);
1229 if (it == active_streams_.end()) {
1230 NOTREACHED();
1231 return;
1234 CloseActiveStreamIterator(it, status);
1237 void SpdySession::CloseCreatedStream(
1238 const base::WeakPtr<SpdyStream>& stream, int status) {
1239 DCHECK_EQ(stream->stream_id(), 0u);
1241 CreatedStreamSet::iterator it = created_streams_.find(stream.get());
1242 if (it == created_streams_.end()) {
1243 NOTREACHED();
1244 return;
1247 CloseCreatedStreamIterator(it, status);
1250 void SpdySession::ResetStream(SpdyStreamId stream_id,
1251 SpdyRstStreamStatus status,
1252 const std::string& description) {
1253 DCHECK_NE(stream_id, 0u);
1255 ActiveStreamMap::iterator it = active_streams_.find(stream_id);
1256 if (it == active_streams_.end()) {
1257 NOTREACHED();
1258 return;
1261 ResetStreamIterator(it, status, description);
1264 bool SpdySession::IsStreamActive(SpdyStreamId stream_id) const {
1265 return ContainsKey(active_streams_, stream_id);
1268 LoadState SpdySession::GetLoadState() const {
1269 // Just report that we're idle since the session could be doing
1270 // many things concurrently.
1271 return LOAD_STATE_IDLE;
1274 void SpdySession::CloseActiveStreamIterator(ActiveStreamMap::iterator it,
1275 int status) {
1276 // TODO(mbelshe): We should send a RST_STREAM control frame here
1277 // so that the server can cancel a large send.
1279 scoped_ptr<SpdyStream> owned_stream(it->second.stream);
1280 active_streams_.erase(it);
1282 // TODO(akalin): When SpdyStream was ref-counted (and
1283 // |unclaimed_pushed_streams_| held scoped_refptr<SpdyStream>), this
1284 // was only done when status was not OK. This meant that pushed
1285 // streams can still be claimed after they're closed. This is
1286 // probably something that we still want to support, although server
1287 // push is hardly used. Write tests for this and fix this. (See
1288 // http://crbug.com/261712 .)
1289 if (owned_stream->type() == SPDY_PUSH_STREAM) {
1290 unclaimed_pushed_streams_.erase(owned_stream->url());
1291 num_pushed_streams_--;
1292 if (!owned_stream->IsReservedRemote())
1293 num_active_pushed_streams_--;
1296 DeleteStream(owned_stream.Pass(), status);
1297 MaybeFinishGoingAway();
1299 // If there are no active streams and the socket pool is stalled, close the
1300 // session to free up a socket slot.
1301 if (active_streams_.empty() && connection_->IsPoolStalled()) {
1302 DoDrainSession(ERR_CONNECTION_CLOSED, "Closing idle connection.");
1306 void SpdySession::CloseCreatedStreamIterator(CreatedStreamSet::iterator it,
1307 int status) {
1308 scoped_ptr<SpdyStream> owned_stream(*it);
1309 created_streams_.erase(it);
1310 DeleteStream(owned_stream.Pass(), status);
1313 void SpdySession::ResetStreamIterator(ActiveStreamMap::iterator it,
1314 SpdyRstStreamStatus status,
1315 const std::string& description) {
1316 // Send the RST_STREAM frame first as CloseActiveStreamIterator()
1317 // may close us.
1318 SpdyStreamId stream_id = it->first;
1319 RequestPriority priority = it->second.stream->priority();
1320 EnqueueResetStreamFrame(stream_id, priority, status, description);
1322 // Removes any pending writes for the stream except for possibly an
1323 // in-flight one.
1324 CloseActiveStreamIterator(it, ERR_SPDY_PROTOCOL_ERROR);
1327 void SpdySession::EnqueueResetStreamFrame(SpdyStreamId stream_id,
1328 RequestPriority priority,
1329 SpdyRstStreamStatus status,
1330 const std::string& description) {
1331 DCHECK_NE(stream_id, 0u);
1333 net_log().AddEvent(
1334 NetLog::TYPE_HTTP2_SESSION_SEND_RST_STREAM,
1335 base::Bind(&NetLogSpdyRstCallback, stream_id, status, &description));
1337 DCHECK(buffered_spdy_framer_.get());
1338 scoped_ptr<SpdyFrame> rst_frame(
1339 buffered_spdy_framer_->CreateRstStream(stream_id, status));
1341 EnqueueSessionWrite(priority, RST_STREAM, rst_frame.Pass());
1342 RecordProtocolErrorHistogram(MapRstStreamStatusToProtocolError(status));
1345 void SpdySession::PumpReadLoop(ReadState expected_read_state, int result) {
1346 // TODO(pkasting): Remove ScopedTracker below once crbug.com/462774 is fixed.
1347 tracked_objects::ScopedTracker tracking_profile(
1348 FROM_HERE_WITH_EXPLICIT_FUNCTION("462774 SpdySession::PumpReadLoop"));
1350 CHECK(!in_io_loop_);
1351 if (availability_state_ == STATE_DRAINING) {
1352 return;
1354 ignore_result(DoReadLoop(expected_read_state, result));
1357 int SpdySession::DoReadLoop(ReadState expected_read_state, int result) {
1358 CHECK(!in_io_loop_);
1359 CHECK_EQ(read_state_, expected_read_state);
1361 in_io_loop_ = true;
1363 int bytes_read_without_yielding = 0;
1365 // Loop until the session is draining, the read becomes blocked, or
1366 // the read limit is exceeded.
1367 while (true) {
1368 switch (read_state_) {
1369 case READ_STATE_DO_READ:
1370 CHECK_EQ(result, OK);
1371 result = DoRead();
1372 break;
1373 case READ_STATE_DO_READ_COMPLETE:
1374 if (result > 0)
1375 bytes_read_without_yielding += result;
1376 result = DoReadComplete(result);
1377 break;
1378 default:
1379 NOTREACHED() << "read_state_: " << read_state_;
1380 break;
1383 if (availability_state_ == STATE_DRAINING)
1384 break;
1386 if (result == ERR_IO_PENDING)
1387 break;
1389 if (bytes_read_without_yielding > kMaxReadBytesWithoutYielding) {
1390 read_state_ = READ_STATE_DO_READ;
1391 base::MessageLoop::current()->PostTask(
1392 FROM_HERE,
1393 base::Bind(&SpdySession::PumpReadLoop,
1394 weak_factory_.GetWeakPtr(), READ_STATE_DO_READ, OK));
1395 result = ERR_IO_PENDING;
1396 break;
1400 CHECK(in_io_loop_);
1401 in_io_loop_ = false;
1403 return result;
1406 int SpdySession::DoRead() {
1407 CHECK(in_io_loop_);
1409 CHECK(connection_);
1410 CHECK(connection_->socket());
1411 read_state_ = READ_STATE_DO_READ_COMPLETE;
1412 return connection_->socket()->Read(
1413 read_buffer_.get(),
1414 kReadBufferSize,
1415 base::Bind(&SpdySession::PumpReadLoop,
1416 weak_factory_.GetWeakPtr(), READ_STATE_DO_READ_COMPLETE));
1419 int SpdySession::DoReadComplete(int result) {
1420 CHECK(in_io_loop_);
1422 // Parse a frame. For now this code requires that the frame fit into our
1423 // buffer (kReadBufferSize).
1424 // TODO(mbelshe): support arbitrarily large frames!
1426 if (result == 0) {
1427 UMA_HISTOGRAM_CUSTOM_COUNTS("Net.SpdySession.BytesRead.EOF",
1428 total_bytes_received_, 1, 100000000, 50);
1429 DoDrainSession(ERR_CONNECTION_CLOSED, "Connection closed");
1431 return ERR_CONNECTION_CLOSED;
1434 if (result < 0) {
1435 DoDrainSession(static_cast<Error>(result), "result is < 0.");
1436 return result;
1438 CHECK_LE(result, kReadBufferSize);
1439 total_bytes_received_ += result;
1441 last_activity_time_ = time_func_();
1443 DCHECK(buffered_spdy_framer_.get());
1444 char* data = read_buffer_->data();
1445 while (result > 0) {
1446 uint32 bytes_processed = buffered_spdy_framer_->ProcessInput(data, result);
1447 result -= bytes_processed;
1448 data += bytes_processed;
1450 if (availability_state_ == STATE_DRAINING) {
1451 return ERR_CONNECTION_CLOSED;
1454 DCHECK_EQ(buffered_spdy_framer_->error_code(), SpdyFramer::SPDY_NO_ERROR);
1457 read_state_ = READ_STATE_DO_READ;
1458 return OK;
1461 void SpdySession::PumpWriteLoop(WriteState expected_write_state, int result) {
1462 CHECK(!in_io_loop_);
1463 DCHECK_EQ(write_state_, expected_write_state);
1465 DoWriteLoop(expected_write_state, result);
1467 if (availability_state_ == STATE_DRAINING && !in_flight_write_ &&
1468 write_queue_.IsEmpty()) {
1469 pool_->RemoveUnavailableSession(GetWeakPtr()); // Destroys |this|.
1470 return;
1474 int SpdySession::DoWriteLoop(WriteState expected_write_state, int result) {
1475 CHECK(!in_io_loop_);
1476 DCHECK_NE(write_state_, WRITE_STATE_IDLE);
1477 DCHECK_EQ(write_state_, expected_write_state);
1479 in_io_loop_ = true;
1481 // Loop until the session is closed or the write becomes blocked.
1482 while (true) {
1483 switch (write_state_) {
1484 case WRITE_STATE_DO_WRITE:
1485 DCHECK_EQ(result, OK);
1486 result = DoWrite();
1487 break;
1488 case WRITE_STATE_DO_WRITE_COMPLETE:
1489 result = DoWriteComplete(result);
1490 break;
1491 case WRITE_STATE_IDLE:
1492 default:
1493 NOTREACHED() << "write_state_: " << write_state_;
1494 break;
1497 if (write_state_ == WRITE_STATE_IDLE) {
1498 DCHECK_EQ(result, ERR_IO_PENDING);
1499 break;
1502 if (result == ERR_IO_PENDING)
1503 break;
1506 CHECK(in_io_loop_);
1507 in_io_loop_ = false;
1509 return result;
1512 int SpdySession::DoWrite() {
1513 CHECK(in_io_loop_);
1515 DCHECK(buffered_spdy_framer_);
1516 if (in_flight_write_) {
1517 DCHECK_GT(in_flight_write_->GetRemainingSize(), 0u);
1518 } else {
1519 // Grab the next frame to send.
1520 SpdyFrameType frame_type = DATA;
1521 scoped_ptr<SpdyBufferProducer> producer;
1522 base::WeakPtr<SpdyStream> stream;
1523 if (!write_queue_.Dequeue(&frame_type, &producer, &stream)) {
1524 write_state_ = WRITE_STATE_IDLE;
1525 return ERR_IO_PENDING;
1528 if (stream.get())
1529 CHECK(!stream->IsClosed());
1531 // Activate the stream only when sending the SYN_STREAM frame to
1532 // guarantee monotonically-increasing stream IDs.
1533 if (frame_type == SYN_STREAM) {
1534 CHECK(stream.get());
1535 CHECK_EQ(stream->stream_id(), 0u);
1536 scoped_ptr<SpdyStream> owned_stream =
1537 ActivateCreatedStream(stream.get());
1538 InsertActivatedStream(owned_stream.Pass());
1540 if (stream_hi_water_mark_ > kLastStreamId) {
1541 CHECK_EQ(stream->stream_id(), kLastStreamId);
1542 // We've exhausted the stream ID space, and no new streams may be
1543 // created after this one.
1544 MakeUnavailable();
1545 StartGoingAway(kLastStreamId, ERR_ABORTED);
1549 // TODO(pkasting): Remove ScopedTracker below once crbug.com/457517 is
1550 // fixed.
1551 tracked_objects::ScopedTracker tracking_profile1(
1552 FROM_HERE_WITH_EXPLICIT_FUNCTION("457517 SpdySession::DoWrite1"));
1553 in_flight_write_ = producer->ProduceBuffer();
1554 if (!in_flight_write_) {
1555 NOTREACHED();
1556 return ERR_UNEXPECTED;
1558 in_flight_write_frame_type_ = frame_type;
1559 in_flight_write_frame_size_ = in_flight_write_->GetRemainingSize();
1560 DCHECK_GE(in_flight_write_frame_size_,
1561 buffered_spdy_framer_->GetFrameMinimumSize());
1562 in_flight_write_stream_ = stream;
1565 write_state_ = WRITE_STATE_DO_WRITE_COMPLETE;
1567 // Explicitly store in a scoped_refptr<IOBuffer> to avoid problems
1568 // with Socket implementations that don't store their IOBuffer
1569 // argument in a scoped_refptr<IOBuffer> (see crbug.com/232345).
1570 // TODO(pkasting): Remove ScopedTracker below once crbug.com/457517 is fixed.
1571 tracked_objects::ScopedTracker tracking_profile2(
1572 FROM_HERE_WITH_EXPLICIT_FUNCTION("457517 SpdySession::DoWrite2"));
1573 scoped_refptr<IOBuffer> write_io_buffer =
1574 in_flight_write_->GetIOBufferForRemainingData();
1575 return connection_->socket()->Write(
1576 write_io_buffer.get(),
1577 in_flight_write_->GetRemainingSize(),
1578 base::Bind(&SpdySession::PumpWriteLoop,
1579 weak_factory_.GetWeakPtr(), WRITE_STATE_DO_WRITE_COMPLETE));
1582 int SpdySession::DoWriteComplete(int result) {
1583 CHECK(in_io_loop_);
1584 DCHECK_NE(result, ERR_IO_PENDING);
1585 DCHECK_GT(in_flight_write_->GetRemainingSize(), 0u);
1587 last_activity_time_ = time_func_();
1589 if (result < 0) {
1590 DCHECK_NE(result, ERR_IO_PENDING);
1591 in_flight_write_.reset();
1592 in_flight_write_frame_type_ = DATA;
1593 in_flight_write_frame_size_ = 0;
1594 in_flight_write_stream_.reset();
1595 write_state_ = WRITE_STATE_DO_WRITE;
1596 DoDrainSession(static_cast<Error>(result), "Write error");
1597 return OK;
1600 // It should not be possible to have written more bytes than our
1601 // in_flight_write_.
1602 DCHECK_LE(static_cast<size_t>(result),
1603 in_flight_write_->GetRemainingSize());
1605 if (result > 0) {
1606 in_flight_write_->Consume(static_cast<size_t>(result));
1608 // We only notify the stream when we've fully written the pending frame.
1609 if (in_flight_write_->GetRemainingSize() == 0) {
1610 // It is possible that the stream was cancelled while we were
1611 // writing to the socket.
1612 if (in_flight_write_stream_.get()) {
1613 DCHECK_GT(in_flight_write_frame_size_, 0u);
1614 in_flight_write_stream_->OnFrameWriteComplete(
1615 in_flight_write_frame_type_,
1616 in_flight_write_frame_size_);
1619 // Cleanup the write which just completed.
1620 in_flight_write_.reset();
1621 in_flight_write_frame_type_ = DATA;
1622 in_flight_write_frame_size_ = 0;
1623 in_flight_write_stream_.reset();
1627 write_state_ = WRITE_STATE_DO_WRITE;
1628 return OK;
1631 void SpdySession::DcheckGoingAway() const {
1632 #if DCHECK_IS_ON()
1633 DCHECK_GE(availability_state_, STATE_GOING_AWAY);
1634 for (int i = MINIMUM_PRIORITY; i <= MAXIMUM_PRIORITY; ++i) {
1635 DCHECK(pending_create_stream_queues_[i].empty());
1637 DCHECK(created_streams_.empty());
1638 #endif
1641 void SpdySession::DcheckDraining() const {
1642 DcheckGoingAway();
1643 DCHECK_EQ(availability_state_, STATE_DRAINING);
1644 DCHECK(active_streams_.empty());
1645 DCHECK(unclaimed_pushed_streams_.empty());
1648 void SpdySession::StartGoingAway(SpdyStreamId last_good_stream_id,
1649 Error status) {
1650 DCHECK_GE(availability_state_, STATE_GOING_AWAY);
1652 // The loops below are carefully written to avoid reentrancy problems.
1654 while (true) {
1655 size_t old_size = GetTotalSize(pending_create_stream_queues_);
1656 base::WeakPtr<SpdyStreamRequest> pending_request =
1657 GetNextPendingStreamRequest();
1658 if (!pending_request)
1659 break;
1660 // No new stream requests should be added while the session is
1661 // going away.
1662 DCHECK_GT(old_size, GetTotalSize(pending_create_stream_queues_));
1663 pending_request->OnRequestCompleteFailure(ERR_ABORTED);
1666 while (true) {
1667 size_t old_size = active_streams_.size();
1668 ActiveStreamMap::iterator it =
1669 active_streams_.lower_bound(last_good_stream_id + 1);
1670 if (it == active_streams_.end())
1671 break;
1672 LogAbandonedActiveStream(it, status);
1673 CloseActiveStreamIterator(it, status);
1674 // No new streams should be activated while the session is going
1675 // away.
1676 DCHECK_GT(old_size, active_streams_.size());
1679 while (!created_streams_.empty()) {
1680 size_t old_size = created_streams_.size();
1681 CreatedStreamSet::iterator it = created_streams_.begin();
1682 LogAbandonedStream(*it, status);
1683 CloseCreatedStreamIterator(it, status);
1684 // No new streams should be created while the session is going
1685 // away.
1686 DCHECK_GT(old_size, created_streams_.size());
1689 write_queue_.RemovePendingWritesForStreamsAfter(last_good_stream_id);
1691 DcheckGoingAway();
1694 void SpdySession::MaybeFinishGoingAway() {
1695 if (active_streams_.empty() && availability_state_ == STATE_GOING_AWAY) {
1696 DoDrainSession(OK, "Finished going away");
1700 void SpdySession::DoDrainSession(Error err, const std::string& description) {
1701 if (availability_state_ == STATE_DRAINING) {
1702 return;
1704 MakeUnavailable();
1706 // Mark host_port_pair requiring HTTP/1.1 for subsequent connections.
1707 if (err == ERR_HTTP_1_1_REQUIRED) {
1708 http_server_properties_->SetHTTP11Required(host_port_pair());
1711 // If |err| indicates an error occurred, inform the peer that we're closing
1712 // and why. Don't GOAWAY on a graceful or idle close, as that may
1713 // unnecessarily wake the radio. We could technically GOAWAY on network errors
1714 // (we'll probably fail to actually write it, but that's okay), however many
1715 // unit-tests would need to be updated.
1716 if (err != OK &&
1717 err != ERR_ABORTED && // Used by SpdySessionPool to close idle sessions.
1718 err != ERR_NETWORK_CHANGED && // Used to deprecate sessions on IP change.
1719 err != ERR_SOCKET_NOT_CONNECTED && err != ERR_HTTP_1_1_REQUIRED &&
1720 err != ERR_CONNECTION_CLOSED && err != ERR_CONNECTION_RESET) {
1721 // Enqueue a GOAWAY to inform the peer of why we're closing the connection.
1722 SpdyGoAwayIR goaway_ir(last_accepted_push_stream_id_,
1723 MapNetErrorToGoAwayStatus(err),
1724 description);
1725 EnqueueSessionWrite(HIGHEST,
1726 GOAWAY,
1727 scoped_ptr<SpdyFrame>(
1728 buffered_spdy_framer_->SerializeFrame(goaway_ir)));
1731 availability_state_ = STATE_DRAINING;
1732 error_on_close_ = err;
1734 net_log_.AddEvent(
1735 NetLog::TYPE_HTTP2_SESSION_CLOSE,
1736 base::Bind(&NetLogSpdySessionCloseCallback, err, &description));
1738 UMA_HISTOGRAM_SPARSE_SLOWLY("Net.SpdySession.ClosedOnError", -err);
1739 UMA_HISTOGRAM_CUSTOM_COUNTS("Net.SpdySession.BytesRead.OtherErrors",
1740 total_bytes_received_, 1, 100000000, 50);
1742 if (err == OK) {
1743 // We ought to be going away already, as this is a graceful close.
1744 DcheckGoingAway();
1745 } else {
1746 StartGoingAway(0, err);
1748 DcheckDraining();
1749 MaybePostWriteLoop();
1752 void SpdySession::LogAbandonedStream(SpdyStream* stream, Error status) {
1753 DCHECK(stream);
1754 std::string description = base::StringPrintf(
1755 "ABANDONED (stream_id=%d): ", stream->stream_id()) +
1756 stream->url().spec();
1757 stream->LogStreamError(status, description);
1758 // We don't increment the streams abandoned counter here. If the
1759 // stream isn't active (i.e., it hasn't written anything to the wire
1760 // yet) then it's as if it never existed. If it is active, then
1761 // LogAbandonedActiveStream() will increment the counters.
1764 void SpdySession::LogAbandonedActiveStream(ActiveStreamMap::const_iterator it,
1765 Error status) {
1766 DCHECK_GT(it->first, 0u);
1767 LogAbandonedStream(it->second.stream, status);
1768 ++streams_abandoned_count_;
1769 if (it->second.stream->type() == SPDY_PUSH_STREAM &&
1770 unclaimed_pushed_streams_.find(it->second.stream->url()) !=
1771 unclaimed_pushed_streams_.end()) {
1775 SpdyStreamId SpdySession::GetNewStreamId() {
1776 CHECK_LE(stream_hi_water_mark_, kLastStreamId);
1777 SpdyStreamId id = stream_hi_water_mark_;
1778 stream_hi_water_mark_ += 2;
1779 return id;
1782 void SpdySession::CloseSessionOnError(Error err,
1783 const std::string& description) {
1784 DCHECK_LT(err, ERR_IO_PENDING);
1785 DoDrainSession(err, description);
1788 void SpdySession::MakeUnavailable() {
1789 if (availability_state_ == STATE_AVAILABLE) {
1790 availability_state_ = STATE_GOING_AWAY;
1791 pool_->MakeSessionUnavailable(GetWeakPtr());
1795 base::Value* SpdySession::GetInfoAsValue() const {
1796 base::DictionaryValue* dict = new base::DictionaryValue();
1798 dict->SetInteger("source_id", net_log_.source().id);
1800 dict->SetString("host_port_pair", host_port_pair().ToString());
1801 if (!pooled_aliases_.empty()) {
1802 base::ListValue* alias_list = new base::ListValue();
1803 for (std::set<SpdySessionKey>::const_iterator it =
1804 pooled_aliases_.begin();
1805 it != pooled_aliases_.end(); it++) {
1806 alias_list->Append(new base::StringValue(
1807 it->host_port_pair().ToString()));
1809 dict->Set("aliases", alias_list);
1811 dict->SetString("proxy", host_port_proxy_pair().second.ToURI());
1813 dict->SetInteger("active_streams", active_streams_.size());
1815 dict->SetInteger("unclaimed_pushed_streams",
1816 unclaimed_pushed_streams_.size());
1818 dict->SetBoolean("is_secure", is_secure_);
1820 dict->SetString("protocol_negotiated",
1821 SSLClientSocket::NextProtoToString(
1822 connection_->socket()->GetNegotiatedProtocol()));
1824 dict->SetInteger("error", error_on_close_);
1825 dict->SetInteger("max_concurrent_streams", max_concurrent_streams_);
1827 dict->SetInteger("streams_initiated_count", streams_initiated_count_);
1828 dict->SetInteger("streams_pushed_count", streams_pushed_count_);
1829 dict->SetInteger("streams_pushed_and_claimed_count",
1830 streams_pushed_and_claimed_count_);
1831 dict->SetInteger("streams_abandoned_count", streams_abandoned_count_);
1832 DCHECK(buffered_spdy_framer_.get());
1833 dict->SetInteger("frames_received", buffered_spdy_framer_->frames_received());
1835 dict->SetBoolean("sent_settings", sent_settings_);
1836 dict->SetBoolean("received_settings", received_settings_);
1838 dict->SetInteger("send_window_size", session_send_window_size_);
1839 dict->SetInteger("recv_window_size", session_recv_window_size_);
1840 dict->SetInteger("unacked_recv_window_bytes",
1841 session_unacked_recv_window_bytes_);
1842 return dict;
1845 bool SpdySession::IsReused() const {
1846 return buffered_spdy_framer_->frames_received() > 0 ||
1847 connection_->reuse_type() == ClientSocketHandle::UNUSED_IDLE;
1850 bool SpdySession::GetLoadTimingInfo(SpdyStreamId stream_id,
1851 LoadTimingInfo* load_timing_info) const {
1852 return connection_->GetLoadTimingInfo(stream_id != kFirstStreamId,
1853 load_timing_info);
1856 int SpdySession::GetPeerAddress(IPEndPoint* address) const {
1857 int rv = ERR_SOCKET_NOT_CONNECTED;
1858 if (connection_->socket()) {
1859 rv = connection_->socket()->GetPeerAddress(address);
1862 UMA_HISTOGRAM_BOOLEAN("Net.SpdySessionSocketNotConnectedGetPeerAddress",
1863 rv == ERR_SOCKET_NOT_CONNECTED);
1865 return rv;
1868 int SpdySession::GetLocalAddress(IPEndPoint* address) const {
1869 int rv = ERR_SOCKET_NOT_CONNECTED;
1870 if (connection_->socket()) {
1871 rv = connection_->socket()->GetLocalAddress(address);
1874 UMA_HISTOGRAM_BOOLEAN("Net.SpdySessionSocketNotConnectedGetLocalAddress",
1875 rv == ERR_SOCKET_NOT_CONNECTED);
1877 return rv;
1880 void SpdySession::EnqueueSessionWrite(RequestPriority priority,
1881 SpdyFrameType frame_type,
1882 scoped_ptr<SpdyFrame> frame) {
1883 DCHECK(frame_type == RST_STREAM || frame_type == SETTINGS ||
1884 frame_type == WINDOW_UPDATE || frame_type == PING ||
1885 frame_type == GOAWAY);
1886 EnqueueWrite(
1887 priority, frame_type,
1888 scoped_ptr<SpdyBufferProducer>(
1889 new SimpleBufferProducer(
1890 scoped_ptr<SpdyBuffer>(new SpdyBuffer(frame.Pass())))),
1891 base::WeakPtr<SpdyStream>());
1894 void SpdySession::EnqueueWrite(RequestPriority priority,
1895 SpdyFrameType frame_type,
1896 scoped_ptr<SpdyBufferProducer> producer,
1897 const base::WeakPtr<SpdyStream>& stream) {
1898 if (availability_state_ == STATE_DRAINING)
1899 return;
1901 write_queue_.Enqueue(priority, frame_type, producer.Pass(), stream);
1902 MaybePostWriteLoop();
1905 void SpdySession::MaybePostWriteLoop() {
1906 if (write_state_ == WRITE_STATE_IDLE) {
1907 CHECK(!in_flight_write_);
1908 write_state_ = WRITE_STATE_DO_WRITE;
1909 base::MessageLoop::current()->PostTask(
1910 FROM_HERE,
1911 base::Bind(&SpdySession::PumpWriteLoop,
1912 weak_factory_.GetWeakPtr(), WRITE_STATE_DO_WRITE, OK));
1916 void SpdySession::InsertCreatedStream(scoped_ptr<SpdyStream> stream) {
1917 CHECK_EQ(stream->stream_id(), 0u);
1918 CHECK(created_streams_.find(stream.get()) == created_streams_.end());
1919 created_streams_.insert(stream.release());
1922 scoped_ptr<SpdyStream> SpdySession::ActivateCreatedStream(SpdyStream* stream) {
1923 CHECK_EQ(stream->stream_id(), 0u);
1924 CHECK(created_streams_.find(stream) != created_streams_.end());
1925 stream->set_stream_id(GetNewStreamId());
1926 scoped_ptr<SpdyStream> owned_stream(stream);
1927 created_streams_.erase(stream);
1928 return owned_stream.Pass();
1931 void SpdySession::InsertActivatedStream(scoped_ptr<SpdyStream> stream) {
1932 SpdyStreamId stream_id = stream->stream_id();
1933 CHECK_NE(stream_id, 0u);
1934 std::pair<ActiveStreamMap::iterator, bool> result =
1935 active_streams_.insert(
1936 std::make_pair(stream_id, ActiveStreamInfo(stream.get())));
1937 CHECK(result.second);
1938 ignore_result(stream.release());
1941 void SpdySession::DeleteStream(scoped_ptr<SpdyStream> stream, int status) {
1942 if (in_flight_write_stream_.get() == stream.get()) {
1943 // If we're deleting the stream for the in-flight write, we still
1944 // need to let the write complete, so we clear
1945 // |in_flight_write_stream_| and let the write finish on its own
1946 // without notifying |in_flight_write_stream_|.
1947 in_flight_write_stream_.reset();
1950 write_queue_.RemovePendingWritesForStream(stream->GetWeakPtr());
1951 stream->OnClose(status);
1953 if (availability_state_ == STATE_AVAILABLE) {
1954 ProcessPendingStreamRequests();
1958 base::WeakPtr<SpdyStream> SpdySession::GetActivePushStream(const GURL& url) {
1959 PushedStreamMap::iterator unclaimed_it = unclaimed_pushed_streams_.find(url);
1960 if (unclaimed_it == unclaimed_pushed_streams_.end())
1961 return base::WeakPtr<SpdyStream>();
1963 SpdyStreamId stream_id = unclaimed_it->second.stream_id;
1964 unclaimed_pushed_streams_.erase(unclaimed_it);
1966 ActiveStreamMap::iterator active_it = active_streams_.find(stream_id);
1967 if (active_it == active_streams_.end()) {
1968 NOTREACHED();
1969 return base::WeakPtr<SpdyStream>();
1972 net_log_.AddEvent(NetLog::TYPE_HTTP2_STREAM_ADOPTED_PUSH_STREAM,
1973 base::Bind(&NetLogSpdyAdoptedPushStreamCallback,
1974 active_it->second.stream->stream_id(), &url));
1975 return active_it->second.stream->GetWeakPtr();
1978 bool SpdySession::GetSSLInfo(SSLInfo* ssl_info,
1979 bool* was_npn_negotiated,
1980 NextProto* protocol_negotiated) {
1981 *was_npn_negotiated = connection_->socket()->WasNpnNegotiated();
1982 *protocol_negotiated = connection_->socket()->GetNegotiatedProtocol();
1983 return connection_->socket()->GetSSLInfo(ssl_info);
1986 bool SpdySession::GetSSLCertRequestInfo(
1987 SSLCertRequestInfo* cert_request_info) {
1988 if (!is_secure_)
1989 return false;
1990 GetSSLClientSocket()->GetSSLCertRequestInfo(cert_request_info);
1991 return true;
1994 void SpdySession::OnError(SpdyFramer::SpdyError error_code) {
1995 CHECK(in_io_loop_);
1997 RecordProtocolErrorHistogram(MapFramerErrorToProtocolError(error_code));
1998 std::string description =
1999 base::StringPrintf("Framer error: %d (%s).",
2000 error_code,
2001 SpdyFramer::ErrorCodeToString(error_code));
2002 DoDrainSession(MapFramerErrorToNetError(error_code), description);
2005 void SpdySession::OnStreamError(SpdyStreamId stream_id,
2006 const std::string& description) {
2007 CHECK(in_io_loop_);
2009 ActiveStreamMap::iterator it = active_streams_.find(stream_id);
2010 if (it == active_streams_.end()) {
2011 // We still want to send a frame to reset the stream even if we
2012 // don't know anything about it.
2013 EnqueueResetStreamFrame(
2014 stream_id, IDLE, RST_STREAM_PROTOCOL_ERROR, description);
2015 return;
2018 ResetStreamIterator(it, RST_STREAM_PROTOCOL_ERROR, description);
2021 void SpdySession::OnDataFrameHeader(SpdyStreamId stream_id,
2022 size_t length,
2023 bool fin) {
2024 CHECK(in_io_loop_);
2026 ActiveStreamMap::iterator it = active_streams_.find(stream_id);
2028 // By the time data comes in, the stream may already be inactive.
2029 if (it == active_streams_.end())
2030 return;
2032 SpdyStream* stream = it->second.stream;
2033 CHECK_EQ(stream->stream_id(), stream_id);
2035 DCHECK(buffered_spdy_framer_);
2036 size_t header_len = buffered_spdy_framer_->GetDataFrameMinimumSize();
2037 stream->IncrementRawReceivedBytes(header_len);
2040 void SpdySession::OnStreamFrameData(SpdyStreamId stream_id,
2041 const char* data,
2042 size_t len,
2043 bool fin) {
2044 CHECK(in_io_loop_);
2045 DCHECK_LT(len, 1u << 24);
2046 if (net_log().IsLogging()) {
2047 net_log().AddEvent(
2048 NetLog::TYPE_HTTP2_SESSION_RECV_DATA,
2049 base::Bind(&NetLogSpdyDataCallback, stream_id, len, fin));
2052 // Build the buffer as early as possible so that we go through the
2053 // session flow control checks and update
2054 // |unacked_recv_window_bytes_| properly even when the stream is
2055 // inactive (since the other side has still reduced its session send
2056 // window).
2057 scoped_ptr<SpdyBuffer> buffer;
2058 if (data) {
2059 DCHECK_GT(len, 0u);
2060 CHECK_LE(len, static_cast<size_t>(kReadBufferSize));
2061 buffer.reset(new SpdyBuffer(data, len));
2063 if (flow_control_state_ == FLOW_CONTROL_STREAM_AND_SESSION) {
2064 DecreaseRecvWindowSize(static_cast<int32>(len));
2065 buffer->AddConsumeCallback(
2066 base::Bind(&SpdySession::OnReadBufferConsumed,
2067 weak_factory_.GetWeakPtr()));
2069 } else {
2070 DCHECK_EQ(len, 0u);
2073 ActiveStreamMap::iterator it = active_streams_.find(stream_id);
2075 // By the time data comes in, the stream may already be inactive.
2076 if (it == active_streams_.end())
2077 return;
2079 SpdyStream* stream = it->second.stream;
2080 CHECK_EQ(stream->stream_id(), stream_id);
2082 stream->IncrementRawReceivedBytes(len);
2084 if (it->second.waiting_for_syn_reply) {
2085 const std::string& error = "Data received before SYN_REPLY.";
2086 stream->LogStreamError(ERR_SPDY_PROTOCOL_ERROR, error);
2087 ResetStreamIterator(it, RST_STREAM_PROTOCOL_ERROR, error);
2088 return;
2091 stream->OnDataReceived(buffer.Pass());
2094 void SpdySession::OnStreamPadding(SpdyStreamId stream_id, size_t len) {
2095 CHECK(in_io_loop_);
2097 if (flow_control_state_ != FLOW_CONTROL_STREAM_AND_SESSION)
2098 return;
2100 // Decrease window size because padding bytes are received.
2101 // Increase window size because padding bytes are consumed (by discarding).
2102 // Net result: |session_unacked_recv_window_bytes_| increases by |len|,
2103 // |session_recv_window_size_| does not change.
2104 DecreaseRecvWindowSize(static_cast<int32>(len));
2105 IncreaseRecvWindowSize(static_cast<int32>(len));
2107 ActiveStreamMap::iterator it = active_streams_.find(stream_id);
2108 if (it == active_streams_.end())
2109 return;
2110 it->second.stream->OnPaddingConsumed(len);
2113 void SpdySession::OnSettings(bool clear_persisted) {
2114 CHECK(in_io_loop_);
2116 if (clear_persisted)
2117 http_server_properties_->ClearSpdySettings(host_port_pair());
2119 if (net_log_.IsLogging()) {
2120 net_log_.AddEvent(NetLog::TYPE_HTTP2_SESSION_RECV_SETTINGS,
2121 base::Bind(&NetLogSpdySettingsCallback, host_port_pair(),
2122 clear_persisted));
2125 if (GetProtocolVersion() >= SPDY4) {
2126 // Send an acknowledgment of the setting.
2127 SpdySettingsIR settings_ir;
2128 settings_ir.set_is_ack(true);
2129 EnqueueSessionWrite(
2130 HIGHEST,
2131 SETTINGS,
2132 scoped_ptr<SpdyFrame>(
2133 buffered_spdy_framer_->SerializeFrame(settings_ir)));
2137 void SpdySession::OnSetting(SpdySettingsIds id,
2138 uint8 flags,
2139 uint32 value) {
2140 CHECK(in_io_loop_);
2142 HandleSetting(id, value);
2143 http_server_properties_->SetSpdySetting(
2144 host_port_pair(),
2146 static_cast<SpdySettingsFlags>(flags),
2147 value);
2148 received_settings_ = true;
2150 // Log the setting.
2151 const SpdyMajorVersion protocol_version = GetProtocolVersion();
2152 net_log_.AddEvent(NetLog::TYPE_HTTP2_SESSION_RECV_SETTING,
2153 base::Bind(&NetLogSpdySettingCallback, id, protocol_version,
2154 static_cast<SpdySettingsFlags>(flags), value));
2157 void SpdySession::OnSendCompressedFrame(
2158 SpdyStreamId stream_id,
2159 SpdyFrameType type,
2160 size_t payload_len,
2161 size_t frame_len) {
2162 if (type != SYN_STREAM && type != HEADERS)
2163 return;
2165 DCHECK(buffered_spdy_framer_.get());
2166 size_t compressed_len =
2167 frame_len - buffered_spdy_framer_->GetSynStreamMinimumSize();
2169 if (payload_len) {
2170 // Make sure we avoid early decimal truncation.
2171 int compression_pct = 100 - (100 * compressed_len) / payload_len;
2172 UMA_HISTOGRAM_PERCENTAGE("Net.SpdySynStreamCompressionPercentage",
2173 compression_pct);
2177 void SpdySession::OnReceiveCompressedFrame(
2178 SpdyStreamId stream_id,
2179 SpdyFrameType type,
2180 size_t frame_len) {
2181 last_compressed_frame_len_ = frame_len;
2184 int SpdySession::OnInitialResponseHeadersReceived(
2185 const SpdyHeaderBlock& response_headers,
2186 base::Time response_time,
2187 base::TimeTicks recv_first_byte_time,
2188 SpdyStream* stream) {
2189 CHECK(in_io_loop_);
2190 SpdyStreamId stream_id = stream->stream_id();
2192 if (stream->type() == SPDY_PUSH_STREAM) {
2193 DCHECK(stream->IsReservedRemote());
2194 if (max_concurrent_pushed_streams_ &&
2195 num_active_pushed_streams_ >= max_concurrent_pushed_streams_) {
2196 ResetStream(stream_id,
2197 RST_STREAM_REFUSED_STREAM,
2198 "Stream concurrency limit reached.");
2199 return STATUS_CODE_REFUSED_STREAM;
2203 if (stream->type() == SPDY_PUSH_STREAM) {
2204 // Will be balanced in DeleteStream.
2205 num_active_pushed_streams_++;
2208 // May invalidate |stream|.
2209 int rv = stream->OnInitialResponseHeadersReceived(
2210 response_headers, response_time, recv_first_byte_time);
2211 if (rv < 0) {
2212 DCHECK_NE(rv, ERR_IO_PENDING);
2213 DCHECK(active_streams_.find(stream_id) == active_streams_.end());
2216 return rv;
2219 void SpdySession::OnSynStream(SpdyStreamId stream_id,
2220 SpdyStreamId associated_stream_id,
2221 SpdyPriority priority,
2222 bool fin,
2223 bool unidirectional,
2224 const SpdyHeaderBlock& headers) {
2225 CHECK(in_io_loop_);
2227 DCHECK_LE(GetProtocolVersion(), SPDY3);
2229 base::Time response_time = base::Time::Now();
2230 base::TimeTicks recv_first_byte_time = time_func_();
2232 if (net_log_.IsLogging()) {
2233 net_log_.AddEvent(
2234 NetLog::TYPE_HTTP2_SESSION_PUSHED_SYN_STREAM,
2235 base::Bind(&NetLogSpdySynStreamReceivedCallback, &headers, fin,
2236 unidirectional, priority, stream_id, associated_stream_id));
2239 // Split headers to simulate push promise and response.
2240 SpdyHeaderBlock request_headers;
2241 SpdyHeaderBlock response_headers;
2242 SplitPushedHeadersToRequestAndResponse(
2243 headers, GetProtocolVersion(), &request_headers, &response_headers);
2245 if (!TryCreatePushStream(
2246 stream_id, associated_stream_id, priority, request_headers))
2247 return;
2249 ActiveStreamMap::iterator active_it = active_streams_.find(stream_id);
2250 if (active_it == active_streams_.end()) {
2251 NOTREACHED();
2252 return;
2255 OnInitialResponseHeadersReceived(response_headers, response_time,
2256 recv_first_byte_time,
2257 active_it->second.stream);
2260 void SpdySession::DeleteExpiredPushedStreams() {
2261 if (unclaimed_pushed_streams_.empty())
2262 return;
2264 // Check that adequate time has elapsed since the last sweep.
2265 if (time_func_() < next_unclaimed_push_stream_sweep_time_)
2266 return;
2268 // Gather old streams to delete.
2269 base::TimeTicks minimum_freshness = time_func_() -
2270 base::TimeDelta::FromSeconds(kMinPushedStreamLifetimeSeconds);
2271 std::vector<SpdyStreamId> streams_to_close;
2272 for (PushedStreamMap::iterator it = unclaimed_pushed_streams_.begin();
2273 it != unclaimed_pushed_streams_.end(); ++it) {
2274 if (minimum_freshness > it->second.creation_time)
2275 streams_to_close.push_back(it->second.stream_id);
2278 for (std::vector<SpdyStreamId>::const_iterator to_close_it =
2279 streams_to_close.begin();
2280 to_close_it != streams_to_close.end(); ++to_close_it) {
2281 ActiveStreamMap::iterator active_it = active_streams_.find(*to_close_it);
2282 if (active_it == active_streams_.end())
2283 continue;
2285 LogAbandonedActiveStream(active_it, ERR_INVALID_SPDY_STREAM);
2286 // CloseActiveStreamIterator() will remove the stream from
2287 // |unclaimed_pushed_streams_|.
2288 ResetStreamIterator(
2289 active_it, RST_STREAM_REFUSED_STREAM, "Stream not claimed.");
2292 next_unclaimed_push_stream_sweep_time_ = time_func_() +
2293 base::TimeDelta::FromSeconds(kMinPushedStreamLifetimeSeconds);
2296 void SpdySession::OnSynReply(SpdyStreamId stream_id,
2297 bool fin,
2298 const SpdyHeaderBlock& headers) {
2299 CHECK(in_io_loop_);
2301 base::Time response_time = base::Time::Now();
2302 base::TimeTicks recv_first_byte_time = time_func_();
2304 if (net_log().IsLogging()) {
2305 net_log().AddEvent(NetLog::TYPE_HTTP2_SESSION_SYN_REPLY,
2306 base::Bind(&NetLogSpdySynReplyOrHeadersReceivedCallback,
2307 &headers, fin, stream_id));
2310 ActiveStreamMap::iterator it = active_streams_.find(stream_id);
2311 if (it == active_streams_.end()) {
2312 // NOTE: it may just be that the stream was cancelled.
2313 return;
2316 SpdyStream* stream = it->second.stream;
2317 CHECK_EQ(stream->stream_id(), stream_id);
2319 stream->IncrementRawReceivedBytes(last_compressed_frame_len_);
2320 last_compressed_frame_len_ = 0;
2322 if (GetProtocolVersion() >= SPDY4) {
2323 const std::string& error =
2324 "SPDY4 wasn't expecting SYN_REPLY.";
2325 stream->LogStreamError(ERR_SPDY_PROTOCOL_ERROR, error);
2326 ResetStreamIterator(it, RST_STREAM_PROTOCOL_ERROR, error);
2327 return;
2329 if (!it->second.waiting_for_syn_reply) {
2330 const std::string& error =
2331 "Received duplicate SYN_REPLY for stream.";
2332 stream->LogStreamError(ERR_SPDY_PROTOCOL_ERROR, error);
2333 ResetStreamIterator(it, RST_STREAM_PROTOCOL_ERROR, error);
2334 return;
2336 it->second.waiting_for_syn_reply = false;
2338 ignore_result(OnInitialResponseHeadersReceived(
2339 headers, response_time, recv_first_byte_time, stream));
2342 void SpdySession::OnHeaders(SpdyStreamId stream_id,
2343 bool has_priority,
2344 SpdyPriority priority,
2345 bool fin,
2346 const SpdyHeaderBlock& headers) {
2347 CHECK(in_io_loop_);
2349 if (net_log().IsLogging()) {
2350 net_log().AddEvent(NetLog::TYPE_HTTP2_SESSION_RECV_HEADERS,
2351 base::Bind(&NetLogSpdySynReplyOrHeadersReceivedCallback,
2352 &headers, fin, stream_id));
2355 ActiveStreamMap::iterator it = active_streams_.find(stream_id);
2356 if (it == active_streams_.end()) {
2357 // NOTE: it may just be that the stream was cancelled.
2358 LOG(WARNING) << "Received HEADERS for invalid stream " << stream_id;
2359 return;
2362 SpdyStream* stream = it->second.stream;
2363 CHECK_EQ(stream->stream_id(), stream_id);
2365 stream->IncrementRawReceivedBytes(last_compressed_frame_len_);
2366 last_compressed_frame_len_ = 0;
2368 base::Time response_time = base::Time::Now();
2369 base::TimeTicks recv_first_byte_time = time_func_();
2371 if (it->second.waiting_for_syn_reply) {
2372 if (GetProtocolVersion() < SPDY4) {
2373 const std::string& error =
2374 "Was expecting SYN_REPLY, not HEADERS.";
2375 stream->LogStreamError(ERR_SPDY_PROTOCOL_ERROR, error);
2376 ResetStreamIterator(it, RST_STREAM_PROTOCOL_ERROR, error);
2377 return;
2380 it->second.waiting_for_syn_reply = false;
2381 ignore_result(OnInitialResponseHeadersReceived(
2382 headers, response_time, recv_first_byte_time, stream));
2383 } else if (it->second.stream->IsReservedRemote()) {
2384 ignore_result(OnInitialResponseHeadersReceived(
2385 headers, response_time, recv_first_byte_time, stream));
2386 } else {
2387 int rv = stream->OnAdditionalResponseHeadersReceived(headers);
2388 if (rv < 0) {
2389 DCHECK_NE(rv, ERR_IO_PENDING);
2390 DCHECK(active_streams_.find(stream_id) == active_streams_.end());
2395 bool SpdySession::OnUnknownFrame(SpdyStreamId stream_id, int frame_type) {
2396 // Validate stream id.
2397 // Was the frame sent on a stream id that has not been used in this session?
2398 if (stream_id % 2 == 1 && stream_id > stream_hi_water_mark_)
2399 return false;
2401 if (stream_id % 2 == 0 && stream_id > last_accepted_push_stream_id_)
2402 return false;
2404 return true;
2407 void SpdySession::OnRstStream(SpdyStreamId stream_id,
2408 SpdyRstStreamStatus status) {
2409 CHECK(in_io_loop_);
2411 std::string description;
2412 net_log().AddEvent(
2413 NetLog::TYPE_HTTP2_SESSION_RST_STREAM,
2414 base::Bind(&NetLogSpdyRstCallback, stream_id, status, &description));
2416 ActiveStreamMap::iterator it = active_streams_.find(stream_id);
2417 if (it == active_streams_.end()) {
2418 // NOTE: it may just be that the stream was cancelled.
2419 LOG(WARNING) << "Received RST for invalid stream" << stream_id;
2420 return;
2423 CHECK_EQ(it->second.stream->stream_id(), stream_id);
2425 if (status == 0) {
2426 it->second.stream->OnDataReceived(scoped_ptr<SpdyBuffer>());
2427 } else if (status == RST_STREAM_REFUSED_STREAM) {
2428 CloseActiveStreamIterator(it, ERR_SPDY_SERVER_REFUSED_STREAM);
2429 } else if (status == RST_STREAM_HTTP_1_1_REQUIRED) {
2430 // TODO(bnc): Record histogram with number of open streams capped at 50.
2431 it->second.stream->LogStreamError(
2432 ERR_HTTP_1_1_REQUIRED,
2433 base::StringPrintf(
2434 "SPDY session closed because of stream with status: %d", status));
2435 DoDrainSession(ERR_HTTP_1_1_REQUIRED, "HTTP_1_1_REQUIRED for stream.");
2436 } else {
2437 RecordProtocolErrorHistogram(
2438 PROTOCOL_ERROR_RST_STREAM_FOR_NON_ACTIVE_STREAM);
2439 it->second.stream->LogStreamError(
2440 ERR_SPDY_PROTOCOL_ERROR,
2441 base::StringPrintf("SPDY stream closed with status: %d", status));
2442 // TODO(mbelshe): Map from Spdy-protocol errors to something sensical.
2443 // For now, it doesn't matter much - it is a protocol error.
2444 CloseActiveStreamIterator(it, ERR_SPDY_PROTOCOL_ERROR);
2448 void SpdySession::OnGoAway(SpdyStreamId last_accepted_stream_id,
2449 SpdyGoAwayStatus status) {
2450 CHECK(in_io_loop_);
2452 // TODO(jgraettinger): UMA histogram on |status|.
2454 net_log_.AddEvent(NetLog::TYPE_HTTP2_SESSION_GOAWAY,
2455 base::Bind(&NetLogSpdyGoAwayCallback,
2456 last_accepted_stream_id, active_streams_.size(),
2457 unclaimed_pushed_streams_.size(), status));
2458 MakeUnavailable();
2459 if (status == GOAWAY_HTTP_1_1_REQUIRED) {
2460 // TODO(bnc): Record histogram with number of open streams capped at 50.
2461 DoDrainSession(ERR_HTTP_1_1_REQUIRED, "HTTP_1_1_REQUIRED for stream.");
2462 } else {
2463 StartGoingAway(last_accepted_stream_id, ERR_ABORTED);
2465 // This is to handle the case when we already don't have any active
2466 // streams (i.e., StartGoingAway() did nothing). Otherwise, we have
2467 // active streams and so the last one being closed will finish the
2468 // going away process (see DeleteStream()).
2469 MaybeFinishGoingAway();
2472 void SpdySession::OnPing(SpdyPingId unique_id, bool is_ack) {
2473 CHECK(in_io_loop_);
2475 net_log_.AddEvent(
2476 NetLog::TYPE_HTTP2_SESSION_PING,
2477 base::Bind(&NetLogSpdyPingCallback, unique_id, is_ack, "received"));
2479 // Send response to a PING from server.
2480 if ((protocol_ >= kProtoSPDY4MinimumVersion && !is_ack) ||
2481 (protocol_ < kProtoSPDY4MinimumVersion && unique_id % 2 == 0)) {
2482 WritePingFrame(unique_id, true);
2483 return;
2486 --pings_in_flight_;
2487 if (pings_in_flight_ < 0) {
2488 RecordProtocolErrorHistogram(PROTOCOL_ERROR_UNEXPECTED_PING);
2489 DoDrainSession(ERR_SPDY_PROTOCOL_ERROR, "pings_in_flight_ is < 0.");
2490 pings_in_flight_ = 0;
2491 return;
2494 if (pings_in_flight_ > 0)
2495 return;
2497 // We will record RTT in histogram when there are no more client sent
2498 // pings_in_flight_.
2499 RecordPingRTTHistogram(time_func_() - last_ping_sent_time_);
2502 void SpdySession::OnWindowUpdate(SpdyStreamId stream_id,
2503 uint32 delta_window_size) {
2504 CHECK(in_io_loop_);
2506 DCHECK_LE(delta_window_size, static_cast<uint32>(kint32max));
2507 net_log_.AddEvent(NetLog::TYPE_HTTP2_SESSION_RECEIVED_WINDOW_UPDATE_FRAME,
2508 base::Bind(&NetLogSpdyWindowUpdateFrameCallback, stream_id,
2509 delta_window_size));
2511 if (stream_id == kSessionFlowControlStreamId) {
2512 // WINDOW_UPDATE for the session.
2513 if (flow_control_state_ < FLOW_CONTROL_STREAM_AND_SESSION) {
2514 LOG(WARNING) << "Received WINDOW_UPDATE for session when "
2515 << "session flow control is not turned on";
2516 // TODO(akalin): Record an error and close the session.
2517 return;
2520 if (delta_window_size < 1u) {
2521 RecordProtocolErrorHistogram(PROTOCOL_ERROR_INVALID_WINDOW_UPDATE_SIZE);
2522 DoDrainSession(
2523 ERR_SPDY_PROTOCOL_ERROR,
2524 "Received WINDOW_UPDATE with an invalid delta_window_size " +
2525 base::UintToString(delta_window_size));
2526 return;
2529 IncreaseSendWindowSize(static_cast<int32>(delta_window_size));
2530 } else {
2531 // WINDOW_UPDATE for a stream.
2532 if (flow_control_state_ < FLOW_CONTROL_STREAM) {
2533 // TODO(akalin): Record an error and close the session.
2534 LOG(WARNING) << "Received WINDOW_UPDATE for stream " << stream_id
2535 << " when flow control is not turned on";
2536 return;
2539 ActiveStreamMap::iterator it = active_streams_.find(stream_id);
2541 if (it == active_streams_.end()) {
2542 // NOTE: it may just be that the stream was cancelled.
2543 LOG(WARNING) << "Received WINDOW_UPDATE for invalid stream " << stream_id;
2544 return;
2547 SpdyStream* stream = it->second.stream;
2548 CHECK_EQ(stream->stream_id(), stream_id);
2550 if (delta_window_size < 1u) {
2551 ResetStreamIterator(it,
2552 RST_STREAM_FLOW_CONTROL_ERROR,
2553 base::StringPrintf(
2554 "Received WINDOW_UPDATE with an invalid "
2555 "delta_window_size %ud", delta_window_size));
2556 return;
2559 CHECK_EQ(it->second.stream->stream_id(), stream_id);
2560 it->second.stream->IncreaseSendWindowSize(
2561 static_cast<int32>(delta_window_size));
2565 bool SpdySession::TryCreatePushStream(SpdyStreamId stream_id,
2566 SpdyStreamId associated_stream_id,
2567 SpdyPriority priority,
2568 const SpdyHeaderBlock& headers) {
2569 // Server-initiated streams should have even sequence numbers.
2570 if ((stream_id & 0x1) != 0) {
2571 LOG(WARNING) << "Received invalid push stream id " << stream_id;
2572 if (GetProtocolVersion() > SPDY2)
2573 CloseSessionOnError(ERR_SPDY_PROTOCOL_ERROR, "Odd push stream id.");
2574 return false;
2577 if (GetProtocolVersion() > SPDY2) {
2578 if (stream_id <= last_accepted_push_stream_id_) {
2579 LOG(WARNING) << "Received push stream id lesser or equal to the last "
2580 << "accepted before " << stream_id;
2581 CloseSessionOnError(
2582 ERR_SPDY_PROTOCOL_ERROR,
2583 "New push stream id must be greater than the last accepted.");
2584 return false;
2588 if (IsStreamActive(stream_id)) {
2589 // For SPDY3 and higher we should not get here, we'll start going away
2590 // earlier on |last_seen_push_stream_id_| check.
2591 CHECK_GT(SPDY3, GetProtocolVersion());
2592 LOG(WARNING) << "Received push for active stream " << stream_id;
2593 return false;
2596 last_accepted_push_stream_id_ = stream_id;
2598 RequestPriority request_priority =
2599 ConvertSpdyPriorityToRequestPriority(priority, GetProtocolVersion());
2601 if (availability_state_ == STATE_GOING_AWAY) {
2602 // TODO(akalin): This behavior isn't in the SPDY spec, although it
2603 // probably should be.
2604 EnqueueResetStreamFrame(stream_id,
2605 request_priority,
2606 RST_STREAM_REFUSED_STREAM,
2607 "push stream request received when going away");
2608 return false;
2611 if (associated_stream_id == 0) {
2612 // In SPDY4 0 stream id in PUSH_PROMISE frame leads to framer error and
2613 // session going away. We should never get here.
2614 CHECK_GT(SPDY4, GetProtocolVersion());
2615 std::string description = base::StringPrintf(
2616 "Received invalid associated stream id %d for pushed stream %d",
2617 associated_stream_id,
2618 stream_id);
2619 EnqueueResetStreamFrame(
2620 stream_id, request_priority, RST_STREAM_REFUSED_STREAM, description);
2621 return false;
2624 streams_pushed_count_++;
2626 // TODO(mbelshe): DCHECK that this is a GET method?
2628 // Verify that the response had a URL for us.
2629 GURL gurl = GetUrlFromHeaderBlock(headers, GetProtocolVersion(), true);
2630 if (!gurl.is_valid()) {
2631 EnqueueResetStreamFrame(stream_id,
2632 request_priority,
2633 RST_STREAM_PROTOCOL_ERROR,
2634 "Pushed stream url was invalid: " + gurl.spec());
2635 return false;
2638 // Verify we have a valid stream association.
2639 ActiveStreamMap::iterator associated_it =
2640 active_streams_.find(associated_stream_id);
2641 if (associated_it == active_streams_.end()) {
2642 EnqueueResetStreamFrame(
2643 stream_id,
2644 request_priority,
2645 RST_STREAM_INVALID_STREAM,
2646 base::StringPrintf("Received push for inactive associated stream %d",
2647 associated_stream_id));
2648 return false;
2651 // Check that the pushed stream advertises the same origin as its associated
2652 // stream. Bypass this check if and only if this session is with a SPDY proxy
2653 // that is trusted explicitly via the --trusted-spdy-proxy switch.
2654 if (trusted_spdy_proxy_.Equals(host_port_pair())) {
2655 // Disallow pushing of HTTPS content.
2656 if (gurl.SchemeIs("https")) {
2657 EnqueueResetStreamFrame(
2658 stream_id,
2659 request_priority,
2660 RST_STREAM_REFUSED_STREAM,
2661 base::StringPrintf("Rejected push of Cross Origin HTTPS content %d",
2662 associated_stream_id));
2664 } else {
2665 GURL associated_url(associated_it->second.stream->GetUrlFromHeaders());
2666 if (associated_url.GetOrigin() != gurl.GetOrigin()) {
2667 EnqueueResetStreamFrame(
2668 stream_id,
2669 request_priority,
2670 RST_STREAM_REFUSED_STREAM,
2671 base::StringPrintf("Rejected Cross Origin Push Stream %d",
2672 associated_stream_id));
2673 return false;
2677 // There should not be an existing pushed stream with the same path.
2678 PushedStreamMap::iterator pushed_it =
2679 unclaimed_pushed_streams_.lower_bound(gurl);
2680 if (pushed_it != unclaimed_pushed_streams_.end() &&
2681 pushed_it->first == gurl) {
2682 EnqueueResetStreamFrame(
2683 stream_id,
2684 request_priority,
2685 RST_STREAM_PROTOCOL_ERROR,
2686 "Received duplicate pushed stream with url: " + gurl.spec());
2687 return false;
2690 scoped_ptr<SpdyStream> stream(new SpdyStream(SPDY_PUSH_STREAM,
2691 GetWeakPtr(),
2692 gurl,
2693 request_priority,
2694 stream_initial_send_window_size_,
2695 stream_initial_recv_window_size_,
2696 net_log_));
2697 stream->set_stream_id(stream_id);
2699 // In spdy4/http2 PUSH_PROMISE arrives on associated stream.
2700 if (associated_it != active_streams_.end() && GetProtocolVersion() >= SPDY4) {
2701 associated_it->second.stream->IncrementRawReceivedBytes(
2702 last_compressed_frame_len_);
2703 } else {
2704 stream->IncrementRawReceivedBytes(last_compressed_frame_len_);
2707 last_compressed_frame_len_ = 0;
2709 PushedStreamMap::iterator inserted_pushed_it =
2710 unclaimed_pushed_streams_.insert(
2711 pushed_it,
2712 std::make_pair(gurl, PushedStreamInfo(stream_id, time_func_())));
2713 DCHECK(inserted_pushed_it != pushed_it);
2714 DeleteExpiredPushedStreams();
2716 InsertActivatedStream(stream.Pass());
2718 ActiveStreamMap::iterator active_it = active_streams_.find(stream_id);
2719 if (active_it == active_streams_.end()) {
2720 NOTREACHED();
2721 return false;
2724 active_it->second.stream->OnPushPromiseHeadersReceived(headers);
2725 DCHECK(active_it->second.stream->IsReservedRemote());
2726 num_pushed_streams_++;
2727 return true;
2730 void SpdySession::OnPushPromise(SpdyStreamId stream_id,
2731 SpdyStreamId promised_stream_id,
2732 const SpdyHeaderBlock& headers) {
2733 CHECK(in_io_loop_);
2735 if (net_log_.IsLogging()) {
2736 net_log_.AddEvent(NetLog::TYPE_HTTP2_SESSION_RECV_PUSH_PROMISE,
2737 base::Bind(&NetLogSpdyPushPromiseReceivedCallback,
2738 &headers, stream_id, promised_stream_id));
2741 // Any priority will do.
2742 // TODO(baranovich): pass parent stream id priority?
2743 if (!TryCreatePushStream(promised_stream_id, stream_id, 0, headers))
2744 return;
2747 void SpdySession::SendStreamWindowUpdate(SpdyStreamId stream_id,
2748 uint32 delta_window_size) {
2749 CHECK_GE(flow_control_state_, FLOW_CONTROL_STREAM);
2750 ActiveStreamMap::const_iterator it = active_streams_.find(stream_id);
2751 CHECK(it != active_streams_.end());
2752 CHECK_EQ(it->second.stream->stream_id(), stream_id);
2753 SendWindowUpdateFrame(
2754 stream_id, delta_window_size, it->second.stream->priority());
2757 void SpdySession::SendInitialData() {
2758 DCHECK(enable_sending_initial_data_);
2760 if (send_connection_header_prefix_) {
2761 DCHECK_GE(protocol_, kProtoSPDY4MinimumVersion);
2762 DCHECK_LE(protocol_, kProtoSPDY4MaximumVersion);
2763 scoped_ptr<SpdyFrame> connection_header_prefix_frame(
2764 new SpdyFrame(const_cast<char*>(kHttp2ConnectionHeaderPrefix),
2765 kHttp2ConnectionHeaderPrefixSize,
2766 false /* take_ownership */));
2767 // Count the prefix as part of the subsequent SETTINGS frame.
2768 EnqueueSessionWrite(HIGHEST, SETTINGS,
2769 connection_header_prefix_frame.Pass());
2772 // First, notify the server about the settings they should use when
2773 // communicating with us.
2774 SettingsMap settings_map;
2775 // Create a new settings frame notifying the server of our
2776 // max concurrent streams and initial window size.
2777 settings_map[SETTINGS_MAX_CONCURRENT_STREAMS] =
2778 SettingsFlagsAndValue(SETTINGS_FLAG_NONE, kMaxConcurrentPushedStreams);
2779 if (flow_control_state_ >= FLOW_CONTROL_STREAM &&
2780 stream_initial_recv_window_size_ != GetInitialWindowSize(protocol_)) {
2781 settings_map[SETTINGS_INITIAL_WINDOW_SIZE] =
2782 SettingsFlagsAndValue(SETTINGS_FLAG_NONE,
2783 stream_initial_recv_window_size_);
2785 SendSettings(settings_map);
2787 // Next, notify the server about our initial recv window size.
2788 if (flow_control_state_ == FLOW_CONTROL_STREAM_AND_SESSION) {
2789 // Bump up the receive window size to the real initial value. This
2790 // has to go here since the WINDOW_UPDATE frame sent by
2791 // IncreaseRecvWindowSize() call uses |buffered_spdy_framer_|.
2792 DCHECK_GT(kDefaultInitialRecvWindowSize, session_recv_window_size_);
2793 // This condition implies that |kDefaultInitialRecvWindowSize| -
2794 // |session_recv_window_size_| doesn't overflow.
2795 DCHECK_GT(session_recv_window_size_, 0);
2796 IncreaseRecvWindowSize(
2797 kDefaultInitialRecvWindowSize - session_recv_window_size_);
2800 if (protocol_ <= kProtoSPDY31) {
2801 // Finally, notify the server about the settings they have
2802 // previously told us to use when communicating with them (after
2803 // applying them).
2804 const SettingsMap& server_settings_map =
2805 http_server_properties_->GetSpdySettings(host_port_pair());
2806 if (server_settings_map.empty())
2807 return;
2809 SettingsMap::const_iterator it =
2810 server_settings_map.find(SETTINGS_CURRENT_CWND);
2811 uint32 cwnd = (it != server_settings_map.end()) ? it->second.second : 0;
2812 UMA_HISTOGRAM_CUSTOM_COUNTS("Net.SpdySettingsCwndSent", cwnd, 1, 200, 100);
2814 for (SettingsMap::const_iterator it = server_settings_map.begin();
2815 it != server_settings_map.end(); ++it) {
2816 const SpdySettingsIds new_id = it->first;
2817 const uint32 new_val = it->second.second;
2818 HandleSetting(new_id, new_val);
2821 SendSettings(server_settings_map);
2826 void SpdySession::SendSettings(const SettingsMap& settings) {
2827 const SpdyMajorVersion protocol_version = GetProtocolVersion();
2828 net_log_.AddEvent(
2829 NetLog::TYPE_HTTP2_SESSION_SEND_SETTINGS,
2830 base::Bind(&NetLogSpdySendSettingsCallback, &settings, protocol_version));
2831 // Create the SETTINGS frame and send it.
2832 DCHECK(buffered_spdy_framer_.get());
2833 scoped_ptr<SpdyFrame> settings_frame(
2834 buffered_spdy_framer_->CreateSettings(settings));
2835 sent_settings_ = true;
2836 EnqueueSessionWrite(HIGHEST, SETTINGS, settings_frame.Pass());
2839 void SpdySession::HandleSetting(uint32 id, uint32 value) {
2840 switch (id) {
2841 case SETTINGS_MAX_CONCURRENT_STREAMS:
2842 max_concurrent_streams_ = std::min(static_cast<size_t>(value),
2843 kMaxConcurrentStreamLimit);
2844 ProcessPendingStreamRequests();
2845 break;
2846 case SETTINGS_INITIAL_WINDOW_SIZE: {
2847 if (flow_control_state_ < FLOW_CONTROL_STREAM) {
2848 net_log().AddEvent(
2849 NetLog::TYPE_HTTP2_SESSION_INITIAL_WINDOW_SIZE_NO_FLOW_CONTROL);
2850 return;
2853 if (value > static_cast<uint32>(kint32max)) {
2854 net_log().AddEvent(
2855 NetLog::TYPE_HTTP2_SESSION_INITIAL_WINDOW_SIZE_OUT_OF_RANGE,
2856 NetLog::IntegerCallback("initial_window_size", value));
2857 return;
2860 // SETTINGS_INITIAL_WINDOW_SIZE updates initial_send_window_size_ only.
2861 int32 delta_window_size =
2862 static_cast<int32>(value) - stream_initial_send_window_size_;
2863 stream_initial_send_window_size_ = static_cast<int32>(value);
2864 UpdateStreamsSendWindowSize(delta_window_size);
2865 net_log().AddEvent(
2866 NetLog::TYPE_HTTP2_SESSION_UPDATE_STREAMS_SEND_WINDOW_SIZE,
2867 NetLog::IntegerCallback("delta_window_size", delta_window_size));
2868 break;
2873 void SpdySession::UpdateStreamsSendWindowSize(int32 delta_window_size) {
2874 DCHECK_GE(flow_control_state_, FLOW_CONTROL_STREAM);
2875 for (ActiveStreamMap::iterator it = active_streams_.begin();
2876 it != active_streams_.end(); ++it) {
2877 it->second.stream->AdjustSendWindowSize(delta_window_size);
2880 for (CreatedStreamSet::const_iterator it = created_streams_.begin();
2881 it != created_streams_.end(); it++) {
2882 (*it)->AdjustSendWindowSize(delta_window_size);
2886 void SpdySession::SendPrefacePingIfNoneInFlight() {
2887 if (pings_in_flight_ || !enable_ping_based_connection_checking_)
2888 return;
2890 base::TimeTicks now = time_func_();
2891 // If there is no activity in the session, then send a preface-PING.
2892 if ((now - last_activity_time_) > connection_at_risk_of_loss_time_)
2893 SendPrefacePing();
2896 void SpdySession::SendPrefacePing() {
2897 WritePingFrame(next_ping_id_, false);
2900 void SpdySession::SendWindowUpdateFrame(SpdyStreamId stream_id,
2901 uint32 delta_window_size,
2902 RequestPriority priority) {
2903 CHECK_GE(flow_control_state_, FLOW_CONTROL_STREAM);
2904 ActiveStreamMap::const_iterator it = active_streams_.find(stream_id);
2905 if (it != active_streams_.end()) {
2906 CHECK_EQ(it->second.stream->stream_id(), stream_id);
2907 } else {
2908 CHECK_EQ(flow_control_state_, FLOW_CONTROL_STREAM_AND_SESSION);
2909 CHECK_EQ(stream_id, kSessionFlowControlStreamId);
2912 net_log_.AddEvent(NetLog::TYPE_HTTP2_SESSION_SENT_WINDOW_UPDATE_FRAME,
2913 base::Bind(&NetLogSpdyWindowUpdateFrameCallback, stream_id,
2914 delta_window_size));
2916 DCHECK(buffered_spdy_framer_.get());
2917 scoped_ptr<SpdyFrame> window_update_frame(
2918 buffered_spdy_framer_->CreateWindowUpdate(stream_id, delta_window_size));
2919 EnqueueSessionWrite(priority, WINDOW_UPDATE, window_update_frame.Pass());
2922 void SpdySession::WritePingFrame(SpdyPingId unique_id, bool is_ack) {
2923 DCHECK(buffered_spdy_framer_.get());
2924 scoped_ptr<SpdyFrame> ping_frame(
2925 buffered_spdy_framer_->CreatePingFrame(unique_id, is_ack));
2926 EnqueueSessionWrite(HIGHEST, PING, ping_frame.Pass());
2928 if (net_log().IsLogging()) {
2929 net_log().AddEvent(
2930 NetLog::TYPE_HTTP2_SESSION_PING,
2931 base::Bind(&NetLogSpdyPingCallback, unique_id, is_ack, "sent"));
2933 if (!is_ack) {
2934 next_ping_id_ += 2;
2935 ++pings_in_flight_;
2936 PlanToCheckPingStatus();
2937 last_ping_sent_time_ = time_func_();
2941 void SpdySession::PlanToCheckPingStatus() {
2942 if (check_ping_status_pending_)
2943 return;
2945 check_ping_status_pending_ = true;
2946 base::MessageLoop::current()->PostDelayedTask(
2947 FROM_HERE,
2948 base::Bind(&SpdySession::CheckPingStatus, weak_factory_.GetWeakPtr(),
2949 time_func_()), hung_interval_);
2952 void SpdySession::CheckPingStatus(base::TimeTicks last_check_time) {
2953 CHECK(!in_io_loop_);
2955 // Check if we got a response back for all PINGs we had sent.
2956 if (pings_in_flight_ == 0) {
2957 check_ping_status_pending_ = false;
2958 return;
2961 DCHECK(check_ping_status_pending_);
2963 base::TimeTicks now = time_func_();
2964 base::TimeDelta delay = hung_interval_ - (now - last_activity_time_);
2966 if (delay.InMilliseconds() < 0 || last_activity_time_ < last_check_time) {
2967 // Track all failed PING messages in a separate bucket.
2968 RecordPingRTTHistogram(base::TimeDelta::Max());
2969 DoDrainSession(ERR_SPDY_PING_FAILED, "Failed ping.");
2970 return;
2973 // Check the status of connection after a delay.
2974 base::MessageLoop::current()->PostDelayedTask(
2975 FROM_HERE,
2976 base::Bind(&SpdySession::CheckPingStatus, weak_factory_.GetWeakPtr(),
2977 now),
2978 delay);
2981 void SpdySession::RecordPingRTTHistogram(base::TimeDelta duration) {
2982 UMA_HISTOGRAM_TIMES("Net.SpdyPing.RTT", duration);
2985 void SpdySession::RecordProtocolErrorHistogram(
2986 SpdyProtocolErrorDetails details) {
2987 UMA_HISTOGRAM_ENUMERATION("Net.SpdySessionErrorDetails2", details,
2988 NUM_SPDY_PROTOCOL_ERROR_DETAILS);
2989 if (EndsWith(host_port_pair().host(), "google.com", false)) {
2990 UMA_HISTOGRAM_ENUMERATION("Net.SpdySessionErrorDetails_Google2", details,
2991 NUM_SPDY_PROTOCOL_ERROR_DETAILS);
2995 void SpdySession::RecordHistograms() {
2996 UMA_HISTOGRAM_CUSTOM_COUNTS("Net.SpdyStreamsPerSession",
2997 streams_initiated_count_,
2998 0, 300, 50);
2999 UMA_HISTOGRAM_CUSTOM_COUNTS("Net.SpdyStreamsPushedPerSession",
3000 streams_pushed_count_,
3001 0, 300, 50);
3002 UMA_HISTOGRAM_CUSTOM_COUNTS("Net.SpdyStreamsPushedAndClaimedPerSession",
3003 streams_pushed_and_claimed_count_,
3004 0, 300, 50);
3005 UMA_HISTOGRAM_CUSTOM_COUNTS("Net.SpdyStreamsAbandonedPerSession",
3006 streams_abandoned_count_,
3007 0, 300, 50);
3008 UMA_HISTOGRAM_ENUMERATION("Net.SpdySettingsSent",
3009 sent_settings_ ? 1 : 0, 2);
3010 UMA_HISTOGRAM_ENUMERATION("Net.SpdySettingsReceived",
3011 received_settings_ ? 1 : 0, 2);
3012 UMA_HISTOGRAM_CUSTOM_COUNTS("Net.SpdyStreamStallsPerSession",
3013 stalled_streams_,
3014 0, 300, 50);
3015 UMA_HISTOGRAM_ENUMERATION("Net.SpdySessionsWithStalls",
3016 stalled_streams_ > 0 ? 1 : 0, 2);
3018 if (received_settings_) {
3019 // Enumerate the saved settings, and set histograms for it.
3020 const SettingsMap& settings_map =
3021 http_server_properties_->GetSpdySettings(host_port_pair());
3023 SettingsMap::const_iterator it;
3024 for (it = settings_map.begin(); it != settings_map.end(); ++it) {
3025 const SpdySettingsIds id = it->first;
3026 const uint32 val = it->second.second;
3027 switch (id) {
3028 case SETTINGS_CURRENT_CWND:
3029 // Record several different histograms to see if cwnd converges
3030 // for larger volumes of data being sent.
3031 UMA_HISTOGRAM_CUSTOM_COUNTS("Net.SpdySettingsCwnd",
3032 val, 1, 200, 100);
3033 if (total_bytes_received_ > 10 * 1024) {
3034 UMA_HISTOGRAM_CUSTOM_COUNTS("Net.SpdySettingsCwnd10K",
3035 val, 1, 200, 100);
3036 if (total_bytes_received_ > 25 * 1024) {
3037 UMA_HISTOGRAM_CUSTOM_COUNTS("Net.SpdySettingsCwnd25K",
3038 val, 1, 200, 100);
3039 if (total_bytes_received_ > 50 * 1024) {
3040 UMA_HISTOGRAM_CUSTOM_COUNTS("Net.SpdySettingsCwnd50K",
3041 val, 1, 200, 100);
3042 if (total_bytes_received_ > 100 * 1024) {
3043 UMA_HISTOGRAM_CUSTOM_COUNTS("Net.SpdySettingsCwnd100K",
3044 val, 1, 200, 100);
3049 break;
3050 case SETTINGS_ROUND_TRIP_TIME:
3051 UMA_HISTOGRAM_CUSTOM_COUNTS("Net.SpdySettingsRTT",
3052 val, 1, 1200, 100);
3053 break;
3054 case SETTINGS_DOWNLOAD_RETRANS_RATE:
3055 UMA_HISTOGRAM_CUSTOM_COUNTS("Net.SpdySettingsRetransRate",
3056 val, 1, 100, 50);
3057 break;
3058 default:
3059 break;
3065 void SpdySession::CompleteStreamRequest(
3066 const base::WeakPtr<SpdyStreamRequest>& pending_request) {
3067 // Abort if the request has already been cancelled.
3068 if (!pending_request)
3069 return;
3071 base::WeakPtr<SpdyStream> stream;
3072 int rv = TryCreateStream(pending_request, &stream);
3074 if (rv == OK) {
3075 DCHECK(stream);
3076 pending_request->OnRequestCompleteSuccess(stream);
3077 return;
3079 DCHECK(!stream);
3081 if (rv != ERR_IO_PENDING) {
3082 pending_request->OnRequestCompleteFailure(rv);
3086 SSLClientSocket* SpdySession::GetSSLClientSocket() const {
3087 if (!is_secure_)
3088 return NULL;
3089 SSLClientSocket* ssl_socket =
3090 reinterpret_cast<SSLClientSocket*>(connection_->socket());
3091 DCHECK(ssl_socket);
3092 return ssl_socket;
3095 void SpdySession::OnWriteBufferConsumed(
3096 size_t frame_payload_size,
3097 size_t consume_size,
3098 SpdyBuffer::ConsumeSource consume_source) {
3099 // We can be called with |in_io_loop_| set if a write SpdyBuffer is
3100 // deleted (e.g., a stream is closed due to incoming data).
3102 DCHECK_EQ(flow_control_state_, FLOW_CONTROL_STREAM_AND_SESSION);
3104 if (consume_source == SpdyBuffer::DISCARD) {
3105 // If we're discarding a frame or part of it, increase the send
3106 // window by the number of discarded bytes. (Although if we're
3107 // discarding part of a frame, it's probably because of a write
3108 // error and we'll be tearing down the session soon.)
3109 size_t remaining_payload_bytes = std::min(consume_size, frame_payload_size);
3110 DCHECK_GT(remaining_payload_bytes, 0u);
3111 IncreaseSendWindowSize(static_cast<int32>(remaining_payload_bytes));
3113 // For consumed bytes, the send window is increased when we receive
3114 // a WINDOW_UPDATE frame.
3117 void SpdySession::IncreaseSendWindowSize(int32 delta_window_size) {
3118 // We can be called with |in_io_loop_| set if a SpdyBuffer is
3119 // deleted (e.g., a stream is closed due to incoming data).
3121 DCHECK_EQ(flow_control_state_, FLOW_CONTROL_STREAM_AND_SESSION);
3122 DCHECK_GE(delta_window_size, 1);
3124 // Check for overflow.
3125 int32 max_delta_window_size = kint32max - session_send_window_size_;
3126 if (delta_window_size > max_delta_window_size) {
3127 RecordProtocolErrorHistogram(PROTOCOL_ERROR_INVALID_WINDOW_UPDATE_SIZE);
3128 DoDrainSession(
3129 ERR_SPDY_PROTOCOL_ERROR,
3130 "Received WINDOW_UPDATE [delta: " +
3131 base::IntToString(delta_window_size) +
3132 "] for session overflows session_send_window_size_ [current: " +
3133 base::IntToString(session_send_window_size_) + "]");
3134 return;
3137 session_send_window_size_ += delta_window_size;
3139 net_log_.AddEvent(NetLog::TYPE_HTTP2_SESSION_UPDATE_SEND_WINDOW,
3140 base::Bind(&NetLogSpdySessionWindowUpdateCallback,
3141 delta_window_size, session_send_window_size_));
3143 DCHECK(!IsSendStalled());
3144 ResumeSendStalledStreams();
3147 void SpdySession::DecreaseSendWindowSize(int32 delta_window_size) {
3148 DCHECK_EQ(flow_control_state_, FLOW_CONTROL_STREAM_AND_SESSION);
3150 // We only call this method when sending a frame. Therefore,
3151 // |delta_window_size| should be within the valid frame size range.
3152 DCHECK_GE(delta_window_size, 1);
3153 DCHECK_LE(delta_window_size, kMaxSpdyFrameChunkSize);
3155 // |send_window_size_| should have been at least |delta_window_size| for
3156 // this call to happen.
3157 DCHECK_GE(session_send_window_size_, delta_window_size);
3159 session_send_window_size_ -= delta_window_size;
3161 net_log_.AddEvent(NetLog::TYPE_HTTP2_SESSION_UPDATE_SEND_WINDOW,
3162 base::Bind(&NetLogSpdySessionWindowUpdateCallback,
3163 -delta_window_size, session_send_window_size_));
3166 void SpdySession::OnReadBufferConsumed(
3167 size_t consume_size,
3168 SpdyBuffer::ConsumeSource consume_source) {
3169 // We can be called with |in_io_loop_| set if a read SpdyBuffer is
3170 // deleted (e.g., discarded by a SpdyReadQueue).
3172 DCHECK_EQ(flow_control_state_, FLOW_CONTROL_STREAM_AND_SESSION);
3173 DCHECK_GE(consume_size, 1u);
3174 DCHECK_LE(consume_size, static_cast<size_t>(kint32max));
3176 IncreaseRecvWindowSize(static_cast<int32>(consume_size));
3179 void SpdySession::IncreaseRecvWindowSize(int32 delta_window_size) {
3180 DCHECK_EQ(flow_control_state_, FLOW_CONTROL_STREAM_AND_SESSION);
3181 DCHECK_GE(session_unacked_recv_window_bytes_, 0);
3182 DCHECK_GE(session_recv_window_size_, session_unacked_recv_window_bytes_);
3183 DCHECK_GE(delta_window_size, 1);
3184 // Check for overflow.
3185 DCHECK_LE(delta_window_size, kint32max - session_recv_window_size_);
3187 session_recv_window_size_ += delta_window_size;
3188 net_log_.AddEvent(NetLog::TYPE_HTTP2_STREAM_UPDATE_RECV_WINDOW,
3189 base::Bind(&NetLogSpdySessionWindowUpdateCallback,
3190 delta_window_size, session_recv_window_size_));
3192 session_unacked_recv_window_bytes_ += delta_window_size;
3193 if (session_unacked_recv_window_bytes_ >
3194 GetInitialWindowSize(protocol_) / 2) {
3195 SendWindowUpdateFrame(kSessionFlowControlStreamId,
3196 session_unacked_recv_window_bytes_,
3197 HIGHEST);
3198 session_unacked_recv_window_bytes_ = 0;
3202 void SpdySession::DecreaseRecvWindowSize(int32 delta_window_size) {
3203 CHECK(in_io_loop_);
3204 DCHECK_EQ(flow_control_state_, FLOW_CONTROL_STREAM_AND_SESSION);
3205 DCHECK_GE(delta_window_size, 1);
3207 // Since we never decrease the initial receive window size,
3208 // |delta_window_size| should never cause |recv_window_size_| to go
3209 // negative. If we do, the receive window isn't being respected.
3210 if (delta_window_size > session_recv_window_size_) {
3211 RecordProtocolErrorHistogram(PROTOCOL_ERROR_RECEIVE_WINDOW_VIOLATION);
3212 DoDrainSession(
3213 ERR_SPDY_FLOW_CONTROL_ERROR,
3214 "delta_window_size is " + base::IntToString(delta_window_size) +
3215 " in DecreaseRecvWindowSize, which is larger than the receive " +
3216 "window size of " + base::IntToString(session_recv_window_size_));
3217 return;
3220 session_recv_window_size_ -= delta_window_size;
3221 net_log_.AddEvent(NetLog::TYPE_HTTP2_SESSION_UPDATE_RECV_WINDOW,
3222 base::Bind(&NetLogSpdySessionWindowUpdateCallback,
3223 -delta_window_size, session_recv_window_size_));
3226 void SpdySession::QueueSendStalledStream(const SpdyStream& stream) {
3227 DCHECK(stream.send_stalled_by_flow_control());
3228 RequestPriority priority = stream.priority();
3229 CHECK_GE(priority, MINIMUM_PRIORITY);
3230 CHECK_LE(priority, MAXIMUM_PRIORITY);
3231 stream_send_unstall_queue_[priority].push_back(stream.stream_id());
3234 void SpdySession::ResumeSendStalledStreams() {
3235 DCHECK_EQ(flow_control_state_, FLOW_CONTROL_STREAM_AND_SESSION);
3237 // We don't have to worry about new streams being queued, since
3238 // doing so would cause IsSendStalled() to return true. But we do
3239 // have to worry about streams being closed, as well as ourselves
3240 // being closed.
3242 while (!IsSendStalled()) {
3243 size_t old_size = 0;
3244 #if DCHECK_IS_ON()
3245 old_size = GetTotalSize(stream_send_unstall_queue_);
3246 #endif
3248 SpdyStreamId stream_id = PopStreamToPossiblyResume();
3249 if (stream_id == 0)
3250 break;
3251 ActiveStreamMap::const_iterator it = active_streams_.find(stream_id);
3252 // The stream may actually still be send-stalled after this (due
3253 // to its own send window) but that's okay -- it'll then be
3254 // resumed once its send window increases.
3255 if (it != active_streams_.end())
3256 it->second.stream->PossiblyResumeIfSendStalled();
3258 // The size should decrease unless we got send-stalled again.
3259 if (!IsSendStalled())
3260 DCHECK_LT(GetTotalSize(stream_send_unstall_queue_), old_size);
3264 SpdyStreamId SpdySession::PopStreamToPossiblyResume() {
3265 for (int i = MAXIMUM_PRIORITY; i >= MINIMUM_PRIORITY; --i) {
3266 std::deque<SpdyStreamId>* queue = &stream_send_unstall_queue_[i];
3267 if (!queue->empty()) {
3268 SpdyStreamId stream_id = queue->front();
3269 queue->pop_front();
3270 return stream_id;
3273 return 0;
3276 } // namespace net