Pin Chrome's shortcut to the Win10 Start menu on install and OS upgrade.
[chromium-blink-merge.git] / net / quic / quic_stream_factory.cc
blob5667f25ba733914ba864038da4203ad4b9771f29
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/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"
44 #if defined(OS_WIN)
45 #include "base/win/windows_version.h"
46 #endif
48 #if defined(USE_OPENSSL)
49 #include <openssl/aead.h>
50 #include "crypto/openssl_util.h"
51 #else
52 #include "base/cpu.h"
53 #endif
55 namespace net {
57 namespace {
59 enum CreateSessionFailure {
60 CREATION_ERROR_CONNECTING_SOCKET,
61 CREATION_ERROR_SETTING_RECEIVE_BUFFER,
62 CREATION_ERROR_SETTING_SEND_BUFFER,
63 CREATION_ERROR_MAX
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,
78 CREATION_ERROR_MAX);
81 bool IsEcdsaSupported() {
82 #if defined(OS_WIN)
83 if (base::win::GetVersion() < base::win::VERSION_VISTA)
84 return false;
85 #endif
87 return true;
90 QuicConfig InitializeQuicConfig(const QuicTagVector& connection_options) {
91 QuicConfig config;
92 config.SetIdleConnectionStateLifetime(
93 QuicTime::Delta::FromSeconds(kIdleConnectionTimeoutSeconds),
94 QuicTime::Delta::FromSeconds(kIdleConnectionTimeoutSeconds));
95 config.SetConnectionOptionsToSend(connection_options);
96 return config;
99 class DefaultPacketWriterFactory : public QuicConnection::PacketWriterFactory {
100 public:
101 explicit DefaultPacketWriterFactory(DatagramClientSocket* socket)
102 : socket_(socket) {}
103 ~DefaultPacketWriterFactory() override {}
105 QuicPacketWriter* Create(QuicConnection* connection) const override;
107 private:
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();
119 } // namespace
121 QuicStreamFactory::IpAliasKey::IpAliasKey() {}
123 QuicStreamFactory::IpAliasKey::IpAliasKey(IPEndPoint ip_endpoint,
124 bool is_https)
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 {
147 public:
148 Job(QuicStreamFactory* factory,
149 HostResolver* host_resolver,
150 const HostPortPair& host_port_pair,
151 bool server_and_origin_have_same_host,
152 bool is_https,
153 bool was_alternative_service_recently_broken,
154 PrivacyMode privacy_mode,
155 int cert_verify_flags,
156 bool is_post,
157 QuicServerInfo* server_info,
158 const BoundNetLog& net_log);
160 // Creates a new job to handle the resumption of for connecting an
161 // existing session.
162 Job(QuicStreamFactory* factory,
163 HostResolver* host_resolver,
164 QuicChromiumClientSession* session,
165 QuicServerId server_id);
167 ~Job();
169 int Run(const CompletionCallback& callback);
171 int DoLoop(int rv);
172 int DoResolveHost();
173 int DoResolveHostComplete(int rv);
174 int DoLoadServerInfo();
175 int DoLoadServerInfoComplete(int rv);
176 int DoConnect();
177 int DoResumeConnect();
178 int DoConnectComplete(int rv);
180 void OnIOComplete(int rv);
182 void RunAuxilaryJob();
184 void Cancel();
186 void CancelWaitForDataReadyCallback();
188 const QuicServerId server_id() const { return server_id_; }
190 base::WeakPtr<Job> GetWeakPtr() { return weak_factory_.GetWeakPtr(); }
192 private:
193 enum IoState {
194 STATE_NONE,
195 STATE_RESOLVE_HOST,
196 STATE_RESOLVE_HOST_COMPLETE,
197 STATE_LOAD_SERVER_INFO,
198 STATE_LOAD_SERVER_INFO_COMPLETE,
199 STATE_CONNECT,
200 STATE_RESUME_CONNECT,
201 STATE_CONNECT_COMPLETE,
203 IoState io_state_;
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_;
211 bool is_post_;
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,
229 bool is_https,
230 bool was_alternative_service_recently_broken,
231 PrivacyMode privacy_mode,
232 int cert_verify_flags,
233 bool is_post,
234 QuicServerInfo* server_info,
235 const BoundNetLog& net_log)
236 : io_state_(STATE_RESOLVE_HOST),
237 factory_(factory),
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),
242 is_post_(is_post),
243 was_alternative_service_recently_broken_(
244 was_alternative_service_recently_broken),
245 server_info_(server_info),
246 started_another_job_(false),
247 net_log_(net_log),
248 session_(nullptr),
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),
257 factory_(factory),
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
266 session_(session),
267 weak_factory_(this) {}
269 QuicStreamFactory::Job::~Job() {
270 // If disk cache has a pending WaitForDataReadyCallback, cancel that callback.
271 if (server_info_)
272 server_info_->ResetWaitForDataReadyCallback();
275 int QuicStreamFactory::Job::Run(const CompletionCallback& callback) {
276 int rv = DoLoop(OK);
277 if (rv == ERR_IO_PENDING)
278 callback_ = callback;
280 return rv > 0 ? OK : rv;
283 int QuicStreamFactory::Job::DoLoop(int rv) {
284 do {
285 IoState state = io_state_;
286 io_state_ = STATE_NONE;
287 switch (state) {
288 case STATE_RESOLVE_HOST:
289 CHECK_EQ(OK, rv);
290 rv = DoResolveHost();
291 break;
292 case STATE_RESOLVE_HOST_COMPLETE:
293 rv = DoResolveHostComplete(rv);
294 break;
295 case STATE_LOAD_SERVER_INFO:
296 CHECK_EQ(OK, rv);
297 rv = DoLoadServerInfo();
298 break;
299 case STATE_LOAD_SERVER_INFO_COMPLETE:
300 rv = DoLoadServerInfoComplete(rv);
301 break;
302 case STATE_CONNECT:
303 CHECK_EQ(OK, rv);
304 rv = DoConnect();
305 break;
306 case STATE_RESUME_CONNECT:
307 CHECK_EQ(OK, rv);
308 rv = DoResumeConnect();
309 break;
310 case STATE_CONNECT_COMPLETE:
311 rv = DoConnectComplete(rv);
312 break;
313 default:
314 NOTREACHED() << "io_state_: " << io_state_;
315 break;
317 } while (io_state_ != STATE_NONE && rv != ERR_IO_PENDING);
318 return rv;
321 void QuicStreamFactory::Job::OnIOComplete(int rv) {
322 rv = DoLoop(rv);
323 if (rv != ERR_IO_PENDING && !callback_.is_null()) {
324 callback_.Run(rv);
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() {
336 callback_.Reset();
337 if (session_)
338 session_->connection()->SendConnectionClose(QUIC_CONNECTION_CANCELLED);
341 void QuicStreamFactory::Job::CancelWaitForDataReadyCallback() {
342 // If we are waiting for WaitForDataReadyCallback, then cancel the callback.
343 if (io_state_ != STATE_LOAD_SERVER_INFO_COMPLETE)
344 return;
345 server_info_->CancelWaitForDataReadyCallback();
346 OnIOComplete(OK);
349 int QuicStreamFactory::Job::DoResolveHost() {
350 // Start loading the data now, and wait for it after we resolve the host.
351 if (server_info_) {
352 server_info_->Start();
355 io_state_ = STATE_RESOLVE_HOST_COMPLETE;
356 dns_resolution_start_time_ = base::TimeTicks::Now();
357 return host_resolver_.Resolve(
358 HostResolver::RequestInfo(server_id_.host_port_pair()), DEFAULT_PRIORITY,
359 &address_list_,
360 base::Bind(&QuicStreamFactory::Job::OnIOComplete, GetWeakPtr()),
361 net_log_);
364 int QuicStreamFactory::Job::DoResolveHostComplete(int rv) {
365 dns_resolution_end_time_ = base::TimeTicks::Now();
366 UMA_HISTOGRAM_TIMES("Net.QuicSession.HostResolutionTime",
367 dns_resolution_end_time_ - dns_resolution_start_time_);
368 if (rv != OK)
369 return rv;
371 DCHECK(!factory_->HasActiveSession(server_id_));
373 // Inform the factory of this resolution, which will set up
374 // a session alias, if possible.
375 if (factory_->OnResolution(server_id_, address_list_)) {
376 return OK;
379 if (server_info_)
380 io_state_ = STATE_LOAD_SERVER_INFO;
381 else
382 io_state_ = STATE_CONNECT;
383 return OK;
386 int QuicStreamFactory::Job::DoLoadServerInfo() {
387 io_state_ = STATE_LOAD_SERVER_INFO_COMPLETE;
389 DCHECK(server_info_);
391 // To mitigate the effects of disk cache taking too long to load QUIC server
392 // information, set up a timer to cancel WaitForDataReady's callback.
393 if (factory_->load_server_info_timeout_srtt_multiplier_ > 0) {
394 int64 load_server_info_timeout_ms =
395 (factory_->load_server_info_timeout_srtt_multiplier_ *
396 factory_->GetServerNetworkStatsSmoothedRttInMicroseconds(server_id_)) /
397 1000;
398 if (load_server_info_timeout_ms > 0) {
399 factory_->task_runner_->PostDelayedTask(
400 FROM_HERE,
401 base::Bind(&QuicStreamFactory::Job::CancelWaitForDataReadyCallback,
402 GetWeakPtr()),
403 base::TimeDelta::FromMilliseconds(load_server_info_timeout_ms));
407 int rv = server_info_->WaitForDataReady(
408 base::Bind(&QuicStreamFactory::Job::OnIOComplete, GetWeakPtr()));
409 if (rv == ERR_IO_PENDING && factory_->enable_connection_racing()) {
410 // If we are waiting to load server config from the disk cache, then start
411 // another job.
412 started_another_job_ = true;
413 factory_->CreateAuxilaryJob(server_id_, cert_verify_flags_,
414 server_and_origin_have_same_host_, is_post_,
415 net_log_);
417 return rv;
420 int QuicStreamFactory::Job::DoLoadServerInfoComplete(int rv) {
421 UMA_HISTOGRAM_TIMES("Net.QuicServerInfo.DiskCacheWaitForDataReadyTime",
422 base::TimeTicks::Now() - dns_resolution_end_time_);
424 if (rv != OK)
425 server_info_.reset();
427 if (started_another_job_ &&
428 (!server_info_ || server_info_->state().server_config.empty() ||
429 !factory_->CryptoConfigCacheIsEmpty(server_id_))) {
430 // If we have started another job and if we didn't load the server config
431 // from the disk cache or if we have received a new server config from the
432 // server, then cancel the current job.
433 io_state_ = STATE_NONE;
434 return ERR_CONNECTION_CLOSED;
437 io_state_ = STATE_CONNECT;
438 return OK;
441 int QuicStreamFactory::Job::DoConnect() {
442 io_state_ = STATE_CONNECT_COMPLETE;
444 int rv = factory_->CreateSession(
445 server_id_, cert_verify_flags_, server_info_.Pass(), address_list_,
446 dns_resolution_end_time_, net_log_, &session_);
447 if (rv != OK) {
448 DCHECK(rv != ERR_IO_PENDING);
449 DCHECK(!session_);
450 return rv;
453 if (!session_->connection()->connected()) {
454 return ERR_CONNECTION_CLOSED;
457 session_->StartReading();
458 if (!session_->connection()->connected()) {
459 return ERR_QUIC_PROTOCOL_ERROR;
461 bool require_confirmation = factory_->require_confirmation() ||
462 !server_and_origin_have_same_host_ || is_post_ ||
463 was_alternative_service_recently_broken_;
465 rv = session_->CryptoConnect(
466 require_confirmation,
467 base::Bind(&QuicStreamFactory::Job::OnIOComplete, GetWeakPtr()));
468 return rv;
471 int QuicStreamFactory::Job::DoResumeConnect() {
472 io_state_ = STATE_CONNECT_COMPLETE;
474 int rv = session_->ResumeCryptoConnect(
475 base::Bind(&QuicStreamFactory::Job::OnIOComplete, GetWeakPtr()));
477 return rv;
480 int QuicStreamFactory::Job::DoConnectComplete(int rv) {
481 if (rv != OK)
482 return rv;
484 DCHECK(!factory_->HasActiveSession(server_id_));
485 // There may well now be an active session for this IP. If so, use the
486 // existing session instead.
487 AddressList address(session_->connection()->peer_address());
488 if (factory_->OnResolution(server_id_, address)) {
489 session_->connection()->SendConnectionClose(QUIC_CONNECTION_IP_POOLED);
490 session_ = nullptr;
491 return OK;
494 factory_->ActivateSession(server_id_, session_);
496 return OK;
499 QuicStreamRequest::QuicStreamRequest(QuicStreamFactory* factory)
500 : factory_(factory) {}
502 QuicStreamRequest::~QuicStreamRequest() {
503 if (factory_ && !callback_.is_null())
504 factory_->CancelRequest(this);
507 int QuicStreamRequest::Request(const HostPortPair& host_port_pair,
508 bool is_https,
509 PrivacyMode privacy_mode,
510 int cert_verify_flags,
511 base::StringPiece origin_host,
512 base::StringPiece method,
513 const BoundNetLog& net_log,
514 const CompletionCallback& callback) {
515 DCHECK(!stream_);
516 DCHECK(callback_.is_null());
517 DCHECK(factory_);
518 origin_host_ = origin_host.as_string();
519 privacy_mode_ = privacy_mode;
520 int rv =
521 factory_->Create(host_port_pair, is_https, privacy_mode,
522 cert_verify_flags, origin_host, method, net_log, this);
523 if (rv == ERR_IO_PENDING) {
524 host_port_pair_ = host_port_pair;
525 net_log_ = net_log;
526 callback_ = callback;
527 } else {
528 factory_ = nullptr;
530 if (rv == OK)
531 DCHECK(stream_);
532 return rv;
535 void QuicStreamRequest::set_stream(scoped_ptr<QuicHttpStream> stream) {
536 DCHECK(stream);
537 stream_ = stream.Pass();
540 void QuicStreamRequest::OnRequestComplete(int rv) {
541 factory_ = nullptr;
542 callback_.Run(rv);
545 scoped_ptr<QuicHttpStream> QuicStreamRequest::ReleaseStream() {
546 DCHECK(stream_);
547 return stream_.Pass();
550 QuicStreamFactory::QuicStreamFactory(
551 HostResolver* host_resolver,
552 ClientSocketFactory* client_socket_factory,
553 base::WeakPtr<HttpServerProperties> http_server_properties,
554 CertVerifier* cert_verifier,
555 ChannelIDService* channel_id_service,
556 TransportSecurityState* transport_security_state,
557 QuicCryptoClientStreamFactory* quic_crypto_client_stream_factory,
558 QuicRandom* random_generator,
559 QuicClock* clock,
560 size_t max_packet_length,
561 const std::string& user_agent_id,
562 const QuicVersionVector& supported_versions,
563 bool enable_port_selection,
564 bool always_require_handshake_confirmation,
565 bool disable_connection_pooling,
566 float load_server_info_timeout_srtt_multiplier,
567 bool enable_connection_racing,
568 bool enable_non_blocking_io,
569 bool disable_disk_cache,
570 bool prefer_aes,
571 int max_number_of_lossy_connections,
572 float packet_loss_threshold,
573 int max_disabled_reasons,
574 int threshold_public_resets_post_handshake,
575 int threshold_timeouts_with_open_streams,
576 int socket_receive_buffer_size,
577 const QuicTagVector& connection_options)
578 : require_confirmation_(true),
579 host_resolver_(host_resolver),
580 client_socket_factory_(client_socket_factory),
581 http_server_properties_(http_server_properties),
582 transport_security_state_(transport_security_state),
583 quic_server_info_factory_(nullptr),
584 quic_crypto_client_stream_factory_(quic_crypto_client_stream_factory),
585 random_generator_(random_generator),
586 clock_(clock),
587 max_packet_length_(max_packet_length),
588 config_(InitializeQuicConfig(connection_options)),
589 supported_versions_(supported_versions),
590 enable_port_selection_(enable_port_selection),
591 always_require_handshake_confirmation_(
592 always_require_handshake_confirmation),
593 disable_connection_pooling_(disable_connection_pooling),
594 load_server_info_timeout_srtt_multiplier_(
595 load_server_info_timeout_srtt_multiplier),
596 enable_connection_racing_(enable_connection_racing),
597 enable_non_blocking_io_(enable_non_blocking_io),
598 disable_disk_cache_(disable_disk_cache),
599 prefer_aes_(prefer_aes),
600 max_number_of_lossy_connections_(max_number_of_lossy_connections),
601 packet_loss_threshold_(packet_loss_threshold),
602 max_disabled_reasons_(max_disabled_reasons),
603 num_public_resets_post_handshake_(0),
604 num_timeouts_with_open_streams_(0),
605 max_public_resets_post_handshake_(0),
606 max_timeouts_with_open_streams_(0),
607 threshold_timeouts_with_open_streams_(
608 threshold_timeouts_with_open_streams),
609 threshold_public_resets_post_handshake_(
610 threshold_public_resets_post_handshake),
611 socket_receive_buffer_size_(socket_receive_buffer_size),
612 port_seed_(random_generator_->RandUint64()),
613 check_persisted_supports_quic_(true),
614 task_runner_(nullptr),
615 weak_factory_(this) {
616 DCHECK(transport_security_state_);
617 crypto_config_.set_user_agent_id(user_agent_id);
618 crypto_config_.AddCanonicalSuffix(".c.youtube.com");
619 crypto_config_.AddCanonicalSuffix(".googlevideo.com");
620 crypto_config_.AddCanonicalSuffix(".googleusercontent.com");
621 crypto_config_.SetProofVerifier(
622 new ProofVerifierChromium(cert_verifier, transport_security_state));
623 // TODO(rtenneti): http://crbug.com/487355. Temporary fix for b/20760730 until
624 // channel_id_service is supported in cronet.
625 if (channel_id_service) {
626 crypto_config_.SetChannelIDSource(
627 new ChannelIDSourceChromium(channel_id_service));
629 #if defined(USE_OPENSSL)
630 crypto::EnsureOpenSSLInit();
631 bool has_aes_hardware_support = !!EVP_has_aes_hardware();
632 #else
633 base::CPU cpu;
634 bool has_aes_hardware_support = cpu.has_aesni() && cpu.has_avx();
635 #endif
636 UMA_HISTOGRAM_BOOLEAN("Net.QuicSession.PreferAesGcm",
637 has_aes_hardware_support);
638 if (has_aes_hardware_support || prefer_aes_)
639 crypto_config_.PreferAesGcm();
640 if (!IsEcdsaSupported())
641 crypto_config_.DisableEcdsa();
644 QuicStreamFactory::~QuicStreamFactory() {
645 CloseAllSessions(ERR_ABORTED);
646 while (!all_sessions_.empty()) {
647 delete all_sessions_.begin()->first;
648 all_sessions_.erase(all_sessions_.begin());
650 while (!active_jobs_.empty()) {
651 const QuicServerId server_id = active_jobs_.begin()->first;
652 STLDeleteElements(&(active_jobs_[server_id]));
653 active_jobs_.erase(server_id);
657 void QuicStreamFactory::set_require_confirmation(bool require_confirmation) {
658 require_confirmation_ = require_confirmation;
659 if (http_server_properties_ && (!(local_address_ == IPEndPoint()))) {
660 http_server_properties_->SetSupportsQuic(!require_confirmation,
661 local_address_.address());
665 int QuicStreamFactory::Create(const HostPortPair& host_port_pair,
666 bool is_https,
667 PrivacyMode privacy_mode,
668 int cert_verify_flags,
669 base::StringPiece origin_host,
670 base::StringPiece method,
671 const BoundNetLog& net_log,
672 QuicStreamRequest* request) {
673 QuicServerId server_id(host_port_pair, is_https, privacy_mode);
674 SessionMap::iterator it = active_sessions_.find(server_id);
675 if (it != active_sessions_.end()) {
676 QuicChromiumClientSession* session = it->second;
677 if (!session->CanPool(origin_host.as_string(), privacy_mode))
678 return ERR_ALTERNATIVE_CERT_NOT_VALID_FOR_ORIGIN;
679 request->set_stream(CreateFromSession(session));
680 return OK;
683 if (HasActiveJob(server_id)) {
684 active_requests_[request] = server_id;
685 job_requests_map_[server_id].insert(request);
686 return ERR_IO_PENDING;
689 // TODO(rtenneti): |task_runner_| is used by the Job. Initialize task_runner_
690 // in the constructor after WebRequestActionWithThreadsTest.* tests are fixed.
691 if (!task_runner_)
692 task_runner_ = base::ThreadTaskRunnerHandle::Get().get();
694 QuicServerInfo* quic_server_info = nullptr;
695 if (quic_server_info_factory_) {
696 bool load_from_disk_cache = !disable_disk_cache_;
697 if (http_server_properties_) {
698 const AlternativeServiceMap& alternative_service_map =
699 http_server_properties_->alternative_service_map();
700 AlternativeServiceMap::const_iterator map_it =
701 alternative_service_map.Peek(server_id.host_port_pair());
702 if (map_it != alternative_service_map.end()) {
703 const AlternativeServiceInfoVector& alternative_service_info_vector =
704 map_it->second;
705 AlternativeServiceInfoVector::const_iterator it;
706 for (it = alternative_service_info_vector.begin();
707 it != alternative_service_info_vector.end(); ++it) {
708 if (it->alternative_service.protocol == QUIC)
709 break;
711 // If there is no entry for QUIC, consider that as a new server and
712 // don't wait for Cache thread to load the data for that server.
713 if (it == alternative_service_info_vector.end())
714 load_from_disk_cache = false;
717 if (load_from_disk_cache && CryptoConfigCacheIsEmpty(server_id)) {
718 quic_server_info = quic_server_info_factory_->GetForServer(server_id);
722 bool server_and_origin_have_same_host = host_port_pair.host() == origin_host;
723 scoped_ptr<Job> job(new Job(this, host_resolver_, host_port_pair,
724 server_and_origin_have_same_host, is_https,
725 WasQuicRecentlyBroken(server_id), privacy_mode,
726 cert_verify_flags, method == "POST" /* is_post */,
727 quic_server_info, net_log));
728 int rv = job->Run(base::Bind(&QuicStreamFactory::OnJobComplete,
729 base::Unretained(this), job.get()));
730 if (rv == ERR_IO_PENDING) {
731 active_requests_[request] = server_id;
732 job_requests_map_[server_id].insert(request);
733 active_jobs_[server_id].insert(job.release());
734 return rv;
736 if (rv == OK) {
737 it = active_sessions_.find(server_id);
738 DCHECK(it != active_sessions_.end());
739 QuicChromiumClientSession* session = it->second;
740 if (!session->CanPool(origin_host.as_string(), privacy_mode))
741 return ERR_ALTERNATIVE_CERT_NOT_VALID_FOR_ORIGIN;
742 request->set_stream(CreateFromSession(session));
744 return rv;
747 void QuicStreamFactory::CreateAuxilaryJob(const QuicServerId server_id,
748 int cert_verify_flags,
749 bool server_and_origin_have_same_host,
750 bool is_post,
751 const BoundNetLog& net_log) {
752 Job* aux_job =
753 new Job(this, host_resolver_, server_id.host_port_pair(),
754 server_and_origin_have_same_host, server_id.is_https(),
755 WasQuicRecentlyBroken(server_id), server_id.privacy_mode(),
756 cert_verify_flags, is_post, nullptr, net_log);
757 active_jobs_[server_id].insert(aux_job);
758 task_runner_->PostTask(FROM_HERE,
759 base::Bind(&QuicStreamFactory::Job::RunAuxilaryJob,
760 aux_job->GetWeakPtr()));
763 bool QuicStreamFactory::OnResolution(
764 const QuicServerId& server_id,
765 const AddressList& address_list) {
766 DCHECK(!HasActiveSession(server_id));
767 if (disable_connection_pooling_) {
768 return false;
770 for (const IPEndPoint& address : address_list) {
771 const IpAliasKey ip_alias_key(address, server_id.is_https());
772 if (!ContainsKey(ip_aliases_, ip_alias_key))
773 continue;
775 const SessionSet& sessions = ip_aliases_[ip_alias_key];
776 for (QuicChromiumClientSession* session : sessions) {
777 if (!session->CanPool(server_id.host(), server_id.privacy_mode()))
778 continue;
779 active_sessions_[server_id] = session;
780 session_aliases_[session].insert(server_id);
781 return true;
784 return false;
787 void QuicStreamFactory::OnJobComplete(Job* job, int rv) {
788 QuicServerId server_id = job->server_id();
789 if (rv != OK) {
790 JobSet* jobs = &(active_jobs_[server_id]);
791 if (jobs->size() > 1) {
792 // If there is another pending job, then we can delete this job and let
793 // the other job handle the request.
794 job->Cancel();
795 jobs->erase(job);
796 delete job;
797 return;
801 if (rv == OK) {
802 if (!always_require_handshake_confirmation_)
803 set_require_confirmation(false);
805 // Create all the streams, but do not notify them yet.
806 SessionMap::iterator session_it = active_sessions_.find(server_id);
807 for (RequestSet::iterator request_it = job_requests_map_[server_id].begin();
808 request_it != job_requests_map_[server_id].end();) {
809 DCHECK(session_it != active_sessions_.end());
810 QuicChromiumClientSession* session = session_it->second;
811 QuicStreamRequest* request = *request_it;
812 if (!session->CanPool(request->origin_host(), request->privacy_mode())) {
813 RequestSet::iterator old_request_it = request_it;
814 ++request_it;
815 // Remove request from containers so that OnRequestComplete() is not
816 // called later again on the same request.
817 job_requests_map_[server_id].erase(old_request_it);
818 active_requests_.erase(request);
819 // Notify request of certificate error.
820 request->OnRequestComplete(ERR_ALTERNATIVE_CERT_NOT_VALID_FOR_ORIGIN);
821 continue;
823 request->set_stream(CreateFromSession(session));
824 ++request_it;
828 while (!job_requests_map_[server_id].empty()) {
829 RequestSet::iterator it = job_requests_map_[server_id].begin();
830 QuicStreamRequest* request = *it;
831 job_requests_map_[server_id].erase(it);
832 active_requests_.erase(request);
833 // Even though we're invoking callbacks here, we don't need to worry
834 // about |this| being deleted, because the factory is owned by the
835 // profile which can not be deleted via callbacks.
836 request->OnRequestComplete(rv);
839 for (Job* other_job : active_jobs_[server_id]) {
840 if (other_job != job)
841 other_job->Cancel();
844 STLDeleteElements(&(active_jobs_[server_id]));
845 active_jobs_.erase(server_id);
846 job_requests_map_.erase(server_id);
849 scoped_ptr<QuicHttpStream> QuicStreamFactory::CreateFromSession(
850 QuicChromiumClientSession* session) {
851 return scoped_ptr<QuicHttpStream>(new QuicHttpStream(session->GetWeakPtr()));
854 QuicChromiumClientSession::QuicDisabledReason
855 QuicStreamFactory::QuicDisabledReason(uint16 port) const {
856 if (max_number_of_lossy_connections_ > 0 &&
857 number_of_lossy_connections_.find(port) !=
858 number_of_lossy_connections_.end() &&
859 number_of_lossy_connections_.at(port) >=
860 max_number_of_lossy_connections_) {
861 return QuicChromiumClientSession::QUIC_DISABLED_BAD_PACKET_LOSS_RATE;
863 if (threshold_public_resets_post_handshake_ > 0 &&
864 num_public_resets_post_handshake_ >=
865 threshold_public_resets_post_handshake_) {
866 return QuicChromiumClientSession::QUIC_DISABLED_PUBLIC_RESET_POST_HANDSHAKE;
868 if (threshold_timeouts_with_open_streams_ > 0 &&
869 num_timeouts_with_open_streams_ >=
870 threshold_timeouts_with_open_streams_) {
871 return QuicChromiumClientSession::QUIC_DISABLED_TIMEOUT_WITH_OPEN_STREAMS;
873 return QuicChromiumClientSession::QUIC_DISABLED_NOT;
876 const char* QuicStreamFactory::QuicDisabledReasonString() const {
877 // TODO(ckrasic) - better solution for port/lossy connections?
878 const uint16 port = 443;
879 switch (QuicDisabledReason(port)) {
880 case QuicChromiumClientSession::QUIC_DISABLED_BAD_PACKET_LOSS_RATE:
881 return "Bad packet loss rate.";
882 case QuicChromiumClientSession::QUIC_DISABLED_PUBLIC_RESET_POST_HANDSHAKE:
883 return "Public resets after successful handshakes.";
884 case QuicChromiumClientSession::QUIC_DISABLED_TIMEOUT_WITH_OPEN_STREAMS:
885 return "Connection timeouts with streams open.";
886 default:
887 return "";
891 bool QuicStreamFactory::IsQuicDisabled(uint16 port) {
892 return QuicDisabledReason(port) !=
893 QuicChromiumClientSession::QUIC_DISABLED_NOT;
896 bool QuicStreamFactory::OnHandshakeConfirmed(QuicChromiumClientSession* session,
897 float packet_loss_rate) {
898 DCHECK(session);
899 uint16 port = session->server_id().port();
900 if (packet_loss_rate < packet_loss_threshold_) {
901 number_of_lossy_connections_[port] = 0;
902 return false;
905 if (http_server_properties_) {
906 // We mark it as recently broken, which means that 0-RTT will be disabled
907 // but we'll still race.
908 http_server_properties_->MarkAlternativeServiceRecentlyBroken(
909 AlternativeService(QUIC, session->server_id().host(), port));
912 bool was_quic_disabled = IsQuicDisabled(port);
913 ++number_of_lossy_connections_[port];
915 // Collect data for port 443 for packet loss events.
916 if (port == 443 && max_number_of_lossy_connections_ > 0) {
917 UMA_HISTOGRAM_SPARSE_SLOWLY(
918 base::StringPrintf("Net.QuicStreamFactory.BadPacketLossEvents%d",
919 max_number_of_lossy_connections_),
920 std::min(number_of_lossy_connections_[port],
921 max_number_of_lossy_connections_));
924 bool is_quic_disabled = IsQuicDisabled(port);
925 if (is_quic_disabled) {
926 // Close QUIC connection if Quic is disabled for this port.
927 session->CloseSessionOnErrorAndNotifyFactoryLater(
928 ERR_ABORTED, QUIC_BAD_PACKET_LOSS_RATE);
930 // If this bad packet loss rate disabled the QUIC, then record it.
931 if (!was_quic_disabled)
932 UMA_HISTOGRAM_SPARSE_SLOWLY("Net.QuicStreamFactory.QuicIsDisabled", port);
934 return is_quic_disabled;
937 void QuicStreamFactory::OnIdleSession(QuicChromiumClientSession* session) {}
939 void QuicStreamFactory::OnSessionGoingAway(QuicChromiumClientSession* session) {
940 const AliasSet& aliases = session_aliases_[session];
941 for (AliasSet::const_iterator it = aliases.begin(); it != aliases.end();
942 ++it) {
943 DCHECK(active_sessions_.count(*it));
944 DCHECK_EQ(session, active_sessions_[*it]);
945 // Track sessions which have recently gone away so that we can disable
946 // port suggestions.
947 if (session->goaway_received()) {
948 gone_away_aliases_.insert(*it);
951 active_sessions_.erase(*it);
952 ProcessGoingAwaySession(session, *it, true);
954 ProcessGoingAwaySession(session, all_sessions_[session], false);
955 if (!aliases.empty()) {
956 const IpAliasKey ip_alias_key(session->connection()->peer_address(),
957 aliases.begin()->is_https());
958 ip_aliases_[ip_alias_key].erase(session);
959 if (ip_aliases_[ip_alias_key].empty()) {
960 ip_aliases_.erase(ip_alias_key);
963 session_aliases_.erase(session);
966 void QuicStreamFactory::MaybeDisableQuic(QuicChromiumClientSession* session) {
967 DCHECK(session);
968 uint16 port = session->server_id().port();
969 if (IsQuicDisabled(port))
970 return;
972 // Expire the oldest disabled_reason if appropriate. This enforces that we
973 // only consider the max_disabled_reasons_ most recent sessions.
974 QuicChromiumClientSession::QuicDisabledReason disabled_reason;
975 if (static_cast<int>(disabled_reasons_.size()) == max_disabled_reasons_) {
976 disabled_reason = disabled_reasons_.front();
977 disabled_reasons_.pop_front();
978 if (disabled_reason ==
979 QuicChromiumClientSession::QUIC_DISABLED_PUBLIC_RESET_POST_HANDSHAKE) {
980 --num_public_resets_post_handshake_;
981 } else if (disabled_reason == QuicChromiumClientSession::
982 QUIC_DISABLED_TIMEOUT_WITH_OPEN_STREAMS) {
983 --num_timeouts_with_open_streams_;
986 disabled_reason = session->disabled_reason();
987 disabled_reasons_.push_back(disabled_reason);
988 if (disabled_reason ==
989 QuicChromiumClientSession::QUIC_DISABLED_PUBLIC_RESET_POST_HANDSHAKE) {
990 ++num_public_resets_post_handshake_;
991 } else if (disabled_reason == QuicChromiumClientSession::
992 QUIC_DISABLED_TIMEOUT_WITH_OPEN_STREAMS) {
993 ++num_timeouts_with_open_streams_;
995 if (num_timeouts_with_open_streams_ > max_timeouts_with_open_streams_) {
996 max_timeouts_with_open_streams_ = num_timeouts_with_open_streams_;
997 UMA_HISTOGRAM_CUSTOM_COUNTS("Net.QuicStreamFactory.TimeoutsWithOpenStreams",
998 num_timeouts_with_open_streams_, 0, 20, 10);
1001 if (num_public_resets_post_handshake_ > max_public_resets_post_handshake_) {
1002 max_public_resets_post_handshake_ = num_public_resets_post_handshake_;
1003 UMA_HISTOGRAM_CUSTOM_COUNTS(
1004 "Net.QuicStreamFactory.PublicResetsPostHandshake",
1005 num_public_resets_post_handshake_, 0, 20, 10);
1008 if (IsQuicDisabled(port)) {
1009 if (disabled_reason ==
1010 QuicChromiumClientSession::QUIC_DISABLED_PUBLIC_RESET_POST_HANDSHAKE) {
1011 session->CloseSessionOnErrorAndNotifyFactoryLater(
1012 ERR_ABORTED, QUIC_PUBLIC_RESETS_POST_HANDSHAKE);
1013 } else if (disabled_reason == QuicChromiumClientSession::
1014 QUIC_DISABLED_TIMEOUT_WITH_OPEN_STREAMS) {
1015 session->CloseSessionOnErrorAndNotifyFactoryLater(
1016 ERR_ABORTED, QUIC_TIMEOUTS_WITH_OPEN_STREAMS);
1018 UMA_HISTOGRAM_ENUMERATION("Net.QuicStreamFactory.DisabledReasons",
1019 disabled_reason,
1020 QuicChromiumClientSession::QUIC_DISABLED_MAX);
1024 void QuicStreamFactory::OnSessionClosed(QuicChromiumClientSession* session) {
1025 DCHECK_EQ(0u, session->GetNumOpenStreams());
1026 MaybeDisableQuic(session);
1027 OnSessionGoingAway(session);
1028 delete session;
1029 all_sessions_.erase(session);
1032 void QuicStreamFactory::OnSessionConnectTimeout(
1033 QuicChromiumClientSession* session) {
1034 const AliasSet& aliases = session_aliases_[session];
1035 for (AliasSet::const_iterator it = aliases.begin(); it != aliases.end();
1036 ++it) {
1037 DCHECK(active_sessions_.count(*it));
1038 DCHECK_EQ(session, active_sessions_[*it]);
1039 active_sessions_.erase(*it);
1042 if (aliases.empty()) {
1043 return;
1046 const IpAliasKey ip_alias_key(session->connection()->peer_address(),
1047 aliases.begin()->is_https());
1048 ip_aliases_[ip_alias_key].erase(session);
1049 if (ip_aliases_[ip_alias_key].empty()) {
1050 ip_aliases_.erase(ip_alias_key);
1052 QuicServerId server_id = *aliases.begin();
1053 session_aliases_.erase(session);
1054 Job* job = new Job(this, host_resolver_, session, server_id);
1055 active_jobs_[server_id].insert(job);
1056 int rv = job->Run(base::Bind(&QuicStreamFactory::OnJobComplete,
1057 base::Unretained(this), job));
1058 DCHECK_EQ(ERR_IO_PENDING, rv);
1061 void QuicStreamFactory::CancelRequest(QuicStreamRequest* request) {
1062 DCHECK(ContainsKey(active_requests_, request));
1063 QuicServerId server_id = active_requests_[request];
1064 job_requests_map_[server_id].erase(request);
1065 active_requests_.erase(request);
1068 void QuicStreamFactory::CloseAllSessions(int error) {
1069 while (!active_sessions_.empty()) {
1070 size_t initial_size = active_sessions_.size();
1071 active_sessions_.begin()->second->CloseSessionOnError(error,
1072 QUIC_INTERNAL_ERROR);
1073 DCHECK_NE(initial_size, active_sessions_.size());
1075 while (!all_sessions_.empty()) {
1076 size_t initial_size = all_sessions_.size();
1077 all_sessions_.begin()->first->CloseSessionOnError(error,
1078 QUIC_INTERNAL_ERROR);
1079 DCHECK_NE(initial_size, all_sessions_.size());
1081 DCHECK(all_sessions_.empty());
1084 scoped_ptr<base::Value> QuicStreamFactory::QuicStreamFactoryInfoToValue()
1085 const {
1086 scoped_ptr<base::ListValue> list(new base::ListValue());
1088 for (SessionMap::const_iterator it = active_sessions_.begin();
1089 it != active_sessions_.end(); ++it) {
1090 const QuicServerId& server_id = it->first;
1091 QuicChromiumClientSession* session = it->second;
1092 const AliasSet& aliases = session_aliases_.find(session)->second;
1093 // Only add a session to the list once.
1094 if (server_id == *aliases.begin()) {
1095 std::set<HostPortPair> hosts;
1096 for (AliasSet::const_iterator alias_it = aliases.begin();
1097 alias_it != aliases.end(); ++alias_it) {
1098 hosts.insert(alias_it->host_port_pair());
1100 list->Append(session->GetInfoAsValue(hosts));
1103 return list.Pass();
1106 void QuicStreamFactory::ClearCachedStatesInCryptoConfig() {
1107 crypto_config_.ClearCachedStates();
1110 void QuicStreamFactory::OnIPAddressChanged() {
1111 CloseAllSessions(ERR_NETWORK_CHANGED);
1112 set_require_confirmation(true);
1115 void QuicStreamFactory::OnCertAdded(const X509Certificate* cert) {
1116 CloseAllSessions(ERR_CERT_DATABASE_CHANGED);
1119 void QuicStreamFactory::OnCACertChanged(const X509Certificate* cert) {
1120 // We should flush the sessions if we removed trust from a
1121 // cert, because a previously trusted server may have become
1122 // untrusted.
1124 // We should not flush the sessions if we added trust to a cert.
1126 // Since the OnCACertChanged method doesn't tell us what
1127 // kind of change it is, we have to flush the socket
1128 // pools to be safe.
1129 CloseAllSessions(ERR_CERT_DATABASE_CHANGED);
1132 bool QuicStreamFactory::HasActiveSession(
1133 const QuicServerId& server_id) const {
1134 return ContainsKey(active_sessions_, server_id);
1137 bool QuicStreamFactory::HasActiveJob(const QuicServerId& key) const {
1138 return ContainsKey(active_jobs_, key);
1141 int QuicStreamFactory::CreateSession(const QuicServerId& server_id,
1142 int cert_verify_flags,
1143 scoped_ptr<QuicServerInfo> server_info,
1144 const AddressList& address_list,
1145 base::TimeTicks dns_resolution_end_time,
1146 const BoundNetLog& net_log,
1147 QuicChromiumClientSession** session) {
1148 bool enable_port_selection = enable_port_selection_;
1149 if (enable_port_selection &&
1150 ContainsKey(gone_away_aliases_, server_id)) {
1151 // Disable port selection when the server is going away.
1152 // There is no point in trying to return to the same server, if
1153 // that server is no longer handling requests.
1154 enable_port_selection = false;
1155 gone_away_aliases_.erase(server_id);
1158 QuicConnectionId connection_id = random_generator_->RandUint64();
1159 IPEndPoint addr = *address_list.begin();
1160 scoped_refptr<PortSuggester> port_suggester =
1161 new PortSuggester(server_id.host_port_pair(), port_seed_);
1162 DatagramSocket::BindType bind_type = enable_port_selection ?
1163 DatagramSocket::RANDOM_BIND : // Use our callback.
1164 DatagramSocket::DEFAULT_BIND; // Use OS to randomize.
1165 scoped_ptr<DatagramClientSocket> socket(
1166 client_socket_factory_->CreateDatagramClientSocket(
1167 bind_type,
1168 base::Bind(&PortSuggester::SuggestPort, port_suggester),
1169 net_log.net_log(), net_log.source()));
1171 if (enable_non_blocking_io_ &&
1172 client_socket_factory_ == ClientSocketFactory::GetDefaultFactory()) {
1173 #if defined(OS_WIN)
1174 static_cast<UDPClientSocket*>(socket.get())->UseNonBlockingIO();
1175 #endif
1178 int rv = socket->Connect(addr);
1180 if (rv != OK) {
1181 HistogramCreateSessionFailure(CREATION_ERROR_CONNECTING_SOCKET);
1182 return rv;
1184 UMA_HISTOGRAM_COUNTS("Net.QuicEphemeralPortsSuggested",
1185 port_suggester->call_count());
1186 if (enable_port_selection) {
1187 DCHECK_LE(1u, port_suggester->call_count());
1188 } else {
1189 DCHECK_EQ(0u, port_suggester->call_count());
1192 rv = socket->SetReceiveBufferSize(socket_receive_buffer_size_);
1193 if (rv != OK) {
1194 HistogramCreateSessionFailure(CREATION_ERROR_SETTING_RECEIVE_BUFFER);
1195 return rv;
1197 // Set a buffer large enough to contain the initial CWND's worth of packet
1198 // to work around the problem with CHLO packets being sent out with the
1199 // wrong encryption level, when the send buffer is full.
1200 rv = socket->SetSendBufferSize(kMaxPacketSize * 20);
1201 if (rv != OK) {
1202 HistogramCreateSessionFailure(CREATION_ERROR_SETTING_SEND_BUFFER);
1203 return rv;
1206 socket->GetLocalAddress(&local_address_);
1207 if (check_persisted_supports_quic_ && http_server_properties_) {
1208 check_persisted_supports_quic_ = false;
1209 IPAddressNumber last_address;
1210 if (http_server_properties_->GetSupportsQuic(&last_address) &&
1211 last_address == local_address_.address()) {
1212 require_confirmation_ = false;
1216 DefaultPacketWriterFactory packet_writer_factory(socket.get());
1218 if (!helper_.get()) {
1219 helper_.reset(
1220 new QuicConnectionHelper(base::ThreadTaskRunnerHandle::Get().get(),
1221 clock_.get(), random_generator_));
1224 QuicConnection* connection = new QuicConnection(
1225 connection_id, addr, helper_.get(), packet_writer_factory,
1226 true /* owns_writer */, Perspective::IS_CLIENT, server_id.is_https(),
1227 supported_versions_);
1228 connection->set_max_packet_length(max_packet_length_);
1230 InitializeCachedStateInCryptoConfig(server_id, server_info);
1232 QuicConfig config = config_;
1233 config.SetSocketReceiveBufferToSend(socket_receive_buffer_size_);
1234 config.set_max_undecryptable_packets(kMaxUndecryptablePackets);
1235 config.SetInitialSessionFlowControlWindowToSend(
1236 kQuicSessionMaxRecvWindowSize);
1237 config.SetInitialStreamFlowControlWindowToSend(kQuicStreamMaxRecvWindowSize);
1238 int64 srtt = GetServerNetworkStatsSmoothedRttInMicroseconds(server_id);
1239 if (srtt > 0)
1240 config.SetInitialRoundTripTimeUsToSend(static_cast<uint32>(srtt));
1241 config.SetBytesForConnectionIdToSend(0);
1243 if (quic_server_info_factory_ && !server_info) {
1244 // Start the disk cache loading so that we can persist the newer QUIC server
1245 // information and/or inform the disk cache that we have reused
1246 // |server_info|.
1247 server_info.reset(quic_server_info_factory_->GetForServer(server_id));
1248 server_info->Start();
1251 *session = new QuicChromiumClientSession(
1252 connection, socket.Pass(), this, quic_crypto_client_stream_factory_,
1253 transport_security_state_, server_info.Pass(), server_id,
1254 cert_verify_flags, config, &crypto_config_,
1255 network_connection_.GetDescription(), dns_resolution_end_time,
1256 base::ThreadTaskRunnerHandle::Get().get(), net_log.net_log());
1258 all_sessions_[*session] = server_id; // owning pointer
1260 (*session)->Initialize();
1261 bool closed_during_initialize =
1262 !ContainsKey(all_sessions_, *session) ||
1263 !(*session)->connection()->connected();
1264 UMA_HISTOGRAM_BOOLEAN("Net.QuicSession.ClosedDuringInitializeSession",
1265 closed_during_initialize);
1266 if (closed_during_initialize) {
1267 DLOG(DFATAL) << "Session closed during initialize";
1268 *session = nullptr;
1269 return ERR_CONNECTION_CLOSED;
1271 return OK;
1274 void QuicStreamFactory::ActivateSession(const QuicServerId& server_id,
1275 QuicChromiumClientSession* session) {
1276 DCHECK(!HasActiveSession(server_id));
1277 UMA_HISTOGRAM_COUNTS("Net.QuicActiveSessions", active_sessions_.size());
1278 active_sessions_[server_id] = session;
1279 session_aliases_[session].insert(server_id);
1280 const IpAliasKey ip_alias_key(session->connection()->peer_address(),
1281 server_id.is_https());
1282 DCHECK(!ContainsKey(ip_aliases_[ip_alias_key], session));
1283 ip_aliases_[ip_alias_key].insert(session);
1286 int64 QuicStreamFactory::GetServerNetworkStatsSmoothedRttInMicroseconds(
1287 const QuicServerId& server_id) const {
1288 if (!http_server_properties_)
1289 return 0;
1290 const ServerNetworkStats* stats =
1291 http_server_properties_->GetServerNetworkStats(
1292 server_id.host_port_pair());
1293 if (stats == nullptr)
1294 return 0;
1295 return stats->srtt.InMicroseconds();
1298 bool QuicStreamFactory::WasQuicRecentlyBroken(
1299 const QuicServerId& server_id) const {
1300 if (!http_server_properties_)
1301 return false;
1302 const AlternativeService alternative_service(QUIC,
1303 server_id.host_port_pair());
1304 return http_server_properties_->WasAlternativeServiceRecentlyBroken(
1305 alternative_service);
1308 bool QuicStreamFactory::CryptoConfigCacheIsEmpty(
1309 const QuicServerId& server_id) {
1310 QuicCryptoClientConfig::CachedState* cached =
1311 crypto_config_.LookupOrCreate(server_id);
1312 return cached->IsEmpty();
1315 void QuicStreamFactory::InitializeCachedStateInCryptoConfig(
1316 const QuicServerId& server_id,
1317 const scoped_ptr<QuicServerInfo>& server_info) {
1318 // |server_info| will be NULL, if a non-empty server config already exists in
1319 // the memory cache. This is a minor optimization to avoid LookupOrCreate.
1320 if (!server_info)
1321 return;
1323 QuicCryptoClientConfig::CachedState* cached =
1324 crypto_config_.LookupOrCreate(server_id);
1325 if (!cached->IsEmpty())
1326 return;
1328 if (http_server_properties_) {
1329 if (quic_supported_servers_at_startup_.empty()) {
1330 for (const std::pair<const HostPortPair, AlternativeServiceInfoVector>&
1331 key_value : http_server_properties_->alternative_service_map()) {
1332 for (const AlternativeServiceInfo& alternative_service_info :
1333 key_value.second) {
1334 if (alternative_service_info.alternative_service.protocol == QUIC) {
1335 quic_supported_servers_at_startup_.insert(key_value.first);
1336 break;
1342 // TODO(rtenneti): Delete the following histogram after collecting stats.
1343 // If the AlternativeServiceMap contained an entry for this host, check if
1344 // the disk cache contained an entry for it.
1345 if (ContainsKey(quic_supported_servers_at_startup_,
1346 server_id.host_port_pair())) {
1347 UMA_HISTOGRAM_BOOLEAN(
1348 "Net.QuicServerInfo.ExpectConfigMissingFromDiskCache",
1349 server_info->state().server_config.empty());
1353 if (!cached->Initialize(server_info->state().server_config,
1354 server_info->state().source_address_token,
1355 server_info->state().certs,
1356 server_info->state().server_config_sig,
1357 clock_->WallNow()))
1358 return;
1360 if (!server_id.is_https()) {
1361 // Don't check the certificates for insecure QUIC.
1362 cached->SetProofValid();
1366 void QuicStreamFactory::ProcessGoingAwaySession(
1367 QuicChromiumClientSession* session,
1368 const QuicServerId& server_id,
1369 bool session_was_active) {
1370 if (!http_server_properties_)
1371 return;
1373 const QuicConnectionStats& stats = session->connection()->GetStats();
1374 const AlternativeService alternative_service(QUIC,
1375 server_id.host_port_pair());
1376 if (session->IsCryptoHandshakeConfirmed()) {
1377 http_server_properties_->ConfirmAlternativeService(alternative_service);
1378 ServerNetworkStats network_stats;
1379 network_stats.srtt = base::TimeDelta::FromMicroseconds(stats.srtt_us);
1380 network_stats.bandwidth_estimate = stats.estimated_bandwidth;
1381 http_server_properties_->SetServerNetworkStats(server_id.host_port_pair(),
1382 network_stats);
1383 return;
1386 UMA_HISTOGRAM_COUNTS("Net.QuicHandshakeNotConfirmedNumPacketsReceived",
1387 stats.packets_received);
1389 if (!session_was_active)
1390 return;
1392 // TODO(rch): In the special case where the session has received no
1393 // packets from the peer, we should consider blacklisting this
1394 // differently so that we still race TCP but we don't consider the
1395 // session connected until the handshake has been confirmed.
1396 HistogramBrokenAlternateProtocolLocation(
1397 BROKEN_ALTERNATE_PROTOCOL_LOCATION_QUIC_STREAM_FACTORY);
1399 // Since the session was active, there's no longer an
1400 // HttpStreamFactoryImpl::Job running which can mark it broken, unless the TCP
1401 // job also fails. So to avoid not using QUIC when we otherwise could, we mark
1402 // it as recently broken, which means that 0-RTT will be disabled but we'll
1403 // still race.
1404 http_server_properties_->MarkAlternativeServiceRecentlyBroken(
1405 alternative_service);
1408 } // namespace net