Snap pinch zoom gestures near the screen edge.
[chromium-blink-merge.git] / net / quic / quic_connection.cc
blobdde2b0710054d8a80ce8609848c9e57079a8ce34
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/debug/stack_trace.h"
18 #include "base/format_macros.h"
19 #include "base/logging.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 // Maximum number of tracked packets.
67 const QuicPacketCount kMaxTrackedPackets = 5000;
69 bool Near(QuicPacketSequenceNumber a, QuicPacketSequenceNumber b) {
70 QuicPacketSequenceNumber delta = (a > b) ? a - b : b - a;
71 return delta <= kMaxPacketGap;
74 // An alarm that is scheduled to send an ack if a timeout occurs.
75 class AckAlarm : public QuicAlarm::Delegate {
76 public:
77 explicit AckAlarm(QuicConnection* connection)
78 : connection_(connection) {
81 QuicTime OnAlarm() override {
82 connection_->SendAck();
83 return QuicTime::Zero();
86 private:
87 QuicConnection* connection_;
89 DISALLOW_COPY_AND_ASSIGN(AckAlarm);
92 // This alarm will be scheduled any time a data-bearing packet is sent out.
93 // When the alarm goes off, the connection checks to see if the oldest packets
94 // have been acked, and retransmit them if they have not.
95 class RetransmissionAlarm : public QuicAlarm::Delegate {
96 public:
97 explicit RetransmissionAlarm(QuicConnection* connection)
98 : connection_(connection) {
101 QuicTime OnAlarm() override {
102 connection_->OnRetransmissionTimeout();
103 return QuicTime::Zero();
106 private:
107 QuicConnection* connection_;
109 DISALLOW_COPY_AND_ASSIGN(RetransmissionAlarm);
112 // An alarm that is scheduled when the SentPacketManager requires a delay
113 // before sending packets and fires when the packet may be sent.
114 class SendAlarm : public QuicAlarm::Delegate {
115 public:
116 explicit SendAlarm(QuicConnection* connection)
117 : connection_(connection) {
120 QuicTime OnAlarm() override {
121 connection_->WriteIfNotBlocked();
122 // Never reschedule the alarm, since CanWrite does that.
123 return QuicTime::Zero();
126 private:
127 QuicConnection* connection_;
129 DISALLOW_COPY_AND_ASSIGN(SendAlarm);
132 class TimeoutAlarm : public QuicAlarm::Delegate {
133 public:
134 explicit TimeoutAlarm(QuicConnection* connection)
135 : connection_(connection) {
138 QuicTime OnAlarm() override {
139 connection_->CheckForTimeout();
140 // Never reschedule the alarm, since CheckForTimeout does that.
141 return QuicTime::Zero();
144 private:
145 QuicConnection* connection_;
147 DISALLOW_COPY_AND_ASSIGN(TimeoutAlarm);
150 class PingAlarm : public QuicAlarm::Delegate {
151 public:
152 explicit PingAlarm(QuicConnection* connection)
153 : connection_(connection) {
156 QuicTime OnAlarm() override {
157 connection_->SendPing();
158 return QuicTime::Zero();
161 private:
162 QuicConnection* connection_;
164 DISALLOW_COPY_AND_ASSIGN(PingAlarm);
167 // This alarm may be scheduled when an FEC protected packet is sent out.
168 class FecAlarm : public QuicAlarm::Delegate {
169 public:
170 explicit FecAlarm(QuicPacketGenerator* packet_generator)
171 : packet_generator_(packet_generator) {}
173 QuicTime OnAlarm() override {
174 packet_generator_->OnFecTimeout();
175 return QuicTime::Zero();
178 private:
179 QuicPacketGenerator* packet_generator_;
181 DISALLOW_COPY_AND_ASSIGN(FecAlarm);
184 } // namespace
186 QuicConnection::QueuedPacket::QueuedPacket(SerializedPacket packet,
187 EncryptionLevel level)
188 : serialized_packet(packet),
189 encryption_level(level),
190 transmission_type(NOT_RETRANSMISSION),
191 original_sequence_number(0) {
194 QuicConnection::QueuedPacket::QueuedPacket(
195 SerializedPacket packet,
196 EncryptionLevel level,
197 TransmissionType transmission_type,
198 QuicPacketSequenceNumber original_sequence_number)
199 : serialized_packet(packet),
200 encryption_level(level),
201 transmission_type(transmission_type),
202 original_sequence_number(original_sequence_number) {
205 #define ENDPOINT \
206 (perspective_ == Perspective::IS_SERVER ? "Server: " : "Client: ")
208 QuicConnection::QuicConnection(QuicConnectionId connection_id,
209 IPEndPoint address,
210 QuicConnectionHelperInterface* helper,
211 const PacketWriterFactory& writer_factory,
212 bool owns_writer,
213 Perspective perspective,
214 bool is_secure,
215 const QuicVersionVector& supported_versions)
216 : framer_(supported_versions,
217 helper->GetClock()->ApproximateNow(),
218 perspective),
219 helper_(helper),
220 writer_(writer_factory.Create(this)),
221 owns_writer_(owns_writer),
222 encryption_level_(ENCRYPTION_NONE),
223 has_forward_secure_encrypter_(false),
224 first_required_forward_secure_packet_(0),
225 clock_(helper->GetClock()),
226 random_generator_(helper->GetRandomGenerator()),
227 connection_id_(connection_id),
228 peer_address_(address),
229 migrating_peer_port_(0),
230 last_packet_decrypted_(false),
231 last_packet_revived_(false),
232 last_size_(0),
233 last_decrypted_packet_level_(ENCRYPTION_NONE),
234 largest_seen_packet_with_ack_(0),
235 largest_seen_packet_with_stop_waiting_(0),
236 max_undecryptable_packets_(0),
237 pending_version_negotiation_packet_(false),
238 silent_close_enabled_(false),
239 received_packet_manager_(&stats_),
240 ack_queued_(false),
241 num_packets_received_since_last_ack_sent_(0),
242 stop_waiting_count_(0),
243 ack_alarm_(helper->CreateAlarm(new AckAlarm(this))),
244 retransmission_alarm_(helper->CreateAlarm(new RetransmissionAlarm(this))),
245 send_alarm_(helper->CreateAlarm(new SendAlarm(this))),
246 resume_writes_alarm_(helper->CreateAlarm(new SendAlarm(this))),
247 timeout_alarm_(helper->CreateAlarm(new TimeoutAlarm(this))),
248 ping_alarm_(helper->CreateAlarm(new PingAlarm(this))),
249 visitor_(nullptr),
250 debug_visitor_(nullptr),
251 packet_generator_(connection_id_, &framer_, random_generator_, this),
252 fec_alarm_(helper->CreateAlarm(new FecAlarm(&packet_generator_))),
253 idle_network_timeout_(QuicTime::Delta::Infinite()),
254 overall_connection_timeout_(QuicTime::Delta::Infinite()),
255 time_of_last_received_packet_(clock_->ApproximateNow()),
256 time_of_last_sent_new_packet_(clock_->ApproximateNow()),
257 sequence_number_of_last_sent_packet_(0),
258 sent_packet_manager_(
259 perspective,
260 clock_,
261 &stats_,
262 FLAGS_quic_use_bbr_congestion_control ? kBBR : kCubic,
263 FLAGS_quic_use_time_loss_detection ? kTime : kNack,
264 is_secure),
265 version_negotiation_state_(START_NEGOTIATION),
266 perspective_(perspective),
267 connected_(true),
268 peer_ip_changed_(false),
269 peer_port_changed_(false),
270 self_ip_changed_(false),
271 self_port_changed_(false),
272 can_truncate_connection_ids_(true),
273 is_secure_(is_secure) {
274 DVLOG(1) << ENDPOINT << "Created connection with connection_id: "
275 << connection_id;
276 framer_.set_visitor(this);
277 framer_.set_received_entropy_calculator(&received_packet_manager_);
278 stats_.connection_creation_time = clock_->ApproximateNow();
279 sent_packet_manager_.set_network_change_visitor(this);
280 if (perspective_ == Perspective::IS_SERVER) {
281 set_max_packet_length(kDefaultServerMaxPacketSize);
285 QuicConnection::~QuicConnection() {
286 if (owns_writer_) {
287 delete writer_;
289 STLDeleteElements(&undecryptable_packets_);
290 STLDeleteValues(&group_map_);
291 for (QueuedPacketList::iterator it = queued_packets_.begin();
292 it != queued_packets_.end(); ++it) {
293 delete it->serialized_packet.retransmittable_frames;
294 delete it->serialized_packet.packet;
298 void QuicConnection::SetFromConfig(const QuicConfig& config) {
299 if (config.negotiated()) {
300 SetNetworkTimeouts(QuicTime::Delta::Infinite(),
301 config.IdleConnectionStateLifetime());
302 if (config.SilentClose()) {
303 silent_close_enabled_ = true;
305 } else {
306 SetNetworkTimeouts(config.max_time_before_crypto_handshake(),
307 config.max_idle_time_before_crypto_handshake());
310 sent_packet_manager_.SetFromConfig(config);
311 if (config.HasReceivedBytesForConnectionId() &&
312 can_truncate_connection_ids_) {
313 packet_generator_.SetConnectionIdLength(
314 config.ReceivedBytesForConnectionId());
316 max_undecryptable_packets_ = config.max_undecryptable_packets();
318 if (FLAGS_quic_send_fec_packet_only_on_fec_alarm &&
319 ((perspective_ == Perspective::IS_SERVER &&
320 config.HasReceivedConnectionOptions() &&
321 ContainsQuicTag(config.ReceivedConnectionOptions(), kFSPA)) ||
322 (perspective_ == Perspective::IS_CLIENT &&
323 config.HasSendConnectionOptions() &&
324 ContainsQuicTag(config.SendConnectionOptions(), kFSPA)))) {
325 packet_generator_.set_fec_send_policy(FecSendPolicy::FEC_ALARM_TRIGGER);
329 void QuicConnection::OnSendConnectionState(
330 const CachedNetworkParameters& cached_network_params) {
331 if (debug_visitor_ != nullptr) {
332 debug_visitor_->OnSendConnectionState(cached_network_params);
336 bool QuicConnection::ResumeConnectionState(
337 const CachedNetworkParameters& cached_network_params,
338 bool max_bandwidth_resumption) {
339 if (debug_visitor_ != nullptr) {
340 debug_visitor_->OnResumeConnectionState(cached_network_params);
342 return sent_packet_manager_.ResumeConnectionState(cached_network_params,
343 max_bandwidth_resumption);
346 void QuicConnection::SetNumOpenStreams(size_t num_streams) {
347 sent_packet_manager_.SetNumOpenStreams(num_streams);
350 bool QuicConnection::SelectMutualVersion(
351 const QuicVersionVector& available_versions) {
352 // Try to find the highest mutual version by iterating over supported
353 // versions, starting with the highest, and breaking out of the loop once we
354 // find a matching version in the provided available_versions vector.
355 const QuicVersionVector& supported_versions = framer_.supported_versions();
356 for (size_t i = 0; i < supported_versions.size(); ++i) {
357 const QuicVersion& version = supported_versions[i];
358 if (std::find(available_versions.begin(), available_versions.end(),
359 version) != available_versions.end()) {
360 framer_.set_version(version);
361 return true;
365 return false;
368 void QuicConnection::OnError(QuicFramer* framer) {
369 // Packets that we can not or have not decrypted are dropped.
370 // TODO(rch): add stats to measure this.
371 if (!connected_ || last_packet_decrypted_ == false) {
372 return;
374 SendConnectionCloseWithDetails(framer->error(), framer->detailed_error());
377 void QuicConnection::MaybeSetFecAlarm(
378 QuicPacketSequenceNumber sequence_number) {
379 if (fec_alarm_->IsSet()) {
380 return;
382 QuicTime::Delta timeout = packet_generator_.GetFecTimeout(sequence_number);
383 if (!timeout.IsInfinite()) {
384 fec_alarm_->Set(clock_->ApproximateNow().Add(timeout));
388 void QuicConnection::OnPacket() {
389 DCHECK(last_stream_frames_.empty() &&
390 last_ack_frames_.empty() &&
391 last_stop_waiting_frames_.empty() &&
392 last_rst_frames_.empty() &&
393 last_goaway_frames_.empty() &&
394 last_window_update_frames_.empty() &&
395 last_blocked_frames_.empty() &&
396 last_ping_frames_.empty() &&
397 last_close_frames_.empty());
398 last_packet_decrypted_ = false;
399 last_packet_revived_ = false;
402 void QuicConnection::OnPublicResetPacket(const QuicPublicResetPacket& packet) {
403 // Check that any public reset packet with a different connection ID that was
404 // routed to this QuicConnection has been redirected before control reaches
405 // here. (Check for a bug regression.)
406 DCHECK_EQ(connection_id_, packet.public_header.connection_id);
407 if (debug_visitor_ != nullptr) {
408 debug_visitor_->OnPublicResetPacket(packet);
410 CloseConnection(QUIC_PUBLIC_RESET, true);
412 DVLOG(1) << ENDPOINT << "Connection " << connection_id()
413 << " closed via QUIC_PUBLIC_RESET from peer.";
416 bool QuicConnection::OnProtocolVersionMismatch(QuicVersion received_version) {
417 DVLOG(1) << ENDPOINT << "Received packet with mismatched version "
418 << received_version;
419 // TODO(satyamshekhar): Implement no server state in this mode.
420 if (perspective_ == Perspective::IS_CLIENT) {
421 LOG(DFATAL) << ENDPOINT << "Framer called OnProtocolVersionMismatch. "
422 << "Closing connection.";
423 CloseConnection(QUIC_INTERNAL_ERROR, false);
424 return false;
426 DCHECK_NE(version(), received_version);
428 if (debug_visitor_ != nullptr) {
429 debug_visitor_->OnProtocolVersionMismatch(received_version);
432 switch (version_negotiation_state_) {
433 case START_NEGOTIATION:
434 if (!framer_.IsSupportedVersion(received_version)) {
435 SendVersionNegotiationPacket();
436 version_negotiation_state_ = NEGOTIATION_IN_PROGRESS;
437 return false;
439 break;
441 case NEGOTIATION_IN_PROGRESS:
442 if (!framer_.IsSupportedVersion(received_version)) {
443 SendVersionNegotiationPacket();
444 return false;
446 break;
448 case NEGOTIATED_VERSION:
449 // Might be old packets that were sent by the client before the version
450 // was negotiated. Drop these.
451 return false;
453 default:
454 DCHECK(false);
457 version_negotiation_state_ = NEGOTIATED_VERSION;
458 visitor_->OnSuccessfulVersionNegotiation(received_version);
459 if (debug_visitor_ != nullptr) {
460 debug_visitor_->OnSuccessfulVersionNegotiation(received_version);
462 DVLOG(1) << ENDPOINT << "version negotiated " << received_version;
464 // Store the new version.
465 framer_.set_version(received_version);
467 // TODO(satyamshekhar): Store the sequence number of this packet and close the
468 // connection if we ever received a packet with incorrect version and whose
469 // sequence number is greater.
470 return true;
473 // Handles version negotiation for client connection.
474 void QuicConnection::OnVersionNegotiationPacket(
475 const QuicVersionNegotiationPacket& packet) {
476 // Check that any public reset packet with a different connection ID that was
477 // routed to this QuicConnection has been redirected before control reaches
478 // here. (Check for a bug regression.)
479 DCHECK_EQ(connection_id_, packet.connection_id);
480 if (perspective_ == Perspective::IS_SERVER) {
481 LOG(DFATAL) << ENDPOINT << "Framer parsed VersionNegotiationPacket."
482 << " Closing connection.";
483 CloseConnection(QUIC_INTERNAL_ERROR, false);
484 return;
486 if (debug_visitor_ != nullptr) {
487 debug_visitor_->OnVersionNegotiationPacket(packet);
490 if (version_negotiation_state_ != START_NEGOTIATION) {
491 // Possibly a duplicate version negotiation packet.
492 return;
495 if (std::find(packet.versions.begin(),
496 packet.versions.end(), version()) !=
497 packet.versions.end()) {
498 DLOG(WARNING) << ENDPOINT << "The server already supports our version. "
499 << "It should have accepted our connection.";
500 // Just drop the connection.
501 CloseConnection(QUIC_INVALID_VERSION_NEGOTIATION_PACKET, false);
502 return;
505 if (!SelectMutualVersion(packet.versions)) {
506 SendConnectionCloseWithDetails(QUIC_INVALID_VERSION,
507 "no common version found");
508 return;
511 DVLOG(1) << ENDPOINT
512 << "Negotiated version: " << QuicVersionToString(version());
513 server_supported_versions_ = packet.versions;
514 version_negotiation_state_ = NEGOTIATION_IN_PROGRESS;
515 RetransmitUnackedPackets(ALL_UNACKED_RETRANSMISSION);
518 void QuicConnection::OnRevivedPacket() {
521 bool QuicConnection::OnUnauthenticatedPublicHeader(
522 const QuicPacketPublicHeader& header) {
523 if (header.connection_id == connection_id_) {
524 return true;
527 ++stats_.packets_dropped;
528 DVLOG(1) << ENDPOINT << "Ignoring packet from unexpected ConnectionId: "
529 << header.connection_id << " instead of " << connection_id_;
530 if (debug_visitor_ != nullptr) {
531 debug_visitor_->OnIncorrectConnectionId(header.connection_id);
533 // If this is a server, the dispatcher routes each packet to the
534 // QuicConnection responsible for the packet's connection ID. So if control
535 // arrives here and this is a server, the dispatcher must be malfunctioning.
536 DCHECK_NE(Perspective::IS_SERVER, perspective_);
537 return false;
540 bool QuicConnection::OnUnauthenticatedHeader(const QuicPacketHeader& header) {
541 // Check that any public reset packet with a different connection ID that was
542 // routed to this QuicConnection has been redirected before control reaches
543 // here.
544 DCHECK_EQ(connection_id_, header.public_header.connection_id);
545 return true;
548 void QuicConnection::OnDecryptedPacket(EncryptionLevel level) {
549 last_decrypted_packet_level_ = level;
550 last_packet_decrypted_ = true;
551 // If this packet was foward-secure encrypted and the forward-secure encrypter
552 // is not being used, start using it.
553 if (encryption_level_ != ENCRYPTION_FORWARD_SECURE &&
554 has_forward_secure_encrypter_ && level == ENCRYPTION_FORWARD_SECURE) {
555 SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
559 bool QuicConnection::OnPacketHeader(const QuicPacketHeader& header) {
560 if (debug_visitor_ != nullptr) {
561 debug_visitor_->OnPacketHeader(header);
564 if (!ProcessValidatedPacket()) {
565 return false;
568 // Will be decremented below if we fall through to return true.
569 ++stats_.packets_dropped;
571 if (!Near(header.packet_sequence_number,
572 last_header_.packet_sequence_number)) {
573 DVLOG(1) << ENDPOINT << "Packet " << header.packet_sequence_number
574 << " out of bounds. Discarding";
575 SendConnectionCloseWithDetails(QUIC_INVALID_PACKET_HEADER,
576 "Packet sequence number out of bounds");
577 return false;
580 // If this packet has already been seen, or the sender has told us that it
581 // will not be retransmitted, then stop processing the packet.
582 if (!received_packet_manager_.IsAwaitingPacket(
583 header.packet_sequence_number)) {
584 DVLOG(1) << ENDPOINT << "Packet " << header.packet_sequence_number
585 << " no longer being waited for. Discarding.";
586 if (debug_visitor_ != nullptr) {
587 debug_visitor_->OnDuplicatePacket(header.packet_sequence_number);
589 return false;
592 if (version_negotiation_state_ != NEGOTIATED_VERSION) {
593 if (perspective_ == Perspective::IS_SERVER) {
594 if (!header.public_header.version_flag) {
595 DLOG(WARNING) << ENDPOINT << "Packet " << header.packet_sequence_number
596 << " without version flag before version negotiated.";
597 // Packets should have the version flag till version negotiation is
598 // done.
599 CloseConnection(QUIC_INVALID_VERSION, false);
600 return false;
601 } else {
602 DCHECK_EQ(1u, header.public_header.versions.size());
603 DCHECK_EQ(header.public_header.versions[0], version());
604 version_negotiation_state_ = NEGOTIATED_VERSION;
605 visitor_->OnSuccessfulVersionNegotiation(version());
606 if (debug_visitor_ != nullptr) {
607 debug_visitor_->OnSuccessfulVersionNegotiation(version());
610 } else {
611 DCHECK(!header.public_header.version_flag);
612 // If the client gets a packet without the version flag from the server
613 // it should stop sending version since the version negotiation is done.
614 packet_generator_.StopSendingVersion();
615 version_negotiation_state_ = NEGOTIATED_VERSION;
616 visitor_->OnSuccessfulVersionNegotiation(version());
617 if (debug_visitor_ != nullptr) {
618 debug_visitor_->OnSuccessfulVersionNegotiation(version());
623 DCHECK_EQ(NEGOTIATED_VERSION, version_negotiation_state_);
625 --stats_.packets_dropped;
626 DVLOG(1) << ENDPOINT << "Received packet header: " << header;
627 last_header_ = header;
628 DCHECK(connected_);
629 return true;
632 void QuicConnection::OnFecProtectedPayload(StringPiece payload) {
633 DCHECK_EQ(IN_FEC_GROUP, last_header_.is_in_fec_group);
634 DCHECK_NE(0u, last_header_.fec_group);
635 QuicFecGroup* group = GetFecGroup();
636 if (group != nullptr) {
637 group->Update(last_decrypted_packet_level_, last_header_, payload);
641 bool QuicConnection::OnStreamFrame(const QuicStreamFrame& frame) {
642 DCHECK(connected_);
643 if (debug_visitor_ != nullptr) {
644 debug_visitor_->OnStreamFrame(frame);
646 if (frame.stream_id != kCryptoStreamId &&
647 last_decrypted_packet_level_ == ENCRYPTION_NONE) {
648 DLOG(WARNING) << ENDPOINT
649 << "Received an unencrypted data frame: closing connection";
650 SendConnectionClose(QUIC_UNENCRYPTED_STREAM_DATA);
651 return false;
653 last_stream_frames_.push_back(frame);
654 return true;
657 bool QuicConnection::OnAckFrame(const QuicAckFrame& incoming_ack) {
658 DCHECK(connected_);
659 if (debug_visitor_ != nullptr) {
660 debug_visitor_->OnAckFrame(incoming_ack);
662 DVLOG(1) << ENDPOINT << "OnAckFrame: " << incoming_ack;
664 if (last_header_.packet_sequence_number <= largest_seen_packet_with_ack_) {
665 DVLOG(1) << ENDPOINT << "Received an old ack frame: ignoring";
666 return true;
669 if (!ValidateAckFrame(incoming_ack)) {
670 SendConnectionClose(QUIC_INVALID_ACK_DATA);
671 return false;
674 last_ack_frames_.push_back(incoming_ack);
675 return connected_;
678 void QuicConnection::ProcessAckFrame(const QuicAckFrame& incoming_ack) {
679 largest_seen_packet_with_ack_ = last_header_.packet_sequence_number;
680 sent_packet_manager_.OnIncomingAck(incoming_ack,
681 time_of_last_received_packet_);
682 sent_entropy_manager_.ClearEntropyBefore(
683 sent_packet_manager_.least_packet_awaited_by_peer() - 1);
684 if (sent_packet_manager_.HasPendingRetransmissions()) {
685 WriteIfNotBlocked();
688 // Always reset the retransmission alarm when an ack comes in, since we now
689 // have a better estimate of the current rtt than when it was set.
690 QuicTime retransmission_time = sent_packet_manager_.GetRetransmissionTime();
691 retransmission_alarm_->Update(retransmission_time,
692 QuicTime::Delta::FromMilliseconds(1));
695 void QuicConnection::ProcessStopWaitingFrame(
696 const QuicStopWaitingFrame& stop_waiting) {
697 largest_seen_packet_with_stop_waiting_ = last_header_.packet_sequence_number;
698 received_packet_manager_.UpdatePacketInformationSentByPeer(stop_waiting);
699 // Possibly close any FecGroups which are now irrelevant.
700 CloseFecGroupsBefore(stop_waiting.least_unacked + 1);
703 bool QuicConnection::OnStopWaitingFrame(const QuicStopWaitingFrame& frame) {
704 DCHECK(connected_);
706 if (last_header_.packet_sequence_number <=
707 largest_seen_packet_with_stop_waiting_) {
708 DVLOG(1) << ENDPOINT << "Received an old stop waiting frame: ignoring";
709 return true;
712 if (!ValidateStopWaitingFrame(frame)) {
713 SendConnectionClose(QUIC_INVALID_STOP_WAITING_DATA);
714 return false;
717 if (debug_visitor_ != nullptr) {
718 debug_visitor_->OnStopWaitingFrame(frame);
721 last_stop_waiting_frames_.push_back(frame);
722 return connected_;
725 bool QuicConnection::OnPingFrame(const QuicPingFrame& frame) {
726 DCHECK(connected_);
727 if (debug_visitor_ != nullptr) {
728 debug_visitor_->OnPingFrame(frame);
730 last_ping_frames_.push_back(frame);
731 return true;
734 bool QuicConnection::ValidateAckFrame(const QuicAckFrame& incoming_ack) {
735 if (incoming_ack.largest_observed > packet_generator_.sequence_number()) {
736 DLOG(ERROR) << ENDPOINT << "Peer's observed unsent packet:"
737 << incoming_ack.largest_observed << " vs "
738 << packet_generator_.sequence_number();
739 // We got an error for data we have not sent. Error out.
740 return false;
743 if (incoming_ack.largest_observed < sent_packet_manager_.largest_observed()) {
744 DLOG(ERROR) << ENDPOINT << "Peer's largest_observed packet decreased:"
745 << incoming_ack.largest_observed << " vs "
746 << sent_packet_manager_.largest_observed();
747 // A new ack has a diminished largest_observed value. Error out.
748 // If this was an old packet, we wouldn't even have checked.
749 return false;
752 if (!incoming_ack.missing_packets.empty() &&
753 *incoming_ack.missing_packets.rbegin() > incoming_ack.largest_observed) {
754 DLOG(ERROR) << ENDPOINT << "Peer sent missing packet: "
755 << *incoming_ack.missing_packets.rbegin()
756 << " which is greater than largest observed: "
757 << incoming_ack.largest_observed;
758 return false;
761 if (!incoming_ack.missing_packets.empty() &&
762 *incoming_ack.missing_packets.begin() <
763 sent_packet_manager_.least_packet_awaited_by_peer()) {
764 DLOG(ERROR) << ENDPOINT << "Peer sent missing packet: "
765 << *incoming_ack.missing_packets.begin()
766 << " which is smaller than least_packet_awaited_by_peer_: "
767 << sent_packet_manager_.least_packet_awaited_by_peer();
768 return false;
771 if (!sent_entropy_manager_.IsValidEntropy(
772 incoming_ack.largest_observed,
773 incoming_ack.missing_packets,
774 incoming_ack.entropy_hash)) {
775 DLOG(ERROR) << ENDPOINT << "Peer sent invalid entropy.";
776 return false;
779 for (QuicPacketSequenceNumber revived_packet : incoming_ack.revived_packets) {
780 if (!ContainsKey(incoming_ack.missing_packets, revived_packet)) {
781 DLOG(ERROR) << ENDPOINT
782 << "Peer specified revived packet which was not missing.";
783 return false;
786 return true;
789 bool QuicConnection::ValidateStopWaitingFrame(
790 const QuicStopWaitingFrame& stop_waiting) {
791 if (stop_waiting.least_unacked <
792 received_packet_manager_.peer_least_packet_awaiting_ack()) {
793 DLOG(ERROR) << ENDPOINT << "Peer's sent low least_unacked: "
794 << stop_waiting.least_unacked << " vs "
795 << received_packet_manager_.peer_least_packet_awaiting_ack();
796 // We never process old ack frames, so this number should only increase.
797 return false;
800 if (stop_waiting.least_unacked >
801 last_header_.packet_sequence_number) {
802 DLOG(ERROR) << ENDPOINT << "Peer sent least_unacked:"
803 << stop_waiting.least_unacked
804 << " greater than the enclosing packet sequence number:"
805 << last_header_.packet_sequence_number;
806 return false;
809 return true;
812 void QuicConnection::OnFecData(const QuicFecData& fec) {
813 DCHECK_EQ(IN_FEC_GROUP, last_header_.is_in_fec_group);
814 DCHECK_NE(0u, last_header_.fec_group);
815 QuicFecGroup* group = GetFecGroup();
816 if (group != nullptr) {
817 group->UpdateFec(last_decrypted_packet_level_,
818 last_header_.packet_sequence_number, fec);
822 bool QuicConnection::OnRstStreamFrame(const QuicRstStreamFrame& frame) {
823 DCHECK(connected_);
824 if (debug_visitor_ != nullptr) {
825 debug_visitor_->OnRstStreamFrame(frame);
827 DVLOG(1) << ENDPOINT << "Stream reset with error "
828 << QuicUtils::StreamErrorToString(frame.error_code);
829 last_rst_frames_.push_back(frame);
830 return connected_;
833 bool QuicConnection::OnConnectionCloseFrame(
834 const QuicConnectionCloseFrame& frame) {
835 DCHECK(connected_);
836 if (debug_visitor_ != nullptr) {
837 debug_visitor_->OnConnectionCloseFrame(frame);
839 DVLOG(1) << ENDPOINT << "Connection " << connection_id()
840 << " closed with error "
841 << QuicUtils::ErrorToString(frame.error_code)
842 << " " << frame.error_details;
843 last_close_frames_.push_back(frame);
844 return connected_;
847 bool QuicConnection::OnGoAwayFrame(const QuicGoAwayFrame& frame) {
848 DCHECK(connected_);
849 if (debug_visitor_ != nullptr) {
850 debug_visitor_->OnGoAwayFrame(frame);
852 DVLOG(1) << ENDPOINT << "Go away received with error "
853 << QuicUtils::ErrorToString(frame.error_code)
854 << " and reason:" << frame.reason_phrase;
855 last_goaway_frames_.push_back(frame);
856 return connected_;
859 bool QuicConnection::OnWindowUpdateFrame(const QuicWindowUpdateFrame& frame) {
860 DCHECK(connected_);
861 if (debug_visitor_ != nullptr) {
862 debug_visitor_->OnWindowUpdateFrame(frame);
864 DVLOG(1) << ENDPOINT << "WindowUpdate received for stream: "
865 << frame.stream_id << " with byte offset: " << frame.byte_offset;
866 last_window_update_frames_.push_back(frame);
867 return connected_;
870 bool QuicConnection::OnBlockedFrame(const QuicBlockedFrame& frame) {
871 DCHECK(connected_);
872 if (debug_visitor_ != nullptr) {
873 debug_visitor_->OnBlockedFrame(frame);
875 DVLOG(1) << ENDPOINT << "Blocked frame received for stream: "
876 << frame.stream_id;
877 last_blocked_frames_.push_back(frame);
878 return connected_;
881 void QuicConnection::OnPacketComplete() {
882 // Don't do anything if this packet closed the connection.
883 if (!connected_) {
884 ClearLastFrames();
885 return;
888 DVLOG(1) << ENDPOINT << (last_packet_revived_ ? "Revived" : "Got")
889 << " packet " << last_header_.packet_sequence_number << " with " //
890 << last_stream_frames_.size() << " stream frames, " //
891 << last_ack_frames_.size() << " acks, " //
892 << last_stop_waiting_frames_.size() << " stop_waiting, " //
893 << last_rst_frames_.size() << " rsts, " //
894 << last_goaway_frames_.size() << " goaways, " //
895 << last_window_update_frames_.size() << " window updates, " //
896 << last_blocked_frames_.size() << " blocked, " //
897 << last_ping_frames_.size() << " pings, " //
898 << last_close_frames_.size() << " closes " //
899 << "for " << last_header_.public_header.connection_id;
901 ++num_packets_received_since_last_ack_sent_;
903 // Call MaybeQueueAck() before recording the received packet, since we want
904 // to trigger an ack if the newly received packet was previously missing.
905 MaybeQueueAck();
907 // Record received or revived packet to populate ack info correctly before
908 // processing stream frames, since the processing may result in a response
909 // packet with a bundled ack.
910 if (last_packet_revived_) {
911 received_packet_manager_.RecordPacketRevived(
912 last_header_.packet_sequence_number);
913 } else {
914 received_packet_manager_.RecordPacketReceived(
915 last_size_, last_header_, time_of_last_received_packet_);
918 if (!last_stream_frames_.empty()) {
919 visitor_->OnStreamFrames(last_stream_frames_);
920 if (!connected_ && FLAGS_quic_stop_early_2) {
921 return;
925 for (const QuicStreamFrame& stream_frame : last_stream_frames_) {
926 stats_.stream_bytes_received += stream_frame.data.size();
928 // Process window updates, blocked, stream resets, acks, then congestion
929 // feedback.
930 if (!last_window_update_frames_.empty()) {
931 visitor_->OnWindowUpdateFrames(last_window_update_frames_);
932 if (!connected_ && FLAGS_quic_stop_early_2) {
933 return;
936 if (!last_blocked_frames_.empty()) {
937 visitor_->OnBlockedFrames(last_blocked_frames_);
938 if (!connected_ && FLAGS_quic_stop_early_2) {
939 return;
942 for (size_t i = 0; i < last_goaway_frames_.size(); ++i) {
943 visitor_->OnGoAway(last_goaway_frames_[i]);
944 if (!connected_ && FLAGS_quic_stop_early_2) {
945 return;
948 for (size_t i = 0; i < last_rst_frames_.size(); ++i) {
949 visitor_->OnRstStream(last_rst_frames_[i]);
950 if (!connected_ && FLAGS_quic_stop_early_2) {
951 return;
954 for (size_t i = 0; i < last_ack_frames_.size(); ++i) {
955 ProcessAckFrame(last_ack_frames_[i]);
956 if (!connected_ && FLAGS_quic_stop_early_2) {
957 return;
960 for (size_t i = 0; i < last_stop_waiting_frames_.size(); ++i) {
961 ProcessStopWaitingFrame(last_stop_waiting_frames_[i]);
962 if (!connected_ && FLAGS_quic_stop_early_2) {
963 return;
966 if (!last_close_frames_.empty()) {
967 CloseConnection(last_close_frames_[0].error_code, true);
968 DCHECK(!connected_);
969 if (FLAGS_quic_stop_early_2) {
970 return;
974 // If there are new missing packets to report, send an ack immediately.
975 if ((!FLAGS_quic_dont_ack_acks || ShouldLastPacketInstigateAck()) &&
976 received_packet_manager_.HasNewMissingPackets()) {
977 ack_queued_ = true;
978 ack_alarm_->Cancel();
981 UpdateStopWaitingCount();
982 ClearLastFrames();
983 MaybeCloseIfTooManyOutstandingPackets();
986 void QuicConnection::MaybeQueueAck() {
987 // If the last packet is an ack, don't ack it.
988 if (!ShouldLastPacketInstigateAck()) {
989 return;
991 // If the incoming packet was missing, send an ack immediately.
992 ack_queued_ = received_packet_manager_.IsMissing(
993 last_header_.packet_sequence_number);
995 if (!ack_queued_) {
996 if (ack_alarm_->IsSet()) {
997 ack_queued_ = true;
998 } else {
999 ack_alarm_->Set(
1000 clock_->ApproximateNow().Add(sent_packet_manager_.DelayedAckTime()));
1001 DVLOG(1) << "Ack timer set; next packet or timer will trigger ACK.";
1005 if (ack_queued_) {
1006 ack_alarm_->Cancel();
1010 void QuicConnection::ClearLastFrames() {
1011 last_stream_frames_.clear();
1012 last_ack_frames_.clear();
1013 last_stop_waiting_frames_.clear();
1014 last_rst_frames_.clear();
1015 last_goaway_frames_.clear();
1016 last_window_update_frames_.clear();
1017 last_blocked_frames_.clear();
1018 last_ping_frames_.clear();
1019 last_close_frames_.clear();
1022 void QuicConnection::MaybeCloseIfTooManyOutstandingPackets() {
1023 // This occurs if we don't discard old packets we've sent fast enough.
1024 // It's possible largest observed is less than least unacked.
1025 if (sent_packet_manager_.largest_observed() >
1026 (sent_packet_manager_.GetLeastUnacked() + kMaxTrackedPackets)) {
1027 SendConnectionCloseWithDetails(
1028 QUIC_TOO_MANY_OUTSTANDING_SENT_PACKETS,
1029 StringPrintf("More than %" PRIu64 " outstanding.", kMaxTrackedPackets));
1031 // This occurs if there are received packet gaps and the peer does not raise
1032 // the least unacked fast enough.
1033 if (received_packet_manager_.NumTrackedPackets() > kMaxTrackedPackets) {
1034 SendConnectionCloseWithDetails(
1035 QUIC_TOO_MANY_OUTSTANDING_RECEIVED_PACKETS,
1036 StringPrintf("More than %" PRIu64 " outstanding.", kMaxTrackedPackets));
1040 void QuicConnection::PopulateAckFrame(QuicAckFrame* ack) {
1041 received_packet_manager_.UpdateReceivedPacketInfo(ack,
1042 clock_->ApproximateNow());
1045 void QuicConnection::PopulateStopWaitingFrame(
1046 QuicStopWaitingFrame* stop_waiting) {
1047 stop_waiting->least_unacked = GetLeastUnacked();
1048 stop_waiting->entropy_hash = sent_entropy_manager_.GetCumulativeEntropy(
1049 stop_waiting->least_unacked - 1);
1052 bool QuicConnection::ShouldLastPacketInstigateAck() const {
1053 if (!last_stream_frames_.empty() ||
1054 !last_goaway_frames_.empty() ||
1055 !last_rst_frames_.empty() ||
1056 !last_window_update_frames_.empty() ||
1057 !last_blocked_frames_.empty() ||
1058 !last_ping_frames_.empty()) {
1059 return true;
1062 if (!last_ack_frames_.empty() && last_ack_frames_.back().is_truncated) {
1063 return true;
1065 // Always send an ack every 20 packets in order to allow the peer to discard
1066 // information from the SentPacketManager and provide an RTT measurement.
1067 if (num_packets_received_since_last_ack_sent_ >=
1068 kMaxPacketsReceivedBeforeAckSend) {
1069 return true;
1071 return false;
1074 void QuicConnection::UpdateStopWaitingCount() {
1075 if (last_ack_frames_.empty()) {
1076 return;
1079 // If the peer is still waiting for a packet that we are no longer planning to
1080 // send, send an ack to raise the high water mark.
1081 if (!last_ack_frames_.back().missing_packets.empty() &&
1082 GetLeastUnacked() > *last_ack_frames_.back().missing_packets.begin()) {
1083 ++stop_waiting_count_;
1084 } else {
1085 stop_waiting_count_ = 0;
1089 QuicPacketSequenceNumber QuicConnection::GetLeastUnacked() const {
1090 return sent_packet_manager_.GetLeastUnacked();
1093 void QuicConnection::MaybeSendInResponseToPacket() {
1094 if (!connected_) {
1095 return;
1097 ScopedPacketBundler bundler(this, ack_queued_ ? SEND_ACK : NO_ACK);
1099 // Now that we have received an ack, we might be able to send packets which
1100 // are queued locally, or drain streams which are blocked.
1101 if (CanWrite(HAS_RETRANSMITTABLE_DATA)) {
1102 OnCanWrite();
1106 void QuicConnection::SendVersionNegotiationPacket() {
1107 // TODO(alyssar): implement zero server state negotiation.
1108 pending_version_negotiation_packet_ = true;
1109 if (writer_->IsWriteBlocked()) {
1110 visitor_->OnWriteBlocked();
1111 return;
1113 DVLOG(1) << ENDPOINT << "Sending version negotiation packet: {"
1114 << QuicVersionVectorToString(framer_.supported_versions()) << "}";
1115 scoped_ptr<QuicEncryptedPacket> version_packet(
1116 packet_generator_.SerializeVersionNegotiationPacket(
1117 framer_.supported_versions()));
1118 WriteResult result = writer_->WritePacket(
1119 version_packet->data(), version_packet->length(),
1120 self_address().address(), peer_address());
1122 if (result.status == WRITE_STATUS_ERROR) {
1123 // We can't send an error as the socket is presumably borked.
1124 CloseConnection(QUIC_PACKET_WRITE_ERROR, false);
1125 return;
1127 if (result.status == WRITE_STATUS_BLOCKED) {
1128 visitor_->OnWriteBlocked();
1129 if (writer_->IsWriteBlockedDataBuffered()) {
1130 pending_version_negotiation_packet_ = false;
1132 return;
1135 pending_version_negotiation_packet_ = false;
1138 QuicConsumedData QuicConnection::SendStreamData(
1139 QuicStreamId id,
1140 const QuicIOVector& iov,
1141 QuicStreamOffset offset,
1142 bool fin,
1143 FecProtection fec_protection,
1144 QuicAckNotifier::DelegateInterface* delegate) {
1145 if (!fin && iov.total_length == 0) {
1146 LOG(DFATAL) << "Attempt to send empty stream frame";
1147 return QuicConsumedData(0, false);
1150 // Opportunistically bundle an ack with every outgoing packet.
1151 // Particularly, we want to bundle with handshake packets since we don't know
1152 // which decrypter will be used on an ack packet following a handshake
1153 // packet (a handshake packet from client to server could result in a REJ or a
1154 // SHLO from the server, leading to two different decrypters at the server.)
1156 // TODO(jri): Note that ConsumeData may cause a response packet to be sent.
1157 // We may end up sending stale ack information if there are undecryptable
1158 // packets hanging around and/or there are revivable packets which may get
1159 // handled after this packet is sent. Change ScopedPacketBundler to do the
1160 // right thing: check ack_queued_, and then check undecryptable packets and
1161 // also if there is possibility of revival. Only bundle an ack if there's no
1162 // processing left that may cause received_info_ to change.
1163 ScopedPacketBundler ack_bundler(this, BUNDLE_PENDING_ACK);
1164 return packet_generator_.ConsumeData(id, iov, offset, fin, fec_protection,
1165 delegate);
1168 void QuicConnection::SendRstStream(QuicStreamId id,
1169 QuicRstStreamErrorCode error,
1170 QuicStreamOffset bytes_written) {
1171 // Opportunistically bundle an ack with this outgoing packet.
1172 ScopedPacketBundler ack_bundler(this, BUNDLE_PENDING_ACK);
1173 packet_generator_.AddControlFrame(QuicFrame(new QuicRstStreamFrame(
1174 id, AdjustErrorForVersion(error, version()), bytes_written)));
1176 sent_packet_manager_.CancelRetransmissionsForStream(id);
1177 // Remove all queued packets which only contain data for the reset stream.
1178 QueuedPacketList::iterator packet_iterator = queued_packets_.begin();
1179 while (packet_iterator != queued_packets_.end()) {
1180 RetransmittableFrames* retransmittable_frames =
1181 packet_iterator->serialized_packet.retransmittable_frames;
1182 if (!retransmittable_frames) {
1183 ++packet_iterator;
1184 continue;
1186 retransmittable_frames->RemoveFramesForStream(id);
1187 if (!retransmittable_frames->frames().empty()) {
1188 ++packet_iterator;
1189 continue;
1191 delete packet_iterator->serialized_packet.retransmittable_frames;
1192 delete packet_iterator->serialized_packet.packet;
1193 packet_iterator->serialized_packet.retransmittable_frames = nullptr;
1194 packet_iterator->serialized_packet.packet = nullptr;
1195 packet_iterator = queued_packets_.erase(packet_iterator);
1199 void QuicConnection::SendWindowUpdate(QuicStreamId id,
1200 QuicStreamOffset byte_offset) {
1201 // Opportunistically bundle an ack with this outgoing packet.
1202 ScopedPacketBundler ack_bundler(this, BUNDLE_PENDING_ACK);
1203 packet_generator_.AddControlFrame(
1204 QuicFrame(new QuicWindowUpdateFrame(id, byte_offset)));
1207 void QuicConnection::SendBlocked(QuicStreamId id) {
1208 // Opportunistically bundle an ack with this outgoing packet.
1209 ScopedPacketBundler ack_bundler(this, BUNDLE_PENDING_ACK);
1210 packet_generator_.AddControlFrame(QuicFrame(new QuicBlockedFrame(id)));
1213 const QuicConnectionStats& QuicConnection::GetStats() {
1214 const RttStats* rtt_stats = sent_packet_manager_.GetRttStats();
1216 // Update rtt and estimated bandwidth.
1217 QuicTime::Delta min_rtt = rtt_stats->min_rtt();
1218 if (min_rtt.IsZero()) {
1219 // If min RTT has not been set, use initial RTT instead.
1220 min_rtt = QuicTime::Delta::FromMicroseconds(rtt_stats->initial_rtt_us());
1222 stats_.min_rtt_us = min_rtt.ToMicroseconds();
1224 QuicTime::Delta srtt = rtt_stats->smoothed_rtt();
1225 if (srtt.IsZero()) {
1226 // If SRTT has not been set, use initial RTT instead.
1227 srtt = QuicTime::Delta::FromMicroseconds(rtt_stats->initial_rtt_us());
1229 stats_.srtt_us = srtt.ToMicroseconds();
1231 stats_.estimated_bandwidth = sent_packet_manager_.BandwidthEstimate();
1232 stats_.max_packet_size = packet_generator_.GetMaxPacketLength();
1233 return stats_;
1236 void QuicConnection::ProcessUdpPacket(const IPEndPoint& self_address,
1237 const IPEndPoint& peer_address,
1238 const QuicEncryptedPacket& packet) {
1239 if (!connected_) {
1240 return;
1242 // TODO(rtenneti): Remove ScopedTracker below once crbug.com/462789 is fixed.
1243 tracked_objects::ScopedTracker tracking_profile(
1244 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1245 "462789 QuicConnection::ProcessUdpPacket"));
1246 if (debug_visitor_ != nullptr) {
1247 debug_visitor_->OnPacketReceived(self_address, peer_address, packet);
1249 last_size_ = packet.length();
1251 CheckForAddressMigration(self_address, peer_address);
1253 stats_.bytes_received += packet.length();
1254 ++stats_.packets_received;
1256 if (!framer_.ProcessPacket(packet)) {
1257 // If we are unable to decrypt this packet, it might be
1258 // because the CHLO or SHLO packet was lost.
1259 if (framer_.error() == QUIC_DECRYPTION_FAILURE) {
1260 if (encryption_level_ != ENCRYPTION_FORWARD_SECURE &&
1261 undecryptable_packets_.size() < max_undecryptable_packets_) {
1262 QueueUndecryptablePacket(packet);
1263 } else if (debug_visitor_ != nullptr) {
1264 debug_visitor_->OnUndecryptablePacket();
1267 DVLOG(1) << ENDPOINT << "Unable to process packet. Last packet processed: "
1268 << last_header_.packet_sequence_number;
1269 return;
1272 ++stats_.packets_processed;
1273 MaybeProcessUndecryptablePackets();
1274 MaybeProcessRevivedPacket();
1275 MaybeSendInResponseToPacket();
1276 SetPingAlarm();
1279 void QuicConnection::CheckForAddressMigration(
1280 const IPEndPoint& self_address, const IPEndPoint& peer_address) {
1281 peer_ip_changed_ = false;
1282 peer_port_changed_ = false;
1283 self_ip_changed_ = false;
1284 self_port_changed_ = false;
1286 if (peer_address_.address().empty()) {
1287 peer_address_ = peer_address;
1289 if (self_address_.address().empty()) {
1290 self_address_ = self_address;
1293 if (!peer_address.address().empty() && !peer_address_.address().empty()) {
1294 peer_ip_changed_ = (peer_address.address() != peer_address_.address());
1295 peer_port_changed_ = (peer_address.port() != peer_address_.port());
1297 // Store in case we want to migrate connection in ProcessValidatedPacket.
1298 migrating_peer_port_ = peer_address.port();
1301 if (!self_address.address().empty() && !self_address_.address().empty()) {
1302 self_ip_changed_ = (self_address.address() != self_address_.address());
1303 self_port_changed_ = (self_address.port() != self_address_.port());
1307 void QuicConnection::OnCanWrite() {
1308 DCHECK(!writer_->IsWriteBlocked());
1310 WriteQueuedPackets();
1311 WritePendingRetransmissions();
1313 // Sending queued packets may have caused the socket to become write blocked,
1314 // or the congestion manager to prohibit sending. If we've sent everything
1315 // we had queued and we're still not blocked, let the visitor know it can
1316 // write more.
1317 if (!CanWrite(HAS_RETRANSMITTABLE_DATA)) {
1318 return;
1321 { // Limit the scope of the bundler. ACK inclusion happens elsewhere.
1322 ScopedPacketBundler bundler(this, NO_ACK);
1323 visitor_->OnCanWrite();
1326 // After the visitor writes, it may have caused the socket to become write
1327 // blocked or the congestion manager to prohibit sending, so check again.
1328 if (visitor_->WillingAndAbleToWrite() &&
1329 !resume_writes_alarm_->IsSet() &&
1330 CanWrite(HAS_RETRANSMITTABLE_DATA)) {
1331 // We're not write blocked, but some stream didn't write out all of its
1332 // bytes. Register for 'immediate' resumption so we'll keep writing after
1333 // other connections and events have had a chance to use the thread.
1334 resume_writes_alarm_->Set(clock_->ApproximateNow());
1338 void QuicConnection::WriteIfNotBlocked() {
1339 if (!writer_->IsWriteBlocked()) {
1340 OnCanWrite();
1344 bool QuicConnection::ProcessValidatedPacket() {
1345 if (peer_ip_changed_ || self_ip_changed_ || self_port_changed_) {
1346 SendConnectionCloseWithDetails(
1347 QUIC_ERROR_MIGRATING_ADDRESS,
1348 "Neither IP address migration, nor self port migration are supported.");
1349 return false;
1352 // Peer port migration is supported, do it now if port has changed.
1353 if (peer_port_changed_) {
1354 DVLOG(1) << ENDPOINT << "Peer's port changed from "
1355 << peer_address_.port() << " to " << migrating_peer_port_
1356 << ", migrating connection.";
1357 peer_address_ = IPEndPoint(peer_address_.address(), migrating_peer_port_);
1360 time_of_last_received_packet_ = clock_->Now();
1361 DVLOG(1) << ENDPOINT << "time of last received packet: "
1362 << time_of_last_received_packet_.ToDebuggingValue();
1364 if (perspective_ == Perspective::IS_SERVER &&
1365 encryption_level_ == ENCRYPTION_NONE &&
1366 last_size_ > packet_generator_.GetMaxPacketLength()) {
1367 set_max_packet_length(last_size_);
1369 return true;
1372 void QuicConnection::WriteQueuedPackets() {
1373 DCHECK(!writer_->IsWriteBlocked());
1375 if (pending_version_negotiation_packet_) {
1376 SendVersionNegotiationPacket();
1379 QueuedPacketList::iterator packet_iterator = queued_packets_.begin();
1380 while (packet_iterator != queued_packets_.end() &&
1381 WritePacket(&(*packet_iterator))) {
1382 packet_iterator = queued_packets_.erase(packet_iterator);
1386 void QuicConnection::WritePendingRetransmissions() {
1387 // Keep writing as long as there's a pending retransmission which can be
1388 // written.
1389 while (sent_packet_manager_.HasPendingRetransmissions()) {
1390 const QuicSentPacketManager::PendingRetransmission pending =
1391 sent_packet_manager_.NextPendingRetransmission();
1392 if (!CanWrite(HAS_RETRANSMITTABLE_DATA)) {
1393 break;
1396 // Re-packetize the frames with a new sequence number for retransmission.
1397 // Retransmitted data packets do not use FEC, even when it's enabled.
1398 // Retransmitted packets use the same sequence number length as the
1399 // original.
1400 // Flush the packet generator before making a new packet.
1401 // TODO(ianswett): Implement ReserializeAllFrames as a separate path that
1402 // does not require the creator to be flushed.
1403 packet_generator_.FlushAllQueuedFrames();
1404 char buffer[kMaxPacketSize];
1405 SerializedPacket serialized_packet = packet_generator_.ReserializeAllFrames(
1406 pending.retransmittable_frames, pending.sequence_number_length, buffer,
1407 kMaxPacketSize);
1408 if (serialized_packet.packet == nullptr) {
1409 // We failed to serialize the packet, so close the connection.
1410 // CloseConnection does not send close packet, so no infinite loop here.
1411 CloseConnection(QUIC_ENCRYPTION_FAILURE, false);
1412 return;
1415 DVLOG(1) << ENDPOINT << "Retransmitting " << pending.sequence_number
1416 << " as " << serialized_packet.sequence_number;
1417 SendOrQueuePacket(
1418 QueuedPacket(serialized_packet,
1419 pending.retransmittable_frames.encryption_level(),
1420 pending.transmission_type,
1421 pending.sequence_number));
1425 void QuicConnection::RetransmitUnackedPackets(
1426 TransmissionType retransmission_type) {
1427 sent_packet_manager_.RetransmitUnackedPackets(retransmission_type);
1429 WriteIfNotBlocked();
1432 void QuicConnection::NeuterUnencryptedPackets() {
1433 sent_packet_manager_.NeuterUnencryptedPackets();
1434 // This may have changed the retransmission timer, so re-arm it.
1435 QuicTime retransmission_time = sent_packet_manager_.GetRetransmissionTime();
1436 retransmission_alarm_->Update(retransmission_time,
1437 QuicTime::Delta::FromMilliseconds(1));
1440 bool QuicConnection::ShouldGeneratePacket(
1441 HasRetransmittableData retransmittable,
1442 IsHandshake handshake) {
1443 // We should serialize handshake packets immediately to ensure that they
1444 // end up sent at the right encryption level.
1445 if (handshake == IS_HANDSHAKE) {
1446 return true;
1449 return CanWrite(retransmittable);
1452 bool QuicConnection::CanWrite(HasRetransmittableData retransmittable) {
1453 if (!connected_) {
1454 return false;
1457 if (writer_->IsWriteBlocked()) {
1458 visitor_->OnWriteBlocked();
1459 return false;
1462 QuicTime now = clock_->Now();
1463 QuicTime::Delta delay = sent_packet_manager_.TimeUntilSend(
1464 now, retransmittable);
1465 if (delay.IsInfinite()) {
1466 send_alarm_->Cancel();
1467 return false;
1470 // If the scheduler requires a delay, then we can not send this packet now.
1471 if (!delay.IsZero()) {
1472 send_alarm_->Update(now.Add(delay), QuicTime::Delta::FromMilliseconds(1));
1473 DVLOG(1) << ENDPOINT << "Delaying sending " << delay.ToMilliseconds()
1474 << "ms";
1475 return false;
1477 send_alarm_->Cancel();
1478 return true;
1481 bool QuicConnection::WritePacket(QueuedPacket* packet) {
1482 if (!WritePacketInner(packet)) {
1483 return false;
1485 delete packet->serialized_packet.retransmittable_frames;
1486 delete packet->serialized_packet.packet;
1487 packet->serialized_packet.retransmittable_frames = nullptr;
1488 packet->serialized_packet.packet = nullptr;
1489 return true;
1492 bool QuicConnection::WritePacketInner(QueuedPacket* packet) {
1493 if (ShouldDiscardPacket(*packet)) {
1494 ++stats_.packets_discarded;
1495 return true;
1497 // Connection close packets are encrypted and saved, so don't exit early.
1498 const bool is_connection_close = IsConnectionClose(*packet);
1499 if (writer_->IsWriteBlocked() && !is_connection_close) {
1500 return false;
1503 QuicPacketSequenceNumber sequence_number =
1504 packet->serialized_packet.sequence_number;
1505 DCHECK_LE(sequence_number_of_last_sent_packet_, sequence_number);
1506 sequence_number_of_last_sent_packet_ = sequence_number;
1508 QuicEncryptedPacket* encrypted = packet->serialized_packet.packet;
1509 // Connection close packets are eventually owned by TimeWaitListManager.
1510 // Others are deleted at the end of this call.
1511 if (is_connection_close) {
1512 DCHECK(connection_close_packet_.get() == nullptr);
1513 // Clone the packet so it's owned in the future.
1514 connection_close_packet_.reset(encrypted->Clone());
1515 // This assures we won't try to write *forced* packets when blocked.
1516 // Return true to stop processing.
1517 if (writer_->IsWriteBlocked()) {
1518 visitor_->OnWriteBlocked();
1519 return true;
1523 if (!FLAGS_quic_allow_oversized_packets_for_test) {
1524 DCHECK_LE(encrypted->length(), kMaxPacketSize);
1526 DCHECK_LE(encrypted->length(), packet_generator_.GetMaxPacketLength());
1527 DVLOG(1) << ENDPOINT << "Sending packet " << sequence_number << " : "
1528 << (packet->serialized_packet.is_fec_packet
1529 ? "FEC "
1530 : (IsRetransmittable(*packet) == HAS_RETRANSMITTABLE_DATA
1531 ? "data bearing "
1532 : " ack only ")) << ", encryption level: "
1533 << QuicUtils::EncryptionLevelToString(packet->encryption_level)
1534 << ", encrypted length:" << encrypted->length();
1535 DVLOG(2) << ENDPOINT << "packet(" << sequence_number << "): " << std::endl
1536 << QuicUtils::StringToHexASCIIDump(encrypted->AsStringPiece());
1538 // Measure the RTT from before the write begins to avoid underestimating the
1539 // min_rtt_, especially in cases where the thread blocks or gets swapped out
1540 // during the WritePacket below.
1541 QuicTime packet_send_time = clock_->Now();
1542 WriteResult result = writer_->WritePacket(encrypted->data(),
1543 encrypted->length(),
1544 self_address().address(),
1545 peer_address());
1546 if (result.error_code == ERR_IO_PENDING) {
1547 DCHECK_EQ(WRITE_STATUS_BLOCKED, result.status);
1550 if (result.status == WRITE_STATUS_BLOCKED) {
1551 visitor_->OnWriteBlocked();
1552 // If the socket buffers the the data, then the packet should not
1553 // be queued and sent again, which would result in an unnecessary
1554 // duplicate packet being sent. The helper must call OnCanWrite
1555 // when the write completes, and OnWriteError if an error occurs.
1556 if (!writer_->IsWriteBlockedDataBuffered()) {
1557 return false;
1560 if (result.status != WRITE_STATUS_ERROR && debug_visitor_ != nullptr) {
1561 // Pass the write result to the visitor.
1562 debug_visitor_->OnPacketSent(packet->serialized_packet,
1563 packet->original_sequence_number,
1564 packet->encryption_level,
1565 packet->transmission_type,
1566 *encrypted,
1567 packet_send_time);
1569 if (packet->transmission_type == NOT_RETRANSMISSION) {
1570 time_of_last_sent_new_packet_ = packet_send_time;
1572 SetPingAlarm();
1573 MaybeSetFecAlarm(sequence_number);
1574 DVLOG(1) << ENDPOINT << "time we began writing last sent packet: "
1575 << packet_send_time.ToDebuggingValue();
1577 // TODO(ianswett): Change the sequence number length and other packet creator
1578 // options by a more explicit API than setting a struct value directly,
1579 // perhaps via the NetworkChangeVisitor.
1580 packet_generator_.UpdateSequenceNumberLength(
1581 sent_packet_manager_.least_packet_awaited_by_peer(),
1582 sent_packet_manager_.EstimateMaxPacketsInFlight(max_packet_length()));
1584 bool reset_retransmission_alarm = sent_packet_manager_.OnPacketSent(
1585 &packet->serialized_packet,
1586 packet->original_sequence_number,
1587 packet_send_time,
1588 encrypted->length(),
1589 packet->transmission_type,
1590 IsRetransmittable(*packet));
1592 if (reset_retransmission_alarm || !retransmission_alarm_->IsSet()) {
1593 retransmission_alarm_->Update(sent_packet_manager_.GetRetransmissionTime(),
1594 QuicTime::Delta::FromMilliseconds(1));
1597 stats_.bytes_sent += result.bytes_written;
1598 ++stats_.packets_sent;
1599 if (packet->transmission_type != NOT_RETRANSMISSION) {
1600 stats_.bytes_retransmitted += result.bytes_written;
1601 ++stats_.packets_retransmitted;
1604 if (result.status == WRITE_STATUS_ERROR) {
1605 OnWriteError(result.error_code);
1606 DLOG(ERROR) << ENDPOINT << "failed writing " << encrypted->length()
1607 << "bytes "
1608 << " from host " << self_address().ToStringWithoutPort()
1609 << " to address " << peer_address().ToString();
1610 return false;
1613 return true;
1616 bool QuicConnection::ShouldDiscardPacket(const QueuedPacket& packet) {
1617 if (!connected_) {
1618 DVLOG(1) << ENDPOINT
1619 << "Not sending packet as connection is disconnected.";
1620 return true;
1623 QuicPacketSequenceNumber sequence_number =
1624 packet.serialized_packet.sequence_number;
1625 if (encryption_level_ == ENCRYPTION_FORWARD_SECURE &&
1626 packet.encryption_level == ENCRYPTION_NONE) {
1627 // Drop packets that are NULL encrypted since the peer won't accept them
1628 // anymore.
1629 DVLOG(1) << ENDPOINT << "Dropping NULL encrypted packet: "
1630 << sequence_number << " since the connection is forward secure.";
1631 return true;
1634 // If a retransmission has been acked before sending, don't send it.
1635 // This occurs if a packet gets serialized, queued, then discarded.
1636 if (packet.transmission_type != NOT_RETRANSMISSION &&
1637 (!sent_packet_manager_.IsUnacked(packet.original_sequence_number) ||
1638 !sent_packet_manager_.HasRetransmittableFrames(
1639 packet.original_sequence_number))) {
1640 DVLOG(1) << ENDPOINT << "Dropping unacked packet: " << sequence_number
1641 << " A previous transmission was acked while write blocked.";
1642 return true;
1645 return false;
1648 void QuicConnection::OnWriteError(int error_code) {
1649 DVLOG(1) << ENDPOINT << "Write failed with error: " << error_code
1650 << " (" << ErrorToString(error_code) << ")";
1651 // We can't send an error as the socket is presumably borked.
1652 CloseConnection(QUIC_PACKET_WRITE_ERROR, false);
1655 void QuicConnection::OnSerializedPacket(
1656 const SerializedPacket& serialized_packet) {
1657 if (serialized_packet.packet == nullptr) {
1658 // We failed to serialize the packet, so close the connection.
1659 // CloseConnection does not send close packet, so no infinite loop here.
1660 CloseConnection(QUIC_ENCRYPTION_FAILURE, false);
1661 return;
1663 if (serialized_packet.retransmittable_frames) {
1664 sent_packet_manager_.OnSerializedPacket(serialized_packet);
1666 if (serialized_packet.is_fec_packet && fec_alarm_->IsSet()) {
1667 // If an FEC packet is serialized with the FEC alarm set, cancel the alarm.
1668 fec_alarm_->Cancel();
1670 SendOrQueuePacket(QueuedPacket(serialized_packet, encryption_level_));
1673 void QuicConnection::OnResetFecGroup() {
1674 if (!fec_alarm_->IsSet()) {
1675 return;
1677 // If an FEC Group is closed with the FEC alarm set, cancel the alarm.
1678 fec_alarm_->Cancel();
1681 void QuicConnection::OnCongestionWindowChange() {
1682 packet_generator_.OnCongestionWindowChange(
1683 sent_packet_manager_.EstimateMaxPacketsInFlight(max_packet_length()));
1684 visitor_->OnCongestionWindowChange(clock_->ApproximateNow());
1687 void QuicConnection::OnRttChange() {
1688 // Uses the connection's smoothed RTT. If zero, uses initial_rtt.
1689 QuicTime::Delta rtt = sent_packet_manager_.GetRttStats()->smoothed_rtt();
1690 if (rtt.IsZero()) {
1691 rtt = QuicTime::Delta::FromMicroseconds(
1692 sent_packet_manager_.GetRttStats()->initial_rtt_us());
1694 packet_generator_.OnRttChange(rtt);
1697 void QuicConnection::OnHandshakeComplete() {
1698 sent_packet_manager_.SetHandshakeConfirmed();
1699 // The client should immediately ack the SHLO to confirm the handshake is
1700 // complete with the server.
1701 if (perspective_ == Perspective::IS_CLIENT && !ack_queued_) {
1702 ack_alarm_->Cancel();
1703 ack_alarm_->Set(clock_->ApproximateNow());
1707 void QuicConnection::SendOrQueuePacket(QueuedPacket packet) {
1708 // The caller of this function is responsible for checking CanWrite().
1709 if (packet.serialized_packet.packet == nullptr) {
1710 LOG(DFATAL)
1711 << "packet.serialized_packet.packet == nullptr in to SendOrQueuePacket";
1712 return;
1715 sent_entropy_manager_.RecordPacketEntropyHash(
1716 packet.serialized_packet.sequence_number,
1717 packet.serialized_packet.entropy_hash);
1718 if (!WritePacket(&packet)) {
1719 // Take ownership of the underlying encrypted packet.
1720 if (!packet.serialized_packet.packet->owns_buffer()) {
1721 scoped_ptr<QuicEncryptedPacket> encrypted_deleter(
1722 packet.serialized_packet.packet);
1723 packet.serialized_packet.packet =
1724 packet.serialized_packet.packet->Clone();
1726 queued_packets_.push_back(packet);
1729 // If a forward-secure encrypter is available but is not being used and the
1730 // next sequence number is the first packet which requires
1731 // forward security, start using the forward-secure encrypter.
1732 if (encryption_level_ != ENCRYPTION_FORWARD_SECURE &&
1733 has_forward_secure_encrypter_ &&
1734 packet.serialized_packet.sequence_number >=
1735 first_required_forward_secure_packet_ - 1) {
1736 SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
1740 void QuicConnection::SendPing() {
1741 if (retransmission_alarm_->IsSet()) {
1742 return;
1744 packet_generator_.AddControlFrame(QuicFrame(new QuicPingFrame));
1747 void QuicConnection::SendAck() {
1748 ack_alarm_->Cancel();
1749 ack_queued_ = false;
1750 stop_waiting_count_ = 0;
1751 num_packets_received_since_last_ack_sent_ = 0;
1753 packet_generator_.SetShouldSendAck(true);
1756 void QuicConnection::OnRetransmissionTimeout() {
1757 if (!sent_packet_manager_.HasUnackedPackets()) {
1758 return;
1761 sent_packet_manager_.OnRetransmissionTimeout();
1762 WriteIfNotBlocked();
1764 // A write failure can result in the connection being closed, don't attempt to
1765 // write further packets, or to set alarms.
1766 if (!connected_) {
1767 return;
1770 // In the TLP case, the SentPacketManager gives the connection the opportunity
1771 // to send new data before retransmitting.
1772 if (sent_packet_manager_.MaybeRetransmitTailLossProbe()) {
1773 // Send the pending retransmission now that it's been queued.
1774 WriteIfNotBlocked();
1777 // Ensure the retransmission alarm is always set if there are unacked packets
1778 // and nothing waiting to be sent.
1779 if (!HasQueuedData() && !retransmission_alarm_->IsSet()) {
1780 QuicTime rto_timeout = sent_packet_manager_.GetRetransmissionTime();
1781 if (rto_timeout.IsInitialized()) {
1782 retransmission_alarm_->Set(rto_timeout);
1787 void QuicConnection::SetEncrypter(EncryptionLevel level,
1788 QuicEncrypter* encrypter) {
1789 packet_generator_.SetEncrypter(level, encrypter);
1790 if (level == ENCRYPTION_FORWARD_SECURE) {
1791 has_forward_secure_encrypter_ = true;
1792 first_required_forward_secure_packet_ =
1793 sequence_number_of_last_sent_packet_ +
1794 // 3 times the current congestion window (in slow start) should cover
1795 // about two full round trips worth of packets, which should be
1796 // sufficient.
1797 3 * sent_packet_manager_.EstimateMaxPacketsInFlight(
1798 max_packet_length());
1802 void QuicConnection::SetDefaultEncryptionLevel(EncryptionLevel level) {
1803 encryption_level_ = level;
1804 packet_generator_.set_encryption_level(level);
1807 void QuicConnection::SetDecrypter(EncryptionLevel level,
1808 QuicDecrypter* decrypter) {
1809 framer_.SetDecrypter(level, decrypter);
1812 void QuicConnection::SetAlternativeDecrypter(EncryptionLevel level,
1813 QuicDecrypter* decrypter,
1814 bool latch_once_used) {
1815 framer_.SetAlternativeDecrypter(level, decrypter, latch_once_used);
1818 const QuicDecrypter* QuicConnection::decrypter() const {
1819 return framer_.decrypter();
1822 const QuicDecrypter* QuicConnection::alternative_decrypter() const {
1823 return framer_.alternative_decrypter();
1826 void QuicConnection::QueueUndecryptablePacket(
1827 const QuicEncryptedPacket& packet) {
1828 DVLOG(1) << ENDPOINT << "Queueing undecryptable packet.";
1829 undecryptable_packets_.push_back(packet.Clone());
1832 void QuicConnection::MaybeProcessUndecryptablePackets() {
1833 if (undecryptable_packets_.empty() || encryption_level_ == ENCRYPTION_NONE) {
1834 return;
1837 while (connected_ && !undecryptable_packets_.empty()) {
1838 DVLOG(1) << ENDPOINT << "Attempting to process undecryptable packet";
1839 QuicEncryptedPacket* packet = undecryptable_packets_.front();
1840 if (!framer_.ProcessPacket(*packet) &&
1841 framer_.error() == QUIC_DECRYPTION_FAILURE) {
1842 DVLOG(1) << ENDPOINT << "Unable to process undecryptable packet...";
1843 break;
1845 DVLOG(1) << ENDPOINT << "Processed undecryptable packet!";
1846 ++stats_.packets_processed;
1847 delete packet;
1848 undecryptable_packets_.pop_front();
1851 // Once forward secure encryption is in use, there will be no
1852 // new keys installed and hence any undecryptable packets will
1853 // never be able to be decrypted.
1854 if (encryption_level_ == ENCRYPTION_FORWARD_SECURE) {
1855 if (debug_visitor_ != nullptr) {
1856 // TODO(rtenneti): perhaps more efficient to pass the number of
1857 // undecryptable packets as the argument to OnUndecryptablePacket so that
1858 // we just need to call OnUndecryptablePacket once?
1859 for (size_t i = 0; i < undecryptable_packets_.size(); ++i) {
1860 debug_visitor_->OnUndecryptablePacket();
1863 STLDeleteElements(&undecryptable_packets_);
1867 void QuicConnection::MaybeProcessRevivedPacket() {
1868 QuicFecGroup* group = GetFecGroup();
1869 if (!connected_ || group == nullptr || !group->CanRevive()) {
1870 return;
1872 QuicPacketHeader revived_header;
1873 char revived_payload[kMaxPacketSize];
1874 size_t len = group->Revive(&revived_header, revived_payload, kMaxPacketSize);
1875 revived_header.public_header.connection_id = connection_id_;
1876 revived_header.public_header.connection_id_length =
1877 last_header_.public_header.connection_id_length;
1878 revived_header.public_header.version_flag = false;
1879 revived_header.public_header.reset_flag = false;
1880 revived_header.public_header.sequence_number_length =
1881 last_header_.public_header.sequence_number_length;
1882 revived_header.fec_flag = false;
1883 revived_header.is_in_fec_group = NOT_IN_FEC_GROUP;
1884 revived_header.fec_group = 0;
1885 group_map_.erase(last_header_.fec_group);
1886 last_decrypted_packet_level_ = group->effective_encryption_level();
1887 DCHECK_LT(last_decrypted_packet_level_, NUM_ENCRYPTION_LEVELS);
1888 delete group;
1890 last_packet_revived_ = true;
1891 if (debug_visitor_ != nullptr) {
1892 debug_visitor_->OnRevivedPacket(revived_header,
1893 StringPiece(revived_payload, len));
1896 ++stats_.packets_revived;
1897 framer_.ProcessRevivedPacket(&revived_header,
1898 StringPiece(revived_payload, len));
1901 QuicFecGroup* QuicConnection::GetFecGroup() {
1902 QuicFecGroupNumber fec_group_num = last_header_.fec_group;
1903 if (fec_group_num == 0) {
1904 return nullptr;
1906 if (!ContainsKey(group_map_, fec_group_num)) {
1907 if (group_map_.size() >= kMaxFecGroups) { // Too many groups
1908 if (fec_group_num < group_map_.begin()->first) {
1909 // The group being requested is a group we've seen before and deleted.
1910 // Don't recreate it.
1911 return nullptr;
1913 // Clear the lowest group number.
1914 delete group_map_.begin()->second;
1915 group_map_.erase(group_map_.begin());
1917 group_map_[fec_group_num] = new QuicFecGroup();
1919 return group_map_[fec_group_num];
1922 void QuicConnection::SendConnectionClose(QuicErrorCode error) {
1923 SendConnectionCloseWithDetails(error, string());
1926 void QuicConnection::SendConnectionCloseWithDetails(QuicErrorCode error,
1927 const string& details) {
1928 // If we're write blocked, WritePacket() will not send, but will capture the
1929 // serialized packet.
1930 SendConnectionClosePacket(error, details);
1931 CloseConnection(error, false);
1934 void QuicConnection::SendConnectionClosePacket(QuicErrorCode error,
1935 const string& details) {
1936 DVLOG(1) << ENDPOINT << "Force closing " << connection_id()
1937 << " with error " << QuicUtils::ErrorToString(error)
1938 << " (" << error << ") " << details;
1939 // Don't send explicit connection close packets for timeouts.
1940 // This is particularly important on mobile, where connections are short.
1941 if (silent_close_enabled_ &&
1942 error == QuicErrorCode::QUIC_CONNECTION_TIMED_OUT) {
1943 return;
1945 ScopedPacketBundler ack_bundler(this, SEND_ACK);
1946 QuicConnectionCloseFrame* frame = new QuicConnectionCloseFrame();
1947 frame->error_code = error;
1948 frame->error_details = details;
1949 packet_generator_.AddControlFrame(QuicFrame(frame));
1950 packet_generator_.FlushAllQueuedFrames();
1953 void QuicConnection::CloseConnection(QuicErrorCode error, bool from_peer) {
1954 if (!connected_) {
1955 DVLOG(1) << "Connection is already closed.";
1956 return;
1958 connected_ = false;
1959 if (debug_visitor_ != nullptr) {
1960 debug_visitor_->OnConnectionClosed(error, from_peer);
1962 DCHECK(visitor_ != nullptr);
1963 visitor_->OnConnectionClosed(error, from_peer);
1964 // Cancel the alarms so they don't trigger any action now that the
1965 // connection is closed.
1966 ack_alarm_->Cancel();
1967 ping_alarm_->Cancel();
1968 fec_alarm_->Cancel();
1969 resume_writes_alarm_->Cancel();
1970 retransmission_alarm_->Cancel();
1971 send_alarm_->Cancel();
1972 timeout_alarm_->Cancel();
1975 void QuicConnection::SendGoAway(QuicErrorCode error,
1976 QuicStreamId last_good_stream_id,
1977 const string& reason) {
1978 DVLOG(1) << ENDPOINT << "Going away with error "
1979 << QuicUtils::ErrorToString(error)
1980 << " (" << error << ")";
1982 // Opportunistically bundle an ack with this outgoing packet.
1983 ScopedPacketBundler ack_bundler(this, BUNDLE_PENDING_ACK);
1984 packet_generator_.AddControlFrame(
1985 QuicFrame(new QuicGoAwayFrame(error, last_good_stream_id, reason)));
1988 void QuicConnection::CloseFecGroupsBefore(
1989 QuicPacketSequenceNumber sequence_number) {
1990 FecGroupMap::iterator it = group_map_.begin();
1991 while (it != group_map_.end()) {
1992 // If this is the current group or the group doesn't protect this packet
1993 // we can ignore it.
1994 if (last_header_.fec_group == it->first ||
1995 !it->second->ProtectsPacketsBefore(sequence_number)) {
1996 ++it;
1997 continue;
1999 QuicFecGroup* fec_group = it->second;
2000 DCHECK(!fec_group->CanRevive());
2001 FecGroupMap::iterator next = it;
2002 ++next;
2003 group_map_.erase(it);
2004 delete fec_group;
2005 it = next;
2009 QuicByteCount QuicConnection::max_packet_length() const {
2010 return packet_generator_.GetMaxPacketLength();
2013 void QuicConnection::set_max_packet_length(QuicByteCount length) {
2014 return packet_generator_.SetMaxPacketLength(length, /*force=*/false);
2017 bool QuicConnection::HasQueuedData() const {
2018 return pending_version_negotiation_packet_ ||
2019 !queued_packets_.empty() || packet_generator_.HasQueuedFrames();
2022 bool QuicConnection::CanWriteStreamData() {
2023 // Don't write stream data if there are negotiation or queued data packets
2024 // to send. Otherwise, continue and bundle as many frames as possible.
2025 if (pending_version_negotiation_packet_ || !queued_packets_.empty()) {
2026 return false;
2029 IsHandshake pending_handshake = visitor_->HasPendingHandshake() ?
2030 IS_HANDSHAKE : NOT_HANDSHAKE;
2031 // Sending queued packets may have caused the socket to become write blocked,
2032 // or the congestion manager to prohibit sending. If we've sent everything
2033 // we had queued and we're still not blocked, let the visitor know it can
2034 // write more.
2035 return ShouldGeneratePacket(HAS_RETRANSMITTABLE_DATA, pending_handshake);
2038 void QuicConnection::SetNetworkTimeouts(QuicTime::Delta overall_timeout,
2039 QuicTime::Delta idle_timeout) {
2040 LOG_IF(DFATAL, idle_timeout > overall_timeout)
2041 << "idle_timeout:" << idle_timeout.ToMilliseconds()
2042 << " overall_timeout:" << overall_timeout.ToMilliseconds();
2043 // Adjust the idle timeout on client and server to prevent clients from
2044 // sending requests to servers which have already closed the connection.
2045 if (perspective_ == Perspective::IS_SERVER) {
2046 idle_timeout = idle_timeout.Add(QuicTime::Delta::FromSeconds(3));
2047 } else if (idle_timeout > QuicTime::Delta::FromSeconds(1)) {
2048 idle_timeout = idle_timeout.Subtract(QuicTime::Delta::FromSeconds(1));
2050 overall_connection_timeout_ = overall_timeout;
2051 idle_network_timeout_ = idle_timeout;
2053 SetTimeoutAlarm();
2056 void QuicConnection::CheckForTimeout() {
2057 QuicTime now = clock_->ApproximateNow();
2058 QuicTime time_of_last_packet = max(time_of_last_received_packet_,
2059 time_of_last_sent_new_packet_);
2061 // |delta| can be < 0 as |now| is approximate time but |time_of_last_packet|
2062 // is accurate time. However, this should not change the behavior of
2063 // timeout handling.
2064 QuicTime::Delta idle_duration = now.Subtract(time_of_last_packet);
2065 DVLOG(1) << ENDPOINT << "last packet "
2066 << time_of_last_packet.ToDebuggingValue()
2067 << " now:" << now.ToDebuggingValue()
2068 << " idle_duration:" << idle_duration.ToMicroseconds()
2069 << " idle_network_timeout: "
2070 << idle_network_timeout_.ToMicroseconds();
2071 if (idle_duration >= idle_network_timeout_) {
2072 DVLOG(1) << ENDPOINT << "Connection timedout due to no network activity.";
2073 SendConnectionClose(QUIC_CONNECTION_TIMED_OUT);
2074 return;
2077 if (!overall_connection_timeout_.IsInfinite()) {
2078 QuicTime::Delta connected_duration =
2079 now.Subtract(stats_.connection_creation_time);
2080 DVLOG(1) << ENDPOINT << "connection time: "
2081 << connected_duration.ToMicroseconds() << " overall timeout: "
2082 << overall_connection_timeout_.ToMicroseconds();
2083 if (connected_duration >= overall_connection_timeout_) {
2084 DVLOG(1) << ENDPOINT <<
2085 "Connection timedout due to overall connection timeout.";
2086 SendConnectionClose(QUIC_CONNECTION_OVERALL_TIMED_OUT);
2087 return;
2091 SetTimeoutAlarm();
2094 void QuicConnection::SetTimeoutAlarm() {
2095 QuicTime time_of_last_packet = max(time_of_last_received_packet_,
2096 time_of_last_sent_new_packet_);
2098 QuicTime deadline = time_of_last_packet.Add(idle_network_timeout_);
2099 if (!overall_connection_timeout_.IsInfinite()) {
2100 deadline = min(deadline,
2101 stats_.connection_creation_time.Add(
2102 overall_connection_timeout_));
2105 timeout_alarm_->Cancel();
2106 timeout_alarm_->Set(deadline);
2109 void QuicConnection::SetPingAlarm() {
2110 if (perspective_ == Perspective::IS_SERVER) {
2111 // Only clients send pings.
2112 return;
2114 if (!visitor_->HasOpenDynamicStreams()) {
2115 ping_alarm_->Cancel();
2116 // Don't send a ping unless there are open streams.
2117 return;
2119 QuicTime::Delta ping_timeout = QuicTime::Delta::FromSeconds(kPingTimeoutSecs);
2120 ping_alarm_->Update(clock_->ApproximateNow().Add(ping_timeout),
2121 QuicTime::Delta::FromSeconds(1));
2124 QuicConnection::ScopedPacketBundler::ScopedPacketBundler(
2125 QuicConnection* connection,
2126 AckBundling send_ack)
2127 : connection_(connection),
2128 already_in_batch_mode_(connection != nullptr &&
2129 connection->packet_generator_.InBatchMode()) {
2130 if (connection_ == nullptr) {
2131 return;
2133 // Move generator into batch mode. If caller wants us to include an ack,
2134 // check the delayed-ack timer to see if there's ack info to be sent.
2135 if (!already_in_batch_mode_) {
2136 DVLOG(1) << "Entering Batch Mode.";
2137 connection_->packet_generator_.StartBatchOperations();
2139 // Bundle an ack if the alarm is set or with every second packet if we need to
2140 // raise the peer's least unacked.
2141 bool ack_pending =
2142 connection_->ack_alarm_->IsSet() || connection_->stop_waiting_count_ > 1;
2143 if (send_ack == SEND_ACK || (send_ack == BUNDLE_PENDING_ACK && ack_pending)) {
2144 DVLOG(1) << "Bundling ack with outgoing packet.";
2145 connection_->SendAck();
2149 QuicConnection::ScopedPacketBundler::~ScopedPacketBundler() {
2150 if (connection_ == nullptr) {
2151 return;
2153 // If we changed the generator's batch state, restore original batch state.
2154 if (!already_in_batch_mode_) {
2155 DVLOG(1) << "Leaving Batch Mode.";
2156 connection_->packet_generator_.FinishBatchOperations();
2158 DCHECK_EQ(already_in_batch_mode_,
2159 connection_->packet_generator_.InBatchMode());
2162 HasRetransmittableData QuicConnection::IsRetransmittable(
2163 const QueuedPacket& packet) {
2164 // Retransmitted packets retransmittable frames are owned by the unacked
2165 // packet map, but are not present in the serialized packet.
2166 if (packet.transmission_type != NOT_RETRANSMISSION ||
2167 packet.serialized_packet.retransmittable_frames != nullptr) {
2168 return HAS_RETRANSMITTABLE_DATA;
2169 } else {
2170 return NO_RETRANSMITTABLE_DATA;
2174 bool QuicConnection::IsConnectionClose(const QueuedPacket& packet) {
2175 const RetransmittableFrames* retransmittable_frames =
2176 packet.serialized_packet.retransmittable_frames;
2177 if (retransmittable_frames == nullptr) {
2178 return false;
2180 for (const QuicFrame& frame : retransmittable_frames->frames()) {
2181 if (frame.type == CONNECTION_CLOSE_FRAME) {
2182 return true;
2185 return false;
2188 } // namespace net