Don't add an aura tooltip to bubble close buttons on Windows.
[chromium-blink-merge.git] / net / quic / quic_connection.cc
blob76a1d566a439626312f82a086a6dea61bc297062
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/quic_decrypter.h"
25 #include "net/quic/crypto/quic_encrypter.h"
26 #include "net/quic/iovector.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 = 5 * kMaxTcpCongestionWindow;
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 sent scheduler requires a
113 // a delay 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 (FLAGS_quic_small_default_packet_size &&
281 perspective_ == Perspective::IS_SERVER) {
282 set_max_packet_length(kDefaultServerMaxPacketSize);
286 QuicConnection::~QuicConnection() {
287 if (owns_writer_) {
288 delete writer_;
290 STLDeleteElements(&undecryptable_packets_);
291 STLDeleteValues(&group_map_);
292 for (QueuedPacketList::iterator it = queued_packets_.begin();
293 it != queued_packets_.end(); ++it) {
294 delete it->serialized_packet.retransmittable_frames;
295 delete it->serialized_packet.packet;
299 void QuicConnection::SetFromConfig(const QuicConfig& config) {
300 if (config.negotiated()) {
301 SetNetworkTimeouts(QuicTime::Delta::Infinite(),
302 config.IdleConnectionStateLifetime());
303 if (config.SilentClose()) {
304 silent_close_enabled_ = true;
306 } else {
307 SetNetworkTimeouts(config.max_time_before_crypto_handshake(),
308 config.max_idle_time_before_crypto_handshake());
311 sent_packet_manager_.SetFromConfig(config);
312 if (config.HasReceivedBytesForConnectionId() &&
313 can_truncate_connection_ids_) {
314 packet_generator_.SetConnectionIdLength(
315 config.ReceivedBytesForConnectionId());
317 max_undecryptable_packets_ = config.max_undecryptable_packets();
320 void QuicConnection::OnSendConnectionState(
321 const CachedNetworkParameters& cached_network_params) {
322 if (debug_visitor_ != nullptr) {
323 debug_visitor_->OnSendConnectionState(cached_network_params);
327 bool QuicConnection::ResumeConnectionState(
328 const CachedNetworkParameters& cached_network_params,
329 bool max_bandwidth_resumption) {
330 if (debug_visitor_ != nullptr) {
331 debug_visitor_->OnResumeConnectionState(cached_network_params);
333 return sent_packet_manager_.ResumeConnectionState(cached_network_params,
334 max_bandwidth_resumption);
337 void QuicConnection::SetNumOpenStreams(size_t num_streams) {
338 sent_packet_manager_.SetNumOpenStreams(num_streams);
341 bool QuicConnection::SelectMutualVersion(
342 const QuicVersionVector& available_versions) {
343 // Try to find the highest mutual version by iterating over supported
344 // versions, starting with the highest, and breaking out of the loop once we
345 // find a matching version in the provided available_versions vector.
346 const QuicVersionVector& supported_versions = framer_.supported_versions();
347 for (size_t i = 0; i < supported_versions.size(); ++i) {
348 const QuicVersion& version = supported_versions[i];
349 if (std::find(available_versions.begin(), available_versions.end(),
350 version) != available_versions.end()) {
351 framer_.set_version(version);
352 return true;
356 return false;
359 void QuicConnection::OnError(QuicFramer* framer) {
360 // Packets that we can not or have not decrypted are dropped.
361 // TODO(rch): add stats to measure this.
362 if (!connected_ || last_packet_decrypted_ == false) {
363 return;
365 SendConnectionCloseWithDetails(framer->error(), framer->detailed_error());
368 void QuicConnection::MaybeSetFecAlarm(
369 QuicPacketSequenceNumber sequence_number) {
370 if (fec_alarm_->IsSet()) {
371 return;
373 QuicTime::Delta timeout = packet_generator_.GetFecTimeout(sequence_number);
374 if (!timeout.IsInfinite()) {
375 fec_alarm_->Set(clock_->ApproximateNow().Add(timeout));
379 void QuicConnection::OnPacket() {
380 DCHECK(last_stream_frames_.empty() &&
381 last_ack_frames_.empty() &&
382 last_stop_waiting_frames_.empty() &&
383 last_rst_frames_.empty() &&
384 last_goaway_frames_.empty() &&
385 last_window_update_frames_.empty() &&
386 last_blocked_frames_.empty() &&
387 last_ping_frames_.empty() &&
388 last_close_frames_.empty());
389 last_packet_decrypted_ = false;
390 last_packet_revived_ = false;
393 void QuicConnection::OnPublicResetPacket(
394 const QuicPublicResetPacket& packet) {
395 // Check that any public reset packet with a different connection ID that was
396 // routed to this QuicConnection has been redirected before control reaches
397 // here. (Check for a bug regression.)
398 DCHECK_EQ(connection_id_, packet.public_header.connection_id);
399 if (debug_visitor_ != nullptr) {
400 debug_visitor_->OnPublicResetPacket(packet);
402 CloseConnection(QUIC_PUBLIC_RESET, true);
404 DVLOG(1) << ENDPOINT << "Connection " << connection_id()
405 << " closed via QUIC_PUBLIC_RESET from peer.";
408 bool QuicConnection::OnProtocolVersionMismatch(QuicVersion received_version) {
409 DVLOG(1) << ENDPOINT << "Received packet with mismatched version "
410 << received_version;
411 // TODO(satyamshekhar): Implement no server state in this mode.
412 if (perspective_ == Perspective::IS_CLIENT) {
413 LOG(DFATAL) << ENDPOINT << "Framer called OnProtocolVersionMismatch. "
414 << "Closing connection.";
415 CloseConnection(QUIC_INTERNAL_ERROR, false);
416 return false;
418 DCHECK_NE(version(), received_version);
420 if (debug_visitor_ != nullptr) {
421 debug_visitor_->OnProtocolVersionMismatch(received_version);
424 switch (version_negotiation_state_) {
425 case START_NEGOTIATION:
426 if (!framer_.IsSupportedVersion(received_version)) {
427 SendVersionNegotiationPacket();
428 version_negotiation_state_ = NEGOTIATION_IN_PROGRESS;
429 return false;
431 break;
433 case NEGOTIATION_IN_PROGRESS:
434 if (!framer_.IsSupportedVersion(received_version)) {
435 SendVersionNegotiationPacket();
436 return false;
438 break;
440 case NEGOTIATED_VERSION:
441 // Might be old packets that were sent by the client before the version
442 // was negotiated. Drop these.
443 return false;
445 default:
446 DCHECK(false);
449 version_negotiation_state_ = NEGOTIATED_VERSION;
450 visitor_->OnSuccessfulVersionNegotiation(received_version);
451 if (debug_visitor_ != nullptr) {
452 debug_visitor_->OnSuccessfulVersionNegotiation(received_version);
454 DVLOG(1) << ENDPOINT << "version negotiated " << received_version;
456 // Store the new version.
457 framer_.set_version(received_version);
459 // TODO(satyamshekhar): Store the sequence number of this packet and close the
460 // connection if we ever received a packet with incorrect version and whose
461 // sequence number is greater.
462 return true;
465 // Handles version negotiation for client connection.
466 void QuicConnection::OnVersionNegotiationPacket(
467 const QuicVersionNegotiationPacket& packet) {
468 // Check that any public reset packet with a different connection ID that was
469 // routed to this QuicConnection has been redirected before control reaches
470 // here. (Check for a bug regression.)
471 DCHECK_EQ(connection_id_, packet.connection_id);
472 if (perspective_ == Perspective::IS_SERVER) {
473 LOG(DFATAL) << ENDPOINT << "Framer parsed VersionNegotiationPacket."
474 << " Closing connection.";
475 CloseConnection(QUIC_INTERNAL_ERROR, false);
476 return;
478 if (debug_visitor_ != nullptr) {
479 debug_visitor_->OnVersionNegotiationPacket(packet);
482 if (version_negotiation_state_ != START_NEGOTIATION) {
483 // Possibly a duplicate version negotiation packet.
484 return;
487 if (std::find(packet.versions.begin(),
488 packet.versions.end(), version()) !=
489 packet.versions.end()) {
490 DLOG(WARNING) << ENDPOINT << "The server already supports our version. "
491 << "It should have accepted our connection.";
492 // Just drop the connection.
493 CloseConnection(QUIC_INVALID_VERSION_NEGOTIATION_PACKET, false);
494 return;
497 if (!SelectMutualVersion(packet.versions)) {
498 SendConnectionCloseWithDetails(QUIC_INVALID_VERSION,
499 "no common version found");
500 return;
503 DVLOG(1) << ENDPOINT
504 << "Negotiated version: " << QuicVersionToString(version());
505 server_supported_versions_ = packet.versions;
506 version_negotiation_state_ = NEGOTIATION_IN_PROGRESS;
507 RetransmitUnackedPackets(ALL_UNACKED_RETRANSMISSION);
510 void QuicConnection::OnRevivedPacket() {
513 bool QuicConnection::OnUnauthenticatedPublicHeader(
514 const QuicPacketPublicHeader& header) {
515 if (header.connection_id == connection_id_) {
516 return true;
519 ++stats_.packets_dropped;
520 DVLOG(1) << ENDPOINT << "Ignoring packet from unexpected ConnectionId: "
521 << header.connection_id << " instead of " << connection_id_;
522 if (debug_visitor_ != nullptr) {
523 debug_visitor_->OnIncorrectConnectionId(header.connection_id);
525 // If this is a server, the dispatcher routes each packet to the
526 // QuicConnection responsible for the packet's connection ID. So if control
527 // arrives here and this is a server, the dispatcher must be malfunctioning.
528 DCHECK_NE(Perspective::IS_SERVER, perspective_);
529 return false;
532 bool QuicConnection::OnUnauthenticatedHeader(const QuicPacketHeader& header) {
533 // Check that any public reset packet with a different connection ID that was
534 // routed to this QuicConnection has been redirected before control reaches
535 // here.
536 DCHECK_EQ(connection_id_, header.public_header.connection_id);
537 return true;
540 void QuicConnection::OnDecryptedPacket(EncryptionLevel level) {
541 last_decrypted_packet_level_ = level;
542 last_packet_decrypted_ = true;
543 // If this packet was foward-secure encrypted and the forward-secure encrypter
544 // is not being used, start using it.
545 if (encryption_level_ != ENCRYPTION_FORWARD_SECURE &&
546 has_forward_secure_encrypter_ && level == ENCRYPTION_FORWARD_SECURE) {
547 SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
551 bool QuicConnection::OnPacketHeader(const QuicPacketHeader& header) {
552 if (debug_visitor_ != nullptr) {
553 debug_visitor_->OnPacketHeader(header);
556 if (!ProcessValidatedPacket()) {
557 return false;
560 // Will be decrement below if we fall through to return true;
561 ++stats_.packets_dropped;
563 if (!Near(header.packet_sequence_number,
564 last_header_.packet_sequence_number)) {
565 DVLOG(1) << ENDPOINT << "Packet " << header.packet_sequence_number
566 << " out of bounds. Discarding";
567 SendConnectionCloseWithDetails(QUIC_INVALID_PACKET_HEADER,
568 "Packet sequence number out of bounds");
569 return false;
572 // If this packet has already been seen, or that the sender
573 // has told us will not be retransmitted, then stop processing the packet.
574 if (!received_packet_manager_.IsAwaitingPacket(
575 header.packet_sequence_number)) {
576 DVLOG(1) << ENDPOINT << "Packet " << header.packet_sequence_number
577 << " no longer being waited for. Discarding.";
578 if (debug_visitor_ != nullptr) {
579 debug_visitor_->OnDuplicatePacket(header.packet_sequence_number);
581 return false;
584 if (version_negotiation_state_ != NEGOTIATED_VERSION) {
585 if (perspective_ == Perspective::IS_SERVER) {
586 if (!header.public_header.version_flag) {
587 DLOG(WARNING) << ENDPOINT << "Packet " << header.packet_sequence_number
588 << " without version flag before version negotiated.";
589 // Packets should have the version flag till version negotiation is
590 // done.
591 CloseConnection(QUIC_INVALID_VERSION, false);
592 return false;
593 } else {
594 DCHECK_EQ(1u, header.public_header.versions.size());
595 DCHECK_EQ(header.public_header.versions[0], version());
596 version_negotiation_state_ = NEGOTIATED_VERSION;
597 visitor_->OnSuccessfulVersionNegotiation(version());
598 if (debug_visitor_ != nullptr) {
599 debug_visitor_->OnSuccessfulVersionNegotiation(version());
602 } else {
603 DCHECK(!header.public_header.version_flag);
604 // If the client gets a packet without the version flag from the server
605 // it should stop sending version since the version negotiation is done.
606 packet_generator_.StopSendingVersion();
607 version_negotiation_state_ = NEGOTIATED_VERSION;
608 visitor_->OnSuccessfulVersionNegotiation(version());
609 if (debug_visitor_ != nullptr) {
610 debug_visitor_->OnSuccessfulVersionNegotiation(version());
615 DCHECK_EQ(NEGOTIATED_VERSION, version_negotiation_state_);
617 --stats_.packets_dropped;
618 DVLOG(1) << ENDPOINT << "Received packet header: " << header;
619 last_header_ = header;
620 DCHECK(connected_);
621 return true;
624 void QuicConnection::OnFecProtectedPayload(StringPiece payload) {
625 DCHECK_EQ(IN_FEC_GROUP, last_header_.is_in_fec_group);
626 DCHECK_NE(0u, last_header_.fec_group);
627 QuicFecGroup* group = GetFecGroup();
628 if (group != nullptr) {
629 group->Update(last_decrypted_packet_level_, last_header_, payload);
633 bool QuicConnection::OnStreamFrame(const QuicStreamFrame& frame) {
634 DCHECK(connected_);
635 if (debug_visitor_ != nullptr) {
636 debug_visitor_->OnStreamFrame(frame);
638 if (frame.stream_id != kCryptoStreamId &&
639 last_decrypted_packet_level_ == ENCRYPTION_NONE) {
640 DLOG(WARNING) << ENDPOINT
641 << "Received an unencrypted data frame: closing connection";
642 SendConnectionClose(QUIC_UNENCRYPTED_STREAM_DATA);
643 return false;
645 last_stream_frames_.push_back(frame);
646 return true;
649 bool QuicConnection::OnAckFrame(const QuicAckFrame& incoming_ack) {
650 DCHECK(connected_);
651 if (debug_visitor_ != nullptr) {
652 debug_visitor_->OnAckFrame(incoming_ack);
654 DVLOG(1) << ENDPOINT << "OnAckFrame: " << incoming_ack;
656 if (last_header_.packet_sequence_number <= largest_seen_packet_with_ack_) {
657 DVLOG(1) << ENDPOINT << "Received an old ack frame: ignoring";
658 return true;
661 if (!ValidateAckFrame(incoming_ack)) {
662 SendConnectionClose(QUIC_INVALID_ACK_DATA);
663 return false;
666 last_ack_frames_.push_back(incoming_ack);
667 return connected_;
670 void QuicConnection::ProcessAckFrame(const QuicAckFrame& incoming_ack) {
671 largest_seen_packet_with_ack_ = last_header_.packet_sequence_number;
672 sent_packet_manager_.OnIncomingAck(incoming_ack,
673 time_of_last_received_packet_);
674 sent_entropy_manager_.ClearEntropyBefore(
675 sent_packet_manager_.least_packet_awaited_by_peer() - 1);
676 if (sent_packet_manager_.HasPendingRetransmissions()) {
677 WriteIfNotBlocked();
680 // Always reset the retransmission alarm when an ack comes in, since we now
681 // have a better estimate of the current rtt than when it was set.
682 QuicTime retransmission_time = sent_packet_manager_.GetRetransmissionTime();
683 retransmission_alarm_->Update(retransmission_time,
684 QuicTime::Delta::FromMilliseconds(1));
687 void QuicConnection::ProcessStopWaitingFrame(
688 const QuicStopWaitingFrame& stop_waiting) {
689 largest_seen_packet_with_stop_waiting_ = last_header_.packet_sequence_number;
690 received_packet_manager_.UpdatePacketInformationSentByPeer(stop_waiting);
691 // Possibly close any FecGroups which are now irrelevant.
692 CloseFecGroupsBefore(stop_waiting.least_unacked + 1);
695 bool QuicConnection::OnStopWaitingFrame(const QuicStopWaitingFrame& frame) {
696 DCHECK(connected_);
698 if (last_header_.packet_sequence_number <=
699 largest_seen_packet_with_stop_waiting_) {
700 DVLOG(1) << ENDPOINT << "Received an old stop waiting frame: ignoring";
701 return true;
704 if (!ValidateStopWaitingFrame(frame)) {
705 SendConnectionClose(QUIC_INVALID_STOP_WAITING_DATA);
706 return false;
709 if (debug_visitor_ != nullptr) {
710 debug_visitor_->OnStopWaitingFrame(frame);
713 last_stop_waiting_frames_.push_back(frame);
714 return connected_;
717 bool QuicConnection::OnPingFrame(const QuicPingFrame& frame) {
718 DCHECK(connected_);
719 if (debug_visitor_ != nullptr) {
720 debug_visitor_->OnPingFrame(frame);
722 last_ping_frames_.push_back(frame);
723 return true;
726 bool QuicConnection::ValidateAckFrame(const QuicAckFrame& incoming_ack) {
727 if (incoming_ack.largest_observed > packet_generator_.sequence_number()) {
728 DLOG(ERROR) << ENDPOINT << "Peer's observed unsent packet:"
729 << incoming_ack.largest_observed << " vs "
730 << packet_generator_.sequence_number();
731 // We got an error for data we have not sent. Error out.
732 return false;
735 if (incoming_ack.largest_observed < sent_packet_manager_.largest_observed()) {
736 DLOG(ERROR) << ENDPOINT << "Peer's largest_observed packet decreased:"
737 << incoming_ack.largest_observed << " vs "
738 << sent_packet_manager_.largest_observed();
739 // A new ack has a diminished largest_observed value. Error out.
740 // If this was an old packet, we wouldn't even have checked.
741 return false;
744 if (!incoming_ack.missing_packets.empty() &&
745 *incoming_ack.missing_packets.rbegin() > incoming_ack.largest_observed) {
746 DLOG(ERROR) << ENDPOINT << "Peer sent missing packet: "
747 << *incoming_ack.missing_packets.rbegin()
748 << " which is greater than largest observed: "
749 << incoming_ack.largest_observed;
750 return false;
753 if (!incoming_ack.missing_packets.empty() &&
754 *incoming_ack.missing_packets.begin() <
755 sent_packet_manager_.least_packet_awaited_by_peer()) {
756 DLOG(ERROR) << ENDPOINT << "Peer sent missing packet: "
757 << *incoming_ack.missing_packets.begin()
758 << " which is smaller than least_packet_awaited_by_peer_: "
759 << sent_packet_manager_.least_packet_awaited_by_peer();
760 return false;
763 if (!sent_entropy_manager_.IsValidEntropy(
764 incoming_ack.largest_observed,
765 incoming_ack.missing_packets,
766 incoming_ack.entropy_hash)) {
767 DLOG(ERROR) << ENDPOINT << "Peer sent invalid entropy.";
768 return false;
771 for (SequenceNumberSet::const_iterator iter =
772 incoming_ack.revived_packets.begin();
773 iter != incoming_ack.revived_packets.end(); ++iter) {
774 if (!ContainsKey(incoming_ack.missing_packets, *iter)) {
775 DLOG(ERROR) << ENDPOINT
776 << "Peer specified revived packet which was not missing.";
777 return false;
780 return true;
783 bool QuicConnection::ValidateStopWaitingFrame(
784 const QuicStopWaitingFrame& stop_waiting) {
785 if (stop_waiting.least_unacked <
786 received_packet_manager_.peer_least_packet_awaiting_ack()) {
787 DLOG(ERROR) << ENDPOINT << "Peer's sent low least_unacked: "
788 << stop_waiting.least_unacked << " vs "
789 << received_packet_manager_.peer_least_packet_awaiting_ack();
790 // We never process old ack frames, so this number should only increase.
791 return false;
794 if (stop_waiting.least_unacked >
795 last_header_.packet_sequence_number) {
796 DLOG(ERROR) << ENDPOINT << "Peer sent least_unacked:"
797 << stop_waiting.least_unacked
798 << " greater than the enclosing packet sequence number:"
799 << last_header_.packet_sequence_number;
800 return false;
803 return true;
806 void QuicConnection::OnFecData(const QuicFecData& fec) {
807 DCHECK_EQ(IN_FEC_GROUP, last_header_.is_in_fec_group);
808 DCHECK_NE(0u, last_header_.fec_group);
809 QuicFecGroup* group = GetFecGroup();
810 if (group != nullptr) {
811 group->UpdateFec(last_decrypted_packet_level_,
812 last_header_.packet_sequence_number, fec);
816 bool QuicConnection::OnRstStreamFrame(const QuicRstStreamFrame& frame) {
817 DCHECK(connected_);
818 if (debug_visitor_ != nullptr) {
819 debug_visitor_->OnRstStreamFrame(frame);
821 DVLOG(1) << ENDPOINT << "Stream reset with error "
822 << QuicUtils::StreamErrorToString(frame.error_code);
823 last_rst_frames_.push_back(frame);
824 return connected_;
827 bool QuicConnection::OnConnectionCloseFrame(
828 const QuicConnectionCloseFrame& frame) {
829 DCHECK(connected_);
830 if (debug_visitor_ != nullptr) {
831 debug_visitor_->OnConnectionCloseFrame(frame);
833 DVLOG(1) << ENDPOINT << "Connection " << connection_id()
834 << " closed with error "
835 << QuicUtils::ErrorToString(frame.error_code)
836 << " " << frame.error_details;
837 last_close_frames_.push_back(frame);
838 return connected_;
841 bool QuicConnection::OnGoAwayFrame(const QuicGoAwayFrame& frame) {
842 DCHECK(connected_);
843 if (debug_visitor_ != nullptr) {
844 debug_visitor_->OnGoAwayFrame(frame);
846 DVLOG(1) << ENDPOINT << "Go away received with error "
847 << QuicUtils::ErrorToString(frame.error_code)
848 << " and reason:" << frame.reason_phrase;
849 last_goaway_frames_.push_back(frame);
850 return connected_;
853 bool QuicConnection::OnWindowUpdateFrame(const QuicWindowUpdateFrame& frame) {
854 DCHECK(connected_);
855 if (debug_visitor_ != nullptr) {
856 debug_visitor_->OnWindowUpdateFrame(frame);
858 DVLOG(1) << ENDPOINT << "WindowUpdate received for stream: "
859 << frame.stream_id << " with byte offset: " << frame.byte_offset;
860 last_window_update_frames_.push_back(frame);
861 return connected_;
864 bool QuicConnection::OnBlockedFrame(const QuicBlockedFrame& frame) {
865 DCHECK(connected_);
866 if (debug_visitor_ != nullptr) {
867 debug_visitor_->OnBlockedFrame(frame);
869 DVLOG(1) << ENDPOINT << "Blocked frame received for stream: "
870 << frame.stream_id;
871 last_blocked_frames_.push_back(frame);
872 return connected_;
875 void QuicConnection::OnPacketComplete() {
876 // Don't do anything if this packet closed the connection.
877 if (!connected_) {
878 ClearLastFrames();
879 return;
882 DVLOG(1) << ENDPOINT << (last_packet_revived_ ? "Revived" : "Got")
883 << " packet " << last_header_.packet_sequence_number
884 << " with " << last_stream_frames_.size()<< " stream frames "
885 << last_ack_frames_.size() << " acks, "
886 << last_stop_waiting_frames_.size() << " stop_waiting, "
887 << last_rst_frames_.size() << " rsts, "
888 << last_goaway_frames_.size() << " goaways, "
889 << last_window_update_frames_.size() << " window updates, "
890 << last_blocked_frames_.size() << " blocked, "
891 << last_ping_frames_.size() << " pings, "
892 << last_close_frames_.size() << " closes, "
893 << "for " << last_header_.public_header.connection_id;
895 ++num_packets_received_since_last_ack_sent_;
897 // Call MaybeQueueAck() before recording the received packet, since we want
898 // to trigger an ack if the newly received packet was previously missing.
899 MaybeQueueAck();
901 // Record received or revived packet to populate ack info correctly before
902 // processing stream frames, since the processing may result in a response
903 // packet with a bundled ack.
904 if (last_packet_revived_) {
905 received_packet_manager_.RecordPacketRevived(
906 last_header_.packet_sequence_number);
907 } else {
908 received_packet_manager_.RecordPacketReceived(
909 last_size_, last_header_, time_of_last_received_packet_);
912 if (!last_stream_frames_.empty()) {
913 visitor_->OnStreamFrames(last_stream_frames_);
916 for (size_t i = 0; i < last_stream_frames_.size(); ++i) {
917 stats_.stream_bytes_received +=
918 last_stream_frames_[i].data.TotalBufferSize();
921 // Process window updates, blocked, stream resets, acks, then congestion
922 // feedback.
923 if (!last_window_update_frames_.empty()) {
924 visitor_->OnWindowUpdateFrames(last_window_update_frames_);
926 if (!last_blocked_frames_.empty()) {
927 visitor_->OnBlockedFrames(last_blocked_frames_);
929 for (size_t i = 0; i < last_goaway_frames_.size(); ++i) {
930 visitor_->OnGoAway(last_goaway_frames_[i]);
932 for (size_t i = 0; i < last_rst_frames_.size(); ++i) {
933 visitor_->OnRstStream(last_rst_frames_[i]);
935 for (size_t i = 0; i < last_ack_frames_.size(); ++i) {
936 ProcessAckFrame(last_ack_frames_[i]);
938 for (size_t i = 0; i < last_stop_waiting_frames_.size(); ++i) {
939 ProcessStopWaitingFrame(last_stop_waiting_frames_[i]);
941 if (!last_close_frames_.empty()) {
942 CloseConnection(last_close_frames_[0].error_code, true);
943 DCHECK(!connected_);
946 // If there are new missing packets to report, send an ack immediately.
947 if (received_packet_manager_.HasNewMissingPackets()) {
948 ack_queued_ = true;
949 ack_alarm_->Cancel();
952 UpdateStopWaitingCount();
953 ClearLastFrames();
954 MaybeCloseIfTooManyOutstandingPackets();
957 void QuicConnection::MaybeQueueAck() {
958 // If the incoming packet was missing, send an ack immediately.
959 ack_queued_ = received_packet_manager_.IsMissing(
960 last_header_.packet_sequence_number);
962 if (!ack_queued_ && ShouldLastPacketInstigateAck()) {
963 if (ack_alarm_->IsSet()) {
964 ack_queued_ = true;
965 } else {
966 // Send an ack much more quickly for crypto handshake packets.
967 QuicTime::Delta delayed_ack_time = sent_packet_manager_.DelayedAckTime();
968 ack_alarm_->Set(clock_->ApproximateNow().Add(delayed_ack_time));
969 DVLOG(1) << "Ack timer set; next packet or timer will trigger ACK.";
973 if (ack_queued_) {
974 ack_alarm_->Cancel();
978 void QuicConnection::ClearLastFrames() {
979 last_stream_frames_.clear();
980 last_ack_frames_.clear();
981 last_stop_waiting_frames_.clear();
982 last_rst_frames_.clear();
983 last_goaway_frames_.clear();
984 last_window_update_frames_.clear();
985 last_blocked_frames_.clear();
986 last_ping_frames_.clear();
987 last_close_frames_.clear();
990 void QuicConnection::MaybeCloseIfTooManyOutstandingPackets() {
991 // This occurs if we don't discard old packets we've sent fast enough.
992 // It's possible largest observed is less than least unacked.
993 if (sent_packet_manager_.largest_observed() >
994 (sent_packet_manager_.GetLeastUnacked() + kMaxTrackedPackets)) {
995 SendConnectionCloseWithDetails(
996 QUIC_TOO_MANY_OUTSTANDING_SENT_PACKETS,
997 StringPrintf("More than %" PRIu64 " outstanding.", kMaxTrackedPackets));
999 // This occurs if there are received packet gaps and the peer does not raise
1000 // the least unacked fast enough.
1001 if (received_packet_manager_.NumTrackedPackets() > kMaxTrackedPackets) {
1002 SendConnectionCloseWithDetails(
1003 QUIC_TOO_MANY_OUTSTANDING_RECEIVED_PACKETS,
1004 StringPrintf("More than %" PRIu64 " outstanding.", kMaxTrackedPackets));
1008 void QuicConnection::PopulateAckFrame(QuicAckFrame* ack) {
1009 received_packet_manager_.UpdateReceivedPacketInfo(ack,
1010 clock_->ApproximateNow());
1013 void QuicConnection::PopulateStopWaitingFrame(
1014 QuicStopWaitingFrame* stop_waiting) {
1015 stop_waiting->least_unacked = GetLeastUnacked();
1016 stop_waiting->entropy_hash = sent_entropy_manager_.GetCumulativeEntropy(
1017 stop_waiting->least_unacked - 1);
1020 bool QuicConnection::ShouldLastPacketInstigateAck() const {
1021 if (!last_stream_frames_.empty() ||
1022 !last_goaway_frames_.empty() ||
1023 !last_rst_frames_.empty() ||
1024 !last_window_update_frames_.empty() ||
1025 !last_blocked_frames_.empty() ||
1026 !last_ping_frames_.empty()) {
1027 return true;
1030 if (!last_ack_frames_.empty() && last_ack_frames_.back().is_truncated) {
1031 return true;
1033 // Always send an ack every 20 packets in order to allow the peer to discard
1034 // information from the SentPacketManager and provide an RTT measurement.
1035 if (num_packets_received_since_last_ack_sent_ >=
1036 kMaxPacketsReceivedBeforeAckSend) {
1037 return true;
1039 return false;
1042 void QuicConnection::UpdateStopWaitingCount() {
1043 if (last_ack_frames_.empty()) {
1044 return;
1047 // If the peer is still waiting for a packet that we are no longer planning to
1048 // send, send an ack to raise the high water mark.
1049 if (!last_ack_frames_.back().missing_packets.empty() &&
1050 GetLeastUnacked() > *last_ack_frames_.back().missing_packets.begin()) {
1051 ++stop_waiting_count_;
1052 } else {
1053 stop_waiting_count_ = 0;
1057 QuicPacketSequenceNumber QuicConnection::GetLeastUnacked() const {
1058 return sent_packet_manager_.GetLeastUnacked();
1061 void QuicConnection::MaybeSendInResponseToPacket() {
1062 if (!connected_) {
1063 return;
1065 ScopedPacketBundler bundler(this, ack_queued_ ? SEND_ACK : NO_ACK);
1067 // Now that we have received an ack, we might be able to send packets which
1068 // are queued locally, or drain streams which are blocked.
1069 if (CanWrite(HAS_RETRANSMITTABLE_DATA)) {
1070 OnCanWrite();
1074 void QuicConnection::SendVersionNegotiationPacket() {
1075 // TODO(alyssar): implement zero server state negotiation.
1076 pending_version_negotiation_packet_ = true;
1077 if (writer_->IsWriteBlocked()) {
1078 visitor_->OnWriteBlocked();
1079 return;
1081 DVLOG(1) << ENDPOINT << "Sending version negotiation packet: {"
1082 << QuicVersionVectorToString(framer_.supported_versions()) << "}";
1083 scoped_ptr<QuicEncryptedPacket> version_packet(
1084 packet_generator_.SerializeVersionNegotiationPacket(
1085 framer_.supported_versions()));
1086 WriteResult result = writer_->WritePacket(
1087 version_packet->data(), version_packet->length(),
1088 self_address().address(), peer_address());
1090 if (result.status == WRITE_STATUS_ERROR) {
1091 // We can't send an error as the socket is presumably borked.
1092 CloseConnection(QUIC_PACKET_WRITE_ERROR, false);
1093 return;
1095 if (result.status == WRITE_STATUS_BLOCKED) {
1096 visitor_->OnWriteBlocked();
1097 if (writer_->IsWriteBlockedDataBuffered()) {
1098 pending_version_negotiation_packet_ = false;
1100 return;
1103 pending_version_negotiation_packet_ = false;
1106 QuicConsumedData QuicConnection::SendStreamData(
1107 QuicStreamId id,
1108 const IOVector& data,
1109 QuicStreamOffset offset,
1110 bool fin,
1111 FecProtection fec_protection,
1112 QuicAckNotifier::DelegateInterface* delegate) {
1113 if (!fin && data.Empty()) {
1114 LOG(DFATAL) << "Attempt to send empty stream frame";
1115 return QuicConsumedData(0, false);
1118 // Opportunistically bundle an ack with every outgoing packet.
1119 // Particularly, we want to bundle with handshake packets since we don't know
1120 // which decrypter will be used on an ack packet following a handshake
1121 // packet (a handshake packet from client to server could result in a REJ or a
1122 // SHLO from the server, leading to two different decrypters at the server.)
1124 // TODO(jri): Note that ConsumeData may cause a response packet to be sent.
1125 // We may end up sending stale ack information if there are undecryptable
1126 // packets hanging around and/or there are revivable packets which may get
1127 // handled after this packet is sent. Change ScopedPacketBundler to do the
1128 // right thing: check ack_queued_, and then check undecryptable packets and
1129 // also if there is possibility of revival. Only bundle an ack if there's no
1130 // processing left that may cause received_info_ to change.
1131 ScopedPacketBundler ack_bundler(this, BUNDLE_PENDING_ACK);
1132 return packet_generator_.ConsumeData(id, data, offset, fin, fec_protection,
1133 delegate);
1136 void QuicConnection::SendRstStream(QuicStreamId id,
1137 QuicRstStreamErrorCode error,
1138 QuicStreamOffset bytes_written) {
1139 // Opportunistically bundle an ack with this outgoing packet.
1140 ScopedPacketBundler ack_bundler(this, BUNDLE_PENDING_ACK);
1141 packet_generator_.AddControlFrame(QuicFrame(new QuicRstStreamFrame(
1142 id, AdjustErrorForVersion(error, version()), bytes_written)));
1143 if (!FLAGS_quic_do_not_retransmit_for_reset_streams) {
1144 return;
1147 sent_packet_manager_.CancelRetransmissionsForStream(id);
1148 // Remove all queued packets which only contain data for the reset stream.
1149 QueuedPacketList::iterator packet_iterator = queued_packets_.begin();
1150 while (packet_iterator != queued_packets_.end()) {
1151 RetransmittableFrames* retransmittable_frames =
1152 packet_iterator->serialized_packet.retransmittable_frames;
1153 if (!retransmittable_frames) {
1154 ++packet_iterator;
1155 continue;
1157 retransmittable_frames->RemoveFramesForStream(id);
1158 if (!retransmittable_frames->frames().empty()) {
1159 ++packet_iterator;
1160 continue;
1162 delete packet_iterator->serialized_packet.retransmittable_frames;
1163 delete packet_iterator->serialized_packet.packet;
1164 packet_iterator->serialized_packet.retransmittable_frames = nullptr;
1165 packet_iterator->serialized_packet.packet = nullptr;
1166 packet_iterator = queued_packets_.erase(packet_iterator);
1170 void QuicConnection::SendWindowUpdate(QuicStreamId id,
1171 QuicStreamOffset byte_offset) {
1172 // Opportunistically bundle an ack with this outgoing packet.
1173 ScopedPacketBundler ack_bundler(this, BUNDLE_PENDING_ACK);
1174 packet_generator_.AddControlFrame(
1175 QuicFrame(new QuicWindowUpdateFrame(id, byte_offset)));
1178 void QuicConnection::SendBlocked(QuicStreamId id) {
1179 // Opportunistically bundle an ack with this outgoing packet.
1180 ScopedPacketBundler ack_bundler(this, BUNDLE_PENDING_ACK);
1181 packet_generator_.AddControlFrame(QuicFrame(new QuicBlockedFrame(id)));
1184 const QuicConnectionStats& QuicConnection::GetStats() {
1185 const RttStats* rtt_stats = sent_packet_manager_.GetRttStats();
1187 // Update rtt and estimated bandwidth.
1188 QuicTime::Delta min_rtt = rtt_stats->min_rtt();
1189 if (min_rtt.IsZero()) {
1190 // If min RTT has not been set, use initial RTT instead.
1191 min_rtt = QuicTime::Delta::FromMicroseconds(rtt_stats->initial_rtt_us());
1193 stats_.min_rtt_us = min_rtt.ToMicroseconds();
1195 QuicTime::Delta srtt = rtt_stats->smoothed_rtt();
1196 if (srtt.IsZero()) {
1197 // If SRTT has not been set, use initial RTT instead.
1198 srtt = QuicTime::Delta::FromMicroseconds(rtt_stats->initial_rtt_us());
1200 stats_.srtt_us = srtt.ToMicroseconds();
1202 stats_.estimated_bandwidth = sent_packet_manager_.BandwidthEstimate();
1203 stats_.max_packet_size = packet_generator_.max_packet_length();
1204 return stats_;
1207 void QuicConnection::ProcessUdpPacket(const IPEndPoint& self_address,
1208 const IPEndPoint& peer_address,
1209 const QuicEncryptedPacket& packet) {
1210 if (!connected_) {
1211 return;
1213 // TODO(rtenneti): Remove ScopedTracker below once crbug.com/462789 is fixed.
1214 tracked_objects::ScopedTracker tracking_profile(
1215 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1216 "462789 QuicConnection::ProcessUdpPacket"));
1217 if (debug_visitor_ != nullptr) {
1218 debug_visitor_->OnPacketReceived(self_address, peer_address, packet);
1220 last_size_ = packet.length();
1222 CheckForAddressMigration(self_address, peer_address);
1224 stats_.bytes_received += packet.length();
1225 ++stats_.packets_received;
1227 if (!framer_.ProcessPacket(packet)) {
1228 // If we are unable to decrypt this packet, it might be
1229 // because the CHLO or SHLO packet was lost.
1230 if (framer_.error() == QUIC_DECRYPTION_FAILURE) {
1231 if (encryption_level_ != ENCRYPTION_FORWARD_SECURE &&
1232 undecryptable_packets_.size() < max_undecryptable_packets_) {
1233 QueueUndecryptablePacket(packet);
1234 } else if (debug_visitor_ != nullptr) {
1235 debug_visitor_->OnUndecryptablePacket();
1238 DVLOG(1) << ENDPOINT << "Unable to process packet. Last packet processed: "
1239 << last_header_.packet_sequence_number;
1240 return;
1243 ++stats_.packets_processed;
1244 MaybeProcessUndecryptablePackets();
1245 MaybeProcessRevivedPacket();
1246 MaybeSendInResponseToPacket();
1247 SetPingAlarm();
1250 void QuicConnection::CheckForAddressMigration(
1251 const IPEndPoint& self_address, const IPEndPoint& peer_address) {
1252 peer_ip_changed_ = false;
1253 peer_port_changed_ = false;
1254 self_ip_changed_ = false;
1255 self_port_changed_ = false;
1257 if (peer_address_.address().empty()) {
1258 peer_address_ = peer_address;
1260 if (self_address_.address().empty()) {
1261 self_address_ = self_address;
1264 if (!peer_address.address().empty() && !peer_address_.address().empty()) {
1265 peer_ip_changed_ = (peer_address.address() != peer_address_.address());
1266 peer_port_changed_ = (peer_address.port() != peer_address_.port());
1268 // Store in case we want to migrate connection in ProcessValidatedPacket.
1269 migrating_peer_port_ = peer_address.port();
1272 if (!self_address.address().empty() && !self_address_.address().empty()) {
1273 self_ip_changed_ = (self_address.address() != self_address_.address());
1274 self_port_changed_ = (self_address.port() != self_address_.port());
1278 void QuicConnection::OnCanWrite() {
1279 DCHECK(!writer_->IsWriteBlocked());
1281 WriteQueuedPackets();
1282 WritePendingRetransmissions();
1284 // Sending queued packets may have caused the socket to become write blocked,
1285 // or the congestion manager to prohibit sending. If we've sent everything
1286 // we had queued and we're still not blocked, let the visitor know it can
1287 // write more.
1288 if (!CanWrite(HAS_RETRANSMITTABLE_DATA)) {
1289 return;
1292 { // Limit the scope of the bundler. ACK inclusion happens elsewhere.
1293 ScopedPacketBundler bundler(this, NO_ACK);
1294 visitor_->OnCanWrite();
1297 // After the visitor writes, it may have caused the socket to become write
1298 // blocked or the congestion manager to prohibit sending, so check again.
1299 if (visitor_->WillingAndAbleToWrite() &&
1300 !resume_writes_alarm_->IsSet() &&
1301 CanWrite(HAS_RETRANSMITTABLE_DATA)) {
1302 // We're not write blocked, but some stream didn't write out all of its
1303 // bytes. Register for 'immediate' resumption so we'll keep writing after
1304 // other connections and events have had a chance to use the thread.
1305 resume_writes_alarm_->Set(clock_->ApproximateNow());
1309 void QuicConnection::WriteIfNotBlocked() {
1310 if (!writer_->IsWriteBlocked()) {
1311 OnCanWrite();
1315 bool QuicConnection::ProcessValidatedPacket() {
1316 if (peer_ip_changed_ || self_ip_changed_ || self_port_changed_) {
1317 SendConnectionCloseWithDetails(
1318 QUIC_ERROR_MIGRATING_ADDRESS,
1319 "Neither IP address migration, nor self port migration are supported.");
1320 return false;
1323 // Peer port migration is supported, do it now if port has changed.
1324 if (peer_port_changed_) {
1325 DVLOG(1) << ENDPOINT << "Peer's port changed from "
1326 << peer_address_.port() << " to " << migrating_peer_port_
1327 << ", migrating connection.";
1328 peer_address_ = IPEndPoint(peer_address_.address(), migrating_peer_port_);
1331 time_of_last_received_packet_ = clock_->Now();
1332 DVLOG(1) << ENDPOINT << "time of last received packet: "
1333 << time_of_last_received_packet_.ToDebuggingValue();
1335 if (perspective_ == Perspective::IS_SERVER &&
1336 encryption_level_ == ENCRYPTION_NONE &&
1337 last_size_ > packet_generator_.max_packet_length()) {
1338 set_max_packet_length(last_size_);
1340 return true;
1343 void QuicConnection::WriteQueuedPackets() {
1344 DCHECK(!writer_->IsWriteBlocked());
1346 if (pending_version_negotiation_packet_) {
1347 SendVersionNegotiationPacket();
1350 QueuedPacketList::iterator packet_iterator = queued_packets_.begin();
1351 while (packet_iterator != queued_packets_.end() &&
1352 WritePacket(&(*packet_iterator))) {
1353 packet_iterator = queued_packets_.erase(packet_iterator);
1357 void QuicConnection::WritePendingRetransmissions() {
1358 // Keep writing as long as there's a pending retransmission which can be
1359 // written.
1360 while (sent_packet_manager_.HasPendingRetransmissions()) {
1361 const QuicSentPacketManager::PendingRetransmission pending =
1362 sent_packet_manager_.NextPendingRetransmission();
1363 if (!CanWrite(HAS_RETRANSMITTABLE_DATA)) {
1364 break;
1367 // Re-packetize the frames with a new sequence number for retransmission.
1368 // Retransmitted data packets do not use FEC, even when it's enabled.
1369 // Retransmitted packets use the same sequence number length as the
1370 // original.
1371 // Flush the packet generator before making a new packet.
1372 // TODO(ianswett): Implement ReserializeAllFrames as a separate path that
1373 // does not require the creator to be flushed.
1374 packet_generator_.FlushAllQueuedFrames();
1375 SerializedPacket serialized_packet = packet_generator_.ReserializeAllFrames(
1376 pending.retransmittable_frames, pending.sequence_number_length);
1377 if (serialized_packet.packet == nullptr) {
1378 // We failed to serialize the packet, so close the connection.
1379 // CloseConnection does not send close packet, so no infinite loop here.
1380 CloseConnection(QUIC_ENCRYPTION_FAILURE, false);
1381 return;
1384 DVLOG(1) << ENDPOINT << "Retransmitting " << pending.sequence_number
1385 << " as " << serialized_packet.sequence_number;
1386 SendOrQueuePacket(
1387 QueuedPacket(serialized_packet,
1388 pending.retransmittable_frames.encryption_level(),
1389 pending.transmission_type,
1390 pending.sequence_number));
1394 void QuicConnection::RetransmitUnackedPackets(
1395 TransmissionType retransmission_type) {
1396 sent_packet_manager_.RetransmitUnackedPackets(retransmission_type);
1398 WriteIfNotBlocked();
1401 void QuicConnection::NeuterUnencryptedPackets() {
1402 sent_packet_manager_.NeuterUnencryptedPackets();
1403 // This may have changed the retransmission timer, so re-arm it.
1404 QuicTime retransmission_time = sent_packet_manager_.GetRetransmissionTime();
1405 retransmission_alarm_->Update(retransmission_time,
1406 QuicTime::Delta::FromMilliseconds(1));
1409 bool QuicConnection::ShouldGeneratePacket(
1410 TransmissionType transmission_type,
1411 HasRetransmittableData retransmittable,
1412 IsHandshake handshake) {
1413 // We should serialize handshake packets immediately to ensure that they
1414 // end up sent at the right encryption level.
1415 if (handshake == IS_HANDSHAKE) {
1416 return true;
1419 return CanWrite(retransmittable);
1422 bool QuicConnection::CanWrite(HasRetransmittableData retransmittable) {
1423 if (!connected_) {
1424 return false;
1427 if (writer_->IsWriteBlocked()) {
1428 visitor_->OnWriteBlocked();
1429 return false;
1432 QuicTime now = clock_->Now();
1433 QuicTime::Delta delay = sent_packet_manager_.TimeUntilSend(
1434 now, retransmittable);
1435 if (delay.IsInfinite()) {
1436 send_alarm_->Cancel();
1437 return false;
1440 // If the scheduler requires a delay, then we can not send this packet now.
1441 if (!delay.IsZero()) {
1442 send_alarm_->Update(now.Add(delay), QuicTime::Delta::FromMilliseconds(1));
1443 DVLOG(1) << ENDPOINT << "Delaying sending " << delay.ToMilliseconds()
1444 << "ms";
1445 return false;
1447 send_alarm_->Cancel();
1448 return true;
1451 bool QuicConnection::WritePacket(QueuedPacket* packet) {
1452 if (!WritePacketInner(packet)) {
1453 return false;
1455 delete packet->serialized_packet.retransmittable_frames;
1456 delete packet->serialized_packet.packet;
1457 packet->serialized_packet.retransmittable_frames = nullptr;
1458 packet->serialized_packet.packet = nullptr;
1459 return true;
1462 bool QuicConnection::WritePacketInner(QueuedPacket* packet) {
1463 if (ShouldDiscardPacket(*packet)) {
1464 ++stats_.packets_discarded;
1465 return true;
1467 // Connection close packets are encrypted and saved, so don't exit early.
1468 const bool is_connection_close = IsConnectionClose(*packet);
1469 if (writer_->IsWriteBlocked() && !is_connection_close) {
1470 return false;
1473 QuicPacketSequenceNumber sequence_number =
1474 packet->serialized_packet.sequence_number;
1475 DCHECK_LE(sequence_number_of_last_sent_packet_, sequence_number);
1476 sequence_number_of_last_sent_packet_ = sequence_number;
1478 QuicEncryptedPacket* encrypted = packet->serialized_packet.packet;
1479 // Connection close packets are eventually owned by TimeWaitListManager.
1480 // Others are deleted at the end of this call.
1481 if (is_connection_close) {
1482 DCHECK(connection_close_packet_.get() == nullptr);
1483 connection_close_packet_.reset(encrypted);
1484 packet->serialized_packet.packet = nullptr;
1485 // This assures we won't try to write *forced* packets when blocked.
1486 // Return true to stop processing.
1487 if (writer_->IsWriteBlocked()) {
1488 visitor_->OnWriteBlocked();
1489 return true;
1493 if (!FLAGS_quic_allow_oversized_packets_for_test) {
1494 DCHECK_LE(encrypted->length(), kMaxPacketSize);
1496 DCHECK_LE(encrypted->length(), packet_generator_.max_packet_length());
1497 DVLOG(1) << ENDPOINT << "Sending packet " << sequence_number << " : "
1498 << (packet->serialized_packet.is_fec_packet
1499 ? "FEC "
1500 : (IsRetransmittable(*packet) == HAS_RETRANSMITTABLE_DATA
1501 ? "data bearing "
1502 : " ack only ")) << ", encryption level: "
1503 << QuicUtils::EncryptionLevelToString(packet->encryption_level)
1504 << ", encrypted length:" << encrypted->length();
1505 DVLOG(2) << ENDPOINT << "packet(" << sequence_number << "): " << std::endl
1506 << QuicUtils::StringToHexASCIIDump(encrypted->AsStringPiece());
1508 // Measure the RTT from before the write begins to avoid underestimating the
1509 // min_rtt_, especially in cases where the thread blocks or gets swapped out
1510 // during the WritePacket below.
1511 QuicTime packet_send_time = clock_->Now();
1512 WriteResult result = writer_->WritePacket(encrypted->data(),
1513 encrypted->length(),
1514 self_address().address(),
1515 peer_address());
1516 if (result.error_code == ERR_IO_PENDING) {
1517 DCHECK_EQ(WRITE_STATUS_BLOCKED, result.status);
1520 if (result.status == WRITE_STATUS_BLOCKED) {
1521 visitor_->OnWriteBlocked();
1522 // If the socket buffers the the data, then the packet should not
1523 // be queued and sent again, which would result in an unnecessary
1524 // duplicate packet being sent. The helper must call OnCanWrite
1525 // when the write completes, and OnWriteError if an error occurs.
1526 if (!writer_->IsWriteBlockedDataBuffered()) {
1527 return false;
1530 if (result.status != WRITE_STATUS_ERROR && debug_visitor_ != nullptr) {
1531 // Pass the write result to the visitor.
1532 debug_visitor_->OnPacketSent(packet->serialized_packet,
1533 packet->original_sequence_number,
1534 packet->encryption_level,
1535 packet->transmission_type,
1536 *encrypted,
1537 packet_send_time);
1539 if (packet->transmission_type == NOT_RETRANSMISSION) {
1540 time_of_last_sent_new_packet_ = packet_send_time;
1542 SetPingAlarm();
1543 MaybeSetFecAlarm(sequence_number);
1544 DVLOG(1) << ENDPOINT << "time we began writing last sent packet: "
1545 << packet_send_time.ToDebuggingValue();
1547 // TODO(ianswett): Change the sequence number length and other packet creator
1548 // options by a more explicit API than setting a struct value directly,
1549 // perhaps via the NetworkChangeVisitor.
1550 packet_generator_.UpdateSequenceNumberLength(
1551 sent_packet_manager_.least_packet_awaited_by_peer(),
1552 sent_packet_manager_.EstimateMaxPacketsInFlight(max_packet_length()));
1554 bool reset_retransmission_alarm = sent_packet_manager_.OnPacketSent(
1555 &packet->serialized_packet,
1556 packet->original_sequence_number,
1557 packet_send_time,
1558 encrypted->length(),
1559 packet->transmission_type,
1560 IsRetransmittable(*packet));
1562 if (reset_retransmission_alarm || !retransmission_alarm_->IsSet()) {
1563 retransmission_alarm_->Update(sent_packet_manager_.GetRetransmissionTime(),
1564 QuicTime::Delta::FromMilliseconds(1));
1567 stats_.bytes_sent += result.bytes_written;
1568 ++stats_.packets_sent;
1569 if (packet->transmission_type != NOT_RETRANSMISSION) {
1570 stats_.bytes_retransmitted += result.bytes_written;
1571 ++stats_.packets_retransmitted;
1574 if (result.status == WRITE_STATUS_ERROR) {
1575 OnWriteError(result.error_code);
1576 DLOG(ERROR) << ENDPOINT << "failed writing " << encrypted->length()
1577 << "bytes "
1578 << " from host " << self_address().ToStringWithoutPort()
1579 << " to address " << peer_address().ToString();
1580 return false;
1583 return true;
1586 bool QuicConnection::ShouldDiscardPacket(const QueuedPacket& packet) {
1587 if (!connected_) {
1588 DVLOG(1) << ENDPOINT
1589 << "Not sending packet as connection is disconnected.";
1590 return true;
1593 QuicPacketSequenceNumber sequence_number =
1594 packet.serialized_packet.sequence_number;
1595 if (encryption_level_ == ENCRYPTION_FORWARD_SECURE &&
1596 packet.encryption_level == ENCRYPTION_NONE) {
1597 // Drop packets that are NULL encrypted since the peer won't accept them
1598 // anymore.
1599 DVLOG(1) << ENDPOINT << "Dropping NULL encrypted packet: "
1600 << sequence_number << " since the connection is forward secure.";
1601 return true;
1604 // If a retransmission has been acked before sending, don't send it.
1605 // This occurs if a packet gets serialized, queued, then discarded.
1606 if (packet.transmission_type != NOT_RETRANSMISSION &&
1607 (!sent_packet_manager_.IsUnacked(packet.original_sequence_number) ||
1608 !sent_packet_manager_.HasRetransmittableFrames(
1609 packet.original_sequence_number))) {
1610 DVLOG(1) << ENDPOINT << "Dropping unacked packet: " << sequence_number
1611 << " A previous transmission was acked while write blocked.";
1612 return true;
1615 return false;
1618 void QuicConnection::OnWriteError(int error_code) {
1619 DVLOG(1) << ENDPOINT << "Write failed with error: " << error_code
1620 << " (" << ErrorToString(error_code) << ")";
1621 // We can't send an error as the socket is presumably borked.
1622 CloseConnection(QUIC_PACKET_WRITE_ERROR, false);
1625 void QuicConnection::OnSerializedPacket(
1626 const SerializedPacket& serialized_packet) {
1627 if (serialized_packet.packet == nullptr) {
1628 // We failed to serialize the packet, so close the connection.
1629 // CloseConnection does not send close packet, so no infinite loop here.
1630 CloseConnection(QUIC_ENCRYPTION_FAILURE, false);
1631 return;
1633 if (serialized_packet.retransmittable_frames) {
1634 sent_packet_manager_.OnSerializedPacket(serialized_packet);
1636 if (serialized_packet.is_fec_packet && fec_alarm_->IsSet()) {
1637 // If an FEC packet is serialized with the FEC alarm set, cancel the alarm.
1638 fec_alarm_->Cancel();
1640 SendOrQueuePacket(QueuedPacket(serialized_packet, encryption_level_));
1643 void QuicConnection::OnCongestionWindowChange() {
1644 packet_generator_.OnCongestionWindowChange(
1645 sent_packet_manager_.EstimateMaxPacketsInFlight(max_packet_length()));
1646 visitor_->OnCongestionWindowChange(clock_->ApproximateNow());
1649 void QuicConnection::OnRttChange() {
1650 // Uses the connection's smoothed RTT. If zero, uses initial_rtt.
1651 QuicTime::Delta rtt = sent_packet_manager_.GetRttStats()->smoothed_rtt();
1652 if (rtt.IsZero()) {
1653 rtt = QuicTime::Delta::FromMicroseconds(
1654 sent_packet_manager_.GetRttStats()->initial_rtt_us());
1656 packet_generator_.OnRttChange(rtt);
1659 void QuicConnection::OnHandshakeComplete() {
1660 sent_packet_manager_.SetHandshakeConfirmed();
1661 // The client should immediately ack the SHLO to confirm the handshake is
1662 // complete with the server.
1663 if (perspective_ == Perspective::IS_CLIENT && !ack_queued_) {
1664 ack_alarm_->Cancel();
1665 ack_alarm_->Set(clock_->ApproximateNow());
1669 void QuicConnection::SendOrQueuePacket(QueuedPacket packet) {
1670 // The caller of this function is responsible for checking CanWrite().
1671 if (packet.serialized_packet.packet == nullptr) {
1672 LOG(DFATAL)
1673 << "packet.serialized_packet.packet == nullptr in to SendOrQueuePacket";
1674 return;
1677 sent_entropy_manager_.RecordPacketEntropyHash(
1678 packet.serialized_packet.sequence_number,
1679 packet.serialized_packet.entropy_hash);
1680 if (!WritePacket(&packet)) {
1681 queued_packets_.push_back(packet);
1684 // If a forward-secure encrypter is available but is not being used and the
1685 // next sequence number is the first packet which requires
1686 // forward security, start using the forward-secure encrypter.
1687 if (encryption_level_ != ENCRYPTION_FORWARD_SECURE &&
1688 has_forward_secure_encrypter_ &&
1689 packet.serialized_packet.sequence_number >=
1690 first_required_forward_secure_packet_ - 1) {
1691 SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
1695 void QuicConnection::SendPing() {
1696 if (retransmission_alarm_->IsSet()) {
1697 return;
1699 packet_generator_.AddControlFrame(QuicFrame(new QuicPingFrame));
1702 void QuicConnection::SendAck() {
1703 ack_alarm_->Cancel();
1704 stop_waiting_count_ = 0;
1705 num_packets_received_since_last_ack_sent_ = 0;
1707 packet_generator_.SetShouldSendAck(true);
1710 void QuicConnection::OnRetransmissionTimeout() {
1711 if (!sent_packet_manager_.HasUnackedPackets()) {
1712 return;
1715 sent_packet_manager_.OnRetransmissionTimeout();
1716 WriteIfNotBlocked();
1718 // A write failure can result in the connection being closed, don't attempt to
1719 // write further packets, or to set alarms.
1720 if (!connected_) {
1721 return;
1724 // In the TLP case, the SentPacketManager gives the connection the opportunity
1725 // to send new data before retransmitting.
1726 if (sent_packet_manager_.MaybeRetransmitTailLossProbe()) {
1727 // Send the pending retransmission now that it's been queued.
1728 WriteIfNotBlocked();
1731 // Ensure the retransmission alarm is always set if there are unacked packets
1732 // and nothing waiting to be sent.
1733 if (!HasQueuedData() && !retransmission_alarm_->IsSet()) {
1734 QuicTime rto_timeout = sent_packet_manager_.GetRetransmissionTime();
1735 if (rto_timeout.IsInitialized()) {
1736 retransmission_alarm_->Set(rto_timeout);
1741 void QuicConnection::SetEncrypter(EncryptionLevel level,
1742 QuicEncrypter* encrypter) {
1743 packet_generator_.SetEncrypter(level, encrypter);
1744 if (level == ENCRYPTION_FORWARD_SECURE) {
1745 has_forward_secure_encrypter_ = true;
1746 first_required_forward_secure_packet_ =
1747 sequence_number_of_last_sent_packet_ +
1748 // 3 times the current congestion window (in slow start) should cover
1749 // about two full round trips worth of packets, which should be
1750 // sufficient.
1751 3 * sent_packet_manager_.EstimateMaxPacketsInFlight(
1752 max_packet_length());
1756 void QuicConnection::SetDefaultEncryptionLevel(EncryptionLevel level) {
1757 encryption_level_ = level;
1758 packet_generator_.set_encryption_level(level);
1761 void QuicConnection::SetDecrypter(QuicDecrypter* decrypter,
1762 EncryptionLevel level) {
1763 framer_.SetDecrypter(decrypter, level);
1766 void QuicConnection::SetAlternativeDecrypter(QuicDecrypter* decrypter,
1767 EncryptionLevel level,
1768 bool latch_once_used) {
1769 framer_.SetAlternativeDecrypter(decrypter, level, latch_once_used);
1772 const QuicDecrypter* QuicConnection::decrypter() const {
1773 return framer_.decrypter();
1776 const QuicDecrypter* QuicConnection::alternative_decrypter() const {
1777 return framer_.alternative_decrypter();
1780 void QuicConnection::QueueUndecryptablePacket(
1781 const QuicEncryptedPacket& packet) {
1782 DVLOG(1) << ENDPOINT << "Queueing undecryptable packet.";
1783 undecryptable_packets_.push_back(packet.Clone());
1786 void QuicConnection::MaybeProcessUndecryptablePackets() {
1787 if (undecryptable_packets_.empty() || encryption_level_ == ENCRYPTION_NONE) {
1788 return;
1791 while (connected_ && !undecryptable_packets_.empty()) {
1792 DVLOG(1) << ENDPOINT << "Attempting to process undecryptable packet";
1793 QuicEncryptedPacket* packet = undecryptable_packets_.front();
1794 if (!framer_.ProcessPacket(*packet) &&
1795 framer_.error() == QUIC_DECRYPTION_FAILURE) {
1796 DVLOG(1) << ENDPOINT << "Unable to process undecryptable packet...";
1797 break;
1799 DVLOG(1) << ENDPOINT << "Processed undecryptable packet!";
1800 ++stats_.packets_processed;
1801 delete packet;
1802 undecryptable_packets_.pop_front();
1805 // Once forward secure encryption is in use, there will be no
1806 // new keys installed and hence any undecryptable packets will
1807 // never be able to be decrypted.
1808 if (encryption_level_ == ENCRYPTION_FORWARD_SECURE) {
1809 if (debug_visitor_ != nullptr) {
1810 // TODO(rtenneti): perhaps more efficient to pass the number of
1811 // undecryptable packets as the argument to OnUndecryptablePacket so that
1812 // we just need to call OnUndecryptablePacket once?
1813 for (size_t i = 0; i < undecryptable_packets_.size(); ++i) {
1814 debug_visitor_->OnUndecryptablePacket();
1817 STLDeleteElements(&undecryptable_packets_);
1821 void QuicConnection::MaybeProcessRevivedPacket() {
1822 QuicFecGroup* group = GetFecGroup();
1823 if (!connected_ || group == nullptr || !group->CanRevive()) {
1824 return;
1826 QuicPacketHeader revived_header;
1827 char revived_payload[kMaxPacketSize];
1828 size_t len = group->Revive(&revived_header, revived_payload, kMaxPacketSize);
1829 revived_header.public_header.connection_id = connection_id_;
1830 revived_header.public_header.connection_id_length =
1831 last_header_.public_header.connection_id_length;
1832 revived_header.public_header.version_flag = false;
1833 revived_header.public_header.reset_flag = false;
1834 revived_header.public_header.sequence_number_length =
1835 last_header_.public_header.sequence_number_length;
1836 revived_header.fec_flag = false;
1837 revived_header.is_in_fec_group = NOT_IN_FEC_GROUP;
1838 revived_header.fec_group = 0;
1839 group_map_.erase(last_header_.fec_group);
1840 last_decrypted_packet_level_ = group->effective_encryption_level();
1841 DCHECK_LT(last_decrypted_packet_level_, NUM_ENCRYPTION_LEVELS);
1842 delete group;
1844 last_packet_revived_ = true;
1845 if (debug_visitor_ != nullptr) {
1846 debug_visitor_->OnRevivedPacket(revived_header,
1847 StringPiece(revived_payload, len));
1850 ++stats_.packets_revived;
1851 framer_.ProcessRevivedPacket(&revived_header,
1852 StringPiece(revived_payload, len));
1855 QuicFecGroup* QuicConnection::GetFecGroup() {
1856 QuicFecGroupNumber fec_group_num = last_header_.fec_group;
1857 if (fec_group_num == 0) {
1858 return nullptr;
1860 if (!ContainsKey(group_map_, fec_group_num)) {
1861 if (group_map_.size() >= kMaxFecGroups) { // Too many groups
1862 if (fec_group_num < group_map_.begin()->first) {
1863 // The group being requested is a group we've seen before and deleted.
1864 // Don't recreate it.
1865 return nullptr;
1867 // Clear the lowest group number.
1868 delete group_map_.begin()->second;
1869 group_map_.erase(group_map_.begin());
1871 group_map_[fec_group_num] = new QuicFecGroup();
1873 return group_map_[fec_group_num];
1876 void QuicConnection::SendConnectionClose(QuicErrorCode error) {
1877 SendConnectionCloseWithDetails(error, string());
1880 void QuicConnection::SendConnectionCloseWithDetails(QuicErrorCode error,
1881 const string& details) {
1882 // If we're write blocked, WritePacket() will not send, but will capture the
1883 // serialized packet.
1884 SendConnectionClosePacket(error, details);
1885 if (connected_) {
1886 // It's possible that while sending the connection close packet, we get a
1887 // socket error and disconnect right then and there. Avoid a double
1888 // disconnect in that case.
1889 CloseConnection(error, false);
1893 void QuicConnection::SendConnectionClosePacket(QuicErrorCode error,
1894 const string& details) {
1895 DVLOG(1) << ENDPOINT << "Force closing " << connection_id()
1896 << " with error " << QuicUtils::ErrorToString(error)
1897 << " (" << error << ") " << details;
1898 // Don't send explicit connection close packets for timeouts.
1899 // This is particularly important on mobile, where connections are short.
1900 if (silent_close_enabled_ &&
1901 error == QuicErrorCode::QUIC_CONNECTION_TIMED_OUT) {
1902 return;
1904 ScopedPacketBundler ack_bundler(this, SEND_ACK);
1905 QuicConnectionCloseFrame* frame = new QuicConnectionCloseFrame();
1906 frame->error_code = error;
1907 frame->error_details = details;
1908 packet_generator_.AddControlFrame(QuicFrame(frame));
1909 packet_generator_.FlushAllQueuedFrames();
1912 void QuicConnection::CloseConnection(QuicErrorCode error, bool from_peer) {
1913 if (!connected_) {
1914 DLOG(DFATAL) << "Error: attempt to close an already closed connection"
1915 << base::debug::StackTrace().ToString();
1916 return;
1918 connected_ = false;
1919 if (debug_visitor_ != nullptr) {
1920 debug_visitor_->OnConnectionClosed(error, from_peer);
1922 DCHECK(visitor_ != nullptr);
1923 visitor_->OnConnectionClosed(error, from_peer);
1924 // Cancel the alarms so they don't trigger any action now that the
1925 // connection is closed.
1926 ack_alarm_->Cancel();
1927 ping_alarm_->Cancel();
1928 fec_alarm_->Cancel();
1929 resume_writes_alarm_->Cancel();
1930 retransmission_alarm_->Cancel();
1931 send_alarm_->Cancel();
1932 timeout_alarm_->Cancel();
1935 void QuicConnection::SendGoAway(QuicErrorCode error,
1936 QuicStreamId last_good_stream_id,
1937 const string& reason) {
1938 DVLOG(1) << ENDPOINT << "Going away with error "
1939 << QuicUtils::ErrorToString(error)
1940 << " (" << error << ")";
1942 // Opportunistically bundle an ack with this outgoing packet.
1943 ScopedPacketBundler ack_bundler(this, BUNDLE_PENDING_ACK);
1944 packet_generator_.AddControlFrame(
1945 QuicFrame(new QuicGoAwayFrame(error, last_good_stream_id, reason)));
1948 void QuicConnection::CloseFecGroupsBefore(
1949 QuicPacketSequenceNumber sequence_number) {
1950 FecGroupMap::iterator it = group_map_.begin();
1951 while (it != group_map_.end()) {
1952 // If this is the current group or the group doesn't protect this packet
1953 // we can ignore it.
1954 if (last_header_.fec_group == it->first ||
1955 !it->second->ProtectsPacketsBefore(sequence_number)) {
1956 ++it;
1957 continue;
1959 QuicFecGroup* fec_group = it->second;
1960 DCHECK(!fec_group->CanRevive());
1961 FecGroupMap::iterator next = it;
1962 ++next;
1963 group_map_.erase(it);
1964 delete fec_group;
1965 it = next;
1969 QuicByteCount QuicConnection::max_packet_length() const {
1970 return packet_generator_.max_packet_length();
1973 void QuicConnection::set_max_packet_length(QuicByteCount length) {
1974 return packet_generator_.set_max_packet_length(length);
1977 bool QuicConnection::HasQueuedData() const {
1978 return pending_version_negotiation_packet_ ||
1979 !queued_packets_.empty() || packet_generator_.HasQueuedFrames();
1982 bool QuicConnection::CanWriteStreamData() {
1983 // Don't write stream data if there are negotiation or queued data packets
1984 // to send. Otherwise, continue and bundle as many frames as possible.
1985 if (pending_version_negotiation_packet_ || !queued_packets_.empty()) {
1986 return false;
1989 IsHandshake pending_handshake = visitor_->HasPendingHandshake() ?
1990 IS_HANDSHAKE : NOT_HANDSHAKE;
1991 // Sending queued packets may have caused the socket to become write blocked,
1992 // or the congestion manager to prohibit sending. If we've sent everything
1993 // we had queued and we're still not blocked, let the visitor know it can
1994 // write more.
1995 return ShouldGeneratePacket(NOT_RETRANSMISSION, HAS_RETRANSMITTABLE_DATA,
1996 pending_handshake);
1999 void QuicConnection::SetNetworkTimeouts(QuicTime::Delta overall_timeout,
2000 QuicTime::Delta idle_timeout) {
2001 LOG_IF(DFATAL, idle_timeout > overall_timeout)
2002 << "idle_timeout:" << idle_timeout.ToMilliseconds()
2003 << " overall_timeout:" << overall_timeout.ToMilliseconds();
2004 // Adjust the idle timeout on client and server to prevent clients from
2005 // sending requests to servers which have already closed the connection.
2006 if (perspective_ == Perspective::IS_SERVER) {
2007 idle_timeout = idle_timeout.Add(QuicTime::Delta::FromSeconds(3));
2008 } else if (idle_timeout > QuicTime::Delta::FromSeconds(1)) {
2009 idle_timeout = idle_timeout.Subtract(QuicTime::Delta::FromSeconds(1));
2011 overall_connection_timeout_ = overall_timeout;
2012 idle_network_timeout_ = idle_timeout;
2014 SetTimeoutAlarm();
2017 void QuicConnection::CheckForTimeout() {
2018 QuicTime now = clock_->ApproximateNow();
2019 QuicTime time_of_last_packet = max(time_of_last_received_packet_,
2020 time_of_last_sent_new_packet_);
2022 // |delta| can be < 0 as |now| is approximate time but |time_of_last_packet|
2023 // is accurate time. However, this should not change the behavior of
2024 // timeout handling.
2025 QuicTime::Delta idle_duration = now.Subtract(time_of_last_packet);
2026 DVLOG(1) << ENDPOINT << "last packet "
2027 << time_of_last_packet.ToDebuggingValue()
2028 << " now:" << now.ToDebuggingValue()
2029 << " idle_duration:" << idle_duration.ToMicroseconds()
2030 << " idle_network_timeout: "
2031 << idle_network_timeout_.ToMicroseconds();
2032 if (idle_duration >= idle_network_timeout_) {
2033 DVLOG(1) << ENDPOINT << "Connection timedout due to no network activity.";
2034 SendConnectionClose(QUIC_CONNECTION_TIMED_OUT);
2035 return;
2038 if (!overall_connection_timeout_.IsInfinite()) {
2039 QuicTime::Delta connected_duration =
2040 now.Subtract(stats_.connection_creation_time);
2041 DVLOG(1) << ENDPOINT << "connection time: "
2042 << connected_duration.ToMicroseconds() << " overall timeout: "
2043 << overall_connection_timeout_.ToMicroseconds();
2044 if (connected_duration >= overall_connection_timeout_) {
2045 DVLOG(1) << ENDPOINT <<
2046 "Connection timedout due to overall connection timeout.";
2047 SendConnectionClose(QUIC_CONNECTION_OVERALL_TIMED_OUT);
2048 return;
2052 SetTimeoutAlarm();
2055 void QuicConnection::SetTimeoutAlarm() {
2056 QuicTime time_of_last_packet = max(time_of_last_received_packet_,
2057 time_of_last_sent_new_packet_);
2059 QuicTime deadline = time_of_last_packet.Add(idle_network_timeout_);
2060 if (!overall_connection_timeout_.IsInfinite()) {
2061 deadline = min(deadline,
2062 stats_.connection_creation_time.Add(
2063 overall_connection_timeout_));
2066 timeout_alarm_->Cancel();
2067 timeout_alarm_->Set(deadline);
2070 void QuicConnection::SetPingAlarm() {
2071 if (perspective_ == Perspective::IS_SERVER) {
2072 // Only clients send pings.
2073 return;
2075 if (!visitor_->HasOpenDataStreams()) {
2076 ping_alarm_->Cancel();
2077 // Don't send a ping unless there are open streams.
2078 return;
2080 QuicTime::Delta ping_timeout = QuicTime::Delta::FromSeconds(kPingTimeoutSecs);
2081 ping_alarm_->Update(clock_->ApproximateNow().Add(ping_timeout),
2082 QuicTime::Delta::FromSeconds(1));
2085 QuicConnection::ScopedPacketBundler::ScopedPacketBundler(
2086 QuicConnection* connection,
2087 AckBundling send_ack)
2088 : connection_(connection),
2089 already_in_batch_mode_(connection != nullptr &&
2090 connection->packet_generator_.InBatchMode()) {
2091 if (connection_ == nullptr) {
2092 return;
2094 // Move generator into batch mode. If caller wants us to include an ack,
2095 // check the delayed-ack timer to see if there's ack info to be sent.
2096 if (!already_in_batch_mode_) {
2097 DVLOG(1) << "Entering Batch Mode.";
2098 connection_->packet_generator_.StartBatchOperations();
2100 // Bundle an ack if the alarm is set or with every second packet if we need to
2101 // raise the peer's least unacked.
2102 bool ack_pending =
2103 connection_->ack_alarm_->IsSet() || connection_->stop_waiting_count_ > 1;
2104 if (send_ack == SEND_ACK || (send_ack == BUNDLE_PENDING_ACK && ack_pending)) {
2105 DVLOG(1) << "Bundling ack with outgoing packet.";
2106 connection_->SendAck();
2110 QuicConnection::ScopedPacketBundler::~ScopedPacketBundler() {
2111 if (connection_ == nullptr) {
2112 return;
2114 // If we changed the generator's batch state, restore original batch state.
2115 if (!already_in_batch_mode_) {
2116 DVLOG(1) << "Leaving Batch Mode.";
2117 connection_->packet_generator_.FinishBatchOperations();
2119 DCHECK_EQ(already_in_batch_mode_,
2120 connection_->packet_generator_.InBatchMode());
2123 HasRetransmittableData QuicConnection::IsRetransmittable(
2124 const QueuedPacket& packet) {
2125 // Retransmitted packets retransmittable frames are owned by the unacked
2126 // packet map, but are not present in the serialized packet.
2127 if (packet.transmission_type != NOT_RETRANSMISSION ||
2128 packet.serialized_packet.retransmittable_frames != nullptr) {
2129 return HAS_RETRANSMITTABLE_DATA;
2130 } else {
2131 return NO_RETRANSMITTABLE_DATA;
2135 bool QuicConnection::IsConnectionClose(const QueuedPacket& packet) {
2136 const RetransmittableFrames* retransmittable_frames =
2137 packet.serialized_packet.retransmittable_frames;
2138 if (retransmittable_frames == nullptr) {
2139 return false;
2141 for (const QuicFrame& frame : retransmittable_frames->frames()) {
2142 if (frame.type == CONNECTION_CLOSE_FRAME) {
2143 return true;
2146 return false;
2149 } // namespace net