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