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