Update broken references to image assets
[chromium-blink-merge.git] / net / quic / quic_connection.cc
blobba3b977f0b8c84208478df0887bff510ba2ebfdc
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/format_macros.h"
18 #include "base/logging.h"
19 #include "base/memory/ref_counted.h"
20 #include "base/profiler/scoped_tracker.h"
21 #include "base/stl_util.h"
22 #include "base/strings/stringprintf.h"
23 #include "net/base/net_errors.h"
24 #include "net/quic/crypto/crypto_protocol.h"
25 #include "net/quic/crypto/quic_decrypter.h"
26 #include "net/quic/crypto/quic_encrypter.h"
27 #include "net/quic/proto/cached_network_parameters.pb.h"
28 #include "net/quic/quic_bandwidth.h"
29 #include "net/quic/quic_config.h"
30 #include "net/quic/quic_fec_group.h"
31 #include "net/quic/quic_flags.h"
32 #include "net/quic/quic_packet_generator.h"
33 #include "net/quic/quic_utils.h"
35 using base::StringPiece;
36 using base::StringPrintf;
37 using base::hash_map;
38 using base::hash_set;
39 using std::list;
40 using std::make_pair;
41 using std::max;
42 using std::min;
43 using std::numeric_limits;
44 using std::set;
45 using std::string;
46 using std::vector;
48 namespace net {
50 class QuicDecrypter;
51 class QuicEncrypter;
53 namespace {
55 // The largest gap in packets we'll accept without closing the connection.
56 // This will likely have to be tuned.
57 const QuicPacketSequenceNumber kMaxPacketGap = 5000;
59 // Limit the number of FEC groups to two. If we get enough out of order packets
60 // that this becomes limiting, we can revisit.
61 const size_t kMaxFecGroups = 2;
63 // Maximum number of acks received before sending an ack in response.
64 const QuicPacketCount kMaxPacketsReceivedBeforeAckSend = 20;
66 bool Near(QuicPacketSequenceNumber a, QuicPacketSequenceNumber b) {
67 QuicPacketSequenceNumber delta = (a > b) ? a - b : b - a;
68 return delta <= kMaxPacketGap;
71 // An alarm that is scheduled to send an ack if a timeout occurs.
72 class AckAlarm : public QuicAlarm::Delegate {
73 public:
74 explicit AckAlarm(QuicConnection* connection)
75 : connection_(connection) {
78 QuicTime OnAlarm() override {
79 connection_->SendAck();
80 return QuicTime::Zero();
83 private:
84 QuicConnection* connection_;
86 DISALLOW_COPY_AND_ASSIGN(AckAlarm);
89 // This alarm will be scheduled any time a data-bearing packet is sent out.
90 // When the alarm goes off, the connection checks to see if the oldest packets
91 // have been acked, and retransmit them if they have not.
92 class RetransmissionAlarm : public QuicAlarm::Delegate {
93 public:
94 explicit RetransmissionAlarm(QuicConnection* connection)
95 : connection_(connection) {
98 QuicTime OnAlarm() override {
99 connection_->OnRetransmissionTimeout();
100 return QuicTime::Zero();
103 private:
104 QuicConnection* connection_;
106 DISALLOW_COPY_AND_ASSIGN(RetransmissionAlarm);
109 // An alarm that is scheduled when the SentPacketManager requires a delay
110 // before sending packets and fires when the packet may be sent.
111 class SendAlarm : public QuicAlarm::Delegate {
112 public:
113 explicit SendAlarm(QuicConnection* connection)
114 : connection_(connection) {
117 QuicTime OnAlarm() override {
118 connection_->WriteIfNotBlocked();
119 // Never reschedule the alarm, since CanWrite does that.
120 return QuicTime::Zero();
123 private:
124 QuicConnection* connection_;
126 DISALLOW_COPY_AND_ASSIGN(SendAlarm);
129 class TimeoutAlarm : public QuicAlarm::Delegate {
130 public:
131 explicit TimeoutAlarm(QuicConnection* connection)
132 : connection_(connection) {
135 QuicTime OnAlarm() override {
136 connection_->CheckForTimeout();
137 // Never reschedule the alarm, since CheckForTimeout does that.
138 return QuicTime::Zero();
141 private:
142 QuicConnection* connection_;
144 DISALLOW_COPY_AND_ASSIGN(TimeoutAlarm);
147 class PingAlarm : public QuicAlarm::Delegate {
148 public:
149 explicit PingAlarm(QuicConnection* connection)
150 : connection_(connection) {
153 QuicTime OnAlarm() override {
154 connection_->SendPing();
155 return QuicTime::Zero();
158 private:
159 QuicConnection* connection_;
161 DISALLOW_COPY_AND_ASSIGN(PingAlarm);
164 class MtuDiscoveryAlarm : public QuicAlarm::Delegate {
165 public:
166 explicit MtuDiscoveryAlarm(QuicConnection* connection)
167 : connection_(connection) {}
169 QuicTime OnAlarm() override {
170 connection_->DiscoverMtu();
171 // DiscoverMtu() handles rescheduling the alarm by itself.
172 return QuicTime::Zero();
175 private:
176 QuicConnection* connection_;
178 DISALLOW_COPY_AND_ASSIGN(MtuDiscoveryAlarm);
181 // This alarm may be scheduled when an FEC protected packet is sent out.
182 class FecAlarm : public QuicAlarm::Delegate {
183 public:
184 explicit FecAlarm(QuicPacketGenerator* packet_generator)
185 : packet_generator_(packet_generator) {}
187 QuicTime OnAlarm() override {
188 packet_generator_->OnFecTimeout();
189 return QuicTime::Zero();
192 private:
193 QuicPacketGenerator* packet_generator_;
195 DISALLOW_COPY_AND_ASSIGN(FecAlarm);
198 // Listens for acks of MTU discovery packets and raises the maximum packet size
199 // of the connection if the probe succeeds.
200 class MtuDiscoveryAckListener : public QuicAckNotifier::DelegateInterface {
201 public:
202 MtuDiscoveryAckListener(QuicConnection* connection, QuicByteCount probe_size)
203 : connection_(connection), probe_size_(probe_size) {}
205 void OnAckNotification(int /*num_retransmittable_packets*/,
206 int /*num_retransmittable_bytes*/,
207 QuicTime::Delta /*delta_largest_observed*/) override {
208 // Since the probe was successful, increase the maximum packet size to that.
209 if (probe_size_ > connection_->max_packet_length()) {
210 connection_->set_max_packet_length(probe_size_);
214 protected:
215 // MtuDiscoveryAckListener is ref counted.
216 ~MtuDiscoveryAckListener() override {}
218 private:
219 QuicConnection* connection_;
220 QuicByteCount probe_size_;
222 DISALLOW_COPY_AND_ASSIGN(MtuDiscoveryAckListener);
225 } // namespace
227 QuicConnection::QueuedPacket::QueuedPacket(SerializedPacket packet,
228 EncryptionLevel level)
229 : serialized_packet(packet),
230 encryption_level(level),
231 transmission_type(NOT_RETRANSMISSION),
232 original_sequence_number(0) {
235 QuicConnection::QueuedPacket::QueuedPacket(
236 SerializedPacket packet,
237 EncryptionLevel level,
238 TransmissionType transmission_type,
239 QuicPacketSequenceNumber original_sequence_number)
240 : serialized_packet(packet),
241 encryption_level(level),
242 transmission_type(transmission_type),
243 original_sequence_number(original_sequence_number) {
246 #define ENDPOINT \
247 (perspective_ == Perspective::IS_SERVER ? "Server: " : "Client: ")
249 QuicConnection::QuicConnection(QuicConnectionId connection_id,
250 IPEndPoint address,
251 QuicConnectionHelperInterface* helper,
252 const PacketWriterFactory& writer_factory,
253 bool owns_writer,
254 Perspective perspective,
255 bool is_secure,
256 const QuicVersionVector& supported_versions)
257 : framer_(supported_versions,
258 helper->GetClock()->ApproximateNow(),
259 perspective),
260 helper_(helper),
261 writer_(writer_factory.Create(this)),
262 owns_writer_(owns_writer),
263 encryption_level_(ENCRYPTION_NONE),
264 has_forward_secure_encrypter_(false),
265 first_required_forward_secure_packet_(0),
266 clock_(helper->GetClock()),
267 random_generator_(helper->GetRandomGenerator()),
268 connection_id_(connection_id),
269 peer_address_(address),
270 migrating_peer_port_(0),
271 last_packet_decrypted_(false),
272 last_packet_revived_(false),
273 last_size_(0),
274 last_decrypted_packet_level_(ENCRYPTION_NONE),
275 should_last_packet_instigate_acks_(false),
276 largest_seen_packet_with_ack_(0),
277 largest_seen_packet_with_stop_waiting_(0),
278 max_undecryptable_packets_(0),
279 pending_version_negotiation_packet_(false),
280 silent_close_enabled_(false),
281 received_packet_manager_(&stats_),
282 ack_queued_(false),
283 num_packets_received_since_last_ack_sent_(0),
284 stop_waiting_count_(0),
285 delay_setting_retransmission_alarm_(false),
286 pending_retransmission_alarm_(false),
287 ack_alarm_(helper->CreateAlarm(new AckAlarm(this))),
288 retransmission_alarm_(helper->CreateAlarm(new RetransmissionAlarm(this))),
289 send_alarm_(helper->CreateAlarm(new SendAlarm(this))),
290 resume_writes_alarm_(helper->CreateAlarm(new SendAlarm(this))),
291 timeout_alarm_(helper->CreateAlarm(new TimeoutAlarm(this))),
292 ping_alarm_(helper->CreateAlarm(new PingAlarm(this))),
293 mtu_discovery_alarm_(helper->CreateAlarm(new MtuDiscoveryAlarm(this))),
294 visitor_(nullptr),
295 debug_visitor_(nullptr),
296 packet_generator_(connection_id_, &framer_, random_generator_, this),
297 fec_alarm_(helper->CreateAlarm(new FecAlarm(&packet_generator_))),
298 idle_network_timeout_(QuicTime::Delta::Infinite()),
299 overall_connection_timeout_(QuicTime::Delta::Infinite()),
300 time_of_last_received_packet_(clock_->ApproximateNow()),
301 time_of_last_sent_new_packet_(clock_->ApproximateNow()),
302 sequence_number_of_last_sent_packet_(0),
303 sent_packet_manager_(
304 perspective,
305 clock_,
306 &stats_,
307 FLAGS_quic_use_bbr_congestion_control ? kBBR : kCubic,
308 FLAGS_quic_use_time_loss_detection ? kTime : kNack,
309 is_secure),
310 version_negotiation_state_(START_NEGOTIATION),
311 perspective_(perspective),
312 connected_(true),
313 peer_ip_changed_(false),
314 peer_port_changed_(false),
315 self_ip_changed_(false),
316 self_port_changed_(false),
317 can_truncate_connection_ids_(true),
318 is_secure_(is_secure),
319 mtu_discovery_target_(0),
320 mtu_probe_count_(0),
321 packets_between_mtu_probes_(kPacketsBetweenMtuProbesBase),
322 next_mtu_probe_at_(kPacketsBetweenMtuProbesBase),
323 largest_received_packet_size_(0),
324 goaway_sent_(false),
325 goaway_received_(false) {
326 DVLOG(1) << ENDPOINT << "Created connection with connection_id: "
327 << connection_id;
328 framer_.set_visitor(this);
329 framer_.set_received_entropy_calculator(&received_packet_manager_);
330 stats_.connection_creation_time = clock_->ApproximateNow();
331 sent_packet_manager_.set_network_change_visitor(this);
332 if (perspective_ == Perspective::IS_SERVER) {
333 set_max_packet_length(kDefaultServerMaxPacketSize);
337 QuicConnection::~QuicConnection() {
338 if (owns_writer_) {
339 delete writer_;
341 STLDeleteElements(&undecryptable_packets_);
342 STLDeleteValues(&group_map_);
343 for (QueuedPacketList::iterator it = queued_packets_.begin();
344 it != queued_packets_.end(); ++it) {
345 delete it->serialized_packet.retransmittable_frames;
346 delete it->serialized_packet.packet;
350 void QuicConnection::SetFromConfig(const QuicConfig& config) {
351 if (config.negotiated()) {
352 SetNetworkTimeouts(QuicTime::Delta::Infinite(),
353 config.IdleConnectionStateLifetime());
354 if (config.SilentClose()) {
355 silent_close_enabled_ = true;
357 } else {
358 SetNetworkTimeouts(config.max_time_before_crypto_handshake(),
359 config.max_idle_time_before_crypto_handshake());
362 sent_packet_manager_.SetFromConfig(config);
363 if (config.HasReceivedBytesForConnectionId() &&
364 can_truncate_connection_ids_) {
365 packet_generator_.SetConnectionIdLength(
366 config.ReceivedBytesForConnectionId());
368 max_undecryptable_packets_ = config.max_undecryptable_packets();
370 if (config.HasClientSentConnectionOption(kFSPA, perspective_)) {
371 packet_generator_.set_fec_send_policy(FecSendPolicy::FEC_ALARM_TRIGGER);
373 if (config.HasClientSentConnectionOption(kFRTT, perspective_)) {
374 // TODO(rtenneti): Delete this code after the 0.25 RTT FEC experiment.
375 const float kFecTimeoutRttMultiplier = 0.25;
376 packet_generator_.set_rtt_multiplier_for_fec_timeout(
377 kFecTimeoutRttMultiplier);
380 if (config.HasClientSentConnectionOption(kMTUH, perspective_)) {
381 mtu_discovery_target_ = kMtuDiscoveryTargetPacketSizeHigh;
383 if (config.HasClientSentConnectionOption(kMTUL, perspective_)) {
384 mtu_discovery_target_ = kMtuDiscoveryTargetPacketSizeLow;
388 void QuicConnection::OnSendConnectionState(
389 const CachedNetworkParameters& cached_network_params) {
390 if (debug_visitor_ != nullptr) {
391 debug_visitor_->OnSendConnectionState(cached_network_params);
395 void QuicConnection::ResumeConnectionState(
396 const CachedNetworkParameters& cached_network_params,
397 bool max_bandwidth_resumption) {
398 if (debug_visitor_ != nullptr) {
399 debug_visitor_->OnResumeConnectionState(cached_network_params);
401 sent_packet_manager_.ResumeConnectionState(cached_network_params,
402 max_bandwidth_resumption);
405 void QuicConnection::SetNumOpenStreams(size_t num_streams) {
406 sent_packet_manager_.SetNumOpenStreams(num_streams);
409 bool QuicConnection::SelectMutualVersion(
410 const QuicVersionVector& available_versions) {
411 // Try to find the highest mutual version by iterating over supported
412 // versions, starting with the highest, and breaking out of the loop once we
413 // find a matching version in the provided available_versions vector.
414 const QuicVersionVector& supported_versions = framer_.supported_versions();
415 for (size_t i = 0; i < supported_versions.size(); ++i) {
416 const QuicVersion& version = supported_versions[i];
417 if (std::find(available_versions.begin(), available_versions.end(),
418 version) != available_versions.end()) {
419 framer_.set_version(version);
420 return true;
424 return false;
427 void QuicConnection::OnError(QuicFramer* framer) {
428 // Packets that we can not or have not decrypted are dropped.
429 // TODO(rch): add stats to measure this.
430 if (!connected_ || last_packet_decrypted_ == false) {
431 return;
433 SendConnectionCloseWithDetails(framer->error(), framer->detailed_error());
436 void QuicConnection::MaybeSetFecAlarm(
437 QuicPacketSequenceNumber sequence_number) {
438 if (fec_alarm_->IsSet()) {
439 return;
441 QuicTime::Delta timeout = packet_generator_.GetFecTimeout(sequence_number);
442 if (!timeout.IsInfinite()) {
443 fec_alarm_->Set(clock_->ApproximateNow().Add(timeout));
447 void QuicConnection::OnPacket() {
448 DCHECK(last_stream_frames_.empty() &&
449 last_ack_frames_.empty() &&
450 last_stop_waiting_frames_.empty() &&
451 last_rst_frames_.empty() &&
452 last_goaway_frames_.empty() &&
453 last_window_update_frames_.empty() &&
454 last_blocked_frames_.empty() &&
455 last_ping_frames_.empty() &&
456 last_close_frames_.empty());
457 last_packet_decrypted_ = false;
458 last_packet_revived_ = false;
461 void QuicConnection::OnPublicResetPacket(const QuicPublicResetPacket& packet) {
462 // Check that any public reset packet with a different connection ID that was
463 // routed to this QuicConnection has been redirected before control reaches
464 // here. (Check for a bug regression.)
465 DCHECK_EQ(connection_id_, packet.public_header.connection_id);
466 if (debug_visitor_ != nullptr) {
467 debug_visitor_->OnPublicResetPacket(packet);
469 CloseConnection(QUIC_PUBLIC_RESET, true);
471 DVLOG(1) << ENDPOINT << "Connection " << connection_id()
472 << " closed via QUIC_PUBLIC_RESET from peer.";
475 bool QuicConnection::OnProtocolVersionMismatch(QuicVersion received_version) {
476 DVLOG(1) << ENDPOINT << "Received packet with mismatched version "
477 << received_version;
478 // TODO(satyamshekhar): Implement no server state in this mode.
479 if (perspective_ == Perspective::IS_CLIENT) {
480 LOG(DFATAL) << ENDPOINT << "Framer called OnProtocolVersionMismatch. "
481 << "Closing connection.";
482 CloseConnection(QUIC_INTERNAL_ERROR, false);
483 return false;
485 DCHECK_NE(version(), received_version);
487 if (debug_visitor_ != nullptr) {
488 debug_visitor_->OnProtocolVersionMismatch(received_version);
491 switch (version_negotiation_state_) {
492 case START_NEGOTIATION:
493 if (!framer_.IsSupportedVersion(received_version)) {
494 SendVersionNegotiationPacket();
495 version_negotiation_state_ = NEGOTIATION_IN_PROGRESS;
496 return false;
498 break;
500 case NEGOTIATION_IN_PROGRESS:
501 if (!framer_.IsSupportedVersion(received_version)) {
502 SendVersionNegotiationPacket();
503 return false;
505 break;
507 case NEGOTIATED_VERSION:
508 // Might be old packets that were sent by the client before the version
509 // was negotiated. Drop these.
510 return false;
512 default:
513 DCHECK(false);
516 version_negotiation_state_ = NEGOTIATED_VERSION;
517 visitor_->OnSuccessfulVersionNegotiation(received_version);
518 if (debug_visitor_ != nullptr) {
519 debug_visitor_->OnSuccessfulVersionNegotiation(received_version);
521 DVLOG(1) << ENDPOINT << "version negotiated " << received_version;
523 // Store the new version.
524 framer_.set_version(received_version);
526 // TODO(satyamshekhar): Store the sequence number of this packet and close the
527 // connection if we ever received a packet with incorrect version and whose
528 // sequence number is greater.
529 return true;
532 // Handles version negotiation for client connection.
533 void QuicConnection::OnVersionNegotiationPacket(
534 const QuicVersionNegotiationPacket& packet) {
535 // Check that any public reset packet with a different connection ID that was
536 // routed to this QuicConnection has been redirected before control reaches
537 // here. (Check for a bug regression.)
538 DCHECK_EQ(connection_id_, packet.connection_id);
539 if (perspective_ == Perspective::IS_SERVER) {
540 LOG(DFATAL) << ENDPOINT << "Framer parsed VersionNegotiationPacket."
541 << " Closing connection.";
542 CloseConnection(QUIC_INTERNAL_ERROR, false);
543 return;
545 if (debug_visitor_ != nullptr) {
546 debug_visitor_->OnVersionNegotiationPacket(packet);
549 if (version_negotiation_state_ != START_NEGOTIATION) {
550 // Possibly a duplicate version negotiation packet.
551 return;
554 if (std::find(packet.versions.begin(),
555 packet.versions.end(), version()) !=
556 packet.versions.end()) {
557 DLOG(WARNING) << ENDPOINT << "The server already supports our version. "
558 << "It should have accepted our connection.";
559 // Just drop the connection.
560 CloseConnection(QUIC_INVALID_VERSION_NEGOTIATION_PACKET, false);
561 return;
564 if (!SelectMutualVersion(packet.versions)) {
565 SendConnectionCloseWithDetails(QUIC_INVALID_VERSION,
566 "no common version found");
567 return;
570 DVLOG(1) << ENDPOINT
571 << "Negotiated version: " << QuicVersionToString(version());
572 server_supported_versions_ = packet.versions;
573 version_negotiation_state_ = NEGOTIATION_IN_PROGRESS;
574 RetransmitUnackedPackets(ALL_UNACKED_RETRANSMISSION);
577 void QuicConnection::OnRevivedPacket() {
580 bool QuicConnection::OnUnauthenticatedPublicHeader(
581 const QuicPacketPublicHeader& header) {
582 if (header.connection_id == connection_id_) {
583 return true;
586 ++stats_.packets_dropped;
587 DVLOG(1) << ENDPOINT << "Ignoring packet from unexpected ConnectionId: "
588 << header.connection_id << " instead of " << connection_id_;
589 if (debug_visitor_ != nullptr) {
590 debug_visitor_->OnIncorrectConnectionId(header.connection_id);
592 // If this is a server, the dispatcher routes each packet to the
593 // QuicConnection responsible for the packet's connection ID. So if control
594 // arrives here and this is a server, the dispatcher must be malfunctioning.
595 DCHECK_NE(Perspective::IS_SERVER, perspective_);
596 return false;
599 bool QuicConnection::OnUnauthenticatedHeader(const QuicPacketHeader& header) {
600 // Check that any public reset packet with a different connection ID that was
601 // routed to this QuicConnection has been redirected before control reaches
602 // here.
603 DCHECK_EQ(connection_id_, header.public_header.connection_id);
604 return true;
607 void QuicConnection::OnDecryptedPacket(EncryptionLevel level) {
608 last_decrypted_packet_level_ = level;
609 last_packet_decrypted_ = true;
610 // If this packet was foward-secure encrypted and the forward-secure encrypter
611 // is not being used, start using it.
612 if (encryption_level_ != ENCRYPTION_FORWARD_SECURE &&
613 has_forward_secure_encrypter_ && level == ENCRYPTION_FORWARD_SECURE) {
614 SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
618 bool QuicConnection::OnPacketHeader(const QuicPacketHeader& header) {
619 if (debug_visitor_ != nullptr) {
620 debug_visitor_->OnPacketHeader(header);
623 if (!ProcessValidatedPacket()) {
624 return false;
627 // Will be decremented below if we fall through to return true.
628 ++stats_.packets_dropped;
630 if (!Near(header.packet_sequence_number,
631 last_header_.packet_sequence_number)) {
632 DVLOG(1) << ENDPOINT << "Packet " << header.packet_sequence_number
633 << " out of bounds. Discarding";
634 SendConnectionCloseWithDetails(QUIC_INVALID_PACKET_HEADER,
635 "Packet sequence number out of bounds");
636 return false;
639 // If this packet has already been seen, or the sender has told us that it
640 // will not be retransmitted, then stop processing the packet.
641 if (!received_packet_manager_.IsAwaitingPacket(
642 header.packet_sequence_number)) {
643 DVLOG(1) << ENDPOINT << "Packet " << header.packet_sequence_number
644 << " no longer being waited for. Discarding.";
645 if (debug_visitor_ != nullptr) {
646 debug_visitor_->OnDuplicatePacket(header.packet_sequence_number);
648 return false;
651 if (version_negotiation_state_ != NEGOTIATED_VERSION) {
652 if (perspective_ == Perspective::IS_SERVER) {
653 if (!header.public_header.version_flag) {
654 DLOG(WARNING) << ENDPOINT << "Packet " << header.packet_sequence_number
655 << " without version flag before version negotiated.";
656 // Packets should have the version flag till version negotiation is
657 // done.
658 CloseConnection(QUIC_INVALID_VERSION, false);
659 return false;
660 } else {
661 DCHECK_EQ(1u, header.public_header.versions.size());
662 DCHECK_EQ(header.public_header.versions[0], version());
663 version_negotiation_state_ = NEGOTIATED_VERSION;
664 visitor_->OnSuccessfulVersionNegotiation(version());
665 if (debug_visitor_ != nullptr) {
666 debug_visitor_->OnSuccessfulVersionNegotiation(version());
669 } else {
670 DCHECK(!header.public_header.version_flag);
671 // If the client gets a packet without the version flag from the server
672 // it should stop sending version since the version negotiation is done.
673 packet_generator_.StopSendingVersion();
674 version_negotiation_state_ = NEGOTIATED_VERSION;
675 visitor_->OnSuccessfulVersionNegotiation(version());
676 if (debug_visitor_ != nullptr) {
677 debug_visitor_->OnSuccessfulVersionNegotiation(version());
682 DCHECK_EQ(NEGOTIATED_VERSION, version_negotiation_state_);
684 --stats_.packets_dropped;
685 DVLOG(1) << ENDPOINT << "Received packet header: " << header;
686 last_header_ = header;
687 DCHECK(connected_);
688 return true;
691 void QuicConnection::OnFecProtectedPayload(StringPiece payload) {
692 DCHECK_EQ(IN_FEC_GROUP, last_header_.is_in_fec_group);
693 DCHECK_NE(0u, last_header_.fec_group);
694 QuicFecGroup* group = GetFecGroup();
695 if (group != nullptr) {
696 group->Update(last_decrypted_packet_level_, last_header_, payload);
700 bool QuicConnection::OnStreamFrame(const QuicStreamFrame& frame) {
701 DCHECK(connected_);
702 if (debug_visitor_ != nullptr) {
703 debug_visitor_->OnStreamFrame(frame);
705 if (frame.stream_id != kCryptoStreamId &&
706 last_decrypted_packet_level_ == ENCRYPTION_NONE) {
707 DLOG(WARNING) << ENDPOINT
708 << "Received an unencrypted data frame: closing connection";
709 SendConnectionClose(QUIC_UNENCRYPTED_STREAM_DATA);
710 return false;
712 if (FLAGS_quic_process_frames_inline) {
713 visitor_->OnStreamFrame(frame);
714 stats_.stream_bytes_received += frame.data.size();
715 should_last_packet_instigate_acks_ = true;
716 } else {
717 last_stream_frames_.push_back(frame);
719 return connected_;
722 bool QuicConnection::OnAckFrame(const QuicAckFrame& incoming_ack) {
723 DCHECK(connected_);
724 if (debug_visitor_ != nullptr) {
725 debug_visitor_->OnAckFrame(incoming_ack);
727 DVLOG(1) << ENDPOINT << "OnAckFrame: " << incoming_ack;
729 if (last_header_.packet_sequence_number <= largest_seen_packet_with_ack_) {
730 DVLOG(1) << ENDPOINT << "Received an old ack frame: ignoring";
731 return true;
734 if (!ValidateAckFrame(incoming_ack)) {
735 SendConnectionClose(QUIC_INVALID_ACK_DATA);
736 return false;
739 if (FLAGS_quic_process_frames_inline) {
740 ProcessAckFrame(incoming_ack);
741 if (incoming_ack.is_truncated) {
742 should_last_packet_instigate_acks_ = true;
744 if (!incoming_ack.missing_packets.empty() &&
745 GetLeastUnacked() > *incoming_ack.missing_packets.begin()) {
746 ++stop_waiting_count_;
747 } else {
748 stop_waiting_count_ = 0;
750 } else {
751 last_ack_frames_.push_back(incoming_ack);
753 return connected_;
756 void QuicConnection::ProcessAckFrame(const QuicAckFrame& incoming_ack) {
757 largest_seen_packet_with_ack_ = last_header_.packet_sequence_number;
758 sent_packet_manager_.OnIncomingAck(incoming_ack,
759 time_of_last_received_packet_);
760 sent_entropy_manager_.ClearEntropyBefore(
761 sent_packet_manager_.least_packet_awaited_by_peer() - 1);
763 // Always reset the retransmission alarm when an ack comes in, since we now
764 // have a better estimate of the current rtt than when it was set.
765 SetRetransmissionAlarm();
768 void QuicConnection::ProcessStopWaitingFrame(
769 const QuicStopWaitingFrame& stop_waiting) {
770 largest_seen_packet_with_stop_waiting_ = last_header_.packet_sequence_number;
771 received_packet_manager_.UpdatePacketInformationSentByPeer(stop_waiting);
772 // Possibly close any FecGroups which are now irrelevant.
773 CloseFecGroupsBefore(stop_waiting.least_unacked + 1);
776 bool QuicConnection::OnStopWaitingFrame(const QuicStopWaitingFrame& frame) {
777 DCHECK(connected_);
779 if (last_header_.packet_sequence_number <=
780 largest_seen_packet_with_stop_waiting_) {
781 DVLOG(1) << ENDPOINT << "Received an old stop waiting frame: ignoring";
782 return true;
785 if (!ValidateStopWaitingFrame(frame)) {
786 SendConnectionClose(QUIC_INVALID_STOP_WAITING_DATA);
787 return false;
790 if (debug_visitor_ != nullptr) {
791 debug_visitor_->OnStopWaitingFrame(frame);
794 last_stop_waiting_frames_.push_back(frame);
795 return connected_;
798 bool QuicConnection::OnPingFrame(const QuicPingFrame& frame) {
799 DCHECK(connected_);
800 if (debug_visitor_ != nullptr) {
801 debug_visitor_->OnPingFrame(frame);
803 if (FLAGS_quic_process_frames_inline) {
804 should_last_packet_instigate_acks_ = true;
805 } else {
806 last_ping_frames_.push_back(frame);
808 return true;
811 bool QuicConnection::ValidateAckFrame(const QuicAckFrame& incoming_ack) {
812 if (incoming_ack.largest_observed > packet_generator_.sequence_number()) {
813 DLOG(ERROR) << ENDPOINT << "Peer's observed unsent packet:"
814 << incoming_ack.largest_observed << " vs "
815 << packet_generator_.sequence_number();
816 // We got an error for data we have not sent. Error out.
817 return false;
820 if (incoming_ack.largest_observed < sent_packet_manager_.largest_observed()) {
821 DLOG(ERROR) << ENDPOINT << "Peer's largest_observed packet decreased:"
822 << incoming_ack.largest_observed << " vs "
823 << sent_packet_manager_.largest_observed();
824 // A new ack has a diminished largest_observed value. Error out.
825 // If this was an old packet, we wouldn't even have checked.
826 return false;
829 if (!incoming_ack.missing_packets.empty() &&
830 *incoming_ack.missing_packets.rbegin() > incoming_ack.largest_observed) {
831 DLOG(ERROR) << ENDPOINT << "Peer sent missing packet: "
832 << *incoming_ack.missing_packets.rbegin()
833 << " which is greater than largest observed: "
834 << incoming_ack.largest_observed;
835 return false;
838 if (!incoming_ack.missing_packets.empty() &&
839 *incoming_ack.missing_packets.begin() <
840 sent_packet_manager_.least_packet_awaited_by_peer()) {
841 DLOG(ERROR) << ENDPOINT << "Peer sent missing packet: "
842 << *incoming_ack.missing_packets.begin()
843 << " which is smaller than least_packet_awaited_by_peer_: "
844 << sent_packet_manager_.least_packet_awaited_by_peer();
845 return false;
848 if (!sent_entropy_manager_.IsValidEntropy(
849 incoming_ack.largest_observed,
850 incoming_ack.missing_packets,
851 incoming_ack.entropy_hash)) {
852 DLOG(ERROR) << ENDPOINT << "Peer sent invalid entropy.";
853 return false;
856 for (QuicPacketSequenceNumber revived_packet : incoming_ack.revived_packets) {
857 if (!ContainsKey(incoming_ack.missing_packets, revived_packet)) {
858 DLOG(ERROR) << ENDPOINT
859 << "Peer specified revived packet which was not missing.";
860 return false;
863 return true;
866 bool QuicConnection::ValidateStopWaitingFrame(
867 const QuicStopWaitingFrame& stop_waiting) {
868 if (stop_waiting.least_unacked <
869 received_packet_manager_.peer_least_packet_awaiting_ack()) {
870 DLOG(ERROR) << ENDPOINT << "Peer's sent low least_unacked: "
871 << stop_waiting.least_unacked << " vs "
872 << received_packet_manager_.peer_least_packet_awaiting_ack();
873 // We never process old ack frames, so this number should only increase.
874 return false;
877 if (stop_waiting.least_unacked >
878 last_header_.packet_sequence_number) {
879 DLOG(ERROR) << ENDPOINT << "Peer sent least_unacked:"
880 << stop_waiting.least_unacked
881 << " greater than the enclosing packet sequence number:"
882 << last_header_.packet_sequence_number;
883 return false;
886 return true;
889 void QuicConnection::OnFecData(const QuicFecData& fec) {
890 DCHECK_EQ(IN_FEC_GROUP, last_header_.is_in_fec_group);
891 DCHECK_NE(0u, last_header_.fec_group);
892 QuicFecGroup* group = GetFecGroup();
893 if (group != nullptr) {
894 group->UpdateFec(last_decrypted_packet_level_,
895 last_header_.packet_sequence_number, fec);
899 bool QuicConnection::OnRstStreamFrame(const QuicRstStreamFrame& frame) {
900 DCHECK(connected_);
901 if (debug_visitor_ != nullptr) {
902 debug_visitor_->OnRstStreamFrame(frame);
904 DVLOG(1) << ENDPOINT << "Stream reset with error "
905 << QuicUtils::StreamErrorToString(frame.error_code);
906 if (FLAGS_quic_process_frames_inline) {
907 visitor_->OnRstStream(frame);
908 should_last_packet_instigate_acks_ = true;
909 } else {
910 last_rst_frames_.push_back(frame);
912 return connected_;
915 bool QuicConnection::OnConnectionCloseFrame(
916 const QuicConnectionCloseFrame& frame) {
917 DCHECK(connected_);
918 if (debug_visitor_ != nullptr) {
919 debug_visitor_->OnConnectionCloseFrame(frame);
921 DVLOG(1) << ENDPOINT << "Connection " << connection_id()
922 << " closed with error "
923 << QuicUtils::ErrorToString(frame.error_code)
924 << " " << frame.error_details;
925 if (FLAGS_quic_process_frames_inline) {
926 CloseConnection(frame.error_code, true);
927 } else {
928 last_close_frames_.push_back(frame);
930 return connected_;
933 bool QuicConnection::OnGoAwayFrame(const QuicGoAwayFrame& frame) {
934 DCHECK(connected_);
935 if (debug_visitor_ != nullptr) {
936 debug_visitor_->OnGoAwayFrame(frame);
938 DVLOG(1) << ENDPOINT << "Go away received with error "
939 << QuicUtils::ErrorToString(frame.error_code)
940 << " and reason:" << frame.reason_phrase;
942 goaway_received_ = true;
943 if (FLAGS_quic_process_frames_inline) {
944 visitor_->OnGoAway(frame);
945 should_last_packet_instigate_acks_ = true;
946 } else {
947 last_goaway_frames_.push_back(frame);
949 return connected_;
952 bool QuicConnection::OnWindowUpdateFrame(const QuicWindowUpdateFrame& frame) {
953 DCHECK(connected_);
954 if (debug_visitor_ != nullptr) {
955 debug_visitor_->OnWindowUpdateFrame(frame);
957 DVLOG(1) << ENDPOINT << "WindowUpdate received for stream: "
958 << frame.stream_id << " with byte offset: " << frame.byte_offset;
959 if (FLAGS_quic_process_frames_inline) {
960 visitor_->OnWindowUpdateFrame(frame);
961 should_last_packet_instigate_acks_ = true;
962 } else {
963 last_window_update_frames_.push_back(frame);
965 return connected_;
968 bool QuicConnection::OnBlockedFrame(const QuicBlockedFrame& frame) {
969 DCHECK(connected_);
970 if (debug_visitor_ != nullptr) {
971 debug_visitor_->OnBlockedFrame(frame);
973 DVLOG(1) << ENDPOINT << "Blocked frame received for stream: "
974 << frame.stream_id;
975 if (FLAGS_quic_process_frames_inline) {
976 visitor_->OnBlockedFrame(frame);
977 should_last_packet_instigate_acks_ = true;
978 } else {
979 last_blocked_frames_.push_back(frame);
981 return connected_;
984 void QuicConnection::OnPacketComplete() {
985 // Don't do anything if this packet closed the connection.
986 if (!connected_) {
987 ClearLastFrames();
988 return;
991 DVLOG(1) << ENDPOINT << (last_packet_revived_ ? "Revived" : "Got")
992 << " packet " << last_header_.packet_sequence_number << " with " //
993 << last_stream_frames_.size() << " stream frames, " //
994 << last_ack_frames_.size() << " acks, " //
995 << last_stop_waiting_frames_.size() << " stop_waiting, " //
996 << last_rst_frames_.size() << " rsts, " //
997 << last_goaway_frames_.size() << " goaways, " //
998 << last_window_update_frames_.size() << " window updates, " //
999 << last_blocked_frames_.size() << " blocked, " //
1000 << last_ping_frames_.size() << " pings, " //
1001 << last_close_frames_.size() << " closes " //
1002 << "for " << last_header_.public_header.connection_id;
1004 ++num_packets_received_since_last_ack_sent_;
1006 // Call MaybeQueueAck() before recording the received packet, since we want
1007 // to trigger an ack if the newly received packet was previously missing.
1008 MaybeQueueAck();
1010 // Record received or revived packet to populate ack info correctly before
1011 // processing stream frames, since the processing may result in a response
1012 // packet with a bundled ack.
1013 if (last_packet_revived_) {
1014 received_packet_manager_.RecordPacketRevived(
1015 last_header_.packet_sequence_number);
1016 } else {
1017 received_packet_manager_.RecordPacketReceived(
1018 last_size_, last_header_, time_of_last_received_packet_);
1021 if (!FLAGS_quic_process_frames_inline) {
1022 for (const QuicStreamFrame& frame : last_stream_frames_) {
1023 visitor_->OnStreamFrame(frame);
1024 stats_.stream_bytes_received += frame.data.size();
1025 if (!connected_) {
1026 return;
1030 // Process window updates, blocked, stream resets, acks, then stop waiting.
1031 for (const QuicWindowUpdateFrame& frame : last_window_update_frames_) {
1032 visitor_->OnWindowUpdateFrame(frame);
1033 if (!connected_) {
1034 return;
1037 for (const QuicBlockedFrame& frame : last_blocked_frames_) {
1038 visitor_->OnBlockedFrame(frame);
1039 if (!connected_) {
1040 return;
1043 for (const QuicGoAwayFrame& frame : last_goaway_frames_) {
1044 visitor_->OnGoAway(frame);
1045 if (!connected_) {
1046 return;
1049 for (const QuicRstStreamFrame& frame : last_rst_frames_) {
1050 visitor_->OnRstStream(frame);
1051 if (!connected_) {
1052 return;
1055 for (const QuicAckFrame& frame : last_ack_frames_) {
1056 ProcessAckFrame(frame);
1057 if (!connected_) {
1058 return;
1061 if (!last_close_frames_.empty()) {
1062 CloseConnection(last_close_frames_[0].error_code, true);
1063 DCHECK(!connected_);
1064 return;
1067 // Continue to process stop waiting frames later, because the packet needs
1068 // to be considered 'received' before the entropy can be updated.
1069 for (const QuicStopWaitingFrame& frame : last_stop_waiting_frames_) {
1070 ProcessStopWaitingFrame(frame);
1071 if (!connected_) {
1072 return;
1076 // If there are new missing packets to report, send an ack immediately.
1077 if (ShouldLastPacketInstigateAck() &&
1078 received_packet_manager_.HasNewMissingPackets()) {
1079 ack_queued_ = true;
1080 ack_alarm_->Cancel();
1083 UpdateStopWaitingCount();
1084 ClearLastFrames();
1085 MaybeCloseIfTooManyOutstandingPackets();
1088 void QuicConnection::MaybeQueueAck() {
1089 // If the last packet is an ack, don't ack it.
1090 if (!ShouldLastPacketInstigateAck()) {
1091 return;
1093 // If the incoming packet was missing, send an ack immediately.
1094 ack_queued_ = received_packet_manager_.IsMissing(
1095 last_header_.packet_sequence_number);
1097 if (!ack_queued_) {
1098 if (ack_alarm_->IsSet()) {
1099 ack_queued_ = true;
1100 } else {
1101 ack_alarm_->Set(
1102 clock_->ApproximateNow().Add(sent_packet_manager_.DelayedAckTime()));
1103 DVLOG(1) << "Ack timer set; next packet or timer will trigger ACK.";
1107 if (ack_queued_) {
1108 ack_alarm_->Cancel();
1112 void QuicConnection::ClearLastFrames() {
1113 if (FLAGS_quic_process_frames_inline) {
1114 should_last_packet_instigate_acks_ = false;
1115 last_stop_waiting_frames_.clear();
1116 return;
1118 last_stream_frames_.clear();
1119 last_ack_frames_.clear();
1120 last_stop_waiting_frames_.clear();
1121 last_rst_frames_.clear();
1122 last_goaway_frames_.clear();
1123 last_window_update_frames_.clear();
1124 last_blocked_frames_.clear();
1125 last_ping_frames_.clear();
1126 last_close_frames_.clear();
1129 void QuicConnection::MaybeCloseIfTooManyOutstandingPackets() {
1130 // This occurs if we don't discard old packets we've sent fast enough.
1131 // It's possible largest observed is less than least unacked.
1132 if (sent_packet_manager_.largest_observed() >
1133 (sent_packet_manager_.GetLeastUnacked() + kMaxTrackedPackets)) {
1134 SendConnectionCloseWithDetails(
1135 QUIC_TOO_MANY_OUTSTANDING_SENT_PACKETS,
1136 StringPrintf("More than %" PRIu64 " outstanding.", kMaxTrackedPackets));
1138 // This occurs if there are received packet gaps and the peer does not raise
1139 // the least unacked fast enough.
1140 if (received_packet_manager_.NumTrackedPackets() > kMaxTrackedPackets) {
1141 SendConnectionCloseWithDetails(
1142 QUIC_TOO_MANY_OUTSTANDING_RECEIVED_PACKETS,
1143 StringPrintf("More than %" PRIu64 " outstanding.", kMaxTrackedPackets));
1147 void QuicConnection::PopulateAckFrame(QuicAckFrame* ack) {
1148 received_packet_manager_.UpdateReceivedPacketInfo(ack,
1149 clock_->ApproximateNow());
1152 void QuicConnection::PopulateStopWaitingFrame(
1153 QuicStopWaitingFrame* stop_waiting) {
1154 stop_waiting->least_unacked = GetLeastUnacked();
1155 stop_waiting->entropy_hash = sent_entropy_manager_.GetCumulativeEntropy(
1156 stop_waiting->least_unacked - 1);
1159 bool QuicConnection::ShouldLastPacketInstigateAck() const {
1160 if (FLAGS_quic_process_frames_inline && should_last_packet_instigate_acks_) {
1161 return true;
1163 if (!FLAGS_quic_process_frames_inline) {
1164 if (!last_stream_frames_.empty() || !last_goaway_frames_.empty() ||
1165 !last_rst_frames_.empty() || !last_window_update_frames_.empty() ||
1166 !last_blocked_frames_.empty() || !last_ping_frames_.empty()) {
1167 return true;
1170 if (!last_ack_frames_.empty() && last_ack_frames_.back().is_truncated) {
1171 return true;
1174 // Always send an ack every 20 packets in order to allow the peer to discard
1175 // information from the SentPacketManager and provide an RTT measurement.
1176 if (num_packets_received_since_last_ack_sent_ >=
1177 kMaxPacketsReceivedBeforeAckSend) {
1178 return true;
1180 return false;
1183 void QuicConnection::UpdateStopWaitingCount() {
1184 if (last_ack_frames_.empty()) {
1185 return;
1188 // If the peer is still waiting for a packet that we are no longer planning to
1189 // send, send an ack to raise the high water mark.
1190 if (!last_ack_frames_.back().missing_packets.empty() &&
1191 GetLeastUnacked() > *last_ack_frames_.back().missing_packets.begin()) {
1192 ++stop_waiting_count_;
1193 } else {
1194 stop_waiting_count_ = 0;
1198 QuicPacketSequenceNumber QuicConnection::GetLeastUnacked() const {
1199 return sent_packet_manager_.GetLeastUnacked();
1202 void QuicConnection::MaybeSendInResponseToPacket() {
1203 if (!connected_) {
1204 return;
1206 ScopedPacketBundler bundler(this, ack_queued_ ? SEND_ACK : NO_ACK);
1208 // Now that we have received an ack, we might be able to send packets which
1209 // are queued locally, or drain streams which are blocked.
1210 WriteIfNotBlocked();
1213 void QuicConnection::SendVersionNegotiationPacket() {
1214 // TODO(alyssar): implement zero server state negotiation.
1215 pending_version_negotiation_packet_ = true;
1216 if (writer_->IsWriteBlocked()) {
1217 visitor_->OnWriteBlocked();
1218 return;
1220 DVLOG(1) << ENDPOINT << "Sending version negotiation packet: {"
1221 << QuicVersionVectorToString(framer_.supported_versions()) << "}";
1222 scoped_ptr<QuicEncryptedPacket> version_packet(
1223 packet_generator_.SerializeVersionNegotiationPacket(
1224 framer_.supported_versions()));
1225 WriteResult result = writer_->WritePacket(
1226 version_packet->data(), version_packet->length(),
1227 self_address().address(), peer_address());
1229 if (result.status == WRITE_STATUS_ERROR) {
1230 // We can't send an error as the socket is presumably borked.
1231 CloseConnection(QUIC_PACKET_WRITE_ERROR, false);
1232 return;
1234 if (result.status == WRITE_STATUS_BLOCKED) {
1235 visitor_->OnWriteBlocked();
1236 if (writer_->IsWriteBlockedDataBuffered()) {
1237 pending_version_negotiation_packet_ = false;
1239 return;
1242 pending_version_negotiation_packet_ = false;
1245 QuicConsumedData QuicConnection::SendStreamData(
1246 QuicStreamId id,
1247 const QuicIOVector& iov,
1248 QuicStreamOffset offset,
1249 bool fin,
1250 FecProtection fec_protection,
1251 QuicAckNotifier::DelegateInterface* delegate) {
1252 if (!fin && iov.total_length == 0) {
1253 LOG(DFATAL) << "Attempt to send empty stream frame";
1254 return QuicConsumedData(0, false);
1257 // Opportunistically bundle an ack with every outgoing packet.
1258 // Particularly, we want to bundle with handshake packets since we don't know
1259 // which decrypter will be used on an ack packet following a handshake
1260 // packet (a handshake packet from client to server could result in a REJ or a
1261 // SHLO from the server, leading to two different decrypters at the server.)
1263 // TODO(jri): Note that ConsumeData may cause a response packet to be sent.
1264 // We may end up sending stale ack information if there are undecryptable
1265 // packets hanging around and/or there are revivable packets which may get
1266 // handled after this packet is sent. Change ScopedPacketBundler to do the
1267 // right thing: check ack_queued_, and then check undecryptable packets and
1268 // also if there is possibility of revival. Only bundle an ack if there's no
1269 // processing left that may cause received_info_ to change.
1270 ScopedRetransmissionScheduler alarm_delayer(this);
1271 ScopedPacketBundler ack_bundler(this, BUNDLE_PENDING_ACK);
1272 return packet_generator_.ConsumeData(id, iov, offset, fin, fec_protection,
1273 delegate);
1276 void QuicConnection::SendRstStream(QuicStreamId id,
1277 QuicRstStreamErrorCode error,
1278 QuicStreamOffset bytes_written) {
1279 // Opportunistically bundle an ack with this outgoing packet.
1280 ScopedPacketBundler ack_bundler(this, BUNDLE_PENDING_ACK);
1281 packet_generator_.AddControlFrame(QuicFrame(new QuicRstStreamFrame(
1282 id, AdjustErrorForVersion(error, version()), bytes_written)));
1284 sent_packet_manager_.CancelRetransmissionsForStream(id);
1285 // Remove all queued packets which only contain data for the reset stream.
1286 QueuedPacketList::iterator packet_iterator = queued_packets_.begin();
1287 while (packet_iterator != queued_packets_.end()) {
1288 RetransmittableFrames* retransmittable_frames =
1289 packet_iterator->serialized_packet.retransmittable_frames;
1290 if (!retransmittable_frames) {
1291 ++packet_iterator;
1292 continue;
1294 retransmittable_frames->RemoveFramesForStream(id);
1295 if (!retransmittable_frames->frames().empty()) {
1296 ++packet_iterator;
1297 continue;
1299 delete packet_iterator->serialized_packet.retransmittable_frames;
1300 delete packet_iterator->serialized_packet.packet;
1301 packet_iterator->serialized_packet.retransmittable_frames = nullptr;
1302 packet_iterator->serialized_packet.packet = nullptr;
1303 packet_iterator = queued_packets_.erase(packet_iterator);
1307 void QuicConnection::SendWindowUpdate(QuicStreamId id,
1308 QuicStreamOffset byte_offset) {
1309 // Opportunistically bundle an ack with this outgoing packet.
1310 ScopedPacketBundler ack_bundler(this, BUNDLE_PENDING_ACK);
1311 packet_generator_.AddControlFrame(
1312 QuicFrame(new QuicWindowUpdateFrame(id, byte_offset)));
1315 void QuicConnection::SendBlocked(QuicStreamId id) {
1316 // Opportunistically bundle an ack with this outgoing packet.
1317 ScopedPacketBundler ack_bundler(this, BUNDLE_PENDING_ACK);
1318 packet_generator_.AddControlFrame(QuicFrame(new QuicBlockedFrame(id)));
1321 const QuicConnectionStats& QuicConnection::GetStats() {
1322 const RttStats* rtt_stats = sent_packet_manager_.GetRttStats();
1324 // Update rtt and estimated bandwidth.
1325 QuicTime::Delta min_rtt = rtt_stats->min_rtt();
1326 if (min_rtt.IsZero()) {
1327 // If min RTT has not been set, use initial RTT instead.
1328 min_rtt = QuicTime::Delta::FromMicroseconds(rtt_stats->initial_rtt_us());
1330 stats_.min_rtt_us = min_rtt.ToMicroseconds();
1332 QuicTime::Delta srtt = rtt_stats->smoothed_rtt();
1333 if (srtt.IsZero()) {
1334 // If SRTT has not been set, use initial RTT instead.
1335 srtt = QuicTime::Delta::FromMicroseconds(rtt_stats->initial_rtt_us());
1337 stats_.srtt_us = srtt.ToMicroseconds();
1339 stats_.estimated_bandwidth = sent_packet_manager_.BandwidthEstimate();
1340 stats_.max_packet_size = packet_generator_.GetMaxPacketLength();
1341 stats_.max_received_packet_size = largest_received_packet_size_;
1342 return stats_;
1345 void QuicConnection::ProcessUdpPacket(const IPEndPoint& self_address,
1346 const IPEndPoint& peer_address,
1347 const QuicEncryptedPacket& packet) {
1348 if (!connected_) {
1349 return;
1351 // TODO(rtenneti): Remove ScopedTracker below once crbug.com/462789 is fixed.
1352 tracked_objects::ScopedTracker tracking_profile(
1353 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1354 "462789 QuicConnection::ProcessUdpPacket"));
1355 if (debug_visitor_ != nullptr) {
1356 debug_visitor_->OnPacketReceived(self_address, peer_address, packet);
1358 last_size_ = packet.length();
1360 CheckForAddressMigration(self_address, peer_address);
1362 stats_.bytes_received += packet.length();
1363 ++stats_.packets_received;
1365 ScopedRetransmissionScheduler alarm_delayer(this);
1366 if (!framer_.ProcessPacket(packet)) {
1367 // If we are unable to decrypt this packet, it might be
1368 // because the CHLO or SHLO packet was lost.
1369 if (framer_.error() == QUIC_DECRYPTION_FAILURE) {
1370 if (encryption_level_ != ENCRYPTION_FORWARD_SECURE &&
1371 undecryptable_packets_.size() < max_undecryptable_packets_) {
1372 QueueUndecryptablePacket(packet);
1373 } else if (debug_visitor_ != nullptr) {
1374 debug_visitor_->OnUndecryptablePacket();
1377 DVLOG(1) << ENDPOINT << "Unable to process packet. Last packet processed: "
1378 << last_header_.packet_sequence_number;
1379 return;
1382 ++stats_.packets_processed;
1383 MaybeProcessUndecryptablePackets();
1384 MaybeProcessRevivedPacket();
1385 MaybeSendInResponseToPacket();
1386 SetPingAlarm();
1389 void QuicConnection::CheckForAddressMigration(
1390 const IPEndPoint& self_address, const IPEndPoint& peer_address) {
1391 peer_ip_changed_ = false;
1392 peer_port_changed_ = false;
1393 self_ip_changed_ = false;
1394 self_port_changed_ = false;
1396 if (peer_address_.address().empty()) {
1397 peer_address_ = peer_address;
1399 if (self_address_.address().empty()) {
1400 self_address_ = self_address;
1403 if (!peer_address.address().empty() && !peer_address_.address().empty()) {
1404 peer_ip_changed_ = (peer_address.address() != peer_address_.address());
1405 peer_port_changed_ = (peer_address.port() != peer_address_.port());
1407 // Store in case we want to migrate connection in ProcessValidatedPacket.
1408 migrating_peer_ip_ = peer_address.address();
1409 migrating_peer_port_ = peer_address.port();
1412 if (!self_address.address().empty() && !self_address_.address().empty()) {
1413 self_ip_changed_ = (self_address.address() != self_address_.address());
1414 self_port_changed_ = (self_address.port() != self_address_.port());
1418 void QuicConnection::OnCanWrite() {
1419 DCHECK(!writer_->IsWriteBlocked());
1421 WriteQueuedPackets();
1422 WritePendingRetransmissions();
1424 // Sending queued packets may have caused the socket to become write blocked,
1425 // or the congestion manager to prohibit sending. If we've sent everything
1426 // we had queued and we're still not blocked, let the visitor know it can
1427 // write more.
1428 if (!CanWrite(HAS_RETRANSMITTABLE_DATA)) {
1429 return;
1432 { // Limit the scope of the bundler. ACK inclusion happens elsewhere.
1433 ScopedPacketBundler bundler(this, NO_ACK);
1434 visitor_->OnCanWrite();
1437 // After the visitor writes, it may have caused the socket to become write
1438 // blocked or the congestion manager to prohibit sending, so check again.
1439 if (visitor_->WillingAndAbleToWrite() &&
1440 !resume_writes_alarm_->IsSet() &&
1441 CanWrite(HAS_RETRANSMITTABLE_DATA)) {
1442 // We're not write blocked, but some stream didn't write out all of its
1443 // bytes. Register for 'immediate' resumption so we'll keep writing after
1444 // other connections and events have had a chance to use the thread.
1445 resume_writes_alarm_->Set(clock_->ApproximateNow());
1449 void QuicConnection::WriteIfNotBlocked() {
1450 if (!writer_->IsWriteBlocked()) {
1451 OnCanWrite();
1455 bool QuicConnection::ProcessValidatedPacket() {
1456 if ((peer_ip_changed_ && !FLAGS_quic_allow_ip_migration) ||
1457 self_ip_changed_ || self_port_changed_) {
1458 SendConnectionCloseWithDetails(
1459 QUIC_ERROR_MIGRATING_ADDRESS,
1460 "Neither IP address migration, nor self port migration are supported.");
1461 return false;
1464 // TODO(fayang): Use peer_address_changed_ instead of peer_ip_changed_ and
1465 // peer_port_changed_ once FLAGS_quic_allow_ip_migration is deprecated.
1466 if (peer_ip_changed_ || peer_port_changed_) {
1467 IPEndPoint old_peer_address = peer_address_;
1468 peer_address_ = IPEndPoint(
1469 peer_ip_changed_ ? migrating_peer_ip_ : peer_address_.address(),
1470 peer_port_changed_ ? migrating_peer_port_ : peer_address_.port());
1472 DVLOG(1) << ENDPOINT << "Peer's ip:port changed from "
1473 << old_peer_address.ToString() << " to "
1474 << peer_address_.ToString() << ", migrating connection.";
1477 time_of_last_received_packet_ = clock_->Now();
1478 DVLOG(1) << ENDPOINT << "time of last received packet: "
1479 << time_of_last_received_packet_.ToDebuggingValue();
1481 if (last_size_ > largest_received_packet_size_) {
1482 largest_received_packet_size_ = last_size_;
1485 if (perspective_ == Perspective::IS_SERVER &&
1486 encryption_level_ == ENCRYPTION_NONE &&
1487 last_size_ > packet_generator_.GetMaxPacketLength()) {
1488 set_max_packet_length(last_size_);
1490 return true;
1493 void QuicConnection::WriteQueuedPackets() {
1494 DCHECK(!writer_->IsWriteBlocked());
1496 if (pending_version_negotiation_packet_) {
1497 SendVersionNegotiationPacket();
1500 QueuedPacketList::iterator packet_iterator = queued_packets_.begin();
1501 while (packet_iterator != queued_packets_.end() &&
1502 WritePacket(&(*packet_iterator))) {
1503 packet_iterator = queued_packets_.erase(packet_iterator);
1507 void QuicConnection::WritePendingRetransmissions() {
1508 // Keep writing as long as there's a pending retransmission which can be
1509 // written.
1510 while (sent_packet_manager_.HasPendingRetransmissions()) {
1511 const QuicSentPacketManager::PendingRetransmission pending =
1512 sent_packet_manager_.NextPendingRetransmission();
1513 if (!CanWrite(HAS_RETRANSMITTABLE_DATA)) {
1514 break;
1517 // Re-packetize the frames with a new sequence number for retransmission.
1518 // Retransmitted data packets do not use FEC, even when it's enabled.
1519 // Retransmitted packets use the same sequence number length as the
1520 // original.
1521 // Flush the packet generator before making a new packet.
1522 // TODO(ianswett): Implement ReserializeAllFrames as a separate path that
1523 // does not require the creator to be flushed.
1524 packet_generator_.FlushAllQueuedFrames();
1525 char buffer[kMaxPacketSize];
1526 SerializedPacket serialized_packet = packet_generator_.ReserializeAllFrames(
1527 pending.retransmittable_frames, pending.sequence_number_length, buffer,
1528 kMaxPacketSize);
1529 if (serialized_packet.packet == nullptr) {
1530 // We failed to serialize the packet, so close the connection.
1531 // CloseConnection does not send close packet, so no infinite loop here.
1532 CloseConnection(QUIC_ENCRYPTION_FAILURE, false);
1533 return;
1536 DVLOG(1) << ENDPOINT << "Retransmitting " << pending.sequence_number
1537 << " as " << serialized_packet.sequence_number;
1538 SendOrQueuePacket(
1539 QueuedPacket(serialized_packet,
1540 pending.retransmittable_frames.encryption_level(),
1541 pending.transmission_type,
1542 pending.sequence_number));
1546 void QuicConnection::RetransmitUnackedPackets(
1547 TransmissionType retransmission_type) {
1548 sent_packet_manager_.RetransmitUnackedPackets(retransmission_type);
1550 WriteIfNotBlocked();
1553 void QuicConnection::NeuterUnencryptedPackets() {
1554 sent_packet_manager_.NeuterUnencryptedPackets();
1555 // This may have changed the retransmission timer, so re-arm it.
1556 SetRetransmissionAlarm();
1559 bool QuicConnection::ShouldGeneratePacket(
1560 HasRetransmittableData retransmittable,
1561 IsHandshake handshake) {
1562 // We should serialize handshake packets immediately to ensure that they
1563 // end up sent at the right encryption level.
1564 if (handshake == IS_HANDSHAKE) {
1565 return true;
1568 return CanWrite(retransmittable);
1571 bool QuicConnection::CanWrite(HasRetransmittableData retransmittable) {
1572 if (!connected_) {
1573 return false;
1576 if (writer_->IsWriteBlocked()) {
1577 visitor_->OnWriteBlocked();
1578 return false;
1581 QuicTime now = clock_->Now();
1582 QuicTime::Delta delay = sent_packet_manager_.TimeUntilSend(
1583 now, retransmittable);
1584 if (delay.IsInfinite()) {
1585 send_alarm_->Cancel();
1586 return false;
1589 // If the scheduler requires a delay, then we can not send this packet now.
1590 if (!delay.IsZero()) {
1591 send_alarm_->Update(now.Add(delay), QuicTime::Delta::FromMilliseconds(1));
1592 DVLOG(1) << ENDPOINT << "Delaying sending " << delay.ToMilliseconds()
1593 << "ms";
1594 return false;
1596 send_alarm_->Cancel();
1597 return true;
1600 bool QuicConnection::WritePacket(QueuedPacket* packet) {
1601 if (!WritePacketInner(packet)) {
1602 return false;
1604 delete packet->serialized_packet.retransmittable_frames;
1605 delete packet->serialized_packet.packet;
1606 packet->serialized_packet.retransmittable_frames = nullptr;
1607 packet->serialized_packet.packet = nullptr;
1608 return true;
1611 bool QuicConnection::WritePacketInner(QueuedPacket* packet) {
1612 if (ShouldDiscardPacket(*packet)) {
1613 ++stats_.packets_discarded;
1614 return true;
1616 // Connection close packets are encrypted and saved, so don't exit early.
1617 const bool is_connection_close = IsConnectionClose(*packet);
1618 if (writer_->IsWriteBlocked() && !is_connection_close) {
1619 return false;
1622 QuicPacketSequenceNumber sequence_number =
1623 packet->serialized_packet.sequence_number;
1624 DCHECK_LE(sequence_number_of_last_sent_packet_, sequence_number);
1625 sequence_number_of_last_sent_packet_ = sequence_number;
1627 QuicEncryptedPacket* encrypted = packet->serialized_packet.packet;
1628 // Connection close packets are eventually owned by TimeWaitListManager.
1629 // Others are deleted at the end of this call.
1630 if (is_connection_close) {
1631 DCHECK(connection_close_packet_.get() == nullptr);
1632 // Clone the packet so it's owned in the future.
1633 connection_close_packet_.reset(encrypted->Clone());
1634 // This assures we won't try to write *forced* packets when blocked.
1635 // Return true to stop processing.
1636 if (writer_->IsWriteBlocked()) {
1637 visitor_->OnWriteBlocked();
1638 return true;
1642 if (!FLAGS_quic_allow_oversized_packets_for_test) {
1643 DCHECK_LE(encrypted->length(), kMaxPacketSize);
1645 DCHECK_LE(encrypted->length(), packet_generator_.GetMaxPacketLength());
1646 DVLOG(1) << ENDPOINT << "Sending packet " << sequence_number << " : "
1647 << (packet->serialized_packet.is_fec_packet
1648 ? "FEC "
1649 : (IsRetransmittable(*packet) == HAS_RETRANSMITTABLE_DATA
1650 ? "data bearing "
1651 : " ack only ")) << ", encryption level: "
1652 << QuicUtils::EncryptionLevelToString(packet->encryption_level)
1653 << ", encrypted length:" << encrypted->length();
1654 DVLOG(2) << ENDPOINT << "packet(" << sequence_number << "): " << std::endl
1655 << QuicUtils::StringToHexASCIIDump(encrypted->AsStringPiece());
1657 // Measure the RTT from before the write begins to avoid underestimating the
1658 // min_rtt_, especially in cases where the thread blocks or gets swapped out
1659 // during the WritePacket below.
1660 QuicTime packet_send_time = clock_->Now();
1661 WriteResult result = writer_->WritePacket(encrypted->data(),
1662 encrypted->length(),
1663 self_address().address(),
1664 peer_address());
1665 if (result.error_code == ERR_IO_PENDING) {
1666 DCHECK_EQ(WRITE_STATUS_BLOCKED, result.status);
1669 if (result.status == WRITE_STATUS_BLOCKED) {
1670 visitor_->OnWriteBlocked();
1671 // If the socket buffers the the data, then the packet should not
1672 // be queued and sent again, which would result in an unnecessary
1673 // duplicate packet being sent. The helper must call OnCanWrite
1674 // when the write completes, and OnWriteError if an error occurs.
1675 if (!writer_->IsWriteBlockedDataBuffered()) {
1676 return false;
1679 if (result.status != WRITE_STATUS_ERROR && debug_visitor_ != nullptr) {
1680 // Pass the write result to the visitor.
1681 debug_visitor_->OnPacketSent(packet->serialized_packet,
1682 packet->original_sequence_number,
1683 packet->encryption_level,
1684 packet->transmission_type,
1685 *encrypted,
1686 packet_send_time);
1688 if (packet->transmission_type == NOT_RETRANSMISSION) {
1689 time_of_last_sent_new_packet_ = packet_send_time;
1691 SetPingAlarm();
1692 MaybeSetFecAlarm(sequence_number);
1693 MaybeSetMtuAlarm();
1694 DVLOG(1) << ENDPOINT << "time we began writing last sent packet: "
1695 << packet_send_time.ToDebuggingValue();
1697 // TODO(ianswett): Change the sequence number length and other packet creator
1698 // options by a more explicit API than setting a struct value directly,
1699 // perhaps via the NetworkChangeVisitor.
1700 packet_generator_.UpdateSequenceNumberLength(
1701 sent_packet_manager_.least_packet_awaited_by_peer(),
1702 sent_packet_manager_.EstimateMaxPacketsInFlight(max_packet_length()));
1704 bool reset_retransmission_alarm = sent_packet_manager_.OnPacketSent(
1705 &packet->serialized_packet,
1706 packet->original_sequence_number,
1707 packet_send_time,
1708 encrypted->length(),
1709 packet->transmission_type,
1710 IsRetransmittable(*packet));
1712 if (reset_retransmission_alarm || !retransmission_alarm_->IsSet()) {
1713 SetRetransmissionAlarm();
1716 stats_.bytes_sent += result.bytes_written;
1717 ++stats_.packets_sent;
1718 if (packet->transmission_type != NOT_RETRANSMISSION) {
1719 stats_.bytes_retransmitted += result.bytes_written;
1720 ++stats_.packets_retransmitted;
1723 if (result.status == WRITE_STATUS_ERROR) {
1724 OnWriteError(result.error_code);
1725 DLOG(ERROR) << ENDPOINT << "failed writing " << encrypted->length()
1726 << " bytes "
1727 << " from host " << self_address().ToStringWithoutPort()
1728 << " to address " << peer_address().ToString();
1729 return false;
1732 return true;
1735 bool QuicConnection::ShouldDiscardPacket(const QueuedPacket& packet) {
1736 if (!connected_) {
1737 DVLOG(1) << ENDPOINT
1738 << "Not sending packet as connection is disconnected.";
1739 return true;
1742 QuicPacketSequenceNumber sequence_number =
1743 packet.serialized_packet.sequence_number;
1744 if (encryption_level_ == ENCRYPTION_FORWARD_SECURE &&
1745 packet.encryption_level == ENCRYPTION_NONE) {
1746 // Drop packets that are NULL encrypted since the peer won't accept them
1747 // anymore.
1748 DVLOG(1) << ENDPOINT << "Dropping NULL encrypted packet: "
1749 << sequence_number << " since the connection is forward secure.";
1750 return true;
1753 // If a retransmission has been acked before sending, don't send it.
1754 // This occurs if a packet gets serialized, queued, then discarded.
1755 if (packet.transmission_type != NOT_RETRANSMISSION &&
1756 (!sent_packet_manager_.IsUnacked(packet.original_sequence_number) ||
1757 !sent_packet_manager_.HasRetransmittableFrames(
1758 packet.original_sequence_number))) {
1759 DVLOG(1) << ENDPOINT << "Dropping unacked packet: " << sequence_number
1760 << " A previous transmission was acked while write blocked.";
1761 return true;
1764 return false;
1767 void QuicConnection::OnWriteError(int error_code) {
1768 DVLOG(1) << ENDPOINT << "Write failed with error: " << error_code
1769 << " (" << ErrorToString(error_code) << ")";
1770 // We can't send an error as the socket is presumably borked.
1771 CloseConnection(QUIC_PACKET_WRITE_ERROR, false);
1774 void QuicConnection::OnSerializedPacket(
1775 const SerializedPacket& serialized_packet) {
1776 if (serialized_packet.packet == nullptr) {
1777 // We failed to serialize the packet, so close the connection.
1778 // CloseConnection does not send close packet, so no infinite loop here.
1779 CloseConnection(QUIC_ENCRYPTION_FAILURE, false);
1780 return;
1782 sent_packet_manager_.OnSerializedPacket(serialized_packet);
1783 if (serialized_packet.is_fec_packet && fec_alarm_->IsSet()) {
1784 // If an FEC packet is serialized with the FEC alarm set, cancel the alarm.
1785 fec_alarm_->Cancel();
1787 SendOrQueuePacket(QueuedPacket(serialized_packet, encryption_level_));
1790 void QuicConnection::OnResetFecGroup() {
1791 if (!fec_alarm_->IsSet()) {
1792 return;
1794 // If an FEC Group is closed with the FEC alarm set, cancel the alarm.
1795 fec_alarm_->Cancel();
1798 void QuicConnection::OnCongestionWindowChange() {
1799 packet_generator_.OnCongestionWindowChange(
1800 sent_packet_manager_.EstimateMaxPacketsInFlight(max_packet_length()));
1801 visitor_->OnCongestionWindowChange(clock_->ApproximateNow());
1804 void QuicConnection::OnRttChange() {
1805 // Uses the connection's smoothed RTT. If zero, uses initial_rtt.
1806 QuicTime::Delta rtt = sent_packet_manager_.GetRttStats()->smoothed_rtt();
1807 if (rtt.IsZero()) {
1808 rtt = QuicTime::Delta::FromMicroseconds(
1809 sent_packet_manager_.GetRttStats()->initial_rtt_us());
1811 packet_generator_.OnRttChange(rtt);
1814 void QuicConnection::OnHandshakeComplete() {
1815 sent_packet_manager_.SetHandshakeConfirmed();
1816 // The client should immediately ack the SHLO to confirm the handshake is
1817 // complete with the server.
1818 if (perspective_ == Perspective::IS_CLIENT && !ack_queued_) {
1819 ack_alarm_->Cancel();
1820 ack_alarm_->Set(clock_->ApproximateNow());
1824 void QuicConnection::SendOrQueuePacket(QueuedPacket packet) {
1825 // The caller of this function is responsible for checking CanWrite().
1826 if (packet.serialized_packet.packet == nullptr) {
1827 LOG(DFATAL)
1828 << "packet.serialized_packet.packet == nullptr in to SendOrQueuePacket";
1829 return;
1832 sent_entropy_manager_.RecordPacketEntropyHash(
1833 packet.serialized_packet.sequence_number,
1834 packet.serialized_packet.entropy_hash);
1835 if (!WritePacket(&packet)) {
1836 // Take ownership of the underlying encrypted packet.
1837 if (!packet.serialized_packet.packet->owns_buffer()) {
1838 scoped_ptr<QuicEncryptedPacket> encrypted_deleter(
1839 packet.serialized_packet.packet);
1840 packet.serialized_packet.packet =
1841 packet.serialized_packet.packet->Clone();
1843 queued_packets_.push_back(packet);
1846 // If a forward-secure encrypter is available but is not being used and the
1847 // next sequence number is the first packet which requires
1848 // forward security, start using the forward-secure encrypter.
1849 if (encryption_level_ != ENCRYPTION_FORWARD_SECURE &&
1850 has_forward_secure_encrypter_ &&
1851 packet.serialized_packet.sequence_number >=
1852 first_required_forward_secure_packet_ - 1) {
1853 SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
1857 void QuicConnection::SendPing() {
1858 if (retransmission_alarm_->IsSet()) {
1859 return;
1861 packet_generator_.AddControlFrame(QuicFrame(new QuicPingFrame));
1864 void QuicConnection::SendAck() {
1865 ack_alarm_->Cancel();
1866 ack_queued_ = false;
1867 stop_waiting_count_ = 0;
1868 num_packets_received_since_last_ack_sent_ = 0;
1870 packet_generator_.SetShouldSendAck(true);
1873 void QuicConnection::OnRetransmissionTimeout() {
1874 if (!sent_packet_manager_.HasUnackedPackets()) {
1875 return;
1878 sent_packet_manager_.OnRetransmissionTimeout();
1879 WriteIfNotBlocked();
1881 // A write failure can result in the connection being closed, don't attempt to
1882 // write further packets, or to set alarms.
1883 if (!connected_) {
1884 return;
1887 // In the TLP case, the SentPacketManager gives the connection the opportunity
1888 // to send new data before retransmitting.
1889 if (sent_packet_manager_.MaybeRetransmitTailLossProbe()) {
1890 // Send the pending retransmission now that it's been queued.
1891 WriteIfNotBlocked();
1894 // Ensure the retransmission alarm is always set if there are unacked packets
1895 // and nothing waiting to be sent.
1896 // This happens if the loss algorithm invokes a timer based loss, but the
1897 // packet doesn't need to be retransmitted.
1898 if (!HasQueuedData() && !retransmission_alarm_->IsSet()) {
1899 SetRetransmissionAlarm();
1903 void QuicConnection::SetEncrypter(EncryptionLevel level,
1904 QuicEncrypter* encrypter) {
1905 packet_generator_.SetEncrypter(level, encrypter);
1906 if (level == ENCRYPTION_FORWARD_SECURE) {
1907 has_forward_secure_encrypter_ = true;
1908 first_required_forward_secure_packet_ =
1909 sequence_number_of_last_sent_packet_ +
1910 // 3 times the current congestion window (in slow start) should cover
1911 // about two full round trips worth of packets, which should be
1912 // sufficient.
1913 3 * sent_packet_manager_.EstimateMaxPacketsInFlight(
1914 max_packet_length());
1918 void QuicConnection::SetDefaultEncryptionLevel(EncryptionLevel level) {
1919 encryption_level_ = level;
1920 packet_generator_.set_encryption_level(level);
1923 void QuicConnection::SetDecrypter(EncryptionLevel level,
1924 QuicDecrypter* decrypter) {
1925 framer_.SetDecrypter(level, decrypter);
1928 void QuicConnection::SetAlternativeDecrypter(EncryptionLevel level,
1929 QuicDecrypter* decrypter,
1930 bool latch_once_used) {
1931 framer_.SetAlternativeDecrypter(level, decrypter, latch_once_used);
1934 const QuicDecrypter* QuicConnection::decrypter() const {
1935 return framer_.decrypter();
1938 const QuicDecrypter* QuicConnection::alternative_decrypter() const {
1939 return framer_.alternative_decrypter();
1942 void QuicConnection::QueueUndecryptablePacket(
1943 const QuicEncryptedPacket& packet) {
1944 DVLOG(1) << ENDPOINT << "Queueing undecryptable packet.";
1945 undecryptable_packets_.push_back(packet.Clone());
1948 void QuicConnection::MaybeProcessUndecryptablePackets() {
1949 if (undecryptable_packets_.empty() || encryption_level_ == ENCRYPTION_NONE) {
1950 return;
1953 while (connected_ && !undecryptable_packets_.empty()) {
1954 DVLOG(1) << ENDPOINT << "Attempting to process undecryptable packet";
1955 QuicEncryptedPacket* packet = undecryptable_packets_.front();
1956 if (!framer_.ProcessPacket(*packet) &&
1957 framer_.error() == QUIC_DECRYPTION_FAILURE) {
1958 DVLOG(1) << ENDPOINT << "Unable to process undecryptable packet...";
1959 break;
1961 DVLOG(1) << ENDPOINT << "Processed undecryptable packet!";
1962 ++stats_.packets_processed;
1963 delete packet;
1964 undecryptable_packets_.pop_front();
1967 // Once forward secure encryption is in use, there will be no
1968 // new keys installed and hence any undecryptable packets will
1969 // never be able to be decrypted.
1970 if (encryption_level_ == ENCRYPTION_FORWARD_SECURE) {
1971 if (debug_visitor_ != nullptr) {
1972 // TODO(rtenneti): perhaps more efficient to pass the number of
1973 // undecryptable packets as the argument to OnUndecryptablePacket so that
1974 // we just need to call OnUndecryptablePacket once?
1975 for (size_t i = 0; i < undecryptable_packets_.size(); ++i) {
1976 debug_visitor_->OnUndecryptablePacket();
1979 STLDeleteElements(&undecryptable_packets_);
1983 void QuicConnection::MaybeProcessRevivedPacket() {
1984 QuicFecGroup* group = GetFecGroup();
1985 if (!connected_ || group == nullptr || !group->CanRevive()) {
1986 return;
1988 QuicPacketHeader revived_header;
1989 char revived_payload[kMaxPacketSize];
1990 size_t len = group->Revive(&revived_header, revived_payload, kMaxPacketSize);
1991 revived_header.public_header.connection_id = connection_id_;
1992 revived_header.public_header.connection_id_length =
1993 last_header_.public_header.connection_id_length;
1994 revived_header.public_header.version_flag = false;
1995 revived_header.public_header.reset_flag = false;
1996 revived_header.public_header.sequence_number_length =
1997 last_header_.public_header.sequence_number_length;
1998 revived_header.fec_flag = false;
1999 revived_header.is_in_fec_group = NOT_IN_FEC_GROUP;
2000 revived_header.fec_group = 0;
2001 group_map_.erase(last_header_.fec_group);
2002 last_decrypted_packet_level_ = group->effective_encryption_level();
2003 DCHECK_LT(last_decrypted_packet_level_, NUM_ENCRYPTION_LEVELS);
2004 delete group;
2006 last_packet_revived_ = true;
2007 if (debug_visitor_ != nullptr) {
2008 debug_visitor_->OnRevivedPacket(revived_header,
2009 StringPiece(revived_payload, len));
2012 ++stats_.packets_revived;
2013 framer_.ProcessRevivedPacket(&revived_header,
2014 StringPiece(revived_payload, len));
2017 QuicFecGroup* QuicConnection::GetFecGroup() {
2018 QuicFecGroupNumber fec_group_num = last_header_.fec_group;
2019 if (fec_group_num == 0) {
2020 return nullptr;
2022 if (!ContainsKey(group_map_, fec_group_num)) {
2023 if (group_map_.size() >= kMaxFecGroups) { // Too many groups
2024 if (fec_group_num < group_map_.begin()->first) {
2025 // The group being requested is a group we've seen before and deleted.
2026 // Don't recreate it.
2027 return nullptr;
2029 // Clear the lowest group number.
2030 delete group_map_.begin()->second;
2031 group_map_.erase(group_map_.begin());
2033 group_map_[fec_group_num] = new QuicFecGroup();
2035 return group_map_[fec_group_num];
2038 void QuicConnection::SendConnectionClose(QuicErrorCode error) {
2039 SendConnectionCloseWithDetails(error, string());
2042 void QuicConnection::SendConnectionCloseWithDetails(QuicErrorCode error,
2043 const string& details) {
2044 // If we're write blocked, WritePacket() will not send, but will capture the
2045 // serialized packet.
2046 SendConnectionClosePacket(error, details);
2047 CloseConnection(error, false);
2050 void QuicConnection::SendConnectionClosePacket(QuicErrorCode error,
2051 const string& details) {
2052 DVLOG(1) << ENDPOINT << "Force closing " << connection_id()
2053 << " with error " << QuicUtils::ErrorToString(error)
2054 << " (" << error << ") " << details;
2055 // Don't send explicit connection close packets for timeouts.
2056 // This is particularly important on mobile, where connections are short.
2057 if (silent_close_enabled_ &&
2058 error == QuicErrorCode::QUIC_CONNECTION_TIMED_OUT) {
2059 return;
2061 ScopedPacketBundler ack_bundler(this, SEND_ACK);
2062 QuicConnectionCloseFrame* frame = new QuicConnectionCloseFrame();
2063 frame->error_code = error;
2064 frame->error_details = details;
2065 packet_generator_.AddControlFrame(QuicFrame(frame));
2066 packet_generator_.FlushAllQueuedFrames();
2069 void QuicConnection::CloseConnection(QuicErrorCode error, bool from_peer) {
2070 if (!connected_) {
2071 DVLOG(1) << "Connection is already closed.";
2072 return;
2074 connected_ = false;
2075 if (debug_visitor_ != nullptr) {
2076 debug_visitor_->OnConnectionClosed(error, from_peer);
2078 DCHECK(visitor_ != nullptr);
2079 visitor_->OnConnectionClosed(error, from_peer);
2080 // Cancel the alarms so they don't trigger any action now that the
2081 // connection is closed.
2082 ack_alarm_->Cancel();
2083 ping_alarm_->Cancel();
2084 fec_alarm_->Cancel();
2085 resume_writes_alarm_->Cancel();
2086 retransmission_alarm_->Cancel();
2087 send_alarm_->Cancel();
2088 timeout_alarm_->Cancel();
2089 mtu_discovery_alarm_->Cancel();
2092 void QuicConnection::SendGoAway(QuicErrorCode error,
2093 QuicStreamId last_good_stream_id,
2094 const string& reason) {
2095 if (goaway_sent_) {
2096 return;
2098 goaway_sent_ = true;
2100 DVLOG(1) << ENDPOINT << "Going away with error "
2101 << QuicUtils::ErrorToString(error)
2102 << " (" << error << ")";
2104 // Opportunistically bundle an ack with this outgoing packet.
2105 ScopedPacketBundler ack_bundler(this, BUNDLE_PENDING_ACK);
2106 packet_generator_.AddControlFrame(
2107 QuicFrame(new QuicGoAwayFrame(error, last_good_stream_id, reason)));
2110 void QuicConnection::CloseFecGroupsBefore(
2111 QuicPacketSequenceNumber sequence_number) {
2112 FecGroupMap::iterator it = group_map_.begin();
2113 while (it != group_map_.end()) {
2114 // If this is the current group or the group doesn't protect this packet
2115 // we can ignore it.
2116 if (last_header_.fec_group == it->first ||
2117 !it->second->ProtectsPacketsBefore(sequence_number)) {
2118 ++it;
2119 continue;
2121 QuicFecGroup* fec_group = it->second;
2122 DCHECK(!fec_group->CanRevive());
2123 FecGroupMap::iterator next = it;
2124 ++next;
2125 group_map_.erase(it);
2126 delete fec_group;
2127 it = next;
2131 QuicByteCount QuicConnection::max_packet_length() const {
2132 return packet_generator_.GetMaxPacketLength();
2135 void QuicConnection::set_max_packet_length(QuicByteCount length) {
2136 return packet_generator_.SetMaxPacketLength(length, /*force=*/false);
2139 bool QuicConnection::HasQueuedData() const {
2140 return pending_version_negotiation_packet_ ||
2141 !queued_packets_.empty() || packet_generator_.HasQueuedFrames();
2144 bool QuicConnection::CanWriteStreamData() {
2145 // Don't write stream data if there are negotiation or queued data packets
2146 // to send. Otherwise, continue and bundle as many frames as possible.
2147 if (pending_version_negotiation_packet_ || !queued_packets_.empty()) {
2148 return false;
2151 IsHandshake pending_handshake = visitor_->HasPendingHandshake() ?
2152 IS_HANDSHAKE : NOT_HANDSHAKE;
2153 // Sending queued packets may have caused the socket to become write blocked,
2154 // or the congestion manager to prohibit sending. If we've sent everything
2155 // we had queued and we're still not blocked, let the visitor know it can
2156 // write more.
2157 return ShouldGeneratePacket(HAS_RETRANSMITTABLE_DATA, pending_handshake);
2160 void QuicConnection::SetNetworkTimeouts(QuicTime::Delta overall_timeout,
2161 QuicTime::Delta idle_timeout) {
2162 LOG_IF(DFATAL, idle_timeout > overall_timeout)
2163 << "idle_timeout:" << idle_timeout.ToMilliseconds()
2164 << " overall_timeout:" << overall_timeout.ToMilliseconds();
2165 // Adjust the idle timeout on client and server to prevent clients from
2166 // sending requests to servers which have already closed the connection.
2167 if (perspective_ == Perspective::IS_SERVER) {
2168 idle_timeout = idle_timeout.Add(QuicTime::Delta::FromSeconds(3));
2169 } else if (idle_timeout > QuicTime::Delta::FromSeconds(1)) {
2170 idle_timeout = idle_timeout.Subtract(QuicTime::Delta::FromSeconds(1));
2172 overall_connection_timeout_ = overall_timeout;
2173 idle_network_timeout_ = idle_timeout;
2175 SetTimeoutAlarm();
2178 void QuicConnection::CheckForTimeout() {
2179 QuicTime now = clock_->ApproximateNow();
2180 QuicTime time_of_last_packet = max(time_of_last_received_packet_,
2181 time_of_last_sent_new_packet_);
2183 // |delta| can be < 0 as |now| is approximate time but |time_of_last_packet|
2184 // is accurate time. However, this should not change the behavior of
2185 // timeout handling.
2186 QuicTime::Delta idle_duration = now.Subtract(time_of_last_packet);
2187 DVLOG(1) << ENDPOINT << "last packet "
2188 << time_of_last_packet.ToDebuggingValue()
2189 << " now:" << now.ToDebuggingValue()
2190 << " idle_duration:" << idle_duration.ToMicroseconds()
2191 << " idle_network_timeout: "
2192 << idle_network_timeout_.ToMicroseconds();
2193 if (idle_duration >= idle_network_timeout_) {
2194 DVLOG(1) << ENDPOINT << "Connection timedout due to no network activity.";
2195 SendConnectionClose(QUIC_CONNECTION_TIMED_OUT);
2196 return;
2199 if (!overall_connection_timeout_.IsInfinite()) {
2200 QuicTime::Delta connected_duration =
2201 now.Subtract(stats_.connection_creation_time);
2202 DVLOG(1) << ENDPOINT << "connection time: "
2203 << connected_duration.ToMicroseconds() << " overall timeout: "
2204 << overall_connection_timeout_.ToMicroseconds();
2205 if (connected_duration >= overall_connection_timeout_) {
2206 DVLOG(1) << ENDPOINT <<
2207 "Connection timedout due to overall connection timeout.";
2208 SendConnectionClose(QUIC_CONNECTION_OVERALL_TIMED_OUT);
2209 return;
2213 SetTimeoutAlarm();
2216 void QuicConnection::SetTimeoutAlarm() {
2217 QuicTime time_of_last_packet = max(time_of_last_received_packet_,
2218 time_of_last_sent_new_packet_);
2220 QuicTime deadline = time_of_last_packet.Add(idle_network_timeout_);
2221 if (!overall_connection_timeout_.IsInfinite()) {
2222 deadline = min(deadline,
2223 stats_.connection_creation_time.Add(
2224 overall_connection_timeout_));
2227 timeout_alarm_->Cancel();
2228 timeout_alarm_->Set(deadline);
2231 void QuicConnection::SetPingAlarm() {
2232 if (perspective_ == Perspective::IS_SERVER) {
2233 // Only clients send pings.
2234 return;
2236 if (!visitor_->HasOpenDynamicStreams()) {
2237 ping_alarm_->Cancel();
2238 // Don't send a ping unless there are open streams.
2239 return;
2241 QuicTime::Delta ping_timeout = QuicTime::Delta::FromSeconds(kPingTimeoutSecs);
2242 ping_alarm_->Update(clock_->ApproximateNow().Add(ping_timeout),
2243 QuicTime::Delta::FromSeconds(1));
2246 void QuicConnection::SetRetransmissionAlarm() {
2247 if (delay_setting_retransmission_alarm_) {
2248 pending_retransmission_alarm_ = true;
2249 return;
2251 QuicTime retransmission_time = sent_packet_manager_.GetRetransmissionTime();
2252 retransmission_alarm_->Update(retransmission_time,
2253 QuicTime::Delta::FromMilliseconds(1));
2256 void QuicConnection::MaybeSetMtuAlarm() {
2257 if (!FLAGS_quic_do_path_mtu_discovery) {
2258 return;
2261 // Do not set the alarm if the target size is less than the current size.
2262 // This covers the case when |mtu_discovery_target_| is at its default value,
2263 // zero.
2264 if (mtu_discovery_target_ <= max_packet_length()) {
2265 return;
2268 if (mtu_probe_count_ >= kMtuDiscoveryAttempts) {
2269 return;
2272 if (mtu_discovery_alarm_->IsSet()) {
2273 return;
2276 if (sequence_number_of_last_sent_packet_ >= next_mtu_probe_at_) {
2277 // Use an alarm to send the MTU probe to ensure that no ScopedPacketBundlers
2278 // are active.
2279 mtu_discovery_alarm_->Set(clock_->ApproximateNow());
2283 QuicConnection::ScopedPacketBundler::ScopedPacketBundler(
2284 QuicConnection* connection,
2285 AckBundling send_ack)
2286 : connection_(connection),
2287 already_in_batch_mode_(connection != nullptr &&
2288 connection->packet_generator_.InBatchMode()) {
2289 if (connection_ == nullptr) {
2290 return;
2292 // Move generator into batch mode. If caller wants us to include an ack,
2293 // check the delayed-ack timer to see if there's ack info to be sent.
2294 if (!already_in_batch_mode_) {
2295 DVLOG(1) << "Entering Batch Mode.";
2296 connection_->packet_generator_.StartBatchOperations();
2298 // Bundle an ack if the alarm is set or with every second packet if we need to
2299 // raise the peer's least unacked.
2300 bool ack_pending =
2301 connection_->ack_alarm_->IsSet() || connection_->stop_waiting_count_ > 1;
2302 if (send_ack == SEND_ACK || (send_ack == BUNDLE_PENDING_ACK && ack_pending)) {
2303 DVLOG(1) << "Bundling ack with outgoing packet.";
2304 connection_->SendAck();
2308 QuicConnection::ScopedPacketBundler::~ScopedPacketBundler() {
2309 if (connection_ == nullptr) {
2310 return;
2312 // If we changed the generator's batch state, restore original batch state.
2313 if (!already_in_batch_mode_) {
2314 DVLOG(1) << "Leaving Batch Mode.";
2315 connection_->packet_generator_.FinishBatchOperations();
2317 DCHECK_EQ(already_in_batch_mode_,
2318 connection_->packet_generator_.InBatchMode());
2321 QuicConnection::ScopedRetransmissionScheduler::ScopedRetransmissionScheduler(
2322 QuicConnection* connection)
2323 : connection_(connection),
2324 already_delayed_(connection_->delay_setting_retransmission_alarm_) {
2325 connection_->delay_setting_retransmission_alarm_ = true;
2328 QuicConnection::ScopedRetransmissionScheduler::
2329 ~ScopedRetransmissionScheduler() {
2330 if (already_delayed_) {
2331 return;
2333 connection_->delay_setting_retransmission_alarm_ = false;
2334 if (connection_->pending_retransmission_alarm_) {
2335 connection_->SetRetransmissionAlarm();
2336 connection_->pending_retransmission_alarm_ = false;
2340 HasRetransmittableData QuicConnection::IsRetransmittable(
2341 const QueuedPacket& packet) {
2342 // Retransmitted packets retransmittable frames are owned by the unacked
2343 // packet map, but are not present in the serialized packet.
2344 if (packet.transmission_type != NOT_RETRANSMISSION ||
2345 packet.serialized_packet.retransmittable_frames != nullptr) {
2346 return HAS_RETRANSMITTABLE_DATA;
2347 } else {
2348 return NO_RETRANSMITTABLE_DATA;
2352 bool QuicConnection::IsConnectionClose(const QueuedPacket& packet) {
2353 const RetransmittableFrames* retransmittable_frames =
2354 packet.serialized_packet.retransmittable_frames;
2355 if (retransmittable_frames == nullptr) {
2356 return false;
2358 for (const QuicFrame& frame : retransmittable_frames->frames()) {
2359 if (frame.type == CONNECTION_CLOSE_FRAME) {
2360 return true;
2363 return false;
2366 void QuicConnection::SendMtuDiscoveryPacket(QuicByteCount target_mtu) {
2367 // Create a listener for the new probe. The ownership of the listener is
2368 // transferred to the AckNotifierManager. The notifier will get destroyed
2369 // before the connection (because it's stored in one of the connection's
2370 // subfields), hence |this| pointer is guaranteed to stay valid at all times.
2371 scoped_refptr<MtuDiscoveryAckListener> last_mtu_discovery_ack_listener(
2372 new MtuDiscoveryAckListener(this, target_mtu));
2374 // Send the probe.
2375 packet_generator_.GenerateMtuDiscoveryPacket(
2376 target_mtu, last_mtu_discovery_ack_listener.get());
2379 void QuicConnection::DiscoverMtu() {
2380 DCHECK(!mtu_discovery_alarm_->IsSet());
2382 // Chcek if the MTU has been already increased.
2383 if (mtu_discovery_target_ <= max_packet_length()) {
2384 return;
2387 // Schedule the next probe *before* sending the current one. This is
2388 // important, otherwise, when SendMtuDiscoveryPacket() is called,
2389 // MaybeSetMtuAlarm() will not realize that the probe has been just sent, and
2390 // will reschedule this probe again.
2391 packets_between_mtu_probes_ *= 2;
2392 next_mtu_probe_at_ =
2393 sequence_number_of_last_sent_packet_ + packets_between_mtu_probes_ + 1;
2394 ++mtu_probe_count_;
2396 DVLOG(2) << "Sending a path MTU discovery packet #" << mtu_probe_count_;
2397 SendMtuDiscoveryPacket(mtu_discovery_target_);
2399 DCHECK(!mtu_discovery_alarm_->IsSet());
2402 } // namespace net