Land Recent QUIC Changes.
[chromium-blink-merge.git] / net / quic / quic_connection.cc
blobad88a90b33d879f183bb812e413d3bf4c7ccf055
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"
7 #include <string.h>
8 #include <sys/types.h>
9 #include <algorithm>
10 #include <iterator>
11 #include <limits>
12 #include <memory>
13 #include <set>
14 #include <utility>
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"
26 using base::hash_map;
27 using base::hash_set;
28 using base::StringPiece;
29 using std::list;
30 using std::make_pair;
31 using std::min;
32 using std::max;
33 using std::numeric_limits;
34 using std::vector;
35 using std::set;
36 using std::string;
38 int FLAGS_fake_packet_loss_percentage = 0;
40 // If true, then QUIC connections will bundle acks with any outgoing packet when
41 // an ack is being delayed. This is an optimization to reduce ack latency and
42 // packet count of pure ack packets.
43 bool FLAGS_bundle_ack_with_outgoing_packet = false;
45 namespace net {
47 class QuicDecrypter;
48 class QuicEncrypter;
50 namespace {
52 // The largest gap in packets we'll accept without closing the connection.
53 // This will likely have to be tuned.
54 const QuicPacketSequenceNumber kMaxPacketGap = 5000;
56 // Limit the number of FEC groups to two. If we get enough out of order packets
57 // that this becomes limiting, we can revisit.
58 const size_t kMaxFecGroups = 2;
60 // Limit the number of undecryptable packets we buffer in
61 // expectation of the CHLO/SHLO arriving.
62 const size_t kMaxUndecryptablePackets = 10;
64 bool Near(QuicPacketSequenceNumber a, QuicPacketSequenceNumber b) {
65 QuicPacketSequenceNumber delta = (a > b) ? a - b : b - a;
66 return delta <= kMaxPacketGap;
70 // An alarm that is scheduled to send an ack if a timeout occurs.
71 class AckAlarm : public QuicAlarm::Delegate {
72 public:
73 explicit AckAlarm(QuicConnection* connection)
74 : connection_(connection) {
77 virtual QuicTime OnAlarm() OVERRIDE {
78 connection_->SendAck();
79 return QuicTime::Zero();
82 private:
83 QuicConnection* connection_;
86 // This alarm will be scheduled any time a data-bearing packet is sent out.
87 // When the alarm goes off, the connection checks to see if the oldest packets
88 // have been acked, and retransmit them if they have not.
89 class RetransmissionAlarm : public QuicAlarm::Delegate {
90 public:
91 explicit RetransmissionAlarm(QuicConnection* connection)
92 : connection_(connection) {
95 virtual QuicTime OnAlarm() OVERRIDE {
96 connection_->OnRetransmissionTimeout();
97 return QuicTime::Zero();
100 private:
101 QuicConnection* connection_;
104 // An alarm that is scheduled when the sent scheduler requires a
105 // a delay before sending packets and fires when the packet may be sent.
106 class SendAlarm : public QuicAlarm::Delegate {
107 public:
108 explicit SendAlarm(QuicConnection* connection)
109 : connection_(connection) {
112 virtual QuicTime OnAlarm() OVERRIDE {
113 connection_->WriteIfNotBlocked();
114 // Never reschedule the alarm, since OnCanWrite does that.
115 return QuicTime::Zero();
118 private:
119 QuicConnection* connection_;
122 class TimeoutAlarm : public QuicAlarm::Delegate {
123 public:
124 explicit TimeoutAlarm(QuicConnection* connection)
125 : connection_(connection) {
128 virtual QuicTime OnAlarm() OVERRIDE {
129 connection_->CheckForTimeout();
130 // Never reschedule the alarm, since CheckForTimeout does that.
131 return QuicTime::Zero();
134 private:
135 QuicConnection* connection_;
138 // Indicates if any of the frames are intended to be sent with FORCE.
139 // Returns FORCE when one of the frames is a CONNECTION_CLOSE_FRAME.
140 net::QuicConnection::Force HasForcedFrames(
141 const RetransmittableFrames* retransmittable_frames) {
142 if (!retransmittable_frames) {
143 return net::QuicConnection::NO_FORCE;
145 for (size_t i = 0; i < retransmittable_frames->frames().size(); ++i) {
146 if (retransmittable_frames->frames()[i].type == CONNECTION_CLOSE_FRAME) {
147 return net::QuicConnection::FORCE;
150 return net::QuicConnection::NO_FORCE;
153 } // namespace
155 #define ENDPOINT (is_server_ ? "Server: " : " Client: ")
157 QuicConnection::QuicConnection(QuicGuid guid,
158 IPEndPoint address,
159 QuicConnectionHelperInterface* helper,
160 QuicPacketWriter* writer,
161 bool is_server,
162 const QuicVersionVector& supported_versions)
163 : framer_(supported_versions,
164 helper->GetClock()->ApproximateNow(),
165 is_server),
166 helper_(helper),
167 writer_(writer),
168 encryption_level_(ENCRYPTION_NONE),
169 clock_(helper->GetClock()),
170 random_generator_(helper->GetRandomGenerator()),
171 guid_(guid),
172 peer_address_(address),
173 largest_seen_packet_with_ack_(0),
174 pending_version_negotiation_packet_(false),
175 write_blocked_(false),
176 received_packet_manager_(kTCP),
177 ack_alarm_(helper->CreateAlarm(new AckAlarm(this))),
178 retransmission_alarm_(helper->CreateAlarm(new RetransmissionAlarm(this))),
179 send_alarm_(helper->CreateAlarm(new SendAlarm(this))),
180 resume_writes_alarm_(helper->CreateAlarm(new SendAlarm(this))),
181 timeout_alarm_(helper->CreateAlarm(new TimeoutAlarm(this))),
182 debug_visitor_(NULL),
183 packet_creator_(guid_, &framer_, random_generator_, is_server),
184 packet_generator_(this, NULL, &packet_creator_),
185 idle_network_timeout_(
186 QuicTime::Delta::FromSeconds(kDefaultInitialTimeoutSecs)),
187 overall_connection_timeout_(QuicTime::Delta::Infinite()),
188 creation_time_(clock_->ApproximateNow()),
189 time_of_last_received_packet_(clock_->ApproximateNow()),
190 time_of_last_sent_new_packet_(clock_->ApproximateNow()),
191 sequence_number_of_last_inorder_packet_(0),
192 sent_packet_manager_(is_server, this, clock_, kTCP),
193 version_negotiation_state_(START_NEGOTIATION),
194 is_server_(is_server),
195 connected_(true),
196 address_migrating_(false) {
197 if (!is_server_) {
198 // Pacing will be enabled if the client negotiates it.
199 sent_packet_manager_.MaybeEnablePacing();
201 DVLOG(1) << ENDPOINT << "Created connection with guid: " << guid;
202 timeout_alarm_->Set(clock_->ApproximateNow().Add(idle_network_timeout_));
203 framer_.set_visitor(this);
204 framer_.set_received_entropy_calculator(&received_packet_manager_);
207 QuicConnection::~QuicConnection() {
208 STLDeleteElements(&undecryptable_packets_);
209 STLDeleteValues(&group_map_);
210 for (QueuedPacketList::iterator it = queued_packets_.begin();
211 it != queued_packets_.end(); ++it) {
212 delete it->packet;
216 void QuicConnection::SetFromConfig(const QuicConfig& config) {
217 DCHECK_LT(0u, config.server_initial_congestion_window());
218 SetIdleNetworkTimeout(config.idle_connection_state_lifetime());
219 sent_packet_manager_.SetFromConfig(config);
220 // TODO(satyamshekhar): Set congestion control and ICSL also.
223 bool QuicConnection::SelectMutualVersion(
224 const QuicVersionVector& available_versions) {
225 // Try to find the highest mutual version by iterating over supported
226 // versions, starting with the highest, and breaking out of the loop once we
227 // find a matching version in the provided available_versions vector.
228 const QuicVersionVector& supported_versions = framer_.supported_versions();
229 for (size_t i = 0; i < supported_versions.size(); ++i) {
230 const QuicVersion& version = supported_versions[i];
231 if (std::find(available_versions.begin(), available_versions.end(),
232 version) != available_versions.end()) {
233 framer_.set_version(version);
234 return true;
238 return false;
241 void QuicConnection::OnError(QuicFramer* framer) {
242 // Packets that we cannot decrypt are dropped.
243 // TODO(rch): add stats to measure this.
244 if (!connected_ || framer->error() == QUIC_DECRYPTION_FAILURE) {
245 return;
247 SendConnectionCloseWithDetails(framer->error(), framer->detailed_error());
250 void QuicConnection::OnPacket() {
251 DCHECK(last_stream_frames_.empty() &&
252 last_goaway_frames_.empty() &&
253 last_rst_frames_.empty() &&
254 last_ack_frames_.empty() &&
255 last_congestion_frames_.empty());
258 void QuicConnection::OnPublicResetPacket(
259 const QuicPublicResetPacket& packet) {
260 if (debug_visitor_) {
261 debug_visitor_->OnPublicResetPacket(packet);
263 CloseConnection(QUIC_PUBLIC_RESET, true);
266 bool QuicConnection::OnProtocolVersionMismatch(QuicVersion received_version) {
267 DVLOG(1) << ENDPOINT << "Received packet with mismatched version "
268 << received_version;
269 // TODO(satyamshekhar): Implement no server state in this mode.
270 if (!is_server_) {
271 LOG(DFATAL) << ENDPOINT << "Framer called OnProtocolVersionMismatch. "
272 << "Closing connection.";
273 CloseConnection(QUIC_INTERNAL_ERROR, false);
274 return false;
276 DCHECK_NE(version(), received_version);
278 if (debug_visitor_) {
279 debug_visitor_->OnProtocolVersionMismatch(received_version);
282 switch (version_negotiation_state_) {
283 case START_NEGOTIATION:
284 if (!framer_.IsSupportedVersion(received_version)) {
285 SendVersionNegotiationPacket();
286 version_negotiation_state_ = NEGOTIATION_IN_PROGRESS;
287 return false;
289 break;
291 case NEGOTIATION_IN_PROGRESS:
292 if (!framer_.IsSupportedVersion(received_version)) {
293 SendVersionNegotiationPacket();
294 return false;
296 break;
298 case NEGOTIATED_VERSION:
299 // Might be old packets that were sent by the client before the version
300 // was negotiated. Drop these.
301 return false;
303 default:
304 DCHECK(false);
307 version_negotiation_state_ = NEGOTIATED_VERSION;
308 visitor_->OnSuccessfulVersionNegotiation(received_version);
309 DVLOG(1) << ENDPOINT << "version negotiated " << received_version;
311 // Store the new version.
312 framer_.set_version(received_version);
314 // TODO(satyamshekhar): Store the sequence number of this packet and close the
315 // connection if we ever received a packet with incorrect version and whose
316 // sequence number is greater.
317 return true;
320 // Handles version negotiation for client connection.
321 void QuicConnection::OnVersionNegotiationPacket(
322 const QuicVersionNegotiationPacket& packet) {
323 if (is_server_) {
324 LOG(DFATAL) << ENDPOINT << "Framer parsed VersionNegotiationPacket."
325 << " Closing connection.";
326 CloseConnection(QUIC_INTERNAL_ERROR, false);
327 return;
329 if (debug_visitor_) {
330 debug_visitor_->OnVersionNegotiationPacket(packet);
333 if (version_negotiation_state_ != START_NEGOTIATION) {
334 // Possibly a duplicate version negotiation packet.
335 return;
338 if (std::find(packet.versions.begin(),
339 packet.versions.end(), version()) !=
340 packet.versions.end()) {
341 DLOG(WARNING) << ENDPOINT << "The server already supports our version. "
342 << "It should have accepted our connection.";
343 // Just drop the connection.
344 CloseConnection(QUIC_INVALID_VERSION_NEGOTIATION_PACKET, false);
345 return;
348 if (!SelectMutualVersion(packet.versions)) {
349 SendConnectionCloseWithDetails(QUIC_INVALID_VERSION,
350 "no common version found");
351 return;
354 DVLOG(1) << ENDPOINT << "negotiating version " << version();
355 server_supported_versions_ = packet.versions;
356 version_negotiation_state_ = NEGOTIATION_IN_PROGRESS;
357 RetransmitUnackedPackets(ALL_PACKETS);
360 void QuicConnection::OnRevivedPacket() {
363 bool QuicConnection::OnUnauthenticatedPublicHeader(
364 const QuicPacketPublicHeader& header) {
365 return true;
368 bool QuicConnection::OnUnauthenticatedHeader(const QuicPacketHeader& header) {
369 return true;
372 bool QuicConnection::OnPacketHeader(const QuicPacketHeader& header) {
373 if (debug_visitor_) {
374 debug_visitor_->OnPacketHeader(header);
377 if (!ProcessValidatedPacket()) {
378 return false;
381 // Will be decrement below if we fall through to return true;
382 ++stats_.packets_dropped;
384 if (header.public_header.guid != guid_) {
385 DVLOG(1) << ENDPOINT << "Ignoring packet from unexpected GUID: "
386 << header.public_header.guid << " instead of " << guid_;
387 return false;
390 if (!Near(header.packet_sequence_number,
391 last_header_.packet_sequence_number)) {
392 DVLOG(1) << ENDPOINT << "Packet " << header.packet_sequence_number
393 << " out of bounds. Discarding";
394 SendConnectionCloseWithDetails(QUIC_INVALID_PACKET_HEADER,
395 "Packet sequence number out of bounds");
396 return false;
399 // If this packet has already been seen, or that the sender
400 // has told us will not be retransmitted, then stop processing the packet.
401 if (!received_packet_manager_.IsAwaitingPacket(
402 header.packet_sequence_number)) {
403 return false;
406 if (version_negotiation_state_ != NEGOTIATED_VERSION) {
407 if (is_server_) {
408 if (!header.public_header.version_flag) {
409 DLOG(WARNING) << ENDPOINT << "Got packet without version flag before "
410 << "version negotiated.";
411 // Packets should have the version flag till version negotiation is
412 // done.
413 CloseConnection(QUIC_INVALID_VERSION, false);
414 return false;
415 } else {
416 DCHECK_EQ(1u, header.public_header.versions.size());
417 DCHECK_EQ(header.public_header.versions[0], version());
418 version_negotiation_state_ = NEGOTIATED_VERSION;
419 visitor_->OnSuccessfulVersionNegotiation(version());
421 } else {
422 DCHECK(!header.public_header.version_flag);
423 // If the client gets a packet without the version flag from the server
424 // it should stop sending version since the version negotiation is done.
425 packet_creator_.StopSendingVersion();
426 version_negotiation_state_ = NEGOTIATED_VERSION;
427 visitor_->OnSuccessfulVersionNegotiation(version());
431 DCHECK_EQ(NEGOTIATED_VERSION, version_negotiation_state_);
433 --stats_.packets_dropped;
434 DVLOG(1) << ENDPOINT << "Received packet header: " << header;
435 last_header_ = header;
436 DCHECK(connected_);
437 return true;
440 void QuicConnection::OnFecProtectedPayload(StringPiece payload) {
441 DCHECK_EQ(IN_FEC_GROUP, last_header_.is_in_fec_group);
442 DCHECK_NE(0u, last_header_.fec_group);
443 QuicFecGroup* group = GetFecGroup();
444 if (group != NULL) {
445 group->Update(last_header_, payload);
449 bool QuicConnection::OnStreamFrame(const QuicStreamFrame& frame) {
450 DCHECK(connected_);
451 if (debug_visitor_) {
452 debug_visitor_->OnStreamFrame(frame);
454 last_stream_frames_.push_back(frame);
455 return true;
458 bool QuicConnection::OnAckFrame(const QuicAckFrame& incoming_ack) {
459 DCHECK(connected_);
460 if (debug_visitor_) {
461 debug_visitor_->OnAckFrame(incoming_ack);
463 DVLOG(1) << ENDPOINT << "OnAckFrame: " << incoming_ack;
465 if (last_header_.packet_sequence_number <= largest_seen_packet_with_ack_) {
466 DVLOG(1) << ENDPOINT << "Received an old ack frame: ignoring";
467 return true;
470 if (!ValidateAckFrame(incoming_ack)) {
471 SendConnectionClose(QUIC_INVALID_ACK_DATA);
472 return false;
475 last_ack_frames_.push_back(incoming_ack);
476 return connected_;
479 void QuicConnection::ProcessAckFrame(const QuicAckFrame& incoming_ack) {
480 largest_seen_packet_with_ack_ = last_header_.packet_sequence_number;
482 received_packet_manager_.UpdatePacketInformationReceivedByPeer(incoming_ack);
483 received_packet_manager_.UpdatePacketInformationSentByPeer(incoming_ack);
484 // Possibly close any FecGroups which are now irrelevant.
485 CloseFecGroupsBefore(incoming_ack.sent_info.least_unacked + 1);
487 sent_entropy_manager_.ClearEntropyBefore(
488 received_packet_manager_.least_packet_awaited_by_peer() - 1);
490 bool reset_retransmission_alarm =
491 sent_packet_manager_.OnIncomingAck(incoming_ack.received_info,
492 time_of_last_received_packet_);
493 if (sent_packet_manager_.HasPendingRetransmissions()) {
494 WriteIfNotBlocked();
497 if (reset_retransmission_alarm) {
498 retransmission_alarm_->Cancel();
499 QuicTime retransmission_time =
500 sent_packet_manager_.GetRetransmissionTime();
501 if (retransmission_time != QuicTime::Zero()) {
502 retransmission_alarm_->Set(retransmission_time);
507 bool QuicConnection::OnCongestionFeedbackFrame(
508 const QuicCongestionFeedbackFrame& feedback) {
509 DCHECK(connected_);
510 if (debug_visitor_) {
511 debug_visitor_->OnCongestionFeedbackFrame(feedback);
513 last_congestion_frames_.push_back(feedback);
514 return connected_;
517 bool QuicConnection::ValidateAckFrame(const QuicAckFrame& incoming_ack) {
518 if (incoming_ack.received_info.largest_observed >
519 packet_creator_.sequence_number()) {
520 DLOG(ERROR) << ENDPOINT << "Peer's observed unsent packet:"
521 << incoming_ack.received_info.largest_observed << " vs "
522 << packet_creator_.sequence_number();
523 // We got an error for data we have not sent. Error out.
524 return false;
527 if (incoming_ack.received_info.largest_observed <
528 received_packet_manager_.peer_largest_observed_packet()) {
529 DLOG(ERROR) << ENDPOINT << "Peer's largest_observed packet decreased:"
530 << incoming_ack.received_info.largest_observed << " vs "
531 << received_packet_manager_.peer_largest_observed_packet();
532 // A new ack has a diminished largest_observed value. Error out.
533 // If this was an old packet, we wouldn't even have checked.
534 return false;
537 if (incoming_ack.sent_info.least_unacked <
538 received_packet_manager_.peer_least_packet_awaiting_ack()) {
539 DLOG(ERROR) << ENDPOINT << "Peer's sent low least_unacked: "
540 << incoming_ack.sent_info.least_unacked << " vs "
541 << received_packet_manager_.peer_least_packet_awaiting_ack();
542 // We never process old ack frames, so this number should only increase.
543 return false;
546 if (incoming_ack.sent_info.least_unacked >
547 last_header_.packet_sequence_number) {
548 DLOG(ERROR) << ENDPOINT << "Peer sent least_unacked:"
549 << incoming_ack.sent_info.least_unacked
550 << " greater than the enclosing packet sequence number:"
551 << last_header_.packet_sequence_number;
552 return false;
555 if (!incoming_ack.received_info.missing_packets.empty() &&
556 *incoming_ack.received_info.missing_packets.rbegin() >
557 incoming_ack.received_info.largest_observed) {
558 DLOG(ERROR) << ENDPOINT << "Peer sent missing packet: "
559 << *incoming_ack.received_info.missing_packets.rbegin()
560 << " which is greater than largest observed: "
561 << incoming_ack.received_info.largest_observed;
562 return false;
565 if (!incoming_ack.received_info.missing_packets.empty() &&
566 *incoming_ack.received_info.missing_packets.begin() <
567 received_packet_manager_.least_packet_awaited_by_peer()) {
568 DLOG(ERROR) << ENDPOINT << "Peer sent missing packet: "
569 << *incoming_ack.received_info.missing_packets.begin()
570 << " which is smaller than least_packet_awaited_by_peer_: "
571 << received_packet_manager_.least_packet_awaited_by_peer();
572 return false;
575 if (!sent_entropy_manager_.IsValidEntropy(
576 incoming_ack.received_info.largest_observed,
577 incoming_ack.received_info.missing_packets,
578 incoming_ack.received_info.entropy_hash)) {
579 DLOG(ERROR) << ENDPOINT << "Peer sent invalid entropy.";
580 return false;
583 return true;
586 void QuicConnection::OnFecData(const QuicFecData& fec) {
587 DCHECK_EQ(IN_FEC_GROUP, last_header_.is_in_fec_group);
588 DCHECK_NE(0u, last_header_.fec_group);
589 QuicFecGroup* group = GetFecGroup();
590 if (group != NULL) {
591 group->UpdateFec(last_header_.packet_sequence_number,
592 last_header_.entropy_flag, fec);
596 bool QuicConnection::OnRstStreamFrame(const QuicRstStreamFrame& frame) {
597 DCHECK(connected_);
598 if (debug_visitor_) {
599 debug_visitor_->OnRstStreamFrame(frame);
601 DVLOG(1) << ENDPOINT << "Stream reset with error "
602 << QuicUtils::StreamErrorToString(frame.error_code);
603 last_rst_frames_.push_back(frame);
604 return connected_;
607 bool QuicConnection::OnConnectionCloseFrame(
608 const QuicConnectionCloseFrame& frame) {
609 DCHECK(connected_);
610 if (debug_visitor_) {
611 debug_visitor_->OnConnectionCloseFrame(frame);
613 DVLOG(1) << ENDPOINT << "Connection " << guid() << " closed with error "
614 << QuicUtils::ErrorToString(frame.error_code)
615 << " " << frame.error_details;
616 last_close_frames_.push_back(frame);
617 return connected_;
620 bool QuicConnection::OnGoAwayFrame(const QuicGoAwayFrame& frame) {
621 DCHECK(connected_);
622 DVLOG(1) << ENDPOINT << "Go away received with error "
623 << QuicUtils::ErrorToString(frame.error_code)
624 << " and reason:" << frame.reason_phrase;
625 last_goaway_frames_.push_back(frame);
626 return connected_;
629 void QuicConnection::OnPacketComplete() {
630 // Don't do anything if this packet closed the connection.
631 if (!connected_) {
632 ClearLastFrames();
633 return;
636 DVLOG(1) << ENDPOINT << (last_packet_revived_ ? "Revived" : "Got")
637 << " packet " << last_header_.packet_sequence_number
638 << " with " << last_ack_frames_.size() << " acks, "
639 << last_congestion_frames_.size() << " congestions, "
640 << last_goaway_frames_.size() << " goaways, "
641 << last_rst_frames_.size() << " rsts, "
642 << last_close_frames_.size() << " closes, "
643 << last_stream_frames_.size()
644 << " stream frames for " << last_header_.public_header.guid;
646 // Must called before ack processing, because processing acks removes entries
647 // from unacket_packets_, increasing the least_unacked.
648 const bool last_packet_should_instigate_ack = ShouldLastPacketInstigateAck();
650 // If the incoming packet was missing, send an ack immediately.
651 bool send_ack_immediately = received_packet_manager_.IsMissing(
652 last_header_.packet_sequence_number);
654 // Ensure the visitor can process the stream frames before recording and
655 // processing the rest of the packet.
656 if (last_stream_frames_.empty() ||
657 visitor_->OnStreamFrames(last_stream_frames_)) {
658 received_packet_manager_.RecordPacketReceived(last_size_,
659 last_header_,
660 time_of_last_received_packet_,
661 last_packet_revived_);
662 for (size_t i = 0; i < last_stream_frames_.size(); ++i) {
663 stats_.stream_bytes_received +=
664 last_stream_frames_[i].data.TotalBufferSize();
668 // Process stream resets, then acks, then congestion feedback.
669 for (size_t i = 0; i < last_goaway_frames_.size(); ++i) {
670 visitor_->OnGoAway(last_goaway_frames_[i]);
672 for (size_t i = 0; i < last_rst_frames_.size(); ++i) {
673 visitor_->OnRstStream(last_rst_frames_[i]);
675 for (size_t i = 0; i < last_ack_frames_.size(); ++i) {
676 ProcessAckFrame(last_ack_frames_[i]);
678 for (size_t i = 0; i < last_congestion_frames_.size(); ++i) {
679 sent_packet_manager_.OnIncomingQuicCongestionFeedbackFrame(
680 last_congestion_frames_[i], time_of_last_received_packet_);
682 if (!last_close_frames_.empty()) {
683 CloseConnection(last_close_frames_[0].error_code, true);
684 DCHECK(!connected_);
687 // If there are new missing packets to report, send an ack immediately.
688 if (received_packet_manager_.HasNewMissingPackets()) {
689 send_ack_immediately = true;
692 MaybeSendInResponseToPacket(send_ack_immediately,
693 last_packet_should_instigate_ack);
695 ClearLastFrames();
698 void QuicConnection::ClearLastFrames() {
699 last_stream_frames_.clear();
700 last_goaway_frames_.clear();
701 last_rst_frames_.clear();
702 last_ack_frames_.clear();
703 last_congestion_frames_.clear();
706 QuicAckFrame* QuicConnection::CreateAckFrame() {
707 QuicAckFrame* outgoing_ack = new QuicAckFrame();
708 received_packet_manager_.UpdateReceivedPacketInfo(
709 &(outgoing_ack->received_info), clock_->ApproximateNow());
710 UpdateSentPacketInfo(&(outgoing_ack->sent_info));
711 DVLOG(1) << ENDPOINT << "Creating ack frame: " << *outgoing_ack;
712 return outgoing_ack;
715 QuicCongestionFeedbackFrame* QuicConnection::CreateFeedbackFrame() {
716 return new QuicCongestionFeedbackFrame(outgoing_congestion_feedback_);
719 bool QuicConnection::ShouldLastPacketInstigateAck() {
720 if (!last_stream_frames_.empty() ||
721 !last_goaway_frames_.empty() ||
722 !last_rst_frames_.empty()) {
723 return true;
726 // If the peer is still waiting for a packet that we are no
727 // longer planning to send, we should send an ack to raise
728 // the high water mark.
729 if (!last_ack_frames_.empty() &&
730 !last_ack_frames_.back().received_info.missing_packets.empty()) {
731 return sent_packet_manager_.GetLeastUnackedSentPacket() >
732 *last_ack_frames_.back().received_info.missing_packets.begin();
734 return false;
737 void QuicConnection::MaybeSendInResponseToPacket(
738 bool send_ack_immediately,
739 bool last_packet_should_instigate_ack) {
740 // |include_ack| is false since we decide about ack bundling below.
741 ScopedPacketBundler bundler(this, false);
743 if (last_packet_should_instigate_ack) {
744 // In general, we ack every second packet. When we don't ack the first
745 // packet, we set the delayed ack alarm. Thus, if the ack alarm is set
746 // then we know this is the second packet, and we should send an ack.
747 if (send_ack_immediately || ack_alarm_->IsSet()) {
748 SendAck();
749 DCHECK(!ack_alarm_->IsSet());
750 } else {
751 ack_alarm_->Set(clock_->ApproximateNow().Add(
752 sent_packet_manager_.DelayedAckTime()));
753 DVLOG(1) << "Ack timer set; next packet or timer will trigger ACK.";
757 if (!last_ack_frames_.empty()) {
758 // Now the we have received an ack, we might be able to send packets which
759 // are queued locally, or drain streams which are blocked.
760 QuicTime::Delta delay = sent_packet_manager_.TimeUntilSend(
761 time_of_last_received_packet_, NOT_RETRANSMISSION,
762 HAS_RETRANSMITTABLE_DATA, NOT_HANDSHAKE);
763 if (delay.IsZero()) {
764 send_alarm_->Cancel();
765 WriteIfNotBlocked();
766 } else if (!delay.IsInfinite()) {
767 send_alarm_->Cancel();
768 send_alarm_->Set(time_of_last_received_packet_.Add(delay));
773 void QuicConnection::SendVersionNegotiationPacket() {
774 scoped_ptr<QuicEncryptedPacket> version_packet(
775 packet_creator_.SerializeVersionNegotiationPacket(
776 framer_.supported_versions()));
777 // TODO(satyamshekhar): implement zero server state negotiation.
778 WriteResult result =
779 writer_->WritePacket(version_packet->data(), version_packet->length(),
780 self_address().address(), peer_address(), this);
781 if (result.status == WRITE_STATUS_BLOCKED) {
782 write_blocked_ = true;
784 if (result.status == WRITE_STATUS_OK ||
785 (result.status == WRITE_STATUS_BLOCKED &&
786 writer_->IsWriteBlockedDataBuffered())) {
787 pending_version_negotiation_packet_ = false;
788 return;
790 if (result.status == WRITE_STATUS_ERROR) {
791 // We can't send an error as the socket is presumably borked.
792 CloseConnection(QUIC_PACKET_WRITE_ERROR, false);
794 pending_version_negotiation_packet_ = true;
797 QuicConsumedData QuicConnection::SendStreamData(
798 QuicStreamId id,
799 const IOVector& data,
800 QuicStreamOffset offset,
801 bool fin,
802 QuicAckNotifier::DelegateInterface* delegate) {
803 if (!fin && data.Empty()) {
804 LOG(DFATAL) << "Attempt to send empty stream frame";
807 // This notifier will be owned by the AckNotifierManager (or deleted below if
808 // no data or FIN was consumed).
809 QuicAckNotifier* notifier = NULL;
810 if (delegate) {
811 notifier = new QuicAckNotifier(delegate);
814 // Opportunistically bundle an ack with this outgoing packet, unless it's the
815 // crypto stream.
816 ScopedPacketBundler ack_bundler(this, id != kCryptoStreamId);
817 QuicConsumedData consumed_data =
818 packet_generator_.ConsumeData(id, data, offset, fin, notifier);
820 if (notifier &&
821 (consumed_data.bytes_consumed == 0 && !consumed_data.fin_consumed)) {
822 // No data was consumed, nor was a fin consumed, so delete the notifier.
823 delete notifier;
826 return consumed_data;
829 void QuicConnection::SendRstStream(QuicStreamId id,
830 QuicRstStreamErrorCode error) {
831 DVLOG(1) << "Sending RST_STREAM: " << id << " code: " << error;
832 // Opportunistically bundle an ack with this outgoing packet.
833 ScopedPacketBundler ack_bundler(this, true);
834 packet_generator_.AddControlFrame(
835 QuicFrame(new QuicRstStreamFrame(id, error)));
838 const QuicConnectionStats& QuicConnection::GetStats() {
839 // Update rtt and estimated bandwidth.
840 stats_.rtt = sent_packet_manager_.SmoothedRtt().ToMicroseconds();
841 stats_.estimated_bandwidth =
842 sent_packet_manager_.BandwidthEstimate().ToBytesPerSecond();
843 return stats_;
846 void QuicConnection::ProcessUdpPacket(const IPEndPoint& self_address,
847 const IPEndPoint& peer_address,
848 const QuicEncryptedPacket& packet) {
849 if (!connected_) {
850 return;
852 if (debug_visitor_) {
853 debug_visitor_->OnPacketReceived(self_address, peer_address, packet);
855 last_packet_revived_ = false;
856 last_size_ = packet.length();
858 address_migrating_ = false;
860 if (peer_address_.address().empty()) {
861 peer_address_ = peer_address;
863 if (self_address_.address().empty()) {
864 self_address_ = self_address;
867 if (!(peer_address == peer_address_ && self_address == self_address_)) {
868 address_migrating_ = true;
871 stats_.bytes_received += packet.length();
872 ++stats_.packets_received;
874 if (!framer_.ProcessPacket(packet)) {
875 // If we are unable to decrypt this packet, it might be
876 // because the CHLO or SHLO packet was lost.
877 if (encryption_level_ != ENCRYPTION_FORWARD_SECURE &&
878 framer_.error() == QUIC_DECRYPTION_FAILURE &&
879 undecryptable_packets_.size() < kMaxUndecryptablePackets) {
880 QueueUndecryptablePacket(packet);
882 DVLOG(1) << ENDPOINT << "Unable to process packet. Last packet processed: "
883 << last_header_.packet_sequence_number;
884 return;
886 MaybeProcessUndecryptablePackets();
887 MaybeProcessRevivedPacket();
890 bool QuicConnection::OnCanWrite() {
891 write_blocked_ = false;
892 return DoWrite();
895 bool QuicConnection::WriteIfNotBlocked() {
896 if (write_blocked_) {
897 return false;
899 return DoWrite();
902 bool QuicConnection::DoWrite() {
903 DCHECK(!write_blocked_);
904 WriteQueuedPackets();
906 WritePendingRetransmissions();
908 IsHandshake pending_handshake = visitor_->HasPendingHandshake() ?
909 IS_HANDSHAKE : NOT_HANDSHAKE;
910 // Sending queued packets may have caused the socket to become write blocked,
911 // or the congestion manager to prohibit sending. If we've sent everything
912 // we had queued and we're still not blocked, let the visitor know it can
913 // write more.
914 if (CanWrite(NOT_RETRANSMISSION, HAS_RETRANSMITTABLE_DATA,
915 pending_handshake)) {
916 // Set |include_ack| to false in bundler; ack inclusion happens elsewhere.
917 scoped_ptr<ScopedPacketBundler> bundler(
918 new ScopedPacketBundler(this, false));
919 bool all_bytes_written = visitor_->OnCanWrite();
920 bundler.reset();
921 // After the visitor writes, it may have caused the socket to become write
922 // blocked or the congestion manager to prohibit sending, so check again.
923 pending_handshake = visitor_->HasPendingHandshake() ? IS_HANDSHAKE
924 : NOT_HANDSHAKE;
925 if (!all_bytes_written && !resume_writes_alarm_->IsSet() &&
926 CanWrite(NOT_RETRANSMISSION, HAS_RETRANSMITTABLE_DATA,
927 pending_handshake)) {
928 // We're not write blocked, but some stream didn't write out all of its
929 // bytes. Register for 'immediate' resumption so we'll keep writing after
930 // other quic connections have had a chance to use the socket.
931 resume_writes_alarm_->Set(clock_->ApproximateNow());
935 return !write_blocked_;
938 bool QuicConnection::ProcessValidatedPacket() {
939 if (address_migrating_) {
940 SendConnectionCloseWithDetails(
941 QUIC_ERROR_MIGRATING_ADDRESS,
942 "Address migration is not yet a supported feature");
943 return false;
945 time_of_last_received_packet_ = clock_->Now();
946 DVLOG(1) << ENDPOINT << "time of last received packet: "
947 << time_of_last_received_packet_.ToDebuggingValue();
949 if (is_server_ && encryption_level_ == ENCRYPTION_NONE &&
950 last_size_ > options()->max_packet_length) {
951 options()->max_packet_length = last_size_;
953 return true;
956 bool QuicConnection::WriteQueuedPackets() {
957 DCHECK(!write_blocked_);
959 if (pending_version_negotiation_packet_) {
960 SendVersionNegotiationPacket();
963 QueuedPacketList::iterator packet_iterator = queued_packets_.begin();
964 while (!write_blocked_ && packet_iterator != queued_packets_.end()) {
965 if (WritePacket(packet_iterator->encryption_level,
966 packet_iterator->sequence_number,
967 packet_iterator->packet,
968 packet_iterator->transmission_type,
969 packet_iterator->retransmittable,
970 packet_iterator->handshake,
971 packet_iterator->forced)) {
972 packet_iterator = queued_packets_.erase(packet_iterator);
973 } else {
974 // Continue, because some queued packets may still be writable.
975 // This can happen if a retransmit send fail.
976 ++packet_iterator;
980 return !write_blocked_;
983 void QuicConnection::WritePendingRetransmissions() {
984 // Keep writing as long as there's a pending retransmission which can be
985 // written.
986 while (sent_packet_manager_.HasPendingRetransmissions()) {
987 const QuicSentPacketManager::PendingRetransmission pending =
988 sent_packet_manager_.NextPendingRetransmission();
989 if (HasForcedFrames(&pending.retransmittable_frames) == NO_FORCE &&
990 !CanWrite(pending.transmission_type, HAS_RETRANSMITTABLE_DATA,
991 pending.retransmittable_frames.HasCryptoHandshake())) {
992 break;
995 // Re-packetize the frames with a new sequence number for retransmission.
996 // Retransmitted data packets do not use FEC, even when it's enabled.
997 // Retransmitted packets use the same sequence number length as the
998 // original.
999 // Flush the packet creator before making a new packet.
1000 // TODO(ianswett): Implement ReserializeAllFrames as a separate path that
1001 // does not require the creator to be flushed.
1002 Flush();
1003 SerializedPacket serialized_packet = packet_creator_.ReserializeAllFrames(
1004 pending.retransmittable_frames.frames(),
1005 pending.sequence_number_length);
1007 DVLOG(1) << ENDPOINT << "Retransmitting " << pending.sequence_number
1008 << " as " << serialized_packet.sequence_number;
1009 if (debug_visitor_) {
1010 debug_visitor_->OnPacketRetransmitted(
1011 pending.sequence_number, serialized_packet.sequence_number);
1013 sent_packet_manager_.OnRetransmittedPacket(
1014 pending.sequence_number, serialized_packet.sequence_number);
1016 SendOrQueuePacket(pending.retransmittable_frames.encryption_level(),
1017 serialized_packet,
1018 pending.transmission_type);
1022 void QuicConnection::RetransmitUnackedPackets(
1023 RetransmissionType retransmission_type) {
1024 sent_packet_manager_.RetransmitUnackedPackets(retransmission_type);
1026 WriteIfNotBlocked();
1029 bool QuicConnection::ShouldGeneratePacket(
1030 TransmissionType transmission_type,
1031 HasRetransmittableData retransmittable,
1032 IsHandshake handshake) {
1033 // We should serialize handshake packets immediately to ensure that they
1034 // end up sent at the right encryption level.
1035 if (handshake == IS_HANDSHAKE) {
1036 return true;
1039 return CanWrite(transmission_type, retransmittable, handshake);
1042 bool QuicConnection::CanWrite(TransmissionType transmission_type,
1043 HasRetransmittableData retransmittable,
1044 IsHandshake handshake) {
1045 if (write_blocked_) {
1046 return false;
1049 // TODO(rch): consider removing this check so that if an ACK comes in
1050 // before the alarm goes it, we might be able send out a packet.
1051 // This check assumes that if the send alarm is set, it applies equally to all
1052 // types of transmissions.
1053 if (send_alarm_->IsSet()) {
1054 DVLOG(1) << "Send alarm set. Not sending.";
1055 return false;
1058 QuicTime now = clock_->Now();
1059 QuicTime::Delta delay = sent_packet_manager_.TimeUntilSend(
1060 now, transmission_type, retransmittable, handshake);
1061 if (delay.IsInfinite()) {
1062 return false;
1065 // If the scheduler requires a delay, then we can not send this packet now.
1066 if (!delay.IsZero()) {
1067 send_alarm_->Cancel();
1068 send_alarm_->Set(now.Add(delay));
1069 DVLOG(1) << "Delaying sending.";
1070 return false;
1072 return true;
1075 bool QuicConnection::WritePacket(EncryptionLevel level,
1076 QuicPacketSequenceNumber sequence_number,
1077 QuicPacket* packet,
1078 TransmissionType transmission_type,
1079 HasRetransmittableData retransmittable,
1080 IsHandshake handshake,
1081 Force forced) {
1082 if (ShouldDiscardPacket(level, sequence_number, retransmittable)) {
1083 delete packet;
1084 return true;
1087 // If we're write blocked, we know we can't write.
1088 if (write_blocked_) {
1089 return false;
1092 // If we are not forced and we can't write, then simply return false;
1093 if (forced == NO_FORCE &&
1094 !CanWrite(transmission_type, retransmittable, handshake)) {
1095 return false;
1098 // Some encryption algorithms require the packet sequence numbers not be
1099 // repeated.
1100 DCHECK_LE(sequence_number_of_last_inorder_packet_, sequence_number);
1101 // Only increase this when packets have not been queued. Once they're queued
1102 // due to a write block, there is the chance of sending forced and other
1103 // higher priority packets out of order.
1104 if (queued_packets_.empty()) {
1105 sequence_number_of_last_inorder_packet_ = sequence_number;
1108 scoped_ptr<QuicEncryptedPacket> encrypted(
1109 framer_.EncryptPacket(level, sequence_number, *packet));
1110 if (encrypted.get() == NULL) {
1111 LOG(DFATAL) << ENDPOINT << "Failed to encrypt packet number "
1112 << sequence_number;
1113 CloseConnection(QUIC_ENCRYPTION_FAILURE, false);
1114 return false;
1117 // If it's the ConnectionClose packet, the only FORCED frame type,
1118 // clone a copy for resending later by the TimeWaitListManager.
1119 if (forced == FORCE) {
1120 DCHECK(connection_close_packet_.get() == NULL);
1121 connection_close_packet_.reset(encrypted->Clone());
1124 if (encrypted->length() > options()->max_packet_length) {
1125 LOG(DFATAL) << "Writing an encrypted packet larger than max_packet_length:"
1126 << options()->max_packet_length << " encrypted length: "
1127 << encrypted->length();
1129 DVLOG(1) << ENDPOINT << "Sending packet number " << sequence_number
1130 << " : " << (packet->is_fec_packet() ? "FEC " :
1131 (retransmittable == HAS_RETRANSMITTABLE_DATA
1132 ? "data bearing " : " ack only "))
1133 << ", encryption level: "
1134 << QuicUtils::EncryptionLevelToString(level)
1135 << ", length:" << packet->length() << ", encrypted length:"
1136 << encrypted->length();
1137 DVLOG(2) << ENDPOINT << "packet(" << sequence_number << "): " << std::endl
1138 << QuicUtils::StringToHexASCIIDump(packet->AsStringPiece());
1140 DCHECK(encrypted->length() <= kMaxPacketSize)
1141 << "Packet " << sequence_number << " will not be read; too large: "
1142 << packet->length() << " " << encrypted->length() << " "
1143 << " forced: " << (forced == FORCE ? "yes" : "no");
1145 DCHECK(pending_write_.get() == NULL);
1146 pending_write_.reset(new PendingWrite(sequence_number, transmission_type,
1147 retransmittable, level,
1148 packet->is_fec_packet(),
1149 packet->length()));
1151 WriteResult result =
1152 writer_->WritePacket(encrypted->data(), encrypted->length(),
1153 self_address().address(), peer_address(), this);
1154 if (result.error_code == ERR_IO_PENDING) {
1155 DCHECK_EQ(WRITE_STATUS_BLOCKED, result.status);
1157 if (debug_visitor_) {
1158 // Pass the write result to the visitor.
1159 debug_visitor_->OnPacketSent(sequence_number, level, *encrypted, result);
1161 if (result.status == WRITE_STATUS_BLOCKED) {
1162 // TODO(satyashekhar): It might be more efficient (fewer system calls), if
1163 // all connections share this variable i.e this becomes a part of
1164 // PacketWriterInterface.
1165 write_blocked_ = true;
1166 // If the socket buffers the the data, then the packet should not
1167 // be queued and sent again, which would result in an unnecessary
1168 // duplicate packet being sent. The helper must call OnPacketSent
1169 // when the packet is actually sent.
1170 if (writer_->IsWriteBlockedDataBuffered()) {
1171 delete packet;
1172 return true;
1174 pending_write_.reset();
1175 return false;
1178 if (OnPacketSent(result)) {
1179 delete packet;
1180 return true;
1182 return false;
1185 bool QuicConnection::ShouldDiscardPacket(
1186 EncryptionLevel level,
1187 QuicPacketSequenceNumber sequence_number,
1188 HasRetransmittableData retransmittable) {
1189 if (!connected_) {
1190 DVLOG(1) << ENDPOINT
1191 << "Not sending packet as connection is disconnected.";
1192 return true;
1195 if (encryption_level_ == ENCRYPTION_FORWARD_SECURE &&
1196 level == ENCRYPTION_NONE) {
1197 // Drop packets that are NULL encrypted since the peer won't accept them
1198 // anymore.
1199 DVLOG(1) << ENDPOINT << "Dropping packet: " << sequence_number
1200 << " since the packet is NULL encrypted.";
1201 sent_packet_manager_.DiscardUnackedPacket(sequence_number);
1202 return true;
1205 if (retransmittable == HAS_RETRANSMITTABLE_DATA) {
1206 if (!sent_packet_manager_.IsUnacked(sequence_number)) {
1207 // This is a crazy edge case, but if we retransmit a packet,
1208 // (but have to queue it for some reason) then receive an ack
1209 // for the previous transmission (but not the retransmission)
1210 // then receive a truncated ACK which causes us to raise the
1211 // high water mark, all before we're able to send the packet
1212 // then we can simply drop it.
1213 DVLOG(1) << ENDPOINT << "Dropping packet: " << sequence_number
1214 << " since it has already been acked.";
1215 return true;
1218 if (sent_packet_manager_.IsPreviousTransmission(sequence_number)) {
1219 // If somehow we have already retransmitted this packet *before*
1220 // we actually send it for the first time (I think this is probably
1221 // impossible in the real world), then don't bother sending it.
1222 // We don't want to call DiscardUnackedPacket because in this case
1223 // the peer has not yet ACK'd the data. We need the subsequent
1224 // retransmission to be sent.
1225 DVLOG(1) << ENDPOINT << "Dropping packet: " << sequence_number
1226 << " since it has already been retransmitted.";
1227 return true;
1230 if (!sent_packet_manager_.HasRetransmittableFrames(sequence_number)) {
1231 DVLOG(1) << ENDPOINT << "Dropping packet: " << sequence_number
1232 << " since a previous transmission has been acked.";
1233 sent_packet_manager_.DiscardUnackedPacket(sequence_number);
1234 return true;
1238 return false;
1241 bool QuicConnection::OnPacketSent(WriteResult result) {
1242 DCHECK_NE(WRITE_STATUS_BLOCKED, result.status);
1243 if (pending_write_.get() == NULL) {
1244 LOG(DFATAL) << "OnPacketSent called without a pending write.";
1245 return false;
1248 QuicPacketSequenceNumber sequence_number = pending_write_->sequence_number;
1249 TransmissionType transmission_type = pending_write_->transmission_type;
1250 HasRetransmittableData retransmittable = pending_write_->retransmittable;
1251 size_t length = pending_write_->length;
1252 pending_write_.reset();
1254 if (result.status == WRITE_STATUS_ERROR) {
1255 DVLOG(1) << "Write failed with error code: " << result.error_code;
1256 // We can't send an error as the socket is presumably borked.
1257 CloseConnection(QUIC_PACKET_WRITE_ERROR, false);
1258 return false;
1261 QuicTime now = clock_->Now();
1262 if (transmission_type == NOT_RETRANSMISSION) {
1263 time_of_last_sent_new_packet_ = now;
1265 DVLOG(1) << ENDPOINT << "time of last sent packet: "
1266 << now.ToDebuggingValue();
1268 // TODO(ianswett): Change the sequence number length and other packet creator
1269 // options by a more explicit API than setting a struct value directly.
1270 packet_creator_.UpdateSequenceNumberLength(
1271 received_packet_manager_.least_packet_awaited_by_peer(),
1272 sent_packet_manager_.BandwidthEstimate().ToBytesPerPeriod(
1273 sent_packet_manager_.SmoothedRtt()));
1275 bool reset_retransmission_alarm =
1276 sent_packet_manager_.OnPacketSent(sequence_number, now, length,
1277 transmission_type, retransmittable);
1279 if (reset_retransmission_alarm || !retransmission_alarm_->IsSet()) {
1280 retransmission_alarm_->Cancel();
1281 QuicTime retransmission_time = sent_packet_manager_.GetRetransmissionTime();
1282 if (retransmission_time != QuicTime::Zero()) {
1283 retransmission_alarm_->Set(retransmission_time);
1287 stats_.bytes_sent += result.bytes_written;
1288 ++stats_.packets_sent;
1290 if (transmission_type == NACK_RETRANSMISSION ||
1291 transmission_type == RTO_RETRANSMISSION) {
1292 stats_.bytes_retransmitted += result.bytes_written;
1293 ++stats_.packets_retransmitted;
1296 return true;
1299 bool QuicConnection::OnSerializedPacket(
1300 const SerializedPacket& serialized_packet) {
1301 if (serialized_packet.retransmittable_frames) {
1302 serialized_packet.retransmittable_frames->
1303 set_encryption_level(encryption_level_);
1305 sent_packet_manager_.OnSerializedPacket(serialized_packet);
1306 // The TransmissionType is NOT_RETRANSMISSION because all retransmissions
1307 // serialize packets and invoke SendOrQueuePacket directly.
1308 return SendOrQueuePacket(encryption_level_,
1309 serialized_packet,
1310 NOT_RETRANSMISSION);
1313 QuicPacketSequenceNumber QuicConnection::GetNextPacketSequenceNumber() {
1314 return packet_creator_.sequence_number() + 1;
1317 bool QuicConnection::SendOrQueuePacket(EncryptionLevel level,
1318 const SerializedPacket& packet,
1319 TransmissionType transmission_type) {
1320 IsHandshake handshake = packet.retransmittable_frames == NULL ?
1321 NOT_HANDSHAKE : packet.retransmittable_frames->HasCryptoHandshake();
1322 Force forced = HasForcedFrames(packet.retransmittable_frames);
1323 HasRetransmittableData retransmittable =
1324 (transmission_type != NOT_RETRANSMISSION ||
1325 packet.retransmittable_frames != NULL) ?
1326 HAS_RETRANSMITTABLE_DATA : NO_RETRANSMITTABLE_DATA;
1327 sent_entropy_manager_.RecordPacketEntropyHash(packet.sequence_number,
1328 packet.entropy_hash);
1329 if (WritePacket(level, packet.sequence_number, packet.packet,
1330 transmission_type, retransmittable, handshake, forced)) {
1331 return true;
1333 queued_packets_.push_back(QueuedPacket(packet.sequence_number, packet.packet,
1334 level, transmission_type,
1335 retransmittable, handshake, forced));
1336 return false;
1339 void QuicConnection::UpdateSentPacketInfo(SentPacketInfo* sent_info) {
1340 sent_info->least_unacked = sent_packet_manager_.GetLeastUnackedSentPacket();
1341 sent_info->entropy_hash = sent_entropy_manager_.EntropyHash(
1342 sent_info->least_unacked - 1);
1345 void QuicConnection::SendAck() {
1346 ack_alarm_->Cancel();
1347 // TODO(rch): delay this until the CreateFeedbackFrame
1348 // method is invoked. This requires changes SetShouldSendAck
1349 // to be a no-arg method, and re-jiggering its implementation.
1350 bool send_feedback = false;
1351 if (received_packet_manager_.GenerateCongestionFeedback(
1352 &outgoing_congestion_feedback_)) {
1353 DVLOG(1) << ENDPOINT << "Sending feedback: "
1354 << outgoing_congestion_feedback_;
1355 send_feedback = true;
1358 packet_generator_.SetShouldSendAck(send_feedback);
1361 void QuicConnection::OnRetransmissionTimeout() {
1362 if (!sent_packet_manager_.HasUnackedPackets()) {
1363 return;
1366 ++stats_.rto_count;
1368 sent_packet_manager_.OnRetransmissionTimeout();
1370 WriteIfNotBlocked();
1372 // Ensure the retransmission alarm is always set if there are unacked packets.
1373 if (!HasQueuedData() && !retransmission_alarm_->IsSet()) {
1374 QuicTime rto_timeout = sent_packet_manager_.GetRetransmissionTime();
1375 if (rto_timeout != QuicTime::Zero()) {
1376 retransmission_alarm_->Set(rto_timeout);
1381 void QuicConnection::SetEncrypter(EncryptionLevel level,
1382 QuicEncrypter* encrypter) {
1383 framer_.SetEncrypter(level, encrypter);
1386 const QuicEncrypter* QuicConnection::encrypter(EncryptionLevel level) const {
1387 return framer_.encrypter(level);
1390 void QuicConnection::SetDefaultEncryptionLevel(
1391 EncryptionLevel level) {
1392 encryption_level_ = level;
1395 void QuicConnection::SetDecrypter(QuicDecrypter* decrypter) {
1396 framer_.SetDecrypter(decrypter);
1399 void QuicConnection::SetAlternativeDecrypter(QuicDecrypter* decrypter,
1400 bool latch_once_used) {
1401 framer_.SetAlternativeDecrypter(decrypter, latch_once_used);
1404 const QuicDecrypter* QuicConnection::decrypter() const {
1405 return framer_.decrypter();
1408 const QuicDecrypter* QuicConnection::alternative_decrypter() const {
1409 return framer_.alternative_decrypter();
1412 void QuicConnection::QueueUndecryptablePacket(
1413 const QuicEncryptedPacket& packet) {
1414 DVLOG(1) << ENDPOINT << "Queueing undecryptable packet.";
1415 undecryptable_packets_.push_back(packet.Clone());
1418 void QuicConnection::MaybeProcessUndecryptablePackets() {
1419 if (undecryptable_packets_.empty() ||
1420 encryption_level_ == ENCRYPTION_NONE) {
1421 return;
1424 while (connected_ && !undecryptable_packets_.empty()) {
1425 DVLOG(1) << ENDPOINT << "Attempting to process undecryptable packet";
1426 QuicEncryptedPacket* packet = undecryptable_packets_.front();
1427 if (!framer_.ProcessPacket(*packet) &&
1428 framer_.error() == QUIC_DECRYPTION_FAILURE) {
1429 DVLOG(1) << ENDPOINT << "Unable to process undecryptable packet...";
1430 break;
1432 DVLOG(1) << ENDPOINT << "Processed undecryptable packet!";
1433 delete packet;
1434 undecryptable_packets_.pop_front();
1437 // Once forward secure encryption is in use, there will be no
1438 // new keys installed and hence any undecryptable packets will
1439 // never be able to be decrypted.
1440 if (encryption_level_ == ENCRYPTION_FORWARD_SECURE) {
1441 STLDeleteElements(&undecryptable_packets_);
1445 void QuicConnection::MaybeProcessRevivedPacket() {
1446 QuicFecGroup* group = GetFecGroup();
1447 if (!connected_ || group == NULL || !group->CanRevive()) {
1448 return;
1450 QuicPacketHeader revived_header;
1451 char revived_payload[kMaxPacketSize];
1452 size_t len = group->Revive(&revived_header, revived_payload, kMaxPacketSize);
1453 revived_header.public_header.guid = guid_;
1454 revived_header.public_header.version_flag = false;
1455 revived_header.public_header.reset_flag = false;
1456 revived_header.fec_flag = false;
1457 revived_header.is_in_fec_group = NOT_IN_FEC_GROUP;
1458 revived_header.fec_group = 0;
1459 group_map_.erase(last_header_.fec_group);
1460 delete group;
1462 last_packet_revived_ = true;
1463 if (debug_visitor_) {
1464 debug_visitor_->OnRevivedPacket(revived_header,
1465 StringPiece(revived_payload, len));
1468 ++stats_.packets_revived;
1469 framer_.ProcessRevivedPacket(&revived_header,
1470 StringPiece(revived_payload, len));
1473 QuicFecGroup* QuicConnection::GetFecGroup() {
1474 QuicFecGroupNumber fec_group_num = last_header_.fec_group;
1475 if (fec_group_num == 0) {
1476 return NULL;
1478 if (group_map_.count(fec_group_num) == 0) {
1479 if (group_map_.size() >= kMaxFecGroups) { // Too many groups
1480 if (fec_group_num < group_map_.begin()->first) {
1481 // The group being requested is a group we've seen before and deleted.
1482 // Don't recreate it.
1483 return NULL;
1485 // Clear the lowest group number.
1486 delete group_map_.begin()->second;
1487 group_map_.erase(group_map_.begin());
1489 group_map_[fec_group_num] = new QuicFecGroup();
1491 return group_map_[fec_group_num];
1494 void QuicConnection::SendConnectionClose(QuicErrorCode error) {
1495 SendConnectionCloseWithDetails(error, string());
1498 void QuicConnection::SendConnectionCloseWithDetails(QuicErrorCode error,
1499 const string& details) {
1500 if (!write_blocked_) {
1501 SendConnectionClosePacket(error, details);
1503 CloseConnection(error, false);
1506 void QuicConnection::SendConnectionClosePacket(QuicErrorCode error,
1507 const string& details) {
1508 DVLOG(1) << ENDPOINT << "Force closing " << guid() << " with error "
1509 << QuicUtils::ErrorToString(error) << " (" << error << ") "
1510 << details;
1511 ScopedPacketBundler ack_bundler(this, true);
1512 QuicConnectionCloseFrame* frame = new QuicConnectionCloseFrame();
1513 frame->error_code = error;
1514 frame->error_details = details;
1515 packet_generator_.AddControlFrame(QuicFrame(frame));
1516 Flush();
1519 void QuicConnection::CloseConnection(QuicErrorCode error, bool from_peer) {
1520 DCHECK(connected_);
1521 connected_ = false;
1522 visitor_->OnConnectionClosed(error, from_peer);
1523 // Cancel the alarms so they don't trigger any action now that the
1524 // connection is closed.
1525 ack_alarm_->Cancel();
1526 resume_writes_alarm_->Cancel();
1527 retransmission_alarm_->Cancel();
1528 send_alarm_->Cancel();
1529 timeout_alarm_->Cancel();
1532 void QuicConnection::SendGoAway(QuicErrorCode error,
1533 QuicStreamId last_good_stream_id,
1534 const string& reason) {
1535 DVLOG(1) << ENDPOINT << "Going away with error "
1536 << QuicUtils::ErrorToString(error)
1537 << " (" << error << ")";
1539 // Opportunistically bundle an ack with this outgoing packet.
1540 ScopedPacketBundler ack_bundler(this, true);
1541 packet_generator_.AddControlFrame(
1542 QuicFrame(new QuicGoAwayFrame(error, last_good_stream_id, reason)));
1545 void QuicConnection::CloseFecGroupsBefore(
1546 QuicPacketSequenceNumber sequence_number) {
1547 FecGroupMap::iterator it = group_map_.begin();
1548 while (it != group_map_.end()) {
1549 // If this is the current group or the group doesn't protect this packet
1550 // we can ignore it.
1551 if (last_header_.fec_group == it->first ||
1552 !it->second->ProtectsPacketsBefore(sequence_number)) {
1553 ++it;
1554 continue;
1556 QuicFecGroup* fec_group = it->second;
1557 DCHECK(!fec_group->CanRevive());
1558 FecGroupMap::iterator next = it;
1559 ++next;
1560 group_map_.erase(it);
1561 delete fec_group;
1562 it = next;
1566 void QuicConnection::Flush() {
1567 packet_generator_.FlushAllQueuedFrames();
1570 bool QuicConnection::HasQueuedData() const {
1571 return pending_version_negotiation_packet_ ||
1572 !queued_packets_.empty() || packet_generator_.HasQueuedFrames();
1575 void QuicConnection::SetIdleNetworkTimeout(QuicTime::Delta timeout) {
1576 if (timeout < idle_network_timeout_) {
1577 idle_network_timeout_ = timeout;
1578 CheckForTimeout();
1579 } else {
1580 idle_network_timeout_ = timeout;
1584 void QuicConnection::SetOverallConnectionTimeout(QuicTime::Delta timeout) {
1585 if (timeout < overall_connection_timeout_) {
1586 overall_connection_timeout_ = timeout;
1587 CheckForTimeout();
1588 } else {
1589 overall_connection_timeout_ = timeout;
1593 bool QuicConnection::CheckForTimeout() {
1594 QuicTime now = clock_->ApproximateNow();
1595 QuicTime time_of_last_packet = std::max(time_of_last_received_packet_,
1596 time_of_last_sent_new_packet_);
1598 // |delta| can be < 0 as |now| is approximate time but |time_of_last_packet|
1599 // is accurate time. However, this should not change the behavior of
1600 // timeout handling.
1601 QuicTime::Delta delta = now.Subtract(time_of_last_packet);
1602 DVLOG(1) << ENDPOINT << "last packet "
1603 << time_of_last_packet.ToDebuggingValue()
1604 << " now:" << now.ToDebuggingValue()
1605 << " delta:" << delta.ToMicroseconds()
1606 << " network_timeout: " << idle_network_timeout_.ToMicroseconds();
1607 if (delta >= idle_network_timeout_) {
1608 DVLOG(1) << ENDPOINT << "Connection timedout due to no network activity.";
1609 SendConnectionClose(QUIC_CONNECTION_TIMED_OUT);
1610 return true;
1613 // Next timeout delta.
1614 QuicTime::Delta timeout = idle_network_timeout_.Subtract(delta);
1616 if (!overall_connection_timeout_.IsInfinite()) {
1617 QuicTime::Delta connected_time = now.Subtract(creation_time_);
1618 DVLOG(1) << ENDPOINT << "connection time: "
1619 << connected_time.ToMilliseconds() << " overall timeout: "
1620 << overall_connection_timeout_.ToMilliseconds();
1621 if (connected_time >= overall_connection_timeout_) {
1622 DVLOG(1) << ENDPOINT <<
1623 "Connection timedout due to overall connection timeout.";
1624 SendConnectionClose(QUIC_CONNECTION_TIMED_OUT);
1625 return true;
1628 // Take the min timeout.
1629 QuicTime::Delta connection_timeout =
1630 overall_connection_timeout_.Subtract(connected_time);
1631 if (connection_timeout < timeout) {
1632 timeout = connection_timeout;
1636 timeout_alarm_->Cancel();
1637 timeout_alarm_->Set(clock_->ApproximateNow().Add(timeout));
1638 return false;
1641 QuicConnection::ScopedPacketBundler::ScopedPacketBundler(
1642 QuicConnection* connection,
1643 bool include_ack)
1644 : connection_(connection),
1645 already_in_batch_mode_(connection->packet_generator_.InBatchMode()) {
1646 // Move generator into batch mode. If caller wants us to include an ack,
1647 // check the delayed-ack timer to see if there's ack info to be sent.
1648 if (!already_in_batch_mode_) {
1649 DVLOG(1) << "Entering Batch Mode.";
1650 connection_->packet_generator_.StartBatchOperations();
1652 if (include_ack && connection_->ack_alarm_->IsSet()) {
1653 DVLOG(1) << "Bundling ack with outgoing packet.";
1654 connection_->SendAck();
1658 QuicConnection::ScopedPacketBundler::~ScopedPacketBundler() {
1659 // If we changed the generator's batch state, restore original batch state.
1660 if (!already_in_batch_mode_) {
1661 DVLOG(1) << "Leaving Batch Mode.";
1662 connection_->packet_generator_.FinishBatchOperations();
1664 DCHECK_EQ(already_in_batch_mode_,
1665 connection_->packet_generator_.InBatchMode());
1668 } // namespace net