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