Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(28)

Side by Side Diff: net/quic/quic_stream_factory.cc

Issue 992733002: Remove //net (except for Android test stuff) and sdch (Closed) Base URL: git@github.com:domokit/mojo.git@master
Patch Set: Created 5 years, 9 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
« no previous file with comments | « net/quic/quic_stream_factory.h ('k') | net/quic/quic_stream_factory_test.cc » ('j') | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
(Empty)
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.
4
5 #include "net/quic/quic_stream_factory.h"
6
7 #include <set>
8
9 #include "base/cpu.h"
10 #include "base/message_loop/message_loop.h"
11 #include "base/message_loop/message_loop_proxy.h"
12 #include "base/metrics/field_trial.h"
13 #include "base/metrics/histogram.h"
14 #include "base/profiler/scoped_tracker.h"
15 #include "base/rand_util.h"
16 #include "base/stl_util.h"
17 #include "base/strings/string_util.h"
18 #include "base/values.h"
19 #include "net/base/net_errors.h"
20 #include "net/cert/cert_verifier.h"
21 #include "net/dns/host_resolver.h"
22 #include "net/dns/single_request_host_resolver.h"
23 #include "net/http/http_server_properties.h"
24 #include "net/quic/crypto/channel_id_chromium.h"
25 #include "net/quic/crypto/proof_verifier_chromium.h"
26 #include "net/quic/crypto/quic_random.h"
27 #include "net/quic/crypto/quic_server_info.h"
28 #include "net/quic/port_suggester.h"
29 #include "net/quic/quic_client_session.h"
30 #include "net/quic/quic_clock.h"
31 #include "net/quic/quic_connection.h"
32 #include "net/quic/quic_connection_helper.h"
33 #include "net/quic/quic_crypto_client_stream_factory.h"
34 #include "net/quic/quic_default_packet_writer.h"
35 #include "net/quic/quic_flags.h"
36 #include "net/quic/quic_http_stream.h"
37 #include "net/quic/quic_protocol.h"
38 #include "net/quic/quic_server_id.h"
39 #include "net/socket/client_socket_factory.h"
40
41 #if defined(OS_WIN)
42 #include "base/win/windows_version.h"
43 #endif
44
45 namespace net {
46
47 namespace {
48
49 enum CreateSessionFailure {
50 CREATION_ERROR_CONNECTING_SOCKET,
51 CREATION_ERROR_SETTING_RECEIVE_BUFFER,
52 CREATION_ERROR_SETTING_SEND_BUFFER,
53 CREATION_ERROR_MAX
54 };
55
56 // When a connection is idle for 30 seconds it will be closed.
57 const int kIdleConnectionTimeoutSeconds = 30;
58
59 // The initial receive window size for both streams and sessions.
60 const int32 kInitialReceiveWindowSize = 10 * 1024 * 1024; // 10MB
61
62 // Set the maximum number of undecryptable packets the connection will store.
63 const int32 kMaxUndecryptablePackets = 100;
64
65 void HistogramCreateSessionFailure(enum CreateSessionFailure error) {
66 UMA_HISTOGRAM_ENUMERATION("Net.QuicSession.CreationError", error,
67 CREATION_ERROR_MAX);
68 }
69
70 bool IsEcdsaSupported() {
71 #if defined(OS_WIN)
72 if (base::win::GetVersion() < base::win::VERSION_VISTA)
73 return false;
74 #endif
75
76 return true;
77 }
78
79 QuicConfig InitializeQuicConfig(const QuicTagVector& connection_options) {
80 QuicConfig config;
81 config.SetIdleConnectionStateLifetime(
82 QuicTime::Delta::FromSeconds(kIdleConnectionTimeoutSeconds),
83 QuicTime::Delta::FromSeconds(kIdleConnectionTimeoutSeconds));
84 config.SetConnectionOptionsToSend(connection_options);
85 return config;
86 }
87
88 class DefaultPacketWriterFactory : public QuicConnection::PacketWriterFactory {
89 public:
90 explicit DefaultPacketWriterFactory(DatagramClientSocket* socket)
91 : socket_(socket) {}
92 ~DefaultPacketWriterFactory() override {}
93
94 QuicPacketWriter* Create(QuicConnection* connection) const override;
95
96 private:
97 DatagramClientSocket* socket_;
98 };
99
100 QuicPacketWriter* DefaultPacketWriterFactory::Create(
101 QuicConnection* connection) const {
102 scoped_ptr<QuicDefaultPacketWriter> writer(
103 new QuicDefaultPacketWriter(socket_));
104 writer->SetConnection(connection);
105 return writer.release();
106 }
107
108 } // namespace
109
110 QuicStreamFactory::IpAliasKey::IpAliasKey() {}
111
112 QuicStreamFactory::IpAliasKey::IpAliasKey(IPEndPoint ip_endpoint,
113 bool is_https)
114 : ip_endpoint(ip_endpoint),
115 is_https(is_https) {}
116
117 QuicStreamFactory::IpAliasKey::~IpAliasKey() {}
118
119 bool QuicStreamFactory::IpAliasKey::operator<(
120 const QuicStreamFactory::IpAliasKey& other) const {
121 if (!(ip_endpoint == other.ip_endpoint)) {
122 return ip_endpoint < other.ip_endpoint;
123 }
124 return is_https < other.is_https;
125 }
126
127 bool QuicStreamFactory::IpAliasKey::operator==(
128 const QuicStreamFactory::IpAliasKey& other) const {
129 return is_https == other.is_https &&
130 ip_endpoint == other.ip_endpoint;
131 };
132
133 // Responsible for creating a new QUIC session to the specified server, and
134 // for notifying any associated requests when complete.
135 class QuicStreamFactory::Job {
136 public:
137 Job(QuicStreamFactory* factory,
138 HostResolver* host_resolver,
139 const HostPortPair& host_port_pair,
140 bool is_https,
141 bool was_alternate_protocol_recently_broken,
142 PrivacyMode privacy_mode,
143 bool is_post,
144 QuicServerInfo* server_info,
145 const BoundNetLog& net_log);
146
147 // Creates a new job to handle the resumption of for connecting an
148 // existing session.
149 Job(QuicStreamFactory* factory,
150 HostResolver* host_resolver,
151 QuicClientSession* session,
152 QuicServerId server_id);
153
154 ~Job();
155
156 int Run(const CompletionCallback& callback);
157
158 int DoLoop(int rv);
159 int DoResolveHost();
160 int DoResolveHostComplete(int rv);
161 int DoLoadServerInfo();
162 int DoLoadServerInfoComplete(int rv);
163 int DoConnect();
164 int DoResumeConnect();
165 int DoConnectComplete(int rv);
166
167 void OnIOComplete(int rv);
168
169 void RunAuxilaryJob();
170
171 void Cancel();
172
173 void CancelWaitForDataReadyCallback();
174
175 const QuicServerId server_id() const { return server_id_; }
176
177 base::WeakPtr<Job> GetWeakPtr() { return weak_factory_.GetWeakPtr(); }
178
179 private:
180 enum IoState {
181 STATE_NONE,
182 STATE_RESOLVE_HOST,
183 STATE_RESOLVE_HOST_COMPLETE,
184 STATE_LOAD_SERVER_INFO,
185 STATE_LOAD_SERVER_INFO_COMPLETE,
186 STATE_CONNECT,
187 STATE_RESUME_CONNECT,
188 STATE_CONNECT_COMPLETE,
189 };
190 IoState io_state_;
191
192 QuicStreamFactory* factory_;
193 SingleRequestHostResolver host_resolver_;
194 QuicServerId server_id_;
195 bool is_post_;
196 bool was_alternate_protocol_recently_broken_;
197 scoped_ptr<QuicServerInfo> server_info_;
198 bool started_another_job_;
199 const BoundNetLog net_log_;
200 QuicClientSession* session_;
201 CompletionCallback callback_;
202 AddressList address_list_;
203 base::TimeTicks disk_cache_load_start_time_;
204 base::TimeTicks dns_resolution_start_time_;
205 base::WeakPtrFactory<Job> weak_factory_;
206 DISALLOW_COPY_AND_ASSIGN(Job);
207 };
208
209 QuicStreamFactory::Job::Job(QuicStreamFactory* factory,
210 HostResolver* host_resolver,
211 const HostPortPair& host_port_pair,
212 bool is_https,
213 bool was_alternate_protocol_recently_broken,
214 PrivacyMode privacy_mode,
215 bool is_post,
216 QuicServerInfo* server_info,
217 const BoundNetLog& net_log)
218 : io_state_(STATE_RESOLVE_HOST),
219 factory_(factory),
220 host_resolver_(host_resolver),
221 server_id_(host_port_pair, is_https, privacy_mode),
222 is_post_(is_post),
223 was_alternate_protocol_recently_broken_(
224 was_alternate_protocol_recently_broken),
225 server_info_(server_info),
226 started_another_job_(false),
227 net_log_(net_log),
228 session_(nullptr),
229 weak_factory_(this) {
230 }
231
232 QuicStreamFactory::Job::Job(QuicStreamFactory* factory,
233 HostResolver* host_resolver,
234 QuicClientSession* session,
235 QuicServerId server_id)
236 : io_state_(STATE_RESUME_CONNECT),
237 factory_(factory),
238 host_resolver_(host_resolver), // unused
239 server_id_(server_id),
240 is_post_(false), // unused
241 was_alternate_protocol_recently_broken_(false), // unused
242 started_another_job_(false), // unused
243 net_log_(session->net_log()), // unused
244 session_(session),
245 weak_factory_(this) {
246 }
247
248 QuicStreamFactory::Job::~Job() {
249 // If disk cache has a pending WaitForDataReadyCallback, cancel that callback.
250 if (server_info_)
251 server_info_->ResetWaitForDataReadyCallback();
252 }
253
254 int QuicStreamFactory::Job::Run(const CompletionCallback& callback) {
255 int rv = DoLoop(OK);
256 if (rv == ERR_IO_PENDING)
257 callback_ = callback;
258
259 return rv > 0 ? OK : rv;
260 }
261
262 int QuicStreamFactory::Job::DoLoop(int rv) {
263 do {
264 IoState state = io_state_;
265 io_state_ = STATE_NONE;
266 switch (state) {
267 case STATE_RESOLVE_HOST:
268 CHECK_EQ(OK, rv);
269 rv = DoResolveHost();
270 break;
271 case STATE_RESOLVE_HOST_COMPLETE:
272 rv = DoResolveHostComplete(rv);
273 break;
274 case STATE_LOAD_SERVER_INFO:
275 CHECK_EQ(OK, rv);
276 rv = DoLoadServerInfo();
277 break;
278 case STATE_LOAD_SERVER_INFO_COMPLETE:
279 rv = DoLoadServerInfoComplete(rv);
280 break;
281 case STATE_CONNECT:
282 CHECK_EQ(OK, rv);
283 rv = DoConnect();
284 break;
285 case STATE_RESUME_CONNECT:
286 CHECK_EQ(OK, rv);
287 rv = DoResumeConnect();
288 break;
289 case STATE_CONNECT_COMPLETE:
290 rv = DoConnectComplete(rv);
291 break;
292 default:
293 NOTREACHED() << "io_state_: " << io_state_;
294 break;
295 }
296 } while (io_state_ != STATE_NONE && rv != ERR_IO_PENDING);
297 return rv;
298 }
299
300 void QuicStreamFactory::Job::OnIOComplete(int rv) {
301 // TODO(vadimt): Remove ScopedTracker below once crbug.com/422516 is fixed.
302 tracked_objects::ScopedTracker tracking_profile1(
303 FROM_HERE_WITH_EXPLICIT_FUNCTION(
304 "422516 QuicStreamFactory::Job::OnIOComplete1"));
305
306 rv = DoLoop(rv);
307
308 tracked_objects::ScopedTracker tracking_profile2(
309 FROM_HERE_WITH_EXPLICIT_FUNCTION(
310 "422516 QuicStreamFactory::Job::OnIOComplete2"));
311
312 if (rv != ERR_IO_PENDING && !callback_.is_null()) {
313 callback_.Run(rv);
314 }
315 }
316
317 void QuicStreamFactory::Job::RunAuxilaryJob() {
318 int rv = Run(base::Bind(&QuicStreamFactory::OnJobComplete,
319 base::Unretained(factory_), this));
320 if (rv != ERR_IO_PENDING)
321 factory_->OnJobComplete(this, rv);
322 }
323
324 void QuicStreamFactory::Job::Cancel() {
325 callback_.Reset();
326 if (session_)
327 session_->connection()->SendConnectionClose(QUIC_CONNECTION_CANCELLED);
328 }
329
330 void QuicStreamFactory::Job::CancelWaitForDataReadyCallback() {
331 // If we are waiting for WaitForDataReadyCallback, then cancel the callback.
332 if (io_state_ != STATE_LOAD_SERVER_INFO_COMPLETE)
333 return;
334 server_info_->CancelWaitForDataReadyCallback();
335 OnIOComplete(OK);
336 }
337
338 int QuicStreamFactory::Job::DoResolveHost() {
339 // TODO(vadimt): Remove ScopedTracker below once crbug.com/422516 is fixed.
340 tracked_objects::ScopedTracker tracking_profile(
341 FROM_HERE_WITH_EXPLICIT_FUNCTION(
342 "422516 QuicStreamFactory::Job::DoResolveHost"));
343
344 // Start loading the data now, and wait for it after we resolve the host.
345 if (server_info_) {
346 server_info_->Start();
347 }
348
349 io_state_ = STATE_RESOLVE_HOST_COMPLETE;
350 dns_resolution_start_time_ = base::TimeTicks::Now();
351 return host_resolver_.Resolve(
352 HostResolver::RequestInfo(server_id_.host_port_pair()), DEFAULT_PRIORITY,
353 &address_list_,
354 base::Bind(&QuicStreamFactory::Job::OnIOComplete, GetWeakPtr()),
355 net_log_);
356 }
357
358 int QuicStreamFactory::Job::DoResolveHostComplete(int rv) {
359 // TODO(vadimt): Remove ScopedTracker below once crbug.com/422516 is fixed.
360 tracked_objects::ScopedTracker tracking_profile(
361 FROM_HERE_WITH_EXPLICIT_FUNCTION(
362 "422516 QuicStreamFactory::Job::DoResolveHostComplete"));
363
364 UMA_HISTOGRAM_TIMES("Net.QuicSession.HostResolutionTime",
365 base::TimeTicks::Now() - dns_resolution_start_time_);
366 if (rv != OK)
367 return rv;
368
369 DCHECK(!factory_->HasActiveSession(server_id_));
370
371 // Inform the factory of this resolution, which will set up
372 // a session alias, if possible.
373 if (factory_->OnResolution(server_id_, address_list_)) {
374 return OK;
375 }
376
377 if (server_info_)
378 io_state_ = STATE_LOAD_SERVER_INFO;
379 else
380 io_state_ = STATE_CONNECT;
381 return OK;
382 }
383
384 int QuicStreamFactory::Job::DoLoadServerInfo() {
385 // TODO(vadimt): Remove ScopedTracker below once crbug.com/422516 is fixed.
386 tracked_objects::ScopedTracker tracking_profile(
387 FROM_HERE_WITH_EXPLICIT_FUNCTION(
388 "422516 QuicStreamFactory::Job::DoLoadServerInfo"));
389
390 io_state_ = STATE_LOAD_SERVER_INFO_COMPLETE;
391
392 DCHECK(server_info_);
393
394 // To mitigate the effects of disk cache taking too long to load QUIC server
395 // information, set up a timer to cancel WaitForDataReady's callback.
396 int64 load_server_info_timeout_ms = factory_->load_server_info_timeout_ms_;
397 if (factory_->load_server_info_timeout_srtt_multiplier_ > 0) {
398 DCHECK_EQ(0, load_server_info_timeout_ms);
399 load_server_info_timeout_ms =
400 (factory_->load_server_info_timeout_srtt_multiplier_ *
401 factory_->GetServerNetworkStatsSmoothedRttInMicroseconds(server_id_)) /
402 1000;
403 }
404 if (load_server_info_timeout_ms > 0) {
405 factory_->task_runner_->PostDelayedTask(
406 FROM_HERE,
407 base::Bind(&QuicStreamFactory::Job::CancelWaitForDataReadyCallback,
408 GetWeakPtr()),
409 base::TimeDelta::FromMilliseconds(load_server_info_timeout_ms));
410 }
411
412 disk_cache_load_start_time_ = base::TimeTicks::Now();
413 int rv = server_info_->WaitForDataReady(
414 base::Bind(&QuicStreamFactory::Job::OnIOComplete, GetWeakPtr()));
415 if (rv == ERR_IO_PENDING && factory_->enable_connection_racing()) {
416 // If we are waiting to load server config from the disk cache, then start
417 // another job.
418 started_another_job_ = true;
419 factory_->CreateAuxilaryJob(server_id_, is_post_, net_log_);
420 }
421 return rv;
422 }
423
424 int QuicStreamFactory::Job::DoLoadServerInfoComplete(int rv) {
425 // TODO(vadimt): Remove ScopedTracker below once crbug.com/422516 is fixed.
426 tracked_objects::ScopedTracker tracking_profile(
427 FROM_HERE_WITH_EXPLICIT_FUNCTION(
428 "422516 QuicStreamFactory::Job::DoLoadServerInfoComplete"));
429
430 UMA_HISTOGRAM_TIMES("Net.QuicServerInfo.DiskCacheWaitForDataReadyTime",
431 base::TimeTicks::Now() - disk_cache_load_start_time_);
432
433 if (rv != OK)
434 server_info_.reset();
435
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;
444 }
445
446 io_state_ = STATE_CONNECT;
447 return OK;
448 }
449
450 int QuicStreamFactory::Job::DoConnect() {
451 // TODO(vadimt): Remove ScopedTracker below once crbug.com/422516 is fixed.
452 tracked_objects::ScopedTracker tracking_profile(
453 FROM_HERE_WITH_EXPLICIT_FUNCTION(
454 "422516 QuicStreamFactory::Job::DoConnect"));
455
456 io_state_ = STATE_CONNECT_COMPLETE;
457
458 int rv = factory_->CreateSession(server_id_, server_info_.Pass(),
459 address_list_, net_log_, &session_);
460 if (rv != OK) {
461 DCHECK(rv != ERR_IO_PENDING);
462 DCHECK(!session_);
463 return rv;
464 }
465
466 if (!session_->connection()->connected()) {
467 return ERR_CONNECTION_CLOSED;
468 }
469
470 // TODO(vadimt): Remove ScopedTracker below once crbug.com/422516 is fixed.
471 tracked_objects::ScopedTracker tracking_profile1(
472 FROM_HERE_WITH_EXPLICIT_FUNCTION(
473 "422516 QuicStreamFactory::Job::DoConnect1"));
474
475 session_->StartReading();
476 if (!session_->connection()->connected()) {
477 return ERR_QUIC_PROTOCOL_ERROR;
478 }
479 bool require_confirmation =
480 factory_->require_confirmation() || is_post_ ||
481 was_alternate_protocol_recently_broken_;
482
483 // TODO(vadimt): Remove ScopedTracker below once crbug.com/422516 is fixed.
484 tracked_objects::ScopedTracker tracking_profile2(
485 FROM_HERE_WITH_EXPLICIT_FUNCTION(
486 "422516 QuicStreamFactory::Job::DoConnect2"));
487
488 rv = session_->CryptoConnect(
489 require_confirmation,
490 base::Bind(&QuicStreamFactory::Job::OnIOComplete, GetWeakPtr()));
491 return rv;
492 }
493
494 int QuicStreamFactory::Job::DoResumeConnect() {
495 // TODO(vadimt): Remove ScopedTracker below once crbug.com/422516 is fixed.
496 tracked_objects::ScopedTracker tracking_profile(
497 FROM_HERE_WITH_EXPLICIT_FUNCTION(
498 "422516 QuicStreamFactory::Job::DoResumeConnect"));
499
500 io_state_ = STATE_CONNECT_COMPLETE;
501
502 int rv = session_->ResumeCryptoConnect(
503 base::Bind(&QuicStreamFactory::Job::OnIOComplete, GetWeakPtr()));
504
505 return rv;
506 }
507
508 int QuicStreamFactory::Job::DoConnectComplete(int rv) {
509 // TODO(vadimt): Remove ScopedTracker below once crbug.com/422516 is fixed.
510 tracked_objects::ScopedTracker tracking_profile(
511 FROM_HERE_WITH_EXPLICIT_FUNCTION(
512 "422516 QuicStreamFactory::Job::DoConnectComplete"));
513
514 if (rv != OK)
515 return rv;
516
517 DCHECK(!factory_->HasActiveSession(server_id_));
518 // There may well now be an active session for this IP. If so, use the
519 // existing session instead.
520 AddressList address(session_->connection()->peer_address());
521 if (factory_->OnResolution(server_id_, address)) {
522 session_->connection()->SendConnectionClose(QUIC_CONNECTION_IP_POOLED);
523 session_ = nullptr;
524 return OK;
525 }
526
527 factory_->ActivateSession(server_id_, session_);
528
529 return OK;
530 }
531
532 QuicStreamRequest::QuicStreamRequest(QuicStreamFactory* factory)
533 : factory_(factory) {}
534
535 QuicStreamRequest::~QuicStreamRequest() {
536 if (factory_ && !callback_.is_null())
537 factory_->CancelRequest(this);
538 }
539
540 int QuicStreamRequest::Request(const HostPortPair& host_port_pair,
541 bool is_https,
542 PrivacyMode privacy_mode,
543 base::StringPiece method,
544 const BoundNetLog& net_log,
545 const CompletionCallback& callback) {
546 DCHECK(!stream_);
547 DCHECK(callback_.is_null());
548 DCHECK(factory_);
549 int rv = factory_->Create(host_port_pair, is_https, privacy_mode, method,
550 net_log, this);
551 if (rv == ERR_IO_PENDING) {
552 host_port_pair_ = host_port_pair;
553 is_https_ = is_https;
554 net_log_ = net_log;
555 callback_ = callback;
556 } else {
557 factory_ = nullptr;
558 }
559 if (rv == OK)
560 DCHECK(stream_);
561 return rv;
562 }
563
564 void QuicStreamRequest::set_stream(scoped_ptr<QuicHttpStream> stream) {
565 DCHECK(stream);
566 stream_ = stream.Pass();
567 }
568
569 void QuicStreamRequest::OnRequestComplete(int rv) {
570 factory_ = nullptr;
571 callback_.Run(rv);
572 }
573
574 scoped_ptr<QuicHttpStream> QuicStreamRequest::ReleaseStream() {
575 DCHECK(stream_);
576 return stream_.Pass();
577 }
578
579 QuicStreamFactory::QuicStreamFactory(
580 HostResolver* host_resolver,
581 ClientSocketFactory* client_socket_factory,
582 base::WeakPtr<HttpServerProperties> http_server_properties,
583 CertVerifier* cert_verifier,
584 ChannelIDService* channel_id_service,
585 TransportSecurityState* transport_security_state,
586 QuicCryptoClientStreamFactory* quic_crypto_client_stream_factory,
587 QuicRandom* random_generator,
588 QuicClock* clock,
589 size_t max_packet_length,
590 const std::string& user_agent_id,
591 const QuicVersionVector& supported_versions,
592 bool enable_port_selection,
593 bool always_require_handshake_confirmation,
594 bool disable_connection_pooling,
595 int load_server_info_timeout,
596 float load_server_info_timeout_srtt_multiplier,
597 bool enable_truncated_connection_ids,
598 bool enable_connection_racing,
599 const QuicTagVector& connection_options)
600 : require_confirmation_(true),
601 host_resolver_(host_resolver),
602 client_socket_factory_(client_socket_factory),
603 http_server_properties_(http_server_properties),
604 transport_security_state_(transport_security_state),
605 quic_server_info_factory_(nullptr),
606 quic_crypto_client_stream_factory_(quic_crypto_client_stream_factory),
607 random_generator_(random_generator),
608 clock_(clock),
609 max_packet_length_(max_packet_length),
610 config_(InitializeQuicConfig(connection_options)),
611 supported_versions_(supported_versions),
612 enable_port_selection_(enable_port_selection),
613 always_require_handshake_confirmation_(
614 always_require_handshake_confirmation),
615 disable_connection_pooling_(disable_connection_pooling),
616 load_server_info_timeout_ms_(load_server_info_timeout),
617 load_server_info_timeout_srtt_multiplier_(
618 load_server_info_timeout_srtt_multiplier),
619 enable_truncated_connection_ids_(enable_truncated_connection_ids),
620 enable_connection_racing_(enable_connection_racing),
621 port_seed_(random_generator_->RandUint64()),
622 check_persisted_supports_quic_(true),
623 task_runner_(nullptr),
624 weak_factory_(this) {
625 DCHECK(transport_security_state_);
626 // TODO(michaeln): Remove ScopedTracker below once crbug.com/454983 is fixed
627 tracked_objects::ScopedTracker tracking_profile(
628 FROM_HERE_WITH_EXPLICIT_FUNCTION(
629 "454983 QuicStreamFactory::QuicStreamFactory"));
630 crypto_config_.set_user_agent_id(user_agent_id);
631 crypto_config_.AddCanonicalSuffix(".c.youtube.com");
632 crypto_config_.AddCanonicalSuffix(".googlevideo.com");
633 crypto_config_.SetProofVerifier(
634 new ProofVerifierChromium(cert_verifier, transport_security_state));
635 crypto_config_.SetChannelIDSource(
636 new ChannelIDSourceChromium(channel_id_service));
637 base::CPU cpu;
638 if (cpu.has_aesni() && cpu.has_avx())
639 crypto_config_.PreferAesGcm();
640 if (!IsEcdsaSupported())
641 crypto_config_.DisableEcdsa();
642 }
643
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());
649 }
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);
654 }
655 }
656
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());
662 }
663 }
664
665 int QuicStreamFactory::Create(const HostPortPair& host_port_pair,
666 bool is_https,
667 PrivacyMode privacy_mode,
668 base::StringPiece method,
669 const BoundNetLog& net_log,
670 QuicStreamRequest* request) {
671 QuicServerId server_id(host_port_pair, is_https, privacy_mode);
672 if (HasActiveSession(server_id)) {
673 request->set_stream(CreateIfSessionExists(server_id, net_log));
674 return OK;
675 }
676
677 if (HasActiveJob(server_id)) {
678 active_requests_[request] = server_id;
679 job_requests_map_[server_id].insert(request);
680 return ERR_IO_PENDING;
681 }
682
683 // TODO(rtenneti): |task_runner_| is used by the Job. Initialize task_runner_
684 // in the constructor after WebRequestActionWithThreadsTest.* tests are fixed.
685 if (!task_runner_)
686 task_runner_ = base::MessageLoop::current()->message_loop_proxy().get();
687
688 QuicServerInfo* quic_server_info = nullptr;
689 if (quic_server_info_factory_) {
690 bool load_from_disk_cache = true;
691 if (http_server_properties_) {
692 const AlternateProtocolMap& alternate_protocol_map =
693 http_server_properties_->alternate_protocol_map();
694 AlternateProtocolMap::const_iterator it =
695 alternate_protocol_map.Peek(server_id.host_port_pair());
696 if (it == alternate_protocol_map.end() || it->second.protocol != QUIC) {
697 // If there is no entry for QUIC, consider that as a new server and
698 // don't wait for Cache thread to load the data for that server.
699 load_from_disk_cache = false;
700 }
701 }
702 if (load_from_disk_cache && CryptoConfigCacheIsEmpty(server_id)) {
703 quic_server_info = quic_server_info_factory_->GetForServer(server_id);
704 }
705 }
706
707 scoped_ptr<Job> job(new Job(this, host_resolver_, host_port_pair, is_https,
708 WasAlternateProtocolRecentlyBroken(server_id),
709 privacy_mode, method == "POST" /* is_post */,
710 quic_server_info, net_log));
711 int rv = job->Run(base::Bind(&QuicStreamFactory::OnJobComplete,
712 base::Unretained(this), job.get()));
713 if (rv == ERR_IO_PENDING) {
714 active_requests_[request] = server_id;
715 job_requests_map_[server_id].insert(request);
716 active_jobs_[server_id].insert(job.release());
717 return rv;
718 }
719 if (rv == OK) {
720 DCHECK(HasActiveSession(server_id));
721 request->set_stream(CreateIfSessionExists(server_id, net_log));
722 }
723 return rv;
724 }
725
726 void QuicStreamFactory::CreateAuxilaryJob(const QuicServerId server_id,
727 bool is_post,
728 const BoundNetLog& net_log) {
729 Job* aux_job = new Job(this, host_resolver_, server_id.host_port_pair(),
730 server_id.is_https(),
731 WasAlternateProtocolRecentlyBroken(server_id),
732 server_id.privacy_mode(), is_post, nullptr, net_log);
733 active_jobs_[server_id].insert(aux_job);
734 task_runner_->PostTask(FROM_HERE,
735 base::Bind(&QuicStreamFactory::Job::RunAuxilaryJob,
736 aux_job->GetWeakPtr()));
737 }
738
739 bool QuicStreamFactory::OnResolution(
740 const QuicServerId& server_id,
741 const AddressList& address_list) {
742 DCHECK(!HasActiveSession(server_id));
743 if (disable_connection_pooling_) {
744 return false;
745 }
746 for (const IPEndPoint& address : address_list) {
747 const IpAliasKey ip_alias_key(address, server_id.is_https());
748 if (!ContainsKey(ip_aliases_, ip_alias_key))
749 continue;
750
751 const SessionSet& sessions = ip_aliases_[ip_alias_key];
752 for (QuicClientSession* session : sessions) {
753 if (!session->CanPool(server_id.host(), server_id.privacy_mode()))
754 continue;
755 active_sessions_[server_id] = session;
756 session_aliases_[session].insert(server_id);
757 return true;
758 }
759 }
760 return false;
761 }
762
763 void QuicStreamFactory::OnJobComplete(Job* job, int rv) {
764 QuicServerId server_id = job->server_id();
765 if (rv != OK) {
766 JobSet* jobs = &(active_jobs_[server_id]);
767 if (jobs->size() > 1) {
768 // If there is another pending job, then we can delete this job and let
769 // the other job handle the request.
770 job->Cancel();
771 jobs->erase(job);
772 delete job;
773 return;
774 }
775 }
776
777 if (rv == OK) {
778 // TODO(vadimt): Remove ScopedTracker below once crbug.com/422516 is fixed.
779 tracked_objects::ScopedTracker tracking_profile1(
780 FROM_HERE_WITH_EXPLICIT_FUNCTION(
781 "422516 QuicStreamFactory::OnJobComplete1"));
782
783 if (!always_require_handshake_confirmation_)
784 set_require_confirmation(false);
785
786 // Create all the streams, but do not notify them yet.
787 for (QuicStreamRequest* request : job_requests_map_[server_id]) {
788 DCHECK(HasActiveSession(server_id));
789 request->set_stream(CreateIfSessionExists(server_id, request->net_log()));
790 }
791 }
792
793 // TODO(vadimt): Remove ScopedTracker below once crbug.com/422516 is fixed.
794 tracked_objects::ScopedTracker tracking_profile2(
795 FROM_HERE_WITH_EXPLICIT_FUNCTION(
796 "422516 QuicStreamFactory::OnJobComplete2"));
797
798 while (!job_requests_map_[server_id].empty()) {
799 RequestSet::iterator it = job_requests_map_[server_id].begin();
800 QuicStreamRequest* request = *it;
801 job_requests_map_[server_id].erase(it);
802 active_requests_.erase(request);
803 // Even though we're invoking callbacks here, we don't need to worry
804 // about |this| being deleted, because the factory is owned by the
805 // profile which can not be deleted via callbacks.
806 request->OnRequestComplete(rv);
807 }
808
809 // TODO(vadimt): Remove ScopedTracker below once crbug.com/422516 is fixed.
810 tracked_objects::ScopedTracker tracking_profile3(
811 FROM_HERE_WITH_EXPLICIT_FUNCTION(
812 "422516 QuicStreamFactory::OnJobComplete3"));
813
814 for (Job* other_job : active_jobs_[server_id]) {
815 if (other_job != job)
816 other_job->Cancel();
817 }
818
819 STLDeleteElements(&(active_jobs_[server_id]));
820 active_jobs_.erase(server_id);
821 job_requests_map_.erase(server_id);
822 }
823
824 // Returns a newly created QuicHttpStream owned by the caller, if a
825 // matching session already exists. Returns nullptr otherwise.
826 scoped_ptr<QuicHttpStream> QuicStreamFactory::CreateIfSessionExists(
827 const QuicServerId& server_id,
828 const BoundNetLog& net_log) {
829 if (!HasActiveSession(server_id)) {
830 DVLOG(1) << "No active session";
831 return scoped_ptr<QuicHttpStream>();
832 }
833
834 QuicClientSession* session = active_sessions_[server_id];
835 DCHECK(session);
836 return scoped_ptr<QuicHttpStream>(
837 new QuicHttpStream(session->GetWeakPtr()));
838 }
839
840 void QuicStreamFactory::OnIdleSession(QuicClientSession* session) {
841 }
842
843 void QuicStreamFactory::OnSessionGoingAway(QuicClientSession* session) {
844 const AliasSet& aliases = session_aliases_[session];
845 for (AliasSet::const_iterator it = aliases.begin(); it != aliases.end();
846 ++it) {
847 DCHECK(active_sessions_.count(*it));
848 DCHECK_EQ(session, active_sessions_[*it]);
849 // Track sessions which have recently gone away so that we can disable
850 // port suggestions.
851 if (session->goaway_received()) {
852 gone_away_aliases_.insert(*it);
853 }
854
855 active_sessions_.erase(*it);
856 ProcessGoingAwaySession(session, *it, true);
857 }
858 ProcessGoingAwaySession(session, all_sessions_[session], false);
859 if (!aliases.empty()) {
860 const IpAliasKey ip_alias_key(session->connection()->peer_address(),
861 aliases.begin()->is_https());
862 ip_aliases_[ip_alias_key].erase(session);
863 if (ip_aliases_[ip_alias_key].empty()) {
864 ip_aliases_.erase(ip_alias_key);
865 }
866 }
867 session_aliases_.erase(session);
868 }
869
870 void QuicStreamFactory::OnSessionClosed(QuicClientSession* session) {
871 DCHECK_EQ(0u, session->GetNumOpenStreams());
872 OnSessionGoingAway(session);
873 delete session;
874 all_sessions_.erase(session);
875 }
876
877 void QuicStreamFactory::OnSessionConnectTimeout(
878 QuicClientSession* session) {
879 const AliasSet& aliases = session_aliases_[session];
880 for (AliasSet::const_iterator it = aliases.begin(); it != aliases.end();
881 ++it) {
882 DCHECK(active_sessions_.count(*it));
883 DCHECK_EQ(session, active_sessions_[*it]);
884 active_sessions_.erase(*it);
885 }
886
887 if (aliases.empty()) {
888 return;
889 }
890
891 const IpAliasKey ip_alias_key(session->connection()->peer_address(),
892 aliases.begin()->is_https());
893 ip_aliases_[ip_alias_key].erase(session);
894 if (ip_aliases_[ip_alias_key].empty()) {
895 ip_aliases_.erase(ip_alias_key);
896 }
897 QuicServerId server_id = *aliases.begin();
898 session_aliases_.erase(session);
899 Job* job = new Job(this, host_resolver_, session, server_id);
900 active_jobs_[server_id].insert(job);
901 int rv = job->Run(base::Bind(&QuicStreamFactory::OnJobComplete,
902 base::Unretained(this), job));
903 DCHECK_EQ(ERR_IO_PENDING, rv);
904 }
905
906 void QuicStreamFactory::CancelRequest(QuicStreamRequest* request) {
907 DCHECK(ContainsKey(active_requests_, request));
908 QuicServerId server_id = active_requests_[request];
909 job_requests_map_[server_id].erase(request);
910 active_requests_.erase(request);
911 }
912
913 void QuicStreamFactory::CloseAllSessions(int error) {
914 while (!active_sessions_.empty()) {
915 size_t initial_size = active_sessions_.size();
916 active_sessions_.begin()->second->CloseSessionOnError(error);
917 DCHECK_NE(initial_size, active_sessions_.size());
918 }
919 while (!all_sessions_.empty()) {
920 size_t initial_size = all_sessions_.size();
921 all_sessions_.begin()->first->CloseSessionOnError(error);
922 DCHECK_NE(initial_size, all_sessions_.size());
923 }
924 DCHECK(all_sessions_.empty());
925 }
926
927 base::Value* QuicStreamFactory::QuicStreamFactoryInfoToValue() const {
928 base::ListValue* list = new base::ListValue();
929
930 for (SessionMap::const_iterator it = active_sessions_.begin();
931 it != active_sessions_.end(); ++it) {
932 const QuicServerId& server_id = it->first;
933 QuicClientSession* session = it->second;
934 const AliasSet& aliases = session_aliases_.find(session)->second;
935 // Only add a session to the list once.
936 if (server_id == *aliases.begin()) {
937 std::set<HostPortPair> hosts;
938 for (AliasSet::const_iterator alias_it = aliases.begin();
939 alias_it != aliases.end(); ++alias_it) {
940 hosts.insert(alias_it->host_port_pair());
941 }
942 list->Append(session->GetInfoAsValue(hosts));
943 }
944 }
945 return list;
946 }
947
948 void QuicStreamFactory::ClearCachedStatesInCryptoConfig() {
949 crypto_config_.ClearCachedStates();
950 }
951
952 void QuicStreamFactory::OnIPAddressChanged() {
953 CloseAllSessions(ERR_NETWORK_CHANGED);
954 set_require_confirmation(true);
955 }
956
957 void QuicStreamFactory::OnCertAdded(const X509Certificate* cert) {
958 CloseAllSessions(ERR_CERT_DATABASE_CHANGED);
959 }
960
961 void QuicStreamFactory::OnCACertChanged(const X509Certificate* cert) {
962 // We should flush the sessions if we removed trust from a
963 // cert, because a previously trusted server may have become
964 // untrusted.
965 //
966 // We should not flush the sessions if we added trust to a cert.
967 //
968 // Since the OnCACertChanged method doesn't tell us what
969 // kind of change it is, we have to flush the socket
970 // pools to be safe.
971 CloseAllSessions(ERR_CERT_DATABASE_CHANGED);
972 }
973
974 bool QuicStreamFactory::HasActiveSession(
975 const QuicServerId& server_id) const {
976 return ContainsKey(active_sessions_, server_id);
977 }
978
979 bool QuicStreamFactory::HasActiveJob(const QuicServerId& key) const {
980 return ContainsKey(active_jobs_, key);
981 }
982
983 int QuicStreamFactory::CreateSession(
984 const QuicServerId& server_id,
985 scoped_ptr<QuicServerInfo> server_info,
986 const AddressList& address_list,
987 const BoundNetLog& net_log,
988 QuicClientSession** session) {
989 // TODO(vadimt): Remove ScopedTracker below once crbug.com/422516 is fixed.
990 tracked_objects::ScopedTracker tracking_profile1(
991 FROM_HERE_WITH_EXPLICIT_FUNCTION(
992 "422516 QuicStreamFactory::CreateSession1"));
993
994 bool enable_port_selection = enable_port_selection_;
995 if (enable_port_selection &&
996 ContainsKey(gone_away_aliases_, server_id)) {
997 // Disable port selection when the server is going away.
998 // There is no point in trying to return to the same server, if
999 // that server is no longer handling requests.
1000 enable_port_selection = false;
1001 gone_away_aliases_.erase(server_id);
1002 }
1003
1004 QuicConnectionId connection_id = random_generator_->RandUint64();
1005 IPEndPoint addr = *address_list.begin();
1006 scoped_refptr<PortSuggester> port_suggester =
1007 new PortSuggester(server_id.host_port_pair(), port_seed_);
1008 DatagramSocket::BindType bind_type = enable_port_selection ?
1009 DatagramSocket::RANDOM_BIND : // Use our callback.
1010 DatagramSocket::DEFAULT_BIND; // Use OS to randomize.
1011 scoped_ptr<DatagramClientSocket> socket(
1012 client_socket_factory_->CreateDatagramClientSocket(
1013 bind_type,
1014 base::Bind(&PortSuggester::SuggestPort, port_suggester),
1015 net_log.net_log(), net_log.source()));
1016
1017 // TODO(vadimt): Remove ScopedTracker below once crbug.com/422516 is fixed.
1018 tracked_objects::ScopedTracker tracking_profile2(
1019 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1020 "422516 QuicStreamFactory::CreateSession2"));
1021
1022 int rv = socket->Connect(addr);
1023
1024 // TODO(vadimt): Remove ScopedTracker below once crbug.com/422516 is fixed.
1025 tracked_objects::ScopedTracker tracking_profile3(
1026 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1027 "422516 QuicStreamFactory::CreateSession3"));
1028
1029 if (rv != OK) {
1030 HistogramCreateSessionFailure(CREATION_ERROR_CONNECTING_SOCKET);
1031 return rv;
1032 }
1033 UMA_HISTOGRAM_COUNTS("Net.QuicEphemeralPortsSuggested",
1034 port_suggester->call_count());
1035 if (enable_port_selection) {
1036 DCHECK_LE(1u, port_suggester->call_count());
1037 } else {
1038 DCHECK_EQ(0u, port_suggester->call_count());
1039 }
1040
1041 // We should adaptively set this buffer size, but for now, we'll use a size
1042 // that is more than large enough for a full receive window, and yet
1043 // does not consume "too much" memory. If we see bursty packet loss, we may
1044 // revisit this setting and test for its impact.
1045 const int32 kSocketBufferSize =
1046 static_cast<int32>(kDefaultSocketReceiveBuffer);
1047 rv = socket->SetReceiveBufferSize(kSocketBufferSize);
1048 if (rv != OK) {
1049 HistogramCreateSessionFailure(CREATION_ERROR_SETTING_RECEIVE_BUFFER);
1050 return rv;
1051 }
1052 // Set a buffer large enough to contain the initial CWND's worth of packet
1053 // to work around the problem with CHLO packets being sent out with the
1054 // wrong encryption level, when the send buffer is full.
1055 rv = socket->SetSendBufferSize(kMaxPacketSize * 20);
1056 if (rv != OK) {
1057 HistogramCreateSessionFailure(CREATION_ERROR_SETTING_SEND_BUFFER);
1058 return rv;
1059 }
1060
1061 socket->GetLocalAddress(&local_address_);
1062 if (check_persisted_supports_quic_ && http_server_properties_) {
1063 check_persisted_supports_quic_ = false;
1064 IPAddressNumber last_address;
1065 if (http_server_properties_->GetSupportsQuic(&last_address) &&
1066 last_address == local_address_.address()) {
1067 require_confirmation_ = false;
1068 }
1069 }
1070
1071 DefaultPacketWriterFactory packet_writer_factory(socket.get());
1072
1073 if (!helper_.get()) {
1074 helper_.reset(new QuicConnectionHelper(
1075 base::MessageLoop::current()->message_loop_proxy().get(),
1076 clock_.get(), random_generator_));
1077 }
1078
1079 // TODO(vadimt): Remove ScopedTracker below once crbug.com/422516 is fixed.
1080 tracked_objects::ScopedTracker tracking_profile4(
1081 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1082 "422516 QuicStreamFactory::CreateSession4"));
1083
1084 QuicConnection* connection = new QuicConnection(connection_id,
1085 addr,
1086 helper_.get(),
1087 packet_writer_factory,
1088 true /* owns_writer */,
1089 false /* is_server */,
1090 server_id.is_https(),
1091 supported_versions_);
1092 connection->set_max_packet_length(max_packet_length_);
1093
1094 // TODO(vadimt): Remove ScopedTracker below once crbug.com/422516 is fixed.
1095 tracked_objects::ScopedTracker tracking_profile5(
1096 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1097 "422516 QuicStreamFactory::CreateSession5"));
1098
1099 InitializeCachedStateInCryptoConfig(server_id, server_info);
1100
1101 // TODO(vadimt): Remove ScopedTracker below once crbug.com/422516 is fixed.
1102 tracked_objects::ScopedTracker tracking_profile51(
1103 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1104 "422516 QuicStreamFactory::CreateSession51"));
1105
1106 QuicConfig config = config_;
1107
1108 // TODO(vadimt): Remove ScopedTracker below once crbug.com/422516 is fixed.
1109 tracked_objects::ScopedTracker tracking_profile52(
1110 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1111 "422516 QuicStreamFactory::CreateSession52"));
1112
1113 config.set_max_undecryptable_packets(kMaxUndecryptablePackets);
1114
1115 // TODO(vadimt): Remove ScopedTracker below once crbug.com/422516 is fixed.
1116 tracked_objects::ScopedTracker tracking_profile53(
1117 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1118 "422516 QuicStreamFactory::CreateSession53"));
1119
1120 config.SetInitialStreamFlowControlWindowToSend(kInitialReceiveWindowSize);
1121
1122 // TODO(vadimt): Remove ScopedTracker below once crbug.com/422516 is fixed.
1123 tracked_objects::ScopedTracker tracking_profile54(
1124 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1125 "422516 QuicStreamFactory::CreateSession54"));
1126
1127 config.SetInitialSessionFlowControlWindowToSend(kInitialReceiveWindowSize);
1128
1129 // TODO(vadimt): Remove ScopedTracker below once crbug.com/422516 is fixed.
1130 tracked_objects::ScopedTracker tracking_profile55(
1131 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1132 "422516 QuicStreamFactory::CreateSession55"));
1133
1134 int64 srtt = GetServerNetworkStatsSmoothedRttInMicroseconds(server_id);
1135
1136 // TODO(vadimt): Remove ScopedTracker below once crbug.com/422516 is fixed.
1137 tracked_objects::ScopedTracker tracking_profile56(
1138 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1139 "422516 QuicStreamFactory::CreateSession56"));
1140
1141 if (srtt > 0)
1142 config.SetInitialRoundTripTimeUsToSend(static_cast<uint32>(srtt));
1143
1144 // TODO(vadimt): Remove ScopedTracker below once crbug.com/422516 is fixed.
1145 tracked_objects::ScopedTracker tracking_profile57(
1146 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1147 "422516 QuicStreamFactory::CreateSession57"));
1148
1149 if (enable_truncated_connection_ids_)
1150 config.SetBytesForConnectionIdToSend(0);
1151
1152 if (quic_server_info_factory_ && !server_info) {
1153 // TODO(vadimt): Remove ScopedTracker below once crbug.com/422516 is fixed.
1154 tracked_objects::ScopedTracker tracking_profile6(
1155 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1156 "422516 QuicStreamFactory::CreateSession6"));
1157
1158 // Start the disk cache loading so that we can persist the newer QUIC server
1159 // information and/or inform the disk cache that we have reused
1160 // |server_info|.
1161 server_info.reset(quic_server_info_factory_->GetForServer(server_id));
1162 server_info->Start();
1163 }
1164
1165 // TODO(vadimt): Remove ScopedTracker below once crbug.com/422516 is fixed.
1166 tracked_objects::ScopedTracker tracking_profile61(
1167 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1168 "422516 QuicStreamFactory::CreateSession61"));
1169
1170 *session = new QuicClientSession(
1171 connection, socket.Pass(), this, transport_security_state_,
1172 server_info.Pass(), config,
1173 base::MessageLoop::current()->message_loop_proxy().get(),
1174 net_log.net_log());
1175
1176 // TODO(rtenneti): Remove ScopedTracker below once crbug.com/422516 is fixed.
1177 tracked_objects::ScopedTracker tracking_profile62(
1178 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1179 "422516 QuicStreamFactory::CreateSession62"));
1180
1181 all_sessions_[*session] = server_id; // owning pointer
1182
1183 // TODO(vadimt): Remove ScopedTracker below once crbug.com/422516 is fixed.
1184 tracked_objects::ScopedTracker tracking_profile7(
1185 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1186 "422516 QuicStreamFactory::CreateSession7"));
1187
1188 (*session)->InitializeSession(server_id, &crypto_config_,
1189 quic_crypto_client_stream_factory_);
1190 bool closed_during_initialize =
1191 !ContainsKey(all_sessions_, *session) ||
1192 !(*session)->connection()->connected();
1193 UMA_HISTOGRAM_BOOLEAN("Net.QuicSession.ClosedDuringInitializeSession",
1194 closed_during_initialize);
1195 if (closed_during_initialize) {
1196 DLOG(DFATAL) << "Session closed during initialize";
1197 *session = nullptr;
1198 return ERR_CONNECTION_CLOSED;
1199 }
1200 return OK;
1201 }
1202
1203 void QuicStreamFactory::ActivateSession(
1204 const QuicServerId& server_id,
1205 QuicClientSession* session) {
1206 DCHECK(!HasActiveSession(server_id));
1207 UMA_HISTOGRAM_COUNTS("Net.QuicActiveSessions", active_sessions_.size());
1208 active_sessions_[server_id] = session;
1209 session_aliases_[session].insert(server_id);
1210 const IpAliasKey ip_alias_key(session->connection()->peer_address(),
1211 server_id.is_https());
1212 DCHECK(!ContainsKey(ip_aliases_[ip_alias_key], session));
1213 ip_aliases_[ip_alias_key].insert(session);
1214 }
1215
1216 int64 QuicStreamFactory::GetServerNetworkStatsSmoothedRttInMicroseconds(
1217 const QuicServerId& server_id) const {
1218 if (!http_server_properties_)
1219 return 0;
1220 const ServerNetworkStats* stats =
1221 http_server_properties_->GetServerNetworkStats(
1222 server_id.host_port_pair());
1223 if (stats == nullptr)
1224 return 0;
1225 return stats->srtt.InMicroseconds();
1226 }
1227
1228 bool QuicStreamFactory::WasAlternateProtocolRecentlyBroken(
1229 const QuicServerId& server_id) const {
1230 return http_server_properties_ &&
1231 http_server_properties_->WasAlternateProtocolRecentlyBroken(
1232 server_id.host_port_pair());
1233 }
1234
1235 bool QuicStreamFactory::CryptoConfigCacheIsEmpty(
1236 const QuicServerId& server_id) {
1237 QuicCryptoClientConfig::CachedState* cached =
1238 crypto_config_.LookupOrCreate(server_id);
1239 return cached->IsEmpty();
1240 }
1241
1242 void QuicStreamFactory::InitializeCachedStateInCryptoConfig(
1243 const QuicServerId& server_id,
1244 const scoped_ptr<QuicServerInfo>& server_info) {
1245 // TODO(vadimt): Remove ScopedTracker below once crbug.com/422516 is fixed.
1246 tracked_objects::ScopedTracker tracking_profile1(
1247 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1248 "422516 QuicStreamFactory::InitializeCachedStateInCryptoConfig1"));
1249
1250 // |server_info| will be NULL, if a non-empty server config already exists in
1251 // the memory cache. This is a minor optimization to avoid LookupOrCreate.
1252 if (!server_info)
1253 return;
1254
1255 QuicCryptoClientConfig::CachedState* cached =
1256 crypto_config_.LookupOrCreate(server_id);
1257 if (!cached->IsEmpty())
1258 return;
1259
1260 if (http_server_properties_) {
1261 if (quic_supported_servers_at_startup_.empty()) {
1262 for (const std::pair<const HostPortPair, AlternateProtocolInfo>&
1263 key_value : http_server_properties_->alternate_protocol_map()) {
1264 if (key_value.second.protocol == QUIC) {
1265 quic_supported_servers_at_startup_.insert(key_value.first);
1266 }
1267 }
1268 }
1269
1270 // TODO(rtenneti): Delete the following histogram after collecting stats.
1271 // If the AlternateProtocolMap contained an entry for this host, check if
1272 // the disk cache contained an entry for it.
1273 if (ContainsKey(quic_supported_servers_at_startup_,
1274 server_id.host_port_pair())) {
1275 UMA_HISTOGRAM_BOOLEAN(
1276 "Net.QuicServerInfo.ExpectConfigMissingFromDiskCache",
1277 server_info->state().server_config.empty());
1278 }
1279 }
1280
1281 // TODO(vadimt): Remove ScopedTracker below once crbug.com/422516 is fixed.
1282 tracked_objects::ScopedTracker tracking_profile2(
1283 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1284 "422516 QuicStreamFactory::InitializeCachedStateInCryptoConfig2"));
1285
1286 if (!cached->Initialize(server_info->state().server_config,
1287 server_info->state().source_address_token,
1288 server_info->state().certs,
1289 server_info->state().server_config_sig,
1290 clock_->WallNow()))
1291 return;
1292
1293 if (!server_id.is_https()) {
1294 // Don't check the certificates for insecure QUIC.
1295 cached->SetProofValid();
1296 }
1297 }
1298
1299 void QuicStreamFactory::ProcessGoingAwaySession(
1300 QuicClientSession* session,
1301 const QuicServerId& server_id,
1302 bool session_was_active) {
1303 if (!http_server_properties_)
1304 return;
1305
1306 const QuicConnectionStats& stats = session->connection()->GetStats();
1307 if (session->IsCryptoHandshakeConfirmed()) {
1308 ServerNetworkStats network_stats;
1309 network_stats.srtt = base::TimeDelta::FromMicroseconds(stats.srtt_us);
1310 network_stats.bandwidth_estimate = stats.estimated_bandwidth;
1311 http_server_properties_->SetServerNetworkStats(server_id.host_port_pair(),
1312 network_stats);
1313 return;
1314 }
1315
1316 UMA_HISTOGRAM_COUNTS("Net.QuicHandshakeNotConfirmedNumPacketsReceived",
1317 stats.packets_received);
1318
1319 if (!session_was_active)
1320 return;
1321
1322 const HostPortPair& server = server_id.host_port_pair();
1323 // Don't try to change the alternate-protocol state, if the
1324 // alternate-protocol state is unknown.
1325 const AlternateProtocolInfo alternate =
1326 http_server_properties_->GetAlternateProtocol(server);
1327 if (alternate.protocol == UNINITIALIZED_ALTERNATE_PROTOCOL)
1328 return;
1329
1330 // TODO(rch): In the special case where the session has received no
1331 // packets from the peer, we should consider blacklisting this
1332 // differently so that we still race TCP but we don't consider the
1333 // session connected until the handshake has been confirmed.
1334 HistogramBrokenAlternateProtocolLocation(
1335 BROKEN_ALTERNATE_PROTOCOL_LOCATION_QUIC_STREAM_FACTORY);
1336 DCHECK_EQ(QUIC, alternate.protocol);
1337
1338 // Since the session was active, there's no longer an
1339 // HttpStreamFactoryImpl::Job running which can mark it broken, unless the
1340 // TCP job also fails. So to avoid not using QUIC when we otherwise could,
1341 // we mark it as broken, and then immediately re-enable it. This leaves
1342 // QUIC as "recently broken" which means that 0-RTT will be disabled but
1343 // we'll still race.
1344 http_server_properties_->SetBrokenAlternateProtocol(server);
1345 http_server_properties_->ClearAlternateProtocol(server);
1346 http_server_properties_->SetAlternateProtocol(
1347 server, alternate.port, alternate.protocol, 1);
1348 DCHECK_EQ(QUIC,
1349 http_server_properties_->GetAlternateProtocol(server).protocol);
1350 DCHECK(http_server_properties_->WasAlternateProtocolRecentlyBroken(
1351 server));
1352 }
1353
1354 } // namespace net
OLDNEW
« no previous file with comments | « net/quic/quic_stream_factory.h ('k') | net/quic/quic_stream_factory_test.cc » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698