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