Delete unused downloads page asset.
[chromium-blink-merge.git] / net / quic / quic_connection.cc
blobf663111c2cdaf13369d6d438ac02004586c5511f
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 QuicPacketNumber 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(QuicPacketNumber a, QuicPacketNumber b) {
67 QuicPacketNumber 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_packet_number(0) {}
234 QuicConnection::QueuedPacket::QueuedPacket(
235 SerializedPacket packet,
236 EncryptionLevel level,
237 TransmissionType transmission_type,
238 QuicPacketNumber original_packet_number)
239 : serialized_packet(packet),
240 encryption_level(level),
241 transmission_type(transmission_type),
242 original_packet_number(original_packet_number) {}
244 #define ENDPOINT \
245 (perspective_ == Perspective::IS_SERVER ? "Server: " : "Client: ")
247 QuicConnection::QuicConnection(QuicConnectionId connection_id,
248 IPEndPoint address,
249 QuicConnectionHelperInterface* helper,
250 const PacketWriterFactory& writer_factory,
251 bool owns_writer,
252 Perspective perspective,
253 bool is_secure,
254 const QuicVersionVector& supported_versions)
255 : framer_(supported_versions,
256 helper->GetClock()->ApproximateNow(),
257 perspective),
258 helper_(helper),
259 writer_(writer_factory.Create(this)),
260 owns_writer_(owns_writer),
261 encryption_level_(ENCRYPTION_NONE),
262 has_forward_secure_encrypter_(false),
263 first_required_forward_secure_packet_(0),
264 clock_(helper->GetClock()),
265 random_generator_(helper->GetRandomGenerator()),
266 connection_id_(connection_id),
267 peer_address_(address),
268 migrating_peer_port_(0),
269 last_packet_decrypted_(false),
270 last_packet_revived_(false),
271 last_size_(0),
272 last_decrypted_packet_level_(ENCRYPTION_NONE),
273 should_last_packet_instigate_acks_(false),
274 largest_seen_packet_with_ack_(0),
275 largest_seen_packet_with_stop_waiting_(0),
276 max_undecryptable_packets_(0),
277 pending_version_negotiation_packet_(false),
278 silent_close_enabled_(false),
279 received_packet_manager_(&stats_),
280 ack_queued_(false),
281 num_packets_received_since_last_ack_sent_(0),
282 stop_waiting_count_(0),
283 delay_setting_retransmission_alarm_(false),
284 pending_retransmission_alarm_(false),
285 ack_alarm_(helper->CreateAlarm(new AckAlarm(this))),
286 retransmission_alarm_(helper->CreateAlarm(new RetransmissionAlarm(this))),
287 send_alarm_(helper->CreateAlarm(new SendAlarm(this))),
288 resume_writes_alarm_(helper->CreateAlarm(new SendAlarm(this))),
289 timeout_alarm_(helper->CreateAlarm(new TimeoutAlarm(this))),
290 ping_alarm_(helper->CreateAlarm(new PingAlarm(this))),
291 mtu_discovery_alarm_(helper->CreateAlarm(new MtuDiscoveryAlarm(this))),
292 visitor_(nullptr),
293 debug_visitor_(nullptr),
294 packet_generator_(connection_id_, &framer_, random_generator_, this),
295 fec_alarm_(helper->CreateAlarm(new FecAlarm(&packet_generator_))),
296 idle_network_timeout_(QuicTime::Delta::Infinite()),
297 overall_connection_timeout_(QuicTime::Delta::Infinite()),
298 time_of_last_received_packet_(clock_->ApproximateNow()),
299 time_of_last_sent_new_packet_(clock_->ApproximateNow()),
300 packet_number_of_last_sent_packet_(0),
301 sent_packet_manager_(
302 perspective,
303 clock_,
304 &stats_,
305 FLAGS_quic_use_bbr_congestion_control ? kBBR : kCubic,
306 FLAGS_quic_use_time_loss_detection ? kTime : kNack,
307 is_secure),
308 version_negotiation_state_(START_NEGOTIATION),
309 perspective_(perspective),
310 connected_(true),
311 peer_ip_changed_(false),
312 peer_port_changed_(false),
313 self_ip_changed_(false),
314 self_port_changed_(false),
315 can_truncate_connection_ids_(true),
316 is_secure_(is_secure),
317 mtu_discovery_target_(0),
318 mtu_probe_count_(0),
319 packets_between_mtu_probes_(kPacketsBetweenMtuProbesBase),
320 next_mtu_probe_at_(kPacketsBetweenMtuProbesBase),
321 largest_received_packet_size_(0),
322 goaway_sent_(false),
323 goaway_received_(false) {
324 DVLOG(1) << ENDPOINT << "Created connection with connection_id: "
325 << connection_id;
326 framer_.set_visitor(this);
327 framer_.set_received_entropy_calculator(&received_packet_manager_);
328 stats_.connection_creation_time = clock_->ApproximateNow();
329 sent_packet_manager_.set_network_change_visitor(this);
330 if (perspective_ == Perspective::IS_SERVER) {
331 set_max_packet_length(kDefaultServerMaxPacketSize);
335 QuicConnection::~QuicConnection() {
336 if (owns_writer_) {
337 delete writer_;
339 STLDeleteElements(&undecryptable_packets_);
340 STLDeleteValues(&group_map_);
341 ClearQueuedPackets();
344 void QuicConnection::ClearQueuedPackets() {
345 for (QueuedPacketList::iterator it = queued_packets_.begin();
346 it != queued_packets_.end(); ++it) {
347 delete it->serialized_packet.retransmittable_frames;
348 delete it->serialized_packet.packet;
350 queued_packets_.clear();
353 void QuicConnection::SetFromConfig(const QuicConfig& config) {
354 if (config.negotiated()) {
355 SetNetworkTimeouts(QuicTime::Delta::Infinite(),
356 config.IdleConnectionStateLifetime());
357 if (config.SilentClose()) {
358 silent_close_enabled_ = true;
360 } else {
361 SetNetworkTimeouts(config.max_time_before_crypto_handshake(),
362 config.max_idle_time_before_crypto_handshake());
365 sent_packet_manager_.SetFromConfig(config);
366 if (config.HasReceivedBytesForConnectionId() &&
367 can_truncate_connection_ids_) {
368 packet_generator_.SetConnectionIdLength(
369 config.ReceivedBytesForConnectionId());
371 max_undecryptable_packets_ = config.max_undecryptable_packets();
373 if (config.HasClientSentConnectionOption(kFSPA, perspective_)) {
374 packet_generator_.set_fec_send_policy(FecSendPolicy::FEC_ALARM_TRIGGER);
376 if (config.HasClientSentConnectionOption(kFRTT, perspective_)) {
377 // TODO(rtenneti): Delete this code after the 0.25 RTT FEC experiment.
378 const float kFecTimeoutRttMultiplier = 0.25;
379 packet_generator_.set_rtt_multiplier_for_fec_timeout(
380 kFecTimeoutRttMultiplier);
383 if (config.HasClientSentConnectionOption(kMTUH, perspective_)) {
384 mtu_discovery_target_ = kMtuDiscoveryTargetPacketSizeHigh;
386 if (config.HasClientSentConnectionOption(kMTUL, perspective_)) {
387 mtu_discovery_target_ = kMtuDiscoveryTargetPacketSizeLow;
391 void QuicConnection::OnSendConnectionState(
392 const CachedNetworkParameters& cached_network_params) {
393 if (debug_visitor_ != nullptr) {
394 debug_visitor_->OnSendConnectionState(cached_network_params);
398 void QuicConnection::ResumeConnectionState(
399 const CachedNetworkParameters& cached_network_params,
400 bool max_bandwidth_resumption) {
401 if (debug_visitor_ != nullptr) {
402 debug_visitor_->OnResumeConnectionState(cached_network_params);
404 sent_packet_manager_.ResumeConnectionState(cached_network_params,
405 max_bandwidth_resumption);
408 void QuicConnection::SetNumOpenStreams(size_t num_streams) {
409 sent_packet_manager_.SetNumOpenStreams(num_streams);
412 bool QuicConnection::SelectMutualVersion(
413 const QuicVersionVector& available_versions) {
414 // Try to find the highest mutual version by iterating over supported
415 // versions, starting with the highest, and breaking out of the loop once we
416 // find a matching version in the provided available_versions vector.
417 const QuicVersionVector& supported_versions = framer_.supported_versions();
418 for (size_t i = 0; i < supported_versions.size(); ++i) {
419 const QuicVersion& version = supported_versions[i];
420 if (std::find(available_versions.begin(), available_versions.end(),
421 version) != available_versions.end()) {
422 framer_.set_version(version);
423 return true;
427 return false;
430 void QuicConnection::OnError(QuicFramer* framer) {
431 // Packets that we can not or have not decrypted are dropped.
432 // TODO(rch): add stats to measure this.
433 if (!connected_ || last_packet_decrypted_ == false) {
434 return;
436 SendConnectionCloseWithDetails(framer->error(), framer->detailed_error());
439 void QuicConnection::MaybeSetFecAlarm(QuicPacketNumber packet_number) {
440 if (fec_alarm_->IsSet()) {
441 return;
443 QuicTime::Delta timeout = packet_generator_.GetFecTimeout(packet_number);
444 if (!timeout.IsInfinite()) {
445 fec_alarm_->Update(clock_->ApproximateNow().Add(timeout),
446 QuicTime::Delta::FromMilliseconds(1));
450 void QuicConnection::OnPacket() {
451 DCHECK(last_stream_frames_.empty() &&
452 last_ack_frames_.empty() &&
453 last_stop_waiting_frames_.empty() &&
454 last_rst_frames_.empty() &&
455 last_goaway_frames_.empty() &&
456 last_window_update_frames_.empty() &&
457 last_blocked_frames_.empty() &&
458 last_ping_frames_.empty() &&
459 last_close_frames_.empty());
460 last_packet_decrypted_ = false;
461 last_packet_revived_ = false;
464 void QuicConnection::OnPublicResetPacket(const QuicPublicResetPacket& packet) {
465 // Check that any public reset packet with a different connection ID that was
466 // routed to this QuicConnection has been redirected before control reaches
467 // here. (Check for a bug regression.)
468 DCHECK_EQ(connection_id_, packet.public_header.connection_id);
469 if (debug_visitor_ != nullptr) {
470 debug_visitor_->OnPublicResetPacket(packet);
472 CloseConnection(QUIC_PUBLIC_RESET, true);
474 DVLOG(1) << ENDPOINT << "Connection " << connection_id()
475 << " closed via QUIC_PUBLIC_RESET from peer.";
478 bool QuicConnection::OnProtocolVersionMismatch(QuicVersion received_version) {
479 DVLOG(1) << ENDPOINT << "Received packet with mismatched version "
480 << received_version;
481 // TODO(satyamshekhar): Implement no server state in this mode.
482 if (perspective_ == Perspective::IS_CLIENT) {
483 LOG(DFATAL) << ENDPOINT << "Framer called OnProtocolVersionMismatch. "
484 << "Closing connection.";
485 CloseConnection(QUIC_INTERNAL_ERROR, false);
486 return false;
488 DCHECK_NE(version(), received_version);
490 if (debug_visitor_ != nullptr) {
491 debug_visitor_->OnProtocolVersionMismatch(received_version);
494 switch (version_negotiation_state_) {
495 case START_NEGOTIATION:
496 if (!framer_.IsSupportedVersion(received_version)) {
497 SendVersionNegotiationPacket();
498 version_negotiation_state_ = NEGOTIATION_IN_PROGRESS;
499 return false;
501 break;
503 case NEGOTIATION_IN_PROGRESS:
504 if (!framer_.IsSupportedVersion(received_version)) {
505 SendVersionNegotiationPacket();
506 return false;
508 break;
510 case NEGOTIATED_VERSION:
511 // Might be old packets that were sent by the client before the version
512 // was negotiated. Drop these.
513 return false;
515 default:
516 DCHECK(false);
519 version_negotiation_state_ = NEGOTIATED_VERSION;
520 visitor_->OnSuccessfulVersionNegotiation(received_version);
521 if (debug_visitor_ != nullptr) {
522 debug_visitor_->OnSuccessfulVersionNegotiation(received_version);
524 DVLOG(1) << ENDPOINT << "version negotiated " << received_version;
526 // Store the new version.
527 framer_.set_version(received_version);
529 // TODO(satyamshekhar): Store the packet number of this packet and close the
530 // connection if we ever received a packet with incorrect version and whose
531 // packet number is greater.
532 return true;
535 // Handles version negotiation for client connection.
536 void QuicConnection::OnVersionNegotiationPacket(
537 const QuicVersionNegotiationPacket& packet) {
538 // Check that any public reset packet with a different connection ID that was
539 // routed to this QuicConnection has been redirected before control reaches
540 // here. (Check for a bug regression.)
541 DCHECK_EQ(connection_id_, packet.connection_id);
542 if (perspective_ == Perspective::IS_SERVER) {
543 LOG(DFATAL) << ENDPOINT << "Framer parsed VersionNegotiationPacket."
544 << " Closing connection.";
545 CloseConnection(QUIC_INTERNAL_ERROR, false);
546 return;
548 if (debug_visitor_ != nullptr) {
549 debug_visitor_->OnVersionNegotiationPacket(packet);
552 if (version_negotiation_state_ != START_NEGOTIATION) {
553 // Possibly a duplicate version negotiation packet.
554 return;
557 if (std::find(packet.versions.begin(),
558 packet.versions.end(), version()) !=
559 packet.versions.end()) {
560 DLOG(WARNING) << ENDPOINT << "The server already supports our version. "
561 << "It should have accepted our connection.";
562 // Just drop the connection.
563 CloseConnection(QUIC_INVALID_VERSION_NEGOTIATION_PACKET, false);
564 return;
567 if (!SelectMutualVersion(packet.versions)) {
568 SendConnectionCloseWithDetails(QUIC_INVALID_VERSION,
569 "no common version found");
570 return;
573 DVLOG(1) << ENDPOINT
574 << "Negotiated version: " << QuicVersionToString(version());
575 server_supported_versions_ = packet.versions;
576 version_negotiation_state_ = NEGOTIATION_IN_PROGRESS;
577 RetransmitUnackedPackets(ALL_UNACKED_RETRANSMISSION);
580 void QuicConnection::OnRevivedPacket() {
583 bool QuicConnection::OnUnauthenticatedPublicHeader(
584 const QuicPacketPublicHeader& header) {
585 if (header.connection_id == connection_id_) {
586 return true;
589 ++stats_.packets_dropped;
590 DVLOG(1) << ENDPOINT << "Ignoring packet from unexpected ConnectionId: "
591 << header.connection_id << " instead of " << connection_id_;
592 if (debug_visitor_ != nullptr) {
593 debug_visitor_->OnIncorrectConnectionId(header.connection_id);
595 // If this is a server, the dispatcher routes each packet to the
596 // QuicConnection responsible for the packet's connection ID. So if control
597 // arrives here and this is a server, the dispatcher must be malfunctioning.
598 DCHECK_NE(Perspective::IS_SERVER, perspective_);
599 return false;
602 bool QuicConnection::OnUnauthenticatedHeader(const QuicPacketHeader& header) {
603 if (debug_visitor_ != nullptr) {
604 debug_visitor_->OnUnauthenticatedHeader(header);
607 // Check that any public reset packet with a different connection ID that was
608 // routed to this QuicConnection has been redirected before control reaches
609 // here.
610 DCHECK_EQ(connection_id_, header.public_header.connection_id);
611 return true;
614 void QuicConnection::OnDecryptedPacket(EncryptionLevel level) {
615 last_decrypted_packet_level_ = level;
616 last_packet_decrypted_ = true;
617 // If this packet was foward-secure encrypted and the forward-secure encrypter
618 // is not being used, start using it.
619 if (encryption_level_ != ENCRYPTION_FORWARD_SECURE &&
620 has_forward_secure_encrypter_ && level == ENCRYPTION_FORWARD_SECURE) {
621 SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
625 bool QuicConnection::OnPacketHeader(const QuicPacketHeader& header) {
626 if (debug_visitor_ != nullptr) {
627 debug_visitor_->OnPacketHeader(header);
630 if (!ProcessValidatedPacket()) {
631 return false;
634 // Will be decremented below if we fall through to return true.
635 ++stats_.packets_dropped;
637 if (!Near(header.packet_packet_number, last_header_.packet_packet_number)) {
638 DVLOG(1) << ENDPOINT << "Packet " << header.packet_packet_number
639 << " out of bounds. Discarding";
640 SendConnectionCloseWithDetails(QUIC_INVALID_PACKET_HEADER,
641 "packet number out of bounds");
642 return false;
645 // If this packet has already been seen, or the sender has told us that it
646 // will not be retransmitted, then stop processing the packet.
647 if (!received_packet_manager_.IsAwaitingPacket(header.packet_packet_number)) {
648 DVLOG(1) << ENDPOINT << "Packet " << header.packet_packet_number
649 << " no longer being waited for. Discarding.";
650 if (debug_visitor_ != nullptr) {
651 debug_visitor_->OnDuplicatePacket(header.packet_packet_number);
653 return false;
656 if (version_negotiation_state_ != NEGOTIATED_VERSION) {
657 if (perspective_ == Perspective::IS_SERVER) {
658 if (!header.public_header.version_flag) {
659 DLOG(WARNING) << ENDPOINT << "Packet " << header.packet_packet_number
660 << " without version flag before version negotiated.";
661 // Packets should have the version flag till version negotiation is
662 // done.
663 CloseConnection(QUIC_INVALID_VERSION, false);
664 return false;
665 } else {
666 DCHECK_EQ(1u, header.public_header.versions.size());
667 DCHECK_EQ(header.public_header.versions[0], version());
668 version_negotiation_state_ = NEGOTIATED_VERSION;
669 visitor_->OnSuccessfulVersionNegotiation(version());
670 if (debug_visitor_ != nullptr) {
671 debug_visitor_->OnSuccessfulVersionNegotiation(version());
674 } else {
675 DCHECK(!header.public_header.version_flag);
676 // If the client gets a packet without the version flag from the server
677 // it should stop sending version since the version negotiation is done.
678 packet_generator_.StopSendingVersion();
679 version_negotiation_state_ = NEGOTIATED_VERSION;
680 visitor_->OnSuccessfulVersionNegotiation(version());
681 if (debug_visitor_ != nullptr) {
682 debug_visitor_->OnSuccessfulVersionNegotiation(version());
687 DCHECK_EQ(NEGOTIATED_VERSION, version_negotiation_state_);
689 --stats_.packets_dropped;
690 DVLOG(1) << ENDPOINT << "Received packet header: " << header;
691 last_header_ = header;
692 DCHECK(connected_);
693 return true;
696 void QuicConnection::OnFecProtectedPayload(StringPiece payload) {
697 DCHECK_EQ(IN_FEC_GROUP, last_header_.is_in_fec_group);
698 DCHECK_NE(0u, last_header_.fec_group);
699 QuicFecGroup* group = GetFecGroup();
700 if (group != nullptr) {
701 group->Update(last_decrypted_packet_level_, last_header_, payload);
705 bool QuicConnection::OnStreamFrame(const QuicStreamFrame& frame) {
706 DCHECK(connected_);
707 if (debug_visitor_ != nullptr) {
708 debug_visitor_->OnStreamFrame(frame);
710 if (frame.stream_id != kCryptoStreamId &&
711 last_decrypted_packet_level_ == ENCRYPTION_NONE) {
712 DLOG(WARNING) << ENDPOINT
713 << "Received an unencrypted data frame: closing connection";
714 SendConnectionClose(QUIC_UNENCRYPTED_STREAM_DATA);
715 return false;
717 if (FLAGS_quic_process_frames_inline) {
718 visitor_->OnStreamFrame(frame);
719 stats_.stream_bytes_received += frame.data.size();
720 should_last_packet_instigate_acks_ = true;
721 } else {
722 last_stream_frames_.push_back(frame);
724 return connected_;
727 bool QuicConnection::OnAckFrame(const QuicAckFrame& incoming_ack) {
728 DCHECK(connected_);
729 if (debug_visitor_ != nullptr) {
730 debug_visitor_->OnAckFrame(incoming_ack);
732 DVLOG(1) << ENDPOINT << "OnAckFrame: " << incoming_ack;
734 if (last_header_.packet_packet_number <= largest_seen_packet_with_ack_) {
735 DVLOG(1) << ENDPOINT << "Received an old ack frame: ignoring";
736 return true;
739 if (!ValidateAckFrame(incoming_ack)) {
740 SendConnectionClose(QUIC_INVALID_ACK_DATA);
741 return false;
744 if (FLAGS_quic_process_frames_inline) {
745 ProcessAckFrame(incoming_ack);
746 if (incoming_ack.is_truncated) {
747 should_last_packet_instigate_acks_ = true;
749 if (!incoming_ack.missing_packets.empty() &&
750 GetLeastUnacked() > *incoming_ack.missing_packets.begin()) {
751 ++stop_waiting_count_;
752 } else {
753 stop_waiting_count_ = 0;
755 } else {
756 last_ack_frames_.push_back(incoming_ack);
758 return connected_;
761 void QuicConnection::ProcessAckFrame(const QuicAckFrame& incoming_ack) {
762 largest_seen_packet_with_ack_ = last_header_.packet_packet_number;
763 sent_packet_manager_.OnIncomingAck(incoming_ack,
764 time_of_last_received_packet_);
765 sent_entropy_manager_.ClearEntropyBefore(
766 sent_packet_manager_.least_packet_awaited_by_peer() - 1);
768 // Always reset the retransmission alarm when an ack comes in, since we now
769 // have a better estimate of the current rtt than when it was set.
770 SetRetransmissionAlarm();
773 void QuicConnection::ProcessStopWaitingFrame(
774 const QuicStopWaitingFrame& stop_waiting) {
775 largest_seen_packet_with_stop_waiting_ = last_header_.packet_packet_number;
776 received_packet_manager_.UpdatePacketInformationSentByPeer(stop_waiting);
777 // Possibly close any FecGroups which are now irrelevant.
778 CloseFecGroupsBefore(stop_waiting.least_unacked + 1);
781 bool QuicConnection::OnStopWaitingFrame(const QuicStopWaitingFrame& frame) {
782 DCHECK(connected_);
784 if (last_header_.packet_packet_number <=
785 largest_seen_packet_with_stop_waiting_) {
786 DVLOG(1) << ENDPOINT << "Received an old stop waiting frame: ignoring";
787 return true;
790 if (!ValidateStopWaitingFrame(frame)) {
791 SendConnectionClose(QUIC_INVALID_STOP_WAITING_DATA);
792 return false;
795 if (debug_visitor_ != nullptr) {
796 debug_visitor_->OnStopWaitingFrame(frame);
799 last_stop_waiting_frames_.push_back(frame);
800 return connected_;
803 bool QuicConnection::OnPingFrame(const QuicPingFrame& frame) {
804 DCHECK(connected_);
805 if (debug_visitor_ != nullptr) {
806 debug_visitor_->OnPingFrame(frame);
808 if (FLAGS_quic_process_frames_inline) {
809 should_last_packet_instigate_acks_ = true;
810 } else {
811 last_ping_frames_.push_back(frame);
813 return true;
816 bool QuicConnection::ValidateAckFrame(const QuicAckFrame& incoming_ack) {
817 if (incoming_ack.largest_observed > packet_generator_.packet_number()) {
818 DLOG(ERROR) << ENDPOINT << "Peer's observed unsent packet:"
819 << incoming_ack.largest_observed << " vs "
820 << packet_generator_.packet_number();
821 // We got an error for data we have not sent. Error out.
822 return false;
825 if (incoming_ack.largest_observed < sent_packet_manager_.largest_observed()) {
826 DLOG(ERROR) << ENDPOINT << "Peer's largest_observed packet decreased:"
827 << incoming_ack.largest_observed << " vs "
828 << sent_packet_manager_.largest_observed();
829 // A new ack has a diminished largest_observed value. Error out.
830 // If this was an old packet, we wouldn't even have checked.
831 return false;
834 if (!incoming_ack.missing_packets.empty() &&
835 *incoming_ack.missing_packets.rbegin() > incoming_ack.largest_observed) {
836 DLOG(ERROR) << ENDPOINT << "Peer sent missing packet: "
837 << *incoming_ack.missing_packets.rbegin()
838 << " which is greater than largest observed: "
839 << incoming_ack.largest_observed;
840 return false;
843 if (!incoming_ack.missing_packets.empty() &&
844 *incoming_ack.missing_packets.begin() <
845 sent_packet_manager_.least_packet_awaited_by_peer()) {
846 DLOG(ERROR) << ENDPOINT << "Peer sent missing packet: "
847 << *incoming_ack.missing_packets.begin()
848 << " which is smaller than least_packet_awaited_by_peer_: "
849 << sent_packet_manager_.least_packet_awaited_by_peer();
850 return false;
853 if (!sent_entropy_manager_.IsValidEntropy(
854 incoming_ack.largest_observed,
855 incoming_ack.missing_packets,
856 incoming_ack.entropy_hash)) {
857 DLOG(ERROR) << ENDPOINT << "Peer sent invalid entropy.";
858 return false;
861 for (QuicPacketNumber revived_packet : incoming_ack.revived_packets) {
862 if (!ContainsKey(incoming_ack.missing_packets, revived_packet)) {
863 DLOG(ERROR) << ENDPOINT
864 << "Peer specified revived packet which was not missing.";
865 return false;
868 return true;
871 bool QuicConnection::ValidateStopWaitingFrame(
872 const QuicStopWaitingFrame& stop_waiting) {
873 if (stop_waiting.least_unacked <
874 received_packet_manager_.peer_least_packet_awaiting_ack()) {
875 DLOG(ERROR) << ENDPOINT << "Peer's sent low least_unacked: "
876 << stop_waiting.least_unacked << " vs "
877 << received_packet_manager_.peer_least_packet_awaiting_ack();
878 // We never process old ack frames, so this number should only increase.
879 return false;
882 if (stop_waiting.least_unacked > last_header_.packet_packet_number) {
883 DLOG(ERROR) << ENDPOINT
884 << "Peer sent least_unacked:" << stop_waiting.least_unacked
885 << " greater than the enclosing packet number:"
886 << last_header_.packet_packet_number;
887 return false;
890 return true;
893 void QuicConnection::OnFecData(const QuicFecData& fec) {
894 DCHECK_EQ(IN_FEC_GROUP, last_header_.is_in_fec_group);
895 DCHECK_NE(0u, last_header_.fec_group);
896 QuicFecGroup* group = GetFecGroup();
897 if (group != nullptr) {
898 group->UpdateFec(last_decrypted_packet_level_,
899 last_header_.packet_packet_number, fec);
903 bool QuicConnection::OnRstStreamFrame(const QuicRstStreamFrame& frame) {
904 DCHECK(connected_);
905 if (debug_visitor_ != nullptr) {
906 debug_visitor_->OnRstStreamFrame(frame);
908 DVLOG(1) << ENDPOINT << "Stream reset with error "
909 << QuicUtils::StreamErrorToString(frame.error_code);
910 if (FLAGS_quic_process_frames_inline) {
911 visitor_->OnRstStream(frame);
912 should_last_packet_instigate_acks_ = true;
913 } else {
914 last_rst_frames_.push_back(frame);
916 return connected_;
919 bool QuicConnection::OnConnectionCloseFrame(
920 const QuicConnectionCloseFrame& frame) {
921 DCHECK(connected_);
922 if (debug_visitor_ != nullptr) {
923 debug_visitor_->OnConnectionCloseFrame(frame);
925 DVLOG(1) << ENDPOINT << "Connection " << connection_id()
926 << " closed with error "
927 << QuicUtils::ErrorToString(frame.error_code)
928 << " " << frame.error_details;
929 if (FLAGS_quic_process_frames_inline) {
930 CloseConnection(frame.error_code, true);
931 } else {
932 last_close_frames_.push_back(frame);
934 return connected_;
937 bool QuicConnection::OnGoAwayFrame(const QuicGoAwayFrame& frame) {
938 DCHECK(connected_);
939 if (debug_visitor_ != nullptr) {
940 debug_visitor_->OnGoAwayFrame(frame);
942 DVLOG(1) << ENDPOINT << "Go away received with error "
943 << QuicUtils::ErrorToString(frame.error_code)
944 << " and reason:" << frame.reason_phrase;
946 goaway_received_ = true;
947 if (FLAGS_quic_process_frames_inline) {
948 visitor_->OnGoAway(frame);
949 should_last_packet_instigate_acks_ = true;
950 } else {
951 last_goaway_frames_.push_back(frame);
953 return connected_;
956 bool QuicConnection::OnWindowUpdateFrame(const QuicWindowUpdateFrame& frame) {
957 DCHECK(connected_);
958 if (debug_visitor_ != nullptr) {
959 debug_visitor_->OnWindowUpdateFrame(frame);
961 DVLOG(1) << ENDPOINT << "WindowUpdate received for stream: "
962 << frame.stream_id << " with byte offset: " << frame.byte_offset;
963 if (FLAGS_quic_process_frames_inline) {
964 visitor_->OnWindowUpdateFrame(frame);
965 should_last_packet_instigate_acks_ = true;
966 } else {
967 last_window_update_frames_.push_back(frame);
969 return connected_;
972 bool QuicConnection::OnBlockedFrame(const QuicBlockedFrame& frame) {
973 DCHECK(connected_);
974 if (debug_visitor_ != nullptr) {
975 debug_visitor_->OnBlockedFrame(frame);
977 DVLOG(1) << ENDPOINT << "Blocked frame received for stream: "
978 << frame.stream_id;
979 if (FLAGS_quic_process_frames_inline) {
980 visitor_->OnBlockedFrame(frame);
981 should_last_packet_instigate_acks_ = true;
982 } else {
983 last_blocked_frames_.push_back(frame);
985 return connected_;
988 void QuicConnection::OnPacketComplete() {
989 // Don't do anything if this packet closed the connection.
990 if (!connected_) {
991 ClearLastFrames();
992 return;
995 DVLOG(1) << ENDPOINT << (last_packet_revived_ ? "Revived" : "Got")
996 << " packet " << last_header_.packet_packet_number << " with " //
997 << last_stream_frames_.size() << " stream frames, " //
998 << last_ack_frames_.size() << " acks, " //
999 << last_stop_waiting_frames_.size() << " stop_waiting, " //
1000 << last_rst_frames_.size() << " rsts, " //
1001 << last_goaway_frames_.size() << " goaways, " //
1002 << last_window_update_frames_.size() << " window updates, " //
1003 << last_blocked_frames_.size() << " blocked, " //
1004 << last_ping_frames_.size() << " pings, " //
1005 << last_close_frames_.size() << " closes " //
1006 << "for " << last_header_.public_header.connection_id;
1008 ++num_packets_received_since_last_ack_sent_;
1010 // Call MaybeQueueAck() before recording the received packet, since we want
1011 // to trigger an ack if the newly received packet was previously missing.
1012 MaybeQueueAck();
1014 // Record received or revived packet to populate ack info correctly before
1015 // processing stream frames, since the processing may result in a response
1016 // packet with a bundled ack.
1017 if (last_packet_revived_) {
1018 received_packet_manager_.RecordPacketRevived(
1019 last_header_.packet_packet_number);
1020 } else {
1021 received_packet_manager_.RecordPacketReceived(
1022 last_size_, last_header_, time_of_last_received_packet_);
1025 if (!FLAGS_quic_process_frames_inline) {
1026 for (const QuicStreamFrame& frame : last_stream_frames_) {
1027 visitor_->OnStreamFrame(frame);
1028 stats_.stream_bytes_received += frame.data.size();
1029 if (!connected_) {
1030 return;
1034 // Process window updates, blocked, stream resets, acks, then stop waiting.
1035 for (const QuicWindowUpdateFrame& frame : last_window_update_frames_) {
1036 visitor_->OnWindowUpdateFrame(frame);
1037 if (!connected_) {
1038 return;
1041 for (const QuicBlockedFrame& frame : last_blocked_frames_) {
1042 visitor_->OnBlockedFrame(frame);
1043 if (!connected_) {
1044 return;
1047 for (const QuicGoAwayFrame& frame : last_goaway_frames_) {
1048 visitor_->OnGoAway(frame);
1049 if (!connected_) {
1050 return;
1053 for (const QuicRstStreamFrame& frame : last_rst_frames_) {
1054 visitor_->OnRstStream(frame);
1055 if (!connected_) {
1056 return;
1059 for (const QuicAckFrame& frame : last_ack_frames_) {
1060 ProcessAckFrame(frame);
1061 if (!connected_) {
1062 return;
1065 if (!last_close_frames_.empty()) {
1066 CloseConnection(last_close_frames_[0].error_code, true);
1067 DCHECK(!connected_);
1068 return;
1071 // Continue to process stop waiting frames later, because the packet needs
1072 // to be considered 'received' before the entropy can be updated.
1073 for (const QuicStopWaitingFrame& frame : last_stop_waiting_frames_) {
1074 ProcessStopWaitingFrame(frame);
1075 if (!connected_) {
1076 return;
1080 // If there are new missing packets to report, send an ack immediately.
1081 if (ShouldLastPacketInstigateAck() &&
1082 received_packet_manager_.HasNewMissingPackets()) {
1083 ack_queued_ = true;
1084 ack_alarm_->Cancel();
1087 UpdateStopWaitingCount();
1088 ClearLastFrames();
1089 MaybeCloseIfTooManyOutstandingPackets();
1092 void QuicConnection::MaybeQueueAck() {
1093 // If the last packet is an ack, don't ack it.
1094 if (!ShouldLastPacketInstigateAck()) {
1095 return;
1097 // If the incoming packet was missing, send an ack immediately.
1098 ack_queued_ =
1099 received_packet_manager_.IsMissing(last_header_.packet_packet_number);
1101 if (!ack_queued_) {
1102 if (ack_alarm_->IsSet()) {
1103 ack_queued_ = true;
1104 } else {
1105 ack_alarm_->Set(
1106 clock_->ApproximateNow().Add(sent_packet_manager_.DelayedAckTime()));
1107 DVLOG(1) << "Ack timer set; next packet or timer will trigger ACK.";
1111 if (ack_queued_) {
1112 ack_alarm_->Cancel();
1116 void QuicConnection::ClearLastFrames() {
1117 if (FLAGS_quic_process_frames_inline) {
1118 should_last_packet_instigate_acks_ = false;
1119 last_stop_waiting_frames_.clear();
1120 return;
1122 last_stream_frames_.clear();
1123 last_ack_frames_.clear();
1124 last_stop_waiting_frames_.clear();
1125 last_rst_frames_.clear();
1126 last_goaway_frames_.clear();
1127 last_window_update_frames_.clear();
1128 last_blocked_frames_.clear();
1129 last_ping_frames_.clear();
1130 last_close_frames_.clear();
1133 void QuicConnection::MaybeCloseIfTooManyOutstandingPackets() {
1134 // This occurs if we don't discard old packets we've sent fast enough.
1135 // It's possible largest observed is less than least unacked.
1136 if (sent_packet_manager_.largest_observed() >
1137 (sent_packet_manager_.GetLeastUnacked() + kMaxTrackedPackets)) {
1138 SendConnectionCloseWithDetails(
1139 QUIC_TOO_MANY_OUTSTANDING_SENT_PACKETS,
1140 StringPrintf("More than %" PRIu64 " outstanding.", kMaxTrackedPackets));
1142 // This occurs if there are received packet gaps and the peer does not raise
1143 // the least unacked fast enough.
1144 if (received_packet_manager_.NumTrackedPackets() > kMaxTrackedPackets) {
1145 SendConnectionCloseWithDetails(
1146 QUIC_TOO_MANY_OUTSTANDING_RECEIVED_PACKETS,
1147 StringPrintf("More than %" PRIu64 " outstanding.", kMaxTrackedPackets));
1151 void QuicConnection::PopulateAckFrame(QuicAckFrame* ack) {
1152 received_packet_manager_.UpdateReceivedPacketInfo(ack,
1153 clock_->ApproximateNow());
1156 void QuicConnection::PopulateStopWaitingFrame(
1157 QuicStopWaitingFrame* stop_waiting) {
1158 stop_waiting->least_unacked = GetLeastUnacked();
1159 stop_waiting->entropy_hash = sent_entropy_manager_.GetCumulativeEntropy(
1160 stop_waiting->least_unacked - 1);
1163 bool QuicConnection::ShouldLastPacketInstigateAck() const {
1164 if (FLAGS_quic_process_frames_inline && should_last_packet_instigate_acks_) {
1165 return true;
1167 if (!FLAGS_quic_process_frames_inline) {
1168 if (!last_stream_frames_.empty() || !last_goaway_frames_.empty() ||
1169 !last_rst_frames_.empty() || !last_window_update_frames_.empty() ||
1170 !last_blocked_frames_.empty() || !last_ping_frames_.empty()) {
1171 return true;
1174 if (!last_ack_frames_.empty() && last_ack_frames_.back().is_truncated) {
1175 return true;
1178 // Always send an ack every 20 packets in order to allow the peer to discard
1179 // information from the SentPacketManager and provide an RTT measurement.
1180 if (num_packets_received_since_last_ack_sent_ >=
1181 kMaxPacketsReceivedBeforeAckSend) {
1182 return true;
1184 return false;
1187 void QuicConnection::UpdateStopWaitingCount() {
1188 if (last_ack_frames_.empty()) {
1189 return;
1192 // If the peer is still waiting for a packet that we are no longer planning to
1193 // send, send an ack to raise the high water mark.
1194 if (!last_ack_frames_.back().missing_packets.empty() &&
1195 GetLeastUnacked() > *last_ack_frames_.back().missing_packets.begin()) {
1196 ++stop_waiting_count_;
1197 } else {
1198 stop_waiting_count_ = 0;
1202 QuicPacketNumber QuicConnection::GetLeastUnacked() const {
1203 return sent_packet_manager_.GetLeastUnacked();
1206 void QuicConnection::MaybeSendInResponseToPacket() {
1207 if (!connected_) {
1208 return;
1210 ScopedPacketBundler bundler(this, ack_queued_ ? SEND_ACK : NO_ACK);
1212 // Now that we have received an ack, we might be able to send packets which
1213 // are queued locally, or drain streams which are blocked.
1214 WriteIfNotBlocked();
1217 void QuicConnection::SendVersionNegotiationPacket() {
1218 // TODO(alyssar): implement zero server state negotiation.
1219 pending_version_negotiation_packet_ = true;
1220 if (writer_->IsWriteBlocked()) {
1221 visitor_->OnWriteBlocked();
1222 return;
1224 DVLOG(1) << ENDPOINT << "Sending version negotiation packet: {"
1225 << QuicVersionVectorToString(framer_.supported_versions()) << "}";
1226 scoped_ptr<QuicEncryptedPacket> version_packet(
1227 packet_generator_.SerializeVersionNegotiationPacket(
1228 framer_.supported_versions()));
1229 WriteResult result = writer_->WritePacket(
1230 version_packet->data(), version_packet->length(),
1231 self_address().address(), peer_address());
1233 if (result.status == WRITE_STATUS_ERROR) {
1234 // We can't send an error as the socket is presumably borked.
1235 CloseConnection(QUIC_PACKET_WRITE_ERROR, false);
1236 return;
1238 if (result.status == WRITE_STATUS_BLOCKED) {
1239 visitor_->OnWriteBlocked();
1240 if (writer_->IsWriteBlockedDataBuffered()) {
1241 pending_version_negotiation_packet_ = false;
1243 return;
1246 pending_version_negotiation_packet_ = false;
1249 QuicConsumedData QuicConnection::SendStreamData(
1250 QuicStreamId id,
1251 const QuicIOVector& iov,
1252 QuicStreamOffset offset,
1253 bool fin,
1254 FecProtection fec_protection,
1255 QuicAckNotifier::DelegateInterface* delegate) {
1256 if (!fin && iov.total_length == 0) {
1257 LOG(DFATAL) << "Attempt to send empty stream frame";
1258 return QuicConsumedData(0, false);
1261 // Opportunistically bundle an ack with every outgoing packet.
1262 // Particularly, we want to bundle with handshake packets since we don't know
1263 // which decrypter will be used on an ack packet following a handshake
1264 // packet (a handshake packet from client to server could result in a REJ or a
1265 // SHLO from the server, leading to two different decrypters at the server.)
1267 // TODO(jri): Note that ConsumeData may cause a response packet to be sent.
1268 // We may end up sending stale ack information if there are undecryptable
1269 // packets hanging around and/or there are revivable packets which may get
1270 // handled after this packet is sent. Change ScopedPacketBundler to do the
1271 // right thing: check ack_queued_, and then check undecryptable packets and
1272 // also if there is possibility of revival. Only bundle an ack if there's no
1273 // processing left that may cause received_info_ to change.
1274 ScopedRetransmissionScheduler alarm_delayer(this);
1275 ScopedPacketBundler ack_bundler(this, BUNDLE_PENDING_ACK);
1276 return packet_generator_.ConsumeData(id, iov, offset, fin, fec_protection,
1277 delegate);
1280 void QuicConnection::SendRstStream(QuicStreamId id,
1281 QuicRstStreamErrorCode error,
1282 QuicStreamOffset bytes_written) {
1283 // Opportunistically bundle an ack with this outgoing packet.
1284 ScopedPacketBundler ack_bundler(this, BUNDLE_PENDING_ACK);
1285 packet_generator_.AddControlFrame(QuicFrame(new QuicRstStreamFrame(
1286 id, AdjustErrorForVersion(error, version()), bytes_written)));
1288 sent_packet_manager_.CancelRetransmissionsForStream(id);
1289 // Remove all queued packets which only contain data for the reset stream.
1290 QueuedPacketList::iterator packet_iterator = queued_packets_.begin();
1291 while (packet_iterator != queued_packets_.end()) {
1292 RetransmittableFrames* retransmittable_frames =
1293 packet_iterator->serialized_packet.retransmittable_frames;
1294 if (!retransmittable_frames) {
1295 ++packet_iterator;
1296 continue;
1298 retransmittable_frames->RemoveFramesForStream(id);
1299 if (!retransmittable_frames->frames().empty()) {
1300 ++packet_iterator;
1301 continue;
1303 delete packet_iterator->serialized_packet.retransmittable_frames;
1304 delete packet_iterator->serialized_packet.packet;
1305 packet_iterator->serialized_packet.retransmittable_frames = nullptr;
1306 packet_iterator->serialized_packet.packet = nullptr;
1307 packet_iterator = queued_packets_.erase(packet_iterator);
1311 void QuicConnection::SendWindowUpdate(QuicStreamId id,
1312 QuicStreamOffset byte_offset) {
1313 // Opportunistically bundle an ack with this outgoing packet.
1314 ScopedPacketBundler ack_bundler(this, BUNDLE_PENDING_ACK);
1315 packet_generator_.AddControlFrame(
1316 QuicFrame(new QuicWindowUpdateFrame(id, byte_offset)));
1319 void QuicConnection::SendBlocked(QuicStreamId id) {
1320 // Opportunistically bundle an ack with this outgoing packet.
1321 ScopedPacketBundler ack_bundler(this, BUNDLE_PENDING_ACK);
1322 packet_generator_.AddControlFrame(QuicFrame(new QuicBlockedFrame(id)));
1325 const QuicConnectionStats& QuicConnection::GetStats() {
1326 const RttStats* rtt_stats = sent_packet_manager_.GetRttStats();
1328 // Update rtt and estimated bandwidth.
1329 QuicTime::Delta min_rtt = rtt_stats->min_rtt();
1330 if (min_rtt.IsZero()) {
1331 // If min RTT has not been set, use initial RTT instead.
1332 min_rtt = QuicTime::Delta::FromMicroseconds(rtt_stats->initial_rtt_us());
1334 stats_.min_rtt_us = min_rtt.ToMicroseconds();
1336 QuicTime::Delta srtt = rtt_stats->smoothed_rtt();
1337 if (srtt.IsZero()) {
1338 // If SRTT has not been set, use initial RTT instead.
1339 srtt = QuicTime::Delta::FromMicroseconds(rtt_stats->initial_rtt_us());
1341 stats_.srtt_us = srtt.ToMicroseconds();
1343 stats_.estimated_bandwidth = sent_packet_manager_.BandwidthEstimate();
1344 stats_.max_packet_size = packet_generator_.GetMaxPacketLength();
1345 stats_.max_received_packet_size = largest_received_packet_size_;
1346 return stats_;
1349 void QuicConnection::ProcessUdpPacket(const IPEndPoint& self_address,
1350 const IPEndPoint& peer_address,
1351 const QuicEncryptedPacket& packet) {
1352 if (!connected_) {
1353 return;
1355 // TODO(rtenneti): Remove ScopedTracker below once crbug.com/462789 is fixed.
1356 tracked_objects::ScopedTracker tracking_profile(
1357 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1358 "462789 QuicConnection::ProcessUdpPacket"));
1359 if (debug_visitor_ != nullptr) {
1360 debug_visitor_->OnPacketReceived(self_address, peer_address, packet);
1362 last_size_ = packet.length();
1364 CheckForAddressMigration(self_address, peer_address);
1366 stats_.bytes_received += packet.length();
1367 ++stats_.packets_received;
1369 ScopedRetransmissionScheduler alarm_delayer(this);
1370 if (!framer_.ProcessPacket(packet)) {
1371 // If we are unable to decrypt this packet, it might be
1372 // because the CHLO or SHLO packet was lost.
1373 if (framer_.error() == QUIC_DECRYPTION_FAILURE) {
1374 if (encryption_level_ != ENCRYPTION_FORWARD_SECURE &&
1375 undecryptable_packets_.size() < max_undecryptable_packets_) {
1376 QueueUndecryptablePacket(packet);
1377 } else if (debug_visitor_ != nullptr) {
1378 debug_visitor_->OnUndecryptablePacket();
1381 DVLOG(1) << ENDPOINT << "Unable to process packet. Last packet processed: "
1382 << last_header_.packet_packet_number;
1383 return;
1386 ++stats_.packets_processed;
1387 MaybeProcessUndecryptablePackets();
1388 MaybeProcessRevivedPacket();
1389 MaybeSendInResponseToPacket();
1390 SetPingAlarm();
1393 void QuicConnection::CheckForAddressMigration(
1394 const IPEndPoint& self_address, const IPEndPoint& peer_address) {
1395 peer_ip_changed_ = false;
1396 peer_port_changed_ = false;
1397 self_ip_changed_ = false;
1398 self_port_changed_ = false;
1400 if (peer_address_.address().empty()) {
1401 peer_address_ = peer_address;
1403 if (self_address_.address().empty()) {
1404 self_address_ = self_address;
1407 if (!peer_address.address().empty() && !peer_address_.address().empty()) {
1408 peer_ip_changed_ = (peer_address.address() != peer_address_.address());
1409 peer_port_changed_ = (peer_address.port() != peer_address_.port());
1411 // Store in case we want to migrate connection in ProcessValidatedPacket.
1412 migrating_peer_ip_ = peer_address.address();
1413 migrating_peer_port_ = peer_address.port();
1416 if (!self_address.address().empty() && !self_address_.address().empty()) {
1417 self_ip_changed_ = (self_address.address() != self_address_.address());
1418 self_port_changed_ = (self_address.port() != self_address_.port());
1422 void QuicConnection::OnCanWrite() {
1423 DCHECK(!writer_->IsWriteBlocked());
1425 WriteQueuedPackets();
1426 WritePendingRetransmissions();
1428 // Sending queued packets may have caused the socket to become write blocked,
1429 // or the congestion manager to prohibit sending. If we've sent everything
1430 // we had queued and we're still not blocked, let the visitor know it can
1431 // write more.
1432 if (!CanWrite(HAS_RETRANSMITTABLE_DATA)) {
1433 return;
1436 { // Limit the scope of the bundler. ACK inclusion happens elsewhere.
1437 ScopedPacketBundler bundler(this, NO_ACK);
1438 visitor_->OnCanWrite();
1441 // After the visitor writes, it may have caused the socket to become write
1442 // blocked or the congestion manager to prohibit sending, so check again.
1443 if (visitor_->WillingAndAbleToWrite() &&
1444 !resume_writes_alarm_->IsSet() &&
1445 CanWrite(HAS_RETRANSMITTABLE_DATA)) {
1446 // We're not write blocked, but some stream didn't write out all of its
1447 // bytes. Register for 'immediate' resumption so we'll keep writing after
1448 // other connections and events have had a chance to use the thread.
1449 resume_writes_alarm_->Set(clock_->ApproximateNow());
1453 void QuicConnection::WriteIfNotBlocked() {
1454 if (!writer_->IsWriteBlocked()) {
1455 OnCanWrite();
1459 bool QuicConnection::ProcessValidatedPacket() {
1460 if ((peer_ip_changed_ && !FLAGS_quic_allow_ip_migration) ||
1461 self_ip_changed_ || self_port_changed_) {
1462 SendConnectionCloseWithDetails(
1463 QUIC_ERROR_MIGRATING_ADDRESS,
1464 "Neither IP address migration, nor self port migration are supported.");
1465 return false;
1468 // TODO(fayang): Use peer_address_changed_ instead of peer_ip_changed_ and
1469 // peer_port_changed_ once FLAGS_quic_allow_ip_migration is deprecated.
1470 if (peer_ip_changed_ || peer_port_changed_) {
1471 IPEndPoint old_peer_address = peer_address_;
1472 peer_address_ = IPEndPoint(
1473 peer_ip_changed_ ? migrating_peer_ip_ : peer_address_.address(),
1474 peer_port_changed_ ? migrating_peer_port_ : peer_address_.port());
1476 DVLOG(1) << ENDPOINT << "Peer's ip:port changed from "
1477 << old_peer_address.ToString() << " to "
1478 << peer_address_.ToString() << ", migrating connection.";
1480 if (FLAGS_send_goaway_after_client_migration) {
1481 visitor_->OnConnectionMigration();
1485 time_of_last_received_packet_ = clock_->Now();
1486 DVLOG(1) << ENDPOINT << "time of last received packet: "
1487 << time_of_last_received_packet_.ToDebuggingValue();
1489 if (last_size_ > largest_received_packet_size_) {
1490 largest_received_packet_size_ = last_size_;
1493 if (perspective_ == Perspective::IS_SERVER &&
1494 encryption_level_ == ENCRYPTION_NONE &&
1495 last_size_ > packet_generator_.GetMaxPacketLength()) {
1496 set_max_packet_length(last_size_);
1498 return true;
1501 void QuicConnection::WriteQueuedPackets() {
1502 DCHECK(!writer_->IsWriteBlocked());
1504 if (pending_version_negotiation_packet_) {
1505 SendVersionNegotiationPacket();
1508 QueuedPacketList::iterator packet_iterator = queued_packets_.begin();
1509 while (packet_iterator != queued_packets_.end() &&
1510 WritePacket(&(*packet_iterator))) {
1511 packet_iterator = queued_packets_.erase(packet_iterator);
1515 void QuicConnection::WritePendingRetransmissions() {
1516 // Keep writing as long as there's a pending retransmission which can be
1517 // written.
1518 while (sent_packet_manager_.HasPendingRetransmissions()) {
1519 const QuicSentPacketManager::PendingRetransmission pending =
1520 sent_packet_manager_.NextPendingRetransmission();
1521 if (!CanWrite(HAS_RETRANSMITTABLE_DATA)) {
1522 break;
1525 // Re-packetize the frames with a new packet number for retransmission.
1526 // Retransmitted data packets do not use FEC, even when it's enabled.
1527 // Retransmitted packets use the same packet number length as the
1528 // original.
1529 // Flush the packet generator before making a new packet.
1530 // TODO(ianswett): Implement ReserializeAllFrames as a separate path that
1531 // does not require the creator to be flushed.
1532 packet_generator_.FlushAllQueuedFrames();
1533 char buffer[kMaxPacketSize];
1534 SerializedPacket serialized_packet = packet_generator_.ReserializeAllFrames(
1535 pending.retransmittable_frames, pending.packet_number_length, buffer,
1536 kMaxPacketSize);
1537 if (serialized_packet.packet == nullptr) {
1538 // We failed to serialize the packet, so close the connection.
1539 // CloseConnection does not send close packet, so no infinite loop here.
1540 CloseConnection(QUIC_ENCRYPTION_FAILURE, false);
1541 return;
1544 DVLOG(1) << ENDPOINT << "Retransmitting " << pending.packet_number << " as "
1545 << serialized_packet.packet_number;
1546 SendOrQueuePacket(QueuedPacket(
1547 serialized_packet, pending.retransmittable_frames.encryption_level(),
1548 pending.transmission_type, pending.packet_number));
1552 void QuicConnection::RetransmitUnackedPackets(
1553 TransmissionType retransmission_type) {
1554 sent_packet_manager_.RetransmitUnackedPackets(retransmission_type);
1556 WriteIfNotBlocked();
1559 void QuicConnection::NeuterUnencryptedPackets() {
1560 sent_packet_manager_.NeuterUnencryptedPackets();
1561 // This may have changed the retransmission timer, so re-arm it.
1562 SetRetransmissionAlarm();
1565 bool QuicConnection::ShouldGeneratePacket(
1566 HasRetransmittableData retransmittable,
1567 IsHandshake handshake) {
1568 // We should serialize handshake packets immediately to ensure that they
1569 // end up sent at the right encryption level.
1570 if (handshake == IS_HANDSHAKE) {
1571 return true;
1574 return CanWrite(retransmittable);
1577 bool QuicConnection::CanWrite(HasRetransmittableData retransmittable) {
1578 if (!connected_) {
1579 return false;
1582 if (writer_->IsWriteBlocked()) {
1583 visitor_->OnWriteBlocked();
1584 return false;
1587 QuicTime now = clock_->Now();
1588 QuicTime::Delta delay = sent_packet_manager_.TimeUntilSend(
1589 now, retransmittable);
1590 if (delay.IsInfinite()) {
1591 send_alarm_->Cancel();
1592 return false;
1595 // If the scheduler requires a delay, then we can not send this packet now.
1596 if (!delay.IsZero()) {
1597 send_alarm_->Update(now.Add(delay), QuicTime::Delta::FromMilliseconds(1));
1598 DVLOG(1) << ENDPOINT << "Delaying sending " << delay.ToMilliseconds()
1599 << "ms";
1600 return false;
1602 send_alarm_->Cancel();
1603 return true;
1606 bool QuicConnection::WritePacket(QueuedPacket* packet) {
1607 if (!WritePacketInner(packet)) {
1608 return false;
1610 delete packet->serialized_packet.retransmittable_frames;
1611 delete packet->serialized_packet.packet;
1612 packet->serialized_packet.retransmittable_frames = nullptr;
1613 packet->serialized_packet.packet = nullptr;
1614 return true;
1617 bool QuicConnection::WritePacketInner(QueuedPacket* packet) {
1618 if (ShouldDiscardPacket(*packet)) {
1619 ++stats_.packets_discarded;
1620 return true;
1622 // Connection close packets are encrypted and saved, so don't exit early.
1623 const bool is_connection_close = IsConnectionClose(*packet);
1624 if (writer_->IsWriteBlocked() && !is_connection_close) {
1625 return false;
1628 QuicPacketNumber packet_number = packet->serialized_packet.packet_number;
1629 DCHECK_LE(packet_number_of_last_sent_packet_, packet_number);
1630 packet_number_of_last_sent_packet_ = packet_number;
1632 QuicEncryptedPacket* encrypted = packet->serialized_packet.packet;
1633 // Connection close packets are eventually owned by TimeWaitListManager.
1634 // Others are deleted at the end of this call.
1635 if (is_connection_close) {
1636 DCHECK(connection_close_packet_.get() == nullptr);
1637 // Clone the packet so it's owned in the future.
1638 connection_close_packet_.reset(encrypted->Clone());
1639 // This assures we won't try to write *forced* packets when blocked.
1640 // Return true to stop processing.
1641 if (writer_->IsWriteBlocked()) {
1642 visitor_->OnWriteBlocked();
1643 return true;
1647 if (!FLAGS_quic_allow_oversized_packets_for_test) {
1648 DCHECK_LE(encrypted->length(), kMaxPacketSize);
1650 DCHECK_LE(encrypted->length(), packet_generator_.GetMaxPacketLength());
1651 DVLOG(1) << ENDPOINT << "Sending packet " << packet_number << " : "
1652 << (packet->serialized_packet.is_fec_packet
1653 ? "FEC "
1654 : (IsRetransmittable(*packet) == HAS_RETRANSMITTABLE_DATA
1655 ? "data bearing "
1656 : " ack only "))
1657 << ", encryption level: "
1658 << QuicUtils::EncryptionLevelToString(packet->encryption_level)
1659 << ", encrypted length:" << encrypted->length();
1660 DVLOG(2) << ENDPOINT << "packet(" << packet_number << "): " << std::endl
1661 << QuicUtils::StringToHexASCIIDump(encrypted->AsStringPiece());
1663 // Measure the RTT from before the write begins to avoid underestimating the
1664 // min_rtt_, especially in cases where the thread blocks or gets swapped out
1665 // during the WritePacket below.
1666 QuicTime packet_send_time = clock_->Now();
1667 WriteResult result = writer_->WritePacket(encrypted->data(),
1668 encrypted->length(),
1669 self_address().address(),
1670 peer_address());
1671 if (result.error_code == ERR_IO_PENDING) {
1672 DCHECK_EQ(WRITE_STATUS_BLOCKED, result.status);
1675 if (result.status == WRITE_STATUS_BLOCKED) {
1676 visitor_->OnWriteBlocked();
1677 // If the socket buffers the the data, then the packet should not
1678 // be queued and sent again, which would result in an unnecessary
1679 // duplicate packet being sent. The helper must call OnCanWrite
1680 // when the write completes, and OnWriteError if an error occurs.
1681 if (!writer_->IsWriteBlockedDataBuffered()) {
1682 return false;
1685 if (result.status != WRITE_STATUS_ERROR && debug_visitor_ != nullptr) {
1686 // Pass the write result to the visitor.
1687 debug_visitor_->OnPacketSent(
1688 packet->serialized_packet, packet->original_packet_number,
1689 packet->encryption_level, packet->transmission_type, *encrypted,
1690 packet_send_time);
1692 if (packet->transmission_type == NOT_RETRANSMISSION) {
1693 time_of_last_sent_new_packet_ = packet_send_time;
1695 SetPingAlarm();
1696 MaybeSetFecAlarm(packet_number);
1697 MaybeSetMtuAlarm();
1698 DVLOG(1) << ENDPOINT << "time we began writing last sent packet: "
1699 << packet_send_time.ToDebuggingValue();
1701 // TODO(ianswett): Change the packet number length and other packet creator
1702 // options by a more explicit API than setting a struct value directly,
1703 // perhaps via the NetworkChangeVisitor.
1704 packet_generator_.UpdateSequenceNumberLength(
1705 sent_packet_manager_.least_packet_awaited_by_peer(),
1706 sent_packet_manager_.EstimateMaxPacketsInFlight(max_packet_length()));
1708 bool reset_retransmission_alarm = sent_packet_manager_.OnPacketSent(
1709 &packet->serialized_packet, packet->original_packet_number,
1710 packet_send_time, encrypted->length(), packet->transmission_type,
1711 IsRetransmittable(*packet));
1713 if (reset_retransmission_alarm || !retransmission_alarm_->IsSet()) {
1714 SetRetransmissionAlarm();
1717 stats_.bytes_sent += result.bytes_written;
1718 ++stats_.packets_sent;
1719 if (packet->transmission_type != NOT_RETRANSMISSION) {
1720 stats_.bytes_retransmitted += result.bytes_written;
1721 ++stats_.packets_retransmitted;
1724 if (result.status == WRITE_STATUS_ERROR) {
1725 OnWriteError(result.error_code);
1726 DLOG(ERROR) << ENDPOINT << "failed writing " << encrypted->length()
1727 << " bytes "
1728 << " from host " << self_address().ToStringWithoutPort()
1729 << " to address " << peer_address().ToString();
1730 return false;
1733 return true;
1736 bool QuicConnection::ShouldDiscardPacket(const QueuedPacket& packet) {
1737 if (!connected_) {
1738 DVLOG(1) << ENDPOINT
1739 << "Not sending packet as connection is disconnected.";
1740 return true;
1743 QuicPacketNumber packet_number = packet.serialized_packet.packet_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: " << packet_number
1749 << " 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_packet_number) ||
1757 !sent_packet_manager_.HasRetransmittableFrames(
1758 packet.original_packet_number))) {
1759 DVLOG(1) << ENDPOINT << "Dropping unacked packet: " << packet_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.packet_number,
1834 packet.serialized_packet.entropy_hash);
1835 // If there are already queued packets, queue this one immediately to ensure
1836 // it's written in sequence number order.
1837 if (!queued_packets_.empty() || !WritePacket(&packet)) {
1838 // Take ownership of the underlying encrypted packet.
1839 if (!packet.serialized_packet.packet->owns_buffer()) {
1840 scoped_ptr<QuicEncryptedPacket> encrypted_deleter(
1841 packet.serialized_packet.packet);
1842 packet.serialized_packet.packet =
1843 packet.serialized_packet.packet->Clone();
1845 queued_packets_.push_back(packet);
1848 // If a forward-secure encrypter is available but is not being used and the
1849 // next packet number is the first packet which requires
1850 // forward security, start using the forward-secure encrypter.
1851 if (encryption_level_ != ENCRYPTION_FORWARD_SECURE &&
1852 has_forward_secure_encrypter_ &&
1853 packet.serialized_packet.packet_number >=
1854 first_required_forward_secure_packet_ - 1) {
1855 SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
1859 void QuicConnection::SendPing() {
1860 if (retransmission_alarm_->IsSet()) {
1861 return;
1863 packet_generator_.AddControlFrame(QuicFrame(new QuicPingFrame));
1866 void QuicConnection::SendAck() {
1867 ack_alarm_->Cancel();
1868 ack_queued_ = false;
1869 stop_waiting_count_ = 0;
1870 num_packets_received_since_last_ack_sent_ = 0;
1872 packet_generator_.SetShouldSendAck(true);
1875 void QuicConnection::OnRetransmissionTimeout() {
1876 if (!sent_packet_manager_.HasUnackedPackets()) {
1877 return;
1880 sent_packet_manager_.OnRetransmissionTimeout();
1881 WriteIfNotBlocked();
1883 // A write failure can result in the connection being closed, don't attempt to
1884 // write further packets, or to set alarms.
1885 if (!connected_) {
1886 return;
1889 // In the TLP case, the SentPacketManager gives the connection the opportunity
1890 // to send new data before retransmitting.
1891 if (sent_packet_manager_.MaybeRetransmitTailLossProbe()) {
1892 // Send the pending retransmission now that it's been queued.
1893 WriteIfNotBlocked();
1896 // Ensure the retransmission alarm is always set if there are unacked packets
1897 // and nothing waiting to be sent.
1898 // This happens if the loss algorithm invokes a timer based loss, but the
1899 // packet doesn't need to be retransmitted.
1900 if (!HasQueuedData() && !retransmission_alarm_->IsSet()) {
1901 SetRetransmissionAlarm();
1905 void QuicConnection::SetEncrypter(EncryptionLevel level,
1906 QuicEncrypter* encrypter) {
1907 packet_generator_.SetEncrypter(level, encrypter);
1908 if (level == ENCRYPTION_FORWARD_SECURE) {
1909 has_forward_secure_encrypter_ = true;
1910 first_required_forward_secure_packet_ =
1911 packet_number_of_last_sent_packet_ +
1912 // 3 times the current congestion window (in slow start) should cover
1913 // about two full round trips worth of packets, which should be
1914 // sufficient.
1916 sent_packet_manager_.EstimateMaxPacketsInFlight(
1917 max_packet_length());
1921 void QuicConnection::SetDefaultEncryptionLevel(EncryptionLevel level) {
1922 encryption_level_ = level;
1923 packet_generator_.set_encryption_level(level);
1926 void QuicConnection::SetDecrypter(EncryptionLevel level,
1927 QuicDecrypter* decrypter) {
1928 framer_.SetDecrypter(level, decrypter);
1931 void QuicConnection::SetAlternativeDecrypter(EncryptionLevel level,
1932 QuicDecrypter* decrypter,
1933 bool latch_once_used) {
1934 framer_.SetAlternativeDecrypter(level, decrypter, latch_once_used);
1937 const QuicDecrypter* QuicConnection::decrypter() const {
1938 return framer_.decrypter();
1941 const QuicDecrypter* QuicConnection::alternative_decrypter() const {
1942 return framer_.alternative_decrypter();
1945 void QuicConnection::QueueUndecryptablePacket(
1946 const QuicEncryptedPacket& packet) {
1947 DVLOG(1) << ENDPOINT << "Queueing undecryptable packet.";
1948 undecryptable_packets_.push_back(packet.Clone());
1951 void QuicConnection::MaybeProcessUndecryptablePackets() {
1952 if (undecryptable_packets_.empty() || encryption_level_ == ENCRYPTION_NONE) {
1953 return;
1956 while (connected_ && !undecryptable_packets_.empty()) {
1957 DVLOG(1) << ENDPOINT << "Attempting to process undecryptable packet";
1958 QuicEncryptedPacket* packet = undecryptable_packets_.front();
1959 if (!framer_.ProcessPacket(*packet) &&
1960 framer_.error() == QUIC_DECRYPTION_FAILURE) {
1961 DVLOG(1) << ENDPOINT << "Unable to process undecryptable packet...";
1962 break;
1964 DVLOG(1) << ENDPOINT << "Processed undecryptable packet!";
1965 ++stats_.packets_processed;
1966 delete packet;
1967 undecryptable_packets_.pop_front();
1970 // Once forward secure encryption is in use, there will be no
1971 // new keys installed and hence any undecryptable packets will
1972 // never be able to be decrypted.
1973 if (encryption_level_ == ENCRYPTION_FORWARD_SECURE) {
1974 if (debug_visitor_ != nullptr) {
1975 // TODO(rtenneti): perhaps more efficient to pass the number of
1976 // undecryptable packets as the argument to OnUndecryptablePacket so that
1977 // we just need to call OnUndecryptablePacket once?
1978 for (size_t i = 0; i < undecryptable_packets_.size(); ++i) {
1979 debug_visitor_->OnUndecryptablePacket();
1982 STLDeleteElements(&undecryptable_packets_);
1986 void QuicConnection::MaybeProcessRevivedPacket() {
1987 QuicFecGroup* group = GetFecGroup();
1988 if (!connected_ || group == nullptr || !group->CanRevive()) {
1989 return;
1991 QuicPacketHeader revived_header;
1992 char revived_payload[kMaxPacketSize];
1993 size_t len = group->Revive(&revived_header, revived_payload, kMaxPacketSize);
1994 revived_header.public_header.connection_id = connection_id_;
1995 revived_header.public_header.connection_id_length =
1996 last_header_.public_header.connection_id_length;
1997 revived_header.public_header.version_flag = false;
1998 revived_header.public_header.reset_flag = false;
1999 revived_header.public_header.packet_number_length =
2000 last_header_.public_header.packet_number_length;
2001 revived_header.fec_flag = false;
2002 revived_header.is_in_fec_group = NOT_IN_FEC_GROUP;
2003 revived_header.fec_group = 0;
2004 group_map_.erase(last_header_.fec_group);
2005 last_decrypted_packet_level_ = group->effective_encryption_level();
2006 DCHECK_LT(last_decrypted_packet_level_, NUM_ENCRYPTION_LEVELS);
2007 delete group;
2009 last_packet_revived_ = true;
2010 if (debug_visitor_ != nullptr) {
2011 debug_visitor_->OnRevivedPacket(revived_header,
2012 StringPiece(revived_payload, len));
2015 ++stats_.packets_revived;
2016 framer_.ProcessRevivedPacket(&revived_header,
2017 StringPiece(revived_payload, len));
2020 QuicFecGroup* QuicConnection::GetFecGroup() {
2021 QuicFecGroupNumber fec_group_num = last_header_.fec_group;
2022 if (fec_group_num == 0) {
2023 return nullptr;
2025 if (!ContainsKey(group_map_, fec_group_num)) {
2026 if (group_map_.size() >= kMaxFecGroups) { // Too many groups
2027 if (fec_group_num < group_map_.begin()->first) {
2028 // The group being requested is a group we've seen before and deleted.
2029 // Don't recreate it.
2030 return nullptr;
2032 // Clear the lowest group number.
2033 delete group_map_.begin()->second;
2034 group_map_.erase(group_map_.begin());
2036 group_map_[fec_group_num] = new QuicFecGroup();
2038 return group_map_[fec_group_num];
2041 void QuicConnection::SendConnectionClose(QuicErrorCode error) {
2042 SendConnectionCloseWithDetails(error, string());
2045 void QuicConnection::SendConnectionCloseWithDetails(QuicErrorCode error,
2046 const string& details) {
2047 // If we're write blocked, WritePacket() will not send, but will capture the
2048 // serialized packet.
2049 SendConnectionClosePacket(error, details);
2050 CloseConnection(error, false);
2053 void QuicConnection::SendConnectionClosePacket(QuicErrorCode error,
2054 const string& details) {
2055 DVLOG(1) << ENDPOINT << "Force closing " << connection_id()
2056 << " with error " << QuicUtils::ErrorToString(error)
2057 << " (" << error << ") " << details;
2058 // Don't send explicit connection close packets for timeouts.
2059 // This is particularly important on mobile, where connections are short.
2060 if (silent_close_enabled_ &&
2061 error == QuicErrorCode::QUIC_CONNECTION_TIMED_OUT) {
2062 return;
2064 ClearQueuedPackets();
2065 ScopedPacketBundler ack_bundler(this, SEND_ACK);
2066 QuicConnectionCloseFrame* frame = new QuicConnectionCloseFrame();
2067 frame->error_code = error;
2068 frame->error_details = details;
2069 packet_generator_.AddControlFrame(QuicFrame(frame));
2070 packet_generator_.FlushAllQueuedFrames();
2073 void QuicConnection::CloseConnection(QuicErrorCode error, bool from_peer) {
2074 if (!connected_) {
2075 DVLOG(1) << "Connection is already closed.";
2076 return;
2078 connected_ = false;
2079 if (debug_visitor_ != nullptr) {
2080 debug_visitor_->OnConnectionClosed(error, from_peer);
2082 DCHECK(visitor_ != nullptr);
2083 visitor_->OnConnectionClosed(error, from_peer);
2084 // Cancel the alarms so they don't trigger any action now that the
2085 // connection is closed.
2086 ack_alarm_->Cancel();
2087 ping_alarm_->Cancel();
2088 fec_alarm_->Cancel();
2089 resume_writes_alarm_->Cancel();
2090 retransmission_alarm_->Cancel();
2091 send_alarm_->Cancel();
2092 timeout_alarm_->Cancel();
2093 mtu_discovery_alarm_->Cancel();
2096 void QuicConnection::SendGoAway(QuicErrorCode error,
2097 QuicStreamId last_good_stream_id,
2098 const string& reason) {
2099 if (goaway_sent_) {
2100 return;
2102 goaway_sent_ = true;
2104 DVLOG(1) << ENDPOINT << "Going away with error "
2105 << QuicUtils::ErrorToString(error)
2106 << " (" << error << ")";
2108 // Opportunistically bundle an ack with this outgoing packet.
2109 ScopedPacketBundler ack_bundler(this, BUNDLE_PENDING_ACK);
2110 packet_generator_.AddControlFrame(
2111 QuicFrame(new QuicGoAwayFrame(error, last_good_stream_id, reason)));
2114 void QuicConnection::CloseFecGroupsBefore(QuicPacketNumber packet_number) {
2115 FecGroupMap::iterator it = group_map_.begin();
2116 while (it != group_map_.end()) {
2117 // If this is the current group or the group doesn't protect this packet
2118 // we can ignore it.
2119 if (last_header_.fec_group == it->first ||
2120 !it->second->ProtectsPacketsBefore(packet_number)) {
2121 ++it;
2122 continue;
2124 QuicFecGroup* fec_group = it->second;
2125 DCHECK(!fec_group->CanRevive());
2126 FecGroupMap::iterator next = it;
2127 ++next;
2128 group_map_.erase(it);
2129 delete fec_group;
2130 it = next;
2134 QuicByteCount QuicConnection::max_packet_length() const {
2135 return packet_generator_.GetMaxPacketLength();
2138 void QuicConnection::set_max_packet_length(QuicByteCount length) {
2139 return packet_generator_.SetMaxPacketLength(length, /*force=*/false);
2142 bool QuicConnection::HasQueuedData() const {
2143 return pending_version_negotiation_packet_ ||
2144 !queued_packets_.empty() || packet_generator_.HasQueuedFrames();
2147 bool QuicConnection::CanWriteStreamData() {
2148 // Don't write stream data if there are negotiation or queued data packets
2149 // to send. Otherwise, continue and bundle as many frames as possible.
2150 if (pending_version_negotiation_packet_ || !queued_packets_.empty()) {
2151 return false;
2154 IsHandshake pending_handshake = visitor_->HasPendingHandshake() ?
2155 IS_HANDSHAKE : NOT_HANDSHAKE;
2156 // Sending queued packets may have caused the socket to become write blocked,
2157 // or the congestion manager to prohibit sending. If we've sent everything
2158 // we had queued and we're still not blocked, let the visitor know it can
2159 // write more.
2160 return ShouldGeneratePacket(HAS_RETRANSMITTABLE_DATA, pending_handshake);
2163 void QuicConnection::SetNetworkTimeouts(QuicTime::Delta overall_timeout,
2164 QuicTime::Delta idle_timeout) {
2165 LOG_IF(DFATAL, idle_timeout > overall_timeout)
2166 << "idle_timeout:" << idle_timeout.ToMilliseconds()
2167 << " overall_timeout:" << overall_timeout.ToMilliseconds();
2168 // Adjust the idle timeout on client and server to prevent clients from
2169 // sending requests to servers which have already closed the connection.
2170 if (perspective_ == Perspective::IS_SERVER) {
2171 idle_timeout = idle_timeout.Add(QuicTime::Delta::FromSeconds(3));
2172 } else if (idle_timeout > QuicTime::Delta::FromSeconds(1)) {
2173 idle_timeout = idle_timeout.Subtract(QuicTime::Delta::FromSeconds(1));
2175 overall_connection_timeout_ = overall_timeout;
2176 idle_network_timeout_ = idle_timeout;
2178 SetTimeoutAlarm();
2181 void QuicConnection::CheckForTimeout() {
2182 QuicTime now = clock_->ApproximateNow();
2183 QuicTime time_of_last_packet = max(time_of_last_received_packet_,
2184 time_of_last_sent_new_packet_);
2186 // |delta| can be < 0 as |now| is approximate time but |time_of_last_packet|
2187 // is accurate time. However, this should not change the behavior of
2188 // timeout handling.
2189 QuicTime::Delta idle_duration = now.Subtract(time_of_last_packet);
2190 DVLOG(1) << ENDPOINT << "last packet "
2191 << time_of_last_packet.ToDebuggingValue()
2192 << " now:" << now.ToDebuggingValue()
2193 << " idle_duration:" << idle_duration.ToMicroseconds()
2194 << " idle_network_timeout: "
2195 << idle_network_timeout_.ToMicroseconds();
2196 if (idle_duration >= idle_network_timeout_) {
2197 DVLOG(1) << ENDPOINT << "Connection timedout due to no network activity.";
2198 SendConnectionClose(QUIC_CONNECTION_TIMED_OUT);
2199 return;
2202 if (!overall_connection_timeout_.IsInfinite()) {
2203 QuicTime::Delta connected_duration =
2204 now.Subtract(stats_.connection_creation_time);
2205 DVLOG(1) << ENDPOINT << "connection time: "
2206 << connected_duration.ToMicroseconds() << " overall timeout: "
2207 << overall_connection_timeout_.ToMicroseconds();
2208 if (connected_duration >= overall_connection_timeout_) {
2209 DVLOG(1) << ENDPOINT <<
2210 "Connection timedout due to overall connection timeout.";
2211 SendConnectionClose(QUIC_CONNECTION_OVERALL_TIMED_OUT);
2212 return;
2216 SetTimeoutAlarm();
2219 void QuicConnection::SetTimeoutAlarm() {
2220 QuicTime time_of_last_packet = max(time_of_last_received_packet_,
2221 time_of_last_sent_new_packet_);
2223 QuicTime deadline = time_of_last_packet.Add(idle_network_timeout_);
2224 if (!overall_connection_timeout_.IsInfinite()) {
2225 deadline = min(deadline,
2226 stats_.connection_creation_time.Add(
2227 overall_connection_timeout_));
2230 timeout_alarm_->Cancel();
2231 timeout_alarm_->Set(deadline);
2234 void QuicConnection::SetPingAlarm() {
2235 if (perspective_ == Perspective::IS_SERVER) {
2236 // Only clients send pings.
2237 return;
2239 if (!visitor_->HasOpenDynamicStreams()) {
2240 ping_alarm_->Cancel();
2241 // Don't send a ping unless there are open streams.
2242 return;
2244 QuicTime::Delta ping_timeout = QuicTime::Delta::FromSeconds(kPingTimeoutSecs);
2245 ping_alarm_->Update(clock_->ApproximateNow().Add(ping_timeout),
2246 QuicTime::Delta::FromSeconds(1));
2249 void QuicConnection::SetRetransmissionAlarm() {
2250 if (delay_setting_retransmission_alarm_) {
2251 pending_retransmission_alarm_ = true;
2252 return;
2254 QuicTime retransmission_time = sent_packet_manager_.GetRetransmissionTime();
2255 retransmission_alarm_->Update(retransmission_time,
2256 QuicTime::Delta::FromMilliseconds(1));
2259 void QuicConnection::MaybeSetMtuAlarm() {
2260 if (!FLAGS_quic_do_path_mtu_discovery) {
2261 return;
2264 // Do not set the alarm if the target size is less than the current size.
2265 // This covers the case when |mtu_discovery_target_| is at its default value,
2266 // zero.
2267 if (mtu_discovery_target_ <= max_packet_length()) {
2268 return;
2271 if (mtu_probe_count_ >= kMtuDiscoveryAttempts) {
2272 return;
2275 if (mtu_discovery_alarm_->IsSet()) {
2276 return;
2279 if (packet_number_of_last_sent_packet_ >= next_mtu_probe_at_) {
2280 // Use an alarm to send the MTU probe to ensure that no ScopedPacketBundlers
2281 // are active.
2282 mtu_discovery_alarm_->Set(clock_->ApproximateNow());
2286 QuicConnection::ScopedPacketBundler::ScopedPacketBundler(
2287 QuicConnection* connection,
2288 AckBundling send_ack)
2289 : connection_(connection),
2290 already_in_batch_mode_(connection != nullptr &&
2291 connection->packet_generator_.InBatchMode()) {
2292 if (connection_ == nullptr) {
2293 return;
2295 // Move generator into batch mode. If caller wants us to include an ack,
2296 // check the delayed-ack timer to see if there's ack info to be sent.
2297 if (!already_in_batch_mode_) {
2298 DVLOG(1) << "Entering Batch Mode.";
2299 connection_->packet_generator_.StartBatchOperations();
2301 // Bundle an ack if the alarm is set or with every second packet if we need to
2302 // raise the peer's least unacked.
2303 bool ack_pending =
2304 connection_->ack_alarm_->IsSet() || connection_->stop_waiting_count_ > 1;
2305 if (send_ack == SEND_ACK || (send_ack == BUNDLE_PENDING_ACK && ack_pending)) {
2306 DVLOG(1) << "Bundling ack with outgoing packet.";
2307 connection_->SendAck();
2311 QuicConnection::ScopedPacketBundler::~ScopedPacketBundler() {
2312 if (connection_ == nullptr) {
2313 return;
2315 // If we changed the generator's batch state, restore original batch state.
2316 if (!already_in_batch_mode_) {
2317 DVLOG(1) << "Leaving Batch Mode.";
2318 connection_->packet_generator_.FinishBatchOperations();
2320 DCHECK_EQ(already_in_batch_mode_,
2321 connection_->packet_generator_.InBatchMode());
2324 QuicConnection::ScopedRetransmissionScheduler::ScopedRetransmissionScheduler(
2325 QuicConnection* connection)
2326 : connection_(connection),
2327 already_delayed_(connection_->delay_setting_retransmission_alarm_) {
2328 connection_->delay_setting_retransmission_alarm_ = true;
2331 QuicConnection::ScopedRetransmissionScheduler::
2332 ~ScopedRetransmissionScheduler() {
2333 if (already_delayed_) {
2334 return;
2336 connection_->delay_setting_retransmission_alarm_ = false;
2337 if (connection_->pending_retransmission_alarm_) {
2338 connection_->SetRetransmissionAlarm();
2339 connection_->pending_retransmission_alarm_ = false;
2343 HasRetransmittableData QuicConnection::IsRetransmittable(
2344 const QueuedPacket& packet) {
2345 // Retransmitted packets retransmittable frames are owned by the unacked
2346 // packet map, but are not present in the serialized packet.
2347 if (packet.transmission_type != NOT_RETRANSMISSION ||
2348 packet.serialized_packet.retransmittable_frames != nullptr) {
2349 return HAS_RETRANSMITTABLE_DATA;
2350 } else {
2351 return NO_RETRANSMITTABLE_DATA;
2355 bool QuicConnection::IsConnectionClose(const QueuedPacket& packet) {
2356 const RetransmittableFrames* retransmittable_frames =
2357 packet.serialized_packet.retransmittable_frames;
2358 if (retransmittable_frames == nullptr) {
2359 return false;
2361 for (const QuicFrame& frame : retransmittable_frames->frames()) {
2362 if (frame.type == CONNECTION_CLOSE_FRAME) {
2363 return true;
2366 return false;
2369 void QuicConnection::SendMtuDiscoveryPacket(QuicByteCount target_mtu) {
2370 // Create a listener for the new probe. The ownership of the listener is
2371 // transferred to the AckNotifierManager. The notifier will get destroyed
2372 // before the connection (because it's stored in one of the connection's
2373 // subfields), hence |this| pointer is guaranteed to stay valid at all times.
2374 scoped_refptr<MtuDiscoveryAckListener> last_mtu_discovery_ack_listener(
2375 new MtuDiscoveryAckListener(this, target_mtu));
2377 // Send the probe.
2378 packet_generator_.GenerateMtuDiscoveryPacket(
2379 target_mtu, last_mtu_discovery_ack_listener.get());
2382 void QuicConnection::DiscoverMtu() {
2383 DCHECK(!mtu_discovery_alarm_->IsSet());
2385 // Chcek if the MTU has been already increased.
2386 if (mtu_discovery_target_ <= max_packet_length()) {
2387 return;
2390 // Schedule the next probe *before* sending the current one. This is
2391 // important, otherwise, when SendMtuDiscoveryPacket() is called,
2392 // MaybeSetMtuAlarm() will not realize that the probe has been just sent, and
2393 // will reschedule this probe again.
2394 packets_between_mtu_probes_ *= 2;
2395 next_mtu_probe_at_ =
2396 packet_number_of_last_sent_packet_ + packets_between_mtu_probes_ + 1;
2397 ++mtu_probe_count_;
2399 DVLOG(2) << "Sending a path MTU discovery packet #" << mtu_probe_count_;
2400 SendMtuDiscoveryPacket(mtu_discovery_target_);
2402 DCHECK(!mtu_discovery_alarm_->IsSet());
2405 } // namespace net