• 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 // A client specific quic::QuicSession subclass.  This class owns the underlying
6 // quic::QuicConnection and QuicConnectionHelper objects.  The connection stores
7 // a non-owning pointer to the helper so this session needs to ensure that
8 // the helper outlives the connection.
9 
10 #ifndef NET_QUIC_QUIC_CHROMIUM_CLIENT_SESSION_H_
11 #define NET_QUIC_QUIC_CHROMIUM_CLIENT_SESSION_H_
12 
13 #include <stddef.h>
14 
15 #include <list>
16 #include <memory>
17 #include <set>
18 #include <string>
19 #include <vector>
20 
21 #include "base/containers/flat_map.h"
22 #include "base/memory/raw_ptr.h"
23 #include "base/memory/raw_ptr_exclusion.h"
24 #include "base/observer_list.h"
25 #include "base/observer_list_types.h"
26 #include "base/strings/string_piece.h"
27 #include "base/task/sequenced_task_runner.h"
28 #include "base/time/time.h"
29 #include "base/timer/timer.h"
30 #include "base/values.h"
31 #include "net/base/completion_once_callback.h"
32 #include "net/base/load_timing_info.h"
33 #include "net/base/net_error_details.h"
34 #include "net/base/net_export.h"
35 #include "net/base/network_handle.h"
36 #include "net/log/net_log_with_source.h"
37 #include "net/net_buildflags.h"
38 #include "net/quic/quic_chromium_client_stream.h"
39 #include "net/quic/quic_chromium_packet_reader.h"
40 #include "net/quic/quic_chromium_packet_writer.h"
41 #include "net/quic/quic_connection_logger.h"
42 #include "net/quic/quic_crypto_client_config_handle.h"
43 #include "net/quic/quic_http3_logger.h"
44 #include "net/quic/quic_session_key.h"
45 #include "net/socket/socket_performance_watcher.h"
46 #include "net/spdy/http2_priority_dependencies.h"
47 #include "net/spdy/multiplexed_session.h"
48 #include "net/third_party/quiche/src/quiche/quic/core/http/quic_spdy_client_session_base.h"
49 #include "net/third_party/quiche/src/quiche/quic/core/quic_crypto_client_stream.h"
50 #include "net/third_party/quiche/src/quiche/quic/core/quic_packet_writer.h"
51 #include "net/third_party/quiche/src/quiche/quic/core/quic_packets.h"
52 #include "net/third_party/quiche/src/quiche/quic/core/quic_path_validator.h"
53 #include "net/third_party/quiche/src/quiche/quic/core/quic_server_id.h"
54 #include "net/third_party/quiche/src/quiche/quic/core/quic_time.h"
55 #include "net/traffic_annotation/network_traffic_annotation.h"
56 #include "url/origin.h"
57 #include "url/scheme_host_port.h"
58 
59 #if BUILDFLAG(ENABLE_WEBSOCKETS)
60 #include "net/websockets/websocket_basic_stream_adapters.h"
61 #endif  // BUILDFLAG(ENABLE_WEBSOCKETS)
62 
63 namespace net {
64 
65 class CertVerifyResult;
66 class DatagramClientSocket;
67 struct HostResolverEndpointResult;
68 class NetLog;
69 class QuicCryptoClientStreamFactory;
70 class QuicServerInfo;
71 class QuicStreamFactory;
72 class SSLConfigService;
73 class SSLInfo;
74 class TransportSecurityState;
75 
76 namespace test {
77 class QuicChromiumClientSessionPeer;
78 }  // namespace test
79 
80 // SETTINGS_MAX_HEADERS_LIST_SIZE, the maximum size of uncompressed QUIC headers
81 // that the server is allowed to send.
82 const size_t kQuicMaxHeaderListSize = 256 * 1024;
83 
84 // Result of a session migration attempt.
85 enum class MigrationResult {
86   SUCCESS,         // Migration succeeded.
87   NO_NEW_NETWORK,  // Migration failed since no new network was found.
88   FAILURE,         // Migration failed for other reasons.
89 };
90 
91 // Mode of connection migration.
92 enum class ConnectionMigrationMode {
93   NO_MIGRATION,
94   NO_MIGRATION_ON_PATH_DEGRADING_V1,
95   FULL_MIGRATION_V1,
96   NO_MIGRATION_ON_PATH_DEGRADING_V2,
97   FULL_MIGRATION_V2
98 };
99 
100 // Cause of a migration.
101 enum MigrationCause {
102   UNKNOWN_CAUSE,
103   ON_NETWORK_CONNECTED,                       // No probing.
104   ON_NETWORK_DISCONNECTED,                    // No probing.
105   ON_WRITE_ERROR,                             // No probing.
106   ON_NETWORK_MADE_DEFAULT,                    // With probing.
107   ON_MIGRATE_BACK_TO_DEFAULT_NETWORK,         // With probing.
108   CHANGE_NETWORK_ON_PATH_DEGRADING,           // With probing.
109   CHANGE_PORT_ON_PATH_DEGRADING,              // With probing.
110   NEW_NETWORK_CONNECTED_POST_PATH_DEGRADING,  // With probing.
111   ON_SERVER_PREFERRED_ADDRESS_AVAILABLE,      // With probing.
112   MIGRATION_CAUSE_MAX
113 };
114 
115 // Result of connection migration.
116 enum QuicConnectionMigrationStatus {
117   MIGRATION_STATUS_NO_MIGRATABLE_STREAMS,
118   MIGRATION_STATUS_ALREADY_MIGRATED,
119   MIGRATION_STATUS_INTERNAL_ERROR,
120   MIGRATION_STATUS_TOO_MANY_CHANGES,
121   MIGRATION_STATUS_SUCCESS,
122   MIGRATION_STATUS_NON_MIGRATABLE_STREAM,
123   MIGRATION_STATUS_NOT_ENABLED,
124   MIGRATION_STATUS_NO_ALTERNATE_NETWORK,
125   MIGRATION_STATUS_ON_PATH_DEGRADING_DISABLED,
126   MIGRATION_STATUS_DISABLED_BY_CONFIG,
127   MIGRATION_STATUS_PATH_DEGRADING_NOT_ENABLED,
128   MIGRATION_STATUS_TIMEOUT,
129   MIGRATION_STATUS_ON_WRITE_ERROR_DISABLED,
130   MIGRATION_STATUS_PATH_DEGRADING_BEFORE_HANDSHAKE_CONFIRMED,
131   MIGRATION_STATUS_IDLE_MIGRATION_TIMEOUT,
132   MIGRATION_STATUS_NO_UNUSED_CONNECTION_ID,
133   MIGRATION_STATUS_MAX
134 };
135 
136 // Result of a connectivity probing attempt.
137 enum class ProbingResult {
138   PENDING,                          // Probing started, pending result.
139   DISABLED_WITH_IDLE_SESSION,       // Probing disabled with idle session.
140   DISABLED_BY_CONFIG,               // Probing disabled by config.
141   DISABLED_BY_NON_MIGRABLE_STREAM,  // Probing disabled by special stream.
142   INTERNAL_ERROR,                   // Probing failed for internal reason.
143   FAILURE,                          // Probing failed for other reason.
144 };
145 
146 class NET_EXPORT_PRIVATE QuicChromiumClientSession
147     : public quic::QuicSpdyClientSessionBase,
148       public MultiplexedSession,
149       public QuicChromiumPacketReader::Visitor,
150       public QuicChromiumPacketWriter::Delegate {
151  public:
152   // Sets a callback that is called in the middle of a connection migration.
153   // Only for testing.
154   static void SetMidMigrationCallbackForTesting(base::OnceClosure callback);
155 
156   class StreamRequest;
157 
158   // An interface that when implemented and added via
159   // AddConnectivityObserver(), provides notifications when connectivity
160   // quality changes.
161   class NET_EXPORT_PRIVATE ConnectivityObserver : public base::CheckedObserver {
162    public:
163     // Called when path degrading is detected on |network|.
164     virtual void OnSessionPathDegrading(QuicChromiumClientSession* session,
165                                         handles::NetworkHandle network) = 0;
166 
167     // Called when forward progress is made after path degrading on |network|.
168     virtual void OnSessionResumedPostPathDegrading(
169         QuicChromiumClientSession* session,
170         handles::NetworkHandle network) = 0;
171 
172     // Called when |session| encounters write error on |network|.
173     // A write error may be caused by the change in the underlying network
174     // interface, and can be pre-emptive hints of connectivity quality changes
175     // based on the |error_code|.
176     virtual void OnSessionEncounteringWriteError(
177         QuicChromiumClientSession* session,
178         handles::NetworkHandle network,
179         int error_code) = 0;
180 
181     // Called when |session| is closed by |source| with |error_code|
182     // and handshake has been confirmed.
183     virtual void OnSessionClosedAfterHandshake(
184         QuicChromiumClientSession* session,
185         handles::NetworkHandle network,
186         quic::ConnectionCloseSource source,
187         quic::QuicErrorCode error_code) = 0;
188 
189     // Called when |this| is registered to monitor the connectivity of the
190     // |session|.
191     virtual void OnSessionRegistered(QuicChromiumClientSession* session,
192                                      handles::NetworkHandle network) = 0;
193 
194     // Called when |session| is removed.
195     virtual void OnSessionRemoved(QuicChromiumClientSession* session) = 0;
196   };
197 
198   // Wrapper for interacting with the session in a restricted fashion which
199   // hides the details of the underlying session's lifetime. All methods of
200   // the Handle are safe to use even after the underlying session is destroyed.
201   class NET_EXPORT_PRIVATE Handle : public MultiplexedSessionHandle {
202    public:
203     // Constructs a handle to |session| which was created via the alternative
204     // server |destination|.
205     Handle(const base::WeakPtr<QuicChromiumClientSession>& session,
206            url::SchemeHostPort destination);
207     Handle(const Handle& other) = delete;
208     ~Handle() override;
209 
210     // Returns true if the session is still connected.
211     bool IsConnected() const;
212 
213     // Returns true if the handshake has been confirmed.
214     bool OneRttKeysAvailable() const;
215 
216     // Starts a request to create a stream.  If OK is returned, then
217     // |stream_| will be updated with the newly created stream.  If
218     // ERR_IO_PENDING is returned, then when the request is eventuallly
219     // complete |callback| will be called.
220     int RequestStream(bool requires_confirmation,
221                       CompletionOnceCallback callback,
222                       const NetworkTrafficAnnotationTag& traffic_annotation);
223 
224     // Releases |stream_| to the caller. Returns nullptr if the underlying
225     // QuicChromiumClientSession is closed.
226     std::unique_ptr<QuicChromiumClientStream::Handle> ReleaseStream();
227 
228     // Returns a new packet bundler while will cause writes to be batched up
229     // until a packet is full, or the last bundler is destroyed.
230     std::unique_ptr<quic::QuicConnection::ScopedPacketFlusher>
231     CreatePacketBundler();
232 
233     // Populates network error details for this session.
234     void PopulateNetErrorDetails(NetErrorDetails* details) const;
235 
236     // Returns the connection timing for the handshake of this session.
237     const LoadTimingInfo::ConnectTiming& GetConnectTiming();
238 
239     // Returns true if |other| is a handle to the same session as this handle.
240     bool SharesSameSession(const Handle& other) const;
241 
242     // Returns the QUIC version used by the session.
243     quic::ParsedQuicVersion GetQuicVersion() const;
244 
245     // Copies the remote udp address into |address| and returns a net error
246     // code.
247     int GetPeerAddress(IPEndPoint* address) const;
248 
249     // Copies the local udp address into |address| and returns a net error
250     // code.
251     int GetSelfAddress(IPEndPoint* address) const;
252 
253     // Returns the session's server ID.
server_id()254     quic::QuicServerId server_id() const { return server_id_; }
255 
256     // Returns the alternative server used for this session.
destination()257     const url::SchemeHostPort& destination() const { return destination_; }
258 
259     // Returns the session's net log.
net_log()260     const NetLogWithSource& net_log() const { return net_log_; }
261 
262     // Returns the session's connection migration mode.
connection_migration_mode()263     ConnectionMigrationMode connection_migration_mode() const {
264       return session_->connection_migration_mode();
265     }
266 
267     // Returns true if the session's connection has sent or received any bytes.
268     bool WasEverUsed() const;
269 
270     // Retrieves any DNS aliases for the given session key from the map stored
271     // in `stream_factory_`. Includes all known aliases, e.g. from A, AAAA, or
272     // HTTPS, not just from the address used for the connection, in no
273     // particular order.
274     const std::set<std::string>& GetDnsAliasesForSessionKey(
275         const QuicSessionKey& key) const;
276 
277 #if BUILDFLAG(ENABLE_WEBSOCKETS)
278     // This method returns nullptr on failure, such as when a new bidirectional
279     // stream could not be made.
280     std::unique_ptr<WebSocketQuicStreamAdapter>
281     CreateWebSocketQuicStreamAdapter(
282         WebSocketQuicStreamAdapter::Delegate* delegate,
283         base::OnceCallback<void(std::unique_ptr<WebSocketQuicStreamAdapter>)>
284             callback,
285         const NetworkTrafficAnnotationTag& traffic_annotation);
286 #endif  // BUILDFLAG(ENABLE_WEBSOCKETS)
287 
288    private:
289     friend class QuicChromiumClientSession;
290     friend class QuicChromiumClientSession::StreamRequest;
291 
292     // Waits for the handshake to be confirmed and invokes |callback| when
293     // that happens. If the handshake has already been confirmed, returns OK.
294     // If the connection has already been closed, returns a net error. If the
295     // connection closes before the handshake is confirmed, |callback| will
296     // be invoked with an error.
297     int WaitForHandshakeConfirmation(CompletionOnceCallback callback);
298 
299     // Called when the handshake is confirmed.
300     void OnCryptoHandshakeConfirmed();
301 
302     // Called when the session is closed with a net error.
303     void OnSessionClosed(quic::ParsedQuicVersion quic_version,
304                          int net_error,
305                          quic::QuicErrorCode quic_error,
306                          bool port_migration_detected,
307                          bool quic_connection_migration_attempted,
308                          bool quic_connection_migration_successful,
309                          LoadTimingInfo::ConnectTiming connect_timing,
310                          bool was_ever_used);
311 
312     // Called by |request| to create a stream.
313     int TryCreateStream(StreamRequest* request);
314 
315     // Called by |request| to cancel stream request.
316     void CancelRequest(StreamRequest* request);
317 
318     // Underlying session which may be destroyed before this handle.
319     base::WeakPtr<QuicChromiumClientSession> session_;
320 
321     url::SchemeHostPort destination_;
322 
323     // Stream request created by |RequestStream()|.
324     std::unique_ptr<StreamRequest> stream_request_;
325 
326     // Information saved from the session which can be used even after the
327     // session is destroyed.
328     NetLogWithSource net_log_;
329     bool was_handshake_confirmed_;
330     int net_error_ = OK;
331     quic::QuicErrorCode quic_error_ = quic::QUIC_NO_ERROR;
332     bool port_migration_detected_ = false;
333     bool quic_connection_migration_attempted_ = false;
334     bool quic_connection_migration_successful_ = false;
335     quic::QuicServerId server_id_;
336     quic::ParsedQuicVersion quic_version_;
337     LoadTimingInfo::ConnectTiming connect_timing_;
338 
339     bool was_ever_used_ = false;
340   };
341 
342   // A helper class used to manage a request to create a stream.
343   class NET_EXPORT_PRIVATE StreamRequest {
344    public:
345     StreamRequest(const StreamRequest&) = delete;
346     StreamRequest& operator=(const StreamRequest&) = delete;
347 
348     // Cancels any pending stream creation request and resets |stream_| if
349     // it has not yet been released.
350     ~StreamRequest();
351 
352     // Starts a request to create a stream.  If OK is returned, then
353     // |stream_| will be updated with the newly created stream.  If
354     // ERR_IO_PENDING is returned, then when the request is eventuallly
355     // complete |callback| will be called.
356     int StartRequest(CompletionOnceCallback callback);
357 
358     // Releases |stream_| to the caller.
359     std::unique_ptr<QuicChromiumClientStream::Handle> ReleaseStream();
360 
traffic_annotation()361     const NetworkTrafficAnnotationTag traffic_annotation() {
362       return traffic_annotation_;
363     }
364 
365    private:
366     friend class QuicChromiumClientSession;
367 
368     enum State {
369       STATE_NONE,
370       STATE_WAIT_FOR_CONFIRMATION,
371       STATE_WAIT_FOR_CONFIRMATION_COMPLETE,
372       STATE_REQUEST_STREAM,
373       STATE_REQUEST_STREAM_COMPLETE,
374     };
375 
376     // |session| must outlive this request.
377     StreamRequest(QuicChromiumClientSession::Handle* session,
378                   bool requires_confirmation,
379                   const NetworkTrafficAnnotationTag& traffic_annotation);
380 
381     void OnIOComplete(int rv);
382     void DoCallback(int rv);
383 
384     int DoLoop(int rv);
385     int DoWaitForConfirmation();
386     int DoWaitForConfirmationComplete(int rv);
387     int DoRequestStream();
388     int DoRequestStreamComplete(int rv);
389 
390     // Called by |session_| for an asynchronous request when the stream
391     // request has finished successfully.
392     void OnRequestCompleteSuccess(
393         std::unique_ptr<QuicChromiumClientStream::Handle> stream);
394 
395     // Called by |session_| for an asynchronous request when the stream
396     // request has finished with an error. Also called with ERR_ABORTED
397     // if |session_| is destroyed while the stream request is still pending.
398     void OnRequestCompleteFailure(int rv);
399 
400     raw_ptr<QuicChromiumClientSession::Handle> session_;
401     const bool requires_confirmation_;
402     CompletionOnceCallback callback_;
403     std::unique_ptr<QuicChromiumClientStream::Handle> stream_;
404     // For tracking how much time pending stream requests wait.
405     base::TimeTicks pending_start_time_;
406     State next_state_;
407 
408     const NetworkTrafficAnnotationTag traffic_annotation_;
409 
410 #if BUILDFLAG(ENABLE_WEBSOCKETS)
411     // For creation of streams for WebSockets over HTTP/3
412     bool for_websockets_ = false;
413     raw_ptr<WebSocketQuicStreamAdapter::Delegate> websocket_adapter_delegate_;
414     base::OnceCallback<void(std::unique_ptr<WebSocketQuicStreamAdapter>)>
415         start_websocket_callback_;
416 #endif  // BUILDFLAG(ENABLE_WEBSOCKETS)
417 
418     base::WeakPtrFactory<StreamRequest> weak_factory_{this};
419   };
420 
421   // This class contains all the context needed for path validation and
422   // migration.
423   class NET_EXPORT_PRIVATE QuicChromiumPathValidationContext
424       : public quic::QuicPathValidationContext {
425    public:
426     QuicChromiumPathValidationContext(
427         const quic::QuicSocketAddress& self_address,
428         const quic::QuicSocketAddress& peer_address,
429         handles::NetworkHandle network,
430         std::unique_ptr<QuicChromiumPacketWriter> writer,
431         std::unique_ptr<QuicChromiumPacketReader> reader);
432     ~QuicChromiumPathValidationContext() override;
433 
434     handles::NetworkHandle network();
435     quic::QuicPacketWriter* WriterToUse() override;
436 
437     // Transfer the ownership from |this| to the caller.
438     std::unique_ptr<QuicChromiumPacketWriter> ReleaseWriter();
439     std::unique_ptr<QuicChromiumPacketReader> ReleaseReader();
440 
441    private:
442     handles::NetworkHandle network_handle_;
443     std::unique_ptr<QuicChromiumPacketWriter> writer_;
444     std::unique_ptr<QuicChromiumPacketReader> reader_;
445   };
446 
447   // This class implements Chrome logic for path validation events associated
448   // with connection migration.
449   class NET_EXPORT_PRIVATE ConnectionMigrationValidationResultDelegate
450       : public quic::QuicPathValidator::ResultDelegate {
451    public:
452     explicit ConnectionMigrationValidationResultDelegate(
453         QuicChromiumClientSession* session);
454 
455     void OnPathValidationSuccess(
456         std::unique_ptr<quic::QuicPathValidationContext> context,
457         quic::QuicTime start_time) override;
458 
459     void OnPathValidationFailure(
460         std::unique_ptr<quic::QuicPathValidationContext> context) override;
461 
462    private:
463     // |session_| owns |this| and should out live |this|.
464     raw_ptr<QuicChromiumClientSession> session_;
465   };
466 
467   // This class implements Chrome logic for path validation events associated
468   // with port migration.
469   class NET_EXPORT_PRIVATE PortMigrationValidationResultDelegate
470       : public quic::QuicPathValidator::ResultDelegate {
471    public:
472     explicit PortMigrationValidationResultDelegate(
473         QuicChromiumClientSession* session);
474 
475     void OnPathValidationSuccess(
476         std::unique_ptr<quic::QuicPathValidationContext> context,
477         quic::QuicTime start_time) override;
478 
479     void OnPathValidationFailure(
480         std::unique_ptr<quic::QuicPathValidationContext> context) override;
481 
482    private:
483     // |session_| owns |this| and should out live |this|.
484     raw_ptr<QuicChromiumClientSession> session_;
485   };
486 
487   // This class implements Chrome logic for path validation events associated
488   // with migrating to server preferred address.
489   class NET_EXPORT_PRIVATE ServerPreferredAddressValidationResultDelegate
490       : public quic::QuicPathValidator::ResultDelegate {
491    public:
492     explicit ServerPreferredAddressValidationResultDelegate(
493         QuicChromiumClientSession* session);
494 
495     void OnPathValidationSuccess(
496         std::unique_ptr<quic::QuicPathValidationContext> context,
497         quic::QuicTime start_time) override;
498 
499     void OnPathValidationFailure(
500         std::unique_ptr<quic::QuicPathValidationContext> context) override;
501 
502    private:
503     // |session_| owns |this| and should out live |this|.
504     raw_ptr<QuicChromiumClientSession> session_;
505   };
506 
507   // This class is used to handle writer events that occur on the probing path.
508   class NET_EXPORT_PRIVATE QuicChromiumPathValidationWriterDelegate
509       : public QuicChromiumPacketWriter::Delegate {
510    public:
511     QuicChromiumPathValidationWriterDelegate(
512         QuicChromiumClientSession* session,
513         base::SequencedTaskRunner* task_runner);
514 
515     QuicChromiumPathValidationWriterDelegate(
516         const QuicChromiumPathValidationWriterDelegate&) = delete;
517     QuicChromiumPathValidationWriterDelegate& operator=(
518         const QuicChromiumPathValidationWriterDelegate&) = delete;
519 
520     ~QuicChromiumPathValidationWriterDelegate();
521 
522     // QuicChromiumPacketWriter::Delegate interface.
523     int HandleWriteError(
524         int error_code,
525         scoped_refptr<QuicChromiumPacketWriter::ReusableIOBuffer> last_packet)
526         override;
527     void OnWriteError(int error_code) override;
528     void OnWriteUnblocked() override;
529 
530     void set_peer_address(const quic::QuicSocketAddress& peer_address);
531     void set_network(handles::NetworkHandle network);
532 
533    private:
534     void NotifySessionProbeFailed(handles::NetworkHandle network);
535 
536     // |session_| owns |this| and should out live |this|.
537     raw_ptr<QuicChromiumClientSession> session_;
538     // |task_owner_| should out live |this|.
539     raw_ptr<base::SequencedTaskRunner> task_runner_;
540     // The path validation context of the most recent probing.
541     handles::NetworkHandle network_;
542     quic::QuicSocketAddress peer_address_;
543     base::WeakPtrFactory<QuicChromiumPathValidationWriterDelegate>
544         weak_factory_{this};
545   };
546 
547   // Constructs a new session which will own |connection|, but not
548   // |stream_factory|, which must outlive this session.
549   // TODO(rch): decouple the factory from the session via a Delegate interface.
550   //
551   // If |require_confirmation| is true, the returned session will wait for a
552   // successful QUIC handshake before vending any streams, to ensure that both
553   // the server and the current network support QUIC, as HTTP fallback can't
554   // trigger (or at least will take longer) after a QUIC stream has successfully
555   // been created.
556   QuicChromiumClientSession(
557       quic::QuicConnection* connection,
558       std::unique_ptr<DatagramClientSocket> socket,
559       QuicStreamFactory* stream_factory,
560       QuicCryptoClientStreamFactory* crypto_client_stream_factory,
561       const quic::QuicClock* clock,
562       TransportSecurityState* transport_security_state,
563       SSLConfigService* ssl_config_service,
564       std::unique_ptr<QuicServerInfo> server_info,
565       const QuicSessionKey& session_key,
566       bool require_confirmation,
567       bool migrate_sesion_early_v2,
568       bool migrate_session_on_network_change_v2,
569       handles::NetworkHandle default_network,
570       quic::QuicTime::Delta retransmittable_on_wire_timeout,
571       bool migrate_idle_session,
572       bool allow_port_migration,
573       base::TimeDelta idle_migration_period,
574       int multi_port_probing_interval,
575       base::TimeDelta max_time_on_non_default_network,
576       int max_migrations_to_non_default_network_on_write_error,
577       int max_migrations_to_non_default_network_on_path_degrading,
578       int yield_after_packets,
579       quic::QuicTime::Delta yield_after_duration,
580       int cert_verify_flags,
581       const quic::QuicConfig& config,
582       std::unique_ptr<QuicCryptoClientConfigHandle> crypto_config,
583       base::TimeTicks dns_resolution_start_time,
584       base::TimeTicks dns_resolution_end_time,
585       const base::TickClock* tick_clock,
586       base::SequencedTaskRunner* task_runner,
587       std::unique_ptr<SocketPerformanceWatcher> socket_performance_watcher,
588       const HostResolverEndpointResult& endpoint_result,
589       NetLog* net_log);
590 
591   QuicChromiumClientSession(const QuicChromiumClientSession&) = delete;
592   QuicChromiumClientSession& operator=(const QuicChromiumClientSession&) =
593       delete;
594 
595   ~QuicChromiumClientSession() override;
596 
597   void Initialize() override;
598 
599   void AddHandle(Handle* handle);
600   void RemoveHandle(Handle* handle);
601 
602   void AddConnectivityObserver(ConnectivityObserver* observer);
603   void RemoveConnectivityObserver(ConnectivityObserver* observer);
604 
605   // Returns the session's connection migration mode.
606   ConnectionMigrationMode connection_migration_mode() const;
607 
608   // Waits for the handshake to be confirmed and invokes |callback| when
609   // that happens. If the handshake has already been confirmed, returns OK.
610   // If the connection has already been closed, returns a net error. If the
611   // connection closes before the handshake is confirmed, |callback| will
612   // be invoked with an error.
613   int WaitForHandshakeConfirmation(CompletionOnceCallback callback);
614 
615   // Attempts to create a new stream.  If the stream can be
616   // created immediately, returns OK.  If the open stream limit
617   // has been reached, returns ERR_IO_PENDING, and |request|
618   // will be added to the stream requets queue and will
619   // be completed asynchronously.
620   // TODO(rch): remove |stream| from this and use setter on |request|
621   // and fix in spdy too.
622   int TryCreateStream(StreamRequest* request);
623 
624   // Cancels the pending stream creation request.
625   void CancelRequest(StreamRequest* request);
626 
627   // QuicChromiumPacketWriter::Delegate override.
628   int HandleWriteError(int error_code,
629                        scoped_refptr<QuicChromiumPacketWriter::ReusableIOBuffer>
630                            last_packet) override;
631   void OnWriteError(int error_code) override;
632   // Called when the associated writer is unblocked. Write the cached |packet_|
633   // if |packet_| is set. May send a PING packet if
634   // |send_packet_after_migration_| is set and writer is not blocked after
635   // writing queued packets.
636   void OnWriteUnblocked() override;
637 
638   void OnConnectionMigrationProbeSucceeded(
639       handles::NetworkHandle network,
640       const quic::QuicSocketAddress& peer_address,
641       const quic::QuicSocketAddress& self_address,
642       std::unique_ptr<QuicChromiumPacketWriter> writer,
643       std::unique_ptr<QuicChromiumPacketReader> reader);
644 
645   void OnPortMigrationProbeSucceeded(
646       handles::NetworkHandle network,
647       const quic::QuicSocketAddress& peer_address,
648       const quic::QuicSocketAddress& self_address,
649       std::unique_ptr<QuicChromiumPacketWriter> writer,
650       std::unique_ptr<QuicChromiumPacketReader> reader);
651 
652   void OnServerPreferredAddressProbeSucceeded(
653       handles::NetworkHandle network,
654       const quic::QuicSocketAddress& peer_address,
655       const quic::QuicSocketAddress& self_address,
656       std::unique_ptr<QuicChromiumPacketWriter> writer,
657       std::unique_ptr<QuicChromiumPacketReader> reader);
658 
659   void OnProbeFailed(handles::NetworkHandle network,
660                      const quic::QuicSocketAddress& peer_address);
661 
662   // quic::QuicSpdySession methods:
663   size_t WriteHeadersOnHeadersStream(
664       quic::QuicStreamId id,
665       spdy::Http2HeaderBlock headers,
666       bool fin,
667       const spdy::SpdyStreamPrecedence& precedence,
668       quiche::QuicheReferenceCountedPointer<quic::QuicAckListenerInterface>
669           ack_listener) override;
670   void OnHttp3GoAway(uint64_t id) override;
671   void OnAcceptChFrameReceivedViaAlps(
672       const quic::AcceptChFrame& frame) override;
673 
674   // quic::QuicSession methods:
675   QuicChromiumClientStream* CreateOutgoingBidirectionalStream() override;
676   QuicChromiumClientStream* CreateOutgoingUnidirectionalStream() override;
677   const quic::QuicCryptoClientStream* GetCryptoStream() const override;
678   quic::QuicCryptoClientStream* GetMutableCryptoStream() override;
679   void SetDefaultEncryptionLevel(quic::EncryptionLevel level) override;
680   void OnTlsHandshakeComplete() override;
681   void OnNewEncryptionKeyAvailable(
682       quic::EncryptionLevel level,
683       std::unique_ptr<quic::QuicEncrypter> encrypter) override;
684   void OnCryptoHandshakeMessageSent(
685       const quic::CryptoHandshakeMessage& message) override;
686   void OnCryptoHandshakeMessageReceived(
687       const quic::CryptoHandshakeMessage& message) override;
688   void OnGoAway(const quic::QuicGoAwayFrame& frame) override;
689   void OnCanCreateNewOutgoingStream(bool unidirectional) override;
690   quic::QuicSSLConfig GetSSLConfig() const override;
691 
692   // QuicSpdyClientSessionBase methods:
693   void OnConfigNegotiated() override;
694   void OnProofValid(
695       const quic::QuicCryptoClientConfig::CachedState& cached) override;
696   void OnProofVerifyDetailsAvailable(
697       const quic::ProofVerifyDetails& verify_details) override;
698 
699   // quic::QuicConnectionVisitorInterface methods:
700   void OnConnectionClosed(const quic::QuicConnectionCloseFrame& frame,
701                           quic::ConnectionCloseSource source) override;
702   void OnSuccessfulVersionNegotiation(
703       const quic::ParsedQuicVersion& version) override;
704   void OnPathDegrading() override;
705   void OnForwardProgressMadeAfterPathDegrading() override;
706   void OnKeyUpdate(quic::KeyUpdateReason reason) override;
707   void CreateContextForMultiPortPath(
708       std::unique_ptr<quic::MultiPortPathContextObserver> context_observer)
709       override;
710   void MigrateToMultiPortPath(
711       std::unique_ptr<quic::QuicPathValidationContext> context) override;
712 
713   // QuicChromiumPacketReader::Visitor methods:
714   bool OnReadError(int result, const DatagramClientSocket* socket) override;
715   bool OnPacket(const quic::QuicReceivedPacket& packet,
716                 const quic::QuicSocketAddress& local_address,
717                 const quic::QuicSocketAddress& peer_address) override;
718   void OnStreamClosed(quic::QuicStreamId stream_id) override;
719 
720   // MultiplexedSession methods:
721   int GetRemoteEndpoint(IPEndPoint* endpoint) override;
722   bool GetSSLInfo(SSLInfo* ssl_info) const override;
723   base::StringPiece GetAcceptChViaAlps(
724       const url::SchemeHostPort& scheme_host_port) const override;
725 
726   // Helper for CreateContextForMultiPortPath. Gets the result of
727   // ConnectAndConfigureSocket and uses it to create the multiport path context.
728   void FinishCreateContextForMultiPortPath(
729       std::unique_ptr<quic::MultiPortPathContextObserver> context_observer,
730       std::unique_ptr<DatagramClientSocket> probing_socket,
731       int rv);
732 
733   // Performs a crypto handshake with the server.
734   int CryptoConnect(CompletionOnceCallback callback);
735 
736   // Causes the QuicConnectionHelper to start reading from all sockets
737   // and passing the data along to the quic::QuicConnection.
738   void StartReading();
739 
740   // Close the session because of |net_error| and notifies the factory
741   // that this session has been closed, which will delete the session.
742   // |behavior| will suggest whether we should send connection close packets
743   // when closing the connection.
744   void CloseSessionOnError(int net_error,
745                            quic::QuicErrorCode quic_error,
746                            quic::ConnectionCloseBehavior behavior);
747 
748   // Close the session because of |net_error| and notifies the factory
749   // that this session has been closed later, which will delete the session.
750   // |behavior| will suggest whether we should send connection close packets
751   // when closing the connection.
752   void CloseSessionOnErrorLater(int net_error,
753                                 quic::QuicErrorCode quic_error,
754                                 quic::ConnectionCloseBehavior behavior);
755 
756   base::Value::Dict GetInfoAsValue(const std::set<HostPortPair>& aliases);
757 
net_log()758   const NetLogWithSource& net_log() const { return net_log_; }
759 
760   // Returns true if the stream factory disables gQUIC 0-RTT.
761   bool gquic_zero_rtt_disabled() const;
762 
763   // Returns a Handle to this session.
764   std::unique_ptr<QuicChromiumClientSession::Handle> CreateHandle(
765       url::SchemeHostPort destination);
766 
767   // Returns the number of client hello messages that have been sent on the
768   // crypto stream. If the handshake has completed then this is one greater
769   // than the number of round-trips needed for the handshake.
770   int GetNumSentClientHellos() const;
771 
772   // Returns true if |hostname| may be pooled onto this session.
773   // |other_session_key| specifies the seession key associated with |hostname|
774   // (its own hostname and port fields are ignored). If this is a secure QUIC
775   // session, then |hostname| must match the certificate presented during the
776   // handshake.
777   bool CanPool(const std::string& hostname,
778                const QuicSessionKey& other_session_key) const;
779 
server_id()780   const quic::QuicServerId& server_id() const {
781     return session_key_.server_id();
782   }
783 
quic_session_key()784   const QuicSessionKey& quic_session_key() const { return session_key_; }
785 
786   // Attempts to migrate session when |writer| encounters a write error.
787   // If |writer| is no longer actively used, abort migration.
788   void MigrateSessionOnWriteError(int error_code,
789                                   quic::QuicPacketWriter* writer);
790   // Called when the Migrate() call from MigrateSessionOnWriteError completes.
791   // Always called asynchronously.
792   void FinishMigrateSessionOnWriteError(handles::NetworkHandle new_network,
793                                         MigrationResult result);
794 
795   // Helper method that completes connection/server migration.
796   // Unblocks packet writer on network level. If the writer becomes unblocked
797   // then, OnWriteUnblocked() will be invoked to send packet after migration.
798   void WriteToNewSocket();
799 
800   // Migrates session over to use |peer_address| and |network|.
801   // If |network| is handles::kInvalidNetworkHandle, default network is used. If
802   // the migration fails and |close_session_on_error| is true, session will be
803   // closed.
804   using MigrationCallback = base::OnceCallback<void(MigrationResult)>;
805   void Migrate(handles::NetworkHandle network,
806                IPEndPoint peer_address,
807                bool close_session_on_error,
808                MigrationCallback migration_callback);
809   // Helper to finish session migration once a socket has been opened. Always
810   // called asynchronously.
811   void FinishMigrate(std::unique_ptr<DatagramClientSocket> socket,
812                      IPEndPoint peer_address,
813                      bool close_session_on_error,
814                      MigrationCallback callback,
815                      int rv);
816 
817   void DoMigrationCallback(MigrationCallback callback, MigrationResult rv);
818 
819   // Migrates session onto new socket, i.e., sets |writer| to be the new
820   // default writer and post a task to write to |socket|. |reader| *must*
821   // has been started reading from the socket. Returns true if
822   // socket was successfully added to the session and the session was
823   // successfully migrated to using the new socket. Returns true on
824   // successful migration, or false if number of migrations exceeds
825   // kMaxReadersPerQuicSession. Takes ownership of |socket|, |reader|,
826   // and |writer|.
827   bool MigrateToSocket(const quic::QuicSocketAddress& self_address,
828                        const quic::QuicSocketAddress& peer_address,
829                        std::unique_ptr<QuicChromiumPacketReader> reader,
830                        std::unique_ptr<QuicChromiumPacketWriter> writer);
831 
832   // Called when NetworkChangeNotifier notifies observers of a newly
833   // connected network. Migrates this session to the newly connected
834   // network if the session has a pending migration.
835   void OnNetworkConnected(handles::NetworkHandle network);
836 
837   // Called when NetworkChangeNotifier broadcasts to observers of
838   // |disconnected_network|.
839   void OnNetworkDisconnectedV2(handles::NetworkHandle disconnected_network);
840 
841   // Called when NetworkChangeNotifier broadcats to observers of a new default
842   // network. Migrates this session to |new_network| if appropriate.
843   void OnNetworkMadeDefault(handles::NetworkHandle new_network);
844 
845   // Schedules a migration alarm to wait for a new network.
846   void OnNoNewNetwork();
847 
848   // Called when migration alarm fires. If migration has not occurred
849   // since alarm was set, closes session with error.
850   void OnMigrationTimeout(size_t num_sockets);
851 
852   // Populates network error details for this session.
853   void PopulateNetErrorDetails(NetErrorDetails* details) const;
854 
855   // Returns current default socket. This is the socket over which all
856   // QUIC packets are sent. This default socket can change, so do not store the
857   // returned socket.
858   const DatagramClientSocket* GetDefaultSocket() const;
859 
860   // Returns the network interface that is currently used to send packets.
861   // If handles::NetworkHandle is not supported, always return
862   // handles::kInvalidNetworkHandle.
863   handles::NetworkHandle GetCurrentNetwork() const;
864 
865   // Override to validate |server_preferred_address| on a different socket.
866   // Migrates to this address on validation succeeds.
867   void OnServerPreferredAddressAvailable(
868       const quic::QuicSocketAddress& server_preferred_address) override;
869 
870   const LoadTimingInfo::ConnectTiming& GetConnectTiming();
871 
872   quic::ParsedQuicVersion GetQuicVersion() const;
873 
require_confirmation()874   bool require_confirmation() const { return require_confirmation_; }
875 
876   // Retrieves any DNS aliases for the given session key from the map stored
877   // in `stream_factory_`. Includes all known aliases, e.g. from A, AAAA, or
878   // HTTPS, not just from the address used for the connection, in no particular
879   // order.
880   const std::set<std::string>& GetDnsAliasesForSessionKey(
881       const QuicSessionKey& key) const;
882 
883  protected:
884   // quic::QuicSession methods:
885   bool ShouldCreateIncomingStream(quic::QuicStreamId id) override;
886   bool ShouldCreateOutgoingBidirectionalStream() override;
887   bool ShouldCreateOutgoingUnidirectionalStream() override;
888 
889   QuicChromiumClientStream* CreateIncomingStream(
890       quic::QuicStreamId id) override;
891   QuicChromiumClientStream* CreateIncomingStream(
892       quic::PendingStream* pending) override;
893 
894  private:
895   friend class test::QuicChromiumClientSessionPeer;
896 
897   typedef std::set<Handle*> HandleSet;
898   typedef std::list<StreamRequest*> StreamRequestQueue;
899 
900   bool WasConnectionEverUsed();
901 
902   QuicChromiumClientStream* CreateOutgoingReliableStreamImpl(
903       const NetworkTrafficAnnotationTag& traffic_annotation);
904   QuicChromiumClientStream* CreateIncomingReliableStreamImpl(
905       quic::QuicStreamId id,
906       const NetworkTrafficAnnotationTag& traffic_annotation);
907   QuicChromiumClientStream* CreateIncomingReliableStreamImpl(
908       quic::PendingStream* pending,
909       const NetworkTrafficAnnotationTag& traffic_annotation);
910   // A completion callback invoked when a read completes.
911   void OnReadComplete(int result);
912 
913   void NotifyAllStreamsOfError(int net_error);
914   void CloseAllHandles(int net_error);
915   void CancelAllRequests(int net_error);
916   void NotifyRequestsOfConfirmation(int net_error);
917 
918   // Probe on <network, peer_address>.
919   // If <network, peer_addres> is identical to the current path, the probe
920   // is sent on a different port.
921   using ProbingCallback = base::OnceCallback<void(ProbingResult)>;
922   void StartProbing(ProbingCallback probing_callback,
923                     handles::NetworkHandle network,
924                     const quic::QuicSocketAddress& peer_address);
925 
926   // Helper to finish network probe once socket has been opened. Always called
927   // asynchronously.
928   void FinishStartProbing(ProbingCallback probing_callback,
929                           std::unique_ptr<DatagramClientSocket> probing_socket,
930                           handles::NetworkHandle network,
931                           const quic::QuicSocketAddress& peer_address,
932                           int rv);
933 
934   // Perform a few checks before StartProbing. If any of those checks fails,
935   // StartProbing will be skipped.
936   void MaybeStartProbing(ProbingCallback probing_callback,
937                          handles::NetworkHandle network,
938                          const quic::QuicSocketAddress& peer_address);
939 
940   // Helper method to perform a few checks and initiate connection migration
941   // attempt when path degrading is detected.
942   // Called when path is degrading and there is an alternate network or a new
943   // network is connected after path degrading.
944   void MaybeMigrateToAlternateNetworkOnPathDegrading();
945 
946   // Helper method to initiate a port migration on path degrading is detected.
947   void MaybeMigrateToDifferentPortOnPathDegrading();
948 
949   // Called when there is only one possible working network: |network|, If any
950   // error encountered, this session will be closed.
951   // When the migration succeeds:
952   //  - If no longer on the default network, set timer to migrate back to the
953   //    default network;
954   //  - If now on the default network, cancel timer to migrate back to default
955   //    network.
956   void MigrateNetworkImmediately(handles::NetworkHandle network);
957 
958   // Called when Migrate() call from MigrateNetworkImmediately completes. Always
959   // called asynchronously.
960   void FinishMigrateNetworkImmediately(handles::NetworkHandle network,
961                                        MigrationResult result);
962 
963   void StartMigrateBackToDefaultNetworkTimer(base::TimeDelta delay);
964   void CancelMigrateBackToDefaultNetworkTimer();
965   void TryMigrateBackToDefaultNetwork(base::TimeDelta timeout);
966   void FinishTryMigrateBackToDefaultNetwork(base::TimeDelta timeout,
967                                             ProbingResult result);
968   void MaybeRetryMigrateBackToDefaultNetwork();
969 
970   // If migrate idle session is enabled, returns true and post a task to close
971   // the connection if session's idle time exceeds the |idle_migration_period_|.
972   // If migrate idle session is not enabled, returns true and posts a task to
973   // close the connection if session doesn't have outstanding streams.
974   bool CheckIdleTimeExceedsIdleMigrationPeriod();
975 
976   // Close non-migratable streams in both directions by sending reset stream to
977   // peer when connection migration attempts to migrate to the alternate
978   // network.
979   void ResetNonMigratableStreams();
980   void LogMetricsOnNetworkDisconnected();
981   void LogMetricsOnNetworkMadeDefault();
982   void LogMigrationResultToHistogram(QuicConnectionMigrationStatus status);
983   void LogHandshakeStatusOnMigrationSignal() const;
984   void HistogramAndLogMigrationFailure(QuicConnectionMigrationStatus status,
985                                        quic::QuicConnectionId connection_id,
986                                        const char* reason);
987   void HistogramAndLogMigrationSuccess(quic::QuicConnectionId connection_id);
988 
989   // Notifies the factory that this session is going away and no more streams
990   // should be created from it.  This needs to be called before closing any
991   // streams, because closing a stream may cause a new stream to be created.
992   void NotifyFactoryOfSessionGoingAway();
993 
994   // Posts a task to notify the factory that this session has been closed.
995   void NotifyFactoryOfSessionClosedLater();
996 
997   // Notifies the factory that this session has been closed which will
998   // delete |this|.
999   void NotifyFactoryOfSessionClosed();
1000 
1001   // Called when default encryption level switches to forward secure.
1002   void OnCryptoHandshakeComplete();
1003 
1004   void LogZeroRttStats();
1005 
1006 #if BUILDFLAG(ENABLE_WEBSOCKETS)
1007   std::unique_ptr<WebSocketQuicStreamAdapter>
1008   CreateWebSocketQuicStreamAdapterImpl(
1009       WebSocketQuicStreamAdapter::Delegate* delegate);
1010 
1011   std::unique_ptr<WebSocketQuicStreamAdapter> CreateWebSocketQuicStreamAdapter(
1012       WebSocketQuicStreamAdapter::Delegate* delegate,
1013       base::OnceCallback<void(std::unique_ptr<WebSocketQuicStreamAdapter>)>
1014           callback,
1015       StreamRequest* stream_request);
1016 #endif  // BUILDFLAG(ENABLE_WEBSOCKETS)
1017 
1018   QuicSessionKey session_key_;
1019   bool require_confirmation_;
1020   bool migrate_session_early_v2_;
1021   bool migrate_session_on_network_change_v2_;
1022   // True when session migration has started from MigrateSessionOnWriteError.
1023   bool pending_migrate_session_on_write_error_ = false;
1024   // True when a session migration starts from MigrateNetworkImmediately.
1025   bool pending_migrate_network_immediately_ = false;
1026   bool migrate_idle_session_;
1027   bool allow_port_migration_;
1028   // Session can be migrated if its idle time is within this period.
1029   base::TimeDelta idle_migration_period_;
1030   base::TimeDelta max_time_on_non_default_network_;
1031   // Maximum allowed number of migrations to non-default network triggered by
1032   // packet write error per default network.
1033   int max_migrations_to_non_default_network_on_write_error_;
1034   int current_migrations_to_non_default_network_on_write_error_ = 0;
1035   // Maximum allowed number of migrations to non-default network triggered by
1036   // path degrading per default network.
1037   int max_migrations_to_non_default_network_on_path_degrading_;
1038   int current_migrations_to_non_default_network_on_path_degrading_ = 0;
1039   raw_ptr<const quic::QuicClock> clock_;  // Unowned.
1040   int yield_after_packets_;
1041   quic::QuicTime::Delta yield_after_duration_;
1042 
1043   base::TimeTicks most_recent_path_degrading_timestamp_;
1044   base::TimeTicks most_recent_network_disconnected_timestamp_;
1045   raw_ptr<const base::TickClock> tick_clock_;
1046   base::TimeTicks most_recent_stream_close_time_;
1047 
1048   int most_recent_write_error_ = 0;
1049   base::TimeTicks most_recent_write_error_timestamp_;
1050 
1051   std::unique_ptr<QuicCryptoClientConfigHandle> crypto_config_;
1052 
1053   std::unique_ptr<quic::QuicCryptoClientStream> crypto_stream_;
1054   raw_ptr<QuicStreamFactory> stream_factory_;
1055   base::ObserverList<ConnectivityObserver> connectivity_observer_list_;
1056   std::vector<std::unique_ptr<QuicChromiumPacketReader>> packet_readers_;
1057   raw_ptr<TransportSecurityState> transport_security_state_;
1058   raw_ptr<SSLConfigService> ssl_config_service_;
1059   std::unique_ptr<QuicServerInfo> server_info_;
1060   std::unique_ptr<CertVerifyResult> cert_verify_result_;
1061   std::string pinning_failure_log_;
1062   bool pkp_bypassed_ = false;
1063   bool is_fatal_cert_error_ = false;
1064   HandleSet handles_;
1065   StreamRequestQueue stream_requests_;
1066   std::vector<CompletionOnceCallback> waiting_for_confirmation_callbacks_;
1067   CompletionOnceCallback callback_;
1068   size_t num_total_streams_ = 0;
1069   raw_ptr<base::SequencedTaskRunner> task_runner_;
1070   NetLogWithSource net_log_;
1071   LoadTimingInfo::ConnectTiming connect_timing_;
1072   std::unique_ptr<QuicConnectionLogger> logger_;
1073   std::unique_ptr<QuicHttp3Logger> http3_logger_;
1074   // True when the session is going away, and streams may no longer be created
1075   // on this session. Existing stream will continue to be processed.
1076   bool going_away_ = false;
1077   // True when the session receives a go away from server due to port migration.
1078   bool port_migration_detected_ = false;
1079   bool quic_connection_migration_attempted_ = false;
1080   bool quic_connection_migration_successful_ = false;
1081   // Stores the packet that witnesses socket write error. This packet will be
1082   // written to an alternate socket when the migration completes and the
1083   // alternate socket is unblocked.
1084   scoped_refptr<QuicChromiumPacketWriter::ReusableIOBuffer> packet_;
1085   // Stores the latest default network platform marks if migration is enabled.
1086   // Otherwise, stores the network interface that is used by the connection.
1087   handles::NetworkHandle default_network_;
1088   int retry_migrate_back_count_ = 0;
1089   base::OneShotTimer migrate_back_to_default_timer_;
1090   MigrationCause current_migration_cause_ = UNKNOWN_CAUSE;
1091   // True if a packet needs to be sent when packet writer is unblocked to
1092   // complete connection migration. The packet can be a cached packet if
1093   // |packet_| is set, a queued packet, or a PING packet.
1094   bool send_packet_after_migration_ = false;
1095   // True if migration is triggered, and there is no alternate network to
1096   // migrate to.
1097   bool wait_for_new_network_ = false;
1098   // True if read errors should be ignored. Set when migration on write error is
1099   // posted and unset until the first packet is written after migration.
1100   bool ignore_read_error_ = false;
1101 
1102   bool attempted_zero_rtt_ = false;
1103 
1104   size_t num_migrations_ = 0;
1105 
1106   // The reason for the last 1-RTT key update on the connection. Will be
1107   // kInvalid if no key updates have occurred.
1108   quic::KeyUpdateReason last_key_update_reason_ =
1109       quic::KeyUpdateReason::kInvalid;
1110 
1111   QuicChromiumPathValidationWriterDelegate path_validation_writer_delegate_;
1112 
1113   // Map of origin to Accept-CH header field values received via ALPS.
1114   base::flat_map<url::SchemeHostPort, std::string>
1115       accept_ch_entries_received_via_alps_;
1116 
1117   std::vector<uint8_t> ech_config_list_;
1118 
1119   base::WeakPtrFactory<QuicChromiumClientSession> weak_factory_{this};
1120 };
1121 
1122 }  // namespace net
1123 
1124 #endif  // NET_QUIC_QUIC_CHROMIUM_CLIENT_SESSION_H_
1125