blob: db717b02d68875b617df76bd41a76fe52e152393 [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#include "net/third_party/quiche/src/quic/core/quic_connection.h"
6
7#include <string.h>
8#include <sys/types.h>
9
10#include <algorithm>
11#include <iterator>
12#include <limits>
13#include <memory>
14#include <set>
vasilvv872e7a32019-03-12 16:42:44 -070015#include <string>
QUICHE teama6ef0a62019-03-07 20:34:33 -050016#include <utility>
17
QUICHE teama6ef0a62019-03-07 20:34:33 -050018#include "net/third_party/quiche/src/quic/core/crypto/crypto_protocol.h"
dschinazi244f6dc2019-05-06 15:45:16 -070019#include "net/third_party/quiche/src/quic/core/crypto/crypto_utils.h"
QUICHE teama6ef0a62019-03-07 20:34:33 -050020#include "net/third_party/quiche/src/quic/core/crypto/quic_decrypter.h"
21#include "net/third_party/quiche/src/quic/core/crypto/quic_encrypter.h"
22#include "net/third_party/quiche/src/quic/core/proto/cached_network_parameters.pb.h"
23#include "net/third_party/quiche/src/quic/core/quic_bandwidth.h"
24#include "net/third_party/quiche/src/quic/core/quic_config.h"
QUICHE teamc65d1d12019-03-19 20:58:04 -070025#include "net/third_party/quiche/src/quic/core/quic_connection_id.h"
ianswettdc1e7ab2019-05-03 16:10:44 -070026#include "net/third_party/quiche/src/quic/core/quic_error_codes.h"
QUICHE teama6ef0a62019-03-07 20:34:33 -050027#include "net/third_party/quiche/src/quic/core/quic_packet_generator.h"
28#include "net/third_party/quiche/src/quic/core/quic_pending_retransmission.h"
29#include "net/third_party/quiche/src/quic/core/quic_types.h"
30#include "net/third_party/quiche/src/quic/core/quic_utils.h"
31#include "net/third_party/quiche/src/quic/platform/api/quic_bug_tracker.h"
32#include "net/third_party/quiche/src/quic/platform/api/quic_client_stats.h"
33#include "net/third_party/quiche/src/quic/platform/api/quic_error_code_wrappers.h"
34#include "net/third_party/quiche/src/quic/platform/api/quic_exported_stats.h"
35#include "net/third_party/quiche/src/quic/platform/api/quic_flag_utils.h"
36#include "net/third_party/quiche/src/quic/platform/api/quic_flags.h"
37#include "net/third_party/quiche/src/quic/platform/api/quic_logging.h"
38#include "net/third_party/quiche/src/quic/platform/api/quic_map_util.h"
39#include "net/third_party/quiche/src/quic/platform/api/quic_str_cat.h"
QUICHE teama6ef0a62019-03-07 20:34:33 -050040#include "net/third_party/quiche/src/quic/platform/api/quic_string_utils.h"
41#include "net/third_party/quiche/src/quic/platform/api/quic_text_utils.h"
42
43namespace quic {
44
45class QuicDecrypter;
46class QuicEncrypter;
47
48namespace {
49
50// Maximum number of consecutive sent nonretransmittable packets.
51const QuicPacketCount kMaxConsecutiveNonRetransmittablePackets = 19;
52
53// Maximum number of retransmittable packets received before sending an ack.
54const QuicPacketCount kDefaultRetransmittablePacketsBeforeAck = 2;
55// Minimum number of packets received before ack decimation is enabled.
56// This intends to avoid the beginning of slow start, when CWNDs may be
57// rapidly increasing.
58const QuicPacketCount kMinReceivedBeforeAckDecimation = 100;
59// Wait for up to 10 retransmittable packets before sending an ack.
60const QuicPacketCount kMaxRetransmittablePacketsBeforeAck = 10;
61// One quarter RTT delay when doing ack decimation.
62const float kAckDecimationDelay = 0.25;
63// One eighth RTT delay when doing ack decimation.
64const float kShortAckDecimationDelay = 0.125;
65
66// The minimum release time into future in ms.
67const int kMinReleaseTimeIntoFutureMs = 1;
68
69bool Near(QuicPacketNumber a, QuicPacketNumber b) {
70 QuicPacketCount delta = (a > b) ? a - b : b - a;
71 return delta <= kMaxPacketGap;
72}
73
74// An alarm that is scheduled to send an ack if a timeout occurs.
75class AckAlarmDelegate : public QuicAlarm::Delegate {
76 public:
77 explicit AckAlarmDelegate(QuicConnection* connection)
78 : connection_(connection) {}
79 AckAlarmDelegate(const AckAlarmDelegate&) = delete;
80 AckAlarmDelegate& operator=(const AckAlarmDelegate&) = delete;
81
82 void OnAlarm() override {
83 DCHECK(connection_->ack_frame_updated());
84 QuicConnection::ScopedPacketFlusher flusher(connection_,
85 QuicConnection::SEND_ACK);
86 if (connection_->packet_generator().deprecate_ack_bundling_mode()) {
QUICHE teamcd098022019-03-22 18:49:55 -070087 if (connection_->SupportsMultiplePacketNumberSpaces()) {
88 connection_->SendAllPendingAcks();
89 } else {
90 DCHECK(!connection_->GetUpdatedAckFrame().ack_frame->packets.Empty());
91 connection_->SendAck();
92 }
QUICHE teama6ef0a62019-03-07 20:34:33 -050093 }
94 }
95
96 private:
97 QuicConnection* connection_;
98};
99
100// This alarm will be scheduled any time a data-bearing packet is sent out.
101// When the alarm goes off, the connection checks to see if the oldest packets
102// have been acked, and retransmit them if they have not.
103class RetransmissionAlarmDelegate : public QuicAlarm::Delegate {
104 public:
105 explicit RetransmissionAlarmDelegate(QuicConnection* connection)
106 : connection_(connection) {}
107 RetransmissionAlarmDelegate(const RetransmissionAlarmDelegate&) = delete;
108 RetransmissionAlarmDelegate& operator=(const RetransmissionAlarmDelegate&) =
109 delete;
110
111 void OnAlarm() override { connection_->OnRetransmissionTimeout(); }
112
113 private:
114 QuicConnection* connection_;
115};
116
117// An alarm that is scheduled when the SentPacketManager requires a delay
118// before sending packets and fires when the packet may be sent.
119class SendAlarmDelegate : public QuicAlarm::Delegate {
120 public:
121 explicit SendAlarmDelegate(QuicConnection* connection)
122 : connection_(connection) {}
123 SendAlarmDelegate(const SendAlarmDelegate&) = delete;
124 SendAlarmDelegate& operator=(const SendAlarmDelegate&) = delete;
125
126 void OnAlarm() override { connection_->WriteAndBundleAcksIfNotBlocked(); }
127
128 private:
129 QuicConnection* connection_;
130};
131
132class PathDegradingAlarmDelegate : public QuicAlarm::Delegate {
133 public:
134 explicit PathDegradingAlarmDelegate(QuicConnection* connection)
135 : connection_(connection) {}
136 PathDegradingAlarmDelegate(const PathDegradingAlarmDelegate&) = delete;
137 PathDegradingAlarmDelegate& operator=(const PathDegradingAlarmDelegate&) =
138 delete;
139
140 void OnAlarm() override { connection_->OnPathDegradingTimeout(); }
141
142 private:
143 QuicConnection* connection_;
144};
145
146class TimeoutAlarmDelegate : public QuicAlarm::Delegate {
147 public:
148 explicit TimeoutAlarmDelegate(QuicConnection* connection)
149 : connection_(connection) {}
150 TimeoutAlarmDelegate(const TimeoutAlarmDelegate&) = delete;
151 TimeoutAlarmDelegate& operator=(const TimeoutAlarmDelegate&) = delete;
152
153 void OnAlarm() override { connection_->CheckForTimeout(); }
154
155 private:
156 QuicConnection* connection_;
157};
158
159class PingAlarmDelegate : public QuicAlarm::Delegate {
160 public:
161 explicit PingAlarmDelegate(QuicConnection* connection)
162 : connection_(connection) {}
163 PingAlarmDelegate(const PingAlarmDelegate&) = delete;
164 PingAlarmDelegate& operator=(const PingAlarmDelegate&) = delete;
165
166 void OnAlarm() override { connection_->OnPingTimeout(); }
167
168 private:
169 QuicConnection* connection_;
170};
171
172class MtuDiscoveryAlarmDelegate : public QuicAlarm::Delegate {
173 public:
174 explicit MtuDiscoveryAlarmDelegate(QuicConnection* connection)
175 : connection_(connection) {}
176 MtuDiscoveryAlarmDelegate(const MtuDiscoveryAlarmDelegate&) = delete;
177 MtuDiscoveryAlarmDelegate& operator=(const MtuDiscoveryAlarmDelegate&) =
178 delete;
179
180 void OnAlarm() override { connection_->DiscoverMtu(); }
181
182 private:
183 QuicConnection* connection_;
184};
185
QUICHE teama6ef0a62019-03-07 20:34:33 -0500186class ProcessUndecryptablePacketsAlarmDelegate : public QuicAlarm::Delegate {
187 public:
188 explicit ProcessUndecryptablePacketsAlarmDelegate(QuicConnection* connection)
189 : connection_(connection) {}
190 ProcessUndecryptablePacketsAlarmDelegate(
191 const ProcessUndecryptablePacketsAlarmDelegate&) = delete;
192 ProcessUndecryptablePacketsAlarmDelegate& operator=(
193 const ProcessUndecryptablePacketsAlarmDelegate&) = delete;
194
rch2af16b12019-03-22 13:52:39 -0700195 void OnAlarm() override {
196 QuicConnection::ScopedPacketFlusher flusher(connection_,
197 QuicConnection::NO_ACK);
198 connection_->MaybeProcessUndecryptablePackets();
199 }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500200
201 private:
202 QuicConnection* connection_;
203};
204
QUICHE teamc65d1d12019-03-19 20:58:04 -0700205// Whether this incoming packet is allowed to replace our connection ID.
206bool PacketCanReplaceConnectionId(const QuicPacketHeader& header,
207 Perspective perspective) {
208 return perspective == Perspective::IS_CLIENT &&
209 header.form == IETF_QUIC_LONG_HEADER_PACKET &&
210 QuicUtils::VariableLengthConnectionIdAllowedForVersion(
211 header.version.transport_version) &&
212 (header.long_packet_type == INITIAL ||
213 header.long_packet_type == RETRY);
214}
215
QUICHE teama6ef0a62019-03-07 20:34:33 -0500216} // namespace
217
218#define ENDPOINT \
219 (perspective_ == Perspective::IS_SERVER ? "Server: " : "Client: ")
220
221QuicConnection::QuicConnection(
dschinazi7b9278c2019-05-20 07:36:21 -0700222 QuicConnectionId server_connection_id,
QUICHE teama6ef0a62019-03-07 20:34:33 -0500223 QuicSocketAddress initial_peer_address,
224 QuicConnectionHelperInterface* helper,
225 QuicAlarmFactory* alarm_factory,
226 QuicPacketWriter* writer,
227 bool owns_writer,
228 Perspective perspective,
229 const ParsedQuicVersionVector& supported_versions)
230 : framer_(supported_versions,
231 helper->GetClock()->ApproximateNow(),
232 perspective,
dschinazi7b9278c2019-05-20 07:36:21 -0700233 server_connection_id.length()),
QUICHE teama6ef0a62019-03-07 20:34:33 -0500234 current_packet_content_(NO_FRAMES_RECEIVED),
235 is_current_packet_connectivity_probing_(false),
236 current_effective_peer_migration_type_(NO_CHANGE),
237 helper_(helper),
238 alarm_factory_(alarm_factory),
239 per_packet_options_(nullptr),
240 writer_(writer),
241 owns_writer_(owns_writer),
QUICHE team6987b4a2019-03-15 16:23:04 -0700242 encryption_level_(ENCRYPTION_INITIAL),
QUICHE teama6ef0a62019-03-07 20:34:33 -0500243 clock_(helper->GetClock()),
244 random_generator_(helper->GetRandomGenerator()),
dschinazi7b9278c2019-05-20 07:36:21 -0700245 server_connection_id_(server_connection_id),
QUICHE teama6ef0a62019-03-07 20:34:33 -0500246 peer_address_(initial_peer_address),
247 direct_peer_address_(initial_peer_address),
248 active_effective_peer_migration_type_(NO_CHANGE),
249 last_packet_decrypted_(false),
250 last_size_(0),
251 current_packet_data_(nullptr),
QUICHE team6987b4a2019-03-15 16:23:04 -0700252 last_decrypted_packet_level_(ENCRYPTION_INITIAL),
QUICHE teama6ef0a62019-03-07 20:34:33 -0500253 should_last_packet_instigate_acks_(false),
254 was_last_packet_missing_(false),
255 max_undecryptable_packets_(0),
256 max_tracked_packets_(kMaxTrackedPackets),
257 pending_version_negotiation_packet_(false),
258 send_ietf_version_negotiation_packet_(false),
259 save_crypto_packets_as_termination_packets_(false),
260 idle_timeout_connection_close_behavior_(
261 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET),
262 close_connection_after_five_rtos_(false),
263 received_packet_manager_(&stats_),
QUICHE teamb23daa72019-03-21 08:37:48 -0700264 uber_received_packet_manager_(&stats_),
QUICHE teama6ef0a62019-03-07 20:34:33 -0500265 ack_queued_(false),
266 num_retransmittable_packets_received_since_last_ack_sent_(0),
267 num_packets_received_since_last_ack_sent_(0),
268 stop_waiting_count_(0),
269 ack_mode_(GetQuicReloadableFlag(quic_enable_ack_decimation)
270 ? ACK_DECIMATION
271 : TCP_ACKING),
272 ack_decimation_delay_(kAckDecimationDelay),
273 unlimited_ack_decimation_(false),
274 fast_ack_after_quiescence_(false),
275 pending_retransmission_alarm_(false),
276 defer_send_in_response_to_packets_(false),
277 ping_timeout_(QuicTime::Delta::FromSeconds(kPingTimeoutSecs)),
278 retransmittable_on_wire_timeout_(QuicTime::Delta::Infinite()),
279 arena_(),
280 ack_alarm_(alarm_factory_->CreateAlarm(arena_.New<AckAlarmDelegate>(this),
281 &arena_)),
282 retransmission_alarm_(alarm_factory_->CreateAlarm(
283 arena_.New<RetransmissionAlarmDelegate>(this),
284 &arena_)),
285 send_alarm_(
286 alarm_factory_->CreateAlarm(arena_.New<SendAlarmDelegate>(this),
287 &arena_)),
288 timeout_alarm_(
289 alarm_factory_->CreateAlarm(arena_.New<TimeoutAlarmDelegate>(this),
290 &arena_)),
291 ping_alarm_(
292 alarm_factory_->CreateAlarm(arena_.New<PingAlarmDelegate>(this),
293 &arena_)),
294 mtu_discovery_alarm_(alarm_factory_->CreateAlarm(
295 arena_.New<MtuDiscoveryAlarmDelegate>(this),
296 &arena_)),
297 path_degrading_alarm_(alarm_factory_->CreateAlarm(
298 arena_.New<PathDegradingAlarmDelegate>(this),
299 &arena_)),
300 process_undecryptable_packets_alarm_(alarm_factory_->CreateAlarm(
301 arena_.New<ProcessUndecryptablePacketsAlarmDelegate>(this),
302 &arena_)),
303 visitor_(nullptr),
304 debug_visitor_(nullptr),
dschinazi7b9278c2019-05-20 07:36:21 -0700305 packet_generator_(server_connection_id_,
306 &framer_,
307 random_generator_,
308 this),
QUICHE teama6ef0a62019-03-07 20:34:33 -0500309 idle_network_timeout_(QuicTime::Delta::Infinite()),
310 handshake_timeout_(QuicTime::Delta::Infinite()),
311 time_of_first_packet_sent_after_receiving_(
312 GetQuicReloadableFlag(
313 quic_fix_time_of_first_packet_sent_after_receiving)
314 ? QuicTime::Zero()
315 : clock_->ApproximateNow()),
316 time_of_last_received_packet_(clock_->ApproximateNow()),
317 time_of_previous_received_packet_(QuicTime::Zero()),
318 sent_packet_manager_(
319 perspective,
320 clock_,
QUICHE team73957f12019-04-18 16:21:52 -0700321 random_generator_,
QUICHE teama6ef0a62019-03-07 20:34:33 -0500322 &stats_,
323 GetQuicReloadableFlag(quic_default_to_bbr) ? kBBR : kCubicBytes,
324 kNack),
325 version_negotiation_state_(START_NEGOTIATION),
326 perspective_(perspective),
327 connected_(true),
328 can_truncate_connection_ids_(perspective == Perspective::IS_SERVER),
329 mtu_discovery_target_(0),
330 mtu_probe_count_(0),
331 packets_between_mtu_probes_(kPacketsBetweenMtuProbesBase),
332 next_mtu_probe_at_(kPacketsBetweenMtuProbesBase),
333 largest_received_packet_size_(0),
334 write_error_occurred_(false),
335 no_stop_waiting_frames_(transport_version() > QUIC_VERSION_43),
336 consecutive_num_packets_with_no_retransmittable_frames_(0),
337 max_consecutive_num_packets_with_no_retransmittable_frames_(
338 kMaxConsecutiveNonRetransmittablePackets),
339 min_received_before_ack_decimation_(kMinReceivedBeforeAckDecimation),
340 ack_frequency_before_ack_decimation_(
341 kDefaultRetransmittablePacketsBeforeAck),
342 fill_up_link_during_probing_(false),
343 probing_retransmission_pending_(false),
344 stateless_reset_token_received_(false),
345 received_stateless_reset_token_(0),
346 last_control_frame_id_(kInvalidControlFrameId),
347 is_path_degrading_(false),
348 processing_ack_frame_(false),
349 supports_release_time_(false),
350 release_time_into_future_(QuicTime::Delta::Zero()),
351 no_version_negotiation_(supported_versions.size() == 1),
QUICHE team692750b2019-03-17 17:57:46 -0700352 send_ack_when_on_can_write_(false),
dschinazi244f6dc2019-05-06 15:45:16 -0700353 retry_has_been_parsed_(false),
QUICHE team692750b2019-03-17 17:57:46 -0700354 validate_packet_number_post_decryption_(
QUICHE teamb23daa72019-03-21 08:37:48 -0700355 GetQuicReloadableFlag(quic_validate_packet_number_post_decryption)),
356 use_uber_received_packet_manager_(
357 received_packet_manager_.decide_when_to_send_acks() &&
QUICHE team1dfa46b2019-03-22 10:39:10 -0700358 validate_packet_number_post_decryption_ &&
QUICHE teamb23daa72019-03-21 08:37:48 -0700359 GetQuicReloadableFlag(quic_use_uber_received_packet_manager)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500360 if (ack_mode_ == ACK_DECIMATION) {
361 QUIC_RELOADABLE_FLAG_COUNT(quic_enable_ack_decimation);
362 }
363 if (perspective_ == Perspective::IS_SERVER &&
364 supported_versions.size() == 1) {
365 QUIC_RESTART_FLAG_COUNT(quic_no_server_conn_ver_negotiation2);
366 }
367 if (packet_generator_.deprecate_ack_bundling_mode()) {
368 QUIC_RELOADABLE_FLAG_COUNT(quic_deprecate_ack_bundling_mode);
369 }
370 if (received_packet_manager_.decide_when_to_send_acks()) {
371 QUIC_RELOADABLE_FLAG_COUNT(quic_rpm_decides_when_to_send_acks);
372 }
QUICHE team692750b2019-03-17 17:57:46 -0700373 if (validate_packet_number_post_decryption_) {
374 QUIC_RELOADABLE_FLAG_COUNT(quic_validate_packet_number_post_decryption);
375 }
QUICHE teamb23daa72019-03-21 08:37:48 -0700376 if (use_uber_received_packet_manager_) {
377 QUIC_RELOADABLE_FLAG_COUNT(quic_use_uber_received_packet_manager);
378 }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500379 QUIC_DLOG(INFO) << ENDPOINT
dschinazi7b9278c2019-05-20 07:36:21 -0700380 << "Created connection with server connection_id: "
381 << server_connection_id
zhongyi546cc452019-04-12 15:27:49 -0700382 << " and version: " << ParsedQuicVersionToString(version());
QUICHE teama6ef0a62019-03-07 20:34:33 -0500383
dschinazi7b9278c2019-05-20 07:36:21 -0700384 QUIC_BUG_IF(!QuicUtils::IsConnectionIdValidForVersion(server_connection_id,
QUICHE teama6ef0a62019-03-07 20:34:33 -0500385 transport_version()))
dschinazi7b9278c2019-05-20 07:36:21 -0700386 << "QuicConnection: attempted to use server connection ID "
387 << server_connection_id << " which is invalid with version "
QUICHE teama6ef0a62019-03-07 20:34:33 -0500388 << QuicVersionToString(transport_version());
389
390 framer_.set_visitor(this);
391 stats_.connection_creation_time = clock_->ApproximateNow();
392 // TODO(ianswett): Supply the NetworkChangeVisitor as a constructor argument
393 // and make it required non-null, because it's always used.
394 sent_packet_manager_.SetNetworkChangeVisitor(this);
395 if (GetQuicRestartFlag(quic_offload_pacing_to_usps2)) {
396 sent_packet_manager_.SetPacingAlarmGranularity(QuicTime::Delta::Zero());
397 release_time_into_future_ =
398 QuicTime::Delta::FromMilliseconds(kMinReleaseTimeIntoFutureMs);
399 }
400 // Allow the packet writer to potentially reduce the packet size to a value
401 // even smaller than kDefaultMaxPacketSize.
402 SetMaxPacketLength(perspective_ == Perspective::IS_SERVER
403 ? kDefaultServerMaxPacketSize
404 : kDefaultMaxPacketSize);
QUICHE teamb23daa72019-03-21 08:37:48 -0700405 if (use_uber_received_packet_manager_) {
406 uber_received_packet_manager_.set_max_ack_ranges(255);
407 } else {
408 received_packet_manager_.set_max_ack_ranges(255);
409 }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500410 MaybeEnableSessionDecidesWhatToWrite();
QUICHE teamcd098022019-03-22 18:49:55 -0700411 MaybeEnableMultiplePacketNumberSpacesSupport();
QUICHE teama6ef0a62019-03-07 20:34:33 -0500412 DCHECK(!GetQuicRestartFlag(quic_no_server_conn_ver_negotiation2) ||
413 perspective_ == Perspective::IS_CLIENT ||
414 supported_versions.size() == 1);
dschinazi6ece5002019-05-22 06:35:49 -0700415 InstallInitialCrypters();
416}
417
418void QuicConnection::InstallInitialCrypters() {
419 if (version().handshake_protocol != PROTOCOL_TLS1_3) {
420 // Initial crypters are currently only supported with TLS.
421 return;
422 }
423 CrypterPair crypters;
424 CryptoUtils::CreateTlsInitialCrypters(perspective_, transport_version(),
425 server_connection_id_, &crypters);
426 SetEncrypter(ENCRYPTION_INITIAL, std::move(crypters.encrypter));
427 InstallDecrypter(ENCRYPTION_INITIAL, std::move(crypters.decrypter));
QUICHE teama6ef0a62019-03-07 20:34:33 -0500428}
429
430QuicConnection::~QuicConnection() {
431 if (owns_writer_) {
432 delete writer_;
433 }
434 ClearQueuedPackets();
435}
436
437void QuicConnection::ClearQueuedPackets() {
438 for (auto it = queued_packets_.begin(); it != queued_packets_.end(); ++it) {
439 // Delete the buffer before calling ClearSerializedPacket, which sets
440 // encrypted_buffer to nullptr.
441 delete[] it->encrypted_buffer;
442 ClearSerializedPacket(&(*it));
443 }
444 queued_packets_.clear();
445}
446
447void QuicConnection::SetFromConfig(const QuicConfig& config) {
448 if (config.negotiated()) {
449 // Handshake complete, set handshake timeout to Infinite.
450 SetNetworkTimeouts(QuicTime::Delta::Infinite(),
451 config.IdleNetworkTimeout());
452 if (config.SilentClose()) {
453 idle_timeout_connection_close_behavior_ =
454 ConnectionCloseBehavior::SILENT_CLOSE;
455 }
456 } else {
457 SetNetworkTimeouts(config.max_time_before_crypto_handshake(),
458 config.max_idle_time_before_crypto_handshake());
459 }
460
461 sent_packet_manager_.SetFromConfig(config);
462 if (config.HasReceivedBytesForConnectionId() &&
463 can_truncate_connection_ids_) {
dschinazi7b9278c2019-05-20 07:36:21 -0700464 packet_generator_.SetServerConnectionIdLength(
QUICHE teama6ef0a62019-03-07 20:34:33 -0500465 config.ReceivedBytesForConnectionId());
466 }
467 max_undecryptable_packets_ = config.max_undecryptable_packets();
468
469 if (config.HasClientSentConnectionOption(kMTUH, perspective_)) {
470 SetMtuDiscoveryTarget(kMtuDiscoveryTargetPacketSizeHigh);
471 }
472 if (config.HasClientSentConnectionOption(kMTUL, perspective_)) {
473 SetMtuDiscoveryTarget(kMtuDiscoveryTargetPacketSizeLow);
474 }
475 if (debug_visitor_ != nullptr) {
476 debug_visitor_->OnSetFromConfig(config);
477 }
478 if (received_packet_manager_.decide_when_to_send_acks()) {
QUICHE teamb23daa72019-03-21 08:37:48 -0700479 if (use_uber_received_packet_manager_) {
480 uber_received_packet_manager_.SetFromConfig(config, perspective_);
481 } else {
482 received_packet_manager_.SetFromConfig(config, perspective_);
483 }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500484 } else {
485 if (GetQuicReloadableFlag(quic_enable_ack_decimation) &&
486 config.HasClientSentConnectionOption(kACD0, perspective_)) {
487 ack_mode_ = TCP_ACKING;
488 }
489 if (config.HasClientSentConnectionOption(kACKD, perspective_)) {
490 ack_mode_ = ACK_DECIMATION;
491 }
492 if (config.HasClientSentConnectionOption(kAKD2, perspective_)) {
493 ack_mode_ = ACK_DECIMATION_WITH_REORDERING;
494 }
495 if (config.HasClientSentConnectionOption(kAKD3, perspective_)) {
496 ack_mode_ = ACK_DECIMATION;
497 ack_decimation_delay_ = kShortAckDecimationDelay;
498 }
499 if (config.HasClientSentConnectionOption(kAKD4, perspective_)) {
500 ack_mode_ = ACK_DECIMATION_WITH_REORDERING;
501 ack_decimation_delay_ = kShortAckDecimationDelay;
502 }
503 if (config.HasClientSentConnectionOption(kAKDU, perspective_)) {
504 unlimited_ack_decimation_ = true;
505 }
506 if (config.HasClientSentConnectionOption(kACKQ, perspective_)) {
507 fast_ack_after_quiescence_ = true;
508 }
509 }
510 if (config.HasClientSentConnectionOption(k5RTO, perspective_)) {
511 close_connection_after_five_rtos_ = true;
512 }
513 if (config.HasClientSentConnectionOption(kNSTP, perspective_)) {
514 no_stop_waiting_frames_ = true;
515 }
516 if (config.HasReceivedStatelessResetToken()) {
517 stateless_reset_token_received_ = true;
518 received_stateless_reset_token_ = config.ReceivedStatelessResetToken();
519 }
520 if (GetQuicReloadableFlag(quic_send_timestamps) &&
521 config.HasClientSentConnectionOption(kSTMP, perspective_)) {
522 QUIC_RELOADABLE_FLAG_COUNT(quic_send_timestamps);
523 framer_.set_process_timestamps(true);
QUICHE teamb23daa72019-03-21 08:37:48 -0700524 if (use_uber_received_packet_manager_) {
525 uber_received_packet_manager_.set_save_timestamps(true);
526 } else {
527 received_packet_manager_.set_save_timestamps(true);
528 }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500529 }
530
531 supports_release_time_ =
532 writer_ != nullptr && writer_->SupportsReleaseTime() &&
533 !config.HasClientSentConnectionOption(kNPCO, perspective_);
534
535 if (supports_release_time_) {
536 UpdateReleaseTimeIntoFuture();
537 }
538}
539
540void QuicConnection::OnSendConnectionState(
541 const CachedNetworkParameters& cached_network_params) {
542 if (debug_visitor_ != nullptr) {
543 debug_visitor_->OnSendConnectionState(cached_network_params);
544 }
545}
546
547void QuicConnection::OnReceiveConnectionState(
548 const CachedNetworkParameters& cached_network_params) {
549 if (debug_visitor_ != nullptr) {
550 debug_visitor_->OnReceiveConnectionState(cached_network_params);
551 }
552}
553
554void QuicConnection::ResumeConnectionState(
555 const CachedNetworkParameters& cached_network_params,
556 bool max_bandwidth_resumption) {
557 sent_packet_manager_.ResumeConnectionState(cached_network_params,
558 max_bandwidth_resumption);
559}
560
561void QuicConnection::SetMaxPacingRate(QuicBandwidth max_pacing_rate) {
562 sent_packet_manager_.SetMaxPacingRate(max_pacing_rate);
563}
564
565void QuicConnection::AdjustNetworkParameters(QuicBandwidth bandwidth,
fayangf1b99dc2019-05-14 06:29:18 -0700566 QuicTime::Delta rtt,
567 bool allow_cwnd_to_decrease) {
568 sent_packet_manager_.AdjustNetworkParameters(bandwidth, rtt,
569 allow_cwnd_to_decrease);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500570}
571
572QuicBandwidth QuicConnection::MaxPacingRate() const {
573 return sent_packet_manager_.MaxPacingRate();
574}
575
576bool QuicConnection::SelectMutualVersion(
577 const ParsedQuicVersionVector& available_versions) {
578 // Try to find the highest mutual version by iterating over supported
579 // versions, starting with the highest, and breaking out of the loop once we
580 // find a matching version in the provided available_versions vector.
581 const ParsedQuicVersionVector& supported_versions =
582 framer_.supported_versions();
583 for (size_t i = 0; i < supported_versions.size(); ++i) {
584 const ParsedQuicVersion& version = supported_versions[i];
585 if (QuicContainsValue(available_versions, version)) {
586 framer_.set_version(version);
587 return true;
588 }
589 }
590
591 return false;
592}
593
594void QuicConnection::OnError(QuicFramer* framer) {
595 // Packets that we can not or have not decrypted are dropped.
596 // TODO(rch): add stats to measure this.
597 if (!connected_ || last_packet_decrypted_ == false) {
598 return;
599 }
600 CloseConnection(framer->error(), framer->detailed_error(),
601 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
602}
603
604void QuicConnection::OnPacket() {
605 last_packet_decrypted_ = false;
606}
607
608void QuicConnection::OnPublicResetPacket(const QuicPublicResetPacket& packet) {
609 // Check that any public reset packet with a different connection ID that was
610 // routed to this QuicConnection has been redirected before control reaches
611 // here. (Check for a bug regression.)
dschinazi7b9278c2019-05-20 07:36:21 -0700612 DCHECK_EQ(server_connection_id_, packet.connection_id);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500613 DCHECK_EQ(perspective_, Perspective::IS_CLIENT);
614 if (debug_visitor_ != nullptr) {
615 debug_visitor_->OnPublicResetPacket(packet);
616 }
vasilvvc48c8712019-03-11 13:38:16 -0700617 std::string error_details = "Received public reset.";
QUICHE teama6ef0a62019-03-07 20:34:33 -0500618 if (perspective_ == Perspective::IS_CLIENT && !packet.endpoint_id.empty()) {
619 QuicStrAppend(&error_details, " From ", packet.endpoint_id, ".");
620 }
621 QUIC_DLOG(INFO) << ENDPOINT << error_details;
622 QUIC_CODE_COUNT(quic_tear_down_local_connection_on_public_reset);
623 TearDownLocalConnectionState(QUIC_PUBLIC_RESET, error_details,
624 ConnectionCloseSource::FROM_PEER);
625}
626
627bool QuicConnection::OnProtocolVersionMismatch(
628 ParsedQuicVersion received_version,
629 PacketHeaderFormat form) {
630 QUIC_DLOG(INFO) << ENDPOINT << "Received packet with mismatched version "
631 << ParsedQuicVersionToString(received_version);
632 if (perspective_ == Perspective::IS_CLIENT) {
vasilvvc48c8712019-03-11 13:38:16 -0700633 const std::string error_details = "Protocol version mismatch.";
QUICHE teama6ef0a62019-03-07 20:34:33 -0500634 QUIC_BUG << ENDPOINT << error_details;
635 TearDownLocalConnectionState(QUIC_INTERNAL_ERROR, error_details,
636 ConnectionCloseSource::FROM_SELF);
637 return false;
638 }
639 if (no_version_negotiation_) {
640 // Drop old packets that were sent by the client before the version was
641 // negotiated.
642 return false;
643 }
644 DCHECK_NE(version(), received_version);
645
646 if (debug_visitor_ != nullptr) {
647 debug_visitor_->OnProtocolVersionMismatch(received_version);
648 }
649
650 switch (version_negotiation_state_) {
651 case START_NEGOTIATION:
652 if (!framer_.IsSupportedVersion(received_version)) {
653 SendVersionNegotiationPacket(form != GOOGLE_QUIC_PACKET);
654 version_negotiation_state_ = NEGOTIATION_IN_PROGRESS;
655 return false;
656 }
657 break;
658
659 case NEGOTIATION_IN_PROGRESS:
660 if (!framer_.IsSupportedVersion(received_version)) {
661 SendVersionNegotiationPacket(form != GOOGLE_QUIC_PACKET);
662 return false;
663 }
664 break;
665
666 case NEGOTIATED_VERSION:
667 // Might be old packets that were sent by the client before the version
668 // was negotiated. Drop these.
669 return false;
670
671 default:
672 DCHECK(false);
673 }
674
675 // Store the new version.
676 framer_.set_version(received_version);
677 framer_.InferPacketHeaderTypeFromVersion();
678
679 version_negotiation_state_ = NEGOTIATED_VERSION;
680 visitor_->OnSuccessfulVersionNegotiation(received_version);
681 if (debug_visitor_ != nullptr) {
682 debug_visitor_->OnSuccessfulVersionNegotiation(received_version);
683 }
684 QUIC_DLOG(INFO) << ENDPOINT << "version negotiated "
685 << ParsedQuicVersionToString(received_version);
686
687 MaybeEnableSessionDecidesWhatToWrite();
688 no_stop_waiting_frames_ =
689 received_version.transport_version > QUIC_VERSION_43;
690
691 // TODO(satyamshekhar): Store the packet number of this packet and close the
692 // connection if we ever received a packet with incorrect version and whose
693 // packet number is greater.
694 return true;
695}
696
697// Handles version negotiation for client connection.
698void QuicConnection::OnVersionNegotiationPacket(
699 const QuicVersionNegotiationPacket& packet) {
700 // Check that any public reset packet with a different connection ID that was
701 // routed to this QuicConnection has been redirected before control reaches
702 // here. (Check for a bug regression.)
dschinazi7b9278c2019-05-20 07:36:21 -0700703 DCHECK_EQ(server_connection_id_, packet.connection_id);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500704 if (perspective_ == Perspective::IS_SERVER) {
vasilvvc48c8712019-03-11 13:38:16 -0700705 const std::string error_details =
dschinazi5a354c92019-05-09 12:18:53 -0700706 "Server received version negotiation packet.";
QUICHE teama6ef0a62019-03-07 20:34:33 -0500707 QUIC_BUG << error_details;
708 QUIC_CODE_COUNT(quic_tear_down_local_connection_on_version_negotiation);
709 TearDownLocalConnectionState(QUIC_INTERNAL_ERROR, error_details,
710 ConnectionCloseSource::FROM_SELF);
711 return;
712 }
713 if (debug_visitor_ != nullptr) {
714 debug_visitor_->OnVersionNegotiationPacket(packet);
715 }
716
717 if (version_negotiation_state_ != START_NEGOTIATION) {
718 // Possibly a duplicate version negotiation packet.
719 return;
720 }
721
722 if (QuicContainsValue(packet.versions, version())) {
vasilvvc48c8712019-03-11 13:38:16 -0700723 const std::string error_details =
QUICHE teama6ef0a62019-03-07 20:34:33 -0500724 "Server already supports client's version and should have accepted the "
725 "connection.";
726 QUIC_DLOG(WARNING) << error_details;
727 TearDownLocalConnectionState(QUIC_INVALID_VERSION_NEGOTIATION_PACKET,
728 error_details,
729 ConnectionCloseSource::FROM_SELF);
730 return;
731 }
732
733 server_supported_versions_ = packet.versions;
734
735 if (GetQuicReloadableFlag(quic_no_client_conn_ver_negotiation)) {
736 QUIC_RELOADABLE_FLAG_COUNT(quic_no_client_conn_ver_negotiation);
737 CloseConnection(
738 QUIC_INVALID_VERSION,
739 QuicStrCat(
740 "Client may support one of the versions in the server's list, but "
741 "it's going to close the connection anyway. Supported versions: {",
742 ParsedQuicVersionVectorToString(framer_.supported_versions()),
743 "}, peer supported versions: {",
744 ParsedQuicVersionVectorToString(packet.versions), "}"),
745 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
746 return;
747 }
748
dschinazi5a354c92019-05-09 12:18:53 -0700749 ParsedQuicVersion original_version = version();
QUICHE teama6ef0a62019-03-07 20:34:33 -0500750 if (!SelectMutualVersion(packet.versions)) {
751 CloseConnection(
752 QUIC_INVALID_VERSION,
753 QuicStrCat(
754 "No common version found. Supported versions: {",
755 ParsedQuicVersionVectorToString(framer_.supported_versions()),
756 "}, peer supported versions: {",
757 ParsedQuicVersionVectorToString(packet.versions), "}"),
758 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
759 return;
760 }
761
dschinazi5a354c92019-05-09 12:18:53 -0700762 if (original_version.handshake_protocol != version().handshake_protocol) {
763 const std::string error_details =
764 "In-connection version negotiation between mismatched handshake "
765 " protocols " +
766 ParsedQuicVersionToString(original_version) + " and " +
767 ParsedQuicVersionToString(version()) + " is currently unsupported.";
768 QUIC_DLOG(WARNING) << error_details;
769 TearDownLocalConnectionState(QUIC_INVALID_VERSION, error_details,
770 ConnectionCloseSource::FROM_SELF);
771 return;
772 }
773
QUICHE teama6ef0a62019-03-07 20:34:33 -0500774 QUIC_DLOG(INFO) << ENDPOINT << "Negotiated version: "
dschinazi5a354c92019-05-09 12:18:53 -0700775 << ParsedQuicVersionToString(version());
QUICHE teama6ef0a62019-03-07 20:34:33 -0500776 no_stop_waiting_frames_ = transport_version() > QUIC_VERSION_43;
777 version_negotiation_state_ = NEGOTIATION_IN_PROGRESS;
dschinazi5a354c92019-05-09 12:18:53 -0700778
QUICHE teama6ef0a62019-03-07 20:34:33 -0500779 RetransmitUnackedPackets(ALL_UNACKED_RETRANSMISSION);
780}
781
dschinazi244f6dc2019-05-06 15:45:16 -0700782// Handles retry for client connection.
783void QuicConnection::OnRetryPacket(QuicConnectionId original_connection_id,
784 QuicConnectionId new_connection_id,
785 QuicStringPiece retry_token) {
dschinazi6ece5002019-05-22 06:35:49 -0700786 DCHECK_EQ(Perspective::IS_CLIENT, perspective_);
dschinazi7b9278c2019-05-20 07:36:21 -0700787 if (original_connection_id != server_connection_id_) {
dschinazi244f6dc2019-05-06 15:45:16 -0700788 QUIC_DLOG(ERROR) << "Ignoring RETRY with original connection ID "
789 << original_connection_id << " not matching expected "
dschinazi7b9278c2019-05-20 07:36:21 -0700790 << server_connection_id_ << " token "
dschinazi244f6dc2019-05-06 15:45:16 -0700791 << QuicTextUtils::HexEncode(retry_token);
792 return;
793 }
794 if (retry_has_been_parsed_) {
795 QUIC_DLOG(ERROR) << "Ignoring non-first RETRY with token "
796 << QuicTextUtils::HexEncode(retry_token);
797 return;
798 }
799 retry_has_been_parsed_ = true;
800 QUIC_DLOG(INFO) << "Received RETRY, replacing connection ID "
dschinazi7b9278c2019-05-20 07:36:21 -0700801 << server_connection_id_ << " with " << new_connection_id
dschinazi244f6dc2019-05-06 15:45:16 -0700802 << ", received token "
803 << QuicTextUtils::HexEncode(retry_token);
dschinazi7b9278c2019-05-20 07:36:21 -0700804 server_connection_id_ = new_connection_id;
805 packet_generator_.SetServerConnectionId(server_connection_id_);
dschinazi244f6dc2019-05-06 15:45:16 -0700806 packet_generator_.SetRetryToken(retry_token);
807
808 // Reinstall initial crypters because the connection ID changed.
dschinazi6ece5002019-05-22 06:35:49 -0700809 InstallInitialCrypters();
dschinazi244f6dc2019-05-06 15:45:16 -0700810}
811
QUICHE teamc65d1d12019-03-19 20:58:04 -0700812bool QuicConnection::HasIncomingConnectionId(QuicConnectionId connection_id) {
813 for (QuicConnectionId const& incoming_connection_id :
814 incoming_connection_ids_) {
815 if (incoming_connection_id == connection_id) {
816 return true;
817 }
818 }
819 return false;
820}
821
822void QuicConnection::AddIncomingConnectionId(QuicConnectionId connection_id) {
823 if (HasIncomingConnectionId(connection_id)) {
824 return;
825 }
826 incoming_connection_ids_.push_back(connection_id);
827}
828
QUICHE teama6ef0a62019-03-07 20:34:33 -0500829bool QuicConnection::OnUnauthenticatedPublicHeader(
830 const QuicPacketHeader& header) {
QUICHE team2252b702019-05-14 23:55:14 -0400831 QuicConnectionId server_connection_id =
832 GetServerConnectionIdAsRecipient(header, perspective_);
833
dschinazi7b9278c2019-05-20 07:36:21 -0700834 if (server_connection_id == server_connection_id_ ||
QUICHE team2252b702019-05-14 23:55:14 -0400835 HasIncomingConnectionId(server_connection_id)) {
QUICHE teamc65d1d12019-03-19 20:58:04 -0700836 return true;
837 }
838
839 if (PacketCanReplaceConnectionId(header, perspective_)) {
840 QUIC_DLOG(INFO) << ENDPOINT << "Accepting packet with new connection ID "
dschinazi7b9278c2019-05-20 07:36:21 -0700841 << server_connection_id << " instead of "
842 << server_connection_id_;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500843 return true;
844 }
845
846 ++stats_.packets_dropped;
847 QUIC_DLOG(INFO) << ENDPOINT
848 << "Ignoring packet from unexpected ConnectionId: "
dschinazi7b9278c2019-05-20 07:36:21 -0700849 << server_connection_id << " instead of "
850 << server_connection_id_;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500851 if (debug_visitor_ != nullptr) {
QUICHE team2252b702019-05-14 23:55:14 -0400852 debug_visitor_->OnIncorrectConnectionId(server_connection_id);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500853 }
854 // If this is a server, the dispatcher routes each packet to the
855 // QuicConnection responsible for the packet's connection ID. So if control
856 // arrives here and this is a server, the dispatcher must be malfunctioning.
857 DCHECK_NE(Perspective::IS_SERVER, perspective_);
858 return false;
859}
860
861bool QuicConnection::OnUnauthenticatedHeader(const QuicPacketHeader& header) {
862 if (debug_visitor_ != nullptr) {
863 debug_visitor_->OnUnauthenticatedHeader(header);
864 }
865
866 // Check that any public reset packet with a different connection ID that was
867 // routed to this QuicConnection has been redirected before control reaches
868 // here.
QUICHE team2252b702019-05-14 23:55:14 -0400869 DCHECK(GetServerConnectionIdAsRecipient(header, perspective_) ==
dschinazi7b9278c2019-05-20 07:36:21 -0700870 server_connection_id_ ||
QUICHE team2252b702019-05-14 23:55:14 -0400871 HasIncomingConnectionId(
872 GetServerConnectionIdAsRecipient(header, perspective_)) ||
QUICHE teamc65d1d12019-03-19 20:58:04 -0700873 PacketCanReplaceConnectionId(header, perspective_));
QUICHE teama6ef0a62019-03-07 20:34:33 -0500874
875 if (!packet_generator_.IsPendingPacketEmpty()) {
876 // Incoming packets may change a queued ACK frame.
vasilvvc48c8712019-03-11 13:38:16 -0700877 const std::string error_details =
QUICHE teama6ef0a62019-03-07 20:34:33 -0500878 "Pending frames must be serialized before incoming packets are "
879 "processed.";
880 QUIC_BUG << error_details << ", received header: " << header;
881 CloseConnection(QUIC_INTERNAL_ERROR, error_details,
882 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
883 return false;
884 }
885
886 // If this packet has already been seen, or the sender has told us that it
887 // will not be retransmitted, then stop processing the packet.
QUICHE teamb23daa72019-03-21 08:37:48 -0700888 if (!validate_packet_number_post_decryption_) {
889 const bool is_awaiting =
890 use_uber_received_packet_manager_
891 ? uber_received_packet_manager_.IsAwaitingPacket(
QUICHE team1dfa46b2019-03-22 10:39:10 -0700892 last_decrypted_packet_level_, header.packet_number)
QUICHE teamb23daa72019-03-21 08:37:48 -0700893 : received_packet_manager_.IsAwaitingPacket(header.packet_number);
894 if (!is_awaiting) {
895 if (framer_.IsIetfStatelessResetPacket(header)) {
896 QuicIetfStatelessResetPacket packet(
897 header, header.possible_stateless_reset_token);
898 OnAuthenticatedIetfStatelessResetPacket(packet);
899 return false;
900 }
901 QUIC_DLOG(INFO) << ENDPOINT << "Packet " << header.packet_number
902 << " no longer being waited for. Discarding.";
903 if (debug_visitor_ != nullptr) {
904 debug_visitor_->OnDuplicatePacket(header.packet_number);
905 }
906 ++stats_.packets_dropped;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500907 return false;
908 }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500909 }
910
911 if (version_negotiation_state_ != NEGOTIATED_VERSION &&
912 perspective_ == Perspective::IS_SERVER) {
913 if (!header.version_flag) {
914 // Packets should have the version flag till version negotiation is
915 // done.
vasilvvc48c8712019-03-11 13:38:16 -0700916 std::string error_details =
QUICHE teama6ef0a62019-03-07 20:34:33 -0500917 QuicStrCat(ENDPOINT, "Packet ", header.packet_number.ToUint64(),
918 " without version flag before version negotiated.");
919 QUIC_DLOG(WARNING) << error_details;
920 CloseConnection(QUIC_INVALID_VERSION, error_details,
921 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
922 return false;
923 } else {
924 DCHECK_EQ(header.version, version());
925 version_negotiation_state_ = NEGOTIATED_VERSION;
926 framer_.InferPacketHeaderTypeFromVersion();
927 visitor_->OnSuccessfulVersionNegotiation(version());
928 if (debug_visitor_ != nullptr) {
929 debug_visitor_->OnSuccessfulVersionNegotiation(version());
930 }
931 }
932 DCHECK_EQ(NEGOTIATED_VERSION, version_negotiation_state_);
933 }
934
935 return true;
936}
937
938void QuicConnection::OnDecryptedPacket(EncryptionLevel level) {
939 last_decrypted_packet_level_ = level;
940 last_packet_decrypted_ = true;
941
942 // Once the server receives a forward secure packet, the handshake is
943 // confirmed.
944 if (level == ENCRYPTION_FORWARD_SECURE &&
945 perspective_ == Perspective::IS_SERVER) {
946 sent_packet_manager_.SetHandshakeConfirmed();
947 if (sent_packet_manager_.unacked_packets().use_uber_loss_algorithm()) {
948 // This may have changed the retransmission timer, so re-arm it.
949 SetRetransmissionAlarm();
950 }
951 }
952}
953
954QuicSocketAddress QuicConnection::GetEffectivePeerAddressFromCurrentPacket()
955 const {
956 // By default, the connection is not proxied, and the effective peer address
957 // is the packet's source address, i.e. the direct peer address.
958 return last_packet_source_address_;
959}
960
961bool QuicConnection::OnPacketHeader(const QuicPacketHeader& header) {
962 if (debug_visitor_ != nullptr) {
963 debug_visitor_->OnPacketHeader(header);
964 }
965
966 // Will be decremented below if we fall through to return true.
967 ++stats_.packets_dropped;
968
969 if (!ProcessValidatedPacket(header)) {
970 return false;
971 }
972
973 // Initialize the current packet content state.
974 current_packet_content_ = NO_FRAMES_RECEIVED;
975 is_current_packet_connectivity_probing_ = false;
976 current_effective_peer_migration_type_ = NO_CHANGE;
977
978 if (perspective_ == Perspective::IS_CLIENT) {
QUICHE team1f3de242019-03-20 07:24:48 -0700979 if (!GetLargestReceivedPacket().IsInitialized() ||
980 header.packet_number > GetLargestReceivedPacket()) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500981 // Update peer_address_ and effective_peer_address_ immediately for
982 // client connections.
QUICHE team1f3de242019-03-20 07:24:48 -0700983 // TODO(fayang): only change peer addresses in application data packet
984 // number space.
QUICHE teama6ef0a62019-03-07 20:34:33 -0500985 direct_peer_address_ = last_packet_source_address_;
986 effective_peer_address_ = GetEffectivePeerAddressFromCurrentPacket();
987 }
988 } else {
989 // At server, remember the address change type of effective_peer_address
990 // in current_effective_peer_migration_type_. But this variable alone
991 // doesn't necessarily starts a migration. A migration will be started
992 // later, once the current packet is confirmed to meet the following
993 // conditions:
994 // 1) current_effective_peer_migration_type_ is not NO_CHANGE.
995 // 2) The current packet is not a connectivity probing.
996 // 3) The current packet is not reordered, i.e. its packet number is the
997 // largest of this connection so far.
998 // Once the above conditions are confirmed, a new migration will start
999 // even if there is an active migration underway.
1000 current_effective_peer_migration_type_ =
1001 QuicUtils::DetermineAddressChangeType(
1002 effective_peer_address_,
1003 GetEffectivePeerAddressFromCurrentPacket());
1004
1005 QUIC_DLOG_IF(INFO, current_effective_peer_migration_type_ != NO_CHANGE)
1006 << ENDPOINT << "Effective peer's ip:port changed from "
1007 << effective_peer_address_.ToString() << " to "
1008 << GetEffectivePeerAddressFromCurrentPacket().ToString()
1009 << ", active_effective_peer_migration_type is "
1010 << active_effective_peer_migration_type_;
1011 }
1012
1013 --stats_.packets_dropped;
1014 QUIC_DVLOG(1) << ENDPOINT << "Received packet header: " << header;
1015 last_header_ = header;
1016 // An ack will be sent if a missing retransmittable packet was received;
QUICHE teamb23daa72019-03-21 08:37:48 -07001017 if (!use_uber_received_packet_manager_) {
1018 was_last_packet_missing_ =
1019 received_packet_manager_.IsMissing(last_header_.packet_number);
1020 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001021
1022 // Record packet receipt to populate ack info before processing stream
1023 // frames, since the processing may result in sending a bundled ack.
QUICHE teamb23daa72019-03-21 08:37:48 -07001024 if (use_uber_received_packet_manager_) {
1025 uber_received_packet_manager_.RecordPacketReceived(
QUICHE team1dfa46b2019-03-22 10:39:10 -07001026 last_decrypted_packet_level_, last_header_,
1027 time_of_last_received_packet_);
QUICHE teamb23daa72019-03-21 08:37:48 -07001028 } else {
1029 received_packet_manager_.RecordPacketReceived(
1030 last_header_, time_of_last_received_packet_);
1031 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001032 DCHECK(connected_);
1033 return true;
1034}
1035
1036bool QuicConnection::OnStreamFrame(const QuicStreamFrame& frame) {
1037 DCHECK(connected_);
1038
1039 // Since a stream frame was received, this is not a connectivity probe.
1040 // A probe only contains a PING and full padding.
1041 UpdatePacketContent(NOT_PADDED_PING);
1042
1043 if (debug_visitor_ != nullptr) {
1044 debug_visitor_->OnStreamFrame(frame);
1045 }
nharper46833c32019-05-15 21:33:05 -07001046 if (!QuicUtils::IsCryptoStreamId(transport_version(), frame.stream_id) &&
QUICHE team6987b4a2019-03-15 16:23:04 -07001047 last_decrypted_packet_level_ == ENCRYPTION_INITIAL) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001048 if (MaybeConsiderAsMemoryCorruption(frame)) {
1049 CloseConnection(QUIC_MAYBE_CORRUPTED_MEMORY,
1050 "Received crypto frame on non crypto stream.",
1051 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
1052 return false;
1053 }
1054
1055 QUIC_PEER_BUG << ENDPOINT
1056 << "Received an unencrypted data frame: closing connection"
1057 << " packet_number:" << last_header_.packet_number
QUICHE teamb23daa72019-03-21 08:37:48 -07001058 << " stream_id:" << frame.stream_id
fayang21ffb712019-05-16 08:39:26 -07001059 << " received_packets:" << ack_frame();
QUICHE teama6ef0a62019-03-07 20:34:33 -05001060 CloseConnection(QUIC_UNENCRYPTED_STREAM_DATA,
1061 "Unencrypted stream data seen.",
1062 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
1063 return false;
1064 }
1065 visitor_->OnStreamFrame(frame);
1066 stats_.stream_bytes_received += frame.data_length;
1067 should_last_packet_instigate_acks_ = true;
1068 return connected_;
1069}
1070
1071bool QuicConnection::OnCryptoFrame(const QuicCryptoFrame& frame) {
1072 DCHECK(connected_);
1073
1074 // Since a CRYPTO frame was received, this is not a connectivity probe.
1075 // A probe only contains a PING and full padding.
1076 UpdatePacketContent(NOT_PADDED_PING);
1077
1078 visitor_->OnCryptoFrame(frame);
1079 should_last_packet_instigate_acks_ = true;
1080 return connected_;
1081}
1082
1083bool QuicConnection::OnAckFrameStart(QuicPacketNumber largest_acked,
1084 QuicTime::Delta ack_delay_time) {
1085 DCHECK(connected_);
1086
1087 if (processing_ack_frame_) {
1088 CloseConnection(QUIC_INVALID_ACK_DATA,
1089 "Received a new ack while processing an ack frame.",
1090 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
1091 return false;
1092 }
1093
1094 // Since an ack frame was received, this is not a connectivity probe.
1095 // A probe only contains a PING and full padding.
1096 UpdatePacketContent(NOT_PADDED_PING);
1097
1098 QUIC_DVLOG(1) << ENDPOINT
1099 << "OnAckFrameStart, largest_acked: " << largest_acked;
1100
QUICHE team76e1c622019-03-19 14:36:39 -07001101 if (GetLargestReceivedPacketWithAck().IsInitialized() &&
1102 last_header_.packet_number <= GetLargestReceivedPacketWithAck()) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001103 QUIC_DLOG(INFO) << ENDPOINT << "Received an old ack frame: ignoring";
1104 return true;
1105 }
1106
QUICHE team76e1c622019-03-19 14:36:39 -07001107 if (!GetLargestSentPacket().IsInitialized() ||
1108 largest_acked > GetLargestSentPacket()) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001109 QUIC_DLOG(WARNING) << ENDPOINT
1110 << "Peer's observed unsent packet:" << largest_acked
QUICHE team76e1c622019-03-19 14:36:39 -07001111 << " vs " << GetLargestSentPacket();
QUICHE teama6ef0a62019-03-07 20:34:33 -05001112 // We got an ack for data we have not sent.
1113 CloseConnection(QUIC_INVALID_ACK_DATA, "Largest observed too high.",
1114 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
1115 return false;
1116 }
1117
QUICHE team76e1c622019-03-19 14:36:39 -07001118 if (!GetLargestAckedPacket().IsInitialized() ||
1119 largest_acked > GetLargestAckedPacket()) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001120 visitor_->OnForwardProgressConfirmed();
QUICHE team9929cc42019-03-13 08:17:43 -07001121 } else if (!sent_packet_manager_.tolerate_reneging() &&
QUICHE team76e1c622019-03-19 14:36:39 -07001122 largest_acked < GetLargestAckedPacket()) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001123 QUIC_LOG(INFO) << ENDPOINT << "Peer's largest_observed packet decreased:"
QUICHE team76e1c622019-03-19 14:36:39 -07001124 << largest_acked << " vs " << GetLargestAckedPacket()
QUICHE teama6ef0a62019-03-07 20:34:33 -05001125 << " packet_number:" << last_header_.packet_number
QUICHE team76e1c622019-03-19 14:36:39 -07001126 << " largest seen with ack:"
1127 << GetLargestReceivedPacketWithAck()
dschinazi7b9278c2019-05-20 07:36:21 -07001128 << " server_connection_id: " << server_connection_id_;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001129 // A new ack has a diminished largest_observed value.
1130 // If this was an old packet, we wouldn't even have checked.
1131 CloseConnection(QUIC_INVALID_ACK_DATA, "Largest observed too low.",
1132 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
1133 return false;
1134 }
1135 processing_ack_frame_ = true;
1136 sent_packet_manager_.OnAckFrameStart(largest_acked, ack_delay_time,
1137 time_of_last_received_packet_);
1138 return true;
1139}
1140
1141bool QuicConnection::OnAckRange(QuicPacketNumber start, QuicPacketNumber end) {
1142 DCHECK(connected_);
1143 QUIC_DVLOG(1) << ENDPOINT << "OnAckRange: [" << start << ", " << end << ")";
1144
QUICHE team76e1c622019-03-19 14:36:39 -07001145 if (GetLargestReceivedPacketWithAck().IsInitialized() &&
1146 last_header_.packet_number <= GetLargestReceivedPacketWithAck()) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001147 QUIC_DLOG(INFO) << ENDPOINT << "Received an old ack frame: ignoring";
1148 return true;
1149 }
1150
1151 sent_packet_manager_.OnAckRange(start, end);
1152 return true;
1153}
1154
1155bool QuicConnection::OnAckTimestamp(QuicPacketNumber packet_number,
1156 QuicTime timestamp) {
1157 DCHECK(connected_);
1158 QUIC_DVLOG(1) << ENDPOINT << "OnAckTimestamp: [" << packet_number << ", "
1159 << timestamp.ToDebuggingValue() << ")";
1160
QUICHE team76e1c622019-03-19 14:36:39 -07001161 if (GetLargestReceivedPacketWithAck().IsInitialized() &&
1162 last_header_.packet_number <= GetLargestReceivedPacketWithAck()) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001163 QUIC_DLOG(INFO) << ENDPOINT << "Received an old ack frame: ignoring";
1164 return true;
1165 }
1166
1167 sent_packet_manager_.OnAckTimestamp(packet_number, timestamp);
1168 return true;
1169}
1170
1171bool QuicConnection::OnAckFrameEnd(QuicPacketNumber start) {
1172 DCHECK(connected_);
1173 QUIC_DVLOG(1) << ENDPOINT << "OnAckFrameEnd, start: " << start;
1174
QUICHE team76e1c622019-03-19 14:36:39 -07001175 if (GetLargestReceivedPacketWithAck().IsInitialized() &&
1176 last_header_.packet_number <= GetLargestReceivedPacketWithAck()) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001177 QUIC_DLOG(INFO) << ENDPOINT << "Received an old ack frame: ignoring";
1178 return true;
1179 }
fayang3eb82212019-04-16 12:05:46 -07001180 const AckResult ack_result = sent_packet_manager_.OnAckFrameEnd(
1181 time_of_last_received_packet_, last_decrypted_packet_level_);
1182 if (ack_result != PACKETS_NEWLY_ACKED &&
1183 ack_result != NO_PACKETS_NEWLY_ACKED) {
1184 // Error occurred (e.g., this ACK tries to ack packets in wrong packet
1185 // number space), and this would cause the connection to be closed.
1186 QUIC_DLOG(ERROR) << ENDPOINT
1187 << "Error occurred when processing an ACK frame: "
1188 << QuicUtils::AckResultToString(ack_result);
1189 return false;
1190 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001191 // Cancel the send alarm because new packets likely have been acked, which
1192 // may change the congestion window and/or pacing rate. Canceling the alarm
1193 // causes CanWrite to recalculate the next send time.
1194 if (send_alarm_->IsSet()) {
1195 send_alarm_->Cancel();
1196 }
1197 if (supports_release_time_) {
1198 // Update pace time into future because smoothed RTT is likely updated.
1199 UpdateReleaseTimeIntoFuture();
1200 }
QUICHE team76e1c622019-03-19 14:36:39 -07001201 SetLargestReceivedPacketWithAck(last_header_.packet_number);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001202 // If the incoming ack's packets set expresses missing packets: peer is still
1203 // waiting for a packet lower than a packet that we are no longer planning to
1204 // send.
1205 // If the incoming ack's packets set expresses received packets: peer is still
1206 // acking packets which we never care about.
1207 // Send an ack to raise the high water mark.
fayang03916692019-05-22 17:57:18 -07001208 bool send_stop_waiting = GetLeastUnacked() > start;
1209 if (GetQuicReloadableFlag(quic_simplify_stop_waiting) &&
1210 no_stop_waiting_frames_) {
1211 QUIC_RELOADABLE_FLAG_COUNT(quic_simplify_stop_waiting);
1212 send_stop_waiting = false;
1213 }
1214 PostProcessAfterAckFrame(send_stop_waiting,
fayang3eb82212019-04-16 12:05:46 -07001215 ack_result == PACKETS_NEWLY_ACKED);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001216 processing_ack_frame_ = false;
1217
1218 return connected_;
1219}
1220
1221bool QuicConnection::OnStopWaitingFrame(const QuicStopWaitingFrame& frame) {
1222 DCHECK(connected_);
1223
1224 // Since a stop waiting frame was received, this is not a connectivity probe.
1225 // A probe only contains a PING and full padding.
1226 UpdatePacketContent(NOT_PADDED_PING);
1227
1228 if (no_stop_waiting_frames_) {
1229 return true;
1230 }
1231 if (largest_seen_packet_with_stop_waiting_.IsInitialized() &&
1232 last_header_.packet_number <= largest_seen_packet_with_stop_waiting_) {
1233 QUIC_DLOG(INFO) << ENDPOINT
1234 << "Received an old stop waiting frame: ignoring";
1235 return true;
1236 }
1237
1238 const char* error = ValidateStopWaitingFrame(frame);
1239 if (error != nullptr) {
1240 CloseConnection(QUIC_INVALID_STOP_WAITING_DATA, error,
1241 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
1242 return false;
1243 }
1244
1245 if (debug_visitor_ != nullptr) {
1246 debug_visitor_->OnStopWaitingFrame(frame);
1247 }
1248
1249 largest_seen_packet_with_stop_waiting_ = last_header_.packet_number;
QUICHE teamb23daa72019-03-21 08:37:48 -07001250 if (use_uber_received_packet_manager_) {
QUICHE team1dfa46b2019-03-22 10:39:10 -07001251 uber_received_packet_manager_.DontWaitForPacketsBefore(
1252 last_decrypted_packet_level_, frame.least_unacked);
QUICHE teamb23daa72019-03-21 08:37:48 -07001253 } else {
1254 received_packet_manager_.DontWaitForPacketsBefore(frame.least_unacked);
1255 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001256 return connected_;
1257}
1258
1259bool QuicConnection::OnPaddingFrame(const QuicPaddingFrame& frame) {
1260 DCHECK(connected_);
1261 UpdatePacketContent(SECOND_FRAME_IS_PADDING);
1262
1263 if (debug_visitor_ != nullptr) {
1264 debug_visitor_->OnPaddingFrame(frame);
1265 }
1266 return true;
1267}
1268
1269bool QuicConnection::OnPingFrame(const QuicPingFrame& frame) {
1270 DCHECK(connected_);
1271 UpdatePacketContent(FIRST_FRAME_IS_PING);
1272
1273 if (debug_visitor_ != nullptr) {
1274 debug_visitor_->OnPingFrame(frame);
1275 }
1276 should_last_packet_instigate_acks_ = true;
1277 return true;
1278}
1279
QUICHE teama6ef0a62019-03-07 20:34:33 -05001280const char* QuicConnection::ValidateStopWaitingFrame(
1281 const QuicStopWaitingFrame& stop_waiting) {
QUICHE teamb23daa72019-03-21 08:37:48 -07001282 const QuicPacketNumber peer_least_packet_awaiting_ack =
1283 use_uber_received_packet_manager_
1284 ? uber_received_packet_manager_.peer_least_packet_awaiting_ack()
1285 : received_packet_manager_.peer_least_packet_awaiting_ack();
1286 if (peer_least_packet_awaiting_ack.IsInitialized() &&
1287 stop_waiting.least_unacked < peer_least_packet_awaiting_ack) {
1288 QUIC_DLOG(ERROR) << ENDPOINT << "Peer's sent low least_unacked: "
1289 << stop_waiting.least_unacked << " vs "
1290 << peer_least_packet_awaiting_ack;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001291 // We never process old ack frames, so this number should only increase.
1292 return "Least unacked too small.";
1293 }
1294
1295 if (stop_waiting.least_unacked > last_header_.packet_number) {
1296 QUIC_DLOG(ERROR) << ENDPOINT
1297 << "Peer sent least_unacked:" << stop_waiting.least_unacked
1298 << " greater than the enclosing packet number:"
1299 << last_header_.packet_number;
1300 return "Least unacked too large.";
1301 }
1302
1303 return nullptr;
1304}
1305
1306bool QuicConnection::OnRstStreamFrame(const QuicRstStreamFrame& frame) {
1307 DCHECK(connected_);
1308
1309 // Since a reset stream frame was received, this is not a connectivity probe.
1310 // A probe only contains a PING and full padding.
1311 UpdatePacketContent(NOT_PADDED_PING);
1312
1313 if (debug_visitor_ != nullptr) {
1314 debug_visitor_->OnRstStreamFrame(frame);
1315 }
1316 QUIC_DLOG(INFO) << ENDPOINT
1317 << "RST_STREAM_FRAME received for stream: " << frame.stream_id
1318 << " with error: "
1319 << QuicRstStreamErrorCodeToString(frame.error_code);
1320 visitor_->OnRstStream(frame);
1321 should_last_packet_instigate_acks_ = true;
1322 return connected_;
1323}
1324
QUICHE teama6ef0a62019-03-07 20:34:33 -05001325bool QuicConnection::OnStopSendingFrame(const QuicStopSendingFrame& frame) {
1326 DCHECK(connected_);
1327
1328 // Since a reset stream frame was received, this is not a connectivity probe.
1329 // A probe only contains a PING and full padding.
1330 UpdatePacketContent(NOT_PADDED_PING);
1331
1332 if (debug_visitor_ != nullptr) {
1333 debug_visitor_->OnStopSendingFrame(frame);
1334 }
1335
1336 QUIC_DLOG(INFO) << ENDPOINT << "STOP_SENDING frame received for stream: "
1337 << frame.stream_id
1338 << " with error: " << frame.application_error_code;
1339
1340 visitor_->OnStopSendingFrame(frame);
1341 return connected_;
1342}
1343
1344bool QuicConnection::OnPathChallengeFrame(const QuicPathChallengeFrame& frame) {
1345 // Save the path challenge's payload, for later use in generating the
1346 // response.
1347 received_path_challenge_payloads_.push_back(frame.data_buffer);
1348
1349 // For VERSION 99 we define a "Padded PATH CHALLENGE" to be the same thing
1350 // as a PADDED PING -- it will start a connectivity check and prevent
1351 // connection migration. Insofar as the connectivity check and connection
1352 // migration are concerned, logically the PATH CHALLENGE is the same as the
1353 // PING, so as a stopgap, tell the FSM that determines whether we have a
1354 // Padded PING or not that we received a PING.
1355 UpdatePacketContent(FIRST_FRAME_IS_PING);
1356 should_last_packet_instigate_acks_ = true;
1357 return true;
1358}
1359
1360bool QuicConnection::OnPathResponseFrame(const QuicPathResponseFrame& frame) {
1361 should_last_packet_instigate_acks_ = true;
1362 if (!transmitted_connectivity_probe_payload_ ||
1363 *transmitted_connectivity_probe_payload_ != frame.data_buffer) {
1364 // Is not for the probe we sent, ignore it.
1365 return true;
1366 }
1367 // Have received the matching PATH RESPONSE, saved payload no longer valid.
1368 transmitted_connectivity_probe_payload_ = nullptr;
1369 UpdatePacketContent(FIRST_FRAME_IS_PING);
1370 return true;
1371}
1372
1373bool QuicConnection::OnConnectionCloseFrame(
1374 const QuicConnectionCloseFrame& frame) {
1375 DCHECK(connected_);
1376
1377 // Since a connection close frame was received, this is not a connectivity
1378 // probe. A probe only contains a PING and full padding.
1379 UpdatePacketContent(NOT_PADDED_PING);
1380
1381 if (debug_visitor_ != nullptr) {
1382 debug_visitor_->OnConnectionCloseFrame(frame);
1383 }
1384 QUIC_DLOG(INFO) << ENDPOINT << "Received ConnectionClose for connection: "
fkastenholze9d71a82019-04-09 05:12:13 -07001385 << connection_id() << ", with error: "
1386 << QuicErrorCodeToString(frame.quic_error_code) << " ("
1387 << frame.error_details << ")";
1388 if (frame.close_type == GOOGLE_QUIC_CONNECTION_CLOSE &&
1389 frame.quic_error_code == QUIC_BAD_MULTIPATH_FLAG) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001390 QUIC_LOG_FIRST_N(ERROR, 10) << "Unexpected QUIC_BAD_MULTIPATH_FLAG error."
1391 << " last_received_header: " << last_header_
1392 << " encryption_level: " << encryption_level_;
1393 }
fkastenholze9d71a82019-04-09 05:12:13 -07001394 TearDownLocalConnectionState(frame.quic_error_code, frame.error_details,
QUICHE teama6ef0a62019-03-07 20:34:33 -05001395 ConnectionCloseSource::FROM_PEER);
1396 return connected_;
1397}
1398
fkastenholz3c4eabf2019-04-22 07:49:59 -07001399bool QuicConnection::OnMaxStreamsFrame(const QuicMaxStreamsFrame& frame) {
1400 return visitor_->OnMaxStreamsFrame(frame);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001401}
1402
fkastenholz3c4eabf2019-04-22 07:49:59 -07001403bool QuicConnection::OnStreamsBlockedFrame(
1404 const QuicStreamsBlockedFrame& frame) {
1405 return visitor_->OnStreamsBlockedFrame(frame);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001406}
1407
1408bool QuicConnection::OnGoAwayFrame(const QuicGoAwayFrame& frame) {
1409 DCHECK(connected_);
1410
1411 // Since a go away frame was received, this is not a connectivity probe.
1412 // A probe only contains a PING and full padding.
1413 UpdatePacketContent(NOT_PADDED_PING);
1414
1415 if (debug_visitor_ != nullptr) {
1416 debug_visitor_->OnGoAwayFrame(frame);
1417 }
1418 QUIC_DLOG(INFO) << ENDPOINT << "GOAWAY_FRAME received with last good stream: "
1419 << frame.last_good_stream_id
1420 << " and error: " << QuicErrorCodeToString(frame.error_code)
1421 << " and reason: " << frame.reason_phrase;
1422
1423 visitor_->OnGoAway(frame);
1424 should_last_packet_instigate_acks_ = true;
1425 return connected_;
1426}
1427
1428bool QuicConnection::OnWindowUpdateFrame(const QuicWindowUpdateFrame& frame) {
1429 DCHECK(connected_);
1430
1431 // Since a window update frame was received, this is not a connectivity probe.
1432 // A probe only contains a PING and full padding.
1433 UpdatePacketContent(NOT_PADDED_PING);
1434
1435 if (debug_visitor_ != nullptr) {
1436 debug_visitor_->OnWindowUpdateFrame(frame, time_of_last_received_packet_);
1437 }
1438 QUIC_DLOG(INFO) << ENDPOINT << "WINDOW_UPDATE_FRAME received for stream: "
1439 << frame.stream_id
1440 << " with byte offset: " << frame.byte_offset;
1441 visitor_->OnWindowUpdateFrame(frame);
1442 should_last_packet_instigate_acks_ = true;
1443 return connected_;
1444}
1445
1446bool QuicConnection::OnNewConnectionIdFrame(
1447 const QuicNewConnectionIdFrame& frame) {
1448 return true;
1449}
1450
1451bool QuicConnection::OnRetireConnectionIdFrame(
1452 const QuicRetireConnectionIdFrame& frame) {
1453 return true;
1454}
1455
1456bool QuicConnection::OnNewTokenFrame(const QuicNewTokenFrame& frame) {
1457 return true;
1458}
1459
1460bool QuicConnection::OnMessageFrame(const QuicMessageFrame& frame) {
1461 DCHECK(connected_);
1462
1463 // Since a message frame was received, this is not a connectivity probe.
1464 // A probe only contains a PING and full padding.
1465 UpdatePacketContent(NOT_PADDED_PING);
1466
1467 if (debug_visitor_ != nullptr) {
1468 debug_visitor_->OnMessageFrame(frame);
1469 }
1470 visitor_->OnMessageReceived(
1471 QuicStringPiece(frame.data, frame.message_length));
1472 should_last_packet_instigate_acks_ = true;
1473 return connected_;
1474}
1475
1476bool QuicConnection::OnBlockedFrame(const QuicBlockedFrame& frame) {
1477 DCHECK(connected_);
1478
1479 // Since a blocked frame was received, this is not a connectivity probe.
1480 // A probe only contains a PING and full padding.
1481 UpdatePacketContent(NOT_PADDED_PING);
1482
1483 if (debug_visitor_ != nullptr) {
1484 debug_visitor_->OnBlockedFrame(frame);
1485 }
1486 QUIC_DLOG(INFO) << ENDPOINT
1487 << "BLOCKED_FRAME received for stream: " << frame.stream_id;
1488 visitor_->OnBlockedFrame(frame);
1489 stats_.blocked_frames_received++;
1490 should_last_packet_instigate_acks_ = true;
1491 return connected_;
1492}
1493
1494void QuicConnection::OnPacketComplete() {
1495 // Don't do anything if this packet closed the connection.
1496 if (!connected_) {
1497 ClearLastFrames();
1498 return;
1499 }
1500
1501 if (IsCurrentPacketConnectivityProbing()) {
1502 ++stats_.num_connectivity_probing_received;
1503 }
1504
1505 QUIC_DVLOG(1) << ENDPOINT << "Got packet " << last_header_.packet_number
QUICHE team2252b702019-05-14 23:55:14 -04001506 << " for "
1507 << GetServerConnectionIdAsRecipient(last_header_, perspective_);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001508
1509 QUIC_DLOG_IF(INFO, current_packet_content_ == SECOND_FRAME_IS_PADDING)
1510 << ENDPOINT << "Received a padded PING packet. is_probing: "
1511 << IsCurrentPacketConnectivityProbing();
1512
1513 if (perspective_ == Perspective::IS_CLIENT) {
1514 QUIC_DVLOG(1) << ENDPOINT
1515 << "Received a speculative connectivity probing packet for "
QUICHE team2252b702019-05-14 23:55:14 -04001516 << GetServerConnectionIdAsRecipient(last_header_,
1517 perspective_)
QUICHE teama6ef0a62019-03-07 20:34:33 -05001518 << " from ip:port: " << last_packet_source_address_.ToString()
1519 << " to ip:port: "
1520 << last_packet_destination_address_.ToString();
1521 // TODO(zhongyi): change the method name.
1522 visitor_->OnConnectivityProbeReceived(last_packet_destination_address_,
1523 last_packet_source_address_);
1524 } else if (IsCurrentPacketConnectivityProbing()) {
1525 // This node is not a client (is a server) AND the received packet was
1526 // connectivity-probing, send an appropriate response.
1527 QUIC_DVLOG(1) << ENDPOINT << "Received a connectivity probing packet for "
QUICHE team2252b702019-05-14 23:55:14 -04001528 << GetServerConnectionIdAsRecipient(last_header_,
1529 perspective_)
QUICHE teama6ef0a62019-03-07 20:34:33 -05001530 << " from ip:port: " << last_packet_source_address_.ToString()
1531 << " to ip:port: "
1532 << last_packet_destination_address_.ToString();
1533 visitor_->OnConnectivityProbeReceived(last_packet_destination_address_,
1534 last_packet_source_address_);
1535 } else {
1536 // This node is not a client (is a server) AND the received packet was
1537 // NOT connectivity-probing. If the packet had PATH CHALLENGES, send
1538 // appropriate RESPONSE. Then deal with possible peer migration.
1539 if (transport_version() == QUIC_VERSION_99 &&
1540 !received_path_challenge_payloads_.empty()) {
1541 // If a PATH CHALLENGE was in a "Padded PING (or PATH CHALLENGE)"
1542 // then it is taken care of above. This handles the case where a PATH
1543 // CHALLENGE appeared someplace else (eg, the peer randomly added a PATH
1544 // CHALLENGE frame to some other packet.
1545 // There was at least one PATH CHALLENGE in the received packet,
1546 // Generate the required PATH RESPONSE.
1547 SendGenericPathProbePacket(nullptr, last_packet_source_address_,
1548 /* is_response= */ true);
1549 }
1550
QUICHE team1f3de242019-03-20 07:24:48 -07001551 if (last_header_.packet_number == GetLargestReceivedPacket()) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001552 direct_peer_address_ = last_packet_source_address_;
1553 if (current_effective_peer_migration_type_ != NO_CHANGE) {
QUICHE team1f3de242019-03-20 07:24:48 -07001554 // TODO(fayang): When multiple packet number spaces is supported, only
1555 // start peer migration for the application data.
QUICHE teama6ef0a62019-03-07 20:34:33 -05001556 StartEffectivePeerMigration(current_effective_peer_migration_type_);
1557 }
1558 }
1559 }
1560
1561 current_effective_peer_migration_type_ = NO_CHANGE;
1562
1563 // An ack will be sent if a missing retransmittable packet was received;
1564 const bool was_missing =
1565 should_last_packet_instigate_acks_ && was_last_packet_missing_;
1566
1567 if (received_packet_manager_.decide_when_to_send_acks()) {
QUICHE teamb23daa72019-03-21 08:37:48 -07001568 if (use_uber_received_packet_manager_) {
dschinazi05e62b12019-04-18 15:43:41 -07001569 // Some encryption levels share a packet number space, it is therefore
1570 // possible for us to want to ack some packets even though we do not yet
1571 // have the appropriate keys to encrypt the acks. In this scenario we
1572 // do not update the ACK timeout. This can happen for example with
1573 // IETF QUIC on the server when we receive 0-RTT packets and do not yet
1574 // have 1-RTT keys (0-RTT packets are acked at the 1-RTT level).
1575 // Note that this could cause slight performance degradations in the edge
1576 // case where one packet is received, then the encrypter is installed,
1577 // then a second packet is received; as that could cause the ACK for the
1578 // second packet to be delayed instead of immediate. This is currently
1579 // considered to be small enough of an edge case to not be optimized for.
fayangde00f8f2019-04-25 09:01:27 -07001580 if (!SupportsMultiplePacketNumberSpaces() ||
1581 framer_.HasEncrypterOfEncryptionLevel(QuicUtils::GetEncryptionLevel(
dschinazi05e62b12019-04-18 15:43:41 -07001582 QuicUtils::GetPacketNumberSpace(last_decrypted_packet_level_)))) {
1583 uber_received_packet_manager_.MaybeUpdateAckTimeout(
1584 should_last_packet_instigate_acks_, last_decrypted_packet_level_,
1585 last_header_.packet_number, time_of_last_received_packet_,
1586 clock_->ApproximateNow(), sent_packet_manager_.GetRttStats(),
1587 sent_packet_manager_.delayed_ack_time());
1588 } else {
1589 QUIC_DLOG(INFO) << ENDPOINT << "Not updating ACK timeout for "
1590 << QuicUtils::EncryptionLevelToString(
1591 last_decrypted_packet_level_)
1592 << " as we do not have the corresponding encrypter";
1593 }
QUICHE teamb23daa72019-03-21 08:37:48 -07001594 } else {
1595 received_packet_manager_.MaybeUpdateAckTimeout(
1596 should_last_packet_instigate_acks_, last_header_.packet_number,
1597 time_of_last_received_packet_, clock_->ApproximateNow(),
1598 sent_packet_manager_.GetRttStats(),
1599 sent_packet_manager_.delayed_ack_time());
1600 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001601 } else if (ack_frame_updated()) {
1602 // It's possible the ack frame was sent along with response data, so it
1603 // no longer needs to be sent.
1604 MaybeQueueAck(was_missing);
1605 }
1606
1607 ClearLastFrames();
1608 CloseIfTooManyOutstandingSentPackets();
1609}
1610
1611bool QuicConnection::IsValidStatelessResetToken(QuicUint128 token) const {
1612 return stateless_reset_token_received_ &&
1613 token == received_stateless_reset_token_;
1614}
1615
1616void QuicConnection::OnAuthenticatedIetfStatelessResetPacket(
1617 const QuicIetfStatelessResetPacket& packet) {
1618 // TODO(fayang): Add OnAuthenticatedIetfStatelessResetPacket to
1619 // debug_visitor_.
vasilvvc48c8712019-03-11 13:38:16 -07001620 const std::string error_details = "Received stateless reset.";
QUICHE teama6ef0a62019-03-07 20:34:33 -05001621 QUIC_CODE_COUNT(quic_tear_down_local_connection_on_stateless_reset);
1622 TearDownLocalConnectionState(QUIC_PUBLIC_RESET, error_details,
1623 ConnectionCloseSource::FROM_PEER);
1624}
1625
1626void QuicConnection::MaybeQueueAck(bool was_missing) {
1627 DCHECK(!received_packet_manager_.decide_when_to_send_acks());
1628 ++num_packets_received_since_last_ack_sent_;
1629 // Determine whether the newly received packet was missing before recording
1630 // the received packet.
1631 if (was_missing) {
1632 // Only ack immediately if an ACK frame was sent with a larger
1633 // largest acked than the newly received packet number.
1634 const QuicPacketNumber largest_sent_largest_acked =
1635 sent_packet_manager_.unacked_packets().largest_sent_largest_acked();
1636 if (largest_sent_largest_acked.IsInitialized() &&
1637 last_header_.packet_number < largest_sent_largest_acked) {
1638 if (packet_generator_.deprecate_ack_bundling_mode()) {
1639 MaybeSetAckAlarmTo(clock_->ApproximateNow());
1640 } else {
1641 ack_queued_ = true;
1642 }
1643 }
1644 }
1645
1646 if (should_last_packet_instigate_acks_ && !ack_queued_) {
1647 ++num_retransmittable_packets_received_since_last_ack_sent_;
1648 if (ack_mode_ != TCP_ACKING &&
1649 last_header_.packet_number >=
1650 received_packet_manager_.PeerFirstSendingPacketNumber() +
1651 min_received_before_ack_decimation_) {
1652 // Ack up to 10 packets at once unless ack decimation is unlimited.
1653 if (!unlimited_ack_decimation_ &&
1654 num_retransmittable_packets_received_since_last_ack_sent_ >=
1655 kMaxRetransmittablePacketsBeforeAck) {
1656 if (packet_generator_.deprecate_ack_bundling_mode()) {
1657 MaybeSetAckAlarmTo(clock_->ApproximateNow());
1658 } else {
1659 ack_queued_ = true;
1660 }
1661 } else if (ShouldSetAckAlarm()) {
1662 // Wait for the minimum of the ack decimation delay or the delayed ack
1663 // time before sending an ack.
1664 QuicTime::Delta ack_delay =
1665 std::min(sent_packet_manager_.delayed_ack_time(),
1666 sent_packet_manager_.GetRttStats()->min_rtt() *
1667 ack_decimation_delay_);
1668 const QuicTime approximate_now = clock_->ApproximateNow();
1669 if (fast_ack_after_quiescence_ &&
1670 (approximate_now - time_of_previous_received_packet_) >
1671 sent_packet_manager_.GetRttStats()->SmoothedOrInitialRtt()) {
1672 // Ack the first packet out of queiscence faster, because QUIC does
1673 // not pace the first few packets and commonly these may be handshake
1674 // or TLP packets, which we'd like to acknowledge quickly.
1675 ack_delay = QuicTime::Delta::FromMilliseconds(1);
1676 }
1677 ack_alarm_->Set(approximate_now + ack_delay);
1678 }
1679 } else {
1680 // Ack with a timer or every 2 packets by default.
1681 if (num_retransmittable_packets_received_since_last_ack_sent_ >=
1682 ack_frequency_before_ack_decimation_) {
1683 if (packet_generator_.deprecate_ack_bundling_mode()) {
1684 MaybeSetAckAlarmTo(clock_->ApproximateNow());
1685 } else {
1686 ack_queued_ = true;
1687 }
1688 } else if (ShouldSetAckAlarm()) {
1689 const QuicTime approximate_now = clock_->ApproximateNow();
1690 if (fast_ack_after_quiescence_ &&
1691 (approximate_now - time_of_previous_received_packet_) >
1692 sent_packet_manager_.GetRttStats()->SmoothedOrInitialRtt()) {
1693 // Ack the first packet out of queiscence faster, because QUIC does
1694 // not pace the first few packets and commonly these may be handshake
1695 // or TLP packets, which we'd like to acknowledge quickly.
1696 ack_alarm_->Set(approximate_now +
1697 QuicTime::Delta::FromMilliseconds(1));
1698 } else {
1699 ack_alarm_->Set(approximate_now +
1700 sent_packet_manager_.delayed_ack_time());
1701 }
1702 }
1703 }
1704
1705 // If there are new missing packets to report, send an ack immediately.
1706 if (received_packet_manager_.HasNewMissingPackets()) {
1707 if (ack_mode_ == ACK_DECIMATION_WITH_REORDERING) {
1708 // Wait the minimum of an eighth min_rtt and the existing ack time.
1709 QuicTime ack_time =
1710 clock_->ApproximateNow() +
1711 0.125 * sent_packet_manager_.GetRttStats()->min_rtt();
1712 if (ShouldSetAckAlarm() || ack_alarm_->deadline() > ack_time) {
1713 ack_alarm_->Update(ack_time, QuicTime::Delta::Zero());
1714 }
1715 } else {
1716 if (packet_generator_.deprecate_ack_bundling_mode()) {
1717 MaybeSetAckAlarmTo(clock_->ApproximateNow());
1718 } else {
1719 ack_queued_ = true;
1720 }
1721 }
1722 }
1723
1724 if (fast_ack_after_quiescence_) {
1725 time_of_previous_received_packet_ = time_of_last_received_packet_;
1726 }
1727 }
1728
1729 if (ack_queued_) {
1730 ack_alarm_->Cancel();
1731 }
1732}
1733
1734void QuicConnection::ClearLastFrames() {
1735 should_last_packet_instigate_acks_ = false;
1736}
1737
1738void QuicConnection::CloseIfTooManyOutstandingSentPackets() {
1739 // This occurs if we don't discard old packets we've seen fast enough. It's
1740 // possible largest observed is less than leaset unacked.
1741 if (sent_packet_manager_.GetLargestObserved().IsInitialized() &&
1742 sent_packet_manager_.GetLargestObserved() >
1743 sent_packet_manager_.GetLeastUnacked() + max_tracked_packets_) {
1744 CloseConnection(
1745 QUIC_TOO_MANY_OUTSTANDING_SENT_PACKETS,
1746 QuicStrCat("More than ", max_tracked_packets_,
1747 " outstanding, least_unacked: ",
1748 sent_packet_manager_.GetLeastUnacked().ToUint64()),
1749 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
1750 }
1751}
1752
1753const QuicFrame QuicConnection::GetUpdatedAckFrame() {
QUICHE teamb23daa72019-03-21 08:37:48 -07001754 if (use_uber_received_packet_manager_) {
1755 return uber_received_packet_manager_.GetUpdatedAckFrame(
QUICHE team1dfa46b2019-03-22 10:39:10 -07001756 QuicUtils::GetPacketNumberSpace(encryption_level_),
QUICHE teamb23daa72019-03-21 08:37:48 -07001757 clock_->ApproximateNow());
1758 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001759 return received_packet_manager_.GetUpdatedAckFrame(clock_->ApproximateNow());
1760}
1761
1762void QuicConnection::PopulateStopWaitingFrame(
1763 QuicStopWaitingFrame* stop_waiting) {
1764 stop_waiting->least_unacked = GetLeastUnacked();
1765}
1766
1767QuicPacketNumber QuicConnection::GetLeastUnacked() const {
1768 return sent_packet_manager_.GetLeastUnacked();
1769}
1770
1771bool QuicConnection::HandleWriteBlocked() {
1772 if (!writer_->IsWriteBlocked()) {
1773 return false;
1774 }
1775
1776 visitor_->OnWriteBlocked();
1777 return true;
1778}
1779
1780void QuicConnection::MaybeSendInResponseToPacket() {
1781 if (!connected_) {
1782 return;
1783 }
1784
1785 // If the writer is blocked, don't attempt to send packets now or in the send
1786 // alarm. When the writer unblocks, OnCanWrite() will be called for this
1787 // connection to send.
1788 if (HandleWriteBlocked()) {
1789 return;
1790 }
1791
1792 // Now that we have received an ack, we might be able to send packets which
1793 // are queued locally, or drain streams which are blocked.
1794 if (defer_send_in_response_to_packets_) {
1795 send_alarm_->Update(clock_->ApproximateNow(), QuicTime::Delta::Zero());
1796 } else {
1797 WriteAndBundleAcksIfNotBlocked();
1798 }
1799}
1800
1801void QuicConnection::SendVersionNegotiationPacket(bool ietf_quic) {
1802 pending_version_negotiation_packet_ = true;
1803 send_ietf_version_negotiation_packet_ = ietf_quic;
1804
1805 if (HandleWriteBlocked()) {
1806 return;
1807 }
1808
1809 QUIC_DLOG(INFO) << ENDPOINT << "Sending version negotiation packet: {"
1810 << ParsedQuicVersionVectorToString(
1811 framer_.supported_versions())
dschinazi965ce092019-05-23 06:29:01 -07001812 << "}, " << (ietf_quic ? "" : "!") << "ietf_quic";
QUICHE teama6ef0a62019-03-07 20:34:33 -05001813 std::unique_ptr<QuicEncryptedPacket> version_packet(
1814 packet_generator_.SerializeVersionNegotiationPacket(
1815 ietf_quic, framer_.supported_versions()));
dschinazi965ce092019-05-23 06:29:01 -07001816 QUIC_DVLOG(2) << ENDPOINT << "Sending version negotiation packet: {"
1817 << ParsedQuicVersionVectorToString(framer_.supported_versions())
1818 << "}, " << (ietf_quic ? "" : "!") << "ietf_quic:" << std::endl
1819 << QuicTextUtils::HexDump(QuicStringPiece(
1820 version_packet->data(), version_packet->length()));
QUICHE teama6ef0a62019-03-07 20:34:33 -05001821 WriteResult result = writer_->WritePacket(
1822 version_packet->data(), version_packet->length(), self_address().host(),
1823 peer_address(), per_packet_options_);
1824
1825 if (IsWriteError(result.status)) {
1826 OnWriteError(result.error_code);
1827 return;
1828 }
1829 if (IsWriteBlockedStatus(result.status)) {
1830 visitor_->OnWriteBlocked();
1831 if (result.status == WRITE_STATUS_BLOCKED_DATA_BUFFERED) {
1832 pending_version_negotiation_packet_ = false;
1833 }
1834 return;
1835 }
1836
1837 pending_version_negotiation_packet_ = false;
1838}
1839
1840size_t QuicConnection::SendCryptoData(EncryptionLevel level,
1841 size_t write_length,
1842 QuicStreamOffset offset) {
1843 if (write_length == 0) {
1844 QUIC_BUG << "Attempt to send empty crypto frame";
1845 return 0;
1846 }
1847
1848 ScopedPacketFlusher flusher(this, SEND_ACK_IF_PENDING);
1849 return packet_generator_.ConsumeCryptoData(level, write_length, offset);
1850}
1851
1852QuicConsumedData QuicConnection::SendStreamData(QuicStreamId id,
1853 size_t write_length,
1854 QuicStreamOffset offset,
1855 StreamSendingState state) {
1856 if (state == NO_FIN && write_length == 0) {
1857 QUIC_BUG << "Attempt to send empty stream frame";
1858 return QuicConsumedData(0, false);
1859 }
1860
1861 // Opportunistically bundle an ack with every outgoing packet.
1862 // Particularly, we want to bundle with handshake packets since we don't know
1863 // which decrypter will be used on an ack packet following a handshake
1864 // packet (a handshake packet from client to server could result in a REJ or a
1865 // SHLO from the server, leading to two different decrypters at the server.)
1866 ScopedPacketFlusher flusher(this, SEND_ACK_IF_PENDING);
1867 return packet_generator_.ConsumeData(id, write_length, offset, state);
1868}
1869
1870bool QuicConnection::SendControlFrame(const QuicFrame& frame) {
fayang3203f252019-05-03 06:00:03 -07001871 if (!packet_generator_.deprecate_queued_control_frames() &&
1872 !CanWrite(HAS_RETRANSMITTABLE_DATA) && frame.type != PING_FRAME) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001873 QUIC_DVLOG(1) << ENDPOINT << "Failed to send control frame: " << frame;
1874 // Do not check congestion window for ping.
1875 return false;
1876 }
1877 ScopedPacketFlusher flusher(this, SEND_ACK_IF_PENDING);
fayang3203f252019-05-03 06:00:03 -07001878 const bool consumed =
1879 packet_generator_.ConsumeRetransmittableControlFrame(frame);
1880 if (packet_generator_.deprecate_queued_control_frames() && !consumed) {
1881 QUIC_DVLOG(1) << ENDPOINT << "Failed to send control frame: " << frame;
1882 return false;
1883 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001884 if (frame.type == PING_FRAME) {
1885 // Flush PING frame immediately.
1886 packet_generator_.FlushAllQueuedFrames();
1887 if (debug_visitor_ != nullptr) {
1888 debug_visitor_->OnPingSent();
1889 }
1890 }
1891 if (frame.type == BLOCKED_FRAME) {
1892 stats_.blocked_frames_sent++;
1893 }
1894 return true;
1895}
1896
1897void QuicConnection::OnStreamReset(QuicStreamId id,
1898 QuicRstStreamErrorCode error) {
1899 if (error == QUIC_STREAM_NO_ERROR) {
1900 // All data for streams which are reset with QUIC_STREAM_NO_ERROR must
1901 // be received by the peer.
1902 return;
1903 }
1904 // Flush stream frames of reset stream.
1905 if (packet_generator_.HasPendingStreamFramesOfStream(id)) {
1906 ScopedPacketFlusher flusher(this, SEND_ACK_IF_PENDING);
1907 packet_generator_.FlushAllQueuedFrames();
1908 }
1909
1910 sent_packet_manager_.CancelRetransmissionsForStream(id);
1911 // Remove all queued packets which only contain data for the reset stream.
1912 // TODO(fayang): consider removing this because it should be rarely executed.
1913 auto packet_iterator = queued_packets_.begin();
1914 while (packet_iterator != queued_packets_.end()) {
1915 QuicFrames* retransmittable_frames =
1916 &packet_iterator->retransmittable_frames;
1917 if (retransmittable_frames->empty()) {
1918 ++packet_iterator;
1919 continue;
1920 }
1921 // NOTE THAT RemoveFramesForStream removes only STREAM frames
1922 // for the specified stream.
1923 RemoveFramesForStream(retransmittable_frames, id);
1924 if (!retransmittable_frames->empty()) {
1925 ++packet_iterator;
1926 continue;
1927 }
1928 delete[] packet_iterator->encrypted_buffer;
1929 ClearSerializedPacket(&(*packet_iterator));
1930 packet_iterator = queued_packets_.erase(packet_iterator);
1931 }
1932 // TODO(ianswett): Consider checking for 3 RTOs when the last stream is
1933 // cancelled as well.
1934}
1935
1936const QuicConnectionStats& QuicConnection::GetStats() {
1937 const RttStats* rtt_stats = sent_packet_manager_.GetRttStats();
1938
1939 // Update rtt and estimated bandwidth.
1940 QuicTime::Delta min_rtt = rtt_stats->min_rtt();
1941 if (min_rtt.IsZero()) {
1942 // If min RTT has not been set, use initial RTT instead.
1943 min_rtt = rtt_stats->initial_rtt();
1944 }
1945 stats_.min_rtt_us = min_rtt.ToMicroseconds();
1946
1947 QuicTime::Delta srtt = rtt_stats->SmoothedOrInitialRtt();
1948 stats_.srtt_us = srtt.ToMicroseconds();
1949
1950 stats_.estimated_bandwidth = sent_packet_manager_.BandwidthEstimate();
1951 stats_.max_packet_size = packet_generator_.GetCurrentMaxPacketLength();
1952 stats_.max_received_packet_size = largest_received_packet_size_;
1953 return stats_;
1954}
1955
1956void QuicConnection::OnCoalescedPacket(const QuicEncryptedPacket& packet) {
1957 QueueCoalescedPacket(packet);
1958}
1959
1960void QuicConnection::ProcessUdpPacket(const QuicSocketAddress& self_address,
1961 const QuicSocketAddress& peer_address,
1962 const QuicReceivedPacket& packet) {
1963 if (!connected_) {
1964 return;
1965 }
dschinazid9467b52019-04-03 16:47:08 -07001966 QUIC_DVLOG(2) << ENDPOINT << "Received encrypted " << packet.length()
1967 << " bytes:" << std::endl
1968 << QuicTextUtils::HexDump(
1969 QuicStringPiece(packet.data(), packet.length()));
QUICHE teama6ef0a62019-03-07 20:34:33 -05001970 QUIC_BUG_IF(current_packet_data_ != nullptr)
1971 << "ProcessUdpPacket must not be called while processing a packet.";
1972 if (debug_visitor_ != nullptr) {
1973 debug_visitor_->OnPacketReceived(self_address, peer_address, packet);
1974 }
1975 last_size_ = packet.length();
1976 current_packet_data_ = packet.data();
1977
1978 last_packet_destination_address_ = self_address;
1979 last_packet_source_address_ = peer_address;
1980 if (!self_address_.IsInitialized()) {
1981 self_address_ = last_packet_destination_address_;
1982 }
1983
1984 if (!direct_peer_address_.IsInitialized()) {
1985 direct_peer_address_ = last_packet_source_address_;
1986 }
1987
1988 if (!effective_peer_address_.IsInitialized()) {
1989 const QuicSocketAddress effective_peer_addr =
1990 GetEffectivePeerAddressFromCurrentPacket();
1991
1992 // effective_peer_address_ must be initialized at the beginning of the
1993 // first packet processed(here). If effective_peer_addr is uninitialized,
1994 // just set effective_peer_address_ to the direct peer address.
1995 effective_peer_address_ = effective_peer_addr.IsInitialized()
1996 ? effective_peer_addr
1997 : direct_peer_address_;
1998 }
1999
2000 stats_.bytes_received += packet.length();
2001 ++stats_.packets_received;
2002
2003 // Ensure the time coming from the packet reader is within 2 minutes of now.
2004 if (std::abs((packet.receipt_time() - clock_->ApproximateNow()).ToSeconds()) >
2005 2 * 60) {
2006 QUIC_BUG << "Packet receipt time:"
2007 << packet.receipt_time().ToDebuggingValue()
2008 << " too far from current time:"
2009 << clock_->ApproximateNow().ToDebuggingValue();
2010 }
2011 time_of_last_received_packet_ = packet.receipt_time();
2012 QUIC_DVLOG(1) << ENDPOINT << "time of last received packet: "
2013 << time_of_last_received_packet_.ToDebuggingValue();
2014
2015 ScopedPacketFlusher flusher(this, NO_ACK);
2016 if (!framer_.ProcessPacket(packet)) {
2017 // If we are unable to decrypt this packet, it might be
2018 // because the CHLO or SHLO packet was lost.
2019 if (framer_.error() == QUIC_DECRYPTION_FAILURE) {
dschinazi6ece5002019-05-22 06:35:49 -07002020 ++stats_.undecryptable_packets_received;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002021 if (encryption_level_ != ENCRYPTION_FORWARD_SECURE &&
2022 undecryptable_packets_.size() < max_undecryptable_packets_) {
2023 QueueUndecryptablePacket(packet);
2024 } else if (debug_visitor_ != nullptr) {
2025 debug_visitor_->OnUndecryptablePacket();
2026 }
2027 }
2028 QUIC_DVLOG(1) << ENDPOINT
2029 << "Unable to process packet. Last packet processed: "
2030 << last_header_.packet_number;
2031 current_packet_data_ = nullptr;
2032 is_current_packet_connectivity_probing_ = false;
2033
2034 MaybeProcessCoalescedPackets();
2035 return;
2036 }
2037
2038 ++stats_.packets_processed;
2039
2040 QUIC_DLOG_IF(INFO, active_effective_peer_migration_type_ != NO_CHANGE)
2041 << "sent_packet_manager_.GetLargestObserved() = "
2042 << sent_packet_manager_.GetLargestObserved()
2043 << ", highest_packet_sent_before_effective_peer_migration_ = "
2044 << highest_packet_sent_before_effective_peer_migration_;
2045 if (active_effective_peer_migration_type_ != NO_CHANGE &&
2046 sent_packet_manager_.GetLargestObserved().IsInitialized() &&
2047 (!highest_packet_sent_before_effective_peer_migration_.IsInitialized() ||
2048 sent_packet_manager_.GetLargestObserved() >
2049 highest_packet_sent_before_effective_peer_migration_)) {
2050 if (perspective_ == Perspective::IS_SERVER) {
2051 OnEffectivePeerMigrationValidated();
2052 }
2053 }
2054
2055 MaybeProcessCoalescedPackets();
2056 MaybeProcessUndecryptablePackets();
2057 MaybeSendInResponseToPacket();
2058 SetPingAlarm();
2059 current_packet_data_ = nullptr;
2060 is_current_packet_connectivity_probing_ = false;
2061}
2062
2063void QuicConnection::OnBlockedWriterCanWrite() {
2064 writer_->SetWritable();
2065 OnCanWrite();
2066}
2067
2068void QuicConnection::OnCanWrite() {
2069 DCHECK(!writer_->IsWriteBlocked());
2070
2071 // Add a flusher to ensure the connection is marked app-limited.
2072 ScopedPacketFlusher flusher(this, NO_ACK);
2073
2074 WriteQueuedPackets();
2075 if (received_packet_manager_.decide_when_to_send_acks()) {
QUICHE teamb23daa72019-03-21 08:37:48 -07002076 const QuicTime ack_timeout =
2077 use_uber_received_packet_manager_
QUICHE teamcd098022019-03-22 18:49:55 -07002078 ? uber_received_packet_manager_.GetEarliestAckTimeout()
QUICHE teamb23daa72019-03-21 08:37:48 -07002079 : received_packet_manager_.ack_timeout();
QUICHE teama6ef0a62019-03-07 20:34:33 -05002080 if (ack_timeout.IsInitialized() &&
2081 ack_timeout <= clock_->ApproximateNow()) {
2082 // Send an ACK now because either 1) we were write blocked when we last
2083 // tried to send an ACK, or 2) both ack alarm and send alarm were set to
2084 // go off together.
QUICHE teamcd098022019-03-22 18:49:55 -07002085 if (SupportsMultiplePacketNumberSpaces()) {
2086 SendAllPendingAcks();
2087 } else {
2088 SendAck();
2089 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002090 }
2091 } else if (send_ack_when_on_can_write_) {
2092 // Send an ACK now because either 1) we were write blocked when we last
2093 // tried to send an ACK, or 2) both ack alarm and send alarm were set to go
2094 // off together.
2095 DCHECK(packet_generator_.deprecate_ack_bundling_mode());
2096 SendAck();
2097 }
2098 if (!session_decides_what_to_write()) {
2099 WritePendingRetransmissions();
2100 }
2101
2102 WriteNewData();
2103}
2104
2105void QuicConnection::WriteNewData() {
2106 // Sending queued packets may have caused the socket to become write blocked,
2107 // or the congestion manager to prohibit sending. If we've sent everything
2108 // we had queued and we're still not blocked, let the visitor know it can
2109 // write more.
2110 if (!CanWrite(HAS_RETRANSMITTABLE_DATA)) {
2111 return;
2112 }
2113
2114 {
2115 ScopedPacketFlusher flusher(this, SEND_ACK_IF_QUEUED);
2116 visitor_->OnCanWrite();
2117 }
2118
2119 // After the visitor writes, it may have caused the socket to become write
2120 // blocked or the congestion manager to prohibit sending, so check again.
2121 if (visitor_->WillingAndAbleToWrite() && !send_alarm_->IsSet() &&
2122 CanWrite(HAS_RETRANSMITTABLE_DATA)) {
2123 // We're not write blocked, but some stream didn't write out all of its
2124 // bytes. Register for 'immediate' resumption so we'll keep writing after
2125 // other connections and events have had a chance to use the thread.
2126 send_alarm_->Set(clock_->ApproximateNow());
2127 }
2128}
2129
2130void QuicConnection::WriteIfNotBlocked() {
2131 if (!HandleWriteBlocked()) {
2132 OnCanWrite();
2133 }
2134}
2135
2136void QuicConnection::WriteAndBundleAcksIfNotBlocked() {
2137 if (!HandleWriteBlocked()) {
2138 ScopedPacketFlusher flusher(this, SEND_ACK_IF_QUEUED);
2139 WriteIfNotBlocked();
2140 }
2141}
2142
2143bool QuicConnection::ProcessValidatedPacket(const QuicPacketHeader& header) {
2144 if (perspective_ == Perspective::IS_SERVER && self_address_.IsInitialized() &&
2145 last_packet_destination_address_.IsInitialized() &&
2146 self_address_ != last_packet_destination_address_) {
2147 // Allow change between pure IPv4 and equivalent mapped IPv4 address.
2148 if (self_address_.port() != last_packet_destination_address_.port() ||
2149 self_address_.host().Normalized() !=
2150 last_packet_destination_address_.host().Normalized()) {
2151 if (!visitor_->AllowSelfAddressChange()) {
2152 CloseConnection(
2153 QUIC_ERROR_MIGRATING_ADDRESS,
2154 "Self address migration is not supported at the server.",
2155 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
2156 return false;
2157 }
2158 }
2159 self_address_ = last_packet_destination_address_;
2160 }
2161
QUICHE teamc65d1d12019-03-19 20:58:04 -07002162 if (PacketCanReplaceConnectionId(header, perspective_) &&
dschinazi7b9278c2019-05-20 07:36:21 -07002163 server_connection_id_ != header.source_connection_id) {
2164 QUIC_DLOG(INFO) << ENDPOINT << "Replacing connection ID "
2165 << server_connection_id_ << " with "
2166 << header.source_connection_id;
2167 server_connection_id_ = header.source_connection_id;
2168 packet_generator_.SetServerConnectionId(server_connection_id_);
QUICHE teamc65d1d12019-03-19 20:58:04 -07002169 }
2170
QUICHE teamd791e2c2019-03-15 10:28:21 -07002171 if (!ValidateReceivedPacketNumber(header.packet_number)) {
2172 return false;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002173 }
2174
2175 if (version_negotiation_state_ != NEGOTIATED_VERSION) {
2176 if (perspective_ == Perspective::IS_CLIENT) {
2177 DCHECK(!header.version_flag || header.form != GOOGLE_QUIC_PACKET);
2178 if (framer_.transport_version() <= QUIC_VERSION_43) {
2179 // If the client gets a packet without the version flag from the server
2180 // it should stop sending version since the version negotiation is done.
2181 // IETF QUIC stops sending version once encryption level switches to
2182 // forward secure.
2183 packet_generator_.StopSendingVersion();
2184 }
2185 version_negotiation_state_ = NEGOTIATED_VERSION;
2186 visitor_->OnSuccessfulVersionNegotiation(version());
2187 if (debug_visitor_ != nullptr) {
2188 debug_visitor_->OnSuccessfulVersionNegotiation(version());
2189 }
2190 }
2191 }
2192
2193 if (last_size_ > largest_received_packet_size_) {
2194 largest_received_packet_size_ = last_size_;
2195 }
2196
2197 if (perspective_ == Perspective::IS_SERVER &&
QUICHE team6987b4a2019-03-15 16:23:04 -07002198 encryption_level_ == ENCRYPTION_INITIAL &&
QUICHE teama6ef0a62019-03-07 20:34:33 -05002199 last_size_ > packet_generator_.GetCurrentMaxPacketLength()) {
2200 SetMaxPacketLength(last_size_);
2201 }
2202 return true;
2203}
2204
QUICHE teamd791e2c2019-03-15 10:28:21 -07002205bool QuicConnection::ValidateReceivedPacketNumber(
2206 QuicPacketNumber packet_number) {
QUICHE teamb23daa72019-03-21 08:37:48 -07002207 if (validate_packet_number_post_decryption_) {
2208 const bool is_awaiting =
2209 use_uber_received_packet_manager_
QUICHE team1dfa46b2019-03-22 10:39:10 -07002210 ? uber_received_packet_manager_.IsAwaitingPacket(
2211 last_decrypted_packet_level_, packet_number)
QUICHE teamb23daa72019-03-21 08:37:48 -07002212 : received_packet_manager_.IsAwaitingPacket(packet_number);
2213 if (!is_awaiting) {
dschinazid9467b52019-04-03 16:47:08 -07002214 if (use_uber_received_packet_manager_) {
2215 QUIC_DLOG(INFO) << ENDPOINT << "Packet " << packet_number
2216 << " no longer being waited for at level "
2217 << static_cast<int>(last_decrypted_packet_level_)
2218 << ". Discarding.";
2219 } else {
2220 QUIC_DLOG(INFO) << ENDPOINT << "Packet " << packet_number
2221 << " no longer being waited for. Discarding.";
2222 }
QUICHE teamb23daa72019-03-21 08:37:48 -07002223 if (debug_visitor_ != nullptr) {
2224 debug_visitor_->OnDuplicatePacket(packet_number);
2225 }
2226 return false;
QUICHE team692750b2019-03-17 17:57:46 -07002227 }
QUICHE team692750b2019-03-17 17:57:46 -07002228 }
2229
QUICHE teamcd098022019-03-22 18:49:55 -07002230 if (use_uber_received_packet_manager_) {
2231 // When using uber_received_packet_manager, accept any packet numbers.
2232 return true;
2233 }
2234
QUICHE teamd791e2c2019-03-15 10:28:21 -07002235 if (GetQuicRestartFlag(quic_enable_accept_random_ipn)) {
2236 QUIC_RESTART_FLAG_COUNT_N(quic_enable_accept_random_ipn, 2, 2);
2237 // Configured to accept any packet number in range 1...0x7fffffff as initial
2238 // packet number.
2239 bool out_of_bound = false;
rchd5d13c22019-03-18 14:31:09 -07002240 std::string error_detail = "Packet number out of bounds.";
QUICHE teamd791e2c2019-03-15 10:28:21 -07002241 if (last_header_.packet_number.IsInitialized()) {
2242 out_of_bound = !Near(packet_number, last_header_.packet_number);
2243 } else if ((packet_number > MaxRandomInitialPacketNumber())) {
2244 out_of_bound = true;
2245 error_detail = "Initial packet number out of bounds.";
2246 }
2247 if (out_of_bound) {
2248 QUIC_DLOG(INFO) << ENDPOINT << "Packet " << packet_number
2249 << " out of bounds. Discarding";
2250 CloseConnection(QUIC_INVALID_PACKET_HEADER, error_detail,
2251 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
2252 return false;
2253 }
2254 return true;
2255 }
QUICHE teamcd098022019-03-22 18:49:55 -07002256
2257 if (packet_number > received_packet_manager_.PeerFirstSendingPacketNumber() &&
QUICHE teamd791e2c2019-03-15 10:28:21 -07002258 packet_number <= MaxRandomInitialPacketNumber()) {
2259 QUIC_CODE_COUNT_N(had_possibly_random_ipn, 2, 2);
2260 }
2261 const bool out_of_bound =
2262 last_header_.packet_number.IsInitialized()
2263 ? !Near(packet_number, last_header_.packet_number)
QUICHE teamcd098022019-03-22 18:49:55 -07002264 : packet_number >=
2265 (received_packet_manager_.PeerFirstSendingPacketNumber() +
2266 kMaxPacketGap);
QUICHE teamd791e2c2019-03-15 10:28:21 -07002267 if (!out_of_bound) {
2268 return true;
2269 }
2270 QUIC_DLOG(INFO) << ENDPOINT << "Packet " << packet_number
2271 << " out of bounds. Discarding";
2272 QuicStringPiece packet_data = GetCurrentPacket();
2273 const size_t kMaxPacketLengthInErrorDetails = 64;
2274 CloseConnection(
2275 QUIC_INVALID_PACKET_HEADER,
2276 QuicStrCat(
2277 "Packet number out of bounds. ",
2278 last_header_.packet_number.IsInitialized()
2279 ? QuicStrCat("last_pkn=", last_header_.packet_number.ToUint64())
2280 : "first received packet",
2281 ", current_pkn=", packet_number.ToUint64(),
2282 ", current_pkt_len=", packet_data.length(), ", current_hdr=",
2283 QuicTextUtils::HexEncode(
2284 packet_data.length() > kMaxPacketLengthInErrorDetails
2285 ? QuicStringPiece(packet_data.data(),
2286 kMaxPacketLengthInErrorDetails)
2287 : packet_data)),
2288 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
2289 return false;
2290}
2291
QUICHE teama6ef0a62019-03-07 20:34:33 -05002292void QuicConnection::WriteQueuedPackets() {
2293 DCHECK(!writer_->IsWriteBlocked());
2294
2295 if (pending_version_negotiation_packet_) {
2296 SendVersionNegotiationPacket(send_ietf_version_negotiation_packet_);
2297 }
2298
2299 QUIC_CLIENT_HISTOGRAM_COUNTS("QuicSession.NumQueuedPacketsBeforeWrite",
2300 queued_packets_.size(), 1, 1000, 50, "");
2301 while (!queued_packets_.empty()) {
2302 // WritePacket() can potentially clear all queued packets, so we need to
2303 // save the first queued packet to a local variable before calling it.
2304 SerializedPacket packet(std::move(queued_packets_.front()));
2305 queued_packets_.pop_front();
2306
2307 const bool write_result = WritePacket(&packet);
2308
2309 if (connected_ && !write_result) {
2310 // Write failed but connection is open, re-insert |packet| into the
2311 // front of the queue, it will be retried later.
2312 queued_packets_.emplace_front(std::move(packet));
2313 break;
2314 }
2315
2316 delete[] packet.encrypted_buffer;
2317 ClearSerializedPacket(&packet);
2318 if (!connected_) {
2319 DCHECK(queued_packets_.empty()) << "Queued packets should have been "
2320 "cleared while closing connection";
2321 break;
2322 }
2323
2324 // Continue to send the next packet in queue.
2325 }
2326}
2327
2328void QuicConnection::WritePendingRetransmissions() {
2329 DCHECK(!session_decides_what_to_write());
2330 // Keep writing as long as there's a pending retransmission which can be
2331 // written.
2332 while (sent_packet_manager_.HasPendingRetransmissions() &&
2333 CanWrite(HAS_RETRANSMITTABLE_DATA)) {
2334 const QuicPendingRetransmission pending =
2335 sent_packet_manager_.NextPendingRetransmission();
2336
2337 // Re-packetize the frames with a new packet number for retransmission.
2338 // Retransmitted packets use the same packet number length as the
2339 // original.
2340 // Flush the packet generator before making a new packet.
2341 // TODO(ianswett): Implement ReserializeAllFrames as a separate path that
2342 // does not require the creator to be flushed.
2343 // TODO(fayang): FlushAllQueuedFrames should only be called once, and should
2344 // be moved outside of the loop. Also, CanWrite is not checked after the
2345 // generator is flushed.
2346 {
2347 ScopedPacketFlusher flusher(this, NO_ACK);
2348 packet_generator_.FlushAllQueuedFrames();
2349 }
2350 DCHECK(!packet_generator_.HasQueuedFrames());
dschinazi66dea072019-04-09 11:41:06 -07002351 char buffer[kMaxOutgoingPacketSize];
2352 packet_generator_.ReserializeAllFrames(pending, buffer,
2353 kMaxOutgoingPacketSize);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002354 }
2355}
2356
2357void QuicConnection::SendProbingRetransmissions() {
2358 while (sent_packet_manager_.GetSendAlgorithm()->ShouldSendProbingPacket() &&
2359 CanWrite(HAS_RETRANSMITTABLE_DATA)) {
QUICHE teamb8343252019-04-29 13:58:01 -07002360 if (!visitor_->SendProbingData()) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002361 QUIC_DVLOG(1)
2362 << "Cannot send probing retransmissions: nothing to retransmit.";
2363 break;
2364 }
2365
2366 if (!session_decides_what_to_write()) {
2367 DCHECK(sent_packet_manager_.HasPendingRetransmissions());
2368 WritePendingRetransmissions();
2369 }
2370 }
2371}
2372
2373void QuicConnection::RetransmitUnackedPackets(
2374 TransmissionType retransmission_type) {
2375 sent_packet_manager_.RetransmitUnackedPackets(retransmission_type);
2376
2377 WriteIfNotBlocked();
2378}
2379
2380void QuicConnection::NeuterUnencryptedPackets() {
2381 sent_packet_manager_.NeuterUnencryptedPackets();
2382 // This may have changed the retransmission timer, so re-arm it.
2383 SetRetransmissionAlarm();
2384}
2385
2386bool QuicConnection::ShouldGeneratePacket(
2387 HasRetransmittableData retransmittable,
2388 IsHandshake handshake) {
2389 // We should serialize handshake packets immediately to ensure that they
2390 // end up sent at the right encryption level.
2391 if (handshake == IS_HANDSHAKE) {
2392 return true;
2393 }
2394
2395 return CanWrite(retransmittable);
2396}
2397
2398const QuicFrames QuicConnection::MaybeBundleAckOpportunistically() {
2399 DCHECK(packet_generator_.deprecate_ack_bundling_mode());
2400 QuicFrames frames;
2401 bool has_pending_ack = false;
2402 if (received_packet_manager_.decide_when_to_send_acks()) {
QUICHE teamb23daa72019-03-21 08:37:48 -07002403 if (use_uber_received_packet_manager_) {
2404 has_pending_ack =
QUICHE team1dfa46b2019-03-22 10:39:10 -07002405 uber_received_packet_manager_
2406 .GetAckTimeout(QuicUtils::GetPacketNumberSpace(encryption_level_))
2407 .IsInitialized();
QUICHE teamb23daa72019-03-21 08:37:48 -07002408 } else {
2409 has_pending_ack = received_packet_manager_.ack_timeout().IsInitialized();
2410 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002411 } else {
2412 has_pending_ack = ack_alarm_->IsSet();
2413 }
2414 if (!has_pending_ack && stop_waiting_count_ <= 1) {
2415 // No need to send an ACK.
2416 return frames;
2417 }
2418 ResetAckStates();
2419
2420 QUIC_DVLOG(1) << ENDPOINT << "Bundle an ACK opportunistically";
dschinazi8cf087e2019-05-23 05:27:48 -07002421 QuicFrame updated_ack_frame = GetUpdatedAckFrame();
2422 QUIC_BUG_IF(updated_ack_frame.ack_frame->packets.Empty())
2423 << ENDPOINT << "Attempted to opportunistically bundle an empty "
2424 << QuicUtils::EncryptionLevelToString(encryption_level_) << " ACK, "
2425 << (has_pending_ack ? "" : "!") << "has_pending_ack, stop_waiting_count_ "
2426 << stop_waiting_count_;
2427 frames.push_back(updated_ack_frame);
2428
QUICHE teama6ef0a62019-03-07 20:34:33 -05002429 if (!no_stop_waiting_frames_) {
2430 QuicStopWaitingFrame stop_waiting;
2431 PopulateStopWaitingFrame(&stop_waiting);
2432 frames.push_back(QuicFrame(stop_waiting));
2433 }
2434 return frames;
2435}
2436
2437bool QuicConnection::CanWrite(HasRetransmittableData retransmittable) {
2438 if (!connected_) {
2439 return false;
2440 }
2441
2442 if (session_decides_what_to_write() &&
2443 sent_packet_manager_.pending_timer_transmission_count() > 0) {
2444 // Force sending the retransmissions for HANDSHAKE, TLP, RTO, PROBING cases.
2445 return true;
2446 }
2447
2448 if (HandleWriteBlocked()) {
2449 return false;
2450 }
2451
2452 // Allow acks to be sent immediately.
2453 if (retransmittable == NO_RETRANSMITTABLE_DATA) {
2454 return true;
2455 }
2456 // If the send alarm is set, wait for it to fire.
2457 if (send_alarm_->IsSet()) {
2458 return false;
2459 }
2460
2461 QuicTime now = clock_->Now();
2462 QuicTime::Delta delay = sent_packet_manager_.TimeUntilSend(now);
2463 if (delay.IsInfinite()) {
2464 send_alarm_->Cancel();
2465 return false;
2466 }
2467
2468 // Scheduler requires a delay.
2469 if (!delay.IsZero()) {
2470 if (delay <= release_time_into_future_) {
2471 // Required delay is within pace time into future, send now.
2472 return true;
2473 }
2474 // Cannot send packet now because delay is too far in the future.
2475 send_alarm_->Update(now + delay, QuicTime::Delta::FromMilliseconds(1));
2476 QUIC_DVLOG(1) << ENDPOINT << "Delaying sending " << delay.ToMilliseconds()
2477 << "ms";
2478 return false;
2479 }
2480 return true;
2481}
2482
2483bool QuicConnection::WritePacket(SerializedPacket* packet) {
2484 if (ShouldDiscardPacket(*packet)) {
2485 ++stats_.packets_discarded;
2486 return true;
2487 }
2488 if (sent_packet_manager_.GetLargestSentPacket().IsInitialized() &&
2489 packet->packet_number < sent_packet_manager_.GetLargestSentPacket()) {
2490 QUIC_BUG << "Attempt to write packet:" << packet->packet_number
2491 << " after:" << sent_packet_manager_.GetLargestSentPacket();
2492 QUIC_CLIENT_HISTOGRAM_COUNTS("QuicSession.NumQueuedPacketsAtOutOfOrder",
2493 queued_packets_.size(), 1, 1000, 50, "");
2494 CloseConnection(QUIC_INTERNAL_ERROR, "Packet written out of order.",
2495 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
2496 return true;
2497 }
2498 // Termination packets are encrypted and saved, so don't exit early.
2499 const bool is_termination_packet = IsTerminationPacket(*packet);
2500 if (HandleWriteBlocked() && !is_termination_packet) {
2501 return false;
2502 }
2503
2504 QuicPacketNumber packet_number = packet->packet_number;
2505
2506 QuicPacketLength encrypted_length = packet->encrypted_length;
2507 // Termination packets are eventually owned by TimeWaitListManager.
2508 // Others are deleted at the end of this call.
2509 if (is_termination_packet) {
2510 if (termination_packets_ == nullptr) {
2511 termination_packets_.reset(
2512 new std::vector<std::unique_ptr<QuicEncryptedPacket>>);
2513 }
2514 // Copy the buffer so it's owned in the future.
2515 char* buffer_copy = CopyBuffer(*packet);
2516 termination_packets_->emplace_back(
2517 new QuicEncryptedPacket(buffer_copy, encrypted_length, true));
2518 // This assures we won't try to write *forced* packets when blocked.
2519 // Return true to stop processing.
2520 if (HandleWriteBlocked()) {
2521 return true;
2522 }
2523 }
2524
dschinazi66dea072019-04-09 11:41:06 -07002525 DCHECK_LE(encrypted_length, kMaxOutgoingPacketSize);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002526 DCHECK_LE(encrypted_length, packet_generator_.GetCurrentMaxPacketLength());
2527 QUIC_DVLOG(1) << ENDPOINT << "Sending packet " << packet_number << " : "
2528 << (IsRetransmittable(*packet) == HAS_RETRANSMITTABLE_DATA
2529 ? "data bearing "
2530 : " ack only ")
2531 << ", encryption level: "
2532 << QuicUtils::EncryptionLevelToString(packet->encryption_level)
2533 << ", encrypted length:" << encrypted_length;
2534 QUIC_DVLOG(2) << ENDPOINT << "packet(" << packet_number << "): " << std::endl
2535 << QuicTextUtils::HexDump(QuicStringPiece(
2536 packet->encrypted_buffer, encrypted_length));
2537
2538 // Measure the RTT from before the write begins to avoid underestimating the
2539 // min_rtt_, especially in cases where the thread blocks or gets swapped out
2540 // during the WritePacket below.
2541 QuicTime packet_send_time = clock_->Now();
2542 if (supports_release_time_ && per_packet_options_ != nullptr) {
2543 QuicTime next_release_time = sent_packet_manager_.GetNextReleaseTime();
2544 QuicTime::Delta release_time_delay = QuicTime::Delta::Zero();
2545 QuicTime now = packet_send_time;
2546 if (next_release_time > now) {
2547 release_time_delay = next_release_time - now;
2548 // Set packet_send_time to the future to make the RTT estimation accurate.
2549 packet_send_time = next_release_time;
2550 }
2551 per_packet_options_->release_time_delay = release_time_delay;
2552 }
2553 WriteResult result = writer_->WritePacket(
2554 packet->encrypted_buffer, encrypted_length, self_address().host(),
2555 peer_address(), per_packet_options_);
2556
2557 QUIC_HISTOGRAM_ENUM(
2558 "QuicConnection.WritePacketStatus", result.status,
2559 WRITE_STATUS_NUM_VALUES,
2560 "Status code returned by writer_->WritePacket() in QuicConnection.");
2561
2562 if (IsWriteBlockedStatus(result.status)) {
2563 // Ensure the writer is still write blocked, otherwise QUIC may continue
2564 // trying to write when it will not be able to.
2565 DCHECK(writer_->IsWriteBlocked());
2566 visitor_->OnWriteBlocked();
2567 // If the socket buffers the data, then the packet should not
2568 // be queued and sent again, which would result in an unnecessary
2569 // duplicate packet being sent. The helper must call OnCanWrite
2570 // when the write completes, and OnWriteError if an error occurs.
2571 if (result.status != WRITE_STATUS_BLOCKED_DATA_BUFFERED) {
2572 return false;
2573 }
2574 }
2575
2576 // In some cases, an MTU probe can cause EMSGSIZE. This indicates that the
2577 // MTU discovery is permanently unsuccessful.
2578 if (IsMsgTooBig(result) && packet->retransmittable_frames.empty() &&
2579 packet->encrypted_length > long_term_mtu_) {
2580 mtu_discovery_target_ = 0;
2581 mtu_discovery_alarm_->Cancel();
2582 // The write failed, but the writer is not blocked, so return true.
2583 return true;
2584 }
2585
2586 if (IsWriteError(result.status)) {
2587 OnWriteError(result.error_code);
2588 QUIC_LOG_FIRST_N(ERROR, 10)
2589 << ENDPOINT << "failed writing " << encrypted_length
2590 << " bytes from host " << self_address().host().ToString()
2591 << " to address " << peer_address().ToString() << " with error code "
2592 << result.error_code;
2593 return false;
2594 }
2595
2596 if (debug_visitor_ != nullptr) {
2597 // Pass the write result to the visitor.
2598 debug_visitor_->OnPacketSent(*packet, packet->original_packet_number,
2599 packet->transmission_type, packet_send_time);
2600 }
2601 if (IsRetransmittable(*packet) == HAS_RETRANSMITTABLE_DATA) {
2602 if (!is_path_degrading_ && !path_degrading_alarm_->IsSet()) {
2603 // This is the first retransmittable packet on the working path.
2604 // Start the path degrading alarm to detect new path degrading.
2605 SetPathDegradingAlarm();
2606 }
2607
2608 if (GetQuicReloadableFlag(
2609 quic_fix_time_of_first_packet_sent_after_receiving)) {
2610 // Update |time_of_first_packet_sent_after_receiving_| if this is the
2611 // first packet sent after the last packet was received. If it were
2612 // updated on every sent packet, then sending into a black hole might
2613 // never timeout.
2614 if (time_of_first_packet_sent_after_receiving_ <
2615 time_of_last_received_packet_) {
2616 QUIC_RELOADABLE_FLAG_COUNT(
2617 quic_fix_time_of_first_packet_sent_after_receiving);
2618 time_of_first_packet_sent_after_receiving_ = packet_send_time;
2619 }
2620 } else {
2621 // Only adjust the last sent time (for the purpose of tracking the idle
2622 // timeout) if this is the first retransmittable packet sent after a
2623 // packet is received. If it were updated on every sent packet, then
2624 // sending into a black hole might never timeout.
2625 if (time_of_first_packet_sent_after_receiving_ <=
2626 time_of_last_received_packet_) {
2627 time_of_first_packet_sent_after_receiving_ = packet_send_time;
2628 }
2629 }
2630 }
2631
2632 MaybeSetMtuAlarm(packet_number);
2633 QUIC_DVLOG(1) << ENDPOINT << "time we began writing last sent packet: "
2634 << packet_send_time.ToDebuggingValue();
2635
2636 bool reset_retransmission_alarm = sent_packet_manager_.OnPacketSent(
2637 packet, packet->original_packet_number, packet_send_time,
2638 packet->transmission_type, IsRetransmittable(*packet));
2639
2640 if (reset_retransmission_alarm || !retransmission_alarm_->IsSet()) {
2641 SetRetransmissionAlarm();
2642 }
2643 SetPingAlarm();
2644
2645 // The packet number length must be updated after OnPacketSent, because it
2646 // may change the packet number length in packet.
2647 packet_generator_.UpdatePacketNumberLength(
2648 sent_packet_manager_.GetLeastUnacked(),
2649 sent_packet_manager_.EstimateMaxPacketsInFlight(max_packet_length()));
2650
2651 stats_.bytes_sent += result.bytes_written;
2652 ++stats_.packets_sent;
2653 if (packet->transmission_type != NOT_RETRANSMISSION) {
2654 stats_.bytes_retransmitted += result.bytes_written;
2655 ++stats_.packets_retransmitted;
2656 }
2657
2658 return true;
2659}
2660
2661void QuicConnection::FlushPackets() {
2662 if (!connected_) {
2663 return;
2664 }
2665
2666 if (!writer_->IsBatchMode()) {
2667 return;
2668 }
2669
2670 if (HandleWriteBlocked()) {
2671 QUIC_DLOG(INFO) << ENDPOINT << "FlushPackets called while blocked.";
2672 return;
2673 }
2674
2675 WriteResult result = writer_->Flush();
2676
2677 if (HandleWriteBlocked()) {
2678 DCHECK_EQ(WRITE_STATUS_BLOCKED, result.status)
2679 << "Unexpected flush result:" << result;
2680 QUIC_DLOG(INFO) << ENDPOINT << "Write blocked in FlushPackets.";
2681 return;
2682 }
2683
2684 if (IsWriteError(result.status)) {
2685 OnWriteError(result.error_code);
2686 }
2687}
2688
2689bool QuicConnection::IsMsgTooBig(const WriteResult& result) {
2690 return (result.status == WRITE_STATUS_MSG_TOO_BIG) ||
2691 (IsWriteError(result.status) && result.error_code == QUIC_EMSGSIZE);
2692}
2693
2694bool QuicConnection::ShouldDiscardPacket(const SerializedPacket& packet) {
2695 if (!connected_) {
2696 QUIC_DLOG(INFO) << ENDPOINT
2697 << "Not sending packet as connection is disconnected.";
2698 return true;
2699 }
2700
2701 QuicPacketNumber packet_number = packet.packet_number;
2702 if (encryption_level_ == ENCRYPTION_FORWARD_SECURE &&
QUICHE team6987b4a2019-03-15 16:23:04 -07002703 packet.encryption_level == ENCRYPTION_INITIAL) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002704 // Drop packets that are NULL encrypted since the peer won't accept them
2705 // anymore.
2706 QUIC_DLOG(INFO) << ENDPOINT
2707 << "Dropping NULL encrypted packet: " << packet_number
2708 << " since the connection is forward secure.";
2709 return true;
2710 }
2711
2712 return false;
2713}
2714
2715void QuicConnection::OnWriteError(int error_code) {
2716 if (write_error_occurred_) {
2717 // A write error already occurred. The connection is being closed.
2718 return;
2719 }
2720 write_error_occurred_ = true;
2721
vasilvvc48c8712019-03-11 13:38:16 -07002722 const std::string error_details = QuicStrCat(
QUICHE teama6ef0a62019-03-07 20:34:33 -05002723 "Write failed with error: ", error_code, " (", strerror(error_code), ")");
2724 QUIC_LOG_FIRST_N(ERROR, 2) << ENDPOINT << error_details;
2725 switch (error_code) {
2726 case QUIC_EMSGSIZE:
ianswettdc1e7ab2019-05-03 16:10:44 -07002727 CloseConnection(QUIC_PACKET_WRITE_ERROR, error_details,
2728 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002729 break;
2730 default:
2731 // We can't send an error as the socket is presumably borked.
2732 if (transport_version() > QUIC_VERSION_43) {
2733 QUIC_CODE_COUNT(quic_tear_down_local_connection_on_write_error_ietf);
2734 } else {
2735 QUIC_CODE_COUNT(
2736 quic_tear_down_local_connection_on_write_error_non_ietf);
2737 }
2738 TearDownLocalConnectionState(QUIC_PACKET_WRITE_ERROR, error_details,
2739 ConnectionCloseSource::FROM_SELF);
2740 }
2741}
2742
2743char* QuicConnection::GetPacketBuffer() {
2744 return writer_->GetNextWriteLocation(self_address().host(), peer_address());
2745}
2746
2747void QuicConnection::OnSerializedPacket(SerializedPacket* serialized_packet) {
2748 if (serialized_packet->encrypted_buffer == nullptr) {
2749 // We failed to serialize the packet, so close the connection.
2750 // TearDownLocalConnectionState does not send close packet, so no infinite
2751 // loop here.
2752 // TODO(ianswett): This is actually an internal error, not an
2753 // encryption failure.
2754 if (transport_version() > QUIC_VERSION_43) {
2755 QUIC_CODE_COUNT(
2756 quic_tear_down_local_connection_on_serialized_packet_ietf);
2757 } else {
2758 QUIC_CODE_COUNT(
2759 quic_tear_down_local_connection_on_serialized_packet_non_ietf);
2760 }
2761 TearDownLocalConnectionState(
2762 QUIC_ENCRYPTION_FAILURE,
2763 "Serialized packet does not have an encrypted buffer.",
2764 ConnectionCloseSource::FROM_SELF);
2765 return;
2766 }
2767
2768 if (serialized_packet->retransmittable_frames.empty() &&
2769 !serialized_packet->original_packet_number.IsInitialized()) {
2770 // Increment consecutive_num_packets_with_no_retransmittable_frames_ if
2771 // this packet is a new transmission with no retransmittable frames.
2772 ++consecutive_num_packets_with_no_retransmittable_frames_;
2773 } else {
2774 consecutive_num_packets_with_no_retransmittable_frames_ = 0;
2775 }
2776 SendOrQueuePacket(serialized_packet);
2777}
2778
2779void QuicConnection::OnUnrecoverableError(QuicErrorCode error,
vasilvvc48c8712019-03-11 13:38:16 -07002780 const std::string& error_details,
QUICHE teama6ef0a62019-03-07 20:34:33 -05002781 ConnectionCloseSource source) {
2782 // The packet creator or generator encountered an unrecoverable error: tear
2783 // down local connection state immediately.
2784 if (transport_version() > QUIC_VERSION_43) {
2785 QUIC_CODE_COUNT(
2786 quic_tear_down_local_connection_on_unrecoverable_error_ietf);
2787 } else {
2788 QUIC_CODE_COUNT(
2789 quic_tear_down_local_connection_on_unrecoverable_error_non_ietf);
2790 }
2791 TearDownLocalConnectionState(error, error_details, source);
2792}
2793
2794void QuicConnection::OnCongestionChange() {
2795 visitor_->OnCongestionWindowChange(clock_->ApproximateNow());
2796
2797 // Uses the connection's smoothed RTT. If zero, uses initial_rtt.
2798 QuicTime::Delta rtt = sent_packet_manager_.GetRttStats()->smoothed_rtt();
2799 if (rtt.IsZero()) {
2800 rtt = sent_packet_manager_.GetRttStats()->initial_rtt();
2801 }
2802
2803 if (debug_visitor_ != nullptr) {
2804 debug_visitor_->OnRttChanged(rtt);
2805 }
2806}
2807
2808void QuicConnection::OnPathMtuIncreased(QuicPacketLength packet_size) {
2809 if (packet_size > max_packet_length()) {
2810 SetMaxPacketLength(packet_size);
2811 }
2812}
2813
2814void QuicConnection::OnHandshakeComplete() {
2815 sent_packet_manager_.SetHandshakeConfirmed();
2816 if (sent_packet_manager_.unacked_packets().use_uber_loss_algorithm()) {
2817 // This may have changed the retransmission timer, so re-arm it.
2818 SetRetransmissionAlarm();
2819 }
2820 // The client should immediately ack the SHLO to confirm the handshake is
2821 // complete with the server.
2822 if (perspective_ == Perspective::IS_CLIENT && !ack_queued_ &&
2823 ack_frame_updated()) {
2824 ack_alarm_->Update(clock_->ApproximateNow(), QuicTime::Delta::Zero());
2825 }
2826}
2827
2828void QuicConnection::SendOrQueuePacket(SerializedPacket* packet) {
2829 // The caller of this function is responsible for checking CanWrite().
2830 if (packet->encrypted_buffer == nullptr) {
2831 QUIC_BUG << "packet.encrypted_buffer == nullptr in to SendOrQueuePacket";
2832 return;
2833 }
2834 // If there are already queued packets, queue this one immediately to ensure
2835 // it's written in sequence number order.
2836 if (!queued_packets_.empty() || !WritePacket(packet)) {
2837 // Take ownership of the underlying encrypted packet.
2838 packet->encrypted_buffer = CopyBuffer(*packet);
2839 queued_packets_.push_back(*packet);
2840 packet->retransmittable_frames.clear();
2841 }
2842
2843 ClearSerializedPacket(packet);
2844}
2845
2846void QuicConnection::OnPingTimeout() {
2847 if (!retransmission_alarm_->IsSet()) {
zhongyifbb25772019-04-10 16:54:08 -07002848 bool enable_half_rtt_tail_loss_probe =
2849 sent_packet_manager_.enable_half_rtt_tail_loss_probe();
2850 if (enable_half_rtt_tail_loss_probe &&
2851 GetQuicReloadableFlag(quic_ignore_tlpr_if_sending_ping)) {
zhongyi19461252019-04-29 12:44:25 -07002852 QUIC_RELOADABLE_FLAG_COUNT_N(quic_ignore_tlpr_if_sending_ping, 1, 2);
zhongyifbb25772019-04-10 16:54:08 -07002853 sent_packet_manager_.set_enable_half_rtt_tail_loss_probe(false);
2854 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002855 visitor_->SendPing();
zhongyifbb25772019-04-10 16:54:08 -07002856 if (enable_half_rtt_tail_loss_probe &&
2857 GetQuicReloadableFlag(quic_ignore_tlpr_if_sending_ping)) {
zhongyi19461252019-04-29 12:44:25 -07002858 QUIC_RELOADABLE_FLAG_COUNT_N(quic_ignore_tlpr_if_sending_ping, 2, 2);
zhongyifbb25772019-04-10 16:54:08 -07002859 sent_packet_manager_.set_enable_half_rtt_tail_loss_probe(true);
2860 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002861 }
2862}
2863
2864void QuicConnection::SendAck() {
QUICHE teamcd098022019-03-22 18:49:55 -07002865 DCHECK(!SupportsMultiplePacketNumberSpaces());
QUICHE teama6ef0a62019-03-07 20:34:33 -05002866 if (!received_packet_manager_.decide_when_to_send_acks()) {
2867 // When received_packet_manager decides when to send ack, delaying
2868 // ResetAckStates until ACK is successfully flushed.
2869 ResetAckStates();
2870 }
2871
2872 if (packet_generator_.deprecate_ack_bundling_mode()) {
2873 QUIC_DVLOG(1) << ENDPOINT << "Sending an ACK proactively";
2874 QuicFrames frames;
2875 frames.push_back(GetUpdatedAckFrame());
2876 if (!no_stop_waiting_frames_) {
2877 QuicStopWaitingFrame stop_waiting;
2878 PopulateStopWaitingFrame(&stop_waiting);
2879 frames.push_back(QuicFrame(stop_waiting));
2880 }
2881 if (received_packet_manager_.decide_when_to_send_acks()) {
2882 if (!packet_generator_.FlushAckFrame(frames)) {
2883 return;
2884 }
2885 ResetAckStates();
2886 } else {
2887 send_ack_when_on_can_write_ = !packet_generator_.FlushAckFrame(frames);
2888 }
2889 } else {
2890 packet_generator_.SetShouldSendAck(!no_stop_waiting_frames_);
2891 }
2892 if (consecutive_num_packets_with_no_retransmittable_frames_ <
2893 max_consecutive_num_packets_with_no_retransmittable_frames_) {
2894 return;
2895 }
2896 consecutive_num_packets_with_no_retransmittable_frames_ = 0;
2897 if (packet_generator_.HasRetransmittableFrames() ||
2898 visitor_->WillingAndAbleToWrite()) {
2899 // There are pending retransmittable frames.
2900 return;
2901 }
2902
2903 visitor_->OnAckNeedsRetransmittableFrame();
2904}
2905
2906void QuicConnection::OnPathDegradingTimeout() {
2907 is_path_degrading_ = true;
2908 visitor_->OnPathDegrading();
2909}
2910
2911void QuicConnection::OnRetransmissionTimeout() {
2912 DCHECK(!sent_packet_manager_.unacked_packets().empty());
2913 if (close_connection_after_five_rtos_ &&
2914 sent_packet_manager_.GetConsecutiveRtoCount() >= 4) {
2915 // Close on the 5th consecutive RTO, so after 4 previous RTOs have occurred.
2916 CloseConnection(QUIC_TOO_MANY_RTOS, "5 consecutive retransmission timeouts",
2917 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
2918 return;
2919 }
2920
2921 sent_packet_manager_.OnRetransmissionTimeout();
2922 WriteIfNotBlocked();
2923
2924 // A write failure can result in the connection being closed, don't attempt to
2925 // write further packets, or to set alarms.
2926 if (!connected_) {
2927 return;
2928 }
2929
2930 // In the TLP case, the SentPacketManager gives the connection the opportunity
2931 // to send new data before retransmitting.
2932 if (sent_packet_manager_.MaybeRetransmitTailLossProbe()) {
2933 // Send the pending retransmission now that it's been queued.
2934 WriteIfNotBlocked();
2935 }
2936
2937 // Ensure the retransmission alarm is always set if there are unacked packets
2938 // and nothing waiting to be sent.
2939 // This happens if the loss algorithm invokes a timer based loss, but the
2940 // packet doesn't need to be retransmitted.
2941 if (!HasQueuedData() && !retransmission_alarm_->IsSet()) {
2942 SetRetransmissionAlarm();
2943 }
2944}
2945
2946void QuicConnection::SetEncrypter(EncryptionLevel level,
2947 std::unique_ptr<QuicEncrypter> encrypter) {
2948 packet_generator_.SetEncrypter(level, std::move(encrypter));
2949}
2950
2951void QuicConnection::SetDiversificationNonce(
2952 const DiversificationNonce& nonce) {
2953 DCHECK_EQ(Perspective::IS_SERVER, perspective_);
2954 packet_generator_.SetDiversificationNonce(nonce);
2955}
2956
2957void QuicConnection::SetDefaultEncryptionLevel(EncryptionLevel level) {
2958 if (level != encryption_level_ && packet_generator_.HasQueuedFrames()) {
2959 // Flush all queued frames when encryption level changes.
2960 ScopedPacketFlusher flusher(this, NO_ACK);
2961 packet_generator_.FlushAllQueuedFrames();
2962 }
2963 encryption_level_ = level;
2964 packet_generator_.set_encryption_level(level);
2965}
2966
2967void QuicConnection::SetDecrypter(EncryptionLevel level,
2968 std::unique_ptr<QuicDecrypter> decrypter) {
2969 framer_.SetDecrypter(level, std::move(decrypter));
2970
2971 if (!undecryptable_packets_.empty() &&
2972 !process_undecryptable_packets_alarm_->IsSet()) {
2973 process_undecryptable_packets_alarm_->Set(clock_->ApproximateNow());
2974 }
2975}
2976
2977void QuicConnection::SetAlternativeDecrypter(
2978 EncryptionLevel level,
2979 std::unique_ptr<QuicDecrypter> decrypter,
2980 bool latch_once_used) {
2981 framer_.SetAlternativeDecrypter(level, std::move(decrypter), latch_once_used);
2982
2983 if (!undecryptable_packets_.empty() &&
2984 !process_undecryptable_packets_alarm_->IsSet()) {
2985 process_undecryptable_packets_alarm_->Set(clock_->ApproximateNow());
2986 }
2987}
2988
zhongyi546cc452019-04-12 15:27:49 -07002989void QuicConnection::InstallDecrypter(
2990 EncryptionLevel level,
2991 std::unique_ptr<QuicDecrypter> decrypter) {
2992 framer_.InstallDecrypter(level, std::move(decrypter));
2993 if (!undecryptable_packets_.empty() &&
2994 !process_undecryptable_packets_alarm_->IsSet()) {
2995 process_undecryptable_packets_alarm_->Set(clock_->ApproximateNow());
2996 }
2997}
2998
2999void QuicConnection::RemoveDecrypter(EncryptionLevel level) {
3000 framer_.RemoveDecrypter(level);
3001}
3002
QUICHE teama6ef0a62019-03-07 20:34:33 -05003003const QuicDecrypter* QuicConnection::decrypter() const {
3004 return framer_.decrypter();
3005}
3006
3007const QuicDecrypter* QuicConnection::alternative_decrypter() const {
3008 return framer_.alternative_decrypter();
3009}
3010
3011void QuicConnection::QueueUndecryptablePacket(
3012 const QuicEncryptedPacket& packet) {
3013 QUIC_DVLOG(1) << ENDPOINT << "Queueing undecryptable packet.";
3014 undecryptable_packets_.push_back(packet.Clone());
3015}
3016
3017void QuicConnection::MaybeProcessUndecryptablePackets() {
3018 process_undecryptable_packets_alarm_->Cancel();
3019
QUICHE team6987b4a2019-03-15 16:23:04 -07003020 if (undecryptable_packets_.empty() ||
3021 encryption_level_ == ENCRYPTION_INITIAL) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05003022 return;
3023 }
3024
3025 while (connected_ && !undecryptable_packets_.empty()) {
3026 // Making sure there is no pending frames when processing next undecrypted
3027 // packet because the queued ack frame may change.
3028 packet_generator_.FlushAllQueuedFrames();
3029 if (!connected_) {
3030 return;
3031 }
3032 QUIC_DVLOG(1) << ENDPOINT << "Attempting to process undecryptable packet";
3033 QuicEncryptedPacket* packet = undecryptable_packets_.front().get();
3034 if (!framer_.ProcessPacket(*packet) &&
3035 framer_.error() == QUIC_DECRYPTION_FAILURE) {
3036 QUIC_DVLOG(1) << ENDPOINT << "Unable to process undecryptable packet...";
3037 break;
3038 }
3039 QUIC_DVLOG(1) << ENDPOINT << "Processed undecryptable packet!";
3040 ++stats_.packets_processed;
3041 undecryptable_packets_.pop_front();
3042 }
3043
3044 // Once forward secure encryption is in use, there will be no
3045 // new keys installed and hence any undecryptable packets will
3046 // never be able to be decrypted.
3047 if (encryption_level_ == ENCRYPTION_FORWARD_SECURE) {
3048 if (debug_visitor_ != nullptr) {
3049 // TODO(rtenneti): perhaps more efficient to pass the number of
3050 // undecryptable packets as the argument to OnUndecryptablePacket so that
3051 // we just need to call OnUndecryptablePacket once?
3052 for (size_t i = 0; i < undecryptable_packets_.size(); ++i) {
3053 debug_visitor_->OnUndecryptablePacket();
3054 }
3055 }
3056 undecryptable_packets_.clear();
3057 }
3058}
3059
3060void QuicConnection::QueueCoalescedPacket(const QuicEncryptedPacket& packet) {
3061 QUIC_DVLOG(1) << ENDPOINT << "Queueing coalesced packet.";
3062 coalesced_packets_.push_back(packet.Clone());
3063}
3064
3065void QuicConnection::MaybeProcessCoalescedPackets() {
3066 bool processed = false;
3067 for (const auto& packet : coalesced_packets_) {
3068 if (!connected_) {
3069 return;
3070 }
3071
3072 // }
3073 // while (connected_ && !coalesced_packets_.empty()) {
3074 QUIC_DVLOG(1) << ENDPOINT << "Processing coalesced packet";
3075 // QuicEncryptedPacket* packet = coalesced_packets_.front().get();
3076 if (framer_.ProcessPacket(*packet)) {
3077 processed = true;
3078 } else {
3079 // If we are unable to decrypt this packet, it might be
3080 // because the CHLO or SHLO packet was lost.
3081 if (framer_.error() == QUIC_DECRYPTION_FAILURE) {
dschinazi6ece5002019-05-22 06:35:49 -07003082 ++stats_.undecryptable_packets_received;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003083 if (encryption_level_ != ENCRYPTION_FORWARD_SECURE &&
3084 undecryptable_packets_.size() < max_undecryptable_packets_) {
3085 QueueUndecryptablePacket(*packet);
3086 } else if (debug_visitor_ != nullptr) {
3087 debug_visitor_->OnUndecryptablePacket();
3088 }
3089 }
3090 }
3091 // coalesced_packets_.pop_front();
3092 }
3093 coalesced_packets_.clear();
3094 if (processed) {
3095 MaybeProcessUndecryptablePackets();
3096 }
3097}
3098
3099void QuicConnection::CloseConnection(
3100 QuicErrorCode error,
vasilvvc48c8712019-03-11 13:38:16 -07003101 const std::string& error_details,
QUICHE teama6ef0a62019-03-07 20:34:33 -05003102 ConnectionCloseBehavior connection_close_behavior) {
3103 DCHECK(!error_details.empty());
3104 if (!connected_) {
3105 QUIC_DLOG(INFO) << "Connection is already closed.";
3106 return;
3107 }
3108
3109 QUIC_DLOG(INFO) << ENDPOINT << "Closing connection: " << connection_id()
3110 << ", with error: " << QuicErrorCodeToString(error) << " ("
3111 << error << "), and details: " << error_details;
3112
ianswettdc1e7ab2019-05-03 16:10:44 -07003113 if (connection_close_behavior != ConnectionCloseBehavior::SILENT_CLOSE) {
3114 SendConnectionClosePacket(error, error_details);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003115 }
3116
3117 ConnectionCloseSource source = ConnectionCloseSource::FROM_SELF;
3118 if (perspective_ == Perspective::IS_CLIENT &&
3119 error == QUIC_CRYPTO_HANDSHAKE_STATELESS_REJECT) {
3120 // Regard stateless rejected connection as closed by server.
3121 source = ConnectionCloseSource::FROM_PEER;
3122 }
3123 TearDownLocalConnectionState(error, error_details, source);
3124}
3125
3126void QuicConnection::SendConnectionClosePacket(QuicErrorCode error,
ianswettdc1e7ab2019-05-03 16:10:44 -07003127 const std::string& details) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05003128 QUIC_DLOG(INFO) << ENDPOINT << "Sending connection close packet.";
QUICHE team2252b702019-05-14 23:55:14 -04003129 SetDefaultEncryptionLevel(GetConnectionCloseEncryptionLevel());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003130 ClearQueuedPackets();
ianswettdc1e7ab2019-05-03 16:10:44 -07003131 // If there was a packet write error, write the smallest close possible.
3132 AckBundling ack_mode = (error == QUIC_PACKET_WRITE_ERROR) ? NO_ACK : SEND_ACK;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003133 ScopedPacketFlusher flusher(this, ack_mode);
QUICHE teamcd098022019-03-22 18:49:55 -07003134 // When multiple packet number spaces is supported, an ACK frame will be
3135 // bundled when connection is not write blocked.
3136 if (!SupportsMultiplePacketNumberSpaces() &&
3137 packet_generator_.deprecate_ack_bundling_mode() && ack_mode == SEND_ACK &&
QUICHE teama6ef0a62019-03-07 20:34:33 -05003138 !GetUpdatedAckFrame().ack_frame->packets.Empty()) {
3139 SendAck();
3140 }
fkastenholze9d71a82019-04-09 05:12:13 -07003141 QuicConnectionCloseFrame* frame =
3142 new QuicConnectionCloseFrame(error, details);
fkastenholz04bd4f32019-04-16 12:24:38 -07003143 // If version99/IETF QUIC set the close type. Default close type is Google
3144 // QUIC.
fkastenholz72f509b2019-04-10 09:17:49 -07003145 if (transport_version() == QUIC_VERSION_99) {
3146 frame->close_type = IETF_QUIC_TRANSPORT_CONNECTION_CLOSE;
3147 }
fayang3203f252019-05-03 06:00:03 -07003148 packet_generator_.ConsumeRetransmittableControlFrame(QuicFrame(frame));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003149 packet_generator_.FlushAllQueuedFrames();
3150}
3151
3152void QuicConnection::TearDownLocalConnectionState(
3153 QuicErrorCode error,
vasilvvc48c8712019-03-11 13:38:16 -07003154 const std::string& error_details,
QUICHE teama6ef0a62019-03-07 20:34:33 -05003155 ConnectionCloseSource source) {
3156 if (!connected_) {
3157 QUIC_DLOG(INFO) << "Connection is already closed.";
3158 return;
3159 }
3160
3161 // If we are using a batch writer, flush packets queued in it, if any.
3162 FlushPackets();
3163 connected_ = false;
3164 DCHECK(visitor_ != nullptr);
3165 visitor_->OnConnectionClosed(error, error_details, source);
3166 if (debug_visitor_ != nullptr) {
3167 debug_visitor_->OnConnectionClosed(error, error_details, source);
3168 }
3169 // Cancel the alarms so they don't trigger any action now that the
3170 // connection is closed.
3171 CancelAllAlarms();
3172}
3173
3174void QuicConnection::CancelAllAlarms() {
3175 QUIC_DVLOG(1) << "Cancelling all QuicConnection alarms.";
3176
3177 ack_alarm_->Cancel();
3178 ping_alarm_->Cancel();
3179 retransmission_alarm_->Cancel();
3180 send_alarm_->Cancel();
3181 timeout_alarm_->Cancel();
3182 mtu_discovery_alarm_->Cancel();
3183 path_degrading_alarm_->Cancel();
renjietang11e4a3d2019-05-03 11:27:26 -07003184 process_undecryptable_packets_alarm_->Cancel();
QUICHE teama6ef0a62019-03-07 20:34:33 -05003185}
3186
3187QuicByteCount QuicConnection::max_packet_length() const {
3188 return packet_generator_.GetCurrentMaxPacketLength();
3189}
3190
3191void QuicConnection::SetMaxPacketLength(QuicByteCount length) {
3192 long_term_mtu_ = length;
3193 packet_generator_.SetMaxPacketLength(GetLimitedMaxPacketSize(length));
3194}
3195
3196bool QuicConnection::HasQueuedData() const {
3197 return pending_version_negotiation_packet_ || !queued_packets_.empty() ||
3198 packet_generator_.HasQueuedFrames();
3199}
3200
3201void QuicConnection::EnableSavingCryptoPackets() {
3202 save_crypto_packets_as_termination_packets_ = true;
3203}
3204
3205bool QuicConnection::CanWriteStreamData() {
3206 // Don't write stream data if there are negotiation or queued data packets
3207 // to send. Otherwise, continue and bundle as many frames as possible.
3208 if (pending_version_negotiation_packet_ || !queued_packets_.empty()) {
3209 return false;
3210 }
3211
3212 IsHandshake pending_handshake =
3213 visitor_->HasPendingHandshake() ? IS_HANDSHAKE : NOT_HANDSHAKE;
3214 // Sending queued packets may have caused the socket to become write blocked,
3215 // or the congestion manager to prohibit sending. If we've sent everything
3216 // we had queued and we're still not blocked, let the visitor know it can
3217 // write more.
3218 return ShouldGeneratePacket(HAS_RETRANSMITTABLE_DATA, pending_handshake);
3219}
3220
3221void QuicConnection::SetNetworkTimeouts(QuicTime::Delta handshake_timeout,
3222 QuicTime::Delta idle_timeout) {
3223 QUIC_BUG_IF(idle_timeout > handshake_timeout)
3224 << "idle_timeout:" << idle_timeout.ToMilliseconds()
3225 << " handshake_timeout:" << handshake_timeout.ToMilliseconds();
3226 // Adjust the idle timeout on client and server to prevent clients from
3227 // sending requests to servers which have already closed the connection.
3228 if (perspective_ == Perspective::IS_SERVER) {
3229 idle_timeout = idle_timeout + QuicTime::Delta::FromSeconds(3);
3230 } else if (idle_timeout > QuicTime::Delta::FromSeconds(1)) {
3231 idle_timeout = idle_timeout - QuicTime::Delta::FromSeconds(1);
3232 }
3233 handshake_timeout_ = handshake_timeout;
3234 idle_network_timeout_ = idle_timeout;
3235
3236 SetTimeoutAlarm();
3237}
3238
3239void QuicConnection::CheckForTimeout() {
3240 QuicTime now = clock_->ApproximateNow();
3241 QuicTime time_of_last_packet =
3242 std::max(time_of_last_received_packet_,
3243 time_of_first_packet_sent_after_receiving_);
3244
3245 // |delta| can be < 0 as |now| is approximate time but |time_of_last_packet|
3246 // is accurate time. However, this should not change the behavior of
3247 // timeout handling.
3248 QuicTime::Delta idle_duration = now - time_of_last_packet;
3249 QUIC_DVLOG(1) << ENDPOINT << "last packet "
3250 << time_of_last_packet.ToDebuggingValue()
3251 << " now:" << now.ToDebuggingValue()
3252 << " idle_duration:" << idle_duration.ToMicroseconds()
3253 << " idle_network_timeout: "
3254 << idle_network_timeout_.ToMicroseconds();
3255 if (idle_duration >= idle_network_timeout_) {
vasilvvc48c8712019-03-11 13:38:16 -07003256 const std::string error_details = "No recent network activity.";
QUICHE teama6ef0a62019-03-07 20:34:33 -05003257 QUIC_DVLOG(1) << ENDPOINT << error_details;
3258 if ((sent_packet_manager_.GetConsecutiveTlpCount() > 0 ||
3259 sent_packet_manager_.GetConsecutiveRtoCount() > 0 ||
3260 visitor_->ShouldKeepConnectionAlive())) {
3261 CloseConnection(QUIC_NETWORK_IDLE_TIMEOUT, error_details,
3262 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
3263 } else {
3264 CloseConnection(QUIC_NETWORK_IDLE_TIMEOUT, error_details,
3265 idle_timeout_connection_close_behavior_);
3266 }
3267 return;
3268 }
3269
3270 if (!handshake_timeout_.IsInfinite()) {
3271 QuicTime::Delta connected_duration = now - stats_.connection_creation_time;
3272 QUIC_DVLOG(1) << ENDPOINT
3273 << "connection time: " << connected_duration.ToMicroseconds()
3274 << " handshake timeout: "
3275 << handshake_timeout_.ToMicroseconds();
3276 if (connected_duration >= handshake_timeout_) {
vasilvvc48c8712019-03-11 13:38:16 -07003277 const std::string error_details = "Handshake timeout expired.";
QUICHE teama6ef0a62019-03-07 20:34:33 -05003278 QUIC_DVLOG(1) << ENDPOINT << error_details;
3279 CloseConnection(QUIC_HANDSHAKE_TIMEOUT, error_details,
3280 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
3281 return;
3282 }
3283 }
3284
3285 SetTimeoutAlarm();
3286}
3287
3288void QuicConnection::SetTimeoutAlarm() {
3289 QuicTime time_of_last_packet =
3290 std::max(time_of_last_received_packet_,
3291 time_of_first_packet_sent_after_receiving_);
3292
3293 QuicTime deadline = time_of_last_packet + idle_network_timeout_;
3294 if (!handshake_timeout_.IsInfinite()) {
3295 deadline = std::min(deadline,
3296 stats_.connection_creation_time + handshake_timeout_);
3297 }
3298
3299 timeout_alarm_->Update(deadline, QuicTime::Delta::Zero());
3300}
3301
3302void QuicConnection::SetPingAlarm() {
3303 if (perspective_ == Perspective::IS_SERVER) {
ianswettb7f7cd22019-05-01 08:04:16 -07003304 // Only clients send pings to avoid NATs from timing out.
QUICHE teama6ef0a62019-03-07 20:34:33 -05003305 return;
3306 }
3307 if (!visitor_->ShouldKeepConnectionAlive()) {
3308 ping_alarm_->Cancel();
ianswettb7f7cd22019-05-01 08:04:16 -07003309 // Don't send a ping unless the application (ie: HTTP/3) says to, usually
3310 // because it is expecting a response from the server.
QUICHE teama6ef0a62019-03-07 20:34:33 -05003311 return;
3312 }
3313 if (retransmittable_on_wire_timeout_.IsInfinite() ||
3314 sent_packet_manager_.HasInFlightPackets()) {
3315 // Extend the ping alarm.
3316 ping_alarm_->Update(clock_->ApproximateNow() + ping_timeout_,
3317 QuicTime::Delta::FromSeconds(1));
3318 return;
3319 }
3320 DCHECK_LT(retransmittable_on_wire_timeout_, ping_timeout_);
3321 // If it's already set to an earlier time, then don't update it.
3322 if (ping_alarm_->IsSet() &&
3323 ping_alarm_->deadline() <
3324 clock_->ApproximateNow() + retransmittable_on_wire_timeout_) {
3325 return;
3326 }
3327 // Use a shorter timeout if there are open streams, but nothing on the wire.
3328 ping_alarm_->Update(
3329 clock_->ApproximateNow() + retransmittable_on_wire_timeout_,
3330 QuicTime::Delta::FromMilliseconds(1));
3331}
3332
3333void QuicConnection::SetRetransmissionAlarm() {
3334 if (packet_generator_.PacketFlusherAttached()) {
3335 pending_retransmission_alarm_ = true;
3336 return;
3337 }
3338 QuicTime retransmission_time = sent_packet_manager_.GetRetransmissionTime();
3339 retransmission_alarm_->Update(retransmission_time,
3340 QuicTime::Delta::FromMilliseconds(1));
3341}
3342
3343void QuicConnection::SetPathDegradingAlarm() {
3344 if (perspective_ == Perspective::IS_SERVER) {
3345 return;
3346 }
3347 const QuicTime::Delta delay = sent_packet_manager_.GetPathDegradingDelay();
3348 path_degrading_alarm_->Update(clock_->ApproximateNow() + delay,
3349 QuicTime::Delta::FromMilliseconds(1));
3350}
3351
3352void QuicConnection::MaybeSetMtuAlarm(QuicPacketNumber sent_packet_number) {
3353 // Do not set the alarm if the target size is less than the current size.
3354 // This covers the case when |mtu_discovery_target_| is at its default value,
3355 // zero.
3356 if (mtu_discovery_target_ <= max_packet_length()) {
3357 return;
3358 }
3359
3360 if (mtu_probe_count_ >= kMtuDiscoveryAttempts) {
3361 return;
3362 }
3363
3364 if (mtu_discovery_alarm_->IsSet()) {
3365 return;
3366 }
3367
3368 if (sent_packet_number >= next_mtu_probe_at_) {
3369 // Use an alarm to send the MTU probe to ensure that no ScopedPacketFlushers
3370 // are active.
3371 mtu_discovery_alarm_->Set(clock_->ApproximateNow());
3372 }
3373}
3374
3375void QuicConnection::MaybeSetAckAlarmTo(QuicTime time) {
3376 DCHECK(packet_generator_.deprecate_ack_bundling_mode());
3377 if (!ack_alarm_->IsSet() || ack_alarm_->deadline() > time) {
3378 ack_alarm_->Update(time, QuicTime::Delta::Zero());
3379 }
3380}
3381
3382QuicConnection::ScopedPacketFlusher::ScopedPacketFlusher(
3383 QuicConnection* connection,
3384 AckBundling ack_mode)
3385 : connection_(connection),
3386 flush_and_set_pending_retransmission_alarm_on_delete_(false) {
3387 if (connection_ == nullptr) {
3388 return;
3389 }
3390
3391 if (!connection_->packet_generator_.PacketFlusherAttached()) {
3392 flush_and_set_pending_retransmission_alarm_on_delete_ = true;
3393 connection->packet_generator_.AttachPacketFlusher();
3394 }
3395 if (connection_->packet_generator_.deprecate_ack_bundling_mode()) {
3396 return;
3397 }
3398
3399 // If caller wants us to include an ack, check the delayed-ack timer to see if
3400 // there's ack info to be sent.
3401 if (ShouldSendAck(ack_mode)) {
3402 if (!connection_->GetUpdatedAckFrame().ack_frame->packets.Empty()) {
3403 QUIC_DVLOG(1) << "Bundling ack with outgoing packet.";
3404 connection_->SendAck();
3405 }
3406 }
3407}
3408
3409bool QuicConnection::ScopedPacketFlusher::ShouldSendAck(
3410 AckBundling ack_mode) const {
3411 DCHECK(!connection_->packet_generator_.deprecate_ack_bundling_mode());
3412 // If the ack alarm is set, make sure the ack has been updated.
3413 DCHECK(!connection_->ack_alarm_->IsSet() || connection_->ack_frame_updated())
3414 << "ack_mode:" << ack_mode;
3415 switch (ack_mode) {
3416 case SEND_ACK:
3417 return true;
3418 case SEND_ACK_IF_QUEUED:
3419 return connection_->ack_queued();
3420 case SEND_ACK_IF_PENDING:
3421 return connection_->ack_alarm_->IsSet() ||
3422 connection_->stop_waiting_count_ > 1;
3423 case NO_ACK:
3424 return false;
3425 default:
3426 QUIC_BUG << "Unsupported ack_mode.";
3427 return true;
3428 }
3429}
3430
3431QuicConnection::ScopedPacketFlusher::~ScopedPacketFlusher() {
3432 if (connection_ == nullptr) {
3433 return;
3434 }
3435
3436 if (flush_and_set_pending_retransmission_alarm_on_delete_) {
3437 if (connection_->packet_generator_.deprecate_ack_bundling_mode()) {
3438 if (connection_->received_packet_manager_.decide_when_to_send_acks()) {
3439 const QuicTime ack_timeout =
QUICHE teamb23daa72019-03-21 08:37:48 -07003440 connection_->use_uber_received_packet_manager_
QUICHE teamcd098022019-03-22 18:49:55 -07003441 ? connection_->uber_received_packet_manager_
3442 .GetEarliestAckTimeout()
QUICHE teamb23daa72019-03-21 08:37:48 -07003443 : connection_->received_packet_manager_.ack_timeout();
QUICHE teama6ef0a62019-03-07 20:34:33 -05003444 if (ack_timeout.IsInitialized()) {
3445 if (ack_timeout <= connection_->clock_->ApproximateNow() &&
3446 !connection_->CanWrite(NO_RETRANSMITTABLE_DATA)) {
3447 // Cancel ACK alarm if connection is write blocked, and ACK will be
3448 // sent when connection gets unblocked.
3449 connection_->ack_alarm_->Cancel();
3450 } else {
3451 connection_->MaybeSetAckAlarmTo(ack_timeout);
3452 }
3453 }
3454 }
3455 if (connection_->ack_alarm_->IsSet() &&
3456 connection_->ack_alarm_->deadline() <=
3457 connection_->clock_->ApproximateNow()) {
3458 // An ACK needs to be sent right now. This ACK did not get bundled
3459 // because either there was no data to write or packets were marked as
3460 // received after frames were queued in the generator.
3461 if (connection_->send_alarm_->IsSet() &&
3462 connection_->send_alarm_->deadline() <=
3463 connection_->clock_->ApproximateNow()) {
3464 // If send alarm will go off soon, let send alarm send the ACK.
3465 connection_->ack_alarm_->Cancel();
3466 if (!connection_->received_packet_manager_
3467 .decide_when_to_send_acks()) {
3468 connection_->send_ack_when_on_can_write_ = true;
3469 }
QUICHE teamcd098022019-03-22 18:49:55 -07003470 } else if (connection_->SupportsMultiplePacketNumberSpaces()) {
3471 connection_->SendAllPendingAcks();
QUICHE teama6ef0a62019-03-07 20:34:33 -05003472 } else {
3473 connection_->SendAck();
3474 }
3475 }
3476 }
3477 connection_->packet_generator_.Flush();
3478 connection_->FlushPackets();
3479 if (connection_->session_decides_what_to_write()) {
3480 // Reset transmission type.
3481 connection_->SetTransmissionType(NOT_RETRANSMISSION);
3482 }
3483
3484 // Once all transmissions are done, check if there is any outstanding data
3485 // to send and notify the congestion controller if not.
3486 //
3487 // Note that this means that the application limited check will happen as
3488 // soon as the last flusher gets destroyed, which is typically after a
3489 // single stream write is finished. This means that if all the data from a
3490 // single write goes through the connection, the application-limited signal
3491 // will fire even if the caller does a write operation immediately after.
3492 // There are two important approaches to remedy this situation:
3493 // (1) Instantiate ScopedPacketFlusher before performing multiple subsequent
3494 // writes, thus deferring this check until all writes are done.
3495 // (2) Write data in chunks sufficiently large so that they cause the
3496 // connection to be limited by the congestion control. Typically, this
3497 // would mean writing chunks larger than the product of the current
3498 // pacing rate and the pacer granularity. So, for instance, if the
3499 // pacing rate of the connection is 1 Gbps, and the pacer granularity is
3500 // 1 ms, the caller should send at least 125k bytes in order to not
3501 // be marked as application-limited.
3502 connection_->CheckIfApplicationLimited();
3503
3504 if (connection_->pending_retransmission_alarm_) {
3505 connection_->SetRetransmissionAlarm();
3506 connection_->pending_retransmission_alarm_ = false;
3507 }
3508 }
3509 DCHECK_EQ(flush_and_set_pending_retransmission_alarm_on_delete_,
3510 !connection_->packet_generator_.PacketFlusherAttached());
3511}
3512
3513HasRetransmittableData QuicConnection::IsRetransmittable(
3514 const SerializedPacket& packet) {
3515 // Retransmitted packets retransmittable frames are owned by the unacked
3516 // packet map, but are not present in the serialized packet.
3517 if (packet.transmission_type != NOT_RETRANSMISSION ||
3518 !packet.retransmittable_frames.empty()) {
3519 return HAS_RETRANSMITTABLE_DATA;
3520 } else {
3521 return NO_RETRANSMITTABLE_DATA;
3522 }
3523}
3524
3525bool QuicConnection::IsTerminationPacket(const SerializedPacket& packet) {
3526 if (packet.retransmittable_frames.empty()) {
3527 return false;
3528 }
3529 for (const QuicFrame& frame : packet.retransmittable_frames) {
3530 if (frame.type == CONNECTION_CLOSE_FRAME) {
3531 return true;
3532 }
3533 if (save_crypto_packets_as_termination_packets_ &&
3534 QuicUtils::IsHandshakeFrame(frame, transport_version())) {
3535 return true;
3536 }
3537 }
3538 return false;
3539}
3540
3541void QuicConnection::SetMtuDiscoveryTarget(QuicByteCount target) {
3542 mtu_discovery_target_ = GetLimitedMaxPacketSize(target);
3543}
3544
3545QuicByteCount QuicConnection::GetLimitedMaxPacketSize(
3546 QuicByteCount suggested_max_packet_size) {
3547 if (!peer_address_.IsInitialized()) {
3548 QUIC_BUG << "Attempted to use a connection without a valid peer address";
3549 return suggested_max_packet_size;
3550 }
3551
3552 const QuicByteCount writer_limit = writer_->GetMaxPacketSize(peer_address());
3553
3554 QuicByteCount max_packet_size = suggested_max_packet_size;
3555 if (max_packet_size > writer_limit) {
3556 max_packet_size = writer_limit;
3557 }
dschinazi66dea072019-04-09 11:41:06 -07003558 if (max_packet_size > kMaxOutgoingPacketSize) {
3559 max_packet_size = kMaxOutgoingPacketSize;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003560 }
3561 return max_packet_size;
3562}
3563
3564void QuicConnection::SendMtuDiscoveryPacket(QuicByteCount target_mtu) {
3565 // Currently, this limit is ensured by the caller.
3566 DCHECK_EQ(target_mtu, GetLimitedMaxPacketSize(target_mtu));
3567
3568 // Send the probe.
3569 packet_generator_.GenerateMtuDiscoveryPacket(target_mtu);
3570}
3571
3572// TODO(zhongyi): change this method to generate a connectivity probing packet
3573// and let the caller to call writer to write the packet and handle write
3574// status.
3575bool QuicConnection::SendConnectivityProbingPacket(
3576 QuicPacketWriter* probing_writer,
3577 const QuicSocketAddress& peer_address) {
3578 return SendGenericPathProbePacket(probing_writer, peer_address,
3579 /* is_response= */ false);
3580}
3581
3582void QuicConnection::SendConnectivityProbingResponsePacket(
3583 const QuicSocketAddress& peer_address) {
3584 SendGenericPathProbePacket(nullptr, peer_address,
3585 /* is_response= */ true);
3586}
3587
3588bool QuicConnection::SendGenericPathProbePacket(
3589 QuicPacketWriter* probing_writer,
3590 const QuicSocketAddress& peer_address,
3591 bool is_response) {
3592 DCHECK(peer_address.IsInitialized());
3593 if (!connected_) {
3594 QUIC_BUG << "Not sending connectivity probing packet as connection is "
3595 << "disconnected.";
3596 return false;
3597 }
3598 if (perspective_ == Perspective::IS_SERVER && probing_writer == nullptr) {
3599 // Server can use default packet writer to write packet.
3600 probing_writer = writer_;
3601 }
3602 DCHECK(probing_writer);
3603
3604 if (probing_writer->IsWriteBlocked()) {
3605 QUIC_DLOG(INFO)
3606 << ENDPOINT
3607 << "Writer blocked when sending connectivity probing packet.";
3608 if (probing_writer == writer_) {
3609 // Visitor should not be write blocked if the probing writer is not the
3610 // default packet writer.
3611 visitor_->OnWriteBlocked();
3612 }
3613 return true;
3614 }
3615
3616 QUIC_DLOG(INFO) << ENDPOINT
3617 << "Sending path probe packet for connection_id = "
dschinazi7b9278c2019-05-20 07:36:21 -07003618 << server_connection_id_;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003619
3620 OwningSerializedPacketPointer probing_packet;
3621 if (transport_version() != QUIC_VERSION_99) {
3622 // Non-IETF QUIC, generate a padded ping regardless of whether this is a
3623 // request or a response.
3624 probing_packet = packet_generator_.SerializeConnectivityProbingPacket();
3625 } else {
3626 if (is_response) {
3627 // Respond using IETF QUIC PATH_RESPONSE frame
3628 if (IsCurrentPacketConnectivityProbing()) {
3629 // Pad the response if the request was a google connectivity probe
3630 // (padded).
3631 probing_packet =
3632 packet_generator_.SerializePathResponseConnectivityProbingPacket(
3633 received_path_challenge_payloads_, /* is_padded = */ true);
3634 received_path_challenge_payloads_.clear();
3635 } else {
3636 // Do not pad the response if the path challenge was not a google
3637 // connectivity probe.
3638 probing_packet =
3639 packet_generator_.SerializePathResponseConnectivityProbingPacket(
3640 received_path_challenge_payloads_,
3641 /* is_padded = */ false);
3642 received_path_challenge_payloads_.clear();
3643 }
3644 } else {
3645 // Request using IETF QUIC PATH_CHALLENGE frame
3646 transmitted_connectivity_probe_payload_ =
3647 QuicMakeUnique<QuicPathFrameBuffer>();
3648 probing_packet =
3649 packet_generator_.SerializePathChallengeConnectivityProbingPacket(
3650 transmitted_connectivity_probe_payload_.get());
3651 if (!probing_packet) {
3652 transmitted_connectivity_probe_payload_ = nullptr;
3653 }
3654 }
3655 }
3656
3657 DCHECK_EQ(IsRetransmittable(*probing_packet), NO_RETRANSMITTABLE_DATA);
3658
3659 const QuicTime packet_send_time = clock_->Now();
dschinazi965ce092019-05-23 06:29:01 -07003660 QUIC_DVLOG(2) << ENDPOINT
3661 << "Sending path probe packet for server connection ID "
3662 << server_connection_id_ << std::endl
3663 << QuicTextUtils::HexDump(
3664 QuicStringPiece(probing_packet->encrypted_buffer,
3665 probing_packet->encrypted_length));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003666 WriteResult result = probing_writer->WritePacket(
3667 probing_packet->encrypted_buffer, probing_packet->encrypted_length,
3668 self_address().host(), peer_address, per_packet_options_);
3669
3670 // If using a batch writer and the probing packet is buffered, flush it.
3671 if (probing_writer->IsBatchMode() && result.status == WRITE_STATUS_OK &&
3672 result.bytes_written == 0) {
3673 result = probing_writer->Flush();
3674 }
3675
3676 if (IsWriteError(result.status)) {
3677 // Write error for any connectivity probe should not affect the connection
3678 // as it is sent on a different path.
3679 QUIC_DLOG(INFO) << ENDPOINT << "Write probing packet failed with error = "
3680 << result.error_code;
3681 return false;
3682 }
3683
3684 if (debug_visitor_ != nullptr) {
3685 debug_visitor_->OnPacketSent(
3686 *probing_packet, probing_packet->original_packet_number,
3687 probing_packet->transmission_type, packet_send_time);
3688 }
3689
3690 // Call OnPacketSent regardless of the write result.
3691 sent_packet_manager_.OnPacketSent(
3692 probing_packet.get(), probing_packet->original_packet_number,
3693 packet_send_time, probing_packet->transmission_type,
3694 NO_RETRANSMITTABLE_DATA);
3695
3696 if (IsWriteBlockedStatus(result.status)) {
3697 if (probing_writer == writer_) {
3698 // Visitor should not be write blocked if the probing writer is not the
3699 // default packet writer.
3700 visitor_->OnWriteBlocked();
3701 }
3702 if (result.status == WRITE_STATUS_BLOCKED_DATA_BUFFERED) {
3703 QUIC_DLOG(INFO) << ENDPOINT << "Write probing packet blocked";
3704 }
3705 }
3706
3707 return true;
3708}
3709
3710void QuicConnection::DiscoverMtu() {
3711 DCHECK(!mtu_discovery_alarm_->IsSet());
3712
3713 // Check if the MTU has been already increased.
3714 if (mtu_discovery_target_ <= max_packet_length()) {
3715 return;
3716 }
3717
3718 // Calculate the packet number of the next probe *before* sending the current
3719 // one. Otherwise, when SendMtuDiscoveryPacket() is called,
3720 // MaybeSetMtuAlarm() will not realize that the probe has been just sent, and
3721 // will reschedule this probe again.
3722 packets_between_mtu_probes_ *= 2;
3723 next_mtu_probe_at_ = sent_packet_manager_.GetLargestSentPacket() +
3724 packets_between_mtu_probes_ + 1;
3725 ++mtu_probe_count_;
3726
3727 QUIC_DVLOG(2) << "Sending a path MTU discovery packet #" << mtu_probe_count_;
3728 SendMtuDiscoveryPacket(mtu_discovery_target_);
3729
3730 DCHECK(!mtu_discovery_alarm_->IsSet());
3731}
3732
3733void QuicConnection::OnEffectivePeerMigrationValidated() {
3734 if (active_effective_peer_migration_type_ == NO_CHANGE) {
3735 QUIC_BUG << "No migration underway.";
3736 return;
3737 }
3738 highest_packet_sent_before_effective_peer_migration_.Clear();
3739 active_effective_peer_migration_type_ = NO_CHANGE;
3740}
3741
3742void QuicConnection::StartEffectivePeerMigration(AddressChangeType type) {
3743 // TODO(fayang): Currently, all peer address change type are allowed. Need to
3744 // add a method ShouldAllowPeerAddressChange(PeerAddressChangeType type) to
3745 // determine whether |type| is allowed.
3746 if (type == NO_CHANGE) {
3747 QUIC_BUG << "EffectivePeerMigration started without address change.";
3748 return;
3749 }
3750 QUIC_DLOG(INFO) << ENDPOINT << "Effective peer's ip:port changed from "
3751 << effective_peer_address_.ToString() << " to "
3752 << GetEffectivePeerAddressFromCurrentPacket().ToString()
3753 << ", address change type is " << type
3754 << ", migrating connection.";
3755
3756 highest_packet_sent_before_effective_peer_migration_ =
3757 sent_packet_manager_.GetLargestSentPacket();
3758 effective_peer_address_ = GetEffectivePeerAddressFromCurrentPacket();
3759 active_effective_peer_migration_type_ = type;
3760
3761 // TODO(wub): Move these calls to OnEffectivePeerMigrationValidated.
3762 OnConnectionMigration(type);
3763}
3764
3765void QuicConnection::OnConnectionMigration(AddressChangeType addr_change_type) {
3766 visitor_->OnConnectionMigration(addr_change_type);
3767 sent_packet_manager_.OnConnectionMigration(addr_change_type);
3768}
3769
3770bool QuicConnection::IsCurrentPacketConnectivityProbing() const {
3771 return is_current_packet_connectivity_probing_;
3772}
3773
3774bool QuicConnection::ack_frame_updated() const {
QUICHE teamb23daa72019-03-21 08:37:48 -07003775 if (use_uber_received_packet_manager_) {
QUICHE team1dfa46b2019-03-22 10:39:10 -07003776 return uber_received_packet_manager_.IsAckFrameUpdated();
QUICHE teamb23daa72019-03-21 08:37:48 -07003777 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05003778 return received_packet_manager_.ack_frame_updated();
3779}
3780
3781QuicStringPiece QuicConnection::GetCurrentPacket() {
3782 if (current_packet_data_ == nullptr) {
3783 return QuicStringPiece();
3784 }
3785 return QuicStringPiece(current_packet_data_, last_size_);
3786}
3787
3788bool QuicConnection::MaybeConsiderAsMemoryCorruption(
3789 const QuicStreamFrame& frame) {
nharper46833c32019-05-15 21:33:05 -07003790 if (QuicUtils::IsCryptoStreamId(transport_version(), frame.stream_id) ||
QUICHE team6987b4a2019-03-15 16:23:04 -07003791 last_decrypted_packet_level_ != ENCRYPTION_INITIAL) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05003792 return false;
3793 }
3794
3795 if (perspective_ == Perspective::IS_SERVER &&
3796 frame.data_length >= sizeof(kCHLO) &&
3797 strncmp(frame.data_buffer, reinterpret_cast<const char*>(&kCHLO),
3798 sizeof(kCHLO)) == 0) {
3799 return true;
3800 }
3801
3802 if (perspective_ == Perspective::IS_CLIENT &&
3803 frame.data_length >= sizeof(kREJ) &&
3804 strncmp(frame.data_buffer, reinterpret_cast<const char*>(&kREJ),
3805 sizeof(kREJ)) == 0) {
3806 return true;
3807 }
3808
3809 return false;
3810}
3811
3812void QuicConnection::MaybeSendProbingRetransmissions() {
3813 DCHECK(fill_up_link_during_probing_);
3814
3815 // Don't send probing retransmissions until the handshake has completed.
3816 if (!sent_packet_manager_.handshake_confirmed() ||
3817 sent_packet_manager().HasUnackedCryptoPackets()) {
3818 return;
3819 }
3820
3821 if (probing_retransmission_pending_) {
3822 QUIC_BUG << "MaybeSendProbingRetransmissions is called while another call "
3823 "to it is already in progress";
3824 return;
3825 }
3826
3827 probing_retransmission_pending_ = true;
3828 SendProbingRetransmissions();
3829 probing_retransmission_pending_ = false;
3830}
3831
3832void QuicConnection::CheckIfApplicationLimited() {
3833 if (session_decides_what_to_write() && probing_retransmission_pending_) {
3834 return;
3835 }
3836
3837 bool application_limited =
3838 queued_packets_.empty() &&
3839 !sent_packet_manager_.HasPendingRetransmissions() &&
3840 !visitor_->WillingAndAbleToWrite();
3841
3842 if (!application_limited) {
3843 return;
3844 }
3845
3846 if (fill_up_link_during_probing_) {
3847 MaybeSendProbingRetransmissions();
3848 if (!CanWrite(HAS_RETRANSMITTABLE_DATA)) {
3849 return;
3850 }
3851 }
3852
3853 sent_packet_manager_.OnApplicationLimited();
3854}
3855
3856void QuicConnection::UpdatePacketContent(PacketContent type) {
3857 if (current_packet_content_ == NOT_PADDED_PING) {
3858 // We have already learned the current packet is not a connectivity
3859 // probing packet. Peer migration should have already been started earlier
3860 // if needed.
3861 return;
3862 }
3863
3864 if (type == NO_FRAMES_RECEIVED) {
3865 return;
3866 }
3867
3868 if (type == FIRST_FRAME_IS_PING) {
3869 if (current_packet_content_ == NO_FRAMES_RECEIVED) {
3870 current_packet_content_ = FIRST_FRAME_IS_PING;
3871 return;
3872 }
3873 }
3874
3875 // In Google QUIC we look for a packet with just a PING and PADDING.
3876 // For IETF QUIC, the packet must consist of just a PATH_CHALLENGE frame,
3877 // followed by PADDING. If the condition is met, mark things as
3878 // connectivity-probing, causing later processing to generate the correct
3879 // response.
3880 if (type == SECOND_FRAME_IS_PADDING &&
3881 current_packet_content_ == FIRST_FRAME_IS_PING) {
3882 current_packet_content_ = SECOND_FRAME_IS_PADDING;
3883 if (perspective_ == Perspective::IS_SERVER) {
3884 is_current_packet_connectivity_probing_ =
3885 current_effective_peer_migration_type_ != NO_CHANGE;
3886 } else {
3887 is_current_packet_connectivity_probing_ =
3888 (last_packet_source_address_ != peer_address_) ||
3889 (last_packet_destination_address_ != self_address_);
3890 }
3891 return;
3892 }
3893
3894 current_packet_content_ = NOT_PADDED_PING;
QUICHE team1f3de242019-03-20 07:24:48 -07003895 if (GetLargestReceivedPacket().IsInitialized() &&
3896 last_header_.packet_number == GetLargestReceivedPacket()) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05003897 direct_peer_address_ = last_packet_source_address_;
3898 if (current_effective_peer_migration_type_ != NO_CHANGE) {
3899 // Start effective peer migration immediately when the current packet is
3900 // confirmed not a connectivity probing packet.
QUICHE team1f3de242019-03-20 07:24:48 -07003901 // TODO(fayang): When multiple packet number spaces is supported, only
3902 // start peer migration for the application data.
QUICHE teama6ef0a62019-03-07 20:34:33 -05003903 StartEffectivePeerMigration(current_effective_peer_migration_type_);
3904 }
3905 }
3906 current_effective_peer_migration_type_ = NO_CHANGE;
3907}
3908
3909void QuicConnection::MaybeEnableSessionDecidesWhatToWrite() {
3910 // Only enable session decides what to write code path for version 42+,
3911 // because it needs the receiver to allow receiving overlapping stream data.
3912 const bool enable_session_decides_what_to_write =
3913 transport_version() > QUIC_VERSION_39;
3914 sent_packet_manager_.SetSessionDecideWhatToWrite(
3915 enable_session_decides_what_to_write);
3916 packet_generator_.SetCanSetTransmissionType(
3917 enable_session_decides_what_to_write);
3918}
3919
3920void QuicConnection::PostProcessAfterAckFrame(bool send_stop_waiting,
3921 bool acked_new_packet) {
3922 if (no_stop_waiting_frames_) {
QUICHE teamb23daa72019-03-21 08:37:48 -07003923 if (use_uber_received_packet_manager_) {
3924 uber_received_packet_manager_.DontWaitForPacketsBefore(
QUICHE team1dfa46b2019-03-22 10:39:10 -07003925 last_decrypted_packet_level_,
QUICHE teamb23daa72019-03-21 08:37:48 -07003926 sent_packet_manager_.largest_packet_peer_knows_is_acked());
3927 } else {
3928 received_packet_manager_.DontWaitForPacketsBefore(
3929 sent_packet_manager_.largest_packet_peer_knows_is_acked());
3930 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05003931 }
3932 // Always reset the retransmission alarm when an ack comes in, since we now
3933 // have a better estimate of the current rtt than when it was set.
3934 SetRetransmissionAlarm();
3935 MaybeSetPathDegradingAlarm(acked_new_packet);
3936
QUICHE teama6ef0a62019-03-07 20:34:33 -05003937 if (send_stop_waiting) {
3938 ++stop_waiting_count_;
3939 } else {
3940 stop_waiting_count_ = 0;
3941 }
3942}
3943
3944void QuicConnection::MaybeSetPathDegradingAlarm(bool acked_new_packet) {
3945 if (!sent_packet_manager_.HasInFlightPackets()) {
3946 // There are no retransmittable packets on the wire, so it's impossible to
3947 // say if the connection has degraded.
3948 path_degrading_alarm_->Cancel();
3949 } else if (acked_new_packet) {
3950 // A previously-unacked packet has been acked, which means forward progress
3951 // has been made. Unset |is_path_degrading| if the path was considered as
3952 // degrading previously. Set/update the path degrading alarm.
3953 is_path_degrading_ = false;
3954 SetPathDegradingAlarm();
3955 }
3956}
3957
3958void QuicConnection::SetSessionNotifier(
3959 SessionNotifierInterface* session_notifier) {
3960 sent_packet_manager_.SetSessionNotifier(session_notifier);
3961}
3962
3963void QuicConnection::SetDataProducer(
3964 QuicStreamFrameDataProducer* data_producer) {
3965 framer_.set_data_producer(data_producer);
3966}
3967
3968void QuicConnection::SetTransmissionType(TransmissionType type) {
3969 packet_generator_.SetTransmissionType(type);
3970}
3971
3972bool QuicConnection::session_decides_what_to_write() const {
3973 return sent_packet_manager_.session_decides_what_to_write();
3974}
3975
3976void QuicConnection::UpdateReleaseTimeIntoFuture() {
3977 DCHECK(supports_release_time_);
3978
3979 release_time_into_future_ = std::max(
3980 QuicTime::Delta::FromMilliseconds(kMinReleaseTimeIntoFutureMs),
3981 std::min(
3982 QuicTime::Delta::FromMilliseconds(
3983 GetQuicFlag(FLAGS_quic_max_pace_time_into_future_ms)),
3984 sent_packet_manager_.GetRttStats()->SmoothedOrInitialRtt() *
3985 GetQuicFlag(FLAGS_quic_pace_time_into_future_srtt_fraction)));
3986}
3987
3988void QuicConnection::ResetAckStates() {
3989 ack_alarm_->Cancel();
3990 ack_queued_ = false;
3991 stop_waiting_count_ = 0;
3992 num_retransmittable_packets_received_since_last_ack_sent_ = 0;
3993 num_packets_received_since_last_ack_sent_ = 0;
3994 if (received_packet_manager_.decide_when_to_send_acks()) {
QUICHE teamb23daa72019-03-21 08:37:48 -07003995 if (use_uber_received_packet_manager_) {
QUICHE team1dfa46b2019-03-22 10:39:10 -07003996 uber_received_packet_manager_.ResetAckStates(encryption_level_);
QUICHE teamb23daa72019-03-21 08:37:48 -07003997 } else {
3998 received_packet_manager_.ResetAckStates();
3999 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004000 }
4001}
4002
4003MessageStatus QuicConnection::SendMessage(QuicMessageId message_id,
4004 QuicMemSliceSpan message) {
4005 if (transport_version() <= QUIC_VERSION_44) {
4006 QUIC_BUG << "MESSAGE frame is not supported for version "
4007 << transport_version();
4008 return MESSAGE_STATUS_UNSUPPORTED;
4009 }
ianswettb239f862019-04-05 09:15:06 -07004010 if (message.total_length() > GetCurrentLargestMessagePayload()) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05004011 return MESSAGE_STATUS_TOO_LARGE;
4012 }
4013 if (!CanWrite(HAS_RETRANSMITTABLE_DATA)) {
4014 return MESSAGE_STATUS_BLOCKED;
4015 }
4016 ScopedPacketFlusher flusher(this, SEND_ACK_IF_PENDING);
4017 return packet_generator_.AddMessageFrame(message_id, message);
4018}
4019
ianswettb239f862019-04-05 09:15:06 -07004020QuicPacketLength QuicConnection::GetCurrentLargestMessagePayload() const {
4021 return packet_generator_.GetCurrentLargestMessagePayload();
4022}
4023
4024QuicPacketLength QuicConnection::GetGuaranteedLargestMessagePayload() const {
4025 return packet_generator_.GetGuaranteedLargestMessagePayload();
QUICHE teama6ef0a62019-03-07 20:34:33 -05004026}
4027
zhongyi546cc452019-04-12 15:27:49 -07004028uint32_t QuicConnection::cipher_id() const {
4029 if (version().KnowsWhichDecrypterToUse()) {
4030 return framer_.GetDecrypter(last_decrypted_packet_level_)->cipher_id();
4031 }
4032 return framer_.decrypter()->cipher_id();
4033}
4034
QUICHE teama6ef0a62019-03-07 20:34:33 -05004035bool QuicConnection::ShouldSetAckAlarm() const {
4036 DCHECK(ack_frame_updated());
4037 if (ack_alarm_->IsSet()) {
4038 // ACK alarm has been set.
4039 return false;
4040 }
4041 if (GetQuicReloadableFlag(quic_fix_spurious_ack_alarm) &&
4042 packet_generator_.should_send_ack()) {
4043 // If the generator is already configured to send an ACK, then there is no
4044 // need to schedule the ACK alarm. The updated ACK information will be sent
4045 // when the generator flushes.
4046 QUIC_RELOADABLE_FLAG_COUNT(quic_fix_spurious_ack_alarm);
4047 return false;
4048 }
4049 return true;
4050}
4051
4052EncryptionLevel QuicConnection::GetConnectionCloseEncryptionLevel() const {
QUICHE teama6ef0a62019-03-07 20:34:33 -05004053 if (perspective_ == Perspective::IS_CLIENT) {
4054 return encryption_level_;
4055 }
4056 if (sent_packet_manager_.handshake_confirmed()) {
4057 // A forward secure packet has been received.
dschinazi965ce092019-05-23 06:29:01 -07004058 QUIC_BUG_IF(encryption_level_ != ENCRYPTION_FORWARD_SECURE)
4059 << ENDPOINT << "Unexpected connection close encryption level "
4060 << QuicUtils::EncryptionLevelToString(encryption_level_);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004061 return ENCRYPTION_FORWARD_SECURE;
4062 }
4063 if (framer_.HasEncrypterOfEncryptionLevel(ENCRYPTION_ZERO_RTT)) {
4064 if (encryption_level_ != ENCRYPTION_ZERO_RTT) {
4065 if (transport_version() > QUIC_VERSION_43) {
4066 QUIC_CODE_COUNT(quic_wrong_encryption_level_connection_close_ietf);
4067 } else {
4068 QUIC_CODE_COUNT(quic_wrong_encryption_level_connection_close);
4069 }
4070 }
4071 return ENCRYPTION_ZERO_RTT;
4072 }
QUICHE team6987b4a2019-03-15 16:23:04 -07004073 return ENCRYPTION_INITIAL;
QUICHE teama6ef0a62019-03-07 20:34:33 -05004074}
4075
QUICHE teamcd098022019-03-22 18:49:55 -07004076void QuicConnection::SendAllPendingAcks() {
4077 DCHECK(SupportsMultiplePacketNumberSpaces());
4078 QUIC_DVLOG(1) << ENDPOINT << "Trying to send all pending ACKs";
4079 // Latches current encryption level.
4080 const EncryptionLevel current_encryption_level = encryption_level_;
4081 for (int8_t i = INITIAL_DATA; i <= APPLICATION_DATA; ++i) {
4082 const QuicTime ack_timeout = uber_received_packet_manager_.GetAckTimeout(
4083 static_cast<PacketNumberSpace>(i));
4084 if (!ack_timeout.IsInitialized() ||
4085 ack_timeout > clock_->ApproximateNow()) {
4086 continue;
4087 }
dschinazi05e62b12019-04-18 15:43:41 -07004088 if (!framer_.HasEncrypterOfEncryptionLevel(
4089 QuicUtils::GetEncryptionLevel(static_cast<PacketNumberSpace>(i)))) {
4090 QUIC_BUG << ENDPOINT << "Cannot send ACKs for packet number space "
4091 << static_cast<uint32_t>(i)
4092 << " without corresponding encrypter";
4093 continue;
4094 }
QUICHE teamcd098022019-03-22 18:49:55 -07004095 QUIC_DVLOG(1) << ENDPOINT << "Sending ACK of packet number space: "
4096 << static_cast<uint32_t>(i);
4097 // Switch to the appropriate encryption level.
4098 SetDefaultEncryptionLevel(
4099 QuicUtils::GetEncryptionLevel(static_cast<PacketNumberSpace>(i)));
4100 QuicFrames frames;
4101 frames.push_back(uber_received_packet_manager_.GetUpdatedAckFrame(
4102 static_cast<PacketNumberSpace>(i), clock_->ApproximateNow()));
4103 const bool flushed = packet_generator_.FlushAckFrame(frames);
4104 if (!flushed) {
4105 // Connection is write blocked.
QUICHE teamdb061532019-03-23 18:23:05 -07004106 QUIC_BUG_IF(!writer_->IsWriteBlocked())
4107 << "Writer not blocked, but ACK not flushed for packet space:" << i;
QUICHE teamcd098022019-03-22 18:49:55 -07004108 break;
4109 }
4110 ResetAckStates();
4111 }
4112 // Restores encryption level.
4113 SetDefaultEncryptionLevel(current_encryption_level);
4114
4115 const QuicTime timeout =
4116 uber_received_packet_manager_.GetEarliestAckTimeout();
4117 if (timeout.IsInitialized()) {
4118 // If there are ACKs pending, re-arm ack alarm.
4119 ack_alarm_->Set(timeout);
4120 }
4121 // Only try to bundle retransmittable data with ACK frame if default
4122 // encryption level is forward secure.
4123 if (encryption_level_ != ENCRYPTION_FORWARD_SECURE ||
4124 consecutive_num_packets_with_no_retransmittable_frames_ <
4125 max_consecutive_num_packets_with_no_retransmittable_frames_) {
4126 return;
4127 }
4128 consecutive_num_packets_with_no_retransmittable_frames_ = 0;
4129 if (packet_generator_.HasRetransmittableFrames() ||
4130 visitor_->WillingAndAbleToWrite()) {
4131 // There are pending retransmittable frames.
4132 return;
4133 }
4134
4135 visitor_->OnAckNeedsRetransmittableFrame();
4136}
4137
4138void QuicConnection::MaybeEnableMultiplePacketNumberSpacesSupport() {
4139 const bool enable_multiple_packet_number_spaces =
4140 version().handshake_protocol == PROTOCOL_TLS1_3 &&
4141 use_uber_received_packet_manager_ &&
4142 sent_packet_manager_.use_uber_loss_algorithm() &&
4143 GetQuicRestartFlag(quic_enable_accept_random_ipn);
4144 if (!enable_multiple_packet_number_spaces) {
4145 return;
4146 }
4147 QUIC_DVLOG(1) << ENDPOINT << "connection " << connection_id()
4148 << " supports multiple packet number spaces";
4149 framer_.EnableMultiplePacketNumberSpacesSupport();
4150 sent_packet_manager_.EnableMultiplePacketNumberSpacesSupport();
4151 uber_received_packet_manager_.EnableMultiplePacketNumberSpacesSupport();
4152}
4153
4154bool QuicConnection::SupportsMultiplePacketNumberSpaces() const {
4155 return sent_packet_manager_.supports_multiple_packet_number_spaces();
4156}
4157
QUICHE team76e1c622019-03-19 14:36:39 -07004158void QuicConnection::SetLargestReceivedPacketWithAck(
4159 QuicPacketNumber new_value) {
QUICHE teamcd098022019-03-22 18:49:55 -07004160 if (SupportsMultiplePacketNumberSpaces()) {
4161 largest_seen_packets_with_ack_[QuicUtils::GetPacketNumberSpace(
4162 last_decrypted_packet_level_)] = new_value;
4163 } else {
4164 largest_seen_packet_with_ack_ = new_value;
4165 }
QUICHE team76e1c622019-03-19 14:36:39 -07004166}
4167
4168QuicPacketNumber QuicConnection::GetLargestReceivedPacketWithAck() const {
QUICHE teamcd098022019-03-22 18:49:55 -07004169 if (SupportsMultiplePacketNumberSpaces()) {
4170 return largest_seen_packets_with_ack_[QuicUtils::GetPacketNumberSpace(
4171 last_decrypted_packet_level_)];
4172 }
QUICHE team76e1c622019-03-19 14:36:39 -07004173 return largest_seen_packet_with_ack_;
4174}
4175
4176QuicPacketNumber QuicConnection::GetLargestSentPacket() const {
QUICHE teamcd098022019-03-22 18:49:55 -07004177 if (SupportsMultiplePacketNumberSpaces()) {
4178 return sent_packet_manager_.GetLargestSentPacket(
4179 last_decrypted_packet_level_);
4180 }
QUICHE team76e1c622019-03-19 14:36:39 -07004181 return sent_packet_manager_.GetLargestSentPacket();
4182}
4183
4184QuicPacketNumber QuicConnection::GetLargestAckedPacket() const {
QUICHE teamcd098022019-03-22 18:49:55 -07004185 if (SupportsMultiplePacketNumberSpaces()) {
4186 return sent_packet_manager_.GetLargestAckedPacket(
4187 last_decrypted_packet_level_);
4188 }
QUICHE team76e1c622019-03-19 14:36:39 -07004189 return sent_packet_manager_.GetLargestObserved();
4190}
4191
QUICHE team1f3de242019-03-20 07:24:48 -07004192QuicPacketNumber QuicConnection::GetLargestReceivedPacket() const {
QUICHE teamb23daa72019-03-21 08:37:48 -07004193 if (use_uber_received_packet_manager_) {
QUICHE team1dfa46b2019-03-22 10:39:10 -07004194 return uber_received_packet_manager_.GetLargestObserved(
4195 last_decrypted_packet_level_);
QUICHE teamb23daa72019-03-21 08:37:48 -07004196 }
QUICHE team1f3de242019-03-20 07:24:48 -07004197 return received_packet_manager_.GetLargestObserved();
4198}
4199
QUICHE teama6ef0a62019-03-07 20:34:33 -05004200size_t QuicConnection::min_received_before_ack_decimation() const {
4201 if (received_packet_manager_.decide_when_to_send_acks()) {
QUICHE teamb23daa72019-03-21 08:37:48 -07004202 if (use_uber_received_packet_manager_) {
4203 return uber_received_packet_manager_.min_received_before_ack_decimation();
4204 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004205 return received_packet_manager_.min_received_before_ack_decimation();
4206 }
4207 return min_received_before_ack_decimation_;
4208}
4209
4210void QuicConnection::set_min_received_before_ack_decimation(size_t new_value) {
4211 if (received_packet_manager_.decide_when_to_send_acks()) {
QUICHE teamb23daa72019-03-21 08:37:48 -07004212 if (use_uber_received_packet_manager_) {
4213 uber_received_packet_manager_.set_min_received_before_ack_decimation(
4214 new_value);
4215 } else {
4216 received_packet_manager_.set_min_received_before_ack_decimation(
4217 new_value);
4218 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004219 } else {
4220 min_received_before_ack_decimation_ = new_value;
4221 }
4222}
4223
4224size_t QuicConnection::ack_frequency_before_ack_decimation() const {
4225 if (received_packet_manager_.decide_when_to_send_acks()) {
QUICHE teamb23daa72019-03-21 08:37:48 -07004226 if (use_uber_received_packet_manager_) {
4227 return uber_received_packet_manager_
4228 .ack_frequency_before_ack_decimation();
4229 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004230 return received_packet_manager_.ack_frequency_before_ack_decimation();
4231 }
4232 return ack_frequency_before_ack_decimation_;
4233}
4234
4235void QuicConnection::set_ack_frequency_before_ack_decimation(size_t new_value) {
4236 DCHECK_GT(new_value, 0u);
4237 if (received_packet_manager_.decide_when_to_send_acks()) {
QUICHE teamb23daa72019-03-21 08:37:48 -07004238 if (use_uber_received_packet_manager_) {
4239 uber_received_packet_manager_.set_ack_frequency_before_ack_decimation(
4240 new_value);
4241 } else {
4242 received_packet_manager_.set_ack_frequency_before_ack_decimation(
4243 new_value);
4244 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004245 } else {
4246 ack_frequency_before_ack_decimation_ = new_value;
4247 }
4248}
4249
fayang21ffb712019-05-16 08:39:26 -07004250const QuicAckFrame& QuicConnection::ack_frame() const {
4251 if (SupportsMultiplePacketNumberSpaces()) {
4252 return uber_received_packet_manager_.GetAckFrame(
4253 QuicUtils::GetPacketNumberSpace(last_decrypted_packet_level_));
4254 }
4255 if (use_uber_received_packet_manager_) {
4256 return uber_received_packet_manager_.ack_frame();
4257 }
4258 return received_packet_manager_.ack_frame();
4259}
4260
QUICHE teama6ef0a62019-03-07 20:34:33 -05004261#undef ENDPOINT // undef for jumbo builds
4262} // namespace quic