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/memory/ref_counted.h"
21 #include "base/profiler/scoped_tracker.h"
22 #include "base/stl_util.h"
23 #include "base/strings/stringprintf.h"
24 #include "net/base/net_errors.h"
25 #include "net/quic/crypto/crypto_protocol.h"
26 #include "net/quic/crypto/quic_decrypter.h"
27 #include "net/quic/crypto/quic_encrypter.h"
28 #include "net/quic/proto/cached_network_parameters.pb.h"
29 #include "net/quic/quic_bandwidth.h"
30 #include "net/quic/quic_config.h"
31 #include "net/quic/quic_fec_group.h"
32 #include "net/quic/quic_flags.h"
33 #include "net/quic/quic_packet_generator.h"
34 #include "net/quic/quic_utils.h"
36 using base::StringPiece
;
37 using base::StringPrintf
;
44 using std::numeric_limits
;
56 // The largest gap in packets we'll accept without closing the connection.
57 // This will likely have to be tuned.
58 const QuicPacketSequenceNumber kMaxPacketGap
= 5000;
60 // Limit the number of FEC groups to two. If we get enough out of order packets
61 // that this becomes limiting, we can revisit.
62 const size_t kMaxFecGroups
= 2;
64 // Maximum number of acks received before sending an ack in response.
65 const QuicPacketCount kMaxPacketsReceivedBeforeAckSend
= 20;
67 bool Near(QuicPacketSequenceNumber a
, QuicPacketSequenceNumber b
) {
68 QuicPacketSequenceNumber delta
= (a
> b
) ? a
- b
: b
- a
;
69 return delta
<= kMaxPacketGap
;
72 // An alarm that is scheduled to send an ack if a timeout occurs.
73 class AckAlarm
: public QuicAlarm::Delegate
{
75 explicit AckAlarm(QuicConnection
* connection
)
76 : connection_(connection
) {
79 QuicTime
OnAlarm() override
{
80 connection_
->SendAck();
81 return QuicTime::Zero();
85 QuicConnection
* connection_
;
87 DISALLOW_COPY_AND_ASSIGN(AckAlarm
);
90 // This alarm will be scheduled any time a data-bearing packet is sent out.
91 // When the alarm goes off, the connection checks to see if the oldest packets
92 // have been acked, and retransmit them if they have not.
93 class RetransmissionAlarm
: public QuicAlarm::Delegate
{
95 explicit RetransmissionAlarm(QuicConnection
* connection
)
96 : connection_(connection
) {
99 QuicTime
OnAlarm() override
{
100 connection_
->OnRetransmissionTimeout();
101 return QuicTime::Zero();
105 QuicConnection
* connection_
;
107 DISALLOW_COPY_AND_ASSIGN(RetransmissionAlarm
);
110 // An alarm that is scheduled when the SentPacketManager requires a delay
111 // before sending packets and fires when the packet may be sent.
112 class SendAlarm
: public QuicAlarm::Delegate
{
114 explicit SendAlarm(QuicConnection
* connection
)
115 : connection_(connection
) {
118 QuicTime
OnAlarm() override
{
119 connection_
->WriteIfNotBlocked();
120 // Never reschedule the alarm, since CanWrite does that.
121 return QuicTime::Zero();
125 QuicConnection
* connection_
;
127 DISALLOW_COPY_AND_ASSIGN(SendAlarm
);
130 class TimeoutAlarm
: public QuicAlarm::Delegate
{
132 explicit TimeoutAlarm(QuicConnection
* connection
)
133 : connection_(connection
) {
136 QuicTime
OnAlarm() override
{
137 connection_
->CheckForTimeout();
138 // Never reschedule the alarm, since CheckForTimeout does that.
139 return QuicTime::Zero();
143 QuicConnection
* connection_
;
145 DISALLOW_COPY_AND_ASSIGN(TimeoutAlarm
);
148 class PingAlarm
: public QuicAlarm::Delegate
{
150 explicit PingAlarm(QuicConnection
* connection
)
151 : connection_(connection
) {
154 QuicTime
OnAlarm() override
{
155 connection_
->SendPing();
156 return QuicTime::Zero();
160 QuicConnection
* connection_
;
162 DISALLOW_COPY_AND_ASSIGN(PingAlarm
);
165 class MtuDiscoveryAlarm
: public QuicAlarm::Delegate
{
167 explicit MtuDiscoveryAlarm(QuicConnection
* connection
)
168 : connection_(connection
) {}
170 QuicTime
OnAlarm() override
{
171 connection_
->DiscoverMtu();
172 // DiscoverMtu() handles rescheduling the alarm by itself.
173 return QuicTime::Zero();
177 QuicConnection
* connection_
;
179 DISALLOW_COPY_AND_ASSIGN(MtuDiscoveryAlarm
);
182 // This alarm may be scheduled when an FEC protected packet is sent out.
183 class FecAlarm
: public QuicAlarm::Delegate
{
185 explicit FecAlarm(QuicPacketGenerator
* packet_generator
)
186 : packet_generator_(packet_generator
) {}
188 QuicTime
OnAlarm() override
{
189 packet_generator_
->OnFecTimeout();
190 return QuicTime::Zero();
194 QuicPacketGenerator
* packet_generator_
;
196 DISALLOW_COPY_AND_ASSIGN(FecAlarm
);
199 // Listens for acks of MTU discovery packets and raises the maximum packet size
200 // of the connection if the probe succeeds.
201 class MtuDiscoveryAckListener
: public QuicAckNotifier::DelegateInterface
{
203 MtuDiscoveryAckListener(QuicConnection
* connection
, QuicByteCount probe_size
)
204 : connection_(connection
), probe_size_(probe_size
) {}
206 void OnAckNotification(int /*num_retransmittable_packets*/,
207 int /*num_retransmittable_bytes*/,
208 QuicTime::Delta
/*delta_largest_observed*/) override
{
209 // Since the probe was successful, increase the maximum packet size to that.
210 if (probe_size_
> connection_
->max_packet_length()) {
211 connection_
->set_max_packet_length(probe_size_
);
216 // MtuDiscoveryAckListener is ref counted.
217 ~MtuDiscoveryAckListener() override
{}
220 QuicConnection
* connection_
;
221 QuicByteCount probe_size_
;
223 DISALLOW_COPY_AND_ASSIGN(MtuDiscoveryAckListener
);
228 QuicConnection::QueuedPacket::QueuedPacket(SerializedPacket packet
,
229 EncryptionLevel level
)
230 : serialized_packet(packet
),
231 encryption_level(level
),
232 transmission_type(NOT_RETRANSMISSION
),
233 original_sequence_number(0) {
236 QuicConnection::QueuedPacket::QueuedPacket(
237 SerializedPacket packet
,
238 EncryptionLevel level
,
239 TransmissionType transmission_type
,
240 QuicPacketSequenceNumber original_sequence_number
)
241 : serialized_packet(packet
),
242 encryption_level(level
),
243 transmission_type(transmission_type
),
244 original_sequence_number(original_sequence_number
) {
248 (perspective_ == Perspective::IS_SERVER ? "Server: " : "Client: ")
250 QuicConnection::QuicConnection(QuicConnectionId connection_id
,
252 QuicConnectionHelperInterface
* helper
,
253 const PacketWriterFactory
& writer_factory
,
255 Perspective perspective
,
257 const QuicVersionVector
& supported_versions
)
258 : framer_(supported_versions
,
259 helper
->GetClock()->ApproximateNow(),
262 writer_(writer_factory
.Create(this)),
263 owns_writer_(owns_writer
),
264 encryption_level_(ENCRYPTION_NONE
),
265 has_forward_secure_encrypter_(false),
266 first_required_forward_secure_packet_(0),
267 clock_(helper
->GetClock()),
268 random_generator_(helper
->GetRandomGenerator()),
269 connection_id_(connection_id
),
270 peer_address_(address
),
271 migrating_peer_port_(0),
272 last_packet_decrypted_(false),
273 last_packet_revived_(false),
275 last_decrypted_packet_level_(ENCRYPTION_NONE
),
276 should_last_packet_instigate_acks_(false),
277 largest_seen_packet_with_ack_(0),
278 largest_seen_packet_with_stop_waiting_(0),
279 max_undecryptable_packets_(0),
280 pending_version_negotiation_packet_(false),
281 silent_close_enabled_(false),
282 received_packet_manager_(&stats_
),
284 num_packets_received_since_last_ack_sent_(0),
285 stop_waiting_count_(0),
286 delay_setting_retransmission_alarm_(false),
287 pending_retransmission_alarm_(false),
288 ack_alarm_(helper
->CreateAlarm(new AckAlarm(this))),
289 retransmission_alarm_(helper
->CreateAlarm(new RetransmissionAlarm(this))),
290 send_alarm_(helper
->CreateAlarm(new SendAlarm(this))),
291 resume_writes_alarm_(helper
->CreateAlarm(new SendAlarm(this))),
292 timeout_alarm_(helper
->CreateAlarm(new TimeoutAlarm(this))),
293 ping_alarm_(helper
->CreateAlarm(new PingAlarm(this))),
294 mtu_discovery_alarm_(helper
->CreateAlarm(new MtuDiscoveryAlarm(this))),
296 debug_visitor_(nullptr),
297 packet_generator_(connection_id_
, &framer_
, random_generator_
, this),
298 fec_alarm_(helper
->CreateAlarm(new FecAlarm(&packet_generator_
))),
299 idle_network_timeout_(QuicTime::Delta::Infinite()),
300 overall_connection_timeout_(QuicTime::Delta::Infinite()),
301 time_of_last_received_packet_(clock_
->ApproximateNow()),
302 time_of_last_sent_new_packet_(clock_
->ApproximateNow()),
303 sequence_number_of_last_sent_packet_(0),
304 sent_packet_manager_(
308 FLAGS_quic_use_bbr_congestion_control
? kBBR
: kCubic
,
309 FLAGS_quic_use_time_loss_detection
? kTime
: kNack
,
311 version_negotiation_state_(START_NEGOTIATION
),
312 perspective_(perspective
),
314 peer_ip_changed_(false),
315 peer_port_changed_(false),
316 self_ip_changed_(false),
317 self_port_changed_(false),
318 can_truncate_connection_ids_(true),
319 is_secure_(is_secure
),
320 mtu_discovery_target_(0),
322 packets_between_mtu_probes_(kPacketsBetweenMtuProbesBase
),
323 next_mtu_probe_at_(kPacketsBetweenMtuProbesBase
),
324 largest_received_packet_size_(0) {
325 DVLOG(1) << ENDPOINT
<< "Created connection with connection_id: "
327 framer_
.set_visitor(this);
328 framer_
.set_received_entropy_calculator(&received_packet_manager_
);
329 stats_
.connection_creation_time
= clock_
->ApproximateNow();
330 sent_packet_manager_
.set_network_change_visitor(this);
331 if (perspective_
== Perspective::IS_SERVER
) {
332 set_max_packet_length(kDefaultServerMaxPacketSize
);
336 QuicConnection::~QuicConnection() {
340 STLDeleteElements(&undecryptable_packets_
);
341 STLDeleteValues(&group_map_
);
342 for (QueuedPacketList::iterator it
= queued_packets_
.begin();
343 it
!= queued_packets_
.end(); ++it
) {
344 delete it
->serialized_packet
.retransmittable_frames
;
345 delete it
->serialized_packet
.packet
;
349 void QuicConnection::SetFromConfig(const QuicConfig
& config
) {
350 if (config
.negotiated()) {
351 SetNetworkTimeouts(QuicTime::Delta::Infinite(),
352 config
.IdleConnectionStateLifetime());
353 if (config
.SilentClose()) {
354 silent_close_enabled_
= true;
357 SetNetworkTimeouts(config
.max_time_before_crypto_handshake(),
358 config
.max_idle_time_before_crypto_handshake());
361 sent_packet_manager_
.SetFromConfig(config
);
362 if (config
.HasReceivedBytesForConnectionId() &&
363 can_truncate_connection_ids_
) {
364 packet_generator_
.SetConnectionIdLength(
365 config
.ReceivedBytesForConnectionId());
367 max_undecryptable_packets_
= config
.max_undecryptable_packets();
369 if (FLAGS_quic_send_fec_packet_only_on_fec_alarm
&&
370 config
.HasClientSentConnectionOption(kFSPA
, perspective_
)) {
371 packet_generator_
.set_fec_send_policy(FecSendPolicy::FEC_ALARM_TRIGGER
);
374 if (config
.HasClientSentConnectionOption(kMTUH
, perspective_
)) {
375 mtu_discovery_target_
= kMtuDiscoveryTargetPacketSizeHigh
;
377 if (config
.HasClientSentConnectionOption(kMTUL
, perspective_
)) {
378 mtu_discovery_target_
= kMtuDiscoveryTargetPacketSizeLow
;
382 void QuicConnection::OnSendConnectionState(
383 const CachedNetworkParameters
& cached_network_params
) {
384 if (debug_visitor_
!= nullptr) {
385 debug_visitor_
->OnSendConnectionState(cached_network_params
);
389 void QuicConnection::ResumeConnectionState(
390 const CachedNetworkParameters
& cached_network_params
,
391 bool max_bandwidth_resumption
) {
392 if (debug_visitor_
!= nullptr) {
393 debug_visitor_
->OnResumeConnectionState(cached_network_params
);
395 sent_packet_manager_
.ResumeConnectionState(cached_network_params
,
396 max_bandwidth_resumption
);
399 void QuicConnection::SetNumOpenStreams(size_t num_streams
) {
400 sent_packet_manager_
.SetNumOpenStreams(num_streams
);
403 bool QuicConnection::SelectMutualVersion(
404 const QuicVersionVector
& available_versions
) {
405 // Try to find the highest mutual version by iterating over supported
406 // versions, starting with the highest, and breaking out of the loop once we
407 // find a matching version in the provided available_versions vector.
408 const QuicVersionVector
& supported_versions
= framer_
.supported_versions();
409 for (size_t i
= 0; i
< supported_versions
.size(); ++i
) {
410 const QuicVersion
& version
= supported_versions
[i
];
411 if (std::find(available_versions
.begin(), available_versions
.end(),
412 version
) != available_versions
.end()) {
413 framer_
.set_version(version
);
421 void QuicConnection::OnError(QuicFramer
* framer
) {
422 // Packets that we can not or have not decrypted are dropped.
423 // TODO(rch): add stats to measure this.
424 if (!connected_
|| last_packet_decrypted_
== false) {
427 SendConnectionCloseWithDetails(framer
->error(), framer
->detailed_error());
430 void QuicConnection::MaybeSetFecAlarm(
431 QuicPacketSequenceNumber sequence_number
) {
432 if (fec_alarm_
->IsSet()) {
435 QuicTime::Delta timeout
= packet_generator_
.GetFecTimeout(sequence_number
);
436 if (!timeout
.IsInfinite()) {
437 fec_alarm_
->Set(clock_
->ApproximateNow().Add(timeout
));
441 void QuicConnection::OnPacket() {
442 DCHECK(last_stream_frames_
.empty() &&
443 last_ack_frames_
.empty() &&
444 last_stop_waiting_frames_
.empty() &&
445 last_rst_frames_
.empty() &&
446 last_goaway_frames_
.empty() &&
447 last_window_update_frames_
.empty() &&
448 last_blocked_frames_
.empty() &&
449 last_ping_frames_
.empty() &&
450 last_close_frames_
.empty());
451 last_packet_decrypted_
= false;
452 last_packet_revived_
= false;
455 void QuicConnection::OnPublicResetPacket(const QuicPublicResetPacket
& packet
) {
456 // Check that any public reset packet with a different connection ID that was
457 // routed to this QuicConnection has been redirected before control reaches
458 // here. (Check for a bug regression.)
459 DCHECK_EQ(connection_id_
, packet
.public_header
.connection_id
);
460 if (debug_visitor_
!= nullptr) {
461 debug_visitor_
->OnPublicResetPacket(packet
);
463 CloseConnection(QUIC_PUBLIC_RESET
, true);
465 DVLOG(1) << ENDPOINT
<< "Connection " << connection_id()
466 << " closed via QUIC_PUBLIC_RESET from peer.";
469 bool QuicConnection::OnProtocolVersionMismatch(QuicVersion received_version
) {
470 DVLOG(1) << ENDPOINT
<< "Received packet with mismatched version "
472 // TODO(satyamshekhar): Implement no server state in this mode.
473 if (perspective_
== Perspective::IS_CLIENT
) {
474 LOG(DFATAL
) << ENDPOINT
<< "Framer called OnProtocolVersionMismatch. "
475 << "Closing connection.";
476 CloseConnection(QUIC_INTERNAL_ERROR
, false);
479 DCHECK_NE(version(), received_version
);
481 if (debug_visitor_
!= nullptr) {
482 debug_visitor_
->OnProtocolVersionMismatch(received_version
);
485 switch (version_negotiation_state_
) {
486 case START_NEGOTIATION
:
487 if (!framer_
.IsSupportedVersion(received_version
)) {
488 SendVersionNegotiationPacket();
489 version_negotiation_state_
= NEGOTIATION_IN_PROGRESS
;
494 case NEGOTIATION_IN_PROGRESS
:
495 if (!framer_
.IsSupportedVersion(received_version
)) {
496 SendVersionNegotiationPacket();
501 case NEGOTIATED_VERSION
:
502 // Might be old packets that were sent by the client before the version
503 // was negotiated. Drop these.
510 version_negotiation_state_
= NEGOTIATED_VERSION
;
511 visitor_
->OnSuccessfulVersionNegotiation(received_version
);
512 if (debug_visitor_
!= nullptr) {
513 debug_visitor_
->OnSuccessfulVersionNegotiation(received_version
);
515 DVLOG(1) << ENDPOINT
<< "version negotiated " << received_version
;
517 // Store the new version.
518 framer_
.set_version(received_version
);
520 // TODO(satyamshekhar): Store the sequence number of this packet and close the
521 // connection if we ever received a packet with incorrect version and whose
522 // sequence number is greater.
526 // Handles version negotiation for client connection.
527 void QuicConnection::OnVersionNegotiationPacket(
528 const QuicVersionNegotiationPacket
& packet
) {
529 // Check that any public reset packet with a different connection ID that was
530 // routed to this QuicConnection has been redirected before control reaches
531 // here. (Check for a bug regression.)
532 DCHECK_EQ(connection_id_
, packet
.connection_id
);
533 if (perspective_
== Perspective::IS_SERVER
) {
534 LOG(DFATAL
) << ENDPOINT
<< "Framer parsed VersionNegotiationPacket."
535 << " Closing connection.";
536 CloseConnection(QUIC_INTERNAL_ERROR
, false);
539 if (debug_visitor_
!= nullptr) {
540 debug_visitor_
->OnVersionNegotiationPacket(packet
);
543 if (version_negotiation_state_
!= START_NEGOTIATION
) {
544 // Possibly a duplicate version negotiation packet.
548 if (std::find(packet
.versions
.begin(),
549 packet
.versions
.end(), version()) !=
550 packet
.versions
.end()) {
551 DLOG(WARNING
) << ENDPOINT
<< "The server already supports our version. "
552 << "It should have accepted our connection.";
553 // Just drop the connection.
554 CloseConnection(QUIC_INVALID_VERSION_NEGOTIATION_PACKET
, false);
558 if (!SelectMutualVersion(packet
.versions
)) {
559 SendConnectionCloseWithDetails(QUIC_INVALID_VERSION
,
560 "no common version found");
565 << "Negotiated version: " << QuicVersionToString(version());
566 server_supported_versions_
= packet
.versions
;
567 version_negotiation_state_
= NEGOTIATION_IN_PROGRESS
;
568 RetransmitUnackedPackets(ALL_UNACKED_RETRANSMISSION
);
571 void QuicConnection::OnRevivedPacket() {
574 bool QuicConnection::OnUnauthenticatedPublicHeader(
575 const QuicPacketPublicHeader
& header
) {
576 if (header
.connection_id
== connection_id_
) {
580 ++stats_
.packets_dropped
;
581 DVLOG(1) << ENDPOINT
<< "Ignoring packet from unexpected ConnectionId: "
582 << header
.connection_id
<< " instead of " << connection_id_
;
583 if (debug_visitor_
!= nullptr) {
584 debug_visitor_
->OnIncorrectConnectionId(header
.connection_id
);
586 // If this is a server, the dispatcher routes each packet to the
587 // QuicConnection responsible for the packet's connection ID. So if control
588 // arrives here and this is a server, the dispatcher must be malfunctioning.
589 DCHECK_NE(Perspective::IS_SERVER
, perspective_
);
593 bool QuicConnection::OnUnauthenticatedHeader(const QuicPacketHeader
& header
) {
594 // Check that any public reset packet with a different connection ID that was
595 // routed to this QuicConnection has been redirected before control reaches
597 DCHECK_EQ(connection_id_
, header
.public_header
.connection_id
);
601 void QuicConnection::OnDecryptedPacket(EncryptionLevel level
) {
602 last_decrypted_packet_level_
= level
;
603 last_packet_decrypted_
= true;
604 // If this packet was foward-secure encrypted and the forward-secure encrypter
605 // is not being used, start using it.
606 if (encryption_level_
!= ENCRYPTION_FORWARD_SECURE
&&
607 has_forward_secure_encrypter_
&& level
== ENCRYPTION_FORWARD_SECURE
) {
608 SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE
);
612 bool QuicConnection::OnPacketHeader(const QuicPacketHeader
& header
) {
613 if (debug_visitor_
!= nullptr) {
614 debug_visitor_
->OnPacketHeader(header
);
617 if (!ProcessValidatedPacket()) {
621 // Will be decremented below if we fall through to return true.
622 ++stats_
.packets_dropped
;
624 if (!Near(header
.packet_sequence_number
,
625 last_header_
.packet_sequence_number
)) {
626 DVLOG(1) << ENDPOINT
<< "Packet " << header
.packet_sequence_number
627 << " out of bounds. Discarding";
628 SendConnectionCloseWithDetails(QUIC_INVALID_PACKET_HEADER
,
629 "Packet sequence number out of bounds");
633 // If this packet has already been seen, or the sender has told us that it
634 // will not be retransmitted, then stop processing the packet.
635 if (!received_packet_manager_
.IsAwaitingPacket(
636 header
.packet_sequence_number
)) {
637 DVLOG(1) << ENDPOINT
<< "Packet " << header
.packet_sequence_number
638 << " no longer being waited for. Discarding.";
639 if (debug_visitor_
!= nullptr) {
640 debug_visitor_
->OnDuplicatePacket(header
.packet_sequence_number
);
645 if (version_negotiation_state_
!= NEGOTIATED_VERSION
) {
646 if (perspective_
== Perspective::IS_SERVER
) {
647 if (!header
.public_header
.version_flag
) {
648 DLOG(WARNING
) << ENDPOINT
<< "Packet " << header
.packet_sequence_number
649 << " without version flag before version negotiated.";
650 // Packets should have the version flag till version negotiation is
652 CloseConnection(QUIC_INVALID_VERSION
, false);
655 DCHECK_EQ(1u, header
.public_header
.versions
.size());
656 DCHECK_EQ(header
.public_header
.versions
[0], version());
657 version_negotiation_state_
= NEGOTIATED_VERSION
;
658 visitor_
->OnSuccessfulVersionNegotiation(version());
659 if (debug_visitor_
!= nullptr) {
660 debug_visitor_
->OnSuccessfulVersionNegotiation(version());
664 DCHECK(!header
.public_header
.version_flag
);
665 // If the client gets a packet without the version flag from the server
666 // it should stop sending version since the version negotiation is done.
667 packet_generator_
.StopSendingVersion();
668 version_negotiation_state_
= NEGOTIATED_VERSION
;
669 visitor_
->OnSuccessfulVersionNegotiation(version());
670 if (debug_visitor_
!= nullptr) {
671 debug_visitor_
->OnSuccessfulVersionNegotiation(version());
676 DCHECK_EQ(NEGOTIATED_VERSION
, version_negotiation_state_
);
678 --stats_
.packets_dropped
;
679 DVLOG(1) << ENDPOINT
<< "Received packet header: " << header
;
680 last_header_
= header
;
685 void QuicConnection::OnFecProtectedPayload(StringPiece payload
) {
686 DCHECK_EQ(IN_FEC_GROUP
, last_header_
.is_in_fec_group
);
687 DCHECK_NE(0u, last_header_
.fec_group
);
688 QuicFecGroup
* group
= GetFecGroup();
689 if (group
!= nullptr) {
690 group
->Update(last_decrypted_packet_level_
, last_header_
, payload
);
694 bool QuicConnection::OnStreamFrame(const QuicStreamFrame
& frame
) {
696 if (debug_visitor_
!= nullptr) {
697 debug_visitor_
->OnStreamFrame(frame
);
699 if (frame
.stream_id
!= kCryptoStreamId
&&
700 last_decrypted_packet_level_
== ENCRYPTION_NONE
) {
701 DLOG(WARNING
) << ENDPOINT
702 << "Received an unencrypted data frame: closing connection";
703 SendConnectionClose(QUIC_UNENCRYPTED_STREAM_DATA
);
706 if (FLAGS_quic_process_frames_inline
) {
707 visitor_
->OnStreamFrame(frame
);
708 stats_
.stream_bytes_received
+= frame
.data
.size();
709 should_last_packet_instigate_acks_
= true;
711 last_stream_frames_
.push_back(frame
);
716 bool QuicConnection::OnAckFrame(const QuicAckFrame
& incoming_ack
) {
718 if (debug_visitor_
!= nullptr) {
719 debug_visitor_
->OnAckFrame(incoming_ack
);
721 DVLOG(1) << ENDPOINT
<< "OnAckFrame: " << incoming_ack
;
723 if (last_header_
.packet_sequence_number
<= largest_seen_packet_with_ack_
) {
724 DVLOG(1) << ENDPOINT
<< "Received an old ack frame: ignoring";
728 if (!ValidateAckFrame(incoming_ack
)) {
729 SendConnectionClose(QUIC_INVALID_ACK_DATA
);
733 if (FLAGS_quic_process_frames_inline
) {
734 ProcessAckFrame(incoming_ack
);
735 if (incoming_ack
.is_truncated
) {
736 should_last_packet_instigate_acks_
= true;
738 if (!incoming_ack
.missing_packets
.empty() &&
739 GetLeastUnacked() > *incoming_ack
.missing_packets
.begin()) {
740 ++stop_waiting_count_
;
742 stop_waiting_count_
= 0;
745 last_ack_frames_
.push_back(incoming_ack
);
750 void QuicConnection::ProcessAckFrame(const QuicAckFrame
& incoming_ack
) {
751 largest_seen_packet_with_ack_
= last_header_
.packet_sequence_number
;
752 sent_packet_manager_
.OnIncomingAck(incoming_ack
,
753 time_of_last_received_packet_
);
754 sent_entropy_manager_
.ClearEntropyBefore(
755 sent_packet_manager_
.least_packet_awaited_by_peer() - 1);
757 // Always reset the retransmission alarm when an ack comes in, since we now
758 // have a better estimate of the current rtt than when it was set.
759 SetRetransmissionAlarm();
762 void QuicConnection::ProcessStopWaitingFrame(
763 const QuicStopWaitingFrame
& stop_waiting
) {
764 largest_seen_packet_with_stop_waiting_
= last_header_
.packet_sequence_number
;
765 received_packet_manager_
.UpdatePacketInformationSentByPeer(stop_waiting
);
766 // Possibly close any FecGroups which are now irrelevant.
767 CloseFecGroupsBefore(stop_waiting
.least_unacked
+ 1);
770 bool QuicConnection::OnStopWaitingFrame(const QuicStopWaitingFrame
& frame
) {
773 if (last_header_
.packet_sequence_number
<=
774 largest_seen_packet_with_stop_waiting_
) {
775 DVLOG(1) << ENDPOINT
<< "Received an old stop waiting frame: ignoring";
779 if (!ValidateStopWaitingFrame(frame
)) {
780 SendConnectionClose(QUIC_INVALID_STOP_WAITING_DATA
);
784 if (debug_visitor_
!= nullptr) {
785 debug_visitor_
->OnStopWaitingFrame(frame
);
788 last_stop_waiting_frames_
.push_back(frame
);
792 bool QuicConnection::OnPingFrame(const QuicPingFrame
& frame
) {
794 if (debug_visitor_
!= nullptr) {
795 debug_visitor_
->OnPingFrame(frame
);
797 if (FLAGS_quic_process_frames_inline
) {
798 should_last_packet_instigate_acks_
= true;
800 last_ping_frames_
.push_back(frame
);
805 bool QuicConnection::ValidateAckFrame(const QuicAckFrame
& incoming_ack
) {
806 if (incoming_ack
.largest_observed
> packet_generator_
.sequence_number()) {
807 DLOG(ERROR
) << ENDPOINT
<< "Peer's observed unsent packet:"
808 << incoming_ack
.largest_observed
<< " vs "
809 << packet_generator_
.sequence_number();
810 // We got an error for data we have not sent. Error out.
814 if (incoming_ack
.largest_observed
< sent_packet_manager_
.largest_observed()) {
815 DLOG(ERROR
) << ENDPOINT
<< "Peer's largest_observed packet decreased:"
816 << incoming_ack
.largest_observed
<< " vs "
817 << sent_packet_manager_
.largest_observed();
818 // A new ack has a diminished largest_observed value. Error out.
819 // If this was an old packet, we wouldn't even have checked.
823 if (!incoming_ack
.missing_packets
.empty() &&
824 *incoming_ack
.missing_packets
.rbegin() > incoming_ack
.largest_observed
) {
825 DLOG(ERROR
) << ENDPOINT
<< "Peer sent missing packet: "
826 << *incoming_ack
.missing_packets
.rbegin()
827 << " which is greater than largest observed: "
828 << incoming_ack
.largest_observed
;
832 if (!incoming_ack
.missing_packets
.empty() &&
833 *incoming_ack
.missing_packets
.begin() <
834 sent_packet_manager_
.least_packet_awaited_by_peer()) {
835 DLOG(ERROR
) << ENDPOINT
<< "Peer sent missing packet: "
836 << *incoming_ack
.missing_packets
.begin()
837 << " which is smaller than least_packet_awaited_by_peer_: "
838 << sent_packet_manager_
.least_packet_awaited_by_peer();
842 if (!sent_entropy_manager_
.IsValidEntropy(
843 incoming_ack
.largest_observed
,
844 incoming_ack
.missing_packets
,
845 incoming_ack
.entropy_hash
)) {
846 DLOG(ERROR
) << ENDPOINT
<< "Peer sent invalid entropy.";
850 for (QuicPacketSequenceNumber revived_packet
: incoming_ack
.revived_packets
) {
851 if (!ContainsKey(incoming_ack
.missing_packets
, revived_packet
)) {
852 DLOG(ERROR
) << ENDPOINT
853 << "Peer specified revived packet which was not missing.";
860 bool QuicConnection::ValidateStopWaitingFrame(
861 const QuicStopWaitingFrame
& stop_waiting
) {
862 if (stop_waiting
.least_unacked
<
863 received_packet_manager_
.peer_least_packet_awaiting_ack()) {
864 DLOG(ERROR
) << ENDPOINT
<< "Peer's sent low least_unacked: "
865 << stop_waiting
.least_unacked
<< " vs "
866 << received_packet_manager_
.peer_least_packet_awaiting_ack();
867 // We never process old ack frames, so this number should only increase.
871 if (stop_waiting
.least_unacked
>
872 last_header_
.packet_sequence_number
) {
873 DLOG(ERROR
) << ENDPOINT
<< "Peer sent least_unacked:"
874 << stop_waiting
.least_unacked
875 << " greater than the enclosing packet sequence number:"
876 << last_header_
.packet_sequence_number
;
883 void QuicConnection::OnFecData(const QuicFecData
& fec
) {
884 DCHECK_EQ(IN_FEC_GROUP
, last_header_
.is_in_fec_group
);
885 DCHECK_NE(0u, last_header_
.fec_group
);
886 QuicFecGroup
* group
= GetFecGroup();
887 if (group
!= nullptr) {
888 group
->UpdateFec(last_decrypted_packet_level_
,
889 last_header_
.packet_sequence_number
, fec
);
893 bool QuicConnection::OnRstStreamFrame(const QuicRstStreamFrame
& frame
) {
895 if (debug_visitor_
!= nullptr) {
896 debug_visitor_
->OnRstStreamFrame(frame
);
898 DVLOG(1) << ENDPOINT
<< "Stream reset with error "
899 << QuicUtils::StreamErrorToString(frame
.error_code
);
900 if (FLAGS_quic_process_frames_inline
) {
901 visitor_
->OnRstStream(frame
);
902 should_last_packet_instigate_acks_
= true;
904 last_rst_frames_
.push_back(frame
);
909 bool QuicConnection::OnConnectionCloseFrame(
910 const QuicConnectionCloseFrame
& frame
) {
912 if (debug_visitor_
!= nullptr) {
913 debug_visitor_
->OnConnectionCloseFrame(frame
);
915 DVLOG(1) << ENDPOINT
<< "Connection " << connection_id()
916 << " closed with error "
917 << QuicUtils::ErrorToString(frame
.error_code
)
918 << " " << frame
.error_details
;
919 if (FLAGS_quic_process_frames_inline
) {
920 CloseConnection(frame
.error_code
, true);
922 last_close_frames_
.push_back(frame
);
927 bool QuicConnection::OnGoAwayFrame(const QuicGoAwayFrame
& frame
) {
929 if (debug_visitor_
!= nullptr) {
930 debug_visitor_
->OnGoAwayFrame(frame
);
932 DVLOG(1) << ENDPOINT
<< "Go away received with error "
933 << QuicUtils::ErrorToString(frame
.error_code
)
934 << " and reason:" << frame
.reason_phrase
;
935 if (FLAGS_quic_process_frames_inline
) {
936 visitor_
->OnGoAway(frame
);
937 should_last_packet_instigate_acks_
= true;
939 last_goaway_frames_
.push_back(frame
);
944 bool QuicConnection::OnWindowUpdateFrame(const QuicWindowUpdateFrame
& frame
) {
946 if (debug_visitor_
!= nullptr) {
947 debug_visitor_
->OnWindowUpdateFrame(frame
);
949 DVLOG(1) << ENDPOINT
<< "WindowUpdate received for stream: "
950 << frame
.stream_id
<< " with byte offset: " << frame
.byte_offset
;
951 if (FLAGS_quic_process_frames_inline
) {
952 visitor_
->OnWindowUpdateFrame(frame
);
953 should_last_packet_instigate_acks_
= true;
955 last_window_update_frames_
.push_back(frame
);
960 bool QuicConnection::OnBlockedFrame(const QuicBlockedFrame
& frame
) {
962 if (debug_visitor_
!= nullptr) {
963 debug_visitor_
->OnBlockedFrame(frame
);
965 DVLOG(1) << ENDPOINT
<< "Blocked frame received for stream: "
967 if (FLAGS_quic_process_frames_inline
) {
968 visitor_
->OnBlockedFrame(frame
);
969 should_last_packet_instigate_acks_
= true;
971 last_blocked_frames_
.push_back(frame
);
976 void QuicConnection::OnPacketComplete() {
977 // Don't do anything if this packet closed the connection.
983 DVLOG(1) << ENDPOINT
<< (last_packet_revived_
? "Revived" : "Got")
984 << " packet " << last_header_
.packet_sequence_number
<< " with " //
985 << last_stream_frames_
.size() << " stream frames, " //
986 << last_ack_frames_
.size() << " acks, " //
987 << last_stop_waiting_frames_
.size() << " stop_waiting, " //
988 << last_rst_frames_
.size() << " rsts, " //
989 << last_goaway_frames_
.size() << " goaways, " //
990 << last_window_update_frames_
.size() << " window updates, " //
991 << last_blocked_frames_
.size() << " blocked, " //
992 << last_ping_frames_
.size() << " pings, " //
993 << last_close_frames_
.size() << " closes " //
994 << "for " << last_header_
.public_header
.connection_id
;
996 ++num_packets_received_since_last_ack_sent_
;
998 // Call MaybeQueueAck() before recording the received packet, since we want
999 // to trigger an ack if the newly received packet was previously missing.
1002 // Record received or revived packet to populate ack info correctly before
1003 // processing stream frames, since the processing may result in a response
1004 // packet with a bundled ack.
1005 if (last_packet_revived_
) {
1006 received_packet_manager_
.RecordPacketRevived(
1007 last_header_
.packet_sequence_number
);
1009 received_packet_manager_
.RecordPacketReceived(
1010 last_size_
, last_header_
, time_of_last_received_packet_
);
1013 if (!FLAGS_quic_process_frames_inline
) {
1014 for (const QuicStreamFrame
& frame
: last_stream_frames_
) {
1015 visitor_
->OnStreamFrame(frame
);
1016 stats_
.stream_bytes_received
+= frame
.data
.size();
1022 // Process window updates, blocked, stream resets, acks, then stop waiting.
1023 for (const QuicWindowUpdateFrame
& frame
: last_window_update_frames_
) {
1024 visitor_
->OnWindowUpdateFrame(frame
);
1029 for (const QuicBlockedFrame
& frame
: last_blocked_frames_
) {
1030 visitor_
->OnBlockedFrame(frame
);
1035 for (const QuicGoAwayFrame
& frame
: last_goaway_frames_
) {
1036 visitor_
->OnGoAway(frame
);
1041 for (const QuicRstStreamFrame
& frame
: last_rst_frames_
) {
1042 visitor_
->OnRstStream(frame
);
1047 for (const QuicAckFrame
& frame
: last_ack_frames_
) {
1048 ProcessAckFrame(frame
);
1053 if (!last_close_frames_
.empty()) {
1054 CloseConnection(last_close_frames_
[0].error_code
, true);
1055 DCHECK(!connected_
);
1059 // Continue to process stop waiting frames later, because the packet needs
1060 // to be considered 'received' before the entropy can be updated.
1061 for (const QuicStopWaitingFrame
& frame
: last_stop_waiting_frames_
) {
1062 ProcessStopWaitingFrame(frame
);
1068 // If there are new missing packets to report, send an ack immediately.
1069 if (ShouldLastPacketInstigateAck() &&
1070 received_packet_manager_
.HasNewMissingPackets()) {
1072 ack_alarm_
->Cancel();
1075 UpdateStopWaitingCount();
1077 MaybeCloseIfTooManyOutstandingPackets();
1080 void QuicConnection::MaybeQueueAck() {
1081 // If the last packet is an ack, don't ack it.
1082 if (!ShouldLastPacketInstigateAck()) {
1085 // If the incoming packet was missing, send an ack immediately.
1086 ack_queued_
= received_packet_manager_
.IsMissing(
1087 last_header_
.packet_sequence_number
);
1090 if (ack_alarm_
->IsSet()) {
1094 clock_
->ApproximateNow().Add(sent_packet_manager_
.DelayedAckTime()));
1095 DVLOG(1) << "Ack timer set; next packet or timer will trigger ACK.";
1100 ack_alarm_
->Cancel();
1104 void QuicConnection::ClearLastFrames() {
1105 if (FLAGS_quic_process_frames_inline
) {
1106 should_last_packet_instigate_acks_
= false;
1107 last_stop_waiting_frames_
.clear();
1110 last_stream_frames_
.clear();
1111 last_ack_frames_
.clear();
1112 last_stop_waiting_frames_
.clear();
1113 last_rst_frames_
.clear();
1114 last_goaway_frames_
.clear();
1115 last_window_update_frames_
.clear();
1116 last_blocked_frames_
.clear();
1117 last_ping_frames_
.clear();
1118 last_close_frames_
.clear();
1121 void QuicConnection::MaybeCloseIfTooManyOutstandingPackets() {
1122 // This occurs if we don't discard old packets we've sent fast enough.
1123 // It's possible largest observed is less than least unacked.
1124 if (sent_packet_manager_
.largest_observed() >
1125 (sent_packet_manager_
.GetLeastUnacked() + kMaxTrackedPackets
)) {
1126 SendConnectionCloseWithDetails(
1127 QUIC_TOO_MANY_OUTSTANDING_SENT_PACKETS
,
1128 StringPrintf("More than %" PRIu64
" outstanding.", kMaxTrackedPackets
));
1130 // This occurs if there are received packet gaps and the peer does not raise
1131 // the least unacked fast enough.
1132 if (received_packet_manager_
.NumTrackedPackets() > kMaxTrackedPackets
) {
1133 SendConnectionCloseWithDetails(
1134 QUIC_TOO_MANY_OUTSTANDING_RECEIVED_PACKETS
,
1135 StringPrintf("More than %" PRIu64
" outstanding.", kMaxTrackedPackets
));
1139 void QuicConnection::PopulateAckFrame(QuicAckFrame
* ack
) {
1140 received_packet_manager_
.UpdateReceivedPacketInfo(ack
,
1141 clock_
->ApproximateNow());
1144 void QuicConnection::PopulateStopWaitingFrame(
1145 QuicStopWaitingFrame
* stop_waiting
) {
1146 stop_waiting
->least_unacked
= GetLeastUnacked();
1147 stop_waiting
->entropy_hash
= sent_entropy_manager_
.GetCumulativeEntropy(
1148 stop_waiting
->least_unacked
- 1);
1151 bool QuicConnection::ShouldLastPacketInstigateAck() const {
1152 if (FLAGS_quic_process_frames_inline
&& should_last_packet_instigate_acks_
) {
1155 if (!FLAGS_quic_process_frames_inline
) {
1156 if (!last_stream_frames_
.empty() || !last_goaway_frames_
.empty() ||
1157 !last_rst_frames_
.empty() || !last_window_update_frames_
.empty() ||
1158 !last_blocked_frames_
.empty() || !last_ping_frames_
.empty()) {
1162 if (!last_ack_frames_
.empty() && last_ack_frames_
.back().is_truncated
) {
1166 // Always send an ack every 20 packets in order to allow the peer to discard
1167 // information from the SentPacketManager and provide an RTT measurement.
1168 if (num_packets_received_since_last_ack_sent_
>=
1169 kMaxPacketsReceivedBeforeAckSend
) {
1175 void QuicConnection::UpdateStopWaitingCount() {
1176 if (last_ack_frames_
.empty()) {
1180 // If the peer is still waiting for a packet that we are no longer planning to
1181 // send, send an ack to raise the high water mark.
1182 if (!last_ack_frames_
.back().missing_packets
.empty() &&
1183 GetLeastUnacked() > *last_ack_frames_
.back().missing_packets
.begin()) {
1184 ++stop_waiting_count_
;
1186 stop_waiting_count_
= 0;
1190 QuicPacketSequenceNumber
QuicConnection::GetLeastUnacked() const {
1191 return sent_packet_manager_
.GetLeastUnacked();
1194 void QuicConnection::MaybeSendInResponseToPacket() {
1198 ScopedPacketBundler
bundler(this, ack_queued_
? SEND_ACK
: NO_ACK
);
1200 // Now that we have received an ack, we might be able to send packets which
1201 // are queued locally, or drain streams which are blocked.
1202 WriteIfNotBlocked();
1205 void QuicConnection::SendVersionNegotiationPacket() {
1206 // TODO(alyssar): implement zero server state negotiation.
1207 pending_version_negotiation_packet_
= true;
1208 if (writer_
->IsWriteBlocked()) {
1209 visitor_
->OnWriteBlocked();
1212 DVLOG(1) << ENDPOINT
<< "Sending version negotiation packet: {"
1213 << QuicVersionVectorToString(framer_
.supported_versions()) << "}";
1214 scoped_ptr
<QuicEncryptedPacket
> version_packet(
1215 packet_generator_
.SerializeVersionNegotiationPacket(
1216 framer_
.supported_versions()));
1217 WriteResult result
= writer_
->WritePacket(
1218 version_packet
->data(), version_packet
->length(),
1219 self_address().address(), peer_address());
1221 if (result
.status
== WRITE_STATUS_ERROR
) {
1222 // We can't send an error as the socket is presumably borked.
1223 CloseConnection(QUIC_PACKET_WRITE_ERROR
, false);
1226 if (result
.status
== WRITE_STATUS_BLOCKED
) {
1227 visitor_
->OnWriteBlocked();
1228 if (writer_
->IsWriteBlockedDataBuffered()) {
1229 pending_version_negotiation_packet_
= false;
1234 pending_version_negotiation_packet_
= false;
1237 QuicConsumedData
QuicConnection::SendStreamData(
1239 const QuicIOVector
& iov
,
1240 QuicStreamOffset offset
,
1242 FecProtection fec_protection
,
1243 QuicAckNotifier::DelegateInterface
* delegate
) {
1244 if (!fin
&& iov
.total_length
== 0) {
1245 LOG(DFATAL
) << "Attempt to send empty stream frame";
1246 return QuicConsumedData(0, false);
1249 // Opportunistically bundle an ack with every outgoing packet.
1250 // Particularly, we want to bundle with handshake packets since we don't know
1251 // which decrypter will be used on an ack packet following a handshake
1252 // packet (a handshake packet from client to server could result in a REJ or a
1253 // SHLO from the server, leading to two different decrypters at the server.)
1255 // TODO(jri): Note that ConsumeData may cause a response packet to be sent.
1256 // We may end up sending stale ack information if there are undecryptable
1257 // packets hanging around and/or there are revivable packets which may get
1258 // handled after this packet is sent. Change ScopedPacketBundler to do the
1259 // right thing: check ack_queued_, and then check undecryptable packets and
1260 // also if there is possibility of revival. Only bundle an ack if there's no
1261 // processing left that may cause received_info_ to change.
1262 ScopedRetransmissionScheduler
alarm_delayer(this);
1263 ScopedPacketBundler
ack_bundler(this, BUNDLE_PENDING_ACK
);
1264 return packet_generator_
.ConsumeData(id
, iov
, offset
, fin
, fec_protection
,
1268 void QuicConnection::SendRstStream(QuicStreamId id
,
1269 QuicRstStreamErrorCode error
,
1270 QuicStreamOffset bytes_written
) {
1271 // Opportunistically bundle an ack with this outgoing packet.
1272 ScopedPacketBundler
ack_bundler(this, BUNDLE_PENDING_ACK
);
1273 packet_generator_
.AddControlFrame(QuicFrame(new QuicRstStreamFrame(
1274 id
, AdjustErrorForVersion(error
, version()), bytes_written
)));
1276 sent_packet_manager_
.CancelRetransmissionsForStream(id
);
1277 // Remove all queued packets which only contain data for the reset stream.
1278 QueuedPacketList::iterator packet_iterator
= queued_packets_
.begin();
1279 while (packet_iterator
!= queued_packets_
.end()) {
1280 RetransmittableFrames
* retransmittable_frames
=
1281 packet_iterator
->serialized_packet
.retransmittable_frames
;
1282 if (!retransmittable_frames
) {
1286 retransmittable_frames
->RemoveFramesForStream(id
);
1287 if (!retransmittable_frames
->frames().empty()) {
1291 delete packet_iterator
->serialized_packet
.retransmittable_frames
;
1292 delete packet_iterator
->serialized_packet
.packet
;
1293 packet_iterator
->serialized_packet
.retransmittable_frames
= nullptr;
1294 packet_iterator
->serialized_packet
.packet
= nullptr;
1295 packet_iterator
= queued_packets_
.erase(packet_iterator
);
1299 void QuicConnection::SendWindowUpdate(QuicStreamId id
,
1300 QuicStreamOffset byte_offset
) {
1301 // Opportunistically bundle an ack with this outgoing packet.
1302 ScopedPacketBundler
ack_bundler(this, BUNDLE_PENDING_ACK
);
1303 packet_generator_
.AddControlFrame(
1304 QuicFrame(new QuicWindowUpdateFrame(id
, byte_offset
)));
1307 void QuicConnection::SendBlocked(QuicStreamId id
) {
1308 // Opportunistically bundle an ack with this outgoing packet.
1309 ScopedPacketBundler
ack_bundler(this, BUNDLE_PENDING_ACK
);
1310 packet_generator_
.AddControlFrame(QuicFrame(new QuicBlockedFrame(id
)));
1313 const QuicConnectionStats
& QuicConnection::GetStats() {
1314 const RttStats
* rtt_stats
= sent_packet_manager_
.GetRttStats();
1316 // Update rtt and estimated bandwidth.
1317 QuicTime::Delta min_rtt
= rtt_stats
->min_rtt();
1318 if (min_rtt
.IsZero()) {
1319 // If min RTT has not been set, use initial RTT instead.
1320 min_rtt
= QuicTime::Delta::FromMicroseconds(rtt_stats
->initial_rtt_us());
1322 stats_
.min_rtt_us
= min_rtt
.ToMicroseconds();
1324 QuicTime::Delta srtt
= rtt_stats
->smoothed_rtt();
1325 if (srtt
.IsZero()) {
1326 // If SRTT has not been set, use initial RTT instead.
1327 srtt
= QuicTime::Delta::FromMicroseconds(rtt_stats
->initial_rtt_us());
1329 stats_
.srtt_us
= srtt
.ToMicroseconds();
1331 stats_
.estimated_bandwidth
= sent_packet_manager_
.BandwidthEstimate();
1332 stats_
.max_packet_size
= packet_generator_
.GetMaxPacketLength();
1333 stats_
.max_received_packet_size
= largest_received_packet_size_
;
1337 void QuicConnection::ProcessUdpPacket(const IPEndPoint
& self_address
,
1338 const IPEndPoint
& peer_address
,
1339 const QuicEncryptedPacket
& packet
) {
1343 // TODO(rtenneti): Remove ScopedTracker below once crbug.com/462789 is fixed.
1344 tracked_objects::ScopedTracker
tracking_profile(
1345 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1346 "462789 QuicConnection::ProcessUdpPacket"));
1347 if (debug_visitor_
!= nullptr) {
1348 debug_visitor_
->OnPacketReceived(self_address
, peer_address
, packet
);
1350 last_size_
= packet
.length();
1352 CheckForAddressMigration(self_address
, peer_address
);
1354 stats_
.bytes_received
+= packet
.length();
1355 ++stats_
.packets_received
;
1357 ScopedRetransmissionScheduler
alarm_delayer(this);
1358 if (!framer_
.ProcessPacket(packet
)) {
1359 // If we are unable to decrypt this packet, it might be
1360 // because the CHLO or SHLO packet was lost.
1361 if (framer_
.error() == QUIC_DECRYPTION_FAILURE
) {
1362 if (encryption_level_
!= ENCRYPTION_FORWARD_SECURE
&&
1363 undecryptable_packets_
.size() < max_undecryptable_packets_
) {
1364 QueueUndecryptablePacket(packet
);
1365 } else if (debug_visitor_
!= nullptr) {
1366 debug_visitor_
->OnUndecryptablePacket();
1369 DVLOG(1) << ENDPOINT
<< "Unable to process packet. Last packet processed: "
1370 << last_header_
.packet_sequence_number
;
1374 ++stats_
.packets_processed
;
1375 MaybeProcessUndecryptablePackets();
1376 MaybeProcessRevivedPacket();
1377 MaybeSendInResponseToPacket();
1381 void QuicConnection::CheckForAddressMigration(
1382 const IPEndPoint
& self_address
, const IPEndPoint
& peer_address
) {
1383 peer_ip_changed_
= false;
1384 peer_port_changed_
= false;
1385 self_ip_changed_
= false;
1386 self_port_changed_
= false;
1388 if (peer_address_
.address().empty()) {
1389 peer_address_
= peer_address
;
1391 if (self_address_
.address().empty()) {
1392 self_address_
= self_address
;
1395 if (!peer_address
.address().empty() && !peer_address_
.address().empty()) {
1396 peer_ip_changed_
= (peer_address
.address() != peer_address_
.address());
1397 peer_port_changed_
= (peer_address
.port() != peer_address_
.port());
1399 // Store in case we want to migrate connection in ProcessValidatedPacket.
1400 migrating_peer_ip_
= peer_address
.address();
1401 migrating_peer_port_
= peer_address
.port();
1404 if (!self_address
.address().empty() && !self_address_
.address().empty()) {
1405 self_ip_changed_
= (self_address
.address() != self_address_
.address());
1406 self_port_changed_
= (self_address
.port() != self_address_
.port());
1410 void QuicConnection::OnCanWrite() {
1411 DCHECK(!writer_
->IsWriteBlocked());
1413 WriteQueuedPackets();
1414 WritePendingRetransmissions();
1416 // Sending queued packets may have caused the socket to become write blocked,
1417 // or the congestion manager to prohibit sending. If we've sent everything
1418 // we had queued and we're still not blocked, let the visitor know it can
1420 if (!CanWrite(HAS_RETRANSMITTABLE_DATA
)) {
1424 { // Limit the scope of the bundler. ACK inclusion happens elsewhere.
1425 ScopedPacketBundler
bundler(this, NO_ACK
);
1426 visitor_
->OnCanWrite();
1429 // After the visitor writes, it may have caused the socket to become write
1430 // blocked or the congestion manager to prohibit sending, so check again.
1431 if (visitor_
->WillingAndAbleToWrite() &&
1432 !resume_writes_alarm_
->IsSet() &&
1433 CanWrite(HAS_RETRANSMITTABLE_DATA
)) {
1434 // We're not write blocked, but some stream didn't write out all of its
1435 // bytes. Register for 'immediate' resumption so we'll keep writing after
1436 // other connections and events have had a chance to use the thread.
1437 resume_writes_alarm_
->Set(clock_
->ApproximateNow());
1441 void QuicConnection::WriteIfNotBlocked() {
1442 if (!writer_
->IsWriteBlocked()) {
1447 bool QuicConnection::ProcessValidatedPacket() {
1448 if ((peer_ip_changed_
&& !FLAGS_quic_allow_ip_migration
) ||
1449 self_ip_changed_
|| self_port_changed_
) {
1450 SendConnectionCloseWithDetails(
1451 QUIC_ERROR_MIGRATING_ADDRESS
,
1452 "Neither IP address migration, nor self port migration are supported.");
1456 // TODO(fayang): Use peer_address_changed_ instead of peer_ip_changed_ and
1457 // peer_port_changed_ once FLAGS_quic_allow_ip_migration is deprecated.
1458 if (peer_ip_changed_
|| peer_port_changed_
) {
1459 IPEndPoint old_peer_address
= peer_address_
;
1460 peer_address_
= IPEndPoint(
1461 peer_ip_changed_
? migrating_peer_ip_
: peer_address_
.address(),
1462 peer_port_changed_
? migrating_peer_port_
: peer_address_
.port());
1464 DVLOG(1) << ENDPOINT
<< "Peer's ip:port changed from "
1465 << old_peer_address
.ToString() << " to "
1466 << peer_address_
.ToString() << ", migrating connection.";
1469 time_of_last_received_packet_
= clock_
->Now();
1470 DVLOG(1) << ENDPOINT
<< "time of last received packet: "
1471 << time_of_last_received_packet_
.ToDebuggingValue();
1473 if (last_size_
> largest_received_packet_size_
) {
1474 largest_received_packet_size_
= last_size_
;
1477 if (perspective_
== Perspective::IS_SERVER
&&
1478 encryption_level_
== ENCRYPTION_NONE
&&
1479 last_size_
> packet_generator_
.GetMaxPacketLength()) {
1480 set_max_packet_length(last_size_
);
1485 void QuicConnection::WriteQueuedPackets() {
1486 DCHECK(!writer_
->IsWriteBlocked());
1488 if (pending_version_negotiation_packet_
) {
1489 SendVersionNegotiationPacket();
1492 QueuedPacketList::iterator packet_iterator
= queued_packets_
.begin();
1493 while (packet_iterator
!= queued_packets_
.end() &&
1494 WritePacket(&(*packet_iterator
))) {
1495 packet_iterator
= queued_packets_
.erase(packet_iterator
);
1499 void QuicConnection::WritePendingRetransmissions() {
1500 // Keep writing as long as there's a pending retransmission which can be
1502 while (sent_packet_manager_
.HasPendingRetransmissions()) {
1503 const QuicSentPacketManager::PendingRetransmission pending
=
1504 sent_packet_manager_
.NextPendingRetransmission();
1505 if (!CanWrite(HAS_RETRANSMITTABLE_DATA
)) {
1509 // Re-packetize the frames with a new sequence number for retransmission.
1510 // Retransmitted data packets do not use FEC, even when it's enabled.
1511 // Retransmitted packets use the same sequence number length as the
1513 // Flush the packet generator before making a new packet.
1514 // TODO(ianswett): Implement ReserializeAllFrames as a separate path that
1515 // does not require the creator to be flushed.
1516 packet_generator_
.FlushAllQueuedFrames();
1517 char buffer
[kMaxPacketSize
];
1518 SerializedPacket serialized_packet
= packet_generator_
.ReserializeAllFrames(
1519 pending
.retransmittable_frames
, pending
.sequence_number_length
, buffer
,
1521 if (serialized_packet
.packet
== nullptr) {
1522 // We failed to serialize the packet, so close the connection.
1523 // CloseConnection does not send close packet, so no infinite loop here.
1524 CloseConnection(QUIC_ENCRYPTION_FAILURE
, false);
1528 DVLOG(1) << ENDPOINT
<< "Retransmitting " << pending
.sequence_number
1529 << " as " << serialized_packet
.sequence_number
;
1531 QueuedPacket(serialized_packet
,
1532 pending
.retransmittable_frames
.encryption_level(),
1533 pending
.transmission_type
,
1534 pending
.sequence_number
));
1538 void QuicConnection::RetransmitUnackedPackets(
1539 TransmissionType retransmission_type
) {
1540 sent_packet_manager_
.RetransmitUnackedPackets(retransmission_type
);
1542 WriteIfNotBlocked();
1545 void QuicConnection::NeuterUnencryptedPackets() {
1546 sent_packet_manager_
.NeuterUnencryptedPackets();
1547 // This may have changed the retransmission timer, so re-arm it.
1548 SetRetransmissionAlarm();
1551 bool QuicConnection::ShouldGeneratePacket(
1552 HasRetransmittableData retransmittable
,
1553 IsHandshake handshake
) {
1554 // We should serialize handshake packets immediately to ensure that they
1555 // end up sent at the right encryption level.
1556 if (handshake
== IS_HANDSHAKE
) {
1560 return CanWrite(retransmittable
);
1563 bool QuicConnection::CanWrite(HasRetransmittableData retransmittable
) {
1568 if (writer_
->IsWriteBlocked()) {
1569 visitor_
->OnWriteBlocked();
1573 QuicTime now
= clock_
->Now();
1574 QuicTime::Delta delay
= sent_packet_manager_
.TimeUntilSend(
1575 now
, retransmittable
);
1576 if (delay
.IsInfinite()) {
1577 send_alarm_
->Cancel();
1581 // If the scheduler requires a delay, then we can not send this packet now.
1582 if (!delay
.IsZero()) {
1583 send_alarm_
->Update(now
.Add(delay
), QuicTime::Delta::FromMilliseconds(1));
1584 DVLOG(1) << ENDPOINT
<< "Delaying sending " << delay
.ToMilliseconds()
1588 send_alarm_
->Cancel();
1592 bool QuicConnection::WritePacket(QueuedPacket
* packet
) {
1593 if (!WritePacketInner(packet
)) {
1596 delete packet
->serialized_packet
.retransmittable_frames
;
1597 delete packet
->serialized_packet
.packet
;
1598 packet
->serialized_packet
.retransmittable_frames
= nullptr;
1599 packet
->serialized_packet
.packet
= nullptr;
1603 bool QuicConnection::WritePacketInner(QueuedPacket
* packet
) {
1604 if (ShouldDiscardPacket(*packet
)) {
1605 ++stats_
.packets_discarded
;
1608 // Connection close packets are encrypted and saved, so don't exit early.
1609 const bool is_connection_close
= IsConnectionClose(*packet
);
1610 if (writer_
->IsWriteBlocked() && !is_connection_close
) {
1614 QuicPacketSequenceNumber sequence_number
=
1615 packet
->serialized_packet
.sequence_number
;
1616 DCHECK_LE(sequence_number_of_last_sent_packet_
, sequence_number
);
1617 sequence_number_of_last_sent_packet_
= sequence_number
;
1619 QuicEncryptedPacket
* encrypted
= packet
->serialized_packet
.packet
;
1620 // Connection close packets are eventually owned by TimeWaitListManager.
1621 // Others are deleted at the end of this call.
1622 if (is_connection_close
) {
1623 DCHECK(connection_close_packet_
.get() == nullptr);
1624 // Clone the packet so it's owned in the future.
1625 connection_close_packet_
.reset(encrypted
->Clone());
1626 // This assures we won't try to write *forced* packets when blocked.
1627 // Return true to stop processing.
1628 if (writer_
->IsWriteBlocked()) {
1629 visitor_
->OnWriteBlocked();
1634 if (!FLAGS_quic_allow_oversized_packets_for_test
) {
1635 DCHECK_LE(encrypted
->length(), kMaxPacketSize
);
1637 DCHECK_LE(encrypted
->length(), packet_generator_
.GetMaxPacketLength());
1638 DVLOG(1) << ENDPOINT
<< "Sending packet " << sequence_number
<< " : "
1639 << (packet
->serialized_packet
.is_fec_packet
1641 : (IsRetransmittable(*packet
) == HAS_RETRANSMITTABLE_DATA
1643 : " ack only ")) << ", encryption level: "
1644 << QuicUtils::EncryptionLevelToString(packet
->encryption_level
)
1645 << ", encrypted length:" << encrypted
->length();
1646 DVLOG(2) << ENDPOINT
<< "packet(" << sequence_number
<< "): " << std::endl
1647 << QuicUtils::StringToHexASCIIDump(encrypted
->AsStringPiece());
1649 // Measure the RTT from before the write begins to avoid underestimating the
1650 // min_rtt_, especially in cases where the thread blocks or gets swapped out
1651 // during the WritePacket below.
1652 QuicTime packet_send_time
= clock_
->Now();
1653 WriteResult result
= writer_
->WritePacket(encrypted
->data(),
1654 encrypted
->length(),
1655 self_address().address(),
1657 if (result
.error_code
== ERR_IO_PENDING
) {
1658 DCHECK_EQ(WRITE_STATUS_BLOCKED
, result
.status
);
1661 if (result
.status
== WRITE_STATUS_BLOCKED
) {
1662 visitor_
->OnWriteBlocked();
1663 // If the socket buffers the the data, then the packet should not
1664 // be queued and sent again, which would result in an unnecessary
1665 // duplicate packet being sent. The helper must call OnCanWrite
1666 // when the write completes, and OnWriteError if an error occurs.
1667 if (!writer_
->IsWriteBlockedDataBuffered()) {
1671 if (result
.status
!= WRITE_STATUS_ERROR
&& debug_visitor_
!= nullptr) {
1672 // Pass the write result to the visitor.
1673 debug_visitor_
->OnPacketSent(packet
->serialized_packet
,
1674 packet
->original_sequence_number
,
1675 packet
->encryption_level
,
1676 packet
->transmission_type
,
1680 if (packet
->transmission_type
== NOT_RETRANSMISSION
) {
1681 time_of_last_sent_new_packet_
= packet_send_time
;
1684 MaybeSetFecAlarm(sequence_number
);
1686 DVLOG(1) << ENDPOINT
<< "time we began writing last sent packet: "
1687 << packet_send_time
.ToDebuggingValue();
1689 // TODO(ianswett): Change the sequence number length and other packet creator
1690 // options by a more explicit API than setting a struct value directly,
1691 // perhaps via the NetworkChangeVisitor.
1692 packet_generator_
.UpdateSequenceNumberLength(
1693 sent_packet_manager_
.least_packet_awaited_by_peer(),
1694 sent_packet_manager_
.EstimateMaxPacketsInFlight(max_packet_length()));
1696 bool reset_retransmission_alarm
= sent_packet_manager_
.OnPacketSent(
1697 &packet
->serialized_packet
,
1698 packet
->original_sequence_number
,
1700 encrypted
->length(),
1701 packet
->transmission_type
,
1702 IsRetransmittable(*packet
));
1704 if (reset_retransmission_alarm
|| !retransmission_alarm_
->IsSet()) {
1705 SetRetransmissionAlarm();
1708 stats_
.bytes_sent
+= result
.bytes_written
;
1709 ++stats_
.packets_sent
;
1710 if (packet
->transmission_type
!= NOT_RETRANSMISSION
) {
1711 stats_
.bytes_retransmitted
+= result
.bytes_written
;
1712 ++stats_
.packets_retransmitted
;
1715 if (result
.status
== WRITE_STATUS_ERROR
) {
1716 OnWriteError(result
.error_code
);
1717 DLOG(ERROR
) << ENDPOINT
<< "failed writing " << encrypted
->length()
1719 << " from host " << self_address().ToStringWithoutPort()
1720 << " to address " << peer_address().ToString();
1727 bool QuicConnection::ShouldDiscardPacket(const QueuedPacket
& packet
) {
1729 DVLOG(1) << ENDPOINT
1730 << "Not sending packet as connection is disconnected.";
1734 QuicPacketSequenceNumber sequence_number
=
1735 packet
.serialized_packet
.sequence_number
;
1736 if (encryption_level_
== ENCRYPTION_FORWARD_SECURE
&&
1737 packet
.encryption_level
== ENCRYPTION_NONE
) {
1738 // Drop packets that are NULL encrypted since the peer won't accept them
1740 DVLOG(1) << ENDPOINT
<< "Dropping NULL encrypted packet: "
1741 << sequence_number
<< " since the connection is forward secure.";
1745 // If a retransmission has been acked before sending, don't send it.
1746 // This occurs if a packet gets serialized, queued, then discarded.
1747 if (packet
.transmission_type
!= NOT_RETRANSMISSION
&&
1748 (!sent_packet_manager_
.IsUnacked(packet
.original_sequence_number
) ||
1749 !sent_packet_manager_
.HasRetransmittableFrames(
1750 packet
.original_sequence_number
))) {
1751 DVLOG(1) << ENDPOINT
<< "Dropping unacked packet: " << sequence_number
1752 << " A previous transmission was acked while write blocked.";
1759 void QuicConnection::OnWriteError(int error_code
) {
1760 DVLOG(1) << ENDPOINT
<< "Write failed with error: " << error_code
1761 << " (" << ErrorToString(error_code
) << ")";
1762 // We can't send an error as the socket is presumably borked.
1763 CloseConnection(QUIC_PACKET_WRITE_ERROR
, false);
1766 void QuicConnection::OnSerializedPacket(
1767 const SerializedPacket
& serialized_packet
) {
1768 if (serialized_packet
.packet
== nullptr) {
1769 // We failed to serialize the packet, so close the connection.
1770 // CloseConnection does not send close packet, so no infinite loop here.
1771 CloseConnection(QUIC_ENCRYPTION_FAILURE
, false);
1774 sent_packet_manager_
.OnSerializedPacket(serialized_packet
);
1775 if (serialized_packet
.is_fec_packet
&& fec_alarm_
->IsSet()) {
1776 // If an FEC packet is serialized with the FEC alarm set, cancel the alarm.
1777 fec_alarm_
->Cancel();
1779 SendOrQueuePacket(QueuedPacket(serialized_packet
, encryption_level_
));
1782 void QuicConnection::OnResetFecGroup() {
1783 if (!fec_alarm_
->IsSet()) {
1786 // If an FEC Group is closed with the FEC alarm set, cancel the alarm.
1787 fec_alarm_
->Cancel();
1790 void QuicConnection::OnCongestionWindowChange() {
1791 packet_generator_
.OnCongestionWindowChange(
1792 sent_packet_manager_
.EstimateMaxPacketsInFlight(max_packet_length()));
1793 visitor_
->OnCongestionWindowChange(clock_
->ApproximateNow());
1796 void QuicConnection::OnRttChange() {
1797 // Uses the connection's smoothed RTT. If zero, uses initial_rtt.
1798 QuicTime::Delta rtt
= sent_packet_manager_
.GetRttStats()->smoothed_rtt();
1800 rtt
= QuicTime::Delta::FromMicroseconds(
1801 sent_packet_manager_
.GetRttStats()->initial_rtt_us());
1803 packet_generator_
.OnRttChange(rtt
);
1806 void QuicConnection::OnHandshakeComplete() {
1807 sent_packet_manager_
.SetHandshakeConfirmed();
1808 // The client should immediately ack the SHLO to confirm the handshake is
1809 // complete with the server.
1810 if (perspective_
== Perspective::IS_CLIENT
&& !ack_queued_
) {
1811 ack_alarm_
->Cancel();
1812 ack_alarm_
->Set(clock_
->ApproximateNow());
1816 void QuicConnection::SendOrQueuePacket(QueuedPacket packet
) {
1817 // The caller of this function is responsible for checking CanWrite().
1818 if (packet
.serialized_packet
.packet
== nullptr) {
1820 << "packet.serialized_packet.packet == nullptr in to SendOrQueuePacket";
1824 sent_entropy_manager_
.RecordPacketEntropyHash(
1825 packet
.serialized_packet
.sequence_number
,
1826 packet
.serialized_packet
.entropy_hash
);
1827 if (!WritePacket(&packet
)) {
1828 // Take ownership of the underlying encrypted packet.
1829 if (!packet
.serialized_packet
.packet
->owns_buffer()) {
1830 scoped_ptr
<QuicEncryptedPacket
> encrypted_deleter(
1831 packet
.serialized_packet
.packet
);
1832 packet
.serialized_packet
.packet
=
1833 packet
.serialized_packet
.packet
->Clone();
1835 queued_packets_
.push_back(packet
);
1838 // If a forward-secure encrypter is available but is not being used and the
1839 // next sequence number is the first packet which requires
1840 // forward security, start using the forward-secure encrypter.
1841 if (encryption_level_
!= ENCRYPTION_FORWARD_SECURE
&&
1842 has_forward_secure_encrypter_
&&
1843 packet
.serialized_packet
.sequence_number
>=
1844 first_required_forward_secure_packet_
- 1) {
1845 SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE
);
1849 void QuicConnection::SendPing() {
1850 if (retransmission_alarm_
->IsSet()) {
1853 packet_generator_
.AddControlFrame(QuicFrame(new QuicPingFrame
));
1856 void QuicConnection::SendAck() {
1857 ack_alarm_
->Cancel();
1858 ack_queued_
= false;
1859 stop_waiting_count_
= 0;
1860 num_packets_received_since_last_ack_sent_
= 0;
1862 packet_generator_
.SetShouldSendAck(true);
1865 void QuicConnection::OnRetransmissionTimeout() {
1866 if (!sent_packet_manager_
.HasUnackedPackets()) {
1870 sent_packet_manager_
.OnRetransmissionTimeout();
1871 WriteIfNotBlocked();
1873 // A write failure can result in the connection being closed, don't attempt to
1874 // write further packets, or to set alarms.
1879 // In the TLP case, the SentPacketManager gives the connection the opportunity
1880 // to send new data before retransmitting.
1881 if (sent_packet_manager_
.MaybeRetransmitTailLossProbe()) {
1882 // Send the pending retransmission now that it's been queued.
1883 WriteIfNotBlocked();
1886 // Ensure the retransmission alarm is always set if there are unacked packets
1887 // and nothing waiting to be sent.
1888 // This happens if the loss algorithm invokes a timer based loss, but the
1889 // packet doesn't need to be retransmitted.
1890 if (!HasQueuedData() && !retransmission_alarm_
->IsSet()) {
1891 SetRetransmissionAlarm();
1895 void QuicConnection::SetEncrypter(EncryptionLevel level
,
1896 QuicEncrypter
* encrypter
) {
1897 packet_generator_
.SetEncrypter(level
, encrypter
);
1898 if (level
== ENCRYPTION_FORWARD_SECURE
) {
1899 has_forward_secure_encrypter_
= true;
1900 first_required_forward_secure_packet_
=
1901 sequence_number_of_last_sent_packet_
+
1902 // 3 times the current congestion window (in slow start) should cover
1903 // about two full round trips worth of packets, which should be
1905 3 * sent_packet_manager_
.EstimateMaxPacketsInFlight(
1906 max_packet_length());
1910 void QuicConnection::SetDefaultEncryptionLevel(EncryptionLevel level
) {
1911 encryption_level_
= level
;
1912 packet_generator_
.set_encryption_level(level
);
1915 void QuicConnection::SetDecrypter(EncryptionLevel level
,
1916 QuicDecrypter
* decrypter
) {
1917 framer_
.SetDecrypter(level
, decrypter
);
1920 void QuicConnection::SetAlternativeDecrypter(EncryptionLevel level
,
1921 QuicDecrypter
* decrypter
,
1922 bool latch_once_used
) {
1923 framer_
.SetAlternativeDecrypter(level
, decrypter
, latch_once_used
);
1926 const QuicDecrypter
* QuicConnection::decrypter() const {
1927 return framer_
.decrypter();
1930 const QuicDecrypter
* QuicConnection::alternative_decrypter() const {
1931 return framer_
.alternative_decrypter();
1934 void QuicConnection::QueueUndecryptablePacket(
1935 const QuicEncryptedPacket
& packet
) {
1936 DVLOG(1) << ENDPOINT
<< "Queueing undecryptable packet.";
1937 undecryptable_packets_
.push_back(packet
.Clone());
1940 void QuicConnection::MaybeProcessUndecryptablePackets() {
1941 if (undecryptable_packets_
.empty() || encryption_level_
== ENCRYPTION_NONE
) {
1945 while (connected_
&& !undecryptable_packets_
.empty()) {
1946 DVLOG(1) << ENDPOINT
<< "Attempting to process undecryptable packet";
1947 QuicEncryptedPacket
* packet
= undecryptable_packets_
.front();
1948 if (!framer_
.ProcessPacket(*packet
) &&
1949 framer_
.error() == QUIC_DECRYPTION_FAILURE
) {
1950 DVLOG(1) << ENDPOINT
<< "Unable to process undecryptable packet...";
1953 DVLOG(1) << ENDPOINT
<< "Processed undecryptable packet!";
1954 ++stats_
.packets_processed
;
1956 undecryptable_packets_
.pop_front();
1959 // Once forward secure encryption is in use, there will be no
1960 // new keys installed and hence any undecryptable packets will
1961 // never be able to be decrypted.
1962 if (encryption_level_
== ENCRYPTION_FORWARD_SECURE
) {
1963 if (debug_visitor_
!= nullptr) {
1964 // TODO(rtenneti): perhaps more efficient to pass the number of
1965 // undecryptable packets as the argument to OnUndecryptablePacket so that
1966 // we just need to call OnUndecryptablePacket once?
1967 for (size_t i
= 0; i
< undecryptable_packets_
.size(); ++i
) {
1968 debug_visitor_
->OnUndecryptablePacket();
1971 STLDeleteElements(&undecryptable_packets_
);
1975 void QuicConnection::MaybeProcessRevivedPacket() {
1976 QuicFecGroup
* group
= GetFecGroup();
1977 if (!connected_
|| group
== nullptr || !group
->CanRevive()) {
1980 QuicPacketHeader revived_header
;
1981 char revived_payload
[kMaxPacketSize
];
1982 size_t len
= group
->Revive(&revived_header
, revived_payload
, kMaxPacketSize
);
1983 revived_header
.public_header
.connection_id
= connection_id_
;
1984 revived_header
.public_header
.connection_id_length
=
1985 last_header_
.public_header
.connection_id_length
;
1986 revived_header
.public_header
.version_flag
= false;
1987 revived_header
.public_header
.reset_flag
= false;
1988 revived_header
.public_header
.sequence_number_length
=
1989 last_header_
.public_header
.sequence_number_length
;
1990 revived_header
.fec_flag
= false;
1991 revived_header
.is_in_fec_group
= NOT_IN_FEC_GROUP
;
1992 revived_header
.fec_group
= 0;
1993 group_map_
.erase(last_header_
.fec_group
);
1994 last_decrypted_packet_level_
= group
->effective_encryption_level();
1995 DCHECK_LT(last_decrypted_packet_level_
, NUM_ENCRYPTION_LEVELS
);
1998 last_packet_revived_
= true;
1999 if (debug_visitor_
!= nullptr) {
2000 debug_visitor_
->OnRevivedPacket(revived_header
,
2001 StringPiece(revived_payload
, len
));
2004 ++stats_
.packets_revived
;
2005 framer_
.ProcessRevivedPacket(&revived_header
,
2006 StringPiece(revived_payload
, len
));
2009 QuicFecGroup
* QuicConnection::GetFecGroup() {
2010 QuicFecGroupNumber fec_group_num
= last_header_
.fec_group
;
2011 if (fec_group_num
== 0) {
2014 if (!ContainsKey(group_map_
, fec_group_num
)) {
2015 if (group_map_
.size() >= kMaxFecGroups
) { // Too many groups
2016 if (fec_group_num
< group_map_
.begin()->first
) {
2017 // The group being requested is a group we've seen before and deleted.
2018 // Don't recreate it.
2021 // Clear the lowest group number.
2022 delete group_map_
.begin()->second
;
2023 group_map_
.erase(group_map_
.begin());
2025 group_map_
[fec_group_num
] = new QuicFecGroup();
2027 return group_map_
[fec_group_num
];
2030 void QuicConnection::SendConnectionClose(QuicErrorCode error
) {
2031 SendConnectionCloseWithDetails(error
, string());
2034 void QuicConnection::SendConnectionCloseWithDetails(QuicErrorCode error
,
2035 const string
& details
) {
2036 // If we're write blocked, WritePacket() will not send, but will capture the
2037 // serialized packet.
2038 SendConnectionClosePacket(error
, details
);
2039 CloseConnection(error
, false);
2042 void QuicConnection::SendConnectionClosePacket(QuicErrorCode error
,
2043 const string
& details
) {
2044 DVLOG(1) << ENDPOINT
<< "Force closing " << connection_id()
2045 << " with error " << QuicUtils::ErrorToString(error
)
2046 << " (" << error
<< ") " << details
;
2047 // Don't send explicit connection close packets for timeouts.
2048 // This is particularly important on mobile, where connections are short.
2049 if (silent_close_enabled_
&&
2050 error
== QuicErrorCode::QUIC_CONNECTION_TIMED_OUT
) {
2053 ScopedPacketBundler
ack_bundler(this, SEND_ACK
);
2054 QuicConnectionCloseFrame
* frame
= new QuicConnectionCloseFrame();
2055 frame
->error_code
= error
;
2056 frame
->error_details
= details
;
2057 packet_generator_
.AddControlFrame(QuicFrame(frame
));
2058 packet_generator_
.FlushAllQueuedFrames();
2061 void QuicConnection::CloseConnection(QuicErrorCode error
, bool from_peer
) {
2063 DVLOG(1) << "Connection is already closed.";
2067 if (debug_visitor_
!= nullptr) {
2068 debug_visitor_
->OnConnectionClosed(error
, from_peer
);
2070 DCHECK(visitor_
!= nullptr);
2071 visitor_
->OnConnectionClosed(error
, from_peer
);
2072 // Cancel the alarms so they don't trigger any action now that the
2073 // connection is closed.
2074 ack_alarm_
->Cancel();
2075 ping_alarm_
->Cancel();
2076 fec_alarm_
->Cancel();
2077 resume_writes_alarm_
->Cancel();
2078 retransmission_alarm_
->Cancel();
2079 send_alarm_
->Cancel();
2080 timeout_alarm_
->Cancel();
2081 mtu_discovery_alarm_
->Cancel();
2084 void QuicConnection::SendGoAway(QuicErrorCode error
,
2085 QuicStreamId last_good_stream_id
,
2086 const string
& reason
) {
2087 DVLOG(1) << ENDPOINT
<< "Going away with error "
2088 << QuicUtils::ErrorToString(error
)
2089 << " (" << error
<< ")";
2091 // Opportunistically bundle an ack with this outgoing packet.
2092 ScopedPacketBundler
ack_bundler(this, BUNDLE_PENDING_ACK
);
2093 packet_generator_
.AddControlFrame(
2094 QuicFrame(new QuicGoAwayFrame(error
, last_good_stream_id
, reason
)));
2097 void QuicConnection::CloseFecGroupsBefore(
2098 QuicPacketSequenceNumber sequence_number
) {
2099 FecGroupMap::iterator it
= group_map_
.begin();
2100 while (it
!= group_map_
.end()) {
2101 // If this is the current group or the group doesn't protect this packet
2102 // we can ignore it.
2103 if (last_header_
.fec_group
== it
->first
||
2104 !it
->second
->ProtectsPacketsBefore(sequence_number
)) {
2108 QuicFecGroup
* fec_group
= it
->second
;
2109 DCHECK(!fec_group
->CanRevive());
2110 FecGroupMap::iterator next
= it
;
2112 group_map_
.erase(it
);
2118 QuicByteCount
QuicConnection::max_packet_length() const {
2119 return packet_generator_
.GetMaxPacketLength();
2122 void QuicConnection::set_max_packet_length(QuicByteCount length
) {
2123 return packet_generator_
.SetMaxPacketLength(length
, /*force=*/false);
2126 bool QuicConnection::HasQueuedData() const {
2127 return pending_version_negotiation_packet_
||
2128 !queued_packets_
.empty() || packet_generator_
.HasQueuedFrames();
2131 bool QuicConnection::CanWriteStreamData() {
2132 // Don't write stream data if there are negotiation or queued data packets
2133 // to send. Otherwise, continue and bundle as many frames as possible.
2134 if (pending_version_negotiation_packet_
|| !queued_packets_
.empty()) {
2138 IsHandshake pending_handshake
= visitor_
->HasPendingHandshake() ?
2139 IS_HANDSHAKE
: NOT_HANDSHAKE
;
2140 // Sending queued packets may have caused the socket to become write blocked,
2141 // or the congestion manager to prohibit sending. If we've sent everything
2142 // we had queued and we're still not blocked, let the visitor know it can
2144 return ShouldGeneratePacket(HAS_RETRANSMITTABLE_DATA
, pending_handshake
);
2147 void QuicConnection::SetNetworkTimeouts(QuicTime::Delta overall_timeout
,
2148 QuicTime::Delta idle_timeout
) {
2149 LOG_IF(DFATAL
, idle_timeout
> overall_timeout
)
2150 << "idle_timeout:" << idle_timeout
.ToMilliseconds()
2151 << " overall_timeout:" << overall_timeout
.ToMilliseconds();
2152 // Adjust the idle timeout on client and server to prevent clients from
2153 // sending requests to servers which have already closed the connection.
2154 if (perspective_
== Perspective::IS_SERVER
) {
2155 idle_timeout
= idle_timeout
.Add(QuicTime::Delta::FromSeconds(3));
2156 } else if (idle_timeout
> QuicTime::Delta::FromSeconds(1)) {
2157 idle_timeout
= idle_timeout
.Subtract(QuicTime::Delta::FromSeconds(1));
2159 overall_connection_timeout_
= overall_timeout
;
2160 idle_network_timeout_
= idle_timeout
;
2165 void QuicConnection::CheckForTimeout() {
2166 QuicTime now
= clock_
->ApproximateNow();
2167 QuicTime time_of_last_packet
= max(time_of_last_received_packet_
,
2168 time_of_last_sent_new_packet_
);
2170 // |delta| can be < 0 as |now| is approximate time but |time_of_last_packet|
2171 // is accurate time. However, this should not change the behavior of
2172 // timeout handling.
2173 QuicTime::Delta idle_duration
= now
.Subtract(time_of_last_packet
);
2174 DVLOG(1) << ENDPOINT
<< "last packet "
2175 << time_of_last_packet
.ToDebuggingValue()
2176 << " now:" << now
.ToDebuggingValue()
2177 << " idle_duration:" << idle_duration
.ToMicroseconds()
2178 << " idle_network_timeout: "
2179 << idle_network_timeout_
.ToMicroseconds();
2180 if (idle_duration
>= idle_network_timeout_
) {
2181 DVLOG(1) << ENDPOINT
<< "Connection timedout due to no network activity.";
2182 SendConnectionClose(QUIC_CONNECTION_TIMED_OUT
);
2186 if (!overall_connection_timeout_
.IsInfinite()) {
2187 QuicTime::Delta connected_duration
=
2188 now
.Subtract(stats_
.connection_creation_time
);
2189 DVLOG(1) << ENDPOINT
<< "connection time: "
2190 << connected_duration
.ToMicroseconds() << " overall timeout: "
2191 << overall_connection_timeout_
.ToMicroseconds();
2192 if (connected_duration
>= overall_connection_timeout_
) {
2193 DVLOG(1) << ENDPOINT
<<
2194 "Connection timedout due to overall connection timeout.";
2195 SendConnectionClose(QUIC_CONNECTION_OVERALL_TIMED_OUT
);
2203 void QuicConnection::SetTimeoutAlarm() {
2204 QuicTime time_of_last_packet
= max(time_of_last_received_packet_
,
2205 time_of_last_sent_new_packet_
);
2207 QuicTime deadline
= time_of_last_packet
.Add(idle_network_timeout_
);
2208 if (!overall_connection_timeout_
.IsInfinite()) {
2209 deadline
= min(deadline
,
2210 stats_
.connection_creation_time
.Add(
2211 overall_connection_timeout_
));
2214 timeout_alarm_
->Cancel();
2215 timeout_alarm_
->Set(deadline
);
2218 void QuicConnection::SetPingAlarm() {
2219 if (perspective_
== Perspective::IS_SERVER
) {
2220 // Only clients send pings.
2223 if (!visitor_
->HasOpenDynamicStreams()) {
2224 ping_alarm_
->Cancel();
2225 // Don't send a ping unless there are open streams.
2228 QuicTime::Delta ping_timeout
= QuicTime::Delta::FromSeconds(kPingTimeoutSecs
);
2229 ping_alarm_
->Update(clock_
->ApproximateNow().Add(ping_timeout
),
2230 QuicTime::Delta::FromSeconds(1));
2233 void QuicConnection::SetRetransmissionAlarm() {
2234 if (delay_setting_retransmission_alarm_
) {
2235 pending_retransmission_alarm_
= true;
2238 QuicTime retransmission_time
= sent_packet_manager_
.GetRetransmissionTime();
2239 retransmission_alarm_
->Update(retransmission_time
,
2240 QuicTime::Delta::FromMilliseconds(1));
2243 void QuicConnection::MaybeSetMtuAlarm() {
2244 if (!FLAGS_quic_do_path_mtu_discovery
) {
2248 // Do not set the alarm if the target size is less than the current size.
2249 // This covers the case when |mtu_discovery_target_| is at its default value,
2251 if (mtu_discovery_target_
<= max_packet_length()) {
2255 if (mtu_probe_count_
>= kMtuDiscoveryAttempts
) {
2259 if (mtu_discovery_alarm_
->IsSet()) {
2263 if (sequence_number_of_last_sent_packet_
>= next_mtu_probe_at_
) {
2264 // Use an alarm to send the MTU probe to ensure that no ScopedPacketBundlers
2266 mtu_discovery_alarm_
->Set(clock_
->ApproximateNow());
2270 QuicConnection::ScopedPacketBundler::ScopedPacketBundler(
2271 QuicConnection
* connection
,
2272 AckBundling send_ack
)
2273 : connection_(connection
),
2274 already_in_batch_mode_(connection
!= nullptr &&
2275 connection
->packet_generator_
.InBatchMode()) {
2276 if (connection_
== nullptr) {
2279 // Move generator into batch mode. If caller wants us to include an ack,
2280 // check the delayed-ack timer to see if there's ack info to be sent.
2281 if (!already_in_batch_mode_
) {
2282 DVLOG(1) << "Entering Batch Mode.";
2283 connection_
->packet_generator_
.StartBatchOperations();
2285 // Bundle an ack if the alarm is set or with every second packet if we need to
2286 // raise the peer's least unacked.
2288 connection_
->ack_alarm_
->IsSet() || connection_
->stop_waiting_count_
> 1;
2289 if (send_ack
== SEND_ACK
|| (send_ack
== BUNDLE_PENDING_ACK
&& ack_pending
)) {
2290 DVLOG(1) << "Bundling ack with outgoing packet.";
2291 connection_
->SendAck();
2295 QuicConnection::ScopedPacketBundler::~ScopedPacketBundler() {
2296 if (connection_
== nullptr) {
2299 // If we changed the generator's batch state, restore original batch state.
2300 if (!already_in_batch_mode_
) {
2301 DVLOG(1) << "Leaving Batch Mode.";
2302 connection_
->packet_generator_
.FinishBatchOperations();
2304 DCHECK_EQ(already_in_batch_mode_
,
2305 connection_
->packet_generator_
.InBatchMode());
2308 QuicConnection::ScopedRetransmissionScheduler::ScopedRetransmissionScheduler(
2309 QuicConnection
* connection
)
2310 : connection_(connection
),
2311 already_delayed_(connection_
->delay_setting_retransmission_alarm_
) {
2312 connection_
->delay_setting_retransmission_alarm_
= true;
2315 QuicConnection::ScopedRetransmissionScheduler::
2316 ~ScopedRetransmissionScheduler() {
2317 if (already_delayed_
) {
2320 connection_
->delay_setting_retransmission_alarm_
= false;
2321 if (connection_
->pending_retransmission_alarm_
) {
2322 connection_
->SetRetransmissionAlarm();
2323 connection_
->pending_retransmission_alarm_
= false;
2327 HasRetransmittableData
QuicConnection::IsRetransmittable(
2328 const QueuedPacket
& packet
) {
2329 // Retransmitted packets retransmittable frames are owned by the unacked
2330 // packet map, but are not present in the serialized packet.
2331 if (packet
.transmission_type
!= NOT_RETRANSMISSION
||
2332 packet
.serialized_packet
.retransmittable_frames
!= nullptr) {
2333 return HAS_RETRANSMITTABLE_DATA
;
2335 return NO_RETRANSMITTABLE_DATA
;
2339 bool QuicConnection::IsConnectionClose(const QueuedPacket
& packet
) {
2340 const RetransmittableFrames
* retransmittable_frames
=
2341 packet
.serialized_packet
.retransmittable_frames
;
2342 if (retransmittable_frames
== nullptr) {
2345 for (const QuicFrame
& frame
: retransmittable_frames
->frames()) {
2346 if (frame
.type
== CONNECTION_CLOSE_FRAME
) {
2353 void QuicConnection::SendMtuDiscoveryPacket(QuicByteCount target_mtu
) {
2354 // Create a listener for the new probe. The ownership of the listener is
2355 // transferred to the AckNotifierManager. The notifier will get destroyed
2356 // before the connection (because it's stored in one of the connection's
2357 // subfields), hence |this| pointer is guaranteed to stay valid at all times.
2358 scoped_refptr
<MtuDiscoveryAckListener
> last_mtu_discovery_ack_listener(
2359 new MtuDiscoveryAckListener(this, target_mtu
));
2362 packet_generator_
.GenerateMtuDiscoveryPacket(
2363 target_mtu
, last_mtu_discovery_ack_listener
.get());
2366 void QuicConnection::DiscoverMtu() {
2367 DCHECK(!mtu_discovery_alarm_
->IsSet());
2369 // Chcek if the MTU has been already increased.
2370 if (mtu_discovery_target_
<= max_packet_length()) {
2374 // Schedule the next probe *before* sending the current one. This is
2375 // important, otherwise, when SendMtuDiscoveryPacket() is called,
2376 // MaybeSetMtuAlarm() will not realize that the probe has been just sent, and
2377 // will reschedule this probe again.
2378 packets_between_mtu_probes_
*= 2;
2379 next_mtu_probe_at_
=
2380 sequence_number_of_last_sent_packet_
+ packets_between_mtu_probes_
+ 1;
2383 DVLOG(2) << "Sending a path MTU discovery packet #" << mtu_probe_count_
;
2384 SendMtuDiscoveryPacket(mtu_discovery_target_
);
2386 DCHECK(!mtu_discovery_alarm_
->IsSet());