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