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 // TODO(rtenneti): Temporary CHECK while investigating crbug.com/473893.
339 DCHECK(session_
->connection());
340 session_
->connection()->SendConnectionClose(QUIC_CONNECTION_CANCELLED
);
344 void QuicStreamFactory::Job::CancelWaitForDataReadyCallback() {
345 // If we are waiting for WaitForDataReadyCallback, then cancel the callback.
346 if (io_state_
!= STATE_LOAD_SERVER_INFO_COMPLETE
)
348 server_info_
->CancelWaitForDataReadyCallback();
352 int QuicStreamFactory::Job::DoResolveHost() {
353 // Start loading the data now, and wait for it after we resolve the host.
355 server_info_
->Start();
358 io_state_
= STATE_RESOLVE_HOST_COMPLETE
;
359 dns_resolution_start_time_
= base::TimeTicks::Now();
360 return host_resolver_
.Resolve(
361 HostResolver::RequestInfo(server_id_
.host_port_pair()), DEFAULT_PRIORITY
,
363 base::Bind(&QuicStreamFactory::Job::OnIOComplete
, GetWeakPtr()),
367 int QuicStreamFactory::Job::DoResolveHostComplete(int rv
) {
368 dns_resolution_end_time_
= base::TimeTicks::Now();
369 UMA_HISTOGRAM_TIMES("Net.QuicSession.HostResolutionTime",
370 dns_resolution_end_time_
- dns_resolution_start_time_
);
374 DCHECK(!factory_
->HasActiveSession(server_id_
));
376 // Inform the factory of this resolution, which will set up
377 // a session alias, if possible.
378 if (factory_
->OnResolution(server_id_
, address_list_
)) {
383 io_state_
= STATE_LOAD_SERVER_INFO
;
385 io_state_
= STATE_CONNECT
;
389 int QuicStreamFactory::Job::DoLoadServerInfo() {
390 io_state_
= STATE_LOAD_SERVER_INFO_COMPLETE
;
392 DCHECK(server_info_
);
394 // To mitigate the effects of disk cache taking too long to load QUIC server
395 // information, set up a timer to cancel WaitForDataReady's callback.
396 if (factory_
->load_server_info_timeout_srtt_multiplier_
> 0) {
397 int64 load_server_info_timeout_ms
=
398 (factory_
->load_server_info_timeout_srtt_multiplier_
*
399 factory_
->GetServerNetworkStatsSmoothedRttInMicroseconds(server_id_
)) /
401 if (load_server_info_timeout_ms
> 0) {
402 factory_
->task_runner_
->PostDelayedTask(
404 base::Bind(&QuicStreamFactory::Job::CancelWaitForDataReadyCallback
,
406 base::TimeDelta::FromMilliseconds(load_server_info_timeout_ms
));
410 int rv
= server_info_
->WaitForDataReady(
411 base::Bind(&QuicStreamFactory::Job::OnIOComplete
, GetWeakPtr()));
412 if (rv
== ERR_IO_PENDING
&& factory_
->enable_connection_racing()) {
413 // If we are waiting to load server config from the disk cache, then start
415 started_another_job_
= true;
416 factory_
->CreateAuxilaryJob(server_id_
, cert_verify_flags_
,
417 server_and_origin_have_same_host_
, is_post_
,
423 int QuicStreamFactory::Job::DoLoadServerInfoComplete(int rv
) {
424 UMA_HISTOGRAM_TIMES("Net.QuicServerInfo.DiskCacheWaitForDataReadyTime",
425 base::TimeTicks::Now() - dns_resolution_end_time_
);
428 server_info_
.reset();
430 if (started_another_job_
&&
431 (!server_info_
|| server_info_
->state().server_config
.empty() ||
432 !factory_
->CryptoConfigCacheIsEmpty(server_id_
))) {
433 // If we have started another job and if we didn't load the server config
434 // from the disk cache or if we have received a new server config from the
435 // server, then cancel the current job.
436 io_state_
= STATE_NONE
;
437 return ERR_CONNECTION_CLOSED
;
440 io_state_
= STATE_CONNECT
;
444 int QuicStreamFactory::Job::DoConnect() {
445 io_state_
= STATE_CONNECT_COMPLETE
;
447 int rv
= factory_
->CreateSession(
448 server_id_
, cert_verify_flags_
, server_info_
.Pass(), address_list_
,
449 dns_resolution_end_time_
, net_log_
, &session_
);
451 DCHECK(rv
!= ERR_IO_PENDING
);
456 if (!session_
->connection()->connected()) {
457 return ERR_CONNECTION_CLOSED
;
460 session_
->StartReading();
461 if (!session_
->connection()->connected()) {
462 return ERR_QUIC_PROTOCOL_ERROR
;
464 bool require_confirmation
= factory_
->require_confirmation() ||
465 !server_and_origin_have_same_host_
|| is_post_
||
466 was_alternative_service_recently_broken_
;
468 rv
= session_
->CryptoConnect(
469 require_confirmation
,
470 base::Bind(&QuicStreamFactory::Job::OnIOComplete
, GetWeakPtr()));
474 int QuicStreamFactory::Job::DoResumeConnect() {
475 io_state_
= STATE_CONNECT_COMPLETE
;
477 int rv
= session_
->ResumeCryptoConnect(
478 base::Bind(&QuicStreamFactory::Job::OnIOComplete
, GetWeakPtr()));
483 int QuicStreamFactory::Job::DoConnectComplete(int rv
) {
487 DCHECK(!factory_
->HasActiveSession(server_id_
));
488 // There may well now be an active session for this IP. If so, use the
489 // existing session instead.
490 AddressList
address(session_
->connection()->peer_address());
491 if (factory_
->OnResolution(server_id_
, address
)) {
492 session_
->connection()->SendConnectionClose(QUIC_CONNECTION_IP_POOLED
);
497 factory_
->ActivateSession(server_id_
, session_
);
502 QuicStreamRequest::QuicStreamRequest(QuicStreamFactory
* factory
)
503 : factory_(factory
) {}
505 QuicStreamRequest::~QuicStreamRequest() {
506 if (factory_
&& !callback_
.is_null())
507 factory_
->CancelRequest(this);
510 int QuicStreamRequest::Request(const HostPortPair
& host_port_pair
,
512 PrivacyMode privacy_mode
,
513 int cert_verify_flags
,
514 base::StringPiece origin_host
,
515 base::StringPiece method
,
516 const BoundNetLog
& net_log
,
517 const CompletionCallback
& callback
) {
519 DCHECK(callback_
.is_null());
521 origin_host_
= origin_host
.as_string();
522 privacy_mode_
= privacy_mode
;
524 factory_
->Create(host_port_pair
, is_https
, privacy_mode
,
525 cert_verify_flags
, origin_host
, method
, net_log
, this);
526 if (rv
== ERR_IO_PENDING
) {
527 host_port_pair_
= host_port_pair
;
529 callback_
= callback
;
538 void QuicStreamRequest::set_stream(scoped_ptr
<QuicHttpStream
> stream
) {
540 stream_
= stream
.Pass();
543 void QuicStreamRequest::OnRequestComplete(int rv
) {
548 scoped_ptr
<QuicHttpStream
> QuicStreamRequest::ReleaseStream() {
550 return stream_
.Pass();
553 QuicStreamFactory::QuicStreamFactory(
554 HostResolver
* host_resolver
,
555 ClientSocketFactory
* client_socket_factory
,
556 base::WeakPtr
<HttpServerProperties
> http_server_properties
,
557 CertVerifier
* cert_verifier
,
558 CertPolicyEnforcer
* cert_policy_enforcer
,
559 ChannelIDService
* channel_id_service
,
560 TransportSecurityState
* transport_security_state
,
561 QuicCryptoClientStreamFactory
* quic_crypto_client_stream_factory
,
562 QuicRandom
* random_generator
,
564 size_t max_packet_length
,
565 const std::string
& user_agent_id
,
566 const QuicVersionVector
& supported_versions
,
567 bool enable_port_selection
,
568 bool always_require_handshake_confirmation
,
569 bool disable_connection_pooling
,
570 float load_server_info_timeout_srtt_multiplier
,
571 bool enable_connection_racing
,
572 bool enable_non_blocking_io
,
573 bool disable_disk_cache
,
575 int max_number_of_lossy_connections
,
576 float packet_loss_threshold
,
577 int max_disabled_reasons
,
578 int threshold_public_resets_post_handshake
,
579 int threshold_timeouts_with_open_streams
,
580 int socket_receive_buffer_size
,
581 const QuicTagVector
& connection_options
)
582 : require_confirmation_(true),
583 host_resolver_(host_resolver
),
584 client_socket_factory_(client_socket_factory
),
585 http_server_properties_(http_server_properties
),
586 transport_security_state_(transport_security_state
),
587 quic_server_info_factory_(nullptr),
588 quic_crypto_client_stream_factory_(quic_crypto_client_stream_factory
),
589 random_generator_(random_generator
),
591 max_packet_length_(max_packet_length
),
592 config_(InitializeQuicConfig(connection_options
)),
593 supported_versions_(supported_versions
),
594 enable_port_selection_(enable_port_selection
),
595 always_require_handshake_confirmation_(
596 always_require_handshake_confirmation
),
597 disable_connection_pooling_(disable_connection_pooling
),
598 load_server_info_timeout_srtt_multiplier_(
599 load_server_info_timeout_srtt_multiplier
),
600 enable_connection_racing_(enable_connection_racing
),
601 enable_non_blocking_io_(enable_non_blocking_io
),
602 disable_disk_cache_(disable_disk_cache
),
603 prefer_aes_(prefer_aes
),
604 max_number_of_lossy_connections_(max_number_of_lossy_connections
),
605 packet_loss_threshold_(packet_loss_threshold
),
606 max_disabled_reasons_(max_disabled_reasons
),
607 num_public_resets_post_handshake_(0),
608 num_timeouts_with_open_streams_(0),
609 max_public_resets_post_handshake_(0),
610 max_timeouts_with_open_streams_(0),
611 threshold_timeouts_with_open_streams_(
612 threshold_timeouts_with_open_streams
),
613 threshold_public_resets_post_handshake_(
614 threshold_public_resets_post_handshake
),
615 socket_receive_buffer_size_(socket_receive_buffer_size
),
616 port_seed_(random_generator_
->RandUint64()),
617 check_persisted_supports_quic_(true),
618 task_runner_(nullptr),
619 weak_factory_(this) {
620 DCHECK(transport_security_state_
);
621 crypto_config_
.set_user_agent_id(user_agent_id
);
622 crypto_config_
.AddCanonicalSuffix(".c.youtube.com");
623 crypto_config_
.AddCanonicalSuffix(".googlevideo.com");
624 crypto_config_
.AddCanonicalSuffix(".googleusercontent.com");
625 crypto_config_
.SetProofVerifier(new ProofVerifierChromium(
626 cert_verifier
, cert_policy_enforcer
, transport_security_state
));
627 // TODO(rtenneti): http://crbug.com/487355. Temporary fix for b/20760730 until
628 // channel_id_service is supported in cronet.
629 if (channel_id_service
) {
630 crypto_config_
.SetChannelIDSource(
631 new ChannelIDSourceChromium(channel_id_service
));
633 #if defined(USE_OPENSSL)
634 crypto::EnsureOpenSSLInit();
635 bool has_aes_hardware_support
= !!EVP_has_aes_hardware();
638 bool has_aes_hardware_support
= cpu
.has_aesni() && cpu
.has_avx();
640 UMA_HISTOGRAM_BOOLEAN("Net.QuicSession.PreferAesGcm",
641 has_aes_hardware_support
);
642 if (has_aes_hardware_support
|| prefer_aes_
)
643 crypto_config_
.PreferAesGcm();
644 if (!IsEcdsaSupported())
645 crypto_config_
.DisableEcdsa();
648 QuicStreamFactory::~QuicStreamFactory() {
649 CloseAllSessions(ERR_ABORTED
);
650 while (!all_sessions_
.empty()) {
651 delete all_sessions_
.begin()->first
;
652 all_sessions_
.erase(all_sessions_
.begin());
654 while (!active_jobs_
.empty()) {
655 const QuicServerId server_id
= active_jobs_
.begin()->first
;
656 STLDeleteElements(&(active_jobs_
[server_id
]));
657 active_jobs_
.erase(server_id
);
661 void QuicStreamFactory::set_require_confirmation(bool require_confirmation
) {
662 require_confirmation_
= require_confirmation
;
663 if (http_server_properties_
&& (!(local_address_
== IPEndPoint()))) {
664 http_server_properties_
->SetSupportsQuic(!require_confirmation
,
665 local_address_
.address());
669 int QuicStreamFactory::Create(const HostPortPair
& host_port_pair
,
671 PrivacyMode privacy_mode
,
672 int cert_verify_flags
,
673 base::StringPiece origin_host
,
674 base::StringPiece method
,
675 const BoundNetLog
& net_log
,
676 QuicStreamRequest
* request
) {
677 QuicServerId
server_id(host_port_pair
, is_https
, privacy_mode
);
678 SessionMap::iterator it
= active_sessions_
.find(server_id
);
679 if (it
!= active_sessions_
.end()) {
680 QuicChromiumClientSession
* session
= it
->second
;
681 if (!session
->CanPool(origin_host
.as_string(), privacy_mode
))
682 return ERR_ALTERNATIVE_CERT_NOT_VALID_FOR_ORIGIN
;
683 request
->set_stream(CreateFromSession(session
));
687 if (HasActiveJob(server_id
)) {
688 active_requests_
[request
] = server_id
;
689 job_requests_map_
[server_id
].insert(request
);
690 return ERR_IO_PENDING
;
693 // TODO(rtenneti): |task_runner_| is used by the Job. Initialize task_runner_
694 // in the constructor after WebRequestActionWithThreadsTest.* tests are fixed.
696 task_runner_
= base::ThreadTaskRunnerHandle::Get().get();
698 QuicServerInfo
* quic_server_info
= nullptr;
699 if (quic_server_info_factory_
) {
700 bool load_from_disk_cache
= !disable_disk_cache_
;
701 if (http_server_properties_
) {
702 const AlternativeServiceMap
& alternative_service_map
=
703 http_server_properties_
->alternative_service_map();
704 AlternativeServiceMap::const_iterator map_it
=
705 alternative_service_map
.Peek(server_id
.host_port_pair());
706 if (map_it
!= alternative_service_map
.end()) {
707 const AlternativeServiceInfoVector
& alternative_service_info_vector
=
709 AlternativeServiceInfoVector::const_iterator it
;
710 for (it
= alternative_service_info_vector
.begin();
711 it
!= alternative_service_info_vector
.end(); ++it
) {
712 if (it
->alternative_service
.protocol
== QUIC
)
715 // If there is no entry for QUIC, consider that as a new server and
716 // don't wait for Cache thread to load the data for that server.
717 if (it
== alternative_service_info_vector
.end())
718 load_from_disk_cache
= false;
721 if (load_from_disk_cache
&& CryptoConfigCacheIsEmpty(server_id
)) {
722 quic_server_info
= quic_server_info_factory_
->GetForServer(server_id
);
726 bool server_and_origin_have_same_host
= host_port_pair
.host() == origin_host
;
727 scoped_ptr
<Job
> job(new Job(this, host_resolver_
, host_port_pair
,
728 server_and_origin_have_same_host
, is_https
,
729 WasQuicRecentlyBroken(server_id
), privacy_mode
,
730 cert_verify_flags
, method
== "POST" /* is_post */,
731 quic_server_info
, net_log
));
732 int rv
= job
->Run(base::Bind(&QuicStreamFactory::OnJobComplete
,
733 base::Unretained(this), job
.get()));
734 if (rv
== ERR_IO_PENDING
) {
735 active_requests_
[request
] = server_id
;
736 job_requests_map_
[server_id
].insert(request
);
737 active_jobs_
[server_id
].insert(job
.release());
741 it
= active_sessions_
.find(server_id
);
742 DCHECK(it
!= active_sessions_
.end());
743 QuicChromiumClientSession
* session
= it
->second
;
744 if (!session
->CanPool(origin_host
.as_string(), privacy_mode
))
745 return ERR_ALTERNATIVE_CERT_NOT_VALID_FOR_ORIGIN
;
746 request
->set_stream(CreateFromSession(session
));
751 void QuicStreamFactory::CreateAuxilaryJob(const QuicServerId server_id
,
752 int cert_verify_flags
,
753 bool server_and_origin_have_same_host
,
755 const BoundNetLog
& net_log
) {
757 new Job(this, host_resolver_
, server_id
.host_port_pair(),
758 server_and_origin_have_same_host
, server_id
.is_https(),
759 WasQuicRecentlyBroken(server_id
), server_id
.privacy_mode(),
760 cert_verify_flags
, is_post
, nullptr, net_log
);
761 active_jobs_
[server_id
].insert(aux_job
);
762 task_runner_
->PostTask(FROM_HERE
,
763 base::Bind(&QuicStreamFactory::Job::RunAuxilaryJob
,
764 aux_job
->GetWeakPtr()));
767 bool QuicStreamFactory::OnResolution(
768 const QuicServerId
& server_id
,
769 const AddressList
& address_list
) {
770 DCHECK(!HasActiveSession(server_id
));
771 if (disable_connection_pooling_
) {
774 for (const IPEndPoint
& address
: address_list
) {
775 const IpAliasKey
ip_alias_key(address
, server_id
.is_https());
776 if (!ContainsKey(ip_aliases_
, ip_alias_key
))
779 const SessionSet
& sessions
= ip_aliases_
[ip_alias_key
];
780 for (QuicChromiumClientSession
* session
: sessions
) {
781 if (!session
->CanPool(server_id
.host(), server_id
.privacy_mode()))
783 active_sessions_
[server_id
] = session
;
784 session_aliases_
[session
].insert(server_id
);
791 void QuicStreamFactory::OnJobComplete(Job
* job
, int rv
) {
792 QuicServerId server_id
= job
->server_id();
794 JobSet
* jobs
= &(active_jobs_
[server_id
]);
795 if (jobs
->size() > 1) {
796 // If there is another pending job, then we can delete this job and let
797 // the other job handle the request.
806 if (!always_require_handshake_confirmation_
)
807 set_require_confirmation(false);
809 // Create all the streams, but do not notify them yet.
810 SessionMap::iterator session_it
= active_sessions_
.find(server_id
);
811 for (RequestSet::iterator request_it
= job_requests_map_
[server_id
].begin();
812 request_it
!= job_requests_map_
[server_id
].end();) {
813 DCHECK(session_it
!= active_sessions_
.end());
814 QuicChromiumClientSession
* session
= session_it
->second
;
815 QuicStreamRequest
* request
= *request_it
;
816 if (!session
->CanPool(request
->origin_host(), request
->privacy_mode())) {
817 RequestSet::iterator old_request_it
= request_it
;
819 // Remove request from containers so that OnRequestComplete() is not
820 // called later again on the same request.
821 job_requests_map_
[server_id
].erase(old_request_it
);
822 active_requests_
.erase(request
);
823 // Notify request of certificate error.
824 request
->OnRequestComplete(ERR_ALTERNATIVE_CERT_NOT_VALID_FOR_ORIGIN
);
827 request
->set_stream(CreateFromSession(session
));
832 while (!job_requests_map_
[server_id
].empty()) {
833 RequestSet::iterator it
= job_requests_map_
[server_id
].begin();
834 QuicStreamRequest
* request
= *it
;
835 job_requests_map_
[server_id
].erase(it
);
836 active_requests_
.erase(request
);
837 // Even though we're invoking callbacks here, we don't need to worry
838 // about |this| being deleted, because the factory is owned by the
839 // profile which can not be deleted via callbacks.
840 request
->OnRequestComplete(rv
);
843 for (Job
* other_job
: active_jobs_
[server_id
]) {
844 if (other_job
!= job
)
848 STLDeleteElements(&(active_jobs_
[server_id
]));
849 active_jobs_
.erase(server_id
);
850 job_requests_map_
.erase(server_id
);
853 scoped_ptr
<QuicHttpStream
> QuicStreamFactory::CreateFromSession(
854 QuicChromiumClientSession
* session
) {
855 return scoped_ptr
<QuicHttpStream
>(new QuicHttpStream(session
->GetWeakPtr()));
858 QuicChromiumClientSession::QuicDisabledReason
859 QuicStreamFactory::QuicDisabledReason(uint16 port
) const {
860 if (max_number_of_lossy_connections_
> 0 &&
861 number_of_lossy_connections_
.find(port
) !=
862 number_of_lossy_connections_
.end() &&
863 number_of_lossy_connections_
.at(port
) >=
864 max_number_of_lossy_connections_
) {
865 return QuicChromiumClientSession::QUIC_DISABLED_BAD_PACKET_LOSS_RATE
;
867 if (threshold_public_resets_post_handshake_
> 0 &&
868 num_public_resets_post_handshake_
>=
869 threshold_public_resets_post_handshake_
) {
870 return QuicChromiumClientSession::QUIC_DISABLED_PUBLIC_RESET_POST_HANDSHAKE
;
872 if (threshold_timeouts_with_open_streams_
> 0 &&
873 num_timeouts_with_open_streams_
>=
874 threshold_timeouts_with_open_streams_
) {
875 return QuicChromiumClientSession::QUIC_DISABLED_TIMEOUT_WITH_OPEN_STREAMS
;
877 return QuicChromiumClientSession::QUIC_DISABLED_NOT
;
880 const char* QuicStreamFactory::QuicDisabledReasonString() const {
881 // TODO(ckrasic) - better solution for port/lossy connections?
882 const uint16 port
= 443;
883 switch (QuicDisabledReason(port
)) {
884 case QuicChromiumClientSession::QUIC_DISABLED_BAD_PACKET_LOSS_RATE
:
885 return "Bad packet loss rate.";
886 case QuicChromiumClientSession::QUIC_DISABLED_PUBLIC_RESET_POST_HANDSHAKE
:
887 return "Public resets after successful handshakes.";
888 case QuicChromiumClientSession::QUIC_DISABLED_TIMEOUT_WITH_OPEN_STREAMS
:
889 return "Connection timeouts with streams open.";
895 bool QuicStreamFactory::IsQuicDisabled(uint16 port
) {
896 return QuicDisabledReason(port
) !=
897 QuicChromiumClientSession::QUIC_DISABLED_NOT
;
900 bool QuicStreamFactory::OnHandshakeConfirmed(QuicChromiumClientSession
* session
,
901 float packet_loss_rate
) {
903 uint16 port
= session
->server_id().port();
904 if (packet_loss_rate
< packet_loss_threshold_
) {
905 number_of_lossy_connections_
[port
] = 0;
909 if (http_server_properties_
) {
910 // We mark it as recently broken, which means that 0-RTT will be disabled
911 // but we'll still race.
912 http_server_properties_
->MarkAlternativeServiceRecentlyBroken(
913 AlternativeService(QUIC
, session
->server_id().host(), port
));
916 bool was_quic_disabled
= IsQuicDisabled(port
);
917 ++number_of_lossy_connections_
[port
];
919 // Collect data for port 443 for packet loss events.
920 if (port
== 443 && max_number_of_lossy_connections_
> 0) {
921 UMA_HISTOGRAM_SPARSE_SLOWLY(
922 base::StringPrintf("Net.QuicStreamFactory.BadPacketLossEvents%d",
923 max_number_of_lossy_connections_
),
924 std::min(number_of_lossy_connections_
[port
],
925 max_number_of_lossy_connections_
));
928 bool is_quic_disabled
= IsQuicDisabled(port
);
929 if (is_quic_disabled
) {
930 // Close QUIC connection if Quic is disabled for this port.
931 session
->CloseSessionOnErrorAndNotifyFactoryLater(
932 ERR_ABORTED
, QUIC_BAD_PACKET_LOSS_RATE
);
934 // If this bad packet loss rate disabled the QUIC, then record it.
935 if (!was_quic_disabled
)
936 UMA_HISTOGRAM_SPARSE_SLOWLY("Net.QuicStreamFactory.QuicIsDisabled", port
);
938 return is_quic_disabled
;
941 void QuicStreamFactory::OnIdleSession(QuicChromiumClientSession
* session
) {}
943 void QuicStreamFactory::OnSessionGoingAway(QuicChromiumClientSession
* session
) {
944 const AliasSet
& aliases
= session_aliases_
[session
];
945 for (AliasSet::const_iterator it
= aliases
.begin(); it
!= aliases
.end();
947 DCHECK(active_sessions_
.count(*it
));
948 DCHECK_EQ(session
, active_sessions_
[*it
]);
949 // Track sessions which have recently gone away so that we can disable
951 if (session
->goaway_received()) {
952 gone_away_aliases_
.insert(*it
);
955 active_sessions_
.erase(*it
);
956 ProcessGoingAwaySession(session
, *it
, true);
958 ProcessGoingAwaySession(session
, all_sessions_
[session
], false);
959 if (!aliases
.empty()) {
960 const IpAliasKey
ip_alias_key(session
->connection()->peer_address(),
961 aliases
.begin()->is_https());
962 ip_aliases_
[ip_alias_key
].erase(session
);
963 if (ip_aliases_
[ip_alias_key
].empty()) {
964 ip_aliases_
.erase(ip_alias_key
);
967 session_aliases_
.erase(session
);
970 void QuicStreamFactory::MaybeDisableQuic(QuicChromiumClientSession
* session
) {
972 uint16 port
= session
->server_id().port();
973 if (IsQuicDisabled(port
))
976 // Expire the oldest disabled_reason if appropriate. This enforces that we
977 // only consider the max_disabled_reasons_ most recent sessions.
978 QuicChromiumClientSession::QuicDisabledReason disabled_reason
;
979 if (static_cast<int>(disabled_reasons_
.size()) == max_disabled_reasons_
) {
980 disabled_reason
= disabled_reasons_
.front();
981 disabled_reasons_
.pop_front();
982 if (disabled_reason
==
983 QuicChromiumClientSession::QUIC_DISABLED_PUBLIC_RESET_POST_HANDSHAKE
) {
984 --num_public_resets_post_handshake_
;
985 } else if (disabled_reason
== QuicChromiumClientSession::
986 QUIC_DISABLED_TIMEOUT_WITH_OPEN_STREAMS
) {
987 --num_timeouts_with_open_streams_
;
990 disabled_reason
= session
->disabled_reason();
991 disabled_reasons_
.push_back(disabled_reason
);
992 if (disabled_reason
==
993 QuicChromiumClientSession::QUIC_DISABLED_PUBLIC_RESET_POST_HANDSHAKE
) {
994 ++num_public_resets_post_handshake_
;
995 } else if (disabled_reason
== QuicChromiumClientSession::
996 QUIC_DISABLED_TIMEOUT_WITH_OPEN_STREAMS
) {
997 ++num_timeouts_with_open_streams_
;
999 if (num_timeouts_with_open_streams_
> max_timeouts_with_open_streams_
) {
1000 max_timeouts_with_open_streams_
= num_timeouts_with_open_streams_
;
1001 UMA_HISTOGRAM_CUSTOM_COUNTS("Net.QuicStreamFactory.TimeoutsWithOpenStreams",
1002 num_timeouts_with_open_streams_
, 0, 20, 10);
1005 if (num_public_resets_post_handshake_
> max_public_resets_post_handshake_
) {
1006 max_public_resets_post_handshake_
= num_public_resets_post_handshake_
;
1007 UMA_HISTOGRAM_CUSTOM_COUNTS(
1008 "Net.QuicStreamFactory.PublicResetsPostHandshake",
1009 num_public_resets_post_handshake_
, 0, 20, 10);
1012 if (IsQuicDisabled(port
)) {
1013 if (disabled_reason
==
1014 QuicChromiumClientSession::QUIC_DISABLED_PUBLIC_RESET_POST_HANDSHAKE
) {
1015 session
->CloseSessionOnErrorAndNotifyFactoryLater(
1016 ERR_ABORTED
, QUIC_PUBLIC_RESETS_POST_HANDSHAKE
);
1017 } else if (disabled_reason
== QuicChromiumClientSession::
1018 QUIC_DISABLED_TIMEOUT_WITH_OPEN_STREAMS
) {
1019 session
->CloseSessionOnErrorAndNotifyFactoryLater(
1020 ERR_ABORTED
, QUIC_TIMEOUTS_WITH_OPEN_STREAMS
);
1022 UMA_HISTOGRAM_ENUMERATION("Net.QuicStreamFactory.DisabledReasons",
1024 QuicChromiumClientSession::QUIC_DISABLED_MAX
);
1028 void QuicStreamFactory::OnSessionClosed(QuicChromiumClientSession
* session
) {
1029 DCHECK_EQ(0u, session
->GetNumOpenStreams());
1030 MaybeDisableQuic(session
);
1031 OnSessionGoingAway(session
);
1033 all_sessions_
.erase(session
);
1036 void QuicStreamFactory::OnSessionConnectTimeout(
1037 QuicChromiumClientSession
* session
) {
1038 const AliasSet
& aliases
= session_aliases_
[session
];
1039 for (AliasSet::const_iterator it
= aliases
.begin(); it
!= aliases
.end();
1041 DCHECK(active_sessions_
.count(*it
));
1042 DCHECK_EQ(session
, active_sessions_
[*it
]);
1043 active_sessions_
.erase(*it
);
1046 if (aliases
.empty()) {
1050 const IpAliasKey
ip_alias_key(session
->connection()->peer_address(),
1051 aliases
.begin()->is_https());
1052 ip_aliases_
[ip_alias_key
].erase(session
);
1053 if (ip_aliases_
[ip_alias_key
].empty()) {
1054 ip_aliases_
.erase(ip_alias_key
);
1056 QuicServerId server_id
= *aliases
.begin();
1057 session_aliases_
.erase(session
);
1058 Job
* job
= new Job(this, host_resolver_
, session
, server_id
);
1059 active_jobs_
[server_id
].insert(job
);
1060 int rv
= job
->Run(base::Bind(&QuicStreamFactory::OnJobComplete
,
1061 base::Unretained(this), job
));
1062 DCHECK_EQ(ERR_IO_PENDING
, rv
);
1065 void QuicStreamFactory::CancelRequest(QuicStreamRequest
* request
) {
1066 DCHECK(ContainsKey(active_requests_
, request
));
1067 QuicServerId server_id
= active_requests_
[request
];
1068 job_requests_map_
[server_id
].erase(request
);
1069 active_requests_
.erase(request
);
1072 void QuicStreamFactory::CloseAllSessions(int error
) {
1073 while (!active_sessions_
.empty()) {
1074 size_t initial_size
= active_sessions_
.size();
1075 active_sessions_
.begin()->second
->CloseSessionOnError(error
,
1076 QUIC_INTERNAL_ERROR
);
1077 DCHECK_NE(initial_size
, active_sessions_
.size());
1079 while (!all_sessions_
.empty()) {
1080 size_t initial_size
= all_sessions_
.size();
1081 all_sessions_
.begin()->first
->CloseSessionOnError(error
,
1082 QUIC_INTERNAL_ERROR
);
1083 DCHECK_NE(initial_size
, all_sessions_
.size());
1085 DCHECK(all_sessions_
.empty());
1088 scoped_ptr
<base::Value
> QuicStreamFactory::QuicStreamFactoryInfoToValue()
1090 scoped_ptr
<base::ListValue
> list(new base::ListValue());
1092 for (SessionMap::const_iterator it
= active_sessions_
.begin();
1093 it
!= active_sessions_
.end(); ++it
) {
1094 const QuicServerId
& server_id
= it
->first
;
1095 QuicChromiumClientSession
* session
= it
->second
;
1096 const AliasSet
& aliases
= session_aliases_
.find(session
)->second
;
1097 // Only add a session to the list once.
1098 if (server_id
== *aliases
.begin()) {
1099 std::set
<HostPortPair
> hosts
;
1100 for (AliasSet::const_iterator alias_it
= aliases
.begin();
1101 alias_it
!= aliases
.end(); ++alias_it
) {
1102 hosts
.insert(alias_it
->host_port_pair());
1104 list
->Append(session
->GetInfoAsValue(hosts
));
1110 void QuicStreamFactory::ClearCachedStatesInCryptoConfig() {
1111 crypto_config_
.ClearCachedStates();
1114 void QuicStreamFactory::OnIPAddressChanged() {
1115 CloseAllSessions(ERR_NETWORK_CHANGED
);
1116 set_require_confirmation(true);
1119 void QuicStreamFactory::OnCertAdded(const X509Certificate
* cert
) {
1120 CloseAllSessions(ERR_CERT_DATABASE_CHANGED
);
1123 void QuicStreamFactory::OnCACertChanged(const X509Certificate
* cert
) {
1124 // We should flush the sessions if we removed trust from a
1125 // cert, because a previously trusted server may have become
1128 // We should not flush the sessions if we added trust to a cert.
1130 // Since the OnCACertChanged method doesn't tell us what
1131 // kind of change it is, we have to flush the socket
1132 // pools to be safe.
1133 CloseAllSessions(ERR_CERT_DATABASE_CHANGED
);
1136 bool QuicStreamFactory::HasActiveSession(
1137 const QuicServerId
& server_id
) const {
1138 return ContainsKey(active_sessions_
, server_id
);
1141 bool QuicStreamFactory::HasActiveJob(const QuicServerId
& key
) const {
1142 return ContainsKey(active_jobs_
, key
);
1145 int QuicStreamFactory::CreateSession(const QuicServerId
& server_id
,
1146 int cert_verify_flags
,
1147 scoped_ptr
<QuicServerInfo
> server_info
,
1148 const AddressList
& address_list
,
1149 base::TimeTicks dns_resolution_end_time
,
1150 const BoundNetLog
& net_log
,
1151 QuicChromiumClientSession
** session
) {
1152 bool enable_port_selection
= enable_port_selection_
;
1153 if (enable_port_selection
&&
1154 ContainsKey(gone_away_aliases_
, server_id
)) {
1155 // Disable port selection when the server is going away.
1156 // There is no point in trying to return to the same server, if
1157 // that server is no longer handling requests.
1158 enable_port_selection
= false;
1159 gone_away_aliases_
.erase(server_id
);
1162 QuicConnectionId connection_id
= random_generator_
->RandUint64();
1163 IPEndPoint addr
= *address_list
.begin();
1164 scoped_refptr
<PortSuggester
> port_suggester
=
1165 new PortSuggester(server_id
.host_port_pair(), port_seed_
);
1166 DatagramSocket::BindType bind_type
= enable_port_selection
?
1167 DatagramSocket::RANDOM_BIND
: // Use our callback.
1168 DatagramSocket::DEFAULT_BIND
; // Use OS to randomize.
1169 scoped_ptr
<DatagramClientSocket
> socket(
1170 client_socket_factory_
->CreateDatagramClientSocket(
1172 base::Bind(&PortSuggester::SuggestPort
, port_suggester
),
1173 net_log
.net_log(), net_log
.source()));
1175 if (enable_non_blocking_io_
&&
1176 client_socket_factory_
== ClientSocketFactory::GetDefaultFactory()) {
1178 static_cast<UDPClientSocket
*>(socket
.get())->UseNonBlockingIO();
1182 int rv
= socket
->Connect(addr
);
1185 HistogramCreateSessionFailure(CREATION_ERROR_CONNECTING_SOCKET
);
1188 UMA_HISTOGRAM_COUNTS("Net.QuicEphemeralPortsSuggested",
1189 port_suggester
->call_count());
1190 if (enable_port_selection
) {
1191 DCHECK_LE(1u, port_suggester
->call_count());
1193 DCHECK_EQ(0u, port_suggester
->call_count());
1196 rv
= socket
->SetReceiveBufferSize(socket_receive_buffer_size_
);
1198 HistogramCreateSessionFailure(CREATION_ERROR_SETTING_RECEIVE_BUFFER
);
1201 // Set a buffer large enough to contain the initial CWND's worth of packet
1202 // to work around the problem with CHLO packets being sent out with the
1203 // wrong encryption level, when the send buffer is full.
1204 rv
= socket
->SetSendBufferSize(kMaxPacketSize
* 20);
1206 HistogramCreateSessionFailure(CREATION_ERROR_SETTING_SEND_BUFFER
);
1210 socket
->GetLocalAddress(&local_address_
);
1211 if (check_persisted_supports_quic_
&& http_server_properties_
) {
1212 check_persisted_supports_quic_
= false;
1213 IPAddressNumber last_address
;
1214 if (http_server_properties_
->GetSupportsQuic(&last_address
) &&
1215 last_address
== local_address_
.address()) {
1216 require_confirmation_
= false;
1220 DefaultPacketWriterFactory
packet_writer_factory(socket
.get());
1222 if (!helper_
.get()) {
1224 new QuicConnectionHelper(base::ThreadTaskRunnerHandle::Get().get(),
1225 clock_
.get(), random_generator_
));
1228 QuicConnection
* connection
= new QuicConnection(
1229 connection_id
, addr
, helper_
.get(), packet_writer_factory
,
1230 true /* owns_writer */, Perspective::IS_CLIENT
, server_id
.is_https(),
1231 supported_versions_
);
1232 connection
->set_max_packet_length(max_packet_length_
);
1234 InitializeCachedStateInCryptoConfig(server_id
, server_info
);
1236 QuicConfig config
= config_
;
1237 config
.SetSocketReceiveBufferToSend(socket_receive_buffer_size_
);
1238 config
.set_max_undecryptable_packets(kMaxUndecryptablePackets
);
1239 config
.SetInitialSessionFlowControlWindowToSend(
1240 kQuicSessionMaxRecvWindowSize
);
1241 config
.SetInitialStreamFlowControlWindowToSend(kQuicStreamMaxRecvWindowSize
);
1242 int64 srtt
= GetServerNetworkStatsSmoothedRttInMicroseconds(server_id
);
1244 config
.SetInitialRoundTripTimeUsToSend(static_cast<uint32
>(srtt
));
1245 config
.SetBytesForConnectionIdToSend(0);
1247 if (quic_server_info_factory_
&& !server_info
) {
1248 // Start the disk cache loading so that we can persist the newer QUIC server
1249 // information and/or inform the disk cache that we have reused
1251 server_info
.reset(quic_server_info_factory_
->GetForServer(server_id
));
1252 server_info
->Start();
1255 *session
= new QuicChromiumClientSession(
1256 connection
, socket
.Pass(), this, quic_crypto_client_stream_factory_
,
1257 transport_security_state_
, server_info
.Pass(), server_id
,
1258 cert_verify_flags
, config
, &crypto_config_
,
1259 network_connection_
.GetDescription(), dns_resolution_end_time
,
1260 base::ThreadTaskRunnerHandle::Get().get(), net_log
.net_log());
1262 all_sessions_
[*session
] = server_id
; // owning pointer
1264 (*session
)->Initialize();
1265 bool closed_during_initialize
=
1266 !ContainsKey(all_sessions_
, *session
) ||
1267 !(*session
)->connection()->connected();
1268 UMA_HISTOGRAM_BOOLEAN("Net.QuicSession.ClosedDuringInitializeSession",
1269 closed_during_initialize
);
1270 if (closed_during_initialize
) {
1271 DLOG(DFATAL
) << "Session closed during initialize";
1273 return ERR_CONNECTION_CLOSED
;
1278 void QuicStreamFactory::ActivateSession(const QuicServerId
& server_id
,
1279 QuicChromiumClientSession
* session
) {
1280 DCHECK(!HasActiveSession(server_id
));
1281 UMA_HISTOGRAM_COUNTS("Net.QuicActiveSessions", active_sessions_
.size());
1282 active_sessions_
[server_id
] = session
;
1283 session_aliases_
[session
].insert(server_id
);
1284 const IpAliasKey
ip_alias_key(session
->connection()->peer_address(),
1285 server_id
.is_https());
1286 DCHECK(!ContainsKey(ip_aliases_
[ip_alias_key
], session
));
1287 ip_aliases_
[ip_alias_key
].insert(session
);
1290 int64
QuicStreamFactory::GetServerNetworkStatsSmoothedRttInMicroseconds(
1291 const QuicServerId
& server_id
) const {
1292 if (!http_server_properties_
)
1294 const ServerNetworkStats
* stats
=
1295 http_server_properties_
->GetServerNetworkStats(
1296 server_id
.host_port_pair());
1297 if (stats
== nullptr)
1299 return stats
->srtt
.InMicroseconds();
1302 bool QuicStreamFactory::WasQuicRecentlyBroken(
1303 const QuicServerId
& server_id
) const {
1304 if (!http_server_properties_
)
1306 const AlternativeService
alternative_service(QUIC
,
1307 server_id
.host_port_pair());
1308 return http_server_properties_
->WasAlternativeServiceRecentlyBroken(
1309 alternative_service
);
1312 bool QuicStreamFactory::CryptoConfigCacheIsEmpty(
1313 const QuicServerId
& server_id
) {
1314 QuicCryptoClientConfig::CachedState
* cached
=
1315 crypto_config_
.LookupOrCreate(server_id
);
1316 return cached
->IsEmpty();
1319 void QuicStreamFactory::InitializeCachedStateInCryptoConfig(
1320 const QuicServerId
& server_id
,
1321 const scoped_ptr
<QuicServerInfo
>& server_info
) {
1322 // |server_info| will be NULL, if a non-empty server config already exists in
1323 // the memory cache. This is a minor optimization to avoid LookupOrCreate.
1327 QuicCryptoClientConfig::CachedState
* cached
=
1328 crypto_config_
.LookupOrCreate(server_id
);
1329 if (!cached
->IsEmpty())
1332 if (http_server_properties_
) {
1333 if (quic_supported_servers_at_startup_
.empty()) {
1334 for (const std::pair
<const HostPortPair
, AlternativeServiceInfoVector
>&
1335 key_value
: http_server_properties_
->alternative_service_map()) {
1336 for (const AlternativeServiceInfo
& alternative_service_info
:
1338 if (alternative_service_info
.alternative_service
.protocol
== QUIC
) {
1339 quic_supported_servers_at_startup_
.insert(key_value
.first
);
1346 // TODO(rtenneti): Delete the following histogram after collecting stats.
1347 // If the AlternativeServiceMap contained an entry for this host, check if
1348 // the disk cache contained an entry for it.
1349 if (ContainsKey(quic_supported_servers_at_startup_
,
1350 server_id
.host_port_pair())) {
1351 UMA_HISTOGRAM_BOOLEAN(
1352 "Net.QuicServerInfo.ExpectConfigMissingFromDiskCache",
1353 server_info
->state().server_config
.empty());
1357 if (!cached
->Initialize(server_info
->state().server_config
,
1358 server_info
->state().source_address_token
,
1359 server_info
->state().certs
,
1360 server_info
->state().server_config_sig
,
1364 if (!server_id
.is_https()) {
1365 // Don't check the certificates for insecure QUIC.
1366 cached
->SetProofValid();
1370 void QuicStreamFactory::ProcessGoingAwaySession(
1371 QuicChromiumClientSession
* session
,
1372 const QuicServerId
& server_id
,
1373 bool session_was_active
) {
1374 if (!http_server_properties_
)
1377 const QuicConnectionStats
& stats
= session
->connection()->GetStats();
1378 const AlternativeService
alternative_service(QUIC
,
1379 server_id
.host_port_pair());
1380 if (session
->IsCryptoHandshakeConfirmed()) {
1381 http_server_properties_
->ConfirmAlternativeService(alternative_service
);
1382 ServerNetworkStats network_stats
;
1383 network_stats
.srtt
= base::TimeDelta::FromMicroseconds(stats
.srtt_us
);
1384 network_stats
.bandwidth_estimate
= stats
.estimated_bandwidth
;
1385 http_server_properties_
->SetServerNetworkStats(server_id
.host_port_pair(),
1390 UMA_HISTOGRAM_COUNTS("Net.QuicHandshakeNotConfirmedNumPacketsReceived",
1391 stats
.packets_received
);
1393 if (!session_was_active
)
1396 // TODO(rch): In the special case where the session has received no
1397 // packets from the peer, we should consider blacklisting this
1398 // differently so that we still race TCP but we don't consider the
1399 // session connected until the handshake has been confirmed.
1400 HistogramBrokenAlternateProtocolLocation(
1401 BROKEN_ALTERNATE_PROTOCOL_LOCATION_QUIC_STREAM_FACTORY
);
1403 // Since the session was active, there's no longer an
1404 // HttpStreamFactoryImpl::Job running which can mark it broken, unless the TCP
1405 // job also fails. So to avoid not using QUIC when we otherwise could, we mark
1406 // it as recently broken, which means that 0-RTT will be disabled but we'll
1408 http_server_properties_
->MarkAlternativeServiceRecentlyBroken(
1409 alternative_service
);