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"
16 #include "base/debug/stack_trace.h"
17 #include "base/logging.h"
18 #include "base/stl_util.h"
19 #include "net/base/net_errors.h"
20 #include "net/quic/crypto/quic_decrypter.h"
21 #include "net/quic/crypto/quic_encrypter.h"
22 #include "net/quic/iovector.h"
23 #include "net/quic/quic_bandwidth.h"
24 #include "net/quic/quic_config.h"
25 #include "net/quic/quic_flags.h"
26 #include "net/quic/quic_utils.h"
28 using base::StringPiece
;
35 using std::numeric_limits
;
47 // The largest gap in packets we'll accept without closing the connection.
48 // This will likely have to be tuned.
49 const QuicPacketSequenceNumber kMaxPacketGap
= 5000;
51 // Limit the number of FEC groups to two. If we get enough out of order packets
52 // that this becomes limiting, we can revisit.
53 const size_t kMaxFecGroups
= 2;
55 // Limit the number of undecryptable packets we buffer in
56 // expectation of the CHLO/SHLO arriving.
57 const size_t kMaxUndecryptablePackets
= 10;
59 bool Near(QuicPacketSequenceNumber a
, QuicPacketSequenceNumber b
) {
60 QuicPacketSequenceNumber delta
= (a
> b
) ? a
- b
: b
- a
;
61 return delta
<= kMaxPacketGap
;
64 // An alarm that is scheduled to send an ack if a timeout occurs.
65 class AckAlarm
: public QuicAlarm::Delegate
{
67 explicit AckAlarm(QuicConnection
* connection
)
68 : connection_(connection
) {
71 virtual QuicTime
OnAlarm() OVERRIDE
{
72 connection_
->SendAck();
73 return QuicTime::Zero();
77 QuicConnection
* connection_
;
79 DISALLOW_COPY_AND_ASSIGN(AckAlarm
);
82 // This alarm will be scheduled any time a data-bearing packet is sent out.
83 // When the alarm goes off, the connection checks to see if the oldest packets
84 // have been acked, and retransmit them if they have not.
85 class RetransmissionAlarm
: public QuicAlarm::Delegate
{
87 explicit RetransmissionAlarm(QuicConnection
* connection
)
88 : connection_(connection
) {
91 virtual QuicTime
OnAlarm() OVERRIDE
{
92 connection_
->OnRetransmissionTimeout();
93 return QuicTime::Zero();
97 QuicConnection
* connection_
;
99 DISALLOW_COPY_AND_ASSIGN(RetransmissionAlarm
);
102 // An alarm that is scheduled when the sent scheduler requires a
103 // a delay before sending packets and fires when the packet may be sent.
104 class SendAlarm
: public QuicAlarm::Delegate
{
106 explicit SendAlarm(QuicConnection
* connection
)
107 : connection_(connection
) {
110 virtual QuicTime
OnAlarm() OVERRIDE
{
111 connection_
->WriteIfNotBlocked();
112 // Never reschedule the alarm, since CanWrite does that.
113 return QuicTime::Zero();
117 QuicConnection
* connection_
;
119 DISALLOW_COPY_AND_ASSIGN(SendAlarm
);
122 class TimeoutAlarm
: public QuicAlarm::Delegate
{
124 explicit TimeoutAlarm(QuicConnection
* connection
)
125 : connection_(connection
) {
128 virtual QuicTime
OnAlarm() OVERRIDE
{
129 connection_
->CheckForTimeout();
130 // Never reschedule the alarm, since CheckForTimeout does that.
131 return QuicTime::Zero();
135 QuicConnection
* connection_
;
137 DISALLOW_COPY_AND_ASSIGN(TimeoutAlarm
);
140 class PingAlarm
: public QuicAlarm::Delegate
{
142 explicit PingAlarm(QuicConnection
* connection
)
143 : connection_(connection
) {
146 virtual QuicTime
OnAlarm() OVERRIDE
{
147 connection_
->SendPing();
148 return QuicTime::Zero();
152 QuicConnection
* connection_
;
154 DISALLOW_COPY_AND_ASSIGN(PingAlarm
);
157 QuicConnection::PacketType
GetPacketType(
158 const RetransmittableFrames
* retransmittable_frames
) {
159 if (!retransmittable_frames
) {
160 return QuicConnection::NORMAL
;
162 for (size_t i
= 0; i
< retransmittable_frames
->frames().size(); ++i
) {
163 if (retransmittable_frames
->frames()[i
].type
== CONNECTION_CLOSE_FRAME
) {
164 return QuicConnection::CONNECTION_CLOSE
;
167 return QuicConnection::NORMAL
;
172 QuicConnection::QueuedPacket::QueuedPacket(SerializedPacket packet
,
173 EncryptionLevel level
,
174 TransmissionType transmission_type
)
175 : sequence_number(packet
.sequence_number
),
176 packet(packet
.packet
),
177 encryption_level(level
),
178 transmission_type(transmission_type
),
179 retransmittable((transmission_type
!= NOT_RETRANSMISSION
||
180 packet
.retransmittable_frames
!= NULL
) ?
181 HAS_RETRANSMITTABLE_DATA
: NO_RETRANSMITTABLE_DATA
),
182 handshake(packet
.retransmittable_frames
== NULL
?
183 NOT_HANDSHAKE
: packet
.retransmittable_frames
->HasCryptoHandshake()),
184 type(GetPacketType(packet
.retransmittable_frames
)),
185 length(packet
.packet
->length()) {
188 #define ENDPOINT (is_server_ ? "Server: " : " Client: ")
190 QuicConnection::QuicConnection(QuicConnectionId connection_id
,
192 QuicConnectionHelperInterface
* helper
,
193 const PacketWriterFactory
& writer_factory
,
196 const QuicVersionVector
& supported_versions
)
197 : framer_(supported_versions
, helper
->GetClock()->ApproximateNow(),
200 writer_(writer_factory
.Create(this)),
201 owns_writer_(owns_writer
),
202 encryption_level_(ENCRYPTION_NONE
),
203 clock_(helper
->GetClock()),
204 random_generator_(helper
->GetRandomGenerator()),
205 connection_id_(connection_id
),
206 peer_address_(address
),
207 migrating_peer_port_(0),
208 last_packet_revived_(false),
210 last_decrypted_packet_level_(ENCRYPTION_NONE
),
211 largest_seen_packet_with_ack_(0),
212 largest_seen_packet_with_stop_waiting_(0),
213 pending_version_negotiation_packet_(false),
214 received_packet_manager_(&stats_
),
216 stop_waiting_count_(0),
217 ack_alarm_(helper
->CreateAlarm(new AckAlarm(this))),
218 retransmission_alarm_(helper
->CreateAlarm(new RetransmissionAlarm(this))),
219 send_alarm_(helper
->CreateAlarm(new SendAlarm(this))),
220 resume_writes_alarm_(helper
->CreateAlarm(new SendAlarm(this))),
221 timeout_alarm_(helper
->CreateAlarm(new TimeoutAlarm(this))),
222 ping_alarm_(helper
->CreateAlarm(new PingAlarm(this))),
223 packet_generator_(connection_id_
, &framer_
, random_generator_
, this),
224 idle_network_timeout_(
225 QuicTime::Delta::FromSeconds(kDefaultInitialTimeoutSecs
)),
226 overall_connection_timeout_(QuicTime::Delta::Infinite()),
227 time_of_last_received_packet_(clock_
->ApproximateNow()),
228 time_of_last_sent_new_packet_(clock_
->ApproximateNow()),
229 sequence_number_of_last_sent_packet_(0),
230 sent_packet_manager_(
231 is_server
, clock_
, &stats_
,
232 FLAGS_quic_use_bbr_congestion_control
? kBBR
: kCubic
,
233 FLAGS_quic_use_time_loss_detection
? kTime
: kNack
),
234 version_negotiation_state_(START_NEGOTIATION
),
235 is_server_(is_server
),
237 peer_ip_changed_(false),
238 peer_port_changed_(false),
239 self_ip_changed_(false),
240 self_port_changed_(false) {
242 // TODO(rtenneti): Should we enable this code in chromium?
244 // Pacing will be enabled if the client negotiates it.
245 sent_packet_manager_
.MaybeEnablePacing();
248 DVLOG(1) << ENDPOINT
<< "Created connection with connection_id: "
250 timeout_alarm_
->Set(clock_
->ApproximateNow().Add(idle_network_timeout_
));
251 framer_
.set_visitor(this);
252 framer_
.set_received_entropy_calculator(&received_packet_manager_
);
253 stats_
.connection_creation_time
= clock_
->ApproximateNow();
254 sent_packet_manager_
.set_network_change_visitor(this);
257 QuicConnection::~QuicConnection() {
261 STLDeleteElements(&undecryptable_packets_
);
262 STLDeleteValues(&group_map_
);
263 for (QueuedPacketList::iterator it
= queued_packets_
.begin();
264 it
!= queued_packets_
.end(); ++it
) {
269 void QuicConnection::SetFromConfig(const QuicConfig
& config
) {
270 SetIdleNetworkTimeout(config
.idle_connection_state_lifetime());
271 sent_packet_manager_
.SetFromConfig(config
);
274 bool QuicConnection::SelectMutualVersion(
275 const QuicVersionVector
& available_versions
) {
276 // Try to find the highest mutual version by iterating over supported
277 // versions, starting with the highest, and breaking out of the loop once we
278 // find a matching version in the provided available_versions vector.
279 const QuicVersionVector
& supported_versions
= framer_
.supported_versions();
280 for (size_t i
= 0; i
< supported_versions
.size(); ++i
) {
281 const QuicVersion
& version
= supported_versions
[i
];
282 if (std::find(available_versions
.begin(), available_versions
.end(),
283 version
) != available_versions
.end()) {
284 framer_
.set_version(version
);
292 void QuicConnection::OnError(QuicFramer
* framer
) {
293 // Packets that we cannot decrypt are dropped.
294 // TODO(rch): add stats to measure this.
295 if (!connected_
|| framer
->error() == QUIC_DECRYPTION_FAILURE
) {
298 SendConnectionCloseWithDetails(framer
->error(), framer
->detailed_error());
301 void QuicConnection::OnPacket() {
302 DCHECK(last_stream_frames_
.empty() &&
303 last_goaway_frames_
.empty() &&
304 last_window_update_frames_
.empty() &&
305 last_blocked_frames_
.empty() &&
306 last_rst_frames_
.empty() &&
307 last_ack_frames_
.empty() &&
308 last_congestion_frames_
.empty() &&
309 last_stop_waiting_frames_
.empty());
312 void QuicConnection::OnPublicResetPacket(
313 const QuicPublicResetPacket
& packet
) {
314 if (debug_visitor_
.get() != NULL
) {
315 debug_visitor_
->OnPublicResetPacket(packet
);
317 CloseConnection(QUIC_PUBLIC_RESET
, true);
319 DVLOG(1) << ENDPOINT
<< "Connection " << connection_id()
320 << " closed via QUIC_PUBLIC_RESET from peer.";
323 bool QuicConnection::OnProtocolVersionMismatch(QuicVersion received_version
) {
324 DVLOG(1) << ENDPOINT
<< "Received packet with mismatched version "
326 // TODO(satyamshekhar): Implement no server state in this mode.
328 LOG(DFATAL
) << ENDPOINT
<< "Framer called OnProtocolVersionMismatch. "
329 << "Closing connection.";
330 CloseConnection(QUIC_INTERNAL_ERROR
, false);
333 DCHECK_NE(version(), received_version
);
335 if (debug_visitor_
.get() != NULL
) {
336 debug_visitor_
->OnProtocolVersionMismatch(received_version
);
339 switch (version_negotiation_state_
) {
340 case START_NEGOTIATION
:
341 if (!framer_
.IsSupportedVersion(received_version
)) {
342 SendVersionNegotiationPacket();
343 version_negotiation_state_
= NEGOTIATION_IN_PROGRESS
;
348 case NEGOTIATION_IN_PROGRESS
:
349 if (!framer_
.IsSupportedVersion(received_version
)) {
350 SendVersionNegotiationPacket();
355 case NEGOTIATED_VERSION
:
356 // Might be old packets that were sent by the client before the version
357 // was negotiated. Drop these.
364 version_negotiation_state_
= NEGOTIATED_VERSION
;
365 visitor_
->OnSuccessfulVersionNegotiation(received_version
);
366 DVLOG(1) << ENDPOINT
<< "version negotiated " << received_version
;
368 // Store the new version.
369 framer_
.set_version(received_version
);
371 // TODO(satyamshekhar): Store the sequence number of this packet and close the
372 // connection if we ever received a packet with incorrect version and whose
373 // sequence number is greater.
377 // Handles version negotiation for client connection.
378 void QuicConnection::OnVersionNegotiationPacket(
379 const QuicVersionNegotiationPacket
& packet
) {
381 LOG(DFATAL
) << ENDPOINT
<< "Framer parsed VersionNegotiationPacket."
382 << " Closing connection.";
383 CloseConnection(QUIC_INTERNAL_ERROR
, false);
386 if (debug_visitor_
.get() != NULL
) {
387 debug_visitor_
->OnVersionNegotiationPacket(packet
);
390 if (version_negotiation_state_
!= START_NEGOTIATION
) {
391 // Possibly a duplicate version negotiation packet.
395 if (std::find(packet
.versions
.begin(),
396 packet
.versions
.end(), version()) !=
397 packet
.versions
.end()) {
398 DLOG(WARNING
) << ENDPOINT
<< "The server already supports our version. "
399 << "It should have accepted our connection.";
400 // Just drop the connection.
401 CloseConnection(QUIC_INVALID_VERSION_NEGOTIATION_PACKET
, false);
405 if (!SelectMutualVersion(packet
.versions
)) {
406 SendConnectionCloseWithDetails(QUIC_INVALID_VERSION
,
407 "no common version found");
412 << "Negotiated version: " << QuicVersionToString(version());
413 server_supported_versions_
= packet
.versions
;
414 version_negotiation_state_
= NEGOTIATION_IN_PROGRESS
;
415 RetransmitUnackedPackets(ALL_PACKETS
);
418 void QuicConnection::OnRevivedPacket() {
421 bool QuicConnection::OnUnauthenticatedPublicHeader(
422 const QuicPacketPublicHeader
& header
) {
426 bool QuicConnection::OnUnauthenticatedHeader(const QuicPacketHeader
& header
) {
430 void QuicConnection::OnDecryptedPacket(EncryptionLevel level
) {
431 last_decrypted_packet_level_
= level
;
434 bool QuicConnection::OnPacketHeader(const QuicPacketHeader
& header
) {
435 if (debug_visitor_
.get() != NULL
) {
436 debug_visitor_
->OnPacketHeader(header
);
439 if (!ProcessValidatedPacket()) {
443 // Will be decrement below if we fall through to return true;
444 ++stats_
.packets_dropped
;
446 if (header
.public_header
.connection_id
!= connection_id_
) {
447 DVLOG(1) << ENDPOINT
<< "Ignoring packet from unexpected ConnectionId: "
448 << header
.public_header
.connection_id
<< " instead of "
450 if (debug_visitor_
.get() != NULL
) {
451 debug_visitor_
->OnIncorrectConnectionId(
452 header
.public_header
.connection_id
);
457 if (!Near(header
.packet_sequence_number
,
458 last_header_
.packet_sequence_number
)) {
459 DVLOG(1) << ENDPOINT
<< "Packet " << header
.packet_sequence_number
460 << " out of bounds. Discarding";
461 SendConnectionCloseWithDetails(QUIC_INVALID_PACKET_HEADER
,
462 "Packet sequence number out of bounds");
466 // If this packet has already been seen, or that the sender
467 // has told us will not be retransmitted, then stop processing the packet.
468 if (!received_packet_manager_
.IsAwaitingPacket(
469 header
.packet_sequence_number
)) {
470 DVLOG(1) << ENDPOINT
<< "Packet " << header
.packet_sequence_number
471 << " no longer being waited for. Discarding.";
472 if (debug_visitor_
.get() != NULL
) {
473 debug_visitor_
->OnDuplicatePacket(header
.packet_sequence_number
);
478 if (version_negotiation_state_
!= NEGOTIATED_VERSION
) {
480 if (!header
.public_header
.version_flag
) {
481 DLOG(WARNING
) << ENDPOINT
<< "Packet " << header
.packet_sequence_number
482 << " without version flag before version negotiated.";
483 // Packets should have the version flag till version negotiation is
485 CloseConnection(QUIC_INVALID_VERSION
, false);
488 DCHECK_EQ(1u, header
.public_header
.versions
.size());
489 DCHECK_EQ(header
.public_header
.versions
[0], version());
490 version_negotiation_state_
= NEGOTIATED_VERSION
;
491 visitor_
->OnSuccessfulVersionNegotiation(version());
494 DCHECK(!header
.public_header
.version_flag
);
495 // If the client gets a packet without the version flag from the server
496 // it should stop sending version since the version negotiation is done.
497 packet_generator_
.StopSendingVersion();
498 version_negotiation_state_
= NEGOTIATED_VERSION
;
499 visitor_
->OnSuccessfulVersionNegotiation(version());
503 DCHECK_EQ(NEGOTIATED_VERSION
, version_negotiation_state_
);
505 --stats_
.packets_dropped
;
506 DVLOG(1) << ENDPOINT
<< "Received packet header: " << header
;
507 last_header_
= header
;
512 void QuicConnection::OnFecProtectedPayload(StringPiece payload
) {
513 DCHECK_EQ(IN_FEC_GROUP
, last_header_
.is_in_fec_group
);
514 DCHECK_NE(0u, last_header_
.fec_group
);
515 QuicFecGroup
* group
= GetFecGroup();
517 group
->Update(last_decrypted_packet_level_
, last_header_
, payload
);
521 bool QuicConnection::OnStreamFrame(const QuicStreamFrame
& frame
) {
523 if (debug_visitor_
.get() != NULL
) {
524 debug_visitor_
->OnStreamFrame(frame
);
526 if (frame
.stream_id
!= kCryptoStreamId
&&
527 last_decrypted_packet_level_
== ENCRYPTION_NONE
) {
528 DLOG(WARNING
) << ENDPOINT
529 << "Received an unencrypted data frame: closing connection";
530 SendConnectionClose(QUIC_UNENCRYPTED_STREAM_DATA
);
533 last_stream_frames_
.push_back(frame
);
537 bool QuicConnection::OnAckFrame(const QuicAckFrame
& incoming_ack
) {
539 if (debug_visitor_
.get() != NULL
) {
540 debug_visitor_
->OnAckFrame(incoming_ack
);
542 DVLOG(1) << ENDPOINT
<< "OnAckFrame: " << incoming_ack
;
544 if (last_header_
.packet_sequence_number
<= largest_seen_packet_with_ack_
) {
545 DVLOG(1) << ENDPOINT
<< "Received an old ack frame: ignoring";
549 if (!ValidateAckFrame(incoming_ack
)) {
550 SendConnectionClose(QUIC_INVALID_ACK_DATA
);
554 last_ack_frames_
.push_back(incoming_ack
);
558 void QuicConnection::ProcessAckFrame(const QuicAckFrame
& incoming_ack
) {
559 largest_seen_packet_with_ack_
= last_header_
.packet_sequence_number
;
560 sent_packet_manager_
.OnIncomingAck(incoming_ack
,
561 time_of_last_received_packet_
);
562 sent_entropy_manager_
.ClearEntropyBefore(
563 sent_packet_manager_
.least_packet_awaited_by_peer() - 1);
564 if (sent_packet_manager_
.HasPendingRetransmissions()) {
568 // Always reset the retransmission alarm when an ack comes in, since we now
569 // have a better estimate of the current rtt than when it was set.
570 QuicTime retransmission_time
= sent_packet_manager_
.GetRetransmissionTime();
571 retransmission_alarm_
->Update(retransmission_time
,
572 QuicTime::Delta::FromMilliseconds(1));
575 void QuicConnection::ProcessStopWaitingFrame(
576 const QuicStopWaitingFrame
& stop_waiting
) {
577 largest_seen_packet_with_stop_waiting_
= last_header_
.packet_sequence_number
;
578 received_packet_manager_
.UpdatePacketInformationSentByPeer(stop_waiting
);
579 // Possibly close any FecGroups which are now irrelevant.
580 CloseFecGroupsBefore(stop_waiting
.least_unacked
+ 1);
583 bool QuicConnection::OnCongestionFeedbackFrame(
584 const QuicCongestionFeedbackFrame
& feedback
) {
586 if (debug_visitor_
.get() != NULL
) {
587 debug_visitor_
->OnCongestionFeedbackFrame(feedback
);
589 last_congestion_frames_
.push_back(feedback
);
593 bool QuicConnection::OnStopWaitingFrame(const QuicStopWaitingFrame
& frame
) {
596 if (last_header_
.packet_sequence_number
<=
597 largest_seen_packet_with_stop_waiting_
) {
598 DVLOG(1) << ENDPOINT
<< "Received an old stop waiting frame: ignoring";
602 if (!ValidateStopWaitingFrame(frame
)) {
603 SendConnectionClose(QUIC_INVALID_STOP_WAITING_DATA
);
607 if (debug_visitor_
.get() != NULL
) {
608 debug_visitor_
->OnStopWaitingFrame(frame
);
611 last_stop_waiting_frames_
.push_back(frame
);
615 bool QuicConnection::OnPingFrame(const QuicPingFrame
& frame
) {
617 if (debug_visitor_
.get() != NULL
) {
618 debug_visitor_
->OnPingFrame(frame
);
623 bool QuicConnection::ValidateAckFrame(const QuicAckFrame
& incoming_ack
) {
624 if (incoming_ack
.largest_observed
> packet_generator_
.sequence_number()) {
625 DLOG(ERROR
) << ENDPOINT
<< "Peer's observed unsent packet:"
626 << incoming_ack
.largest_observed
<< " vs "
627 << packet_generator_
.sequence_number();
628 // We got an error for data we have not sent. Error out.
632 if (incoming_ack
.largest_observed
< sent_packet_manager_
.largest_observed()) {
633 DLOG(ERROR
) << ENDPOINT
<< "Peer's largest_observed packet decreased:"
634 << incoming_ack
.largest_observed
<< " vs "
635 << sent_packet_manager_
.largest_observed();
636 // A new ack has a diminished largest_observed value. Error out.
637 // If this was an old packet, we wouldn't even have checked.
641 if (!incoming_ack
.missing_packets
.empty() &&
642 *incoming_ack
.missing_packets
.rbegin() > incoming_ack
.largest_observed
) {
643 DLOG(ERROR
) << ENDPOINT
<< "Peer sent missing packet: "
644 << *incoming_ack
.missing_packets
.rbegin()
645 << " which is greater than largest observed: "
646 << incoming_ack
.largest_observed
;
650 if (!incoming_ack
.missing_packets
.empty() &&
651 *incoming_ack
.missing_packets
.begin() <
652 sent_packet_manager_
.least_packet_awaited_by_peer()) {
653 DLOG(ERROR
) << ENDPOINT
<< "Peer sent missing packet: "
654 << *incoming_ack
.missing_packets
.begin()
655 << " which is smaller than least_packet_awaited_by_peer_: "
656 << sent_packet_manager_
.least_packet_awaited_by_peer();
660 if (!sent_entropy_manager_
.IsValidEntropy(
661 incoming_ack
.largest_observed
,
662 incoming_ack
.missing_packets
,
663 incoming_ack
.entropy_hash
)) {
664 DLOG(ERROR
) << ENDPOINT
<< "Peer sent invalid entropy.";
668 for (SequenceNumberSet::const_iterator iter
=
669 incoming_ack
.revived_packets
.begin();
670 iter
!= incoming_ack
.revived_packets
.end(); ++iter
) {
671 if (!ContainsKey(incoming_ack
.missing_packets
, *iter
)) {
672 DLOG(ERROR
) << ENDPOINT
673 << "Peer specified revived packet which was not missing.";
680 bool QuicConnection::ValidateStopWaitingFrame(
681 const QuicStopWaitingFrame
& stop_waiting
) {
682 if (stop_waiting
.least_unacked
<
683 received_packet_manager_
.peer_least_packet_awaiting_ack()) {
684 DLOG(ERROR
) << ENDPOINT
<< "Peer's sent low least_unacked: "
685 << stop_waiting
.least_unacked
<< " vs "
686 << received_packet_manager_
.peer_least_packet_awaiting_ack();
687 // We never process old ack frames, so this number should only increase.
691 if (stop_waiting
.least_unacked
>
692 last_header_
.packet_sequence_number
) {
693 DLOG(ERROR
) << ENDPOINT
<< "Peer sent least_unacked:"
694 << stop_waiting
.least_unacked
695 << " greater than the enclosing packet sequence number:"
696 << last_header_
.packet_sequence_number
;
703 void QuicConnection::OnFecData(const QuicFecData
& fec
) {
704 DCHECK_EQ(IN_FEC_GROUP
, last_header_
.is_in_fec_group
);
705 DCHECK_NE(0u, last_header_
.fec_group
);
706 QuicFecGroup
* group
= GetFecGroup();
708 group
->UpdateFec(last_decrypted_packet_level_
,
709 last_header_
.packet_sequence_number
, fec
);
713 bool QuicConnection::OnRstStreamFrame(const QuicRstStreamFrame
& frame
) {
715 if (debug_visitor_
.get() != NULL
) {
716 debug_visitor_
->OnRstStreamFrame(frame
);
718 DVLOG(1) << ENDPOINT
<< "Stream reset with error "
719 << QuicUtils::StreamErrorToString(frame
.error_code
);
720 last_rst_frames_
.push_back(frame
);
724 bool QuicConnection::OnConnectionCloseFrame(
725 const QuicConnectionCloseFrame
& frame
) {
727 if (debug_visitor_
.get() != NULL
) {
728 debug_visitor_
->OnConnectionCloseFrame(frame
);
730 DVLOG(1) << ENDPOINT
<< "Connection " << connection_id()
731 << " closed with error "
732 << QuicUtils::ErrorToString(frame
.error_code
)
733 << " " << frame
.error_details
;
734 last_close_frames_
.push_back(frame
);
738 bool QuicConnection::OnGoAwayFrame(const QuicGoAwayFrame
& frame
) {
740 if (debug_visitor_
.get() != NULL
) {
741 debug_visitor_
->OnGoAwayFrame(frame
);
743 DVLOG(1) << ENDPOINT
<< "Go away received with error "
744 << QuicUtils::ErrorToString(frame
.error_code
)
745 << " and reason:" << frame
.reason_phrase
;
746 last_goaway_frames_
.push_back(frame
);
750 bool QuicConnection::OnWindowUpdateFrame(const QuicWindowUpdateFrame
& frame
) {
752 if (debug_visitor_
.get() != NULL
) {
753 debug_visitor_
->OnWindowUpdateFrame(frame
);
755 DVLOG(1) << ENDPOINT
<< "WindowUpdate received for stream: "
756 << frame
.stream_id
<< " with byte offset: " << frame
.byte_offset
;
757 last_window_update_frames_
.push_back(frame
);
761 bool QuicConnection::OnBlockedFrame(const QuicBlockedFrame
& frame
) {
763 if (debug_visitor_
.get() != NULL
) {
764 debug_visitor_
->OnBlockedFrame(frame
);
766 DVLOG(1) << ENDPOINT
<< "Blocked frame received for stream: "
768 last_blocked_frames_
.push_back(frame
);
772 void QuicConnection::OnPacketComplete() {
773 // Don't do anything if this packet closed the connection.
779 DVLOG(1) << ENDPOINT
<< (last_packet_revived_
? "Revived" : "Got")
780 << " packet " << last_header_
.packet_sequence_number
781 << " with " << last_ack_frames_
.size() << " acks, "
782 << last_congestion_frames_
.size() << " congestions, "
783 << last_stop_waiting_frames_
.size() << " stop_waiting, "
784 << last_goaway_frames_
.size() << " goaways, "
785 << last_window_update_frames_
.size() << " window updates, "
786 << last_blocked_frames_
.size() << " blocked, "
787 << last_rst_frames_
.size() << " rsts, "
788 << last_close_frames_
.size() << " closes, "
789 << last_stream_frames_
.size()
790 << " stream frames for "
791 << last_header_
.public_header
.connection_id
;
793 // Call MaybeQueueAck() before recording the received packet, since we want
794 // to trigger an ack if the newly received packet was previously missing.
797 // Record received or revived packet to populate ack info correctly before
798 // processing stream frames, since the processing may result in a response
799 // packet with a bundled ack.
800 if (last_packet_revived_
) {
801 received_packet_manager_
.RecordPacketRevived(
802 last_header_
.packet_sequence_number
);
804 received_packet_manager_
.RecordPacketReceived(
805 last_size_
, last_header_
, time_of_last_received_packet_
);
808 if (!last_stream_frames_
.empty()) {
809 visitor_
->OnStreamFrames(last_stream_frames_
);
812 for (size_t i
= 0; i
< last_stream_frames_
.size(); ++i
) {
813 stats_
.stream_bytes_received
+=
814 last_stream_frames_
[i
].data
.TotalBufferSize();
817 // Process window updates, blocked, stream resets, acks, then congestion
819 if (!last_window_update_frames_
.empty()) {
820 visitor_
->OnWindowUpdateFrames(last_window_update_frames_
);
822 if (!last_blocked_frames_
.empty()) {
823 visitor_
->OnBlockedFrames(last_blocked_frames_
);
825 for (size_t i
= 0; i
< last_goaway_frames_
.size(); ++i
) {
826 visitor_
->OnGoAway(last_goaway_frames_
[i
]);
828 for (size_t i
= 0; i
< last_rst_frames_
.size(); ++i
) {
829 visitor_
->OnRstStream(last_rst_frames_
[i
]);
831 for (size_t i
= 0; i
< last_ack_frames_
.size(); ++i
) {
832 ProcessAckFrame(last_ack_frames_
[i
]);
834 for (size_t i
= 0; i
< last_congestion_frames_
.size(); ++i
) {
835 sent_packet_manager_
.OnIncomingQuicCongestionFeedbackFrame(
836 last_congestion_frames_
[i
], time_of_last_received_packet_
);
838 for (size_t i
= 0; i
< last_stop_waiting_frames_
.size(); ++i
) {
839 ProcessStopWaitingFrame(last_stop_waiting_frames_
[i
]);
841 if (!last_close_frames_
.empty()) {
842 CloseConnection(last_close_frames_
[0].error_code
, true);
846 // If there are new missing packets to report, send an ack immediately.
847 if (received_packet_manager_
.HasNewMissingPackets()) {
849 ack_alarm_
->Cancel();
852 UpdateStopWaitingCount();
857 void QuicConnection::MaybeQueueAck() {
858 // If the incoming packet was missing, send an ack immediately.
859 ack_queued_
= received_packet_manager_
.IsMissing(
860 last_header_
.packet_sequence_number
);
862 if (!ack_queued_
&& ShouldLastPacketInstigateAck()) {
863 if (ack_alarm_
->IsSet()) {
866 // Send an ack much more quickly for crypto handshake packets.
867 QuicTime::Delta delayed_ack_time
= sent_packet_manager_
.DelayedAckTime();
868 if (last_stream_frames_
.size() == 1 &&
869 last_stream_frames_
[0].stream_id
== kCryptoStreamId
) {
870 delayed_ack_time
= QuicTime::Delta::Zero();
872 ack_alarm_
->Set(clock_
->ApproximateNow().Add(delayed_ack_time
));
873 DVLOG(1) << "Ack timer set; next packet or timer will trigger ACK.";
878 ack_alarm_
->Cancel();
882 void QuicConnection::ClearLastFrames() {
883 last_stream_frames_
.clear();
884 last_goaway_frames_
.clear();
885 last_window_update_frames_
.clear();
886 last_blocked_frames_
.clear();
887 last_rst_frames_
.clear();
888 last_ack_frames_
.clear();
889 last_stop_waiting_frames_
.clear();
890 last_congestion_frames_
.clear();
893 QuicAckFrame
* QuicConnection::CreateAckFrame() {
894 QuicAckFrame
* outgoing_ack
= new QuicAckFrame();
895 received_packet_manager_
.UpdateReceivedPacketInfo(
896 outgoing_ack
, clock_
->ApproximateNow());
897 DVLOG(1) << ENDPOINT
<< "Creating ack frame: " << *outgoing_ack
;
901 QuicCongestionFeedbackFrame
* QuicConnection::CreateFeedbackFrame() {
902 return new QuicCongestionFeedbackFrame(outgoing_congestion_feedback_
);
905 QuicStopWaitingFrame
* QuicConnection::CreateStopWaitingFrame() {
906 QuicStopWaitingFrame stop_waiting
;
907 UpdateStopWaiting(&stop_waiting
);
908 return new QuicStopWaitingFrame(stop_waiting
);
911 bool QuicConnection::ShouldLastPacketInstigateAck() const {
912 if (!last_stream_frames_
.empty() ||
913 !last_goaway_frames_
.empty() ||
914 !last_rst_frames_
.empty() ||
915 !last_window_update_frames_
.empty() ||
916 !last_blocked_frames_
.empty()) {
920 if (!last_ack_frames_
.empty() && last_ack_frames_
.back().is_truncated
) {
926 void QuicConnection::UpdateStopWaitingCount() {
927 if (last_ack_frames_
.empty()) {
931 // If the peer is still waiting for a packet that we are no longer planning to
932 // send, send an ack to raise the high water mark.
933 if (!last_ack_frames_
.back().missing_packets
.empty() &&
934 GetLeastUnacked() > *last_ack_frames_
.back().missing_packets
.begin()) {
935 ++stop_waiting_count_
;
937 stop_waiting_count_
= 0;
941 QuicPacketSequenceNumber
QuicConnection::GetLeastUnacked() const {
942 return sent_packet_manager_
.HasUnackedPackets() ?
943 sent_packet_manager_
.GetLeastUnackedSentPacket() :
944 packet_generator_
.sequence_number() + 1;
947 void QuicConnection::MaybeSendInResponseToPacket() {
951 ScopedPacketBundler
bundler(this, ack_queued_
? SEND_ACK
: NO_ACK
);
953 // Now that we have received an ack, we might be able to send packets which
954 // are queued locally, or drain streams which are blocked.
955 if (CanWrite(HAS_RETRANSMITTABLE_DATA
)) {
960 void QuicConnection::SendVersionNegotiationPacket() {
961 // TODO(alyssar): implement zero server state negotiation.
962 pending_version_negotiation_packet_
= true;
963 if (writer_
->IsWriteBlocked()) {
964 visitor_
->OnWriteBlocked();
967 DVLOG(1) << ENDPOINT
<< "Sending version negotiation packet: {"
968 << QuicVersionVectorToString(framer_
.supported_versions()) << "}";
969 scoped_ptr
<QuicEncryptedPacket
> version_packet(
970 packet_generator_
.SerializeVersionNegotiationPacket(
971 framer_
.supported_versions()));
972 WriteResult result
= writer_
->WritePacket(
973 version_packet
->data(), version_packet
->length(),
974 self_address().address(), peer_address());
976 if (result
.status
== WRITE_STATUS_ERROR
) {
977 // We can't send an error as the socket is presumably borked.
978 CloseConnection(QUIC_PACKET_WRITE_ERROR
, false);
981 if (result
.status
== WRITE_STATUS_BLOCKED
) {
982 visitor_
->OnWriteBlocked();
983 if (writer_
->IsWriteBlockedDataBuffered()) {
984 pending_version_negotiation_packet_
= false;
989 pending_version_negotiation_packet_
= false;
992 QuicConsumedData
QuicConnection::SendStreamData(
994 const IOVector
& data
,
995 QuicStreamOffset offset
,
997 FecProtection fec_protection
,
998 QuicAckNotifier::DelegateInterface
* delegate
) {
999 if (!fin
&& data
.Empty()) {
1000 LOG(DFATAL
) << "Attempt to send empty stream frame";
1003 // This notifier will be owned by the AckNotifierManager (or deleted below if
1004 // no data or FIN was consumed).
1005 QuicAckNotifier
* notifier
= NULL
;
1007 notifier
= new QuicAckNotifier(delegate
);
1010 // Opportunistically bundle an ack with every outgoing packet.
1011 // Particularly, we want to bundle with handshake packets since we don't know
1012 // which decrypter will be used on an ack packet following a handshake
1013 // packet (a handshake packet from client to server could result in a REJ or a
1014 // SHLO from the server, leading to two different decrypters at the server.)
1016 // TODO(jri): Note that ConsumeData may cause a response packet to be sent.
1017 // We may end up sending stale ack information if there are undecryptable
1018 // packets hanging around and/or there are revivable packets which may get
1019 // handled after this packet is sent. Change ScopedPacketBundler to do the
1020 // right thing: check ack_queued_, and then check undecryptable packets and
1021 // also if there is possibility of revival. Only bundle an ack if there's no
1022 // processing left that may cause received_info_ to change.
1023 ScopedPacketBundler
ack_bundler(this, BUNDLE_PENDING_ACK
);
1024 QuicConsumedData consumed_data
=
1025 packet_generator_
.ConsumeData(id
, data
, offset
, fin
, fec_protection
,
1029 (consumed_data
.bytes_consumed
== 0 && !consumed_data
.fin_consumed
)) {
1030 // No data was consumed, nor was a fin consumed, so delete the notifier.
1034 return consumed_data
;
1037 void QuicConnection::SendRstStream(QuicStreamId id
,
1038 QuicRstStreamErrorCode error
,
1039 QuicStreamOffset bytes_written
) {
1040 // Opportunistically bundle an ack with this outgoing packet.
1041 ScopedPacketBundler
ack_bundler(this, BUNDLE_PENDING_ACK
);
1042 packet_generator_
.AddControlFrame(QuicFrame(new QuicRstStreamFrame(
1043 id
, AdjustErrorForVersion(error
, version()), bytes_written
)));
1046 void QuicConnection::SendWindowUpdate(QuicStreamId id
,
1047 QuicStreamOffset byte_offset
) {
1048 // Opportunistically bundle an ack with this outgoing packet.
1049 ScopedPacketBundler
ack_bundler(this, BUNDLE_PENDING_ACK
);
1050 packet_generator_
.AddControlFrame(
1051 QuicFrame(new QuicWindowUpdateFrame(id
, byte_offset
)));
1054 void QuicConnection::SendBlocked(QuicStreamId id
) {
1055 // Opportunistically bundle an ack with this outgoing packet.
1056 ScopedPacketBundler
ack_bundler(this, BUNDLE_PENDING_ACK
);
1057 packet_generator_
.AddControlFrame(QuicFrame(new QuicBlockedFrame(id
)));
1060 const QuicConnectionStats
& QuicConnection::GetStats() {
1061 // Update rtt and estimated bandwidth.
1063 sent_packet_manager_
.GetRttStats()->min_rtt().ToMicroseconds();
1065 sent_packet_manager_
.GetRttStats()->SmoothedRtt().ToMicroseconds();
1066 stats_
.estimated_bandwidth
=
1067 sent_packet_manager_
.BandwidthEstimate().ToBytesPerSecond();
1068 stats_
.congestion_window
= sent_packet_manager_
.GetCongestionWindow();
1069 stats_
.slow_start_threshold
= sent_packet_manager_
.GetSlowStartThreshold();
1070 stats_
.max_packet_size
= packet_generator_
.max_packet_length();
1074 void QuicConnection::ProcessUdpPacket(const IPEndPoint
& self_address
,
1075 const IPEndPoint
& peer_address
,
1076 const QuicEncryptedPacket
& packet
) {
1080 if (debug_visitor_
.get() != NULL
) {
1081 debug_visitor_
->OnPacketReceived(self_address
, peer_address
, packet
);
1083 last_packet_revived_
= false;
1084 last_size_
= packet
.length();
1086 CheckForAddressMigration(self_address
, peer_address
);
1088 stats_
.bytes_received
+= packet
.length();
1089 ++stats_
.packets_received
;
1091 if (!framer_
.ProcessPacket(packet
)) {
1092 // If we are unable to decrypt this packet, it might be
1093 // because the CHLO or SHLO packet was lost.
1094 if (framer_
.error() == QUIC_DECRYPTION_FAILURE
) {
1095 if (encryption_level_
!= ENCRYPTION_FORWARD_SECURE
&&
1096 undecryptable_packets_
.size() < kMaxUndecryptablePackets
) {
1097 QueueUndecryptablePacket(packet
);
1098 } else if (debug_visitor_
.get() != NULL
) {
1099 debug_visitor_
->OnUndecryptablePacket();
1102 DVLOG(1) << ENDPOINT
<< "Unable to process packet. Last packet processed: "
1103 << last_header_
.packet_sequence_number
;
1107 ++stats_
.packets_processed
;
1108 MaybeProcessUndecryptablePackets();
1109 MaybeProcessRevivedPacket();
1110 MaybeSendInResponseToPacket();
1114 void QuicConnection::CheckForAddressMigration(
1115 const IPEndPoint
& self_address
, const IPEndPoint
& peer_address
) {
1116 peer_ip_changed_
= false;
1117 peer_port_changed_
= false;
1118 self_ip_changed_
= false;
1119 self_port_changed_
= false;
1121 if (peer_address_
.address().empty()) {
1122 peer_address_
= peer_address
;
1124 if (self_address_
.address().empty()) {
1125 self_address_
= self_address
;
1128 if (!peer_address
.address().empty() && !peer_address_
.address().empty()) {
1129 peer_ip_changed_
= (peer_address
.address() != peer_address_
.address());
1130 peer_port_changed_
= (peer_address
.port() != peer_address_
.port());
1132 // Store in case we want to migrate connection in ProcessValidatedPacket.
1133 migrating_peer_port_
= peer_address
.port();
1136 if (!self_address
.address().empty() && !self_address_
.address().empty()) {
1137 self_ip_changed_
= (self_address
.address() != self_address_
.address());
1138 self_port_changed_
= (self_address
.port() != self_address_
.port());
1142 void QuicConnection::OnCanWrite() {
1143 DCHECK(!writer_
->IsWriteBlocked());
1145 WriteQueuedPackets();
1146 WritePendingRetransmissions();
1148 // Sending queued packets may have caused the socket to become write blocked,
1149 // or the congestion manager to prohibit sending. If we've sent everything
1150 // we had queued and we're still not blocked, let the visitor know it can
1152 if (!CanWrite(HAS_RETRANSMITTABLE_DATA
)) {
1156 { // Limit the scope of the bundler.
1157 // Set |include_ack| to false in bundler; ack inclusion happens elsewhere.
1158 ScopedPacketBundler
bundler(this, NO_ACK
);
1159 visitor_
->OnCanWrite();
1162 // After the visitor writes, it may have caused the socket to become write
1163 // blocked or the congestion manager to prohibit sending, so check again.
1164 if (visitor_
->WillingAndAbleToWrite() &&
1165 !resume_writes_alarm_
->IsSet() &&
1166 CanWrite(HAS_RETRANSMITTABLE_DATA
)) {
1167 // We're not write blocked, but some stream didn't write out all of its
1168 // bytes. Register for 'immediate' resumption so we'll keep writing after
1169 // other connections and events have had a chance to use the thread.
1170 resume_writes_alarm_
->Set(clock_
->ApproximateNow());
1174 void QuicConnection::WriteIfNotBlocked() {
1175 if (!writer_
->IsWriteBlocked()) {
1180 bool QuicConnection::ProcessValidatedPacket() {
1181 if (peer_ip_changed_
|| self_ip_changed_
|| self_port_changed_
) {
1182 SendConnectionCloseWithDetails(
1183 QUIC_ERROR_MIGRATING_ADDRESS
,
1184 "Neither IP address migration, nor self port migration are supported.");
1188 // Peer port migration is supported, do it now if port has changed.
1189 if (peer_port_changed_
) {
1190 DVLOG(1) << ENDPOINT
<< "Peer's port changed from "
1191 << peer_address_
.port() << " to " << migrating_peer_port_
1192 << ", migrating connection.";
1193 peer_address_
= IPEndPoint(peer_address_
.address(), migrating_peer_port_
);
1196 time_of_last_received_packet_
= clock_
->Now();
1197 DVLOG(1) << ENDPOINT
<< "time of last received packet: "
1198 << time_of_last_received_packet_
.ToDebuggingValue();
1200 if (is_server_
&& encryption_level_
== ENCRYPTION_NONE
&&
1201 last_size_
> packet_generator_
.max_packet_length()) {
1202 packet_generator_
.set_max_packet_length(last_size_
);
1207 void QuicConnection::WriteQueuedPackets() {
1208 DCHECK(!writer_
->IsWriteBlocked());
1210 if (pending_version_negotiation_packet_
) {
1211 SendVersionNegotiationPacket();
1214 QueuedPacketList::iterator packet_iterator
= queued_packets_
.begin();
1215 while (!writer_
->IsWriteBlocked() &&
1216 packet_iterator
!= queued_packets_
.end()) {
1217 if (WritePacket(*packet_iterator
)) {
1218 delete packet_iterator
->packet
;
1219 packet_iterator
= queued_packets_
.erase(packet_iterator
);
1221 // Continue, because some queued packets may still be writable.
1222 // This can happen if a retransmit send fails.
1228 void QuicConnection::WritePendingRetransmissions() {
1229 // Keep writing as long as there's a pending retransmission which can be
1231 while (sent_packet_manager_
.HasPendingRetransmissions()) {
1232 const QuicSentPacketManager::PendingRetransmission pending
=
1233 sent_packet_manager_
.NextPendingRetransmission();
1234 if (GetPacketType(&pending
.retransmittable_frames
) == NORMAL
&&
1235 !CanWrite(HAS_RETRANSMITTABLE_DATA
)) {
1239 // Re-packetize the frames with a new sequence number for retransmission.
1240 // Retransmitted data packets do not use FEC, even when it's enabled.
1241 // Retransmitted packets use the same sequence number length as the
1243 // Flush the packet generator before making a new packet.
1244 // TODO(ianswett): Implement ReserializeAllFrames as a separate path that
1245 // does not require the creator to be flushed.
1246 packet_generator_
.FlushAllQueuedFrames();
1247 SerializedPacket serialized_packet
= packet_generator_
.ReserializeAllFrames(
1248 pending
.retransmittable_frames
.frames(),
1249 pending
.sequence_number_length
);
1251 DVLOG(1) << ENDPOINT
<< "Retransmitting " << pending
.sequence_number
1252 << " as " << serialized_packet
.sequence_number
;
1253 if (debug_visitor_
.get() != NULL
) {
1254 debug_visitor_
->OnPacketRetransmitted(
1255 pending
.sequence_number
, serialized_packet
.sequence_number
);
1257 sent_packet_manager_
.OnRetransmittedPacket(
1258 pending
.sequence_number
,
1259 serialized_packet
.sequence_number
);
1261 SendOrQueuePacket(pending
.retransmittable_frames
.encryption_level(),
1263 pending
.transmission_type
);
1267 void QuicConnection::RetransmitUnackedPackets(
1268 RetransmissionType retransmission_type
) {
1269 sent_packet_manager_
.RetransmitUnackedPackets(retransmission_type
);
1271 WriteIfNotBlocked();
1274 void QuicConnection::NeuterUnencryptedPackets() {
1275 sent_packet_manager_
.NeuterUnencryptedPackets();
1276 // This may have changed the retransmission timer, so re-arm it.
1277 QuicTime retransmission_time
= sent_packet_manager_
.GetRetransmissionTime();
1278 retransmission_alarm_
->Update(retransmission_time
,
1279 QuicTime::Delta::FromMilliseconds(1));
1282 bool QuicConnection::ShouldGeneratePacket(
1283 TransmissionType transmission_type
,
1284 HasRetransmittableData retransmittable
,
1285 IsHandshake handshake
) {
1286 // We should serialize handshake packets immediately to ensure that they
1287 // end up sent at the right encryption level.
1288 if (handshake
== IS_HANDSHAKE
) {
1292 return CanWrite(retransmittable
);
1295 bool QuicConnection::CanWrite(HasRetransmittableData retransmittable
) {
1296 if (writer_
->IsWriteBlocked()) {
1297 visitor_
->OnWriteBlocked();
1301 QuicTime now
= clock_
->Now();
1302 QuicTime::Delta delay
= sent_packet_manager_
.TimeUntilSend(
1303 now
, retransmittable
);
1304 if (delay
.IsInfinite()) {
1305 send_alarm_
->Cancel();
1309 // If the scheduler requires a delay, then we can not send this packet now.
1310 if (!delay
.IsZero()) {
1311 send_alarm_
->Update(now
.Add(delay
), QuicTime::Delta::FromMilliseconds(1));
1312 DVLOG(1) << "Delaying sending.";
1315 send_alarm_
->Cancel();
1319 bool QuicConnection::WritePacket(QueuedPacket packet
) {
1320 QuicPacketSequenceNumber sequence_number
= packet
.sequence_number
;
1321 if (ShouldDiscardPacket(packet
.encryption_level
,
1323 packet
.retransmittable
)) {
1324 ++stats_
.packets_discarded
;
1328 // If the packet is CONNECTION_CLOSE, we need to try to send it immediately
1329 // and encrypt it to hand it off to TimeWaitListManager.
1330 // If the packet is QUEUED, we don't re-consult the congestion control.
1331 // This ensures packets are sent in sequence number order.
1332 // TODO(ianswett): The congestion control should have been consulted before
1333 // serializing the packet, so this could be turned into a LOG_IF(DFATAL).
1334 if (packet
.type
== NORMAL
&& !CanWrite(packet
.retransmittable
)) {
1338 // Some encryption algorithms require the packet sequence numbers not be
1340 DCHECK_LE(sequence_number_of_last_sent_packet_
, sequence_number
);
1341 sequence_number_of_last_sent_packet_
= sequence_number
;
1343 QuicEncryptedPacket
* encrypted
= framer_
.EncryptPacket(
1344 packet
.encryption_level
, sequence_number
, *packet
.packet
);
1345 if (encrypted
== NULL
) {
1346 LOG(DFATAL
) << ENDPOINT
<< "Failed to encrypt packet number "
1348 // CloseConnection does not send close packet, so no infinite loop here.
1349 CloseConnection(QUIC_ENCRYPTION_FAILURE
, false);
1353 // Connection close packets are eventually owned by TimeWaitListManager.
1354 // Others are deleted at the end of this call.
1355 scoped_ptr
<QuicEncryptedPacket
> encrypted_deleter
;
1356 if (packet
.type
== CONNECTION_CLOSE
) {
1357 DCHECK(connection_close_packet_
.get() == NULL
);
1358 connection_close_packet_
.reset(encrypted
);
1359 // This assures we won't try to write *forced* packets when blocked.
1360 // Return true to stop processing.
1361 if (writer_
->IsWriteBlocked()) {
1362 visitor_
->OnWriteBlocked();
1366 encrypted_deleter
.reset(encrypted
);
1369 if (!FLAGS_quic_allow_oversized_packets_for_test
) {
1370 DCHECK_LE(encrypted
->length(), kMaxPacketSize
);
1372 DCHECK_LE(encrypted
->length(), packet_generator_
.max_packet_length());
1373 DVLOG(1) << ENDPOINT
<< "Sending packet " << sequence_number
1374 << " : " << (packet
.packet
->is_fec_packet() ? "FEC " :
1375 (packet
.retransmittable
== HAS_RETRANSMITTABLE_DATA
1376 ? "data bearing " : " ack only "))
1377 << ", encryption level: "
1378 << QuicUtils::EncryptionLevelToString(packet
.encryption_level
)
1379 << ", length:" << packet
.packet
->length() << ", encrypted length:"
1380 << encrypted
->length();
1381 DVLOG(2) << ENDPOINT
<< "packet(" << sequence_number
<< "): " << std::endl
1382 << QuicUtils::StringToHexASCIIDump(packet
.packet
->AsStringPiece());
1384 WriteResult result
= writer_
->WritePacket(encrypted
->data(),
1385 encrypted
->length(),
1386 self_address().address(),
1388 if (result
.error_code
== ERR_IO_PENDING
) {
1389 DCHECK_EQ(WRITE_STATUS_BLOCKED
, result
.status
);
1391 if (debug_visitor_
.get() != NULL
) {
1392 // Pass the write result to the visitor.
1393 debug_visitor_
->OnPacketSent(sequence_number
,
1394 packet
.encryption_level
,
1395 packet
.transmission_type
,
1400 if (result
.status
== WRITE_STATUS_BLOCKED
) {
1401 visitor_
->OnWriteBlocked();
1402 // If the socket buffers the the data, then the packet should not
1403 // be queued and sent again, which would result in an unnecessary
1404 // duplicate packet being sent. The helper must call OnCanWrite
1405 // when the write completes, and OnWriteError if an error occurs.
1406 if (!writer_
->IsWriteBlockedDataBuffered()) {
1410 QuicTime now
= clock_
->Now();
1411 if (packet
.transmission_type
== NOT_RETRANSMISSION
) {
1412 time_of_last_sent_new_packet_
= now
;
1415 DVLOG(1) << ENDPOINT
<< "time of last sent packet: "
1416 << now
.ToDebuggingValue();
1418 // TODO(ianswett): Change the sequence number length and other packet creator
1419 // options by a more explicit API than setting a struct value directly,
1420 // perhaps via the NetworkChangeVisitor.
1421 packet_generator_
.UpdateSequenceNumberLength(
1422 sent_packet_manager_
.least_packet_awaited_by_peer(),
1423 sent_packet_manager_
.GetCongestionWindow());
1425 bool reset_retransmission_alarm
=
1426 sent_packet_manager_
.OnPacketSent(sequence_number
,
1428 encrypted
->length(),
1429 packet
.transmission_type
,
1430 packet
.retransmittable
);
1432 if (reset_retransmission_alarm
|| !retransmission_alarm_
->IsSet()) {
1433 retransmission_alarm_
->Update(sent_packet_manager_
.GetRetransmissionTime(),
1434 QuicTime::Delta::FromMilliseconds(1));
1437 stats_
.bytes_sent
+= result
.bytes_written
;
1438 ++stats_
.packets_sent
;
1439 if (packet
.transmission_type
!= NOT_RETRANSMISSION
) {
1440 stats_
.bytes_retransmitted
+= result
.bytes_written
;
1441 ++stats_
.packets_retransmitted
;
1444 if (result
.status
== WRITE_STATUS_ERROR
) {
1445 OnWriteError(result
.error_code
);
1452 bool QuicConnection::ShouldDiscardPacket(
1453 EncryptionLevel level
,
1454 QuicPacketSequenceNumber sequence_number
,
1455 HasRetransmittableData retransmittable
) {
1457 DVLOG(1) << ENDPOINT
1458 << "Not sending packet as connection is disconnected.";
1462 // If the packet has been discarded before sending, don't send it.
1463 // This occurs if a packet gets serialized, queued, then discarded.
1464 if (!sent_packet_manager_
.IsUnacked(sequence_number
)) {
1465 DVLOG(1) << ENDPOINT
<< "Dropping packet before sending: "
1466 << sequence_number
<< " since it has already been discarded.";
1470 if (encryption_level_
== ENCRYPTION_FORWARD_SECURE
&&
1471 level
== ENCRYPTION_NONE
) {
1472 // Drop packets that are NULL encrypted since the peer won't accept them
1474 DVLOG(1) << ENDPOINT
<< "Dropping NULL encrypted packet: "
1475 << sequence_number
<< " since the connection is forward secure.";
1477 sent_packet_manager_
.HasRetransmittableFrames(sequence_number
))
1478 << "Once forward secure, all NULL encrypted packets should be "
1483 if (retransmittable
== HAS_RETRANSMITTABLE_DATA
&&
1484 !sent_packet_manager_
.HasRetransmittableFrames(sequence_number
)) {
1485 DVLOG(1) << ENDPOINT
<< "Dropping unacked packet: " << sequence_number
1486 << " A previous transmission was acked while write blocked.";
1493 void QuicConnection::OnWriteError(int error_code
) {
1494 DVLOG(1) << ENDPOINT
<< "Write failed with error: " << error_code
1495 << " (" << ErrorToString(error_code
) << ")";
1496 // We can't send an error as the socket is presumably borked.
1497 CloseConnection(QUIC_PACKET_WRITE_ERROR
, false);
1500 bool QuicConnection::OnSerializedPacket(
1501 const SerializedPacket
& serialized_packet
) {
1502 if (serialized_packet
.retransmittable_frames
) {
1503 serialized_packet
.retransmittable_frames
->
1504 set_encryption_level(encryption_level_
);
1506 sent_packet_manager_
.OnSerializedPacket(serialized_packet
);
1507 // The TransmissionType is NOT_RETRANSMISSION because all retransmissions
1508 // serialize packets and invoke SendOrQueuePacket directly.
1509 return SendOrQueuePacket(encryption_level_
,
1511 NOT_RETRANSMISSION
);
1514 void QuicConnection::OnCongestionWindowChange(QuicByteCount congestion_window
) {
1515 packet_generator_
.OnCongestionWindowChange(congestion_window
);
1516 visitor_
->OnCongestionWindowChange(clock_
->ApproximateNow());
1519 void QuicConnection::OnHandshakeComplete() {
1520 sent_packet_manager_
.SetHandshakeConfirmed();
1523 bool QuicConnection::SendOrQueuePacket(EncryptionLevel level
,
1524 const SerializedPacket
& packet
,
1525 TransmissionType transmission_type
) {
1526 if (packet
.packet
== NULL
) {
1527 LOG(DFATAL
) << "NULL packet passed in to SendOrQueuePacket";
1531 sent_entropy_manager_
.RecordPacketEntropyHash(packet
.sequence_number
,
1532 packet
.entropy_hash
);
1533 QueuedPacket
queued_packet(packet
, level
, transmission_type
);
1534 // If there are already queued packets, put this at the end,
1535 // unless it's ConnectionClose, in which case it is written immediately.
1536 if ((queued_packet
.type
== CONNECTION_CLOSE
|| queued_packets_
.empty()) &&
1537 WritePacket(queued_packet
)) {
1538 delete packet
.packet
;
1541 queued_packet
.type
= QUEUED
;
1542 queued_packets_
.push_back(queued_packet
);
1546 void QuicConnection::UpdateStopWaiting(QuicStopWaitingFrame
* stop_waiting
) {
1547 stop_waiting
->least_unacked
= GetLeastUnacked();
1548 stop_waiting
->entropy_hash
= sent_entropy_manager_
.GetCumulativeEntropy(
1549 stop_waiting
->least_unacked
- 1);
1552 void QuicConnection::SendPing() {
1553 if (retransmission_alarm_
->IsSet()) {
1556 if (version() == QUIC_VERSION_16
) {
1557 // TODO(rch): remove this when we remove version 15 and 16.
1558 // This is a horrible hideous hack which we should not support.
1560 char c_data
[] = "C";
1561 data
.Append(c_data
, 1);
1562 QuicConsumedData consumed_data
=
1563 packet_generator_
.ConsumeData(kCryptoStreamId
, data
, 0, false,
1564 MAY_FEC_PROTECT
, NULL
);
1565 if (consumed_data
.bytes_consumed
== 0) {
1566 DLOG(ERROR
) << "Unable to send ping!?";
1569 packet_generator_
.AddControlFrame(QuicFrame(new QuicPingFrame
));
1573 void QuicConnection::SendAck() {
1574 ack_alarm_
->Cancel();
1575 stop_waiting_count_
= 0;
1576 bool send_feedback
= false;
1578 // Deprecating the Congestion Feedback Frame after QUIC_VERSION_22.
1579 if (version() <= QUIC_VERSION_22
) {
1580 if (received_packet_manager_
.GenerateCongestionFeedback(
1581 &outgoing_congestion_feedback_
)) {
1582 DVLOG(1) << ENDPOINT
<< "Sending feedback: "
1583 << outgoing_congestion_feedback_
;
1584 send_feedback
= true;
1588 packet_generator_
.SetShouldSendAck(send_feedback
, true);
1591 void QuicConnection::OnRetransmissionTimeout() {
1592 if (!sent_packet_manager_
.HasUnackedPackets()) {
1596 sent_packet_manager_
.OnRetransmissionTimeout();
1597 WriteIfNotBlocked();
1599 // A write failure can result in the connection being closed, don't attempt to
1600 // write further packets, or to set alarms.
1605 // In the TLP case, the SentPacketManager gives the connection the opportunity
1606 // to send new data before retransmitting.
1607 if (sent_packet_manager_
.MaybeRetransmitTailLossProbe()) {
1608 // Send the pending retransmission now that it's been queued.
1609 WriteIfNotBlocked();
1612 // Ensure the retransmission alarm is always set if there are unacked packets
1613 // and nothing waiting to be sent.
1614 if (!HasQueuedData() && !retransmission_alarm_
->IsSet()) {
1615 QuicTime rto_timeout
= sent_packet_manager_
.GetRetransmissionTime();
1616 if (rto_timeout
.IsInitialized()) {
1617 retransmission_alarm_
->Set(rto_timeout
);
1622 void QuicConnection::SetEncrypter(EncryptionLevel level
,
1623 QuicEncrypter
* encrypter
) {
1624 framer_
.SetEncrypter(level
, encrypter
);
1627 const QuicEncrypter
* QuicConnection::encrypter(EncryptionLevel level
) const {
1628 return framer_
.encrypter(level
);
1631 void QuicConnection::SetDefaultEncryptionLevel(EncryptionLevel level
) {
1632 encryption_level_
= level
;
1633 packet_generator_
.set_encryption_level(level
);
1636 void QuicConnection::SetDecrypter(QuicDecrypter
* decrypter
,
1637 EncryptionLevel level
) {
1638 framer_
.SetDecrypter(decrypter
, level
);
1641 void QuicConnection::SetAlternativeDecrypter(QuicDecrypter
* decrypter
,
1642 EncryptionLevel level
,
1643 bool latch_once_used
) {
1644 framer_
.SetAlternativeDecrypter(decrypter
, level
, latch_once_used
);
1647 const QuicDecrypter
* QuicConnection::decrypter() const {
1648 return framer_
.decrypter();
1651 const QuicDecrypter
* QuicConnection::alternative_decrypter() const {
1652 return framer_
.alternative_decrypter();
1655 void QuicConnection::QueueUndecryptablePacket(
1656 const QuicEncryptedPacket
& packet
) {
1657 DVLOG(1) << ENDPOINT
<< "Queueing undecryptable packet.";
1658 undecryptable_packets_
.push_back(packet
.Clone());
1661 void QuicConnection::MaybeProcessUndecryptablePackets() {
1662 if (undecryptable_packets_
.empty() || encryption_level_
== ENCRYPTION_NONE
) {
1666 while (connected_
&& !undecryptable_packets_
.empty()) {
1667 DVLOG(1) << ENDPOINT
<< "Attempting to process undecryptable packet";
1668 QuicEncryptedPacket
* packet
= undecryptable_packets_
.front();
1669 if (!framer_
.ProcessPacket(*packet
) &&
1670 framer_
.error() == QUIC_DECRYPTION_FAILURE
) {
1671 DVLOG(1) << ENDPOINT
<< "Unable to process undecryptable packet...";
1674 DVLOG(1) << ENDPOINT
<< "Processed undecryptable packet!";
1675 ++stats_
.packets_processed
;
1677 undecryptable_packets_
.pop_front();
1680 // Once forward secure encryption is in use, there will be no
1681 // new keys installed and hence any undecryptable packets will
1682 // never be able to be decrypted.
1683 if (encryption_level_
== ENCRYPTION_FORWARD_SECURE
) {
1684 if (debug_visitor_
.get() != NULL
) {
1685 // TODO(rtenneti): perhaps more efficient to pass the number of
1686 // undecryptable packets as the argument to OnUndecryptablePacket so that
1687 // we just need to call OnUndecryptablePacket once?
1688 for (size_t i
= 0; i
< undecryptable_packets_
.size(); ++i
) {
1689 debug_visitor_
->OnUndecryptablePacket();
1692 STLDeleteElements(&undecryptable_packets_
);
1696 void QuicConnection::MaybeProcessRevivedPacket() {
1697 QuicFecGroup
* group
= GetFecGroup();
1698 if (!connected_
|| group
== NULL
|| !group
->CanRevive()) {
1701 QuicPacketHeader revived_header
;
1702 char revived_payload
[kMaxPacketSize
];
1703 size_t len
= group
->Revive(&revived_header
, revived_payload
, kMaxPacketSize
);
1704 revived_header
.public_header
.connection_id
= connection_id_
;
1705 revived_header
.public_header
.connection_id_length
=
1706 last_header_
.public_header
.connection_id_length
;
1707 revived_header
.public_header
.version_flag
= false;
1708 revived_header
.public_header
.reset_flag
= false;
1709 revived_header
.public_header
.sequence_number_length
=
1710 last_header_
.public_header
.sequence_number_length
;
1711 revived_header
.fec_flag
= false;
1712 revived_header
.is_in_fec_group
= NOT_IN_FEC_GROUP
;
1713 revived_header
.fec_group
= 0;
1714 group_map_
.erase(last_header_
.fec_group
);
1715 last_decrypted_packet_level_
= group
->effective_encryption_level();
1716 DCHECK_LT(last_decrypted_packet_level_
, NUM_ENCRYPTION_LEVELS
);
1719 last_packet_revived_
= true;
1720 if (debug_visitor_
.get() != NULL
) {
1721 debug_visitor_
->OnRevivedPacket(revived_header
,
1722 StringPiece(revived_payload
, len
));
1725 ++stats_
.packets_revived
;
1726 framer_
.ProcessRevivedPacket(&revived_header
,
1727 StringPiece(revived_payload
, len
));
1730 QuicFecGroup
* QuicConnection::GetFecGroup() {
1731 QuicFecGroupNumber fec_group_num
= last_header_
.fec_group
;
1732 if (fec_group_num
== 0) {
1735 if (group_map_
.count(fec_group_num
) == 0) {
1736 if (group_map_
.size() >= kMaxFecGroups
) { // Too many groups
1737 if (fec_group_num
< group_map_
.begin()->first
) {
1738 // The group being requested is a group we've seen before and deleted.
1739 // Don't recreate it.
1742 // Clear the lowest group number.
1743 delete group_map_
.begin()->second
;
1744 group_map_
.erase(group_map_
.begin());
1746 group_map_
[fec_group_num
] = new QuicFecGroup();
1748 return group_map_
[fec_group_num
];
1751 void QuicConnection::SendConnectionClose(QuicErrorCode error
) {
1752 SendConnectionCloseWithDetails(error
, string());
1755 void QuicConnection::SendConnectionCloseWithDetails(QuicErrorCode error
,
1756 const string
& details
) {
1757 // If we're write blocked, WritePacket() will not send, but will capture the
1758 // serialized packet.
1759 SendConnectionClosePacket(error
, details
);
1761 // It's possible that while sending the connection close packet, we get a
1762 // socket error and disconnect right then and there. Avoid a double
1763 // disconnect in that case.
1764 CloseConnection(error
, false);
1768 void QuicConnection::SendConnectionClosePacket(QuicErrorCode error
,
1769 const string
& details
) {
1770 DVLOG(1) << ENDPOINT
<< "Force closing " << connection_id()
1771 << " with error " << QuicUtils::ErrorToString(error
)
1772 << " (" << error
<< ") " << details
;
1773 ScopedPacketBundler
ack_bundler(this, SEND_ACK
);
1774 QuicConnectionCloseFrame
* frame
= new QuicConnectionCloseFrame();
1775 frame
->error_code
= error
;
1776 frame
->error_details
= details
;
1777 packet_generator_
.AddControlFrame(QuicFrame(frame
));
1778 packet_generator_
.FlushAllQueuedFrames();
1781 void QuicConnection::CloseConnection(QuicErrorCode error
, bool from_peer
) {
1783 DLOG(DFATAL
) << "Error: attempt to close an already closed connection"
1784 << base::debug::StackTrace().ToString();
1788 if (debug_visitor_
.get() != NULL
) {
1789 debug_visitor_
->OnConnectionClosed(error
, from_peer
);
1791 visitor_
->OnConnectionClosed(error
, from_peer
);
1792 // Cancel the alarms so they don't trigger any action now that the
1793 // connection is closed.
1794 ack_alarm_
->Cancel();
1795 ping_alarm_
->Cancel();
1796 resume_writes_alarm_
->Cancel();
1797 retransmission_alarm_
->Cancel();
1798 send_alarm_
->Cancel();
1799 timeout_alarm_
->Cancel();
1802 void QuicConnection::SendGoAway(QuicErrorCode error
,
1803 QuicStreamId last_good_stream_id
,
1804 const string
& reason
) {
1805 DVLOG(1) << ENDPOINT
<< "Going away with error "
1806 << QuicUtils::ErrorToString(error
)
1807 << " (" << error
<< ")";
1809 // Opportunistically bundle an ack with this outgoing packet.
1810 ScopedPacketBundler
ack_bundler(this, BUNDLE_PENDING_ACK
);
1811 packet_generator_
.AddControlFrame(
1812 QuicFrame(new QuicGoAwayFrame(error
, last_good_stream_id
, reason
)));
1815 void QuicConnection::CloseFecGroupsBefore(
1816 QuicPacketSequenceNumber sequence_number
) {
1817 FecGroupMap::iterator it
= group_map_
.begin();
1818 while (it
!= group_map_
.end()) {
1819 // If this is the current group or the group doesn't protect this packet
1820 // we can ignore it.
1821 if (last_header_
.fec_group
== it
->first
||
1822 !it
->second
->ProtectsPacketsBefore(sequence_number
)) {
1826 QuicFecGroup
* fec_group
= it
->second
;
1827 DCHECK(!fec_group
->CanRevive());
1828 FecGroupMap::iterator next
= it
;
1830 group_map_
.erase(it
);
1836 size_t QuicConnection::max_packet_length() const {
1837 return packet_generator_
.max_packet_length();
1840 void QuicConnection::set_max_packet_length(size_t length
) {
1841 return packet_generator_
.set_max_packet_length(length
);
1844 bool QuicConnection::HasQueuedData() const {
1845 return pending_version_negotiation_packet_
||
1846 !queued_packets_
.empty() || packet_generator_
.HasQueuedFrames();
1849 bool QuicConnection::CanWriteStreamData() {
1850 // Don't write stream data if there are negotiation or queued data packets
1851 // to send. Otherwise, continue and bundle as many frames as possible.
1852 if (pending_version_negotiation_packet_
|| !queued_packets_
.empty()) {
1856 IsHandshake pending_handshake
= visitor_
->HasPendingHandshake() ?
1857 IS_HANDSHAKE
: NOT_HANDSHAKE
;
1858 // Sending queued packets may have caused the socket to become write blocked,
1859 // or the congestion manager to prohibit sending. If we've sent everything
1860 // we had queued and we're still not blocked, let the visitor know it can
1862 return ShouldGeneratePacket(NOT_RETRANSMISSION
, HAS_RETRANSMITTABLE_DATA
,
1866 void QuicConnection::SetIdleNetworkTimeout(QuicTime::Delta timeout
) {
1867 // Adjust the idle timeout on client and server to prevent clients from
1868 // sending requests to servers which have already closed the connection.
1870 timeout
= timeout
.Add(QuicTime::Delta::FromSeconds(1));
1871 } else if (timeout
> QuicTime::Delta::FromSeconds(1)) {
1872 timeout
= timeout
.Subtract(QuicTime::Delta::FromSeconds(1));
1875 if (timeout
< idle_network_timeout_
) {
1876 idle_network_timeout_
= timeout
;
1879 idle_network_timeout_
= timeout
;
1883 void QuicConnection::SetOverallConnectionTimeout(QuicTime::Delta timeout
) {
1884 if (timeout
< overall_connection_timeout_
) {
1885 overall_connection_timeout_
= timeout
;
1888 overall_connection_timeout_
= timeout
;
1892 bool QuicConnection::CheckForTimeout() {
1893 QuicTime now
= clock_
->ApproximateNow();
1894 QuicTime time_of_last_packet
= max(time_of_last_received_packet_
,
1895 time_of_last_sent_new_packet_
);
1897 // |delta| can be < 0 as |now| is approximate time but |time_of_last_packet|
1898 // is accurate time. However, this should not change the behavior of
1899 // timeout handling.
1900 QuicTime::Delta delta
= now
.Subtract(time_of_last_packet
);
1901 DVLOG(1) << ENDPOINT
<< "last packet "
1902 << time_of_last_packet
.ToDebuggingValue()
1903 << " now:" << now
.ToDebuggingValue()
1904 << " delta:" << delta
.ToMicroseconds()
1905 << " network_timeout: " << idle_network_timeout_
.ToMicroseconds();
1906 if (delta
>= idle_network_timeout_
) {
1907 DVLOG(1) << ENDPOINT
<< "Connection timedout due to no network activity.";
1908 SendConnectionClose(QUIC_CONNECTION_TIMED_OUT
);
1912 // Next timeout delta.
1913 QuicTime::Delta timeout
= idle_network_timeout_
.Subtract(delta
);
1915 if (!overall_connection_timeout_
.IsInfinite()) {
1916 QuicTime::Delta connected_time
=
1917 now
.Subtract(stats_
.connection_creation_time
);
1918 DVLOG(1) << ENDPOINT
<< "connection time: "
1919 << connected_time
.ToMilliseconds() << " overall timeout: "
1920 << overall_connection_timeout_
.ToMilliseconds();
1921 if (connected_time
>= overall_connection_timeout_
) {
1922 DVLOG(1) << ENDPOINT
<<
1923 "Connection timedout due to overall connection timeout.";
1924 SendConnectionClose(QUIC_CONNECTION_TIMED_OUT
);
1928 // Take the min timeout.
1929 QuicTime::Delta connection_timeout
=
1930 overall_connection_timeout_
.Subtract(connected_time
);
1931 if (connection_timeout
< timeout
) {
1932 timeout
= connection_timeout
;
1936 timeout_alarm_
->Cancel();
1937 timeout_alarm_
->Set(now
.Add(timeout
));
1941 void QuicConnection::SetPingAlarm() {
1943 // Only clients send pings.
1946 if (!visitor_
->HasOpenDataStreams()) {
1947 ping_alarm_
->Cancel();
1948 // Don't send a ping unless there are open streams.
1951 QuicTime::Delta ping_timeout
= QuicTime::Delta::FromSeconds(kPingTimeoutSecs
);
1952 ping_alarm_
->Update(clock_
->ApproximateNow().Add(ping_timeout
),
1953 QuicTime::Delta::FromSeconds(1));
1956 QuicConnection::ScopedPacketBundler::ScopedPacketBundler(
1957 QuicConnection
* connection
,
1958 AckBundling send_ack
)
1959 : connection_(connection
),
1960 already_in_batch_mode_(connection
!= NULL
&&
1961 connection
->packet_generator_
.InBatchMode()) {
1962 if (connection_
== NULL
) {
1965 // Move generator into batch mode. If caller wants us to include an ack,
1966 // check the delayed-ack timer to see if there's ack info to be sent.
1967 if (!already_in_batch_mode_
) {
1968 DVLOG(1) << "Entering Batch Mode.";
1969 connection_
->packet_generator_
.StartBatchOperations();
1971 // Bundle an ack if the alarm is set or with every second packet if we need to
1972 // raise the peer's least unacked.
1974 connection_
->ack_alarm_
->IsSet() || connection_
->stop_waiting_count_
> 1;
1975 if (send_ack
== SEND_ACK
|| (send_ack
== BUNDLE_PENDING_ACK
&& ack_pending
)) {
1976 DVLOG(1) << "Bundling ack with outgoing packet.";
1977 connection_
->SendAck();
1981 QuicConnection::ScopedPacketBundler::~ScopedPacketBundler() {
1982 if (connection_
== NULL
) {
1985 // If we changed the generator's batch state, restore original batch state.
1986 if (!already_in_batch_mode_
) {
1987 DVLOG(1) << "Leaving Batch Mode.";
1988 connection_
->packet_generator_
.FinishBatchOperations();
1990 DCHECK_EQ(already_in_batch_mode_
,
1991 connection_
->packet_generator_
.InBatchMode());