blob: 588504b650835cf47f527369ef1a555154ab1218 [file] [log] [blame]
QUICHE teama6ef0a62019-03-07 20:34:33 -05001// 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>
vasilvv872e7a32019-03-12 16:42:44 -070024#include <string>
QUICHE teama6ef0a62019-03-07 20:34:33 -050025#include <vector>
26
vasilvv9a36d722020-10-02 16:51:38 -070027#include "absl/strings/string_view.h"
vasilvv7df418b2020-10-13 13:47:09 -070028#include "absl/types/optional.h"
QUICHE team5be974e2020-12-29 18:35:24 -050029#include "quic/core/crypto/quic_decrypter.h"
30#include "quic/core/crypto/quic_encrypter.h"
31#include "quic/core/crypto/transport_parameters.h"
32#include "quic/core/frames/quic_ack_frequency_frame.h"
33#include "quic/core/frames/quic_max_streams_frame.h"
haoyuewange3c51d92021-03-08 07:35:03 -080034#include "quic/core/frames/quic_new_connection_id_frame.h"
QUICHE team5be974e2020-12-29 18:35:24 -050035#include "quic/core/proto/cached_network_parameters_proto.h"
36#include "quic/core/quic_alarm.h"
37#include "quic/core/quic_alarm_factory.h"
38#include "quic/core/quic_blocked_writer_interface.h"
QUICHE team5be974e2020-12-29 18:35:24 -050039#include "quic/core/quic_connection_id.h"
haoyuewange3c51d92021-03-08 07:35:03 -080040#include "quic/core/quic_connection_id_manager.h"
QUICHE team5be974e2020-12-29 18:35:24 -050041#include "quic/core/quic_connection_stats.h"
42#include "quic/core/quic_constants.h"
43#include "quic/core/quic_framer.h"
44#include "quic/core/quic_idle_network_detector.h"
45#include "quic/core/quic_mtu_discovery.h"
46#include "quic/core/quic_network_blackhole_detector.h"
47#include "quic/core/quic_one_block_arena.h"
48#include "quic/core/quic_packet_creator.h"
49#include "quic/core/quic_packet_writer.h"
50#include "quic/core/quic_packets.h"
51#include "quic/core/quic_path_validator.h"
52#include "quic/core/quic_sent_packet_manager.h"
53#include "quic/core/quic_time.h"
54#include "quic/core/quic_types.h"
55#include "quic/core/uber_received_packet_manager.h"
56#include "quic/platform/api/quic_containers.h"
57#include "quic/platform/api/quic_export.h"
renjietang7f1d9e12021-01-22 19:10:57 -080058#include "quic/platform/api/quic_flags.h"
QUICHE team5be974e2020-12-29 18:35:24 -050059#include "quic/platform/api/quic_socket_address.h"
bnc08fc2ae2021-04-27 14:57:51 -070060#include "common/quiche_circular_deque.h"
QUICHE teama6ef0a62019-03-07 20:34:33 -050061
62namespace quic {
63
64class QuicClock;
65class QuicConfig;
66class QuicConnection;
67class QuicRandom;
68
69namespace test {
70class QuicConnectionPeer;
71} // namespace test
72
QUICHE teama6ef0a62019-03-07 20:34:33 -050073// Class that receives callbacks from the connection when frames are received
74// and when other interesting events happen.
75class QUIC_EXPORT_PRIVATE QuicConnectionVisitorInterface {
76 public:
77 virtual ~QuicConnectionVisitorInterface() {}
78
79 // A simple visitor interface for dealing with a data frame.
80 virtual void OnStreamFrame(const QuicStreamFrame& frame) = 0;
81
82 // Called when a CRYPTO frame containing handshake data is received.
83 virtual void OnCryptoFrame(const QuicCryptoFrame& frame) = 0;
84
85 // The session should process the WINDOW_UPDATE frame, adjusting both stream
86 // and connection level flow control windows.
87 virtual void OnWindowUpdateFrame(const QuicWindowUpdateFrame& frame) = 0;
88
89 // A BLOCKED frame indicates the peer is flow control blocked
90 // on a specified stream.
91 virtual void OnBlockedFrame(const QuicBlockedFrame& frame) = 0;
92
93 // Called when the stream is reset by the peer.
94 virtual void OnRstStream(const QuicRstStreamFrame& frame) = 0;
95
96 // Called when the connection is going away according to the peer.
97 virtual void OnGoAway(const QuicGoAwayFrame& frame) = 0;
98
99 // Called when |message| has been received.
vasilvv9a36d722020-10-02 16:51:38 -0700100 virtual void OnMessageReceived(absl::string_view message) = 0;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500101
fayang01062942020-01-22 07:23:23 -0800102 // Called when a HANDSHAKE_DONE frame has been received.
103 virtual void OnHandshakeDoneReceived() = 0;
104
fayang133b8682020-12-08 05:50:33 -0800105 // Called when a NEW_TOKEN frame has been received.
106 virtual void OnNewTokenReceived(absl::string_view token) = 0;
107
fkastenholz3c4eabf2019-04-22 07:49:59 -0700108 // Called when a MAX_STREAMS frame has been received from the peer.
109 virtual bool OnMaxStreamsFrame(const QuicMaxStreamsFrame& frame) = 0;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500110
fkastenholz3c4eabf2019-04-22 07:49:59 -0700111 // Called when a STREAMS_BLOCKED frame has been received from the peer.
112 virtual bool OnStreamsBlockedFrame(const QuicStreamsBlockedFrame& frame) = 0;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500113
114 // Called when the connection is closed either locally by the framer, or
115 // remotely by the peer.
fkastenholz5d880a92019-06-21 09:01:56 -0700116 virtual void OnConnectionClosed(const QuicConnectionCloseFrame& frame,
QUICHE teama6ef0a62019-03-07 20:34:33 -0500117 ConnectionCloseSource source) = 0;
118
119 // Called when the connection failed to write because the socket was blocked.
120 virtual void OnWriteBlocked() = 0;
121
122 // Called once a specific QUIC version is agreed by both endpoints.
123 virtual void OnSuccessfulVersionNegotiation(
124 const ParsedQuicVersion& version) = 0;
125
zhongyi83161e42019-08-19 09:06:25 -0700126 // Called when a packet has been received by the connection, after being
127 // validated and parsed. Only called when the client receives a valid packet
128 // or the server receives a connectivity probing packet.
129 // |is_connectivity_probe| is true if the received packet is a connectivity
130 // probe.
131 virtual void OnPacketReceived(const QuicSocketAddress& self_address,
132 const QuicSocketAddress& peer_address,
133 bool is_connectivity_probe) = 0;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500134
135 // Called when a blocked socket becomes writable.
136 virtual void OnCanWrite() = 0;
137
QUICHE teamb8343252019-04-29 13:58:01 -0700138 // Called when the connection needs more data to probe for additional
139 // bandwidth. Returns true if data was sent, false otherwise.
140 virtual bool SendProbingData() = 0;
141
renjietang7f483b52020-05-20 14:30:47 -0700142 // Called when stateless reset packet is received. Returns true if the
143 // connection needs to be closed.
144 virtual bool ValidateStatelessReset(
145 const quic::QuicSocketAddress& self_address,
146 const quic::QuicSocketAddress& peer_address) = 0;
renjietang5b245892020-05-18 11:57:26 -0700147
QUICHE teama6ef0a62019-03-07 20:34:33 -0500148 // Called when the connection experiences a change in congestion window.
149 virtual void OnCongestionWindowChange(QuicTime now) = 0;
150
151 // Called when the connection receives a packet from a migrated client.
152 virtual void OnConnectionMigration(AddressChangeType type) = 0;
153
154 // Called when the peer seems unreachable over the current path.
155 virtual void OnPathDegrading() = 0;
156
zhongyief1d6752020-06-11 16:19:28 -0700157 // Called when forward progress made after path degrading.
158 virtual void OnForwardProgressMadeAfterPathDegrading() = 0;
159
QUICHE teama6ef0a62019-03-07 20:34:33 -0500160 // Called when the connection sends ack after
161 // max_consecutive_num_packets_with_no_retransmittable_frames_ consecutive not
162 // retransmittable packets sent. To instigate an ack from peer, a
163 // retransmittable frame needs to be added.
164 virtual void OnAckNeedsRetransmittableFrame() = 0;
165
haoyuewangc921f8d2020-10-14 18:06:52 -0700166 // Called when an AckFrequency frame need to be sent.
167 virtual void SendAckFrequency(const QuicAckFrequencyFrame& frame) = 0;
168
haoyuewange3c51d92021-03-08 07:35:03 -0800169 // Called to send a NEW_CONNECTION_ID frame.
170 virtual void SendNewConnectionId(const QuicNewConnectionIdFrame& frame) = 0;
171
172 // Called to send a RETIRE_CONNECTION_ID frame.
173 virtual void SendRetireConnectionId(uint64_t sequence_number) = 0;
174
175 // Called when server starts to use a server issued connection ID.
176 virtual void OnServerConnectionIdIssued(
177 const QuicConnectionId& server_connection_id) = 0;
178
179 // Called when server stops to use a server issued connection ID.
180 virtual void OnServerConnectionIdRetired(
181 const QuicConnectionId& server_connection_id) = 0;
182
QUICHE teama6ef0a62019-03-07 20:34:33 -0500183 // Called to ask if the visitor wants to schedule write resumption as it both
184 // has pending data to write, and is able to write (e.g. based on flow control
185 // limits).
186 // Writes may be pending because they were write-blocked, congestion-throttled
187 // or yielded to other connections.
188 virtual bool WillingAndAbleToWrite() const = 0;
189
QUICHE teama6ef0a62019-03-07 20:34:33 -0500190 // Called to ask if the connection should be kept alive and prevented
191 // from timing out, for example if there are outstanding application
192 // transactions expecting a response.
193 virtual bool ShouldKeepConnectionAlive() const = 0;
194
fayanga330b7c2020-09-10 08:15:39 -0700195 // Called to retrieve streams information for logging purpose.
196 virtual std::string GetStreamsInfoForLogging() const = 0;
197
QUICHE teama6ef0a62019-03-07 20:34:33 -0500198 // Called when a self address change is observed. Returns true if self address
199 // change is allowed.
200 virtual bool AllowSelfAddressChange() const = 0;
201
fayangc67c5202020-01-22 07:43:15 -0800202 // Called to get current handshake state.
203 virtual HandshakeState GetHandshakeState() const = 0;
204
QUICHE teama6ef0a62019-03-07 20:34:33 -0500205 // Called when a STOP_SENDING frame has been received.
renjietangeab918f2019-10-28 12:10:32 -0700206 virtual void OnStopSendingFrame(const QuicStopSendingFrame& frame) = 0;
fayangd58736d2019-11-27 13:35:31 -0800207
208 // Called when a packet of encryption |level| has been successfully decrypted.
209 virtual void OnPacketDecrypted(EncryptionLevel level) = 0;
fayang2f2915d2020-01-24 06:47:15 -0800210
211 // Called when a 1RTT packet has been acknowledged.
212 virtual void OnOneRttPacketAcknowledged() = 0;
fayang44ae4e92020-04-28 13:09:42 -0700213
214 // Called when a packet of ENCRYPTION_HANDSHAKE gets sent.
215 virtual void OnHandshakePacketSent() = 0;
mattm072a7e32020-10-09 16:16:56 -0700216
mattme57062e2020-10-19 11:32:43 -0700217 // Called when a key update has occurred.
218 virtual void OnKeyUpdate(KeyUpdateReason reason) = 0;
219
mattm072a7e32020-10-09 16:16:56 -0700220 // Called to generate a decrypter for the next key phase. Each call should
221 // generate the key for phase n+1.
222 virtual std::unique_ptr<QuicDecrypter>
223 AdvanceKeysAndCreateCurrentOneRttDecrypter() = 0;
224
225 // Called to generate an encrypter for the same key phase of the last
226 // decrypter returned by AdvanceKeysAndCreateCurrentOneRttDecrypter().
227 virtual std::unique_ptr<QuicEncrypter> CreateCurrentOneRttEncrypter() = 0;
bncc03d2c22020-10-15 13:30:09 -0700228
229 // Called when connection is being closed right before a CONNECTION_CLOSE
230 // frame is serialized, but only on the server and only if forward secure
231 // encryption has already been established.
232 virtual void BeforeConnectionCloseSent() = 0;
fayang133b8682020-12-08 05:50:33 -0800233
234 // Called by the server to validate |token| in received INITIAL packets.
235 // Consider the client address gets validated (and therefore remove
236 // amplification factor) once the |token| gets successfully validated.
237 virtual bool ValidateToken(absl::string_view token) const = 0;
danzhedcc10d2020-12-21 14:47:15 -0800238
239 // Called by the server to send another token.
240 // Return false if the crypto stream fail to generate one.
241 virtual void MaybeSendAddressToken() = 0;
haoyuewang1c1771f2021-03-15 15:01:53 -0700242
243 // Whether the server address is known to the connection.
244 virtual bool IsKnownServerAddress(const QuicSocketAddress& address) const = 0;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500245};
246
247// Interface which gets callbacks from the QuicConnection at interesting
248// points. Implementations must not mutate the state of the connection
249// as a result of these callbacks.
250class QUIC_EXPORT_PRIVATE QuicConnectionDebugVisitor
251 : public QuicSentPacketManager::DebugDelegate {
252 public:
253 ~QuicConnectionDebugVisitor() override {}
254
255 // Called when a packet has been sent.
wubacc7c972020-09-14 16:16:32 -0700256 virtual void OnPacketSent(QuicPacketNumber /*packet_number*/,
257 QuicPacketLength /*packet_length*/,
258 bool /*has_crypto_handshake*/,
259 TransmissionType /*transmission_type*/,
260 EncryptionLevel /*encryption_level*/,
261 const QuicFrames& /*retransmittable_frames*/,
262 const QuicFrames& /*nonretransmittable_frames*/,
263 QuicTime /*sent_time*/) {}
264
fayang6100ab72020-03-18 13:16:25 -0700265 // Called when a coalesced packet has been sent.
266 virtual void OnCoalescedPacketSent(
267 const QuicCoalescedPacket& /*coalesced_packet*/,
268 size_t /*length*/) {}
269
QUICHE teama6ef0a62019-03-07 20:34:33 -0500270 // Called when a PING frame has been sent.
271 virtual void OnPingSent() {}
272
273 // Called when a packet has been received, but before it is
274 // validated or parsed.
dschinazi17d42422019-06-18 16:35:07 -0700275 virtual void OnPacketReceived(const QuicSocketAddress& /*self_address*/,
276 const QuicSocketAddress& /*peer_address*/,
277 const QuicEncryptedPacket& /*packet*/) {}
QUICHE teama6ef0a62019-03-07 20:34:33 -0500278
279 // Called when the unauthenticated portion of the header has been parsed.
dschinazi17d42422019-06-18 16:35:07 -0700280 virtual void OnUnauthenticatedHeader(const QuicPacketHeader& /*header*/) {}
QUICHE teama6ef0a62019-03-07 20:34:33 -0500281
282 // Called when a packet is received with a connection id that does not
283 // match the ID of this connection.
dschinazi17d42422019-06-18 16:35:07 -0700284 virtual void OnIncorrectConnectionId(QuicConnectionId /*connection_id*/) {}
QUICHE teama6ef0a62019-03-07 20:34:33 -0500285
fayang9dcfaca2020-04-24 06:57:14 -0700286 // Called when an undecryptable packet has been received. If |dropped| is
287 // true, the packet has been dropped. Otherwise, the packet will be queued and
288 // connection will attempt to process it later.
289 virtual void OnUndecryptablePacket(EncryptionLevel /*decryption_level*/,
290 bool /*dropped*/) {}
291
292 // Called when attempting to process a previously undecryptable packet.
293 virtual void OnAttemptingToProcessUndecryptablePacket(
294 EncryptionLevel /*decryption_level*/) {}
QUICHE teama6ef0a62019-03-07 20:34:33 -0500295
296 // Called when a duplicate packet has been received.
dschinazi17d42422019-06-18 16:35:07 -0700297 virtual void OnDuplicatePacket(QuicPacketNumber /*packet_number*/) {}
QUICHE teama6ef0a62019-03-07 20:34:33 -0500298
299 // Called when the protocol version on the received packet doensn't match
300 // current protocol version of the connection.
dschinazi17d42422019-06-18 16:35:07 -0700301 virtual void OnProtocolVersionMismatch(ParsedQuicVersion /*version*/) {}
QUICHE teama6ef0a62019-03-07 20:34:33 -0500302
303 // Called when the complete header of a packet has been parsed.
fayang182ae362020-10-01 12:08:49 -0700304 virtual void OnPacketHeader(const QuicPacketHeader& /*header*/,
305 QuicTime /*receive_time*/,
306 EncryptionLevel /*level*/) {}
QUICHE teama6ef0a62019-03-07 20:34:33 -0500307
308 // Called when a StreamFrame has been parsed.
dschinazi17d42422019-06-18 16:35:07 -0700309 virtual void OnStreamFrame(const QuicStreamFrame& /*frame*/) {}
QUICHE teama6ef0a62019-03-07 20:34:33 -0500310
rchb7e6e642019-09-03 21:57:05 -0700311 // Called when a CRYPTO frame containing handshake data is received.
312 virtual void OnCryptoFrame(const QuicCryptoFrame& /*frame*/) {}
313
QUICHE teama6ef0a62019-03-07 20:34:33 -0500314 // Called when a StopWaitingFrame has been parsed.
dschinazi17d42422019-06-18 16:35:07 -0700315 virtual void OnStopWaitingFrame(const QuicStopWaitingFrame& /*frame*/) {}
QUICHE teama6ef0a62019-03-07 20:34:33 -0500316
317 // Called when a QuicPaddingFrame has been parsed.
dschinazi17d42422019-06-18 16:35:07 -0700318 virtual void OnPaddingFrame(const QuicPaddingFrame& /*frame*/) {}
QUICHE teama6ef0a62019-03-07 20:34:33 -0500319
320 // Called when a Ping has been parsed.
fayangd2bf0ba2020-08-14 07:57:56 -0700321 virtual void OnPingFrame(const QuicPingFrame& /*frame*/,
322 QuicTime::Delta /*ping_received_delay*/) {}
QUICHE teama6ef0a62019-03-07 20:34:33 -0500323
324 // Called when a GoAway has been parsed.
dschinazi17d42422019-06-18 16:35:07 -0700325 virtual void OnGoAwayFrame(const QuicGoAwayFrame& /*frame*/) {}
QUICHE teama6ef0a62019-03-07 20:34:33 -0500326
327 // Called when a RstStreamFrame has been parsed.
dschinazi17d42422019-06-18 16:35:07 -0700328 virtual void OnRstStreamFrame(const QuicRstStreamFrame& /*frame*/) {}
QUICHE teama6ef0a62019-03-07 20:34:33 -0500329
fkastenholz04bd4f32019-04-16 12:24:38 -0700330 // Called when a ConnectionCloseFrame has been parsed. All forms
331 // of CONNECTION CLOSE are handled, Google QUIC, IETF QUIC
332 // CONNECTION CLOSE/Transport and IETF QUIC CONNECTION CLOSE/Application
dschinazi17d42422019-06-18 16:35:07 -0700333 virtual void OnConnectionCloseFrame(
334 const QuicConnectionCloseFrame& /*frame*/) {}
QUICHE teama6ef0a62019-03-07 20:34:33 -0500335
QUICHE teama6ef0a62019-03-07 20:34:33 -0500336 // Called when a WindowUpdate has been parsed.
dschinazi17d42422019-06-18 16:35:07 -0700337 virtual void OnWindowUpdateFrame(const QuicWindowUpdateFrame& /*frame*/,
338 const QuicTime& /*receive_time*/) {}
QUICHE teama6ef0a62019-03-07 20:34:33 -0500339
340 // Called when a BlockedFrame has been parsed.
dschinazi17d42422019-06-18 16:35:07 -0700341 virtual void OnBlockedFrame(const QuicBlockedFrame& /*frame*/) {}
QUICHE teama6ef0a62019-03-07 20:34:33 -0500342
rchb7e6e642019-09-03 21:57:05 -0700343 // Called when a NewConnectionIdFrame has been parsed.
344 virtual void OnNewConnectionIdFrame(
345 const QuicNewConnectionIdFrame& /*frame*/) {}
346
347 // Called when a RetireConnectionIdFrame has been parsed.
348 virtual void OnRetireConnectionIdFrame(
349 const QuicRetireConnectionIdFrame& /*frame*/) {}
350
351 // Called when a NewTokenFrame has been parsed.
352 virtual void OnNewTokenFrame(const QuicNewTokenFrame& /*frame*/) {}
353
QUICHE teama6ef0a62019-03-07 20:34:33 -0500354 // Called when a MessageFrame has been parsed.
dschinazi17d42422019-06-18 16:35:07 -0700355 virtual void OnMessageFrame(const QuicMessageFrame& /*frame*/) {}
QUICHE teama6ef0a62019-03-07 20:34:33 -0500356
fayang01062942020-01-22 07:23:23 -0800357 // Called when a HandshakeDoneFrame has been parsed.
358 virtual void OnHandshakeDoneFrame(const QuicHandshakeDoneFrame& /*frame*/) {}
359
QUICHE teama6ef0a62019-03-07 20:34:33 -0500360 // Called when a public reset packet has been received.
dschinazi17d42422019-06-18 16:35:07 -0700361 virtual void OnPublicResetPacket(const QuicPublicResetPacket& /*packet*/) {}
QUICHE teama6ef0a62019-03-07 20:34:33 -0500362
363 // Called when a version negotiation packet has been received.
364 virtual void OnVersionNegotiationPacket(
dschinazi17d42422019-06-18 16:35:07 -0700365 const QuicVersionNegotiationPacket& /*packet*/) {}
QUICHE teama6ef0a62019-03-07 20:34:33 -0500366
367 // Called when the connection is closed.
fkastenholzac11db02019-06-24 06:22:04 -0700368 virtual void OnConnectionClosed(const QuicConnectionCloseFrame& /*frame*/,
dschinazi17d42422019-06-18 16:35:07 -0700369 ConnectionCloseSource /*source*/) {}
QUICHE teama6ef0a62019-03-07 20:34:33 -0500370
371 // Called when the version negotiation is successful.
372 virtual void OnSuccessfulVersionNegotiation(
dschinazi17d42422019-06-18 16:35:07 -0700373 const ParsedQuicVersion& /*version*/) {}
QUICHE teama6ef0a62019-03-07 20:34:33 -0500374
375 // Called when a CachedNetworkParameters is sent to the client.
376 virtual void OnSendConnectionState(
dschinazi17d42422019-06-18 16:35:07 -0700377 const CachedNetworkParameters& /*cached_network_params*/) {}
QUICHE teama6ef0a62019-03-07 20:34:33 -0500378
379 // Called when a CachedNetworkParameters are received from the client.
380 virtual void OnReceiveConnectionState(
dschinazi17d42422019-06-18 16:35:07 -0700381 const CachedNetworkParameters& /*cached_network_params*/) {}
QUICHE teama6ef0a62019-03-07 20:34:33 -0500382
383 // Called when the connection parameters are set from the supplied
384 // |config|.
dschinazi17d42422019-06-18 16:35:07 -0700385 virtual void OnSetFromConfig(const QuicConfig& /*config*/) {}
QUICHE teama6ef0a62019-03-07 20:34:33 -0500386
387 // Called when RTT may have changed, including when an RTT is read from
388 // the config.
dschinazi17d42422019-06-18 16:35:07 -0700389 virtual void OnRttChanged(QuicTime::Delta /*rtt*/) const {}
QUICHE teama6ef0a62019-03-07 20:34:33 -0500390
391 // Called when a StopSendingFrame has been parsed.
dschinazi17d42422019-06-18 16:35:07 -0700392 virtual void OnStopSendingFrame(const QuicStopSendingFrame& /*frame*/) {}
rchb7e6e642019-09-03 21:57:05 -0700393
394 // Called when a PathChallengeFrame has been parsed.
395 virtual void OnPathChallengeFrame(const QuicPathChallengeFrame& /*frame*/) {}
396
397 // Called when a PathResponseFrame has been parsed.
398 virtual void OnPathResponseFrame(const QuicPathResponseFrame& /*frame*/) {}
renjietangc7054902019-09-25 13:13:52 -0700399
400 // Called when a StreamsBlockedFrame has been parsed.
401 virtual void OnStreamsBlockedFrame(const QuicStreamsBlockedFrame& /*frame*/) {
402 }
403
404 // Called when a MaxStreamsFrame has been parsed.
405 virtual void OnMaxStreamsFrame(const QuicMaxStreamsFrame& /*frame*/) {}
fayang2cbfccf2019-11-14 14:02:15 -0800406
fayang182ae362020-10-01 12:08:49 -0700407 // Called when an AckFrequencyFrame has been parsed.
408 virtual void OnAckFrequencyFrame(const QuicAckFrequencyFrame& /*frame*/) {}
409
fayang2cbfccf2019-11-14 14:02:15 -0800410 // Called when |count| packet numbers have been skipped.
fayang08e19602020-07-09 13:08:35 -0700411 virtual void OnNPacketNumbersSkipped(QuicPacketCount /*count*/,
412 QuicTime /*now*/) {}
dschinazi631f1602020-05-19 10:10:22 -0700413
414 // Called for QUIC+TLS versions when we send transport parameters.
415 virtual void OnTransportParametersSent(
416 const TransportParameters& /*transport_parameters*/) {}
417
418 // Called for QUIC+TLS versions when we receive transport parameters.
419 virtual void OnTransportParametersReceived(
420 const TransportParameters& /*transport_parameters*/) {}
renjietang8957c6e2020-08-12 16:08:21 -0700421
422 // Called for QUIC+TLS versions when we resume cached transport parameters for
423 // 0-RTT.
424 virtual void OnTransportParametersResumed(
425 const TransportParameters& /*transport_parameters*/) {}
renjietang5c6834b2020-08-17 11:00:48 -0700426
427 // Called for QUIC+TLS versions when 0-RTT is rejected.
renjietangf71e8062020-09-14 12:01:15 -0700428 virtual void OnZeroRttRejected(int /*reject_reason*/) {}
fayang2ac31ae2020-09-17 17:02:59 -0700429
fayangf2e0d902020-09-25 14:47:19 -0700430 // Called for QUIC+TLS versions when 0-RTT packet gets acked.
431 virtual void OnZeroRttPacketAcked() {}
432
fayang2ac31ae2020-09-17 17:02:59 -0700433 // Called on peer address change.
434 virtual void OnPeerAddressChange(AddressChangeType /*type*/,
435 QuicTime::Delta /*connection_time*/) {}
danzhd6cf8bd2021-03-03 15:45:08 -0800436
437 // Called after peer migration is validated.
438 virtual void OnPeerMigrationValidated(QuicTime::Delta /*connection_time*/) {}
QUICHE teama6ef0a62019-03-07 20:34:33 -0500439};
440
441class QUIC_EXPORT_PRIVATE QuicConnectionHelperInterface {
442 public:
443 virtual ~QuicConnectionHelperInterface() {}
444
445 // Returns a QuicClock to be used for all time related functions.
446 virtual const QuicClock* GetClock() const = 0;
447
448 // Returns a QuicRandom to be used for all random number related functions.
449 virtual QuicRandom* GetRandomGenerator() = 0;
450
451 // Returns a QuicBufferAllocator to be used for stream send buffers.
452 virtual QuicBufferAllocator* GetStreamSendBufferAllocator() = 0;
453};
454
455class QUIC_EXPORT_PRIVATE QuicConnection
456 : public QuicFramerVisitorInterface,
457 public QuicBlockedWriterInterface,
fayangcad11792019-09-16 13:11:44 -0700458 public QuicPacketCreator::DelegateInterface,
fayangb59c6f12020-03-23 15:06:14 -0700459 public QuicSentPacketManager::NetworkChangeVisitor,
fayangb9c88442020-03-26 07:03:57 -0700460 public QuicNetworkBlackholeDetector::Delegate,
danzhe6211dc2020-11-19 09:19:00 -0800461 public QuicIdleNetworkDetector::Delegate,
haoyuewange3c51d92021-03-08 07:35:03 -0800462 public QuicPathValidator::SendDelegate,
463 public QuicConnectionIdManagerVisitorInterface {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500464 public:
QUICHE teama6ef0a62019-03-07 20:34:33 -0500465 // Constructs a new QuicConnection for |connection_id| and
466 // |initial_peer_address| using |writer| to write packets. |owns_writer|
467 // specifies whether the connection takes ownership of |writer|. |helper| must
468 // outlive this connection.
dschinazi7b9278c2019-05-20 07:36:21 -0700469 QuicConnection(QuicConnectionId server_connection_id,
wub5df36632020-10-01 14:42:17 -0700470 QuicSocketAddress initial_self_address,
QUICHE teama6ef0a62019-03-07 20:34:33 -0500471 QuicSocketAddress initial_peer_address,
472 QuicConnectionHelperInterface* helper,
473 QuicAlarmFactory* alarm_factory,
474 QuicPacketWriter* writer,
475 bool owns_writer,
476 Perspective perspective,
477 const ParsedQuicVersionVector& supported_versions);
478 QuicConnection(const QuicConnection&) = delete;
479 QuicConnection& operator=(const QuicConnection&) = delete;
480 ~QuicConnection() override;
481
482 // Sets connection parameters from the supplied |config|.
483 void SetFromConfig(const QuicConfig& config);
484
wubd09f1a62020-05-04 06:57:40 -0700485 // Apply |connection_options| for this connection. Unlike SetFromConfig, this
486 // can happen at anytime in the life of a connection.
487 // Note there is no guarantee that all options can be applied. Components will
488 // only apply cherrypicked options that make sense at the time of the call.
489 void ApplyConnectionOptions(const QuicTagVector& connection_options);
490
QUICHE teama6ef0a62019-03-07 20:34:33 -0500491 // Called by the session when sending connection state to the client.
492 virtual void OnSendConnectionState(
493 const CachedNetworkParameters& cached_network_params);
494
495 // Called by the session when receiving connection state from the client.
496 virtual void OnReceiveConnectionState(
497 const CachedNetworkParameters& cached_network_params);
498
499 // Called by the Session when the client has provided CachedNetworkParameters.
500 virtual void ResumeConnectionState(
501 const CachedNetworkParameters& cached_network_params,
502 bool max_bandwidth_resumption);
503
504 // Called by the Session when a max pacing rate for the connection is needed.
505 virtual void SetMaxPacingRate(QuicBandwidth max_pacing_rate);
506
507 // Allows the client to adjust network parameters based on external
508 // information.
QUICHE teamfdcfe3b2019-11-06 10:54:25 -0800509 void AdjustNetworkParameters(
510 const SendAlgorithmInterface::NetworkParams& params);
fayangf1b99dc2019-05-14 06:29:18 -0700511 void AdjustNetworkParameters(QuicBandwidth bandwidth,
512 QuicTime::Delta rtt,
513 bool allow_cwnd_to_decrease);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500514
wub44e33052020-03-03 17:11:40 -0800515 // Install a loss detection tuner. Must be called before OnConfigNegotiated.
516 void SetLossDetectionTuner(
517 std::unique_ptr<LossDetectionTunerInterface> tuner);
518 // Called by the session when session->is_configured() becomes true.
519 void OnConfigNegotiated();
520
QUICHE teama6ef0a62019-03-07 20:34:33 -0500521 // Returns the max pacing rate for the connection.
522 virtual QuicBandwidth MaxPacingRate() const;
523
524 // Sends crypto handshake messages of length |write_length| to the peer in as
525 // few packets as possible. Returns the number of bytes consumed from the
526 // data.
527 virtual size_t SendCryptoData(EncryptionLevel level,
528 size_t write_length,
529 QuicStreamOffset offset);
530
531 // Send the data of length |write_length| to the peer in as few packets as
532 // possible. Returns the number of bytes consumed from data, and a boolean
533 // indicating if the fin bit was consumed. This does not indicate the data
534 // has been sent on the wire: it may have been turned into a packet and queued
535 // if the socket was unexpectedly blocked.
536 virtual QuicConsumedData SendStreamData(QuicStreamId id,
537 size_t write_length,
538 QuicStreamOffset offset,
539 StreamSendingState state);
540
541 // Send |frame| to the peer. Returns true if frame is consumed, false
542 // otherwise.
543 virtual bool SendControlFrame(const QuicFrame& frame);
544
545 // Called when stream |id| is reset because of |error|.
546 virtual void OnStreamReset(QuicStreamId id, QuicRstStreamErrorCode error);
547
548 // Closes the connection.
549 // |connection_close_behavior| determines whether or not a connection close
550 // packet is sent to the peer.
551 virtual void CloseConnection(
552 QuicErrorCode error,
vasilvvc48c8712019-03-11 13:38:16 -0700553 const std::string& details,
QUICHE teama6ef0a62019-03-07 20:34:33 -0500554 ConnectionCloseBehavior connection_close_behavior);
mattm55006b02021-01-14 15:09:54 -0800555 // Closes the connection, specifying the wire error code |ietf_error|
556 // explicitly.
557 virtual void CloseConnection(
558 QuicErrorCode error,
559 QuicIetfTransportErrorCodes ietf_error,
560 const std::string& details,
561 ConnectionCloseBehavior connection_close_behavior);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500562
wubb104f0f2020-07-06 11:58:08 -0700563 QuicConnectionStats& mutable_stats() { return stats_; }
564
dschinazi4933ced2020-10-20 09:51:12 -0700565 int retransmittable_on_wire_ping_count() const {
566 return retransmittable_on_wire_ping_count_;
567 }
568
QUICHE teama6ef0a62019-03-07 20:34:33 -0500569 // Returns statistics tracked for this connection.
570 const QuicConnectionStats& GetStats();
571
572 // Processes an incoming UDP packet (consisting of a QuicEncryptedPacket) from
573 // the peer.
574 // In a client, the packet may be "stray" and have a different connection ID
575 // than that of this connection.
576 virtual void ProcessUdpPacket(const QuicSocketAddress& self_address,
577 const QuicSocketAddress& peer_address,
578 const QuicReceivedPacket& packet);
579
580 // QuicBlockedWriterInterface
581 // Called when the underlying connection becomes writable to allow queued
582 // writes to happen.
583 void OnBlockedWriterCanWrite() override;
584
585 bool IsWriterBlocked() const override {
586 return writer_ != nullptr && writer_->IsWriteBlocked();
587 }
588
589 // Called when the caller thinks it's worth a try to write.
fayangc2638cc2021-04-05 14:45:40 -0700590 // TODO(fayang): consider unifying this with QuicSession::OnCanWrite.
QUICHE teama6ef0a62019-03-07 20:34:33 -0500591 virtual void OnCanWrite();
592
593 // Called when an error occurs while attempting to write a packet to the
594 // network.
595 void OnWriteError(int error_code);
596
597 // Whether |result| represents a MSG TOO BIG write error.
598 bool IsMsgTooBig(const WriteResult& result);
599
600 // If the socket is not blocked, writes queued packets.
601 void WriteIfNotBlocked();
602
QUICHE teama6ef0a62019-03-07 20:34:33 -0500603 // Set the packet writer.
604 void SetQuicPacketWriter(QuicPacketWriter* writer, bool owns_writer) {
vasilvv5cef78e2021-01-30 11:11:14 -0800605 QUICHE_DCHECK(writer != nullptr);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500606 if (writer_ != nullptr && owns_writer_) {
607 delete writer_;
608 }
609 writer_ = writer;
610 owns_writer_ = owns_writer;
611 }
612
613 // Set self address.
danzh37b722e2021-02-17 11:09:08 -0800614 void SetSelfAddress(QuicSocketAddress address) {
615 default_path_.self_address = address;
616 }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500617
618 // The version of the protocol this connection is using.
619 QuicTransportVersion transport_version() const {
620 return framer_.transport_version();
621 }
622
623 ParsedQuicVersion version() const { return framer_.version(); }
624
625 // The versions of the protocol that this connection supports.
626 const ParsedQuicVersionVector& supported_versions() const {
627 return framer_.supported_versions();
628 }
629
wubf75c2c62020-02-05 06:34:09 -0800630 // Mark version negotiated for this connection. Once called, the connection
631 // will ignore received version negotiation packets.
632 void SetVersionNegotiated() {
633 version_negotiated_ = true;
634 if (perspective_ == Perspective::IS_SERVER) {
635 framer_.InferPacketHeaderTypeFromVersion();
636 }
637 }
638
QUICHE teama6ef0a62019-03-07 20:34:33 -0500639 // From QuicFramerVisitorInterface
640 void OnError(QuicFramer* framer) override;
fayang8aba1ff2019-06-21 12:00:54 -0700641 bool OnProtocolVersionMismatch(ParsedQuicVersion received_version) override;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500642 void OnPacket() override;
643 void OnPublicResetPacket(const QuicPublicResetPacket& packet) override;
644 void OnVersionNegotiationPacket(
645 const QuicVersionNegotiationPacket& packet) override;
dschinazi244f6dc2019-05-06 15:45:16 -0700646 void OnRetryPacket(QuicConnectionId original_connection_id,
647 QuicConnectionId new_connection_id,
vasilvv9a36d722020-10-02 16:51:38 -0700648 absl::string_view retry_token,
649 absl::string_view retry_integrity_tag,
650 absl::string_view retry_without_tag) override;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500651 bool OnUnauthenticatedPublicHeader(const QuicPacketHeader& header) override;
652 bool OnUnauthenticatedHeader(const QuicPacketHeader& header) override;
fayang93b4e4d2020-11-25 07:56:47 -0800653 void OnDecryptedPacket(size_t length, EncryptionLevel level) override;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500654 bool OnPacketHeader(const QuicPacketHeader& header) override;
655 void OnCoalescedPacket(const QuicEncryptedPacket& packet) override;
dschinazi4b5a68a2019-08-15 15:45:36 -0700656 void OnUndecryptablePacket(const QuicEncryptedPacket& packet,
657 EncryptionLevel decryption_level,
658 bool has_decryption_key) override;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500659 bool OnStreamFrame(const QuicStreamFrame& frame) override;
660 bool OnCryptoFrame(const QuicCryptoFrame& frame) override;
661 bool OnAckFrameStart(QuicPacketNumber largest_acked,
662 QuicTime::Delta ack_delay_time) override;
663 bool OnAckRange(QuicPacketNumber start, QuicPacketNumber end) override;
664 bool OnAckTimestamp(QuicPacketNumber packet_number,
665 QuicTime timestamp) override;
666 bool OnAckFrameEnd(QuicPacketNumber start) override;
667 bool OnStopWaitingFrame(const QuicStopWaitingFrame& frame) override;
668 bool OnPaddingFrame(const QuicPaddingFrame& frame) override;
669 bool OnPingFrame(const QuicPingFrame& frame) override;
670 bool OnRstStreamFrame(const QuicRstStreamFrame& frame) override;
671 bool OnConnectionCloseFrame(const QuicConnectionCloseFrame& frame) override;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500672 bool OnStopSendingFrame(const QuicStopSendingFrame& frame) override;
673 bool OnPathChallengeFrame(const QuicPathChallengeFrame& frame) override;
674 bool OnPathResponseFrame(const QuicPathResponseFrame& frame) override;
675 bool OnGoAwayFrame(const QuicGoAwayFrame& frame) override;
fkastenholz3c4eabf2019-04-22 07:49:59 -0700676 bool OnMaxStreamsFrame(const QuicMaxStreamsFrame& frame) override;
677 bool OnStreamsBlockedFrame(const QuicStreamsBlockedFrame& frame) override;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500678 bool OnWindowUpdateFrame(const QuicWindowUpdateFrame& frame) override;
679 bool OnBlockedFrame(const QuicBlockedFrame& frame) override;
680 bool OnNewConnectionIdFrame(const QuicNewConnectionIdFrame& frame) override;
681 bool OnRetireConnectionIdFrame(
682 const QuicRetireConnectionIdFrame& frame) override;
683 bool OnNewTokenFrame(const QuicNewTokenFrame& frame) override;
684 bool OnMessageFrame(const QuicMessageFrame& frame) override;
fayang01062942020-01-22 07:23:23 -0800685 bool OnHandshakeDoneFrame(const QuicHandshakeDoneFrame& frame) override;
haoyuewang6a6a0ff2020-06-23 16:32:26 -0700686 bool OnAckFrequencyFrame(const QuicAckFrequencyFrame& frame) override;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500687 void OnPacketComplete() override;
bnc1ccd0bc2021-04-07 10:20:17 -0700688 bool IsValidStatelessResetToken(
689 const StatelessResetToken& token) const override;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500690 void OnAuthenticatedIetfStatelessResetPacket(
691 const QuicIetfStatelessResetPacket& packet) override;
mattm5c7090d2020-10-19 10:36:43 -0700692 void OnKeyUpdate(KeyUpdateReason reason) override;
mattm072a7e32020-10-09 16:16:56 -0700693 void OnDecryptedFirstPacketInKeyPhase() override;
694 std::unique_ptr<QuicDecrypter> AdvanceKeysAndCreateCurrentOneRttDecrypter()
695 override;
696 std::unique_ptr<QuicEncrypter> CreateCurrentOneRttEncrypter() override;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500697
fayang4245c212019-11-05 13:33:46 -0800698 // QuicPacketCreator::DelegateInterface
QUICHE teama6ef0a62019-03-07 20:34:33 -0500699 bool ShouldGeneratePacket(HasRetransmittableData retransmittable,
700 IsHandshake handshake) override;
701 const QuicFrames MaybeBundleAckOpportunistically() override;
wub50d4c712020-05-19 15:48:28 -0700702 QuicPacketBuffer GetPacketBuffer() override;
wub8a5dafa2020-05-13 12:30:17 -0700703 void OnSerializedPacket(SerializedPacket packet) override;
ianswettb023c7b2019-05-06 12:38:10 -0700704 void OnUnrecoverableError(QuicErrorCode error,
fkastenholz85f18902019-05-28 12:47:00 -0700705 const std::string& error_details) override;
fayang15042962020-07-01 12:14:29 -0700706 SerializedPacketFate GetSerializedPacketFate(
707 bool is_mtu_discovery,
708 EncryptionLevel encryption_level) override;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500709
710 // QuicSentPacketManager::NetworkChangeVisitor
711 void OnCongestionChange() override;
712 void OnPathMtuIncreased(QuicPacketLength packet_size) override;
713
fayangb59c6f12020-03-23 15:06:14 -0700714 // QuicNetworkBlackholeDetector::Delegate
715 void OnPathDegradingDetected() override;
716 void OnBlackholeDetected() override;
wub8add68a2020-07-27 12:07:38 -0700717 void OnPathMtuReductionDetected() override;
fayangb59c6f12020-03-23 15:06:14 -0700718
fayangb9c88442020-03-26 07:03:57 -0700719 // QuicIdleNetworkDetector::Delegate
720 void OnHandshakeTimeout() override;
721 void OnIdleNetworkDetected() override;
722
haoyuewange3c51d92021-03-08 07:35:03 -0800723 // QuicConnectionIdManagerVisitorInterface
724 void OnPeerIssuedConnectionIdRetired() override;
725 bool SendNewConnectionId(const QuicNewConnectionIdFrame& frame) override;
726 void OnNewConnectionIdIssued(const QuicConnectionId& connection_id) override;
727 void OnSelfIssuedConnectionIdRetired(
728 const QuicConnectionId& connection_id) override;
729
fayanga4b37b22019-06-18 13:37:47 -0700730 // Please note, this is not a const function. For logging purpose, please use
731 // ack_frame().
732 const QuicFrame GetUpdatedAckFrame();
733
haoyuewange3c51d92021-03-08 07:35:03 -0800734 // Called to send a new connection ID to client if the # of connection ID has
735 // not exceeded the active connection ID limits.
736 void MaybeSendConnectionIdToClient();
737
fayangbd793922019-08-26 14:19:24 -0700738 // Called when the handshake completes. On the client side, handshake
739 // completes on receipt of SHLO. On the server side, handshake completes when
740 // SHLO gets ACKed (or a forward secure packet gets decrypted successfully).
741 // TODO(fayang): Add a guard that this only gets called once.
QUICHE teama6ef0a62019-03-07 20:34:33 -0500742 void OnHandshakeComplete();
743
744 // Accessors
745 void set_visitor(QuicConnectionVisitorInterface* visitor) {
746 visitor_ = visitor;
747 }
748 void set_debug_visitor(QuicConnectionDebugVisitor* debug_visitor) {
749 debug_visitor_ = debug_visitor;
750 sent_packet_manager_.SetDebugDelegate(debug_visitor);
751 }
752 // Used in Chromium, but not internally.
753 // Must only be called before ping_alarm_ is set.
754 void set_ping_timeout(QuicTime::Delta ping_timeout) {
vasilvv5cef78e2021-01-30 11:11:14 -0800755 QUICHE_DCHECK(!ping_alarm_->IsSet());
QUICHE teama6ef0a62019-03-07 20:34:33 -0500756 ping_timeout_ = ping_timeout;
757 }
zhongyicdf8b1b2019-10-22 12:03:10 -0700758 const QuicTime::Delta ping_timeout() const { return ping_timeout_; }
zhongyi79ace162019-10-21 15:57:09 -0700759 // Sets an initial timeout for the ping alarm when there is no retransmittable
760 // data in flight, allowing for a more aggressive ping alarm in that case.
761 void set_initial_retransmittable_on_wire_timeout(
QUICHE teama6ef0a62019-03-07 20:34:33 -0500762 QuicTime::Delta retransmittable_on_wire_timeout) {
vasilvv5cef78e2021-01-30 11:11:14 -0800763 QUICHE_DCHECK(!ping_alarm_->IsSet());
zhongyi79ace162019-10-21 15:57:09 -0700764 initial_retransmittable_on_wire_timeout_ = retransmittable_on_wire_timeout;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500765 }
zhongyicdf8b1b2019-10-22 12:03:10 -0700766 const QuicTime::Delta initial_retransmittable_on_wire_timeout() const {
767 return initial_retransmittable_on_wire_timeout_;
768 }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500769 // Used in Chromium, but not internally.
770 void set_creator_debug_delegate(QuicPacketCreator::DebugDelegate* visitor) {
fayang4245c212019-11-05 13:33:46 -0800771 packet_creator_.set_debug_delegate(visitor);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500772 }
danzh37b722e2021-02-17 11:09:08 -0800773 const QuicSocketAddress& self_address() const {
774 return default_path_.self_address;
775 }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500776 const QuicSocketAddress& peer_address() const { return direct_peer_address_; }
777 const QuicSocketAddress& effective_peer_address() const {
danzh37b722e2021-02-17 11:09:08 -0800778 return default_path_.peer_address;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500779 }
haoyuewang5c49d3e2021-04-08 07:33:33 -0700780 const QuicConnectionId& connection_id() const { return ServerConnectionId(); }
781 const QuicConnectionId& client_connection_id() const {
782 return ClientConnectionId();
dschinazi346b7ce2019-06-05 01:38:18 -0700783 }
784 void set_client_connection_id(QuicConnectionId client_connection_id);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500785 const QuicClock* clock() const { return clock_; }
786 QuicRandom* random_generator() const { return random_generator_; }
787 QuicByteCount max_packet_length() const;
788 void SetMaxPacketLength(QuicByteCount length);
789
790 size_t mtu_probe_count() const { return mtu_probe_count_; }
791
792 bool connected() const { return connected_; }
793
794 // Must only be called on client connections.
795 const ParsedQuicVersionVector& server_supported_versions() const {
vasilvv5cef78e2021-01-30 11:11:14 -0800796 QUICHE_DCHECK_EQ(Perspective::IS_CLIENT, perspective_);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500797 return server_supported_versions_;
798 }
799
ianswettfc16a2b2020-05-18 16:05:49 -0700800 bool HasQueuedPackets() const { return !buffered_packets_.empty(); }
801 // Testing only. TODO(ianswett): Use a peer instead.
fayange62e63c2019-12-04 07:16:25 -0800802 size_t NumQueuedPackets() const { return buffered_packets_.size(); }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500803
QUICHE teama6ef0a62019-03-07 20:34:33 -0500804 // Returns true if the connection has queued packets or frames.
805 bool HasQueuedData() const;
806
807 // Sets the handshake and idle state connection timeouts.
808 void SetNetworkTimeouts(QuicTime::Delta handshake_timeout,
809 QuicTime::Delta idle_timeout);
810
QUICHE teama6ef0a62019-03-07 20:34:33 -0500811 // Called when the ping alarm fires. Causes a ping frame to be sent only
812 // if the retransmission alarm is not running.
813 void OnPingTimeout();
814
815 // Sets up a packet with an QuicAckFrame and sends it out.
816 void SendAck();
817
QUICHE teama6ef0a62019-03-07 20:34:33 -0500818 // Called when an RTO fires. Resets the retransmission alarm if there are
819 // remaining unacked packets.
820 void OnRetransmissionTimeout();
821
renjietangb2b8ff22020-07-07 16:18:54 -0700822 // Mark all sent 0-RTT encrypted packets for retransmission. Called when new
823 // 0-RTT or 1-RTT key is available in gQUIC, or when 0-RTT is rejected in IETF
renjietangf71e8062020-09-14 12:01:15 -0700824 // QUIC. |reject_reason| is used in TLS-QUIC to log why 0-RTT was rejected.
825 void MarkZeroRttPacketsForRetransmission(int reject_reason);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500826
827 // Calls |sent_packet_manager_|'s NeuterUnencryptedPackets. Used when the
828 // connection becomes forward secure and hasn't received acks for all packets.
829 void NeuterUnencryptedPackets();
830
831 // Changes the encrypter used for level |level| to |encrypter|.
832 void SetEncrypter(EncryptionLevel level,
833 std::unique_ptr<QuicEncrypter> encrypter);
834
fayangb296fb82020-02-11 08:14:28 -0800835 // Called to remove encrypter of encryption |level|.
836 void RemoveEncrypter(EncryptionLevel level);
837
QUICHE teama6ef0a62019-03-07 20:34:33 -0500838 // SetNonceForPublicHeader sets the nonce that will be transmitted in the
839 // header of each packet encrypted at the initial encryption level decrypted.
840 // This should only be called on the server side.
841 void SetDiversificationNonce(const DiversificationNonce& nonce);
842
843 // SetDefaultEncryptionLevel sets the encryption level that will be applied
844 // to new packets.
845 void SetDefaultEncryptionLevel(EncryptionLevel level);
846
847 // SetDecrypter sets the primary decrypter, replacing any that already exists.
vasilvv5cef78e2021-01-30 11:11:14 -0800848 // If an alternative decrypter is in place then the function QUICHE_DCHECKs.
849 // This is intended for cases where one knows that future packets will be
850 // using the new decrypter and the previous decrypter is now obsolete. |level|
851 // indicates the encryption level of the new decrypter.
QUICHE teama6ef0a62019-03-07 20:34:33 -0500852 void SetDecrypter(EncryptionLevel level,
853 std::unique_ptr<QuicDecrypter> decrypter);
854
855 // SetAlternativeDecrypter sets a decrypter that may be used to decrypt
856 // future packets. |level| indicates the encryption level of the decrypter. If
857 // |latch_once_used| is true, then the first time that the decrypter is
858 // successful it will replace the primary decrypter. Otherwise both
859 // decrypters will remain active and the primary decrypter will be the one
860 // last used.
861 void SetAlternativeDecrypter(EncryptionLevel level,
862 std::unique_ptr<QuicDecrypter> decrypter,
863 bool latch_once_used);
864
zhongyi546cc452019-04-12 15:27:49 -0700865 void InstallDecrypter(EncryptionLevel level,
866 std::unique_ptr<QuicDecrypter> decrypter);
867 void RemoveDecrypter(EncryptionLevel level);
868
mattm072a7e32020-10-09 16:16:56 -0700869 // Discard keys for the previous key phase.
870 void DiscardPreviousOneRttKeys();
871
872 // Returns true if it is currently allowed to initiate a key update.
873 bool IsKeyUpdateAllowed() const;
874
mattm948d6892020-10-22 17:24:11 -0700875 // Returns true if packets have been sent in the current 1-RTT key phase but
876 // none of these packets have been acked.
877 bool HaveSentPacketsInCurrentKeyPhaseButNoneAcked() const;
878
mattmd061ef12020-10-23 11:21:31 -0700879 // Returns the count of packets received that appeared to attempt a key
880 // update but failed decryption that have been received since the last
881 // successfully decrypted packet.
882 QuicPacketCount PotentialPeerKeyUpdateAttemptCount() const;
883
mattm072a7e32020-10-09 16:16:56 -0700884 // Increment the key phase. It is a bug to call this when IsKeyUpdateAllowed()
885 // is false. Returns false on error.
mattm5c7090d2020-10-19 10:36:43 -0700886 bool InitiateKeyUpdate(KeyUpdateReason reason);
mattm072a7e32020-10-09 16:16:56 -0700887
QUICHE teama6ef0a62019-03-07 20:34:33 -0500888 const QuicDecrypter* decrypter() const;
889 const QuicDecrypter* alternative_decrypter() const;
890
891 Perspective perspective() const { return perspective_; }
892
893 // Allow easy overriding of truncated connection IDs.
894 void set_can_truncate_connection_ids(bool can) {
895 can_truncate_connection_ids_ = can;
896 }
897
898 // Returns the underlying sent packet manager.
899 const QuicSentPacketManager& sent_packet_manager() const {
900 return sent_packet_manager_;
901 }
902
903 // Returns the underlying sent packet manager.
904 QuicSentPacketManager& sent_packet_manager() { return sent_packet_manager_; }
905
ianswett309987e2019-08-02 13:16:26 -0700906 UberReceivedPacketManager& received_packet_manager() {
907 return uber_received_packet_manager_;
908 }
909
QUICHE teama6ef0a62019-03-07 20:34:33 -0500910 bool CanWrite(HasRetransmittableData retransmittable);
911
912 // When the flusher is out of scope, only the outermost flusher will cause a
913 // flush of the connection and set the retransmission alarm if there is one
914 // pending. In addition, this flusher can be configured to ensure that an ACK
915 // frame is included in the first packet created, if there's new ack
916 // information to be sent.
917 class QUIC_EXPORT_PRIVATE ScopedPacketFlusher {
918 public:
fayanga4b37b22019-06-18 13:37:47 -0700919 explicit ScopedPacketFlusher(QuicConnection* connection);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500920 ~ScopedPacketFlusher();
921
922 private:
QUICHE teama6ef0a62019-03-07 20:34:33 -0500923 QuicConnection* connection_;
924 // If true, when this flusher goes out of scope, flush connection and set
925 // retransmission alarm if there is one pending.
926 bool flush_and_set_pending_retransmission_alarm_on_delete_;
fayangd8682452020-09-28 09:09:29 -0700927 // Latched connection's handshake_packet_sent_ on creation of this flusher.
928 const bool handshake_packet_sent_;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500929 };
930
fayangec14d2b2020-10-02 12:00:05 -0700931 class QUIC_EXPORT_PRIVATE ScopedEncryptionLevelContext {
932 public:
933 ScopedEncryptionLevelContext(QuicConnection* connection,
934 EncryptionLevel level);
935 ~ScopedEncryptionLevelContext();
936
937 private:
938 QuicConnection* connection_;
939 // Latched current write encryption level on creation of this context.
940 EncryptionLevel latched_encryption_level_;
941 };
942
QUICHE teama6ef0a62019-03-07 20:34:33 -0500943 QuicPacketWriter* writer() { return writer_; }
944 const QuicPacketWriter* writer() const { return writer_; }
945
946 // Sends an MTU discovery packet of size |target_mtu|. If the packet is
947 // acknowledged by the peer, the maximum packet size will be increased to
948 // |target_mtu|.
949 void SendMtuDiscoveryPacket(QuicByteCount target_mtu);
950
951 // Sends a connectivity probing packet to |peer_address| with
952 // |probing_writer|. If |probing_writer| is nullptr, will use default
953 // packet writer to write the packet. Returns true if subsequent packets can
954 // be written to the probing writer. If connection is V99, a padded IETF QUIC
955 // PATH_CHALLENGE packet is transmitted; if not V99, a Google QUIC padded PING
956 // packet is transmitted.
957 virtual bool SendConnectivityProbingPacket(
958 QuicPacketWriter* probing_writer,
959 const QuicSocketAddress& peer_address);
960
961 // Sends response to a connectivity probe. Sends either a Padded Ping
962 // or an IETF PATH_RESPONSE based on the version of the connection.
963 // Is the counterpart to SendConnectivityProbingPacket().
danzh8a27a1a2020-09-02 10:26:28 -0700964 // TODO(danzh): remove this method after deprecating
965 // --gfe2_reloadable_flag_quic_send_path_response.
QUICHE teama6ef0a62019-03-07 20:34:33 -0500966 virtual void SendConnectivityProbingResponsePacket(
967 const QuicSocketAddress& peer_address);
968
wub610f7ce2020-08-14 14:19:02 -0700969 // Disable MTU discovery on this connection.
970 void DisableMtuDiscovery();
971
wub173916e2019-11-27 14:36:24 -0800972 // Sends an MTU discovery packet and updates the MTU discovery alarm.
QUICHE teama6ef0a62019-03-07 20:34:33 -0500973 void DiscoverMtu();
974
975 // Sets the session notifier on the SentPacketManager.
976 void SetSessionNotifier(SessionNotifierInterface* session_notifier);
977
978 // Set data producer in framer.
979 void SetDataProducer(QuicStreamFrameDataProducer* data_producer);
980
981 // Set transmission type of next sending packets.
982 void SetTransmissionType(TransmissionType type);
983
984 // Tries to send |message| and returns the message status.
QUICHE team350e9e62019-11-19 13:16:24 -0800985 // If |flush| is false, this will return a MESSAGE_STATUS_BLOCKED
986 // when the connection is deemed unwritable.
QUICHE teama6ef0a62019-03-07 20:34:33 -0500987 virtual MessageStatus SendMessage(QuicMessageId message_id,
QUICHE team350e9e62019-11-19 13:16:24 -0800988 QuicMemSliceSpan message,
989 bool flush);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500990
991 // Returns the largest payload that will fit into a single MESSAGE frame.
ianswettb239f862019-04-05 09:15:06 -0700992 // Because overhead can vary during a connection, this method should be
993 // checked for every message.
994 QuicPacketLength GetCurrentLargestMessagePayload() const;
995 // Returns the largest payload that will fit into a single MESSAGE frame at
996 // any point during the connection. This assumes the version and
997 // connection ID lengths do not change.
998 QuicPacketLength GetGuaranteedLargestMessagePayload() const;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500999
haoyuewangcb7960c2020-11-23 16:40:53 -08001000 void SetUnackedMapInitialCapacity();
1001
haoyuewange0acd512020-11-05 09:18:36 -08001002 virtual int GetUnackedMapInitialCapacity() const {
1003 return kDefaultUnackedPacketsInitialCapacity;
1004 }
1005
zhongyi546cc452019-04-12 15:27:49 -07001006 // Returns the id of the cipher last used for decrypting packets.
1007 uint32_t cipher_id() const;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001008
1009 std::vector<std::unique_ptr<QuicEncryptedPacket>>* termination_packets() {
1010 return termination_packets_.get();
1011 }
1012
QUICHE teama6ef0a62019-03-07 20:34:33 -05001013 bool ack_frame_updated() const;
1014
1015 QuicConnectionHelperInterface* helper() { return helper_; }
wubb104f0f2020-07-06 11:58:08 -07001016 const QuicConnectionHelperInterface* helper() const { return helper_; }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001017 QuicAlarmFactory* alarm_factory() { return alarm_factory_; }
1018
vasilvv9a36d722020-10-02 16:51:38 -07001019 absl::string_view GetCurrentPacket();
QUICHE teama6ef0a62019-03-07 20:34:33 -05001020
1021 const QuicFramer& framer() const { return framer_; }
1022
fayang4245c212019-11-05 13:33:46 -08001023 const QuicPacketCreator& packet_creator() const { return packet_creator_; }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001024
QUICHE teama6ef0a62019-03-07 20:34:33 -05001025 EncryptionLevel encryption_level() const { return encryption_level_; }
1026 EncryptionLevel last_decrypted_level() const {
1027 return last_decrypted_packet_level_;
1028 }
1029
1030 const QuicSocketAddress& last_packet_source_address() const {
1031 return last_packet_source_address_;
1032 }
1033
1034 bool fill_up_link_during_probing() const {
1035 return fill_up_link_during_probing_;
1036 }
1037 void set_fill_up_link_during_probing(bool new_value) {
1038 fill_up_link_during_probing_ = new_value;
1039 }
1040
1041 // This setting may be changed during the crypto handshake in order to
1042 // enable/disable padding of different packets in the crypto handshake.
1043 //
1044 // This setting should never be set to false in public facing endpoints. It
1045 // can only be set to false if there is some other mechanism of preventing
1046 // amplification attacks, such as ICE (plus its a non-standard quic).
nharper3907ac22019-09-25 15:32:28 -07001047 void set_fully_pad_crypto_handshake_packets(bool new_value) {
fayang4245c212019-11-05 13:33:46 -08001048 packet_creator_.set_fully_pad_crypto_handshake_packets(new_value);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001049 }
1050
1051 bool fully_pad_during_crypto_handshake() const {
fayang4245c212019-11-05 13:33:46 -08001052 return packet_creator_.fully_pad_crypto_handshake_packets();
QUICHE teama6ef0a62019-03-07 20:34:33 -05001053 }
1054
1055 size_t min_received_before_ack_decimation() const;
1056 void set_min_received_before_ack_decimation(size_t new_value);
1057
QUICHE teama6ef0a62019-03-07 20:34:33 -05001058 // If |defer| is true, configures the connection to defer sending packets in
1059 // response to an ACK to the SendAlarm. If |defer| is false, packets may be
1060 // sent immediately after receiving an ACK.
1061 void set_defer_send_in_response_to_packets(bool defer) {
1062 defer_send_in_response_to_packets_ = defer;
1063 }
1064
QUICHE teama6ef0a62019-03-07 20:34:33 -05001065 // Sets the current per-packet options for the connection. The QuicConnection
1066 // does not take ownership of |options|; |options| must live for as long as
1067 // the QuicConnection is in use.
1068 void set_per_packet_options(PerPacketOptions* options) {
1069 per_packet_options_ = options;
1070 }
1071
1072 bool IsPathDegrading() const { return is_path_degrading_; }
1073
1074 // Attempts to process any queued undecryptable packets.
1075 void MaybeProcessUndecryptablePackets();
1076
1077 // Queue a coalesced packet.
1078 void QueueCoalescedPacket(const QuicEncryptedPacket& packet);
1079
fayangc2638cc2021-04-05 14:45:40 -07001080 // Process previously queued coalesced packets. Returns true if any coalesced
1081 // packets have been successfully processed.
1082 bool MaybeProcessCoalescedPackets();
QUICHE teama6ef0a62019-03-07 20:34:33 -05001083
1084 enum PacketContent : uint8_t {
1085 NO_FRAMES_RECEIVED,
1086 // TODO(fkastenholz): Change name when we get rid of padded ping/
1087 // pre-version-99.
1088 // Also PATH CHALLENGE and PATH RESPONSE.
1089 FIRST_FRAME_IS_PING,
1090 SECOND_FRAME_IS_PADDING,
1091 NOT_PADDED_PING, // Set if the packet is not {PING, PADDING}.
1092 };
1093
fayangfa3b1d62019-11-18 08:02:13 -08001094 // Whether the handshake completes from this connection's perspective.
fayang63a19842020-01-23 02:51:28 -08001095 bool IsHandshakeComplete() const;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001096
fayang5014e922020-01-22 12:28:11 -08001097 // Whether peer completes handshake. Only used with TLS handshake.
1098 bool IsHandshakeConfirmed() const;
1099
QUICHE team1f3de242019-03-20 07:24:48 -07001100 // Returns the largest received packet number sent by peer.
1101 QuicPacketNumber GetLargestReceivedPacket() const;
1102
dschinazi187683d2020-05-27 17:34:51 -04001103 // Sets the original destination connection ID on the connection.
1104 // This is called by QuicDispatcher when it has replaced the connection ID.
1105 void SetOriginalDestinationConnectionId(
1106 const QuicConnectionId& original_destination_connection_id);
QUICHE teamc65d1d12019-03-19 20:58:04 -07001107
dschinazie7c38a52020-05-29 15:25:45 -07001108 // Returns the original destination connection ID used for this connection.
1109 QuicConnectionId GetOriginalDestinationConnectionId();
1110
QUICHE teamcd098022019-03-22 18:49:55 -07001111 // Called when ACK alarm goes off. Sends ACKs of those packet number spaces
1112 // which have expired ACK timeout. Only used when this connection supports
1113 // multiple packet number spaces.
1114 void SendAllPendingAcks();
1115
1116 // Returns true if this connection supports multiple packet number spaces.
1117 bool SupportsMultiplePacketNumberSpaces() const;
1118
fayang21ffb712019-05-16 08:39:26 -07001119 // For logging purpose.
1120 const QuicAckFrame& ack_frame() const;
1121
dschinazi5c030852019-07-11 15:45:53 -07001122 // Install encrypter and decrypter for ENCRYPTION_INITIAL using
1123 // |connection_id| as the first client-sent destination connection ID,
1124 // or the one sent after an IETF Retry.
1125 void InstallInitialCrypters(QuicConnectionId connection_id);
1126
wub256b2d62019-11-25 08:46:55 -08001127 // Called when version is considered negotiated.
1128 void OnSuccessfulVersionNegotiation();
1129
zhongyi2da16be2020-06-17 11:05:23 -07001130 // Called when self migration succeeds after probing.
danzhdb844622021-02-18 10:23:05 -08001131 void OnSuccessfulMigration(bool is_port_change);
zhongyi2da16be2020-06-17 11:05:23 -07001132
dschinazi631f1602020-05-19 10:10:22 -07001133 // Called for QUIC+TLS versions when we send transport parameters.
1134 void OnTransportParametersSent(
1135 const TransportParameters& transport_parameters) const;
1136
1137 // Called for QUIC+TLS versions when we receive transport parameters.
1138 void OnTransportParametersReceived(
1139 const TransportParameters& transport_parameters) const;
1140
renjietang8957c6e2020-08-12 16:08:21 -07001141 // Called for QUIC+TLS versions when we resume cached transport parameters for
1142 // 0-RTT.
1143 void OnTransportParametersResumed(
1144 const TransportParameters& transport_parameters) const;
1145
fayang9adfb532020-06-04 06:58:45 -07001146 // Returns true if ack_alarm_ is set.
1147 bool HasPendingAcks() const;
1148
wubbe634b72020-06-16 08:41:26 -07001149 void OnUserAgentIdKnown() { sent_packet_manager_.OnUserAgentIdKnown(); }
1150
dschinazi6458eb32020-06-23 12:38:41 -07001151 // Enables Legacy Version Encapsulation using |server_name| as SNI.
1152 // Can only be set if this is a client connection.
1153 void EnableLegacyVersionEncapsulation(const std::string& server_name);
1154
danzh8a27a1a2020-09-02 10:26:28 -07001155 bool send_path_response() const { return send_path_response_; }
1156
danzhe6211dc2020-11-19 09:19:00 -08001157 bool use_path_validator() const { return use_path_validator_; }
1158
fayang001c8282020-07-29 12:39:29 -07001159 // If now is close to idle timeout, returns true and sends a connectivity
1160 // probing packet to test the connection for liveness. Otherwise, returns
1161 // false.
1162 bool MaybeTestLiveness();
1163
danzhe6211dc2020-11-19 09:19:00 -08001164 // QuicPathValidator::SendDelegate
danzhe919b002020-10-14 14:44:46 -07001165 // Send PATH_CHALLENGE using the given path information. If |writer| is the
1166 // default writer, PATH_CHALLENGE can be bundled with other frames, and the
1167 // containing packet can be buffered if the writer is blocked. Otherwise,
1168 // PATH_CHALLENGE will be written in an individual packet and it will be
1169 // dropped if write fails. |data_buffer| will be populated with the payload
1170 // for future validation.
danzhe6211dc2020-11-19 09:19:00 -08001171 // Return false if the connection is closed thus the caller will not continue
1172 // the validation, otherwise return true.
1173 bool SendPathChallenge(const QuicPathFrameBuffer& data_buffer,
danzhe919b002020-10-14 14:44:46 -07001174 const QuicSocketAddress& self_address,
1175 const QuicSocketAddress& peer_address,
danzh80374662020-12-21 15:56:17 -08001176 const QuicSocketAddress& effective_peer_address,
danzhe6211dc2020-11-19 09:19:00 -08001177 QuicPacketWriter* writer) override;
1178 // If |writer| is the default writer and |peer_address| is the same as
1179 // peer_address(), return the PTO of this connection. Otherwise, return 3 *
1180 // kInitialRtt.
1181 QuicTime GetRetryTimeout(const QuicSocketAddress& peer_address_to_use,
1182 QuicPacketWriter* writer_to_use) const override;
1183
1184 // Start vaildating the path defined by |context| asynchronously and call the
danzha25ed9d2021-02-19 12:40:26 -08001185 // |result_delegate| after validation finishes. If the connection is
1186 // validating another path, cancel and fail that validation before starting
1187 // this one.
danzhe6211dc2020-11-19 09:19:00 -08001188 void ValidatePath(
1189 std::unique_ptr<QuicPathValidationContext> context,
1190 std::unique_ptr<QuicPathValidator::ResultDelegate> result_delegate);
danzhe919b002020-10-14 14:44:46 -07001191
haoyuewang2d2fdd12020-09-16 11:26:56 -07001192 bool can_receive_ack_frequency_frame() const {
1193 return can_receive_ack_frequency_frame_;
1194 }
1195
1196 void set_can_receive_ack_frequency_frame() {
1197 can_receive_ack_frequency_frame_ = true;
1198 }
1199
wub28ecbba2020-10-16 16:13:47 -07001200 bool is_processing_packet() const { return framer_.is_processing_packet(); }
1201
fayang29ce0bd2020-10-29 08:28:44 -07001202 bool encrypted_control_frames() const { return encrypted_control_frames_; }
1203
fayang5100e292020-10-30 14:37:44 -07001204 bool use_encryption_level_context() const {
1205 return use_encryption_level_context_;
1206 }
1207
danzhe6211dc2020-11-19 09:19:00 -08001208 bool HasPendingPathValidation() const;
1209
renjietang4afe9ca2020-12-15 10:52:08 -08001210 QuicPathValidationContext* GetPathValidationContext() const;
1211
1212 void CancelPathValidation();
1213
haoyuewangdc60baf2021-04-19 14:03:14 -07001214 // Returns true if the migration succeeds, otherwise returns false (e.g., no
1215 // available CIDs, connection disconnected, etc).
1216 bool MigratePath(const QuicSocketAddress& self_address,
danzhe6211dc2020-11-19 09:19:00 -08001217 const QuicSocketAddress& peer_address,
1218 QuicPacketWriter* writer,
1219 bool owns_writer);
1220
haoyuewangdc60baf2021-04-19 14:03:14 -07001221 // Called to clear the alternative_path_ when path validation failed on the
1222 // client side.
1223 void OnPathValidationFailureAtClient();
1224
fayang133b8682020-12-08 05:50:33 -08001225 void SetSourceAddressTokenToSend(absl::string_view token);
1226
wuba9b70f02020-12-09 12:49:27 -08001227 void SendPing() {
1228 SendPingAtLevel(use_encryption_level_context_
1229 ? framer().GetEncryptionLevelToSendApplicationData()
1230 : encryption_level_);
1231 }
1232
haoyuewang2d355fe2021-01-05 16:42:50 -08001233 virtual std::vector<QuicConnectionId> GetActiveServerConnectionIds() const;
1234
danzha25ed9d2021-02-19 12:40:26 -08001235 bool validate_client_address() const { return validate_client_addresses_; }
1236
haoyuewangb9142bc2021-04-13 06:28:22 -07001237 bool support_multiple_connection_ids() const {
1238 return support_multiple_connection_ids_;
1239 }
1240
haoyuewang5c49d3e2021-04-08 07:33:33 -07001241 bool use_connection_id_on_default_path() const {
1242 return use_connection_id_on_default_path_;
1243 }
1244
haoyuewangdc60baf2021-04-19 14:03:14 -07001245 bool connection_migration_use_new_cid() const {
1246 return connection_migration_use_new_cid_;
1247 }
1248
haoyuewange3c51d92021-03-08 07:35:03 -08001249 // Instantiates connection ID manager.
1250 void CreateConnectionIdManager();
1251
fayangc2638cc2021-04-05 14:45:40 -07001252 bool donot_write_mid_packet_processing() const {
1253 return donot_write_mid_packet_processing_;
1254 }
1255
QUICHE teama6ef0a62019-03-07 20:34:33 -05001256 protected:
1257 // Calls cancel() on all the alarms owned by this connection.
1258 void CancelAllAlarms();
1259
1260 // Send a packet to the peer, and takes ownership of the packet if the packet
1261 // cannot be written immediately.
wub8a5dafa2020-05-13 12:30:17 -07001262 virtual void SendOrQueuePacket(SerializedPacket packet);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001263
1264 // Called after a packet is received from a new effective peer address and is
1265 // decrypted. Starts validation of effective peer's address change. Calls
1266 // OnConnectionMigration as soon as the address changed.
1267 void StartEffectivePeerMigration(AddressChangeType type);
1268
1269 // Called when a effective peer address migration is validated.
1270 virtual void OnEffectivePeerMigrationValidated();
1271
1272 // Get the effective peer address from the packet being processed. For proxied
1273 // connections, effective peer address is the address of the endpoint behind
1274 // the proxy. For non-proxied connections, effective peer address is the same
1275 // as peer address.
1276 //
1277 // Notes for implementations in subclasses:
1278 // - If the connection is not proxied, the overridden method should use the
1279 // base implementation:
1280 //
1281 // return QuicConnection::GetEffectivePeerAddressFromCurrentPacket();
1282 //
1283 // - If the connection is proxied, the overridden method may return either of
1284 // the following:
1285 // a) The address of the endpoint behind the proxy. The address is used to
1286 // drive effective peer migration.
1287 // b) An uninitialized address, meaning the effective peer address does not
1288 // change.
1289 virtual QuicSocketAddress GetEffectivePeerAddressFromCurrentPacket() const;
1290
1291 // Selects and updates the version of the protocol being used by selecting a
1292 // version from |available_versions| which is also supported. Returns true if
1293 // such a version exists, false otherwise.
1294 bool SelectMutualVersion(const ParsedQuicVersionVector& available_versions);
1295
1296 // Returns the current per-packet options for the connection.
1297 PerPacketOptions* per_packet_options() { return per_packet_options_; }
1298
1299 AddressChangeType active_effective_peer_migration_type() const {
1300 return active_effective_peer_migration_type_;
1301 }
1302
ianswettdc1e7ab2019-05-03 16:10:44 -07001303 // Sends a connection close packet to the peer and includes an ACK if the ACK
1304 // is not empty, the |error| is not PACKET_WRITE_ERROR, and it fits.
mattm55006b02021-01-14 15:09:54 -08001305 // |ietf_error| may optionally be be used to directly specify the wire
1306 // error code. Otherwise if |ietf_error| is NO_IETF_QUIC_ERROR, the
1307 // QuicErrorCodeToTransportErrorCode mapping of |error| will be used.
QUICHE teama6ef0a62019-03-07 20:34:33 -05001308 virtual void SendConnectionClosePacket(QuicErrorCode error,
mattm55006b02021-01-14 15:09:54 -08001309 QuicIetfTransportErrorCodes ietf_error,
ianswettdc1e7ab2019-05-03 16:10:44 -07001310 const std::string& details);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001311
1312 // Returns true if the packet should be discarded and not sent.
fayang15042962020-07-01 12:14:29 -07001313 virtual bool ShouldDiscardPacket(EncryptionLevel encryption_level);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001314
1315 // Retransmits packets continuously until blocked by the congestion control.
1316 // If there are no packets to retransmit, does not do anything.
1317 void SendProbingRetransmissions();
1318
1319 // Decides whether to send probing retransmissions, and does so if required.
1320 void MaybeSendProbingRetransmissions();
1321
danzha25ed9d2021-02-19 12:40:26 -08001322 // Notify various components(Session etc.) that this connection has been
1323 // migrated.
danzhab0c7a32021-01-19 15:20:17 -08001324 virtual void OnConnectionMigration();
QUICHE teama6ef0a62019-03-07 20:34:33 -05001325
1326 // Return whether the packet being processed is a connectivity probing.
1327 // A packet is a connectivity probing if it is a padded ping packet with self
1328 // and/or peer address changes.
1329 bool IsCurrentPacketConnectivityProbing() const;
1330
1331 // Return true iff the writer is blocked, if blocked, call
1332 // visitor_->OnWriteBlocked() to add the connection into the write blocked
1333 // list.
1334 bool HandleWriteBlocked();
1335
fayang93b4e4d2020-11-25 07:56:47 -08001336 // Whether connection enforces anti-amplification limit.
1337 bool EnforceAntiAmplificationLimit() const;
1338
1339 void AddBytesReceivedBeforeAddressValidation(size_t length) {
danzh37b722e2021-02-17 11:09:08 -08001340 default_path_.bytes_received_before_address_validation += length;
fayang93b4e4d2020-11-25 07:56:47 -08001341 }
1342
QUICHE teama6ef0a62019-03-07 20:34:33 -05001343 private:
1344 friend class test::QuicConnectionPeer;
1345
danzh9cb85b72020-12-30 07:17:09 -08001346 struct QUIC_EXPORT_PRIVATE PendingPathChallenge {
1347 QuicPathFrameBuffer received_path_challenge;
1348 QuicSocketAddress peer_address;
1349 };
1350
danzh37b722e2021-02-17 11:09:08 -08001351 struct QUIC_EXPORT_PRIVATE PathState {
haoyuewang5c49d3e2021-04-08 07:33:33 -07001352 PathState() = default;
1353
danzh37b722e2021-02-17 11:09:08 -08001354 PathState(const QuicSocketAddress& alternative_self_address,
haoyuewang5c49d3e2021-04-08 07:33:33 -07001355 const QuicSocketAddress& alternative_peer_address,
1356 const QuicConnectionId& client_connection_id,
1357 const QuicConnectionId& server_connection_id,
1358 bool stateless_reset_token_received,
1359 StatelessResetToken stateless_reset_token)
danzh9cb85b72020-12-30 07:17:09 -08001360 : self_address(alternative_self_address),
haoyuewang5c49d3e2021-04-08 07:33:33 -07001361 peer_address(alternative_peer_address),
1362 client_connection_id(client_connection_id),
1363 server_connection_id(server_connection_id),
1364 stateless_reset_token(stateless_reset_token),
1365 stateless_reset_token_received(stateless_reset_token_received) {}
danzh9cb85b72020-12-30 07:17:09 -08001366
danzha25ed9d2021-02-19 12:40:26 -08001367 PathState(PathState&& other);
1368
1369 PathState& operator=(PathState&& other);
1370
danzh3b630702021-01-12 14:15:23 -08001371 // Reset all the members.
1372 void Clear();
1373
danzh9cb85b72020-12-30 07:17:09 -08001374 QuicSocketAddress self_address;
1375 // The actual peer address behind the proxy if there is any.
1376 QuicSocketAddress peer_address;
haoyuewang5c49d3e2021-04-08 07:33:33 -07001377 QuicConnectionId client_connection_id;
1378 QuicConnectionId server_connection_id;
1379 StatelessResetToken stateless_reset_token;
1380 bool stateless_reset_token_received = false;
danzh37b722e2021-02-17 11:09:08 -08001381 // True if the peer address has been validated. Address is considered
1382 // validated when 1) an address token of the peer address is received and
1383 // validated, or 2) a HANDSHAKE packet has been successfully processed on
1384 // this path, or 3) a path validation on this path has succeeded.
danzh9cb85b72020-12-30 07:17:09 -08001385 bool validated = false;
1386 // Used by the sever to apply anti-amplification limit after this path
1387 // becomes the default path if |peer_address| hasn't been validated.
danzh046212e2021-01-26 11:44:09 -08001388 QuicByteCount bytes_received_before_address_validation = 0;
1389 QuicByteCount bytes_sent_before_address_validation = 0;
danzha25ed9d2021-02-19 12:40:26 -08001390 // Points to the send algorithm on the old default path while connection is
1391 // validating migrated peer address. Nullptr otherwise.
1392 std::unique_ptr<SendAlgorithmInterface> send_algorithm;
1393 absl::optional<RttStats> rtt_stats;
danzh9cb85b72020-12-30 07:17:09 -08001394 };
1395
renjietang58b3af32020-11-11 15:48:58 -08001396 using QueuedPacketList = std::list<SerializedPacket>;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001397
fayang2ce66082019-10-02 06:29:04 -07001398 // BufferedPacket stores necessary information (encrypted buffer and self/peer
1399 // addresses) of those packets which are serialized but failed to send because
1400 // socket is blocked. From unacked packet map and send algorithm's
1401 // perspective, buffered packets are treated as sent.
dschinazif25169a2019-10-23 08:12:18 -07001402 struct QUIC_EXPORT_PRIVATE BufferedPacket {
fayang2ce66082019-10-02 06:29:04 -07001403 BufferedPacket(const SerializedPacket& packet,
1404 const QuicSocketAddress& self_address,
1405 const QuicSocketAddress& peer_address);
fayang58f71072019-11-05 08:47:02 -08001406 BufferedPacket(char* encrypted_buffer,
1407 QuicPacketLength encrypted_length,
1408 const QuicSocketAddress& self_address,
1409 const QuicSocketAddress& peer_address);
fayang2ce66082019-10-02 06:29:04 -07001410 BufferedPacket(const BufferedPacket& other) = delete;
1411 BufferedPacket(const BufferedPacket&& other) = delete;
1412
1413 ~BufferedPacket();
1414
1415 // encrypted_buffer is owned by buffered packet.
vasilvv9a36d722020-10-02 16:51:38 -07001416 absl::string_view encrypted_buffer;
fayang2ce66082019-10-02 06:29:04 -07001417 // Self and peer addresses when the packet is serialized.
1418 const QuicSocketAddress self_address;
1419 const QuicSocketAddress peer_address;
1420 };
1421
fayang9dcfaca2020-04-24 06:57:14 -07001422 // UndecrytablePacket comprises a undecryptable packet and the its encryption
1423 // level.
1424 struct QUIC_EXPORT_PRIVATE UndecryptablePacket {
1425 UndecryptablePacket(const QuicEncryptedPacket& packet,
1426 EncryptionLevel encryption_level)
fayangbf256ae2020-12-07 12:38:51 -08001427 : packet(packet.Clone()), encryption_level(encryption_level) {}
fayang9dcfaca2020-04-24 06:57:14 -07001428
1429 std::unique_ptr<QuicEncryptedPacket> packet;
fayang9dcfaca2020-04-24 06:57:14 -07001430 EncryptionLevel encryption_level;
1431 };
1432
danzha25ed9d2021-02-19 12:40:26 -08001433 // Handles the reverse path validation result depending on connection state:
1434 // whether the connection is validating a migrated peer address or is
1435 // validating an alternative path.
1436 class ReversePathValidationResultDelegate
1437 : public QuicPathValidator::ResultDelegate {
1438 public:
1439 ReversePathValidationResultDelegate(
1440 QuicConnection* connection,
1441 const QuicSocketAddress& direct_peer_address);
1442
1443 void OnPathValidationSuccess(
1444 std::unique_ptr<QuicPathValidationContext> context) override;
1445
1446 void OnPathValidationFailure(
1447 std::unique_ptr<QuicPathValidationContext> context) override;
1448
1449 private:
1450 QuicConnection* connection_;
1451 QuicSocketAddress original_direct_peer_address_;
1452 };
1453
fayang4b5b4e62021-04-14 06:16:42 -07001454 // A class which sets and clears in_on_retransmission_time_out_ when entering
1455 // and exiting OnRetransmissionTimeout, respectively.
1456 class QUIC_EXPORT_PRIVATE ScopedRetransmissionTimeoutIndicator {
1457 public:
1458 // |connection| must outlive this indicator.
1459 explicit ScopedRetransmissionTimeoutIndicator(QuicConnection* connection);
1460
1461 ~ScopedRetransmissionTimeoutIndicator();
1462
1463 private:
1464 QuicConnection* connection_; // Not owned.
1465 };
1466
haoyuewang5c49d3e2021-04-08 07:33:33 -07001467 QuicConnectionId& ClientConnectionId() {
1468 return use_connection_id_on_default_path_
1469 ? default_path_.client_connection_id
1470 : client_connection_id_;
1471 }
1472 const QuicConnectionId& ClientConnectionId() const {
1473 return use_connection_id_on_default_path_
1474 ? default_path_.client_connection_id
1475 : client_connection_id_;
1476 }
1477 QuicConnectionId& ServerConnectionId() {
1478 return use_connection_id_on_default_path_
1479 ? default_path_.server_connection_id
1480 : server_connection_id_;
1481 }
1482 const QuicConnectionId& ServerConnectionId() const {
1483 return use_connection_id_on_default_path_
1484 ? default_path_.server_connection_id
1485 : server_connection_id_;
1486 }
1487 void SetServerConnectionId(const QuicConnectionId& server_connection_id);
1488
QUICHE teama6ef0a62019-03-07 20:34:33 -05001489 // Notifies the visitor of the close and marks the connection as disconnected.
fkastenholz85f18902019-05-28 12:47:00 -07001490 // Does not send a connection close frame to the peer. It should only be
1491 // called by CloseConnection or OnConnectionCloseFrame, OnPublicResetPacket,
1492 // and OnAuthenticatedIetfStatelessResetPacket.
mattm55006b02021-01-14 15:09:54 -08001493 // |ietf_error| may optionally be be used to directly specify the wire
1494 // error code. Otherwise if |ietf_error| is NO_IETF_QUIC_ERROR, the
1495 // QuicErrorCodeToTransportErrorCode mapping of |error| will be used.
QUICHE teama6ef0a62019-03-07 20:34:33 -05001496 void TearDownLocalConnectionState(QuicErrorCode error,
mattm55006b02021-01-14 15:09:54 -08001497 QuicIetfTransportErrorCodes ietf_error,
vasilvvc48c8712019-03-11 13:38:16 -07001498 const std::string& details,
QUICHE teama6ef0a62019-03-07 20:34:33 -05001499 ConnectionCloseSource source);
fkastenholz488a4622019-08-26 06:24:46 -07001500 void TearDownLocalConnectionState(const QuicConnectionCloseFrame& frame,
1501 ConnectionCloseSource source);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001502
haoyuewange3c51d92021-03-08 07:35:03 -08001503 // Replace server connection ID on the client side from retry packet or
1504 // initial packets with a different source connection ID.
1505 void ReplaceInitialServerConnectionId(
1506 const QuicConnectionId& new_server_connection_id);
1507
haoyuewang5c49d3e2021-04-08 07:33:33 -07001508 // Given the server_connection_id find if there is already a corresponding
1509 // client connection ID used on default/alternative path.
1510 void FindMatchingClientConnectionIdOrToken(
1511 const PathState& default_path,
1512 const PathState& alternative_path,
1513 const QuicConnectionId& server_connection_id,
1514 QuicConnectionId* client_connection_id,
1515 bool* stateless_reset_token_received,
1516 StatelessResetToken* stateless_reset_token) const;
1517
haoyuewangae8f91f2021-04-28 14:58:13 -04001518 // Returns true if header contains valid server connection ID.
1519 bool ValidateServerConnectionId(const QuicPacketHeader& header) const;
1520
haoyuewangdc60baf2021-04-19 14:03:14 -07001521 // Update the connection IDs when client migrates with/without validation.
1522 // Returns false if required connection ID is not available.
1523 bool UpdateConnectionIdsOnClientMigration(
1524 const QuicSocketAddress& self_address,
1525 const QuicSocketAddress& peer_address);
1526
1527 // Retire active peer issued connection IDs after they are no longer used on
1528 // any path.
1529 void RetirePeerIssuedConnectionIdsNoLongerOnPath();
1530
QUICHE teama6ef0a62019-03-07 20:34:33 -05001531 // Writes the given packet to socket, encrypted with packet's
1532 // encryption_level. Returns true on successful write, and false if the writer
1533 // was blocked and the write needs to be tried again. Notifies the
1534 // SentPacketManager when the write is successful and sets
1535 // retransmittable frames to nullptr.
1536 // Saves the connection close packet for later transmission, even if the
1537 // writer is write blocked.
1538 bool WritePacket(SerializedPacket* packet);
1539
mattmd0744852020-10-16 14:42:01 -07001540 // Enforce AEAD Confidentiality limits by iniating key update or closing
1541 // connection if too many packets have been encrypted with the current key.
1542 // Returns true if the connection was closed. Should not be called for
1543 // termination packets.
1544 bool MaybeHandleAeadConfidentialityLimits(const SerializedPacket& packet);
1545
QUICHE teama6ef0a62019-03-07 20:34:33 -05001546 // Flush packets buffered in the writer, if any.
1547 void FlushPackets();
1548
QUICHE teama6ef0a62019-03-07 20:34:33 -05001549 // Make sure a stop waiting we got from our peer is sane.
1550 // Returns nullptr if the frame is valid or an error string if it was invalid.
1551 const char* ValidateStopWaitingFrame(
1552 const QuicStopWaitingFrame& stop_waiting);
1553
1554 // Sends a version negotiation packet to the peer.
dschinazi48ac9192019-07-31 00:07:26 -07001555 void SendVersionNegotiationPacket(bool ietf_quic, bool has_length_prefix);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001556
1557 // Clears any accumulated frames from the last received packet.
1558 void ClearLastFrames();
1559
1560 // Deletes and clears any queued packets.
1561 void ClearQueuedPackets();
1562
1563 // Closes the connection if the sent packet manager is tracking too many
1564 // outstanding packets.
1565 void CloseIfTooManyOutstandingSentPackets();
1566
1567 // Writes as many queued packets as possible. The connection must not be
1568 // blocked when this is called.
1569 void WriteQueuedPackets();
1570
QUICHE teama6ef0a62019-03-07 20:34:33 -05001571 // Queues |packet| in the hopes that it can be decrypted in the
1572 // future, when a new key is installed.
fayang9dcfaca2020-04-24 06:57:14 -07001573 void QueueUndecryptablePacket(const QuicEncryptedPacket& packet,
1574 EncryptionLevel decryption_level);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001575
1576 // Sends any packets which are a response to the last packet, including both
1577 // acks and pending writes if an ack opened the congestion window.
1578 void MaybeSendInResponseToPacket();
1579
QUICHE teama6ef0a62019-03-07 20:34:33 -05001580 // Gets the least unacked packet number, which is the next packet number to be
1581 // sent if there are no outstanding packets.
1582 QuicPacketNumber GetLeastUnacked() const;
1583
QUICHE teama6ef0a62019-03-07 20:34:33 -05001584 // Sets the ping alarm to the appropriate value, if any.
1585 void SetPingAlarm();
1586
1587 // Sets the retransmission alarm based on SentPacketManager.
1588 void SetRetransmissionAlarm();
1589
QUICHE teama6ef0a62019-03-07 20:34:33 -05001590 // Sets the MTU discovery alarm if necessary.
1591 // |sent_packet_number| is the recently sent packet number.
1592 void MaybeSetMtuAlarm(QuicPacketNumber sent_packet_number);
1593
QUICHE teama6ef0a62019-03-07 20:34:33 -05001594 HasRetransmittableData IsRetransmittable(const SerializedPacket& packet);
fayang8bff33c2020-08-06 07:37:22 -07001595 bool IsTerminationPacket(const SerializedPacket& packet,
1596 QuicErrorCode* error_code);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001597
1598 // Set the size of the packet we are targeting while doing path MTU discovery.
1599 void SetMtuDiscoveryTarget(QuicByteCount target);
1600
1601 // Returns |suggested_max_packet_size| clamped to any limits set by the
1602 // underlying writer, connection, or protocol.
1603 QuicByteCount GetLimitedMaxPacketSize(
1604 QuicByteCount suggested_max_packet_size);
1605
1606 // Do any work which logically would be done in OnPacket but can not be
1607 // safely done until the packet is validated. Returns true if packet can be
1608 // handled, false otherwise.
1609 bool ProcessValidatedPacket(const QuicPacketHeader& header);
1610
QUICHE teamd791e2c2019-03-15 10:28:21 -07001611 // Returns true if received |packet_number| can be processed. Please note,
1612 // this is called after packet got decrypted successfully.
1613 bool ValidateReceivedPacketNumber(QuicPacketNumber packet_number);
1614
QUICHE teama6ef0a62019-03-07 20:34:33 -05001615 // Consider receiving crypto frame on non crypto stream as memory corruption.
1616 bool MaybeConsiderAsMemoryCorruption(const QuicStreamFrame& frame);
1617
1618 // Check if the connection has no outstanding data to send and notify
1619 // congestion controller if it is the case.
1620 void CheckIfApplicationLimited();
1621
1622 // Sets |current_packet_content_| to |type| if applicable. And
1623 // starts effective peer migration if current packet is confirmed not a
1624 // connectivity probe and |current_effective_peer_migration_type_| indicates
1625 // effective peer address change.
renjietang7f1d9e12021-01-22 19:10:57 -08001626 // Returns true if connection is still alive.
1627 ABSL_MUST_USE_RESULT bool UpdatePacketContent(QuicFrameType type);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001628
QUICHE teama6ef0a62019-03-07 20:34:33 -05001629 // Called when last received ack frame has been processed.
1630 // |send_stop_waiting| indicates whether a stop waiting needs to be sent.
1631 // |acked_new_packet| is true if a previously-unacked packet was acked.
1632 void PostProcessAfterAckFrame(bool send_stop_waiting, bool acked_new_packet);
1633
QUICHE teama6ef0a62019-03-07 20:34:33 -05001634 // Updates the release time into the future.
1635 void UpdateReleaseTimeIntoFuture();
1636
1637 // Sends generic path probe packet to the peer. If we are not IETF QUIC, will
danzh8a27a1a2020-09-02 10:26:28 -07001638 // always send a padded ping, regardless of whether this is a request or not.
1639 // TODO(danzh): remove |is_response| after deprecating
1640 // --gfe2_reloadable_flag_quic_send_path_response.
QUICHE teama6ef0a62019-03-07 20:34:33 -05001641 bool SendGenericPathProbePacket(QuicPacketWriter* probing_writer,
1642 const QuicSocketAddress& peer_address,
1643 bool is_response);
1644
1645 // Called when an ACK is about to send. Resets ACK related internal states,
1646 // e.g., cancels ack_alarm_, resets
1647 // num_retransmittable_packets_received_since_last_ack_sent_ etc.
1648 void ResetAckStates();
1649
ianswett6083a102020-02-09 12:04:04 -08001650 // Returns true if the ACK frame should be bundled with ACK-eliciting frame.
1651 bool ShouldBundleRetransmittableFrameWithAck() const;
1652
fayanga4b37b22019-06-18 13:37:47 -07001653 void PopulateStopWaitingFrame(QuicStopWaitingFrame* stop_waiting);
1654
QUICHE teamcd098022019-03-22 18:49:55 -07001655 // Enables multiple packet number spaces support based on handshake protocol
1656 // and flags.
1657 void MaybeEnableMultiplePacketNumberSpacesSupport();
1658
fayang9f430a52020-05-08 07:28:33 -07001659 // Called to update ACK timeout when an retransmittable frame has been parsed.
1660 void MaybeUpdateAckTimeout();
1661
fayangfe963c52020-07-16 06:56:09 -07001662 // Tries to fill coalesced packet with data of higher packet space.
1663 void MaybeCoalescePacketOfHigherSpace();
1664
fayang58f71072019-11-05 08:47:02 -08001665 // Serialize and send coalesced_packet. Returns false if serialization fails
1666 // or the write causes errors, otherwise, returns true.
1667 bool FlushCoalescedPacket();
fayang2ce66082019-10-02 06:29:04 -07001668
QUICHE teama6ef0a62019-03-07 20:34:33 -05001669 // Returns the encryption level the connection close packet should be sent at,
1670 // which is the highest encryption level that peer can guarantee to process.
1671 EncryptionLevel GetConnectionCloseEncryptionLevel() const;
1672
QUICHE team76e1c622019-03-19 14:36:39 -07001673 // Called after an ACK frame is successfully processed to update largest
1674 // received packet number which contains an ACK frame.
1675 void SetLargestReceivedPacketWithAck(QuicPacketNumber new_value);
1676
fayang656cbb52020-06-09 13:29:35 -07001677 // Called when new packets have been acknowledged or old keys have been
1678 // discarded.
1679 void OnForwardProgressMade();
1680
QUICHE team76e1c622019-03-19 14:36:39 -07001681 // Returns largest received packet number which contains an ACK frame.
1682 QuicPacketNumber GetLargestReceivedPacketWithAck() const;
1683
1684 // Returns the largest packet number that has been sent.
1685 QuicPacketNumber GetLargestSentPacket() const;
1686
1687 // Returns the largest sent packet number that has been ACKed by peer.
1688 QuicPacketNumber GetLargestAckedPacket() const;
1689
QUICHE teamc65d1d12019-03-19 20:58:04 -07001690 // Whether incoming_connection_ids_ contains connection_id.
haoyuewangae8f91f2021-04-28 14:58:13 -04001691 bool HasIncomingConnectionId(QuicConnectionId connection_id) const;
QUICHE teamc65d1d12019-03-19 20:58:04 -07001692
fayang5f135052019-08-22 17:59:40 -07001693 // Whether connection is limited by amplification factor.
1694 bool LimitedByAmplificationFactor() const;
1695
wubed245d22020-05-07 10:46:00 -07001696 // Called before sending a packet to get packet send time and to set the
1697 // release time delay in |per_packet_options_|. Return the time when the
1698 // packet is scheduled to be released(a.k.a send time), which is NOW + delay.
1699 // Returns Now() and does not update release time delay if
1700 // |supports_release_time_| is false.
1701 QuicTime CalculatePacketSentTime();
1702
wub8add68a2020-07-27 12:07:38 -07001703 // If we have a previously validate MTU value, e.g. due to a write error,
1704 // revert to it and disable MTU discovery.
1705 // Return true iff we reverted to a previously validate MTU.
1706 bool MaybeRevertToPreviousMtu();
1707
1708 QuicTime GetPathMtuReductionDeadline() const;
wub748e20b2020-03-20 14:33:59 -07001709
fayangb59c6f12020-03-23 15:06:14 -07001710 // Returns path degrading deadline. QuicTime::Zero() means no path degrading
1711 // detection is needed.
1712 QuicTime GetPathDegradingDeadline() const;
1713
1714 // Returns true if path degrading should be detected.
1715 bool ShouldDetectPathDegrading() const;
1716
1717 // Returns network blackhole deadline. QuicTime::Zero() means no blackhole
1718 // detection is needed.
1719 QuicTime GetNetworkBlackholeDeadline() const;
1720
1721 // Returns true if network blackhole should be detected.
1722 bool ShouldDetectBlackhole() const;
1723
fayang1d49cfb2020-10-22 08:19:46 -07001724 // Returns retransmission deadline.
1725 QuicTime GetRetransmissionDeadline() const;
1726
dschinazie7c38a52020-05-29 15:25:45 -07001727 // Validate connection IDs used during the handshake. Closes the connection
1728 // on validation failure.
1729 bool ValidateConfigConnectionIds(const QuicConfig& config);
dschinazie7c38a52020-05-29 15:25:45 -07001730
fayang5c2c7b52020-07-09 13:47:16 -04001731 // Called when ACK alarm goes off. Try to bundle crypto data with ACKs.
1732 void MaybeBundleCryptoDataWithAcks();
fayang7d4b0172020-06-18 14:05:45 -07001733
fayang750b54f2020-06-18 06:26:54 -07001734 // Returns true if an undecryptable packet of |decryption_level| should be
1735 // buffered (such that connection can try to decrypt it later).
1736 bool ShouldEnqueueUnDecryptablePacket(EncryptionLevel decryption_level,
1737 bool has_decryption_key) const;
1738
fayang06574dc2020-06-18 13:58:09 -07001739 // Returns string which contains undecryptable packets information.
1740 std::string UndecryptablePacketsInfo() const;
1741
dschinazi6458eb32020-06-23 12:38:41 -07001742 // Sets the max packet length on the packet creator if needed.
1743 void MaybeUpdatePacketCreatorMaxPacketLengthAndPadding();
1744
1745 // Sets internal state to enable or disable Legacy Version Encapsulation.
1746 void MaybeActivateLegacyVersionEncapsulation();
1747 void MaybeDisactivateLegacyVersionEncapsulation();
1748
danzhb7abebb2020-08-04 11:06:17 -07001749 // For Google Quic, if the current packet is connectivity probing packet, call
1750 // session OnPacketReceived() which eventually sends connectivity probing
1751 // response on server side. And no-op on client side. And for both Google Quic
1752 // and IETF Quic, start migration if the current packet is a non-probing
1753 // packet.
1754 // TODO(danzh) rename to MaybeRespondToPeerMigration() when Google Quic is
1755 // deprecated.
1756 void MaybeRespondToConnectivityProbingOrMigration();
1757
danzh623f6ef2020-08-25 16:44:37 -07001758 // Called in IETF QUIC. Start peer migration if a non-probing frame is
1759 // received and the current packet number is largest received so far.
danzh9cb85b72020-12-30 07:17:09 -08001760 void MaybeStartIetfPeerMigration();
danzh623f6ef2020-08-25 16:44:37 -07001761
danzh8a27a1a2020-09-02 10:26:28 -07001762 // Send PATH_RESPONSE to the given peer address.
1763 bool SendPathResponse(const QuicPathFrameBuffer& data_buffer,
1764 QuicSocketAddress peer_address_to_send);
1765
1766 // Update both connection's and packet creator's peer address.
1767 void UpdatePeerAddress(QuicSocketAddress peer_address);
1768
fayangec14d2b2020-10-02 12:00:05 -07001769 // Send PING at encryption level.
1770 void SendPingAtLevel(EncryptionLevel level);
1771
danzhe919b002020-10-14 14:44:46 -07001772 // Write the given packet with |self_address| and |peer_address| using
1773 // |writer|.
1774 bool WritePacketUsingWriter(std::unique_ptr<SerializedPacket> packet,
1775 QuicPacketWriter* writer,
1776 const QuicSocketAddress& self_address,
1777 const QuicSocketAddress& peer_address,
1778 bool measure_rtt);
danzh9cb85b72020-12-30 07:17:09 -08001779
danzha4b519c2021-02-05 12:10:55 -08001780 // Increment bytes sent/received on the alternative path if the current packet
1781 // is sent/received on that path.
danzh9cb85b72020-12-30 07:17:09 -08001782 void MaybeUpdateBytesSentToAlternativeAddress(
1783 const QuicSocketAddress& peer_address,
1784 QuicByteCount sent_packet_size);
1785 void MaybeUpdateBytesReceivedFromAlternativeAddress(
1786 QuicByteCount received_packet_size);
1787
danzha25ed9d2021-02-19 12:40:26 -08001788 // TODO(danzh) pass in PathState of the incoming packet or the packet sent
1789 // once PathState is used in packet creator. Return true if the given self
1790 // address and peer address is the same as the self address and peer address
1791 // of the default path.
danzh9cb85b72020-12-30 07:17:09 -08001792 bool IsDefaultPath(const QuicSocketAddress& self_address,
1793 const QuicSocketAddress& peer_address) const;
1794
danzha25ed9d2021-02-19 12:40:26 -08001795 // Return true if the |self_address| and |peer_address| is the same as the
danzha4b519c2021-02-05 12:10:55 -08001796 // self address and peer address of the alternative path.
1797 bool IsAlternativePath(const QuicSocketAddress& self_address,
1798 const QuicSocketAddress& peer_address) const;
danzh9cb85b72020-12-30 07:17:09 -08001799
danzha25ed9d2021-02-19 12:40:26 -08001800 // Restore connection default path and congestion control state to the last
1801 // validated path and its state. Called after fail to validate peer address
1802 // upon detecting a peer migration.
1803 void RestoreToLastValidatedPath(
1804 QuicSocketAddress original_direct_peer_address);
1805
1806 // Return true if the current incoming packet is from a peer address that is
1807 // validated.
1808 bool IsReceivedPeerAddressValidated() const;
1809
1810 // Called after receiving PATH_CHALLENGE. Update packet content and
1811 // alternative path state if the current packet is from a non-default path.
1812 // Return true if framer should continue processing the packet.
1813 bool OnPathChallengeFrameInternal(const QuicPathChallengeFrame& frame);
1814
haoyuewange3c51d92021-03-08 07:35:03 -08001815 virtual std::unique_ptr<QuicSelfIssuedConnectionIdManager>
1816 MakeSelfIssuedConnectionIdManager();
1817
danzha1c08152021-03-15 10:29:40 -07001818 // Called on peer IP change or restoring to previous address to reset
1819 // congestion window, RTT stats, retransmission timer, etc. Only used in IETF
1820 // QUIC.
1821 std::unique_ptr<SendAlgorithmInterface> OnPeerIpAddressChanged();
1822
haoyuewange3c51d92021-03-08 07:35:03 -08001823 // Process NewConnectionIdFrame either sent from peer or synsthesized from
1824 // preferred_address transport parameter.
1825 bool OnNewConnectionIdFrameInner(const QuicNewConnectionIdFrame& frame);
1826
haoyuewangb9142bc2021-04-13 06:28:22 -07001827 // Called to patch missing client connection ID on default/alternative paths
1828 // when a new client connection ID is received.
1829 void OnClientConnectionIdAvailable();
1830
QUICHE teama6ef0a62019-03-07 20:34:33 -05001831 QuicFramer framer_;
1832
1833 // Contents received in the current packet, especially used to identify
1834 // whether the current packet is a padded PING packet.
1835 PacketContent current_packet_content_;
1836 // Set to true as soon as the packet currently being processed has been
1837 // detected as a connectivity probing.
1838 // Always false outside the context of ProcessUdpPacket().
1839 bool is_current_packet_connectivity_probing_;
1840
danzh8a27a1a2020-09-02 10:26:28 -07001841 bool has_path_challenge_in_current_packet_;
1842
QUICHE teama6ef0a62019-03-07 20:34:33 -05001843 // Caches the current effective peer migration type if a effective peer
1844 // migration might be initiated. As soon as the current packet is confirmed
1845 // not a connectivity probe, effective peer migration will start.
1846 AddressChangeType current_effective_peer_migration_type_;
1847 QuicConnectionHelperInterface* helper_; // Not owned.
1848 QuicAlarmFactory* alarm_factory_; // Not owned.
1849 PerPacketOptions* per_packet_options_; // Not owned.
1850 QuicPacketWriter* writer_; // Owned or not depending on |owns_writer_|.
1851 bool owns_writer_;
1852 // Encryption level for new packets. Should only be changed via
1853 // SetDefaultEncryptionLevel().
1854 EncryptionLevel encryption_level_;
1855 const QuicClock* clock_;
1856 QuicRandom* random_generator_;
1857
dschinazi7b9278c2019-05-20 07:36:21 -07001858 QuicConnectionId server_connection_id_;
dschinazi346b7ce2019-06-05 01:38:18 -07001859 QuicConnectionId client_connection_id_;
1860 // On the server, the connection ID is set when receiving the first packet.
1861 // This variable ensures we only set it this way once.
1862 bool client_connection_id_is_set_;
dschinazif31282b2021-03-03 11:33:48 -08001863
1864 // Whether we've already replaced our server connection ID due to receiving an
1865 // INITIAL packet with a different source connection ID. Only used on client.
1866 bool server_connection_id_replaced_by_initial_ = false;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001867 // Address on the last successfully processed packet received from the
1868 // direct peer.
QUICHE teama6ef0a62019-03-07 20:34:33 -05001869
danzh8a27a1a2020-09-02 10:26:28 -07001870 // Other than initialization, do not modify it directly, use
1871 // UpdatePeerAddress() instead.
QUICHE teama6ef0a62019-03-07 20:34:33 -05001872 QuicSocketAddress direct_peer_address_;
danzh37b722e2021-02-17 11:09:08 -08001873 // The default path on which the endpoint sends non-probing packets.
1874 // The send algorithm and RTT stats of this path are stored in
1875 // |sent_packet_manager_| instead of in this object.
1876 PathState default_path_;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001877
1878 // Records change type when the effective peer initiates migration to a new
1879 // address. Reset to NO_CHANGE after effective peer migration is validated.
1880 AddressChangeType active_effective_peer_migration_type_;
1881
1882 // Records highest sent packet number when effective peer migration is
1883 // started.
1884 QuicPacketNumber highest_packet_sent_before_effective_peer_migration_;
1885
mattm072a7e32020-10-09 16:16:56 -07001886 // True if Key Update is supported on this connection.
1887 bool support_key_update_for_connection_;
1888
1889 // Tracks the lowest packet sent in the current key phase. Will be
1890 // uninitialized before the first one-RTT packet has been sent or after a
1891 // key update but before the first packet has been sent.
1892 QuicPacketNumber lowest_packet_sent_in_current_key_phase_;
1893
QUICHE teama6ef0a62019-03-07 20:34:33 -05001894 // True if the last packet has gotten far enough in the framer to be
1895 // decrypted.
1896 bool last_packet_decrypted_;
1897 QuicByteCount last_size_; // Size of the last received packet.
1898 // TODO(rch): remove this when b/27221014 is fixed.
1899 const char* current_packet_data_; // UDP payload of packet currently being
1900 // parsed or nullptr.
1901 EncryptionLevel last_decrypted_packet_level_;
1902 QuicPacketHeader last_header_;
1903 bool should_last_packet_instigate_acks_;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001904
1905 // Track some peer state so we can do less bookkeeping
1906 // Largest sequence sent by the peer which had an ack frame (latest ack info).
QUICHE team76e1c622019-03-19 14:36:39 -07001907 // Do not read or write directly, use GetLargestReceivedPacketWithAck() and
1908 // SetLargestReceivedPacketWithAck() instead.
QUICHE teama6ef0a62019-03-07 20:34:33 -05001909 QuicPacketNumber largest_seen_packet_with_ack_;
QUICHE teamcd098022019-03-22 18:49:55 -07001910 // Largest packet number sent by the peer which had an ACK frame per packet
1911 // number space. Only used when this connection supports multiple packet
1912 // number spaces.
1913 QuicPacketNumber largest_seen_packets_with_ack_[NUM_PACKET_NUMBER_SPACES];
QUICHE teama6ef0a62019-03-07 20:34:33 -05001914
1915 // Largest packet number sent by the peer which had a stop waiting frame.
1916 QuicPacketNumber largest_seen_packet_with_stop_waiting_;
1917
1918 // Collection of packets which were received before encryption was
1919 // established, but which could not be decrypted. We buffer these on
1920 // the assumption that they could not be processed because they were
1921 // sent with the INITIAL encryption and the CHLO message was lost.
fayanga5c33832020-09-15 09:16:48 -07001922 std::deque<UndecryptablePacket> undecryptable_packets_;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001923
1924 // Collection of coalesced packets which were received while processing
1925 // the current packet.
bnc08fc2ae2021-04-27 14:57:51 -07001926 quiche::QuicheCircularDeque<std::unique_ptr<QuicEncryptedPacket>>
wuba750aab2020-02-10 06:43:15 -08001927 received_coalesced_packets_;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001928
1929 // Maximum number of undecryptable packets the connection will store.
1930 size_t max_undecryptable_packets_;
1931
1932 // Maximum number of tracked packets.
1933 QuicPacketCount max_tracked_packets_;
1934
QUICHE teama6ef0a62019-03-07 20:34:33 -05001935 // Contains the connection close packets if the connection has been closed.
1936 std::unique_ptr<std::vector<std::unique_ptr<QuicEncryptedPacket>>>
1937 termination_packets_;
1938
1939 // Determines whether or not a connection close packet is sent to the peer
dschinazi9a6194e2020-04-30 16:21:09 -07001940 // after idle timeout due to lack of network activity. During the handshake,
1941 // a connection close packet is sent, but not after.
QUICHE teama6ef0a62019-03-07 20:34:33 -05001942 ConnectionCloseBehavior idle_timeout_connection_close_behavior_;
1943
fayangddd3e9d2020-06-03 11:00:19 -07001944 // When > 0, close the QUIC connection after this number of RTOs.
1945 size_t num_rtos_for_blackhole_detection_;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001946
wub5ea41ef2020-10-16 13:31:19 -07001947 // Statistics for this session.
1948 QuicConnectionStats stats_;
1949
QUICHE teamb23daa72019-03-21 08:37:48 -07001950 UberReceivedPacketManager uber_received_packet_manager_;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001951
QUICHE teama6ef0a62019-03-07 20:34:33 -05001952 // Indicates how many consecutive times an ack has arrived which indicates
1953 // the peer needs to stop waiting for some packets.
dschinazi5c1d7d82020-07-29 16:42:50 -07001954 // TODO(fayang): remove this when deprecating Q043.
QUICHE teama6ef0a62019-03-07 20:34:33 -05001955 int stop_waiting_count_;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001956
1957 // Indicates the retransmission alarm needs to be set.
1958 bool pending_retransmission_alarm_;
1959
1960 // If true, defer sending data in response to received packets to the
1961 // SendAlarm.
1962 bool defer_send_in_response_to_packets_;
1963
1964 // The timeout for PING.
1965 QuicTime::Delta ping_timeout_;
1966
zhongyi79ace162019-10-21 15:57:09 -07001967 // Initial timeout for how long the wire can have no retransmittable packets.
1968 QuicTime::Delta initial_retransmittable_on_wire_timeout_;
1969
1970 // Indicates how many retransmittable-on-wire pings have been emitted without
1971 // receiving any new data in between.
1972 int consecutive_retransmittable_on_wire_ping_count_;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001973
dschinazi4933ced2020-10-20 09:51:12 -07001974 // Indicates how many retransmittable-on-wire pings have been emitted.
1975 int retransmittable_on_wire_ping_count_;
1976
QUICHE teama6ef0a62019-03-07 20:34:33 -05001977 // Arena to store class implementations within the QuicConnection.
1978 QuicConnectionArena arena_;
1979
1980 // An alarm that fires when an ACK should be sent to the peer.
1981 QuicArenaScopedPtr<QuicAlarm> ack_alarm_;
1982 // An alarm that fires when a packet needs to be retransmitted.
1983 QuicArenaScopedPtr<QuicAlarm> retransmission_alarm_;
1984 // An alarm that is scheduled when the SentPacketManager requires a delay
1985 // before sending packets and fires when the packet may be sent.
1986 QuicArenaScopedPtr<QuicAlarm> send_alarm_;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001987 // An alarm that fires when a ping should be sent.
1988 QuicArenaScopedPtr<QuicAlarm> ping_alarm_;
1989 // An alarm that fires when an MTU probe should be sent.
1990 QuicArenaScopedPtr<QuicAlarm> mtu_discovery_alarm_;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001991 // An alarm that fires to process undecryptable packets when new decyrption
1992 // keys are available.
1993 QuicArenaScopedPtr<QuicAlarm> process_undecryptable_packets_alarm_;
mattm072a7e32020-10-09 16:16:56 -07001994 // An alarm that fires to discard keys for the previous key phase some time
1995 // after a key update has completed.
1996 QuicArenaScopedPtr<QuicAlarm> discard_previous_one_rtt_keys_alarm_;
mattmad5eb5d2020-12-03 16:12:15 -08001997 // An alarm that fires to discard 0-RTT decryption keys some time after the
1998 // first 1-RTT packet has been decrypted. Only used on server connections with
1999 // TLS handshaker.
2000 QuicArenaScopedPtr<QuicAlarm> discard_zero_rtt_decryption_keys_alarm_;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002001 // Neither visitor is owned by this class.
2002 QuicConnectionVisitorInterface* visitor_;
2003 QuicConnectionDebugVisitor* debug_visitor_;
2004
fayang4245c212019-11-05 13:33:46 -08002005 QuicPacketCreator packet_creator_;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002006
QUICHE teama6ef0a62019-03-07 20:34:33 -05002007 // The time that a packet is received for this connection. Initialized to
2008 // connection creation time.
fayange9304002020-05-07 11:57:48 -07002009 // This does not indicate the packet was processed.
QUICHE teama6ef0a62019-03-07 20:34:33 -05002010 QuicTime time_of_last_received_packet_;
2011
QUICHE teama6ef0a62019-03-07 20:34:33 -05002012 // Sent packet manager which tracks the status of packets sent by this
2013 // connection and contains the send and receive algorithms to determine when
2014 // to send packets.
2015 QuicSentPacketManager sent_packet_manager_;
2016
fayang8aba1ff2019-06-21 12:00:54 -07002017 // Indicates whether connection version has been negotiated.
wub256b2d62019-11-25 08:46:55 -08002018 // Always true for server connections.
fayang8aba1ff2019-06-21 12:00:54 -07002019 bool version_negotiated_;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002020
2021 // Tracks if the connection was created by the server or the client.
2022 Perspective perspective_;
2023
2024 // True by default. False if we've received or sent an explicit connection
2025 // close.
2026 bool connected_;
2027
2028 // Destination address of the last received packet.
2029 QuicSocketAddress last_packet_destination_address_;
2030
2031 // Source address of the last received packet.
2032 QuicSocketAddress last_packet_source_address_;
2033
haoyuewang1063e452021-04-28 10:44:33 -07002034 // Destination connection ID of the last received packet. If this ID is the
2035 // original server connection ID chosen by client and server replaces it with
2036 // a different ID, last_packet_destination_connection_id_ is set to the
2037 // replacement connection ID on the server side.
haoyuewang5c49d3e2021-04-08 07:33:33 -07002038 QuicConnectionId last_packet_destination_connection_id_;
2039
QUICHE teama6ef0a62019-03-07 20:34:33 -05002040 // Set to false if the connection should not send truncated connection IDs to
2041 // the peer, even if the peer supports it.
2042 bool can_truncate_connection_ids_;
2043
2044 // If non-empty this contains the set of versions received in a
2045 // version negotiation packet.
2046 ParsedQuicVersionVector server_supported_versions_;
2047
QUICHE teama6ef0a62019-03-07 20:34:33 -05002048 // The number of MTU probes already sent.
2049 size_t mtu_probe_count_;
2050
wubecb643f2020-03-19 08:58:46 -07002051 // The value of |long_term_mtu_| prior to the last successful MTU increase.
2052 // 0 means either
2053 // - MTU discovery has never been enabled, or
2054 // - MTU discovery has been enabled, but the connection got a packet write
2055 // error with a new (successfully probed) MTU, so it reverted
wub748e20b2020-03-20 14:33:59 -07002056 // |long_term_mtu_| to the value before the last increase.
wubecb643f2020-03-19 08:58:46 -07002057 QuicPacketLength previous_validated_mtu_;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002058 // The value of the MTU regularly used by the connection. This is different
2059 // from the value returned by max_packet_size(), as max_packet_size() returns
2060 // the value of the MTU as currently used by the serializer, so if
2061 // serialization of an MTU probe is in progress, those two values will be
2062 // different.
2063 QuicByteCount long_term_mtu_;
2064
dschinazi4ad1f462020-01-16 11:56:52 -08002065 // The maximum UDP payload size that our peer has advertised support for.
2066 // Defaults to kDefaultMaxPacketSizeTransportParam until received from peer.
2067 QuicByteCount peer_max_packet_size_;
2068
QUICHE teama6ef0a62019-03-07 20:34:33 -05002069 // The size of the largest packet received from peer.
2070 QuicByteCount largest_received_packet_size_;
2071
2072 // Indicates whether a write error is encountered currently. This is used to
2073 // avoid infinite write errors.
2074 bool write_error_occurred_;
2075
2076 // Indicates not to send or process stop waiting frames.
2077 bool no_stop_waiting_frames_;
2078
2079 // Consecutive number of sent packets which have no retransmittable frames.
2080 size_t consecutive_num_packets_with_no_retransmittable_frames_;
2081
2082 // After this many packets sent without retransmittable frames, an artificial
2083 // retransmittable frame(a WINDOW_UPDATE) will be created to solicit an ack
2084 // from the peer. Default to kMaxConsecutiveNonRetransmittablePackets.
2085 size_t max_consecutive_num_packets_with_no_retransmittable_frames_;
2086
ianswett6083a102020-02-09 12:04:04 -08002087 // If true, bundle an ack-eliciting frame with an ACK if the PTO or RTO alarm
2088 // have previously fired.
2089 bool bundle_retransmittable_with_pto_ack_;
2090
QUICHE teama6ef0a62019-03-07 20:34:33 -05002091 // If true, the connection will fill up the pipe with extra data whenever the
2092 // congestion controller needs it in order to make a bandwidth estimate. This
2093 // is useful if the application pesistently underutilizes the link, but still
2094 // relies on having a reasonable bandwidth estimate from the connection, e.g.
2095 // for real time applications.
2096 bool fill_up_link_during_probing_;
2097
2098 // If true, the probing retransmission will not be started again. This is
2099 // used to safeguard against an accidental tail recursion in probing
2100 // retransmission code.
2101 bool probing_retransmission_pending_;
2102
2103 // Indicates whether a stateless reset token has been received from peer.
2104 bool stateless_reset_token_received_;
2105 // Stores received stateless reset token from peer. Used to verify whether a
2106 // packet is a stateless reset packet.
bnc1ccd0bc2021-04-07 10:20:17 -07002107 StatelessResetToken received_stateless_reset_token_;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002108
2109 // Id of latest sent control frame. 0 if no control frame has been sent.
2110 QuicControlFrameId last_control_frame_id_;
2111
2112 // True if the peer is unreachable on the current path.
2113 bool is_path_degrading_;
2114
2115 // True if an ack frame is being processed.
2116 bool processing_ack_frame_;
2117
2118 // True if the writer supports release timestamp.
2119 bool supports_release_time_;
2120
haoyuewange3c51d92021-03-08 07:35:03 -08002121 std::unique_ptr<QuicPeerIssuedConnectionIdManager> peer_issued_cid_manager_;
2122 std::unique_ptr<QuicSelfIssuedConnectionIdManager> self_issued_cid_manager_;
2123
QUICHE teama6ef0a62019-03-07 20:34:33 -05002124 // Time this connection can release packets into the future.
2125 QuicTime::Delta release_time_into_future_;
2126
fkastenholz305e1732019-06-18 05:01:22 -07002127 // Payload of most recently transmitted IETF QUIC connectivity
QUICHE teama6ef0a62019-03-07 20:34:33 -05002128 // probe packet (the PATH_CHALLENGE payload). This implementation transmits
2129 // only one PATH_CHALLENGE per connectivity probe, so only one
2130 // QuicPathFrameBuffer is needed.
2131 std::unique_ptr<QuicPathFrameBuffer> transmitted_connectivity_probe_payload_;
2132
2133 // Payloads that were received in the most recent probe. This needs to be a
2134 // Deque because the peer might no be using this implementation, and others
2135 // might send a packet with more than one PATH_CHALLENGE, so all need to be
2136 // saved and responded to.
danzh8a27a1a2020-09-02 10:26:28 -07002137 // TODO(danzh) deprecate this field when deprecating
2138 // --quic_send_path_response.
bnc08fc2ae2021-04-27 14:57:51 -07002139 quiche::QuicheCircularDeque<QuicPathFrameBuffer>
2140 received_path_challenge_payloads_;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002141
danzh8a27a1a2020-09-02 10:26:28 -07002142 // Buffer outstanding PATH_CHALLENGEs if socket write is blocked, future
2143 // OnCanWrite will attempt to respond with PATH_RESPONSEs using the retained
2144 // payload and peer addresses.
fayanga1ffa162021-04-13 05:43:02 -07002145 // TODO(fayang): remove this when deprecating quic_drop_unsent_path_response.
bnc08fc2ae2021-04-27 14:57:51 -07002146 quiche::QuicheCircularDeque<PendingPathChallenge>
2147 pending_path_challenge_payloads_;
danzh8a27a1a2020-09-02 10:26:28 -07002148
QUICHE teamc65d1d12019-03-19 20:58:04 -07002149 // Set of connection IDs that should be accepted as destination on
2150 // received packets. This is conceptually a set but is implemented as a
2151 // vector to improve performance since it is expected to be very small.
2152 std::vector<QuicConnectionId> incoming_connection_ids_;
2153
dschinazie7c38a52020-05-29 15:25:45 -07002154 // When we receive a RETRY packet or some INITIAL packets, we replace
2155 // |server_connection_id_| with the value from that packet and save off the
2156 // original value of |server_connection_id_| into
2157 // |original_destination_connection_id_| for validation.
vasilvv7df418b2020-10-13 13:47:09 -07002158 absl::optional<QuicConnectionId> original_destination_connection_id_;
dschinazie7c38a52020-05-29 15:25:45 -07002159
haoyuewang1063e452021-04-28 10:44:33 -07002160 // The connection ID that replaces original_destination_connection_id_.
2161 QuicConnectionId original_destination_connection_id_replacement_;
2162
dschinazie7c38a52020-05-29 15:25:45 -07002163 // After we receive a RETRY packet, |retry_source_connection_id_| contains
2164 // the source connection ID from that packet.
vasilvv7df418b2020-10-13 13:47:09 -07002165 absl::optional<QuicConnectionId> retry_source_connection_id_;
dschinazi39e5e552020-05-06 13:55:24 -07002166
fayang2ce66082019-10-02 06:29:04 -07002167 // Used to store content of packets which cannot be sent because of write
2168 // blocked. Packets' encrypted buffers are copied and owned by
2169 // buffered_packets_. From unacked_packet_map (and congestion control)'s
fayange62e63c2019-12-04 07:16:25 -08002170 // perspective, those packets are considered sent.
fayang2ce66082019-10-02 06:29:04 -07002171 std::list<BufferedPacket> buffered_packets_;
2172
fayang58f71072019-11-05 08:47:02 -08002173 // Used to coalesce packets of different encryption level into the same UDP
2174 // datagram. Connection stops trying to coalesce packets if a forward secure
2175 // packet gets acknowledged.
2176 QuicCoalescedPacket coalesced_packet_;
2177
wubf76cf2a2019-10-11 18:49:07 -07002178 QuicConnectionMtuDiscoverer mtu_discoverer_;
fayangb59c6f12020-03-23 15:06:14 -07002179
2180 QuicNetworkBlackholeDetector blackhole_detector_;
2181
fayangb9c88442020-03-26 07:03:57 -07002182 QuicIdleNetworkDetector idle_network_detector_;
2183
fayangf78b6932020-06-08 08:36:45 -07002184 bool blackhole_detection_disabled_ = false;
2185
fayangaa4f3f22020-06-05 16:22:00 -07002186 const bool default_enable_5rto_blackhole_detection_ =
fayang656cbb52020-06-09 13:29:35 -07002187 GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection2);
dschinazi6458eb32020-06-23 12:38:41 -07002188
2189 // Whether the Legacy Version Encapsulation feature is enabled.
2190 bool legacy_version_encapsulation_enabled_ = false;
2191 // Whether we are in the middle of sending a packet using Legacy Version
2192 // Encapsulation.
2193 bool legacy_version_encapsulation_in_progress_ = false;
2194 // SNI to send when using Legacy Version Encapsulation.
2195 std::string legacy_version_encapsulation_sni_;
fayangfe963c52020-07-16 06:56:09 -07002196 // True if next packet is intended to consume remaining space in the
2197 // coalescer.
2198 bool fill_coalesced_packet_ = false;
fayang84305ed2020-08-24 13:00:40 -07002199
2200 size_t anti_amplification_factor_ =
2201 GetQuicFlag(FLAGS_quic_anti_amplification_factor);
danzh623f6ef2020-08-25 16:44:37 -07002202
QUICHE team33668082021-01-30 13:15:33 -08002203 bool start_peer_migration_earlier_ =
2204 GetQuicReloadableFlag(quic_start_peer_migration_earlier);
2205
danzh8a27a1a2020-09-02 10:26:28 -07002206 // latch --gfe2_reloadable_flag_quic_send_path_response and
2207 // --gfe2_reloadable_flag_quic_start_peer_migration_earlier.
2208 bool send_path_response_ = start_peer_migration_earlier_ &&
danzh8efd70d2021-03-09 13:00:27 -08002209 GetQuicReloadableFlag(quic_send_path_response2);
danzhe6211dc2020-11-19 09:19:00 -08002210
2211 bool use_path_validator_ =
2212 send_path_response_ &&
2213 GetQuicReloadableFlag(quic_pass_path_response_to_validator);
2214
haoyuewang2d2fdd12020-09-16 11:26:56 -07002215 // True if AckFrequencyFrame is supported.
2216 bool can_receive_ack_frequency_frame_ = false;
fayang9a74ee92020-09-23 15:49:11 -07002217
fayangdaeb8192020-09-24 09:28:59 -07002218 // Indicate whether coalescing is done.
2219 bool coalescing_done_ = false;
2220
fayangd8682452020-09-28 09:09:29 -07002221 // Indicate whether any ENCRYPTION_HANDSHAKE packet has been sent.
2222 bool handshake_packet_sent_ = false;
2223
haoyuewang24d8d702020-10-19 08:05:01 -07002224 // Indicate whether to send an AckFrequencyFrame upon handshake completion.
2225 // The AckFrequencyFrame sent will updates client's max_ack_delay, which if
2226 // chosen properly can reduce the CPU and bandwidth usage for ACK frames.
2227 bool send_ack_frequency_on_handshake_completion_ = false;
2228
haoyuewangc921f8d2020-10-14 18:06:52 -07002229 // Indicate whether AckFrequency frame has been sent.
2230 bool ack_frequency_sent_ = false;
2231
mattmad5eb5d2020-12-03 16:12:15 -08002232 // True if a 0-RTT decrypter was or is installed at some point in the
2233 // connection's lifetime.
2234 bool had_zero_rtt_decrypter_ = false;
2235
2236 // True after the first 1-RTT packet has successfully decrypted.
2237 bool have_decrypted_first_one_rtt_packet_ = false;
2238
fayang4b5b4e62021-04-14 06:16:42 -07002239 // True if we are currently processing OnRetransmissionTimeout.
2240 bool in_on_retransmission_time_out_ = false;
2241
fayang5100e292020-10-30 14:37:44 -07002242 const bool encrypted_control_frames_;
2243
2244 const bool use_encryption_level_context_;
danzhe6211dc2020-11-19 09:19:00 -08002245
2246 QuicPathValidator path_validator_;
danzh9cb85b72020-12-30 07:17:09 -08002247
danzha4b519c2021-02-05 12:10:55 -08002248 // Stores information of a path which maybe used as default path in the
2249 // future. On the client side, it gets created when the client starts
2250 // validating a new path and gets cleared once it becomes the default path or
2251 // the path validation fails or replaced by a newer path of interest. On the
danzha25ed9d2021-02-19 12:40:26 -08002252 // server side, alternative_path gets created when server: 1) receives
2253 // PATH_CHALLENGE on non-default path, or 2) switches to a not yet validated
2254 // default path such that it needs to store the previous validated default
2255 // path.
2256 // Note that if alternative_path_ stores a validated path information (case
2257 // 2), do not override it on receiving PATH_CHALLENGE (case 1).
danzh37b722e2021-02-17 11:09:08 -08002258 PathState alternative_path_;
danzh9cb85b72020-12-30 07:17:09 -08002259
renjietang5c9a9ce2021-01-19 15:48:57 -08002260 // This field is used to debug b/177312785.
2261 QuicFrameType most_recent_frame_type_;
2262
danzh9cb85b72020-12-30 07:17:09 -08002263 bool current_incoming_packet_received_bytes_counted_ = false;
2264
danzh046212e2021-01-26 11:44:09 -08002265 bool count_bytes_on_alternative_path_separately_ =
danzh9cb85b72020-12-30 07:17:09 -08002266 GetQuicReloadableFlag(quic_count_bytes_on_alternative_path_seperately);
renjietang7f1d9e12021-01-22 19:10:57 -08002267
danzha25ed9d2021-02-19 12:40:26 -08002268 // If true, upon seeing a new client address, validate the client address.
danzhf0bc77d2021-03-25 15:08:48 -07002269 bool validate_client_addresses_ = false;
haoyuewange3c51d92021-03-08 07:35:03 -08002270
2271 bool support_multiple_connection_ids_ = false;
fayangc2638cc2021-04-05 14:45:40 -07002272
2273 const bool donot_write_mid_packet_processing_ =
2274 GetQuicReloadableFlag(quic_donot_write_mid_packet_processing);
haoyuewang5c49d3e2021-04-08 07:33:33 -07002275
2276 bool use_connection_id_on_default_path_ =
haoyuewang1063e452021-04-28 10:44:33 -07002277 GetQuicReloadableFlag(quic_use_connection_id_on_default_path_v2);
haoyuewangf8e24a72021-04-08 13:40:55 -07002278
haoyuewang53cbf3f2021-04-13 12:52:11 -07002279 // Indicates whether we should proactively validate peer address on a
2280 // PATH_CHALLENGE received.
2281 bool should_proactively_validate_peer_address_on_path_challenge_ = false;
2282
haoyuewangdc60baf2021-04-19 14:03:14 -07002283 // Enable this via reloadable flag once this feature is complete.
2284 bool connection_migration_use_new_cid_ = false;
2285
haoyuewang53cbf3f2021-04-13 12:52:11 -07002286 const bool group_path_response_and_challenge_sending_closer_ =
2287 GetQuicReloadableFlag(
2288 quic_group_path_response_and_challenge_sending_closer);
2289
haoyuewangf8e24a72021-04-08 13:40:55 -07002290 const bool quic_deprecate_incoming_connection_ids_ =
2291 GetQuicReloadableFlag(quic_deprecate_incoming_connection_ids);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002292};
2293
2294} // namespace quic
2295
2296#endif // QUICHE_QUIC_CORE_QUIC_CONNECTION_H_