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