Upstream version 7.36.149.0
[platform/framework/web/crosswalk.git] / src / net / quic / quic_connection.cc
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.
4
5 #include "net/quic/quic_connection.h"
6
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>
15
16 #include "base/debug/stack_trace.h"
17 #include "base/logging.h"
18 #include "base/stl_util.h"
19 #include "net/base/net_errors.h"
20 #include "net/quic/crypto/quic_decrypter.h"
21 #include "net/quic/crypto/quic_encrypter.h"
22 #include "net/quic/iovector.h"
23 #include "net/quic/quic_bandwidth.h"
24 #include "net/quic/quic_config.h"
25 #include "net/quic/quic_flags.h"
26 #include "net/quic/quic_flow_controller.h"
27 #include "net/quic/quic_utils.h"
28
29 using base::hash_map;
30 using base::hash_set;
31 using base::StringPiece;
32 using std::list;
33 using std::make_pair;
34 using std::min;
35 using std::max;
36 using std::numeric_limits;
37 using std::vector;
38 using std::set;
39 using std::string;
40
41 namespace net {
42
43 class QuicDecrypter;
44 class QuicEncrypter;
45
46 namespace {
47
48 // The largest gap in packets we'll accept without closing the connection.
49 // This will likely have to be tuned.
50 const QuicPacketSequenceNumber kMaxPacketGap = 5000;
51
52 // Limit the number of FEC groups to two.  If we get enough out of order packets
53 // that this becomes limiting, we can revisit.
54 const size_t kMaxFecGroups = 2;
55
56 // Limit the number of undecryptable packets we buffer in
57 // expectation of the CHLO/SHLO arriving.
58 const size_t kMaxUndecryptablePackets = 10;
59
60 bool Near(QuicPacketSequenceNumber a, QuicPacketSequenceNumber b) {
61   QuicPacketSequenceNumber delta = (a > b) ? a - b : b - a;
62   return delta <= kMaxPacketGap;
63 }
64
65 // An alarm that is scheduled to send an ack if a timeout occurs.
66 class AckAlarm : public QuicAlarm::Delegate {
67  public:
68   explicit AckAlarm(QuicConnection* connection)
69       : connection_(connection) {
70   }
71
72   virtual QuicTime OnAlarm() OVERRIDE {
73     connection_->SendAck();
74     return QuicTime::Zero();
75   }
76
77  private:
78   QuicConnection* connection_;
79
80   DISALLOW_COPY_AND_ASSIGN(AckAlarm);
81 };
82
83 // This alarm will be scheduled any time a data-bearing packet is sent out.
84 // When the alarm goes off, the connection checks to see if the oldest packets
85 // have been acked, and retransmit them if they have not.
86 class RetransmissionAlarm : public QuicAlarm::Delegate {
87  public:
88   explicit RetransmissionAlarm(QuicConnection* connection)
89       : connection_(connection) {
90   }
91
92   virtual QuicTime OnAlarm() OVERRIDE {
93     connection_->OnRetransmissionTimeout();
94     return QuicTime::Zero();
95   }
96
97  private:
98   QuicConnection* connection_;
99
100   DISALLOW_COPY_AND_ASSIGN(RetransmissionAlarm);
101 };
102
103 // An alarm that is scheduled when the sent scheduler requires a
104 // a delay before sending packets and fires when the packet may be sent.
105 class SendAlarm : public QuicAlarm::Delegate {
106  public:
107   explicit SendAlarm(QuicConnection* connection)
108       : connection_(connection) {
109   }
110
111   virtual QuicTime OnAlarm() OVERRIDE {
112     connection_->WriteIfNotBlocked();
113     // Never reschedule the alarm, since CanWrite does that.
114     return QuicTime::Zero();
115   }
116
117  private:
118   QuicConnection* connection_;
119
120   DISALLOW_COPY_AND_ASSIGN(SendAlarm);
121 };
122
123 class TimeoutAlarm : public QuicAlarm::Delegate {
124  public:
125   explicit TimeoutAlarm(QuicConnection* connection)
126       : connection_(connection) {
127   }
128
129   virtual QuicTime OnAlarm() OVERRIDE {
130     connection_->CheckForTimeout();
131     // Never reschedule the alarm, since CheckForTimeout does that.
132     return QuicTime::Zero();
133   }
134
135  private:
136   QuicConnection* connection_;
137
138   DISALLOW_COPY_AND_ASSIGN(TimeoutAlarm);
139 };
140
141 class PingAlarm : public QuicAlarm::Delegate {
142  public:
143   explicit PingAlarm(QuicConnection* connection)
144       : connection_(connection) {
145   }
146
147   virtual QuicTime OnAlarm() OVERRIDE {
148     connection_->SendPing();
149     return QuicTime::Zero();
150   }
151
152  private:
153   QuicConnection* connection_;
154
155   DISALLOW_COPY_AND_ASSIGN(PingAlarm);
156 };
157
158 QuicConnection::PacketType GetPacketType(
159     const RetransmittableFrames* retransmittable_frames) {
160   if (!retransmittable_frames) {
161     return QuicConnection::NORMAL;
162   }
163   for (size_t i = 0; i < retransmittable_frames->frames().size(); ++i) {
164     if (retransmittable_frames->frames()[i].type == CONNECTION_CLOSE_FRAME) {
165       return QuicConnection::CONNECTION_CLOSE;
166     }
167   }
168   return QuicConnection::NORMAL;
169 }
170
171 }  // namespace
172
173 QuicConnection::QueuedPacket::QueuedPacket(SerializedPacket packet,
174                                            EncryptionLevel level,
175                                            TransmissionType transmission_type)
176   : sequence_number(packet.sequence_number),
177     packet(packet.packet),
178     encryption_level(level),
179     transmission_type(transmission_type),
180     retransmittable((transmission_type != NOT_RETRANSMISSION ||
181                      packet.retransmittable_frames != NULL) ?
182                          HAS_RETRANSMITTABLE_DATA : NO_RETRANSMITTABLE_DATA),
183     handshake(packet.retransmittable_frames == NULL ?
184       NOT_HANDSHAKE : packet.retransmittable_frames->HasCryptoHandshake()),
185     type(GetPacketType(packet.retransmittable_frames)),
186     length(packet.packet->length()) {
187 }
188
189 #define ENDPOINT (is_server_ ? "Server: " : " Client: ")
190
191 QuicConnection::QuicConnection(QuicConnectionId connection_id,
192                                IPEndPoint address,
193                                QuicConnectionHelperInterface* helper,
194                                QuicPacketWriter* writer,
195                                bool is_server,
196                                const QuicVersionVector& supported_versions,
197                                uint32 max_flow_control_receive_window_bytes)
198     : framer_(supported_versions, helper->GetClock()->ApproximateNow(),
199               is_server),
200       helper_(helper),
201       writer_(writer),
202       encryption_level_(ENCRYPTION_NONE),
203       clock_(helper->GetClock()),
204       random_generator_(helper->GetRandomGenerator()),
205       connection_id_(connection_id),
206       peer_address_(address),
207       last_packet_revived_(false),
208       last_size_(0),
209       last_decrypted_packet_level_(ENCRYPTION_NONE),
210       largest_seen_packet_with_ack_(0),
211       largest_seen_packet_with_stop_waiting_(0),
212       pending_version_negotiation_packet_(false),
213       received_packet_manager_(kTCP, &stats_),
214       ack_queued_(false),
215       stop_waiting_count_(0),
216       ack_alarm_(helper->CreateAlarm(new AckAlarm(this))),
217       retransmission_alarm_(helper->CreateAlarm(new RetransmissionAlarm(this))),
218       send_alarm_(helper->CreateAlarm(new SendAlarm(this))),
219       resume_writes_alarm_(helper->CreateAlarm(new SendAlarm(this))),
220       timeout_alarm_(helper->CreateAlarm(new TimeoutAlarm(this))),
221       ping_alarm_(helper->CreateAlarm(new PingAlarm(this))),
222       debug_visitor_(NULL),
223       packet_creator_(connection_id_, &framer_, random_generator_, is_server),
224       packet_generator_(this, NULL, &packet_creator_),
225       idle_network_timeout_(
226           QuicTime::Delta::FromSeconds(kDefaultInitialTimeoutSecs)),
227       overall_connection_timeout_(QuicTime::Delta::Infinite()),
228       time_of_last_received_packet_(clock_->ApproximateNow()),
229       time_of_last_sent_new_packet_(clock_->ApproximateNow()),
230       sequence_number_of_last_sent_packet_(0),
231       sent_packet_manager_(
232           is_server, clock_, &stats_, kTCP,
233           FLAGS_quic_use_time_loss_detection ? kTime : kNack),
234       version_negotiation_state_(START_NEGOTIATION),
235       is_server_(is_server),
236       connected_(true),
237       address_migrating_(false),
238       max_flow_control_receive_window_bytes_(
239           max_flow_control_receive_window_bytes) {
240   if (max_flow_control_receive_window_bytes_ < kDefaultFlowControlSendWindow) {
241     DLOG(ERROR) << "Initial receive window ("
242                 << max_flow_control_receive_window_bytes_
243                 << ") cannot be set lower than default ("
244                 << kDefaultFlowControlSendWindow << ").";
245     max_flow_control_receive_window_bytes_ = kDefaultFlowControlSendWindow;
246   }
247
248   flow_controller_.reset(new QuicFlowController(
249       supported_versions.front(), 0, is_server_,
250       kDefaultFlowControlSendWindow, max_flow_control_receive_window_bytes_,
251       max_flow_control_receive_window_bytes_));
252
253   if (!is_server_) {
254     // Pacing will be enabled if the client negotiates it.
255     sent_packet_manager_.MaybeEnablePacing();
256   }
257   DVLOG(1) << ENDPOINT << "Created connection with connection_id: "
258            << connection_id;
259   timeout_alarm_->Set(clock_->ApproximateNow().Add(idle_network_timeout_));
260   framer_.set_visitor(this);
261   framer_.set_received_entropy_calculator(&received_packet_manager_);
262   stats_.connection_creation_time = clock_->ApproximateNow();
263 }
264
265 QuicConnection::~QuicConnection() {
266   STLDeleteElements(&undecryptable_packets_);
267   STLDeleteValues(&group_map_);
268   for (QueuedPacketList::iterator it = queued_packets_.begin();
269        it != queued_packets_.end(); ++it) {
270     delete it->packet;
271   }
272 }
273
274 void QuicConnection::SetFromConfig(const QuicConfig& config) {
275   SetIdleNetworkTimeout(config.idle_connection_state_lifetime());
276   sent_packet_manager_.SetFromConfig(config);
277   // TODO(satyamshekhar): Set congestion control and ICSL also.
278 }
279
280 bool QuicConnection::SelectMutualVersion(
281     const QuicVersionVector& available_versions) {
282   // Try to find the highest mutual version by iterating over supported
283   // versions, starting with the highest, and breaking out of the loop once we
284   // find a matching version in the provided available_versions vector.
285   const QuicVersionVector& supported_versions = framer_.supported_versions();
286   for (size_t i = 0; i < supported_versions.size(); ++i) {
287     const QuicVersion& version = supported_versions[i];
288     if (std::find(available_versions.begin(), available_versions.end(),
289                   version) != available_versions.end()) {
290       framer_.set_version(version);
291       return true;
292     }
293   }
294
295   return false;
296 }
297
298 void QuicConnection::OnError(QuicFramer* framer) {
299   // Packets that we cannot decrypt are dropped.
300   // TODO(rch): add stats to measure this.
301   if (!connected_ || framer->error() == QUIC_DECRYPTION_FAILURE) {
302     return;
303   }
304   SendConnectionCloseWithDetails(framer->error(), framer->detailed_error());
305 }
306
307 void QuicConnection::OnPacket() {
308   DCHECK(last_stream_frames_.empty() &&
309          last_goaway_frames_.empty() &&
310          last_window_update_frames_.empty() &&
311          last_blocked_frames_.empty() &&
312          last_rst_frames_.empty() &&
313          last_ack_frames_.empty() &&
314          last_congestion_frames_.empty() &&
315          last_stop_waiting_frames_.empty());
316 }
317
318 void QuicConnection::OnPublicResetPacket(
319     const QuicPublicResetPacket& packet) {
320   if (debug_visitor_) {
321     debug_visitor_->OnPublicResetPacket(packet);
322   }
323   CloseConnection(QUIC_PUBLIC_RESET, true);
324 }
325
326 bool QuicConnection::OnProtocolVersionMismatch(QuicVersion received_version) {
327   DVLOG(1) << ENDPOINT << "Received packet with mismatched version "
328            << received_version;
329   // TODO(satyamshekhar): Implement no server state in this mode.
330   if (!is_server_) {
331     LOG(DFATAL) << ENDPOINT << "Framer called OnProtocolVersionMismatch. "
332                 << "Closing connection.";
333     CloseConnection(QUIC_INTERNAL_ERROR, false);
334     return false;
335   }
336   DCHECK_NE(version(), received_version);
337
338   if (debug_visitor_) {
339     debug_visitor_->OnProtocolVersionMismatch(received_version);
340   }
341
342   switch (version_negotiation_state_) {
343     case START_NEGOTIATION:
344       if (!framer_.IsSupportedVersion(received_version)) {
345         SendVersionNegotiationPacket();
346         version_negotiation_state_ = NEGOTIATION_IN_PROGRESS;
347         return false;
348       }
349       break;
350
351     case NEGOTIATION_IN_PROGRESS:
352       if (!framer_.IsSupportedVersion(received_version)) {
353         SendVersionNegotiationPacket();
354         return false;
355       }
356       break;
357
358     case NEGOTIATED_VERSION:
359       // Might be old packets that were sent by the client before the version
360       // was negotiated. Drop these.
361       return false;
362
363     default:
364       DCHECK(false);
365   }
366
367   version_negotiation_state_ = NEGOTIATED_VERSION;
368   visitor_->OnSuccessfulVersionNegotiation(received_version);
369   DVLOG(1) << ENDPOINT << "version negotiated " << received_version;
370
371   // Store the new version.
372   framer_.set_version(received_version);
373
374   if (received_version < QUIC_VERSION_19) {
375     flow_controller_->Disable();
376   }
377
378   // TODO(satyamshekhar): Store the sequence number of this packet and close the
379   // connection if we ever received a packet with incorrect version and whose
380   // sequence number is greater.
381   return true;
382 }
383
384 // Handles version negotiation for client connection.
385 void QuicConnection::OnVersionNegotiationPacket(
386     const QuicVersionNegotiationPacket& packet) {
387   if (is_server_) {
388     LOG(DFATAL) << ENDPOINT << "Framer parsed VersionNegotiationPacket."
389                 << " Closing connection.";
390     CloseConnection(QUIC_INTERNAL_ERROR, false);
391     return;
392   }
393   if (debug_visitor_) {
394     debug_visitor_->OnVersionNegotiationPacket(packet);
395   }
396
397   if (version_negotiation_state_ != START_NEGOTIATION) {
398     // Possibly a duplicate version negotiation packet.
399     return;
400   }
401
402   if (std::find(packet.versions.begin(),
403                 packet.versions.end(), version()) !=
404       packet.versions.end()) {
405     DLOG(WARNING) << ENDPOINT << "The server already supports our version. "
406                   << "It should have accepted our connection.";
407     // Just drop the connection.
408     CloseConnection(QUIC_INVALID_VERSION_NEGOTIATION_PACKET, false);
409     return;
410   }
411
412   if (!SelectMutualVersion(packet.versions)) {
413     SendConnectionCloseWithDetails(QUIC_INVALID_VERSION,
414                                    "no common version found");
415     return;
416   }
417
418   DVLOG(1) << ENDPOINT << "negotiating version " << version();
419   server_supported_versions_ = packet.versions;
420   version_negotiation_state_ = NEGOTIATION_IN_PROGRESS;
421   RetransmitUnackedPackets(ALL_PACKETS);
422 }
423
424 void QuicConnection::OnRevivedPacket() {
425 }
426
427 bool QuicConnection::OnUnauthenticatedPublicHeader(
428     const QuicPacketPublicHeader& header) {
429   return true;
430 }
431
432 bool QuicConnection::OnUnauthenticatedHeader(const QuicPacketHeader& header) {
433   return true;
434 }
435
436 void QuicConnection::OnDecryptedPacket(EncryptionLevel level) {
437   last_decrypted_packet_level_ = level;
438 }
439
440 bool QuicConnection::OnPacketHeader(const QuicPacketHeader& header) {
441   if (debug_visitor_) {
442     debug_visitor_->OnPacketHeader(header);
443   }
444
445   if (!ProcessValidatedPacket()) {
446     return false;
447   }
448
449   // Will be decrement below if we fall through to return true;
450   ++stats_.packets_dropped;
451
452   if (header.public_header.connection_id != connection_id_) {
453     DVLOG(1) << ENDPOINT << "Ignoring packet from unexpected ConnectionId: "
454              << header.public_header.connection_id << " instead of "
455              << connection_id_;
456     return false;
457   }
458
459   if (!Near(header.packet_sequence_number,
460             last_header_.packet_sequence_number)) {
461     DVLOG(1) << ENDPOINT << "Packet " << header.packet_sequence_number
462              << " out of bounds.  Discarding";
463     SendConnectionCloseWithDetails(QUIC_INVALID_PACKET_HEADER,
464                                    "Packet sequence number out of bounds");
465     return false;
466   }
467
468   // If this packet has already been seen, or that the sender
469   // has told us will not be retransmitted, then stop processing the packet.
470   if (!received_packet_manager_.IsAwaitingPacket(
471           header.packet_sequence_number)) {
472     DVLOG(1) << ENDPOINT << "Packet " << header.packet_sequence_number
473              << " no longer being waited for.  Discarding.";
474     // TODO(jri): Log reception of duplicate packets or packets the peer has
475     // told us to stop waiting for.
476     return false;
477   }
478
479   if (version_negotiation_state_ != NEGOTIATED_VERSION) {
480     if (is_server_) {
481       if (!header.public_header.version_flag) {
482         DLOG(WARNING) << ENDPOINT << "Packet " << header.packet_sequence_number
483                       << " without version flag before version negotiated.";
484         // Packets should have the version flag till version negotiation is
485         // done.
486         CloseConnection(QUIC_INVALID_VERSION, false);
487         return false;
488       } else {
489         DCHECK_EQ(1u, header.public_header.versions.size());
490         DCHECK_EQ(header.public_header.versions[0], version());
491         version_negotiation_state_ = NEGOTIATED_VERSION;
492         visitor_->OnSuccessfulVersionNegotiation(version());
493         if (version() < QUIC_VERSION_19) {
494           flow_controller_->Disable();
495         }
496       }
497     } else {
498       DCHECK(!header.public_header.version_flag);
499       // If the client gets a packet without the version flag from the server
500       // it should stop sending version since the version negotiation is done.
501       packet_creator_.StopSendingVersion();
502       version_negotiation_state_ = NEGOTIATED_VERSION;
503       visitor_->OnSuccessfulVersionNegotiation(version());
504       if (version() < QUIC_VERSION_19) {
505         flow_controller_->Disable();
506       }
507     }
508   }
509
510   DCHECK_EQ(NEGOTIATED_VERSION, version_negotiation_state_);
511
512   --stats_.packets_dropped;
513   DVLOG(1) << ENDPOINT << "Received packet header: " << header;
514   last_header_ = header;
515   DCHECK(connected_);
516   return true;
517 }
518
519 void QuicConnection::OnFecProtectedPayload(StringPiece payload) {
520   DCHECK_EQ(IN_FEC_GROUP, last_header_.is_in_fec_group);
521   DCHECK_NE(0u, last_header_.fec_group);
522   QuicFecGroup* group = GetFecGroup();
523   if (group != NULL) {
524     group->Update(last_decrypted_packet_level_, last_header_, payload);
525   }
526 }
527
528 bool QuicConnection::OnStreamFrame(const QuicStreamFrame& frame) {
529   DCHECK(connected_);
530   if (debug_visitor_) {
531     debug_visitor_->OnStreamFrame(frame);
532   }
533   if (frame.stream_id != kCryptoStreamId &&
534       last_decrypted_packet_level_ == ENCRYPTION_NONE) {
535     DLOG(WARNING) << ENDPOINT
536                   << "Received an unencrypted data frame: closing connection";
537     SendConnectionClose(QUIC_UNENCRYPTED_STREAM_DATA);
538     return false;
539   }
540   last_stream_frames_.push_back(frame);
541   return true;
542 }
543
544 bool QuicConnection::OnAckFrame(const QuicAckFrame& incoming_ack) {
545   DCHECK(connected_);
546   if (debug_visitor_) {
547     debug_visitor_->OnAckFrame(incoming_ack);
548   }
549   DVLOG(1) << ENDPOINT << "OnAckFrame: " << incoming_ack;
550
551   if (last_header_.packet_sequence_number <= largest_seen_packet_with_ack_) {
552     DVLOG(1) << ENDPOINT << "Received an old ack frame: ignoring";
553     return true;
554   }
555
556   if (!ValidateAckFrame(incoming_ack)) {
557     SendConnectionClose(QUIC_INVALID_ACK_DATA);
558     return false;
559   }
560
561   last_ack_frames_.push_back(incoming_ack);
562   return connected_;
563 }
564
565 void QuicConnection::ProcessAckFrame(const QuicAckFrame& incoming_ack) {
566   largest_seen_packet_with_ack_ = last_header_.packet_sequence_number;
567   received_packet_manager_.UpdatePacketInformationReceivedByPeer(
568       incoming_ack.received_info);
569   if (version() <= QUIC_VERSION_15) {
570     ProcessStopWaitingFrame(incoming_ack.sent_info);
571   }
572
573   sent_entropy_manager_.ClearEntropyBefore(
574       received_packet_manager_.least_packet_awaited_by_peer() - 1);
575
576   sent_packet_manager_.OnIncomingAck(incoming_ack.received_info,
577                                      time_of_last_received_packet_);
578   if (sent_packet_manager_.HasPendingRetransmissions()) {
579     WriteIfNotBlocked();
580   }
581
582   // Always reset the retransmission alarm when an ack comes in, since we now
583   // have a better estimate of the current rtt than when it was set.
584   retransmission_alarm_->Cancel();
585   QuicTime retransmission_time =
586       sent_packet_manager_.GetRetransmissionTime();
587   if (retransmission_time != QuicTime::Zero()) {
588     retransmission_alarm_->Set(retransmission_time);
589   }
590 }
591
592 void QuicConnection::ProcessStopWaitingFrame(
593     const QuicStopWaitingFrame& stop_waiting) {
594   largest_seen_packet_with_stop_waiting_ = last_header_.packet_sequence_number;
595   received_packet_manager_.UpdatePacketInformationSentByPeer(stop_waiting);
596   // Possibly close any FecGroups which are now irrelevant.
597   CloseFecGroupsBefore(stop_waiting.least_unacked + 1);
598 }
599
600 bool QuicConnection::OnCongestionFeedbackFrame(
601     const QuicCongestionFeedbackFrame& feedback) {
602   DCHECK(connected_);
603   if (debug_visitor_) {
604     debug_visitor_->OnCongestionFeedbackFrame(feedback);
605   }
606   last_congestion_frames_.push_back(feedback);
607   return connected_;
608 }
609
610 bool QuicConnection::OnStopWaitingFrame(const QuicStopWaitingFrame& frame) {
611   DCHECK(connected_);
612
613   if (last_header_.packet_sequence_number <=
614       largest_seen_packet_with_stop_waiting_) {
615     DVLOG(1) << ENDPOINT << "Received an old stop waiting frame: ignoring";
616     return true;
617   }
618
619   if (!ValidateStopWaitingFrame(frame)) {
620     SendConnectionClose(QUIC_INVALID_STOP_WAITING_DATA);
621     return false;
622   }
623
624   if (debug_visitor_) {
625     debug_visitor_->OnStopWaitingFrame(frame);
626   }
627
628   last_stop_waiting_frames_.push_back(frame);
629   return connected_;
630 }
631
632 bool QuicConnection::OnPingFrame(const QuicPingFrame& frame) {
633   DCHECK(connected_);
634   if (debug_visitor_) {
635     debug_visitor_->OnPingFrame(frame);
636   }
637   return true;
638 }
639
640 bool QuicConnection::ValidateAckFrame(const QuicAckFrame& incoming_ack) {
641   if (incoming_ack.received_info.largest_observed >
642       packet_creator_.sequence_number()) {
643     DLOG(ERROR) << ENDPOINT << "Peer's observed unsent packet:"
644                 << incoming_ack.received_info.largest_observed << " vs "
645                 << packet_creator_.sequence_number();
646     // We got an error for data we have not sent.  Error out.
647     return false;
648   }
649
650   if (incoming_ack.received_info.largest_observed <
651           received_packet_manager_.peer_largest_observed_packet()) {
652     DLOG(ERROR) << ENDPOINT << "Peer's largest_observed packet decreased:"
653                 << incoming_ack.received_info.largest_observed << " vs "
654                 << received_packet_manager_.peer_largest_observed_packet();
655     // A new ack has a diminished largest_observed value.  Error out.
656     // If this was an old packet, we wouldn't even have checked.
657     return false;
658   }
659
660   if (version() <= QUIC_VERSION_15) {
661     if (!ValidateStopWaitingFrame(incoming_ack.sent_info)) {
662       return false;
663     }
664   }
665
666   if (!incoming_ack.received_info.missing_packets.empty() &&
667       *incoming_ack.received_info.missing_packets.rbegin() >
668       incoming_ack.received_info.largest_observed) {
669     DLOG(ERROR) << ENDPOINT << "Peer sent missing packet: "
670                 << *incoming_ack.received_info.missing_packets.rbegin()
671                 << " which is greater than largest observed: "
672                 << incoming_ack.received_info.largest_observed;
673     return false;
674   }
675
676   if (!incoming_ack.received_info.missing_packets.empty() &&
677       *incoming_ack.received_info.missing_packets.begin() <
678       received_packet_manager_.least_packet_awaited_by_peer()) {
679     DLOG(ERROR) << ENDPOINT << "Peer sent missing packet: "
680                 << *incoming_ack.received_info.missing_packets.begin()
681                 << " which is smaller than least_packet_awaited_by_peer_: "
682                 << received_packet_manager_.least_packet_awaited_by_peer();
683     return false;
684   }
685
686   if (!sent_entropy_manager_.IsValidEntropy(
687           incoming_ack.received_info.largest_observed,
688           incoming_ack.received_info.missing_packets,
689           incoming_ack.received_info.entropy_hash)) {
690     DLOG(ERROR) << ENDPOINT << "Peer sent invalid entropy.";
691     return false;
692   }
693
694   for (SequenceNumberSet::const_iterator iter =
695            incoming_ack.received_info.revived_packets.begin();
696        iter != incoming_ack.received_info.revived_packets.end(); ++iter) {
697     if (!ContainsKey(incoming_ack.received_info.missing_packets, *iter)) {
698       DLOG(ERROR) << ENDPOINT
699                   << "Peer specified revived packet which was not missing.";
700       return false;
701     }
702   }
703   return true;
704 }
705
706 bool QuicConnection::ValidateStopWaitingFrame(
707     const QuicStopWaitingFrame& stop_waiting) {
708   if (stop_waiting.least_unacked <
709       received_packet_manager_.peer_least_packet_awaiting_ack()) {
710     DLOG(ERROR) << ENDPOINT << "Peer's sent low least_unacked: "
711                 << stop_waiting.least_unacked << " vs "
712                 << received_packet_manager_.peer_least_packet_awaiting_ack();
713     // We never process old ack frames, so this number should only increase.
714     return false;
715   }
716
717   if (stop_waiting.least_unacked >
718       last_header_.packet_sequence_number) {
719     DLOG(ERROR) << ENDPOINT << "Peer sent least_unacked:"
720                 << stop_waiting.least_unacked
721                 << " greater than the enclosing packet sequence number:"
722                 << last_header_.packet_sequence_number;
723     return false;
724   }
725
726   return true;
727 }
728
729 void QuicConnection::OnFecData(const QuicFecData& fec) {
730   DCHECK_EQ(IN_FEC_GROUP, last_header_.is_in_fec_group);
731   DCHECK_NE(0u, last_header_.fec_group);
732   QuicFecGroup* group = GetFecGroup();
733   if (group != NULL) {
734     group->UpdateFec(last_decrypted_packet_level_,
735                      last_header_.packet_sequence_number, fec);
736   }
737 }
738
739 bool QuicConnection::OnRstStreamFrame(const QuicRstStreamFrame& frame) {
740   DCHECK(connected_);
741   if (debug_visitor_) {
742     debug_visitor_->OnRstStreamFrame(frame);
743   }
744   DVLOG(1) << ENDPOINT << "Stream reset with error "
745            << QuicUtils::StreamErrorToString(frame.error_code);
746   last_rst_frames_.push_back(frame);
747   return connected_;
748 }
749
750 bool QuicConnection::OnConnectionCloseFrame(
751     const QuicConnectionCloseFrame& frame) {
752   DCHECK(connected_);
753   if (debug_visitor_) {
754     debug_visitor_->OnConnectionCloseFrame(frame);
755   }
756   DVLOG(1) << ENDPOINT << "Connection " << connection_id()
757            << " closed with error "
758            << QuicUtils::ErrorToString(frame.error_code)
759            << " " << frame.error_details;
760   last_close_frames_.push_back(frame);
761   return connected_;
762 }
763
764 bool QuicConnection::OnGoAwayFrame(const QuicGoAwayFrame& frame) {
765   DCHECK(connected_);
766   DVLOG(1) << ENDPOINT << "Go away received with error "
767            << QuicUtils::ErrorToString(frame.error_code)
768            << " and reason:" << frame.reason_phrase;
769   last_goaway_frames_.push_back(frame);
770   return connected_;
771 }
772
773 bool QuicConnection::OnWindowUpdateFrame(const QuicWindowUpdateFrame& frame) {
774   DCHECK(connected_);
775   DVLOG(1) << ENDPOINT << "WindowUpdate received for stream: "
776            << frame.stream_id << " with byte offset: " << frame.byte_offset;
777   last_window_update_frames_.push_back(frame);
778   return connected_;
779 }
780
781 bool QuicConnection::OnBlockedFrame(const QuicBlockedFrame& frame) {
782   DCHECK(connected_);
783   DVLOG(1) << ENDPOINT << "Blocked frame received for stream: "
784            << frame.stream_id;
785   last_blocked_frames_.push_back(frame);
786   return connected_;
787 }
788
789 void QuicConnection::OnPacketComplete() {
790   // Don't do anything if this packet closed the connection.
791   if (!connected_) {
792     ClearLastFrames();
793     return;
794   }
795
796   DVLOG(1) << ENDPOINT << (last_packet_revived_ ? "Revived" : "Got")
797            << " packet " << last_header_.packet_sequence_number
798            << " with " << last_ack_frames_.size() << " acks, "
799            << last_congestion_frames_.size() << " congestions, "
800            << last_stop_waiting_frames_.size() << " stop_waiting, "
801            << last_goaway_frames_.size() << " goaways, "
802            << last_window_update_frames_.size() << " window updates, "
803            << last_blocked_frames_.size() << " blocked, "
804            << last_rst_frames_.size() << " rsts, "
805            << last_close_frames_.size() << " closes, "
806            << last_stream_frames_.size()
807            << " stream frames for "
808            << last_header_.public_header.connection_id;
809
810   // Call MaybeQueueAck() before recording the received packet, since we want
811   // to trigger an ack if the newly received packet was previously missing.
812   MaybeQueueAck();
813
814   // Record received or revived packet to populate ack info correctly before
815   // processing stream frames, since the processing may result in a response
816   // packet with a bundled ack.
817   if (last_packet_revived_) {
818     received_packet_manager_.RecordPacketRevived(
819         last_header_.packet_sequence_number);
820   } else {
821     received_packet_manager_.RecordPacketReceived(
822         last_size_, last_header_, time_of_last_received_packet_);
823   }
824
825   if (!last_stream_frames_.empty()) {
826     visitor_->OnStreamFrames(last_stream_frames_);
827   }
828
829   for (size_t i = 0; i < last_stream_frames_.size(); ++i) {
830     stats_.stream_bytes_received +=
831         last_stream_frames_[i].data.TotalBufferSize();
832   }
833
834   // Process window updates, blocked, stream resets, acks, then congestion
835   // feedback.
836   if (!last_window_update_frames_.empty()) {
837     visitor_->OnWindowUpdateFrames(last_window_update_frames_);
838   }
839   if (!last_blocked_frames_.empty()) {
840     visitor_->OnBlockedFrames(last_blocked_frames_);
841   }
842   for (size_t i = 0; i < last_goaway_frames_.size(); ++i) {
843     visitor_->OnGoAway(last_goaway_frames_[i]);
844   }
845   for (size_t i = 0; i < last_rst_frames_.size(); ++i) {
846     visitor_->OnRstStream(last_rst_frames_[i]);
847   }
848   for (size_t i = 0; i < last_ack_frames_.size(); ++i) {
849     ProcessAckFrame(last_ack_frames_[i]);
850   }
851   for (size_t i = 0; i < last_congestion_frames_.size(); ++i) {
852     sent_packet_manager_.OnIncomingQuicCongestionFeedbackFrame(
853         last_congestion_frames_[i], time_of_last_received_packet_);
854   }
855   for (size_t i = 0; i < last_stop_waiting_frames_.size(); ++i) {
856     ProcessStopWaitingFrame(last_stop_waiting_frames_[i]);
857   }
858   if (!last_close_frames_.empty()) {
859     CloseConnection(last_close_frames_[0].error_code, true);
860     DCHECK(!connected_);
861   }
862
863   // If there are new missing packets to report, send an ack immediately.
864   if (received_packet_manager_.HasNewMissingPackets()) {
865     ack_queued_ = true;
866     ack_alarm_->Cancel();
867   }
868
869   UpdateStopWaitingCount();
870
871   ClearLastFrames();
872 }
873
874 void QuicConnection::MaybeQueueAck() {
875   // If the incoming packet was missing, send an ack immediately.
876   ack_queued_ = received_packet_manager_.IsMissing(
877       last_header_.packet_sequence_number);
878
879   if (!ack_queued_ && ShouldLastPacketInstigateAck()) {
880     if (ack_alarm_->IsSet()) {
881       ack_queued_ = true;
882     } else {
883       // Send an ack much more quickly for crypto handshake packets.
884       QuicTime::Delta delayed_ack_time = sent_packet_manager_.DelayedAckTime();
885       if (last_stream_frames_.size() == 1 &&
886           last_stream_frames_[0].stream_id == kCryptoStreamId) {
887         delayed_ack_time = QuicTime::Delta::Zero();
888       }
889       ack_alarm_->Set(clock_->ApproximateNow().Add(delayed_ack_time));
890       DVLOG(1) << "Ack timer set; next packet or timer will trigger ACK.";
891     }
892   }
893
894   if (ack_queued_) {
895     ack_alarm_->Cancel();
896   }
897 }
898
899 void QuicConnection::ClearLastFrames() {
900   last_stream_frames_.clear();
901   last_goaway_frames_.clear();
902   last_window_update_frames_.clear();
903   last_blocked_frames_.clear();
904   last_rst_frames_.clear();
905   last_ack_frames_.clear();
906   last_stop_waiting_frames_.clear();
907   last_congestion_frames_.clear();
908 }
909
910 QuicAckFrame* QuicConnection::CreateAckFrame() {
911   QuicAckFrame* outgoing_ack = new QuicAckFrame();
912   received_packet_manager_.UpdateReceivedPacketInfo(
913       &(outgoing_ack->received_info), clock_->ApproximateNow());
914   UpdateStopWaiting(&(outgoing_ack->sent_info));
915   DVLOG(1) << ENDPOINT << "Creating ack frame: " << *outgoing_ack;
916   return outgoing_ack;
917 }
918
919 QuicCongestionFeedbackFrame* QuicConnection::CreateFeedbackFrame() {
920   return new QuicCongestionFeedbackFrame(outgoing_congestion_feedback_);
921 }
922
923 QuicStopWaitingFrame* QuicConnection::CreateStopWaitingFrame() {
924   QuicStopWaitingFrame stop_waiting;
925   UpdateStopWaiting(&stop_waiting);
926   return new QuicStopWaitingFrame(stop_waiting);
927 }
928
929 bool QuicConnection::ShouldLastPacketInstigateAck() const {
930   if (!last_stream_frames_.empty() ||
931       !last_goaway_frames_.empty() ||
932       !last_rst_frames_.empty() ||
933       !last_window_update_frames_.empty() ||
934       !last_blocked_frames_.empty()) {
935     return true;
936   }
937
938   if (!last_ack_frames_.empty() &&
939       last_ack_frames_.back().received_info.is_truncated) {
940     return true;
941   }
942   return false;
943 }
944
945 void QuicConnection::UpdateStopWaitingCount() {
946   if (last_ack_frames_.empty()) {
947     return;
948   }
949
950   // If the peer is still waiting for a packet that we are no longer planning to
951   // send, send an ack to raise the high water mark.
952   if (!last_ack_frames_.back().received_info.missing_packets.empty() &&
953       GetLeastUnacked() >
954           *last_ack_frames_.back().received_info.missing_packets.begin()) {
955     ++stop_waiting_count_;
956   } else {
957     stop_waiting_count_ = 0;
958   }
959 }
960
961 QuicPacketSequenceNumber QuicConnection::GetLeastUnacked() const {
962   return sent_packet_manager_.HasUnackedPackets() ?
963       sent_packet_manager_.GetLeastUnackedSentPacket() :
964       packet_creator_.sequence_number() + 1;
965 }
966
967 void QuicConnection::MaybeSendInResponseToPacket() {
968   if (!connected_) {
969     return;
970   }
971   ScopedPacketBundler bundler(this, ack_queued_ ? SEND_ACK : NO_ACK);
972
973   // Now that we have received an ack, we might be able to send packets which
974   // are queued locally, or drain streams which are blocked.
975   QuicTime::Delta delay = sent_packet_manager_.TimeUntilSend(
976       time_of_last_received_packet_, NOT_RETRANSMISSION,
977       HAS_RETRANSMITTABLE_DATA);
978   if (delay.IsZero()) {
979     send_alarm_->Cancel();
980     WriteIfNotBlocked();
981   } else if (!delay.IsInfinite()) {
982     send_alarm_->Cancel();
983     send_alarm_->Set(time_of_last_received_packet_.Add(delay));
984   }
985 }
986
987 void QuicConnection::SendVersionNegotiationPacket() {
988   // TODO(alyssar): implement zero server state negotiation.
989   pending_version_negotiation_packet_ = true;
990   if (writer_->IsWriteBlocked()) {
991     visitor_->OnWriteBlocked();
992     return;
993   }
994   scoped_ptr<QuicEncryptedPacket> version_packet(
995       packet_creator_.SerializeVersionNegotiationPacket(
996           framer_.supported_versions()));
997   WriteResult result = writer_->WritePacket(
998       version_packet->data(), version_packet->length(),
999       self_address().address(), peer_address());
1000
1001   if (result.status == WRITE_STATUS_ERROR) {
1002     // We can't send an error as the socket is presumably borked.
1003     CloseConnection(QUIC_PACKET_WRITE_ERROR, false);
1004     return;
1005   }
1006   if (result.status == WRITE_STATUS_BLOCKED) {
1007     visitor_->OnWriteBlocked();
1008     if (writer_->IsWriteBlockedDataBuffered()) {
1009       pending_version_negotiation_packet_ = false;
1010     }
1011     return;
1012   }
1013
1014   pending_version_negotiation_packet_ = false;
1015 }
1016
1017 QuicConsumedData QuicConnection::SendStreamData(
1018     QuicStreamId id,
1019     const IOVector& data,
1020     QuicStreamOffset offset,
1021     bool fin,
1022     QuicAckNotifier::DelegateInterface* delegate) {
1023   if (!fin && data.Empty()) {
1024     LOG(DFATAL) << "Attempt to send empty stream frame";
1025   }
1026
1027   // This notifier will be owned by the AckNotifierManager (or deleted below if
1028   // no data or FIN was consumed).
1029   QuicAckNotifier* notifier = NULL;
1030   if (delegate) {
1031     notifier = new QuicAckNotifier(delegate);
1032   }
1033
1034   // Opportunistically bundle an ack with every outgoing packet.
1035   // Particularly, we want to bundle with handshake packets since we don't know
1036   // which decrypter will be used on an ack packet following a handshake
1037   // packet (a handshake packet from client to server could result in a REJ or a
1038   // SHLO from the server, leading to two different decrypters at the server.)
1039   //
1040   // TODO(jri): Note that ConsumeData may cause a response packet to be sent.
1041   // We may end up sending stale ack information if there are undecryptable
1042   // packets hanging around and/or there are revivable packets which may get
1043   // handled after this packet is sent. Change ScopedPacketBundler to do the
1044   // right thing: check ack_queued_, and then check undecryptable packets and
1045   // also if there is possibility of revival. Only bundle an ack if there's no
1046   // processing left that may cause received_info_ to change.
1047   ScopedPacketBundler ack_bundler(this, BUNDLE_PENDING_ACK);
1048   QuicConsumedData consumed_data =
1049       packet_generator_.ConsumeData(id, data, offset, fin, notifier);
1050
1051   if (notifier &&
1052       (consumed_data.bytes_consumed == 0 && !consumed_data.fin_consumed)) {
1053     // No data was consumed, nor was a fin consumed, so delete the notifier.
1054     delete notifier;
1055   }
1056
1057   return consumed_data;
1058 }
1059
1060 void QuicConnection::SendRstStream(QuicStreamId id,
1061                                    QuicRstStreamErrorCode error,
1062                                    QuicStreamOffset bytes_written) {
1063   // Opportunistically bundle an ack with this outgoing packet.
1064   ScopedPacketBundler ack_bundler(this, BUNDLE_PENDING_ACK);
1065   packet_generator_.AddControlFrame(QuicFrame(new QuicRstStreamFrame(
1066       id, AdjustErrorForVersion(error, version()), bytes_written)));
1067 }
1068
1069 void QuicConnection::SendWindowUpdate(QuicStreamId id,
1070                                       QuicStreamOffset byte_offset) {
1071   // Opportunistically bundle an ack with this outgoing packet.
1072   ScopedPacketBundler ack_bundler(this, BUNDLE_PENDING_ACK);
1073   packet_generator_.AddControlFrame(
1074       QuicFrame(new QuicWindowUpdateFrame(id, byte_offset)));
1075 }
1076
1077 void QuicConnection::SendBlocked(QuicStreamId id) {
1078   // Opportunistically bundle an ack with this outgoing packet.
1079   ScopedPacketBundler ack_bundler(this, BUNDLE_PENDING_ACK);
1080   packet_generator_.AddControlFrame(QuicFrame(new QuicBlockedFrame(id)));
1081 }
1082
1083 const QuicConnectionStats& QuicConnection::GetStats() {
1084   // Update rtt and estimated bandwidth.
1085   stats_.min_rtt_us =
1086       sent_packet_manager_.GetRttStats()->min_rtt().ToMicroseconds();
1087   stats_.srtt_us =
1088       sent_packet_manager_.GetRttStats()->SmoothedRtt().ToMicroseconds();
1089   stats_.estimated_bandwidth =
1090       sent_packet_manager_.BandwidthEstimate().ToBytesPerSecond();
1091   stats_.congestion_window = sent_packet_manager_.GetCongestionWindow();
1092   stats_.max_packet_size = options()->max_packet_length;
1093   return stats_;
1094 }
1095
1096 void QuicConnection::ProcessUdpPacket(const IPEndPoint& self_address,
1097                                       const IPEndPoint& peer_address,
1098                                       const QuicEncryptedPacket& packet) {
1099   if (!connected_) {
1100     return;
1101   }
1102   if (debug_visitor_) {
1103     debug_visitor_->OnPacketReceived(self_address, peer_address, packet);
1104   }
1105   last_packet_revived_ = false;
1106   last_size_ = packet.length();
1107
1108   address_migrating_ = false;
1109
1110   if (peer_address_.address().empty()) {
1111     peer_address_ = peer_address;
1112   }
1113   if (self_address_.address().empty()) {
1114     self_address_ = self_address;
1115   }
1116
1117   if (!(peer_address == peer_address_ && self_address == self_address_)) {
1118     address_migrating_ = true;
1119   }
1120
1121   stats_.bytes_received += packet.length();
1122   ++stats_.packets_received;
1123
1124   if (!framer_.ProcessPacket(packet)) {
1125     // If we are unable to decrypt this packet, it might be
1126     // because the CHLO or SHLO packet was lost.
1127     if (encryption_level_ != ENCRYPTION_FORWARD_SECURE &&
1128         framer_.error() == QUIC_DECRYPTION_FAILURE &&
1129         undecryptable_packets_.size() < kMaxUndecryptablePackets) {
1130       QueueUndecryptablePacket(packet);
1131     }
1132     DVLOG(1) << ENDPOINT << "Unable to process packet.  Last packet processed: "
1133              << last_header_.packet_sequence_number;
1134     return;
1135   }
1136
1137   ++stats_.packets_processed;
1138   MaybeProcessUndecryptablePackets();
1139   MaybeProcessRevivedPacket();
1140   MaybeSendInResponseToPacket();
1141   SetPingAlarm();
1142 }
1143
1144 void QuicConnection::OnCanWrite() {
1145   DCHECK(!writer_->IsWriteBlocked());
1146
1147   WriteQueuedPackets();
1148   WritePendingRetransmissions();
1149
1150   IsHandshake pending_handshake = visitor_->HasPendingHandshake() ?
1151       IS_HANDSHAKE : NOT_HANDSHAKE;
1152   // Sending queued packets may have caused the socket to become write blocked,
1153   // or the congestion manager to prohibit sending.  If we've sent everything
1154   // we had queued and we're still not blocked, let the visitor know it can
1155   // write more.
1156   if (!CanWrite(NOT_RETRANSMISSION, HAS_RETRANSMITTABLE_DATA,
1157                 pending_handshake)) {
1158     return;
1159   }
1160
1161   {  // Limit the scope of the bundler.
1162     // Set |include_ack| to false in bundler; ack inclusion happens elsewhere.
1163     ScopedPacketBundler bundler(this, NO_ACK);
1164     visitor_->OnCanWrite();
1165   }
1166
1167   // After the visitor writes, it may have caused the socket to become write
1168   // blocked or the congestion manager to prohibit sending, so check again.
1169   pending_handshake = visitor_->HasPendingHandshake() ?
1170       IS_HANDSHAKE : NOT_HANDSHAKE;
1171   if (visitor_->HasPendingWrites() && !resume_writes_alarm_->IsSet() &&
1172       CanWrite(NOT_RETRANSMISSION, HAS_RETRANSMITTABLE_DATA,
1173                pending_handshake)) {
1174     // We're not write blocked, but some stream didn't write out all of its
1175     // bytes. Register for 'immediate' resumption so we'll keep writing after
1176     // other connections and events have had a chance to use the thread.
1177     resume_writes_alarm_->Set(clock_->ApproximateNow());
1178   }
1179 }
1180
1181 void QuicConnection::WriteIfNotBlocked() {
1182   if (!writer_->IsWriteBlocked()) {
1183     OnCanWrite();
1184   }
1185 }
1186
1187 bool QuicConnection::ProcessValidatedPacket() {
1188   if (address_migrating_) {
1189     SendConnectionCloseWithDetails(
1190         QUIC_ERROR_MIGRATING_ADDRESS,
1191         "Address migration is not yet a supported feature");
1192     return false;
1193   }
1194   time_of_last_received_packet_ = clock_->Now();
1195   DVLOG(1) << ENDPOINT << "time of last received packet: "
1196            << time_of_last_received_packet_.ToDebuggingValue();
1197
1198   if (is_server_ && encryption_level_ == ENCRYPTION_NONE &&
1199       last_size_ > options()->max_packet_length) {
1200     options()->max_packet_length = last_size_;
1201   }
1202   return true;
1203 }
1204
1205 void QuicConnection::WriteQueuedPackets() {
1206   DCHECK(!writer_->IsWriteBlocked());
1207
1208   if (pending_version_negotiation_packet_) {
1209     SendVersionNegotiationPacket();
1210   }
1211
1212   QueuedPacketList::iterator packet_iterator = queued_packets_.begin();
1213   while (!writer_->IsWriteBlocked() &&
1214          packet_iterator != queued_packets_.end()) {
1215     if (WritePacket(*packet_iterator)) {
1216       delete packet_iterator->packet;
1217       packet_iterator = queued_packets_.erase(packet_iterator);
1218     } else {
1219       // Continue, because some queued packets may still be writable.
1220       // This can happen if a retransmit send fails.
1221       ++packet_iterator;
1222     }
1223   }
1224 }
1225
1226 void QuicConnection::WritePendingRetransmissions() {
1227   // Keep writing as long as there's a pending retransmission which can be
1228   // written.
1229   while (sent_packet_manager_.HasPendingRetransmissions()) {
1230     const QuicSentPacketManager::PendingRetransmission pending =
1231         sent_packet_manager_.NextPendingRetransmission();
1232     if (GetPacketType(&pending.retransmittable_frames) == NORMAL &&
1233         !CanWrite(pending.transmission_type, HAS_RETRANSMITTABLE_DATA,
1234                   pending.retransmittable_frames.HasCryptoHandshake())) {
1235       break;
1236     }
1237
1238     // Re-packetize the frames with a new sequence number for retransmission.
1239     // Retransmitted data packets do not use FEC, even when it's enabled.
1240     // Retransmitted packets use the same sequence number length as the
1241     // original.
1242     // Flush the packet creator before making a new packet.
1243     // TODO(ianswett): Implement ReserializeAllFrames as a separate path that
1244     // does not require the creator to be flushed.
1245     Flush();
1246     SerializedPacket serialized_packet = packet_creator_.ReserializeAllFrames(
1247         pending.retransmittable_frames.frames(),
1248         pending.sequence_number_length);
1249
1250     DVLOG(1) << ENDPOINT << "Retransmitting " << pending.sequence_number
1251              << " as " << serialized_packet.sequence_number;
1252     if (debug_visitor_) {
1253       debug_visitor_->OnPacketRetransmitted(
1254           pending.sequence_number, serialized_packet.sequence_number);
1255     }
1256     sent_packet_manager_.OnRetransmittedPacket(
1257         pending.sequence_number, serialized_packet.sequence_number);
1258
1259     SendOrQueuePacket(pending.retransmittable_frames.encryption_level(),
1260                       serialized_packet,
1261                       pending.transmission_type);
1262   }
1263 }
1264
1265 void QuicConnection::RetransmitUnackedPackets(
1266     RetransmissionType retransmission_type) {
1267   sent_packet_manager_.RetransmitUnackedPackets(retransmission_type);
1268
1269   WriteIfNotBlocked();
1270 }
1271
1272 void QuicConnection::DiscardUnencryptedPackets() {
1273   sent_packet_manager_.DiscardUnencryptedPackets();
1274   // This may have changed the retransmission timer, so re-arm it.
1275   retransmission_alarm_->Cancel();
1276   QuicTime retransmission_time = sent_packet_manager_.GetRetransmissionTime();
1277   if (retransmission_time != QuicTime::Zero()) {
1278     retransmission_alarm_->Set(retransmission_time);
1279   }
1280 }
1281
1282 bool QuicConnection::ShouldGeneratePacket(
1283     TransmissionType transmission_type,
1284     HasRetransmittableData retransmittable,
1285     IsHandshake handshake) {
1286   // We should serialize handshake packets immediately to ensure that they
1287   // end up sent at the right encryption level.
1288   if (handshake == IS_HANDSHAKE) {
1289     return true;
1290   }
1291
1292   return CanWrite(transmission_type, retransmittable, handshake);
1293 }
1294
1295 bool QuicConnection::CanWrite(TransmissionType transmission_type,
1296                               HasRetransmittableData retransmittable,
1297                               IsHandshake handshake) {
1298   if (writer_->IsWriteBlocked()) {
1299     visitor_->OnWriteBlocked();
1300     return false;
1301   }
1302
1303   // TODO(rch): consider removing this check so that if an ACK comes in
1304   // before the alarm goes it, we might be able send out a packet.
1305   // This check assumes that if the send alarm is set, it applies equally to all
1306   // types of transmissions.
1307   if (send_alarm_->IsSet()) {
1308     DVLOG(1) << "Send alarm set.  Not sending.";
1309     return false;
1310   }
1311
1312   QuicTime now = clock_->Now();
1313   QuicTime::Delta delay = sent_packet_manager_.TimeUntilSend(
1314       now, transmission_type, retransmittable);
1315   if (delay.IsInfinite()) {
1316     return false;
1317   }
1318
1319   // If the scheduler requires a delay, then we can not send this packet now.
1320   if (!delay.IsZero()) {
1321     send_alarm_->Cancel();
1322     send_alarm_->Set(now.Add(delay));
1323     DVLOG(1) << "Delaying sending.";
1324     return false;
1325   }
1326   return true;
1327 }
1328
1329 bool QuicConnection::WritePacket(QueuedPacket packet) {
1330   QuicPacketSequenceNumber sequence_number = packet.sequence_number;
1331   if (ShouldDiscardPacket(packet.encryption_level,
1332                           sequence_number,
1333                           packet.retransmittable)) {
1334     ++stats_.packets_discarded;
1335     return true;
1336   }
1337
1338   // If the packet is CONNECTION_CLOSE, we need to try to send it immediately
1339   // and encrypt it to hand it off to TimeWaitListManager.
1340   // If the packet is QUEUED, we don't re-consult the congestion control.
1341   // This ensures packets are sent in sequence number order.
1342   // TODO(ianswett): The congestion control should have been consulted before
1343   // serializing the packet, so this could be turned into a LOG_IF(DFATAL).
1344   if (packet.type == NORMAL && !CanWrite(packet.transmission_type,
1345                                          packet.retransmittable,
1346                                          packet.handshake)) {
1347     return false;
1348   }
1349
1350   // Some encryption algorithms require the packet sequence numbers not be
1351   // repeated.
1352   DCHECK_LE(sequence_number_of_last_sent_packet_, sequence_number);
1353   sequence_number_of_last_sent_packet_ = sequence_number;
1354
1355   QuicEncryptedPacket* encrypted = framer_.EncryptPacket(
1356       packet.encryption_level, sequence_number, *packet.packet);
1357   if (encrypted == NULL) {
1358     LOG(DFATAL) << ENDPOINT << "Failed to encrypt packet number "
1359                 << sequence_number;
1360     // CloseConnection does not send close packet, so no infinite loop here.
1361     CloseConnection(QUIC_ENCRYPTION_FAILURE, false);
1362     return false;
1363   }
1364
1365   // Connection close packets are eventually owned by TimeWaitListManager.
1366   // Others are deleted at the end of this call.
1367   scoped_ptr<QuicEncryptedPacket> encrypted_deleter;
1368   if (packet.type == CONNECTION_CLOSE) {
1369     DCHECK(connection_close_packet_.get() == NULL);
1370     connection_close_packet_.reset(encrypted);
1371     // This assures we won't try to write *forced* packets when blocked.
1372     // Return true to stop processing.
1373     if (writer_->IsWriteBlocked()) {
1374       visitor_->OnWriteBlocked();
1375       return true;
1376     }
1377   } else {
1378     encrypted_deleter.reset(encrypted);
1379   }
1380
1381   LOG_IF(DFATAL, encrypted->length() > options()->max_packet_length)
1382       << "Writing an encrypted packet larger than max_packet_length:"
1383       << options()->max_packet_length << " encrypted length: "
1384       << encrypted->length();
1385   DVLOG(1) << ENDPOINT << "Sending packet " << sequence_number
1386            << " : " << (packet.packet->is_fec_packet() ? "FEC " :
1387                (packet.retransmittable == HAS_RETRANSMITTABLE_DATA
1388                     ? "data bearing " : " ack only "))
1389            << ", encryption level: "
1390            << QuicUtils::EncryptionLevelToString(packet.encryption_level)
1391            << ", length:" << packet.packet->length() << ", encrypted length:"
1392            << encrypted->length();
1393   DVLOG(2) << ENDPOINT << "packet(" << sequence_number << "): " << std::endl
1394            << QuicUtils::StringToHexASCIIDump(packet.packet->AsStringPiece());
1395
1396   DCHECK(encrypted->length() <= kMaxPacketSize ||
1397          FLAGS_quic_allow_oversized_packets_for_test)
1398       << "Packet " << sequence_number << " will not be read; too large: "
1399       << packet.packet->length() << " " << encrypted->length() << " "
1400       << " close: " << (packet.type == CONNECTION_CLOSE ? "yes" : "no");
1401
1402   DCHECK(pending_write_.get() == NULL);
1403   pending_write_.reset(new QueuedPacket(packet));
1404
1405   WriteResult result = writer_->WritePacket(encrypted->data(),
1406                                             encrypted->length(),
1407                                             self_address().address(),
1408                                             peer_address());
1409   if (result.error_code == ERR_IO_PENDING) {
1410     DCHECK_EQ(WRITE_STATUS_BLOCKED, result.status);
1411   }
1412   if (debug_visitor_) {
1413     // Pass the write result to the visitor.
1414     debug_visitor_->OnPacketSent(sequence_number,
1415                                  packet.encryption_level,
1416                                  packet.transmission_type,
1417                                  *encrypted,
1418                                  result);
1419   }
1420   if (result.status == WRITE_STATUS_BLOCKED) {
1421     visitor_->OnWriteBlocked();
1422     // If the socket buffers the the data, then the packet should not
1423     // be queued and sent again, which would result in an unnecessary
1424     // duplicate packet being sent.  The helper must call OnPacketSent
1425     // when the packet is actually sent.
1426     if (writer_->IsWriteBlockedDataBuffered()) {
1427       return true;
1428     }
1429     pending_write_.reset();
1430     return false;
1431   }
1432
1433   if (OnPacketSent(result)) {
1434     return true;
1435   }
1436   return false;
1437 }
1438
1439 bool QuicConnection::ShouldDiscardPacket(
1440     EncryptionLevel level,
1441     QuicPacketSequenceNumber sequence_number,
1442     HasRetransmittableData retransmittable) {
1443   if (!connected_) {
1444     DVLOG(1) << ENDPOINT
1445              << "Not sending packet as connection is disconnected.";
1446     return true;
1447   }
1448
1449   if (encryption_level_ == ENCRYPTION_FORWARD_SECURE &&
1450       level == ENCRYPTION_NONE) {
1451     // Drop packets that are NULL encrypted since the peer won't accept them
1452     // anymore.
1453     DVLOG(1) << ENDPOINT << "Dropping packet: " << sequence_number
1454              << " since the packet is NULL encrypted.";
1455     sent_packet_manager_.DiscardUnackedPacket(sequence_number);
1456     return true;
1457   }
1458
1459   // If the packet has been discarded before sending, don't send it.
1460   // This occurs if a packet gets serialized, queued, then discarded.
1461   if (!sent_packet_manager_.IsUnacked(sequence_number)) {
1462     DVLOG(1) << ENDPOINT << "Dropping packet before sending: "
1463              << sequence_number << " since it has already been discarded.";
1464     return true;
1465   }
1466
1467   if (retransmittable == HAS_RETRANSMITTABLE_DATA &&
1468       !sent_packet_manager_.HasRetransmittableFrames(sequence_number)) {
1469     DVLOG(1) << ENDPOINT << "Dropping packet: " << sequence_number
1470              << " since a previous transmission has been acked.";
1471     sent_packet_manager_.DiscardUnackedPacket(sequence_number);
1472     return true;
1473   }
1474
1475   return false;
1476 }
1477
1478 bool QuicConnection::OnPacketSent(WriteResult result) {
1479   DCHECK_NE(WRITE_STATUS_BLOCKED, result.status);
1480   if (pending_write_.get() == NULL) {
1481     LOG(DFATAL) << "OnPacketSent called without a pending write.";
1482     return false;
1483   }
1484
1485   QuicPacketSequenceNumber sequence_number = pending_write_->sequence_number;
1486   TransmissionType transmission_type  = pending_write_->transmission_type;
1487   HasRetransmittableData retransmittable = pending_write_->retransmittable;
1488   size_t length = pending_write_->length;
1489   pending_write_.reset();
1490
1491   if (result.status == WRITE_STATUS_ERROR) {
1492     DVLOG(1) << "Write failed with error: " << result.error_code << " ("
1493              << ErrorToString(result.error_code) << ")";
1494     // We can't send an error as the socket is presumably borked.
1495     CloseConnection(QUIC_PACKET_WRITE_ERROR, false);
1496     return false;
1497   }
1498
1499   QuicTime now = clock_->Now();
1500   if (transmission_type == NOT_RETRANSMISSION) {
1501     time_of_last_sent_new_packet_ = now;
1502   }
1503   SetPingAlarm();
1504   DVLOG(1) << ENDPOINT << "time of last sent packet: "
1505            << now.ToDebuggingValue();
1506
1507   // TODO(ianswett): Change the sequence number length and other packet creator
1508   // options by a more explicit API than setting a struct value directly.
1509   packet_creator_.UpdateSequenceNumberLength(
1510       received_packet_manager_.least_packet_awaited_by_peer(),
1511       sent_packet_manager_.GetCongestionWindow());
1512
1513   bool reset_retransmission_alarm =
1514       sent_packet_manager_.OnPacketSent(sequence_number, now, length,
1515                                         transmission_type, retransmittable);
1516
1517   if (reset_retransmission_alarm || !retransmission_alarm_->IsSet()) {
1518     retransmission_alarm_->Cancel();
1519     QuicTime retransmission_time = sent_packet_manager_.GetRetransmissionTime();
1520     if (retransmission_time != QuicTime::Zero()) {
1521       retransmission_alarm_->Set(retransmission_time);
1522     }
1523   }
1524
1525   stats_.bytes_sent += result.bytes_written;
1526   ++stats_.packets_sent;
1527
1528   if (transmission_type != NOT_RETRANSMISSION) {
1529     stats_.bytes_retransmitted += result.bytes_written;
1530     ++stats_.packets_retransmitted;
1531   }
1532
1533   return true;
1534 }
1535
1536 bool QuicConnection::OnSerializedPacket(
1537     const SerializedPacket& serialized_packet) {
1538   if (serialized_packet.retransmittable_frames) {
1539     serialized_packet.retransmittable_frames->
1540         set_encryption_level(encryption_level_);
1541   }
1542   sent_packet_manager_.OnSerializedPacket(serialized_packet);
1543   // The TransmissionType is NOT_RETRANSMISSION because all retransmissions
1544   // serialize packets and invoke SendOrQueuePacket directly.
1545   return SendOrQueuePacket(encryption_level_,
1546                            serialized_packet,
1547                            NOT_RETRANSMISSION);
1548 }
1549
1550 bool QuicConnection::SendOrQueuePacket(EncryptionLevel level,
1551                                        const SerializedPacket& packet,
1552                                        TransmissionType transmission_type) {
1553   if (packet.packet == NULL) {
1554     LOG(DFATAL) << "NULL packet passed in to SendOrQueuePacket";
1555     return true;
1556   }
1557
1558   sent_entropy_manager_.RecordPacketEntropyHash(packet.sequence_number,
1559                                                 packet.entropy_hash);
1560   QueuedPacket queued_packet(packet, level, transmission_type);
1561   // If there are already queued packets, put this at the end,
1562   // unless it's ConnectionClose, in which case it is written immediately.
1563   if ((queued_packet.type == CONNECTION_CLOSE || queued_packets_.empty()) &&
1564       WritePacket(queued_packet)) {
1565     delete packet.packet;
1566     return true;
1567   }
1568   queued_packet.type = QUEUED;
1569   queued_packets_.push_back(queued_packet);
1570   return false;
1571 }
1572
1573 void QuicConnection::UpdateStopWaiting(QuicStopWaitingFrame* stop_waiting) {
1574   stop_waiting->least_unacked = GetLeastUnacked();
1575   stop_waiting->entropy_hash = sent_entropy_manager_.EntropyHash(
1576       stop_waiting->least_unacked - 1);
1577 }
1578
1579 void QuicConnection::SendPing() {
1580   if (retransmission_alarm_->IsSet()) {
1581     return;
1582   }
1583   if (version() <= QUIC_VERSION_17) {
1584     // TODO(rch): remove this when we remove version 17.
1585     // This is a horrible hideous hack which we should not support.
1586     IOVector data;
1587     char c_data[] = "C";
1588     data.Append(c_data, 1);
1589     QuicConsumedData consumed_data =
1590         packet_generator_.ConsumeData(kCryptoStreamId, data, 0, false, NULL);
1591     if (consumed_data.bytes_consumed == 0) {
1592       DLOG(ERROR) << "Unable to send ping!?";
1593     }
1594   } else {
1595     packet_generator_.AddControlFrame(QuicFrame(new QuicPingFrame));
1596   }
1597 }
1598
1599 void QuicConnection::SendAck() {
1600   ack_alarm_->Cancel();
1601   stop_waiting_count_ = 0;
1602   // TODO(rch): delay this until the CreateFeedbackFrame
1603   // method is invoked.  This requires changes SetShouldSendAck
1604   // to be a no-arg method, and re-jiggering its implementation.
1605   bool send_feedback = false;
1606   if (received_packet_manager_.GenerateCongestionFeedback(
1607           &outgoing_congestion_feedback_)) {
1608     DVLOG(1) << ENDPOINT << "Sending feedback: "
1609              << outgoing_congestion_feedback_;
1610     send_feedback = true;
1611   }
1612
1613   packet_generator_.SetShouldSendAck(send_feedback,
1614                                      version() > QUIC_VERSION_15);
1615 }
1616
1617 void QuicConnection::OnRetransmissionTimeout() {
1618   if (!sent_packet_manager_.HasUnackedPackets()) {
1619     return;
1620   }
1621
1622   sent_packet_manager_.OnRetransmissionTimeout();
1623
1624   WriteIfNotBlocked();
1625
1626   // Ensure the retransmission alarm is always set if there are unacked packets.
1627   if (!HasQueuedData() && !retransmission_alarm_->IsSet()) {
1628     QuicTime rto_timeout = sent_packet_manager_.GetRetransmissionTime();
1629     if (rto_timeout != QuicTime::Zero()) {
1630       retransmission_alarm_->Set(rto_timeout);
1631     }
1632   }
1633 }
1634
1635 void QuicConnection::SetEncrypter(EncryptionLevel level,
1636                                   QuicEncrypter* encrypter) {
1637   framer_.SetEncrypter(level, encrypter);
1638 }
1639
1640 const QuicEncrypter* QuicConnection::encrypter(EncryptionLevel level) const {
1641   return framer_.encrypter(level);
1642 }
1643
1644 void QuicConnection::SetDefaultEncryptionLevel(EncryptionLevel level) {
1645   encryption_level_ = level;
1646   packet_creator_.set_encryption_level(level);
1647 }
1648
1649 void QuicConnection::SetDecrypter(QuicDecrypter* decrypter,
1650                                   EncryptionLevel level) {
1651   framer_.SetDecrypter(decrypter, level);
1652 }
1653
1654 void QuicConnection::SetAlternativeDecrypter(QuicDecrypter* decrypter,
1655                                              EncryptionLevel level,
1656                                              bool latch_once_used) {
1657   framer_.SetAlternativeDecrypter(decrypter, level, latch_once_used);
1658 }
1659
1660 const QuicDecrypter* QuicConnection::decrypter() const {
1661   return framer_.decrypter();
1662 }
1663
1664 const QuicDecrypter* QuicConnection::alternative_decrypter() const {
1665   return framer_.alternative_decrypter();
1666 }
1667
1668 void QuicConnection::QueueUndecryptablePacket(
1669     const QuicEncryptedPacket& packet) {
1670   DVLOG(1) << ENDPOINT << "Queueing undecryptable packet.";
1671   undecryptable_packets_.push_back(packet.Clone());
1672 }
1673
1674 void QuicConnection::MaybeProcessUndecryptablePackets() {
1675   if (undecryptable_packets_.empty() || encryption_level_ == ENCRYPTION_NONE) {
1676     return;
1677   }
1678
1679   while (connected_ && !undecryptable_packets_.empty()) {
1680     DVLOG(1) << ENDPOINT << "Attempting to process undecryptable packet";
1681     QuicEncryptedPacket* packet = undecryptable_packets_.front();
1682     if (!framer_.ProcessPacket(*packet) &&
1683         framer_.error() == QUIC_DECRYPTION_FAILURE) {
1684       DVLOG(1) << ENDPOINT << "Unable to process undecryptable packet...";
1685       break;
1686     }
1687     DVLOG(1) << ENDPOINT << "Processed undecryptable packet!";
1688     ++stats_.packets_processed;
1689     delete packet;
1690     undecryptable_packets_.pop_front();
1691   }
1692
1693   // Once forward secure encryption is in use, there will be no
1694   // new keys installed and hence any undecryptable packets will
1695   // never be able to be decrypted.
1696   if (encryption_level_ == ENCRYPTION_FORWARD_SECURE) {
1697     STLDeleteElements(&undecryptable_packets_);
1698   }
1699 }
1700
1701 void QuicConnection::MaybeProcessRevivedPacket() {
1702   QuicFecGroup* group = GetFecGroup();
1703   if (!connected_ || group == NULL || !group->CanRevive()) {
1704     return;
1705   }
1706   QuicPacketHeader revived_header;
1707   char revived_payload[kMaxPacketSize];
1708   size_t len = group->Revive(&revived_header, revived_payload, kMaxPacketSize);
1709   revived_header.public_header.connection_id = connection_id_;
1710   revived_header.public_header.connection_id_length =
1711       last_header_.public_header.connection_id_length;
1712   revived_header.public_header.version_flag = false;
1713   revived_header.public_header.reset_flag = false;
1714   revived_header.public_header.sequence_number_length =
1715       last_header_.public_header.sequence_number_length;
1716   revived_header.fec_flag = false;
1717   revived_header.is_in_fec_group = NOT_IN_FEC_GROUP;
1718   revived_header.fec_group = 0;
1719   group_map_.erase(last_header_.fec_group);
1720   last_decrypted_packet_level_ = group->effective_encryption_level();
1721   DCHECK_LT(last_decrypted_packet_level_, NUM_ENCRYPTION_LEVELS);
1722   delete group;
1723
1724   last_packet_revived_ = true;
1725   if (debug_visitor_) {
1726     debug_visitor_->OnRevivedPacket(revived_header,
1727                                     StringPiece(revived_payload, len));
1728   }
1729
1730   ++stats_.packets_revived;
1731   framer_.ProcessRevivedPacket(&revived_header,
1732                                StringPiece(revived_payload, len));
1733 }
1734
1735 QuicFecGroup* QuicConnection::GetFecGroup() {
1736   QuicFecGroupNumber fec_group_num = last_header_.fec_group;
1737   if (fec_group_num == 0) {
1738     return NULL;
1739   }
1740   if (group_map_.count(fec_group_num) == 0) {
1741     if (group_map_.size() >= kMaxFecGroups) {  // Too many groups
1742       if (fec_group_num < group_map_.begin()->first) {
1743         // The group being requested is a group we've seen before and deleted.
1744         // Don't recreate it.
1745         return NULL;
1746       }
1747       // Clear the lowest group number.
1748       delete group_map_.begin()->second;
1749       group_map_.erase(group_map_.begin());
1750     }
1751     group_map_[fec_group_num] = new QuicFecGroup();
1752   }
1753   return group_map_[fec_group_num];
1754 }
1755
1756 void QuicConnection::SendConnectionClose(QuicErrorCode error) {
1757   SendConnectionCloseWithDetails(error, string());
1758 }
1759
1760 void QuicConnection::SendConnectionCloseWithDetails(QuicErrorCode error,
1761                                                     const string& details) {
1762   // If we're write blocked, WritePacket() will not send, but will capture the
1763   // serialized packet.
1764   SendConnectionClosePacket(error, details);
1765   if (connected_) {
1766     // It's possible that while sending the connection close packet, we get a
1767     // socket error and disconnect right then and there.  Avoid a double
1768     // disconnect in that case.
1769     CloseConnection(error, false);
1770   }
1771 }
1772
1773 void QuicConnection::SendConnectionClosePacket(QuicErrorCode error,
1774                                                const string& details) {
1775   DVLOG(1) << ENDPOINT << "Force closing " << connection_id()
1776            << " with error " << QuicUtils::ErrorToString(error)
1777            << " (" << error << ") " << details;
1778   ScopedPacketBundler ack_bundler(this, SEND_ACK);
1779   QuicConnectionCloseFrame* frame = new QuicConnectionCloseFrame();
1780   frame->error_code = error;
1781   frame->error_details = details;
1782   packet_generator_.AddControlFrame(QuicFrame(frame));
1783   Flush();
1784 }
1785
1786 void QuicConnection::CloseConnection(QuicErrorCode error, bool from_peer) {
1787   if (!connected_) {
1788     DLOG(DFATAL) << "Error: attempt to close an already closed connection"
1789                  << base::debug::StackTrace().ToString();
1790     return;
1791   }
1792   connected_ = false;
1793   visitor_->OnConnectionClosed(error, from_peer);
1794   // Cancel the alarms so they don't trigger any action now that the
1795   // connection is closed.
1796   ack_alarm_->Cancel();
1797   resume_writes_alarm_->Cancel();
1798   retransmission_alarm_->Cancel();
1799   send_alarm_->Cancel();
1800   timeout_alarm_->Cancel();
1801 }
1802
1803 void QuicConnection::SendGoAway(QuicErrorCode error,
1804                                 QuicStreamId last_good_stream_id,
1805                                 const string& reason) {
1806   DVLOG(1) << ENDPOINT << "Going away with error "
1807            << QuicUtils::ErrorToString(error)
1808            << " (" << error << ")";
1809
1810   // Opportunistically bundle an ack with this outgoing packet.
1811   ScopedPacketBundler ack_bundler(this, BUNDLE_PENDING_ACK);
1812   packet_generator_.AddControlFrame(
1813       QuicFrame(new QuicGoAwayFrame(error, last_good_stream_id, reason)));
1814 }
1815
1816 void QuicConnection::CloseFecGroupsBefore(
1817     QuicPacketSequenceNumber sequence_number) {
1818   FecGroupMap::iterator it = group_map_.begin();
1819   while (it != group_map_.end()) {
1820     // If this is the current group or the group doesn't protect this packet
1821     // we can ignore it.
1822     if (last_header_.fec_group == it->first ||
1823         !it->second->ProtectsPacketsBefore(sequence_number)) {
1824       ++it;
1825       continue;
1826     }
1827     QuicFecGroup* fec_group = it->second;
1828     DCHECK(!fec_group->CanRevive());
1829     FecGroupMap::iterator next = it;
1830     ++next;
1831     group_map_.erase(it);
1832     delete fec_group;
1833     it = next;
1834   }
1835 }
1836
1837 void QuicConnection::Flush() {
1838   packet_generator_.FlushAllQueuedFrames();
1839 }
1840
1841 bool QuicConnection::HasQueuedData() const {
1842   return pending_version_negotiation_packet_ ||
1843       !queued_packets_.empty() || packet_generator_.HasQueuedFrames();
1844 }
1845
1846 bool QuicConnection::CanWriteStreamData() {
1847   // Don't write stream data if there are negotiation or queued data packets
1848   // to send. Otherwise, continue and bundle as many frames as possible.
1849   if (pending_version_negotiation_packet_ || !queued_packets_.empty()) {
1850     return false;
1851   }
1852
1853   IsHandshake pending_handshake = visitor_->HasPendingHandshake() ?
1854       IS_HANDSHAKE : NOT_HANDSHAKE;
1855   // Sending queued packets may have caused the socket to become write blocked,
1856   // or the congestion manager to prohibit sending.  If we've sent everything
1857   // we had queued and we're still not blocked, let the visitor know it can
1858   // write more.
1859   return ShouldGeneratePacket(NOT_RETRANSMISSION, HAS_RETRANSMITTABLE_DATA,
1860                               pending_handshake);
1861 }
1862
1863 void QuicConnection::SetIdleNetworkTimeout(QuicTime::Delta timeout) {
1864   if (timeout < idle_network_timeout_) {
1865     idle_network_timeout_ = timeout;
1866     CheckForTimeout();
1867   } else {
1868     idle_network_timeout_ = timeout;
1869   }
1870 }
1871
1872 void QuicConnection::SetOverallConnectionTimeout(QuicTime::Delta timeout) {
1873   if (timeout < overall_connection_timeout_) {
1874     overall_connection_timeout_ = timeout;
1875     CheckForTimeout();
1876   } else {
1877     overall_connection_timeout_ = timeout;
1878   }
1879 }
1880
1881 bool QuicConnection::CheckForTimeout() {
1882   QuicTime now = clock_->ApproximateNow();
1883   QuicTime time_of_last_packet = max(time_of_last_received_packet_,
1884                                      time_of_last_sent_new_packet_);
1885
1886   // |delta| can be < 0 as |now| is approximate time but |time_of_last_packet|
1887   // is accurate time. However, this should not change the behavior of
1888   // timeout handling.
1889   QuicTime::Delta delta = now.Subtract(time_of_last_packet);
1890   DVLOG(1) << ENDPOINT << "last packet "
1891            << time_of_last_packet.ToDebuggingValue()
1892            << " now:" << now.ToDebuggingValue()
1893            << " delta:" << delta.ToMicroseconds()
1894            << " network_timeout: " << idle_network_timeout_.ToMicroseconds();
1895   if (delta >= idle_network_timeout_) {
1896     DVLOG(1) << ENDPOINT << "Connection timedout due to no network activity.";
1897     SendConnectionClose(QUIC_CONNECTION_TIMED_OUT);
1898     return true;
1899   }
1900
1901   // Next timeout delta.
1902   QuicTime::Delta timeout = idle_network_timeout_.Subtract(delta);
1903
1904   if (!overall_connection_timeout_.IsInfinite()) {
1905     QuicTime::Delta connected_time =
1906         now.Subtract(stats_.connection_creation_time);
1907     DVLOG(1) << ENDPOINT << "connection time: "
1908              << connected_time.ToMilliseconds() << " overall timeout: "
1909              << overall_connection_timeout_.ToMilliseconds();
1910     if (connected_time >= overall_connection_timeout_) {
1911       DVLOG(1) << ENDPOINT <<
1912           "Connection timedout due to overall connection timeout.";
1913       SendConnectionClose(QUIC_CONNECTION_TIMED_OUT);
1914       return true;
1915     }
1916
1917     // Take the min timeout.
1918     QuicTime::Delta connection_timeout =
1919         overall_connection_timeout_.Subtract(connected_time);
1920     if (connection_timeout < timeout) {
1921       timeout = connection_timeout;
1922     }
1923   }
1924
1925   timeout_alarm_->Cancel();
1926   timeout_alarm_->Set(clock_->ApproximateNow().Add(timeout));
1927   return false;
1928 }
1929
1930 void QuicConnection::SetPingAlarm() {
1931   if (is_server_) {
1932     // Only clients send pings.
1933     return;
1934   }
1935   ping_alarm_->Cancel();
1936   if (!visitor_->HasOpenDataStreams()) {
1937     // Don't send a ping unless there are open streams.
1938     return;
1939   }
1940   QuicTime::Delta ping_timeout = QuicTime::Delta::FromSeconds(kPingTimeoutSecs);
1941   ping_alarm_->Set(clock_->ApproximateNow().Add(ping_timeout));
1942 }
1943
1944 QuicConnection::ScopedPacketBundler::ScopedPacketBundler(
1945     QuicConnection* connection,
1946     AckBundling send_ack)
1947     : connection_(connection),
1948       already_in_batch_mode_(connection->packet_generator_.InBatchMode()) {
1949   // Move generator into batch mode. If caller wants us to include an ack,
1950   // check the delayed-ack timer to see if there's ack info to be sent.
1951   if (!already_in_batch_mode_) {
1952     DVLOG(1) << "Entering Batch Mode.";
1953     connection_->packet_generator_.StartBatchOperations();
1954   }
1955   // Bundle an ack if the alarm is set or with every second packet if we need to
1956   // raise the peer's least unacked.
1957   bool ack_pending =
1958       connection_->ack_alarm_->IsSet() || connection_->stop_waiting_count_ > 1;
1959   if (send_ack == SEND_ACK || (send_ack == BUNDLE_PENDING_ACK && ack_pending)) {
1960     DVLOG(1) << "Bundling ack with outgoing packet.";
1961     connection_->SendAck();
1962   }
1963 }
1964
1965 QuicConnection::ScopedPacketBundler::~ScopedPacketBundler() {
1966   // If we changed the generator's batch state, restore original batch state.
1967   if (!already_in_batch_mode_) {
1968     DVLOG(1) << "Leaving Batch Mode.";
1969     connection_->packet_generator_.FinishBatchOperations();
1970   }
1971   DCHECK_EQ(already_in_batch_mode_,
1972             connection_->packet_generator_.InBatchMode());
1973 }
1974
1975 }  // namespace net