blob: af388a9ae34a86f490fd8e640ae034a41a684f95 [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(
222 QuicConnectionId connection_id,
223 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,
233 connection_id.length()),
234 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()),
245 connection_id_(connection_id),
246 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),
305 packet_generator_(connection_id_, &framer_, random_generator_, this),
306 idle_network_timeout_(QuicTime::Delta::Infinite()),
307 handshake_timeout_(QuicTime::Delta::Infinite()),
308 time_of_first_packet_sent_after_receiving_(
309 GetQuicReloadableFlag(
310 quic_fix_time_of_first_packet_sent_after_receiving)
311 ? QuicTime::Zero()
312 : clock_->ApproximateNow()),
313 time_of_last_received_packet_(clock_->ApproximateNow()),
314 time_of_previous_received_packet_(QuicTime::Zero()),
315 sent_packet_manager_(
316 perspective,
317 clock_,
QUICHE team73957f12019-04-18 16:21:52 -0700318 random_generator_,
QUICHE teama6ef0a62019-03-07 20:34:33 -0500319 &stats_,
320 GetQuicReloadableFlag(quic_default_to_bbr) ? kBBR : kCubicBytes,
321 kNack),
322 version_negotiation_state_(START_NEGOTIATION),
323 perspective_(perspective),
324 connected_(true),
325 can_truncate_connection_ids_(perspective == Perspective::IS_SERVER),
326 mtu_discovery_target_(0),
327 mtu_probe_count_(0),
328 packets_between_mtu_probes_(kPacketsBetweenMtuProbesBase),
329 next_mtu_probe_at_(kPacketsBetweenMtuProbesBase),
330 largest_received_packet_size_(0),
331 write_error_occurred_(false),
332 no_stop_waiting_frames_(transport_version() > QUIC_VERSION_43),
333 consecutive_num_packets_with_no_retransmittable_frames_(0),
334 max_consecutive_num_packets_with_no_retransmittable_frames_(
335 kMaxConsecutiveNonRetransmittablePackets),
336 min_received_before_ack_decimation_(kMinReceivedBeforeAckDecimation),
337 ack_frequency_before_ack_decimation_(
338 kDefaultRetransmittablePacketsBeforeAck),
339 fill_up_link_during_probing_(false),
340 probing_retransmission_pending_(false),
341 stateless_reset_token_received_(false),
342 received_stateless_reset_token_(0),
343 last_control_frame_id_(kInvalidControlFrameId),
344 is_path_degrading_(false),
345 processing_ack_frame_(false),
346 supports_release_time_(false),
347 release_time_into_future_(QuicTime::Delta::Zero()),
348 no_version_negotiation_(supported_versions.size() == 1),
QUICHE team692750b2019-03-17 17:57:46 -0700349 send_ack_when_on_can_write_(false),
dschinazi244f6dc2019-05-06 15:45:16 -0700350 retry_has_been_parsed_(false),
QUICHE team692750b2019-03-17 17:57:46 -0700351 validate_packet_number_post_decryption_(
QUICHE teamb23daa72019-03-21 08:37:48 -0700352 GetQuicReloadableFlag(quic_validate_packet_number_post_decryption)),
353 use_uber_received_packet_manager_(
354 received_packet_manager_.decide_when_to_send_acks() &&
QUICHE team1dfa46b2019-03-22 10:39:10 -0700355 validate_packet_number_post_decryption_ &&
QUICHE teamb23daa72019-03-21 08:37:48 -0700356 GetQuicReloadableFlag(quic_use_uber_received_packet_manager)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500357 if (ack_mode_ == ACK_DECIMATION) {
358 QUIC_RELOADABLE_FLAG_COUNT(quic_enable_ack_decimation);
359 }
360 if (perspective_ == Perspective::IS_SERVER &&
361 supported_versions.size() == 1) {
362 QUIC_RESTART_FLAG_COUNT(quic_no_server_conn_ver_negotiation2);
363 }
364 if (packet_generator_.deprecate_ack_bundling_mode()) {
365 QUIC_RELOADABLE_FLAG_COUNT(quic_deprecate_ack_bundling_mode);
366 }
367 if (received_packet_manager_.decide_when_to_send_acks()) {
368 QUIC_RELOADABLE_FLAG_COUNT(quic_rpm_decides_when_to_send_acks);
369 }
QUICHE team692750b2019-03-17 17:57:46 -0700370 if (validate_packet_number_post_decryption_) {
371 QUIC_RELOADABLE_FLAG_COUNT(quic_validate_packet_number_post_decryption);
372 }
QUICHE teamb23daa72019-03-21 08:37:48 -0700373 if (use_uber_received_packet_manager_) {
374 QUIC_RELOADABLE_FLAG_COUNT(quic_use_uber_received_packet_manager);
375 }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500376 QUIC_DLOG(INFO) << ENDPOINT
377 << "Created connection with connection_id: " << connection_id
zhongyi546cc452019-04-12 15:27:49 -0700378 << " and version: " << ParsedQuicVersionToString(version());
QUICHE teama6ef0a62019-03-07 20:34:33 -0500379
380 QUIC_BUG_IF(!QuicUtils::IsConnectionIdValidForVersion(connection_id,
381 transport_version()))
382 << "QuicConnection: attempted to use connection ID " << connection_id
383 << " which is invalid with version "
384 << QuicVersionToString(transport_version());
385
386 framer_.set_visitor(this);
387 stats_.connection_creation_time = clock_->ApproximateNow();
388 // TODO(ianswett): Supply the NetworkChangeVisitor as a constructor argument
389 // and make it required non-null, because it's always used.
390 sent_packet_manager_.SetNetworkChangeVisitor(this);
391 if (GetQuicRestartFlag(quic_offload_pacing_to_usps2)) {
392 sent_packet_manager_.SetPacingAlarmGranularity(QuicTime::Delta::Zero());
393 release_time_into_future_ =
394 QuicTime::Delta::FromMilliseconds(kMinReleaseTimeIntoFutureMs);
395 }
396 // Allow the packet writer to potentially reduce the packet size to a value
397 // even smaller than kDefaultMaxPacketSize.
398 SetMaxPacketLength(perspective_ == Perspective::IS_SERVER
399 ? kDefaultServerMaxPacketSize
400 : kDefaultMaxPacketSize);
QUICHE teamb23daa72019-03-21 08:37:48 -0700401 if (use_uber_received_packet_manager_) {
402 uber_received_packet_manager_.set_max_ack_ranges(255);
403 } else {
404 received_packet_manager_.set_max_ack_ranges(255);
405 }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500406 MaybeEnableSessionDecidesWhatToWrite();
QUICHE teamcd098022019-03-22 18:49:55 -0700407 MaybeEnableMultiplePacketNumberSpacesSupport();
QUICHE teama6ef0a62019-03-07 20:34:33 -0500408 DCHECK(!GetQuicRestartFlag(quic_no_server_conn_ver_negotiation2) ||
409 perspective_ == Perspective::IS_CLIENT ||
410 supported_versions.size() == 1);
411}
412
413QuicConnection::~QuicConnection() {
414 if (owns_writer_) {
415 delete writer_;
416 }
417 ClearQueuedPackets();
418}
419
420void QuicConnection::ClearQueuedPackets() {
421 for (auto it = queued_packets_.begin(); it != queued_packets_.end(); ++it) {
422 // Delete the buffer before calling ClearSerializedPacket, which sets
423 // encrypted_buffer to nullptr.
424 delete[] it->encrypted_buffer;
425 ClearSerializedPacket(&(*it));
426 }
427 queued_packets_.clear();
428}
429
430void QuicConnection::SetFromConfig(const QuicConfig& config) {
431 if (config.negotiated()) {
432 // Handshake complete, set handshake timeout to Infinite.
433 SetNetworkTimeouts(QuicTime::Delta::Infinite(),
434 config.IdleNetworkTimeout());
435 if (config.SilentClose()) {
436 idle_timeout_connection_close_behavior_ =
437 ConnectionCloseBehavior::SILENT_CLOSE;
438 }
439 } else {
440 SetNetworkTimeouts(config.max_time_before_crypto_handshake(),
441 config.max_idle_time_before_crypto_handshake());
442 }
443
444 sent_packet_manager_.SetFromConfig(config);
445 if (config.HasReceivedBytesForConnectionId() &&
446 can_truncate_connection_ids_) {
447 packet_generator_.SetConnectionIdLength(
448 config.ReceivedBytesForConnectionId());
449 }
450 max_undecryptable_packets_ = config.max_undecryptable_packets();
451
452 if (config.HasClientSentConnectionOption(kMTUH, perspective_)) {
453 SetMtuDiscoveryTarget(kMtuDiscoveryTargetPacketSizeHigh);
454 }
455 if (config.HasClientSentConnectionOption(kMTUL, perspective_)) {
456 SetMtuDiscoveryTarget(kMtuDiscoveryTargetPacketSizeLow);
457 }
458 if (debug_visitor_ != nullptr) {
459 debug_visitor_->OnSetFromConfig(config);
460 }
461 if (received_packet_manager_.decide_when_to_send_acks()) {
QUICHE teamb23daa72019-03-21 08:37:48 -0700462 if (use_uber_received_packet_manager_) {
463 uber_received_packet_manager_.SetFromConfig(config, perspective_);
464 } else {
465 received_packet_manager_.SetFromConfig(config, perspective_);
466 }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500467 } else {
468 if (GetQuicReloadableFlag(quic_enable_ack_decimation) &&
469 config.HasClientSentConnectionOption(kACD0, perspective_)) {
470 ack_mode_ = TCP_ACKING;
471 }
472 if (config.HasClientSentConnectionOption(kACKD, perspective_)) {
473 ack_mode_ = ACK_DECIMATION;
474 }
475 if (config.HasClientSentConnectionOption(kAKD2, perspective_)) {
476 ack_mode_ = ACK_DECIMATION_WITH_REORDERING;
477 }
478 if (config.HasClientSentConnectionOption(kAKD3, perspective_)) {
479 ack_mode_ = ACK_DECIMATION;
480 ack_decimation_delay_ = kShortAckDecimationDelay;
481 }
482 if (config.HasClientSentConnectionOption(kAKD4, perspective_)) {
483 ack_mode_ = ACK_DECIMATION_WITH_REORDERING;
484 ack_decimation_delay_ = kShortAckDecimationDelay;
485 }
486 if (config.HasClientSentConnectionOption(kAKDU, perspective_)) {
487 unlimited_ack_decimation_ = true;
488 }
489 if (config.HasClientSentConnectionOption(kACKQ, perspective_)) {
490 fast_ack_after_quiescence_ = true;
491 }
492 }
493 if (config.HasClientSentConnectionOption(k5RTO, perspective_)) {
494 close_connection_after_five_rtos_ = true;
495 }
496 if (config.HasClientSentConnectionOption(kNSTP, perspective_)) {
497 no_stop_waiting_frames_ = true;
498 }
499 if (config.HasReceivedStatelessResetToken()) {
500 stateless_reset_token_received_ = true;
501 received_stateless_reset_token_ = config.ReceivedStatelessResetToken();
502 }
503 if (GetQuicReloadableFlag(quic_send_timestamps) &&
504 config.HasClientSentConnectionOption(kSTMP, perspective_)) {
505 QUIC_RELOADABLE_FLAG_COUNT(quic_send_timestamps);
506 framer_.set_process_timestamps(true);
QUICHE teamb23daa72019-03-21 08:37:48 -0700507 if (use_uber_received_packet_manager_) {
508 uber_received_packet_manager_.set_save_timestamps(true);
509 } else {
510 received_packet_manager_.set_save_timestamps(true);
511 }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500512 }
513
514 supports_release_time_ =
515 writer_ != nullptr && writer_->SupportsReleaseTime() &&
516 !config.HasClientSentConnectionOption(kNPCO, perspective_);
517
518 if (supports_release_time_) {
519 UpdateReleaseTimeIntoFuture();
520 }
521}
522
523void QuicConnection::OnSendConnectionState(
524 const CachedNetworkParameters& cached_network_params) {
525 if (debug_visitor_ != nullptr) {
526 debug_visitor_->OnSendConnectionState(cached_network_params);
527 }
528}
529
530void QuicConnection::OnReceiveConnectionState(
531 const CachedNetworkParameters& cached_network_params) {
532 if (debug_visitor_ != nullptr) {
533 debug_visitor_->OnReceiveConnectionState(cached_network_params);
534 }
535}
536
537void QuicConnection::ResumeConnectionState(
538 const CachedNetworkParameters& cached_network_params,
539 bool max_bandwidth_resumption) {
540 sent_packet_manager_.ResumeConnectionState(cached_network_params,
541 max_bandwidth_resumption);
542}
543
544void QuicConnection::SetMaxPacingRate(QuicBandwidth max_pacing_rate) {
545 sent_packet_manager_.SetMaxPacingRate(max_pacing_rate);
546}
547
548void QuicConnection::AdjustNetworkParameters(QuicBandwidth bandwidth,
fayangf1b99dc2019-05-14 06:29:18 -0700549 QuicTime::Delta rtt,
550 bool allow_cwnd_to_decrease) {
551 sent_packet_manager_.AdjustNetworkParameters(bandwidth, rtt,
552 allow_cwnd_to_decrease);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500553}
554
555QuicBandwidth QuicConnection::MaxPacingRate() const {
556 return sent_packet_manager_.MaxPacingRate();
557}
558
559bool QuicConnection::SelectMutualVersion(
560 const ParsedQuicVersionVector& available_versions) {
561 // Try to find the highest mutual version by iterating over supported
562 // versions, starting with the highest, and breaking out of the loop once we
563 // find a matching version in the provided available_versions vector.
564 const ParsedQuicVersionVector& supported_versions =
565 framer_.supported_versions();
566 for (size_t i = 0; i < supported_versions.size(); ++i) {
567 const ParsedQuicVersion& version = supported_versions[i];
568 if (QuicContainsValue(available_versions, version)) {
569 framer_.set_version(version);
570 return true;
571 }
572 }
573
574 return false;
575}
576
577void QuicConnection::OnError(QuicFramer* framer) {
578 // Packets that we can not or have not decrypted are dropped.
579 // TODO(rch): add stats to measure this.
580 if (!connected_ || last_packet_decrypted_ == false) {
581 return;
582 }
583 CloseConnection(framer->error(), framer->detailed_error(),
584 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
585}
586
587void QuicConnection::OnPacket() {
588 last_packet_decrypted_ = false;
589}
590
591void QuicConnection::OnPublicResetPacket(const QuicPublicResetPacket& packet) {
592 // Check that any public reset packet with a different connection ID that was
593 // routed to this QuicConnection has been redirected before control reaches
594 // here. (Check for a bug regression.)
595 DCHECK_EQ(connection_id_, packet.connection_id);
596 DCHECK_EQ(perspective_, Perspective::IS_CLIENT);
597 if (debug_visitor_ != nullptr) {
598 debug_visitor_->OnPublicResetPacket(packet);
599 }
vasilvvc48c8712019-03-11 13:38:16 -0700600 std::string error_details = "Received public reset.";
QUICHE teama6ef0a62019-03-07 20:34:33 -0500601 if (perspective_ == Perspective::IS_CLIENT && !packet.endpoint_id.empty()) {
602 QuicStrAppend(&error_details, " From ", packet.endpoint_id, ".");
603 }
604 QUIC_DLOG(INFO) << ENDPOINT << error_details;
605 QUIC_CODE_COUNT(quic_tear_down_local_connection_on_public_reset);
606 TearDownLocalConnectionState(QUIC_PUBLIC_RESET, error_details,
607 ConnectionCloseSource::FROM_PEER);
608}
609
610bool QuicConnection::OnProtocolVersionMismatch(
611 ParsedQuicVersion received_version,
612 PacketHeaderFormat form) {
613 QUIC_DLOG(INFO) << ENDPOINT << "Received packet with mismatched version "
614 << ParsedQuicVersionToString(received_version);
615 if (perspective_ == Perspective::IS_CLIENT) {
vasilvvc48c8712019-03-11 13:38:16 -0700616 const std::string error_details = "Protocol version mismatch.";
QUICHE teama6ef0a62019-03-07 20:34:33 -0500617 QUIC_BUG << ENDPOINT << error_details;
618 TearDownLocalConnectionState(QUIC_INTERNAL_ERROR, error_details,
619 ConnectionCloseSource::FROM_SELF);
620 return false;
621 }
622 if (no_version_negotiation_) {
623 // Drop old packets that were sent by the client before the version was
624 // negotiated.
625 return false;
626 }
627 DCHECK_NE(version(), received_version);
628
629 if (debug_visitor_ != nullptr) {
630 debug_visitor_->OnProtocolVersionMismatch(received_version);
631 }
632
633 switch (version_negotiation_state_) {
634 case START_NEGOTIATION:
635 if (!framer_.IsSupportedVersion(received_version)) {
636 SendVersionNegotiationPacket(form != GOOGLE_QUIC_PACKET);
637 version_negotiation_state_ = NEGOTIATION_IN_PROGRESS;
638 return false;
639 }
640 break;
641
642 case NEGOTIATION_IN_PROGRESS:
643 if (!framer_.IsSupportedVersion(received_version)) {
644 SendVersionNegotiationPacket(form != GOOGLE_QUIC_PACKET);
645 return false;
646 }
647 break;
648
649 case NEGOTIATED_VERSION:
650 // Might be old packets that were sent by the client before the version
651 // was negotiated. Drop these.
652 return false;
653
654 default:
655 DCHECK(false);
656 }
657
658 // Store the new version.
659 framer_.set_version(received_version);
660 framer_.InferPacketHeaderTypeFromVersion();
661
662 version_negotiation_state_ = NEGOTIATED_VERSION;
663 visitor_->OnSuccessfulVersionNegotiation(received_version);
664 if (debug_visitor_ != nullptr) {
665 debug_visitor_->OnSuccessfulVersionNegotiation(received_version);
666 }
667 QUIC_DLOG(INFO) << ENDPOINT << "version negotiated "
668 << ParsedQuicVersionToString(received_version);
669
670 MaybeEnableSessionDecidesWhatToWrite();
671 no_stop_waiting_frames_ =
672 received_version.transport_version > QUIC_VERSION_43;
673
674 // TODO(satyamshekhar): Store the packet number of this packet and close the
675 // connection if we ever received a packet with incorrect version and whose
676 // packet number is greater.
677 return true;
678}
679
680// Handles version negotiation for client connection.
681void QuicConnection::OnVersionNegotiationPacket(
682 const QuicVersionNegotiationPacket& packet) {
683 // Check that any public reset packet with a different connection ID that was
684 // routed to this QuicConnection has been redirected before control reaches
685 // here. (Check for a bug regression.)
686 DCHECK_EQ(connection_id_, packet.connection_id);
687 if (perspective_ == Perspective::IS_SERVER) {
vasilvvc48c8712019-03-11 13:38:16 -0700688 const std::string error_details =
dschinazi5a354c92019-05-09 12:18:53 -0700689 "Server received version negotiation packet.";
QUICHE teama6ef0a62019-03-07 20:34:33 -0500690 QUIC_BUG << error_details;
691 QUIC_CODE_COUNT(quic_tear_down_local_connection_on_version_negotiation);
692 TearDownLocalConnectionState(QUIC_INTERNAL_ERROR, error_details,
693 ConnectionCloseSource::FROM_SELF);
694 return;
695 }
696 if (debug_visitor_ != nullptr) {
697 debug_visitor_->OnVersionNegotiationPacket(packet);
698 }
699
700 if (version_negotiation_state_ != START_NEGOTIATION) {
701 // Possibly a duplicate version negotiation packet.
702 return;
703 }
704
705 if (QuicContainsValue(packet.versions, version())) {
vasilvvc48c8712019-03-11 13:38:16 -0700706 const std::string error_details =
QUICHE teama6ef0a62019-03-07 20:34:33 -0500707 "Server already supports client's version and should have accepted the "
708 "connection.";
709 QUIC_DLOG(WARNING) << error_details;
710 TearDownLocalConnectionState(QUIC_INVALID_VERSION_NEGOTIATION_PACKET,
711 error_details,
712 ConnectionCloseSource::FROM_SELF);
713 return;
714 }
715
716 server_supported_versions_ = packet.versions;
717
718 if (GetQuicReloadableFlag(quic_no_client_conn_ver_negotiation)) {
719 QUIC_RELOADABLE_FLAG_COUNT(quic_no_client_conn_ver_negotiation);
720 CloseConnection(
721 QUIC_INVALID_VERSION,
722 QuicStrCat(
723 "Client may support one of the versions in the server's list, but "
724 "it's going to close the connection anyway. Supported versions: {",
725 ParsedQuicVersionVectorToString(framer_.supported_versions()),
726 "}, peer supported versions: {",
727 ParsedQuicVersionVectorToString(packet.versions), "}"),
728 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
729 return;
730 }
731
dschinazi5a354c92019-05-09 12:18:53 -0700732 ParsedQuicVersion original_version = version();
QUICHE teama6ef0a62019-03-07 20:34:33 -0500733 if (!SelectMutualVersion(packet.versions)) {
734 CloseConnection(
735 QUIC_INVALID_VERSION,
736 QuicStrCat(
737 "No common version found. Supported versions: {",
738 ParsedQuicVersionVectorToString(framer_.supported_versions()),
739 "}, peer supported versions: {",
740 ParsedQuicVersionVectorToString(packet.versions), "}"),
741 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
742 return;
743 }
744
dschinazi5a354c92019-05-09 12:18:53 -0700745 if (original_version.handshake_protocol != version().handshake_protocol) {
746 const std::string error_details =
747 "In-connection version negotiation between mismatched handshake "
748 " protocols " +
749 ParsedQuicVersionToString(original_version) + " and " +
750 ParsedQuicVersionToString(version()) + " is currently unsupported.";
751 QUIC_DLOG(WARNING) << error_details;
752 TearDownLocalConnectionState(QUIC_INVALID_VERSION, error_details,
753 ConnectionCloseSource::FROM_SELF);
754 return;
755 }
756
QUICHE teama6ef0a62019-03-07 20:34:33 -0500757 QUIC_DLOG(INFO) << ENDPOINT << "Negotiated version: "
dschinazi5a354c92019-05-09 12:18:53 -0700758 << ParsedQuicVersionToString(version());
QUICHE teama6ef0a62019-03-07 20:34:33 -0500759 no_stop_waiting_frames_ = transport_version() > QUIC_VERSION_43;
760 version_negotiation_state_ = NEGOTIATION_IN_PROGRESS;
dschinazi5a354c92019-05-09 12:18:53 -0700761
QUICHE teama6ef0a62019-03-07 20:34:33 -0500762 RetransmitUnackedPackets(ALL_UNACKED_RETRANSMISSION);
763}
764
dschinazi244f6dc2019-05-06 15:45:16 -0700765// Handles retry for client connection.
766void QuicConnection::OnRetryPacket(QuicConnectionId original_connection_id,
767 QuicConnectionId new_connection_id,
768 QuicStringPiece retry_token) {
769 if (original_connection_id != connection_id_) {
770 QUIC_DLOG(ERROR) << "Ignoring RETRY with original connection ID "
771 << original_connection_id << " not matching expected "
772 << connection_id_ << " token "
773 << QuicTextUtils::HexEncode(retry_token);
774 return;
775 }
776 if (retry_has_been_parsed_) {
777 QUIC_DLOG(ERROR) << "Ignoring non-first RETRY with token "
778 << QuicTextUtils::HexEncode(retry_token);
779 return;
780 }
781 retry_has_been_parsed_ = true;
782 QUIC_DLOG(INFO) << "Received RETRY, replacing connection ID "
783 << connection_id_ << " with " << new_connection_id
784 << ", received token "
785 << QuicTextUtils::HexEncode(retry_token);
786 connection_id_ = new_connection_id;
787 packet_generator_.SetConnectionId(connection_id_);
788 packet_generator_.SetRetryToken(retry_token);
789
790 // Reinstall initial crypters because the connection ID changed.
791 CrypterPair crypters;
792 CryptoUtils::CreateTlsInitialCrypters(
793 Perspective::IS_CLIENT, transport_version(), connection_id_, &crypters);
794 SetEncrypter(ENCRYPTION_INITIAL, std::move(crypters.encrypter));
795 InstallDecrypter(ENCRYPTION_INITIAL, std::move(crypters.decrypter));
796}
797
QUICHE teamc65d1d12019-03-19 20:58:04 -0700798bool QuicConnection::HasIncomingConnectionId(QuicConnectionId connection_id) {
799 for (QuicConnectionId const& incoming_connection_id :
800 incoming_connection_ids_) {
801 if (incoming_connection_id == connection_id) {
802 return true;
803 }
804 }
805 return false;
806}
807
808void QuicConnection::AddIncomingConnectionId(QuicConnectionId connection_id) {
809 if (HasIncomingConnectionId(connection_id)) {
810 return;
811 }
812 incoming_connection_ids_.push_back(connection_id);
813}
814
QUICHE teama6ef0a62019-03-07 20:34:33 -0500815bool QuicConnection::OnUnauthenticatedPublicHeader(
816 const QuicPacketHeader& header) {
QUICHE team2252b702019-05-14 23:55:14 -0400817 QuicConnectionId server_connection_id =
818 GetServerConnectionIdAsRecipient(header, perspective_);
819
820 if (server_connection_id == connection_id_ ||
821 HasIncomingConnectionId(server_connection_id)) {
QUICHE teamc65d1d12019-03-19 20:58:04 -0700822 return true;
823 }
824
825 if (PacketCanReplaceConnectionId(header, perspective_)) {
826 QUIC_DLOG(INFO) << ENDPOINT << "Accepting packet with new connection ID "
QUICHE team2252b702019-05-14 23:55:14 -0400827 << server_connection_id << " instead of " << connection_id_;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500828 return true;
829 }
830
831 ++stats_.packets_dropped;
832 QUIC_DLOG(INFO) << ENDPOINT
833 << "Ignoring packet from unexpected ConnectionId: "
QUICHE team2252b702019-05-14 23:55:14 -0400834 << server_connection_id << " instead of " << connection_id_;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500835 if (debug_visitor_ != nullptr) {
QUICHE team2252b702019-05-14 23:55:14 -0400836 debug_visitor_->OnIncorrectConnectionId(server_connection_id);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500837 }
838 // If this is a server, the dispatcher routes each packet to the
839 // QuicConnection responsible for the packet's connection ID. So if control
840 // arrives here and this is a server, the dispatcher must be malfunctioning.
841 DCHECK_NE(Perspective::IS_SERVER, perspective_);
842 return false;
843}
844
845bool QuicConnection::OnUnauthenticatedHeader(const QuicPacketHeader& header) {
846 if (debug_visitor_ != nullptr) {
847 debug_visitor_->OnUnauthenticatedHeader(header);
848 }
849
850 // Check that any public reset packet with a different connection ID that was
851 // routed to this QuicConnection has been redirected before control reaches
852 // here.
QUICHE team2252b702019-05-14 23:55:14 -0400853 DCHECK(GetServerConnectionIdAsRecipient(header, perspective_) ==
854 connection_id_ ||
855 HasIncomingConnectionId(
856 GetServerConnectionIdAsRecipient(header, perspective_)) ||
QUICHE teamc65d1d12019-03-19 20:58:04 -0700857 PacketCanReplaceConnectionId(header, perspective_));
QUICHE teama6ef0a62019-03-07 20:34:33 -0500858
859 if (!packet_generator_.IsPendingPacketEmpty()) {
860 // Incoming packets may change a queued ACK frame.
vasilvvc48c8712019-03-11 13:38:16 -0700861 const std::string error_details =
QUICHE teama6ef0a62019-03-07 20:34:33 -0500862 "Pending frames must be serialized before incoming packets are "
863 "processed.";
864 QUIC_BUG << error_details << ", received header: " << header;
865 CloseConnection(QUIC_INTERNAL_ERROR, error_details,
866 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
867 return false;
868 }
869
870 // If this packet has already been seen, or the sender has told us that it
871 // will not be retransmitted, then stop processing the packet.
QUICHE teamb23daa72019-03-21 08:37:48 -0700872 if (!validate_packet_number_post_decryption_) {
873 const bool is_awaiting =
874 use_uber_received_packet_manager_
875 ? uber_received_packet_manager_.IsAwaitingPacket(
QUICHE team1dfa46b2019-03-22 10:39:10 -0700876 last_decrypted_packet_level_, header.packet_number)
QUICHE teamb23daa72019-03-21 08:37:48 -0700877 : received_packet_manager_.IsAwaitingPacket(header.packet_number);
878 if (!is_awaiting) {
879 if (framer_.IsIetfStatelessResetPacket(header)) {
880 QuicIetfStatelessResetPacket packet(
881 header, header.possible_stateless_reset_token);
882 OnAuthenticatedIetfStatelessResetPacket(packet);
883 return false;
884 }
885 QUIC_DLOG(INFO) << ENDPOINT << "Packet " << header.packet_number
886 << " no longer being waited for. Discarding.";
887 if (debug_visitor_ != nullptr) {
888 debug_visitor_->OnDuplicatePacket(header.packet_number);
889 }
890 ++stats_.packets_dropped;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500891 return false;
892 }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500893 }
894
895 if (version_negotiation_state_ != NEGOTIATED_VERSION &&
896 perspective_ == Perspective::IS_SERVER) {
897 if (!header.version_flag) {
898 // Packets should have the version flag till version negotiation is
899 // done.
vasilvvc48c8712019-03-11 13:38:16 -0700900 std::string error_details =
QUICHE teama6ef0a62019-03-07 20:34:33 -0500901 QuicStrCat(ENDPOINT, "Packet ", header.packet_number.ToUint64(),
902 " without version flag before version negotiated.");
903 QUIC_DLOG(WARNING) << error_details;
904 CloseConnection(QUIC_INVALID_VERSION, error_details,
905 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
906 return false;
907 } else {
908 DCHECK_EQ(header.version, version());
909 version_negotiation_state_ = NEGOTIATED_VERSION;
910 framer_.InferPacketHeaderTypeFromVersion();
911 visitor_->OnSuccessfulVersionNegotiation(version());
912 if (debug_visitor_ != nullptr) {
913 debug_visitor_->OnSuccessfulVersionNegotiation(version());
914 }
915 }
916 DCHECK_EQ(NEGOTIATED_VERSION, version_negotiation_state_);
917 }
918
919 return true;
920}
921
922void QuicConnection::OnDecryptedPacket(EncryptionLevel level) {
923 last_decrypted_packet_level_ = level;
924 last_packet_decrypted_ = true;
925
926 // Once the server receives a forward secure packet, the handshake is
927 // confirmed.
928 if (level == ENCRYPTION_FORWARD_SECURE &&
929 perspective_ == Perspective::IS_SERVER) {
930 sent_packet_manager_.SetHandshakeConfirmed();
931 if (sent_packet_manager_.unacked_packets().use_uber_loss_algorithm()) {
932 // This may have changed the retransmission timer, so re-arm it.
933 SetRetransmissionAlarm();
934 }
935 }
936}
937
938QuicSocketAddress QuicConnection::GetEffectivePeerAddressFromCurrentPacket()
939 const {
940 // By default, the connection is not proxied, and the effective peer address
941 // is the packet's source address, i.e. the direct peer address.
942 return last_packet_source_address_;
943}
944
945bool QuicConnection::OnPacketHeader(const QuicPacketHeader& header) {
946 if (debug_visitor_ != nullptr) {
947 debug_visitor_->OnPacketHeader(header);
948 }
949
950 // Will be decremented below if we fall through to return true.
951 ++stats_.packets_dropped;
952
953 if (!ProcessValidatedPacket(header)) {
954 return false;
955 }
956
957 // Initialize the current packet content state.
958 current_packet_content_ = NO_FRAMES_RECEIVED;
959 is_current_packet_connectivity_probing_ = false;
960 current_effective_peer_migration_type_ = NO_CHANGE;
961
962 if (perspective_ == Perspective::IS_CLIENT) {
QUICHE team1f3de242019-03-20 07:24:48 -0700963 if (!GetLargestReceivedPacket().IsInitialized() ||
964 header.packet_number > GetLargestReceivedPacket()) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500965 // Update peer_address_ and effective_peer_address_ immediately for
966 // client connections.
QUICHE team1f3de242019-03-20 07:24:48 -0700967 // TODO(fayang): only change peer addresses in application data packet
968 // number space.
QUICHE teama6ef0a62019-03-07 20:34:33 -0500969 direct_peer_address_ = last_packet_source_address_;
970 effective_peer_address_ = GetEffectivePeerAddressFromCurrentPacket();
971 }
972 } else {
973 // At server, remember the address change type of effective_peer_address
974 // in current_effective_peer_migration_type_. But this variable alone
975 // doesn't necessarily starts a migration. A migration will be started
976 // later, once the current packet is confirmed to meet the following
977 // conditions:
978 // 1) current_effective_peer_migration_type_ is not NO_CHANGE.
979 // 2) The current packet is not a connectivity probing.
980 // 3) The current packet is not reordered, i.e. its packet number is the
981 // largest of this connection so far.
982 // Once the above conditions are confirmed, a new migration will start
983 // even if there is an active migration underway.
984 current_effective_peer_migration_type_ =
985 QuicUtils::DetermineAddressChangeType(
986 effective_peer_address_,
987 GetEffectivePeerAddressFromCurrentPacket());
988
989 QUIC_DLOG_IF(INFO, current_effective_peer_migration_type_ != NO_CHANGE)
990 << ENDPOINT << "Effective peer's ip:port changed from "
991 << effective_peer_address_.ToString() << " to "
992 << GetEffectivePeerAddressFromCurrentPacket().ToString()
993 << ", active_effective_peer_migration_type is "
994 << active_effective_peer_migration_type_;
995 }
996
997 --stats_.packets_dropped;
998 QUIC_DVLOG(1) << ENDPOINT << "Received packet header: " << header;
999 last_header_ = header;
1000 // An ack will be sent if a missing retransmittable packet was received;
QUICHE teamb23daa72019-03-21 08:37:48 -07001001 if (!use_uber_received_packet_manager_) {
1002 was_last_packet_missing_ =
1003 received_packet_manager_.IsMissing(last_header_.packet_number);
1004 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001005
1006 // Record packet receipt to populate ack info before processing stream
1007 // frames, since the processing may result in sending a bundled ack.
QUICHE teamb23daa72019-03-21 08:37:48 -07001008 if (use_uber_received_packet_manager_) {
1009 uber_received_packet_manager_.RecordPacketReceived(
QUICHE team1dfa46b2019-03-22 10:39:10 -07001010 last_decrypted_packet_level_, last_header_,
1011 time_of_last_received_packet_);
QUICHE teamb23daa72019-03-21 08:37:48 -07001012 } else {
1013 received_packet_manager_.RecordPacketReceived(
1014 last_header_, time_of_last_received_packet_);
1015 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001016 DCHECK(connected_);
1017 return true;
1018}
1019
1020bool QuicConnection::OnStreamFrame(const QuicStreamFrame& frame) {
1021 DCHECK(connected_);
1022
1023 // Since a stream frame was received, this is not a connectivity probe.
1024 // A probe only contains a PING and full padding.
1025 UpdatePacketContent(NOT_PADDED_PING);
1026
1027 if (debug_visitor_ != nullptr) {
1028 debug_visitor_->OnStreamFrame(frame);
1029 }
1030 if (frame.stream_id != QuicUtils::GetCryptoStreamId(transport_version()) &&
QUICHE team6987b4a2019-03-15 16:23:04 -07001031 last_decrypted_packet_level_ == ENCRYPTION_INITIAL) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001032 if (MaybeConsiderAsMemoryCorruption(frame)) {
1033 CloseConnection(QUIC_MAYBE_CORRUPTED_MEMORY,
1034 "Received crypto frame on non crypto stream.",
1035 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
1036 return false;
1037 }
1038
1039 QUIC_PEER_BUG << ENDPOINT
1040 << "Received an unencrypted data frame: closing connection"
1041 << " packet_number:" << last_header_.packet_number
QUICHE teamb23daa72019-03-21 08:37:48 -07001042 << " stream_id:" << frame.stream_id
1043 << " received_packets:" << GetUpdatedAckFrame();
QUICHE teama6ef0a62019-03-07 20:34:33 -05001044 CloseConnection(QUIC_UNENCRYPTED_STREAM_DATA,
1045 "Unencrypted stream data seen.",
1046 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
1047 return false;
1048 }
1049 visitor_->OnStreamFrame(frame);
1050 stats_.stream_bytes_received += frame.data_length;
1051 should_last_packet_instigate_acks_ = true;
1052 return connected_;
1053}
1054
1055bool QuicConnection::OnCryptoFrame(const QuicCryptoFrame& frame) {
1056 DCHECK(connected_);
1057
1058 // Since a CRYPTO frame was received, this is not a connectivity probe.
1059 // A probe only contains a PING and full padding.
1060 UpdatePacketContent(NOT_PADDED_PING);
1061
1062 visitor_->OnCryptoFrame(frame);
1063 should_last_packet_instigate_acks_ = true;
1064 return connected_;
1065}
1066
1067bool QuicConnection::OnAckFrameStart(QuicPacketNumber largest_acked,
1068 QuicTime::Delta ack_delay_time) {
1069 DCHECK(connected_);
1070
1071 if (processing_ack_frame_) {
1072 CloseConnection(QUIC_INVALID_ACK_DATA,
1073 "Received a new ack while processing an ack frame.",
1074 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
1075 return false;
1076 }
1077
1078 // Since an ack frame was received, this is not a connectivity probe.
1079 // A probe only contains a PING and full padding.
1080 UpdatePacketContent(NOT_PADDED_PING);
1081
1082 QUIC_DVLOG(1) << ENDPOINT
1083 << "OnAckFrameStart, largest_acked: " << largest_acked;
1084
QUICHE team76e1c622019-03-19 14:36:39 -07001085 if (GetLargestReceivedPacketWithAck().IsInitialized() &&
1086 last_header_.packet_number <= GetLargestReceivedPacketWithAck()) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001087 QUIC_DLOG(INFO) << ENDPOINT << "Received an old ack frame: ignoring";
1088 return true;
1089 }
1090
QUICHE team76e1c622019-03-19 14:36:39 -07001091 if (!GetLargestSentPacket().IsInitialized() ||
1092 largest_acked > GetLargestSentPacket()) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001093 QUIC_DLOG(WARNING) << ENDPOINT
1094 << "Peer's observed unsent packet:" << largest_acked
QUICHE team76e1c622019-03-19 14:36:39 -07001095 << " vs " << GetLargestSentPacket();
QUICHE teama6ef0a62019-03-07 20:34:33 -05001096 // We got an ack for data we have not sent.
1097 CloseConnection(QUIC_INVALID_ACK_DATA, "Largest observed too high.",
1098 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
1099 return false;
1100 }
1101
QUICHE team76e1c622019-03-19 14:36:39 -07001102 if (!GetLargestAckedPacket().IsInitialized() ||
1103 largest_acked > GetLargestAckedPacket()) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001104 visitor_->OnForwardProgressConfirmed();
QUICHE team9929cc42019-03-13 08:17:43 -07001105 } else if (!sent_packet_manager_.tolerate_reneging() &&
QUICHE team76e1c622019-03-19 14:36:39 -07001106 largest_acked < GetLargestAckedPacket()) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001107 QUIC_LOG(INFO) << ENDPOINT << "Peer's largest_observed packet decreased:"
QUICHE team76e1c622019-03-19 14:36:39 -07001108 << largest_acked << " vs " << GetLargestAckedPacket()
QUICHE teama6ef0a62019-03-07 20:34:33 -05001109 << " packet_number:" << last_header_.packet_number
QUICHE team76e1c622019-03-19 14:36:39 -07001110 << " largest seen with ack:"
1111 << GetLargestReceivedPacketWithAck()
QUICHE teama6ef0a62019-03-07 20:34:33 -05001112 << " connection_id: " << connection_id_;
1113 // A new ack has a diminished largest_observed value.
1114 // If this was an old packet, we wouldn't even have checked.
1115 CloseConnection(QUIC_INVALID_ACK_DATA, "Largest observed too low.",
1116 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
1117 return false;
1118 }
1119 processing_ack_frame_ = true;
1120 sent_packet_manager_.OnAckFrameStart(largest_acked, ack_delay_time,
1121 time_of_last_received_packet_);
1122 return true;
1123}
1124
1125bool QuicConnection::OnAckRange(QuicPacketNumber start, QuicPacketNumber end) {
1126 DCHECK(connected_);
1127 QUIC_DVLOG(1) << ENDPOINT << "OnAckRange: [" << start << ", " << end << ")";
1128
QUICHE team76e1c622019-03-19 14:36:39 -07001129 if (GetLargestReceivedPacketWithAck().IsInitialized() &&
1130 last_header_.packet_number <= GetLargestReceivedPacketWithAck()) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001131 QUIC_DLOG(INFO) << ENDPOINT << "Received an old ack frame: ignoring";
1132 return true;
1133 }
1134
1135 sent_packet_manager_.OnAckRange(start, end);
1136 return true;
1137}
1138
1139bool QuicConnection::OnAckTimestamp(QuicPacketNumber packet_number,
1140 QuicTime timestamp) {
1141 DCHECK(connected_);
1142 QUIC_DVLOG(1) << ENDPOINT << "OnAckTimestamp: [" << packet_number << ", "
1143 << timestamp.ToDebuggingValue() << ")";
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_.OnAckTimestamp(packet_number, timestamp);
1152 return true;
1153}
1154
1155bool QuicConnection::OnAckFrameEnd(QuicPacketNumber start) {
1156 DCHECK(connected_);
1157 QUIC_DVLOG(1) << ENDPOINT << "OnAckFrameEnd, start: " << start;
1158
QUICHE team76e1c622019-03-19 14:36:39 -07001159 if (GetLargestReceivedPacketWithAck().IsInitialized() &&
1160 last_header_.packet_number <= GetLargestReceivedPacketWithAck()) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001161 QUIC_DLOG(INFO) << ENDPOINT << "Received an old ack frame: ignoring";
1162 return true;
1163 }
fayang3eb82212019-04-16 12:05:46 -07001164 const AckResult ack_result = sent_packet_manager_.OnAckFrameEnd(
1165 time_of_last_received_packet_, last_decrypted_packet_level_);
1166 if (ack_result != PACKETS_NEWLY_ACKED &&
1167 ack_result != NO_PACKETS_NEWLY_ACKED) {
1168 // Error occurred (e.g., this ACK tries to ack packets in wrong packet
1169 // number space), and this would cause the connection to be closed.
1170 QUIC_DLOG(ERROR) << ENDPOINT
1171 << "Error occurred when processing an ACK frame: "
1172 << QuicUtils::AckResultToString(ack_result);
1173 return false;
1174 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001175 // Cancel the send alarm because new packets likely have been acked, which
1176 // may change the congestion window and/or pacing rate. Canceling the alarm
1177 // causes CanWrite to recalculate the next send time.
1178 if (send_alarm_->IsSet()) {
1179 send_alarm_->Cancel();
1180 }
1181 if (supports_release_time_) {
1182 // Update pace time into future because smoothed RTT is likely updated.
1183 UpdateReleaseTimeIntoFuture();
1184 }
QUICHE team76e1c622019-03-19 14:36:39 -07001185 SetLargestReceivedPacketWithAck(last_header_.packet_number);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001186 // If the incoming ack's packets set expresses missing packets: peer is still
1187 // waiting for a packet lower than a packet that we are no longer planning to
1188 // send.
1189 // If the incoming ack's packets set expresses received packets: peer is still
1190 // acking packets which we never care about.
1191 // Send an ack to raise the high water mark.
fayang3eb82212019-04-16 12:05:46 -07001192 PostProcessAfterAckFrame(GetLeastUnacked() > start,
1193 ack_result == PACKETS_NEWLY_ACKED);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001194 processing_ack_frame_ = false;
1195
1196 return connected_;
1197}
1198
1199bool QuicConnection::OnStopWaitingFrame(const QuicStopWaitingFrame& frame) {
1200 DCHECK(connected_);
1201
1202 // Since a stop waiting frame was received, this is not a connectivity probe.
1203 // A probe only contains a PING and full padding.
1204 UpdatePacketContent(NOT_PADDED_PING);
1205
1206 if (no_stop_waiting_frames_) {
1207 return true;
1208 }
1209 if (largest_seen_packet_with_stop_waiting_.IsInitialized() &&
1210 last_header_.packet_number <= largest_seen_packet_with_stop_waiting_) {
1211 QUIC_DLOG(INFO) << ENDPOINT
1212 << "Received an old stop waiting frame: ignoring";
1213 return true;
1214 }
1215
1216 const char* error = ValidateStopWaitingFrame(frame);
1217 if (error != nullptr) {
1218 CloseConnection(QUIC_INVALID_STOP_WAITING_DATA, error,
1219 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
1220 return false;
1221 }
1222
1223 if (debug_visitor_ != nullptr) {
1224 debug_visitor_->OnStopWaitingFrame(frame);
1225 }
1226
1227 largest_seen_packet_with_stop_waiting_ = last_header_.packet_number;
QUICHE teamb23daa72019-03-21 08:37:48 -07001228 if (use_uber_received_packet_manager_) {
QUICHE team1dfa46b2019-03-22 10:39:10 -07001229 uber_received_packet_manager_.DontWaitForPacketsBefore(
1230 last_decrypted_packet_level_, frame.least_unacked);
QUICHE teamb23daa72019-03-21 08:37:48 -07001231 } else {
1232 received_packet_manager_.DontWaitForPacketsBefore(frame.least_unacked);
1233 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001234 return connected_;
1235}
1236
1237bool QuicConnection::OnPaddingFrame(const QuicPaddingFrame& frame) {
1238 DCHECK(connected_);
1239 UpdatePacketContent(SECOND_FRAME_IS_PADDING);
1240
1241 if (debug_visitor_ != nullptr) {
1242 debug_visitor_->OnPaddingFrame(frame);
1243 }
1244 return true;
1245}
1246
1247bool QuicConnection::OnPingFrame(const QuicPingFrame& frame) {
1248 DCHECK(connected_);
1249 UpdatePacketContent(FIRST_FRAME_IS_PING);
1250
1251 if (debug_visitor_ != nullptr) {
1252 debug_visitor_->OnPingFrame(frame);
1253 }
1254 should_last_packet_instigate_acks_ = true;
1255 return true;
1256}
1257
QUICHE teama6ef0a62019-03-07 20:34:33 -05001258const char* QuicConnection::ValidateStopWaitingFrame(
1259 const QuicStopWaitingFrame& stop_waiting) {
QUICHE teamb23daa72019-03-21 08:37:48 -07001260 const QuicPacketNumber peer_least_packet_awaiting_ack =
1261 use_uber_received_packet_manager_
1262 ? uber_received_packet_manager_.peer_least_packet_awaiting_ack()
1263 : received_packet_manager_.peer_least_packet_awaiting_ack();
1264 if (peer_least_packet_awaiting_ack.IsInitialized() &&
1265 stop_waiting.least_unacked < peer_least_packet_awaiting_ack) {
1266 QUIC_DLOG(ERROR) << ENDPOINT << "Peer's sent low least_unacked: "
1267 << stop_waiting.least_unacked << " vs "
1268 << peer_least_packet_awaiting_ack;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001269 // We never process old ack frames, so this number should only increase.
1270 return "Least unacked too small.";
1271 }
1272
1273 if (stop_waiting.least_unacked > last_header_.packet_number) {
1274 QUIC_DLOG(ERROR) << ENDPOINT
1275 << "Peer sent least_unacked:" << stop_waiting.least_unacked
1276 << " greater than the enclosing packet number:"
1277 << last_header_.packet_number;
1278 return "Least unacked too large.";
1279 }
1280
1281 return nullptr;
1282}
1283
1284bool QuicConnection::OnRstStreamFrame(const QuicRstStreamFrame& frame) {
1285 DCHECK(connected_);
1286
1287 // Since a reset stream frame was received, this is not a connectivity probe.
1288 // A probe only contains a PING and full padding.
1289 UpdatePacketContent(NOT_PADDED_PING);
1290
1291 if (debug_visitor_ != nullptr) {
1292 debug_visitor_->OnRstStreamFrame(frame);
1293 }
1294 QUIC_DLOG(INFO) << ENDPOINT
1295 << "RST_STREAM_FRAME received for stream: " << frame.stream_id
1296 << " with error: "
1297 << QuicRstStreamErrorCodeToString(frame.error_code);
1298 visitor_->OnRstStream(frame);
1299 should_last_packet_instigate_acks_ = true;
1300 return connected_;
1301}
1302
QUICHE teama6ef0a62019-03-07 20:34:33 -05001303bool QuicConnection::OnStopSendingFrame(const QuicStopSendingFrame& frame) {
1304 DCHECK(connected_);
1305
1306 // Since a reset stream frame was received, this is not a connectivity probe.
1307 // A probe only contains a PING and full padding.
1308 UpdatePacketContent(NOT_PADDED_PING);
1309
1310 if (debug_visitor_ != nullptr) {
1311 debug_visitor_->OnStopSendingFrame(frame);
1312 }
1313
1314 QUIC_DLOG(INFO) << ENDPOINT << "STOP_SENDING frame received for stream: "
1315 << frame.stream_id
1316 << " with error: " << frame.application_error_code;
1317
1318 visitor_->OnStopSendingFrame(frame);
1319 return connected_;
1320}
1321
1322bool QuicConnection::OnPathChallengeFrame(const QuicPathChallengeFrame& frame) {
1323 // Save the path challenge's payload, for later use in generating the
1324 // response.
1325 received_path_challenge_payloads_.push_back(frame.data_buffer);
1326
1327 // For VERSION 99 we define a "Padded PATH CHALLENGE" to be the same thing
1328 // as a PADDED PING -- it will start a connectivity check and prevent
1329 // connection migration. Insofar as the connectivity check and connection
1330 // migration are concerned, logically the PATH CHALLENGE is the same as the
1331 // PING, so as a stopgap, tell the FSM that determines whether we have a
1332 // Padded PING or not that we received a PING.
1333 UpdatePacketContent(FIRST_FRAME_IS_PING);
1334 should_last_packet_instigate_acks_ = true;
1335 return true;
1336}
1337
1338bool QuicConnection::OnPathResponseFrame(const QuicPathResponseFrame& frame) {
1339 should_last_packet_instigate_acks_ = true;
1340 if (!transmitted_connectivity_probe_payload_ ||
1341 *transmitted_connectivity_probe_payload_ != frame.data_buffer) {
1342 // Is not for the probe we sent, ignore it.
1343 return true;
1344 }
1345 // Have received the matching PATH RESPONSE, saved payload no longer valid.
1346 transmitted_connectivity_probe_payload_ = nullptr;
1347 UpdatePacketContent(FIRST_FRAME_IS_PING);
1348 return true;
1349}
1350
1351bool QuicConnection::OnConnectionCloseFrame(
1352 const QuicConnectionCloseFrame& frame) {
1353 DCHECK(connected_);
1354
1355 // Since a connection close frame was received, this is not a connectivity
1356 // probe. A probe only contains a PING and full padding.
1357 UpdatePacketContent(NOT_PADDED_PING);
1358
1359 if (debug_visitor_ != nullptr) {
1360 debug_visitor_->OnConnectionCloseFrame(frame);
1361 }
1362 QUIC_DLOG(INFO) << ENDPOINT << "Received ConnectionClose for connection: "
fkastenholze9d71a82019-04-09 05:12:13 -07001363 << connection_id() << ", with error: "
1364 << QuicErrorCodeToString(frame.quic_error_code) << " ("
1365 << frame.error_details << ")";
1366 if (frame.close_type == GOOGLE_QUIC_CONNECTION_CLOSE &&
1367 frame.quic_error_code == QUIC_BAD_MULTIPATH_FLAG) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001368 QUIC_LOG_FIRST_N(ERROR, 10) << "Unexpected QUIC_BAD_MULTIPATH_FLAG error."
1369 << " last_received_header: " << last_header_
1370 << " encryption_level: " << encryption_level_;
1371 }
fkastenholze9d71a82019-04-09 05:12:13 -07001372 TearDownLocalConnectionState(frame.quic_error_code, frame.error_details,
QUICHE teama6ef0a62019-03-07 20:34:33 -05001373 ConnectionCloseSource::FROM_PEER);
1374 return connected_;
1375}
1376
fkastenholz3c4eabf2019-04-22 07:49:59 -07001377bool QuicConnection::OnMaxStreamsFrame(const QuicMaxStreamsFrame& frame) {
1378 return visitor_->OnMaxStreamsFrame(frame);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001379}
1380
fkastenholz3c4eabf2019-04-22 07:49:59 -07001381bool QuicConnection::OnStreamsBlockedFrame(
1382 const QuicStreamsBlockedFrame& frame) {
1383 return visitor_->OnStreamsBlockedFrame(frame);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001384}
1385
1386bool QuicConnection::OnGoAwayFrame(const QuicGoAwayFrame& frame) {
1387 DCHECK(connected_);
1388
1389 // Since a go away frame was received, this is not a connectivity probe.
1390 // A probe only contains a PING and full padding.
1391 UpdatePacketContent(NOT_PADDED_PING);
1392
1393 if (debug_visitor_ != nullptr) {
1394 debug_visitor_->OnGoAwayFrame(frame);
1395 }
1396 QUIC_DLOG(INFO) << ENDPOINT << "GOAWAY_FRAME received with last good stream: "
1397 << frame.last_good_stream_id
1398 << " and error: " << QuicErrorCodeToString(frame.error_code)
1399 << " and reason: " << frame.reason_phrase;
1400
1401 visitor_->OnGoAway(frame);
1402 should_last_packet_instigate_acks_ = true;
1403 return connected_;
1404}
1405
1406bool QuicConnection::OnWindowUpdateFrame(const QuicWindowUpdateFrame& frame) {
1407 DCHECK(connected_);
1408
1409 // Since a window update frame was received, this is not a connectivity probe.
1410 // A probe only contains a PING and full padding.
1411 UpdatePacketContent(NOT_PADDED_PING);
1412
1413 if (debug_visitor_ != nullptr) {
1414 debug_visitor_->OnWindowUpdateFrame(frame, time_of_last_received_packet_);
1415 }
1416 QUIC_DLOG(INFO) << ENDPOINT << "WINDOW_UPDATE_FRAME received for stream: "
1417 << frame.stream_id
1418 << " with byte offset: " << frame.byte_offset;
1419 visitor_->OnWindowUpdateFrame(frame);
1420 should_last_packet_instigate_acks_ = true;
1421 return connected_;
1422}
1423
1424bool QuicConnection::OnNewConnectionIdFrame(
1425 const QuicNewConnectionIdFrame& frame) {
1426 return true;
1427}
1428
1429bool QuicConnection::OnRetireConnectionIdFrame(
1430 const QuicRetireConnectionIdFrame& frame) {
1431 return true;
1432}
1433
1434bool QuicConnection::OnNewTokenFrame(const QuicNewTokenFrame& frame) {
1435 return true;
1436}
1437
1438bool QuicConnection::OnMessageFrame(const QuicMessageFrame& frame) {
1439 DCHECK(connected_);
1440
1441 // Since a message frame was received, this is not a connectivity probe.
1442 // A probe only contains a PING and full padding.
1443 UpdatePacketContent(NOT_PADDED_PING);
1444
1445 if (debug_visitor_ != nullptr) {
1446 debug_visitor_->OnMessageFrame(frame);
1447 }
1448 visitor_->OnMessageReceived(
1449 QuicStringPiece(frame.data, frame.message_length));
1450 should_last_packet_instigate_acks_ = true;
1451 return connected_;
1452}
1453
1454bool QuicConnection::OnBlockedFrame(const QuicBlockedFrame& frame) {
1455 DCHECK(connected_);
1456
1457 // Since a blocked frame was received, this is not a connectivity probe.
1458 // A probe only contains a PING and full padding.
1459 UpdatePacketContent(NOT_PADDED_PING);
1460
1461 if (debug_visitor_ != nullptr) {
1462 debug_visitor_->OnBlockedFrame(frame);
1463 }
1464 QUIC_DLOG(INFO) << ENDPOINT
1465 << "BLOCKED_FRAME received for stream: " << frame.stream_id;
1466 visitor_->OnBlockedFrame(frame);
1467 stats_.blocked_frames_received++;
1468 should_last_packet_instigate_acks_ = true;
1469 return connected_;
1470}
1471
1472void QuicConnection::OnPacketComplete() {
1473 // Don't do anything if this packet closed the connection.
1474 if (!connected_) {
1475 ClearLastFrames();
1476 return;
1477 }
1478
1479 if (IsCurrentPacketConnectivityProbing()) {
1480 ++stats_.num_connectivity_probing_received;
1481 }
1482
1483 QUIC_DVLOG(1) << ENDPOINT << "Got packet " << last_header_.packet_number
QUICHE team2252b702019-05-14 23:55:14 -04001484 << " for "
1485 << GetServerConnectionIdAsRecipient(last_header_, perspective_);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001486
1487 QUIC_DLOG_IF(INFO, current_packet_content_ == SECOND_FRAME_IS_PADDING)
1488 << ENDPOINT << "Received a padded PING packet. is_probing: "
1489 << IsCurrentPacketConnectivityProbing();
1490
1491 if (perspective_ == Perspective::IS_CLIENT) {
1492 QUIC_DVLOG(1) << ENDPOINT
1493 << "Received a speculative connectivity probing packet for "
QUICHE team2252b702019-05-14 23:55:14 -04001494 << GetServerConnectionIdAsRecipient(last_header_,
1495 perspective_)
QUICHE teama6ef0a62019-03-07 20:34:33 -05001496 << " from ip:port: " << last_packet_source_address_.ToString()
1497 << " to ip:port: "
1498 << last_packet_destination_address_.ToString();
1499 // TODO(zhongyi): change the method name.
1500 visitor_->OnConnectivityProbeReceived(last_packet_destination_address_,
1501 last_packet_source_address_);
1502 } else if (IsCurrentPacketConnectivityProbing()) {
1503 // This node is not a client (is a server) AND the received packet was
1504 // connectivity-probing, send an appropriate response.
1505 QUIC_DVLOG(1) << ENDPOINT << "Received a connectivity probing packet for "
QUICHE team2252b702019-05-14 23:55:14 -04001506 << GetServerConnectionIdAsRecipient(last_header_,
1507 perspective_)
QUICHE teama6ef0a62019-03-07 20:34:33 -05001508 << " from ip:port: " << last_packet_source_address_.ToString()
1509 << " to ip:port: "
1510 << last_packet_destination_address_.ToString();
1511 visitor_->OnConnectivityProbeReceived(last_packet_destination_address_,
1512 last_packet_source_address_);
1513 } else {
1514 // This node is not a client (is a server) AND the received packet was
1515 // NOT connectivity-probing. If the packet had PATH CHALLENGES, send
1516 // appropriate RESPONSE. Then deal with possible peer migration.
1517 if (transport_version() == QUIC_VERSION_99 &&
1518 !received_path_challenge_payloads_.empty()) {
1519 // If a PATH CHALLENGE was in a "Padded PING (or PATH CHALLENGE)"
1520 // then it is taken care of above. This handles the case where a PATH
1521 // CHALLENGE appeared someplace else (eg, the peer randomly added a PATH
1522 // CHALLENGE frame to some other packet.
1523 // There was at least one PATH CHALLENGE in the received packet,
1524 // Generate the required PATH RESPONSE.
1525 SendGenericPathProbePacket(nullptr, last_packet_source_address_,
1526 /* is_response= */ true);
1527 }
1528
QUICHE team1f3de242019-03-20 07:24:48 -07001529 if (last_header_.packet_number == GetLargestReceivedPacket()) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001530 direct_peer_address_ = last_packet_source_address_;
1531 if (current_effective_peer_migration_type_ != NO_CHANGE) {
QUICHE team1f3de242019-03-20 07:24:48 -07001532 // TODO(fayang): When multiple packet number spaces is supported, only
1533 // start peer migration for the application data.
QUICHE teama6ef0a62019-03-07 20:34:33 -05001534 StartEffectivePeerMigration(current_effective_peer_migration_type_);
1535 }
1536 }
1537 }
1538
1539 current_effective_peer_migration_type_ = NO_CHANGE;
1540
1541 // An ack will be sent if a missing retransmittable packet was received;
1542 const bool was_missing =
1543 should_last_packet_instigate_acks_ && was_last_packet_missing_;
1544
1545 if (received_packet_manager_.decide_when_to_send_acks()) {
QUICHE teamb23daa72019-03-21 08:37:48 -07001546 if (use_uber_received_packet_manager_) {
dschinazi05e62b12019-04-18 15:43:41 -07001547 // Some encryption levels share a packet number space, it is therefore
1548 // possible for us to want to ack some packets even though we do not yet
1549 // have the appropriate keys to encrypt the acks. In this scenario we
1550 // do not update the ACK timeout. This can happen for example with
1551 // IETF QUIC on the server when we receive 0-RTT packets and do not yet
1552 // have 1-RTT keys (0-RTT packets are acked at the 1-RTT level).
1553 // Note that this could cause slight performance degradations in the edge
1554 // case where one packet is received, then the encrypter is installed,
1555 // then a second packet is received; as that could cause the ACK for the
1556 // second packet to be delayed instead of immediate. This is currently
1557 // considered to be small enough of an edge case to not be optimized for.
fayangde00f8f2019-04-25 09:01:27 -07001558 if (!SupportsMultiplePacketNumberSpaces() ||
1559 framer_.HasEncrypterOfEncryptionLevel(QuicUtils::GetEncryptionLevel(
dschinazi05e62b12019-04-18 15:43:41 -07001560 QuicUtils::GetPacketNumberSpace(last_decrypted_packet_level_)))) {
1561 uber_received_packet_manager_.MaybeUpdateAckTimeout(
1562 should_last_packet_instigate_acks_, last_decrypted_packet_level_,
1563 last_header_.packet_number, time_of_last_received_packet_,
1564 clock_->ApproximateNow(), sent_packet_manager_.GetRttStats(),
1565 sent_packet_manager_.delayed_ack_time());
1566 } else {
1567 QUIC_DLOG(INFO) << ENDPOINT << "Not updating ACK timeout for "
1568 << QuicUtils::EncryptionLevelToString(
1569 last_decrypted_packet_level_)
1570 << " as we do not have the corresponding encrypter";
1571 }
QUICHE teamb23daa72019-03-21 08:37:48 -07001572 } else {
1573 received_packet_manager_.MaybeUpdateAckTimeout(
1574 should_last_packet_instigate_acks_, last_header_.packet_number,
1575 time_of_last_received_packet_, clock_->ApproximateNow(),
1576 sent_packet_manager_.GetRttStats(),
1577 sent_packet_manager_.delayed_ack_time());
1578 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001579 } else if (ack_frame_updated()) {
1580 // It's possible the ack frame was sent along with response data, so it
1581 // no longer needs to be sent.
1582 MaybeQueueAck(was_missing);
1583 }
1584
1585 ClearLastFrames();
1586 CloseIfTooManyOutstandingSentPackets();
1587}
1588
1589bool QuicConnection::IsValidStatelessResetToken(QuicUint128 token) const {
1590 return stateless_reset_token_received_ &&
1591 token == received_stateless_reset_token_;
1592}
1593
1594void QuicConnection::OnAuthenticatedIetfStatelessResetPacket(
1595 const QuicIetfStatelessResetPacket& packet) {
1596 // TODO(fayang): Add OnAuthenticatedIetfStatelessResetPacket to
1597 // debug_visitor_.
vasilvvc48c8712019-03-11 13:38:16 -07001598 const std::string error_details = "Received stateless reset.";
QUICHE teama6ef0a62019-03-07 20:34:33 -05001599 QUIC_CODE_COUNT(quic_tear_down_local_connection_on_stateless_reset);
1600 TearDownLocalConnectionState(QUIC_PUBLIC_RESET, error_details,
1601 ConnectionCloseSource::FROM_PEER);
1602}
1603
1604void QuicConnection::MaybeQueueAck(bool was_missing) {
1605 DCHECK(!received_packet_manager_.decide_when_to_send_acks());
1606 ++num_packets_received_since_last_ack_sent_;
1607 // Determine whether the newly received packet was missing before recording
1608 // the received packet.
1609 if (was_missing) {
1610 // Only ack immediately if an ACK frame was sent with a larger
1611 // largest acked than the newly received packet number.
1612 const QuicPacketNumber largest_sent_largest_acked =
1613 sent_packet_manager_.unacked_packets().largest_sent_largest_acked();
1614 if (largest_sent_largest_acked.IsInitialized() &&
1615 last_header_.packet_number < largest_sent_largest_acked) {
1616 if (packet_generator_.deprecate_ack_bundling_mode()) {
1617 MaybeSetAckAlarmTo(clock_->ApproximateNow());
1618 } else {
1619 ack_queued_ = true;
1620 }
1621 }
1622 }
1623
1624 if (should_last_packet_instigate_acks_ && !ack_queued_) {
1625 ++num_retransmittable_packets_received_since_last_ack_sent_;
1626 if (ack_mode_ != TCP_ACKING &&
1627 last_header_.packet_number >=
1628 received_packet_manager_.PeerFirstSendingPacketNumber() +
1629 min_received_before_ack_decimation_) {
1630 // Ack up to 10 packets at once unless ack decimation is unlimited.
1631 if (!unlimited_ack_decimation_ &&
1632 num_retransmittable_packets_received_since_last_ack_sent_ >=
1633 kMaxRetransmittablePacketsBeforeAck) {
1634 if (packet_generator_.deprecate_ack_bundling_mode()) {
1635 MaybeSetAckAlarmTo(clock_->ApproximateNow());
1636 } else {
1637 ack_queued_ = true;
1638 }
1639 } else if (ShouldSetAckAlarm()) {
1640 // Wait for the minimum of the ack decimation delay or the delayed ack
1641 // time before sending an ack.
1642 QuicTime::Delta ack_delay =
1643 std::min(sent_packet_manager_.delayed_ack_time(),
1644 sent_packet_manager_.GetRttStats()->min_rtt() *
1645 ack_decimation_delay_);
1646 const QuicTime approximate_now = clock_->ApproximateNow();
1647 if (fast_ack_after_quiescence_ &&
1648 (approximate_now - time_of_previous_received_packet_) >
1649 sent_packet_manager_.GetRttStats()->SmoothedOrInitialRtt()) {
1650 // Ack the first packet out of queiscence faster, because QUIC does
1651 // not pace the first few packets and commonly these may be handshake
1652 // or TLP packets, which we'd like to acknowledge quickly.
1653 ack_delay = QuicTime::Delta::FromMilliseconds(1);
1654 }
1655 ack_alarm_->Set(approximate_now + ack_delay);
1656 }
1657 } else {
1658 // Ack with a timer or every 2 packets by default.
1659 if (num_retransmittable_packets_received_since_last_ack_sent_ >=
1660 ack_frequency_before_ack_decimation_) {
1661 if (packet_generator_.deprecate_ack_bundling_mode()) {
1662 MaybeSetAckAlarmTo(clock_->ApproximateNow());
1663 } else {
1664 ack_queued_ = true;
1665 }
1666 } else if (ShouldSetAckAlarm()) {
1667 const QuicTime approximate_now = clock_->ApproximateNow();
1668 if (fast_ack_after_quiescence_ &&
1669 (approximate_now - time_of_previous_received_packet_) >
1670 sent_packet_manager_.GetRttStats()->SmoothedOrInitialRtt()) {
1671 // Ack the first packet out of queiscence faster, because QUIC does
1672 // not pace the first few packets and commonly these may be handshake
1673 // or TLP packets, which we'd like to acknowledge quickly.
1674 ack_alarm_->Set(approximate_now +
1675 QuicTime::Delta::FromMilliseconds(1));
1676 } else {
1677 ack_alarm_->Set(approximate_now +
1678 sent_packet_manager_.delayed_ack_time());
1679 }
1680 }
1681 }
1682
1683 // If there are new missing packets to report, send an ack immediately.
1684 if (received_packet_manager_.HasNewMissingPackets()) {
1685 if (ack_mode_ == ACK_DECIMATION_WITH_REORDERING) {
1686 // Wait the minimum of an eighth min_rtt and the existing ack time.
1687 QuicTime ack_time =
1688 clock_->ApproximateNow() +
1689 0.125 * sent_packet_manager_.GetRttStats()->min_rtt();
1690 if (ShouldSetAckAlarm() || ack_alarm_->deadline() > ack_time) {
1691 ack_alarm_->Update(ack_time, QuicTime::Delta::Zero());
1692 }
1693 } else {
1694 if (packet_generator_.deprecate_ack_bundling_mode()) {
1695 MaybeSetAckAlarmTo(clock_->ApproximateNow());
1696 } else {
1697 ack_queued_ = true;
1698 }
1699 }
1700 }
1701
1702 if (fast_ack_after_quiescence_) {
1703 time_of_previous_received_packet_ = time_of_last_received_packet_;
1704 }
1705 }
1706
1707 if (ack_queued_) {
1708 ack_alarm_->Cancel();
1709 }
1710}
1711
1712void QuicConnection::ClearLastFrames() {
1713 should_last_packet_instigate_acks_ = false;
1714}
1715
1716void QuicConnection::CloseIfTooManyOutstandingSentPackets() {
1717 // This occurs if we don't discard old packets we've seen fast enough. It's
1718 // possible largest observed is less than leaset unacked.
1719 if (sent_packet_manager_.GetLargestObserved().IsInitialized() &&
1720 sent_packet_manager_.GetLargestObserved() >
1721 sent_packet_manager_.GetLeastUnacked() + max_tracked_packets_) {
1722 CloseConnection(
1723 QUIC_TOO_MANY_OUTSTANDING_SENT_PACKETS,
1724 QuicStrCat("More than ", max_tracked_packets_,
1725 " outstanding, least_unacked: ",
1726 sent_packet_manager_.GetLeastUnacked().ToUint64()),
1727 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
1728 }
1729}
1730
1731const QuicFrame QuicConnection::GetUpdatedAckFrame() {
QUICHE teamb23daa72019-03-21 08:37:48 -07001732 if (use_uber_received_packet_manager_) {
1733 return uber_received_packet_manager_.GetUpdatedAckFrame(
QUICHE team1dfa46b2019-03-22 10:39:10 -07001734 QuicUtils::GetPacketNumberSpace(encryption_level_),
QUICHE teamb23daa72019-03-21 08:37:48 -07001735 clock_->ApproximateNow());
1736 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001737 return received_packet_manager_.GetUpdatedAckFrame(clock_->ApproximateNow());
1738}
1739
1740void QuicConnection::PopulateStopWaitingFrame(
1741 QuicStopWaitingFrame* stop_waiting) {
1742 stop_waiting->least_unacked = GetLeastUnacked();
1743}
1744
1745QuicPacketNumber QuicConnection::GetLeastUnacked() const {
1746 return sent_packet_manager_.GetLeastUnacked();
1747}
1748
1749bool QuicConnection::HandleWriteBlocked() {
1750 if (!writer_->IsWriteBlocked()) {
1751 return false;
1752 }
1753
1754 visitor_->OnWriteBlocked();
1755 return true;
1756}
1757
1758void QuicConnection::MaybeSendInResponseToPacket() {
1759 if (!connected_) {
1760 return;
1761 }
1762
1763 // If the writer is blocked, don't attempt to send packets now or in the send
1764 // alarm. When the writer unblocks, OnCanWrite() will be called for this
1765 // connection to send.
1766 if (HandleWriteBlocked()) {
1767 return;
1768 }
1769
1770 // Now that we have received an ack, we might be able to send packets which
1771 // are queued locally, or drain streams which are blocked.
1772 if (defer_send_in_response_to_packets_) {
1773 send_alarm_->Update(clock_->ApproximateNow(), QuicTime::Delta::Zero());
1774 } else {
1775 WriteAndBundleAcksIfNotBlocked();
1776 }
1777}
1778
1779void QuicConnection::SendVersionNegotiationPacket(bool ietf_quic) {
1780 pending_version_negotiation_packet_ = true;
1781 send_ietf_version_negotiation_packet_ = ietf_quic;
1782
1783 if (HandleWriteBlocked()) {
1784 return;
1785 }
1786
1787 QUIC_DLOG(INFO) << ENDPOINT << "Sending version negotiation packet: {"
1788 << ParsedQuicVersionVectorToString(
1789 framer_.supported_versions())
1790 << "}, ietf_quic: " << ietf_quic;
1791 std::unique_ptr<QuicEncryptedPacket> version_packet(
1792 packet_generator_.SerializeVersionNegotiationPacket(
1793 ietf_quic, framer_.supported_versions()));
1794 WriteResult result = writer_->WritePacket(
1795 version_packet->data(), version_packet->length(), self_address().host(),
1796 peer_address(), per_packet_options_);
1797
1798 if (IsWriteError(result.status)) {
1799 OnWriteError(result.error_code);
1800 return;
1801 }
1802 if (IsWriteBlockedStatus(result.status)) {
1803 visitor_->OnWriteBlocked();
1804 if (result.status == WRITE_STATUS_BLOCKED_DATA_BUFFERED) {
1805 pending_version_negotiation_packet_ = false;
1806 }
1807 return;
1808 }
1809
1810 pending_version_negotiation_packet_ = false;
1811}
1812
1813size_t QuicConnection::SendCryptoData(EncryptionLevel level,
1814 size_t write_length,
1815 QuicStreamOffset offset) {
1816 if (write_length == 0) {
1817 QUIC_BUG << "Attempt to send empty crypto frame";
1818 return 0;
1819 }
1820
1821 ScopedPacketFlusher flusher(this, SEND_ACK_IF_PENDING);
1822 return packet_generator_.ConsumeCryptoData(level, write_length, offset);
1823}
1824
1825QuicConsumedData QuicConnection::SendStreamData(QuicStreamId id,
1826 size_t write_length,
1827 QuicStreamOffset offset,
1828 StreamSendingState state) {
1829 if (state == NO_FIN && write_length == 0) {
1830 QUIC_BUG << "Attempt to send empty stream frame";
1831 return QuicConsumedData(0, false);
1832 }
1833
1834 // Opportunistically bundle an ack with every outgoing packet.
1835 // Particularly, we want to bundle with handshake packets since we don't know
1836 // which decrypter will be used on an ack packet following a handshake
1837 // packet (a handshake packet from client to server could result in a REJ or a
1838 // SHLO from the server, leading to two different decrypters at the server.)
1839 ScopedPacketFlusher flusher(this, SEND_ACK_IF_PENDING);
1840 return packet_generator_.ConsumeData(id, write_length, offset, state);
1841}
1842
1843bool QuicConnection::SendControlFrame(const QuicFrame& frame) {
fayang3203f252019-05-03 06:00:03 -07001844 if (!packet_generator_.deprecate_queued_control_frames() &&
1845 !CanWrite(HAS_RETRANSMITTABLE_DATA) && frame.type != PING_FRAME) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001846 QUIC_DVLOG(1) << ENDPOINT << "Failed to send control frame: " << frame;
1847 // Do not check congestion window for ping.
1848 return false;
1849 }
1850 ScopedPacketFlusher flusher(this, SEND_ACK_IF_PENDING);
fayang3203f252019-05-03 06:00:03 -07001851 const bool consumed =
1852 packet_generator_.ConsumeRetransmittableControlFrame(frame);
1853 if (packet_generator_.deprecate_queued_control_frames() && !consumed) {
1854 QUIC_DVLOG(1) << ENDPOINT << "Failed to send control frame: " << frame;
1855 return false;
1856 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001857 if (frame.type == PING_FRAME) {
1858 // Flush PING frame immediately.
1859 packet_generator_.FlushAllQueuedFrames();
1860 if (debug_visitor_ != nullptr) {
1861 debug_visitor_->OnPingSent();
1862 }
1863 }
1864 if (frame.type == BLOCKED_FRAME) {
1865 stats_.blocked_frames_sent++;
1866 }
1867 return true;
1868}
1869
1870void QuicConnection::OnStreamReset(QuicStreamId id,
1871 QuicRstStreamErrorCode error) {
1872 if (error == QUIC_STREAM_NO_ERROR) {
1873 // All data for streams which are reset with QUIC_STREAM_NO_ERROR must
1874 // be received by the peer.
1875 return;
1876 }
1877 // Flush stream frames of reset stream.
1878 if (packet_generator_.HasPendingStreamFramesOfStream(id)) {
1879 ScopedPacketFlusher flusher(this, SEND_ACK_IF_PENDING);
1880 packet_generator_.FlushAllQueuedFrames();
1881 }
1882
1883 sent_packet_manager_.CancelRetransmissionsForStream(id);
1884 // Remove all queued packets which only contain data for the reset stream.
1885 // TODO(fayang): consider removing this because it should be rarely executed.
1886 auto packet_iterator = queued_packets_.begin();
1887 while (packet_iterator != queued_packets_.end()) {
1888 QuicFrames* retransmittable_frames =
1889 &packet_iterator->retransmittable_frames;
1890 if (retransmittable_frames->empty()) {
1891 ++packet_iterator;
1892 continue;
1893 }
1894 // NOTE THAT RemoveFramesForStream removes only STREAM frames
1895 // for the specified stream.
1896 RemoveFramesForStream(retransmittable_frames, id);
1897 if (!retransmittable_frames->empty()) {
1898 ++packet_iterator;
1899 continue;
1900 }
1901 delete[] packet_iterator->encrypted_buffer;
1902 ClearSerializedPacket(&(*packet_iterator));
1903 packet_iterator = queued_packets_.erase(packet_iterator);
1904 }
1905 // TODO(ianswett): Consider checking for 3 RTOs when the last stream is
1906 // cancelled as well.
1907}
1908
1909const QuicConnectionStats& QuicConnection::GetStats() {
1910 const RttStats* rtt_stats = sent_packet_manager_.GetRttStats();
1911
1912 // Update rtt and estimated bandwidth.
1913 QuicTime::Delta min_rtt = rtt_stats->min_rtt();
1914 if (min_rtt.IsZero()) {
1915 // If min RTT has not been set, use initial RTT instead.
1916 min_rtt = rtt_stats->initial_rtt();
1917 }
1918 stats_.min_rtt_us = min_rtt.ToMicroseconds();
1919
1920 QuicTime::Delta srtt = rtt_stats->SmoothedOrInitialRtt();
1921 stats_.srtt_us = srtt.ToMicroseconds();
1922
1923 stats_.estimated_bandwidth = sent_packet_manager_.BandwidthEstimate();
1924 stats_.max_packet_size = packet_generator_.GetCurrentMaxPacketLength();
1925 stats_.max_received_packet_size = largest_received_packet_size_;
1926 return stats_;
1927}
1928
1929void QuicConnection::OnCoalescedPacket(const QuicEncryptedPacket& packet) {
1930 QueueCoalescedPacket(packet);
1931}
1932
1933void QuicConnection::ProcessUdpPacket(const QuicSocketAddress& self_address,
1934 const QuicSocketAddress& peer_address,
1935 const QuicReceivedPacket& packet) {
1936 if (!connected_) {
1937 return;
1938 }
dschinazid9467b52019-04-03 16:47:08 -07001939 QUIC_DVLOG(2) << ENDPOINT << "Received encrypted " << packet.length()
1940 << " bytes:" << std::endl
1941 << QuicTextUtils::HexDump(
1942 QuicStringPiece(packet.data(), packet.length()));
QUICHE teama6ef0a62019-03-07 20:34:33 -05001943 QUIC_BUG_IF(current_packet_data_ != nullptr)
1944 << "ProcessUdpPacket must not be called while processing a packet.";
1945 if (debug_visitor_ != nullptr) {
1946 debug_visitor_->OnPacketReceived(self_address, peer_address, packet);
1947 }
1948 last_size_ = packet.length();
1949 current_packet_data_ = packet.data();
1950
1951 last_packet_destination_address_ = self_address;
1952 last_packet_source_address_ = peer_address;
1953 if (!self_address_.IsInitialized()) {
1954 self_address_ = last_packet_destination_address_;
1955 }
1956
1957 if (!direct_peer_address_.IsInitialized()) {
1958 direct_peer_address_ = last_packet_source_address_;
1959 }
1960
1961 if (!effective_peer_address_.IsInitialized()) {
1962 const QuicSocketAddress effective_peer_addr =
1963 GetEffectivePeerAddressFromCurrentPacket();
1964
1965 // effective_peer_address_ must be initialized at the beginning of the
1966 // first packet processed(here). If effective_peer_addr is uninitialized,
1967 // just set effective_peer_address_ to the direct peer address.
1968 effective_peer_address_ = effective_peer_addr.IsInitialized()
1969 ? effective_peer_addr
1970 : direct_peer_address_;
1971 }
1972
1973 stats_.bytes_received += packet.length();
1974 ++stats_.packets_received;
1975
1976 // Ensure the time coming from the packet reader is within 2 minutes of now.
1977 if (std::abs((packet.receipt_time() - clock_->ApproximateNow()).ToSeconds()) >
1978 2 * 60) {
1979 QUIC_BUG << "Packet receipt time:"
1980 << packet.receipt_time().ToDebuggingValue()
1981 << " too far from current time:"
1982 << clock_->ApproximateNow().ToDebuggingValue();
1983 }
1984 time_of_last_received_packet_ = packet.receipt_time();
1985 QUIC_DVLOG(1) << ENDPOINT << "time of last received packet: "
1986 << time_of_last_received_packet_.ToDebuggingValue();
1987
1988 ScopedPacketFlusher flusher(this, NO_ACK);
1989 if (!framer_.ProcessPacket(packet)) {
1990 // If we are unable to decrypt this packet, it might be
1991 // because the CHLO or SHLO packet was lost.
1992 if (framer_.error() == QUIC_DECRYPTION_FAILURE) {
1993 if (encryption_level_ != ENCRYPTION_FORWARD_SECURE &&
1994 undecryptable_packets_.size() < max_undecryptable_packets_) {
1995 QueueUndecryptablePacket(packet);
1996 } else if (debug_visitor_ != nullptr) {
1997 debug_visitor_->OnUndecryptablePacket();
1998 }
1999 }
2000 QUIC_DVLOG(1) << ENDPOINT
2001 << "Unable to process packet. Last packet processed: "
2002 << last_header_.packet_number;
2003 current_packet_data_ = nullptr;
2004 is_current_packet_connectivity_probing_ = false;
2005
2006 MaybeProcessCoalescedPackets();
2007 return;
2008 }
2009
2010 ++stats_.packets_processed;
2011
2012 QUIC_DLOG_IF(INFO, active_effective_peer_migration_type_ != NO_CHANGE)
2013 << "sent_packet_manager_.GetLargestObserved() = "
2014 << sent_packet_manager_.GetLargestObserved()
2015 << ", highest_packet_sent_before_effective_peer_migration_ = "
2016 << highest_packet_sent_before_effective_peer_migration_;
2017 if (active_effective_peer_migration_type_ != NO_CHANGE &&
2018 sent_packet_manager_.GetLargestObserved().IsInitialized() &&
2019 (!highest_packet_sent_before_effective_peer_migration_.IsInitialized() ||
2020 sent_packet_manager_.GetLargestObserved() >
2021 highest_packet_sent_before_effective_peer_migration_)) {
2022 if (perspective_ == Perspective::IS_SERVER) {
2023 OnEffectivePeerMigrationValidated();
2024 }
2025 }
2026
2027 MaybeProcessCoalescedPackets();
2028 MaybeProcessUndecryptablePackets();
2029 MaybeSendInResponseToPacket();
2030 SetPingAlarm();
2031 current_packet_data_ = nullptr;
2032 is_current_packet_connectivity_probing_ = false;
2033}
2034
2035void QuicConnection::OnBlockedWriterCanWrite() {
2036 writer_->SetWritable();
2037 OnCanWrite();
2038}
2039
2040void QuicConnection::OnCanWrite() {
2041 DCHECK(!writer_->IsWriteBlocked());
2042
2043 // Add a flusher to ensure the connection is marked app-limited.
2044 ScopedPacketFlusher flusher(this, NO_ACK);
2045
2046 WriteQueuedPackets();
2047 if (received_packet_manager_.decide_when_to_send_acks()) {
QUICHE teamb23daa72019-03-21 08:37:48 -07002048 const QuicTime ack_timeout =
2049 use_uber_received_packet_manager_
QUICHE teamcd098022019-03-22 18:49:55 -07002050 ? uber_received_packet_manager_.GetEarliestAckTimeout()
QUICHE teamb23daa72019-03-21 08:37:48 -07002051 : received_packet_manager_.ack_timeout();
QUICHE teama6ef0a62019-03-07 20:34:33 -05002052 if (ack_timeout.IsInitialized() &&
2053 ack_timeout <= clock_->ApproximateNow()) {
2054 // Send an ACK now because either 1) we were write blocked when we last
2055 // tried to send an ACK, or 2) both ack alarm and send alarm were set to
2056 // go off together.
QUICHE teamcd098022019-03-22 18:49:55 -07002057 if (SupportsMultiplePacketNumberSpaces()) {
2058 SendAllPendingAcks();
2059 } else {
2060 SendAck();
2061 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002062 }
2063 } else if (send_ack_when_on_can_write_) {
2064 // Send an ACK now because either 1) we were write blocked when we last
2065 // tried to send an ACK, or 2) both ack alarm and send alarm were set to go
2066 // off together.
2067 DCHECK(packet_generator_.deprecate_ack_bundling_mode());
2068 SendAck();
2069 }
2070 if (!session_decides_what_to_write()) {
2071 WritePendingRetransmissions();
2072 }
2073
2074 WriteNewData();
2075}
2076
2077void QuicConnection::WriteNewData() {
2078 // Sending queued packets may have caused the socket to become write blocked,
2079 // or the congestion manager to prohibit sending. If we've sent everything
2080 // we had queued and we're still not blocked, let the visitor know it can
2081 // write more.
2082 if (!CanWrite(HAS_RETRANSMITTABLE_DATA)) {
2083 return;
2084 }
2085
2086 {
2087 ScopedPacketFlusher flusher(this, SEND_ACK_IF_QUEUED);
2088 visitor_->OnCanWrite();
2089 }
2090
2091 // After the visitor writes, it may have caused the socket to become write
2092 // blocked or the congestion manager to prohibit sending, so check again.
2093 if (visitor_->WillingAndAbleToWrite() && !send_alarm_->IsSet() &&
2094 CanWrite(HAS_RETRANSMITTABLE_DATA)) {
2095 // We're not write blocked, but some stream didn't write out all of its
2096 // bytes. Register for 'immediate' resumption so we'll keep writing after
2097 // other connections and events have had a chance to use the thread.
2098 send_alarm_->Set(clock_->ApproximateNow());
2099 }
2100}
2101
2102void QuicConnection::WriteIfNotBlocked() {
2103 if (!HandleWriteBlocked()) {
2104 OnCanWrite();
2105 }
2106}
2107
2108void QuicConnection::WriteAndBundleAcksIfNotBlocked() {
2109 if (!HandleWriteBlocked()) {
2110 ScopedPacketFlusher flusher(this, SEND_ACK_IF_QUEUED);
2111 WriteIfNotBlocked();
2112 }
2113}
2114
2115bool QuicConnection::ProcessValidatedPacket(const QuicPacketHeader& header) {
2116 if (perspective_ == Perspective::IS_SERVER && self_address_.IsInitialized() &&
2117 last_packet_destination_address_.IsInitialized() &&
2118 self_address_ != last_packet_destination_address_) {
2119 // Allow change between pure IPv4 and equivalent mapped IPv4 address.
2120 if (self_address_.port() != last_packet_destination_address_.port() ||
2121 self_address_.host().Normalized() !=
2122 last_packet_destination_address_.host().Normalized()) {
2123 if (!visitor_->AllowSelfAddressChange()) {
2124 CloseConnection(
2125 QUIC_ERROR_MIGRATING_ADDRESS,
2126 "Self address migration is not supported at the server.",
2127 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
2128 return false;
2129 }
2130 }
2131 self_address_ = last_packet_destination_address_;
2132 }
2133
QUICHE teamc65d1d12019-03-19 20:58:04 -07002134 if (PacketCanReplaceConnectionId(header, perspective_) &&
2135 connection_id_ != header.source_connection_id) {
2136 QUIC_DLOG(INFO) << ENDPOINT << "Replacing connection ID " << connection_id_
2137 << " with " << header.source_connection_id;
2138 connection_id_ = header.source_connection_id;
2139 packet_generator_.SetConnectionId(connection_id_);
2140 }
2141
QUICHE teamd791e2c2019-03-15 10:28:21 -07002142 if (!ValidateReceivedPacketNumber(header.packet_number)) {
2143 return false;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002144 }
2145
2146 if (version_negotiation_state_ != NEGOTIATED_VERSION) {
2147 if (perspective_ == Perspective::IS_CLIENT) {
2148 DCHECK(!header.version_flag || header.form != GOOGLE_QUIC_PACKET);
2149 if (framer_.transport_version() <= QUIC_VERSION_43) {
2150 // If the client gets a packet without the version flag from the server
2151 // it should stop sending version since the version negotiation is done.
2152 // IETF QUIC stops sending version once encryption level switches to
2153 // forward secure.
2154 packet_generator_.StopSendingVersion();
2155 }
2156 version_negotiation_state_ = NEGOTIATED_VERSION;
2157 visitor_->OnSuccessfulVersionNegotiation(version());
2158 if (debug_visitor_ != nullptr) {
2159 debug_visitor_->OnSuccessfulVersionNegotiation(version());
2160 }
2161 }
2162 }
2163
2164 if (last_size_ > largest_received_packet_size_) {
2165 largest_received_packet_size_ = last_size_;
2166 }
2167
2168 if (perspective_ == Perspective::IS_SERVER &&
QUICHE team6987b4a2019-03-15 16:23:04 -07002169 encryption_level_ == ENCRYPTION_INITIAL &&
QUICHE teama6ef0a62019-03-07 20:34:33 -05002170 last_size_ > packet_generator_.GetCurrentMaxPacketLength()) {
2171 SetMaxPacketLength(last_size_);
2172 }
2173 return true;
2174}
2175
QUICHE teamd791e2c2019-03-15 10:28:21 -07002176bool QuicConnection::ValidateReceivedPacketNumber(
2177 QuicPacketNumber packet_number) {
QUICHE teamb23daa72019-03-21 08:37:48 -07002178 if (validate_packet_number_post_decryption_) {
2179 const bool is_awaiting =
2180 use_uber_received_packet_manager_
QUICHE team1dfa46b2019-03-22 10:39:10 -07002181 ? uber_received_packet_manager_.IsAwaitingPacket(
2182 last_decrypted_packet_level_, packet_number)
QUICHE teamb23daa72019-03-21 08:37:48 -07002183 : received_packet_manager_.IsAwaitingPacket(packet_number);
2184 if (!is_awaiting) {
dschinazid9467b52019-04-03 16:47:08 -07002185 if (use_uber_received_packet_manager_) {
2186 QUIC_DLOG(INFO) << ENDPOINT << "Packet " << packet_number
2187 << " no longer being waited for at level "
2188 << static_cast<int>(last_decrypted_packet_level_)
2189 << ". Discarding.";
2190 } else {
2191 QUIC_DLOG(INFO) << ENDPOINT << "Packet " << packet_number
2192 << " no longer being waited for. Discarding.";
2193 }
QUICHE teamb23daa72019-03-21 08:37:48 -07002194 if (debug_visitor_ != nullptr) {
2195 debug_visitor_->OnDuplicatePacket(packet_number);
2196 }
2197 return false;
QUICHE team692750b2019-03-17 17:57:46 -07002198 }
QUICHE team692750b2019-03-17 17:57:46 -07002199 }
2200
QUICHE teamcd098022019-03-22 18:49:55 -07002201 if (use_uber_received_packet_manager_) {
2202 // When using uber_received_packet_manager, accept any packet numbers.
2203 return true;
2204 }
2205
QUICHE teamd791e2c2019-03-15 10:28:21 -07002206 if (GetQuicRestartFlag(quic_enable_accept_random_ipn)) {
2207 QUIC_RESTART_FLAG_COUNT_N(quic_enable_accept_random_ipn, 2, 2);
2208 // Configured to accept any packet number in range 1...0x7fffffff as initial
2209 // packet number.
2210 bool out_of_bound = false;
rchd5d13c22019-03-18 14:31:09 -07002211 std::string error_detail = "Packet number out of bounds.";
QUICHE teamd791e2c2019-03-15 10:28:21 -07002212 if (last_header_.packet_number.IsInitialized()) {
2213 out_of_bound = !Near(packet_number, last_header_.packet_number);
2214 } else if ((packet_number > MaxRandomInitialPacketNumber())) {
2215 out_of_bound = true;
2216 error_detail = "Initial packet number out of bounds.";
2217 }
2218 if (out_of_bound) {
2219 QUIC_DLOG(INFO) << ENDPOINT << "Packet " << packet_number
2220 << " out of bounds. Discarding";
2221 CloseConnection(QUIC_INVALID_PACKET_HEADER, error_detail,
2222 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
2223 return false;
2224 }
2225 return true;
2226 }
QUICHE teamcd098022019-03-22 18:49:55 -07002227
2228 if (packet_number > received_packet_manager_.PeerFirstSendingPacketNumber() &&
QUICHE teamd791e2c2019-03-15 10:28:21 -07002229 packet_number <= MaxRandomInitialPacketNumber()) {
2230 QUIC_CODE_COUNT_N(had_possibly_random_ipn, 2, 2);
2231 }
2232 const bool out_of_bound =
2233 last_header_.packet_number.IsInitialized()
2234 ? !Near(packet_number, last_header_.packet_number)
QUICHE teamcd098022019-03-22 18:49:55 -07002235 : packet_number >=
2236 (received_packet_manager_.PeerFirstSendingPacketNumber() +
2237 kMaxPacketGap);
QUICHE teamd791e2c2019-03-15 10:28:21 -07002238 if (!out_of_bound) {
2239 return true;
2240 }
2241 QUIC_DLOG(INFO) << ENDPOINT << "Packet " << packet_number
2242 << " out of bounds. Discarding";
2243 QuicStringPiece packet_data = GetCurrentPacket();
2244 const size_t kMaxPacketLengthInErrorDetails = 64;
2245 CloseConnection(
2246 QUIC_INVALID_PACKET_HEADER,
2247 QuicStrCat(
2248 "Packet number out of bounds. ",
2249 last_header_.packet_number.IsInitialized()
2250 ? QuicStrCat("last_pkn=", last_header_.packet_number.ToUint64())
2251 : "first received packet",
2252 ", current_pkn=", packet_number.ToUint64(),
2253 ", current_pkt_len=", packet_data.length(), ", current_hdr=",
2254 QuicTextUtils::HexEncode(
2255 packet_data.length() > kMaxPacketLengthInErrorDetails
2256 ? QuicStringPiece(packet_data.data(),
2257 kMaxPacketLengthInErrorDetails)
2258 : packet_data)),
2259 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
2260 return false;
2261}
2262
QUICHE teama6ef0a62019-03-07 20:34:33 -05002263void QuicConnection::WriteQueuedPackets() {
2264 DCHECK(!writer_->IsWriteBlocked());
2265
2266 if (pending_version_negotiation_packet_) {
2267 SendVersionNegotiationPacket(send_ietf_version_negotiation_packet_);
2268 }
2269
2270 QUIC_CLIENT_HISTOGRAM_COUNTS("QuicSession.NumQueuedPacketsBeforeWrite",
2271 queued_packets_.size(), 1, 1000, 50, "");
2272 while (!queued_packets_.empty()) {
2273 // WritePacket() can potentially clear all queued packets, so we need to
2274 // save the first queued packet to a local variable before calling it.
2275 SerializedPacket packet(std::move(queued_packets_.front()));
2276 queued_packets_.pop_front();
2277
2278 const bool write_result = WritePacket(&packet);
2279
2280 if (connected_ && !write_result) {
2281 // Write failed but connection is open, re-insert |packet| into the
2282 // front of the queue, it will be retried later.
2283 queued_packets_.emplace_front(std::move(packet));
2284 break;
2285 }
2286
2287 delete[] packet.encrypted_buffer;
2288 ClearSerializedPacket(&packet);
2289 if (!connected_) {
2290 DCHECK(queued_packets_.empty()) << "Queued packets should have been "
2291 "cleared while closing connection";
2292 break;
2293 }
2294
2295 // Continue to send the next packet in queue.
2296 }
2297}
2298
2299void QuicConnection::WritePendingRetransmissions() {
2300 DCHECK(!session_decides_what_to_write());
2301 // Keep writing as long as there's a pending retransmission which can be
2302 // written.
2303 while (sent_packet_manager_.HasPendingRetransmissions() &&
2304 CanWrite(HAS_RETRANSMITTABLE_DATA)) {
2305 const QuicPendingRetransmission pending =
2306 sent_packet_manager_.NextPendingRetransmission();
2307
2308 // Re-packetize the frames with a new packet number for retransmission.
2309 // Retransmitted packets use the same packet number length as the
2310 // original.
2311 // Flush the packet generator before making a new packet.
2312 // TODO(ianswett): Implement ReserializeAllFrames as a separate path that
2313 // does not require the creator to be flushed.
2314 // TODO(fayang): FlushAllQueuedFrames should only be called once, and should
2315 // be moved outside of the loop. Also, CanWrite is not checked after the
2316 // generator is flushed.
2317 {
2318 ScopedPacketFlusher flusher(this, NO_ACK);
2319 packet_generator_.FlushAllQueuedFrames();
2320 }
2321 DCHECK(!packet_generator_.HasQueuedFrames());
dschinazi66dea072019-04-09 11:41:06 -07002322 char buffer[kMaxOutgoingPacketSize];
2323 packet_generator_.ReserializeAllFrames(pending, buffer,
2324 kMaxOutgoingPacketSize);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002325 }
2326}
2327
2328void QuicConnection::SendProbingRetransmissions() {
2329 while (sent_packet_manager_.GetSendAlgorithm()->ShouldSendProbingPacket() &&
2330 CanWrite(HAS_RETRANSMITTABLE_DATA)) {
QUICHE teamb8343252019-04-29 13:58:01 -07002331 if (!visitor_->SendProbingData()) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002332 QUIC_DVLOG(1)
2333 << "Cannot send probing retransmissions: nothing to retransmit.";
2334 break;
2335 }
2336
2337 if (!session_decides_what_to_write()) {
2338 DCHECK(sent_packet_manager_.HasPendingRetransmissions());
2339 WritePendingRetransmissions();
2340 }
2341 }
2342}
2343
2344void QuicConnection::RetransmitUnackedPackets(
2345 TransmissionType retransmission_type) {
2346 sent_packet_manager_.RetransmitUnackedPackets(retransmission_type);
2347
2348 WriteIfNotBlocked();
2349}
2350
2351void QuicConnection::NeuterUnencryptedPackets() {
2352 sent_packet_manager_.NeuterUnencryptedPackets();
2353 // This may have changed the retransmission timer, so re-arm it.
2354 SetRetransmissionAlarm();
2355}
2356
2357bool QuicConnection::ShouldGeneratePacket(
2358 HasRetransmittableData retransmittable,
2359 IsHandshake handshake) {
2360 // We should serialize handshake packets immediately to ensure that they
2361 // end up sent at the right encryption level.
2362 if (handshake == IS_HANDSHAKE) {
2363 return true;
2364 }
2365
2366 return CanWrite(retransmittable);
2367}
2368
2369const QuicFrames QuicConnection::MaybeBundleAckOpportunistically() {
2370 DCHECK(packet_generator_.deprecate_ack_bundling_mode());
2371 QuicFrames frames;
2372 bool has_pending_ack = false;
2373 if (received_packet_manager_.decide_when_to_send_acks()) {
QUICHE teamb23daa72019-03-21 08:37:48 -07002374 if (use_uber_received_packet_manager_) {
2375 has_pending_ack =
QUICHE team1dfa46b2019-03-22 10:39:10 -07002376 uber_received_packet_manager_
2377 .GetAckTimeout(QuicUtils::GetPacketNumberSpace(encryption_level_))
2378 .IsInitialized();
QUICHE teamb23daa72019-03-21 08:37:48 -07002379 } else {
2380 has_pending_ack = received_packet_manager_.ack_timeout().IsInitialized();
2381 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002382 } else {
2383 has_pending_ack = ack_alarm_->IsSet();
2384 }
2385 if (!has_pending_ack && stop_waiting_count_ <= 1) {
2386 // No need to send an ACK.
2387 return frames;
2388 }
2389 ResetAckStates();
2390
2391 QUIC_DVLOG(1) << ENDPOINT << "Bundle an ACK opportunistically";
2392 frames.push_back(GetUpdatedAckFrame());
2393 if (!no_stop_waiting_frames_) {
2394 QuicStopWaitingFrame stop_waiting;
2395 PopulateStopWaitingFrame(&stop_waiting);
2396 frames.push_back(QuicFrame(stop_waiting));
2397 }
2398 return frames;
2399}
2400
2401bool QuicConnection::CanWrite(HasRetransmittableData retransmittable) {
2402 if (!connected_) {
2403 return false;
2404 }
2405
2406 if (session_decides_what_to_write() &&
2407 sent_packet_manager_.pending_timer_transmission_count() > 0) {
2408 // Force sending the retransmissions for HANDSHAKE, TLP, RTO, PROBING cases.
2409 return true;
2410 }
2411
2412 if (HandleWriteBlocked()) {
2413 return false;
2414 }
2415
2416 // Allow acks to be sent immediately.
2417 if (retransmittable == NO_RETRANSMITTABLE_DATA) {
2418 return true;
2419 }
2420 // If the send alarm is set, wait for it to fire.
2421 if (send_alarm_->IsSet()) {
2422 return false;
2423 }
2424
2425 QuicTime now = clock_->Now();
2426 QuicTime::Delta delay = sent_packet_manager_.TimeUntilSend(now);
2427 if (delay.IsInfinite()) {
2428 send_alarm_->Cancel();
2429 return false;
2430 }
2431
2432 // Scheduler requires a delay.
2433 if (!delay.IsZero()) {
2434 if (delay <= release_time_into_future_) {
2435 // Required delay is within pace time into future, send now.
2436 return true;
2437 }
2438 // Cannot send packet now because delay is too far in the future.
2439 send_alarm_->Update(now + delay, QuicTime::Delta::FromMilliseconds(1));
2440 QUIC_DVLOG(1) << ENDPOINT << "Delaying sending " << delay.ToMilliseconds()
2441 << "ms";
2442 return false;
2443 }
2444 return true;
2445}
2446
2447bool QuicConnection::WritePacket(SerializedPacket* packet) {
2448 if (ShouldDiscardPacket(*packet)) {
2449 ++stats_.packets_discarded;
2450 return true;
2451 }
2452 if (sent_packet_manager_.GetLargestSentPacket().IsInitialized() &&
2453 packet->packet_number < sent_packet_manager_.GetLargestSentPacket()) {
2454 QUIC_BUG << "Attempt to write packet:" << packet->packet_number
2455 << " after:" << sent_packet_manager_.GetLargestSentPacket();
2456 QUIC_CLIENT_HISTOGRAM_COUNTS("QuicSession.NumQueuedPacketsAtOutOfOrder",
2457 queued_packets_.size(), 1, 1000, 50, "");
2458 CloseConnection(QUIC_INTERNAL_ERROR, "Packet written out of order.",
2459 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
2460 return true;
2461 }
2462 // Termination packets are encrypted and saved, so don't exit early.
2463 const bool is_termination_packet = IsTerminationPacket(*packet);
2464 if (HandleWriteBlocked() && !is_termination_packet) {
2465 return false;
2466 }
2467
2468 QuicPacketNumber packet_number = packet->packet_number;
2469
2470 QuicPacketLength encrypted_length = packet->encrypted_length;
2471 // Termination packets are eventually owned by TimeWaitListManager.
2472 // Others are deleted at the end of this call.
2473 if (is_termination_packet) {
2474 if (termination_packets_ == nullptr) {
2475 termination_packets_.reset(
2476 new std::vector<std::unique_ptr<QuicEncryptedPacket>>);
2477 }
2478 // Copy the buffer so it's owned in the future.
2479 char* buffer_copy = CopyBuffer(*packet);
2480 termination_packets_->emplace_back(
2481 new QuicEncryptedPacket(buffer_copy, encrypted_length, true));
2482 // This assures we won't try to write *forced* packets when blocked.
2483 // Return true to stop processing.
2484 if (HandleWriteBlocked()) {
2485 return true;
2486 }
2487 }
2488
dschinazi66dea072019-04-09 11:41:06 -07002489 DCHECK_LE(encrypted_length, kMaxOutgoingPacketSize);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002490 DCHECK_LE(encrypted_length, packet_generator_.GetCurrentMaxPacketLength());
2491 QUIC_DVLOG(1) << ENDPOINT << "Sending packet " << packet_number << " : "
2492 << (IsRetransmittable(*packet) == HAS_RETRANSMITTABLE_DATA
2493 ? "data bearing "
2494 : " ack only ")
2495 << ", encryption level: "
2496 << QuicUtils::EncryptionLevelToString(packet->encryption_level)
2497 << ", encrypted length:" << encrypted_length;
2498 QUIC_DVLOG(2) << ENDPOINT << "packet(" << packet_number << "): " << std::endl
2499 << QuicTextUtils::HexDump(QuicStringPiece(
2500 packet->encrypted_buffer, encrypted_length));
2501
2502 // Measure the RTT from before the write begins to avoid underestimating the
2503 // min_rtt_, especially in cases where the thread blocks or gets swapped out
2504 // during the WritePacket below.
2505 QuicTime packet_send_time = clock_->Now();
2506 if (supports_release_time_ && per_packet_options_ != nullptr) {
2507 QuicTime next_release_time = sent_packet_manager_.GetNextReleaseTime();
2508 QuicTime::Delta release_time_delay = QuicTime::Delta::Zero();
2509 QuicTime now = packet_send_time;
2510 if (next_release_time > now) {
2511 release_time_delay = next_release_time - now;
2512 // Set packet_send_time to the future to make the RTT estimation accurate.
2513 packet_send_time = next_release_time;
2514 }
2515 per_packet_options_->release_time_delay = release_time_delay;
2516 }
2517 WriteResult result = writer_->WritePacket(
2518 packet->encrypted_buffer, encrypted_length, self_address().host(),
2519 peer_address(), per_packet_options_);
2520
2521 QUIC_HISTOGRAM_ENUM(
2522 "QuicConnection.WritePacketStatus", result.status,
2523 WRITE_STATUS_NUM_VALUES,
2524 "Status code returned by writer_->WritePacket() in QuicConnection.");
2525
2526 if (IsWriteBlockedStatus(result.status)) {
2527 // Ensure the writer is still write blocked, otherwise QUIC may continue
2528 // trying to write when it will not be able to.
2529 DCHECK(writer_->IsWriteBlocked());
2530 visitor_->OnWriteBlocked();
2531 // If the socket buffers the data, then the packet should not
2532 // be queued and sent again, which would result in an unnecessary
2533 // duplicate packet being sent. The helper must call OnCanWrite
2534 // when the write completes, and OnWriteError if an error occurs.
2535 if (result.status != WRITE_STATUS_BLOCKED_DATA_BUFFERED) {
2536 return false;
2537 }
2538 }
2539
2540 // In some cases, an MTU probe can cause EMSGSIZE. This indicates that the
2541 // MTU discovery is permanently unsuccessful.
2542 if (IsMsgTooBig(result) && packet->retransmittable_frames.empty() &&
2543 packet->encrypted_length > long_term_mtu_) {
2544 mtu_discovery_target_ = 0;
2545 mtu_discovery_alarm_->Cancel();
2546 // The write failed, but the writer is not blocked, so return true.
2547 return true;
2548 }
2549
2550 if (IsWriteError(result.status)) {
2551 OnWriteError(result.error_code);
2552 QUIC_LOG_FIRST_N(ERROR, 10)
2553 << ENDPOINT << "failed writing " << encrypted_length
2554 << " bytes from host " << self_address().host().ToString()
2555 << " to address " << peer_address().ToString() << " with error code "
2556 << result.error_code;
2557 return false;
2558 }
2559
2560 if (debug_visitor_ != nullptr) {
2561 // Pass the write result to the visitor.
2562 debug_visitor_->OnPacketSent(*packet, packet->original_packet_number,
2563 packet->transmission_type, packet_send_time);
2564 }
2565 if (IsRetransmittable(*packet) == HAS_RETRANSMITTABLE_DATA) {
2566 if (!is_path_degrading_ && !path_degrading_alarm_->IsSet()) {
2567 // This is the first retransmittable packet on the working path.
2568 // Start the path degrading alarm to detect new path degrading.
2569 SetPathDegradingAlarm();
2570 }
2571
2572 if (GetQuicReloadableFlag(
2573 quic_fix_time_of_first_packet_sent_after_receiving)) {
2574 // Update |time_of_first_packet_sent_after_receiving_| if this is the
2575 // first packet sent after the last packet was received. If it were
2576 // updated on every sent packet, then sending into a black hole might
2577 // never timeout.
2578 if (time_of_first_packet_sent_after_receiving_ <
2579 time_of_last_received_packet_) {
2580 QUIC_RELOADABLE_FLAG_COUNT(
2581 quic_fix_time_of_first_packet_sent_after_receiving);
2582 time_of_first_packet_sent_after_receiving_ = packet_send_time;
2583 }
2584 } else {
2585 // Only adjust the last sent time (for the purpose of tracking the idle
2586 // timeout) if this is the first retransmittable packet sent after a
2587 // packet is received. If it were updated on every sent packet, then
2588 // sending into a black hole might never timeout.
2589 if (time_of_first_packet_sent_after_receiving_ <=
2590 time_of_last_received_packet_) {
2591 time_of_first_packet_sent_after_receiving_ = packet_send_time;
2592 }
2593 }
2594 }
2595
2596 MaybeSetMtuAlarm(packet_number);
2597 QUIC_DVLOG(1) << ENDPOINT << "time we began writing last sent packet: "
2598 << packet_send_time.ToDebuggingValue();
2599
2600 bool reset_retransmission_alarm = sent_packet_manager_.OnPacketSent(
2601 packet, packet->original_packet_number, packet_send_time,
2602 packet->transmission_type, IsRetransmittable(*packet));
2603
2604 if (reset_retransmission_alarm || !retransmission_alarm_->IsSet()) {
2605 SetRetransmissionAlarm();
2606 }
2607 SetPingAlarm();
2608
2609 // The packet number length must be updated after OnPacketSent, because it
2610 // may change the packet number length in packet.
2611 packet_generator_.UpdatePacketNumberLength(
2612 sent_packet_manager_.GetLeastUnacked(),
2613 sent_packet_manager_.EstimateMaxPacketsInFlight(max_packet_length()));
2614
2615 stats_.bytes_sent += result.bytes_written;
2616 ++stats_.packets_sent;
2617 if (packet->transmission_type != NOT_RETRANSMISSION) {
2618 stats_.bytes_retransmitted += result.bytes_written;
2619 ++stats_.packets_retransmitted;
2620 }
2621
2622 return true;
2623}
2624
2625void QuicConnection::FlushPackets() {
2626 if (!connected_) {
2627 return;
2628 }
2629
2630 if (!writer_->IsBatchMode()) {
2631 return;
2632 }
2633
2634 if (HandleWriteBlocked()) {
2635 QUIC_DLOG(INFO) << ENDPOINT << "FlushPackets called while blocked.";
2636 return;
2637 }
2638
2639 WriteResult result = writer_->Flush();
2640
2641 if (HandleWriteBlocked()) {
2642 DCHECK_EQ(WRITE_STATUS_BLOCKED, result.status)
2643 << "Unexpected flush result:" << result;
2644 QUIC_DLOG(INFO) << ENDPOINT << "Write blocked in FlushPackets.";
2645 return;
2646 }
2647
2648 if (IsWriteError(result.status)) {
2649 OnWriteError(result.error_code);
2650 }
2651}
2652
2653bool QuicConnection::IsMsgTooBig(const WriteResult& result) {
2654 return (result.status == WRITE_STATUS_MSG_TOO_BIG) ||
2655 (IsWriteError(result.status) && result.error_code == QUIC_EMSGSIZE);
2656}
2657
2658bool QuicConnection::ShouldDiscardPacket(const SerializedPacket& packet) {
2659 if (!connected_) {
2660 QUIC_DLOG(INFO) << ENDPOINT
2661 << "Not sending packet as connection is disconnected.";
2662 return true;
2663 }
2664
2665 QuicPacketNumber packet_number = packet.packet_number;
2666 if (encryption_level_ == ENCRYPTION_FORWARD_SECURE &&
QUICHE team6987b4a2019-03-15 16:23:04 -07002667 packet.encryption_level == ENCRYPTION_INITIAL) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002668 // Drop packets that are NULL encrypted since the peer won't accept them
2669 // anymore.
2670 QUIC_DLOG(INFO) << ENDPOINT
2671 << "Dropping NULL encrypted packet: " << packet_number
2672 << " since the connection is forward secure.";
2673 return true;
2674 }
2675
2676 return false;
2677}
2678
2679void QuicConnection::OnWriteError(int error_code) {
2680 if (write_error_occurred_) {
2681 // A write error already occurred. The connection is being closed.
2682 return;
2683 }
2684 write_error_occurred_ = true;
2685
vasilvvc48c8712019-03-11 13:38:16 -07002686 const std::string error_details = QuicStrCat(
QUICHE teama6ef0a62019-03-07 20:34:33 -05002687 "Write failed with error: ", error_code, " (", strerror(error_code), ")");
2688 QUIC_LOG_FIRST_N(ERROR, 2) << ENDPOINT << error_details;
2689 switch (error_code) {
2690 case QUIC_EMSGSIZE:
ianswettdc1e7ab2019-05-03 16:10:44 -07002691 CloseConnection(QUIC_PACKET_WRITE_ERROR, error_details,
2692 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002693 break;
2694 default:
2695 // We can't send an error as the socket is presumably borked.
2696 if (transport_version() > QUIC_VERSION_43) {
2697 QUIC_CODE_COUNT(quic_tear_down_local_connection_on_write_error_ietf);
2698 } else {
2699 QUIC_CODE_COUNT(
2700 quic_tear_down_local_connection_on_write_error_non_ietf);
2701 }
2702 TearDownLocalConnectionState(QUIC_PACKET_WRITE_ERROR, error_details,
2703 ConnectionCloseSource::FROM_SELF);
2704 }
2705}
2706
2707char* QuicConnection::GetPacketBuffer() {
2708 return writer_->GetNextWriteLocation(self_address().host(), peer_address());
2709}
2710
2711void QuicConnection::OnSerializedPacket(SerializedPacket* serialized_packet) {
2712 if (serialized_packet->encrypted_buffer == nullptr) {
2713 // We failed to serialize the packet, so close the connection.
2714 // TearDownLocalConnectionState does not send close packet, so no infinite
2715 // loop here.
2716 // TODO(ianswett): This is actually an internal error, not an
2717 // encryption failure.
2718 if (transport_version() > QUIC_VERSION_43) {
2719 QUIC_CODE_COUNT(
2720 quic_tear_down_local_connection_on_serialized_packet_ietf);
2721 } else {
2722 QUIC_CODE_COUNT(
2723 quic_tear_down_local_connection_on_serialized_packet_non_ietf);
2724 }
2725 TearDownLocalConnectionState(
2726 QUIC_ENCRYPTION_FAILURE,
2727 "Serialized packet does not have an encrypted buffer.",
2728 ConnectionCloseSource::FROM_SELF);
2729 return;
2730 }
2731
2732 if (serialized_packet->retransmittable_frames.empty() &&
2733 !serialized_packet->original_packet_number.IsInitialized()) {
2734 // Increment consecutive_num_packets_with_no_retransmittable_frames_ if
2735 // this packet is a new transmission with no retransmittable frames.
2736 ++consecutive_num_packets_with_no_retransmittable_frames_;
2737 } else {
2738 consecutive_num_packets_with_no_retransmittable_frames_ = 0;
2739 }
2740 SendOrQueuePacket(serialized_packet);
2741}
2742
2743void QuicConnection::OnUnrecoverableError(QuicErrorCode error,
vasilvvc48c8712019-03-11 13:38:16 -07002744 const std::string& error_details,
QUICHE teama6ef0a62019-03-07 20:34:33 -05002745 ConnectionCloseSource source) {
2746 // The packet creator or generator encountered an unrecoverable error: tear
2747 // down local connection state immediately.
2748 if (transport_version() > QUIC_VERSION_43) {
2749 QUIC_CODE_COUNT(
2750 quic_tear_down_local_connection_on_unrecoverable_error_ietf);
2751 } else {
2752 QUIC_CODE_COUNT(
2753 quic_tear_down_local_connection_on_unrecoverable_error_non_ietf);
2754 }
2755 TearDownLocalConnectionState(error, error_details, source);
2756}
2757
2758void QuicConnection::OnCongestionChange() {
2759 visitor_->OnCongestionWindowChange(clock_->ApproximateNow());
2760
2761 // Uses the connection's smoothed RTT. If zero, uses initial_rtt.
2762 QuicTime::Delta rtt = sent_packet_manager_.GetRttStats()->smoothed_rtt();
2763 if (rtt.IsZero()) {
2764 rtt = sent_packet_manager_.GetRttStats()->initial_rtt();
2765 }
2766
2767 if (debug_visitor_ != nullptr) {
2768 debug_visitor_->OnRttChanged(rtt);
2769 }
2770}
2771
2772void QuicConnection::OnPathMtuIncreased(QuicPacketLength packet_size) {
2773 if (packet_size > max_packet_length()) {
2774 SetMaxPacketLength(packet_size);
2775 }
2776}
2777
2778void QuicConnection::OnHandshakeComplete() {
2779 sent_packet_manager_.SetHandshakeConfirmed();
2780 if (sent_packet_manager_.unacked_packets().use_uber_loss_algorithm()) {
2781 // This may have changed the retransmission timer, so re-arm it.
2782 SetRetransmissionAlarm();
2783 }
2784 // The client should immediately ack the SHLO to confirm the handshake is
2785 // complete with the server.
2786 if (perspective_ == Perspective::IS_CLIENT && !ack_queued_ &&
2787 ack_frame_updated()) {
2788 ack_alarm_->Update(clock_->ApproximateNow(), QuicTime::Delta::Zero());
2789 }
2790}
2791
2792void QuicConnection::SendOrQueuePacket(SerializedPacket* packet) {
2793 // The caller of this function is responsible for checking CanWrite().
2794 if (packet->encrypted_buffer == nullptr) {
2795 QUIC_BUG << "packet.encrypted_buffer == nullptr in to SendOrQueuePacket";
2796 return;
2797 }
2798 // If there are already queued packets, queue this one immediately to ensure
2799 // it's written in sequence number order.
2800 if (!queued_packets_.empty() || !WritePacket(packet)) {
2801 // Take ownership of the underlying encrypted packet.
2802 packet->encrypted_buffer = CopyBuffer(*packet);
2803 queued_packets_.push_back(*packet);
2804 packet->retransmittable_frames.clear();
2805 }
2806
2807 ClearSerializedPacket(packet);
2808}
2809
2810void QuicConnection::OnPingTimeout() {
2811 if (!retransmission_alarm_->IsSet()) {
zhongyifbb25772019-04-10 16:54:08 -07002812 bool enable_half_rtt_tail_loss_probe =
2813 sent_packet_manager_.enable_half_rtt_tail_loss_probe();
2814 if (enable_half_rtt_tail_loss_probe &&
2815 GetQuicReloadableFlag(quic_ignore_tlpr_if_sending_ping)) {
zhongyi19461252019-04-29 12:44:25 -07002816 QUIC_RELOADABLE_FLAG_COUNT_N(quic_ignore_tlpr_if_sending_ping, 1, 2);
zhongyifbb25772019-04-10 16:54:08 -07002817 sent_packet_manager_.set_enable_half_rtt_tail_loss_probe(false);
2818 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002819 visitor_->SendPing();
zhongyifbb25772019-04-10 16:54:08 -07002820 if (enable_half_rtt_tail_loss_probe &&
2821 GetQuicReloadableFlag(quic_ignore_tlpr_if_sending_ping)) {
zhongyi19461252019-04-29 12:44:25 -07002822 QUIC_RELOADABLE_FLAG_COUNT_N(quic_ignore_tlpr_if_sending_ping, 2, 2);
zhongyifbb25772019-04-10 16:54:08 -07002823 sent_packet_manager_.set_enable_half_rtt_tail_loss_probe(true);
2824 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002825 }
2826}
2827
2828void QuicConnection::SendAck() {
QUICHE teamcd098022019-03-22 18:49:55 -07002829 DCHECK(!SupportsMultiplePacketNumberSpaces());
QUICHE teama6ef0a62019-03-07 20:34:33 -05002830 if (!received_packet_manager_.decide_when_to_send_acks()) {
2831 // When received_packet_manager decides when to send ack, delaying
2832 // ResetAckStates until ACK is successfully flushed.
2833 ResetAckStates();
2834 }
2835
2836 if (packet_generator_.deprecate_ack_bundling_mode()) {
2837 QUIC_DVLOG(1) << ENDPOINT << "Sending an ACK proactively";
2838 QuicFrames frames;
2839 frames.push_back(GetUpdatedAckFrame());
2840 if (!no_stop_waiting_frames_) {
2841 QuicStopWaitingFrame stop_waiting;
2842 PopulateStopWaitingFrame(&stop_waiting);
2843 frames.push_back(QuicFrame(stop_waiting));
2844 }
2845 if (received_packet_manager_.decide_when_to_send_acks()) {
2846 if (!packet_generator_.FlushAckFrame(frames)) {
2847 return;
2848 }
2849 ResetAckStates();
2850 } else {
2851 send_ack_when_on_can_write_ = !packet_generator_.FlushAckFrame(frames);
2852 }
2853 } else {
2854 packet_generator_.SetShouldSendAck(!no_stop_waiting_frames_);
2855 }
2856 if (consecutive_num_packets_with_no_retransmittable_frames_ <
2857 max_consecutive_num_packets_with_no_retransmittable_frames_) {
2858 return;
2859 }
2860 consecutive_num_packets_with_no_retransmittable_frames_ = 0;
2861 if (packet_generator_.HasRetransmittableFrames() ||
2862 visitor_->WillingAndAbleToWrite()) {
2863 // There are pending retransmittable frames.
2864 return;
2865 }
2866
2867 visitor_->OnAckNeedsRetransmittableFrame();
2868}
2869
2870void QuicConnection::OnPathDegradingTimeout() {
2871 is_path_degrading_ = true;
2872 visitor_->OnPathDegrading();
2873}
2874
2875void QuicConnection::OnRetransmissionTimeout() {
2876 DCHECK(!sent_packet_manager_.unacked_packets().empty());
2877 if (close_connection_after_five_rtos_ &&
2878 sent_packet_manager_.GetConsecutiveRtoCount() >= 4) {
2879 // Close on the 5th consecutive RTO, so after 4 previous RTOs have occurred.
2880 CloseConnection(QUIC_TOO_MANY_RTOS, "5 consecutive retransmission timeouts",
2881 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
2882 return;
2883 }
2884
2885 sent_packet_manager_.OnRetransmissionTimeout();
2886 WriteIfNotBlocked();
2887
2888 // A write failure can result in the connection being closed, don't attempt to
2889 // write further packets, or to set alarms.
2890 if (!connected_) {
2891 return;
2892 }
2893
2894 // In the TLP case, the SentPacketManager gives the connection the opportunity
2895 // to send new data before retransmitting.
2896 if (sent_packet_manager_.MaybeRetransmitTailLossProbe()) {
2897 // Send the pending retransmission now that it's been queued.
2898 WriteIfNotBlocked();
2899 }
2900
2901 // Ensure the retransmission alarm is always set if there are unacked packets
2902 // and nothing waiting to be sent.
2903 // This happens if the loss algorithm invokes a timer based loss, but the
2904 // packet doesn't need to be retransmitted.
2905 if (!HasQueuedData() && !retransmission_alarm_->IsSet()) {
2906 SetRetransmissionAlarm();
2907 }
2908}
2909
2910void QuicConnection::SetEncrypter(EncryptionLevel level,
2911 std::unique_ptr<QuicEncrypter> encrypter) {
2912 packet_generator_.SetEncrypter(level, std::move(encrypter));
2913}
2914
2915void QuicConnection::SetDiversificationNonce(
2916 const DiversificationNonce& nonce) {
2917 DCHECK_EQ(Perspective::IS_SERVER, perspective_);
2918 packet_generator_.SetDiversificationNonce(nonce);
2919}
2920
2921void QuicConnection::SetDefaultEncryptionLevel(EncryptionLevel level) {
2922 if (level != encryption_level_ && packet_generator_.HasQueuedFrames()) {
2923 // Flush all queued frames when encryption level changes.
2924 ScopedPacketFlusher flusher(this, NO_ACK);
2925 packet_generator_.FlushAllQueuedFrames();
2926 }
2927 encryption_level_ = level;
2928 packet_generator_.set_encryption_level(level);
2929}
2930
2931void QuicConnection::SetDecrypter(EncryptionLevel level,
2932 std::unique_ptr<QuicDecrypter> decrypter) {
2933 framer_.SetDecrypter(level, std::move(decrypter));
2934
2935 if (!undecryptable_packets_.empty() &&
2936 !process_undecryptable_packets_alarm_->IsSet()) {
2937 process_undecryptable_packets_alarm_->Set(clock_->ApproximateNow());
2938 }
2939}
2940
2941void QuicConnection::SetAlternativeDecrypter(
2942 EncryptionLevel level,
2943 std::unique_ptr<QuicDecrypter> decrypter,
2944 bool latch_once_used) {
2945 framer_.SetAlternativeDecrypter(level, std::move(decrypter), latch_once_used);
2946
2947 if (!undecryptable_packets_.empty() &&
2948 !process_undecryptable_packets_alarm_->IsSet()) {
2949 process_undecryptable_packets_alarm_->Set(clock_->ApproximateNow());
2950 }
2951}
2952
zhongyi546cc452019-04-12 15:27:49 -07002953void QuicConnection::InstallDecrypter(
2954 EncryptionLevel level,
2955 std::unique_ptr<QuicDecrypter> decrypter) {
2956 framer_.InstallDecrypter(level, std::move(decrypter));
2957 if (!undecryptable_packets_.empty() &&
2958 !process_undecryptable_packets_alarm_->IsSet()) {
2959 process_undecryptable_packets_alarm_->Set(clock_->ApproximateNow());
2960 }
2961}
2962
2963void QuicConnection::RemoveDecrypter(EncryptionLevel level) {
2964 framer_.RemoveDecrypter(level);
2965}
2966
QUICHE teama6ef0a62019-03-07 20:34:33 -05002967const QuicDecrypter* QuicConnection::decrypter() const {
2968 return framer_.decrypter();
2969}
2970
2971const QuicDecrypter* QuicConnection::alternative_decrypter() const {
2972 return framer_.alternative_decrypter();
2973}
2974
2975void QuicConnection::QueueUndecryptablePacket(
2976 const QuicEncryptedPacket& packet) {
2977 QUIC_DVLOG(1) << ENDPOINT << "Queueing undecryptable packet.";
2978 undecryptable_packets_.push_back(packet.Clone());
2979}
2980
2981void QuicConnection::MaybeProcessUndecryptablePackets() {
2982 process_undecryptable_packets_alarm_->Cancel();
2983
QUICHE team6987b4a2019-03-15 16:23:04 -07002984 if (undecryptable_packets_.empty() ||
2985 encryption_level_ == ENCRYPTION_INITIAL) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002986 return;
2987 }
2988
2989 while (connected_ && !undecryptable_packets_.empty()) {
2990 // Making sure there is no pending frames when processing next undecrypted
2991 // packet because the queued ack frame may change.
2992 packet_generator_.FlushAllQueuedFrames();
2993 if (!connected_) {
2994 return;
2995 }
2996 QUIC_DVLOG(1) << ENDPOINT << "Attempting to process undecryptable packet";
2997 QuicEncryptedPacket* packet = undecryptable_packets_.front().get();
2998 if (!framer_.ProcessPacket(*packet) &&
2999 framer_.error() == QUIC_DECRYPTION_FAILURE) {
3000 QUIC_DVLOG(1) << ENDPOINT << "Unable to process undecryptable packet...";
3001 break;
3002 }
3003 QUIC_DVLOG(1) << ENDPOINT << "Processed undecryptable packet!";
3004 ++stats_.packets_processed;
3005 undecryptable_packets_.pop_front();
3006 }
3007
3008 // Once forward secure encryption is in use, there will be no
3009 // new keys installed and hence any undecryptable packets will
3010 // never be able to be decrypted.
3011 if (encryption_level_ == ENCRYPTION_FORWARD_SECURE) {
3012 if (debug_visitor_ != nullptr) {
3013 // TODO(rtenneti): perhaps more efficient to pass the number of
3014 // undecryptable packets as the argument to OnUndecryptablePacket so that
3015 // we just need to call OnUndecryptablePacket once?
3016 for (size_t i = 0; i < undecryptable_packets_.size(); ++i) {
3017 debug_visitor_->OnUndecryptablePacket();
3018 }
3019 }
3020 undecryptable_packets_.clear();
3021 }
3022}
3023
3024void QuicConnection::QueueCoalescedPacket(const QuicEncryptedPacket& packet) {
3025 QUIC_DVLOG(1) << ENDPOINT << "Queueing coalesced packet.";
3026 coalesced_packets_.push_back(packet.Clone());
3027}
3028
3029void QuicConnection::MaybeProcessCoalescedPackets() {
3030 bool processed = false;
3031 for (const auto& packet : coalesced_packets_) {
3032 if (!connected_) {
3033 return;
3034 }
3035
3036 // }
3037 // while (connected_ && !coalesced_packets_.empty()) {
3038 QUIC_DVLOG(1) << ENDPOINT << "Processing coalesced packet";
3039 // QuicEncryptedPacket* packet = coalesced_packets_.front().get();
3040 if (framer_.ProcessPacket(*packet)) {
3041 processed = true;
3042 } else {
3043 // If we are unable to decrypt this packet, it might be
3044 // because the CHLO or SHLO packet was lost.
3045 if (framer_.error() == QUIC_DECRYPTION_FAILURE) {
3046 if (encryption_level_ != ENCRYPTION_FORWARD_SECURE &&
3047 undecryptable_packets_.size() < max_undecryptable_packets_) {
3048 QueueUndecryptablePacket(*packet);
3049 } else if (debug_visitor_ != nullptr) {
3050 debug_visitor_->OnUndecryptablePacket();
3051 }
3052 }
3053 }
3054 // coalesced_packets_.pop_front();
3055 }
3056 coalesced_packets_.clear();
3057 if (processed) {
3058 MaybeProcessUndecryptablePackets();
3059 }
3060}
3061
3062void QuicConnection::CloseConnection(
3063 QuicErrorCode error,
vasilvvc48c8712019-03-11 13:38:16 -07003064 const std::string& error_details,
QUICHE teama6ef0a62019-03-07 20:34:33 -05003065 ConnectionCloseBehavior connection_close_behavior) {
3066 DCHECK(!error_details.empty());
3067 if (!connected_) {
3068 QUIC_DLOG(INFO) << "Connection is already closed.";
3069 return;
3070 }
3071
3072 QUIC_DLOG(INFO) << ENDPOINT << "Closing connection: " << connection_id()
3073 << ", with error: " << QuicErrorCodeToString(error) << " ("
3074 << error << "), and details: " << error_details;
3075
ianswettdc1e7ab2019-05-03 16:10:44 -07003076 if (connection_close_behavior != ConnectionCloseBehavior::SILENT_CLOSE) {
3077 SendConnectionClosePacket(error, error_details);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003078 }
3079
3080 ConnectionCloseSource source = ConnectionCloseSource::FROM_SELF;
3081 if (perspective_ == Perspective::IS_CLIENT &&
3082 error == QUIC_CRYPTO_HANDSHAKE_STATELESS_REJECT) {
3083 // Regard stateless rejected connection as closed by server.
3084 source = ConnectionCloseSource::FROM_PEER;
3085 }
3086 TearDownLocalConnectionState(error, error_details, source);
3087}
3088
3089void QuicConnection::SendConnectionClosePacket(QuicErrorCode error,
ianswettdc1e7ab2019-05-03 16:10:44 -07003090 const std::string& details) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05003091 QUIC_DLOG(INFO) << ENDPOINT << "Sending connection close packet.";
QUICHE team2252b702019-05-14 23:55:14 -04003092 SetDefaultEncryptionLevel(GetConnectionCloseEncryptionLevel());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003093 ClearQueuedPackets();
ianswettdc1e7ab2019-05-03 16:10:44 -07003094 // If there was a packet write error, write the smallest close possible.
3095 AckBundling ack_mode = (error == QUIC_PACKET_WRITE_ERROR) ? NO_ACK : SEND_ACK;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003096 ScopedPacketFlusher flusher(this, ack_mode);
QUICHE teamcd098022019-03-22 18:49:55 -07003097 // When multiple packet number spaces is supported, an ACK frame will be
3098 // bundled when connection is not write blocked.
3099 if (!SupportsMultiplePacketNumberSpaces() &&
3100 packet_generator_.deprecate_ack_bundling_mode() && ack_mode == SEND_ACK &&
QUICHE teama6ef0a62019-03-07 20:34:33 -05003101 !GetUpdatedAckFrame().ack_frame->packets.Empty()) {
3102 SendAck();
3103 }
fkastenholze9d71a82019-04-09 05:12:13 -07003104 QuicConnectionCloseFrame* frame =
3105 new QuicConnectionCloseFrame(error, details);
fkastenholz04bd4f32019-04-16 12:24:38 -07003106 // If version99/IETF QUIC set the close type. Default close type is Google
3107 // QUIC.
fkastenholz72f509b2019-04-10 09:17:49 -07003108 if (transport_version() == QUIC_VERSION_99) {
3109 frame->close_type = IETF_QUIC_TRANSPORT_CONNECTION_CLOSE;
3110 }
fayang3203f252019-05-03 06:00:03 -07003111 packet_generator_.ConsumeRetransmittableControlFrame(QuicFrame(frame));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003112 packet_generator_.FlushAllQueuedFrames();
3113}
3114
3115void QuicConnection::TearDownLocalConnectionState(
3116 QuicErrorCode error,
vasilvvc48c8712019-03-11 13:38:16 -07003117 const std::string& error_details,
QUICHE teama6ef0a62019-03-07 20:34:33 -05003118 ConnectionCloseSource source) {
3119 if (!connected_) {
3120 QUIC_DLOG(INFO) << "Connection is already closed.";
3121 return;
3122 }
3123
3124 // If we are using a batch writer, flush packets queued in it, if any.
3125 FlushPackets();
3126 connected_ = false;
3127 DCHECK(visitor_ != nullptr);
3128 visitor_->OnConnectionClosed(error, error_details, source);
3129 if (debug_visitor_ != nullptr) {
3130 debug_visitor_->OnConnectionClosed(error, error_details, source);
3131 }
3132 // Cancel the alarms so they don't trigger any action now that the
3133 // connection is closed.
3134 CancelAllAlarms();
3135}
3136
3137void QuicConnection::CancelAllAlarms() {
3138 QUIC_DVLOG(1) << "Cancelling all QuicConnection alarms.";
3139
3140 ack_alarm_->Cancel();
3141 ping_alarm_->Cancel();
3142 retransmission_alarm_->Cancel();
3143 send_alarm_->Cancel();
3144 timeout_alarm_->Cancel();
3145 mtu_discovery_alarm_->Cancel();
3146 path_degrading_alarm_->Cancel();
renjietang11e4a3d2019-05-03 11:27:26 -07003147 process_undecryptable_packets_alarm_->Cancel();
QUICHE teama6ef0a62019-03-07 20:34:33 -05003148}
3149
3150QuicByteCount QuicConnection::max_packet_length() const {
3151 return packet_generator_.GetCurrentMaxPacketLength();
3152}
3153
3154void QuicConnection::SetMaxPacketLength(QuicByteCount length) {
3155 long_term_mtu_ = length;
3156 packet_generator_.SetMaxPacketLength(GetLimitedMaxPacketSize(length));
3157}
3158
3159bool QuicConnection::HasQueuedData() const {
3160 return pending_version_negotiation_packet_ || !queued_packets_.empty() ||
3161 packet_generator_.HasQueuedFrames();
3162}
3163
3164void QuicConnection::EnableSavingCryptoPackets() {
3165 save_crypto_packets_as_termination_packets_ = true;
3166}
3167
3168bool QuicConnection::CanWriteStreamData() {
3169 // Don't write stream data if there are negotiation or queued data packets
3170 // to send. Otherwise, continue and bundle as many frames as possible.
3171 if (pending_version_negotiation_packet_ || !queued_packets_.empty()) {
3172 return false;
3173 }
3174
3175 IsHandshake pending_handshake =
3176 visitor_->HasPendingHandshake() ? IS_HANDSHAKE : NOT_HANDSHAKE;
3177 // Sending queued packets may have caused the socket to become write blocked,
3178 // or the congestion manager to prohibit sending. If we've sent everything
3179 // we had queued and we're still not blocked, let the visitor know it can
3180 // write more.
3181 return ShouldGeneratePacket(HAS_RETRANSMITTABLE_DATA, pending_handshake);
3182}
3183
3184void QuicConnection::SetNetworkTimeouts(QuicTime::Delta handshake_timeout,
3185 QuicTime::Delta idle_timeout) {
3186 QUIC_BUG_IF(idle_timeout > handshake_timeout)
3187 << "idle_timeout:" << idle_timeout.ToMilliseconds()
3188 << " handshake_timeout:" << handshake_timeout.ToMilliseconds();
3189 // Adjust the idle timeout on client and server to prevent clients from
3190 // sending requests to servers which have already closed the connection.
3191 if (perspective_ == Perspective::IS_SERVER) {
3192 idle_timeout = idle_timeout + QuicTime::Delta::FromSeconds(3);
3193 } else if (idle_timeout > QuicTime::Delta::FromSeconds(1)) {
3194 idle_timeout = idle_timeout - QuicTime::Delta::FromSeconds(1);
3195 }
3196 handshake_timeout_ = handshake_timeout;
3197 idle_network_timeout_ = idle_timeout;
3198
3199 SetTimeoutAlarm();
3200}
3201
3202void QuicConnection::CheckForTimeout() {
3203 QuicTime now = clock_->ApproximateNow();
3204 QuicTime time_of_last_packet =
3205 std::max(time_of_last_received_packet_,
3206 time_of_first_packet_sent_after_receiving_);
3207
3208 // |delta| can be < 0 as |now| is approximate time but |time_of_last_packet|
3209 // is accurate time. However, this should not change the behavior of
3210 // timeout handling.
3211 QuicTime::Delta idle_duration = now - time_of_last_packet;
3212 QUIC_DVLOG(1) << ENDPOINT << "last packet "
3213 << time_of_last_packet.ToDebuggingValue()
3214 << " now:" << now.ToDebuggingValue()
3215 << " idle_duration:" << idle_duration.ToMicroseconds()
3216 << " idle_network_timeout: "
3217 << idle_network_timeout_.ToMicroseconds();
3218 if (idle_duration >= idle_network_timeout_) {
vasilvvc48c8712019-03-11 13:38:16 -07003219 const std::string error_details = "No recent network activity.";
QUICHE teama6ef0a62019-03-07 20:34:33 -05003220 QUIC_DVLOG(1) << ENDPOINT << error_details;
3221 if ((sent_packet_manager_.GetConsecutiveTlpCount() > 0 ||
3222 sent_packet_manager_.GetConsecutiveRtoCount() > 0 ||
3223 visitor_->ShouldKeepConnectionAlive())) {
3224 CloseConnection(QUIC_NETWORK_IDLE_TIMEOUT, error_details,
3225 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
3226 } else {
3227 CloseConnection(QUIC_NETWORK_IDLE_TIMEOUT, error_details,
3228 idle_timeout_connection_close_behavior_);
3229 }
3230 return;
3231 }
3232
3233 if (!handshake_timeout_.IsInfinite()) {
3234 QuicTime::Delta connected_duration = now - stats_.connection_creation_time;
3235 QUIC_DVLOG(1) << ENDPOINT
3236 << "connection time: " << connected_duration.ToMicroseconds()
3237 << " handshake timeout: "
3238 << handshake_timeout_.ToMicroseconds();
3239 if (connected_duration >= handshake_timeout_) {
vasilvvc48c8712019-03-11 13:38:16 -07003240 const std::string error_details = "Handshake timeout expired.";
QUICHE teama6ef0a62019-03-07 20:34:33 -05003241 QUIC_DVLOG(1) << ENDPOINT << error_details;
3242 CloseConnection(QUIC_HANDSHAKE_TIMEOUT, error_details,
3243 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
3244 return;
3245 }
3246 }
3247
3248 SetTimeoutAlarm();
3249}
3250
3251void QuicConnection::SetTimeoutAlarm() {
3252 QuicTime time_of_last_packet =
3253 std::max(time_of_last_received_packet_,
3254 time_of_first_packet_sent_after_receiving_);
3255
3256 QuicTime deadline = time_of_last_packet + idle_network_timeout_;
3257 if (!handshake_timeout_.IsInfinite()) {
3258 deadline = std::min(deadline,
3259 stats_.connection_creation_time + handshake_timeout_);
3260 }
3261
3262 timeout_alarm_->Update(deadline, QuicTime::Delta::Zero());
3263}
3264
3265void QuicConnection::SetPingAlarm() {
3266 if (perspective_ == Perspective::IS_SERVER) {
ianswettb7f7cd22019-05-01 08:04:16 -07003267 // Only clients send pings to avoid NATs from timing out.
QUICHE teama6ef0a62019-03-07 20:34:33 -05003268 return;
3269 }
3270 if (!visitor_->ShouldKeepConnectionAlive()) {
3271 ping_alarm_->Cancel();
ianswettb7f7cd22019-05-01 08:04:16 -07003272 // Don't send a ping unless the application (ie: HTTP/3) says to, usually
3273 // because it is expecting a response from the server.
QUICHE teama6ef0a62019-03-07 20:34:33 -05003274 return;
3275 }
3276 if (retransmittable_on_wire_timeout_.IsInfinite() ||
3277 sent_packet_manager_.HasInFlightPackets()) {
3278 // Extend the ping alarm.
3279 ping_alarm_->Update(clock_->ApproximateNow() + ping_timeout_,
3280 QuicTime::Delta::FromSeconds(1));
3281 return;
3282 }
3283 DCHECK_LT(retransmittable_on_wire_timeout_, ping_timeout_);
3284 // If it's already set to an earlier time, then don't update it.
3285 if (ping_alarm_->IsSet() &&
3286 ping_alarm_->deadline() <
3287 clock_->ApproximateNow() + retransmittable_on_wire_timeout_) {
3288 return;
3289 }
3290 // Use a shorter timeout if there are open streams, but nothing on the wire.
3291 ping_alarm_->Update(
3292 clock_->ApproximateNow() + retransmittable_on_wire_timeout_,
3293 QuicTime::Delta::FromMilliseconds(1));
3294}
3295
3296void QuicConnection::SetRetransmissionAlarm() {
3297 if (packet_generator_.PacketFlusherAttached()) {
3298 pending_retransmission_alarm_ = true;
3299 return;
3300 }
3301 QuicTime retransmission_time = sent_packet_manager_.GetRetransmissionTime();
3302 retransmission_alarm_->Update(retransmission_time,
3303 QuicTime::Delta::FromMilliseconds(1));
3304}
3305
3306void QuicConnection::SetPathDegradingAlarm() {
3307 if (perspective_ == Perspective::IS_SERVER) {
3308 return;
3309 }
3310 const QuicTime::Delta delay = sent_packet_manager_.GetPathDegradingDelay();
3311 path_degrading_alarm_->Update(clock_->ApproximateNow() + delay,
3312 QuicTime::Delta::FromMilliseconds(1));
3313}
3314
3315void QuicConnection::MaybeSetMtuAlarm(QuicPacketNumber sent_packet_number) {
3316 // Do not set the alarm if the target size is less than the current size.
3317 // This covers the case when |mtu_discovery_target_| is at its default value,
3318 // zero.
3319 if (mtu_discovery_target_ <= max_packet_length()) {
3320 return;
3321 }
3322
3323 if (mtu_probe_count_ >= kMtuDiscoveryAttempts) {
3324 return;
3325 }
3326
3327 if (mtu_discovery_alarm_->IsSet()) {
3328 return;
3329 }
3330
3331 if (sent_packet_number >= next_mtu_probe_at_) {
3332 // Use an alarm to send the MTU probe to ensure that no ScopedPacketFlushers
3333 // are active.
3334 mtu_discovery_alarm_->Set(clock_->ApproximateNow());
3335 }
3336}
3337
3338void QuicConnection::MaybeSetAckAlarmTo(QuicTime time) {
3339 DCHECK(packet_generator_.deprecate_ack_bundling_mode());
3340 if (!ack_alarm_->IsSet() || ack_alarm_->deadline() > time) {
3341 ack_alarm_->Update(time, QuicTime::Delta::Zero());
3342 }
3343}
3344
3345QuicConnection::ScopedPacketFlusher::ScopedPacketFlusher(
3346 QuicConnection* connection,
3347 AckBundling ack_mode)
3348 : connection_(connection),
3349 flush_and_set_pending_retransmission_alarm_on_delete_(false) {
3350 if (connection_ == nullptr) {
3351 return;
3352 }
3353
3354 if (!connection_->packet_generator_.PacketFlusherAttached()) {
3355 flush_and_set_pending_retransmission_alarm_on_delete_ = true;
3356 connection->packet_generator_.AttachPacketFlusher();
3357 }
3358 if (connection_->packet_generator_.deprecate_ack_bundling_mode()) {
3359 return;
3360 }
3361
3362 // If caller wants us to include an ack, check the delayed-ack timer to see if
3363 // there's ack info to be sent.
3364 if (ShouldSendAck(ack_mode)) {
3365 if (!connection_->GetUpdatedAckFrame().ack_frame->packets.Empty()) {
3366 QUIC_DVLOG(1) << "Bundling ack with outgoing packet.";
3367 connection_->SendAck();
3368 }
3369 }
3370}
3371
3372bool QuicConnection::ScopedPacketFlusher::ShouldSendAck(
3373 AckBundling ack_mode) const {
3374 DCHECK(!connection_->packet_generator_.deprecate_ack_bundling_mode());
3375 // If the ack alarm is set, make sure the ack has been updated.
3376 DCHECK(!connection_->ack_alarm_->IsSet() || connection_->ack_frame_updated())
3377 << "ack_mode:" << ack_mode;
3378 switch (ack_mode) {
3379 case SEND_ACK:
3380 return true;
3381 case SEND_ACK_IF_QUEUED:
3382 return connection_->ack_queued();
3383 case SEND_ACK_IF_PENDING:
3384 return connection_->ack_alarm_->IsSet() ||
3385 connection_->stop_waiting_count_ > 1;
3386 case NO_ACK:
3387 return false;
3388 default:
3389 QUIC_BUG << "Unsupported ack_mode.";
3390 return true;
3391 }
3392}
3393
3394QuicConnection::ScopedPacketFlusher::~ScopedPacketFlusher() {
3395 if (connection_ == nullptr) {
3396 return;
3397 }
3398
3399 if (flush_and_set_pending_retransmission_alarm_on_delete_) {
3400 if (connection_->packet_generator_.deprecate_ack_bundling_mode()) {
3401 if (connection_->received_packet_manager_.decide_when_to_send_acks()) {
3402 const QuicTime ack_timeout =
QUICHE teamb23daa72019-03-21 08:37:48 -07003403 connection_->use_uber_received_packet_manager_
QUICHE teamcd098022019-03-22 18:49:55 -07003404 ? connection_->uber_received_packet_manager_
3405 .GetEarliestAckTimeout()
QUICHE teamb23daa72019-03-21 08:37:48 -07003406 : connection_->received_packet_manager_.ack_timeout();
QUICHE teama6ef0a62019-03-07 20:34:33 -05003407 if (ack_timeout.IsInitialized()) {
3408 if (ack_timeout <= connection_->clock_->ApproximateNow() &&
3409 !connection_->CanWrite(NO_RETRANSMITTABLE_DATA)) {
3410 // Cancel ACK alarm if connection is write blocked, and ACK will be
3411 // sent when connection gets unblocked.
3412 connection_->ack_alarm_->Cancel();
3413 } else {
3414 connection_->MaybeSetAckAlarmTo(ack_timeout);
3415 }
3416 }
3417 }
3418 if (connection_->ack_alarm_->IsSet() &&
3419 connection_->ack_alarm_->deadline() <=
3420 connection_->clock_->ApproximateNow()) {
3421 // An ACK needs to be sent right now. This ACK did not get bundled
3422 // because either there was no data to write or packets were marked as
3423 // received after frames were queued in the generator.
3424 if (connection_->send_alarm_->IsSet() &&
3425 connection_->send_alarm_->deadline() <=
3426 connection_->clock_->ApproximateNow()) {
3427 // If send alarm will go off soon, let send alarm send the ACK.
3428 connection_->ack_alarm_->Cancel();
3429 if (!connection_->received_packet_manager_
3430 .decide_when_to_send_acks()) {
3431 connection_->send_ack_when_on_can_write_ = true;
3432 }
QUICHE teamcd098022019-03-22 18:49:55 -07003433 } else if (connection_->SupportsMultiplePacketNumberSpaces()) {
3434 connection_->SendAllPendingAcks();
QUICHE teama6ef0a62019-03-07 20:34:33 -05003435 } else {
3436 connection_->SendAck();
3437 }
3438 }
3439 }
3440 connection_->packet_generator_.Flush();
3441 connection_->FlushPackets();
3442 if (connection_->session_decides_what_to_write()) {
3443 // Reset transmission type.
3444 connection_->SetTransmissionType(NOT_RETRANSMISSION);
3445 }
3446
3447 // Once all transmissions are done, check if there is any outstanding data
3448 // to send and notify the congestion controller if not.
3449 //
3450 // Note that this means that the application limited check will happen as
3451 // soon as the last flusher gets destroyed, which is typically after a
3452 // single stream write is finished. This means that if all the data from a
3453 // single write goes through the connection, the application-limited signal
3454 // will fire even if the caller does a write operation immediately after.
3455 // There are two important approaches to remedy this situation:
3456 // (1) Instantiate ScopedPacketFlusher before performing multiple subsequent
3457 // writes, thus deferring this check until all writes are done.
3458 // (2) Write data in chunks sufficiently large so that they cause the
3459 // connection to be limited by the congestion control. Typically, this
3460 // would mean writing chunks larger than the product of the current
3461 // pacing rate and the pacer granularity. So, for instance, if the
3462 // pacing rate of the connection is 1 Gbps, and the pacer granularity is
3463 // 1 ms, the caller should send at least 125k bytes in order to not
3464 // be marked as application-limited.
3465 connection_->CheckIfApplicationLimited();
3466
3467 if (connection_->pending_retransmission_alarm_) {
3468 connection_->SetRetransmissionAlarm();
3469 connection_->pending_retransmission_alarm_ = false;
3470 }
3471 }
3472 DCHECK_EQ(flush_and_set_pending_retransmission_alarm_on_delete_,
3473 !connection_->packet_generator_.PacketFlusherAttached());
3474}
3475
3476HasRetransmittableData QuicConnection::IsRetransmittable(
3477 const SerializedPacket& packet) {
3478 // Retransmitted packets retransmittable frames are owned by the unacked
3479 // packet map, but are not present in the serialized packet.
3480 if (packet.transmission_type != NOT_RETRANSMISSION ||
3481 !packet.retransmittable_frames.empty()) {
3482 return HAS_RETRANSMITTABLE_DATA;
3483 } else {
3484 return NO_RETRANSMITTABLE_DATA;
3485 }
3486}
3487
3488bool QuicConnection::IsTerminationPacket(const SerializedPacket& packet) {
3489 if (packet.retransmittable_frames.empty()) {
3490 return false;
3491 }
3492 for (const QuicFrame& frame : packet.retransmittable_frames) {
3493 if (frame.type == CONNECTION_CLOSE_FRAME) {
3494 return true;
3495 }
3496 if (save_crypto_packets_as_termination_packets_ &&
3497 QuicUtils::IsHandshakeFrame(frame, transport_version())) {
3498 return true;
3499 }
3500 }
3501 return false;
3502}
3503
3504void QuicConnection::SetMtuDiscoveryTarget(QuicByteCount target) {
3505 mtu_discovery_target_ = GetLimitedMaxPacketSize(target);
3506}
3507
3508QuicByteCount QuicConnection::GetLimitedMaxPacketSize(
3509 QuicByteCount suggested_max_packet_size) {
3510 if (!peer_address_.IsInitialized()) {
3511 QUIC_BUG << "Attempted to use a connection without a valid peer address";
3512 return suggested_max_packet_size;
3513 }
3514
3515 const QuicByteCount writer_limit = writer_->GetMaxPacketSize(peer_address());
3516
3517 QuicByteCount max_packet_size = suggested_max_packet_size;
3518 if (max_packet_size > writer_limit) {
3519 max_packet_size = writer_limit;
3520 }
dschinazi66dea072019-04-09 11:41:06 -07003521 if (max_packet_size > kMaxOutgoingPacketSize) {
3522 max_packet_size = kMaxOutgoingPacketSize;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003523 }
3524 return max_packet_size;
3525}
3526
3527void QuicConnection::SendMtuDiscoveryPacket(QuicByteCount target_mtu) {
3528 // Currently, this limit is ensured by the caller.
3529 DCHECK_EQ(target_mtu, GetLimitedMaxPacketSize(target_mtu));
3530
3531 // Send the probe.
3532 packet_generator_.GenerateMtuDiscoveryPacket(target_mtu);
3533}
3534
3535// TODO(zhongyi): change this method to generate a connectivity probing packet
3536// and let the caller to call writer to write the packet and handle write
3537// status.
3538bool QuicConnection::SendConnectivityProbingPacket(
3539 QuicPacketWriter* probing_writer,
3540 const QuicSocketAddress& peer_address) {
3541 return SendGenericPathProbePacket(probing_writer, peer_address,
3542 /* is_response= */ false);
3543}
3544
3545void QuicConnection::SendConnectivityProbingResponsePacket(
3546 const QuicSocketAddress& peer_address) {
3547 SendGenericPathProbePacket(nullptr, peer_address,
3548 /* is_response= */ true);
3549}
3550
3551bool QuicConnection::SendGenericPathProbePacket(
3552 QuicPacketWriter* probing_writer,
3553 const QuicSocketAddress& peer_address,
3554 bool is_response) {
3555 DCHECK(peer_address.IsInitialized());
3556 if (!connected_) {
3557 QUIC_BUG << "Not sending connectivity probing packet as connection is "
3558 << "disconnected.";
3559 return false;
3560 }
3561 if (perspective_ == Perspective::IS_SERVER && probing_writer == nullptr) {
3562 // Server can use default packet writer to write packet.
3563 probing_writer = writer_;
3564 }
3565 DCHECK(probing_writer);
3566
3567 if (probing_writer->IsWriteBlocked()) {
3568 QUIC_DLOG(INFO)
3569 << ENDPOINT
3570 << "Writer blocked when sending connectivity probing packet.";
3571 if (probing_writer == writer_) {
3572 // Visitor should not be write blocked if the probing writer is not the
3573 // default packet writer.
3574 visitor_->OnWriteBlocked();
3575 }
3576 return true;
3577 }
3578
3579 QUIC_DLOG(INFO) << ENDPOINT
3580 << "Sending path probe packet for connection_id = "
3581 << connection_id_;
3582
3583 OwningSerializedPacketPointer probing_packet;
3584 if (transport_version() != QUIC_VERSION_99) {
3585 // Non-IETF QUIC, generate a padded ping regardless of whether this is a
3586 // request or a response.
3587 probing_packet = packet_generator_.SerializeConnectivityProbingPacket();
3588 } else {
3589 if (is_response) {
3590 // Respond using IETF QUIC PATH_RESPONSE frame
3591 if (IsCurrentPacketConnectivityProbing()) {
3592 // Pad the response if the request was a google connectivity probe
3593 // (padded).
3594 probing_packet =
3595 packet_generator_.SerializePathResponseConnectivityProbingPacket(
3596 received_path_challenge_payloads_, /* is_padded = */ true);
3597 received_path_challenge_payloads_.clear();
3598 } else {
3599 // Do not pad the response if the path challenge was not a google
3600 // connectivity probe.
3601 probing_packet =
3602 packet_generator_.SerializePathResponseConnectivityProbingPacket(
3603 received_path_challenge_payloads_,
3604 /* is_padded = */ false);
3605 received_path_challenge_payloads_.clear();
3606 }
3607 } else {
3608 // Request using IETF QUIC PATH_CHALLENGE frame
3609 transmitted_connectivity_probe_payload_ =
3610 QuicMakeUnique<QuicPathFrameBuffer>();
3611 probing_packet =
3612 packet_generator_.SerializePathChallengeConnectivityProbingPacket(
3613 transmitted_connectivity_probe_payload_.get());
3614 if (!probing_packet) {
3615 transmitted_connectivity_probe_payload_ = nullptr;
3616 }
3617 }
3618 }
3619
3620 DCHECK_EQ(IsRetransmittable(*probing_packet), NO_RETRANSMITTABLE_DATA);
3621
3622 const QuicTime packet_send_time = clock_->Now();
3623 WriteResult result = probing_writer->WritePacket(
3624 probing_packet->encrypted_buffer, probing_packet->encrypted_length,
3625 self_address().host(), peer_address, per_packet_options_);
3626
3627 // If using a batch writer and the probing packet is buffered, flush it.
3628 if (probing_writer->IsBatchMode() && result.status == WRITE_STATUS_OK &&
3629 result.bytes_written == 0) {
3630 result = probing_writer->Flush();
3631 }
3632
3633 if (IsWriteError(result.status)) {
3634 // Write error for any connectivity probe should not affect the connection
3635 // as it is sent on a different path.
3636 QUIC_DLOG(INFO) << ENDPOINT << "Write probing packet failed with error = "
3637 << result.error_code;
3638 return false;
3639 }
3640
3641 if (debug_visitor_ != nullptr) {
3642 debug_visitor_->OnPacketSent(
3643 *probing_packet, probing_packet->original_packet_number,
3644 probing_packet->transmission_type, packet_send_time);
3645 }
3646
3647 // Call OnPacketSent regardless of the write result.
3648 sent_packet_manager_.OnPacketSent(
3649 probing_packet.get(), probing_packet->original_packet_number,
3650 packet_send_time, probing_packet->transmission_type,
3651 NO_RETRANSMITTABLE_DATA);
3652
3653 if (IsWriteBlockedStatus(result.status)) {
3654 if (probing_writer == writer_) {
3655 // Visitor should not be write blocked if the probing writer is not the
3656 // default packet writer.
3657 visitor_->OnWriteBlocked();
3658 }
3659 if (result.status == WRITE_STATUS_BLOCKED_DATA_BUFFERED) {
3660 QUIC_DLOG(INFO) << ENDPOINT << "Write probing packet blocked";
3661 }
3662 }
3663
3664 return true;
3665}
3666
3667void QuicConnection::DiscoverMtu() {
3668 DCHECK(!mtu_discovery_alarm_->IsSet());
3669
3670 // Check if the MTU has been already increased.
3671 if (mtu_discovery_target_ <= max_packet_length()) {
3672 return;
3673 }
3674
3675 // Calculate the packet number of the next probe *before* sending the current
3676 // one. Otherwise, when SendMtuDiscoveryPacket() is called,
3677 // MaybeSetMtuAlarm() will not realize that the probe has been just sent, and
3678 // will reschedule this probe again.
3679 packets_between_mtu_probes_ *= 2;
3680 next_mtu_probe_at_ = sent_packet_manager_.GetLargestSentPacket() +
3681 packets_between_mtu_probes_ + 1;
3682 ++mtu_probe_count_;
3683
3684 QUIC_DVLOG(2) << "Sending a path MTU discovery packet #" << mtu_probe_count_;
3685 SendMtuDiscoveryPacket(mtu_discovery_target_);
3686
3687 DCHECK(!mtu_discovery_alarm_->IsSet());
3688}
3689
3690void QuicConnection::OnEffectivePeerMigrationValidated() {
3691 if (active_effective_peer_migration_type_ == NO_CHANGE) {
3692 QUIC_BUG << "No migration underway.";
3693 return;
3694 }
3695 highest_packet_sent_before_effective_peer_migration_.Clear();
3696 active_effective_peer_migration_type_ = NO_CHANGE;
3697}
3698
3699void QuicConnection::StartEffectivePeerMigration(AddressChangeType type) {
3700 // TODO(fayang): Currently, all peer address change type are allowed. Need to
3701 // add a method ShouldAllowPeerAddressChange(PeerAddressChangeType type) to
3702 // determine whether |type| is allowed.
3703 if (type == NO_CHANGE) {
3704 QUIC_BUG << "EffectivePeerMigration started without address change.";
3705 return;
3706 }
3707 QUIC_DLOG(INFO) << ENDPOINT << "Effective peer's ip:port changed from "
3708 << effective_peer_address_.ToString() << " to "
3709 << GetEffectivePeerAddressFromCurrentPacket().ToString()
3710 << ", address change type is " << type
3711 << ", migrating connection.";
3712
3713 highest_packet_sent_before_effective_peer_migration_ =
3714 sent_packet_manager_.GetLargestSentPacket();
3715 effective_peer_address_ = GetEffectivePeerAddressFromCurrentPacket();
3716 active_effective_peer_migration_type_ = type;
3717
3718 // TODO(wub): Move these calls to OnEffectivePeerMigrationValidated.
3719 OnConnectionMigration(type);
3720}
3721
3722void QuicConnection::OnConnectionMigration(AddressChangeType addr_change_type) {
3723 visitor_->OnConnectionMigration(addr_change_type);
3724 sent_packet_manager_.OnConnectionMigration(addr_change_type);
3725}
3726
3727bool QuicConnection::IsCurrentPacketConnectivityProbing() const {
3728 return is_current_packet_connectivity_probing_;
3729}
3730
3731bool QuicConnection::ack_frame_updated() const {
QUICHE teamb23daa72019-03-21 08:37:48 -07003732 if (use_uber_received_packet_manager_) {
QUICHE team1dfa46b2019-03-22 10:39:10 -07003733 return uber_received_packet_manager_.IsAckFrameUpdated();
QUICHE teamb23daa72019-03-21 08:37:48 -07003734 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05003735 return received_packet_manager_.ack_frame_updated();
3736}
3737
3738QuicStringPiece QuicConnection::GetCurrentPacket() {
3739 if (current_packet_data_ == nullptr) {
3740 return QuicStringPiece();
3741 }
3742 return QuicStringPiece(current_packet_data_, last_size_);
3743}
3744
3745bool QuicConnection::MaybeConsiderAsMemoryCorruption(
3746 const QuicStreamFrame& frame) {
3747 if (frame.stream_id == QuicUtils::GetCryptoStreamId(transport_version()) ||
QUICHE team6987b4a2019-03-15 16:23:04 -07003748 last_decrypted_packet_level_ != ENCRYPTION_INITIAL) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05003749 return false;
3750 }
3751
3752 if (perspective_ == Perspective::IS_SERVER &&
3753 frame.data_length >= sizeof(kCHLO) &&
3754 strncmp(frame.data_buffer, reinterpret_cast<const char*>(&kCHLO),
3755 sizeof(kCHLO)) == 0) {
3756 return true;
3757 }
3758
3759 if (perspective_ == Perspective::IS_CLIENT &&
3760 frame.data_length >= sizeof(kREJ) &&
3761 strncmp(frame.data_buffer, reinterpret_cast<const char*>(&kREJ),
3762 sizeof(kREJ)) == 0) {
3763 return true;
3764 }
3765
3766 return false;
3767}
3768
3769void QuicConnection::MaybeSendProbingRetransmissions() {
3770 DCHECK(fill_up_link_during_probing_);
3771
3772 // Don't send probing retransmissions until the handshake has completed.
3773 if (!sent_packet_manager_.handshake_confirmed() ||
3774 sent_packet_manager().HasUnackedCryptoPackets()) {
3775 return;
3776 }
3777
3778 if (probing_retransmission_pending_) {
3779 QUIC_BUG << "MaybeSendProbingRetransmissions is called while another call "
3780 "to it is already in progress";
3781 return;
3782 }
3783
3784 probing_retransmission_pending_ = true;
3785 SendProbingRetransmissions();
3786 probing_retransmission_pending_ = false;
3787}
3788
3789void QuicConnection::CheckIfApplicationLimited() {
3790 if (session_decides_what_to_write() && probing_retransmission_pending_) {
3791 return;
3792 }
3793
3794 bool application_limited =
3795 queued_packets_.empty() &&
3796 !sent_packet_manager_.HasPendingRetransmissions() &&
3797 !visitor_->WillingAndAbleToWrite();
3798
3799 if (!application_limited) {
3800 return;
3801 }
3802
3803 if (fill_up_link_during_probing_) {
3804 MaybeSendProbingRetransmissions();
3805 if (!CanWrite(HAS_RETRANSMITTABLE_DATA)) {
3806 return;
3807 }
3808 }
3809
3810 sent_packet_manager_.OnApplicationLimited();
3811}
3812
3813void QuicConnection::UpdatePacketContent(PacketContent type) {
3814 if (current_packet_content_ == NOT_PADDED_PING) {
3815 // We have already learned the current packet is not a connectivity
3816 // probing packet. Peer migration should have already been started earlier
3817 // if needed.
3818 return;
3819 }
3820
3821 if (type == NO_FRAMES_RECEIVED) {
3822 return;
3823 }
3824
3825 if (type == FIRST_FRAME_IS_PING) {
3826 if (current_packet_content_ == NO_FRAMES_RECEIVED) {
3827 current_packet_content_ = FIRST_FRAME_IS_PING;
3828 return;
3829 }
3830 }
3831
3832 // In Google QUIC we look for a packet with just a PING and PADDING.
3833 // For IETF QUIC, the packet must consist of just a PATH_CHALLENGE frame,
3834 // followed by PADDING. If the condition is met, mark things as
3835 // connectivity-probing, causing later processing to generate the correct
3836 // response.
3837 if (type == SECOND_FRAME_IS_PADDING &&
3838 current_packet_content_ == FIRST_FRAME_IS_PING) {
3839 current_packet_content_ = SECOND_FRAME_IS_PADDING;
3840 if (perspective_ == Perspective::IS_SERVER) {
3841 is_current_packet_connectivity_probing_ =
3842 current_effective_peer_migration_type_ != NO_CHANGE;
3843 } else {
3844 is_current_packet_connectivity_probing_ =
3845 (last_packet_source_address_ != peer_address_) ||
3846 (last_packet_destination_address_ != self_address_);
3847 }
3848 return;
3849 }
3850
3851 current_packet_content_ = NOT_PADDED_PING;
QUICHE team1f3de242019-03-20 07:24:48 -07003852 if (GetLargestReceivedPacket().IsInitialized() &&
3853 last_header_.packet_number == GetLargestReceivedPacket()) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05003854 direct_peer_address_ = last_packet_source_address_;
3855 if (current_effective_peer_migration_type_ != NO_CHANGE) {
3856 // Start effective peer migration immediately when the current packet is
3857 // confirmed not a connectivity probing packet.
QUICHE team1f3de242019-03-20 07:24:48 -07003858 // TODO(fayang): When multiple packet number spaces is supported, only
3859 // start peer migration for the application data.
QUICHE teama6ef0a62019-03-07 20:34:33 -05003860 StartEffectivePeerMigration(current_effective_peer_migration_type_);
3861 }
3862 }
3863 current_effective_peer_migration_type_ = NO_CHANGE;
3864}
3865
3866void QuicConnection::MaybeEnableSessionDecidesWhatToWrite() {
3867 // Only enable session decides what to write code path for version 42+,
3868 // because it needs the receiver to allow receiving overlapping stream data.
3869 const bool enable_session_decides_what_to_write =
3870 transport_version() > QUIC_VERSION_39;
3871 sent_packet_manager_.SetSessionDecideWhatToWrite(
3872 enable_session_decides_what_to_write);
3873 packet_generator_.SetCanSetTransmissionType(
3874 enable_session_decides_what_to_write);
3875}
3876
3877void QuicConnection::PostProcessAfterAckFrame(bool send_stop_waiting,
3878 bool acked_new_packet) {
3879 if (no_stop_waiting_frames_) {
QUICHE teamb23daa72019-03-21 08:37:48 -07003880 if (use_uber_received_packet_manager_) {
3881 uber_received_packet_manager_.DontWaitForPacketsBefore(
QUICHE team1dfa46b2019-03-22 10:39:10 -07003882 last_decrypted_packet_level_,
QUICHE teamb23daa72019-03-21 08:37:48 -07003883 sent_packet_manager_.largest_packet_peer_knows_is_acked());
3884 } else {
3885 received_packet_manager_.DontWaitForPacketsBefore(
3886 sent_packet_manager_.largest_packet_peer_knows_is_acked());
3887 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05003888 }
3889 // Always reset the retransmission alarm when an ack comes in, since we now
3890 // have a better estimate of the current rtt than when it was set.
3891 SetRetransmissionAlarm();
3892 MaybeSetPathDegradingAlarm(acked_new_packet);
3893
3894 // TODO(ianswett): Only increment stop_waiting_count_ if StopWaiting frames
3895 // are sent.
3896 if (send_stop_waiting) {
3897 ++stop_waiting_count_;
3898 } else {
3899 stop_waiting_count_ = 0;
3900 }
3901}
3902
3903void QuicConnection::MaybeSetPathDegradingAlarm(bool acked_new_packet) {
3904 if (!sent_packet_manager_.HasInFlightPackets()) {
3905 // There are no retransmittable packets on the wire, so it's impossible to
3906 // say if the connection has degraded.
3907 path_degrading_alarm_->Cancel();
3908 } else if (acked_new_packet) {
3909 // A previously-unacked packet has been acked, which means forward progress
3910 // has been made. Unset |is_path_degrading| if the path was considered as
3911 // degrading previously. Set/update the path degrading alarm.
3912 is_path_degrading_ = false;
3913 SetPathDegradingAlarm();
3914 }
3915}
3916
3917void QuicConnection::SetSessionNotifier(
3918 SessionNotifierInterface* session_notifier) {
3919 sent_packet_manager_.SetSessionNotifier(session_notifier);
3920}
3921
3922void QuicConnection::SetDataProducer(
3923 QuicStreamFrameDataProducer* data_producer) {
3924 framer_.set_data_producer(data_producer);
3925}
3926
3927void QuicConnection::SetTransmissionType(TransmissionType type) {
3928 packet_generator_.SetTransmissionType(type);
3929}
3930
3931bool QuicConnection::session_decides_what_to_write() const {
3932 return sent_packet_manager_.session_decides_what_to_write();
3933}
3934
3935void QuicConnection::UpdateReleaseTimeIntoFuture() {
3936 DCHECK(supports_release_time_);
3937
3938 release_time_into_future_ = std::max(
3939 QuicTime::Delta::FromMilliseconds(kMinReleaseTimeIntoFutureMs),
3940 std::min(
3941 QuicTime::Delta::FromMilliseconds(
3942 GetQuicFlag(FLAGS_quic_max_pace_time_into_future_ms)),
3943 sent_packet_manager_.GetRttStats()->SmoothedOrInitialRtt() *
3944 GetQuicFlag(FLAGS_quic_pace_time_into_future_srtt_fraction)));
3945}
3946
3947void QuicConnection::ResetAckStates() {
3948 ack_alarm_->Cancel();
3949 ack_queued_ = false;
3950 stop_waiting_count_ = 0;
3951 num_retransmittable_packets_received_since_last_ack_sent_ = 0;
3952 num_packets_received_since_last_ack_sent_ = 0;
3953 if (received_packet_manager_.decide_when_to_send_acks()) {
QUICHE teamb23daa72019-03-21 08:37:48 -07003954 if (use_uber_received_packet_manager_) {
QUICHE team1dfa46b2019-03-22 10:39:10 -07003955 uber_received_packet_manager_.ResetAckStates(encryption_level_);
QUICHE teamb23daa72019-03-21 08:37:48 -07003956 } else {
3957 received_packet_manager_.ResetAckStates();
3958 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05003959 }
3960}
3961
3962MessageStatus QuicConnection::SendMessage(QuicMessageId message_id,
3963 QuicMemSliceSpan message) {
3964 if (transport_version() <= QUIC_VERSION_44) {
3965 QUIC_BUG << "MESSAGE frame is not supported for version "
3966 << transport_version();
3967 return MESSAGE_STATUS_UNSUPPORTED;
3968 }
ianswettb239f862019-04-05 09:15:06 -07003969 if (message.total_length() > GetCurrentLargestMessagePayload()) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05003970 return MESSAGE_STATUS_TOO_LARGE;
3971 }
3972 if (!CanWrite(HAS_RETRANSMITTABLE_DATA)) {
3973 return MESSAGE_STATUS_BLOCKED;
3974 }
3975 ScopedPacketFlusher flusher(this, SEND_ACK_IF_PENDING);
3976 return packet_generator_.AddMessageFrame(message_id, message);
3977}
3978
ianswettb239f862019-04-05 09:15:06 -07003979QuicPacketLength QuicConnection::GetCurrentLargestMessagePayload() const {
3980 return packet_generator_.GetCurrentLargestMessagePayload();
3981}
3982
3983QuicPacketLength QuicConnection::GetGuaranteedLargestMessagePayload() const {
3984 return packet_generator_.GetGuaranteedLargestMessagePayload();
QUICHE teama6ef0a62019-03-07 20:34:33 -05003985}
3986
zhongyi546cc452019-04-12 15:27:49 -07003987uint32_t QuicConnection::cipher_id() const {
3988 if (version().KnowsWhichDecrypterToUse()) {
3989 return framer_.GetDecrypter(last_decrypted_packet_level_)->cipher_id();
3990 }
3991 return framer_.decrypter()->cipher_id();
3992}
3993
QUICHE teama6ef0a62019-03-07 20:34:33 -05003994bool QuicConnection::ShouldSetAckAlarm() const {
3995 DCHECK(ack_frame_updated());
3996 if (ack_alarm_->IsSet()) {
3997 // ACK alarm has been set.
3998 return false;
3999 }
4000 if (GetQuicReloadableFlag(quic_fix_spurious_ack_alarm) &&
4001 packet_generator_.should_send_ack()) {
4002 // If the generator is already configured to send an ACK, then there is no
4003 // need to schedule the ACK alarm. The updated ACK information will be sent
4004 // when the generator flushes.
4005 QUIC_RELOADABLE_FLAG_COUNT(quic_fix_spurious_ack_alarm);
4006 return false;
4007 }
4008 return true;
4009}
4010
4011EncryptionLevel QuicConnection::GetConnectionCloseEncryptionLevel() const {
QUICHE teama6ef0a62019-03-07 20:34:33 -05004012 if (perspective_ == Perspective::IS_CLIENT) {
4013 return encryption_level_;
4014 }
4015 if (sent_packet_manager_.handshake_confirmed()) {
4016 // A forward secure packet has been received.
4017 QUIC_BUG_IF(encryption_level_ != ENCRYPTION_FORWARD_SECURE);
4018 return ENCRYPTION_FORWARD_SECURE;
4019 }
4020 if (framer_.HasEncrypterOfEncryptionLevel(ENCRYPTION_ZERO_RTT)) {
4021 if (encryption_level_ != ENCRYPTION_ZERO_RTT) {
4022 if (transport_version() > QUIC_VERSION_43) {
4023 QUIC_CODE_COUNT(quic_wrong_encryption_level_connection_close_ietf);
4024 } else {
4025 QUIC_CODE_COUNT(quic_wrong_encryption_level_connection_close);
4026 }
4027 }
4028 return ENCRYPTION_ZERO_RTT;
4029 }
QUICHE team6987b4a2019-03-15 16:23:04 -07004030 return ENCRYPTION_INITIAL;
QUICHE teama6ef0a62019-03-07 20:34:33 -05004031}
4032
QUICHE teamcd098022019-03-22 18:49:55 -07004033void QuicConnection::SendAllPendingAcks() {
4034 DCHECK(SupportsMultiplePacketNumberSpaces());
4035 QUIC_DVLOG(1) << ENDPOINT << "Trying to send all pending ACKs";
4036 // Latches current encryption level.
4037 const EncryptionLevel current_encryption_level = encryption_level_;
4038 for (int8_t i = INITIAL_DATA; i <= APPLICATION_DATA; ++i) {
4039 const QuicTime ack_timeout = uber_received_packet_manager_.GetAckTimeout(
4040 static_cast<PacketNumberSpace>(i));
4041 if (!ack_timeout.IsInitialized() ||
4042 ack_timeout > clock_->ApproximateNow()) {
4043 continue;
4044 }
dschinazi05e62b12019-04-18 15:43:41 -07004045 if (!framer_.HasEncrypterOfEncryptionLevel(
4046 QuicUtils::GetEncryptionLevel(static_cast<PacketNumberSpace>(i)))) {
4047 QUIC_BUG << ENDPOINT << "Cannot send ACKs for packet number space "
4048 << static_cast<uint32_t>(i)
4049 << " without corresponding encrypter";
4050 continue;
4051 }
QUICHE teamcd098022019-03-22 18:49:55 -07004052 QUIC_DVLOG(1) << ENDPOINT << "Sending ACK of packet number space: "
4053 << static_cast<uint32_t>(i);
4054 // Switch to the appropriate encryption level.
4055 SetDefaultEncryptionLevel(
4056 QuicUtils::GetEncryptionLevel(static_cast<PacketNumberSpace>(i)));
4057 QuicFrames frames;
4058 frames.push_back(uber_received_packet_manager_.GetUpdatedAckFrame(
4059 static_cast<PacketNumberSpace>(i), clock_->ApproximateNow()));
4060 const bool flushed = packet_generator_.FlushAckFrame(frames);
4061 if (!flushed) {
4062 // Connection is write blocked.
QUICHE teamdb061532019-03-23 18:23:05 -07004063 QUIC_BUG_IF(!writer_->IsWriteBlocked())
4064 << "Writer not blocked, but ACK not flushed for packet space:" << i;
QUICHE teamcd098022019-03-22 18:49:55 -07004065 break;
4066 }
4067 ResetAckStates();
4068 }
4069 // Restores encryption level.
4070 SetDefaultEncryptionLevel(current_encryption_level);
4071
4072 const QuicTime timeout =
4073 uber_received_packet_manager_.GetEarliestAckTimeout();
4074 if (timeout.IsInitialized()) {
4075 // If there are ACKs pending, re-arm ack alarm.
4076 ack_alarm_->Set(timeout);
4077 }
4078 // Only try to bundle retransmittable data with ACK frame if default
4079 // encryption level is forward secure.
4080 if (encryption_level_ != ENCRYPTION_FORWARD_SECURE ||
4081 consecutive_num_packets_with_no_retransmittable_frames_ <
4082 max_consecutive_num_packets_with_no_retransmittable_frames_) {
4083 return;
4084 }
4085 consecutive_num_packets_with_no_retransmittable_frames_ = 0;
4086 if (packet_generator_.HasRetransmittableFrames() ||
4087 visitor_->WillingAndAbleToWrite()) {
4088 // There are pending retransmittable frames.
4089 return;
4090 }
4091
4092 visitor_->OnAckNeedsRetransmittableFrame();
4093}
4094
4095void QuicConnection::MaybeEnableMultiplePacketNumberSpacesSupport() {
4096 const bool enable_multiple_packet_number_spaces =
4097 version().handshake_protocol == PROTOCOL_TLS1_3 &&
4098 use_uber_received_packet_manager_ &&
4099 sent_packet_manager_.use_uber_loss_algorithm() &&
4100 GetQuicRestartFlag(quic_enable_accept_random_ipn);
4101 if (!enable_multiple_packet_number_spaces) {
4102 return;
4103 }
4104 QUIC_DVLOG(1) << ENDPOINT << "connection " << connection_id()
4105 << " supports multiple packet number spaces";
4106 framer_.EnableMultiplePacketNumberSpacesSupport();
4107 sent_packet_manager_.EnableMultiplePacketNumberSpacesSupport();
4108 uber_received_packet_manager_.EnableMultiplePacketNumberSpacesSupport();
4109}
4110
4111bool QuicConnection::SupportsMultiplePacketNumberSpaces() const {
4112 return sent_packet_manager_.supports_multiple_packet_number_spaces();
4113}
4114
QUICHE team76e1c622019-03-19 14:36:39 -07004115void QuicConnection::SetLargestReceivedPacketWithAck(
4116 QuicPacketNumber new_value) {
QUICHE teamcd098022019-03-22 18:49:55 -07004117 if (SupportsMultiplePacketNumberSpaces()) {
4118 largest_seen_packets_with_ack_[QuicUtils::GetPacketNumberSpace(
4119 last_decrypted_packet_level_)] = new_value;
4120 } else {
4121 largest_seen_packet_with_ack_ = new_value;
4122 }
QUICHE team76e1c622019-03-19 14:36:39 -07004123}
4124
4125QuicPacketNumber QuicConnection::GetLargestReceivedPacketWithAck() const {
QUICHE teamcd098022019-03-22 18:49:55 -07004126 if (SupportsMultiplePacketNumberSpaces()) {
4127 return largest_seen_packets_with_ack_[QuicUtils::GetPacketNumberSpace(
4128 last_decrypted_packet_level_)];
4129 }
QUICHE team76e1c622019-03-19 14:36:39 -07004130 return largest_seen_packet_with_ack_;
4131}
4132
4133QuicPacketNumber QuicConnection::GetLargestSentPacket() const {
QUICHE teamcd098022019-03-22 18:49:55 -07004134 if (SupportsMultiplePacketNumberSpaces()) {
4135 return sent_packet_manager_.GetLargestSentPacket(
4136 last_decrypted_packet_level_);
4137 }
QUICHE team76e1c622019-03-19 14:36:39 -07004138 return sent_packet_manager_.GetLargestSentPacket();
4139}
4140
4141QuicPacketNumber QuicConnection::GetLargestAckedPacket() const {
QUICHE teamcd098022019-03-22 18:49:55 -07004142 if (SupportsMultiplePacketNumberSpaces()) {
4143 return sent_packet_manager_.GetLargestAckedPacket(
4144 last_decrypted_packet_level_);
4145 }
QUICHE team76e1c622019-03-19 14:36:39 -07004146 return sent_packet_manager_.GetLargestObserved();
4147}
4148
QUICHE team1f3de242019-03-20 07:24:48 -07004149QuicPacketNumber QuicConnection::GetLargestReceivedPacket() const {
QUICHE teamb23daa72019-03-21 08:37:48 -07004150 if (use_uber_received_packet_manager_) {
QUICHE team1dfa46b2019-03-22 10:39:10 -07004151 return uber_received_packet_manager_.GetLargestObserved(
4152 last_decrypted_packet_level_);
QUICHE teamb23daa72019-03-21 08:37:48 -07004153 }
QUICHE team1f3de242019-03-20 07:24:48 -07004154 return received_packet_manager_.GetLargestObserved();
4155}
4156
QUICHE teama6ef0a62019-03-07 20:34:33 -05004157size_t QuicConnection::min_received_before_ack_decimation() const {
4158 if (received_packet_manager_.decide_when_to_send_acks()) {
QUICHE teamb23daa72019-03-21 08:37:48 -07004159 if (use_uber_received_packet_manager_) {
4160 return uber_received_packet_manager_.min_received_before_ack_decimation();
4161 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004162 return received_packet_manager_.min_received_before_ack_decimation();
4163 }
4164 return min_received_before_ack_decimation_;
4165}
4166
4167void QuicConnection::set_min_received_before_ack_decimation(size_t new_value) {
4168 if (received_packet_manager_.decide_when_to_send_acks()) {
QUICHE teamb23daa72019-03-21 08:37:48 -07004169 if (use_uber_received_packet_manager_) {
4170 uber_received_packet_manager_.set_min_received_before_ack_decimation(
4171 new_value);
4172 } else {
4173 received_packet_manager_.set_min_received_before_ack_decimation(
4174 new_value);
4175 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004176 } else {
4177 min_received_before_ack_decimation_ = new_value;
4178 }
4179}
4180
4181size_t QuicConnection::ack_frequency_before_ack_decimation() const {
4182 if (received_packet_manager_.decide_when_to_send_acks()) {
QUICHE teamb23daa72019-03-21 08:37:48 -07004183 if (use_uber_received_packet_manager_) {
4184 return uber_received_packet_manager_
4185 .ack_frequency_before_ack_decimation();
4186 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004187 return received_packet_manager_.ack_frequency_before_ack_decimation();
4188 }
4189 return ack_frequency_before_ack_decimation_;
4190}
4191
4192void QuicConnection::set_ack_frequency_before_ack_decimation(size_t new_value) {
4193 DCHECK_GT(new_value, 0u);
4194 if (received_packet_manager_.decide_when_to_send_acks()) {
QUICHE teamb23daa72019-03-21 08:37:48 -07004195 if (use_uber_received_packet_manager_) {
4196 uber_received_packet_manager_.set_ack_frequency_before_ack_decimation(
4197 new_value);
4198 } else {
4199 received_packet_manager_.set_ack_frequency_before_ack_decimation(
4200 new_value);
4201 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004202 } else {
4203 ack_frequency_before_ack_decimation_ = new_value;
4204 }
4205}
4206
4207#undef ENDPOINT // undef for jumbo builds
4208} // namespace quic