Updating XTBs based on .GRDs from branch master
[chromium-blink-merge.git] / net / quic / quic_connection.cc
blob4f09086727aa543ce876ab959a84ed90b05d8c02
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 QuicPacketSequenceNumber 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(QuicPacketSequenceNumber a, QuicPacketSequenceNumber b) {
67 QuicPacketSequenceNumber 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_->set_max_packet_length(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_sequence_number(0) {
235 QuicConnection::QueuedPacket::QueuedPacket(
236 SerializedPacket packet,
237 EncryptionLevel level,
238 TransmissionType transmission_type,
239 QuicPacketSequenceNumber original_sequence_number)
240 : serialized_packet(packet),
241 encryption_level(level),
242 transmission_type(transmission_type),
243 original_sequence_number(original_sequence_number) {
246 #define ENDPOINT \
247 (perspective_ == Perspective::IS_SERVER ? "Server: " : "Client: ")
249 QuicConnection::QuicConnection(QuicConnectionId connection_id,
250 IPEndPoint address,
251 QuicConnectionHelperInterface* helper,
252 const PacketWriterFactory& writer_factory,
253 bool owns_writer,
254 Perspective perspective,
255 bool is_secure,
256 const QuicVersionVector& supported_versions)
257 : framer_(supported_versions,
258 helper->GetClock()->ApproximateNow(),
259 perspective),
260 helper_(helper),
261 writer_(writer_factory.Create(this)),
262 owns_writer_(owns_writer),
263 encryption_level_(ENCRYPTION_NONE),
264 has_forward_secure_encrypter_(false),
265 first_required_forward_secure_packet_(0),
266 clock_(helper->GetClock()),
267 random_generator_(helper->GetRandomGenerator()),
268 connection_id_(connection_id),
269 peer_address_(address),
270 migrating_peer_port_(0),
271 last_packet_decrypted_(false),
272 last_packet_revived_(false),
273 last_size_(0),
274 last_decrypted_packet_level_(ENCRYPTION_NONE),
275 should_last_packet_instigate_acks_(false),
276 largest_seen_packet_with_ack_(0),
277 largest_seen_packet_with_stop_waiting_(0),
278 max_undecryptable_packets_(0),
279 pending_version_negotiation_packet_(false),
280 silent_close_enabled_(false),
281 received_packet_manager_(&stats_),
282 ack_queued_(false),
283 num_packets_received_since_last_ack_sent_(0),
284 stop_waiting_count_(0),
285 delay_setting_retransmission_alarm_(false),
286 pending_retransmission_alarm_(false),
287 ack_alarm_(helper->CreateAlarm(new AckAlarm(this))),
288 retransmission_alarm_(helper->CreateAlarm(new RetransmissionAlarm(this))),
289 send_alarm_(helper->CreateAlarm(new SendAlarm(this))),
290 resume_writes_alarm_(helper->CreateAlarm(new SendAlarm(this))),
291 timeout_alarm_(helper->CreateAlarm(new TimeoutAlarm(this))),
292 ping_alarm_(helper->CreateAlarm(new PingAlarm(this))),
293 mtu_discovery_alarm_(helper->CreateAlarm(new MtuDiscoveryAlarm(this))),
294 visitor_(nullptr),
295 debug_visitor_(nullptr),
296 packet_generator_(connection_id_, &framer_, random_generator_, this),
297 fec_alarm_(helper->CreateAlarm(new FecAlarm(&packet_generator_))),
298 idle_network_timeout_(QuicTime::Delta::Infinite()),
299 overall_connection_timeout_(QuicTime::Delta::Infinite()),
300 time_of_last_received_packet_(clock_->ApproximateNow()),
301 time_of_last_sent_new_packet_(clock_->ApproximateNow()),
302 sequence_number_of_last_sent_packet_(0),
303 sent_packet_manager_(
304 perspective,
305 clock_,
306 &stats_,
307 FLAGS_quic_use_bbr_congestion_control ? kBBR : kCubic,
308 FLAGS_quic_use_time_loss_detection ? kTime : kNack,
309 is_secure),
310 version_negotiation_state_(START_NEGOTIATION),
311 perspective_(perspective),
312 connected_(true),
313 peer_ip_changed_(false),
314 peer_port_changed_(false),
315 self_ip_changed_(false),
316 self_port_changed_(false),
317 can_truncate_connection_ids_(true),
318 is_secure_(is_secure),
319 mtu_discovery_target_(0),
320 mtu_probe_count_(0),
321 packets_between_mtu_probes_(kPacketsBetweenMtuProbesBase),
322 next_mtu_probe_at_(kPacketsBetweenMtuProbesBase),
323 largest_received_packet_size_(0) {
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 stats_.connection_creation_time = clock_->ApproximateNow();
329 sent_packet_manager_.set_network_change_visitor(this);
330 if (perspective_ == Perspective::IS_SERVER) {
331 set_max_packet_length(kDefaultServerMaxPacketSize);
335 QuicConnection::~QuicConnection() {
336 if (owns_writer_) {
337 delete writer_;
339 STLDeleteElements(&undecryptable_packets_);
340 STLDeleteValues(&group_map_);
341 for (QueuedPacketList::iterator it = queued_packets_.begin();
342 it != queued_packets_.end(); ++it) {
343 delete it->serialized_packet.retransmittable_frames;
344 delete it->serialized_packet.packet;
348 void QuicConnection::SetFromConfig(const QuicConfig& config) {
349 if (config.negotiated()) {
350 SetNetworkTimeouts(QuicTime::Delta::Infinite(),
351 config.IdleConnectionStateLifetime());
352 if (config.SilentClose()) {
353 silent_close_enabled_ = true;
355 } else {
356 SetNetworkTimeouts(config.max_time_before_crypto_handshake(),
357 config.max_idle_time_before_crypto_handshake());
360 sent_packet_manager_.SetFromConfig(config);
361 if (config.HasReceivedBytesForConnectionId() &&
362 can_truncate_connection_ids_) {
363 packet_generator_.SetConnectionIdLength(
364 config.ReceivedBytesForConnectionId());
366 max_undecryptable_packets_ = config.max_undecryptable_packets();
368 if (config.HasClientSentConnectionOption(kFSPA, perspective_)) {
369 packet_generator_.set_fec_send_policy(FecSendPolicy::FEC_ALARM_TRIGGER);
372 if (config.HasClientSentConnectionOption(kMTUH, perspective_)) {
373 mtu_discovery_target_ = kMtuDiscoveryTargetPacketSizeHigh;
375 if (config.HasClientSentConnectionOption(kMTUL, perspective_)) {
376 mtu_discovery_target_ = kMtuDiscoveryTargetPacketSizeLow;
380 void QuicConnection::OnSendConnectionState(
381 const CachedNetworkParameters& cached_network_params) {
382 if (debug_visitor_ != nullptr) {
383 debug_visitor_->OnSendConnectionState(cached_network_params);
387 void QuicConnection::ResumeConnectionState(
388 const CachedNetworkParameters& cached_network_params,
389 bool max_bandwidth_resumption) {
390 if (debug_visitor_ != nullptr) {
391 debug_visitor_->OnResumeConnectionState(cached_network_params);
393 sent_packet_manager_.ResumeConnectionState(cached_network_params,
394 max_bandwidth_resumption);
397 void QuicConnection::SetNumOpenStreams(size_t num_streams) {
398 sent_packet_manager_.SetNumOpenStreams(num_streams);
401 bool QuicConnection::SelectMutualVersion(
402 const QuicVersionVector& available_versions) {
403 // Try to find the highest mutual version by iterating over supported
404 // versions, starting with the highest, and breaking out of the loop once we
405 // find a matching version in the provided available_versions vector.
406 const QuicVersionVector& supported_versions = framer_.supported_versions();
407 for (size_t i = 0; i < supported_versions.size(); ++i) {
408 const QuicVersion& version = supported_versions[i];
409 if (std::find(available_versions.begin(), available_versions.end(),
410 version) != available_versions.end()) {
411 framer_.set_version(version);
412 return true;
416 return false;
419 void QuicConnection::OnError(QuicFramer* framer) {
420 // Packets that we can not or have not decrypted are dropped.
421 // TODO(rch): add stats to measure this.
422 if (!connected_ || last_packet_decrypted_ == false) {
423 return;
425 SendConnectionCloseWithDetails(framer->error(), framer->detailed_error());
428 void QuicConnection::MaybeSetFecAlarm(
429 QuicPacketSequenceNumber sequence_number) {
430 if (fec_alarm_->IsSet()) {
431 return;
433 QuicTime::Delta timeout = packet_generator_.GetFecTimeout(sequence_number);
434 if (!timeout.IsInfinite()) {
435 fec_alarm_->Set(clock_->ApproximateNow().Add(timeout));
439 void QuicConnection::OnPacket() {
440 DCHECK(last_stream_frames_.empty() &&
441 last_ack_frames_.empty() &&
442 last_stop_waiting_frames_.empty() &&
443 last_rst_frames_.empty() &&
444 last_goaway_frames_.empty() &&
445 last_window_update_frames_.empty() &&
446 last_blocked_frames_.empty() &&
447 last_ping_frames_.empty() &&
448 last_close_frames_.empty());
449 last_packet_decrypted_ = false;
450 last_packet_revived_ = false;
453 void QuicConnection::OnPublicResetPacket(const QuicPublicResetPacket& packet) {
454 // Check that any public reset packet with a different connection ID that was
455 // routed to this QuicConnection has been redirected before control reaches
456 // here. (Check for a bug regression.)
457 DCHECK_EQ(connection_id_, packet.public_header.connection_id);
458 if (debug_visitor_ != nullptr) {
459 debug_visitor_->OnPublicResetPacket(packet);
461 CloseConnection(QUIC_PUBLIC_RESET, true);
463 DVLOG(1) << ENDPOINT << "Connection " << connection_id()
464 << " closed via QUIC_PUBLIC_RESET from peer.";
467 bool QuicConnection::OnProtocolVersionMismatch(QuicVersion received_version) {
468 DVLOG(1) << ENDPOINT << "Received packet with mismatched version "
469 << received_version;
470 // TODO(satyamshekhar): Implement no server state in this mode.
471 if (perspective_ == Perspective::IS_CLIENT) {
472 LOG(DFATAL) << ENDPOINT << "Framer called OnProtocolVersionMismatch. "
473 << "Closing connection.";
474 CloseConnection(QUIC_INTERNAL_ERROR, false);
475 return false;
477 DCHECK_NE(version(), received_version);
479 if (debug_visitor_ != nullptr) {
480 debug_visitor_->OnProtocolVersionMismatch(received_version);
483 switch (version_negotiation_state_) {
484 case START_NEGOTIATION:
485 if (!framer_.IsSupportedVersion(received_version)) {
486 SendVersionNegotiationPacket();
487 version_negotiation_state_ = NEGOTIATION_IN_PROGRESS;
488 return false;
490 break;
492 case NEGOTIATION_IN_PROGRESS:
493 if (!framer_.IsSupportedVersion(received_version)) {
494 SendVersionNegotiationPacket();
495 return false;
497 break;
499 case NEGOTIATED_VERSION:
500 // Might be old packets that were sent by the client before the version
501 // was negotiated. Drop these.
502 return false;
504 default:
505 DCHECK(false);
508 version_negotiation_state_ = NEGOTIATED_VERSION;
509 visitor_->OnSuccessfulVersionNegotiation(received_version);
510 if (debug_visitor_ != nullptr) {
511 debug_visitor_->OnSuccessfulVersionNegotiation(received_version);
513 DVLOG(1) << ENDPOINT << "version negotiated " << received_version;
515 // Store the new version.
516 framer_.set_version(received_version);
518 // TODO(satyamshekhar): Store the sequence number of this packet and close the
519 // connection if we ever received a packet with incorrect version and whose
520 // sequence number is greater.
521 return true;
524 // Handles version negotiation for client connection.
525 void QuicConnection::OnVersionNegotiationPacket(
526 const QuicVersionNegotiationPacket& packet) {
527 // Check that any public reset packet with a different connection ID that was
528 // routed to this QuicConnection has been redirected before control reaches
529 // here. (Check for a bug regression.)
530 DCHECK_EQ(connection_id_, packet.connection_id);
531 if (perspective_ == Perspective::IS_SERVER) {
532 LOG(DFATAL) << ENDPOINT << "Framer parsed VersionNegotiationPacket."
533 << " Closing connection.";
534 CloseConnection(QUIC_INTERNAL_ERROR, false);
535 return;
537 if (debug_visitor_ != nullptr) {
538 debug_visitor_->OnVersionNegotiationPacket(packet);
541 if (version_negotiation_state_ != START_NEGOTIATION) {
542 // Possibly a duplicate version negotiation packet.
543 return;
546 if (std::find(packet.versions.begin(),
547 packet.versions.end(), version()) !=
548 packet.versions.end()) {
549 DLOG(WARNING) << ENDPOINT << "The server already supports our version. "
550 << "It should have accepted our connection.";
551 // Just drop the connection.
552 CloseConnection(QUIC_INVALID_VERSION_NEGOTIATION_PACKET, false);
553 return;
556 if (!SelectMutualVersion(packet.versions)) {
557 SendConnectionCloseWithDetails(QUIC_INVALID_VERSION,
558 "no common version found");
559 return;
562 DVLOG(1) << ENDPOINT
563 << "Negotiated version: " << QuicVersionToString(version());
564 server_supported_versions_ = packet.versions;
565 version_negotiation_state_ = NEGOTIATION_IN_PROGRESS;
566 RetransmitUnackedPackets(ALL_UNACKED_RETRANSMISSION);
569 void QuicConnection::OnRevivedPacket() {
572 bool QuicConnection::OnUnauthenticatedPublicHeader(
573 const QuicPacketPublicHeader& header) {
574 if (header.connection_id == connection_id_) {
575 return true;
578 ++stats_.packets_dropped;
579 DVLOG(1) << ENDPOINT << "Ignoring packet from unexpected ConnectionId: "
580 << header.connection_id << " instead of " << connection_id_;
581 if (debug_visitor_ != nullptr) {
582 debug_visitor_->OnIncorrectConnectionId(header.connection_id);
584 // If this is a server, the dispatcher routes each packet to the
585 // QuicConnection responsible for the packet's connection ID. So if control
586 // arrives here and this is a server, the dispatcher must be malfunctioning.
587 DCHECK_NE(Perspective::IS_SERVER, perspective_);
588 return false;
591 bool QuicConnection::OnUnauthenticatedHeader(const QuicPacketHeader& header) {
592 // Check that any public reset packet with a different connection ID that was
593 // routed to this QuicConnection has been redirected before control reaches
594 // here.
595 DCHECK_EQ(connection_id_, header.public_header.connection_id);
596 return true;
599 void QuicConnection::OnDecryptedPacket(EncryptionLevel level) {
600 last_decrypted_packet_level_ = level;
601 last_packet_decrypted_ = true;
602 // If this packet was foward-secure encrypted and the forward-secure encrypter
603 // is not being used, start using it.
604 if (encryption_level_ != ENCRYPTION_FORWARD_SECURE &&
605 has_forward_secure_encrypter_ && level == ENCRYPTION_FORWARD_SECURE) {
606 SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
610 bool QuicConnection::OnPacketHeader(const QuicPacketHeader& header) {
611 if (debug_visitor_ != nullptr) {
612 debug_visitor_->OnPacketHeader(header);
615 if (!ProcessValidatedPacket()) {
616 return false;
619 // Will be decremented below if we fall through to return true.
620 ++stats_.packets_dropped;
622 if (!Near(header.packet_sequence_number,
623 last_header_.packet_sequence_number)) {
624 DVLOG(1) << ENDPOINT << "Packet " << header.packet_sequence_number
625 << " out of bounds. Discarding";
626 SendConnectionCloseWithDetails(QUIC_INVALID_PACKET_HEADER,
627 "Packet sequence number out of bounds");
628 return false;
631 // If this packet has already been seen, or the sender has told us that it
632 // will not be retransmitted, then stop processing the packet.
633 if (!received_packet_manager_.IsAwaitingPacket(
634 header.packet_sequence_number)) {
635 DVLOG(1) << ENDPOINT << "Packet " << header.packet_sequence_number
636 << " no longer being waited for. Discarding.";
637 if (debug_visitor_ != nullptr) {
638 debug_visitor_->OnDuplicatePacket(header.packet_sequence_number);
640 return false;
643 if (version_negotiation_state_ != NEGOTIATED_VERSION) {
644 if (perspective_ == Perspective::IS_SERVER) {
645 if (!header.public_header.version_flag) {
646 DLOG(WARNING) << ENDPOINT << "Packet " << header.packet_sequence_number
647 << " without version flag before version negotiated.";
648 // Packets should have the version flag till version negotiation is
649 // done.
650 CloseConnection(QUIC_INVALID_VERSION, false);
651 return false;
652 } else {
653 DCHECK_EQ(1u, header.public_header.versions.size());
654 DCHECK_EQ(header.public_header.versions[0], version());
655 version_negotiation_state_ = NEGOTIATED_VERSION;
656 visitor_->OnSuccessfulVersionNegotiation(version());
657 if (debug_visitor_ != nullptr) {
658 debug_visitor_->OnSuccessfulVersionNegotiation(version());
661 } else {
662 DCHECK(!header.public_header.version_flag);
663 // If the client gets a packet without the version flag from the server
664 // it should stop sending version since the version negotiation is done.
665 packet_generator_.StopSendingVersion();
666 version_negotiation_state_ = NEGOTIATED_VERSION;
667 visitor_->OnSuccessfulVersionNegotiation(version());
668 if (debug_visitor_ != nullptr) {
669 debug_visitor_->OnSuccessfulVersionNegotiation(version());
674 DCHECK_EQ(NEGOTIATED_VERSION, version_negotiation_state_);
676 --stats_.packets_dropped;
677 DVLOG(1) << ENDPOINT << "Received packet header: " << header;
678 last_header_ = header;
679 DCHECK(connected_);
680 return true;
683 void QuicConnection::OnFecProtectedPayload(StringPiece payload) {
684 DCHECK_EQ(IN_FEC_GROUP, last_header_.is_in_fec_group);
685 DCHECK_NE(0u, last_header_.fec_group);
686 QuicFecGroup* group = GetFecGroup();
687 if (group != nullptr) {
688 group->Update(last_decrypted_packet_level_, last_header_, payload);
692 bool QuicConnection::OnStreamFrame(const QuicStreamFrame& frame) {
693 DCHECK(connected_);
694 if (debug_visitor_ != nullptr) {
695 debug_visitor_->OnStreamFrame(frame);
697 if (frame.stream_id != kCryptoStreamId &&
698 last_decrypted_packet_level_ == ENCRYPTION_NONE) {
699 DLOG(WARNING) << ENDPOINT
700 << "Received an unencrypted data frame: closing connection";
701 SendConnectionClose(QUIC_UNENCRYPTED_STREAM_DATA);
702 return false;
704 if (FLAGS_quic_process_frames_inline) {
705 visitor_->OnStreamFrame(frame);
706 stats_.stream_bytes_received += frame.data.size();
707 should_last_packet_instigate_acks_ = true;
708 } else {
709 last_stream_frames_.push_back(frame);
711 return connected_;
714 bool QuicConnection::OnAckFrame(const QuicAckFrame& incoming_ack) {
715 DCHECK(connected_);
716 if (debug_visitor_ != nullptr) {
717 debug_visitor_->OnAckFrame(incoming_ack);
719 DVLOG(1) << ENDPOINT << "OnAckFrame: " << incoming_ack;
721 if (last_header_.packet_sequence_number <= largest_seen_packet_with_ack_) {
722 DVLOG(1) << ENDPOINT << "Received an old ack frame: ignoring";
723 return true;
726 if (!ValidateAckFrame(incoming_ack)) {
727 SendConnectionClose(QUIC_INVALID_ACK_DATA);
728 return false;
731 if (FLAGS_quic_process_frames_inline) {
732 ProcessAckFrame(incoming_ack);
733 if (incoming_ack.is_truncated) {
734 should_last_packet_instigate_acks_ = true;
736 if (!incoming_ack.missing_packets.empty() &&
737 GetLeastUnacked() > *incoming_ack.missing_packets.begin()) {
738 ++stop_waiting_count_;
739 } else {
740 stop_waiting_count_ = 0;
742 } else {
743 last_ack_frames_.push_back(incoming_ack);
745 return connected_;
748 void QuicConnection::ProcessAckFrame(const QuicAckFrame& incoming_ack) {
749 largest_seen_packet_with_ack_ = last_header_.packet_sequence_number;
750 sent_packet_manager_.OnIncomingAck(incoming_ack,
751 time_of_last_received_packet_);
752 sent_entropy_manager_.ClearEntropyBefore(
753 sent_packet_manager_.least_packet_awaited_by_peer() - 1);
755 // Always reset the retransmission alarm when an ack comes in, since we now
756 // have a better estimate of the current rtt than when it was set.
757 SetRetransmissionAlarm();
760 void QuicConnection::ProcessStopWaitingFrame(
761 const QuicStopWaitingFrame& stop_waiting) {
762 largest_seen_packet_with_stop_waiting_ = last_header_.packet_sequence_number;
763 received_packet_manager_.UpdatePacketInformationSentByPeer(stop_waiting);
764 // Possibly close any FecGroups which are now irrelevant.
765 CloseFecGroupsBefore(stop_waiting.least_unacked + 1);
768 bool QuicConnection::OnStopWaitingFrame(const QuicStopWaitingFrame& frame) {
769 DCHECK(connected_);
771 if (last_header_.packet_sequence_number <=
772 largest_seen_packet_with_stop_waiting_) {
773 DVLOG(1) << ENDPOINT << "Received an old stop waiting frame: ignoring";
774 return true;
777 if (!ValidateStopWaitingFrame(frame)) {
778 SendConnectionClose(QUIC_INVALID_STOP_WAITING_DATA);
779 return false;
782 if (debug_visitor_ != nullptr) {
783 debug_visitor_->OnStopWaitingFrame(frame);
786 last_stop_waiting_frames_.push_back(frame);
787 return connected_;
790 bool QuicConnection::OnPingFrame(const QuicPingFrame& frame) {
791 DCHECK(connected_);
792 if (debug_visitor_ != nullptr) {
793 debug_visitor_->OnPingFrame(frame);
795 if (FLAGS_quic_process_frames_inline) {
796 should_last_packet_instigate_acks_ = true;
797 } else {
798 last_ping_frames_.push_back(frame);
800 return true;
803 bool QuicConnection::ValidateAckFrame(const QuicAckFrame& incoming_ack) {
804 if (incoming_ack.largest_observed > packet_generator_.sequence_number()) {
805 DLOG(ERROR) << ENDPOINT << "Peer's observed unsent packet:"
806 << incoming_ack.largest_observed << " vs "
807 << packet_generator_.sequence_number();
808 // We got an error for data we have not sent. Error out.
809 return false;
812 if (incoming_ack.largest_observed < sent_packet_manager_.largest_observed()) {
813 DLOG(ERROR) << ENDPOINT << "Peer's largest_observed packet decreased:"
814 << incoming_ack.largest_observed << " vs "
815 << sent_packet_manager_.largest_observed();
816 // A new ack has a diminished largest_observed value. Error out.
817 // If this was an old packet, we wouldn't even have checked.
818 return false;
821 if (!incoming_ack.missing_packets.empty() &&
822 *incoming_ack.missing_packets.rbegin() > incoming_ack.largest_observed) {
823 DLOG(ERROR) << ENDPOINT << "Peer sent missing packet: "
824 << *incoming_ack.missing_packets.rbegin()
825 << " which is greater than largest observed: "
826 << incoming_ack.largest_observed;
827 return false;
830 if (!incoming_ack.missing_packets.empty() &&
831 *incoming_ack.missing_packets.begin() <
832 sent_packet_manager_.least_packet_awaited_by_peer()) {
833 DLOG(ERROR) << ENDPOINT << "Peer sent missing packet: "
834 << *incoming_ack.missing_packets.begin()
835 << " which is smaller than least_packet_awaited_by_peer_: "
836 << sent_packet_manager_.least_packet_awaited_by_peer();
837 return false;
840 if (!sent_entropy_manager_.IsValidEntropy(
841 incoming_ack.largest_observed,
842 incoming_ack.missing_packets,
843 incoming_ack.entropy_hash)) {
844 DLOG(ERROR) << ENDPOINT << "Peer sent invalid entropy.";
845 return false;
848 for (QuicPacketSequenceNumber revived_packet : incoming_ack.revived_packets) {
849 if (!ContainsKey(incoming_ack.missing_packets, revived_packet)) {
850 DLOG(ERROR) << ENDPOINT
851 << "Peer specified revived packet which was not missing.";
852 return false;
855 return true;
858 bool QuicConnection::ValidateStopWaitingFrame(
859 const QuicStopWaitingFrame& stop_waiting) {
860 if (stop_waiting.least_unacked <
861 received_packet_manager_.peer_least_packet_awaiting_ack()) {
862 DLOG(ERROR) << ENDPOINT << "Peer's sent low least_unacked: "
863 << stop_waiting.least_unacked << " vs "
864 << received_packet_manager_.peer_least_packet_awaiting_ack();
865 // We never process old ack frames, so this number should only increase.
866 return false;
869 if (stop_waiting.least_unacked >
870 last_header_.packet_sequence_number) {
871 DLOG(ERROR) << ENDPOINT << "Peer sent least_unacked:"
872 << stop_waiting.least_unacked
873 << " greater than the enclosing packet sequence number:"
874 << last_header_.packet_sequence_number;
875 return false;
878 return true;
881 void QuicConnection::OnFecData(const QuicFecData& fec) {
882 DCHECK_EQ(IN_FEC_GROUP, last_header_.is_in_fec_group);
883 DCHECK_NE(0u, last_header_.fec_group);
884 QuicFecGroup* group = GetFecGroup();
885 if (group != nullptr) {
886 group->UpdateFec(last_decrypted_packet_level_,
887 last_header_.packet_sequence_number, fec);
891 bool QuicConnection::OnRstStreamFrame(const QuicRstStreamFrame& frame) {
892 DCHECK(connected_);
893 if (debug_visitor_ != nullptr) {
894 debug_visitor_->OnRstStreamFrame(frame);
896 DVLOG(1) << ENDPOINT << "Stream reset with error "
897 << QuicUtils::StreamErrorToString(frame.error_code);
898 if (FLAGS_quic_process_frames_inline) {
899 visitor_->OnRstStream(frame);
900 should_last_packet_instigate_acks_ = true;
901 } else {
902 last_rst_frames_.push_back(frame);
904 return connected_;
907 bool QuicConnection::OnConnectionCloseFrame(
908 const QuicConnectionCloseFrame& frame) {
909 DCHECK(connected_);
910 if (debug_visitor_ != nullptr) {
911 debug_visitor_->OnConnectionCloseFrame(frame);
913 DVLOG(1) << ENDPOINT << "Connection " << connection_id()
914 << " closed with error "
915 << QuicUtils::ErrorToString(frame.error_code)
916 << " " << frame.error_details;
917 if (FLAGS_quic_process_frames_inline) {
918 CloseConnection(frame.error_code, true);
919 } else {
920 last_close_frames_.push_back(frame);
922 return connected_;
925 bool QuicConnection::OnGoAwayFrame(const QuicGoAwayFrame& frame) {
926 DCHECK(connected_);
927 if (debug_visitor_ != nullptr) {
928 debug_visitor_->OnGoAwayFrame(frame);
930 DVLOG(1) << ENDPOINT << "Go away received with error "
931 << QuicUtils::ErrorToString(frame.error_code)
932 << " and reason:" << frame.reason_phrase;
933 if (FLAGS_quic_process_frames_inline) {
934 visitor_->OnGoAway(frame);
935 should_last_packet_instigate_acks_ = true;
936 } else {
937 last_goaway_frames_.push_back(frame);
939 return connected_;
942 bool QuicConnection::OnWindowUpdateFrame(const QuicWindowUpdateFrame& frame) {
943 DCHECK(connected_);
944 if (debug_visitor_ != nullptr) {
945 debug_visitor_->OnWindowUpdateFrame(frame);
947 DVLOG(1) << ENDPOINT << "WindowUpdate received for stream: "
948 << frame.stream_id << " with byte offset: " << frame.byte_offset;
949 if (FLAGS_quic_process_frames_inline) {
950 visitor_->OnWindowUpdateFrame(frame);
951 should_last_packet_instigate_acks_ = true;
952 } else {
953 last_window_update_frames_.push_back(frame);
955 return connected_;
958 bool QuicConnection::OnBlockedFrame(const QuicBlockedFrame& frame) {
959 DCHECK(connected_);
960 if (debug_visitor_ != nullptr) {
961 debug_visitor_->OnBlockedFrame(frame);
963 DVLOG(1) << ENDPOINT << "Blocked frame received for stream: "
964 << frame.stream_id;
965 if (FLAGS_quic_process_frames_inline) {
966 visitor_->OnBlockedFrame(frame);
967 should_last_packet_instigate_acks_ = true;
968 } else {
969 last_blocked_frames_.push_back(frame);
971 return connected_;
974 void QuicConnection::OnPacketComplete() {
975 // Don't do anything if this packet closed the connection.
976 if (!connected_) {
977 ClearLastFrames();
978 return;
981 DVLOG(1) << ENDPOINT << (last_packet_revived_ ? "Revived" : "Got")
982 << " packet " << last_header_.packet_sequence_number << " with " //
983 << last_stream_frames_.size() << " stream frames, " //
984 << last_ack_frames_.size() << " acks, " //
985 << last_stop_waiting_frames_.size() << " stop_waiting, " //
986 << last_rst_frames_.size() << " rsts, " //
987 << last_goaway_frames_.size() << " goaways, " //
988 << last_window_update_frames_.size() << " window updates, " //
989 << last_blocked_frames_.size() << " blocked, " //
990 << last_ping_frames_.size() << " pings, " //
991 << last_close_frames_.size() << " closes " //
992 << "for " << last_header_.public_header.connection_id;
994 ++num_packets_received_since_last_ack_sent_;
996 // Call MaybeQueueAck() before recording the received packet, since we want
997 // to trigger an ack if the newly received packet was previously missing.
998 MaybeQueueAck();
1000 // Record received or revived packet to populate ack info correctly before
1001 // processing stream frames, since the processing may result in a response
1002 // packet with a bundled ack.
1003 if (last_packet_revived_) {
1004 received_packet_manager_.RecordPacketRevived(
1005 last_header_.packet_sequence_number);
1006 } else {
1007 received_packet_manager_.RecordPacketReceived(
1008 last_size_, last_header_, time_of_last_received_packet_);
1011 if (!FLAGS_quic_process_frames_inline) {
1012 for (const QuicStreamFrame& frame : last_stream_frames_) {
1013 visitor_->OnStreamFrame(frame);
1014 stats_.stream_bytes_received += frame.data.size();
1015 if (!connected_) {
1016 return;
1020 // Process window updates, blocked, stream resets, acks, then stop waiting.
1021 for (const QuicWindowUpdateFrame& frame : last_window_update_frames_) {
1022 visitor_->OnWindowUpdateFrame(frame);
1023 if (!connected_) {
1024 return;
1027 for (const QuicBlockedFrame& frame : last_blocked_frames_) {
1028 visitor_->OnBlockedFrame(frame);
1029 if (!connected_) {
1030 return;
1033 for (const QuicGoAwayFrame& frame : last_goaway_frames_) {
1034 visitor_->OnGoAway(frame);
1035 if (!connected_) {
1036 return;
1039 for (const QuicRstStreamFrame& frame : last_rst_frames_) {
1040 visitor_->OnRstStream(frame);
1041 if (!connected_) {
1042 return;
1045 for (const QuicAckFrame& frame : last_ack_frames_) {
1046 ProcessAckFrame(frame);
1047 if (!connected_) {
1048 return;
1051 if (!last_close_frames_.empty()) {
1052 CloseConnection(last_close_frames_[0].error_code, true);
1053 DCHECK(!connected_);
1054 return;
1057 // Continue to process stop waiting frames later, because the packet needs
1058 // to be considered 'received' before the entropy can be updated.
1059 for (const QuicStopWaitingFrame& frame : last_stop_waiting_frames_) {
1060 ProcessStopWaitingFrame(frame);
1061 if (!connected_) {
1062 return;
1066 // If there are new missing packets to report, send an ack immediately.
1067 if (ShouldLastPacketInstigateAck() &&
1068 received_packet_manager_.HasNewMissingPackets()) {
1069 ack_queued_ = true;
1070 ack_alarm_->Cancel();
1073 UpdateStopWaitingCount();
1074 ClearLastFrames();
1075 MaybeCloseIfTooManyOutstandingPackets();
1078 void QuicConnection::MaybeQueueAck() {
1079 // If the last packet is an ack, don't ack it.
1080 if (!ShouldLastPacketInstigateAck()) {
1081 return;
1083 // If the incoming packet was missing, send an ack immediately.
1084 ack_queued_ = received_packet_manager_.IsMissing(
1085 last_header_.packet_sequence_number);
1087 if (!ack_queued_) {
1088 if (ack_alarm_->IsSet()) {
1089 ack_queued_ = true;
1090 } else {
1091 ack_alarm_->Set(
1092 clock_->ApproximateNow().Add(sent_packet_manager_.DelayedAckTime()));
1093 DVLOG(1) << "Ack timer set; next packet or timer will trigger ACK.";
1097 if (ack_queued_) {
1098 ack_alarm_->Cancel();
1102 void QuicConnection::ClearLastFrames() {
1103 if (FLAGS_quic_process_frames_inline) {
1104 should_last_packet_instigate_acks_ = false;
1105 last_stop_waiting_frames_.clear();
1106 return;
1108 last_stream_frames_.clear();
1109 last_ack_frames_.clear();
1110 last_stop_waiting_frames_.clear();
1111 last_rst_frames_.clear();
1112 last_goaway_frames_.clear();
1113 last_window_update_frames_.clear();
1114 last_blocked_frames_.clear();
1115 last_ping_frames_.clear();
1116 last_close_frames_.clear();
1119 void QuicConnection::MaybeCloseIfTooManyOutstandingPackets() {
1120 // This occurs if we don't discard old packets we've sent fast enough.
1121 // It's possible largest observed is less than least unacked.
1122 if (sent_packet_manager_.largest_observed() >
1123 (sent_packet_manager_.GetLeastUnacked() + kMaxTrackedPackets)) {
1124 SendConnectionCloseWithDetails(
1125 QUIC_TOO_MANY_OUTSTANDING_SENT_PACKETS,
1126 StringPrintf("More than %" PRIu64 " outstanding.", kMaxTrackedPackets));
1128 // This occurs if there are received packet gaps and the peer does not raise
1129 // the least unacked fast enough.
1130 if (received_packet_manager_.NumTrackedPackets() > kMaxTrackedPackets) {
1131 SendConnectionCloseWithDetails(
1132 QUIC_TOO_MANY_OUTSTANDING_RECEIVED_PACKETS,
1133 StringPrintf("More than %" PRIu64 " outstanding.", kMaxTrackedPackets));
1137 void QuicConnection::PopulateAckFrame(QuicAckFrame* ack) {
1138 received_packet_manager_.UpdateReceivedPacketInfo(ack,
1139 clock_->ApproximateNow());
1142 void QuicConnection::PopulateStopWaitingFrame(
1143 QuicStopWaitingFrame* stop_waiting) {
1144 stop_waiting->least_unacked = GetLeastUnacked();
1145 stop_waiting->entropy_hash = sent_entropy_manager_.GetCumulativeEntropy(
1146 stop_waiting->least_unacked - 1);
1149 bool QuicConnection::ShouldLastPacketInstigateAck() const {
1150 if (FLAGS_quic_process_frames_inline && should_last_packet_instigate_acks_) {
1151 return true;
1153 if (!FLAGS_quic_process_frames_inline) {
1154 if (!last_stream_frames_.empty() || !last_goaway_frames_.empty() ||
1155 !last_rst_frames_.empty() || !last_window_update_frames_.empty() ||
1156 !last_blocked_frames_.empty() || !last_ping_frames_.empty()) {
1157 return true;
1160 if (!last_ack_frames_.empty() && last_ack_frames_.back().is_truncated) {
1161 return true;
1164 // Always send an ack every 20 packets in order to allow the peer to discard
1165 // information from the SentPacketManager and provide an RTT measurement.
1166 if (num_packets_received_since_last_ack_sent_ >=
1167 kMaxPacketsReceivedBeforeAckSend) {
1168 return true;
1170 return false;
1173 void QuicConnection::UpdateStopWaitingCount() {
1174 if (last_ack_frames_.empty()) {
1175 return;
1178 // If the peer is still waiting for a packet that we are no longer planning to
1179 // send, send an ack to raise the high water mark.
1180 if (!last_ack_frames_.back().missing_packets.empty() &&
1181 GetLeastUnacked() > *last_ack_frames_.back().missing_packets.begin()) {
1182 ++stop_waiting_count_;
1183 } else {
1184 stop_waiting_count_ = 0;
1188 QuicPacketSequenceNumber QuicConnection::GetLeastUnacked() const {
1189 return sent_packet_manager_.GetLeastUnacked();
1192 void QuicConnection::MaybeSendInResponseToPacket() {
1193 if (!connected_) {
1194 return;
1196 ScopedPacketBundler bundler(this, ack_queued_ ? SEND_ACK : NO_ACK);
1198 // Now that we have received an ack, we might be able to send packets which
1199 // are queued locally, or drain streams which are blocked.
1200 WriteIfNotBlocked();
1203 void QuicConnection::SendVersionNegotiationPacket() {
1204 // TODO(alyssar): implement zero server state negotiation.
1205 pending_version_negotiation_packet_ = true;
1206 if (writer_->IsWriteBlocked()) {
1207 visitor_->OnWriteBlocked();
1208 return;
1210 DVLOG(1) << ENDPOINT << "Sending version negotiation packet: {"
1211 << QuicVersionVectorToString(framer_.supported_versions()) << "}";
1212 scoped_ptr<QuicEncryptedPacket> version_packet(
1213 packet_generator_.SerializeVersionNegotiationPacket(
1214 framer_.supported_versions()));
1215 WriteResult result = writer_->WritePacket(
1216 version_packet->data(), version_packet->length(),
1217 self_address().address(), peer_address());
1219 if (result.status == WRITE_STATUS_ERROR) {
1220 // We can't send an error as the socket is presumably borked.
1221 CloseConnection(QUIC_PACKET_WRITE_ERROR, false);
1222 return;
1224 if (result.status == WRITE_STATUS_BLOCKED) {
1225 visitor_->OnWriteBlocked();
1226 if (writer_->IsWriteBlockedDataBuffered()) {
1227 pending_version_negotiation_packet_ = false;
1229 return;
1232 pending_version_negotiation_packet_ = false;
1235 QuicConsumedData QuicConnection::SendStreamData(
1236 QuicStreamId id,
1237 const QuicIOVector& iov,
1238 QuicStreamOffset offset,
1239 bool fin,
1240 FecProtection fec_protection,
1241 QuicAckNotifier::DelegateInterface* delegate) {
1242 if (!fin && iov.total_length == 0) {
1243 LOG(DFATAL) << "Attempt to send empty stream frame";
1244 return QuicConsumedData(0, false);
1247 // Opportunistically bundle an ack with every outgoing packet.
1248 // Particularly, we want to bundle with handshake packets since we don't know
1249 // which decrypter will be used on an ack packet following a handshake
1250 // packet (a handshake packet from client to server could result in a REJ or a
1251 // SHLO from the server, leading to two different decrypters at the server.)
1253 // TODO(jri): Note that ConsumeData may cause a response packet to be sent.
1254 // We may end up sending stale ack information if there are undecryptable
1255 // packets hanging around and/or there are revivable packets which may get
1256 // handled after this packet is sent. Change ScopedPacketBundler to do the
1257 // right thing: check ack_queued_, and then check undecryptable packets and
1258 // also if there is possibility of revival. Only bundle an ack if there's no
1259 // processing left that may cause received_info_ to change.
1260 ScopedRetransmissionScheduler alarm_delayer(this);
1261 ScopedPacketBundler ack_bundler(this, BUNDLE_PENDING_ACK);
1262 return packet_generator_.ConsumeData(id, iov, offset, fin, fec_protection,
1263 delegate);
1266 void QuicConnection::SendRstStream(QuicStreamId id,
1267 QuicRstStreamErrorCode error,
1268 QuicStreamOffset bytes_written) {
1269 // Opportunistically bundle an ack with this outgoing packet.
1270 ScopedPacketBundler ack_bundler(this, BUNDLE_PENDING_ACK);
1271 packet_generator_.AddControlFrame(QuicFrame(new QuicRstStreamFrame(
1272 id, AdjustErrorForVersion(error, version()), bytes_written)));
1274 sent_packet_manager_.CancelRetransmissionsForStream(id);
1275 // Remove all queued packets which only contain data for the reset stream.
1276 QueuedPacketList::iterator packet_iterator = queued_packets_.begin();
1277 while (packet_iterator != queued_packets_.end()) {
1278 RetransmittableFrames* retransmittable_frames =
1279 packet_iterator->serialized_packet.retransmittable_frames;
1280 if (!retransmittable_frames) {
1281 ++packet_iterator;
1282 continue;
1284 retransmittable_frames->RemoveFramesForStream(id);
1285 if (!retransmittable_frames->frames().empty()) {
1286 ++packet_iterator;
1287 continue;
1289 delete packet_iterator->serialized_packet.retransmittable_frames;
1290 delete packet_iterator->serialized_packet.packet;
1291 packet_iterator->serialized_packet.retransmittable_frames = nullptr;
1292 packet_iterator->serialized_packet.packet = nullptr;
1293 packet_iterator = queued_packets_.erase(packet_iterator);
1297 void QuicConnection::SendWindowUpdate(QuicStreamId id,
1298 QuicStreamOffset byte_offset) {
1299 // Opportunistically bundle an ack with this outgoing packet.
1300 ScopedPacketBundler ack_bundler(this, BUNDLE_PENDING_ACK);
1301 packet_generator_.AddControlFrame(
1302 QuicFrame(new QuicWindowUpdateFrame(id, byte_offset)));
1305 void QuicConnection::SendBlocked(QuicStreamId id) {
1306 // Opportunistically bundle an ack with this outgoing packet.
1307 ScopedPacketBundler ack_bundler(this, BUNDLE_PENDING_ACK);
1308 packet_generator_.AddControlFrame(QuicFrame(new QuicBlockedFrame(id)));
1311 const QuicConnectionStats& QuicConnection::GetStats() {
1312 const RttStats* rtt_stats = sent_packet_manager_.GetRttStats();
1314 // Update rtt and estimated bandwidth.
1315 QuicTime::Delta min_rtt = rtt_stats->min_rtt();
1316 if (min_rtt.IsZero()) {
1317 // If min RTT has not been set, use initial RTT instead.
1318 min_rtt = QuicTime::Delta::FromMicroseconds(rtt_stats->initial_rtt_us());
1320 stats_.min_rtt_us = min_rtt.ToMicroseconds();
1322 QuicTime::Delta srtt = rtt_stats->smoothed_rtt();
1323 if (srtt.IsZero()) {
1324 // If SRTT has not been set, use initial RTT instead.
1325 srtt = QuicTime::Delta::FromMicroseconds(rtt_stats->initial_rtt_us());
1327 stats_.srtt_us = srtt.ToMicroseconds();
1329 stats_.estimated_bandwidth = sent_packet_manager_.BandwidthEstimate();
1330 stats_.max_packet_size = packet_generator_.GetMaxPacketLength();
1331 stats_.max_received_packet_size = largest_received_packet_size_;
1332 return stats_;
1335 void QuicConnection::ProcessUdpPacket(const IPEndPoint& self_address,
1336 const IPEndPoint& peer_address,
1337 const QuicEncryptedPacket& packet) {
1338 if (!connected_) {
1339 return;
1341 // TODO(rtenneti): Remove ScopedTracker below once crbug.com/462789 is fixed.
1342 tracked_objects::ScopedTracker tracking_profile(
1343 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1344 "462789 QuicConnection::ProcessUdpPacket"));
1345 if (debug_visitor_ != nullptr) {
1346 debug_visitor_->OnPacketReceived(self_address, peer_address, packet);
1348 last_size_ = packet.length();
1350 CheckForAddressMigration(self_address, peer_address);
1352 stats_.bytes_received += packet.length();
1353 ++stats_.packets_received;
1355 ScopedRetransmissionScheduler alarm_delayer(this);
1356 if (!framer_.ProcessPacket(packet)) {
1357 // If we are unable to decrypt this packet, it might be
1358 // because the CHLO or SHLO packet was lost.
1359 if (framer_.error() == QUIC_DECRYPTION_FAILURE) {
1360 if (encryption_level_ != ENCRYPTION_FORWARD_SECURE &&
1361 undecryptable_packets_.size() < max_undecryptable_packets_) {
1362 QueueUndecryptablePacket(packet);
1363 } else if (debug_visitor_ != nullptr) {
1364 debug_visitor_->OnUndecryptablePacket();
1367 DVLOG(1) << ENDPOINT << "Unable to process packet. Last packet processed: "
1368 << last_header_.packet_sequence_number;
1369 return;
1372 ++stats_.packets_processed;
1373 MaybeProcessUndecryptablePackets();
1374 MaybeProcessRevivedPacket();
1375 MaybeSendInResponseToPacket();
1376 SetPingAlarm();
1379 void QuicConnection::CheckForAddressMigration(
1380 const IPEndPoint& self_address, const IPEndPoint& peer_address) {
1381 peer_ip_changed_ = false;
1382 peer_port_changed_ = false;
1383 self_ip_changed_ = false;
1384 self_port_changed_ = false;
1386 if (peer_address_.address().empty()) {
1387 peer_address_ = peer_address;
1389 if (self_address_.address().empty()) {
1390 self_address_ = self_address;
1393 if (!peer_address.address().empty() && !peer_address_.address().empty()) {
1394 peer_ip_changed_ = (peer_address.address() != peer_address_.address());
1395 peer_port_changed_ = (peer_address.port() != peer_address_.port());
1397 // Store in case we want to migrate connection in ProcessValidatedPacket.
1398 migrating_peer_ip_ = peer_address.address();
1399 migrating_peer_port_ = peer_address.port();
1402 if (!self_address.address().empty() && !self_address_.address().empty()) {
1403 self_ip_changed_ = (self_address.address() != self_address_.address());
1404 self_port_changed_ = (self_address.port() != self_address_.port());
1408 void QuicConnection::OnCanWrite() {
1409 DCHECK(!writer_->IsWriteBlocked());
1411 WriteQueuedPackets();
1412 WritePendingRetransmissions();
1414 // Sending queued packets may have caused the socket to become write blocked,
1415 // or the congestion manager to prohibit sending. If we've sent everything
1416 // we had queued and we're still not blocked, let the visitor know it can
1417 // write more.
1418 if (!CanWrite(HAS_RETRANSMITTABLE_DATA)) {
1419 return;
1422 { // Limit the scope of the bundler. ACK inclusion happens elsewhere.
1423 ScopedPacketBundler bundler(this, NO_ACK);
1424 visitor_->OnCanWrite();
1427 // After the visitor writes, it may have caused the socket to become write
1428 // blocked or the congestion manager to prohibit sending, so check again.
1429 if (visitor_->WillingAndAbleToWrite() &&
1430 !resume_writes_alarm_->IsSet() &&
1431 CanWrite(HAS_RETRANSMITTABLE_DATA)) {
1432 // We're not write blocked, but some stream didn't write out all of its
1433 // bytes. Register for 'immediate' resumption so we'll keep writing after
1434 // other connections and events have had a chance to use the thread.
1435 resume_writes_alarm_->Set(clock_->ApproximateNow());
1439 void QuicConnection::WriteIfNotBlocked() {
1440 if (!writer_->IsWriteBlocked()) {
1441 OnCanWrite();
1445 bool QuicConnection::ProcessValidatedPacket() {
1446 if ((peer_ip_changed_ && !FLAGS_quic_allow_ip_migration) ||
1447 self_ip_changed_ || self_port_changed_) {
1448 SendConnectionCloseWithDetails(
1449 QUIC_ERROR_MIGRATING_ADDRESS,
1450 "Neither IP address migration, nor self port migration are supported.");
1451 return false;
1454 // TODO(fayang): Use peer_address_changed_ instead of peer_ip_changed_ and
1455 // peer_port_changed_ once FLAGS_quic_allow_ip_migration is deprecated.
1456 if (peer_ip_changed_ || peer_port_changed_) {
1457 IPEndPoint old_peer_address = peer_address_;
1458 peer_address_ = IPEndPoint(
1459 peer_ip_changed_ ? migrating_peer_ip_ : peer_address_.address(),
1460 peer_port_changed_ ? migrating_peer_port_ : peer_address_.port());
1462 DVLOG(1) << ENDPOINT << "Peer's ip:port changed from "
1463 << old_peer_address.ToString() << " to "
1464 << peer_address_.ToString() << ", migrating connection.";
1467 time_of_last_received_packet_ = clock_->Now();
1468 DVLOG(1) << ENDPOINT << "time of last received packet: "
1469 << time_of_last_received_packet_.ToDebuggingValue();
1471 if (last_size_ > largest_received_packet_size_) {
1472 largest_received_packet_size_ = last_size_;
1475 if (perspective_ == Perspective::IS_SERVER &&
1476 encryption_level_ == ENCRYPTION_NONE &&
1477 last_size_ > packet_generator_.GetMaxPacketLength()) {
1478 set_max_packet_length(last_size_);
1480 return true;
1483 void QuicConnection::WriteQueuedPackets() {
1484 DCHECK(!writer_->IsWriteBlocked());
1486 if (pending_version_negotiation_packet_) {
1487 SendVersionNegotiationPacket();
1490 QueuedPacketList::iterator packet_iterator = queued_packets_.begin();
1491 while (packet_iterator != queued_packets_.end() &&
1492 WritePacket(&(*packet_iterator))) {
1493 packet_iterator = queued_packets_.erase(packet_iterator);
1497 void QuicConnection::WritePendingRetransmissions() {
1498 // Keep writing as long as there's a pending retransmission which can be
1499 // written.
1500 while (sent_packet_manager_.HasPendingRetransmissions()) {
1501 const QuicSentPacketManager::PendingRetransmission pending =
1502 sent_packet_manager_.NextPendingRetransmission();
1503 if (!CanWrite(HAS_RETRANSMITTABLE_DATA)) {
1504 break;
1507 // Re-packetize the frames with a new sequence number for retransmission.
1508 // Retransmitted data packets do not use FEC, even when it's enabled.
1509 // Retransmitted packets use the same sequence number length as the
1510 // original.
1511 // Flush the packet generator before making a new packet.
1512 // TODO(ianswett): Implement ReserializeAllFrames as a separate path that
1513 // does not require the creator to be flushed.
1514 packet_generator_.FlushAllQueuedFrames();
1515 char buffer[kMaxPacketSize];
1516 SerializedPacket serialized_packet = packet_generator_.ReserializeAllFrames(
1517 pending.retransmittable_frames, pending.sequence_number_length, buffer,
1518 kMaxPacketSize);
1519 if (serialized_packet.packet == nullptr) {
1520 // We failed to serialize the packet, so close the connection.
1521 // CloseConnection does not send close packet, so no infinite loop here.
1522 CloseConnection(QUIC_ENCRYPTION_FAILURE, false);
1523 return;
1526 DVLOG(1) << ENDPOINT << "Retransmitting " << pending.sequence_number
1527 << " as " << serialized_packet.sequence_number;
1528 SendOrQueuePacket(
1529 QueuedPacket(serialized_packet,
1530 pending.retransmittable_frames.encryption_level(),
1531 pending.transmission_type,
1532 pending.sequence_number));
1536 void QuicConnection::RetransmitUnackedPackets(
1537 TransmissionType retransmission_type) {
1538 sent_packet_manager_.RetransmitUnackedPackets(retransmission_type);
1540 WriteIfNotBlocked();
1543 void QuicConnection::NeuterUnencryptedPackets() {
1544 sent_packet_manager_.NeuterUnencryptedPackets();
1545 // This may have changed the retransmission timer, so re-arm it.
1546 SetRetransmissionAlarm();
1549 bool QuicConnection::ShouldGeneratePacket(
1550 HasRetransmittableData retransmittable,
1551 IsHandshake handshake) {
1552 // We should serialize handshake packets immediately to ensure that they
1553 // end up sent at the right encryption level.
1554 if (handshake == IS_HANDSHAKE) {
1555 return true;
1558 return CanWrite(retransmittable);
1561 bool QuicConnection::CanWrite(HasRetransmittableData retransmittable) {
1562 if (!connected_) {
1563 return false;
1566 if (writer_->IsWriteBlocked()) {
1567 visitor_->OnWriteBlocked();
1568 return false;
1571 QuicTime now = clock_->Now();
1572 QuicTime::Delta delay = sent_packet_manager_.TimeUntilSend(
1573 now, retransmittable);
1574 if (delay.IsInfinite()) {
1575 send_alarm_->Cancel();
1576 return false;
1579 // If the scheduler requires a delay, then we can not send this packet now.
1580 if (!delay.IsZero()) {
1581 send_alarm_->Update(now.Add(delay), QuicTime::Delta::FromMilliseconds(1));
1582 DVLOG(1) << ENDPOINT << "Delaying sending " << delay.ToMilliseconds()
1583 << "ms";
1584 return false;
1586 send_alarm_->Cancel();
1587 return true;
1590 bool QuicConnection::WritePacket(QueuedPacket* packet) {
1591 if (!WritePacketInner(packet)) {
1592 return false;
1594 delete packet->serialized_packet.retransmittable_frames;
1595 delete packet->serialized_packet.packet;
1596 packet->serialized_packet.retransmittable_frames = nullptr;
1597 packet->serialized_packet.packet = nullptr;
1598 return true;
1601 bool QuicConnection::WritePacketInner(QueuedPacket* packet) {
1602 if (ShouldDiscardPacket(*packet)) {
1603 ++stats_.packets_discarded;
1604 return true;
1606 // Connection close packets are encrypted and saved, so don't exit early.
1607 const bool is_connection_close = IsConnectionClose(*packet);
1608 if (writer_->IsWriteBlocked() && !is_connection_close) {
1609 return false;
1612 QuicPacketSequenceNumber sequence_number =
1613 packet->serialized_packet.sequence_number;
1614 DCHECK_LE(sequence_number_of_last_sent_packet_, sequence_number);
1615 sequence_number_of_last_sent_packet_ = sequence_number;
1617 QuicEncryptedPacket* encrypted = packet->serialized_packet.packet;
1618 // Connection close packets are eventually owned by TimeWaitListManager.
1619 // Others are deleted at the end of this call.
1620 if (is_connection_close) {
1621 DCHECK(connection_close_packet_.get() == nullptr);
1622 // Clone the packet so it's owned in the future.
1623 connection_close_packet_.reset(encrypted->Clone());
1624 // This assures we won't try to write *forced* packets when blocked.
1625 // Return true to stop processing.
1626 if (writer_->IsWriteBlocked()) {
1627 visitor_->OnWriteBlocked();
1628 return true;
1632 if (!FLAGS_quic_allow_oversized_packets_for_test) {
1633 DCHECK_LE(encrypted->length(), kMaxPacketSize);
1635 DCHECK_LE(encrypted->length(), packet_generator_.GetMaxPacketLength());
1636 DVLOG(1) << ENDPOINT << "Sending packet " << sequence_number << " : "
1637 << (packet->serialized_packet.is_fec_packet
1638 ? "FEC "
1639 : (IsRetransmittable(*packet) == HAS_RETRANSMITTABLE_DATA
1640 ? "data bearing "
1641 : " ack only ")) << ", encryption level: "
1642 << QuicUtils::EncryptionLevelToString(packet->encryption_level)
1643 << ", encrypted length:" << encrypted->length();
1644 DVLOG(2) << ENDPOINT << "packet(" << sequence_number << "): " << std::endl
1645 << QuicUtils::StringToHexASCIIDump(encrypted->AsStringPiece());
1647 // Measure the RTT from before the write begins to avoid underestimating the
1648 // min_rtt_, especially in cases where the thread blocks or gets swapped out
1649 // during the WritePacket below.
1650 QuicTime packet_send_time = clock_->Now();
1651 WriteResult result = writer_->WritePacket(encrypted->data(),
1652 encrypted->length(),
1653 self_address().address(),
1654 peer_address());
1655 if (result.error_code == ERR_IO_PENDING) {
1656 DCHECK_EQ(WRITE_STATUS_BLOCKED, result.status);
1659 if (result.status == WRITE_STATUS_BLOCKED) {
1660 visitor_->OnWriteBlocked();
1661 // If the socket buffers the the data, then the packet should not
1662 // be queued and sent again, which would result in an unnecessary
1663 // duplicate packet being sent. The helper must call OnCanWrite
1664 // when the write completes, and OnWriteError if an error occurs.
1665 if (!writer_->IsWriteBlockedDataBuffered()) {
1666 return false;
1669 if (result.status != WRITE_STATUS_ERROR && debug_visitor_ != nullptr) {
1670 // Pass the write result to the visitor.
1671 debug_visitor_->OnPacketSent(packet->serialized_packet,
1672 packet->original_sequence_number,
1673 packet->encryption_level,
1674 packet->transmission_type,
1675 *encrypted,
1676 packet_send_time);
1678 if (packet->transmission_type == NOT_RETRANSMISSION) {
1679 time_of_last_sent_new_packet_ = packet_send_time;
1681 SetPingAlarm();
1682 MaybeSetFecAlarm(sequence_number);
1683 MaybeSetMtuAlarm();
1684 DVLOG(1) << ENDPOINT << "time we began writing last sent packet: "
1685 << packet_send_time.ToDebuggingValue();
1687 // TODO(ianswett): Change the sequence number length and other packet creator
1688 // options by a more explicit API than setting a struct value directly,
1689 // perhaps via the NetworkChangeVisitor.
1690 packet_generator_.UpdateSequenceNumberLength(
1691 sent_packet_manager_.least_packet_awaited_by_peer(),
1692 sent_packet_manager_.EstimateMaxPacketsInFlight(max_packet_length()));
1694 bool reset_retransmission_alarm = sent_packet_manager_.OnPacketSent(
1695 &packet->serialized_packet,
1696 packet->original_sequence_number,
1697 packet_send_time,
1698 encrypted->length(),
1699 packet->transmission_type,
1700 IsRetransmittable(*packet));
1702 if (reset_retransmission_alarm || !retransmission_alarm_->IsSet()) {
1703 SetRetransmissionAlarm();
1706 stats_.bytes_sent += result.bytes_written;
1707 ++stats_.packets_sent;
1708 if (packet->transmission_type != NOT_RETRANSMISSION) {
1709 stats_.bytes_retransmitted += result.bytes_written;
1710 ++stats_.packets_retransmitted;
1713 if (result.status == WRITE_STATUS_ERROR) {
1714 OnWriteError(result.error_code);
1715 DLOG(ERROR) << ENDPOINT << "failed writing " << encrypted->length()
1716 << " bytes "
1717 << " from host " << self_address().ToStringWithoutPort()
1718 << " to address " << peer_address().ToString();
1719 return false;
1722 return true;
1725 bool QuicConnection::ShouldDiscardPacket(const QueuedPacket& packet) {
1726 if (!connected_) {
1727 DVLOG(1) << ENDPOINT
1728 << "Not sending packet as connection is disconnected.";
1729 return true;
1732 QuicPacketSequenceNumber sequence_number =
1733 packet.serialized_packet.sequence_number;
1734 if (encryption_level_ == ENCRYPTION_FORWARD_SECURE &&
1735 packet.encryption_level == ENCRYPTION_NONE) {
1736 // Drop packets that are NULL encrypted since the peer won't accept them
1737 // anymore.
1738 DVLOG(1) << ENDPOINT << "Dropping NULL encrypted packet: "
1739 << sequence_number << " since the connection is forward secure.";
1740 return true;
1743 // If a retransmission has been acked before sending, don't send it.
1744 // This occurs if a packet gets serialized, queued, then discarded.
1745 if (packet.transmission_type != NOT_RETRANSMISSION &&
1746 (!sent_packet_manager_.IsUnacked(packet.original_sequence_number) ||
1747 !sent_packet_manager_.HasRetransmittableFrames(
1748 packet.original_sequence_number))) {
1749 DVLOG(1) << ENDPOINT << "Dropping unacked packet: " << sequence_number
1750 << " A previous transmission was acked while write blocked.";
1751 return true;
1754 return false;
1757 void QuicConnection::OnWriteError(int error_code) {
1758 DVLOG(1) << ENDPOINT << "Write failed with error: " << error_code
1759 << " (" << ErrorToString(error_code) << ")";
1760 // We can't send an error as the socket is presumably borked.
1761 CloseConnection(QUIC_PACKET_WRITE_ERROR, false);
1764 void QuicConnection::OnSerializedPacket(
1765 const SerializedPacket& serialized_packet) {
1766 if (serialized_packet.packet == nullptr) {
1767 // We failed to serialize the packet, so close the connection.
1768 // CloseConnection does not send close packet, so no infinite loop here.
1769 CloseConnection(QUIC_ENCRYPTION_FAILURE, false);
1770 return;
1772 sent_packet_manager_.OnSerializedPacket(serialized_packet);
1773 if (serialized_packet.is_fec_packet && fec_alarm_->IsSet()) {
1774 // If an FEC packet is serialized with the FEC alarm set, cancel the alarm.
1775 fec_alarm_->Cancel();
1777 SendOrQueuePacket(QueuedPacket(serialized_packet, encryption_level_));
1780 void QuicConnection::OnResetFecGroup() {
1781 if (!fec_alarm_->IsSet()) {
1782 return;
1784 // If an FEC Group is closed with the FEC alarm set, cancel the alarm.
1785 fec_alarm_->Cancel();
1788 void QuicConnection::OnCongestionWindowChange() {
1789 packet_generator_.OnCongestionWindowChange(
1790 sent_packet_manager_.EstimateMaxPacketsInFlight(max_packet_length()));
1791 visitor_->OnCongestionWindowChange(clock_->ApproximateNow());
1794 void QuicConnection::OnRttChange() {
1795 // Uses the connection's smoothed RTT. If zero, uses initial_rtt.
1796 QuicTime::Delta rtt = sent_packet_manager_.GetRttStats()->smoothed_rtt();
1797 if (rtt.IsZero()) {
1798 rtt = QuicTime::Delta::FromMicroseconds(
1799 sent_packet_manager_.GetRttStats()->initial_rtt_us());
1801 packet_generator_.OnRttChange(rtt);
1804 void QuicConnection::OnHandshakeComplete() {
1805 sent_packet_manager_.SetHandshakeConfirmed();
1806 // The client should immediately ack the SHLO to confirm the handshake is
1807 // complete with the server.
1808 if (perspective_ == Perspective::IS_CLIENT && !ack_queued_) {
1809 ack_alarm_->Cancel();
1810 ack_alarm_->Set(clock_->ApproximateNow());
1814 void QuicConnection::SendOrQueuePacket(QueuedPacket packet) {
1815 // The caller of this function is responsible for checking CanWrite().
1816 if (packet.serialized_packet.packet == nullptr) {
1817 LOG(DFATAL)
1818 << "packet.serialized_packet.packet == nullptr in to SendOrQueuePacket";
1819 return;
1822 sent_entropy_manager_.RecordPacketEntropyHash(
1823 packet.serialized_packet.sequence_number,
1824 packet.serialized_packet.entropy_hash);
1825 if (!WritePacket(&packet)) {
1826 // Take ownership of the underlying encrypted packet.
1827 if (!packet.serialized_packet.packet->owns_buffer()) {
1828 scoped_ptr<QuicEncryptedPacket> encrypted_deleter(
1829 packet.serialized_packet.packet);
1830 packet.serialized_packet.packet =
1831 packet.serialized_packet.packet->Clone();
1833 queued_packets_.push_back(packet);
1836 // If a forward-secure encrypter is available but is not being used and the
1837 // next sequence number is the first packet which requires
1838 // forward security, start using the forward-secure encrypter.
1839 if (encryption_level_ != ENCRYPTION_FORWARD_SECURE &&
1840 has_forward_secure_encrypter_ &&
1841 packet.serialized_packet.sequence_number >=
1842 first_required_forward_secure_packet_ - 1) {
1843 SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
1847 void QuicConnection::SendPing() {
1848 if (retransmission_alarm_->IsSet()) {
1849 return;
1851 packet_generator_.AddControlFrame(QuicFrame(new QuicPingFrame));
1854 void QuicConnection::SendAck() {
1855 ack_alarm_->Cancel();
1856 ack_queued_ = false;
1857 stop_waiting_count_ = 0;
1858 num_packets_received_since_last_ack_sent_ = 0;
1860 packet_generator_.SetShouldSendAck(true);
1863 void QuicConnection::OnRetransmissionTimeout() {
1864 if (!sent_packet_manager_.HasUnackedPackets()) {
1865 return;
1868 sent_packet_manager_.OnRetransmissionTimeout();
1869 WriteIfNotBlocked();
1871 // A write failure can result in the connection being closed, don't attempt to
1872 // write further packets, or to set alarms.
1873 if (!connected_) {
1874 return;
1877 // In the TLP case, the SentPacketManager gives the connection the opportunity
1878 // to send new data before retransmitting.
1879 if (sent_packet_manager_.MaybeRetransmitTailLossProbe()) {
1880 // Send the pending retransmission now that it's been queued.
1881 WriteIfNotBlocked();
1884 // Ensure the retransmission alarm is always set if there are unacked packets
1885 // and nothing waiting to be sent.
1886 // This happens if the loss algorithm invokes a timer based loss, but the
1887 // packet doesn't need to be retransmitted.
1888 if (!HasQueuedData() && !retransmission_alarm_->IsSet()) {
1889 SetRetransmissionAlarm();
1893 void QuicConnection::SetEncrypter(EncryptionLevel level,
1894 QuicEncrypter* encrypter) {
1895 packet_generator_.SetEncrypter(level, encrypter);
1896 if (level == ENCRYPTION_FORWARD_SECURE) {
1897 has_forward_secure_encrypter_ = true;
1898 first_required_forward_secure_packet_ =
1899 sequence_number_of_last_sent_packet_ +
1900 // 3 times the current congestion window (in slow start) should cover
1901 // about two full round trips worth of packets, which should be
1902 // sufficient.
1903 3 * sent_packet_manager_.EstimateMaxPacketsInFlight(
1904 max_packet_length());
1908 void QuicConnection::SetDefaultEncryptionLevel(EncryptionLevel level) {
1909 encryption_level_ = level;
1910 packet_generator_.set_encryption_level(level);
1913 void QuicConnection::SetDecrypter(EncryptionLevel level,
1914 QuicDecrypter* decrypter) {
1915 framer_.SetDecrypter(level, decrypter);
1918 void QuicConnection::SetAlternativeDecrypter(EncryptionLevel level,
1919 QuicDecrypter* decrypter,
1920 bool latch_once_used) {
1921 framer_.SetAlternativeDecrypter(level, decrypter, latch_once_used);
1924 const QuicDecrypter* QuicConnection::decrypter() const {
1925 return framer_.decrypter();
1928 const QuicDecrypter* QuicConnection::alternative_decrypter() const {
1929 return framer_.alternative_decrypter();
1932 void QuicConnection::QueueUndecryptablePacket(
1933 const QuicEncryptedPacket& packet) {
1934 DVLOG(1) << ENDPOINT << "Queueing undecryptable packet.";
1935 undecryptable_packets_.push_back(packet.Clone());
1938 void QuicConnection::MaybeProcessUndecryptablePackets() {
1939 if (undecryptable_packets_.empty() || encryption_level_ == ENCRYPTION_NONE) {
1940 return;
1943 while (connected_ && !undecryptable_packets_.empty()) {
1944 DVLOG(1) << ENDPOINT << "Attempting to process undecryptable packet";
1945 QuicEncryptedPacket* packet = undecryptable_packets_.front();
1946 if (!framer_.ProcessPacket(*packet) &&
1947 framer_.error() == QUIC_DECRYPTION_FAILURE) {
1948 DVLOG(1) << ENDPOINT << "Unable to process undecryptable packet...";
1949 break;
1951 DVLOG(1) << ENDPOINT << "Processed undecryptable packet!";
1952 ++stats_.packets_processed;
1953 delete packet;
1954 undecryptable_packets_.pop_front();
1957 // Once forward secure encryption is in use, there will be no
1958 // new keys installed and hence any undecryptable packets will
1959 // never be able to be decrypted.
1960 if (encryption_level_ == ENCRYPTION_FORWARD_SECURE) {
1961 if (debug_visitor_ != nullptr) {
1962 // TODO(rtenneti): perhaps more efficient to pass the number of
1963 // undecryptable packets as the argument to OnUndecryptablePacket so that
1964 // we just need to call OnUndecryptablePacket once?
1965 for (size_t i = 0; i < undecryptable_packets_.size(); ++i) {
1966 debug_visitor_->OnUndecryptablePacket();
1969 STLDeleteElements(&undecryptable_packets_);
1973 void QuicConnection::MaybeProcessRevivedPacket() {
1974 QuicFecGroup* group = GetFecGroup();
1975 if (!connected_ || group == nullptr || !group->CanRevive()) {
1976 return;
1978 QuicPacketHeader revived_header;
1979 char revived_payload[kMaxPacketSize];
1980 size_t len = group->Revive(&revived_header, revived_payload, kMaxPacketSize);
1981 revived_header.public_header.connection_id = connection_id_;
1982 revived_header.public_header.connection_id_length =
1983 last_header_.public_header.connection_id_length;
1984 revived_header.public_header.version_flag = false;
1985 revived_header.public_header.reset_flag = false;
1986 revived_header.public_header.sequence_number_length =
1987 last_header_.public_header.sequence_number_length;
1988 revived_header.fec_flag = false;
1989 revived_header.is_in_fec_group = NOT_IN_FEC_GROUP;
1990 revived_header.fec_group = 0;
1991 group_map_.erase(last_header_.fec_group);
1992 last_decrypted_packet_level_ = group->effective_encryption_level();
1993 DCHECK_LT(last_decrypted_packet_level_, NUM_ENCRYPTION_LEVELS);
1994 delete group;
1996 last_packet_revived_ = true;
1997 if (debug_visitor_ != nullptr) {
1998 debug_visitor_->OnRevivedPacket(revived_header,
1999 StringPiece(revived_payload, len));
2002 ++stats_.packets_revived;
2003 framer_.ProcessRevivedPacket(&revived_header,
2004 StringPiece(revived_payload, len));
2007 QuicFecGroup* QuicConnection::GetFecGroup() {
2008 QuicFecGroupNumber fec_group_num = last_header_.fec_group;
2009 if (fec_group_num == 0) {
2010 return nullptr;
2012 if (!ContainsKey(group_map_, fec_group_num)) {
2013 if (group_map_.size() >= kMaxFecGroups) { // Too many groups
2014 if (fec_group_num < group_map_.begin()->first) {
2015 // The group being requested is a group we've seen before and deleted.
2016 // Don't recreate it.
2017 return nullptr;
2019 // Clear the lowest group number.
2020 delete group_map_.begin()->second;
2021 group_map_.erase(group_map_.begin());
2023 group_map_[fec_group_num] = new QuicFecGroup();
2025 return group_map_[fec_group_num];
2028 void QuicConnection::SendConnectionClose(QuicErrorCode error) {
2029 SendConnectionCloseWithDetails(error, string());
2032 void QuicConnection::SendConnectionCloseWithDetails(QuicErrorCode error,
2033 const string& details) {
2034 // If we're write blocked, WritePacket() will not send, but will capture the
2035 // serialized packet.
2036 SendConnectionClosePacket(error, details);
2037 CloseConnection(error, false);
2040 void QuicConnection::SendConnectionClosePacket(QuicErrorCode error,
2041 const string& details) {
2042 DVLOG(1) << ENDPOINT << "Force closing " << connection_id()
2043 << " with error " << QuicUtils::ErrorToString(error)
2044 << " (" << error << ") " << details;
2045 // Don't send explicit connection close packets for timeouts.
2046 // This is particularly important on mobile, where connections are short.
2047 if (silent_close_enabled_ &&
2048 error == QuicErrorCode::QUIC_CONNECTION_TIMED_OUT) {
2049 return;
2051 ScopedPacketBundler ack_bundler(this, SEND_ACK);
2052 QuicConnectionCloseFrame* frame = new QuicConnectionCloseFrame();
2053 frame->error_code = error;
2054 frame->error_details = details;
2055 packet_generator_.AddControlFrame(QuicFrame(frame));
2056 packet_generator_.FlushAllQueuedFrames();
2059 void QuicConnection::CloseConnection(QuicErrorCode error, bool from_peer) {
2060 if (!connected_) {
2061 DVLOG(1) << "Connection is already closed.";
2062 return;
2064 connected_ = false;
2065 if (debug_visitor_ != nullptr) {
2066 debug_visitor_->OnConnectionClosed(error, from_peer);
2068 DCHECK(visitor_ != nullptr);
2069 visitor_->OnConnectionClosed(error, from_peer);
2070 // Cancel the alarms so they don't trigger any action now that the
2071 // connection is closed.
2072 ack_alarm_->Cancel();
2073 ping_alarm_->Cancel();
2074 fec_alarm_->Cancel();
2075 resume_writes_alarm_->Cancel();
2076 retransmission_alarm_->Cancel();
2077 send_alarm_->Cancel();
2078 timeout_alarm_->Cancel();
2079 mtu_discovery_alarm_->Cancel();
2082 void QuicConnection::SendGoAway(QuicErrorCode error,
2083 QuicStreamId last_good_stream_id,
2084 const string& reason) {
2085 DVLOG(1) << ENDPOINT << "Going away with error "
2086 << QuicUtils::ErrorToString(error)
2087 << " (" << error << ")";
2089 // Opportunistically bundle an ack with this outgoing packet.
2090 ScopedPacketBundler ack_bundler(this, BUNDLE_PENDING_ACK);
2091 packet_generator_.AddControlFrame(
2092 QuicFrame(new QuicGoAwayFrame(error, last_good_stream_id, reason)));
2095 void QuicConnection::CloseFecGroupsBefore(
2096 QuicPacketSequenceNumber sequence_number) {
2097 FecGroupMap::iterator it = group_map_.begin();
2098 while (it != group_map_.end()) {
2099 // If this is the current group or the group doesn't protect this packet
2100 // we can ignore it.
2101 if (last_header_.fec_group == it->first ||
2102 !it->second->ProtectsPacketsBefore(sequence_number)) {
2103 ++it;
2104 continue;
2106 QuicFecGroup* fec_group = it->second;
2107 DCHECK(!fec_group->CanRevive());
2108 FecGroupMap::iterator next = it;
2109 ++next;
2110 group_map_.erase(it);
2111 delete fec_group;
2112 it = next;
2116 QuicByteCount QuicConnection::max_packet_length() const {
2117 return packet_generator_.GetMaxPacketLength();
2120 void QuicConnection::set_max_packet_length(QuicByteCount length) {
2121 return packet_generator_.SetMaxPacketLength(length, /*force=*/false);
2124 bool QuicConnection::HasQueuedData() const {
2125 return pending_version_negotiation_packet_ ||
2126 !queued_packets_.empty() || packet_generator_.HasQueuedFrames();
2129 bool QuicConnection::CanWriteStreamData() {
2130 // Don't write stream data if there are negotiation or queued data packets
2131 // to send. Otherwise, continue and bundle as many frames as possible.
2132 if (pending_version_negotiation_packet_ || !queued_packets_.empty()) {
2133 return false;
2136 IsHandshake pending_handshake = visitor_->HasPendingHandshake() ?
2137 IS_HANDSHAKE : NOT_HANDSHAKE;
2138 // Sending queued packets may have caused the socket to become write blocked,
2139 // or the congestion manager to prohibit sending. If we've sent everything
2140 // we had queued and we're still not blocked, let the visitor know it can
2141 // write more.
2142 return ShouldGeneratePacket(HAS_RETRANSMITTABLE_DATA, pending_handshake);
2145 void QuicConnection::SetNetworkTimeouts(QuicTime::Delta overall_timeout,
2146 QuicTime::Delta idle_timeout) {
2147 LOG_IF(DFATAL, idle_timeout > overall_timeout)
2148 << "idle_timeout:" << idle_timeout.ToMilliseconds()
2149 << " overall_timeout:" << overall_timeout.ToMilliseconds();
2150 // Adjust the idle timeout on client and server to prevent clients from
2151 // sending requests to servers which have already closed the connection.
2152 if (perspective_ == Perspective::IS_SERVER) {
2153 idle_timeout = idle_timeout.Add(QuicTime::Delta::FromSeconds(3));
2154 } else if (idle_timeout > QuicTime::Delta::FromSeconds(1)) {
2155 idle_timeout = idle_timeout.Subtract(QuicTime::Delta::FromSeconds(1));
2157 overall_connection_timeout_ = overall_timeout;
2158 idle_network_timeout_ = idle_timeout;
2160 SetTimeoutAlarm();
2163 void QuicConnection::CheckForTimeout() {
2164 QuicTime now = clock_->ApproximateNow();
2165 QuicTime time_of_last_packet = max(time_of_last_received_packet_,
2166 time_of_last_sent_new_packet_);
2168 // |delta| can be < 0 as |now| is approximate time but |time_of_last_packet|
2169 // is accurate time. However, this should not change the behavior of
2170 // timeout handling.
2171 QuicTime::Delta idle_duration = now.Subtract(time_of_last_packet);
2172 DVLOG(1) << ENDPOINT << "last packet "
2173 << time_of_last_packet.ToDebuggingValue()
2174 << " now:" << now.ToDebuggingValue()
2175 << " idle_duration:" << idle_duration.ToMicroseconds()
2176 << " idle_network_timeout: "
2177 << idle_network_timeout_.ToMicroseconds();
2178 if (idle_duration >= idle_network_timeout_) {
2179 DVLOG(1) << ENDPOINT << "Connection timedout due to no network activity.";
2180 SendConnectionClose(QUIC_CONNECTION_TIMED_OUT);
2181 return;
2184 if (!overall_connection_timeout_.IsInfinite()) {
2185 QuicTime::Delta connected_duration =
2186 now.Subtract(stats_.connection_creation_time);
2187 DVLOG(1) << ENDPOINT << "connection time: "
2188 << connected_duration.ToMicroseconds() << " overall timeout: "
2189 << overall_connection_timeout_.ToMicroseconds();
2190 if (connected_duration >= overall_connection_timeout_) {
2191 DVLOG(1) << ENDPOINT <<
2192 "Connection timedout due to overall connection timeout.";
2193 SendConnectionClose(QUIC_CONNECTION_OVERALL_TIMED_OUT);
2194 return;
2198 SetTimeoutAlarm();
2201 void QuicConnection::SetTimeoutAlarm() {
2202 QuicTime time_of_last_packet = max(time_of_last_received_packet_,
2203 time_of_last_sent_new_packet_);
2205 QuicTime deadline = time_of_last_packet.Add(idle_network_timeout_);
2206 if (!overall_connection_timeout_.IsInfinite()) {
2207 deadline = min(deadline,
2208 stats_.connection_creation_time.Add(
2209 overall_connection_timeout_));
2212 timeout_alarm_->Cancel();
2213 timeout_alarm_->Set(deadline);
2216 void QuicConnection::SetPingAlarm() {
2217 if (perspective_ == Perspective::IS_SERVER) {
2218 // Only clients send pings.
2219 return;
2221 if (!visitor_->HasOpenDynamicStreams()) {
2222 ping_alarm_->Cancel();
2223 // Don't send a ping unless there are open streams.
2224 return;
2226 QuicTime::Delta ping_timeout = QuicTime::Delta::FromSeconds(kPingTimeoutSecs);
2227 ping_alarm_->Update(clock_->ApproximateNow().Add(ping_timeout),
2228 QuicTime::Delta::FromSeconds(1));
2231 void QuicConnection::SetRetransmissionAlarm() {
2232 if (delay_setting_retransmission_alarm_) {
2233 pending_retransmission_alarm_ = true;
2234 return;
2236 QuicTime retransmission_time = sent_packet_manager_.GetRetransmissionTime();
2237 retransmission_alarm_->Update(retransmission_time,
2238 QuicTime::Delta::FromMilliseconds(1));
2241 void QuicConnection::MaybeSetMtuAlarm() {
2242 if (!FLAGS_quic_do_path_mtu_discovery) {
2243 return;
2246 // Do not set the alarm if the target size is less than the current size.
2247 // This covers the case when |mtu_discovery_target_| is at its default value,
2248 // zero.
2249 if (mtu_discovery_target_ <= max_packet_length()) {
2250 return;
2253 if (mtu_probe_count_ >= kMtuDiscoveryAttempts) {
2254 return;
2257 if (mtu_discovery_alarm_->IsSet()) {
2258 return;
2261 if (sequence_number_of_last_sent_packet_ >= next_mtu_probe_at_) {
2262 // Use an alarm to send the MTU probe to ensure that no ScopedPacketBundlers
2263 // are active.
2264 mtu_discovery_alarm_->Set(clock_->ApproximateNow());
2268 QuicConnection::ScopedPacketBundler::ScopedPacketBundler(
2269 QuicConnection* connection,
2270 AckBundling send_ack)
2271 : connection_(connection),
2272 already_in_batch_mode_(connection != nullptr &&
2273 connection->packet_generator_.InBatchMode()) {
2274 if (connection_ == nullptr) {
2275 return;
2277 // Move generator into batch mode. If caller wants us to include an ack,
2278 // check the delayed-ack timer to see if there's ack info to be sent.
2279 if (!already_in_batch_mode_) {
2280 DVLOG(1) << "Entering Batch Mode.";
2281 connection_->packet_generator_.StartBatchOperations();
2283 // Bundle an ack if the alarm is set or with every second packet if we need to
2284 // raise the peer's least unacked.
2285 bool ack_pending =
2286 connection_->ack_alarm_->IsSet() || connection_->stop_waiting_count_ > 1;
2287 if (send_ack == SEND_ACK || (send_ack == BUNDLE_PENDING_ACK && ack_pending)) {
2288 DVLOG(1) << "Bundling ack with outgoing packet.";
2289 connection_->SendAck();
2293 QuicConnection::ScopedPacketBundler::~ScopedPacketBundler() {
2294 if (connection_ == nullptr) {
2295 return;
2297 // If we changed the generator's batch state, restore original batch state.
2298 if (!already_in_batch_mode_) {
2299 DVLOG(1) << "Leaving Batch Mode.";
2300 connection_->packet_generator_.FinishBatchOperations();
2302 DCHECK_EQ(already_in_batch_mode_,
2303 connection_->packet_generator_.InBatchMode());
2306 QuicConnection::ScopedRetransmissionScheduler::ScopedRetransmissionScheduler(
2307 QuicConnection* connection)
2308 : connection_(connection),
2309 already_delayed_(connection_->delay_setting_retransmission_alarm_) {
2310 connection_->delay_setting_retransmission_alarm_ = true;
2313 QuicConnection::ScopedRetransmissionScheduler::
2314 ~ScopedRetransmissionScheduler() {
2315 if (already_delayed_) {
2316 return;
2318 connection_->delay_setting_retransmission_alarm_ = false;
2319 if (connection_->pending_retransmission_alarm_) {
2320 connection_->SetRetransmissionAlarm();
2321 connection_->pending_retransmission_alarm_ = false;
2325 HasRetransmittableData QuicConnection::IsRetransmittable(
2326 const QueuedPacket& packet) {
2327 // Retransmitted packets retransmittable frames are owned by the unacked
2328 // packet map, but are not present in the serialized packet.
2329 if (packet.transmission_type != NOT_RETRANSMISSION ||
2330 packet.serialized_packet.retransmittable_frames != nullptr) {
2331 return HAS_RETRANSMITTABLE_DATA;
2332 } else {
2333 return NO_RETRANSMITTABLE_DATA;
2337 bool QuicConnection::IsConnectionClose(const QueuedPacket& packet) {
2338 const RetransmittableFrames* retransmittable_frames =
2339 packet.serialized_packet.retransmittable_frames;
2340 if (retransmittable_frames == nullptr) {
2341 return false;
2343 for (const QuicFrame& frame : retransmittable_frames->frames()) {
2344 if (frame.type == CONNECTION_CLOSE_FRAME) {
2345 return true;
2348 return false;
2351 void QuicConnection::SendMtuDiscoveryPacket(QuicByteCount target_mtu) {
2352 // Create a listener for the new probe. The ownership of the listener is
2353 // transferred to the AckNotifierManager. The notifier will get destroyed
2354 // before the connection (because it's stored in one of the connection's
2355 // subfields), hence |this| pointer is guaranteed to stay valid at all times.
2356 scoped_refptr<MtuDiscoveryAckListener> last_mtu_discovery_ack_listener(
2357 new MtuDiscoveryAckListener(this, target_mtu));
2359 // Send the probe.
2360 packet_generator_.GenerateMtuDiscoveryPacket(
2361 target_mtu, last_mtu_discovery_ack_listener.get());
2364 void QuicConnection::DiscoverMtu() {
2365 DCHECK(!mtu_discovery_alarm_->IsSet());
2367 // Chcek if the MTU has been already increased.
2368 if (mtu_discovery_target_ <= max_packet_length()) {
2369 return;
2372 // Schedule the next probe *before* sending the current one. This is
2373 // important, otherwise, when SendMtuDiscoveryPacket() is called,
2374 // MaybeSetMtuAlarm() will not realize that the probe has been just sent, and
2375 // will reschedule this probe again.
2376 packets_between_mtu_probes_ *= 2;
2377 next_mtu_probe_at_ =
2378 sequence_number_of_last_sent_packet_ + packets_between_mtu_probes_ + 1;
2379 ++mtu_probe_count_;
2381 DVLOG(2) << "Sending a path MTU discovery packet #" << mtu_probe_count_;
2382 SendMtuDiscoveryPacket(mtu_discovery_target_);
2384 DCHECK(!mtu_discovery_alarm_->IsSet());
2387 } // namespace net