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