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/profiler/scoped_tracker.h"
21 #include "base/stl_util.h"
22 #include "base/strings/stringprintf.h"
23 #include "net/base/net_errors.h"
24 #include "net/quic/crypto/quic_decrypter.h"
25 #include "net/quic/crypto/quic_encrypter.h"
26 #include "net/quic/iovector.h"
27 #include "net/quic/proto/cached_network_parameters.pb.h"
28 #include "net/quic/quic_bandwidth.h"
29 #include "net/quic/quic_config.h"
30 #include "net/quic/quic_fec_group.h"
31 #include "net/quic/quic_flags.h"
32 #include "net/quic/quic_packet_generator.h"
33 #include "net/quic/quic_utils.h"
35 using base::StringPiece
;
36 using base::StringPrintf
;
43 using std::numeric_limits
;
55 // The largest gap in packets we'll accept without closing the connection.
56 // This will likely have to be tuned.
57 const QuicPacketSequenceNumber kMaxPacketGap
= 5000;
59 // Limit the number of FEC groups to two. If we get enough out of order packets
60 // that this becomes limiting, we can revisit.
61 const size_t kMaxFecGroups
= 2;
63 // Maximum number of acks received before sending an ack in response.
64 const QuicPacketCount kMaxPacketsReceivedBeforeAckSend
= 20;
66 // Maximum number of tracked packets.
67 const QuicPacketCount kMaxTrackedPackets
= 5 * kMaxTcpCongestionWindow
;
69 bool Near(QuicPacketSequenceNumber a
, QuicPacketSequenceNumber b
) {
70 QuicPacketSequenceNumber delta
= (a
> b
) ? a
- b
: b
- a
;
71 return delta
<= kMaxPacketGap
;
74 // An alarm that is scheduled to send an ack if a timeout occurs.
75 class AckAlarm
: public QuicAlarm::Delegate
{
77 explicit AckAlarm(QuicConnection
* connection
)
78 : connection_(connection
) {
81 QuicTime
OnAlarm() override
{
82 connection_
->SendAck();
83 return QuicTime::Zero();
87 QuicConnection
* connection_
;
89 DISALLOW_COPY_AND_ASSIGN(AckAlarm
);
92 // This alarm will be scheduled any time a data-bearing packet is sent out.
93 // When the alarm goes off, the connection checks to see if the oldest packets
94 // have been acked, and retransmit them if they have not.
95 class RetransmissionAlarm
: public QuicAlarm::Delegate
{
97 explicit RetransmissionAlarm(QuicConnection
* connection
)
98 : connection_(connection
) {
101 QuicTime
OnAlarm() override
{
102 connection_
->OnRetransmissionTimeout();
103 return QuicTime::Zero();
107 QuicConnection
* connection_
;
109 DISALLOW_COPY_AND_ASSIGN(RetransmissionAlarm
);
112 // An alarm that is scheduled when the SentPacketManager requires a delay
113 // before sending packets and fires when the packet may be sent.
114 class SendAlarm
: public QuicAlarm::Delegate
{
116 explicit SendAlarm(QuicConnection
* connection
)
117 : connection_(connection
) {
120 QuicTime
OnAlarm() override
{
121 connection_
->WriteIfNotBlocked();
122 // Never reschedule the alarm, since CanWrite does that.
123 return QuicTime::Zero();
127 QuicConnection
* connection_
;
129 DISALLOW_COPY_AND_ASSIGN(SendAlarm
);
132 class TimeoutAlarm
: public QuicAlarm::Delegate
{
134 explicit TimeoutAlarm(QuicConnection
* connection
)
135 : connection_(connection
) {
138 QuicTime
OnAlarm() override
{
139 connection_
->CheckForTimeout();
140 // Never reschedule the alarm, since CheckForTimeout does that.
141 return QuicTime::Zero();
145 QuicConnection
* connection_
;
147 DISALLOW_COPY_AND_ASSIGN(TimeoutAlarm
);
150 class PingAlarm
: public QuicAlarm::Delegate
{
152 explicit PingAlarm(QuicConnection
* connection
)
153 : connection_(connection
) {
156 QuicTime
OnAlarm() override
{
157 connection_
->SendPing();
158 return QuicTime::Zero();
162 QuicConnection
* connection_
;
164 DISALLOW_COPY_AND_ASSIGN(PingAlarm
);
167 // This alarm may be scheduled when an FEC protected packet is sent out.
168 class FecAlarm
: public QuicAlarm::Delegate
{
170 explicit FecAlarm(QuicPacketGenerator
* packet_generator
)
171 : packet_generator_(packet_generator
) {}
173 QuicTime
OnAlarm() override
{
174 packet_generator_
->OnFecTimeout();
175 return QuicTime::Zero();
179 QuicPacketGenerator
* packet_generator_
;
181 DISALLOW_COPY_AND_ASSIGN(FecAlarm
);
186 QuicConnection::QueuedPacket::QueuedPacket(SerializedPacket packet
,
187 EncryptionLevel level
)
188 : serialized_packet(packet
),
189 encryption_level(level
),
190 transmission_type(NOT_RETRANSMISSION
),
191 original_sequence_number(0) {
194 QuicConnection::QueuedPacket::QueuedPacket(
195 SerializedPacket packet
,
196 EncryptionLevel level
,
197 TransmissionType transmission_type
,
198 QuicPacketSequenceNumber original_sequence_number
)
199 : serialized_packet(packet
),
200 encryption_level(level
),
201 transmission_type(transmission_type
),
202 original_sequence_number(original_sequence_number
) {
206 (perspective_ == Perspective::IS_SERVER ? "Server: " : "Client: ")
208 QuicConnection::QuicConnection(QuicConnectionId connection_id
,
210 QuicConnectionHelperInterface
* helper
,
211 const PacketWriterFactory
& writer_factory
,
213 Perspective perspective
,
215 const QuicVersionVector
& supported_versions
)
216 : framer_(supported_versions
,
217 helper
->GetClock()->ApproximateNow(),
220 writer_(writer_factory
.Create(this)),
221 owns_writer_(owns_writer
),
222 encryption_level_(ENCRYPTION_NONE
),
223 has_forward_secure_encrypter_(false),
224 first_required_forward_secure_packet_(0),
225 clock_(helper
->GetClock()),
226 random_generator_(helper
->GetRandomGenerator()),
227 connection_id_(connection_id
),
228 peer_address_(address
),
229 migrating_peer_port_(0),
230 last_packet_decrypted_(false),
231 last_packet_revived_(false),
233 last_decrypted_packet_level_(ENCRYPTION_NONE
),
234 largest_seen_packet_with_ack_(0),
235 largest_seen_packet_with_stop_waiting_(0),
236 max_undecryptable_packets_(0),
237 pending_version_negotiation_packet_(false),
238 silent_close_enabled_(false),
239 received_packet_manager_(&stats_
),
241 num_packets_received_since_last_ack_sent_(0),
242 stop_waiting_count_(0),
243 ack_alarm_(helper
->CreateAlarm(new AckAlarm(this))),
244 retransmission_alarm_(helper
->CreateAlarm(new RetransmissionAlarm(this))),
245 send_alarm_(helper
->CreateAlarm(new SendAlarm(this))),
246 resume_writes_alarm_(helper
->CreateAlarm(new SendAlarm(this))),
247 timeout_alarm_(helper
->CreateAlarm(new TimeoutAlarm(this))),
248 ping_alarm_(helper
->CreateAlarm(new PingAlarm(this))),
250 debug_visitor_(nullptr),
251 packet_generator_(connection_id_
, &framer_
, random_generator_
, this),
252 fec_alarm_(helper
->CreateAlarm(new FecAlarm(&packet_generator_
))),
253 idle_network_timeout_(QuicTime::Delta::Infinite()),
254 overall_connection_timeout_(QuicTime::Delta::Infinite()),
255 time_of_last_received_packet_(clock_
->ApproximateNow()),
256 time_of_last_sent_new_packet_(clock_
->ApproximateNow()),
257 sequence_number_of_last_sent_packet_(0),
258 sent_packet_manager_(
262 FLAGS_quic_use_bbr_congestion_control
? kBBR
: kCubic
,
263 FLAGS_quic_use_time_loss_detection
? kTime
: kNack
,
265 version_negotiation_state_(START_NEGOTIATION
),
266 perspective_(perspective
),
268 peer_ip_changed_(false),
269 peer_port_changed_(false),
270 self_ip_changed_(false),
271 self_port_changed_(false),
272 can_truncate_connection_ids_(true),
273 is_secure_(is_secure
) {
274 DVLOG(1) << ENDPOINT
<< "Created connection with connection_id: "
276 framer_
.set_visitor(this);
277 framer_
.set_received_entropy_calculator(&received_packet_manager_
);
278 stats_
.connection_creation_time
= clock_
->ApproximateNow();
279 sent_packet_manager_
.set_network_change_visitor(this);
280 if (perspective_
== Perspective::IS_SERVER
) {
281 set_max_packet_length(kDefaultServerMaxPacketSize
);
285 QuicConnection::~QuicConnection() {
289 STLDeleteElements(&undecryptable_packets_
);
290 STLDeleteValues(&group_map_
);
291 for (QueuedPacketList::iterator it
= queued_packets_
.begin();
292 it
!= queued_packets_
.end(); ++it
) {
293 delete it
->serialized_packet
.retransmittable_frames
;
294 delete it
->serialized_packet
.packet
;
298 void QuicConnection::SetFromConfig(const QuicConfig
& config
) {
299 if (config
.negotiated()) {
300 SetNetworkTimeouts(QuicTime::Delta::Infinite(),
301 config
.IdleConnectionStateLifetime());
302 if (config
.SilentClose()) {
303 silent_close_enabled_
= true;
306 SetNetworkTimeouts(config
.max_time_before_crypto_handshake(),
307 config
.max_idle_time_before_crypto_handshake());
310 sent_packet_manager_
.SetFromConfig(config
);
311 if (config
.HasReceivedBytesForConnectionId() &&
312 can_truncate_connection_ids_
) {
313 packet_generator_
.SetConnectionIdLength(
314 config
.ReceivedBytesForConnectionId());
316 max_undecryptable_packets_
= config
.max_undecryptable_packets();
319 void QuicConnection::OnSendConnectionState(
320 const CachedNetworkParameters
& cached_network_params
) {
321 if (debug_visitor_
!= nullptr) {
322 debug_visitor_
->OnSendConnectionState(cached_network_params
);
326 bool QuicConnection::ResumeConnectionState(
327 const CachedNetworkParameters
& cached_network_params
,
328 bool max_bandwidth_resumption
) {
329 if (debug_visitor_
!= nullptr) {
330 debug_visitor_
->OnResumeConnectionState(cached_network_params
);
332 return sent_packet_manager_
.ResumeConnectionState(cached_network_params
,
333 max_bandwidth_resumption
);
336 void QuicConnection::SetNumOpenStreams(size_t num_streams
) {
337 sent_packet_manager_
.SetNumOpenStreams(num_streams
);
340 bool QuicConnection::SelectMutualVersion(
341 const QuicVersionVector
& available_versions
) {
342 // Try to find the highest mutual version by iterating over supported
343 // versions, starting with the highest, and breaking out of the loop once we
344 // find a matching version in the provided available_versions vector.
345 const QuicVersionVector
& supported_versions
= framer_
.supported_versions();
346 for (size_t i
= 0; i
< supported_versions
.size(); ++i
) {
347 const QuicVersion
& version
= supported_versions
[i
];
348 if (std::find(available_versions
.begin(), available_versions
.end(),
349 version
) != available_versions
.end()) {
350 framer_
.set_version(version
);
358 void QuicConnection::OnError(QuicFramer
* framer
) {
359 // Packets that we can not or have not decrypted are dropped.
360 // TODO(rch): add stats to measure this.
361 if (!connected_
|| last_packet_decrypted_
== false) {
364 SendConnectionCloseWithDetails(framer
->error(), framer
->detailed_error());
367 void QuicConnection::MaybeSetFecAlarm(
368 QuicPacketSequenceNumber sequence_number
) {
369 if (fec_alarm_
->IsSet()) {
372 QuicTime::Delta timeout
= packet_generator_
.GetFecTimeout(sequence_number
);
373 if (!timeout
.IsInfinite()) {
374 fec_alarm_
->Set(clock_
->ApproximateNow().Add(timeout
));
378 void QuicConnection::OnPacket() {
379 DCHECK(last_stream_frames_
.empty() &&
380 last_ack_frames_
.empty() &&
381 last_stop_waiting_frames_
.empty() &&
382 last_rst_frames_
.empty() &&
383 last_goaway_frames_
.empty() &&
384 last_window_update_frames_
.empty() &&
385 last_blocked_frames_
.empty() &&
386 last_ping_frames_
.empty() &&
387 last_close_frames_
.empty());
388 last_packet_decrypted_
= false;
389 last_packet_revived_
= false;
392 void QuicConnection::OnPublicResetPacket(const QuicPublicResetPacket
& packet
) {
393 // Check that any public reset packet with a different connection ID that was
394 // routed to this QuicConnection has been redirected before control reaches
395 // here. (Check for a bug regression.)
396 DCHECK_EQ(connection_id_
, packet
.public_header
.connection_id
);
397 if (debug_visitor_
!= nullptr) {
398 debug_visitor_
->OnPublicResetPacket(packet
);
400 CloseConnection(QUIC_PUBLIC_RESET
, true);
402 DVLOG(1) << ENDPOINT
<< "Connection " << connection_id()
403 << " closed via QUIC_PUBLIC_RESET from peer.";
406 bool QuicConnection::OnProtocolVersionMismatch(QuicVersion received_version
) {
407 DVLOG(1) << ENDPOINT
<< "Received packet with mismatched version "
409 // TODO(satyamshekhar): Implement no server state in this mode.
410 if (perspective_
== Perspective::IS_CLIENT
) {
411 LOG(DFATAL
) << ENDPOINT
<< "Framer called OnProtocolVersionMismatch. "
412 << "Closing connection.";
413 CloseConnection(QUIC_INTERNAL_ERROR
, false);
416 DCHECK_NE(version(), received_version
);
418 if (debug_visitor_
!= nullptr) {
419 debug_visitor_
->OnProtocolVersionMismatch(received_version
);
422 switch (version_negotiation_state_
) {
423 case START_NEGOTIATION
:
424 if (!framer_
.IsSupportedVersion(received_version
)) {
425 SendVersionNegotiationPacket();
426 version_negotiation_state_
= NEGOTIATION_IN_PROGRESS
;
431 case NEGOTIATION_IN_PROGRESS
:
432 if (!framer_
.IsSupportedVersion(received_version
)) {
433 SendVersionNegotiationPacket();
438 case NEGOTIATED_VERSION
:
439 // Might be old packets that were sent by the client before the version
440 // was negotiated. Drop these.
447 version_negotiation_state_
= NEGOTIATED_VERSION
;
448 visitor_
->OnSuccessfulVersionNegotiation(received_version
);
449 if (debug_visitor_
!= nullptr) {
450 debug_visitor_
->OnSuccessfulVersionNegotiation(received_version
);
452 DVLOG(1) << ENDPOINT
<< "version negotiated " << received_version
;
454 // Store the new version.
455 framer_
.set_version(received_version
);
457 // TODO(satyamshekhar): Store the sequence number of this packet and close the
458 // connection if we ever received a packet with incorrect version and whose
459 // sequence number is greater.
463 // Handles version negotiation for client connection.
464 void QuicConnection::OnVersionNegotiationPacket(
465 const QuicVersionNegotiationPacket
& packet
) {
466 // Check that any public reset packet with a different connection ID that was
467 // routed to this QuicConnection has been redirected before control reaches
468 // here. (Check for a bug regression.)
469 DCHECK_EQ(connection_id_
, packet
.connection_id
);
470 if (perspective_
== Perspective::IS_SERVER
) {
471 LOG(DFATAL
) << ENDPOINT
<< "Framer parsed VersionNegotiationPacket."
472 << " Closing connection.";
473 CloseConnection(QUIC_INTERNAL_ERROR
, false);
476 if (debug_visitor_
!= nullptr) {
477 debug_visitor_
->OnVersionNegotiationPacket(packet
);
480 if (version_negotiation_state_
!= START_NEGOTIATION
) {
481 // Possibly a duplicate version negotiation packet.
485 if (std::find(packet
.versions
.begin(),
486 packet
.versions
.end(), version()) !=
487 packet
.versions
.end()) {
488 DLOG(WARNING
) << ENDPOINT
<< "The server already supports our version. "
489 << "It should have accepted our connection.";
490 // Just drop the connection.
491 CloseConnection(QUIC_INVALID_VERSION_NEGOTIATION_PACKET
, false);
495 if (!SelectMutualVersion(packet
.versions
)) {
496 SendConnectionCloseWithDetails(QUIC_INVALID_VERSION
,
497 "no common version found");
502 << "Negotiated version: " << QuicVersionToString(version());
503 server_supported_versions_
= packet
.versions
;
504 version_negotiation_state_
= NEGOTIATION_IN_PROGRESS
;
505 RetransmitUnackedPackets(ALL_UNACKED_RETRANSMISSION
);
508 void QuicConnection::OnRevivedPacket() {
511 bool QuicConnection::OnUnauthenticatedPublicHeader(
512 const QuicPacketPublicHeader
& header
) {
513 if (header
.connection_id
== connection_id_
) {
517 ++stats_
.packets_dropped
;
518 DVLOG(1) << ENDPOINT
<< "Ignoring packet from unexpected ConnectionId: "
519 << header
.connection_id
<< " instead of " << connection_id_
;
520 if (debug_visitor_
!= nullptr) {
521 debug_visitor_
->OnIncorrectConnectionId(header
.connection_id
);
523 // If this is a server, the dispatcher routes each packet to the
524 // QuicConnection responsible for the packet's connection ID. So if control
525 // arrives here and this is a server, the dispatcher must be malfunctioning.
526 DCHECK_NE(Perspective::IS_SERVER
, perspective_
);
530 bool QuicConnection::OnUnauthenticatedHeader(const QuicPacketHeader
& header
) {
531 // Check that any public reset packet with a different connection ID that was
532 // routed to this QuicConnection has been redirected before control reaches
534 DCHECK_EQ(connection_id_
, header
.public_header
.connection_id
);
538 void QuicConnection::OnDecryptedPacket(EncryptionLevel level
) {
539 last_decrypted_packet_level_
= level
;
540 last_packet_decrypted_
= true;
541 // If this packet was foward-secure encrypted and the forward-secure encrypter
542 // is not being used, start using it.
543 if (encryption_level_
!= ENCRYPTION_FORWARD_SECURE
&&
544 has_forward_secure_encrypter_
&& level
== ENCRYPTION_FORWARD_SECURE
) {
545 SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE
);
549 bool QuicConnection::OnPacketHeader(const QuicPacketHeader
& header
) {
550 if (debug_visitor_
!= nullptr) {
551 debug_visitor_
->OnPacketHeader(header
);
554 if (!ProcessValidatedPacket()) {
558 // Will be decremented below if we fall through to return true.
559 ++stats_
.packets_dropped
;
561 if (!Near(header
.packet_sequence_number
,
562 last_header_
.packet_sequence_number
)) {
563 DVLOG(1) << ENDPOINT
<< "Packet " << header
.packet_sequence_number
564 << " out of bounds. Discarding";
565 SendConnectionCloseWithDetails(QUIC_INVALID_PACKET_HEADER
,
566 "Packet sequence number out of bounds");
570 // If this packet has already been seen, or the sender has told us that it
571 // will not be retransmitted, then stop processing the packet.
572 if (!received_packet_manager_
.IsAwaitingPacket(
573 header
.packet_sequence_number
)) {
574 DVLOG(1) << ENDPOINT
<< "Packet " << header
.packet_sequence_number
575 << " no longer being waited for. Discarding.";
576 if (debug_visitor_
!= nullptr) {
577 debug_visitor_
->OnDuplicatePacket(header
.packet_sequence_number
);
582 if (version_negotiation_state_
!= NEGOTIATED_VERSION
) {
583 if (perspective_
== Perspective::IS_SERVER
) {
584 if (!header
.public_header
.version_flag
) {
585 DLOG(WARNING
) << ENDPOINT
<< "Packet " << header
.packet_sequence_number
586 << " without version flag before version negotiated.";
587 // Packets should have the version flag till version negotiation is
589 CloseConnection(QUIC_INVALID_VERSION
, false);
592 DCHECK_EQ(1u, header
.public_header
.versions
.size());
593 DCHECK_EQ(header
.public_header
.versions
[0], version());
594 version_negotiation_state_
= NEGOTIATED_VERSION
;
595 visitor_
->OnSuccessfulVersionNegotiation(version());
596 if (debug_visitor_
!= nullptr) {
597 debug_visitor_
->OnSuccessfulVersionNegotiation(version());
601 DCHECK(!header
.public_header
.version_flag
);
602 // If the client gets a packet without the version flag from the server
603 // it should stop sending version since the version negotiation is done.
604 packet_generator_
.StopSendingVersion();
605 version_negotiation_state_
= NEGOTIATED_VERSION
;
606 visitor_
->OnSuccessfulVersionNegotiation(version());
607 if (debug_visitor_
!= nullptr) {
608 debug_visitor_
->OnSuccessfulVersionNegotiation(version());
613 DCHECK_EQ(NEGOTIATED_VERSION
, version_negotiation_state_
);
615 --stats_
.packets_dropped
;
616 DVLOG(1) << ENDPOINT
<< "Received packet header: " << header
;
617 last_header_
= header
;
622 void QuicConnection::OnFecProtectedPayload(StringPiece payload
) {
623 DCHECK_EQ(IN_FEC_GROUP
, last_header_
.is_in_fec_group
);
624 DCHECK_NE(0u, last_header_
.fec_group
);
625 QuicFecGroup
* group
= GetFecGroup();
626 if (group
!= nullptr) {
627 group
->Update(last_decrypted_packet_level_
, last_header_
, payload
);
631 bool QuicConnection::OnStreamFrame(const QuicStreamFrame
& frame
) {
633 if (debug_visitor_
!= nullptr) {
634 debug_visitor_
->OnStreamFrame(frame
);
636 if (frame
.stream_id
!= kCryptoStreamId
&&
637 last_decrypted_packet_level_
== ENCRYPTION_NONE
) {
638 DLOG(WARNING
) << ENDPOINT
639 << "Received an unencrypted data frame: closing connection";
640 SendConnectionClose(QUIC_UNENCRYPTED_STREAM_DATA
);
643 last_stream_frames_
.push_back(frame
);
647 bool QuicConnection::OnAckFrame(const QuicAckFrame
& incoming_ack
) {
649 if (debug_visitor_
!= nullptr) {
650 debug_visitor_
->OnAckFrame(incoming_ack
);
652 DVLOG(1) << ENDPOINT
<< "OnAckFrame: " << incoming_ack
;
654 if (last_header_
.packet_sequence_number
<= largest_seen_packet_with_ack_
) {
655 DVLOG(1) << ENDPOINT
<< "Received an old ack frame: ignoring";
659 if (!ValidateAckFrame(incoming_ack
)) {
660 SendConnectionClose(QUIC_INVALID_ACK_DATA
);
664 last_ack_frames_
.push_back(incoming_ack
);
668 void QuicConnection::ProcessAckFrame(const QuicAckFrame
& incoming_ack
) {
669 largest_seen_packet_with_ack_
= last_header_
.packet_sequence_number
;
670 sent_packet_manager_
.OnIncomingAck(incoming_ack
,
671 time_of_last_received_packet_
);
672 sent_entropy_manager_
.ClearEntropyBefore(
673 sent_packet_manager_
.least_packet_awaited_by_peer() - 1);
674 if (sent_packet_manager_
.HasPendingRetransmissions()) {
678 // Always reset the retransmission alarm when an ack comes in, since we now
679 // have a better estimate of the current rtt than when it was set.
680 QuicTime retransmission_time
= sent_packet_manager_
.GetRetransmissionTime();
681 retransmission_alarm_
->Update(retransmission_time
,
682 QuicTime::Delta::FromMilliseconds(1));
685 void QuicConnection::ProcessStopWaitingFrame(
686 const QuicStopWaitingFrame
& stop_waiting
) {
687 largest_seen_packet_with_stop_waiting_
= last_header_
.packet_sequence_number
;
688 received_packet_manager_
.UpdatePacketInformationSentByPeer(stop_waiting
);
689 // Possibly close any FecGroups which are now irrelevant.
690 CloseFecGroupsBefore(stop_waiting
.least_unacked
+ 1);
693 bool QuicConnection::OnStopWaitingFrame(const QuicStopWaitingFrame
& frame
) {
696 if (last_header_
.packet_sequence_number
<=
697 largest_seen_packet_with_stop_waiting_
) {
698 DVLOG(1) << ENDPOINT
<< "Received an old stop waiting frame: ignoring";
702 if (!ValidateStopWaitingFrame(frame
)) {
703 SendConnectionClose(QUIC_INVALID_STOP_WAITING_DATA
);
707 if (debug_visitor_
!= nullptr) {
708 debug_visitor_
->OnStopWaitingFrame(frame
);
711 last_stop_waiting_frames_
.push_back(frame
);
715 bool QuicConnection::OnPingFrame(const QuicPingFrame
& frame
) {
717 if (debug_visitor_
!= nullptr) {
718 debug_visitor_
->OnPingFrame(frame
);
720 last_ping_frames_
.push_back(frame
);
724 bool QuicConnection::ValidateAckFrame(const QuicAckFrame
& incoming_ack
) {
725 if (incoming_ack
.largest_observed
> packet_generator_
.sequence_number()) {
726 DLOG(ERROR
) << ENDPOINT
<< "Peer's observed unsent packet:"
727 << incoming_ack
.largest_observed
<< " vs "
728 << packet_generator_
.sequence_number();
729 // We got an error for data we have not sent. Error out.
733 if (incoming_ack
.largest_observed
< sent_packet_manager_
.largest_observed()) {
734 DLOG(ERROR
) << ENDPOINT
<< "Peer's largest_observed packet decreased:"
735 << incoming_ack
.largest_observed
<< " vs "
736 << sent_packet_manager_
.largest_observed();
737 // A new ack has a diminished largest_observed value. Error out.
738 // If this was an old packet, we wouldn't even have checked.
742 if (!incoming_ack
.missing_packets
.empty() &&
743 *incoming_ack
.missing_packets
.rbegin() > incoming_ack
.largest_observed
) {
744 DLOG(ERROR
) << ENDPOINT
<< "Peer sent missing packet: "
745 << *incoming_ack
.missing_packets
.rbegin()
746 << " which is greater than largest observed: "
747 << incoming_ack
.largest_observed
;
751 if (!incoming_ack
.missing_packets
.empty() &&
752 *incoming_ack
.missing_packets
.begin() <
753 sent_packet_manager_
.least_packet_awaited_by_peer()) {
754 DLOG(ERROR
) << ENDPOINT
<< "Peer sent missing packet: "
755 << *incoming_ack
.missing_packets
.begin()
756 << " which is smaller than least_packet_awaited_by_peer_: "
757 << sent_packet_manager_
.least_packet_awaited_by_peer();
761 if (!sent_entropy_manager_
.IsValidEntropy(
762 incoming_ack
.largest_observed
,
763 incoming_ack
.missing_packets
,
764 incoming_ack
.entropy_hash
)) {
765 DLOG(ERROR
) << ENDPOINT
<< "Peer sent invalid entropy.";
769 for (QuicPacketSequenceNumber revived_packet
: incoming_ack
.revived_packets
) {
770 if (!ContainsKey(incoming_ack
.missing_packets
, revived_packet
)) {
771 DLOG(ERROR
) << ENDPOINT
772 << "Peer specified revived packet which was not missing.";
779 bool QuicConnection::ValidateStopWaitingFrame(
780 const QuicStopWaitingFrame
& stop_waiting
) {
781 if (stop_waiting
.least_unacked
<
782 received_packet_manager_
.peer_least_packet_awaiting_ack()) {
783 DLOG(ERROR
) << ENDPOINT
<< "Peer's sent low least_unacked: "
784 << stop_waiting
.least_unacked
<< " vs "
785 << received_packet_manager_
.peer_least_packet_awaiting_ack();
786 // We never process old ack frames, so this number should only increase.
790 if (stop_waiting
.least_unacked
>
791 last_header_
.packet_sequence_number
) {
792 DLOG(ERROR
) << ENDPOINT
<< "Peer sent least_unacked:"
793 << stop_waiting
.least_unacked
794 << " greater than the enclosing packet sequence number:"
795 << last_header_
.packet_sequence_number
;
802 void QuicConnection::OnFecData(const QuicFecData
& fec
) {
803 DCHECK_EQ(IN_FEC_GROUP
, last_header_
.is_in_fec_group
);
804 DCHECK_NE(0u, last_header_
.fec_group
);
805 QuicFecGroup
* group
= GetFecGroup();
806 if (group
!= nullptr) {
807 group
->UpdateFec(last_decrypted_packet_level_
,
808 last_header_
.packet_sequence_number
, fec
);
812 bool QuicConnection::OnRstStreamFrame(const QuicRstStreamFrame
& frame
) {
814 if (debug_visitor_
!= nullptr) {
815 debug_visitor_
->OnRstStreamFrame(frame
);
817 DVLOG(1) << ENDPOINT
<< "Stream reset with error "
818 << QuicUtils::StreamErrorToString(frame
.error_code
);
819 last_rst_frames_
.push_back(frame
);
823 bool QuicConnection::OnConnectionCloseFrame(
824 const QuicConnectionCloseFrame
& frame
) {
826 if (debug_visitor_
!= nullptr) {
827 debug_visitor_
->OnConnectionCloseFrame(frame
);
829 DVLOG(1) << ENDPOINT
<< "Connection " << connection_id()
830 << " closed with error "
831 << QuicUtils::ErrorToString(frame
.error_code
)
832 << " " << frame
.error_details
;
833 last_close_frames_
.push_back(frame
);
837 bool QuicConnection::OnGoAwayFrame(const QuicGoAwayFrame
& frame
) {
839 if (debug_visitor_
!= nullptr) {
840 debug_visitor_
->OnGoAwayFrame(frame
);
842 DVLOG(1) << ENDPOINT
<< "Go away received with error "
843 << QuicUtils::ErrorToString(frame
.error_code
)
844 << " and reason:" << frame
.reason_phrase
;
845 last_goaway_frames_
.push_back(frame
);
849 bool QuicConnection::OnWindowUpdateFrame(const QuicWindowUpdateFrame
& frame
) {
851 if (debug_visitor_
!= nullptr) {
852 debug_visitor_
->OnWindowUpdateFrame(frame
);
854 DVLOG(1) << ENDPOINT
<< "WindowUpdate received for stream: "
855 << frame
.stream_id
<< " with byte offset: " << frame
.byte_offset
;
856 last_window_update_frames_
.push_back(frame
);
860 bool QuicConnection::OnBlockedFrame(const QuicBlockedFrame
& frame
) {
862 if (debug_visitor_
!= nullptr) {
863 debug_visitor_
->OnBlockedFrame(frame
);
865 DVLOG(1) << ENDPOINT
<< "Blocked frame received for stream: "
867 last_blocked_frames_
.push_back(frame
);
871 void QuicConnection::OnPacketComplete() {
872 // Don't do anything if this packet closed the connection.
878 DVLOG(1) << ENDPOINT
<< (last_packet_revived_
? "Revived" : "Got")
879 << " packet " << last_header_
.packet_sequence_number
880 << " with " << last_stream_frames_
.size()<< " stream frames "
881 << last_ack_frames_
.size() << " acks, "
882 << last_stop_waiting_frames_
.size() << " stop_waiting, "
883 << last_rst_frames_
.size() << " rsts, "
884 << last_goaway_frames_
.size() << " goaways, "
885 << last_window_update_frames_
.size() << " window updates, "
886 << last_blocked_frames_
.size() << " blocked, "
887 << last_ping_frames_
.size() << " pings, "
888 << last_close_frames_
.size() << " closes, "
889 << "for " << last_header_
.public_header
.connection_id
;
891 ++num_packets_received_since_last_ack_sent_
;
893 // Call MaybeQueueAck() before recording the received packet, since we want
894 // to trigger an ack if the newly received packet was previously missing.
897 // Record received or revived packet to populate ack info correctly before
898 // processing stream frames, since the processing may result in a response
899 // packet with a bundled ack.
900 if (last_packet_revived_
) {
901 received_packet_manager_
.RecordPacketRevived(
902 last_header_
.packet_sequence_number
);
904 received_packet_manager_
.RecordPacketReceived(
905 last_size_
, last_header_
, time_of_last_received_packet_
);
908 if (!last_stream_frames_
.empty()) {
909 visitor_
->OnStreamFrames(last_stream_frames_
);
912 for (size_t i
= 0; i
< last_stream_frames_
.size(); ++i
) {
913 stats_
.stream_bytes_received
+=
914 last_stream_frames_
[i
].data
.TotalBufferSize();
917 // Process window updates, blocked, stream resets, acks, then congestion
919 if (!last_window_update_frames_
.empty()) {
920 visitor_
->OnWindowUpdateFrames(last_window_update_frames_
);
922 if (!last_blocked_frames_
.empty()) {
923 visitor_
->OnBlockedFrames(last_blocked_frames_
);
925 for (size_t i
= 0; i
< last_goaway_frames_
.size(); ++i
) {
926 visitor_
->OnGoAway(last_goaway_frames_
[i
]);
928 for (size_t i
= 0; i
< last_rst_frames_
.size(); ++i
) {
929 visitor_
->OnRstStream(last_rst_frames_
[i
]);
931 for (size_t i
= 0; i
< last_ack_frames_
.size(); ++i
) {
932 ProcessAckFrame(last_ack_frames_
[i
]);
934 for (size_t i
= 0; i
< last_stop_waiting_frames_
.size(); ++i
) {
935 ProcessStopWaitingFrame(last_stop_waiting_frames_
[i
]);
937 if (!last_close_frames_
.empty()) {
938 CloseConnection(last_close_frames_
[0].error_code
, true);
942 // If there are new missing packets to report, send an ack immediately.
943 if (received_packet_manager_
.HasNewMissingPackets()) {
945 ack_alarm_
->Cancel();
948 UpdateStopWaitingCount();
950 MaybeCloseIfTooManyOutstandingPackets();
953 void QuicConnection::MaybeQueueAck() {
954 // If the incoming packet was missing, send an ack immediately.
955 ack_queued_
= received_packet_manager_
.IsMissing(
956 last_header_
.packet_sequence_number
);
958 if (!ack_queued_
&& ShouldLastPacketInstigateAck()) {
959 if (ack_alarm_
->IsSet()) {
962 // Send an ack much more quickly for crypto handshake packets.
963 QuicTime::Delta delayed_ack_time
= sent_packet_manager_
.DelayedAckTime();
964 ack_alarm_
->Set(clock_
->ApproximateNow().Add(delayed_ack_time
));
965 DVLOG(1) << "Ack timer set; next packet or timer will trigger ACK.";
970 ack_alarm_
->Cancel();
974 void QuicConnection::ClearLastFrames() {
975 last_stream_frames_
.clear();
976 last_ack_frames_
.clear();
977 last_stop_waiting_frames_
.clear();
978 last_rst_frames_
.clear();
979 last_goaway_frames_
.clear();
980 last_window_update_frames_
.clear();
981 last_blocked_frames_
.clear();
982 last_ping_frames_
.clear();
983 last_close_frames_
.clear();
986 void QuicConnection::MaybeCloseIfTooManyOutstandingPackets() {
987 // This occurs if we don't discard old packets we've sent fast enough.
988 // It's possible largest observed is less than least unacked.
989 if (sent_packet_manager_
.largest_observed() >
990 (sent_packet_manager_
.GetLeastUnacked() + kMaxTrackedPackets
)) {
991 SendConnectionCloseWithDetails(
992 QUIC_TOO_MANY_OUTSTANDING_SENT_PACKETS
,
993 StringPrintf("More than %" PRIu64
" outstanding.", kMaxTrackedPackets
));
995 // This occurs if there are received packet gaps and the peer does not raise
996 // the least unacked fast enough.
997 if (received_packet_manager_
.NumTrackedPackets() > kMaxTrackedPackets
) {
998 SendConnectionCloseWithDetails(
999 QUIC_TOO_MANY_OUTSTANDING_RECEIVED_PACKETS
,
1000 StringPrintf("More than %" PRIu64
" outstanding.", kMaxTrackedPackets
));
1004 void QuicConnection::PopulateAckFrame(QuicAckFrame
* ack
) {
1005 received_packet_manager_
.UpdateReceivedPacketInfo(ack
,
1006 clock_
->ApproximateNow());
1009 void QuicConnection::PopulateStopWaitingFrame(
1010 QuicStopWaitingFrame
* stop_waiting
) {
1011 stop_waiting
->least_unacked
= GetLeastUnacked();
1012 stop_waiting
->entropy_hash
= sent_entropy_manager_
.GetCumulativeEntropy(
1013 stop_waiting
->least_unacked
- 1);
1016 bool QuicConnection::ShouldLastPacketInstigateAck() const {
1017 if (!last_stream_frames_
.empty() ||
1018 !last_goaway_frames_
.empty() ||
1019 !last_rst_frames_
.empty() ||
1020 !last_window_update_frames_
.empty() ||
1021 !last_blocked_frames_
.empty() ||
1022 !last_ping_frames_
.empty()) {
1026 if (!last_ack_frames_
.empty() && last_ack_frames_
.back().is_truncated
) {
1029 // Always send an ack every 20 packets in order to allow the peer to discard
1030 // information from the SentPacketManager and provide an RTT measurement.
1031 if (num_packets_received_since_last_ack_sent_
>=
1032 kMaxPacketsReceivedBeforeAckSend
) {
1038 void QuicConnection::UpdateStopWaitingCount() {
1039 if (last_ack_frames_
.empty()) {
1043 // If the peer is still waiting for a packet that we are no longer planning to
1044 // send, send an ack to raise the high water mark.
1045 if (!last_ack_frames_
.back().missing_packets
.empty() &&
1046 GetLeastUnacked() > *last_ack_frames_
.back().missing_packets
.begin()) {
1047 ++stop_waiting_count_
;
1049 stop_waiting_count_
= 0;
1053 QuicPacketSequenceNumber
QuicConnection::GetLeastUnacked() const {
1054 return sent_packet_manager_
.GetLeastUnacked();
1057 void QuicConnection::MaybeSendInResponseToPacket() {
1061 ScopedPacketBundler
bundler(this, ack_queued_
? SEND_ACK
: NO_ACK
);
1063 // Now that we have received an ack, we might be able to send packets which
1064 // are queued locally, or drain streams which are blocked.
1065 if (CanWrite(HAS_RETRANSMITTABLE_DATA
)) {
1070 void QuicConnection::SendVersionNegotiationPacket() {
1071 // TODO(alyssar): implement zero server state negotiation.
1072 pending_version_negotiation_packet_
= true;
1073 if (writer_
->IsWriteBlocked()) {
1074 visitor_
->OnWriteBlocked();
1077 DVLOG(1) << ENDPOINT
<< "Sending version negotiation packet: {"
1078 << QuicVersionVectorToString(framer_
.supported_versions()) << "}";
1079 scoped_ptr
<QuicEncryptedPacket
> version_packet(
1080 packet_generator_
.SerializeVersionNegotiationPacket(
1081 framer_
.supported_versions()));
1082 WriteResult result
= writer_
->WritePacket(
1083 version_packet
->data(), version_packet
->length(),
1084 self_address().address(), peer_address());
1086 if (result
.status
== WRITE_STATUS_ERROR
) {
1087 // We can't send an error as the socket is presumably borked.
1088 CloseConnection(QUIC_PACKET_WRITE_ERROR
, false);
1091 if (result
.status
== WRITE_STATUS_BLOCKED
) {
1092 visitor_
->OnWriteBlocked();
1093 if (writer_
->IsWriteBlockedDataBuffered()) {
1094 pending_version_negotiation_packet_
= false;
1099 pending_version_negotiation_packet_
= false;
1102 QuicConsumedData
QuicConnection::SendStreamData(
1104 const IOVector
& data
,
1105 QuicStreamOffset offset
,
1107 FecProtection fec_protection
,
1108 QuicAckNotifier::DelegateInterface
* delegate
) {
1109 if (!fin
&& data
.Empty()) {
1110 LOG(DFATAL
) << "Attempt to send empty stream frame";
1111 return QuicConsumedData(0, false);
1114 // Opportunistically bundle an ack with every outgoing packet.
1115 // Particularly, we want to bundle with handshake packets since we don't know
1116 // which decrypter will be used on an ack packet following a handshake
1117 // packet (a handshake packet from client to server could result in a REJ or a
1118 // SHLO from the server, leading to two different decrypters at the server.)
1120 // TODO(jri): Note that ConsumeData may cause a response packet to be sent.
1121 // We may end up sending stale ack information if there are undecryptable
1122 // packets hanging around and/or there are revivable packets which may get
1123 // handled after this packet is sent. Change ScopedPacketBundler to do the
1124 // right thing: check ack_queued_, and then check undecryptable packets and
1125 // also if there is possibility of revival. Only bundle an ack if there's no
1126 // processing left that may cause received_info_ to change.
1127 ScopedPacketBundler
ack_bundler(this, BUNDLE_PENDING_ACK
);
1128 return packet_generator_
.ConsumeData(id
, data
, offset
, fin
, fec_protection
,
1132 void QuicConnection::SendRstStream(QuicStreamId id
,
1133 QuicRstStreamErrorCode error
,
1134 QuicStreamOffset bytes_written
) {
1135 // Opportunistically bundle an ack with this outgoing packet.
1136 ScopedPacketBundler
ack_bundler(this, BUNDLE_PENDING_ACK
);
1137 packet_generator_
.AddControlFrame(QuicFrame(new QuicRstStreamFrame(
1138 id
, AdjustErrorForVersion(error
, version()), bytes_written
)));
1140 sent_packet_manager_
.CancelRetransmissionsForStream(id
);
1141 // Remove all queued packets which only contain data for the reset stream.
1142 QueuedPacketList::iterator packet_iterator
= queued_packets_
.begin();
1143 while (packet_iterator
!= queued_packets_
.end()) {
1144 RetransmittableFrames
* retransmittable_frames
=
1145 packet_iterator
->serialized_packet
.retransmittable_frames
;
1146 if (!retransmittable_frames
) {
1150 retransmittable_frames
->RemoveFramesForStream(id
);
1151 if (!retransmittable_frames
->frames().empty()) {
1155 delete packet_iterator
->serialized_packet
.retransmittable_frames
;
1156 delete packet_iterator
->serialized_packet
.packet
;
1157 packet_iterator
->serialized_packet
.retransmittable_frames
= nullptr;
1158 packet_iterator
->serialized_packet
.packet
= nullptr;
1159 packet_iterator
= queued_packets_
.erase(packet_iterator
);
1163 void QuicConnection::SendWindowUpdate(QuicStreamId id
,
1164 QuicStreamOffset byte_offset
) {
1165 // Opportunistically bundle an ack with this outgoing packet.
1166 ScopedPacketBundler
ack_bundler(this, BUNDLE_PENDING_ACK
);
1167 packet_generator_
.AddControlFrame(
1168 QuicFrame(new QuicWindowUpdateFrame(id
, byte_offset
)));
1171 void QuicConnection::SendBlocked(QuicStreamId id
) {
1172 // Opportunistically bundle an ack with this outgoing packet.
1173 ScopedPacketBundler
ack_bundler(this, BUNDLE_PENDING_ACK
);
1174 packet_generator_
.AddControlFrame(QuicFrame(new QuicBlockedFrame(id
)));
1177 const QuicConnectionStats
& QuicConnection::GetStats() {
1178 const RttStats
* rtt_stats
= sent_packet_manager_
.GetRttStats();
1180 // Update rtt and estimated bandwidth.
1181 QuicTime::Delta min_rtt
= rtt_stats
->min_rtt();
1182 if (min_rtt
.IsZero()) {
1183 // If min RTT has not been set, use initial RTT instead.
1184 min_rtt
= QuicTime::Delta::FromMicroseconds(rtt_stats
->initial_rtt_us());
1186 stats_
.min_rtt_us
= min_rtt
.ToMicroseconds();
1188 QuicTime::Delta srtt
= rtt_stats
->smoothed_rtt();
1189 if (srtt
.IsZero()) {
1190 // If SRTT has not been set, use initial RTT instead.
1191 srtt
= QuicTime::Delta::FromMicroseconds(rtt_stats
->initial_rtt_us());
1193 stats_
.srtt_us
= srtt
.ToMicroseconds();
1195 stats_
.estimated_bandwidth
= sent_packet_manager_
.BandwidthEstimate();
1196 stats_
.max_packet_size
= packet_generator_
.max_packet_length();
1200 void QuicConnection::ProcessUdpPacket(const IPEndPoint
& self_address
,
1201 const IPEndPoint
& peer_address
,
1202 const QuicEncryptedPacket
& packet
) {
1206 // TODO(rtenneti): Remove ScopedTracker below once crbug.com/462789 is fixed.
1207 tracked_objects::ScopedTracker
tracking_profile(
1208 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1209 "462789 QuicConnection::ProcessUdpPacket"));
1210 if (debug_visitor_
!= nullptr) {
1211 debug_visitor_
->OnPacketReceived(self_address
, peer_address
, packet
);
1213 last_size_
= packet
.length();
1215 CheckForAddressMigration(self_address
, peer_address
);
1217 stats_
.bytes_received
+= packet
.length();
1218 ++stats_
.packets_received
;
1220 if (!framer_
.ProcessPacket(packet
)) {
1221 // If we are unable to decrypt this packet, it might be
1222 // because the CHLO or SHLO packet was lost.
1223 if (framer_
.error() == QUIC_DECRYPTION_FAILURE
) {
1224 if (encryption_level_
!= ENCRYPTION_FORWARD_SECURE
&&
1225 undecryptable_packets_
.size() < max_undecryptable_packets_
) {
1226 QueueUndecryptablePacket(packet
);
1227 } else if (debug_visitor_
!= nullptr) {
1228 debug_visitor_
->OnUndecryptablePacket();
1231 DVLOG(1) << ENDPOINT
<< "Unable to process packet. Last packet processed: "
1232 << last_header_
.packet_sequence_number
;
1236 ++stats_
.packets_processed
;
1237 MaybeProcessUndecryptablePackets();
1238 MaybeProcessRevivedPacket();
1239 MaybeSendInResponseToPacket();
1243 void QuicConnection::CheckForAddressMigration(
1244 const IPEndPoint
& self_address
, const IPEndPoint
& peer_address
) {
1245 peer_ip_changed_
= false;
1246 peer_port_changed_
= false;
1247 self_ip_changed_
= false;
1248 self_port_changed_
= false;
1250 if (peer_address_
.address().empty()) {
1251 peer_address_
= peer_address
;
1253 if (self_address_
.address().empty()) {
1254 self_address_
= self_address
;
1257 if (!peer_address
.address().empty() && !peer_address_
.address().empty()) {
1258 peer_ip_changed_
= (peer_address
.address() != peer_address_
.address());
1259 peer_port_changed_
= (peer_address
.port() != peer_address_
.port());
1261 // Store in case we want to migrate connection in ProcessValidatedPacket.
1262 migrating_peer_port_
= peer_address
.port();
1265 if (!self_address
.address().empty() && !self_address_
.address().empty()) {
1266 self_ip_changed_
= (self_address
.address() != self_address_
.address());
1267 self_port_changed_
= (self_address
.port() != self_address_
.port());
1271 void QuicConnection::OnCanWrite() {
1272 DCHECK(!writer_
->IsWriteBlocked());
1274 WriteQueuedPackets();
1275 WritePendingRetransmissions();
1277 // Sending queued packets may have caused the socket to become write blocked,
1278 // or the congestion manager to prohibit sending. If we've sent everything
1279 // we had queued and we're still not blocked, let the visitor know it can
1281 if (!CanWrite(HAS_RETRANSMITTABLE_DATA
)) {
1285 { // Limit the scope of the bundler. ACK inclusion happens elsewhere.
1286 ScopedPacketBundler
bundler(this, NO_ACK
);
1287 visitor_
->OnCanWrite();
1290 // After the visitor writes, it may have caused the socket to become write
1291 // blocked or the congestion manager to prohibit sending, so check again.
1292 if (visitor_
->WillingAndAbleToWrite() &&
1293 !resume_writes_alarm_
->IsSet() &&
1294 CanWrite(HAS_RETRANSMITTABLE_DATA
)) {
1295 // We're not write blocked, but some stream didn't write out all of its
1296 // bytes. Register for 'immediate' resumption so we'll keep writing after
1297 // other connections and events have had a chance to use the thread.
1298 resume_writes_alarm_
->Set(clock_
->ApproximateNow());
1302 void QuicConnection::WriteIfNotBlocked() {
1303 if (!writer_
->IsWriteBlocked()) {
1308 bool QuicConnection::ProcessValidatedPacket() {
1309 if (peer_ip_changed_
|| self_ip_changed_
|| self_port_changed_
) {
1310 SendConnectionCloseWithDetails(
1311 QUIC_ERROR_MIGRATING_ADDRESS
,
1312 "Neither IP address migration, nor self port migration are supported.");
1316 // Peer port migration is supported, do it now if port has changed.
1317 if (peer_port_changed_
) {
1318 DVLOG(1) << ENDPOINT
<< "Peer's port changed from "
1319 << peer_address_
.port() << " to " << migrating_peer_port_
1320 << ", migrating connection.";
1321 peer_address_
= IPEndPoint(peer_address_
.address(), migrating_peer_port_
);
1324 time_of_last_received_packet_
= clock_
->Now();
1325 DVLOG(1) << ENDPOINT
<< "time of last received packet: "
1326 << time_of_last_received_packet_
.ToDebuggingValue();
1328 if (perspective_
== Perspective::IS_SERVER
&&
1329 encryption_level_
== ENCRYPTION_NONE
&&
1330 last_size_
> packet_generator_
.max_packet_length()) {
1331 set_max_packet_length(last_size_
);
1336 void QuicConnection::WriteQueuedPackets() {
1337 DCHECK(!writer_
->IsWriteBlocked());
1339 if (pending_version_negotiation_packet_
) {
1340 SendVersionNegotiationPacket();
1343 QueuedPacketList::iterator packet_iterator
= queued_packets_
.begin();
1344 while (packet_iterator
!= queued_packets_
.end() &&
1345 WritePacket(&(*packet_iterator
))) {
1346 packet_iterator
= queued_packets_
.erase(packet_iterator
);
1350 void QuicConnection::WritePendingRetransmissions() {
1351 // Keep writing as long as there's a pending retransmission which can be
1353 while (sent_packet_manager_
.HasPendingRetransmissions()) {
1354 const QuicSentPacketManager::PendingRetransmission pending
=
1355 sent_packet_manager_
.NextPendingRetransmission();
1356 if (!CanWrite(HAS_RETRANSMITTABLE_DATA
)) {
1360 // Re-packetize the frames with a new sequence number for retransmission.
1361 // Retransmitted data packets do not use FEC, even when it's enabled.
1362 // Retransmitted packets use the same sequence number length as the
1364 // Flush the packet generator before making a new packet.
1365 // TODO(ianswett): Implement ReserializeAllFrames as a separate path that
1366 // does not require the creator to be flushed.
1367 packet_generator_
.FlushAllQueuedFrames();
1368 char buffer
[kMaxPacketSize
];
1369 SerializedPacket serialized_packet
= packet_generator_
.ReserializeAllFrames(
1370 pending
.retransmittable_frames
, pending
.sequence_number_length
, buffer
,
1372 if (serialized_packet
.packet
== nullptr) {
1373 // We failed to serialize the packet, so close the connection.
1374 // CloseConnection does not send close packet, so no infinite loop here.
1375 CloseConnection(QUIC_ENCRYPTION_FAILURE
, false);
1379 DVLOG(1) << ENDPOINT
<< "Retransmitting " << pending
.sequence_number
1380 << " as " << serialized_packet
.sequence_number
;
1382 QueuedPacket(serialized_packet
,
1383 pending
.retransmittable_frames
.encryption_level(),
1384 pending
.transmission_type
,
1385 pending
.sequence_number
));
1389 void QuicConnection::RetransmitUnackedPackets(
1390 TransmissionType retransmission_type
) {
1391 sent_packet_manager_
.RetransmitUnackedPackets(retransmission_type
);
1393 WriteIfNotBlocked();
1396 void QuicConnection::NeuterUnencryptedPackets() {
1397 sent_packet_manager_
.NeuterUnencryptedPackets();
1398 // This may have changed the retransmission timer, so re-arm it.
1399 QuicTime retransmission_time
= sent_packet_manager_
.GetRetransmissionTime();
1400 retransmission_alarm_
->Update(retransmission_time
,
1401 QuicTime::Delta::FromMilliseconds(1));
1404 bool QuicConnection::ShouldGeneratePacket(
1405 HasRetransmittableData retransmittable
,
1406 IsHandshake handshake
) {
1407 // We should serialize handshake packets immediately to ensure that they
1408 // end up sent at the right encryption level.
1409 if (handshake
== IS_HANDSHAKE
) {
1413 return CanWrite(retransmittable
);
1416 bool QuicConnection::CanWrite(HasRetransmittableData retransmittable
) {
1421 if (writer_
->IsWriteBlocked()) {
1422 visitor_
->OnWriteBlocked();
1426 QuicTime now
= clock_
->Now();
1427 QuicTime::Delta delay
= sent_packet_manager_
.TimeUntilSend(
1428 now
, retransmittable
);
1429 if (delay
.IsInfinite()) {
1430 send_alarm_
->Cancel();
1434 // If the scheduler requires a delay, then we can not send this packet now.
1435 if (!delay
.IsZero()) {
1436 send_alarm_
->Update(now
.Add(delay
), QuicTime::Delta::FromMilliseconds(1));
1437 DVLOG(1) << ENDPOINT
<< "Delaying sending " << delay
.ToMilliseconds()
1441 send_alarm_
->Cancel();
1445 bool QuicConnection::WritePacket(QueuedPacket
* packet
) {
1446 if (!WritePacketInner(packet
)) {
1449 delete packet
->serialized_packet
.retransmittable_frames
;
1450 delete packet
->serialized_packet
.packet
;
1451 packet
->serialized_packet
.retransmittable_frames
= nullptr;
1452 packet
->serialized_packet
.packet
= nullptr;
1456 bool QuicConnection::WritePacketInner(QueuedPacket
* packet
) {
1457 if (ShouldDiscardPacket(*packet
)) {
1458 ++stats_
.packets_discarded
;
1461 // Connection close packets are encrypted and saved, so don't exit early.
1462 const bool is_connection_close
= IsConnectionClose(*packet
);
1463 if (writer_
->IsWriteBlocked() && !is_connection_close
) {
1467 QuicPacketSequenceNumber sequence_number
=
1468 packet
->serialized_packet
.sequence_number
;
1469 DCHECK_LE(sequence_number_of_last_sent_packet_
, sequence_number
);
1470 sequence_number_of_last_sent_packet_
= sequence_number
;
1472 QuicEncryptedPacket
* encrypted
= packet
->serialized_packet
.packet
;
1473 // Connection close packets are eventually owned by TimeWaitListManager.
1474 // Others are deleted at the end of this call.
1475 if (is_connection_close
) {
1476 DCHECK(connection_close_packet_
.get() == nullptr);
1477 // Clone the packet so it's owned in the future.
1478 connection_close_packet_
.reset(encrypted
->Clone());
1479 // This assures we won't try to write *forced* packets when blocked.
1480 // Return true to stop processing.
1481 if (writer_
->IsWriteBlocked()) {
1482 visitor_
->OnWriteBlocked();
1487 if (!FLAGS_quic_allow_oversized_packets_for_test
) {
1488 DCHECK_LE(encrypted
->length(), kMaxPacketSize
);
1490 DCHECK_LE(encrypted
->length(), packet_generator_
.max_packet_length());
1491 DVLOG(1) << ENDPOINT
<< "Sending packet " << sequence_number
<< " : "
1492 << (packet
->serialized_packet
.is_fec_packet
1494 : (IsRetransmittable(*packet
) == HAS_RETRANSMITTABLE_DATA
1496 : " ack only ")) << ", encryption level: "
1497 << QuicUtils::EncryptionLevelToString(packet
->encryption_level
)
1498 << ", encrypted length:" << encrypted
->length();
1499 DVLOG(2) << ENDPOINT
<< "packet(" << sequence_number
<< "): " << std::endl
1500 << QuicUtils::StringToHexASCIIDump(encrypted
->AsStringPiece());
1502 // Measure the RTT from before the write begins to avoid underestimating the
1503 // min_rtt_, especially in cases where the thread blocks or gets swapped out
1504 // during the WritePacket below.
1505 QuicTime packet_send_time
= clock_
->Now();
1506 WriteResult result
= writer_
->WritePacket(encrypted
->data(),
1507 encrypted
->length(),
1508 self_address().address(),
1510 if (result
.error_code
== ERR_IO_PENDING
) {
1511 DCHECK_EQ(WRITE_STATUS_BLOCKED
, result
.status
);
1514 if (result
.status
== WRITE_STATUS_BLOCKED
) {
1515 visitor_
->OnWriteBlocked();
1516 // If the socket buffers the the data, then the packet should not
1517 // be queued and sent again, which would result in an unnecessary
1518 // duplicate packet being sent. The helper must call OnCanWrite
1519 // when the write completes, and OnWriteError if an error occurs.
1520 if (!writer_
->IsWriteBlockedDataBuffered()) {
1524 if (result
.status
!= WRITE_STATUS_ERROR
&& debug_visitor_
!= nullptr) {
1525 // Pass the write result to the visitor.
1526 debug_visitor_
->OnPacketSent(packet
->serialized_packet
,
1527 packet
->original_sequence_number
,
1528 packet
->encryption_level
,
1529 packet
->transmission_type
,
1533 if (packet
->transmission_type
== NOT_RETRANSMISSION
) {
1534 time_of_last_sent_new_packet_
= packet_send_time
;
1537 MaybeSetFecAlarm(sequence_number
);
1538 DVLOG(1) << ENDPOINT
<< "time we began writing last sent packet: "
1539 << packet_send_time
.ToDebuggingValue();
1541 // TODO(ianswett): Change the sequence number length and other packet creator
1542 // options by a more explicit API than setting a struct value directly,
1543 // perhaps via the NetworkChangeVisitor.
1544 packet_generator_
.UpdateSequenceNumberLength(
1545 sent_packet_manager_
.least_packet_awaited_by_peer(),
1546 sent_packet_manager_
.EstimateMaxPacketsInFlight(max_packet_length()));
1548 bool reset_retransmission_alarm
= sent_packet_manager_
.OnPacketSent(
1549 &packet
->serialized_packet
,
1550 packet
->original_sequence_number
,
1552 encrypted
->length(),
1553 packet
->transmission_type
,
1554 IsRetransmittable(*packet
));
1556 if (reset_retransmission_alarm
|| !retransmission_alarm_
->IsSet()) {
1557 retransmission_alarm_
->Update(sent_packet_manager_
.GetRetransmissionTime(),
1558 QuicTime::Delta::FromMilliseconds(1));
1561 stats_
.bytes_sent
+= result
.bytes_written
;
1562 ++stats_
.packets_sent
;
1563 if (packet
->transmission_type
!= NOT_RETRANSMISSION
) {
1564 stats_
.bytes_retransmitted
+= result
.bytes_written
;
1565 ++stats_
.packets_retransmitted
;
1568 if (result
.status
== WRITE_STATUS_ERROR
) {
1569 OnWriteError(result
.error_code
);
1570 DLOG(ERROR
) << ENDPOINT
<< "failed writing " << encrypted
->length()
1572 << " from host " << self_address().ToStringWithoutPort()
1573 << " to address " << peer_address().ToString();
1580 bool QuicConnection::ShouldDiscardPacket(const QueuedPacket
& packet
) {
1582 DVLOG(1) << ENDPOINT
1583 << "Not sending packet as connection is disconnected.";
1587 QuicPacketSequenceNumber sequence_number
=
1588 packet
.serialized_packet
.sequence_number
;
1589 if (encryption_level_
== ENCRYPTION_FORWARD_SECURE
&&
1590 packet
.encryption_level
== ENCRYPTION_NONE
) {
1591 // Drop packets that are NULL encrypted since the peer won't accept them
1593 DVLOG(1) << ENDPOINT
<< "Dropping NULL encrypted packet: "
1594 << sequence_number
<< " since the connection is forward secure.";
1598 // If a retransmission has been acked before sending, don't send it.
1599 // This occurs if a packet gets serialized, queued, then discarded.
1600 if (packet
.transmission_type
!= NOT_RETRANSMISSION
&&
1601 (!sent_packet_manager_
.IsUnacked(packet
.original_sequence_number
) ||
1602 !sent_packet_manager_
.HasRetransmittableFrames(
1603 packet
.original_sequence_number
))) {
1604 DVLOG(1) << ENDPOINT
<< "Dropping unacked packet: " << sequence_number
1605 << " A previous transmission was acked while write blocked.";
1612 void QuicConnection::OnWriteError(int error_code
) {
1613 DVLOG(1) << ENDPOINT
<< "Write failed with error: " << error_code
1614 << " (" << ErrorToString(error_code
) << ")";
1615 // We can't send an error as the socket is presumably borked.
1616 CloseConnection(QUIC_PACKET_WRITE_ERROR
, false);
1619 void QuicConnection::OnSerializedPacket(
1620 const SerializedPacket
& serialized_packet
) {
1621 if (serialized_packet
.packet
== nullptr) {
1622 // We failed to serialize the packet, so close the connection.
1623 // CloseConnection does not send close packet, so no infinite loop here.
1624 CloseConnection(QUIC_ENCRYPTION_FAILURE
, false);
1627 if (serialized_packet
.retransmittable_frames
) {
1628 sent_packet_manager_
.OnSerializedPacket(serialized_packet
);
1630 if (serialized_packet
.is_fec_packet
&& fec_alarm_
->IsSet()) {
1631 // If an FEC packet is serialized with the FEC alarm set, cancel the alarm.
1632 fec_alarm_
->Cancel();
1634 SendOrQueuePacket(QueuedPacket(serialized_packet
, encryption_level_
));
1637 void QuicConnection::OnCongestionWindowChange() {
1638 packet_generator_
.OnCongestionWindowChange(
1639 sent_packet_manager_
.EstimateMaxPacketsInFlight(max_packet_length()));
1640 visitor_
->OnCongestionWindowChange(clock_
->ApproximateNow());
1643 void QuicConnection::OnRttChange() {
1644 // Uses the connection's smoothed RTT. If zero, uses initial_rtt.
1645 QuicTime::Delta rtt
= sent_packet_manager_
.GetRttStats()->smoothed_rtt();
1647 rtt
= QuicTime::Delta::FromMicroseconds(
1648 sent_packet_manager_
.GetRttStats()->initial_rtt_us());
1650 packet_generator_
.OnRttChange(rtt
);
1653 void QuicConnection::OnHandshakeComplete() {
1654 sent_packet_manager_
.SetHandshakeConfirmed();
1655 // The client should immediately ack the SHLO to confirm the handshake is
1656 // complete with the server.
1657 if (perspective_
== Perspective::IS_CLIENT
&& !ack_queued_
) {
1658 ack_alarm_
->Cancel();
1659 ack_alarm_
->Set(clock_
->ApproximateNow());
1663 void QuicConnection::SendOrQueuePacket(QueuedPacket packet
) {
1664 // The caller of this function is responsible for checking CanWrite().
1665 if (packet
.serialized_packet
.packet
== nullptr) {
1667 << "packet.serialized_packet.packet == nullptr in to SendOrQueuePacket";
1671 sent_entropy_manager_
.RecordPacketEntropyHash(
1672 packet
.serialized_packet
.sequence_number
,
1673 packet
.serialized_packet
.entropy_hash
);
1674 if (!WritePacket(&packet
)) {
1675 // Take ownership of the underlying encrypted packet.
1676 if (!packet
.serialized_packet
.packet
->owns_buffer()) {
1677 scoped_ptr
<QuicEncryptedPacket
> encrypted_deleter(
1678 packet
.serialized_packet
.packet
);
1679 packet
.serialized_packet
.packet
=
1680 packet
.serialized_packet
.packet
->Clone();
1682 queued_packets_
.push_back(packet
);
1685 // If a forward-secure encrypter is available but is not being used and the
1686 // next sequence number is the first packet which requires
1687 // forward security, start using the forward-secure encrypter.
1688 if (encryption_level_
!= ENCRYPTION_FORWARD_SECURE
&&
1689 has_forward_secure_encrypter_
&&
1690 packet
.serialized_packet
.sequence_number
>=
1691 first_required_forward_secure_packet_
- 1) {
1692 SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE
);
1696 void QuicConnection::SendPing() {
1697 if (retransmission_alarm_
->IsSet()) {
1700 packet_generator_
.AddControlFrame(QuicFrame(new QuicPingFrame
));
1703 void QuicConnection::SendAck() {
1704 ack_alarm_
->Cancel();
1705 stop_waiting_count_
= 0;
1706 num_packets_received_since_last_ack_sent_
= 0;
1708 packet_generator_
.SetShouldSendAck(true);
1711 void QuicConnection::OnRetransmissionTimeout() {
1712 if (!sent_packet_manager_
.HasUnackedPackets()) {
1716 sent_packet_manager_
.OnRetransmissionTimeout();
1717 WriteIfNotBlocked();
1719 // A write failure can result in the connection being closed, don't attempt to
1720 // write further packets, or to set alarms.
1725 // In the TLP case, the SentPacketManager gives the connection the opportunity
1726 // to send new data before retransmitting.
1727 if (sent_packet_manager_
.MaybeRetransmitTailLossProbe()) {
1728 // Send the pending retransmission now that it's been queued.
1729 WriteIfNotBlocked();
1732 // Ensure the retransmission alarm is always set if there are unacked packets
1733 // and nothing waiting to be sent.
1734 if (!HasQueuedData() && !retransmission_alarm_
->IsSet()) {
1735 QuicTime rto_timeout
= sent_packet_manager_
.GetRetransmissionTime();
1736 if (rto_timeout
.IsInitialized()) {
1737 retransmission_alarm_
->Set(rto_timeout
);
1742 void QuicConnection::SetEncrypter(EncryptionLevel level
,
1743 QuicEncrypter
* encrypter
) {
1744 packet_generator_
.SetEncrypter(level
, encrypter
);
1745 if (level
== ENCRYPTION_FORWARD_SECURE
) {
1746 has_forward_secure_encrypter_
= true;
1747 first_required_forward_secure_packet_
=
1748 sequence_number_of_last_sent_packet_
+
1749 // 3 times the current congestion window (in slow start) should cover
1750 // about two full round trips worth of packets, which should be
1752 3 * sent_packet_manager_
.EstimateMaxPacketsInFlight(
1753 max_packet_length());
1757 void QuicConnection::SetDefaultEncryptionLevel(EncryptionLevel level
) {
1758 encryption_level_
= level
;
1759 packet_generator_
.set_encryption_level(level
);
1762 void QuicConnection::SetDecrypter(QuicDecrypter
* decrypter
,
1763 EncryptionLevel level
) {
1764 framer_
.SetDecrypter(decrypter
, level
);
1767 void QuicConnection::SetAlternativeDecrypter(QuicDecrypter
* decrypter
,
1768 EncryptionLevel level
,
1769 bool latch_once_used
) {
1770 framer_
.SetAlternativeDecrypter(decrypter
, level
, latch_once_used
);
1773 const QuicDecrypter
* QuicConnection::decrypter() const {
1774 return framer_
.decrypter();
1777 const QuicDecrypter
* QuicConnection::alternative_decrypter() const {
1778 return framer_
.alternative_decrypter();
1781 void QuicConnection::QueueUndecryptablePacket(
1782 const QuicEncryptedPacket
& packet
) {
1783 DVLOG(1) << ENDPOINT
<< "Queueing undecryptable packet.";
1784 undecryptable_packets_
.push_back(packet
.Clone());
1787 void QuicConnection::MaybeProcessUndecryptablePackets() {
1788 if (undecryptable_packets_
.empty() || encryption_level_
== ENCRYPTION_NONE
) {
1792 while (connected_
&& !undecryptable_packets_
.empty()) {
1793 DVLOG(1) << ENDPOINT
<< "Attempting to process undecryptable packet";
1794 QuicEncryptedPacket
* packet
= undecryptable_packets_
.front();
1795 if (!framer_
.ProcessPacket(*packet
) &&
1796 framer_
.error() == QUIC_DECRYPTION_FAILURE
) {
1797 DVLOG(1) << ENDPOINT
<< "Unable to process undecryptable packet...";
1800 DVLOG(1) << ENDPOINT
<< "Processed undecryptable packet!";
1801 ++stats_
.packets_processed
;
1803 undecryptable_packets_
.pop_front();
1806 // Once forward secure encryption is in use, there will be no
1807 // new keys installed and hence any undecryptable packets will
1808 // never be able to be decrypted.
1809 if (encryption_level_
== ENCRYPTION_FORWARD_SECURE
) {
1810 if (debug_visitor_
!= nullptr) {
1811 // TODO(rtenneti): perhaps more efficient to pass the number of
1812 // undecryptable packets as the argument to OnUndecryptablePacket so that
1813 // we just need to call OnUndecryptablePacket once?
1814 for (size_t i
= 0; i
< undecryptable_packets_
.size(); ++i
) {
1815 debug_visitor_
->OnUndecryptablePacket();
1818 STLDeleteElements(&undecryptable_packets_
);
1822 void QuicConnection::MaybeProcessRevivedPacket() {
1823 QuicFecGroup
* group
= GetFecGroup();
1824 if (!connected_
|| group
== nullptr || !group
->CanRevive()) {
1827 QuicPacketHeader revived_header
;
1828 char revived_payload
[kMaxPacketSize
];
1829 size_t len
= group
->Revive(&revived_header
, revived_payload
, kMaxPacketSize
);
1830 revived_header
.public_header
.connection_id
= connection_id_
;
1831 revived_header
.public_header
.connection_id_length
=
1832 last_header_
.public_header
.connection_id_length
;
1833 revived_header
.public_header
.version_flag
= false;
1834 revived_header
.public_header
.reset_flag
= false;
1835 revived_header
.public_header
.sequence_number_length
=
1836 last_header_
.public_header
.sequence_number_length
;
1837 revived_header
.fec_flag
= false;
1838 revived_header
.is_in_fec_group
= NOT_IN_FEC_GROUP
;
1839 revived_header
.fec_group
= 0;
1840 group_map_
.erase(last_header_
.fec_group
);
1841 last_decrypted_packet_level_
= group
->effective_encryption_level();
1842 DCHECK_LT(last_decrypted_packet_level_
, NUM_ENCRYPTION_LEVELS
);
1845 last_packet_revived_
= true;
1846 if (debug_visitor_
!= nullptr) {
1847 debug_visitor_
->OnRevivedPacket(revived_header
,
1848 StringPiece(revived_payload
, len
));
1851 ++stats_
.packets_revived
;
1852 framer_
.ProcessRevivedPacket(&revived_header
,
1853 StringPiece(revived_payload
, len
));
1856 QuicFecGroup
* QuicConnection::GetFecGroup() {
1857 QuicFecGroupNumber fec_group_num
= last_header_
.fec_group
;
1858 if (fec_group_num
== 0) {
1861 if (!ContainsKey(group_map_
, fec_group_num
)) {
1862 if (group_map_
.size() >= kMaxFecGroups
) { // Too many groups
1863 if (fec_group_num
< group_map_
.begin()->first
) {
1864 // The group being requested is a group we've seen before and deleted.
1865 // Don't recreate it.
1868 // Clear the lowest group number.
1869 delete group_map_
.begin()->second
;
1870 group_map_
.erase(group_map_
.begin());
1872 group_map_
[fec_group_num
] = new QuicFecGroup();
1874 return group_map_
[fec_group_num
];
1877 void QuicConnection::SendConnectionClose(QuicErrorCode error
) {
1878 SendConnectionCloseWithDetails(error
, string());
1881 void QuicConnection::SendConnectionCloseWithDetails(QuicErrorCode error
,
1882 const string
& details
) {
1883 // If we're write blocked, WritePacket() will not send, but will capture the
1884 // serialized packet.
1885 SendConnectionClosePacket(error
, details
);
1886 CloseConnection(error
, false);
1889 void QuicConnection::SendConnectionClosePacket(QuicErrorCode error
,
1890 const string
& details
) {
1891 DVLOG(1) << ENDPOINT
<< "Force closing " << connection_id()
1892 << " with error " << QuicUtils::ErrorToString(error
)
1893 << " (" << error
<< ") " << details
;
1894 // Don't send explicit connection close packets for timeouts.
1895 // This is particularly important on mobile, where connections are short.
1896 if (silent_close_enabled_
&&
1897 error
== QuicErrorCode::QUIC_CONNECTION_TIMED_OUT
) {
1900 ScopedPacketBundler
ack_bundler(this, SEND_ACK
);
1901 QuicConnectionCloseFrame
* frame
= new QuicConnectionCloseFrame();
1902 frame
->error_code
= error
;
1903 frame
->error_details
= details
;
1904 packet_generator_
.AddControlFrame(QuicFrame(frame
));
1905 packet_generator_
.FlushAllQueuedFrames();
1908 void QuicConnection::CloseConnection(QuicErrorCode error
, bool from_peer
) {
1910 DVLOG(1) << "Connection is already closed.";
1914 if (debug_visitor_
!= nullptr) {
1915 debug_visitor_
->OnConnectionClosed(error
, from_peer
);
1917 DCHECK(visitor_
!= nullptr);
1918 visitor_
->OnConnectionClosed(error
, from_peer
);
1919 // Cancel the alarms so they don't trigger any action now that the
1920 // connection is closed.
1921 ack_alarm_
->Cancel();
1922 ping_alarm_
->Cancel();
1923 fec_alarm_
->Cancel();
1924 resume_writes_alarm_
->Cancel();
1925 retransmission_alarm_
->Cancel();
1926 send_alarm_
->Cancel();
1927 timeout_alarm_
->Cancel();
1930 void QuicConnection::SendGoAway(QuicErrorCode error
,
1931 QuicStreamId last_good_stream_id
,
1932 const string
& reason
) {
1933 DVLOG(1) << ENDPOINT
<< "Going away with error "
1934 << QuicUtils::ErrorToString(error
)
1935 << " (" << error
<< ")";
1937 // Opportunistically bundle an ack with this outgoing packet.
1938 ScopedPacketBundler
ack_bundler(this, BUNDLE_PENDING_ACK
);
1939 packet_generator_
.AddControlFrame(
1940 QuicFrame(new QuicGoAwayFrame(error
, last_good_stream_id
, reason
)));
1943 void QuicConnection::CloseFecGroupsBefore(
1944 QuicPacketSequenceNumber sequence_number
) {
1945 FecGroupMap::iterator it
= group_map_
.begin();
1946 while (it
!= group_map_
.end()) {
1947 // If this is the current group or the group doesn't protect this packet
1948 // we can ignore it.
1949 if (last_header_
.fec_group
== it
->first
||
1950 !it
->second
->ProtectsPacketsBefore(sequence_number
)) {
1954 QuicFecGroup
* fec_group
= it
->second
;
1955 DCHECK(!fec_group
->CanRevive());
1956 FecGroupMap::iterator next
= it
;
1958 group_map_
.erase(it
);
1964 QuicByteCount
QuicConnection::max_packet_length() const {
1965 return packet_generator_
.max_packet_length();
1968 void QuicConnection::set_max_packet_length(QuicByteCount length
) {
1969 return packet_generator_
.set_max_packet_length(length
);
1972 bool QuicConnection::HasQueuedData() const {
1973 return pending_version_negotiation_packet_
||
1974 !queued_packets_
.empty() || packet_generator_
.HasQueuedFrames();
1977 bool QuicConnection::CanWriteStreamData() {
1978 // Don't write stream data if there are negotiation or queued data packets
1979 // to send. Otherwise, continue and bundle as many frames as possible.
1980 if (pending_version_negotiation_packet_
|| !queued_packets_
.empty()) {
1984 IsHandshake pending_handshake
= visitor_
->HasPendingHandshake() ?
1985 IS_HANDSHAKE
: NOT_HANDSHAKE
;
1986 // Sending queued packets may have caused the socket to become write blocked,
1987 // or the congestion manager to prohibit sending. If we've sent everything
1988 // we had queued and we're still not blocked, let the visitor know it can
1990 return ShouldGeneratePacket(HAS_RETRANSMITTABLE_DATA
, pending_handshake
);
1993 void QuicConnection::SetNetworkTimeouts(QuicTime::Delta overall_timeout
,
1994 QuicTime::Delta idle_timeout
) {
1995 LOG_IF(DFATAL
, idle_timeout
> overall_timeout
)
1996 << "idle_timeout:" << idle_timeout
.ToMilliseconds()
1997 << " overall_timeout:" << overall_timeout
.ToMilliseconds();
1998 // Adjust the idle timeout on client and server to prevent clients from
1999 // sending requests to servers which have already closed the connection.
2000 if (perspective_
== Perspective::IS_SERVER
) {
2001 idle_timeout
= idle_timeout
.Add(QuicTime::Delta::FromSeconds(3));
2002 } else if (idle_timeout
> QuicTime::Delta::FromSeconds(1)) {
2003 idle_timeout
= idle_timeout
.Subtract(QuicTime::Delta::FromSeconds(1));
2005 overall_connection_timeout_
= overall_timeout
;
2006 idle_network_timeout_
= idle_timeout
;
2011 void QuicConnection::CheckForTimeout() {
2012 QuicTime now
= clock_
->ApproximateNow();
2013 QuicTime time_of_last_packet
= max(time_of_last_received_packet_
,
2014 time_of_last_sent_new_packet_
);
2016 // |delta| can be < 0 as |now| is approximate time but |time_of_last_packet|
2017 // is accurate time. However, this should not change the behavior of
2018 // timeout handling.
2019 QuicTime::Delta idle_duration
= now
.Subtract(time_of_last_packet
);
2020 DVLOG(1) << ENDPOINT
<< "last packet "
2021 << time_of_last_packet
.ToDebuggingValue()
2022 << " now:" << now
.ToDebuggingValue()
2023 << " idle_duration:" << idle_duration
.ToMicroseconds()
2024 << " idle_network_timeout: "
2025 << idle_network_timeout_
.ToMicroseconds();
2026 if (idle_duration
>= idle_network_timeout_
) {
2027 DVLOG(1) << ENDPOINT
<< "Connection timedout due to no network activity.";
2028 SendConnectionClose(QUIC_CONNECTION_TIMED_OUT
);
2032 if (!overall_connection_timeout_
.IsInfinite()) {
2033 QuicTime::Delta connected_duration
=
2034 now
.Subtract(stats_
.connection_creation_time
);
2035 DVLOG(1) << ENDPOINT
<< "connection time: "
2036 << connected_duration
.ToMicroseconds() << " overall timeout: "
2037 << overall_connection_timeout_
.ToMicroseconds();
2038 if (connected_duration
>= overall_connection_timeout_
) {
2039 DVLOG(1) << ENDPOINT
<<
2040 "Connection timedout due to overall connection timeout.";
2041 SendConnectionClose(QUIC_CONNECTION_OVERALL_TIMED_OUT
);
2049 void QuicConnection::SetTimeoutAlarm() {
2050 QuicTime time_of_last_packet
= max(time_of_last_received_packet_
,
2051 time_of_last_sent_new_packet_
);
2053 QuicTime deadline
= time_of_last_packet
.Add(idle_network_timeout_
);
2054 if (!overall_connection_timeout_
.IsInfinite()) {
2055 deadline
= min(deadline
,
2056 stats_
.connection_creation_time
.Add(
2057 overall_connection_timeout_
));
2060 timeout_alarm_
->Cancel();
2061 timeout_alarm_
->Set(deadline
);
2064 void QuicConnection::SetPingAlarm() {
2065 if (perspective_
== Perspective::IS_SERVER
) {
2066 // Only clients send pings.
2069 if (!visitor_
->HasOpenDataStreams()) {
2070 ping_alarm_
->Cancel();
2071 // Don't send a ping unless there are open streams.
2074 QuicTime::Delta ping_timeout
= QuicTime::Delta::FromSeconds(kPingTimeoutSecs
);
2075 ping_alarm_
->Update(clock_
->ApproximateNow().Add(ping_timeout
),
2076 QuicTime::Delta::FromSeconds(1));
2079 QuicConnection::ScopedPacketBundler::ScopedPacketBundler(
2080 QuicConnection
* connection
,
2081 AckBundling send_ack
)
2082 : connection_(connection
),
2083 already_in_batch_mode_(connection
!= nullptr &&
2084 connection
->packet_generator_
.InBatchMode()) {
2085 if (connection_
== nullptr) {
2088 // Move generator into batch mode. If caller wants us to include an ack,
2089 // check the delayed-ack timer to see if there's ack info to be sent.
2090 if (!already_in_batch_mode_
) {
2091 DVLOG(1) << "Entering Batch Mode.";
2092 connection_
->packet_generator_
.StartBatchOperations();
2094 // Bundle an ack if the alarm is set or with every second packet if we need to
2095 // raise the peer's least unacked.
2097 connection_
->ack_alarm_
->IsSet() || connection_
->stop_waiting_count_
> 1;
2098 if (send_ack
== SEND_ACK
|| (send_ack
== BUNDLE_PENDING_ACK
&& ack_pending
)) {
2099 DVLOG(1) << "Bundling ack with outgoing packet.";
2100 connection_
->SendAck();
2104 QuicConnection::ScopedPacketBundler::~ScopedPacketBundler() {
2105 if (connection_
== nullptr) {
2108 // If we changed the generator's batch state, restore original batch state.
2109 if (!already_in_batch_mode_
) {
2110 DVLOG(1) << "Leaving Batch Mode.";
2111 connection_
->packet_generator_
.FinishBatchOperations();
2113 DCHECK_EQ(already_in_batch_mode_
,
2114 connection_
->packet_generator_
.InBatchMode());
2117 HasRetransmittableData
QuicConnection::IsRetransmittable(
2118 const QueuedPacket
& packet
) {
2119 // Retransmitted packets retransmittable frames are owned by the unacked
2120 // packet map, but are not present in the serialized packet.
2121 if (packet
.transmission_type
!= NOT_RETRANSMISSION
||
2122 packet
.serialized_packet
.retransmittable_frames
!= nullptr) {
2123 return HAS_RETRANSMITTABLE_DATA
;
2125 return NO_RETRANSMITTABLE_DATA
;
2129 bool QuicConnection::IsConnectionClose(const QueuedPacket
& packet
) {
2130 const RetransmittableFrames
* retransmittable_frames
=
2131 packet
.serialized_packet
.retransmittable_frames
;
2132 if (retransmittable_frames
== nullptr) {
2135 for (const QuicFrame
& frame
: retransmittable_frames
->frames()) {
2136 if (frame
.type
== CONNECTION_CLOSE_FRAME
) {