Update Polymer and pull in iron-list
[chromium-blink-merge.git] / net / quic / quic_stream_factory.cc
blobbf6d977ba2a41b571293ba1fcfe246609f59f33a
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"
7 #include <algorithm>
8 #include <set>
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/base/socket_performance_watcher.h"
23 #include "net/base/socket_performance_watcher_factory.h"
24 #include "net/cert/cert_verifier.h"
25 #include "net/dns/host_resolver.h"
26 #include "net/dns/single_request_host_resolver.h"
27 #include "net/http/http_server_properties.h"
28 #include "net/quic/crypto/channel_id_chromium.h"
29 #include "net/quic/crypto/proof_verifier_chromium.h"
30 #include "net/quic/crypto/quic_random.h"
31 #include "net/quic/crypto/quic_server_info.h"
32 #include "net/quic/port_suggester.h"
33 #include "net/quic/quic_chromium_client_session.h"
34 #include "net/quic/quic_clock.h"
35 #include "net/quic/quic_connection.h"
36 #include "net/quic/quic_connection_helper.h"
37 #include "net/quic/quic_crypto_client_stream_factory.h"
38 #include "net/quic/quic_default_packet_writer.h"
39 #include "net/quic/quic_flags.h"
40 #include "net/quic/quic_http_stream.h"
41 #include "net/quic/quic_protocol.h"
42 #include "net/quic/quic_server_id.h"
43 #include "net/socket/client_socket_factory.h"
44 #include "net/udp/udp_client_socket.h"
46 #if defined(OS_WIN)
47 #include "base/win/windows_version.h"
48 #endif
50 #if defined(USE_OPENSSL)
51 #include <openssl/aead.h>
52 #include "crypto/openssl_util.h"
53 #else
54 #include "base/cpu.h"
55 #endif
57 using std::min;
59 namespace net {
61 namespace {
63 enum CreateSessionFailure {
64 CREATION_ERROR_CONNECTING_SOCKET,
65 CREATION_ERROR_SETTING_RECEIVE_BUFFER,
66 CREATION_ERROR_SETTING_SEND_BUFFER,
67 CREATION_ERROR_MAX
70 // When a connection is idle for 30 seconds it will be closed.
71 const int kIdleConnectionTimeoutSeconds = 30;
73 // The maximum receive window sizes for QUIC sessions and streams.
74 const int32 kQuicSessionMaxRecvWindowSize = 15 * 1024 * 1024; // 15 MB
75 const int32 kQuicStreamMaxRecvWindowSize = 6 * 1024 * 1024; // 6 MB
77 // Set the maximum number of undecryptable packets the connection will store.
78 const int32 kMaxUndecryptablePackets = 100;
80 void HistogramCreateSessionFailure(enum CreateSessionFailure error) {
81 UMA_HISTOGRAM_ENUMERATION("Net.QuicSession.CreationError", error,
82 CREATION_ERROR_MAX);
85 bool IsEcdsaSupported() {
86 #if defined(OS_WIN)
87 if (base::win::GetVersion() < base::win::VERSION_VISTA)
88 return false;
89 #endif
91 return true;
94 QuicConfig InitializeQuicConfig(const QuicTagVector& connection_options) {
95 QuicConfig config;
96 config.SetIdleConnectionStateLifetime(
97 QuicTime::Delta::FromSeconds(kIdleConnectionTimeoutSeconds),
98 QuicTime::Delta::FromSeconds(kIdleConnectionTimeoutSeconds));
99 config.SetConnectionOptionsToSend(connection_options);
100 return config;
103 class DefaultPacketWriterFactory : public QuicConnection::PacketWriterFactory {
104 public:
105 explicit DefaultPacketWriterFactory(DatagramClientSocket* socket)
106 : socket_(socket) {}
107 ~DefaultPacketWriterFactory() override {}
109 QuicPacketWriter* Create(QuicConnection* connection) const override;
111 private:
112 DatagramClientSocket* socket_;
115 QuicPacketWriter* DefaultPacketWriterFactory::Create(
116 QuicConnection* connection) const {
117 scoped_ptr<QuicDefaultPacketWriter> writer(
118 new QuicDefaultPacketWriter(socket_));
119 writer->SetConnection(connection);
120 return writer.release();
123 } // namespace
125 QuicStreamFactory::IpAliasKey::IpAliasKey() {}
127 QuicStreamFactory::IpAliasKey::IpAliasKey(IPEndPoint ip_endpoint,
128 bool is_https)
129 : ip_endpoint(ip_endpoint),
130 is_https(is_https) {}
132 QuicStreamFactory::IpAliasKey::~IpAliasKey() {}
134 bool QuicStreamFactory::IpAliasKey::operator<(
135 const QuicStreamFactory::IpAliasKey& other) const {
136 if (!(ip_endpoint == other.ip_endpoint)) {
137 return ip_endpoint < other.ip_endpoint;
139 return is_https < other.is_https;
142 bool QuicStreamFactory::IpAliasKey::operator==(
143 const QuicStreamFactory::IpAliasKey& other) const {
144 return is_https == other.is_https &&
145 ip_endpoint == other.ip_endpoint;
148 // Responsible for creating a new QUIC session to the specified server, and
149 // for notifying any associated requests when complete.
150 class QuicStreamFactory::Job {
151 public:
152 Job(QuicStreamFactory* factory,
153 HostResolver* host_resolver,
154 const HostPortPair& host_port_pair,
155 bool server_and_origin_have_same_host,
156 bool is_https,
157 bool was_alternative_service_recently_broken,
158 PrivacyMode privacy_mode,
159 int cert_verify_flags,
160 bool is_post,
161 QuicServerInfo* server_info,
162 const BoundNetLog& net_log);
164 // Creates a new job to handle the resumption of for connecting an
165 // existing session.
166 Job(QuicStreamFactory* factory,
167 HostResolver* host_resolver,
168 QuicChromiumClientSession* session,
169 QuicServerId server_id);
171 ~Job();
173 int Run(const CompletionCallback& callback);
175 int DoLoop(int rv);
176 int DoResolveHost();
177 int DoResolveHostComplete(int rv);
178 int DoLoadServerInfo();
179 int DoLoadServerInfoComplete(int rv);
180 int DoConnect();
181 int DoResumeConnect();
182 int DoConnectComplete(int rv);
184 void OnIOComplete(int rv);
186 void RunAuxilaryJob();
188 void Cancel();
190 void CancelWaitForDataReadyCallback();
192 const QuicServerId server_id() const { return server_id_; }
194 base::WeakPtr<Job> GetWeakPtr() { return weak_factory_.GetWeakPtr(); }
196 private:
197 enum IoState {
198 STATE_NONE,
199 STATE_RESOLVE_HOST,
200 STATE_RESOLVE_HOST_COMPLETE,
201 STATE_LOAD_SERVER_INFO,
202 STATE_LOAD_SERVER_INFO_COMPLETE,
203 STATE_CONNECT,
204 STATE_RESUME_CONNECT,
205 STATE_CONNECT_COMPLETE,
207 IoState io_state_;
209 QuicStreamFactory* factory_;
210 SingleRequestHostResolver host_resolver_;
211 QuicServerId server_id_;
212 int cert_verify_flags_;
213 // True if and only if server and origin have the same hostname.
214 bool server_and_origin_have_same_host_;
215 bool is_post_;
216 bool was_alternative_service_recently_broken_;
217 scoped_ptr<QuicServerInfo> server_info_;
218 bool started_another_job_;
219 const BoundNetLog net_log_;
220 QuicChromiumClientSession* session_;
221 CompletionCallback callback_;
222 AddressList address_list_;
223 base::TimeTicks dns_resolution_start_time_;
224 base::TimeTicks dns_resolution_end_time_;
225 base::WeakPtrFactory<Job> weak_factory_;
226 DISALLOW_COPY_AND_ASSIGN(Job);
229 QuicStreamFactory::Job::Job(QuicStreamFactory* factory,
230 HostResolver* host_resolver,
231 const HostPortPair& host_port_pair,
232 bool server_and_origin_have_same_host,
233 bool is_https,
234 bool was_alternative_service_recently_broken,
235 PrivacyMode privacy_mode,
236 int cert_verify_flags,
237 bool is_post,
238 QuicServerInfo* server_info,
239 const BoundNetLog& net_log)
240 : io_state_(STATE_RESOLVE_HOST),
241 factory_(factory),
242 host_resolver_(host_resolver),
243 server_id_(host_port_pair, is_https, privacy_mode),
244 cert_verify_flags_(cert_verify_flags),
245 server_and_origin_have_same_host_(server_and_origin_have_same_host),
246 is_post_(is_post),
247 was_alternative_service_recently_broken_(
248 was_alternative_service_recently_broken),
249 server_info_(server_info),
250 started_another_job_(false),
251 net_log_(net_log),
252 session_(nullptr),
253 weak_factory_(this) {
256 QuicStreamFactory::Job::Job(QuicStreamFactory* factory,
257 HostResolver* host_resolver,
258 QuicChromiumClientSession* session,
259 QuicServerId server_id)
260 : io_state_(STATE_RESUME_CONNECT),
261 factory_(factory),
262 host_resolver_(host_resolver), // unused
263 server_id_(server_id),
264 cert_verify_flags_(0), // unused
265 server_and_origin_have_same_host_(false), // unused
266 is_post_(false), // unused
267 was_alternative_service_recently_broken_(false), // unused
268 started_another_job_(false), // unused
269 net_log_(session->net_log()), // unused
270 session_(session),
271 weak_factory_(this) {}
273 QuicStreamFactory::Job::~Job() {
274 // If disk cache has a pending WaitForDataReadyCallback, cancel that callback.
275 if (server_info_)
276 server_info_->ResetWaitForDataReadyCallback();
279 int QuicStreamFactory::Job::Run(const CompletionCallback& callback) {
280 int rv = DoLoop(OK);
281 if (rv == ERR_IO_PENDING)
282 callback_ = callback;
284 return rv > 0 ? OK : rv;
287 int QuicStreamFactory::Job::DoLoop(int rv) {
288 do {
289 IoState state = io_state_;
290 io_state_ = STATE_NONE;
291 switch (state) {
292 case STATE_RESOLVE_HOST:
293 CHECK_EQ(OK, rv);
294 rv = DoResolveHost();
295 break;
296 case STATE_RESOLVE_HOST_COMPLETE:
297 rv = DoResolveHostComplete(rv);
298 break;
299 case STATE_LOAD_SERVER_INFO:
300 CHECK_EQ(OK, rv);
301 rv = DoLoadServerInfo();
302 break;
303 case STATE_LOAD_SERVER_INFO_COMPLETE:
304 rv = DoLoadServerInfoComplete(rv);
305 break;
306 case STATE_CONNECT:
307 CHECK_EQ(OK, rv);
308 rv = DoConnect();
309 break;
310 case STATE_RESUME_CONNECT:
311 CHECK_EQ(OK, rv);
312 rv = DoResumeConnect();
313 break;
314 case STATE_CONNECT_COMPLETE:
315 rv = DoConnectComplete(rv);
316 break;
317 default:
318 NOTREACHED() << "io_state_: " << io_state_;
319 break;
321 } while (io_state_ != STATE_NONE && rv != ERR_IO_PENDING);
322 return rv;
325 void QuicStreamFactory::Job::OnIOComplete(int rv) {
326 rv = DoLoop(rv);
327 if (rv != ERR_IO_PENDING && !callback_.is_null()) {
328 callback_.Run(rv);
332 void QuicStreamFactory::Job::RunAuxilaryJob() {
333 int rv = Run(base::Bind(&QuicStreamFactory::OnJobComplete,
334 base::Unretained(factory_), this));
335 if (rv != ERR_IO_PENDING)
336 factory_->OnJobComplete(this, rv);
339 void QuicStreamFactory::Job::Cancel() {
340 callback_.Reset();
341 if (session_)
342 session_->connection()->SendConnectionClose(QUIC_CONNECTION_CANCELLED);
345 void QuicStreamFactory::Job::CancelWaitForDataReadyCallback() {
346 // If we are waiting for WaitForDataReadyCallback, then cancel the callback.
347 if (io_state_ != STATE_LOAD_SERVER_INFO_COMPLETE)
348 return;
349 server_info_->CancelWaitForDataReadyCallback();
350 OnIOComplete(OK);
353 int QuicStreamFactory::Job::DoResolveHost() {
354 // Start loading the data now, and wait for it after we resolve the host.
355 if (server_info_) {
356 server_info_->Start();
359 io_state_ = STATE_RESOLVE_HOST_COMPLETE;
360 dns_resolution_start_time_ = base::TimeTicks::Now();
361 return host_resolver_.Resolve(
362 HostResolver::RequestInfo(server_id_.host_port_pair()), DEFAULT_PRIORITY,
363 &address_list_,
364 base::Bind(&QuicStreamFactory::Job::OnIOComplete, GetWeakPtr()),
365 net_log_);
368 int QuicStreamFactory::Job::DoResolveHostComplete(int rv) {
369 dns_resolution_end_time_ = base::TimeTicks::Now();
370 UMA_HISTOGRAM_TIMES("Net.QuicSession.HostResolutionTime",
371 dns_resolution_end_time_ - dns_resolution_start_time_);
372 if (rv != OK)
373 return rv;
375 DCHECK(!factory_->HasActiveSession(server_id_));
377 // Inform the factory of this resolution, which will set up
378 // a session alias, if possible.
379 if (factory_->OnResolution(server_id_, address_list_)) {
380 return OK;
383 if (server_info_)
384 io_state_ = STATE_LOAD_SERVER_INFO;
385 else
386 io_state_ = STATE_CONNECT;
387 return OK;
390 int QuicStreamFactory::Job::DoLoadServerInfo() {
391 io_state_ = STATE_LOAD_SERVER_INFO_COMPLETE;
393 DCHECK(server_info_);
395 // To mitigate the effects of disk cache taking too long to load QUIC server
396 // information, set up a timer to cancel WaitForDataReady's callback.
397 if (factory_->load_server_info_timeout_srtt_multiplier_ > 0) {
398 const int kMaxLoadServerInfoTimeoutMs = 50;
399 // Wait for DiskCache a maximum of 50ms.
400 int64 load_server_info_timeout_ms =
401 min(static_cast<int>(
402 (factory_->load_server_info_timeout_srtt_multiplier_ *
403 factory_->GetServerNetworkStatsSmoothedRttInMicroseconds(
404 server_id_)) /
405 1000),
406 kMaxLoadServerInfoTimeoutMs);
407 if (load_server_info_timeout_ms > 0) {
408 factory_->task_runner_->PostDelayedTask(
409 FROM_HERE,
410 base::Bind(&QuicStreamFactory::Job::CancelWaitForDataReadyCallback,
411 GetWeakPtr()),
412 base::TimeDelta::FromMilliseconds(load_server_info_timeout_ms));
416 int rv = server_info_->WaitForDataReady(
417 base::Bind(&QuicStreamFactory::Job::OnIOComplete, GetWeakPtr()));
418 if (rv == ERR_IO_PENDING && factory_->enable_connection_racing()) {
419 // If we are waiting to load server config from the disk cache, then start
420 // another job.
421 started_another_job_ = true;
422 factory_->CreateAuxilaryJob(server_id_, cert_verify_flags_,
423 server_and_origin_have_same_host_, is_post_,
424 net_log_);
426 return rv;
429 int QuicStreamFactory::Job::DoLoadServerInfoComplete(int rv) {
430 UMA_HISTOGRAM_TIMES("Net.QuicServerInfo.DiskCacheWaitForDataReadyTime",
431 base::TimeTicks::Now() - dns_resolution_end_time_);
433 if (rv != OK)
434 server_info_.reset();
436 if (started_another_job_ &&
437 (!server_info_ || server_info_->state().server_config.empty() ||
438 !factory_->CryptoConfigCacheIsEmpty(server_id_))) {
439 // If we have started another job and if we didn't load the server config
440 // from the disk cache or if we have received a new server config from the
441 // server, then cancel the current job.
442 io_state_ = STATE_NONE;
443 return ERR_CONNECTION_CLOSED;
446 io_state_ = STATE_CONNECT;
447 return OK;
450 int QuicStreamFactory::Job::DoConnect() {
451 io_state_ = STATE_CONNECT_COMPLETE;
453 int rv = factory_->CreateSession(
454 server_id_, cert_verify_flags_, server_info_.Pass(), address_list_,
455 dns_resolution_end_time_, net_log_, &session_);
456 if (rv != OK) {
457 DCHECK(rv != ERR_IO_PENDING);
458 DCHECK(!session_);
459 return rv;
462 if (!session_->connection()->connected()) {
463 return ERR_CONNECTION_CLOSED;
466 session_->StartReading();
467 if (!session_->connection()->connected()) {
468 return ERR_QUIC_PROTOCOL_ERROR;
470 bool require_confirmation = factory_->require_confirmation() ||
471 !server_and_origin_have_same_host_ || is_post_ ||
472 was_alternative_service_recently_broken_;
474 rv = session_->CryptoConnect(
475 require_confirmation,
476 base::Bind(&QuicStreamFactory::Job::OnIOComplete, GetWeakPtr()));
477 return rv;
480 int QuicStreamFactory::Job::DoResumeConnect() {
481 io_state_ = STATE_CONNECT_COMPLETE;
483 int rv = session_->ResumeCryptoConnect(
484 base::Bind(&QuicStreamFactory::Job::OnIOComplete, GetWeakPtr()));
486 return rv;
489 int QuicStreamFactory::Job::DoConnectComplete(int rv) {
490 if (rv != OK)
491 return rv;
493 DCHECK(!factory_->HasActiveSession(server_id_));
494 // There may well now be an active session for this IP. If so, use the
495 // existing session instead.
496 AddressList address(session_->connection()->peer_address());
497 if (factory_->OnResolution(server_id_, address)) {
498 session_->connection()->SendConnectionClose(QUIC_CONNECTION_IP_POOLED);
499 session_ = nullptr;
500 return OK;
503 factory_->ActivateSession(server_id_, session_);
505 return OK;
508 QuicStreamRequest::QuicStreamRequest(QuicStreamFactory* factory)
509 : factory_(factory) {}
511 QuicStreamRequest::~QuicStreamRequest() {
512 if (factory_ && !callback_.is_null())
513 factory_->CancelRequest(this);
516 int QuicStreamRequest::Request(const HostPortPair& host_port_pair,
517 bool is_https,
518 PrivacyMode privacy_mode,
519 int cert_verify_flags,
520 base::StringPiece origin_host,
521 base::StringPiece method,
522 const BoundNetLog& net_log,
523 const CompletionCallback& callback) {
524 DCHECK(!stream_);
525 DCHECK(callback_.is_null());
526 DCHECK(factory_);
527 origin_host_ = origin_host.as_string();
528 privacy_mode_ = privacy_mode;
529 int rv =
530 factory_->Create(host_port_pair, is_https, privacy_mode,
531 cert_verify_flags, origin_host, method, net_log, this);
532 if (rv == ERR_IO_PENDING) {
533 host_port_pair_ = host_port_pair;
534 is_https_ = is_https;
535 net_log_ = net_log;
536 callback_ = callback;
537 } else {
538 factory_ = nullptr;
540 if (rv == OK)
541 DCHECK(stream_);
542 return rv;
545 void QuicStreamRequest::set_stream(scoped_ptr<QuicHttpStream> stream) {
546 DCHECK(stream);
547 stream_ = stream.Pass();
550 void QuicStreamRequest::OnRequestComplete(int rv) {
551 factory_ = nullptr;
552 callback_.Run(rv);
555 base::TimeDelta QuicStreamRequest::GetTimeDelayForWaitingJob() const {
556 if (!factory_)
557 return base::TimeDelta();
558 return factory_->GetTimeDelayForWaitingJob(
559 QuicServerId(host_port_pair_, is_https_, privacy_mode_));
562 scoped_ptr<QuicHttpStream> QuicStreamRequest::ReleaseStream() {
563 DCHECK(stream_);
564 return stream_.Pass();
567 QuicStreamFactory::QuicStreamFactory(
568 HostResolver* host_resolver,
569 ClientSocketFactory* client_socket_factory,
570 base::WeakPtr<HttpServerProperties> http_server_properties,
571 CertVerifier* cert_verifier,
572 CertPolicyEnforcer* cert_policy_enforcer,
573 ChannelIDService* channel_id_service,
574 TransportSecurityState* transport_security_state,
575 const SocketPerformanceWatcherFactory* socket_performance_watcher_factory,
576 QuicCryptoClientStreamFactory* quic_crypto_client_stream_factory,
577 QuicRandom* random_generator,
578 QuicClock* clock,
579 size_t max_packet_length,
580 const std::string& user_agent_id,
581 const QuicVersionVector& supported_versions,
582 bool enable_port_selection,
583 bool always_require_handshake_confirmation,
584 bool disable_connection_pooling,
585 float load_server_info_timeout_srtt_multiplier,
586 bool enable_connection_racing,
587 bool enable_non_blocking_io,
588 bool disable_disk_cache,
589 bool prefer_aes,
590 int max_number_of_lossy_connections,
591 float packet_loss_threshold,
592 int max_disabled_reasons,
593 int threshold_public_resets_post_handshake,
594 int threshold_timeouts_with_open_streams,
595 int socket_receive_buffer_size,
596 bool delay_tcp_race,
597 const QuicTagVector& connection_options)
598 : require_confirmation_(true),
599 host_resolver_(host_resolver),
600 client_socket_factory_(client_socket_factory),
601 http_server_properties_(http_server_properties),
602 transport_security_state_(transport_security_state),
603 quic_server_info_factory_(nullptr),
604 quic_crypto_client_stream_factory_(quic_crypto_client_stream_factory),
605 random_generator_(random_generator),
606 clock_(clock),
607 max_packet_length_(max_packet_length),
608 socket_performance_watcher_factory_(socket_performance_watcher_factory),
609 config_(InitializeQuicConfig(connection_options)),
610 supported_versions_(supported_versions),
611 enable_port_selection_(enable_port_selection),
612 always_require_handshake_confirmation_(
613 always_require_handshake_confirmation),
614 disable_connection_pooling_(disable_connection_pooling),
615 load_server_info_timeout_srtt_multiplier_(
616 load_server_info_timeout_srtt_multiplier),
617 enable_connection_racing_(enable_connection_racing),
618 enable_non_blocking_io_(enable_non_blocking_io),
619 disable_disk_cache_(disable_disk_cache),
620 prefer_aes_(prefer_aes),
621 max_number_of_lossy_connections_(max_number_of_lossy_connections),
622 packet_loss_threshold_(packet_loss_threshold),
623 max_disabled_reasons_(max_disabled_reasons),
624 num_public_resets_post_handshake_(0),
625 num_timeouts_with_open_streams_(0),
626 max_public_resets_post_handshake_(0),
627 max_timeouts_with_open_streams_(0),
628 threshold_timeouts_with_open_streams_(
629 threshold_timeouts_with_open_streams),
630 threshold_public_resets_post_handshake_(
631 threshold_public_resets_post_handshake),
632 socket_receive_buffer_size_(socket_receive_buffer_size),
633 delay_tcp_race_(delay_tcp_race),
634 port_seed_(random_generator_->RandUint64()),
635 check_persisted_supports_quic_(true),
636 quic_supported_servers_at_startup_initialzied_(false),
637 task_runner_(nullptr),
638 weak_factory_(this) {
639 DCHECK(transport_security_state_);
640 crypto_config_.set_user_agent_id(user_agent_id);
641 crypto_config_.AddCanonicalSuffix(".c.youtube.com");
642 crypto_config_.AddCanonicalSuffix(".googlevideo.com");
643 crypto_config_.AddCanonicalSuffix(".googleusercontent.com");
644 crypto_config_.SetProofVerifier(new ProofVerifierChromium(
645 cert_verifier, cert_policy_enforcer, transport_security_state));
646 // TODO(rtenneti): http://crbug.com/487355. Temporary fix for b/20760730 until
647 // channel_id_service is supported in cronet.
648 if (channel_id_service) {
649 crypto_config_.SetChannelIDSource(
650 new ChannelIDSourceChromium(channel_id_service));
652 #if defined(USE_OPENSSL)
653 crypto::EnsureOpenSSLInit();
654 bool has_aes_hardware_support = !!EVP_has_aes_hardware();
655 #else
656 base::CPU cpu;
657 bool has_aes_hardware_support = cpu.has_aesni() && cpu.has_avx();
658 #endif
659 UMA_HISTOGRAM_BOOLEAN("Net.QuicSession.PreferAesGcm",
660 has_aes_hardware_support);
661 if (has_aes_hardware_support || prefer_aes_)
662 crypto_config_.PreferAesGcm();
663 if (!IsEcdsaSupported())
664 crypto_config_.DisableEcdsa();
667 QuicStreamFactory::~QuicStreamFactory() {
668 CloseAllSessions(ERR_ABORTED);
669 while (!all_sessions_.empty()) {
670 delete all_sessions_.begin()->first;
671 all_sessions_.erase(all_sessions_.begin());
673 while (!active_jobs_.empty()) {
674 const QuicServerId server_id = active_jobs_.begin()->first;
675 STLDeleteElements(&(active_jobs_[server_id]));
676 active_jobs_.erase(server_id);
680 void QuicStreamFactory::set_require_confirmation(bool require_confirmation) {
681 require_confirmation_ = require_confirmation;
682 if (http_server_properties_ && (!(local_address_ == IPEndPoint()))) {
683 http_server_properties_->SetSupportsQuic(!require_confirmation,
684 local_address_.address());
688 base::TimeDelta QuicStreamFactory::GetTimeDelayForWaitingJob(
689 const QuicServerId& server_id) {
690 if (!delay_tcp_race_ || require_confirmation_)
691 return base::TimeDelta();
692 int64 srtt = 1.5 * GetServerNetworkStatsSmoothedRttInMicroseconds(server_id);
693 // Picked 300ms based on mean time from
694 // Net.QuicSession.HostResolution.HandshakeConfirmedTime histogram.
695 const int kDefaultRTT = 300 * kNumMicrosPerMilli;
696 if (!srtt)
697 srtt = kDefaultRTT;
698 return base::TimeDelta::FromMicroseconds(srtt);
701 int QuicStreamFactory::Create(const HostPortPair& host_port_pair,
702 bool is_https,
703 PrivacyMode privacy_mode,
704 int cert_verify_flags,
705 base::StringPiece origin_host,
706 base::StringPiece method,
707 const BoundNetLog& net_log,
708 QuicStreamRequest* request) {
709 QuicServerId server_id(host_port_pair, is_https, privacy_mode);
710 SessionMap::iterator it = active_sessions_.find(server_id);
711 if (it != active_sessions_.end()) {
712 QuicChromiumClientSession* session = it->second;
713 if (!session->CanPool(origin_host.as_string(), privacy_mode))
714 return ERR_ALTERNATIVE_CERT_NOT_VALID_FOR_ORIGIN;
715 request->set_stream(CreateFromSession(session));
716 return OK;
719 if (HasActiveJob(server_id)) {
720 active_requests_[request] = server_id;
721 job_requests_map_[server_id].insert(request);
722 return ERR_IO_PENDING;
725 // TODO(rtenneti): |task_runner_| is used by the Job. Initialize task_runner_
726 // in the constructor after WebRequestActionWithThreadsTest.* tests are fixed.
727 if (!task_runner_)
728 task_runner_ = base::ThreadTaskRunnerHandle::Get().get();
730 QuicServerInfo* quic_server_info = nullptr;
731 if (quic_server_info_factory_) {
732 bool load_from_disk_cache = !disable_disk_cache_;
733 if (http_server_properties_) {
734 if (!quic_supported_servers_at_startup_initialzied_)
735 InitializeQuicSupportedServersAtStartup();
736 if (!ContainsKey(quic_supported_servers_at_startup_,
737 server_id.host_port_pair())) {
738 // If there is no entry for QUIC, consider that as a new server and
739 // don't wait for Cache thread to load the data for that server.
740 load_from_disk_cache = false;
743 if (load_from_disk_cache && CryptoConfigCacheIsEmpty(server_id)) {
744 quic_server_info = quic_server_info_factory_->GetForServer(server_id);
748 bool server_and_origin_have_same_host = host_port_pair.host() == origin_host;
749 scoped_ptr<Job> job(new Job(this, host_resolver_, host_port_pair,
750 server_and_origin_have_same_host, is_https,
751 WasQuicRecentlyBroken(server_id), privacy_mode,
752 cert_verify_flags, method == "POST" /* is_post */,
753 quic_server_info, net_log));
754 int rv = job->Run(base::Bind(&QuicStreamFactory::OnJobComplete,
755 base::Unretained(this), job.get()));
756 if (rv == ERR_IO_PENDING) {
757 active_requests_[request] = server_id;
758 job_requests_map_[server_id].insert(request);
759 active_jobs_[server_id].insert(job.release());
760 return rv;
762 if (rv == OK) {
763 it = active_sessions_.find(server_id);
764 DCHECK(it != active_sessions_.end());
765 QuicChromiumClientSession* session = it->second;
766 if (!session->CanPool(origin_host.as_string(), privacy_mode))
767 return ERR_ALTERNATIVE_CERT_NOT_VALID_FOR_ORIGIN;
768 request->set_stream(CreateFromSession(session));
770 return rv;
773 void QuicStreamFactory::CreateAuxilaryJob(const QuicServerId server_id,
774 int cert_verify_flags,
775 bool server_and_origin_have_same_host,
776 bool is_post,
777 const BoundNetLog& net_log) {
778 Job* aux_job =
779 new Job(this, host_resolver_, server_id.host_port_pair(),
780 server_and_origin_have_same_host, server_id.is_https(),
781 WasQuicRecentlyBroken(server_id), server_id.privacy_mode(),
782 cert_verify_flags, is_post, nullptr, net_log);
783 active_jobs_[server_id].insert(aux_job);
784 task_runner_->PostTask(FROM_HERE,
785 base::Bind(&QuicStreamFactory::Job::RunAuxilaryJob,
786 aux_job->GetWeakPtr()));
789 bool QuicStreamFactory::OnResolution(
790 const QuicServerId& server_id,
791 const AddressList& address_list) {
792 DCHECK(!HasActiveSession(server_id));
793 if (disable_connection_pooling_) {
794 return false;
796 for (const IPEndPoint& address : address_list) {
797 const IpAliasKey ip_alias_key(address, server_id.is_https());
798 if (!ContainsKey(ip_aliases_, ip_alias_key))
799 continue;
801 const SessionSet& sessions = ip_aliases_[ip_alias_key];
802 for (QuicChromiumClientSession* session : sessions) {
803 if (!session->CanPool(server_id.host(), server_id.privacy_mode()))
804 continue;
805 active_sessions_[server_id] = session;
806 session_aliases_[session].insert(server_id);
807 return true;
810 return false;
813 void QuicStreamFactory::OnJobComplete(Job* job, int rv) {
814 QuicServerId server_id = job->server_id();
815 if (rv != OK) {
816 JobSet* jobs = &(active_jobs_[server_id]);
817 if (jobs->size() > 1) {
818 // If there is another pending job, then we can delete this job and let
819 // the other job handle the request.
820 job->Cancel();
821 jobs->erase(job);
822 delete job;
823 return;
827 if (rv == OK) {
828 if (!always_require_handshake_confirmation_)
829 set_require_confirmation(false);
831 // Create all the streams, but do not notify them yet.
832 SessionMap::iterator session_it = active_sessions_.find(server_id);
833 for (RequestSet::iterator request_it = job_requests_map_[server_id].begin();
834 request_it != job_requests_map_[server_id].end();) {
835 DCHECK(session_it != active_sessions_.end());
836 QuicChromiumClientSession* session = session_it->second;
837 QuicStreamRequest* request = *request_it;
838 if (!session->CanPool(request->origin_host(), request->privacy_mode())) {
839 RequestSet::iterator old_request_it = request_it;
840 ++request_it;
841 // Remove request from containers so that OnRequestComplete() is not
842 // called later again on the same request.
843 job_requests_map_[server_id].erase(old_request_it);
844 active_requests_.erase(request);
845 // Notify request of certificate error.
846 request->OnRequestComplete(ERR_ALTERNATIVE_CERT_NOT_VALID_FOR_ORIGIN);
847 continue;
849 request->set_stream(CreateFromSession(session));
850 ++request_it;
854 while (!job_requests_map_[server_id].empty()) {
855 RequestSet::iterator it = job_requests_map_[server_id].begin();
856 QuicStreamRequest* request = *it;
857 job_requests_map_[server_id].erase(it);
858 active_requests_.erase(request);
859 // Even though we're invoking callbacks here, we don't need to worry
860 // about |this| being deleted, because the factory is owned by the
861 // profile which can not be deleted via callbacks.
862 request->OnRequestComplete(rv);
865 for (Job* other_job : active_jobs_[server_id]) {
866 if (other_job != job)
867 other_job->Cancel();
870 STLDeleteElements(&(active_jobs_[server_id]));
871 active_jobs_.erase(server_id);
872 job_requests_map_.erase(server_id);
875 scoped_ptr<QuicHttpStream> QuicStreamFactory::CreateFromSession(
876 QuicChromiumClientSession* session) {
877 return scoped_ptr<QuicHttpStream>(new QuicHttpStream(session->GetWeakPtr()));
880 QuicChromiumClientSession::QuicDisabledReason
881 QuicStreamFactory::QuicDisabledReason(uint16 port) const {
882 if (max_number_of_lossy_connections_ > 0 &&
883 number_of_lossy_connections_.find(port) !=
884 number_of_lossy_connections_.end() &&
885 number_of_lossy_connections_.at(port) >=
886 max_number_of_lossy_connections_) {
887 return QuicChromiumClientSession::QUIC_DISABLED_BAD_PACKET_LOSS_RATE;
889 if (threshold_public_resets_post_handshake_ > 0 &&
890 num_public_resets_post_handshake_ >=
891 threshold_public_resets_post_handshake_) {
892 return QuicChromiumClientSession::QUIC_DISABLED_PUBLIC_RESET_POST_HANDSHAKE;
894 if (threshold_timeouts_with_open_streams_ > 0 &&
895 num_timeouts_with_open_streams_ >=
896 threshold_timeouts_with_open_streams_) {
897 return QuicChromiumClientSession::QUIC_DISABLED_TIMEOUT_WITH_OPEN_STREAMS;
899 return QuicChromiumClientSession::QUIC_DISABLED_NOT;
902 const char* QuicStreamFactory::QuicDisabledReasonString() const {
903 // TODO(ckrasic) - better solution for port/lossy connections?
904 const uint16 port = 443;
905 switch (QuicDisabledReason(port)) {
906 case QuicChromiumClientSession::QUIC_DISABLED_BAD_PACKET_LOSS_RATE:
907 return "Bad packet loss rate.";
908 case QuicChromiumClientSession::QUIC_DISABLED_PUBLIC_RESET_POST_HANDSHAKE:
909 return "Public resets after successful handshakes.";
910 case QuicChromiumClientSession::QUIC_DISABLED_TIMEOUT_WITH_OPEN_STREAMS:
911 return "Connection timeouts with streams open.";
912 default:
913 return "";
917 bool QuicStreamFactory::IsQuicDisabled(uint16 port) {
918 return QuicDisabledReason(port) !=
919 QuicChromiumClientSession::QUIC_DISABLED_NOT;
922 bool QuicStreamFactory::OnHandshakeConfirmed(QuicChromiumClientSession* session,
923 float packet_loss_rate) {
924 DCHECK(session);
925 uint16 port = session->server_id().port();
926 if (packet_loss_rate < packet_loss_threshold_) {
927 number_of_lossy_connections_[port] = 0;
928 return false;
931 if (http_server_properties_) {
932 // We mark it as recently broken, which means that 0-RTT will be disabled
933 // but we'll still race.
934 http_server_properties_->MarkAlternativeServiceRecentlyBroken(
935 AlternativeService(QUIC, session->server_id().host(), port));
938 bool was_quic_disabled = IsQuicDisabled(port);
939 ++number_of_lossy_connections_[port];
941 // Collect data for port 443 for packet loss events.
942 if (port == 443 && max_number_of_lossy_connections_ > 0) {
943 UMA_HISTOGRAM_SPARSE_SLOWLY(
944 base::StringPrintf("Net.QuicStreamFactory.BadPacketLossEvents%d",
945 max_number_of_lossy_connections_),
946 std::min(number_of_lossy_connections_[port],
947 max_number_of_lossy_connections_));
950 bool is_quic_disabled = IsQuicDisabled(port);
951 if (is_quic_disabled) {
952 // Close QUIC connection if Quic is disabled for this port.
953 session->CloseSessionOnErrorAndNotifyFactoryLater(
954 ERR_ABORTED, QUIC_BAD_PACKET_LOSS_RATE);
956 // If this bad packet loss rate disabled the QUIC, then record it.
957 if (!was_quic_disabled)
958 UMA_HISTOGRAM_SPARSE_SLOWLY("Net.QuicStreamFactory.QuicIsDisabled", port);
960 return is_quic_disabled;
963 void QuicStreamFactory::OnIdleSession(QuicChromiumClientSession* session) {}
965 void QuicStreamFactory::OnSessionGoingAway(QuicChromiumClientSession* session) {
966 const AliasSet& aliases = session_aliases_[session];
967 for (AliasSet::const_iterator it = aliases.begin(); it != aliases.end();
968 ++it) {
969 DCHECK(active_sessions_.count(*it));
970 DCHECK_EQ(session, active_sessions_[*it]);
971 // Track sessions which have recently gone away so that we can disable
972 // port suggestions.
973 if (session->goaway_received()) {
974 gone_away_aliases_.insert(*it);
977 active_sessions_.erase(*it);
978 ProcessGoingAwaySession(session, *it, true);
980 ProcessGoingAwaySession(session, all_sessions_[session], false);
981 if (!aliases.empty()) {
982 const IpAliasKey ip_alias_key(session->connection()->peer_address(),
983 aliases.begin()->is_https());
984 ip_aliases_[ip_alias_key].erase(session);
985 if (ip_aliases_[ip_alias_key].empty()) {
986 ip_aliases_.erase(ip_alias_key);
989 session_aliases_.erase(session);
992 void QuicStreamFactory::MaybeDisableQuic(QuicChromiumClientSession* session) {
993 DCHECK(session);
994 uint16 port = session->server_id().port();
995 if (IsQuicDisabled(port))
996 return;
998 // Expire the oldest disabled_reason if appropriate. This enforces that we
999 // only consider the max_disabled_reasons_ most recent sessions.
1000 QuicChromiumClientSession::QuicDisabledReason disabled_reason;
1001 if (static_cast<int>(disabled_reasons_.size()) == max_disabled_reasons_) {
1002 disabled_reason = disabled_reasons_.front();
1003 disabled_reasons_.pop_front();
1004 if (disabled_reason ==
1005 QuicChromiumClientSession::QUIC_DISABLED_PUBLIC_RESET_POST_HANDSHAKE) {
1006 --num_public_resets_post_handshake_;
1007 } else if (disabled_reason == QuicChromiumClientSession::
1008 QUIC_DISABLED_TIMEOUT_WITH_OPEN_STREAMS) {
1009 --num_timeouts_with_open_streams_;
1012 disabled_reason = session->disabled_reason();
1013 disabled_reasons_.push_back(disabled_reason);
1014 if (disabled_reason ==
1015 QuicChromiumClientSession::QUIC_DISABLED_PUBLIC_RESET_POST_HANDSHAKE) {
1016 ++num_public_resets_post_handshake_;
1017 } else if (disabled_reason == QuicChromiumClientSession::
1018 QUIC_DISABLED_TIMEOUT_WITH_OPEN_STREAMS) {
1019 ++num_timeouts_with_open_streams_;
1021 if (num_timeouts_with_open_streams_ > max_timeouts_with_open_streams_) {
1022 max_timeouts_with_open_streams_ = num_timeouts_with_open_streams_;
1023 UMA_HISTOGRAM_CUSTOM_COUNTS("Net.QuicStreamFactory.TimeoutsWithOpenStreams",
1024 num_timeouts_with_open_streams_, 0, 20, 10);
1027 if (num_public_resets_post_handshake_ > max_public_resets_post_handshake_) {
1028 max_public_resets_post_handshake_ = num_public_resets_post_handshake_;
1029 UMA_HISTOGRAM_CUSTOM_COUNTS(
1030 "Net.QuicStreamFactory.PublicResetsPostHandshake",
1031 num_public_resets_post_handshake_, 0, 20, 10);
1034 if (IsQuicDisabled(port)) {
1035 if (disabled_reason ==
1036 QuicChromiumClientSession::QUIC_DISABLED_PUBLIC_RESET_POST_HANDSHAKE) {
1037 session->CloseSessionOnErrorAndNotifyFactoryLater(
1038 ERR_ABORTED, QUIC_PUBLIC_RESETS_POST_HANDSHAKE);
1039 } else if (disabled_reason == QuicChromiumClientSession::
1040 QUIC_DISABLED_TIMEOUT_WITH_OPEN_STREAMS) {
1041 session->CloseSessionOnErrorAndNotifyFactoryLater(
1042 ERR_ABORTED, QUIC_TIMEOUTS_WITH_OPEN_STREAMS);
1044 UMA_HISTOGRAM_ENUMERATION("Net.QuicStreamFactory.DisabledReasons",
1045 disabled_reason,
1046 QuicChromiumClientSession::QUIC_DISABLED_MAX);
1050 void QuicStreamFactory::OnSessionClosed(QuicChromiumClientSession* session) {
1051 DCHECK_EQ(0u, session->GetNumOpenStreams());
1052 MaybeDisableQuic(session);
1053 OnSessionGoingAway(session);
1054 delete session;
1055 all_sessions_.erase(session);
1058 void QuicStreamFactory::OnSessionConnectTimeout(
1059 QuicChromiumClientSession* session) {
1060 const AliasSet& aliases = session_aliases_[session];
1061 for (AliasSet::const_iterator it = aliases.begin(); it != aliases.end();
1062 ++it) {
1063 DCHECK(active_sessions_.count(*it));
1064 DCHECK_EQ(session, active_sessions_[*it]);
1065 active_sessions_.erase(*it);
1068 if (aliases.empty()) {
1069 return;
1072 const IpAliasKey ip_alias_key(session->connection()->peer_address(),
1073 aliases.begin()->is_https());
1074 ip_aliases_[ip_alias_key].erase(session);
1075 if (ip_aliases_[ip_alias_key].empty()) {
1076 ip_aliases_.erase(ip_alias_key);
1078 QuicServerId server_id = *aliases.begin();
1079 session_aliases_.erase(session);
1080 Job* job = new Job(this, host_resolver_, session, server_id);
1081 active_jobs_[server_id].insert(job);
1082 int rv = job->Run(base::Bind(&QuicStreamFactory::OnJobComplete,
1083 base::Unretained(this), job));
1084 DCHECK_EQ(ERR_IO_PENDING, rv);
1087 void QuicStreamFactory::CancelRequest(QuicStreamRequest* request) {
1088 DCHECK(ContainsKey(active_requests_, request));
1089 QuicServerId server_id = active_requests_[request];
1090 job_requests_map_[server_id].erase(request);
1091 active_requests_.erase(request);
1094 void QuicStreamFactory::CloseAllSessions(int error) {
1095 while (!active_sessions_.empty()) {
1096 size_t initial_size = active_sessions_.size();
1097 active_sessions_.begin()->second->CloseSessionOnError(error,
1098 QUIC_INTERNAL_ERROR);
1099 DCHECK_NE(initial_size, active_sessions_.size());
1101 while (!all_sessions_.empty()) {
1102 size_t initial_size = all_sessions_.size();
1103 all_sessions_.begin()->first->CloseSessionOnError(error,
1104 QUIC_INTERNAL_ERROR);
1105 DCHECK_NE(initial_size, all_sessions_.size());
1107 DCHECK(all_sessions_.empty());
1110 scoped_ptr<base::Value> QuicStreamFactory::QuicStreamFactoryInfoToValue()
1111 const {
1112 scoped_ptr<base::ListValue> list(new base::ListValue());
1114 for (SessionMap::const_iterator it = active_sessions_.begin();
1115 it != active_sessions_.end(); ++it) {
1116 const QuicServerId& server_id = it->first;
1117 QuicChromiumClientSession* session = it->second;
1118 const AliasSet& aliases = session_aliases_.find(session)->second;
1119 // Only add a session to the list once.
1120 if (server_id == *aliases.begin()) {
1121 std::set<HostPortPair> hosts;
1122 for (AliasSet::const_iterator alias_it = aliases.begin();
1123 alias_it != aliases.end(); ++alias_it) {
1124 hosts.insert(alias_it->host_port_pair());
1126 list->Append(session->GetInfoAsValue(hosts));
1129 return list.Pass();
1132 void QuicStreamFactory::ClearCachedStatesInCryptoConfig() {
1133 crypto_config_.ClearCachedStates();
1136 void QuicStreamFactory::OnIPAddressChanged() {
1137 CloseAllSessions(ERR_NETWORK_CHANGED);
1138 set_require_confirmation(true);
1141 void QuicStreamFactory::OnSSLConfigChanged() {
1142 CloseAllSessions(ERR_CERT_DATABASE_CHANGED);
1145 void QuicStreamFactory::OnCertAdded(const X509Certificate* cert) {
1146 CloseAllSessions(ERR_CERT_DATABASE_CHANGED);
1149 void QuicStreamFactory::OnCACertChanged(const X509Certificate* cert) {
1150 // We should flush the sessions if we removed trust from a
1151 // cert, because a previously trusted server may have become
1152 // untrusted.
1154 // We should not flush the sessions if we added trust to a cert.
1156 // Since the OnCACertChanged method doesn't tell us what
1157 // kind of change it is, we have to flush the socket
1158 // pools to be safe.
1159 CloseAllSessions(ERR_CERT_DATABASE_CHANGED);
1162 bool QuicStreamFactory::HasActiveSession(
1163 const QuicServerId& server_id) const {
1164 return ContainsKey(active_sessions_, server_id);
1167 bool QuicStreamFactory::HasActiveJob(const QuicServerId& key) const {
1168 return ContainsKey(active_jobs_, key);
1171 int QuicStreamFactory::CreateSession(const QuicServerId& server_id,
1172 int cert_verify_flags,
1173 scoped_ptr<QuicServerInfo> server_info,
1174 const AddressList& address_list,
1175 base::TimeTicks dns_resolution_end_time,
1176 const BoundNetLog& net_log,
1177 QuicChromiumClientSession** session) {
1178 bool enable_port_selection = enable_port_selection_;
1179 if (enable_port_selection &&
1180 ContainsKey(gone_away_aliases_, server_id)) {
1181 // Disable port selection when the server is going away.
1182 // There is no point in trying to return to the same server, if
1183 // that server is no longer handling requests.
1184 enable_port_selection = false;
1185 gone_away_aliases_.erase(server_id);
1188 QuicConnectionId connection_id = random_generator_->RandUint64();
1189 IPEndPoint addr = *address_list.begin();
1190 scoped_refptr<PortSuggester> port_suggester =
1191 new PortSuggester(server_id.host_port_pair(), port_seed_);
1192 DatagramSocket::BindType bind_type = enable_port_selection ?
1193 DatagramSocket::RANDOM_BIND : // Use our callback.
1194 DatagramSocket::DEFAULT_BIND; // Use OS to randomize.
1195 scoped_ptr<DatagramClientSocket> socket(
1196 client_socket_factory_->CreateDatagramClientSocket(
1197 bind_type,
1198 base::Bind(&PortSuggester::SuggestPort, port_suggester),
1199 net_log.net_log(), net_log.source()));
1201 if (enable_non_blocking_io_ &&
1202 client_socket_factory_ == ClientSocketFactory::GetDefaultFactory()) {
1203 #if defined(OS_WIN)
1204 static_cast<UDPClientSocket*>(socket.get())->UseNonBlockingIO();
1205 #endif
1208 int rv = socket->Connect(addr);
1210 if (rv != OK) {
1211 HistogramCreateSessionFailure(CREATION_ERROR_CONNECTING_SOCKET);
1212 return rv;
1214 UMA_HISTOGRAM_COUNTS("Net.QuicEphemeralPortsSuggested",
1215 port_suggester->call_count());
1216 if (enable_port_selection) {
1217 DCHECK_LE(1u, port_suggester->call_count());
1218 } else {
1219 DCHECK_EQ(0u, port_suggester->call_count());
1222 rv = socket->SetReceiveBufferSize(socket_receive_buffer_size_);
1223 if (rv != OK) {
1224 HistogramCreateSessionFailure(CREATION_ERROR_SETTING_RECEIVE_BUFFER);
1225 return rv;
1227 // Set a buffer large enough to contain the initial CWND's worth of packet
1228 // to work around the problem with CHLO packets being sent out with the
1229 // wrong encryption level, when the send buffer is full.
1230 rv = socket->SetSendBufferSize(kMaxPacketSize * 20);
1231 if (rv != OK) {
1232 HistogramCreateSessionFailure(CREATION_ERROR_SETTING_SEND_BUFFER);
1233 return rv;
1236 socket->GetLocalAddress(&local_address_);
1237 if (check_persisted_supports_quic_ && http_server_properties_) {
1238 check_persisted_supports_quic_ = false;
1239 IPAddressNumber last_address;
1240 if (http_server_properties_->GetSupportsQuic(&last_address) &&
1241 last_address == local_address_.address()) {
1242 require_confirmation_ = false;
1246 DefaultPacketWriterFactory packet_writer_factory(socket.get());
1248 if (!helper_.get()) {
1249 helper_.reset(
1250 new QuicConnectionHelper(base::ThreadTaskRunnerHandle::Get().get(),
1251 clock_.get(), random_generator_));
1254 QuicConnection* connection = new QuicConnection(
1255 connection_id, addr, helper_.get(), packet_writer_factory,
1256 true /* owns_writer */, Perspective::IS_CLIENT, server_id.is_https(),
1257 supported_versions_);
1258 connection->SetMaxPacketLength(max_packet_length_);
1260 InitializeCachedStateInCryptoConfig(server_id, server_info);
1262 QuicConfig config = config_;
1263 config.SetSocketReceiveBufferToSend(socket_receive_buffer_size_);
1264 config.set_max_undecryptable_packets(kMaxUndecryptablePackets);
1265 config.SetInitialSessionFlowControlWindowToSend(
1266 kQuicSessionMaxRecvWindowSize);
1267 config.SetInitialStreamFlowControlWindowToSend(kQuicStreamMaxRecvWindowSize);
1268 int64 srtt = GetServerNetworkStatsSmoothedRttInMicroseconds(server_id);
1269 if (srtt > 0)
1270 config.SetInitialRoundTripTimeUsToSend(static_cast<uint32>(srtt));
1271 config.SetBytesForConnectionIdToSend(0);
1273 if (quic_server_info_factory_ && !server_info) {
1274 // Start the disk cache loading so that we can persist the newer QUIC server
1275 // information and/or inform the disk cache that we have reused
1276 // |server_info|.
1277 server_info.reset(quic_server_info_factory_->GetForServer(server_id));
1278 server_info->Start();
1281 // Use the factory to create a new socket performance watcher, and pass the
1282 // ownership to QuicChromiumClientSession.
1283 scoped_ptr<SocketPerformanceWatcher> socket_performance_watcher;
1284 if (socket_performance_watcher_factory_) {
1285 socket_performance_watcher = socket_performance_watcher_factory_
1286 ->CreateUDPSocketPerformanceWatcher();
1289 *session = new QuicChromiumClientSession(
1290 connection, socket.Pass(), this, quic_crypto_client_stream_factory_,
1291 transport_security_state_, server_info.Pass(), server_id,
1292 cert_verify_flags, config, &crypto_config_,
1293 network_connection_.GetDescription(), dns_resolution_end_time,
1294 base::ThreadTaskRunnerHandle::Get().get(),
1295 socket_performance_watcher.Pass(), net_log.net_log());
1297 all_sessions_[*session] = server_id; // owning pointer
1299 (*session)->Initialize();
1300 bool closed_during_initialize =
1301 !ContainsKey(all_sessions_, *session) ||
1302 !(*session)->connection()->connected();
1303 UMA_HISTOGRAM_BOOLEAN("Net.QuicSession.ClosedDuringInitializeSession",
1304 closed_during_initialize);
1305 if (closed_during_initialize) {
1306 DLOG(DFATAL) << "Session closed during initialize";
1307 *session = nullptr;
1308 return ERR_CONNECTION_CLOSED;
1310 return OK;
1313 void QuicStreamFactory::ActivateSession(const QuicServerId& server_id,
1314 QuicChromiumClientSession* session) {
1315 DCHECK(!HasActiveSession(server_id));
1316 UMA_HISTOGRAM_COUNTS("Net.QuicActiveSessions", active_sessions_.size());
1317 active_sessions_[server_id] = session;
1318 session_aliases_[session].insert(server_id);
1319 const IpAliasKey ip_alias_key(session->connection()->peer_address(),
1320 server_id.is_https());
1321 DCHECK(!ContainsKey(ip_aliases_[ip_alias_key], session));
1322 ip_aliases_[ip_alias_key].insert(session);
1325 int64 QuicStreamFactory::GetServerNetworkStatsSmoothedRttInMicroseconds(
1326 const QuicServerId& server_id) const {
1327 if (!http_server_properties_)
1328 return 0;
1329 const ServerNetworkStats* stats =
1330 http_server_properties_->GetServerNetworkStats(
1331 server_id.host_port_pair());
1332 if (stats == nullptr)
1333 return 0;
1334 return stats->srtt.InMicroseconds();
1337 bool QuicStreamFactory::WasQuicRecentlyBroken(
1338 const QuicServerId& server_id) const {
1339 if (!http_server_properties_)
1340 return false;
1341 const AlternativeService alternative_service(QUIC,
1342 server_id.host_port_pair());
1343 return http_server_properties_->WasAlternativeServiceRecentlyBroken(
1344 alternative_service);
1347 bool QuicStreamFactory::CryptoConfigCacheIsEmpty(
1348 const QuicServerId& server_id) {
1349 QuicCryptoClientConfig::CachedState* cached =
1350 crypto_config_.LookupOrCreate(server_id);
1351 return cached->IsEmpty();
1354 void QuicStreamFactory::InitializeCachedStateInCryptoConfig(
1355 const QuicServerId& server_id,
1356 const scoped_ptr<QuicServerInfo>& server_info) {
1357 // |server_info| will be NULL, if a non-empty server config already exists in
1358 // the memory cache. This is a minor optimization to avoid LookupOrCreate.
1359 if (!server_info)
1360 return;
1362 QuicCryptoClientConfig::CachedState* cached =
1363 crypto_config_.LookupOrCreate(server_id);
1364 if (!cached->IsEmpty())
1365 return;
1367 if (http_server_properties_) {
1368 DCHECK(quic_supported_servers_at_startup_initialzied_);
1369 // TODO(rtenneti): Delete the following histogram after collecting stats.
1370 // If the AlternativeServiceMap contained an entry for this host, check if
1371 // the disk cache contained an entry for it.
1372 if (ContainsKey(quic_supported_servers_at_startup_,
1373 server_id.host_port_pair())) {
1374 UMA_HISTOGRAM_BOOLEAN(
1375 "Net.QuicServerInfo.ExpectConfigMissingFromDiskCache",
1376 server_info->state().server_config.empty());
1380 if (!cached->Initialize(server_info->state().server_config,
1381 server_info->state().source_address_token,
1382 server_info->state().certs,
1383 server_info->state().server_config_sig,
1384 clock_->WallNow()))
1385 return;
1387 if (!server_id.is_https()) {
1388 // Don't check the certificates for insecure QUIC.
1389 cached->SetProofValid();
1393 void QuicStreamFactory::InitializeQuicSupportedServersAtStartup() {
1394 DCHECK(http_server_properties_);
1395 DCHECK(!quic_supported_servers_at_startup_initialzied_);
1396 quic_supported_servers_at_startup_initialzied_ = true;
1397 for (const std::pair<const HostPortPair, AlternativeServiceInfoVector>&
1398 key_value : http_server_properties_->alternative_service_map()) {
1399 for (const AlternativeServiceInfo& alternative_service_info :
1400 key_value.second) {
1401 if (alternative_service_info.alternative_service.protocol == QUIC) {
1402 quic_supported_servers_at_startup_.insert(key_value.first);
1403 break;
1409 void QuicStreamFactory::ProcessGoingAwaySession(
1410 QuicChromiumClientSession* session,
1411 const QuicServerId& server_id,
1412 bool session_was_active) {
1413 if (!http_server_properties_)
1414 return;
1416 const QuicConnectionStats& stats = session->connection()->GetStats();
1417 const AlternativeService alternative_service(QUIC,
1418 server_id.host_port_pair());
1419 if (session->IsCryptoHandshakeConfirmed()) {
1420 http_server_properties_->ConfirmAlternativeService(alternative_service);
1421 ServerNetworkStats network_stats;
1422 network_stats.srtt = base::TimeDelta::FromMicroseconds(stats.srtt_us);
1423 network_stats.bandwidth_estimate = stats.estimated_bandwidth;
1424 http_server_properties_->SetServerNetworkStats(server_id.host_port_pair(),
1425 network_stats);
1426 return;
1429 UMA_HISTOGRAM_COUNTS("Net.QuicHandshakeNotConfirmedNumPacketsReceived",
1430 stats.packets_received);
1432 if (!session_was_active)
1433 return;
1435 // TODO(rch): In the special case where the session has received no
1436 // packets from the peer, we should consider blacklisting this
1437 // differently so that we still race TCP but we don't consider the
1438 // session connected until the handshake has been confirmed.
1439 HistogramBrokenAlternateProtocolLocation(
1440 BROKEN_ALTERNATE_PROTOCOL_LOCATION_QUIC_STREAM_FACTORY);
1442 // Since the session was active, there's no longer an
1443 // HttpStreamFactoryImpl::Job running which can mark it broken, unless the TCP
1444 // job also fails. So to avoid not using QUIC when we otherwise could, we mark
1445 // it as recently broken, which means that 0-RTT will be disabled but we'll
1446 // still race.
1447 http_server_properties_->MarkAlternativeServiceRecentlyBroken(
1448 alternative_service);
1451 } // namespace net