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/crypto/quic_decrypter.h"
33 #include "net/quic/quic_ack_notifier.h"
34 #include "net/quic/quic_ack_notifier_manager.h"
35 #include "net/quic/quic_alarm.h"
36 #include "net/quic/quic_blocked_writer_interface.h"
37 #include "net/quic/quic_connection_stats.h"
38 #include "net/quic/quic_packet_creator.h"
39 #include "net/quic/quic_packet_generator.h"
40 #include "net/quic/quic_packet_writer.h"
41 #include "net/quic/quic_protocol.h"
42 #include "net/quic/quic_received_packet_manager.h"
43 #include "net/quic/quic_sent_entropy_manager.h"
44 #include "net/quic/quic_sent_packet_manager.h"
45 #include "net/quic/quic_time.h"
46 #include "net/quic/quic_types.h"
59 class PacketSavingConnection
;
60 class QuicConnectionPeer
;
63 // The initial number of packets between MTU probes. After each attempt the
65 const QuicPacketCount kPacketsBetweenMtuProbesBase
= 100;
67 // The number of MTU probes that get sent before giving up.
68 const size_t kMtuDiscoveryAttempts
= 3;
70 // Ensure that exponential back-off does not result in an integer overflow.
71 // The number of packets can be potentially capped, but that is not useful at
72 // current kMtuDiscoveryAttempts value, and hence is not implemented at present.
73 static_assert(kMtuDiscoveryAttempts
+ 8 < 8 * sizeof(QuicPacketNumber
),
74 "The number of MTU discovery attempts is too high");
75 static_assert(kPacketsBetweenMtuProbesBase
< (1 << 8),
76 "The initial number of packets between MTU probes is too high");
78 // The incresed packet size targeted when doing path MTU discovery.
79 const QuicByteCount kMtuDiscoveryTargetPacketSizeHigh
= 1450;
80 const QuicByteCount kMtuDiscoveryTargetPacketSizeLow
= 1430;
82 static_assert(kMtuDiscoveryTargetPacketSizeLow
<= kMaxPacketSize
,
83 "MTU discovery target is too large");
84 static_assert(kMtuDiscoveryTargetPacketSizeHigh
<= kMaxPacketSize
,
85 "MTU discovery target is too large");
87 static_assert(kMtuDiscoveryTargetPacketSizeLow
> kDefaultMaxPacketSize
,
88 "MTU discovery target does not exceed the default packet size");
89 static_assert(kMtuDiscoveryTargetPacketSizeHigh
> kDefaultMaxPacketSize
,
90 "MTU discovery target does not exceed the default packet size");
92 // Class that receives callbacks from the connection when frames are received
93 // and when other interesting events happen.
94 class NET_EXPORT_PRIVATE QuicConnectionVisitorInterface
{
96 virtual ~QuicConnectionVisitorInterface() {}
98 // A simple visitor interface for dealing with a data frame.
99 virtual void OnStreamFrame(const QuicStreamFrame
& frame
) = 0;
101 // The session should process the WINDOW_UPDATE frame, adjusting both stream
102 // and connection level flow control windows.
103 virtual void OnWindowUpdateFrame(const QuicWindowUpdateFrame
& frame
) = 0;
105 // A BLOCKED frame indicates the peer is flow control blocked
106 // on a specified stream.
107 virtual void OnBlockedFrame(const QuicBlockedFrame
& frame
) = 0;
109 // Called when the stream is reset by the peer.
110 virtual void OnRstStream(const QuicRstStreamFrame
& frame
) = 0;
112 // Called when the connection is going away according to the peer.
113 virtual void OnGoAway(const QuicGoAwayFrame
& frame
) = 0;
115 // Called when the connection is closed either locally by the framer, or
116 // remotely by the peer.
117 virtual void OnConnectionClosed(QuicErrorCode error
, bool from_peer
) = 0;
119 // Called when the connection failed to write because the socket was blocked.
120 virtual void OnWriteBlocked() = 0;
122 // Called once a specific QUIC version is agreed by both endpoints.
123 virtual void OnSuccessfulVersionNegotiation(const QuicVersion
& version
) = 0;
125 // Called when a blocked socket becomes writable.
126 virtual void OnCanWrite() = 0;
128 // Called when the connection experiences a change in congestion window.
129 virtual void OnCongestionWindowChange(QuicTime now
) = 0;
131 // Called when the connection receives a packet from a migrated client.
132 virtual void OnConnectionMigration() = 0;
134 // Called to ask if the visitor wants to schedule write resumption as it both
135 // has pending data to write, and is able to write (e.g. based on flow control
137 // Writes may be pending because they were write-blocked, congestion-throttled
138 // or yielded to other connections.
139 virtual bool WillingAndAbleToWrite() const = 0;
141 // Called to ask if any handshake messages are pending in this visitor.
142 virtual bool HasPendingHandshake() const = 0;
144 // Called to ask if any streams are open in this visitor, excluding the
145 // reserved crypto and headers stream.
146 virtual bool HasOpenDynamicStreams() const = 0;
149 // Interface which gets callbacks from the QuicConnection at interesting
150 // points. Implementations must not mutate the state of the connection
151 // as a result of these callbacks.
152 class NET_EXPORT_PRIVATE QuicConnectionDebugVisitor
153 : public QuicPacketGenerator::DebugDelegate
,
154 public QuicSentPacketManager::DebugDelegate
{
156 ~QuicConnectionDebugVisitor() override
{}
158 // Called when a packet has been sent.
159 virtual void OnPacketSent(const SerializedPacket
& serialized_packet
,
160 QuicPacketNumber original_packet_number
,
161 EncryptionLevel level
,
162 TransmissionType transmission_type
,
163 const QuicEncryptedPacket
& packet
,
164 QuicTime sent_time
) {}
166 // Called when a packet has been received, but before it is
167 // validated or parsed.
168 virtual void OnPacketReceived(const IPEndPoint
& self_address
,
169 const IPEndPoint
& peer_address
,
170 const QuicEncryptedPacket
& packet
) {}
172 // Called when the unauthenticated portion of the header has been parsed.
173 virtual void OnUnauthenticatedHeader(const QuicPacketHeader
& header
) {}
175 // Called when a packet is received with a connection id that does not
176 // match the ID of this connection.
177 virtual void OnIncorrectConnectionId(
178 QuicConnectionId connection_id
) {}
180 // Called when an undecryptable packet has been received.
181 virtual void OnUndecryptablePacket() {}
183 // Called when a duplicate packet has been received.
184 virtual void OnDuplicatePacket(QuicPacketNumber packet_number
) {}
186 // Called when the protocol version on the received packet doensn't match
187 // current protocol version of the connection.
188 virtual void OnProtocolVersionMismatch(QuicVersion version
) {}
190 // Called when the complete header of a packet has been parsed.
191 virtual void OnPacketHeader(const QuicPacketHeader
& header
) {}
193 // Called when a StreamFrame has been parsed.
194 virtual void OnStreamFrame(const QuicStreamFrame
& frame
) {}
196 // Called when a AckFrame has been parsed.
197 virtual void OnAckFrame(const QuicAckFrame
& frame
) {}
199 // Called when a StopWaitingFrame has been parsed.
200 virtual void OnStopWaitingFrame(const QuicStopWaitingFrame
& frame
) {}
202 // Called when a Ping has been parsed.
203 virtual void OnPingFrame(const QuicPingFrame
& frame
) {}
205 // Called when a GoAway has been parsed.
206 virtual void OnGoAwayFrame(const QuicGoAwayFrame
& frame
) {}
208 // Called when a RstStreamFrame has been parsed.
209 virtual void OnRstStreamFrame(const QuicRstStreamFrame
& frame
) {}
211 // Called when a ConnectionCloseFrame has been parsed.
212 virtual void OnConnectionCloseFrame(
213 const QuicConnectionCloseFrame
& frame
) {}
215 // Called when a WindowUpdate has been parsed.
216 virtual void OnWindowUpdateFrame(const QuicWindowUpdateFrame
& frame
) {}
218 // Called when a BlockedFrame has been parsed.
219 virtual void OnBlockedFrame(const QuicBlockedFrame
& frame
) {}
221 // Called when a public reset packet has been received.
222 virtual void OnPublicResetPacket(const QuicPublicResetPacket
& packet
) {}
224 // Called when a version negotiation packet has been received.
225 virtual void OnVersionNegotiationPacket(
226 const QuicVersionNegotiationPacket
& packet
) {}
228 // Called after a packet has been successfully parsed which results
229 // in the revival of a packet via FEC.
230 virtual void OnRevivedPacket(const QuicPacketHeader
& revived_header
,
231 base::StringPiece payload
) {}
233 // Called when the connection is closed.
234 virtual void OnConnectionClosed(QuicErrorCode error
, bool from_peer
) {}
236 // Called when the version negotiation is successful.
237 virtual void OnSuccessfulVersionNegotiation(const QuicVersion
& version
) {}
239 // Called when a CachedNetworkParameters is sent to the client.
240 virtual void OnSendConnectionState(
241 const CachedNetworkParameters
& cached_network_params
) {}
243 // Called when resuming previous connection state.
244 virtual void OnResumeConnectionState(
245 const CachedNetworkParameters
& cached_network_params
) {}
248 class NET_EXPORT_PRIVATE QuicConnectionHelperInterface
{
250 virtual ~QuicConnectionHelperInterface() {}
252 // Returns a QuicClock to be used for all time related functions.
253 virtual const QuicClock
* GetClock() const = 0;
255 // Returns a QuicRandom to be used for all random number related functions.
256 virtual QuicRandom
* GetRandomGenerator() = 0;
258 // Creates a new platform-specific alarm which will be configured to
259 // notify |delegate| when the alarm fires. Caller takes ownership
260 // of the new alarm, which will not yet be "set" to fire.
261 virtual QuicAlarm
* CreateAlarm(QuicAlarm::Delegate
* delegate
) = 0;
264 class NET_EXPORT_PRIVATE QuicConnection
265 : public QuicFramerVisitorInterface
,
266 public QuicBlockedWriterInterface
,
267 public QuicPacketGenerator::DelegateInterface
,
268 public QuicSentPacketManager::NetworkChangeVisitor
{
273 BUNDLE_PENDING_ACK
= 2,
276 class PacketWriterFactory
{
278 virtual ~PacketWriterFactory() {}
280 virtual QuicPacketWriter
* Create(QuicConnection
* connection
) const = 0;
283 // Constructs a new QuicConnection for |connection_id| and |address|. Invokes
284 // writer_factory->Create() to get a writer; |owns_writer| specifies whether
285 // the connection takes ownership of the returned writer. |helper| must
286 // outlive this connection.
287 QuicConnection(QuicConnectionId connection_id
,
289 QuicConnectionHelperInterface
* helper
,
290 const PacketWriterFactory
& writer_factory
,
292 Perspective perspective
,
294 const QuicVersionVector
& supported_versions
);
295 ~QuicConnection() override
;
297 // Sets connection parameters from the supplied |config|.
298 void SetFromConfig(const QuicConfig
& config
);
300 // Called by the session when sending connection state to the client.
301 virtual void OnSendConnectionState(
302 const CachedNetworkParameters
& cached_network_params
);
304 // Called by the Session when the client has provided CachedNetworkParameters.
305 virtual void ResumeConnectionState(
306 const CachedNetworkParameters
& cached_network_params
,
307 bool max_bandwidth_resumption
);
309 // Sets the number of active streams on the connection for congestion control.
310 void SetNumOpenStreams(size_t num_streams
);
312 // Send the data in |data| to the peer in as few packets as possible.
313 // Returns a pair with the number of bytes consumed from data, and a boolean
314 // indicating if the fin bit was consumed. This does not indicate the data
315 // has been sent on the wire: it may have been turned into a packet and queued
316 // if the socket was unexpectedly blocked. |fec_protection| indicates if
317 // data is to be FEC protected. Note that data that is sent immediately
318 // following MUST_FEC_PROTECT data may get protected by falling within the
320 // If |delegate| is provided, then it will be informed once ACKs have been
321 // received for all the packets written in this call.
322 // The |delegate| is not owned by the QuicConnection and must outlive it.
323 QuicConsumedData
SendStreamData(QuicStreamId id
,
324 const QuicIOVector
& iov
,
325 QuicStreamOffset offset
,
327 FecProtection fec_protection
,
328 QuicAckNotifier::DelegateInterface
* delegate
);
330 // Send a RST_STREAM frame to the peer.
331 virtual void SendRstStream(QuicStreamId id
,
332 QuicRstStreamErrorCode error
,
333 QuicStreamOffset bytes_written
);
335 // Send a BLOCKED frame to the peer.
336 virtual void SendBlocked(QuicStreamId id
);
338 // Send a WINDOW_UPDATE frame to the peer.
339 virtual void SendWindowUpdate(QuicStreamId id
,
340 QuicStreamOffset byte_offset
);
342 // Sends the connection close packet without affecting the state of the
343 // connection. This should only be called if the session is actively being
344 // destroyed: otherwise call SendConnectionCloseWithDetails instead.
345 virtual void SendConnectionClosePacket(QuicErrorCode error
,
346 const std::string
& details
);
348 // Sends a connection close frame to the peer, and closes the connection by
349 // calling CloseConnection(notifying the visitor as it does so).
350 virtual void SendConnectionClose(QuicErrorCode error
);
351 virtual void SendConnectionCloseWithDetails(QuicErrorCode error
,
352 const std::string
& details
);
353 // Notifies the visitor of the close and marks the connection as disconnected.
354 void CloseConnection(QuicErrorCode error
, bool from_peer
) override
;
356 // Sends a GOAWAY frame. Does nothing if a GOAWAY frame has already been sent.
357 virtual void SendGoAway(QuicErrorCode error
,
358 QuicStreamId last_good_stream_id
,
359 const std::string
& reason
);
361 // Returns statistics tracked for this connection.
362 const QuicConnectionStats
& GetStats();
364 // Processes an incoming UDP packet (consisting of a QuicEncryptedPacket) from
365 // the peer. If processing this packet permits a packet to be revived from
366 // its FEC group that packet will be revived and processed.
367 // In a client, the packet may be "stray" and have a different connection ID
368 // than that of this connection.
369 virtual void ProcessUdpPacket(const IPEndPoint
& self_address
,
370 const IPEndPoint
& peer_address
,
371 const QuicEncryptedPacket
& packet
);
373 // QuicBlockedWriterInterface
374 // Called when the underlying connection becomes writable to allow queued
376 void OnCanWrite() override
;
378 // Called when an error occurs while attempting to write a packet to the
380 void OnWriteError(int error_code
);
382 // If the socket is not blocked, writes queued packets.
383 void WriteIfNotBlocked();
385 // Set the packet writer.
386 void SetQuicPacketWriter(QuicPacketWriter
* writer
, bool owns_writer
) {
388 owns_writer_
= owns_writer
;
392 void SetSelfAddress(IPEndPoint address
) { self_address_
= address
; }
394 // The version of the protocol this connection is using.
395 QuicVersion
version() const { return framer_
.version(); }
397 // The versions of the protocol that this connection supports.
398 const QuicVersionVector
& supported_versions() const {
399 return framer_
.supported_versions();
402 // From QuicFramerVisitorInterface
403 void OnError(QuicFramer
* framer
) override
;
404 bool OnProtocolVersionMismatch(QuicVersion received_version
) override
;
405 void OnPacket() override
;
406 void OnPublicResetPacket(const QuicPublicResetPacket
& packet
) override
;
407 void OnVersionNegotiationPacket(
408 const QuicVersionNegotiationPacket
& packet
) override
;
409 void OnRevivedPacket() override
;
410 bool OnUnauthenticatedPublicHeader(
411 const QuicPacketPublicHeader
& header
) override
;
412 bool OnUnauthenticatedHeader(const QuicPacketHeader
& header
) override
;
413 void OnDecryptedPacket(EncryptionLevel level
) override
;
414 bool OnPacketHeader(const QuicPacketHeader
& header
) override
;
415 void OnFecProtectedPayload(base::StringPiece payload
) override
;
416 bool OnStreamFrame(const QuicStreamFrame
& frame
) override
;
417 bool OnAckFrame(const QuicAckFrame
& frame
) override
;
418 bool OnStopWaitingFrame(const QuicStopWaitingFrame
& frame
) override
;
419 bool OnPingFrame(const QuicPingFrame
& frame
) override
;
420 bool OnRstStreamFrame(const QuicRstStreamFrame
& frame
) override
;
421 bool OnConnectionCloseFrame(const QuicConnectionCloseFrame
& frame
) override
;
422 bool OnGoAwayFrame(const QuicGoAwayFrame
& frame
) override
;
423 bool OnWindowUpdateFrame(const QuicWindowUpdateFrame
& frame
) override
;
424 bool OnBlockedFrame(const QuicBlockedFrame
& frame
) override
;
425 void OnFecData(const QuicFecData
& fec
) override
;
426 void OnPacketComplete() override
;
428 // QuicPacketGenerator::DelegateInterface
429 bool ShouldGeneratePacket(HasRetransmittableData retransmittable
,
430 IsHandshake handshake
) override
;
431 void PopulateAckFrame(QuicAckFrame
* ack
) override
;
432 void PopulateStopWaitingFrame(QuicStopWaitingFrame
* stop_waiting
) override
;
433 void OnSerializedPacket(const SerializedPacket
& packet
) override
;
434 void OnResetFecGroup() override
;
436 // QuicSentPacketManager::NetworkChangeVisitor
437 void OnCongestionWindowChange() override
;
438 void OnRttChange() override
;
440 // Called by the crypto stream when the handshake completes. In the server's
441 // case this is when the SHLO has been ACKed. Clients call this on receipt of
443 void OnHandshakeComplete();
446 void set_visitor(QuicConnectionVisitorInterface
* visitor
) {
449 void set_debug_visitor(QuicConnectionDebugVisitor
* debug_visitor
) {
450 debug_visitor_
= debug_visitor
;
451 packet_generator_
.set_debug_delegate(debug_visitor
);
452 sent_packet_manager_
.set_debug_delegate(debug_visitor
);
454 const IPEndPoint
& self_address() const { return self_address_
; }
455 const IPEndPoint
& peer_address() const { return peer_address_
; }
456 QuicConnectionId
connection_id() const { return connection_id_
; }
457 const QuicClock
* clock() const { return clock_
; }
458 QuicRandom
* random_generator() const { return random_generator_
; }
459 QuicByteCount
max_packet_length() const;
460 void set_max_packet_length(QuicByteCount length
);
462 size_t mtu_probe_count() const { return mtu_probe_count_
; }
464 bool connected() const { return connected_
; }
466 bool goaway_sent() const { return goaway_sent_
; }
468 bool goaway_received() const { return goaway_received_
; }
470 // Must only be called on client connections.
471 const QuicVersionVector
& server_supported_versions() const {
472 DCHECK_EQ(Perspective::IS_CLIENT
, perspective_
);
473 return server_supported_versions_
;
476 size_t NumFecGroups() const { return group_map_
.size(); }
479 size_t NumQueuedPackets() const { return queued_packets_
.size(); }
481 QuicEncryptedPacket
* ReleaseConnectionClosePacket() {
482 return connection_close_packet_
.release();
485 // Returns true if the underlying UDP socket is writable, there is
486 // no queued data and the connection is not congestion-control
488 bool CanWriteStreamData();
490 // Returns true if the connection has queued packets or frames.
491 bool HasQueuedData() const;
493 // Sets the overall and idle state connection timeouts.
494 void SetNetworkTimeouts(QuicTime::Delta overall_timeout
,
495 QuicTime::Delta idle_timeout
);
497 // If the connection has timed out, this will close the connection.
498 // Otherwise, it will reschedule the timeout alarm.
499 void CheckForTimeout();
501 // Sends a ping, and resets the ping alarm.
504 // Sets up a packet with an QuicAckFrame and sends it out.
507 // Called when an RTO fires. Resets the retransmission alarm if there are
508 // remaining unacked packets.
509 void OnRetransmissionTimeout();
511 // Called when a data packet is sent. Starts an alarm if the data sent in
512 // |packet_number| was FEC protected.
513 void MaybeSetFecAlarm(QuicPacketNumber packet_number
);
515 // Retransmits all unacked packets with retransmittable frames if
516 // |retransmission_type| is ALL_UNACKED_PACKETS, otherwise retransmits only
517 // initially encrypted packets. Used when the negotiated protocol version is
518 // different from what was initially assumed and when the initial encryption
520 void RetransmitUnackedPackets(TransmissionType retransmission_type
);
522 // Calls |sent_packet_manager_|'s NeuterUnencryptedPackets. Used when the
523 // connection becomes forward secure and hasn't received acks for all packets.
524 void NeuterUnencryptedPackets();
526 // Changes the encrypter used for level |level| to |encrypter|. The function
527 // takes ownership of |encrypter|.
528 void SetEncrypter(EncryptionLevel level
, QuicEncrypter
* encrypter
);
530 // SetDefaultEncryptionLevel sets the encryption level that will be applied
532 void SetDefaultEncryptionLevel(EncryptionLevel level
);
534 // SetDecrypter sets the primary decrypter, replacing any that already exists,
535 // and takes ownership. If an alternative decrypter is in place then the
536 // function DCHECKs. This is intended for cases where one knows that future
537 // packets will be using the new decrypter and the previous decrypter is now
538 // obsolete. |level| indicates the encryption level of the new decrypter.
539 void SetDecrypter(EncryptionLevel level
, QuicDecrypter
* decrypter
);
541 // SetAlternativeDecrypter sets a decrypter that may be used to decrypt
542 // future packets and takes ownership of it. |level| indicates the encryption
543 // level of the decrypter. If |latch_once_used| is true, then the first time
544 // that the decrypter is successful it will replace the primary decrypter.
545 // Otherwise both decrypters will remain active and the primary decrypter
546 // will be the one last used.
547 void SetAlternativeDecrypter(EncryptionLevel level
,
548 QuicDecrypter
* decrypter
,
549 bool latch_once_used
);
551 const QuicDecrypter
* decrypter() const;
552 const QuicDecrypter
* alternative_decrypter() const;
554 Perspective
perspective() const { return perspective_
; }
556 // Allow easy overriding of truncated connection IDs.
557 void set_can_truncate_connection_ids(bool can
) {
558 can_truncate_connection_ids_
= can
;
561 // Returns the underlying sent packet manager.
562 const QuicSentPacketManager
& sent_packet_manager() const {
563 return sent_packet_manager_
;
566 bool CanWrite(HasRetransmittableData retransmittable
);
568 // Stores current batch state for connection, puts the connection
569 // into batch mode, and destruction restores the stored batch state.
570 // While the bundler is in scope, any generated frames are bundled
571 // as densely as possible into packets. In addition, this bundler
572 // can be configured to ensure that an ACK frame is included in the
573 // first packet created, if there's new ack information to be sent.
574 class ScopedPacketBundler
{
576 // In addition to all outgoing frames being bundled when the
577 // bundler is in scope, setting |include_ack| to true ensures that
578 // an ACK frame is opportunistically bundled with the first
580 ScopedPacketBundler(QuicConnection
* connection
, AckBundling send_ack
);
581 ~ScopedPacketBundler();
584 QuicConnection
* connection_
;
585 bool already_in_batch_mode_
;
588 // Delays setting the retransmission alarm until the scope is exited.
589 // When nested, only the outermost scheduler will set the alarm, and inner
590 // ones have no effect.
591 class NET_EXPORT_PRIVATE ScopedRetransmissionScheduler
{
593 explicit ScopedRetransmissionScheduler(QuicConnection
* connection
);
594 ~ScopedRetransmissionScheduler();
597 QuicConnection
* connection_
;
598 // Set to the connection's delay_setting_retransmission_alarm_ value in the
599 // constructor and when true, causes this class to do nothing.
600 const bool already_delayed_
;
603 QuicPacketNumber
packet_number_of_last_sent_packet() const {
604 return packet_number_of_last_sent_packet_
;
607 QuicPacketWriter
* writer() { return writer_
; }
608 const QuicPacketWriter
* writer() const { return writer_
; }
610 bool is_secure() const { return is_secure_
; }
612 // Sends an MTU discovery packet of size |target_mtu|. If the packet is
613 // acknowledged by the peer, the maximum packet size will be increased to
615 void SendMtuDiscoveryPacket(QuicByteCount target_mtu
);
617 // Sends an MTU discovery packet of size |mtu_discovery_target_| and updates
618 // the MTU discovery alarm.
621 // Return the name of the cipher of the primary decrypter of the framer.
622 const char* cipher_name() const { return framer_
.decrypter()->cipher_name(); }
623 // Return the id of the cipher of the primary decrypter of the framer.
624 uint32
cipher_id() const { return framer_
.decrypter()->cipher_id(); }
627 // Packets which have not been written to the wire.
628 // Owns the QuicPacket* packet.
629 struct QueuedPacket
{
630 QueuedPacket(SerializedPacket packet
,
631 EncryptionLevel level
);
632 QueuedPacket(SerializedPacket packet
,
633 EncryptionLevel level
,
634 TransmissionType transmission_type
,
635 QuicPacketNumber original_packet_number
);
637 SerializedPacket serialized_packet
;
638 const EncryptionLevel encryption_level
;
639 TransmissionType transmission_type
;
640 // The packet's original packet number if it is a retransmission.
641 // Otherwise it must be 0.
642 QuicPacketNumber original_packet_number
;
645 // Do any work which logically would be done in OnPacket but can not be
646 // safely done until the packet is validated. Returns true if the packet
647 // can be handled, false otherwise.
648 virtual bool ProcessValidatedPacket();
650 // Send a packet to the peer, and takes ownership of the packet if the packet
651 // cannot be written immediately.
652 virtual void SendOrQueuePacket(QueuedPacket packet
);
654 QuicConnectionHelperInterface
* helper() { return helper_
; }
656 // Selects and updates the version of the protocol being used by selecting a
657 // version from |available_versions| which is also supported. Returns true if
658 // such a version exists, false otherwise.
659 bool SelectMutualVersion(const QuicVersionVector
& available_versions
);
661 bool peer_port_changed() const { return peer_port_changed_
; }
664 friend class test::QuicConnectionPeer
;
665 friend class test::PacketSavingConnection
;
667 typedef std::list
<QueuedPacket
> QueuedPacketList
;
668 typedef std::map
<QuicFecGroupNumber
, QuicFecGroup
*> FecGroupMap
;
670 // Writes the given packet to socket, encrypted with packet's
671 // encryption_level. Returns true on successful write, and false if the writer
672 // was blocked and the write needs to be tried again. Notifies the
673 // SentPacketManager when the write is successful and sets
674 // retransmittable frames to nullptr.
675 // Saves the connection close packet for later transmission, even if the
676 // writer is write blocked.
677 bool WritePacket(QueuedPacket
* packet
);
679 // Does the main work of WritePacket, but does not delete the packet or
680 // retransmittable frames upon success.
681 bool WritePacketInner(QueuedPacket
* packet
);
683 // Make sure an ack we got from our peer is sane.
684 bool ValidateAckFrame(const QuicAckFrame
& incoming_ack
);
686 // Make sure a stop waiting we got from our peer is sane.
687 bool ValidateStopWaitingFrame(const QuicStopWaitingFrame
& stop_waiting
);
689 // Sends a version negotiation packet to the peer.
690 void SendVersionNegotiationPacket();
692 // Clears any accumulated frames from the last received packet.
693 void ClearLastFrames();
695 // Deletes and clears any QueuedPackets.
696 void ClearQueuedPackets();
698 // Closes the connection if the sent or received packet manager are tracking
699 // too many outstanding packets.
700 void MaybeCloseIfTooManyOutstandingPackets();
702 // Writes as many queued packets as possible. The connection must not be
703 // blocked when this is called.
704 void WriteQueuedPackets();
706 // Writes as many pending retransmissions as possible.
707 void WritePendingRetransmissions();
709 // Returns true if the packet should be discarded and not sent.
710 bool ShouldDiscardPacket(const QueuedPacket
& packet
);
712 // Queues |packet| in the hopes that it can be decrypted in the
713 // future, when a new key is installed.
714 void QueueUndecryptablePacket(const QuicEncryptedPacket
& packet
);
716 // Attempts to process any queued undecryptable packets.
717 void MaybeProcessUndecryptablePackets();
719 // If a packet can be revived from the current FEC group, then
720 // revive and process the packet.
721 void MaybeProcessRevivedPacket();
723 void ProcessAckFrame(const QuicAckFrame
& incoming_ack
);
725 void ProcessStopWaitingFrame(const QuicStopWaitingFrame
& stop_waiting
);
727 // Queues an ack or sets the ack alarm when an incoming packet arrives that
729 void MaybeQueueAck();
731 // Checks if the last packet should instigate an ack.
732 bool ShouldLastPacketInstigateAck() const;
734 // Checks if the peer is waiting for packets that have been given up on, and
735 // therefore an ack frame should be sent with a larger least_unacked.
736 void UpdateStopWaitingCount();
738 // Sends any packets which are a response to the last packet, including both
739 // acks and pending writes if an ack opened the congestion window.
740 void MaybeSendInResponseToPacket();
742 // Gets the least unacked packet number, which is the next packet number
743 // to be sent if there are no outstanding packets.
744 QuicPacketNumber
GetLeastUnacked() const;
746 // Get the FEC group associate with the last processed packet or nullptr, if
747 // the group has already been deleted.
748 QuicFecGroup
* GetFecGroup();
750 // Closes any FEC groups protecting packets before |packet_number|.
751 void CloseFecGroupsBefore(QuicPacketNumber packet_number
);
753 // Sets the timeout alarm to the appropriate value, if any.
754 void SetTimeoutAlarm();
756 // Sets the ping alarm to the appropriate value, if any.
759 // Sets the retransmission alarm based on SentPacketManager.
760 void SetRetransmissionAlarm();
762 // Sets the MTU discovery alarm if necessary.
763 void MaybeSetMtuAlarm();
765 // On arrival of a new packet, checks to see if the socket addresses have
766 // changed since the last packet we saw on this connection.
767 void CheckForAddressMigration(const IPEndPoint
& self_address
,
768 const IPEndPoint
& peer_address
);
770 HasRetransmittableData
IsRetransmittable(const QueuedPacket
& packet
);
771 bool IsConnectionClose(const QueuedPacket
& packet
);
774 QuicConnectionHelperInterface
* helper_
; // Not owned.
775 QuicPacketWriter
* writer_
; // Owned or not depending on |owns_writer_|.
777 // Encryption level for new packets. Should only be changed via
778 // SetDefaultEncryptionLevel().
779 EncryptionLevel encryption_level_
;
780 bool has_forward_secure_encrypter_
;
781 // The packet number of the first packet which will be encrypted with the
782 // foward-secure encrypter, even if the peer has not started sending
783 // forward-secure packets.
784 QuicPacketNumber first_required_forward_secure_packet_
;
785 const QuicClock
* clock_
;
786 QuicRandom
* random_generator_
;
788 const QuicConnectionId connection_id_
;
789 // Address on the last successfully processed packet received from the
791 IPEndPoint self_address_
;
792 IPEndPoint peer_address_
;
794 // TODO(fayang): Use migrating_peer_address_ instead of migrating_peer_ip_
795 // and migrating_peer_port_ once FLAGS_quic_allow_ip_migration is deprecated.
796 // Used to store latest peer IP address for IP address migration.
797 IPAddressNumber migrating_peer_ip_
;
798 // Used to store latest peer port to possibly migrate to later.
799 uint16 migrating_peer_port_
;
801 // True if the last packet has gotten far enough in the framer to be
803 bool last_packet_decrypted_
;
804 bool last_packet_revived_
; // True if the last packet was revived from FEC.
805 QuicByteCount last_size_
; // Size of the last received packet.
806 EncryptionLevel last_decrypted_packet_level_
;
807 QuicPacketHeader last_header_
;
808 std::vector
<QuicStreamFrame
> last_stream_frames_
;
809 std::vector
<QuicAckFrame
> last_ack_frames_
;
810 std::vector
<QuicStopWaitingFrame
> last_stop_waiting_frames_
;
811 std::vector
<QuicRstStreamFrame
> last_rst_frames_
;
812 std::vector
<QuicGoAwayFrame
> last_goaway_frames_
;
813 std::vector
<QuicWindowUpdateFrame
> last_window_update_frames_
;
814 std::vector
<QuicBlockedFrame
> last_blocked_frames_
;
815 std::vector
<QuicPingFrame
> last_ping_frames_
;
816 std::vector
<QuicConnectionCloseFrame
> last_close_frames_
;
817 bool should_last_packet_instigate_acks_
;
819 // Track some peer state so we can do less bookkeeping
820 // Largest sequence sent by the peer which had an ack frame (latest ack info).
821 QuicPacketNumber largest_seen_packet_with_ack_
;
823 // Largest packet number sent by the peer which had a stop waiting frame.
824 QuicPacketNumber largest_seen_packet_with_stop_waiting_
;
826 // Collection of packets which were received before encryption was
827 // established, but which could not be decrypted. We buffer these on
828 // the assumption that they could not be processed because they were
829 // sent with the INITIAL encryption and the CHLO message was lost.
830 std::deque
<QuicEncryptedPacket
*> undecryptable_packets_
;
832 // Maximum number of undecryptable packets the connection will store.
833 size_t max_undecryptable_packets_
;
835 // When the version negotiation packet could not be sent because the socket
836 // was not writable, this is set to true.
837 bool pending_version_negotiation_packet_
;
839 // When packets could not be sent because the socket was not writable,
840 // they are added to this list. All corresponding frames are in
841 // unacked_packets_ if they are to be retransmitted.
842 QueuedPacketList queued_packets_
;
844 // Contains the connection close packet if the connection has been closed.
845 scoped_ptr
<QuicEncryptedPacket
> connection_close_packet_
;
847 // When true, the connection does not send a close packet on timeout.
848 bool silent_close_enabled_
;
850 FecGroupMap group_map_
;
852 QuicReceivedPacketManager received_packet_manager_
;
853 QuicSentEntropyManager sent_entropy_manager_
;
855 // Indicates whether an ack should be sent the next time we try to write.
857 // Indicates how many consecutive packets have arrived without sending an ack.
858 QuicPacketCount num_packets_received_since_last_ack_sent_
;
859 // Indicates how many consecutive times an ack has arrived which indicates
860 // the peer needs to stop waiting for some packets.
861 int stop_waiting_count_
;
863 // Indicates the retransmit alarm is going to be set by the
864 // ScopedRetransmitAlarmDelayer
865 bool delay_setting_retransmission_alarm_
;
866 // Indicates the retransmission alarm needs to be set.
867 bool pending_retransmission_alarm_
;
869 // An alarm that fires when an ACK should be sent to the peer.
870 scoped_ptr
<QuicAlarm
> ack_alarm_
;
871 // An alarm that fires when a packet needs to be retransmitted.
872 scoped_ptr
<QuicAlarm
> retransmission_alarm_
;
873 // An alarm that is scheduled when the SentPacketManager requires a delay
874 // before sending packets and fires when the packet may be sent.
875 scoped_ptr
<QuicAlarm
> send_alarm_
;
876 // An alarm that is scheduled when the connection can still write and there
877 // may be more data to send.
878 scoped_ptr
<QuicAlarm
> resume_writes_alarm_
;
879 // An alarm that fires when the connection may have timed out.
880 scoped_ptr
<QuicAlarm
> timeout_alarm_
;
881 // An alarm that fires when a ping should be sent.
882 scoped_ptr
<QuicAlarm
> ping_alarm_
;
883 // An alarm that fires when an MTU probe should be sent.
884 scoped_ptr
<QuicAlarm
> mtu_discovery_alarm_
;
886 // Neither visitor is owned by this class.
887 QuicConnectionVisitorInterface
* visitor_
;
888 QuicConnectionDebugVisitor
* debug_visitor_
;
890 QuicPacketGenerator packet_generator_
;
892 // An alarm that fires when an FEC packet should be sent.
893 scoped_ptr
<QuicAlarm
> fec_alarm_
;
895 // Network idle time before we kill of this connection.
896 QuicTime::Delta idle_network_timeout_
;
897 // Overall connection timeout.
898 QuicTime::Delta overall_connection_timeout_
;
900 // Statistics for this session.
901 QuicConnectionStats stats_
;
903 // The time that we got a packet for this connection.
904 // This is used for timeouts, and does not indicate the packet was processed.
905 QuicTime time_of_last_received_packet_
;
907 // The last time this connection began sending a new (non-retransmitted)
909 QuicTime time_of_last_sent_new_packet_
;
911 // packet number of the last sent packet. Packets are guaranteed to be sent
912 // in packet number order.
913 QuicPacketNumber packet_number_of_last_sent_packet_
;
915 // Sent packet manager which tracks the status of packets sent by this
916 // connection and contains the send and receive algorithms to determine when
918 QuicSentPacketManager sent_packet_manager_
;
920 // The state of connection in version negotiation finite state machine.
921 QuicVersionNegotiationState version_negotiation_state_
;
923 // Tracks if the connection was created by the server or the client.
924 Perspective perspective_
;
926 // True by default. False if we've received or sent an explicit connection
930 // Set to true if the UDP packet headers have a new IP address for the peer.
931 // If true, do not perform connection migration.
932 bool peer_ip_changed_
;
934 // Set to true if the UDP packet headers have a new port for the peer.
935 // If true, and the IP has not changed, then we can migrate the connection.
936 bool peer_port_changed_
;
938 // Set to true if the UDP packet headers are addressed to a different IP.
939 // We do not support connection migration when the self IP changed.
940 bool self_ip_changed_
;
942 // Set to true if the UDP packet headers are addressed to a different port.
943 // We do not support connection migration when the self port changed.
944 bool self_port_changed_
;
946 // Set to false if the connection should not send truncated connection IDs to
947 // the peer, even if the peer supports it.
948 bool can_truncate_connection_ids_
;
950 // If non-empty this contains the set of versions received in a
951 // version negotiation packet.
952 QuicVersionVector server_supported_versions_
;
954 // True if this is a secure QUIC connection.
957 // The size of the packet we are targeting while doing path MTU discovery.
958 QuicByteCount mtu_discovery_target_
;
960 // The number of MTU probes already sent.
961 size_t mtu_probe_count_
;
963 // The number of packets between MTU probes.
964 QuicPacketCount packets_between_mtu_probes_
;
966 // The packet number of the packet after which the next MTU probe will be
968 QuicPacketNumber next_mtu_probe_at_
;
970 // The size of the largest packet received from peer.
971 QuicByteCount largest_received_packet_size_
;
973 // Whether a GoAway has been sent.
976 // Whether a GoAway has been received.
977 bool goaway_received_
;
979 DISALLOW_COPY_AND_ASSIGN(QuicConnection
);
984 #endif // NET_QUIC_QUIC_CONNECTION_H_