Explicitly add python-numpy dependency to install-build-deps.
[chromium-blink-merge.git] / net / quic / quic_connection.cc
blob62cbc6465ff0d63eb16175c74cc37b7bac355f42
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "net/quic/quic_connection.h"
7 #include <string.h>
8 #include <sys/types.h>
10 #include <algorithm>
11 #include <iterator>
12 #include <limits>
13 #include <memory>
14 #include <set>
15 #include <utility>
17 #include "base/debug/stack_trace.h"
18 #include "base/logging.h"
19 #include "base/stl_util.h"
20 #include "base/strings/stringprintf.h"
21 #include "net/base/net_errors.h"
22 #include "net/quic/crypto/quic_decrypter.h"
23 #include "net/quic/crypto/quic_encrypter.h"
24 #include "net/quic/iovector.h"
25 #include "net/quic/quic_bandwidth.h"
26 #include "net/quic/quic_config.h"
27 #include "net/quic/quic_fec_group.h"
28 #include "net/quic/quic_flags.h"
29 #include "net/quic/quic_utils.h"
31 using base::StringPiece;
32 using base::StringPrintf;
33 using base::hash_map;
34 using base::hash_set;
35 using std::list;
36 using std::make_pair;
37 using std::max;
38 using std::min;
39 using std::numeric_limits;
40 using std::set;
41 using std::string;
42 using std::vector;
44 namespace net {
46 class QuicDecrypter;
47 class QuicEncrypter;
49 namespace {
51 // The largest gap in packets we'll accept without closing the connection.
52 // This will likely have to be tuned.
53 const QuicPacketSequenceNumber kMaxPacketGap = 5000;
55 // Limit the number of FEC groups to two. If we get enough out of order packets
56 // that this becomes limiting, we can revisit.
57 const size_t kMaxFecGroups = 2;
59 // Maximum number of acks received before sending an ack in response.
60 const size_t kMaxPacketsReceivedBeforeAckSend = 20;
62 // Maximum number of tracked packets.
63 const size_t kMaxTrackedPackets = 5 * kMaxTcpCongestionWindow;;
65 bool Near(QuicPacketSequenceNumber a, QuicPacketSequenceNumber b) {
66 QuicPacketSequenceNumber delta = (a > b) ? a - b : b - a;
67 return delta <= kMaxPacketGap;
70 // An alarm that is scheduled to send an ack if a timeout occurs.
71 class AckAlarm : public QuicAlarm::Delegate {
72 public:
73 explicit AckAlarm(QuicConnection* connection)
74 : connection_(connection) {
77 QuicTime OnAlarm() override {
78 connection_->SendAck();
79 return QuicTime::Zero();
82 private:
83 QuicConnection* connection_;
85 DISALLOW_COPY_AND_ASSIGN(AckAlarm);
88 // This alarm will be scheduled any time a data-bearing packet is sent out.
89 // When the alarm goes off, the connection checks to see if the oldest packets
90 // have been acked, and retransmit them if they have not.
91 class RetransmissionAlarm : public QuicAlarm::Delegate {
92 public:
93 explicit RetransmissionAlarm(QuicConnection* connection)
94 : connection_(connection) {
97 QuicTime OnAlarm() override {
98 connection_->OnRetransmissionTimeout();
99 return QuicTime::Zero();
102 private:
103 QuicConnection* connection_;
105 DISALLOW_COPY_AND_ASSIGN(RetransmissionAlarm);
108 // An alarm that is scheduled when the sent scheduler requires a
109 // a delay before sending packets and fires when the packet may be sent.
110 class SendAlarm : public QuicAlarm::Delegate {
111 public:
112 explicit SendAlarm(QuicConnection* connection)
113 : connection_(connection) {
116 QuicTime OnAlarm() override {
117 connection_->WriteIfNotBlocked();
118 // Never reschedule the alarm, since CanWrite does that.
119 return QuicTime::Zero();
122 private:
123 QuicConnection* connection_;
125 DISALLOW_COPY_AND_ASSIGN(SendAlarm);
128 class TimeoutAlarm : public QuicAlarm::Delegate {
129 public:
130 explicit TimeoutAlarm(QuicConnection* connection)
131 : connection_(connection) {
134 QuicTime OnAlarm() override {
135 connection_->CheckForTimeout();
136 // Never reschedule the alarm, since CheckForTimeout does that.
137 return QuicTime::Zero();
140 private:
141 QuicConnection* connection_;
143 DISALLOW_COPY_AND_ASSIGN(TimeoutAlarm);
146 class PingAlarm : public QuicAlarm::Delegate {
147 public:
148 explicit PingAlarm(QuicConnection* connection)
149 : connection_(connection) {
152 QuicTime OnAlarm() override {
153 connection_->SendPing();
154 return QuicTime::Zero();
157 private:
158 QuicConnection* connection_;
160 DISALLOW_COPY_AND_ASSIGN(PingAlarm);
163 } // namespace
165 QuicConnection::QueuedPacket::QueuedPacket(SerializedPacket packet,
166 EncryptionLevel level)
167 : serialized_packet(packet),
168 encryption_level(level),
169 transmission_type(NOT_RETRANSMISSION),
170 original_sequence_number(0) {
173 QuicConnection::QueuedPacket::QueuedPacket(
174 SerializedPacket packet,
175 EncryptionLevel level,
176 TransmissionType transmission_type,
177 QuicPacketSequenceNumber original_sequence_number)
178 : serialized_packet(packet),
179 encryption_level(level),
180 transmission_type(transmission_type),
181 original_sequence_number(original_sequence_number) {
184 #define ENDPOINT (is_server_ ? "Server: " : " Client: ")
186 QuicConnection::QuicConnection(QuicConnectionId connection_id,
187 IPEndPoint address,
188 QuicConnectionHelperInterface* helper,
189 const PacketWriterFactory& writer_factory,
190 bool owns_writer,
191 bool is_server,
192 bool is_secure,
193 const QuicVersionVector& supported_versions)
194 : framer_(supported_versions, helper->GetClock()->ApproximateNow(),
195 is_server),
196 helper_(helper),
197 writer_(writer_factory.Create(this)),
198 owns_writer_(owns_writer),
199 encryption_level_(ENCRYPTION_NONE),
200 has_forward_secure_encrypter_(false),
201 first_required_forward_secure_packet_(0),
202 clock_(helper->GetClock()),
203 random_generator_(helper->GetRandomGenerator()),
204 connection_id_(connection_id),
205 peer_address_(address),
206 migrating_peer_port_(0),
207 last_packet_decrypted_(false),
208 last_packet_revived_(false),
209 last_size_(0),
210 last_decrypted_packet_level_(ENCRYPTION_NONE),
211 largest_seen_packet_with_ack_(0),
212 largest_seen_packet_with_stop_waiting_(0),
213 max_undecryptable_packets_(0),
214 pending_version_negotiation_packet_(false),
215 received_packet_manager_(&stats_),
216 ack_queued_(false),
217 num_packets_received_since_last_ack_sent_(0),
218 stop_waiting_count_(0),
219 ack_alarm_(helper->CreateAlarm(new AckAlarm(this))),
220 retransmission_alarm_(helper->CreateAlarm(new RetransmissionAlarm(this))),
221 send_alarm_(helper->CreateAlarm(new SendAlarm(this))),
222 resume_writes_alarm_(helper->CreateAlarm(new SendAlarm(this))),
223 timeout_alarm_(helper->CreateAlarm(new TimeoutAlarm(this))),
224 ping_alarm_(helper->CreateAlarm(new PingAlarm(this))),
225 packet_generator_(connection_id_, &framer_, random_generator_, this),
226 idle_network_timeout_(QuicTime::Delta::Infinite()),
227 overall_connection_timeout_(QuicTime::Delta::Infinite()),
228 time_of_last_received_packet_(clock_->ApproximateNow()),
229 time_of_last_sent_new_packet_(clock_->ApproximateNow()),
230 sequence_number_of_last_sent_packet_(0),
231 sent_packet_manager_(
232 is_server, clock_, &stats_,
233 FLAGS_quic_use_bbr_congestion_control ? kBBR : kCubic,
234 FLAGS_quic_use_time_loss_detection ? kTime : kNack,
235 is_secure),
236 version_negotiation_state_(START_NEGOTIATION),
237 is_server_(is_server),
238 connected_(true),
239 peer_ip_changed_(false),
240 peer_port_changed_(false),
241 self_ip_changed_(false),
242 self_port_changed_(false),
243 can_truncate_connection_ids_(true),
244 is_secure_(is_secure) {
245 DVLOG(1) << ENDPOINT << "Created connection with connection_id: "
246 << connection_id;
247 framer_.set_visitor(this);
248 framer_.set_received_entropy_calculator(&received_packet_manager_);
249 stats_.connection_creation_time = clock_->ApproximateNow();
250 sent_packet_manager_.set_network_change_visitor(this);
253 QuicConnection::~QuicConnection() {
254 if (owns_writer_) {
255 delete writer_;
257 STLDeleteElements(&undecryptable_packets_);
258 STLDeleteValues(&group_map_);
259 for (QueuedPacketList::iterator it = queued_packets_.begin();
260 it != queued_packets_.end(); ++it) {
261 delete it->serialized_packet.retransmittable_frames;
262 delete it->serialized_packet.packet;
266 void QuicConnection::SetFromConfig(const QuicConfig& config) {
267 if (config.negotiated()) {
268 SetNetworkTimeouts(QuicTime::Delta::Infinite(),
269 config.IdleConnectionStateLifetime());
270 } else {
271 SetNetworkTimeouts(config.max_time_before_crypto_handshake(),
272 config.max_idle_time_before_crypto_handshake());
275 sent_packet_manager_.SetFromConfig(config);
276 if (FLAGS_allow_truncated_connection_ids_for_quic &&
277 config.HasReceivedBytesForConnectionId() &&
278 can_truncate_connection_ids_) {
279 packet_generator_.SetConnectionIdLength(
280 config.ReceivedBytesForConnectionId());
282 max_undecryptable_packets_ = config.max_undecryptable_packets();
285 void QuicConnection::ResumeConnectionState(
286 const CachedNetworkParameters& cached_network_params) {
287 sent_packet_manager_.ResumeConnectionState(cached_network_params);
290 void QuicConnection::SetNumOpenStreams(size_t num_streams) {
291 sent_packet_manager_.SetNumOpenStreams(num_streams);
294 bool QuicConnection::SelectMutualVersion(
295 const QuicVersionVector& available_versions) {
296 // Try to find the highest mutual version by iterating over supported
297 // versions, starting with the highest, and breaking out of the loop once we
298 // find a matching version in the provided available_versions vector.
299 const QuicVersionVector& supported_versions = framer_.supported_versions();
300 for (size_t i = 0; i < supported_versions.size(); ++i) {
301 const QuicVersion& version = supported_versions[i];
302 if (std::find(available_versions.begin(), available_versions.end(),
303 version) != available_versions.end()) {
304 framer_.set_version(version);
305 return true;
309 return false;
312 void QuicConnection::OnError(QuicFramer* framer) {
313 // Packets that we can not or have not decrypted are dropped.
314 // TODO(rch): add stats to measure this.
315 if (FLAGS_quic_drop_junk_packets) {
316 if (!connected_ || last_packet_decrypted_ == false) {
317 return;
319 } else {
320 if (!connected_ || framer->error() == QUIC_DECRYPTION_FAILURE) {
321 return;
324 SendConnectionCloseWithDetails(framer->error(), framer->detailed_error());
327 void QuicConnection::OnPacket() {
328 DCHECK(last_stream_frames_.empty() &&
329 last_ack_frames_.empty() &&
330 last_congestion_frames_.empty() &&
331 last_stop_waiting_frames_.empty() &&
332 last_rst_frames_.empty() &&
333 last_goaway_frames_.empty() &&
334 last_window_update_frames_.empty() &&
335 last_blocked_frames_.empty() &&
336 last_ping_frames_.empty() &&
337 last_close_frames_.empty());
338 last_packet_decrypted_ = false;
339 last_packet_revived_ = false;
342 void QuicConnection::OnPublicResetPacket(
343 const QuicPublicResetPacket& packet) {
344 if (debug_visitor_.get() != nullptr) {
345 debug_visitor_->OnPublicResetPacket(packet);
347 CloseConnection(QUIC_PUBLIC_RESET, true);
349 DVLOG(1) << ENDPOINT << "Connection " << connection_id()
350 << " closed via QUIC_PUBLIC_RESET from peer.";
353 bool QuicConnection::OnProtocolVersionMismatch(QuicVersion received_version) {
354 DVLOG(1) << ENDPOINT << "Received packet with mismatched version "
355 << received_version;
356 // TODO(satyamshekhar): Implement no server state in this mode.
357 if (!is_server_) {
358 LOG(DFATAL) << ENDPOINT << "Framer called OnProtocolVersionMismatch. "
359 << "Closing connection.";
360 CloseConnection(QUIC_INTERNAL_ERROR, false);
361 return false;
363 DCHECK_NE(version(), received_version);
365 if (debug_visitor_.get() != nullptr) {
366 debug_visitor_->OnProtocolVersionMismatch(received_version);
369 switch (version_negotiation_state_) {
370 case START_NEGOTIATION:
371 if (!framer_.IsSupportedVersion(received_version)) {
372 SendVersionNegotiationPacket();
373 version_negotiation_state_ = NEGOTIATION_IN_PROGRESS;
374 return false;
376 break;
378 case NEGOTIATION_IN_PROGRESS:
379 if (!framer_.IsSupportedVersion(received_version)) {
380 SendVersionNegotiationPacket();
381 return false;
383 break;
385 case NEGOTIATED_VERSION:
386 // Might be old packets that were sent by the client before the version
387 // was negotiated. Drop these.
388 return false;
390 default:
391 DCHECK(false);
394 version_negotiation_state_ = NEGOTIATED_VERSION;
395 visitor_->OnSuccessfulVersionNegotiation(received_version);
396 if (debug_visitor_.get() != nullptr) {
397 debug_visitor_->OnSuccessfulVersionNegotiation(received_version);
399 DVLOG(1) << ENDPOINT << "version negotiated " << received_version;
401 // Store the new version.
402 framer_.set_version(received_version);
404 // TODO(satyamshekhar): Store the sequence number of this packet and close the
405 // connection if we ever received a packet with incorrect version and whose
406 // sequence number is greater.
407 return true;
410 // Handles version negotiation for client connection.
411 void QuicConnection::OnVersionNegotiationPacket(
412 const QuicVersionNegotiationPacket& packet) {
413 if (is_server_) {
414 LOG(DFATAL) << ENDPOINT << "Framer parsed VersionNegotiationPacket."
415 << " Closing connection.";
416 CloseConnection(QUIC_INTERNAL_ERROR, false);
417 return;
419 if (debug_visitor_.get() != nullptr) {
420 debug_visitor_->OnVersionNegotiationPacket(packet);
423 if (version_negotiation_state_ != START_NEGOTIATION) {
424 // Possibly a duplicate version negotiation packet.
425 return;
428 if (std::find(packet.versions.begin(),
429 packet.versions.end(), version()) !=
430 packet.versions.end()) {
431 DLOG(WARNING) << ENDPOINT << "The server already supports our version. "
432 << "It should have accepted our connection.";
433 // Just drop the connection.
434 CloseConnection(QUIC_INVALID_VERSION_NEGOTIATION_PACKET, false);
435 return;
438 if (!SelectMutualVersion(packet.versions)) {
439 SendConnectionCloseWithDetails(QUIC_INVALID_VERSION,
440 "no common version found");
441 return;
444 DVLOG(1) << ENDPOINT
445 << "Negotiated version: " << QuicVersionToString(version());
446 server_supported_versions_ = packet.versions;
447 version_negotiation_state_ = NEGOTIATION_IN_PROGRESS;
448 RetransmitUnackedPackets(ALL_UNACKED_RETRANSMISSION);
451 void QuicConnection::OnRevivedPacket() {
454 bool QuicConnection::OnUnauthenticatedPublicHeader(
455 const QuicPacketPublicHeader& header) {
456 return true;
459 bool QuicConnection::OnUnauthenticatedHeader(const QuicPacketHeader& header) {
460 return true;
463 void QuicConnection::OnDecryptedPacket(EncryptionLevel level) {
464 last_decrypted_packet_level_ = level;
465 last_packet_decrypted_ = true;
466 // If this packet was foward-secure encrypted and the forward-secure encrypter
467 // is not being used, start using it.
468 if (FLAGS_enable_quic_delay_forward_security &&
469 encryption_level_ != ENCRYPTION_FORWARD_SECURE &&
470 has_forward_secure_encrypter_ &&
471 level == ENCRYPTION_FORWARD_SECURE) {
472 SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
476 bool QuicConnection::OnPacketHeader(const QuicPacketHeader& header) {
477 if (debug_visitor_.get() != nullptr) {
478 debug_visitor_->OnPacketHeader(header);
481 if (!ProcessValidatedPacket()) {
482 return false;
485 // Will be decrement below if we fall through to return true;
486 ++stats_.packets_dropped;
488 if (header.public_header.connection_id != connection_id_) {
489 DVLOG(1) << ENDPOINT << "Ignoring packet from unexpected ConnectionId: "
490 << header.public_header.connection_id << " instead of "
491 << connection_id_;
492 if (debug_visitor_.get() != nullptr) {
493 debug_visitor_->OnIncorrectConnectionId(
494 header.public_header.connection_id);
496 return false;
499 if (!Near(header.packet_sequence_number,
500 last_header_.packet_sequence_number)) {
501 DVLOG(1) << ENDPOINT << "Packet " << header.packet_sequence_number
502 << " out of bounds. Discarding";
503 SendConnectionCloseWithDetails(QUIC_INVALID_PACKET_HEADER,
504 "Packet sequence number out of bounds");
505 return false;
508 // If this packet has already been seen, or that the sender
509 // has told us will not be retransmitted, then stop processing the packet.
510 if (!received_packet_manager_.IsAwaitingPacket(
511 header.packet_sequence_number)) {
512 DVLOG(1) << ENDPOINT << "Packet " << header.packet_sequence_number
513 << " no longer being waited for. Discarding.";
514 if (debug_visitor_.get() != nullptr) {
515 debug_visitor_->OnDuplicatePacket(header.packet_sequence_number);
517 return false;
520 if (version_negotiation_state_ != NEGOTIATED_VERSION) {
521 if (is_server_) {
522 if (!header.public_header.version_flag) {
523 DLOG(WARNING) << ENDPOINT << "Packet " << header.packet_sequence_number
524 << " without version flag before version negotiated.";
525 // Packets should have the version flag till version negotiation is
526 // done.
527 CloseConnection(QUIC_INVALID_VERSION, false);
528 return false;
529 } else {
530 DCHECK_EQ(1u, header.public_header.versions.size());
531 DCHECK_EQ(header.public_header.versions[0], version());
532 version_negotiation_state_ = NEGOTIATED_VERSION;
533 visitor_->OnSuccessfulVersionNegotiation(version());
534 if (debug_visitor_.get() != nullptr) {
535 debug_visitor_->OnSuccessfulVersionNegotiation(version());
538 } else {
539 DCHECK(!header.public_header.version_flag);
540 // If the client gets a packet without the version flag from the server
541 // it should stop sending version since the version negotiation is done.
542 packet_generator_.StopSendingVersion();
543 version_negotiation_state_ = NEGOTIATED_VERSION;
544 visitor_->OnSuccessfulVersionNegotiation(version());
545 if (debug_visitor_.get() != nullptr) {
546 debug_visitor_->OnSuccessfulVersionNegotiation(version());
551 DCHECK_EQ(NEGOTIATED_VERSION, version_negotiation_state_);
553 --stats_.packets_dropped;
554 DVLOG(1) << ENDPOINT << "Received packet header: " << header;
555 last_header_ = header;
556 DCHECK(connected_);
557 return true;
560 void QuicConnection::OnFecProtectedPayload(StringPiece payload) {
561 DCHECK_EQ(IN_FEC_GROUP, last_header_.is_in_fec_group);
562 DCHECK_NE(0u, last_header_.fec_group);
563 QuicFecGroup* group = GetFecGroup();
564 if (group != nullptr) {
565 group->Update(last_decrypted_packet_level_, last_header_, payload);
569 bool QuicConnection::OnStreamFrame(const QuicStreamFrame& frame) {
570 DCHECK(connected_);
571 if (debug_visitor_.get() != nullptr) {
572 debug_visitor_->OnStreamFrame(frame);
574 if (frame.stream_id != kCryptoStreamId &&
575 last_decrypted_packet_level_ == ENCRYPTION_NONE) {
576 DLOG(WARNING) << ENDPOINT
577 << "Received an unencrypted data frame: closing connection";
578 SendConnectionClose(QUIC_UNENCRYPTED_STREAM_DATA);
579 return false;
581 last_stream_frames_.push_back(frame);
582 return true;
585 bool QuicConnection::OnAckFrame(const QuicAckFrame& incoming_ack) {
586 DCHECK(connected_);
587 if (debug_visitor_.get() != nullptr) {
588 debug_visitor_->OnAckFrame(incoming_ack);
590 DVLOG(1) << ENDPOINT << "OnAckFrame: " << incoming_ack;
592 if (last_header_.packet_sequence_number <= largest_seen_packet_with_ack_) {
593 DVLOG(1) << ENDPOINT << "Received an old ack frame: ignoring";
594 return true;
597 if (!ValidateAckFrame(incoming_ack)) {
598 SendConnectionClose(QUIC_INVALID_ACK_DATA);
599 return false;
602 last_ack_frames_.push_back(incoming_ack);
603 return connected_;
606 void QuicConnection::ProcessAckFrame(const QuicAckFrame& incoming_ack) {
607 largest_seen_packet_with_ack_ = last_header_.packet_sequence_number;
608 sent_packet_manager_.OnIncomingAck(incoming_ack,
609 time_of_last_received_packet_);
610 sent_entropy_manager_.ClearEntropyBefore(
611 sent_packet_manager_.least_packet_awaited_by_peer() - 1);
612 if (sent_packet_manager_.HasPendingRetransmissions()) {
613 WriteIfNotBlocked();
616 // Always reset the retransmission alarm when an ack comes in, since we now
617 // have a better estimate of the current rtt than when it was set.
618 QuicTime retransmission_time = sent_packet_manager_.GetRetransmissionTime();
619 retransmission_alarm_->Update(retransmission_time,
620 QuicTime::Delta::FromMilliseconds(1));
623 void QuicConnection::ProcessStopWaitingFrame(
624 const QuicStopWaitingFrame& stop_waiting) {
625 largest_seen_packet_with_stop_waiting_ = last_header_.packet_sequence_number;
626 received_packet_manager_.UpdatePacketInformationSentByPeer(stop_waiting);
627 // Possibly close any FecGroups which are now irrelevant.
628 CloseFecGroupsBefore(stop_waiting.least_unacked + 1);
631 bool QuicConnection::OnCongestionFeedbackFrame(
632 const QuicCongestionFeedbackFrame& feedback) {
633 DCHECK(connected_);
634 if (debug_visitor_.get() != nullptr) {
635 debug_visitor_->OnCongestionFeedbackFrame(feedback);
637 last_congestion_frames_.push_back(feedback);
638 return connected_;
641 bool QuicConnection::OnStopWaitingFrame(const QuicStopWaitingFrame& frame) {
642 DCHECK(connected_);
644 if (last_header_.packet_sequence_number <=
645 largest_seen_packet_with_stop_waiting_) {
646 DVLOG(1) << ENDPOINT << "Received an old stop waiting frame: ignoring";
647 return true;
650 if (!ValidateStopWaitingFrame(frame)) {
651 SendConnectionClose(QUIC_INVALID_STOP_WAITING_DATA);
652 return false;
655 if (debug_visitor_.get() != nullptr) {
656 debug_visitor_->OnStopWaitingFrame(frame);
659 last_stop_waiting_frames_.push_back(frame);
660 return connected_;
663 bool QuicConnection::OnPingFrame(const QuicPingFrame& frame) {
664 DCHECK(connected_);
665 if (debug_visitor_.get() != nullptr) {
666 debug_visitor_->OnPingFrame(frame);
668 last_ping_frames_.push_back(frame);
669 return true;
672 bool QuicConnection::ValidateAckFrame(const QuicAckFrame& incoming_ack) {
673 if (incoming_ack.largest_observed > packet_generator_.sequence_number()) {
674 DLOG(ERROR) << ENDPOINT << "Peer's observed unsent packet:"
675 << incoming_ack.largest_observed << " vs "
676 << packet_generator_.sequence_number();
677 // We got an error for data we have not sent. Error out.
678 return false;
681 if (incoming_ack.largest_observed < sent_packet_manager_.largest_observed()) {
682 DLOG(ERROR) << ENDPOINT << "Peer's largest_observed packet decreased:"
683 << incoming_ack.largest_observed << " vs "
684 << sent_packet_manager_.largest_observed();
685 // A new ack has a diminished largest_observed value. Error out.
686 // If this was an old packet, we wouldn't even have checked.
687 return false;
690 if (!incoming_ack.missing_packets.empty() &&
691 *incoming_ack.missing_packets.rbegin() > incoming_ack.largest_observed) {
692 DLOG(ERROR) << ENDPOINT << "Peer sent missing packet: "
693 << *incoming_ack.missing_packets.rbegin()
694 << " which is greater than largest observed: "
695 << incoming_ack.largest_observed;
696 return false;
699 if (!incoming_ack.missing_packets.empty() &&
700 *incoming_ack.missing_packets.begin() <
701 sent_packet_manager_.least_packet_awaited_by_peer()) {
702 DLOG(ERROR) << ENDPOINT << "Peer sent missing packet: "
703 << *incoming_ack.missing_packets.begin()
704 << " which is smaller than least_packet_awaited_by_peer_: "
705 << sent_packet_manager_.least_packet_awaited_by_peer();
706 return false;
709 if (!sent_entropy_manager_.IsValidEntropy(
710 incoming_ack.largest_observed,
711 incoming_ack.missing_packets,
712 incoming_ack.entropy_hash)) {
713 DLOG(ERROR) << ENDPOINT << "Peer sent invalid entropy.";
714 return false;
717 for (SequenceNumberSet::const_iterator iter =
718 incoming_ack.revived_packets.begin();
719 iter != incoming_ack.revived_packets.end(); ++iter) {
720 if (!ContainsKey(incoming_ack.missing_packets, *iter)) {
721 DLOG(ERROR) << ENDPOINT
722 << "Peer specified revived packet which was not missing.";
723 return false;
726 return true;
729 bool QuicConnection::ValidateStopWaitingFrame(
730 const QuicStopWaitingFrame& stop_waiting) {
731 if (stop_waiting.least_unacked <
732 received_packet_manager_.peer_least_packet_awaiting_ack()) {
733 DLOG(ERROR) << ENDPOINT << "Peer's sent low least_unacked: "
734 << stop_waiting.least_unacked << " vs "
735 << received_packet_manager_.peer_least_packet_awaiting_ack();
736 // We never process old ack frames, so this number should only increase.
737 return false;
740 if (stop_waiting.least_unacked >
741 last_header_.packet_sequence_number) {
742 DLOG(ERROR) << ENDPOINT << "Peer sent least_unacked:"
743 << stop_waiting.least_unacked
744 << " greater than the enclosing packet sequence number:"
745 << last_header_.packet_sequence_number;
746 return false;
749 return true;
752 void QuicConnection::OnFecData(const QuicFecData& fec) {
753 DCHECK_EQ(IN_FEC_GROUP, last_header_.is_in_fec_group);
754 DCHECK_NE(0u, last_header_.fec_group);
755 QuicFecGroup* group = GetFecGroup();
756 if (group != nullptr) {
757 group->UpdateFec(last_decrypted_packet_level_,
758 last_header_.packet_sequence_number, fec);
762 bool QuicConnection::OnRstStreamFrame(const QuicRstStreamFrame& frame) {
763 DCHECK(connected_);
764 if (debug_visitor_.get() != nullptr) {
765 debug_visitor_->OnRstStreamFrame(frame);
767 DVLOG(1) << ENDPOINT << "Stream reset with error "
768 << QuicUtils::StreamErrorToString(frame.error_code);
769 last_rst_frames_.push_back(frame);
770 return connected_;
773 bool QuicConnection::OnConnectionCloseFrame(
774 const QuicConnectionCloseFrame& frame) {
775 DCHECK(connected_);
776 if (debug_visitor_.get() != nullptr) {
777 debug_visitor_->OnConnectionCloseFrame(frame);
779 DVLOG(1) << ENDPOINT << "Connection " << connection_id()
780 << " closed with error "
781 << QuicUtils::ErrorToString(frame.error_code)
782 << " " << frame.error_details;
783 last_close_frames_.push_back(frame);
784 return connected_;
787 bool QuicConnection::OnGoAwayFrame(const QuicGoAwayFrame& frame) {
788 DCHECK(connected_);
789 if (debug_visitor_.get() != nullptr) {
790 debug_visitor_->OnGoAwayFrame(frame);
792 DVLOG(1) << ENDPOINT << "Go away received with error "
793 << QuicUtils::ErrorToString(frame.error_code)
794 << " and reason:" << frame.reason_phrase;
795 last_goaway_frames_.push_back(frame);
796 return connected_;
799 bool QuicConnection::OnWindowUpdateFrame(const QuicWindowUpdateFrame& frame) {
800 DCHECK(connected_);
801 if (debug_visitor_.get() != nullptr) {
802 debug_visitor_->OnWindowUpdateFrame(frame);
804 DVLOG(1) << ENDPOINT << "WindowUpdate received for stream: "
805 << frame.stream_id << " with byte offset: " << frame.byte_offset;
806 last_window_update_frames_.push_back(frame);
807 return connected_;
810 bool QuicConnection::OnBlockedFrame(const QuicBlockedFrame& frame) {
811 DCHECK(connected_);
812 if (debug_visitor_.get() != nullptr) {
813 debug_visitor_->OnBlockedFrame(frame);
815 DVLOG(1) << ENDPOINT << "Blocked frame received for stream: "
816 << frame.stream_id;
817 last_blocked_frames_.push_back(frame);
818 return connected_;
821 void QuicConnection::OnPacketComplete() {
822 // Don't do anything if this packet closed the connection.
823 if (!connected_) {
824 ClearLastFrames();
825 return;
828 DVLOG(1) << ENDPOINT << (last_packet_revived_ ? "Revived" : "Got")
829 << " packet " << last_header_.packet_sequence_number
830 << " with " << last_stream_frames_.size()<< " stream frames "
831 << last_ack_frames_.size() << " acks, "
832 << last_congestion_frames_.size() << " congestions, "
833 << last_stop_waiting_frames_.size() << " stop_waiting, "
834 << last_rst_frames_.size() << " rsts, "
835 << last_goaway_frames_.size() << " goaways, "
836 << last_window_update_frames_.size() << " window updates, "
837 << last_blocked_frames_.size() << " blocked, "
838 << last_ping_frames_.size() << " pings, "
839 << last_close_frames_.size() << " closes, "
840 << "for " << last_header_.public_header.connection_id;
842 ++num_packets_received_since_last_ack_sent_;
844 // Call MaybeQueueAck() before recording the received packet, since we want
845 // to trigger an ack if the newly received packet was previously missing.
846 MaybeQueueAck();
848 // Record received or revived packet to populate ack info correctly before
849 // processing stream frames, since the processing may result in a response
850 // packet with a bundled ack.
851 if (last_packet_revived_) {
852 received_packet_manager_.RecordPacketRevived(
853 last_header_.packet_sequence_number);
854 } else {
855 received_packet_manager_.RecordPacketReceived(
856 last_size_, last_header_, time_of_last_received_packet_);
859 if (!last_stream_frames_.empty()) {
860 visitor_->OnStreamFrames(last_stream_frames_);
863 for (size_t i = 0; i < last_stream_frames_.size(); ++i) {
864 stats_.stream_bytes_received +=
865 last_stream_frames_[i].data.TotalBufferSize();
868 // Process window updates, blocked, stream resets, acks, then congestion
869 // feedback.
870 if (!last_window_update_frames_.empty()) {
871 visitor_->OnWindowUpdateFrames(last_window_update_frames_);
873 if (!last_blocked_frames_.empty()) {
874 visitor_->OnBlockedFrames(last_blocked_frames_);
876 for (size_t i = 0; i < last_goaway_frames_.size(); ++i) {
877 visitor_->OnGoAway(last_goaway_frames_[i]);
879 for (size_t i = 0; i < last_rst_frames_.size(); ++i) {
880 visitor_->OnRstStream(last_rst_frames_[i]);
882 for (size_t i = 0; i < last_ack_frames_.size(); ++i) {
883 ProcessAckFrame(last_ack_frames_[i]);
885 for (size_t i = 0; i < last_congestion_frames_.size(); ++i) {
886 sent_packet_manager_.OnIncomingQuicCongestionFeedbackFrame(
887 last_congestion_frames_[i], time_of_last_received_packet_);
889 for (size_t i = 0; i < last_stop_waiting_frames_.size(); ++i) {
890 ProcessStopWaitingFrame(last_stop_waiting_frames_[i]);
892 if (!last_close_frames_.empty()) {
893 CloseConnection(last_close_frames_[0].error_code, true);
894 DCHECK(!connected_);
897 // If there are new missing packets to report, send an ack immediately.
898 if (received_packet_manager_.HasNewMissingPackets()) {
899 ack_queued_ = true;
900 ack_alarm_->Cancel();
903 UpdateStopWaitingCount();
904 ClearLastFrames();
905 MaybeCloseIfTooManyOutstandingPackets();
908 void QuicConnection::MaybeQueueAck() {
909 // If the incoming packet was missing, send an ack immediately.
910 ack_queued_ = received_packet_manager_.IsMissing(
911 last_header_.packet_sequence_number);
913 if (!ack_queued_ && ShouldLastPacketInstigateAck()) {
914 if (ack_alarm_->IsSet()) {
915 ack_queued_ = true;
916 } else {
917 // Send an ack much more quickly for crypto handshake packets.
918 QuicTime::Delta delayed_ack_time = sent_packet_manager_.DelayedAckTime();
919 ack_alarm_->Set(clock_->ApproximateNow().Add(delayed_ack_time));
920 DVLOG(1) << "Ack timer set; next packet or timer will trigger ACK.";
924 if (ack_queued_) {
925 ack_alarm_->Cancel();
929 void QuicConnection::ClearLastFrames() {
930 last_stream_frames_.clear();
931 last_ack_frames_.clear();
932 last_congestion_frames_.clear();
933 last_stop_waiting_frames_.clear();
934 last_rst_frames_.clear();
935 last_goaway_frames_.clear();
936 last_window_update_frames_.clear();
937 last_blocked_frames_.clear();
938 last_ping_frames_.clear();
939 last_close_frames_.clear();
942 void QuicConnection::MaybeCloseIfTooManyOutstandingPackets() {
943 if (!FLAGS_quic_too_many_outstanding_packets) {
944 return;
946 // This occurs if we don't discard old packets we've sent fast enough.
947 // It's possible largest observed is less than least unacked.
948 if (sent_packet_manager_.largest_observed() >
949 (sent_packet_manager_.GetLeastUnacked() + kMaxTrackedPackets)) {
950 SendConnectionCloseWithDetails(
951 QUIC_TOO_MANY_OUTSTANDING_SENT_PACKETS,
952 StringPrintf("More than %zu outstanding.", kMaxTrackedPackets));
954 // This occurs if there are received packet gaps and the peer does not raise
955 // the least unacked fast enough.
956 if (received_packet_manager_.NumTrackedPackets() > kMaxTrackedPackets) {
957 SendConnectionCloseWithDetails(
958 QUIC_TOO_MANY_OUTSTANDING_RECEIVED_PACKETS,
959 StringPrintf("More than %zu outstanding.", kMaxTrackedPackets));
963 QuicAckFrame* QuicConnection::CreateAckFrame() {
964 QuicAckFrame* outgoing_ack = new QuicAckFrame();
965 received_packet_manager_.UpdateReceivedPacketInfo(
966 outgoing_ack, clock_->ApproximateNow());
967 DVLOG(1) << ENDPOINT << "Creating ack frame: " << *outgoing_ack;
968 return outgoing_ack;
971 QuicCongestionFeedbackFrame* QuicConnection::CreateFeedbackFrame() {
972 return new QuicCongestionFeedbackFrame(outgoing_congestion_feedback_);
975 QuicStopWaitingFrame* QuicConnection::CreateStopWaitingFrame() {
976 QuicStopWaitingFrame stop_waiting;
977 UpdateStopWaiting(&stop_waiting);
978 return new QuicStopWaitingFrame(stop_waiting);
981 bool QuicConnection::ShouldLastPacketInstigateAck() const {
982 if (!last_stream_frames_.empty() ||
983 !last_goaway_frames_.empty() ||
984 !last_rst_frames_.empty() ||
985 !last_window_update_frames_.empty() ||
986 !last_blocked_frames_.empty() ||
987 !last_ping_frames_.empty()) {
988 return true;
991 if (!last_ack_frames_.empty() && last_ack_frames_.back().is_truncated) {
992 return true;
994 // Always send an ack every 20 packets in order to allow the peer to discard
995 // information from the SentPacketManager and provide an RTT measurement.
996 if (num_packets_received_since_last_ack_sent_ >=
997 kMaxPacketsReceivedBeforeAckSend) {
998 return true;
1000 return false;
1003 void QuicConnection::UpdateStopWaitingCount() {
1004 if (last_ack_frames_.empty()) {
1005 return;
1008 // If the peer is still waiting for a packet that we are no longer planning to
1009 // send, send an ack to raise the high water mark.
1010 if (!last_ack_frames_.back().missing_packets.empty() &&
1011 GetLeastUnacked() > *last_ack_frames_.back().missing_packets.begin()) {
1012 ++stop_waiting_count_;
1013 } else {
1014 stop_waiting_count_ = 0;
1018 QuicPacketSequenceNumber QuicConnection::GetLeastUnacked() const {
1019 return sent_packet_manager_.GetLeastUnacked();
1022 void QuicConnection::MaybeSendInResponseToPacket() {
1023 if (!connected_) {
1024 return;
1026 ScopedPacketBundler bundler(this, ack_queued_ ? SEND_ACK : NO_ACK);
1028 // Now that we have received an ack, we might be able to send packets which
1029 // are queued locally, or drain streams which are blocked.
1030 if (CanWrite(HAS_RETRANSMITTABLE_DATA)) {
1031 OnCanWrite();
1035 void QuicConnection::SendVersionNegotiationPacket() {
1036 // TODO(alyssar): implement zero server state negotiation.
1037 pending_version_negotiation_packet_ = true;
1038 if (writer_->IsWriteBlocked()) {
1039 visitor_->OnWriteBlocked();
1040 return;
1042 DVLOG(1) << ENDPOINT << "Sending version negotiation packet: {"
1043 << QuicVersionVectorToString(framer_.supported_versions()) << "}";
1044 scoped_ptr<QuicEncryptedPacket> version_packet(
1045 packet_generator_.SerializeVersionNegotiationPacket(
1046 framer_.supported_versions()));
1047 WriteResult result = writer_->WritePacket(
1048 version_packet->data(), version_packet->length(),
1049 self_address().address(), peer_address());
1051 if (result.status == WRITE_STATUS_ERROR) {
1052 // We can't send an error as the socket is presumably borked.
1053 CloseConnection(QUIC_PACKET_WRITE_ERROR, false);
1054 return;
1056 if (result.status == WRITE_STATUS_BLOCKED) {
1057 visitor_->OnWriteBlocked();
1058 if (writer_->IsWriteBlockedDataBuffered()) {
1059 pending_version_negotiation_packet_ = false;
1061 return;
1064 pending_version_negotiation_packet_ = false;
1067 QuicConsumedData QuicConnection::SendStreamData(
1068 QuicStreamId id,
1069 const IOVector& data,
1070 QuicStreamOffset offset,
1071 bool fin,
1072 FecProtection fec_protection,
1073 QuicAckNotifier::DelegateInterface* delegate) {
1074 if (!fin && data.Empty()) {
1075 LOG(DFATAL) << "Attempt to send empty stream frame";
1078 // This notifier will be owned by the AckNotifierManager (or deleted below if
1079 // no data or FIN was consumed).
1080 QuicAckNotifier* notifier = nullptr;
1081 if (delegate) {
1082 notifier = new QuicAckNotifier(delegate);
1085 // Opportunistically bundle an ack with every outgoing packet.
1086 // Particularly, we want to bundle with handshake packets since we don't know
1087 // which decrypter will be used on an ack packet following a handshake
1088 // packet (a handshake packet from client to server could result in a REJ or a
1089 // SHLO from the server, leading to two different decrypters at the server.)
1091 // TODO(jri): Note that ConsumeData may cause a response packet to be sent.
1092 // We may end up sending stale ack information if there are undecryptable
1093 // packets hanging around and/or there are revivable packets which may get
1094 // handled after this packet is sent. Change ScopedPacketBundler to do the
1095 // right thing: check ack_queued_, and then check undecryptable packets and
1096 // also if there is possibility of revival. Only bundle an ack if there's no
1097 // processing left that may cause received_info_ to change.
1098 ScopedPacketBundler ack_bundler(this, BUNDLE_PENDING_ACK);
1099 QuicConsumedData consumed_data =
1100 packet_generator_.ConsumeData(id, data, offset, fin, fec_protection,
1101 notifier);
1103 if (notifier &&
1104 (consumed_data.bytes_consumed == 0 && !consumed_data.fin_consumed)) {
1105 // No data was consumed, nor was a fin consumed, so delete the notifier.
1106 delete notifier;
1109 return consumed_data;
1112 void QuicConnection::SendRstStream(QuicStreamId id,
1113 QuicRstStreamErrorCode error,
1114 QuicStreamOffset bytes_written) {
1115 // Opportunistically bundle an ack with this outgoing packet.
1116 ScopedPacketBundler ack_bundler(this, BUNDLE_PENDING_ACK);
1117 packet_generator_.AddControlFrame(QuicFrame(new QuicRstStreamFrame(
1118 id, AdjustErrorForVersion(error, version()), bytes_written)));
1121 void QuicConnection::SendWindowUpdate(QuicStreamId id,
1122 QuicStreamOffset byte_offset) {
1123 // Opportunistically bundle an ack with this outgoing packet.
1124 ScopedPacketBundler ack_bundler(this, BUNDLE_PENDING_ACK);
1125 packet_generator_.AddControlFrame(
1126 QuicFrame(new QuicWindowUpdateFrame(id, byte_offset)));
1129 void QuicConnection::SendBlocked(QuicStreamId id) {
1130 // Opportunistically bundle an ack with this outgoing packet.
1131 ScopedPacketBundler ack_bundler(this, BUNDLE_PENDING_ACK);
1132 packet_generator_.AddControlFrame(QuicFrame(new QuicBlockedFrame(id)));
1135 const QuicConnectionStats& QuicConnection::GetStats() {
1136 // Update rtt and estimated bandwidth.
1137 stats_.min_rtt_us =
1138 sent_packet_manager_.GetRttStats()->min_rtt().ToMicroseconds();
1139 stats_.srtt_us =
1140 sent_packet_manager_.GetRttStats()->smoothed_rtt().ToMicroseconds();
1141 stats_.estimated_bandwidth =
1142 sent_packet_manager_.BandwidthEstimate().ToBytesPerSecond();
1143 stats_.max_packet_size = packet_generator_.max_packet_length();
1144 return stats_;
1147 void QuicConnection::ProcessUdpPacket(const IPEndPoint& self_address,
1148 const IPEndPoint& peer_address,
1149 const QuicEncryptedPacket& packet) {
1150 if (!connected_) {
1151 return;
1153 if (debug_visitor_.get() != nullptr) {
1154 debug_visitor_->OnPacketReceived(self_address, peer_address, packet);
1156 last_size_ = packet.length();
1158 CheckForAddressMigration(self_address, peer_address);
1160 stats_.bytes_received += packet.length();
1161 ++stats_.packets_received;
1163 if (!framer_.ProcessPacket(packet)) {
1164 // If we are unable to decrypt this packet, it might be
1165 // because the CHLO or SHLO packet was lost.
1166 if (framer_.error() == QUIC_DECRYPTION_FAILURE) {
1167 if (encryption_level_ != ENCRYPTION_FORWARD_SECURE &&
1168 undecryptable_packets_.size() < max_undecryptable_packets_) {
1169 QueueUndecryptablePacket(packet);
1170 } else if (debug_visitor_.get() != nullptr) {
1171 debug_visitor_->OnUndecryptablePacket();
1174 DVLOG(1) << ENDPOINT << "Unable to process packet. Last packet processed: "
1175 << last_header_.packet_sequence_number;
1176 return;
1179 ++stats_.packets_processed;
1180 MaybeProcessUndecryptablePackets();
1181 MaybeProcessRevivedPacket();
1182 MaybeSendInResponseToPacket();
1183 SetPingAlarm();
1186 void QuicConnection::CheckForAddressMigration(
1187 const IPEndPoint& self_address, const IPEndPoint& peer_address) {
1188 peer_ip_changed_ = false;
1189 peer_port_changed_ = false;
1190 self_ip_changed_ = false;
1191 self_port_changed_ = false;
1193 if (peer_address_.address().empty()) {
1194 peer_address_ = peer_address;
1196 if (self_address_.address().empty()) {
1197 self_address_ = self_address;
1200 if (!peer_address.address().empty() && !peer_address_.address().empty()) {
1201 peer_ip_changed_ = (peer_address.address() != peer_address_.address());
1202 peer_port_changed_ = (peer_address.port() != peer_address_.port());
1204 // Store in case we want to migrate connection in ProcessValidatedPacket.
1205 migrating_peer_port_ = peer_address.port();
1208 if (!self_address.address().empty() && !self_address_.address().empty()) {
1209 self_ip_changed_ = (self_address.address() != self_address_.address());
1210 self_port_changed_ = (self_address.port() != self_address_.port());
1214 void QuicConnection::OnCanWrite() {
1215 DCHECK(!writer_->IsWriteBlocked());
1217 WriteQueuedPackets();
1218 WritePendingRetransmissions();
1220 // Sending queued packets may have caused the socket to become write blocked,
1221 // or the congestion manager to prohibit sending. If we've sent everything
1222 // we had queued and we're still not blocked, let the visitor know it can
1223 // write more.
1224 if (!CanWrite(HAS_RETRANSMITTABLE_DATA)) {
1225 return;
1228 { // Limit the scope of the bundler. ACK inclusion happens elsewhere.
1229 ScopedPacketBundler bundler(this, NO_ACK);
1230 visitor_->OnCanWrite();
1233 // After the visitor writes, it may have caused the socket to become write
1234 // blocked or the congestion manager to prohibit sending, so check again.
1235 if (visitor_->WillingAndAbleToWrite() &&
1236 !resume_writes_alarm_->IsSet() &&
1237 CanWrite(HAS_RETRANSMITTABLE_DATA)) {
1238 // We're not write blocked, but some stream didn't write out all of its
1239 // bytes. Register for 'immediate' resumption so we'll keep writing after
1240 // other connections and events have had a chance to use the thread.
1241 resume_writes_alarm_->Set(clock_->ApproximateNow());
1245 void QuicConnection::WriteIfNotBlocked() {
1246 if (!writer_->IsWriteBlocked()) {
1247 OnCanWrite();
1251 bool QuicConnection::ProcessValidatedPacket() {
1252 if (peer_ip_changed_ || self_ip_changed_ || self_port_changed_) {
1253 SendConnectionCloseWithDetails(
1254 QUIC_ERROR_MIGRATING_ADDRESS,
1255 "Neither IP address migration, nor self port migration are supported.");
1256 return false;
1259 // Peer port migration is supported, do it now if port has changed.
1260 if (peer_port_changed_) {
1261 DVLOG(1) << ENDPOINT << "Peer's port changed from "
1262 << peer_address_.port() << " to " << migrating_peer_port_
1263 << ", migrating connection.";
1264 peer_address_ = IPEndPoint(peer_address_.address(), migrating_peer_port_);
1267 time_of_last_received_packet_ = clock_->Now();
1268 DVLOG(1) << ENDPOINT << "time of last received packet: "
1269 << time_of_last_received_packet_.ToDebuggingValue();
1271 if (is_server_ && encryption_level_ == ENCRYPTION_NONE &&
1272 last_size_ > packet_generator_.max_packet_length()) {
1273 set_max_packet_length(last_size_);
1275 return true;
1278 void QuicConnection::WriteQueuedPackets() {
1279 DCHECK(!writer_->IsWriteBlocked());
1281 if (pending_version_negotiation_packet_) {
1282 SendVersionNegotiationPacket();
1285 QueuedPacketList::iterator packet_iterator = queued_packets_.begin();
1286 while (packet_iterator != queued_packets_.end() &&
1287 WritePacket(&(*packet_iterator))) {
1288 packet_iterator = queued_packets_.erase(packet_iterator);
1292 void QuicConnection::WritePendingRetransmissions() {
1293 // Keep writing as long as there's a pending retransmission which can be
1294 // written.
1295 while (sent_packet_manager_.HasPendingRetransmissions()) {
1296 const QuicSentPacketManager::PendingRetransmission pending =
1297 sent_packet_manager_.NextPendingRetransmission();
1298 if (!CanWrite(HAS_RETRANSMITTABLE_DATA)) {
1299 break;
1302 // Re-packetize the frames with a new sequence number for retransmission.
1303 // Retransmitted data packets do not use FEC, even when it's enabled.
1304 // Retransmitted packets use the same sequence number length as the
1305 // original.
1306 // Flush the packet generator before making a new packet.
1307 // TODO(ianswett): Implement ReserializeAllFrames as a separate path that
1308 // does not require the creator to be flushed.
1309 packet_generator_.FlushAllQueuedFrames();
1310 SerializedPacket serialized_packet = packet_generator_.ReserializeAllFrames(
1311 pending.retransmittable_frames.frames(),
1312 pending.sequence_number_length);
1314 DVLOG(1) << ENDPOINT << "Retransmitting " << pending.sequence_number
1315 << " as " << serialized_packet.sequence_number;
1316 SendOrQueuePacket(
1317 QueuedPacket(serialized_packet,
1318 pending.retransmittable_frames.encryption_level(),
1319 pending.transmission_type,
1320 pending.sequence_number));
1324 void QuicConnection::RetransmitUnackedPackets(
1325 TransmissionType retransmission_type) {
1326 sent_packet_manager_.RetransmitUnackedPackets(retransmission_type);
1328 WriteIfNotBlocked();
1331 void QuicConnection::NeuterUnencryptedPackets() {
1332 sent_packet_manager_.NeuterUnencryptedPackets();
1333 // This may have changed the retransmission timer, so re-arm it.
1334 QuicTime retransmission_time = sent_packet_manager_.GetRetransmissionTime();
1335 retransmission_alarm_->Update(retransmission_time,
1336 QuicTime::Delta::FromMilliseconds(1));
1339 bool QuicConnection::ShouldGeneratePacket(
1340 TransmissionType transmission_type,
1341 HasRetransmittableData retransmittable,
1342 IsHandshake handshake) {
1343 // We should serialize handshake packets immediately to ensure that they
1344 // end up sent at the right encryption level.
1345 if (handshake == IS_HANDSHAKE) {
1346 return true;
1349 return CanWrite(retransmittable);
1352 bool QuicConnection::CanWrite(HasRetransmittableData retransmittable) {
1353 if (!connected_) {
1354 return false;
1357 if (writer_->IsWriteBlocked()) {
1358 visitor_->OnWriteBlocked();
1359 return false;
1362 QuicTime now = clock_->Now();
1363 QuicTime::Delta delay = sent_packet_manager_.TimeUntilSend(
1364 now, retransmittable);
1365 if (delay.IsInfinite()) {
1366 send_alarm_->Cancel();
1367 return false;
1370 // If the scheduler requires a delay, then we can not send this packet now.
1371 if (!delay.IsZero()) {
1372 send_alarm_->Update(now.Add(delay), QuicTime::Delta::FromMilliseconds(1));
1373 DVLOG(1) << ENDPOINT << "Delaying sending " << delay.ToMilliseconds()
1374 << "ms";
1375 return false;
1377 send_alarm_->Cancel();
1378 return true;
1381 bool QuicConnection::WritePacket(QueuedPacket* packet) {
1382 if (!WritePacketInner(packet)) {
1383 return false;
1385 delete packet->serialized_packet.retransmittable_frames;
1386 delete packet->serialized_packet.packet;
1387 packet->serialized_packet.retransmittable_frames = nullptr;
1388 packet->serialized_packet.packet = nullptr;
1389 return true;
1392 bool QuicConnection::WritePacketInner(QueuedPacket* packet) {
1393 if (ShouldDiscardPacket(*packet)) {
1394 ++stats_.packets_discarded;
1395 return true;
1397 // Connection close packets are encrypted and saved, so don't exit early.
1398 if (writer_->IsWriteBlocked() && !IsConnectionClose(*packet)) {
1399 return false;
1402 QuicPacketSequenceNumber sequence_number =
1403 packet->serialized_packet.sequence_number;
1404 DCHECK_LE(sequence_number_of_last_sent_packet_, sequence_number);
1405 sequence_number_of_last_sent_packet_ = sequence_number;
1407 QuicEncryptedPacket* encrypted = framer_.EncryptPacket(
1408 packet->encryption_level,
1409 sequence_number,
1410 *packet->serialized_packet.packet);
1411 if (encrypted == nullptr) {
1412 LOG(DFATAL) << ENDPOINT << "Failed to encrypt packet number "
1413 << sequence_number;
1414 // CloseConnection does not send close packet, so no infinite loop here.
1415 CloseConnection(QUIC_ENCRYPTION_FAILURE, false);
1416 return false;
1419 // Connection close packets are eventually owned by TimeWaitListManager.
1420 // Others are deleted at the end of this call.
1421 scoped_ptr<QuicEncryptedPacket> encrypted_deleter;
1422 if (IsConnectionClose(*packet)) {
1423 DCHECK(connection_close_packet_.get() == nullptr);
1424 connection_close_packet_.reset(encrypted);
1425 // This assures we won't try to write *forced* packets when blocked.
1426 // Return true to stop processing.
1427 if (writer_->IsWriteBlocked()) {
1428 visitor_->OnWriteBlocked();
1429 return true;
1431 } else {
1432 encrypted_deleter.reset(encrypted);
1435 if (!FLAGS_quic_allow_oversized_packets_for_test) {
1436 DCHECK_LE(encrypted->length(), kMaxPacketSize);
1438 DCHECK_LE(encrypted->length(), packet_generator_.max_packet_length());
1439 DVLOG(1) << ENDPOINT << "Sending packet " << sequence_number << " : "
1440 << (packet->serialized_packet.packet->is_fec_packet() ? "FEC " :
1441 (IsRetransmittable(*packet) == HAS_RETRANSMITTABLE_DATA
1442 ? "data bearing " : " ack only "))
1443 << ", encryption level: "
1444 << QuicUtils::EncryptionLevelToString(packet->encryption_level)
1445 << ", length:"
1446 << packet->serialized_packet.packet->length()
1447 << ", encrypted length:"
1448 << encrypted->length();
1449 DVLOG(2) << ENDPOINT << "packet(" << sequence_number << "): " << std::endl
1450 << QuicUtils::StringToHexASCIIDump(
1451 packet->serialized_packet.packet->AsStringPiece());
1453 QuicTime packet_send_time = QuicTime::Zero();
1454 if (FLAGS_quic_record_send_time_before_write) {
1455 // Measure the RTT from before the write begins to avoid underestimating the
1456 // min_rtt_, especially in cases where the thread blocks or gets swapped out
1457 // during the WritePacket below.
1458 packet_send_time = clock_->Now();
1460 WriteResult result = writer_->WritePacket(encrypted->data(),
1461 encrypted->length(),
1462 self_address().address(),
1463 peer_address());
1464 if (result.error_code == ERR_IO_PENDING) {
1465 DCHECK_EQ(WRITE_STATUS_BLOCKED, result.status);
1468 if (result.status == WRITE_STATUS_BLOCKED) {
1469 visitor_->OnWriteBlocked();
1470 // If the socket buffers the the data, then the packet should not
1471 // be queued and sent again, which would result in an unnecessary
1472 // duplicate packet being sent. The helper must call OnCanWrite
1473 // when the write completes, and OnWriteError if an error occurs.
1474 if (!writer_->IsWriteBlockedDataBuffered()) {
1475 return false;
1478 if (!FLAGS_quic_record_send_time_before_write) {
1479 packet_send_time = clock_->Now();
1481 if (!packet_send_time.IsInitialized()) {
1482 // TODO(jokulik): This is only needed because of the two code paths for
1483 // initializing packet_send_time. Once "quic_record_send_time_before_write"
1484 // is deprecated, this check can be removed.
1485 LOG(DFATAL) << "The packet send time should never be zero. "
1486 << "This is a programming bug, please report it.";
1488 if (result.status != WRITE_STATUS_ERROR && debug_visitor_.get() != nullptr) {
1489 // Pass the write result to the visitor.
1490 debug_visitor_->OnPacketSent(packet->serialized_packet,
1491 packet->original_sequence_number,
1492 packet->encryption_level,
1493 packet->transmission_type,
1494 *encrypted,
1495 packet_send_time);
1497 if (packet->transmission_type == NOT_RETRANSMISSION) {
1498 time_of_last_sent_new_packet_ = packet_send_time;
1500 SetPingAlarm();
1501 DVLOG(1) << ENDPOINT << "time "
1502 << (FLAGS_quic_record_send_time_before_write ?
1503 "we began writing " : "we finished writing ")
1504 << "last sent packet: "
1505 << packet_send_time.ToDebuggingValue();
1507 // TODO(ianswett): Change the sequence number length and other packet creator
1508 // options by a more explicit API than setting a struct value directly,
1509 // perhaps via the NetworkChangeVisitor.
1510 packet_generator_.UpdateSequenceNumberLength(
1511 sent_packet_manager_.least_packet_awaited_by_peer(),
1512 sent_packet_manager_.EstimateMaxPacketsInFlight(max_packet_length()));
1514 bool reset_retransmission_alarm = sent_packet_manager_.OnPacketSent(
1515 &packet->serialized_packet,
1516 packet->original_sequence_number,
1517 packet_send_time,
1518 encrypted->length(),
1519 packet->transmission_type,
1520 IsRetransmittable(*packet));
1522 if (reset_retransmission_alarm || !retransmission_alarm_->IsSet()) {
1523 retransmission_alarm_->Update(sent_packet_manager_.GetRetransmissionTime(),
1524 QuicTime::Delta::FromMilliseconds(1));
1527 stats_.bytes_sent += result.bytes_written;
1528 ++stats_.packets_sent;
1529 if (packet->transmission_type != NOT_RETRANSMISSION) {
1530 stats_.bytes_retransmitted += result.bytes_written;
1531 ++stats_.packets_retransmitted;
1534 if (result.status == WRITE_STATUS_ERROR) {
1535 OnWriteError(result.error_code);
1536 return false;
1539 return true;
1542 bool QuicConnection::ShouldDiscardPacket(const QueuedPacket& packet) {
1543 if (!connected_) {
1544 DVLOG(1) << ENDPOINT
1545 << "Not sending packet as connection is disconnected.";
1546 return true;
1549 QuicPacketSequenceNumber sequence_number =
1550 packet.serialized_packet.sequence_number;
1551 if (encryption_level_ == ENCRYPTION_FORWARD_SECURE &&
1552 packet.encryption_level == ENCRYPTION_NONE) {
1553 // Drop packets that are NULL encrypted since the peer won't accept them
1554 // anymore.
1555 DVLOG(1) << ENDPOINT << "Dropping NULL encrypted packet: "
1556 << sequence_number << " since the connection is forward secure.";
1557 return true;
1560 // If a retransmission has been acked before sending, don't send it.
1561 // This occurs if a packet gets serialized, queued, then discarded.
1562 if (packet.transmission_type != NOT_RETRANSMISSION &&
1563 (!sent_packet_manager_.IsUnacked(packet.original_sequence_number) ||
1564 !sent_packet_manager_.HasRetransmittableFrames(
1565 packet.original_sequence_number))) {
1566 DVLOG(1) << ENDPOINT << "Dropping unacked packet: " << sequence_number
1567 << " A previous transmission was acked while write blocked.";
1568 return true;
1571 return false;
1574 void QuicConnection::OnWriteError(int error_code) {
1575 DVLOG(1) << ENDPOINT << "Write failed with error: " << error_code
1576 << " (" << ErrorToString(error_code) << ")";
1577 // We can't send an error as the socket is presumably borked.
1578 CloseConnection(QUIC_PACKET_WRITE_ERROR, false);
1581 void QuicConnection::OnSerializedPacket(
1582 const SerializedPacket& serialized_packet) {
1583 // If a forward-secure encrypter is available but is not being used and this
1584 // packet's sequence number is after the first packet which requires
1585 // forward security, start using the forward-secure encrypter.
1586 if (FLAGS_enable_quic_delay_forward_security &&
1587 encryption_level_ != ENCRYPTION_FORWARD_SECURE &&
1588 has_forward_secure_encrypter_ &&
1589 serialized_packet.sequence_number >=
1590 first_required_forward_secure_packet_) {
1591 SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
1593 if (serialized_packet.retransmittable_frames) {
1594 serialized_packet.retransmittable_frames->
1595 set_encryption_level(encryption_level_);
1597 SendOrQueuePacket(QueuedPacket(serialized_packet, encryption_level_));
1600 void QuicConnection::OnCongestionWindowChange() {
1601 packet_generator_.OnCongestionWindowChange(
1602 sent_packet_manager_.EstimateMaxPacketsInFlight(max_packet_length()));
1603 visitor_->OnCongestionWindowChange(clock_->ApproximateNow());
1606 void QuicConnection::OnHandshakeComplete() {
1607 sent_packet_manager_.SetHandshakeConfirmed();
1608 // The client should immediately ack the SHLO to confirm the handshake is
1609 // complete with the server.
1610 if (!is_server_ && !ack_queued_) {
1611 ack_alarm_->Cancel();
1612 ack_alarm_->Set(clock_->ApproximateNow());
1616 void QuicConnection::SendOrQueuePacket(QueuedPacket packet) {
1617 // The caller of this function is responsible for checking CanWrite().
1618 if (packet.serialized_packet.packet == nullptr) {
1619 LOG(DFATAL)
1620 << "packet.serialized_packet.packet == nullptr in to SendOrQueuePacket";
1621 return;
1624 sent_entropy_manager_.RecordPacketEntropyHash(
1625 packet.serialized_packet.sequence_number,
1626 packet.serialized_packet.entropy_hash);
1627 if (!WritePacket(&packet)) {
1628 queued_packets_.push_back(packet);
1632 void QuicConnection::UpdateStopWaiting(QuicStopWaitingFrame* stop_waiting) {
1633 stop_waiting->least_unacked = GetLeastUnacked();
1634 stop_waiting->entropy_hash = sent_entropy_manager_.GetCumulativeEntropy(
1635 stop_waiting->least_unacked - 1);
1638 void QuicConnection::SendPing() {
1639 if (retransmission_alarm_->IsSet()) {
1640 return;
1642 packet_generator_.AddControlFrame(QuicFrame(new QuicPingFrame));
1645 void QuicConnection::SendAck() {
1646 ack_alarm_->Cancel();
1647 stop_waiting_count_ = 0;
1648 num_packets_received_since_last_ack_sent_ = 0;
1649 bool send_feedback = false;
1651 // Deprecating the Congestion Feedback Frame after QUIC_VERSION_22.
1652 if (version() <= QUIC_VERSION_22) {
1653 if (received_packet_manager_.GenerateCongestionFeedback(
1654 &outgoing_congestion_feedback_)) {
1655 DVLOG(1) << ENDPOINT << "Sending feedback: "
1656 << outgoing_congestion_feedback_;
1657 send_feedback = true;
1661 packet_generator_.SetShouldSendAck(send_feedback, true);
1664 void QuicConnection::OnRetransmissionTimeout() {
1665 if (!sent_packet_manager_.HasUnackedPackets()) {
1666 return;
1669 sent_packet_manager_.OnRetransmissionTimeout();
1670 WriteIfNotBlocked();
1672 // A write failure can result in the connection being closed, don't attempt to
1673 // write further packets, or to set alarms.
1674 if (!connected_) {
1675 return;
1678 // In the TLP case, the SentPacketManager gives the connection the opportunity
1679 // to send new data before retransmitting.
1680 if (sent_packet_manager_.MaybeRetransmitTailLossProbe()) {
1681 // Send the pending retransmission now that it's been queued.
1682 WriteIfNotBlocked();
1685 // Ensure the retransmission alarm is always set if there are unacked packets
1686 // and nothing waiting to be sent.
1687 if (!HasQueuedData() && !retransmission_alarm_->IsSet()) {
1688 QuicTime rto_timeout = sent_packet_manager_.GetRetransmissionTime();
1689 if (rto_timeout.IsInitialized()) {
1690 retransmission_alarm_->Set(rto_timeout);
1695 void QuicConnection::SetEncrypter(EncryptionLevel level,
1696 QuicEncrypter* encrypter) {
1697 framer_.SetEncrypter(level, encrypter);
1698 if (FLAGS_enable_quic_delay_forward_security &&
1699 level == ENCRYPTION_FORWARD_SECURE) {
1700 has_forward_secure_encrypter_ = true;
1701 first_required_forward_secure_packet_ =
1702 sequence_number_of_last_sent_packet_ +
1703 // 3 times the current congestion window (in slow start) should cover
1704 // about two full round trips worth of packets, which should be
1705 // sufficient.
1706 3 * sent_packet_manager_.EstimateMaxPacketsInFlight(
1707 max_packet_length());
1711 const QuicEncrypter* QuicConnection::encrypter(EncryptionLevel level) const {
1712 return framer_.encrypter(level);
1715 void QuicConnection::SetDefaultEncryptionLevel(EncryptionLevel level) {
1716 encryption_level_ = level;
1717 packet_generator_.set_encryption_level(level);
1720 void QuicConnection::SetDecrypter(QuicDecrypter* decrypter,
1721 EncryptionLevel level) {
1722 framer_.SetDecrypter(decrypter, level);
1725 void QuicConnection::SetAlternativeDecrypter(QuicDecrypter* decrypter,
1726 EncryptionLevel level,
1727 bool latch_once_used) {
1728 framer_.SetAlternativeDecrypter(decrypter, level, latch_once_used);
1731 const QuicDecrypter* QuicConnection::decrypter() const {
1732 return framer_.decrypter();
1735 const QuicDecrypter* QuicConnection::alternative_decrypter() const {
1736 return framer_.alternative_decrypter();
1739 void QuicConnection::QueueUndecryptablePacket(
1740 const QuicEncryptedPacket& packet) {
1741 DVLOG(1) << ENDPOINT << "Queueing undecryptable packet.";
1742 undecryptable_packets_.push_back(packet.Clone());
1745 void QuicConnection::MaybeProcessUndecryptablePackets() {
1746 if (undecryptable_packets_.empty() || encryption_level_ == ENCRYPTION_NONE) {
1747 return;
1750 while (connected_ && !undecryptable_packets_.empty()) {
1751 DVLOG(1) << ENDPOINT << "Attempting to process undecryptable packet";
1752 QuicEncryptedPacket* packet = undecryptable_packets_.front();
1753 if (!framer_.ProcessPacket(*packet) &&
1754 framer_.error() == QUIC_DECRYPTION_FAILURE) {
1755 DVLOG(1) << ENDPOINT << "Unable to process undecryptable packet...";
1756 break;
1758 DVLOG(1) << ENDPOINT << "Processed undecryptable packet!";
1759 ++stats_.packets_processed;
1760 delete packet;
1761 undecryptable_packets_.pop_front();
1764 // Once forward secure encryption is in use, there will be no
1765 // new keys installed and hence any undecryptable packets will
1766 // never be able to be decrypted.
1767 if (encryption_level_ == ENCRYPTION_FORWARD_SECURE) {
1768 if (debug_visitor_.get() != nullptr) {
1769 // TODO(rtenneti): perhaps more efficient to pass the number of
1770 // undecryptable packets as the argument to OnUndecryptablePacket so that
1771 // we just need to call OnUndecryptablePacket once?
1772 for (size_t i = 0; i < undecryptable_packets_.size(); ++i) {
1773 debug_visitor_->OnUndecryptablePacket();
1776 STLDeleteElements(&undecryptable_packets_);
1780 void QuicConnection::MaybeProcessRevivedPacket() {
1781 QuicFecGroup* group = GetFecGroup();
1782 if (!connected_ || group == nullptr || !group->CanRevive()) {
1783 return;
1785 QuicPacketHeader revived_header;
1786 char revived_payload[kMaxPacketSize];
1787 size_t len = group->Revive(&revived_header, revived_payload, kMaxPacketSize);
1788 revived_header.public_header.connection_id = connection_id_;
1789 revived_header.public_header.connection_id_length =
1790 last_header_.public_header.connection_id_length;
1791 revived_header.public_header.version_flag = false;
1792 revived_header.public_header.reset_flag = false;
1793 revived_header.public_header.sequence_number_length =
1794 last_header_.public_header.sequence_number_length;
1795 revived_header.fec_flag = false;
1796 revived_header.is_in_fec_group = NOT_IN_FEC_GROUP;
1797 revived_header.fec_group = 0;
1798 group_map_.erase(last_header_.fec_group);
1799 last_decrypted_packet_level_ = group->effective_encryption_level();
1800 DCHECK_LT(last_decrypted_packet_level_, NUM_ENCRYPTION_LEVELS);
1801 delete group;
1803 last_packet_revived_ = true;
1804 if (debug_visitor_.get() != nullptr) {
1805 debug_visitor_->OnRevivedPacket(revived_header,
1806 StringPiece(revived_payload, len));
1809 ++stats_.packets_revived;
1810 framer_.ProcessRevivedPacket(&revived_header,
1811 StringPiece(revived_payload, len));
1814 QuicFecGroup* QuicConnection::GetFecGroup() {
1815 QuicFecGroupNumber fec_group_num = last_header_.fec_group;
1816 if (fec_group_num == 0) {
1817 return nullptr;
1819 if (!ContainsKey(group_map_, fec_group_num)) {
1820 if (group_map_.size() >= kMaxFecGroups) { // Too many groups
1821 if (fec_group_num < group_map_.begin()->first) {
1822 // The group being requested is a group we've seen before and deleted.
1823 // Don't recreate it.
1824 return nullptr;
1826 // Clear the lowest group number.
1827 delete group_map_.begin()->second;
1828 group_map_.erase(group_map_.begin());
1830 group_map_[fec_group_num] = new QuicFecGroup();
1832 return group_map_[fec_group_num];
1835 void QuicConnection::SendConnectionClose(QuicErrorCode error) {
1836 SendConnectionCloseWithDetails(error, string());
1839 void QuicConnection::SendConnectionCloseWithDetails(QuicErrorCode error,
1840 const string& details) {
1841 // If we're write blocked, WritePacket() will not send, but will capture the
1842 // serialized packet.
1843 SendConnectionClosePacket(error, details);
1844 if (connected_) {
1845 // It's possible that while sending the connection close packet, we get a
1846 // socket error and disconnect right then and there. Avoid a double
1847 // disconnect in that case.
1848 CloseConnection(error, false);
1852 void QuicConnection::SendConnectionClosePacket(QuicErrorCode error,
1853 const string& details) {
1854 DVLOG(1) << ENDPOINT << "Force closing " << connection_id()
1855 << " with error " << QuicUtils::ErrorToString(error)
1856 << " (" << error << ") " << details;
1857 ScopedPacketBundler ack_bundler(this, SEND_ACK);
1858 QuicConnectionCloseFrame* frame = new QuicConnectionCloseFrame();
1859 frame->error_code = error;
1860 frame->error_details = details;
1861 packet_generator_.AddControlFrame(QuicFrame(frame));
1862 packet_generator_.FlushAllQueuedFrames();
1865 void QuicConnection::CloseConnection(QuicErrorCode error, bool from_peer) {
1866 if (!connected_) {
1867 DLOG(DFATAL) << "Error: attempt to close an already closed connection"
1868 << base::debug::StackTrace().ToString();
1869 return;
1871 connected_ = false;
1872 if (debug_visitor_.get() != nullptr) {
1873 debug_visitor_->OnConnectionClosed(error, from_peer);
1875 visitor_->OnConnectionClosed(error, from_peer);
1876 // Cancel the alarms so they don't trigger any action now that the
1877 // connection is closed.
1878 ack_alarm_->Cancel();
1879 ping_alarm_->Cancel();
1880 resume_writes_alarm_->Cancel();
1881 retransmission_alarm_->Cancel();
1882 send_alarm_->Cancel();
1883 timeout_alarm_->Cancel();
1886 void QuicConnection::SendGoAway(QuicErrorCode error,
1887 QuicStreamId last_good_stream_id,
1888 const string& reason) {
1889 DVLOG(1) << ENDPOINT << "Going away with error "
1890 << QuicUtils::ErrorToString(error)
1891 << " (" << error << ")";
1893 // Opportunistically bundle an ack with this outgoing packet.
1894 ScopedPacketBundler ack_bundler(this, BUNDLE_PENDING_ACK);
1895 packet_generator_.AddControlFrame(
1896 QuicFrame(new QuicGoAwayFrame(error, last_good_stream_id, reason)));
1899 void QuicConnection::CloseFecGroupsBefore(
1900 QuicPacketSequenceNumber sequence_number) {
1901 FecGroupMap::iterator it = group_map_.begin();
1902 while (it != group_map_.end()) {
1903 // If this is the current group or the group doesn't protect this packet
1904 // we can ignore it.
1905 if (last_header_.fec_group == it->first ||
1906 !it->second->ProtectsPacketsBefore(sequence_number)) {
1907 ++it;
1908 continue;
1910 QuicFecGroup* fec_group = it->second;
1911 DCHECK(!fec_group->CanRevive());
1912 FecGroupMap::iterator next = it;
1913 ++next;
1914 group_map_.erase(it);
1915 delete fec_group;
1916 it = next;
1920 QuicByteCount QuicConnection::max_packet_length() const {
1921 return packet_generator_.max_packet_length();
1924 void QuicConnection::set_max_packet_length(QuicByteCount length) {
1925 return packet_generator_.set_max_packet_length(length);
1928 bool QuicConnection::HasQueuedData() const {
1929 return pending_version_negotiation_packet_ ||
1930 !queued_packets_.empty() || packet_generator_.HasQueuedFrames();
1933 bool QuicConnection::CanWriteStreamData() {
1934 // Don't write stream data if there are negotiation or queued data packets
1935 // to send. Otherwise, continue and bundle as many frames as possible.
1936 if (pending_version_negotiation_packet_ || !queued_packets_.empty()) {
1937 return false;
1940 IsHandshake pending_handshake = visitor_->HasPendingHandshake() ?
1941 IS_HANDSHAKE : NOT_HANDSHAKE;
1942 // Sending queued packets may have caused the socket to become write blocked,
1943 // or the congestion manager to prohibit sending. If we've sent everything
1944 // we had queued and we're still not blocked, let the visitor know it can
1945 // write more.
1946 return ShouldGeneratePacket(NOT_RETRANSMISSION, HAS_RETRANSMITTABLE_DATA,
1947 pending_handshake);
1950 void QuicConnection::SetNetworkTimeouts(QuicTime::Delta overall_timeout,
1951 QuicTime::Delta idle_timeout) {
1952 LOG_IF(DFATAL, idle_timeout > overall_timeout)
1953 << "idle_timeout:" << idle_timeout.ToMilliseconds()
1954 << " overall_timeout:" << overall_timeout.ToMilliseconds();
1955 // Adjust the idle timeout on client and server to prevent clients from
1956 // sending requests to servers which have already closed the connection.
1957 if (is_server_) {
1958 idle_timeout = idle_timeout.Add(QuicTime::Delta::FromSeconds(3));
1959 } else if (idle_timeout > QuicTime::Delta::FromSeconds(1)) {
1960 idle_timeout = idle_timeout.Subtract(QuicTime::Delta::FromSeconds(1));
1962 overall_connection_timeout_ = overall_timeout;
1963 idle_network_timeout_ = idle_timeout;
1965 SetTimeoutAlarm();
1968 void QuicConnection::CheckForTimeout() {
1969 QuicTime now = clock_->ApproximateNow();
1970 QuicTime time_of_last_packet = max(time_of_last_received_packet_,
1971 time_of_last_sent_new_packet_);
1973 // |delta| can be < 0 as |now| is approximate time but |time_of_last_packet|
1974 // is accurate time. However, this should not change the behavior of
1975 // timeout handling.
1976 QuicTime::Delta idle_duration = now.Subtract(time_of_last_packet);
1977 DVLOG(1) << ENDPOINT << "last packet "
1978 << time_of_last_packet.ToDebuggingValue()
1979 << " now:" << now.ToDebuggingValue()
1980 << " idle_duration:" << idle_duration.ToMicroseconds()
1981 << " idle_network_timeout: "
1982 << idle_network_timeout_.ToMicroseconds();
1983 if (idle_duration >= idle_network_timeout_) {
1984 DVLOG(1) << ENDPOINT << "Connection timedout due to no network activity.";
1985 SendConnectionClose(QUIC_CONNECTION_TIMED_OUT);
1986 return;
1989 if (!overall_connection_timeout_.IsInfinite()) {
1990 QuicTime::Delta connected_duration =
1991 now.Subtract(stats_.connection_creation_time);
1992 DVLOG(1) << ENDPOINT << "connection time: "
1993 << connected_duration.ToMicroseconds() << " overall timeout: "
1994 << overall_connection_timeout_.ToMicroseconds();
1995 if (connected_duration >= overall_connection_timeout_) {
1996 DVLOG(1) << ENDPOINT <<
1997 "Connection timedout due to overall connection timeout.";
1998 SendConnectionClose(QUIC_CONNECTION_OVERALL_TIMED_OUT);
1999 return;
2003 SetTimeoutAlarm();
2006 void QuicConnection::SetTimeoutAlarm() {
2007 QuicTime time_of_last_packet = max(time_of_last_received_packet_,
2008 time_of_last_sent_new_packet_);
2010 QuicTime deadline = time_of_last_packet.Add(idle_network_timeout_);
2011 if (!overall_connection_timeout_.IsInfinite()) {
2012 deadline = min(deadline,
2013 stats_.connection_creation_time.Add(
2014 overall_connection_timeout_));
2017 timeout_alarm_->Cancel();
2018 timeout_alarm_->Set(deadline);
2021 void QuicConnection::SetPingAlarm() {
2022 if (is_server_) {
2023 // Only clients send pings.
2024 return;
2026 if (!visitor_->HasOpenDataStreams()) {
2027 ping_alarm_->Cancel();
2028 // Don't send a ping unless there are open streams.
2029 return;
2031 QuicTime::Delta ping_timeout = QuicTime::Delta::FromSeconds(kPingTimeoutSecs);
2032 ping_alarm_->Update(clock_->ApproximateNow().Add(ping_timeout),
2033 QuicTime::Delta::FromSeconds(1));
2036 QuicConnection::ScopedPacketBundler::ScopedPacketBundler(
2037 QuicConnection* connection,
2038 AckBundling send_ack)
2039 : connection_(connection),
2040 already_in_batch_mode_(connection != nullptr &&
2041 connection->packet_generator_.InBatchMode()) {
2042 if (connection_ == nullptr) {
2043 return;
2045 // Move generator into batch mode. If caller wants us to include an ack,
2046 // check the delayed-ack timer to see if there's ack info to be sent.
2047 if (!already_in_batch_mode_) {
2048 DVLOG(1) << "Entering Batch Mode.";
2049 connection_->packet_generator_.StartBatchOperations();
2051 // Bundle an ack if the alarm is set or with every second packet if we need to
2052 // raise the peer's least unacked.
2053 bool ack_pending =
2054 connection_->ack_alarm_->IsSet() || connection_->stop_waiting_count_ > 1;
2055 if (send_ack == SEND_ACK || (send_ack == BUNDLE_PENDING_ACK && ack_pending)) {
2056 DVLOG(1) << "Bundling ack with outgoing packet.";
2057 connection_->SendAck();
2061 QuicConnection::ScopedPacketBundler::~ScopedPacketBundler() {
2062 if (connection_ == nullptr) {
2063 return;
2065 // If we changed the generator's batch state, restore original batch state.
2066 if (!already_in_batch_mode_) {
2067 DVLOG(1) << "Leaving Batch Mode.";
2068 connection_->packet_generator_.FinishBatchOperations();
2070 DCHECK_EQ(already_in_batch_mode_,
2071 connection_->packet_generator_.InBatchMode());
2074 HasRetransmittableData QuicConnection::IsRetransmittable(
2075 const QueuedPacket& packet) {
2076 // Retransmitted packets retransmittable frames are owned by the unacked
2077 // packet map, but are not present in the serialized packet.
2078 if (packet.transmission_type != NOT_RETRANSMISSION ||
2079 packet.serialized_packet.retransmittable_frames != nullptr) {
2080 return HAS_RETRANSMITTABLE_DATA;
2081 } else {
2082 return NO_RETRANSMITTABLE_DATA;
2086 bool QuicConnection::IsConnectionClose(
2087 QueuedPacket packet) {
2088 RetransmittableFrames* retransmittable_frames =
2089 packet.serialized_packet.retransmittable_frames;
2090 if (!retransmittable_frames) {
2091 return false;
2093 for (size_t i = 0; i < retransmittable_frames->frames().size(); ++i) {
2094 if (retransmittable_frames->frames()[i].type == CONNECTION_CLOSE_FRAME) {
2095 return true;
2098 return false;
2101 } // namespace net