• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 // The entity that handles framing writes for a Quic client or server.
6 // Each QuicSession will have a connection associated with it.
7 //
8 // On the server side, the Dispatcher handles the raw reads, and hands off
9 // packets via ProcessUdpPacket for framing and processing.
10 //
11 // On the client side, the Connection handles the raw reads, as well as the
12 // processing.
13 //
14 // Note: this class is not thread-safe.
15 
16 #ifndef QUICHE_QUIC_CORE_QUIC_CONNECTION_H_
17 #define QUICHE_QUIC_CORE_QUIC_CONNECTION_H_
18 
19 #include <cstddef>
20 #include <cstdint>
21 #include <list>
22 #include <map>
23 #include <memory>
24 #include <string>
25 #include <vector>
26 
27 #include "absl/strings/string_view.h"
28 #include "absl/types/optional.h"
29 #include "quiche/quic/core/congestion_control/rtt_stats.h"
30 #include "quiche/quic/core/crypto/quic_decrypter.h"
31 #include "quiche/quic/core/crypto/quic_encrypter.h"
32 #include "quiche/quic/core/crypto/quic_random.h"
33 #include "quiche/quic/core/crypto/transport_parameters.h"
34 #include "quiche/quic/core/frames/quic_ack_frequency_frame.h"
35 #include "quiche/quic/core/frames/quic_max_streams_frame.h"
36 #include "quiche/quic/core/frames/quic_new_connection_id_frame.h"
37 #include "quiche/quic/core/quic_alarm.h"
38 #include "quiche/quic/core/quic_alarm_factory.h"
39 #include "quiche/quic/core/quic_blocked_writer_interface.h"
40 #include "quiche/quic/core/quic_connection_context.h"
41 #include "quiche/quic/core/quic_connection_id.h"
42 #include "quiche/quic/core/quic_connection_id_manager.h"
43 #include "quiche/quic/core/quic_connection_stats.h"
44 #include "quiche/quic/core/quic_constants.h"
45 #include "quiche/quic/core/quic_framer.h"
46 #include "quiche/quic/core/quic_idle_network_detector.h"
47 #include "quiche/quic/core/quic_lru_cache.h"
48 #include "quiche/quic/core/quic_mtu_discovery.h"
49 #include "quiche/quic/core/quic_network_blackhole_detector.h"
50 #include "quiche/quic/core/quic_one_block_arena.h"
51 #include "quiche/quic/core/quic_packet_creator.h"
52 #include "quiche/quic/core/quic_packet_writer.h"
53 #include "quiche/quic/core/quic_packets.h"
54 #include "quiche/quic/core/quic_path_validator.h"
55 #include "quiche/quic/core/quic_ping_manager.h"
56 #include "quiche/quic/core/quic_sent_packet_manager.h"
57 #include "quiche/quic/core/quic_time.h"
58 #include "quiche/quic/core/quic_types.h"
59 #include "quiche/quic/core/uber_received_packet_manager.h"
60 #include "quiche/quic/platform/api/quic_export.h"
61 #include "quiche/quic/platform/api/quic_flags.h"
62 #include "quiche/quic/platform/api/quic_socket_address.h"
63 #include "quiche/common/platform/api/quiche_mem_slice.h"
64 #include "quiche/common/quiche_circular_deque.h"
65 
66 namespace quic {
67 
68 class QuicClock;
69 class QuicConfig;
70 class QuicConnection;
71 
72 namespace test {
73 class QuicConnectionPeer;
74 }  // namespace test
75 
76 // Class that receives callbacks from the connection when frames are received
77 // and when other interesting events happen.
78 class QUIC_EXPORT_PRIVATE QuicConnectionVisitorInterface {
79  public:
~QuicConnectionVisitorInterface()80   virtual ~QuicConnectionVisitorInterface() {}
81 
82   // A simple visitor interface for dealing with a data frame.
83   virtual void OnStreamFrame(const QuicStreamFrame& frame) = 0;
84 
85   // Called when a CRYPTO frame containing handshake data is received.
86   virtual void OnCryptoFrame(const QuicCryptoFrame& frame) = 0;
87 
88   // The session should process the WINDOW_UPDATE frame, adjusting both stream
89   // and connection level flow control windows.
90   virtual void OnWindowUpdateFrame(const QuicWindowUpdateFrame& frame) = 0;
91 
92   // A BLOCKED frame indicates the peer is flow control blocked
93   // on a specified stream.
94   virtual void OnBlockedFrame(const QuicBlockedFrame& frame) = 0;
95 
96   // Called when the stream is reset by the peer.
97   virtual void OnRstStream(const QuicRstStreamFrame& frame) = 0;
98 
99   // Called when the connection is going away according to the peer.
100   virtual void OnGoAway(const QuicGoAwayFrame& frame) = 0;
101 
102   // Called when |message| has been received.
103   virtual void OnMessageReceived(absl::string_view message) = 0;
104 
105   // Called when a HANDSHAKE_DONE frame has been received.
106   virtual void OnHandshakeDoneReceived() = 0;
107 
108   // Called when a NEW_TOKEN frame has been received.
109   virtual void OnNewTokenReceived(absl::string_view token) = 0;
110 
111   // Called when a MAX_STREAMS frame has been received from the peer.
112   virtual bool OnMaxStreamsFrame(const QuicMaxStreamsFrame& frame) = 0;
113 
114   // Called when a STREAMS_BLOCKED frame has been received from the peer.
115   virtual bool OnStreamsBlockedFrame(const QuicStreamsBlockedFrame& frame) = 0;
116 
117   // Called when the connection is closed either locally by the framer, or
118   // remotely by the peer.
119   virtual void OnConnectionClosed(const QuicConnectionCloseFrame& frame,
120                                   ConnectionCloseSource source) = 0;
121 
122   // Called when the connection failed to write because the socket was blocked.
123   virtual void OnWriteBlocked() = 0;
124 
125   // Called once a specific QUIC version is agreed by both endpoints.
126   virtual void OnSuccessfulVersionNegotiation(
127       const ParsedQuicVersion& version) = 0;
128 
129   // Called when a packet has been received by the connection, after being
130   // validated and parsed. Only called when the client receives a valid packet
131   // or the server receives a connectivity probing packet.
132   // |is_connectivity_probe| is true if the received packet is a connectivity
133   // probe.
134   virtual void OnPacketReceived(const QuicSocketAddress& self_address,
135                                 const QuicSocketAddress& peer_address,
136                                 bool is_connectivity_probe) = 0;
137 
138   // Called when a blocked socket becomes writable.
139   virtual void OnCanWrite() = 0;
140 
141   // Called when the connection experiences a change in congestion window.
142   virtual void OnCongestionWindowChange(QuicTime now) = 0;
143 
144   // Called when the connection receives a packet from a migrated client.
145   virtual void OnConnectionMigration(AddressChangeType type) = 0;
146 
147   // Called when the peer seems unreachable over the current path.
148   virtual void OnPathDegrading() = 0;
149 
150   // Called when forward progress made after path degrading.
151   virtual void OnForwardProgressMadeAfterPathDegrading() = 0;
152 
153   // Called when the connection sends ack after
154   // max_consecutive_num_packets_with_no_retransmittable_frames_ consecutive not
155   // retransmittable packets sent. To instigate an ack from peer, a
156   // retransmittable frame needs to be added.
157   virtual void OnAckNeedsRetransmittableFrame() = 0;
158 
159   // Called when an AckFrequency frame need to be sent.
160   virtual void SendAckFrequency(const QuicAckFrequencyFrame& frame) = 0;
161 
162   // Called to send a NEW_CONNECTION_ID frame.
163   virtual void SendNewConnectionId(const QuicNewConnectionIdFrame& frame) = 0;
164 
165   // Called to send a RETIRE_CONNECTION_ID frame.
166   virtual void SendRetireConnectionId(uint64_t sequence_number) = 0;
167 
168   // Called when server starts to use a server issued connection ID. Returns
169   // true if this connection ID hasn't been used by another connection.
170   virtual bool MaybeReserveConnectionId(
171       const QuicConnectionId& server_connection_id) = 0;
172 
173   // Called when server stops to use a server issued connection ID.
174   virtual void OnServerConnectionIdRetired(
175       const QuicConnectionId& server_connection_id) = 0;
176 
177   // Called to ask if the visitor wants to schedule write resumption as it both
178   // has pending data to write, and is able to write (e.g. based on flow control
179   // limits).
180   // Writes may be pending because they were write-blocked, congestion-throttled
181   // or yielded to other connections.
182   virtual bool WillingAndAbleToWrite() const = 0;
183 
184   // Called to ask if the connection should be kept alive and prevented
185   // from timing out, for example if there are outstanding application
186   // transactions expecting a response.
187   virtual bool ShouldKeepConnectionAlive() const = 0;
188 
189   // Called to retrieve streams information for logging purpose.
190   virtual std::string GetStreamsInfoForLogging() const = 0;
191 
192   // Called when a self address change is observed. Returns true if self address
193   // change is allowed.
194   virtual bool AllowSelfAddressChange() const = 0;
195 
196   // Called to get current handshake state.
197   virtual HandshakeState GetHandshakeState() const = 0;
198 
199   // Called when a STOP_SENDING frame has been received.
200   virtual void OnStopSendingFrame(const QuicStopSendingFrame& frame) = 0;
201 
202   // Called when a packet of encryption |level| has been successfully decrypted.
203   virtual void OnPacketDecrypted(EncryptionLevel level) = 0;
204 
205   // Called when a 1RTT packet has been acknowledged.
206   virtual void OnOneRttPacketAcknowledged() = 0;
207 
208   // Called when a packet of ENCRYPTION_HANDSHAKE gets sent.
209   virtual void OnHandshakePacketSent() = 0;
210 
211   // Called when a key update has occurred.
212   virtual void OnKeyUpdate(KeyUpdateReason reason) = 0;
213 
214   // Called to generate a decrypter for the next key phase. Each call should
215   // generate the key for phase n+1.
216   virtual std::unique_ptr<QuicDecrypter>
217   AdvanceKeysAndCreateCurrentOneRttDecrypter() = 0;
218 
219   // Called to generate an encrypter for the same key phase of the last
220   // decrypter returned by AdvanceKeysAndCreateCurrentOneRttDecrypter().
221   virtual std::unique_ptr<QuicEncrypter> CreateCurrentOneRttEncrypter() = 0;
222 
223   // Called when connection is being closed right before a CONNECTION_CLOSE
224   // frame is serialized, but only on the server and only if forward secure
225   // encryption has already been established.
226   virtual void BeforeConnectionCloseSent() = 0;
227 
228   // Called by the server to validate |token| in received INITIAL packets.
229   // Consider the client address gets validated (and therefore remove
230   // amplification factor) once the |token| gets successfully validated.
231   virtual bool ValidateToken(absl::string_view token) = 0;
232 
233   // Called by the server to send another token.
234   // Return false if the crypto stream fail to generate one.
235   virtual bool MaybeSendAddressToken() = 0;
236 
237   // When bandwidth update alarms.
238   virtual void OnBandwidthUpdateTimeout() = 0;
239 
240   // Returns context needed for the connection to probe on the alternative path.
241   virtual std::unique_ptr<QuicPathValidationContext>
242   CreateContextForMultiPortPath() = 0;
243 
244   // Migrate to the multi-port path which is identified by |context|.
245   virtual void MigrateToMultiPortPath(
246       std::unique_ptr<QuicPathValidationContext> context) = 0;
247 
248   // Called when the client receives a preferred address from its peer.
249   virtual void OnServerPreferredAddressAvailable(
250       const QuicSocketAddress& server_preferred_address) = 0;
251 };
252 
253 // Interface which gets callbacks from the QuicConnection at interesting
254 // points.  Implementations must not mutate the state of the connection
255 // as a result of these callbacks.
256 class QUIC_EXPORT_PRIVATE QuicConnectionDebugVisitor
257     : public QuicSentPacketManager::DebugDelegate {
258  public:
~QuicConnectionDebugVisitor()259   ~QuicConnectionDebugVisitor() override {}
260 
261   // Called when a packet has been sent.
OnPacketSent(QuicPacketNumber,QuicPacketLength,bool,TransmissionType,EncryptionLevel,const QuicFrames &,const QuicFrames &,QuicTime)262   virtual void OnPacketSent(QuicPacketNumber /*packet_number*/,
263                             QuicPacketLength /*packet_length*/,
264                             bool /*has_crypto_handshake*/,
265                             TransmissionType /*transmission_type*/,
266                             EncryptionLevel /*encryption_level*/,
267                             const QuicFrames& /*retransmittable_frames*/,
268                             const QuicFrames& /*nonretransmittable_frames*/,
269                             QuicTime /*sent_time*/) {}
270 
271   // Called when a coalesced packet is successfully serialized.
OnCoalescedPacketSent(const QuicCoalescedPacket &,size_t)272   virtual void OnCoalescedPacketSent(
273       const QuicCoalescedPacket& /*coalesced_packet*/, size_t /*length*/) {}
274 
275   // Called when a PING frame has been sent.
OnPingSent()276   virtual void OnPingSent() {}
277 
278   // Called when a packet has been received, but before it is
279   // validated or parsed.
OnPacketReceived(const QuicSocketAddress &,const QuicSocketAddress &,const QuicEncryptedPacket &)280   virtual void OnPacketReceived(const QuicSocketAddress& /*self_address*/,
281                                 const QuicSocketAddress& /*peer_address*/,
282                                 const QuicEncryptedPacket& /*packet*/) {}
283 
284   // Called when the unauthenticated portion of the header has been parsed.
OnUnauthenticatedHeader(const QuicPacketHeader &)285   virtual void OnUnauthenticatedHeader(const QuicPacketHeader& /*header*/) {}
286 
287   // Called when a packet is received with a connection id that does not
288   // match the ID of this connection.
OnIncorrectConnectionId(QuicConnectionId)289   virtual void OnIncorrectConnectionId(QuicConnectionId /*connection_id*/) {}
290 
291   // Called when an undecryptable packet has been received. If |dropped| is
292   // true, the packet has been dropped. Otherwise, the packet will be queued and
293   // connection will attempt to process it later.
OnUndecryptablePacket(EncryptionLevel,bool)294   virtual void OnUndecryptablePacket(EncryptionLevel /*decryption_level*/,
295                                      bool /*dropped*/) {}
296 
297   // Called when attempting to process a previously undecryptable packet.
OnAttemptingToProcessUndecryptablePacket(EncryptionLevel)298   virtual void OnAttemptingToProcessUndecryptablePacket(
299       EncryptionLevel /*decryption_level*/) {}
300 
301   // Called when a duplicate packet has been received.
OnDuplicatePacket(QuicPacketNumber)302   virtual void OnDuplicatePacket(QuicPacketNumber /*packet_number*/) {}
303 
304   // Called when the protocol version on the received packet doensn't match
305   // current protocol version of the connection.
OnProtocolVersionMismatch(ParsedQuicVersion)306   virtual void OnProtocolVersionMismatch(ParsedQuicVersion /*version*/) {}
307 
308   // Called when the complete header of a packet has been parsed.
OnPacketHeader(const QuicPacketHeader &,QuicTime,EncryptionLevel)309   virtual void OnPacketHeader(const QuicPacketHeader& /*header*/,
310                               QuicTime /*receive_time*/,
311                               EncryptionLevel /*level*/) {}
312 
313   // Called when a StreamFrame has been parsed.
OnStreamFrame(const QuicStreamFrame &)314   virtual void OnStreamFrame(const QuicStreamFrame& /*frame*/) {}
315 
316   // Called when a CRYPTO frame containing handshake data is received.
OnCryptoFrame(const QuicCryptoFrame &)317   virtual void OnCryptoFrame(const QuicCryptoFrame& /*frame*/) {}
318 
319   // Called when a StopWaitingFrame has been parsed.
OnStopWaitingFrame(const QuicStopWaitingFrame &)320   virtual void OnStopWaitingFrame(const QuicStopWaitingFrame& /*frame*/) {}
321 
322   // Called when a QuicPaddingFrame has been parsed.
OnPaddingFrame(const QuicPaddingFrame &)323   virtual void OnPaddingFrame(const QuicPaddingFrame& /*frame*/) {}
324 
325   // Called when a Ping has been parsed.
OnPingFrame(const QuicPingFrame &,QuicTime::Delta)326   virtual void OnPingFrame(const QuicPingFrame& /*frame*/,
327                            QuicTime::Delta /*ping_received_delay*/) {}
328 
329   // Called when a GoAway has been parsed.
OnGoAwayFrame(const QuicGoAwayFrame &)330   virtual void OnGoAwayFrame(const QuicGoAwayFrame& /*frame*/) {}
331 
332   // Called when a RstStreamFrame has been parsed.
OnRstStreamFrame(const QuicRstStreamFrame &)333   virtual void OnRstStreamFrame(const QuicRstStreamFrame& /*frame*/) {}
334 
335   // Called when a ConnectionCloseFrame has been parsed. All forms
336   // of CONNECTION CLOSE are handled, Google QUIC, IETF QUIC
337   // CONNECTION CLOSE/Transport and IETF QUIC CONNECTION CLOSE/Application
OnConnectionCloseFrame(const QuicConnectionCloseFrame &)338   virtual void OnConnectionCloseFrame(
339       const QuicConnectionCloseFrame& /*frame*/) {}
340 
341   // Called when a WindowUpdate has been parsed.
OnWindowUpdateFrame(const QuicWindowUpdateFrame &,const QuicTime &)342   virtual void OnWindowUpdateFrame(const QuicWindowUpdateFrame& /*frame*/,
343                                    const QuicTime& /*receive_time*/) {}
344 
345   // Called when a BlockedFrame has been parsed.
OnBlockedFrame(const QuicBlockedFrame &)346   virtual void OnBlockedFrame(const QuicBlockedFrame& /*frame*/) {}
347 
348   // Called when a NewConnectionIdFrame has been parsed.
OnNewConnectionIdFrame(const QuicNewConnectionIdFrame &)349   virtual void OnNewConnectionIdFrame(
350       const QuicNewConnectionIdFrame& /*frame*/) {}
351 
352   // Called when a RetireConnectionIdFrame has been parsed.
OnRetireConnectionIdFrame(const QuicRetireConnectionIdFrame &)353   virtual void OnRetireConnectionIdFrame(
354       const QuicRetireConnectionIdFrame& /*frame*/) {}
355 
356   // Called when a NewTokenFrame has been parsed.
OnNewTokenFrame(const QuicNewTokenFrame &)357   virtual void OnNewTokenFrame(const QuicNewTokenFrame& /*frame*/) {}
358 
359   // Called when a MessageFrame has been parsed.
OnMessageFrame(const QuicMessageFrame &)360   virtual void OnMessageFrame(const QuicMessageFrame& /*frame*/) {}
361 
362   // Called when a HandshakeDoneFrame has been parsed.
OnHandshakeDoneFrame(const QuicHandshakeDoneFrame &)363   virtual void OnHandshakeDoneFrame(const QuicHandshakeDoneFrame& /*frame*/) {}
364 
365   // Called when a public reset packet has been received.
OnPublicResetPacket(const QuicPublicResetPacket &)366   virtual void OnPublicResetPacket(const QuicPublicResetPacket& /*packet*/) {}
367 
368   // Called when a version negotiation packet has been received.
OnVersionNegotiationPacket(const QuicVersionNegotiationPacket &)369   virtual void OnVersionNegotiationPacket(
370       const QuicVersionNegotiationPacket& /*packet*/) {}
371 
372   // Called when the connection is closed.
OnConnectionClosed(const QuicConnectionCloseFrame &,ConnectionCloseSource)373   virtual void OnConnectionClosed(const QuicConnectionCloseFrame& /*frame*/,
374                                   ConnectionCloseSource /*source*/) {}
375 
376   // Called when the version negotiation is successful.
OnSuccessfulVersionNegotiation(const ParsedQuicVersion &)377   virtual void OnSuccessfulVersionNegotiation(
378       const ParsedQuicVersion& /*version*/) {}
379 
380   // Called when a CachedNetworkParameters is sent to the client.
OnSendConnectionState(const CachedNetworkParameters &)381   virtual void OnSendConnectionState(
382       const CachedNetworkParameters& /*cached_network_params*/) {}
383 
384   // Called when a CachedNetworkParameters are received from the client.
OnReceiveConnectionState(const CachedNetworkParameters &)385   virtual void OnReceiveConnectionState(
386       const CachedNetworkParameters& /*cached_network_params*/) {}
387 
388   // Called when the connection parameters are set from the supplied
389   // |config|.
OnSetFromConfig(const QuicConfig &)390   virtual void OnSetFromConfig(const QuicConfig& /*config*/) {}
391 
392   // Called when RTT may have changed, including when an RTT is read from
393   // the config.
OnRttChanged(QuicTime::Delta)394   virtual void OnRttChanged(QuicTime::Delta /*rtt*/) const {}
395 
396   // Called when a StopSendingFrame has been parsed.
OnStopSendingFrame(const QuicStopSendingFrame &)397   virtual void OnStopSendingFrame(const QuicStopSendingFrame& /*frame*/) {}
398 
399   // Called when a PathChallengeFrame has been parsed.
OnPathChallengeFrame(const QuicPathChallengeFrame &)400   virtual void OnPathChallengeFrame(const QuicPathChallengeFrame& /*frame*/) {}
401 
402   // Called when a PathResponseFrame has been parsed.
OnPathResponseFrame(const QuicPathResponseFrame &)403   virtual void OnPathResponseFrame(const QuicPathResponseFrame& /*frame*/) {}
404 
405   // Called when a StreamsBlockedFrame has been parsed.
OnStreamsBlockedFrame(const QuicStreamsBlockedFrame &)406   virtual void OnStreamsBlockedFrame(const QuicStreamsBlockedFrame& /*frame*/) {
407   }
408 
409   // Called when a MaxStreamsFrame has been parsed.
OnMaxStreamsFrame(const QuicMaxStreamsFrame &)410   virtual void OnMaxStreamsFrame(const QuicMaxStreamsFrame& /*frame*/) {}
411 
412   // Called when an AckFrequencyFrame has been parsed.
OnAckFrequencyFrame(const QuicAckFrequencyFrame &)413   virtual void OnAckFrequencyFrame(const QuicAckFrequencyFrame& /*frame*/) {}
414 
415   // Called when |count| packet numbers have been skipped.
OnNPacketNumbersSkipped(QuicPacketCount,QuicTime)416   virtual void OnNPacketNumbersSkipped(QuicPacketCount /*count*/,
417                                        QuicTime /*now*/) {}
418 
419   // Called when a packet is serialized but discarded (i.e. not sent).
OnPacketDiscarded(const SerializedPacket &)420   virtual void OnPacketDiscarded(const SerializedPacket& /*packet*/) {}
421 
422   // Called for QUIC+TLS versions when we send transport parameters.
OnTransportParametersSent(const TransportParameters &)423   virtual void OnTransportParametersSent(
424       const TransportParameters& /*transport_parameters*/) {}
425 
426   // Called for QUIC+TLS versions when we receive transport parameters.
OnTransportParametersReceived(const TransportParameters &)427   virtual void OnTransportParametersReceived(
428       const TransportParameters& /*transport_parameters*/) {}
429 
430   // Called for QUIC+TLS versions when we resume cached transport parameters for
431   // 0-RTT.
OnTransportParametersResumed(const TransportParameters &)432   virtual void OnTransportParametersResumed(
433       const TransportParameters& /*transport_parameters*/) {}
434 
435   // Called for QUIC+TLS versions when 0-RTT is rejected.
OnZeroRttRejected(int)436   virtual void OnZeroRttRejected(int /*reject_reason*/) {}
437 
438   // Called for QUIC+TLS versions when 0-RTT packet gets acked.
OnZeroRttPacketAcked()439   virtual void OnZeroRttPacketAcked() {}
440 
441   // Called on peer address change.
OnPeerAddressChange(AddressChangeType,QuicTime::Delta)442   virtual void OnPeerAddressChange(AddressChangeType /*type*/,
443                                    QuicTime::Delta /*connection_time*/) {}
444 
445   // Called after peer migration is validated.
OnPeerMigrationValidated(QuicTime::Delta)446   virtual void OnPeerMigrationValidated(QuicTime::Delta /*connection_time*/) {}
447 };
448 
449 class QUIC_EXPORT_PRIVATE QuicConnectionHelperInterface {
450  public:
~QuicConnectionHelperInterface()451   virtual ~QuicConnectionHelperInterface() {}
452 
453   // Returns a QuicClock to be used for all time related functions.
454   virtual const QuicClock* GetClock() const = 0;
455 
456   // Returns a QuicRandom to be used for all random number related functions.
457   virtual QuicRandom* GetRandomGenerator() = 0;
458 
459   // Returns a QuicheBufferAllocator to be used for stream send buffers.
460   virtual quiche::QuicheBufferAllocator* GetStreamSendBufferAllocator() = 0;
461 };
462 
463 class QUIC_EXPORT_PRIVATE QuicConnection
464     : public QuicFramerVisitorInterface,
465       public QuicBlockedWriterInterface,
466       public QuicPacketCreator::DelegateInterface,
467       public QuicSentPacketManager::NetworkChangeVisitor,
468       public QuicNetworkBlackholeDetector::Delegate,
469       public QuicIdleNetworkDetector::Delegate,
470       public QuicPathValidator::SendDelegate,
471       public QuicConnectionIdManagerVisitorInterface,
472       public QuicPingManager::Delegate {
473  public:
474   // Constructs a new QuicConnection for |connection_id| and
475   // |initial_peer_address| using |writer| to write packets. |owns_writer|
476   // specifies whether the connection takes ownership of |writer|. |helper| must
477   // outlive this connection.
478   QuicConnection(QuicConnectionId server_connection_id,
479                  QuicSocketAddress initial_self_address,
480                  QuicSocketAddress initial_peer_address,
481                  QuicConnectionHelperInterface* helper,
482                  QuicAlarmFactory* alarm_factory, QuicPacketWriter* writer,
483                  bool owns_writer, Perspective perspective,
484                  const ParsedQuicVersionVector& supported_versions,
485                  ConnectionIdGeneratorInterface& generator);
486   QuicConnection(const QuicConnection&) = delete;
487   QuicConnection& operator=(const QuicConnection&) = delete;
488   ~QuicConnection() override;
489 
490   struct MultiPortStats {
491     // general rtt stats of the multi-port path.
492     RttStats rtt_stats;
493     // rtt stats for the multi-port path when the default path is degrading.
494     RttStats rtt_stats_when_default_path_degrading;
495     // number of path degrading triggered when multi-port is enabled.
496     size_t num_path_degrading = 0;
497     // number of multi-port probe failures when path is not degrading
498     size_t num_multi_port_probe_failures_when_path_not_degrading = 0;
499     // number of multi-port probe failure when path is degrading
500     size_t num_multi_port_probe_failures_when_path_degrading = 0;
501     // number of total multi-port path creations in a connection
502     size_t num_multi_port_paths_created = 0;
503   };
504 
505   // Sets connection parameters from the supplied |config|.
506   void SetFromConfig(const QuicConfig& config);
507 
508   // Apply |connection_options| for this connection. Unlike SetFromConfig, this
509   // can happen at anytime in the life of a connection.
510   // Note there is no guarantee that all options can be applied. Components will
511   // only apply cherrypicked options that make sense at the time of the call.
512   void ApplyConnectionOptions(const QuicTagVector& connection_options);
513 
514   // Called by the session when sending connection state to the client.
515   virtual void OnSendConnectionState(
516       const CachedNetworkParameters& cached_network_params);
517 
518   // Called by the session when receiving connection state from the client.
519   virtual void OnReceiveConnectionState(
520       const CachedNetworkParameters& cached_network_params);
521 
522   // Called by the Session when the client has provided CachedNetworkParameters.
523   virtual void ResumeConnectionState(
524       const CachedNetworkParameters& cached_network_params,
525       bool max_bandwidth_resumption);
526 
527   // Called by the Session when a max pacing rate for the connection is needed.
528   virtual void SetMaxPacingRate(QuicBandwidth max_pacing_rate);
529 
530   // Allows the client to adjust network parameters based on external
531   // information.
532   void AdjustNetworkParameters(
533       const SendAlgorithmInterface::NetworkParams& params);
534   void AdjustNetworkParameters(QuicBandwidth bandwidth, QuicTime::Delta rtt,
535                                bool allow_cwnd_to_decrease);
536 
537   // Install a loss detection tuner. Must be called before OnConfigNegotiated.
538   void SetLossDetectionTuner(
539       std::unique_ptr<LossDetectionTunerInterface> tuner);
540   // Called by the session when session->is_configured() becomes true.
541   void OnConfigNegotiated();
542 
543   // Returns the max pacing rate for the connection.
544   virtual QuicBandwidth MaxPacingRate() const;
545 
546   // Sends crypto handshake messages of length |write_length| to the peer in as
547   // few packets as possible. Returns the number of bytes consumed from the
548   // data.
549   virtual size_t SendCryptoData(EncryptionLevel level, size_t write_length,
550                                 QuicStreamOffset offset);
551 
552   // Send the data of length |write_length| to the peer in as few packets as
553   // possible. Returns the number of bytes consumed from data, and a boolean
554   // indicating if the fin bit was consumed.  This does not indicate the data
555   // has been sent on the wire: it may have been turned into a packet and queued
556   // if the socket was unexpectedly blocked.
557   virtual QuicConsumedData SendStreamData(QuicStreamId id, size_t write_length,
558                                           QuicStreamOffset offset,
559                                           StreamSendingState state);
560 
561   // Send |frame| to the peer. Returns true if frame is consumed, false
562   // otherwise.
563   virtual bool SendControlFrame(const QuicFrame& frame);
564 
565   // Called when stream |id| is reset because of |error|.
566   virtual void OnStreamReset(QuicStreamId id, QuicRstStreamErrorCode error);
567 
568   // Closes the connection.
569   // |connection_close_behavior| determines whether or not a connection close
570   // packet is sent to the peer.
571   virtual void CloseConnection(
572       QuicErrorCode error, const std::string& details,
573       ConnectionCloseBehavior connection_close_behavior);
574   // Closes the connection, specifying the wire error code |ietf_error|
575   // explicitly.
576   virtual void CloseConnection(
577       QuicErrorCode error, QuicIetfTransportErrorCodes ietf_error,
578       const std::string& details,
579       ConnectionCloseBehavior connection_close_behavior);
580 
mutable_stats()581   QuicConnectionStats& mutable_stats() { return stats_; }
582 
583   // Returns statistics tracked for this connection.
584   const QuicConnectionStats& GetStats();
585 
586   // Processes an incoming UDP packet (consisting of a QuicEncryptedPacket) from
587   // the peer.
588   // In a client, the packet may be "stray" and have a different connection ID
589   // than that of this connection.
590   virtual void ProcessUdpPacket(const QuicSocketAddress& self_address,
591                                 const QuicSocketAddress& peer_address,
592                                 const QuicReceivedPacket& packet);
593 
594   // QuicBlockedWriterInterface
595   // Called when the underlying connection becomes writable to allow queued
596   // writes to happen.
597   void OnBlockedWriterCanWrite() override;
598 
IsWriterBlocked()599   bool IsWriterBlocked() const override {
600     return writer_ != nullptr && writer_->IsWriteBlocked();
601   }
602 
603   // Called when the caller thinks it's worth a try to write.
604   // TODO(fayang): consider unifying this with QuicSession::OnCanWrite.
605   virtual void OnCanWrite();
606 
607   // Called when an error occurs while attempting to write a packet to the
608   // network.
609   void OnWriteError(int error_code);
610 
611   // Whether |result| represents a MSG TOO BIG write error.
612   bool IsMsgTooBig(const QuicPacketWriter* writer, const WriteResult& result);
613 
614   // If the socket is not blocked, writes queued packets.
615   void WriteIfNotBlocked();
616 
617   // Set the packet writer.
SetQuicPacketWriter(QuicPacketWriter * writer,bool owns_writer)618   void SetQuicPacketWriter(QuicPacketWriter* writer, bool owns_writer) {
619     QUICHE_DCHECK(writer != nullptr);
620     if (writer_ != nullptr && owns_writer_) {
621       delete writer_;
622     }
623     writer_ = writer;
624     owns_writer_ = owns_writer;
625   }
626 
627   // Set self address.
SetSelfAddress(QuicSocketAddress address)628   void SetSelfAddress(QuicSocketAddress address) {
629     default_path_.self_address = address;
630   }
631 
632   // The version of the protocol this connection is using.
transport_version()633   QuicTransportVersion transport_version() const {
634     return framer_.transport_version();
635   }
636 
version()637   ParsedQuicVersion version() const { return framer_.version(); }
638 
639   // The versions of the protocol that this connection supports.
supported_versions()640   const ParsedQuicVersionVector& supported_versions() const {
641     return framer_.supported_versions();
642   }
643 
644   // Mark version negotiated for this connection. Once called, the connection
645   // will ignore received version negotiation packets.
SetVersionNegotiated()646   void SetVersionNegotiated() {
647     version_negotiated_ = true;
648     if (perspective_ == Perspective::IS_SERVER) {
649       framer_.InferPacketHeaderTypeFromVersion();
650     }
651   }
652 
653   // From QuicFramerVisitorInterface
654   void OnError(QuicFramer* framer) override;
655   bool OnProtocolVersionMismatch(ParsedQuicVersion received_version) override;
656   void OnPacket() override;
657   void OnPublicResetPacket(const QuicPublicResetPacket& packet) override;
658   void OnVersionNegotiationPacket(
659       const QuicVersionNegotiationPacket& packet) override;
660   void OnRetryPacket(QuicConnectionId original_connection_id,
661                      QuicConnectionId new_connection_id,
662                      absl::string_view retry_token,
663                      absl::string_view retry_integrity_tag,
664                      absl::string_view retry_without_tag) override;
665   bool OnUnauthenticatedPublicHeader(const QuicPacketHeader& header) override;
666   bool OnUnauthenticatedHeader(const QuicPacketHeader& header) override;
667   void OnDecryptedPacket(size_t length, EncryptionLevel level) override;
668   bool OnPacketHeader(const QuicPacketHeader& header) override;
669   void OnCoalescedPacket(const QuicEncryptedPacket& packet) override;
670   void OnUndecryptablePacket(const QuicEncryptedPacket& packet,
671                              EncryptionLevel decryption_level,
672                              bool has_decryption_key) override;
673   bool OnStreamFrame(const QuicStreamFrame& frame) override;
674   bool OnCryptoFrame(const QuicCryptoFrame& frame) override;
675   bool OnAckFrameStart(QuicPacketNumber largest_acked,
676                        QuicTime::Delta ack_delay_time) override;
677   bool OnAckRange(QuicPacketNumber start, QuicPacketNumber end) override;
678   bool OnAckTimestamp(QuicPacketNumber packet_number,
679                       QuicTime timestamp) override;
680   bool OnAckFrameEnd(QuicPacketNumber start,
681                      const absl::optional<QuicEcnCounts>& ecn_counts) override;
682   bool OnStopWaitingFrame(const QuicStopWaitingFrame& frame) override;
683   bool OnPaddingFrame(const QuicPaddingFrame& frame) override;
684   bool OnPingFrame(const QuicPingFrame& frame) override;
685   bool OnRstStreamFrame(const QuicRstStreamFrame& frame) override;
686   bool OnConnectionCloseFrame(const QuicConnectionCloseFrame& frame) override;
687   bool OnStopSendingFrame(const QuicStopSendingFrame& frame) override;
688   bool OnPathChallengeFrame(const QuicPathChallengeFrame& frame) override;
689   bool OnPathResponseFrame(const QuicPathResponseFrame& frame) override;
690   bool OnGoAwayFrame(const QuicGoAwayFrame& frame) override;
691   bool OnMaxStreamsFrame(const QuicMaxStreamsFrame& frame) override;
692   bool OnStreamsBlockedFrame(const QuicStreamsBlockedFrame& frame) override;
693   bool OnWindowUpdateFrame(const QuicWindowUpdateFrame& frame) override;
694   bool OnBlockedFrame(const QuicBlockedFrame& frame) override;
695   bool OnNewConnectionIdFrame(const QuicNewConnectionIdFrame& frame) override;
696   bool OnRetireConnectionIdFrame(
697       const QuicRetireConnectionIdFrame& frame) override;
698   bool OnNewTokenFrame(const QuicNewTokenFrame& frame) override;
699   bool OnMessageFrame(const QuicMessageFrame& frame) override;
700   bool OnHandshakeDoneFrame(const QuicHandshakeDoneFrame& frame) override;
701   bool OnAckFrequencyFrame(const QuicAckFrequencyFrame& frame) override;
702   void OnPacketComplete() override;
703   bool IsValidStatelessResetToken(
704       const StatelessResetToken& token) const override;
705   void OnAuthenticatedIetfStatelessResetPacket(
706       const QuicIetfStatelessResetPacket& packet) override;
707   void OnKeyUpdate(KeyUpdateReason reason) override;
708   void OnDecryptedFirstPacketInKeyPhase() override;
709   std::unique_ptr<QuicDecrypter> AdvanceKeysAndCreateCurrentOneRttDecrypter()
710       override;
711   std::unique_ptr<QuicEncrypter> CreateCurrentOneRttEncrypter() override;
712 
713   // QuicPacketCreator::DelegateInterface
714   bool ShouldGeneratePacket(HasRetransmittableData retransmittable,
715                             IsHandshake handshake) override;
716   const QuicFrames MaybeBundleAckOpportunistically() override;
717   QuicPacketBuffer GetPacketBuffer() override;
718   void OnSerializedPacket(SerializedPacket packet) override;
719   void OnUnrecoverableError(QuicErrorCode error,
720                             const std::string& error_details) override;
721   SerializedPacketFate GetSerializedPacketFate(
722       bool is_mtu_discovery, EncryptionLevel encryption_level) override;
723 
724   // QuicSentPacketManager::NetworkChangeVisitor
725   void OnCongestionChange() override;
726   void OnPathMtuIncreased(QuicPacketLength packet_size) override;
727 
728   // QuicNetworkBlackholeDetector::Delegate
729   void OnPathDegradingDetected() override;
730   void OnBlackholeDetected() override;
731   void OnPathMtuReductionDetected() override;
732 
733   // QuicIdleNetworkDetector::Delegate
734   void OnHandshakeTimeout() override;
735   void OnIdleNetworkDetected() override;
736   void OnBandwidthUpdateTimeout() override;
737 
738   // QuicPingManager::Delegate
739   void OnKeepAliveTimeout() override;
740   void OnRetransmittableOnWireTimeout() override;
741 
742   // QuicConnectionIdManagerVisitorInterface
743   void OnPeerIssuedConnectionIdRetired() override;
744   bool SendNewConnectionId(const QuicNewConnectionIdFrame& frame) override;
745   bool MaybeReserveConnectionId(const QuicConnectionId& connection_id) override;
746   void OnSelfIssuedConnectionIdRetired(
747       const QuicConnectionId& connection_id) override;
748 
749   // Please note, this is not a const function. For logging purpose, please use
750   // ack_frame().
751   const QuicFrame GetUpdatedAckFrame();
752 
753   // Called to send a new connection ID to client if the # of connection ID has
754   // not exceeded the active connection ID limits.
755   void MaybeSendConnectionIdToClient();
756 
757   // Called when the handshake completes. On the client side, handshake
758   // completes on receipt of SHLO. On the server side, handshake completes when
759   // SHLO gets ACKed (or a forward secure packet gets decrypted successfully).
760   // TODO(fayang): Add a guard that this only gets called once.
761   void OnHandshakeComplete();
762 
763   // Creates and probes an multi-port path if none exists.
764   void MaybeCreateMultiPortPath();
765 
766   // Called in multi-port QUIC when the alternative path validation succeeds.
767   // Stores the path validation context and prepares for the next validation.
768   void OnMultiPortPathProbingSuccess(
769       std::unique_ptr<QuicPathValidationContext> context, QuicTime start_time);
770 
771   // Probe the existing alternative path. Does not create a new alternative
772   // path. This method is the callback for |multi_port_probing_alarm_|.
773   virtual void MaybeProbeMultiPortPath();
774 
775   // Accessors
set_visitor(QuicConnectionVisitorInterface * visitor)776   void set_visitor(QuicConnectionVisitorInterface* visitor) {
777     visitor_ = visitor;
778   }
set_debug_visitor(QuicConnectionDebugVisitor * debug_visitor)779   void set_debug_visitor(QuicConnectionDebugVisitor* debug_visitor) {
780     debug_visitor_ = debug_visitor;
781     sent_packet_manager_.SetDebugDelegate(debug_visitor);
782   }
783   // Used in Chromium, but not internally.
784   // Must only be called before ping_alarm_ is set.
785   void set_keep_alive_ping_timeout(QuicTime::Delta keep_alive_ping_timeout);
786   // Sets an initial timeout for the ping alarm when there is no retransmittable
787   // data in flight, allowing for a more aggressive ping alarm in that case.
788   void set_initial_retransmittable_on_wire_timeout(
789       QuicTime::Delta retransmittable_on_wire_timeout);
790   // Used in Chromium, but not internally.
set_creator_debug_delegate(QuicPacketCreator::DebugDelegate * visitor)791   void set_creator_debug_delegate(QuicPacketCreator::DebugDelegate* visitor) {
792     packet_creator_.set_debug_delegate(visitor);
793   }
self_address()794   const QuicSocketAddress& self_address() const {
795     return default_path_.self_address;
796   }
peer_address()797   const QuicSocketAddress& peer_address() const { return direct_peer_address_; }
effective_peer_address()798   const QuicSocketAddress& effective_peer_address() const {
799     return default_path_.peer_address;
800   }
801 
802   // Returns the server connection ID used on the default path.
connection_id()803   const QuicConnectionId& connection_id() const {
804     return default_path_.server_connection_id;
805   }
806 
client_connection_id()807   const QuicConnectionId& client_connection_id() const {
808     return default_path_.client_connection_id;
809   }
810   void set_client_connection_id(QuicConnectionId client_connection_id);
clock()811   const QuicClock* clock() const { return clock_; }
random_generator()812   QuicRandom* random_generator() const { return random_generator_; }
813   QuicByteCount max_packet_length() const;
814   void SetMaxPacketLength(QuicByteCount length);
815 
mtu_probe_count()816   size_t mtu_probe_count() const { return mtu_probe_count_; }
817 
connected()818   bool connected() const { return connected_; }
819 
820   // Must only be called on client connections.
server_supported_versions()821   const ParsedQuicVersionVector& server_supported_versions() const {
822     QUICHE_DCHECK_EQ(Perspective::IS_CLIENT, perspective_);
823     return server_supported_versions_;
824   }
825 
HasQueuedPackets()826   bool HasQueuedPackets() const { return !buffered_packets_.empty(); }
827   // Testing only. TODO(ianswett): Use a peer instead.
NumQueuedPackets()828   size_t NumQueuedPackets() const { return buffered_packets_.size(); }
829 
830   // Returns true if the connection has queued packets or frames.
831   bool HasQueuedData() const;
832 
833   // Sets the handshake and idle state connection timeouts.
834   void SetNetworkTimeouts(QuicTime::Delta handshake_timeout,
835                           QuicTime::Delta idle_timeout);
836 
SetMultiPortProbingInterval(QuicTime::Delta probing_interval)837   void SetMultiPortProbingInterval(QuicTime::Delta probing_interval) {
838     multi_port_probing_interval_ = probing_interval;
839   }
840 
multi_port_stats()841   const MultiPortStats* multi_port_stats() const {
842     return multi_port_stats_.get();
843   }
844 
845   // Sets up a packet with an QuicAckFrame and sends it out.
846   void SendAck();
847 
848   // Called when an RTO fires.  Resets the retransmission alarm if there are
849   // remaining unacked packets.
850   void OnRetransmissionTimeout();
851 
852   // Mark all sent 0-RTT encrypted packets for retransmission. Called when new
853   // 0-RTT or 1-RTT key is available in gQUIC, or when 0-RTT is rejected in IETF
854   // QUIC. |reject_reason| is used in TLS-QUIC to log why 0-RTT was rejected.
855   void MarkZeroRttPacketsForRetransmission(int reject_reason);
856 
857   // Calls |sent_packet_manager_|'s NeuterUnencryptedPackets. Used when the
858   // connection becomes forward secure and hasn't received acks for all packets.
859   void NeuterUnencryptedPackets();
860 
861   // Changes the encrypter used for level |level| to |encrypter|.
862   void SetEncrypter(EncryptionLevel level,
863                     std::unique_ptr<QuicEncrypter> encrypter);
864 
865   // Called to remove encrypter of encryption |level|.
866   void RemoveEncrypter(EncryptionLevel level);
867 
868   // SetNonceForPublicHeader sets the nonce that will be transmitted in the
869   // header of each packet encrypted at the initial encryption level decrypted.
870   // This should only be called on the server side.
871   void SetDiversificationNonce(const DiversificationNonce& nonce);
872 
873   // SetDefaultEncryptionLevel sets the encryption level that will be applied
874   // to new packets.
875   void SetDefaultEncryptionLevel(EncryptionLevel level);
876 
877   // SetDecrypter sets the primary decrypter, replacing any that already exists.
878   // If an alternative decrypter is in place then the function QUICHE_DCHECKs.
879   // This is intended for cases where one knows that future packets will be
880   // using the new decrypter and the previous decrypter is now obsolete. |level|
881   // indicates the encryption level of the new decrypter.
882   void SetDecrypter(EncryptionLevel level,
883                     std::unique_ptr<QuicDecrypter> decrypter);
884 
885   // SetAlternativeDecrypter sets a decrypter that may be used to decrypt
886   // future packets. |level| indicates the encryption level of the decrypter. If
887   // |latch_once_used| is true, then the first time that the decrypter is
888   // successful it will replace the primary decrypter.  Otherwise both
889   // decrypters will remain active and the primary decrypter will be the one
890   // last used.
891   void SetAlternativeDecrypter(EncryptionLevel level,
892                                std::unique_ptr<QuicDecrypter> decrypter,
893                                bool latch_once_used);
894 
895   void InstallDecrypter(EncryptionLevel level,
896                         std::unique_ptr<QuicDecrypter> decrypter);
897   void RemoveDecrypter(EncryptionLevel level);
898 
899   // Discard keys for the previous key phase.
900   void DiscardPreviousOneRttKeys();
901 
902   // Returns true if it is currently allowed to initiate a key update.
903   bool IsKeyUpdateAllowed() const;
904 
905   // Returns true if packets have been sent in the current 1-RTT key phase but
906   // none of these packets have been acked.
907   bool HaveSentPacketsInCurrentKeyPhaseButNoneAcked() const;
908 
909   // Returns the count of packets received that appeared to attempt a key
910   // update but failed decryption that have been received since the last
911   // successfully decrypted packet.
912   QuicPacketCount PotentialPeerKeyUpdateAttemptCount() const;
913 
914   // Increment the key phase. It is a bug to call this when IsKeyUpdateAllowed()
915   // is false. Returns false on error.
916   bool InitiateKeyUpdate(KeyUpdateReason reason);
917 
918   const QuicDecrypter* decrypter() const;
919   const QuicDecrypter* alternative_decrypter() const;
920 
perspective()921   Perspective perspective() const { return perspective_; }
922 
923   // Allow easy overriding of truncated connection IDs.
set_can_truncate_connection_ids(bool can)924   void set_can_truncate_connection_ids(bool can) {
925     can_truncate_connection_ids_ = can;
926   }
927 
928   // Returns the underlying sent packet manager.
sent_packet_manager()929   const QuicSentPacketManager& sent_packet_manager() const {
930     return sent_packet_manager_;
931   }
932 
933   // Returns the underlying sent packet manager.
sent_packet_manager()934   QuicSentPacketManager& sent_packet_manager() { return sent_packet_manager_; }
935 
received_packet_manager()936   UberReceivedPacketManager& received_packet_manager() {
937     return uber_received_packet_manager_;
938   }
939 
940   bool CanWrite(HasRetransmittableData retransmittable);
941 
942   // When the flusher is out of scope, only the outermost flusher will cause a
943   // flush of the connection and set the retransmission alarm if there is one
944   // pending.  In addition, this flusher can be configured to ensure that an ACK
945   // frame is included in the first packet created, if there's new ack
946   // information to be sent.
947   class QUIC_EXPORT_PRIVATE ScopedPacketFlusher {
948    public:
949     explicit ScopedPacketFlusher(QuicConnection* connection);
950     ~ScopedPacketFlusher();
951 
952    private:
953     QuicConnection* connection_;
954     // If true, when this flusher goes out of scope, flush connection and set
955     // retransmission alarm if there is one pending.
956     bool flush_and_set_pending_retransmission_alarm_on_delete_;
957     // Latched connection's handshake_packet_sent_ on creation of this flusher.
958     const bool handshake_packet_sent_;
959   };
960 
961   class QUIC_EXPORT_PRIVATE ScopedEncryptionLevelContext {
962    public:
963     ScopedEncryptionLevelContext(QuicConnection* connection,
964                                  EncryptionLevel level);
965     ~ScopedEncryptionLevelContext();
966 
967    private:
968     QuicConnection* connection_;
969     // Latched current write encryption level on creation of this context.
970     EncryptionLevel latched_encryption_level_;
971   };
972 
writer()973   QuicPacketWriter* writer() { return writer_; }
writer()974   const QuicPacketWriter* writer() const { return writer_; }
975 
976   // Sends an MTU discovery packet of size |target_mtu|.  If the packet is
977   // acknowledged by the peer, the maximum packet size will be increased to
978   // |target_mtu|.
979   void SendMtuDiscoveryPacket(QuicByteCount target_mtu);
980 
981   // Sends a connectivity probing packet to |peer_address| with
982   // |probing_writer|. If |probing_writer| is nullptr, will use default
983   // packet writer to write the packet. Returns true if subsequent packets can
984   // be written to the probing writer. If connection is V99, a padded IETF QUIC
985   // PATH_CHALLENGE packet is transmitted; if not V99, a Google QUIC padded PING
986   // packet is transmitted.
987   virtual bool SendConnectivityProbingPacket(
988       QuicPacketWriter* probing_writer, const QuicSocketAddress& peer_address);
989 
990   // Disable MTU discovery on this connection.
991   void DisableMtuDiscovery();
992 
993   // Sends an MTU discovery packet and updates the MTU discovery alarm.
994   void DiscoverMtu();
995 
996   // Sets the session notifier on the SentPacketManager.
997   void SetSessionNotifier(SessionNotifierInterface* session_notifier);
998 
999   // Set data producer in framer.
1000   void SetDataProducer(QuicStreamFrameDataProducer* data_producer);
1001 
1002   // Set transmission type of next sending packets.
1003   void SetTransmissionType(TransmissionType type);
1004 
1005   // Tries to send |message| and returns the message status.
1006   // If |flush| is false, this will return a MESSAGE_STATUS_BLOCKED
1007   // when the connection is deemed unwritable.
1008   virtual MessageStatus SendMessage(QuicMessageId message_id,
1009                                     absl::Span<quiche::QuicheMemSlice> message,
1010                                     bool flush);
1011 
1012   // Returns the largest payload that will fit into a single MESSAGE frame.
1013   // Because overhead can vary during a connection, this method should be
1014   // checked for every message.
1015   QuicPacketLength GetCurrentLargestMessagePayload() const;
1016   // Returns the largest payload that will fit into a single MESSAGE frame at
1017   // any point during the connection.  This assumes the version and
1018   // connection ID lengths do not change.
1019   QuicPacketLength GetGuaranteedLargestMessagePayload() const;
1020 
1021   void SetUnackedMapInitialCapacity();
1022 
GetUnackedMapInitialCapacity()1023   virtual int GetUnackedMapInitialCapacity() const {
1024     return kDefaultUnackedPacketsInitialCapacity;
1025   }
1026 
1027   // Returns the id of the cipher last used for decrypting packets.
1028   uint32_t cipher_id() const;
1029 
termination_packets()1030   std::vector<std::unique_ptr<QuicEncryptedPacket>>* termination_packets() {
1031     return termination_packets_.get();
1032   }
1033 
1034   bool ack_frame_updated() const;
1035 
helper()1036   QuicConnectionHelperInterface* helper() { return helper_; }
helper()1037   const QuicConnectionHelperInterface* helper() const { return helper_; }
alarm_factory()1038   QuicAlarmFactory* alarm_factory() { return alarm_factory_; }
1039 
1040   absl::string_view GetCurrentPacket();
1041 
framer()1042   const QuicFramer& framer() const { return framer_; }
1043 
packet_creator()1044   const QuicPacketCreator& packet_creator() const { return packet_creator_; }
1045 
encryption_level()1046   EncryptionLevel encryption_level() const { return encryption_level_; }
last_decrypted_level()1047   EncryptionLevel last_decrypted_level() const {
1048     return last_received_packet_info_.decrypted_level;
1049   }
1050 
last_packet_source_address()1051   const QuicSocketAddress& last_packet_source_address() const {
1052     return last_received_packet_info_.source_address;
1053   }
1054 
1055   // This setting may be changed during the crypto handshake in order to
1056   // enable/disable padding of different packets in the crypto handshake.
1057   //
1058   // This setting should never be set to false in public facing endpoints. It
1059   // can only be set to false if there is some other mechanism of preventing
1060   // amplification attacks, such as ICE (plus its a non-standard quic).
set_fully_pad_crypto_handshake_packets(bool new_value)1061   void set_fully_pad_crypto_handshake_packets(bool new_value) {
1062     packet_creator_.set_fully_pad_crypto_handshake_packets(new_value);
1063   }
1064 
fully_pad_during_crypto_handshake()1065   bool fully_pad_during_crypto_handshake() const {
1066     return packet_creator_.fully_pad_crypto_handshake_packets();
1067   }
1068 
1069   size_t min_received_before_ack_decimation() const;
1070   void set_min_received_before_ack_decimation(size_t new_value);
1071 
1072   // If |defer| is true, configures the connection to defer sending packets in
1073   // response to an ACK to the SendAlarm. If |defer| is false, packets may be
1074   // sent immediately after receiving an ACK.
set_defer_send_in_response_to_packets(bool defer)1075   void set_defer_send_in_response_to_packets(bool defer) {
1076     defer_send_in_response_to_packets_ = defer;
1077   }
1078 
1079   // Sets the current per-packet options for the connection. The QuicConnection
1080   // does not take ownership of |options|; |options| must live for as long as
1081   // the QuicConnection is in use.
set_per_packet_options(PerPacketOptions * options)1082   void set_per_packet_options(PerPacketOptions* options) {
1083     per_packet_options_ = options;
1084   }
1085 
IsPathDegrading()1086   bool IsPathDegrading() const { return is_path_degrading_; }
1087 
1088   // Attempts to process any queued undecryptable packets.
1089   void MaybeProcessUndecryptablePackets();
1090 
1091   // Queue a coalesced packet.
1092   void QueueCoalescedPacket(const QuicEncryptedPacket& packet);
1093 
1094   // Process previously queued coalesced packets. Returns true if any coalesced
1095   // packets have been successfully processed.
1096   bool MaybeProcessCoalescedPackets();
1097 
1098   enum PacketContent : uint8_t {
1099     NO_FRAMES_RECEIVED,
1100     // TODO(fkastenholz): Change name when we get rid of padded ping/
1101     // pre-version-99.
1102     // Also PATH CHALLENGE and PATH RESPONSE.
1103     FIRST_FRAME_IS_PING,
1104     SECOND_FRAME_IS_PADDING,
1105     NOT_PADDED_PING,  // Set if the packet is not {PING, PADDING}.
1106   };
1107 
1108   // Whether the handshake completes from this connection's perspective.
1109   bool IsHandshakeComplete() const;
1110 
1111   // Whether peer completes handshake. Only used with TLS handshake.
1112   bool IsHandshakeConfirmed() const;
1113 
1114   // Returns the largest received packet number sent by peer.
1115   QuicPacketNumber GetLargestReceivedPacket() const;
1116 
1117   // Sets the original destination connection ID on the connection.
1118   // This is called by QuicDispatcher when it has replaced the connection ID.
1119   void SetOriginalDestinationConnectionId(
1120       const QuicConnectionId& original_destination_connection_id);
1121 
1122   // Returns the original destination connection ID used for this connection.
1123   QuicConnectionId GetOriginalDestinationConnectionId() const;
1124 
1125   // Tells the visitor the serverside connection is no longer expecting packets
1126   // with the client-generated destination connection ID.
1127   void RetireOriginalDestinationConnectionId();
1128 
1129   // Called when ACK alarm goes off. Sends ACKs of those packet number spaces
1130   // which have expired ACK timeout. Only used when this connection supports
1131   // multiple packet number spaces.
1132   void SendAllPendingAcks();
1133 
1134   // Returns true if this connection supports multiple packet number spaces.
1135   bool SupportsMultiplePacketNumberSpaces() const;
1136 
1137   // For logging purpose.
1138   const QuicAckFrame& ack_frame() const;
1139 
1140   // Install encrypter and decrypter for ENCRYPTION_INITIAL using
1141   // |connection_id| as the first client-sent destination connection ID,
1142   // or the one sent after an IETF Retry.
1143   void InstallInitialCrypters(QuicConnectionId connection_id);
1144 
1145   // Called when version is considered negotiated.
1146   void OnSuccessfulVersionNegotiation();
1147 
1148   // Called when self migration succeeds after probing.
1149   void OnSuccessfulMigration(bool is_port_change);
1150 
1151   // Called for QUIC+TLS versions when we send transport parameters.
1152   void OnTransportParametersSent(
1153       const TransportParameters& transport_parameters) const;
1154 
1155   // Called for QUIC+TLS versions when we receive transport parameters.
1156   void OnTransportParametersReceived(
1157       const TransportParameters& transport_parameters) const;
1158 
1159   // Called for QUIC+TLS versions when we resume cached transport parameters for
1160   // 0-RTT.
1161   void OnTransportParametersResumed(
1162       const TransportParameters& transport_parameters) const;
1163 
1164   // Returns true if ack_alarm_ is set.
1165   bool HasPendingAcks() const;
1166 
1167   virtual void OnUserAgentIdKnown(const std::string& user_agent_id);
1168 
1169   // If now is close to idle timeout, returns true and sends a connectivity
1170   // probing packet to test the connection for liveness. Otherwise, returns
1171   // false.
1172   bool MaybeTestLiveness();
1173 
1174   // QuicPathValidator::SendDelegate
1175   // Send PATH_CHALLENGE using the given path information. If |writer| is the
1176   // default writer, PATH_CHALLENGE can be bundled with other frames, and the
1177   // containing packet can be buffered if the writer is blocked. Otherwise,
1178   // PATH_CHALLENGE will be written in an individual packet and it will be
1179   // dropped if write fails. |data_buffer| will be populated with the payload
1180   // for future validation.
1181   // Return false if the connection is closed thus the caller will not continue
1182   // the validation, otherwise return true.
1183   bool SendPathChallenge(const QuicPathFrameBuffer& data_buffer,
1184                          const QuicSocketAddress& self_address,
1185                          const QuicSocketAddress& peer_address,
1186                          const QuicSocketAddress& effective_peer_address,
1187                          QuicPacketWriter* writer) override;
1188   // If |writer| is the default writer and |peer_address| is the same as
1189   // peer_address(), return the PTO of this connection. Otherwise, return 3 *
1190   // kInitialRtt.
1191   QuicTime GetRetryTimeout(const QuicSocketAddress& peer_address_to_use,
1192                            QuicPacketWriter* writer_to_use) const override;
1193 
1194   // Start vaildating the path defined by |context| asynchronously and call the
1195   // |result_delegate| after validation finishes. If the connection is
1196   // validating another path, cancel and fail that validation before starting
1197   // this one.
1198   void ValidatePath(
1199       std::unique_ptr<QuicPathValidationContext> context,
1200       std::unique_ptr<QuicPathValidator::ResultDelegate> result_delegate,
1201       PathValidationReason reason);
1202 
can_receive_ack_frequency_frame()1203   bool can_receive_ack_frequency_frame() const {
1204     return can_receive_ack_frequency_frame_;
1205   }
1206 
set_can_receive_ack_frequency_frame()1207   void set_can_receive_ack_frequency_frame() {
1208     can_receive_ack_frequency_frame_ = true;
1209   }
1210 
is_processing_packet()1211   bool is_processing_packet() const { return framer_.is_processing_packet(); }
1212 
1213   bool HasPendingPathValidation() const;
1214 
1215   QuicPathValidationContext* GetPathValidationContext() const;
1216 
1217   void CancelPathValidation();
1218 
1219   // Returns true if the migration succeeds, otherwise returns false (e.g., no
1220   // available CIDs, connection disconnected, etc).
1221   bool MigratePath(const QuicSocketAddress& self_address,
1222                    const QuicSocketAddress& peer_address,
1223                    QuicPacketWriter* writer, bool owns_writer);
1224 
1225   // Called to clear the alternative_path_ when path validation failed on the
1226   // client side.
1227   void OnPathValidationFailureAtClient(
1228       bool is_multi_port, const QuicPathValidationContext& context);
1229 
1230   void SetSourceAddressTokenToSend(absl::string_view token);
1231 
SendPing()1232   void SendPing() {
1233     SendPingAtLevel(framer().GetEncryptionLevelToSendApplicationData());
1234   }
1235 
1236   // Returns one server connection ID that associates the current session in the
1237   // session map.
1238   virtual QuicConnectionId GetOneActiveServerConnectionId() const;
1239 
1240   // Returns all server connection IDs that have not been removed from the
1241   // session map.
1242   virtual std::vector<QuicConnectionId> GetActiveServerConnectionIds() const;
1243 
validate_client_address()1244   bool validate_client_address() const { return validate_client_addresses_; }
1245 
connection_migration_use_new_cid()1246   bool connection_migration_use_new_cid() const {
1247     return connection_migration_use_new_cid_;
1248   }
1249 
1250   // Instantiates connection ID manager.
1251   void CreateConnectionIdManager();
1252 
1253   // Log QUIC_BUG if there is pending frames for the stream with |id|.
1254   void QuicBugIfHasPendingFrames(QuicStreamId id) const;
1255 
context()1256   QuicConnectionContext* context() { return &context_; }
context()1257   const QuicConnectionContext* context() const { return &context_; }
1258 
set_tracer(std::unique_ptr<QuicConnectionTracer> tracer)1259   void set_tracer(std::unique_ptr<QuicConnectionTracer> tracer) {
1260     context_.tracer.swap(tracer);
1261   }
1262 
set_bug_listener(std::unique_ptr<QuicBugListener> bug_listener)1263   void set_bug_listener(std::unique_ptr<QuicBugListener> bug_listener) {
1264     context_.bug_listener.swap(bug_listener);
1265   }
1266 
in_probe_time_out()1267   bool in_probe_time_out() const { return in_probe_time_out_; }
1268 
1269   // Ensures the network blackhole delay is longer than path degrading delay.
1270   static QuicTime::Delta CalculateNetworkBlackholeDelay(
1271       QuicTime::Delta blackhole_delay, QuicTime::Delta path_degrading_delay,
1272       QuicTime::Delta pto_delay);
1273 
DisableLivenessTesting()1274   void DisableLivenessTesting() { liveness_testing_disabled_ = true; }
1275 
1276   void AddKnownServerAddress(const QuicSocketAddress& address);
1277 
1278   absl::optional<QuicNewConnectionIdFrame>
1279   MaybeIssueNewConnectionIdForPreferredAddress();
1280 
1281   // Kicks off validation of received server preferred address.
1282   void ValidateServerPreferredAddress();
1283 
1284   // Returns true if the client is validating the server preferred address which
1285   // hasn't been used before.
1286   bool IsValidatingServerPreferredAddress() const;
1287 
1288   // Called by client to start sending packets to the preferred address.
1289   // If |owns_writer| is true, the ownership of the writer in the |context| is
1290   // also passed in.
1291   void OnServerPreferredAddressValidated(QuicPathValidationContext& context,
1292                                          bool owns_writer);
1293 
set_sent_server_preferred_address(const QuicSocketAddress & sent_server_preferred_address)1294   void set_sent_server_preferred_address(
1295       const QuicSocketAddress& sent_server_preferred_address) {
1296     sent_server_preferred_address_ = sent_server_preferred_address;
1297   }
1298 
sent_server_preferred_address()1299   const QuicSocketAddress& sent_server_preferred_address() const {
1300     return sent_server_preferred_address_;
1301   }
1302 
1303  protected:
1304   // Calls cancel() on all the alarms owned by this connection.
1305   void CancelAllAlarms();
1306 
1307   // Send a packet to the peer, and takes ownership of the packet if the packet
1308   // cannot be written immediately.
1309   virtual void SendOrQueuePacket(SerializedPacket packet);
1310 
1311   // Called after a packet is received from a new effective peer address and is
1312   // decrypted. Starts validation of effective peer's address change. Calls
1313   // OnConnectionMigration as soon as the address changed.
1314   void StartEffectivePeerMigration(AddressChangeType type);
1315 
1316   // Called when a effective peer address migration is validated.
1317   virtual void OnEffectivePeerMigrationValidated(bool is_migration_linkable);
1318 
1319   // Get the effective peer address from the packet being processed. For proxied
1320   // connections, effective peer address is the address of the endpoint behind
1321   // the proxy. For non-proxied connections, effective peer address is the same
1322   // as peer address.
1323   //
1324   // Notes for implementations in subclasses:
1325   // - If the connection is not proxied, the overridden method should use the
1326   //   base implementation:
1327   //
1328   //       return QuicConnection::GetEffectivePeerAddressFromCurrentPacket();
1329   //
1330   // - If the connection is proxied, the overridden method may return either of
1331   //   the following:
1332   //   a) The address of the endpoint behind the proxy. The address is used to
1333   //      drive effective peer migration.
1334   //   b) An uninitialized address, meaning the effective peer address does not
1335   //      change.
1336   virtual QuicSocketAddress GetEffectivePeerAddressFromCurrentPacket() const;
1337 
1338   // Selects and updates the version of the protocol being used by selecting a
1339   // version from |available_versions| which is also supported. Returns true if
1340   // such a version exists, false otherwise.
1341   bool SelectMutualVersion(const ParsedQuicVersionVector& available_versions);
1342 
1343   // Returns the current per-packet options for the connection.
per_packet_options()1344   PerPacketOptions* per_packet_options() { return per_packet_options_; }
1345 
active_effective_peer_migration_type()1346   AddressChangeType active_effective_peer_migration_type() const {
1347     return active_effective_peer_migration_type_;
1348   }
1349 
1350   // Sends a connection close packet to the peer and includes an ACK if the ACK
1351   // is not empty, the |error| is not PACKET_WRITE_ERROR, and it fits.
1352   // |ietf_error| may optionally be be used to directly specify the wire
1353   // error code. Otherwise if |ietf_error| is NO_IETF_QUIC_ERROR, the
1354   // QuicErrorCodeToTransportErrorCode mapping of |error| will be used.
1355   // Caller may choose to call SendConnectionClosePacket() directly instead of
1356   // CloseConnection() to notify peer that the connection is going to be closed,
1357   // for example, when the server is tearing down. Given
1358   // SendConnectionClosePacket() does not close connection, multiple connection
1359   // close packets could be sent to the peer.
1360   virtual void SendConnectionClosePacket(QuicErrorCode error,
1361                                          QuicIetfTransportErrorCodes ietf_error,
1362                                          const std::string& details);
1363 
1364   // Returns true if the packet should be discarded and not sent.
1365   virtual bool ShouldDiscardPacket(EncryptionLevel encryption_level);
1366 
1367   // Notify various components(Session etc.) that this connection has been
1368   // migrated.
1369   virtual void OnConnectionMigration();
1370 
1371   // Return whether the packet being processed is a connectivity probing.
1372   // A packet is a connectivity probing if it is a padded ping packet with self
1373   // and/or peer address changes.
1374   bool IsCurrentPacketConnectivityProbing() const;
1375 
1376   // Return true iff the writer is blocked, if blocked, call
1377   // visitor_->OnWriteBlocked() to add the connection into the write blocked
1378   // list.
1379   bool HandleWriteBlocked();
1380 
1381   // Whether connection enforces anti-amplification limit.
1382   bool EnforceAntiAmplificationLimit() const;
1383 
AddBytesReceivedBeforeAddressValidation(size_t length)1384   void AddBytesReceivedBeforeAddressValidation(size_t length) {
1385     default_path_.bytes_received_before_address_validation += length;
1386   }
1387 
set_validate_client_addresses(bool value)1388   void set_validate_client_addresses(bool value) {
1389     validate_client_addresses_ = value;
1390   }
1391 
defer_send_in_response_to_packets()1392   bool defer_send_in_response_to_packets() const {
1393     return defer_send_in_response_to_packets_;
1394   }
1395 
connection_id_generator()1396   ConnectionIdGeneratorInterface& connection_id_generator() const {
1397     return connection_id_generator_;
1398   }
1399 
count_reverse_path_validation_stats()1400   bool count_reverse_path_validation_stats() const {
1401     return count_reverse_path_validation_stats_;
1402   }
set_count_reverse_path_validation_stats(bool value)1403   void set_count_reverse_path_validation_stats(bool value) {
1404     count_reverse_path_validation_stats_ = value;
1405   }
1406 
1407  private:
1408   friend class test::QuicConnectionPeer;
1409 
1410   enum RetransmittableOnWireBehavior {
1411     DEFAULT,                           // Send packet containing a PING frame.
1412     SEND_FIRST_FORWARD_SECURE_PACKET,  // Send 1st 1-RTT packet.
1413     SEND_RANDOM_BYTES  // Send random bytes which is an unprocessable packet.
1414   };
1415 
1416   enum class MultiPortStatusOnMigration {
1417     kNotValidated,
1418     kPendingRefreshValidation,
1419     kWaitingForRefreshValidation,
1420     kMaxValue,
1421   };
1422 
1423   struct QUIC_EXPORT_PRIVATE PendingPathChallenge {
1424     QuicPathFrameBuffer received_path_challenge;
1425     QuicSocketAddress peer_address;
1426   };
1427 
1428   struct QUIC_EXPORT_PRIVATE PathState {
1429     PathState() = default;
1430 
PathStatePathState1431     PathState(const QuicSocketAddress& alternative_self_address,
1432               const QuicSocketAddress& alternative_peer_address,
1433               const QuicConnectionId& client_connection_id,
1434               const QuicConnectionId& server_connection_id,
1435               absl::optional<StatelessResetToken> stateless_reset_token)
1436         : self_address(alternative_self_address),
1437           peer_address(alternative_peer_address),
1438           client_connection_id(client_connection_id),
1439           server_connection_id(server_connection_id),
1440           stateless_reset_token(stateless_reset_token) {}
1441 
1442     PathState(PathState&& other);
1443 
1444     PathState& operator=(PathState&& other);
1445 
1446     // Reset all the members.
1447     void Clear();
1448 
1449     QuicSocketAddress self_address;
1450     // The actual peer address behind the proxy if there is any.
1451     QuicSocketAddress peer_address;
1452     QuicConnectionId client_connection_id;
1453     QuicConnectionId server_connection_id;
1454     absl::optional<StatelessResetToken> stateless_reset_token;
1455     // True if the peer address has been validated. Address is considered
1456     // validated when 1) an address token of the peer address is received and
1457     // validated, or 2) a HANDSHAKE packet has been successfully processed on
1458     // this path, or 3) a path validation on this path has succeeded.
1459     bool validated = false;
1460     // Used by the sever to apply anti-amplification limit after this path
1461     // becomes the default path if |peer_address| hasn't been validated.
1462     QuicByteCount bytes_received_before_address_validation = 0;
1463     QuicByteCount bytes_sent_before_address_validation = 0;
1464     // Points to the send algorithm on the old default path while connection is
1465     // validating migrated peer address. Nullptr otherwise.
1466     std::unique_ptr<SendAlgorithmInterface> send_algorithm;
1467     absl::optional<RttStats> rtt_stats;
1468   };
1469 
1470   using QueuedPacketList = std::list<SerializedPacket>;
1471 
1472   // BufferedPacket stores necessary information (encrypted buffer and self/peer
1473   // addresses) of those packets which are serialized but failed to send because
1474   // socket is blocked. From unacked packet map and send algorithm's
1475   // perspective, buffered packets are treated as sent.
1476   struct QUIC_EXPORT_PRIVATE BufferedPacket {
1477     BufferedPacket(const SerializedPacket& packet,
1478                    const QuicSocketAddress& self_address,
1479                    const QuicSocketAddress& peer_address);
1480     BufferedPacket(const char* encrypted_buffer,
1481                    QuicPacketLength encrypted_length,
1482                    const QuicSocketAddress& self_address,
1483                    const QuicSocketAddress& peer_address);
1484     // Please note, this buffered packet contains random bytes (and is not
1485     // *actually* a QUIC packet).
1486     BufferedPacket(QuicRandom& random, QuicPacketLength encrypted_length,
1487                    const QuicSocketAddress& self_address,
1488                    const QuicSocketAddress& peer_address);
1489     BufferedPacket(const BufferedPacket& other) = delete;
1490     BufferedPacket(const BufferedPacket&& other) = delete;
1491 
1492     ~BufferedPacket() = default;
1493 
1494     std::unique_ptr<char[]> data;
1495     const QuicPacketLength length;
1496     // Self and peer addresses when the packet is serialized.
1497     const QuicSocketAddress self_address;
1498     const QuicSocketAddress peer_address;
1499   };
1500 
1501   // ReceivedPacketInfo comprises the received packet information.
1502   // TODO(fayang): move more fields to ReceivedPacketInfo.
1503   struct QUIC_EXPORT_PRIVATE ReceivedPacketInfo {
1504     explicit ReceivedPacketInfo(QuicTime receipt_time);
1505     ReceivedPacketInfo(const QuicSocketAddress& destination_address,
1506                        const QuicSocketAddress& source_address,
1507                        QuicTime receipt_time, QuicByteCount length,
1508                        QuicEcnCodepoint ecn_codepoint);
1509 
1510     QuicSocketAddress destination_address;
1511     QuicSocketAddress source_address;
1512     QuicTime receipt_time = QuicTime::Zero();
1513     bool received_bytes_counted = false;
1514     QuicByteCount length = 0;
1515     QuicConnectionId destination_connection_id;
1516     // Fields below are only populated if packet gets decrypted successfully.
1517     // TODO(fayang): consider using absl::optional for following fields.
1518     bool decrypted = false;
1519     EncryptionLevel decrypted_level = ENCRYPTION_INITIAL;
1520     QuicPacketHeader header;
1521     absl::InlinedVector<QuicFrameType, 1> frames;
1522     QuicEcnCodepoint ecn_codepoint = ECN_NOT_ECT;
1523     // Stores the actual address this packet is received on when it is received
1524     // on the preferred address. In this case, |destination_address| will
1525     // be overridden to the current default self address.
1526     QuicSocketAddress actual_destination_address;
1527   };
1528 
1529   QUIC_EXPORT_PRIVATE friend std::ostream& operator<<(
1530       std::ostream& os, const QuicConnection::ReceivedPacketInfo& info);
1531 
1532   // UndecrytablePacket comprises a undecryptable packet and related
1533   // information.
1534   struct QUIC_EXPORT_PRIVATE UndecryptablePacket {
UndecryptablePacketUndecryptablePacket1535     UndecryptablePacket(const QuicEncryptedPacket& packet,
1536                         EncryptionLevel encryption_level,
1537                         const ReceivedPacketInfo& packet_info)
1538         : packet(packet.Clone()),
1539           encryption_level(encryption_level),
1540           packet_info(packet_info) {}
1541 
1542     std::unique_ptr<QuicEncryptedPacket> packet;
1543     EncryptionLevel encryption_level;
1544     ReceivedPacketInfo packet_info;
1545   };
1546 
1547   // Handles the reverse path validation result depending on connection state:
1548   // whether the connection is validating a migrated peer address or is
1549   // validating an alternative path.
1550   class ReversePathValidationResultDelegate
1551       : public QuicPathValidator::ResultDelegate {
1552    public:
1553     ReversePathValidationResultDelegate(
1554         QuicConnection* connection,
1555         const QuicSocketAddress& direct_peer_address);
1556 
1557     void OnPathValidationSuccess(
1558         std::unique_ptr<QuicPathValidationContext> context,
1559         QuicTime start_time) override;
1560 
1561     void OnPathValidationFailure(
1562         std::unique_ptr<QuicPathValidationContext> context) override;
1563 
1564    private:
1565     QuicConnection* connection_;
1566     QuicSocketAddress original_direct_peer_address_;
1567     // TODO(b/205023946) Debug-only fields, to be deprecated after the bug is
1568     // fixed.
1569     QuicSocketAddress peer_address_default_path_;
1570     QuicSocketAddress peer_address_alternative_path_;
1571     AddressChangeType active_effective_peer_migration_type_;
1572   };
1573 
1574   // Keeps an ongoing alternative path. The connection will not migrate upon
1575   // validation success.
1576   class MultiPortPathValidationResultDelegate
1577       : public QuicPathValidator::ResultDelegate {
1578    public:
1579     MultiPortPathValidationResultDelegate(QuicConnection* connection);
1580 
1581     void OnPathValidationSuccess(
1582         std::unique_ptr<QuicPathValidationContext> context,
1583         QuicTime start_time) override;
1584 
1585     void OnPathValidationFailure(
1586         std::unique_ptr<QuicPathValidationContext> context) override;
1587 
1588    private:
1589     QuicConnection* connection_;
1590   };
1591 
1592   // A class which sets and clears in_probe_time_out_ when entering
1593   // and exiting OnRetransmissionTimeout, respectively.
1594   class QUIC_EXPORT_PRIVATE ScopedRetransmissionTimeoutIndicator {
1595    public:
1596     // |connection| must outlive this indicator.
1597     explicit ScopedRetransmissionTimeoutIndicator(QuicConnection* connection);
1598 
1599     ~ScopedRetransmissionTimeoutIndicator();
1600 
1601    private:
1602     QuicConnection* connection_;  // Not owned.
1603   };
1604 
1605   // If peer uses non-empty connection ID, discards any buffered packets on path
1606   // change in IETF QUIC.
1607   void MaybeClearQueuedPacketsOnPathChange();
1608 
1609   // Notifies the visitor of the close and marks the connection as disconnected.
1610   // Does not send a connection close frame to the peer. It should only be
1611   // called by CloseConnection or OnConnectionCloseFrame, OnPublicResetPacket,
1612   // and OnAuthenticatedIetfStatelessResetPacket.
1613   // |ietf_error| may optionally be be used to directly specify the wire
1614   // error code. Otherwise if |ietf_error| is NO_IETF_QUIC_ERROR, the
1615   // QuicErrorCodeToTransportErrorCode mapping of |error| will be used.
1616   void TearDownLocalConnectionState(QuicErrorCode error,
1617                                     QuicIetfTransportErrorCodes ietf_error,
1618                                     const std::string& details,
1619                                     ConnectionCloseSource source);
1620   void TearDownLocalConnectionState(const QuicConnectionCloseFrame& frame,
1621                                     ConnectionCloseSource source);
1622 
1623   // Replace server connection ID on the client side from retry packet or
1624   // initial packets with a different source connection ID.
1625   void ReplaceInitialServerConnectionId(
1626       const QuicConnectionId& new_server_connection_id);
1627 
1628   // Given the server_connection_id find if there is already a corresponding
1629   // client connection ID used on default/alternative path. If not, find if
1630   // there is an unused connection ID.
1631   void FindMatchingOrNewClientConnectionIdOrToken(
1632       const PathState& default_path, const PathState& alternative_path,
1633       const QuicConnectionId& server_connection_id,
1634       QuicConnectionId* client_connection_id,
1635       absl::optional<StatelessResetToken>* stateless_reset_token);
1636 
1637   // Returns true and sets connection IDs if (self_address, peer_address)
1638   // corresponds to either the default path or alternative path. Returns false
1639   // otherwise.
1640   bool FindOnPathConnectionIds(const QuicSocketAddress& self_address,
1641                                const QuicSocketAddress& peer_address,
1642                                QuicConnectionId* client_connection_id,
1643                                QuicConnectionId* server_connection_id) const;
1644 
1645   // Set default_path_ to the new_path_state and update the connection IDs in
1646   // packet creator accordingly.
1647   void SetDefaultPathState(PathState new_path_state);
1648 
1649   // Returns true if header contains valid server connection ID.
1650   bool ValidateServerConnectionId(const QuicPacketHeader& header) const;
1651 
1652   // Update the connection IDs when client migrates its own address
1653   // (with/without validation) or switches to server preferred address.
1654   // Returns false if required connection ID is not available.
1655   bool UpdateConnectionIdsOnMigration(const QuicSocketAddress& self_address,
1656                                       const QuicSocketAddress& peer_address);
1657 
1658   // Retire active peer issued connection IDs after they are no longer used on
1659   // any path.
1660   void RetirePeerIssuedConnectionIdsNoLongerOnPath();
1661 
1662   // When path validation fails, proactively retire peer issued connection IDs
1663   // no longer used on any path.
1664   void RetirePeerIssuedConnectionIdsOnPathValidationFailure();
1665 
1666   // Writes the given packet to socket, encrypted with packet's
1667   // encryption_level. Returns true on successful write, and false if the writer
1668   // was blocked and the write needs to be tried again. Notifies the
1669   // SentPacketManager when the write is successful and sets
1670   // retransmittable frames to nullptr.
1671   // Saves the connection close packet for later transmission, even if the
1672   // writer is write blocked.
1673   bool WritePacket(SerializedPacket* packet);
1674 
1675   // Enforce AEAD Confidentiality limits by iniating key update or closing
1676   // connection if too many packets have been encrypted with the current key.
1677   // Returns true if the connection was closed. Should not be called for
1678   // termination packets.
1679   bool MaybeHandleAeadConfidentialityLimits(const SerializedPacket& packet);
1680 
1681   // Flush packets buffered in the writer, if any.
1682   void FlushPackets();
1683 
1684   // Make sure a stop waiting we got from our peer is sane.
1685   // Returns nullptr if the frame is valid or an error string if it was invalid.
1686   const char* ValidateStopWaitingFrame(
1687       const QuicStopWaitingFrame& stop_waiting);
1688 
1689   // Clears any accumulated frames from the last received packet.
1690   void ClearLastFrames();
1691 
1692   // Deletes and clears any queued packets.
1693   void ClearQueuedPackets();
1694 
1695   // Closes the connection if the sent packet manager is tracking too many
1696   // outstanding packets.
1697   void CloseIfTooManyOutstandingSentPackets();
1698 
1699   // Writes as many queued packets as possible.  The connection must not be
1700   // blocked when this is called.
1701   void WriteQueuedPackets();
1702 
1703   // Queues |packet| in the hopes that it can be decrypted in the
1704   // future, when a new key is installed.
1705   void QueueUndecryptablePacket(const QuicEncryptedPacket& packet,
1706                                 EncryptionLevel decryption_level);
1707 
1708   // Sends any packets which are a response to the last packet, including both
1709   // acks and pending writes if an ack opened the congestion window.
1710   void MaybeSendInResponseToPacket();
1711 
1712   // Gets the least unacked packet number, which is the next packet number to be
1713   // sent if there are no outstanding packets.
1714   QuicPacketNumber GetLeastUnacked() const;
1715 
1716   // Sets the ping alarm to the appropriate value, if any.
1717   void SetPingAlarm();
1718 
1719   // Sets the retransmission alarm based on SentPacketManager.
1720   void SetRetransmissionAlarm();
1721 
1722   // Sets the MTU discovery alarm if necessary.
1723   // |sent_packet_number| is the recently sent packet number.
1724   void MaybeSetMtuAlarm(QuicPacketNumber sent_packet_number);
1725 
1726   HasRetransmittableData IsRetransmittable(const SerializedPacket& packet);
1727   bool IsTerminationPacket(const SerializedPacket& packet,
1728                            QuicErrorCode* error_code);
1729 
1730   // Set the size of the packet we are targeting while doing path MTU discovery.
1731   void SetMtuDiscoveryTarget(QuicByteCount target);
1732 
1733   // Returns |suggested_max_packet_size| clamped to any limits set by the
1734   // underlying writer, connection, or protocol.
1735   QuicByteCount GetLimitedMaxPacketSize(
1736       QuicByteCount suggested_max_packet_size);
1737 
1738   // Do any work which logically would be done in OnPacket but can not be
1739   // safely done until the packet is validated. Returns true if packet can be
1740   // handled, false otherwise.
1741   bool ProcessValidatedPacket(const QuicPacketHeader& header);
1742 
1743   // Returns true if received |packet_number| can be processed. Please note,
1744   // this is called after packet got decrypted successfully.
1745   bool ValidateReceivedPacketNumber(QuicPacketNumber packet_number);
1746 
1747   // Consider receiving crypto frame on non crypto stream as memory corruption.
1748   bool MaybeConsiderAsMemoryCorruption(const QuicStreamFrame& frame);
1749 
1750   // Check if the connection has no outstanding data to send and notify
1751   // congestion controller if it is the case.
1752   void CheckIfApplicationLimited();
1753 
1754   // Sets |current_packet_content_| to |type| if applicable. And
1755   // starts effective peer migration if current packet is confirmed not a
1756   // connectivity probe and |current_effective_peer_migration_type_| indicates
1757   // effective peer address change.
1758   // Returns true if connection is still alive.
1759   ABSL_MUST_USE_RESULT bool UpdatePacketContent(QuicFrameType type);
1760 
1761   // Called when last received ack frame has been processed.
1762   // |send_stop_waiting| indicates whether a stop waiting needs to be sent.
1763   // |acked_new_packet| is true if a previously-unacked packet was acked.
1764   void PostProcessAfterAckFrame(bool send_stop_waiting, bool acked_new_packet);
1765 
1766   // Updates the release time into the future.
1767   void UpdateReleaseTimeIntoFuture();
1768 
1769   // Sends generic path probe packet to the peer. If we are not IETF QUIC, will
1770   // always send a padded ping, regardless of whether this is a request or not.
1771   bool SendGenericPathProbePacket(QuicPacketWriter* probing_writer,
1772                                   const QuicSocketAddress& peer_address);
1773 
1774   // Called when an ACK is about to send. Resets ACK related internal states,
1775   // e.g., cancels ack_alarm_, resets
1776   // num_retransmittable_packets_received_since_last_ack_sent_ etc.
1777   void ResetAckStates();
1778 
1779   // Returns true if the ACK frame should be bundled with ACK-eliciting frame.
1780   bool ShouldBundleRetransmittableFrameWithAck() const;
1781 
1782   void PopulateStopWaitingFrame(QuicStopWaitingFrame* stop_waiting);
1783 
1784   // Enables multiple packet number spaces support based on handshake protocol
1785   // and flags.
1786   void MaybeEnableMultiplePacketNumberSpacesSupport();
1787 
1788   // Called to update ACK timeout when an retransmittable frame has been parsed.
1789   void MaybeUpdateAckTimeout();
1790 
1791   // Tries to fill coalesced packet with data of higher packet space.
1792   void MaybeCoalescePacketOfHigherSpace();
1793 
1794   // Serialize and send coalesced_packet. Returns false if serialization fails
1795   // or the write causes errors, otherwise, returns true.
1796   bool FlushCoalescedPacket();
1797 
1798   // Returns the encryption level the connection close packet should be sent at,
1799   // which is the highest encryption level that peer can guarantee to process.
1800   EncryptionLevel GetConnectionCloseEncryptionLevel() const;
1801 
1802   // Called after an ACK frame is successfully processed to update largest
1803   // received packet number which contains an ACK frame.
1804   void SetLargestReceivedPacketWithAck(QuicPacketNumber new_value);
1805 
1806   // Called when new packets have been acknowledged or old keys have been
1807   // discarded.
1808   void OnForwardProgressMade();
1809 
1810   // Returns largest received packet number which contains an ACK frame.
1811   QuicPacketNumber GetLargestReceivedPacketWithAck() const;
1812 
1813   // Returns the largest packet number that has been sent.
1814   QuicPacketNumber GetLargestSentPacket() const;
1815 
1816   // Returns the largest sent packet number that has been ACKed by peer.
1817   QuicPacketNumber GetLargestAckedPacket() const;
1818 
1819   // Whether connection is limited by amplification factor.
1820   // If enforce_strict_amplification_factor_ is true, this will return true if
1821   // connection is amplification limited after sending |bytes|.
1822   bool LimitedByAmplificationFactor(QuicByteCount bytes) const;
1823 
1824   // Called before sending a packet to get packet send time and to set the
1825   // release time delay in |per_packet_options_|. Return the time when the
1826   // packet is scheduled to be released(a.k.a send time), which is NOW + delay.
1827   // Returns Now() and does not update release time delay if
1828   // |supports_release_time_| is false.
1829   QuicTime CalculatePacketSentTime();
1830 
1831   // If we have a previously validate MTU value, e.g. due to a write error,
1832   // revert to it and disable MTU discovery.
1833   // Return true iff we reverted to a previously validate MTU.
1834   bool MaybeRevertToPreviousMtu();
1835 
1836   QuicTime GetPathMtuReductionDeadline() const;
1837 
1838   // Returns path degrading deadline. QuicTime::Zero() means no path degrading
1839   // detection is needed.
1840   QuicTime GetPathDegradingDeadline() const;
1841 
1842   // Returns true if path degrading should be detected.
1843   bool ShouldDetectPathDegrading() const;
1844 
1845   // Returns network blackhole deadline. QuicTime::Zero() means no blackhole
1846   // detection is needed.
1847   QuicTime GetNetworkBlackholeDeadline() const;
1848 
1849   // Returns true if network blackhole should be detected.
1850   bool ShouldDetectBlackhole() const;
1851 
1852   // Returns retransmission deadline.
1853   QuicTime GetRetransmissionDeadline() const;
1854 
1855   // Validate connection IDs used during the handshake. Closes the connection
1856   // on validation failure.
1857   bool ValidateConfigConnectionIds(const QuicConfig& config);
1858 
1859   // Called when ACK alarm goes off. Try to bundle crypto data with ACKs.
1860   void MaybeBundleCryptoDataWithAcks();
1861 
1862   // Returns true if an undecryptable packet of |decryption_level| should be
1863   // buffered (such that connection can try to decrypt it later).
1864   bool ShouldEnqueueUnDecryptablePacket(EncryptionLevel decryption_level,
1865                                         bool has_decryption_key) const;
1866 
1867   // Returns string which contains undecryptable packets information.
1868   std::string UndecryptablePacketsInfo() const;
1869 
1870   // For Google Quic, if the current packet is connectivity probing packet, call
1871   // session OnPacketReceived() which eventually sends connectivity probing
1872   // response on server side. And no-op on client side. And for both Google Quic
1873   // and IETF Quic, start migration if the current packet is a non-probing
1874   // packet.
1875   // TODO(danzh) rename to MaybeRespondToPeerMigration() when Google Quic is
1876   // deprecated.
1877   void MaybeRespondToConnectivityProbingOrMigration();
1878 
1879   // Called in IETF QUIC. Start peer migration if a non-probing frame is
1880   // received and the current packet number is largest received so far.
1881   void MaybeStartIetfPeerMigration();
1882 
1883   // Send PATH_RESPONSE to the given peer address.
1884   bool SendPathResponse(const QuicPathFrameBuffer& data_buffer,
1885                         const QuicSocketAddress& peer_address_to_send,
1886                         const QuicSocketAddress& effective_peer_address);
1887 
1888   // Update both connection's and packet creator's peer address.
1889   void UpdatePeerAddress(QuicSocketAddress peer_address);
1890 
1891   // Send PING at encryption level.
1892   void SendPingAtLevel(EncryptionLevel level);
1893 
1894   // Write the given packet with |self_address| and |peer_address| using
1895   // |writer|.
1896   bool WritePacketUsingWriter(std::unique_ptr<SerializedPacket> packet,
1897                               QuicPacketWriter* writer,
1898                               const QuicSocketAddress& self_address,
1899                               const QuicSocketAddress& peer_address,
1900                               bool measure_rtt);
1901 
1902   // Increment bytes sent/received on the alternative path if the current packet
1903   // is sent/received on that path.
1904   void MaybeUpdateBytesSentToAlternativeAddress(
1905       const QuicSocketAddress& peer_address, QuicByteCount sent_packet_size);
1906   void MaybeUpdateBytesReceivedFromAlternativeAddress(
1907       QuicByteCount received_packet_size);
1908 
1909   // TODO(danzh) pass in PathState of the incoming packet or the packet sent
1910   // once PathState is used in packet creator. Return true if the given self
1911   // address and peer address is the same as the self address and peer address
1912   // of the default path.
1913   bool IsDefaultPath(const QuicSocketAddress& self_address,
1914                      const QuicSocketAddress& peer_address) const;
1915 
1916   // Return true if the |self_address| and |peer_address| is the same as the
1917   // self address and peer address of the alternative path.
1918   bool IsAlternativePath(const QuicSocketAddress& self_address,
1919                          const QuicSocketAddress& peer_address) const;
1920 
1921   // Restore connection default path and congestion control state to the last
1922   // validated path and its state. Called after fail to validate peer address
1923   // upon detecting a peer migration.
1924   void RestoreToLastValidatedPath(
1925       QuicSocketAddress original_direct_peer_address);
1926 
1927   // Return true if the current incoming packet is from a peer address that is
1928   // validated.
1929   bool IsReceivedPeerAddressValidated() const;
1930 
1931   // Called after receiving PATH_CHALLENGE. Update packet content and
1932   // alternative path state if the current packet is from a non-default path.
1933   // Return true if framer should continue processing the packet.
1934   bool OnPathChallengeFrameInternal(const QuicPathChallengeFrame& frame);
1935 
1936   // Check the state of the multi-port alternative path and initiate path
1937   // migration.
1938   void MaybeMigrateToMultiPortPath();
1939 
1940   std::unique_ptr<QuicSelfIssuedConnectionIdManager>
1941   MakeSelfIssuedConnectionIdManager();
1942 
1943   // Called on peer IP change or restoring to previous address to reset
1944   // congestion window, RTT stats, retransmission timer, etc. Only used in IETF
1945   // QUIC.
1946   std::unique_ptr<SendAlgorithmInterface> OnPeerIpAddressChanged();
1947 
1948   // Process NewConnectionIdFrame either sent from peer or synsthesized from
1949   // preferred_address transport parameter.
1950   bool OnNewConnectionIdFrameInner(const QuicNewConnectionIdFrame& frame);
1951 
1952   // Called to patch missing client connection ID on default/alternative paths
1953   // when a new client connection ID is received.
1954   void OnClientConnectionIdAvailable();
1955 
1956   // Determines encryption level to send ping in `packet_number_space`.
1957   EncryptionLevel GetEncryptionLevelToSendPingForSpace(
1958       PacketNumberSpace space) const;
1959 
1960   // Returns true if |address| is known server address.
1961   bool IsKnownServerAddress(const QuicSocketAddress& address) const;
1962 
1963   // Retrieves the ECN codepoint to be sent on the next packet.
GetNextEcnCodepoint()1964   QuicEcnCodepoint GetNextEcnCodepoint() const {
1965     return (per_packet_options_ != nullptr) ? per_packet_options_->ecn_codepoint
1966                                             : ECN_NOT_ECT;
1967   }
1968 
1969   // Sets the ECN codepoint to Not-ECT.
1970   void ClearEcnCodepoint();
1971 
1972   // Writes the packet to the writer and clears the ECN codepoint in |options|
1973   // if it is invalid.
1974   WriteResult SendPacketToWriter(const char* buffer, size_t buf_len,
1975                                  const QuicIpAddress& self_address,
1976                                  const QuicSocketAddress& peer_address,
1977                                  PerPacketOptions* options);
1978 
1979   QuicConnectionContext context_;
1980 
1981   QuicFramer framer_;
1982 
1983   // Contents received in the current packet, especially used to identify
1984   // whether the current packet is a padded PING packet.
1985   PacketContent current_packet_content_;
1986   // Set to true as soon as the packet currently being processed has been
1987   // detected as a connectivity probing.
1988   // Always false outside the context of ProcessUdpPacket().
1989   bool is_current_packet_connectivity_probing_;
1990 
1991   bool has_path_challenge_in_current_packet_;
1992 
1993   // Caches the current effective peer migration type if a effective peer
1994   // migration might be initiated. As soon as the current packet is confirmed
1995   // not a connectivity probe, effective peer migration will start.
1996   AddressChangeType current_effective_peer_migration_type_;
1997   QuicConnectionHelperInterface* helper_;  // Not owned.
1998   QuicAlarmFactory* alarm_factory_;        // Not owned.
1999   PerPacketOptions* per_packet_options_;   // Not owned.
2000   QuicPacketWriter* writer_;  // Owned or not depending on |owns_writer_|.
2001   bool owns_writer_;
2002   // Encryption level for new packets. Should only be changed via
2003   // SetDefaultEncryptionLevel().
2004   EncryptionLevel encryption_level_;
2005   const QuicClock* clock_;
2006   QuicRandom* random_generator_;
2007 
2008   // On the server, the connection ID is set when receiving the first packet.
2009   // This variable ensures we only set it this way once.
2010   bool client_connection_id_is_set_;
2011 
2012   // Whether we've already replaced our server connection ID due to receiving an
2013   // INITIAL packet with a different source connection ID. Only used on client.
2014   bool server_connection_id_replaced_by_initial_ = false;
2015   // Address on the last successfully processed packet received from the
2016   // direct peer.
2017 
2018   // Other than initialization, do not modify it directly, use
2019   // UpdatePeerAddress() instead.
2020   QuicSocketAddress direct_peer_address_;
2021   // The default path on which the endpoint sends non-probing packets.
2022   // The send algorithm and RTT stats of this path are stored in
2023   // |sent_packet_manager_| instead of in this object.
2024   PathState default_path_;
2025 
2026   // Records change type when the effective peer initiates migration to a new
2027   // address. Reset to NO_CHANGE after effective peer migration is validated.
2028   AddressChangeType active_effective_peer_migration_type_;
2029 
2030   // Records highest sent packet number when effective peer migration is
2031   // started.
2032   QuicPacketNumber highest_packet_sent_before_effective_peer_migration_;
2033 
2034   // True if Key Update is supported on this connection.
2035   bool support_key_update_for_connection_;
2036 
2037   // Tracks the lowest packet sent in the current key phase. Will be
2038   // uninitialized before the first one-RTT packet has been sent or after a
2039   // key update but before the first packet has been sent.
2040   QuicPacketNumber lowest_packet_sent_in_current_key_phase_;
2041 
2042   // TODO(rch): remove this when b/27221014 is fixed.
2043   const char* current_packet_data_;  // UDP payload of packet currently being
2044                                      // parsed or nullptr.
2045   bool should_last_packet_instigate_acks_;
2046 
2047   // Track some peer state so we can do less bookkeeping
2048   // Largest sequence sent by the peer which had an ack frame (latest ack info).
2049   // Do not read or write directly, use GetLargestReceivedPacketWithAck() and
2050   // SetLargestReceivedPacketWithAck() instead.
2051   QuicPacketNumber largest_seen_packet_with_ack_;
2052   // Largest packet number sent by the peer which had an ACK frame per packet
2053   // number space. Only used when this connection supports multiple packet
2054   // number spaces.
2055   QuicPacketNumber largest_seen_packets_with_ack_[NUM_PACKET_NUMBER_SPACES];
2056 
2057   // Largest packet number sent by the peer which had a stop waiting frame.
2058   QuicPacketNumber largest_seen_packet_with_stop_waiting_;
2059 
2060   // Collection of packets which were received before encryption was
2061   // established, but which could not be decrypted.  We buffer these on
2062   // the assumption that they could not be processed because they were
2063   // sent with the INITIAL encryption and the CHLO message was lost.
2064   std::deque<UndecryptablePacket> undecryptable_packets_;
2065 
2066   // Collection of coalesced packets which were received while processing
2067   // the current packet.
2068   quiche::QuicheCircularDeque<std::unique_ptr<QuicEncryptedPacket>>
2069       received_coalesced_packets_;
2070 
2071   // Maximum number of undecryptable packets the connection will store.
2072   size_t max_undecryptable_packets_;
2073 
2074   // Maximum number of tracked packets.
2075   QuicPacketCount max_tracked_packets_;
2076 
2077   // Contains the connection close packets if the connection has been closed.
2078   std::unique_ptr<std::vector<std::unique_ptr<QuicEncryptedPacket>>>
2079       termination_packets_;
2080 
2081   // Determines whether or not a connection close packet is sent to the peer
2082   // after idle timeout due to lack of network activity. During the handshake,
2083   // a connection close packet is sent, but not after.
2084   ConnectionCloseBehavior idle_timeout_connection_close_behavior_;
2085 
2086   // When > 0, close the QUIC connection after this number of RTOs.
2087   size_t num_rtos_for_blackhole_detection_;
2088 
2089   // Statistics for this session.
2090   QuicConnectionStats stats_;
2091 
2092   UberReceivedPacketManager uber_received_packet_manager_;
2093 
2094   // Indicates how many consecutive times an ack has arrived which indicates
2095   // the peer needs to stop waiting for some packets.
2096   // TODO(fayang): remove this when deprecating Q043.
2097   int stop_waiting_count_;
2098 
2099   // Indicates the retransmission alarm needs to be set.
2100   bool pending_retransmission_alarm_;
2101 
2102   // If true, defer sending data in response to received packets to the
2103   // SendAlarm.
2104   bool defer_send_in_response_to_packets_;
2105 
2106   // Arena to store class implementations within the QuicConnection.
2107   QuicConnectionArena arena_;
2108 
2109   // An alarm that fires when an ACK should be sent to the peer.
2110   QuicArenaScopedPtr<QuicAlarm> ack_alarm_;
2111   // An alarm that fires when a packet needs to be retransmitted.
2112   QuicArenaScopedPtr<QuicAlarm> retransmission_alarm_;
2113   // An alarm that is scheduled when the SentPacketManager requires a delay
2114   // before sending packets and fires when the packet may be sent.
2115   QuicArenaScopedPtr<QuicAlarm> send_alarm_;
2116   // An alarm that fires when an MTU probe should be sent.
2117   QuicArenaScopedPtr<QuicAlarm> mtu_discovery_alarm_;
2118   // An alarm that fires to process undecryptable packets when new decyrption
2119   // keys are available.
2120   QuicArenaScopedPtr<QuicAlarm> process_undecryptable_packets_alarm_;
2121   // An alarm that fires to discard keys for the previous key phase some time
2122   // after a key update has completed.
2123   QuicArenaScopedPtr<QuicAlarm> discard_previous_one_rtt_keys_alarm_;
2124   // An alarm that fires to discard 0-RTT decryption keys some time after the
2125   // first 1-RTT packet has been decrypted. Only used on server connections with
2126   // TLS handshaker.
2127   QuicArenaScopedPtr<QuicAlarm> discard_zero_rtt_decryption_keys_alarm_;
2128   // An alarm that fires to keep probing the multi-port path.
2129   QuicArenaScopedPtr<QuicAlarm> multi_port_probing_alarm_;
2130   // Neither visitor is owned by this class.
2131   QuicConnectionVisitorInterface* visitor_;
2132   QuicConnectionDebugVisitor* debug_visitor_;
2133 
2134   QuicPacketCreator packet_creator_;
2135 
2136   // Information about the last received QUIC packet, which may not have been
2137   // successfully decrypted and processed.
2138   ReceivedPacketInfo last_received_packet_info_;
2139 
2140   // Sent packet manager which tracks the status of packets sent by this
2141   // connection and contains the send and receive algorithms to determine when
2142   // to send packets.
2143   QuicSentPacketManager sent_packet_manager_;
2144 
2145   // Indicates whether connection version has been negotiated.
2146   // Always true for server connections.
2147   bool version_negotiated_;
2148 
2149   // Tracks if the connection was created by the server or the client.
2150   Perspective perspective_;
2151 
2152   // True by default.  False if we've received or sent an explicit connection
2153   // close.
2154   bool connected_;
2155 
2156   // Set to false if the connection should not send truncated connection IDs to
2157   // the peer, even if the peer supports it.
2158   bool can_truncate_connection_ids_;
2159 
2160   // If non-empty this contains the set of versions received in a
2161   // version negotiation packet.
2162   ParsedQuicVersionVector server_supported_versions_;
2163 
2164   // The number of MTU probes already sent.
2165   size_t mtu_probe_count_;
2166 
2167   // The value of |long_term_mtu_| prior to the last successful MTU increase.
2168   // 0 means either
2169   // - MTU discovery has never been enabled, or
2170   // - MTU discovery has been enabled, but the connection got a packet write
2171   //   error with a new (successfully probed) MTU, so it reverted
2172   //   |long_term_mtu_| to the value before the last increase.
2173   QuicPacketLength previous_validated_mtu_;
2174   // The value of the MTU regularly used by the connection. This is different
2175   // from the value returned by max_packet_size(), as max_packet_size() returns
2176   // the value of the MTU as currently used by the serializer, so if
2177   // serialization of an MTU probe is in progress, those two values will be
2178   // different.
2179   QuicByteCount long_term_mtu_;
2180 
2181   // The maximum UDP payload size that our peer has advertised support for.
2182   // Defaults to kDefaultMaxPacketSizeTransportParam until received from peer.
2183   QuicByteCount peer_max_packet_size_;
2184 
2185   // The size of the largest packet received from peer.
2186   QuicByteCount largest_received_packet_size_;
2187 
2188   // Indicates whether a write error is encountered currently. This is used to
2189   // avoid infinite write errors.
2190   bool write_error_occurred_;
2191 
2192   // Indicates not to send or process stop waiting frames.
2193   bool no_stop_waiting_frames_;
2194 
2195   // Consecutive number of sent packets which have no retransmittable frames.
2196   size_t consecutive_num_packets_with_no_retransmittable_frames_;
2197 
2198   // After this many packets sent without retransmittable frames, an artificial
2199   // retransmittable frame(a WINDOW_UPDATE) will be created to solicit an ack
2200   // from the peer. Default to kMaxConsecutiveNonRetransmittablePackets.
2201   size_t max_consecutive_num_packets_with_no_retransmittable_frames_;
2202 
2203   // If true, bundle an ack-eliciting frame with an ACK if the PTO alarm have
2204   // previously fired.
2205   bool bundle_retransmittable_with_pto_ack_;
2206 
2207   // Id of latest sent control frame. 0 if no control frame has been sent.
2208   QuicControlFrameId last_control_frame_id_;
2209 
2210   // True if the peer is unreachable on the current path.
2211   bool is_path_degrading_;
2212 
2213   // True if an ack frame is being processed.
2214   bool processing_ack_frame_;
2215 
2216   // True if the writer supports release timestamp.
2217   bool supports_release_time_;
2218 
2219   std::unique_ptr<QuicPeerIssuedConnectionIdManager> peer_issued_cid_manager_;
2220   std::unique_ptr<QuicSelfIssuedConnectionIdManager> self_issued_cid_manager_;
2221 
2222   // Time this connection can release packets into the future.
2223   QuicTime::Delta release_time_into_future_;
2224 
2225   // Payloads that were received in the most recent probe. This needs to be a
2226   // Deque because the peer might no be using this implementation, and others
2227   // might send a packet with more than one PATH_CHALLENGE, so all need to be
2228   // saved and responded to.
2229   // TODO(danzh) deprecate this field when deprecating
2230   // --quic_send_path_response.
2231   quiche::QuicheCircularDeque<QuicPathFrameBuffer>
2232       received_path_challenge_payloads_;
2233 
2234   // When we receive a RETRY packet or some INITIAL packets, we replace
2235   // |server_connection_id_| with the value from that packet and save off the
2236   // original value of |server_connection_id_| into
2237   // |original_destination_connection_id_| for validation.
2238   absl::optional<QuicConnectionId> original_destination_connection_id_;
2239 
2240   // The connection ID that replaces original_destination_connection_id_.
2241   QuicConnectionId original_destination_connection_id_replacement_;
2242 
2243   // After we receive a RETRY packet, |retry_source_connection_id_| contains
2244   // the source connection ID from that packet.
2245   absl::optional<QuicConnectionId> retry_source_connection_id_;
2246 
2247   // Used to store content of packets which cannot be sent because of write
2248   // blocked. Packets' encrypted buffers are copied and owned by
2249   // buffered_packets_. From unacked_packet_map (and congestion control)'s
2250   // perspective, those packets are considered sent.
2251   std::list<BufferedPacket> buffered_packets_;
2252 
2253   // Used to coalesce packets of different encryption level into the same UDP
2254   // datagram. Connection stops trying to coalesce packets if a forward secure
2255   // packet gets acknowledged.
2256   QuicCoalescedPacket coalesced_packet_;
2257 
2258   QuicConnectionMtuDiscoverer mtu_discoverer_;
2259 
2260   QuicNetworkBlackholeDetector blackhole_detector_;
2261 
2262   QuicIdleNetworkDetector idle_network_detector_;
2263 
2264   bool blackhole_detection_disabled_ = false;
2265 
2266   const bool default_enable_5rto_blackhole_detection_ =
2267       GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection2);
2268 
2269   // True if next packet is intended to consume remaining space in the
2270   // coalescer.
2271   bool fill_coalesced_packet_ = false;
2272 
2273   size_t anti_amplification_factor_ =
2274       GetQuicFlag(quic_anti_amplification_factor);
2275 
2276   // True if AckFrequencyFrame is supported.
2277   bool can_receive_ack_frequency_frame_ = false;
2278 
2279   // Indicate whether coalescing is done.
2280   bool coalescing_done_ = false;
2281 
2282   // Indicate whether any ENCRYPTION_HANDSHAKE packet has been sent.
2283   bool handshake_packet_sent_ = false;
2284 
2285   // Indicate whether to send an AckFrequencyFrame upon handshake completion.
2286   // The AckFrequencyFrame sent will updates client's max_ack_delay, which if
2287   // chosen properly can reduce the CPU and bandwidth usage for ACK frames.
2288   bool send_ack_frequency_on_handshake_completion_ = false;
2289 
2290   // Indicate whether AckFrequency frame has been sent.
2291   bool ack_frequency_sent_ = false;
2292 
2293   // True if a 0-RTT decrypter was or is installed at some point in the
2294   // connection's lifetime.
2295   bool had_zero_rtt_decrypter_ = false;
2296 
2297   // True after the first 1-RTT packet has successfully decrypted.
2298   bool have_decrypted_first_one_rtt_packet_ = false;
2299 
2300   // True if we are currently processing OnRetransmissionTimeout.
2301   bool in_probe_time_out_ = false;
2302 
2303   QuicPathValidator path_validator_;
2304 
2305   // Stores information of a path which maybe used as default path in the
2306   // future. On the client side, it gets created when the client starts
2307   // validating a new path and gets cleared once it becomes the default path or
2308   // the path validation fails or replaced by a newer path of interest. On the
2309   // server side, alternative_path gets created when server: 1) receives
2310   // PATH_CHALLENGE on non-default path, or 2) switches to a not yet validated
2311   // default path such that it needs to store the previous validated default
2312   // path.
2313   // Note that if alternative_path_ stores a validated path information (case
2314   // 2), do not override it on receiving PATH_CHALLENGE (case 1).
2315   PathState alternative_path_;
2316 
2317   // If true, upon seeing a new client address, validate the client address.
2318   bool validate_client_addresses_ = false;
2319 
2320   // Indicates whether we should proactively validate peer address on a
2321   // PATH_CHALLENGE received.
2322   bool should_proactively_validate_peer_address_on_path_challenge_ = false;
2323 
2324   // Enable this via reloadable flag once this feature is complete.
2325   bool connection_migration_use_new_cid_ = false;
2326 
2327   // If true, send connection close packet on INVALID_VERSION.
2328   bool send_connection_close_for_invalid_version_ = false;
2329 
2330   // If true, disable liveness testing.
2331   bool liveness_testing_disabled_ = false;
2332 
2333   QuicPingManager ping_manager_;
2334 
2335   // Records first serialized 1-RTT packet.
2336   std::unique_ptr<BufferedPacket> first_serialized_one_rtt_packet_;
2337 
2338   std::unique_ptr<QuicPathValidationContext> multi_port_path_context_;
2339 
2340   QuicTime::Delta multi_port_probing_interval_;
2341 
2342   std::unique_ptr<MultiPortStats> multi_port_stats_;
2343 
2344   RetransmittableOnWireBehavior retransmittable_on_wire_behavior_ = DEFAULT;
2345 
2346   // Server addresses that are known to the client.
2347   std::vector<QuicSocketAddress> known_server_addresses_;
2348 
2349   // Stores received server preferred address in transport param. Client side
2350   // only.
2351   QuicSocketAddress received_server_preferred_address_;
2352 
2353   // Stores sent server preferred address in transport param. Server side only.
2354   QuicSocketAddress sent_server_preferred_address_;
2355 
2356   // If true, kicks off validation of server_preferred_address_ once it is
2357   // received. Also, send all coalesced packets on both paths until handshake is
2358   // confirmed.
2359   bool accelerated_server_preferred_address_ = false;
2360 
2361   // TODO(b/223634460) Remove this.
2362   bool count_reverse_path_validation_stats_ = false;
2363 
2364   // If true, throttle sending if next created packet will exceed amplification
2365   // limit.
2366   const bool enforce_strict_amplification_factor_ =
2367       GetQuicFlag(quic_enforce_strict_amplification_factor);
2368 
2369   ConnectionIdGeneratorInterface& connection_id_generator_;
2370 
2371   // This LRU cache records source addresses of packets received on server's
2372   // original address.
2373   QuicLRUCache<QuicSocketAddress, bool, QuicSocketAddressHash>
2374       received_client_addresses_cache_;
2375 
2376   // Endpoints should never mark packets with Congestion Experienced (CE), as
2377   // this is only done by routers. Endpoints cannot send ECT(0) or ECT(1) if
2378   // their congestion control cannot respond to these signals in accordance with
2379   // the spec, or if the QUIC implementation doesn't validate ECN feedback. When
2380   // true, the connection will not verify that the requested codepoint adheres
2381   // to these policies. This is only accessible through QuicConnectionPeer.
2382   bool disable_ecn_codepoint_validation_ = false;
2383 };
2384 
2385 }  // namespace quic
2386 
2387 #endif  // QUICHE_QUIC_CORE_QUIC_CONNECTION_H_
2388