Supervised user whitelists: Cleanup
[chromium-blink-merge.git] / net / quic / quic_connection.cc
blob66a78515299643337a29dfd8033a5263cdef5f52
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "net/quic/quic_connection.h"
7 #include <string.h>
8 #include <sys/types.h>
10 #include <algorithm>
11 #include <iterator>
12 #include <limits>
13 #include <memory>
14 #include <set>
15 #include <utility>
17 #include "base/debug/stack_trace.h"
18 #include "base/format_macros.h"
19 #include "base/logging.h"
20 #include "base/profiler/scoped_tracker.h"
21 #include "base/stl_util.h"
22 #include "base/strings/stringprintf.h"
23 #include "net/base/net_errors.h"
24 #include "net/quic/crypto/quic_decrypter.h"
25 #include "net/quic/crypto/quic_encrypter.h"
26 #include "net/quic/iovector.h"
27 #include "net/quic/proto/cached_network_parameters.pb.h"
28 #include "net/quic/quic_bandwidth.h"
29 #include "net/quic/quic_config.h"
30 #include "net/quic/quic_fec_group.h"
31 #include "net/quic/quic_flags.h"
32 #include "net/quic/quic_packet_generator.h"
33 #include "net/quic/quic_utils.h"
35 using base::StringPiece;
36 using base::StringPrintf;
37 using base::hash_map;
38 using base::hash_set;
39 using std::list;
40 using std::make_pair;
41 using std::max;
42 using std::min;
43 using std::numeric_limits;
44 using std::set;
45 using std::string;
46 using std::vector;
48 namespace net {
50 class QuicDecrypter;
51 class QuicEncrypter;
53 namespace {
55 // The largest gap in packets we'll accept without closing the connection.
56 // This will likely have to be tuned.
57 const QuicPacketSequenceNumber kMaxPacketGap = 5000;
59 // Limit the number of FEC groups to two. If we get enough out of order packets
60 // that this becomes limiting, we can revisit.
61 const size_t kMaxFecGroups = 2;
63 // Maximum number of acks received before sending an ack in response.
64 const QuicPacketCount kMaxPacketsReceivedBeforeAckSend = 20;
66 // Maximum number of tracked packets.
67 const QuicPacketCount kMaxTrackedPackets = 5 * kMaxTcpCongestionWindow;
69 bool Near(QuicPacketSequenceNumber a, QuicPacketSequenceNumber b) {
70 QuicPacketSequenceNumber delta = (a > b) ? a - b : b - a;
71 return delta <= kMaxPacketGap;
74 // An alarm that is scheduled to send an ack if a timeout occurs.
75 class AckAlarm : public QuicAlarm::Delegate {
76 public:
77 explicit AckAlarm(QuicConnection* connection)
78 : connection_(connection) {
81 QuicTime OnAlarm() override {
82 connection_->SendAck();
83 return QuicTime::Zero();
86 private:
87 QuicConnection* connection_;
89 DISALLOW_COPY_AND_ASSIGN(AckAlarm);
92 // This alarm will be scheduled any time a data-bearing packet is sent out.
93 // When the alarm goes off, the connection checks to see if the oldest packets
94 // have been acked, and retransmit them if they have not.
95 class RetransmissionAlarm : public QuicAlarm::Delegate {
96 public:
97 explicit RetransmissionAlarm(QuicConnection* connection)
98 : connection_(connection) {
101 QuicTime OnAlarm() override {
102 connection_->OnRetransmissionTimeout();
103 return QuicTime::Zero();
106 private:
107 QuicConnection* connection_;
109 DISALLOW_COPY_AND_ASSIGN(RetransmissionAlarm);
112 // An alarm that is scheduled when the SentPacketManager requires a delay
113 // before sending packets and fires when the packet may be sent.
114 class SendAlarm : public QuicAlarm::Delegate {
115 public:
116 explicit SendAlarm(QuicConnection* connection)
117 : connection_(connection) {
120 QuicTime OnAlarm() override {
121 connection_->WriteIfNotBlocked();
122 // Never reschedule the alarm, since CanWrite does that.
123 return QuicTime::Zero();
126 private:
127 QuicConnection* connection_;
129 DISALLOW_COPY_AND_ASSIGN(SendAlarm);
132 class TimeoutAlarm : public QuicAlarm::Delegate {
133 public:
134 explicit TimeoutAlarm(QuicConnection* connection)
135 : connection_(connection) {
138 QuicTime OnAlarm() override {
139 connection_->CheckForTimeout();
140 // Never reschedule the alarm, since CheckForTimeout does that.
141 return QuicTime::Zero();
144 private:
145 QuicConnection* connection_;
147 DISALLOW_COPY_AND_ASSIGN(TimeoutAlarm);
150 class PingAlarm : public QuicAlarm::Delegate {
151 public:
152 explicit PingAlarm(QuicConnection* connection)
153 : connection_(connection) {
156 QuicTime OnAlarm() override {
157 connection_->SendPing();
158 return QuicTime::Zero();
161 private:
162 QuicConnection* connection_;
164 DISALLOW_COPY_AND_ASSIGN(PingAlarm);
167 // This alarm may be scheduled when an FEC protected packet is sent out.
168 class FecAlarm : public QuicAlarm::Delegate {
169 public:
170 explicit FecAlarm(QuicPacketGenerator* packet_generator)
171 : packet_generator_(packet_generator) {}
173 QuicTime OnAlarm() override {
174 packet_generator_->OnFecTimeout();
175 return QuicTime::Zero();
178 private:
179 QuicPacketGenerator* packet_generator_;
181 DISALLOW_COPY_AND_ASSIGN(FecAlarm);
184 } // namespace
186 QuicConnection::QueuedPacket::QueuedPacket(SerializedPacket packet,
187 EncryptionLevel level)
188 : serialized_packet(packet),
189 encryption_level(level),
190 transmission_type(NOT_RETRANSMISSION),
191 original_sequence_number(0) {
194 QuicConnection::QueuedPacket::QueuedPacket(
195 SerializedPacket packet,
196 EncryptionLevel level,
197 TransmissionType transmission_type,
198 QuicPacketSequenceNumber original_sequence_number)
199 : serialized_packet(packet),
200 encryption_level(level),
201 transmission_type(transmission_type),
202 original_sequence_number(original_sequence_number) {
205 #define ENDPOINT \
206 (perspective_ == Perspective::IS_SERVER ? "Server: " : "Client: ")
208 QuicConnection::QuicConnection(QuicConnectionId connection_id,
209 IPEndPoint address,
210 QuicConnectionHelperInterface* helper,
211 const PacketWriterFactory& writer_factory,
212 bool owns_writer,
213 Perspective perspective,
214 bool is_secure,
215 const QuicVersionVector& supported_versions)
216 : framer_(supported_versions,
217 helper->GetClock()->ApproximateNow(),
218 perspective),
219 helper_(helper),
220 writer_(writer_factory.Create(this)),
221 owns_writer_(owns_writer),
222 encryption_level_(ENCRYPTION_NONE),
223 has_forward_secure_encrypter_(false),
224 first_required_forward_secure_packet_(0),
225 clock_(helper->GetClock()),
226 random_generator_(helper->GetRandomGenerator()),
227 connection_id_(connection_id),
228 peer_address_(address),
229 migrating_peer_port_(0),
230 last_packet_decrypted_(false),
231 last_packet_revived_(false),
232 last_size_(0),
233 last_decrypted_packet_level_(ENCRYPTION_NONE),
234 largest_seen_packet_with_ack_(0),
235 largest_seen_packet_with_stop_waiting_(0),
236 max_undecryptable_packets_(0),
237 pending_version_negotiation_packet_(false),
238 silent_close_enabled_(false),
239 received_packet_manager_(&stats_),
240 ack_queued_(false),
241 num_packets_received_since_last_ack_sent_(0),
242 stop_waiting_count_(0),
243 ack_alarm_(helper->CreateAlarm(new AckAlarm(this))),
244 retransmission_alarm_(helper->CreateAlarm(new RetransmissionAlarm(this))),
245 send_alarm_(helper->CreateAlarm(new SendAlarm(this))),
246 resume_writes_alarm_(helper->CreateAlarm(new SendAlarm(this))),
247 timeout_alarm_(helper->CreateAlarm(new TimeoutAlarm(this))),
248 ping_alarm_(helper->CreateAlarm(new PingAlarm(this))),
249 visitor_(nullptr),
250 debug_visitor_(nullptr),
251 packet_generator_(connection_id_, &framer_, random_generator_, this),
252 fec_alarm_(helper->CreateAlarm(new FecAlarm(&packet_generator_))),
253 idle_network_timeout_(QuicTime::Delta::Infinite()),
254 overall_connection_timeout_(QuicTime::Delta::Infinite()),
255 time_of_last_received_packet_(clock_->ApproximateNow()),
256 time_of_last_sent_new_packet_(clock_->ApproximateNow()),
257 sequence_number_of_last_sent_packet_(0),
258 sent_packet_manager_(
259 perspective,
260 clock_,
261 &stats_,
262 FLAGS_quic_use_bbr_congestion_control ? kBBR : kCubic,
263 FLAGS_quic_use_time_loss_detection ? kTime : kNack,
264 is_secure),
265 version_negotiation_state_(START_NEGOTIATION),
266 perspective_(perspective),
267 connected_(true),
268 peer_ip_changed_(false),
269 peer_port_changed_(false),
270 self_ip_changed_(false),
271 self_port_changed_(false),
272 can_truncate_connection_ids_(true),
273 is_secure_(is_secure) {
274 DVLOG(1) << ENDPOINT << "Created connection with connection_id: "
275 << connection_id;
276 framer_.set_visitor(this);
277 framer_.set_received_entropy_calculator(&received_packet_manager_);
278 stats_.connection_creation_time = clock_->ApproximateNow();
279 sent_packet_manager_.set_network_change_visitor(this);
280 if (perspective_ == Perspective::IS_SERVER) {
281 set_max_packet_length(kDefaultServerMaxPacketSize);
285 QuicConnection::~QuicConnection() {
286 if (owns_writer_) {
287 delete writer_;
289 STLDeleteElements(&undecryptable_packets_);
290 STLDeleteValues(&group_map_);
291 for (QueuedPacketList::iterator it = queued_packets_.begin();
292 it != queued_packets_.end(); ++it) {
293 delete it->serialized_packet.retransmittable_frames;
294 delete it->serialized_packet.packet;
298 void QuicConnection::SetFromConfig(const QuicConfig& config) {
299 if (config.negotiated()) {
300 SetNetworkTimeouts(QuicTime::Delta::Infinite(),
301 config.IdleConnectionStateLifetime());
302 if (config.SilentClose()) {
303 silent_close_enabled_ = true;
305 } else {
306 SetNetworkTimeouts(config.max_time_before_crypto_handshake(),
307 config.max_idle_time_before_crypto_handshake());
310 sent_packet_manager_.SetFromConfig(config);
311 if (config.HasReceivedBytesForConnectionId() &&
312 can_truncate_connection_ids_) {
313 packet_generator_.SetConnectionIdLength(
314 config.ReceivedBytesForConnectionId());
316 max_undecryptable_packets_ = config.max_undecryptable_packets();
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(const QuicPublicResetPacket& packet) {
393 // Check that any public reset packet with a different connection ID that was
394 // routed to this QuicConnection has been redirected before control reaches
395 // here. (Check for a bug regression.)
396 DCHECK_EQ(connection_id_, packet.public_header.connection_id);
397 if (debug_visitor_ != nullptr) {
398 debug_visitor_->OnPublicResetPacket(packet);
400 CloseConnection(QUIC_PUBLIC_RESET, true);
402 DVLOG(1) << ENDPOINT << "Connection " << connection_id()
403 << " closed via QUIC_PUBLIC_RESET from peer.";
406 bool QuicConnection::OnProtocolVersionMismatch(QuicVersion received_version) {
407 DVLOG(1) << ENDPOINT << "Received packet with mismatched version "
408 << received_version;
409 // TODO(satyamshekhar): Implement no server state in this mode.
410 if (perspective_ == Perspective::IS_CLIENT) {
411 LOG(DFATAL) << ENDPOINT << "Framer called OnProtocolVersionMismatch. "
412 << "Closing connection.";
413 CloseConnection(QUIC_INTERNAL_ERROR, false);
414 return false;
416 DCHECK_NE(version(), received_version);
418 if (debug_visitor_ != nullptr) {
419 debug_visitor_->OnProtocolVersionMismatch(received_version);
422 switch (version_negotiation_state_) {
423 case START_NEGOTIATION:
424 if (!framer_.IsSupportedVersion(received_version)) {
425 SendVersionNegotiationPacket();
426 version_negotiation_state_ = NEGOTIATION_IN_PROGRESS;
427 return false;
429 break;
431 case NEGOTIATION_IN_PROGRESS:
432 if (!framer_.IsSupportedVersion(received_version)) {
433 SendVersionNegotiationPacket();
434 return false;
436 break;
438 case NEGOTIATED_VERSION:
439 // Might be old packets that were sent by the client before the version
440 // was negotiated. Drop these.
441 return false;
443 default:
444 DCHECK(false);
447 version_negotiation_state_ = NEGOTIATED_VERSION;
448 visitor_->OnSuccessfulVersionNegotiation(received_version);
449 if (debug_visitor_ != nullptr) {
450 debug_visitor_->OnSuccessfulVersionNegotiation(received_version);
452 DVLOG(1) << ENDPOINT << "version negotiated " << received_version;
454 // Store the new version.
455 framer_.set_version(received_version);
457 // TODO(satyamshekhar): Store the sequence number of this packet and close the
458 // connection if we ever received a packet with incorrect version and whose
459 // sequence number is greater.
460 return true;
463 // Handles version negotiation for client connection.
464 void QuicConnection::OnVersionNegotiationPacket(
465 const QuicVersionNegotiationPacket& packet) {
466 // Check that any public reset packet with a different connection ID that was
467 // routed to this QuicConnection has been redirected before control reaches
468 // here. (Check for a bug regression.)
469 DCHECK_EQ(connection_id_, packet.connection_id);
470 if (perspective_ == Perspective::IS_SERVER) {
471 LOG(DFATAL) << ENDPOINT << "Framer parsed VersionNegotiationPacket."
472 << " Closing connection.";
473 CloseConnection(QUIC_INTERNAL_ERROR, false);
474 return;
476 if (debug_visitor_ != nullptr) {
477 debug_visitor_->OnVersionNegotiationPacket(packet);
480 if (version_negotiation_state_ != START_NEGOTIATION) {
481 // Possibly a duplicate version negotiation packet.
482 return;
485 if (std::find(packet.versions.begin(),
486 packet.versions.end(), version()) !=
487 packet.versions.end()) {
488 DLOG(WARNING) << ENDPOINT << "The server already supports our version. "
489 << "It should have accepted our connection.";
490 // Just drop the connection.
491 CloseConnection(QUIC_INVALID_VERSION_NEGOTIATION_PACKET, false);
492 return;
495 if (!SelectMutualVersion(packet.versions)) {
496 SendConnectionCloseWithDetails(QUIC_INVALID_VERSION,
497 "no common version found");
498 return;
501 DVLOG(1) << ENDPOINT
502 << "Negotiated version: " << QuicVersionToString(version());
503 server_supported_versions_ = packet.versions;
504 version_negotiation_state_ = NEGOTIATION_IN_PROGRESS;
505 RetransmitUnackedPackets(ALL_UNACKED_RETRANSMISSION);
508 void QuicConnection::OnRevivedPacket() {
511 bool QuicConnection::OnUnauthenticatedPublicHeader(
512 const QuicPacketPublicHeader& header) {
513 if (header.connection_id == connection_id_) {
514 return true;
517 ++stats_.packets_dropped;
518 DVLOG(1) << ENDPOINT << "Ignoring packet from unexpected ConnectionId: "
519 << header.connection_id << " instead of " << connection_id_;
520 if (debug_visitor_ != nullptr) {
521 debug_visitor_->OnIncorrectConnectionId(header.connection_id);
523 // If this is a server, the dispatcher routes each packet to the
524 // QuicConnection responsible for the packet's connection ID. So if control
525 // arrives here and this is a server, the dispatcher must be malfunctioning.
526 DCHECK_NE(Perspective::IS_SERVER, perspective_);
527 return false;
530 bool QuicConnection::OnUnauthenticatedHeader(const QuicPacketHeader& header) {
531 // Check that any public reset packet with a different connection ID that was
532 // routed to this QuicConnection has been redirected before control reaches
533 // here.
534 DCHECK_EQ(connection_id_, header.public_header.connection_id);
535 return true;
538 void QuicConnection::OnDecryptedPacket(EncryptionLevel level) {
539 last_decrypted_packet_level_ = level;
540 last_packet_decrypted_ = true;
541 // If this packet was foward-secure encrypted and the forward-secure encrypter
542 // is not being used, start using it.
543 if (encryption_level_ != ENCRYPTION_FORWARD_SECURE &&
544 has_forward_secure_encrypter_ && level == ENCRYPTION_FORWARD_SECURE) {
545 SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
549 bool QuicConnection::OnPacketHeader(const QuicPacketHeader& header) {
550 if (debug_visitor_ != nullptr) {
551 debug_visitor_->OnPacketHeader(header);
554 if (!ProcessValidatedPacket()) {
555 return false;
558 // Will be decremented below if we fall through to return true.
559 ++stats_.packets_dropped;
561 if (!Near(header.packet_sequence_number,
562 last_header_.packet_sequence_number)) {
563 DVLOG(1) << ENDPOINT << "Packet " << header.packet_sequence_number
564 << " out of bounds. Discarding";
565 SendConnectionCloseWithDetails(QUIC_INVALID_PACKET_HEADER,
566 "Packet sequence number out of bounds");
567 return false;
570 // If this packet has already been seen, or the sender has told us that it
571 // will not be retransmitted, then stop processing the packet.
572 if (!received_packet_manager_.IsAwaitingPacket(
573 header.packet_sequence_number)) {
574 DVLOG(1) << ENDPOINT << "Packet " << header.packet_sequence_number
575 << " no longer being waited for. Discarding.";
576 if (debug_visitor_ != nullptr) {
577 debug_visitor_->OnDuplicatePacket(header.packet_sequence_number);
579 return false;
582 if (version_negotiation_state_ != NEGOTIATED_VERSION) {
583 if (perspective_ == Perspective::IS_SERVER) {
584 if (!header.public_header.version_flag) {
585 DLOG(WARNING) << ENDPOINT << "Packet " << header.packet_sequence_number
586 << " without version flag before version negotiated.";
587 // Packets should have the version flag till version negotiation is
588 // done.
589 CloseConnection(QUIC_INVALID_VERSION, false);
590 return false;
591 } else {
592 DCHECK_EQ(1u, header.public_header.versions.size());
593 DCHECK_EQ(header.public_header.versions[0], version());
594 version_negotiation_state_ = NEGOTIATED_VERSION;
595 visitor_->OnSuccessfulVersionNegotiation(version());
596 if (debug_visitor_ != nullptr) {
597 debug_visitor_->OnSuccessfulVersionNegotiation(version());
600 } else {
601 DCHECK(!header.public_header.version_flag);
602 // If the client gets a packet without the version flag from the server
603 // it should stop sending version since the version negotiation is done.
604 packet_generator_.StopSendingVersion();
605 version_negotiation_state_ = NEGOTIATED_VERSION;
606 visitor_->OnSuccessfulVersionNegotiation(version());
607 if (debug_visitor_ != nullptr) {
608 debug_visitor_->OnSuccessfulVersionNegotiation(version());
613 DCHECK_EQ(NEGOTIATED_VERSION, version_negotiation_state_);
615 --stats_.packets_dropped;
616 DVLOG(1) << ENDPOINT << "Received packet header: " << header;
617 last_header_ = header;
618 DCHECK(connected_);
619 return true;
622 void QuicConnection::OnFecProtectedPayload(StringPiece payload) {
623 DCHECK_EQ(IN_FEC_GROUP, last_header_.is_in_fec_group);
624 DCHECK_NE(0u, last_header_.fec_group);
625 QuicFecGroup* group = GetFecGroup();
626 if (group != nullptr) {
627 group->Update(last_decrypted_packet_level_, last_header_, payload);
631 bool QuicConnection::OnStreamFrame(const QuicStreamFrame& frame) {
632 DCHECK(connected_);
633 if (debug_visitor_ != nullptr) {
634 debug_visitor_->OnStreamFrame(frame);
636 if (frame.stream_id != kCryptoStreamId &&
637 last_decrypted_packet_level_ == ENCRYPTION_NONE) {
638 DLOG(WARNING) << ENDPOINT
639 << "Received an unencrypted data frame: closing connection";
640 SendConnectionClose(QUIC_UNENCRYPTED_STREAM_DATA);
641 return false;
643 last_stream_frames_.push_back(frame);
644 return true;
647 bool QuicConnection::OnAckFrame(const QuicAckFrame& incoming_ack) {
648 DCHECK(connected_);
649 if (debug_visitor_ != nullptr) {
650 debug_visitor_->OnAckFrame(incoming_ack);
652 DVLOG(1) << ENDPOINT << "OnAckFrame: " << incoming_ack;
654 if (last_header_.packet_sequence_number <= largest_seen_packet_with_ack_) {
655 DVLOG(1) << ENDPOINT << "Received an old ack frame: ignoring";
656 return true;
659 if (!ValidateAckFrame(incoming_ack)) {
660 SendConnectionClose(QUIC_INVALID_ACK_DATA);
661 return false;
664 last_ack_frames_.push_back(incoming_ack);
665 return connected_;
668 void QuicConnection::ProcessAckFrame(const QuicAckFrame& incoming_ack) {
669 largest_seen_packet_with_ack_ = last_header_.packet_sequence_number;
670 sent_packet_manager_.OnIncomingAck(incoming_ack,
671 time_of_last_received_packet_);
672 sent_entropy_manager_.ClearEntropyBefore(
673 sent_packet_manager_.least_packet_awaited_by_peer() - 1);
674 if (sent_packet_manager_.HasPendingRetransmissions()) {
675 WriteIfNotBlocked();
678 // Always reset the retransmission alarm when an ack comes in, since we now
679 // have a better estimate of the current rtt than when it was set.
680 QuicTime retransmission_time = sent_packet_manager_.GetRetransmissionTime();
681 retransmission_alarm_->Update(retransmission_time,
682 QuicTime::Delta::FromMilliseconds(1));
685 void QuicConnection::ProcessStopWaitingFrame(
686 const QuicStopWaitingFrame& stop_waiting) {
687 largest_seen_packet_with_stop_waiting_ = last_header_.packet_sequence_number;
688 received_packet_manager_.UpdatePacketInformationSentByPeer(stop_waiting);
689 // Possibly close any FecGroups which are now irrelevant.
690 CloseFecGroupsBefore(stop_waiting.least_unacked + 1);
693 bool QuicConnection::OnStopWaitingFrame(const QuicStopWaitingFrame& frame) {
694 DCHECK(connected_);
696 if (last_header_.packet_sequence_number <=
697 largest_seen_packet_with_stop_waiting_) {
698 DVLOG(1) << ENDPOINT << "Received an old stop waiting frame: ignoring";
699 return true;
702 if (!ValidateStopWaitingFrame(frame)) {
703 SendConnectionClose(QUIC_INVALID_STOP_WAITING_DATA);
704 return false;
707 if (debug_visitor_ != nullptr) {
708 debug_visitor_->OnStopWaitingFrame(frame);
711 last_stop_waiting_frames_.push_back(frame);
712 return connected_;
715 bool QuicConnection::OnPingFrame(const QuicPingFrame& frame) {
716 DCHECK(connected_);
717 if (debug_visitor_ != nullptr) {
718 debug_visitor_->OnPingFrame(frame);
720 last_ping_frames_.push_back(frame);
721 return true;
724 bool QuicConnection::ValidateAckFrame(const QuicAckFrame& incoming_ack) {
725 if (incoming_ack.largest_observed > packet_generator_.sequence_number()) {
726 DLOG(ERROR) << ENDPOINT << "Peer's observed unsent packet:"
727 << incoming_ack.largest_observed << " vs "
728 << packet_generator_.sequence_number();
729 // We got an error for data we have not sent. Error out.
730 return false;
733 if (incoming_ack.largest_observed < sent_packet_manager_.largest_observed()) {
734 DLOG(ERROR) << ENDPOINT << "Peer's largest_observed packet decreased:"
735 << incoming_ack.largest_observed << " vs "
736 << sent_packet_manager_.largest_observed();
737 // A new ack has a diminished largest_observed value. Error out.
738 // If this was an old packet, we wouldn't even have checked.
739 return false;
742 if (!incoming_ack.missing_packets.empty() &&
743 *incoming_ack.missing_packets.rbegin() > incoming_ack.largest_observed) {
744 DLOG(ERROR) << ENDPOINT << "Peer sent missing packet: "
745 << *incoming_ack.missing_packets.rbegin()
746 << " which is greater than largest observed: "
747 << incoming_ack.largest_observed;
748 return false;
751 if (!incoming_ack.missing_packets.empty() &&
752 *incoming_ack.missing_packets.begin() <
753 sent_packet_manager_.least_packet_awaited_by_peer()) {
754 DLOG(ERROR) << ENDPOINT << "Peer sent missing packet: "
755 << *incoming_ack.missing_packets.begin()
756 << " which is smaller than least_packet_awaited_by_peer_: "
757 << sent_packet_manager_.least_packet_awaited_by_peer();
758 return false;
761 if (!sent_entropy_manager_.IsValidEntropy(
762 incoming_ack.largest_observed,
763 incoming_ack.missing_packets,
764 incoming_ack.entropy_hash)) {
765 DLOG(ERROR) << ENDPOINT << "Peer sent invalid entropy.";
766 return false;
769 for (SequenceNumberSet::const_iterator iter =
770 incoming_ack.revived_packets.begin();
771 iter != incoming_ack.revived_packets.end(); ++iter) {
772 if (!ContainsKey(incoming_ack.missing_packets, *iter)) {
773 DLOG(ERROR) << ENDPOINT
774 << "Peer specified revived packet which was not missing.";
775 return false;
778 return true;
781 bool QuicConnection::ValidateStopWaitingFrame(
782 const QuicStopWaitingFrame& stop_waiting) {
783 if (stop_waiting.least_unacked <
784 received_packet_manager_.peer_least_packet_awaiting_ack()) {
785 DLOG(ERROR) << ENDPOINT << "Peer's sent low least_unacked: "
786 << stop_waiting.least_unacked << " vs "
787 << received_packet_manager_.peer_least_packet_awaiting_ack();
788 // We never process old ack frames, so this number should only increase.
789 return false;
792 if (stop_waiting.least_unacked >
793 last_header_.packet_sequence_number) {
794 DLOG(ERROR) << ENDPOINT << "Peer sent least_unacked:"
795 << stop_waiting.least_unacked
796 << " greater than the enclosing packet sequence number:"
797 << last_header_.packet_sequence_number;
798 return false;
801 return true;
804 void QuicConnection::OnFecData(const QuicFecData& fec) {
805 DCHECK_EQ(IN_FEC_GROUP, last_header_.is_in_fec_group);
806 DCHECK_NE(0u, last_header_.fec_group);
807 QuicFecGroup* group = GetFecGroup();
808 if (group != nullptr) {
809 group->UpdateFec(last_decrypted_packet_level_,
810 last_header_.packet_sequence_number, fec);
814 bool QuicConnection::OnRstStreamFrame(const QuicRstStreamFrame& frame) {
815 DCHECK(connected_);
816 if (debug_visitor_ != nullptr) {
817 debug_visitor_->OnRstStreamFrame(frame);
819 DVLOG(1) << ENDPOINT << "Stream reset with error "
820 << QuicUtils::StreamErrorToString(frame.error_code);
821 last_rst_frames_.push_back(frame);
822 return connected_;
825 bool QuicConnection::OnConnectionCloseFrame(
826 const QuicConnectionCloseFrame& frame) {
827 DCHECK(connected_);
828 if (debug_visitor_ != nullptr) {
829 debug_visitor_->OnConnectionCloseFrame(frame);
831 DVLOG(1) << ENDPOINT << "Connection " << connection_id()
832 << " closed with error "
833 << QuicUtils::ErrorToString(frame.error_code)
834 << " " << frame.error_details;
835 last_close_frames_.push_back(frame);
836 return connected_;
839 bool QuicConnection::OnGoAwayFrame(const QuicGoAwayFrame& frame) {
840 DCHECK(connected_);
841 if (debug_visitor_ != nullptr) {
842 debug_visitor_->OnGoAwayFrame(frame);
844 DVLOG(1) << ENDPOINT << "Go away received with error "
845 << QuicUtils::ErrorToString(frame.error_code)
846 << " and reason:" << frame.reason_phrase;
847 last_goaway_frames_.push_back(frame);
848 return connected_;
851 bool QuicConnection::OnWindowUpdateFrame(const QuicWindowUpdateFrame& frame) {
852 DCHECK(connected_);
853 if (debug_visitor_ != nullptr) {
854 debug_visitor_->OnWindowUpdateFrame(frame);
856 DVLOG(1) << ENDPOINT << "WindowUpdate received for stream: "
857 << frame.stream_id << " with byte offset: " << frame.byte_offset;
858 last_window_update_frames_.push_back(frame);
859 return connected_;
862 bool QuicConnection::OnBlockedFrame(const QuicBlockedFrame& frame) {
863 DCHECK(connected_);
864 if (debug_visitor_ != nullptr) {
865 debug_visitor_->OnBlockedFrame(frame);
867 DVLOG(1) << ENDPOINT << "Blocked frame received for stream: "
868 << frame.stream_id;
869 last_blocked_frames_.push_back(frame);
870 return connected_;
873 void QuicConnection::OnPacketComplete() {
874 // Don't do anything if this packet closed the connection.
875 if (!connected_) {
876 ClearLastFrames();
877 return;
880 DVLOG(1) << ENDPOINT << (last_packet_revived_ ? "Revived" : "Got")
881 << " packet " << last_header_.packet_sequence_number
882 << " with " << last_stream_frames_.size()<< " stream frames "
883 << last_ack_frames_.size() << " acks, "
884 << last_stop_waiting_frames_.size() << " stop_waiting, "
885 << last_rst_frames_.size() << " rsts, "
886 << last_goaway_frames_.size() << " goaways, "
887 << last_window_update_frames_.size() << " window updates, "
888 << last_blocked_frames_.size() << " blocked, "
889 << last_ping_frames_.size() << " pings, "
890 << last_close_frames_.size() << " closes, "
891 << "for " << last_header_.public_header.connection_id;
893 ++num_packets_received_since_last_ack_sent_;
895 // Call MaybeQueueAck() before recording the received packet, since we want
896 // to trigger an ack if the newly received packet was previously missing.
897 MaybeQueueAck();
899 // Record received or revived packet to populate ack info correctly before
900 // processing stream frames, since the processing may result in a response
901 // packet with a bundled ack.
902 if (last_packet_revived_) {
903 received_packet_manager_.RecordPacketRevived(
904 last_header_.packet_sequence_number);
905 } else {
906 received_packet_manager_.RecordPacketReceived(
907 last_size_, last_header_, time_of_last_received_packet_);
910 if (!last_stream_frames_.empty()) {
911 visitor_->OnStreamFrames(last_stream_frames_);
914 for (size_t i = 0; i < last_stream_frames_.size(); ++i) {
915 stats_.stream_bytes_received +=
916 last_stream_frames_[i].data.TotalBufferSize();
919 // Process window updates, blocked, stream resets, acks, then congestion
920 // feedback.
921 if (!last_window_update_frames_.empty()) {
922 visitor_->OnWindowUpdateFrames(last_window_update_frames_);
924 if (!last_blocked_frames_.empty()) {
925 visitor_->OnBlockedFrames(last_blocked_frames_);
927 for (size_t i = 0; i < last_goaway_frames_.size(); ++i) {
928 visitor_->OnGoAway(last_goaway_frames_[i]);
930 for (size_t i = 0; i < last_rst_frames_.size(); ++i) {
931 visitor_->OnRstStream(last_rst_frames_[i]);
933 for (size_t i = 0; i < last_ack_frames_.size(); ++i) {
934 ProcessAckFrame(last_ack_frames_[i]);
936 for (size_t i = 0; i < last_stop_waiting_frames_.size(); ++i) {
937 ProcessStopWaitingFrame(last_stop_waiting_frames_[i]);
939 if (!last_close_frames_.empty()) {
940 CloseConnection(last_close_frames_[0].error_code, true);
941 DCHECK(!connected_);
944 // If there are new missing packets to report, send an ack immediately.
945 if (received_packet_manager_.HasNewMissingPackets()) {
946 ack_queued_ = true;
947 ack_alarm_->Cancel();
950 UpdateStopWaitingCount();
951 ClearLastFrames();
952 MaybeCloseIfTooManyOutstandingPackets();
955 void QuicConnection::MaybeQueueAck() {
956 // If the incoming packet was missing, send an ack immediately.
957 ack_queued_ = received_packet_manager_.IsMissing(
958 last_header_.packet_sequence_number);
960 if (!ack_queued_ && ShouldLastPacketInstigateAck()) {
961 if (ack_alarm_->IsSet()) {
962 ack_queued_ = true;
963 } else {
964 // Send an ack much more quickly for crypto handshake packets.
965 QuicTime::Delta delayed_ack_time = sent_packet_manager_.DelayedAckTime();
966 ack_alarm_->Set(clock_->ApproximateNow().Add(delayed_ack_time));
967 DVLOG(1) << "Ack timer set; next packet or timer will trigger ACK.";
971 if (ack_queued_) {
972 ack_alarm_->Cancel();
976 void QuicConnection::ClearLastFrames() {
977 last_stream_frames_.clear();
978 last_ack_frames_.clear();
979 last_stop_waiting_frames_.clear();
980 last_rst_frames_.clear();
981 last_goaway_frames_.clear();
982 last_window_update_frames_.clear();
983 last_blocked_frames_.clear();
984 last_ping_frames_.clear();
985 last_close_frames_.clear();
988 void QuicConnection::MaybeCloseIfTooManyOutstandingPackets() {
989 // This occurs if we don't discard old packets we've sent fast enough.
990 // It's possible largest observed is less than least unacked.
991 if (sent_packet_manager_.largest_observed() >
992 (sent_packet_manager_.GetLeastUnacked() + kMaxTrackedPackets)) {
993 SendConnectionCloseWithDetails(
994 QUIC_TOO_MANY_OUTSTANDING_SENT_PACKETS,
995 StringPrintf("More than %" PRIu64 " outstanding.", kMaxTrackedPackets));
997 // This occurs if there are received packet gaps and the peer does not raise
998 // the least unacked fast enough.
999 if (received_packet_manager_.NumTrackedPackets() > kMaxTrackedPackets) {
1000 SendConnectionCloseWithDetails(
1001 QUIC_TOO_MANY_OUTSTANDING_RECEIVED_PACKETS,
1002 StringPrintf("More than %" PRIu64 " outstanding.", kMaxTrackedPackets));
1006 void QuicConnection::PopulateAckFrame(QuicAckFrame* ack) {
1007 received_packet_manager_.UpdateReceivedPacketInfo(ack,
1008 clock_->ApproximateNow());
1011 void QuicConnection::PopulateStopWaitingFrame(
1012 QuicStopWaitingFrame* stop_waiting) {
1013 stop_waiting->least_unacked = GetLeastUnacked();
1014 stop_waiting->entropy_hash = sent_entropy_manager_.GetCumulativeEntropy(
1015 stop_waiting->least_unacked - 1);
1018 bool QuicConnection::ShouldLastPacketInstigateAck() const {
1019 if (!last_stream_frames_.empty() ||
1020 !last_goaway_frames_.empty() ||
1021 !last_rst_frames_.empty() ||
1022 !last_window_update_frames_.empty() ||
1023 !last_blocked_frames_.empty() ||
1024 !last_ping_frames_.empty()) {
1025 return true;
1028 if (!last_ack_frames_.empty() && last_ack_frames_.back().is_truncated) {
1029 return true;
1031 // Always send an ack every 20 packets in order to allow the peer to discard
1032 // information from the SentPacketManager and provide an RTT measurement.
1033 if (num_packets_received_since_last_ack_sent_ >=
1034 kMaxPacketsReceivedBeforeAckSend) {
1035 return true;
1037 return false;
1040 void QuicConnection::UpdateStopWaitingCount() {
1041 if (last_ack_frames_.empty()) {
1042 return;
1045 // If the peer is still waiting for a packet that we are no longer planning to
1046 // send, send an ack to raise the high water mark.
1047 if (!last_ack_frames_.back().missing_packets.empty() &&
1048 GetLeastUnacked() > *last_ack_frames_.back().missing_packets.begin()) {
1049 ++stop_waiting_count_;
1050 } else {
1051 stop_waiting_count_ = 0;
1055 QuicPacketSequenceNumber QuicConnection::GetLeastUnacked() const {
1056 return sent_packet_manager_.GetLeastUnacked();
1059 void QuicConnection::MaybeSendInResponseToPacket() {
1060 if (!connected_) {
1061 return;
1063 ScopedPacketBundler bundler(this, ack_queued_ ? SEND_ACK : NO_ACK);
1065 // Now that we have received an ack, we might be able to send packets which
1066 // are queued locally, or drain streams which are blocked.
1067 if (CanWrite(HAS_RETRANSMITTABLE_DATA)) {
1068 OnCanWrite();
1072 void QuicConnection::SendVersionNegotiationPacket() {
1073 // TODO(alyssar): implement zero server state negotiation.
1074 pending_version_negotiation_packet_ = true;
1075 if (writer_->IsWriteBlocked()) {
1076 visitor_->OnWriteBlocked();
1077 return;
1079 DVLOG(1) << ENDPOINT << "Sending version negotiation packet: {"
1080 << QuicVersionVectorToString(framer_.supported_versions()) << "}";
1081 scoped_ptr<QuicEncryptedPacket> version_packet(
1082 packet_generator_.SerializeVersionNegotiationPacket(
1083 framer_.supported_versions()));
1084 WriteResult result = writer_->WritePacket(
1085 version_packet->data(), version_packet->length(),
1086 self_address().address(), peer_address());
1088 if (result.status == WRITE_STATUS_ERROR) {
1089 // We can't send an error as the socket is presumably borked.
1090 CloseConnection(QUIC_PACKET_WRITE_ERROR, false);
1091 return;
1093 if (result.status == WRITE_STATUS_BLOCKED) {
1094 visitor_->OnWriteBlocked();
1095 if (writer_->IsWriteBlockedDataBuffered()) {
1096 pending_version_negotiation_packet_ = false;
1098 return;
1101 pending_version_negotiation_packet_ = false;
1104 QuicConsumedData QuicConnection::SendStreamData(
1105 QuicStreamId id,
1106 const IOVector& data,
1107 QuicStreamOffset offset,
1108 bool fin,
1109 FecProtection fec_protection,
1110 QuicAckNotifier::DelegateInterface* delegate) {
1111 if (!fin && data.Empty()) {
1112 LOG(DFATAL) << "Attempt to send empty stream frame";
1113 return QuicConsumedData(0, false);
1116 // Opportunistically bundle an ack with every outgoing packet.
1117 // Particularly, we want to bundle with handshake packets since we don't know
1118 // which decrypter will be used on an ack packet following a handshake
1119 // packet (a handshake packet from client to server could result in a REJ or a
1120 // SHLO from the server, leading to two different decrypters at the server.)
1122 // TODO(jri): Note that ConsumeData may cause a response packet to be sent.
1123 // We may end up sending stale ack information if there are undecryptable
1124 // packets hanging around and/or there are revivable packets which may get
1125 // handled after this packet is sent. Change ScopedPacketBundler to do the
1126 // right thing: check ack_queued_, and then check undecryptable packets and
1127 // also if there is possibility of revival. Only bundle an ack if there's no
1128 // processing left that may cause received_info_ to change.
1129 ScopedPacketBundler ack_bundler(this, BUNDLE_PENDING_ACK);
1130 return packet_generator_.ConsumeData(id, data, offset, fin, fec_protection,
1131 delegate);
1134 void QuicConnection::SendRstStream(QuicStreamId id,
1135 QuicRstStreamErrorCode error,
1136 QuicStreamOffset bytes_written) {
1137 // Opportunistically bundle an ack with this outgoing packet.
1138 ScopedPacketBundler ack_bundler(this, BUNDLE_PENDING_ACK);
1139 packet_generator_.AddControlFrame(QuicFrame(new QuicRstStreamFrame(
1140 id, AdjustErrorForVersion(error, version()), bytes_written)));
1141 if (!FLAGS_quic_do_not_retransmit_for_reset_streams) {
1142 return;
1145 sent_packet_manager_.CancelRetransmissionsForStream(id);
1146 // Remove all queued packets which only contain data for the reset stream.
1147 QueuedPacketList::iterator packet_iterator = queued_packets_.begin();
1148 while (packet_iterator != queued_packets_.end()) {
1149 RetransmittableFrames* retransmittable_frames =
1150 packet_iterator->serialized_packet.retransmittable_frames;
1151 if (!retransmittable_frames) {
1152 ++packet_iterator;
1153 continue;
1155 retransmittable_frames->RemoveFramesForStream(id);
1156 if (!retransmittable_frames->frames().empty()) {
1157 ++packet_iterator;
1158 continue;
1160 delete packet_iterator->serialized_packet.retransmittable_frames;
1161 delete packet_iterator->serialized_packet.packet;
1162 packet_iterator->serialized_packet.retransmittable_frames = nullptr;
1163 packet_iterator->serialized_packet.packet = nullptr;
1164 packet_iterator = queued_packets_.erase(packet_iterator);
1168 void QuicConnection::SendWindowUpdate(QuicStreamId id,
1169 QuicStreamOffset byte_offset) {
1170 // Opportunistically bundle an ack with this outgoing packet.
1171 ScopedPacketBundler ack_bundler(this, BUNDLE_PENDING_ACK);
1172 packet_generator_.AddControlFrame(
1173 QuicFrame(new QuicWindowUpdateFrame(id, byte_offset)));
1176 void QuicConnection::SendBlocked(QuicStreamId id) {
1177 // Opportunistically bundle an ack with this outgoing packet.
1178 ScopedPacketBundler ack_bundler(this, BUNDLE_PENDING_ACK);
1179 packet_generator_.AddControlFrame(QuicFrame(new QuicBlockedFrame(id)));
1182 const QuicConnectionStats& QuicConnection::GetStats() {
1183 const RttStats* rtt_stats = sent_packet_manager_.GetRttStats();
1185 // Update rtt and estimated bandwidth.
1186 QuicTime::Delta min_rtt = rtt_stats->min_rtt();
1187 if (min_rtt.IsZero()) {
1188 // If min RTT has not been set, use initial RTT instead.
1189 min_rtt = QuicTime::Delta::FromMicroseconds(rtt_stats->initial_rtt_us());
1191 stats_.min_rtt_us = min_rtt.ToMicroseconds();
1193 QuicTime::Delta srtt = rtt_stats->smoothed_rtt();
1194 if (srtt.IsZero()) {
1195 // If SRTT has not been set, use initial RTT instead.
1196 srtt = QuicTime::Delta::FromMicroseconds(rtt_stats->initial_rtt_us());
1198 stats_.srtt_us = srtt.ToMicroseconds();
1200 stats_.estimated_bandwidth = sent_packet_manager_.BandwidthEstimate();
1201 stats_.max_packet_size = packet_generator_.max_packet_length();
1202 return stats_;
1205 void QuicConnection::ProcessUdpPacket(const IPEndPoint& self_address,
1206 const IPEndPoint& peer_address,
1207 const QuicEncryptedPacket& packet) {
1208 if (!connected_) {
1209 return;
1211 // TODO(rtenneti): Remove ScopedTracker below once crbug.com/462789 is fixed.
1212 tracked_objects::ScopedTracker tracking_profile(
1213 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1214 "462789 QuicConnection::ProcessUdpPacket"));
1215 if (debug_visitor_ != nullptr) {
1216 debug_visitor_->OnPacketReceived(self_address, peer_address, packet);
1218 last_size_ = packet.length();
1220 CheckForAddressMigration(self_address, peer_address);
1222 stats_.bytes_received += packet.length();
1223 ++stats_.packets_received;
1225 if (!framer_.ProcessPacket(packet)) {
1226 // If we are unable to decrypt this packet, it might be
1227 // because the CHLO or SHLO packet was lost.
1228 if (framer_.error() == QUIC_DECRYPTION_FAILURE) {
1229 if (encryption_level_ != ENCRYPTION_FORWARD_SECURE &&
1230 undecryptable_packets_.size() < max_undecryptable_packets_) {
1231 QueueUndecryptablePacket(packet);
1232 } else if (debug_visitor_ != nullptr) {
1233 debug_visitor_->OnUndecryptablePacket();
1236 DVLOG(1) << ENDPOINT << "Unable to process packet. Last packet processed: "
1237 << last_header_.packet_sequence_number;
1238 return;
1241 ++stats_.packets_processed;
1242 MaybeProcessUndecryptablePackets();
1243 MaybeProcessRevivedPacket();
1244 MaybeSendInResponseToPacket();
1245 SetPingAlarm();
1248 void QuicConnection::CheckForAddressMigration(
1249 const IPEndPoint& self_address, const IPEndPoint& peer_address) {
1250 peer_ip_changed_ = false;
1251 peer_port_changed_ = false;
1252 self_ip_changed_ = false;
1253 self_port_changed_ = false;
1255 if (peer_address_.address().empty()) {
1256 peer_address_ = peer_address;
1258 if (self_address_.address().empty()) {
1259 self_address_ = self_address;
1262 if (!peer_address.address().empty() && !peer_address_.address().empty()) {
1263 peer_ip_changed_ = (peer_address.address() != peer_address_.address());
1264 peer_port_changed_ = (peer_address.port() != peer_address_.port());
1266 // Store in case we want to migrate connection in ProcessValidatedPacket.
1267 migrating_peer_port_ = peer_address.port();
1270 if (!self_address.address().empty() && !self_address_.address().empty()) {
1271 self_ip_changed_ = (self_address.address() != self_address_.address());
1272 self_port_changed_ = (self_address.port() != self_address_.port());
1276 void QuicConnection::OnCanWrite() {
1277 DCHECK(!writer_->IsWriteBlocked());
1279 WriteQueuedPackets();
1280 WritePendingRetransmissions();
1282 // Sending queued packets may have caused the socket to become write blocked,
1283 // or the congestion manager to prohibit sending. If we've sent everything
1284 // we had queued and we're still not blocked, let the visitor know it can
1285 // write more.
1286 if (!CanWrite(HAS_RETRANSMITTABLE_DATA)) {
1287 return;
1290 { // Limit the scope of the bundler. ACK inclusion happens elsewhere.
1291 ScopedPacketBundler bundler(this, NO_ACK);
1292 visitor_->OnCanWrite();
1295 // After the visitor writes, it may have caused the socket to become write
1296 // blocked or the congestion manager to prohibit sending, so check again.
1297 if (visitor_->WillingAndAbleToWrite() &&
1298 !resume_writes_alarm_->IsSet() &&
1299 CanWrite(HAS_RETRANSMITTABLE_DATA)) {
1300 // We're not write blocked, but some stream didn't write out all of its
1301 // bytes. Register for 'immediate' resumption so we'll keep writing after
1302 // other connections and events have had a chance to use the thread.
1303 resume_writes_alarm_->Set(clock_->ApproximateNow());
1307 void QuicConnection::WriteIfNotBlocked() {
1308 if (!writer_->IsWriteBlocked()) {
1309 OnCanWrite();
1313 bool QuicConnection::ProcessValidatedPacket() {
1314 if (peer_ip_changed_ || self_ip_changed_ || self_port_changed_) {
1315 SendConnectionCloseWithDetails(
1316 QUIC_ERROR_MIGRATING_ADDRESS,
1317 "Neither IP address migration, nor self port migration are supported.");
1318 return false;
1321 // Peer port migration is supported, do it now if port has changed.
1322 if (peer_port_changed_) {
1323 DVLOG(1) << ENDPOINT << "Peer's port changed from "
1324 << peer_address_.port() << " to " << migrating_peer_port_
1325 << ", migrating connection.";
1326 peer_address_ = IPEndPoint(peer_address_.address(), migrating_peer_port_);
1329 time_of_last_received_packet_ = clock_->Now();
1330 DVLOG(1) << ENDPOINT << "time of last received packet: "
1331 << time_of_last_received_packet_.ToDebuggingValue();
1333 if (perspective_ == Perspective::IS_SERVER &&
1334 encryption_level_ == ENCRYPTION_NONE &&
1335 last_size_ > packet_generator_.max_packet_length()) {
1336 set_max_packet_length(last_size_);
1338 return true;
1341 void QuicConnection::WriteQueuedPackets() {
1342 DCHECK(!writer_->IsWriteBlocked());
1344 if (pending_version_negotiation_packet_) {
1345 SendVersionNegotiationPacket();
1348 QueuedPacketList::iterator packet_iterator = queued_packets_.begin();
1349 while (packet_iterator != queued_packets_.end() &&
1350 WritePacket(&(*packet_iterator))) {
1351 packet_iterator = queued_packets_.erase(packet_iterator);
1355 void QuicConnection::WritePendingRetransmissions() {
1356 // Keep writing as long as there's a pending retransmission which can be
1357 // written.
1358 while (sent_packet_manager_.HasPendingRetransmissions()) {
1359 const QuicSentPacketManager::PendingRetransmission pending =
1360 sent_packet_manager_.NextPendingRetransmission();
1361 if (!CanWrite(HAS_RETRANSMITTABLE_DATA)) {
1362 break;
1365 // Re-packetize the frames with a new sequence number for retransmission.
1366 // Retransmitted data packets do not use FEC, even when it's enabled.
1367 // Retransmitted packets use the same sequence number length as the
1368 // original.
1369 // Flush the packet generator before making a new packet.
1370 // TODO(ianswett): Implement ReserializeAllFrames as a separate path that
1371 // does not require the creator to be flushed.
1372 packet_generator_.FlushAllQueuedFrames();
1373 SerializedPacket serialized_packet = packet_generator_.ReserializeAllFrames(
1374 pending.retransmittable_frames, pending.sequence_number_length);
1375 if (serialized_packet.packet == nullptr) {
1376 // We failed to serialize the packet, so close the connection.
1377 // CloseConnection does not send close packet, so no infinite loop here.
1378 CloseConnection(QUIC_ENCRYPTION_FAILURE, false);
1379 return;
1382 DVLOG(1) << ENDPOINT << "Retransmitting " << pending.sequence_number
1383 << " as " << serialized_packet.sequence_number;
1384 SendOrQueuePacket(
1385 QueuedPacket(serialized_packet,
1386 pending.retransmittable_frames.encryption_level(),
1387 pending.transmission_type,
1388 pending.sequence_number));
1392 void QuicConnection::RetransmitUnackedPackets(
1393 TransmissionType retransmission_type) {
1394 sent_packet_manager_.RetransmitUnackedPackets(retransmission_type);
1396 WriteIfNotBlocked();
1399 void QuicConnection::NeuterUnencryptedPackets() {
1400 sent_packet_manager_.NeuterUnencryptedPackets();
1401 // This may have changed the retransmission timer, so re-arm it.
1402 QuicTime retransmission_time = sent_packet_manager_.GetRetransmissionTime();
1403 retransmission_alarm_->Update(retransmission_time,
1404 QuicTime::Delta::FromMilliseconds(1));
1407 bool QuicConnection::ShouldGeneratePacket(
1408 TransmissionType transmission_type,
1409 HasRetransmittableData retransmittable,
1410 IsHandshake handshake) {
1411 // We should serialize handshake packets immediately to ensure that they
1412 // end up sent at the right encryption level.
1413 if (handshake == IS_HANDSHAKE) {
1414 return true;
1417 return CanWrite(retransmittable);
1420 bool QuicConnection::CanWrite(HasRetransmittableData retransmittable) {
1421 if (!connected_) {
1422 return false;
1425 if (writer_->IsWriteBlocked()) {
1426 visitor_->OnWriteBlocked();
1427 return false;
1430 QuicTime now = clock_->Now();
1431 QuicTime::Delta delay = sent_packet_manager_.TimeUntilSend(
1432 now, retransmittable);
1433 if (delay.IsInfinite()) {
1434 send_alarm_->Cancel();
1435 return false;
1438 // If the scheduler requires a delay, then we can not send this packet now.
1439 if (!delay.IsZero()) {
1440 send_alarm_->Update(now.Add(delay), QuicTime::Delta::FromMilliseconds(1));
1441 DVLOG(1) << ENDPOINT << "Delaying sending " << delay.ToMilliseconds()
1442 << "ms";
1443 return false;
1445 send_alarm_->Cancel();
1446 return true;
1449 bool QuicConnection::WritePacket(QueuedPacket* packet) {
1450 if (!WritePacketInner(packet)) {
1451 return false;
1453 delete packet->serialized_packet.retransmittable_frames;
1454 delete packet->serialized_packet.packet;
1455 packet->serialized_packet.retransmittable_frames = nullptr;
1456 packet->serialized_packet.packet = nullptr;
1457 return true;
1460 bool QuicConnection::WritePacketInner(QueuedPacket* packet) {
1461 if (ShouldDiscardPacket(*packet)) {
1462 ++stats_.packets_discarded;
1463 return true;
1465 // Connection close packets are encrypted and saved, so don't exit early.
1466 const bool is_connection_close = IsConnectionClose(*packet);
1467 if (writer_->IsWriteBlocked() && !is_connection_close) {
1468 return false;
1471 QuicPacketSequenceNumber sequence_number =
1472 packet->serialized_packet.sequence_number;
1473 DCHECK_LE(sequence_number_of_last_sent_packet_, sequence_number);
1474 sequence_number_of_last_sent_packet_ = sequence_number;
1476 QuicEncryptedPacket* encrypted = packet->serialized_packet.packet;
1477 // Connection close packets are eventually owned by TimeWaitListManager.
1478 // Others are deleted at the end of this call.
1479 if (is_connection_close) {
1480 DCHECK(connection_close_packet_.get() == nullptr);
1481 connection_close_packet_.reset(encrypted);
1482 packet->serialized_packet.packet = nullptr;
1483 // This assures we won't try to write *forced* packets when blocked.
1484 // Return true to stop processing.
1485 if (writer_->IsWriteBlocked()) {
1486 visitor_->OnWriteBlocked();
1487 return true;
1491 if (!FLAGS_quic_allow_oversized_packets_for_test) {
1492 DCHECK_LE(encrypted->length(), kMaxPacketSize);
1494 DCHECK_LE(encrypted->length(), packet_generator_.max_packet_length());
1495 DVLOG(1) << ENDPOINT << "Sending packet " << sequence_number << " : "
1496 << (packet->serialized_packet.is_fec_packet
1497 ? "FEC "
1498 : (IsRetransmittable(*packet) == HAS_RETRANSMITTABLE_DATA
1499 ? "data bearing "
1500 : " ack only ")) << ", encryption level: "
1501 << QuicUtils::EncryptionLevelToString(packet->encryption_level)
1502 << ", encrypted length:" << encrypted->length();
1503 DVLOG(2) << ENDPOINT << "packet(" << sequence_number << "): " << std::endl
1504 << QuicUtils::StringToHexASCIIDump(encrypted->AsStringPiece());
1506 // Measure the RTT from before the write begins to avoid underestimating the
1507 // min_rtt_, especially in cases where the thread blocks or gets swapped out
1508 // during the WritePacket below.
1509 QuicTime packet_send_time = clock_->Now();
1510 WriteResult result = writer_->WritePacket(encrypted->data(),
1511 encrypted->length(),
1512 self_address().address(),
1513 peer_address());
1514 if (result.error_code == ERR_IO_PENDING) {
1515 DCHECK_EQ(WRITE_STATUS_BLOCKED, result.status);
1518 if (result.status == WRITE_STATUS_BLOCKED) {
1519 visitor_->OnWriteBlocked();
1520 // If the socket buffers the the data, then the packet should not
1521 // be queued and sent again, which would result in an unnecessary
1522 // duplicate packet being sent. The helper must call OnCanWrite
1523 // when the write completes, and OnWriteError if an error occurs.
1524 if (!writer_->IsWriteBlockedDataBuffered()) {
1525 return false;
1528 if (result.status != WRITE_STATUS_ERROR && debug_visitor_ != nullptr) {
1529 // Pass the write result to the visitor.
1530 debug_visitor_->OnPacketSent(packet->serialized_packet,
1531 packet->original_sequence_number,
1532 packet->encryption_level,
1533 packet->transmission_type,
1534 *encrypted,
1535 packet_send_time);
1537 if (packet->transmission_type == NOT_RETRANSMISSION) {
1538 time_of_last_sent_new_packet_ = packet_send_time;
1540 SetPingAlarm();
1541 MaybeSetFecAlarm(sequence_number);
1542 DVLOG(1) << ENDPOINT << "time we began writing last sent packet: "
1543 << packet_send_time.ToDebuggingValue();
1545 // TODO(ianswett): Change the sequence number length and other packet creator
1546 // options by a more explicit API than setting a struct value directly,
1547 // perhaps via the NetworkChangeVisitor.
1548 packet_generator_.UpdateSequenceNumberLength(
1549 sent_packet_manager_.least_packet_awaited_by_peer(),
1550 sent_packet_manager_.EstimateMaxPacketsInFlight(max_packet_length()));
1552 bool reset_retransmission_alarm = sent_packet_manager_.OnPacketSent(
1553 &packet->serialized_packet,
1554 packet->original_sequence_number,
1555 packet_send_time,
1556 encrypted->length(),
1557 packet->transmission_type,
1558 IsRetransmittable(*packet));
1560 if (reset_retransmission_alarm || !retransmission_alarm_->IsSet()) {
1561 retransmission_alarm_->Update(sent_packet_manager_.GetRetransmissionTime(),
1562 QuicTime::Delta::FromMilliseconds(1));
1565 stats_.bytes_sent += result.bytes_written;
1566 ++stats_.packets_sent;
1567 if (packet->transmission_type != NOT_RETRANSMISSION) {
1568 stats_.bytes_retransmitted += result.bytes_written;
1569 ++stats_.packets_retransmitted;
1572 if (result.status == WRITE_STATUS_ERROR) {
1573 OnWriteError(result.error_code);
1574 DLOG(ERROR) << ENDPOINT << "failed writing " << encrypted->length()
1575 << "bytes "
1576 << " from host " << self_address().ToStringWithoutPort()
1577 << " to address " << peer_address().ToString();
1578 return false;
1581 return true;
1584 bool QuicConnection::ShouldDiscardPacket(const QueuedPacket& packet) {
1585 if (!connected_) {
1586 DVLOG(1) << ENDPOINT
1587 << "Not sending packet as connection is disconnected.";
1588 return true;
1591 QuicPacketSequenceNumber sequence_number =
1592 packet.serialized_packet.sequence_number;
1593 if (encryption_level_ == ENCRYPTION_FORWARD_SECURE &&
1594 packet.encryption_level == ENCRYPTION_NONE) {
1595 // Drop packets that are NULL encrypted since the peer won't accept them
1596 // anymore.
1597 DVLOG(1) << ENDPOINT << "Dropping NULL encrypted packet: "
1598 << sequence_number << " since the connection is forward secure.";
1599 return true;
1602 // If a retransmission has been acked before sending, don't send it.
1603 // This occurs if a packet gets serialized, queued, then discarded.
1604 if (packet.transmission_type != NOT_RETRANSMISSION &&
1605 (!sent_packet_manager_.IsUnacked(packet.original_sequence_number) ||
1606 !sent_packet_manager_.HasRetransmittableFrames(
1607 packet.original_sequence_number))) {
1608 DVLOG(1) << ENDPOINT << "Dropping unacked packet: " << sequence_number
1609 << " A previous transmission was acked while write blocked.";
1610 return true;
1613 return false;
1616 void QuicConnection::OnWriteError(int error_code) {
1617 DVLOG(1) << ENDPOINT << "Write failed with error: " << error_code
1618 << " (" << ErrorToString(error_code) << ")";
1619 // We can't send an error as the socket is presumably borked.
1620 CloseConnection(QUIC_PACKET_WRITE_ERROR, false);
1623 void QuicConnection::OnSerializedPacket(
1624 const SerializedPacket& serialized_packet) {
1625 if (serialized_packet.packet == nullptr) {
1626 // We failed to serialize the packet, so close the connection.
1627 // CloseConnection does not send close packet, so no infinite loop here.
1628 CloseConnection(QUIC_ENCRYPTION_FAILURE, false);
1629 return;
1631 if (serialized_packet.retransmittable_frames) {
1632 sent_packet_manager_.OnSerializedPacket(serialized_packet);
1634 if (serialized_packet.is_fec_packet && fec_alarm_->IsSet()) {
1635 // If an FEC packet is serialized with the FEC alarm set, cancel the alarm.
1636 fec_alarm_->Cancel();
1638 SendOrQueuePacket(QueuedPacket(serialized_packet, encryption_level_));
1641 void QuicConnection::OnCongestionWindowChange() {
1642 packet_generator_.OnCongestionWindowChange(
1643 sent_packet_manager_.EstimateMaxPacketsInFlight(max_packet_length()));
1644 visitor_->OnCongestionWindowChange(clock_->ApproximateNow());
1647 void QuicConnection::OnRttChange() {
1648 // Uses the connection's smoothed RTT. If zero, uses initial_rtt.
1649 QuicTime::Delta rtt = sent_packet_manager_.GetRttStats()->smoothed_rtt();
1650 if (rtt.IsZero()) {
1651 rtt = QuicTime::Delta::FromMicroseconds(
1652 sent_packet_manager_.GetRttStats()->initial_rtt_us());
1654 packet_generator_.OnRttChange(rtt);
1657 void QuicConnection::OnHandshakeComplete() {
1658 sent_packet_manager_.SetHandshakeConfirmed();
1659 // The client should immediately ack the SHLO to confirm the handshake is
1660 // complete with the server.
1661 if (perspective_ == Perspective::IS_CLIENT && !ack_queued_) {
1662 ack_alarm_->Cancel();
1663 ack_alarm_->Set(clock_->ApproximateNow());
1667 void QuicConnection::SendOrQueuePacket(QueuedPacket packet) {
1668 // The caller of this function is responsible for checking CanWrite().
1669 if (packet.serialized_packet.packet == nullptr) {
1670 LOG(DFATAL)
1671 << "packet.serialized_packet.packet == nullptr in to SendOrQueuePacket";
1672 return;
1675 sent_entropy_manager_.RecordPacketEntropyHash(
1676 packet.serialized_packet.sequence_number,
1677 packet.serialized_packet.entropy_hash);
1678 if (!WritePacket(&packet)) {
1679 queued_packets_.push_back(packet);
1682 // If a forward-secure encrypter is available but is not being used and the
1683 // next sequence number is the first packet which requires
1684 // forward security, start using the forward-secure encrypter.
1685 if (encryption_level_ != ENCRYPTION_FORWARD_SECURE &&
1686 has_forward_secure_encrypter_ &&
1687 packet.serialized_packet.sequence_number >=
1688 first_required_forward_secure_packet_ - 1) {
1689 SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
1693 void QuicConnection::SendPing() {
1694 if (retransmission_alarm_->IsSet()) {
1695 return;
1697 packet_generator_.AddControlFrame(QuicFrame(new QuicPingFrame));
1700 void QuicConnection::SendAck() {
1701 ack_alarm_->Cancel();
1702 stop_waiting_count_ = 0;
1703 num_packets_received_since_last_ack_sent_ = 0;
1705 packet_generator_.SetShouldSendAck(true);
1708 void QuicConnection::OnRetransmissionTimeout() {
1709 if (!sent_packet_manager_.HasUnackedPackets()) {
1710 return;
1713 sent_packet_manager_.OnRetransmissionTimeout();
1714 WriteIfNotBlocked();
1716 // A write failure can result in the connection being closed, don't attempt to
1717 // write further packets, or to set alarms.
1718 if (!connected_) {
1719 return;
1722 // In the TLP case, the SentPacketManager gives the connection the opportunity
1723 // to send new data before retransmitting.
1724 if (sent_packet_manager_.MaybeRetransmitTailLossProbe()) {
1725 // Send the pending retransmission now that it's been queued.
1726 WriteIfNotBlocked();
1729 // Ensure the retransmission alarm is always set if there are unacked packets
1730 // and nothing waiting to be sent.
1731 if (!HasQueuedData() && !retransmission_alarm_->IsSet()) {
1732 QuicTime rto_timeout = sent_packet_manager_.GetRetransmissionTime();
1733 if (rto_timeout.IsInitialized()) {
1734 retransmission_alarm_->Set(rto_timeout);
1739 void QuicConnection::SetEncrypter(EncryptionLevel level,
1740 QuicEncrypter* encrypter) {
1741 packet_generator_.SetEncrypter(level, encrypter);
1742 if (level == ENCRYPTION_FORWARD_SECURE) {
1743 has_forward_secure_encrypter_ = true;
1744 first_required_forward_secure_packet_ =
1745 sequence_number_of_last_sent_packet_ +
1746 // 3 times the current congestion window (in slow start) should cover
1747 // about two full round trips worth of packets, which should be
1748 // sufficient.
1749 3 * sent_packet_manager_.EstimateMaxPacketsInFlight(
1750 max_packet_length());
1754 void QuicConnection::SetDefaultEncryptionLevel(EncryptionLevel level) {
1755 encryption_level_ = level;
1756 packet_generator_.set_encryption_level(level);
1759 void QuicConnection::SetDecrypter(QuicDecrypter* decrypter,
1760 EncryptionLevel level) {
1761 framer_.SetDecrypter(decrypter, level);
1764 void QuicConnection::SetAlternativeDecrypter(QuicDecrypter* decrypter,
1765 EncryptionLevel level,
1766 bool latch_once_used) {
1767 framer_.SetAlternativeDecrypter(decrypter, level, latch_once_used);
1770 const QuicDecrypter* QuicConnection::decrypter() const {
1771 return framer_.decrypter();
1774 const QuicDecrypter* QuicConnection::alternative_decrypter() const {
1775 return framer_.alternative_decrypter();
1778 void QuicConnection::QueueUndecryptablePacket(
1779 const QuicEncryptedPacket& packet) {
1780 DVLOG(1) << ENDPOINT << "Queueing undecryptable packet.";
1781 undecryptable_packets_.push_back(packet.Clone());
1784 void QuicConnection::MaybeProcessUndecryptablePackets() {
1785 if (undecryptable_packets_.empty() || encryption_level_ == ENCRYPTION_NONE) {
1786 return;
1789 while (connected_ && !undecryptable_packets_.empty()) {
1790 DVLOG(1) << ENDPOINT << "Attempting to process undecryptable packet";
1791 QuicEncryptedPacket* packet = undecryptable_packets_.front();
1792 if (!framer_.ProcessPacket(*packet) &&
1793 framer_.error() == QUIC_DECRYPTION_FAILURE) {
1794 DVLOG(1) << ENDPOINT << "Unable to process undecryptable packet...";
1795 break;
1797 DVLOG(1) << ENDPOINT << "Processed undecryptable packet!";
1798 ++stats_.packets_processed;
1799 delete packet;
1800 undecryptable_packets_.pop_front();
1803 // Once forward secure encryption is in use, there will be no
1804 // new keys installed and hence any undecryptable packets will
1805 // never be able to be decrypted.
1806 if (encryption_level_ == ENCRYPTION_FORWARD_SECURE) {
1807 if (debug_visitor_ != nullptr) {
1808 // TODO(rtenneti): perhaps more efficient to pass the number of
1809 // undecryptable packets as the argument to OnUndecryptablePacket so that
1810 // we just need to call OnUndecryptablePacket once?
1811 for (size_t i = 0; i < undecryptable_packets_.size(); ++i) {
1812 debug_visitor_->OnUndecryptablePacket();
1815 STLDeleteElements(&undecryptable_packets_);
1819 void QuicConnection::MaybeProcessRevivedPacket() {
1820 QuicFecGroup* group = GetFecGroup();
1821 if (!connected_ || group == nullptr || !group->CanRevive()) {
1822 return;
1824 QuicPacketHeader revived_header;
1825 char revived_payload[kMaxPacketSize];
1826 size_t len = group->Revive(&revived_header, revived_payload, kMaxPacketSize);
1827 revived_header.public_header.connection_id = connection_id_;
1828 revived_header.public_header.connection_id_length =
1829 last_header_.public_header.connection_id_length;
1830 revived_header.public_header.version_flag = false;
1831 revived_header.public_header.reset_flag = false;
1832 revived_header.public_header.sequence_number_length =
1833 last_header_.public_header.sequence_number_length;
1834 revived_header.fec_flag = false;
1835 revived_header.is_in_fec_group = NOT_IN_FEC_GROUP;
1836 revived_header.fec_group = 0;
1837 group_map_.erase(last_header_.fec_group);
1838 last_decrypted_packet_level_ = group->effective_encryption_level();
1839 DCHECK_LT(last_decrypted_packet_level_, NUM_ENCRYPTION_LEVELS);
1840 delete group;
1842 last_packet_revived_ = true;
1843 if (debug_visitor_ != nullptr) {
1844 debug_visitor_->OnRevivedPacket(revived_header,
1845 StringPiece(revived_payload, len));
1848 ++stats_.packets_revived;
1849 framer_.ProcessRevivedPacket(&revived_header,
1850 StringPiece(revived_payload, len));
1853 QuicFecGroup* QuicConnection::GetFecGroup() {
1854 QuicFecGroupNumber fec_group_num = last_header_.fec_group;
1855 if (fec_group_num == 0) {
1856 return nullptr;
1858 if (!ContainsKey(group_map_, fec_group_num)) {
1859 if (group_map_.size() >= kMaxFecGroups) { // Too many groups
1860 if (fec_group_num < group_map_.begin()->first) {
1861 // The group being requested is a group we've seen before and deleted.
1862 // Don't recreate it.
1863 return nullptr;
1865 // Clear the lowest group number.
1866 delete group_map_.begin()->second;
1867 group_map_.erase(group_map_.begin());
1869 group_map_[fec_group_num] = new QuicFecGroup();
1871 return group_map_[fec_group_num];
1874 void QuicConnection::SendConnectionClose(QuicErrorCode error) {
1875 SendConnectionCloseWithDetails(error, string());
1878 void QuicConnection::SendConnectionCloseWithDetails(QuicErrorCode error,
1879 const string& details) {
1880 // If we're write blocked, WritePacket() will not send, but will capture the
1881 // serialized packet.
1882 SendConnectionClosePacket(error, details);
1883 CloseConnection(error, false);
1886 void QuicConnection::SendConnectionClosePacket(QuicErrorCode error,
1887 const string& details) {
1888 DVLOG(1) << ENDPOINT << "Force closing " << connection_id()
1889 << " with error " << QuicUtils::ErrorToString(error)
1890 << " (" << error << ") " << details;
1891 // Don't send explicit connection close packets for timeouts.
1892 // This is particularly important on mobile, where connections are short.
1893 if (silent_close_enabled_ &&
1894 error == QuicErrorCode::QUIC_CONNECTION_TIMED_OUT) {
1895 return;
1897 ScopedPacketBundler ack_bundler(this, SEND_ACK);
1898 QuicConnectionCloseFrame* frame = new QuicConnectionCloseFrame();
1899 frame->error_code = error;
1900 frame->error_details = details;
1901 packet_generator_.AddControlFrame(QuicFrame(frame));
1902 packet_generator_.FlushAllQueuedFrames();
1905 void QuicConnection::CloseConnection(QuicErrorCode error, bool from_peer) {
1906 if (!connected_) {
1907 DVLOG(1) << "Connection is already closed.";
1908 return;
1910 connected_ = false;
1911 if (debug_visitor_ != nullptr) {
1912 debug_visitor_->OnConnectionClosed(error, from_peer);
1914 DCHECK(visitor_ != nullptr);
1915 visitor_->OnConnectionClosed(error, from_peer);
1916 // Cancel the alarms so they don't trigger any action now that the
1917 // connection is closed.
1918 ack_alarm_->Cancel();
1919 ping_alarm_->Cancel();
1920 fec_alarm_->Cancel();
1921 resume_writes_alarm_->Cancel();
1922 retransmission_alarm_->Cancel();
1923 send_alarm_->Cancel();
1924 timeout_alarm_->Cancel();
1927 void QuicConnection::SendGoAway(QuicErrorCode error,
1928 QuicStreamId last_good_stream_id,
1929 const string& reason) {
1930 DVLOG(1) << ENDPOINT << "Going away with error "
1931 << QuicUtils::ErrorToString(error)
1932 << " (" << error << ")";
1934 // Opportunistically bundle an ack with this outgoing packet.
1935 ScopedPacketBundler ack_bundler(this, BUNDLE_PENDING_ACK);
1936 packet_generator_.AddControlFrame(
1937 QuicFrame(new QuicGoAwayFrame(error, last_good_stream_id, reason)));
1940 void QuicConnection::CloseFecGroupsBefore(
1941 QuicPacketSequenceNumber sequence_number) {
1942 FecGroupMap::iterator it = group_map_.begin();
1943 while (it != group_map_.end()) {
1944 // If this is the current group or the group doesn't protect this packet
1945 // we can ignore it.
1946 if (last_header_.fec_group == it->first ||
1947 !it->second->ProtectsPacketsBefore(sequence_number)) {
1948 ++it;
1949 continue;
1951 QuicFecGroup* fec_group = it->second;
1952 DCHECK(!fec_group->CanRevive());
1953 FecGroupMap::iterator next = it;
1954 ++next;
1955 group_map_.erase(it);
1956 delete fec_group;
1957 it = next;
1961 QuicByteCount QuicConnection::max_packet_length() const {
1962 return packet_generator_.max_packet_length();
1965 void QuicConnection::set_max_packet_length(QuicByteCount length) {
1966 return packet_generator_.set_max_packet_length(length);
1969 bool QuicConnection::HasQueuedData() const {
1970 return pending_version_negotiation_packet_ ||
1971 !queued_packets_.empty() || packet_generator_.HasQueuedFrames();
1974 bool QuicConnection::CanWriteStreamData() {
1975 // Don't write stream data if there are negotiation or queued data packets
1976 // to send. Otherwise, continue and bundle as many frames as possible.
1977 if (pending_version_negotiation_packet_ || !queued_packets_.empty()) {
1978 return false;
1981 IsHandshake pending_handshake = visitor_->HasPendingHandshake() ?
1982 IS_HANDSHAKE : NOT_HANDSHAKE;
1983 // Sending queued packets may have caused the socket to become write blocked,
1984 // or the congestion manager to prohibit sending. If we've sent everything
1985 // we had queued and we're still not blocked, let the visitor know it can
1986 // write more.
1987 return ShouldGeneratePacket(NOT_RETRANSMISSION, HAS_RETRANSMITTABLE_DATA,
1988 pending_handshake);
1991 void QuicConnection::SetNetworkTimeouts(QuicTime::Delta overall_timeout,
1992 QuicTime::Delta idle_timeout) {
1993 LOG_IF(DFATAL, idle_timeout > overall_timeout)
1994 << "idle_timeout:" << idle_timeout.ToMilliseconds()
1995 << " overall_timeout:" << overall_timeout.ToMilliseconds();
1996 // Adjust the idle timeout on client and server to prevent clients from
1997 // sending requests to servers which have already closed the connection.
1998 if (perspective_ == Perspective::IS_SERVER) {
1999 idle_timeout = idle_timeout.Add(QuicTime::Delta::FromSeconds(3));
2000 } else if (idle_timeout > QuicTime::Delta::FromSeconds(1)) {
2001 idle_timeout = idle_timeout.Subtract(QuicTime::Delta::FromSeconds(1));
2003 overall_connection_timeout_ = overall_timeout;
2004 idle_network_timeout_ = idle_timeout;
2006 SetTimeoutAlarm();
2009 void QuicConnection::CheckForTimeout() {
2010 QuicTime now = clock_->ApproximateNow();
2011 QuicTime time_of_last_packet = max(time_of_last_received_packet_,
2012 time_of_last_sent_new_packet_);
2014 // |delta| can be < 0 as |now| is approximate time but |time_of_last_packet|
2015 // is accurate time. However, this should not change the behavior of
2016 // timeout handling.
2017 QuicTime::Delta idle_duration = now.Subtract(time_of_last_packet);
2018 DVLOG(1) << ENDPOINT << "last packet "
2019 << time_of_last_packet.ToDebuggingValue()
2020 << " now:" << now.ToDebuggingValue()
2021 << " idle_duration:" << idle_duration.ToMicroseconds()
2022 << " idle_network_timeout: "
2023 << idle_network_timeout_.ToMicroseconds();
2024 if (idle_duration >= idle_network_timeout_) {
2025 DVLOG(1) << ENDPOINT << "Connection timedout due to no network activity.";
2026 SendConnectionClose(QUIC_CONNECTION_TIMED_OUT);
2027 return;
2030 if (!overall_connection_timeout_.IsInfinite()) {
2031 QuicTime::Delta connected_duration =
2032 now.Subtract(stats_.connection_creation_time);
2033 DVLOG(1) << ENDPOINT << "connection time: "
2034 << connected_duration.ToMicroseconds() << " overall timeout: "
2035 << overall_connection_timeout_.ToMicroseconds();
2036 if (connected_duration >= overall_connection_timeout_) {
2037 DVLOG(1) << ENDPOINT <<
2038 "Connection timedout due to overall connection timeout.";
2039 SendConnectionClose(QUIC_CONNECTION_OVERALL_TIMED_OUT);
2040 return;
2044 SetTimeoutAlarm();
2047 void QuicConnection::SetTimeoutAlarm() {
2048 QuicTime time_of_last_packet = max(time_of_last_received_packet_,
2049 time_of_last_sent_new_packet_);
2051 QuicTime deadline = time_of_last_packet.Add(idle_network_timeout_);
2052 if (!overall_connection_timeout_.IsInfinite()) {
2053 deadline = min(deadline,
2054 stats_.connection_creation_time.Add(
2055 overall_connection_timeout_));
2058 timeout_alarm_->Cancel();
2059 timeout_alarm_->Set(deadline);
2062 void QuicConnection::SetPingAlarm() {
2063 if (perspective_ == Perspective::IS_SERVER) {
2064 // Only clients send pings.
2065 return;
2067 if (!visitor_->HasOpenDataStreams()) {
2068 ping_alarm_->Cancel();
2069 // Don't send a ping unless there are open streams.
2070 return;
2072 QuicTime::Delta ping_timeout = QuicTime::Delta::FromSeconds(kPingTimeoutSecs);
2073 ping_alarm_->Update(clock_->ApproximateNow().Add(ping_timeout),
2074 QuicTime::Delta::FromSeconds(1));
2077 QuicConnection::ScopedPacketBundler::ScopedPacketBundler(
2078 QuicConnection* connection,
2079 AckBundling send_ack)
2080 : connection_(connection),
2081 already_in_batch_mode_(connection != nullptr &&
2082 connection->packet_generator_.InBatchMode()) {
2083 if (connection_ == nullptr) {
2084 return;
2086 // Move generator into batch mode. If caller wants us to include an ack,
2087 // check the delayed-ack timer to see if there's ack info to be sent.
2088 if (!already_in_batch_mode_) {
2089 DVLOG(1) << "Entering Batch Mode.";
2090 connection_->packet_generator_.StartBatchOperations();
2092 // Bundle an ack if the alarm is set or with every second packet if we need to
2093 // raise the peer's least unacked.
2094 bool ack_pending =
2095 connection_->ack_alarm_->IsSet() || connection_->stop_waiting_count_ > 1;
2096 if (send_ack == SEND_ACK || (send_ack == BUNDLE_PENDING_ACK && ack_pending)) {
2097 DVLOG(1) << "Bundling ack with outgoing packet.";
2098 connection_->SendAck();
2102 QuicConnection::ScopedPacketBundler::~ScopedPacketBundler() {
2103 if (connection_ == nullptr) {
2104 return;
2106 // If we changed the generator's batch state, restore original batch state.
2107 if (!already_in_batch_mode_) {
2108 DVLOG(1) << "Leaving Batch Mode.";
2109 connection_->packet_generator_.FinishBatchOperations();
2111 DCHECK_EQ(already_in_batch_mode_,
2112 connection_->packet_generator_.InBatchMode());
2115 HasRetransmittableData QuicConnection::IsRetransmittable(
2116 const QueuedPacket& packet) {
2117 // Retransmitted packets retransmittable frames are owned by the unacked
2118 // packet map, but are not present in the serialized packet.
2119 if (packet.transmission_type != NOT_RETRANSMISSION ||
2120 packet.serialized_packet.retransmittable_frames != nullptr) {
2121 return HAS_RETRANSMITTABLE_DATA;
2122 } else {
2123 return NO_RETRANSMITTABLE_DATA;
2127 bool QuicConnection::IsConnectionClose(const QueuedPacket& packet) {
2128 const RetransmittableFrames* retransmittable_frames =
2129 packet.serialized_packet.retransmittable_frames;
2130 if (retransmittable_frames == nullptr) {
2131 return false;
2133 for (const QuicFrame& frame : retransmittable_frames->frames()) {
2134 if (frame.type == CONNECTION_CLOSE_FRAME) {
2135 return true;
2138 return false;
2141 } // namespace net