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/format_macros.h"
18 #include "base/logging.h"
19 #include "base/memory/ref_counted.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/crypto_protocol.h"
25 #include "net/quic/crypto/quic_decrypter.h"
26 #include "net/quic/crypto/quic_encrypter.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 bool Near(QuicPacketSequenceNumber a
, QuicPacketSequenceNumber b
) {
67 QuicPacketSequenceNumber delta
= (a
> b
) ? a
- b
: b
- a
;
68 return delta
<= kMaxPacketGap
;
71 // An alarm that is scheduled to send an ack if a timeout occurs.
72 class AckAlarm
: public QuicAlarm::Delegate
{
74 explicit AckAlarm(QuicConnection
* connection
)
75 : connection_(connection
) {
78 QuicTime
OnAlarm() override
{
79 connection_
->SendAck();
80 return QuicTime::Zero();
84 QuicConnection
* connection_
;
86 DISALLOW_COPY_AND_ASSIGN(AckAlarm
);
89 // This alarm will be scheduled any time a data-bearing packet is sent out.
90 // When the alarm goes off, the connection checks to see if the oldest packets
91 // have been acked, and retransmit them if they have not.
92 class RetransmissionAlarm
: public QuicAlarm::Delegate
{
94 explicit RetransmissionAlarm(QuicConnection
* connection
)
95 : connection_(connection
) {
98 QuicTime
OnAlarm() override
{
99 connection_
->OnRetransmissionTimeout();
100 return QuicTime::Zero();
104 QuicConnection
* connection_
;
106 DISALLOW_COPY_AND_ASSIGN(RetransmissionAlarm
);
109 // An alarm that is scheduled when the SentPacketManager requires a delay
110 // before sending packets and fires when the packet may be sent.
111 class SendAlarm
: public QuicAlarm::Delegate
{
113 explicit SendAlarm(QuicConnection
* connection
)
114 : connection_(connection
) {
117 QuicTime
OnAlarm() override
{
118 connection_
->WriteIfNotBlocked();
119 // Never reschedule the alarm, since CanWrite does that.
120 return QuicTime::Zero();
124 QuicConnection
* connection_
;
126 DISALLOW_COPY_AND_ASSIGN(SendAlarm
);
129 class TimeoutAlarm
: public QuicAlarm::Delegate
{
131 explicit TimeoutAlarm(QuicConnection
* connection
)
132 : connection_(connection
) {
135 QuicTime
OnAlarm() override
{
136 connection_
->CheckForTimeout();
137 // Never reschedule the alarm, since CheckForTimeout does that.
138 return QuicTime::Zero();
142 QuicConnection
* connection_
;
144 DISALLOW_COPY_AND_ASSIGN(TimeoutAlarm
);
147 class PingAlarm
: public QuicAlarm::Delegate
{
149 explicit PingAlarm(QuicConnection
* connection
)
150 : connection_(connection
) {
153 QuicTime
OnAlarm() override
{
154 connection_
->SendPing();
155 return QuicTime::Zero();
159 QuicConnection
* connection_
;
161 DISALLOW_COPY_AND_ASSIGN(PingAlarm
);
164 class MtuDiscoveryAlarm
: public QuicAlarm::Delegate
{
166 explicit MtuDiscoveryAlarm(QuicConnection
* connection
)
167 : connection_(connection
) {}
169 QuicTime
OnAlarm() override
{
170 connection_
->DiscoverMtu();
171 // DiscoverMtu() handles rescheduling the alarm by itself.
172 return QuicTime::Zero();
176 QuicConnection
* connection_
;
178 DISALLOW_COPY_AND_ASSIGN(MtuDiscoveryAlarm
);
181 // This alarm may be scheduled when an FEC protected packet is sent out.
182 class FecAlarm
: public QuicAlarm::Delegate
{
184 explicit FecAlarm(QuicPacketGenerator
* packet_generator
)
185 : packet_generator_(packet_generator
) {}
187 QuicTime
OnAlarm() override
{
188 packet_generator_
->OnFecTimeout();
189 return QuicTime::Zero();
193 QuicPacketGenerator
* packet_generator_
;
195 DISALLOW_COPY_AND_ASSIGN(FecAlarm
);
198 // Listens for acks of MTU discovery packets and raises the maximum packet size
199 // of the connection if the probe succeeds.
200 class MtuDiscoveryAckListener
: public QuicAckNotifier::DelegateInterface
{
202 MtuDiscoveryAckListener(QuicConnection
* connection
, QuicByteCount probe_size
)
203 : connection_(connection
), probe_size_(probe_size
) {}
205 void OnAckNotification(int /*num_retransmittable_packets*/,
206 int /*num_retransmittable_bytes*/,
207 QuicTime::Delta
/*delta_largest_observed*/) override
{
208 // Since the probe was successful, increase the maximum packet size to that.
209 if (probe_size_
> connection_
->max_packet_length()) {
210 connection_
->set_max_packet_length(probe_size_
);
215 // MtuDiscoveryAckListener is ref counted.
216 ~MtuDiscoveryAckListener() override
{}
219 QuicConnection
* connection_
;
220 QuicByteCount probe_size_
;
222 DISALLOW_COPY_AND_ASSIGN(MtuDiscoveryAckListener
);
227 QuicConnection::QueuedPacket::QueuedPacket(SerializedPacket packet
,
228 EncryptionLevel level
)
229 : serialized_packet(packet
),
230 encryption_level(level
),
231 transmission_type(NOT_RETRANSMISSION
),
232 original_sequence_number(0) {
235 QuicConnection::QueuedPacket::QueuedPacket(
236 SerializedPacket packet
,
237 EncryptionLevel level
,
238 TransmissionType transmission_type
,
239 QuicPacketSequenceNumber original_sequence_number
)
240 : serialized_packet(packet
),
241 encryption_level(level
),
242 transmission_type(transmission_type
),
243 original_sequence_number(original_sequence_number
) {
247 (perspective_ == Perspective::IS_SERVER ? "Server: " : "Client: ")
249 QuicConnection::QuicConnection(QuicConnectionId connection_id
,
251 QuicConnectionHelperInterface
* helper
,
252 const PacketWriterFactory
& writer_factory
,
254 Perspective perspective
,
256 const QuicVersionVector
& supported_versions
)
257 : framer_(supported_versions
,
258 helper
->GetClock()->ApproximateNow(),
261 writer_(writer_factory
.Create(this)),
262 owns_writer_(owns_writer
),
263 encryption_level_(ENCRYPTION_NONE
),
264 has_forward_secure_encrypter_(false),
265 first_required_forward_secure_packet_(0),
266 clock_(helper
->GetClock()),
267 random_generator_(helper
->GetRandomGenerator()),
268 connection_id_(connection_id
),
269 peer_address_(address
),
270 migrating_peer_port_(0),
271 last_packet_decrypted_(false),
272 last_packet_revived_(false),
274 last_decrypted_packet_level_(ENCRYPTION_NONE
),
275 should_last_packet_instigate_acks_(false),
276 largest_seen_packet_with_ack_(0),
277 largest_seen_packet_with_stop_waiting_(0),
278 max_undecryptable_packets_(0),
279 pending_version_negotiation_packet_(false),
280 silent_close_enabled_(false),
281 received_packet_manager_(&stats_
),
283 num_packets_received_since_last_ack_sent_(0),
284 stop_waiting_count_(0),
285 delay_setting_retransmission_alarm_(false),
286 pending_retransmission_alarm_(false),
287 ack_alarm_(helper
->CreateAlarm(new AckAlarm(this))),
288 retransmission_alarm_(helper
->CreateAlarm(new RetransmissionAlarm(this))),
289 send_alarm_(helper
->CreateAlarm(new SendAlarm(this))),
290 resume_writes_alarm_(helper
->CreateAlarm(new SendAlarm(this))),
291 timeout_alarm_(helper
->CreateAlarm(new TimeoutAlarm(this))),
292 ping_alarm_(helper
->CreateAlarm(new PingAlarm(this))),
293 mtu_discovery_alarm_(helper
->CreateAlarm(new MtuDiscoveryAlarm(this))),
295 debug_visitor_(nullptr),
296 packet_generator_(connection_id_
, &framer_
, random_generator_
, this),
297 fec_alarm_(helper
->CreateAlarm(new FecAlarm(&packet_generator_
))),
298 idle_network_timeout_(QuicTime::Delta::Infinite()),
299 overall_connection_timeout_(QuicTime::Delta::Infinite()),
300 time_of_last_received_packet_(clock_
->ApproximateNow()),
301 time_of_last_sent_new_packet_(clock_
->ApproximateNow()),
302 sequence_number_of_last_sent_packet_(0),
303 sent_packet_manager_(
307 FLAGS_quic_use_bbr_congestion_control
? kBBR
: kCubic
,
308 FLAGS_quic_use_time_loss_detection
? kTime
: kNack
,
310 version_negotiation_state_(START_NEGOTIATION
),
311 perspective_(perspective
),
313 peer_ip_changed_(false),
314 peer_port_changed_(false),
315 self_ip_changed_(false),
316 self_port_changed_(false),
317 can_truncate_connection_ids_(true),
318 is_secure_(is_secure
),
319 mtu_discovery_target_(0),
321 packets_between_mtu_probes_(kPacketsBetweenMtuProbesBase
),
322 next_mtu_probe_at_(kPacketsBetweenMtuProbesBase
),
323 largest_received_packet_size_(0) {
324 DVLOG(1) << ENDPOINT
<< "Created connection with connection_id: "
326 framer_
.set_visitor(this);
327 framer_
.set_received_entropy_calculator(&received_packet_manager_
);
328 stats_
.connection_creation_time
= clock_
->ApproximateNow();
329 sent_packet_manager_
.set_network_change_visitor(this);
330 if (perspective_
== Perspective::IS_SERVER
) {
331 set_max_packet_length(kDefaultServerMaxPacketSize
);
335 QuicConnection::~QuicConnection() {
339 STLDeleteElements(&undecryptable_packets_
);
340 STLDeleteValues(&group_map_
);
341 for (QueuedPacketList::iterator it
= queued_packets_
.begin();
342 it
!= queued_packets_
.end(); ++it
) {
343 delete it
->serialized_packet
.retransmittable_frames
;
344 delete it
->serialized_packet
.packet
;
348 void QuicConnection::SetFromConfig(const QuicConfig
& config
) {
349 if (config
.negotiated()) {
350 SetNetworkTimeouts(QuicTime::Delta::Infinite(),
351 config
.IdleConnectionStateLifetime());
352 if (config
.SilentClose()) {
353 silent_close_enabled_
= true;
356 SetNetworkTimeouts(config
.max_time_before_crypto_handshake(),
357 config
.max_idle_time_before_crypto_handshake());
360 sent_packet_manager_
.SetFromConfig(config
);
361 if (config
.HasReceivedBytesForConnectionId() &&
362 can_truncate_connection_ids_
) {
363 packet_generator_
.SetConnectionIdLength(
364 config
.ReceivedBytesForConnectionId());
366 max_undecryptable_packets_
= config
.max_undecryptable_packets();
368 if (config
.HasClientSentConnectionOption(kFSPA
, perspective_
)) {
369 packet_generator_
.set_fec_send_policy(FecSendPolicy::FEC_ALARM_TRIGGER
);
371 if (config
.HasClientSentConnectionOption(kFRTT
, perspective_
)) {
372 // TODO(rtenneti): Delete this code after the 0.25 RTT FEC experiment.
373 const float kFecTimeoutRttMultiplier
= 0.25;
374 packet_generator_
.set_rtt_multiplier_for_fec_timeout(
375 kFecTimeoutRttMultiplier
);
378 if (config
.HasClientSentConnectionOption(kMTUH
, perspective_
)) {
379 mtu_discovery_target_
= kMtuDiscoveryTargetPacketSizeHigh
;
381 if (config
.HasClientSentConnectionOption(kMTUL
, perspective_
)) {
382 mtu_discovery_target_
= kMtuDiscoveryTargetPacketSizeLow
;
386 void QuicConnection::OnSendConnectionState(
387 const CachedNetworkParameters
& cached_network_params
) {
388 if (debug_visitor_
!= nullptr) {
389 debug_visitor_
->OnSendConnectionState(cached_network_params
);
393 void QuicConnection::ResumeConnectionState(
394 const CachedNetworkParameters
& cached_network_params
,
395 bool max_bandwidth_resumption
) {
396 if (debug_visitor_
!= nullptr) {
397 debug_visitor_
->OnResumeConnectionState(cached_network_params
);
399 sent_packet_manager_
.ResumeConnectionState(cached_network_params
,
400 max_bandwidth_resumption
);
403 void QuicConnection::SetNumOpenStreams(size_t num_streams
) {
404 sent_packet_manager_
.SetNumOpenStreams(num_streams
);
407 bool QuicConnection::SelectMutualVersion(
408 const QuicVersionVector
& available_versions
) {
409 // Try to find the highest mutual version by iterating over supported
410 // versions, starting with the highest, and breaking out of the loop once we
411 // find a matching version in the provided available_versions vector.
412 const QuicVersionVector
& supported_versions
= framer_
.supported_versions();
413 for (size_t i
= 0; i
< supported_versions
.size(); ++i
) {
414 const QuicVersion
& version
= supported_versions
[i
];
415 if (std::find(available_versions
.begin(), available_versions
.end(),
416 version
) != available_versions
.end()) {
417 framer_
.set_version(version
);
425 void QuicConnection::OnError(QuicFramer
* framer
) {
426 // Packets that we can not or have not decrypted are dropped.
427 // TODO(rch): add stats to measure this.
428 if (!connected_
|| last_packet_decrypted_
== false) {
431 SendConnectionCloseWithDetails(framer
->error(), framer
->detailed_error());
434 void QuicConnection::MaybeSetFecAlarm(
435 QuicPacketSequenceNumber sequence_number
) {
436 if (fec_alarm_
->IsSet()) {
439 QuicTime::Delta timeout
= packet_generator_
.GetFecTimeout(sequence_number
);
440 if (!timeout
.IsInfinite()) {
441 fec_alarm_
->Set(clock_
->ApproximateNow().Add(timeout
));
445 void QuicConnection::OnPacket() {
446 DCHECK(last_stream_frames_
.empty() &&
447 last_ack_frames_
.empty() &&
448 last_stop_waiting_frames_
.empty() &&
449 last_rst_frames_
.empty() &&
450 last_goaway_frames_
.empty() &&
451 last_window_update_frames_
.empty() &&
452 last_blocked_frames_
.empty() &&
453 last_ping_frames_
.empty() &&
454 last_close_frames_
.empty());
455 last_packet_decrypted_
= false;
456 last_packet_revived_
= false;
459 void QuicConnection::OnPublicResetPacket(const QuicPublicResetPacket
& packet
) {
460 // Check that any public reset packet with a different connection ID that was
461 // routed to this QuicConnection has been redirected before control reaches
462 // here. (Check for a bug regression.)
463 DCHECK_EQ(connection_id_
, packet
.public_header
.connection_id
);
464 if (debug_visitor_
!= nullptr) {
465 debug_visitor_
->OnPublicResetPacket(packet
);
467 CloseConnection(QUIC_PUBLIC_RESET
, true);
469 DVLOG(1) << ENDPOINT
<< "Connection " << connection_id()
470 << " closed via QUIC_PUBLIC_RESET from peer.";
473 bool QuicConnection::OnProtocolVersionMismatch(QuicVersion received_version
) {
474 DVLOG(1) << ENDPOINT
<< "Received packet with mismatched version "
476 // TODO(satyamshekhar): Implement no server state in this mode.
477 if (perspective_
== Perspective::IS_CLIENT
) {
478 LOG(DFATAL
) << ENDPOINT
<< "Framer called OnProtocolVersionMismatch. "
479 << "Closing connection.";
480 CloseConnection(QUIC_INTERNAL_ERROR
, false);
483 DCHECK_NE(version(), received_version
);
485 if (debug_visitor_
!= nullptr) {
486 debug_visitor_
->OnProtocolVersionMismatch(received_version
);
489 switch (version_negotiation_state_
) {
490 case START_NEGOTIATION
:
491 if (!framer_
.IsSupportedVersion(received_version
)) {
492 SendVersionNegotiationPacket();
493 version_negotiation_state_
= NEGOTIATION_IN_PROGRESS
;
498 case NEGOTIATION_IN_PROGRESS
:
499 if (!framer_
.IsSupportedVersion(received_version
)) {
500 SendVersionNegotiationPacket();
505 case NEGOTIATED_VERSION
:
506 // Might be old packets that were sent by the client before the version
507 // was negotiated. Drop these.
514 version_negotiation_state_
= NEGOTIATED_VERSION
;
515 visitor_
->OnSuccessfulVersionNegotiation(received_version
);
516 if (debug_visitor_
!= nullptr) {
517 debug_visitor_
->OnSuccessfulVersionNegotiation(received_version
);
519 DVLOG(1) << ENDPOINT
<< "version negotiated " << received_version
;
521 // Store the new version.
522 framer_
.set_version(received_version
);
524 // TODO(satyamshekhar): Store the sequence number of this packet and close the
525 // connection if we ever received a packet with incorrect version and whose
526 // sequence number is greater.
530 // Handles version negotiation for client connection.
531 void QuicConnection::OnVersionNegotiationPacket(
532 const QuicVersionNegotiationPacket
& packet
) {
533 // Check that any public reset packet with a different connection ID that was
534 // routed to this QuicConnection has been redirected before control reaches
535 // here. (Check for a bug regression.)
536 DCHECK_EQ(connection_id_
, packet
.connection_id
);
537 if (perspective_
== Perspective::IS_SERVER
) {
538 LOG(DFATAL
) << ENDPOINT
<< "Framer parsed VersionNegotiationPacket."
539 << " Closing connection.";
540 CloseConnection(QUIC_INTERNAL_ERROR
, false);
543 if (debug_visitor_
!= nullptr) {
544 debug_visitor_
->OnVersionNegotiationPacket(packet
);
547 if (version_negotiation_state_
!= START_NEGOTIATION
) {
548 // Possibly a duplicate version negotiation packet.
552 if (std::find(packet
.versions
.begin(),
553 packet
.versions
.end(), version()) !=
554 packet
.versions
.end()) {
555 DLOG(WARNING
) << ENDPOINT
<< "The server already supports our version. "
556 << "It should have accepted our connection.";
557 // Just drop the connection.
558 CloseConnection(QUIC_INVALID_VERSION_NEGOTIATION_PACKET
, false);
562 if (!SelectMutualVersion(packet
.versions
)) {
563 SendConnectionCloseWithDetails(QUIC_INVALID_VERSION
,
564 "no common version found");
569 << "Negotiated version: " << QuicVersionToString(version());
570 server_supported_versions_
= packet
.versions
;
571 version_negotiation_state_
= NEGOTIATION_IN_PROGRESS
;
572 RetransmitUnackedPackets(ALL_UNACKED_RETRANSMISSION
);
575 void QuicConnection::OnRevivedPacket() {
578 bool QuicConnection::OnUnauthenticatedPublicHeader(
579 const QuicPacketPublicHeader
& header
) {
580 if (header
.connection_id
== connection_id_
) {
584 ++stats_
.packets_dropped
;
585 DVLOG(1) << ENDPOINT
<< "Ignoring packet from unexpected ConnectionId: "
586 << header
.connection_id
<< " instead of " << connection_id_
;
587 if (debug_visitor_
!= nullptr) {
588 debug_visitor_
->OnIncorrectConnectionId(header
.connection_id
);
590 // If this is a server, the dispatcher routes each packet to the
591 // QuicConnection responsible for the packet's connection ID. So if control
592 // arrives here and this is a server, the dispatcher must be malfunctioning.
593 DCHECK_NE(Perspective::IS_SERVER
, perspective_
);
597 bool QuicConnection::OnUnauthenticatedHeader(const QuicPacketHeader
& header
) {
598 // Check that any public reset packet with a different connection ID that was
599 // routed to this QuicConnection has been redirected before control reaches
601 DCHECK_EQ(connection_id_
, header
.public_header
.connection_id
);
605 void QuicConnection::OnDecryptedPacket(EncryptionLevel level
) {
606 last_decrypted_packet_level_
= level
;
607 last_packet_decrypted_
= true;
608 // If this packet was foward-secure encrypted and the forward-secure encrypter
609 // is not being used, start using it.
610 if (encryption_level_
!= ENCRYPTION_FORWARD_SECURE
&&
611 has_forward_secure_encrypter_
&& level
== ENCRYPTION_FORWARD_SECURE
) {
612 SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE
);
616 bool QuicConnection::OnPacketHeader(const QuicPacketHeader
& header
) {
617 if (debug_visitor_
!= nullptr) {
618 debug_visitor_
->OnPacketHeader(header
);
621 if (!ProcessValidatedPacket()) {
625 // Will be decremented below if we fall through to return true.
626 ++stats_
.packets_dropped
;
628 if (!Near(header
.packet_sequence_number
,
629 last_header_
.packet_sequence_number
)) {
630 DVLOG(1) << ENDPOINT
<< "Packet " << header
.packet_sequence_number
631 << " out of bounds. Discarding";
632 SendConnectionCloseWithDetails(QUIC_INVALID_PACKET_HEADER
,
633 "Packet sequence number out of bounds");
637 // If this packet has already been seen, or the sender has told us that it
638 // will not be retransmitted, then stop processing the packet.
639 if (!received_packet_manager_
.IsAwaitingPacket(
640 header
.packet_sequence_number
)) {
641 DVLOG(1) << ENDPOINT
<< "Packet " << header
.packet_sequence_number
642 << " no longer being waited for. Discarding.";
643 if (debug_visitor_
!= nullptr) {
644 debug_visitor_
->OnDuplicatePacket(header
.packet_sequence_number
);
649 if (version_negotiation_state_
!= NEGOTIATED_VERSION
) {
650 if (perspective_
== Perspective::IS_SERVER
) {
651 if (!header
.public_header
.version_flag
) {
652 DLOG(WARNING
) << ENDPOINT
<< "Packet " << header
.packet_sequence_number
653 << " without version flag before version negotiated.";
654 // Packets should have the version flag till version negotiation is
656 CloseConnection(QUIC_INVALID_VERSION
, false);
659 DCHECK_EQ(1u, header
.public_header
.versions
.size());
660 DCHECK_EQ(header
.public_header
.versions
[0], version());
661 version_negotiation_state_
= NEGOTIATED_VERSION
;
662 visitor_
->OnSuccessfulVersionNegotiation(version());
663 if (debug_visitor_
!= nullptr) {
664 debug_visitor_
->OnSuccessfulVersionNegotiation(version());
668 DCHECK(!header
.public_header
.version_flag
);
669 // If the client gets a packet without the version flag from the server
670 // it should stop sending version since the version negotiation is done.
671 packet_generator_
.StopSendingVersion();
672 version_negotiation_state_
= NEGOTIATED_VERSION
;
673 visitor_
->OnSuccessfulVersionNegotiation(version());
674 if (debug_visitor_
!= nullptr) {
675 debug_visitor_
->OnSuccessfulVersionNegotiation(version());
680 DCHECK_EQ(NEGOTIATED_VERSION
, version_negotiation_state_
);
682 --stats_
.packets_dropped
;
683 DVLOG(1) << ENDPOINT
<< "Received packet header: " << header
;
684 last_header_
= header
;
689 void QuicConnection::OnFecProtectedPayload(StringPiece payload
) {
690 DCHECK_EQ(IN_FEC_GROUP
, last_header_
.is_in_fec_group
);
691 DCHECK_NE(0u, last_header_
.fec_group
);
692 QuicFecGroup
* group
= GetFecGroup();
693 if (group
!= nullptr) {
694 group
->Update(last_decrypted_packet_level_
, last_header_
, payload
);
698 bool QuicConnection::OnStreamFrame(const QuicStreamFrame
& frame
) {
700 if (debug_visitor_
!= nullptr) {
701 debug_visitor_
->OnStreamFrame(frame
);
703 if (frame
.stream_id
!= kCryptoStreamId
&&
704 last_decrypted_packet_level_
== ENCRYPTION_NONE
) {
705 DLOG(WARNING
) << ENDPOINT
706 << "Received an unencrypted data frame: closing connection";
707 SendConnectionClose(QUIC_UNENCRYPTED_STREAM_DATA
);
710 if (FLAGS_quic_process_frames_inline
) {
711 visitor_
->OnStreamFrame(frame
);
712 stats_
.stream_bytes_received
+= frame
.data
.size();
713 should_last_packet_instigate_acks_
= true;
715 last_stream_frames_
.push_back(frame
);
720 bool QuicConnection::OnAckFrame(const QuicAckFrame
& incoming_ack
) {
722 if (debug_visitor_
!= nullptr) {
723 debug_visitor_
->OnAckFrame(incoming_ack
);
725 DVLOG(1) << ENDPOINT
<< "OnAckFrame: " << incoming_ack
;
727 if (last_header_
.packet_sequence_number
<= largest_seen_packet_with_ack_
) {
728 DVLOG(1) << ENDPOINT
<< "Received an old ack frame: ignoring";
732 if (!ValidateAckFrame(incoming_ack
)) {
733 SendConnectionClose(QUIC_INVALID_ACK_DATA
);
737 if (FLAGS_quic_process_frames_inline
) {
738 ProcessAckFrame(incoming_ack
);
739 if (incoming_ack
.is_truncated
) {
740 should_last_packet_instigate_acks_
= true;
742 if (!incoming_ack
.missing_packets
.empty() &&
743 GetLeastUnacked() > *incoming_ack
.missing_packets
.begin()) {
744 ++stop_waiting_count_
;
746 stop_waiting_count_
= 0;
749 last_ack_frames_
.push_back(incoming_ack
);
754 void QuicConnection::ProcessAckFrame(const QuicAckFrame
& incoming_ack
) {
755 largest_seen_packet_with_ack_
= last_header_
.packet_sequence_number
;
756 sent_packet_manager_
.OnIncomingAck(incoming_ack
,
757 time_of_last_received_packet_
);
758 sent_entropy_manager_
.ClearEntropyBefore(
759 sent_packet_manager_
.least_packet_awaited_by_peer() - 1);
761 // Always reset the retransmission alarm when an ack comes in, since we now
762 // have a better estimate of the current rtt than when it was set.
763 SetRetransmissionAlarm();
766 void QuicConnection::ProcessStopWaitingFrame(
767 const QuicStopWaitingFrame
& stop_waiting
) {
768 largest_seen_packet_with_stop_waiting_
= last_header_
.packet_sequence_number
;
769 received_packet_manager_
.UpdatePacketInformationSentByPeer(stop_waiting
);
770 // Possibly close any FecGroups which are now irrelevant.
771 CloseFecGroupsBefore(stop_waiting
.least_unacked
+ 1);
774 bool QuicConnection::OnStopWaitingFrame(const QuicStopWaitingFrame
& frame
) {
777 if (last_header_
.packet_sequence_number
<=
778 largest_seen_packet_with_stop_waiting_
) {
779 DVLOG(1) << ENDPOINT
<< "Received an old stop waiting frame: ignoring";
783 if (!ValidateStopWaitingFrame(frame
)) {
784 SendConnectionClose(QUIC_INVALID_STOP_WAITING_DATA
);
788 if (debug_visitor_
!= nullptr) {
789 debug_visitor_
->OnStopWaitingFrame(frame
);
792 last_stop_waiting_frames_
.push_back(frame
);
796 bool QuicConnection::OnPingFrame(const QuicPingFrame
& frame
) {
798 if (debug_visitor_
!= nullptr) {
799 debug_visitor_
->OnPingFrame(frame
);
801 if (FLAGS_quic_process_frames_inline
) {
802 should_last_packet_instigate_acks_
= true;
804 last_ping_frames_
.push_back(frame
);
809 bool QuicConnection::ValidateAckFrame(const QuicAckFrame
& incoming_ack
) {
810 if (incoming_ack
.largest_observed
> packet_generator_
.sequence_number()) {
811 DLOG(ERROR
) << ENDPOINT
<< "Peer's observed unsent packet:"
812 << incoming_ack
.largest_observed
<< " vs "
813 << packet_generator_
.sequence_number();
814 // We got an error for data we have not sent. Error out.
818 if (incoming_ack
.largest_observed
< sent_packet_manager_
.largest_observed()) {
819 DLOG(ERROR
) << ENDPOINT
<< "Peer's largest_observed packet decreased:"
820 << incoming_ack
.largest_observed
<< " vs "
821 << sent_packet_manager_
.largest_observed();
822 // A new ack has a diminished largest_observed value. Error out.
823 // If this was an old packet, we wouldn't even have checked.
827 if (!incoming_ack
.missing_packets
.empty() &&
828 *incoming_ack
.missing_packets
.rbegin() > incoming_ack
.largest_observed
) {
829 DLOG(ERROR
) << ENDPOINT
<< "Peer sent missing packet: "
830 << *incoming_ack
.missing_packets
.rbegin()
831 << " which is greater than largest observed: "
832 << incoming_ack
.largest_observed
;
836 if (!incoming_ack
.missing_packets
.empty() &&
837 *incoming_ack
.missing_packets
.begin() <
838 sent_packet_manager_
.least_packet_awaited_by_peer()) {
839 DLOG(ERROR
) << ENDPOINT
<< "Peer sent missing packet: "
840 << *incoming_ack
.missing_packets
.begin()
841 << " which is smaller than least_packet_awaited_by_peer_: "
842 << sent_packet_manager_
.least_packet_awaited_by_peer();
846 if (!sent_entropy_manager_
.IsValidEntropy(
847 incoming_ack
.largest_observed
,
848 incoming_ack
.missing_packets
,
849 incoming_ack
.entropy_hash
)) {
850 DLOG(ERROR
) << ENDPOINT
<< "Peer sent invalid entropy.";
854 for (QuicPacketSequenceNumber revived_packet
: incoming_ack
.revived_packets
) {
855 if (!ContainsKey(incoming_ack
.missing_packets
, revived_packet
)) {
856 DLOG(ERROR
) << ENDPOINT
857 << "Peer specified revived packet which was not missing.";
864 bool QuicConnection::ValidateStopWaitingFrame(
865 const QuicStopWaitingFrame
& stop_waiting
) {
866 if (stop_waiting
.least_unacked
<
867 received_packet_manager_
.peer_least_packet_awaiting_ack()) {
868 DLOG(ERROR
) << ENDPOINT
<< "Peer's sent low least_unacked: "
869 << stop_waiting
.least_unacked
<< " vs "
870 << received_packet_manager_
.peer_least_packet_awaiting_ack();
871 // We never process old ack frames, so this number should only increase.
875 if (stop_waiting
.least_unacked
>
876 last_header_
.packet_sequence_number
) {
877 DLOG(ERROR
) << ENDPOINT
<< "Peer sent least_unacked:"
878 << stop_waiting
.least_unacked
879 << " greater than the enclosing packet sequence number:"
880 << last_header_
.packet_sequence_number
;
887 void QuicConnection::OnFecData(const QuicFecData
& fec
) {
888 DCHECK_EQ(IN_FEC_GROUP
, last_header_
.is_in_fec_group
);
889 DCHECK_NE(0u, last_header_
.fec_group
);
890 QuicFecGroup
* group
= GetFecGroup();
891 if (group
!= nullptr) {
892 group
->UpdateFec(last_decrypted_packet_level_
,
893 last_header_
.packet_sequence_number
, fec
);
897 bool QuicConnection::OnRstStreamFrame(const QuicRstStreamFrame
& frame
) {
899 if (debug_visitor_
!= nullptr) {
900 debug_visitor_
->OnRstStreamFrame(frame
);
902 DVLOG(1) << ENDPOINT
<< "Stream reset with error "
903 << QuicUtils::StreamErrorToString(frame
.error_code
);
904 if (FLAGS_quic_process_frames_inline
) {
905 visitor_
->OnRstStream(frame
);
906 should_last_packet_instigate_acks_
= true;
908 last_rst_frames_
.push_back(frame
);
913 bool QuicConnection::OnConnectionCloseFrame(
914 const QuicConnectionCloseFrame
& frame
) {
916 if (debug_visitor_
!= nullptr) {
917 debug_visitor_
->OnConnectionCloseFrame(frame
);
919 DVLOG(1) << ENDPOINT
<< "Connection " << connection_id()
920 << " closed with error "
921 << QuicUtils::ErrorToString(frame
.error_code
)
922 << " " << frame
.error_details
;
923 if (FLAGS_quic_process_frames_inline
) {
924 CloseConnection(frame
.error_code
, true);
926 last_close_frames_
.push_back(frame
);
931 bool QuicConnection::OnGoAwayFrame(const QuicGoAwayFrame
& frame
) {
933 if (debug_visitor_
!= nullptr) {
934 debug_visitor_
->OnGoAwayFrame(frame
);
936 DVLOG(1) << ENDPOINT
<< "Go away received with error "
937 << QuicUtils::ErrorToString(frame
.error_code
)
938 << " and reason:" << frame
.reason_phrase
;
939 if (FLAGS_quic_process_frames_inline
) {
940 visitor_
->OnGoAway(frame
);
941 should_last_packet_instigate_acks_
= true;
943 last_goaway_frames_
.push_back(frame
);
948 bool QuicConnection::OnWindowUpdateFrame(const QuicWindowUpdateFrame
& frame
) {
950 if (debug_visitor_
!= nullptr) {
951 debug_visitor_
->OnWindowUpdateFrame(frame
);
953 DVLOG(1) << ENDPOINT
<< "WindowUpdate received for stream: "
954 << frame
.stream_id
<< " with byte offset: " << frame
.byte_offset
;
955 if (FLAGS_quic_process_frames_inline
) {
956 visitor_
->OnWindowUpdateFrame(frame
);
957 should_last_packet_instigate_acks_
= true;
959 last_window_update_frames_
.push_back(frame
);
964 bool QuicConnection::OnBlockedFrame(const QuicBlockedFrame
& frame
) {
966 if (debug_visitor_
!= nullptr) {
967 debug_visitor_
->OnBlockedFrame(frame
);
969 DVLOG(1) << ENDPOINT
<< "Blocked frame received for stream: "
971 if (FLAGS_quic_process_frames_inline
) {
972 visitor_
->OnBlockedFrame(frame
);
973 should_last_packet_instigate_acks_
= true;
975 last_blocked_frames_
.push_back(frame
);
980 void QuicConnection::OnPacketComplete() {
981 // Don't do anything if this packet closed the connection.
987 DVLOG(1) << ENDPOINT
<< (last_packet_revived_
? "Revived" : "Got")
988 << " packet " << last_header_
.packet_sequence_number
<< " with " //
989 << last_stream_frames_
.size() << " stream frames, " //
990 << last_ack_frames_
.size() << " acks, " //
991 << last_stop_waiting_frames_
.size() << " stop_waiting, " //
992 << last_rst_frames_
.size() << " rsts, " //
993 << last_goaway_frames_
.size() << " goaways, " //
994 << last_window_update_frames_
.size() << " window updates, " //
995 << last_blocked_frames_
.size() << " blocked, " //
996 << last_ping_frames_
.size() << " pings, " //
997 << last_close_frames_
.size() << " closes " //
998 << "for " << last_header_
.public_header
.connection_id
;
1000 ++num_packets_received_since_last_ack_sent_
;
1002 // Call MaybeQueueAck() before recording the received packet, since we want
1003 // to trigger an ack if the newly received packet was previously missing.
1006 // Record received or revived packet to populate ack info correctly before
1007 // processing stream frames, since the processing may result in a response
1008 // packet with a bundled ack.
1009 if (last_packet_revived_
) {
1010 received_packet_manager_
.RecordPacketRevived(
1011 last_header_
.packet_sequence_number
);
1013 received_packet_manager_
.RecordPacketReceived(
1014 last_size_
, last_header_
, time_of_last_received_packet_
);
1017 if (!FLAGS_quic_process_frames_inline
) {
1018 for (const QuicStreamFrame
& frame
: last_stream_frames_
) {
1019 visitor_
->OnStreamFrame(frame
);
1020 stats_
.stream_bytes_received
+= frame
.data
.size();
1026 // Process window updates, blocked, stream resets, acks, then stop waiting.
1027 for (const QuicWindowUpdateFrame
& frame
: last_window_update_frames_
) {
1028 visitor_
->OnWindowUpdateFrame(frame
);
1033 for (const QuicBlockedFrame
& frame
: last_blocked_frames_
) {
1034 visitor_
->OnBlockedFrame(frame
);
1039 for (const QuicGoAwayFrame
& frame
: last_goaway_frames_
) {
1040 visitor_
->OnGoAway(frame
);
1045 for (const QuicRstStreamFrame
& frame
: last_rst_frames_
) {
1046 visitor_
->OnRstStream(frame
);
1051 for (const QuicAckFrame
& frame
: last_ack_frames_
) {
1052 ProcessAckFrame(frame
);
1057 if (!last_close_frames_
.empty()) {
1058 CloseConnection(last_close_frames_
[0].error_code
, true);
1059 DCHECK(!connected_
);
1063 // Continue to process stop waiting frames later, because the packet needs
1064 // to be considered 'received' before the entropy can be updated.
1065 for (const QuicStopWaitingFrame
& frame
: last_stop_waiting_frames_
) {
1066 ProcessStopWaitingFrame(frame
);
1072 // If there are new missing packets to report, send an ack immediately.
1073 if (ShouldLastPacketInstigateAck() &&
1074 received_packet_manager_
.HasNewMissingPackets()) {
1076 ack_alarm_
->Cancel();
1079 UpdateStopWaitingCount();
1081 MaybeCloseIfTooManyOutstandingPackets();
1084 void QuicConnection::MaybeQueueAck() {
1085 // If the last packet is an ack, don't ack it.
1086 if (!ShouldLastPacketInstigateAck()) {
1089 // If the incoming packet was missing, send an ack immediately.
1090 ack_queued_
= received_packet_manager_
.IsMissing(
1091 last_header_
.packet_sequence_number
);
1094 if (ack_alarm_
->IsSet()) {
1098 clock_
->ApproximateNow().Add(sent_packet_manager_
.DelayedAckTime()));
1099 DVLOG(1) << "Ack timer set; next packet or timer will trigger ACK.";
1104 ack_alarm_
->Cancel();
1108 void QuicConnection::ClearLastFrames() {
1109 if (FLAGS_quic_process_frames_inline
) {
1110 should_last_packet_instigate_acks_
= false;
1111 last_stop_waiting_frames_
.clear();
1114 last_stream_frames_
.clear();
1115 last_ack_frames_
.clear();
1116 last_stop_waiting_frames_
.clear();
1117 last_rst_frames_
.clear();
1118 last_goaway_frames_
.clear();
1119 last_window_update_frames_
.clear();
1120 last_blocked_frames_
.clear();
1121 last_ping_frames_
.clear();
1122 last_close_frames_
.clear();
1125 void QuicConnection::MaybeCloseIfTooManyOutstandingPackets() {
1126 // This occurs if we don't discard old packets we've sent fast enough.
1127 // It's possible largest observed is less than least unacked.
1128 if (sent_packet_manager_
.largest_observed() >
1129 (sent_packet_manager_
.GetLeastUnacked() + kMaxTrackedPackets
)) {
1130 SendConnectionCloseWithDetails(
1131 QUIC_TOO_MANY_OUTSTANDING_SENT_PACKETS
,
1132 StringPrintf("More than %" PRIu64
" outstanding.", kMaxTrackedPackets
));
1134 // This occurs if there are received packet gaps and the peer does not raise
1135 // the least unacked fast enough.
1136 if (received_packet_manager_
.NumTrackedPackets() > kMaxTrackedPackets
) {
1137 SendConnectionCloseWithDetails(
1138 QUIC_TOO_MANY_OUTSTANDING_RECEIVED_PACKETS
,
1139 StringPrintf("More than %" PRIu64
" outstanding.", kMaxTrackedPackets
));
1143 void QuicConnection::PopulateAckFrame(QuicAckFrame
* ack
) {
1144 received_packet_manager_
.UpdateReceivedPacketInfo(ack
,
1145 clock_
->ApproximateNow());
1148 void QuicConnection::PopulateStopWaitingFrame(
1149 QuicStopWaitingFrame
* stop_waiting
) {
1150 stop_waiting
->least_unacked
= GetLeastUnacked();
1151 stop_waiting
->entropy_hash
= sent_entropy_manager_
.GetCumulativeEntropy(
1152 stop_waiting
->least_unacked
- 1);
1155 bool QuicConnection::ShouldLastPacketInstigateAck() const {
1156 if (FLAGS_quic_process_frames_inline
&& should_last_packet_instigate_acks_
) {
1159 if (!FLAGS_quic_process_frames_inline
) {
1160 if (!last_stream_frames_
.empty() || !last_goaway_frames_
.empty() ||
1161 !last_rst_frames_
.empty() || !last_window_update_frames_
.empty() ||
1162 !last_blocked_frames_
.empty() || !last_ping_frames_
.empty()) {
1166 if (!last_ack_frames_
.empty() && last_ack_frames_
.back().is_truncated
) {
1170 // Always send an ack every 20 packets in order to allow the peer to discard
1171 // information from the SentPacketManager and provide an RTT measurement.
1172 if (num_packets_received_since_last_ack_sent_
>=
1173 kMaxPacketsReceivedBeforeAckSend
) {
1179 void QuicConnection::UpdateStopWaitingCount() {
1180 if (last_ack_frames_
.empty()) {
1184 // If the peer is still waiting for a packet that we are no longer planning to
1185 // send, send an ack to raise the high water mark.
1186 if (!last_ack_frames_
.back().missing_packets
.empty() &&
1187 GetLeastUnacked() > *last_ack_frames_
.back().missing_packets
.begin()) {
1188 ++stop_waiting_count_
;
1190 stop_waiting_count_
= 0;
1194 QuicPacketSequenceNumber
QuicConnection::GetLeastUnacked() const {
1195 return sent_packet_manager_
.GetLeastUnacked();
1198 void QuicConnection::MaybeSendInResponseToPacket() {
1202 ScopedPacketBundler
bundler(this, ack_queued_
? SEND_ACK
: NO_ACK
);
1204 // Now that we have received an ack, we might be able to send packets which
1205 // are queued locally, or drain streams which are blocked.
1206 WriteIfNotBlocked();
1209 void QuicConnection::SendVersionNegotiationPacket() {
1210 // TODO(alyssar): implement zero server state negotiation.
1211 pending_version_negotiation_packet_
= true;
1212 if (writer_
->IsWriteBlocked()) {
1213 visitor_
->OnWriteBlocked();
1216 DVLOG(1) << ENDPOINT
<< "Sending version negotiation packet: {"
1217 << QuicVersionVectorToString(framer_
.supported_versions()) << "}";
1218 scoped_ptr
<QuicEncryptedPacket
> version_packet(
1219 packet_generator_
.SerializeVersionNegotiationPacket(
1220 framer_
.supported_versions()));
1221 WriteResult result
= writer_
->WritePacket(
1222 version_packet
->data(), version_packet
->length(),
1223 self_address().address(), peer_address());
1225 if (result
.status
== WRITE_STATUS_ERROR
) {
1226 // We can't send an error as the socket is presumably borked.
1227 CloseConnection(QUIC_PACKET_WRITE_ERROR
, false);
1230 if (result
.status
== WRITE_STATUS_BLOCKED
) {
1231 visitor_
->OnWriteBlocked();
1232 if (writer_
->IsWriteBlockedDataBuffered()) {
1233 pending_version_negotiation_packet_
= false;
1238 pending_version_negotiation_packet_
= false;
1241 QuicConsumedData
QuicConnection::SendStreamData(
1243 const QuicIOVector
& iov
,
1244 QuicStreamOffset offset
,
1246 FecProtection fec_protection
,
1247 QuicAckNotifier::DelegateInterface
* delegate
) {
1248 if (!fin
&& iov
.total_length
== 0) {
1249 LOG(DFATAL
) << "Attempt to send empty stream frame";
1250 return QuicConsumedData(0, false);
1253 // Opportunistically bundle an ack with every outgoing packet.
1254 // Particularly, we want to bundle with handshake packets since we don't know
1255 // which decrypter will be used on an ack packet following a handshake
1256 // packet (a handshake packet from client to server could result in a REJ or a
1257 // SHLO from the server, leading to two different decrypters at the server.)
1259 // TODO(jri): Note that ConsumeData may cause a response packet to be sent.
1260 // We may end up sending stale ack information if there are undecryptable
1261 // packets hanging around and/or there are revivable packets which may get
1262 // handled after this packet is sent. Change ScopedPacketBundler to do the
1263 // right thing: check ack_queued_, and then check undecryptable packets and
1264 // also if there is possibility of revival. Only bundle an ack if there's no
1265 // processing left that may cause received_info_ to change.
1266 ScopedRetransmissionScheduler
alarm_delayer(this);
1267 ScopedPacketBundler
ack_bundler(this, BUNDLE_PENDING_ACK
);
1268 return packet_generator_
.ConsumeData(id
, iov
, offset
, fin
, fec_protection
,
1272 void QuicConnection::SendRstStream(QuicStreamId id
,
1273 QuicRstStreamErrorCode error
,
1274 QuicStreamOffset bytes_written
) {
1275 // Opportunistically bundle an ack with this outgoing packet.
1276 ScopedPacketBundler
ack_bundler(this, BUNDLE_PENDING_ACK
);
1277 packet_generator_
.AddControlFrame(QuicFrame(new QuicRstStreamFrame(
1278 id
, AdjustErrorForVersion(error
, version()), bytes_written
)));
1280 sent_packet_manager_
.CancelRetransmissionsForStream(id
);
1281 // Remove all queued packets which only contain data for the reset stream.
1282 QueuedPacketList::iterator packet_iterator
= queued_packets_
.begin();
1283 while (packet_iterator
!= queued_packets_
.end()) {
1284 RetransmittableFrames
* retransmittable_frames
=
1285 packet_iterator
->serialized_packet
.retransmittable_frames
;
1286 if (!retransmittable_frames
) {
1290 retransmittable_frames
->RemoveFramesForStream(id
);
1291 if (!retransmittable_frames
->frames().empty()) {
1295 delete packet_iterator
->serialized_packet
.retransmittable_frames
;
1296 delete packet_iterator
->serialized_packet
.packet
;
1297 packet_iterator
->serialized_packet
.retransmittable_frames
= nullptr;
1298 packet_iterator
->serialized_packet
.packet
= nullptr;
1299 packet_iterator
= queued_packets_
.erase(packet_iterator
);
1303 void QuicConnection::SendWindowUpdate(QuicStreamId id
,
1304 QuicStreamOffset byte_offset
) {
1305 // Opportunistically bundle an ack with this outgoing packet.
1306 ScopedPacketBundler
ack_bundler(this, BUNDLE_PENDING_ACK
);
1307 packet_generator_
.AddControlFrame(
1308 QuicFrame(new QuicWindowUpdateFrame(id
, byte_offset
)));
1311 void QuicConnection::SendBlocked(QuicStreamId id
) {
1312 // Opportunistically bundle an ack with this outgoing packet.
1313 ScopedPacketBundler
ack_bundler(this, BUNDLE_PENDING_ACK
);
1314 packet_generator_
.AddControlFrame(QuicFrame(new QuicBlockedFrame(id
)));
1317 const QuicConnectionStats
& QuicConnection::GetStats() {
1318 const RttStats
* rtt_stats
= sent_packet_manager_
.GetRttStats();
1320 // Update rtt and estimated bandwidth.
1321 QuicTime::Delta min_rtt
= rtt_stats
->min_rtt();
1322 if (min_rtt
.IsZero()) {
1323 // If min RTT has not been set, use initial RTT instead.
1324 min_rtt
= QuicTime::Delta::FromMicroseconds(rtt_stats
->initial_rtt_us());
1326 stats_
.min_rtt_us
= min_rtt
.ToMicroseconds();
1328 QuicTime::Delta srtt
= rtt_stats
->smoothed_rtt();
1329 if (srtt
.IsZero()) {
1330 // If SRTT has not been set, use initial RTT instead.
1331 srtt
= QuicTime::Delta::FromMicroseconds(rtt_stats
->initial_rtt_us());
1333 stats_
.srtt_us
= srtt
.ToMicroseconds();
1335 stats_
.estimated_bandwidth
= sent_packet_manager_
.BandwidthEstimate();
1336 stats_
.max_packet_size
= packet_generator_
.GetMaxPacketLength();
1337 stats_
.max_received_packet_size
= largest_received_packet_size_
;
1341 void QuicConnection::ProcessUdpPacket(const IPEndPoint
& self_address
,
1342 const IPEndPoint
& peer_address
,
1343 const QuicEncryptedPacket
& packet
) {
1347 // TODO(rtenneti): Remove ScopedTracker below once crbug.com/462789 is fixed.
1348 tracked_objects::ScopedTracker
tracking_profile(
1349 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1350 "462789 QuicConnection::ProcessUdpPacket"));
1351 if (debug_visitor_
!= nullptr) {
1352 debug_visitor_
->OnPacketReceived(self_address
, peer_address
, packet
);
1354 last_size_
= packet
.length();
1356 CheckForAddressMigration(self_address
, peer_address
);
1358 stats_
.bytes_received
+= packet
.length();
1359 ++stats_
.packets_received
;
1361 ScopedRetransmissionScheduler
alarm_delayer(this);
1362 if (!framer_
.ProcessPacket(packet
)) {
1363 // If we are unable to decrypt this packet, it might be
1364 // because the CHLO or SHLO packet was lost.
1365 if (framer_
.error() == QUIC_DECRYPTION_FAILURE
) {
1366 if (encryption_level_
!= ENCRYPTION_FORWARD_SECURE
&&
1367 undecryptable_packets_
.size() < max_undecryptable_packets_
) {
1368 QueueUndecryptablePacket(packet
);
1369 } else if (debug_visitor_
!= nullptr) {
1370 debug_visitor_
->OnUndecryptablePacket();
1373 DVLOG(1) << ENDPOINT
<< "Unable to process packet. Last packet processed: "
1374 << last_header_
.packet_sequence_number
;
1378 ++stats_
.packets_processed
;
1379 MaybeProcessUndecryptablePackets();
1380 MaybeProcessRevivedPacket();
1381 MaybeSendInResponseToPacket();
1385 void QuicConnection::CheckForAddressMigration(
1386 const IPEndPoint
& self_address
, const IPEndPoint
& peer_address
) {
1387 peer_ip_changed_
= false;
1388 peer_port_changed_
= false;
1389 self_ip_changed_
= false;
1390 self_port_changed_
= false;
1392 if (peer_address_
.address().empty()) {
1393 peer_address_
= peer_address
;
1395 if (self_address_
.address().empty()) {
1396 self_address_
= self_address
;
1399 if (!peer_address
.address().empty() && !peer_address_
.address().empty()) {
1400 peer_ip_changed_
= (peer_address
.address() != peer_address_
.address());
1401 peer_port_changed_
= (peer_address
.port() != peer_address_
.port());
1403 // Store in case we want to migrate connection in ProcessValidatedPacket.
1404 migrating_peer_ip_
= peer_address
.address();
1405 migrating_peer_port_
= peer_address
.port();
1408 if (!self_address
.address().empty() && !self_address_
.address().empty()) {
1409 self_ip_changed_
= (self_address
.address() != self_address_
.address());
1410 self_port_changed_
= (self_address
.port() != self_address_
.port());
1414 void QuicConnection::OnCanWrite() {
1415 DCHECK(!writer_
->IsWriteBlocked());
1417 WriteQueuedPackets();
1418 WritePendingRetransmissions();
1420 // Sending queued packets may have caused the socket to become write blocked,
1421 // or the congestion manager to prohibit sending. If we've sent everything
1422 // we had queued and we're still not blocked, let the visitor know it can
1424 if (!CanWrite(HAS_RETRANSMITTABLE_DATA
)) {
1428 { // Limit the scope of the bundler. ACK inclusion happens elsewhere.
1429 ScopedPacketBundler
bundler(this, NO_ACK
);
1430 visitor_
->OnCanWrite();
1433 // After the visitor writes, it may have caused the socket to become write
1434 // blocked or the congestion manager to prohibit sending, so check again.
1435 if (visitor_
->WillingAndAbleToWrite() &&
1436 !resume_writes_alarm_
->IsSet() &&
1437 CanWrite(HAS_RETRANSMITTABLE_DATA
)) {
1438 // We're not write blocked, but some stream didn't write out all of its
1439 // bytes. Register for 'immediate' resumption so we'll keep writing after
1440 // other connections and events have had a chance to use the thread.
1441 resume_writes_alarm_
->Set(clock_
->ApproximateNow());
1445 void QuicConnection::WriteIfNotBlocked() {
1446 if (!writer_
->IsWriteBlocked()) {
1451 bool QuicConnection::ProcessValidatedPacket() {
1452 if ((peer_ip_changed_
&& !FLAGS_quic_allow_ip_migration
) ||
1453 self_ip_changed_
|| self_port_changed_
) {
1454 SendConnectionCloseWithDetails(
1455 QUIC_ERROR_MIGRATING_ADDRESS
,
1456 "Neither IP address migration, nor self port migration are supported.");
1460 // TODO(fayang): Use peer_address_changed_ instead of peer_ip_changed_ and
1461 // peer_port_changed_ once FLAGS_quic_allow_ip_migration is deprecated.
1462 if (peer_ip_changed_
|| peer_port_changed_
) {
1463 IPEndPoint old_peer_address
= peer_address_
;
1464 peer_address_
= IPEndPoint(
1465 peer_ip_changed_
? migrating_peer_ip_
: peer_address_
.address(),
1466 peer_port_changed_
? migrating_peer_port_
: peer_address_
.port());
1468 DVLOG(1) << ENDPOINT
<< "Peer's ip:port changed from "
1469 << old_peer_address
.ToString() << " to "
1470 << peer_address_
.ToString() << ", migrating connection.";
1473 time_of_last_received_packet_
= clock_
->Now();
1474 DVLOG(1) << ENDPOINT
<< "time of last received packet: "
1475 << time_of_last_received_packet_
.ToDebuggingValue();
1477 if (last_size_
> largest_received_packet_size_
) {
1478 largest_received_packet_size_
= last_size_
;
1481 if (perspective_
== Perspective::IS_SERVER
&&
1482 encryption_level_
== ENCRYPTION_NONE
&&
1483 last_size_
> packet_generator_
.GetMaxPacketLength()) {
1484 set_max_packet_length(last_size_
);
1489 void QuicConnection::WriteQueuedPackets() {
1490 DCHECK(!writer_
->IsWriteBlocked());
1492 if (pending_version_negotiation_packet_
) {
1493 SendVersionNegotiationPacket();
1496 QueuedPacketList::iterator packet_iterator
= queued_packets_
.begin();
1497 while (packet_iterator
!= queued_packets_
.end() &&
1498 WritePacket(&(*packet_iterator
))) {
1499 packet_iterator
= queued_packets_
.erase(packet_iterator
);
1503 void QuicConnection::WritePendingRetransmissions() {
1504 // Keep writing as long as there's a pending retransmission which can be
1506 while (sent_packet_manager_
.HasPendingRetransmissions()) {
1507 const QuicSentPacketManager::PendingRetransmission pending
=
1508 sent_packet_manager_
.NextPendingRetransmission();
1509 if (!CanWrite(HAS_RETRANSMITTABLE_DATA
)) {
1513 // Re-packetize the frames with a new sequence number for retransmission.
1514 // Retransmitted data packets do not use FEC, even when it's enabled.
1515 // Retransmitted packets use the same sequence number length as the
1517 // Flush the packet generator before making a new packet.
1518 // TODO(ianswett): Implement ReserializeAllFrames as a separate path that
1519 // does not require the creator to be flushed.
1520 packet_generator_
.FlushAllQueuedFrames();
1521 char buffer
[kMaxPacketSize
];
1522 SerializedPacket serialized_packet
= packet_generator_
.ReserializeAllFrames(
1523 pending
.retransmittable_frames
, pending
.sequence_number_length
, buffer
,
1525 if (serialized_packet
.packet
== nullptr) {
1526 // We failed to serialize the packet, so close the connection.
1527 // CloseConnection does not send close packet, so no infinite loop here.
1528 CloseConnection(QUIC_ENCRYPTION_FAILURE
, false);
1532 DVLOG(1) << ENDPOINT
<< "Retransmitting " << pending
.sequence_number
1533 << " as " << serialized_packet
.sequence_number
;
1535 QueuedPacket(serialized_packet
,
1536 pending
.retransmittable_frames
.encryption_level(),
1537 pending
.transmission_type
,
1538 pending
.sequence_number
));
1542 void QuicConnection::RetransmitUnackedPackets(
1543 TransmissionType retransmission_type
) {
1544 sent_packet_manager_
.RetransmitUnackedPackets(retransmission_type
);
1546 WriteIfNotBlocked();
1549 void QuicConnection::NeuterUnencryptedPackets() {
1550 sent_packet_manager_
.NeuterUnencryptedPackets();
1551 // This may have changed the retransmission timer, so re-arm it.
1552 SetRetransmissionAlarm();
1555 bool QuicConnection::ShouldGeneratePacket(
1556 HasRetransmittableData retransmittable
,
1557 IsHandshake handshake
) {
1558 // We should serialize handshake packets immediately to ensure that they
1559 // end up sent at the right encryption level.
1560 if (handshake
== IS_HANDSHAKE
) {
1564 return CanWrite(retransmittable
);
1567 bool QuicConnection::CanWrite(HasRetransmittableData retransmittable
) {
1572 if (writer_
->IsWriteBlocked()) {
1573 visitor_
->OnWriteBlocked();
1577 QuicTime now
= clock_
->Now();
1578 QuicTime::Delta delay
= sent_packet_manager_
.TimeUntilSend(
1579 now
, retransmittable
);
1580 if (delay
.IsInfinite()) {
1581 send_alarm_
->Cancel();
1585 // If the scheduler requires a delay, then we can not send this packet now.
1586 if (!delay
.IsZero()) {
1587 send_alarm_
->Update(now
.Add(delay
), QuicTime::Delta::FromMilliseconds(1));
1588 DVLOG(1) << ENDPOINT
<< "Delaying sending " << delay
.ToMilliseconds()
1592 send_alarm_
->Cancel();
1596 bool QuicConnection::WritePacket(QueuedPacket
* packet
) {
1597 if (!WritePacketInner(packet
)) {
1600 delete packet
->serialized_packet
.retransmittable_frames
;
1601 delete packet
->serialized_packet
.packet
;
1602 packet
->serialized_packet
.retransmittable_frames
= nullptr;
1603 packet
->serialized_packet
.packet
= nullptr;
1607 bool QuicConnection::WritePacketInner(QueuedPacket
* packet
) {
1608 if (ShouldDiscardPacket(*packet
)) {
1609 ++stats_
.packets_discarded
;
1612 // Connection close packets are encrypted and saved, so don't exit early.
1613 const bool is_connection_close
= IsConnectionClose(*packet
);
1614 if (writer_
->IsWriteBlocked() && !is_connection_close
) {
1618 QuicPacketSequenceNumber sequence_number
=
1619 packet
->serialized_packet
.sequence_number
;
1620 DCHECK_LE(sequence_number_of_last_sent_packet_
, sequence_number
);
1621 sequence_number_of_last_sent_packet_
= sequence_number
;
1623 QuicEncryptedPacket
* encrypted
= packet
->serialized_packet
.packet
;
1624 // Connection close packets are eventually owned by TimeWaitListManager.
1625 // Others are deleted at the end of this call.
1626 if (is_connection_close
) {
1627 DCHECK(connection_close_packet_
.get() == nullptr);
1628 // Clone the packet so it's owned in the future.
1629 connection_close_packet_
.reset(encrypted
->Clone());
1630 // This assures we won't try to write *forced* packets when blocked.
1631 // Return true to stop processing.
1632 if (writer_
->IsWriteBlocked()) {
1633 visitor_
->OnWriteBlocked();
1638 if (!FLAGS_quic_allow_oversized_packets_for_test
) {
1639 DCHECK_LE(encrypted
->length(), kMaxPacketSize
);
1641 DCHECK_LE(encrypted
->length(), packet_generator_
.GetMaxPacketLength());
1642 DVLOG(1) << ENDPOINT
<< "Sending packet " << sequence_number
<< " : "
1643 << (packet
->serialized_packet
.is_fec_packet
1645 : (IsRetransmittable(*packet
) == HAS_RETRANSMITTABLE_DATA
1647 : " ack only ")) << ", encryption level: "
1648 << QuicUtils::EncryptionLevelToString(packet
->encryption_level
)
1649 << ", encrypted length:" << encrypted
->length();
1650 DVLOG(2) << ENDPOINT
<< "packet(" << sequence_number
<< "): " << std::endl
1651 << QuicUtils::StringToHexASCIIDump(encrypted
->AsStringPiece());
1653 // Measure the RTT from before the write begins to avoid underestimating the
1654 // min_rtt_, especially in cases where the thread blocks or gets swapped out
1655 // during the WritePacket below.
1656 QuicTime packet_send_time
= clock_
->Now();
1657 WriteResult result
= writer_
->WritePacket(encrypted
->data(),
1658 encrypted
->length(),
1659 self_address().address(),
1661 if (result
.error_code
== ERR_IO_PENDING
) {
1662 DCHECK_EQ(WRITE_STATUS_BLOCKED
, result
.status
);
1665 if (result
.status
== WRITE_STATUS_BLOCKED
) {
1666 visitor_
->OnWriteBlocked();
1667 // If the socket buffers the the data, then the packet should not
1668 // be queued and sent again, which would result in an unnecessary
1669 // duplicate packet being sent. The helper must call OnCanWrite
1670 // when the write completes, and OnWriteError if an error occurs.
1671 if (!writer_
->IsWriteBlockedDataBuffered()) {
1675 if (result
.status
!= WRITE_STATUS_ERROR
&& debug_visitor_
!= nullptr) {
1676 // Pass the write result to the visitor.
1677 debug_visitor_
->OnPacketSent(packet
->serialized_packet
,
1678 packet
->original_sequence_number
,
1679 packet
->encryption_level
,
1680 packet
->transmission_type
,
1684 if (packet
->transmission_type
== NOT_RETRANSMISSION
) {
1685 time_of_last_sent_new_packet_
= packet_send_time
;
1688 MaybeSetFecAlarm(sequence_number
);
1690 DVLOG(1) << ENDPOINT
<< "time we began writing last sent packet: "
1691 << packet_send_time
.ToDebuggingValue();
1693 // TODO(ianswett): Change the sequence number length and other packet creator
1694 // options by a more explicit API than setting a struct value directly,
1695 // perhaps via the NetworkChangeVisitor.
1696 packet_generator_
.UpdateSequenceNumberLength(
1697 sent_packet_manager_
.least_packet_awaited_by_peer(),
1698 sent_packet_manager_
.EstimateMaxPacketsInFlight(max_packet_length()));
1700 bool reset_retransmission_alarm
= sent_packet_manager_
.OnPacketSent(
1701 &packet
->serialized_packet
,
1702 packet
->original_sequence_number
,
1704 encrypted
->length(),
1705 packet
->transmission_type
,
1706 IsRetransmittable(*packet
));
1708 if (reset_retransmission_alarm
|| !retransmission_alarm_
->IsSet()) {
1709 SetRetransmissionAlarm();
1712 stats_
.bytes_sent
+= result
.bytes_written
;
1713 ++stats_
.packets_sent
;
1714 if (packet
->transmission_type
!= NOT_RETRANSMISSION
) {
1715 stats_
.bytes_retransmitted
+= result
.bytes_written
;
1716 ++stats_
.packets_retransmitted
;
1719 if (result
.status
== WRITE_STATUS_ERROR
) {
1720 OnWriteError(result
.error_code
);
1721 DLOG(ERROR
) << ENDPOINT
<< "failed writing " << encrypted
->length()
1723 << " from host " << self_address().ToStringWithoutPort()
1724 << " to address " << peer_address().ToString();
1731 bool QuicConnection::ShouldDiscardPacket(const QueuedPacket
& packet
) {
1733 DVLOG(1) << ENDPOINT
1734 << "Not sending packet as connection is disconnected.";
1738 QuicPacketSequenceNumber sequence_number
=
1739 packet
.serialized_packet
.sequence_number
;
1740 if (encryption_level_
== ENCRYPTION_FORWARD_SECURE
&&
1741 packet
.encryption_level
== ENCRYPTION_NONE
) {
1742 // Drop packets that are NULL encrypted since the peer won't accept them
1744 DVLOG(1) << ENDPOINT
<< "Dropping NULL encrypted packet: "
1745 << sequence_number
<< " since the connection is forward secure.";
1749 // If a retransmission has been acked before sending, don't send it.
1750 // This occurs if a packet gets serialized, queued, then discarded.
1751 if (packet
.transmission_type
!= NOT_RETRANSMISSION
&&
1752 (!sent_packet_manager_
.IsUnacked(packet
.original_sequence_number
) ||
1753 !sent_packet_manager_
.HasRetransmittableFrames(
1754 packet
.original_sequence_number
))) {
1755 DVLOG(1) << ENDPOINT
<< "Dropping unacked packet: " << sequence_number
1756 << " A previous transmission was acked while write blocked.";
1763 void QuicConnection::OnWriteError(int error_code
) {
1764 DVLOG(1) << ENDPOINT
<< "Write failed with error: " << error_code
1765 << " (" << ErrorToString(error_code
) << ")";
1766 // We can't send an error as the socket is presumably borked.
1767 CloseConnection(QUIC_PACKET_WRITE_ERROR
, false);
1770 void QuicConnection::OnSerializedPacket(
1771 const SerializedPacket
& serialized_packet
) {
1772 if (serialized_packet
.packet
== nullptr) {
1773 // We failed to serialize the packet, so close the connection.
1774 // CloseConnection does not send close packet, so no infinite loop here.
1775 CloseConnection(QUIC_ENCRYPTION_FAILURE
, false);
1778 sent_packet_manager_
.OnSerializedPacket(serialized_packet
);
1779 if (serialized_packet
.is_fec_packet
&& fec_alarm_
->IsSet()) {
1780 // If an FEC packet is serialized with the FEC alarm set, cancel the alarm.
1781 fec_alarm_
->Cancel();
1783 SendOrQueuePacket(QueuedPacket(serialized_packet
, encryption_level_
));
1786 void QuicConnection::OnResetFecGroup() {
1787 if (!fec_alarm_
->IsSet()) {
1790 // If an FEC Group is closed with the FEC alarm set, cancel the alarm.
1791 fec_alarm_
->Cancel();
1794 void QuicConnection::OnCongestionWindowChange() {
1795 packet_generator_
.OnCongestionWindowChange(
1796 sent_packet_manager_
.EstimateMaxPacketsInFlight(max_packet_length()));
1797 visitor_
->OnCongestionWindowChange(clock_
->ApproximateNow());
1800 void QuicConnection::OnRttChange() {
1801 // Uses the connection's smoothed RTT. If zero, uses initial_rtt.
1802 QuicTime::Delta rtt
= sent_packet_manager_
.GetRttStats()->smoothed_rtt();
1804 rtt
= QuicTime::Delta::FromMicroseconds(
1805 sent_packet_manager_
.GetRttStats()->initial_rtt_us());
1807 packet_generator_
.OnRttChange(rtt
);
1810 void QuicConnection::OnHandshakeComplete() {
1811 sent_packet_manager_
.SetHandshakeConfirmed();
1812 // The client should immediately ack the SHLO to confirm the handshake is
1813 // complete with the server.
1814 if (perspective_
== Perspective::IS_CLIENT
&& !ack_queued_
) {
1815 ack_alarm_
->Cancel();
1816 ack_alarm_
->Set(clock_
->ApproximateNow());
1820 void QuicConnection::SendOrQueuePacket(QueuedPacket packet
) {
1821 // The caller of this function is responsible for checking CanWrite().
1822 if (packet
.serialized_packet
.packet
== nullptr) {
1824 << "packet.serialized_packet.packet == nullptr in to SendOrQueuePacket";
1828 sent_entropy_manager_
.RecordPacketEntropyHash(
1829 packet
.serialized_packet
.sequence_number
,
1830 packet
.serialized_packet
.entropy_hash
);
1831 if (!WritePacket(&packet
)) {
1832 // Take ownership of the underlying encrypted packet.
1833 if (!packet
.serialized_packet
.packet
->owns_buffer()) {
1834 scoped_ptr
<QuicEncryptedPacket
> encrypted_deleter(
1835 packet
.serialized_packet
.packet
);
1836 packet
.serialized_packet
.packet
=
1837 packet
.serialized_packet
.packet
->Clone();
1839 queued_packets_
.push_back(packet
);
1842 // If a forward-secure encrypter is available but is not being used and the
1843 // next sequence number is the first packet which requires
1844 // forward security, start using the forward-secure encrypter.
1845 if (encryption_level_
!= ENCRYPTION_FORWARD_SECURE
&&
1846 has_forward_secure_encrypter_
&&
1847 packet
.serialized_packet
.sequence_number
>=
1848 first_required_forward_secure_packet_
- 1) {
1849 SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE
);
1853 void QuicConnection::SendPing() {
1854 if (retransmission_alarm_
->IsSet()) {
1857 packet_generator_
.AddControlFrame(QuicFrame(new QuicPingFrame
));
1860 void QuicConnection::SendAck() {
1861 ack_alarm_
->Cancel();
1862 ack_queued_
= false;
1863 stop_waiting_count_
= 0;
1864 num_packets_received_since_last_ack_sent_
= 0;
1866 packet_generator_
.SetShouldSendAck(true);
1869 void QuicConnection::OnRetransmissionTimeout() {
1870 if (!sent_packet_manager_
.HasUnackedPackets()) {
1874 sent_packet_manager_
.OnRetransmissionTimeout();
1875 WriteIfNotBlocked();
1877 // A write failure can result in the connection being closed, don't attempt to
1878 // write further packets, or to set alarms.
1883 // In the TLP case, the SentPacketManager gives the connection the opportunity
1884 // to send new data before retransmitting.
1885 if (sent_packet_manager_
.MaybeRetransmitTailLossProbe()) {
1886 // Send the pending retransmission now that it's been queued.
1887 WriteIfNotBlocked();
1890 // Ensure the retransmission alarm is always set if there are unacked packets
1891 // and nothing waiting to be sent.
1892 // This happens if the loss algorithm invokes a timer based loss, but the
1893 // packet doesn't need to be retransmitted.
1894 if (!HasQueuedData() && !retransmission_alarm_
->IsSet()) {
1895 SetRetransmissionAlarm();
1899 void QuicConnection::SetEncrypter(EncryptionLevel level
,
1900 QuicEncrypter
* encrypter
) {
1901 packet_generator_
.SetEncrypter(level
, encrypter
);
1902 if (level
== ENCRYPTION_FORWARD_SECURE
) {
1903 has_forward_secure_encrypter_
= true;
1904 first_required_forward_secure_packet_
=
1905 sequence_number_of_last_sent_packet_
+
1906 // 3 times the current congestion window (in slow start) should cover
1907 // about two full round trips worth of packets, which should be
1909 3 * sent_packet_manager_
.EstimateMaxPacketsInFlight(
1910 max_packet_length());
1914 void QuicConnection::SetDefaultEncryptionLevel(EncryptionLevel level
) {
1915 encryption_level_
= level
;
1916 packet_generator_
.set_encryption_level(level
);
1919 void QuicConnection::SetDecrypter(EncryptionLevel level
,
1920 QuicDecrypter
* decrypter
) {
1921 framer_
.SetDecrypter(level
, decrypter
);
1924 void QuicConnection::SetAlternativeDecrypter(EncryptionLevel level
,
1925 QuicDecrypter
* decrypter
,
1926 bool latch_once_used
) {
1927 framer_
.SetAlternativeDecrypter(level
, decrypter
, latch_once_used
);
1930 const QuicDecrypter
* QuicConnection::decrypter() const {
1931 return framer_
.decrypter();
1934 const QuicDecrypter
* QuicConnection::alternative_decrypter() const {
1935 return framer_
.alternative_decrypter();
1938 void QuicConnection::QueueUndecryptablePacket(
1939 const QuicEncryptedPacket
& packet
) {
1940 DVLOG(1) << ENDPOINT
<< "Queueing undecryptable packet.";
1941 undecryptable_packets_
.push_back(packet
.Clone());
1944 void QuicConnection::MaybeProcessUndecryptablePackets() {
1945 if (undecryptable_packets_
.empty() || encryption_level_
== ENCRYPTION_NONE
) {
1949 while (connected_
&& !undecryptable_packets_
.empty()) {
1950 DVLOG(1) << ENDPOINT
<< "Attempting to process undecryptable packet";
1951 QuicEncryptedPacket
* packet
= undecryptable_packets_
.front();
1952 if (!framer_
.ProcessPacket(*packet
) &&
1953 framer_
.error() == QUIC_DECRYPTION_FAILURE
) {
1954 DVLOG(1) << ENDPOINT
<< "Unable to process undecryptable packet...";
1957 DVLOG(1) << ENDPOINT
<< "Processed undecryptable packet!";
1958 ++stats_
.packets_processed
;
1960 undecryptable_packets_
.pop_front();
1963 // Once forward secure encryption is in use, there will be no
1964 // new keys installed and hence any undecryptable packets will
1965 // never be able to be decrypted.
1966 if (encryption_level_
== ENCRYPTION_FORWARD_SECURE
) {
1967 if (debug_visitor_
!= nullptr) {
1968 // TODO(rtenneti): perhaps more efficient to pass the number of
1969 // undecryptable packets as the argument to OnUndecryptablePacket so that
1970 // we just need to call OnUndecryptablePacket once?
1971 for (size_t i
= 0; i
< undecryptable_packets_
.size(); ++i
) {
1972 debug_visitor_
->OnUndecryptablePacket();
1975 STLDeleteElements(&undecryptable_packets_
);
1979 void QuicConnection::MaybeProcessRevivedPacket() {
1980 QuicFecGroup
* group
= GetFecGroup();
1981 if (!connected_
|| group
== nullptr || !group
->CanRevive()) {
1984 QuicPacketHeader revived_header
;
1985 char revived_payload
[kMaxPacketSize
];
1986 size_t len
= group
->Revive(&revived_header
, revived_payload
, kMaxPacketSize
);
1987 revived_header
.public_header
.connection_id
= connection_id_
;
1988 revived_header
.public_header
.connection_id_length
=
1989 last_header_
.public_header
.connection_id_length
;
1990 revived_header
.public_header
.version_flag
= false;
1991 revived_header
.public_header
.reset_flag
= false;
1992 revived_header
.public_header
.sequence_number_length
=
1993 last_header_
.public_header
.sequence_number_length
;
1994 revived_header
.fec_flag
= false;
1995 revived_header
.is_in_fec_group
= NOT_IN_FEC_GROUP
;
1996 revived_header
.fec_group
= 0;
1997 group_map_
.erase(last_header_
.fec_group
);
1998 last_decrypted_packet_level_
= group
->effective_encryption_level();
1999 DCHECK_LT(last_decrypted_packet_level_
, NUM_ENCRYPTION_LEVELS
);
2002 last_packet_revived_
= true;
2003 if (debug_visitor_
!= nullptr) {
2004 debug_visitor_
->OnRevivedPacket(revived_header
,
2005 StringPiece(revived_payload
, len
));
2008 ++stats_
.packets_revived
;
2009 framer_
.ProcessRevivedPacket(&revived_header
,
2010 StringPiece(revived_payload
, len
));
2013 QuicFecGroup
* QuicConnection::GetFecGroup() {
2014 QuicFecGroupNumber fec_group_num
= last_header_
.fec_group
;
2015 if (fec_group_num
== 0) {
2018 if (!ContainsKey(group_map_
, fec_group_num
)) {
2019 if (group_map_
.size() >= kMaxFecGroups
) { // Too many groups
2020 if (fec_group_num
< group_map_
.begin()->first
) {
2021 // The group being requested is a group we've seen before and deleted.
2022 // Don't recreate it.
2025 // Clear the lowest group number.
2026 delete group_map_
.begin()->second
;
2027 group_map_
.erase(group_map_
.begin());
2029 group_map_
[fec_group_num
] = new QuicFecGroup();
2031 return group_map_
[fec_group_num
];
2034 void QuicConnection::SendConnectionClose(QuicErrorCode error
) {
2035 SendConnectionCloseWithDetails(error
, string());
2038 void QuicConnection::SendConnectionCloseWithDetails(QuicErrorCode error
,
2039 const string
& details
) {
2040 // If we're write blocked, WritePacket() will not send, but will capture the
2041 // serialized packet.
2042 SendConnectionClosePacket(error
, details
);
2043 CloseConnection(error
, false);
2046 void QuicConnection::SendConnectionClosePacket(QuicErrorCode error
,
2047 const string
& details
) {
2048 DVLOG(1) << ENDPOINT
<< "Force closing " << connection_id()
2049 << " with error " << QuicUtils::ErrorToString(error
)
2050 << " (" << error
<< ") " << details
;
2051 // Don't send explicit connection close packets for timeouts.
2052 // This is particularly important on mobile, where connections are short.
2053 if (silent_close_enabled_
&&
2054 error
== QuicErrorCode::QUIC_CONNECTION_TIMED_OUT
) {
2057 ScopedPacketBundler
ack_bundler(this, SEND_ACK
);
2058 QuicConnectionCloseFrame
* frame
= new QuicConnectionCloseFrame();
2059 frame
->error_code
= error
;
2060 frame
->error_details
= details
;
2061 packet_generator_
.AddControlFrame(QuicFrame(frame
));
2062 packet_generator_
.FlushAllQueuedFrames();
2065 void QuicConnection::CloseConnection(QuicErrorCode error
, bool from_peer
) {
2067 DVLOG(1) << "Connection is already closed.";
2071 if (debug_visitor_
!= nullptr) {
2072 debug_visitor_
->OnConnectionClosed(error
, from_peer
);
2074 DCHECK(visitor_
!= nullptr);
2075 visitor_
->OnConnectionClosed(error
, from_peer
);
2076 // Cancel the alarms so they don't trigger any action now that the
2077 // connection is closed.
2078 ack_alarm_
->Cancel();
2079 ping_alarm_
->Cancel();
2080 fec_alarm_
->Cancel();
2081 resume_writes_alarm_
->Cancel();
2082 retransmission_alarm_
->Cancel();
2083 send_alarm_
->Cancel();
2084 timeout_alarm_
->Cancel();
2085 mtu_discovery_alarm_
->Cancel();
2088 void QuicConnection::SendGoAway(QuicErrorCode error
,
2089 QuicStreamId last_good_stream_id
,
2090 const string
& reason
) {
2091 DVLOG(1) << ENDPOINT
<< "Going away with error "
2092 << QuicUtils::ErrorToString(error
)
2093 << " (" << error
<< ")";
2095 // Opportunistically bundle an ack with this outgoing packet.
2096 ScopedPacketBundler
ack_bundler(this, BUNDLE_PENDING_ACK
);
2097 packet_generator_
.AddControlFrame(
2098 QuicFrame(new QuicGoAwayFrame(error
, last_good_stream_id
, reason
)));
2101 void QuicConnection::CloseFecGroupsBefore(
2102 QuicPacketSequenceNumber sequence_number
) {
2103 FecGroupMap::iterator it
= group_map_
.begin();
2104 while (it
!= group_map_
.end()) {
2105 // If this is the current group or the group doesn't protect this packet
2106 // we can ignore it.
2107 if (last_header_
.fec_group
== it
->first
||
2108 !it
->second
->ProtectsPacketsBefore(sequence_number
)) {
2112 QuicFecGroup
* fec_group
= it
->second
;
2113 DCHECK(!fec_group
->CanRevive());
2114 FecGroupMap::iterator next
= it
;
2116 group_map_
.erase(it
);
2122 QuicByteCount
QuicConnection::max_packet_length() const {
2123 return packet_generator_
.GetMaxPacketLength();
2126 void QuicConnection::set_max_packet_length(QuicByteCount length
) {
2127 return packet_generator_
.SetMaxPacketLength(length
, /*force=*/false);
2130 bool QuicConnection::HasQueuedData() const {
2131 return pending_version_negotiation_packet_
||
2132 !queued_packets_
.empty() || packet_generator_
.HasQueuedFrames();
2135 bool QuicConnection::CanWriteStreamData() {
2136 // Don't write stream data if there are negotiation or queued data packets
2137 // to send. Otherwise, continue and bundle as many frames as possible.
2138 if (pending_version_negotiation_packet_
|| !queued_packets_
.empty()) {
2142 IsHandshake pending_handshake
= visitor_
->HasPendingHandshake() ?
2143 IS_HANDSHAKE
: NOT_HANDSHAKE
;
2144 // Sending queued packets may have caused the socket to become write blocked,
2145 // or the congestion manager to prohibit sending. If we've sent everything
2146 // we had queued and we're still not blocked, let the visitor know it can
2148 return ShouldGeneratePacket(HAS_RETRANSMITTABLE_DATA
, pending_handshake
);
2151 void QuicConnection::SetNetworkTimeouts(QuicTime::Delta overall_timeout
,
2152 QuicTime::Delta idle_timeout
) {
2153 LOG_IF(DFATAL
, idle_timeout
> overall_timeout
)
2154 << "idle_timeout:" << idle_timeout
.ToMilliseconds()
2155 << " overall_timeout:" << overall_timeout
.ToMilliseconds();
2156 // Adjust the idle timeout on client and server to prevent clients from
2157 // sending requests to servers which have already closed the connection.
2158 if (perspective_
== Perspective::IS_SERVER
) {
2159 idle_timeout
= idle_timeout
.Add(QuicTime::Delta::FromSeconds(3));
2160 } else if (idle_timeout
> QuicTime::Delta::FromSeconds(1)) {
2161 idle_timeout
= idle_timeout
.Subtract(QuicTime::Delta::FromSeconds(1));
2163 overall_connection_timeout_
= overall_timeout
;
2164 idle_network_timeout_
= idle_timeout
;
2169 void QuicConnection::CheckForTimeout() {
2170 QuicTime now
= clock_
->ApproximateNow();
2171 QuicTime time_of_last_packet
= max(time_of_last_received_packet_
,
2172 time_of_last_sent_new_packet_
);
2174 // |delta| can be < 0 as |now| is approximate time but |time_of_last_packet|
2175 // is accurate time. However, this should not change the behavior of
2176 // timeout handling.
2177 QuicTime::Delta idle_duration
= now
.Subtract(time_of_last_packet
);
2178 DVLOG(1) << ENDPOINT
<< "last packet "
2179 << time_of_last_packet
.ToDebuggingValue()
2180 << " now:" << now
.ToDebuggingValue()
2181 << " idle_duration:" << idle_duration
.ToMicroseconds()
2182 << " idle_network_timeout: "
2183 << idle_network_timeout_
.ToMicroseconds();
2184 if (idle_duration
>= idle_network_timeout_
) {
2185 DVLOG(1) << ENDPOINT
<< "Connection timedout due to no network activity.";
2186 SendConnectionClose(QUIC_CONNECTION_TIMED_OUT
);
2190 if (!overall_connection_timeout_
.IsInfinite()) {
2191 QuicTime::Delta connected_duration
=
2192 now
.Subtract(stats_
.connection_creation_time
);
2193 DVLOG(1) << ENDPOINT
<< "connection time: "
2194 << connected_duration
.ToMicroseconds() << " overall timeout: "
2195 << overall_connection_timeout_
.ToMicroseconds();
2196 if (connected_duration
>= overall_connection_timeout_
) {
2197 DVLOG(1) << ENDPOINT
<<
2198 "Connection timedout due to overall connection timeout.";
2199 SendConnectionClose(QUIC_CONNECTION_OVERALL_TIMED_OUT
);
2207 void QuicConnection::SetTimeoutAlarm() {
2208 QuicTime time_of_last_packet
= max(time_of_last_received_packet_
,
2209 time_of_last_sent_new_packet_
);
2211 QuicTime deadline
= time_of_last_packet
.Add(idle_network_timeout_
);
2212 if (!overall_connection_timeout_
.IsInfinite()) {
2213 deadline
= min(deadline
,
2214 stats_
.connection_creation_time
.Add(
2215 overall_connection_timeout_
));
2218 timeout_alarm_
->Cancel();
2219 timeout_alarm_
->Set(deadline
);
2222 void QuicConnection::SetPingAlarm() {
2223 if (perspective_
== Perspective::IS_SERVER
) {
2224 // Only clients send pings.
2227 if (!visitor_
->HasOpenDynamicStreams()) {
2228 ping_alarm_
->Cancel();
2229 // Don't send a ping unless there are open streams.
2232 QuicTime::Delta ping_timeout
= QuicTime::Delta::FromSeconds(kPingTimeoutSecs
);
2233 ping_alarm_
->Update(clock_
->ApproximateNow().Add(ping_timeout
),
2234 QuicTime::Delta::FromSeconds(1));
2237 void QuicConnection::SetRetransmissionAlarm() {
2238 if (delay_setting_retransmission_alarm_
) {
2239 pending_retransmission_alarm_
= true;
2242 QuicTime retransmission_time
= sent_packet_manager_
.GetRetransmissionTime();
2243 retransmission_alarm_
->Update(retransmission_time
,
2244 QuicTime::Delta::FromMilliseconds(1));
2247 void QuicConnection::MaybeSetMtuAlarm() {
2248 if (!FLAGS_quic_do_path_mtu_discovery
) {
2252 // Do not set the alarm if the target size is less than the current size.
2253 // This covers the case when |mtu_discovery_target_| is at its default value,
2255 if (mtu_discovery_target_
<= max_packet_length()) {
2259 if (mtu_probe_count_
>= kMtuDiscoveryAttempts
) {
2263 if (mtu_discovery_alarm_
->IsSet()) {
2267 if (sequence_number_of_last_sent_packet_
>= next_mtu_probe_at_
) {
2268 // Use an alarm to send the MTU probe to ensure that no ScopedPacketBundlers
2270 mtu_discovery_alarm_
->Set(clock_
->ApproximateNow());
2274 QuicConnection::ScopedPacketBundler::ScopedPacketBundler(
2275 QuicConnection
* connection
,
2276 AckBundling send_ack
)
2277 : connection_(connection
),
2278 already_in_batch_mode_(connection
!= nullptr &&
2279 connection
->packet_generator_
.InBatchMode()) {
2280 if (connection_
== nullptr) {
2283 // Move generator into batch mode. If caller wants us to include an ack,
2284 // check the delayed-ack timer to see if there's ack info to be sent.
2285 if (!already_in_batch_mode_
) {
2286 DVLOG(1) << "Entering Batch Mode.";
2287 connection_
->packet_generator_
.StartBatchOperations();
2289 // Bundle an ack if the alarm is set or with every second packet if we need to
2290 // raise the peer's least unacked.
2292 connection_
->ack_alarm_
->IsSet() || connection_
->stop_waiting_count_
> 1;
2293 if (send_ack
== SEND_ACK
|| (send_ack
== BUNDLE_PENDING_ACK
&& ack_pending
)) {
2294 DVLOG(1) << "Bundling ack with outgoing packet.";
2295 connection_
->SendAck();
2299 QuicConnection::ScopedPacketBundler::~ScopedPacketBundler() {
2300 if (connection_
== nullptr) {
2303 // If we changed the generator's batch state, restore original batch state.
2304 if (!already_in_batch_mode_
) {
2305 DVLOG(1) << "Leaving Batch Mode.";
2306 connection_
->packet_generator_
.FinishBatchOperations();
2308 DCHECK_EQ(already_in_batch_mode_
,
2309 connection_
->packet_generator_
.InBatchMode());
2312 QuicConnection::ScopedRetransmissionScheduler::ScopedRetransmissionScheduler(
2313 QuicConnection
* connection
)
2314 : connection_(connection
),
2315 already_delayed_(connection_
->delay_setting_retransmission_alarm_
) {
2316 connection_
->delay_setting_retransmission_alarm_
= true;
2319 QuicConnection::ScopedRetransmissionScheduler::
2320 ~ScopedRetransmissionScheduler() {
2321 if (already_delayed_
) {
2324 connection_
->delay_setting_retransmission_alarm_
= false;
2325 if (connection_
->pending_retransmission_alarm_
) {
2326 connection_
->SetRetransmissionAlarm();
2327 connection_
->pending_retransmission_alarm_
= false;
2331 HasRetransmittableData
QuicConnection::IsRetransmittable(
2332 const QueuedPacket
& packet
) {
2333 // Retransmitted packets retransmittable frames are owned by the unacked
2334 // packet map, but are not present in the serialized packet.
2335 if (packet
.transmission_type
!= NOT_RETRANSMISSION
||
2336 packet
.serialized_packet
.retransmittable_frames
!= nullptr) {
2337 return HAS_RETRANSMITTABLE_DATA
;
2339 return NO_RETRANSMITTABLE_DATA
;
2343 bool QuicConnection::IsConnectionClose(const QueuedPacket
& packet
) {
2344 const RetransmittableFrames
* retransmittable_frames
=
2345 packet
.serialized_packet
.retransmittable_frames
;
2346 if (retransmittable_frames
== nullptr) {
2349 for (const QuicFrame
& frame
: retransmittable_frames
->frames()) {
2350 if (frame
.type
== CONNECTION_CLOSE_FRAME
) {
2357 void QuicConnection::SendMtuDiscoveryPacket(QuicByteCount target_mtu
) {
2358 // Create a listener for the new probe. The ownership of the listener is
2359 // transferred to the AckNotifierManager. The notifier will get destroyed
2360 // before the connection (because it's stored in one of the connection's
2361 // subfields), hence |this| pointer is guaranteed to stay valid at all times.
2362 scoped_refptr
<MtuDiscoveryAckListener
> last_mtu_discovery_ack_listener(
2363 new MtuDiscoveryAckListener(this, target_mtu
));
2366 packet_generator_
.GenerateMtuDiscoveryPacket(
2367 target_mtu
, last_mtu_discovery_ack_listener
.get());
2370 void QuicConnection::DiscoverMtu() {
2371 DCHECK(!mtu_discovery_alarm_
->IsSet());
2373 // Chcek if the MTU has been already increased.
2374 if (mtu_discovery_target_
<= max_packet_length()) {
2378 // Schedule the next probe *before* sending the current one. This is
2379 // important, otherwise, when SendMtuDiscoveryPacket() is called,
2380 // MaybeSetMtuAlarm() will not realize that the probe has been just sent, and
2381 // will reschedule this probe again.
2382 packets_between_mtu_probes_
*= 2;
2383 next_mtu_probe_at_
=
2384 sequence_number_of_last_sent_packet_
+ packets_between_mtu_probes_
+ 1;
2387 DVLOG(2) << "Sending a path MTU discovery packet #" << mtu_probe_count_
;
2388 SendMtuDiscoveryPacket(mtu_discovery_target_
);
2390 DCHECK(!mtu_discovery_alarm_
->IsSet());