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 QuicPacketWriter
* writer
,
195 const QuicVersionVector
& supported_versions
)
196 : framer_(supported_versions
, helper
->GetClock()->ApproximateNow(),
200 encryption_level_(ENCRYPTION_NONE
),
201 clock_(helper
->GetClock()),
202 random_generator_(helper
->GetRandomGenerator()),
203 connection_id_(connection_id
),
204 peer_address_(address
),
205 migrating_peer_port_(0),
206 last_packet_revived_(false),
208 last_decrypted_packet_level_(ENCRYPTION_NONE
),
209 largest_seen_packet_with_ack_(0),
210 largest_seen_packet_with_stop_waiting_(0),
211 pending_version_negotiation_packet_(false),
212 received_packet_manager_(kTCP
, &stats_
),
214 stop_waiting_count_(0),
215 ack_alarm_(helper
->CreateAlarm(new AckAlarm(this))),
216 retransmission_alarm_(helper
->CreateAlarm(new RetransmissionAlarm(this))),
217 send_alarm_(helper
->CreateAlarm(new SendAlarm(this))),
218 resume_writes_alarm_(helper
->CreateAlarm(new SendAlarm(this))),
219 timeout_alarm_(helper
->CreateAlarm(new TimeoutAlarm(this))),
220 ping_alarm_(helper
->CreateAlarm(new PingAlarm(this))),
221 debug_visitor_(NULL
),
222 packet_generator_(connection_id_
, &framer_
, random_generator_
, this),
223 idle_network_timeout_(
224 QuicTime::Delta::FromSeconds(kDefaultInitialTimeoutSecs
)),
225 overall_connection_timeout_(QuicTime::Delta::Infinite()),
226 time_of_last_received_packet_(clock_
->ApproximateNow()),
227 time_of_last_sent_new_packet_(clock_
->ApproximateNow()),
228 sequence_number_of_last_sent_packet_(0),
229 sent_packet_manager_(
230 is_server
, clock_
, &stats_
, kTCP
,
231 FLAGS_quic_use_time_loss_detection
? kTime
: kNack
),
232 version_negotiation_state_(START_NEGOTIATION
),
233 is_server_(is_server
),
235 peer_ip_changed_(false),
236 peer_port_changed_(false),
237 self_ip_changed_(false),
238 self_port_changed_(false) {
240 // Pacing will be enabled if the client negotiates it.
241 sent_packet_manager_
.MaybeEnablePacing();
243 DVLOG(1) << ENDPOINT
<< "Created connection with connection_id: "
245 timeout_alarm_
->Set(clock_
->ApproximateNow().Add(idle_network_timeout_
));
246 framer_
.set_visitor(this);
247 framer_
.set_received_entropy_calculator(&received_packet_manager_
);
248 stats_
.connection_creation_time
= clock_
->ApproximateNow();
251 QuicConnection::~QuicConnection() {
252 STLDeleteElements(&undecryptable_packets_
);
253 STLDeleteValues(&group_map_
);
254 for (QueuedPacketList::iterator it
= queued_packets_
.begin();
255 it
!= queued_packets_
.end(); ++it
) {
260 void QuicConnection::SetFromConfig(const QuicConfig
& config
) {
261 SetIdleNetworkTimeout(config
.idle_connection_state_lifetime());
262 sent_packet_manager_
.SetFromConfig(config
);
263 // TODO(satyamshekhar): Set congestion control and ICSL also.
266 bool QuicConnection::SelectMutualVersion(
267 const QuicVersionVector
& available_versions
) {
268 // Try to find the highest mutual version by iterating over supported
269 // versions, starting with the highest, and breaking out of the loop once we
270 // find a matching version in the provided available_versions vector.
271 const QuicVersionVector
& supported_versions
= framer_
.supported_versions();
272 for (size_t i
= 0; i
< supported_versions
.size(); ++i
) {
273 const QuicVersion
& version
= supported_versions
[i
];
274 if (std::find(available_versions
.begin(), available_versions
.end(),
275 version
) != available_versions
.end()) {
276 framer_
.set_version(version
);
284 void QuicConnection::OnError(QuicFramer
* framer
) {
285 // Packets that we cannot decrypt are dropped.
286 // TODO(rch): add stats to measure this.
287 if (!connected_
|| framer
->error() == QUIC_DECRYPTION_FAILURE
) {
290 SendConnectionCloseWithDetails(framer
->error(), framer
->detailed_error());
293 void QuicConnection::OnPacket() {
294 DCHECK(last_stream_frames_
.empty() &&
295 last_goaway_frames_
.empty() &&
296 last_window_update_frames_
.empty() &&
297 last_blocked_frames_
.empty() &&
298 last_rst_frames_
.empty() &&
299 last_ack_frames_
.empty() &&
300 last_congestion_frames_
.empty() &&
301 last_stop_waiting_frames_
.empty());
304 void QuicConnection::OnPublicResetPacket(
305 const QuicPublicResetPacket
& packet
) {
306 if (debug_visitor_
) {
307 debug_visitor_
->OnPublicResetPacket(packet
);
309 CloseConnection(QUIC_PUBLIC_RESET
, true);
312 bool QuicConnection::OnProtocolVersionMismatch(QuicVersion received_version
) {
313 DVLOG(1) << ENDPOINT
<< "Received packet with mismatched version "
315 // TODO(satyamshekhar): Implement no server state in this mode.
317 LOG(DFATAL
) << ENDPOINT
<< "Framer called OnProtocolVersionMismatch. "
318 << "Closing connection.";
319 CloseConnection(QUIC_INTERNAL_ERROR
, false);
322 DCHECK_NE(version(), received_version
);
324 if (debug_visitor_
) {
325 debug_visitor_
->OnProtocolVersionMismatch(received_version
);
328 switch (version_negotiation_state_
) {
329 case START_NEGOTIATION
:
330 if (!framer_
.IsSupportedVersion(received_version
)) {
331 SendVersionNegotiationPacket();
332 version_negotiation_state_
= NEGOTIATION_IN_PROGRESS
;
337 case NEGOTIATION_IN_PROGRESS
:
338 if (!framer_
.IsSupportedVersion(received_version
)) {
339 SendVersionNegotiationPacket();
344 case NEGOTIATED_VERSION
:
345 // Might be old packets that were sent by the client before the version
346 // was negotiated. Drop these.
353 version_negotiation_state_
= NEGOTIATED_VERSION
;
354 visitor_
->OnSuccessfulVersionNegotiation(received_version
);
355 DVLOG(1) << ENDPOINT
<< "version negotiated " << received_version
;
357 // Store the new version.
358 framer_
.set_version(received_version
);
360 // TODO(satyamshekhar): Store the sequence number of this packet and close the
361 // connection if we ever received a packet with incorrect version and whose
362 // sequence number is greater.
366 // Handles version negotiation for client connection.
367 void QuicConnection::OnVersionNegotiationPacket(
368 const QuicVersionNegotiationPacket
& packet
) {
370 LOG(DFATAL
) << ENDPOINT
<< "Framer parsed VersionNegotiationPacket."
371 << " Closing connection.";
372 CloseConnection(QUIC_INTERNAL_ERROR
, false);
375 if (debug_visitor_
) {
376 debug_visitor_
->OnVersionNegotiationPacket(packet
);
379 if (version_negotiation_state_
!= START_NEGOTIATION
) {
380 // Possibly a duplicate version negotiation packet.
384 if (std::find(packet
.versions
.begin(),
385 packet
.versions
.end(), version()) !=
386 packet
.versions
.end()) {
387 DLOG(WARNING
) << ENDPOINT
<< "The server already supports our version. "
388 << "It should have accepted our connection.";
389 // Just drop the connection.
390 CloseConnection(QUIC_INVALID_VERSION_NEGOTIATION_PACKET
, false);
394 if (!SelectMutualVersion(packet
.versions
)) {
395 SendConnectionCloseWithDetails(QUIC_INVALID_VERSION
,
396 "no common version found");
400 DVLOG(1) << ENDPOINT
<< "negotiating version " << version();
401 server_supported_versions_
= packet
.versions
;
402 version_negotiation_state_
= NEGOTIATION_IN_PROGRESS
;
403 RetransmitUnackedPackets(ALL_PACKETS
);
406 void QuicConnection::OnRevivedPacket() {
409 bool QuicConnection::OnUnauthenticatedPublicHeader(
410 const QuicPacketPublicHeader
& header
) {
414 bool QuicConnection::OnUnauthenticatedHeader(const QuicPacketHeader
& header
) {
418 void QuicConnection::OnDecryptedPacket(EncryptionLevel level
) {
419 last_decrypted_packet_level_
= level
;
422 bool QuicConnection::OnPacketHeader(const QuicPacketHeader
& header
) {
423 if (debug_visitor_
) {
424 debug_visitor_
->OnPacketHeader(header
);
427 if (!ProcessValidatedPacket()) {
431 // Will be decrement below if we fall through to return true;
432 ++stats_
.packets_dropped
;
434 if (header
.public_header
.connection_id
!= connection_id_
) {
435 DVLOG(1) << ENDPOINT
<< "Ignoring packet from unexpected ConnectionId: "
436 << header
.public_header
.connection_id
<< " instead of "
441 if (!Near(header
.packet_sequence_number
,
442 last_header_
.packet_sequence_number
)) {
443 DVLOG(1) << ENDPOINT
<< "Packet " << header
.packet_sequence_number
444 << " out of bounds. Discarding";
445 SendConnectionCloseWithDetails(QUIC_INVALID_PACKET_HEADER
,
446 "Packet sequence number out of bounds");
450 // If this packet has already been seen, or that the sender
451 // has told us will not be retransmitted, then stop processing the packet.
452 if (!received_packet_manager_
.IsAwaitingPacket(
453 header
.packet_sequence_number
)) {
454 DVLOG(1) << ENDPOINT
<< "Packet " << header
.packet_sequence_number
455 << " no longer being waited for. Discarding.";
456 // TODO(jri): Log reception of duplicate packets or packets the peer has
457 // told us to stop waiting for.
461 if (version_negotiation_state_
!= NEGOTIATED_VERSION
) {
463 if (!header
.public_header
.version_flag
) {
464 DLOG(WARNING
) << ENDPOINT
<< "Packet " << header
.packet_sequence_number
465 << " without version flag before version negotiated.";
466 // Packets should have the version flag till version negotiation is
468 CloseConnection(QUIC_INVALID_VERSION
, false);
471 DCHECK_EQ(1u, header
.public_header
.versions
.size());
472 DCHECK_EQ(header
.public_header
.versions
[0], version());
473 version_negotiation_state_
= NEGOTIATED_VERSION
;
474 visitor_
->OnSuccessfulVersionNegotiation(version());
477 DCHECK(!header
.public_header
.version_flag
);
478 // If the client gets a packet without the version flag from the server
479 // it should stop sending version since the version negotiation is done.
480 packet_generator_
.StopSendingVersion();
481 version_negotiation_state_
= NEGOTIATED_VERSION
;
482 visitor_
->OnSuccessfulVersionNegotiation(version());
486 DCHECK_EQ(NEGOTIATED_VERSION
, version_negotiation_state_
);
488 --stats_
.packets_dropped
;
489 DVLOG(1) << ENDPOINT
<< "Received packet header: " << header
;
490 last_header_
= header
;
495 void QuicConnection::OnFecProtectedPayload(StringPiece payload
) {
496 DCHECK_EQ(IN_FEC_GROUP
, last_header_
.is_in_fec_group
);
497 DCHECK_NE(0u, last_header_
.fec_group
);
498 QuicFecGroup
* group
= GetFecGroup();
500 group
->Update(last_decrypted_packet_level_
, last_header_
, payload
);
504 bool QuicConnection::OnStreamFrame(const QuicStreamFrame
& frame
) {
506 if (debug_visitor_
) {
507 debug_visitor_
->OnStreamFrame(frame
);
509 if (frame
.stream_id
!= kCryptoStreamId
&&
510 last_decrypted_packet_level_
== ENCRYPTION_NONE
) {
511 DLOG(WARNING
) << ENDPOINT
512 << "Received an unencrypted data frame: closing connection";
513 SendConnectionClose(QUIC_UNENCRYPTED_STREAM_DATA
);
516 last_stream_frames_
.push_back(frame
);
520 bool QuicConnection::OnAckFrame(const QuicAckFrame
& incoming_ack
) {
522 if (debug_visitor_
) {
523 debug_visitor_
->OnAckFrame(incoming_ack
);
525 DVLOG(1) << ENDPOINT
<< "OnAckFrame: " << incoming_ack
;
527 if (last_header_
.packet_sequence_number
<= largest_seen_packet_with_ack_
) {
528 DVLOG(1) << ENDPOINT
<< "Received an old ack frame: ignoring";
532 if (!ValidateAckFrame(incoming_ack
)) {
533 SendConnectionClose(QUIC_INVALID_ACK_DATA
);
537 last_ack_frames_
.push_back(incoming_ack
);
541 void QuicConnection::ProcessAckFrame(const QuicAckFrame
& incoming_ack
) {
542 largest_seen_packet_with_ack_
= last_header_
.packet_sequence_number
;
543 received_packet_manager_
.UpdatePacketInformationReceivedByPeer(
544 incoming_ack
.received_info
);
545 if (version() <= QUIC_VERSION_15
) {
546 ProcessStopWaitingFrame(incoming_ack
.sent_info
);
549 sent_entropy_manager_
.ClearEntropyBefore(
550 received_packet_manager_
.least_packet_awaited_by_peer() - 1);
552 sent_packet_manager_
.OnIncomingAck(incoming_ack
.received_info
,
553 time_of_last_received_packet_
);
554 if (sent_packet_manager_
.HasPendingRetransmissions()) {
558 // Always reset the retransmission alarm when an ack comes in, since we now
559 // have a better estimate of the current rtt than when it was set.
560 retransmission_alarm_
->Cancel();
561 QuicTime retransmission_time
=
562 sent_packet_manager_
.GetRetransmissionTime();
563 if (retransmission_time
!= QuicTime::Zero()) {
564 retransmission_alarm_
->Set(retransmission_time
);
568 void QuicConnection::ProcessStopWaitingFrame(
569 const QuicStopWaitingFrame
& stop_waiting
) {
570 largest_seen_packet_with_stop_waiting_
= last_header_
.packet_sequence_number
;
571 received_packet_manager_
.UpdatePacketInformationSentByPeer(stop_waiting
);
572 // Possibly close any FecGroups which are now irrelevant.
573 CloseFecGroupsBefore(stop_waiting
.least_unacked
+ 1);
576 bool QuicConnection::OnCongestionFeedbackFrame(
577 const QuicCongestionFeedbackFrame
& feedback
) {
579 if (debug_visitor_
) {
580 debug_visitor_
->OnCongestionFeedbackFrame(feedback
);
582 last_congestion_frames_
.push_back(feedback
);
586 bool QuicConnection::OnStopWaitingFrame(const QuicStopWaitingFrame
& frame
) {
589 if (last_header_
.packet_sequence_number
<=
590 largest_seen_packet_with_stop_waiting_
) {
591 DVLOG(1) << ENDPOINT
<< "Received an old stop waiting frame: ignoring";
595 if (!ValidateStopWaitingFrame(frame
)) {
596 SendConnectionClose(QUIC_INVALID_STOP_WAITING_DATA
);
600 if (debug_visitor_
) {
601 debug_visitor_
->OnStopWaitingFrame(frame
);
604 last_stop_waiting_frames_
.push_back(frame
);
608 bool QuicConnection::OnPingFrame(const QuicPingFrame
& frame
) {
610 if (debug_visitor_
) {
611 debug_visitor_
->OnPingFrame(frame
);
616 bool QuicConnection::ValidateAckFrame(const QuicAckFrame
& incoming_ack
) {
617 if (incoming_ack
.received_info
.largest_observed
>
618 packet_generator_
.sequence_number()) {
619 DLOG(ERROR
) << ENDPOINT
<< "Peer's observed unsent packet:"
620 << incoming_ack
.received_info
.largest_observed
<< " vs "
621 << packet_generator_
.sequence_number();
622 // We got an error for data we have not sent. Error out.
626 if (incoming_ack
.received_info
.largest_observed
<
627 received_packet_manager_
.peer_largest_observed_packet()) {
628 DLOG(ERROR
) << ENDPOINT
<< "Peer's largest_observed packet decreased:"
629 << incoming_ack
.received_info
.largest_observed
<< " vs "
630 << received_packet_manager_
.peer_largest_observed_packet();
631 // A new ack has a diminished largest_observed value. Error out.
632 // If this was an old packet, we wouldn't even have checked.
636 if (version() <= QUIC_VERSION_15
) {
637 if (!ValidateStopWaitingFrame(incoming_ack
.sent_info
)) {
642 if (!incoming_ack
.received_info
.missing_packets
.empty() &&
643 *incoming_ack
.received_info
.missing_packets
.rbegin() >
644 incoming_ack
.received_info
.largest_observed
) {
645 DLOG(ERROR
) << ENDPOINT
<< "Peer sent missing packet: "
646 << *incoming_ack
.received_info
.missing_packets
.rbegin()
647 << " which is greater than largest observed: "
648 << incoming_ack
.received_info
.largest_observed
;
652 if (!incoming_ack
.received_info
.missing_packets
.empty() &&
653 *incoming_ack
.received_info
.missing_packets
.begin() <
654 received_packet_manager_
.least_packet_awaited_by_peer()) {
655 DLOG(ERROR
) << ENDPOINT
<< "Peer sent missing packet: "
656 << *incoming_ack
.received_info
.missing_packets
.begin()
657 << " which is smaller than least_packet_awaited_by_peer_: "
658 << received_packet_manager_
.least_packet_awaited_by_peer();
662 if (!sent_entropy_manager_
.IsValidEntropy(
663 incoming_ack
.received_info
.largest_observed
,
664 incoming_ack
.received_info
.missing_packets
,
665 incoming_ack
.received_info
.entropy_hash
)) {
666 DLOG(ERROR
) << ENDPOINT
<< "Peer sent invalid entropy.";
670 for (SequenceNumberSet::const_iterator iter
=
671 incoming_ack
.received_info
.revived_packets
.begin();
672 iter
!= incoming_ack
.received_info
.revived_packets
.end(); ++iter
) {
673 if (!ContainsKey(incoming_ack
.received_info
.missing_packets
, *iter
)) {
674 DLOG(ERROR
) << ENDPOINT
675 << "Peer specified revived packet which was not missing.";
682 bool QuicConnection::ValidateStopWaitingFrame(
683 const QuicStopWaitingFrame
& stop_waiting
) {
684 if (stop_waiting
.least_unacked
<
685 received_packet_manager_
.peer_least_packet_awaiting_ack()) {
686 DLOG(ERROR
) << ENDPOINT
<< "Peer's sent low least_unacked: "
687 << stop_waiting
.least_unacked
<< " vs "
688 << received_packet_manager_
.peer_least_packet_awaiting_ack();
689 // We never process old ack frames, so this number should only increase.
693 if (stop_waiting
.least_unacked
>
694 last_header_
.packet_sequence_number
) {
695 DLOG(ERROR
) << ENDPOINT
<< "Peer sent least_unacked:"
696 << stop_waiting
.least_unacked
697 << " greater than the enclosing packet sequence number:"
698 << last_header_
.packet_sequence_number
;
705 void QuicConnection::OnFecData(const QuicFecData
& fec
) {
706 DCHECK_EQ(IN_FEC_GROUP
, last_header_
.is_in_fec_group
);
707 DCHECK_NE(0u, last_header_
.fec_group
);
708 QuicFecGroup
* group
= GetFecGroup();
710 group
->UpdateFec(last_decrypted_packet_level_
,
711 last_header_
.packet_sequence_number
, fec
);
715 bool QuicConnection::OnRstStreamFrame(const QuicRstStreamFrame
& frame
) {
717 if (debug_visitor_
) {
718 debug_visitor_
->OnRstStreamFrame(frame
);
720 DVLOG(1) << ENDPOINT
<< "Stream reset with error "
721 << QuicUtils::StreamErrorToString(frame
.error_code
);
722 last_rst_frames_
.push_back(frame
);
726 bool QuicConnection::OnConnectionCloseFrame(
727 const QuicConnectionCloseFrame
& frame
) {
729 if (debug_visitor_
) {
730 debug_visitor_
->OnConnectionCloseFrame(frame
);
732 DVLOG(1) << ENDPOINT
<< "Connection " << connection_id()
733 << " closed with error "
734 << QuicUtils::ErrorToString(frame
.error_code
)
735 << " " << frame
.error_details
;
736 last_close_frames_
.push_back(frame
);
740 bool QuicConnection::OnGoAwayFrame(const QuicGoAwayFrame
& frame
) {
742 if (debug_visitor_
) {
743 debug_visitor_
->OnGoAwayFrame(frame
);
745 DVLOG(1) << ENDPOINT
<< "Go away received with error "
746 << QuicUtils::ErrorToString(frame
.error_code
)
747 << " and reason:" << frame
.reason_phrase
;
748 last_goaway_frames_
.push_back(frame
);
752 bool QuicConnection::OnWindowUpdateFrame(const QuicWindowUpdateFrame
& frame
) {
754 if (debug_visitor_
) {
755 debug_visitor_
->OnWindowUpdateFrame(frame
);
757 DVLOG(1) << ENDPOINT
<< "WindowUpdate received for stream: "
758 << frame
.stream_id
<< " with byte offset: " << frame
.byte_offset
;
759 last_window_update_frames_
.push_back(frame
);
763 bool QuicConnection::OnBlockedFrame(const QuicBlockedFrame
& frame
) {
765 if (debug_visitor_
) {
766 debug_visitor_
->OnBlockedFrame(frame
);
768 DVLOG(1) << ENDPOINT
<< "Blocked frame received for stream: "
770 last_blocked_frames_
.push_back(frame
);
774 void QuicConnection::OnPacketComplete() {
775 // Don't do anything if this packet closed the connection.
781 DVLOG(1) << ENDPOINT
<< (last_packet_revived_
? "Revived" : "Got")
782 << " packet " << last_header_
.packet_sequence_number
783 << " with " << last_ack_frames_
.size() << " acks, "
784 << last_congestion_frames_
.size() << " congestions, "
785 << last_stop_waiting_frames_
.size() << " stop_waiting, "
786 << last_goaway_frames_
.size() << " goaways, "
787 << last_window_update_frames_
.size() << " window updates, "
788 << last_blocked_frames_
.size() << " blocked, "
789 << last_rst_frames_
.size() << " rsts, "
790 << last_close_frames_
.size() << " closes, "
791 << last_stream_frames_
.size()
792 << " stream frames for "
793 << last_header_
.public_header
.connection_id
;
795 // Call MaybeQueueAck() before recording the received packet, since we want
796 // to trigger an ack if the newly received packet was previously missing.
799 // Record received or revived packet to populate ack info correctly before
800 // processing stream frames, since the processing may result in a response
801 // packet with a bundled ack.
802 if (last_packet_revived_
) {
803 received_packet_manager_
.RecordPacketRevived(
804 last_header_
.packet_sequence_number
);
806 received_packet_manager_
.RecordPacketReceived(
807 last_size_
, last_header_
, time_of_last_received_packet_
);
810 if (!last_stream_frames_
.empty()) {
811 visitor_
->OnStreamFrames(last_stream_frames_
);
814 for (size_t i
= 0; i
< last_stream_frames_
.size(); ++i
) {
815 stats_
.stream_bytes_received
+=
816 last_stream_frames_
[i
].data
.TotalBufferSize();
819 // Process window updates, blocked, stream resets, acks, then congestion
821 if (!last_window_update_frames_
.empty()) {
822 visitor_
->OnWindowUpdateFrames(last_window_update_frames_
);
824 if (!last_blocked_frames_
.empty()) {
825 visitor_
->OnBlockedFrames(last_blocked_frames_
);
827 for (size_t i
= 0; i
< last_goaway_frames_
.size(); ++i
) {
828 visitor_
->OnGoAway(last_goaway_frames_
[i
]);
830 for (size_t i
= 0; i
< last_rst_frames_
.size(); ++i
) {
831 visitor_
->OnRstStream(last_rst_frames_
[i
]);
833 for (size_t i
= 0; i
< last_ack_frames_
.size(); ++i
) {
834 ProcessAckFrame(last_ack_frames_
[i
]);
836 for (size_t i
= 0; i
< last_congestion_frames_
.size(); ++i
) {
837 sent_packet_manager_
.OnIncomingQuicCongestionFeedbackFrame(
838 last_congestion_frames_
[i
], time_of_last_received_packet_
);
840 for (size_t i
= 0; i
< last_stop_waiting_frames_
.size(); ++i
) {
841 ProcessStopWaitingFrame(last_stop_waiting_frames_
[i
]);
843 if (!last_close_frames_
.empty()) {
844 CloseConnection(last_close_frames_
[0].error_code
, true);
848 // If there are new missing packets to report, send an ack immediately.
849 if (received_packet_manager_
.HasNewMissingPackets()) {
851 ack_alarm_
->Cancel();
854 UpdateStopWaitingCount();
859 void QuicConnection::MaybeQueueAck() {
860 // If the incoming packet was missing, send an ack immediately.
861 ack_queued_
= received_packet_manager_
.IsMissing(
862 last_header_
.packet_sequence_number
);
864 if (!ack_queued_
&& ShouldLastPacketInstigateAck()) {
865 if (ack_alarm_
->IsSet()) {
868 // Send an ack much more quickly for crypto handshake packets.
869 QuicTime::Delta delayed_ack_time
= sent_packet_manager_
.DelayedAckTime();
870 if (last_stream_frames_
.size() == 1 &&
871 last_stream_frames_
[0].stream_id
== kCryptoStreamId
) {
872 delayed_ack_time
= QuicTime::Delta::Zero();
874 ack_alarm_
->Set(clock_
->ApproximateNow().Add(delayed_ack_time
));
875 DVLOG(1) << "Ack timer set; next packet or timer will trigger ACK.";
880 ack_alarm_
->Cancel();
884 void QuicConnection::ClearLastFrames() {
885 last_stream_frames_
.clear();
886 last_goaway_frames_
.clear();
887 last_window_update_frames_
.clear();
888 last_blocked_frames_
.clear();
889 last_rst_frames_
.clear();
890 last_ack_frames_
.clear();
891 last_stop_waiting_frames_
.clear();
892 last_congestion_frames_
.clear();
895 QuicAckFrame
* QuicConnection::CreateAckFrame() {
896 QuicAckFrame
* outgoing_ack
= new QuicAckFrame();
897 received_packet_manager_
.UpdateReceivedPacketInfo(
898 &(outgoing_ack
->received_info
), clock_
->ApproximateNow());
899 UpdateStopWaiting(&(outgoing_ack
->sent_info
));
900 DVLOG(1) << ENDPOINT
<< "Creating ack frame: " << *outgoing_ack
;
904 QuicCongestionFeedbackFrame
* QuicConnection::CreateFeedbackFrame() {
905 return new QuicCongestionFeedbackFrame(outgoing_congestion_feedback_
);
908 QuicStopWaitingFrame
* QuicConnection::CreateStopWaitingFrame() {
909 QuicStopWaitingFrame stop_waiting
;
910 UpdateStopWaiting(&stop_waiting
);
911 return new QuicStopWaitingFrame(stop_waiting
);
914 bool QuicConnection::ShouldLastPacketInstigateAck() const {
915 if (!last_stream_frames_
.empty() ||
916 !last_goaway_frames_
.empty() ||
917 !last_rst_frames_
.empty() ||
918 !last_window_update_frames_
.empty() ||
919 !last_blocked_frames_
.empty()) {
923 if (!last_ack_frames_
.empty() &&
924 last_ack_frames_
.back().received_info
.is_truncated
) {
930 void QuicConnection::UpdateStopWaitingCount() {
931 if (last_ack_frames_
.empty()) {
935 // If the peer is still waiting for a packet that we are no longer planning to
936 // send, send an ack to raise the high water mark.
937 if (!last_ack_frames_
.back().received_info
.missing_packets
.empty() &&
939 *last_ack_frames_
.back().received_info
.missing_packets
.begin()) {
940 ++stop_waiting_count_
;
942 stop_waiting_count_
= 0;
946 QuicPacketSequenceNumber
QuicConnection::GetLeastUnacked() const {
947 return sent_packet_manager_
.HasUnackedPackets() ?
948 sent_packet_manager_
.GetLeastUnackedSentPacket() :
949 packet_generator_
.sequence_number() + 1;
952 void QuicConnection::MaybeSendInResponseToPacket() {
956 ScopedPacketBundler
bundler(this, ack_queued_
? SEND_ACK
: NO_ACK
);
958 // Now that we have received an ack, we might be able to send packets which
959 // are queued locally, or drain streams which are blocked.
960 if (CanWrite(HAS_RETRANSMITTABLE_DATA
)) {
965 void QuicConnection::SendVersionNegotiationPacket() {
966 // TODO(alyssar): implement zero server state negotiation.
967 pending_version_negotiation_packet_
= true;
968 if (writer_
->IsWriteBlocked()) {
969 visitor_
->OnWriteBlocked();
972 scoped_ptr
<QuicEncryptedPacket
> version_packet(
973 packet_generator_
.SerializeVersionNegotiationPacket(
974 framer_
.supported_versions()));
975 WriteResult result
= writer_
->WritePacket(
976 version_packet
->data(), version_packet
->length(),
977 self_address().address(), peer_address());
979 if (result
.status
== WRITE_STATUS_ERROR
) {
980 // We can't send an error as the socket is presumably borked.
981 CloseConnection(QUIC_PACKET_WRITE_ERROR
, false);
984 if (result
.status
== WRITE_STATUS_BLOCKED
) {
985 visitor_
->OnWriteBlocked();
986 if (writer_
->IsWriteBlockedDataBuffered()) {
987 pending_version_negotiation_packet_
= false;
992 pending_version_negotiation_packet_
= false;
995 QuicConsumedData
QuicConnection::SendStreamData(
997 const IOVector
& data
,
998 QuicStreamOffset offset
,
1000 FecProtection fec_protection
,
1001 QuicAckNotifier::DelegateInterface
* delegate
) {
1002 if (!fin
&& data
.Empty()) {
1003 LOG(DFATAL
) << "Attempt to send empty stream frame";
1006 // This notifier will be owned by the AckNotifierManager (or deleted below if
1007 // no data or FIN was consumed).
1008 QuicAckNotifier
* notifier
= NULL
;
1010 notifier
= new QuicAckNotifier(delegate
);
1013 // Opportunistically bundle an ack with every outgoing packet.
1014 // Particularly, we want to bundle with handshake packets since we don't know
1015 // which decrypter will be used on an ack packet following a handshake
1016 // packet (a handshake packet from client to server could result in a REJ or a
1017 // SHLO from the server, leading to two different decrypters at the server.)
1019 // TODO(jri): Note that ConsumeData may cause a response packet to be sent.
1020 // We may end up sending stale ack information if there are undecryptable
1021 // packets hanging around and/or there are revivable packets which may get
1022 // handled after this packet is sent. Change ScopedPacketBundler to do the
1023 // right thing: check ack_queued_, and then check undecryptable packets and
1024 // also if there is possibility of revival. Only bundle an ack if there's no
1025 // processing left that may cause received_info_ to change.
1026 ScopedPacketBundler
ack_bundler(this, BUNDLE_PENDING_ACK
);
1027 QuicConsumedData consumed_data
=
1028 packet_generator_
.ConsumeData(id
, data
, offset
, fin
, fec_protection
,
1032 (consumed_data
.bytes_consumed
== 0 && !consumed_data
.fin_consumed
)) {
1033 // No data was consumed, nor was a fin consumed, so delete the notifier.
1037 return consumed_data
;
1040 void QuicConnection::SendRstStream(QuicStreamId id
,
1041 QuicRstStreamErrorCode error
,
1042 QuicStreamOffset bytes_written
) {
1043 // Opportunistically bundle an ack with this outgoing packet.
1044 ScopedPacketBundler
ack_bundler(this, BUNDLE_PENDING_ACK
);
1045 packet_generator_
.AddControlFrame(QuicFrame(new QuicRstStreamFrame(
1046 id
, AdjustErrorForVersion(error
, version()), bytes_written
)));
1049 void QuicConnection::SendWindowUpdate(QuicStreamId id
,
1050 QuicStreamOffset byte_offset
) {
1051 // Opportunistically bundle an ack with this outgoing packet.
1052 ScopedPacketBundler
ack_bundler(this, BUNDLE_PENDING_ACK
);
1053 packet_generator_
.AddControlFrame(
1054 QuicFrame(new QuicWindowUpdateFrame(id
, byte_offset
)));
1057 void QuicConnection::SendBlocked(QuicStreamId id
) {
1058 // Opportunistically bundle an ack with this outgoing packet.
1059 ScopedPacketBundler
ack_bundler(this, BUNDLE_PENDING_ACK
);
1060 packet_generator_
.AddControlFrame(QuicFrame(new QuicBlockedFrame(id
)));
1063 const QuicConnectionStats
& QuicConnection::GetStats() {
1064 // Update rtt and estimated bandwidth.
1066 sent_packet_manager_
.GetRttStats()->min_rtt().ToMicroseconds();
1068 sent_packet_manager_
.GetRttStats()->SmoothedRtt().ToMicroseconds();
1069 stats_
.estimated_bandwidth
=
1070 sent_packet_manager_
.BandwidthEstimate().ToBytesPerSecond();
1071 stats_
.congestion_window
= sent_packet_manager_
.GetCongestionWindow();
1072 stats_
.max_packet_size
= packet_generator_
.max_packet_length();
1076 void QuicConnection::ProcessUdpPacket(const IPEndPoint
& self_address
,
1077 const IPEndPoint
& peer_address
,
1078 const QuicEncryptedPacket
& packet
) {
1082 if (debug_visitor_
) {
1083 debug_visitor_
->OnPacketReceived(self_address
, peer_address
, packet
);
1085 last_packet_revived_
= false;
1086 last_size_
= packet
.length();
1088 CheckForAddressMigration(self_address
, peer_address
);
1090 stats_
.bytes_received
+= packet
.length();
1091 ++stats_
.packets_received
;
1093 if (!framer_
.ProcessPacket(packet
)) {
1094 // If we are unable to decrypt this packet, it might be
1095 // because the CHLO or SHLO packet was lost.
1096 if (encryption_level_
!= ENCRYPTION_FORWARD_SECURE
&&
1097 framer_
.error() == QUIC_DECRYPTION_FAILURE
&&
1098 undecryptable_packets_
.size() < kMaxUndecryptablePackets
) {
1099 QueueUndecryptablePacket(packet
);
1101 DVLOG(1) << ENDPOINT
<< "Unable to process packet. Last packet processed: "
1102 << last_header_
.packet_sequence_number
;
1106 ++stats_
.packets_processed
;
1107 MaybeProcessUndecryptablePackets();
1108 MaybeProcessRevivedPacket();
1109 MaybeSendInResponseToPacket();
1113 void QuicConnection::CheckForAddressMigration(
1114 const IPEndPoint
& self_address
, const IPEndPoint
& peer_address
) {
1115 peer_ip_changed_
= false;
1116 peer_port_changed_
= false;
1117 self_ip_changed_
= false;
1118 self_port_changed_
= false;
1120 if (peer_address_
.address().empty()) {
1121 peer_address_
= peer_address
;
1123 if (self_address_
.address().empty()) {
1124 self_address_
= self_address
;
1127 if (!peer_address
.address().empty() && !peer_address_
.address().empty()) {
1128 peer_ip_changed_
= (peer_address
.address() != peer_address_
.address());
1129 peer_port_changed_
= (peer_address
.port() != peer_address_
.port());
1131 // Store in case we want to migrate connection in ProcessValidatedPacket.
1132 migrating_peer_port_
= peer_address
.port();
1135 if (!self_address
.address().empty() && !self_address_
.address().empty()) {
1136 self_ip_changed_
= (self_address
.address() != self_address_
.address());
1137 self_port_changed_
= (self_address
.port() != self_address_
.port());
1141 void QuicConnection::OnCanWrite() {
1142 DCHECK(!writer_
->IsWriteBlocked());
1144 WriteQueuedPackets();
1145 WritePendingRetransmissions();
1147 // Sending queued packets may have caused the socket to become write blocked,
1148 // or the congestion manager to prohibit sending. If we've sent everything
1149 // we had queued and we're still not blocked, let the visitor know it can
1151 if (!CanWrite(HAS_RETRANSMITTABLE_DATA
)) {
1155 { // Limit the scope of the bundler.
1156 // Set |include_ack| to false in bundler; ack inclusion happens elsewhere.
1157 ScopedPacketBundler
bundler(this, NO_ACK
);
1158 visitor_
->OnCanWrite();
1161 // After the visitor writes, it may have caused the socket to become write
1162 // blocked or the congestion manager to prohibit sending, so check again.
1163 if (visitor_
->WillingAndAbleToWrite() &&
1164 !resume_writes_alarm_
->IsSet() &&
1165 CanWrite(HAS_RETRANSMITTABLE_DATA
)) {
1166 // We're not write blocked, but some stream didn't write out all of its
1167 // bytes. Register for 'immediate' resumption so we'll keep writing after
1168 // other connections and events have had a chance to use the thread.
1169 resume_writes_alarm_
->Set(clock_
->ApproximateNow());
1173 void QuicConnection::WriteIfNotBlocked() {
1174 if (!writer_
->IsWriteBlocked()) {
1179 bool QuicConnection::ProcessValidatedPacket() {
1180 if ((!FLAGS_quic_allow_port_migration
&& peer_port_changed_
) ||
1181 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 // Port migration is supported, do it now if port has changed.
1189 if (FLAGS_quic_allow_port_migration
&&
1190 peer_port_changed_
) {
1191 DVLOG(1) << ENDPOINT
<< "Peer's port changed from "
1192 << peer_address_
.port() << " to " << migrating_peer_port_
1193 << ", migrating connection.";
1194 peer_address_
= IPEndPoint(peer_address_
.address(), migrating_peer_port_
);
1197 time_of_last_received_packet_
= clock_
->Now();
1198 DVLOG(1) << ENDPOINT
<< "time of last received packet: "
1199 << time_of_last_received_packet_
.ToDebuggingValue();
1201 if (is_server_
&& encryption_level_
== ENCRYPTION_NONE
&&
1202 last_size_
> packet_generator_
.max_packet_length()) {
1203 packet_generator_
.set_max_packet_length(last_size_
);
1208 void QuicConnection::WriteQueuedPackets() {
1209 DCHECK(!writer_
->IsWriteBlocked());
1211 if (pending_version_negotiation_packet_
) {
1212 SendVersionNegotiationPacket();
1215 QueuedPacketList::iterator packet_iterator
= queued_packets_
.begin();
1216 while (!writer_
->IsWriteBlocked() &&
1217 packet_iterator
!= queued_packets_
.end()) {
1218 if (WritePacket(*packet_iterator
)) {
1219 delete packet_iterator
->packet
;
1220 packet_iterator
= queued_packets_
.erase(packet_iterator
);
1222 // Continue, because some queued packets may still be writable.
1223 // This can happen if a retransmit send fails.
1229 void QuicConnection::WritePendingRetransmissions() {
1230 // Keep writing as long as there's a pending retransmission which can be
1232 while (sent_packet_manager_
.HasPendingRetransmissions()) {
1233 const QuicSentPacketManager::PendingRetransmission pending
=
1234 sent_packet_manager_
.NextPendingRetransmission();
1235 if (GetPacketType(&pending
.retransmittable_frames
) == NORMAL
&&
1236 !CanWrite(HAS_RETRANSMITTABLE_DATA
)) {
1240 // Re-packetize the frames with a new sequence number for retransmission.
1241 // Retransmitted data packets do not use FEC, even when it's enabled.
1242 // Retransmitted packets use the same sequence number length as the
1244 // Flush the packet generator before making a new packet.
1245 // TODO(ianswett): Implement ReserializeAllFrames as a separate path that
1246 // does not require the creator to be flushed.
1247 packet_generator_
.FlushAllQueuedFrames();
1248 SerializedPacket serialized_packet
= packet_generator_
.ReserializeAllFrames(
1249 pending
.retransmittable_frames
.frames(),
1250 pending
.sequence_number_length
);
1252 DVLOG(1) << ENDPOINT
<< "Retransmitting " << pending
.sequence_number
1253 << " as " << serialized_packet
.sequence_number
;
1254 if (debug_visitor_
) {
1255 debug_visitor_
->OnPacketRetransmitted(
1256 pending
.sequence_number
, serialized_packet
.sequence_number
);
1258 sent_packet_manager_
.OnRetransmittedPacket(
1259 pending
.sequence_number
,
1260 serialized_packet
.sequence_number
);
1262 SendOrQueuePacket(pending
.retransmittable_frames
.encryption_level(),
1264 pending
.transmission_type
);
1268 void QuicConnection::RetransmitUnackedPackets(
1269 RetransmissionType retransmission_type
) {
1270 sent_packet_manager_
.RetransmitUnackedPackets(retransmission_type
);
1272 WriteIfNotBlocked();
1275 void QuicConnection::NeuterUnencryptedPackets() {
1276 sent_packet_manager_
.NeuterUnencryptedPackets();
1277 // This may have changed the retransmission timer, so re-arm it.
1278 retransmission_alarm_
->Cancel();
1279 QuicTime retransmission_time
= sent_packet_manager_
.GetRetransmissionTime();
1280 if (retransmission_time
!= QuicTime::Zero()) {
1281 retransmission_alarm_
->Set(retransmission_time
);
1285 bool QuicConnection::ShouldGeneratePacket(
1286 TransmissionType transmission_type
,
1287 HasRetransmittableData retransmittable
,
1288 IsHandshake handshake
) {
1289 // We should serialize handshake packets immediately to ensure that they
1290 // end up sent at the right encryption level.
1291 if (handshake
== IS_HANDSHAKE
) {
1295 return CanWrite(retransmittable
);
1298 bool QuicConnection::CanWrite(HasRetransmittableData retransmittable
) {
1299 if (writer_
->IsWriteBlocked()) {
1300 visitor_
->OnWriteBlocked();
1304 send_alarm_
->Cancel();
1305 QuicTime now
= clock_
->Now();
1306 QuicTime::Delta delay
= sent_packet_manager_
.TimeUntilSend(
1307 now
, retransmittable
);
1308 if (delay
.IsInfinite()) {
1312 // If the scheduler requires a delay, then we can not send this packet now.
1313 if (!delay
.IsZero()) {
1314 send_alarm_
->Set(now
.Add(delay
));
1315 DVLOG(1) << "Delaying sending.";
1321 bool QuicConnection::WritePacket(QueuedPacket packet
) {
1322 QuicPacketSequenceNumber sequence_number
= packet
.sequence_number
;
1323 if (ShouldDiscardPacket(packet
.encryption_level
,
1325 packet
.retransmittable
)) {
1326 ++stats_
.packets_discarded
;
1330 // If the packet is CONNECTION_CLOSE, we need to try to send it immediately
1331 // and encrypt it to hand it off to TimeWaitListManager.
1332 // If the packet is QUEUED, we don't re-consult the congestion control.
1333 // This ensures packets are sent in sequence number order.
1334 // TODO(ianswett): The congestion control should have been consulted before
1335 // serializing the packet, so this could be turned into a LOG_IF(DFATAL).
1336 if (packet
.type
== NORMAL
&& !CanWrite(packet
.retransmittable
)) {
1340 // Some encryption algorithms require the packet sequence numbers not be
1342 DCHECK_LE(sequence_number_of_last_sent_packet_
, sequence_number
);
1343 sequence_number_of_last_sent_packet_
= sequence_number
;
1345 QuicEncryptedPacket
* encrypted
= framer_
.EncryptPacket(
1346 packet
.encryption_level
, sequence_number
, *packet
.packet
);
1347 if (encrypted
== NULL
) {
1348 LOG(DFATAL
) << ENDPOINT
<< "Failed to encrypt packet number "
1350 // CloseConnection does not send close packet, so no infinite loop here.
1351 CloseConnection(QUIC_ENCRYPTION_FAILURE
, false);
1355 // Connection close packets are eventually owned by TimeWaitListManager.
1356 // Others are deleted at the end of this call.
1357 scoped_ptr
<QuicEncryptedPacket
> encrypted_deleter
;
1358 if (packet
.type
== CONNECTION_CLOSE
) {
1359 DCHECK(connection_close_packet_
.get() == NULL
);
1360 connection_close_packet_
.reset(encrypted
);
1361 // This assures we won't try to write *forced* packets when blocked.
1362 // Return true to stop processing.
1363 if (writer_
->IsWriteBlocked()) {
1364 visitor_
->OnWriteBlocked();
1368 encrypted_deleter
.reset(encrypted
);
1371 LOG_IF(DFATAL
, encrypted
->length() >
1372 packet_generator_
.max_packet_length())
1373 << "Writing an encrypted packet larger than max_packet_length:"
1374 << packet_generator_
.max_packet_length() << " encrypted length: "
1375 << encrypted
->length();
1376 DVLOG(1) << ENDPOINT
<< "Sending packet " << sequence_number
1377 << " : " << (packet
.packet
->is_fec_packet() ? "FEC " :
1378 (packet
.retransmittable
== HAS_RETRANSMITTABLE_DATA
1379 ? "data bearing " : " ack only "))
1380 << ", encryption level: "
1381 << QuicUtils::EncryptionLevelToString(packet
.encryption_level
)
1382 << ", length:" << packet
.packet
->length() << ", encrypted length:"
1383 << encrypted
->length();
1384 DVLOG(2) << ENDPOINT
<< "packet(" << sequence_number
<< "): " << std::endl
1385 << QuicUtils::StringToHexASCIIDump(packet
.packet
->AsStringPiece());
1387 DCHECK(encrypted
->length() <= kMaxPacketSize
||
1388 FLAGS_quic_allow_oversized_packets_for_test
)
1389 << "Packet " << sequence_number
<< " will not be read; too large: "
1390 << packet
.packet
->length() << " " << encrypted
->length() << " "
1391 << " close: " << (packet
.type
== CONNECTION_CLOSE
? "yes" : "no");
1393 DCHECK(pending_write_
.get() == NULL
);
1394 pending_write_
.reset(new QueuedPacket(packet
));
1396 WriteResult result
= writer_
->WritePacket(encrypted
->data(),
1397 encrypted
->length(),
1398 self_address().address(),
1400 if (result
.error_code
== ERR_IO_PENDING
) {
1401 DCHECK_EQ(WRITE_STATUS_BLOCKED
, result
.status
);
1403 if (debug_visitor_
) {
1404 // Pass the write result to the visitor.
1405 debug_visitor_
->OnPacketSent(sequence_number
,
1406 packet
.encryption_level
,
1407 packet
.transmission_type
,
1411 if (result
.status
== WRITE_STATUS_BLOCKED
) {
1412 visitor_
->OnWriteBlocked();
1413 // If the socket buffers the the data, then the packet should not
1414 // be queued and sent again, which would result in an unnecessary
1415 // duplicate packet being sent. The helper must call OnPacketSent
1416 // when the packet is actually sent.
1417 if (writer_
->IsWriteBlockedDataBuffered()) {
1420 pending_write_
.reset();
1424 if (OnPacketSent(result
)) {
1430 bool QuicConnection::ShouldDiscardPacket(
1431 EncryptionLevel level
,
1432 QuicPacketSequenceNumber sequence_number
,
1433 HasRetransmittableData retransmittable
) {
1435 DVLOG(1) << ENDPOINT
1436 << "Not sending packet as connection is disconnected.";
1440 // If the packet has been discarded before sending, don't send it.
1441 // This occurs if a packet gets serialized, queued, then discarded.
1442 if (!sent_packet_manager_
.IsUnacked(sequence_number
)) {
1443 DVLOG(1) << ENDPOINT
<< "Dropping packet before sending: "
1444 << sequence_number
<< " since it has already been discarded.";
1448 if (encryption_level_
== ENCRYPTION_FORWARD_SECURE
&&
1449 level
== ENCRYPTION_NONE
) {
1450 // Drop packets that are NULL encrypted since the peer won't accept them
1452 DVLOG(1) << ENDPOINT
<< "Dropping NULL encrypted packet: "
1453 << sequence_number
<< " since the connection is forward secure.";
1455 sent_packet_manager_
.HasRetransmittableFrames(sequence_number
))
1456 << "Once forward secure, all NULL encrypted packets should be "
1461 if (retransmittable
== HAS_RETRANSMITTABLE_DATA
&&
1462 !sent_packet_manager_
.HasRetransmittableFrames(sequence_number
)) {
1463 DVLOG(1) << ENDPOINT
<< "Dropping unacked packet: " << sequence_number
1464 << " A previous transmission was acked while write blocked.";
1471 bool QuicConnection::OnPacketSent(WriteResult result
) {
1472 DCHECK_NE(WRITE_STATUS_BLOCKED
, result
.status
);
1473 if (pending_write_
.get() == NULL
) {
1474 LOG(DFATAL
) << "OnPacketSent called without a pending write.";
1478 QuicPacketSequenceNumber sequence_number
= pending_write_
->sequence_number
;
1479 TransmissionType transmission_type
= pending_write_
->transmission_type
;
1480 HasRetransmittableData retransmittable
= pending_write_
->retransmittable
;
1481 size_t length
= pending_write_
->length
;
1482 pending_write_
.reset();
1484 if (result
.status
== WRITE_STATUS_ERROR
) {
1485 DVLOG(1) << ENDPOINT
<< "Write failed with error: " << result
.error_code
1486 << " (" << ErrorToString(result
.error_code
) << ")";
1487 // We can't send an error as the socket is presumably borked.
1488 CloseConnection(QUIC_PACKET_WRITE_ERROR
, false);
1492 QuicTime now
= clock_
->Now();
1493 if (transmission_type
== NOT_RETRANSMISSION
) {
1494 time_of_last_sent_new_packet_
= now
;
1497 DVLOG(1) << ENDPOINT
<< "time of last sent packet: "
1498 << now
.ToDebuggingValue();
1500 // TODO(ianswett): Change the sequence number length and other packet creator
1501 // options by a more explicit API than setting a struct value directly.
1502 packet_generator_
.UpdateSequenceNumberLength(
1503 received_packet_manager_
.least_packet_awaited_by_peer(),
1504 sent_packet_manager_
.GetCongestionWindow());
1506 bool reset_retransmission_alarm
=
1507 sent_packet_manager_
.OnPacketSent(sequence_number
, now
, length
,
1508 transmission_type
, retransmittable
);
1510 if (reset_retransmission_alarm
|| !retransmission_alarm_
->IsSet()) {
1511 retransmission_alarm_
->Cancel();
1512 QuicTime retransmission_time
= sent_packet_manager_
.GetRetransmissionTime();
1513 if (retransmission_time
!= QuicTime::Zero()) {
1514 retransmission_alarm_
->Set(retransmission_time
);
1518 stats_
.bytes_sent
+= result
.bytes_written
;
1519 ++stats_
.packets_sent
;
1521 if (transmission_type
!= NOT_RETRANSMISSION
) {
1522 stats_
.bytes_retransmitted
+= result
.bytes_written
;
1523 ++stats_
.packets_retransmitted
;
1529 bool QuicConnection::OnSerializedPacket(
1530 const SerializedPacket
& serialized_packet
) {
1531 if (serialized_packet
.retransmittable_frames
) {
1532 serialized_packet
.retransmittable_frames
->
1533 set_encryption_level(encryption_level_
);
1535 sent_packet_manager_
.OnSerializedPacket(serialized_packet
);
1536 // The TransmissionType is NOT_RETRANSMISSION because all retransmissions
1537 // serialize packets and invoke SendOrQueuePacket directly.
1538 return SendOrQueuePacket(encryption_level_
,
1540 NOT_RETRANSMISSION
);
1543 bool QuicConnection::SendOrQueuePacket(EncryptionLevel level
,
1544 const SerializedPacket
& packet
,
1545 TransmissionType transmission_type
) {
1546 if (packet
.packet
== NULL
) {
1547 LOG(DFATAL
) << "NULL packet passed in to SendOrQueuePacket";
1551 sent_entropy_manager_
.RecordPacketEntropyHash(packet
.sequence_number
,
1552 packet
.entropy_hash
);
1553 QueuedPacket
queued_packet(packet
, level
, transmission_type
);
1554 // If there are already queued packets, put this at the end,
1555 // unless it's ConnectionClose, in which case it is written immediately.
1556 if ((queued_packet
.type
== CONNECTION_CLOSE
|| queued_packets_
.empty()) &&
1557 WritePacket(queued_packet
)) {
1558 delete packet
.packet
;
1561 queued_packet
.type
= QUEUED
;
1562 queued_packets_
.push_back(queued_packet
);
1566 void QuicConnection::UpdateStopWaiting(QuicStopWaitingFrame
* stop_waiting
) {
1567 stop_waiting
->least_unacked
= GetLeastUnacked();
1568 stop_waiting
->entropy_hash
= sent_entropy_manager_
.EntropyHash(
1569 stop_waiting
->least_unacked
- 1);
1572 void QuicConnection::SendPing() {
1573 if (retransmission_alarm_
->IsSet()) {
1576 if (version() <= QUIC_VERSION_16
) {
1577 // TODO(rch): remove this when we remove version 15 and 16.
1578 // This is a horrible hideous hack which we should not support.
1580 char c_data
[] = "C";
1581 data
.Append(c_data
, 1);
1582 QuicConsumedData consumed_data
=
1583 packet_generator_
.ConsumeData(kCryptoStreamId
, data
, 0, false,
1584 MAY_FEC_PROTECT
, NULL
);
1585 if (consumed_data
.bytes_consumed
== 0) {
1586 DLOG(ERROR
) << "Unable to send ping!?";
1589 packet_generator_
.AddControlFrame(QuicFrame(new QuicPingFrame
));
1593 void QuicConnection::SendAck() {
1594 ack_alarm_
->Cancel();
1595 stop_waiting_count_
= 0;
1596 // TODO(rch): delay this until the CreateFeedbackFrame
1597 // method is invoked. This requires changes SetShouldSendAck
1598 // to be a no-arg method, and re-jiggering its implementation.
1599 bool send_feedback
= false;
1600 if (received_packet_manager_
.GenerateCongestionFeedback(
1601 &outgoing_congestion_feedback_
)) {
1602 DVLOG(1) << ENDPOINT
<< "Sending feedback: "
1603 << outgoing_congestion_feedback_
;
1604 send_feedback
= true;
1607 packet_generator_
.SetShouldSendAck(send_feedback
,
1608 version() > QUIC_VERSION_15
);
1611 void QuicConnection::OnRetransmissionTimeout() {
1612 if (!sent_packet_manager_
.HasUnackedPackets()) {
1616 sent_packet_manager_
.OnRetransmissionTimeout();
1617 WriteIfNotBlocked();
1618 // In the TLP case, the SentPacketManager gives the connection the opportunity
1619 // to send new data before retransmitting.
1620 if (sent_packet_manager_
.MaybeRetransmitTailLossProbe()) {
1621 // Send the pending retransmission now that it's been queued.
1622 WriteIfNotBlocked();
1625 // Ensure the retransmission alarm is always set if there are unacked packets
1626 // and nothing waiting to be sent.
1627 if (!HasQueuedData() && !retransmission_alarm_
->IsSet()) {
1628 QuicTime rto_timeout
= sent_packet_manager_
.GetRetransmissionTime();
1629 if (rto_timeout
!= QuicTime::Zero()) {
1630 retransmission_alarm_
->Set(rto_timeout
);
1635 void QuicConnection::SetEncrypter(EncryptionLevel level
,
1636 QuicEncrypter
* encrypter
) {
1637 framer_
.SetEncrypter(level
, encrypter
);
1640 const QuicEncrypter
* QuicConnection::encrypter(EncryptionLevel level
) const {
1641 return framer_
.encrypter(level
);
1644 void QuicConnection::SetDefaultEncryptionLevel(EncryptionLevel level
) {
1645 encryption_level_
= level
;
1646 packet_generator_
.set_encryption_level(level
);
1649 void QuicConnection::SetDecrypter(QuicDecrypter
* decrypter
,
1650 EncryptionLevel level
) {
1651 framer_
.SetDecrypter(decrypter
, level
);
1654 void QuicConnection::SetAlternativeDecrypter(QuicDecrypter
* decrypter
,
1655 EncryptionLevel level
,
1656 bool latch_once_used
) {
1657 framer_
.SetAlternativeDecrypter(decrypter
, level
, latch_once_used
);
1660 const QuicDecrypter
* QuicConnection::decrypter() const {
1661 return framer_
.decrypter();
1664 const QuicDecrypter
* QuicConnection::alternative_decrypter() const {
1665 return framer_
.alternative_decrypter();
1668 void QuicConnection::QueueUndecryptablePacket(
1669 const QuicEncryptedPacket
& packet
) {
1670 DVLOG(1) << ENDPOINT
<< "Queueing undecryptable packet.";
1671 undecryptable_packets_
.push_back(packet
.Clone());
1674 void QuicConnection::MaybeProcessUndecryptablePackets() {
1675 if (undecryptable_packets_
.empty() || encryption_level_
== ENCRYPTION_NONE
) {
1679 while (connected_
&& !undecryptable_packets_
.empty()) {
1680 DVLOG(1) << ENDPOINT
<< "Attempting to process undecryptable packet";
1681 QuicEncryptedPacket
* packet
= undecryptable_packets_
.front();
1682 if (!framer_
.ProcessPacket(*packet
) &&
1683 framer_
.error() == QUIC_DECRYPTION_FAILURE
) {
1684 DVLOG(1) << ENDPOINT
<< "Unable to process undecryptable packet...";
1687 DVLOG(1) << ENDPOINT
<< "Processed undecryptable packet!";
1688 ++stats_
.packets_processed
;
1690 undecryptable_packets_
.pop_front();
1693 // Once forward secure encryption is in use, there will be no
1694 // new keys installed and hence any undecryptable packets will
1695 // never be able to be decrypted.
1696 if (encryption_level_
== ENCRYPTION_FORWARD_SECURE
) {
1697 STLDeleteElements(&undecryptable_packets_
);
1701 void QuicConnection::MaybeProcessRevivedPacket() {
1702 QuicFecGroup
* group
= GetFecGroup();
1703 if (!connected_
|| group
== NULL
|| !group
->CanRevive()) {
1706 QuicPacketHeader revived_header
;
1707 char revived_payload
[kMaxPacketSize
];
1708 size_t len
= group
->Revive(&revived_header
, revived_payload
, kMaxPacketSize
);
1709 revived_header
.public_header
.connection_id
= connection_id_
;
1710 revived_header
.public_header
.connection_id_length
=
1711 last_header_
.public_header
.connection_id_length
;
1712 revived_header
.public_header
.version_flag
= false;
1713 revived_header
.public_header
.reset_flag
= false;
1714 revived_header
.public_header
.sequence_number_length
=
1715 last_header_
.public_header
.sequence_number_length
;
1716 revived_header
.fec_flag
= false;
1717 revived_header
.is_in_fec_group
= NOT_IN_FEC_GROUP
;
1718 revived_header
.fec_group
= 0;
1719 group_map_
.erase(last_header_
.fec_group
);
1720 last_decrypted_packet_level_
= group
->effective_encryption_level();
1721 DCHECK_LT(last_decrypted_packet_level_
, NUM_ENCRYPTION_LEVELS
);
1724 last_packet_revived_
= true;
1725 if (debug_visitor_
) {
1726 debug_visitor_
->OnRevivedPacket(revived_header
,
1727 StringPiece(revived_payload
, len
));
1730 ++stats_
.packets_revived
;
1731 framer_
.ProcessRevivedPacket(&revived_header
,
1732 StringPiece(revived_payload
, len
));
1735 QuicFecGroup
* QuicConnection::GetFecGroup() {
1736 QuicFecGroupNumber fec_group_num
= last_header_
.fec_group
;
1737 if (fec_group_num
== 0) {
1740 if (group_map_
.count(fec_group_num
) == 0) {
1741 if (group_map_
.size() >= kMaxFecGroups
) { // Too many groups
1742 if (fec_group_num
< group_map_
.begin()->first
) {
1743 // The group being requested is a group we've seen before and deleted.
1744 // Don't recreate it.
1747 // Clear the lowest group number.
1748 delete group_map_
.begin()->second
;
1749 group_map_
.erase(group_map_
.begin());
1751 group_map_
[fec_group_num
] = new QuicFecGroup();
1753 return group_map_
[fec_group_num
];
1756 void QuicConnection::SendConnectionClose(QuicErrorCode error
) {
1757 SendConnectionCloseWithDetails(error
, string());
1760 void QuicConnection::SendConnectionCloseWithDetails(QuicErrorCode error
,
1761 const string
& details
) {
1762 // If we're write blocked, WritePacket() will not send, but will capture the
1763 // serialized packet.
1764 SendConnectionClosePacket(error
, details
);
1766 // It's possible that while sending the connection close packet, we get a
1767 // socket error and disconnect right then and there. Avoid a double
1768 // disconnect in that case.
1769 CloseConnection(error
, false);
1773 void QuicConnection::SendConnectionClosePacket(QuicErrorCode error
,
1774 const string
& details
) {
1775 DVLOG(1) << ENDPOINT
<< "Force closing " << connection_id()
1776 << " with error " << QuicUtils::ErrorToString(error
)
1777 << " (" << error
<< ") " << details
;
1778 ScopedPacketBundler
ack_bundler(this, SEND_ACK
);
1779 QuicConnectionCloseFrame
* frame
= new QuicConnectionCloseFrame();
1780 frame
->error_code
= error
;
1781 frame
->error_details
= details
;
1782 packet_generator_
.AddControlFrame(QuicFrame(frame
));
1783 packet_generator_
.FlushAllQueuedFrames();
1786 void QuicConnection::CloseConnection(QuicErrorCode error
, bool from_peer
) {
1788 DLOG(DFATAL
) << "Error: attempt to close an already closed connection"
1789 << base::debug::StackTrace().ToString();
1793 visitor_
->OnConnectionClosed(error
, from_peer
);
1794 // Cancel the alarms so they don't trigger any action now that the
1795 // connection is closed.
1796 ack_alarm_
->Cancel();
1797 resume_writes_alarm_
->Cancel();
1798 retransmission_alarm_
->Cancel();
1799 send_alarm_
->Cancel();
1800 timeout_alarm_
->Cancel();
1803 void QuicConnection::SendGoAway(QuicErrorCode error
,
1804 QuicStreamId last_good_stream_id
,
1805 const string
& reason
) {
1806 DVLOG(1) << ENDPOINT
<< "Going away with error "
1807 << QuicUtils::ErrorToString(error
)
1808 << " (" << error
<< ")";
1810 // Opportunistically bundle an ack with this outgoing packet.
1811 ScopedPacketBundler
ack_bundler(this, BUNDLE_PENDING_ACK
);
1812 packet_generator_
.AddControlFrame(
1813 QuicFrame(new QuicGoAwayFrame(error
, last_good_stream_id
, reason
)));
1816 void QuicConnection::CloseFecGroupsBefore(
1817 QuicPacketSequenceNumber sequence_number
) {
1818 FecGroupMap::iterator it
= group_map_
.begin();
1819 while (it
!= group_map_
.end()) {
1820 // If this is the current group or the group doesn't protect this packet
1821 // we can ignore it.
1822 if (last_header_
.fec_group
== it
->first
||
1823 !it
->second
->ProtectsPacketsBefore(sequence_number
)) {
1827 QuicFecGroup
* fec_group
= it
->second
;
1828 DCHECK(!fec_group
->CanRevive());
1829 FecGroupMap::iterator next
= it
;
1831 group_map_
.erase(it
);
1837 size_t QuicConnection::max_packet_length() const {
1838 return packet_generator_
.max_packet_length();
1841 void QuicConnection::set_max_packet_length(size_t length
) {
1842 return packet_generator_
.set_max_packet_length(length
);
1845 bool QuicConnection::HasQueuedData() const {
1846 return pending_version_negotiation_packet_
||
1847 !queued_packets_
.empty() || packet_generator_
.HasQueuedFrames();
1850 bool QuicConnection::CanWriteStreamData() {
1851 // Don't write stream data if there are negotiation or queued data packets
1852 // to send. Otherwise, continue and bundle as many frames as possible.
1853 if (pending_version_negotiation_packet_
|| !queued_packets_
.empty()) {
1857 IsHandshake pending_handshake
= visitor_
->HasPendingHandshake() ?
1858 IS_HANDSHAKE
: NOT_HANDSHAKE
;
1859 // Sending queued packets may have caused the socket to become write blocked,
1860 // or the congestion manager to prohibit sending. If we've sent everything
1861 // we had queued and we're still not blocked, let the visitor know it can
1863 return ShouldGeneratePacket(NOT_RETRANSMISSION
, HAS_RETRANSMITTABLE_DATA
,
1867 void QuicConnection::SetIdleNetworkTimeout(QuicTime::Delta timeout
) {
1868 if (timeout
< idle_network_timeout_
) {
1869 idle_network_timeout_
= timeout
;
1872 idle_network_timeout_
= timeout
;
1876 void QuicConnection::SetOverallConnectionTimeout(QuicTime::Delta timeout
) {
1877 if (timeout
< overall_connection_timeout_
) {
1878 overall_connection_timeout_
= timeout
;
1881 overall_connection_timeout_
= timeout
;
1885 bool QuicConnection::CheckForTimeout() {
1886 QuicTime now
= clock_
->ApproximateNow();
1887 QuicTime time_of_last_packet
= max(time_of_last_received_packet_
,
1888 time_of_last_sent_new_packet_
);
1890 // |delta| can be < 0 as |now| is approximate time but |time_of_last_packet|
1891 // is accurate time. However, this should not change the behavior of
1892 // timeout handling.
1893 QuicTime::Delta delta
= now
.Subtract(time_of_last_packet
);
1894 DVLOG(1) << ENDPOINT
<< "last packet "
1895 << time_of_last_packet
.ToDebuggingValue()
1896 << " now:" << now
.ToDebuggingValue()
1897 << " delta:" << delta
.ToMicroseconds()
1898 << " network_timeout: " << idle_network_timeout_
.ToMicroseconds();
1899 if (delta
>= idle_network_timeout_
) {
1900 DVLOG(1) << ENDPOINT
<< "Connection timedout due to no network activity.";
1901 SendConnectionClose(QUIC_CONNECTION_TIMED_OUT
);
1905 // Next timeout delta.
1906 QuicTime::Delta timeout
= idle_network_timeout_
.Subtract(delta
);
1908 if (!overall_connection_timeout_
.IsInfinite()) {
1909 QuicTime::Delta connected_time
=
1910 now
.Subtract(stats_
.connection_creation_time
);
1911 DVLOG(1) << ENDPOINT
<< "connection time: "
1912 << connected_time
.ToMilliseconds() << " overall timeout: "
1913 << overall_connection_timeout_
.ToMilliseconds();
1914 if (connected_time
>= overall_connection_timeout_
) {
1915 DVLOG(1) << ENDPOINT
<<
1916 "Connection timedout due to overall connection timeout.";
1917 SendConnectionClose(QUIC_CONNECTION_TIMED_OUT
);
1921 // Take the min timeout.
1922 QuicTime::Delta connection_timeout
=
1923 overall_connection_timeout_
.Subtract(connected_time
);
1924 if (connection_timeout
< timeout
) {
1925 timeout
= connection_timeout
;
1929 timeout_alarm_
->Cancel();
1930 timeout_alarm_
->Set(clock_
->ApproximateNow().Add(timeout
));
1934 void QuicConnection::SetPingAlarm() {
1936 // Only clients send pings.
1939 ping_alarm_
->Cancel();
1940 if (!visitor_
->HasOpenDataStreams()) {
1941 // Don't send a ping unless there are open streams.
1944 QuicTime::Delta ping_timeout
= QuicTime::Delta::FromSeconds(kPingTimeoutSecs
);
1945 ping_alarm_
->Set(clock_
->ApproximateNow().Add(ping_timeout
));
1948 QuicConnection::ScopedPacketBundler::ScopedPacketBundler(
1949 QuicConnection
* connection
,
1950 AckBundling send_ack
)
1951 : connection_(connection
),
1952 already_in_batch_mode_(connection
!= NULL
&&
1953 connection
->packet_generator_
.InBatchMode()) {
1954 if (connection_
== NULL
) {
1957 // Move generator into batch mode. If caller wants us to include an ack,
1958 // check the delayed-ack timer to see if there's ack info to be sent.
1959 if (!already_in_batch_mode_
) {
1960 DVLOG(1) << "Entering Batch Mode.";
1961 connection_
->packet_generator_
.StartBatchOperations();
1963 // Bundle an ack if the alarm is set or with every second packet if we need to
1964 // raise the peer's least unacked.
1966 connection_
->ack_alarm_
->IsSet() || connection_
->stop_waiting_count_
> 1;
1967 if (send_ack
== SEND_ACK
|| (send_ack
== BUNDLE_PENDING_ACK
&& ack_pending
)) {
1968 DVLOG(1) << "Bundling ack with outgoing packet.";
1969 connection_
->SendAck();
1973 QuicConnection::ScopedPacketBundler::~ScopedPacketBundler() {
1974 if (connection_
== NULL
) {
1977 // If we changed the generator's batch state, restore original batch state.
1978 if (!already_in_batch_mode_
) {
1979 DVLOG(1) << "Leaving Batch Mode.";
1980 connection_
->packet_generator_
.FinishBatchOperations();
1982 DCHECK_EQ(already_in_batch_mode_
,
1983 connection_
->packet_generator_
.InBatchMode());