blob: cf72fec12c95e48365b5f4abc5a904b3ee59ebc7 [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"
19#include "net/third_party/quiche/src/quic/core/crypto/quic_decrypter.h"
20#include "net/third_party/quiche/src/quic/core/crypto/quic_encrypter.h"
21#include "net/third_party/quiche/src/quic/core/proto/cached_network_parameters.pb.h"
22#include "net/third_party/quiche/src/quic/core/quic_bandwidth.h"
23#include "net/third_party/quiche/src/quic/core/quic_config.h"
24#include "net/third_party/quiche/src/quic/core/quic_packet_generator.h"
25#include "net/third_party/quiche/src/quic/core/quic_pending_retransmission.h"
26#include "net/third_party/quiche/src/quic/core/quic_types.h"
27#include "net/third_party/quiche/src/quic/core/quic_utils.h"
28#include "net/third_party/quiche/src/quic/platform/api/quic_bug_tracker.h"
29#include "net/third_party/quiche/src/quic/platform/api/quic_client_stats.h"
30#include "net/third_party/quiche/src/quic/platform/api/quic_error_code_wrappers.h"
31#include "net/third_party/quiche/src/quic/platform/api/quic_exported_stats.h"
32#include "net/third_party/quiche/src/quic/platform/api/quic_flag_utils.h"
33#include "net/third_party/quiche/src/quic/platform/api/quic_flags.h"
34#include "net/third_party/quiche/src/quic/platform/api/quic_logging.h"
35#include "net/third_party/quiche/src/quic/platform/api/quic_map_util.h"
36#include "net/third_party/quiche/src/quic/platform/api/quic_str_cat.h"
QUICHE teama6ef0a62019-03-07 20:34:33 -050037#include "net/third_party/quiche/src/quic/platform/api/quic_string_utils.h"
38#include "net/third_party/quiche/src/quic/platform/api/quic_text_utils.h"
39
40namespace quic {
41
42class QuicDecrypter;
43class QuicEncrypter;
44
45namespace {
46
47// Maximum number of consecutive sent nonretransmittable packets.
48const QuicPacketCount kMaxConsecutiveNonRetransmittablePackets = 19;
49
50// Maximum number of retransmittable packets received before sending an ack.
51const QuicPacketCount kDefaultRetransmittablePacketsBeforeAck = 2;
52// Minimum number of packets received before ack decimation is enabled.
53// This intends to avoid the beginning of slow start, when CWNDs may be
54// rapidly increasing.
55const QuicPacketCount kMinReceivedBeforeAckDecimation = 100;
56// Wait for up to 10 retransmittable packets before sending an ack.
57const QuicPacketCount kMaxRetransmittablePacketsBeforeAck = 10;
58// One quarter RTT delay when doing ack decimation.
59const float kAckDecimationDelay = 0.25;
60// One eighth RTT delay when doing ack decimation.
61const float kShortAckDecimationDelay = 0.125;
62
63// The minimum release time into future in ms.
64const int kMinReleaseTimeIntoFutureMs = 1;
65
66bool Near(QuicPacketNumber a, QuicPacketNumber b) {
67 QuicPacketCount delta = (a > b) ? a - b : b - a;
68 return delta <= kMaxPacketGap;
69}
70
71// An alarm that is scheduled to send an ack if a timeout occurs.
72class AckAlarmDelegate : public QuicAlarm::Delegate {
73 public:
74 explicit AckAlarmDelegate(QuicConnection* connection)
75 : connection_(connection) {}
76 AckAlarmDelegate(const AckAlarmDelegate&) = delete;
77 AckAlarmDelegate& operator=(const AckAlarmDelegate&) = delete;
78
79 void OnAlarm() override {
80 DCHECK(connection_->ack_frame_updated());
81 QuicConnection::ScopedPacketFlusher flusher(connection_,
82 QuicConnection::SEND_ACK);
83 if (connection_->packet_generator().deprecate_ack_bundling_mode()) {
84 DCHECK(!connection_->GetUpdatedAckFrame().ack_frame->packets.Empty());
85 connection_->SendAck();
86 }
87 }
88
89 private:
90 QuicConnection* connection_;
91};
92
93// This alarm will be scheduled any time a data-bearing packet is sent out.
94// When the alarm goes off, the connection checks to see if the oldest packets
95// have been acked, and retransmit them if they have not.
96class RetransmissionAlarmDelegate : public QuicAlarm::Delegate {
97 public:
98 explicit RetransmissionAlarmDelegate(QuicConnection* connection)
99 : connection_(connection) {}
100 RetransmissionAlarmDelegate(const RetransmissionAlarmDelegate&) = delete;
101 RetransmissionAlarmDelegate& operator=(const RetransmissionAlarmDelegate&) =
102 delete;
103
104 void OnAlarm() override { connection_->OnRetransmissionTimeout(); }
105
106 private:
107 QuicConnection* connection_;
108};
109
110// An alarm that is scheduled when the SentPacketManager requires a delay
111// before sending packets and fires when the packet may be sent.
112class SendAlarmDelegate : public QuicAlarm::Delegate {
113 public:
114 explicit SendAlarmDelegate(QuicConnection* connection)
115 : connection_(connection) {}
116 SendAlarmDelegate(const SendAlarmDelegate&) = delete;
117 SendAlarmDelegate& operator=(const SendAlarmDelegate&) = delete;
118
119 void OnAlarm() override { connection_->WriteAndBundleAcksIfNotBlocked(); }
120
121 private:
122 QuicConnection* connection_;
123};
124
125class PathDegradingAlarmDelegate : public QuicAlarm::Delegate {
126 public:
127 explicit PathDegradingAlarmDelegate(QuicConnection* connection)
128 : connection_(connection) {}
129 PathDegradingAlarmDelegate(const PathDegradingAlarmDelegate&) = delete;
130 PathDegradingAlarmDelegate& operator=(const PathDegradingAlarmDelegate&) =
131 delete;
132
133 void OnAlarm() override { connection_->OnPathDegradingTimeout(); }
134
135 private:
136 QuicConnection* connection_;
137};
138
139class TimeoutAlarmDelegate : public QuicAlarm::Delegate {
140 public:
141 explicit TimeoutAlarmDelegate(QuicConnection* connection)
142 : connection_(connection) {}
143 TimeoutAlarmDelegate(const TimeoutAlarmDelegate&) = delete;
144 TimeoutAlarmDelegate& operator=(const TimeoutAlarmDelegate&) = delete;
145
146 void OnAlarm() override { connection_->CheckForTimeout(); }
147
148 private:
149 QuicConnection* connection_;
150};
151
152class PingAlarmDelegate : public QuicAlarm::Delegate {
153 public:
154 explicit PingAlarmDelegate(QuicConnection* connection)
155 : connection_(connection) {}
156 PingAlarmDelegate(const PingAlarmDelegate&) = delete;
157 PingAlarmDelegate& operator=(const PingAlarmDelegate&) = delete;
158
159 void OnAlarm() override { connection_->OnPingTimeout(); }
160
161 private:
162 QuicConnection* connection_;
163};
164
165class MtuDiscoveryAlarmDelegate : public QuicAlarm::Delegate {
166 public:
167 explicit MtuDiscoveryAlarmDelegate(QuicConnection* connection)
168 : connection_(connection) {}
169 MtuDiscoveryAlarmDelegate(const MtuDiscoveryAlarmDelegate&) = delete;
170 MtuDiscoveryAlarmDelegate& operator=(const MtuDiscoveryAlarmDelegate&) =
171 delete;
172
173 void OnAlarm() override { connection_->DiscoverMtu(); }
174
175 private:
176 QuicConnection* connection_;
177};
178
179class RetransmittableOnWireAlarmDelegate : public QuicAlarm::Delegate {
180 public:
181 explicit RetransmittableOnWireAlarmDelegate(QuicConnection* connection)
182 : connection_(connection) {}
183 RetransmittableOnWireAlarmDelegate(
184 const RetransmittableOnWireAlarmDelegate&) = delete;
185 RetransmittableOnWireAlarmDelegate& operator=(
186 const RetransmittableOnWireAlarmDelegate&) = delete;
187
188 void OnAlarm() override { connection_->OnPingTimeout(); }
189
190 private:
191 QuicConnection* connection_;
192};
193
194class ProcessUndecryptablePacketsAlarmDelegate : public QuicAlarm::Delegate {
195 public:
196 explicit ProcessUndecryptablePacketsAlarmDelegate(QuicConnection* connection)
197 : connection_(connection) {}
198 ProcessUndecryptablePacketsAlarmDelegate(
199 const ProcessUndecryptablePacketsAlarmDelegate&) = delete;
200 ProcessUndecryptablePacketsAlarmDelegate& operator=(
201 const ProcessUndecryptablePacketsAlarmDelegate&) = delete;
202
203 void OnAlarm() override { connection_->MaybeProcessUndecryptablePackets(); }
204
205 private:
206 QuicConnection* connection_;
207};
208
209} // namespace
210
211#define ENDPOINT \
212 (perspective_ == Perspective::IS_SERVER ? "Server: " : "Client: ")
213
214QuicConnection::QuicConnection(
215 QuicConnectionId connection_id,
216 QuicSocketAddress initial_peer_address,
217 QuicConnectionHelperInterface* helper,
218 QuicAlarmFactory* alarm_factory,
219 QuicPacketWriter* writer,
220 bool owns_writer,
221 Perspective perspective,
222 const ParsedQuicVersionVector& supported_versions)
223 : framer_(supported_versions,
224 helper->GetClock()->ApproximateNow(),
225 perspective,
226 connection_id.length()),
227 current_packet_content_(NO_FRAMES_RECEIVED),
228 is_current_packet_connectivity_probing_(false),
229 current_effective_peer_migration_type_(NO_CHANGE),
230 helper_(helper),
231 alarm_factory_(alarm_factory),
232 per_packet_options_(nullptr),
233 writer_(writer),
234 owns_writer_(owns_writer),
QUICHE team6987b4a2019-03-15 16:23:04 -0700235 encryption_level_(ENCRYPTION_INITIAL),
QUICHE teama6ef0a62019-03-07 20:34:33 -0500236 clock_(helper->GetClock()),
237 random_generator_(helper->GetRandomGenerator()),
238 connection_id_(connection_id),
239 peer_address_(initial_peer_address),
240 direct_peer_address_(initial_peer_address),
241 active_effective_peer_migration_type_(NO_CHANGE),
242 last_packet_decrypted_(false),
243 last_size_(0),
244 current_packet_data_(nullptr),
QUICHE team6987b4a2019-03-15 16:23:04 -0700245 last_decrypted_packet_level_(ENCRYPTION_INITIAL),
QUICHE teama6ef0a62019-03-07 20:34:33 -0500246 should_last_packet_instigate_acks_(false),
247 was_last_packet_missing_(false),
248 max_undecryptable_packets_(0),
249 max_tracked_packets_(kMaxTrackedPackets),
250 pending_version_negotiation_packet_(false),
251 send_ietf_version_negotiation_packet_(false),
252 save_crypto_packets_as_termination_packets_(false),
253 idle_timeout_connection_close_behavior_(
254 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET),
255 close_connection_after_five_rtos_(false),
256 received_packet_manager_(&stats_),
257 ack_queued_(false),
258 num_retransmittable_packets_received_since_last_ack_sent_(0),
259 num_packets_received_since_last_ack_sent_(0),
260 stop_waiting_count_(0),
261 ack_mode_(GetQuicReloadableFlag(quic_enable_ack_decimation)
262 ? ACK_DECIMATION
263 : TCP_ACKING),
264 ack_decimation_delay_(kAckDecimationDelay),
265 unlimited_ack_decimation_(false),
266 fast_ack_after_quiescence_(false),
267 pending_retransmission_alarm_(false),
268 defer_send_in_response_to_packets_(false),
269 ping_timeout_(QuicTime::Delta::FromSeconds(kPingTimeoutSecs)),
270 retransmittable_on_wire_timeout_(QuicTime::Delta::Infinite()),
271 arena_(),
272 ack_alarm_(alarm_factory_->CreateAlarm(arena_.New<AckAlarmDelegate>(this),
273 &arena_)),
274 retransmission_alarm_(alarm_factory_->CreateAlarm(
275 arena_.New<RetransmissionAlarmDelegate>(this),
276 &arena_)),
277 send_alarm_(
278 alarm_factory_->CreateAlarm(arena_.New<SendAlarmDelegate>(this),
279 &arena_)),
280 timeout_alarm_(
281 alarm_factory_->CreateAlarm(arena_.New<TimeoutAlarmDelegate>(this),
282 &arena_)),
283 ping_alarm_(
284 alarm_factory_->CreateAlarm(arena_.New<PingAlarmDelegate>(this),
285 &arena_)),
286 mtu_discovery_alarm_(alarm_factory_->CreateAlarm(
287 arena_.New<MtuDiscoveryAlarmDelegate>(this),
288 &arena_)),
289 path_degrading_alarm_(alarm_factory_->CreateAlarm(
290 arena_.New<PathDegradingAlarmDelegate>(this),
291 &arena_)),
292 process_undecryptable_packets_alarm_(alarm_factory_->CreateAlarm(
293 arena_.New<ProcessUndecryptablePacketsAlarmDelegate>(this),
294 &arena_)),
295 visitor_(nullptr),
296 debug_visitor_(nullptr),
297 packet_generator_(connection_id_, &framer_, random_generator_, this),
298 idle_network_timeout_(QuicTime::Delta::Infinite()),
299 handshake_timeout_(QuicTime::Delta::Infinite()),
300 time_of_first_packet_sent_after_receiving_(
301 GetQuicReloadableFlag(
302 quic_fix_time_of_first_packet_sent_after_receiving)
303 ? QuicTime::Zero()
304 : clock_->ApproximateNow()),
305 time_of_last_received_packet_(clock_->ApproximateNow()),
306 time_of_previous_received_packet_(QuicTime::Zero()),
307 sent_packet_manager_(
308 perspective,
309 clock_,
310 &stats_,
311 GetQuicReloadableFlag(quic_default_to_bbr) ? kBBR : kCubicBytes,
312 kNack),
313 version_negotiation_state_(START_NEGOTIATION),
314 perspective_(perspective),
315 connected_(true),
316 can_truncate_connection_ids_(perspective == Perspective::IS_SERVER),
317 mtu_discovery_target_(0),
318 mtu_probe_count_(0),
319 packets_between_mtu_probes_(kPacketsBetweenMtuProbesBase),
320 next_mtu_probe_at_(kPacketsBetweenMtuProbesBase),
321 largest_received_packet_size_(0),
322 write_error_occurred_(false),
323 no_stop_waiting_frames_(transport_version() > QUIC_VERSION_43),
324 consecutive_num_packets_with_no_retransmittable_frames_(0),
325 max_consecutive_num_packets_with_no_retransmittable_frames_(
326 kMaxConsecutiveNonRetransmittablePackets),
327 min_received_before_ack_decimation_(kMinReceivedBeforeAckDecimation),
328 ack_frequency_before_ack_decimation_(
329 kDefaultRetransmittablePacketsBeforeAck),
330 fill_up_link_during_probing_(false),
331 probing_retransmission_pending_(false),
332 stateless_reset_token_received_(false),
333 received_stateless_reset_token_(0),
334 last_control_frame_id_(kInvalidControlFrameId),
335 is_path_degrading_(false),
336 processing_ack_frame_(false),
337 supports_release_time_(false),
338 release_time_into_future_(QuicTime::Delta::Zero()),
339 no_version_negotiation_(supported_versions.size() == 1),
340 fix_termination_packets_(
341 GetQuicReloadableFlag(quic_fix_termination_packets)),
342 send_ack_when_on_can_write_(false) {
343 if (ack_mode_ == ACK_DECIMATION) {
344 QUIC_RELOADABLE_FLAG_COUNT(quic_enable_ack_decimation);
345 }
346 if (perspective_ == Perspective::IS_SERVER &&
347 supported_versions.size() == 1) {
348 QUIC_RESTART_FLAG_COUNT(quic_no_server_conn_ver_negotiation2);
349 }
350 if (packet_generator_.deprecate_ack_bundling_mode()) {
351 QUIC_RELOADABLE_FLAG_COUNT(quic_deprecate_ack_bundling_mode);
352 }
353 if (received_packet_manager_.decide_when_to_send_acks()) {
354 QUIC_RELOADABLE_FLAG_COUNT(quic_rpm_decides_when_to_send_acks);
355 }
356 QUIC_DLOG(INFO) << ENDPOINT
357 << "Created connection with connection_id: " << connection_id
358 << " and version: "
359 << QuicVersionToString(transport_version());
360
361 QUIC_BUG_IF(!QuicUtils::IsConnectionIdValidForVersion(connection_id,
362 transport_version()))
363 << "QuicConnection: attempted to use connection ID " << connection_id
364 << " which is invalid with version "
365 << QuicVersionToString(transport_version());
366
367 framer_.set_visitor(this);
368 stats_.connection_creation_time = clock_->ApproximateNow();
369 // TODO(ianswett): Supply the NetworkChangeVisitor as a constructor argument
370 // and make it required non-null, because it's always used.
371 sent_packet_manager_.SetNetworkChangeVisitor(this);
372 if (GetQuicRestartFlag(quic_offload_pacing_to_usps2)) {
373 sent_packet_manager_.SetPacingAlarmGranularity(QuicTime::Delta::Zero());
374 release_time_into_future_ =
375 QuicTime::Delta::FromMilliseconds(kMinReleaseTimeIntoFutureMs);
376 }
377 // Allow the packet writer to potentially reduce the packet size to a value
378 // even smaller than kDefaultMaxPacketSize.
379 SetMaxPacketLength(perspective_ == Perspective::IS_SERVER
380 ? kDefaultServerMaxPacketSize
381 : kDefaultMaxPacketSize);
382 received_packet_manager_.set_max_ack_ranges(255);
383 MaybeEnableSessionDecidesWhatToWrite();
384 DCHECK(!GetQuicRestartFlag(quic_no_server_conn_ver_negotiation2) ||
385 perspective_ == Perspective::IS_CLIENT ||
386 supported_versions.size() == 1);
387}
388
389QuicConnection::~QuicConnection() {
390 if (owns_writer_) {
391 delete writer_;
392 }
393 ClearQueuedPackets();
394}
395
396void QuicConnection::ClearQueuedPackets() {
397 for (auto it = queued_packets_.begin(); it != queued_packets_.end(); ++it) {
398 // Delete the buffer before calling ClearSerializedPacket, which sets
399 // encrypted_buffer to nullptr.
400 delete[] it->encrypted_buffer;
401 ClearSerializedPacket(&(*it));
402 }
403 queued_packets_.clear();
404}
405
406void QuicConnection::SetFromConfig(const QuicConfig& config) {
407 if (config.negotiated()) {
408 // Handshake complete, set handshake timeout to Infinite.
409 SetNetworkTimeouts(QuicTime::Delta::Infinite(),
410 config.IdleNetworkTimeout());
411 if (config.SilentClose()) {
412 idle_timeout_connection_close_behavior_ =
413 ConnectionCloseBehavior::SILENT_CLOSE;
414 }
415 } else {
416 SetNetworkTimeouts(config.max_time_before_crypto_handshake(),
417 config.max_idle_time_before_crypto_handshake());
418 }
419
420 sent_packet_manager_.SetFromConfig(config);
421 if (config.HasReceivedBytesForConnectionId() &&
422 can_truncate_connection_ids_) {
423 packet_generator_.SetConnectionIdLength(
424 config.ReceivedBytesForConnectionId());
425 }
426 max_undecryptable_packets_ = config.max_undecryptable_packets();
427
428 if (config.HasClientSentConnectionOption(kMTUH, perspective_)) {
429 SetMtuDiscoveryTarget(kMtuDiscoveryTargetPacketSizeHigh);
430 }
431 if (config.HasClientSentConnectionOption(kMTUL, perspective_)) {
432 SetMtuDiscoveryTarget(kMtuDiscoveryTargetPacketSizeLow);
433 }
434 if (debug_visitor_ != nullptr) {
435 debug_visitor_->OnSetFromConfig(config);
436 }
437 if (received_packet_manager_.decide_when_to_send_acks()) {
438 received_packet_manager_.SetFromConfig(config, perspective_);
439 } else {
440 if (GetQuicReloadableFlag(quic_enable_ack_decimation) &&
441 config.HasClientSentConnectionOption(kACD0, perspective_)) {
442 ack_mode_ = TCP_ACKING;
443 }
444 if (config.HasClientSentConnectionOption(kACKD, perspective_)) {
445 ack_mode_ = ACK_DECIMATION;
446 }
447 if (config.HasClientSentConnectionOption(kAKD2, perspective_)) {
448 ack_mode_ = ACK_DECIMATION_WITH_REORDERING;
449 }
450 if (config.HasClientSentConnectionOption(kAKD3, perspective_)) {
451 ack_mode_ = ACK_DECIMATION;
452 ack_decimation_delay_ = kShortAckDecimationDelay;
453 }
454 if (config.HasClientSentConnectionOption(kAKD4, perspective_)) {
455 ack_mode_ = ACK_DECIMATION_WITH_REORDERING;
456 ack_decimation_delay_ = kShortAckDecimationDelay;
457 }
458 if (config.HasClientSentConnectionOption(kAKDU, perspective_)) {
459 unlimited_ack_decimation_ = true;
460 }
461 if (config.HasClientSentConnectionOption(kACKQ, perspective_)) {
462 fast_ack_after_quiescence_ = true;
463 }
464 }
465 if (config.HasClientSentConnectionOption(k5RTO, perspective_)) {
466 close_connection_after_five_rtos_ = true;
467 }
468 if (config.HasClientSentConnectionOption(kNSTP, perspective_)) {
469 no_stop_waiting_frames_ = true;
470 }
471 if (config.HasReceivedStatelessResetToken()) {
472 stateless_reset_token_received_ = true;
473 received_stateless_reset_token_ = config.ReceivedStatelessResetToken();
474 }
475 if (GetQuicReloadableFlag(quic_send_timestamps) &&
476 config.HasClientSentConnectionOption(kSTMP, perspective_)) {
477 QUIC_RELOADABLE_FLAG_COUNT(quic_send_timestamps);
478 framer_.set_process_timestamps(true);
479 received_packet_manager_.set_save_timestamps(true);
480 }
481
482 supports_release_time_ =
483 writer_ != nullptr && writer_->SupportsReleaseTime() &&
484 !config.HasClientSentConnectionOption(kNPCO, perspective_);
485
486 if (supports_release_time_) {
487 UpdateReleaseTimeIntoFuture();
488 }
489}
490
491void QuicConnection::OnSendConnectionState(
492 const CachedNetworkParameters& cached_network_params) {
493 if (debug_visitor_ != nullptr) {
494 debug_visitor_->OnSendConnectionState(cached_network_params);
495 }
496}
497
498void QuicConnection::OnReceiveConnectionState(
499 const CachedNetworkParameters& cached_network_params) {
500 if (debug_visitor_ != nullptr) {
501 debug_visitor_->OnReceiveConnectionState(cached_network_params);
502 }
503}
504
505void QuicConnection::ResumeConnectionState(
506 const CachedNetworkParameters& cached_network_params,
507 bool max_bandwidth_resumption) {
508 sent_packet_manager_.ResumeConnectionState(cached_network_params,
509 max_bandwidth_resumption);
510}
511
512void QuicConnection::SetMaxPacingRate(QuicBandwidth max_pacing_rate) {
513 sent_packet_manager_.SetMaxPacingRate(max_pacing_rate);
514}
515
516void QuicConnection::AdjustNetworkParameters(QuicBandwidth bandwidth,
517 QuicTime::Delta rtt) {
518 sent_packet_manager_.AdjustNetworkParameters(bandwidth, rtt);
519}
520
521QuicBandwidth QuicConnection::MaxPacingRate() const {
522 return sent_packet_manager_.MaxPacingRate();
523}
524
525bool QuicConnection::SelectMutualVersion(
526 const ParsedQuicVersionVector& available_versions) {
527 // Try to find the highest mutual version by iterating over supported
528 // versions, starting with the highest, and breaking out of the loop once we
529 // find a matching version in the provided available_versions vector.
530 const ParsedQuicVersionVector& supported_versions =
531 framer_.supported_versions();
532 for (size_t i = 0; i < supported_versions.size(); ++i) {
533 const ParsedQuicVersion& version = supported_versions[i];
534 if (QuicContainsValue(available_versions, version)) {
535 framer_.set_version(version);
536 return true;
537 }
538 }
539
540 return false;
541}
542
543void QuicConnection::OnError(QuicFramer* framer) {
544 // Packets that we can not or have not decrypted are dropped.
545 // TODO(rch): add stats to measure this.
546 if (!connected_ || last_packet_decrypted_ == false) {
547 return;
548 }
549 CloseConnection(framer->error(), framer->detailed_error(),
550 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
551}
552
553void QuicConnection::OnPacket() {
554 last_packet_decrypted_ = false;
555}
556
557void QuicConnection::OnPublicResetPacket(const QuicPublicResetPacket& packet) {
558 // Check that any public reset packet with a different connection ID that was
559 // routed to this QuicConnection has been redirected before control reaches
560 // here. (Check for a bug regression.)
561 DCHECK_EQ(connection_id_, packet.connection_id);
562 DCHECK_EQ(perspective_, Perspective::IS_CLIENT);
563 if (debug_visitor_ != nullptr) {
564 debug_visitor_->OnPublicResetPacket(packet);
565 }
vasilvvc48c8712019-03-11 13:38:16 -0700566 std::string error_details = "Received public reset.";
QUICHE teama6ef0a62019-03-07 20:34:33 -0500567 if (perspective_ == Perspective::IS_CLIENT && !packet.endpoint_id.empty()) {
568 QuicStrAppend(&error_details, " From ", packet.endpoint_id, ".");
569 }
570 QUIC_DLOG(INFO) << ENDPOINT << error_details;
571 QUIC_CODE_COUNT(quic_tear_down_local_connection_on_public_reset);
572 TearDownLocalConnectionState(QUIC_PUBLIC_RESET, error_details,
573 ConnectionCloseSource::FROM_PEER);
574}
575
576bool QuicConnection::OnProtocolVersionMismatch(
577 ParsedQuicVersion received_version,
578 PacketHeaderFormat form) {
579 QUIC_DLOG(INFO) << ENDPOINT << "Received packet with mismatched version "
580 << ParsedQuicVersionToString(received_version);
581 if (perspective_ == Perspective::IS_CLIENT) {
vasilvvc48c8712019-03-11 13:38:16 -0700582 const std::string error_details = "Protocol version mismatch.";
QUICHE teama6ef0a62019-03-07 20:34:33 -0500583 QUIC_BUG << ENDPOINT << error_details;
584 TearDownLocalConnectionState(QUIC_INTERNAL_ERROR, error_details,
585 ConnectionCloseSource::FROM_SELF);
586 return false;
587 }
588 if (no_version_negotiation_) {
589 // Drop old packets that were sent by the client before the version was
590 // negotiated.
591 return false;
592 }
593 DCHECK_NE(version(), received_version);
594
595 if (debug_visitor_ != nullptr) {
596 debug_visitor_->OnProtocolVersionMismatch(received_version);
597 }
598
599 switch (version_negotiation_state_) {
600 case START_NEGOTIATION:
601 if (!framer_.IsSupportedVersion(received_version)) {
602 SendVersionNegotiationPacket(form != GOOGLE_QUIC_PACKET);
603 version_negotiation_state_ = NEGOTIATION_IN_PROGRESS;
604 return false;
605 }
606 break;
607
608 case NEGOTIATION_IN_PROGRESS:
609 if (!framer_.IsSupportedVersion(received_version)) {
610 SendVersionNegotiationPacket(form != GOOGLE_QUIC_PACKET);
611 return false;
612 }
613 break;
614
615 case NEGOTIATED_VERSION:
616 // Might be old packets that were sent by the client before the version
617 // was negotiated. Drop these.
618 return false;
619
620 default:
621 DCHECK(false);
622 }
623
624 // Store the new version.
625 framer_.set_version(received_version);
626 framer_.InferPacketHeaderTypeFromVersion();
627
628 version_negotiation_state_ = NEGOTIATED_VERSION;
629 visitor_->OnSuccessfulVersionNegotiation(received_version);
630 if (debug_visitor_ != nullptr) {
631 debug_visitor_->OnSuccessfulVersionNegotiation(received_version);
632 }
633 QUIC_DLOG(INFO) << ENDPOINT << "version negotiated "
634 << ParsedQuicVersionToString(received_version);
635
636 MaybeEnableSessionDecidesWhatToWrite();
637 no_stop_waiting_frames_ =
638 received_version.transport_version > QUIC_VERSION_43;
639
640 // TODO(satyamshekhar): Store the packet number of this packet and close the
641 // connection if we ever received a packet with incorrect version and whose
642 // packet number is greater.
643 return true;
644}
645
646// Handles version negotiation for client connection.
647void QuicConnection::OnVersionNegotiationPacket(
648 const QuicVersionNegotiationPacket& packet) {
649 // Check that any public reset packet with a different connection ID that was
650 // routed to this QuicConnection has been redirected before control reaches
651 // here. (Check for a bug regression.)
652 DCHECK_EQ(connection_id_, packet.connection_id);
653 if (perspective_ == Perspective::IS_SERVER) {
vasilvvc48c8712019-03-11 13:38:16 -0700654 const std::string error_details =
QUICHE teama6ef0a62019-03-07 20:34:33 -0500655 "Server receieved version negotiation packet.";
656 QUIC_BUG << error_details;
657 QUIC_CODE_COUNT(quic_tear_down_local_connection_on_version_negotiation);
658 TearDownLocalConnectionState(QUIC_INTERNAL_ERROR, error_details,
659 ConnectionCloseSource::FROM_SELF);
660 return;
661 }
662 if (debug_visitor_ != nullptr) {
663 debug_visitor_->OnVersionNegotiationPacket(packet);
664 }
665
666 if (version_negotiation_state_ != START_NEGOTIATION) {
667 // Possibly a duplicate version negotiation packet.
668 return;
669 }
670
671 if (QuicContainsValue(packet.versions, version())) {
vasilvvc48c8712019-03-11 13:38:16 -0700672 const std::string error_details =
QUICHE teama6ef0a62019-03-07 20:34:33 -0500673 "Server already supports client's version and should have accepted the "
674 "connection.";
675 QUIC_DLOG(WARNING) << error_details;
676 TearDownLocalConnectionState(QUIC_INVALID_VERSION_NEGOTIATION_PACKET,
677 error_details,
678 ConnectionCloseSource::FROM_SELF);
679 return;
680 }
681
682 server_supported_versions_ = packet.versions;
683
684 if (GetQuicReloadableFlag(quic_no_client_conn_ver_negotiation)) {
685 QUIC_RELOADABLE_FLAG_COUNT(quic_no_client_conn_ver_negotiation);
686 CloseConnection(
687 QUIC_INVALID_VERSION,
688 QuicStrCat(
689 "Client may support one of the versions in the server's list, but "
690 "it's going to close the connection anyway. Supported versions: {",
691 ParsedQuicVersionVectorToString(framer_.supported_versions()),
692 "}, peer supported versions: {",
693 ParsedQuicVersionVectorToString(packet.versions), "}"),
694 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
695 return;
696 }
697
698 if (!SelectMutualVersion(packet.versions)) {
699 CloseConnection(
700 QUIC_INVALID_VERSION,
701 QuicStrCat(
702 "No common version found. Supported versions: {",
703 ParsedQuicVersionVectorToString(framer_.supported_versions()),
704 "}, peer supported versions: {",
705 ParsedQuicVersionVectorToString(packet.versions), "}"),
706 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
707 return;
708 }
709
710 QUIC_DLOG(INFO) << ENDPOINT << "Negotiated version: "
711 << QuicVersionToString(transport_version());
712 no_stop_waiting_frames_ = transport_version() > QUIC_VERSION_43;
713 version_negotiation_state_ = NEGOTIATION_IN_PROGRESS;
714 RetransmitUnackedPackets(ALL_UNACKED_RETRANSMISSION);
715}
716
717bool QuicConnection::OnUnauthenticatedPublicHeader(
718 const QuicPacketHeader& header) {
719 if (header.destination_connection_id == connection_id_) {
720 return true;
721 }
722
723 ++stats_.packets_dropped;
724 QUIC_DLOG(INFO) << ENDPOINT
725 << "Ignoring packet from unexpected ConnectionId: "
726 << header.destination_connection_id << " instead of "
727 << connection_id_;
728 if (debug_visitor_ != nullptr) {
729 debug_visitor_->OnIncorrectConnectionId(header.destination_connection_id);
730 }
731 // If this is a server, the dispatcher routes each packet to the
732 // QuicConnection responsible for the packet's connection ID. So if control
733 // arrives here and this is a server, the dispatcher must be malfunctioning.
734 DCHECK_NE(Perspective::IS_SERVER, perspective_);
735 return false;
736}
737
738bool QuicConnection::OnUnauthenticatedHeader(const QuicPacketHeader& header) {
739 if (debug_visitor_ != nullptr) {
740 debug_visitor_->OnUnauthenticatedHeader(header);
741 }
742
743 // Check that any public reset packet with a different connection ID that was
744 // routed to this QuicConnection has been redirected before control reaches
745 // here.
746 DCHECK_EQ(connection_id_, header.destination_connection_id);
747
748 if (!packet_generator_.IsPendingPacketEmpty()) {
749 // Incoming packets may change a queued ACK frame.
vasilvvc48c8712019-03-11 13:38:16 -0700750 const std::string error_details =
QUICHE teama6ef0a62019-03-07 20:34:33 -0500751 "Pending frames must be serialized before incoming packets are "
752 "processed.";
753 QUIC_BUG << error_details << ", received header: " << header;
754 CloseConnection(QUIC_INTERNAL_ERROR, error_details,
755 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
756 return false;
757 }
758
759 // If this packet has already been seen, or the sender has told us that it
760 // will not be retransmitted, then stop processing the packet.
761 if (!received_packet_manager_.IsAwaitingPacket(header.packet_number)) {
762 if (framer_.IsIetfStatelessResetPacket(header)) {
763 QuicIetfStatelessResetPacket packet(
764 header, header.possible_stateless_reset_token);
765 OnAuthenticatedIetfStatelessResetPacket(packet);
766 return false;
767 }
768 QUIC_DLOG(INFO) << ENDPOINT << "Packet " << header.packet_number
769 << " no longer being waited for. Discarding.";
770 if (debug_visitor_ != nullptr) {
771 debug_visitor_->OnDuplicatePacket(header.packet_number);
772 }
773 ++stats_.packets_dropped;
774 return false;
775 }
776
777 if (version_negotiation_state_ != NEGOTIATED_VERSION &&
778 perspective_ == Perspective::IS_SERVER) {
779 if (!header.version_flag) {
780 // Packets should have the version flag till version negotiation is
781 // done.
vasilvvc48c8712019-03-11 13:38:16 -0700782 std::string error_details =
QUICHE teama6ef0a62019-03-07 20:34:33 -0500783 QuicStrCat(ENDPOINT, "Packet ", header.packet_number.ToUint64(),
784 " without version flag before version negotiated.");
785 QUIC_DLOG(WARNING) << error_details;
786 CloseConnection(QUIC_INVALID_VERSION, error_details,
787 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
788 return false;
789 } else {
790 DCHECK_EQ(header.version, version());
791 version_negotiation_state_ = NEGOTIATED_VERSION;
792 framer_.InferPacketHeaderTypeFromVersion();
793 visitor_->OnSuccessfulVersionNegotiation(version());
794 if (debug_visitor_ != nullptr) {
795 debug_visitor_->OnSuccessfulVersionNegotiation(version());
796 }
797 }
798 DCHECK_EQ(NEGOTIATED_VERSION, version_negotiation_state_);
799 }
800
801 return true;
802}
803
804void QuicConnection::OnDecryptedPacket(EncryptionLevel level) {
805 last_decrypted_packet_level_ = level;
806 last_packet_decrypted_ = true;
807
808 // Once the server receives a forward secure packet, the handshake is
809 // confirmed.
810 if (level == ENCRYPTION_FORWARD_SECURE &&
811 perspective_ == Perspective::IS_SERVER) {
812 sent_packet_manager_.SetHandshakeConfirmed();
813 if (sent_packet_manager_.unacked_packets().use_uber_loss_algorithm()) {
814 // This may have changed the retransmission timer, so re-arm it.
815 SetRetransmissionAlarm();
816 }
817 }
818}
819
820QuicSocketAddress QuicConnection::GetEffectivePeerAddressFromCurrentPacket()
821 const {
822 // By default, the connection is not proxied, and the effective peer address
823 // is the packet's source address, i.e. the direct peer address.
824 return last_packet_source_address_;
825}
826
827bool QuicConnection::OnPacketHeader(const QuicPacketHeader& header) {
828 if (debug_visitor_ != nullptr) {
829 debug_visitor_->OnPacketHeader(header);
830 }
831
832 // Will be decremented below if we fall through to return true.
833 ++stats_.packets_dropped;
834
835 if (!ProcessValidatedPacket(header)) {
836 return false;
837 }
838
839 // Initialize the current packet content state.
840 current_packet_content_ = NO_FRAMES_RECEIVED;
841 is_current_packet_connectivity_probing_ = false;
842 current_effective_peer_migration_type_ = NO_CHANGE;
843
844 if (perspective_ == Perspective::IS_CLIENT) {
845 if (!received_packet_manager_.GetLargestObserved().IsInitialized() ||
846 header.packet_number > received_packet_manager_.GetLargestObserved()) {
847 // Update peer_address_ and effective_peer_address_ immediately for
848 // client connections.
849 direct_peer_address_ = last_packet_source_address_;
850 effective_peer_address_ = GetEffectivePeerAddressFromCurrentPacket();
851 }
852 } else {
853 // At server, remember the address change type of effective_peer_address
854 // in current_effective_peer_migration_type_. But this variable alone
855 // doesn't necessarily starts a migration. A migration will be started
856 // later, once the current packet is confirmed to meet the following
857 // conditions:
858 // 1) current_effective_peer_migration_type_ is not NO_CHANGE.
859 // 2) The current packet is not a connectivity probing.
860 // 3) The current packet is not reordered, i.e. its packet number is the
861 // largest of this connection so far.
862 // Once the above conditions are confirmed, a new migration will start
863 // even if there is an active migration underway.
864 current_effective_peer_migration_type_ =
865 QuicUtils::DetermineAddressChangeType(
866 effective_peer_address_,
867 GetEffectivePeerAddressFromCurrentPacket());
868
869 QUIC_DLOG_IF(INFO, current_effective_peer_migration_type_ != NO_CHANGE)
870 << ENDPOINT << "Effective peer's ip:port changed from "
871 << effective_peer_address_.ToString() << " to "
872 << GetEffectivePeerAddressFromCurrentPacket().ToString()
873 << ", active_effective_peer_migration_type is "
874 << active_effective_peer_migration_type_;
875 }
876
877 --stats_.packets_dropped;
878 QUIC_DVLOG(1) << ENDPOINT << "Received packet header: " << header;
879 last_header_ = header;
880 // An ack will be sent if a missing retransmittable packet was received;
881 was_last_packet_missing_ =
882 received_packet_manager_.IsMissing(last_header_.packet_number);
883
884 // Record packet receipt to populate ack info before processing stream
885 // frames, since the processing may result in sending a bundled ack.
886 received_packet_manager_.RecordPacketReceived(last_header_,
887 time_of_last_received_packet_);
888 DCHECK(connected_);
889 return true;
890}
891
892bool QuicConnection::OnStreamFrame(const QuicStreamFrame& frame) {
893 DCHECK(connected_);
894
895 // Since a stream frame was received, this is not a connectivity probe.
896 // A probe only contains a PING and full padding.
897 UpdatePacketContent(NOT_PADDED_PING);
898
899 if (debug_visitor_ != nullptr) {
900 debug_visitor_->OnStreamFrame(frame);
901 }
902 if (frame.stream_id != QuicUtils::GetCryptoStreamId(transport_version()) &&
QUICHE team6987b4a2019-03-15 16:23:04 -0700903 last_decrypted_packet_level_ == ENCRYPTION_INITIAL) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500904 if (MaybeConsiderAsMemoryCorruption(frame)) {
905 CloseConnection(QUIC_MAYBE_CORRUPTED_MEMORY,
906 "Received crypto frame on non crypto stream.",
907 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
908 return false;
909 }
910
911 QUIC_PEER_BUG << ENDPOINT
912 << "Received an unencrypted data frame: closing connection"
913 << " packet_number:" << last_header_.packet_number
914 << " stream_id:" << frame.stream_id << " received_packets:"
915 << received_packet_manager_.ack_frame();
916 CloseConnection(QUIC_UNENCRYPTED_STREAM_DATA,
917 "Unencrypted stream data seen.",
918 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
919 return false;
920 }
921 visitor_->OnStreamFrame(frame);
922 stats_.stream_bytes_received += frame.data_length;
923 should_last_packet_instigate_acks_ = true;
924 return connected_;
925}
926
927bool QuicConnection::OnCryptoFrame(const QuicCryptoFrame& frame) {
928 DCHECK(connected_);
929
930 // Since a CRYPTO frame was received, this is not a connectivity probe.
931 // A probe only contains a PING and full padding.
932 UpdatePacketContent(NOT_PADDED_PING);
933
934 visitor_->OnCryptoFrame(frame);
935 should_last_packet_instigate_acks_ = true;
936 return connected_;
937}
938
939bool QuicConnection::OnAckFrameStart(QuicPacketNumber largest_acked,
940 QuicTime::Delta ack_delay_time) {
941 DCHECK(connected_);
942
943 if (processing_ack_frame_) {
944 CloseConnection(QUIC_INVALID_ACK_DATA,
945 "Received a new ack while processing an ack frame.",
946 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
947 return false;
948 }
949
950 // Since an ack frame was received, this is not a connectivity probe.
951 // A probe only contains a PING and full padding.
952 UpdatePacketContent(NOT_PADDED_PING);
953
954 QUIC_DVLOG(1) << ENDPOINT
955 << "OnAckFrameStart, largest_acked: " << largest_acked;
956
957 if (largest_seen_packet_with_ack_.IsInitialized() &&
958 last_header_.packet_number <= largest_seen_packet_with_ack_) {
959 QUIC_DLOG(INFO) << ENDPOINT << "Received an old ack frame: ignoring";
960 return true;
961 }
962
963 if (!sent_packet_manager_.GetLargestSentPacket().IsInitialized() ||
964 largest_acked > sent_packet_manager_.GetLargestSentPacket()) {
965 QUIC_DLOG(WARNING) << ENDPOINT
966 << "Peer's observed unsent packet:" << largest_acked
967 << " vs " << sent_packet_manager_.GetLargestSentPacket();
968 // We got an ack for data we have not sent.
969 CloseConnection(QUIC_INVALID_ACK_DATA, "Largest observed too high.",
970 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
971 return false;
972 }
973
974 if (!sent_packet_manager_.GetLargestObserved().IsInitialized() ||
975 largest_acked > sent_packet_manager_.GetLargestObserved()) {
976 visitor_->OnForwardProgressConfirmed();
QUICHE team9929cc42019-03-13 08:17:43 -0700977 } else if (!sent_packet_manager_.tolerate_reneging() &&
978 largest_acked < sent_packet_manager_.GetLargestObserved()) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500979 QUIC_LOG(INFO) << ENDPOINT << "Peer's largest_observed packet decreased:"
980 << largest_acked << " vs "
981 << sent_packet_manager_.GetLargestObserved()
982 << " packet_number:" << last_header_.packet_number
983 << " largest seen with ack:" << largest_seen_packet_with_ack_
984 << " connection_id: " << connection_id_;
985 // A new ack has a diminished largest_observed value.
986 // If this was an old packet, we wouldn't even have checked.
987 CloseConnection(QUIC_INVALID_ACK_DATA, "Largest observed too low.",
988 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
989 return false;
990 }
991 processing_ack_frame_ = true;
992 sent_packet_manager_.OnAckFrameStart(largest_acked, ack_delay_time,
993 time_of_last_received_packet_);
994 return true;
995}
996
997bool QuicConnection::OnAckRange(QuicPacketNumber start, QuicPacketNumber end) {
998 DCHECK(connected_);
999 QUIC_DVLOG(1) << ENDPOINT << "OnAckRange: [" << start << ", " << end << ")";
1000
1001 if (largest_seen_packet_with_ack_.IsInitialized() &&
1002 last_header_.packet_number <= largest_seen_packet_with_ack_) {
1003 QUIC_DLOG(INFO) << ENDPOINT << "Received an old ack frame: ignoring";
1004 return true;
1005 }
1006
1007 sent_packet_manager_.OnAckRange(start, end);
1008 return true;
1009}
1010
1011bool QuicConnection::OnAckTimestamp(QuicPacketNumber packet_number,
1012 QuicTime timestamp) {
1013 DCHECK(connected_);
1014 QUIC_DVLOG(1) << ENDPOINT << "OnAckTimestamp: [" << packet_number << ", "
1015 << timestamp.ToDebuggingValue() << ")";
1016
1017 if (largest_seen_packet_with_ack_.IsInitialized() &&
1018 last_header_.packet_number <= largest_seen_packet_with_ack_) {
1019 QUIC_DLOG(INFO) << ENDPOINT << "Received an old ack frame: ignoring";
1020 return true;
1021 }
1022
1023 sent_packet_manager_.OnAckTimestamp(packet_number, timestamp);
1024 return true;
1025}
1026
1027bool QuicConnection::OnAckFrameEnd(QuicPacketNumber start) {
1028 DCHECK(connected_);
1029 QUIC_DVLOG(1) << ENDPOINT << "OnAckFrameEnd, start: " << start;
1030
1031 if (largest_seen_packet_with_ack_.IsInitialized() &&
1032 last_header_.packet_number <= largest_seen_packet_with_ack_) {
1033 QUIC_DLOG(INFO) << ENDPOINT << "Received an old ack frame: ignoring";
1034 return true;
1035 }
1036 bool acked_new_packet =
1037 sent_packet_manager_.OnAckFrameEnd(time_of_last_received_packet_);
1038 // Cancel the send alarm because new packets likely have been acked, which
1039 // may change the congestion window and/or pacing rate. Canceling the alarm
1040 // causes CanWrite to recalculate the next send time.
1041 if (send_alarm_->IsSet()) {
1042 send_alarm_->Cancel();
1043 }
1044 if (supports_release_time_) {
1045 // Update pace time into future because smoothed RTT is likely updated.
1046 UpdateReleaseTimeIntoFuture();
1047 }
1048 largest_seen_packet_with_ack_ = last_header_.packet_number;
1049 // If the incoming ack's packets set expresses missing packets: peer is still
1050 // waiting for a packet lower than a packet that we are no longer planning to
1051 // send.
1052 // If the incoming ack's packets set expresses received packets: peer is still
1053 // acking packets which we never care about.
1054 // Send an ack to raise the high water mark.
1055 PostProcessAfterAckFrame(GetLeastUnacked() > start, acked_new_packet);
1056 processing_ack_frame_ = false;
1057
1058 return connected_;
1059}
1060
1061bool QuicConnection::OnStopWaitingFrame(const QuicStopWaitingFrame& frame) {
1062 DCHECK(connected_);
1063
1064 // Since a stop waiting frame was received, this is not a connectivity probe.
1065 // A probe only contains a PING and full padding.
1066 UpdatePacketContent(NOT_PADDED_PING);
1067
1068 if (no_stop_waiting_frames_) {
1069 return true;
1070 }
1071 if (largest_seen_packet_with_stop_waiting_.IsInitialized() &&
1072 last_header_.packet_number <= largest_seen_packet_with_stop_waiting_) {
1073 QUIC_DLOG(INFO) << ENDPOINT
1074 << "Received an old stop waiting frame: ignoring";
1075 return true;
1076 }
1077
1078 const char* error = ValidateStopWaitingFrame(frame);
1079 if (error != nullptr) {
1080 CloseConnection(QUIC_INVALID_STOP_WAITING_DATA, error,
1081 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
1082 return false;
1083 }
1084
1085 if (debug_visitor_ != nullptr) {
1086 debug_visitor_->OnStopWaitingFrame(frame);
1087 }
1088
1089 largest_seen_packet_with_stop_waiting_ = last_header_.packet_number;
1090 received_packet_manager_.DontWaitForPacketsBefore(frame.least_unacked);
1091 return connected_;
1092}
1093
1094bool QuicConnection::OnPaddingFrame(const QuicPaddingFrame& frame) {
1095 DCHECK(connected_);
1096 UpdatePacketContent(SECOND_FRAME_IS_PADDING);
1097
1098 if (debug_visitor_ != nullptr) {
1099 debug_visitor_->OnPaddingFrame(frame);
1100 }
1101 return true;
1102}
1103
1104bool QuicConnection::OnPingFrame(const QuicPingFrame& frame) {
1105 DCHECK(connected_);
1106 UpdatePacketContent(FIRST_FRAME_IS_PING);
1107
1108 if (debug_visitor_ != nullptr) {
1109 debug_visitor_->OnPingFrame(frame);
1110 }
1111 should_last_packet_instigate_acks_ = true;
1112 return true;
1113}
1114
QUICHE teama6ef0a62019-03-07 20:34:33 -05001115const char* QuicConnection::ValidateStopWaitingFrame(
1116 const QuicStopWaitingFrame& stop_waiting) {
1117 if (received_packet_manager_.peer_least_packet_awaiting_ack()
1118 .IsInitialized() &&
1119 stop_waiting.least_unacked <
1120 received_packet_manager_.peer_least_packet_awaiting_ack()) {
1121 QUIC_DLOG(ERROR)
1122 << ENDPOINT
1123 << "Peer's sent low least_unacked: " << stop_waiting.least_unacked
1124 << " vs " << received_packet_manager_.peer_least_packet_awaiting_ack();
1125 // We never process old ack frames, so this number should only increase.
1126 return "Least unacked too small.";
1127 }
1128
1129 if (stop_waiting.least_unacked > last_header_.packet_number) {
1130 QUIC_DLOG(ERROR) << ENDPOINT
1131 << "Peer sent least_unacked:" << stop_waiting.least_unacked
1132 << " greater than the enclosing packet number:"
1133 << last_header_.packet_number;
1134 return "Least unacked too large.";
1135 }
1136
1137 return nullptr;
1138}
1139
1140bool QuicConnection::OnRstStreamFrame(const QuicRstStreamFrame& frame) {
1141 DCHECK(connected_);
1142
1143 // Since a reset stream frame was received, this is not a connectivity probe.
1144 // A probe only contains a PING and full padding.
1145 UpdatePacketContent(NOT_PADDED_PING);
1146
1147 if (debug_visitor_ != nullptr) {
1148 debug_visitor_->OnRstStreamFrame(frame);
1149 }
1150 QUIC_DLOG(INFO) << ENDPOINT
1151 << "RST_STREAM_FRAME received for stream: " << frame.stream_id
1152 << " with error: "
1153 << QuicRstStreamErrorCodeToString(frame.error_code);
1154 visitor_->OnRstStream(frame);
1155 should_last_packet_instigate_acks_ = true;
1156 return connected_;
1157}
1158
1159bool QuicConnection::OnApplicationCloseFrame(
1160 const QuicApplicationCloseFrame& frame) {
1161 // TODO(fkastenholz): Need to figure out what the right thing is to do with
1162 // this when we get one. Most likely, the correct action is to mimic the
1163 // OnConnectionCloseFrame actions, with possibly an indication to the
1164 // application of the ApplicationClose information.
1165 return true;
1166}
1167
1168bool QuicConnection::OnStopSendingFrame(const QuicStopSendingFrame& frame) {
1169 DCHECK(connected_);
1170
1171 // Since a reset stream frame was received, this is not a connectivity probe.
1172 // A probe only contains a PING and full padding.
1173 UpdatePacketContent(NOT_PADDED_PING);
1174
1175 if (debug_visitor_ != nullptr) {
1176 debug_visitor_->OnStopSendingFrame(frame);
1177 }
1178
1179 QUIC_DLOG(INFO) << ENDPOINT << "STOP_SENDING frame received for stream: "
1180 << frame.stream_id
1181 << " with error: " << frame.application_error_code;
1182
1183 visitor_->OnStopSendingFrame(frame);
1184 return connected_;
1185}
1186
1187bool QuicConnection::OnPathChallengeFrame(const QuicPathChallengeFrame& frame) {
1188 // Save the path challenge's payload, for later use in generating the
1189 // response.
1190 received_path_challenge_payloads_.push_back(frame.data_buffer);
1191
1192 // For VERSION 99 we define a "Padded PATH CHALLENGE" to be the same thing
1193 // as a PADDED PING -- it will start a connectivity check and prevent
1194 // connection migration. Insofar as the connectivity check and connection
1195 // migration are concerned, logically the PATH CHALLENGE is the same as the
1196 // PING, so as a stopgap, tell the FSM that determines whether we have a
1197 // Padded PING or not that we received a PING.
1198 UpdatePacketContent(FIRST_FRAME_IS_PING);
1199 should_last_packet_instigate_acks_ = true;
1200 return true;
1201}
1202
1203bool QuicConnection::OnPathResponseFrame(const QuicPathResponseFrame& frame) {
1204 should_last_packet_instigate_acks_ = true;
1205 if (!transmitted_connectivity_probe_payload_ ||
1206 *transmitted_connectivity_probe_payload_ != frame.data_buffer) {
1207 // Is not for the probe we sent, ignore it.
1208 return true;
1209 }
1210 // Have received the matching PATH RESPONSE, saved payload no longer valid.
1211 transmitted_connectivity_probe_payload_ = nullptr;
1212 UpdatePacketContent(FIRST_FRAME_IS_PING);
1213 return true;
1214}
1215
1216bool QuicConnection::OnConnectionCloseFrame(
1217 const QuicConnectionCloseFrame& frame) {
1218 DCHECK(connected_);
1219
1220 // Since a connection close frame was received, this is not a connectivity
1221 // probe. A probe only contains a PING and full padding.
1222 UpdatePacketContent(NOT_PADDED_PING);
1223
1224 if (debug_visitor_ != nullptr) {
1225 debug_visitor_->OnConnectionCloseFrame(frame);
1226 }
1227 QUIC_DLOG(INFO) << ENDPOINT << "Received ConnectionClose for connection: "
1228 << connection_id()
1229 << ", with error: " << QuicErrorCodeToString(frame.error_code)
1230 << " (" << frame.error_details << ")";
1231 if (frame.error_code == QUIC_BAD_MULTIPATH_FLAG) {
1232 QUIC_LOG_FIRST_N(ERROR, 10) << "Unexpected QUIC_BAD_MULTIPATH_FLAG error."
1233 << " last_received_header: " << last_header_
1234 << " encryption_level: " << encryption_level_;
1235 }
1236 TearDownLocalConnectionState(frame.error_code, frame.error_details,
1237 ConnectionCloseSource::FROM_PEER);
1238 return connected_;
1239}
1240
1241bool QuicConnection::OnMaxStreamIdFrame(const QuicMaxStreamIdFrame& frame) {
1242 return visitor_->OnMaxStreamIdFrame(frame);
1243}
1244
1245bool QuicConnection::OnStreamIdBlockedFrame(
1246 const QuicStreamIdBlockedFrame& frame) {
1247 return visitor_->OnStreamIdBlockedFrame(frame);
1248}
1249
1250bool QuicConnection::OnGoAwayFrame(const QuicGoAwayFrame& frame) {
1251 DCHECK(connected_);
1252
1253 // Since a go away frame was received, this is not a connectivity probe.
1254 // A probe only contains a PING and full padding.
1255 UpdatePacketContent(NOT_PADDED_PING);
1256
1257 if (debug_visitor_ != nullptr) {
1258 debug_visitor_->OnGoAwayFrame(frame);
1259 }
1260 QUIC_DLOG(INFO) << ENDPOINT << "GOAWAY_FRAME received with last good stream: "
1261 << frame.last_good_stream_id
1262 << " and error: " << QuicErrorCodeToString(frame.error_code)
1263 << " and reason: " << frame.reason_phrase;
1264
1265 visitor_->OnGoAway(frame);
1266 should_last_packet_instigate_acks_ = true;
1267 return connected_;
1268}
1269
1270bool QuicConnection::OnWindowUpdateFrame(const QuicWindowUpdateFrame& frame) {
1271 DCHECK(connected_);
1272
1273 // Since a window update frame was received, this is not a connectivity probe.
1274 // A probe only contains a PING and full padding.
1275 UpdatePacketContent(NOT_PADDED_PING);
1276
1277 if (debug_visitor_ != nullptr) {
1278 debug_visitor_->OnWindowUpdateFrame(frame, time_of_last_received_packet_);
1279 }
1280 QUIC_DLOG(INFO) << ENDPOINT << "WINDOW_UPDATE_FRAME received for stream: "
1281 << frame.stream_id
1282 << " with byte offset: " << frame.byte_offset;
1283 visitor_->OnWindowUpdateFrame(frame);
1284 should_last_packet_instigate_acks_ = true;
1285 return connected_;
1286}
1287
1288bool QuicConnection::OnNewConnectionIdFrame(
1289 const QuicNewConnectionIdFrame& frame) {
1290 return true;
1291}
1292
1293bool QuicConnection::OnRetireConnectionIdFrame(
1294 const QuicRetireConnectionIdFrame& frame) {
1295 return true;
1296}
1297
1298bool QuicConnection::OnNewTokenFrame(const QuicNewTokenFrame& frame) {
1299 return true;
1300}
1301
1302bool QuicConnection::OnMessageFrame(const QuicMessageFrame& frame) {
1303 DCHECK(connected_);
1304
1305 // Since a message frame was received, this is not a connectivity probe.
1306 // A probe only contains a PING and full padding.
1307 UpdatePacketContent(NOT_PADDED_PING);
1308
1309 if (debug_visitor_ != nullptr) {
1310 debug_visitor_->OnMessageFrame(frame);
1311 }
1312 visitor_->OnMessageReceived(
1313 QuicStringPiece(frame.data, frame.message_length));
1314 should_last_packet_instigate_acks_ = true;
1315 return connected_;
1316}
1317
1318bool QuicConnection::OnBlockedFrame(const QuicBlockedFrame& frame) {
1319 DCHECK(connected_);
1320
1321 // Since a blocked frame was received, this is not a connectivity probe.
1322 // A probe only contains a PING and full padding.
1323 UpdatePacketContent(NOT_PADDED_PING);
1324
1325 if (debug_visitor_ != nullptr) {
1326 debug_visitor_->OnBlockedFrame(frame);
1327 }
1328 QUIC_DLOG(INFO) << ENDPOINT
1329 << "BLOCKED_FRAME received for stream: " << frame.stream_id;
1330 visitor_->OnBlockedFrame(frame);
1331 stats_.blocked_frames_received++;
1332 should_last_packet_instigate_acks_ = true;
1333 return connected_;
1334}
1335
1336void QuicConnection::OnPacketComplete() {
1337 // Don't do anything if this packet closed the connection.
1338 if (!connected_) {
1339 ClearLastFrames();
1340 return;
1341 }
1342
1343 if (IsCurrentPacketConnectivityProbing()) {
1344 ++stats_.num_connectivity_probing_received;
1345 }
1346
1347 QUIC_DVLOG(1) << ENDPOINT << "Got packet " << last_header_.packet_number
1348 << " for " << last_header_.destination_connection_id;
1349
1350 QUIC_DLOG_IF(INFO, current_packet_content_ == SECOND_FRAME_IS_PADDING)
1351 << ENDPOINT << "Received a padded PING packet. is_probing: "
1352 << IsCurrentPacketConnectivityProbing();
1353
1354 if (perspective_ == Perspective::IS_CLIENT) {
1355 QUIC_DVLOG(1) << ENDPOINT
1356 << "Received a speculative connectivity probing packet for "
1357 << last_header_.destination_connection_id
1358 << " from ip:port: " << last_packet_source_address_.ToString()
1359 << " to ip:port: "
1360 << last_packet_destination_address_.ToString();
1361 // TODO(zhongyi): change the method name.
1362 visitor_->OnConnectivityProbeReceived(last_packet_destination_address_,
1363 last_packet_source_address_);
1364 } else if (IsCurrentPacketConnectivityProbing()) {
1365 // This node is not a client (is a server) AND the received packet was
1366 // connectivity-probing, send an appropriate response.
1367 QUIC_DVLOG(1) << ENDPOINT << "Received a connectivity probing packet for "
1368 << last_header_.destination_connection_id
1369 << " from ip:port: " << last_packet_source_address_.ToString()
1370 << " to ip:port: "
1371 << last_packet_destination_address_.ToString();
1372 visitor_->OnConnectivityProbeReceived(last_packet_destination_address_,
1373 last_packet_source_address_);
1374 } else {
1375 // This node is not a client (is a server) AND the received packet was
1376 // NOT connectivity-probing. If the packet had PATH CHALLENGES, send
1377 // appropriate RESPONSE. Then deal with possible peer migration.
1378 if (transport_version() == QUIC_VERSION_99 &&
1379 !received_path_challenge_payloads_.empty()) {
1380 // If a PATH CHALLENGE was in a "Padded PING (or PATH CHALLENGE)"
1381 // then it is taken care of above. This handles the case where a PATH
1382 // CHALLENGE appeared someplace else (eg, the peer randomly added a PATH
1383 // CHALLENGE frame to some other packet.
1384 // There was at least one PATH CHALLENGE in the received packet,
1385 // Generate the required PATH RESPONSE.
1386 SendGenericPathProbePacket(nullptr, last_packet_source_address_,
1387 /* is_response= */ true);
1388 }
1389
1390 if (last_header_.packet_number ==
1391 received_packet_manager_.GetLargestObserved()) {
1392 direct_peer_address_ = last_packet_source_address_;
1393 if (current_effective_peer_migration_type_ != NO_CHANGE) {
1394 StartEffectivePeerMigration(current_effective_peer_migration_type_);
1395 }
1396 }
1397 }
1398
1399 current_effective_peer_migration_type_ = NO_CHANGE;
1400
1401 // An ack will be sent if a missing retransmittable packet was received;
1402 const bool was_missing =
1403 should_last_packet_instigate_acks_ && was_last_packet_missing_;
1404
1405 if (received_packet_manager_.decide_when_to_send_acks()) {
1406 received_packet_manager_.MaybeUpdateAckTimeout(
1407 should_last_packet_instigate_acks_, last_header_.packet_number,
1408 time_of_last_received_packet_, clock_->ApproximateNow(),
1409 sent_packet_manager_.GetRttStats(),
1410 sent_packet_manager_.delayed_ack_time());
1411 } else if (ack_frame_updated()) {
1412 // It's possible the ack frame was sent along with response data, so it
1413 // no longer needs to be sent.
1414 MaybeQueueAck(was_missing);
1415 }
1416
1417 ClearLastFrames();
1418 CloseIfTooManyOutstandingSentPackets();
1419}
1420
1421bool QuicConnection::IsValidStatelessResetToken(QuicUint128 token) const {
1422 return stateless_reset_token_received_ &&
1423 token == received_stateless_reset_token_;
1424}
1425
1426void QuicConnection::OnAuthenticatedIetfStatelessResetPacket(
1427 const QuicIetfStatelessResetPacket& packet) {
1428 // TODO(fayang): Add OnAuthenticatedIetfStatelessResetPacket to
1429 // debug_visitor_.
vasilvvc48c8712019-03-11 13:38:16 -07001430 const std::string error_details = "Received stateless reset.";
QUICHE teama6ef0a62019-03-07 20:34:33 -05001431 QUIC_CODE_COUNT(quic_tear_down_local_connection_on_stateless_reset);
1432 TearDownLocalConnectionState(QUIC_PUBLIC_RESET, error_details,
1433 ConnectionCloseSource::FROM_PEER);
1434}
1435
1436void QuicConnection::MaybeQueueAck(bool was_missing) {
1437 DCHECK(!received_packet_manager_.decide_when_to_send_acks());
1438 ++num_packets_received_since_last_ack_sent_;
1439 // Determine whether the newly received packet was missing before recording
1440 // the received packet.
1441 if (was_missing) {
1442 // Only ack immediately if an ACK frame was sent with a larger
1443 // largest acked than the newly received packet number.
1444 const QuicPacketNumber largest_sent_largest_acked =
1445 sent_packet_manager_.unacked_packets().largest_sent_largest_acked();
1446 if (largest_sent_largest_acked.IsInitialized() &&
1447 last_header_.packet_number < largest_sent_largest_acked) {
1448 if (packet_generator_.deprecate_ack_bundling_mode()) {
1449 MaybeSetAckAlarmTo(clock_->ApproximateNow());
1450 } else {
1451 ack_queued_ = true;
1452 }
1453 }
1454 }
1455
1456 if (should_last_packet_instigate_acks_ && !ack_queued_) {
1457 ++num_retransmittable_packets_received_since_last_ack_sent_;
1458 if (ack_mode_ != TCP_ACKING &&
1459 last_header_.packet_number >=
1460 received_packet_manager_.PeerFirstSendingPacketNumber() +
1461 min_received_before_ack_decimation_) {
1462 // Ack up to 10 packets at once unless ack decimation is unlimited.
1463 if (!unlimited_ack_decimation_ &&
1464 num_retransmittable_packets_received_since_last_ack_sent_ >=
1465 kMaxRetransmittablePacketsBeforeAck) {
1466 if (packet_generator_.deprecate_ack_bundling_mode()) {
1467 MaybeSetAckAlarmTo(clock_->ApproximateNow());
1468 } else {
1469 ack_queued_ = true;
1470 }
1471 } else if (ShouldSetAckAlarm()) {
1472 // Wait for the minimum of the ack decimation delay or the delayed ack
1473 // time before sending an ack.
1474 QuicTime::Delta ack_delay =
1475 std::min(sent_packet_manager_.delayed_ack_time(),
1476 sent_packet_manager_.GetRttStats()->min_rtt() *
1477 ack_decimation_delay_);
1478 const QuicTime approximate_now = clock_->ApproximateNow();
1479 if (fast_ack_after_quiescence_ &&
1480 (approximate_now - time_of_previous_received_packet_) >
1481 sent_packet_manager_.GetRttStats()->SmoothedOrInitialRtt()) {
1482 // Ack the first packet out of queiscence faster, because QUIC does
1483 // not pace the first few packets and commonly these may be handshake
1484 // or TLP packets, which we'd like to acknowledge quickly.
1485 ack_delay = QuicTime::Delta::FromMilliseconds(1);
1486 }
1487 ack_alarm_->Set(approximate_now + ack_delay);
1488 }
1489 } else {
1490 // Ack with a timer or every 2 packets by default.
1491 if (num_retransmittable_packets_received_since_last_ack_sent_ >=
1492 ack_frequency_before_ack_decimation_) {
1493 if (packet_generator_.deprecate_ack_bundling_mode()) {
1494 MaybeSetAckAlarmTo(clock_->ApproximateNow());
1495 } else {
1496 ack_queued_ = true;
1497 }
1498 } else if (ShouldSetAckAlarm()) {
1499 const QuicTime approximate_now = clock_->ApproximateNow();
1500 if (fast_ack_after_quiescence_ &&
1501 (approximate_now - time_of_previous_received_packet_) >
1502 sent_packet_manager_.GetRttStats()->SmoothedOrInitialRtt()) {
1503 // Ack the first packet out of queiscence faster, because QUIC does
1504 // not pace the first few packets and commonly these may be handshake
1505 // or TLP packets, which we'd like to acknowledge quickly.
1506 ack_alarm_->Set(approximate_now +
1507 QuicTime::Delta::FromMilliseconds(1));
1508 } else {
1509 ack_alarm_->Set(approximate_now +
1510 sent_packet_manager_.delayed_ack_time());
1511 }
1512 }
1513 }
1514
1515 // If there are new missing packets to report, send an ack immediately.
1516 if (received_packet_manager_.HasNewMissingPackets()) {
1517 if (ack_mode_ == ACK_DECIMATION_WITH_REORDERING) {
1518 // Wait the minimum of an eighth min_rtt and the existing ack time.
1519 QuicTime ack_time =
1520 clock_->ApproximateNow() +
1521 0.125 * sent_packet_manager_.GetRttStats()->min_rtt();
1522 if (ShouldSetAckAlarm() || ack_alarm_->deadline() > ack_time) {
1523 ack_alarm_->Update(ack_time, QuicTime::Delta::Zero());
1524 }
1525 } else {
1526 if (packet_generator_.deprecate_ack_bundling_mode()) {
1527 MaybeSetAckAlarmTo(clock_->ApproximateNow());
1528 } else {
1529 ack_queued_ = true;
1530 }
1531 }
1532 }
1533
1534 if (fast_ack_after_quiescence_) {
1535 time_of_previous_received_packet_ = time_of_last_received_packet_;
1536 }
1537 }
1538
1539 if (ack_queued_) {
1540 ack_alarm_->Cancel();
1541 }
1542}
1543
1544void QuicConnection::ClearLastFrames() {
1545 should_last_packet_instigate_acks_ = false;
1546}
1547
1548void QuicConnection::CloseIfTooManyOutstandingSentPackets() {
1549 // This occurs if we don't discard old packets we've seen fast enough. It's
1550 // possible largest observed is less than leaset unacked.
1551 if (sent_packet_manager_.GetLargestObserved().IsInitialized() &&
1552 sent_packet_manager_.GetLargestObserved() >
1553 sent_packet_manager_.GetLeastUnacked() + max_tracked_packets_) {
1554 CloseConnection(
1555 QUIC_TOO_MANY_OUTSTANDING_SENT_PACKETS,
1556 QuicStrCat("More than ", max_tracked_packets_,
1557 " outstanding, least_unacked: ",
1558 sent_packet_manager_.GetLeastUnacked().ToUint64()),
1559 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
1560 }
1561}
1562
1563const QuicFrame QuicConnection::GetUpdatedAckFrame() {
1564 return received_packet_manager_.GetUpdatedAckFrame(clock_->ApproximateNow());
1565}
1566
1567void QuicConnection::PopulateStopWaitingFrame(
1568 QuicStopWaitingFrame* stop_waiting) {
1569 stop_waiting->least_unacked = GetLeastUnacked();
1570}
1571
1572QuicPacketNumber QuicConnection::GetLeastUnacked() const {
1573 return sent_packet_manager_.GetLeastUnacked();
1574}
1575
1576bool QuicConnection::HandleWriteBlocked() {
1577 if (!writer_->IsWriteBlocked()) {
1578 return false;
1579 }
1580
1581 visitor_->OnWriteBlocked();
1582 return true;
1583}
1584
1585void QuicConnection::MaybeSendInResponseToPacket() {
1586 if (!connected_) {
1587 return;
1588 }
1589
1590 // If the writer is blocked, don't attempt to send packets now or in the send
1591 // alarm. When the writer unblocks, OnCanWrite() will be called for this
1592 // connection to send.
1593 if (HandleWriteBlocked()) {
1594 return;
1595 }
1596
1597 // Now that we have received an ack, we might be able to send packets which
1598 // are queued locally, or drain streams which are blocked.
1599 if (defer_send_in_response_to_packets_) {
1600 send_alarm_->Update(clock_->ApproximateNow(), QuicTime::Delta::Zero());
1601 } else {
1602 WriteAndBundleAcksIfNotBlocked();
1603 }
1604}
1605
1606void QuicConnection::SendVersionNegotiationPacket(bool ietf_quic) {
1607 pending_version_negotiation_packet_ = true;
1608 send_ietf_version_negotiation_packet_ = ietf_quic;
1609
1610 if (HandleWriteBlocked()) {
1611 return;
1612 }
1613
1614 QUIC_DLOG(INFO) << ENDPOINT << "Sending version negotiation packet: {"
1615 << ParsedQuicVersionVectorToString(
1616 framer_.supported_versions())
1617 << "}, ietf_quic: " << ietf_quic;
1618 std::unique_ptr<QuicEncryptedPacket> version_packet(
1619 packet_generator_.SerializeVersionNegotiationPacket(
1620 ietf_quic, framer_.supported_versions()));
1621 WriteResult result = writer_->WritePacket(
1622 version_packet->data(), version_packet->length(), self_address().host(),
1623 peer_address(), per_packet_options_);
1624
1625 if (IsWriteError(result.status)) {
1626 OnWriteError(result.error_code);
1627 return;
1628 }
1629 if (IsWriteBlockedStatus(result.status)) {
1630 visitor_->OnWriteBlocked();
1631 if (result.status == WRITE_STATUS_BLOCKED_DATA_BUFFERED) {
1632 pending_version_negotiation_packet_ = false;
1633 }
1634 return;
1635 }
1636
1637 pending_version_negotiation_packet_ = false;
1638}
1639
1640size_t QuicConnection::SendCryptoData(EncryptionLevel level,
1641 size_t write_length,
1642 QuicStreamOffset offset) {
1643 if (write_length == 0) {
1644 QUIC_BUG << "Attempt to send empty crypto frame";
1645 return 0;
1646 }
1647
1648 ScopedPacketFlusher flusher(this, SEND_ACK_IF_PENDING);
1649 return packet_generator_.ConsumeCryptoData(level, write_length, offset);
1650}
1651
1652QuicConsumedData QuicConnection::SendStreamData(QuicStreamId id,
1653 size_t write_length,
1654 QuicStreamOffset offset,
1655 StreamSendingState state) {
1656 if (state == NO_FIN && write_length == 0) {
1657 QUIC_BUG << "Attempt to send empty stream frame";
1658 return QuicConsumedData(0, false);
1659 }
1660
1661 // Opportunistically bundle an ack with every outgoing packet.
1662 // Particularly, we want to bundle with handshake packets since we don't know
1663 // which decrypter will be used on an ack packet following a handshake
1664 // packet (a handshake packet from client to server could result in a REJ or a
1665 // SHLO from the server, leading to two different decrypters at the server.)
1666 ScopedPacketFlusher flusher(this, SEND_ACK_IF_PENDING);
1667 return packet_generator_.ConsumeData(id, write_length, offset, state);
1668}
1669
1670bool QuicConnection::SendControlFrame(const QuicFrame& frame) {
1671 if (!CanWrite(HAS_RETRANSMITTABLE_DATA) && frame.type != PING_FRAME) {
1672 QUIC_DVLOG(1) << ENDPOINT << "Failed to send control frame: " << frame;
1673 // Do not check congestion window for ping.
1674 return false;
1675 }
1676 ScopedPacketFlusher flusher(this, SEND_ACK_IF_PENDING);
1677 packet_generator_.AddControlFrame(frame);
1678 if (frame.type == PING_FRAME) {
1679 // Flush PING frame immediately.
1680 packet_generator_.FlushAllQueuedFrames();
1681 if (debug_visitor_ != nullptr) {
1682 debug_visitor_->OnPingSent();
1683 }
1684 }
1685 if (frame.type == BLOCKED_FRAME) {
1686 stats_.blocked_frames_sent++;
1687 }
1688 return true;
1689}
1690
1691void QuicConnection::OnStreamReset(QuicStreamId id,
1692 QuicRstStreamErrorCode error) {
1693 if (error == QUIC_STREAM_NO_ERROR) {
1694 // All data for streams which are reset with QUIC_STREAM_NO_ERROR must
1695 // be received by the peer.
1696 return;
1697 }
1698 // Flush stream frames of reset stream.
1699 if (packet_generator_.HasPendingStreamFramesOfStream(id)) {
1700 ScopedPacketFlusher flusher(this, SEND_ACK_IF_PENDING);
1701 packet_generator_.FlushAllQueuedFrames();
1702 }
1703
1704 sent_packet_manager_.CancelRetransmissionsForStream(id);
1705 // Remove all queued packets which only contain data for the reset stream.
1706 // TODO(fayang): consider removing this because it should be rarely executed.
1707 auto packet_iterator = queued_packets_.begin();
1708 while (packet_iterator != queued_packets_.end()) {
1709 QuicFrames* retransmittable_frames =
1710 &packet_iterator->retransmittable_frames;
1711 if (retransmittable_frames->empty()) {
1712 ++packet_iterator;
1713 continue;
1714 }
1715 // NOTE THAT RemoveFramesForStream removes only STREAM frames
1716 // for the specified stream.
1717 RemoveFramesForStream(retransmittable_frames, id);
1718 if (!retransmittable_frames->empty()) {
1719 ++packet_iterator;
1720 continue;
1721 }
1722 delete[] packet_iterator->encrypted_buffer;
1723 ClearSerializedPacket(&(*packet_iterator));
1724 packet_iterator = queued_packets_.erase(packet_iterator);
1725 }
1726 // TODO(ianswett): Consider checking for 3 RTOs when the last stream is
1727 // cancelled as well.
1728}
1729
1730const QuicConnectionStats& QuicConnection::GetStats() {
1731 const RttStats* rtt_stats = sent_packet_manager_.GetRttStats();
1732
1733 // Update rtt and estimated bandwidth.
1734 QuicTime::Delta min_rtt = rtt_stats->min_rtt();
1735 if (min_rtt.IsZero()) {
1736 // If min RTT has not been set, use initial RTT instead.
1737 min_rtt = rtt_stats->initial_rtt();
1738 }
1739 stats_.min_rtt_us = min_rtt.ToMicroseconds();
1740
1741 QuicTime::Delta srtt = rtt_stats->SmoothedOrInitialRtt();
1742 stats_.srtt_us = srtt.ToMicroseconds();
1743
1744 stats_.estimated_bandwidth = sent_packet_manager_.BandwidthEstimate();
1745 stats_.max_packet_size = packet_generator_.GetCurrentMaxPacketLength();
1746 stats_.max_received_packet_size = largest_received_packet_size_;
1747 return stats_;
1748}
1749
1750void QuicConnection::OnCoalescedPacket(const QuicEncryptedPacket& packet) {
1751 QueueCoalescedPacket(packet);
1752}
1753
1754void QuicConnection::ProcessUdpPacket(const QuicSocketAddress& self_address,
1755 const QuicSocketAddress& peer_address,
1756 const QuicReceivedPacket& packet) {
1757 if (!connected_) {
1758 return;
1759 }
1760 QUIC_BUG_IF(current_packet_data_ != nullptr)
1761 << "ProcessUdpPacket must not be called while processing a packet.";
1762 if (debug_visitor_ != nullptr) {
1763 debug_visitor_->OnPacketReceived(self_address, peer_address, packet);
1764 }
1765 last_size_ = packet.length();
1766 current_packet_data_ = packet.data();
1767
1768 last_packet_destination_address_ = self_address;
1769 last_packet_source_address_ = peer_address;
1770 if (!self_address_.IsInitialized()) {
1771 self_address_ = last_packet_destination_address_;
1772 }
1773
1774 if (!direct_peer_address_.IsInitialized()) {
1775 direct_peer_address_ = last_packet_source_address_;
1776 }
1777
1778 if (!effective_peer_address_.IsInitialized()) {
1779 const QuicSocketAddress effective_peer_addr =
1780 GetEffectivePeerAddressFromCurrentPacket();
1781
1782 // effective_peer_address_ must be initialized at the beginning of the
1783 // first packet processed(here). If effective_peer_addr is uninitialized,
1784 // just set effective_peer_address_ to the direct peer address.
1785 effective_peer_address_ = effective_peer_addr.IsInitialized()
1786 ? effective_peer_addr
1787 : direct_peer_address_;
1788 }
1789
1790 stats_.bytes_received += packet.length();
1791 ++stats_.packets_received;
1792
1793 // Ensure the time coming from the packet reader is within 2 minutes of now.
1794 if (std::abs((packet.receipt_time() - clock_->ApproximateNow()).ToSeconds()) >
1795 2 * 60) {
1796 QUIC_BUG << "Packet receipt time:"
1797 << packet.receipt_time().ToDebuggingValue()
1798 << " too far from current time:"
1799 << clock_->ApproximateNow().ToDebuggingValue();
1800 }
1801 time_of_last_received_packet_ = packet.receipt_time();
1802 QUIC_DVLOG(1) << ENDPOINT << "time of last received packet: "
1803 << time_of_last_received_packet_.ToDebuggingValue();
1804
1805 ScopedPacketFlusher flusher(this, NO_ACK);
1806 if (!framer_.ProcessPacket(packet)) {
1807 // If we are unable to decrypt this packet, it might be
1808 // because the CHLO or SHLO packet was lost.
1809 if (framer_.error() == QUIC_DECRYPTION_FAILURE) {
1810 if (encryption_level_ != ENCRYPTION_FORWARD_SECURE &&
1811 undecryptable_packets_.size() < max_undecryptable_packets_) {
1812 QueueUndecryptablePacket(packet);
1813 } else if (debug_visitor_ != nullptr) {
1814 debug_visitor_->OnUndecryptablePacket();
1815 }
1816 }
1817 QUIC_DVLOG(1) << ENDPOINT
1818 << "Unable to process packet. Last packet processed: "
1819 << last_header_.packet_number;
1820 current_packet_data_ = nullptr;
1821 is_current_packet_connectivity_probing_ = false;
1822
1823 MaybeProcessCoalescedPackets();
1824 return;
1825 }
1826
1827 ++stats_.packets_processed;
1828
1829 QUIC_DLOG_IF(INFO, active_effective_peer_migration_type_ != NO_CHANGE)
1830 << "sent_packet_manager_.GetLargestObserved() = "
1831 << sent_packet_manager_.GetLargestObserved()
1832 << ", highest_packet_sent_before_effective_peer_migration_ = "
1833 << highest_packet_sent_before_effective_peer_migration_;
1834 if (active_effective_peer_migration_type_ != NO_CHANGE &&
1835 sent_packet_manager_.GetLargestObserved().IsInitialized() &&
1836 (!highest_packet_sent_before_effective_peer_migration_.IsInitialized() ||
1837 sent_packet_manager_.GetLargestObserved() >
1838 highest_packet_sent_before_effective_peer_migration_)) {
1839 if (perspective_ == Perspective::IS_SERVER) {
1840 OnEffectivePeerMigrationValidated();
1841 }
1842 }
1843
1844 MaybeProcessCoalescedPackets();
1845 MaybeProcessUndecryptablePackets();
1846 MaybeSendInResponseToPacket();
1847 SetPingAlarm();
1848 current_packet_data_ = nullptr;
1849 is_current_packet_connectivity_probing_ = false;
1850}
1851
1852void QuicConnection::OnBlockedWriterCanWrite() {
1853 writer_->SetWritable();
1854 OnCanWrite();
1855}
1856
1857void QuicConnection::OnCanWrite() {
1858 DCHECK(!writer_->IsWriteBlocked());
1859
1860 // Add a flusher to ensure the connection is marked app-limited.
1861 ScopedPacketFlusher flusher(this, NO_ACK);
1862
1863 WriteQueuedPackets();
1864 if (received_packet_manager_.decide_when_to_send_acks()) {
1865 const QuicTime ack_timeout = received_packet_manager_.ack_timeout();
1866 if (ack_timeout.IsInitialized() &&
1867 ack_timeout <= clock_->ApproximateNow()) {
1868 // Send an ACK now because either 1) we were write blocked when we last
1869 // tried to send an ACK, or 2) both ack alarm and send alarm were set to
1870 // go off together.
1871 SendAck();
1872 }
1873 } else if (send_ack_when_on_can_write_) {
1874 // Send an ACK now because either 1) we were write blocked when we last
1875 // tried to send an ACK, or 2) both ack alarm and send alarm were set to go
1876 // off together.
1877 DCHECK(packet_generator_.deprecate_ack_bundling_mode());
1878 SendAck();
1879 }
1880 if (!session_decides_what_to_write()) {
1881 WritePendingRetransmissions();
1882 }
1883
1884 WriteNewData();
1885}
1886
1887void QuicConnection::WriteNewData() {
1888 // Sending queued packets may have caused the socket to become write blocked,
1889 // or the congestion manager to prohibit sending. If we've sent everything
1890 // we had queued and we're still not blocked, let the visitor know it can
1891 // write more.
1892 if (!CanWrite(HAS_RETRANSMITTABLE_DATA)) {
1893 return;
1894 }
1895
1896 {
1897 ScopedPacketFlusher flusher(this, SEND_ACK_IF_QUEUED);
1898 visitor_->OnCanWrite();
1899 }
1900
1901 // After the visitor writes, it may have caused the socket to become write
1902 // blocked or the congestion manager to prohibit sending, so check again.
1903 if (visitor_->WillingAndAbleToWrite() && !send_alarm_->IsSet() &&
1904 CanWrite(HAS_RETRANSMITTABLE_DATA)) {
1905 // We're not write blocked, but some stream didn't write out all of its
1906 // bytes. Register for 'immediate' resumption so we'll keep writing after
1907 // other connections and events have had a chance to use the thread.
1908 send_alarm_->Set(clock_->ApproximateNow());
1909 }
1910}
1911
1912void QuicConnection::WriteIfNotBlocked() {
1913 if (!HandleWriteBlocked()) {
1914 OnCanWrite();
1915 }
1916}
1917
1918void QuicConnection::WriteAndBundleAcksIfNotBlocked() {
1919 if (!HandleWriteBlocked()) {
1920 ScopedPacketFlusher flusher(this, SEND_ACK_IF_QUEUED);
1921 WriteIfNotBlocked();
1922 }
1923}
1924
1925bool QuicConnection::ProcessValidatedPacket(const QuicPacketHeader& header) {
1926 if (perspective_ == Perspective::IS_SERVER && self_address_.IsInitialized() &&
1927 last_packet_destination_address_.IsInitialized() &&
1928 self_address_ != last_packet_destination_address_) {
1929 // Allow change between pure IPv4 and equivalent mapped IPv4 address.
1930 if (self_address_.port() != last_packet_destination_address_.port() ||
1931 self_address_.host().Normalized() !=
1932 last_packet_destination_address_.host().Normalized()) {
1933 if (!visitor_->AllowSelfAddressChange()) {
1934 CloseConnection(
1935 QUIC_ERROR_MIGRATING_ADDRESS,
1936 "Self address migration is not supported at the server.",
1937 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
1938 return false;
1939 }
1940 }
1941 self_address_ = last_packet_destination_address_;
1942 }
1943
QUICHE teamd791e2c2019-03-15 10:28:21 -07001944 if (!ValidateReceivedPacketNumber(header.packet_number)) {
1945 return false;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001946 }
1947
1948 if (version_negotiation_state_ != NEGOTIATED_VERSION) {
1949 if (perspective_ == Perspective::IS_CLIENT) {
1950 DCHECK(!header.version_flag || header.form != GOOGLE_QUIC_PACKET);
1951 if (framer_.transport_version() <= QUIC_VERSION_43) {
1952 // If the client gets a packet without the version flag from the server
1953 // it should stop sending version since the version negotiation is done.
1954 // IETF QUIC stops sending version once encryption level switches to
1955 // forward secure.
1956 packet_generator_.StopSendingVersion();
1957 }
1958 version_negotiation_state_ = NEGOTIATED_VERSION;
1959 visitor_->OnSuccessfulVersionNegotiation(version());
1960 if (debug_visitor_ != nullptr) {
1961 debug_visitor_->OnSuccessfulVersionNegotiation(version());
1962 }
1963 }
1964 }
1965
1966 if (last_size_ > largest_received_packet_size_) {
1967 largest_received_packet_size_ = last_size_;
1968 }
1969
1970 if (perspective_ == Perspective::IS_SERVER &&
QUICHE team6987b4a2019-03-15 16:23:04 -07001971 encryption_level_ == ENCRYPTION_INITIAL &&
QUICHE teama6ef0a62019-03-07 20:34:33 -05001972 last_size_ > packet_generator_.GetCurrentMaxPacketLength()) {
1973 SetMaxPacketLength(last_size_);
1974 }
1975 return true;
1976}
1977
QUICHE teamd791e2c2019-03-15 10:28:21 -07001978bool QuicConnection::ValidateReceivedPacketNumber(
1979 QuicPacketNumber packet_number) {
1980 if (GetQuicRestartFlag(quic_enable_accept_random_ipn)) {
1981 QUIC_RESTART_FLAG_COUNT_N(quic_enable_accept_random_ipn, 2, 2);
1982 // Configured to accept any packet number in range 1...0x7fffffff as initial
1983 // packet number.
1984 bool out_of_bound = false;
1985 string error_detail = "Packet number out of bounds.";
1986 if (last_header_.packet_number.IsInitialized()) {
1987 out_of_bound = !Near(packet_number, last_header_.packet_number);
1988 } else if ((packet_number > MaxRandomInitialPacketNumber())) {
1989 out_of_bound = true;
1990 error_detail = "Initial packet number out of bounds.";
1991 }
1992 if (out_of_bound) {
1993 QUIC_DLOG(INFO) << ENDPOINT << "Packet " << packet_number
1994 << " out of bounds. Discarding";
1995 CloseConnection(QUIC_INVALID_PACKET_HEADER, error_detail,
1996 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
1997 return false;
1998 }
1999 return true;
2000 }
2001
2002 if (packet_number > received_packet_manager_.PeerFirstSendingPacketNumber() &&
2003 packet_number <= MaxRandomInitialPacketNumber()) {
2004 QUIC_CODE_COUNT_N(had_possibly_random_ipn, 2, 2);
2005 }
2006 const bool out_of_bound =
2007 last_header_.packet_number.IsInitialized()
2008 ? !Near(packet_number, last_header_.packet_number)
2009 : packet_number >=
2010 (received_packet_manager_.PeerFirstSendingPacketNumber() +
2011 kMaxPacketGap);
2012 if (!out_of_bound) {
2013 return true;
2014 }
2015 QUIC_DLOG(INFO) << ENDPOINT << "Packet " << packet_number
2016 << " out of bounds. Discarding";
2017 QuicStringPiece packet_data = GetCurrentPacket();
2018 const size_t kMaxPacketLengthInErrorDetails = 64;
2019 CloseConnection(
2020 QUIC_INVALID_PACKET_HEADER,
2021 QuicStrCat(
2022 "Packet number out of bounds. ",
2023 last_header_.packet_number.IsInitialized()
2024 ? QuicStrCat("last_pkn=", last_header_.packet_number.ToUint64())
2025 : "first received packet",
2026 ", current_pkn=", packet_number.ToUint64(),
2027 ", current_pkt_len=", packet_data.length(), ", current_hdr=",
2028 QuicTextUtils::HexEncode(
2029 packet_data.length() > kMaxPacketLengthInErrorDetails
2030 ? QuicStringPiece(packet_data.data(),
2031 kMaxPacketLengthInErrorDetails)
2032 : packet_data)),
2033 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
2034 return false;
2035}
2036
QUICHE teama6ef0a62019-03-07 20:34:33 -05002037void QuicConnection::WriteQueuedPackets() {
2038 DCHECK(!writer_->IsWriteBlocked());
2039
2040 if (pending_version_negotiation_packet_) {
2041 SendVersionNegotiationPacket(send_ietf_version_negotiation_packet_);
2042 }
2043
2044 QUIC_CLIENT_HISTOGRAM_COUNTS("QuicSession.NumQueuedPacketsBeforeWrite",
2045 queued_packets_.size(), 1, 1000, 50, "");
2046 while (!queued_packets_.empty()) {
2047 // WritePacket() can potentially clear all queued packets, so we need to
2048 // save the first queued packet to a local variable before calling it.
2049 SerializedPacket packet(std::move(queued_packets_.front()));
2050 queued_packets_.pop_front();
2051
2052 const bool write_result = WritePacket(&packet);
2053
2054 if (connected_ && !write_result) {
2055 // Write failed but connection is open, re-insert |packet| into the
2056 // front of the queue, it will be retried later.
2057 queued_packets_.emplace_front(std::move(packet));
2058 break;
2059 }
2060
2061 delete[] packet.encrypted_buffer;
2062 ClearSerializedPacket(&packet);
2063 if (!connected_) {
2064 DCHECK(queued_packets_.empty()) << "Queued packets should have been "
2065 "cleared while closing connection";
2066 break;
2067 }
2068
2069 // Continue to send the next packet in queue.
2070 }
2071}
2072
2073void QuicConnection::WritePendingRetransmissions() {
2074 DCHECK(!session_decides_what_to_write());
2075 // Keep writing as long as there's a pending retransmission which can be
2076 // written.
2077 while (sent_packet_manager_.HasPendingRetransmissions() &&
2078 CanWrite(HAS_RETRANSMITTABLE_DATA)) {
2079 const QuicPendingRetransmission pending =
2080 sent_packet_manager_.NextPendingRetransmission();
2081
2082 // Re-packetize the frames with a new packet number for retransmission.
2083 // Retransmitted packets use the same packet number length as the
2084 // original.
2085 // Flush the packet generator before making a new packet.
2086 // TODO(ianswett): Implement ReserializeAllFrames as a separate path that
2087 // does not require the creator to be flushed.
2088 // TODO(fayang): FlushAllQueuedFrames should only be called once, and should
2089 // be moved outside of the loop. Also, CanWrite is not checked after the
2090 // generator is flushed.
2091 {
2092 ScopedPacketFlusher flusher(this, NO_ACK);
2093 packet_generator_.FlushAllQueuedFrames();
2094 }
2095 DCHECK(!packet_generator_.HasQueuedFrames());
2096 char buffer[kMaxPacketSize];
2097 packet_generator_.ReserializeAllFrames(pending, buffer, kMaxPacketSize);
2098 }
2099}
2100
2101void QuicConnection::SendProbingRetransmissions() {
2102 while (sent_packet_manager_.GetSendAlgorithm()->ShouldSendProbingPacket() &&
2103 CanWrite(HAS_RETRANSMITTABLE_DATA)) {
2104 const bool can_retransmit =
2105 sent_packet_manager_.MaybeRetransmitOldestPacket(
2106 PROBING_RETRANSMISSION);
2107 if (!can_retransmit) {
2108 QUIC_DVLOG(1)
2109 << "Cannot send probing retransmissions: nothing to retransmit.";
2110 break;
2111 }
2112
2113 if (!session_decides_what_to_write()) {
2114 DCHECK(sent_packet_manager_.HasPendingRetransmissions());
2115 WritePendingRetransmissions();
2116 }
2117 }
2118}
2119
2120void QuicConnection::RetransmitUnackedPackets(
2121 TransmissionType retransmission_type) {
2122 sent_packet_manager_.RetransmitUnackedPackets(retransmission_type);
2123
2124 WriteIfNotBlocked();
2125}
2126
2127void QuicConnection::NeuterUnencryptedPackets() {
2128 sent_packet_manager_.NeuterUnencryptedPackets();
2129 // This may have changed the retransmission timer, so re-arm it.
2130 SetRetransmissionAlarm();
2131}
2132
2133bool QuicConnection::ShouldGeneratePacket(
2134 HasRetransmittableData retransmittable,
2135 IsHandshake handshake) {
2136 // We should serialize handshake packets immediately to ensure that they
2137 // end up sent at the right encryption level.
2138 if (handshake == IS_HANDSHAKE) {
2139 return true;
2140 }
2141
2142 return CanWrite(retransmittable);
2143}
2144
2145const QuicFrames QuicConnection::MaybeBundleAckOpportunistically() {
2146 DCHECK(packet_generator_.deprecate_ack_bundling_mode());
2147 QuicFrames frames;
2148 bool has_pending_ack = false;
2149 if (received_packet_manager_.decide_when_to_send_acks()) {
2150 has_pending_ack = received_packet_manager_.ack_timeout().IsInitialized();
2151 } else {
2152 has_pending_ack = ack_alarm_->IsSet();
2153 }
2154 if (!has_pending_ack && stop_waiting_count_ <= 1) {
2155 // No need to send an ACK.
2156 return frames;
2157 }
2158 ResetAckStates();
2159
2160 QUIC_DVLOG(1) << ENDPOINT << "Bundle an ACK opportunistically";
2161 frames.push_back(GetUpdatedAckFrame());
2162 if (!no_stop_waiting_frames_) {
2163 QuicStopWaitingFrame stop_waiting;
2164 PopulateStopWaitingFrame(&stop_waiting);
2165 frames.push_back(QuicFrame(stop_waiting));
2166 }
2167 return frames;
2168}
2169
2170bool QuicConnection::CanWrite(HasRetransmittableData retransmittable) {
2171 if (!connected_) {
2172 return false;
2173 }
2174
2175 if (session_decides_what_to_write() &&
2176 sent_packet_manager_.pending_timer_transmission_count() > 0) {
2177 // Force sending the retransmissions for HANDSHAKE, TLP, RTO, PROBING cases.
2178 return true;
2179 }
2180
2181 if (HandleWriteBlocked()) {
2182 return false;
2183 }
2184
2185 // Allow acks to be sent immediately.
2186 if (retransmittable == NO_RETRANSMITTABLE_DATA) {
2187 return true;
2188 }
2189 // If the send alarm is set, wait for it to fire.
2190 if (send_alarm_->IsSet()) {
2191 return false;
2192 }
2193
2194 QuicTime now = clock_->Now();
2195 QuicTime::Delta delay = sent_packet_manager_.TimeUntilSend(now);
2196 if (delay.IsInfinite()) {
2197 send_alarm_->Cancel();
2198 return false;
2199 }
2200
2201 // Scheduler requires a delay.
2202 if (!delay.IsZero()) {
2203 if (delay <= release_time_into_future_) {
2204 // Required delay is within pace time into future, send now.
2205 return true;
2206 }
2207 // Cannot send packet now because delay is too far in the future.
2208 send_alarm_->Update(now + delay, QuicTime::Delta::FromMilliseconds(1));
2209 QUIC_DVLOG(1) << ENDPOINT << "Delaying sending " << delay.ToMilliseconds()
2210 << "ms";
2211 return false;
2212 }
2213 return true;
2214}
2215
2216bool QuicConnection::WritePacket(SerializedPacket* packet) {
2217 if (ShouldDiscardPacket(*packet)) {
2218 ++stats_.packets_discarded;
2219 return true;
2220 }
2221 if (sent_packet_manager_.GetLargestSentPacket().IsInitialized() &&
2222 packet->packet_number < sent_packet_manager_.GetLargestSentPacket()) {
2223 QUIC_BUG << "Attempt to write packet:" << packet->packet_number
2224 << " after:" << sent_packet_manager_.GetLargestSentPacket();
2225 QUIC_CLIENT_HISTOGRAM_COUNTS("QuicSession.NumQueuedPacketsAtOutOfOrder",
2226 queued_packets_.size(), 1, 1000, 50, "");
2227 CloseConnection(QUIC_INTERNAL_ERROR, "Packet written out of order.",
2228 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
2229 return true;
2230 }
2231 // Termination packets are encrypted and saved, so don't exit early.
2232 const bool is_termination_packet = IsTerminationPacket(*packet);
2233 if (HandleWriteBlocked() && !is_termination_packet) {
2234 return false;
2235 }
2236
2237 QuicPacketNumber packet_number = packet->packet_number;
2238
2239 QuicPacketLength encrypted_length = packet->encrypted_length;
2240 // Termination packets are eventually owned by TimeWaitListManager.
2241 // Others are deleted at the end of this call.
2242 if (is_termination_packet) {
2243 if (termination_packets_ == nullptr) {
2244 termination_packets_.reset(
2245 new std::vector<std::unique_ptr<QuicEncryptedPacket>>);
2246 }
2247 // Copy the buffer so it's owned in the future.
2248 char* buffer_copy = CopyBuffer(*packet);
2249 termination_packets_->emplace_back(
2250 new QuicEncryptedPacket(buffer_copy, encrypted_length, true));
2251 // This assures we won't try to write *forced* packets when blocked.
2252 // Return true to stop processing.
2253 if (HandleWriteBlocked()) {
2254 return true;
2255 }
2256 }
2257
2258 DCHECK_LE(encrypted_length, kMaxPacketSize);
2259 DCHECK_LE(encrypted_length, packet_generator_.GetCurrentMaxPacketLength());
2260 QUIC_DVLOG(1) << ENDPOINT << "Sending packet " << packet_number << " : "
2261 << (IsRetransmittable(*packet) == HAS_RETRANSMITTABLE_DATA
2262 ? "data bearing "
2263 : " ack only ")
2264 << ", encryption level: "
2265 << QuicUtils::EncryptionLevelToString(packet->encryption_level)
2266 << ", encrypted length:" << encrypted_length;
2267 QUIC_DVLOG(2) << ENDPOINT << "packet(" << packet_number << "): " << std::endl
2268 << QuicTextUtils::HexDump(QuicStringPiece(
2269 packet->encrypted_buffer, encrypted_length));
2270
2271 // Measure the RTT from before the write begins to avoid underestimating the
2272 // min_rtt_, especially in cases where the thread blocks or gets swapped out
2273 // during the WritePacket below.
2274 QuicTime packet_send_time = clock_->Now();
2275 if (supports_release_time_ && per_packet_options_ != nullptr) {
2276 QuicTime next_release_time = sent_packet_manager_.GetNextReleaseTime();
2277 QuicTime::Delta release_time_delay = QuicTime::Delta::Zero();
2278 QuicTime now = packet_send_time;
2279 if (next_release_time > now) {
2280 release_time_delay = next_release_time - now;
2281 // Set packet_send_time to the future to make the RTT estimation accurate.
2282 packet_send_time = next_release_time;
2283 }
2284 per_packet_options_->release_time_delay = release_time_delay;
2285 }
2286 WriteResult result = writer_->WritePacket(
2287 packet->encrypted_buffer, encrypted_length, self_address().host(),
2288 peer_address(), per_packet_options_);
2289
2290 QUIC_HISTOGRAM_ENUM(
2291 "QuicConnection.WritePacketStatus", result.status,
2292 WRITE_STATUS_NUM_VALUES,
2293 "Status code returned by writer_->WritePacket() in QuicConnection.");
2294
2295 if (IsWriteBlockedStatus(result.status)) {
2296 // Ensure the writer is still write blocked, otherwise QUIC may continue
2297 // trying to write when it will not be able to.
2298 DCHECK(writer_->IsWriteBlocked());
2299 visitor_->OnWriteBlocked();
2300 // If the socket buffers the data, then the packet should not
2301 // be queued and sent again, which would result in an unnecessary
2302 // duplicate packet being sent. The helper must call OnCanWrite
2303 // when the write completes, and OnWriteError if an error occurs.
2304 if (result.status != WRITE_STATUS_BLOCKED_DATA_BUFFERED) {
2305 return false;
2306 }
2307 }
2308
2309 // In some cases, an MTU probe can cause EMSGSIZE. This indicates that the
2310 // MTU discovery is permanently unsuccessful.
2311 if (IsMsgTooBig(result) && packet->retransmittable_frames.empty() &&
2312 packet->encrypted_length > long_term_mtu_) {
2313 mtu_discovery_target_ = 0;
2314 mtu_discovery_alarm_->Cancel();
2315 // The write failed, but the writer is not blocked, so return true.
2316 return true;
2317 }
2318
2319 if (IsWriteError(result.status)) {
2320 OnWriteError(result.error_code);
2321 QUIC_LOG_FIRST_N(ERROR, 10)
2322 << ENDPOINT << "failed writing " << encrypted_length
2323 << " bytes from host " << self_address().host().ToString()
2324 << " to address " << peer_address().ToString() << " with error code "
2325 << result.error_code;
2326 return false;
2327 }
2328
2329 if (debug_visitor_ != nullptr) {
2330 // Pass the write result to the visitor.
2331 debug_visitor_->OnPacketSent(*packet, packet->original_packet_number,
2332 packet->transmission_type, packet_send_time);
2333 }
2334 if (IsRetransmittable(*packet) == HAS_RETRANSMITTABLE_DATA) {
2335 if (!is_path_degrading_ && !path_degrading_alarm_->IsSet()) {
2336 // This is the first retransmittable packet on the working path.
2337 // Start the path degrading alarm to detect new path degrading.
2338 SetPathDegradingAlarm();
2339 }
2340
2341 if (GetQuicReloadableFlag(
2342 quic_fix_time_of_first_packet_sent_after_receiving)) {
2343 // Update |time_of_first_packet_sent_after_receiving_| if this is the
2344 // first packet sent after the last packet was received. If it were
2345 // updated on every sent packet, then sending into a black hole might
2346 // never timeout.
2347 if (time_of_first_packet_sent_after_receiving_ <
2348 time_of_last_received_packet_) {
2349 QUIC_RELOADABLE_FLAG_COUNT(
2350 quic_fix_time_of_first_packet_sent_after_receiving);
2351 time_of_first_packet_sent_after_receiving_ = packet_send_time;
2352 }
2353 } else {
2354 // Only adjust the last sent time (for the purpose of tracking the idle
2355 // timeout) if this is the first retransmittable packet sent after a
2356 // packet is received. If it were updated on every sent packet, then
2357 // sending into a black hole might never timeout.
2358 if (time_of_first_packet_sent_after_receiving_ <=
2359 time_of_last_received_packet_) {
2360 time_of_first_packet_sent_after_receiving_ = packet_send_time;
2361 }
2362 }
2363 }
2364
2365 MaybeSetMtuAlarm(packet_number);
2366 QUIC_DVLOG(1) << ENDPOINT << "time we began writing last sent packet: "
2367 << packet_send_time.ToDebuggingValue();
2368
2369 bool reset_retransmission_alarm = sent_packet_manager_.OnPacketSent(
2370 packet, packet->original_packet_number, packet_send_time,
2371 packet->transmission_type, IsRetransmittable(*packet));
2372
2373 if (reset_retransmission_alarm || !retransmission_alarm_->IsSet()) {
2374 SetRetransmissionAlarm();
2375 }
2376 SetPingAlarm();
2377
2378 // The packet number length must be updated after OnPacketSent, because it
2379 // may change the packet number length in packet.
2380 packet_generator_.UpdatePacketNumberLength(
2381 sent_packet_manager_.GetLeastUnacked(),
2382 sent_packet_manager_.EstimateMaxPacketsInFlight(max_packet_length()));
2383
2384 stats_.bytes_sent += result.bytes_written;
2385 ++stats_.packets_sent;
2386 if (packet->transmission_type != NOT_RETRANSMISSION) {
2387 stats_.bytes_retransmitted += result.bytes_written;
2388 ++stats_.packets_retransmitted;
2389 }
2390
2391 return true;
2392}
2393
2394void QuicConnection::FlushPackets() {
2395 if (!connected_) {
2396 return;
2397 }
2398
2399 if (!writer_->IsBatchMode()) {
2400 return;
2401 }
2402
2403 if (HandleWriteBlocked()) {
2404 QUIC_DLOG(INFO) << ENDPOINT << "FlushPackets called while blocked.";
2405 return;
2406 }
2407
2408 WriteResult result = writer_->Flush();
2409
2410 if (HandleWriteBlocked()) {
2411 DCHECK_EQ(WRITE_STATUS_BLOCKED, result.status)
2412 << "Unexpected flush result:" << result;
2413 QUIC_DLOG(INFO) << ENDPOINT << "Write blocked in FlushPackets.";
2414 return;
2415 }
2416
2417 if (IsWriteError(result.status)) {
2418 OnWriteError(result.error_code);
2419 }
2420}
2421
2422bool QuicConnection::IsMsgTooBig(const WriteResult& result) {
2423 return (result.status == WRITE_STATUS_MSG_TOO_BIG) ||
2424 (IsWriteError(result.status) && result.error_code == QUIC_EMSGSIZE);
2425}
2426
2427bool QuicConnection::ShouldDiscardPacket(const SerializedPacket& packet) {
2428 if (!connected_) {
2429 QUIC_DLOG(INFO) << ENDPOINT
2430 << "Not sending packet as connection is disconnected.";
2431 return true;
2432 }
2433
2434 QuicPacketNumber packet_number = packet.packet_number;
2435 if (encryption_level_ == ENCRYPTION_FORWARD_SECURE &&
QUICHE team6987b4a2019-03-15 16:23:04 -07002436 packet.encryption_level == ENCRYPTION_INITIAL) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002437 // Drop packets that are NULL encrypted since the peer won't accept them
2438 // anymore.
2439 QUIC_DLOG(INFO) << ENDPOINT
2440 << "Dropping NULL encrypted packet: " << packet_number
2441 << " since the connection is forward secure.";
2442 return true;
2443 }
2444
2445 return false;
2446}
2447
2448void QuicConnection::OnWriteError(int error_code) {
2449 if (write_error_occurred_) {
2450 // A write error already occurred. The connection is being closed.
2451 return;
2452 }
2453 write_error_occurred_ = true;
2454
vasilvvc48c8712019-03-11 13:38:16 -07002455 const std::string error_details = QuicStrCat(
QUICHE teama6ef0a62019-03-07 20:34:33 -05002456 "Write failed with error: ", error_code, " (", strerror(error_code), ")");
2457 QUIC_LOG_FIRST_N(ERROR, 2) << ENDPOINT << error_details;
2458 switch (error_code) {
2459 case QUIC_EMSGSIZE:
2460 CloseConnection(
2461 QUIC_PACKET_WRITE_ERROR, error_details,
2462 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET_WITH_NO_ACK);
2463 break;
2464 default:
2465 // We can't send an error as the socket is presumably borked.
2466 if (transport_version() > QUIC_VERSION_43) {
2467 QUIC_CODE_COUNT(quic_tear_down_local_connection_on_write_error_ietf);
2468 } else {
2469 QUIC_CODE_COUNT(
2470 quic_tear_down_local_connection_on_write_error_non_ietf);
2471 }
2472 TearDownLocalConnectionState(QUIC_PACKET_WRITE_ERROR, error_details,
2473 ConnectionCloseSource::FROM_SELF);
2474 }
2475}
2476
2477char* QuicConnection::GetPacketBuffer() {
2478 return writer_->GetNextWriteLocation(self_address().host(), peer_address());
2479}
2480
2481void QuicConnection::OnSerializedPacket(SerializedPacket* serialized_packet) {
2482 if (serialized_packet->encrypted_buffer == nullptr) {
2483 // We failed to serialize the packet, so close the connection.
2484 // TearDownLocalConnectionState does not send close packet, so no infinite
2485 // loop here.
2486 // TODO(ianswett): This is actually an internal error, not an
2487 // encryption failure.
2488 if (transport_version() > QUIC_VERSION_43) {
2489 QUIC_CODE_COUNT(
2490 quic_tear_down_local_connection_on_serialized_packet_ietf);
2491 } else {
2492 QUIC_CODE_COUNT(
2493 quic_tear_down_local_connection_on_serialized_packet_non_ietf);
2494 }
2495 TearDownLocalConnectionState(
2496 QUIC_ENCRYPTION_FAILURE,
2497 "Serialized packet does not have an encrypted buffer.",
2498 ConnectionCloseSource::FROM_SELF);
2499 return;
2500 }
2501
2502 if (serialized_packet->retransmittable_frames.empty() &&
2503 !serialized_packet->original_packet_number.IsInitialized()) {
2504 // Increment consecutive_num_packets_with_no_retransmittable_frames_ if
2505 // this packet is a new transmission with no retransmittable frames.
2506 ++consecutive_num_packets_with_no_retransmittable_frames_;
2507 } else {
2508 consecutive_num_packets_with_no_retransmittable_frames_ = 0;
2509 }
2510 SendOrQueuePacket(serialized_packet);
2511}
2512
2513void QuicConnection::OnUnrecoverableError(QuicErrorCode error,
vasilvvc48c8712019-03-11 13:38:16 -07002514 const std::string& error_details,
QUICHE teama6ef0a62019-03-07 20:34:33 -05002515 ConnectionCloseSource source) {
2516 // The packet creator or generator encountered an unrecoverable error: tear
2517 // down local connection state immediately.
2518 if (transport_version() > QUIC_VERSION_43) {
2519 QUIC_CODE_COUNT(
2520 quic_tear_down_local_connection_on_unrecoverable_error_ietf);
2521 } else {
2522 QUIC_CODE_COUNT(
2523 quic_tear_down_local_connection_on_unrecoverable_error_non_ietf);
2524 }
2525 TearDownLocalConnectionState(error, error_details, source);
2526}
2527
2528void QuicConnection::OnCongestionChange() {
2529 visitor_->OnCongestionWindowChange(clock_->ApproximateNow());
2530
2531 // Uses the connection's smoothed RTT. If zero, uses initial_rtt.
2532 QuicTime::Delta rtt = sent_packet_manager_.GetRttStats()->smoothed_rtt();
2533 if (rtt.IsZero()) {
2534 rtt = sent_packet_manager_.GetRttStats()->initial_rtt();
2535 }
2536
2537 if (debug_visitor_ != nullptr) {
2538 debug_visitor_->OnRttChanged(rtt);
2539 }
2540}
2541
2542void QuicConnection::OnPathMtuIncreased(QuicPacketLength packet_size) {
2543 if (packet_size > max_packet_length()) {
2544 SetMaxPacketLength(packet_size);
2545 }
2546}
2547
2548void QuicConnection::OnHandshakeComplete() {
2549 sent_packet_manager_.SetHandshakeConfirmed();
2550 if (sent_packet_manager_.unacked_packets().use_uber_loss_algorithm()) {
2551 // This may have changed the retransmission timer, so re-arm it.
2552 SetRetransmissionAlarm();
2553 }
2554 // The client should immediately ack the SHLO to confirm the handshake is
2555 // complete with the server.
2556 if (perspective_ == Perspective::IS_CLIENT && !ack_queued_ &&
2557 ack_frame_updated()) {
2558 ack_alarm_->Update(clock_->ApproximateNow(), QuicTime::Delta::Zero());
2559 }
2560}
2561
2562void QuicConnection::SendOrQueuePacket(SerializedPacket* packet) {
2563 // The caller of this function is responsible for checking CanWrite().
2564 if (packet->encrypted_buffer == nullptr) {
2565 QUIC_BUG << "packet.encrypted_buffer == nullptr in to SendOrQueuePacket";
2566 return;
2567 }
2568 // If there are already queued packets, queue this one immediately to ensure
2569 // it's written in sequence number order.
2570 if (!queued_packets_.empty() || !WritePacket(packet)) {
2571 // Take ownership of the underlying encrypted packet.
2572 packet->encrypted_buffer = CopyBuffer(*packet);
2573 queued_packets_.push_back(*packet);
2574 packet->retransmittable_frames.clear();
2575 }
2576
2577 ClearSerializedPacket(packet);
2578}
2579
2580void QuicConnection::OnPingTimeout() {
2581 if (!retransmission_alarm_->IsSet()) {
2582 visitor_->SendPing();
2583 }
2584}
2585
2586void QuicConnection::SendAck() {
2587 if (!received_packet_manager_.decide_when_to_send_acks()) {
2588 // When received_packet_manager decides when to send ack, delaying
2589 // ResetAckStates until ACK is successfully flushed.
2590 ResetAckStates();
2591 }
2592
2593 if (packet_generator_.deprecate_ack_bundling_mode()) {
2594 QUIC_DVLOG(1) << ENDPOINT << "Sending an ACK proactively";
2595 QuicFrames frames;
2596 frames.push_back(GetUpdatedAckFrame());
2597 if (!no_stop_waiting_frames_) {
2598 QuicStopWaitingFrame stop_waiting;
2599 PopulateStopWaitingFrame(&stop_waiting);
2600 frames.push_back(QuicFrame(stop_waiting));
2601 }
2602 if (received_packet_manager_.decide_when_to_send_acks()) {
2603 if (!packet_generator_.FlushAckFrame(frames)) {
2604 return;
2605 }
2606 ResetAckStates();
2607 } else {
2608 send_ack_when_on_can_write_ = !packet_generator_.FlushAckFrame(frames);
2609 }
2610 } else {
2611 packet_generator_.SetShouldSendAck(!no_stop_waiting_frames_);
2612 }
2613 if (consecutive_num_packets_with_no_retransmittable_frames_ <
2614 max_consecutive_num_packets_with_no_retransmittable_frames_) {
2615 return;
2616 }
2617 consecutive_num_packets_with_no_retransmittable_frames_ = 0;
2618 if (packet_generator_.HasRetransmittableFrames() ||
2619 visitor_->WillingAndAbleToWrite()) {
2620 // There are pending retransmittable frames.
2621 return;
2622 }
2623
2624 visitor_->OnAckNeedsRetransmittableFrame();
2625}
2626
2627void QuicConnection::OnPathDegradingTimeout() {
2628 is_path_degrading_ = true;
2629 visitor_->OnPathDegrading();
2630}
2631
2632void QuicConnection::OnRetransmissionTimeout() {
2633 DCHECK(!sent_packet_manager_.unacked_packets().empty());
2634 if (close_connection_after_five_rtos_ &&
2635 sent_packet_manager_.GetConsecutiveRtoCount() >= 4) {
2636 // Close on the 5th consecutive RTO, so after 4 previous RTOs have occurred.
2637 CloseConnection(QUIC_TOO_MANY_RTOS, "5 consecutive retransmission timeouts",
2638 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
2639 return;
2640 }
2641
2642 sent_packet_manager_.OnRetransmissionTimeout();
2643 WriteIfNotBlocked();
2644
2645 // A write failure can result in the connection being closed, don't attempt to
2646 // write further packets, or to set alarms.
2647 if (!connected_) {
2648 return;
2649 }
2650
2651 // In the TLP case, the SentPacketManager gives the connection the opportunity
2652 // to send new data before retransmitting.
2653 if (sent_packet_manager_.MaybeRetransmitTailLossProbe()) {
2654 // Send the pending retransmission now that it's been queued.
2655 WriteIfNotBlocked();
2656 }
2657
2658 // Ensure the retransmission alarm is always set if there are unacked packets
2659 // and nothing waiting to be sent.
2660 // This happens if the loss algorithm invokes a timer based loss, but the
2661 // packet doesn't need to be retransmitted.
2662 if (!HasQueuedData() && !retransmission_alarm_->IsSet()) {
2663 SetRetransmissionAlarm();
2664 }
2665}
2666
2667void QuicConnection::SetEncrypter(EncryptionLevel level,
2668 std::unique_ptr<QuicEncrypter> encrypter) {
2669 packet_generator_.SetEncrypter(level, std::move(encrypter));
2670}
2671
2672void QuicConnection::SetDiversificationNonce(
2673 const DiversificationNonce& nonce) {
2674 DCHECK_EQ(Perspective::IS_SERVER, perspective_);
2675 packet_generator_.SetDiversificationNonce(nonce);
2676}
2677
2678void QuicConnection::SetDefaultEncryptionLevel(EncryptionLevel level) {
2679 if (level != encryption_level_ && packet_generator_.HasQueuedFrames()) {
2680 // Flush all queued frames when encryption level changes.
2681 ScopedPacketFlusher flusher(this, NO_ACK);
2682 packet_generator_.FlushAllQueuedFrames();
2683 }
2684 encryption_level_ = level;
2685 packet_generator_.set_encryption_level(level);
2686}
2687
2688void QuicConnection::SetDecrypter(EncryptionLevel level,
2689 std::unique_ptr<QuicDecrypter> decrypter) {
2690 framer_.SetDecrypter(level, std::move(decrypter));
2691
2692 if (!undecryptable_packets_.empty() &&
2693 !process_undecryptable_packets_alarm_->IsSet()) {
2694 process_undecryptable_packets_alarm_->Set(clock_->ApproximateNow());
2695 }
2696}
2697
2698void QuicConnection::SetAlternativeDecrypter(
2699 EncryptionLevel level,
2700 std::unique_ptr<QuicDecrypter> decrypter,
2701 bool latch_once_used) {
2702 framer_.SetAlternativeDecrypter(level, std::move(decrypter), latch_once_used);
2703
2704 if (!undecryptable_packets_.empty() &&
2705 !process_undecryptable_packets_alarm_->IsSet()) {
2706 process_undecryptable_packets_alarm_->Set(clock_->ApproximateNow());
2707 }
2708}
2709
2710const QuicDecrypter* QuicConnection::decrypter() const {
2711 return framer_.decrypter();
2712}
2713
2714const QuicDecrypter* QuicConnection::alternative_decrypter() const {
2715 return framer_.alternative_decrypter();
2716}
2717
2718void QuicConnection::QueueUndecryptablePacket(
2719 const QuicEncryptedPacket& packet) {
2720 QUIC_DVLOG(1) << ENDPOINT << "Queueing undecryptable packet.";
2721 undecryptable_packets_.push_back(packet.Clone());
2722}
2723
2724void QuicConnection::MaybeProcessUndecryptablePackets() {
2725 process_undecryptable_packets_alarm_->Cancel();
2726
QUICHE team6987b4a2019-03-15 16:23:04 -07002727 if (undecryptable_packets_.empty() ||
2728 encryption_level_ == ENCRYPTION_INITIAL) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002729 return;
2730 }
2731
2732 while (connected_ && !undecryptable_packets_.empty()) {
2733 // Making sure there is no pending frames when processing next undecrypted
2734 // packet because the queued ack frame may change.
2735 packet_generator_.FlushAllQueuedFrames();
2736 if (!connected_) {
2737 return;
2738 }
2739 QUIC_DVLOG(1) << ENDPOINT << "Attempting to process undecryptable packet";
2740 QuicEncryptedPacket* packet = undecryptable_packets_.front().get();
2741 if (!framer_.ProcessPacket(*packet) &&
2742 framer_.error() == QUIC_DECRYPTION_FAILURE) {
2743 QUIC_DVLOG(1) << ENDPOINT << "Unable to process undecryptable packet...";
2744 break;
2745 }
2746 QUIC_DVLOG(1) << ENDPOINT << "Processed undecryptable packet!";
2747 ++stats_.packets_processed;
2748 undecryptable_packets_.pop_front();
2749 }
2750
2751 // Once forward secure encryption is in use, there will be no
2752 // new keys installed and hence any undecryptable packets will
2753 // never be able to be decrypted.
2754 if (encryption_level_ == ENCRYPTION_FORWARD_SECURE) {
2755 if (debug_visitor_ != nullptr) {
2756 // TODO(rtenneti): perhaps more efficient to pass the number of
2757 // undecryptable packets as the argument to OnUndecryptablePacket so that
2758 // we just need to call OnUndecryptablePacket once?
2759 for (size_t i = 0; i < undecryptable_packets_.size(); ++i) {
2760 debug_visitor_->OnUndecryptablePacket();
2761 }
2762 }
2763 undecryptable_packets_.clear();
2764 }
2765}
2766
2767void QuicConnection::QueueCoalescedPacket(const QuicEncryptedPacket& packet) {
2768 QUIC_DVLOG(1) << ENDPOINT << "Queueing coalesced packet.";
2769 coalesced_packets_.push_back(packet.Clone());
2770}
2771
2772void QuicConnection::MaybeProcessCoalescedPackets() {
2773 bool processed = false;
2774 for (const auto& packet : coalesced_packets_) {
2775 if (!connected_) {
2776 return;
2777 }
2778
2779 // }
2780 // while (connected_ && !coalesced_packets_.empty()) {
2781 QUIC_DVLOG(1) << ENDPOINT << "Processing coalesced packet";
2782 // QuicEncryptedPacket* packet = coalesced_packets_.front().get();
2783 if (framer_.ProcessPacket(*packet)) {
2784 processed = true;
2785 } else {
2786 // If we are unable to decrypt this packet, it might be
2787 // because the CHLO or SHLO packet was lost.
2788 if (framer_.error() == QUIC_DECRYPTION_FAILURE) {
2789 if (encryption_level_ != ENCRYPTION_FORWARD_SECURE &&
2790 undecryptable_packets_.size() < max_undecryptable_packets_) {
2791 QueueUndecryptablePacket(*packet);
2792 } else if (debug_visitor_ != nullptr) {
2793 debug_visitor_->OnUndecryptablePacket();
2794 }
2795 }
2796 }
2797 // coalesced_packets_.pop_front();
2798 }
2799 coalesced_packets_.clear();
2800 if (processed) {
2801 MaybeProcessUndecryptablePackets();
2802 }
2803}
2804
2805void QuicConnection::CloseConnection(
2806 QuicErrorCode error,
vasilvvc48c8712019-03-11 13:38:16 -07002807 const std::string& error_details,
QUICHE teama6ef0a62019-03-07 20:34:33 -05002808 ConnectionCloseBehavior connection_close_behavior) {
2809 DCHECK(!error_details.empty());
2810 if (!connected_) {
2811 QUIC_DLOG(INFO) << "Connection is already closed.";
2812 return;
2813 }
2814
2815 QUIC_DLOG(INFO) << ENDPOINT << "Closing connection: " << connection_id()
2816 << ", with error: " << QuicErrorCodeToString(error) << " ("
2817 << error << "), and details: " << error_details;
2818
2819 if (connection_close_behavior ==
2820 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET) {
2821 SendConnectionClosePacket(error, error_details, SEND_ACK);
2822 } else if (connection_close_behavior ==
2823 ConnectionCloseBehavior::
2824 SEND_CONNECTION_CLOSE_PACKET_WITH_NO_ACK) {
2825 SendConnectionClosePacket(error, error_details, NO_ACK);
2826 }
2827
2828 ConnectionCloseSource source = ConnectionCloseSource::FROM_SELF;
2829 if (perspective_ == Perspective::IS_CLIENT &&
2830 error == QUIC_CRYPTO_HANDSHAKE_STATELESS_REJECT) {
2831 // Regard stateless rejected connection as closed by server.
2832 source = ConnectionCloseSource::FROM_PEER;
2833 }
2834 TearDownLocalConnectionState(error, error_details, source);
2835}
2836
2837void QuicConnection::SendConnectionClosePacket(QuicErrorCode error,
vasilvvc48c8712019-03-11 13:38:16 -07002838 const std::string& details,
QUICHE teama6ef0a62019-03-07 20:34:33 -05002839 AckBundling ack_mode) {
2840 QUIC_DLOG(INFO) << ENDPOINT << "Sending connection close packet.";
2841 if (fix_termination_packets_) {
2842 QUIC_RELOADABLE_FLAG_COUNT(quic_fix_termination_packets);
2843 SetDefaultEncryptionLevel(GetConnectionCloseEncryptionLevel());
2844 }
2845 ClearQueuedPackets();
2846 ScopedPacketFlusher flusher(this, ack_mode);
2847 if (packet_generator_.deprecate_ack_bundling_mode() && ack_mode == SEND_ACK &&
2848 !GetUpdatedAckFrame().ack_frame->packets.Empty()) {
2849 SendAck();
2850 }
2851 QuicConnectionCloseFrame* frame = new QuicConnectionCloseFrame();
2852 frame->error_code = error;
2853 frame->error_details = details;
2854 packet_generator_.AddControlFrame(QuicFrame(frame));
2855 packet_generator_.FlushAllQueuedFrames();
2856}
2857
2858void QuicConnection::TearDownLocalConnectionState(
2859 QuicErrorCode error,
vasilvvc48c8712019-03-11 13:38:16 -07002860 const std::string& error_details,
QUICHE teama6ef0a62019-03-07 20:34:33 -05002861 ConnectionCloseSource source) {
2862 if (!connected_) {
2863 QUIC_DLOG(INFO) << "Connection is already closed.";
2864 return;
2865 }
2866
2867 // If we are using a batch writer, flush packets queued in it, if any.
2868 FlushPackets();
2869 connected_ = false;
2870 DCHECK(visitor_ != nullptr);
2871 visitor_->OnConnectionClosed(error, error_details, source);
2872 if (debug_visitor_ != nullptr) {
2873 debug_visitor_->OnConnectionClosed(error, error_details, source);
2874 }
2875 // Cancel the alarms so they don't trigger any action now that the
2876 // connection is closed.
2877 CancelAllAlarms();
2878}
2879
2880void QuicConnection::CancelAllAlarms() {
2881 QUIC_DVLOG(1) << "Cancelling all QuicConnection alarms.";
2882
2883 ack_alarm_->Cancel();
2884 ping_alarm_->Cancel();
2885 retransmission_alarm_->Cancel();
2886 send_alarm_->Cancel();
2887 timeout_alarm_->Cancel();
2888 mtu_discovery_alarm_->Cancel();
2889 path_degrading_alarm_->Cancel();
2890}
2891
2892QuicByteCount QuicConnection::max_packet_length() const {
2893 return packet_generator_.GetCurrentMaxPacketLength();
2894}
2895
2896void QuicConnection::SetMaxPacketLength(QuicByteCount length) {
2897 long_term_mtu_ = length;
2898 packet_generator_.SetMaxPacketLength(GetLimitedMaxPacketSize(length));
2899}
2900
2901bool QuicConnection::HasQueuedData() const {
2902 return pending_version_negotiation_packet_ || !queued_packets_.empty() ||
2903 packet_generator_.HasQueuedFrames();
2904}
2905
2906void QuicConnection::EnableSavingCryptoPackets() {
2907 save_crypto_packets_as_termination_packets_ = true;
2908}
2909
2910bool QuicConnection::CanWriteStreamData() {
2911 // Don't write stream data if there are negotiation or queued data packets
2912 // to send. Otherwise, continue and bundle as many frames as possible.
2913 if (pending_version_negotiation_packet_ || !queued_packets_.empty()) {
2914 return false;
2915 }
2916
2917 IsHandshake pending_handshake =
2918 visitor_->HasPendingHandshake() ? IS_HANDSHAKE : NOT_HANDSHAKE;
2919 // Sending queued packets may have caused the socket to become write blocked,
2920 // or the congestion manager to prohibit sending. If we've sent everything
2921 // we had queued and we're still not blocked, let the visitor know it can
2922 // write more.
2923 return ShouldGeneratePacket(HAS_RETRANSMITTABLE_DATA, pending_handshake);
2924}
2925
2926void QuicConnection::SetNetworkTimeouts(QuicTime::Delta handshake_timeout,
2927 QuicTime::Delta idle_timeout) {
2928 QUIC_BUG_IF(idle_timeout > handshake_timeout)
2929 << "idle_timeout:" << idle_timeout.ToMilliseconds()
2930 << " handshake_timeout:" << handshake_timeout.ToMilliseconds();
2931 // Adjust the idle timeout on client and server to prevent clients from
2932 // sending requests to servers which have already closed the connection.
2933 if (perspective_ == Perspective::IS_SERVER) {
2934 idle_timeout = idle_timeout + QuicTime::Delta::FromSeconds(3);
2935 } else if (idle_timeout > QuicTime::Delta::FromSeconds(1)) {
2936 idle_timeout = idle_timeout - QuicTime::Delta::FromSeconds(1);
2937 }
2938 handshake_timeout_ = handshake_timeout;
2939 idle_network_timeout_ = idle_timeout;
2940
2941 SetTimeoutAlarm();
2942}
2943
2944void QuicConnection::CheckForTimeout() {
2945 QuicTime now = clock_->ApproximateNow();
2946 QuicTime time_of_last_packet =
2947 std::max(time_of_last_received_packet_,
2948 time_of_first_packet_sent_after_receiving_);
2949
2950 // |delta| can be < 0 as |now| is approximate time but |time_of_last_packet|
2951 // is accurate time. However, this should not change the behavior of
2952 // timeout handling.
2953 QuicTime::Delta idle_duration = now - time_of_last_packet;
2954 QUIC_DVLOG(1) << ENDPOINT << "last packet "
2955 << time_of_last_packet.ToDebuggingValue()
2956 << " now:" << now.ToDebuggingValue()
2957 << " idle_duration:" << idle_duration.ToMicroseconds()
2958 << " idle_network_timeout: "
2959 << idle_network_timeout_.ToMicroseconds();
2960 if (idle_duration >= idle_network_timeout_) {
vasilvvc48c8712019-03-11 13:38:16 -07002961 const std::string error_details = "No recent network activity.";
QUICHE teama6ef0a62019-03-07 20:34:33 -05002962 QUIC_DVLOG(1) << ENDPOINT << error_details;
2963 if ((sent_packet_manager_.GetConsecutiveTlpCount() > 0 ||
2964 sent_packet_manager_.GetConsecutiveRtoCount() > 0 ||
2965 visitor_->ShouldKeepConnectionAlive())) {
2966 CloseConnection(QUIC_NETWORK_IDLE_TIMEOUT, error_details,
2967 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
2968 } else {
2969 CloseConnection(QUIC_NETWORK_IDLE_TIMEOUT, error_details,
2970 idle_timeout_connection_close_behavior_);
2971 }
2972 return;
2973 }
2974
2975 if (!handshake_timeout_.IsInfinite()) {
2976 QuicTime::Delta connected_duration = now - stats_.connection_creation_time;
2977 QUIC_DVLOG(1) << ENDPOINT
2978 << "connection time: " << connected_duration.ToMicroseconds()
2979 << " handshake timeout: "
2980 << handshake_timeout_.ToMicroseconds();
2981 if (connected_duration >= handshake_timeout_) {
vasilvvc48c8712019-03-11 13:38:16 -07002982 const std::string error_details = "Handshake timeout expired.";
QUICHE teama6ef0a62019-03-07 20:34:33 -05002983 QUIC_DVLOG(1) << ENDPOINT << error_details;
2984 CloseConnection(QUIC_HANDSHAKE_TIMEOUT, error_details,
2985 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
2986 return;
2987 }
2988 }
2989
2990 SetTimeoutAlarm();
2991}
2992
2993void QuicConnection::SetTimeoutAlarm() {
2994 QuicTime time_of_last_packet =
2995 std::max(time_of_last_received_packet_,
2996 time_of_first_packet_sent_after_receiving_);
2997
2998 QuicTime deadline = time_of_last_packet + idle_network_timeout_;
2999 if (!handshake_timeout_.IsInfinite()) {
3000 deadline = std::min(deadline,
3001 stats_.connection_creation_time + handshake_timeout_);
3002 }
3003
3004 timeout_alarm_->Update(deadline, QuicTime::Delta::Zero());
3005}
3006
3007void QuicConnection::SetPingAlarm() {
3008 if (perspective_ == Perspective::IS_SERVER) {
3009 // Only clients send pings.
3010 return;
3011 }
3012 if (!visitor_->ShouldKeepConnectionAlive()) {
3013 ping_alarm_->Cancel();
3014 // Don't send a ping unless there are open streams.
3015 return;
3016 }
3017 if (retransmittable_on_wire_timeout_.IsInfinite() ||
3018 sent_packet_manager_.HasInFlightPackets()) {
3019 // Extend the ping alarm.
3020 ping_alarm_->Update(clock_->ApproximateNow() + ping_timeout_,
3021 QuicTime::Delta::FromSeconds(1));
3022 return;
3023 }
3024 DCHECK_LT(retransmittable_on_wire_timeout_, ping_timeout_);
3025 // If it's already set to an earlier time, then don't update it.
3026 if (ping_alarm_->IsSet() &&
3027 ping_alarm_->deadline() <
3028 clock_->ApproximateNow() + retransmittable_on_wire_timeout_) {
3029 return;
3030 }
3031 // Use a shorter timeout if there are open streams, but nothing on the wire.
3032 ping_alarm_->Update(
3033 clock_->ApproximateNow() + retransmittable_on_wire_timeout_,
3034 QuicTime::Delta::FromMilliseconds(1));
3035}
3036
3037void QuicConnection::SetRetransmissionAlarm() {
3038 if (packet_generator_.PacketFlusherAttached()) {
3039 pending_retransmission_alarm_ = true;
3040 return;
3041 }
3042 QuicTime retransmission_time = sent_packet_manager_.GetRetransmissionTime();
3043 retransmission_alarm_->Update(retransmission_time,
3044 QuicTime::Delta::FromMilliseconds(1));
3045}
3046
3047void QuicConnection::SetPathDegradingAlarm() {
3048 if (perspective_ == Perspective::IS_SERVER) {
3049 return;
3050 }
3051 const QuicTime::Delta delay = sent_packet_manager_.GetPathDegradingDelay();
3052 path_degrading_alarm_->Update(clock_->ApproximateNow() + delay,
3053 QuicTime::Delta::FromMilliseconds(1));
3054}
3055
3056void QuicConnection::MaybeSetMtuAlarm(QuicPacketNumber sent_packet_number) {
3057 // Do not set the alarm if the target size is less than the current size.
3058 // This covers the case when |mtu_discovery_target_| is at its default value,
3059 // zero.
3060 if (mtu_discovery_target_ <= max_packet_length()) {
3061 return;
3062 }
3063
3064 if (mtu_probe_count_ >= kMtuDiscoveryAttempts) {
3065 return;
3066 }
3067
3068 if (mtu_discovery_alarm_->IsSet()) {
3069 return;
3070 }
3071
3072 if (sent_packet_number >= next_mtu_probe_at_) {
3073 // Use an alarm to send the MTU probe to ensure that no ScopedPacketFlushers
3074 // are active.
3075 mtu_discovery_alarm_->Set(clock_->ApproximateNow());
3076 }
3077}
3078
3079void QuicConnection::MaybeSetAckAlarmTo(QuicTime time) {
3080 DCHECK(packet_generator_.deprecate_ack_bundling_mode());
3081 if (!ack_alarm_->IsSet() || ack_alarm_->deadline() > time) {
3082 ack_alarm_->Update(time, QuicTime::Delta::Zero());
3083 }
3084}
3085
3086QuicConnection::ScopedPacketFlusher::ScopedPacketFlusher(
3087 QuicConnection* connection,
3088 AckBundling ack_mode)
3089 : connection_(connection),
3090 flush_and_set_pending_retransmission_alarm_on_delete_(false) {
3091 if (connection_ == nullptr) {
3092 return;
3093 }
3094
3095 if (!connection_->packet_generator_.PacketFlusherAttached()) {
3096 flush_and_set_pending_retransmission_alarm_on_delete_ = true;
3097 connection->packet_generator_.AttachPacketFlusher();
3098 }
3099 if (connection_->packet_generator_.deprecate_ack_bundling_mode()) {
3100 return;
3101 }
3102
3103 // If caller wants us to include an ack, check the delayed-ack timer to see if
3104 // there's ack info to be sent.
3105 if (ShouldSendAck(ack_mode)) {
3106 if (!connection_->GetUpdatedAckFrame().ack_frame->packets.Empty()) {
3107 QUIC_DVLOG(1) << "Bundling ack with outgoing packet.";
3108 connection_->SendAck();
3109 }
3110 }
3111}
3112
3113bool QuicConnection::ScopedPacketFlusher::ShouldSendAck(
3114 AckBundling ack_mode) const {
3115 DCHECK(!connection_->packet_generator_.deprecate_ack_bundling_mode());
3116 // If the ack alarm is set, make sure the ack has been updated.
3117 DCHECK(!connection_->ack_alarm_->IsSet() || connection_->ack_frame_updated())
3118 << "ack_mode:" << ack_mode;
3119 switch (ack_mode) {
3120 case SEND_ACK:
3121 return true;
3122 case SEND_ACK_IF_QUEUED:
3123 return connection_->ack_queued();
3124 case SEND_ACK_IF_PENDING:
3125 return connection_->ack_alarm_->IsSet() ||
3126 connection_->stop_waiting_count_ > 1;
3127 case NO_ACK:
3128 return false;
3129 default:
3130 QUIC_BUG << "Unsupported ack_mode.";
3131 return true;
3132 }
3133}
3134
3135QuicConnection::ScopedPacketFlusher::~ScopedPacketFlusher() {
3136 if (connection_ == nullptr) {
3137 return;
3138 }
3139
3140 if (flush_and_set_pending_retransmission_alarm_on_delete_) {
3141 if (connection_->packet_generator_.deprecate_ack_bundling_mode()) {
3142 if (connection_->received_packet_manager_.decide_when_to_send_acks()) {
3143 const QuicTime ack_timeout =
3144 connection_->received_packet_manager_.ack_timeout();
3145 if (ack_timeout.IsInitialized()) {
3146 if (ack_timeout <= connection_->clock_->ApproximateNow() &&
3147 !connection_->CanWrite(NO_RETRANSMITTABLE_DATA)) {
3148 // Cancel ACK alarm if connection is write blocked, and ACK will be
3149 // sent when connection gets unblocked.
3150 connection_->ack_alarm_->Cancel();
3151 } else {
3152 connection_->MaybeSetAckAlarmTo(ack_timeout);
3153 }
3154 }
3155 }
3156 if (connection_->ack_alarm_->IsSet() &&
3157 connection_->ack_alarm_->deadline() <=
3158 connection_->clock_->ApproximateNow()) {
3159 // An ACK needs to be sent right now. This ACK did not get bundled
3160 // because either there was no data to write or packets were marked as
3161 // received after frames were queued in the generator.
3162 if (connection_->send_alarm_->IsSet() &&
3163 connection_->send_alarm_->deadline() <=
3164 connection_->clock_->ApproximateNow()) {
3165 // If send alarm will go off soon, let send alarm send the ACK.
3166 connection_->ack_alarm_->Cancel();
3167 if (!connection_->received_packet_manager_
3168 .decide_when_to_send_acks()) {
3169 connection_->send_ack_when_on_can_write_ = true;
3170 }
3171 } else {
3172 connection_->SendAck();
3173 }
3174 }
3175 }
3176 connection_->packet_generator_.Flush();
3177 connection_->FlushPackets();
3178 if (connection_->session_decides_what_to_write()) {
3179 // Reset transmission type.
3180 connection_->SetTransmissionType(NOT_RETRANSMISSION);
3181 }
3182
3183 // Once all transmissions are done, check if there is any outstanding data
3184 // to send and notify the congestion controller if not.
3185 //
3186 // Note that this means that the application limited check will happen as
3187 // soon as the last flusher gets destroyed, which is typically after a
3188 // single stream write is finished. This means that if all the data from a
3189 // single write goes through the connection, the application-limited signal
3190 // will fire even if the caller does a write operation immediately after.
3191 // There are two important approaches to remedy this situation:
3192 // (1) Instantiate ScopedPacketFlusher before performing multiple subsequent
3193 // writes, thus deferring this check until all writes are done.
3194 // (2) Write data in chunks sufficiently large so that they cause the
3195 // connection to be limited by the congestion control. Typically, this
3196 // would mean writing chunks larger than the product of the current
3197 // pacing rate and the pacer granularity. So, for instance, if the
3198 // pacing rate of the connection is 1 Gbps, and the pacer granularity is
3199 // 1 ms, the caller should send at least 125k bytes in order to not
3200 // be marked as application-limited.
3201 connection_->CheckIfApplicationLimited();
3202
3203 if (connection_->pending_retransmission_alarm_) {
3204 connection_->SetRetransmissionAlarm();
3205 connection_->pending_retransmission_alarm_ = false;
3206 }
3207 }
3208 DCHECK_EQ(flush_and_set_pending_retransmission_alarm_on_delete_,
3209 !connection_->packet_generator_.PacketFlusherAttached());
3210}
3211
3212HasRetransmittableData QuicConnection::IsRetransmittable(
3213 const SerializedPacket& packet) {
3214 // Retransmitted packets retransmittable frames are owned by the unacked
3215 // packet map, but are not present in the serialized packet.
3216 if (packet.transmission_type != NOT_RETRANSMISSION ||
3217 !packet.retransmittable_frames.empty()) {
3218 return HAS_RETRANSMITTABLE_DATA;
3219 } else {
3220 return NO_RETRANSMITTABLE_DATA;
3221 }
3222}
3223
3224bool QuicConnection::IsTerminationPacket(const SerializedPacket& packet) {
3225 if (packet.retransmittable_frames.empty()) {
3226 return false;
3227 }
3228 for (const QuicFrame& frame : packet.retransmittable_frames) {
3229 if (frame.type == CONNECTION_CLOSE_FRAME) {
3230 return true;
3231 }
3232 if (save_crypto_packets_as_termination_packets_ &&
3233 QuicUtils::IsHandshakeFrame(frame, transport_version())) {
3234 return true;
3235 }
3236 }
3237 return false;
3238}
3239
3240void QuicConnection::SetMtuDiscoveryTarget(QuicByteCount target) {
3241 mtu_discovery_target_ = GetLimitedMaxPacketSize(target);
3242}
3243
3244QuicByteCount QuicConnection::GetLimitedMaxPacketSize(
3245 QuicByteCount suggested_max_packet_size) {
3246 if (!peer_address_.IsInitialized()) {
3247 QUIC_BUG << "Attempted to use a connection without a valid peer address";
3248 return suggested_max_packet_size;
3249 }
3250
3251 const QuicByteCount writer_limit = writer_->GetMaxPacketSize(peer_address());
3252
3253 QuicByteCount max_packet_size = suggested_max_packet_size;
3254 if (max_packet_size > writer_limit) {
3255 max_packet_size = writer_limit;
3256 }
3257 if (max_packet_size > kMaxPacketSize) {
3258 max_packet_size = kMaxPacketSize;
3259 }
3260 return max_packet_size;
3261}
3262
3263void QuicConnection::SendMtuDiscoveryPacket(QuicByteCount target_mtu) {
3264 // Currently, this limit is ensured by the caller.
3265 DCHECK_EQ(target_mtu, GetLimitedMaxPacketSize(target_mtu));
3266
3267 // Send the probe.
3268 packet_generator_.GenerateMtuDiscoveryPacket(target_mtu);
3269}
3270
3271// TODO(zhongyi): change this method to generate a connectivity probing packet
3272// and let the caller to call writer to write the packet and handle write
3273// status.
3274bool QuicConnection::SendConnectivityProbingPacket(
3275 QuicPacketWriter* probing_writer,
3276 const QuicSocketAddress& peer_address) {
3277 return SendGenericPathProbePacket(probing_writer, peer_address,
3278 /* is_response= */ false);
3279}
3280
3281void QuicConnection::SendConnectivityProbingResponsePacket(
3282 const QuicSocketAddress& peer_address) {
3283 SendGenericPathProbePacket(nullptr, peer_address,
3284 /* is_response= */ true);
3285}
3286
3287bool QuicConnection::SendGenericPathProbePacket(
3288 QuicPacketWriter* probing_writer,
3289 const QuicSocketAddress& peer_address,
3290 bool is_response) {
3291 DCHECK(peer_address.IsInitialized());
3292 if (!connected_) {
3293 QUIC_BUG << "Not sending connectivity probing packet as connection is "
3294 << "disconnected.";
3295 return false;
3296 }
3297 if (perspective_ == Perspective::IS_SERVER && probing_writer == nullptr) {
3298 // Server can use default packet writer to write packet.
3299 probing_writer = writer_;
3300 }
3301 DCHECK(probing_writer);
3302
3303 if (probing_writer->IsWriteBlocked()) {
3304 QUIC_DLOG(INFO)
3305 << ENDPOINT
3306 << "Writer blocked when sending connectivity probing packet.";
3307 if (probing_writer == writer_) {
3308 // Visitor should not be write blocked if the probing writer is not the
3309 // default packet writer.
3310 visitor_->OnWriteBlocked();
3311 }
3312 return true;
3313 }
3314
3315 QUIC_DLOG(INFO) << ENDPOINT
3316 << "Sending path probe packet for connection_id = "
3317 << connection_id_;
3318
3319 OwningSerializedPacketPointer probing_packet;
3320 if (transport_version() != QUIC_VERSION_99) {
3321 // Non-IETF QUIC, generate a padded ping regardless of whether this is a
3322 // request or a response.
3323 probing_packet = packet_generator_.SerializeConnectivityProbingPacket();
3324 } else {
3325 if (is_response) {
3326 // Respond using IETF QUIC PATH_RESPONSE frame
3327 if (IsCurrentPacketConnectivityProbing()) {
3328 // Pad the response if the request was a google connectivity probe
3329 // (padded).
3330 probing_packet =
3331 packet_generator_.SerializePathResponseConnectivityProbingPacket(
3332 received_path_challenge_payloads_, /* is_padded = */ true);
3333 received_path_challenge_payloads_.clear();
3334 } else {
3335 // Do not pad the response if the path challenge was not a google
3336 // connectivity probe.
3337 probing_packet =
3338 packet_generator_.SerializePathResponseConnectivityProbingPacket(
3339 received_path_challenge_payloads_,
3340 /* is_padded = */ false);
3341 received_path_challenge_payloads_.clear();
3342 }
3343 } else {
3344 // Request using IETF QUIC PATH_CHALLENGE frame
3345 transmitted_connectivity_probe_payload_ =
3346 QuicMakeUnique<QuicPathFrameBuffer>();
3347 probing_packet =
3348 packet_generator_.SerializePathChallengeConnectivityProbingPacket(
3349 transmitted_connectivity_probe_payload_.get());
3350 if (!probing_packet) {
3351 transmitted_connectivity_probe_payload_ = nullptr;
3352 }
3353 }
3354 }
3355
3356 DCHECK_EQ(IsRetransmittable(*probing_packet), NO_RETRANSMITTABLE_DATA);
3357
3358 const QuicTime packet_send_time = clock_->Now();
3359 WriteResult result = probing_writer->WritePacket(
3360 probing_packet->encrypted_buffer, probing_packet->encrypted_length,
3361 self_address().host(), peer_address, per_packet_options_);
3362
3363 // If using a batch writer and the probing packet is buffered, flush it.
3364 if (probing_writer->IsBatchMode() && result.status == WRITE_STATUS_OK &&
3365 result.bytes_written == 0) {
3366 result = probing_writer->Flush();
3367 }
3368
3369 if (IsWriteError(result.status)) {
3370 // Write error for any connectivity probe should not affect the connection
3371 // as it is sent on a different path.
3372 QUIC_DLOG(INFO) << ENDPOINT << "Write probing packet failed with error = "
3373 << result.error_code;
3374 return false;
3375 }
3376
3377 if (debug_visitor_ != nullptr) {
3378 debug_visitor_->OnPacketSent(
3379 *probing_packet, probing_packet->original_packet_number,
3380 probing_packet->transmission_type, packet_send_time);
3381 }
3382
3383 // Call OnPacketSent regardless of the write result.
3384 sent_packet_manager_.OnPacketSent(
3385 probing_packet.get(), probing_packet->original_packet_number,
3386 packet_send_time, probing_packet->transmission_type,
3387 NO_RETRANSMITTABLE_DATA);
3388
3389 if (IsWriteBlockedStatus(result.status)) {
3390 if (probing_writer == writer_) {
3391 // Visitor should not be write blocked if the probing writer is not the
3392 // default packet writer.
3393 visitor_->OnWriteBlocked();
3394 }
3395 if (result.status == WRITE_STATUS_BLOCKED_DATA_BUFFERED) {
3396 QUIC_DLOG(INFO) << ENDPOINT << "Write probing packet blocked";
3397 }
3398 }
3399
3400 return true;
3401}
3402
3403void QuicConnection::DiscoverMtu() {
3404 DCHECK(!mtu_discovery_alarm_->IsSet());
3405
3406 // Check if the MTU has been already increased.
3407 if (mtu_discovery_target_ <= max_packet_length()) {
3408 return;
3409 }
3410
3411 // Calculate the packet number of the next probe *before* sending the current
3412 // one. Otherwise, when SendMtuDiscoveryPacket() is called,
3413 // MaybeSetMtuAlarm() will not realize that the probe has been just sent, and
3414 // will reschedule this probe again.
3415 packets_between_mtu_probes_ *= 2;
3416 next_mtu_probe_at_ = sent_packet_manager_.GetLargestSentPacket() +
3417 packets_between_mtu_probes_ + 1;
3418 ++mtu_probe_count_;
3419
3420 QUIC_DVLOG(2) << "Sending a path MTU discovery packet #" << mtu_probe_count_;
3421 SendMtuDiscoveryPacket(mtu_discovery_target_);
3422
3423 DCHECK(!mtu_discovery_alarm_->IsSet());
3424}
3425
3426void QuicConnection::OnEffectivePeerMigrationValidated() {
3427 if (active_effective_peer_migration_type_ == NO_CHANGE) {
3428 QUIC_BUG << "No migration underway.";
3429 return;
3430 }
3431 highest_packet_sent_before_effective_peer_migration_.Clear();
3432 active_effective_peer_migration_type_ = NO_CHANGE;
3433}
3434
3435void QuicConnection::StartEffectivePeerMigration(AddressChangeType type) {
3436 // TODO(fayang): Currently, all peer address change type are allowed. Need to
3437 // add a method ShouldAllowPeerAddressChange(PeerAddressChangeType type) to
3438 // determine whether |type| is allowed.
3439 if (type == NO_CHANGE) {
3440 QUIC_BUG << "EffectivePeerMigration started without address change.";
3441 return;
3442 }
3443 QUIC_DLOG(INFO) << ENDPOINT << "Effective peer's ip:port changed from "
3444 << effective_peer_address_.ToString() << " to "
3445 << GetEffectivePeerAddressFromCurrentPacket().ToString()
3446 << ", address change type is " << type
3447 << ", migrating connection.";
3448
3449 highest_packet_sent_before_effective_peer_migration_ =
3450 sent_packet_manager_.GetLargestSentPacket();
3451 effective_peer_address_ = GetEffectivePeerAddressFromCurrentPacket();
3452 active_effective_peer_migration_type_ = type;
3453
3454 // TODO(wub): Move these calls to OnEffectivePeerMigrationValidated.
3455 OnConnectionMigration(type);
3456}
3457
3458void QuicConnection::OnConnectionMigration(AddressChangeType addr_change_type) {
3459 visitor_->OnConnectionMigration(addr_change_type);
3460 sent_packet_manager_.OnConnectionMigration(addr_change_type);
3461}
3462
3463bool QuicConnection::IsCurrentPacketConnectivityProbing() const {
3464 return is_current_packet_connectivity_probing_;
3465}
3466
3467bool QuicConnection::ack_frame_updated() const {
3468 return received_packet_manager_.ack_frame_updated();
3469}
3470
3471QuicStringPiece QuicConnection::GetCurrentPacket() {
3472 if (current_packet_data_ == nullptr) {
3473 return QuicStringPiece();
3474 }
3475 return QuicStringPiece(current_packet_data_, last_size_);
3476}
3477
3478bool QuicConnection::MaybeConsiderAsMemoryCorruption(
3479 const QuicStreamFrame& frame) {
3480 if (frame.stream_id == QuicUtils::GetCryptoStreamId(transport_version()) ||
QUICHE team6987b4a2019-03-15 16:23:04 -07003481 last_decrypted_packet_level_ != ENCRYPTION_INITIAL) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05003482 return false;
3483 }
3484
3485 if (perspective_ == Perspective::IS_SERVER &&
3486 frame.data_length >= sizeof(kCHLO) &&
3487 strncmp(frame.data_buffer, reinterpret_cast<const char*>(&kCHLO),
3488 sizeof(kCHLO)) == 0) {
3489 return true;
3490 }
3491
3492 if (perspective_ == Perspective::IS_CLIENT &&
3493 frame.data_length >= sizeof(kREJ) &&
3494 strncmp(frame.data_buffer, reinterpret_cast<const char*>(&kREJ),
3495 sizeof(kREJ)) == 0) {
3496 return true;
3497 }
3498
3499 return false;
3500}
3501
3502void QuicConnection::MaybeSendProbingRetransmissions() {
3503 DCHECK(fill_up_link_during_probing_);
3504
3505 // Don't send probing retransmissions until the handshake has completed.
3506 if (!sent_packet_manager_.handshake_confirmed() ||
3507 sent_packet_manager().HasUnackedCryptoPackets()) {
3508 return;
3509 }
3510
3511 if (probing_retransmission_pending_) {
3512 QUIC_BUG << "MaybeSendProbingRetransmissions is called while another call "
3513 "to it is already in progress";
3514 return;
3515 }
3516
3517 probing_retransmission_pending_ = true;
3518 SendProbingRetransmissions();
3519 probing_retransmission_pending_ = false;
3520}
3521
3522void QuicConnection::CheckIfApplicationLimited() {
3523 if (session_decides_what_to_write() && probing_retransmission_pending_) {
3524 return;
3525 }
3526
3527 bool application_limited =
3528 queued_packets_.empty() &&
3529 !sent_packet_manager_.HasPendingRetransmissions() &&
3530 !visitor_->WillingAndAbleToWrite();
3531
3532 if (!application_limited) {
3533 return;
3534 }
3535
3536 if (fill_up_link_during_probing_) {
3537 MaybeSendProbingRetransmissions();
3538 if (!CanWrite(HAS_RETRANSMITTABLE_DATA)) {
3539 return;
3540 }
3541 }
3542
3543 sent_packet_manager_.OnApplicationLimited();
3544}
3545
3546void QuicConnection::UpdatePacketContent(PacketContent type) {
3547 if (current_packet_content_ == NOT_PADDED_PING) {
3548 // We have already learned the current packet is not a connectivity
3549 // probing packet. Peer migration should have already been started earlier
3550 // if needed.
3551 return;
3552 }
3553
3554 if (type == NO_FRAMES_RECEIVED) {
3555 return;
3556 }
3557
3558 if (type == FIRST_FRAME_IS_PING) {
3559 if (current_packet_content_ == NO_FRAMES_RECEIVED) {
3560 current_packet_content_ = FIRST_FRAME_IS_PING;
3561 return;
3562 }
3563 }
3564
3565 // In Google QUIC we look for a packet with just a PING and PADDING.
3566 // For IETF QUIC, the packet must consist of just a PATH_CHALLENGE frame,
3567 // followed by PADDING. If the condition is met, mark things as
3568 // connectivity-probing, causing later processing to generate the correct
3569 // response.
3570 if (type == SECOND_FRAME_IS_PADDING &&
3571 current_packet_content_ == FIRST_FRAME_IS_PING) {
3572 current_packet_content_ = SECOND_FRAME_IS_PADDING;
3573 if (perspective_ == Perspective::IS_SERVER) {
3574 is_current_packet_connectivity_probing_ =
3575 current_effective_peer_migration_type_ != NO_CHANGE;
3576 } else {
3577 is_current_packet_connectivity_probing_ =
3578 (last_packet_source_address_ != peer_address_) ||
3579 (last_packet_destination_address_ != self_address_);
3580 }
3581 return;
3582 }
3583
3584 current_packet_content_ = NOT_PADDED_PING;
3585 if (received_packet_manager_.GetLargestObserved().IsInitialized() &&
3586 last_header_.packet_number ==
3587 received_packet_manager_.GetLargestObserved()) {
3588 direct_peer_address_ = last_packet_source_address_;
3589 if (current_effective_peer_migration_type_ != NO_CHANGE) {
3590 // Start effective peer migration immediately when the current packet is
3591 // confirmed not a connectivity probing packet.
3592 StartEffectivePeerMigration(current_effective_peer_migration_type_);
3593 }
3594 }
3595 current_effective_peer_migration_type_ = NO_CHANGE;
3596}
3597
3598void QuicConnection::MaybeEnableSessionDecidesWhatToWrite() {
3599 // Only enable session decides what to write code path for version 42+,
3600 // because it needs the receiver to allow receiving overlapping stream data.
3601 const bool enable_session_decides_what_to_write =
3602 transport_version() > QUIC_VERSION_39;
3603 sent_packet_manager_.SetSessionDecideWhatToWrite(
3604 enable_session_decides_what_to_write);
3605 packet_generator_.SetCanSetTransmissionType(
3606 enable_session_decides_what_to_write);
3607}
3608
3609void QuicConnection::PostProcessAfterAckFrame(bool send_stop_waiting,
3610 bool acked_new_packet) {
3611 if (no_stop_waiting_frames_) {
3612 received_packet_manager_.DontWaitForPacketsBefore(
3613 sent_packet_manager_.largest_packet_peer_knows_is_acked());
3614 }
3615 // Always reset the retransmission alarm when an ack comes in, since we now
3616 // have a better estimate of the current rtt than when it was set.
3617 SetRetransmissionAlarm();
3618 MaybeSetPathDegradingAlarm(acked_new_packet);
3619
3620 // TODO(ianswett): Only increment stop_waiting_count_ if StopWaiting frames
3621 // are sent.
3622 if (send_stop_waiting) {
3623 ++stop_waiting_count_;
3624 } else {
3625 stop_waiting_count_ = 0;
3626 }
3627}
3628
3629void QuicConnection::MaybeSetPathDegradingAlarm(bool acked_new_packet) {
3630 if (!sent_packet_manager_.HasInFlightPackets()) {
3631 // There are no retransmittable packets on the wire, so it's impossible to
3632 // say if the connection has degraded.
3633 path_degrading_alarm_->Cancel();
3634 } else if (acked_new_packet) {
3635 // A previously-unacked packet has been acked, which means forward progress
3636 // has been made. Unset |is_path_degrading| if the path was considered as
3637 // degrading previously. Set/update the path degrading alarm.
3638 is_path_degrading_ = false;
3639 SetPathDegradingAlarm();
3640 }
3641}
3642
3643void QuicConnection::SetSessionNotifier(
3644 SessionNotifierInterface* session_notifier) {
3645 sent_packet_manager_.SetSessionNotifier(session_notifier);
3646}
3647
3648void QuicConnection::SetDataProducer(
3649 QuicStreamFrameDataProducer* data_producer) {
3650 framer_.set_data_producer(data_producer);
3651}
3652
3653void QuicConnection::SetTransmissionType(TransmissionType type) {
3654 packet_generator_.SetTransmissionType(type);
3655}
3656
3657bool QuicConnection::session_decides_what_to_write() const {
3658 return sent_packet_manager_.session_decides_what_to_write();
3659}
3660
3661void QuicConnection::UpdateReleaseTimeIntoFuture() {
3662 DCHECK(supports_release_time_);
3663
3664 release_time_into_future_ = std::max(
3665 QuicTime::Delta::FromMilliseconds(kMinReleaseTimeIntoFutureMs),
3666 std::min(
3667 QuicTime::Delta::FromMilliseconds(
3668 GetQuicFlag(FLAGS_quic_max_pace_time_into_future_ms)),
3669 sent_packet_manager_.GetRttStats()->SmoothedOrInitialRtt() *
3670 GetQuicFlag(FLAGS_quic_pace_time_into_future_srtt_fraction)));
3671}
3672
3673void QuicConnection::ResetAckStates() {
3674 ack_alarm_->Cancel();
3675 ack_queued_ = false;
3676 stop_waiting_count_ = 0;
3677 num_retransmittable_packets_received_since_last_ack_sent_ = 0;
3678 num_packets_received_since_last_ack_sent_ = 0;
3679 if (received_packet_manager_.decide_when_to_send_acks()) {
3680 received_packet_manager_.ResetAckStates();
3681 }
3682}
3683
3684MessageStatus QuicConnection::SendMessage(QuicMessageId message_id,
3685 QuicMemSliceSpan message) {
3686 if (transport_version() <= QUIC_VERSION_44) {
3687 QUIC_BUG << "MESSAGE frame is not supported for version "
3688 << transport_version();
3689 return MESSAGE_STATUS_UNSUPPORTED;
3690 }
3691 if (message.total_length() > GetLargestMessagePayload()) {
3692 return MESSAGE_STATUS_TOO_LARGE;
3693 }
3694 if (!CanWrite(HAS_RETRANSMITTABLE_DATA)) {
3695 return MESSAGE_STATUS_BLOCKED;
3696 }
3697 ScopedPacketFlusher flusher(this, SEND_ACK_IF_PENDING);
3698 return packet_generator_.AddMessageFrame(message_id, message);
3699}
3700
3701QuicPacketLength QuicConnection::GetLargestMessagePayload() const {
3702 return packet_generator_.GetLargestMessagePayload();
3703}
3704
3705bool QuicConnection::ShouldSetAckAlarm() const {
3706 DCHECK(ack_frame_updated());
3707 if (ack_alarm_->IsSet()) {
3708 // ACK alarm has been set.
3709 return false;
3710 }
3711 if (GetQuicReloadableFlag(quic_fix_spurious_ack_alarm) &&
3712 packet_generator_.should_send_ack()) {
3713 // If the generator is already configured to send an ACK, then there is no
3714 // need to schedule the ACK alarm. The updated ACK information will be sent
3715 // when the generator flushes.
3716 QUIC_RELOADABLE_FLAG_COUNT(quic_fix_spurious_ack_alarm);
3717 return false;
3718 }
3719 return true;
3720}
3721
3722EncryptionLevel QuicConnection::GetConnectionCloseEncryptionLevel() const {
3723 DCHECK(fix_termination_packets_);
3724 if (perspective_ == Perspective::IS_CLIENT) {
3725 return encryption_level_;
3726 }
3727 if (sent_packet_manager_.handshake_confirmed()) {
3728 // A forward secure packet has been received.
3729 QUIC_BUG_IF(encryption_level_ != ENCRYPTION_FORWARD_SECURE);
3730 return ENCRYPTION_FORWARD_SECURE;
3731 }
3732 if (framer_.HasEncrypterOfEncryptionLevel(ENCRYPTION_ZERO_RTT)) {
3733 if (encryption_level_ != ENCRYPTION_ZERO_RTT) {
3734 if (transport_version() > QUIC_VERSION_43) {
3735 QUIC_CODE_COUNT(quic_wrong_encryption_level_connection_close_ietf);
3736 } else {
3737 QUIC_CODE_COUNT(quic_wrong_encryption_level_connection_close);
3738 }
3739 }
3740 return ENCRYPTION_ZERO_RTT;
3741 }
QUICHE team6987b4a2019-03-15 16:23:04 -07003742 return ENCRYPTION_INITIAL;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003743}
3744
3745size_t QuicConnection::min_received_before_ack_decimation() const {
3746 if (received_packet_manager_.decide_when_to_send_acks()) {
3747 return received_packet_manager_.min_received_before_ack_decimation();
3748 }
3749 return min_received_before_ack_decimation_;
3750}
3751
3752void QuicConnection::set_min_received_before_ack_decimation(size_t new_value) {
3753 if (received_packet_manager_.decide_when_to_send_acks()) {
3754 received_packet_manager_.set_min_received_before_ack_decimation(new_value);
3755 } else {
3756 min_received_before_ack_decimation_ = new_value;
3757 }
3758}
3759
3760size_t QuicConnection::ack_frequency_before_ack_decimation() const {
3761 if (received_packet_manager_.decide_when_to_send_acks()) {
3762 return received_packet_manager_.ack_frequency_before_ack_decimation();
3763 }
3764 return ack_frequency_before_ack_decimation_;
3765}
3766
3767void QuicConnection::set_ack_frequency_before_ack_decimation(size_t new_value) {
3768 DCHECK_GT(new_value, 0u);
3769 if (received_packet_manager_.decide_when_to_send_acks()) {
3770 received_packet_manager_.set_ack_frequency_before_ack_decimation(new_value);
3771 } else {
3772 ack_frequency_before_ack_decimation_ = new_value;
3773 }
3774}
3775
3776#undef ENDPOINT // undef for jumbo builds
3777} // namespace quic