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/logging.h"
17 #include "base/stl_util.h"
18 #include "net/base/net_errors.h"
19 #include "net/quic/crypto/quic_decrypter.h"
20 #include "net/quic/crypto/quic_encrypter.h"
21 #include "net/quic/iovector.h"
22 #include "net/quic/quic_bandwidth.h"
23 #include "net/quic/quic_config.h"
24 #include "net/quic/quic_utils.h"
28 using base::StringPiece
;
33 using std::numeric_limits
;
38 extern bool FLAGS_quic_allow_oversized_packets_for_test
;
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_
;
80 // This alarm will be scheduled any time a data-bearing packet is sent out.
81 // When the alarm goes off, the connection checks to see if the oldest packets
82 // have been acked, and retransmit them if they have not.
83 class RetransmissionAlarm
: public QuicAlarm::Delegate
{
85 explicit RetransmissionAlarm(QuicConnection
* connection
)
86 : connection_(connection
) {
89 virtual QuicTime
OnAlarm() OVERRIDE
{
90 connection_
->OnRetransmissionTimeout();
91 return QuicTime::Zero();
95 QuicConnection
* connection_
;
98 // An alarm that is scheduled when the sent scheduler requires a
99 // a delay before sending packets and fires when the packet may be sent.
100 class SendAlarm
: public QuicAlarm::Delegate
{
102 explicit SendAlarm(QuicConnection
* connection
)
103 : connection_(connection
) {
106 virtual QuicTime
OnAlarm() OVERRIDE
{
107 connection_
->WriteIfNotBlocked();
108 // Never reschedule the alarm, since OnCanWrite does that.
109 return QuicTime::Zero();
113 QuicConnection
* connection_
;
116 class TimeoutAlarm
: public QuicAlarm::Delegate
{
118 explicit TimeoutAlarm(QuicConnection
* connection
)
119 : connection_(connection
) {
122 virtual QuicTime
OnAlarm() OVERRIDE
{
123 connection_
->CheckForTimeout();
124 // Never reschedule the alarm, since CheckForTimeout does that.
125 return QuicTime::Zero();
129 QuicConnection
* connection_
;
132 // Indicates if any of the frames are intended to be sent with FORCE.
133 // Returns FORCE when one of the frames is a CONNECTION_CLOSE_FRAME.
134 QuicConnection::Force
HasForcedFrames(
135 const RetransmittableFrames
* retransmittable_frames
) {
136 if (!retransmittable_frames
) {
137 return QuicConnection::NO_FORCE
;
139 for (size_t i
= 0; i
< retransmittable_frames
->frames().size(); ++i
) {
140 if (retransmittable_frames
->frames()[i
].type
== CONNECTION_CLOSE_FRAME
) {
141 return QuicConnection::FORCE
;
144 return QuicConnection::NO_FORCE
;
149 #define ENDPOINT (is_server_ ? "Server: " : " Client: ")
151 QuicConnection::QuicConnection(QuicGuid guid
,
153 QuicConnectionHelperInterface
* helper
,
154 QuicPacketWriter
* writer
,
156 const QuicVersionVector
& supported_versions
)
157 : framer_(supported_versions
,
158 helper
->GetClock()->ApproximateNow(),
162 encryption_level_(ENCRYPTION_NONE
),
163 clock_(helper
->GetClock()),
164 random_generator_(helper
->GetRandomGenerator()),
166 peer_address_(address
),
167 largest_seen_packet_with_ack_(0),
168 pending_version_negotiation_packet_(false),
169 received_packet_manager_(kTCP
),
170 ack_alarm_(helper
->CreateAlarm(new AckAlarm(this))),
171 retransmission_alarm_(helper
->CreateAlarm(new RetransmissionAlarm(this))),
172 send_alarm_(helper
->CreateAlarm(new SendAlarm(this))),
173 resume_writes_alarm_(helper
->CreateAlarm(new SendAlarm(this))),
174 timeout_alarm_(helper
->CreateAlarm(new TimeoutAlarm(this))),
175 debug_visitor_(NULL
),
176 packet_creator_(guid_
, &framer_
, random_generator_
, is_server
),
177 packet_generator_(this, NULL
, &packet_creator_
),
178 idle_network_timeout_(
179 QuicTime::Delta::FromSeconds(kDefaultInitialTimeoutSecs
)),
180 overall_connection_timeout_(QuicTime::Delta::Infinite()),
181 creation_time_(clock_
->ApproximateNow()),
182 time_of_last_received_packet_(clock_
->ApproximateNow()),
183 time_of_last_sent_new_packet_(clock_
->ApproximateNow()),
184 sequence_number_of_last_inorder_packet_(0),
185 sent_packet_manager_(is_server
, this, clock_
, kTCP
),
186 version_negotiation_state_(START_NEGOTIATION
),
187 is_server_(is_server
),
189 address_migrating_(false) {
191 // Pacing will be enabled if the client negotiates it.
192 sent_packet_manager_
.MaybeEnablePacing();
194 DVLOG(1) << ENDPOINT
<< "Created connection with guid: " << guid
;
195 timeout_alarm_
->Set(clock_
->ApproximateNow().Add(idle_network_timeout_
));
196 framer_
.set_visitor(this);
197 framer_
.set_received_entropy_calculator(&received_packet_manager_
);
200 QuicConnection::~QuicConnection() {
201 STLDeleteElements(&undecryptable_packets_
);
202 STLDeleteValues(&group_map_
);
203 for (QueuedPacketList::iterator it
= queued_packets_
.begin();
204 it
!= queued_packets_
.end(); ++it
) {
209 void QuicConnection::SetFromConfig(const QuicConfig
& config
) {
210 DCHECK_LT(0u, config
.server_initial_congestion_window());
211 SetIdleNetworkTimeout(config
.idle_connection_state_lifetime());
212 sent_packet_manager_
.SetFromConfig(config
);
213 // TODO(satyamshekhar): Set congestion control and ICSL also.
216 bool QuicConnection::SelectMutualVersion(
217 const QuicVersionVector
& available_versions
) {
218 // Try to find the highest mutual version by iterating over supported
219 // versions, starting with the highest, and breaking out of the loop once we
220 // find a matching version in the provided available_versions vector.
221 const QuicVersionVector
& supported_versions
= framer_
.supported_versions();
222 for (size_t i
= 0; i
< supported_versions
.size(); ++i
) {
223 const QuicVersion
& version
= supported_versions
[i
];
224 if (std::find(available_versions
.begin(), available_versions
.end(),
225 version
) != available_versions
.end()) {
226 framer_
.set_version(version
);
234 void QuicConnection::OnError(QuicFramer
* framer
) {
235 // Packets that we cannot decrypt are dropped.
236 // TODO(rch): add stats to measure this.
237 if (!connected_
|| framer
->error() == QUIC_DECRYPTION_FAILURE
) {
240 SendConnectionCloseWithDetails(framer
->error(), framer
->detailed_error());
243 void QuicConnection::OnPacket() {
244 DCHECK(last_stream_frames_
.empty() &&
245 last_goaway_frames_
.empty() &&
246 last_rst_frames_
.empty() &&
247 last_ack_frames_
.empty() &&
248 last_congestion_frames_
.empty());
251 void QuicConnection::OnPublicResetPacket(
252 const QuicPublicResetPacket
& packet
) {
253 if (debug_visitor_
) {
254 debug_visitor_
->OnPublicResetPacket(packet
);
256 CloseConnection(QUIC_PUBLIC_RESET
, true);
259 bool QuicConnection::OnProtocolVersionMismatch(QuicVersion received_version
) {
260 DVLOG(1) << ENDPOINT
<< "Received packet with mismatched version "
262 // TODO(satyamshekhar): Implement no server state in this mode.
264 LOG(DFATAL
) << ENDPOINT
<< "Framer called OnProtocolVersionMismatch. "
265 << "Closing connection.";
266 CloseConnection(QUIC_INTERNAL_ERROR
, false);
269 DCHECK_NE(version(), received_version
);
271 if (debug_visitor_
) {
272 debug_visitor_
->OnProtocolVersionMismatch(received_version
);
275 switch (version_negotiation_state_
) {
276 case START_NEGOTIATION
:
277 if (!framer_
.IsSupportedVersion(received_version
)) {
278 SendVersionNegotiationPacket();
279 version_negotiation_state_
= NEGOTIATION_IN_PROGRESS
;
284 case NEGOTIATION_IN_PROGRESS
:
285 if (!framer_
.IsSupportedVersion(received_version
)) {
286 SendVersionNegotiationPacket();
291 case NEGOTIATED_VERSION
:
292 // Might be old packets that were sent by the client before the version
293 // was negotiated. Drop these.
300 version_negotiation_state_
= NEGOTIATED_VERSION
;
301 visitor_
->OnSuccessfulVersionNegotiation(received_version
);
302 DVLOG(1) << ENDPOINT
<< "version negotiated " << received_version
;
304 // Store the new version.
305 framer_
.set_version(received_version
);
307 // TODO(satyamshekhar): Store the sequence number of this packet and close the
308 // connection if we ever received a packet with incorrect version and whose
309 // sequence number is greater.
313 // Handles version negotiation for client connection.
314 void QuicConnection::OnVersionNegotiationPacket(
315 const QuicVersionNegotiationPacket
& packet
) {
317 LOG(DFATAL
) << ENDPOINT
<< "Framer parsed VersionNegotiationPacket."
318 << " Closing connection.";
319 CloseConnection(QUIC_INTERNAL_ERROR
, false);
322 if (debug_visitor_
) {
323 debug_visitor_
->OnVersionNegotiationPacket(packet
);
326 if (version_negotiation_state_
!= START_NEGOTIATION
) {
327 // Possibly a duplicate version negotiation packet.
331 if (std::find(packet
.versions
.begin(),
332 packet
.versions
.end(), version()) !=
333 packet
.versions
.end()) {
334 DLOG(WARNING
) << ENDPOINT
<< "The server already supports our version. "
335 << "It should have accepted our connection.";
336 // Just drop the connection.
337 CloseConnection(QUIC_INVALID_VERSION_NEGOTIATION_PACKET
, false);
341 if (!SelectMutualVersion(packet
.versions
)) {
342 SendConnectionCloseWithDetails(QUIC_INVALID_VERSION
,
343 "no common version found");
347 DVLOG(1) << ENDPOINT
<< "negotiating version " << version();
348 server_supported_versions_
= packet
.versions
;
349 version_negotiation_state_
= NEGOTIATION_IN_PROGRESS
;
350 RetransmitUnackedPackets(ALL_PACKETS
);
353 void QuicConnection::OnRevivedPacket() {
356 bool QuicConnection::OnUnauthenticatedPublicHeader(
357 const QuicPacketPublicHeader
& header
) {
361 bool QuicConnection::OnUnauthenticatedHeader(const QuicPacketHeader
& header
) {
365 bool QuicConnection::OnPacketHeader(const QuicPacketHeader
& header
) {
366 if (debug_visitor_
) {
367 debug_visitor_
->OnPacketHeader(header
);
370 if (!ProcessValidatedPacket()) {
374 // Will be decrement below if we fall through to return true;
375 ++stats_
.packets_dropped
;
377 if (header
.public_header
.guid
!= guid_
) {
378 DVLOG(1) << ENDPOINT
<< "Ignoring packet from unexpected GUID: "
379 << header
.public_header
.guid
<< " instead of " << guid_
;
383 if (!Near(header
.packet_sequence_number
,
384 last_header_
.packet_sequence_number
)) {
385 DVLOG(1) << ENDPOINT
<< "Packet " << header
.packet_sequence_number
386 << " out of bounds. Discarding";
387 SendConnectionCloseWithDetails(QUIC_INVALID_PACKET_HEADER
,
388 "Packet sequence number out of bounds");
392 // If this packet has already been seen, or that the sender
393 // has told us will not be retransmitted, then stop processing the packet.
394 if (!received_packet_manager_
.IsAwaitingPacket(
395 header
.packet_sequence_number
)) {
399 if (version_negotiation_state_
!= NEGOTIATED_VERSION
) {
401 if (!header
.public_header
.version_flag
) {
402 DLOG(WARNING
) << ENDPOINT
<< "Got packet without version flag before "
403 << "version negotiated.";
404 // Packets should have the version flag till version negotiation is
406 CloseConnection(QUIC_INVALID_VERSION
, false);
409 DCHECK_EQ(1u, header
.public_header
.versions
.size());
410 DCHECK_EQ(header
.public_header
.versions
[0], version());
411 version_negotiation_state_
= NEGOTIATED_VERSION
;
412 visitor_
->OnSuccessfulVersionNegotiation(version());
415 DCHECK(!header
.public_header
.version_flag
);
416 // If the client gets a packet without the version flag from the server
417 // it should stop sending version since the version negotiation is done.
418 packet_creator_
.StopSendingVersion();
419 version_negotiation_state_
= NEGOTIATED_VERSION
;
420 visitor_
->OnSuccessfulVersionNegotiation(version());
424 DCHECK_EQ(NEGOTIATED_VERSION
, version_negotiation_state_
);
426 --stats_
.packets_dropped
;
427 DVLOG(1) << ENDPOINT
<< "Received packet header: " << header
;
428 last_header_
= header
;
433 void QuicConnection::OnFecProtectedPayload(StringPiece payload
) {
434 DCHECK_EQ(IN_FEC_GROUP
, last_header_
.is_in_fec_group
);
435 DCHECK_NE(0u, last_header_
.fec_group
);
436 QuicFecGroup
* group
= GetFecGroup();
438 group
->Update(last_header_
, payload
);
442 bool QuicConnection::OnStreamFrame(const QuicStreamFrame
& frame
) {
444 if (debug_visitor_
) {
445 debug_visitor_
->OnStreamFrame(frame
);
447 last_stream_frames_
.push_back(frame
);
451 bool QuicConnection::OnAckFrame(const QuicAckFrame
& incoming_ack
) {
453 if (debug_visitor_
) {
454 debug_visitor_
->OnAckFrame(incoming_ack
);
456 DVLOG(1) << ENDPOINT
<< "OnAckFrame: " << incoming_ack
;
458 if (last_header_
.packet_sequence_number
<= largest_seen_packet_with_ack_
) {
459 DVLOG(1) << ENDPOINT
<< "Received an old ack frame: ignoring";
463 if (!ValidateAckFrame(incoming_ack
)) {
464 SendConnectionClose(QUIC_INVALID_ACK_DATA
);
468 last_ack_frames_
.push_back(incoming_ack
);
472 void QuicConnection::ProcessAckFrame(const QuicAckFrame
& incoming_ack
) {
473 largest_seen_packet_with_ack_
= last_header_
.packet_sequence_number
;
475 received_packet_manager_
.UpdatePacketInformationReceivedByPeer(incoming_ack
);
476 received_packet_manager_
.UpdatePacketInformationSentByPeer(incoming_ack
);
477 // Possibly close any FecGroups which are now irrelevant.
478 CloseFecGroupsBefore(incoming_ack
.sent_info
.least_unacked
+ 1);
480 sent_entropy_manager_
.ClearEntropyBefore(
481 received_packet_manager_
.least_packet_awaited_by_peer() - 1);
483 bool reset_retransmission_alarm
=
484 sent_packet_manager_
.OnIncomingAck(incoming_ack
.received_info
,
485 time_of_last_received_packet_
);
486 if (sent_packet_manager_
.HasPendingRetransmissions()) {
490 if (reset_retransmission_alarm
) {
491 retransmission_alarm_
->Cancel();
492 QuicTime retransmission_time
=
493 sent_packet_manager_
.GetRetransmissionTime();
494 if (retransmission_time
!= QuicTime::Zero()) {
495 retransmission_alarm_
->Set(retransmission_time
);
500 bool QuicConnection::OnCongestionFeedbackFrame(
501 const QuicCongestionFeedbackFrame
& feedback
) {
503 if (debug_visitor_
) {
504 debug_visitor_
->OnCongestionFeedbackFrame(feedback
);
506 last_congestion_frames_
.push_back(feedback
);
510 bool QuicConnection::ValidateAckFrame(const QuicAckFrame
& incoming_ack
) {
511 if (incoming_ack
.received_info
.largest_observed
>
512 packet_creator_
.sequence_number()) {
513 DLOG(ERROR
) << ENDPOINT
<< "Peer's observed unsent packet:"
514 << incoming_ack
.received_info
.largest_observed
<< " vs "
515 << packet_creator_
.sequence_number();
516 // We got an error for data we have not sent. Error out.
520 if (incoming_ack
.received_info
.largest_observed
<
521 received_packet_manager_
.peer_largest_observed_packet()) {
522 DLOG(ERROR
) << ENDPOINT
<< "Peer's largest_observed packet decreased:"
523 << incoming_ack
.received_info
.largest_observed
<< " vs "
524 << received_packet_manager_
.peer_largest_observed_packet();
525 // A new ack has a diminished largest_observed value. Error out.
526 // If this was an old packet, we wouldn't even have checked.
530 if (incoming_ack
.sent_info
.least_unacked
<
531 received_packet_manager_
.peer_least_packet_awaiting_ack()) {
532 DLOG(ERROR
) << ENDPOINT
<< "Peer's sent low least_unacked: "
533 << incoming_ack
.sent_info
.least_unacked
<< " vs "
534 << received_packet_manager_
.peer_least_packet_awaiting_ack();
535 // We never process old ack frames, so this number should only increase.
539 if (incoming_ack
.sent_info
.least_unacked
>
540 last_header_
.packet_sequence_number
) {
541 DLOG(ERROR
) << ENDPOINT
<< "Peer sent least_unacked:"
542 << incoming_ack
.sent_info
.least_unacked
543 << " greater than the enclosing packet sequence number:"
544 << last_header_
.packet_sequence_number
;
548 if (!incoming_ack
.received_info
.missing_packets
.empty() &&
549 *incoming_ack
.received_info
.missing_packets
.rbegin() >
550 incoming_ack
.received_info
.largest_observed
) {
551 DLOG(ERROR
) << ENDPOINT
<< "Peer sent missing packet: "
552 << *incoming_ack
.received_info
.missing_packets
.rbegin()
553 << " which is greater than largest observed: "
554 << incoming_ack
.received_info
.largest_observed
;
558 if (!incoming_ack
.received_info
.missing_packets
.empty() &&
559 *incoming_ack
.received_info
.missing_packets
.begin() <
560 received_packet_manager_
.least_packet_awaited_by_peer()) {
561 DLOG(ERROR
) << ENDPOINT
<< "Peer sent missing packet: "
562 << *incoming_ack
.received_info
.missing_packets
.begin()
563 << " which is smaller than least_packet_awaited_by_peer_: "
564 << received_packet_manager_
.least_packet_awaited_by_peer();
568 if (!sent_entropy_manager_
.IsValidEntropy(
569 incoming_ack
.received_info
.largest_observed
,
570 incoming_ack
.received_info
.missing_packets
,
571 incoming_ack
.received_info
.entropy_hash
)) {
572 DLOG(ERROR
) << ENDPOINT
<< "Peer sent invalid entropy.";
579 void QuicConnection::OnFecData(const QuicFecData
& fec
) {
580 DCHECK_EQ(IN_FEC_GROUP
, last_header_
.is_in_fec_group
);
581 DCHECK_NE(0u, last_header_
.fec_group
);
582 QuicFecGroup
* group
= GetFecGroup();
584 group
->UpdateFec(last_header_
.packet_sequence_number
,
585 last_header_
.entropy_flag
, fec
);
589 bool QuicConnection::OnRstStreamFrame(const QuicRstStreamFrame
& frame
) {
591 if (debug_visitor_
) {
592 debug_visitor_
->OnRstStreamFrame(frame
);
594 DVLOG(1) << ENDPOINT
<< "Stream reset with error "
595 << QuicUtils::StreamErrorToString(frame
.error_code
);
596 last_rst_frames_
.push_back(frame
);
600 bool QuicConnection::OnConnectionCloseFrame(
601 const QuicConnectionCloseFrame
& frame
) {
603 if (debug_visitor_
) {
604 debug_visitor_
->OnConnectionCloseFrame(frame
);
606 DVLOG(1) << ENDPOINT
<< "Connection " << guid() << " closed with error "
607 << QuicUtils::ErrorToString(frame
.error_code
)
608 << " " << frame
.error_details
;
609 last_close_frames_
.push_back(frame
);
613 bool QuicConnection::OnGoAwayFrame(const QuicGoAwayFrame
& frame
) {
615 DVLOG(1) << ENDPOINT
<< "Go away received with error "
616 << QuicUtils::ErrorToString(frame
.error_code
)
617 << " and reason:" << frame
.reason_phrase
;
618 last_goaway_frames_
.push_back(frame
);
622 void QuicConnection::OnPacketComplete() {
623 // Don't do anything if this packet closed the connection.
629 DVLOG(1) << ENDPOINT
<< (last_packet_revived_
? "Revived" : "Got")
630 << " packet " << last_header_
.packet_sequence_number
631 << " with " << last_ack_frames_
.size() << " acks, "
632 << last_congestion_frames_
.size() << " congestions, "
633 << last_goaway_frames_
.size() << " goaways, "
634 << last_rst_frames_
.size() << " rsts, "
635 << last_close_frames_
.size() << " closes, "
636 << last_stream_frames_
.size()
637 << " stream frames for " << last_header_
.public_header
.guid
;
639 // Must called before ack processing, because processing acks removes entries
640 // from unacket_packets_, increasing the least_unacked.
641 const bool last_packet_should_instigate_ack
= ShouldLastPacketInstigateAck();
643 // If the incoming packet was missing, send an ack immediately.
644 bool send_ack_immediately
= received_packet_manager_
.IsMissing(
645 last_header_
.packet_sequence_number
);
647 // Ensure the visitor can process the stream frames before recording and
648 // processing the rest of the packet.
649 if (last_stream_frames_
.empty() ||
650 visitor_
->OnStreamFrames(last_stream_frames_
)) {
651 received_packet_manager_
.RecordPacketReceived(last_size_
,
653 time_of_last_received_packet_
,
654 last_packet_revived_
);
655 for (size_t i
= 0; i
< last_stream_frames_
.size(); ++i
) {
656 stats_
.stream_bytes_received
+=
657 last_stream_frames_
[i
].data
.TotalBufferSize();
661 // Process stream resets, then acks, then congestion feedback.
662 for (size_t i
= 0; i
< last_goaway_frames_
.size(); ++i
) {
663 visitor_
->OnGoAway(last_goaway_frames_
[i
]);
665 for (size_t i
= 0; i
< last_rst_frames_
.size(); ++i
) {
666 visitor_
->OnRstStream(last_rst_frames_
[i
]);
668 for (size_t i
= 0; i
< last_ack_frames_
.size(); ++i
) {
669 ProcessAckFrame(last_ack_frames_
[i
]);
671 for (size_t i
= 0; i
< last_congestion_frames_
.size(); ++i
) {
672 sent_packet_manager_
.OnIncomingQuicCongestionFeedbackFrame(
673 last_congestion_frames_
[i
], time_of_last_received_packet_
);
675 if (!last_close_frames_
.empty()) {
676 CloseConnection(last_close_frames_
[0].error_code
, true);
680 // If there are new missing packets to report, send an ack immediately.
681 if (received_packet_manager_
.HasNewMissingPackets()) {
682 send_ack_immediately
= true;
685 MaybeSendInResponseToPacket(send_ack_immediately
,
686 last_packet_should_instigate_ack
);
691 void QuicConnection::ClearLastFrames() {
692 last_stream_frames_
.clear();
693 last_goaway_frames_
.clear();
694 last_rst_frames_
.clear();
695 last_ack_frames_
.clear();
696 last_congestion_frames_
.clear();
699 QuicAckFrame
* QuicConnection::CreateAckFrame() {
700 QuicAckFrame
* outgoing_ack
= new QuicAckFrame();
701 received_packet_manager_
.UpdateReceivedPacketInfo(
702 &(outgoing_ack
->received_info
), clock_
->ApproximateNow());
703 UpdateSentPacketInfo(&(outgoing_ack
->sent_info
));
704 DVLOG(1) << ENDPOINT
<< "Creating ack frame: " << *outgoing_ack
;
708 QuicCongestionFeedbackFrame
* QuicConnection::CreateFeedbackFrame() {
709 return new QuicCongestionFeedbackFrame(outgoing_congestion_feedback_
);
712 bool QuicConnection::ShouldLastPacketInstigateAck() {
713 if (!last_stream_frames_
.empty() ||
714 !last_goaway_frames_
.empty() ||
715 !last_rst_frames_
.empty()) {
719 // If the peer is still waiting for a packet that we are no
720 // longer planning to send, we should send an ack to raise
721 // the high water mark.
722 if (!last_ack_frames_
.empty() &&
723 !last_ack_frames_
.back().received_info
.missing_packets
.empty()) {
724 return sent_packet_manager_
.GetLeastUnackedSentPacket() >
725 *last_ack_frames_
.back().received_info
.missing_packets
.begin();
730 void QuicConnection::MaybeSendInResponseToPacket(
731 bool send_ack_immediately
,
732 bool last_packet_should_instigate_ack
) {
733 // |include_ack| is false since we decide about ack bundling below.
734 ScopedPacketBundler
bundler(this, false);
736 if (last_packet_should_instigate_ack
) {
737 // In general, we ack every second packet. When we don't ack the first
738 // packet, we set the delayed ack alarm. Thus, if the ack alarm is set
739 // then we know this is the second packet, and we should send an ack.
740 if (send_ack_immediately
|| ack_alarm_
->IsSet()) {
742 DCHECK(!ack_alarm_
->IsSet());
744 ack_alarm_
->Set(clock_
->ApproximateNow().Add(
745 sent_packet_manager_
.DelayedAckTime()));
746 DVLOG(1) << "Ack timer set; next packet or timer will trigger ACK.";
750 if (!last_ack_frames_
.empty()) {
751 // Now the we have received an ack, we might be able to send packets which
752 // are queued locally, or drain streams which are blocked.
753 QuicTime::Delta delay
= sent_packet_manager_
.TimeUntilSend(
754 time_of_last_received_packet_
, NOT_RETRANSMISSION
,
755 HAS_RETRANSMITTABLE_DATA
, NOT_HANDSHAKE
);
756 if (delay
.IsZero()) {
757 send_alarm_
->Cancel();
759 } else if (!delay
.IsInfinite()) {
760 send_alarm_
->Cancel();
761 send_alarm_
->Set(time_of_last_received_packet_
.Add(delay
));
766 void QuicConnection::SendVersionNegotiationPacket() {
767 scoped_ptr
<QuicEncryptedPacket
> version_packet(
768 packet_creator_
.SerializeVersionNegotiationPacket(
769 framer_
.supported_versions()));
770 // TODO(satyamshekhar): implement zero server state negotiation.
772 writer_
->WritePacket(version_packet
->data(), version_packet
->length(),
773 self_address().address(), peer_address(), this);
774 if (result
.status
== WRITE_STATUS_OK
||
775 (result
.status
== WRITE_STATUS_BLOCKED
&&
776 writer_
->IsWriteBlockedDataBuffered())) {
777 pending_version_negotiation_packet_
= false;
780 if (result
.status
== WRITE_STATUS_ERROR
) {
781 // We can't send an error as the socket is presumably borked.
782 CloseConnection(QUIC_PACKET_WRITE_ERROR
, false);
784 pending_version_negotiation_packet_
= true;
787 QuicConsumedData
QuicConnection::SendStreamData(
789 const IOVector
& data
,
790 QuicStreamOffset offset
,
792 QuicAckNotifier::DelegateInterface
* delegate
) {
793 if (!fin
&& data
.Empty()) {
794 LOG(DFATAL
) << "Attempt to send empty stream frame";
797 // This notifier will be owned by the AckNotifierManager (or deleted below if
798 // no data or FIN was consumed).
799 QuicAckNotifier
* notifier
= NULL
;
801 notifier
= new QuicAckNotifier(delegate
);
804 // Opportunistically bundle an ack with this outgoing packet, unless it's the
806 ScopedPacketBundler
ack_bundler(this, id
!= kCryptoStreamId
);
807 QuicConsumedData consumed_data
=
808 packet_generator_
.ConsumeData(id
, data
, offset
, fin
, notifier
);
811 (consumed_data
.bytes_consumed
== 0 && !consumed_data
.fin_consumed
)) {
812 // No data was consumed, nor was a fin consumed, so delete the notifier.
816 return consumed_data
;
819 void QuicConnection::SendRstStream(QuicStreamId id
,
820 QuicRstStreamErrorCode error
) {
821 // Opportunistically bundle an ack with this outgoing packet.
822 ScopedPacketBundler
ack_bundler(this, true);
823 packet_generator_
.AddControlFrame(
824 QuicFrame(new QuicRstStreamFrame(id
, error
)));
827 const QuicConnectionStats
& QuicConnection::GetStats() {
828 // Update rtt and estimated bandwidth.
829 stats_
.rtt
= sent_packet_manager_
.SmoothedRtt().ToMicroseconds();
830 stats_
.estimated_bandwidth
=
831 sent_packet_manager_
.BandwidthEstimate().ToBytesPerSecond();
835 void QuicConnection::ProcessUdpPacket(const IPEndPoint
& self_address
,
836 const IPEndPoint
& peer_address
,
837 const QuicEncryptedPacket
& packet
) {
841 if (debug_visitor_
) {
842 debug_visitor_
->OnPacketReceived(self_address
, peer_address
, packet
);
844 last_packet_revived_
= false;
845 last_size_
= packet
.length();
847 address_migrating_
= false;
849 if (peer_address_
.address().empty()) {
850 peer_address_
= peer_address
;
852 if (self_address_
.address().empty()) {
853 self_address_
= self_address
;
856 if (!(peer_address
== peer_address_
&& self_address
== self_address_
)) {
857 address_migrating_
= true;
860 stats_
.bytes_received
+= packet
.length();
861 ++stats_
.packets_received
;
863 if (!framer_
.ProcessPacket(packet
)) {
864 // If we are unable to decrypt this packet, it might be
865 // because the CHLO or SHLO packet was lost.
866 if (encryption_level_
!= ENCRYPTION_FORWARD_SECURE
&&
867 framer_
.error() == QUIC_DECRYPTION_FAILURE
&&
868 undecryptable_packets_
.size() < kMaxUndecryptablePackets
) {
869 QueueUndecryptablePacket(packet
);
871 DVLOG(1) << ENDPOINT
<< "Unable to process packet. Last packet processed: "
872 << last_header_
.packet_sequence_number
;
875 MaybeProcessUndecryptablePackets();
876 MaybeProcessRevivedPacket();
879 bool QuicConnection::OnCanWrite() {
880 DCHECK(!writer_
->IsWriteBlocked());
882 WriteQueuedPackets();
883 WritePendingRetransmissions();
885 IsHandshake pending_handshake
= visitor_
->HasPendingHandshake() ?
886 IS_HANDSHAKE
: NOT_HANDSHAKE
;
887 // Sending queued packets may have caused the socket to become write blocked,
888 // or the congestion manager to prohibit sending. If we've sent everything
889 // we had queued and we're still not blocked, let the visitor know it can
891 if (CanWrite(NOT_RETRANSMISSION
, HAS_RETRANSMITTABLE_DATA
,
892 pending_handshake
)) {
893 // Set |include_ack| to false in bundler; ack inclusion happens elsewhere.
894 scoped_ptr
<ScopedPacketBundler
> bundler(
895 new ScopedPacketBundler(this, false));
896 bool all_bytes_written
= visitor_
->OnCanWrite();
898 // After the visitor writes, it may have caused the socket to become write
899 // blocked or the congestion manager to prohibit sending, so check again.
900 pending_handshake
= visitor_
->HasPendingHandshake() ? IS_HANDSHAKE
902 if (!all_bytes_written
&& !resume_writes_alarm_
->IsSet() &&
903 CanWrite(NOT_RETRANSMISSION
, HAS_RETRANSMITTABLE_DATA
,
904 pending_handshake
)) {
905 // We're not write blocked, but some stream didn't write out all of its
906 // bytes. Register for 'immediate' resumption so we'll keep writing after
907 // other quic connections have had a chance to use the socket.
908 resume_writes_alarm_
->Set(clock_
->ApproximateNow());
912 return !writer_
->IsWriteBlocked();
915 void QuicConnection::WriteIfNotBlocked() {
916 if (!writer_
->IsWriteBlocked()) {
921 bool QuicConnection::ProcessValidatedPacket() {
922 if (address_migrating_
) {
923 SendConnectionCloseWithDetails(
924 QUIC_ERROR_MIGRATING_ADDRESS
,
925 "Address migration is not yet a supported feature");
928 time_of_last_received_packet_
= clock_
->Now();
929 DVLOG(1) << ENDPOINT
<< "time of last received packet: "
930 << time_of_last_received_packet_
.ToDebuggingValue();
932 if (is_server_
&& encryption_level_
== ENCRYPTION_NONE
&&
933 last_size_
> options()->max_packet_length
) {
934 options()->max_packet_length
= last_size_
;
939 void QuicConnection::WriteQueuedPackets() {
940 DCHECK(!writer_
->IsWriteBlocked());
942 if (pending_version_negotiation_packet_
) {
943 SendVersionNegotiationPacket();
946 QueuedPacketList::iterator packet_iterator
= queued_packets_
.begin();
947 while (!writer_
->IsWriteBlocked() &&
948 packet_iterator
!= queued_packets_
.end()) {
949 if (WritePacket(packet_iterator
->encryption_level
,
950 packet_iterator
->sequence_number
,
951 packet_iterator
->packet
,
952 packet_iterator
->transmission_type
,
953 packet_iterator
->retransmittable
,
954 packet_iterator
->handshake
,
955 packet_iterator
->forced
)) {
956 delete packet_iterator
->packet
;
957 packet_iterator
= queued_packets_
.erase(packet_iterator
);
959 // Continue, because some queued packets may still be writable.
960 // This can happen if a retransmit send fails.
966 void QuicConnection::WritePendingRetransmissions() {
967 // Keep writing as long as there's a pending retransmission which can be
969 while (sent_packet_manager_
.HasPendingRetransmissions()) {
970 const QuicSentPacketManager::PendingRetransmission pending
=
971 sent_packet_manager_
.NextPendingRetransmission();
972 if (HasForcedFrames(&pending
.retransmittable_frames
) == NO_FORCE
&&
973 !CanWrite(pending
.transmission_type
, HAS_RETRANSMITTABLE_DATA
,
974 pending
.retransmittable_frames
.HasCryptoHandshake())) {
978 // Re-packetize the frames with a new sequence number for retransmission.
979 // Retransmitted data packets do not use FEC, even when it's enabled.
980 // Retransmitted packets use the same sequence number length as the
982 // Flush the packet creator before making a new packet.
983 // TODO(ianswett): Implement ReserializeAllFrames as a separate path that
984 // does not require the creator to be flushed.
986 SerializedPacket serialized_packet
= packet_creator_
.ReserializeAllFrames(
987 pending
.retransmittable_frames
.frames(),
988 pending
.sequence_number_length
);
990 DVLOG(1) << ENDPOINT
<< "Retransmitting " << pending
.sequence_number
991 << " as " << serialized_packet
.sequence_number
;
992 if (debug_visitor_
) {
993 debug_visitor_
->OnPacketRetransmitted(
994 pending
.sequence_number
, serialized_packet
.sequence_number
);
996 sent_packet_manager_
.OnRetransmittedPacket(
997 pending
.sequence_number
, serialized_packet
.sequence_number
);
999 SendOrQueuePacket(pending
.retransmittable_frames
.encryption_level(),
1001 pending
.transmission_type
);
1005 void QuicConnection::RetransmitUnackedPackets(
1006 RetransmissionType retransmission_type
) {
1007 sent_packet_manager_
.RetransmitUnackedPackets(retransmission_type
);
1009 WriteIfNotBlocked();
1012 bool QuicConnection::ShouldGeneratePacket(
1013 TransmissionType transmission_type
,
1014 HasRetransmittableData retransmittable
,
1015 IsHandshake handshake
) {
1016 // We should serialize handshake packets immediately to ensure that they
1017 // end up sent at the right encryption level.
1018 if (handshake
== IS_HANDSHAKE
) {
1022 return CanWrite(transmission_type
, retransmittable
, handshake
);
1025 bool QuicConnection::CanWrite(TransmissionType transmission_type
,
1026 HasRetransmittableData retransmittable
,
1027 IsHandshake handshake
) {
1028 if (writer_
->IsWriteBlocked()) {
1032 // TODO(rch): consider removing this check so that if an ACK comes in
1033 // before the alarm goes it, we might be able send out a packet.
1034 // This check assumes that if the send alarm is set, it applies equally to all
1035 // types of transmissions.
1036 if (send_alarm_
->IsSet()) {
1037 DVLOG(1) << "Send alarm set. Not sending.";
1041 QuicTime now
= clock_
->Now();
1042 QuicTime::Delta delay
= sent_packet_manager_
.TimeUntilSend(
1043 now
, transmission_type
, retransmittable
, handshake
);
1044 if (delay
.IsInfinite()) {
1048 // If the scheduler requires a delay, then we can not send this packet now.
1049 if (!delay
.IsZero()) {
1050 send_alarm_
->Cancel();
1051 send_alarm_
->Set(now
.Add(delay
));
1052 DVLOG(1) << "Delaying sending.";
1058 bool QuicConnection::WritePacket(EncryptionLevel level
,
1059 QuicPacketSequenceNumber sequence_number
,
1061 TransmissionType transmission_type
,
1062 HasRetransmittableData retransmittable
,
1063 IsHandshake handshake
,
1065 if (ShouldDiscardPacket(level
, sequence_number
, retransmittable
)) {
1069 // If the writer is blocked, we must not write. However, if the packet is
1070 // forced (i.e., it's the ConnectionClose packet), we still need to encrypt it
1071 // and hand it off to TimeWaitListManager.
1072 // We check nonforced packets here and forced after encryption.
1073 if (forced
== NO_FORCE
&&
1074 !CanWrite(transmission_type
, retransmittable
, handshake
)) {
1078 // Some encryption algorithms require the packet sequence numbers not be
1080 DCHECK_LE(sequence_number_of_last_inorder_packet_
, sequence_number
);
1081 // Only increase this when packets have not been queued. Once they're queued
1082 // due to a write block, there is the chance of sending forced and other
1083 // higher priority packets out of order.
1084 if (queued_packets_
.empty()) {
1085 sequence_number_of_last_inorder_packet_
= sequence_number
;
1088 QuicEncryptedPacket
* encrypted
=
1089 framer_
.EncryptPacket(level
, sequence_number
, *packet
);
1090 if (encrypted
== NULL
) {
1091 LOG(DFATAL
) << ENDPOINT
<< "Failed to encrypt packet number "
1093 // CloseConnection does not send close packet, so no infinite loop here.
1094 CloseConnection(QUIC_ENCRYPTION_FAILURE
, false);
1098 // Forced packets are eventually owned by TimeWaitListManager; nonforced are
1099 // deleted at the end of this call.
1100 scoped_ptr
<QuicEncryptedPacket
> encrypted_deleter
;
1101 if (forced
== NO_FORCE
) {
1102 encrypted_deleter
.reset(encrypted
);
1103 } else { // forced == FORCE
1104 DCHECK(connection_close_packet_
.get() == NULL
);
1105 connection_close_packet_
.reset(encrypted
);
1106 // This assures we won't try to write *forced* packets when blocked.
1107 // Return true to stop processing.
1108 if (writer_
->IsWriteBlocked()) {
1113 if (encrypted
->length() > options()->max_packet_length
) {
1114 LOG(DFATAL
) << "Writing an encrypted packet larger than max_packet_length:"
1115 << options()->max_packet_length
<< " encrypted length: "
1116 << encrypted
->length();
1118 DVLOG(1) << ENDPOINT
<< "Sending packet number " << sequence_number
1119 << " : " << (packet
->is_fec_packet() ? "FEC " :
1120 (retransmittable
== HAS_RETRANSMITTABLE_DATA
1121 ? "data bearing " : " ack only "))
1122 << ", encryption level: "
1123 << QuicUtils::EncryptionLevelToString(level
)
1124 << ", length:" << packet
->length() << ", encrypted length:"
1125 << encrypted
->length();
1126 DVLOG(2) << ENDPOINT
<< "packet(" << sequence_number
<< "): " << std::endl
1127 << QuicUtils::StringToHexASCIIDump(packet
->AsStringPiece());
1129 DCHECK(encrypted
->length() <= kMaxPacketSize
||
1130 FLAGS_quic_allow_oversized_packets_for_test
)
1131 << "Packet " << sequence_number
<< " will not be read; too large: "
1132 << packet
->length() << " " << encrypted
->length() << " "
1133 << " forced: " << (forced
== FORCE
? "yes" : "no");
1135 DCHECK(pending_write_
.get() == NULL
);
1136 pending_write_
.reset(new PendingWrite(sequence_number
, transmission_type
,
1137 retransmittable
, level
,
1138 packet
->is_fec_packet(),
1141 WriteResult result
=
1142 writer_
->WritePacket(encrypted
->data(), encrypted
->length(),
1143 self_address().address(), peer_address(), this);
1144 if (result
.error_code
== ERR_IO_PENDING
) {
1145 DCHECK_EQ(WRITE_STATUS_BLOCKED
, result
.status
);
1147 if (debug_visitor_
) {
1148 // Pass the write result to the visitor.
1149 debug_visitor_
->OnPacketSent(sequence_number
, level
, *encrypted
, result
);
1151 if (result
.status
== WRITE_STATUS_BLOCKED
) {
1152 // If the socket buffers the the data, then the packet should not
1153 // be queued and sent again, which would result in an unnecessary
1154 // duplicate packet being sent. The helper must call OnPacketSent
1155 // when the packet is actually sent.
1156 if (writer_
->IsWriteBlockedDataBuffered()) {
1159 pending_write_
.reset();
1163 if (OnPacketSent(result
)) {
1169 bool QuicConnection::ShouldDiscardPacket(
1170 EncryptionLevel level
,
1171 QuicPacketSequenceNumber sequence_number
,
1172 HasRetransmittableData retransmittable
) {
1174 DVLOG(1) << ENDPOINT
1175 << "Not sending packet as connection is disconnected.";
1179 if (encryption_level_
== ENCRYPTION_FORWARD_SECURE
&&
1180 level
== ENCRYPTION_NONE
) {
1181 // Drop packets that are NULL encrypted since the peer won't accept them
1183 DVLOG(1) << ENDPOINT
<< "Dropping packet: " << sequence_number
1184 << " since the packet is NULL encrypted.";
1185 sent_packet_manager_
.DiscardUnackedPacket(sequence_number
);
1189 // If the packet has been discarded before sending, don't send it.
1190 // This occurs if a packet gets serialized, queued, then discarded.
1191 if (!sent_packet_manager_
.IsUnacked(sequence_number
)) {
1192 DVLOG(1) << ENDPOINT
<< "Dropping packet before sending: "
1193 << sequence_number
<< " since it has already been discarded.";
1197 if (retransmittable
== HAS_RETRANSMITTABLE_DATA
) {
1198 if (sent_packet_manager_
.IsPreviousTransmission(sequence_number
)) {
1199 // If somehow we have already retransmitted this packet *before*
1200 // we actually send it for the first time (I think this is probably
1201 // impossible in the real world), then don't bother sending it.
1202 // We don't want to call DiscardUnackedPacket because in this case
1203 // the peer has not yet ACK'd the data. We need the subsequent
1204 // retransmission to be sent.
1205 DVLOG(1) << ENDPOINT
<< "Dropping packet: " << sequence_number
1206 << " since it has already been retransmitted.";
1210 if (!sent_packet_manager_
.HasRetransmittableFrames(sequence_number
)) {
1211 DVLOG(1) << ENDPOINT
<< "Dropping packet: " << sequence_number
1212 << " since a previous transmission has been acked.";
1213 sent_packet_manager_
.DiscardUnackedPacket(sequence_number
);
1221 bool QuicConnection::OnPacketSent(WriteResult result
) {
1222 DCHECK_NE(WRITE_STATUS_BLOCKED
, result
.status
);
1223 if (pending_write_
.get() == NULL
) {
1224 LOG(DFATAL
) << "OnPacketSent called without a pending write.";
1228 QuicPacketSequenceNumber sequence_number
= pending_write_
->sequence_number
;
1229 TransmissionType transmission_type
= pending_write_
->transmission_type
;
1230 HasRetransmittableData retransmittable
= pending_write_
->retransmittable
;
1231 size_t length
= pending_write_
->length
;
1232 pending_write_
.reset();
1234 if (result
.status
== WRITE_STATUS_ERROR
) {
1235 DVLOG(1) << "Write failed with error code: " << result
.error_code
;
1236 // We can't send an error as the socket is presumably borked.
1237 CloseConnection(QUIC_PACKET_WRITE_ERROR
, false);
1241 QuicTime now
= clock_
->Now();
1242 if (transmission_type
== NOT_RETRANSMISSION
) {
1243 time_of_last_sent_new_packet_
= now
;
1245 DVLOG(1) << ENDPOINT
<< "time of last sent packet: "
1246 << now
.ToDebuggingValue();
1248 // TODO(ianswett): Change the sequence number length and other packet creator
1249 // options by a more explicit API than setting a struct value directly.
1250 packet_creator_
.UpdateSequenceNumberLength(
1251 received_packet_manager_
.least_packet_awaited_by_peer(),
1252 sent_packet_manager_
.BandwidthEstimate().ToBytesPerPeriod(
1253 sent_packet_manager_
.SmoothedRtt()));
1255 bool reset_retransmission_alarm
=
1256 sent_packet_manager_
.OnPacketSent(sequence_number
, now
, length
,
1257 transmission_type
, retransmittable
);
1259 if (reset_retransmission_alarm
|| !retransmission_alarm_
->IsSet()) {
1260 retransmission_alarm_
->Cancel();
1261 QuicTime retransmission_time
= sent_packet_manager_
.GetRetransmissionTime();
1262 if (retransmission_time
!= QuicTime::Zero()) {
1263 retransmission_alarm_
->Set(retransmission_time
);
1267 stats_
.bytes_sent
+= result
.bytes_written
;
1268 ++stats_
.packets_sent
;
1270 if (transmission_type
== NACK_RETRANSMISSION
||
1271 transmission_type
== RTO_RETRANSMISSION
) {
1272 stats_
.bytes_retransmitted
+= result
.bytes_written
;
1273 ++stats_
.packets_retransmitted
;
1279 bool QuicConnection::OnSerializedPacket(
1280 const SerializedPacket
& serialized_packet
) {
1281 if (serialized_packet
.retransmittable_frames
) {
1282 serialized_packet
.retransmittable_frames
->
1283 set_encryption_level(encryption_level_
);
1285 sent_packet_manager_
.OnSerializedPacket(serialized_packet
);
1286 // The TransmissionType is NOT_RETRANSMISSION because all retransmissions
1287 // serialize packets and invoke SendOrQueuePacket directly.
1288 return SendOrQueuePacket(encryption_level_
,
1290 NOT_RETRANSMISSION
);
1293 QuicPacketSequenceNumber
QuicConnection::GetNextPacketSequenceNumber() {
1294 return packet_creator_
.sequence_number() + 1;
1297 bool QuicConnection::SendOrQueuePacket(EncryptionLevel level
,
1298 const SerializedPacket
& packet
,
1299 TransmissionType transmission_type
) {
1300 IsHandshake handshake
= packet
.retransmittable_frames
== NULL
?
1301 NOT_HANDSHAKE
: packet
.retransmittable_frames
->HasCryptoHandshake();
1302 Force forced
= HasForcedFrames(packet
.retransmittable_frames
);
1303 HasRetransmittableData retransmittable
=
1304 (transmission_type
!= NOT_RETRANSMISSION
||
1305 packet
.retransmittable_frames
!= NULL
) ?
1306 HAS_RETRANSMITTABLE_DATA
: NO_RETRANSMITTABLE_DATA
;
1307 sent_entropy_manager_
.RecordPacketEntropyHash(packet
.sequence_number
,
1308 packet
.entropy_hash
);
1309 if (WritePacket(level
, packet
.sequence_number
, packet
.packet
,
1310 transmission_type
, retransmittable
, handshake
, forced
)) {
1311 delete packet
.packet
;
1314 queued_packets_
.push_back(QueuedPacket(packet
.sequence_number
, packet
.packet
,
1315 level
, transmission_type
,
1316 retransmittable
, handshake
, forced
));
1320 void QuicConnection::UpdateSentPacketInfo(SentPacketInfo
* sent_info
) {
1321 sent_info
->least_unacked
= sent_packet_manager_
.GetLeastUnackedSentPacket();
1322 sent_info
->entropy_hash
= sent_entropy_manager_
.EntropyHash(
1323 sent_info
->least_unacked
- 1);
1326 void QuicConnection::SendAck() {
1327 ack_alarm_
->Cancel();
1328 // TODO(rch): delay this until the CreateFeedbackFrame
1329 // method is invoked. This requires changes SetShouldSendAck
1330 // to be a no-arg method, and re-jiggering its implementation.
1331 bool send_feedback
= false;
1332 if (received_packet_manager_
.GenerateCongestionFeedback(
1333 &outgoing_congestion_feedback_
)) {
1334 DVLOG(1) << ENDPOINT
<< "Sending feedback: "
1335 << outgoing_congestion_feedback_
;
1336 send_feedback
= true;
1339 packet_generator_
.SetShouldSendAck(send_feedback
);
1342 void QuicConnection::OnRetransmissionTimeout() {
1343 if (!sent_packet_manager_
.HasUnackedPackets()) {
1349 sent_packet_manager_
.OnRetransmissionTimeout();
1351 WriteIfNotBlocked();
1353 // Ensure the retransmission alarm is always set if there are unacked packets.
1354 if (!HasQueuedData() && !retransmission_alarm_
->IsSet()) {
1355 QuicTime rto_timeout
= sent_packet_manager_
.GetRetransmissionTime();
1356 if (rto_timeout
!= QuicTime::Zero()) {
1357 retransmission_alarm_
->Set(rto_timeout
);
1362 void QuicConnection::SetEncrypter(EncryptionLevel level
,
1363 QuicEncrypter
* encrypter
) {
1364 framer_
.SetEncrypter(level
, encrypter
);
1367 const QuicEncrypter
* QuicConnection::encrypter(EncryptionLevel level
) const {
1368 return framer_
.encrypter(level
);
1371 void QuicConnection::SetDefaultEncryptionLevel(
1372 EncryptionLevel level
) {
1373 encryption_level_
= level
;
1376 void QuicConnection::SetDecrypter(QuicDecrypter
* decrypter
) {
1377 framer_
.SetDecrypter(decrypter
);
1380 void QuicConnection::SetAlternativeDecrypter(QuicDecrypter
* decrypter
,
1381 bool latch_once_used
) {
1382 framer_
.SetAlternativeDecrypter(decrypter
, latch_once_used
);
1385 const QuicDecrypter
* QuicConnection::decrypter() const {
1386 return framer_
.decrypter();
1389 const QuicDecrypter
* QuicConnection::alternative_decrypter() const {
1390 return framer_
.alternative_decrypter();
1393 void QuicConnection::QueueUndecryptablePacket(
1394 const QuicEncryptedPacket
& packet
) {
1395 DVLOG(1) << ENDPOINT
<< "Queueing undecryptable packet.";
1396 undecryptable_packets_
.push_back(packet
.Clone());
1399 void QuicConnection::MaybeProcessUndecryptablePackets() {
1400 if (undecryptable_packets_
.empty() ||
1401 encryption_level_
== ENCRYPTION_NONE
) {
1405 while (connected_
&& !undecryptable_packets_
.empty()) {
1406 DVLOG(1) << ENDPOINT
<< "Attempting to process undecryptable packet";
1407 QuicEncryptedPacket
* packet
= undecryptable_packets_
.front();
1408 if (!framer_
.ProcessPacket(*packet
) &&
1409 framer_
.error() == QUIC_DECRYPTION_FAILURE
) {
1410 DVLOG(1) << ENDPOINT
<< "Unable to process undecryptable packet...";
1413 DVLOG(1) << ENDPOINT
<< "Processed undecryptable packet!";
1415 undecryptable_packets_
.pop_front();
1418 // Once forward secure encryption is in use, there will be no
1419 // new keys installed and hence any undecryptable packets will
1420 // never be able to be decrypted.
1421 if (encryption_level_
== ENCRYPTION_FORWARD_SECURE
) {
1422 STLDeleteElements(&undecryptable_packets_
);
1426 void QuicConnection::MaybeProcessRevivedPacket() {
1427 QuicFecGroup
* group
= GetFecGroup();
1428 if (!connected_
|| group
== NULL
|| !group
->CanRevive()) {
1431 QuicPacketHeader revived_header
;
1432 char revived_payload
[kMaxPacketSize
];
1433 size_t len
= group
->Revive(&revived_header
, revived_payload
, kMaxPacketSize
);
1434 revived_header
.public_header
.guid
= guid_
;
1435 revived_header
.public_header
.version_flag
= false;
1436 revived_header
.public_header
.reset_flag
= false;
1437 revived_header
.fec_flag
= false;
1438 revived_header
.is_in_fec_group
= NOT_IN_FEC_GROUP
;
1439 revived_header
.fec_group
= 0;
1440 group_map_
.erase(last_header_
.fec_group
);
1443 last_packet_revived_
= true;
1444 if (debug_visitor_
) {
1445 debug_visitor_
->OnRevivedPacket(revived_header
,
1446 StringPiece(revived_payload
, len
));
1449 ++stats_
.packets_revived
;
1450 framer_
.ProcessRevivedPacket(&revived_header
,
1451 StringPiece(revived_payload
, len
));
1454 QuicFecGroup
* QuicConnection::GetFecGroup() {
1455 QuicFecGroupNumber fec_group_num
= last_header_
.fec_group
;
1456 if (fec_group_num
== 0) {
1459 if (group_map_
.count(fec_group_num
) == 0) {
1460 if (group_map_
.size() >= kMaxFecGroups
) { // Too many groups
1461 if (fec_group_num
< group_map_
.begin()->first
) {
1462 // The group being requested is a group we've seen before and deleted.
1463 // Don't recreate it.
1466 // Clear the lowest group number.
1467 delete group_map_
.begin()->second
;
1468 group_map_
.erase(group_map_
.begin());
1470 group_map_
[fec_group_num
] = new QuicFecGroup();
1472 return group_map_
[fec_group_num
];
1475 void QuicConnection::SendConnectionClose(QuicErrorCode error
) {
1476 SendConnectionCloseWithDetails(error
, string());
1479 void QuicConnection::SendConnectionCloseWithDetails(QuicErrorCode error
,
1480 const string
& details
) {
1481 // If we're write blocked, WritePacket() will not send, but will capture the
1482 // serialized packet.
1483 SendConnectionClosePacket(error
, details
);
1484 CloseConnection(error
, false);
1487 void QuicConnection::SendConnectionClosePacket(QuicErrorCode error
,
1488 const string
& details
) {
1489 DVLOG(1) << ENDPOINT
<< "Force closing " << guid() << " with error "
1490 << QuicUtils::ErrorToString(error
) << " (" << error
<< ") "
1492 ScopedPacketBundler
ack_bundler(this, true);
1493 QuicConnectionCloseFrame
* frame
= new QuicConnectionCloseFrame();
1494 frame
->error_code
= error
;
1495 frame
->error_details
= details
;
1496 packet_generator_
.AddControlFrame(QuicFrame(frame
));
1500 void QuicConnection::CloseConnection(QuicErrorCode error
, bool from_peer
) {
1503 visitor_
->OnConnectionClosed(error
, from_peer
);
1504 // Cancel the alarms so they don't trigger any action now that the
1505 // connection is closed.
1506 ack_alarm_
->Cancel();
1507 resume_writes_alarm_
->Cancel();
1508 retransmission_alarm_
->Cancel();
1509 send_alarm_
->Cancel();
1510 timeout_alarm_
->Cancel();
1513 void QuicConnection::SendGoAway(QuicErrorCode error
,
1514 QuicStreamId last_good_stream_id
,
1515 const string
& reason
) {
1516 DVLOG(1) << ENDPOINT
<< "Going away with error "
1517 << QuicUtils::ErrorToString(error
)
1518 << " (" << error
<< ")";
1520 // Opportunistically bundle an ack with this outgoing packet.
1521 ScopedPacketBundler
ack_bundler(this, true);
1522 packet_generator_
.AddControlFrame(
1523 QuicFrame(new QuicGoAwayFrame(error
, last_good_stream_id
, reason
)));
1526 void QuicConnection::CloseFecGroupsBefore(
1527 QuicPacketSequenceNumber sequence_number
) {
1528 FecGroupMap::iterator it
= group_map_
.begin();
1529 while (it
!= group_map_
.end()) {
1530 // If this is the current group or the group doesn't protect this packet
1531 // we can ignore it.
1532 if (last_header_
.fec_group
== it
->first
||
1533 !it
->second
->ProtectsPacketsBefore(sequence_number
)) {
1537 QuicFecGroup
* fec_group
= it
->second
;
1538 DCHECK(!fec_group
->CanRevive());
1539 FecGroupMap::iterator next
= it
;
1541 group_map_
.erase(it
);
1547 void QuicConnection::Flush() {
1548 packet_generator_
.FlushAllQueuedFrames();
1551 bool QuicConnection::HasQueuedData() const {
1552 return pending_version_negotiation_packet_
||
1553 !queued_packets_
.empty() || packet_generator_
.HasQueuedFrames();
1556 bool QuicConnection::CanWriteStreamData() {
1557 if (HasQueuedData()) {
1561 IsHandshake pending_handshake
= visitor_
->HasPendingHandshake() ?
1562 IS_HANDSHAKE
: NOT_HANDSHAKE
;
1563 // Sending queued packets may have caused the socket to become write blocked,
1564 // or the congestion manager to prohibit sending. If we've sent everything
1565 // we had queued and we're still not blocked, let the visitor know it can
1567 return ShouldGeneratePacket(NOT_RETRANSMISSION
, HAS_RETRANSMITTABLE_DATA
,
1571 void QuicConnection::SetIdleNetworkTimeout(QuicTime::Delta timeout
) {
1572 if (timeout
< idle_network_timeout_
) {
1573 idle_network_timeout_
= timeout
;
1576 idle_network_timeout_
= timeout
;
1580 void QuicConnection::SetOverallConnectionTimeout(QuicTime::Delta timeout
) {
1581 if (timeout
< overall_connection_timeout_
) {
1582 overall_connection_timeout_
= timeout
;
1585 overall_connection_timeout_
= timeout
;
1589 bool QuicConnection::CheckForTimeout() {
1590 QuicTime now
= clock_
->ApproximateNow();
1591 QuicTime time_of_last_packet
= max(time_of_last_received_packet_
,
1592 time_of_last_sent_new_packet_
);
1594 // |delta| can be < 0 as |now| is approximate time but |time_of_last_packet|
1595 // is accurate time. However, this should not change the behavior of
1596 // timeout handling.
1597 QuicTime::Delta delta
= now
.Subtract(time_of_last_packet
);
1598 DVLOG(1) << ENDPOINT
<< "last packet "
1599 << time_of_last_packet
.ToDebuggingValue()
1600 << " now:" << now
.ToDebuggingValue()
1601 << " delta:" << delta
.ToMicroseconds()
1602 << " network_timeout: " << idle_network_timeout_
.ToMicroseconds();
1603 if (delta
>= idle_network_timeout_
) {
1604 DVLOG(1) << ENDPOINT
<< "Connection timedout due to no network activity.";
1605 SendConnectionClose(QUIC_CONNECTION_TIMED_OUT
);
1609 // Next timeout delta.
1610 QuicTime::Delta timeout
= idle_network_timeout_
.Subtract(delta
);
1612 if (!overall_connection_timeout_
.IsInfinite()) {
1613 QuicTime::Delta connected_time
= now
.Subtract(creation_time_
);
1614 DVLOG(1) << ENDPOINT
<< "connection time: "
1615 << connected_time
.ToMilliseconds() << " overall timeout: "
1616 << overall_connection_timeout_
.ToMilliseconds();
1617 if (connected_time
>= overall_connection_timeout_
) {
1618 DVLOG(1) << ENDPOINT
<<
1619 "Connection timedout due to overall connection timeout.";
1620 SendConnectionClose(QUIC_CONNECTION_TIMED_OUT
);
1624 // Take the min timeout.
1625 QuicTime::Delta connection_timeout
=
1626 overall_connection_timeout_
.Subtract(connected_time
);
1627 if (connection_timeout
< timeout
) {
1628 timeout
= connection_timeout
;
1632 timeout_alarm_
->Cancel();
1633 timeout_alarm_
->Set(clock_
->ApproximateNow().Add(timeout
));
1637 QuicConnection::ScopedPacketBundler::ScopedPacketBundler(
1638 QuicConnection
* connection
,
1640 : connection_(connection
),
1641 already_in_batch_mode_(connection
->packet_generator_
.InBatchMode()) {
1642 // Move generator into batch mode. If caller wants us to include an ack,
1643 // check the delayed-ack timer to see if there's ack info to be sent.
1644 if (!already_in_batch_mode_
) {
1645 DVLOG(1) << "Entering Batch Mode.";
1646 connection_
->packet_generator_
.StartBatchOperations();
1648 if (include_ack
&& connection_
->ack_alarm_
->IsSet()) {
1649 DVLOG(1) << "Bundling ack with outgoing packet.";
1650 connection_
->SendAck();
1654 QuicConnection::ScopedPacketBundler::~ScopedPacketBundler() {
1655 // If we changed the generator's batch state, restore original batch state.
1656 if (!already_in_batch_mode_
) {
1657 DVLOG(1) << "Leaving Batch Mode.";
1658 connection_
->packet_generator_
.FinishBatchOperations();
1660 DCHECK_EQ(already_in_batch_mode_
,
1661 connection_
->packet_generator_
.InBatchMode());