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