Add details (where missing) for histograms and remove a few that are not worth provid...
[chromium-blink-merge.git] / net / quic / quic_connection.h
blobf5e152f75343c3a58689becb30fc859cba41227c
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.
11 // On the client side, the Connection handles the raw reads, as well as the
12 // processing.
14 // Note: this class is not thread-safe.
16 #ifndef NET_QUIC_QUIC_CONNECTION_H_
17 #define NET_QUIC_QUIC_CONNECTION_H_
19 #include <stddef.h>
20 #include <deque>
21 #include <list>
22 #include <map>
23 #include <queue>
24 #include <string>
25 #include <vector>
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"
44 namespace net {
46 class QuicClock;
47 class QuicConfig;
48 class QuicConnection;
49 class QuicDecrypter;
50 class QuicEncrypter;
51 class QuicFecGroup;
52 class QuicFlowController;
53 class QuicRandom;
55 namespace test {
56 class QuicConnectionPeer;
57 } // namespace test
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() {}
65 // A simple visitor interface for dealing with data frames.
66 virtual void OnStreamFrames(const std::vector<QuicStreamFrame>& frames) = 0;
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;
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;
78 // Called when the stream is reset by the peer.
79 virtual void OnRstStream(const QuicRstStreamFrame& frame) = 0;
81 // Called when the connection is going away according to the peer.
82 virtual void OnGoAway(const QuicGoAwayFrame& frame) = 0;
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;
88 // Called when the connection failed to write because the socket was blocked.
89 virtual void OnWriteBlocked() = 0;
91 // Called once a specific QUIC version is agreed by both endpoints.
92 virtual void OnSuccessfulVersionNegotiation(const QuicVersion& version) = 0;
94 // Called when a blocked socket becomes writable.
95 virtual void OnCanWrite() = 0;
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;
102 // Called to ask if any handshake messages are pending in this visitor.
103 virtual bool HasPendingHandshake() const = 0;
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;
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() {}
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) {}
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) {}
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) {}
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) {}
141 // Called when the complete header of a packet has been parsed.
142 virtual void OnPacketHeader(const QuicPacketHeader& header) {}
144 // Called when a StreamFrame has been parsed.
145 virtual void OnStreamFrame(const QuicStreamFrame& frame) {}
147 // Called when a AckFrame has been parsed.
148 virtual void OnAckFrame(const QuicAckFrame& frame) {}
150 // Called when a CongestionFeedbackFrame has been parsed.
151 virtual void OnCongestionFeedbackFrame(
152 const QuicCongestionFeedbackFrame& frame) {}
154 // Called when a StopWaitingFrame has been parsed.
155 virtual void OnStopWaitingFrame(const QuicStopWaitingFrame& frame) {}
157 // Called when a Ping has been parsed.
158 virtual void OnPingFrame(const QuicPingFrame& frame) {}
160 // Called when a RstStreamFrame has been parsed.
161 virtual void OnRstStreamFrame(const QuicRstStreamFrame& frame) {}
163 // Called when a ConnectionCloseFrame has been parsed.
164 virtual void OnConnectionCloseFrame(
165 const QuicConnectionCloseFrame& frame) {}
167 // Called when a public reset packet has been received.
168 virtual void OnPublicResetPacket(const QuicPublicResetPacket& packet) {}
170 // Called when a version negotiation packet has been received.
171 virtual void OnVersionNegotiationPacket(
172 const QuicVersionNegotiationPacket& packet) {}
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) {}
180 class NET_EXPORT_PRIVATE QuicConnectionHelperInterface {
181 public:
182 virtual ~QuicConnectionHelperInterface() {}
184 // Returns a QuicClock to be used for all time related functions.
185 virtual const QuicClock* GetClock() const = 0;
187 // Returns a QuicRandom to be used for all random number related functions.
188 virtual QuicRandom* GetRandomGenerator() = 0;
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;
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
207 enum AckBundling {
208 NO_ACK = 0,
209 SEND_ACK = 1,
210 BUNDLE_PENDING_ACK = 2,
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();
224 // Sets connection parameters from the supplied |config|.
225 void SetFromConfig(const QuicConfig& config);
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);
241 // Send a RST_STREAM frame to the peer.
242 virtual void SendRstStream(QuicStreamId id,
243 QuicRstStreamErrorCode error,
244 QuicStreamOffset bytes_written);
246 // Send a BLOCKED frame to the peer.
247 virtual void SendBlocked(QuicStreamId id);
249 // Send a WINDOW_UPDATE frame to the peer.
250 virtual void SendWindowUpdate(QuicStreamId id,
251 QuicStreamOffset byte_offset);
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);
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);
270 QuicFlowController* flow_controller() { return flow_controller_.get(); }
272 // Returns statistics tracked for this connection.
273 const QuicConnectionStats& GetStats();
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);
282 // QuicBlockedWriterInterface
283 // Called when the underlying connection becomes writable to allow queued
284 // writes to happen.
285 virtual void OnCanWrite() OVERRIDE;
287 // Called when a packet has been finally sent to the network.
288 bool OnPacketSent(WriteResult result);
290 // If the socket is not blocked, writes queued packets.
291 void WriteIfNotBlocked();
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();
298 // The version of the protocol this connection is using.
299 QuicVersion version() const { return framer_.version(); }
301 // The versions of the protocol that this connection supports.
302 const QuicVersionVector& supported_versions() const {
303 return framer_.supported_versions();
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;
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;
345 // Accessors
346 void set_visitor(QuicConnectionVisitorInterface* visitor) {
347 visitor_ = visitor;
349 void set_debug_visitor(QuicConnectionDebugVisitorInterface* debug_visitor) {
350 debug_visitor_ = debug_visitor;
351 packet_generator_.set_debug_delegate(debug_visitor);
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_; }
359 QuicPacketCreator::Options* options() { return packet_creator_.options(); }
361 bool connected() const { return connected_; }
363 // Must only be called on client connections.
364 const QuicVersionVector& server_supported_versions() const {
365 DCHECK(!is_server_);
366 return server_supported_versions_;
369 size_t NumFecGroups() const { return group_map_.size(); }
371 // Testing only.
372 size_t NumQueuedPackets() const { return queued_packets_.size(); }
374 QuicEncryptedPacket* ReleaseConnectionClosePacket() {
375 return connection_close_packet_.release();
378 // Flush any queued frames immediately. Preserves the batch write mode and
379 // does nothing if there are no pending frames.
380 void Flush();
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();
387 // Returns true if the connection has queued packets or frames.
388 bool HasQueuedData() const;
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);
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();
403 // Sends a ping, and resets the ping alarm.
404 void SendPing();
406 // Sets up a packet with an QuicAckFrame and sends it out.
407 void SendAck();
409 // Called when an RTO fires. Resets the retransmission alarm if there are
410 // remaining unacked packets.
411 void OnRetransmissionTimeout();
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);
420 // Calls |sent_packet_manager_|'s NeuterUnencryptedPackets. Used when the
421 // connection becomes forward secure and hasn't received acks for all packets.
422 void NeuterUnencryptedPackets();
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;
429 // SetDefaultEncryptionLevel sets the encryption level that will be applied
430 // to new packets.
431 void SetDefaultEncryptionLevel(EncryptionLevel level);
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);
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);
450 const QuicDecrypter* decrypter() const;
451 const QuicDecrypter* alternative_decrypter() const;
453 bool is_server() const { return is_server_; }
455 // Returns the underlying sent packet manager.
456 const QuicSentPacketManager& sent_packet_manager() const {
457 return sent_packet_manager_;
460 bool CanWrite(TransmissionType transmission_type,
461 HasRetransmittableData retransmittable);
463 uint32 max_flow_control_receive_window_bytes() const {
464 return max_flow_control_receive_window_bytes_;
467 // Stores current batch state for connection, puts the connection
468 // into batch mode, and destruction restores the stored batch state.
469 // While the bundler is in scope, any generated frames are bundled
470 // as densely as possible into packets. In addition, this bundler
471 // can be configured to ensure that an ACK frame is included in the
472 // first packet created, if there's new ack information to be sent.
473 class ScopedPacketBundler {
474 public:
475 // In addition to all outgoing frames being bundled when the
476 // bundler is in scope, setting |include_ack| to true ensures that
477 // an ACK frame is opportunistically bundled with the first
478 // outgoing packet.
479 ScopedPacketBundler(QuicConnection* connection, AckBundling send_ack);
480 ~ScopedPacketBundler();
482 private:
483 QuicConnection* connection_;
484 bool already_in_batch_mode_;
487 protected:
488 // Send a packet to the peer using encryption |level|. If |sequence_number|
489 // is present in the |retransmission_map_|, then contents of this packet will
490 // be retransmitted with a new sequence number if it's not acked by the peer.
491 // Deletes |packet| if WritePacket call succeeds, or transfers ownership to
492 // QueuedPacket, ultimately deleted in WriteQueuedPackets. Updates the
493 // entropy map corresponding to |sequence_number| using |entropy_hash|.
494 // |transmission_type| and |retransmittable| are supplied to the congestion
495 // manager, and when |forced| is true, it bypasses the congestion manager.
496 // TODO(wtc): none of the callers check the return value.
497 virtual bool SendOrQueuePacket(EncryptionLevel level,
498 const SerializedPacket& packet,
499 TransmissionType transmission_type);
501 QuicConnectionHelperInterface* helper() { return helper_; }
503 // Selects and updates the version of the protocol being used by selecting a
504 // version from |available_versions| which is also supported. Returns true if
505 // such a version exists, false otherwise.
506 bool SelectMutualVersion(const QuicVersionVector& available_versions);
508 QuicPacketWriter* writer() { return writer_; }
510 private:
511 friend class test::QuicConnectionPeer;
513 // Packets which have not been written to the wire.
514 // Owns the QuicPacket* packet.
515 struct QueuedPacket {
516 QueuedPacket(SerializedPacket packet,
517 EncryptionLevel level,
518 TransmissionType transmission_type);
520 QuicPacketSequenceNumber sequence_number;
521 QuicPacket* packet;
522 const EncryptionLevel encryption_level;
523 TransmissionType transmission_type;
524 HasRetransmittableData retransmittable;
525 IsHandshake handshake;
526 PacketType type;
527 QuicByteCount length;
530 typedef std::list<QueuedPacket> QueuedPacketList;
531 typedef std::map<QuicFecGroupNumber, QuicFecGroup*> FecGroupMap;
533 // Writes the given packet to socket, encrypted with packet's
534 // encryption_level. Returns true on successful write. Behavior is undefined
535 // if connection is not established or broken. A return value of true means
536 // the packet was transmitted and may be destroyed. If the packet is
537 // retransmittable, WritePacket sets up retransmission for a successful write.
538 // If packet is FORCE, then it will be sent immediately and the send scheduler
539 // will not be consulted.
540 bool WritePacket(QueuedPacket packet);
542 // Make sure an ack we got from our peer is sane.
543 bool ValidateAckFrame(const QuicAckFrame& incoming_ack);
545 // Make sure a stop waiting we got from our peer is sane.
546 bool ValidateStopWaitingFrame(const QuicStopWaitingFrame& stop_waiting);
548 // Sends a version negotiation packet to the peer.
549 void SendVersionNegotiationPacket();
551 // Clears any accumulated frames from the last received packet.
552 void ClearLastFrames();
554 // Writes as many queued packets as possible. The connection must not be
555 // blocked when this is called.
556 void WriteQueuedPackets();
558 // Writes as many pending retransmissions as possible.
559 void WritePendingRetransmissions();
561 // Returns true if the packet should be discarded and not sent.
562 bool ShouldDiscardPacket(EncryptionLevel level,
563 QuicPacketSequenceNumber sequence_number,
564 HasRetransmittableData retransmittable);
566 // Queues |packet| in the hopes that it can be decrypted in the
567 // future, when a new key is installed.
568 void QueueUndecryptablePacket(const QuicEncryptedPacket& packet);
570 // Attempts to process any queued undecryptable packets.
571 void MaybeProcessUndecryptablePackets();
573 // If a packet can be revived from the current FEC group, then
574 // revive and process the packet.
575 void MaybeProcessRevivedPacket();
577 void ProcessAckFrame(const QuicAckFrame& incoming_ack);
579 void ProcessStopWaitingFrame(const QuicStopWaitingFrame& stop_waiting);
581 // Update |stop_waiting| for an outgoing ack.
582 void UpdateStopWaiting(QuicStopWaitingFrame* stop_waiting);
584 // Queues an ack or sets the ack alarm when an incoming packet arrives that
585 // should be acked.
586 void MaybeQueueAck();
588 // Checks if the last packet should instigate an ack.
589 bool ShouldLastPacketInstigateAck() const;
591 // Checks if the peer is waiting for packets that have been given up on, and
592 // therefore an ack frame should be sent with a larger least_unacked.
593 void UpdateStopWaitingCount();
595 // Sends any packets which are a response to the last packet, including both
596 // acks and pending writes if an ack opened the congestion window.
597 void MaybeSendInResponseToPacket();
599 // Gets the least unacked sequence number, which is the next sequence number
600 // to be sent if there are no outstanding packets.
601 QuicPacketSequenceNumber GetLeastUnacked() const;
603 // Get the FEC group associate with the last processed packet or NULL, if the
604 // group has already been deleted.
605 QuicFecGroup* GetFecGroup();
607 // Closes any FEC groups protecting packets before |sequence_number|.
608 void CloseFecGroupsBefore(QuicPacketSequenceNumber sequence_number);
610 // Sets the ping alarm to the appropriate value, if any.
611 void SetPingAlarm();
613 // On arrival of a new packet, checks to see if the socket addresses have
614 // changed since the last packet we saw on this connection.
615 void CheckForAddressMigration(const IPEndPoint& self_address,
616 const IPEndPoint& peer_address);
618 QuicFramer framer_;
619 QuicConnectionHelperInterface* helper_; // Not owned.
620 QuicPacketWriter* writer_; // Not owned.
621 EncryptionLevel encryption_level_;
622 const QuicClock* clock_;
623 QuicRandom* random_generator_;
625 const QuicConnectionId connection_id_;
626 // Address on the last successfully processed packet received from the
627 // client.
628 IPEndPoint self_address_;
629 IPEndPoint peer_address_;
630 // Used to store latest peer port to possibly migrate to later.
631 int migrating_peer_port_;
633 bool last_packet_revived_; // True if the last packet was revived from FEC.
634 size_t last_size_; // Size of the last received packet.
635 EncryptionLevel last_decrypted_packet_level_;
636 QuicPacketHeader last_header_;
637 std::vector<QuicStreamFrame> last_stream_frames_;
638 std::vector<QuicAckFrame> last_ack_frames_;
639 std::vector<QuicCongestionFeedbackFrame> last_congestion_frames_;
640 std::vector<QuicStopWaitingFrame> last_stop_waiting_frames_;
641 std::vector<QuicRstStreamFrame> last_rst_frames_;
642 std::vector<QuicGoAwayFrame> last_goaway_frames_;
643 std::vector<QuicWindowUpdateFrame> last_window_update_frames_;
644 std::vector<QuicBlockedFrame> last_blocked_frames_;
645 std::vector<QuicConnectionCloseFrame> last_close_frames_;
647 QuicCongestionFeedbackFrame outgoing_congestion_feedback_;
649 // Track some peer state so we can do less bookkeeping
650 // Largest sequence sent by the peer which had an ack frame (latest ack info).
651 QuicPacketSequenceNumber largest_seen_packet_with_ack_;
653 // Largest sequence number sent by the peer which had a stop waiting frame.
654 QuicPacketSequenceNumber largest_seen_packet_with_stop_waiting_;
656 // Collection of packets which were received before encryption was
657 // established, but which could not be decrypted. We buffer these on
658 // the assumption that they could not be processed because they were
659 // sent with the INITIAL encryption and the CHLO message was lost.
660 std::deque<QuicEncryptedPacket*> undecryptable_packets_;
662 // When the version negotiation packet could not be sent because the socket
663 // was not writable, this is set to true.
664 bool pending_version_negotiation_packet_;
666 // When packets could not be sent because the socket was not writable,
667 // they are added to this list. All corresponding frames are in
668 // unacked_packets_ if they are to be retransmitted.
669 QueuedPacketList queued_packets_;
671 // Contains information about the current write in progress, if any.
672 scoped_ptr<QueuedPacket> pending_write_;
674 // Contains the connection close packet if the connection has been closed.
675 scoped_ptr<QuicEncryptedPacket> connection_close_packet_;
677 FecGroupMap group_map_;
679 QuicReceivedPacketManager received_packet_manager_;
680 QuicSentEntropyManager sent_entropy_manager_;
682 // Indicates whether an ack should be sent the next time we try to write.
683 bool ack_queued_;
684 // Indicates how many consecutive times an ack has arrived which indicates
685 // the peer needs to stop waiting for some packets.
686 int stop_waiting_count_;
688 // An alarm that fires when an ACK should be sent to the peer.
689 scoped_ptr<QuicAlarm> ack_alarm_;
690 // An alarm that fires when a packet needs to be retransmitted.
691 scoped_ptr<QuicAlarm> retransmission_alarm_;
692 // An alarm that is scheduled when the sent scheduler requires a
693 // a delay before sending packets and fires when the packet may be sent.
694 scoped_ptr<QuicAlarm> send_alarm_;
695 // An alarm that is scheduled when the connection can still write and there
696 // may be more data to send.
697 scoped_ptr<QuicAlarm> resume_writes_alarm_;
698 // An alarm that fires when the connection may have timed out.
699 scoped_ptr<QuicAlarm> timeout_alarm_;
700 // An alarm that fires when a ping should be sent.
701 scoped_ptr<QuicAlarm> ping_alarm_;
703 QuicConnectionVisitorInterface* visitor_;
704 QuicConnectionDebugVisitorInterface* debug_visitor_;
705 QuicPacketCreator packet_creator_;
706 QuicPacketGenerator packet_generator_;
708 // Network idle time before we kill of this connection.
709 QuicTime::Delta idle_network_timeout_;
710 // Overall connection timeout.
711 QuicTime::Delta overall_connection_timeout_;
713 // Statistics for this session.
714 QuicConnectionStats stats_;
716 // The time that we got a packet for this connection.
717 // This is used for timeouts, and does not indicate the packet was processed.
718 QuicTime time_of_last_received_packet_;
720 // The last time a new (non-retransmitted) packet was sent for this
721 // connection.
722 QuicTime time_of_last_sent_new_packet_;
724 // Sequence number of the last sent packet. Packets are guaranteed to be sent
725 // in sequence number order.
726 QuicPacketSequenceNumber sequence_number_of_last_sent_packet_;
728 // Sent packet manager which tracks the status of packets sent by this
729 // connection and contains the send and receive algorithms to determine when
730 // to send packets.
731 QuicSentPacketManager sent_packet_manager_;
733 // The state of connection in version negotiation finite state machine.
734 QuicVersionNegotiationState version_negotiation_state_;
736 // Tracks if the connection was created by the server.
737 bool is_server_;
739 // True by default. False if we've received or sent an explicit connection
740 // close.
741 bool connected_;
743 // Set to true if the UDP packet headers have a new IP address for the peer.
744 // If true, do not perform connection migration.
745 bool peer_ip_changed_;
747 // Set to true if the UDP packet headers have a new port for the peer.
748 // If true, and the IP has not changed, then we can migrate the connection.
749 bool peer_port_changed_;
751 // Set to true if the UDP packet headers are addressed to a different IP.
752 // We do not support connection migration when the self IP changed.
753 bool self_ip_changed_;
755 // Set to true if the UDP packet headers are addressed to a different port.
756 // If true, and the IP has not changed, then we can migrate the connection.
757 bool self_port_changed_;
759 // If non-empty this contains the set of versions received in a
760 // version negotiation packet.
761 QuicVersionVector server_supported_versions_;
763 // Initial flow control receive window size for new streams.
764 uint32 max_flow_control_receive_window_bytes_;
766 // Used for connection level flow control.
767 scoped_ptr<QuicFlowController> flow_controller_;
769 DISALLOW_COPY_AND_ASSIGN(QuicConnection);
772 } // namespace net
774 #endif // NET_QUIC_QUIC_CONNECTION_H_