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"
17 #include "base/debug/stack_trace.h"
18 #include "base/format_macros.h"
19 #include "base/logging.h"
20 #include "base/stl_util.h"
21 #include "base/strings/stringprintf.h"
22 #include "net/base/net_errors.h"
23 #include "net/quic/crypto/quic_decrypter.h"
24 #include "net/quic/crypto/quic_encrypter.h"
25 #include "net/quic/iovector.h"
26 #include "net/quic/quic_bandwidth.h"
27 #include "net/quic/quic_config.h"
28 #include "net/quic/quic_fec_group.h"
29 #include "net/quic/quic_flags.h"
30 #include "net/quic/quic_packet_generator.h"
31 #include "net/quic/quic_utils.h"
33 using base::StringPiece
;
34 using base::StringPrintf
;
41 using std::numeric_limits
;
53 // The largest gap in packets we'll accept without closing the connection.
54 // This will likely have to be tuned.
55 const QuicPacketSequenceNumber kMaxPacketGap
= 5000;
57 // Limit the number of FEC groups to two. If we get enough out of order packets
58 // that this becomes limiting, we can revisit.
59 const size_t kMaxFecGroups
= 2;
61 // Maximum number of acks received before sending an ack in response.
62 const QuicPacketCount kMaxPacketsReceivedBeforeAckSend
= 20;
64 // Maximum number of tracked packets.
65 const QuicPacketCount kMaxTrackedPackets
= 5 * kMaxTcpCongestionWindow
;
67 bool Near(QuicPacketSequenceNumber a
, QuicPacketSequenceNumber b
) {
68 QuicPacketSequenceNumber delta
= (a
> b
) ? a
- b
: b
- a
;
69 return delta
<= kMaxPacketGap
;
72 // An alarm that is scheduled to send an ack if a timeout occurs.
73 class AckAlarm
: public QuicAlarm::Delegate
{
75 explicit AckAlarm(QuicConnection
* connection
)
76 : connection_(connection
) {
79 QuicTime
OnAlarm() override
{
80 connection_
->SendAck();
81 return QuicTime::Zero();
85 QuicConnection
* connection_
;
87 DISALLOW_COPY_AND_ASSIGN(AckAlarm
);
90 // This alarm will be scheduled any time a data-bearing packet is sent out.
91 // When the alarm goes off, the connection checks to see if the oldest packets
92 // have been acked, and retransmit them if they have not.
93 class RetransmissionAlarm
: public QuicAlarm::Delegate
{
95 explicit RetransmissionAlarm(QuicConnection
* connection
)
96 : connection_(connection
) {
99 QuicTime
OnAlarm() override
{
100 connection_
->OnRetransmissionTimeout();
101 return QuicTime::Zero();
105 QuicConnection
* connection_
;
107 DISALLOW_COPY_AND_ASSIGN(RetransmissionAlarm
);
110 // An alarm that is scheduled when the sent scheduler requires a
111 // a delay before sending packets and fires when the packet may be sent.
112 class SendAlarm
: public QuicAlarm::Delegate
{
114 explicit SendAlarm(QuicConnection
* connection
)
115 : connection_(connection
) {
118 QuicTime
OnAlarm() override
{
119 connection_
->WriteIfNotBlocked();
120 // Never reschedule the alarm, since CanWrite does that.
121 return QuicTime::Zero();
125 QuicConnection
* connection_
;
127 DISALLOW_COPY_AND_ASSIGN(SendAlarm
);
130 class TimeoutAlarm
: public QuicAlarm::Delegate
{
132 explicit TimeoutAlarm(QuicConnection
* connection
)
133 : connection_(connection
) {
136 QuicTime
OnAlarm() override
{
137 connection_
->CheckForTimeout();
138 // Never reschedule the alarm, since CheckForTimeout does that.
139 return QuicTime::Zero();
143 QuicConnection
* connection_
;
145 DISALLOW_COPY_AND_ASSIGN(TimeoutAlarm
);
148 class PingAlarm
: public QuicAlarm::Delegate
{
150 explicit PingAlarm(QuicConnection
* connection
)
151 : connection_(connection
) {
154 QuicTime
OnAlarm() override
{
155 connection_
->SendPing();
156 return QuicTime::Zero();
160 QuicConnection
* connection_
;
162 DISALLOW_COPY_AND_ASSIGN(PingAlarm
);
165 // This alarm may be scheduled when an FEC protected packet is sent out.
166 class FecAlarm
: public QuicAlarm::Delegate
{
168 explicit FecAlarm(QuicPacketGenerator
* packet_generator
)
169 : packet_generator_(packet_generator
) {}
171 QuicTime
OnAlarm() override
{
172 packet_generator_
->OnFecTimeout();
173 return QuicTime::Zero();
177 QuicPacketGenerator
* packet_generator_
;
179 DISALLOW_COPY_AND_ASSIGN(FecAlarm
);
184 QuicConnection::QueuedPacket::QueuedPacket(SerializedPacket packet
,
185 EncryptionLevel level
)
186 : serialized_packet(packet
),
187 encryption_level(level
),
188 transmission_type(NOT_RETRANSMISSION
),
189 original_sequence_number(0) {
192 QuicConnection::QueuedPacket::QueuedPacket(
193 SerializedPacket packet
,
194 EncryptionLevel level
,
195 TransmissionType transmission_type
,
196 QuicPacketSequenceNumber original_sequence_number
)
197 : serialized_packet(packet
),
198 encryption_level(level
),
199 transmission_type(transmission_type
),
200 original_sequence_number(original_sequence_number
) {
203 #define ENDPOINT (is_server_ ? "Server: " : " Client: ")
205 QuicConnection::QuicConnection(QuicConnectionId connection_id
,
207 QuicConnectionHelperInterface
* helper
,
208 const PacketWriterFactory
& writer_factory
,
212 const QuicVersionVector
& supported_versions
)
213 : framer_(supported_versions
,
214 helper
->GetClock()->ApproximateNow(),
217 writer_(writer_factory
.Create(this)),
218 owns_writer_(owns_writer
),
219 encryption_level_(ENCRYPTION_NONE
),
220 has_forward_secure_encrypter_(false),
221 first_required_forward_secure_packet_(0),
222 clock_(helper
->GetClock()),
223 random_generator_(helper
->GetRandomGenerator()),
224 connection_id_(connection_id
),
225 peer_address_(address
),
226 migrating_peer_port_(0),
227 last_packet_decrypted_(false),
228 last_packet_revived_(false),
230 last_decrypted_packet_level_(ENCRYPTION_NONE
),
231 largest_seen_packet_with_ack_(0),
232 largest_seen_packet_with_stop_waiting_(0),
233 max_undecryptable_packets_(0),
234 pending_version_negotiation_packet_(false),
235 silent_close_enabled_(false),
236 received_packet_manager_(&stats_
),
238 num_packets_received_since_last_ack_sent_(0),
239 stop_waiting_count_(0),
240 ack_alarm_(helper
->CreateAlarm(new AckAlarm(this))),
241 retransmission_alarm_(helper
->CreateAlarm(new RetransmissionAlarm(this))),
242 send_alarm_(helper
->CreateAlarm(new SendAlarm(this))),
243 resume_writes_alarm_(helper
->CreateAlarm(new SendAlarm(this))),
244 timeout_alarm_(helper
->CreateAlarm(new TimeoutAlarm(this))),
245 ping_alarm_(helper
->CreateAlarm(new PingAlarm(this))),
246 packet_generator_(connection_id_
, &framer_
, random_generator_
, this),
247 fec_alarm_(helper
->CreateAlarm(new FecAlarm(&packet_generator_
))),
248 idle_network_timeout_(QuicTime::Delta::Infinite()),
249 overall_connection_timeout_(QuicTime::Delta::Infinite()),
250 time_of_last_received_packet_(clock_
->ApproximateNow()),
251 time_of_last_sent_new_packet_(clock_
->ApproximateNow()),
252 sequence_number_of_last_sent_packet_(0),
253 sent_packet_manager_(
257 FLAGS_quic_use_bbr_congestion_control
? kBBR
: kCubic
,
258 FLAGS_quic_use_time_loss_detection
? kTime
: kNack
,
260 version_negotiation_state_(START_NEGOTIATION
),
261 is_server_(is_server
),
263 peer_ip_changed_(false),
264 peer_port_changed_(false),
265 self_ip_changed_(false),
266 self_port_changed_(false),
267 can_truncate_connection_ids_(true),
268 is_secure_(is_secure
) {
269 DVLOG(1) << ENDPOINT
<< "Created connection with connection_id: "
271 framer_
.set_visitor(this);
272 framer_
.set_received_entropy_calculator(&received_packet_manager_
);
273 stats_
.connection_creation_time
= clock_
->ApproximateNow();
274 sent_packet_manager_
.set_network_change_visitor(this);
275 if (FLAGS_quic_small_default_packet_size
&& is_server_
) {
276 set_max_packet_length(kDefaultServerMaxPacketSize
);
280 QuicConnection::~QuicConnection() {
284 STLDeleteElements(&undecryptable_packets_
);
285 STLDeleteValues(&group_map_
);
286 for (QueuedPacketList::iterator it
= queued_packets_
.begin();
287 it
!= queued_packets_
.end(); ++it
) {
288 delete it
->serialized_packet
.retransmittable_frames
;
289 delete it
->serialized_packet
.packet
;
293 void QuicConnection::SetFromConfig(const QuicConfig
& config
) {
294 if (config
.negotiated()) {
295 SetNetworkTimeouts(QuicTime::Delta::Infinite(),
296 config
.IdleConnectionStateLifetime());
297 if (config
.SilentClose()) {
298 silent_close_enabled_
= true;
301 SetNetworkTimeouts(config
.max_time_before_crypto_handshake(),
302 config
.max_idle_time_before_crypto_handshake());
305 sent_packet_manager_
.SetFromConfig(config
);
306 if (config
.HasReceivedBytesForConnectionId() &&
307 can_truncate_connection_ids_
) {
308 packet_generator_
.SetConnectionIdLength(
309 config
.ReceivedBytesForConnectionId());
311 max_undecryptable_packets_
= config
.max_undecryptable_packets();
314 bool QuicConnection::ResumeConnectionState(
315 const CachedNetworkParameters
& cached_network_params
) {
316 return sent_packet_manager_
.ResumeConnectionState(cached_network_params
);
319 void QuicConnection::SetNumOpenStreams(size_t num_streams
) {
320 sent_packet_manager_
.SetNumOpenStreams(num_streams
);
323 bool QuicConnection::SelectMutualVersion(
324 const QuicVersionVector
& available_versions
) {
325 // Try to find the highest mutual version by iterating over supported
326 // versions, starting with the highest, and breaking out of the loop once we
327 // find a matching version in the provided available_versions vector.
328 const QuicVersionVector
& supported_versions
= framer_
.supported_versions();
329 for (size_t i
= 0; i
< supported_versions
.size(); ++i
) {
330 const QuicVersion
& version
= supported_versions
[i
];
331 if (std::find(available_versions
.begin(), available_versions
.end(),
332 version
) != available_versions
.end()) {
333 framer_
.set_version(version
);
341 void QuicConnection::OnError(QuicFramer
* framer
) {
342 // Packets that we can not or have not decrypted are dropped.
343 // TODO(rch): add stats to measure this.
344 if (!connected_
|| last_packet_decrypted_
== false) {
347 SendConnectionCloseWithDetails(framer
->error(), framer
->detailed_error());
350 void QuicConnection::MaybeSetFecAlarm(
351 QuicPacketSequenceNumber sequence_number
) {
352 if (fec_alarm_
->IsSet()) {
355 QuicTime::Delta timeout
= packet_generator_
.GetFecTimeout(sequence_number
);
356 if (!timeout
.IsInfinite()) {
357 fec_alarm_
->Set(clock_
->ApproximateNow().Add(timeout
));
361 void QuicConnection::OnPacket() {
362 DCHECK(last_stream_frames_
.empty() &&
363 last_ack_frames_
.empty() &&
364 last_stop_waiting_frames_
.empty() &&
365 last_rst_frames_
.empty() &&
366 last_goaway_frames_
.empty() &&
367 last_window_update_frames_
.empty() &&
368 last_blocked_frames_
.empty() &&
369 last_ping_frames_
.empty() &&
370 last_close_frames_
.empty());
371 last_packet_decrypted_
= false;
372 last_packet_revived_
= false;
375 void QuicConnection::OnPublicResetPacket(
376 const QuicPublicResetPacket
& packet
) {
377 if (debug_visitor_
.get() != nullptr) {
378 debug_visitor_
->OnPublicResetPacket(packet
);
380 CloseConnection(QUIC_PUBLIC_RESET
, true);
382 DVLOG(1) << ENDPOINT
<< "Connection " << connection_id()
383 << " closed via QUIC_PUBLIC_RESET from peer.";
386 bool QuicConnection::OnProtocolVersionMismatch(QuicVersion received_version
) {
387 DVLOG(1) << ENDPOINT
<< "Received packet with mismatched version "
389 // TODO(satyamshekhar): Implement no server state in this mode.
391 LOG(DFATAL
) << ENDPOINT
<< "Framer called OnProtocolVersionMismatch. "
392 << "Closing connection.";
393 CloseConnection(QUIC_INTERNAL_ERROR
, false);
396 DCHECK_NE(version(), received_version
);
398 if (debug_visitor_
.get() != nullptr) {
399 debug_visitor_
->OnProtocolVersionMismatch(received_version
);
402 switch (version_negotiation_state_
) {
403 case START_NEGOTIATION
:
404 if (!framer_
.IsSupportedVersion(received_version
)) {
405 SendVersionNegotiationPacket();
406 version_negotiation_state_
= NEGOTIATION_IN_PROGRESS
;
411 case NEGOTIATION_IN_PROGRESS
:
412 if (!framer_
.IsSupportedVersion(received_version
)) {
413 SendVersionNegotiationPacket();
418 case NEGOTIATED_VERSION
:
419 // Might be old packets that were sent by the client before the version
420 // was negotiated. Drop these.
427 version_negotiation_state_
= NEGOTIATED_VERSION
;
428 visitor_
->OnSuccessfulVersionNegotiation(received_version
);
429 if (debug_visitor_
.get() != nullptr) {
430 debug_visitor_
->OnSuccessfulVersionNegotiation(received_version
);
432 DVLOG(1) << ENDPOINT
<< "version negotiated " << received_version
;
434 // Store the new version.
435 framer_
.set_version(received_version
);
437 // TODO(satyamshekhar): Store the sequence number of this packet and close the
438 // connection if we ever received a packet with incorrect version and whose
439 // sequence number is greater.
443 // Handles version negotiation for client connection.
444 void QuicConnection::OnVersionNegotiationPacket(
445 const QuicVersionNegotiationPacket
& packet
) {
447 LOG(DFATAL
) << ENDPOINT
<< "Framer parsed VersionNegotiationPacket."
448 << " Closing connection.";
449 CloseConnection(QUIC_INTERNAL_ERROR
, false);
452 if (debug_visitor_
.get() != nullptr) {
453 debug_visitor_
->OnVersionNegotiationPacket(packet
);
456 if (version_negotiation_state_
!= START_NEGOTIATION
) {
457 // Possibly a duplicate version negotiation packet.
461 if (std::find(packet
.versions
.begin(),
462 packet
.versions
.end(), version()) !=
463 packet
.versions
.end()) {
464 DLOG(WARNING
) << ENDPOINT
<< "The server already supports our version. "
465 << "It should have accepted our connection.";
466 // Just drop the connection.
467 CloseConnection(QUIC_INVALID_VERSION_NEGOTIATION_PACKET
, false);
471 if (!SelectMutualVersion(packet
.versions
)) {
472 SendConnectionCloseWithDetails(QUIC_INVALID_VERSION
,
473 "no common version found");
478 << "Negotiated version: " << QuicVersionToString(version());
479 server_supported_versions_
= packet
.versions
;
480 version_negotiation_state_
= NEGOTIATION_IN_PROGRESS
;
481 RetransmitUnackedPackets(ALL_UNACKED_RETRANSMISSION
);
484 void QuicConnection::OnRevivedPacket() {
487 bool QuicConnection::OnUnauthenticatedPublicHeader(
488 const QuicPacketPublicHeader
& header
) {
492 bool QuicConnection::OnUnauthenticatedHeader(const QuicPacketHeader
& header
) {
496 void QuicConnection::OnDecryptedPacket(EncryptionLevel level
) {
497 last_decrypted_packet_level_
= level
;
498 last_packet_decrypted_
= true;
499 // If this packet was foward-secure encrypted and the forward-secure encrypter
500 // is not being used, start using it.
501 if (encryption_level_
!= ENCRYPTION_FORWARD_SECURE
&&
502 has_forward_secure_encrypter_
&& level
== ENCRYPTION_FORWARD_SECURE
) {
503 SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE
);
507 bool QuicConnection::OnPacketHeader(const QuicPacketHeader
& header
) {
508 if (debug_visitor_
.get() != nullptr) {
509 debug_visitor_
->OnPacketHeader(header
);
512 if (!ProcessValidatedPacket()) {
516 // Will be decrement below if we fall through to return true;
517 ++stats_
.packets_dropped
;
519 if (header
.public_header
.connection_id
!= connection_id_
) {
520 DVLOG(1) << ENDPOINT
<< "Ignoring packet from unexpected ConnectionId: "
521 << header
.public_header
.connection_id
<< " instead of "
523 if (debug_visitor_
.get() != nullptr) {
524 debug_visitor_
->OnIncorrectConnectionId(
525 header
.public_header
.connection_id
);
530 if (!Near(header
.packet_sequence_number
,
531 last_header_
.packet_sequence_number
)) {
532 DVLOG(1) << ENDPOINT
<< "Packet " << header
.packet_sequence_number
533 << " out of bounds. Discarding";
534 SendConnectionCloseWithDetails(QUIC_INVALID_PACKET_HEADER
,
535 "Packet sequence number out of bounds");
539 // If this packet has already been seen, or that the sender
540 // has told us will not be retransmitted, then stop processing the packet.
541 if (!received_packet_manager_
.IsAwaitingPacket(
542 header
.packet_sequence_number
)) {
543 DVLOG(1) << ENDPOINT
<< "Packet " << header
.packet_sequence_number
544 << " no longer being waited for. Discarding.";
545 if (debug_visitor_
.get() != nullptr) {
546 debug_visitor_
->OnDuplicatePacket(header
.packet_sequence_number
);
551 if (version_negotiation_state_
!= NEGOTIATED_VERSION
) {
553 if (!header
.public_header
.version_flag
) {
554 DLOG(WARNING
) << ENDPOINT
<< "Packet " << header
.packet_sequence_number
555 << " without version flag before version negotiated.";
556 // Packets should have the version flag till version negotiation is
558 CloseConnection(QUIC_INVALID_VERSION
, false);
561 DCHECK_EQ(1u, header
.public_header
.versions
.size());
562 DCHECK_EQ(header
.public_header
.versions
[0], version());
563 version_negotiation_state_
= NEGOTIATED_VERSION
;
564 visitor_
->OnSuccessfulVersionNegotiation(version());
565 if (debug_visitor_
.get() != nullptr) {
566 debug_visitor_
->OnSuccessfulVersionNegotiation(version());
570 DCHECK(!header
.public_header
.version_flag
);
571 // If the client gets a packet without the version flag from the server
572 // it should stop sending version since the version negotiation is done.
573 packet_generator_
.StopSendingVersion();
574 version_negotiation_state_
= NEGOTIATED_VERSION
;
575 visitor_
->OnSuccessfulVersionNegotiation(version());
576 if (debug_visitor_
.get() != nullptr) {
577 debug_visitor_
->OnSuccessfulVersionNegotiation(version());
582 DCHECK_EQ(NEGOTIATED_VERSION
, version_negotiation_state_
);
584 --stats_
.packets_dropped
;
585 DVLOG(1) << ENDPOINT
<< "Received packet header: " << header
;
586 last_header_
= header
;
591 void QuicConnection::OnFecProtectedPayload(StringPiece payload
) {
592 DCHECK_EQ(IN_FEC_GROUP
, last_header_
.is_in_fec_group
);
593 DCHECK_NE(0u, last_header_
.fec_group
);
594 QuicFecGroup
* group
= GetFecGroup();
595 if (group
!= nullptr) {
596 group
->Update(last_decrypted_packet_level_
, last_header_
, payload
);
600 bool QuicConnection::OnStreamFrame(const QuicStreamFrame
& frame
) {
602 if (debug_visitor_
.get() != nullptr) {
603 debug_visitor_
->OnStreamFrame(frame
);
605 if (frame
.stream_id
!= kCryptoStreamId
&&
606 last_decrypted_packet_level_
== ENCRYPTION_NONE
) {
607 DLOG(WARNING
) << ENDPOINT
608 << "Received an unencrypted data frame: closing connection";
609 SendConnectionClose(QUIC_UNENCRYPTED_STREAM_DATA
);
612 last_stream_frames_
.push_back(frame
);
616 bool QuicConnection::OnAckFrame(const QuicAckFrame
& incoming_ack
) {
618 if (debug_visitor_
.get() != nullptr) {
619 debug_visitor_
->OnAckFrame(incoming_ack
);
621 DVLOG(1) << ENDPOINT
<< "OnAckFrame: " << incoming_ack
;
623 if (last_header_
.packet_sequence_number
<= largest_seen_packet_with_ack_
) {
624 DVLOG(1) << ENDPOINT
<< "Received an old ack frame: ignoring";
628 if (!ValidateAckFrame(incoming_ack
)) {
629 SendConnectionClose(QUIC_INVALID_ACK_DATA
);
633 last_ack_frames_
.push_back(incoming_ack
);
637 void QuicConnection::ProcessAckFrame(const QuicAckFrame
& incoming_ack
) {
638 largest_seen_packet_with_ack_
= last_header_
.packet_sequence_number
;
639 sent_packet_manager_
.OnIncomingAck(incoming_ack
,
640 time_of_last_received_packet_
);
641 sent_entropy_manager_
.ClearEntropyBefore(
642 sent_packet_manager_
.least_packet_awaited_by_peer() - 1);
643 if (sent_packet_manager_
.HasPendingRetransmissions()) {
647 // Always reset the retransmission alarm when an ack comes in, since we now
648 // have a better estimate of the current rtt than when it was set.
649 QuicTime retransmission_time
= sent_packet_manager_
.GetRetransmissionTime();
650 retransmission_alarm_
->Update(retransmission_time
,
651 QuicTime::Delta::FromMilliseconds(1));
654 void QuicConnection::ProcessStopWaitingFrame(
655 const QuicStopWaitingFrame
& stop_waiting
) {
656 largest_seen_packet_with_stop_waiting_
= last_header_
.packet_sequence_number
;
657 received_packet_manager_
.UpdatePacketInformationSentByPeer(stop_waiting
);
658 // Possibly close any FecGroups which are now irrelevant.
659 CloseFecGroupsBefore(stop_waiting
.least_unacked
+ 1);
662 bool QuicConnection::OnStopWaitingFrame(const QuicStopWaitingFrame
& frame
) {
665 if (last_header_
.packet_sequence_number
<=
666 largest_seen_packet_with_stop_waiting_
) {
667 DVLOG(1) << ENDPOINT
<< "Received an old stop waiting frame: ignoring";
671 if (!ValidateStopWaitingFrame(frame
)) {
672 SendConnectionClose(QUIC_INVALID_STOP_WAITING_DATA
);
676 if (debug_visitor_
.get() != nullptr) {
677 debug_visitor_
->OnStopWaitingFrame(frame
);
680 last_stop_waiting_frames_
.push_back(frame
);
684 bool QuicConnection::OnPingFrame(const QuicPingFrame
& frame
) {
686 if (debug_visitor_
.get() != nullptr) {
687 debug_visitor_
->OnPingFrame(frame
);
689 last_ping_frames_
.push_back(frame
);
693 bool QuicConnection::ValidateAckFrame(const QuicAckFrame
& incoming_ack
) {
694 if (incoming_ack
.largest_observed
> packet_generator_
.sequence_number()) {
695 DLOG(ERROR
) << ENDPOINT
<< "Peer's observed unsent packet:"
696 << incoming_ack
.largest_observed
<< " vs "
697 << packet_generator_
.sequence_number();
698 // We got an error for data we have not sent. Error out.
702 if (incoming_ack
.largest_observed
< sent_packet_manager_
.largest_observed()) {
703 DLOG(ERROR
) << ENDPOINT
<< "Peer's largest_observed packet decreased:"
704 << incoming_ack
.largest_observed
<< " vs "
705 << sent_packet_manager_
.largest_observed();
706 // A new ack has a diminished largest_observed value. Error out.
707 // If this was an old packet, we wouldn't even have checked.
711 if (!incoming_ack
.missing_packets
.empty() &&
712 *incoming_ack
.missing_packets
.rbegin() > incoming_ack
.largest_observed
) {
713 DLOG(ERROR
) << ENDPOINT
<< "Peer sent missing packet: "
714 << *incoming_ack
.missing_packets
.rbegin()
715 << " which is greater than largest observed: "
716 << incoming_ack
.largest_observed
;
720 if (!incoming_ack
.missing_packets
.empty() &&
721 *incoming_ack
.missing_packets
.begin() <
722 sent_packet_manager_
.least_packet_awaited_by_peer()) {
723 DLOG(ERROR
) << ENDPOINT
<< "Peer sent missing packet: "
724 << *incoming_ack
.missing_packets
.begin()
725 << " which is smaller than least_packet_awaited_by_peer_: "
726 << sent_packet_manager_
.least_packet_awaited_by_peer();
730 if (!sent_entropy_manager_
.IsValidEntropy(
731 incoming_ack
.largest_observed
,
732 incoming_ack
.missing_packets
,
733 incoming_ack
.entropy_hash
)) {
734 DLOG(ERROR
) << ENDPOINT
<< "Peer sent invalid entropy.";
738 for (SequenceNumberSet::const_iterator iter
=
739 incoming_ack
.revived_packets
.begin();
740 iter
!= incoming_ack
.revived_packets
.end(); ++iter
) {
741 if (!ContainsKey(incoming_ack
.missing_packets
, *iter
)) {
742 DLOG(ERROR
) << ENDPOINT
743 << "Peer specified revived packet which was not missing.";
750 bool QuicConnection::ValidateStopWaitingFrame(
751 const QuicStopWaitingFrame
& stop_waiting
) {
752 if (stop_waiting
.least_unacked
<
753 received_packet_manager_
.peer_least_packet_awaiting_ack()) {
754 DLOG(ERROR
) << ENDPOINT
<< "Peer's sent low least_unacked: "
755 << stop_waiting
.least_unacked
<< " vs "
756 << received_packet_manager_
.peer_least_packet_awaiting_ack();
757 // We never process old ack frames, so this number should only increase.
761 if (stop_waiting
.least_unacked
>
762 last_header_
.packet_sequence_number
) {
763 DLOG(ERROR
) << ENDPOINT
<< "Peer sent least_unacked:"
764 << stop_waiting
.least_unacked
765 << " greater than the enclosing packet sequence number:"
766 << last_header_
.packet_sequence_number
;
773 void QuicConnection::OnFecData(const QuicFecData
& fec
) {
774 DCHECK_EQ(IN_FEC_GROUP
, last_header_
.is_in_fec_group
);
775 DCHECK_NE(0u, last_header_
.fec_group
);
776 QuicFecGroup
* group
= GetFecGroup();
777 if (group
!= nullptr) {
778 group
->UpdateFec(last_decrypted_packet_level_
,
779 last_header_
.packet_sequence_number
, fec
);
783 bool QuicConnection::OnRstStreamFrame(const QuicRstStreamFrame
& frame
) {
785 if (debug_visitor_
.get() != nullptr) {
786 debug_visitor_
->OnRstStreamFrame(frame
);
788 DVLOG(1) << ENDPOINT
<< "Stream reset with error "
789 << QuicUtils::StreamErrorToString(frame
.error_code
);
790 last_rst_frames_
.push_back(frame
);
794 bool QuicConnection::OnConnectionCloseFrame(
795 const QuicConnectionCloseFrame
& frame
) {
797 if (debug_visitor_
.get() != nullptr) {
798 debug_visitor_
->OnConnectionCloseFrame(frame
);
800 DVLOG(1) << ENDPOINT
<< "Connection " << connection_id()
801 << " closed with error "
802 << QuicUtils::ErrorToString(frame
.error_code
)
803 << " " << frame
.error_details
;
804 last_close_frames_
.push_back(frame
);
808 bool QuicConnection::OnGoAwayFrame(const QuicGoAwayFrame
& frame
) {
810 if (debug_visitor_
.get() != nullptr) {
811 debug_visitor_
->OnGoAwayFrame(frame
);
813 DVLOG(1) << ENDPOINT
<< "Go away received with error "
814 << QuicUtils::ErrorToString(frame
.error_code
)
815 << " and reason:" << frame
.reason_phrase
;
816 last_goaway_frames_
.push_back(frame
);
820 bool QuicConnection::OnWindowUpdateFrame(const QuicWindowUpdateFrame
& frame
) {
822 if (debug_visitor_
.get() != nullptr) {
823 debug_visitor_
->OnWindowUpdateFrame(frame
);
825 DVLOG(1) << ENDPOINT
<< "WindowUpdate received for stream: "
826 << frame
.stream_id
<< " with byte offset: " << frame
.byte_offset
;
827 last_window_update_frames_
.push_back(frame
);
831 bool QuicConnection::OnBlockedFrame(const QuicBlockedFrame
& frame
) {
833 if (debug_visitor_
.get() != nullptr) {
834 debug_visitor_
->OnBlockedFrame(frame
);
836 DVLOG(1) << ENDPOINT
<< "Blocked frame received for stream: "
838 last_blocked_frames_
.push_back(frame
);
842 void QuicConnection::OnPacketComplete() {
843 // Don't do anything if this packet closed the connection.
849 DVLOG(1) << ENDPOINT
<< (last_packet_revived_
? "Revived" : "Got")
850 << " packet " << last_header_
.packet_sequence_number
851 << " with " << last_stream_frames_
.size()<< " stream frames "
852 << last_ack_frames_
.size() << " acks, "
853 << last_stop_waiting_frames_
.size() << " stop_waiting, "
854 << last_rst_frames_
.size() << " rsts, "
855 << last_goaway_frames_
.size() << " goaways, "
856 << last_window_update_frames_
.size() << " window updates, "
857 << last_blocked_frames_
.size() << " blocked, "
858 << last_ping_frames_
.size() << " pings, "
859 << last_close_frames_
.size() << " closes, "
860 << "for " << last_header_
.public_header
.connection_id
;
862 ++num_packets_received_since_last_ack_sent_
;
864 // Call MaybeQueueAck() before recording the received packet, since we want
865 // to trigger an ack if the newly received packet was previously missing.
868 // Record received or revived packet to populate ack info correctly before
869 // processing stream frames, since the processing may result in a response
870 // packet with a bundled ack.
871 if (last_packet_revived_
) {
872 received_packet_manager_
.RecordPacketRevived(
873 last_header_
.packet_sequence_number
);
875 received_packet_manager_
.RecordPacketReceived(
876 last_size_
, last_header_
, time_of_last_received_packet_
);
879 if (!last_stream_frames_
.empty()) {
880 visitor_
->OnStreamFrames(last_stream_frames_
);
883 for (size_t i
= 0; i
< last_stream_frames_
.size(); ++i
) {
884 stats_
.stream_bytes_received
+=
885 last_stream_frames_
[i
].data
.TotalBufferSize();
888 // Process window updates, blocked, stream resets, acks, then congestion
890 if (!last_window_update_frames_
.empty()) {
891 visitor_
->OnWindowUpdateFrames(last_window_update_frames_
);
893 if (!last_blocked_frames_
.empty()) {
894 visitor_
->OnBlockedFrames(last_blocked_frames_
);
896 for (size_t i
= 0; i
< last_goaway_frames_
.size(); ++i
) {
897 visitor_
->OnGoAway(last_goaway_frames_
[i
]);
899 for (size_t i
= 0; i
< last_rst_frames_
.size(); ++i
) {
900 visitor_
->OnRstStream(last_rst_frames_
[i
]);
902 for (size_t i
= 0; i
< last_ack_frames_
.size(); ++i
) {
903 ProcessAckFrame(last_ack_frames_
[i
]);
905 for (size_t i
= 0; i
< last_stop_waiting_frames_
.size(); ++i
) {
906 ProcessStopWaitingFrame(last_stop_waiting_frames_
[i
]);
908 if (!last_close_frames_
.empty()) {
909 CloseConnection(last_close_frames_
[0].error_code
, true);
913 // If there are new missing packets to report, send an ack immediately.
914 if (received_packet_manager_
.HasNewMissingPackets()) {
916 ack_alarm_
->Cancel();
919 UpdateStopWaitingCount();
921 MaybeCloseIfTooManyOutstandingPackets();
924 void QuicConnection::MaybeQueueAck() {
925 // If the incoming packet was missing, send an ack immediately.
926 ack_queued_
= received_packet_manager_
.IsMissing(
927 last_header_
.packet_sequence_number
);
929 if (!ack_queued_
&& ShouldLastPacketInstigateAck()) {
930 if (ack_alarm_
->IsSet()) {
933 // Send an ack much more quickly for crypto handshake packets.
934 QuicTime::Delta delayed_ack_time
= sent_packet_manager_
.DelayedAckTime();
935 ack_alarm_
->Set(clock_
->ApproximateNow().Add(delayed_ack_time
));
936 DVLOG(1) << "Ack timer set; next packet or timer will trigger ACK.";
941 ack_alarm_
->Cancel();
945 void QuicConnection::ClearLastFrames() {
946 last_stream_frames_
.clear();
947 last_ack_frames_
.clear();
948 last_stop_waiting_frames_
.clear();
949 last_rst_frames_
.clear();
950 last_goaway_frames_
.clear();
951 last_window_update_frames_
.clear();
952 last_blocked_frames_
.clear();
953 last_ping_frames_
.clear();
954 last_close_frames_
.clear();
957 void QuicConnection::MaybeCloseIfTooManyOutstandingPackets() {
958 // This occurs if we don't discard old packets we've sent fast enough.
959 // It's possible largest observed is less than least unacked.
960 if (sent_packet_manager_
.largest_observed() >
961 (sent_packet_manager_
.GetLeastUnacked() + kMaxTrackedPackets
)) {
962 SendConnectionCloseWithDetails(
963 QUIC_TOO_MANY_OUTSTANDING_SENT_PACKETS
,
964 StringPrintf("More than %" PRIu64
" outstanding.", kMaxTrackedPackets
));
966 // This occurs if there are received packet gaps and the peer does not raise
967 // the least unacked fast enough.
968 if (received_packet_manager_
.NumTrackedPackets() > kMaxTrackedPackets
) {
969 SendConnectionCloseWithDetails(
970 QUIC_TOO_MANY_OUTSTANDING_RECEIVED_PACKETS
,
971 StringPrintf("More than %" PRIu64
" outstanding.", kMaxTrackedPackets
));
975 void QuicConnection::PopulateAckFrame(QuicAckFrame
* ack
) {
976 received_packet_manager_
.UpdateReceivedPacketInfo(ack
,
977 clock_
->ApproximateNow());
980 void QuicConnection::PopulateStopWaitingFrame(
981 QuicStopWaitingFrame
* stop_waiting
) {
982 stop_waiting
->least_unacked
= GetLeastUnacked();
983 stop_waiting
->entropy_hash
= sent_entropy_manager_
.GetCumulativeEntropy(
984 stop_waiting
->least_unacked
- 1);
987 bool QuicConnection::ShouldLastPacketInstigateAck() const {
988 if (!last_stream_frames_
.empty() ||
989 !last_goaway_frames_
.empty() ||
990 !last_rst_frames_
.empty() ||
991 !last_window_update_frames_
.empty() ||
992 !last_blocked_frames_
.empty() ||
993 !last_ping_frames_
.empty()) {
997 if (!last_ack_frames_
.empty() && last_ack_frames_
.back().is_truncated
) {
1000 // Always send an ack every 20 packets in order to allow the peer to discard
1001 // information from the SentPacketManager and provide an RTT measurement.
1002 if (num_packets_received_since_last_ack_sent_
>=
1003 kMaxPacketsReceivedBeforeAckSend
) {
1009 void QuicConnection::UpdateStopWaitingCount() {
1010 if (last_ack_frames_
.empty()) {
1014 // If the peer is still waiting for a packet that we are no longer planning to
1015 // send, send an ack to raise the high water mark.
1016 if (!last_ack_frames_
.back().missing_packets
.empty() &&
1017 GetLeastUnacked() > *last_ack_frames_
.back().missing_packets
.begin()) {
1018 ++stop_waiting_count_
;
1020 stop_waiting_count_
= 0;
1024 QuicPacketSequenceNumber
QuicConnection::GetLeastUnacked() const {
1025 return sent_packet_manager_
.GetLeastUnacked();
1028 void QuicConnection::MaybeSendInResponseToPacket() {
1032 ScopedPacketBundler
bundler(this, ack_queued_
? SEND_ACK
: NO_ACK
);
1034 // Now that we have received an ack, we might be able to send packets which
1035 // are queued locally, or drain streams which are blocked.
1036 if (CanWrite(HAS_RETRANSMITTABLE_DATA
)) {
1041 void QuicConnection::SendVersionNegotiationPacket() {
1042 // TODO(alyssar): implement zero server state negotiation.
1043 pending_version_negotiation_packet_
= true;
1044 if (writer_
->IsWriteBlocked()) {
1045 visitor_
->OnWriteBlocked();
1048 DVLOG(1) << ENDPOINT
<< "Sending version negotiation packet: {"
1049 << QuicVersionVectorToString(framer_
.supported_versions()) << "}";
1050 scoped_ptr
<QuicEncryptedPacket
> version_packet(
1051 packet_generator_
.SerializeVersionNegotiationPacket(
1052 framer_
.supported_versions()));
1053 WriteResult result
= writer_
->WritePacket(
1054 version_packet
->data(), version_packet
->length(),
1055 self_address().address(), peer_address());
1057 if (result
.status
== WRITE_STATUS_ERROR
) {
1058 // We can't send an error as the socket is presumably borked.
1059 CloseConnection(QUIC_PACKET_WRITE_ERROR
, false);
1062 if (result
.status
== WRITE_STATUS_BLOCKED
) {
1063 visitor_
->OnWriteBlocked();
1064 if (writer_
->IsWriteBlockedDataBuffered()) {
1065 pending_version_negotiation_packet_
= false;
1070 pending_version_negotiation_packet_
= false;
1073 QuicConsumedData
QuicConnection::SendStreamData(
1075 const IOVector
& data
,
1076 QuicStreamOffset offset
,
1078 FecProtection fec_protection
,
1079 QuicAckNotifier::DelegateInterface
* delegate
) {
1080 if (!fin
&& data
.Empty()) {
1081 LOG(DFATAL
) << "Attempt to send empty stream frame";
1082 return QuicConsumedData(0, false);
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 return packet_generator_
.ConsumeData(id
, data
, offset
, fin
, fec_protection
,
1103 void QuicConnection::SendRstStream(QuicStreamId id
,
1104 QuicRstStreamErrorCode error
,
1105 QuicStreamOffset bytes_written
) {
1106 // Opportunistically bundle an ack with this outgoing packet.
1107 ScopedPacketBundler
ack_bundler(this, BUNDLE_PENDING_ACK
);
1108 packet_generator_
.AddControlFrame(QuicFrame(new QuicRstStreamFrame(
1109 id
, AdjustErrorForVersion(error
, version()), bytes_written
)));
1112 void QuicConnection::SendWindowUpdate(QuicStreamId id
,
1113 QuicStreamOffset byte_offset
) {
1114 // Opportunistically bundle an ack with this outgoing packet.
1115 ScopedPacketBundler
ack_bundler(this, BUNDLE_PENDING_ACK
);
1116 packet_generator_
.AddControlFrame(
1117 QuicFrame(new QuicWindowUpdateFrame(id
, byte_offset
)));
1120 void QuicConnection::SendBlocked(QuicStreamId id
) {
1121 // Opportunistically bundle an ack with this outgoing packet.
1122 ScopedPacketBundler
ack_bundler(this, BUNDLE_PENDING_ACK
);
1123 packet_generator_
.AddControlFrame(QuicFrame(new QuicBlockedFrame(id
)));
1126 const QuicConnectionStats
& QuicConnection::GetStats() {
1127 const RttStats
* rtt_stats
= sent_packet_manager_
.GetRttStats();
1129 // Update rtt and estimated bandwidth.
1130 QuicTime::Delta min_rtt
= rtt_stats
->min_rtt();
1131 if (min_rtt
.IsZero()) {
1132 // If min RTT has not been set, use initial RTT instead.
1133 min_rtt
= QuicTime::Delta::FromMicroseconds(rtt_stats
->initial_rtt_us());
1135 stats_
.min_rtt_us
= min_rtt
.ToMicroseconds();
1137 QuicTime::Delta srtt
= rtt_stats
->smoothed_rtt();
1138 if (srtt
.IsZero()) {
1139 // If SRTT has not been set, use initial RTT instead.
1140 srtt
= QuicTime::Delta::FromMicroseconds(rtt_stats
->initial_rtt_us());
1142 stats_
.srtt_us
= srtt
.ToMicroseconds();
1144 stats_
.estimated_bandwidth
= sent_packet_manager_
.BandwidthEstimate();
1145 stats_
.max_packet_size
= packet_generator_
.max_packet_length();
1149 void QuicConnection::ProcessUdpPacket(const IPEndPoint
& self_address
,
1150 const IPEndPoint
& peer_address
,
1151 const QuicEncryptedPacket
& packet
) {
1155 if (debug_visitor_
.get() != nullptr) {
1156 debug_visitor_
->OnPacketReceived(self_address
, peer_address
, packet
);
1158 last_size_
= packet
.length();
1160 CheckForAddressMigration(self_address
, peer_address
);
1162 stats_
.bytes_received
+= packet
.length();
1163 ++stats_
.packets_received
;
1165 if (!framer_
.ProcessPacket(packet
)) {
1166 // If we are unable to decrypt this packet, it might be
1167 // because the CHLO or SHLO packet was lost.
1168 if (framer_
.error() == QUIC_DECRYPTION_FAILURE
) {
1169 if (encryption_level_
!= ENCRYPTION_FORWARD_SECURE
&&
1170 undecryptable_packets_
.size() < max_undecryptable_packets_
) {
1171 QueueUndecryptablePacket(packet
);
1172 } else if (debug_visitor_
.get() != nullptr) {
1173 debug_visitor_
->OnUndecryptablePacket();
1176 DVLOG(1) << ENDPOINT
<< "Unable to process packet. Last packet processed: "
1177 << last_header_
.packet_sequence_number
;
1181 ++stats_
.packets_processed
;
1182 MaybeProcessUndecryptablePackets();
1183 MaybeProcessRevivedPacket();
1184 MaybeSendInResponseToPacket();
1188 void QuicConnection::CheckForAddressMigration(
1189 const IPEndPoint
& self_address
, const IPEndPoint
& peer_address
) {
1190 peer_ip_changed_
= false;
1191 peer_port_changed_
= false;
1192 self_ip_changed_
= false;
1193 self_port_changed_
= false;
1195 if (peer_address_
.address().empty()) {
1196 peer_address_
= peer_address
;
1198 if (self_address_
.address().empty()) {
1199 self_address_
= self_address
;
1202 if (!peer_address
.address().empty() && !peer_address_
.address().empty()) {
1203 peer_ip_changed_
= (peer_address
.address() != peer_address_
.address());
1204 peer_port_changed_
= (peer_address
.port() != peer_address_
.port());
1206 // Store in case we want to migrate connection in ProcessValidatedPacket.
1207 migrating_peer_port_
= peer_address
.port();
1210 if (!self_address
.address().empty() && !self_address_
.address().empty()) {
1211 self_ip_changed_
= (self_address
.address() != self_address_
.address());
1212 self_port_changed_
= (self_address
.port() != self_address_
.port());
1216 void QuicConnection::OnCanWrite() {
1217 DCHECK(!writer_
->IsWriteBlocked());
1219 WriteQueuedPackets();
1220 WritePendingRetransmissions();
1222 // Sending queued packets may have caused the socket to become write blocked,
1223 // or the congestion manager to prohibit sending. If we've sent everything
1224 // we had queued and we're still not blocked, let the visitor know it can
1226 if (!CanWrite(HAS_RETRANSMITTABLE_DATA
)) {
1230 { // Limit the scope of the bundler. ACK inclusion happens elsewhere.
1231 ScopedPacketBundler
bundler(this, NO_ACK
);
1232 visitor_
->OnCanWrite();
1235 // After the visitor writes, it may have caused the socket to become write
1236 // blocked or the congestion manager to prohibit sending, so check again.
1237 if (visitor_
->WillingAndAbleToWrite() &&
1238 !resume_writes_alarm_
->IsSet() &&
1239 CanWrite(HAS_RETRANSMITTABLE_DATA
)) {
1240 // We're not write blocked, but some stream didn't write out all of its
1241 // bytes. Register for 'immediate' resumption so we'll keep writing after
1242 // other connections and events have had a chance to use the thread.
1243 resume_writes_alarm_
->Set(clock_
->ApproximateNow());
1247 void QuicConnection::WriteIfNotBlocked() {
1248 if (!writer_
->IsWriteBlocked()) {
1253 bool QuicConnection::ProcessValidatedPacket() {
1254 if (peer_ip_changed_
|| self_ip_changed_
|| self_port_changed_
) {
1255 SendConnectionCloseWithDetails(
1256 QUIC_ERROR_MIGRATING_ADDRESS
,
1257 "Neither IP address migration, nor self port migration are supported.");
1261 // Peer port migration is supported, do it now if port has changed.
1262 if (peer_port_changed_
) {
1263 DVLOG(1) << ENDPOINT
<< "Peer's port changed from "
1264 << peer_address_
.port() << " to " << migrating_peer_port_
1265 << ", migrating connection.";
1266 peer_address_
= IPEndPoint(peer_address_
.address(), migrating_peer_port_
);
1269 time_of_last_received_packet_
= clock_
->Now();
1270 DVLOG(1) << ENDPOINT
<< "time of last received packet: "
1271 << time_of_last_received_packet_
.ToDebuggingValue();
1273 if (is_server_
&& encryption_level_
== ENCRYPTION_NONE
&&
1274 last_size_
> packet_generator_
.max_packet_length()) {
1275 set_max_packet_length(last_size_
);
1280 void QuicConnection::WriteQueuedPackets() {
1281 DCHECK(!writer_
->IsWriteBlocked());
1283 if (pending_version_negotiation_packet_
) {
1284 SendVersionNegotiationPacket();
1287 QueuedPacketList::iterator packet_iterator
= queued_packets_
.begin();
1288 while (packet_iterator
!= queued_packets_
.end() &&
1289 WritePacket(&(*packet_iterator
))) {
1290 packet_iterator
= queued_packets_
.erase(packet_iterator
);
1294 void QuicConnection::WritePendingRetransmissions() {
1295 // Keep writing as long as there's a pending retransmission which can be
1297 while (sent_packet_manager_
.HasPendingRetransmissions()) {
1298 const QuicSentPacketManager::PendingRetransmission pending
=
1299 sent_packet_manager_
.NextPendingRetransmission();
1300 if (!CanWrite(HAS_RETRANSMITTABLE_DATA
)) {
1304 // Re-packetize the frames with a new sequence number for retransmission.
1305 // Retransmitted data packets do not use FEC, even when it's enabled.
1306 // Retransmitted packets use the same sequence number length as the
1308 // Flush the packet generator before making a new packet.
1309 // TODO(ianswett): Implement ReserializeAllFrames as a separate path that
1310 // does not require the creator to be flushed.
1311 packet_generator_
.FlushAllQueuedFrames();
1312 SerializedPacket serialized_packet
= packet_generator_
.ReserializeAllFrames(
1313 pending
.retransmittable_frames
, pending
.sequence_number_length
);
1314 if (serialized_packet
.packet
== nullptr) {
1315 // We failed to serialize the packet, so close the connection.
1316 // CloseConnection does not send close packet, so no infinite loop here.
1317 CloseConnection(QUIC_ENCRYPTION_FAILURE
, false);
1321 DVLOG(1) << ENDPOINT
<< "Retransmitting " << pending
.sequence_number
1322 << " as " << serialized_packet
.sequence_number
;
1324 QueuedPacket(serialized_packet
,
1325 pending
.retransmittable_frames
.encryption_level(),
1326 pending
.transmission_type
,
1327 pending
.sequence_number
));
1331 void QuicConnection::RetransmitUnackedPackets(
1332 TransmissionType retransmission_type
) {
1333 sent_packet_manager_
.RetransmitUnackedPackets(retransmission_type
);
1335 WriteIfNotBlocked();
1338 void QuicConnection::NeuterUnencryptedPackets() {
1339 sent_packet_manager_
.NeuterUnencryptedPackets();
1340 // This may have changed the retransmission timer, so re-arm it.
1341 QuicTime retransmission_time
= sent_packet_manager_
.GetRetransmissionTime();
1342 retransmission_alarm_
->Update(retransmission_time
,
1343 QuicTime::Delta::FromMilliseconds(1));
1346 bool QuicConnection::ShouldGeneratePacket(
1347 TransmissionType transmission_type
,
1348 HasRetransmittableData retransmittable
,
1349 IsHandshake handshake
) {
1350 // We should serialize handshake packets immediately to ensure that they
1351 // end up sent at the right encryption level.
1352 if (handshake
== IS_HANDSHAKE
) {
1356 return CanWrite(retransmittable
);
1359 bool QuicConnection::CanWrite(HasRetransmittableData retransmittable
) {
1364 if (writer_
->IsWriteBlocked()) {
1365 visitor_
->OnWriteBlocked();
1369 QuicTime now
= clock_
->Now();
1370 QuicTime::Delta delay
= sent_packet_manager_
.TimeUntilSend(
1371 now
, retransmittable
);
1372 if (delay
.IsInfinite()) {
1373 send_alarm_
->Cancel();
1377 // If the scheduler requires a delay, then we can not send this packet now.
1378 if (!delay
.IsZero()) {
1379 send_alarm_
->Update(now
.Add(delay
), QuicTime::Delta::FromMilliseconds(1));
1380 DVLOG(1) << ENDPOINT
<< "Delaying sending " << delay
.ToMilliseconds()
1384 send_alarm_
->Cancel();
1388 bool QuicConnection::WritePacket(QueuedPacket
* packet
) {
1389 if (!WritePacketInner(packet
)) {
1392 delete packet
->serialized_packet
.retransmittable_frames
;
1393 delete packet
->serialized_packet
.packet
;
1394 packet
->serialized_packet
.retransmittable_frames
= nullptr;
1395 packet
->serialized_packet
.packet
= nullptr;
1399 bool QuicConnection::WritePacketInner(QueuedPacket
* packet
) {
1400 if (ShouldDiscardPacket(*packet
)) {
1401 ++stats_
.packets_discarded
;
1404 // Connection close packets are encrypted and saved, so don't exit early.
1405 const bool is_connection_close
= IsConnectionClose(*packet
);
1406 if (writer_
->IsWriteBlocked() && !is_connection_close
) {
1410 QuicPacketSequenceNumber sequence_number
=
1411 packet
->serialized_packet
.sequence_number
;
1412 DCHECK_LE(sequence_number_of_last_sent_packet_
, sequence_number
);
1413 sequence_number_of_last_sent_packet_
= sequence_number
;
1415 QuicEncryptedPacket
* encrypted
= packet
->serialized_packet
.packet
;
1416 // Connection close packets are eventually owned by TimeWaitListManager.
1417 // Others are deleted at the end of this call.
1418 if (is_connection_close
) {
1419 DCHECK(connection_close_packet_
.get() == nullptr);
1420 connection_close_packet_
.reset(encrypted
);
1421 packet
->serialized_packet
.packet
= nullptr;
1422 // This assures we won't try to write *forced* packets when blocked.
1423 // Return true to stop processing.
1424 if (writer_
->IsWriteBlocked()) {
1425 visitor_
->OnWriteBlocked();
1430 if (!FLAGS_quic_allow_oversized_packets_for_test
) {
1431 DCHECK_LE(encrypted
->length(), kMaxPacketSize
);
1433 DCHECK_LE(encrypted
->length(), packet_generator_
.max_packet_length());
1434 DVLOG(1) << ENDPOINT
<< "Sending packet " << sequence_number
<< " : "
1435 << (packet
->serialized_packet
.is_fec_packet
1437 : (IsRetransmittable(*packet
) == HAS_RETRANSMITTABLE_DATA
1439 : " ack only ")) << ", encryption level: "
1440 << QuicUtils::EncryptionLevelToString(packet
->encryption_level
)
1441 << ", encrypted length:" << encrypted
->length();
1442 DVLOG(2) << ENDPOINT
<< "packet(" << sequence_number
<< "): " << std::endl
1443 << QuicUtils::StringToHexASCIIDump(encrypted
->AsStringPiece());
1445 QuicTime packet_send_time
= QuicTime::Zero();
1446 if (FLAGS_quic_record_send_time_before_write
) {
1447 // Measure the RTT from before the write begins to avoid underestimating the
1448 // min_rtt_, especially in cases where the thread blocks or gets swapped out
1449 // during the WritePacket below.
1450 packet_send_time
= clock_
->Now();
1452 WriteResult result
= writer_
->WritePacket(encrypted
->data(),
1453 encrypted
->length(),
1454 self_address().address(),
1456 if (result
.error_code
== ERR_IO_PENDING
) {
1457 DCHECK_EQ(WRITE_STATUS_BLOCKED
, result
.status
);
1460 if (result
.status
== WRITE_STATUS_BLOCKED
) {
1461 visitor_
->OnWriteBlocked();
1462 // If the socket buffers the the data, then the packet should not
1463 // be queued and sent again, which would result in an unnecessary
1464 // duplicate packet being sent. The helper must call OnCanWrite
1465 // when the write completes, and OnWriteError if an error occurs.
1466 if (!writer_
->IsWriteBlockedDataBuffered()) {
1470 if (!FLAGS_quic_record_send_time_before_write
) {
1471 packet_send_time
= clock_
->Now();
1473 if (!packet_send_time
.IsInitialized()) {
1474 // TODO(jokulik): This is only needed because of the two code paths for
1475 // initializing packet_send_time. Once "quic_record_send_time_before_write"
1476 // is deprecated, this check can be removed.
1477 LOG(DFATAL
) << "The packet send time should never be zero. "
1478 << "This is a programming bug, please report it.";
1480 if (result
.status
!= WRITE_STATUS_ERROR
&& debug_visitor_
.get() != nullptr) {
1481 // Pass the write result to the visitor.
1482 debug_visitor_
->OnPacketSent(packet
->serialized_packet
,
1483 packet
->original_sequence_number
,
1484 packet
->encryption_level
,
1485 packet
->transmission_type
,
1489 if (packet
->transmission_type
== NOT_RETRANSMISSION
) {
1490 time_of_last_sent_new_packet_
= packet_send_time
;
1493 MaybeSetFecAlarm(sequence_number
);
1494 DVLOG(1) << ENDPOINT
<< "time "
1495 << (FLAGS_quic_record_send_time_before_write
?
1496 "we began writing " : "we finished writing ")
1497 << "last sent packet: "
1498 << packet_send_time
.ToDebuggingValue();
1500 // TODO(ianswett): Change the sequence number length and other packet creator
1501 // options by a more explicit API than setting a struct value directly,
1502 // perhaps via the NetworkChangeVisitor.
1503 packet_generator_
.UpdateSequenceNumberLength(
1504 sent_packet_manager_
.least_packet_awaited_by_peer(),
1505 sent_packet_manager_
.EstimateMaxPacketsInFlight(max_packet_length()));
1507 bool reset_retransmission_alarm
= sent_packet_manager_
.OnPacketSent(
1508 &packet
->serialized_packet
,
1509 packet
->original_sequence_number
,
1511 encrypted
->length(),
1512 packet
->transmission_type
,
1513 IsRetransmittable(*packet
));
1515 if (reset_retransmission_alarm
|| !retransmission_alarm_
->IsSet()) {
1516 retransmission_alarm_
->Update(sent_packet_manager_
.GetRetransmissionTime(),
1517 QuicTime::Delta::FromMilliseconds(1));
1520 stats_
.bytes_sent
+= result
.bytes_written
;
1521 ++stats_
.packets_sent
;
1522 if (packet
->transmission_type
!= NOT_RETRANSMISSION
) {
1523 stats_
.bytes_retransmitted
+= result
.bytes_written
;
1524 ++stats_
.packets_retransmitted
;
1527 if (result
.status
== WRITE_STATUS_ERROR
) {
1528 OnWriteError(result
.error_code
);
1529 DLOG(ERROR
) << ENDPOINT
<< "failed writing " << encrypted
->length()
1531 << " from host " << self_address().ToStringWithoutPort()
1532 << " to address " << peer_address().ToString();
1539 bool QuicConnection::ShouldDiscardPacket(const QueuedPacket
& packet
) {
1541 DVLOG(1) << ENDPOINT
1542 << "Not sending packet as connection is disconnected.";
1546 QuicPacketSequenceNumber sequence_number
=
1547 packet
.serialized_packet
.sequence_number
;
1548 if (encryption_level_
== ENCRYPTION_FORWARD_SECURE
&&
1549 packet
.encryption_level
== ENCRYPTION_NONE
) {
1550 // Drop packets that are NULL encrypted since the peer won't accept them
1552 DVLOG(1) << ENDPOINT
<< "Dropping NULL encrypted packet: "
1553 << sequence_number
<< " since the connection is forward secure.";
1557 // If a retransmission has been acked before sending, don't send it.
1558 // This occurs if a packet gets serialized, queued, then discarded.
1559 if (packet
.transmission_type
!= NOT_RETRANSMISSION
&&
1560 (!sent_packet_manager_
.IsUnacked(packet
.original_sequence_number
) ||
1561 !sent_packet_manager_
.HasRetransmittableFrames(
1562 packet
.original_sequence_number
))) {
1563 DVLOG(1) << ENDPOINT
<< "Dropping unacked packet: " << sequence_number
1564 << " A previous transmission was acked while write blocked.";
1571 void QuicConnection::OnWriteError(int error_code
) {
1572 DVLOG(1) << ENDPOINT
<< "Write failed with error: " << error_code
1573 << " (" << ErrorToString(error_code
) << ")";
1574 // We can't send an error as the socket is presumably borked.
1575 CloseConnection(QUIC_PACKET_WRITE_ERROR
, false);
1578 void QuicConnection::OnSerializedPacket(
1579 const SerializedPacket
& serialized_packet
) {
1580 if (serialized_packet
.packet
== nullptr) {
1581 // We failed to serialize the packet, so close the connection.
1582 // CloseConnection does not send close packet, so no infinite loop here.
1583 CloseConnection(QUIC_ENCRYPTION_FAILURE
, false);
1586 if (serialized_packet
.retransmittable_frames
) {
1587 sent_packet_manager_
.OnSerializedPacket(serialized_packet
);
1589 if (serialized_packet
.is_fec_packet
&& fec_alarm_
->IsSet()) {
1590 // If an FEC packet is serialized with the FEC alarm set, cancel the alarm.
1591 fec_alarm_
->Cancel();
1593 SendOrQueuePacket(QueuedPacket(serialized_packet
, encryption_level_
));
1596 void QuicConnection::OnCongestionWindowChange() {
1597 packet_generator_
.OnCongestionWindowChange(
1598 sent_packet_manager_
.EstimateMaxPacketsInFlight(max_packet_length()));
1599 visitor_
->OnCongestionWindowChange(clock_
->ApproximateNow());
1602 void QuicConnection::OnRttChange() {
1603 // Uses the connection's smoothed RTT. If zero, uses initial_rtt.
1604 QuicTime::Delta rtt
= sent_packet_manager_
.GetRttStats()->smoothed_rtt();
1606 rtt
= QuicTime::Delta::FromMicroseconds(
1607 sent_packet_manager_
.GetRttStats()->initial_rtt_us());
1609 packet_generator_
.OnRttChange(rtt
);
1612 void QuicConnection::OnHandshakeComplete() {
1613 sent_packet_manager_
.SetHandshakeConfirmed();
1614 // The client should immediately ack the SHLO to confirm the handshake is
1615 // complete with the server.
1616 if (!is_server_
&& !ack_queued_
) {
1617 ack_alarm_
->Cancel();
1618 ack_alarm_
->Set(clock_
->ApproximateNow());
1622 void QuicConnection::SendOrQueuePacket(QueuedPacket packet
) {
1623 // The caller of this function is responsible for checking CanWrite().
1624 if (packet
.serialized_packet
.packet
== nullptr) {
1626 << "packet.serialized_packet.packet == nullptr in to SendOrQueuePacket";
1630 sent_entropy_manager_
.RecordPacketEntropyHash(
1631 packet
.serialized_packet
.sequence_number
,
1632 packet
.serialized_packet
.entropy_hash
);
1633 if (!WritePacket(&packet
)) {
1634 queued_packets_
.push_back(packet
);
1637 // If a forward-secure encrypter is available but is not being used and the
1638 // next sequence number is the first packet which requires
1639 // forward security, start using the forward-secure encrypter.
1640 if (encryption_level_
!= ENCRYPTION_FORWARD_SECURE
&&
1641 has_forward_secure_encrypter_
&&
1642 packet
.serialized_packet
.sequence_number
>=
1643 first_required_forward_secure_packet_
- 1) {
1644 SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE
);
1648 void QuicConnection::SendPing() {
1649 if (retransmission_alarm_
->IsSet()) {
1652 packet_generator_
.AddControlFrame(QuicFrame(new QuicPingFrame
));
1655 void QuicConnection::SendAck() {
1656 ack_alarm_
->Cancel();
1657 stop_waiting_count_
= 0;
1658 num_packets_received_since_last_ack_sent_
= 0;
1660 packet_generator_
.SetShouldSendAck(true);
1663 void QuicConnection::OnRetransmissionTimeout() {
1664 if (!sent_packet_manager_
.HasUnackedPackets()) {
1668 sent_packet_manager_
.OnRetransmissionTimeout();
1669 WriteIfNotBlocked();
1671 // A write failure can result in the connection being closed, don't attempt to
1672 // write further packets, or to set alarms.
1677 // In the TLP case, the SentPacketManager gives the connection the opportunity
1678 // to send new data before retransmitting.
1679 if (sent_packet_manager_
.MaybeRetransmitTailLossProbe()) {
1680 // Send the pending retransmission now that it's been queued.
1681 WriteIfNotBlocked();
1684 // Ensure the retransmission alarm is always set if there are unacked packets
1685 // and nothing waiting to be sent.
1686 if (!HasQueuedData() && !retransmission_alarm_
->IsSet()) {
1687 QuicTime rto_timeout
= sent_packet_manager_
.GetRetransmissionTime();
1688 if (rto_timeout
.IsInitialized()) {
1689 retransmission_alarm_
->Set(rto_timeout
);
1694 void QuicConnection::SetEncrypter(EncryptionLevel level
,
1695 QuicEncrypter
* encrypter
) {
1696 framer_
.SetEncrypter(level
, encrypter
);
1697 if (level
== ENCRYPTION_FORWARD_SECURE
) {
1698 has_forward_secure_encrypter_
= true;
1699 first_required_forward_secure_packet_
=
1700 sequence_number_of_last_sent_packet_
+
1701 // 3 times the current congestion window (in slow start) should cover
1702 // about two full round trips worth of packets, which should be
1704 3 * sent_packet_manager_
.EstimateMaxPacketsInFlight(
1705 max_packet_length());
1709 const QuicEncrypter
* QuicConnection::encrypter(EncryptionLevel level
) const {
1710 return framer_
.encrypter(level
);
1713 void QuicConnection::SetDefaultEncryptionLevel(EncryptionLevel level
) {
1714 encryption_level_
= level
;
1715 packet_generator_
.set_encryption_level(level
);
1718 void QuicConnection::SetDecrypter(QuicDecrypter
* decrypter
,
1719 EncryptionLevel level
) {
1720 framer_
.SetDecrypter(decrypter
, level
);
1723 void QuicConnection::SetAlternativeDecrypter(QuicDecrypter
* decrypter
,
1724 EncryptionLevel level
,
1725 bool latch_once_used
) {
1726 framer_
.SetAlternativeDecrypter(decrypter
, level
, latch_once_used
);
1729 const QuicDecrypter
* QuicConnection::decrypter() const {
1730 return framer_
.decrypter();
1733 const QuicDecrypter
* QuicConnection::alternative_decrypter() const {
1734 return framer_
.alternative_decrypter();
1737 void QuicConnection::QueueUndecryptablePacket(
1738 const QuicEncryptedPacket
& packet
) {
1739 DVLOG(1) << ENDPOINT
<< "Queueing undecryptable packet.";
1740 undecryptable_packets_
.push_back(packet
.Clone());
1743 void QuicConnection::MaybeProcessUndecryptablePackets() {
1744 if (undecryptable_packets_
.empty() || encryption_level_
== ENCRYPTION_NONE
) {
1748 while (connected_
&& !undecryptable_packets_
.empty()) {
1749 DVLOG(1) << ENDPOINT
<< "Attempting to process undecryptable packet";
1750 QuicEncryptedPacket
* packet
= undecryptable_packets_
.front();
1751 if (!framer_
.ProcessPacket(*packet
) &&
1752 framer_
.error() == QUIC_DECRYPTION_FAILURE
) {
1753 DVLOG(1) << ENDPOINT
<< "Unable to process undecryptable packet...";
1756 DVLOG(1) << ENDPOINT
<< "Processed undecryptable packet!";
1757 ++stats_
.packets_processed
;
1759 undecryptable_packets_
.pop_front();
1762 // Once forward secure encryption is in use, there will be no
1763 // new keys installed and hence any undecryptable packets will
1764 // never be able to be decrypted.
1765 if (encryption_level_
== ENCRYPTION_FORWARD_SECURE
) {
1766 if (debug_visitor_
.get() != nullptr) {
1767 // TODO(rtenneti): perhaps more efficient to pass the number of
1768 // undecryptable packets as the argument to OnUndecryptablePacket so that
1769 // we just need to call OnUndecryptablePacket once?
1770 for (size_t i
= 0; i
< undecryptable_packets_
.size(); ++i
) {
1771 debug_visitor_
->OnUndecryptablePacket();
1774 STLDeleteElements(&undecryptable_packets_
);
1778 void QuicConnection::MaybeProcessRevivedPacket() {
1779 QuicFecGroup
* group
= GetFecGroup();
1780 if (!connected_
|| group
== nullptr || !group
->CanRevive()) {
1783 QuicPacketHeader revived_header
;
1784 char revived_payload
[kMaxPacketSize
];
1785 size_t len
= group
->Revive(&revived_header
, revived_payload
, kMaxPacketSize
);
1786 revived_header
.public_header
.connection_id
= connection_id_
;
1787 revived_header
.public_header
.connection_id_length
=
1788 last_header_
.public_header
.connection_id_length
;
1789 revived_header
.public_header
.version_flag
= false;
1790 revived_header
.public_header
.reset_flag
= false;
1791 revived_header
.public_header
.sequence_number_length
=
1792 last_header_
.public_header
.sequence_number_length
;
1793 revived_header
.fec_flag
= false;
1794 revived_header
.is_in_fec_group
= NOT_IN_FEC_GROUP
;
1795 revived_header
.fec_group
= 0;
1796 group_map_
.erase(last_header_
.fec_group
);
1797 last_decrypted_packet_level_
= group
->effective_encryption_level();
1798 DCHECK_LT(last_decrypted_packet_level_
, NUM_ENCRYPTION_LEVELS
);
1801 last_packet_revived_
= true;
1802 if (debug_visitor_
.get() != nullptr) {
1803 debug_visitor_
->OnRevivedPacket(revived_header
,
1804 StringPiece(revived_payload
, len
));
1807 ++stats_
.packets_revived
;
1808 framer_
.ProcessRevivedPacket(&revived_header
,
1809 StringPiece(revived_payload
, len
));
1812 QuicFecGroup
* QuicConnection::GetFecGroup() {
1813 QuicFecGroupNumber fec_group_num
= last_header_
.fec_group
;
1814 if (fec_group_num
== 0) {
1817 if (!ContainsKey(group_map_
, fec_group_num
)) {
1818 if (group_map_
.size() >= kMaxFecGroups
) { // Too many groups
1819 if (fec_group_num
< group_map_
.begin()->first
) {
1820 // The group being requested is a group we've seen before and deleted.
1821 // Don't recreate it.
1824 // Clear the lowest group number.
1825 delete group_map_
.begin()->second
;
1826 group_map_
.erase(group_map_
.begin());
1828 group_map_
[fec_group_num
] = new QuicFecGroup();
1830 return group_map_
[fec_group_num
];
1833 void QuicConnection::SendConnectionClose(QuicErrorCode error
) {
1834 SendConnectionCloseWithDetails(error
, string());
1837 void QuicConnection::SendConnectionCloseWithDetails(QuicErrorCode error
,
1838 const string
& details
) {
1839 // If we're write blocked, WritePacket() will not send, but will capture the
1840 // serialized packet.
1841 SendConnectionClosePacket(error
, details
);
1843 // It's possible that while sending the connection close packet, we get a
1844 // socket error and disconnect right then and there. Avoid a double
1845 // disconnect in that case.
1846 CloseConnection(error
, false);
1850 void QuicConnection::SendConnectionClosePacket(QuicErrorCode error
,
1851 const string
& details
) {
1852 DVLOG(1) << ENDPOINT
<< "Force closing " << connection_id()
1853 << " with error " << QuicUtils::ErrorToString(error
)
1854 << " (" << error
<< ") " << details
;
1855 // Don't send explicit connection close packets for timeouts.
1856 // This is particularly important on mobile, where connections are short.
1857 if (silent_close_enabled_
&&
1858 error
== QuicErrorCode::QUIC_CONNECTION_TIMED_OUT
) {
1861 ScopedPacketBundler
ack_bundler(this, SEND_ACK
);
1862 QuicConnectionCloseFrame
* frame
= new QuicConnectionCloseFrame();
1863 frame
->error_code
= error
;
1864 frame
->error_details
= details
;
1865 packet_generator_
.AddControlFrame(QuicFrame(frame
));
1866 packet_generator_
.FlushAllQueuedFrames();
1869 void QuicConnection::CloseConnection(QuicErrorCode error
, bool from_peer
) {
1871 DLOG(DFATAL
) << "Error: attempt to close an already closed connection"
1872 << base::debug::StackTrace().ToString();
1876 if (debug_visitor_
.get() != nullptr) {
1877 debug_visitor_
->OnConnectionClosed(error
, from_peer
);
1879 visitor_
->OnConnectionClosed(error
, from_peer
);
1880 // Cancel the alarms so they don't trigger any action now that the
1881 // connection is closed.
1882 ack_alarm_
->Cancel();
1883 ping_alarm_
->Cancel();
1884 fec_alarm_
->Cancel();
1885 resume_writes_alarm_
->Cancel();
1886 retransmission_alarm_
->Cancel();
1887 send_alarm_
->Cancel();
1888 timeout_alarm_
->Cancel();
1891 void QuicConnection::SendGoAway(QuicErrorCode error
,
1892 QuicStreamId last_good_stream_id
,
1893 const string
& reason
) {
1894 DVLOG(1) << ENDPOINT
<< "Going away with error "
1895 << QuicUtils::ErrorToString(error
)
1896 << " (" << error
<< ")";
1898 // Opportunistically bundle an ack with this outgoing packet.
1899 ScopedPacketBundler
ack_bundler(this, BUNDLE_PENDING_ACK
);
1900 packet_generator_
.AddControlFrame(
1901 QuicFrame(new QuicGoAwayFrame(error
, last_good_stream_id
, reason
)));
1904 void QuicConnection::CloseFecGroupsBefore(
1905 QuicPacketSequenceNumber sequence_number
) {
1906 FecGroupMap::iterator it
= group_map_
.begin();
1907 while (it
!= group_map_
.end()) {
1908 // If this is the current group or the group doesn't protect this packet
1909 // we can ignore it.
1910 if (last_header_
.fec_group
== it
->first
||
1911 !it
->second
->ProtectsPacketsBefore(sequence_number
)) {
1915 QuicFecGroup
* fec_group
= it
->second
;
1916 DCHECK(!fec_group
->CanRevive());
1917 FecGroupMap::iterator next
= it
;
1919 group_map_
.erase(it
);
1925 QuicByteCount
QuicConnection::max_packet_length() const {
1926 return packet_generator_
.max_packet_length();
1929 void QuicConnection::set_max_packet_length(QuicByteCount length
) {
1930 return packet_generator_
.set_max_packet_length(length
);
1933 bool QuicConnection::HasQueuedData() const {
1934 return pending_version_negotiation_packet_
||
1935 !queued_packets_
.empty() || packet_generator_
.HasQueuedFrames();
1938 bool QuicConnection::CanWriteStreamData() {
1939 // Don't write stream data if there are negotiation or queued data packets
1940 // to send. Otherwise, continue and bundle as many frames as possible.
1941 if (pending_version_negotiation_packet_
|| !queued_packets_
.empty()) {
1945 IsHandshake pending_handshake
= visitor_
->HasPendingHandshake() ?
1946 IS_HANDSHAKE
: NOT_HANDSHAKE
;
1947 // Sending queued packets may have caused the socket to become write blocked,
1948 // or the congestion manager to prohibit sending. If we've sent everything
1949 // we had queued and we're still not blocked, let the visitor know it can
1951 return ShouldGeneratePacket(NOT_RETRANSMISSION
, HAS_RETRANSMITTABLE_DATA
,
1955 void QuicConnection::SetNetworkTimeouts(QuicTime::Delta overall_timeout
,
1956 QuicTime::Delta idle_timeout
) {
1957 LOG_IF(DFATAL
, idle_timeout
> overall_timeout
)
1958 << "idle_timeout:" << idle_timeout
.ToMilliseconds()
1959 << " overall_timeout:" << overall_timeout
.ToMilliseconds();
1960 // Adjust the idle timeout on client and server to prevent clients from
1961 // sending requests to servers which have already closed the connection.
1963 idle_timeout
= idle_timeout
.Add(QuicTime::Delta::FromSeconds(3));
1964 } else if (idle_timeout
> QuicTime::Delta::FromSeconds(1)) {
1965 idle_timeout
= idle_timeout
.Subtract(QuicTime::Delta::FromSeconds(1));
1967 overall_connection_timeout_
= overall_timeout
;
1968 idle_network_timeout_
= idle_timeout
;
1973 void QuicConnection::CheckForTimeout() {
1974 QuicTime now
= clock_
->ApproximateNow();
1975 QuicTime time_of_last_packet
= max(time_of_last_received_packet_
,
1976 time_of_last_sent_new_packet_
);
1978 // |delta| can be < 0 as |now| is approximate time but |time_of_last_packet|
1979 // is accurate time. However, this should not change the behavior of
1980 // timeout handling.
1981 QuicTime::Delta idle_duration
= now
.Subtract(time_of_last_packet
);
1982 DVLOG(1) << ENDPOINT
<< "last packet "
1983 << time_of_last_packet
.ToDebuggingValue()
1984 << " now:" << now
.ToDebuggingValue()
1985 << " idle_duration:" << idle_duration
.ToMicroseconds()
1986 << " idle_network_timeout: "
1987 << idle_network_timeout_
.ToMicroseconds();
1988 if (idle_duration
>= idle_network_timeout_
) {
1989 DVLOG(1) << ENDPOINT
<< "Connection timedout due to no network activity.";
1990 SendConnectionClose(QUIC_CONNECTION_TIMED_OUT
);
1994 if (!overall_connection_timeout_
.IsInfinite()) {
1995 QuicTime::Delta connected_duration
=
1996 now
.Subtract(stats_
.connection_creation_time
);
1997 DVLOG(1) << ENDPOINT
<< "connection time: "
1998 << connected_duration
.ToMicroseconds() << " overall timeout: "
1999 << overall_connection_timeout_
.ToMicroseconds();
2000 if (connected_duration
>= overall_connection_timeout_
) {
2001 DVLOG(1) << ENDPOINT
<<
2002 "Connection timedout due to overall connection timeout.";
2003 SendConnectionClose(QUIC_CONNECTION_OVERALL_TIMED_OUT
);
2011 void QuicConnection::SetTimeoutAlarm() {
2012 QuicTime time_of_last_packet
= max(time_of_last_received_packet_
,
2013 time_of_last_sent_new_packet_
);
2015 QuicTime deadline
= time_of_last_packet
.Add(idle_network_timeout_
);
2016 if (!overall_connection_timeout_
.IsInfinite()) {
2017 deadline
= min(deadline
,
2018 stats_
.connection_creation_time
.Add(
2019 overall_connection_timeout_
));
2022 timeout_alarm_
->Cancel();
2023 timeout_alarm_
->Set(deadline
);
2026 void QuicConnection::SetPingAlarm() {
2028 // Only clients send pings.
2031 if (!visitor_
->HasOpenDataStreams()) {
2032 ping_alarm_
->Cancel();
2033 // Don't send a ping unless there are open streams.
2036 QuicTime::Delta ping_timeout
= QuicTime::Delta::FromSeconds(kPingTimeoutSecs
);
2037 ping_alarm_
->Update(clock_
->ApproximateNow().Add(ping_timeout
),
2038 QuicTime::Delta::FromSeconds(1));
2041 QuicConnection::ScopedPacketBundler::ScopedPacketBundler(
2042 QuicConnection
* connection
,
2043 AckBundling send_ack
)
2044 : connection_(connection
),
2045 already_in_batch_mode_(connection
!= nullptr &&
2046 connection
->packet_generator_
.InBatchMode()) {
2047 if (connection_
== nullptr) {
2050 // Move generator into batch mode. If caller wants us to include an ack,
2051 // check the delayed-ack timer to see if there's ack info to be sent.
2052 if (!already_in_batch_mode_
) {
2053 DVLOG(1) << "Entering Batch Mode.";
2054 connection_
->packet_generator_
.StartBatchOperations();
2056 // Bundle an ack if the alarm is set or with every second packet if we need to
2057 // raise the peer's least unacked.
2059 connection_
->ack_alarm_
->IsSet() || connection_
->stop_waiting_count_
> 1;
2060 if (send_ack
== SEND_ACK
|| (send_ack
== BUNDLE_PENDING_ACK
&& ack_pending
)) {
2061 DVLOG(1) << "Bundling ack with outgoing packet.";
2062 connection_
->SendAck();
2066 QuicConnection::ScopedPacketBundler::~ScopedPacketBundler() {
2067 if (connection_
== nullptr) {
2070 // If we changed the generator's batch state, restore original batch state.
2071 if (!already_in_batch_mode_
) {
2072 DVLOG(1) << "Leaving Batch Mode.";
2073 connection_
->packet_generator_
.FinishBatchOperations();
2075 DCHECK_EQ(already_in_batch_mode_
,
2076 connection_
->packet_generator_
.InBatchMode());
2079 HasRetransmittableData
QuicConnection::IsRetransmittable(
2080 const QueuedPacket
& packet
) {
2081 // Retransmitted packets retransmittable frames are owned by the unacked
2082 // packet map, but are not present in the serialized packet.
2083 if (packet
.transmission_type
!= NOT_RETRANSMISSION
||
2084 packet
.serialized_packet
.retransmittable_frames
!= nullptr) {
2085 return HAS_RETRANSMITTABLE_DATA
;
2087 return NO_RETRANSMITTABLE_DATA
;
2091 bool QuicConnection::IsConnectionClose(const QueuedPacket
& packet
) {
2092 const RetransmittableFrames
* retransmittable_frames
=
2093 packet
.serialized_packet
.retransmittable_frames
;
2094 if (retransmittable_frames
== nullptr) {
2097 for (const QuicFrame
& frame
: retransmittable_frames
->frames()) {
2098 if (frame
.type
== CONNECTION_CLOSE_FRAME
) {