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