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 <stddef.h>
     20 #include <deque>
     21 #include <list>
     22 #include <map>
     23 #include <queue>
     24 #include <string>
     25 #include <vector>
     26 
     27 #include "base/logging.h"
     28 #include "net/base/iovec.h"
     29 #include "net/base/ip_endpoint.h"
     30 #include "net/quic/iovector.h"
     31 #include "net/quic/quic_ack_notifier.h"
     32 #include "net/quic/quic_ack_notifier_manager.h"
     33 #include "net/quic/quic_alarm.h"
     34 #include "net/quic/quic_blocked_writer_interface.h"
     35 #include "net/quic/quic_connection_stats.h"
     36 #include "net/quic/quic_packet_creator.h"
     37 #include "net/quic/quic_packet_generator.h"
     38 #include "net/quic/quic_packet_writer.h"
     39 #include "net/quic/quic_protocol.h"
     40 #include "net/quic/quic_received_packet_manager.h"
     41 #include "net/quic/quic_sent_entropy_manager.h"
     42 #include "net/quic/quic_sent_packet_manager.h"
     43 
     44 NET_EXPORT_PRIVATE extern int FLAGS_fake_packet_loss_percentage;
     45 NET_EXPORT_PRIVATE extern bool FLAGS_bundle_ack_with_outgoing_packet;
     46 
     47 namespace net {
     48 
     49 class QuicClock;
     50 class QuicConfig;
     51 class QuicConnection;
     52 class QuicDecrypter;
     53 class QuicEncrypter;
     54 class QuicFecGroup;
     55 class QuicRandom;
     56 
     57 namespace test {
     58 class QuicConnectionPeer;
     59 }  // namespace test
     60 
     61 // Class that receives callbacks from the connection when frames are received
     62 // and when other interesting events happen.
     63 class NET_EXPORT_PRIVATE QuicConnectionVisitorInterface {
     64  public:
     65   virtual ~QuicConnectionVisitorInterface() {}
     66 
     67   // A simple visitor interface for dealing with data frames.  The session
     68   // should determine if all frames will be accepted, and return true if so.
     69   // If any frames can't be processed or buffered, none of the data should
     70   // be used, and the callee should return false.
     71   virtual bool OnStreamFrames(const std::vector<QuicStreamFrame>& frames) = 0;
     72 
     73   // Called when the stream is reset by the peer.
     74   virtual void OnRstStream(const QuicRstStreamFrame& frame) = 0;
     75 
     76   // Called when the connection is going away according to the peer.
     77   virtual void OnGoAway(const QuicGoAwayFrame& frame) = 0;
     78 
     79   // Called when the connection is closed either locally by the framer, or
     80   // remotely by the peer.
     81   virtual void OnConnectionClosed(QuicErrorCode error,
     82                                   bool from_peer) = 0;
     83 
     84   // Called once a specific QUIC version is agreed by both endpoints.
     85   virtual void OnSuccessfulVersionNegotiation(const QuicVersion& version) = 0;
     86 
     87   // Indicates a new QuicConfig has been negotiated.
     88   virtual void OnConfigNegotiated() = 0;
     89 
     90   // Called when a blocked socket becomes writable.  If all pending bytes for
     91   // this visitor are consumed by the connection successfully this should
     92   // return true, otherwise it should return false.
     93   virtual bool OnCanWrite() = 0;
     94 
     95   // Called to ask if any handshake messages are pending in this visitor.
     96   virtual bool HasPendingHandshake() const = 0;
     97 };
     98 
     99 // Interface which gets callbacks from the QuicConnection at interesting
    100 // points.  Implementations must not mutate the state of the connection
    101 // as a result of these callbacks.
    102 class NET_EXPORT_PRIVATE QuicConnectionDebugVisitorInterface
    103     : public QuicPacketGenerator::DebugDelegateInterface {
    104  public:
    105   virtual ~QuicConnectionDebugVisitorInterface() {}
    106 
    107   // Called when a packet has been sent.
    108   virtual void OnPacketSent(QuicPacketSequenceNumber sequence_number,
    109                             EncryptionLevel level,
    110                             const QuicEncryptedPacket& packet,
    111                             WriteResult result) = 0;
    112 
    113   // Called when the contents of a packet have been retransmitted as
    114   // a new packet.
    115   virtual void OnPacketRetransmitted(
    116       QuicPacketSequenceNumber old_sequence_number,
    117       QuicPacketSequenceNumber new_sequence_number) = 0;
    118 
    119   // Called when a packet has been received, but before it is
    120   // validated or parsed.
    121   virtual void OnPacketReceived(const IPEndPoint& self_address,
    122                                 const IPEndPoint& peer_address,
    123                                 const QuicEncryptedPacket& packet) = 0;
    124 
    125   // Called when the protocol version on the received packet doensn't match
    126   // current protocol version of the connection.
    127   virtual void OnProtocolVersionMismatch(QuicVersion version) = 0;
    128 
    129   // Called when the complete header of a packet has been parsed.
    130   virtual void OnPacketHeader(const QuicPacketHeader& header) = 0;
    131 
    132   // Called when a StreamFrame has been parsed.
    133   virtual void OnStreamFrame(const QuicStreamFrame& frame) = 0;
    134 
    135   // Called when a AckFrame has been parsed.
    136   virtual void OnAckFrame(const QuicAckFrame& frame) = 0;
    137 
    138   // Called when a CongestionFeedbackFrame has been parsed.
    139   virtual void OnCongestionFeedbackFrame(
    140       const QuicCongestionFeedbackFrame& frame) = 0;
    141 
    142   // Called when a RstStreamFrame has been parsed.
    143   virtual void OnRstStreamFrame(const QuicRstStreamFrame& frame) = 0;
    144 
    145   // Called when a ConnectionCloseFrame has been parsed.
    146   virtual void OnConnectionCloseFrame(
    147       const QuicConnectionCloseFrame& frame) = 0;
    148 
    149   // Called when a public reset packet has been received.
    150   virtual void OnPublicResetPacket(const QuicPublicResetPacket& packet) = 0;
    151 
    152   // Called when a version negotiation packet has been received.
    153   virtual void OnVersionNegotiationPacket(
    154       const QuicVersionNegotiationPacket& packet) = 0;
    155 
    156   // Called after a packet has been successfully parsed which results
    157   // in the revival of a packet via FEC.
    158   virtual void OnRevivedPacket(const QuicPacketHeader& revived_header,
    159                                base::StringPiece payload) = 0;
    160 };
    161 
    162 class NET_EXPORT_PRIVATE QuicConnectionHelperInterface {
    163  public:
    164   virtual ~QuicConnectionHelperInterface() {}
    165 
    166   // Returns a QuicClock to be used for all time related functions.
    167   virtual const QuicClock* GetClock() const = 0;
    168 
    169   // Returns a QuicRandom to be used for all random number related functions.
    170   virtual QuicRandom* GetRandomGenerator() = 0;
    171 
    172   // Creates a new platform-specific alarm which will be configured to
    173   // notify |delegate| when the alarm fires.  Caller takes ownership
    174   // of the new alarm, which will not yet be "set" to fire.
    175   virtual QuicAlarm* CreateAlarm(QuicAlarm::Delegate* delegate) = 0;
    176 };
    177 
    178 class NET_EXPORT_PRIVATE QuicConnection
    179     : public QuicFramerVisitorInterface,
    180       public QuicBlockedWriterInterface,
    181       public QuicPacketGenerator::DelegateInterface,
    182       public QuicSentPacketManager::HelperInterface {
    183  public:
    184   enum Force {
    185     NO_FORCE,
    186     FORCE
    187   };
    188 
    189   // Constructs a new QuicConnection for the specified |guid| and |address|.
    190   // |helper| and |writer| must outlive this connection.
    191   QuicConnection(QuicGuid guid,
    192                  IPEndPoint address,
    193                  QuicConnectionHelperInterface* helper,
    194                  QuicPacketWriter* writer,
    195                  bool is_server,
    196                  const QuicVersionVector& supported_versions);
    197   virtual ~QuicConnection();
    198 
    199   // Sets connection parameters from the supplied |config|.
    200   void SetFromConfig(const QuicConfig& config);
    201 
    202   // Send the data in |data| to the peer in as few packets as possible.
    203   // Returns a pair with the number of bytes consumed from data, and a boolean
    204   // indicating if the fin bit was consumed.  This does not indicate the data
    205   // has been sent on the wire: it may have been turned into a packet and queued
    206   // if the socket was unexpectedly blocked.
    207   // If |delegate| is provided, then it will be informed once ACKs have been
    208   // received for all the packets written in this call.
    209   // The |delegate| is not owned by the QuicConnection and must outlive it.
    210   QuicConsumedData SendStreamData(QuicStreamId id,
    211                                   const IOVector& data,
    212                                   QuicStreamOffset offset,
    213                                   bool fin,
    214                                   QuicAckNotifier::DelegateInterface* delegate);
    215 
    216   // Send a stream reset frame to the peer.
    217   virtual void SendRstStream(QuicStreamId id,
    218                              QuicRstStreamErrorCode error);
    219 
    220   // Sends the connection close packet without affecting the state of the
    221   // connection.  This should only be called if the session is actively being
    222   // destroyed: otherwise call SendConnectionCloseWithDetails instead.
    223   virtual void SendConnectionClosePacket(QuicErrorCode error,
    224                                          const std::string& details);
    225 
    226   // Sends a connection close frame to the peer, and closes the connection by
    227   // calling CloseConnection(notifying the visitor as it does so).
    228   virtual void SendConnectionClose(QuicErrorCode error);
    229   virtual void SendConnectionCloseWithDetails(QuicErrorCode error,
    230                                               const std::string& details);
    231   // Notifies the visitor of the close and marks the connection as disconnected.
    232   virtual void CloseConnection(QuicErrorCode error, bool from_peer) OVERRIDE;
    233   virtual void SendGoAway(QuicErrorCode error,
    234                           QuicStreamId last_good_stream_id,
    235                           const std::string& reason);
    236 
    237   // Returns statistics tracked for this connection.
    238   const QuicConnectionStats& GetStats();
    239 
    240   // Processes an incoming UDP packet (consisting of a QuicEncryptedPacket) from
    241   // the peer.  If processing this packet permits a packet to be revived from
    242   // its FEC group that packet will be revived and processed.
    243   virtual void ProcessUdpPacket(const IPEndPoint& self_address,
    244                                 const IPEndPoint& peer_address,
    245                                 const QuicEncryptedPacket& packet);
    246 
    247   // QuicBlockedWriterInterface
    248   // Called when the underlying connection becomes writable to allow queued
    249   // writes to happen.  Returns false if the socket has become blocked.
    250   virtual bool OnCanWrite() OVERRIDE;
    251 
    252   // Called when a packet has been finally sent to the network.
    253   bool OnPacketSent(WriteResult result);
    254 
    255   // If the socket is not blocked, this allows queued writes to happen. Returns
    256   // false if the socket has become blocked.
    257   bool WriteIfNotBlocked();
    258 
    259   // Do any work which logically would be done in OnPacket but can not be
    260   // safely done until the packet is validated.  Returns true if the packet
    261   // can be handled, false otherwise.
    262   bool ProcessValidatedPacket();
    263 
    264   // The version of the protocol this connection is using.
    265   QuicVersion version() const { return framer_.version(); }
    266 
    267   // The versions of the protocol that this connection supports.
    268   const QuicVersionVector& supported_versions() const {
    269     return framer_.supported_versions();
    270   }
    271 
    272   // From QuicFramerVisitorInterface
    273   virtual void OnError(QuicFramer* framer) OVERRIDE;
    274   virtual bool OnProtocolVersionMismatch(QuicVersion received_version) OVERRIDE;
    275   virtual void OnPacket() OVERRIDE;
    276   virtual void OnPublicResetPacket(
    277       const QuicPublicResetPacket& packet) OVERRIDE;
    278   virtual void OnVersionNegotiationPacket(
    279       const QuicVersionNegotiationPacket& packet) OVERRIDE;
    280   virtual void OnRevivedPacket() OVERRIDE;
    281   virtual bool OnUnauthenticatedHeader(const QuicPacketHeader& header) OVERRIDE;
    282   virtual bool OnPacketHeader(const QuicPacketHeader& header) OVERRIDE;
    283   virtual void OnFecProtectedPayload(base::StringPiece payload) OVERRIDE;
    284   virtual bool OnStreamFrame(const QuicStreamFrame& frame) OVERRIDE;
    285   virtual bool OnAckFrame(const QuicAckFrame& frame) OVERRIDE;
    286   virtual bool OnCongestionFeedbackFrame(
    287       const QuicCongestionFeedbackFrame& frame) OVERRIDE;
    288   virtual bool OnRstStreamFrame(const QuicRstStreamFrame& frame) OVERRIDE;
    289   virtual bool OnConnectionCloseFrame(
    290       const QuicConnectionCloseFrame& frame) OVERRIDE;
    291   virtual bool OnGoAwayFrame(const QuicGoAwayFrame& frame) OVERRIDE;
    292   virtual void OnFecData(const QuicFecData& fec) OVERRIDE;
    293   virtual void OnPacketComplete() OVERRIDE;
    294 
    295   // QuicPacketGenerator::DelegateInterface
    296   virtual bool ShouldGeneratePacket(TransmissionType transmission_type,
    297                                     HasRetransmittableData retransmittable,
    298                                     IsHandshake handshake) OVERRIDE;
    299   virtual QuicAckFrame* CreateAckFrame() OVERRIDE;
    300   virtual QuicCongestionFeedbackFrame* CreateFeedbackFrame() OVERRIDE;
    301   virtual bool OnSerializedPacket(const SerializedPacket& packet) OVERRIDE;
    302 
    303   // QuicSentPacketManager::HelperInterface
    304   virtual QuicPacketSequenceNumber GetNextPacketSequenceNumber() OVERRIDE;
    305 
    306   // Accessors
    307   void set_visitor(QuicConnectionVisitorInterface* visitor) {
    308     visitor_ = visitor;
    309   }
    310   void set_debug_visitor(QuicConnectionDebugVisitorInterface* debug_visitor) {
    311     debug_visitor_ = debug_visitor;
    312     packet_generator_.set_debug_delegate(debug_visitor);
    313   }
    314   const IPEndPoint& self_address() const { return self_address_; }
    315   const IPEndPoint& peer_address() const { return peer_address_; }
    316   QuicGuid guid() const { return guid_; }
    317   const QuicClock* clock() const { return clock_; }
    318   QuicRandom* random_generator() const { return random_generator_; }
    319 
    320   QuicPacketCreator::Options* options() { return packet_creator_.options(); }
    321 
    322   bool connected() const { return connected_; }
    323 
    324   // Must only be called on client connections.
    325   const QuicVersionVector& server_supported_versions() const {
    326     DCHECK(!is_server_);
    327     return server_supported_versions_;
    328   }
    329 
    330   size_t NumFecGroups() const { return group_map_.size(); }
    331 
    332   // Testing only.
    333   size_t NumQueuedPackets() const { return queued_packets_.size(); }
    334 
    335   QuicEncryptedPacket* ReleaseConnectionClosePacket() {
    336     return connection_close_packet_.release();
    337   }
    338 
    339   // Flush any queued frames immediately.  Preserves the batch write mode and
    340   // does nothing if there are no pending frames.
    341   void Flush();
    342 
    343   // Returns true if the connection has queued packets or frames.
    344   bool HasQueuedData() const;
    345 
    346   // Sets (or resets) the idle state connection timeout. Also, checks and times
    347   // out the connection if network timer has expired for |timeout|.
    348   void SetIdleNetworkTimeout(QuicTime::Delta timeout);
    349   // Sets (or resets) the total time delta the connection can be alive for.
    350   // Also, checks and times out the connection if timer has expired for
    351   // |timeout|. Used to limit the time a connection can be alive before crypto
    352   // handshake finishes.
    353   void SetOverallConnectionTimeout(QuicTime::Delta timeout);
    354 
    355   // If the connection has timed out, this will close the connection and return
    356   // true.  Otherwise, it will return false and will reset the timeout alarm.
    357   bool CheckForTimeout();
    358 
    359   // Sets up a packet with an QuicAckFrame and sends it out.
    360   void SendAck();
    361 
    362   // Called when an RTO fires.  Resets the retransmission alarm if there are
    363   // remaining unacked packets.
    364   void OnRetransmissionTimeout();
    365 
    366   // Retransmits all unacked packets with retransmittable frames if
    367   // |retransmission_type| is ALL_PACKETS, otherwise retransmits only initially
    368   // encrypted packets. Used when the negotiated protocol version is different
    369   // from what was initially assumed and when the visitor wants to re-transmit
    370   // initially encrypted packets when the initial encrypter changes.
    371   void RetransmitUnackedPackets(RetransmissionType retransmission_type);
    372 
    373   // Changes the encrypter used for level |level| to |encrypter|. The function
    374   // takes ownership of |encrypter|.
    375   void SetEncrypter(EncryptionLevel level, QuicEncrypter* encrypter);
    376   const QuicEncrypter* encrypter(EncryptionLevel level) const;
    377 
    378   // SetDefaultEncryptionLevel sets the encryption level that will be applied
    379   // to new packets.
    380   void SetDefaultEncryptionLevel(EncryptionLevel level);
    381 
    382   // SetDecrypter sets the primary decrypter, replacing any that already exists,
    383   // and takes ownership. If an alternative decrypter is in place then the
    384   // function DCHECKs. This is intended for cases where one knows that future
    385   // packets will be using the new decrypter and the previous decrypter is now
    386   // obsolete.
    387   void SetDecrypter(QuicDecrypter* decrypter);
    388 
    389   // SetAlternativeDecrypter sets a decrypter that may be used to decrypt
    390   // future packets and takes ownership of it. If |latch_once_used| is true,
    391   // then the first time that the decrypter is successful it will replace the
    392   // primary decrypter. Otherwise both decrypters will remain active and the
    393   // primary decrypter will be the one last used.
    394   void SetAlternativeDecrypter(QuicDecrypter* decrypter,
    395                                bool latch_once_used);
    396 
    397   const QuicDecrypter* decrypter() const;
    398   const QuicDecrypter* alternative_decrypter() const;
    399 
    400   bool is_server() const { return is_server_; }
    401 
    402   // Returns the underlying sent packet manager.
    403   const QuicSentPacketManager& sent_packet_manager() const {
    404     return sent_packet_manager_;
    405   }
    406 
    407   bool CanWrite(TransmissionType transmission_type,
    408                 HasRetransmittableData retransmittable,
    409                 IsHandshake handshake);
    410 
    411  protected:
    412   // Send a packet to the peer using encryption |level|. If |sequence_number|
    413   // is present in the |retransmission_map_|, then contents of this packet will
    414   // be retransmitted with a new sequence number if it's not acked by the peer.
    415   // Deletes |packet| via WritePacket call or transfers ownership to
    416   // QueuedPacket, ultimately deleted via WritePacket. Updates the
    417   // entropy map corresponding to |sequence_number| using |entropy_hash|.
    418   // |transmission_type| and |retransmittable| are supplied to the congestion
    419   // manager, and when |forced| is true, it bypasses the congestion manager.
    420   // TODO(wtc): none of the callers check the return value.
    421   virtual bool SendOrQueuePacket(EncryptionLevel level,
    422                                  const SerializedPacket& packet,
    423                                  TransmissionType transmission_type);
    424 
    425   // Writes the given packet to socket, encrypted with |level|, with the help
    426   // of helper. Returns true on successful write, false otherwise. However,
    427   // behavior is undefined if connection is not established or broken. In any
    428   // circumstances, a return value of true implies that |packet| has been
    429   // deleted and should not be accessed. If |sequence_number| is present in
    430   // |retransmission_map_| it also sets up retransmission of the given packet
    431   // in case of successful write. If |force| is FORCE, then the packet will be
    432   // sent immediately and the send scheduler will not be consulted.
    433   bool WritePacket(EncryptionLevel level,
    434                    QuicPacketSequenceNumber sequence_number,
    435                    QuicPacket* packet,
    436                    TransmissionType transmission_type,
    437                    HasRetransmittableData retransmittable,
    438                    IsHandshake handshake,
    439                    Force force);
    440 
    441   // Make sure an ack we got from our peer is sane.
    442   bool ValidateAckFrame(const QuicAckFrame& incoming_ack);
    443 
    444   QuicConnectionHelperInterface* helper() { return helper_; }
    445 
    446   // Selects and updates the version of the protocol being used by selecting a
    447   // version from |available_versions| which is also supported. Returns true if
    448   // such a version exists, false otherwise.
    449   bool SelectMutualVersion(const QuicVersionVector& available_versions);
    450 
    451   QuicFramer framer_;
    452 
    453  private:
    454   // Stores current batch state for connection, puts the connection
    455   // into batch mode, and destruction restores the stored batch state.
    456   // While the bundler is in scope, any generated frames are bundled
    457   // as densely as possible into packets.  In addition, this bundler
    458   // can be configured to ensure that an ACK frame is included in the
    459   // first packet created, if there's new ack information to be sent.
    460   class ScopedPacketBundler {
    461    public:
    462     // In addition to all outgoing frames being bundled when the
    463     // bundler is in scope, setting |include_ack| to true ensures that
    464     // an ACK frame is opportunistically bundled with the first
    465     // outgoing packet.
    466     ScopedPacketBundler(QuicConnection* connection, bool include_ack);
    467     ~ScopedPacketBundler();
    468 
    469    private:
    470     QuicConnection* connection_;
    471     bool already_in_batch_mode_;
    472   };
    473 
    474   friend class ScopedPacketBundler;
    475   friend class test::QuicConnectionPeer;
    476 
    477   // Packets which have not been written to the wire.
    478   // Owns the QuicPacket* packet.
    479   struct QueuedPacket {
    480     QueuedPacket(QuicPacketSequenceNumber sequence_number,
    481                  QuicPacket* packet,
    482                  EncryptionLevel level,
    483                  TransmissionType transmission_type,
    484                  HasRetransmittableData retransmittable,
    485                  IsHandshake handshake,
    486                  Force forced)
    487         : sequence_number(sequence_number),
    488           packet(packet),
    489           encryption_level(level),
    490           transmission_type(transmission_type),
    491           retransmittable(retransmittable),
    492           handshake(handshake),
    493           forced(forced) {
    494     }
    495 
    496     QuicPacketSequenceNumber sequence_number;
    497     QuicPacket* packet;
    498     const EncryptionLevel encryption_level;
    499     TransmissionType transmission_type;
    500     HasRetransmittableData retransmittable;
    501     IsHandshake handshake;
    502     Force forced;
    503   };
    504 
    505   struct RetransmissionInfo {
    506     RetransmissionInfo(QuicPacketSequenceNumber sequence_number,
    507                        QuicSequenceNumberLength sequence_number_length,
    508                        QuicTime sent_time)
    509         : sequence_number(sequence_number),
    510           sequence_number_length(sequence_number_length),
    511           sent_time(sent_time),
    512           number_nacks(0),
    513           number_retransmissions(0) {
    514     }
    515 
    516     QuicPacketSequenceNumber sequence_number;
    517     QuicSequenceNumberLength sequence_number_length;
    518     QuicTime sent_time;
    519     size_t number_nacks;
    520     size_t number_retransmissions;
    521   };
    522 
    523   struct RetransmissionTime {
    524     RetransmissionTime(QuicPacketSequenceNumber sequence_number,
    525                        const QuicTime& scheduled_time,
    526                        bool for_fec)
    527         : sequence_number(sequence_number),
    528           scheduled_time(scheduled_time),
    529           for_fec(for_fec) { }
    530 
    531     QuicPacketSequenceNumber sequence_number;
    532     QuicTime scheduled_time;
    533     bool for_fec;
    534   };
    535 
    536   struct PendingWrite {
    537     PendingWrite(QuicPacketSequenceNumber sequence_number,
    538                  TransmissionType transmission_type,
    539                  HasRetransmittableData retransmittable,
    540                  EncryptionLevel level,
    541                  bool is_fec_packet,
    542                  size_t length)
    543         : sequence_number(sequence_number),
    544           transmission_type(transmission_type),
    545           retransmittable(retransmittable),
    546           level(level),
    547           is_fec_packet(is_fec_packet),
    548           length(length) { }
    549 
    550     QuicPacketSequenceNumber sequence_number;
    551     TransmissionType transmission_type;
    552     HasRetransmittableData retransmittable;
    553     EncryptionLevel level;
    554     bool is_fec_packet;
    555     size_t length;
    556   };
    557 
    558   class RetransmissionTimeComparator {
    559    public:
    560     bool operator()(const RetransmissionTime& lhs,
    561                     const RetransmissionTime& rhs) const {
    562       DCHECK(lhs.scheduled_time.IsInitialized() &&
    563              rhs.scheduled_time.IsInitialized());
    564       return lhs.scheduled_time > rhs.scheduled_time;
    565     }
    566   };
    567 
    568   typedef std::list<QueuedPacket> QueuedPacketList;
    569   typedef std::map<QuicFecGroupNumber, QuicFecGroup*> FecGroupMap;
    570   typedef std::priority_queue<RetransmissionTime,
    571                               std::vector<RetransmissionTime>,
    572                               RetransmissionTimeComparator>
    573       RetransmissionTimeouts;
    574 
    575   // Sends a version negotiation packet to the peer.
    576   void SendVersionNegotiationPacket();
    577 
    578   void SetupRetransmissionAlarm(QuicPacketSequenceNumber sequence_number);
    579   bool IsRetransmission(QuicPacketSequenceNumber sequence_number);
    580 
    581   void SetupAbandonFecTimer(QuicPacketSequenceNumber sequence_number);
    582 
    583   // Clears any accumulated frames from the last received packet.
    584   void ClearLastFrames();
    585 
    586   // Called from OnCanWrite and WriteIfNotBlocked to write queued packets.
    587   // Returns false if the socket has become blocked.
    588   bool DoWrite();
    589 
    590   // Calculates the smallest sequence number length that can also represent four
    591   // times the maximum of the congestion window and the difference between the
    592   // least_packet_awaited_by_peer_ and |sequence_number|.
    593   QuicSequenceNumberLength CalculateSequenceNumberLength(
    594       QuicPacketSequenceNumber sequence_number);
    595 
    596   // Drop packet corresponding to |sequence_number| by deleting entries from
    597   // |unacked_packets_| and |retransmission_map_|, if present. We need to drop
    598   // all packets with encryption level NONE after the default level has been set
    599   // to FORWARD_SECURE.
    600   void DropPacket(QuicPacketSequenceNumber sequence_number);
    601 
    602   // Writes as many queued packets as possible.  The connection must not be
    603   // blocked when this is called.
    604   bool WriteQueuedPackets();
    605 
    606   // Writes as many pending retransmissions as possible.
    607   void WritePendingRetransmissions();
    608 
    609   // Returns true if the packet should be discarded and not sent.
    610   bool ShouldDiscardPacket(EncryptionLevel level,
    611                            QuicPacketSequenceNumber sequence_number,
    612                            HasRetransmittableData retransmittable);
    613 
    614   // Queues |packet| in the hopes that it can be decrypted in the
    615   // future, when a new key is installed.
    616   void QueueUndecryptablePacket(const QuicEncryptedPacket& packet);
    617 
    618   // Attempts to process any queued undecryptable packets.
    619   void MaybeProcessUndecryptablePackets();
    620 
    621   // If a packet can be revived from the current FEC group, then
    622   // revive and process the packet.
    623   void MaybeProcessRevivedPacket();
    624 
    625   void ProcessAckFrame(const QuicAckFrame& incoming_ack);
    626 
    627   // Update the |sent_info| for an outgoing ack.
    628   void UpdateSentPacketInfo(SentPacketInfo* sent_info);
    629 
    630   // Checks if the last packet should instigate an ack.
    631   bool ShouldLastPacketInstigateAck();
    632 
    633   // Sends any packets which are a response to the last packet, including both
    634   // acks and pending writes if an ack opened the congestion window.
    635   void MaybeSendInResponseToPacket(bool send_ack_immediately,
    636                                    bool last_packet_should_instigate_ack);
    637 
    638   // Get the FEC group associate with the last processed packet or NULL, if the
    639   // group has already been deleted.
    640   QuicFecGroup* GetFecGroup();
    641 
    642   // Closes any FEC groups protecting packets before |sequence_number|.
    643   void CloseFecGroupsBefore(QuicPacketSequenceNumber sequence_number);
    644 
    645   QuicConnectionHelperInterface* helper_;  // Not owned.
    646   QuicPacketWriter* writer_;  // Not owned.
    647   EncryptionLevel encryption_level_;
    648   const QuicClock* clock_;
    649   QuicRandom* random_generator_;
    650 
    651   const QuicGuid guid_;
    652   // Address on the last successfully processed packet received from the
    653   // client.
    654   IPEndPoint self_address_;
    655   IPEndPoint peer_address_;
    656 
    657   bool last_packet_revived_;  // True if the last packet was revived from FEC.
    658   size_t last_size_;  // Size of the last received packet.
    659   QuicPacketHeader last_header_;
    660   std::vector<QuicStreamFrame> last_stream_frames_;
    661   std::vector<QuicAckFrame> last_ack_frames_;
    662   std::vector<QuicCongestionFeedbackFrame> last_congestion_frames_;
    663   std::vector<QuicRstStreamFrame> last_rst_frames_;
    664   std::vector<QuicGoAwayFrame> last_goaway_frames_;
    665   std::vector<QuicConnectionCloseFrame> last_close_frames_;
    666 
    667   QuicCongestionFeedbackFrame outgoing_congestion_feedback_;
    668 
    669   // Track some peer state so we can do less bookkeeping
    670   // Largest sequence sent by the peer which had an ack frame (latest ack info).
    671   QuicPacketSequenceNumber largest_seen_packet_with_ack_;
    672 
    673   // Collection of packets which were received before encryption was
    674   // established, but which could not be decrypted.  We buffer these on
    675   // the assumption that they could not be processed because they were
    676   // sent with the INITIAL encryption and the CHLO message was lost.
    677   std::deque<QuicEncryptedPacket*> undecryptable_packets_;
    678 
    679   // When the version negotiation packet could not be sent because the socket
    680   // was not writable, this is set to true.
    681   bool pending_version_negotiation_packet_;
    682 
    683   // When packets could not be sent because the socket was not writable,
    684   // they are added to this list.  All corresponding frames are in
    685   // unacked_packets_ if they are to be retransmitted.
    686   QueuedPacketList queued_packets_;
    687 
    688   // Contains information about the current write in progress, if any.
    689   scoped_ptr<PendingWrite> pending_write_;
    690 
    691   // Contains the connection close packet if the connection has been closed.
    692   scoped_ptr<QuicEncryptedPacket> connection_close_packet_;
    693 
    694   // True when the socket becomes unwritable.
    695   bool write_blocked_;
    696 
    697   FecGroupMap group_map_;
    698 
    699   QuicReceivedPacketManager received_packet_manager_;
    700   QuicSentEntropyManager sent_entropy_manager_;
    701 
    702   // An alarm that fires when an ACK should be sent to the peer.
    703   scoped_ptr<QuicAlarm> ack_alarm_;
    704   // An alarm that fires when a packet needs to be retransmitted.
    705   scoped_ptr<QuicAlarm> retransmission_alarm_;
    706   // An alarm that is scheduled when the sent scheduler requires a
    707   // a delay before sending packets and fires when the packet may be sent.
    708   scoped_ptr<QuicAlarm> send_alarm_;
    709   // An alarm that is scheduled when the connection can still write and there
    710   // may be more data to send.
    711   scoped_ptr<QuicAlarm> resume_writes_alarm_;
    712   // An alarm that fires when the connection may have timed out.
    713   scoped_ptr<QuicAlarm> timeout_alarm_;
    714 
    715   QuicConnectionVisitorInterface* visitor_;
    716   QuicConnectionDebugVisitorInterface* debug_visitor_;
    717   QuicPacketCreator packet_creator_;
    718   QuicPacketGenerator packet_generator_;
    719 
    720   // Network idle time before we kill of this connection.
    721   QuicTime::Delta idle_network_timeout_;
    722   // Overall connection timeout.
    723   QuicTime::Delta overall_connection_timeout_;
    724   // Connection creation time.
    725   QuicTime creation_time_;
    726 
    727   // Statistics for this session.
    728   QuicConnectionStats stats_;
    729 
    730   // The time that we got a packet for this connection.
    731   // This is used for timeouts, and does not indicate the packet was processed.
    732   QuicTime time_of_last_received_packet_;
    733 
    734   // The time that we last sent a packet for this connection.
    735   QuicTime time_of_last_sent_packet_;
    736 
    737   // Sequence number of the last packet guaranteed to be sent in packet sequence
    738   // number order.  Not set when packets are queued, since that may cause
    739   // re-ordering.
    740   QuicPacketSequenceNumber sequence_number_of_last_inorder_packet_;
    741 
    742   // Sent packet manager which tracks the status of packets sent by this
    743   // connection and contains the send and receive algorithms to determine when
    744   // to send packets.
    745   QuicSentPacketManager sent_packet_manager_;
    746 
    747   // The state of connection in version negotiation finite state machine.
    748   QuicVersionNegotiationState version_negotiation_state_;
    749 
    750   // Tracks if the connection was created by the server.
    751   bool is_server_;
    752 
    753   // True by default.  False if we've received or sent an explicit connection
    754   // close.
    755   bool connected_;
    756 
    757   // Set to true if the udp packet headers have a new self or peer address.
    758   // This is checked later on validating a data or version negotiation packet.
    759   bool address_migrating_;
    760 
    761   // An AckNotifier can register to be informed when ACKs have been received for
    762   // all packets that a given block of data was sent in. The AckNotifierManager
    763   // maintains the currently active notifiers.
    764   AckNotifierManager ack_notifier_manager_;
    765 
    766   // If non-empty this contains the set of versions received in a
    767   // version negotiation packet.
    768   QuicVersionVector server_supported_versions_;
    769 
    770   DISALLOW_COPY_AND_ASSIGN(QuicConnection);
    771 };
    772 
    773 }  // namespace net
    774 
    775 #endif  // NET_QUIC_QUIC_CONNECTION_H_
    776