Refactors gesture conversion functions to ui/events/blink
[chromium-blink-merge.git] / net / quic / quic_connection.cc
blobe6a3d8ce71f674fc32951ec444ced242856de482
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/quic_bandwidth.h"
28 #include "net/quic/quic_config.h"
29 #include "net/quic/quic_fec_group.h"
30 #include "net/quic/quic_flags.h"
31 #include "net/quic/quic_packet_generator.h"
32 #include "net/quic/quic_utils.h"
34 using base::StringPiece;
35 using base::StringPrintf;
36 using base::hash_map;
37 using base::hash_set;
38 using std::list;
39 using std::make_pair;
40 using std::max;
41 using std::min;
42 using std::numeric_limits;
43 using std::set;
44 using std::string;
45 using std::vector;
47 namespace net {
49 class QuicDecrypter;
50 class QuicEncrypter;
52 namespace {
54 // The largest gap in packets we'll accept without closing the connection.
55 // This will likely have to be tuned.
56 const QuicPacketSequenceNumber kMaxPacketGap = 5000;
58 // Limit the number of FEC groups to two. If we get enough out of order packets
59 // that this becomes limiting, we can revisit.
60 const size_t kMaxFecGroups = 2;
62 // Maximum number of acks received before sending an ack in response.
63 const QuicPacketCount kMaxPacketsReceivedBeforeAckSend = 20;
65 // Maximum number of tracked packets.
66 const QuicPacketCount kMaxTrackedPackets = 5 * kMaxTcpCongestionWindow;
68 bool Near(QuicPacketSequenceNumber a, QuicPacketSequenceNumber b) {
69 QuicPacketSequenceNumber delta = (a > b) ? a - b : b - a;
70 return delta <= kMaxPacketGap;
73 // An alarm that is scheduled to send an ack if a timeout occurs.
74 class AckAlarm : public QuicAlarm::Delegate {
75 public:
76 explicit AckAlarm(QuicConnection* connection)
77 : connection_(connection) {
80 QuicTime OnAlarm() override {
81 connection_->SendAck();
82 return QuicTime::Zero();
85 private:
86 QuicConnection* connection_;
88 DISALLOW_COPY_AND_ASSIGN(AckAlarm);
91 // This alarm will be scheduled any time a data-bearing packet is sent out.
92 // When the alarm goes off, the connection checks to see if the oldest packets
93 // have been acked, and retransmit them if they have not.
94 class RetransmissionAlarm : public QuicAlarm::Delegate {
95 public:
96 explicit RetransmissionAlarm(QuicConnection* connection)
97 : connection_(connection) {
100 QuicTime OnAlarm() override {
101 connection_->OnRetransmissionTimeout();
102 return QuicTime::Zero();
105 private:
106 QuicConnection* connection_;
108 DISALLOW_COPY_AND_ASSIGN(RetransmissionAlarm);
111 // An alarm that is scheduled when the sent scheduler requires a
112 // a delay before sending packets and fires when the packet may be sent.
113 class SendAlarm : public QuicAlarm::Delegate {
114 public:
115 explicit SendAlarm(QuicConnection* connection)
116 : connection_(connection) {
119 QuicTime OnAlarm() override {
120 connection_->WriteIfNotBlocked();
121 // Never reschedule the alarm, since CanWrite does that.
122 return QuicTime::Zero();
125 private:
126 QuicConnection* connection_;
128 DISALLOW_COPY_AND_ASSIGN(SendAlarm);
131 class TimeoutAlarm : public QuicAlarm::Delegate {
132 public:
133 explicit TimeoutAlarm(QuicConnection* connection)
134 : connection_(connection) {
137 QuicTime OnAlarm() override {
138 connection_->CheckForTimeout();
139 // Never reschedule the alarm, since CheckForTimeout does that.
140 return QuicTime::Zero();
143 private:
144 QuicConnection* connection_;
146 DISALLOW_COPY_AND_ASSIGN(TimeoutAlarm);
149 class PingAlarm : public QuicAlarm::Delegate {
150 public:
151 explicit PingAlarm(QuicConnection* connection)
152 : connection_(connection) {
155 QuicTime OnAlarm() override {
156 connection_->SendPing();
157 return QuicTime::Zero();
160 private:
161 QuicConnection* connection_;
163 DISALLOW_COPY_AND_ASSIGN(PingAlarm);
166 // This alarm may be scheduled when an FEC protected packet is sent out.
167 class FecAlarm : public QuicAlarm::Delegate {
168 public:
169 explicit FecAlarm(QuicPacketGenerator* packet_generator)
170 : packet_generator_(packet_generator) {}
172 QuicTime OnAlarm() override {
173 packet_generator_->OnFecTimeout();
174 return QuicTime::Zero();
177 private:
178 QuicPacketGenerator* packet_generator_;
180 DISALLOW_COPY_AND_ASSIGN(FecAlarm);
183 } // namespace
185 QuicConnection::QueuedPacket::QueuedPacket(SerializedPacket packet,
186 EncryptionLevel level)
187 : serialized_packet(packet),
188 encryption_level(level),
189 transmission_type(NOT_RETRANSMISSION),
190 original_sequence_number(0) {
193 QuicConnection::QueuedPacket::QueuedPacket(
194 SerializedPacket packet,
195 EncryptionLevel level,
196 TransmissionType transmission_type,
197 QuicPacketSequenceNumber original_sequence_number)
198 : serialized_packet(packet),
199 encryption_level(level),
200 transmission_type(transmission_type),
201 original_sequence_number(original_sequence_number) {
204 #define ENDPOINT \
205 (perspective_ == Perspective::IS_SERVER ? "Server: " : "Client: ")
207 QuicConnection::QuicConnection(QuicConnectionId connection_id,
208 IPEndPoint address,
209 QuicConnectionHelperInterface* helper,
210 const PacketWriterFactory& writer_factory,
211 bool owns_writer,
212 Perspective perspective,
213 bool is_secure,
214 const QuicVersionVector& supported_versions)
215 : framer_(supported_versions,
216 helper->GetClock()->ApproximateNow(),
217 perspective),
218 helper_(helper),
219 writer_(writer_factory.Create(this)),
220 owns_writer_(owns_writer),
221 encryption_level_(ENCRYPTION_NONE),
222 has_forward_secure_encrypter_(false),
223 first_required_forward_secure_packet_(0),
224 clock_(helper->GetClock()),
225 random_generator_(helper->GetRandomGenerator()),
226 connection_id_(connection_id),
227 peer_address_(address),
228 migrating_peer_port_(0),
229 last_packet_decrypted_(false),
230 last_packet_revived_(false),
231 last_size_(0),
232 last_decrypted_packet_level_(ENCRYPTION_NONE),
233 largest_seen_packet_with_ack_(0),
234 largest_seen_packet_with_stop_waiting_(0),
235 max_undecryptable_packets_(0),
236 pending_version_negotiation_packet_(false),
237 silent_close_enabled_(false),
238 received_packet_manager_(&stats_),
239 ack_queued_(false),
240 num_packets_received_since_last_ack_sent_(0),
241 stop_waiting_count_(0),
242 ack_alarm_(helper->CreateAlarm(new AckAlarm(this))),
243 retransmission_alarm_(helper->CreateAlarm(new RetransmissionAlarm(this))),
244 send_alarm_(helper->CreateAlarm(new SendAlarm(this))),
245 resume_writes_alarm_(helper->CreateAlarm(new SendAlarm(this))),
246 timeout_alarm_(helper->CreateAlarm(new TimeoutAlarm(this))),
247 ping_alarm_(helper->CreateAlarm(new PingAlarm(this))),
248 visitor_(nullptr),
249 debug_visitor_(nullptr),
250 packet_generator_(connection_id_, &framer_, random_generator_, this),
251 fec_alarm_(helper->CreateAlarm(new FecAlarm(&packet_generator_))),
252 idle_network_timeout_(QuicTime::Delta::Infinite()),
253 overall_connection_timeout_(QuicTime::Delta::Infinite()),
254 time_of_last_received_packet_(clock_->ApproximateNow()),
255 time_of_last_sent_new_packet_(clock_->ApproximateNow()),
256 sequence_number_of_last_sent_packet_(0),
257 sent_packet_manager_(
258 perspective,
259 clock_,
260 &stats_,
261 FLAGS_quic_use_bbr_congestion_control ? kBBR : kCubic,
262 FLAGS_quic_use_time_loss_detection ? kTime : kNack,
263 is_secure),
264 version_negotiation_state_(START_NEGOTIATION),
265 perspective_(perspective),
266 connected_(true),
267 peer_ip_changed_(false),
268 peer_port_changed_(false),
269 self_ip_changed_(false),
270 self_port_changed_(false),
271 can_truncate_connection_ids_(true),
272 is_secure_(is_secure) {
273 DVLOG(1) << ENDPOINT << "Created connection with connection_id: "
274 << connection_id;
275 framer_.set_visitor(this);
276 framer_.set_received_entropy_calculator(&received_packet_manager_);
277 stats_.connection_creation_time = clock_->ApproximateNow();
278 sent_packet_manager_.set_network_change_visitor(this);
279 if (FLAGS_quic_small_default_packet_size &&
280 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();
319 void QuicConnection::OnSendConnectionState(
320 const CachedNetworkParameters& cached_network_params) {
321 if (debug_visitor_ != nullptr) {
322 debug_visitor_->OnSendConnectionState(cached_network_params);
326 bool QuicConnection::ResumeConnectionState(
327 const CachedNetworkParameters& cached_network_params,
328 bool max_bandwidth_resumption) {
329 if (debug_visitor_ != nullptr) {
330 debug_visitor_->OnResumeConnectionState(cached_network_params);
332 return sent_packet_manager_.ResumeConnectionState(cached_network_params,
333 max_bandwidth_resumption);
336 void QuicConnection::SetNumOpenStreams(size_t num_streams) {
337 sent_packet_manager_.SetNumOpenStreams(num_streams);
340 bool QuicConnection::SelectMutualVersion(
341 const QuicVersionVector& available_versions) {
342 // Try to find the highest mutual version by iterating over supported
343 // versions, starting with the highest, and breaking out of the loop once we
344 // find a matching version in the provided available_versions vector.
345 const QuicVersionVector& supported_versions = framer_.supported_versions();
346 for (size_t i = 0; i < supported_versions.size(); ++i) {
347 const QuicVersion& version = supported_versions[i];
348 if (std::find(available_versions.begin(), available_versions.end(),
349 version) != available_versions.end()) {
350 framer_.set_version(version);
351 return true;
355 return false;
358 void QuicConnection::OnError(QuicFramer* framer) {
359 // Packets that we can not or have not decrypted are dropped.
360 // TODO(rch): add stats to measure this.
361 if (!connected_ || last_packet_decrypted_ == false) {
362 return;
364 SendConnectionCloseWithDetails(framer->error(), framer->detailed_error());
367 void QuicConnection::MaybeSetFecAlarm(
368 QuicPacketSequenceNumber sequence_number) {
369 if (fec_alarm_->IsSet()) {
370 return;
372 QuicTime::Delta timeout = packet_generator_.GetFecTimeout(sequence_number);
373 if (!timeout.IsInfinite()) {
374 fec_alarm_->Set(clock_->ApproximateNow().Add(timeout));
378 void QuicConnection::OnPacket() {
379 DCHECK(last_stream_frames_.empty() &&
380 last_ack_frames_.empty() &&
381 last_stop_waiting_frames_.empty() &&
382 last_rst_frames_.empty() &&
383 last_goaway_frames_.empty() &&
384 last_window_update_frames_.empty() &&
385 last_blocked_frames_.empty() &&
386 last_ping_frames_.empty() &&
387 last_close_frames_.empty());
388 last_packet_decrypted_ = false;
389 last_packet_revived_ = false;
392 void QuicConnection::OnPublicResetPacket(
393 const QuicPublicResetPacket& packet) {
394 if (debug_visitor_ != nullptr) {
395 debug_visitor_->OnPublicResetPacket(packet);
397 CloseConnection(QUIC_PUBLIC_RESET, true);
399 DVLOG(1) << ENDPOINT << "Connection " << connection_id()
400 << " closed via QUIC_PUBLIC_RESET from peer.";
403 bool QuicConnection::OnProtocolVersionMismatch(QuicVersion received_version) {
404 DVLOG(1) << ENDPOINT << "Received packet with mismatched version "
405 << received_version;
406 // TODO(satyamshekhar): Implement no server state in this mode.
407 if (perspective_ == Perspective::IS_CLIENT) {
408 LOG(DFATAL) << ENDPOINT << "Framer called OnProtocolVersionMismatch. "
409 << "Closing connection.";
410 CloseConnection(QUIC_INTERNAL_ERROR, false);
411 return false;
413 DCHECK_NE(version(), received_version);
415 if (debug_visitor_ != nullptr) {
416 debug_visitor_->OnProtocolVersionMismatch(received_version);
419 switch (version_negotiation_state_) {
420 case START_NEGOTIATION:
421 if (!framer_.IsSupportedVersion(received_version)) {
422 SendVersionNegotiationPacket();
423 version_negotiation_state_ = NEGOTIATION_IN_PROGRESS;
424 return false;
426 break;
428 case NEGOTIATION_IN_PROGRESS:
429 if (!framer_.IsSupportedVersion(received_version)) {
430 SendVersionNegotiationPacket();
431 return false;
433 break;
435 case NEGOTIATED_VERSION:
436 // Might be old packets that were sent by the client before the version
437 // was negotiated. Drop these.
438 return false;
440 default:
441 DCHECK(false);
444 version_negotiation_state_ = NEGOTIATED_VERSION;
445 visitor_->OnSuccessfulVersionNegotiation(received_version);
446 if (debug_visitor_ != nullptr) {
447 debug_visitor_->OnSuccessfulVersionNegotiation(received_version);
449 DVLOG(1) << ENDPOINT << "version negotiated " << received_version;
451 // Store the new version.
452 framer_.set_version(received_version);
454 // TODO(satyamshekhar): Store the sequence number of this packet and close the
455 // connection if we ever received a packet with incorrect version and whose
456 // sequence number is greater.
457 return true;
460 // Handles version negotiation for client connection.
461 void QuicConnection::OnVersionNegotiationPacket(
462 const QuicVersionNegotiationPacket& packet) {
463 if (perspective_ == Perspective::IS_SERVER) {
464 LOG(DFATAL) << ENDPOINT << "Framer parsed VersionNegotiationPacket."
465 << " Closing connection.";
466 CloseConnection(QUIC_INTERNAL_ERROR, false);
467 return;
469 if (debug_visitor_ != nullptr) {
470 debug_visitor_->OnVersionNegotiationPacket(packet);
473 if (version_negotiation_state_ != START_NEGOTIATION) {
474 // Possibly a duplicate version negotiation packet.
475 return;
478 if (std::find(packet.versions.begin(),
479 packet.versions.end(), version()) !=
480 packet.versions.end()) {
481 DLOG(WARNING) << ENDPOINT << "The server already supports our version. "
482 << "It should have accepted our connection.";
483 // Just drop the connection.
484 CloseConnection(QUIC_INVALID_VERSION_NEGOTIATION_PACKET, false);
485 return;
488 if (!SelectMutualVersion(packet.versions)) {
489 SendConnectionCloseWithDetails(QUIC_INVALID_VERSION,
490 "no common version found");
491 return;
494 DVLOG(1) << ENDPOINT
495 << "Negotiated version: " << QuicVersionToString(version());
496 server_supported_versions_ = packet.versions;
497 version_negotiation_state_ = NEGOTIATION_IN_PROGRESS;
498 RetransmitUnackedPackets(ALL_UNACKED_RETRANSMISSION);
501 void QuicConnection::OnRevivedPacket() {
504 bool QuicConnection::OnUnauthenticatedPublicHeader(
505 const QuicPacketPublicHeader& header) {
506 return true;
509 bool QuicConnection::OnUnauthenticatedHeader(const QuicPacketHeader& header) {
510 return true;
513 void QuicConnection::OnDecryptedPacket(EncryptionLevel level) {
514 last_decrypted_packet_level_ = level;
515 last_packet_decrypted_ = true;
516 // If this packet was foward-secure encrypted and the forward-secure encrypter
517 // is not being used, start using it.
518 if (encryption_level_ != ENCRYPTION_FORWARD_SECURE &&
519 has_forward_secure_encrypter_ && level == ENCRYPTION_FORWARD_SECURE) {
520 SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
524 bool QuicConnection::OnPacketHeader(const QuicPacketHeader& header) {
525 if (debug_visitor_ != nullptr) {
526 debug_visitor_->OnPacketHeader(header);
529 if (!ProcessValidatedPacket()) {
530 return false;
533 // Will be decrement below if we fall through to return true;
534 ++stats_.packets_dropped;
536 if (header.public_header.connection_id != connection_id_) {
537 DVLOG(1) << ENDPOINT << "Ignoring packet from unexpected ConnectionId: "
538 << header.public_header.connection_id << " instead of "
539 << connection_id_;
540 if (debug_visitor_ != nullptr) {
541 debug_visitor_->OnIncorrectConnectionId(
542 header.public_header.connection_id);
544 return false;
547 if (!Near(header.packet_sequence_number,
548 last_header_.packet_sequence_number)) {
549 DVLOG(1) << ENDPOINT << "Packet " << header.packet_sequence_number
550 << " out of bounds. Discarding";
551 SendConnectionCloseWithDetails(QUIC_INVALID_PACKET_HEADER,
552 "Packet sequence number out of bounds");
553 return false;
556 // If this packet has already been seen, or that the sender
557 // has told us will not be retransmitted, then stop processing the packet.
558 if (!received_packet_manager_.IsAwaitingPacket(
559 header.packet_sequence_number)) {
560 DVLOG(1) << ENDPOINT << "Packet " << header.packet_sequence_number
561 << " no longer being waited for. Discarding.";
562 if (debug_visitor_ != nullptr) {
563 debug_visitor_->OnDuplicatePacket(header.packet_sequence_number);
565 return false;
568 if (version_negotiation_state_ != NEGOTIATED_VERSION) {
569 if (perspective_ == Perspective::IS_SERVER) {
570 if (!header.public_header.version_flag) {
571 DLOG(WARNING) << ENDPOINT << "Packet " << header.packet_sequence_number
572 << " without version flag before version negotiated.";
573 // Packets should have the version flag till version negotiation is
574 // done.
575 CloseConnection(QUIC_INVALID_VERSION, false);
576 return false;
577 } else {
578 DCHECK_EQ(1u, header.public_header.versions.size());
579 DCHECK_EQ(header.public_header.versions[0], version());
580 version_negotiation_state_ = NEGOTIATED_VERSION;
581 visitor_->OnSuccessfulVersionNegotiation(version());
582 if (debug_visitor_ != nullptr) {
583 debug_visitor_->OnSuccessfulVersionNegotiation(version());
586 } else {
587 DCHECK(!header.public_header.version_flag);
588 // If the client gets a packet without the version flag from the server
589 // it should stop sending version since the version negotiation is done.
590 packet_generator_.StopSendingVersion();
591 version_negotiation_state_ = NEGOTIATED_VERSION;
592 visitor_->OnSuccessfulVersionNegotiation(version());
593 if (debug_visitor_ != nullptr) {
594 debug_visitor_->OnSuccessfulVersionNegotiation(version());
599 DCHECK_EQ(NEGOTIATED_VERSION, version_negotiation_state_);
601 --stats_.packets_dropped;
602 DVLOG(1) << ENDPOINT << "Received packet header: " << header;
603 last_header_ = header;
604 DCHECK(connected_);
605 return true;
608 void QuicConnection::OnFecProtectedPayload(StringPiece payload) {
609 DCHECK_EQ(IN_FEC_GROUP, last_header_.is_in_fec_group);
610 DCHECK_NE(0u, last_header_.fec_group);
611 QuicFecGroup* group = GetFecGroup();
612 if (group != nullptr) {
613 group->Update(last_decrypted_packet_level_, last_header_, payload);
617 bool QuicConnection::OnStreamFrame(const QuicStreamFrame& frame) {
618 DCHECK(connected_);
619 if (debug_visitor_ != nullptr) {
620 debug_visitor_->OnStreamFrame(frame);
622 if (frame.stream_id != kCryptoStreamId &&
623 last_decrypted_packet_level_ == ENCRYPTION_NONE) {
624 DLOG(WARNING) << ENDPOINT
625 << "Received an unencrypted data frame: closing connection";
626 SendConnectionClose(QUIC_UNENCRYPTED_STREAM_DATA);
627 return false;
629 last_stream_frames_.push_back(frame);
630 return true;
633 bool QuicConnection::OnAckFrame(const QuicAckFrame& incoming_ack) {
634 DCHECK(connected_);
635 if (debug_visitor_ != nullptr) {
636 debug_visitor_->OnAckFrame(incoming_ack);
638 DVLOG(1) << ENDPOINT << "OnAckFrame: " << incoming_ack;
640 if (last_header_.packet_sequence_number <= largest_seen_packet_with_ack_) {
641 DVLOG(1) << ENDPOINT << "Received an old ack frame: ignoring";
642 return true;
645 if (!ValidateAckFrame(incoming_ack)) {
646 SendConnectionClose(QUIC_INVALID_ACK_DATA);
647 return false;
650 last_ack_frames_.push_back(incoming_ack);
651 return connected_;
654 void QuicConnection::ProcessAckFrame(const QuicAckFrame& incoming_ack) {
655 largest_seen_packet_with_ack_ = last_header_.packet_sequence_number;
656 sent_packet_manager_.OnIncomingAck(incoming_ack,
657 time_of_last_received_packet_);
658 sent_entropy_manager_.ClearEntropyBefore(
659 sent_packet_manager_.least_packet_awaited_by_peer() - 1);
660 if (sent_packet_manager_.HasPendingRetransmissions()) {
661 WriteIfNotBlocked();
664 // Always reset the retransmission alarm when an ack comes in, since we now
665 // have a better estimate of the current rtt than when it was set.
666 QuicTime retransmission_time = sent_packet_manager_.GetRetransmissionTime();
667 retransmission_alarm_->Update(retransmission_time,
668 QuicTime::Delta::FromMilliseconds(1));
671 void QuicConnection::ProcessStopWaitingFrame(
672 const QuicStopWaitingFrame& stop_waiting) {
673 largest_seen_packet_with_stop_waiting_ = last_header_.packet_sequence_number;
674 received_packet_manager_.UpdatePacketInformationSentByPeer(stop_waiting);
675 // Possibly close any FecGroups which are now irrelevant.
676 CloseFecGroupsBefore(stop_waiting.least_unacked + 1);
679 bool QuicConnection::OnStopWaitingFrame(const QuicStopWaitingFrame& frame) {
680 DCHECK(connected_);
682 if (last_header_.packet_sequence_number <=
683 largest_seen_packet_with_stop_waiting_) {
684 DVLOG(1) << ENDPOINT << "Received an old stop waiting frame: ignoring";
685 return true;
688 if (!ValidateStopWaitingFrame(frame)) {
689 SendConnectionClose(QUIC_INVALID_STOP_WAITING_DATA);
690 return false;
693 if (debug_visitor_ != nullptr) {
694 debug_visitor_->OnStopWaitingFrame(frame);
697 last_stop_waiting_frames_.push_back(frame);
698 return connected_;
701 bool QuicConnection::OnPingFrame(const QuicPingFrame& frame) {
702 DCHECK(connected_);
703 if (debug_visitor_ != nullptr) {
704 debug_visitor_->OnPingFrame(frame);
706 last_ping_frames_.push_back(frame);
707 return true;
710 bool QuicConnection::ValidateAckFrame(const QuicAckFrame& incoming_ack) {
711 if (incoming_ack.largest_observed > packet_generator_.sequence_number()) {
712 DLOG(ERROR) << ENDPOINT << "Peer's observed unsent packet:"
713 << incoming_ack.largest_observed << " vs "
714 << packet_generator_.sequence_number();
715 // We got an error for data we have not sent. Error out.
716 return false;
719 if (incoming_ack.largest_observed < sent_packet_manager_.largest_observed()) {
720 DLOG(ERROR) << ENDPOINT << "Peer's largest_observed packet decreased:"
721 << incoming_ack.largest_observed << " vs "
722 << sent_packet_manager_.largest_observed();
723 // A new ack has a diminished largest_observed value. Error out.
724 // If this was an old packet, we wouldn't even have checked.
725 return false;
728 if (!incoming_ack.missing_packets.empty() &&
729 *incoming_ack.missing_packets.rbegin() > incoming_ack.largest_observed) {
730 DLOG(ERROR) << ENDPOINT << "Peer sent missing packet: "
731 << *incoming_ack.missing_packets.rbegin()
732 << " which is greater than largest observed: "
733 << incoming_ack.largest_observed;
734 return false;
737 if (!incoming_ack.missing_packets.empty() &&
738 *incoming_ack.missing_packets.begin() <
739 sent_packet_manager_.least_packet_awaited_by_peer()) {
740 DLOG(ERROR) << ENDPOINT << "Peer sent missing packet: "
741 << *incoming_ack.missing_packets.begin()
742 << " which is smaller than least_packet_awaited_by_peer_: "
743 << sent_packet_manager_.least_packet_awaited_by_peer();
744 return false;
747 if (!sent_entropy_manager_.IsValidEntropy(
748 incoming_ack.largest_observed,
749 incoming_ack.missing_packets,
750 incoming_ack.entropy_hash)) {
751 DLOG(ERROR) << ENDPOINT << "Peer sent invalid entropy.";
752 return false;
755 for (SequenceNumberSet::const_iterator iter =
756 incoming_ack.revived_packets.begin();
757 iter != incoming_ack.revived_packets.end(); ++iter) {
758 if (!ContainsKey(incoming_ack.missing_packets, *iter)) {
759 DLOG(ERROR) << ENDPOINT
760 << "Peer specified revived packet which was not missing.";
761 return false;
764 return true;
767 bool QuicConnection::ValidateStopWaitingFrame(
768 const QuicStopWaitingFrame& stop_waiting) {
769 if (stop_waiting.least_unacked <
770 received_packet_manager_.peer_least_packet_awaiting_ack()) {
771 DLOG(ERROR) << ENDPOINT << "Peer's sent low least_unacked: "
772 << stop_waiting.least_unacked << " vs "
773 << received_packet_manager_.peer_least_packet_awaiting_ack();
774 // We never process old ack frames, so this number should only increase.
775 return false;
778 if (stop_waiting.least_unacked >
779 last_header_.packet_sequence_number) {
780 DLOG(ERROR) << ENDPOINT << "Peer sent least_unacked:"
781 << stop_waiting.least_unacked
782 << " greater than the enclosing packet sequence number:"
783 << last_header_.packet_sequence_number;
784 return false;
787 return true;
790 void QuicConnection::OnFecData(const QuicFecData& fec) {
791 DCHECK_EQ(IN_FEC_GROUP, last_header_.is_in_fec_group);
792 DCHECK_NE(0u, last_header_.fec_group);
793 QuicFecGroup* group = GetFecGroup();
794 if (group != nullptr) {
795 group->UpdateFec(last_decrypted_packet_level_,
796 last_header_.packet_sequence_number, fec);
800 bool QuicConnection::OnRstStreamFrame(const QuicRstStreamFrame& frame) {
801 DCHECK(connected_);
802 if (debug_visitor_ != nullptr) {
803 debug_visitor_->OnRstStreamFrame(frame);
805 DVLOG(1) << ENDPOINT << "Stream reset with error "
806 << QuicUtils::StreamErrorToString(frame.error_code);
807 last_rst_frames_.push_back(frame);
808 return connected_;
811 bool QuicConnection::OnConnectionCloseFrame(
812 const QuicConnectionCloseFrame& frame) {
813 DCHECK(connected_);
814 if (debug_visitor_ != nullptr) {
815 debug_visitor_->OnConnectionCloseFrame(frame);
817 DVLOG(1) << ENDPOINT << "Connection " << connection_id()
818 << " closed with error "
819 << QuicUtils::ErrorToString(frame.error_code)
820 << " " << frame.error_details;
821 last_close_frames_.push_back(frame);
822 return connected_;
825 bool QuicConnection::OnGoAwayFrame(const QuicGoAwayFrame& frame) {
826 DCHECK(connected_);
827 if (debug_visitor_ != nullptr) {
828 debug_visitor_->OnGoAwayFrame(frame);
830 DVLOG(1) << ENDPOINT << "Go away received with error "
831 << QuicUtils::ErrorToString(frame.error_code)
832 << " and reason:" << frame.reason_phrase;
833 last_goaway_frames_.push_back(frame);
834 return connected_;
837 bool QuicConnection::OnWindowUpdateFrame(const QuicWindowUpdateFrame& frame) {
838 DCHECK(connected_);
839 if (debug_visitor_ != nullptr) {
840 debug_visitor_->OnWindowUpdateFrame(frame);
842 DVLOG(1) << ENDPOINT << "WindowUpdate received for stream: "
843 << frame.stream_id << " with byte offset: " << frame.byte_offset;
844 last_window_update_frames_.push_back(frame);
845 return connected_;
848 bool QuicConnection::OnBlockedFrame(const QuicBlockedFrame& frame) {
849 DCHECK(connected_);
850 if (debug_visitor_ != nullptr) {
851 debug_visitor_->OnBlockedFrame(frame);
853 DVLOG(1) << ENDPOINT << "Blocked frame received for stream: "
854 << frame.stream_id;
855 last_blocked_frames_.push_back(frame);
856 return connected_;
859 void QuicConnection::OnPacketComplete() {
860 // Don't do anything if this packet closed the connection.
861 if (!connected_) {
862 ClearLastFrames();
863 return;
866 DVLOG(1) << ENDPOINT << (last_packet_revived_ ? "Revived" : "Got")
867 << " packet " << last_header_.packet_sequence_number
868 << " with " << last_stream_frames_.size()<< " stream frames "
869 << last_ack_frames_.size() << " acks, "
870 << last_stop_waiting_frames_.size() << " stop_waiting, "
871 << last_rst_frames_.size() << " rsts, "
872 << last_goaway_frames_.size() << " goaways, "
873 << last_window_update_frames_.size() << " window updates, "
874 << last_blocked_frames_.size() << " blocked, "
875 << last_ping_frames_.size() << " pings, "
876 << last_close_frames_.size() << " closes, "
877 << "for " << last_header_.public_header.connection_id;
879 ++num_packets_received_since_last_ack_sent_;
881 // Call MaybeQueueAck() before recording the received packet, since we want
882 // to trigger an ack if the newly received packet was previously missing.
883 MaybeQueueAck();
885 // Record received or revived packet to populate ack info correctly before
886 // processing stream frames, since the processing may result in a response
887 // packet with a bundled ack.
888 if (last_packet_revived_) {
889 received_packet_manager_.RecordPacketRevived(
890 last_header_.packet_sequence_number);
891 } else {
892 received_packet_manager_.RecordPacketReceived(
893 last_size_, last_header_, time_of_last_received_packet_);
896 if (!last_stream_frames_.empty()) {
897 visitor_->OnStreamFrames(last_stream_frames_);
900 for (size_t i = 0; i < last_stream_frames_.size(); ++i) {
901 stats_.stream_bytes_received +=
902 last_stream_frames_[i].data.TotalBufferSize();
905 // Process window updates, blocked, stream resets, acks, then congestion
906 // feedback.
907 if (!last_window_update_frames_.empty()) {
908 visitor_->OnWindowUpdateFrames(last_window_update_frames_);
910 if (!last_blocked_frames_.empty()) {
911 visitor_->OnBlockedFrames(last_blocked_frames_);
913 for (size_t i = 0; i < last_goaway_frames_.size(); ++i) {
914 visitor_->OnGoAway(last_goaway_frames_[i]);
916 for (size_t i = 0; i < last_rst_frames_.size(); ++i) {
917 visitor_->OnRstStream(last_rst_frames_[i]);
919 for (size_t i = 0; i < last_ack_frames_.size(); ++i) {
920 ProcessAckFrame(last_ack_frames_[i]);
922 for (size_t i = 0; i < last_stop_waiting_frames_.size(); ++i) {
923 ProcessStopWaitingFrame(last_stop_waiting_frames_[i]);
925 if (!last_close_frames_.empty()) {
926 CloseConnection(last_close_frames_[0].error_code, true);
927 DCHECK(!connected_);
930 // If there are new missing packets to report, send an ack immediately.
931 if (received_packet_manager_.HasNewMissingPackets()) {
932 ack_queued_ = true;
933 ack_alarm_->Cancel();
936 UpdateStopWaitingCount();
937 ClearLastFrames();
938 MaybeCloseIfTooManyOutstandingPackets();
941 void QuicConnection::MaybeQueueAck() {
942 // If the incoming packet was missing, send an ack immediately.
943 ack_queued_ = received_packet_manager_.IsMissing(
944 last_header_.packet_sequence_number);
946 if (!ack_queued_ && ShouldLastPacketInstigateAck()) {
947 if (ack_alarm_->IsSet()) {
948 ack_queued_ = true;
949 } else {
950 // Send an ack much more quickly for crypto handshake packets.
951 QuicTime::Delta delayed_ack_time = sent_packet_manager_.DelayedAckTime();
952 ack_alarm_->Set(clock_->ApproximateNow().Add(delayed_ack_time));
953 DVLOG(1) << "Ack timer set; next packet or timer will trigger ACK.";
957 if (ack_queued_) {
958 ack_alarm_->Cancel();
962 void QuicConnection::ClearLastFrames() {
963 last_stream_frames_.clear();
964 last_ack_frames_.clear();
965 last_stop_waiting_frames_.clear();
966 last_rst_frames_.clear();
967 last_goaway_frames_.clear();
968 last_window_update_frames_.clear();
969 last_blocked_frames_.clear();
970 last_ping_frames_.clear();
971 last_close_frames_.clear();
974 void QuicConnection::MaybeCloseIfTooManyOutstandingPackets() {
975 // This occurs if we don't discard old packets we've sent fast enough.
976 // It's possible largest observed is less than least unacked.
977 if (sent_packet_manager_.largest_observed() >
978 (sent_packet_manager_.GetLeastUnacked() + kMaxTrackedPackets)) {
979 SendConnectionCloseWithDetails(
980 QUIC_TOO_MANY_OUTSTANDING_SENT_PACKETS,
981 StringPrintf("More than %" PRIu64 " outstanding.", kMaxTrackedPackets));
983 // This occurs if there are received packet gaps and the peer does not raise
984 // the least unacked fast enough.
985 if (received_packet_manager_.NumTrackedPackets() > kMaxTrackedPackets) {
986 SendConnectionCloseWithDetails(
987 QUIC_TOO_MANY_OUTSTANDING_RECEIVED_PACKETS,
988 StringPrintf("More than %" PRIu64 " outstanding.", kMaxTrackedPackets));
992 void QuicConnection::PopulateAckFrame(QuicAckFrame* ack) {
993 received_packet_manager_.UpdateReceivedPacketInfo(ack,
994 clock_->ApproximateNow());
997 void QuicConnection::PopulateStopWaitingFrame(
998 QuicStopWaitingFrame* stop_waiting) {
999 stop_waiting->least_unacked = GetLeastUnacked();
1000 stop_waiting->entropy_hash = sent_entropy_manager_.GetCumulativeEntropy(
1001 stop_waiting->least_unacked - 1);
1004 bool QuicConnection::ShouldLastPacketInstigateAck() const {
1005 if (!last_stream_frames_.empty() ||
1006 !last_goaway_frames_.empty() ||
1007 !last_rst_frames_.empty() ||
1008 !last_window_update_frames_.empty() ||
1009 !last_blocked_frames_.empty() ||
1010 !last_ping_frames_.empty()) {
1011 return true;
1014 if (!last_ack_frames_.empty() && last_ack_frames_.back().is_truncated) {
1015 return true;
1017 // Always send an ack every 20 packets in order to allow the peer to discard
1018 // information from the SentPacketManager and provide an RTT measurement.
1019 if (num_packets_received_since_last_ack_sent_ >=
1020 kMaxPacketsReceivedBeforeAckSend) {
1021 return true;
1023 return false;
1026 void QuicConnection::UpdateStopWaitingCount() {
1027 if (last_ack_frames_.empty()) {
1028 return;
1031 // If the peer is still waiting for a packet that we are no longer planning to
1032 // send, send an ack to raise the high water mark.
1033 if (!last_ack_frames_.back().missing_packets.empty() &&
1034 GetLeastUnacked() > *last_ack_frames_.back().missing_packets.begin()) {
1035 ++stop_waiting_count_;
1036 } else {
1037 stop_waiting_count_ = 0;
1041 QuicPacketSequenceNumber QuicConnection::GetLeastUnacked() const {
1042 return sent_packet_manager_.GetLeastUnacked();
1045 void QuicConnection::MaybeSendInResponseToPacket() {
1046 if (!connected_) {
1047 return;
1049 ScopedPacketBundler bundler(this, ack_queued_ ? SEND_ACK : NO_ACK);
1051 // Now that we have received an ack, we might be able to send packets which
1052 // are queued locally, or drain streams which are blocked.
1053 if (CanWrite(HAS_RETRANSMITTABLE_DATA)) {
1054 OnCanWrite();
1058 void QuicConnection::SendVersionNegotiationPacket() {
1059 // TODO(alyssar): implement zero server state negotiation.
1060 pending_version_negotiation_packet_ = true;
1061 if (writer_->IsWriteBlocked()) {
1062 visitor_->OnWriteBlocked();
1063 return;
1065 DVLOG(1) << ENDPOINT << "Sending version negotiation packet: {"
1066 << QuicVersionVectorToString(framer_.supported_versions()) << "}";
1067 scoped_ptr<QuicEncryptedPacket> version_packet(
1068 packet_generator_.SerializeVersionNegotiationPacket(
1069 framer_.supported_versions()));
1070 WriteResult result = writer_->WritePacket(
1071 version_packet->data(), version_packet->length(),
1072 self_address().address(), peer_address());
1074 if (result.status == WRITE_STATUS_ERROR) {
1075 // We can't send an error as the socket is presumably borked.
1076 CloseConnection(QUIC_PACKET_WRITE_ERROR, false);
1077 return;
1079 if (result.status == WRITE_STATUS_BLOCKED) {
1080 visitor_->OnWriteBlocked();
1081 if (writer_->IsWriteBlockedDataBuffered()) {
1082 pending_version_negotiation_packet_ = false;
1084 return;
1087 pending_version_negotiation_packet_ = false;
1090 QuicConsumedData QuicConnection::SendStreamData(
1091 QuicStreamId id,
1092 const IOVector& data,
1093 QuicStreamOffset offset,
1094 bool fin,
1095 FecProtection fec_protection,
1096 QuicAckNotifier::DelegateInterface* delegate) {
1097 if (!fin && data.Empty()) {
1098 LOG(DFATAL) << "Attempt to send empty stream frame";
1099 return QuicConsumedData(0, false);
1102 // Opportunistically bundle an ack with every outgoing packet.
1103 // Particularly, we want to bundle with handshake packets since we don't know
1104 // which decrypter will be used on an ack packet following a handshake
1105 // packet (a handshake packet from client to server could result in a REJ or a
1106 // SHLO from the server, leading to two different decrypters at the server.)
1108 // TODO(jri): Note that ConsumeData may cause a response packet to be sent.
1109 // We may end up sending stale ack information if there are undecryptable
1110 // packets hanging around and/or there are revivable packets which may get
1111 // handled after this packet is sent. Change ScopedPacketBundler to do the
1112 // right thing: check ack_queued_, and then check undecryptable packets and
1113 // also if there is possibility of revival. Only bundle an ack if there's no
1114 // processing left that may cause received_info_ to change.
1115 ScopedPacketBundler ack_bundler(this, BUNDLE_PENDING_ACK);
1116 return packet_generator_.ConsumeData(id, data, offset, fin, fec_protection,
1117 delegate);
1120 void QuicConnection::SendRstStream(QuicStreamId id,
1121 QuicRstStreamErrorCode error,
1122 QuicStreamOffset bytes_written) {
1123 // Opportunistically bundle an ack with this outgoing packet.
1124 ScopedPacketBundler ack_bundler(this, BUNDLE_PENDING_ACK);
1125 packet_generator_.AddControlFrame(QuicFrame(new QuicRstStreamFrame(
1126 id, AdjustErrorForVersion(error, version()), bytes_written)));
1127 if (!FLAGS_quic_do_not_retransmit_for_reset_streams) {
1128 return;
1131 sent_packet_manager_.CancelRetransmissionsForStream(id);
1132 // Remove all queued packets which only contain data for the reset stream.
1133 QueuedPacketList::iterator packet_iterator = queued_packets_.begin();
1134 while (packet_iterator != queued_packets_.end()) {
1135 RetransmittableFrames* retransmittable_frames =
1136 packet_iterator->serialized_packet.retransmittable_frames;
1137 if (!retransmittable_frames) {
1138 ++packet_iterator;
1139 continue;
1141 retransmittable_frames->RemoveFramesForStream(id);
1142 if (!retransmittable_frames->frames().empty()) {
1143 ++packet_iterator;
1144 continue;
1146 delete packet_iterator->serialized_packet.retransmittable_frames;
1147 delete packet_iterator->serialized_packet.packet;
1148 packet_iterator->serialized_packet.retransmittable_frames = nullptr;
1149 packet_iterator->serialized_packet.packet = nullptr;
1150 packet_iterator = queued_packets_.erase(packet_iterator);
1154 void QuicConnection::SendWindowUpdate(QuicStreamId id,
1155 QuicStreamOffset byte_offset) {
1156 // Opportunistically bundle an ack with this outgoing packet.
1157 ScopedPacketBundler ack_bundler(this, BUNDLE_PENDING_ACK);
1158 packet_generator_.AddControlFrame(
1159 QuicFrame(new QuicWindowUpdateFrame(id, byte_offset)));
1162 void QuicConnection::SendBlocked(QuicStreamId id) {
1163 // Opportunistically bundle an ack with this outgoing packet.
1164 ScopedPacketBundler ack_bundler(this, BUNDLE_PENDING_ACK);
1165 packet_generator_.AddControlFrame(QuicFrame(new QuicBlockedFrame(id)));
1168 const QuicConnectionStats& QuicConnection::GetStats() {
1169 const RttStats* rtt_stats = sent_packet_manager_.GetRttStats();
1171 // Update rtt and estimated bandwidth.
1172 QuicTime::Delta min_rtt = rtt_stats->min_rtt();
1173 if (min_rtt.IsZero()) {
1174 // If min RTT has not been set, use initial RTT instead.
1175 min_rtt = QuicTime::Delta::FromMicroseconds(rtt_stats->initial_rtt_us());
1177 stats_.min_rtt_us = min_rtt.ToMicroseconds();
1179 QuicTime::Delta srtt = rtt_stats->smoothed_rtt();
1180 if (srtt.IsZero()) {
1181 // If SRTT has not been set, use initial RTT instead.
1182 srtt = QuicTime::Delta::FromMicroseconds(rtt_stats->initial_rtt_us());
1184 stats_.srtt_us = srtt.ToMicroseconds();
1186 stats_.estimated_bandwidth = sent_packet_manager_.BandwidthEstimate();
1187 stats_.max_packet_size = packet_generator_.max_packet_length();
1188 return stats_;
1191 void QuicConnection::ProcessUdpPacket(const IPEndPoint& self_address,
1192 const IPEndPoint& peer_address,
1193 const QuicEncryptedPacket& packet) {
1194 if (!connected_) {
1195 return;
1197 // TODO(rtenneti): Remove ScopedTracker below once crbug.com/462789 is fixed.
1198 tracked_objects::ScopedTracker tracking_profile(
1199 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1200 "462789 QuicConnection::ProcessUdpPacket"));
1201 if (debug_visitor_ != nullptr) {
1202 debug_visitor_->OnPacketReceived(self_address, peer_address, packet);
1204 last_size_ = packet.length();
1206 CheckForAddressMigration(self_address, peer_address);
1208 stats_.bytes_received += packet.length();
1209 ++stats_.packets_received;
1211 if (!framer_.ProcessPacket(packet)) {
1212 // If we are unable to decrypt this packet, it might be
1213 // because the CHLO or SHLO packet was lost.
1214 if (framer_.error() == QUIC_DECRYPTION_FAILURE) {
1215 if (encryption_level_ != ENCRYPTION_FORWARD_SECURE &&
1216 undecryptable_packets_.size() < max_undecryptable_packets_) {
1217 QueueUndecryptablePacket(packet);
1218 } else if (debug_visitor_ != nullptr) {
1219 debug_visitor_->OnUndecryptablePacket();
1222 DVLOG(1) << ENDPOINT << "Unable to process packet. Last packet processed: "
1223 << last_header_.packet_sequence_number;
1224 return;
1227 ++stats_.packets_processed;
1228 MaybeProcessUndecryptablePackets();
1229 MaybeProcessRevivedPacket();
1230 MaybeSendInResponseToPacket();
1231 SetPingAlarm();
1234 void QuicConnection::CheckForAddressMigration(
1235 const IPEndPoint& self_address, const IPEndPoint& peer_address) {
1236 peer_ip_changed_ = false;
1237 peer_port_changed_ = false;
1238 self_ip_changed_ = false;
1239 self_port_changed_ = false;
1241 if (peer_address_.address().empty()) {
1242 peer_address_ = peer_address;
1244 if (self_address_.address().empty()) {
1245 self_address_ = self_address;
1248 if (!peer_address.address().empty() && !peer_address_.address().empty()) {
1249 peer_ip_changed_ = (peer_address.address() != peer_address_.address());
1250 peer_port_changed_ = (peer_address.port() != peer_address_.port());
1252 // Store in case we want to migrate connection in ProcessValidatedPacket.
1253 migrating_peer_port_ = peer_address.port();
1256 if (!self_address.address().empty() && !self_address_.address().empty()) {
1257 self_ip_changed_ = (self_address.address() != self_address_.address());
1258 self_port_changed_ = (self_address.port() != self_address_.port());
1262 void QuicConnection::OnCanWrite() {
1263 DCHECK(!writer_->IsWriteBlocked());
1265 WriteQueuedPackets();
1266 WritePendingRetransmissions();
1268 // Sending queued packets may have caused the socket to become write blocked,
1269 // or the congestion manager to prohibit sending. If we've sent everything
1270 // we had queued and we're still not blocked, let the visitor know it can
1271 // write more.
1272 if (!CanWrite(HAS_RETRANSMITTABLE_DATA)) {
1273 return;
1276 { // Limit the scope of the bundler. ACK inclusion happens elsewhere.
1277 ScopedPacketBundler bundler(this, NO_ACK);
1278 visitor_->OnCanWrite();
1281 // After the visitor writes, it may have caused the socket to become write
1282 // blocked or the congestion manager to prohibit sending, so check again.
1283 if (visitor_->WillingAndAbleToWrite() &&
1284 !resume_writes_alarm_->IsSet() &&
1285 CanWrite(HAS_RETRANSMITTABLE_DATA)) {
1286 // We're not write blocked, but some stream didn't write out all of its
1287 // bytes. Register for 'immediate' resumption so we'll keep writing after
1288 // other connections and events have had a chance to use the thread.
1289 resume_writes_alarm_->Set(clock_->ApproximateNow());
1293 void QuicConnection::WriteIfNotBlocked() {
1294 if (!writer_->IsWriteBlocked()) {
1295 OnCanWrite();
1299 bool QuicConnection::ProcessValidatedPacket() {
1300 if (peer_ip_changed_ || self_ip_changed_ || self_port_changed_) {
1301 SendConnectionCloseWithDetails(
1302 QUIC_ERROR_MIGRATING_ADDRESS,
1303 "Neither IP address migration, nor self port migration are supported.");
1304 return false;
1307 // Peer port migration is supported, do it now if port has changed.
1308 if (peer_port_changed_) {
1309 DVLOG(1) << ENDPOINT << "Peer's port changed from "
1310 << peer_address_.port() << " to " << migrating_peer_port_
1311 << ", migrating connection.";
1312 peer_address_ = IPEndPoint(peer_address_.address(), migrating_peer_port_);
1315 time_of_last_received_packet_ = clock_->Now();
1316 DVLOG(1) << ENDPOINT << "time of last received packet: "
1317 << time_of_last_received_packet_.ToDebuggingValue();
1319 if (perspective_ == Perspective::IS_SERVER &&
1320 encryption_level_ == ENCRYPTION_NONE &&
1321 last_size_ > packet_generator_.max_packet_length()) {
1322 set_max_packet_length(last_size_);
1324 return true;
1327 void QuicConnection::WriteQueuedPackets() {
1328 DCHECK(!writer_->IsWriteBlocked());
1330 if (pending_version_negotiation_packet_) {
1331 SendVersionNegotiationPacket();
1334 QueuedPacketList::iterator packet_iterator = queued_packets_.begin();
1335 while (packet_iterator != queued_packets_.end() &&
1336 WritePacket(&(*packet_iterator))) {
1337 packet_iterator = queued_packets_.erase(packet_iterator);
1341 void QuicConnection::WritePendingRetransmissions() {
1342 // Keep writing as long as there's a pending retransmission which can be
1343 // written.
1344 while (sent_packet_manager_.HasPendingRetransmissions()) {
1345 const QuicSentPacketManager::PendingRetransmission pending =
1346 sent_packet_manager_.NextPendingRetransmission();
1347 if (!CanWrite(HAS_RETRANSMITTABLE_DATA)) {
1348 break;
1351 // Re-packetize the frames with a new sequence number for retransmission.
1352 // Retransmitted data packets do not use FEC, even when it's enabled.
1353 // Retransmitted packets use the same sequence number length as the
1354 // original.
1355 // Flush the packet generator before making a new packet.
1356 // TODO(ianswett): Implement ReserializeAllFrames as a separate path that
1357 // does not require the creator to be flushed.
1358 packet_generator_.FlushAllQueuedFrames();
1359 SerializedPacket serialized_packet = packet_generator_.ReserializeAllFrames(
1360 pending.retransmittable_frames, pending.sequence_number_length);
1361 if (serialized_packet.packet == nullptr) {
1362 // We failed to serialize the packet, so close the connection.
1363 // CloseConnection does not send close packet, so no infinite loop here.
1364 CloseConnection(QUIC_ENCRYPTION_FAILURE, false);
1365 return;
1368 DVLOG(1) << ENDPOINT << "Retransmitting " << pending.sequence_number
1369 << " as " << serialized_packet.sequence_number;
1370 SendOrQueuePacket(
1371 QueuedPacket(serialized_packet,
1372 pending.retransmittable_frames.encryption_level(),
1373 pending.transmission_type,
1374 pending.sequence_number));
1378 void QuicConnection::RetransmitUnackedPackets(
1379 TransmissionType retransmission_type) {
1380 sent_packet_manager_.RetransmitUnackedPackets(retransmission_type);
1382 WriteIfNotBlocked();
1385 void QuicConnection::NeuterUnencryptedPackets() {
1386 sent_packet_manager_.NeuterUnencryptedPackets();
1387 // This may have changed the retransmission timer, so re-arm it.
1388 QuicTime retransmission_time = sent_packet_manager_.GetRetransmissionTime();
1389 retransmission_alarm_->Update(retransmission_time,
1390 QuicTime::Delta::FromMilliseconds(1));
1393 bool QuicConnection::ShouldGeneratePacket(
1394 TransmissionType transmission_type,
1395 HasRetransmittableData retransmittable,
1396 IsHandshake handshake) {
1397 // We should serialize handshake packets immediately to ensure that they
1398 // end up sent at the right encryption level.
1399 if (handshake == IS_HANDSHAKE) {
1400 return true;
1403 return CanWrite(retransmittable);
1406 bool QuicConnection::CanWrite(HasRetransmittableData retransmittable) {
1407 if (!connected_) {
1408 return false;
1411 if (writer_->IsWriteBlocked()) {
1412 visitor_->OnWriteBlocked();
1413 return false;
1416 QuicTime now = clock_->Now();
1417 QuicTime::Delta delay = sent_packet_manager_.TimeUntilSend(
1418 now, retransmittable);
1419 if (delay.IsInfinite()) {
1420 send_alarm_->Cancel();
1421 return false;
1424 // If the scheduler requires a delay, then we can not send this packet now.
1425 if (!delay.IsZero()) {
1426 send_alarm_->Update(now.Add(delay), QuicTime::Delta::FromMilliseconds(1));
1427 DVLOG(1) << ENDPOINT << "Delaying sending " << delay.ToMilliseconds()
1428 << "ms";
1429 return false;
1431 send_alarm_->Cancel();
1432 return true;
1435 bool QuicConnection::WritePacket(QueuedPacket* packet) {
1436 if (!WritePacketInner(packet)) {
1437 return false;
1439 delete packet->serialized_packet.retransmittable_frames;
1440 delete packet->serialized_packet.packet;
1441 packet->serialized_packet.retransmittable_frames = nullptr;
1442 packet->serialized_packet.packet = nullptr;
1443 return true;
1446 bool QuicConnection::WritePacketInner(QueuedPacket* packet) {
1447 if (ShouldDiscardPacket(*packet)) {
1448 ++stats_.packets_discarded;
1449 return true;
1451 // Connection close packets are encrypted and saved, so don't exit early.
1452 const bool is_connection_close = IsConnectionClose(*packet);
1453 if (writer_->IsWriteBlocked() && !is_connection_close) {
1454 return false;
1457 QuicPacketSequenceNumber sequence_number =
1458 packet->serialized_packet.sequence_number;
1459 DCHECK_LE(sequence_number_of_last_sent_packet_, sequence_number);
1460 sequence_number_of_last_sent_packet_ = sequence_number;
1462 QuicEncryptedPacket* encrypted = packet->serialized_packet.packet;
1463 // Connection close packets are eventually owned by TimeWaitListManager.
1464 // Others are deleted at the end of this call.
1465 if (is_connection_close) {
1466 DCHECK(connection_close_packet_.get() == nullptr);
1467 connection_close_packet_.reset(encrypted);
1468 packet->serialized_packet.packet = nullptr;
1469 // This assures we won't try to write *forced* packets when blocked.
1470 // Return true to stop processing.
1471 if (writer_->IsWriteBlocked()) {
1472 visitor_->OnWriteBlocked();
1473 return true;
1477 if (!FLAGS_quic_allow_oversized_packets_for_test) {
1478 DCHECK_LE(encrypted->length(), kMaxPacketSize);
1480 DCHECK_LE(encrypted->length(), packet_generator_.max_packet_length());
1481 DVLOG(1) << ENDPOINT << "Sending packet " << sequence_number << " : "
1482 << (packet->serialized_packet.is_fec_packet
1483 ? "FEC "
1484 : (IsRetransmittable(*packet) == HAS_RETRANSMITTABLE_DATA
1485 ? "data bearing "
1486 : " ack only ")) << ", encryption level: "
1487 << QuicUtils::EncryptionLevelToString(packet->encryption_level)
1488 << ", encrypted length:" << encrypted->length();
1489 DVLOG(2) << ENDPOINT << "packet(" << sequence_number << "): " << std::endl
1490 << QuicUtils::StringToHexASCIIDump(encrypted->AsStringPiece());
1492 // Measure the RTT from before the write begins to avoid underestimating the
1493 // min_rtt_, especially in cases where the thread blocks or gets swapped out
1494 // during the WritePacket below.
1495 QuicTime packet_send_time = clock_->Now();
1496 WriteResult result = writer_->WritePacket(encrypted->data(),
1497 encrypted->length(),
1498 self_address().address(),
1499 peer_address());
1500 if (result.error_code == ERR_IO_PENDING) {
1501 DCHECK_EQ(WRITE_STATUS_BLOCKED, result.status);
1504 if (result.status == WRITE_STATUS_BLOCKED) {
1505 visitor_->OnWriteBlocked();
1506 // If the socket buffers the the data, then the packet should not
1507 // be queued and sent again, which would result in an unnecessary
1508 // duplicate packet being sent. The helper must call OnCanWrite
1509 // when the write completes, and OnWriteError if an error occurs.
1510 if (!writer_->IsWriteBlockedDataBuffered()) {
1511 return false;
1514 if (result.status != WRITE_STATUS_ERROR && debug_visitor_ != nullptr) {
1515 // Pass the write result to the visitor.
1516 debug_visitor_->OnPacketSent(packet->serialized_packet,
1517 packet->original_sequence_number,
1518 packet->encryption_level,
1519 packet->transmission_type,
1520 *encrypted,
1521 packet_send_time);
1523 if (packet->transmission_type == NOT_RETRANSMISSION) {
1524 time_of_last_sent_new_packet_ = packet_send_time;
1526 SetPingAlarm();
1527 MaybeSetFecAlarm(sequence_number);
1528 DVLOG(1) << ENDPOINT << "time we began writing last sent packet: "
1529 << packet_send_time.ToDebuggingValue();
1531 // TODO(ianswett): Change the sequence number length and other packet creator
1532 // options by a more explicit API than setting a struct value directly,
1533 // perhaps via the NetworkChangeVisitor.
1534 packet_generator_.UpdateSequenceNumberLength(
1535 sent_packet_manager_.least_packet_awaited_by_peer(),
1536 sent_packet_manager_.EstimateMaxPacketsInFlight(max_packet_length()));
1538 bool reset_retransmission_alarm = sent_packet_manager_.OnPacketSent(
1539 &packet->serialized_packet,
1540 packet->original_sequence_number,
1541 packet_send_time,
1542 encrypted->length(),
1543 packet->transmission_type,
1544 IsRetransmittable(*packet));
1546 if (reset_retransmission_alarm || !retransmission_alarm_->IsSet()) {
1547 retransmission_alarm_->Update(sent_packet_manager_.GetRetransmissionTime(),
1548 QuicTime::Delta::FromMilliseconds(1));
1551 stats_.bytes_sent += result.bytes_written;
1552 ++stats_.packets_sent;
1553 if (packet->transmission_type != NOT_RETRANSMISSION) {
1554 stats_.bytes_retransmitted += result.bytes_written;
1555 ++stats_.packets_retransmitted;
1558 if (result.status == WRITE_STATUS_ERROR) {
1559 OnWriteError(result.error_code);
1560 DLOG(ERROR) << ENDPOINT << "failed writing " << encrypted->length()
1561 << "bytes "
1562 << " from host " << self_address().ToStringWithoutPort()
1563 << " to address " << peer_address().ToString();
1564 return false;
1567 return true;
1570 bool QuicConnection::ShouldDiscardPacket(const QueuedPacket& packet) {
1571 if (!connected_) {
1572 DVLOG(1) << ENDPOINT
1573 << "Not sending packet as connection is disconnected.";
1574 return true;
1577 QuicPacketSequenceNumber sequence_number =
1578 packet.serialized_packet.sequence_number;
1579 if (encryption_level_ == ENCRYPTION_FORWARD_SECURE &&
1580 packet.encryption_level == ENCRYPTION_NONE) {
1581 // Drop packets that are NULL encrypted since the peer won't accept them
1582 // anymore.
1583 DVLOG(1) << ENDPOINT << "Dropping NULL encrypted packet: "
1584 << sequence_number << " since the connection is forward secure.";
1585 return true;
1588 // If a retransmission has been acked before sending, don't send it.
1589 // This occurs if a packet gets serialized, queued, then discarded.
1590 if (packet.transmission_type != NOT_RETRANSMISSION &&
1591 (!sent_packet_manager_.IsUnacked(packet.original_sequence_number) ||
1592 !sent_packet_manager_.HasRetransmittableFrames(
1593 packet.original_sequence_number))) {
1594 DVLOG(1) << ENDPOINT << "Dropping unacked packet: " << sequence_number
1595 << " A previous transmission was acked while write blocked.";
1596 return true;
1599 return false;
1602 void QuicConnection::OnWriteError(int error_code) {
1603 DVLOG(1) << ENDPOINT << "Write failed with error: " << error_code
1604 << " (" << ErrorToString(error_code) << ")";
1605 // We can't send an error as the socket is presumably borked.
1606 CloseConnection(QUIC_PACKET_WRITE_ERROR, false);
1609 void QuicConnection::OnSerializedPacket(
1610 const SerializedPacket& serialized_packet) {
1611 if (serialized_packet.packet == nullptr) {
1612 // We failed to serialize the packet, so close the connection.
1613 // CloseConnection does not send close packet, so no infinite loop here.
1614 CloseConnection(QUIC_ENCRYPTION_FAILURE, false);
1615 return;
1617 if (serialized_packet.retransmittable_frames) {
1618 sent_packet_manager_.OnSerializedPacket(serialized_packet);
1620 if (serialized_packet.is_fec_packet && fec_alarm_->IsSet()) {
1621 // If an FEC packet is serialized with the FEC alarm set, cancel the alarm.
1622 fec_alarm_->Cancel();
1624 SendOrQueuePacket(QueuedPacket(serialized_packet, encryption_level_));
1627 void QuicConnection::OnCongestionWindowChange() {
1628 packet_generator_.OnCongestionWindowChange(
1629 sent_packet_manager_.EstimateMaxPacketsInFlight(max_packet_length()));
1630 visitor_->OnCongestionWindowChange(clock_->ApproximateNow());
1633 void QuicConnection::OnRttChange() {
1634 // Uses the connection's smoothed RTT. If zero, uses initial_rtt.
1635 QuicTime::Delta rtt = sent_packet_manager_.GetRttStats()->smoothed_rtt();
1636 if (rtt.IsZero()) {
1637 rtt = QuicTime::Delta::FromMicroseconds(
1638 sent_packet_manager_.GetRttStats()->initial_rtt_us());
1640 packet_generator_.OnRttChange(rtt);
1643 void QuicConnection::OnHandshakeComplete() {
1644 sent_packet_manager_.SetHandshakeConfirmed();
1645 // The client should immediately ack the SHLO to confirm the handshake is
1646 // complete with the server.
1647 if (perspective_ == Perspective::IS_CLIENT && !ack_queued_) {
1648 ack_alarm_->Cancel();
1649 ack_alarm_->Set(clock_->ApproximateNow());
1653 void QuicConnection::SendOrQueuePacket(QueuedPacket packet) {
1654 // The caller of this function is responsible for checking CanWrite().
1655 if (packet.serialized_packet.packet == nullptr) {
1656 LOG(DFATAL)
1657 << "packet.serialized_packet.packet == nullptr in to SendOrQueuePacket";
1658 return;
1661 sent_entropy_manager_.RecordPacketEntropyHash(
1662 packet.serialized_packet.sequence_number,
1663 packet.serialized_packet.entropy_hash);
1664 if (!WritePacket(&packet)) {
1665 queued_packets_.push_back(packet);
1668 // If a forward-secure encrypter is available but is not being used and the
1669 // next sequence number is the first packet which requires
1670 // forward security, start using the forward-secure encrypter.
1671 if (encryption_level_ != ENCRYPTION_FORWARD_SECURE &&
1672 has_forward_secure_encrypter_ &&
1673 packet.serialized_packet.sequence_number >=
1674 first_required_forward_secure_packet_ - 1) {
1675 SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
1679 void QuicConnection::SendPing() {
1680 if (retransmission_alarm_->IsSet()) {
1681 return;
1683 packet_generator_.AddControlFrame(QuicFrame(new QuicPingFrame));
1686 void QuicConnection::SendAck() {
1687 ack_alarm_->Cancel();
1688 stop_waiting_count_ = 0;
1689 num_packets_received_since_last_ack_sent_ = 0;
1691 packet_generator_.SetShouldSendAck(true);
1694 void QuicConnection::OnRetransmissionTimeout() {
1695 if (!sent_packet_manager_.HasUnackedPackets()) {
1696 return;
1699 sent_packet_manager_.OnRetransmissionTimeout();
1700 WriteIfNotBlocked();
1702 // A write failure can result in the connection being closed, don't attempt to
1703 // write further packets, or to set alarms.
1704 if (!connected_) {
1705 return;
1708 // In the TLP case, the SentPacketManager gives the connection the opportunity
1709 // to send new data before retransmitting.
1710 if (sent_packet_manager_.MaybeRetransmitTailLossProbe()) {
1711 // Send the pending retransmission now that it's been queued.
1712 WriteIfNotBlocked();
1715 // Ensure the retransmission alarm is always set if there are unacked packets
1716 // and nothing waiting to be sent.
1717 if (!HasQueuedData() && !retransmission_alarm_->IsSet()) {
1718 QuicTime rto_timeout = sent_packet_manager_.GetRetransmissionTime();
1719 if (rto_timeout.IsInitialized()) {
1720 retransmission_alarm_->Set(rto_timeout);
1725 void QuicConnection::SetEncrypter(EncryptionLevel level,
1726 QuicEncrypter* encrypter) {
1727 framer_.SetEncrypter(level, encrypter);
1728 if (level == ENCRYPTION_FORWARD_SECURE) {
1729 has_forward_secure_encrypter_ = true;
1730 first_required_forward_secure_packet_ =
1731 sequence_number_of_last_sent_packet_ +
1732 // 3 times the current congestion window (in slow start) should cover
1733 // about two full round trips worth of packets, which should be
1734 // sufficient.
1735 3 * sent_packet_manager_.EstimateMaxPacketsInFlight(
1736 max_packet_length());
1740 const QuicEncrypter* QuicConnection::encrypter(EncryptionLevel level) const {
1741 return framer_.encrypter(level);
1744 void QuicConnection::SetDefaultEncryptionLevel(EncryptionLevel level) {
1745 encryption_level_ = level;
1746 packet_generator_.set_encryption_level(level);
1749 void QuicConnection::SetDecrypter(QuicDecrypter* decrypter,
1750 EncryptionLevel level) {
1751 framer_.SetDecrypter(decrypter, level);
1754 void QuicConnection::SetAlternativeDecrypter(QuicDecrypter* decrypter,
1755 EncryptionLevel level,
1756 bool latch_once_used) {
1757 framer_.SetAlternativeDecrypter(decrypter, level, latch_once_used);
1760 const QuicDecrypter* QuicConnection::decrypter() const {
1761 return framer_.decrypter();
1764 const QuicDecrypter* QuicConnection::alternative_decrypter() const {
1765 return framer_.alternative_decrypter();
1768 void QuicConnection::QueueUndecryptablePacket(
1769 const QuicEncryptedPacket& packet) {
1770 DVLOG(1) << ENDPOINT << "Queueing undecryptable packet.";
1771 undecryptable_packets_.push_back(packet.Clone());
1774 void QuicConnection::MaybeProcessUndecryptablePackets() {
1775 if (undecryptable_packets_.empty() || encryption_level_ == ENCRYPTION_NONE) {
1776 return;
1779 while (connected_ && !undecryptable_packets_.empty()) {
1780 DVLOG(1) << ENDPOINT << "Attempting to process undecryptable packet";
1781 QuicEncryptedPacket* packet = undecryptable_packets_.front();
1782 if (!framer_.ProcessPacket(*packet) &&
1783 framer_.error() == QUIC_DECRYPTION_FAILURE) {
1784 DVLOG(1) << ENDPOINT << "Unable to process undecryptable packet...";
1785 break;
1787 DVLOG(1) << ENDPOINT << "Processed undecryptable packet!";
1788 ++stats_.packets_processed;
1789 delete packet;
1790 undecryptable_packets_.pop_front();
1793 // Once forward secure encryption is in use, there will be no
1794 // new keys installed and hence any undecryptable packets will
1795 // never be able to be decrypted.
1796 if (encryption_level_ == ENCRYPTION_FORWARD_SECURE) {
1797 if (debug_visitor_ != nullptr) {
1798 // TODO(rtenneti): perhaps more efficient to pass the number of
1799 // undecryptable packets as the argument to OnUndecryptablePacket so that
1800 // we just need to call OnUndecryptablePacket once?
1801 for (size_t i = 0; i < undecryptable_packets_.size(); ++i) {
1802 debug_visitor_->OnUndecryptablePacket();
1805 STLDeleteElements(&undecryptable_packets_);
1809 void QuicConnection::MaybeProcessRevivedPacket() {
1810 QuicFecGroup* group = GetFecGroup();
1811 if (!connected_ || group == nullptr || !group->CanRevive()) {
1812 return;
1814 QuicPacketHeader revived_header;
1815 char revived_payload[kMaxPacketSize];
1816 size_t len = group->Revive(&revived_header, revived_payload, kMaxPacketSize);
1817 revived_header.public_header.connection_id = connection_id_;
1818 revived_header.public_header.connection_id_length =
1819 last_header_.public_header.connection_id_length;
1820 revived_header.public_header.version_flag = false;
1821 revived_header.public_header.reset_flag = false;
1822 revived_header.public_header.sequence_number_length =
1823 last_header_.public_header.sequence_number_length;
1824 revived_header.fec_flag = false;
1825 revived_header.is_in_fec_group = NOT_IN_FEC_GROUP;
1826 revived_header.fec_group = 0;
1827 group_map_.erase(last_header_.fec_group);
1828 last_decrypted_packet_level_ = group->effective_encryption_level();
1829 DCHECK_LT(last_decrypted_packet_level_, NUM_ENCRYPTION_LEVELS);
1830 delete group;
1832 last_packet_revived_ = true;
1833 if (debug_visitor_ != nullptr) {
1834 debug_visitor_->OnRevivedPacket(revived_header,
1835 StringPiece(revived_payload, len));
1838 ++stats_.packets_revived;
1839 framer_.ProcessRevivedPacket(&revived_header,
1840 StringPiece(revived_payload, len));
1843 QuicFecGroup* QuicConnection::GetFecGroup() {
1844 QuicFecGroupNumber fec_group_num = last_header_.fec_group;
1845 if (fec_group_num == 0) {
1846 return nullptr;
1848 if (!ContainsKey(group_map_, fec_group_num)) {
1849 if (group_map_.size() >= kMaxFecGroups) { // Too many groups
1850 if (fec_group_num < group_map_.begin()->first) {
1851 // The group being requested is a group we've seen before and deleted.
1852 // Don't recreate it.
1853 return nullptr;
1855 // Clear the lowest group number.
1856 delete group_map_.begin()->second;
1857 group_map_.erase(group_map_.begin());
1859 group_map_[fec_group_num] = new QuicFecGroup();
1861 return group_map_[fec_group_num];
1864 void QuicConnection::SendConnectionClose(QuicErrorCode error) {
1865 SendConnectionCloseWithDetails(error, string());
1868 void QuicConnection::SendConnectionCloseWithDetails(QuicErrorCode error,
1869 const string& details) {
1870 // If we're write blocked, WritePacket() will not send, but will capture the
1871 // serialized packet.
1872 SendConnectionClosePacket(error, details);
1873 if (connected_) {
1874 // It's possible that while sending the connection close packet, we get a
1875 // socket error and disconnect right then and there. Avoid a double
1876 // disconnect in that case.
1877 CloseConnection(error, false);
1881 void QuicConnection::SendConnectionClosePacket(QuicErrorCode error,
1882 const string& details) {
1883 DVLOG(1) << ENDPOINT << "Force closing " << connection_id()
1884 << " with error " << QuicUtils::ErrorToString(error)
1885 << " (" << error << ") " << details;
1886 // Don't send explicit connection close packets for timeouts.
1887 // This is particularly important on mobile, where connections are short.
1888 if (silent_close_enabled_ &&
1889 error == QuicErrorCode::QUIC_CONNECTION_TIMED_OUT) {
1890 return;
1892 ScopedPacketBundler ack_bundler(this, SEND_ACK);
1893 QuicConnectionCloseFrame* frame = new QuicConnectionCloseFrame();
1894 frame->error_code = error;
1895 frame->error_details = details;
1896 packet_generator_.AddControlFrame(QuicFrame(frame));
1897 packet_generator_.FlushAllQueuedFrames();
1900 void QuicConnection::CloseConnection(QuicErrorCode error, bool from_peer) {
1901 if (!connected_) {
1902 DLOG(DFATAL) << "Error: attempt to close an already closed connection"
1903 << base::debug::StackTrace().ToString();
1904 return;
1906 connected_ = false;
1907 if (debug_visitor_ != nullptr) {
1908 debug_visitor_->OnConnectionClosed(error, from_peer);
1910 DCHECK(visitor_ != nullptr);
1911 visitor_->OnConnectionClosed(error, from_peer);
1912 // Cancel the alarms so they don't trigger any action now that the
1913 // connection is closed.
1914 ack_alarm_->Cancel();
1915 ping_alarm_->Cancel();
1916 fec_alarm_->Cancel();
1917 resume_writes_alarm_->Cancel();
1918 retransmission_alarm_->Cancel();
1919 send_alarm_->Cancel();
1920 timeout_alarm_->Cancel();
1923 void QuicConnection::SendGoAway(QuicErrorCode error,
1924 QuicStreamId last_good_stream_id,
1925 const string& reason) {
1926 DVLOG(1) << ENDPOINT << "Going away with error "
1927 << QuicUtils::ErrorToString(error)
1928 << " (" << error << ")";
1930 // Opportunistically bundle an ack with this outgoing packet.
1931 ScopedPacketBundler ack_bundler(this, BUNDLE_PENDING_ACK);
1932 packet_generator_.AddControlFrame(
1933 QuicFrame(new QuicGoAwayFrame(error, last_good_stream_id, reason)));
1936 void QuicConnection::CloseFecGroupsBefore(
1937 QuicPacketSequenceNumber sequence_number) {
1938 FecGroupMap::iterator it = group_map_.begin();
1939 while (it != group_map_.end()) {
1940 // If this is the current group or the group doesn't protect this packet
1941 // we can ignore it.
1942 if (last_header_.fec_group == it->first ||
1943 !it->second->ProtectsPacketsBefore(sequence_number)) {
1944 ++it;
1945 continue;
1947 QuicFecGroup* fec_group = it->second;
1948 DCHECK(!fec_group->CanRevive());
1949 FecGroupMap::iterator next = it;
1950 ++next;
1951 group_map_.erase(it);
1952 delete fec_group;
1953 it = next;
1957 QuicByteCount QuicConnection::max_packet_length() const {
1958 return packet_generator_.max_packet_length();
1961 void QuicConnection::set_max_packet_length(QuicByteCount length) {
1962 return packet_generator_.set_max_packet_length(length);
1965 bool QuicConnection::HasQueuedData() const {
1966 return pending_version_negotiation_packet_ ||
1967 !queued_packets_.empty() || packet_generator_.HasQueuedFrames();
1970 bool QuicConnection::CanWriteStreamData() {
1971 // Don't write stream data if there are negotiation or queued data packets
1972 // to send. Otherwise, continue and bundle as many frames as possible.
1973 if (pending_version_negotiation_packet_ || !queued_packets_.empty()) {
1974 return false;
1977 IsHandshake pending_handshake = visitor_->HasPendingHandshake() ?
1978 IS_HANDSHAKE : NOT_HANDSHAKE;
1979 // Sending queued packets may have caused the socket to become write blocked,
1980 // or the congestion manager to prohibit sending. If we've sent everything
1981 // we had queued and we're still not blocked, let the visitor know it can
1982 // write more.
1983 return ShouldGeneratePacket(NOT_RETRANSMISSION, HAS_RETRANSMITTABLE_DATA,
1984 pending_handshake);
1987 void QuicConnection::SetNetworkTimeouts(QuicTime::Delta overall_timeout,
1988 QuicTime::Delta idle_timeout) {
1989 LOG_IF(DFATAL, idle_timeout > overall_timeout)
1990 << "idle_timeout:" << idle_timeout.ToMilliseconds()
1991 << " overall_timeout:" << overall_timeout.ToMilliseconds();
1992 // Adjust the idle timeout on client and server to prevent clients from
1993 // sending requests to servers which have already closed the connection.
1994 if (perspective_ == Perspective::IS_SERVER) {
1995 idle_timeout = idle_timeout.Add(QuicTime::Delta::FromSeconds(3));
1996 } else if (idle_timeout > QuicTime::Delta::FromSeconds(1)) {
1997 idle_timeout = idle_timeout.Subtract(QuicTime::Delta::FromSeconds(1));
1999 overall_connection_timeout_ = overall_timeout;
2000 idle_network_timeout_ = idle_timeout;
2002 SetTimeoutAlarm();
2005 void QuicConnection::CheckForTimeout() {
2006 QuicTime now = clock_->ApproximateNow();
2007 QuicTime time_of_last_packet = max(time_of_last_received_packet_,
2008 time_of_last_sent_new_packet_);
2010 // |delta| can be < 0 as |now| is approximate time but |time_of_last_packet|
2011 // is accurate time. However, this should not change the behavior of
2012 // timeout handling.
2013 QuicTime::Delta idle_duration = now.Subtract(time_of_last_packet);
2014 DVLOG(1) << ENDPOINT << "last packet "
2015 << time_of_last_packet.ToDebuggingValue()
2016 << " now:" << now.ToDebuggingValue()
2017 << " idle_duration:" << idle_duration.ToMicroseconds()
2018 << " idle_network_timeout: "
2019 << idle_network_timeout_.ToMicroseconds();
2020 if (idle_duration >= idle_network_timeout_) {
2021 DVLOG(1) << ENDPOINT << "Connection timedout due to no network activity.";
2022 SendConnectionClose(QUIC_CONNECTION_TIMED_OUT);
2023 return;
2026 if (!overall_connection_timeout_.IsInfinite()) {
2027 QuicTime::Delta connected_duration =
2028 now.Subtract(stats_.connection_creation_time);
2029 DVLOG(1) << ENDPOINT << "connection time: "
2030 << connected_duration.ToMicroseconds() << " overall timeout: "
2031 << overall_connection_timeout_.ToMicroseconds();
2032 if (connected_duration >= overall_connection_timeout_) {
2033 DVLOG(1) << ENDPOINT <<
2034 "Connection timedout due to overall connection timeout.";
2035 SendConnectionClose(QUIC_CONNECTION_OVERALL_TIMED_OUT);
2036 return;
2040 SetTimeoutAlarm();
2043 void QuicConnection::SetTimeoutAlarm() {
2044 QuicTime time_of_last_packet = max(time_of_last_received_packet_,
2045 time_of_last_sent_new_packet_);
2047 QuicTime deadline = time_of_last_packet.Add(idle_network_timeout_);
2048 if (!overall_connection_timeout_.IsInfinite()) {
2049 deadline = min(deadline,
2050 stats_.connection_creation_time.Add(
2051 overall_connection_timeout_));
2054 timeout_alarm_->Cancel();
2055 timeout_alarm_->Set(deadline);
2058 void QuicConnection::SetPingAlarm() {
2059 if (perspective_ == Perspective::IS_SERVER) {
2060 // Only clients send pings.
2061 return;
2063 if (!visitor_->HasOpenDataStreams()) {
2064 ping_alarm_->Cancel();
2065 // Don't send a ping unless there are open streams.
2066 return;
2068 QuicTime::Delta ping_timeout = QuicTime::Delta::FromSeconds(kPingTimeoutSecs);
2069 ping_alarm_->Update(clock_->ApproximateNow().Add(ping_timeout),
2070 QuicTime::Delta::FromSeconds(1));
2073 QuicConnection::ScopedPacketBundler::ScopedPacketBundler(
2074 QuicConnection* connection,
2075 AckBundling send_ack)
2076 : connection_(connection),
2077 already_in_batch_mode_(connection != nullptr &&
2078 connection->packet_generator_.InBatchMode()) {
2079 if (connection_ == nullptr) {
2080 return;
2082 // Move generator into batch mode. If caller wants us to include an ack,
2083 // check the delayed-ack timer to see if there's ack info to be sent.
2084 if (!already_in_batch_mode_) {
2085 DVLOG(1) << "Entering Batch Mode.";
2086 connection_->packet_generator_.StartBatchOperations();
2088 // Bundle an ack if the alarm is set or with every second packet if we need to
2089 // raise the peer's least unacked.
2090 bool ack_pending =
2091 connection_->ack_alarm_->IsSet() || connection_->stop_waiting_count_ > 1;
2092 if (send_ack == SEND_ACK || (send_ack == BUNDLE_PENDING_ACK && ack_pending)) {
2093 DVLOG(1) << "Bundling ack with outgoing packet.";
2094 connection_->SendAck();
2098 QuicConnection::ScopedPacketBundler::~ScopedPacketBundler() {
2099 if (connection_ == nullptr) {
2100 return;
2102 // If we changed the generator's batch state, restore original batch state.
2103 if (!already_in_batch_mode_) {
2104 DVLOG(1) << "Leaving Batch Mode.";
2105 connection_->packet_generator_.FinishBatchOperations();
2107 DCHECK_EQ(already_in_batch_mode_,
2108 connection_->packet_generator_.InBatchMode());
2111 HasRetransmittableData QuicConnection::IsRetransmittable(
2112 const QueuedPacket& packet) {
2113 // Retransmitted packets retransmittable frames are owned by the unacked
2114 // packet map, but are not present in the serialized packet.
2115 if (packet.transmission_type != NOT_RETRANSMISSION ||
2116 packet.serialized_packet.retransmittable_frames != nullptr) {
2117 return HAS_RETRANSMITTABLE_DATA;
2118 } else {
2119 return NO_RETRANSMITTABLE_DATA;
2123 bool QuicConnection::IsConnectionClose(const QueuedPacket& packet) {
2124 const RetransmittableFrames* retransmittable_frames =
2125 packet.serialized_packet.retransmittable_frames;
2126 if (retransmittable_frames == nullptr) {
2127 return false;
2129 for (const QuicFrame& frame : retransmittable_frames->frames()) {
2130 if (frame.type == CONNECTION_CLOSE_FRAME) {
2131 return true;
2134 return false;
2137 } // namespace net