Sync relocation packer to AOSP bionic.
[chromium-blink-merge.git] / net / quic / quic_connection.cc
blobbb39d6c965bbac95dc8fb147314240fd5eea8a0e
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 // Check that any public reset packet with a different connection ID that was
395 // routed to this QuicConnection has been redirected before control reaches
396 // here. (Check for a bug regression.)
397 DCHECK_EQ(connection_id_, packet.public_header.connection_id);
398 if (debug_visitor_ != nullptr) {
399 debug_visitor_->OnPublicResetPacket(packet);
401 CloseConnection(QUIC_PUBLIC_RESET, true);
403 DVLOG(1) << ENDPOINT << "Connection " << connection_id()
404 << " closed via QUIC_PUBLIC_RESET from peer.";
407 bool QuicConnection::OnProtocolVersionMismatch(QuicVersion received_version) {
408 DVLOG(1) << ENDPOINT << "Received packet with mismatched version "
409 << received_version;
410 // TODO(satyamshekhar): Implement no server state in this mode.
411 if (perspective_ == Perspective::IS_CLIENT) {
412 LOG(DFATAL) << ENDPOINT << "Framer called OnProtocolVersionMismatch. "
413 << "Closing connection.";
414 CloseConnection(QUIC_INTERNAL_ERROR, false);
415 return false;
417 DCHECK_NE(version(), received_version);
419 if (debug_visitor_ != nullptr) {
420 debug_visitor_->OnProtocolVersionMismatch(received_version);
423 switch (version_negotiation_state_) {
424 case START_NEGOTIATION:
425 if (!framer_.IsSupportedVersion(received_version)) {
426 SendVersionNegotiationPacket();
427 version_negotiation_state_ = NEGOTIATION_IN_PROGRESS;
428 return false;
430 break;
432 case NEGOTIATION_IN_PROGRESS:
433 if (!framer_.IsSupportedVersion(received_version)) {
434 SendVersionNegotiationPacket();
435 return false;
437 break;
439 case NEGOTIATED_VERSION:
440 // Might be old packets that were sent by the client before the version
441 // was negotiated. Drop these.
442 return false;
444 default:
445 DCHECK(false);
448 version_negotiation_state_ = NEGOTIATED_VERSION;
449 visitor_->OnSuccessfulVersionNegotiation(received_version);
450 if (debug_visitor_ != nullptr) {
451 debug_visitor_->OnSuccessfulVersionNegotiation(received_version);
453 DVLOG(1) << ENDPOINT << "version negotiated " << received_version;
455 // Store the new version.
456 framer_.set_version(received_version);
458 // TODO(satyamshekhar): Store the sequence number of this packet and close the
459 // connection if we ever received a packet with incorrect version and whose
460 // sequence number is greater.
461 return true;
464 // Handles version negotiation for client connection.
465 void QuicConnection::OnVersionNegotiationPacket(
466 const QuicVersionNegotiationPacket& packet) {
467 // Check that any public reset packet with a different connection ID that was
468 // routed to this QuicConnection has been redirected before control reaches
469 // here. (Check for a bug regression.)
470 DCHECK_EQ(connection_id_, packet.connection_id);
471 if (perspective_ == Perspective::IS_SERVER) {
472 LOG(DFATAL) << ENDPOINT << "Framer parsed VersionNegotiationPacket."
473 << " Closing connection.";
474 CloseConnection(QUIC_INTERNAL_ERROR, false);
475 return;
477 if (debug_visitor_ != nullptr) {
478 debug_visitor_->OnVersionNegotiationPacket(packet);
481 if (version_negotiation_state_ != START_NEGOTIATION) {
482 // Possibly a duplicate version negotiation packet.
483 return;
486 if (std::find(packet.versions.begin(),
487 packet.versions.end(), version()) !=
488 packet.versions.end()) {
489 DLOG(WARNING) << ENDPOINT << "The server already supports our version. "
490 << "It should have accepted our connection.";
491 // Just drop the connection.
492 CloseConnection(QUIC_INVALID_VERSION_NEGOTIATION_PACKET, false);
493 return;
496 if (!SelectMutualVersion(packet.versions)) {
497 SendConnectionCloseWithDetails(QUIC_INVALID_VERSION,
498 "no common version found");
499 return;
502 DVLOG(1) << ENDPOINT
503 << "Negotiated version: " << QuicVersionToString(version());
504 server_supported_versions_ = packet.versions;
505 version_negotiation_state_ = NEGOTIATION_IN_PROGRESS;
506 RetransmitUnackedPackets(ALL_UNACKED_RETRANSMISSION);
509 void QuicConnection::OnRevivedPacket() {
512 bool QuicConnection::OnUnauthenticatedPublicHeader(
513 const QuicPacketPublicHeader& header) {
514 if (header.connection_id == connection_id_) {
515 return true;
518 ++stats_.packets_dropped;
519 DVLOG(1) << ENDPOINT << "Ignoring packet from unexpected ConnectionId: "
520 << header.connection_id << " instead of " << connection_id_;
521 if (debug_visitor_ != nullptr) {
522 debug_visitor_->OnIncorrectConnectionId(header.connection_id);
524 // If this is a server, the dispatcher routes each packet to the
525 // QuicConnection responsible for the packet's connection ID. So if control
526 // arrives here and this is a server, the dispatcher must be malfunctioning.
527 DCHECK_NE(Perspective::IS_SERVER, perspective_);
528 return false;
531 bool QuicConnection::OnUnauthenticatedHeader(const QuicPacketHeader& header) {
532 // Check that any public reset packet with a different connection ID that was
533 // routed to this QuicConnection has been redirected before control reaches
534 // here.
535 DCHECK_EQ(connection_id_, header.public_header.connection_id);
536 return true;
539 void QuicConnection::OnDecryptedPacket(EncryptionLevel level) {
540 last_decrypted_packet_level_ = level;
541 last_packet_decrypted_ = true;
542 // If this packet was foward-secure encrypted and the forward-secure encrypter
543 // is not being used, start using it.
544 if (encryption_level_ != ENCRYPTION_FORWARD_SECURE &&
545 has_forward_secure_encrypter_ && level == ENCRYPTION_FORWARD_SECURE) {
546 SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
550 bool QuicConnection::OnPacketHeader(const QuicPacketHeader& header) {
551 if (debug_visitor_ != nullptr) {
552 debug_visitor_->OnPacketHeader(header);
555 if (!ProcessValidatedPacket()) {
556 return false;
559 // Will be decrement below if we fall through to return true;
560 ++stats_.packets_dropped;
562 if (!Near(header.packet_sequence_number,
563 last_header_.packet_sequence_number)) {
564 DVLOG(1) << ENDPOINT << "Packet " << header.packet_sequence_number
565 << " out of bounds. Discarding";
566 SendConnectionCloseWithDetails(QUIC_INVALID_PACKET_HEADER,
567 "Packet sequence number out of bounds");
568 return false;
571 // If this packet has already been seen, or that the sender
572 // has told us will not be retransmitted, then stop processing the packet.
573 if (!received_packet_manager_.IsAwaitingPacket(
574 header.packet_sequence_number)) {
575 DVLOG(1) << ENDPOINT << "Packet " << header.packet_sequence_number
576 << " no longer being waited for. Discarding.";
577 if (debug_visitor_ != nullptr) {
578 debug_visitor_->OnDuplicatePacket(header.packet_sequence_number);
580 return false;
583 if (version_negotiation_state_ != NEGOTIATED_VERSION) {
584 if (perspective_ == Perspective::IS_SERVER) {
585 if (!header.public_header.version_flag) {
586 DLOG(WARNING) << ENDPOINT << "Packet " << header.packet_sequence_number
587 << " without version flag before version negotiated.";
588 // Packets should have the version flag till version negotiation is
589 // done.
590 CloseConnection(QUIC_INVALID_VERSION, false);
591 return false;
592 } else {
593 DCHECK_EQ(1u, header.public_header.versions.size());
594 DCHECK_EQ(header.public_header.versions[0], version());
595 version_negotiation_state_ = NEGOTIATED_VERSION;
596 visitor_->OnSuccessfulVersionNegotiation(version());
597 if (debug_visitor_ != nullptr) {
598 debug_visitor_->OnSuccessfulVersionNegotiation(version());
601 } else {
602 DCHECK(!header.public_header.version_flag);
603 // If the client gets a packet without the version flag from the server
604 // it should stop sending version since the version negotiation is done.
605 packet_generator_.StopSendingVersion();
606 version_negotiation_state_ = NEGOTIATED_VERSION;
607 visitor_->OnSuccessfulVersionNegotiation(version());
608 if (debug_visitor_ != nullptr) {
609 debug_visitor_->OnSuccessfulVersionNegotiation(version());
614 DCHECK_EQ(NEGOTIATED_VERSION, version_negotiation_state_);
616 --stats_.packets_dropped;
617 DVLOG(1) << ENDPOINT << "Received packet header: " << header;
618 last_header_ = header;
619 DCHECK(connected_);
620 return true;
623 void QuicConnection::OnFecProtectedPayload(StringPiece payload) {
624 DCHECK_EQ(IN_FEC_GROUP, last_header_.is_in_fec_group);
625 DCHECK_NE(0u, last_header_.fec_group);
626 QuicFecGroup* group = GetFecGroup();
627 if (group != nullptr) {
628 group->Update(last_decrypted_packet_level_, last_header_, payload);
632 bool QuicConnection::OnStreamFrame(const QuicStreamFrame& frame) {
633 DCHECK(connected_);
634 if (debug_visitor_ != nullptr) {
635 debug_visitor_->OnStreamFrame(frame);
637 if (frame.stream_id != kCryptoStreamId &&
638 last_decrypted_packet_level_ == ENCRYPTION_NONE) {
639 DLOG(WARNING) << ENDPOINT
640 << "Received an unencrypted data frame: closing connection";
641 SendConnectionClose(QUIC_UNENCRYPTED_STREAM_DATA);
642 return false;
644 last_stream_frames_.push_back(frame);
645 return true;
648 bool QuicConnection::OnAckFrame(const QuicAckFrame& incoming_ack) {
649 DCHECK(connected_);
650 if (debug_visitor_ != nullptr) {
651 debug_visitor_->OnAckFrame(incoming_ack);
653 DVLOG(1) << ENDPOINT << "OnAckFrame: " << incoming_ack;
655 if (last_header_.packet_sequence_number <= largest_seen_packet_with_ack_) {
656 DVLOG(1) << ENDPOINT << "Received an old ack frame: ignoring";
657 return true;
660 if (!ValidateAckFrame(incoming_ack)) {
661 SendConnectionClose(QUIC_INVALID_ACK_DATA);
662 return false;
665 last_ack_frames_.push_back(incoming_ack);
666 return connected_;
669 void QuicConnection::ProcessAckFrame(const QuicAckFrame& incoming_ack) {
670 largest_seen_packet_with_ack_ = last_header_.packet_sequence_number;
671 sent_packet_manager_.OnIncomingAck(incoming_ack,
672 time_of_last_received_packet_);
673 sent_entropy_manager_.ClearEntropyBefore(
674 sent_packet_manager_.least_packet_awaited_by_peer() - 1);
675 if (sent_packet_manager_.HasPendingRetransmissions()) {
676 WriteIfNotBlocked();
679 // Always reset the retransmission alarm when an ack comes in, since we now
680 // have a better estimate of the current rtt than when it was set.
681 QuicTime retransmission_time = sent_packet_manager_.GetRetransmissionTime();
682 retransmission_alarm_->Update(retransmission_time,
683 QuicTime::Delta::FromMilliseconds(1));
686 void QuicConnection::ProcessStopWaitingFrame(
687 const QuicStopWaitingFrame& stop_waiting) {
688 largest_seen_packet_with_stop_waiting_ = last_header_.packet_sequence_number;
689 received_packet_manager_.UpdatePacketInformationSentByPeer(stop_waiting);
690 // Possibly close any FecGroups which are now irrelevant.
691 CloseFecGroupsBefore(stop_waiting.least_unacked + 1);
694 bool QuicConnection::OnStopWaitingFrame(const QuicStopWaitingFrame& frame) {
695 DCHECK(connected_);
697 if (last_header_.packet_sequence_number <=
698 largest_seen_packet_with_stop_waiting_) {
699 DVLOG(1) << ENDPOINT << "Received an old stop waiting frame: ignoring";
700 return true;
703 if (!ValidateStopWaitingFrame(frame)) {
704 SendConnectionClose(QUIC_INVALID_STOP_WAITING_DATA);
705 return false;
708 if (debug_visitor_ != nullptr) {
709 debug_visitor_->OnStopWaitingFrame(frame);
712 last_stop_waiting_frames_.push_back(frame);
713 return connected_;
716 bool QuicConnection::OnPingFrame(const QuicPingFrame& frame) {
717 DCHECK(connected_);
718 if (debug_visitor_ != nullptr) {
719 debug_visitor_->OnPingFrame(frame);
721 last_ping_frames_.push_back(frame);
722 return true;
725 bool QuicConnection::ValidateAckFrame(const QuicAckFrame& incoming_ack) {
726 if (incoming_ack.largest_observed > packet_generator_.sequence_number()) {
727 DLOG(ERROR) << ENDPOINT << "Peer's observed unsent packet:"
728 << incoming_ack.largest_observed << " vs "
729 << packet_generator_.sequence_number();
730 // We got an error for data we have not sent. Error out.
731 return false;
734 if (incoming_ack.largest_observed < sent_packet_manager_.largest_observed()) {
735 DLOG(ERROR) << ENDPOINT << "Peer's largest_observed packet decreased:"
736 << incoming_ack.largest_observed << " vs "
737 << sent_packet_manager_.largest_observed();
738 // A new ack has a diminished largest_observed value. Error out.
739 // If this was an old packet, we wouldn't even have checked.
740 return false;
743 if (!incoming_ack.missing_packets.empty() &&
744 *incoming_ack.missing_packets.rbegin() > incoming_ack.largest_observed) {
745 DLOG(ERROR) << ENDPOINT << "Peer sent missing packet: "
746 << *incoming_ack.missing_packets.rbegin()
747 << " which is greater than largest observed: "
748 << incoming_ack.largest_observed;
749 return false;
752 if (!incoming_ack.missing_packets.empty() &&
753 *incoming_ack.missing_packets.begin() <
754 sent_packet_manager_.least_packet_awaited_by_peer()) {
755 DLOG(ERROR) << ENDPOINT << "Peer sent missing packet: "
756 << *incoming_ack.missing_packets.begin()
757 << " which is smaller than least_packet_awaited_by_peer_: "
758 << sent_packet_manager_.least_packet_awaited_by_peer();
759 return false;
762 if (!sent_entropy_manager_.IsValidEntropy(
763 incoming_ack.largest_observed,
764 incoming_ack.missing_packets,
765 incoming_ack.entropy_hash)) {
766 DLOG(ERROR) << ENDPOINT << "Peer sent invalid entropy.";
767 return false;
770 for (SequenceNumberSet::const_iterator iter =
771 incoming_ack.revived_packets.begin();
772 iter != incoming_ack.revived_packets.end(); ++iter) {
773 if (!ContainsKey(incoming_ack.missing_packets, *iter)) {
774 DLOG(ERROR) << ENDPOINT
775 << "Peer specified revived packet which was not missing.";
776 return false;
779 return true;
782 bool QuicConnection::ValidateStopWaitingFrame(
783 const QuicStopWaitingFrame& stop_waiting) {
784 if (stop_waiting.least_unacked <
785 received_packet_manager_.peer_least_packet_awaiting_ack()) {
786 DLOG(ERROR) << ENDPOINT << "Peer's sent low least_unacked: "
787 << stop_waiting.least_unacked << " vs "
788 << received_packet_manager_.peer_least_packet_awaiting_ack();
789 // We never process old ack frames, so this number should only increase.
790 return false;
793 if (stop_waiting.least_unacked >
794 last_header_.packet_sequence_number) {
795 DLOG(ERROR) << ENDPOINT << "Peer sent least_unacked:"
796 << stop_waiting.least_unacked
797 << " greater than the enclosing packet sequence number:"
798 << last_header_.packet_sequence_number;
799 return false;
802 return true;
805 void QuicConnection::OnFecData(const QuicFecData& fec) {
806 DCHECK_EQ(IN_FEC_GROUP, last_header_.is_in_fec_group);
807 DCHECK_NE(0u, last_header_.fec_group);
808 QuicFecGroup* group = GetFecGroup();
809 if (group != nullptr) {
810 group->UpdateFec(last_decrypted_packet_level_,
811 last_header_.packet_sequence_number, fec);
815 bool QuicConnection::OnRstStreamFrame(const QuicRstStreamFrame& frame) {
816 DCHECK(connected_);
817 if (debug_visitor_ != nullptr) {
818 debug_visitor_->OnRstStreamFrame(frame);
820 DVLOG(1) << ENDPOINT << "Stream reset with error "
821 << QuicUtils::StreamErrorToString(frame.error_code);
822 last_rst_frames_.push_back(frame);
823 return connected_;
826 bool QuicConnection::OnConnectionCloseFrame(
827 const QuicConnectionCloseFrame& frame) {
828 DCHECK(connected_);
829 if (debug_visitor_ != nullptr) {
830 debug_visitor_->OnConnectionCloseFrame(frame);
832 DVLOG(1) << ENDPOINT << "Connection " << connection_id()
833 << " closed with error "
834 << QuicUtils::ErrorToString(frame.error_code)
835 << " " << frame.error_details;
836 last_close_frames_.push_back(frame);
837 return connected_;
840 bool QuicConnection::OnGoAwayFrame(const QuicGoAwayFrame& frame) {
841 DCHECK(connected_);
842 if (debug_visitor_ != nullptr) {
843 debug_visitor_->OnGoAwayFrame(frame);
845 DVLOG(1) << ENDPOINT << "Go away received with error "
846 << QuicUtils::ErrorToString(frame.error_code)
847 << " and reason:" << frame.reason_phrase;
848 last_goaway_frames_.push_back(frame);
849 return connected_;
852 bool QuicConnection::OnWindowUpdateFrame(const QuicWindowUpdateFrame& frame) {
853 DCHECK(connected_);
854 if (debug_visitor_ != nullptr) {
855 debug_visitor_->OnWindowUpdateFrame(frame);
857 DVLOG(1) << ENDPOINT << "WindowUpdate received for stream: "
858 << frame.stream_id << " with byte offset: " << frame.byte_offset;
859 last_window_update_frames_.push_back(frame);
860 return connected_;
863 bool QuicConnection::OnBlockedFrame(const QuicBlockedFrame& frame) {
864 DCHECK(connected_);
865 if (debug_visitor_ != nullptr) {
866 debug_visitor_->OnBlockedFrame(frame);
868 DVLOG(1) << ENDPOINT << "Blocked frame received for stream: "
869 << frame.stream_id;
870 last_blocked_frames_.push_back(frame);
871 return connected_;
874 void QuicConnection::OnPacketComplete() {
875 // Don't do anything if this packet closed the connection.
876 if (!connected_) {
877 ClearLastFrames();
878 return;
881 DVLOG(1) << ENDPOINT << (last_packet_revived_ ? "Revived" : "Got")
882 << " packet " << last_header_.packet_sequence_number
883 << " with " << last_stream_frames_.size()<< " stream frames "
884 << last_ack_frames_.size() << " acks, "
885 << last_stop_waiting_frames_.size() << " stop_waiting, "
886 << last_rst_frames_.size() << " rsts, "
887 << last_goaway_frames_.size() << " goaways, "
888 << last_window_update_frames_.size() << " window updates, "
889 << last_blocked_frames_.size() << " blocked, "
890 << last_ping_frames_.size() << " pings, "
891 << last_close_frames_.size() << " closes, "
892 << "for " << last_header_.public_header.connection_id;
894 ++num_packets_received_since_last_ack_sent_;
896 // Call MaybeQueueAck() before recording the received packet, since we want
897 // to trigger an ack if the newly received packet was previously missing.
898 MaybeQueueAck();
900 // Record received or revived packet to populate ack info correctly before
901 // processing stream frames, since the processing may result in a response
902 // packet with a bundled ack.
903 if (last_packet_revived_) {
904 received_packet_manager_.RecordPacketRevived(
905 last_header_.packet_sequence_number);
906 } else {
907 received_packet_manager_.RecordPacketReceived(
908 last_size_, last_header_, time_of_last_received_packet_);
911 if (!last_stream_frames_.empty()) {
912 visitor_->OnStreamFrames(last_stream_frames_);
915 for (size_t i = 0; i < last_stream_frames_.size(); ++i) {
916 stats_.stream_bytes_received +=
917 last_stream_frames_[i].data.TotalBufferSize();
920 // Process window updates, blocked, stream resets, acks, then congestion
921 // feedback.
922 if (!last_window_update_frames_.empty()) {
923 visitor_->OnWindowUpdateFrames(last_window_update_frames_);
925 if (!last_blocked_frames_.empty()) {
926 visitor_->OnBlockedFrames(last_blocked_frames_);
928 for (size_t i = 0; i < last_goaway_frames_.size(); ++i) {
929 visitor_->OnGoAway(last_goaway_frames_[i]);
931 for (size_t i = 0; i < last_rst_frames_.size(); ++i) {
932 visitor_->OnRstStream(last_rst_frames_[i]);
934 for (size_t i = 0; i < last_ack_frames_.size(); ++i) {
935 ProcessAckFrame(last_ack_frames_[i]);
937 for (size_t i = 0; i < last_stop_waiting_frames_.size(); ++i) {
938 ProcessStopWaitingFrame(last_stop_waiting_frames_[i]);
940 if (!last_close_frames_.empty()) {
941 CloseConnection(last_close_frames_[0].error_code, true);
942 DCHECK(!connected_);
945 // If there are new missing packets to report, send an ack immediately.
946 if (received_packet_manager_.HasNewMissingPackets()) {
947 ack_queued_ = true;
948 ack_alarm_->Cancel();
951 UpdateStopWaitingCount();
952 ClearLastFrames();
953 MaybeCloseIfTooManyOutstandingPackets();
956 void QuicConnection::MaybeQueueAck() {
957 // If the incoming packet was missing, send an ack immediately.
958 ack_queued_ = received_packet_manager_.IsMissing(
959 last_header_.packet_sequence_number);
961 if (!ack_queued_ && ShouldLastPacketInstigateAck()) {
962 if (ack_alarm_->IsSet()) {
963 ack_queued_ = true;
964 } else {
965 // Send an ack much more quickly for crypto handshake packets.
966 QuicTime::Delta delayed_ack_time = sent_packet_manager_.DelayedAckTime();
967 ack_alarm_->Set(clock_->ApproximateNow().Add(delayed_ack_time));
968 DVLOG(1) << "Ack timer set; next packet or timer will trigger ACK.";
972 if (ack_queued_) {
973 ack_alarm_->Cancel();
977 void QuicConnection::ClearLastFrames() {
978 last_stream_frames_.clear();
979 last_ack_frames_.clear();
980 last_stop_waiting_frames_.clear();
981 last_rst_frames_.clear();
982 last_goaway_frames_.clear();
983 last_window_update_frames_.clear();
984 last_blocked_frames_.clear();
985 last_ping_frames_.clear();
986 last_close_frames_.clear();
989 void QuicConnection::MaybeCloseIfTooManyOutstandingPackets() {
990 // This occurs if we don't discard old packets we've sent fast enough.
991 // It's possible largest observed is less than least unacked.
992 if (sent_packet_manager_.largest_observed() >
993 (sent_packet_manager_.GetLeastUnacked() + kMaxTrackedPackets)) {
994 SendConnectionCloseWithDetails(
995 QUIC_TOO_MANY_OUTSTANDING_SENT_PACKETS,
996 StringPrintf("More than %" PRIu64 " outstanding.", kMaxTrackedPackets));
998 // This occurs if there are received packet gaps and the peer does not raise
999 // the least unacked fast enough.
1000 if (received_packet_manager_.NumTrackedPackets() > kMaxTrackedPackets) {
1001 SendConnectionCloseWithDetails(
1002 QUIC_TOO_MANY_OUTSTANDING_RECEIVED_PACKETS,
1003 StringPrintf("More than %" PRIu64 " outstanding.", kMaxTrackedPackets));
1007 void QuicConnection::PopulateAckFrame(QuicAckFrame* ack) {
1008 received_packet_manager_.UpdateReceivedPacketInfo(ack,
1009 clock_->ApproximateNow());
1012 void QuicConnection::PopulateStopWaitingFrame(
1013 QuicStopWaitingFrame* stop_waiting) {
1014 stop_waiting->least_unacked = GetLeastUnacked();
1015 stop_waiting->entropy_hash = sent_entropy_manager_.GetCumulativeEntropy(
1016 stop_waiting->least_unacked - 1);
1019 bool QuicConnection::ShouldLastPacketInstigateAck() const {
1020 if (!last_stream_frames_.empty() ||
1021 !last_goaway_frames_.empty() ||
1022 !last_rst_frames_.empty() ||
1023 !last_window_update_frames_.empty() ||
1024 !last_blocked_frames_.empty() ||
1025 !last_ping_frames_.empty()) {
1026 return true;
1029 if (!last_ack_frames_.empty() && last_ack_frames_.back().is_truncated) {
1030 return true;
1032 // Always send an ack every 20 packets in order to allow the peer to discard
1033 // information from the SentPacketManager and provide an RTT measurement.
1034 if (num_packets_received_since_last_ack_sent_ >=
1035 kMaxPacketsReceivedBeforeAckSend) {
1036 return true;
1038 return false;
1041 void QuicConnection::UpdateStopWaitingCount() {
1042 if (last_ack_frames_.empty()) {
1043 return;
1046 // If the peer is still waiting for a packet that we are no longer planning to
1047 // send, send an ack to raise the high water mark.
1048 if (!last_ack_frames_.back().missing_packets.empty() &&
1049 GetLeastUnacked() > *last_ack_frames_.back().missing_packets.begin()) {
1050 ++stop_waiting_count_;
1051 } else {
1052 stop_waiting_count_ = 0;
1056 QuicPacketSequenceNumber QuicConnection::GetLeastUnacked() const {
1057 return sent_packet_manager_.GetLeastUnacked();
1060 void QuicConnection::MaybeSendInResponseToPacket() {
1061 if (!connected_) {
1062 return;
1064 ScopedPacketBundler bundler(this, ack_queued_ ? SEND_ACK : NO_ACK);
1066 // Now that we have received an ack, we might be able to send packets which
1067 // are queued locally, or drain streams which are blocked.
1068 if (CanWrite(HAS_RETRANSMITTABLE_DATA)) {
1069 OnCanWrite();
1073 void QuicConnection::SendVersionNegotiationPacket() {
1074 // TODO(alyssar): implement zero server state negotiation.
1075 pending_version_negotiation_packet_ = true;
1076 if (writer_->IsWriteBlocked()) {
1077 visitor_->OnWriteBlocked();
1078 return;
1080 DVLOG(1) << ENDPOINT << "Sending version negotiation packet: {"
1081 << QuicVersionVectorToString(framer_.supported_versions()) << "}";
1082 scoped_ptr<QuicEncryptedPacket> version_packet(
1083 packet_generator_.SerializeVersionNegotiationPacket(
1084 framer_.supported_versions()));
1085 WriteResult result = writer_->WritePacket(
1086 version_packet->data(), version_packet->length(),
1087 self_address().address(), peer_address());
1089 if (result.status == WRITE_STATUS_ERROR) {
1090 // We can't send an error as the socket is presumably borked.
1091 CloseConnection(QUIC_PACKET_WRITE_ERROR, false);
1092 return;
1094 if (result.status == WRITE_STATUS_BLOCKED) {
1095 visitor_->OnWriteBlocked();
1096 if (writer_->IsWriteBlockedDataBuffered()) {
1097 pending_version_negotiation_packet_ = false;
1099 return;
1102 pending_version_negotiation_packet_ = false;
1105 QuicConsumedData QuicConnection::SendStreamData(
1106 QuicStreamId id,
1107 const IOVector& data,
1108 QuicStreamOffset offset,
1109 bool fin,
1110 FecProtection fec_protection,
1111 QuicAckNotifier::DelegateInterface* delegate) {
1112 if (!fin && data.Empty()) {
1113 LOG(DFATAL) << "Attempt to send empty stream frame";
1114 return QuicConsumedData(0, false);
1117 // Opportunistically bundle an ack with every outgoing packet.
1118 // Particularly, we want to bundle with handshake packets since we don't know
1119 // which decrypter will be used on an ack packet following a handshake
1120 // packet (a handshake packet from client to server could result in a REJ or a
1121 // SHLO from the server, leading to two different decrypters at the server.)
1123 // TODO(jri): Note that ConsumeData may cause a response packet to be sent.
1124 // We may end up sending stale ack information if there are undecryptable
1125 // packets hanging around and/or there are revivable packets which may get
1126 // handled after this packet is sent. Change ScopedPacketBundler to do the
1127 // right thing: check ack_queued_, and then check undecryptable packets and
1128 // also if there is possibility of revival. Only bundle an ack if there's no
1129 // processing left that may cause received_info_ to change.
1130 ScopedPacketBundler ack_bundler(this, BUNDLE_PENDING_ACK);
1131 return packet_generator_.ConsumeData(id, data, offset, fin, fec_protection,
1132 delegate);
1135 void QuicConnection::SendRstStream(QuicStreamId id,
1136 QuicRstStreamErrorCode error,
1137 QuicStreamOffset bytes_written) {
1138 // Opportunistically bundle an ack with this outgoing packet.
1139 ScopedPacketBundler ack_bundler(this, BUNDLE_PENDING_ACK);
1140 packet_generator_.AddControlFrame(QuicFrame(new QuicRstStreamFrame(
1141 id, AdjustErrorForVersion(error, version()), bytes_written)));
1142 if (!FLAGS_quic_do_not_retransmit_for_reset_streams) {
1143 return;
1146 sent_packet_manager_.CancelRetransmissionsForStream(id);
1147 // Remove all queued packets which only contain data for the reset stream.
1148 QueuedPacketList::iterator packet_iterator = queued_packets_.begin();
1149 while (packet_iterator != queued_packets_.end()) {
1150 RetransmittableFrames* retransmittable_frames =
1151 packet_iterator->serialized_packet.retransmittable_frames;
1152 if (!retransmittable_frames) {
1153 ++packet_iterator;
1154 continue;
1156 retransmittable_frames->RemoveFramesForStream(id);
1157 if (!retransmittable_frames->frames().empty()) {
1158 ++packet_iterator;
1159 continue;
1161 delete packet_iterator->serialized_packet.retransmittable_frames;
1162 delete packet_iterator->serialized_packet.packet;
1163 packet_iterator->serialized_packet.retransmittable_frames = nullptr;
1164 packet_iterator->serialized_packet.packet = nullptr;
1165 packet_iterator = queued_packets_.erase(packet_iterator);
1169 void QuicConnection::SendWindowUpdate(QuicStreamId id,
1170 QuicStreamOffset byte_offset) {
1171 // Opportunistically bundle an ack with this outgoing packet.
1172 ScopedPacketBundler ack_bundler(this, BUNDLE_PENDING_ACK);
1173 packet_generator_.AddControlFrame(
1174 QuicFrame(new QuicWindowUpdateFrame(id, byte_offset)));
1177 void QuicConnection::SendBlocked(QuicStreamId id) {
1178 // Opportunistically bundle an ack with this outgoing packet.
1179 ScopedPacketBundler ack_bundler(this, BUNDLE_PENDING_ACK);
1180 packet_generator_.AddControlFrame(QuicFrame(new QuicBlockedFrame(id)));
1183 const QuicConnectionStats& QuicConnection::GetStats() {
1184 const RttStats* rtt_stats = sent_packet_manager_.GetRttStats();
1186 // Update rtt and estimated bandwidth.
1187 QuicTime::Delta min_rtt = rtt_stats->min_rtt();
1188 if (min_rtt.IsZero()) {
1189 // If min RTT has not been set, use initial RTT instead.
1190 min_rtt = QuicTime::Delta::FromMicroseconds(rtt_stats->initial_rtt_us());
1192 stats_.min_rtt_us = min_rtt.ToMicroseconds();
1194 QuicTime::Delta srtt = rtt_stats->smoothed_rtt();
1195 if (srtt.IsZero()) {
1196 // If SRTT has not been set, use initial RTT instead.
1197 srtt = QuicTime::Delta::FromMicroseconds(rtt_stats->initial_rtt_us());
1199 stats_.srtt_us = srtt.ToMicroseconds();
1201 stats_.estimated_bandwidth = sent_packet_manager_.BandwidthEstimate();
1202 stats_.max_packet_size = packet_generator_.max_packet_length();
1203 return stats_;
1206 void QuicConnection::ProcessUdpPacket(const IPEndPoint& self_address,
1207 const IPEndPoint& peer_address,
1208 const QuicEncryptedPacket& packet) {
1209 if (!connected_) {
1210 return;
1212 // TODO(rtenneti): Remove ScopedTracker below once crbug.com/462789 is fixed.
1213 tracked_objects::ScopedTracker tracking_profile(
1214 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1215 "462789 QuicConnection::ProcessUdpPacket"));
1216 if (debug_visitor_ != nullptr) {
1217 debug_visitor_->OnPacketReceived(self_address, peer_address, packet);
1219 last_size_ = packet.length();
1221 CheckForAddressMigration(self_address, peer_address);
1223 stats_.bytes_received += packet.length();
1224 ++stats_.packets_received;
1226 if (!framer_.ProcessPacket(packet)) {
1227 // If we are unable to decrypt this packet, it might be
1228 // because the CHLO or SHLO packet was lost.
1229 if (framer_.error() == QUIC_DECRYPTION_FAILURE) {
1230 if (encryption_level_ != ENCRYPTION_FORWARD_SECURE &&
1231 undecryptable_packets_.size() < max_undecryptable_packets_) {
1232 QueueUndecryptablePacket(packet);
1233 } else if (debug_visitor_ != nullptr) {
1234 debug_visitor_->OnUndecryptablePacket();
1237 DVLOG(1) << ENDPOINT << "Unable to process packet. Last packet processed: "
1238 << last_header_.packet_sequence_number;
1239 return;
1242 ++stats_.packets_processed;
1243 MaybeProcessUndecryptablePackets();
1244 MaybeProcessRevivedPacket();
1245 MaybeSendInResponseToPacket();
1246 SetPingAlarm();
1249 void QuicConnection::CheckForAddressMigration(
1250 const IPEndPoint& self_address, const IPEndPoint& peer_address) {
1251 peer_ip_changed_ = false;
1252 peer_port_changed_ = false;
1253 self_ip_changed_ = false;
1254 self_port_changed_ = false;
1256 if (peer_address_.address().empty()) {
1257 peer_address_ = peer_address;
1259 if (self_address_.address().empty()) {
1260 self_address_ = self_address;
1263 if (!peer_address.address().empty() && !peer_address_.address().empty()) {
1264 peer_ip_changed_ = (peer_address.address() != peer_address_.address());
1265 peer_port_changed_ = (peer_address.port() != peer_address_.port());
1267 // Store in case we want to migrate connection in ProcessValidatedPacket.
1268 migrating_peer_port_ = peer_address.port();
1271 if (!self_address.address().empty() && !self_address_.address().empty()) {
1272 self_ip_changed_ = (self_address.address() != self_address_.address());
1273 self_port_changed_ = (self_address.port() != self_address_.port());
1277 void QuicConnection::OnCanWrite() {
1278 DCHECK(!writer_->IsWriteBlocked());
1280 WriteQueuedPackets();
1281 WritePendingRetransmissions();
1283 // Sending queued packets may have caused the socket to become write blocked,
1284 // or the congestion manager to prohibit sending. If we've sent everything
1285 // we had queued and we're still not blocked, let the visitor know it can
1286 // write more.
1287 if (!CanWrite(HAS_RETRANSMITTABLE_DATA)) {
1288 return;
1291 { // Limit the scope of the bundler. ACK inclusion happens elsewhere.
1292 ScopedPacketBundler bundler(this, NO_ACK);
1293 visitor_->OnCanWrite();
1296 // After the visitor writes, it may have caused the socket to become write
1297 // blocked or the congestion manager to prohibit sending, so check again.
1298 if (visitor_->WillingAndAbleToWrite() &&
1299 !resume_writes_alarm_->IsSet() &&
1300 CanWrite(HAS_RETRANSMITTABLE_DATA)) {
1301 // We're not write blocked, but some stream didn't write out all of its
1302 // bytes. Register for 'immediate' resumption so we'll keep writing after
1303 // other connections and events have had a chance to use the thread.
1304 resume_writes_alarm_->Set(clock_->ApproximateNow());
1308 void QuicConnection::WriteIfNotBlocked() {
1309 if (!writer_->IsWriteBlocked()) {
1310 OnCanWrite();
1314 bool QuicConnection::ProcessValidatedPacket() {
1315 if (peer_ip_changed_ || self_ip_changed_ || self_port_changed_) {
1316 SendConnectionCloseWithDetails(
1317 QUIC_ERROR_MIGRATING_ADDRESS,
1318 "Neither IP address migration, nor self port migration are supported.");
1319 return false;
1322 // Peer port migration is supported, do it now if port has changed.
1323 if (peer_port_changed_) {
1324 DVLOG(1) << ENDPOINT << "Peer's port changed from "
1325 << peer_address_.port() << " to " << migrating_peer_port_
1326 << ", migrating connection.";
1327 peer_address_ = IPEndPoint(peer_address_.address(), migrating_peer_port_);
1330 time_of_last_received_packet_ = clock_->Now();
1331 DVLOG(1) << ENDPOINT << "time of last received packet: "
1332 << time_of_last_received_packet_.ToDebuggingValue();
1334 if (perspective_ == Perspective::IS_SERVER &&
1335 encryption_level_ == ENCRYPTION_NONE &&
1336 last_size_ > packet_generator_.max_packet_length()) {
1337 set_max_packet_length(last_size_);
1339 return true;
1342 void QuicConnection::WriteQueuedPackets() {
1343 DCHECK(!writer_->IsWriteBlocked());
1345 if (pending_version_negotiation_packet_) {
1346 SendVersionNegotiationPacket();
1349 QueuedPacketList::iterator packet_iterator = queued_packets_.begin();
1350 while (packet_iterator != queued_packets_.end() &&
1351 WritePacket(&(*packet_iterator))) {
1352 packet_iterator = queued_packets_.erase(packet_iterator);
1356 void QuicConnection::WritePendingRetransmissions() {
1357 // Keep writing as long as there's a pending retransmission which can be
1358 // written.
1359 while (sent_packet_manager_.HasPendingRetransmissions()) {
1360 const QuicSentPacketManager::PendingRetransmission pending =
1361 sent_packet_manager_.NextPendingRetransmission();
1362 if (!CanWrite(HAS_RETRANSMITTABLE_DATA)) {
1363 break;
1366 // Re-packetize the frames with a new sequence number for retransmission.
1367 // Retransmitted data packets do not use FEC, even when it's enabled.
1368 // Retransmitted packets use the same sequence number length as the
1369 // original.
1370 // Flush the packet generator before making a new packet.
1371 // TODO(ianswett): Implement ReserializeAllFrames as a separate path that
1372 // does not require the creator to be flushed.
1373 packet_generator_.FlushAllQueuedFrames();
1374 SerializedPacket serialized_packet = packet_generator_.ReserializeAllFrames(
1375 pending.retransmittable_frames, pending.sequence_number_length);
1376 if (serialized_packet.packet == nullptr) {
1377 // We failed to serialize the packet, so close the connection.
1378 // CloseConnection does not send close packet, so no infinite loop here.
1379 CloseConnection(QUIC_ENCRYPTION_FAILURE, false);
1380 return;
1383 DVLOG(1) << ENDPOINT << "Retransmitting " << pending.sequence_number
1384 << " as " << serialized_packet.sequence_number;
1385 SendOrQueuePacket(
1386 QueuedPacket(serialized_packet,
1387 pending.retransmittable_frames.encryption_level(),
1388 pending.transmission_type,
1389 pending.sequence_number));
1393 void QuicConnection::RetransmitUnackedPackets(
1394 TransmissionType retransmission_type) {
1395 sent_packet_manager_.RetransmitUnackedPackets(retransmission_type);
1397 WriteIfNotBlocked();
1400 void QuicConnection::NeuterUnencryptedPackets() {
1401 sent_packet_manager_.NeuterUnencryptedPackets();
1402 // This may have changed the retransmission timer, so re-arm it.
1403 QuicTime retransmission_time = sent_packet_manager_.GetRetransmissionTime();
1404 retransmission_alarm_->Update(retransmission_time,
1405 QuicTime::Delta::FromMilliseconds(1));
1408 bool QuicConnection::ShouldGeneratePacket(
1409 TransmissionType transmission_type,
1410 HasRetransmittableData retransmittable,
1411 IsHandshake handshake) {
1412 // We should serialize handshake packets immediately to ensure that they
1413 // end up sent at the right encryption level.
1414 if (handshake == IS_HANDSHAKE) {
1415 return true;
1418 return CanWrite(retransmittable);
1421 bool QuicConnection::CanWrite(HasRetransmittableData retransmittable) {
1422 if (!connected_) {
1423 return false;
1426 if (writer_->IsWriteBlocked()) {
1427 visitor_->OnWriteBlocked();
1428 return false;
1431 QuicTime now = clock_->Now();
1432 QuicTime::Delta delay = sent_packet_manager_.TimeUntilSend(
1433 now, retransmittable);
1434 if (delay.IsInfinite()) {
1435 send_alarm_->Cancel();
1436 return false;
1439 // If the scheduler requires a delay, then we can not send this packet now.
1440 if (!delay.IsZero()) {
1441 send_alarm_->Update(now.Add(delay), QuicTime::Delta::FromMilliseconds(1));
1442 DVLOG(1) << ENDPOINT << "Delaying sending " << delay.ToMilliseconds()
1443 << "ms";
1444 return false;
1446 send_alarm_->Cancel();
1447 return true;
1450 bool QuicConnection::WritePacket(QueuedPacket* packet) {
1451 if (!WritePacketInner(packet)) {
1452 return false;
1454 delete packet->serialized_packet.retransmittable_frames;
1455 delete packet->serialized_packet.packet;
1456 packet->serialized_packet.retransmittable_frames = nullptr;
1457 packet->serialized_packet.packet = nullptr;
1458 return true;
1461 bool QuicConnection::WritePacketInner(QueuedPacket* packet) {
1462 if (ShouldDiscardPacket(*packet)) {
1463 ++stats_.packets_discarded;
1464 return true;
1466 // Connection close packets are encrypted and saved, so don't exit early.
1467 const bool is_connection_close = IsConnectionClose(*packet);
1468 if (writer_->IsWriteBlocked() && !is_connection_close) {
1469 return false;
1472 QuicPacketSequenceNumber sequence_number =
1473 packet->serialized_packet.sequence_number;
1474 DCHECK_LE(sequence_number_of_last_sent_packet_, sequence_number);
1475 sequence_number_of_last_sent_packet_ = sequence_number;
1477 QuicEncryptedPacket* encrypted = packet->serialized_packet.packet;
1478 // Connection close packets are eventually owned by TimeWaitListManager.
1479 // Others are deleted at the end of this call.
1480 if (is_connection_close) {
1481 DCHECK(connection_close_packet_.get() == nullptr);
1482 connection_close_packet_.reset(encrypted);
1483 packet->serialized_packet.packet = nullptr;
1484 // This assures we won't try to write *forced* packets when blocked.
1485 // Return true to stop processing.
1486 if (writer_->IsWriteBlocked()) {
1487 visitor_->OnWriteBlocked();
1488 return true;
1492 if (!FLAGS_quic_allow_oversized_packets_for_test) {
1493 DCHECK_LE(encrypted->length(), kMaxPacketSize);
1495 DCHECK_LE(encrypted->length(), packet_generator_.max_packet_length());
1496 DVLOG(1) << ENDPOINT << "Sending packet " << sequence_number << " : "
1497 << (packet->serialized_packet.is_fec_packet
1498 ? "FEC "
1499 : (IsRetransmittable(*packet) == HAS_RETRANSMITTABLE_DATA
1500 ? "data bearing "
1501 : " ack only ")) << ", encryption level: "
1502 << QuicUtils::EncryptionLevelToString(packet->encryption_level)
1503 << ", encrypted length:" << encrypted->length();
1504 DVLOG(2) << ENDPOINT << "packet(" << sequence_number << "): " << std::endl
1505 << QuicUtils::StringToHexASCIIDump(encrypted->AsStringPiece());
1507 // Measure the RTT from before the write begins to avoid underestimating the
1508 // min_rtt_, especially in cases where the thread blocks or gets swapped out
1509 // during the WritePacket below.
1510 QuicTime packet_send_time = clock_->Now();
1511 WriteResult result = writer_->WritePacket(encrypted->data(),
1512 encrypted->length(),
1513 self_address().address(),
1514 peer_address());
1515 if (result.error_code == ERR_IO_PENDING) {
1516 DCHECK_EQ(WRITE_STATUS_BLOCKED, result.status);
1519 if (result.status == WRITE_STATUS_BLOCKED) {
1520 visitor_->OnWriteBlocked();
1521 // If the socket buffers the the data, then the packet should not
1522 // be queued and sent again, which would result in an unnecessary
1523 // duplicate packet being sent. The helper must call OnCanWrite
1524 // when the write completes, and OnWriteError if an error occurs.
1525 if (!writer_->IsWriteBlockedDataBuffered()) {
1526 return false;
1529 if (result.status != WRITE_STATUS_ERROR && debug_visitor_ != nullptr) {
1530 // Pass the write result to the visitor.
1531 debug_visitor_->OnPacketSent(packet->serialized_packet,
1532 packet->original_sequence_number,
1533 packet->encryption_level,
1534 packet->transmission_type,
1535 *encrypted,
1536 packet_send_time);
1538 if (packet->transmission_type == NOT_RETRANSMISSION) {
1539 time_of_last_sent_new_packet_ = packet_send_time;
1541 SetPingAlarm();
1542 MaybeSetFecAlarm(sequence_number);
1543 DVLOG(1) << ENDPOINT << "time we began writing last sent packet: "
1544 << packet_send_time.ToDebuggingValue();
1546 // TODO(ianswett): Change the sequence number length and other packet creator
1547 // options by a more explicit API than setting a struct value directly,
1548 // perhaps via the NetworkChangeVisitor.
1549 packet_generator_.UpdateSequenceNumberLength(
1550 sent_packet_manager_.least_packet_awaited_by_peer(),
1551 sent_packet_manager_.EstimateMaxPacketsInFlight(max_packet_length()));
1553 bool reset_retransmission_alarm = sent_packet_manager_.OnPacketSent(
1554 &packet->serialized_packet,
1555 packet->original_sequence_number,
1556 packet_send_time,
1557 encrypted->length(),
1558 packet->transmission_type,
1559 IsRetransmittable(*packet));
1561 if (reset_retransmission_alarm || !retransmission_alarm_->IsSet()) {
1562 retransmission_alarm_->Update(sent_packet_manager_.GetRetransmissionTime(),
1563 QuicTime::Delta::FromMilliseconds(1));
1566 stats_.bytes_sent += result.bytes_written;
1567 ++stats_.packets_sent;
1568 if (packet->transmission_type != NOT_RETRANSMISSION) {
1569 stats_.bytes_retransmitted += result.bytes_written;
1570 ++stats_.packets_retransmitted;
1573 if (result.status == WRITE_STATUS_ERROR) {
1574 OnWriteError(result.error_code);
1575 DLOG(ERROR) << ENDPOINT << "failed writing " << encrypted->length()
1576 << "bytes "
1577 << " from host " << self_address().ToStringWithoutPort()
1578 << " to address " << peer_address().ToString();
1579 return false;
1582 return true;
1585 bool QuicConnection::ShouldDiscardPacket(const QueuedPacket& packet) {
1586 if (!connected_) {
1587 DVLOG(1) << ENDPOINT
1588 << "Not sending packet as connection is disconnected.";
1589 return true;
1592 QuicPacketSequenceNumber sequence_number =
1593 packet.serialized_packet.sequence_number;
1594 if (encryption_level_ == ENCRYPTION_FORWARD_SECURE &&
1595 packet.encryption_level == ENCRYPTION_NONE) {
1596 // Drop packets that are NULL encrypted since the peer won't accept them
1597 // anymore.
1598 DVLOG(1) << ENDPOINT << "Dropping NULL encrypted packet: "
1599 << sequence_number << " since the connection is forward secure.";
1600 return true;
1603 // If a retransmission has been acked before sending, don't send it.
1604 // This occurs if a packet gets serialized, queued, then discarded.
1605 if (packet.transmission_type != NOT_RETRANSMISSION &&
1606 (!sent_packet_manager_.IsUnacked(packet.original_sequence_number) ||
1607 !sent_packet_manager_.HasRetransmittableFrames(
1608 packet.original_sequence_number))) {
1609 DVLOG(1) << ENDPOINT << "Dropping unacked packet: " << sequence_number
1610 << " A previous transmission was acked while write blocked.";
1611 return true;
1614 return false;
1617 void QuicConnection::OnWriteError(int error_code) {
1618 DVLOG(1) << ENDPOINT << "Write failed with error: " << error_code
1619 << " (" << ErrorToString(error_code) << ")";
1620 // We can't send an error as the socket is presumably borked.
1621 CloseConnection(QUIC_PACKET_WRITE_ERROR, false);
1624 void QuicConnection::OnSerializedPacket(
1625 const SerializedPacket& serialized_packet) {
1626 if (serialized_packet.packet == nullptr) {
1627 // We failed to serialize the packet, so close the connection.
1628 // CloseConnection does not send close packet, so no infinite loop here.
1629 CloseConnection(QUIC_ENCRYPTION_FAILURE, false);
1630 return;
1632 if (serialized_packet.retransmittable_frames) {
1633 sent_packet_manager_.OnSerializedPacket(serialized_packet);
1635 if (serialized_packet.is_fec_packet && fec_alarm_->IsSet()) {
1636 // If an FEC packet is serialized with the FEC alarm set, cancel the alarm.
1637 fec_alarm_->Cancel();
1639 SendOrQueuePacket(QueuedPacket(serialized_packet, encryption_level_));
1642 void QuicConnection::OnCongestionWindowChange() {
1643 packet_generator_.OnCongestionWindowChange(
1644 sent_packet_manager_.EstimateMaxPacketsInFlight(max_packet_length()));
1645 visitor_->OnCongestionWindowChange(clock_->ApproximateNow());
1648 void QuicConnection::OnRttChange() {
1649 // Uses the connection's smoothed RTT. If zero, uses initial_rtt.
1650 QuicTime::Delta rtt = sent_packet_manager_.GetRttStats()->smoothed_rtt();
1651 if (rtt.IsZero()) {
1652 rtt = QuicTime::Delta::FromMicroseconds(
1653 sent_packet_manager_.GetRttStats()->initial_rtt_us());
1655 packet_generator_.OnRttChange(rtt);
1658 void QuicConnection::OnHandshakeComplete() {
1659 sent_packet_manager_.SetHandshakeConfirmed();
1660 // The client should immediately ack the SHLO to confirm the handshake is
1661 // complete with the server.
1662 if (perspective_ == Perspective::IS_CLIENT && !ack_queued_) {
1663 ack_alarm_->Cancel();
1664 ack_alarm_->Set(clock_->ApproximateNow());
1668 void QuicConnection::SendOrQueuePacket(QueuedPacket packet) {
1669 // The caller of this function is responsible for checking CanWrite().
1670 if (packet.serialized_packet.packet == nullptr) {
1671 LOG(DFATAL)
1672 << "packet.serialized_packet.packet == nullptr in to SendOrQueuePacket";
1673 return;
1676 sent_entropy_manager_.RecordPacketEntropyHash(
1677 packet.serialized_packet.sequence_number,
1678 packet.serialized_packet.entropy_hash);
1679 if (!WritePacket(&packet)) {
1680 queued_packets_.push_back(packet);
1683 // If a forward-secure encrypter is available but is not being used and the
1684 // next sequence number is the first packet which requires
1685 // forward security, start using the forward-secure encrypter.
1686 if (encryption_level_ != ENCRYPTION_FORWARD_SECURE &&
1687 has_forward_secure_encrypter_ &&
1688 packet.serialized_packet.sequence_number >=
1689 first_required_forward_secure_packet_ - 1) {
1690 SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
1694 void QuicConnection::SendPing() {
1695 if (retransmission_alarm_->IsSet()) {
1696 return;
1698 packet_generator_.AddControlFrame(QuicFrame(new QuicPingFrame));
1701 void QuicConnection::SendAck() {
1702 ack_alarm_->Cancel();
1703 stop_waiting_count_ = 0;
1704 num_packets_received_since_last_ack_sent_ = 0;
1706 packet_generator_.SetShouldSendAck(true);
1709 void QuicConnection::OnRetransmissionTimeout() {
1710 if (!sent_packet_manager_.HasUnackedPackets()) {
1711 return;
1714 sent_packet_manager_.OnRetransmissionTimeout();
1715 WriteIfNotBlocked();
1717 // A write failure can result in the connection being closed, don't attempt to
1718 // write further packets, or to set alarms.
1719 if (!connected_) {
1720 return;
1723 // In the TLP case, the SentPacketManager gives the connection the opportunity
1724 // to send new data before retransmitting.
1725 if (sent_packet_manager_.MaybeRetransmitTailLossProbe()) {
1726 // Send the pending retransmission now that it's been queued.
1727 WriteIfNotBlocked();
1730 // Ensure the retransmission alarm is always set if there are unacked packets
1731 // and nothing waiting to be sent.
1732 if (!HasQueuedData() && !retransmission_alarm_->IsSet()) {
1733 QuicTime rto_timeout = sent_packet_manager_.GetRetransmissionTime();
1734 if (rto_timeout.IsInitialized()) {
1735 retransmission_alarm_->Set(rto_timeout);
1740 void QuicConnection::SetEncrypter(EncryptionLevel level,
1741 QuicEncrypter* encrypter) {
1742 packet_generator_.SetEncrypter(level, encrypter);
1743 if (level == ENCRYPTION_FORWARD_SECURE) {
1744 has_forward_secure_encrypter_ = true;
1745 first_required_forward_secure_packet_ =
1746 sequence_number_of_last_sent_packet_ +
1747 // 3 times the current congestion window (in slow start) should cover
1748 // about two full round trips worth of packets, which should be
1749 // sufficient.
1750 3 * sent_packet_manager_.EstimateMaxPacketsInFlight(
1751 max_packet_length());
1755 void QuicConnection::SetDefaultEncryptionLevel(EncryptionLevel level) {
1756 encryption_level_ = level;
1757 packet_generator_.set_encryption_level(level);
1760 void QuicConnection::SetDecrypter(QuicDecrypter* decrypter,
1761 EncryptionLevel level) {
1762 framer_.SetDecrypter(decrypter, level);
1765 void QuicConnection::SetAlternativeDecrypter(QuicDecrypter* decrypter,
1766 EncryptionLevel level,
1767 bool latch_once_used) {
1768 framer_.SetAlternativeDecrypter(decrypter, level, latch_once_used);
1771 const QuicDecrypter* QuicConnection::decrypter() const {
1772 return framer_.decrypter();
1775 const QuicDecrypter* QuicConnection::alternative_decrypter() const {
1776 return framer_.alternative_decrypter();
1779 void QuicConnection::QueueUndecryptablePacket(
1780 const QuicEncryptedPacket& packet) {
1781 DVLOG(1) << ENDPOINT << "Queueing undecryptable packet.";
1782 undecryptable_packets_.push_back(packet.Clone());
1785 void QuicConnection::MaybeProcessUndecryptablePackets() {
1786 if (undecryptable_packets_.empty() || encryption_level_ == ENCRYPTION_NONE) {
1787 return;
1790 while (connected_ && !undecryptable_packets_.empty()) {
1791 DVLOG(1) << ENDPOINT << "Attempting to process undecryptable packet";
1792 QuicEncryptedPacket* packet = undecryptable_packets_.front();
1793 if (!framer_.ProcessPacket(*packet) &&
1794 framer_.error() == QUIC_DECRYPTION_FAILURE) {
1795 DVLOG(1) << ENDPOINT << "Unable to process undecryptable packet...";
1796 break;
1798 DVLOG(1) << ENDPOINT << "Processed undecryptable packet!";
1799 ++stats_.packets_processed;
1800 delete packet;
1801 undecryptable_packets_.pop_front();
1804 // Once forward secure encryption is in use, there will be no
1805 // new keys installed and hence any undecryptable packets will
1806 // never be able to be decrypted.
1807 if (encryption_level_ == ENCRYPTION_FORWARD_SECURE) {
1808 if (debug_visitor_ != nullptr) {
1809 // TODO(rtenneti): perhaps more efficient to pass the number of
1810 // undecryptable packets as the argument to OnUndecryptablePacket so that
1811 // we just need to call OnUndecryptablePacket once?
1812 for (size_t i = 0; i < undecryptable_packets_.size(); ++i) {
1813 debug_visitor_->OnUndecryptablePacket();
1816 STLDeleteElements(&undecryptable_packets_);
1820 void QuicConnection::MaybeProcessRevivedPacket() {
1821 QuicFecGroup* group = GetFecGroup();
1822 if (!connected_ || group == nullptr || !group->CanRevive()) {
1823 return;
1825 QuicPacketHeader revived_header;
1826 char revived_payload[kMaxPacketSize];
1827 size_t len = group->Revive(&revived_header, revived_payload, kMaxPacketSize);
1828 revived_header.public_header.connection_id = connection_id_;
1829 revived_header.public_header.connection_id_length =
1830 last_header_.public_header.connection_id_length;
1831 revived_header.public_header.version_flag = false;
1832 revived_header.public_header.reset_flag = false;
1833 revived_header.public_header.sequence_number_length =
1834 last_header_.public_header.sequence_number_length;
1835 revived_header.fec_flag = false;
1836 revived_header.is_in_fec_group = NOT_IN_FEC_GROUP;
1837 revived_header.fec_group = 0;
1838 group_map_.erase(last_header_.fec_group);
1839 last_decrypted_packet_level_ = group->effective_encryption_level();
1840 DCHECK_LT(last_decrypted_packet_level_, NUM_ENCRYPTION_LEVELS);
1841 delete group;
1843 last_packet_revived_ = true;
1844 if (debug_visitor_ != nullptr) {
1845 debug_visitor_->OnRevivedPacket(revived_header,
1846 StringPiece(revived_payload, len));
1849 ++stats_.packets_revived;
1850 framer_.ProcessRevivedPacket(&revived_header,
1851 StringPiece(revived_payload, len));
1854 QuicFecGroup* QuicConnection::GetFecGroup() {
1855 QuicFecGroupNumber fec_group_num = last_header_.fec_group;
1856 if (fec_group_num == 0) {
1857 return nullptr;
1859 if (!ContainsKey(group_map_, fec_group_num)) {
1860 if (group_map_.size() >= kMaxFecGroups) { // Too many groups
1861 if (fec_group_num < group_map_.begin()->first) {
1862 // The group being requested is a group we've seen before and deleted.
1863 // Don't recreate it.
1864 return nullptr;
1866 // Clear the lowest group number.
1867 delete group_map_.begin()->second;
1868 group_map_.erase(group_map_.begin());
1870 group_map_[fec_group_num] = new QuicFecGroup();
1872 return group_map_[fec_group_num];
1875 void QuicConnection::SendConnectionClose(QuicErrorCode error) {
1876 SendConnectionCloseWithDetails(error, string());
1879 void QuicConnection::SendConnectionCloseWithDetails(QuicErrorCode error,
1880 const string& details) {
1881 // If we're write blocked, WritePacket() will not send, but will capture the
1882 // serialized packet.
1883 SendConnectionClosePacket(error, details);
1884 if (connected_) {
1885 // It's possible that while sending the connection close packet, we get a
1886 // socket error and disconnect right then and there. Avoid a double
1887 // disconnect in that case.
1888 CloseConnection(error, false);
1892 void QuicConnection::SendConnectionClosePacket(QuicErrorCode error,
1893 const string& details) {
1894 DVLOG(1) << ENDPOINT << "Force closing " << connection_id()
1895 << " with error " << QuicUtils::ErrorToString(error)
1896 << " (" << error << ") " << details;
1897 // Don't send explicit connection close packets for timeouts.
1898 // This is particularly important on mobile, where connections are short.
1899 if (silent_close_enabled_ &&
1900 error == QuicErrorCode::QUIC_CONNECTION_TIMED_OUT) {
1901 return;
1903 ScopedPacketBundler ack_bundler(this, SEND_ACK);
1904 QuicConnectionCloseFrame* frame = new QuicConnectionCloseFrame();
1905 frame->error_code = error;
1906 frame->error_details = details;
1907 packet_generator_.AddControlFrame(QuicFrame(frame));
1908 packet_generator_.FlushAllQueuedFrames();
1911 void QuicConnection::CloseConnection(QuicErrorCode error, bool from_peer) {
1912 if (!connected_) {
1913 DLOG(DFATAL) << "Error: attempt to close an already closed connection"
1914 << base::debug::StackTrace().ToString();
1915 return;
1917 connected_ = false;
1918 if (debug_visitor_ != nullptr) {
1919 debug_visitor_->OnConnectionClosed(error, from_peer);
1921 DCHECK(visitor_ != nullptr);
1922 visitor_->OnConnectionClosed(error, from_peer);
1923 // Cancel the alarms so they don't trigger any action now that the
1924 // connection is closed.
1925 ack_alarm_->Cancel();
1926 ping_alarm_->Cancel();
1927 fec_alarm_->Cancel();
1928 resume_writes_alarm_->Cancel();
1929 retransmission_alarm_->Cancel();
1930 send_alarm_->Cancel();
1931 timeout_alarm_->Cancel();
1934 void QuicConnection::SendGoAway(QuicErrorCode error,
1935 QuicStreamId last_good_stream_id,
1936 const string& reason) {
1937 DVLOG(1) << ENDPOINT << "Going away with error "
1938 << QuicUtils::ErrorToString(error)
1939 << " (" << error << ")";
1941 // Opportunistically bundle an ack with this outgoing packet.
1942 ScopedPacketBundler ack_bundler(this, BUNDLE_PENDING_ACK);
1943 packet_generator_.AddControlFrame(
1944 QuicFrame(new QuicGoAwayFrame(error, last_good_stream_id, reason)));
1947 void QuicConnection::CloseFecGroupsBefore(
1948 QuicPacketSequenceNumber sequence_number) {
1949 FecGroupMap::iterator it = group_map_.begin();
1950 while (it != group_map_.end()) {
1951 // If this is the current group or the group doesn't protect this packet
1952 // we can ignore it.
1953 if (last_header_.fec_group == it->first ||
1954 !it->second->ProtectsPacketsBefore(sequence_number)) {
1955 ++it;
1956 continue;
1958 QuicFecGroup* fec_group = it->second;
1959 DCHECK(!fec_group->CanRevive());
1960 FecGroupMap::iterator next = it;
1961 ++next;
1962 group_map_.erase(it);
1963 delete fec_group;
1964 it = next;
1968 QuicByteCount QuicConnection::max_packet_length() const {
1969 return packet_generator_.max_packet_length();
1972 void QuicConnection::set_max_packet_length(QuicByteCount length) {
1973 return packet_generator_.set_max_packet_length(length);
1976 bool QuicConnection::HasQueuedData() const {
1977 return pending_version_negotiation_packet_ ||
1978 !queued_packets_.empty() || packet_generator_.HasQueuedFrames();
1981 bool QuicConnection::CanWriteStreamData() {
1982 // Don't write stream data if there are negotiation or queued data packets
1983 // to send. Otherwise, continue and bundle as many frames as possible.
1984 if (pending_version_negotiation_packet_ || !queued_packets_.empty()) {
1985 return false;
1988 IsHandshake pending_handshake = visitor_->HasPendingHandshake() ?
1989 IS_HANDSHAKE : NOT_HANDSHAKE;
1990 // Sending queued packets may have caused the socket to become write blocked,
1991 // or the congestion manager to prohibit sending. If we've sent everything
1992 // we had queued and we're still not blocked, let the visitor know it can
1993 // write more.
1994 return ShouldGeneratePacket(NOT_RETRANSMISSION, HAS_RETRANSMITTABLE_DATA,
1995 pending_handshake);
1998 void QuicConnection::SetNetworkTimeouts(QuicTime::Delta overall_timeout,
1999 QuicTime::Delta idle_timeout) {
2000 LOG_IF(DFATAL, idle_timeout > overall_timeout)
2001 << "idle_timeout:" << idle_timeout.ToMilliseconds()
2002 << " overall_timeout:" << overall_timeout.ToMilliseconds();
2003 // Adjust the idle timeout on client and server to prevent clients from
2004 // sending requests to servers which have already closed the connection.
2005 if (perspective_ == Perspective::IS_SERVER) {
2006 idle_timeout = idle_timeout.Add(QuicTime::Delta::FromSeconds(3));
2007 } else if (idle_timeout > QuicTime::Delta::FromSeconds(1)) {
2008 idle_timeout = idle_timeout.Subtract(QuicTime::Delta::FromSeconds(1));
2010 overall_connection_timeout_ = overall_timeout;
2011 idle_network_timeout_ = idle_timeout;
2013 SetTimeoutAlarm();
2016 void QuicConnection::CheckForTimeout() {
2017 QuicTime now = clock_->ApproximateNow();
2018 QuicTime time_of_last_packet = max(time_of_last_received_packet_,
2019 time_of_last_sent_new_packet_);
2021 // |delta| can be < 0 as |now| is approximate time but |time_of_last_packet|
2022 // is accurate time. However, this should not change the behavior of
2023 // timeout handling.
2024 QuicTime::Delta idle_duration = now.Subtract(time_of_last_packet);
2025 DVLOG(1) << ENDPOINT << "last packet "
2026 << time_of_last_packet.ToDebuggingValue()
2027 << " now:" << now.ToDebuggingValue()
2028 << " idle_duration:" << idle_duration.ToMicroseconds()
2029 << " idle_network_timeout: "
2030 << idle_network_timeout_.ToMicroseconds();
2031 if (idle_duration >= idle_network_timeout_) {
2032 DVLOG(1) << ENDPOINT << "Connection timedout due to no network activity.";
2033 SendConnectionClose(QUIC_CONNECTION_TIMED_OUT);
2034 return;
2037 if (!overall_connection_timeout_.IsInfinite()) {
2038 QuicTime::Delta connected_duration =
2039 now.Subtract(stats_.connection_creation_time);
2040 DVLOG(1) << ENDPOINT << "connection time: "
2041 << connected_duration.ToMicroseconds() << " overall timeout: "
2042 << overall_connection_timeout_.ToMicroseconds();
2043 if (connected_duration >= overall_connection_timeout_) {
2044 DVLOG(1) << ENDPOINT <<
2045 "Connection timedout due to overall connection timeout.";
2046 SendConnectionClose(QUIC_CONNECTION_OVERALL_TIMED_OUT);
2047 return;
2051 SetTimeoutAlarm();
2054 void QuicConnection::SetTimeoutAlarm() {
2055 QuicTime time_of_last_packet = max(time_of_last_received_packet_,
2056 time_of_last_sent_new_packet_);
2058 QuicTime deadline = time_of_last_packet.Add(idle_network_timeout_);
2059 if (!overall_connection_timeout_.IsInfinite()) {
2060 deadline = min(deadline,
2061 stats_.connection_creation_time.Add(
2062 overall_connection_timeout_));
2065 timeout_alarm_->Cancel();
2066 timeout_alarm_->Set(deadline);
2069 void QuicConnection::SetPingAlarm() {
2070 if (perspective_ == Perspective::IS_SERVER) {
2071 // Only clients send pings.
2072 return;
2074 if (!visitor_->HasOpenDataStreams()) {
2075 ping_alarm_->Cancel();
2076 // Don't send a ping unless there are open streams.
2077 return;
2079 QuicTime::Delta ping_timeout = QuicTime::Delta::FromSeconds(kPingTimeoutSecs);
2080 ping_alarm_->Update(clock_->ApproximateNow().Add(ping_timeout),
2081 QuicTime::Delta::FromSeconds(1));
2084 QuicConnection::ScopedPacketBundler::ScopedPacketBundler(
2085 QuicConnection* connection,
2086 AckBundling send_ack)
2087 : connection_(connection),
2088 already_in_batch_mode_(connection != nullptr &&
2089 connection->packet_generator_.InBatchMode()) {
2090 if (connection_ == nullptr) {
2091 return;
2093 // Move generator into batch mode. If caller wants us to include an ack,
2094 // check the delayed-ack timer to see if there's ack info to be sent.
2095 if (!already_in_batch_mode_) {
2096 DVLOG(1) << "Entering Batch Mode.";
2097 connection_->packet_generator_.StartBatchOperations();
2099 // Bundle an ack if the alarm is set or with every second packet if we need to
2100 // raise the peer's least unacked.
2101 bool ack_pending =
2102 connection_->ack_alarm_->IsSet() || connection_->stop_waiting_count_ > 1;
2103 if (send_ack == SEND_ACK || (send_ack == BUNDLE_PENDING_ACK && ack_pending)) {
2104 DVLOG(1) << "Bundling ack with outgoing packet.";
2105 connection_->SendAck();
2109 QuicConnection::ScopedPacketBundler::~ScopedPacketBundler() {
2110 if (connection_ == nullptr) {
2111 return;
2113 // If we changed the generator's batch state, restore original batch state.
2114 if (!already_in_batch_mode_) {
2115 DVLOG(1) << "Leaving Batch Mode.";
2116 connection_->packet_generator_.FinishBatchOperations();
2118 DCHECK_EQ(already_in_batch_mode_,
2119 connection_->packet_generator_.InBatchMode());
2122 HasRetransmittableData QuicConnection::IsRetransmittable(
2123 const QueuedPacket& packet) {
2124 // Retransmitted packets retransmittable frames are owned by the unacked
2125 // packet map, but are not present in the serialized packet.
2126 if (packet.transmission_type != NOT_RETRANSMISSION ||
2127 packet.serialized_packet.retransmittable_frames != nullptr) {
2128 return HAS_RETRANSMITTABLE_DATA;
2129 } else {
2130 return NO_RETRANSMITTABLE_DATA;
2134 bool QuicConnection::IsConnectionClose(const QueuedPacket& packet) {
2135 const RetransmittableFrames* retransmittable_frames =
2136 packet.serialized_packet.retransmittable_frames;
2137 if (retransmittable_frames == nullptr) {
2138 return false;
2140 for (const QuicFrame& frame : retransmittable_frames->frames()) {
2141 if (frame.type == CONNECTION_CLOSE_FRAME) {
2142 return true;
2145 return false;
2148 } // namespace net