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 // The entity that handles framing writes for a Quic client or server.
      6 // Each QuicSession will have a connection associated with it.
      7 //
      8 // On the server side, the Dispatcher handles the raw reads, and hands off
      9 // packets via ProcessUdpPacket for framing and processing.
     10 //
     11 // On the client side, the Connection handles the raw reads, as well as the
     12 // processing.
     13 //
     14 // Note: this class is not thread-safe.
     15 
     16 #ifndef NET_QUIC_QUIC_CONNECTION_H_
     17 #define NET_QUIC_QUIC_CONNECTION_H_
     18 
     19 #include <deque>
     20 #include <list>
     21 #include <map>
     22 #include <queue>
     23 #include <set>
     24 #include <vector>
     25 
     26 #include "base/containers/hash_tables.h"
     27 #include "net/base/ip_endpoint.h"
     28 #include "net/base/linked_hash_map.h"
     29 #include "net/quic/congestion_control/quic_congestion_manager.h"
     30 #include "net/quic/quic_alarm.h"
     31 #include "net/quic/quic_blocked_writer_interface.h"
     32 #include "net/quic/quic_framer.h"
     33 #include "net/quic/quic_packet_creator.h"
     34 #include "net/quic/quic_packet_generator.h"
     35 #include "net/quic/quic_protocol.h"
     36 #include "net/quic/quic_received_packet_manager.h"
     37 #include "net/quic/quic_sent_entropy_manager.h"
     38 #include "net/quic/quic_stats.h"
     39 
     40 namespace net {
     41 
     42 class QuicClock;
     43 class QuicConnection;
     44 class QuicFecGroup;
     45 class QuicRandom;
     46 
     47 namespace test {
     48 class QuicConnectionPeer;
     49 }  // namespace test
     50 
     51 class NET_EXPORT_PRIVATE QuicConnectionVisitorInterface {
     52  public:
     53   virtual ~QuicConnectionVisitorInterface() {}
     54 
     55   // A simple visitor interface for dealing with data frames.  The session
     56   // should determine if all frames will be accepted, and return true if so.
     57   // If any frames can't be processed or buffered, none of the data should
     58   // be used, and the callee should return false.
     59   virtual bool OnPacket(const IPEndPoint& self_address,
     60                         const IPEndPoint& peer_address,
     61                         const QuicPacketHeader& header,
     62                         const std::vector<QuicStreamFrame>& frame) = 0;
     63 
     64   // Called when the stream is reset by the peer.
     65   virtual void OnRstStream(const QuicRstStreamFrame& frame) = 0;
     66 
     67   // Called when the connection is going away according to the peer.
     68   virtual void OnGoAway(const QuicGoAwayFrame& frame) = 0;
     69 
     70   // Called when the connection is closed either locally by the framer, or
     71   // remotely by the peer.
     72   virtual void ConnectionClose(QuicErrorCode error,
     73                                bool from_peer) = 0;
     74 
     75   // Called when packets are acked by the peer.
     76   virtual void OnAck(const SequenceNumberSet& acked_packets) = 0;
     77 
     78   // Called when a blocked socket becomes writable.  If all pending bytes for
     79   // this visitor are consumed by the connection successfully this should
     80   // return true, otherwise it should return false.
     81   virtual bool OnCanWrite() = 0;
     82 };
     83 
     84 // Interface which gets callbacks from the QuicConnection at interesting
     85 // points.  Implementations must not mutate the state of the connection
     86 // as a result of these callbacks.
     87 class NET_EXPORT_PRIVATE QuicConnectionDebugVisitorInterface
     88     : public QuicPacketGenerator::DebugDelegateInterface {
     89  public:
     90   virtual ~QuicConnectionDebugVisitorInterface() {}
     91 
     92   // Called when a packet has been sent.
     93   virtual void OnPacketSent(QuicPacketSequenceNumber sequence_number,
     94                             EncryptionLevel level,
     95                             const QuicEncryptedPacket& packet,
     96                             int rv) = 0;
     97 
     98   // Called when a packet has been received, but before it is
     99   // validated or parsed.
    100   virtual void OnPacketReceived(const IPEndPoint& self_address,
    101                                 const IPEndPoint& peer_address,
    102                                 const QuicEncryptedPacket& packet) = 0;
    103 
    104   // Called when the protocol version on the received packet doensn't match
    105   // current protocol version of the connection.
    106   virtual void OnProtocolVersionMismatch(QuicVersion version) = 0;
    107 
    108   // Called when the complete header of a packet has been parsed.
    109   virtual void OnPacketHeader(const QuicPacketHeader& header) = 0;
    110 
    111   // Called when a StreamFrame has been parsed.
    112   virtual void OnStreamFrame(const QuicStreamFrame& frame) = 0;
    113 
    114   // Called when a AckFrame has been parsed.
    115   virtual void OnAckFrame(const QuicAckFrame& frame) = 0;
    116 
    117   // Called when a CongestionFeedbackFrame has been parsed.
    118   virtual void OnCongestionFeedbackFrame(
    119       const QuicCongestionFeedbackFrame& frame) = 0;
    120 
    121   // Called when a RstStreamFrame has been parsed.
    122   virtual void OnRstStreamFrame(const QuicRstStreamFrame& frame) = 0;
    123 
    124   // Called when a ConnectionCloseFrame has been parsed.
    125   virtual void OnConnectionCloseFrame(
    126       const QuicConnectionCloseFrame& frame) = 0;
    127 
    128   // Called when a public reset packet has been received.
    129   virtual void OnPublicResetPacket(const QuicPublicResetPacket& packet) = 0;
    130 
    131   // Called when a version negotiation packet has been received.
    132   virtual void OnVersionNegotiationPacket(
    133       const QuicVersionNegotiationPacket& packet) = 0;
    134 
    135   // Called after a packet has been successfully parsed which results
    136   // in the revival of a packet via FEC.
    137   virtual void OnRevivedPacket(const QuicPacketHeader& revived_header,
    138                                base::StringPiece payload) = 0;
    139 };
    140 
    141 class NET_EXPORT_PRIVATE QuicConnectionHelperInterface {
    142  public:
    143   virtual ~QuicConnectionHelperInterface() {}
    144 
    145   // Sets the QuicConnection to be used by this helper.  This method
    146   // must only be called once.
    147   virtual void SetConnection(QuicConnection* connection) = 0;
    148 
    149   // Returns a QuicClock to be used for all time related functions.
    150   virtual const QuicClock* GetClock() const = 0;
    151 
    152   // Returns a QuicRandom to be used for all random number related functions.
    153   virtual QuicRandom* GetRandomGenerator() = 0;
    154 
    155   // Sends the packet out to the peer, possibly simulating packet
    156   // loss if FLAGS_fake_packet_loss_percentage is set.  If the write
    157   // succeeded, returns the number of bytes written.  If the write
    158   // failed, returns -1 and the error code will be copied to |*error|.
    159   virtual int WritePacketToWire(const QuicEncryptedPacket& packet,
    160                                 int* error) = 0;
    161 
    162   // Returns true if the helper buffers and subsequently rewrites data
    163   // when an attempt to write results in the underlying socket becoming
    164   // write blocked.
    165   virtual bool IsWriteBlockedDataBuffered() = 0;
    166 
    167   // Returns true if |error| represents a write-block error code such
    168   // as EAGAIN or ERR_IO_PENDING.
    169   virtual bool IsWriteBlocked(int error) = 0;
    170 
    171   // Creates a new platform-specific alarm which will be configured to
    172   // notify |delegate| when the alarm fires.  Caller takes ownership
    173   // of the new alarm, which will not yet be "set" to fire.
    174   virtual QuicAlarm* CreateAlarm(QuicAlarm::Delegate* delegate) = 0;
    175 };
    176 
    177 class NET_EXPORT_PRIVATE QuicConnection
    178     : public QuicFramerVisitorInterface,
    179       public QuicBlockedWriterInterface,
    180       public QuicPacketGenerator::DelegateInterface {
    181  public:
    182   enum Force {
    183     NO_FORCE,
    184     FORCE
    185   };
    186 
    187   enum RetransmissionType {
    188     INITIAL_ENCRYPTION_ONLY,
    189     ALL_PACKETS
    190   };
    191 
    192   // Constructs a new QuicConnection for the specified |guid| and |address|.
    193   // |helper| will be owned by this connection.
    194   QuicConnection(QuicGuid guid,
    195                  IPEndPoint address,
    196                  QuicConnectionHelperInterface* helper,
    197                  bool is_server,
    198                  QuicVersion version);
    199   virtual ~QuicConnection();
    200 
    201   static void DeleteEnclosedFrame(QuicFrame* frame);
    202 
    203   // Send the data payload to the peer.
    204   // Returns a pair with the number of bytes consumed from data, and a boolean
    205   // indicating if the fin bit was consumed.  This does not indicate the data
    206   // has been sent on the wire: it may have been turned into a packet and queued
    207   // if the socket was unexpectedly blocked.
    208   QuicConsumedData SendStreamData(QuicStreamId id,
    209                                   base::StringPiece data,
    210                                   QuicStreamOffset offset,
    211                                   bool fin);
    212   // Send a stream reset frame to the peer.
    213   virtual void SendRstStream(QuicStreamId id,
    214                              QuicRstStreamErrorCode error);
    215 
    216   // Sends the connection close packet without affecting the state of the
    217   // connection.  This should only be called if the session is actively being
    218   // destroyed: otherwise call SendConnectionCloseWithDetails instead.
    219   virtual void SendConnectionClosePacket(QuicErrorCode error,
    220                                          const std::string& details);
    221 
    222   // Sends a connection close frame to the peer, and closes the connection by
    223   // calling CloseConnection(notifying the visitor as it does so).
    224   virtual void SendConnectionClose(QuicErrorCode error);
    225   virtual void SendConnectionCloseWithDetails(QuicErrorCode error,
    226                                               const std::string& details);
    227   // Notifies the visitor of the close and marks the connection as disconnected.
    228   void CloseConnection(QuicErrorCode error, bool from_peer);
    229   virtual void SendGoAway(QuicErrorCode error,
    230                           QuicStreamId last_good_stream_id,
    231                           const std::string& reason);
    232 
    233   // Returns statistics tracked for this connection.
    234   const QuicConnectionStats& GetStats();
    235 
    236   // Processes an incoming UDP packet (consisting of a QuicEncryptedPacket) from
    237   // the peer.  If processing this packet permits a packet to be revived from
    238   // its FEC group that packet will be revived and processed.
    239   virtual void ProcessUdpPacket(const IPEndPoint& self_address,
    240                                 const IPEndPoint& peer_address,
    241                                 const QuicEncryptedPacket& packet);
    242 
    243   // QuicBlockedWriterInterface
    244   // Called when the underlying connection becomes writable to allow queued
    245   // writes to happen.  Returns false if the socket has become blocked.
    246   virtual bool OnCanWrite() OVERRIDE;
    247 
    248   // If the socket is not blocked, this allows queued writes to happen. Returns
    249   // false if the socket has become blocked.
    250   bool WriteIfNotBlocked();
    251 
    252   // Do any work which logically would be done in OnPacket but can not be
    253   // safely done until the packet is validated.  Returns true if the packet
    254   // can be handled, false otherwise.
    255   bool ProcessValidatedPacket();
    256 
    257   // The version of the protocol this connection is using.
    258   QuicVersion version() const { return framer_.version(); }
    259 
    260   // From QuicFramerVisitorInterface
    261   virtual void OnError(QuicFramer* framer) OVERRIDE;
    262   virtual bool OnProtocolVersionMismatch(QuicVersion received_version) OVERRIDE;
    263   virtual void OnPacket() OVERRIDE;
    264   virtual void OnPublicResetPacket(
    265       const QuicPublicResetPacket& packet) OVERRIDE;
    266   virtual void OnVersionNegotiationPacket(
    267       const QuicVersionNegotiationPacket& packet) OVERRIDE;
    268   virtual void OnRevivedPacket() OVERRIDE;
    269   virtual bool OnPacketHeader(const QuicPacketHeader& header) OVERRIDE;
    270   virtual void OnFecProtectedPayload(base::StringPiece payload) OVERRIDE;
    271   virtual bool OnStreamFrame(const QuicStreamFrame& frame) OVERRIDE;
    272   virtual bool OnAckFrame(const QuicAckFrame& frame) OVERRIDE;
    273   virtual bool OnCongestionFeedbackFrame(
    274       const QuicCongestionFeedbackFrame& frame) OVERRIDE;
    275   virtual bool OnRstStreamFrame(const QuicRstStreamFrame& frame) OVERRIDE;
    276   virtual bool OnConnectionCloseFrame(
    277       const QuicConnectionCloseFrame& frame) OVERRIDE;
    278   virtual bool OnGoAwayFrame(const QuicGoAwayFrame& frame) OVERRIDE;
    279   virtual void OnFecData(const QuicFecData& fec) OVERRIDE;
    280   virtual void OnPacketComplete() OVERRIDE;
    281 
    282   // QuicPacketGenerator::DelegateInterface
    283   virtual bool CanWrite(
    284       Retransmission is_retransmission,
    285       HasRetransmittableData has_retransmittable_data,
    286       IsHandshake handshake) OVERRIDE;
    287   virtual QuicAckFrame* CreateAckFrame() OVERRIDE;
    288   virtual QuicCongestionFeedbackFrame* CreateFeedbackFrame() OVERRIDE;
    289   virtual bool OnSerializedPacket(const SerializedPacket& packet) OVERRIDE;
    290 
    291   // Accessors
    292   void set_visitor(QuicConnectionVisitorInterface* visitor) {
    293     visitor_ = visitor;
    294   }
    295   void set_debug_visitor(QuicConnectionDebugVisitorInterface* debug_visitor) {
    296     debug_visitor_ = debug_visitor;
    297     packet_generator_.set_debug_delegate(debug_visitor);
    298   }
    299   const IPEndPoint& self_address() const { return self_address_; }
    300   const IPEndPoint& peer_address() const { return peer_address_; }
    301   QuicGuid guid() const { return guid_; }
    302   const QuicClock* clock() const { return clock_; }
    303   QuicRandom* random_generator() const { return random_generator_; }
    304 
    305   // Called by a RetransmissionAlarm when the timer goes off.  If the peer
    306   // appears to be sending truncated acks, this returns false to indicate
    307   // failure, otherwise it calls MaybeRetransmitPacket and returns true.
    308   bool MaybeRetransmitPacketForRTO(QuicPacketSequenceNumber sequence_number);
    309 
    310   // Called to retransmit a packet, in the case a packet was sufficiently
    311   // nacked by the peer, or not acked within the time out window.
    312   void RetransmitPacket(QuicPacketSequenceNumber sequence_number);
    313 
    314   QuicPacketCreator::Options* options() { return packet_creator_.options(); }
    315 
    316   bool connected() { return connected_; }
    317 
    318   size_t NumFecGroups() const { return group_map_.size(); }
    319 
    320   // Testing only.
    321   size_t NumQueuedPackets() const { return queued_packets_.size(); }
    322 
    323   // Returns true if the connection has queued packets or frames.
    324   bool HasQueuedData() const;
    325 
    326   // Sets (or resets) the idle state connection timeout. Also, checks and times
    327   // out the connection if network timer has expired for |timeout|.
    328   void SetIdleNetworkTimeout(QuicTime::Delta timeout);
    329   // Sets (or resets) the total time delta the connection can be alive for.
    330   // Also, checks and times out the connection if timer has expired for
    331   // |timeout|. Used to limit the time a connection can be alive before crypto
    332   // handshake finishes.
    333   void SetOverallConnectionTimeout(QuicTime::Delta timeout);
    334 
    335   // If the connection has timed out, this will close the connection and return
    336   // true.  Otherwise, it will return false and will reset the timeout alarm.
    337   bool CheckForTimeout();
    338 
    339   // Returns true of the next packet to be sent should be "lost" by
    340   // not actually writing it to the wire.
    341   bool ShouldSimulateLostPacket();
    342 
    343   // Sets up a packet with an QuicAckFrame and sends it out.
    344   void SendAck();
    345 
    346   // Called when an RTO fires.  Returns the time when this alarm
    347   // should next fire, or 0 if no retransmission alarm should be set.
    348   QuicTime OnRetransmissionTimeout();
    349 
    350   // Retransmits unacked packets which were sent with initial encryption, if
    351   // |initial_encryption_only| is true, otherwise retransmits all unacked
    352   // packets. Used when the negotiated protocol version is different than what
    353   // was initially assumed and when the visitor wants to re-transmit packets
    354   // with initial encryption when the initial encrypter changes.
    355   void RetransmitUnackedPackets(RetransmissionType retransmission_type);
    356 
    357   // Changes the encrypter used for level |level| to |encrypter|. The function
    358   // takes ownership of |encrypter|.
    359   void SetEncrypter(EncryptionLevel level, QuicEncrypter* encrypter);
    360   const QuicEncrypter* encrypter(EncryptionLevel level) const;
    361 
    362   // SetDefaultEncryptionLevel sets the encryption level that will be applied
    363   // to new packets.
    364   void SetDefaultEncryptionLevel(EncryptionLevel level);
    365 
    366   // SetDecrypter sets the primary decrypter, replacing any that already exists,
    367   // and takes ownership. If an alternative decrypter is in place then the
    368   // function DCHECKs. This is intended for cases where one knows that future
    369   // packets will be using the new decrypter and the previous decrypter is now
    370   // obsolete.
    371   void SetDecrypter(QuicDecrypter* decrypter);
    372 
    373   // SetAlternativeDecrypter sets a decrypter that may be used to decrypt
    374   // future packets and takes ownership of it. If |latch_once_used| is true,
    375   // then the first time that the decrypter is successful it will replace the
    376   // primary decrypter. Otherwise both decrypters will remain active and the
    377   // primary decrypter will be the one last used.
    378   void SetAlternativeDecrypter(QuicDecrypter* decrypter,
    379                                bool latch_once_used);
    380 
    381   const QuicDecrypter* decrypter() const;
    382   const QuicDecrypter* alternative_decrypter() const;
    383 
    384  protected:
    385   // Send a packet to the peer using encryption |level|. If |sequence_number|
    386   // is present in the |retransmission_map_|, then contents of this packet will
    387   // be retransmitted with a new sequence number if it's not acked by the peer.
    388   // Deletes |packet| via WritePacket call or transfers ownership to
    389   // QueuedPacket, ultimately deleted via WritePacket. Also, it updates the
    390   // entropy map corresponding to |sequence_number| using |entropy_hash|.
    391   // TODO(wtc): none of the callers check the return value.
    392   virtual bool SendOrQueuePacket(EncryptionLevel level,
    393                                  QuicPacketSequenceNumber sequence_number,
    394                                  QuicPacket* packet,
    395                                  QuicPacketEntropyHash entropy_hash,
    396                                  HasRetransmittableData retransmittable);
    397 
    398   // Writes the given packet to socket, encrypted with |level|, with the help
    399   // of helper. Returns true on successful write, false otherwise. However,
    400   // behavior is undefined if connection is not established or broken. In any
    401   // circumstances, a return value of true implies that |packet| has been
    402   // deleted and should not be accessed. If |sequence_number| is present in
    403   // |retransmission_map_| it also sets up retransmission of the given packet
    404   // in case of successful write. If |force| is FORCE, then the packet will be
    405   // sent immediately and the send scheduler will not be consulted.
    406   bool WritePacket(EncryptionLevel level,
    407                    QuicPacketSequenceNumber sequence_number,
    408                    QuicPacket* packet,
    409                    HasRetransmittableData retransmittable,
    410                    Force force);
    411 
    412   int WritePacketToWire(QuicPacketSequenceNumber sequence_number,
    413                         EncryptionLevel level,
    414                         const QuicEncryptedPacket& packet,
    415                         int* error);
    416 
    417   // Make sure an ack we got from our peer is sane.
    418   bool ValidateAckFrame(const QuicAckFrame& incoming_ack);
    419 
    420   QuicConnectionHelperInterface* helper() { return helper_.get(); }
    421 
    422   // Selects and updates the version of the protocol being used by selecting a
    423   // version from |available_versions| which is also supported. Returns true if
    424   // such a version exists, false otherwise.
    425   bool SelectMutualVersion(const QuicVersionVector& available_versions);
    426 
    427   QuicFramer framer_;
    428 
    429  private:
    430   friend class test::QuicConnectionPeer;
    431 
    432   // Packets which have not been written to the wire.
    433   // Owns the QuicPacket* packet.
    434   struct QueuedPacket {
    435     QueuedPacket(QuicPacketSequenceNumber sequence_number,
    436                  QuicPacket* packet,
    437                  EncryptionLevel level,
    438                  HasRetransmittableData retransmittable)
    439         : sequence_number(sequence_number),
    440           packet(packet),
    441           encryption_level(level),
    442           retransmittable(retransmittable) {
    443     }
    444 
    445     QuicPacketSequenceNumber sequence_number;
    446     QuicPacket* packet;
    447     const EncryptionLevel encryption_level;
    448     HasRetransmittableData retransmittable;
    449   };
    450 
    451   struct RetransmissionInfo {
    452     explicit RetransmissionInfo(QuicPacketSequenceNumber sequence_number)
    453         : sequence_number(sequence_number),
    454           number_nacks(0),
    455           number_retransmissions(0) {
    456     }
    457 
    458     QuicPacketSequenceNumber sequence_number;
    459     size_t number_nacks;
    460     size_t number_retransmissions;
    461   };
    462 
    463   struct RetransmissionTime {
    464     RetransmissionTime(QuicPacketSequenceNumber sequence_number,
    465                        const QuicTime& scheduled_time,
    466                        bool for_fec)
    467         : sequence_number(sequence_number),
    468           scheduled_time(scheduled_time),
    469           for_fec(for_fec) { }
    470 
    471     QuicPacketSequenceNumber sequence_number;
    472     QuicTime scheduled_time;
    473     bool for_fec;
    474   };
    475 
    476   class RetransmissionTimeComparator {
    477    public:
    478     bool operator()(const RetransmissionTime& lhs,
    479                     const RetransmissionTime& rhs) const {
    480       DCHECK(lhs.scheduled_time.IsInitialized() &&
    481              rhs.scheduled_time.IsInitialized());
    482       return lhs.scheduled_time > rhs.scheduled_time;
    483     }
    484   };
    485 
    486   typedef std::list<QueuedPacket> QueuedPacketList;
    487   typedef linked_hash_map<QuicPacketSequenceNumber,
    488                           RetransmittableFrames*> UnackedPacketMap;
    489   typedef std::map<QuicFecGroupNumber, QuicFecGroup*> FecGroupMap;
    490   typedef base::hash_map<QuicPacketSequenceNumber,
    491                          RetransmissionInfo> RetransmissionMap;
    492   typedef std::priority_queue<RetransmissionTime,
    493                               std::vector<RetransmissionTime>,
    494                               RetransmissionTimeComparator>
    495       RetransmissionTimeouts;
    496 
    497   // Sends a version negotiation packet to the peer.
    498   void SendVersionNegotiationPacket();
    499 
    500   void SetupRetransmission(QuicPacketSequenceNumber sequence_number,
    501                            EncryptionLevel level);
    502   bool IsRetransmission(QuicPacketSequenceNumber sequence_number);
    503 
    504   void SetupAbandonFecTimer(QuicPacketSequenceNumber sequence_number);
    505 
    506   // Clears any accumulated frames from the last received packet.
    507   void ClearLastFrames();
    508 
    509   // Called from OnCanWrite and WriteIfNotBlocked to write queued packets.
    510   // Returns false if the socket has become blocked.
    511   bool DoWrite();
    512 
    513   // Drop packet corresponding to |sequence_number| by deleting entries from
    514   // |unacked_packets_| and |retransmission_map_|, if present. We need to drop
    515   // all packets with encryption level NONE after the default level has been set
    516   // to FORWARD_SECURE.
    517   void DropPacket(QuicPacketSequenceNumber sequence_number);
    518 
    519   // Writes as many queued packets as possible.  The connection must not be
    520   // blocked when this is called.
    521   bool WriteQueuedPackets();
    522 
    523   // Queues |packet| in the hopes that it can be decrypted in the
    524   // future, when a new key is installed.
    525   void QueueUndecryptablePacket(const QuicEncryptedPacket& packet);
    526 
    527   // Attempts to process any queued undecryptable packets.
    528   void MaybeProcessUndecryptablePackets();
    529 
    530   // If a packet can be revived from the current FEC group, then
    531   // revive and process the packet.
    532   void MaybeProcessRevivedPacket();
    533 
    534   void ProcessAckFrame(const QuicAckFrame& incoming_ack);
    535 
    536   void HandleAckForSentPackets(const QuicAckFrame& incoming_ack,
    537                                SequenceNumberSet* acked_packets);
    538   void HandleAckForSentFecPackets(const QuicAckFrame& incoming_ack,
    539                                   SequenceNumberSet* acked_packets);
    540 
    541   // Update the |sent_info| for an outgoing ack.
    542   void UpdateSentPacketInfo(SentPacketInfo* sent_info);
    543 
    544   // Checks if the last packet should instigate an ack.
    545   bool ShouldLastPacketInstigateAck();
    546 
    547   // Sends any packets which are a response to the last packet, including both
    548   // acks and pending writes if an ack opened the congestion window.
    549   void MaybeSendInResponseToPacket(bool last_packet_should_instigate_ack);
    550 
    551   void MaybeAbandonFecPacket(QuicPacketSequenceNumber sequence_number);
    552 
    553   // Get the FEC group associate with the last processed packet or NULL, if the
    554   // group has already been deleted.
    555   QuicFecGroup* GetFecGroup();
    556 
    557   // Closes any FEC groups protecting packets before |sequence_number|.
    558   void CloseFecGroupsBefore(QuicPacketSequenceNumber sequence_number);
    559 
    560   scoped_ptr<QuicConnectionHelperInterface> helper_;
    561   EncryptionLevel encryption_level_;
    562   const QuicClock* clock_;
    563   QuicRandom* random_generator_;
    564 
    565   const QuicGuid guid_;
    566   // Address on the last successfully processed packet received from the
    567   // client.
    568   IPEndPoint self_address_;
    569   IPEndPoint peer_address_;
    570 
    571   bool last_packet_revived_;  // True if the last packet was revived from FEC.
    572   size_t last_size_;  // Size of the last received packet.
    573   QuicPacketHeader last_header_;
    574   std::vector<QuicStreamFrame> last_stream_frames_;
    575   std::vector<QuicAckFrame> last_ack_frames_;
    576   std::vector<QuicCongestionFeedbackFrame> last_congestion_frames_;
    577   std::vector<QuicRstStreamFrame> last_rst_frames_;
    578   std::vector<QuicGoAwayFrame> last_goaway_frames_;
    579 
    580   QuicCongestionFeedbackFrame outgoing_congestion_feedback_;
    581 
    582   // Track some peer state so we can do less bookkeeping
    583   // Largest sequence sent by the peer which had an ack frame (latest ack info).
    584   QuicPacketSequenceNumber largest_seen_packet_with_ack_;
    585 
    586   // When new packets are created which may be retransmitted, they are added
    587   // to this map, which contains owning pointers to the contained frames.
    588   UnackedPacketMap unacked_packets_;
    589 
    590   // Pending fec packets that have not been acked yet. These packets need to be
    591   // cleared out of the cgst_window after a timeout since FEC packets are never
    592   // retransmitted.
    593   // Ask: What should be the timeout for these packets?
    594   UnackedPacketMap unacked_fec_packets_;
    595 
    596   // Collection of packets which were received before encryption was
    597   // established, but which could not be decrypted.  We buffer these on
    598   // the assumption that they could not be processed because they were
    599   // sent with the INITIAL encryption and the CHLO message was lost.
    600   std::deque<QuicEncryptedPacket*> undecryptable_packets_;
    601 
    602   // Heap of packets that we might need to retransmit, and the time at
    603   // which we should retransmit them. Every time a packet is sent it is added
    604   // to this heap which is O(log(number of pending packets to be retransmitted))
    605   // which might be costly. This should be optimized to O(1) by maintaining a
    606   // priority queue of lists of packets to be retransmitted, where list x
    607   // contains all packets that have been retransmitted x times.
    608   RetransmissionTimeouts retransmission_timeouts_;
    609 
    610   // Map from sequence number to the retransmission info.
    611   RetransmissionMap retransmission_map_;
    612 
    613   // True while OnRetransmissionTimeout is running to prevent
    614   // SetRetransmissionAlarm from being called erroneously.
    615   bool handling_retransmission_timeout_;
    616 
    617   // When packets could not be sent because the socket was not writable,
    618   // they are added to this list.  All corresponding frames are in
    619   // unacked_packets_ if they are to be retransmitted.
    620   QueuedPacketList queued_packets_;
    621 
    622   // True when the socket becomes unwritable.
    623   bool write_blocked_;
    624 
    625   FecGroupMap group_map_;
    626 
    627   QuicReceivedPacketManager received_packet_manager_;
    628   QuicSentEntropyManager sent_entropy_manager_;
    629 
    630   // An alarm that fires when an ACK should be sent to the peer.
    631   scoped_ptr<QuicAlarm> ack_alarm_;
    632   // An alarm that fires when a packet needs to be retransmitted.
    633   scoped_ptr<QuicAlarm> retransmission_alarm_;
    634   // An alarm that is scheduled when the sent scheduler requires a
    635   // a delay before sending packets and fires when the packet may be sent.
    636   scoped_ptr<QuicAlarm> send_alarm_;
    637   // An alarm that fires when the connection may have timed out.
    638   scoped_ptr<QuicAlarm> timeout_alarm_;
    639 
    640   QuicConnectionVisitorInterface* visitor_;
    641   QuicConnectionDebugVisitorInterface* debug_visitor_;
    642   QuicPacketCreator packet_creator_;
    643   QuicPacketGenerator packet_generator_;
    644 
    645   // Network idle time before we kill of this connection.
    646   QuicTime::Delta idle_network_timeout_;
    647   // Overall connection timeout.
    648   QuicTime::Delta overall_connection_timeout_;
    649   // Connection creation time.
    650   QuicTime creation_time_;
    651 
    652   // Statistics for this session.
    653   QuicConnectionStats stats_;
    654 
    655   // The time that we got a packet for this connection.
    656   // This is used for timeouts, and does not indicate the packet was processed.
    657   QuicTime time_of_last_received_packet_;
    658 
    659   // The time that we last sent a packet for this connection.
    660   QuicTime time_of_last_sent_packet_;
    661 
    662   // Congestion manager which controls the rate the connection sends packets
    663   // as well as collecting and generating congestion feedback.
    664   QuicCongestionManager congestion_manager_;
    665 
    666   // The state of connection in version negotiation finite state machine.
    667   QuicVersionNegotiationState version_negotiation_state_;
    668 
    669   size_t max_packets_per_retransmission_alarm_;
    670 
    671   // Tracks if the connection was created by the server.
    672   bool is_server_;
    673 
    674   // True by default.  False if we've received or sent an explicit connection
    675   // close.
    676   bool connected_;
    677 
    678   // True if the last ack received from the peer may have been truncated.  False
    679   // otherwise.
    680   bool received_truncated_ack_;
    681   bool send_ack_in_response_to_packet_;
    682 
    683   // Set to true if the udp packet headers have a new self or peer address.
    684   // This is checked later on validating a data or version negotiation packet.
    685   bool address_migrating_;
    686 
    687   DISALLOW_COPY_AND_ASSIGN(QuicConnection);
    688 };
    689 
    690 }  // namespace net
    691 
    692 #endif  // NET_QUIC_QUIC_CONNECTION_H_
    693