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