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_flow_controller.h"
27 #include "net/quic/quic_utils.h"
31 using base::StringPiece
;
36 using std::numeric_limits
;
48 // The largest gap in packets we'll accept without closing the connection.
49 // This will likely have to be tuned.
50 const QuicPacketSequenceNumber kMaxPacketGap
= 5000;
52 // Limit the number of FEC groups to two. If we get enough out of order packets
53 // that this becomes limiting, we can revisit.
54 const size_t kMaxFecGroups
= 2;
56 // Limit the number of undecryptable packets we buffer in
57 // expectation of the CHLO/SHLO arriving.
58 const size_t kMaxUndecryptablePackets
= 10;
60 bool Near(QuicPacketSequenceNumber a
, QuicPacketSequenceNumber b
) {
61 QuicPacketSequenceNumber delta
= (a
> b
) ? a
- b
: b
- a
;
62 return delta
<= kMaxPacketGap
;
65 // An alarm that is scheduled to send an ack if a timeout occurs.
66 class AckAlarm
: public QuicAlarm::Delegate
{
68 explicit AckAlarm(QuicConnection
* connection
)
69 : connection_(connection
) {
72 virtual QuicTime
OnAlarm() OVERRIDE
{
73 connection_
->SendAck();
74 return QuicTime::Zero();
78 QuicConnection
* connection_
;
80 DISALLOW_COPY_AND_ASSIGN(AckAlarm
);
83 // This alarm will be scheduled any time a data-bearing packet is sent out.
84 // When the alarm goes off, the connection checks to see if the oldest packets
85 // have been acked, and retransmit them if they have not.
86 class RetransmissionAlarm
: public QuicAlarm::Delegate
{
88 explicit RetransmissionAlarm(QuicConnection
* connection
)
89 : connection_(connection
) {
92 virtual QuicTime
OnAlarm() OVERRIDE
{
93 connection_
->OnRetransmissionTimeout();
94 return QuicTime::Zero();
98 QuicConnection
* connection_
;
100 DISALLOW_COPY_AND_ASSIGN(RetransmissionAlarm
);
103 // An alarm that is scheduled when the sent scheduler requires a
104 // a delay before sending packets and fires when the packet may be sent.
105 class SendAlarm
: public QuicAlarm::Delegate
{
107 explicit SendAlarm(QuicConnection
* connection
)
108 : connection_(connection
) {
111 virtual QuicTime
OnAlarm() OVERRIDE
{
112 connection_
->WriteIfNotBlocked();
113 // Never reschedule the alarm, since CanWrite does that.
114 return QuicTime::Zero();
118 QuicConnection
* connection_
;
120 DISALLOW_COPY_AND_ASSIGN(SendAlarm
);
123 class TimeoutAlarm
: public QuicAlarm::Delegate
{
125 explicit TimeoutAlarm(QuicConnection
* connection
)
126 : connection_(connection
) {
129 virtual QuicTime
OnAlarm() OVERRIDE
{
130 connection_
->CheckForTimeout();
131 // Never reschedule the alarm, since CheckForTimeout does that.
132 return QuicTime::Zero();
136 QuicConnection
* connection_
;
138 DISALLOW_COPY_AND_ASSIGN(TimeoutAlarm
);
141 class PingAlarm
: public QuicAlarm::Delegate
{
143 explicit PingAlarm(QuicConnection
* connection
)
144 : connection_(connection
) {
147 virtual QuicTime
OnAlarm() OVERRIDE
{
148 connection_
->SendPing();
149 return QuicTime::Zero();
153 QuicConnection
* connection_
;
155 DISALLOW_COPY_AND_ASSIGN(PingAlarm
);
158 QuicConnection::PacketType
GetPacketType(
159 const RetransmittableFrames
* retransmittable_frames
) {
160 if (!retransmittable_frames
) {
161 return QuicConnection::NORMAL
;
163 for (size_t i
= 0; i
< retransmittable_frames
->frames().size(); ++i
) {
164 if (retransmittable_frames
->frames()[i
].type
== CONNECTION_CLOSE_FRAME
) {
165 return QuicConnection::CONNECTION_CLOSE
;
168 return QuicConnection::NORMAL
;
173 QuicConnection::QueuedPacket::QueuedPacket(SerializedPacket packet
,
174 EncryptionLevel level
,
175 TransmissionType transmission_type
)
176 : sequence_number(packet
.sequence_number
),
177 packet(packet
.packet
),
178 encryption_level(level
),
179 transmission_type(transmission_type
),
180 retransmittable((transmission_type
!= NOT_RETRANSMISSION
||
181 packet
.retransmittable_frames
!= NULL
) ?
182 HAS_RETRANSMITTABLE_DATA
: NO_RETRANSMITTABLE_DATA
),
183 handshake(packet
.retransmittable_frames
== NULL
?
184 NOT_HANDSHAKE
: packet
.retransmittable_frames
->HasCryptoHandshake()),
185 type(GetPacketType(packet
.retransmittable_frames
)),
186 length(packet
.packet
->length()) {
189 #define ENDPOINT (is_server_ ? "Server: " : " Client: ")
191 QuicConnection::QuicConnection(QuicConnectionId connection_id
,
193 QuicConnectionHelperInterface
* helper
,
194 QuicPacketWriter
* writer
,
196 const QuicVersionVector
& supported_versions
,
197 uint32 max_flow_control_receive_window_bytes
)
198 : framer_(supported_versions
, helper
->GetClock()->ApproximateNow(),
202 encryption_level_(ENCRYPTION_NONE
),
203 clock_(helper
->GetClock()),
204 random_generator_(helper
->GetRandomGenerator()),
205 connection_id_(connection_id
),
206 peer_address_(address
),
207 last_packet_revived_(false),
209 last_decrypted_packet_level_(ENCRYPTION_NONE
),
210 largest_seen_packet_with_ack_(0),
211 largest_seen_packet_with_stop_waiting_(0),
212 pending_version_negotiation_packet_(false),
213 received_packet_manager_(kTCP
, &stats_
),
215 stop_waiting_count_(0),
216 ack_alarm_(helper
->CreateAlarm(new AckAlarm(this))),
217 retransmission_alarm_(helper
->CreateAlarm(new RetransmissionAlarm(this))),
218 send_alarm_(helper
->CreateAlarm(new SendAlarm(this))),
219 resume_writes_alarm_(helper
->CreateAlarm(new SendAlarm(this))),
220 timeout_alarm_(helper
->CreateAlarm(new TimeoutAlarm(this))),
221 ping_alarm_(helper
->CreateAlarm(new PingAlarm(this))),
222 debug_visitor_(NULL
),
223 packet_creator_(connection_id_
, &framer_
, random_generator_
, is_server
),
224 packet_generator_(this, NULL
, &packet_creator_
),
225 idle_network_timeout_(
226 QuicTime::Delta::FromSeconds(kDefaultInitialTimeoutSecs
)),
227 overall_connection_timeout_(QuicTime::Delta::Infinite()),
228 time_of_last_received_packet_(clock_
->ApproximateNow()),
229 time_of_last_sent_new_packet_(clock_
->ApproximateNow()),
230 sequence_number_of_last_sent_packet_(0),
231 sent_packet_manager_(
232 is_server
, clock_
, &stats_
, kTCP
,
233 FLAGS_quic_use_time_loss_detection
? kTime
: kNack
),
234 version_negotiation_state_(START_NEGOTIATION
),
235 is_server_(is_server
),
237 address_migrating_(false),
238 max_flow_control_receive_window_bytes_(
239 max_flow_control_receive_window_bytes
) {
240 if (max_flow_control_receive_window_bytes_
< kDefaultFlowControlSendWindow
) {
241 DLOG(ERROR
) << "Initial receive window ("
242 << max_flow_control_receive_window_bytes_
243 << ") cannot be set lower than default ("
244 << kDefaultFlowControlSendWindow
<< ").";
245 max_flow_control_receive_window_bytes_
= kDefaultFlowControlSendWindow
;
248 flow_controller_
.reset(new QuicFlowController(
249 supported_versions
.front(), 0, is_server_
,
250 kDefaultFlowControlSendWindow
, max_flow_control_receive_window_bytes_
,
251 max_flow_control_receive_window_bytes_
));
254 // Pacing will be enabled if the client negotiates it.
255 sent_packet_manager_
.MaybeEnablePacing();
257 DVLOG(1) << ENDPOINT
<< "Created connection with connection_id: "
259 timeout_alarm_
->Set(clock_
->ApproximateNow().Add(idle_network_timeout_
));
260 framer_
.set_visitor(this);
261 framer_
.set_received_entropy_calculator(&received_packet_manager_
);
262 stats_
.connection_creation_time
= clock_
->ApproximateNow();
265 QuicConnection::~QuicConnection() {
266 STLDeleteElements(&undecryptable_packets_
);
267 STLDeleteValues(&group_map_
);
268 for (QueuedPacketList::iterator it
= queued_packets_
.begin();
269 it
!= queued_packets_
.end(); ++it
) {
274 void QuicConnection::SetFromConfig(const QuicConfig
& config
) {
275 SetIdleNetworkTimeout(config
.idle_connection_state_lifetime());
276 sent_packet_manager_
.SetFromConfig(config
);
277 // TODO(satyamshekhar): Set congestion control and ICSL also.
280 bool QuicConnection::SelectMutualVersion(
281 const QuicVersionVector
& available_versions
) {
282 // Try to find the highest mutual version by iterating over supported
283 // versions, starting with the highest, and breaking out of the loop once we
284 // find a matching version in the provided available_versions vector.
285 const QuicVersionVector
& supported_versions
= framer_
.supported_versions();
286 for (size_t i
= 0; i
< supported_versions
.size(); ++i
) {
287 const QuicVersion
& version
= supported_versions
[i
];
288 if (std::find(available_versions
.begin(), available_versions
.end(),
289 version
) != available_versions
.end()) {
290 framer_
.set_version(version
);
298 void QuicConnection::OnError(QuicFramer
* framer
) {
299 // Packets that we cannot decrypt are dropped.
300 // TODO(rch): add stats to measure this.
301 if (!connected_
|| framer
->error() == QUIC_DECRYPTION_FAILURE
) {
304 SendConnectionCloseWithDetails(framer
->error(), framer
->detailed_error());
307 void QuicConnection::OnPacket() {
308 DCHECK(last_stream_frames_
.empty() &&
309 last_goaway_frames_
.empty() &&
310 last_window_update_frames_
.empty() &&
311 last_blocked_frames_
.empty() &&
312 last_rst_frames_
.empty() &&
313 last_ack_frames_
.empty() &&
314 last_congestion_frames_
.empty() &&
315 last_stop_waiting_frames_
.empty());
318 void QuicConnection::OnPublicResetPacket(
319 const QuicPublicResetPacket
& packet
) {
320 if (debug_visitor_
) {
321 debug_visitor_
->OnPublicResetPacket(packet
);
323 CloseConnection(QUIC_PUBLIC_RESET
, true);
326 bool QuicConnection::OnProtocolVersionMismatch(QuicVersion received_version
) {
327 DVLOG(1) << ENDPOINT
<< "Received packet with mismatched version "
329 // TODO(satyamshekhar): Implement no server state in this mode.
331 LOG(DFATAL
) << ENDPOINT
<< "Framer called OnProtocolVersionMismatch. "
332 << "Closing connection.";
333 CloseConnection(QUIC_INTERNAL_ERROR
, false);
336 DCHECK_NE(version(), received_version
);
338 if (debug_visitor_
) {
339 debug_visitor_
->OnProtocolVersionMismatch(received_version
);
342 switch (version_negotiation_state_
) {
343 case START_NEGOTIATION
:
344 if (!framer_
.IsSupportedVersion(received_version
)) {
345 SendVersionNegotiationPacket();
346 version_negotiation_state_
= NEGOTIATION_IN_PROGRESS
;
351 case NEGOTIATION_IN_PROGRESS
:
352 if (!framer_
.IsSupportedVersion(received_version
)) {
353 SendVersionNegotiationPacket();
358 case NEGOTIATED_VERSION
:
359 // Might be old packets that were sent by the client before the version
360 // was negotiated. Drop these.
367 version_negotiation_state_
= NEGOTIATED_VERSION
;
368 visitor_
->OnSuccessfulVersionNegotiation(received_version
);
369 DVLOG(1) << ENDPOINT
<< "version negotiated " << received_version
;
371 // Store the new version.
372 framer_
.set_version(received_version
);
374 if (received_version
< QUIC_VERSION_19
) {
375 flow_controller_
->Disable();
378 // TODO(satyamshekhar): Store the sequence number of this packet and close the
379 // connection if we ever received a packet with incorrect version and whose
380 // sequence number is greater.
384 // Handles version negotiation for client connection.
385 void QuicConnection::OnVersionNegotiationPacket(
386 const QuicVersionNegotiationPacket
& packet
) {
388 LOG(DFATAL
) << ENDPOINT
<< "Framer parsed VersionNegotiationPacket."
389 << " Closing connection.";
390 CloseConnection(QUIC_INTERNAL_ERROR
, false);
393 if (debug_visitor_
) {
394 debug_visitor_
->OnVersionNegotiationPacket(packet
);
397 if (version_negotiation_state_
!= START_NEGOTIATION
) {
398 // Possibly a duplicate version negotiation packet.
402 if (std::find(packet
.versions
.begin(),
403 packet
.versions
.end(), version()) !=
404 packet
.versions
.end()) {
405 DLOG(WARNING
) << ENDPOINT
<< "The server already supports our version. "
406 << "It should have accepted our connection.";
407 // Just drop the connection.
408 CloseConnection(QUIC_INVALID_VERSION_NEGOTIATION_PACKET
, false);
412 if (!SelectMutualVersion(packet
.versions
)) {
413 SendConnectionCloseWithDetails(QUIC_INVALID_VERSION
,
414 "no common version found");
418 DVLOG(1) << ENDPOINT
<< "negotiating version " << version();
419 server_supported_versions_
= packet
.versions
;
420 version_negotiation_state_
= NEGOTIATION_IN_PROGRESS
;
421 RetransmitUnackedPackets(ALL_PACKETS
);
424 void QuicConnection::OnRevivedPacket() {
427 bool QuicConnection::OnUnauthenticatedPublicHeader(
428 const QuicPacketPublicHeader
& header
) {
432 bool QuicConnection::OnUnauthenticatedHeader(const QuicPacketHeader
& header
) {
436 void QuicConnection::OnDecryptedPacket(EncryptionLevel level
) {
437 last_decrypted_packet_level_
= level
;
440 bool QuicConnection::OnPacketHeader(const QuicPacketHeader
& header
) {
441 if (debug_visitor_
) {
442 debug_visitor_
->OnPacketHeader(header
);
445 if (!ProcessValidatedPacket()) {
449 // Will be decrement below if we fall through to return true;
450 ++stats_
.packets_dropped
;
452 if (header
.public_header
.connection_id
!= connection_id_
) {
453 DVLOG(1) << ENDPOINT
<< "Ignoring packet from unexpected ConnectionId: "
454 << header
.public_header
.connection_id
<< " instead of "
459 if (!Near(header
.packet_sequence_number
,
460 last_header_
.packet_sequence_number
)) {
461 DVLOG(1) << ENDPOINT
<< "Packet " << header
.packet_sequence_number
462 << " out of bounds. Discarding";
463 SendConnectionCloseWithDetails(QUIC_INVALID_PACKET_HEADER
,
464 "Packet sequence number out of bounds");
468 // If this packet has already been seen, or that the sender
469 // has told us will not be retransmitted, then stop processing the packet.
470 if (!received_packet_manager_
.IsAwaitingPacket(
471 header
.packet_sequence_number
)) {
472 DVLOG(1) << ENDPOINT
<< "Packet " << header
.packet_sequence_number
473 << " no longer being waited for. Discarding.";
474 // TODO(jri): Log reception of duplicate packets or packets the peer has
475 // told us to stop waiting for.
479 if (version_negotiation_state_
!= NEGOTIATED_VERSION
) {
481 if (!header
.public_header
.version_flag
) {
482 DLOG(WARNING
) << ENDPOINT
<< "Packet " << header
.packet_sequence_number
483 << " without version flag before version negotiated.";
484 // Packets should have the version flag till version negotiation is
486 CloseConnection(QUIC_INVALID_VERSION
, false);
489 DCHECK_EQ(1u, header
.public_header
.versions
.size());
490 DCHECK_EQ(header
.public_header
.versions
[0], version());
491 version_negotiation_state_
= NEGOTIATED_VERSION
;
492 visitor_
->OnSuccessfulVersionNegotiation(version());
493 if (version() < QUIC_VERSION_19
) {
494 flow_controller_
->Disable();
498 DCHECK(!header
.public_header
.version_flag
);
499 // If the client gets a packet without the version flag from the server
500 // it should stop sending version since the version negotiation is done.
501 packet_creator_
.StopSendingVersion();
502 version_negotiation_state_
= NEGOTIATED_VERSION
;
503 visitor_
->OnSuccessfulVersionNegotiation(version());
504 if (version() < QUIC_VERSION_19
) {
505 flow_controller_
->Disable();
510 DCHECK_EQ(NEGOTIATED_VERSION
, version_negotiation_state_
);
512 --stats_
.packets_dropped
;
513 DVLOG(1) << ENDPOINT
<< "Received packet header: " << header
;
514 last_header_
= header
;
519 void QuicConnection::OnFecProtectedPayload(StringPiece payload
) {
520 DCHECK_EQ(IN_FEC_GROUP
, last_header_
.is_in_fec_group
);
521 DCHECK_NE(0u, last_header_
.fec_group
);
522 QuicFecGroup
* group
= GetFecGroup();
524 group
->Update(last_decrypted_packet_level_
, last_header_
, payload
);
528 bool QuicConnection::OnStreamFrame(const QuicStreamFrame
& frame
) {
530 if (debug_visitor_
) {
531 debug_visitor_
->OnStreamFrame(frame
);
533 if (frame
.stream_id
!= kCryptoStreamId
&&
534 last_decrypted_packet_level_
== ENCRYPTION_NONE
) {
535 DLOG(WARNING
) << ENDPOINT
536 << "Received an unencrypted data frame: closing connection";
537 SendConnectionClose(QUIC_UNENCRYPTED_STREAM_DATA
);
540 last_stream_frames_
.push_back(frame
);
544 bool QuicConnection::OnAckFrame(const QuicAckFrame
& incoming_ack
) {
546 if (debug_visitor_
) {
547 debug_visitor_
->OnAckFrame(incoming_ack
);
549 DVLOG(1) << ENDPOINT
<< "OnAckFrame: " << incoming_ack
;
551 if (last_header_
.packet_sequence_number
<= largest_seen_packet_with_ack_
) {
552 DVLOG(1) << ENDPOINT
<< "Received an old ack frame: ignoring";
556 if (!ValidateAckFrame(incoming_ack
)) {
557 SendConnectionClose(QUIC_INVALID_ACK_DATA
);
561 last_ack_frames_
.push_back(incoming_ack
);
565 void QuicConnection::ProcessAckFrame(const QuicAckFrame
& incoming_ack
) {
566 largest_seen_packet_with_ack_
= last_header_
.packet_sequence_number
;
567 received_packet_manager_
.UpdatePacketInformationReceivedByPeer(
568 incoming_ack
.received_info
);
569 if (version() <= QUIC_VERSION_15
) {
570 ProcessStopWaitingFrame(incoming_ack
.sent_info
);
573 sent_entropy_manager_
.ClearEntropyBefore(
574 received_packet_manager_
.least_packet_awaited_by_peer() - 1);
576 sent_packet_manager_
.OnIncomingAck(incoming_ack
.received_info
,
577 time_of_last_received_packet_
);
578 if (sent_packet_manager_
.HasPendingRetransmissions()) {
582 // Always reset the retransmission alarm when an ack comes in, since we now
583 // have a better estimate of the current rtt than when it was set.
584 retransmission_alarm_
->Cancel();
585 QuicTime retransmission_time
=
586 sent_packet_manager_
.GetRetransmissionTime();
587 if (retransmission_time
!= QuicTime::Zero()) {
588 retransmission_alarm_
->Set(retransmission_time
);
592 void QuicConnection::ProcessStopWaitingFrame(
593 const QuicStopWaitingFrame
& stop_waiting
) {
594 largest_seen_packet_with_stop_waiting_
= last_header_
.packet_sequence_number
;
595 received_packet_manager_
.UpdatePacketInformationSentByPeer(stop_waiting
);
596 // Possibly close any FecGroups which are now irrelevant.
597 CloseFecGroupsBefore(stop_waiting
.least_unacked
+ 1);
600 bool QuicConnection::OnCongestionFeedbackFrame(
601 const QuicCongestionFeedbackFrame
& feedback
) {
603 if (debug_visitor_
) {
604 debug_visitor_
->OnCongestionFeedbackFrame(feedback
);
606 last_congestion_frames_
.push_back(feedback
);
610 bool QuicConnection::OnStopWaitingFrame(const QuicStopWaitingFrame
& frame
) {
613 if (last_header_
.packet_sequence_number
<=
614 largest_seen_packet_with_stop_waiting_
) {
615 DVLOG(1) << ENDPOINT
<< "Received an old stop waiting frame: ignoring";
619 if (!ValidateStopWaitingFrame(frame
)) {
620 SendConnectionClose(QUIC_INVALID_STOP_WAITING_DATA
);
624 if (debug_visitor_
) {
625 debug_visitor_
->OnStopWaitingFrame(frame
);
628 last_stop_waiting_frames_
.push_back(frame
);
632 bool QuicConnection::OnPingFrame(const QuicPingFrame
& frame
) {
634 if (debug_visitor_
) {
635 debug_visitor_
->OnPingFrame(frame
);
640 bool QuicConnection::ValidateAckFrame(const QuicAckFrame
& incoming_ack
) {
641 if (incoming_ack
.received_info
.largest_observed
>
642 packet_creator_
.sequence_number()) {
643 DLOG(ERROR
) << ENDPOINT
<< "Peer's observed unsent packet:"
644 << incoming_ack
.received_info
.largest_observed
<< " vs "
645 << packet_creator_
.sequence_number();
646 // We got an error for data we have not sent. Error out.
650 if (incoming_ack
.received_info
.largest_observed
<
651 received_packet_manager_
.peer_largest_observed_packet()) {
652 DLOG(ERROR
) << ENDPOINT
<< "Peer's largest_observed packet decreased:"
653 << incoming_ack
.received_info
.largest_observed
<< " vs "
654 << received_packet_manager_
.peer_largest_observed_packet();
655 // A new ack has a diminished largest_observed value. Error out.
656 // If this was an old packet, we wouldn't even have checked.
660 if (version() <= QUIC_VERSION_15
) {
661 if (!ValidateStopWaitingFrame(incoming_ack
.sent_info
)) {
666 if (!incoming_ack
.received_info
.missing_packets
.empty() &&
667 *incoming_ack
.received_info
.missing_packets
.rbegin() >
668 incoming_ack
.received_info
.largest_observed
) {
669 DLOG(ERROR
) << ENDPOINT
<< "Peer sent missing packet: "
670 << *incoming_ack
.received_info
.missing_packets
.rbegin()
671 << " which is greater than largest observed: "
672 << incoming_ack
.received_info
.largest_observed
;
676 if (!incoming_ack
.received_info
.missing_packets
.empty() &&
677 *incoming_ack
.received_info
.missing_packets
.begin() <
678 received_packet_manager_
.least_packet_awaited_by_peer()) {
679 DLOG(ERROR
) << ENDPOINT
<< "Peer sent missing packet: "
680 << *incoming_ack
.received_info
.missing_packets
.begin()
681 << " which is smaller than least_packet_awaited_by_peer_: "
682 << received_packet_manager_
.least_packet_awaited_by_peer();
686 if (!sent_entropy_manager_
.IsValidEntropy(
687 incoming_ack
.received_info
.largest_observed
,
688 incoming_ack
.received_info
.missing_packets
,
689 incoming_ack
.received_info
.entropy_hash
)) {
690 DLOG(ERROR
) << ENDPOINT
<< "Peer sent invalid entropy.";
694 for (SequenceNumberSet::const_iterator iter
=
695 incoming_ack
.received_info
.revived_packets
.begin();
696 iter
!= incoming_ack
.received_info
.revived_packets
.end(); ++iter
) {
697 if (!ContainsKey(incoming_ack
.received_info
.missing_packets
, *iter
)) {
698 DLOG(ERROR
) << ENDPOINT
699 << "Peer specified revived packet which was not missing.";
706 bool QuicConnection::ValidateStopWaitingFrame(
707 const QuicStopWaitingFrame
& stop_waiting
) {
708 if (stop_waiting
.least_unacked
<
709 received_packet_manager_
.peer_least_packet_awaiting_ack()) {
710 DLOG(ERROR
) << ENDPOINT
<< "Peer's sent low least_unacked: "
711 << stop_waiting
.least_unacked
<< " vs "
712 << received_packet_manager_
.peer_least_packet_awaiting_ack();
713 // We never process old ack frames, so this number should only increase.
717 if (stop_waiting
.least_unacked
>
718 last_header_
.packet_sequence_number
) {
719 DLOG(ERROR
) << ENDPOINT
<< "Peer sent least_unacked:"
720 << stop_waiting
.least_unacked
721 << " greater than the enclosing packet sequence number:"
722 << last_header_
.packet_sequence_number
;
729 void QuicConnection::OnFecData(const QuicFecData
& fec
) {
730 DCHECK_EQ(IN_FEC_GROUP
, last_header_
.is_in_fec_group
);
731 DCHECK_NE(0u, last_header_
.fec_group
);
732 QuicFecGroup
* group
= GetFecGroup();
734 group
->UpdateFec(last_decrypted_packet_level_
,
735 last_header_
.packet_sequence_number
, fec
);
739 bool QuicConnection::OnRstStreamFrame(const QuicRstStreamFrame
& frame
) {
741 if (debug_visitor_
) {
742 debug_visitor_
->OnRstStreamFrame(frame
);
744 DVLOG(1) << ENDPOINT
<< "Stream reset with error "
745 << QuicUtils::StreamErrorToString(frame
.error_code
);
746 last_rst_frames_
.push_back(frame
);
750 bool QuicConnection::OnConnectionCloseFrame(
751 const QuicConnectionCloseFrame
& frame
) {
753 if (debug_visitor_
) {
754 debug_visitor_
->OnConnectionCloseFrame(frame
);
756 DVLOG(1) << ENDPOINT
<< "Connection " << connection_id()
757 << " closed with error "
758 << QuicUtils::ErrorToString(frame
.error_code
)
759 << " " << frame
.error_details
;
760 last_close_frames_
.push_back(frame
);
764 bool QuicConnection::OnGoAwayFrame(const QuicGoAwayFrame
& frame
) {
766 DVLOG(1) << ENDPOINT
<< "Go away received with error "
767 << QuicUtils::ErrorToString(frame
.error_code
)
768 << " and reason:" << frame
.reason_phrase
;
769 last_goaway_frames_
.push_back(frame
);
773 bool QuicConnection::OnWindowUpdateFrame(const QuicWindowUpdateFrame
& frame
) {
775 DVLOG(1) << ENDPOINT
<< "WindowUpdate received for stream: "
776 << frame
.stream_id
<< " with byte offset: " << frame
.byte_offset
;
777 last_window_update_frames_
.push_back(frame
);
781 bool QuicConnection::OnBlockedFrame(const QuicBlockedFrame
& frame
) {
783 DVLOG(1) << ENDPOINT
<< "Blocked frame received for stream: "
785 last_blocked_frames_
.push_back(frame
);
789 void QuicConnection::OnPacketComplete() {
790 // Don't do anything if this packet closed the connection.
796 DVLOG(1) << ENDPOINT
<< (last_packet_revived_
? "Revived" : "Got")
797 << " packet " << last_header_
.packet_sequence_number
798 << " with " << last_ack_frames_
.size() << " acks, "
799 << last_congestion_frames_
.size() << " congestions, "
800 << last_stop_waiting_frames_
.size() << " stop_waiting, "
801 << last_goaway_frames_
.size() << " goaways, "
802 << last_window_update_frames_
.size() << " window updates, "
803 << last_blocked_frames_
.size() << " blocked, "
804 << last_rst_frames_
.size() << " rsts, "
805 << last_close_frames_
.size() << " closes, "
806 << last_stream_frames_
.size()
807 << " stream frames for "
808 << last_header_
.public_header
.connection_id
;
810 // Call MaybeQueueAck() before recording the received packet, since we want
811 // to trigger an ack if the newly received packet was previously missing.
814 // Record received or revived packet to populate ack info correctly before
815 // processing stream frames, since the processing may result in a response
816 // packet with a bundled ack.
817 if (last_packet_revived_
) {
818 received_packet_manager_
.RecordPacketRevived(
819 last_header_
.packet_sequence_number
);
821 received_packet_manager_
.RecordPacketReceived(
822 last_size_
, last_header_
, time_of_last_received_packet_
);
825 if (!last_stream_frames_
.empty()) {
826 visitor_
->OnStreamFrames(last_stream_frames_
);
829 for (size_t i
= 0; i
< last_stream_frames_
.size(); ++i
) {
830 stats_
.stream_bytes_received
+=
831 last_stream_frames_
[i
].data
.TotalBufferSize();
834 // Process window updates, blocked, stream resets, acks, then congestion
836 if (!last_window_update_frames_
.empty()) {
837 visitor_
->OnWindowUpdateFrames(last_window_update_frames_
);
839 if (!last_blocked_frames_
.empty()) {
840 visitor_
->OnBlockedFrames(last_blocked_frames_
);
842 for (size_t i
= 0; i
< last_goaway_frames_
.size(); ++i
) {
843 visitor_
->OnGoAway(last_goaway_frames_
[i
]);
845 for (size_t i
= 0; i
< last_rst_frames_
.size(); ++i
) {
846 visitor_
->OnRstStream(last_rst_frames_
[i
]);
848 for (size_t i
= 0; i
< last_ack_frames_
.size(); ++i
) {
849 ProcessAckFrame(last_ack_frames_
[i
]);
851 for (size_t i
= 0; i
< last_congestion_frames_
.size(); ++i
) {
852 sent_packet_manager_
.OnIncomingQuicCongestionFeedbackFrame(
853 last_congestion_frames_
[i
], time_of_last_received_packet_
);
855 for (size_t i
= 0; i
< last_stop_waiting_frames_
.size(); ++i
) {
856 ProcessStopWaitingFrame(last_stop_waiting_frames_
[i
]);
858 if (!last_close_frames_
.empty()) {
859 CloseConnection(last_close_frames_
[0].error_code
, true);
863 // If there are new missing packets to report, send an ack immediately.
864 if (received_packet_manager_
.HasNewMissingPackets()) {
866 ack_alarm_
->Cancel();
869 UpdateStopWaitingCount();
874 void QuicConnection::MaybeQueueAck() {
875 // If the incoming packet was missing, send an ack immediately.
876 ack_queued_
= received_packet_manager_
.IsMissing(
877 last_header_
.packet_sequence_number
);
879 if (!ack_queued_
&& ShouldLastPacketInstigateAck()) {
880 if (ack_alarm_
->IsSet()) {
883 // Send an ack much more quickly for crypto handshake packets.
884 QuicTime::Delta delayed_ack_time
= sent_packet_manager_
.DelayedAckTime();
885 if (last_stream_frames_
.size() == 1 &&
886 last_stream_frames_
[0].stream_id
== kCryptoStreamId
) {
887 delayed_ack_time
= QuicTime::Delta::Zero();
889 ack_alarm_
->Set(clock_
->ApproximateNow().Add(delayed_ack_time
));
890 DVLOG(1) << "Ack timer set; next packet or timer will trigger ACK.";
895 ack_alarm_
->Cancel();
899 void QuicConnection::ClearLastFrames() {
900 last_stream_frames_
.clear();
901 last_goaway_frames_
.clear();
902 last_window_update_frames_
.clear();
903 last_blocked_frames_
.clear();
904 last_rst_frames_
.clear();
905 last_ack_frames_
.clear();
906 last_stop_waiting_frames_
.clear();
907 last_congestion_frames_
.clear();
910 QuicAckFrame
* QuicConnection::CreateAckFrame() {
911 QuicAckFrame
* outgoing_ack
= new QuicAckFrame();
912 received_packet_manager_
.UpdateReceivedPacketInfo(
913 &(outgoing_ack
->received_info
), clock_
->ApproximateNow());
914 UpdateStopWaiting(&(outgoing_ack
->sent_info
));
915 DVLOG(1) << ENDPOINT
<< "Creating ack frame: " << *outgoing_ack
;
919 QuicCongestionFeedbackFrame
* QuicConnection::CreateFeedbackFrame() {
920 return new QuicCongestionFeedbackFrame(outgoing_congestion_feedback_
);
923 QuicStopWaitingFrame
* QuicConnection::CreateStopWaitingFrame() {
924 QuicStopWaitingFrame stop_waiting
;
925 UpdateStopWaiting(&stop_waiting
);
926 return new QuicStopWaitingFrame(stop_waiting
);
929 bool QuicConnection::ShouldLastPacketInstigateAck() const {
930 if (!last_stream_frames_
.empty() ||
931 !last_goaway_frames_
.empty() ||
932 !last_rst_frames_
.empty() ||
933 !last_window_update_frames_
.empty() ||
934 !last_blocked_frames_
.empty()) {
938 if (!last_ack_frames_
.empty() &&
939 last_ack_frames_
.back().received_info
.is_truncated
) {
945 void QuicConnection::UpdateStopWaitingCount() {
946 if (last_ack_frames_
.empty()) {
950 // If the peer is still waiting for a packet that we are no longer planning to
951 // send, send an ack to raise the high water mark.
952 if (!last_ack_frames_
.back().received_info
.missing_packets
.empty() &&
954 *last_ack_frames_
.back().received_info
.missing_packets
.begin()) {
955 ++stop_waiting_count_
;
957 stop_waiting_count_
= 0;
961 QuicPacketSequenceNumber
QuicConnection::GetLeastUnacked() const {
962 return sent_packet_manager_
.HasUnackedPackets() ?
963 sent_packet_manager_
.GetLeastUnackedSentPacket() :
964 packet_creator_
.sequence_number() + 1;
967 void QuicConnection::MaybeSendInResponseToPacket() {
971 ScopedPacketBundler
bundler(this, ack_queued_
? SEND_ACK
: NO_ACK
);
973 // Now that we have received an ack, we might be able to send packets which
974 // are queued locally, or drain streams which are blocked.
975 QuicTime::Delta delay
= sent_packet_manager_
.TimeUntilSend(
976 time_of_last_received_packet_
, NOT_RETRANSMISSION
,
977 HAS_RETRANSMITTABLE_DATA
);
978 if (delay
.IsZero()) {
979 send_alarm_
->Cancel();
981 } else if (!delay
.IsInfinite()) {
982 send_alarm_
->Cancel();
983 send_alarm_
->Set(time_of_last_received_packet_
.Add(delay
));
987 void QuicConnection::SendVersionNegotiationPacket() {
988 // TODO(alyssar): implement zero server state negotiation.
989 pending_version_negotiation_packet_
= true;
990 if (writer_
->IsWriteBlocked()) {
991 visitor_
->OnWriteBlocked();
994 scoped_ptr
<QuicEncryptedPacket
> version_packet(
995 packet_creator_
.SerializeVersionNegotiationPacket(
996 framer_
.supported_versions()));
997 WriteResult result
= writer_
->WritePacket(
998 version_packet
->data(), version_packet
->length(),
999 self_address().address(), peer_address());
1001 if (result
.status
== WRITE_STATUS_ERROR
) {
1002 // We can't send an error as the socket is presumably borked.
1003 CloseConnection(QUIC_PACKET_WRITE_ERROR
, false);
1006 if (result
.status
== WRITE_STATUS_BLOCKED
) {
1007 visitor_
->OnWriteBlocked();
1008 if (writer_
->IsWriteBlockedDataBuffered()) {
1009 pending_version_negotiation_packet_
= false;
1014 pending_version_negotiation_packet_
= false;
1017 QuicConsumedData
QuicConnection::SendStreamData(
1019 const IOVector
& data
,
1020 QuicStreamOffset offset
,
1022 QuicAckNotifier::DelegateInterface
* delegate
) {
1023 if (!fin
&& data
.Empty()) {
1024 LOG(DFATAL
) << "Attempt to send empty stream frame";
1027 // This notifier will be owned by the AckNotifierManager (or deleted below if
1028 // no data or FIN was consumed).
1029 QuicAckNotifier
* notifier
= NULL
;
1031 notifier
= new QuicAckNotifier(delegate
);
1034 // Opportunistically bundle an ack with every outgoing packet.
1035 // Particularly, we want to bundle with handshake packets since we don't know
1036 // which decrypter will be used on an ack packet following a handshake
1037 // packet (a handshake packet from client to server could result in a REJ or a
1038 // SHLO from the server, leading to two different decrypters at the server.)
1040 // TODO(jri): Note that ConsumeData may cause a response packet to be sent.
1041 // We may end up sending stale ack information if there are undecryptable
1042 // packets hanging around and/or there are revivable packets which may get
1043 // handled after this packet is sent. Change ScopedPacketBundler to do the
1044 // right thing: check ack_queued_, and then check undecryptable packets and
1045 // also if there is possibility of revival. Only bundle an ack if there's no
1046 // processing left that may cause received_info_ to change.
1047 ScopedPacketBundler
ack_bundler(this, BUNDLE_PENDING_ACK
);
1048 QuicConsumedData consumed_data
=
1049 packet_generator_
.ConsumeData(id
, data
, offset
, fin
, notifier
);
1052 (consumed_data
.bytes_consumed
== 0 && !consumed_data
.fin_consumed
)) {
1053 // No data was consumed, nor was a fin consumed, so delete the notifier.
1057 return consumed_data
;
1060 void QuicConnection::SendRstStream(QuicStreamId id
,
1061 QuicRstStreamErrorCode error
,
1062 QuicStreamOffset bytes_written
) {
1063 // Opportunistically bundle an ack with this outgoing packet.
1064 ScopedPacketBundler
ack_bundler(this, BUNDLE_PENDING_ACK
);
1065 packet_generator_
.AddControlFrame(QuicFrame(new QuicRstStreamFrame(
1066 id
, AdjustErrorForVersion(error
, version()), bytes_written
)));
1069 void QuicConnection::SendWindowUpdate(QuicStreamId id
,
1070 QuicStreamOffset byte_offset
) {
1071 // Opportunistically bundle an ack with this outgoing packet.
1072 ScopedPacketBundler
ack_bundler(this, BUNDLE_PENDING_ACK
);
1073 packet_generator_
.AddControlFrame(
1074 QuicFrame(new QuicWindowUpdateFrame(id
, byte_offset
)));
1077 void QuicConnection::SendBlocked(QuicStreamId id
) {
1078 // Opportunistically bundle an ack with this outgoing packet.
1079 ScopedPacketBundler
ack_bundler(this, BUNDLE_PENDING_ACK
);
1080 packet_generator_
.AddControlFrame(QuicFrame(new QuicBlockedFrame(id
)));
1083 const QuicConnectionStats
& QuicConnection::GetStats() {
1084 // Update rtt and estimated bandwidth.
1086 sent_packet_manager_
.GetRttStats()->min_rtt().ToMicroseconds();
1088 sent_packet_manager_
.GetRttStats()->SmoothedRtt().ToMicroseconds();
1089 stats_
.estimated_bandwidth
=
1090 sent_packet_manager_
.BandwidthEstimate().ToBytesPerSecond();
1091 stats_
.congestion_window
= sent_packet_manager_
.GetCongestionWindow();
1092 stats_
.max_packet_size
= options()->max_packet_length
;
1096 void QuicConnection::ProcessUdpPacket(const IPEndPoint
& self_address
,
1097 const IPEndPoint
& peer_address
,
1098 const QuicEncryptedPacket
& packet
) {
1102 if (debug_visitor_
) {
1103 debug_visitor_
->OnPacketReceived(self_address
, peer_address
, packet
);
1105 last_packet_revived_
= false;
1106 last_size_
= packet
.length();
1108 address_migrating_
= false;
1110 if (peer_address_
.address().empty()) {
1111 peer_address_
= peer_address
;
1113 if (self_address_
.address().empty()) {
1114 self_address_
= self_address
;
1117 if (!(peer_address
== peer_address_
&& self_address
== self_address_
)) {
1118 address_migrating_
= true;
1121 stats_
.bytes_received
+= packet
.length();
1122 ++stats_
.packets_received
;
1124 if (!framer_
.ProcessPacket(packet
)) {
1125 // If we are unable to decrypt this packet, it might be
1126 // because the CHLO or SHLO packet was lost.
1127 if (encryption_level_
!= ENCRYPTION_FORWARD_SECURE
&&
1128 framer_
.error() == QUIC_DECRYPTION_FAILURE
&&
1129 undecryptable_packets_
.size() < kMaxUndecryptablePackets
) {
1130 QueueUndecryptablePacket(packet
);
1132 DVLOG(1) << ENDPOINT
<< "Unable to process packet. Last packet processed: "
1133 << last_header_
.packet_sequence_number
;
1137 ++stats_
.packets_processed
;
1138 MaybeProcessUndecryptablePackets();
1139 MaybeProcessRevivedPacket();
1140 MaybeSendInResponseToPacket();
1144 void QuicConnection::OnCanWrite() {
1145 DCHECK(!writer_
->IsWriteBlocked());
1147 WriteQueuedPackets();
1148 WritePendingRetransmissions();
1150 IsHandshake pending_handshake
= visitor_
->HasPendingHandshake() ?
1151 IS_HANDSHAKE
: NOT_HANDSHAKE
;
1152 // Sending queued packets may have caused the socket to become write blocked,
1153 // or the congestion manager to prohibit sending. If we've sent everything
1154 // we had queued and we're still not blocked, let the visitor know it can
1156 if (!CanWrite(NOT_RETRANSMISSION
, HAS_RETRANSMITTABLE_DATA
,
1157 pending_handshake
)) {
1161 { // Limit the scope of the bundler.
1162 // Set |include_ack| to false in bundler; ack inclusion happens elsewhere.
1163 ScopedPacketBundler
bundler(this, NO_ACK
);
1164 visitor_
->OnCanWrite();
1167 // After the visitor writes, it may have caused the socket to become write
1168 // blocked or the congestion manager to prohibit sending, so check again.
1169 pending_handshake
= visitor_
->HasPendingHandshake() ?
1170 IS_HANDSHAKE
: NOT_HANDSHAKE
;
1171 if (visitor_
->HasPendingWrites() && !resume_writes_alarm_
->IsSet() &&
1172 CanWrite(NOT_RETRANSMISSION
, HAS_RETRANSMITTABLE_DATA
,
1173 pending_handshake
)) {
1174 // We're not write blocked, but some stream didn't write out all of its
1175 // bytes. Register for 'immediate' resumption so we'll keep writing after
1176 // other connections and events have had a chance to use the thread.
1177 resume_writes_alarm_
->Set(clock_
->ApproximateNow());
1181 void QuicConnection::WriteIfNotBlocked() {
1182 if (!writer_
->IsWriteBlocked()) {
1187 bool QuicConnection::ProcessValidatedPacket() {
1188 if (address_migrating_
) {
1189 SendConnectionCloseWithDetails(
1190 QUIC_ERROR_MIGRATING_ADDRESS
,
1191 "Address migration is not yet a supported feature");
1194 time_of_last_received_packet_
= clock_
->Now();
1195 DVLOG(1) << ENDPOINT
<< "time of last received packet: "
1196 << time_of_last_received_packet_
.ToDebuggingValue();
1198 if (is_server_
&& encryption_level_
== ENCRYPTION_NONE
&&
1199 last_size_
> options()->max_packet_length
) {
1200 options()->max_packet_length
= last_size_
;
1205 void QuicConnection::WriteQueuedPackets() {
1206 DCHECK(!writer_
->IsWriteBlocked());
1208 if (pending_version_negotiation_packet_
) {
1209 SendVersionNegotiationPacket();
1212 QueuedPacketList::iterator packet_iterator
= queued_packets_
.begin();
1213 while (!writer_
->IsWriteBlocked() &&
1214 packet_iterator
!= queued_packets_
.end()) {
1215 if (WritePacket(*packet_iterator
)) {
1216 delete packet_iterator
->packet
;
1217 packet_iterator
= queued_packets_
.erase(packet_iterator
);
1219 // Continue, because some queued packets may still be writable.
1220 // This can happen if a retransmit send fails.
1226 void QuicConnection::WritePendingRetransmissions() {
1227 // Keep writing as long as there's a pending retransmission which can be
1229 while (sent_packet_manager_
.HasPendingRetransmissions()) {
1230 const QuicSentPacketManager::PendingRetransmission pending
=
1231 sent_packet_manager_
.NextPendingRetransmission();
1232 if (GetPacketType(&pending
.retransmittable_frames
) == NORMAL
&&
1233 !CanWrite(pending
.transmission_type
, HAS_RETRANSMITTABLE_DATA
,
1234 pending
.retransmittable_frames
.HasCryptoHandshake())) {
1238 // Re-packetize the frames with a new sequence number for retransmission.
1239 // Retransmitted data packets do not use FEC, even when it's enabled.
1240 // Retransmitted packets use the same sequence number length as the
1242 // Flush the packet creator before making a new packet.
1243 // TODO(ianswett): Implement ReserializeAllFrames as a separate path that
1244 // does not require the creator to be flushed.
1246 SerializedPacket serialized_packet
= packet_creator_
.ReserializeAllFrames(
1247 pending
.retransmittable_frames
.frames(),
1248 pending
.sequence_number_length
);
1250 DVLOG(1) << ENDPOINT
<< "Retransmitting " << pending
.sequence_number
1251 << " as " << serialized_packet
.sequence_number
;
1252 if (debug_visitor_
) {
1253 debug_visitor_
->OnPacketRetransmitted(
1254 pending
.sequence_number
, serialized_packet
.sequence_number
);
1256 sent_packet_manager_
.OnRetransmittedPacket(
1257 pending
.sequence_number
, serialized_packet
.sequence_number
);
1259 SendOrQueuePacket(pending
.retransmittable_frames
.encryption_level(),
1261 pending
.transmission_type
);
1265 void QuicConnection::RetransmitUnackedPackets(
1266 RetransmissionType retransmission_type
) {
1267 sent_packet_manager_
.RetransmitUnackedPackets(retransmission_type
);
1269 WriteIfNotBlocked();
1272 void QuicConnection::NeuterUnencryptedPackets() {
1273 sent_packet_manager_
.NeuterUnencryptedPackets();
1274 // This may have changed the retransmission timer, so re-arm it.
1275 retransmission_alarm_
->Cancel();
1276 QuicTime retransmission_time
= sent_packet_manager_
.GetRetransmissionTime();
1277 if (retransmission_time
!= QuicTime::Zero()) {
1278 retransmission_alarm_
->Set(retransmission_time
);
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(transmission_type
, retransmittable
, handshake
);
1295 bool QuicConnection::CanWrite(TransmissionType transmission_type
,
1296 HasRetransmittableData retransmittable
,
1297 IsHandshake handshake
) {
1298 if (writer_
->IsWriteBlocked()) {
1299 visitor_
->OnWriteBlocked();
1303 // TODO(rch): consider removing this check so that if an ACK comes in
1304 // before the alarm goes it, we might be able send out a packet.
1305 // This check assumes that if the send alarm is set, it applies equally to all
1306 // types of transmissions.
1307 if (send_alarm_
->IsSet()) {
1308 DVLOG(1) << "Send alarm set. Not sending.";
1312 QuicTime now
= clock_
->Now();
1313 QuicTime::Delta delay
= sent_packet_manager_
.TimeUntilSend(
1314 now
, transmission_type
, retransmittable
);
1315 if (delay
.IsInfinite()) {
1319 // If the scheduler requires a delay, then we can not send this packet now.
1320 if (!delay
.IsZero()) {
1321 send_alarm_
->Cancel();
1322 send_alarm_
->Set(now
.Add(delay
));
1323 DVLOG(1) << "Delaying sending.";
1329 bool QuicConnection::WritePacket(QueuedPacket packet
) {
1330 QuicPacketSequenceNumber sequence_number
= packet
.sequence_number
;
1331 if (ShouldDiscardPacket(packet
.encryption_level
,
1333 packet
.retransmittable
)) {
1334 ++stats_
.packets_discarded
;
1338 // If the packet is CONNECTION_CLOSE, we need to try to send it immediately
1339 // and encrypt it to hand it off to TimeWaitListManager.
1340 // If the packet is QUEUED, we don't re-consult the congestion control.
1341 // This ensures packets are sent in sequence number order.
1342 // TODO(ianswett): The congestion control should have been consulted before
1343 // serializing the packet, so this could be turned into a LOG_IF(DFATAL).
1344 if (packet
.type
== NORMAL
&& !CanWrite(packet
.transmission_type
,
1345 packet
.retransmittable
,
1346 packet
.handshake
)) {
1350 // Some encryption algorithms require the packet sequence numbers not be
1352 DCHECK_LE(sequence_number_of_last_sent_packet_
, sequence_number
);
1353 sequence_number_of_last_sent_packet_
= sequence_number
;
1355 QuicEncryptedPacket
* encrypted
= framer_
.EncryptPacket(
1356 packet
.encryption_level
, sequence_number
, *packet
.packet
);
1357 if (encrypted
== NULL
) {
1358 LOG(DFATAL
) << ENDPOINT
<< "Failed to encrypt packet number "
1360 // CloseConnection does not send close packet, so no infinite loop here.
1361 CloseConnection(QUIC_ENCRYPTION_FAILURE
, false);
1365 // Connection close packets are eventually owned by TimeWaitListManager.
1366 // Others are deleted at the end of this call.
1367 scoped_ptr
<QuicEncryptedPacket
> encrypted_deleter
;
1368 if (packet
.type
== CONNECTION_CLOSE
) {
1369 DCHECK(connection_close_packet_
.get() == NULL
);
1370 connection_close_packet_
.reset(encrypted
);
1371 // This assures we won't try to write *forced* packets when blocked.
1372 // Return true to stop processing.
1373 if (writer_
->IsWriteBlocked()) {
1374 visitor_
->OnWriteBlocked();
1378 encrypted_deleter
.reset(encrypted
);
1381 LOG_IF(DFATAL
, encrypted
->length() > options()->max_packet_length
)
1382 << "Writing an encrypted packet larger than max_packet_length:"
1383 << options()->max_packet_length
<< " encrypted length: "
1384 << encrypted
->length();
1385 DVLOG(1) << ENDPOINT
<< "Sending packet " << sequence_number
1386 << " : " << (packet
.packet
->is_fec_packet() ? "FEC " :
1387 (packet
.retransmittable
== HAS_RETRANSMITTABLE_DATA
1388 ? "data bearing " : " ack only "))
1389 << ", encryption level: "
1390 << QuicUtils::EncryptionLevelToString(packet
.encryption_level
)
1391 << ", length:" << packet
.packet
->length() << ", encrypted length:"
1392 << encrypted
->length();
1393 DVLOG(2) << ENDPOINT
<< "packet(" << sequence_number
<< "): " << std::endl
1394 << QuicUtils::StringToHexASCIIDump(packet
.packet
->AsStringPiece());
1396 DCHECK(encrypted
->length() <= kMaxPacketSize
||
1397 FLAGS_quic_allow_oversized_packets_for_test
)
1398 << "Packet " << sequence_number
<< " will not be read; too large: "
1399 << packet
.packet
->length() << " " << encrypted
->length() << " "
1400 << " close: " << (packet
.type
== CONNECTION_CLOSE
? "yes" : "no");
1402 DCHECK(pending_write_
.get() == NULL
);
1403 pending_write_
.reset(new QueuedPacket(packet
));
1405 WriteResult result
= writer_
->WritePacket(encrypted
->data(),
1406 encrypted
->length(),
1407 self_address().address(),
1409 if (result
.error_code
== ERR_IO_PENDING
) {
1410 DCHECK_EQ(WRITE_STATUS_BLOCKED
, result
.status
);
1412 if (debug_visitor_
) {
1413 // Pass the write result to the visitor.
1414 debug_visitor_
->OnPacketSent(sequence_number
,
1415 packet
.encryption_level
,
1416 packet
.transmission_type
,
1420 if (result
.status
== WRITE_STATUS_BLOCKED
) {
1421 visitor_
->OnWriteBlocked();
1422 // If the socket buffers the the data, then the packet should not
1423 // be queued and sent again, which would result in an unnecessary
1424 // duplicate packet being sent. The helper must call OnPacketSent
1425 // when the packet is actually sent.
1426 if (writer_
->IsWriteBlockedDataBuffered()) {
1429 pending_write_
.reset();
1433 if (OnPacketSent(result
)) {
1439 bool QuicConnection::ShouldDiscardPacket(
1440 EncryptionLevel level
,
1441 QuicPacketSequenceNumber sequence_number
,
1442 HasRetransmittableData retransmittable
) {
1444 DVLOG(1) << ENDPOINT
1445 << "Not sending packet as connection is disconnected.";
1449 if (encryption_level_
== ENCRYPTION_FORWARD_SECURE
&&
1450 level
== ENCRYPTION_NONE
) {
1451 // Drop packets that are NULL encrypted since the peer won't accept them
1453 DVLOG(1) << ENDPOINT
<< "Dropping packet: " << sequence_number
1454 << " since the packet is NULL encrypted.";
1455 sent_packet_manager_
.DiscardUnackedPacket(sequence_number
);
1459 // If the packet has been discarded before sending, don't send it.
1460 // This occurs if a packet gets serialized, queued, then discarded.
1461 if (!sent_packet_manager_
.IsUnacked(sequence_number
)) {
1462 DVLOG(1) << ENDPOINT
<< "Dropping packet before sending: "
1463 << sequence_number
<< " since it has already been discarded.";
1467 if (retransmittable
== HAS_RETRANSMITTABLE_DATA
&&
1468 !sent_packet_manager_
.HasRetransmittableFrames(sequence_number
)) {
1469 DVLOG(1) << ENDPOINT
<< "Dropping packet: " << sequence_number
1470 << " since a previous transmission has been acked.";
1471 sent_packet_manager_
.DiscardUnackedPacket(sequence_number
);
1478 bool QuicConnection::OnPacketSent(WriteResult result
) {
1479 DCHECK_NE(WRITE_STATUS_BLOCKED
, result
.status
);
1480 if (pending_write_
.get() == NULL
) {
1481 LOG(DFATAL
) << "OnPacketSent called without a pending write.";
1485 QuicPacketSequenceNumber sequence_number
= pending_write_
->sequence_number
;
1486 TransmissionType transmission_type
= pending_write_
->transmission_type
;
1487 HasRetransmittableData retransmittable
= pending_write_
->retransmittable
;
1488 size_t length
= pending_write_
->length
;
1489 pending_write_
.reset();
1491 if (result
.status
== WRITE_STATUS_ERROR
) {
1492 DVLOG(1) << "Write failed with error: " << result
.error_code
<< " ("
1493 << ErrorToString(result
.error_code
) << ")";
1494 // We can't send an error as the socket is presumably borked.
1495 CloseConnection(QUIC_PACKET_WRITE_ERROR
, false);
1499 QuicTime now
= clock_
->Now();
1500 if (transmission_type
== NOT_RETRANSMISSION
) {
1501 time_of_last_sent_new_packet_
= now
;
1504 DVLOG(1) << ENDPOINT
<< "time of last sent packet: "
1505 << now
.ToDebuggingValue();
1507 // TODO(ianswett): Change the sequence number length and other packet creator
1508 // options by a more explicit API than setting a struct value directly.
1509 packet_creator_
.UpdateSequenceNumberLength(
1510 received_packet_manager_
.least_packet_awaited_by_peer(),
1511 sent_packet_manager_
.GetCongestionWindow());
1513 bool reset_retransmission_alarm
=
1514 sent_packet_manager_
.OnPacketSent(sequence_number
, now
, length
,
1515 transmission_type
, retransmittable
);
1517 if (reset_retransmission_alarm
|| !retransmission_alarm_
->IsSet()) {
1518 retransmission_alarm_
->Cancel();
1519 QuicTime retransmission_time
= sent_packet_manager_
.GetRetransmissionTime();
1520 if (retransmission_time
!= QuicTime::Zero()) {
1521 retransmission_alarm_
->Set(retransmission_time
);
1525 stats_
.bytes_sent
+= result
.bytes_written
;
1526 ++stats_
.packets_sent
;
1528 if (transmission_type
!= NOT_RETRANSMISSION
) {
1529 stats_
.bytes_retransmitted
+= result
.bytes_written
;
1530 ++stats_
.packets_retransmitted
;
1536 bool QuicConnection::OnSerializedPacket(
1537 const SerializedPacket
& serialized_packet
) {
1538 if (serialized_packet
.retransmittable_frames
) {
1539 serialized_packet
.retransmittable_frames
->
1540 set_encryption_level(encryption_level_
);
1542 sent_packet_manager_
.OnSerializedPacket(serialized_packet
);
1543 // The TransmissionType is NOT_RETRANSMISSION because all retransmissions
1544 // serialize packets and invoke SendOrQueuePacket directly.
1545 return SendOrQueuePacket(encryption_level_
,
1547 NOT_RETRANSMISSION
);
1550 bool QuicConnection::SendOrQueuePacket(EncryptionLevel level
,
1551 const SerializedPacket
& packet
,
1552 TransmissionType transmission_type
) {
1553 if (packet
.packet
== NULL
) {
1554 LOG(DFATAL
) << "NULL packet passed in to SendOrQueuePacket";
1558 sent_entropy_manager_
.RecordPacketEntropyHash(packet
.sequence_number
,
1559 packet
.entropy_hash
);
1560 QueuedPacket
queued_packet(packet
, level
, transmission_type
);
1561 // If there are already queued packets, put this at the end,
1562 // unless it's ConnectionClose, in which case it is written immediately.
1563 if ((queued_packet
.type
== CONNECTION_CLOSE
|| queued_packets_
.empty()) &&
1564 WritePacket(queued_packet
)) {
1565 delete packet
.packet
;
1568 queued_packet
.type
= QUEUED
;
1569 queued_packets_
.push_back(queued_packet
);
1573 void QuicConnection::UpdateStopWaiting(QuicStopWaitingFrame
* stop_waiting
) {
1574 stop_waiting
->least_unacked
= GetLeastUnacked();
1575 stop_waiting
->entropy_hash
= sent_entropy_manager_
.EntropyHash(
1576 stop_waiting
->least_unacked
- 1);
1579 void QuicConnection::SendPing() {
1580 if (retransmission_alarm_
->IsSet()) {
1583 if (version() <= QUIC_VERSION_17
) {
1584 // TODO(rch): remove this when we remove version 17.
1585 // This is a horrible hideous hack which we should not support.
1587 char c_data
[] = "C";
1588 data
.Append(c_data
, 1);
1589 QuicConsumedData consumed_data
=
1590 packet_generator_
.ConsumeData(kCryptoStreamId
, data
, 0, false, NULL
);
1591 if (consumed_data
.bytes_consumed
== 0) {
1592 DLOG(ERROR
) << "Unable to send ping!?";
1595 packet_generator_
.AddControlFrame(QuicFrame(new QuicPingFrame
));
1599 void QuicConnection::SendAck() {
1600 ack_alarm_
->Cancel();
1601 stop_waiting_count_
= 0;
1602 // TODO(rch): delay this until the CreateFeedbackFrame
1603 // method is invoked. This requires changes SetShouldSendAck
1604 // to be a no-arg method, and re-jiggering its implementation.
1605 bool send_feedback
= false;
1606 if (received_packet_manager_
.GenerateCongestionFeedback(
1607 &outgoing_congestion_feedback_
)) {
1608 DVLOG(1) << ENDPOINT
<< "Sending feedback: "
1609 << outgoing_congestion_feedback_
;
1610 send_feedback
= true;
1613 packet_generator_
.SetShouldSendAck(send_feedback
,
1614 version() > QUIC_VERSION_15
);
1617 void QuicConnection::OnRetransmissionTimeout() {
1618 if (!sent_packet_manager_
.HasUnackedPackets()) {
1622 sent_packet_manager_
.OnRetransmissionTimeout();
1624 WriteIfNotBlocked();
1626 // Ensure the retransmission alarm is always set if there are unacked packets.
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_creator_
.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
));
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 void QuicConnection::Flush() {
1838 packet_generator_
.FlushAllQueuedFrames();
1841 bool QuicConnection::HasQueuedData() const {
1842 return pending_version_negotiation_packet_
||
1843 !queued_packets_
.empty() || packet_generator_
.HasQueuedFrames();
1846 bool QuicConnection::CanWriteStreamData() {
1847 // Don't write stream data if there are negotiation or queued data packets
1848 // to send. Otherwise, continue and bundle as many frames as possible.
1849 if (pending_version_negotiation_packet_
|| !queued_packets_
.empty()) {
1853 IsHandshake pending_handshake
= visitor_
->HasPendingHandshake() ?
1854 IS_HANDSHAKE
: NOT_HANDSHAKE
;
1855 // Sending queued packets may have caused the socket to become write blocked,
1856 // or the congestion manager to prohibit sending. If we've sent everything
1857 // we had queued and we're still not blocked, let the visitor know it can
1859 return ShouldGeneratePacket(NOT_RETRANSMISSION
, HAS_RETRANSMITTABLE_DATA
,
1863 void QuicConnection::SetIdleNetworkTimeout(QuicTime::Delta timeout
) {
1864 if (timeout
< idle_network_timeout_
) {
1865 idle_network_timeout_
= timeout
;
1868 idle_network_timeout_
= timeout
;
1872 void QuicConnection::SetOverallConnectionTimeout(QuicTime::Delta timeout
) {
1873 if (timeout
< overall_connection_timeout_
) {
1874 overall_connection_timeout_
= timeout
;
1877 overall_connection_timeout_
= timeout
;
1881 bool QuicConnection::CheckForTimeout() {
1882 QuicTime now
= clock_
->ApproximateNow();
1883 QuicTime time_of_last_packet
= max(time_of_last_received_packet_
,
1884 time_of_last_sent_new_packet_
);
1886 // |delta| can be < 0 as |now| is approximate time but |time_of_last_packet|
1887 // is accurate time. However, this should not change the behavior of
1888 // timeout handling.
1889 QuicTime::Delta delta
= now
.Subtract(time_of_last_packet
);
1890 DVLOG(1) << ENDPOINT
<< "last packet "
1891 << time_of_last_packet
.ToDebuggingValue()
1892 << " now:" << now
.ToDebuggingValue()
1893 << " delta:" << delta
.ToMicroseconds()
1894 << " network_timeout: " << idle_network_timeout_
.ToMicroseconds();
1895 if (delta
>= idle_network_timeout_
) {
1896 DVLOG(1) << ENDPOINT
<< "Connection timedout due to no network activity.";
1897 SendConnectionClose(QUIC_CONNECTION_TIMED_OUT
);
1901 // Next timeout delta.
1902 QuicTime::Delta timeout
= idle_network_timeout_
.Subtract(delta
);
1904 if (!overall_connection_timeout_
.IsInfinite()) {
1905 QuicTime::Delta connected_time
=
1906 now
.Subtract(stats_
.connection_creation_time
);
1907 DVLOG(1) << ENDPOINT
<< "connection time: "
1908 << connected_time
.ToMilliseconds() << " overall timeout: "
1909 << overall_connection_timeout_
.ToMilliseconds();
1910 if (connected_time
>= overall_connection_timeout_
) {
1911 DVLOG(1) << ENDPOINT
<<
1912 "Connection timedout due to overall connection timeout.";
1913 SendConnectionClose(QUIC_CONNECTION_TIMED_OUT
);
1917 // Take the min timeout.
1918 QuicTime::Delta connection_timeout
=
1919 overall_connection_timeout_
.Subtract(connected_time
);
1920 if (connection_timeout
< timeout
) {
1921 timeout
= connection_timeout
;
1925 timeout_alarm_
->Cancel();
1926 timeout_alarm_
->Set(clock_
->ApproximateNow().Add(timeout
));
1930 void QuicConnection::SetPingAlarm() {
1932 // Only clients send pings.
1935 ping_alarm_
->Cancel();
1936 if (!visitor_
->HasOpenDataStreams()) {
1937 // Don't send a ping unless there are open streams.
1940 QuicTime::Delta ping_timeout
= QuicTime::Delta::FromSeconds(kPingTimeoutSecs
);
1941 ping_alarm_
->Set(clock_
->ApproximateNow().Add(ping_timeout
));
1944 QuicConnection::ScopedPacketBundler::ScopedPacketBundler(
1945 QuicConnection
* connection
,
1946 AckBundling send_ack
)
1947 : connection_(connection
),
1948 already_in_batch_mode_(connection
->packet_generator_
.InBatchMode()) {
1949 // Move generator into batch mode. If caller wants us to include an ack,
1950 // check the delayed-ack timer to see if there's ack info to be sent.
1951 if (!already_in_batch_mode_
) {
1952 DVLOG(1) << "Entering Batch Mode.";
1953 connection_
->packet_generator_
.StartBatchOperations();
1955 // Bundle an ack if the alarm is set or with every second packet if we need to
1956 // raise the peer's least unacked.
1958 connection_
->ack_alarm_
->IsSet() || connection_
->stop_waiting_count_
> 1;
1959 if (send_ack
== SEND_ACK
|| (send_ack
== BUNDLE_PENDING_ACK
&& ack_pending
)) {
1960 DVLOG(1) << "Bundling ack with outgoing packet.";
1961 connection_
->SendAck();
1965 QuicConnection::ScopedPacketBundler::~ScopedPacketBundler() {
1966 // If we changed the generator's batch state, restore original batch state.
1967 if (!already_in_batch_mode_
) {
1968 DVLOG(1) << "Leaving Batch Mode.";
1969 connection_
->packet_generator_
.FinishBatchOperations();
1971 DCHECK_EQ(already_in_batch_mode_
,
1972 connection_
->packet_generator_
.InBatchMode());