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"
61 enum CreateSessionFailure
{
62 CREATION_ERROR_CONNECTING_SOCKET
,
63 CREATION_ERROR_SETTING_RECEIVE_BUFFER
,
64 CREATION_ERROR_SETTING_SEND_BUFFER
,
68 // When a connection is idle for 30 seconds it will be closed.
69 const int kIdleConnectionTimeoutSeconds
= 30;
71 // The maximum receive window sizes for QUIC sessions and streams.
72 const int32 kQuicSessionMaxRecvWindowSize
= 15 * 1024 * 1024; // 15 MB
73 const int32 kQuicStreamMaxRecvWindowSize
= 6 * 1024 * 1024; // 6 MB
75 // Set the maximum number of undecryptable packets the connection will store.
76 const int32 kMaxUndecryptablePackets
= 100;
78 void HistogramCreateSessionFailure(enum CreateSessionFailure error
) {
79 UMA_HISTOGRAM_ENUMERATION("Net.QuicSession.CreationError", error
,
83 bool IsEcdsaSupported() {
85 if (base::win::GetVersion() < base::win::VERSION_VISTA
)
92 QuicConfig
InitializeQuicConfig(const QuicTagVector
& connection_options
) {
94 config
.SetIdleConnectionStateLifetime(
95 QuicTime::Delta::FromSeconds(kIdleConnectionTimeoutSeconds
),
96 QuicTime::Delta::FromSeconds(kIdleConnectionTimeoutSeconds
));
97 config
.SetConnectionOptionsToSend(connection_options
);
101 class DefaultPacketWriterFactory
: public QuicConnection::PacketWriterFactory
{
103 explicit DefaultPacketWriterFactory(DatagramClientSocket
* socket
)
105 ~DefaultPacketWriterFactory() override
{}
107 QuicPacketWriter
* Create(QuicConnection
* connection
) const override
;
110 DatagramClientSocket
* socket_
;
113 QuicPacketWriter
* DefaultPacketWriterFactory::Create(
114 QuicConnection
* connection
) const {
115 scoped_ptr
<QuicDefaultPacketWriter
> writer(
116 new QuicDefaultPacketWriter(socket_
));
117 writer
->SetConnection(connection
);
118 return writer
.release();
123 QuicStreamFactory::IpAliasKey::IpAliasKey() {}
125 QuicStreamFactory::IpAliasKey::IpAliasKey(IPEndPoint ip_endpoint
,
127 : ip_endpoint(ip_endpoint
),
128 is_https(is_https
) {}
130 QuicStreamFactory::IpAliasKey::~IpAliasKey() {}
132 bool QuicStreamFactory::IpAliasKey::operator<(
133 const QuicStreamFactory::IpAliasKey
& other
) const {
134 if (!(ip_endpoint
== other
.ip_endpoint
)) {
135 return ip_endpoint
< other
.ip_endpoint
;
137 return is_https
< other
.is_https
;
140 bool QuicStreamFactory::IpAliasKey::operator==(
141 const QuicStreamFactory::IpAliasKey
& other
) const {
142 return is_https
== other
.is_https
&&
143 ip_endpoint
== other
.ip_endpoint
;
146 // Responsible for creating a new QUIC session to the specified server, and
147 // for notifying any associated requests when complete.
148 class QuicStreamFactory::Job
{
150 Job(QuicStreamFactory
* factory
,
151 HostResolver
* host_resolver
,
152 const HostPortPair
& host_port_pair
,
153 bool server_and_origin_have_same_host
,
155 bool was_alternative_service_recently_broken
,
156 PrivacyMode privacy_mode
,
157 int cert_verify_flags
,
159 QuicServerInfo
* server_info
,
160 const BoundNetLog
& net_log
);
162 // Creates a new job to handle the resumption of for connecting an
164 Job(QuicStreamFactory
* factory
,
165 HostResolver
* host_resolver
,
166 QuicChromiumClientSession
* session
,
167 QuicServerId server_id
);
171 int Run(const CompletionCallback
& callback
);
175 int DoResolveHostComplete(int rv
);
176 int DoLoadServerInfo();
177 int DoLoadServerInfoComplete(int rv
);
179 int DoResumeConnect();
180 int DoConnectComplete(int rv
);
182 void OnIOComplete(int rv
);
184 void RunAuxilaryJob();
188 void CancelWaitForDataReadyCallback();
190 const QuicServerId
server_id() const { return server_id_
; }
192 base::WeakPtr
<Job
> GetWeakPtr() { return weak_factory_
.GetWeakPtr(); }
198 STATE_RESOLVE_HOST_COMPLETE
,
199 STATE_LOAD_SERVER_INFO
,
200 STATE_LOAD_SERVER_INFO_COMPLETE
,
202 STATE_RESUME_CONNECT
,
203 STATE_CONNECT_COMPLETE
,
207 QuicStreamFactory
* factory_
;
208 SingleRequestHostResolver host_resolver_
;
209 QuicServerId server_id_
;
210 int cert_verify_flags_
;
211 // True if and only if server and origin have the same hostname.
212 bool server_and_origin_have_same_host_
;
214 bool was_alternative_service_recently_broken_
;
215 scoped_ptr
<QuicServerInfo
> server_info_
;
216 bool started_another_job_
;
217 const BoundNetLog net_log_
;
218 QuicChromiumClientSession
* session_
;
219 CompletionCallback callback_
;
220 AddressList address_list_
;
221 base::TimeTicks dns_resolution_start_time_
;
222 base::TimeTicks dns_resolution_end_time_
;
223 base::WeakPtrFactory
<Job
> weak_factory_
;
224 DISALLOW_COPY_AND_ASSIGN(Job
);
227 QuicStreamFactory::Job::Job(QuicStreamFactory
* factory
,
228 HostResolver
* host_resolver
,
229 const HostPortPair
& host_port_pair
,
230 bool server_and_origin_have_same_host
,
232 bool was_alternative_service_recently_broken
,
233 PrivacyMode privacy_mode
,
234 int cert_verify_flags
,
236 QuicServerInfo
* server_info
,
237 const BoundNetLog
& net_log
)
238 : io_state_(STATE_RESOLVE_HOST
),
240 host_resolver_(host_resolver
),
241 server_id_(host_port_pair
, is_https
, privacy_mode
),
242 cert_verify_flags_(cert_verify_flags
),
243 server_and_origin_have_same_host_(server_and_origin_have_same_host
),
245 was_alternative_service_recently_broken_(
246 was_alternative_service_recently_broken
),
247 server_info_(server_info
),
248 started_another_job_(false),
251 weak_factory_(this) {
254 QuicStreamFactory::Job::Job(QuicStreamFactory
* factory
,
255 HostResolver
* host_resolver
,
256 QuicChromiumClientSession
* session
,
257 QuicServerId server_id
)
258 : io_state_(STATE_RESUME_CONNECT
),
260 host_resolver_(host_resolver
), // unused
261 server_id_(server_id
),
262 cert_verify_flags_(0), // unused
263 server_and_origin_have_same_host_(false), // unused
264 is_post_(false), // unused
265 was_alternative_service_recently_broken_(false), // unused
266 started_another_job_(false), // unused
267 net_log_(session
->net_log()), // unused
269 weak_factory_(this) {}
271 QuicStreamFactory::Job::~Job() {
272 // If disk cache has a pending WaitForDataReadyCallback, cancel that callback.
274 server_info_
->ResetWaitForDataReadyCallback();
277 int QuicStreamFactory::Job::Run(const CompletionCallback
& callback
) {
279 if (rv
== ERR_IO_PENDING
)
280 callback_
= callback
;
282 return rv
> 0 ? OK
: rv
;
285 int QuicStreamFactory::Job::DoLoop(int rv
) {
287 IoState state
= io_state_
;
288 io_state_
= STATE_NONE
;
290 case STATE_RESOLVE_HOST
:
292 rv
= DoResolveHost();
294 case STATE_RESOLVE_HOST_COMPLETE
:
295 rv
= DoResolveHostComplete(rv
);
297 case STATE_LOAD_SERVER_INFO
:
299 rv
= DoLoadServerInfo();
301 case STATE_LOAD_SERVER_INFO_COMPLETE
:
302 rv
= DoLoadServerInfoComplete(rv
);
308 case STATE_RESUME_CONNECT
:
310 rv
= DoResumeConnect();
312 case STATE_CONNECT_COMPLETE
:
313 rv
= DoConnectComplete(rv
);
316 NOTREACHED() << "io_state_: " << io_state_
;
319 } while (io_state_
!= STATE_NONE
&& rv
!= ERR_IO_PENDING
);
323 void QuicStreamFactory::Job::OnIOComplete(int rv
) {
325 if (rv
!= ERR_IO_PENDING
&& !callback_
.is_null()) {
330 void QuicStreamFactory::Job::RunAuxilaryJob() {
331 int rv
= Run(base::Bind(&QuicStreamFactory::OnJobComplete
,
332 base::Unretained(factory_
), this));
333 if (rv
!= ERR_IO_PENDING
)
334 factory_
->OnJobComplete(this, rv
);
337 void QuicStreamFactory::Job::Cancel() {
340 // TODO(rtenneti): Temporary CHECK while investigating crbug.com/473893.
341 DCHECK(session_
->connection());
342 session_
->connection()->SendConnectionClose(QUIC_CONNECTION_CANCELLED
);
346 void QuicStreamFactory::Job::CancelWaitForDataReadyCallback() {
347 // If we are waiting for WaitForDataReadyCallback, then cancel the callback.
348 if (io_state_
!= STATE_LOAD_SERVER_INFO_COMPLETE
)
350 server_info_
->CancelWaitForDataReadyCallback();
354 int QuicStreamFactory::Job::DoResolveHost() {
355 // Start loading the data now, and wait for it after we resolve the host.
357 server_info_
->Start();
360 io_state_
= STATE_RESOLVE_HOST_COMPLETE
;
361 dns_resolution_start_time_
= base::TimeTicks::Now();
362 return host_resolver_
.Resolve(
363 HostResolver::RequestInfo(server_id_
.host_port_pair()), DEFAULT_PRIORITY
,
365 base::Bind(&QuicStreamFactory::Job::OnIOComplete
, GetWeakPtr()),
369 int QuicStreamFactory::Job::DoResolveHostComplete(int rv
) {
370 dns_resolution_end_time_
= base::TimeTicks::Now();
371 UMA_HISTOGRAM_TIMES("Net.QuicSession.HostResolutionTime",
372 dns_resolution_end_time_
- dns_resolution_start_time_
);
376 DCHECK(!factory_
->HasActiveSession(server_id_
));
378 // Inform the factory of this resolution, which will set up
379 // a session alias, if possible.
380 if (factory_
->OnResolution(server_id_
, address_list_
)) {
385 io_state_
= STATE_LOAD_SERVER_INFO
;
387 io_state_
= STATE_CONNECT
;
391 int QuicStreamFactory::Job::DoLoadServerInfo() {
392 io_state_
= STATE_LOAD_SERVER_INFO_COMPLETE
;
394 DCHECK(server_info_
);
396 // To mitigate the effects of disk cache taking too long to load QUIC server
397 // information, set up a timer to cancel WaitForDataReady's callback.
398 if (factory_
->load_server_info_timeout_srtt_multiplier_
> 0) {
399 const int kMaxLoadServerInfoTimeoutMs
= 50;
400 // Wait for DiskCache a maximum of 50ms.
401 int64 load_server_info_timeout_ms
=
402 min(static_cast<int>(
403 (factory_
->load_server_info_timeout_srtt_multiplier_
*
404 factory_
->GetServerNetworkStatsSmoothedRttInMicroseconds(
407 kMaxLoadServerInfoTimeoutMs
);
408 if (load_server_info_timeout_ms
> 0) {
409 factory_
->task_runner_
->PostDelayedTask(
411 base::Bind(&QuicStreamFactory::Job::CancelWaitForDataReadyCallback
,
413 base::TimeDelta::FromMilliseconds(load_server_info_timeout_ms
));
417 int rv
= server_info_
->WaitForDataReady(
418 base::Bind(&QuicStreamFactory::Job::OnIOComplete
, GetWeakPtr()));
419 if (rv
== ERR_IO_PENDING
&& factory_
->enable_connection_racing()) {
420 // If we are waiting to load server config from the disk cache, then start
422 started_another_job_
= true;
423 factory_
->CreateAuxilaryJob(server_id_
, cert_verify_flags_
,
424 server_and_origin_have_same_host_
, is_post_
,
430 int QuicStreamFactory::Job::DoLoadServerInfoComplete(int rv
) {
431 UMA_HISTOGRAM_TIMES("Net.QuicServerInfo.DiskCacheWaitForDataReadyTime",
432 base::TimeTicks::Now() - dns_resolution_end_time_
);
435 server_info_
.reset();
437 if (started_another_job_
&&
438 (!server_info_
|| server_info_
->state().server_config
.empty() ||
439 !factory_
->CryptoConfigCacheIsEmpty(server_id_
))) {
440 // If we have started another job and if we didn't load the server config
441 // from the disk cache or if we have received a new server config from the
442 // server, then cancel the current job.
443 io_state_
= STATE_NONE
;
444 return ERR_CONNECTION_CLOSED
;
447 io_state_
= STATE_CONNECT
;
451 int QuicStreamFactory::Job::DoConnect() {
452 io_state_
= STATE_CONNECT_COMPLETE
;
454 int rv
= factory_
->CreateSession(
455 server_id_
, cert_verify_flags_
, server_info_
.Pass(), address_list_
,
456 dns_resolution_end_time_
, net_log_
, &session_
);
458 DCHECK(rv
!= ERR_IO_PENDING
);
463 if (!session_
->connection()->connected()) {
464 return ERR_CONNECTION_CLOSED
;
467 session_
->StartReading();
468 if (!session_
->connection()->connected()) {
469 return ERR_QUIC_PROTOCOL_ERROR
;
471 bool require_confirmation
= factory_
->require_confirmation() ||
472 !server_and_origin_have_same_host_
|| is_post_
||
473 was_alternative_service_recently_broken_
;
475 rv
= session_
->CryptoConnect(
476 require_confirmation
,
477 base::Bind(&QuicStreamFactory::Job::OnIOComplete
, GetWeakPtr()));
481 int QuicStreamFactory::Job::DoResumeConnect() {
482 io_state_
= STATE_CONNECT_COMPLETE
;
484 int rv
= session_
->ResumeCryptoConnect(
485 base::Bind(&QuicStreamFactory::Job::OnIOComplete
, GetWeakPtr()));
490 int QuicStreamFactory::Job::DoConnectComplete(int rv
) {
494 DCHECK(!factory_
->HasActiveSession(server_id_
));
495 // There may well now be an active session for this IP. If so, use the
496 // existing session instead.
497 AddressList
address(session_
->connection()->peer_address());
498 if (factory_
->OnResolution(server_id_
, address
)) {
499 session_
->connection()->SendConnectionClose(QUIC_CONNECTION_IP_POOLED
);
504 factory_
->ActivateSession(server_id_
, session_
);
509 QuicStreamRequest::QuicStreamRequest(QuicStreamFactory
* factory
)
510 : factory_(factory
) {}
512 QuicStreamRequest::~QuicStreamRequest() {
513 if (factory_
&& !callback_
.is_null())
514 factory_
->CancelRequest(this);
517 int QuicStreamRequest::Request(const HostPortPair
& host_port_pair
,
519 PrivacyMode privacy_mode
,
520 int cert_verify_flags
,
521 base::StringPiece origin_host
,
522 base::StringPiece method
,
523 const BoundNetLog
& net_log
,
524 const CompletionCallback
& callback
) {
526 DCHECK(callback_
.is_null());
528 origin_host_
= origin_host
.as_string();
529 privacy_mode_
= privacy_mode
;
531 factory_
->Create(host_port_pair
, is_https
, privacy_mode
,
532 cert_verify_flags
, origin_host
, method
, net_log
, this);
533 if (rv
== ERR_IO_PENDING
) {
534 host_port_pair_
= host_port_pair
;
536 callback_
= callback
;
545 void QuicStreamRequest::set_stream(scoped_ptr
<QuicHttpStream
> stream
) {
547 stream_
= stream
.Pass();
550 void QuicStreamRequest::OnRequestComplete(int rv
) {
555 scoped_ptr
<QuicHttpStream
> QuicStreamRequest::ReleaseStream() {
557 return stream_
.Pass();
560 QuicStreamFactory::QuicStreamFactory(
561 HostResolver
* host_resolver
,
562 ClientSocketFactory
* client_socket_factory
,
563 base::WeakPtr
<HttpServerProperties
> http_server_properties
,
564 CertVerifier
* cert_verifier
,
565 CertPolicyEnforcer
* cert_policy_enforcer
,
566 ChannelIDService
* channel_id_service
,
567 TransportSecurityState
* transport_security_state
,
568 QuicCryptoClientStreamFactory
* quic_crypto_client_stream_factory
,
569 QuicRandom
* random_generator
,
571 size_t max_packet_length
,
572 const std::string
& user_agent_id
,
573 const QuicVersionVector
& supported_versions
,
574 bool enable_port_selection
,
575 bool always_require_handshake_confirmation
,
576 bool disable_connection_pooling
,
577 float load_server_info_timeout_srtt_multiplier
,
578 bool enable_connection_racing
,
579 bool enable_non_blocking_io
,
580 bool disable_disk_cache
,
582 int max_number_of_lossy_connections
,
583 float packet_loss_threshold
,
584 int max_disabled_reasons
,
585 int threshold_public_resets_post_handshake
,
586 int threshold_timeouts_with_open_streams
,
587 int socket_receive_buffer_size
,
588 const QuicTagVector
& connection_options
)
589 : require_confirmation_(true),
590 host_resolver_(host_resolver
),
591 client_socket_factory_(client_socket_factory
),
592 http_server_properties_(http_server_properties
),
593 transport_security_state_(transport_security_state
),
594 quic_server_info_factory_(nullptr),
595 quic_crypto_client_stream_factory_(quic_crypto_client_stream_factory
),
596 random_generator_(random_generator
),
598 max_packet_length_(max_packet_length
),
599 config_(InitializeQuicConfig(connection_options
)),
600 supported_versions_(supported_versions
),
601 enable_port_selection_(enable_port_selection
),
602 always_require_handshake_confirmation_(
603 always_require_handshake_confirmation
),
604 disable_connection_pooling_(disable_connection_pooling
),
605 load_server_info_timeout_srtt_multiplier_(
606 load_server_info_timeout_srtt_multiplier
),
607 enable_connection_racing_(enable_connection_racing
),
608 enable_non_blocking_io_(enable_non_blocking_io
),
609 disable_disk_cache_(disable_disk_cache
),
610 prefer_aes_(prefer_aes
),
611 max_number_of_lossy_connections_(max_number_of_lossy_connections
),
612 packet_loss_threshold_(packet_loss_threshold
),
613 max_disabled_reasons_(max_disabled_reasons
),
614 num_public_resets_post_handshake_(0),
615 num_timeouts_with_open_streams_(0),
616 max_public_resets_post_handshake_(0),
617 max_timeouts_with_open_streams_(0),
618 threshold_timeouts_with_open_streams_(
619 threshold_timeouts_with_open_streams
),
620 threshold_public_resets_post_handshake_(
621 threshold_public_resets_post_handshake
),
622 socket_receive_buffer_size_(socket_receive_buffer_size
),
623 port_seed_(random_generator_
->RandUint64()),
624 check_persisted_supports_quic_(true),
625 task_runner_(nullptr),
626 weak_factory_(this) {
627 DCHECK(transport_security_state_
);
628 crypto_config_
.set_user_agent_id(user_agent_id
);
629 crypto_config_
.AddCanonicalSuffix(".c.youtube.com");
630 crypto_config_
.AddCanonicalSuffix(".googlevideo.com");
631 crypto_config_
.AddCanonicalSuffix(".googleusercontent.com");
632 crypto_config_
.SetProofVerifier(new ProofVerifierChromium(
633 cert_verifier
, cert_policy_enforcer
, transport_security_state
));
634 // TODO(rtenneti): http://crbug.com/487355. Temporary fix for b/20760730 until
635 // channel_id_service is supported in cronet.
636 if (channel_id_service
) {
637 crypto_config_
.SetChannelIDSource(
638 new ChannelIDSourceChromium(channel_id_service
));
640 #if defined(USE_OPENSSL)
641 crypto::EnsureOpenSSLInit();
642 bool has_aes_hardware_support
= !!EVP_has_aes_hardware();
645 bool has_aes_hardware_support
= cpu
.has_aesni() && cpu
.has_avx();
647 UMA_HISTOGRAM_BOOLEAN("Net.QuicSession.PreferAesGcm",
648 has_aes_hardware_support
);
649 if (has_aes_hardware_support
|| prefer_aes_
)
650 crypto_config_
.PreferAesGcm();
651 if (!IsEcdsaSupported())
652 crypto_config_
.DisableEcdsa();
655 QuicStreamFactory::~QuicStreamFactory() {
656 CloseAllSessions(ERR_ABORTED
);
657 while (!all_sessions_
.empty()) {
658 delete all_sessions_
.begin()->first
;
659 all_sessions_
.erase(all_sessions_
.begin());
661 while (!active_jobs_
.empty()) {
662 const QuicServerId server_id
= active_jobs_
.begin()->first
;
663 STLDeleteElements(&(active_jobs_
[server_id
]));
664 active_jobs_
.erase(server_id
);
668 void QuicStreamFactory::set_require_confirmation(bool require_confirmation
) {
669 require_confirmation_
= require_confirmation
;
670 if (http_server_properties_
&& (!(local_address_
== IPEndPoint()))) {
671 http_server_properties_
->SetSupportsQuic(!require_confirmation
,
672 local_address_
.address());
676 int QuicStreamFactory::Create(const HostPortPair
& host_port_pair
,
678 PrivacyMode privacy_mode
,
679 int cert_verify_flags
,
680 base::StringPiece origin_host
,
681 base::StringPiece method
,
682 const BoundNetLog
& net_log
,
683 QuicStreamRequest
* request
) {
684 QuicServerId
server_id(host_port_pair
, is_https
, privacy_mode
);
685 SessionMap::iterator it
= active_sessions_
.find(server_id
);
686 if (it
!= active_sessions_
.end()) {
687 QuicChromiumClientSession
* session
= it
->second
;
688 if (!session
->CanPool(origin_host
.as_string(), privacy_mode
))
689 return ERR_ALTERNATIVE_CERT_NOT_VALID_FOR_ORIGIN
;
690 request
->set_stream(CreateFromSession(session
));
694 if (HasActiveJob(server_id
)) {
695 active_requests_
[request
] = server_id
;
696 job_requests_map_
[server_id
].insert(request
);
697 return ERR_IO_PENDING
;
700 // TODO(rtenneti): |task_runner_| is used by the Job. Initialize task_runner_
701 // in the constructor after WebRequestActionWithThreadsTest.* tests are fixed.
703 task_runner_
= base::ThreadTaskRunnerHandle::Get().get();
705 QuicServerInfo
* quic_server_info
= nullptr;
706 if (quic_server_info_factory_
) {
707 bool load_from_disk_cache
= !disable_disk_cache_
;
708 if (http_server_properties_
) {
709 const AlternativeServiceMap
& alternative_service_map
=
710 http_server_properties_
->alternative_service_map();
711 AlternativeServiceMap::const_iterator map_it
=
712 alternative_service_map
.Peek(server_id
.host_port_pair());
713 if (map_it
!= alternative_service_map
.end()) {
714 const AlternativeServiceInfoVector
& alternative_service_info_vector
=
716 AlternativeServiceInfoVector::const_iterator it
;
717 for (it
= alternative_service_info_vector
.begin();
718 it
!= alternative_service_info_vector
.end(); ++it
) {
719 if (it
->alternative_service
.protocol
== QUIC
)
722 // If there is no entry for QUIC, consider that as a new server and
723 // don't wait for Cache thread to load the data for that server.
724 if (it
== alternative_service_info_vector
.end())
725 load_from_disk_cache
= false;
728 if (load_from_disk_cache
&& CryptoConfigCacheIsEmpty(server_id
)) {
729 quic_server_info
= quic_server_info_factory_
->GetForServer(server_id
);
733 bool server_and_origin_have_same_host
= host_port_pair
.host() == origin_host
;
734 scoped_ptr
<Job
> job(new Job(this, host_resolver_
, host_port_pair
,
735 server_and_origin_have_same_host
, is_https
,
736 WasQuicRecentlyBroken(server_id
), privacy_mode
,
737 cert_verify_flags
, method
== "POST" /* is_post */,
738 quic_server_info
, net_log
));
739 int rv
= job
->Run(base::Bind(&QuicStreamFactory::OnJobComplete
,
740 base::Unretained(this), job
.get()));
741 if (rv
== ERR_IO_PENDING
) {
742 active_requests_
[request
] = server_id
;
743 job_requests_map_
[server_id
].insert(request
);
744 active_jobs_
[server_id
].insert(job
.release());
748 it
= active_sessions_
.find(server_id
);
749 DCHECK(it
!= active_sessions_
.end());
750 QuicChromiumClientSession
* session
= it
->second
;
751 if (!session
->CanPool(origin_host
.as_string(), privacy_mode
))
752 return ERR_ALTERNATIVE_CERT_NOT_VALID_FOR_ORIGIN
;
753 request
->set_stream(CreateFromSession(session
));
758 void QuicStreamFactory::CreateAuxilaryJob(const QuicServerId server_id
,
759 int cert_verify_flags
,
760 bool server_and_origin_have_same_host
,
762 const BoundNetLog
& net_log
) {
764 new Job(this, host_resolver_
, server_id
.host_port_pair(),
765 server_and_origin_have_same_host
, server_id
.is_https(),
766 WasQuicRecentlyBroken(server_id
), server_id
.privacy_mode(),
767 cert_verify_flags
, is_post
, nullptr, net_log
);
768 active_jobs_
[server_id
].insert(aux_job
);
769 task_runner_
->PostTask(FROM_HERE
,
770 base::Bind(&QuicStreamFactory::Job::RunAuxilaryJob
,
771 aux_job
->GetWeakPtr()));
774 bool QuicStreamFactory::OnResolution(
775 const QuicServerId
& server_id
,
776 const AddressList
& address_list
) {
777 DCHECK(!HasActiveSession(server_id
));
778 if (disable_connection_pooling_
) {
781 for (const IPEndPoint
& address
: address_list
) {
782 const IpAliasKey
ip_alias_key(address
, server_id
.is_https());
783 if (!ContainsKey(ip_aliases_
, ip_alias_key
))
786 const SessionSet
& sessions
= ip_aliases_
[ip_alias_key
];
787 for (QuicChromiumClientSession
* session
: sessions
) {
788 if (!session
->CanPool(server_id
.host(), server_id
.privacy_mode()))
790 active_sessions_
[server_id
] = session
;
791 session_aliases_
[session
].insert(server_id
);
798 void QuicStreamFactory::OnJobComplete(Job
* job
, int rv
) {
799 QuicServerId server_id
= job
->server_id();
801 JobSet
* jobs
= &(active_jobs_
[server_id
]);
802 if (jobs
->size() > 1) {
803 // If there is another pending job, then we can delete this job and let
804 // the other job handle the request.
813 if (!always_require_handshake_confirmation_
)
814 set_require_confirmation(false);
816 // Create all the streams, but do not notify them yet.
817 SessionMap::iterator session_it
= active_sessions_
.find(server_id
);
818 for (RequestSet::iterator request_it
= job_requests_map_
[server_id
].begin();
819 request_it
!= job_requests_map_
[server_id
].end();) {
820 DCHECK(session_it
!= active_sessions_
.end());
821 QuicChromiumClientSession
* session
= session_it
->second
;
822 QuicStreamRequest
* request
= *request_it
;
823 if (!session
->CanPool(request
->origin_host(), request
->privacy_mode())) {
824 RequestSet::iterator old_request_it
= request_it
;
826 // Remove request from containers so that OnRequestComplete() is not
827 // called later again on the same request.
828 job_requests_map_
[server_id
].erase(old_request_it
);
829 active_requests_
.erase(request
);
830 // Notify request of certificate error.
831 request
->OnRequestComplete(ERR_ALTERNATIVE_CERT_NOT_VALID_FOR_ORIGIN
);
834 request
->set_stream(CreateFromSession(session
));
839 while (!job_requests_map_
[server_id
].empty()) {
840 RequestSet::iterator it
= job_requests_map_
[server_id
].begin();
841 QuicStreamRequest
* request
= *it
;
842 job_requests_map_
[server_id
].erase(it
);
843 active_requests_
.erase(request
);
844 // Even though we're invoking callbacks here, we don't need to worry
845 // about |this| being deleted, because the factory is owned by the
846 // profile which can not be deleted via callbacks.
847 request
->OnRequestComplete(rv
);
850 for (Job
* other_job
: active_jobs_
[server_id
]) {
851 if (other_job
!= job
)
855 STLDeleteElements(&(active_jobs_
[server_id
]));
856 active_jobs_
.erase(server_id
);
857 job_requests_map_
.erase(server_id
);
860 scoped_ptr
<QuicHttpStream
> QuicStreamFactory::CreateFromSession(
861 QuicChromiumClientSession
* session
) {
862 return scoped_ptr
<QuicHttpStream
>(new QuicHttpStream(session
->GetWeakPtr()));
865 QuicChromiumClientSession::QuicDisabledReason
866 QuicStreamFactory::QuicDisabledReason(uint16 port
) const {
867 if (max_number_of_lossy_connections_
> 0 &&
868 number_of_lossy_connections_
.find(port
) !=
869 number_of_lossy_connections_
.end() &&
870 number_of_lossy_connections_
.at(port
) >=
871 max_number_of_lossy_connections_
) {
872 return QuicChromiumClientSession::QUIC_DISABLED_BAD_PACKET_LOSS_RATE
;
874 if (threshold_public_resets_post_handshake_
> 0 &&
875 num_public_resets_post_handshake_
>=
876 threshold_public_resets_post_handshake_
) {
877 return QuicChromiumClientSession::QUIC_DISABLED_PUBLIC_RESET_POST_HANDSHAKE
;
879 if (threshold_timeouts_with_open_streams_
> 0 &&
880 num_timeouts_with_open_streams_
>=
881 threshold_timeouts_with_open_streams_
) {
882 return QuicChromiumClientSession::QUIC_DISABLED_TIMEOUT_WITH_OPEN_STREAMS
;
884 return QuicChromiumClientSession::QUIC_DISABLED_NOT
;
887 const char* QuicStreamFactory::QuicDisabledReasonString() const {
888 // TODO(ckrasic) - better solution for port/lossy connections?
889 const uint16 port
= 443;
890 switch (QuicDisabledReason(port
)) {
891 case QuicChromiumClientSession::QUIC_DISABLED_BAD_PACKET_LOSS_RATE
:
892 return "Bad packet loss rate.";
893 case QuicChromiumClientSession::QUIC_DISABLED_PUBLIC_RESET_POST_HANDSHAKE
:
894 return "Public resets after successful handshakes.";
895 case QuicChromiumClientSession::QUIC_DISABLED_TIMEOUT_WITH_OPEN_STREAMS
:
896 return "Connection timeouts with streams open.";
902 bool QuicStreamFactory::IsQuicDisabled(uint16 port
) {
903 return QuicDisabledReason(port
) !=
904 QuicChromiumClientSession::QUIC_DISABLED_NOT
;
907 bool QuicStreamFactory::OnHandshakeConfirmed(QuicChromiumClientSession
* session
,
908 float packet_loss_rate
) {
910 uint16 port
= session
->server_id().port();
911 if (packet_loss_rate
< packet_loss_threshold_
) {
912 number_of_lossy_connections_
[port
] = 0;
916 if (http_server_properties_
) {
917 // We mark it as recently broken, which means that 0-RTT will be disabled
918 // but we'll still race.
919 http_server_properties_
->MarkAlternativeServiceRecentlyBroken(
920 AlternativeService(QUIC
, session
->server_id().host(), port
));
923 bool was_quic_disabled
= IsQuicDisabled(port
);
924 ++number_of_lossy_connections_
[port
];
926 // Collect data for port 443 for packet loss events.
927 if (port
== 443 && max_number_of_lossy_connections_
> 0) {
928 UMA_HISTOGRAM_SPARSE_SLOWLY(
929 base::StringPrintf("Net.QuicStreamFactory.BadPacketLossEvents%d",
930 max_number_of_lossy_connections_
),
931 std::min(number_of_lossy_connections_
[port
],
932 max_number_of_lossy_connections_
));
935 bool is_quic_disabled
= IsQuicDisabled(port
);
936 if (is_quic_disabled
) {
937 // Close QUIC connection if Quic is disabled for this port.
938 session
->CloseSessionOnErrorAndNotifyFactoryLater(
939 ERR_ABORTED
, QUIC_BAD_PACKET_LOSS_RATE
);
941 // If this bad packet loss rate disabled the QUIC, then record it.
942 if (!was_quic_disabled
)
943 UMA_HISTOGRAM_SPARSE_SLOWLY("Net.QuicStreamFactory.QuicIsDisabled", port
);
945 return is_quic_disabled
;
948 void QuicStreamFactory::OnIdleSession(QuicChromiumClientSession
* session
) {}
950 void QuicStreamFactory::OnSessionGoingAway(QuicChromiumClientSession
* session
) {
951 const AliasSet
& aliases
= session_aliases_
[session
];
952 for (AliasSet::const_iterator it
= aliases
.begin(); it
!= aliases
.end();
954 DCHECK(active_sessions_
.count(*it
));
955 DCHECK_EQ(session
, active_sessions_
[*it
]);
956 // Track sessions which have recently gone away so that we can disable
958 if (session
->goaway_received()) {
959 gone_away_aliases_
.insert(*it
);
962 active_sessions_
.erase(*it
);
963 ProcessGoingAwaySession(session
, *it
, true);
965 ProcessGoingAwaySession(session
, all_sessions_
[session
], false);
966 if (!aliases
.empty()) {
967 const IpAliasKey
ip_alias_key(session
->connection()->peer_address(),
968 aliases
.begin()->is_https());
969 ip_aliases_
[ip_alias_key
].erase(session
);
970 if (ip_aliases_
[ip_alias_key
].empty()) {
971 ip_aliases_
.erase(ip_alias_key
);
974 session_aliases_
.erase(session
);
977 void QuicStreamFactory::MaybeDisableQuic(QuicChromiumClientSession
* session
) {
979 uint16 port
= session
->server_id().port();
980 if (IsQuicDisabled(port
))
983 // Expire the oldest disabled_reason if appropriate. This enforces that we
984 // only consider the max_disabled_reasons_ most recent sessions.
985 QuicChromiumClientSession::QuicDisabledReason disabled_reason
;
986 if (static_cast<int>(disabled_reasons_
.size()) == max_disabled_reasons_
) {
987 disabled_reason
= disabled_reasons_
.front();
988 disabled_reasons_
.pop_front();
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_
;
997 disabled_reason
= session
->disabled_reason();
998 disabled_reasons_
.push_back(disabled_reason
);
999 if (disabled_reason
==
1000 QuicChromiumClientSession::QUIC_DISABLED_PUBLIC_RESET_POST_HANDSHAKE
) {
1001 ++num_public_resets_post_handshake_
;
1002 } else if (disabled_reason
== QuicChromiumClientSession::
1003 QUIC_DISABLED_TIMEOUT_WITH_OPEN_STREAMS
) {
1004 ++num_timeouts_with_open_streams_
;
1006 if (num_timeouts_with_open_streams_
> max_timeouts_with_open_streams_
) {
1007 max_timeouts_with_open_streams_
= num_timeouts_with_open_streams_
;
1008 UMA_HISTOGRAM_CUSTOM_COUNTS("Net.QuicStreamFactory.TimeoutsWithOpenStreams",
1009 num_timeouts_with_open_streams_
, 0, 20, 10);
1012 if (num_public_resets_post_handshake_
> max_public_resets_post_handshake_
) {
1013 max_public_resets_post_handshake_
= num_public_resets_post_handshake_
;
1014 UMA_HISTOGRAM_CUSTOM_COUNTS(
1015 "Net.QuicStreamFactory.PublicResetsPostHandshake",
1016 num_public_resets_post_handshake_
, 0, 20, 10);
1019 if (IsQuicDisabled(port
)) {
1020 if (disabled_reason
==
1021 QuicChromiumClientSession::QUIC_DISABLED_PUBLIC_RESET_POST_HANDSHAKE
) {
1022 session
->CloseSessionOnErrorAndNotifyFactoryLater(
1023 ERR_ABORTED
, QUIC_PUBLIC_RESETS_POST_HANDSHAKE
);
1024 } else if (disabled_reason
== QuicChromiumClientSession::
1025 QUIC_DISABLED_TIMEOUT_WITH_OPEN_STREAMS
) {
1026 session
->CloseSessionOnErrorAndNotifyFactoryLater(
1027 ERR_ABORTED
, QUIC_TIMEOUTS_WITH_OPEN_STREAMS
);
1029 UMA_HISTOGRAM_ENUMERATION("Net.QuicStreamFactory.DisabledReasons",
1031 QuicChromiumClientSession::QUIC_DISABLED_MAX
);
1035 void QuicStreamFactory::OnSessionClosed(QuicChromiumClientSession
* session
) {
1036 DCHECK_EQ(0u, session
->GetNumOpenStreams());
1037 MaybeDisableQuic(session
);
1038 OnSessionGoingAway(session
);
1040 all_sessions_
.erase(session
);
1043 void QuicStreamFactory::OnSessionConnectTimeout(
1044 QuicChromiumClientSession
* session
) {
1045 const AliasSet
& aliases
= session_aliases_
[session
];
1046 for (AliasSet::const_iterator it
= aliases
.begin(); it
!= aliases
.end();
1048 DCHECK(active_sessions_
.count(*it
));
1049 DCHECK_EQ(session
, active_sessions_
[*it
]);
1050 active_sessions_
.erase(*it
);
1053 if (aliases
.empty()) {
1057 const IpAliasKey
ip_alias_key(session
->connection()->peer_address(),
1058 aliases
.begin()->is_https());
1059 ip_aliases_
[ip_alias_key
].erase(session
);
1060 if (ip_aliases_
[ip_alias_key
].empty()) {
1061 ip_aliases_
.erase(ip_alias_key
);
1063 QuicServerId server_id
= *aliases
.begin();
1064 session_aliases_
.erase(session
);
1065 Job
* job
= new Job(this, host_resolver_
, session
, server_id
);
1066 active_jobs_
[server_id
].insert(job
);
1067 int rv
= job
->Run(base::Bind(&QuicStreamFactory::OnJobComplete
,
1068 base::Unretained(this), job
));
1069 DCHECK_EQ(ERR_IO_PENDING
, rv
);
1072 void QuicStreamFactory::CancelRequest(QuicStreamRequest
* request
) {
1073 DCHECK(ContainsKey(active_requests_
, request
));
1074 QuicServerId server_id
= active_requests_
[request
];
1075 job_requests_map_
[server_id
].erase(request
);
1076 active_requests_
.erase(request
);
1079 void QuicStreamFactory::CloseAllSessions(int error
) {
1080 while (!active_sessions_
.empty()) {
1081 size_t initial_size
= active_sessions_
.size();
1082 active_sessions_
.begin()->second
->CloseSessionOnError(error
,
1083 QUIC_INTERNAL_ERROR
);
1084 DCHECK_NE(initial_size
, active_sessions_
.size());
1086 while (!all_sessions_
.empty()) {
1087 size_t initial_size
= all_sessions_
.size();
1088 all_sessions_
.begin()->first
->CloseSessionOnError(error
,
1089 QUIC_INTERNAL_ERROR
);
1090 DCHECK_NE(initial_size
, all_sessions_
.size());
1092 DCHECK(all_sessions_
.empty());
1095 scoped_ptr
<base::Value
> QuicStreamFactory::QuicStreamFactoryInfoToValue()
1097 scoped_ptr
<base::ListValue
> list(new base::ListValue());
1099 for (SessionMap::const_iterator it
= active_sessions_
.begin();
1100 it
!= active_sessions_
.end(); ++it
) {
1101 const QuicServerId
& server_id
= it
->first
;
1102 QuicChromiumClientSession
* session
= it
->second
;
1103 const AliasSet
& aliases
= session_aliases_
.find(session
)->second
;
1104 // Only add a session to the list once.
1105 if (server_id
== *aliases
.begin()) {
1106 std::set
<HostPortPair
> hosts
;
1107 for (AliasSet::const_iterator alias_it
= aliases
.begin();
1108 alias_it
!= aliases
.end(); ++alias_it
) {
1109 hosts
.insert(alias_it
->host_port_pair());
1111 list
->Append(session
->GetInfoAsValue(hosts
));
1117 void QuicStreamFactory::ClearCachedStatesInCryptoConfig() {
1118 crypto_config_
.ClearCachedStates();
1121 void QuicStreamFactory::OnIPAddressChanged() {
1122 CloseAllSessions(ERR_NETWORK_CHANGED
);
1123 set_require_confirmation(true);
1126 void QuicStreamFactory::OnSSLConfigChanged() {
1127 CloseAllSessions(ERR_CERT_DATABASE_CHANGED
);
1130 void QuicStreamFactory::OnCertAdded(const X509Certificate
* cert
) {
1131 CloseAllSessions(ERR_CERT_DATABASE_CHANGED
);
1134 void QuicStreamFactory::OnCACertChanged(const X509Certificate
* cert
) {
1135 // We should flush the sessions if we removed trust from a
1136 // cert, because a previously trusted server may have become
1139 // We should not flush the sessions if we added trust to a cert.
1141 // Since the OnCACertChanged method doesn't tell us what
1142 // kind of change it is, we have to flush the socket
1143 // pools to be safe.
1144 CloseAllSessions(ERR_CERT_DATABASE_CHANGED
);
1147 bool QuicStreamFactory::HasActiveSession(
1148 const QuicServerId
& server_id
) const {
1149 return ContainsKey(active_sessions_
, server_id
);
1152 bool QuicStreamFactory::HasActiveJob(const QuicServerId
& key
) const {
1153 return ContainsKey(active_jobs_
, key
);
1156 int QuicStreamFactory::CreateSession(const QuicServerId
& server_id
,
1157 int cert_verify_flags
,
1158 scoped_ptr
<QuicServerInfo
> server_info
,
1159 const AddressList
& address_list
,
1160 base::TimeTicks dns_resolution_end_time
,
1161 const BoundNetLog
& net_log
,
1162 QuicChromiumClientSession
** session
) {
1163 bool enable_port_selection
= enable_port_selection_
;
1164 if (enable_port_selection
&&
1165 ContainsKey(gone_away_aliases_
, server_id
)) {
1166 // Disable port selection when the server is going away.
1167 // There is no point in trying to return to the same server, if
1168 // that server is no longer handling requests.
1169 enable_port_selection
= false;
1170 gone_away_aliases_
.erase(server_id
);
1173 QuicConnectionId connection_id
= random_generator_
->RandUint64();
1174 IPEndPoint addr
= *address_list
.begin();
1175 scoped_refptr
<PortSuggester
> port_suggester
=
1176 new PortSuggester(server_id
.host_port_pair(), port_seed_
);
1177 DatagramSocket::BindType bind_type
= enable_port_selection
?
1178 DatagramSocket::RANDOM_BIND
: // Use our callback.
1179 DatagramSocket::DEFAULT_BIND
; // Use OS to randomize.
1180 scoped_ptr
<DatagramClientSocket
> socket(
1181 client_socket_factory_
->CreateDatagramClientSocket(
1183 base::Bind(&PortSuggester::SuggestPort
, port_suggester
),
1184 net_log
.net_log(), net_log
.source()));
1186 if (enable_non_blocking_io_
&&
1187 client_socket_factory_
== ClientSocketFactory::GetDefaultFactory()) {
1189 static_cast<UDPClientSocket
*>(socket
.get())->UseNonBlockingIO();
1193 int rv
= socket
->Connect(addr
);
1196 HistogramCreateSessionFailure(CREATION_ERROR_CONNECTING_SOCKET
);
1199 UMA_HISTOGRAM_COUNTS("Net.QuicEphemeralPortsSuggested",
1200 port_suggester
->call_count());
1201 if (enable_port_selection
) {
1202 DCHECK_LE(1u, port_suggester
->call_count());
1204 DCHECK_EQ(0u, port_suggester
->call_count());
1207 rv
= socket
->SetReceiveBufferSize(socket_receive_buffer_size_
);
1209 HistogramCreateSessionFailure(CREATION_ERROR_SETTING_RECEIVE_BUFFER
);
1212 // Set a buffer large enough to contain the initial CWND's worth of packet
1213 // to work around the problem with CHLO packets being sent out with the
1214 // wrong encryption level, when the send buffer is full.
1215 rv
= socket
->SetSendBufferSize(kMaxPacketSize
* 20);
1217 HistogramCreateSessionFailure(CREATION_ERROR_SETTING_SEND_BUFFER
);
1221 socket
->GetLocalAddress(&local_address_
);
1222 if (check_persisted_supports_quic_
&& http_server_properties_
) {
1223 check_persisted_supports_quic_
= false;
1224 IPAddressNumber last_address
;
1225 if (http_server_properties_
->GetSupportsQuic(&last_address
) &&
1226 last_address
== local_address_
.address()) {
1227 require_confirmation_
= false;
1231 DefaultPacketWriterFactory
packet_writer_factory(socket
.get());
1233 if (!helper_
.get()) {
1235 new QuicConnectionHelper(base::ThreadTaskRunnerHandle::Get().get(),
1236 clock_
.get(), random_generator_
));
1239 QuicConnection
* connection
= new QuicConnection(
1240 connection_id
, addr
, helper_
.get(), packet_writer_factory
,
1241 true /* owns_writer */, Perspective::IS_CLIENT
, server_id
.is_https(),
1242 supported_versions_
);
1243 connection
->set_max_packet_length(max_packet_length_
);
1245 InitializeCachedStateInCryptoConfig(server_id
, server_info
);
1247 QuicConfig config
= config_
;
1248 config
.SetSocketReceiveBufferToSend(socket_receive_buffer_size_
);
1249 config
.set_max_undecryptable_packets(kMaxUndecryptablePackets
);
1250 config
.SetInitialSessionFlowControlWindowToSend(
1251 kQuicSessionMaxRecvWindowSize
);
1252 config
.SetInitialStreamFlowControlWindowToSend(kQuicStreamMaxRecvWindowSize
);
1253 int64 srtt
= GetServerNetworkStatsSmoothedRttInMicroseconds(server_id
);
1255 config
.SetInitialRoundTripTimeUsToSend(static_cast<uint32
>(srtt
));
1256 config
.SetBytesForConnectionIdToSend(0);
1258 if (quic_server_info_factory_
&& !server_info
) {
1259 // Start the disk cache loading so that we can persist the newer QUIC server
1260 // information and/or inform the disk cache that we have reused
1262 server_info
.reset(quic_server_info_factory_
->GetForServer(server_id
));
1263 server_info
->Start();
1266 *session
= new QuicChromiumClientSession(
1267 connection
, socket
.Pass(), this, quic_crypto_client_stream_factory_
,
1268 transport_security_state_
, server_info
.Pass(), server_id
,
1269 cert_verify_flags
, config
, &crypto_config_
,
1270 network_connection_
.GetDescription(), dns_resolution_end_time
,
1271 base::ThreadTaskRunnerHandle::Get().get(), net_log
.net_log());
1273 all_sessions_
[*session
] = server_id
; // owning pointer
1275 (*session
)->Initialize();
1276 bool closed_during_initialize
=
1277 !ContainsKey(all_sessions_
, *session
) ||
1278 !(*session
)->connection()->connected();
1279 UMA_HISTOGRAM_BOOLEAN("Net.QuicSession.ClosedDuringInitializeSession",
1280 closed_during_initialize
);
1281 if (closed_during_initialize
) {
1282 DLOG(DFATAL
) << "Session closed during initialize";
1284 return ERR_CONNECTION_CLOSED
;
1289 void QuicStreamFactory::ActivateSession(const QuicServerId
& server_id
,
1290 QuicChromiumClientSession
* session
) {
1291 DCHECK(!HasActiveSession(server_id
));
1292 UMA_HISTOGRAM_COUNTS("Net.QuicActiveSessions", active_sessions_
.size());
1293 active_sessions_
[server_id
] = session
;
1294 session_aliases_
[session
].insert(server_id
);
1295 const IpAliasKey
ip_alias_key(session
->connection()->peer_address(),
1296 server_id
.is_https());
1297 DCHECK(!ContainsKey(ip_aliases_
[ip_alias_key
], session
));
1298 ip_aliases_
[ip_alias_key
].insert(session
);
1301 int64
QuicStreamFactory::GetServerNetworkStatsSmoothedRttInMicroseconds(
1302 const QuicServerId
& server_id
) const {
1303 if (!http_server_properties_
)
1305 const ServerNetworkStats
* stats
=
1306 http_server_properties_
->GetServerNetworkStats(
1307 server_id
.host_port_pair());
1308 if (stats
== nullptr)
1310 return stats
->srtt
.InMicroseconds();
1313 bool QuicStreamFactory::WasQuicRecentlyBroken(
1314 const QuicServerId
& server_id
) const {
1315 if (!http_server_properties_
)
1317 const AlternativeService
alternative_service(QUIC
,
1318 server_id
.host_port_pair());
1319 return http_server_properties_
->WasAlternativeServiceRecentlyBroken(
1320 alternative_service
);
1323 bool QuicStreamFactory::CryptoConfigCacheIsEmpty(
1324 const QuicServerId
& server_id
) {
1325 QuicCryptoClientConfig::CachedState
* cached
=
1326 crypto_config_
.LookupOrCreate(server_id
);
1327 return cached
->IsEmpty();
1330 void QuicStreamFactory::InitializeCachedStateInCryptoConfig(
1331 const QuicServerId
& server_id
,
1332 const scoped_ptr
<QuicServerInfo
>& server_info
) {
1333 // |server_info| will be NULL, if a non-empty server config already exists in
1334 // the memory cache. This is a minor optimization to avoid LookupOrCreate.
1338 QuicCryptoClientConfig::CachedState
* cached
=
1339 crypto_config_
.LookupOrCreate(server_id
);
1340 if (!cached
->IsEmpty())
1343 if (http_server_properties_
) {
1344 if (quic_supported_servers_at_startup_
.empty()) {
1345 for (const std::pair
<const HostPortPair
, AlternativeServiceInfoVector
>&
1346 key_value
: http_server_properties_
->alternative_service_map()) {
1347 for (const AlternativeServiceInfo
& alternative_service_info
:
1349 if (alternative_service_info
.alternative_service
.protocol
== QUIC
) {
1350 quic_supported_servers_at_startup_
.insert(key_value
.first
);
1357 // TODO(rtenneti): Delete the following histogram after collecting stats.
1358 // If the AlternativeServiceMap contained an entry for this host, check if
1359 // the disk cache contained an entry for it.
1360 if (ContainsKey(quic_supported_servers_at_startup_
,
1361 server_id
.host_port_pair())) {
1362 UMA_HISTOGRAM_BOOLEAN(
1363 "Net.QuicServerInfo.ExpectConfigMissingFromDiskCache",
1364 server_info
->state().server_config
.empty());
1368 if (!cached
->Initialize(server_info
->state().server_config
,
1369 server_info
->state().source_address_token
,
1370 server_info
->state().certs
,
1371 server_info
->state().server_config_sig
,
1375 if (!server_id
.is_https()) {
1376 // Don't check the certificates for insecure QUIC.
1377 cached
->SetProofValid();
1381 void QuicStreamFactory::ProcessGoingAwaySession(
1382 QuicChromiumClientSession
* session
,
1383 const QuicServerId
& server_id
,
1384 bool session_was_active
) {
1385 if (!http_server_properties_
)
1388 const QuicConnectionStats
& stats
= session
->connection()->GetStats();
1389 const AlternativeService
alternative_service(QUIC
,
1390 server_id
.host_port_pair());
1391 if (session
->IsCryptoHandshakeConfirmed()) {
1392 http_server_properties_
->ConfirmAlternativeService(alternative_service
);
1393 ServerNetworkStats network_stats
;
1394 network_stats
.srtt
= base::TimeDelta::FromMicroseconds(stats
.srtt_us
);
1395 network_stats
.bandwidth_estimate
= stats
.estimated_bandwidth
;
1396 http_server_properties_
->SetServerNetworkStats(server_id
.host_port_pair(),
1401 UMA_HISTOGRAM_COUNTS("Net.QuicHandshakeNotConfirmedNumPacketsReceived",
1402 stats
.packets_received
);
1404 if (!session_was_active
)
1407 // TODO(rch): In the special case where the session has received no
1408 // packets from the peer, we should consider blacklisting this
1409 // differently so that we still race TCP but we don't consider the
1410 // session connected until the handshake has been confirmed.
1411 HistogramBrokenAlternateProtocolLocation(
1412 BROKEN_ALTERNATE_PROTOCOL_LOCATION_QUIC_STREAM_FACTORY
);
1414 // Since the session was active, there's no longer an
1415 // HttpStreamFactoryImpl::Job running which can mark it broken, unless the TCP
1416 // job also fails. So to avoid not using QUIC when we otherwise could, we mark
1417 // it as recently broken, which means that 0-RTT will be disabled but we'll
1419 http_server_properties_
->MarkAlternativeServiceRecentlyBroken(
1420 alternative_service
);