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_
);
910 if (!connected_
&& FLAGS_quic_stop_early_2
) {
915 for (const QuicStreamFrame
& stream_frame
: last_stream_frames_
) {
916 stats_
.stream_bytes_received
+= stream_frame
.data
.size();
918 // Process window updates, blocked, stream resets, acks, then congestion
920 if (!last_window_update_frames_
.empty()) {
921 visitor_
->OnWindowUpdateFrames(last_window_update_frames_
);
922 if (!connected_
&& FLAGS_quic_stop_early_2
) {
926 if (!last_blocked_frames_
.empty()) {
927 visitor_
->OnBlockedFrames(last_blocked_frames_
);
928 if (!connected_
&& FLAGS_quic_stop_early_2
) {
932 for (size_t i
= 0; i
< last_goaway_frames_
.size(); ++i
) {
933 visitor_
->OnGoAway(last_goaway_frames_
[i
]);
934 if (!connected_
&& FLAGS_quic_stop_early_2
) {
938 for (size_t i
= 0; i
< last_rst_frames_
.size(); ++i
) {
939 visitor_
->OnRstStream(last_rst_frames_
[i
]);
940 if (!connected_
&& FLAGS_quic_stop_early_2
) {
944 for (size_t i
= 0; i
< last_ack_frames_
.size(); ++i
) {
945 ProcessAckFrame(last_ack_frames_
[i
]);
946 if (!connected_
&& FLAGS_quic_stop_early_2
) {
950 for (size_t i
= 0; i
< last_stop_waiting_frames_
.size(); ++i
) {
951 ProcessStopWaitingFrame(last_stop_waiting_frames_
[i
]);
952 if (!connected_
&& FLAGS_quic_stop_early_2
) {
956 if (!last_close_frames_
.empty()) {
957 CloseConnection(last_close_frames_
[0].error_code
, true);
959 if (FLAGS_quic_stop_early_2
) {
964 // If there are new missing packets to report, send an ack immediately.
965 if (received_packet_manager_
.HasNewMissingPackets()) {
967 ack_alarm_
->Cancel();
970 UpdateStopWaitingCount();
972 MaybeCloseIfTooManyOutstandingPackets();
975 void QuicConnection::MaybeQueueAck() {
976 // If the incoming packet was missing, send an ack immediately.
977 ack_queued_
= received_packet_manager_
.IsMissing(
978 last_header_
.packet_sequence_number
);
980 if (!ack_queued_
&& ShouldLastPacketInstigateAck()) {
981 if (ack_alarm_
->IsSet()) {
985 clock_
->ApproximateNow().Add(sent_packet_manager_
.DelayedAckTime()));
986 DVLOG(1) << "Ack timer set; next packet or timer will trigger ACK.";
991 ack_alarm_
->Cancel();
995 void QuicConnection::ClearLastFrames() {
996 last_stream_frames_
.clear();
997 last_ack_frames_
.clear();
998 last_stop_waiting_frames_
.clear();
999 last_rst_frames_
.clear();
1000 last_goaway_frames_
.clear();
1001 last_window_update_frames_
.clear();
1002 last_blocked_frames_
.clear();
1003 last_ping_frames_
.clear();
1004 last_close_frames_
.clear();
1007 void QuicConnection::MaybeCloseIfTooManyOutstandingPackets() {
1008 // This occurs if we don't discard old packets we've sent fast enough.
1009 // It's possible largest observed is less than least unacked.
1010 if (sent_packet_manager_
.largest_observed() >
1011 (sent_packet_manager_
.GetLeastUnacked() + kMaxTrackedPackets
)) {
1012 SendConnectionCloseWithDetails(
1013 QUIC_TOO_MANY_OUTSTANDING_SENT_PACKETS
,
1014 StringPrintf("More than %" PRIu64
" outstanding.", kMaxTrackedPackets
));
1016 // This occurs if there are received packet gaps and the peer does not raise
1017 // the least unacked fast enough.
1018 if (received_packet_manager_
.NumTrackedPackets() > kMaxTrackedPackets
) {
1019 SendConnectionCloseWithDetails(
1020 QUIC_TOO_MANY_OUTSTANDING_RECEIVED_PACKETS
,
1021 StringPrintf("More than %" PRIu64
" outstanding.", kMaxTrackedPackets
));
1025 void QuicConnection::PopulateAckFrame(QuicAckFrame
* ack
) {
1026 received_packet_manager_
.UpdateReceivedPacketInfo(ack
,
1027 clock_
->ApproximateNow());
1030 void QuicConnection::PopulateStopWaitingFrame(
1031 QuicStopWaitingFrame
* stop_waiting
) {
1032 stop_waiting
->least_unacked
= GetLeastUnacked();
1033 stop_waiting
->entropy_hash
= sent_entropy_manager_
.GetCumulativeEntropy(
1034 stop_waiting
->least_unacked
- 1);
1037 bool QuicConnection::ShouldLastPacketInstigateAck() const {
1038 if (!last_stream_frames_
.empty() ||
1039 !last_goaway_frames_
.empty() ||
1040 !last_rst_frames_
.empty() ||
1041 !last_window_update_frames_
.empty() ||
1042 !last_blocked_frames_
.empty() ||
1043 !last_ping_frames_
.empty()) {
1047 if (!last_ack_frames_
.empty() && last_ack_frames_
.back().is_truncated
) {
1050 // Always send an ack every 20 packets in order to allow the peer to discard
1051 // information from the SentPacketManager and provide an RTT measurement.
1052 if (num_packets_received_since_last_ack_sent_
>=
1053 kMaxPacketsReceivedBeforeAckSend
) {
1059 void QuicConnection::UpdateStopWaitingCount() {
1060 if (last_ack_frames_
.empty()) {
1064 // If the peer is still waiting for a packet that we are no longer planning to
1065 // send, send an ack to raise the high water mark.
1066 if (!last_ack_frames_
.back().missing_packets
.empty() &&
1067 GetLeastUnacked() > *last_ack_frames_
.back().missing_packets
.begin()) {
1068 ++stop_waiting_count_
;
1070 stop_waiting_count_
= 0;
1074 QuicPacketSequenceNumber
QuicConnection::GetLeastUnacked() const {
1075 return sent_packet_manager_
.GetLeastUnacked();
1078 void QuicConnection::MaybeSendInResponseToPacket() {
1082 ScopedPacketBundler
bundler(this, ack_queued_
? SEND_ACK
: NO_ACK
);
1084 // Now that we have received an ack, we might be able to send packets which
1085 // are queued locally, or drain streams which are blocked.
1086 if (CanWrite(HAS_RETRANSMITTABLE_DATA
)) {
1091 void QuicConnection::SendVersionNegotiationPacket() {
1092 // TODO(alyssar): implement zero server state negotiation.
1093 pending_version_negotiation_packet_
= true;
1094 if (writer_
->IsWriteBlocked()) {
1095 visitor_
->OnWriteBlocked();
1098 DVLOG(1) << ENDPOINT
<< "Sending version negotiation packet: {"
1099 << QuicVersionVectorToString(framer_
.supported_versions()) << "}";
1100 scoped_ptr
<QuicEncryptedPacket
> version_packet(
1101 packet_generator_
.SerializeVersionNegotiationPacket(
1102 framer_
.supported_versions()));
1103 WriteResult result
= writer_
->WritePacket(
1104 version_packet
->data(), version_packet
->length(),
1105 self_address().address(), peer_address());
1107 if (result
.status
== WRITE_STATUS_ERROR
) {
1108 // We can't send an error as the socket is presumably borked.
1109 CloseConnection(QUIC_PACKET_WRITE_ERROR
, false);
1112 if (result
.status
== WRITE_STATUS_BLOCKED
) {
1113 visitor_
->OnWriteBlocked();
1114 if (writer_
->IsWriteBlockedDataBuffered()) {
1115 pending_version_negotiation_packet_
= false;
1120 pending_version_negotiation_packet_
= false;
1123 QuicConsumedData
QuicConnection::SendStreamData(
1125 const IOVector
& data
,
1126 QuicStreamOffset offset
,
1128 FecProtection fec_protection
,
1129 QuicAckNotifier::DelegateInterface
* delegate
) {
1130 if (!fin
&& data
.Empty()) {
1131 LOG(DFATAL
) << "Attempt to send empty stream frame";
1132 return QuicConsumedData(0, false);
1135 // Opportunistically bundle an ack with every outgoing packet.
1136 // Particularly, we want to bundle with handshake packets since we don't know
1137 // which decrypter will be used on an ack packet following a handshake
1138 // packet (a handshake packet from client to server could result in a REJ or a
1139 // SHLO from the server, leading to two different decrypters at the server.)
1141 // TODO(jri): Note that ConsumeData may cause a response packet to be sent.
1142 // We may end up sending stale ack information if there are undecryptable
1143 // packets hanging around and/or there are revivable packets which may get
1144 // handled after this packet is sent. Change ScopedPacketBundler to do the
1145 // right thing: check ack_queued_, and then check undecryptable packets and
1146 // also if there is possibility of revival. Only bundle an ack if there's no
1147 // processing left that may cause received_info_ to change.
1148 ScopedPacketBundler
ack_bundler(this, BUNDLE_PENDING_ACK
);
1149 return packet_generator_
.ConsumeData(id
, data
, offset
, fin
, fec_protection
,
1153 void QuicConnection::SendRstStream(QuicStreamId id
,
1154 QuicRstStreamErrorCode error
,
1155 QuicStreamOffset bytes_written
) {
1156 // Opportunistically bundle an ack with this outgoing packet.
1157 ScopedPacketBundler
ack_bundler(this, BUNDLE_PENDING_ACK
);
1158 packet_generator_
.AddControlFrame(QuicFrame(new QuicRstStreamFrame(
1159 id
, AdjustErrorForVersion(error
, version()), bytes_written
)));
1161 sent_packet_manager_
.CancelRetransmissionsForStream(id
);
1162 // Remove all queued packets which only contain data for the reset stream.
1163 QueuedPacketList::iterator packet_iterator
= queued_packets_
.begin();
1164 while (packet_iterator
!= queued_packets_
.end()) {
1165 RetransmittableFrames
* retransmittable_frames
=
1166 packet_iterator
->serialized_packet
.retransmittable_frames
;
1167 if (!retransmittable_frames
) {
1171 retransmittable_frames
->RemoveFramesForStream(id
);
1172 if (!retransmittable_frames
->frames().empty()) {
1176 delete packet_iterator
->serialized_packet
.retransmittable_frames
;
1177 delete packet_iterator
->serialized_packet
.packet
;
1178 packet_iterator
->serialized_packet
.retransmittable_frames
= nullptr;
1179 packet_iterator
->serialized_packet
.packet
= nullptr;
1180 packet_iterator
= queued_packets_
.erase(packet_iterator
);
1184 void QuicConnection::SendWindowUpdate(QuicStreamId id
,
1185 QuicStreamOffset byte_offset
) {
1186 // Opportunistically bundle an ack with this outgoing packet.
1187 ScopedPacketBundler
ack_bundler(this, BUNDLE_PENDING_ACK
);
1188 packet_generator_
.AddControlFrame(
1189 QuicFrame(new QuicWindowUpdateFrame(id
, byte_offset
)));
1192 void QuicConnection::SendBlocked(QuicStreamId id
) {
1193 // Opportunistically bundle an ack with this outgoing packet.
1194 ScopedPacketBundler
ack_bundler(this, BUNDLE_PENDING_ACK
);
1195 packet_generator_
.AddControlFrame(QuicFrame(new QuicBlockedFrame(id
)));
1198 const QuicConnectionStats
& QuicConnection::GetStats() {
1199 const RttStats
* rtt_stats
= sent_packet_manager_
.GetRttStats();
1201 // Update rtt and estimated bandwidth.
1202 QuicTime::Delta min_rtt
= rtt_stats
->min_rtt();
1203 if (min_rtt
.IsZero()) {
1204 // If min RTT has not been set, use initial RTT instead.
1205 min_rtt
= QuicTime::Delta::FromMicroseconds(rtt_stats
->initial_rtt_us());
1207 stats_
.min_rtt_us
= min_rtt
.ToMicroseconds();
1209 QuicTime::Delta srtt
= rtt_stats
->smoothed_rtt();
1210 if (srtt
.IsZero()) {
1211 // If SRTT has not been set, use initial RTT instead.
1212 srtt
= QuicTime::Delta::FromMicroseconds(rtt_stats
->initial_rtt_us());
1214 stats_
.srtt_us
= srtt
.ToMicroseconds();
1216 stats_
.estimated_bandwidth
= sent_packet_manager_
.BandwidthEstimate();
1217 stats_
.max_packet_size
= packet_generator_
.max_packet_length();
1221 void QuicConnection::ProcessUdpPacket(const IPEndPoint
& self_address
,
1222 const IPEndPoint
& peer_address
,
1223 const QuicEncryptedPacket
& packet
) {
1227 // TODO(rtenneti): Remove ScopedTracker below once crbug.com/462789 is fixed.
1228 tracked_objects::ScopedTracker
tracking_profile(
1229 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1230 "462789 QuicConnection::ProcessUdpPacket"));
1231 if (debug_visitor_
!= nullptr) {
1232 debug_visitor_
->OnPacketReceived(self_address
, peer_address
, packet
);
1234 last_size_
= packet
.length();
1236 CheckForAddressMigration(self_address
, peer_address
);
1238 stats_
.bytes_received
+= packet
.length();
1239 ++stats_
.packets_received
;
1241 if (!framer_
.ProcessPacket(packet
)) {
1242 // If we are unable to decrypt this packet, it might be
1243 // because the CHLO or SHLO packet was lost.
1244 if (framer_
.error() == QUIC_DECRYPTION_FAILURE
) {
1245 if (encryption_level_
!= ENCRYPTION_FORWARD_SECURE
&&
1246 undecryptable_packets_
.size() < max_undecryptable_packets_
) {
1247 QueueUndecryptablePacket(packet
);
1248 } else if (debug_visitor_
!= nullptr) {
1249 debug_visitor_
->OnUndecryptablePacket();
1252 DVLOG(1) << ENDPOINT
<< "Unable to process packet. Last packet processed: "
1253 << last_header_
.packet_sequence_number
;
1257 ++stats_
.packets_processed
;
1258 MaybeProcessUndecryptablePackets();
1259 MaybeProcessRevivedPacket();
1260 MaybeSendInResponseToPacket();
1264 void QuicConnection::CheckForAddressMigration(
1265 const IPEndPoint
& self_address
, const IPEndPoint
& peer_address
) {
1266 peer_ip_changed_
= false;
1267 peer_port_changed_
= false;
1268 self_ip_changed_
= false;
1269 self_port_changed_
= false;
1271 if (peer_address_
.address().empty()) {
1272 peer_address_
= peer_address
;
1274 if (self_address_
.address().empty()) {
1275 self_address_
= self_address
;
1278 if (!peer_address
.address().empty() && !peer_address_
.address().empty()) {
1279 peer_ip_changed_
= (peer_address
.address() != peer_address_
.address());
1280 peer_port_changed_
= (peer_address
.port() != peer_address_
.port());
1282 // Store in case we want to migrate connection in ProcessValidatedPacket.
1283 migrating_peer_port_
= peer_address
.port();
1286 if (!self_address
.address().empty() && !self_address_
.address().empty()) {
1287 self_ip_changed_
= (self_address
.address() != self_address_
.address());
1288 self_port_changed_
= (self_address
.port() != self_address_
.port());
1292 void QuicConnection::OnCanWrite() {
1293 DCHECK(!writer_
->IsWriteBlocked());
1295 WriteQueuedPackets();
1296 WritePendingRetransmissions();
1298 // Sending queued packets may have caused the socket to become write blocked,
1299 // or the congestion manager to prohibit sending. If we've sent everything
1300 // we had queued and we're still not blocked, let the visitor know it can
1302 if (!CanWrite(HAS_RETRANSMITTABLE_DATA
)) {
1306 { // Limit the scope of the bundler. ACK inclusion happens elsewhere.
1307 ScopedPacketBundler
bundler(this, NO_ACK
);
1308 visitor_
->OnCanWrite();
1311 // After the visitor writes, it may have caused the socket to become write
1312 // blocked or the congestion manager to prohibit sending, so check again.
1313 if (visitor_
->WillingAndAbleToWrite() &&
1314 !resume_writes_alarm_
->IsSet() &&
1315 CanWrite(HAS_RETRANSMITTABLE_DATA
)) {
1316 // We're not write blocked, but some stream didn't write out all of its
1317 // bytes. Register for 'immediate' resumption so we'll keep writing after
1318 // other connections and events have had a chance to use the thread.
1319 resume_writes_alarm_
->Set(clock_
->ApproximateNow());
1323 void QuicConnection::WriteIfNotBlocked() {
1324 if (!writer_
->IsWriteBlocked()) {
1329 bool QuicConnection::ProcessValidatedPacket() {
1330 if (peer_ip_changed_
|| self_ip_changed_
|| self_port_changed_
) {
1331 SendConnectionCloseWithDetails(
1332 QUIC_ERROR_MIGRATING_ADDRESS
,
1333 "Neither IP address migration, nor self port migration are supported.");
1337 // Peer port migration is supported, do it now if port has changed.
1338 if (peer_port_changed_
) {
1339 DVLOG(1) << ENDPOINT
<< "Peer's port changed from "
1340 << peer_address_
.port() << " to " << migrating_peer_port_
1341 << ", migrating connection.";
1342 peer_address_
= IPEndPoint(peer_address_
.address(), migrating_peer_port_
);
1345 time_of_last_received_packet_
= clock_
->Now();
1346 DVLOG(1) << ENDPOINT
<< "time of last received packet: "
1347 << time_of_last_received_packet_
.ToDebuggingValue();
1349 if (perspective_
== Perspective::IS_SERVER
&&
1350 encryption_level_
== ENCRYPTION_NONE
&&
1351 last_size_
> packet_generator_
.max_packet_length()) {
1352 set_max_packet_length(last_size_
);
1357 void QuicConnection::WriteQueuedPackets() {
1358 DCHECK(!writer_
->IsWriteBlocked());
1360 if (pending_version_negotiation_packet_
) {
1361 SendVersionNegotiationPacket();
1364 QueuedPacketList::iterator packet_iterator
= queued_packets_
.begin();
1365 while (packet_iterator
!= queued_packets_
.end() &&
1366 WritePacket(&(*packet_iterator
))) {
1367 packet_iterator
= queued_packets_
.erase(packet_iterator
);
1371 void QuicConnection::WritePendingRetransmissions() {
1372 // Keep writing as long as there's a pending retransmission which can be
1374 while (sent_packet_manager_
.HasPendingRetransmissions()) {
1375 const QuicSentPacketManager::PendingRetransmission pending
=
1376 sent_packet_manager_
.NextPendingRetransmission();
1377 if (!CanWrite(HAS_RETRANSMITTABLE_DATA
)) {
1381 // Re-packetize the frames with a new sequence number for retransmission.
1382 // Retransmitted data packets do not use FEC, even when it's enabled.
1383 // Retransmitted packets use the same sequence number length as the
1385 // Flush the packet generator before making a new packet.
1386 // TODO(ianswett): Implement ReserializeAllFrames as a separate path that
1387 // does not require the creator to be flushed.
1388 packet_generator_
.FlushAllQueuedFrames();
1389 char buffer
[kMaxPacketSize
];
1390 SerializedPacket serialized_packet
= packet_generator_
.ReserializeAllFrames(
1391 pending
.retransmittable_frames
, pending
.sequence_number_length
, buffer
,
1393 if (serialized_packet
.packet
== nullptr) {
1394 // We failed to serialize the packet, so close the connection.
1395 // CloseConnection does not send close packet, so no infinite loop here.
1396 CloseConnection(QUIC_ENCRYPTION_FAILURE
, false);
1400 DVLOG(1) << ENDPOINT
<< "Retransmitting " << pending
.sequence_number
1401 << " as " << serialized_packet
.sequence_number
;
1403 QueuedPacket(serialized_packet
,
1404 pending
.retransmittable_frames
.encryption_level(),
1405 pending
.transmission_type
,
1406 pending
.sequence_number
));
1410 void QuicConnection::RetransmitUnackedPackets(
1411 TransmissionType retransmission_type
) {
1412 sent_packet_manager_
.RetransmitUnackedPackets(retransmission_type
);
1414 WriteIfNotBlocked();
1417 void QuicConnection::NeuterUnencryptedPackets() {
1418 sent_packet_manager_
.NeuterUnencryptedPackets();
1419 // This may have changed the retransmission timer, so re-arm it.
1420 QuicTime retransmission_time
= sent_packet_manager_
.GetRetransmissionTime();
1421 retransmission_alarm_
->Update(retransmission_time
,
1422 QuicTime::Delta::FromMilliseconds(1));
1425 bool QuicConnection::ShouldGeneratePacket(
1426 HasRetransmittableData retransmittable
,
1427 IsHandshake handshake
) {
1428 // We should serialize handshake packets immediately to ensure that they
1429 // end up sent at the right encryption level.
1430 if (handshake
== IS_HANDSHAKE
) {
1434 return CanWrite(retransmittable
);
1437 bool QuicConnection::CanWrite(HasRetransmittableData retransmittable
) {
1442 if (writer_
->IsWriteBlocked()) {
1443 visitor_
->OnWriteBlocked();
1447 QuicTime now
= clock_
->Now();
1448 QuicTime::Delta delay
= sent_packet_manager_
.TimeUntilSend(
1449 now
, retransmittable
);
1450 if (delay
.IsInfinite()) {
1451 send_alarm_
->Cancel();
1455 // If the scheduler requires a delay, then we can not send this packet now.
1456 if (!delay
.IsZero()) {
1457 send_alarm_
->Update(now
.Add(delay
), QuicTime::Delta::FromMilliseconds(1));
1458 DVLOG(1) << ENDPOINT
<< "Delaying sending " << delay
.ToMilliseconds()
1462 send_alarm_
->Cancel();
1466 bool QuicConnection::WritePacket(QueuedPacket
* packet
) {
1467 if (!WritePacketInner(packet
)) {
1470 delete packet
->serialized_packet
.retransmittable_frames
;
1471 delete packet
->serialized_packet
.packet
;
1472 packet
->serialized_packet
.retransmittable_frames
= nullptr;
1473 packet
->serialized_packet
.packet
= nullptr;
1477 bool QuicConnection::WritePacketInner(QueuedPacket
* packet
) {
1478 if (ShouldDiscardPacket(*packet
)) {
1479 ++stats_
.packets_discarded
;
1482 // Connection close packets are encrypted and saved, so don't exit early.
1483 const bool is_connection_close
= IsConnectionClose(*packet
);
1484 if (writer_
->IsWriteBlocked() && !is_connection_close
) {
1488 QuicPacketSequenceNumber sequence_number
=
1489 packet
->serialized_packet
.sequence_number
;
1490 DCHECK_LE(sequence_number_of_last_sent_packet_
, sequence_number
);
1491 sequence_number_of_last_sent_packet_
= sequence_number
;
1493 QuicEncryptedPacket
* encrypted
= packet
->serialized_packet
.packet
;
1494 // Connection close packets are eventually owned by TimeWaitListManager.
1495 // Others are deleted at the end of this call.
1496 if (is_connection_close
) {
1497 DCHECK(connection_close_packet_
.get() == nullptr);
1498 // Clone the packet so it's owned in the future.
1499 connection_close_packet_
.reset(encrypted
->Clone());
1500 // This assures we won't try to write *forced* packets when blocked.
1501 // Return true to stop processing.
1502 if (writer_
->IsWriteBlocked()) {
1503 visitor_
->OnWriteBlocked();
1508 if (!FLAGS_quic_allow_oversized_packets_for_test
) {
1509 DCHECK_LE(encrypted
->length(), kMaxPacketSize
);
1511 DCHECK_LE(encrypted
->length(), packet_generator_
.max_packet_length());
1512 DVLOG(1) << ENDPOINT
<< "Sending packet " << sequence_number
<< " : "
1513 << (packet
->serialized_packet
.is_fec_packet
1515 : (IsRetransmittable(*packet
) == HAS_RETRANSMITTABLE_DATA
1517 : " ack only ")) << ", encryption level: "
1518 << QuicUtils::EncryptionLevelToString(packet
->encryption_level
)
1519 << ", encrypted length:" << encrypted
->length();
1520 DVLOG(2) << ENDPOINT
<< "packet(" << sequence_number
<< "): " << std::endl
1521 << QuicUtils::StringToHexASCIIDump(encrypted
->AsStringPiece());
1523 // Measure the RTT from before the write begins to avoid underestimating the
1524 // min_rtt_, especially in cases where the thread blocks or gets swapped out
1525 // during the WritePacket below.
1526 QuicTime packet_send_time
= clock_
->Now();
1527 WriteResult result
= writer_
->WritePacket(encrypted
->data(),
1528 encrypted
->length(),
1529 self_address().address(),
1531 if (result
.error_code
== ERR_IO_PENDING
) {
1532 DCHECK_EQ(WRITE_STATUS_BLOCKED
, result
.status
);
1535 if (result
.status
== WRITE_STATUS_BLOCKED
) {
1536 visitor_
->OnWriteBlocked();
1537 // If the socket buffers the the data, then the packet should not
1538 // be queued and sent again, which would result in an unnecessary
1539 // duplicate packet being sent. The helper must call OnCanWrite
1540 // when the write completes, and OnWriteError if an error occurs.
1541 if (!writer_
->IsWriteBlockedDataBuffered()) {
1545 if (result
.status
!= WRITE_STATUS_ERROR
&& debug_visitor_
!= nullptr) {
1546 // Pass the write result to the visitor.
1547 debug_visitor_
->OnPacketSent(packet
->serialized_packet
,
1548 packet
->original_sequence_number
,
1549 packet
->encryption_level
,
1550 packet
->transmission_type
,
1554 if (packet
->transmission_type
== NOT_RETRANSMISSION
) {
1555 time_of_last_sent_new_packet_
= packet_send_time
;
1558 MaybeSetFecAlarm(sequence_number
);
1559 DVLOG(1) << ENDPOINT
<< "time we began writing last sent packet: "
1560 << packet_send_time
.ToDebuggingValue();
1562 // TODO(ianswett): Change the sequence number length and other packet creator
1563 // options by a more explicit API than setting a struct value directly,
1564 // perhaps via the NetworkChangeVisitor.
1565 packet_generator_
.UpdateSequenceNumberLength(
1566 sent_packet_manager_
.least_packet_awaited_by_peer(),
1567 sent_packet_manager_
.EstimateMaxPacketsInFlight(max_packet_length()));
1569 bool reset_retransmission_alarm
= sent_packet_manager_
.OnPacketSent(
1570 &packet
->serialized_packet
,
1571 packet
->original_sequence_number
,
1573 encrypted
->length(),
1574 packet
->transmission_type
,
1575 IsRetransmittable(*packet
));
1577 if (reset_retransmission_alarm
|| !retransmission_alarm_
->IsSet()) {
1578 retransmission_alarm_
->Update(sent_packet_manager_
.GetRetransmissionTime(),
1579 QuicTime::Delta::FromMilliseconds(1));
1582 stats_
.bytes_sent
+= result
.bytes_written
;
1583 ++stats_
.packets_sent
;
1584 if (packet
->transmission_type
!= NOT_RETRANSMISSION
) {
1585 stats_
.bytes_retransmitted
+= result
.bytes_written
;
1586 ++stats_
.packets_retransmitted
;
1589 if (result
.status
== WRITE_STATUS_ERROR
) {
1590 OnWriteError(result
.error_code
);
1591 DLOG(ERROR
) << ENDPOINT
<< "failed writing " << encrypted
->length()
1593 << " from host " << self_address().ToStringWithoutPort()
1594 << " to address " << peer_address().ToString();
1601 bool QuicConnection::ShouldDiscardPacket(const QueuedPacket
& packet
) {
1603 DVLOG(1) << ENDPOINT
1604 << "Not sending packet as connection is disconnected.";
1608 QuicPacketSequenceNumber sequence_number
=
1609 packet
.serialized_packet
.sequence_number
;
1610 if (encryption_level_
== ENCRYPTION_FORWARD_SECURE
&&
1611 packet
.encryption_level
== ENCRYPTION_NONE
) {
1612 // Drop packets that are NULL encrypted since the peer won't accept them
1614 DVLOG(1) << ENDPOINT
<< "Dropping NULL encrypted packet: "
1615 << sequence_number
<< " since the connection is forward secure.";
1619 // If a retransmission has been acked before sending, don't send it.
1620 // This occurs if a packet gets serialized, queued, then discarded.
1621 if (packet
.transmission_type
!= NOT_RETRANSMISSION
&&
1622 (!sent_packet_manager_
.IsUnacked(packet
.original_sequence_number
) ||
1623 !sent_packet_manager_
.HasRetransmittableFrames(
1624 packet
.original_sequence_number
))) {
1625 DVLOG(1) << ENDPOINT
<< "Dropping unacked packet: " << sequence_number
1626 << " A previous transmission was acked while write blocked.";
1633 void QuicConnection::OnWriteError(int error_code
) {
1634 DVLOG(1) << ENDPOINT
<< "Write failed with error: " << error_code
1635 << " (" << ErrorToString(error_code
) << ")";
1636 // We can't send an error as the socket is presumably borked.
1637 CloseConnection(QUIC_PACKET_WRITE_ERROR
, false);
1640 void QuicConnection::OnSerializedPacket(
1641 const SerializedPacket
& serialized_packet
) {
1642 if (serialized_packet
.packet
== nullptr) {
1643 // We failed to serialize the packet, so close the connection.
1644 // CloseConnection does not send close packet, so no infinite loop here.
1645 CloseConnection(QUIC_ENCRYPTION_FAILURE
, false);
1648 if (serialized_packet
.retransmittable_frames
) {
1649 sent_packet_manager_
.OnSerializedPacket(serialized_packet
);
1651 if (serialized_packet
.is_fec_packet
&& fec_alarm_
->IsSet()) {
1652 // If an FEC packet is serialized with the FEC alarm set, cancel the alarm.
1653 fec_alarm_
->Cancel();
1655 SendOrQueuePacket(QueuedPacket(serialized_packet
, encryption_level_
));
1658 void QuicConnection::OnResetFecGroup() {
1659 if (!fec_alarm_
->IsSet()) {
1662 // If an FEC Group is closed with the FEC alarm set, cancel the alarm.
1663 fec_alarm_
->Cancel();
1666 void QuicConnection::OnCongestionWindowChange() {
1667 packet_generator_
.OnCongestionWindowChange(
1668 sent_packet_manager_
.EstimateMaxPacketsInFlight(max_packet_length()));
1669 visitor_
->OnCongestionWindowChange(clock_
->ApproximateNow());
1672 void QuicConnection::OnRttChange() {
1673 // Uses the connection's smoothed RTT. If zero, uses initial_rtt.
1674 QuicTime::Delta rtt
= sent_packet_manager_
.GetRttStats()->smoothed_rtt();
1676 rtt
= QuicTime::Delta::FromMicroseconds(
1677 sent_packet_manager_
.GetRttStats()->initial_rtt_us());
1679 packet_generator_
.OnRttChange(rtt
);
1682 void QuicConnection::OnHandshakeComplete() {
1683 sent_packet_manager_
.SetHandshakeConfirmed();
1684 // The client should immediately ack the SHLO to confirm the handshake is
1685 // complete with the server.
1686 if (perspective_
== Perspective::IS_CLIENT
&& !ack_queued_
) {
1687 ack_alarm_
->Cancel();
1688 ack_alarm_
->Set(clock_
->ApproximateNow());
1692 void QuicConnection::SendOrQueuePacket(QueuedPacket packet
) {
1693 // The caller of this function is responsible for checking CanWrite().
1694 if (packet
.serialized_packet
.packet
== nullptr) {
1696 << "packet.serialized_packet.packet == nullptr in to SendOrQueuePacket";
1700 sent_entropy_manager_
.RecordPacketEntropyHash(
1701 packet
.serialized_packet
.sequence_number
,
1702 packet
.serialized_packet
.entropy_hash
);
1703 if (!WritePacket(&packet
)) {
1704 // Take ownership of the underlying encrypted packet.
1705 if (!packet
.serialized_packet
.packet
->owns_buffer()) {
1706 scoped_ptr
<QuicEncryptedPacket
> encrypted_deleter(
1707 packet
.serialized_packet
.packet
);
1708 packet
.serialized_packet
.packet
=
1709 packet
.serialized_packet
.packet
->Clone();
1711 queued_packets_
.push_back(packet
);
1714 // If a forward-secure encrypter is available but is not being used and the
1715 // next sequence number is the first packet which requires
1716 // forward security, start using the forward-secure encrypter.
1717 if (encryption_level_
!= ENCRYPTION_FORWARD_SECURE
&&
1718 has_forward_secure_encrypter_
&&
1719 packet
.serialized_packet
.sequence_number
>=
1720 first_required_forward_secure_packet_
- 1) {
1721 SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE
);
1725 void QuicConnection::SendPing() {
1726 if (retransmission_alarm_
->IsSet()) {
1729 packet_generator_
.AddControlFrame(QuicFrame(new QuicPingFrame
));
1732 void QuicConnection::SendAck() {
1733 ack_alarm_
->Cancel();
1734 stop_waiting_count_
= 0;
1735 num_packets_received_since_last_ack_sent_
= 0;
1737 packet_generator_
.SetShouldSendAck(true);
1740 void QuicConnection::OnRetransmissionTimeout() {
1741 if (!sent_packet_manager_
.HasUnackedPackets()) {
1745 sent_packet_manager_
.OnRetransmissionTimeout();
1746 WriteIfNotBlocked();
1748 // A write failure can result in the connection being closed, don't attempt to
1749 // write further packets, or to set alarms.
1754 // In the TLP case, the SentPacketManager gives the connection the opportunity
1755 // to send new data before retransmitting.
1756 if (sent_packet_manager_
.MaybeRetransmitTailLossProbe()) {
1757 // Send the pending retransmission now that it's been queued.
1758 WriteIfNotBlocked();
1761 // Ensure the retransmission alarm is always set if there are unacked packets
1762 // and nothing waiting to be sent.
1763 if (!HasQueuedData() && !retransmission_alarm_
->IsSet()) {
1764 QuicTime rto_timeout
= sent_packet_manager_
.GetRetransmissionTime();
1765 if (rto_timeout
.IsInitialized()) {
1766 retransmission_alarm_
->Set(rto_timeout
);
1771 void QuicConnection::SetEncrypter(EncryptionLevel level
,
1772 QuicEncrypter
* encrypter
) {
1773 packet_generator_
.SetEncrypter(level
, encrypter
);
1774 if (level
== ENCRYPTION_FORWARD_SECURE
) {
1775 has_forward_secure_encrypter_
= true;
1776 first_required_forward_secure_packet_
=
1777 sequence_number_of_last_sent_packet_
+
1778 // 3 times the current congestion window (in slow start) should cover
1779 // about two full round trips worth of packets, which should be
1781 3 * sent_packet_manager_
.EstimateMaxPacketsInFlight(
1782 max_packet_length());
1786 void QuicConnection::SetDefaultEncryptionLevel(EncryptionLevel level
) {
1787 encryption_level_
= level
;
1788 packet_generator_
.set_encryption_level(level
);
1791 void QuicConnection::SetDecrypter(QuicDecrypter
* decrypter
,
1792 EncryptionLevel level
) {
1793 framer_
.SetDecrypter(decrypter
, level
);
1796 void QuicConnection::SetAlternativeDecrypter(QuicDecrypter
* decrypter
,
1797 EncryptionLevel level
,
1798 bool latch_once_used
) {
1799 framer_
.SetAlternativeDecrypter(decrypter
, level
, latch_once_used
);
1802 const QuicDecrypter
* QuicConnection::decrypter() const {
1803 return framer_
.decrypter();
1806 const QuicDecrypter
* QuicConnection::alternative_decrypter() const {
1807 return framer_
.alternative_decrypter();
1810 void QuicConnection::QueueUndecryptablePacket(
1811 const QuicEncryptedPacket
& packet
) {
1812 DVLOG(1) << ENDPOINT
<< "Queueing undecryptable packet.";
1813 undecryptable_packets_
.push_back(packet
.Clone());
1816 void QuicConnection::MaybeProcessUndecryptablePackets() {
1817 if (undecryptable_packets_
.empty() || encryption_level_
== ENCRYPTION_NONE
) {
1821 while (connected_
&& !undecryptable_packets_
.empty()) {
1822 DVLOG(1) << ENDPOINT
<< "Attempting to process undecryptable packet";
1823 QuicEncryptedPacket
* packet
= undecryptable_packets_
.front();
1824 if (!framer_
.ProcessPacket(*packet
) &&
1825 framer_
.error() == QUIC_DECRYPTION_FAILURE
) {
1826 DVLOG(1) << ENDPOINT
<< "Unable to process undecryptable packet...";
1829 DVLOG(1) << ENDPOINT
<< "Processed undecryptable packet!";
1830 ++stats_
.packets_processed
;
1832 undecryptable_packets_
.pop_front();
1835 // Once forward secure encryption is in use, there will be no
1836 // new keys installed and hence any undecryptable packets will
1837 // never be able to be decrypted.
1838 if (encryption_level_
== ENCRYPTION_FORWARD_SECURE
) {
1839 if (debug_visitor_
!= nullptr) {
1840 // TODO(rtenneti): perhaps more efficient to pass the number of
1841 // undecryptable packets as the argument to OnUndecryptablePacket so that
1842 // we just need to call OnUndecryptablePacket once?
1843 for (size_t i
= 0; i
< undecryptable_packets_
.size(); ++i
) {
1844 debug_visitor_
->OnUndecryptablePacket();
1847 STLDeleteElements(&undecryptable_packets_
);
1851 void QuicConnection::MaybeProcessRevivedPacket() {
1852 QuicFecGroup
* group
= GetFecGroup();
1853 if (!connected_
|| group
== nullptr || !group
->CanRevive()) {
1856 QuicPacketHeader revived_header
;
1857 char revived_payload
[kMaxPacketSize
];
1858 size_t len
= group
->Revive(&revived_header
, revived_payload
, kMaxPacketSize
);
1859 revived_header
.public_header
.connection_id
= connection_id_
;
1860 revived_header
.public_header
.connection_id_length
=
1861 last_header_
.public_header
.connection_id_length
;
1862 revived_header
.public_header
.version_flag
= false;
1863 revived_header
.public_header
.reset_flag
= false;
1864 revived_header
.public_header
.sequence_number_length
=
1865 last_header_
.public_header
.sequence_number_length
;
1866 revived_header
.fec_flag
= false;
1867 revived_header
.is_in_fec_group
= NOT_IN_FEC_GROUP
;
1868 revived_header
.fec_group
= 0;
1869 group_map_
.erase(last_header_
.fec_group
);
1870 last_decrypted_packet_level_
= group
->effective_encryption_level();
1871 DCHECK_LT(last_decrypted_packet_level_
, NUM_ENCRYPTION_LEVELS
);
1874 last_packet_revived_
= true;
1875 if (debug_visitor_
!= nullptr) {
1876 debug_visitor_
->OnRevivedPacket(revived_header
,
1877 StringPiece(revived_payload
, len
));
1880 ++stats_
.packets_revived
;
1881 framer_
.ProcessRevivedPacket(&revived_header
,
1882 StringPiece(revived_payload
, len
));
1885 QuicFecGroup
* QuicConnection::GetFecGroup() {
1886 QuicFecGroupNumber fec_group_num
= last_header_
.fec_group
;
1887 if (fec_group_num
== 0) {
1890 if (!ContainsKey(group_map_
, fec_group_num
)) {
1891 if (group_map_
.size() >= kMaxFecGroups
) { // Too many groups
1892 if (fec_group_num
< group_map_
.begin()->first
) {
1893 // The group being requested is a group we've seen before and deleted.
1894 // Don't recreate it.
1897 // Clear the lowest group number.
1898 delete group_map_
.begin()->second
;
1899 group_map_
.erase(group_map_
.begin());
1901 group_map_
[fec_group_num
] = new QuicFecGroup();
1903 return group_map_
[fec_group_num
];
1906 void QuicConnection::SendConnectionClose(QuicErrorCode error
) {
1907 SendConnectionCloseWithDetails(error
, string());
1910 void QuicConnection::SendConnectionCloseWithDetails(QuicErrorCode error
,
1911 const string
& details
) {
1912 // If we're write blocked, WritePacket() will not send, but will capture the
1913 // serialized packet.
1914 SendConnectionClosePacket(error
, details
);
1915 CloseConnection(error
, false);
1918 void QuicConnection::SendConnectionClosePacket(QuicErrorCode error
,
1919 const string
& details
) {
1920 DVLOG(1) << ENDPOINT
<< "Force closing " << connection_id()
1921 << " with error " << QuicUtils::ErrorToString(error
)
1922 << " (" << error
<< ") " << details
;
1923 // Don't send explicit connection close packets for timeouts.
1924 // This is particularly important on mobile, where connections are short.
1925 if (silent_close_enabled_
&&
1926 error
== QuicErrorCode::QUIC_CONNECTION_TIMED_OUT
) {
1929 ScopedPacketBundler
ack_bundler(this, SEND_ACK
);
1930 QuicConnectionCloseFrame
* frame
= new QuicConnectionCloseFrame();
1931 frame
->error_code
= error
;
1932 frame
->error_details
= details
;
1933 packet_generator_
.AddControlFrame(QuicFrame(frame
));
1934 packet_generator_
.FlushAllQueuedFrames();
1937 void QuicConnection::CloseConnection(QuicErrorCode error
, bool from_peer
) {
1939 DVLOG(1) << "Connection is already closed.";
1943 if (debug_visitor_
!= nullptr) {
1944 debug_visitor_
->OnConnectionClosed(error
, from_peer
);
1946 DCHECK(visitor_
!= nullptr);
1947 visitor_
->OnConnectionClosed(error
, from_peer
);
1948 // Cancel the alarms so they don't trigger any action now that the
1949 // connection is closed.
1950 ack_alarm_
->Cancel();
1951 ping_alarm_
->Cancel();
1952 fec_alarm_
->Cancel();
1953 resume_writes_alarm_
->Cancel();
1954 retransmission_alarm_
->Cancel();
1955 send_alarm_
->Cancel();
1956 timeout_alarm_
->Cancel();
1959 void QuicConnection::SendGoAway(QuicErrorCode error
,
1960 QuicStreamId last_good_stream_id
,
1961 const string
& reason
) {
1962 DVLOG(1) << ENDPOINT
<< "Going away with error "
1963 << QuicUtils::ErrorToString(error
)
1964 << " (" << error
<< ")";
1966 // Opportunistically bundle an ack with this outgoing packet.
1967 ScopedPacketBundler
ack_bundler(this, BUNDLE_PENDING_ACK
);
1968 packet_generator_
.AddControlFrame(
1969 QuicFrame(new QuicGoAwayFrame(error
, last_good_stream_id
, reason
)));
1972 void QuicConnection::CloseFecGroupsBefore(
1973 QuicPacketSequenceNumber sequence_number
) {
1974 FecGroupMap::iterator it
= group_map_
.begin();
1975 while (it
!= group_map_
.end()) {
1976 // If this is the current group or the group doesn't protect this packet
1977 // we can ignore it.
1978 if (last_header_
.fec_group
== it
->first
||
1979 !it
->second
->ProtectsPacketsBefore(sequence_number
)) {
1983 QuicFecGroup
* fec_group
= it
->second
;
1984 DCHECK(!fec_group
->CanRevive());
1985 FecGroupMap::iterator next
= it
;
1987 group_map_
.erase(it
);
1993 QuicByteCount
QuicConnection::max_packet_length() const {
1994 return packet_generator_
.max_packet_length();
1997 void QuicConnection::set_max_packet_length(QuicByteCount length
) {
1998 return packet_generator_
.set_max_packet_length(length
);
2001 bool QuicConnection::HasQueuedData() const {
2002 return pending_version_negotiation_packet_
||
2003 !queued_packets_
.empty() || packet_generator_
.HasQueuedFrames();
2006 bool QuicConnection::CanWriteStreamData() {
2007 // Don't write stream data if there are negotiation or queued data packets
2008 // to send. Otherwise, continue and bundle as many frames as possible.
2009 if (pending_version_negotiation_packet_
|| !queued_packets_
.empty()) {
2013 IsHandshake pending_handshake
= visitor_
->HasPendingHandshake() ?
2014 IS_HANDSHAKE
: NOT_HANDSHAKE
;
2015 // Sending queued packets may have caused the socket to become write blocked,
2016 // or the congestion manager to prohibit sending. If we've sent everything
2017 // we had queued and we're still not blocked, let the visitor know it can
2019 return ShouldGeneratePacket(HAS_RETRANSMITTABLE_DATA
, pending_handshake
);
2022 void QuicConnection::SetNetworkTimeouts(QuicTime::Delta overall_timeout
,
2023 QuicTime::Delta idle_timeout
) {
2024 LOG_IF(DFATAL
, idle_timeout
> overall_timeout
)
2025 << "idle_timeout:" << idle_timeout
.ToMilliseconds()
2026 << " overall_timeout:" << overall_timeout
.ToMilliseconds();
2027 // Adjust the idle timeout on client and server to prevent clients from
2028 // sending requests to servers which have already closed the connection.
2029 if (perspective_
== Perspective::IS_SERVER
) {
2030 idle_timeout
= idle_timeout
.Add(QuicTime::Delta::FromSeconds(3));
2031 } else if (idle_timeout
> QuicTime::Delta::FromSeconds(1)) {
2032 idle_timeout
= idle_timeout
.Subtract(QuicTime::Delta::FromSeconds(1));
2034 overall_connection_timeout_
= overall_timeout
;
2035 idle_network_timeout_
= idle_timeout
;
2040 void QuicConnection::CheckForTimeout() {
2041 QuicTime now
= clock_
->ApproximateNow();
2042 QuicTime time_of_last_packet
= max(time_of_last_received_packet_
,
2043 time_of_last_sent_new_packet_
);
2045 // |delta| can be < 0 as |now| is approximate time but |time_of_last_packet|
2046 // is accurate time. However, this should not change the behavior of
2047 // timeout handling.
2048 QuicTime::Delta idle_duration
= now
.Subtract(time_of_last_packet
);
2049 DVLOG(1) << ENDPOINT
<< "last packet "
2050 << time_of_last_packet
.ToDebuggingValue()
2051 << " now:" << now
.ToDebuggingValue()
2052 << " idle_duration:" << idle_duration
.ToMicroseconds()
2053 << " idle_network_timeout: "
2054 << idle_network_timeout_
.ToMicroseconds();
2055 if (idle_duration
>= idle_network_timeout_
) {
2056 DVLOG(1) << ENDPOINT
<< "Connection timedout due to no network activity.";
2057 SendConnectionClose(QUIC_CONNECTION_TIMED_OUT
);
2061 if (!overall_connection_timeout_
.IsInfinite()) {
2062 QuicTime::Delta connected_duration
=
2063 now
.Subtract(stats_
.connection_creation_time
);
2064 DVLOG(1) << ENDPOINT
<< "connection time: "
2065 << connected_duration
.ToMicroseconds() << " overall timeout: "
2066 << overall_connection_timeout_
.ToMicroseconds();
2067 if (connected_duration
>= overall_connection_timeout_
) {
2068 DVLOG(1) << ENDPOINT
<<
2069 "Connection timedout due to overall connection timeout.";
2070 SendConnectionClose(QUIC_CONNECTION_OVERALL_TIMED_OUT
);
2078 void QuicConnection::SetTimeoutAlarm() {
2079 QuicTime time_of_last_packet
= max(time_of_last_received_packet_
,
2080 time_of_last_sent_new_packet_
);
2082 QuicTime deadline
= time_of_last_packet
.Add(idle_network_timeout_
);
2083 if (!overall_connection_timeout_
.IsInfinite()) {
2084 deadline
= min(deadline
,
2085 stats_
.connection_creation_time
.Add(
2086 overall_connection_timeout_
));
2089 timeout_alarm_
->Cancel();
2090 timeout_alarm_
->Set(deadline
);
2093 void QuicConnection::SetPingAlarm() {
2094 if (perspective_
== Perspective::IS_SERVER
) {
2095 // Only clients send pings.
2098 if (!visitor_
->HasOpenDataStreams()) {
2099 ping_alarm_
->Cancel();
2100 // Don't send a ping unless there are open streams.
2103 QuicTime::Delta ping_timeout
= QuicTime::Delta::FromSeconds(kPingTimeoutSecs
);
2104 ping_alarm_
->Update(clock_
->ApproximateNow().Add(ping_timeout
),
2105 QuicTime::Delta::FromSeconds(1));
2108 QuicConnection::ScopedPacketBundler::ScopedPacketBundler(
2109 QuicConnection
* connection
,
2110 AckBundling send_ack
)
2111 : connection_(connection
),
2112 already_in_batch_mode_(connection
!= nullptr &&
2113 connection
->packet_generator_
.InBatchMode()) {
2114 if (connection_
== nullptr) {
2117 // Move generator into batch mode. If caller wants us to include an ack,
2118 // check the delayed-ack timer to see if there's ack info to be sent.
2119 if (!already_in_batch_mode_
) {
2120 DVLOG(1) << "Entering Batch Mode.";
2121 connection_
->packet_generator_
.StartBatchOperations();
2123 // Bundle an ack if the alarm is set or with every second packet if we need to
2124 // raise the peer's least unacked.
2126 connection_
->ack_alarm_
->IsSet() || connection_
->stop_waiting_count_
> 1;
2127 if (send_ack
== SEND_ACK
|| (send_ack
== BUNDLE_PENDING_ACK
&& ack_pending
)) {
2128 DVLOG(1) << "Bundling ack with outgoing packet.";
2129 connection_
->SendAck();
2133 QuicConnection::ScopedPacketBundler::~ScopedPacketBundler() {
2134 if (connection_
== nullptr) {
2137 // If we changed the generator's batch state, restore original batch state.
2138 if (!already_in_batch_mode_
) {
2139 DVLOG(1) << "Leaving Batch Mode.";
2140 connection_
->packet_generator_
.FinishBatchOperations();
2142 DCHECK_EQ(already_in_batch_mode_
,
2143 connection_
->packet_generator_
.InBatchMode());
2146 HasRetransmittableData
QuicConnection::IsRetransmittable(
2147 const QueuedPacket
& packet
) {
2148 // Retransmitted packets retransmittable frames are owned by the unacked
2149 // packet map, but are not present in the serialized packet.
2150 if (packet
.transmission_type
!= NOT_RETRANSMISSION
||
2151 packet
.serialized_packet
.retransmittable_frames
!= nullptr) {
2152 return HAS_RETRANSMITTABLE_DATA
;
2154 return NO_RETRANSMITTABLE_DATA
;
2158 bool QuicConnection::IsConnectionClose(const QueuedPacket
& packet
) {
2159 const RetransmittableFrames
* retransmittable_frames
=
2160 packet
.serialized_packet
.retransmittable_frames
;
2161 if (retransmittable_frames
== nullptr) {
2164 for (const QuicFrame
& frame
: retransmittable_frames
->frames()) {
2165 if (frame
.type
== CONNECTION_CLOSE_FRAME
) {