2fc1b9e334c41b9a9b4e39b0e596eea9676bddb7
[platform/framework/web/crosswalk.git] / src / net / quic / quic_stream_factory.cc
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/histogram.h"
13 #include "base/rand_util.h"
14 #include "base/stl_util.h"
15 #include "base/strings/string_util.h"
16 #include "base/values.h"
17 #include "net/base/net_errors.h"
18 #include "net/cert/cert_verifier.h"
19 #include "net/dns/host_resolver.h"
20 #include "net/dns/single_request_host_resolver.h"
21 #include "net/http/http_server_properties.h"
22 #include "net/quic/congestion_control/tcp_receiver.h"
23 #include "net/quic/crypto/proof_verifier_chromium.h"
24 #include "net/quic/crypto/quic_random.h"
25 #include "net/quic/crypto/quic_server_info.h"
26 #include "net/quic/port_suggester.h"
27 #include "net/quic/quic_client_session.h"
28 #include "net/quic/quic_clock.h"
29 #include "net/quic/quic_connection.h"
30 #include "net/quic/quic_connection_helper.h"
31 #include "net/quic/quic_crypto_client_stream_factory.h"
32 #include "net/quic/quic_default_packet_writer.h"
33 #include "net/quic/quic_http_stream.h"
34 #include "net/quic/quic_protocol.h"
35 #include "net/quic/quic_server_id.h"
36 #include "net/socket/client_socket_factory.h"
37
38 #if defined(OS_WIN)
39 #include "base/win/windows_version.h"
40 #endif
41
42 using std::string;
43 using std::vector;
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 // The suggested initial congestion windows for a server to use.
63 // TODO: This should be tested and optimized, and even better, suggest a window
64 // that corresponds to historical bandwidth and min-RTT.
65 // Larger initial congestion windows can, if we don't overshoot, reduce latency
66 // by avoiding the RTT needed for slow start to double (and re-double) from a
67 // default of 10.
68 // We match SPDY's use of 32 when secure (since we'd compete with SPDY).
69 const int32 kServerSecureInitialCongestionWindow = 32;
70 // Be conservative, and just use double a typical TCP  ICWND for HTTP.
71 const int32 kServerInecureInitialCongestionWindow = 20;
72
73 void HistogramCreateSessionFailure(enum CreateSessionFailure error) {
74   UMA_HISTOGRAM_ENUMERATION("Net.QuicSession.CreationError", error,
75                             CREATION_ERROR_MAX);
76 }
77
78 bool IsEcdsaSupported() {
79 #if defined(OS_WIN)
80   if (base::win::GetVersion() < base::win::VERSION_VISTA)
81     return false;
82 #endif
83
84   return true;
85 }
86
87 QuicConfig InitializeQuicConfig(bool enable_pacing,
88                                 bool enable_time_based_loss_detection) {
89   QuicConfig config;
90   config.SetDefaults();
91   config.EnablePacing(enable_pacing);
92   if (enable_time_based_loss_detection)
93     config.SetLossDetectionToSend(kTIME);
94   config.set_idle_connection_state_lifetime(
95       QuicTime::Delta::FromSeconds(kIdleConnectionTimeoutSeconds),
96       QuicTime::Delta::FromSeconds(kIdleConnectionTimeoutSeconds));
97   return config;
98 }
99
100 }  // namespace
101
102 QuicStreamFactory::IpAliasKey::IpAliasKey() {}
103
104 QuicStreamFactory::IpAliasKey::IpAliasKey(IPEndPoint ip_endpoint,
105                                           bool is_https)
106     : ip_endpoint(ip_endpoint),
107       is_https(is_https) {}
108
109 QuicStreamFactory::IpAliasKey::~IpAliasKey() {}
110
111 bool QuicStreamFactory::IpAliasKey::operator<(
112     const QuicStreamFactory::IpAliasKey& other) const {
113   if (!(ip_endpoint == other.ip_endpoint)) {
114     return ip_endpoint < other.ip_endpoint;
115   }
116   return is_https < other.is_https;
117 }
118
119 bool QuicStreamFactory::IpAliasKey::operator==(
120     const QuicStreamFactory::IpAliasKey& other) const {
121   return is_https == other.is_https &&
122       ip_endpoint == other.ip_endpoint;
123 };
124
125 // Responsible for creating a new QUIC session to the specified server, and
126 // for notifying any associated requests when complete.
127 class QuicStreamFactory::Job {
128  public:
129   Job(QuicStreamFactory* factory,
130       HostResolver* host_resolver,
131       const HostPortPair& host_port_pair,
132       bool is_https,
133       bool was_alternate_protocol_recently_broken,
134       PrivacyMode privacy_mode,
135       base::StringPiece method,
136       QuicServerInfo* server_info,
137       const BoundNetLog& net_log);
138
139   // Creates a new job to handle the resumption of for connecting an
140   // existing session.
141   Job(QuicStreamFactory* factory,
142       HostResolver* host_resolver,
143       QuicClientSession* session,
144       QuicServerId server_id);
145
146   ~Job();
147
148   int Run(const CompletionCallback& callback);
149
150   int DoLoop(int rv);
151   int DoResolveHost();
152   int DoResolveHostComplete(int rv);
153   int DoLoadServerInfo();
154   int DoLoadServerInfoComplete(int rv);
155   int DoConnect();
156   int DoResumeConnect();
157   int DoConnectComplete(int rv);
158
159   void OnIOComplete(int rv);
160
161   CompletionCallback callback() {
162     return callback_;
163   }
164
165   const QuicServerId server_id() const {
166     return server_id_;
167   }
168
169  private:
170   enum IoState {
171     STATE_NONE,
172     STATE_RESOLVE_HOST,
173     STATE_RESOLVE_HOST_COMPLETE,
174     STATE_LOAD_SERVER_INFO,
175     STATE_LOAD_SERVER_INFO_COMPLETE,
176     STATE_CONNECT,
177     STATE_RESUME_CONNECT,
178     STATE_CONNECT_COMPLETE,
179   };
180   IoState io_state_;
181
182   QuicStreamFactory* factory_;
183   SingleRequestHostResolver host_resolver_;
184   QuicServerId server_id_;
185   bool is_post_;
186   bool was_alternate_protocol_recently_broken_;
187   scoped_ptr<QuicServerInfo> server_info_;
188   const BoundNetLog net_log_;
189   QuicClientSession* session_;
190   CompletionCallback callback_;
191   AddressList address_list_;
192   base::TimeTicks disk_cache_load_start_time_;
193   base::WeakPtrFactory<Job> weak_factory_;
194   DISALLOW_COPY_AND_ASSIGN(Job);
195 };
196
197 QuicStreamFactory::Job::Job(QuicStreamFactory* factory,
198                             HostResolver* host_resolver,
199                             const HostPortPair& host_port_pair,
200                             bool is_https,
201                             bool was_alternate_protocol_recently_broken,
202                             PrivacyMode privacy_mode,
203                             base::StringPiece method,
204                             QuicServerInfo* server_info,
205                             const BoundNetLog& net_log)
206     : io_state_(STATE_RESOLVE_HOST),
207       factory_(factory),
208       host_resolver_(host_resolver),
209       server_id_(host_port_pair, is_https, privacy_mode),
210       is_post_(method == "POST"),
211       was_alternate_protocol_recently_broken_(
212           was_alternate_protocol_recently_broken),
213       server_info_(server_info),
214       net_log_(net_log),
215       session_(NULL),
216       weak_factory_(this) {}
217
218 QuicStreamFactory::Job::Job(QuicStreamFactory* factory,
219                             HostResolver* host_resolver,
220                             QuicClientSession* session,
221                             QuicServerId server_id)
222     : io_state_(STATE_RESUME_CONNECT),
223       factory_(factory),
224       host_resolver_(host_resolver),  // unused
225       server_id_(server_id),
226       is_post_(false),  // unused
227       was_alternate_protocol_recently_broken_(false),  // unused
228       net_log_(session->net_log()),  // unused
229       session_(session),
230       weak_factory_(this) {}
231
232 QuicStreamFactory::Job::~Job() {
233 }
234
235 int QuicStreamFactory::Job::Run(const CompletionCallback& callback) {
236   int rv = DoLoop(OK);
237   if (rv == ERR_IO_PENDING)
238     callback_ = callback;
239
240   return rv > 0 ? OK : rv;
241 }
242
243 int QuicStreamFactory::Job::DoLoop(int rv) {
244   do {
245     IoState state = io_state_;
246     io_state_ = STATE_NONE;
247     switch (state) {
248       case STATE_RESOLVE_HOST:
249         CHECK_EQ(OK, rv);
250         rv = DoResolveHost();
251         break;
252       case STATE_RESOLVE_HOST_COMPLETE:
253         rv = DoResolveHostComplete(rv);
254         break;
255       case STATE_LOAD_SERVER_INFO:
256         CHECK_EQ(OK, rv);
257         rv = DoLoadServerInfo();
258         break;
259       case STATE_LOAD_SERVER_INFO_COMPLETE:
260         rv = DoLoadServerInfoComplete(rv);
261         break;
262       case STATE_CONNECT:
263         CHECK_EQ(OK, rv);
264         rv = DoConnect();
265         break;
266       case STATE_RESUME_CONNECT:
267         CHECK_EQ(OK, rv);
268         rv = DoResumeConnect();
269         break;
270       case STATE_CONNECT_COMPLETE:
271         rv = DoConnectComplete(rv);
272         break;
273       default:
274         NOTREACHED() << "io_state_: " << io_state_;
275         break;
276     }
277   } while (io_state_ != STATE_NONE && rv != ERR_IO_PENDING);
278   return rv;
279 }
280
281 void QuicStreamFactory::Job::OnIOComplete(int rv) {
282   rv = DoLoop(rv);
283
284   if (rv != ERR_IO_PENDING && !callback_.is_null()) {
285     callback_.Run(rv);
286   }
287 }
288
289 int QuicStreamFactory::Job::DoResolveHost() {
290   // Start loading the data now, and wait for it after we resolve the host.
291   if (server_info_) {
292     disk_cache_load_start_time_ = base::TimeTicks::Now();
293     server_info_->Start();
294   }
295
296   io_state_ = STATE_RESOLVE_HOST_COMPLETE;
297   return host_resolver_.Resolve(
298       HostResolver::RequestInfo(server_id_.host_port_pair()),
299       DEFAULT_PRIORITY,
300       &address_list_,
301       base::Bind(&QuicStreamFactory::Job::OnIOComplete,
302                  weak_factory_.GetWeakPtr()),
303       net_log_);
304 }
305
306 int QuicStreamFactory::Job::DoResolveHostComplete(int rv) {
307   if (rv != OK)
308     return rv;
309
310   DCHECK(!factory_->HasActiveSession(server_id_));
311
312   // Inform the factory of this resolution, which will set up
313   // a session alias, if possible.
314   if (factory_->OnResolution(server_id_, address_list_)) {
315     return OK;
316   }
317
318   io_state_ = STATE_LOAD_SERVER_INFO;
319   return OK;
320 }
321
322 int QuicStreamFactory::Job::DoLoadServerInfo() {
323   io_state_ = STATE_LOAD_SERVER_INFO_COMPLETE;
324
325   if (!server_info_)
326     return OK;
327
328   return server_info_->WaitForDataReady(
329       base::Bind(&QuicStreamFactory::Job::OnIOComplete,
330                  weak_factory_.GetWeakPtr()));
331 }
332
333 int QuicStreamFactory::Job::DoLoadServerInfoComplete(int rv) {
334   if (server_info_) {
335     UMA_HISTOGRAM_TIMES("Net.QuicServerInfo.DiskCacheReadTime",
336                         base::TimeTicks::Now() - disk_cache_load_start_time_);
337   }
338
339   if (rv != OK) {
340     server_info_.reset();
341   }
342
343   io_state_ = STATE_CONNECT;
344   return OK;
345 }
346
347 int QuicStreamFactory::Job::DoConnect() {
348   io_state_ = STATE_CONNECT_COMPLETE;
349
350   int rv = factory_->CreateSession(server_id_, server_info_.Pass(),
351                                    address_list_, net_log_, &session_);
352   if (rv != OK) {
353     DCHECK(rv != ERR_IO_PENDING);
354     DCHECK(!session_);
355     return rv;
356   }
357
358   session_->StartReading();
359   if (!session_->connection()->connected()) {
360     return ERR_QUIC_PROTOCOL_ERROR;
361   }
362   bool require_confirmation =
363       factory_->require_confirmation() || is_post_ ||
364       was_alternate_protocol_recently_broken_;
365   rv = session_->CryptoConnect(
366       require_confirmation,
367       base::Bind(&QuicStreamFactory::Job::OnIOComplete,
368                  base::Unretained(this)));
369   return rv;
370 }
371
372 int QuicStreamFactory::Job::DoResumeConnect() {
373   io_state_ = STATE_CONNECT_COMPLETE;
374
375   int rv = session_->ResumeCryptoConnect(
376       base::Bind(&QuicStreamFactory::Job::OnIOComplete,
377                  base::Unretained(this)));
378
379   return rv;
380 }
381
382 int QuicStreamFactory::Job::DoConnectComplete(int rv) {
383   if (rv != OK)
384     return rv;
385
386   DCHECK(!factory_->HasActiveSession(server_id_));
387   // There may well now be an active session for this IP.  If so, use the
388   // existing session instead.
389   AddressList address(session_->connection()->peer_address());
390   if (factory_->OnResolution(server_id_, address)) {
391     session_->connection()->SendConnectionClose(QUIC_CONNECTION_IP_POOLED);
392     session_ = NULL;
393     return OK;
394   }
395
396   factory_->ActivateSession(server_id_, session_);
397
398   return OK;
399 }
400
401 QuicStreamRequest::QuicStreamRequest(QuicStreamFactory* factory)
402     : factory_(factory) {}
403
404 QuicStreamRequest::~QuicStreamRequest() {
405   if (factory_ && !callback_.is_null())
406     factory_->CancelRequest(this);
407 }
408
409 int QuicStreamRequest::Request(const HostPortPair& host_port_pair,
410                                bool is_https,
411                                PrivacyMode privacy_mode,
412                                base::StringPiece method,
413                                const BoundNetLog& net_log,
414                                const CompletionCallback& callback) {
415   DCHECK(!stream_);
416   DCHECK(callback_.is_null());
417   DCHECK(factory_);
418   int rv = factory_->Create(host_port_pair, is_https, privacy_mode, method,
419                             net_log, this);
420   if (rv == ERR_IO_PENDING) {
421     host_port_pair_ = host_port_pair;
422     is_https_ = is_https;
423     net_log_ = net_log;
424     callback_ = callback;
425   } else {
426     factory_ = NULL;
427   }
428   if (rv == OK)
429     DCHECK(stream_);
430   return rv;
431 }
432
433 void QuicStreamRequest::set_stream(scoped_ptr<QuicHttpStream> stream) {
434   DCHECK(stream);
435   stream_ = stream.Pass();
436 }
437
438 void QuicStreamRequest::OnRequestComplete(int rv) {
439   factory_ = NULL;
440   callback_.Run(rv);
441 }
442
443 scoped_ptr<QuicHttpStream> QuicStreamRequest::ReleaseStream() {
444   DCHECK(stream_);
445   return stream_.Pass();
446 }
447
448 QuicStreamFactory::QuicStreamFactory(
449     HostResolver* host_resolver,
450     ClientSocketFactory* client_socket_factory,
451     base::WeakPtr<HttpServerProperties> http_server_properties,
452     CertVerifier* cert_verifier,
453     QuicCryptoClientStreamFactory* quic_crypto_client_stream_factory,
454     QuicRandom* random_generator,
455     QuicClock* clock,
456     size_t max_packet_length,
457     const std::string& user_agent_id,
458     const QuicVersionVector& supported_versions,
459     bool enable_port_selection,
460     bool enable_pacing,
461     bool enable_time_based_loss_detection)
462     : require_confirmation_(true),
463       host_resolver_(host_resolver),
464       client_socket_factory_(client_socket_factory),
465       http_server_properties_(http_server_properties),
466       cert_verifier_(cert_verifier),
467       quic_server_info_factory_(NULL),
468       quic_crypto_client_stream_factory_(quic_crypto_client_stream_factory),
469       random_generator_(random_generator),
470       clock_(clock),
471       max_packet_length_(max_packet_length),
472       config_(InitializeQuicConfig(enable_pacing,
473                                    enable_time_based_loss_detection)),
474       supported_versions_(supported_versions),
475       enable_port_selection_(enable_port_selection),
476       port_seed_(random_generator_->RandUint64()),
477       weak_factory_(this) {
478   crypto_config_.SetDefaults();
479   crypto_config_.set_user_agent_id(user_agent_id);
480   crypto_config_.AddCanonicalSuffix(".c.youtube.com");
481   crypto_config_.AddCanonicalSuffix(".googlevideo.com");
482   crypto_config_.SetProofVerifier(new ProofVerifierChromium(cert_verifier));
483   base::CPU cpu;
484   if (cpu.has_aesni() && cpu.has_avx())
485     crypto_config_.PreferAesGcm();
486   if (!IsEcdsaSupported())
487     crypto_config_.DisableEcdsa();
488 }
489
490 QuicStreamFactory::~QuicStreamFactory() {
491   CloseAllSessions(ERR_ABORTED);
492   while (!all_sessions_.empty()) {
493     delete all_sessions_.begin()->first;
494     all_sessions_.erase(all_sessions_.begin());
495   }
496   STLDeleteValues(&active_jobs_);
497 }
498
499 int QuicStreamFactory::Create(const HostPortPair& host_port_pair,
500                               bool is_https,
501                               PrivacyMode privacy_mode,
502                               base::StringPiece method,
503                               const BoundNetLog& net_log,
504                               QuicStreamRequest* request) {
505   QuicServerId server_id(host_port_pair, is_https, privacy_mode);
506   if (HasActiveSession(server_id)) {
507     request->set_stream(CreateIfSessionExists(server_id, net_log));
508     return OK;
509   }
510
511   if (HasActiveJob(server_id)) {
512     Job* job = active_jobs_[server_id];
513     active_requests_[request] = job;
514     job_requests_map_[job].insert(request);
515     return ERR_IO_PENDING;
516   }
517
518   QuicServerInfo* quic_server_info = NULL;
519   if (quic_server_info_factory_) {
520     QuicCryptoClientConfig::CachedState* cached =
521         crypto_config_.LookupOrCreate(server_id);
522     DCHECK(cached);
523     if (cached->IsEmpty()) {
524       quic_server_info = quic_server_info_factory_->GetForServer(server_id);
525     }
526   }
527   bool was_alternate_protocol_recently_broken =
528       http_server_properties_ &&
529       http_server_properties_->WasAlternateProtocolRecentlyBroken(
530           server_id.host_port_pair());
531   scoped_ptr<Job> job(new Job(this, host_resolver_, host_port_pair, is_https,
532                               was_alternate_protocol_recently_broken,
533                               privacy_mode, method, quic_server_info, net_log));
534   int rv = job->Run(base::Bind(&QuicStreamFactory::OnJobComplete,
535                                base::Unretained(this), job.get()));
536
537   if (rv == ERR_IO_PENDING) {
538     active_requests_[request] = job.get();
539     job_requests_map_[job.get()].insert(request);
540     active_jobs_[server_id] = job.release();
541   }
542   if (rv == OK) {
543     DCHECK(HasActiveSession(server_id));
544     request->set_stream(CreateIfSessionExists(server_id, net_log));
545   }
546   return rv;
547 }
548
549 bool QuicStreamFactory::OnResolution(
550     const QuicServerId& server_id,
551     const AddressList& address_list) {
552   DCHECK(!HasActiveSession(server_id));
553   for (size_t i = 0; i < address_list.size(); ++i) {
554     const IPEndPoint& address = address_list[i];
555     const IpAliasKey ip_alias_key(address, server_id.is_https());
556     if (!ContainsKey(ip_aliases_, ip_alias_key))
557       continue;
558
559     const SessionSet& sessions = ip_aliases_[ip_alias_key];
560     for (SessionSet::const_iterator i = sessions.begin();
561          i != sessions.end(); ++i) {
562       QuicClientSession* session = *i;
563       if (!session->CanPool(server_id.host()))
564         continue;
565       active_sessions_[server_id] = session;
566       session_aliases_[session].insert(server_id);
567       return true;
568     }
569   }
570   return false;
571 }
572
573 void QuicStreamFactory::OnJobComplete(Job* job, int rv) {
574   if (rv == OK) {
575     require_confirmation_ = false;
576
577     // Create all the streams, but do not notify them yet.
578     for (RequestSet::iterator it = job_requests_map_[job].begin();
579          it != job_requests_map_[job].end() ; ++it) {
580       DCHECK(HasActiveSession(job->server_id()));
581       (*it)->set_stream(CreateIfSessionExists(job->server_id(),
582                                               (*it)->net_log()));
583     }
584   }
585   while (!job_requests_map_[job].empty()) {
586     RequestSet::iterator it = job_requests_map_[job].begin();
587     QuicStreamRequest* request = *it;
588     job_requests_map_[job].erase(it);
589     active_requests_.erase(request);
590     // Even though we're invoking callbacks here, we don't need to worry
591     // about |this| being deleted, because the factory is owned by the
592     // profile which can not be deleted via callbacks.
593     request->OnRequestComplete(rv);
594   }
595   active_jobs_.erase(job->server_id());
596   job_requests_map_.erase(job);
597   delete job;
598   return;
599 }
600
601 // Returns a newly created QuicHttpStream owned by the caller, if a
602 // matching session already exists.  Returns NULL otherwise.
603 scoped_ptr<QuicHttpStream> QuicStreamFactory::CreateIfSessionExists(
604     const QuicServerId& server_id,
605     const BoundNetLog& net_log) {
606   if (!HasActiveSession(server_id)) {
607     DVLOG(1) << "No active session";
608     return scoped_ptr<QuicHttpStream>();
609   }
610
611   QuicClientSession* session = active_sessions_[server_id];
612   DCHECK(session);
613   return scoped_ptr<QuicHttpStream>(
614       new QuicHttpStream(session->GetWeakPtr()));
615 }
616
617 void QuicStreamFactory::OnIdleSession(QuicClientSession* session) {
618 }
619
620 void QuicStreamFactory::OnSessionGoingAway(QuicClientSession* session) {
621   const AliasSet& aliases = session_aliases_[session];
622   for (AliasSet::const_iterator it = aliases.begin(); it != aliases.end();
623        ++it) {
624     DCHECK(active_sessions_.count(*it));
625     DCHECK_EQ(session, active_sessions_[*it]);
626     // Track sessions which have recently gone away so that we can disable
627     // port suggestions.
628     if (session->goaway_received()) {
629       gone_away_aliases_.insert(*it);
630     }
631
632     active_sessions_.erase(*it);
633     ProcessGoingAwaySession(session, *it, true);
634   }
635   ProcessGoingAwaySession(session, all_sessions_[session], false);
636   if (!aliases.empty()) {
637     const IpAliasKey ip_alias_key(session->connection()->peer_address(),
638                                   aliases.begin()->is_https());
639     ip_aliases_[ip_alias_key].erase(session);
640     if (ip_aliases_[ip_alias_key].empty()) {
641       ip_aliases_.erase(ip_alias_key);
642     }
643   }
644   session_aliases_.erase(session);
645 }
646
647 void QuicStreamFactory::OnSessionClosed(QuicClientSession* session) {
648   DCHECK_EQ(0u, session->GetNumOpenStreams());
649   OnSessionGoingAway(session);
650   delete session;
651   all_sessions_.erase(session);
652 }
653
654 void QuicStreamFactory::OnSessionConnectTimeout(
655     QuicClientSession* session) {
656   const AliasSet& aliases = session_aliases_[session];
657   for (AliasSet::const_iterator it = aliases.begin(); it != aliases.end();
658        ++it) {
659     DCHECK(active_sessions_.count(*it));
660     DCHECK_EQ(session, active_sessions_[*it]);
661     active_sessions_.erase(*it);
662   }
663
664   if (aliases.empty()) {
665     return;
666   }
667
668   const IpAliasKey ip_alias_key(session->connection()->peer_address(),
669                                 aliases.begin()->is_https());
670   ip_aliases_[ip_alias_key].erase(session);
671   if (ip_aliases_[ip_alias_key].empty()) {
672     ip_aliases_.erase(ip_alias_key);
673   }
674   QuicServerId server_id = *aliases.begin();
675   session_aliases_.erase(session);
676   Job* job = new Job(this, host_resolver_, session, server_id);
677   active_jobs_[server_id] = job;
678   int rv = job->Run(base::Bind(&QuicStreamFactory::OnJobComplete,
679                                base::Unretained(this), job));
680   DCHECK_EQ(ERR_IO_PENDING, rv);
681 }
682
683 void QuicStreamFactory::CancelRequest(QuicStreamRequest* request) {
684   DCHECK(ContainsKey(active_requests_, request));
685   Job* job = active_requests_[request];
686   job_requests_map_[job].erase(request);
687   active_requests_.erase(request);
688 }
689
690 void QuicStreamFactory::CloseAllSessions(int error) {
691   while (!active_sessions_.empty()) {
692     size_t initial_size = active_sessions_.size();
693     active_sessions_.begin()->second->CloseSessionOnError(error);
694     DCHECK_NE(initial_size, active_sessions_.size());
695   }
696   while (!all_sessions_.empty()) {
697     size_t initial_size = all_sessions_.size();
698     all_sessions_.begin()->first->CloseSessionOnError(error);
699     DCHECK_NE(initial_size, all_sessions_.size());
700   }
701   DCHECK(all_sessions_.empty());
702 }
703
704 base::Value* QuicStreamFactory::QuicStreamFactoryInfoToValue() const {
705   base::ListValue* list = new base::ListValue();
706
707   for (SessionMap::const_iterator it = active_sessions_.begin();
708        it != active_sessions_.end(); ++it) {
709     const QuicServerId& server_id = it->first;
710     QuicClientSession* session = it->second;
711     const AliasSet& aliases = session_aliases_.find(session)->second;
712     // Only add a session to the list once.
713     if (server_id == *aliases.begin()) {
714       std::set<HostPortPair> hosts;
715       for (AliasSet::const_iterator alias_it = aliases.begin();
716            alias_it != aliases.end(); ++alias_it) {
717         hosts.insert(alias_it->host_port_pair());
718       }
719       list->Append(session->GetInfoAsValue(hosts));
720     }
721   }
722   return list;
723 }
724
725 void QuicStreamFactory::ClearCachedStatesInCryptoConfig() {
726   crypto_config_.ClearCachedStates();
727 }
728
729 void QuicStreamFactory::OnIPAddressChanged() {
730   CloseAllSessions(ERR_NETWORK_CHANGED);
731   require_confirmation_ = true;
732 }
733
734 void QuicStreamFactory::OnCertAdded(const X509Certificate* cert) {
735   CloseAllSessions(ERR_CERT_DATABASE_CHANGED);
736 }
737
738 void QuicStreamFactory::OnCACertChanged(const X509Certificate* cert) {
739   // We should flush the sessions if we removed trust from a
740   // cert, because a previously trusted server may have become
741   // untrusted.
742   //
743   // We should not flush the sessions if we added trust to a cert.
744   //
745   // Since the OnCACertChanged method doesn't tell us what
746   // kind of change it is, we have to flush the socket
747   // pools to be safe.
748   CloseAllSessions(ERR_CERT_DATABASE_CHANGED);
749 }
750
751 bool QuicStreamFactory::HasActiveSession(
752     const QuicServerId& server_id) const {
753   return ContainsKey(active_sessions_, server_id);
754 }
755
756 int QuicStreamFactory::CreateSession(
757     const QuicServerId& server_id,
758     scoped_ptr<QuicServerInfo> server_info,
759     const AddressList& address_list,
760     const BoundNetLog& net_log,
761     QuicClientSession** session) {
762   bool enable_port_selection = enable_port_selection_;
763   if (enable_port_selection &&
764       ContainsKey(gone_away_aliases_, server_id)) {
765     // Disable port selection when the server is going away.
766     // There is no point in trying to return to the same server, if
767     // that server is no longer handling requests.
768     enable_port_selection = false;
769     gone_away_aliases_.erase(server_id);
770   }
771
772   QuicConnectionId connection_id = random_generator_->RandUint64();
773   IPEndPoint addr = *address_list.begin();
774   scoped_refptr<PortSuggester> port_suggester =
775       new PortSuggester(server_id.host_port_pair(), port_seed_);
776   DatagramSocket::BindType bind_type = enable_port_selection ?
777       DatagramSocket::RANDOM_BIND :  // Use our callback.
778       DatagramSocket::DEFAULT_BIND;  // Use OS to randomize.
779   scoped_ptr<DatagramClientSocket> socket(
780       client_socket_factory_->CreateDatagramClientSocket(
781           bind_type,
782           base::Bind(&PortSuggester::SuggestPort, port_suggester),
783           net_log.net_log(), net_log.source()));
784   int rv = socket->Connect(addr);
785   if (rv != OK) {
786     HistogramCreateSessionFailure(CREATION_ERROR_CONNECTING_SOCKET);
787     return rv;
788   }
789   UMA_HISTOGRAM_COUNTS("Net.QuicEphemeralPortsSuggested",
790                        port_suggester->call_count());
791   if (enable_port_selection) {
792     DCHECK_LE(1u, port_suggester->call_count());
793   } else {
794     DCHECK_EQ(0u, port_suggester->call_count());
795   }
796
797   // We should adaptively set this buffer size, but for now, we'll use a size
798   // that is more than large enough for a full receive window, and yet
799   // does not consume "too much" memory.  If we see bursty packet loss, we may
800   // revisit this setting and test for its impact.
801   const int32 kSocketBufferSize(TcpReceiver::kReceiveWindowTCP);
802   rv = socket->SetReceiveBufferSize(kSocketBufferSize);
803   if (rv != OK) {
804     HistogramCreateSessionFailure(CREATION_ERROR_SETTING_RECEIVE_BUFFER);
805     return rv;
806   }
807   // Set a buffer large enough to contain the initial CWND's worth of packet
808   // to work around the problem with CHLO packets being sent out with the
809   // wrong encryption level, when the send buffer is full.
810   rv = socket->SetSendBufferSize(kMaxPacketSize * 20);
811   if (rv != OK) {
812     HistogramCreateSessionFailure(CREATION_ERROR_SETTING_SEND_BUFFER);
813     return rv;
814   }
815
816   scoped_ptr<QuicDefaultPacketWriter> writer(
817       new QuicDefaultPacketWriter(socket.get()));
818
819   if (!helper_.get()) {
820     helper_.reset(new QuicConnectionHelper(
821         base::MessageLoop::current()->message_loop_proxy().get(),
822         clock_.get(), random_generator_));
823   }
824
825   QuicConnection* connection =
826       new QuicConnection(connection_id, addr, helper_.get(), writer.get(),
827                          false, supported_versions_);
828   writer->SetConnection(connection);
829   connection->set_max_packet_length(max_packet_length_);
830
831   InitializeCachedStateInCryptoConfig(server_id, server_info);
832
833   QuicConfig config = config_;
834   config.SetInitialCongestionWindowToSend(
835       server_id.is_https() ? kServerSecureInitialCongestionWindow
836                            : kServerInecureInitialCongestionWindow);
837   config.SetInitialFlowControlWindowToSend(kInitialReceiveWindowSize);
838   config.SetInitialStreamFlowControlWindowToSend(kInitialReceiveWindowSize);
839   config.SetInitialSessionFlowControlWindowToSend(kInitialReceiveWindowSize);
840   if (http_server_properties_) {
841     const HttpServerProperties::NetworkStats* stats =
842         http_server_properties_->GetServerNetworkStats(
843             server_id.host_port_pair());
844     if (stats != NULL) {
845       config.SetInitialRoundTripTimeUsToSend(stats->srtt.InMicroseconds());
846     }
847   }
848
849   *session = new QuicClientSession(
850       connection, socket.Pass(), writer.Pass(), this,
851       quic_crypto_client_stream_factory_, server_info.Pass(), server_id,
852       config, &crypto_config_,
853       base::MessageLoop::current()->message_loop_proxy().get(),
854       net_log.net_log());
855   all_sessions_[*session] = server_id;  // owning pointer
856   return OK;
857 }
858
859 bool QuicStreamFactory::HasActiveJob(const QuicServerId& key) const {
860   return ContainsKey(active_jobs_, key);
861 }
862
863 void QuicStreamFactory::ActivateSession(
864     const QuicServerId& server_id,
865     QuicClientSession* session) {
866   DCHECK(!HasActiveSession(server_id));
867   UMA_HISTOGRAM_COUNTS("Net.QuicActiveSessions", active_sessions_.size());
868   active_sessions_[server_id] = session;
869   session_aliases_[session].insert(server_id);
870   const IpAliasKey ip_alias_key(session->connection()->peer_address(),
871                                 server_id.is_https());
872   DCHECK(!ContainsKey(ip_aliases_[ip_alias_key], session));
873   ip_aliases_[ip_alias_key].insert(session);
874 }
875
876 void QuicStreamFactory::InitializeCachedStateInCryptoConfig(
877     const QuicServerId& server_id,
878     const scoped_ptr<QuicServerInfo>& server_info) {
879   if (!server_info)
880     return;
881
882   QuicCryptoClientConfig::CachedState* cached =
883       crypto_config_.LookupOrCreate(server_id);
884   if (!cached->IsEmpty())
885     return;
886
887   if (!cached->Initialize(server_info->state().server_config,
888                           server_info->state().source_address_token,
889                           server_info->state().certs,
890                           server_info->state().server_config_sig,
891                           clock_->WallNow()))
892     return;
893
894   if (!server_id.is_https()) {
895     // Don't check the certificates for insecure QUIC.
896     cached->SetProofValid();
897   }
898 }
899
900 void QuicStreamFactory::ProcessGoingAwaySession(
901     QuicClientSession* session,
902     const QuicServerId& server_id,
903     bool session_was_active) {
904   if (!http_server_properties_)
905     return;
906
907   const QuicConnectionStats& stats = session->connection()->GetStats();
908   if (session->IsCryptoHandshakeConfirmed()) {
909     HttpServerProperties::NetworkStats network_stats;
910     network_stats.srtt = base::TimeDelta::FromMicroseconds(stats.srtt_us);
911     network_stats.bandwidth_estimate = stats.estimated_bandwidth;
912     http_server_properties_->SetServerNetworkStats(server_id.host_port_pair(),
913                                                    network_stats);
914     return;
915   }
916
917   UMA_HISTOGRAM_COUNTS("Net.QuicHandshakeNotConfirmedNumPacketsReceived",
918                        stats.packets_received);
919
920   if (!session_was_active)
921     return;
922
923   const HostPortPair& server = server_id.host_port_pair();
924   // Don't try to change the alternate-protocol state, if the
925   // alternate-protocol state is unknown.
926   if (!http_server_properties_->HasAlternateProtocol(server))
927     return;
928
929   // TODO(rch):  In the special case where the session has received no
930   // packets from the peer, we should consider blacklisting this
931   // differently so that we still race TCP but we don't consider the
932   // session connected until the handshake has been confirmed.
933   HistogramBrokenAlternateProtocolLocation(
934       BROKEN_ALTERNATE_PROTOCOL_LOCATION_QUIC_STREAM_FACTORY);
935   PortAlternateProtocolPair alternate =
936       http_server_properties_->GetAlternateProtocol(server);
937   DCHECK_EQ(QUIC, alternate.protocol);
938
939   // Since the session was active, there's no longer an
940   // HttpStreamFactoryImpl::Job running which can mark it broken, unless the
941   // TCP job also fails. So to avoid not using QUIC when we otherwise could,
942   // we mark it as broken, and then immediately re-enable it. This leaves
943   // QUIC as "recently broken" which means that 0-RTT will be disabled but
944   // we'll still race.
945   http_server_properties_->SetBrokenAlternateProtocol(server);
946   http_server_properties_->ClearAlternateProtocol(server);
947   http_server_properties_->SetAlternateProtocol(
948       server, alternate.port, alternate.protocol);
949   DCHECK_EQ(QUIC,
950             http_server_properties_->GetAlternateProtocol(server).protocol);
951   DCHECK(http_server_properties_->WasAlternateProtocolRecentlyBroken(
952       server));
953 }
954
955 }  // namespace net