• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2012 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #ifndef NET_QUIC_QUIC_STREAM_FACTORY_H_
6 #define NET_QUIC_QUIC_STREAM_FACTORY_H_
7 
8 #include <stddef.h>
9 #include <stdint.h>
10 
11 #include <map>
12 #include <memory>
13 #include <set>
14 #include <string>
15 #include <vector>
16 
17 #include "base/containers/lru_cache.h"
18 #include "base/gtest_prod_util.h"
19 #include "base/memory/raw_ptr.h"
20 #include "base/memory/weak_ptr.h"
21 #include "base/task/sequenced_task_runner.h"
22 #include "base/time/tick_clock.h"
23 #include "base/time/time.h"
24 #include "net/base/address_list.h"
25 #include "net/base/completion_once_callback.h"
26 #include "net/base/host_port_pair.h"
27 #include "net/base/ip_endpoint.h"
28 #include "net/base/net_export.h"
29 #include "net/base/network_change_notifier.h"
30 #include "net/base/network_handle.h"
31 #include "net/base/proxy_server.h"
32 #include "net/cert/cert_database.h"
33 #include "net/dns/public/secure_dns_policy.h"
34 #include "net/http/http_server_properties.h"
35 #include "net/http/http_stream_factory.h"
36 #include "net/log/net_log_with_source.h"
37 #include "net/quic/network_connection.h"
38 #include "net/quic/quic_chromium_client_session.h"
39 #include "net/quic/quic_clock_skew_detector.h"
40 #include "net/quic/quic_connectivity_monitor.h"
41 #include "net/quic/quic_context.h"
42 #include "net/quic/quic_crypto_client_config_handle.h"
43 #include "net/quic/quic_session_key.h"
44 #include "net/socket/client_socket_pool.h"
45 #include "net/ssl/ssl_config_service.h"
46 #include "net/third_party/quiche/src/quiche/quic/core/deterministic_connection_id_generator.h"
47 #include "net/third_party/quiche/src/quiche/quic/core/quic_config.h"
48 #include "net/third_party/quiche/src/quiche/quic/core/quic_connection_id.h"
49 #include "net/third_party/quiche/src/quiche/quic/core/quic_crypto_stream.h"
50 #include "net/third_party/quiche/src/quiche/quic/core/quic_packets.h"
51 #include "net/third_party/quiche/src/quiche/quic/core/quic_server_id.h"
52 #include "url/scheme_host_port.h"
53 
54 namespace base {
55 class Value;
56 }  // namespace base
57 
58 namespace quic {
59 class QuicAlarmFactory;
60 class QuicClock;
61 }  // namespace quic
62 
63 namespace quiche {
64 class QuicRandom;
65 }  // namespace quiche
66 
67 namespace net {
68 
69 class CTPolicyEnforcer;
70 class CertVerifier;
71 class ClientSocketFactory;
72 class HostResolver;
73 struct HostResolverEndpointResult;
74 class HttpServerProperties;
75 class NetLog;
76 class NetworkAnonymizationKey;
77 class QuicChromiumConnectionHelper;
78 class QuicCryptoClientStreamFactory;
79 class QuicServerInfo;
80 class QuicStreamFactory;
81 class QuicContext;
82 class SCTAuditingDelegate;
83 class SocketPerformanceWatcherFactory;
84 class SocketTag;
85 class TransportSecurityState;
86 
87 namespace test {
88 class QuicStreamFactoryPeer;
89 }  // namespace test
90 
91 // Maximum number of not currently in use QuicCryptoClientConfig that can be
92 // stored in |recent_crypto_config_map_|.
93 //
94 // TODO(mmenke): Should figure out a reasonable value of this, using field
95 // trials. The optimal value may increase over time, as QUIC becomes more
96 // prevalent. Whether or not NetworkAnonymizationKeys end up including subframe
97 // URLs will also influence the ideal value.
98 const int kMaxRecentCryptoConfigs = 100;
99 
100 enum QuicPlatformNotification {
101   NETWORK_CONNECTED,
102   NETWORK_MADE_DEFAULT,
103   NETWORK_DISCONNECTED,
104   NETWORK_SOON_TO_DISCONNECT,
105   NETWORK_IP_ADDRESS_CHANGED,
106   NETWORK_NOTIFICATION_MAX
107 };
108 
109 enum AllActiveSessionsGoingAwayReason {
110   kClockSkewDetected,
111   kIPAddressChanged,
112   kCertDBChanged,
113   kCertVerifierChanged
114 };
115 
116 enum CreateSessionFailure {
117   CREATION_ERROR_CONNECTING_SOCKET,
118   CREATION_ERROR_SETTING_RECEIVE_BUFFER,
119   CREATION_ERROR_SETTING_SEND_BUFFER,
120   CREATION_ERROR_SETTING_DO_NOT_FRAGMENT,
121   CREATION_ERROR_MAX
122 };
123 
124 // Encapsulates a pending request for a QuicChromiumClientSession.
125 // If the request is still pending when it is destroyed, it will
126 // cancel the request with the factory.
127 class NET_EXPORT_PRIVATE QuicStreamRequest {
128  public:
129   explicit QuicStreamRequest(QuicStreamFactory* factory);
130 
131   QuicStreamRequest(const QuicStreamRequest&) = delete;
132   QuicStreamRequest& operator=(const QuicStreamRequest&) = delete;
133 
134   ~QuicStreamRequest();
135 
136   // |cert_verify_flags| is bitwise OR'd of CertVerifier::VerifyFlags and it is
137   // passed to CertVerifier::Verify.
138   // |destination| will be resolved and resulting IPEndPoint used to open a
139   // quic::QuicConnection.  This can be different than
140   // HostPortPair::FromURL(url).
141   // When |use_dns_aliases| is true, any DNS aliases found in host resolution
142   // are stored in the |dns_aliases_by_session_key_| map. |use_dns_aliases|
143   // should be false in the case of a proxy.
144   int Request(url::SchemeHostPort destination,
145               quic::ParsedQuicVersion quic_version,
146               PrivacyMode privacy_mode,
147               RequestPriority priority,
148               const SocketTag& socket_tag,
149               const NetworkAnonymizationKey& network_anonymization_key,
150               SecureDnsPolicy secure_dns_policy,
151               bool use_dns_aliases,
152               bool require_dns_https_alpn,
153               int cert_verify_flags,
154               const GURL& url,
155               const NetLogWithSource& net_log,
156               NetErrorDetails* net_error_details,
157               CompletionOnceCallback failed_on_default_network_callback,
158               CompletionOnceCallback callback);
159 
160   // This function must be called after Request() returns ERR_IO_PENDING.
161   // Returns true if Request() requires host resolution and it hasn't completed
162   // yet. If true is returned, |callback| will run when host resolution
163   // completes. It will be called with the result after host resolution during
164   // the connection process. For example, if host resolution returns OK and then
165   // crypto handshake returns ERR_IO_PENDING, then |callback| will run with
166   // ERR_IO_PENDING.
167   bool WaitForHostResolution(CompletionOnceCallback callback);
168 
169   // Tells QuicStreamRequest it should expect OnHostResolutionComplete()
170   // to be called in the future.
171   void ExpectOnHostResolution();
172 
173   // Will be called by the associated QuicStreamFactory::Job when host
174   // resolution completes asynchronously after Request().
175   void OnHostResolutionComplete(int rv);
176 
177   // This function must be called after Request() returns ERR_IO_PENDING.
178   // Returns true if no QUIC session has been created yet. If true is returned,
179   // `callback` will be run when the QUIC session has been created and will be
180   // called with the result of OnCreateSessionComplete. For example, if session
181   // creation returned OK but CryptoConnect returns ERR_IO_PENDING then
182   // `callback` will be run with ERR_IO_PENDING.
183   bool WaitForQuicSessionCreation(CompletionOnceCallback callback);
184 
185   // Tells QuicStreamRequest it should expect OnQuicSessionCreationComplete()
186   // to be called in the future.
187   void ExpectQuicSessionCreation();
188 
189   // Will be called by the associated QuicStreamFactory::Job when session
190   // creation completes asynchronously after Request().
191   void OnQuicSessionCreationComplete(int rv);
192 
193   void OnRequestComplete(int rv);
194 
195   // Called when the original connection created on the default network for
196   // |this| fails and a new connection has been created on the alternate
197   // network.
198   void OnConnectionFailedOnDefaultNetwork();
199 
200   // Helper method that calls |factory_|'s GetTimeDelayForWaitingJob(). It
201   // returns the amount of time waiting job should be delayed.
202   base::TimeDelta GetTimeDelayForWaitingJob() const;
203 
204   // If host resolution is underway, changes the priority of the host resolver
205   // request.
206   void SetPriority(RequestPriority priority);
207 
208   // Releases the handle to the QUIC session retrieved as a result of Request().
209   std::unique_ptr<QuicChromiumClientSession::Handle> ReleaseSessionHandle();
210 
211   // Sets |session_|.
212   void SetSession(std::unique_ptr<QuicChromiumClientSession::Handle> session);
213 
net_error_details()214   NetErrorDetails* net_error_details() { return net_error_details_; }
215 
session_key()216   const QuicSessionKey& session_key() const { return session_key_; }
217 
net_log()218   const NetLogWithSource& net_log() const { return net_log_; }
219 
220   bool CanUseExistingSession(
221       const GURL& url,
222       PrivacyMode privacy_mode,
223       const SocketTag& socket_tag,
224       const NetworkAnonymizationKey& network_anonymization_key,
225       SecureDnsPolicy secure_dns_policy,
226       bool require_dns_https_alpn,
227       const url::SchemeHostPort& destination) const;
228 
229  private:
230   raw_ptr<QuicStreamFactory> factory_;
231   QuicSessionKey session_key_;
232   NetLogWithSource net_log_;
233   CompletionOnceCallback callback_;
234   CompletionOnceCallback failed_on_default_network_callback_;
235   raw_ptr<NetErrorDetails> net_error_details_;  // Unowned.
236   std::unique_ptr<QuicChromiumClientSession::Handle> session_;
237 
238   // Set in Request(). If true, then OnHostResolutionComplete() is expected to
239   // be called in the future.
240   bool expect_on_host_resolution_ = false;
241 
242   bool expect_on_quic_session_creation_ = false;
243   // Callback passed to WaitForHostResolution().
244   CompletionOnceCallback host_resolution_callback_;
245 
246   CompletionOnceCallback create_session_callback_;
247 };
248 
249 // A factory for fetching QuicChromiumClientSessions.
250 class NET_EXPORT_PRIVATE QuicStreamFactory
251     : public NetworkChangeNotifier::IPAddressObserver,
252       public NetworkChangeNotifier::NetworkObserver,
253       public CertDatabase::Observer,
254       public CertVerifier::Observer {
255  public:
256   // This class encompasses |destination| and |server_id|.
257   // |destination| is a HostPortPair which is resolved
258   // and a quic::QuicConnection is made to the resulting IP address.
259   // |server_id| identifies the origin of the request,
260   // the crypto handshake advertises |server_id.host()| to the server,
261   // and the certificate is also matched against |server_id.host()|.
262   class NET_EXPORT_PRIVATE QuicSessionAliasKey {
263    public:
264     QuicSessionAliasKey() = default;
265     QuicSessionAliasKey(url::SchemeHostPort destination,
266                         QuicSessionKey session_key);
267     ~QuicSessionAliasKey() = default;
268 
269     // Needed to be an element of std::set.
270     bool operator<(const QuicSessionAliasKey& other) const;
271     bool operator==(const QuicSessionAliasKey& other) const;
272 
destination()273     const url::SchemeHostPort& destination() const { return destination_; }
server_id()274     const quic::QuicServerId& server_id() const {
275       return session_key_.server_id();
276     }
session_key()277     const QuicSessionKey& session_key() const { return session_key_; }
278 
279     // Returns the estimate of dynamically allocated memory in bytes.
280 
281    private:
282     url::SchemeHostPort destination_;
283     QuicSessionKey session_key_;
284   };
285 
286   QuicStreamFactory(
287       NetLog* net_log,
288       HostResolver* host_resolver,
289       SSLConfigService* ssl_config_service,
290       ClientSocketFactory* client_socket_factory,
291       HttpServerProperties* http_server_properties,
292       CertVerifier* cert_verifier,
293       CTPolicyEnforcer* ct_policy_enforcer,
294       TransportSecurityState* transport_security_state,
295       SCTAuditingDelegate* sct_auditing_delegate,
296       SocketPerformanceWatcherFactory* socket_performance_watcher_factory,
297       QuicCryptoClientStreamFactory* quic_crypto_client_stream_factory,
298       QuicContext* context);
299 
300   QuicStreamFactory(const QuicStreamFactory&) = delete;
301   QuicStreamFactory& operator=(const QuicStreamFactory&) = delete;
302 
303   ~QuicStreamFactory() override;
304 
305   // Returns true if there is an existing session for |session_key| or if the
306   // request can be pooled to an existing session to the IP address of
307   // |destination|.
308   bool CanUseExistingSession(const QuicSessionKey& session_key,
309                              const url::SchemeHostPort& destination) const;
310 
311   // Fetches a QuicChromiumClientSession to |host_port_pair| which will be
312   // owned by |request|.
313   // If a matching session already exists, this method will return OK.  If no
314   // matching session exists, this will return ERR_IO_PENDING and will invoke
315   // OnRequestComplete asynchronously.
316   // When |use_dns_aliases| is true, any DNS aliases found in host resolution
317   // are stored in the |dns_aliases_by_session_key_| map. |use_dns_aliases|
318   // should be false in the case of a proxy.
319   int Create(const QuicSessionKey& session_key,
320              url::SchemeHostPort destination,
321              quic::ParsedQuicVersion quic_version,
322              RequestPriority priority,
323              bool use_dns_aliases,
324              int cert_verify_flags,
325              const GURL& url,
326              const NetLogWithSource& net_log,
327              QuicStreamRequest* request);
328 
329   // Called by a session when it is going away and no more streams should be
330   // created on it.
331   void OnSessionGoingAway(QuicChromiumClientSession* session);
332 
333   // Called by a session after it shuts down.
334   void OnSessionClosed(QuicChromiumClientSession* session);
335 
336   // Called by a session when it blackholes after the handshake is confirmed.
337   void OnBlackholeAfterHandshakeConfirmed(QuicChromiumClientSession* session);
338 
339   // Cancels a pending request.
340   void CancelRequest(QuicStreamRequest* request);
341 
342   // Sets priority of a request.
343   void SetRequestPriority(QuicStreamRequest* request, RequestPriority priority);
344 
345   // Closes all current sessions with specified network, QUIC error codes.
346   // It sends connection close packet when closing connections.
347   void CloseAllSessions(int error, quic::QuicErrorCode quic_error);
348 
349   base::Value QuicStreamFactoryInfoToValue() const;
350 
351   // Delete cached state objects in |crypto_config_|. If |origin_filter| is not
352   // null, only objects on matching origins will be deleted.
353   void ClearCachedStatesInCryptoConfig(
354       const base::RepeatingCallback<bool(const GURL&)>& origin_filter);
355 
356   // Helper method that connects a DatagramClientSocket. Socket is
357   // bound to the default network if the |network| param is
358   // handles::kInvalidNetworkHandle. This method calls
359   // DatagramClientSocket::ConnectAsync and completes asynchronously. Returns
360   // ERR_IO_PENDING.
361   int ConnectAndConfigureSocket(CompletionOnceCallback callback,
362                                 DatagramClientSocket* socket,
363                                 IPEndPoint addr,
364                                 handles::NetworkHandle network,
365                                 const SocketTag& socket_tag);
366 
367   // Helper method that configures a DatagramClientSocket once
368   // DatagramClientSocket::ConnectAsync completes. Posts a task to run
369   // `callback` with a net_error code.
370   virtual void FinishConnectAndConfigureSocket(CompletionOnceCallback callback,
371                                                DatagramClientSocket* socket,
372                                                const SocketTag& socket_tag,
373                                                int rv);
374 
375   void OnFinishConnectAndConfigureSocketError(CompletionOnceCallback callback,
376                                               enum CreateSessionFailure error,
377                                               int rv);
378 
379   void DoCallback(CompletionOnceCallback callback, int rv);
380 
381   // Helper method that configures a DatagramClientSocket. Socket is
382   // bound to the default network if the |network| param is
383   // handles::kInvalidNetworkHandle. This method calls
384   // DatagramClientSocket::Connect and completes synchronously. Returns
385   // net_error code.
386   // TODO(liza): Remove this once QuicStreamFactory::Job calls
387   // ConnectAndConfigureSocket.
388   int ConfigureSocket(DatagramClientSocket* socket,
389                       IPEndPoint addr,
390                       handles::NetworkHandle network,
391                       const SocketTag& socket_tag);
392 
393   // Finds an alternative to |old_network| from the platform's list of connected
394   // networks. Returns handles::kInvalidNetworkHandle if no
395   // alternative is found.
396   handles::NetworkHandle FindAlternateNetwork(
397       handles::NetworkHandle old_network);
398 
399   // Creates a datagram socket. |source| is the NetLogSource for the entity
400   // trying to create the socket, if it has one.
401   std::unique_ptr<DatagramClientSocket> CreateSocket(
402       NetLog* net_log,
403       const NetLogSource& source);
404 
405   // NetworkChangeNotifier::IPAddressObserver methods:
406 
407   // Until the servers support roaming, close all connections when the local
408   // IP address changes.
409   void OnIPAddressChanged() override;
410 
411   // NetworkChangeNotifier::NetworkObserver methods:
412   void OnNetworkConnected(handles::NetworkHandle network) override;
413   void OnNetworkDisconnected(handles::NetworkHandle network) override;
414   void OnNetworkSoonToDisconnect(handles::NetworkHandle network) override;
415   void OnNetworkMadeDefault(handles::NetworkHandle network) override;
416 
417   // CertDatabase::Observer methods:
418 
419   // We close all sessions when certificate database is changed.
420   void OnCertDBChanged() override;
421 
422   // CertVerifier::Observer:
423   // We close all sessions when certificate verifier settings have changed.
424   void OnCertVerifierChanged() override;
425 
is_quic_known_to_work_on_current_network()426   bool is_quic_known_to_work_on_current_network() const {
427     return is_quic_known_to_work_on_current_network_;
428   }
429 
allow_server_migration()430   bool allow_server_migration() const { return params_.allow_server_migration; }
431 
432   // Returns true is gQUIC 0-RTT is disabled from quic_context.
gquic_zero_rtt_disabled()433   bool gquic_zero_rtt_disabled() const {
434     return params_.disable_gquic_zero_rtt;
435   }
436 
437   void set_is_quic_known_to_work_on_current_network(
438       bool is_quic_known_to_work_on_current_network);
439 
440   // It returns the amount of time waiting job should be delayed.
441   base::TimeDelta GetTimeDelayForWaitingJob(const QuicSessionKey& session_key);
442 
helper()443   QuicChromiumConnectionHelper* helper() { return helper_.get(); }
444 
alarm_factory()445   quic::QuicAlarmFactory* alarm_factory() { return alarm_factory_.get(); }
446 
set_server_push_delegate(ServerPushDelegate * push_delegate)447   void set_server_push_delegate(ServerPushDelegate* push_delegate) {
448     push_delegate_ = push_delegate;
449   }
450 
default_network()451   handles::NetworkHandle default_network() const { return default_network_; }
452 
453   // Returns the stored DNS aliases for the session key.
454   const std::set<std::string>& GetDnsAliasesForSessionKey(
455       const QuicSessionKey& key) const;
456 
457  private:
458   class Job;
459   class QuicCryptoClientConfigOwner;
460   class CryptoClientConfigHandle;
461   friend class MockQuicStreamFactory;
462   friend class test::QuicStreamFactoryPeer;
463 
464   using SessionMap = std::map<QuicSessionKey, QuicChromiumClientSession*>;
465   using SessionIdMap =
466       std::map<QuicChromiumClientSession*, QuicSessionAliasKey>;
467   using AliasSet = std::set<QuicSessionAliasKey>;
468   using SessionAliasMap = std::map<QuicChromiumClientSession*, AliasSet>;
469   using SessionSet = std::set<QuicChromiumClientSession*>;
470   using IPAliasMap = std::map<IPEndPoint, SessionSet>;
471   using SessionPeerIPMap = std::map<QuicChromiumClientSession*, IPEndPoint>;
472   using JobMap = std::map<QuicSessionKey, std::unique_ptr<Job>>;
473   using DnsAliasesBySessionKeyMap =
474       std::map<QuicSessionKey, std::set<std::string>>;
475   using QuicCryptoClientConfigMap =
476       std::map<NetworkAnonymizationKey,
477                std::unique_ptr<QuicCryptoClientConfigOwner>>;
478 
479   bool HasMatchingIpSession(const QuicSessionAliasKey& key,
480                             const std::vector<IPEndPoint>& ip_endpoints,
481                             const std::set<std::string>& aliases,
482                             bool use_dns_aliases);
483   void OnJobComplete(Job* job, int rv);
484   bool HasActiveSession(const QuicSessionKey& session_key) const;
485   bool HasActiveJob(const QuicSessionKey& session_key) const;
486   int CreateSessionSync(const QuicSessionAliasKey& key,
487                         quic::ParsedQuicVersion quic_version,
488                         int cert_verify_flags,
489                         bool require_confirmation,
490                         const HostResolverEndpointResult& endpoint_result,
491                         base::TimeTicks dns_resolution_start_time,
492                         base::TimeTicks dns_resolution_end_time,
493                         const NetLogWithSource& net_log,
494                         QuicChromiumClientSession** session,
495                         handles::NetworkHandle* network);
496   int CreateSessionAsync(CompletionOnceCallback callback,
497                          const QuicSessionAliasKey& key,
498                          quic::ParsedQuicVersion quic_version,
499                          int cert_verify_flags,
500                          bool require_confirmation,
501                          const HostResolverEndpointResult& endpoint_result,
502                          base::TimeTicks dns_resolution_start_time,
503                          base::TimeTicks dns_resolution_end_time,
504                          const NetLogWithSource& net_log,
505                          QuicChromiumClientSession** session,
506                          handles::NetworkHandle* network);
507   void FinishCreateSession(CompletionOnceCallback callback,
508                            const QuicSessionAliasKey& key,
509                            quic::ParsedQuicVersion quic_version,
510                            int cert_verify_flags,
511                            bool require_confirmation,
512                            const HostResolverEndpointResult& endpoint_result,
513                            base::TimeTicks dns_resolution_start_time,
514                            base::TimeTicks dns_resolution_end_time,
515                            const NetLogWithSource& net_log,
516                            QuicChromiumClientSession** session,
517                            handles::NetworkHandle* network,
518                            std::unique_ptr<DatagramClientSocket> socket,
519                            int rv);
520   bool CreateSessionHelper(const QuicSessionAliasKey& key,
521                            quic::ParsedQuicVersion quic_version,
522                            int cert_verify_flags,
523                            bool require_confirmation,
524                            const HostResolverEndpointResult& endpoint_result,
525                            base::TimeTicks dns_resolution_start_time,
526                            base::TimeTicks dns_resolution_end_time,
527                            const NetLogWithSource& net_log,
528                            QuicChromiumClientSession** session,
529                            handles::NetworkHandle* network,
530                            std::unique_ptr<DatagramClientSocket> socket);
531   void ActivateSession(const QuicSessionAliasKey& key,
532                        QuicChromiumClientSession* session,
533                        std::set<std::string> dns_aliases);
534   // Go away all active sessions. May disable session's connectivity monitoring
535   // based on the |reason|.
536   void MarkAllActiveSessionsGoingAway(AllActiveSessionsGoingAwayReason reason);
537 
538   void ConfigureInitialRttEstimate(
539       const quic::QuicServerId& server_id,
540       const NetworkAnonymizationKey& network_anonymization_key,
541       quic::QuicConfig* config);
542 
543   // Returns |srtt| in micro seconds from ServerNetworkStats. Returns 0 if there
544   // is no |http_server_properties_| or if |http_server_properties_| doesn't
545   // have ServerNetworkStats for the given |server_id|.
546   int64_t GetServerNetworkStatsSmoothedRttInMicroseconds(
547       const quic::QuicServerId& server_id,
548       const NetworkAnonymizationKey& network_anonymization_key) const;
549 
550   // Returns |srtt| from ServerNetworkStats. Returns null if there
551   // is no |http_server_properties_| or if |http_server_properties_| doesn't
552   // have ServerNetworkStats for the given |server_id|.
553   const base::TimeDelta* GetServerNetworkStatsSmoothedRtt(
554       const quic::QuicServerId& server_id,
555       const NetworkAnonymizationKey& network_anonymization_key) const;
556 
557   // Helper methods.
558   bool WasQuicRecentlyBroken(const QuicSessionKey& session_key) const;
559 
560   // Helper method to initialize the following migration options and check
561   // pre-requisites:
562   // - |params_.migrate_sessions_on_network_change_v2|
563   // - |params_.migrate_sessions_early_v2|
564   // - |params_.migrate_idle_sessions|
565   // - |params_.retry_on_alternate_network_before_handshake|
566   // If pre-requisites are not met, turn off the corresponding options.
567   void InitializeMigrationOptions();
568 
569   // Initializes the cached state associated with |server_id| in
570   // |crypto_config_| with the information in |server_info|.
571   void InitializeCachedStateInCryptoConfig(
572       const CryptoClientConfigHandle& crypto_config_handle,
573       const quic::QuicServerId& server_id,
574       const std::unique_ptr<QuicServerInfo>& server_info);
575 
576   void ProcessGoingAwaySession(QuicChromiumClientSession* session,
577                                const quic::QuicServerId& server_id,
578                                bool was_session_active);
579 
580   // Insert the given alias `key` in the AliasSet for the given `session` in
581   // the map `session_aliases_`, and add the given `dns_aliases` for
582   // `key.session_key()` in `dns_aliases_by_session_key_`.
583   void MapSessionToAliasKey(QuicChromiumClientSession* session,
584                             const QuicSessionAliasKey& key,
585                             std::set<std::string> dns_aliases);
586 
587   // For all alias keys for `session` in `session_aliases_`, erase the
588   // corresponding DNS aliases in `dns_aliases_by_session_key_`. Then erase
589   // `session` from `session_aliases_`.
590   void UnmapSessionFromSessionAliases(QuicChromiumClientSession* session);
591 
592   // Creates a CreateCryptoConfigHandle for the specified
593   // NetworkAnonymizationKey. If there's already a corresponding entry in
594   // |active_crypto_config_map_|, reuses it. If there's a corresponding entry in
595   // |recent_crypto_config_map_|, promotes it to |active_crypto_config_map_| and
596   // then reuses it. Otherwise, creates a new entry in
597   // |active_crypto_config_map_|.
598   std::unique_ptr<CryptoClientConfigHandle> CreateCryptoConfigHandle(
599       const NetworkAnonymizationKey& network_anonymization_key);
600 
601   // Salled when the indicated member of |active_crypto_config_map_| has no
602   // outstanding references. The QuicCryptoClientConfigOwner is then moved to
603   // |recent_crypto_config_map_|, an MRU cache.
604   void OnAllCryptoClientRefReleased(
605       QuicCryptoClientConfigMap::iterator& map_iterator);
606 
607   // Called when a network change happens.
608   // Collect platform notification metrics, and if the change affects the
609   // original default network interface, collect connectivity degradation
610   // metrics from |connectivity_monitor_| and add to histograms.
611   void CollectDataOnPlatformNotification(
612       enum QuicPlatformNotification notification,
613       handles::NetworkHandle affected_network) const;
614 
615   std::unique_ptr<QuicCryptoClientConfigHandle> GetCryptoConfigForTesting(
616       const NetworkAnonymizationKey& network_anonymization_key);
617 
618   bool CryptoConfigCacheIsEmptyForTesting(
619       const quic::QuicServerId& server_id,
620       const NetworkAnonymizationKey& network_anonymization_key);
621 
supported_versions()622   const quic::ParsedQuicVersionVector& supported_versions() const {
623     return params_.supported_versions;
624   }
625 
626   // Whether QUIC is known to work on current network. This is true when QUIC is
627   // expected to work in general, rather than whether QUIC was broken / recently
628   // broken when used with a particular server. That information is stored in
629   // the broken alternative service map in HttpServerProperties.
630   bool is_quic_known_to_work_on_current_network_ = false;
631 
632   raw_ptr<NetLog> net_log_;
633   raw_ptr<HostResolver> host_resolver_;
634   raw_ptr<ClientSocketFactory> client_socket_factory_;
635   raw_ptr<HttpServerProperties> http_server_properties_;
636   raw_ptr<ServerPushDelegate> push_delegate_ = nullptr;
637   const raw_ptr<CertVerifier> cert_verifier_;
638   const raw_ptr<CTPolicyEnforcer> ct_policy_enforcer_;
639   const raw_ptr<TransportSecurityState> transport_security_state_;
640   const raw_ptr<SCTAuditingDelegate> sct_auditing_delegate_;
641   raw_ptr<QuicCryptoClientStreamFactory> quic_crypto_client_stream_factory_;
642   raw_ptr<quic::QuicRandom> random_generator_;  // Unowned.
643   raw_ptr<const quic::QuicClock> clock_;        // Unowned.
644   QuicParams params_;
645   QuicClockSkewDetector clock_skew_detector_;
646 
647   // Factory which is used to create socket performance watcher. A new watcher
648   // is created for every QUIC connection.
649   // |socket_performance_watcher_factory_| may be null.
650   raw_ptr<SocketPerformanceWatcherFactory> socket_performance_watcher_factory_;
651 
652   // The helper used for all connections.
653   std::unique_ptr<QuicChromiumConnectionHelper> helper_;
654 
655   // The alarm factory used for all connections.
656   std::unique_ptr<quic::QuicAlarmFactory> alarm_factory_;
657 
658   // Contains owning pointers to all sessions that currently exist.
659   SessionIdMap all_sessions_;
660   // Contains non-owning pointers to currently active session
661   // (not going away session, once they're implemented).
662   SessionMap active_sessions_;
663   // Map from session to set of aliases that this session is known by.
664   SessionAliasMap session_aliases_;
665   // Map from IP address to sessions which are connected to this address.
666   IPAliasMap ip_aliases_;
667   // Map from session to its original peer IP address.
668   SessionPeerIPMap session_peer_ip_;
669 
670   // Origins which have gone away recently.
671   AliasSet gone_away_aliases_;
672 
673   // A map of DNS alias vectors by session keys.
674   DnsAliasesBySessionKeyMap dns_aliases_by_session_key_;
675 
676   // When a QuicCryptoClientConfig is in use, it has one or more live
677   // CryptoClientConfigHandles, and is stored in |active_crypto_config_map_|.
678   // Once all the handles are deleted, it's moved to
679   // |recent_crypto_config_map_|. If reused before it is evicted from LRUCache,
680   // it will be removed from the cache and return to the active config map.
681   // These two maps should never both have entries with the same
682   // NetworkAnonymizationKey.
683   QuicCryptoClientConfigMap active_crypto_config_map_;
684   base::LRUCache<NetworkAnonymizationKey,
685                  std::unique_ptr<QuicCryptoClientConfigOwner>>
686       recent_crypto_config_map_;
687 
688   const quic::QuicConfig config_;
689 
690   JobMap active_jobs_;
691 
692   // PING timeout for connections.
693   quic::QuicTime::Delta ping_timeout_;
694   quic::QuicTime::Delta reduced_ping_timeout_;
695 
696   // Timeout for how long the wire can have no retransmittable packets.
697   quic::QuicTime::Delta retransmittable_on_wire_timeout_;
698 
699   // If more than |yield_after_packets_| packets have been read or more than
700   // |yield_after_duration_| time has passed, then
701   // QuicChromiumPacketReader::StartReading() yields by doing a PostTask().
702   int yield_after_packets_;
703   quic::QuicTime::Delta yield_after_duration_;
704 
705   // If |migrate_sessions_early_v2_| is true, tracks the current default
706   // network, and is updated OnNetworkMadeDefault.
707   // Otherwise, always set to NetworkChangeNotifier::kInvalidNetwork.
708   handles::NetworkHandle default_network_;
709 
710   // Local address of socket that was created in CreateSession.
711   IPEndPoint local_address_;
712   // True if we need to check HttpServerProperties if QUIC was supported last
713   // time.
714   bool need_to_check_persisted_supports_quic_ = true;
715   bool prefer_aes_gcm_recorded_ = false;
716 
717   NetworkConnection network_connection_;
718 
719   int num_push_streams_created_ = 0;
720 
721   QuicConnectivityMonitor connectivity_monitor_;
722 
723   raw_ptr<const base::TickClock> tick_clock_ = nullptr;
724 
725   raw_ptr<base::SequencedTaskRunner> task_runner_ = nullptr;
726 
727   const raw_ptr<SSLConfigService> ssl_config_service_;
728 
729   // Whether NetworkAnonymizationKeys should be used for
730   // |active_crypto_config_map_|. If false, there will just be one config with
731   // an empty NetworkAnonymizationKey. Whether QuicSessionAliasKeys all have an
732   // empty NIK is based on whether socket pools are respecting NIKs, but whether
733   // those NIKs are also used when accessing |active_crypto_config_map_| is also
734   // gated this, which is set based on whether HttpServerProperties is
735   // respecting NIKs, as that data is fed into the crypto config map using the
736   // corresponding NIK.
737   const bool use_network_anonymization_key_for_crypto_configs_;
738 
739   quic::DeterministicConnectionIdGenerator connection_id_generator_{
740       quic::kQuicDefaultConnectionIdLength};
741 
742   base::WeakPtrFactory<QuicStreamFactory> weak_factory_{this};
743 };
744 
745 }  // namespace net
746 
747 #endif  // NET_QUIC_QUIC_STREAM_FACTORY_H_
748