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/quic/quic_stream_factory.h"
10 #include "base/location.h"
11 #include "base/metrics/field_trial.h"
12 #include "base/metrics/histogram_macros.h"
13 #include "base/metrics/sparse_histogram.h"
14 #include "base/rand_util.h"
15 #include "base/single_thread_task_runner.h"
16 #include "base/stl_util.h"
17 #include "base/strings/string_util.h"
18 #include "base/strings/stringprintf.h"
19 #include "base/thread_task_runner_handle.h"
20 #include "base/values.h"
21 #include "net/base/net_errors.h"
22 #include "net/cert/cert_verifier.h"
23 #include "net/dns/host_resolver.h"
24 #include "net/dns/single_request_host_resolver.h"
25 #include "net/http/http_server_properties.h"
26 #include "net/quic/crypto/channel_id_chromium.h"
27 #include "net/quic/crypto/proof_verifier_chromium.h"
28 #include "net/quic/crypto/quic_random.h"
29 #include "net/quic/crypto/quic_server_info.h"
30 #include "net/quic/port_suggester.h"
31 #include "net/quic/quic_chromium_client_session.h"
32 #include "net/quic/quic_clock.h"
33 #include "net/quic/quic_connection.h"
34 #include "net/quic/quic_connection_helper.h"
35 #include "net/quic/quic_crypto_client_stream_factory.h"
36 #include "net/quic/quic_default_packet_writer.h"
37 #include "net/quic/quic_flags.h"
38 #include "net/quic/quic_http_stream.h"
39 #include "net/quic/quic_protocol.h"
40 #include "net/quic/quic_server_id.h"
41 #include "net/socket/client_socket_factory.h"
42 #include "net/udp/udp_client_socket.h"
45 #include "base/win/windows_version.h"
48 #if defined(USE_OPENSSL)
49 #include <openssl/aead.h>
50 #include "crypto/openssl_util.h"
59 enum CreateSessionFailure
{
60 CREATION_ERROR_CONNECTING_SOCKET
,
61 CREATION_ERROR_SETTING_RECEIVE_BUFFER
,
62 CREATION_ERROR_SETTING_SEND_BUFFER
,
66 // When a connection is idle for 30 seconds it will be closed.
67 const int kIdleConnectionTimeoutSeconds
= 30;
69 // The maximum receive window sizes for QUIC sessions and streams.
70 const int32 kQuicSessionMaxRecvWindowSize
= 15 * 1024 * 1024; // 15 MB
71 const int32 kQuicStreamMaxRecvWindowSize
= 6 * 1024 * 1024; // 6 MB
73 // Set the maximum number of undecryptable packets the connection will store.
74 const int32 kMaxUndecryptablePackets
= 100;
76 void HistogramCreateSessionFailure(enum CreateSessionFailure error
) {
77 UMA_HISTOGRAM_ENUMERATION("Net.QuicSession.CreationError", error
,
81 bool IsEcdsaSupported() {
83 if (base::win::GetVersion() < base::win::VERSION_VISTA
)
90 QuicConfig
InitializeQuicConfig(const QuicTagVector
& connection_options
) {
92 config
.SetIdleConnectionStateLifetime(
93 QuicTime::Delta::FromSeconds(kIdleConnectionTimeoutSeconds
),
94 QuicTime::Delta::FromSeconds(kIdleConnectionTimeoutSeconds
));
95 config
.SetConnectionOptionsToSend(connection_options
);
99 class DefaultPacketWriterFactory
: public QuicConnection::PacketWriterFactory
{
101 explicit DefaultPacketWriterFactory(DatagramClientSocket
* socket
)
103 ~DefaultPacketWriterFactory() override
{}
105 QuicPacketWriter
* Create(QuicConnection
* connection
) const override
;
108 DatagramClientSocket
* socket_
;
111 QuicPacketWriter
* DefaultPacketWriterFactory::Create(
112 QuicConnection
* connection
) const {
113 scoped_ptr
<QuicDefaultPacketWriter
> writer(
114 new QuicDefaultPacketWriter(socket_
));
115 writer
->SetConnection(connection
);
116 return writer
.release();
121 QuicStreamFactory::IpAliasKey::IpAliasKey() {}
123 QuicStreamFactory::IpAliasKey::IpAliasKey(IPEndPoint ip_endpoint
,
125 : ip_endpoint(ip_endpoint
),
126 is_https(is_https
) {}
128 QuicStreamFactory::IpAliasKey::~IpAliasKey() {}
130 bool QuicStreamFactory::IpAliasKey::operator<(
131 const QuicStreamFactory::IpAliasKey
& other
) const {
132 if (!(ip_endpoint
== other
.ip_endpoint
)) {
133 return ip_endpoint
< other
.ip_endpoint
;
135 return is_https
< other
.is_https
;
138 bool QuicStreamFactory::IpAliasKey::operator==(
139 const QuicStreamFactory::IpAliasKey
& other
) const {
140 return is_https
== other
.is_https
&&
141 ip_endpoint
== other
.ip_endpoint
;
144 // Responsible for creating a new QUIC session to the specified server, and
145 // for notifying any associated requests when complete.
146 class QuicStreamFactory::Job
{
148 Job(QuicStreamFactory
* factory
,
149 HostResolver
* host_resolver
,
150 const HostPortPair
& host_port_pair
,
151 bool server_and_origin_have_same_host
,
153 bool was_alternative_service_recently_broken
,
154 PrivacyMode privacy_mode
,
155 int cert_verify_flags
,
157 QuicServerInfo
* server_info
,
158 const BoundNetLog
& net_log
);
160 // Creates a new job to handle the resumption of for connecting an
162 Job(QuicStreamFactory
* factory
,
163 HostResolver
* host_resolver
,
164 QuicChromiumClientSession
* session
,
165 QuicServerId server_id
);
169 int Run(const CompletionCallback
& callback
);
173 int DoResolveHostComplete(int rv
);
174 int DoLoadServerInfo();
175 int DoLoadServerInfoComplete(int rv
);
177 int DoResumeConnect();
178 int DoConnectComplete(int rv
);
180 void OnIOComplete(int rv
);
182 void RunAuxilaryJob();
186 void CancelWaitForDataReadyCallback();
188 const QuicServerId
server_id() const { return server_id_
; }
190 base::WeakPtr
<Job
> GetWeakPtr() { return weak_factory_
.GetWeakPtr(); }
196 STATE_RESOLVE_HOST_COMPLETE
,
197 STATE_LOAD_SERVER_INFO
,
198 STATE_LOAD_SERVER_INFO_COMPLETE
,
200 STATE_RESUME_CONNECT
,
201 STATE_CONNECT_COMPLETE
,
205 QuicStreamFactory
* factory_
;
206 SingleRequestHostResolver host_resolver_
;
207 QuicServerId server_id_
;
208 int cert_verify_flags_
;
209 // True if and only if server and origin have the same hostname.
210 bool server_and_origin_have_same_host_
;
212 bool was_alternative_service_recently_broken_
;
213 scoped_ptr
<QuicServerInfo
> server_info_
;
214 bool started_another_job_
;
215 const BoundNetLog net_log_
;
216 QuicChromiumClientSession
* session_
;
217 CompletionCallback callback_
;
218 AddressList address_list_
;
219 base::TimeTicks dns_resolution_start_time_
;
220 base::TimeTicks dns_resolution_end_time_
;
221 base::WeakPtrFactory
<Job
> weak_factory_
;
222 DISALLOW_COPY_AND_ASSIGN(Job
);
225 QuicStreamFactory::Job::Job(QuicStreamFactory
* factory
,
226 HostResolver
* host_resolver
,
227 const HostPortPair
& host_port_pair
,
228 bool server_and_origin_have_same_host
,
230 bool was_alternative_service_recently_broken
,
231 PrivacyMode privacy_mode
,
232 int cert_verify_flags
,
234 QuicServerInfo
* server_info
,
235 const BoundNetLog
& net_log
)
236 : io_state_(STATE_RESOLVE_HOST
),
238 host_resolver_(host_resolver
),
239 server_id_(host_port_pair
, is_https
, privacy_mode
),
240 cert_verify_flags_(cert_verify_flags
),
241 server_and_origin_have_same_host_(server_and_origin_have_same_host
),
243 was_alternative_service_recently_broken_(
244 was_alternative_service_recently_broken
),
245 server_info_(server_info
),
246 started_another_job_(false),
249 weak_factory_(this) {
252 QuicStreamFactory::Job::Job(QuicStreamFactory
* factory
,
253 HostResolver
* host_resolver
,
254 QuicChromiumClientSession
* session
,
255 QuicServerId server_id
)
256 : io_state_(STATE_RESUME_CONNECT
),
258 host_resolver_(host_resolver
), // unused
259 server_id_(server_id
),
260 cert_verify_flags_(0), // unused
261 server_and_origin_have_same_host_(false), // unused
262 is_post_(false), // unused
263 was_alternative_service_recently_broken_(false), // unused
264 started_another_job_(false), // unused
265 net_log_(session
->net_log()), // unused
267 weak_factory_(this) {}
269 QuicStreamFactory::Job::~Job() {
270 // If disk cache has a pending WaitForDataReadyCallback, cancel that callback.
272 server_info_
->ResetWaitForDataReadyCallback();
275 int QuicStreamFactory::Job::Run(const CompletionCallback
& callback
) {
277 if (rv
== ERR_IO_PENDING
)
278 callback_
= callback
;
280 return rv
> 0 ? OK
: rv
;
283 int QuicStreamFactory::Job::DoLoop(int rv
) {
285 IoState state
= io_state_
;
286 io_state_
= STATE_NONE
;
288 case STATE_RESOLVE_HOST
:
290 rv
= DoResolveHost();
292 case STATE_RESOLVE_HOST_COMPLETE
:
293 rv
= DoResolveHostComplete(rv
);
295 case STATE_LOAD_SERVER_INFO
:
297 rv
= DoLoadServerInfo();
299 case STATE_LOAD_SERVER_INFO_COMPLETE
:
300 rv
= DoLoadServerInfoComplete(rv
);
306 case STATE_RESUME_CONNECT
:
308 rv
= DoResumeConnect();
310 case STATE_CONNECT_COMPLETE
:
311 rv
= DoConnectComplete(rv
);
314 NOTREACHED() << "io_state_: " << io_state_
;
317 } while (io_state_
!= STATE_NONE
&& rv
!= ERR_IO_PENDING
);
321 void QuicStreamFactory::Job::OnIOComplete(int rv
) {
323 if (rv
!= ERR_IO_PENDING
&& !callback_
.is_null()) {
328 void QuicStreamFactory::Job::RunAuxilaryJob() {
329 int rv
= Run(base::Bind(&QuicStreamFactory::OnJobComplete
,
330 base::Unretained(factory_
), this));
331 if (rv
!= ERR_IO_PENDING
)
332 factory_
->OnJobComplete(this, rv
);
335 void QuicStreamFactory::Job::Cancel() {
338 session_
->connection()->SendConnectionClose(QUIC_CONNECTION_CANCELLED
);
341 void QuicStreamFactory::Job::CancelWaitForDataReadyCallback() {
342 // If we are waiting for WaitForDataReadyCallback, then cancel the callback.
343 if (io_state_
!= STATE_LOAD_SERVER_INFO_COMPLETE
)
345 server_info_
->CancelWaitForDataReadyCallback();
349 int QuicStreamFactory::Job::DoResolveHost() {
350 // Start loading the data now, and wait for it after we resolve the host.
352 server_info_
->Start();
355 io_state_
= STATE_RESOLVE_HOST_COMPLETE
;
356 dns_resolution_start_time_
= base::TimeTicks::Now();
357 return host_resolver_
.Resolve(
358 HostResolver::RequestInfo(server_id_
.host_port_pair()), DEFAULT_PRIORITY
,
360 base::Bind(&QuicStreamFactory::Job::OnIOComplete
, GetWeakPtr()),
364 int QuicStreamFactory::Job::DoResolveHostComplete(int rv
) {
365 dns_resolution_end_time_
= base::TimeTicks::Now();
366 UMA_HISTOGRAM_TIMES("Net.QuicSession.HostResolutionTime",
367 dns_resolution_end_time_
- dns_resolution_start_time_
);
371 DCHECK(!factory_
->HasActiveSession(server_id_
));
373 // Inform the factory of this resolution, which will set up
374 // a session alias, if possible.
375 if (factory_
->OnResolution(server_id_
, address_list_
)) {
380 io_state_
= STATE_LOAD_SERVER_INFO
;
382 io_state_
= STATE_CONNECT
;
386 int QuicStreamFactory::Job::DoLoadServerInfo() {
387 io_state_
= STATE_LOAD_SERVER_INFO_COMPLETE
;
389 DCHECK(server_info_
);
391 // To mitigate the effects of disk cache taking too long to load QUIC server
392 // information, set up a timer to cancel WaitForDataReady's callback.
393 if (factory_
->load_server_info_timeout_srtt_multiplier_
> 0) {
394 int64 load_server_info_timeout_ms
=
395 (factory_
->load_server_info_timeout_srtt_multiplier_
*
396 factory_
->GetServerNetworkStatsSmoothedRttInMicroseconds(server_id_
)) /
398 if (load_server_info_timeout_ms
> 0) {
399 factory_
->task_runner_
->PostDelayedTask(
401 base::Bind(&QuicStreamFactory::Job::CancelWaitForDataReadyCallback
,
403 base::TimeDelta::FromMilliseconds(load_server_info_timeout_ms
));
407 int rv
= server_info_
->WaitForDataReady(
408 base::Bind(&QuicStreamFactory::Job::OnIOComplete
, GetWeakPtr()));
409 if (rv
== ERR_IO_PENDING
&& factory_
->enable_connection_racing()) {
410 // If we are waiting to load server config from the disk cache, then start
412 started_another_job_
= true;
413 factory_
->CreateAuxilaryJob(server_id_
, cert_verify_flags_
,
414 server_and_origin_have_same_host_
, is_post_
,
420 int QuicStreamFactory::Job::DoLoadServerInfoComplete(int rv
) {
421 UMA_HISTOGRAM_TIMES("Net.QuicServerInfo.DiskCacheWaitForDataReadyTime",
422 base::TimeTicks::Now() - dns_resolution_end_time_
);
425 server_info_
.reset();
427 if (started_another_job_
&&
428 (!server_info_
|| server_info_
->state().server_config
.empty() ||
429 !factory_
->CryptoConfigCacheIsEmpty(server_id_
))) {
430 // If we have started another job and if we didn't load the server config
431 // from the disk cache or if we have received a new server config from the
432 // server, then cancel the current job.
433 io_state_
= STATE_NONE
;
434 return ERR_CONNECTION_CLOSED
;
437 io_state_
= STATE_CONNECT
;
441 int QuicStreamFactory::Job::DoConnect() {
442 io_state_
= STATE_CONNECT_COMPLETE
;
444 int rv
= factory_
->CreateSession(
445 server_id_
, cert_verify_flags_
, server_info_
.Pass(), address_list_
,
446 dns_resolution_end_time_
, net_log_
, &session_
);
448 DCHECK(rv
!= ERR_IO_PENDING
);
453 if (!session_
->connection()->connected()) {
454 return ERR_CONNECTION_CLOSED
;
457 session_
->StartReading();
458 if (!session_
->connection()->connected()) {
459 return ERR_QUIC_PROTOCOL_ERROR
;
461 bool require_confirmation
= factory_
->require_confirmation() ||
462 !server_and_origin_have_same_host_
|| is_post_
||
463 was_alternative_service_recently_broken_
;
465 rv
= session_
->CryptoConnect(
466 require_confirmation
,
467 base::Bind(&QuicStreamFactory::Job::OnIOComplete
, GetWeakPtr()));
471 int QuicStreamFactory::Job::DoResumeConnect() {
472 io_state_
= STATE_CONNECT_COMPLETE
;
474 int rv
= session_
->ResumeCryptoConnect(
475 base::Bind(&QuicStreamFactory::Job::OnIOComplete
, GetWeakPtr()));
480 int QuicStreamFactory::Job::DoConnectComplete(int rv
) {
484 DCHECK(!factory_
->HasActiveSession(server_id_
));
485 // There may well now be an active session for this IP. If so, use the
486 // existing session instead.
487 AddressList
address(session_
->connection()->peer_address());
488 if (factory_
->OnResolution(server_id_
, address
)) {
489 session_
->connection()->SendConnectionClose(QUIC_CONNECTION_IP_POOLED
);
494 factory_
->ActivateSession(server_id_
, session_
);
499 QuicStreamRequest::QuicStreamRequest(QuicStreamFactory
* factory
)
500 : factory_(factory
) {}
502 QuicStreamRequest::~QuicStreamRequest() {
503 if (factory_
&& !callback_
.is_null())
504 factory_
->CancelRequest(this);
507 int QuicStreamRequest::Request(const HostPortPair
& host_port_pair
,
509 PrivacyMode privacy_mode
,
510 int cert_verify_flags
,
511 base::StringPiece origin_host
,
512 base::StringPiece method
,
513 const BoundNetLog
& net_log
,
514 const CompletionCallback
& callback
) {
516 DCHECK(callback_
.is_null());
518 origin_host_
= origin_host
.as_string();
519 privacy_mode_
= privacy_mode
;
521 factory_
->Create(host_port_pair
, is_https
, privacy_mode
,
522 cert_verify_flags
, origin_host
, method
, net_log
, this);
523 if (rv
== ERR_IO_PENDING
) {
524 host_port_pair_
= host_port_pair
;
526 callback_
= callback
;
535 void QuicStreamRequest::set_stream(scoped_ptr
<QuicHttpStream
> stream
) {
537 stream_
= stream
.Pass();
540 void QuicStreamRequest::OnRequestComplete(int rv
) {
545 scoped_ptr
<QuicHttpStream
> QuicStreamRequest::ReleaseStream() {
547 return stream_
.Pass();
550 QuicStreamFactory::QuicStreamFactory(
551 HostResolver
* host_resolver
,
552 ClientSocketFactory
* client_socket_factory
,
553 base::WeakPtr
<HttpServerProperties
> http_server_properties
,
554 CertVerifier
* cert_verifier
,
555 CertPolicyEnforcer
* cert_policy_enforcer
,
556 ChannelIDService
* channel_id_service
,
557 TransportSecurityState
* transport_security_state
,
558 QuicCryptoClientStreamFactory
* quic_crypto_client_stream_factory
,
559 QuicRandom
* random_generator
,
561 size_t max_packet_length
,
562 const std::string
& user_agent_id
,
563 const QuicVersionVector
& supported_versions
,
564 bool enable_port_selection
,
565 bool always_require_handshake_confirmation
,
566 bool disable_connection_pooling
,
567 float load_server_info_timeout_srtt_multiplier
,
568 bool enable_connection_racing
,
569 bool enable_non_blocking_io
,
570 bool disable_disk_cache
,
572 int max_number_of_lossy_connections
,
573 float packet_loss_threshold
,
574 int max_disabled_reasons
,
575 int threshold_public_resets_post_handshake
,
576 int threshold_timeouts_with_open_streams
,
577 int socket_receive_buffer_size
,
578 const QuicTagVector
& connection_options
)
579 : require_confirmation_(true),
580 host_resolver_(host_resolver
),
581 client_socket_factory_(client_socket_factory
),
582 http_server_properties_(http_server_properties
),
583 transport_security_state_(transport_security_state
),
584 quic_server_info_factory_(nullptr),
585 quic_crypto_client_stream_factory_(quic_crypto_client_stream_factory
),
586 random_generator_(random_generator
),
588 max_packet_length_(max_packet_length
),
589 config_(InitializeQuicConfig(connection_options
)),
590 supported_versions_(supported_versions
),
591 enable_port_selection_(enable_port_selection
),
592 always_require_handshake_confirmation_(
593 always_require_handshake_confirmation
),
594 disable_connection_pooling_(disable_connection_pooling
),
595 load_server_info_timeout_srtt_multiplier_(
596 load_server_info_timeout_srtt_multiplier
),
597 enable_connection_racing_(enable_connection_racing
),
598 enable_non_blocking_io_(enable_non_blocking_io
),
599 disable_disk_cache_(disable_disk_cache
),
600 prefer_aes_(prefer_aes
),
601 max_number_of_lossy_connections_(max_number_of_lossy_connections
),
602 packet_loss_threshold_(packet_loss_threshold
),
603 max_disabled_reasons_(max_disabled_reasons
),
604 num_public_resets_post_handshake_(0),
605 num_timeouts_with_open_streams_(0),
606 max_public_resets_post_handshake_(0),
607 max_timeouts_with_open_streams_(0),
608 threshold_timeouts_with_open_streams_(
609 threshold_timeouts_with_open_streams
),
610 threshold_public_resets_post_handshake_(
611 threshold_public_resets_post_handshake
),
612 socket_receive_buffer_size_(socket_receive_buffer_size
),
613 port_seed_(random_generator_
->RandUint64()),
614 check_persisted_supports_quic_(true),
615 task_runner_(nullptr),
616 weak_factory_(this) {
617 DCHECK(transport_security_state_
);
618 crypto_config_
.set_user_agent_id(user_agent_id
);
619 crypto_config_
.AddCanonicalSuffix(".c.youtube.com");
620 crypto_config_
.AddCanonicalSuffix(".googlevideo.com");
621 crypto_config_
.AddCanonicalSuffix(".googleusercontent.com");
622 crypto_config_
.SetProofVerifier(new ProofVerifierChromium(
623 cert_verifier
, cert_policy_enforcer
, transport_security_state
));
624 // TODO(rtenneti): http://crbug.com/487355. Temporary fix for b/20760730 until
625 // channel_id_service is supported in cronet.
626 if (channel_id_service
) {
627 crypto_config_
.SetChannelIDSource(
628 new ChannelIDSourceChromium(channel_id_service
));
630 #if defined(USE_OPENSSL)
631 crypto::EnsureOpenSSLInit();
632 bool has_aes_hardware_support
= !!EVP_has_aes_hardware();
635 bool has_aes_hardware_support
= cpu
.has_aesni() && cpu
.has_avx();
637 UMA_HISTOGRAM_BOOLEAN("Net.QuicSession.PreferAesGcm",
638 has_aes_hardware_support
);
639 if (has_aes_hardware_support
|| prefer_aes_
)
640 crypto_config_
.PreferAesGcm();
641 if (!IsEcdsaSupported())
642 crypto_config_
.DisableEcdsa();
645 QuicStreamFactory::~QuicStreamFactory() {
646 CloseAllSessions(ERR_ABORTED
);
647 while (!all_sessions_
.empty()) {
648 delete all_sessions_
.begin()->first
;
649 all_sessions_
.erase(all_sessions_
.begin());
651 while (!active_jobs_
.empty()) {
652 const QuicServerId server_id
= active_jobs_
.begin()->first
;
653 STLDeleteElements(&(active_jobs_
[server_id
]));
654 active_jobs_
.erase(server_id
);
658 void QuicStreamFactory::set_require_confirmation(bool require_confirmation
) {
659 require_confirmation_
= require_confirmation
;
660 if (http_server_properties_
&& (!(local_address_
== IPEndPoint()))) {
661 http_server_properties_
->SetSupportsQuic(!require_confirmation
,
662 local_address_
.address());
666 int QuicStreamFactory::Create(const HostPortPair
& host_port_pair
,
668 PrivacyMode privacy_mode
,
669 int cert_verify_flags
,
670 base::StringPiece origin_host
,
671 base::StringPiece method
,
672 const BoundNetLog
& net_log
,
673 QuicStreamRequest
* request
) {
674 QuicServerId
server_id(host_port_pair
, is_https
, privacy_mode
);
675 SessionMap::iterator it
= active_sessions_
.find(server_id
);
676 if (it
!= active_sessions_
.end()) {
677 QuicChromiumClientSession
* session
= it
->second
;
678 if (!session
->CanPool(origin_host
.as_string(), privacy_mode
))
679 return ERR_ALTERNATIVE_CERT_NOT_VALID_FOR_ORIGIN
;
680 request
->set_stream(CreateFromSession(session
));
684 if (HasActiveJob(server_id
)) {
685 active_requests_
[request
] = server_id
;
686 job_requests_map_
[server_id
].insert(request
);
687 return ERR_IO_PENDING
;
690 // TODO(rtenneti): |task_runner_| is used by the Job. Initialize task_runner_
691 // in the constructor after WebRequestActionWithThreadsTest.* tests are fixed.
693 task_runner_
= base::ThreadTaskRunnerHandle::Get().get();
695 QuicServerInfo
* quic_server_info
= nullptr;
696 if (quic_server_info_factory_
) {
697 bool load_from_disk_cache
= !disable_disk_cache_
;
698 if (http_server_properties_
) {
699 const AlternativeServiceMap
& alternative_service_map
=
700 http_server_properties_
->alternative_service_map();
701 AlternativeServiceMap::const_iterator map_it
=
702 alternative_service_map
.Peek(server_id
.host_port_pair());
703 if (map_it
!= alternative_service_map
.end()) {
704 const AlternativeServiceInfoVector
& alternative_service_info_vector
=
706 AlternativeServiceInfoVector::const_iterator it
;
707 for (it
= alternative_service_info_vector
.begin();
708 it
!= alternative_service_info_vector
.end(); ++it
) {
709 if (it
->alternative_service
.protocol
== QUIC
)
712 // If there is no entry for QUIC, consider that as a new server and
713 // don't wait for Cache thread to load the data for that server.
714 if (it
== alternative_service_info_vector
.end())
715 load_from_disk_cache
= false;
718 if (load_from_disk_cache
&& CryptoConfigCacheIsEmpty(server_id
)) {
719 quic_server_info
= quic_server_info_factory_
->GetForServer(server_id
);
723 bool server_and_origin_have_same_host
= host_port_pair
.host() == origin_host
;
724 scoped_ptr
<Job
> job(new Job(this, host_resolver_
, host_port_pair
,
725 server_and_origin_have_same_host
, is_https
,
726 WasQuicRecentlyBroken(server_id
), privacy_mode
,
727 cert_verify_flags
, method
== "POST" /* is_post */,
728 quic_server_info
, net_log
));
729 int rv
= job
->Run(base::Bind(&QuicStreamFactory::OnJobComplete
,
730 base::Unretained(this), job
.get()));
731 if (rv
== ERR_IO_PENDING
) {
732 active_requests_
[request
] = server_id
;
733 job_requests_map_
[server_id
].insert(request
);
734 active_jobs_
[server_id
].insert(job
.release());
738 it
= active_sessions_
.find(server_id
);
739 DCHECK(it
!= active_sessions_
.end());
740 QuicChromiumClientSession
* session
= it
->second
;
741 if (!session
->CanPool(origin_host
.as_string(), privacy_mode
))
742 return ERR_ALTERNATIVE_CERT_NOT_VALID_FOR_ORIGIN
;
743 request
->set_stream(CreateFromSession(session
));
748 void QuicStreamFactory::CreateAuxilaryJob(const QuicServerId server_id
,
749 int cert_verify_flags
,
750 bool server_and_origin_have_same_host
,
752 const BoundNetLog
& net_log
) {
754 new Job(this, host_resolver_
, server_id
.host_port_pair(),
755 server_and_origin_have_same_host
, server_id
.is_https(),
756 WasQuicRecentlyBroken(server_id
), server_id
.privacy_mode(),
757 cert_verify_flags
, is_post
, nullptr, net_log
);
758 active_jobs_
[server_id
].insert(aux_job
);
759 task_runner_
->PostTask(FROM_HERE
,
760 base::Bind(&QuicStreamFactory::Job::RunAuxilaryJob
,
761 aux_job
->GetWeakPtr()));
764 bool QuicStreamFactory::OnResolution(
765 const QuicServerId
& server_id
,
766 const AddressList
& address_list
) {
767 DCHECK(!HasActiveSession(server_id
));
768 if (disable_connection_pooling_
) {
771 for (const IPEndPoint
& address
: address_list
) {
772 const IpAliasKey
ip_alias_key(address
, server_id
.is_https());
773 if (!ContainsKey(ip_aliases_
, ip_alias_key
))
776 const SessionSet
& sessions
= ip_aliases_
[ip_alias_key
];
777 for (QuicChromiumClientSession
* session
: sessions
) {
778 if (!session
->CanPool(server_id
.host(), server_id
.privacy_mode()))
780 active_sessions_
[server_id
] = session
;
781 session_aliases_
[session
].insert(server_id
);
788 void QuicStreamFactory::OnJobComplete(Job
* job
, int rv
) {
789 QuicServerId server_id
= job
->server_id();
791 JobSet
* jobs
= &(active_jobs_
[server_id
]);
792 if (jobs
->size() > 1) {
793 // If there is another pending job, then we can delete this job and let
794 // the other job handle the request.
803 if (!always_require_handshake_confirmation_
)
804 set_require_confirmation(false);
806 // Create all the streams, but do not notify them yet.
807 SessionMap::iterator session_it
= active_sessions_
.find(server_id
);
808 for (RequestSet::iterator request_it
= job_requests_map_
[server_id
].begin();
809 request_it
!= job_requests_map_
[server_id
].end();) {
810 DCHECK(session_it
!= active_sessions_
.end());
811 QuicChromiumClientSession
* session
= session_it
->second
;
812 QuicStreamRequest
* request
= *request_it
;
813 if (!session
->CanPool(request
->origin_host(), request
->privacy_mode())) {
814 RequestSet::iterator old_request_it
= request_it
;
816 // Remove request from containers so that OnRequestComplete() is not
817 // called later again on the same request.
818 job_requests_map_
[server_id
].erase(old_request_it
);
819 active_requests_
.erase(request
);
820 // Notify request of certificate error.
821 request
->OnRequestComplete(ERR_ALTERNATIVE_CERT_NOT_VALID_FOR_ORIGIN
);
824 request
->set_stream(CreateFromSession(session
));
829 while (!job_requests_map_
[server_id
].empty()) {
830 RequestSet::iterator it
= job_requests_map_
[server_id
].begin();
831 QuicStreamRequest
* request
= *it
;
832 job_requests_map_
[server_id
].erase(it
);
833 active_requests_
.erase(request
);
834 // Even though we're invoking callbacks here, we don't need to worry
835 // about |this| being deleted, because the factory is owned by the
836 // profile which can not be deleted via callbacks.
837 request
->OnRequestComplete(rv
);
840 for (Job
* other_job
: active_jobs_
[server_id
]) {
841 if (other_job
!= job
)
845 STLDeleteElements(&(active_jobs_
[server_id
]));
846 active_jobs_
.erase(server_id
);
847 job_requests_map_
.erase(server_id
);
850 scoped_ptr
<QuicHttpStream
> QuicStreamFactory::CreateFromSession(
851 QuicChromiumClientSession
* session
) {
852 return scoped_ptr
<QuicHttpStream
>(new QuicHttpStream(session
->GetWeakPtr()));
855 QuicChromiumClientSession::QuicDisabledReason
856 QuicStreamFactory::QuicDisabledReason(uint16 port
) const {
857 if (max_number_of_lossy_connections_
> 0 &&
858 number_of_lossy_connections_
.find(port
) !=
859 number_of_lossy_connections_
.end() &&
860 number_of_lossy_connections_
.at(port
) >=
861 max_number_of_lossy_connections_
) {
862 return QuicChromiumClientSession::QUIC_DISABLED_BAD_PACKET_LOSS_RATE
;
864 if (threshold_public_resets_post_handshake_
> 0 &&
865 num_public_resets_post_handshake_
>=
866 threshold_public_resets_post_handshake_
) {
867 return QuicChromiumClientSession::QUIC_DISABLED_PUBLIC_RESET_POST_HANDSHAKE
;
869 if (threshold_timeouts_with_open_streams_
> 0 &&
870 num_timeouts_with_open_streams_
>=
871 threshold_timeouts_with_open_streams_
) {
872 return QuicChromiumClientSession::QUIC_DISABLED_TIMEOUT_WITH_OPEN_STREAMS
;
874 return QuicChromiumClientSession::QUIC_DISABLED_NOT
;
877 const char* QuicStreamFactory::QuicDisabledReasonString() const {
878 // TODO(ckrasic) - better solution for port/lossy connections?
879 const uint16 port
= 443;
880 switch (QuicDisabledReason(port
)) {
881 case QuicChromiumClientSession::QUIC_DISABLED_BAD_PACKET_LOSS_RATE
:
882 return "Bad packet loss rate.";
883 case QuicChromiumClientSession::QUIC_DISABLED_PUBLIC_RESET_POST_HANDSHAKE
:
884 return "Public resets after successful handshakes.";
885 case QuicChromiumClientSession::QUIC_DISABLED_TIMEOUT_WITH_OPEN_STREAMS
:
886 return "Connection timeouts with streams open.";
892 bool QuicStreamFactory::IsQuicDisabled(uint16 port
) {
893 return QuicDisabledReason(port
) !=
894 QuicChromiumClientSession::QUIC_DISABLED_NOT
;
897 bool QuicStreamFactory::OnHandshakeConfirmed(QuicChromiumClientSession
* session
,
898 float packet_loss_rate
) {
900 uint16 port
= session
->server_id().port();
901 if (packet_loss_rate
< packet_loss_threshold_
) {
902 number_of_lossy_connections_
[port
] = 0;
906 if (http_server_properties_
) {
907 // We mark it as recently broken, which means that 0-RTT will be disabled
908 // but we'll still race.
909 http_server_properties_
->MarkAlternativeServiceRecentlyBroken(
910 AlternativeService(QUIC
, session
->server_id().host(), port
));
913 bool was_quic_disabled
= IsQuicDisabled(port
);
914 ++number_of_lossy_connections_
[port
];
916 // Collect data for port 443 for packet loss events.
917 if (port
== 443 && max_number_of_lossy_connections_
> 0) {
918 UMA_HISTOGRAM_SPARSE_SLOWLY(
919 base::StringPrintf("Net.QuicStreamFactory.BadPacketLossEvents%d",
920 max_number_of_lossy_connections_
),
921 std::min(number_of_lossy_connections_
[port
],
922 max_number_of_lossy_connections_
));
925 bool is_quic_disabled
= IsQuicDisabled(port
);
926 if (is_quic_disabled
) {
927 // Close QUIC connection if Quic is disabled for this port.
928 session
->CloseSessionOnErrorAndNotifyFactoryLater(
929 ERR_ABORTED
, QUIC_BAD_PACKET_LOSS_RATE
);
931 // If this bad packet loss rate disabled the QUIC, then record it.
932 if (!was_quic_disabled
)
933 UMA_HISTOGRAM_SPARSE_SLOWLY("Net.QuicStreamFactory.QuicIsDisabled", port
);
935 return is_quic_disabled
;
938 void QuicStreamFactory::OnIdleSession(QuicChromiumClientSession
* session
) {}
940 void QuicStreamFactory::OnSessionGoingAway(QuicChromiumClientSession
* session
) {
941 const AliasSet
& aliases
= session_aliases_
[session
];
942 for (AliasSet::const_iterator it
= aliases
.begin(); it
!= aliases
.end();
944 DCHECK(active_sessions_
.count(*it
));
945 DCHECK_EQ(session
, active_sessions_
[*it
]);
946 // Track sessions which have recently gone away so that we can disable
948 if (session
->goaway_received()) {
949 gone_away_aliases_
.insert(*it
);
952 active_sessions_
.erase(*it
);
953 ProcessGoingAwaySession(session
, *it
, true);
955 ProcessGoingAwaySession(session
, all_sessions_
[session
], false);
956 if (!aliases
.empty()) {
957 const IpAliasKey
ip_alias_key(session
->connection()->peer_address(),
958 aliases
.begin()->is_https());
959 ip_aliases_
[ip_alias_key
].erase(session
);
960 if (ip_aliases_
[ip_alias_key
].empty()) {
961 ip_aliases_
.erase(ip_alias_key
);
964 session_aliases_
.erase(session
);
967 void QuicStreamFactory::MaybeDisableQuic(QuicChromiumClientSession
* session
) {
969 uint16 port
= session
->server_id().port();
970 if (IsQuicDisabled(port
))
973 // Expire the oldest disabled_reason if appropriate. This enforces that we
974 // only consider the max_disabled_reasons_ most recent sessions.
975 QuicChromiumClientSession::QuicDisabledReason disabled_reason
;
976 if (static_cast<int>(disabled_reasons_
.size()) == max_disabled_reasons_
) {
977 disabled_reason
= disabled_reasons_
.front();
978 disabled_reasons_
.pop_front();
979 if (disabled_reason
==
980 QuicChromiumClientSession::QUIC_DISABLED_PUBLIC_RESET_POST_HANDSHAKE
) {
981 --num_public_resets_post_handshake_
;
982 } else if (disabled_reason
== QuicChromiumClientSession::
983 QUIC_DISABLED_TIMEOUT_WITH_OPEN_STREAMS
) {
984 --num_timeouts_with_open_streams_
;
987 disabled_reason
= session
->disabled_reason();
988 disabled_reasons_
.push_back(disabled_reason
);
989 if (disabled_reason
==
990 QuicChromiumClientSession::QUIC_DISABLED_PUBLIC_RESET_POST_HANDSHAKE
) {
991 ++num_public_resets_post_handshake_
;
992 } else if (disabled_reason
== QuicChromiumClientSession::
993 QUIC_DISABLED_TIMEOUT_WITH_OPEN_STREAMS
) {
994 ++num_timeouts_with_open_streams_
;
996 if (num_timeouts_with_open_streams_
> max_timeouts_with_open_streams_
) {
997 max_timeouts_with_open_streams_
= num_timeouts_with_open_streams_
;
998 UMA_HISTOGRAM_CUSTOM_COUNTS("Net.QuicStreamFactory.TimeoutsWithOpenStreams",
999 num_timeouts_with_open_streams_
, 0, 20, 10);
1002 if (num_public_resets_post_handshake_
> max_public_resets_post_handshake_
) {
1003 max_public_resets_post_handshake_
= num_public_resets_post_handshake_
;
1004 UMA_HISTOGRAM_CUSTOM_COUNTS(
1005 "Net.QuicStreamFactory.PublicResetsPostHandshake",
1006 num_public_resets_post_handshake_
, 0, 20, 10);
1009 if (IsQuicDisabled(port
)) {
1010 if (disabled_reason
==
1011 QuicChromiumClientSession::QUIC_DISABLED_PUBLIC_RESET_POST_HANDSHAKE
) {
1012 session
->CloseSessionOnErrorAndNotifyFactoryLater(
1013 ERR_ABORTED
, QUIC_PUBLIC_RESETS_POST_HANDSHAKE
);
1014 } else if (disabled_reason
== QuicChromiumClientSession::
1015 QUIC_DISABLED_TIMEOUT_WITH_OPEN_STREAMS
) {
1016 session
->CloseSessionOnErrorAndNotifyFactoryLater(
1017 ERR_ABORTED
, QUIC_TIMEOUTS_WITH_OPEN_STREAMS
);
1019 UMA_HISTOGRAM_ENUMERATION("Net.QuicStreamFactory.DisabledReasons",
1021 QuicChromiumClientSession::QUIC_DISABLED_MAX
);
1025 void QuicStreamFactory::OnSessionClosed(QuicChromiumClientSession
* session
) {
1026 DCHECK_EQ(0u, session
->GetNumOpenStreams());
1027 MaybeDisableQuic(session
);
1028 OnSessionGoingAway(session
);
1030 all_sessions_
.erase(session
);
1033 void QuicStreamFactory::OnSessionConnectTimeout(
1034 QuicChromiumClientSession
* session
) {
1035 const AliasSet
& aliases
= session_aliases_
[session
];
1036 for (AliasSet::const_iterator it
= aliases
.begin(); it
!= aliases
.end();
1038 DCHECK(active_sessions_
.count(*it
));
1039 DCHECK_EQ(session
, active_sessions_
[*it
]);
1040 active_sessions_
.erase(*it
);
1043 if (aliases
.empty()) {
1047 const IpAliasKey
ip_alias_key(session
->connection()->peer_address(),
1048 aliases
.begin()->is_https());
1049 ip_aliases_
[ip_alias_key
].erase(session
);
1050 if (ip_aliases_
[ip_alias_key
].empty()) {
1051 ip_aliases_
.erase(ip_alias_key
);
1053 QuicServerId server_id
= *aliases
.begin();
1054 session_aliases_
.erase(session
);
1055 Job
* job
= new Job(this, host_resolver_
, session
, server_id
);
1056 active_jobs_
[server_id
].insert(job
);
1057 int rv
= job
->Run(base::Bind(&QuicStreamFactory::OnJobComplete
,
1058 base::Unretained(this), job
));
1059 DCHECK_EQ(ERR_IO_PENDING
, rv
);
1062 void QuicStreamFactory::CancelRequest(QuicStreamRequest
* request
) {
1063 DCHECK(ContainsKey(active_requests_
, request
));
1064 QuicServerId server_id
= active_requests_
[request
];
1065 job_requests_map_
[server_id
].erase(request
);
1066 active_requests_
.erase(request
);
1069 void QuicStreamFactory::CloseAllSessions(int error
) {
1070 while (!active_sessions_
.empty()) {
1071 size_t initial_size
= active_sessions_
.size();
1072 active_sessions_
.begin()->second
->CloseSessionOnError(error
,
1073 QUIC_INTERNAL_ERROR
);
1074 DCHECK_NE(initial_size
, active_sessions_
.size());
1076 while (!all_sessions_
.empty()) {
1077 size_t initial_size
= all_sessions_
.size();
1078 all_sessions_
.begin()->first
->CloseSessionOnError(error
,
1079 QUIC_INTERNAL_ERROR
);
1080 DCHECK_NE(initial_size
, all_sessions_
.size());
1082 DCHECK(all_sessions_
.empty());
1085 scoped_ptr
<base::Value
> QuicStreamFactory::QuicStreamFactoryInfoToValue()
1087 scoped_ptr
<base::ListValue
> list(new base::ListValue());
1089 for (SessionMap::const_iterator it
= active_sessions_
.begin();
1090 it
!= active_sessions_
.end(); ++it
) {
1091 const QuicServerId
& server_id
= it
->first
;
1092 QuicChromiumClientSession
* session
= it
->second
;
1093 const AliasSet
& aliases
= session_aliases_
.find(session
)->second
;
1094 // Only add a session to the list once.
1095 if (server_id
== *aliases
.begin()) {
1096 std::set
<HostPortPair
> hosts
;
1097 for (AliasSet::const_iterator alias_it
= aliases
.begin();
1098 alias_it
!= aliases
.end(); ++alias_it
) {
1099 hosts
.insert(alias_it
->host_port_pair());
1101 list
->Append(session
->GetInfoAsValue(hosts
));
1107 void QuicStreamFactory::ClearCachedStatesInCryptoConfig() {
1108 crypto_config_
.ClearCachedStates();
1111 void QuicStreamFactory::OnIPAddressChanged() {
1112 CloseAllSessions(ERR_NETWORK_CHANGED
);
1113 set_require_confirmation(true);
1116 void QuicStreamFactory::OnCertAdded(const X509Certificate
* cert
) {
1117 CloseAllSessions(ERR_CERT_DATABASE_CHANGED
);
1120 void QuicStreamFactory::OnCACertChanged(const X509Certificate
* cert
) {
1121 // We should flush the sessions if we removed trust from a
1122 // cert, because a previously trusted server may have become
1125 // We should not flush the sessions if we added trust to a cert.
1127 // Since the OnCACertChanged method doesn't tell us what
1128 // kind of change it is, we have to flush the socket
1129 // pools to be safe.
1130 CloseAllSessions(ERR_CERT_DATABASE_CHANGED
);
1133 bool QuicStreamFactory::HasActiveSession(
1134 const QuicServerId
& server_id
) const {
1135 return ContainsKey(active_sessions_
, server_id
);
1138 bool QuicStreamFactory::HasActiveJob(const QuicServerId
& key
) const {
1139 return ContainsKey(active_jobs_
, key
);
1142 int QuicStreamFactory::CreateSession(const QuicServerId
& server_id
,
1143 int cert_verify_flags
,
1144 scoped_ptr
<QuicServerInfo
> server_info
,
1145 const AddressList
& address_list
,
1146 base::TimeTicks dns_resolution_end_time
,
1147 const BoundNetLog
& net_log
,
1148 QuicChromiumClientSession
** session
) {
1149 bool enable_port_selection
= enable_port_selection_
;
1150 if (enable_port_selection
&&
1151 ContainsKey(gone_away_aliases_
, server_id
)) {
1152 // Disable port selection when the server is going away.
1153 // There is no point in trying to return to the same server, if
1154 // that server is no longer handling requests.
1155 enable_port_selection
= false;
1156 gone_away_aliases_
.erase(server_id
);
1159 QuicConnectionId connection_id
= random_generator_
->RandUint64();
1160 IPEndPoint addr
= *address_list
.begin();
1161 scoped_refptr
<PortSuggester
> port_suggester
=
1162 new PortSuggester(server_id
.host_port_pair(), port_seed_
);
1163 DatagramSocket::BindType bind_type
= enable_port_selection
?
1164 DatagramSocket::RANDOM_BIND
: // Use our callback.
1165 DatagramSocket::DEFAULT_BIND
; // Use OS to randomize.
1166 scoped_ptr
<DatagramClientSocket
> socket(
1167 client_socket_factory_
->CreateDatagramClientSocket(
1169 base::Bind(&PortSuggester::SuggestPort
, port_suggester
),
1170 net_log
.net_log(), net_log
.source()));
1172 if (enable_non_blocking_io_
&&
1173 client_socket_factory_
== ClientSocketFactory::GetDefaultFactory()) {
1175 static_cast<UDPClientSocket
*>(socket
.get())->UseNonBlockingIO();
1179 int rv
= socket
->Connect(addr
);
1182 HistogramCreateSessionFailure(CREATION_ERROR_CONNECTING_SOCKET
);
1185 UMA_HISTOGRAM_COUNTS("Net.QuicEphemeralPortsSuggested",
1186 port_suggester
->call_count());
1187 if (enable_port_selection
) {
1188 DCHECK_LE(1u, port_suggester
->call_count());
1190 DCHECK_EQ(0u, port_suggester
->call_count());
1193 rv
= socket
->SetReceiveBufferSize(socket_receive_buffer_size_
);
1195 HistogramCreateSessionFailure(CREATION_ERROR_SETTING_RECEIVE_BUFFER
);
1198 // Set a buffer large enough to contain the initial CWND's worth of packet
1199 // to work around the problem with CHLO packets being sent out with the
1200 // wrong encryption level, when the send buffer is full.
1201 rv
= socket
->SetSendBufferSize(kMaxPacketSize
* 20);
1203 HistogramCreateSessionFailure(CREATION_ERROR_SETTING_SEND_BUFFER
);
1207 socket
->GetLocalAddress(&local_address_
);
1208 if (check_persisted_supports_quic_
&& http_server_properties_
) {
1209 check_persisted_supports_quic_
= false;
1210 IPAddressNumber last_address
;
1211 if (http_server_properties_
->GetSupportsQuic(&last_address
) &&
1212 last_address
== local_address_
.address()) {
1213 require_confirmation_
= false;
1217 DefaultPacketWriterFactory
packet_writer_factory(socket
.get());
1219 if (!helper_
.get()) {
1221 new QuicConnectionHelper(base::ThreadTaskRunnerHandle::Get().get(),
1222 clock_
.get(), random_generator_
));
1225 QuicConnection
* connection
= new QuicConnection(
1226 connection_id
, addr
, helper_
.get(), packet_writer_factory
,
1227 true /* owns_writer */, Perspective::IS_CLIENT
, server_id
.is_https(),
1228 supported_versions_
);
1229 connection
->set_max_packet_length(max_packet_length_
);
1231 InitializeCachedStateInCryptoConfig(server_id
, server_info
);
1233 QuicConfig config
= config_
;
1234 config
.SetSocketReceiveBufferToSend(socket_receive_buffer_size_
);
1235 config
.set_max_undecryptable_packets(kMaxUndecryptablePackets
);
1236 config
.SetInitialSessionFlowControlWindowToSend(
1237 kQuicSessionMaxRecvWindowSize
);
1238 config
.SetInitialStreamFlowControlWindowToSend(kQuicStreamMaxRecvWindowSize
);
1239 int64 srtt
= GetServerNetworkStatsSmoothedRttInMicroseconds(server_id
);
1241 config
.SetInitialRoundTripTimeUsToSend(static_cast<uint32
>(srtt
));
1242 config
.SetBytesForConnectionIdToSend(0);
1244 if (quic_server_info_factory_
&& !server_info
) {
1245 // Start the disk cache loading so that we can persist the newer QUIC server
1246 // information and/or inform the disk cache that we have reused
1248 server_info
.reset(quic_server_info_factory_
->GetForServer(server_id
));
1249 server_info
->Start();
1252 *session
= new QuicChromiumClientSession(
1253 connection
, socket
.Pass(), this, quic_crypto_client_stream_factory_
,
1254 transport_security_state_
, server_info
.Pass(), server_id
,
1255 cert_verify_flags
, config
, &crypto_config_
,
1256 network_connection_
.GetDescription(), dns_resolution_end_time
,
1257 base::ThreadTaskRunnerHandle::Get().get(), net_log
.net_log());
1259 all_sessions_
[*session
] = server_id
; // owning pointer
1261 (*session
)->Initialize();
1262 bool closed_during_initialize
=
1263 !ContainsKey(all_sessions_
, *session
) ||
1264 !(*session
)->connection()->connected();
1265 UMA_HISTOGRAM_BOOLEAN("Net.QuicSession.ClosedDuringInitializeSession",
1266 closed_during_initialize
);
1267 if (closed_during_initialize
) {
1268 DLOG(DFATAL
) << "Session closed during initialize";
1270 return ERR_CONNECTION_CLOSED
;
1275 void QuicStreamFactory::ActivateSession(const QuicServerId
& server_id
,
1276 QuicChromiumClientSession
* session
) {
1277 DCHECK(!HasActiveSession(server_id
));
1278 UMA_HISTOGRAM_COUNTS("Net.QuicActiveSessions", active_sessions_
.size());
1279 active_sessions_
[server_id
] = session
;
1280 session_aliases_
[session
].insert(server_id
);
1281 const IpAliasKey
ip_alias_key(session
->connection()->peer_address(),
1282 server_id
.is_https());
1283 DCHECK(!ContainsKey(ip_aliases_
[ip_alias_key
], session
));
1284 ip_aliases_
[ip_alias_key
].insert(session
);
1287 int64
QuicStreamFactory::GetServerNetworkStatsSmoothedRttInMicroseconds(
1288 const QuicServerId
& server_id
) const {
1289 if (!http_server_properties_
)
1291 const ServerNetworkStats
* stats
=
1292 http_server_properties_
->GetServerNetworkStats(
1293 server_id
.host_port_pair());
1294 if (stats
== nullptr)
1296 return stats
->srtt
.InMicroseconds();
1299 bool QuicStreamFactory::WasQuicRecentlyBroken(
1300 const QuicServerId
& server_id
) const {
1301 if (!http_server_properties_
)
1303 const AlternativeService
alternative_service(QUIC
,
1304 server_id
.host_port_pair());
1305 return http_server_properties_
->WasAlternativeServiceRecentlyBroken(
1306 alternative_service
);
1309 bool QuicStreamFactory::CryptoConfigCacheIsEmpty(
1310 const QuicServerId
& server_id
) {
1311 QuicCryptoClientConfig::CachedState
* cached
=
1312 crypto_config_
.LookupOrCreate(server_id
);
1313 return cached
->IsEmpty();
1316 void QuicStreamFactory::InitializeCachedStateInCryptoConfig(
1317 const QuicServerId
& server_id
,
1318 const scoped_ptr
<QuicServerInfo
>& server_info
) {
1319 // |server_info| will be NULL, if a non-empty server config already exists in
1320 // the memory cache. This is a minor optimization to avoid LookupOrCreate.
1324 QuicCryptoClientConfig::CachedState
* cached
=
1325 crypto_config_
.LookupOrCreate(server_id
);
1326 if (!cached
->IsEmpty())
1329 if (http_server_properties_
) {
1330 if (quic_supported_servers_at_startup_
.empty()) {
1331 for (const std::pair
<const HostPortPair
, AlternativeServiceInfoVector
>&
1332 key_value
: http_server_properties_
->alternative_service_map()) {
1333 for (const AlternativeServiceInfo
& alternative_service_info
:
1335 if (alternative_service_info
.alternative_service
.protocol
== QUIC
) {
1336 quic_supported_servers_at_startup_
.insert(key_value
.first
);
1343 // TODO(rtenneti): Delete the following histogram after collecting stats.
1344 // If the AlternativeServiceMap contained an entry for this host, check if
1345 // the disk cache contained an entry for it.
1346 if (ContainsKey(quic_supported_servers_at_startup_
,
1347 server_id
.host_port_pair())) {
1348 UMA_HISTOGRAM_BOOLEAN(
1349 "Net.QuicServerInfo.ExpectConfigMissingFromDiskCache",
1350 server_info
->state().server_config
.empty());
1354 if (!cached
->Initialize(server_info
->state().server_config
,
1355 server_info
->state().source_address_token
,
1356 server_info
->state().certs
,
1357 server_info
->state().server_config_sig
,
1361 if (!server_id
.is_https()) {
1362 // Don't check the certificates for insecure QUIC.
1363 cached
->SetProofValid();
1367 void QuicStreamFactory::ProcessGoingAwaySession(
1368 QuicChromiumClientSession
* session
,
1369 const QuicServerId
& server_id
,
1370 bool session_was_active
) {
1371 if (!http_server_properties_
)
1374 const QuicConnectionStats
& stats
= session
->connection()->GetStats();
1375 const AlternativeService
alternative_service(QUIC
,
1376 server_id
.host_port_pair());
1377 if (session
->IsCryptoHandshakeConfirmed()) {
1378 http_server_properties_
->ConfirmAlternativeService(alternative_service
);
1379 ServerNetworkStats network_stats
;
1380 network_stats
.srtt
= base::TimeDelta::FromMicroseconds(stats
.srtt_us
);
1381 network_stats
.bandwidth_estimate
= stats
.estimated_bandwidth
;
1382 http_server_properties_
->SetServerNetworkStats(server_id
.host_port_pair(),
1387 UMA_HISTOGRAM_COUNTS("Net.QuicHandshakeNotConfirmedNumPacketsReceived",
1388 stats
.packets_received
);
1390 if (!session_was_active
)
1393 // TODO(rch): In the special case where the session has received no
1394 // packets from the peer, we should consider blacklisting this
1395 // differently so that we still race TCP but we don't consider the
1396 // session connected until the handshake has been confirmed.
1397 HistogramBrokenAlternateProtocolLocation(
1398 BROKEN_ALTERNATE_PROTOCOL_LOCATION_QUIC_STREAM_FACTORY
);
1400 // Since the session was active, there's no longer an
1401 // HttpStreamFactoryImpl::Job running which can mark it broken, unless the TCP
1402 // job also fails. So to avoid not using QUIC when we otherwise could, we mark
1403 // it as recently broken, which means that 0-RTT will be disabled but we'll
1405 http_server_properties_
->MarkAlternativeServiceRecentlyBroken(
1406 alternative_service
);