Roll src/third_party/WebKit eac3800:0237a66 (svn 202606:202607)
[chromium-blink-merge.git] / net / quic / quic_connection.cc
blob97895bdba250ef977a41bb147023449f525319d5
1 // 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.
5 #include "net/quic/quic_connection.h"
7 #include <string.h>
8 #include <sys/types.h>
10 #include <algorithm>
11 #include <iterator>
12 #include <limits>
13 #include <memory>
14 #include <set>
15 #include <utility>
17 #include "base/format_macros.h"
18 #include "base/logging.h"
19 #include "base/memory/ref_counted.h"
20 #include "base/profiler/scoped_tracker.h"
21 #include "base/stl_util.h"
22 #include "base/strings/stringprintf.h"
23 #include "net/base/net_errors.h"
24 #include "net/quic/crypto/crypto_protocol.h"
25 #include "net/quic/crypto/quic_decrypter.h"
26 #include "net/quic/crypto/quic_encrypter.h"
27 #include "net/quic/proto/cached_network_parameters.pb.h"
28 #include "net/quic/quic_bandwidth.h"
29 #include "net/quic/quic_config.h"
30 #include "net/quic/quic_fec_group.h"
31 #include "net/quic/quic_flags.h"
32 #include "net/quic/quic_packet_generator.h"
33 #include "net/quic/quic_utils.h"
35 using base::StringPiece;
36 using base::StringPrintf;
37 using base::hash_map;
38 using base::hash_set;
39 using std::list;
40 using std::make_pair;
41 using std::max;
42 using std::min;
43 using std::numeric_limits;
44 using std::set;
45 using std::string;
46 using std::vector;
48 namespace net {
50 class QuicDecrypter;
51 class QuicEncrypter;
53 namespace {
55 // The largest gap in packets we'll accept without closing the connection.
56 // This will likely have to be tuned.
57 const QuicPacketNumber kMaxPacketGap = 5000;
59 // Limit the number of FEC groups to two. If we get enough out of order packets
60 // that this becomes limiting, we can revisit.
61 const size_t kMaxFecGroups = 2;
63 // Maximum number of acks received before sending an ack in response.
64 const QuicPacketCount kMaxPacketsReceivedBeforeAckSend = 20;
66 bool Near(QuicPacketNumber a, QuicPacketNumber b) {
67 QuicPacketNumber delta = (a > b) ? a - b : b - a;
68 return delta <= kMaxPacketGap;
71 // An alarm that is scheduled to send an ack if a timeout occurs.
72 class AckAlarm : public QuicAlarm::Delegate {
73 public:
74 explicit AckAlarm(QuicConnection* connection)
75 : connection_(connection) {
78 QuicTime OnAlarm() override {
79 connection_->SendAck();
80 return QuicTime::Zero();
83 private:
84 QuicConnection* connection_;
86 DISALLOW_COPY_AND_ASSIGN(AckAlarm);
89 // This alarm will be scheduled any time a data-bearing packet is sent out.
90 // When the alarm goes off, the connection checks to see if the oldest packets
91 // have been acked, and retransmit them if they have not.
92 class RetransmissionAlarm : public QuicAlarm::Delegate {
93 public:
94 explicit RetransmissionAlarm(QuicConnection* connection)
95 : connection_(connection) {
98 QuicTime OnAlarm() override {
99 connection_->OnRetransmissionTimeout();
100 return QuicTime::Zero();
103 private:
104 QuicConnection* connection_;
106 DISALLOW_COPY_AND_ASSIGN(RetransmissionAlarm);
109 // An alarm that is scheduled when the SentPacketManager requires a delay
110 // before sending packets and fires when the packet may be sent.
111 class SendAlarm : public QuicAlarm::Delegate {
112 public:
113 explicit SendAlarm(QuicConnection* connection)
114 : connection_(connection) {
117 QuicTime OnAlarm() override {
118 connection_->WriteIfNotBlocked();
119 // Never reschedule the alarm, since CanWrite does that.
120 return QuicTime::Zero();
123 private:
124 QuicConnection* connection_;
126 DISALLOW_COPY_AND_ASSIGN(SendAlarm);
129 class TimeoutAlarm : public QuicAlarm::Delegate {
130 public:
131 explicit TimeoutAlarm(QuicConnection* connection)
132 : connection_(connection) {
135 QuicTime OnAlarm() override {
136 connection_->CheckForTimeout();
137 // Never reschedule the alarm, since CheckForTimeout does that.
138 return QuicTime::Zero();
141 private:
142 QuicConnection* connection_;
144 DISALLOW_COPY_AND_ASSIGN(TimeoutAlarm);
147 class PingAlarm : public QuicAlarm::Delegate {
148 public:
149 explicit PingAlarm(QuicConnection* connection)
150 : connection_(connection) {
153 QuicTime OnAlarm() override {
154 connection_->SendPing();
155 return QuicTime::Zero();
158 private:
159 QuicConnection* connection_;
161 DISALLOW_COPY_AND_ASSIGN(PingAlarm);
164 class MtuDiscoveryAlarm : public QuicAlarm::Delegate {
165 public:
166 explicit MtuDiscoveryAlarm(QuicConnection* connection)
167 : connection_(connection) {}
169 QuicTime OnAlarm() override {
170 connection_->DiscoverMtu();
171 // DiscoverMtu() handles rescheduling the alarm by itself.
172 return QuicTime::Zero();
175 private:
176 QuicConnection* connection_;
178 DISALLOW_COPY_AND_ASSIGN(MtuDiscoveryAlarm);
181 // This alarm may be scheduled when an FEC protected packet is sent out.
182 class FecAlarm : public QuicAlarm::Delegate {
183 public:
184 explicit FecAlarm(QuicPacketGenerator* packet_generator)
185 : packet_generator_(packet_generator) {}
187 QuicTime OnAlarm() override {
188 packet_generator_->OnFecTimeout();
189 return QuicTime::Zero();
192 private:
193 QuicPacketGenerator* packet_generator_;
195 DISALLOW_COPY_AND_ASSIGN(FecAlarm);
198 // Listens for acks of MTU discovery packets and raises the maximum packet size
199 // of the connection if the probe succeeds.
200 class MtuDiscoveryAckListener : public QuicAckNotifier::DelegateInterface {
201 public:
202 MtuDiscoveryAckListener(QuicConnection* connection, QuicByteCount probe_size)
203 : connection_(connection), probe_size_(probe_size) {}
205 void OnAckNotification(int /*num_retransmittable_packets*/,
206 int /*num_retransmittable_bytes*/,
207 QuicTime::Delta /*delta_largest_observed*/) override {
208 // Since the probe was successful, increase the maximum packet size to that.
209 if (probe_size_ > connection_->max_packet_length()) {
210 connection_->SetMaxPacketLength(probe_size_);
214 protected:
215 // MtuDiscoveryAckListener is ref counted.
216 ~MtuDiscoveryAckListener() override {}
218 private:
219 QuicConnection* connection_;
220 QuicByteCount probe_size_;
222 DISALLOW_COPY_AND_ASSIGN(MtuDiscoveryAckListener);
225 } // namespace
227 QuicConnection::QueuedPacket::QueuedPacket(SerializedPacket packet,
228 EncryptionLevel level)
229 : serialized_packet(packet),
230 encryption_level(level),
231 transmission_type(NOT_RETRANSMISSION),
232 original_packet_number(0) {}
234 QuicConnection::QueuedPacket::QueuedPacket(
235 SerializedPacket packet,
236 EncryptionLevel level,
237 TransmissionType transmission_type,
238 QuicPacketNumber original_packet_number)
239 : serialized_packet(packet),
240 encryption_level(level),
241 transmission_type(transmission_type),
242 original_packet_number(original_packet_number) {}
244 #define ENDPOINT \
245 (perspective_ == Perspective::IS_SERVER ? "Server: " : "Client: ")
247 QuicConnection::QuicConnection(QuicConnectionId connection_id,
248 IPEndPoint address,
249 QuicConnectionHelperInterface* helper,
250 const PacketWriterFactory& writer_factory,
251 bool owns_writer,
252 Perspective perspective,
253 bool is_secure,
254 const QuicVersionVector& supported_versions)
255 : framer_(supported_versions,
256 helper->GetClock()->ApproximateNow(),
257 perspective),
258 helper_(helper),
259 writer_(writer_factory.Create(this)),
260 owns_writer_(owns_writer),
261 encryption_level_(ENCRYPTION_NONE),
262 has_forward_secure_encrypter_(false),
263 first_required_forward_secure_packet_(0),
264 clock_(helper->GetClock()),
265 random_generator_(helper->GetRandomGenerator()),
266 connection_id_(connection_id),
267 peer_address_(address),
268 migrating_peer_port_(0),
269 last_packet_decrypted_(false),
270 last_packet_revived_(false),
271 last_size_(0),
272 last_decrypted_packet_level_(ENCRYPTION_NONE),
273 should_last_packet_instigate_acks_(false),
274 largest_seen_packet_with_ack_(0),
275 largest_seen_packet_with_stop_waiting_(0),
276 max_undecryptable_packets_(0),
277 pending_version_negotiation_packet_(false),
278 silent_close_enabled_(false),
279 received_packet_manager_(&stats_),
280 ack_queued_(false),
281 num_packets_received_since_last_ack_sent_(0),
282 stop_waiting_count_(0),
283 delay_setting_retransmission_alarm_(false),
284 pending_retransmission_alarm_(false),
285 ack_alarm_(helper->CreateAlarm(new AckAlarm(this))),
286 retransmission_alarm_(helper->CreateAlarm(new RetransmissionAlarm(this))),
287 send_alarm_(helper->CreateAlarm(new SendAlarm(this))),
288 resume_writes_alarm_(helper->CreateAlarm(new SendAlarm(this))),
289 timeout_alarm_(helper->CreateAlarm(new TimeoutAlarm(this))),
290 ping_alarm_(helper->CreateAlarm(new PingAlarm(this))),
291 mtu_discovery_alarm_(helper->CreateAlarm(new MtuDiscoveryAlarm(this))),
292 visitor_(nullptr),
293 debug_visitor_(nullptr),
294 packet_generator_(connection_id_, &framer_, random_generator_, this),
295 fec_alarm_(helper->CreateAlarm(new FecAlarm(&packet_generator_))),
296 idle_network_timeout_(QuicTime::Delta::Infinite()),
297 overall_connection_timeout_(QuicTime::Delta::Infinite()),
298 time_of_last_received_packet_(clock_->ApproximateNow()),
299 time_of_last_sent_new_packet_(clock_->ApproximateNow()),
300 packet_number_of_last_sent_packet_(0),
301 sent_packet_manager_(
302 perspective,
303 clock_,
304 &stats_,
305 FLAGS_quic_use_bbr_congestion_control ? kBBR : kCubic,
306 FLAGS_quic_use_time_loss_detection ? kTime : kNack,
307 is_secure),
308 version_negotiation_state_(START_NEGOTIATION),
309 perspective_(perspective),
310 connected_(true),
311 peer_ip_changed_(false),
312 peer_port_changed_(false),
313 self_ip_changed_(false),
314 self_port_changed_(false),
315 can_truncate_connection_ids_(true),
316 is_secure_(is_secure),
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 goaway_sent_(false),
323 goaway_received_(false) {
324 DVLOG(1) << ENDPOINT << "Created connection with connection_id: "
325 << connection_id;
326 framer_.set_visitor(this);
327 framer_.set_received_entropy_calculator(&received_packet_manager_);
328 last_stop_waiting_frame_.least_unacked = 0;
329 stats_.connection_creation_time = clock_->ApproximateNow();
330 sent_packet_manager_.set_network_change_visitor(this);
331 // Allow the packet writer to potentially reduce the packet size to a value
332 // even smaller than kDefaultMaxPacketSize.
333 SetMaxPacketLength(perspective_ == Perspective::IS_SERVER
334 ? kDefaultServerMaxPacketSize
335 : kDefaultMaxPacketSize);
338 QuicConnection::~QuicConnection() {
339 if (owns_writer_) {
340 delete writer_;
342 STLDeleteElements(&undecryptable_packets_);
343 STLDeleteValues(&group_map_);
344 ClearQueuedPackets();
347 void QuicConnection::ClearQueuedPackets() {
348 for (QueuedPacketList::iterator it = queued_packets_.begin();
349 it != queued_packets_.end(); ++it) {
350 delete it->serialized_packet.retransmittable_frames;
351 delete it->serialized_packet.packet;
353 queued_packets_.clear();
356 void QuicConnection::SetFromConfig(const QuicConfig& config) {
357 if (config.negotiated()) {
358 SetNetworkTimeouts(QuicTime::Delta::Infinite(),
359 config.IdleConnectionStateLifetime());
360 if (config.SilentClose()) {
361 silent_close_enabled_ = true;
363 } else {
364 SetNetworkTimeouts(config.max_time_before_crypto_handshake(),
365 config.max_idle_time_before_crypto_handshake());
368 sent_packet_manager_.SetFromConfig(config);
369 if (config.HasReceivedBytesForConnectionId() &&
370 can_truncate_connection_ids_) {
371 packet_generator_.SetConnectionIdLength(
372 config.ReceivedBytesForConnectionId());
374 max_undecryptable_packets_ = config.max_undecryptable_packets();
376 if (config.HasClientSentConnectionOption(kFSPA, perspective_)) {
377 packet_generator_.set_fec_send_policy(FecSendPolicy::FEC_ALARM_TRIGGER);
379 if (config.HasClientSentConnectionOption(kFRTT, perspective_)) {
380 // TODO(rtenneti): Delete this code after the 0.25 RTT FEC experiment.
381 const float kFecTimeoutRttMultiplier = 0.25;
382 packet_generator_.set_rtt_multiplier_for_fec_timeout(
383 kFecTimeoutRttMultiplier);
386 if (config.HasClientSentConnectionOption(kMTUH, perspective_)) {
387 SetMtuDiscoveryTarget(kMtuDiscoveryTargetPacketSizeHigh);
389 if (config.HasClientSentConnectionOption(kMTUL, perspective_)) {
390 SetMtuDiscoveryTarget(kMtuDiscoveryTargetPacketSizeLow);
394 void QuicConnection::OnSendConnectionState(
395 const CachedNetworkParameters& cached_network_params) {
396 if (debug_visitor_ != nullptr) {
397 debug_visitor_->OnSendConnectionState(cached_network_params);
401 void QuicConnection::ResumeConnectionState(
402 const CachedNetworkParameters& cached_network_params,
403 bool max_bandwidth_resumption) {
404 if (debug_visitor_ != nullptr) {
405 debug_visitor_->OnResumeConnectionState(cached_network_params);
407 sent_packet_manager_.ResumeConnectionState(cached_network_params,
408 max_bandwidth_resumption);
411 void QuicConnection::SetNumOpenStreams(size_t num_streams) {
412 sent_packet_manager_.SetNumOpenStreams(num_streams);
415 bool QuicConnection::SelectMutualVersion(
416 const QuicVersionVector& available_versions) {
417 // Try to find the highest mutual version by iterating over supported
418 // versions, starting with the highest, and breaking out of the loop once we
419 // find a matching version in the provided available_versions vector.
420 const QuicVersionVector& supported_versions = framer_.supported_versions();
421 for (size_t i = 0; i < supported_versions.size(); ++i) {
422 const QuicVersion& version = supported_versions[i];
423 if (std::find(available_versions.begin(), available_versions.end(),
424 version) != available_versions.end()) {
425 framer_.set_version(version);
426 return true;
430 return false;
433 void QuicConnection::OnError(QuicFramer* framer) {
434 // Packets that we can not or have not decrypted are dropped.
435 // TODO(rch): add stats to measure this.
436 if (!connected_ || last_packet_decrypted_ == false) {
437 return;
439 SendConnectionCloseWithDetails(framer->error(), framer->detailed_error());
442 void QuicConnection::MaybeSetFecAlarm(QuicPacketNumber packet_number) {
443 if (fec_alarm_->IsSet()) {
444 return;
446 QuicTime::Delta timeout = packet_generator_.GetFecTimeout(packet_number);
447 if (!timeout.IsInfinite()) {
448 fec_alarm_->Update(clock_->ApproximateNow().Add(timeout),
449 QuicTime::Delta::FromMilliseconds(1));
453 void QuicConnection::OnPacket() {
454 last_packet_decrypted_ = false;
455 last_packet_revived_ = false;
458 void QuicConnection::OnPublicResetPacket(const QuicPublicResetPacket& packet) {
459 // Check that any public reset packet with a different connection ID that was
460 // routed to this QuicConnection has been redirected before control reaches
461 // here. (Check for a bug regression.)
462 DCHECK_EQ(connection_id_, packet.public_header.connection_id);
463 if (debug_visitor_ != nullptr) {
464 debug_visitor_->OnPublicResetPacket(packet);
466 CloseConnection(QUIC_PUBLIC_RESET, true);
468 DVLOG(1) << ENDPOINT << "Connection " << connection_id()
469 << " closed via QUIC_PUBLIC_RESET from peer.";
472 bool QuicConnection::OnProtocolVersionMismatch(QuicVersion received_version) {
473 DVLOG(1) << ENDPOINT << "Received packet with mismatched version "
474 << received_version;
475 // TODO(satyamshekhar): Implement no server state in this mode.
476 if (perspective_ == Perspective::IS_CLIENT) {
477 LOG(DFATAL) << ENDPOINT << "Framer called OnProtocolVersionMismatch. "
478 << "Closing connection.";
479 CloseConnection(QUIC_INTERNAL_ERROR, false);
480 return false;
482 DCHECK_NE(version(), received_version);
484 if (debug_visitor_ != nullptr) {
485 debug_visitor_->OnProtocolVersionMismatch(received_version);
488 switch (version_negotiation_state_) {
489 case START_NEGOTIATION:
490 if (!framer_.IsSupportedVersion(received_version)) {
491 SendVersionNegotiationPacket();
492 version_negotiation_state_ = NEGOTIATION_IN_PROGRESS;
493 return false;
495 break;
497 case NEGOTIATION_IN_PROGRESS:
498 if (!framer_.IsSupportedVersion(received_version)) {
499 SendVersionNegotiationPacket();
500 return false;
502 break;
504 case NEGOTIATED_VERSION:
505 // Might be old packets that were sent by the client before the version
506 // was negotiated. Drop these.
507 return false;
509 default:
510 DCHECK(false);
513 version_negotiation_state_ = NEGOTIATED_VERSION;
514 visitor_->OnSuccessfulVersionNegotiation(received_version);
515 if (debug_visitor_ != nullptr) {
516 debug_visitor_->OnSuccessfulVersionNegotiation(received_version);
518 DVLOG(1) << ENDPOINT << "version negotiated " << received_version;
520 // Store the new version.
521 framer_.set_version(received_version);
523 // TODO(satyamshekhar): Store the packet number of this packet and close the
524 // connection if we ever received a packet with incorrect version and whose
525 // packet number is greater.
526 return true;
529 // Handles version negotiation for client connection.
530 void QuicConnection::OnVersionNegotiationPacket(
531 const QuicVersionNegotiationPacket& packet) {
532 // Check that any public reset packet with a different connection ID that was
533 // routed to this QuicConnection has been redirected before control reaches
534 // here. (Check for a bug regression.)
535 DCHECK_EQ(connection_id_, packet.connection_id);
536 if (perspective_ == Perspective::IS_SERVER) {
537 LOG(DFATAL) << ENDPOINT << "Framer parsed VersionNegotiationPacket."
538 << " Closing connection.";
539 CloseConnection(QUIC_INTERNAL_ERROR, false);
540 return;
542 if (debug_visitor_ != nullptr) {
543 debug_visitor_->OnVersionNegotiationPacket(packet);
546 if (version_negotiation_state_ != START_NEGOTIATION) {
547 // Possibly a duplicate version negotiation packet.
548 return;
551 if (std::find(packet.versions.begin(),
552 packet.versions.end(), version()) !=
553 packet.versions.end()) {
554 DLOG(WARNING) << ENDPOINT << "The server already supports our version. "
555 << "It should have accepted our connection.";
556 // Just drop the connection.
557 CloseConnection(QUIC_INVALID_VERSION_NEGOTIATION_PACKET, false);
558 return;
561 if (!SelectMutualVersion(packet.versions)) {
562 SendConnectionCloseWithDetails(QUIC_INVALID_VERSION,
563 "no common version found");
564 return;
567 DVLOG(1) << ENDPOINT
568 << "Negotiated version: " << QuicVersionToString(version());
569 server_supported_versions_ = packet.versions;
570 version_negotiation_state_ = NEGOTIATION_IN_PROGRESS;
571 RetransmitUnackedPackets(ALL_UNACKED_RETRANSMISSION);
574 void QuicConnection::OnRevivedPacket() {
577 bool QuicConnection::OnUnauthenticatedPublicHeader(
578 const QuicPacketPublicHeader& header) {
579 if (header.connection_id == connection_id_) {
580 return true;
583 ++stats_.packets_dropped;
584 DVLOG(1) << ENDPOINT << "Ignoring packet from unexpected ConnectionId: "
585 << header.connection_id << " instead of " << connection_id_;
586 if (debug_visitor_ != nullptr) {
587 debug_visitor_->OnIncorrectConnectionId(header.connection_id);
589 // If this is a server, the dispatcher routes each packet to the
590 // QuicConnection responsible for the packet's connection ID. So if control
591 // arrives here and this is a server, the dispatcher must be malfunctioning.
592 DCHECK_NE(Perspective::IS_SERVER, perspective_);
593 return false;
596 bool QuicConnection::OnUnauthenticatedHeader(const QuicPacketHeader& header) {
597 if (debug_visitor_ != nullptr) {
598 debug_visitor_->OnUnauthenticatedHeader(header);
601 // Check that any public reset packet with a different connection ID that was
602 // routed to this QuicConnection has been redirected before control reaches
603 // here.
604 DCHECK_EQ(connection_id_, header.public_header.connection_id);
605 return true;
608 void QuicConnection::OnDecryptedPacket(EncryptionLevel level) {
609 last_decrypted_packet_level_ = level;
610 last_packet_decrypted_ = true;
611 // If this packet was foward-secure encrypted and the forward-secure encrypter
612 // is not being used, start using it.
613 if (encryption_level_ != ENCRYPTION_FORWARD_SECURE &&
614 has_forward_secure_encrypter_ && level == ENCRYPTION_FORWARD_SECURE) {
615 SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
619 bool QuicConnection::OnPacketHeader(const QuicPacketHeader& header) {
620 if (debug_visitor_ != nullptr) {
621 debug_visitor_->OnPacketHeader(header);
624 if (!ProcessValidatedPacket()) {
625 return false;
628 // Will be decremented below if we fall through to return true.
629 ++stats_.packets_dropped;
631 if (!Near(header.packet_packet_number, last_header_.packet_packet_number)) {
632 DVLOG(1) << ENDPOINT << "Packet " << header.packet_packet_number
633 << " out of bounds. Discarding";
634 SendConnectionCloseWithDetails(QUIC_INVALID_PACKET_HEADER,
635 "packet number out of bounds");
636 return false;
639 // If this packet has already been seen, or the sender has told us that it
640 // will not be retransmitted, then stop processing the packet.
641 if (!received_packet_manager_.IsAwaitingPacket(header.packet_packet_number)) {
642 DVLOG(1) << ENDPOINT << "Packet " << header.packet_packet_number
643 << " no longer being waited for. Discarding.";
644 if (debug_visitor_ != nullptr) {
645 debug_visitor_->OnDuplicatePacket(header.packet_packet_number);
647 return false;
650 if (version_negotiation_state_ != NEGOTIATED_VERSION) {
651 if (perspective_ == Perspective::IS_SERVER) {
652 if (!header.public_header.version_flag) {
653 DLOG(WARNING) << ENDPOINT << "Packet " << header.packet_packet_number
654 << " without version flag before version negotiated.";
655 // Packets should have the version flag till version negotiation is
656 // done.
657 CloseConnection(QUIC_INVALID_VERSION, false);
658 return false;
659 } else {
660 DCHECK_EQ(1u, header.public_header.versions.size());
661 DCHECK_EQ(header.public_header.versions[0], version());
662 version_negotiation_state_ = NEGOTIATED_VERSION;
663 visitor_->OnSuccessfulVersionNegotiation(version());
664 if (debug_visitor_ != nullptr) {
665 debug_visitor_->OnSuccessfulVersionNegotiation(version());
668 } else {
669 DCHECK(!header.public_header.version_flag);
670 // If the client gets a packet without the version flag from the server
671 // it should stop sending version since the version negotiation is done.
672 packet_generator_.StopSendingVersion();
673 version_negotiation_state_ = NEGOTIATED_VERSION;
674 visitor_->OnSuccessfulVersionNegotiation(version());
675 if (debug_visitor_ != nullptr) {
676 debug_visitor_->OnSuccessfulVersionNegotiation(version());
681 DCHECK_EQ(NEGOTIATED_VERSION, version_negotiation_state_);
683 --stats_.packets_dropped;
684 DVLOG(1) << ENDPOINT << "Received packet header: " << header;
685 last_header_ = header;
686 DCHECK(connected_);
687 return true;
690 void QuicConnection::OnFecProtectedPayload(StringPiece payload) {
691 DCHECK_EQ(IN_FEC_GROUP, last_header_.is_in_fec_group);
692 DCHECK_NE(0u, last_header_.fec_group);
693 QuicFecGroup* group = GetFecGroup();
694 if (group != nullptr) {
695 group->Update(last_decrypted_packet_level_, last_header_, payload);
699 bool QuicConnection::OnStreamFrame(const QuicStreamFrame& frame) {
700 DCHECK(connected_);
701 if (debug_visitor_ != nullptr) {
702 debug_visitor_->OnStreamFrame(frame);
704 if (frame.stream_id != kCryptoStreamId &&
705 last_decrypted_packet_level_ == ENCRYPTION_NONE) {
706 DLOG(WARNING) << ENDPOINT
707 << "Received an unencrypted data frame: closing connection";
708 SendConnectionClose(QUIC_UNENCRYPTED_STREAM_DATA);
709 return false;
711 visitor_->OnStreamFrame(frame);
712 stats_.stream_bytes_received += frame.data.size();
713 should_last_packet_instigate_acks_ = true;
714 return connected_;
717 bool QuicConnection::OnAckFrame(const QuicAckFrame& incoming_ack) {
718 DCHECK(connected_);
719 if (debug_visitor_ != nullptr) {
720 debug_visitor_->OnAckFrame(incoming_ack);
722 DVLOG(1) << ENDPOINT << "OnAckFrame: " << incoming_ack;
724 if (last_header_.packet_packet_number <= largest_seen_packet_with_ack_) {
725 DVLOG(1) << ENDPOINT << "Received an old ack frame: ignoring";
726 return true;
729 if (!ValidateAckFrame(incoming_ack)) {
730 SendConnectionClose(QUIC_INVALID_ACK_DATA);
731 return false;
734 ProcessAckFrame(incoming_ack);
735 if (incoming_ack.is_truncated) {
736 should_last_packet_instigate_acks_ = true;
738 // If the peer is still waiting for a packet that we are no longer planning to
739 // send, send an ack to raise the high water mark.
740 if (!incoming_ack.missing_packets.Empty() &&
741 GetLeastUnacked() > incoming_ack.missing_packets.Min()) {
742 ++stop_waiting_count_;
743 } else {
744 stop_waiting_count_ = 0;
747 return connected_;
750 void QuicConnection::ProcessAckFrame(const QuicAckFrame& incoming_ack) {
751 largest_seen_packet_with_ack_ = last_header_.packet_packet_number;
752 sent_packet_manager_.OnIncomingAck(incoming_ack,
753 time_of_last_received_packet_);
754 sent_entropy_manager_.ClearEntropyBefore(
755 sent_packet_manager_.least_packet_awaited_by_peer() - 1);
757 // Always reset the retransmission alarm when an ack comes in, since we now
758 // have a better estimate of the current rtt than when it was set.
759 SetRetransmissionAlarm();
762 void QuicConnection::ProcessStopWaitingFrame(
763 const QuicStopWaitingFrame& stop_waiting) {
764 largest_seen_packet_with_stop_waiting_ = last_header_.packet_packet_number;
765 received_packet_manager_.UpdatePacketInformationSentByPeer(stop_waiting);
766 // Possibly close any FecGroups which are now irrelevant.
767 CloseFecGroupsBefore(stop_waiting.least_unacked + 1);
770 bool QuicConnection::OnStopWaitingFrame(const QuicStopWaitingFrame& frame) {
771 DCHECK(connected_);
773 if (last_header_.packet_packet_number <=
774 largest_seen_packet_with_stop_waiting_) {
775 DVLOG(1) << ENDPOINT << "Received an old stop waiting frame: ignoring";
776 return true;
779 if (!ValidateStopWaitingFrame(frame)) {
780 SendConnectionClose(QUIC_INVALID_STOP_WAITING_DATA);
781 return false;
784 if (debug_visitor_ != nullptr) {
785 debug_visitor_->OnStopWaitingFrame(frame);
788 last_stop_waiting_frame_ = frame;
789 return connected_;
792 bool QuicConnection::OnPingFrame(const QuicPingFrame& frame) {
793 DCHECK(connected_);
794 if (debug_visitor_ != nullptr) {
795 debug_visitor_->OnPingFrame(frame);
797 should_last_packet_instigate_acks_ = true;
798 return true;
801 bool QuicConnection::ValidateAckFrame(const QuicAckFrame& incoming_ack) {
802 if (incoming_ack.largest_observed > packet_generator_.packet_number()) {
803 DLOG(ERROR) << ENDPOINT << "Peer's observed unsent packet:"
804 << incoming_ack.largest_observed << " vs "
805 << packet_generator_.packet_number();
806 // We got an error for data we have not sent. Error out.
807 return false;
810 if (incoming_ack.largest_observed < sent_packet_manager_.largest_observed()) {
811 DLOG(ERROR) << ENDPOINT << "Peer's largest_observed packet decreased:"
812 << incoming_ack.largest_observed << " vs "
813 << sent_packet_manager_.largest_observed();
814 // A new ack has a diminished largest_observed value. Error out.
815 // If this was an old packet, we wouldn't even have checked.
816 return false;
819 if (!incoming_ack.missing_packets.Empty() &&
820 incoming_ack.missing_packets.Max() > incoming_ack.largest_observed) {
821 DLOG(ERROR) << ENDPOINT << "Peer sent missing packet: "
822 << incoming_ack.missing_packets.Max()
823 << " which is greater than largest observed: "
824 << incoming_ack.largest_observed;
825 return false;
828 if (!incoming_ack.missing_packets.Empty() &&
829 incoming_ack.missing_packets.Min() <
830 sent_packet_manager_.least_packet_awaited_by_peer()) {
831 DLOG(ERROR) << ENDPOINT << "Peer sent missing packet: "
832 << incoming_ack.missing_packets.Min()
833 << " which is smaller than least_packet_awaited_by_peer_: "
834 << sent_packet_manager_.least_packet_awaited_by_peer();
835 return false;
838 if (!sent_entropy_manager_.IsValidEntropy(
839 incoming_ack.largest_observed,
840 incoming_ack.missing_packets,
841 incoming_ack.entropy_hash)) {
842 DLOG(ERROR) << ENDPOINT << "Peer sent invalid entropy.";
843 return false;
846 for (QuicPacketNumber revived_packet : incoming_ack.revived_packets) {
847 if (!incoming_ack.missing_packets.Contains(revived_packet)) {
848 DLOG(ERROR) << ENDPOINT
849 << "Peer specified revived packet which was not missing.";
850 return false;
853 return true;
856 bool QuicConnection::ValidateStopWaitingFrame(
857 const QuicStopWaitingFrame& stop_waiting) {
858 if (stop_waiting.least_unacked <
859 received_packet_manager_.peer_least_packet_awaiting_ack()) {
860 DLOG(ERROR) << ENDPOINT << "Peer's sent low least_unacked: "
861 << stop_waiting.least_unacked << " vs "
862 << received_packet_manager_.peer_least_packet_awaiting_ack();
863 // We never process old ack frames, so this number should only increase.
864 return false;
867 if (stop_waiting.least_unacked > last_header_.packet_packet_number) {
868 DLOG(ERROR) << ENDPOINT
869 << "Peer sent least_unacked:" << stop_waiting.least_unacked
870 << " greater than the enclosing packet number:"
871 << last_header_.packet_packet_number;
872 return false;
875 return true;
878 void QuicConnection::OnFecData(const QuicFecData& fec) {
879 DCHECK_EQ(IN_FEC_GROUP, last_header_.is_in_fec_group);
880 DCHECK_NE(0u, last_header_.fec_group);
881 QuicFecGroup* group = GetFecGroup();
882 if (group != nullptr) {
883 group->UpdateFec(last_decrypted_packet_level_,
884 last_header_.packet_packet_number, fec);
888 bool QuicConnection::OnRstStreamFrame(const QuicRstStreamFrame& frame) {
889 DCHECK(connected_);
890 if (debug_visitor_ != nullptr) {
891 debug_visitor_->OnRstStreamFrame(frame);
893 DVLOG(1) << ENDPOINT
894 << "RST_STREAM_FRAME received for stream: " << frame.stream_id
895 << " with error: "
896 << QuicUtils::StreamErrorToString(frame.error_code);
897 visitor_->OnRstStream(frame);
898 should_last_packet_instigate_acks_ = true;
899 return connected_;
902 bool QuicConnection::OnConnectionCloseFrame(
903 const QuicConnectionCloseFrame& frame) {
904 DCHECK(connected_);
905 if (debug_visitor_ != nullptr) {
906 debug_visitor_->OnConnectionCloseFrame(frame);
908 DVLOG(1) << ENDPOINT << "CONNECTION_CLOSE_FRAME received for connection: "
909 << connection_id()
910 << " with error: " << QuicUtils::ErrorToString(frame.error_code)
911 << " " << frame.error_details;
912 CloseConnection(frame.error_code, true);
913 return connected_;
916 bool QuicConnection::OnGoAwayFrame(const QuicGoAwayFrame& frame) {
917 DCHECK(connected_);
918 if (debug_visitor_ != nullptr) {
919 debug_visitor_->OnGoAwayFrame(frame);
921 DVLOG(1) << ENDPOINT << "GOAWAY_FRAME received with last good stream: "
922 << frame.last_good_stream_id
923 << " and error: " << QuicUtils::ErrorToString(frame.error_code)
924 << " and reason: " << frame.reason_phrase;
926 goaway_received_ = true;
927 visitor_->OnGoAway(frame);
928 should_last_packet_instigate_acks_ = true;
929 return connected_;
932 bool QuicConnection::OnWindowUpdateFrame(const QuicWindowUpdateFrame& frame) {
933 DCHECK(connected_);
934 if (debug_visitor_ != nullptr) {
935 debug_visitor_->OnWindowUpdateFrame(frame);
937 DVLOG(1) << ENDPOINT
938 << "WINDOW_UPDATE_FRAME received for stream: " << frame.stream_id
939 << " with byte offset: " << frame.byte_offset;
940 visitor_->OnWindowUpdateFrame(frame);
941 should_last_packet_instigate_acks_ = true;
942 return connected_;
945 bool QuicConnection::OnBlockedFrame(const QuicBlockedFrame& frame) {
946 DCHECK(connected_);
947 if (debug_visitor_ != nullptr) {
948 debug_visitor_->OnBlockedFrame(frame);
950 DVLOG(1) << ENDPOINT
951 << "BLOCKED_FRAME received for stream: " << frame.stream_id;
952 visitor_->OnBlockedFrame(frame);
953 should_last_packet_instigate_acks_ = true;
954 return connected_;
957 void QuicConnection::OnPacketComplete() {
958 // Don't do anything if this packet closed the connection.
959 if (!connected_) {
960 ClearLastFrames();
961 return;
964 DVLOG(1) << ENDPOINT << (last_packet_revived_ ? "Revived" : "Got")
965 << " packet " << last_header_.packet_packet_number << "for "
966 << last_header_.public_header.connection_id;
968 ++num_packets_received_since_last_ack_sent_;
970 // Call MaybeQueueAck() before recording the received packet, since we want
971 // to trigger an ack if the newly received packet was previously missing.
972 MaybeQueueAck();
974 // Record received or revived packet to populate ack info correctly before
975 // processing stream frames, since the processing may result in a response
976 // packet with a bundled ack.
977 if (last_packet_revived_) {
978 received_packet_manager_.RecordPacketRevived(
979 last_header_.packet_packet_number);
980 } else {
981 received_packet_manager_.RecordPacketReceived(
982 last_size_, last_header_, time_of_last_received_packet_);
985 // Continue to process stop waiting frames later, because the packet needs
986 // to be considered 'received' before the entropy can be updated.
987 if (last_stop_waiting_frame_.least_unacked > 0) {
988 ProcessStopWaitingFrame(last_stop_waiting_frame_);
989 if (!connected_) {
990 return;
994 // If there are new missing packets to report, send an ack immediately.
995 if (ShouldLastPacketInstigateAck() &&
996 received_packet_manager_.HasNewMissingPackets()) {
997 ack_queued_ = true;
998 ack_alarm_->Cancel();
1001 ClearLastFrames();
1002 MaybeCloseIfTooManyOutstandingPackets();
1005 void QuicConnection::MaybeQueueAck() {
1006 // If the last packet is an ack, don't ack it.
1007 if (!ShouldLastPacketInstigateAck()) {
1008 return;
1010 // If the incoming packet was missing, send an ack immediately.
1011 ack_queued_ =
1012 received_packet_manager_.IsMissing(last_header_.packet_packet_number);
1014 if (!ack_queued_) {
1015 if (ack_alarm_->IsSet()) {
1016 ack_queued_ = true;
1017 } else {
1018 ack_alarm_->Set(
1019 clock_->ApproximateNow().Add(sent_packet_manager_.DelayedAckTime()));
1020 DVLOG(1) << "Ack timer set; next packet or timer will trigger ACK.";
1024 if (ack_queued_) {
1025 ack_alarm_->Cancel();
1029 void QuicConnection::ClearLastFrames() {
1030 should_last_packet_instigate_acks_ = false;
1031 last_stop_waiting_frame_.least_unacked = 0;
1034 void QuicConnection::MaybeCloseIfTooManyOutstandingPackets() {
1035 // This occurs if we don't discard old packets we've sent fast enough.
1036 // It's possible largest observed is less than least unacked.
1037 if (sent_packet_manager_.largest_observed() >
1038 (sent_packet_manager_.GetLeastUnacked() + kMaxTrackedPackets)) {
1039 SendConnectionCloseWithDetails(
1040 QUIC_TOO_MANY_OUTSTANDING_SENT_PACKETS,
1041 StringPrintf("More than %" PRIu64 " outstanding.", kMaxTrackedPackets));
1043 // This occurs if there are received packet gaps and the peer does not raise
1044 // the least unacked fast enough.
1045 if (received_packet_manager_.NumTrackedPackets() > kMaxTrackedPackets) {
1046 SendConnectionCloseWithDetails(
1047 QUIC_TOO_MANY_OUTSTANDING_RECEIVED_PACKETS,
1048 StringPrintf("More than %" PRIu64 " outstanding.", kMaxTrackedPackets));
1052 void QuicConnection::PopulateAckFrame(QuicAckFrame* ack) {
1053 received_packet_manager_.UpdateReceivedPacketInfo(ack,
1054 clock_->ApproximateNow());
1057 void QuicConnection::PopulateStopWaitingFrame(
1058 QuicStopWaitingFrame* stop_waiting) {
1059 stop_waiting->least_unacked = GetLeastUnacked();
1060 stop_waiting->entropy_hash = sent_entropy_manager_.GetCumulativeEntropy(
1061 stop_waiting->least_unacked - 1);
1064 bool QuicConnection::ShouldLastPacketInstigateAck() const {
1065 if (should_last_packet_instigate_acks_) {
1066 return true;
1068 // Always send an ack every 20 packets in order to allow the peer to discard
1069 // information from the SentPacketManager and provide an RTT measurement.
1070 if (num_packets_received_since_last_ack_sent_ >=
1071 kMaxPacketsReceivedBeforeAckSend) {
1072 return true;
1074 return false;
1077 QuicPacketNumber QuicConnection::GetLeastUnacked() const {
1078 return sent_packet_manager_.GetLeastUnacked();
1081 void QuicConnection::MaybeSendInResponseToPacket() {
1082 if (!connected_) {
1083 return;
1085 ScopedPacketBundler bundler(this, ack_queued_ ? SEND_ACK : NO_ACK);
1087 // Now that we have received an ack, we might be able to send packets which
1088 // are queued locally, or drain streams which are blocked.
1089 WriteIfNotBlocked();
1092 void QuicConnection::SendVersionNegotiationPacket() {
1093 // TODO(alyssar): implement zero server state negotiation.
1094 pending_version_negotiation_packet_ = true;
1095 if (writer_->IsWriteBlocked()) {
1096 visitor_->OnWriteBlocked();
1097 return;
1099 DVLOG(1) << ENDPOINT << "Sending version negotiation packet: {"
1100 << QuicVersionVectorToString(framer_.supported_versions()) << "}";
1101 scoped_ptr<QuicEncryptedPacket> version_packet(
1102 packet_generator_.SerializeVersionNegotiationPacket(
1103 framer_.supported_versions()));
1104 WriteResult result = writer_->WritePacket(
1105 version_packet->data(), version_packet->length(),
1106 self_address().address(), peer_address());
1108 if (result.status == WRITE_STATUS_ERROR) {
1109 // We can't send an error as the socket is presumably borked.
1110 CloseConnection(QUIC_PACKET_WRITE_ERROR, false);
1111 return;
1113 if (result.status == WRITE_STATUS_BLOCKED) {
1114 visitor_->OnWriteBlocked();
1115 if (writer_->IsWriteBlockedDataBuffered()) {
1116 pending_version_negotiation_packet_ = false;
1118 return;
1121 pending_version_negotiation_packet_ = false;
1124 QuicConsumedData QuicConnection::SendStreamData(
1125 QuicStreamId id,
1126 const QuicIOVector& iov,
1127 QuicStreamOffset offset,
1128 bool fin,
1129 FecProtection fec_protection,
1130 QuicAckNotifier::DelegateInterface* delegate) {
1131 if (!fin && iov.total_length == 0) {
1132 LOG(DFATAL) << "Attempt to send empty stream frame";
1133 return QuicConsumedData(0, false);
1136 // Opportunistically bundle an ack with every outgoing packet.
1137 // Particularly, we want to bundle with handshake packets since we don't know
1138 // which decrypter will be used on an ack packet following a handshake
1139 // packet (a handshake packet from client to server could result in a REJ or a
1140 // SHLO from the server, leading to two different decrypters at the server.)
1142 // TODO(jri): Note that ConsumeData may cause a response packet to be sent.
1143 // We may end up sending stale ack information if there are undecryptable
1144 // packets hanging around and/or there are revivable packets which may get
1145 // handled after this packet is sent. Change ScopedPacketBundler to do the
1146 // right thing: check ack_queued_, and then check undecryptable packets and
1147 // also if there is possibility of revival. Only bundle an ack if there's no
1148 // processing left that may cause received_info_ to change.
1149 ScopedRetransmissionScheduler alarm_delayer(this);
1150 ScopedPacketBundler ack_bundler(this, BUNDLE_PENDING_ACK);
1151 return packet_generator_.ConsumeData(id, iov, offset, fin, fec_protection,
1152 delegate);
1155 void QuicConnection::SendRstStream(QuicStreamId id,
1156 QuicRstStreamErrorCode error,
1157 QuicStreamOffset bytes_written) {
1158 // Opportunistically bundle an ack with this outgoing packet.
1159 ScopedPacketBundler ack_bundler(this, BUNDLE_PENDING_ACK);
1160 packet_generator_.AddControlFrame(QuicFrame(new QuicRstStreamFrame(
1161 id, AdjustErrorForVersion(error, version()), bytes_written)));
1163 sent_packet_manager_.CancelRetransmissionsForStream(id);
1164 // Remove all queued packets which only contain data for the reset stream.
1165 QueuedPacketList::iterator packet_iterator = queued_packets_.begin();
1166 while (packet_iterator != queued_packets_.end()) {
1167 RetransmittableFrames* retransmittable_frames =
1168 packet_iterator->serialized_packet.retransmittable_frames;
1169 if (!retransmittable_frames) {
1170 ++packet_iterator;
1171 continue;
1173 retransmittable_frames->RemoveFramesForStream(id);
1174 if (!retransmittable_frames->frames().empty()) {
1175 ++packet_iterator;
1176 continue;
1178 delete packet_iterator->serialized_packet.retransmittable_frames;
1179 delete packet_iterator->serialized_packet.packet;
1180 packet_iterator->serialized_packet.retransmittable_frames = nullptr;
1181 packet_iterator->serialized_packet.packet = nullptr;
1182 packet_iterator = queued_packets_.erase(packet_iterator);
1186 void QuicConnection::SendWindowUpdate(QuicStreamId id,
1187 QuicStreamOffset byte_offset) {
1188 // Opportunistically bundle an ack with this outgoing packet.
1189 ScopedPacketBundler ack_bundler(this, BUNDLE_PENDING_ACK);
1190 packet_generator_.AddControlFrame(
1191 QuicFrame(new QuicWindowUpdateFrame(id, byte_offset)));
1194 void QuicConnection::SendBlocked(QuicStreamId id) {
1195 // Opportunistically bundle an ack with this outgoing packet.
1196 ScopedPacketBundler ack_bundler(this, BUNDLE_PENDING_ACK);
1197 packet_generator_.AddControlFrame(QuicFrame(new QuicBlockedFrame(id)));
1200 const QuicConnectionStats& QuicConnection::GetStats() {
1201 const RttStats* rtt_stats = sent_packet_manager_.GetRttStats();
1203 // Update rtt and estimated bandwidth.
1204 QuicTime::Delta min_rtt = rtt_stats->min_rtt();
1205 if (min_rtt.IsZero()) {
1206 // If min RTT has not been set, use initial RTT instead.
1207 min_rtt = QuicTime::Delta::FromMicroseconds(rtt_stats->initial_rtt_us());
1209 stats_.min_rtt_us = min_rtt.ToMicroseconds();
1211 QuicTime::Delta srtt = rtt_stats->smoothed_rtt();
1212 if (srtt.IsZero()) {
1213 // If SRTT has not been set, use initial RTT instead.
1214 srtt = QuicTime::Delta::FromMicroseconds(rtt_stats->initial_rtt_us());
1216 stats_.srtt_us = srtt.ToMicroseconds();
1218 stats_.estimated_bandwidth = sent_packet_manager_.BandwidthEstimate();
1219 stats_.max_packet_size = packet_generator_.GetMaxPacketLength();
1220 stats_.max_received_packet_size = largest_received_packet_size_;
1221 return stats_;
1224 void QuicConnection::ProcessUdpPacket(const IPEndPoint& self_address,
1225 const IPEndPoint& peer_address,
1226 const QuicEncryptedPacket& packet) {
1227 if (!connected_) {
1228 return;
1230 // TODO(rtenneti): Remove ScopedTracker below once crbug.com/462789 is fixed.
1231 tracked_objects::ScopedTracker tracking_profile(
1232 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1233 "462789 QuicConnection::ProcessUdpPacket"));
1234 if (debug_visitor_ != nullptr) {
1235 debug_visitor_->OnPacketReceived(self_address, peer_address, packet);
1237 last_size_ = packet.length();
1239 CheckForAddressMigration(self_address, peer_address);
1241 stats_.bytes_received += packet.length();
1242 ++stats_.packets_received;
1244 ScopedRetransmissionScheduler alarm_delayer(this);
1245 if (!framer_.ProcessPacket(packet)) {
1246 // If we are unable to decrypt this packet, it might be
1247 // because the CHLO or SHLO packet was lost.
1248 if (framer_.error() == QUIC_DECRYPTION_FAILURE) {
1249 if (encryption_level_ != ENCRYPTION_FORWARD_SECURE &&
1250 undecryptable_packets_.size() < max_undecryptable_packets_) {
1251 QueueUndecryptablePacket(packet);
1252 } else if (debug_visitor_ != nullptr) {
1253 debug_visitor_->OnUndecryptablePacket();
1256 DVLOG(1) << ENDPOINT << "Unable to process packet. Last packet processed: "
1257 << last_header_.packet_packet_number;
1258 return;
1261 ++stats_.packets_processed;
1262 MaybeProcessUndecryptablePackets();
1263 MaybeProcessRevivedPacket();
1264 MaybeSendInResponseToPacket();
1265 SetPingAlarm();
1268 void QuicConnection::CheckForAddressMigration(
1269 const IPEndPoint& self_address, const IPEndPoint& peer_address) {
1270 peer_ip_changed_ = false;
1271 peer_port_changed_ = false;
1272 self_ip_changed_ = false;
1273 self_port_changed_ = false;
1275 if (peer_address_.address().empty()) {
1276 peer_address_ = peer_address;
1278 if (self_address_.address().empty()) {
1279 self_address_ = self_address;
1282 if (!peer_address.address().empty() && !peer_address_.address().empty()) {
1283 peer_ip_changed_ = (peer_address.address() != peer_address_.address());
1284 peer_port_changed_ = (peer_address.port() != peer_address_.port());
1286 // Store in case we want to migrate connection in ProcessValidatedPacket.
1287 migrating_peer_ip_ = peer_address.address();
1288 migrating_peer_port_ = peer_address.port();
1291 if (!self_address.address().empty() && !self_address_.address().empty()) {
1292 self_ip_changed_ = (self_address.address() != self_address_.address());
1293 self_port_changed_ = (self_address.port() != self_address_.port());
1296 // TODO(vasilvv): reset maximum packet size on connection migration. Whenever
1297 // the connection is migrated, it usually ends up being on a different path,
1298 // with possibly smaller MTU. This means the max packet size has to be reset
1299 // and MTU discovery mechanism re-initialized. The main reason the code does
1300 // not do it now is that the retransmission code currently cannot deal with
1301 // the case when it needs to resend a packet created with larger MTU (see
1302 // b/22172803).
1305 void QuicConnection::OnCanWrite() {
1306 DCHECK(!writer_->IsWriteBlocked());
1308 WriteQueuedPackets();
1309 WritePendingRetransmissions();
1311 // Sending queued packets may have caused the socket to become write blocked,
1312 // or the congestion manager to prohibit sending. If we've sent everything
1313 // we had queued and we're still not blocked, let the visitor know it can
1314 // write more.
1315 if (!CanWrite(HAS_RETRANSMITTABLE_DATA)) {
1316 return;
1319 { // Limit the scope of the bundler. ACK inclusion happens elsewhere.
1320 ScopedPacketBundler bundler(this, NO_ACK);
1321 visitor_->OnCanWrite();
1324 // After the visitor writes, it may have caused the socket to become write
1325 // blocked or the congestion manager to prohibit sending, so check again.
1326 if (visitor_->WillingAndAbleToWrite() &&
1327 !resume_writes_alarm_->IsSet() &&
1328 CanWrite(HAS_RETRANSMITTABLE_DATA)) {
1329 // We're not write blocked, but some stream didn't write out all of its
1330 // bytes. Register for 'immediate' resumption so we'll keep writing after
1331 // other connections and events have had a chance to use the thread.
1332 resume_writes_alarm_->Set(clock_->ApproximateNow());
1336 void QuicConnection::WriteIfNotBlocked() {
1337 if (!writer_->IsWriteBlocked()) {
1338 OnCanWrite();
1342 bool QuicConnection::ProcessValidatedPacket() {
1343 if (self_ip_changed_ || self_port_changed_) {
1344 SendConnectionCloseWithDetails(QUIC_ERROR_MIGRATING_ADDRESS,
1345 "Self address migration is not supported.");
1346 return false;
1349 if (peer_ip_changed_ || peer_port_changed_) {
1350 IPEndPoint old_peer_address = peer_address_;
1351 peer_address_ = IPEndPoint(
1352 peer_ip_changed_ ? migrating_peer_ip_ : peer_address_.address(),
1353 peer_port_changed_ ? migrating_peer_port_ : peer_address_.port());
1355 DVLOG(1) << ENDPOINT << "Peer's ip:port changed from "
1356 << old_peer_address.ToString() << " to "
1357 << peer_address_.ToString() << ", migrating connection.";
1359 if (FLAGS_send_goaway_after_client_migration) {
1360 visitor_->OnConnectionMigration();
1364 time_of_last_received_packet_ = clock_->Now();
1365 DVLOG(1) << ENDPOINT << "time of last received packet: "
1366 << time_of_last_received_packet_.ToDebuggingValue();
1368 if (last_size_ > largest_received_packet_size_) {
1369 largest_received_packet_size_ = last_size_;
1372 if (perspective_ == Perspective::IS_SERVER &&
1373 encryption_level_ == ENCRYPTION_NONE &&
1374 last_size_ > packet_generator_.GetMaxPacketLength()) {
1375 SetMaxPacketLength(last_size_);
1377 return true;
1380 void QuicConnection::WriteQueuedPackets() {
1381 DCHECK(!writer_->IsWriteBlocked());
1383 if (pending_version_negotiation_packet_) {
1384 SendVersionNegotiationPacket();
1387 QueuedPacketList::iterator packet_iterator = queued_packets_.begin();
1388 while (packet_iterator != queued_packets_.end() &&
1389 WritePacket(&(*packet_iterator))) {
1390 packet_iterator = queued_packets_.erase(packet_iterator);
1394 void QuicConnection::WritePendingRetransmissions() {
1395 // Keep writing as long as there's a pending retransmission which can be
1396 // written.
1397 while (sent_packet_manager_.HasPendingRetransmissions()) {
1398 const QuicSentPacketManager::PendingRetransmission pending =
1399 sent_packet_manager_.NextPendingRetransmission();
1400 if (!CanWrite(HAS_RETRANSMITTABLE_DATA)) {
1401 break;
1404 // Re-packetize the frames with a new packet number for retransmission.
1405 // Retransmitted data packets do not use FEC, even when it's enabled.
1406 // Retransmitted packets use the same packet number length as the
1407 // original.
1408 // Flush the packet generator before making a new packet.
1409 // TODO(ianswett): Implement ReserializeAllFrames as a separate path that
1410 // does not require the creator to be flushed.
1411 packet_generator_.FlushAllQueuedFrames();
1412 char buffer[kMaxPacketSize];
1413 SerializedPacket serialized_packet = packet_generator_.ReserializeAllFrames(
1414 pending.retransmittable_frames, pending.packet_number_length, buffer,
1415 kMaxPacketSize);
1416 if (serialized_packet.packet == nullptr) {
1417 // We failed to serialize the packet, so close the connection.
1418 // CloseConnection does not send close packet, so no infinite loop here.
1419 CloseConnection(QUIC_ENCRYPTION_FAILURE, false);
1420 return;
1423 DVLOG(1) << ENDPOINT << "Retransmitting " << pending.packet_number << " as "
1424 << serialized_packet.packet_number;
1425 SendOrQueuePacket(QueuedPacket(
1426 serialized_packet, pending.retransmittable_frames.encryption_level(),
1427 pending.transmission_type, pending.packet_number));
1431 void QuicConnection::RetransmitUnackedPackets(
1432 TransmissionType retransmission_type) {
1433 sent_packet_manager_.RetransmitUnackedPackets(retransmission_type);
1435 WriteIfNotBlocked();
1438 void QuicConnection::NeuterUnencryptedPackets() {
1439 sent_packet_manager_.NeuterUnencryptedPackets();
1440 // This may have changed the retransmission timer, so re-arm it.
1441 SetRetransmissionAlarm();
1444 bool QuicConnection::ShouldGeneratePacket(
1445 HasRetransmittableData retransmittable,
1446 IsHandshake handshake) {
1447 // We should serialize handshake packets immediately to ensure that they
1448 // end up sent at the right encryption level.
1449 if (handshake == IS_HANDSHAKE) {
1450 return true;
1453 return CanWrite(retransmittable);
1456 bool QuicConnection::CanWrite(HasRetransmittableData retransmittable) {
1457 if (!connected_) {
1458 return false;
1461 if (writer_->IsWriteBlocked()) {
1462 visitor_->OnWriteBlocked();
1463 return false;
1466 QuicTime now = clock_->Now();
1467 QuicTime::Delta delay = sent_packet_manager_.TimeUntilSend(
1468 now, retransmittable);
1469 if (delay.IsInfinite()) {
1470 send_alarm_->Cancel();
1471 return false;
1474 // If the scheduler requires a delay, then we can not send this packet now.
1475 if (!delay.IsZero()) {
1476 send_alarm_->Update(now.Add(delay), QuicTime::Delta::FromMilliseconds(1));
1477 DVLOG(1) << ENDPOINT << "Delaying sending " << delay.ToMilliseconds()
1478 << "ms";
1479 return false;
1481 send_alarm_->Cancel();
1482 return true;
1485 bool QuicConnection::WritePacket(QueuedPacket* packet) {
1486 if (!WritePacketInner(packet)) {
1487 return false;
1489 delete packet->serialized_packet.retransmittable_frames;
1490 delete packet->serialized_packet.packet;
1491 packet->serialized_packet.retransmittable_frames = nullptr;
1492 packet->serialized_packet.packet = nullptr;
1493 return true;
1496 bool QuicConnection::WritePacketInner(QueuedPacket* packet) {
1497 if (FLAGS_quic_close_connection_out_of_order_sending &&
1498 packet->serialized_packet.packet_number <
1499 sent_packet_manager_.largest_sent_packet()) {
1500 LOG(DFATAL) << "Attempt to write packet:"
1501 << packet->serialized_packet.packet_number
1502 << " after:" << sent_packet_manager_.largest_sent_packet();
1503 SendConnectionCloseWithDetails(QUIC_INTERNAL_ERROR,
1504 "Packet written out of order.");
1505 return true;
1507 if (ShouldDiscardPacket(*packet)) {
1508 ++stats_.packets_discarded;
1509 return true;
1511 // Connection close packets are encrypted and saved, so don't exit early.
1512 const bool is_connection_close = IsConnectionClose(*packet);
1513 if (writer_->IsWriteBlocked() && !is_connection_close) {
1514 return false;
1517 QuicPacketNumber packet_number = packet->serialized_packet.packet_number;
1518 DCHECK_LE(packet_number_of_last_sent_packet_, packet_number);
1519 packet_number_of_last_sent_packet_ = packet_number;
1521 QuicEncryptedPacket* encrypted = packet->serialized_packet.packet;
1522 // Connection close packets are eventually owned by TimeWaitListManager.
1523 // Others are deleted at the end of this call.
1524 if (is_connection_close) {
1525 DCHECK(connection_close_packet_.get() == nullptr);
1526 // Clone the packet so it's owned in the future.
1527 connection_close_packet_.reset(encrypted->Clone());
1528 // This assures we won't try to write *forced* packets when blocked.
1529 // Return true to stop processing.
1530 if (writer_->IsWriteBlocked()) {
1531 visitor_->OnWriteBlocked();
1532 return true;
1536 if (!FLAGS_quic_allow_oversized_packets_for_test) {
1537 DCHECK_LE(encrypted->length(), kMaxPacketSize);
1539 DCHECK_LE(encrypted->length(), packet_generator_.GetMaxPacketLength());
1540 DVLOG(1) << ENDPOINT << "Sending packet " << packet_number << " : "
1541 << (packet->serialized_packet.is_fec_packet
1542 ? "FEC "
1543 : (IsRetransmittable(*packet) == HAS_RETRANSMITTABLE_DATA
1544 ? "data bearing "
1545 : " ack only "))
1546 << ", encryption level: "
1547 << QuicUtils::EncryptionLevelToString(packet->encryption_level)
1548 << ", encrypted length:" << encrypted->length();
1549 DVLOG(2) << ENDPOINT << "packet(" << packet_number << "): " << std::endl
1550 << QuicUtils::StringToHexASCIIDump(encrypted->AsStringPiece());
1552 // Measure the RTT from before the write begins to avoid underestimating the
1553 // min_rtt_, especially in cases where the thread blocks or gets swapped out
1554 // during the WritePacket below.
1555 QuicTime packet_send_time = clock_->Now();
1556 WriteResult result = writer_->WritePacket(encrypted->data(),
1557 encrypted->length(),
1558 self_address().address(),
1559 peer_address());
1560 if (result.error_code == ERR_IO_PENDING) {
1561 DCHECK_EQ(WRITE_STATUS_BLOCKED, result.status);
1564 if (result.status == WRITE_STATUS_BLOCKED) {
1565 visitor_->OnWriteBlocked();
1566 // If the socket buffers the the data, then the packet should not
1567 // be queued and sent again, which would result in an unnecessary
1568 // duplicate packet being sent. The helper must call OnCanWrite
1569 // when the write completes, and OnWriteError if an error occurs.
1570 if (!writer_->IsWriteBlockedDataBuffered()) {
1571 return false;
1574 if (result.status != WRITE_STATUS_ERROR && debug_visitor_ != nullptr) {
1575 // Pass the write result to the visitor.
1576 debug_visitor_->OnPacketSent(
1577 packet->serialized_packet, packet->original_packet_number,
1578 packet->encryption_level, packet->transmission_type, *encrypted,
1579 packet_send_time);
1581 if (packet->transmission_type == NOT_RETRANSMISSION) {
1582 time_of_last_sent_new_packet_ = packet_send_time;
1584 SetPingAlarm();
1585 MaybeSetFecAlarm(packet_number);
1586 MaybeSetMtuAlarm();
1587 DVLOG(1) << ENDPOINT << "time we began writing last sent packet: "
1588 << packet_send_time.ToDebuggingValue();
1590 // TODO(ianswett): Change the packet number length and other packet creator
1591 // options by a more explicit API than setting a struct value directly,
1592 // perhaps via the NetworkChangeVisitor.
1593 packet_generator_.UpdateSequenceNumberLength(
1594 sent_packet_manager_.least_packet_awaited_by_peer(),
1595 sent_packet_manager_.EstimateMaxPacketsInFlight(max_packet_length()));
1597 bool reset_retransmission_alarm = sent_packet_manager_.OnPacketSent(
1598 &packet->serialized_packet, packet->original_packet_number,
1599 packet_send_time, encrypted->length(), packet->transmission_type,
1600 IsRetransmittable(*packet));
1602 if (reset_retransmission_alarm || !retransmission_alarm_->IsSet()) {
1603 SetRetransmissionAlarm();
1606 stats_.bytes_sent += result.bytes_written;
1607 ++stats_.packets_sent;
1608 if (packet->transmission_type != NOT_RETRANSMISSION) {
1609 stats_.bytes_retransmitted += result.bytes_written;
1610 ++stats_.packets_retransmitted;
1613 if (result.status == WRITE_STATUS_ERROR) {
1614 OnWriteError(result.error_code);
1615 DLOG(ERROR) << ENDPOINT << "failed writing " << encrypted->length()
1616 << " bytes "
1617 << " from host " << self_address().ToStringWithoutPort()
1618 << " to address " << peer_address().ToString();
1619 return false;
1622 return true;
1625 bool QuicConnection::ShouldDiscardPacket(const QueuedPacket& packet) {
1626 if (!connected_) {
1627 DVLOG(1) << ENDPOINT
1628 << "Not sending packet as connection is disconnected.";
1629 return true;
1632 QuicPacketNumber packet_number = packet.serialized_packet.packet_number;
1633 if (encryption_level_ == ENCRYPTION_FORWARD_SECURE &&
1634 packet.encryption_level == ENCRYPTION_NONE) {
1635 // Drop packets that are NULL encrypted since the peer won't accept them
1636 // anymore.
1637 DVLOG(1) << ENDPOINT << "Dropping NULL encrypted packet: " << packet_number
1638 << " since the connection is forward secure.";
1639 return true;
1642 // If a retransmission has been acked before sending, don't send it.
1643 // This occurs if a packet gets serialized, queued, then discarded.
1644 if (packet.transmission_type != NOT_RETRANSMISSION &&
1645 (!sent_packet_manager_.IsUnacked(packet.original_packet_number) ||
1646 !sent_packet_manager_.HasRetransmittableFrames(
1647 packet.original_packet_number))) {
1648 DVLOG(1) << ENDPOINT << "Dropping unacked packet: " << packet_number
1649 << " A previous transmission was acked while write blocked.";
1650 return true;
1653 return false;
1656 void QuicConnection::OnWriteError(int error_code) {
1657 DVLOG(1) << ENDPOINT << "Write failed with error: " << error_code
1658 << " (" << ErrorToString(error_code) << ")";
1659 // We can't send an error as the socket is presumably borked.
1660 CloseConnection(QUIC_PACKET_WRITE_ERROR, false);
1663 void QuicConnection::OnSerializedPacket(
1664 const SerializedPacket& serialized_packet) {
1665 if (serialized_packet.packet == nullptr) {
1666 // We failed to serialize the packet, so close the connection.
1667 // CloseConnection does not send close packet, so no infinite loop here.
1668 CloseConnection(QUIC_ENCRYPTION_FAILURE, false);
1669 return;
1671 sent_packet_manager_.OnSerializedPacket(serialized_packet);
1672 if (serialized_packet.is_fec_packet && fec_alarm_->IsSet()) {
1673 // If an FEC packet is serialized with the FEC alarm set, cancel the alarm.
1674 fec_alarm_->Cancel();
1676 SendOrQueuePacket(QueuedPacket(serialized_packet, encryption_level_));
1679 void QuicConnection::OnResetFecGroup() {
1680 if (!fec_alarm_->IsSet()) {
1681 return;
1683 // If an FEC Group is closed with the FEC alarm set, cancel the alarm.
1684 fec_alarm_->Cancel();
1687 void QuicConnection::OnCongestionWindowChange() {
1688 packet_generator_.OnCongestionWindowChange(
1689 sent_packet_manager_.EstimateMaxPacketsInFlight(max_packet_length()));
1690 visitor_->OnCongestionWindowChange(clock_->ApproximateNow());
1693 void QuicConnection::OnRttChange() {
1694 // Uses the connection's smoothed RTT. If zero, uses initial_rtt.
1695 QuicTime::Delta rtt = sent_packet_manager_.GetRttStats()->smoothed_rtt();
1696 if (rtt.IsZero()) {
1697 rtt = QuicTime::Delta::FromMicroseconds(
1698 sent_packet_manager_.GetRttStats()->initial_rtt_us());
1700 packet_generator_.OnRttChange(rtt);
1703 void QuicConnection::OnHandshakeComplete() {
1704 sent_packet_manager_.SetHandshakeConfirmed();
1705 // The client should immediately ack the SHLO to confirm the handshake is
1706 // complete with the server.
1707 if (perspective_ == Perspective::IS_CLIENT && !ack_queued_) {
1708 ack_alarm_->Cancel();
1709 ack_alarm_->Set(clock_->ApproximateNow());
1713 void QuicConnection::SendOrQueuePacket(QueuedPacket packet) {
1714 // The caller of this function is responsible for checking CanWrite().
1715 if (packet.serialized_packet.packet == nullptr) {
1716 LOG(DFATAL)
1717 << "packet.serialized_packet.packet == nullptr in to SendOrQueuePacket";
1718 return;
1721 sent_entropy_manager_.RecordPacketEntropyHash(
1722 packet.serialized_packet.packet_number,
1723 packet.serialized_packet.entropy_hash);
1724 // If there are already queued packets, queue this one immediately to ensure
1725 // it's written in sequence number order.
1726 if (!queued_packets_.empty() || !WritePacket(&packet)) {
1727 // Take ownership of the underlying encrypted packet.
1728 if (!packet.serialized_packet.packet->owns_buffer()) {
1729 scoped_ptr<QuicEncryptedPacket> encrypted_deleter(
1730 packet.serialized_packet.packet);
1731 packet.serialized_packet.packet =
1732 packet.serialized_packet.packet->Clone();
1734 queued_packets_.push_back(packet);
1737 // If a forward-secure encrypter is available but is not being used and the
1738 // next packet number is the first packet which requires
1739 // forward security, start using the forward-secure encrypter.
1740 if (encryption_level_ != ENCRYPTION_FORWARD_SECURE &&
1741 has_forward_secure_encrypter_ &&
1742 packet.serialized_packet.packet_number >=
1743 first_required_forward_secure_packet_ - 1) {
1744 SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
1748 void QuicConnection::SendPing() {
1749 if (retransmission_alarm_->IsSet()) {
1750 return;
1752 packet_generator_.AddControlFrame(QuicFrame(new QuicPingFrame));
1755 void QuicConnection::SendAck() {
1756 ack_alarm_->Cancel();
1757 ack_queued_ = false;
1758 stop_waiting_count_ = 0;
1759 num_packets_received_since_last_ack_sent_ = 0;
1761 packet_generator_.SetShouldSendAck(true);
1764 void QuicConnection::OnRetransmissionTimeout() {
1765 if (!sent_packet_manager_.HasUnackedPackets()) {
1766 return;
1769 sent_packet_manager_.OnRetransmissionTimeout();
1770 WriteIfNotBlocked();
1772 // A write failure can result in the connection being closed, don't attempt to
1773 // write further packets, or to set alarms.
1774 if (!connected_) {
1775 return;
1778 // In the TLP case, the SentPacketManager gives the connection the opportunity
1779 // to send new data before retransmitting.
1780 if (sent_packet_manager_.MaybeRetransmitTailLossProbe()) {
1781 // Send the pending retransmission now that it's been queued.
1782 WriteIfNotBlocked();
1785 // Ensure the retransmission alarm is always set if there are unacked packets
1786 // and nothing waiting to be sent.
1787 // This happens if the loss algorithm invokes a timer based loss, but the
1788 // packet doesn't need to be retransmitted.
1789 if (!HasQueuedData() && !retransmission_alarm_->IsSet()) {
1790 SetRetransmissionAlarm();
1794 void QuicConnection::SetEncrypter(EncryptionLevel level,
1795 QuicEncrypter* encrypter) {
1796 packet_generator_.SetEncrypter(level, encrypter);
1797 if (level == ENCRYPTION_FORWARD_SECURE) {
1798 has_forward_secure_encrypter_ = true;
1799 first_required_forward_secure_packet_ =
1800 packet_number_of_last_sent_packet_ +
1801 // 3 times the current congestion window (in slow start) should cover
1802 // about two full round trips worth of packets, which should be
1803 // sufficient.
1805 sent_packet_manager_.EstimateMaxPacketsInFlight(
1806 max_packet_length());
1810 void QuicConnection::SetDefaultEncryptionLevel(EncryptionLevel level) {
1811 encryption_level_ = level;
1812 packet_generator_.set_encryption_level(level);
1815 void QuicConnection::SetDecrypter(EncryptionLevel level,
1816 QuicDecrypter* decrypter) {
1817 framer_.SetDecrypter(level, decrypter);
1820 void QuicConnection::SetAlternativeDecrypter(EncryptionLevel level,
1821 QuicDecrypter* decrypter,
1822 bool latch_once_used) {
1823 framer_.SetAlternativeDecrypter(level, decrypter, latch_once_used);
1826 const QuicDecrypter* QuicConnection::decrypter() const {
1827 return framer_.decrypter();
1830 const QuicDecrypter* QuicConnection::alternative_decrypter() const {
1831 return framer_.alternative_decrypter();
1834 void QuicConnection::QueueUndecryptablePacket(
1835 const QuicEncryptedPacket& packet) {
1836 DVLOG(1) << ENDPOINT << "Queueing undecryptable packet.";
1837 undecryptable_packets_.push_back(packet.Clone());
1840 void QuicConnection::MaybeProcessUndecryptablePackets() {
1841 if (undecryptable_packets_.empty() || encryption_level_ == ENCRYPTION_NONE) {
1842 return;
1845 while (connected_ && !undecryptable_packets_.empty()) {
1846 DVLOG(1) << ENDPOINT << "Attempting to process undecryptable packet";
1847 QuicEncryptedPacket* packet = undecryptable_packets_.front();
1848 if (!framer_.ProcessPacket(*packet) &&
1849 framer_.error() == QUIC_DECRYPTION_FAILURE) {
1850 DVLOG(1) << ENDPOINT << "Unable to process undecryptable packet...";
1851 break;
1853 DVLOG(1) << ENDPOINT << "Processed undecryptable packet!";
1854 ++stats_.packets_processed;
1855 delete packet;
1856 undecryptable_packets_.pop_front();
1859 // Once forward secure encryption is in use, there will be no
1860 // new keys installed and hence any undecryptable packets will
1861 // never be able to be decrypted.
1862 if (encryption_level_ == ENCRYPTION_FORWARD_SECURE) {
1863 if (debug_visitor_ != nullptr) {
1864 // TODO(rtenneti): perhaps more efficient to pass the number of
1865 // undecryptable packets as the argument to OnUndecryptablePacket so that
1866 // we just need to call OnUndecryptablePacket once?
1867 for (size_t i = 0; i < undecryptable_packets_.size(); ++i) {
1868 debug_visitor_->OnUndecryptablePacket();
1871 STLDeleteElements(&undecryptable_packets_);
1875 void QuicConnection::MaybeProcessRevivedPacket() {
1876 QuicFecGroup* group = GetFecGroup();
1877 if (!connected_ || group == nullptr || !group->CanRevive()) {
1878 return;
1880 QuicPacketHeader revived_header;
1881 char revived_payload[kMaxPacketSize];
1882 size_t len = group->Revive(&revived_header, revived_payload, kMaxPacketSize);
1883 revived_header.public_header.connection_id = connection_id_;
1884 revived_header.public_header.connection_id_length =
1885 last_header_.public_header.connection_id_length;
1886 revived_header.public_header.version_flag = false;
1887 revived_header.public_header.reset_flag = false;
1888 revived_header.public_header.packet_number_length =
1889 last_header_.public_header.packet_number_length;
1890 revived_header.fec_flag = false;
1891 revived_header.is_in_fec_group = NOT_IN_FEC_GROUP;
1892 revived_header.fec_group = 0;
1893 group_map_.erase(last_header_.fec_group);
1894 last_decrypted_packet_level_ = group->effective_encryption_level();
1895 DCHECK_LT(last_decrypted_packet_level_, NUM_ENCRYPTION_LEVELS);
1896 delete group;
1898 last_packet_revived_ = true;
1899 if (debug_visitor_ != nullptr) {
1900 debug_visitor_->OnRevivedPacket(revived_header,
1901 StringPiece(revived_payload, len));
1904 ++stats_.packets_revived;
1905 framer_.ProcessRevivedPacket(&revived_header,
1906 StringPiece(revived_payload, len));
1909 QuicFecGroup* QuicConnection::GetFecGroup() {
1910 QuicFecGroupNumber fec_group_num = last_header_.fec_group;
1911 if (fec_group_num == 0) {
1912 return nullptr;
1914 if (!ContainsKey(group_map_, fec_group_num)) {
1915 if (group_map_.size() >= kMaxFecGroups) { // Too many groups
1916 if (fec_group_num < group_map_.begin()->first) {
1917 // The group being requested is a group we've seen before and deleted.
1918 // Don't recreate it.
1919 return nullptr;
1921 // Clear the lowest group number.
1922 delete group_map_.begin()->second;
1923 group_map_.erase(group_map_.begin());
1925 group_map_[fec_group_num] = new QuicFecGroup();
1927 return group_map_[fec_group_num];
1930 void QuicConnection::SendConnectionClose(QuicErrorCode error) {
1931 SendConnectionCloseWithDetails(error, string());
1934 void QuicConnection::SendConnectionCloseWithDetails(QuicErrorCode error,
1935 const string& details) {
1936 // If we're write blocked, WritePacket() will not send, but will capture the
1937 // serialized packet.
1938 SendConnectionClosePacket(error, details);
1939 CloseConnection(error, false);
1942 void QuicConnection::SendConnectionClosePacket(QuicErrorCode error,
1943 const string& details) {
1944 DVLOG(1) << ENDPOINT << "Force closing " << connection_id()
1945 << " with error " << QuicUtils::ErrorToString(error)
1946 << " (" << error << ") " << details;
1947 // Don't send explicit connection close packets for timeouts.
1948 // This is particularly important on mobile, where connections are short.
1949 if (silent_close_enabled_ &&
1950 error == QuicErrorCode::QUIC_CONNECTION_TIMED_OUT) {
1951 return;
1953 ClearQueuedPackets();
1954 ScopedPacketBundler ack_bundler(this, SEND_ACK);
1955 QuicConnectionCloseFrame* frame = new QuicConnectionCloseFrame();
1956 frame->error_code = error;
1957 frame->error_details = details;
1958 packet_generator_.AddControlFrame(QuicFrame(frame));
1959 packet_generator_.FlushAllQueuedFrames();
1962 void QuicConnection::CloseConnection(QuicErrorCode error, bool from_peer) {
1963 if (!connected_) {
1964 DVLOG(1) << "Connection is already closed.";
1965 return;
1967 connected_ = false;
1968 if (debug_visitor_ != nullptr) {
1969 debug_visitor_->OnConnectionClosed(error, from_peer);
1971 DCHECK(visitor_ != nullptr);
1972 visitor_->OnConnectionClosed(error, from_peer);
1973 // Cancel the alarms so they don't trigger any action now that the
1974 // connection is closed.
1975 ack_alarm_->Cancel();
1976 ping_alarm_->Cancel();
1977 fec_alarm_->Cancel();
1978 resume_writes_alarm_->Cancel();
1979 retransmission_alarm_->Cancel();
1980 send_alarm_->Cancel();
1981 timeout_alarm_->Cancel();
1982 mtu_discovery_alarm_->Cancel();
1985 void QuicConnection::SendGoAway(QuicErrorCode error,
1986 QuicStreamId last_good_stream_id,
1987 const string& reason) {
1988 if (goaway_sent_) {
1989 return;
1991 goaway_sent_ = true;
1993 DVLOG(1) << ENDPOINT << "Going away with error "
1994 << QuicUtils::ErrorToString(error)
1995 << " (" << error << ")";
1997 // Opportunistically bundle an ack with this outgoing packet.
1998 ScopedPacketBundler ack_bundler(this, BUNDLE_PENDING_ACK);
1999 packet_generator_.AddControlFrame(
2000 QuicFrame(new QuicGoAwayFrame(error, last_good_stream_id, reason)));
2003 void QuicConnection::CloseFecGroupsBefore(QuicPacketNumber packet_number) {
2004 FecGroupMap::iterator it = group_map_.begin();
2005 while (it != group_map_.end()) {
2006 // If this is the current group or the group doesn't protect this packet
2007 // we can ignore it.
2008 if (last_header_.fec_group == it->first ||
2009 !it->second->ProtectsPacketsBefore(packet_number)) {
2010 ++it;
2011 continue;
2013 QuicFecGroup* fec_group = it->second;
2014 DCHECK(!fec_group->CanRevive());
2015 FecGroupMap::iterator next = it;
2016 ++next;
2017 group_map_.erase(it);
2018 delete fec_group;
2019 it = next;
2023 QuicByteCount QuicConnection::max_packet_length() const {
2024 return packet_generator_.GetMaxPacketLength();
2027 void QuicConnection::SetMaxPacketLength(QuicByteCount length) {
2028 return packet_generator_.SetMaxPacketLength(LimitMaxPacketSize(length),
2029 /*force=*/false);
2032 bool QuicConnection::HasQueuedData() const {
2033 return pending_version_negotiation_packet_ ||
2034 !queued_packets_.empty() || packet_generator_.HasQueuedFrames();
2037 bool QuicConnection::CanWriteStreamData() {
2038 // Don't write stream data if there are negotiation or queued data packets
2039 // to send. Otherwise, continue and bundle as many frames as possible.
2040 if (pending_version_negotiation_packet_ || !queued_packets_.empty()) {
2041 return false;
2044 IsHandshake pending_handshake = visitor_->HasPendingHandshake() ?
2045 IS_HANDSHAKE : NOT_HANDSHAKE;
2046 // Sending queued packets may have caused the socket to become write blocked,
2047 // or the congestion manager to prohibit sending. If we've sent everything
2048 // we had queued and we're still not blocked, let the visitor know it can
2049 // write more.
2050 return ShouldGeneratePacket(HAS_RETRANSMITTABLE_DATA, pending_handshake);
2053 void QuicConnection::SetNetworkTimeouts(QuicTime::Delta overall_timeout,
2054 QuicTime::Delta idle_timeout) {
2055 LOG_IF(DFATAL, idle_timeout > overall_timeout)
2056 << "idle_timeout:" << idle_timeout.ToMilliseconds()
2057 << " overall_timeout:" << overall_timeout.ToMilliseconds();
2058 // Adjust the idle timeout on client and server to prevent clients from
2059 // sending requests to servers which have already closed the connection.
2060 if (perspective_ == Perspective::IS_SERVER) {
2061 idle_timeout = idle_timeout.Add(QuicTime::Delta::FromSeconds(3));
2062 } else if (idle_timeout > QuicTime::Delta::FromSeconds(1)) {
2063 idle_timeout = idle_timeout.Subtract(QuicTime::Delta::FromSeconds(1));
2065 overall_connection_timeout_ = overall_timeout;
2066 idle_network_timeout_ = idle_timeout;
2068 SetTimeoutAlarm();
2071 void QuicConnection::CheckForTimeout() {
2072 QuicTime now = clock_->ApproximateNow();
2073 QuicTime time_of_last_packet = max(time_of_last_received_packet_,
2074 time_of_last_sent_new_packet_);
2076 // |delta| can be < 0 as |now| is approximate time but |time_of_last_packet|
2077 // is accurate time. However, this should not change the behavior of
2078 // timeout handling.
2079 QuicTime::Delta idle_duration = now.Subtract(time_of_last_packet);
2080 DVLOG(1) << ENDPOINT << "last packet "
2081 << time_of_last_packet.ToDebuggingValue()
2082 << " now:" << now.ToDebuggingValue()
2083 << " idle_duration:" << idle_duration.ToMicroseconds()
2084 << " idle_network_timeout: "
2085 << idle_network_timeout_.ToMicroseconds();
2086 if (idle_duration >= idle_network_timeout_) {
2087 DVLOG(1) << ENDPOINT << "Connection timedout due to no network activity.";
2088 SendConnectionClose(QUIC_CONNECTION_TIMED_OUT);
2089 return;
2092 if (!overall_connection_timeout_.IsInfinite()) {
2093 QuicTime::Delta connected_duration =
2094 now.Subtract(stats_.connection_creation_time);
2095 DVLOG(1) << ENDPOINT << "connection time: "
2096 << connected_duration.ToMicroseconds() << " overall timeout: "
2097 << overall_connection_timeout_.ToMicroseconds();
2098 if (connected_duration >= overall_connection_timeout_) {
2099 DVLOG(1) << ENDPOINT <<
2100 "Connection timedout due to overall connection timeout.";
2101 SendConnectionClose(QUIC_CONNECTION_OVERALL_TIMED_OUT);
2102 return;
2106 SetTimeoutAlarm();
2109 void QuicConnection::SetTimeoutAlarm() {
2110 QuicTime time_of_last_packet = max(time_of_last_received_packet_,
2111 time_of_last_sent_new_packet_);
2113 QuicTime deadline = time_of_last_packet.Add(idle_network_timeout_);
2114 if (!overall_connection_timeout_.IsInfinite()) {
2115 deadline = min(deadline,
2116 stats_.connection_creation_time.Add(
2117 overall_connection_timeout_));
2120 timeout_alarm_->Cancel();
2121 timeout_alarm_->Set(deadline);
2124 void QuicConnection::SetPingAlarm() {
2125 if (perspective_ == Perspective::IS_SERVER) {
2126 // Only clients send pings.
2127 return;
2129 if (!visitor_->HasOpenDynamicStreams()) {
2130 ping_alarm_->Cancel();
2131 // Don't send a ping unless there are open streams.
2132 return;
2134 QuicTime::Delta ping_timeout = QuicTime::Delta::FromSeconds(kPingTimeoutSecs);
2135 ping_alarm_->Update(clock_->ApproximateNow().Add(ping_timeout),
2136 QuicTime::Delta::FromSeconds(1));
2139 void QuicConnection::SetRetransmissionAlarm() {
2140 if (delay_setting_retransmission_alarm_) {
2141 pending_retransmission_alarm_ = true;
2142 return;
2144 QuicTime retransmission_time = sent_packet_manager_.GetRetransmissionTime();
2145 retransmission_alarm_->Update(retransmission_time,
2146 QuicTime::Delta::FromMilliseconds(1));
2149 void QuicConnection::MaybeSetMtuAlarm() {
2150 // Do not set the alarm if the target size is less than the current size.
2151 // This covers the case when |mtu_discovery_target_| is at its default value,
2152 // zero.
2153 if (mtu_discovery_target_ <= max_packet_length()) {
2154 return;
2157 if (mtu_probe_count_ >= kMtuDiscoveryAttempts) {
2158 return;
2161 if (mtu_discovery_alarm_->IsSet()) {
2162 return;
2165 if (packet_number_of_last_sent_packet_ >= next_mtu_probe_at_) {
2166 // Use an alarm to send the MTU probe to ensure that no ScopedPacketBundlers
2167 // are active.
2168 mtu_discovery_alarm_->Set(clock_->ApproximateNow());
2172 QuicConnection::ScopedPacketBundler::ScopedPacketBundler(
2173 QuicConnection* connection,
2174 AckBundling send_ack)
2175 : connection_(connection),
2176 already_in_batch_mode_(connection != nullptr &&
2177 connection->packet_generator_.InBatchMode()) {
2178 if (connection_ == nullptr) {
2179 return;
2181 // Move generator into batch mode. If caller wants us to include an ack,
2182 // check the delayed-ack timer to see if there's ack info to be sent.
2183 if (!already_in_batch_mode_) {
2184 DVLOG(1) << "Entering Batch Mode.";
2185 connection_->packet_generator_.StartBatchOperations();
2187 // Bundle an ack if the alarm is set or with every second packet if we need to
2188 // raise the peer's least unacked.
2189 bool ack_pending =
2190 connection_->ack_alarm_->IsSet() || connection_->stop_waiting_count_ > 1;
2191 if (send_ack == SEND_ACK || (send_ack == BUNDLE_PENDING_ACK && ack_pending)) {
2192 DVLOG(1) << "Bundling ack with outgoing packet.";
2193 connection_->SendAck();
2197 QuicConnection::ScopedPacketBundler::~ScopedPacketBundler() {
2198 if (connection_ == nullptr) {
2199 return;
2201 // If we changed the generator's batch state, restore original batch state.
2202 if (!already_in_batch_mode_) {
2203 DVLOG(1) << "Leaving Batch Mode.";
2204 connection_->packet_generator_.FinishBatchOperations();
2206 DCHECK_EQ(already_in_batch_mode_,
2207 connection_->packet_generator_.InBatchMode());
2210 QuicConnection::ScopedRetransmissionScheduler::ScopedRetransmissionScheduler(
2211 QuicConnection* connection)
2212 : connection_(connection),
2213 already_delayed_(connection_->delay_setting_retransmission_alarm_) {
2214 connection_->delay_setting_retransmission_alarm_ = true;
2217 QuicConnection::ScopedRetransmissionScheduler::
2218 ~ScopedRetransmissionScheduler() {
2219 if (already_delayed_) {
2220 return;
2222 connection_->delay_setting_retransmission_alarm_ = false;
2223 if (connection_->pending_retransmission_alarm_) {
2224 connection_->SetRetransmissionAlarm();
2225 connection_->pending_retransmission_alarm_ = false;
2229 HasRetransmittableData QuicConnection::IsRetransmittable(
2230 const QueuedPacket& packet) {
2231 // Retransmitted packets retransmittable frames are owned by the unacked
2232 // packet map, but are not present in the serialized packet.
2233 if (packet.transmission_type != NOT_RETRANSMISSION ||
2234 packet.serialized_packet.retransmittable_frames != nullptr) {
2235 return HAS_RETRANSMITTABLE_DATA;
2236 } else {
2237 return NO_RETRANSMITTABLE_DATA;
2241 bool QuicConnection::IsConnectionClose(const QueuedPacket& packet) {
2242 const RetransmittableFrames* retransmittable_frames =
2243 packet.serialized_packet.retransmittable_frames;
2244 if (retransmittable_frames == nullptr) {
2245 return false;
2247 for (const QuicFrame& frame : retransmittable_frames->frames()) {
2248 if (frame.type == CONNECTION_CLOSE_FRAME) {
2249 return true;
2252 return false;
2255 void QuicConnection::SetMtuDiscoveryTarget(QuicByteCount target) {
2256 mtu_discovery_target_ = LimitMaxPacketSize(target);
2259 QuicByteCount QuicConnection::LimitMaxPacketSize(
2260 QuicByteCount suggested_max_packet_size) {
2261 if (FLAGS_quic_allow_oversized_packets_for_test) {
2262 return suggested_max_packet_size;
2265 if (!FLAGS_quic_limit_mtu_by_writer) {
2266 return suggested_max_packet_size;
2269 if (peer_address_.address().empty()) {
2270 LOG(DFATAL) << "Attempted to use a connection without a valid peer address";
2271 return suggested_max_packet_size;
2274 const QuicByteCount writer_limit = writer_->GetMaxPacketSize(peer_address());
2276 QuicByteCount max_packet_size = suggested_max_packet_size;
2277 if (max_packet_size > writer_limit) {
2278 max_packet_size = writer_limit;
2280 if (max_packet_size > kMaxPacketSize) {
2281 max_packet_size = kMaxPacketSize;
2283 return max_packet_size;
2286 void QuicConnection::SendMtuDiscoveryPacket(QuicByteCount target_mtu) {
2287 // Currently, this limit is ensured by the caller.
2288 DCHECK_EQ(target_mtu, LimitMaxPacketSize(target_mtu));
2290 // Create a listener for the new probe. The ownership of the listener is
2291 // transferred to the AckNotifierManager. The notifier will get destroyed
2292 // before the connection (because it's stored in one of the connection's
2293 // subfields), hence |this| pointer is guaranteed to stay valid at all times.
2294 scoped_refptr<MtuDiscoveryAckListener> last_mtu_discovery_ack_listener(
2295 new MtuDiscoveryAckListener(this, target_mtu));
2297 // Send the probe.
2298 packet_generator_.GenerateMtuDiscoveryPacket(
2299 target_mtu, last_mtu_discovery_ack_listener.get());
2302 void QuicConnection::DiscoverMtu() {
2303 DCHECK(!mtu_discovery_alarm_->IsSet());
2305 // Chcek if the MTU has been already increased.
2306 if (mtu_discovery_target_ <= max_packet_length()) {
2307 return;
2310 // Schedule the next probe *before* sending the current one. This is
2311 // important, otherwise, when SendMtuDiscoveryPacket() is called,
2312 // MaybeSetMtuAlarm() will not realize that the probe has been just sent, and
2313 // will reschedule this probe again.
2314 packets_between_mtu_probes_ *= 2;
2315 next_mtu_probe_at_ =
2316 packet_number_of_last_sent_packet_ + packets_between_mtu_probes_ + 1;
2317 ++mtu_probe_count_;
2319 DVLOG(2) << "Sending a path MTU discovery packet #" << mtu_probe_count_;
2320 SendMtuDiscoveryPacket(mtu_discovery_target_);
2322 DCHECK(!mtu_discovery_alarm_->IsSet());
2325 } // namespace net