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.
5 // The entity that handles framing writes for a Quic client or server.
6 // Each QuicSession will have a connection associated with it.
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
14 // Note: this class is not thread-safe.
16 #ifndef NET_QUIC_QUIC_CONNECTION_H_
17 #define NET_QUIC_QUIC_CONNECTION_H_
27 #include "base/basictypes.h"
28 #include "base/logging.h"
29 #include "base/memory/scoped_ptr.h"
30 #include "base/strings/string_piece.h"
31 #include "net/base/ip_endpoint.h"
32 #include "net/quic/quic_ack_notifier.h"
33 #include "net/quic/quic_ack_notifier_manager.h"
34 #include "net/quic/quic_alarm.h"
35 #include "net/quic/quic_blocked_writer_interface.h"
36 #include "net/quic/quic_connection_stats.h"
37 #include "net/quic/quic_packet_creator.h"
38 #include "net/quic/quic_packet_generator.h"
39 #include "net/quic/quic_packet_writer.h"
40 #include "net/quic/quic_protocol.h"
41 #include "net/quic/quic_received_packet_manager.h"
42 #include "net/quic/quic_sent_entropy_manager.h"
43 #include "net/quic/quic_sent_packet_manager.h"
44 #include "net/quic/quic_time.h"
45 #include "net/quic/quic_types.h"
58 class PacketSavingConnection
;
59 class QuicConnectionPeer
;
62 // Class that receives callbacks from the connection when frames are received
63 // and when other interesting events happen.
64 class NET_EXPORT_PRIVATE QuicConnectionVisitorInterface
{
66 virtual ~QuicConnectionVisitorInterface() {}
68 // A simple visitor interface for dealing with data frames.
69 virtual void OnStreamFrames(const std::vector
<QuicStreamFrame
>& frames
) = 0;
71 // The session should process all WINDOW_UPDATE frames, adjusting both stream
72 // and connection level flow control windows.
73 virtual void OnWindowUpdateFrames(
74 const std::vector
<QuicWindowUpdateFrame
>& frames
) = 0;
76 // BLOCKED frames tell us that the peer believes it is flow control blocked on
77 // a specified stream. If the session at this end disagrees, something has
78 // gone wrong with our flow control accounting.
79 virtual void OnBlockedFrames(const std::vector
<QuicBlockedFrame
>& frames
) = 0;
81 // Called when the stream is reset by the peer.
82 virtual void OnRstStream(const QuicRstStreamFrame
& frame
) = 0;
84 // Called when the connection is going away according to the peer.
85 virtual void OnGoAway(const QuicGoAwayFrame
& frame
) = 0;
87 // Called when the connection is closed either locally by the framer, or
88 // remotely by the peer.
89 virtual void OnConnectionClosed(QuicErrorCode error
, bool from_peer
) = 0;
91 // Called when the connection failed to write because the socket was blocked.
92 virtual void OnWriteBlocked() = 0;
94 // Called once a specific QUIC version is agreed by both endpoints.
95 virtual void OnSuccessfulVersionNegotiation(const QuicVersion
& version
) = 0;
97 // Called when a blocked socket becomes writable.
98 virtual void OnCanWrite() = 0;
100 // Called when the connection experiences a change in congestion window.
101 virtual void OnCongestionWindowChange(QuicTime now
) = 0;
103 // Called to ask if the visitor wants to schedule write resumption as it both
104 // has pending data to write, and is able to write (e.g. based on flow control
106 // Writes may be pending because they were write-blocked, congestion-throttled
107 // or yielded to other connections.
108 virtual bool WillingAndAbleToWrite() const = 0;
110 // Called to ask if any handshake messages are pending in this visitor.
111 virtual bool HasPendingHandshake() const = 0;
113 // Called to ask if any streams are open in this visitor, excluding the
114 // reserved crypto and headers stream.
115 virtual bool HasOpenDynamicStreams() const = 0;
118 // Interface which gets callbacks from the QuicConnection at interesting
119 // points. Implementations must not mutate the state of the connection
120 // as a result of these callbacks.
121 class NET_EXPORT_PRIVATE QuicConnectionDebugVisitor
122 : public QuicPacketGenerator::DebugDelegate
,
123 public QuicSentPacketManager::DebugDelegate
{
125 ~QuicConnectionDebugVisitor() override
{}
127 // Called when a packet has been sent.
128 virtual void OnPacketSent(const SerializedPacket
& serialized_packet
,
129 QuicPacketSequenceNumber original_sequence_number
,
130 EncryptionLevel level
,
131 TransmissionType transmission_type
,
132 const QuicEncryptedPacket
& packet
,
133 QuicTime sent_time
) {}
135 // Called when a packet has been received, but before it is
136 // validated or parsed.
137 virtual void OnPacketReceived(const IPEndPoint
& self_address
,
138 const IPEndPoint
& peer_address
,
139 const QuicEncryptedPacket
& packet
) {}
141 // Called when a packet is received with a connection id that does not
142 // match the ID of this connection.
143 virtual void OnIncorrectConnectionId(
144 QuicConnectionId connection_id
) {}
146 // Called when an undecryptable packet has been received.
147 virtual void OnUndecryptablePacket() {}
149 // Called when a duplicate packet has been received.
150 virtual void OnDuplicatePacket(QuicPacketSequenceNumber sequence_number
) {}
152 // Called when the protocol version on the received packet doensn't match
153 // current protocol version of the connection.
154 virtual void OnProtocolVersionMismatch(QuicVersion version
) {}
156 // Called when the complete header of a packet has been parsed.
157 virtual void OnPacketHeader(const QuicPacketHeader
& header
) {}
159 // Called when a StreamFrame has been parsed.
160 virtual void OnStreamFrame(const QuicStreamFrame
& frame
) {}
162 // Called when a AckFrame has been parsed.
163 virtual void OnAckFrame(const QuicAckFrame
& frame
) {}
165 // Called when a StopWaitingFrame has been parsed.
166 virtual void OnStopWaitingFrame(const QuicStopWaitingFrame
& frame
) {}
168 // Called when a Ping has been parsed.
169 virtual void OnPingFrame(const QuicPingFrame
& frame
) {}
171 // Called when a GoAway has been parsed.
172 virtual void OnGoAwayFrame(const QuicGoAwayFrame
& frame
) {}
174 // Called when a RstStreamFrame has been parsed.
175 virtual void OnRstStreamFrame(const QuicRstStreamFrame
& frame
) {}
177 // Called when a ConnectionCloseFrame has been parsed.
178 virtual void OnConnectionCloseFrame(
179 const QuicConnectionCloseFrame
& frame
) {}
181 // Called when a WindowUpdate has been parsed.
182 virtual void OnWindowUpdateFrame(const QuicWindowUpdateFrame
& frame
) {}
184 // Called when a BlockedFrame has been parsed.
185 virtual void OnBlockedFrame(const QuicBlockedFrame
& frame
) {}
187 // Called when a public reset packet has been received.
188 virtual void OnPublicResetPacket(const QuicPublicResetPacket
& packet
) {}
190 // Called when a version negotiation packet has been received.
191 virtual void OnVersionNegotiationPacket(
192 const QuicVersionNegotiationPacket
& packet
) {}
194 // Called after a packet has been successfully parsed which results
195 // in the revival of a packet via FEC.
196 virtual void OnRevivedPacket(const QuicPacketHeader
& revived_header
,
197 base::StringPiece payload
) {}
199 // Called when the connection is closed.
200 virtual void OnConnectionClosed(QuicErrorCode error
, bool from_peer
) {}
202 // Called when the version negotiation is successful.
203 virtual void OnSuccessfulVersionNegotiation(const QuicVersion
& version
) {}
205 // Called when a CachedNetworkParameters is sent to the client.
206 virtual void OnSendConnectionState(
207 const CachedNetworkParameters
& cached_network_params
) {}
209 // Called when resuming previous connection state.
210 virtual void OnResumeConnectionState(
211 const CachedNetworkParameters
& cached_network_params
) {}
214 class NET_EXPORT_PRIVATE QuicConnectionHelperInterface
{
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
{
239 BUNDLE_PENDING_ACK
= 2,
242 class PacketWriterFactory
{
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
,
255 QuicConnectionHelperInterface
* helper
,
256 const PacketWriterFactory
& writer_factory
,
258 Perspective perspective
,
260 const QuicVersionVector
& supported_versions
);
261 ~QuicConnection() override
;
263 // Sets connection parameters from the supplied |config|.
264 void SetFromConfig(const QuicConfig
& config
);
266 // Called by the session when sending connection state to the client.
267 virtual void OnSendConnectionState(
268 const CachedNetworkParameters
& cached_network_params
);
270 // Called by the Session when the client has provided CachedNetworkParameters.
271 // Returns true if this changes the initial connection state.
272 virtual bool ResumeConnectionState(
273 const CachedNetworkParameters
& cached_network_params
,
274 bool max_bandwidth_resumption
);
276 // Sets the number of active streams on the connection for congestion control.
277 void SetNumOpenStreams(size_t num_streams
);
279 // Send the data in |data| to the peer in as few packets as possible.
280 // Returns a pair with the number of bytes consumed from data, and a boolean
281 // indicating if the fin bit was consumed. This does not indicate the data
282 // has been sent on the wire: it may have been turned into a packet and queued
283 // if the socket was unexpectedly blocked. |fec_protection| indicates if
284 // data is to be FEC protected. Note that data that is sent immediately
285 // following MUST_FEC_PROTECT data may get protected by falling within the
287 // If |delegate| is provided, then it will be informed once ACKs have been
288 // received for all the packets written in this call.
289 // The |delegate| is not owned by the QuicConnection and must outlive it.
290 QuicConsumedData
SendStreamData(QuicStreamId id
,
291 const QuicIOVector
& iov
,
292 QuicStreamOffset offset
,
294 FecProtection fec_protection
,
295 QuicAckNotifier::DelegateInterface
* delegate
);
297 // Send a RST_STREAM frame to the peer.
298 virtual void SendRstStream(QuicStreamId id
,
299 QuicRstStreamErrorCode error
,
300 QuicStreamOffset bytes_written
);
302 // Send a BLOCKED frame to the peer.
303 virtual void SendBlocked(QuicStreamId id
);
305 // Send a WINDOW_UPDATE frame to the peer.
306 virtual void SendWindowUpdate(QuicStreamId id
,
307 QuicStreamOffset byte_offset
);
309 // Sends the connection close packet without affecting the state of the
310 // connection. This should only be called if the session is actively being
311 // destroyed: otherwise call SendConnectionCloseWithDetails instead.
312 virtual void SendConnectionClosePacket(QuicErrorCode error
,
313 const std::string
& details
);
315 // Sends a connection close frame to the peer, and closes the connection by
316 // calling CloseConnection(notifying the visitor as it does so).
317 virtual void SendConnectionClose(QuicErrorCode error
);
318 virtual void SendConnectionCloseWithDetails(QuicErrorCode error
,
319 const std::string
& details
);
320 // Notifies the visitor of the close and marks the connection as disconnected.
321 void CloseConnection(QuicErrorCode error
, bool from_peer
) override
;
322 virtual void SendGoAway(QuicErrorCode error
,
323 QuicStreamId last_good_stream_id
,
324 const std::string
& reason
);
326 // Returns statistics tracked for this connection.
327 const QuicConnectionStats
& GetStats();
329 // Processes an incoming UDP packet (consisting of a QuicEncryptedPacket) from
330 // the peer. If processing this packet permits a packet to be revived from
331 // its FEC group that packet will be revived and processed.
332 // In a client, the packet may be "stray" and have a different connection ID
333 // than that of this connection.
334 virtual void ProcessUdpPacket(const IPEndPoint
& self_address
,
335 const IPEndPoint
& peer_address
,
336 const QuicEncryptedPacket
& packet
);
338 // QuicBlockedWriterInterface
339 // Called when the underlying connection becomes writable to allow queued
341 void OnCanWrite() override
;
343 // Called when an error occurs while attempting to write a packet to the
345 void OnWriteError(int error_code
);
347 // If the socket is not blocked, writes queued packets.
348 void WriteIfNotBlocked();
350 // The version of the protocol this connection is using.
351 QuicVersion
version() const { return framer_
.version(); }
353 // The versions of the protocol that this connection supports.
354 const QuicVersionVector
& supported_versions() const {
355 return framer_
.supported_versions();
358 // From QuicFramerVisitorInterface
359 void OnError(QuicFramer
* framer
) override
;
360 bool OnProtocolVersionMismatch(QuicVersion received_version
) override
;
361 void OnPacket() override
;
362 void OnPublicResetPacket(const QuicPublicResetPacket
& packet
) override
;
363 void OnVersionNegotiationPacket(
364 const QuicVersionNegotiationPacket
& packet
) override
;
365 void OnRevivedPacket() override
;
366 bool OnUnauthenticatedPublicHeader(
367 const QuicPacketPublicHeader
& header
) override
;
368 bool OnUnauthenticatedHeader(const QuicPacketHeader
& header
) override
;
369 void OnDecryptedPacket(EncryptionLevel level
) override
;
370 bool OnPacketHeader(const QuicPacketHeader
& header
) override
;
371 void OnFecProtectedPayload(base::StringPiece payload
) override
;
372 bool OnStreamFrame(const QuicStreamFrame
& frame
) override
;
373 bool OnAckFrame(const QuicAckFrame
& frame
) override
;
374 bool OnStopWaitingFrame(const QuicStopWaitingFrame
& frame
) override
;
375 bool OnPingFrame(const QuicPingFrame
& frame
) override
;
376 bool OnRstStreamFrame(const QuicRstStreamFrame
& frame
) override
;
377 bool OnConnectionCloseFrame(const QuicConnectionCloseFrame
& frame
) override
;
378 bool OnGoAwayFrame(const QuicGoAwayFrame
& frame
) override
;
379 bool OnWindowUpdateFrame(const QuicWindowUpdateFrame
& frame
) override
;
380 bool OnBlockedFrame(const QuicBlockedFrame
& frame
) override
;
381 void OnFecData(const QuicFecData
& fec
) override
;
382 void OnPacketComplete() override
;
384 // QuicPacketGenerator::DelegateInterface
385 bool ShouldGeneratePacket(HasRetransmittableData retransmittable
,
386 IsHandshake handshake
) override
;
387 void PopulateAckFrame(QuicAckFrame
* ack
) override
;
388 void PopulateStopWaitingFrame(QuicStopWaitingFrame
* stop_waiting
) override
;
389 void OnSerializedPacket(const SerializedPacket
& packet
) override
;
390 void OnResetFecGroup() override
;
392 // QuicSentPacketManager::NetworkChangeVisitor
393 void OnCongestionWindowChange() override
;
394 void OnRttChange() override
;
396 // Called by the crypto stream when the handshake completes. In the server's
397 // case this is when the SHLO has been ACKed. Clients call this on receipt of
399 void OnHandshakeComplete();
402 void set_visitor(QuicConnectionVisitorInterface
* visitor
) {
405 void set_debug_visitor(QuicConnectionDebugVisitor
* debug_visitor
) {
406 debug_visitor_
= debug_visitor
;
407 packet_generator_
.set_debug_delegate(debug_visitor
);
408 sent_packet_manager_
.set_debug_delegate(debug_visitor
);
410 const IPEndPoint
& self_address() const { return self_address_
; }
411 const IPEndPoint
& peer_address() const { return peer_address_
; }
412 QuicConnectionId
connection_id() const { return connection_id_
; }
413 const QuicClock
* clock() const { return clock_
; }
414 QuicRandom
* random_generator() const { return random_generator_
; }
415 QuicByteCount
max_packet_length() const;
416 void set_max_packet_length(QuicByteCount length
);
418 bool connected() const { return connected_
; }
420 // Must only be called on client connections.
421 const QuicVersionVector
& server_supported_versions() const {
422 DCHECK_EQ(Perspective::IS_CLIENT
, perspective_
);
423 return server_supported_versions_
;
426 size_t NumFecGroups() const { return group_map_
.size(); }
429 size_t NumQueuedPackets() const { return queued_packets_
.size(); }
431 QuicEncryptedPacket
* ReleaseConnectionClosePacket() {
432 return connection_close_packet_
.release();
435 // Returns true if the underlying UDP socket is writable, there is
436 // no queued data and the connection is not congestion-control
438 bool CanWriteStreamData();
440 // Returns true if the connection has queued packets or frames.
441 bool HasQueuedData() const;
443 // Sets the overall and idle state connection timeouts.
444 void SetNetworkTimeouts(QuicTime::Delta overall_timeout
,
445 QuicTime::Delta idle_timeout
);
447 // If the connection has timed out, this will close the connection.
448 // Otherwise, it will reschedule the timeout alarm.
449 void CheckForTimeout();
451 // Sends a ping, and resets the ping alarm.
454 // Sets up a packet with an QuicAckFrame and sends it out.
457 // Called when an RTO fires. Resets the retransmission alarm if there are
458 // remaining unacked packets.
459 void OnRetransmissionTimeout();
461 // Called when a data packet is sent. Starts an alarm if the data sent in
462 // |sequence_number| was FEC protected.
463 void MaybeSetFecAlarm(QuicPacketSequenceNumber sequence_number
);
465 // Retransmits all unacked packets with retransmittable frames if
466 // |retransmission_type| is ALL_UNACKED_PACKETS, otherwise retransmits only
467 // initially encrypted packets. Used when the negotiated protocol version is
468 // different from what was initially assumed and when the initial encryption
470 void RetransmitUnackedPackets(TransmissionType retransmission_type
);
472 // Calls |sent_packet_manager_|'s NeuterUnencryptedPackets. Used when the
473 // connection becomes forward secure and hasn't received acks for all packets.
474 void NeuterUnencryptedPackets();
476 // Changes the encrypter used for level |level| to |encrypter|. The function
477 // takes ownership of |encrypter|.
478 void SetEncrypter(EncryptionLevel level
, QuicEncrypter
* encrypter
);
480 // SetDefaultEncryptionLevel sets the encryption level that will be applied
482 void SetDefaultEncryptionLevel(EncryptionLevel level
);
484 // SetDecrypter sets the primary decrypter, replacing any that already exists,
485 // and takes ownership. If an alternative decrypter is in place then the
486 // function DCHECKs. This is intended for cases where one knows that future
487 // packets will be using the new decrypter and the previous decrypter is now
488 // obsolete. |level| indicates the encryption level of the new decrypter.
489 void SetDecrypter(EncryptionLevel level
, QuicDecrypter
* decrypter
);
491 // SetAlternativeDecrypter sets a decrypter that may be used to decrypt
492 // future packets and takes ownership of it. |level| indicates the encryption
493 // level of the decrypter. If |latch_once_used| is true, then the first time
494 // that the decrypter is successful it will replace the primary decrypter.
495 // Otherwise both decrypters will remain active and the primary decrypter
496 // will be the one last used.
497 void SetAlternativeDecrypter(EncryptionLevel level
,
498 QuicDecrypter
* decrypter
,
499 bool latch_once_used
);
501 const QuicDecrypter
* decrypter() const;
502 const QuicDecrypter
* alternative_decrypter() const;
504 Perspective
perspective() const { return perspective_
; }
506 // Allow easy overriding of truncated connection IDs.
507 void set_can_truncate_connection_ids(bool can
) {
508 can_truncate_connection_ids_
= can
;
511 // Returns the underlying sent packet manager.
512 const QuicSentPacketManager
& sent_packet_manager() const {
513 return sent_packet_manager_
;
516 bool CanWrite(HasRetransmittableData retransmittable
);
518 // Stores current batch state for connection, puts the connection
519 // into batch mode, and destruction restores the stored batch state.
520 // While the bundler is in scope, any generated frames are bundled
521 // as densely as possible into packets. In addition, this bundler
522 // can be configured to ensure that an ACK frame is included in the
523 // first packet created, if there's new ack information to be sent.
524 class ScopedPacketBundler
{
526 // In addition to all outgoing frames being bundled when the
527 // bundler is in scope, setting |include_ack| to true ensures that
528 // an ACK frame is opportunistically bundled with the first
530 ScopedPacketBundler(QuicConnection
* connection
, AckBundling send_ack
);
531 ~ScopedPacketBundler();
534 QuicConnection
* connection_
;
535 bool already_in_batch_mode_
;
538 QuicPacketSequenceNumber
sequence_number_of_last_sent_packet() const {
539 return sequence_number_of_last_sent_packet_
;
541 const QuicPacketWriter
* writer() const { return writer_
; }
543 bool is_secure() const { return is_secure_
; }
546 // Packets which have not been written to the wire.
547 // Owns the QuicPacket* packet.
548 struct QueuedPacket
{
549 QueuedPacket(SerializedPacket packet
,
550 EncryptionLevel level
);
551 QueuedPacket(SerializedPacket packet
,
552 EncryptionLevel level
,
553 TransmissionType transmission_type
,
554 QuicPacketSequenceNumber original_sequence_number
);
556 SerializedPacket serialized_packet
;
557 const EncryptionLevel encryption_level
;
558 TransmissionType transmission_type
;
559 // The packet's original sequence number if it is a retransmission.
560 // Otherwise it must be 0.
561 QuicPacketSequenceNumber original_sequence_number
;
564 // Do any work which logically would be done in OnPacket but can not be
565 // safely done until the packet is validated. Returns true if the packet
566 // can be handled, false otherwise.
567 virtual bool ProcessValidatedPacket();
569 // Send a packet to the peer, and takes ownership of the packet if the packet
570 // cannot be written immediately.
571 virtual void SendOrQueuePacket(QueuedPacket packet
);
573 QuicConnectionHelperInterface
* helper() { return helper_
; }
575 // Selects and updates the version of the protocol being used by selecting a
576 // version from |available_versions| which is also supported. Returns true if
577 // such a version exists, false otherwise.
578 bool SelectMutualVersion(const QuicVersionVector
& available_versions
);
580 QuicPacketWriter
* writer() { return writer_
; }
582 bool peer_port_changed() const { return peer_port_changed_
; }
585 friend class test::QuicConnectionPeer
;
586 friend class test::PacketSavingConnection
;
588 typedef std::list
<QueuedPacket
> QueuedPacketList
;
589 typedef std::map
<QuicFecGroupNumber
, QuicFecGroup
*> FecGroupMap
;
591 // Writes the given packet to socket, encrypted with packet's
592 // encryption_level. Returns true on successful write, and false if the writer
593 // was blocked and the write needs to be tried again. Notifies the
594 // SentPacketManager when the write is successful and sets
595 // retransmittable frames to nullptr.
596 // Saves the connection close packet for later transmission, even if the
597 // writer is write blocked.
598 bool WritePacket(QueuedPacket
* packet
);
600 // Does the main work of WritePacket, but does not delete the packet or
601 // retransmittable frames upon success.
602 bool WritePacketInner(QueuedPacket
* packet
);
604 // Make sure an ack we got from our peer is sane.
605 bool ValidateAckFrame(const QuicAckFrame
& incoming_ack
);
607 // Make sure a stop waiting we got from our peer is sane.
608 bool ValidateStopWaitingFrame(const QuicStopWaitingFrame
& stop_waiting
);
610 // Sends a version negotiation packet to the peer.
611 void SendVersionNegotiationPacket();
613 // Clears any accumulated frames from the last received packet.
614 void ClearLastFrames();
616 // Closes the connection if the sent or received packet manager are tracking
617 // too many outstanding packets.
618 void MaybeCloseIfTooManyOutstandingPackets();
620 // Writes as many queued packets as possible. The connection must not be
621 // blocked when this is called.
622 void WriteQueuedPackets();
624 // Writes as many pending retransmissions as possible.
625 void WritePendingRetransmissions();
627 // Returns true if the packet should be discarded and not sent.
628 bool ShouldDiscardPacket(const QueuedPacket
& packet
);
630 // Queues |packet| in the hopes that it can be decrypted in the
631 // future, when a new key is installed.
632 void QueueUndecryptablePacket(const QuicEncryptedPacket
& packet
);
634 // Attempts to process any queued undecryptable packets.
635 void MaybeProcessUndecryptablePackets();
637 // If a packet can be revived from the current FEC group, then
638 // revive and process the packet.
639 void MaybeProcessRevivedPacket();
641 void ProcessAckFrame(const QuicAckFrame
& incoming_ack
);
643 void ProcessStopWaitingFrame(const QuicStopWaitingFrame
& stop_waiting
);
645 // Queues an ack or sets the ack alarm when an incoming packet arrives that
647 void MaybeQueueAck();
649 // Checks if the last packet should instigate an ack.
650 bool ShouldLastPacketInstigateAck() const;
652 // Checks if the peer is waiting for packets that have been given up on, and
653 // therefore an ack frame should be sent with a larger least_unacked.
654 void UpdateStopWaitingCount();
656 // Sends any packets which are a response to the last packet, including both
657 // acks and pending writes if an ack opened the congestion window.
658 void MaybeSendInResponseToPacket();
660 // Gets the least unacked sequence number, which is the next sequence number
661 // to be sent if there are no outstanding packets.
662 QuicPacketSequenceNumber
GetLeastUnacked() const;
664 // Get the FEC group associate with the last processed packet or nullptr, if
665 // the group has already been deleted.
666 QuicFecGroup
* GetFecGroup();
668 // Closes any FEC groups protecting packets before |sequence_number|.
669 void CloseFecGroupsBefore(QuicPacketSequenceNumber sequence_number
);
671 // Sets the timeout alarm to the appropriate value, if any.
672 void SetTimeoutAlarm();
674 // Sets the ping alarm to the appropriate value, if any.
677 // On arrival of a new packet, checks to see if the socket addresses have
678 // changed since the last packet we saw on this connection.
679 void CheckForAddressMigration(const IPEndPoint
& self_address
,
680 const IPEndPoint
& peer_address
);
682 HasRetransmittableData
IsRetransmittable(const QueuedPacket
& packet
);
683 bool IsConnectionClose(const QueuedPacket
& packet
);
686 QuicConnectionHelperInterface
* helper_
; // Not owned.
687 QuicPacketWriter
* writer_
; // Owned or not depending on |owns_writer_|.
689 // Encryption level for new packets. Should only be changed via
690 // SetDefaultEncryptionLevel().
691 EncryptionLevel encryption_level_
;
692 bool has_forward_secure_encrypter_
;
693 // The sequence number of the first packet which will be encrypted with the
694 // foward-secure encrypter, even if the peer has not started sending
695 // forward-secure packets.
696 QuicPacketSequenceNumber first_required_forward_secure_packet_
;
697 const QuicClock
* clock_
;
698 QuicRandom
* random_generator_
;
700 const QuicConnectionId connection_id_
;
701 // Address on the last successfully processed packet received from the
703 IPEndPoint self_address_
;
704 IPEndPoint peer_address_
;
705 // Used to store latest peer port to possibly migrate to later.
706 uint16 migrating_peer_port_
;
708 // True if the last packet has gotten far enough in the framer to be
710 bool last_packet_decrypted_
;
711 bool last_packet_revived_
; // True if the last packet was revived from FEC.
712 QuicByteCount last_size_
; // Size of the last received packet.
713 EncryptionLevel last_decrypted_packet_level_
;
714 QuicPacketHeader last_header_
;
715 std::vector
<QuicStreamFrame
> last_stream_frames_
;
716 std::vector
<QuicAckFrame
> last_ack_frames_
;
717 std::vector
<QuicStopWaitingFrame
> last_stop_waiting_frames_
;
718 std::vector
<QuicRstStreamFrame
> last_rst_frames_
;
719 std::vector
<QuicGoAwayFrame
> last_goaway_frames_
;
720 std::vector
<QuicWindowUpdateFrame
> last_window_update_frames_
;
721 std::vector
<QuicBlockedFrame
> last_blocked_frames_
;
722 std::vector
<QuicPingFrame
> last_ping_frames_
;
723 std::vector
<QuicConnectionCloseFrame
> last_close_frames_
;
725 // Track some peer state so we can do less bookkeeping
726 // Largest sequence sent by the peer which had an ack frame (latest ack info).
727 QuicPacketSequenceNumber largest_seen_packet_with_ack_
;
729 // Largest sequence number sent by the peer which had a stop waiting frame.
730 QuicPacketSequenceNumber largest_seen_packet_with_stop_waiting_
;
732 // Collection of packets which were received before encryption was
733 // established, but which could not be decrypted. We buffer these on
734 // the assumption that they could not be processed because they were
735 // sent with the INITIAL encryption and the CHLO message was lost.
736 std::deque
<QuicEncryptedPacket
*> undecryptable_packets_
;
738 // Maximum number of undecryptable packets the connection will store.
739 size_t max_undecryptable_packets_
;
741 // When the version negotiation packet could not be sent because the socket
742 // was not writable, this is set to true.
743 bool pending_version_negotiation_packet_
;
745 // When packets could not be sent because the socket was not writable,
746 // they are added to this list. All corresponding frames are in
747 // unacked_packets_ if they are to be retransmitted.
748 QueuedPacketList queued_packets_
;
750 // Contains the connection close packet if the connection has been closed.
751 scoped_ptr
<QuicEncryptedPacket
> connection_close_packet_
;
753 // When true, the connection does not send a close packet on timeout.
754 bool silent_close_enabled_
;
756 FecGroupMap group_map_
;
758 QuicReceivedPacketManager received_packet_manager_
;
759 QuicSentEntropyManager sent_entropy_manager_
;
761 // Indicates whether an ack should be sent the next time we try to write.
763 // Indicates how many consecutive packets have arrived without sending an ack.
764 QuicPacketCount num_packets_received_since_last_ack_sent_
;
765 // Indicates how many consecutive times an ack has arrived which indicates
766 // the peer needs to stop waiting for some packets.
767 int stop_waiting_count_
;
769 // An alarm that fires when an ACK should be sent to the peer.
770 scoped_ptr
<QuicAlarm
> ack_alarm_
;
771 // An alarm that fires when a packet needs to be retransmitted.
772 scoped_ptr
<QuicAlarm
> retransmission_alarm_
;
773 // An alarm that is scheduled when the SentPacketManager requires a delay
774 // before sending packets and fires when the packet may be sent.
775 scoped_ptr
<QuicAlarm
> send_alarm_
;
776 // An alarm that is scheduled when the connection can still write and there
777 // may be more data to send.
778 scoped_ptr
<QuicAlarm
> resume_writes_alarm_
;
779 // An alarm that fires when the connection may have timed out.
780 scoped_ptr
<QuicAlarm
> timeout_alarm_
;
781 // An alarm that fires when a ping should be sent.
782 scoped_ptr
<QuicAlarm
> ping_alarm_
;
784 // Neither visitor is owned by this class.
785 QuicConnectionVisitorInterface
* visitor_
;
786 QuicConnectionDebugVisitor
* debug_visitor_
;
788 QuicPacketGenerator packet_generator_
;
790 // An alarm that fires when an FEC packet should be sent.
791 scoped_ptr
<QuicAlarm
> fec_alarm_
;
793 // Network idle time before we kill of this connection.
794 QuicTime::Delta idle_network_timeout_
;
795 // Overall connection timeout.
796 QuicTime::Delta overall_connection_timeout_
;
798 // Statistics for this session.
799 QuicConnectionStats stats_
;
801 // The time that we got a packet for this connection.
802 // This is used for timeouts, and does not indicate the packet was processed.
803 QuicTime time_of_last_received_packet_
;
805 // The last time this connection began sending a new (non-retransmitted)
807 QuicTime time_of_last_sent_new_packet_
;
809 // Sequence number of the last sent packet. Packets are guaranteed to be sent
810 // in sequence number order.
811 QuicPacketSequenceNumber sequence_number_of_last_sent_packet_
;
813 // Sent packet manager which tracks the status of packets sent by this
814 // connection and contains the send and receive algorithms to determine when
816 QuicSentPacketManager sent_packet_manager_
;
818 // The state of connection in version negotiation finite state machine.
819 QuicVersionNegotiationState version_negotiation_state_
;
821 // Tracks if the connection was created by the server or the client.
822 Perspective perspective_
;
824 // True by default. False if we've received or sent an explicit connection
828 // Set to true if the UDP packet headers have a new IP address for the peer.
829 // If true, do not perform connection migration.
830 bool peer_ip_changed_
;
832 // Set to true if the UDP packet headers have a new port for the peer.
833 // If true, and the IP has not changed, then we can migrate the connection.
834 bool peer_port_changed_
;
836 // Set to true if the UDP packet headers are addressed to a different IP.
837 // We do not support connection migration when the self IP changed.
838 bool self_ip_changed_
;
840 // Set to true if the UDP packet headers are addressed to a different port.
841 // We do not support connection migration when the self port changed.
842 bool self_port_changed_
;
844 // Set to false if the connection should not send truncated connection IDs to
845 // the peer, even if the peer supports it.
846 bool can_truncate_connection_ids_
;
848 // If non-empty this contains the set of versions received in a
849 // version negotiation packet.
850 QuicVersionVector server_supported_versions_
;
852 // True if this is a secure QUIC connection.
855 DISALLOW_COPY_AND_ASSIGN(QuicConnection
);
860 #endif // NET_QUIC_QUIC_CONNECTION_H_