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