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 bool Near(QuicPacketSequenceNumber a
, QuicPacketSequenceNumber b
) {
65 QuicPacketSequenceNumber delta
= (a
> b
) ? a
- b
: b
- a
;
66 return delta
<= kMaxPacketGap
;
69 // An alarm that is scheduled to send an ack if a timeout occurs.
70 class AckAlarm
: public QuicAlarm::Delegate
{
72 explicit AckAlarm(QuicConnection
* connection
)
73 : connection_(connection
) {
76 QuicTime
OnAlarm() override
{
77 connection_
->SendAck();
78 return QuicTime::Zero();
82 QuicConnection
* connection_
;
84 DISALLOW_COPY_AND_ASSIGN(AckAlarm
);
87 // This alarm will be scheduled any time a data-bearing packet is sent out.
88 // When the alarm goes off, the connection checks to see if the oldest packets
89 // have been acked, and retransmit them if they have not.
90 class RetransmissionAlarm
: public QuicAlarm::Delegate
{
92 explicit RetransmissionAlarm(QuicConnection
* connection
)
93 : connection_(connection
) {
96 QuicTime
OnAlarm() override
{
97 connection_
->OnRetransmissionTimeout();
98 return QuicTime::Zero();
102 QuicConnection
* connection_
;
104 DISALLOW_COPY_AND_ASSIGN(RetransmissionAlarm
);
107 // An alarm that is scheduled when the sent scheduler requires a
108 // a delay before sending packets and fires when the packet may be sent.
109 class SendAlarm
: public QuicAlarm::Delegate
{
111 explicit SendAlarm(QuicConnection
* connection
)
112 : connection_(connection
) {
115 QuicTime
OnAlarm() override
{
116 connection_
->WriteIfNotBlocked();
117 // Never reschedule the alarm, since CanWrite does that.
118 return QuicTime::Zero();
122 QuicConnection
* connection_
;
124 DISALLOW_COPY_AND_ASSIGN(SendAlarm
);
127 class TimeoutAlarm
: public QuicAlarm::Delegate
{
129 explicit TimeoutAlarm(QuicConnection
* connection
)
130 : connection_(connection
) {
133 QuicTime
OnAlarm() override
{
134 connection_
->CheckForTimeout();
135 // Never reschedule the alarm, since CheckForTimeout does that.
136 return QuicTime::Zero();
140 QuicConnection
* connection_
;
142 DISALLOW_COPY_AND_ASSIGN(TimeoutAlarm
);
145 class PingAlarm
: public QuicAlarm::Delegate
{
147 explicit PingAlarm(QuicConnection
* connection
)
148 : connection_(connection
) {
151 QuicTime
OnAlarm() override
{
152 connection_
->SendPing();
153 return QuicTime::Zero();
157 QuicConnection
* connection_
;
159 DISALLOW_COPY_AND_ASSIGN(PingAlarm
);
162 // This alarm may be scheduled when an FEC protected packet is sent out.
163 class FecAlarm
: public QuicAlarm::Delegate
{
165 explicit FecAlarm(QuicPacketGenerator
* packet_generator
)
166 : packet_generator_(packet_generator
) {}
168 QuicTime
OnAlarm() override
{
169 packet_generator_
->OnFecTimeout();
170 return QuicTime::Zero();
174 QuicPacketGenerator
* packet_generator_
;
176 DISALLOW_COPY_AND_ASSIGN(FecAlarm
);
181 QuicConnection::QueuedPacket::QueuedPacket(SerializedPacket packet
,
182 EncryptionLevel level
)
183 : serialized_packet(packet
),
184 encryption_level(level
),
185 transmission_type(NOT_RETRANSMISSION
),
186 original_sequence_number(0) {
189 QuicConnection::QueuedPacket::QueuedPacket(
190 SerializedPacket packet
,
191 EncryptionLevel level
,
192 TransmissionType transmission_type
,
193 QuicPacketSequenceNumber original_sequence_number
)
194 : serialized_packet(packet
),
195 encryption_level(level
),
196 transmission_type(transmission_type
),
197 original_sequence_number(original_sequence_number
) {
200 #define ENDPOINT (is_server_ ? "Server: " : " Client: ")
202 QuicConnection::QuicConnection(QuicConnectionId connection_id
,
204 QuicConnectionHelperInterface
* helper
,
205 const PacketWriterFactory
& writer_factory
,
209 const QuicVersionVector
& supported_versions
)
210 : framer_(supported_versions
,
211 helper
->GetClock()->ApproximateNow(),
214 writer_(writer_factory
.Create(this)),
215 owns_writer_(owns_writer
),
216 encryption_level_(ENCRYPTION_NONE
),
217 has_forward_secure_encrypter_(false),
218 first_required_forward_secure_packet_(0),
219 clock_(helper
->GetClock()),
220 random_generator_(helper
->GetRandomGenerator()),
221 connection_id_(connection_id
),
222 peer_address_(address
),
223 migrating_peer_port_(0),
224 last_packet_decrypted_(false),
225 last_packet_revived_(false),
227 last_decrypted_packet_level_(ENCRYPTION_NONE
),
228 largest_seen_packet_with_ack_(0),
229 largest_seen_packet_with_stop_waiting_(0),
230 max_undecryptable_packets_(0),
231 pending_version_negotiation_packet_(false),
232 silent_close_enabled_(false),
233 received_packet_manager_(&stats_
),
235 num_packets_received_since_last_ack_sent_(0),
236 stop_waiting_count_(0),
237 ack_alarm_(helper
->CreateAlarm(new AckAlarm(this))),
238 retransmission_alarm_(helper
->CreateAlarm(new RetransmissionAlarm(this))),
239 send_alarm_(helper
->CreateAlarm(new SendAlarm(this))),
240 resume_writes_alarm_(helper
->CreateAlarm(new SendAlarm(this))),
241 timeout_alarm_(helper
->CreateAlarm(new TimeoutAlarm(this))),
242 ping_alarm_(helper
->CreateAlarm(new PingAlarm(this))),
244 debug_visitor_(nullptr),
245 packet_generator_(connection_id_
, &framer_
, random_generator_
, this),
246 fec_alarm_(helper
->CreateAlarm(new FecAlarm(&packet_generator_
))),
247 idle_network_timeout_(QuicTime::Delta::Infinite()),
248 overall_connection_timeout_(QuicTime::Delta::Infinite()),
249 time_of_last_received_packet_(clock_
->ApproximateNow()),
250 time_of_last_sent_new_packet_(clock_
->ApproximateNow()),
251 sequence_number_of_last_sent_packet_(0),
252 sent_packet_manager_(
256 FLAGS_quic_use_bbr_congestion_control
? kBBR
: kCubic
,
257 FLAGS_quic_use_time_loss_detection
? kTime
: kNack
,
259 version_negotiation_state_(START_NEGOTIATION
),
260 is_server_(is_server
),
262 peer_ip_changed_(false),
263 peer_port_changed_(false),
264 self_ip_changed_(false),
265 self_port_changed_(false),
266 can_truncate_connection_ids_(true),
267 is_secure_(is_secure
) {
268 DVLOG(1) << ENDPOINT
<< "Created connection with connection_id: "
270 framer_
.set_visitor(this);
271 framer_
.set_received_entropy_calculator(&received_packet_manager_
);
272 stats_
.connection_creation_time
= clock_
->ApproximateNow();
273 sent_packet_manager_
.set_network_change_visitor(this);
274 if (FLAGS_quic_small_default_packet_size
&& is_server_
) {
275 set_max_packet_length(kDefaultServerMaxPacketSize
);
279 QuicConnection::~QuicConnection() {
283 STLDeleteElements(&undecryptable_packets_
);
284 STLDeleteValues(&group_map_
);
285 for (QueuedPacketList::iterator it
= queued_packets_
.begin();
286 it
!= queued_packets_
.end(); ++it
) {
287 delete it
->serialized_packet
.retransmittable_frames
;
288 delete it
->serialized_packet
.packet
;
292 void QuicConnection::SetFromConfig(const QuicConfig
& config
) {
293 if (config
.negotiated()) {
294 SetNetworkTimeouts(QuicTime::Delta::Infinite(),
295 config
.IdleConnectionStateLifetime());
296 if (config
.SilentClose()) {
297 silent_close_enabled_
= true;
300 SetNetworkTimeouts(config
.max_time_before_crypto_handshake(),
301 config
.max_idle_time_before_crypto_handshake());
304 sent_packet_manager_
.SetFromConfig(config
);
305 if (config
.HasReceivedBytesForConnectionId() &&
306 can_truncate_connection_ids_
) {
307 packet_generator_
.SetConnectionIdLength(
308 config
.ReceivedBytesForConnectionId());
310 max_undecryptable_packets_
= config
.max_undecryptable_packets();
313 bool QuicConnection::ResumeConnectionState(
314 const CachedNetworkParameters
& cached_network_params
) {
315 return sent_packet_manager_
.ResumeConnectionState(cached_network_params
);
318 void QuicConnection::SetNumOpenStreams(size_t num_streams
) {
319 sent_packet_manager_
.SetNumOpenStreams(num_streams
);
322 bool QuicConnection::SelectMutualVersion(
323 const QuicVersionVector
& available_versions
) {
324 // Try to find the highest mutual version by iterating over supported
325 // versions, starting with the highest, and breaking out of the loop once we
326 // find a matching version in the provided available_versions vector.
327 const QuicVersionVector
& supported_versions
= framer_
.supported_versions();
328 for (size_t i
= 0; i
< supported_versions
.size(); ++i
) {
329 const QuicVersion
& version
= supported_versions
[i
];
330 if (std::find(available_versions
.begin(), available_versions
.end(),
331 version
) != available_versions
.end()) {
332 framer_
.set_version(version
);
340 void QuicConnection::OnError(QuicFramer
* framer
) {
341 // Packets that we can not or have not decrypted are dropped.
342 // TODO(rch): add stats to measure this.
343 if (!connected_
|| last_packet_decrypted_
== false) {
346 SendConnectionCloseWithDetails(framer
->error(), framer
->detailed_error());
349 void QuicConnection::MaybeSetFecAlarm(
350 QuicPacketSequenceNumber sequence_number
) {
351 if (fec_alarm_
->IsSet()) {
354 QuicTime::Delta timeout
= packet_generator_
.GetFecTimeout(sequence_number
);
355 if (!timeout
.IsInfinite()) {
356 fec_alarm_
->Set(clock_
->ApproximateNow().Add(timeout
));
360 void QuicConnection::OnPacket() {
361 DCHECK(last_stream_frames_
.empty() &&
362 last_ack_frames_
.empty() &&
363 last_stop_waiting_frames_
.empty() &&
364 last_rst_frames_
.empty() &&
365 last_goaway_frames_
.empty() &&
366 last_window_update_frames_
.empty() &&
367 last_blocked_frames_
.empty() &&
368 last_ping_frames_
.empty() &&
369 last_close_frames_
.empty());
370 last_packet_decrypted_
= false;
371 last_packet_revived_
= false;
374 void QuicConnection::OnPublicResetPacket(
375 const QuicPublicResetPacket
& packet
) {
376 if (debug_visitor_
!= nullptr) {
377 debug_visitor_
->OnPublicResetPacket(packet
);
379 CloseConnection(QUIC_PUBLIC_RESET
, true);
381 DVLOG(1) << ENDPOINT
<< "Connection " << connection_id()
382 << " closed via QUIC_PUBLIC_RESET from peer.";
385 bool QuicConnection::OnProtocolVersionMismatch(QuicVersion received_version
) {
386 DVLOG(1) << ENDPOINT
<< "Received packet with mismatched version "
388 // TODO(satyamshekhar): Implement no server state in this mode.
390 LOG(DFATAL
) << ENDPOINT
<< "Framer called OnProtocolVersionMismatch. "
391 << "Closing connection.";
392 CloseConnection(QUIC_INTERNAL_ERROR
, false);
395 DCHECK_NE(version(), received_version
);
397 if (debug_visitor_
!= nullptr) {
398 debug_visitor_
->OnProtocolVersionMismatch(received_version
);
401 switch (version_negotiation_state_
) {
402 case START_NEGOTIATION
:
403 if (!framer_
.IsSupportedVersion(received_version
)) {
404 SendVersionNegotiationPacket();
405 version_negotiation_state_
= NEGOTIATION_IN_PROGRESS
;
410 case NEGOTIATION_IN_PROGRESS
:
411 if (!framer_
.IsSupportedVersion(received_version
)) {
412 SendVersionNegotiationPacket();
417 case NEGOTIATED_VERSION
:
418 // Might be old packets that were sent by the client before the version
419 // was negotiated. Drop these.
426 version_negotiation_state_
= NEGOTIATED_VERSION
;
427 visitor_
->OnSuccessfulVersionNegotiation(received_version
);
428 if (debug_visitor_
!= nullptr) {
429 debug_visitor_
->OnSuccessfulVersionNegotiation(received_version
);
431 DVLOG(1) << ENDPOINT
<< "version negotiated " << received_version
;
433 // Store the new version.
434 framer_
.set_version(received_version
);
436 // TODO(satyamshekhar): Store the sequence number of this packet and close the
437 // connection if we ever received a packet with incorrect version and whose
438 // sequence number is greater.
442 // Handles version negotiation for client connection.
443 void QuicConnection::OnVersionNegotiationPacket(
444 const QuicVersionNegotiationPacket
& packet
) {
446 LOG(DFATAL
) << ENDPOINT
<< "Framer parsed VersionNegotiationPacket."
447 << " Closing connection.";
448 CloseConnection(QUIC_INTERNAL_ERROR
, false);
451 if (debug_visitor_
!= nullptr) {
452 debug_visitor_
->OnVersionNegotiationPacket(packet
);
455 if (version_negotiation_state_
!= START_NEGOTIATION
) {
456 // Possibly a duplicate version negotiation packet.
460 if (std::find(packet
.versions
.begin(),
461 packet
.versions
.end(), version()) !=
462 packet
.versions
.end()) {
463 DLOG(WARNING
) << ENDPOINT
<< "The server already supports our version. "
464 << "It should have accepted our connection.";
465 // Just drop the connection.
466 CloseConnection(QUIC_INVALID_VERSION_NEGOTIATION_PACKET
, false);
470 if (!SelectMutualVersion(packet
.versions
)) {
471 SendConnectionCloseWithDetails(QUIC_INVALID_VERSION
,
472 "no common version found");
477 << "Negotiated version: " << QuicVersionToString(version());
478 server_supported_versions_
= packet
.versions
;
479 version_negotiation_state_
= NEGOTIATION_IN_PROGRESS
;
480 RetransmitUnackedPackets(ALL_UNACKED_RETRANSMISSION
);
483 void QuicConnection::OnRevivedPacket() {
486 bool QuicConnection::OnUnauthenticatedPublicHeader(
487 const QuicPacketPublicHeader
& header
) {
491 bool QuicConnection::OnUnauthenticatedHeader(const QuicPacketHeader
& header
) {
495 void QuicConnection::OnDecryptedPacket(EncryptionLevel level
) {
496 last_decrypted_packet_level_
= level
;
497 last_packet_decrypted_
= true;
498 // If this packet was foward-secure encrypted and the forward-secure encrypter
499 // is not being used, start using it.
500 if (encryption_level_
!= ENCRYPTION_FORWARD_SECURE
&&
501 has_forward_secure_encrypter_
&& level
== ENCRYPTION_FORWARD_SECURE
) {
502 SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE
);
506 bool QuicConnection::OnPacketHeader(const QuicPacketHeader
& header
) {
507 if (debug_visitor_
!= nullptr) {
508 debug_visitor_
->OnPacketHeader(header
);
511 if (!ProcessValidatedPacket()) {
515 // Will be decrement below if we fall through to return true;
516 ++stats_
.packets_dropped
;
518 if (header
.public_header
.connection_id
!= connection_id_
) {
519 DVLOG(1) << ENDPOINT
<< "Ignoring packet from unexpected ConnectionId: "
520 << header
.public_header
.connection_id
<< " instead of "
522 if (debug_visitor_
!= nullptr) {
523 debug_visitor_
->OnIncorrectConnectionId(
524 header
.public_header
.connection_id
);
529 if (!Near(header
.packet_sequence_number
,
530 last_header_
.packet_sequence_number
)) {
531 DVLOG(1) << ENDPOINT
<< "Packet " << header
.packet_sequence_number
532 << " out of bounds. Discarding";
533 SendConnectionCloseWithDetails(QUIC_INVALID_PACKET_HEADER
,
534 "Packet sequence number out of bounds");
538 // If this packet has already been seen, or that the sender
539 // has told us will not be retransmitted, then stop processing the packet.
540 if (!received_packet_manager_
.IsAwaitingPacket(
541 header
.packet_sequence_number
)) {
542 DVLOG(1) << ENDPOINT
<< "Packet " << header
.packet_sequence_number
543 << " no longer being waited for. Discarding.";
544 if (debug_visitor_
!= nullptr) {
545 debug_visitor_
->OnDuplicatePacket(header
.packet_sequence_number
);
550 if (version_negotiation_state_
!= NEGOTIATED_VERSION
) {
552 if (!header
.public_header
.version_flag
) {
553 DLOG(WARNING
) << ENDPOINT
<< "Packet " << header
.packet_sequence_number
554 << " without version flag before version negotiated.";
555 // Packets should have the version flag till version negotiation is
557 CloseConnection(QUIC_INVALID_VERSION
, false);
560 DCHECK_EQ(1u, header
.public_header
.versions
.size());
561 DCHECK_EQ(header
.public_header
.versions
[0], version());
562 version_negotiation_state_
= NEGOTIATED_VERSION
;
563 visitor_
->OnSuccessfulVersionNegotiation(version());
564 if (debug_visitor_
!= nullptr) {
565 debug_visitor_
->OnSuccessfulVersionNegotiation(version());
569 DCHECK(!header
.public_header
.version_flag
);
570 // If the client gets a packet without the version flag from the server
571 // it should stop sending version since the version negotiation is done.
572 packet_generator_
.StopSendingVersion();
573 version_negotiation_state_
= NEGOTIATED_VERSION
;
574 visitor_
->OnSuccessfulVersionNegotiation(version());
575 if (debug_visitor_
!= nullptr) {
576 debug_visitor_
->OnSuccessfulVersionNegotiation(version());
581 DCHECK_EQ(NEGOTIATED_VERSION
, version_negotiation_state_
);
583 --stats_
.packets_dropped
;
584 DVLOG(1) << ENDPOINT
<< "Received packet header: " << header
;
585 last_header_
= header
;
590 void QuicConnection::OnFecProtectedPayload(StringPiece payload
) {
591 DCHECK_EQ(IN_FEC_GROUP
, last_header_
.is_in_fec_group
);
592 DCHECK_NE(0u, last_header_
.fec_group
);
593 QuicFecGroup
* group
= GetFecGroup();
594 if (group
!= nullptr) {
595 group
->Update(last_decrypted_packet_level_
, last_header_
, payload
);
599 bool QuicConnection::OnStreamFrame(const QuicStreamFrame
& frame
) {
601 if (debug_visitor_
!= nullptr) {
602 debug_visitor_
->OnStreamFrame(frame
);
604 if (frame
.stream_id
!= kCryptoStreamId
&&
605 last_decrypted_packet_level_
== ENCRYPTION_NONE
) {
606 DLOG(WARNING
) << ENDPOINT
607 << "Received an unencrypted data frame: closing connection";
608 SendConnectionClose(QUIC_UNENCRYPTED_STREAM_DATA
);
611 last_stream_frames_
.push_back(frame
);
615 bool QuicConnection::OnAckFrame(const QuicAckFrame
& incoming_ack
) {
617 if (debug_visitor_
!= nullptr) {
618 debug_visitor_
->OnAckFrame(incoming_ack
);
620 DVLOG(1) << ENDPOINT
<< "OnAckFrame: " << incoming_ack
;
622 if (last_header_
.packet_sequence_number
<= largest_seen_packet_with_ack_
) {
623 DVLOG(1) << ENDPOINT
<< "Received an old ack frame: ignoring";
627 if (!ValidateAckFrame(incoming_ack
)) {
628 SendConnectionClose(QUIC_INVALID_ACK_DATA
);
632 last_ack_frames_
.push_back(incoming_ack
);
636 void QuicConnection::ProcessAckFrame(const QuicAckFrame
& incoming_ack
) {
637 largest_seen_packet_with_ack_
= last_header_
.packet_sequence_number
;
638 sent_packet_manager_
.OnIncomingAck(incoming_ack
,
639 time_of_last_received_packet_
);
640 sent_entropy_manager_
.ClearEntropyBefore(
641 sent_packet_manager_
.least_packet_awaited_by_peer() - 1);
642 if (sent_packet_manager_
.HasPendingRetransmissions()) {
646 // Always reset the retransmission alarm when an ack comes in, since we now
647 // have a better estimate of the current rtt than when it was set.
648 QuicTime retransmission_time
= sent_packet_manager_
.GetRetransmissionTime();
649 retransmission_alarm_
->Update(retransmission_time
,
650 QuicTime::Delta::FromMilliseconds(1));
653 void QuicConnection::ProcessStopWaitingFrame(
654 const QuicStopWaitingFrame
& stop_waiting
) {
655 largest_seen_packet_with_stop_waiting_
= last_header_
.packet_sequence_number
;
656 received_packet_manager_
.UpdatePacketInformationSentByPeer(stop_waiting
);
657 // Possibly close any FecGroups which are now irrelevant.
658 CloseFecGroupsBefore(stop_waiting
.least_unacked
+ 1);
661 bool QuicConnection::OnStopWaitingFrame(const QuicStopWaitingFrame
& frame
) {
664 if (last_header_
.packet_sequence_number
<=
665 largest_seen_packet_with_stop_waiting_
) {
666 DVLOG(1) << ENDPOINT
<< "Received an old stop waiting frame: ignoring";
670 if (!ValidateStopWaitingFrame(frame
)) {
671 SendConnectionClose(QUIC_INVALID_STOP_WAITING_DATA
);
675 if (debug_visitor_
!= nullptr) {
676 debug_visitor_
->OnStopWaitingFrame(frame
);
679 last_stop_waiting_frames_
.push_back(frame
);
683 bool QuicConnection::OnPingFrame(const QuicPingFrame
& frame
) {
685 if (debug_visitor_
!= nullptr) {
686 debug_visitor_
->OnPingFrame(frame
);
688 last_ping_frames_
.push_back(frame
);
692 bool QuicConnection::ValidateAckFrame(const QuicAckFrame
& incoming_ack
) {
693 if (incoming_ack
.largest_observed
> packet_generator_
.sequence_number()) {
694 DLOG(ERROR
) << ENDPOINT
<< "Peer's observed unsent packet:"
695 << incoming_ack
.largest_observed
<< " vs "
696 << packet_generator_
.sequence_number();
697 // We got an error for data we have not sent. Error out.
701 if (incoming_ack
.largest_observed
< sent_packet_manager_
.largest_observed()) {
702 DLOG(ERROR
) << ENDPOINT
<< "Peer's largest_observed packet decreased:"
703 << incoming_ack
.largest_observed
<< " vs "
704 << sent_packet_manager_
.largest_observed();
705 // A new ack has a diminished largest_observed value. Error out.
706 // If this was an old packet, we wouldn't even have checked.
710 if (!incoming_ack
.missing_packets
.empty() &&
711 *incoming_ack
.missing_packets
.rbegin() > incoming_ack
.largest_observed
) {
712 DLOG(ERROR
) << ENDPOINT
<< "Peer sent missing packet: "
713 << *incoming_ack
.missing_packets
.rbegin()
714 << " which is greater than largest observed: "
715 << incoming_ack
.largest_observed
;
719 if (!incoming_ack
.missing_packets
.empty() &&
720 *incoming_ack
.missing_packets
.begin() <
721 sent_packet_manager_
.least_packet_awaited_by_peer()) {
722 DLOG(ERROR
) << ENDPOINT
<< "Peer sent missing packet: "
723 << *incoming_ack
.missing_packets
.begin()
724 << " which is smaller than least_packet_awaited_by_peer_: "
725 << sent_packet_manager_
.least_packet_awaited_by_peer();
729 if (!sent_entropy_manager_
.IsValidEntropy(
730 incoming_ack
.largest_observed
,
731 incoming_ack
.missing_packets
,
732 incoming_ack
.entropy_hash
)) {
733 DLOG(ERROR
) << ENDPOINT
<< "Peer sent invalid entropy.";
737 for (SequenceNumberSet::const_iterator iter
=
738 incoming_ack
.revived_packets
.begin();
739 iter
!= incoming_ack
.revived_packets
.end(); ++iter
) {
740 if (!ContainsKey(incoming_ack
.missing_packets
, *iter
)) {
741 DLOG(ERROR
) << ENDPOINT
742 << "Peer specified revived packet which was not missing.";
749 bool QuicConnection::ValidateStopWaitingFrame(
750 const QuicStopWaitingFrame
& stop_waiting
) {
751 if (stop_waiting
.least_unacked
<
752 received_packet_manager_
.peer_least_packet_awaiting_ack()) {
753 DLOG(ERROR
) << ENDPOINT
<< "Peer's sent low least_unacked: "
754 << stop_waiting
.least_unacked
<< " vs "
755 << received_packet_manager_
.peer_least_packet_awaiting_ack();
756 // We never process old ack frames, so this number should only increase.
760 if (stop_waiting
.least_unacked
>
761 last_header_
.packet_sequence_number
) {
762 DLOG(ERROR
) << ENDPOINT
<< "Peer sent least_unacked:"
763 << stop_waiting
.least_unacked
764 << " greater than the enclosing packet sequence number:"
765 << last_header_
.packet_sequence_number
;
772 void QuicConnection::OnFecData(const QuicFecData
& fec
) {
773 DCHECK_EQ(IN_FEC_GROUP
, last_header_
.is_in_fec_group
);
774 DCHECK_NE(0u, last_header_
.fec_group
);
775 QuicFecGroup
* group
= GetFecGroup();
776 if (group
!= nullptr) {
777 group
->UpdateFec(last_decrypted_packet_level_
,
778 last_header_
.packet_sequence_number
, fec
);
782 bool QuicConnection::OnRstStreamFrame(const QuicRstStreamFrame
& frame
) {
784 if (debug_visitor_
!= nullptr) {
785 debug_visitor_
->OnRstStreamFrame(frame
);
787 DVLOG(1) << ENDPOINT
<< "Stream reset with error "
788 << QuicUtils::StreamErrorToString(frame
.error_code
);
789 last_rst_frames_
.push_back(frame
);
793 bool QuicConnection::OnConnectionCloseFrame(
794 const QuicConnectionCloseFrame
& frame
) {
796 if (debug_visitor_
!= nullptr) {
797 debug_visitor_
->OnConnectionCloseFrame(frame
);
799 DVLOG(1) << ENDPOINT
<< "Connection " << connection_id()
800 << " closed with error "
801 << QuicUtils::ErrorToString(frame
.error_code
)
802 << " " << frame
.error_details
;
803 last_close_frames_
.push_back(frame
);
807 bool QuicConnection::OnGoAwayFrame(const QuicGoAwayFrame
& frame
) {
809 if (debug_visitor_
!= nullptr) {
810 debug_visitor_
->OnGoAwayFrame(frame
);
812 DVLOG(1) << ENDPOINT
<< "Go away received with error "
813 << QuicUtils::ErrorToString(frame
.error_code
)
814 << " and reason:" << frame
.reason_phrase
;
815 last_goaway_frames_
.push_back(frame
);
819 bool QuicConnection::OnWindowUpdateFrame(const QuicWindowUpdateFrame
& frame
) {
821 if (debug_visitor_
!= nullptr) {
822 debug_visitor_
->OnWindowUpdateFrame(frame
);
824 DVLOG(1) << ENDPOINT
<< "WindowUpdate received for stream: "
825 << frame
.stream_id
<< " with byte offset: " << frame
.byte_offset
;
826 last_window_update_frames_
.push_back(frame
);
830 bool QuicConnection::OnBlockedFrame(const QuicBlockedFrame
& frame
) {
832 if (debug_visitor_
!= nullptr) {
833 debug_visitor_
->OnBlockedFrame(frame
);
835 DVLOG(1) << ENDPOINT
<< "Blocked frame received for stream: "
837 last_blocked_frames_
.push_back(frame
);
841 void QuicConnection::OnPacketComplete() {
842 // Don't do anything if this packet closed the connection.
848 DVLOG(1) << ENDPOINT
<< (last_packet_revived_
? "Revived" : "Got")
849 << " packet " << last_header_
.packet_sequence_number
850 << " with " << last_stream_frames_
.size()<< " stream frames "
851 << last_ack_frames_
.size() << " acks, "
852 << last_stop_waiting_frames_
.size() << " stop_waiting, "
853 << last_rst_frames_
.size() << " rsts, "
854 << last_goaway_frames_
.size() << " goaways, "
855 << last_window_update_frames_
.size() << " window updates, "
856 << last_blocked_frames_
.size() << " blocked, "
857 << last_ping_frames_
.size() << " pings, "
858 << last_close_frames_
.size() << " closes, "
859 << "for " << last_header_
.public_header
.connection_id
;
861 ++num_packets_received_since_last_ack_sent_
;
863 // Call MaybeQueueAck() before recording the received packet, since we want
864 // to trigger an ack if the newly received packet was previously missing.
867 // Record received or revived packet to populate ack info correctly before
868 // processing stream frames, since the processing may result in a response
869 // packet with a bundled ack.
870 if (last_packet_revived_
) {
871 received_packet_manager_
.RecordPacketRevived(
872 last_header_
.packet_sequence_number
);
874 received_packet_manager_
.RecordPacketReceived(
875 last_size_
, last_header_
, time_of_last_received_packet_
);
878 if (!last_stream_frames_
.empty()) {
879 visitor_
->OnStreamFrames(last_stream_frames_
);
882 for (size_t i
= 0; i
< last_stream_frames_
.size(); ++i
) {
883 stats_
.stream_bytes_received
+=
884 last_stream_frames_
[i
].data
.TotalBufferSize();
887 // Process window updates, blocked, stream resets, acks, then congestion
889 if (!last_window_update_frames_
.empty()) {
890 visitor_
->OnWindowUpdateFrames(last_window_update_frames_
);
892 if (!last_blocked_frames_
.empty()) {
893 visitor_
->OnBlockedFrames(last_blocked_frames_
);
895 for (size_t i
= 0; i
< last_goaway_frames_
.size(); ++i
) {
896 visitor_
->OnGoAway(last_goaway_frames_
[i
]);
898 for (size_t i
= 0; i
< last_rst_frames_
.size(); ++i
) {
899 visitor_
->OnRstStream(last_rst_frames_
[i
]);
901 for (size_t i
= 0; i
< last_ack_frames_
.size(); ++i
) {
902 ProcessAckFrame(last_ack_frames_
[i
]);
904 for (size_t i
= 0; i
< last_stop_waiting_frames_
.size(); ++i
) {
905 ProcessStopWaitingFrame(last_stop_waiting_frames_
[i
]);
907 if (!last_close_frames_
.empty()) {
908 CloseConnection(last_close_frames_
[0].error_code
, true);
912 // If there are new missing packets to report, send an ack immediately.
913 if (received_packet_manager_
.HasNewMissingPackets()) {
915 ack_alarm_
->Cancel();
918 UpdateStopWaitingCount();
920 MaybeCloseIfTooManyOutstandingPackets();
923 void QuicConnection::MaybeQueueAck() {
924 // If the incoming packet was missing, send an ack immediately.
925 ack_queued_
= received_packet_manager_
.IsMissing(
926 last_header_
.packet_sequence_number
);
928 if (!ack_queued_
&& ShouldLastPacketInstigateAck()) {
929 if (ack_alarm_
->IsSet()) {
932 // Send an ack much more quickly for crypto handshake packets.
933 QuicTime::Delta delayed_ack_time
= sent_packet_manager_
.DelayedAckTime();
934 ack_alarm_
->Set(clock_
->ApproximateNow().Add(delayed_ack_time
));
935 DVLOG(1) << "Ack timer set; next packet or timer will trigger ACK.";
940 ack_alarm_
->Cancel();
944 void QuicConnection::ClearLastFrames() {
945 last_stream_frames_
.clear();
946 last_ack_frames_
.clear();
947 last_stop_waiting_frames_
.clear();
948 last_rst_frames_
.clear();
949 last_goaway_frames_
.clear();
950 last_window_update_frames_
.clear();
951 last_blocked_frames_
.clear();
952 last_ping_frames_
.clear();
953 last_close_frames_
.clear();
956 void QuicConnection::MaybeCloseIfTooManyOutstandingPackets() {
957 // This occurs if we don't discard old packets we've sent fast enough.
958 // It's possible largest observed is less than least unacked.
959 if (sent_packet_manager_
.largest_observed() >
960 (sent_packet_manager_
.GetLeastUnacked() + kMaxTrackedPackets
)) {
961 SendConnectionCloseWithDetails(
962 QUIC_TOO_MANY_OUTSTANDING_SENT_PACKETS
,
963 StringPrintf("More than %" PRIu64
" outstanding.", kMaxTrackedPackets
));
965 // This occurs if there are received packet gaps and the peer does not raise
966 // the least unacked fast enough.
967 if (received_packet_manager_
.NumTrackedPackets() > kMaxTrackedPackets
) {
968 SendConnectionCloseWithDetails(
969 QUIC_TOO_MANY_OUTSTANDING_RECEIVED_PACKETS
,
970 StringPrintf("More than %" PRIu64
" outstanding.", kMaxTrackedPackets
));
974 void QuicConnection::PopulateAckFrame(QuicAckFrame
* ack
) {
975 received_packet_manager_
.UpdateReceivedPacketInfo(ack
,
976 clock_
->ApproximateNow());
979 void QuicConnection::PopulateStopWaitingFrame(
980 QuicStopWaitingFrame
* stop_waiting
) {
981 stop_waiting
->least_unacked
= GetLeastUnacked();
982 stop_waiting
->entropy_hash
= sent_entropy_manager_
.GetCumulativeEntropy(
983 stop_waiting
->least_unacked
- 1);
986 bool QuicConnection::ShouldLastPacketInstigateAck() const {
987 if (!last_stream_frames_
.empty() ||
988 !last_goaway_frames_
.empty() ||
989 !last_rst_frames_
.empty() ||
990 !last_window_update_frames_
.empty() ||
991 !last_blocked_frames_
.empty() ||
992 !last_ping_frames_
.empty()) {
996 if (!last_ack_frames_
.empty() && last_ack_frames_
.back().is_truncated
) {
999 // Always send an ack every 20 packets in order to allow the peer to discard
1000 // information from the SentPacketManager and provide an RTT measurement.
1001 if (num_packets_received_since_last_ack_sent_
>=
1002 kMaxPacketsReceivedBeforeAckSend
) {
1008 void QuicConnection::UpdateStopWaitingCount() {
1009 if (last_ack_frames_
.empty()) {
1013 // If the peer is still waiting for a packet that we are no longer planning to
1014 // send, send an ack to raise the high water mark.
1015 if (!last_ack_frames_
.back().missing_packets
.empty() &&
1016 GetLeastUnacked() > *last_ack_frames_
.back().missing_packets
.begin()) {
1017 ++stop_waiting_count_
;
1019 stop_waiting_count_
= 0;
1023 QuicPacketSequenceNumber
QuicConnection::GetLeastUnacked() const {
1024 return sent_packet_manager_
.GetLeastUnacked();
1027 void QuicConnection::MaybeSendInResponseToPacket() {
1031 ScopedPacketBundler
bundler(this, ack_queued_
? SEND_ACK
: NO_ACK
);
1033 // Now that we have received an ack, we might be able to send packets which
1034 // are queued locally, or drain streams which are blocked.
1035 if (CanWrite(HAS_RETRANSMITTABLE_DATA
)) {
1040 void QuicConnection::SendVersionNegotiationPacket() {
1041 // TODO(alyssar): implement zero server state negotiation.
1042 pending_version_negotiation_packet_
= true;
1043 if (writer_
->IsWriteBlocked()) {
1044 visitor_
->OnWriteBlocked();
1047 DVLOG(1) << ENDPOINT
<< "Sending version negotiation packet: {"
1048 << QuicVersionVectorToString(framer_
.supported_versions()) << "}";
1049 scoped_ptr
<QuicEncryptedPacket
> version_packet(
1050 packet_generator_
.SerializeVersionNegotiationPacket(
1051 framer_
.supported_versions()));
1052 WriteResult result
= writer_
->WritePacket(
1053 version_packet
->data(), version_packet
->length(),
1054 self_address().address(), peer_address());
1056 if (result
.status
== WRITE_STATUS_ERROR
) {
1057 // We can't send an error as the socket is presumably borked.
1058 CloseConnection(QUIC_PACKET_WRITE_ERROR
, false);
1061 if (result
.status
== WRITE_STATUS_BLOCKED
) {
1062 visitor_
->OnWriteBlocked();
1063 if (writer_
->IsWriteBlockedDataBuffered()) {
1064 pending_version_negotiation_packet_
= false;
1069 pending_version_negotiation_packet_
= false;
1072 QuicConsumedData
QuicConnection::SendStreamData(
1074 const IOVector
& data
,
1075 QuicStreamOffset offset
,
1077 FecProtection fec_protection
,
1078 QuicAckNotifier::DelegateInterface
* delegate
) {
1079 if (!fin
&& data
.Empty()) {
1080 LOG(DFATAL
) << "Attempt to send empty stream frame";
1081 return QuicConsumedData(0, false);
1084 // Opportunistically bundle an ack with every outgoing packet.
1085 // Particularly, we want to bundle with handshake packets since we don't know
1086 // which decrypter will be used on an ack packet following a handshake
1087 // packet (a handshake packet from client to server could result in a REJ or a
1088 // SHLO from the server, leading to two different decrypters at the server.)
1090 // TODO(jri): Note that ConsumeData may cause a response packet to be sent.
1091 // We may end up sending stale ack information if there are undecryptable
1092 // packets hanging around and/or there are revivable packets which may get
1093 // handled after this packet is sent. Change ScopedPacketBundler to do the
1094 // right thing: check ack_queued_, and then check undecryptable packets and
1095 // also if there is possibility of revival. Only bundle an ack if there's no
1096 // processing left that may cause received_info_ to change.
1097 ScopedPacketBundler
ack_bundler(this, BUNDLE_PENDING_ACK
);
1098 return packet_generator_
.ConsumeData(id
, data
, offset
, fin
, fec_protection
,
1102 void QuicConnection::SendRstStream(QuicStreamId id
,
1103 QuicRstStreamErrorCode error
,
1104 QuicStreamOffset bytes_written
) {
1105 // Opportunistically bundle an ack with this outgoing packet.
1106 ScopedPacketBundler
ack_bundler(this, BUNDLE_PENDING_ACK
);
1107 packet_generator_
.AddControlFrame(QuicFrame(new QuicRstStreamFrame(
1108 id
, AdjustErrorForVersion(error
, version()), bytes_written
)));
1111 void QuicConnection::SendWindowUpdate(QuicStreamId id
,
1112 QuicStreamOffset byte_offset
) {
1113 // Opportunistically bundle an ack with this outgoing packet.
1114 ScopedPacketBundler
ack_bundler(this, BUNDLE_PENDING_ACK
);
1115 packet_generator_
.AddControlFrame(
1116 QuicFrame(new QuicWindowUpdateFrame(id
, byte_offset
)));
1119 void QuicConnection::SendBlocked(QuicStreamId id
) {
1120 // Opportunistically bundle an ack with this outgoing packet.
1121 ScopedPacketBundler
ack_bundler(this, BUNDLE_PENDING_ACK
);
1122 packet_generator_
.AddControlFrame(QuicFrame(new QuicBlockedFrame(id
)));
1125 const QuicConnectionStats
& QuicConnection::GetStats() {
1126 const RttStats
* rtt_stats
= sent_packet_manager_
.GetRttStats();
1128 // Update rtt and estimated bandwidth.
1129 QuicTime::Delta min_rtt
= rtt_stats
->min_rtt();
1130 if (min_rtt
.IsZero()) {
1131 // If min RTT has not been set, use initial RTT instead.
1132 min_rtt
= QuicTime::Delta::FromMicroseconds(rtt_stats
->initial_rtt_us());
1134 stats_
.min_rtt_us
= min_rtt
.ToMicroseconds();
1136 QuicTime::Delta srtt
= rtt_stats
->smoothed_rtt();
1137 if (srtt
.IsZero()) {
1138 // If SRTT has not been set, use initial RTT instead.
1139 srtt
= QuicTime::Delta::FromMicroseconds(rtt_stats
->initial_rtt_us());
1141 stats_
.srtt_us
= srtt
.ToMicroseconds();
1143 stats_
.estimated_bandwidth
= sent_packet_manager_
.BandwidthEstimate();
1144 stats_
.max_packet_size
= packet_generator_
.max_packet_length();
1148 void QuicConnection::ProcessUdpPacket(const IPEndPoint
& self_address
,
1149 const IPEndPoint
& peer_address
,
1150 const QuicEncryptedPacket
& packet
) {
1154 if (debug_visitor_
!= nullptr) {
1155 debug_visitor_
->OnPacketReceived(self_address
, peer_address
, packet
);
1157 last_size_
= packet
.length();
1159 CheckForAddressMigration(self_address
, peer_address
);
1161 stats_
.bytes_received
+= packet
.length();
1162 ++stats_
.packets_received
;
1164 if (!framer_
.ProcessPacket(packet
)) {
1165 // If we are unable to decrypt this packet, it might be
1166 // because the CHLO or SHLO packet was lost.
1167 if (framer_
.error() == QUIC_DECRYPTION_FAILURE
) {
1168 if (encryption_level_
!= ENCRYPTION_FORWARD_SECURE
&&
1169 undecryptable_packets_
.size() < max_undecryptable_packets_
) {
1170 QueueUndecryptablePacket(packet
);
1171 } else if (debug_visitor_
!= nullptr) {
1172 debug_visitor_
->OnUndecryptablePacket();
1175 DVLOG(1) << ENDPOINT
<< "Unable to process packet. Last packet processed: "
1176 << last_header_
.packet_sequence_number
;
1180 ++stats_
.packets_processed
;
1181 MaybeProcessUndecryptablePackets();
1182 MaybeProcessRevivedPacket();
1183 MaybeSendInResponseToPacket();
1187 void QuicConnection::CheckForAddressMigration(
1188 const IPEndPoint
& self_address
, const IPEndPoint
& peer_address
) {
1189 peer_ip_changed_
= false;
1190 peer_port_changed_
= false;
1191 self_ip_changed_
= false;
1192 self_port_changed_
= false;
1194 if (peer_address_
.address().empty()) {
1195 peer_address_
= peer_address
;
1197 if (self_address_
.address().empty()) {
1198 self_address_
= self_address
;
1201 if (!peer_address
.address().empty() && !peer_address_
.address().empty()) {
1202 peer_ip_changed_
= (peer_address
.address() != peer_address_
.address());
1203 peer_port_changed_
= (peer_address
.port() != peer_address_
.port());
1205 // Store in case we want to migrate connection in ProcessValidatedPacket.
1206 migrating_peer_port_
= peer_address
.port();
1209 if (!self_address
.address().empty() && !self_address_
.address().empty()) {
1210 self_ip_changed_
= (self_address
.address() != self_address_
.address());
1211 self_port_changed_
= (self_address
.port() != self_address_
.port());
1215 void QuicConnection::OnCanWrite() {
1216 DCHECK(!writer_
->IsWriteBlocked());
1218 WriteQueuedPackets();
1219 WritePendingRetransmissions();
1221 // Sending queued packets may have caused the socket to become write blocked,
1222 // or the congestion manager to prohibit sending. If we've sent everything
1223 // we had queued and we're still not blocked, let the visitor know it can
1225 if (!CanWrite(HAS_RETRANSMITTABLE_DATA
)) {
1229 { // Limit the scope of the bundler. ACK inclusion happens elsewhere.
1230 ScopedPacketBundler
bundler(this, NO_ACK
);
1231 visitor_
->OnCanWrite();
1234 // After the visitor writes, it may have caused the socket to become write
1235 // blocked or the congestion manager to prohibit sending, so check again.
1236 if (visitor_
->WillingAndAbleToWrite() &&
1237 !resume_writes_alarm_
->IsSet() &&
1238 CanWrite(HAS_RETRANSMITTABLE_DATA
)) {
1239 // We're not write blocked, but some stream didn't write out all of its
1240 // bytes. Register for 'immediate' resumption so we'll keep writing after
1241 // other connections and events have had a chance to use the thread.
1242 resume_writes_alarm_
->Set(clock_
->ApproximateNow());
1246 void QuicConnection::WriteIfNotBlocked() {
1247 if (!writer_
->IsWriteBlocked()) {
1252 bool QuicConnection::ProcessValidatedPacket() {
1253 if (peer_ip_changed_
|| self_ip_changed_
|| self_port_changed_
) {
1254 SendConnectionCloseWithDetails(
1255 QUIC_ERROR_MIGRATING_ADDRESS
,
1256 "Neither IP address migration, nor self port migration are supported.");
1260 // Peer port migration is supported, do it now if port has changed.
1261 if (peer_port_changed_
) {
1262 DVLOG(1) << ENDPOINT
<< "Peer's port changed from "
1263 << peer_address_
.port() << " to " << migrating_peer_port_
1264 << ", migrating connection.";
1265 peer_address_
= IPEndPoint(peer_address_
.address(), migrating_peer_port_
);
1268 time_of_last_received_packet_
= clock_
->Now();
1269 DVLOG(1) << ENDPOINT
<< "time of last received packet: "
1270 << time_of_last_received_packet_
.ToDebuggingValue();
1272 if (is_server_
&& encryption_level_
== ENCRYPTION_NONE
&&
1273 last_size_
> packet_generator_
.max_packet_length()) {
1274 set_max_packet_length(last_size_
);
1279 void QuicConnection::WriteQueuedPackets() {
1280 DCHECK(!writer_
->IsWriteBlocked());
1282 if (pending_version_negotiation_packet_
) {
1283 SendVersionNegotiationPacket();
1286 QueuedPacketList::iterator packet_iterator
= queued_packets_
.begin();
1287 while (packet_iterator
!= queued_packets_
.end() &&
1288 WritePacket(&(*packet_iterator
))) {
1289 packet_iterator
= queued_packets_
.erase(packet_iterator
);
1293 void QuicConnection::WritePendingRetransmissions() {
1294 // Keep writing as long as there's a pending retransmission which can be
1296 while (sent_packet_manager_
.HasPendingRetransmissions()) {
1297 const QuicSentPacketManager::PendingRetransmission pending
=
1298 sent_packet_manager_
.NextPendingRetransmission();
1299 if (!CanWrite(HAS_RETRANSMITTABLE_DATA
)) {
1303 // Re-packetize the frames with a new sequence number for retransmission.
1304 // Retransmitted data packets do not use FEC, even when it's enabled.
1305 // Retransmitted packets use the same sequence number length as the
1307 // Flush the packet generator before making a new packet.
1308 // TODO(ianswett): Implement ReserializeAllFrames as a separate path that
1309 // does not require the creator to be flushed.
1310 packet_generator_
.FlushAllQueuedFrames();
1311 SerializedPacket serialized_packet
= packet_generator_
.ReserializeAllFrames(
1312 pending
.retransmittable_frames
, pending
.sequence_number_length
);
1313 if (serialized_packet
.packet
== nullptr) {
1314 // We failed to serialize the packet, so close the connection.
1315 // CloseConnection does not send close packet, so no infinite loop here.
1316 CloseConnection(QUIC_ENCRYPTION_FAILURE
, false);
1320 DVLOG(1) << ENDPOINT
<< "Retransmitting " << pending
.sequence_number
1321 << " as " << serialized_packet
.sequence_number
;
1323 QueuedPacket(serialized_packet
,
1324 pending
.retransmittable_frames
.encryption_level(),
1325 pending
.transmission_type
,
1326 pending
.sequence_number
));
1330 void QuicConnection::RetransmitUnackedPackets(
1331 TransmissionType retransmission_type
) {
1332 sent_packet_manager_
.RetransmitUnackedPackets(retransmission_type
);
1334 WriteIfNotBlocked();
1337 void QuicConnection::NeuterUnencryptedPackets() {
1338 sent_packet_manager_
.NeuterUnencryptedPackets();
1339 // This may have changed the retransmission timer, so re-arm it.
1340 QuicTime retransmission_time
= sent_packet_manager_
.GetRetransmissionTime();
1341 retransmission_alarm_
->Update(retransmission_time
,
1342 QuicTime::Delta::FromMilliseconds(1));
1345 bool QuicConnection::ShouldGeneratePacket(
1346 TransmissionType transmission_type
,
1347 HasRetransmittableData retransmittable
,
1348 IsHandshake handshake
) {
1349 // We should serialize handshake packets immediately to ensure that they
1350 // end up sent at the right encryption level.
1351 if (handshake
== IS_HANDSHAKE
) {
1355 return CanWrite(retransmittable
);
1358 bool QuicConnection::CanWrite(HasRetransmittableData retransmittable
) {
1363 if (writer_
->IsWriteBlocked()) {
1364 visitor_
->OnWriteBlocked();
1368 QuicTime now
= clock_
->Now();
1369 QuicTime::Delta delay
= sent_packet_manager_
.TimeUntilSend(
1370 now
, retransmittable
);
1371 if (delay
.IsInfinite()) {
1372 send_alarm_
->Cancel();
1376 // If the scheduler requires a delay, then we can not send this packet now.
1377 if (!delay
.IsZero()) {
1378 send_alarm_
->Update(now
.Add(delay
), QuicTime::Delta::FromMilliseconds(1));
1379 DVLOG(1) << ENDPOINT
<< "Delaying sending " << delay
.ToMilliseconds()
1383 send_alarm_
->Cancel();
1387 bool QuicConnection::WritePacket(QueuedPacket
* packet
) {
1388 if (!WritePacketInner(packet
)) {
1391 delete packet
->serialized_packet
.retransmittable_frames
;
1392 delete packet
->serialized_packet
.packet
;
1393 packet
->serialized_packet
.retransmittable_frames
= nullptr;
1394 packet
->serialized_packet
.packet
= nullptr;
1398 bool QuicConnection::WritePacketInner(QueuedPacket
* packet
) {
1399 if (ShouldDiscardPacket(*packet
)) {
1400 ++stats_
.packets_discarded
;
1403 // Connection close packets are encrypted and saved, so don't exit early.
1404 const bool is_connection_close
= IsConnectionClose(*packet
);
1405 if (writer_
->IsWriteBlocked() && !is_connection_close
) {
1409 QuicPacketSequenceNumber sequence_number
=
1410 packet
->serialized_packet
.sequence_number
;
1411 DCHECK_LE(sequence_number_of_last_sent_packet_
, sequence_number
);
1412 sequence_number_of_last_sent_packet_
= sequence_number
;
1414 QuicEncryptedPacket
* encrypted
= packet
->serialized_packet
.packet
;
1415 // Connection close packets are eventually owned by TimeWaitListManager.
1416 // Others are deleted at the end of this call.
1417 if (is_connection_close
) {
1418 DCHECK(connection_close_packet_
.get() == nullptr);
1419 connection_close_packet_
.reset(encrypted
);
1420 packet
->serialized_packet
.packet
= nullptr;
1421 // This assures we won't try to write *forced* packets when blocked.
1422 // Return true to stop processing.
1423 if (writer_
->IsWriteBlocked()) {
1424 visitor_
->OnWriteBlocked();
1429 if (!FLAGS_quic_allow_oversized_packets_for_test
) {
1430 DCHECK_LE(encrypted
->length(), kMaxPacketSize
);
1432 DCHECK_LE(encrypted
->length(), packet_generator_
.max_packet_length());
1433 DVLOG(1) << ENDPOINT
<< "Sending packet " << sequence_number
<< " : "
1434 << (packet
->serialized_packet
.is_fec_packet
1436 : (IsRetransmittable(*packet
) == HAS_RETRANSMITTABLE_DATA
1438 : " ack only ")) << ", encryption level: "
1439 << QuicUtils::EncryptionLevelToString(packet
->encryption_level
)
1440 << ", encrypted length:" << encrypted
->length();
1441 DVLOG(2) << ENDPOINT
<< "packet(" << sequence_number
<< "): " << std::endl
1442 << QuicUtils::StringToHexASCIIDump(encrypted
->AsStringPiece());
1444 // Measure the RTT from before the write begins to avoid underestimating the
1445 // min_rtt_, especially in cases where the thread blocks or gets swapped out
1446 // during the WritePacket below.
1447 QuicTime packet_send_time
= clock_
->Now();
1448 WriteResult result
= writer_
->WritePacket(encrypted
->data(),
1449 encrypted
->length(),
1450 self_address().address(),
1452 if (result
.error_code
== ERR_IO_PENDING
) {
1453 DCHECK_EQ(WRITE_STATUS_BLOCKED
, result
.status
);
1456 if (result
.status
== WRITE_STATUS_BLOCKED
) {
1457 visitor_
->OnWriteBlocked();
1458 // If the socket buffers the the data, then the packet should not
1459 // be queued and sent again, which would result in an unnecessary
1460 // duplicate packet being sent. The helper must call OnCanWrite
1461 // when the write completes, and OnWriteError if an error occurs.
1462 if (!writer_
->IsWriteBlockedDataBuffered()) {
1466 if (result
.status
!= WRITE_STATUS_ERROR
&& debug_visitor_
!= nullptr) {
1467 // Pass the write result to the visitor.
1468 debug_visitor_
->OnPacketSent(packet
->serialized_packet
,
1469 packet
->original_sequence_number
,
1470 packet
->encryption_level
,
1471 packet
->transmission_type
,
1475 if (packet
->transmission_type
== NOT_RETRANSMISSION
) {
1476 time_of_last_sent_new_packet_
= packet_send_time
;
1479 MaybeSetFecAlarm(sequence_number
);
1480 DVLOG(1) << ENDPOINT
<< "time we began writing last sent packet: "
1481 << packet_send_time
.ToDebuggingValue();
1483 // TODO(ianswett): Change the sequence number length and other packet creator
1484 // options by a more explicit API than setting a struct value directly,
1485 // perhaps via the NetworkChangeVisitor.
1486 packet_generator_
.UpdateSequenceNumberLength(
1487 sent_packet_manager_
.least_packet_awaited_by_peer(),
1488 sent_packet_manager_
.EstimateMaxPacketsInFlight(max_packet_length()));
1490 bool reset_retransmission_alarm
= sent_packet_manager_
.OnPacketSent(
1491 &packet
->serialized_packet
,
1492 packet
->original_sequence_number
,
1494 encrypted
->length(),
1495 packet
->transmission_type
,
1496 IsRetransmittable(*packet
));
1498 if (reset_retransmission_alarm
|| !retransmission_alarm_
->IsSet()) {
1499 retransmission_alarm_
->Update(sent_packet_manager_
.GetRetransmissionTime(),
1500 QuicTime::Delta::FromMilliseconds(1));
1503 stats_
.bytes_sent
+= result
.bytes_written
;
1504 ++stats_
.packets_sent
;
1505 if (packet
->transmission_type
!= NOT_RETRANSMISSION
) {
1506 stats_
.bytes_retransmitted
+= result
.bytes_written
;
1507 ++stats_
.packets_retransmitted
;
1510 if (result
.status
== WRITE_STATUS_ERROR
) {
1511 OnWriteError(result
.error_code
);
1512 DLOG(ERROR
) << ENDPOINT
<< "failed writing " << encrypted
->length()
1514 << " from host " << self_address().ToStringWithoutPort()
1515 << " to address " << peer_address().ToString();
1522 bool QuicConnection::ShouldDiscardPacket(const QueuedPacket
& packet
) {
1524 DVLOG(1) << ENDPOINT
1525 << "Not sending packet as connection is disconnected.";
1529 QuicPacketSequenceNumber sequence_number
=
1530 packet
.serialized_packet
.sequence_number
;
1531 if (encryption_level_
== ENCRYPTION_FORWARD_SECURE
&&
1532 packet
.encryption_level
== ENCRYPTION_NONE
) {
1533 // Drop packets that are NULL encrypted since the peer won't accept them
1535 DVLOG(1) << ENDPOINT
<< "Dropping NULL encrypted packet: "
1536 << sequence_number
<< " since the connection is forward secure.";
1540 // If a retransmission has been acked before sending, don't send it.
1541 // This occurs if a packet gets serialized, queued, then discarded.
1542 if (packet
.transmission_type
!= NOT_RETRANSMISSION
&&
1543 (!sent_packet_manager_
.IsUnacked(packet
.original_sequence_number
) ||
1544 !sent_packet_manager_
.HasRetransmittableFrames(
1545 packet
.original_sequence_number
))) {
1546 DVLOG(1) << ENDPOINT
<< "Dropping unacked packet: " << sequence_number
1547 << " A previous transmission was acked while write blocked.";
1554 void QuicConnection::OnWriteError(int error_code
) {
1555 DVLOG(1) << ENDPOINT
<< "Write failed with error: " << error_code
1556 << " (" << ErrorToString(error_code
) << ")";
1557 // We can't send an error as the socket is presumably borked.
1558 CloseConnection(QUIC_PACKET_WRITE_ERROR
, false);
1561 void QuicConnection::OnSerializedPacket(
1562 const SerializedPacket
& serialized_packet
) {
1563 if (serialized_packet
.packet
== nullptr) {
1564 // We failed to serialize the packet, so close the connection.
1565 // CloseConnection does not send close packet, so no infinite loop here.
1566 CloseConnection(QUIC_ENCRYPTION_FAILURE
, false);
1569 if (serialized_packet
.retransmittable_frames
) {
1570 sent_packet_manager_
.OnSerializedPacket(serialized_packet
);
1572 if (serialized_packet
.is_fec_packet
&& fec_alarm_
->IsSet()) {
1573 // If an FEC packet is serialized with the FEC alarm set, cancel the alarm.
1574 fec_alarm_
->Cancel();
1576 SendOrQueuePacket(QueuedPacket(serialized_packet
, encryption_level_
));
1579 void QuicConnection::OnCongestionWindowChange() {
1580 packet_generator_
.OnCongestionWindowChange(
1581 sent_packet_manager_
.EstimateMaxPacketsInFlight(max_packet_length()));
1582 visitor_
->OnCongestionWindowChange(clock_
->ApproximateNow());
1585 void QuicConnection::OnRttChange() {
1586 // Uses the connection's smoothed RTT. If zero, uses initial_rtt.
1587 QuicTime::Delta rtt
= sent_packet_manager_
.GetRttStats()->smoothed_rtt();
1589 rtt
= QuicTime::Delta::FromMicroseconds(
1590 sent_packet_manager_
.GetRttStats()->initial_rtt_us());
1592 packet_generator_
.OnRttChange(rtt
);
1595 void QuicConnection::OnHandshakeComplete() {
1596 sent_packet_manager_
.SetHandshakeConfirmed();
1597 // The client should immediately ack the SHLO to confirm the handshake is
1598 // complete with the server.
1599 if (!is_server_
&& !ack_queued_
) {
1600 ack_alarm_
->Cancel();
1601 ack_alarm_
->Set(clock_
->ApproximateNow());
1605 void QuicConnection::SendOrQueuePacket(QueuedPacket packet
) {
1606 // The caller of this function is responsible for checking CanWrite().
1607 if (packet
.serialized_packet
.packet
== nullptr) {
1609 << "packet.serialized_packet.packet == nullptr in to SendOrQueuePacket";
1613 sent_entropy_manager_
.RecordPacketEntropyHash(
1614 packet
.serialized_packet
.sequence_number
,
1615 packet
.serialized_packet
.entropy_hash
);
1616 if (!WritePacket(&packet
)) {
1617 queued_packets_
.push_back(packet
);
1620 // If a forward-secure encrypter is available but is not being used and the
1621 // next sequence number is the first packet which requires
1622 // forward security, start using the forward-secure encrypter.
1623 if (encryption_level_
!= ENCRYPTION_FORWARD_SECURE
&&
1624 has_forward_secure_encrypter_
&&
1625 packet
.serialized_packet
.sequence_number
>=
1626 first_required_forward_secure_packet_
- 1) {
1627 SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE
);
1631 void QuicConnection::SendPing() {
1632 if (retransmission_alarm_
->IsSet()) {
1635 packet_generator_
.AddControlFrame(QuicFrame(new QuicPingFrame
));
1638 void QuicConnection::SendAck() {
1639 ack_alarm_
->Cancel();
1640 stop_waiting_count_
= 0;
1641 num_packets_received_since_last_ack_sent_
= 0;
1643 packet_generator_
.SetShouldSendAck(true);
1646 void QuicConnection::OnRetransmissionTimeout() {
1647 if (!sent_packet_manager_
.HasUnackedPackets()) {
1651 sent_packet_manager_
.OnRetransmissionTimeout();
1652 WriteIfNotBlocked();
1654 // A write failure can result in the connection being closed, don't attempt to
1655 // write further packets, or to set alarms.
1660 // In the TLP case, the SentPacketManager gives the connection the opportunity
1661 // to send new data before retransmitting.
1662 if (sent_packet_manager_
.MaybeRetransmitTailLossProbe()) {
1663 // Send the pending retransmission now that it's been queued.
1664 WriteIfNotBlocked();
1667 // Ensure the retransmission alarm is always set if there are unacked packets
1668 // and nothing waiting to be sent.
1669 if (!HasQueuedData() && !retransmission_alarm_
->IsSet()) {
1670 QuicTime rto_timeout
= sent_packet_manager_
.GetRetransmissionTime();
1671 if (rto_timeout
.IsInitialized()) {
1672 retransmission_alarm_
->Set(rto_timeout
);
1677 void QuicConnection::SetEncrypter(EncryptionLevel level
,
1678 QuicEncrypter
* encrypter
) {
1679 framer_
.SetEncrypter(level
, encrypter
);
1680 if (level
== ENCRYPTION_FORWARD_SECURE
) {
1681 has_forward_secure_encrypter_
= true;
1682 first_required_forward_secure_packet_
=
1683 sequence_number_of_last_sent_packet_
+
1684 // 3 times the current congestion window (in slow start) should cover
1685 // about two full round trips worth of packets, which should be
1687 3 * sent_packet_manager_
.EstimateMaxPacketsInFlight(
1688 max_packet_length());
1692 const QuicEncrypter
* QuicConnection::encrypter(EncryptionLevel level
) const {
1693 return framer_
.encrypter(level
);
1696 void QuicConnection::SetDefaultEncryptionLevel(EncryptionLevel level
) {
1697 encryption_level_
= level
;
1698 packet_generator_
.set_encryption_level(level
);
1701 void QuicConnection::SetDecrypter(QuicDecrypter
* decrypter
,
1702 EncryptionLevel level
) {
1703 framer_
.SetDecrypter(decrypter
, level
);
1706 void QuicConnection::SetAlternativeDecrypter(QuicDecrypter
* decrypter
,
1707 EncryptionLevel level
,
1708 bool latch_once_used
) {
1709 framer_
.SetAlternativeDecrypter(decrypter
, level
, latch_once_used
);
1712 const QuicDecrypter
* QuicConnection::decrypter() const {
1713 return framer_
.decrypter();
1716 const QuicDecrypter
* QuicConnection::alternative_decrypter() const {
1717 return framer_
.alternative_decrypter();
1720 void QuicConnection::QueueUndecryptablePacket(
1721 const QuicEncryptedPacket
& packet
) {
1722 DVLOG(1) << ENDPOINT
<< "Queueing undecryptable packet.";
1723 undecryptable_packets_
.push_back(packet
.Clone());
1726 void QuicConnection::MaybeProcessUndecryptablePackets() {
1727 if (undecryptable_packets_
.empty() || encryption_level_
== ENCRYPTION_NONE
) {
1731 while (connected_
&& !undecryptable_packets_
.empty()) {
1732 DVLOG(1) << ENDPOINT
<< "Attempting to process undecryptable packet";
1733 QuicEncryptedPacket
* packet
= undecryptable_packets_
.front();
1734 if (!framer_
.ProcessPacket(*packet
) &&
1735 framer_
.error() == QUIC_DECRYPTION_FAILURE
) {
1736 DVLOG(1) << ENDPOINT
<< "Unable to process undecryptable packet...";
1739 DVLOG(1) << ENDPOINT
<< "Processed undecryptable packet!";
1740 ++stats_
.packets_processed
;
1742 undecryptable_packets_
.pop_front();
1745 // Once forward secure encryption is in use, there will be no
1746 // new keys installed and hence any undecryptable packets will
1747 // never be able to be decrypted.
1748 if (encryption_level_
== ENCRYPTION_FORWARD_SECURE
) {
1749 if (debug_visitor_
!= nullptr) {
1750 // TODO(rtenneti): perhaps more efficient to pass the number of
1751 // undecryptable packets as the argument to OnUndecryptablePacket so that
1752 // we just need to call OnUndecryptablePacket once?
1753 for (size_t i
= 0; i
< undecryptable_packets_
.size(); ++i
) {
1754 debug_visitor_
->OnUndecryptablePacket();
1757 STLDeleteElements(&undecryptable_packets_
);
1761 void QuicConnection::MaybeProcessRevivedPacket() {
1762 QuicFecGroup
* group
= GetFecGroup();
1763 if (!connected_
|| group
== nullptr || !group
->CanRevive()) {
1766 QuicPacketHeader revived_header
;
1767 char revived_payload
[kMaxPacketSize
];
1768 size_t len
= group
->Revive(&revived_header
, revived_payload
, kMaxPacketSize
);
1769 revived_header
.public_header
.connection_id
= connection_id_
;
1770 revived_header
.public_header
.connection_id_length
=
1771 last_header_
.public_header
.connection_id_length
;
1772 revived_header
.public_header
.version_flag
= false;
1773 revived_header
.public_header
.reset_flag
= false;
1774 revived_header
.public_header
.sequence_number_length
=
1775 last_header_
.public_header
.sequence_number_length
;
1776 revived_header
.fec_flag
= false;
1777 revived_header
.is_in_fec_group
= NOT_IN_FEC_GROUP
;
1778 revived_header
.fec_group
= 0;
1779 group_map_
.erase(last_header_
.fec_group
);
1780 last_decrypted_packet_level_
= group
->effective_encryption_level();
1781 DCHECK_LT(last_decrypted_packet_level_
, NUM_ENCRYPTION_LEVELS
);
1784 last_packet_revived_
= true;
1785 if (debug_visitor_
!= nullptr) {
1786 debug_visitor_
->OnRevivedPacket(revived_header
,
1787 StringPiece(revived_payload
, len
));
1790 ++stats_
.packets_revived
;
1791 framer_
.ProcessRevivedPacket(&revived_header
,
1792 StringPiece(revived_payload
, len
));
1795 QuicFecGroup
* QuicConnection::GetFecGroup() {
1796 QuicFecGroupNumber fec_group_num
= last_header_
.fec_group
;
1797 if (fec_group_num
== 0) {
1800 if (!ContainsKey(group_map_
, fec_group_num
)) {
1801 if (group_map_
.size() >= kMaxFecGroups
) { // Too many groups
1802 if (fec_group_num
< group_map_
.begin()->first
) {
1803 // The group being requested is a group we've seen before and deleted.
1804 // Don't recreate it.
1807 // Clear the lowest group number.
1808 delete group_map_
.begin()->second
;
1809 group_map_
.erase(group_map_
.begin());
1811 group_map_
[fec_group_num
] = new QuicFecGroup();
1813 return group_map_
[fec_group_num
];
1816 void QuicConnection::SendConnectionClose(QuicErrorCode error
) {
1817 SendConnectionCloseWithDetails(error
, string());
1820 void QuicConnection::SendConnectionCloseWithDetails(QuicErrorCode error
,
1821 const string
& details
) {
1822 // If we're write blocked, WritePacket() will not send, but will capture the
1823 // serialized packet.
1824 SendConnectionClosePacket(error
, details
);
1826 // It's possible that while sending the connection close packet, we get a
1827 // socket error and disconnect right then and there. Avoid a double
1828 // disconnect in that case.
1829 CloseConnection(error
, false);
1833 void QuicConnection::SendConnectionClosePacket(QuicErrorCode error
,
1834 const string
& details
) {
1835 DVLOG(1) << ENDPOINT
<< "Force closing " << connection_id()
1836 << " with error " << QuicUtils::ErrorToString(error
)
1837 << " (" << error
<< ") " << details
;
1838 // Don't send explicit connection close packets for timeouts.
1839 // This is particularly important on mobile, where connections are short.
1840 if (silent_close_enabled_
&&
1841 error
== QuicErrorCode::QUIC_CONNECTION_TIMED_OUT
) {
1844 ScopedPacketBundler
ack_bundler(this, SEND_ACK
);
1845 QuicConnectionCloseFrame
* frame
= new QuicConnectionCloseFrame();
1846 frame
->error_code
= error
;
1847 frame
->error_details
= details
;
1848 packet_generator_
.AddControlFrame(QuicFrame(frame
));
1849 packet_generator_
.FlushAllQueuedFrames();
1852 void QuicConnection::CloseConnection(QuicErrorCode error
, bool from_peer
) {
1854 DLOG(DFATAL
) << "Error: attempt to close an already closed connection"
1855 << base::debug::StackTrace().ToString();
1859 if (debug_visitor_
!= nullptr) {
1860 debug_visitor_
->OnConnectionClosed(error
, from_peer
);
1862 visitor_
->OnConnectionClosed(error
, from_peer
);
1863 // Cancel the alarms so they don't trigger any action now that the
1864 // connection is closed.
1865 ack_alarm_
->Cancel();
1866 ping_alarm_
->Cancel();
1867 fec_alarm_
->Cancel();
1868 resume_writes_alarm_
->Cancel();
1869 retransmission_alarm_
->Cancel();
1870 send_alarm_
->Cancel();
1871 timeout_alarm_
->Cancel();
1874 void QuicConnection::SendGoAway(QuicErrorCode error
,
1875 QuicStreamId last_good_stream_id
,
1876 const string
& reason
) {
1877 DVLOG(1) << ENDPOINT
<< "Going away with error "
1878 << QuicUtils::ErrorToString(error
)
1879 << " (" << error
<< ")";
1881 // Opportunistically bundle an ack with this outgoing packet.
1882 ScopedPacketBundler
ack_bundler(this, BUNDLE_PENDING_ACK
);
1883 packet_generator_
.AddControlFrame(
1884 QuicFrame(new QuicGoAwayFrame(error
, last_good_stream_id
, reason
)));
1887 void QuicConnection::CloseFecGroupsBefore(
1888 QuicPacketSequenceNumber sequence_number
) {
1889 FecGroupMap::iterator it
= group_map_
.begin();
1890 while (it
!= group_map_
.end()) {
1891 // If this is the current group or the group doesn't protect this packet
1892 // we can ignore it.
1893 if (last_header_
.fec_group
== it
->first
||
1894 !it
->second
->ProtectsPacketsBefore(sequence_number
)) {
1898 QuicFecGroup
* fec_group
= it
->second
;
1899 DCHECK(!fec_group
->CanRevive());
1900 FecGroupMap::iterator next
= it
;
1902 group_map_
.erase(it
);
1908 QuicByteCount
QuicConnection::max_packet_length() const {
1909 return packet_generator_
.max_packet_length();
1912 void QuicConnection::set_max_packet_length(QuicByteCount length
) {
1913 return packet_generator_
.set_max_packet_length(length
);
1916 bool QuicConnection::HasQueuedData() const {
1917 return pending_version_negotiation_packet_
||
1918 !queued_packets_
.empty() || packet_generator_
.HasQueuedFrames();
1921 bool QuicConnection::CanWriteStreamData() {
1922 // Don't write stream data if there are negotiation or queued data packets
1923 // to send. Otherwise, continue and bundle as many frames as possible.
1924 if (pending_version_negotiation_packet_
|| !queued_packets_
.empty()) {
1928 IsHandshake pending_handshake
= visitor_
->HasPendingHandshake() ?
1929 IS_HANDSHAKE
: NOT_HANDSHAKE
;
1930 // Sending queued packets may have caused the socket to become write blocked,
1931 // or the congestion manager to prohibit sending. If we've sent everything
1932 // we had queued and we're still not blocked, let the visitor know it can
1934 return ShouldGeneratePacket(NOT_RETRANSMISSION
, HAS_RETRANSMITTABLE_DATA
,
1938 void QuicConnection::SetNetworkTimeouts(QuicTime::Delta overall_timeout
,
1939 QuicTime::Delta idle_timeout
) {
1940 LOG_IF(DFATAL
, idle_timeout
> overall_timeout
)
1941 << "idle_timeout:" << idle_timeout
.ToMilliseconds()
1942 << " overall_timeout:" << overall_timeout
.ToMilliseconds();
1943 // Adjust the idle timeout on client and server to prevent clients from
1944 // sending requests to servers which have already closed the connection.
1946 idle_timeout
= idle_timeout
.Add(QuicTime::Delta::FromSeconds(3));
1947 } else if (idle_timeout
> QuicTime::Delta::FromSeconds(1)) {
1948 idle_timeout
= idle_timeout
.Subtract(QuicTime::Delta::FromSeconds(1));
1950 overall_connection_timeout_
= overall_timeout
;
1951 idle_network_timeout_
= idle_timeout
;
1956 void QuicConnection::CheckForTimeout() {
1957 QuicTime now
= clock_
->ApproximateNow();
1958 QuicTime time_of_last_packet
= max(time_of_last_received_packet_
,
1959 time_of_last_sent_new_packet_
);
1961 // |delta| can be < 0 as |now| is approximate time but |time_of_last_packet|
1962 // is accurate time. However, this should not change the behavior of
1963 // timeout handling.
1964 QuicTime::Delta idle_duration
= now
.Subtract(time_of_last_packet
);
1965 DVLOG(1) << ENDPOINT
<< "last packet "
1966 << time_of_last_packet
.ToDebuggingValue()
1967 << " now:" << now
.ToDebuggingValue()
1968 << " idle_duration:" << idle_duration
.ToMicroseconds()
1969 << " idle_network_timeout: "
1970 << idle_network_timeout_
.ToMicroseconds();
1971 if (idle_duration
>= idle_network_timeout_
) {
1972 DVLOG(1) << ENDPOINT
<< "Connection timedout due to no network activity.";
1973 SendConnectionClose(QUIC_CONNECTION_TIMED_OUT
);
1977 if (!overall_connection_timeout_
.IsInfinite()) {
1978 QuicTime::Delta connected_duration
=
1979 now
.Subtract(stats_
.connection_creation_time
);
1980 DVLOG(1) << ENDPOINT
<< "connection time: "
1981 << connected_duration
.ToMicroseconds() << " overall timeout: "
1982 << overall_connection_timeout_
.ToMicroseconds();
1983 if (connected_duration
>= overall_connection_timeout_
) {
1984 DVLOG(1) << ENDPOINT
<<
1985 "Connection timedout due to overall connection timeout.";
1986 SendConnectionClose(QUIC_CONNECTION_OVERALL_TIMED_OUT
);
1994 void QuicConnection::SetTimeoutAlarm() {
1995 QuicTime time_of_last_packet
= max(time_of_last_received_packet_
,
1996 time_of_last_sent_new_packet_
);
1998 QuicTime deadline
= time_of_last_packet
.Add(idle_network_timeout_
);
1999 if (!overall_connection_timeout_
.IsInfinite()) {
2000 deadline
= min(deadline
,
2001 stats_
.connection_creation_time
.Add(
2002 overall_connection_timeout_
));
2005 timeout_alarm_
->Cancel();
2006 timeout_alarm_
->Set(deadline
);
2009 void QuicConnection::SetPingAlarm() {
2011 // Only clients send pings.
2014 if (!visitor_
->HasOpenDataStreams()) {
2015 ping_alarm_
->Cancel();
2016 // Don't send a ping unless there are open streams.
2019 QuicTime::Delta ping_timeout
= QuicTime::Delta::FromSeconds(kPingTimeoutSecs
);
2020 ping_alarm_
->Update(clock_
->ApproximateNow().Add(ping_timeout
),
2021 QuicTime::Delta::FromSeconds(1));
2024 QuicConnection::ScopedPacketBundler::ScopedPacketBundler(
2025 QuicConnection
* connection
,
2026 AckBundling send_ack
)
2027 : connection_(connection
),
2028 already_in_batch_mode_(connection
!= nullptr &&
2029 connection
->packet_generator_
.InBatchMode()) {
2030 if (connection_
== nullptr) {
2033 // Move generator into batch mode. If caller wants us to include an ack,
2034 // check the delayed-ack timer to see if there's ack info to be sent.
2035 if (!already_in_batch_mode_
) {
2036 DVLOG(1) << "Entering Batch Mode.";
2037 connection_
->packet_generator_
.StartBatchOperations();
2039 // Bundle an ack if the alarm is set or with every second packet if we need to
2040 // raise the peer's least unacked.
2042 connection_
->ack_alarm_
->IsSet() || connection_
->stop_waiting_count_
> 1;
2043 if (send_ack
== SEND_ACK
|| (send_ack
== BUNDLE_PENDING_ACK
&& ack_pending
)) {
2044 DVLOG(1) << "Bundling ack with outgoing packet.";
2045 connection_
->SendAck();
2049 QuicConnection::ScopedPacketBundler::~ScopedPacketBundler() {
2050 if (connection_
== nullptr) {
2053 // If we changed the generator's batch state, restore original batch state.
2054 if (!already_in_batch_mode_
) {
2055 DVLOG(1) << "Leaving Batch Mode.";
2056 connection_
->packet_generator_
.FinishBatchOperations();
2058 DCHECK_EQ(already_in_batch_mode_
,
2059 connection_
->packet_generator_
.InBatchMode());
2062 HasRetransmittableData
QuicConnection::IsRetransmittable(
2063 const QueuedPacket
& packet
) {
2064 // Retransmitted packets retransmittable frames are owned by the unacked
2065 // packet map, but are not present in the serialized packet.
2066 if (packet
.transmission_type
!= NOT_RETRANSMISSION
||
2067 packet
.serialized_packet
.retransmittable_frames
!= nullptr) {
2068 return HAS_RETRANSMITTABLE_DATA
;
2070 return NO_RETRANSMITTABLE_DATA
;
2074 bool QuicConnection::IsConnectionClose(const QueuedPacket
& packet
) {
2075 const RetransmittableFrames
* retransmittable_frames
=
2076 packet
.serialized_packet
.retransmittable_frames
;
2077 if (retransmittable_frames
== nullptr) {
2080 for (const QuicFrame
& frame
: retransmittable_frames
->frames()) {
2081 if (frame
.type
== CONNECTION_CLOSE_FRAME
) {