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(QuicPacketSequenceNumber
),
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 to ask if the visitor wants to schedule write resumption as it both
132 // has pending data to write, and is able to write (e.g. based on flow control
134 // Writes may be pending because they were write-blocked, congestion-throttled
135 // or yielded to other connections.
136 virtual bool WillingAndAbleToWrite() const = 0;
138 // Called to ask if any handshake messages are pending in this visitor.
139 virtual bool HasPendingHandshake() const = 0;
141 // Called to ask if any streams are open in this visitor, excluding the
142 // reserved crypto and headers stream.
143 virtual bool HasOpenDynamicStreams() const = 0;
146 // Interface which gets callbacks from the QuicConnection at interesting
147 // points. Implementations must not mutate the state of the connection
148 // as a result of these callbacks.
149 class NET_EXPORT_PRIVATE QuicConnectionDebugVisitor
150 : public QuicPacketGenerator::DebugDelegate
,
151 public QuicSentPacketManager::DebugDelegate
{
153 ~QuicConnectionDebugVisitor() override
{}
155 // Called when a packet has been sent.
156 virtual void OnPacketSent(const SerializedPacket
& serialized_packet
,
157 QuicPacketSequenceNumber original_sequence_number
,
158 EncryptionLevel level
,
159 TransmissionType transmission_type
,
160 const QuicEncryptedPacket
& packet
,
161 QuicTime sent_time
) {}
163 // Called when a packet has been received, but before it is
164 // validated or parsed.
165 virtual void OnPacketReceived(const IPEndPoint
& self_address
,
166 const IPEndPoint
& peer_address
,
167 const QuicEncryptedPacket
& packet
) {}
169 // Called when a packet is received with a connection id that does not
170 // match the ID of this connection.
171 virtual void OnIncorrectConnectionId(
172 QuicConnectionId connection_id
) {}
174 // Called when an undecryptable packet has been received.
175 virtual void OnUndecryptablePacket() {}
177 // Called when a duplicate packet has been received.
178 virtual void OnDuplicatePacket(QuicPacketSequenceNumber sequence_number
) {}
180 // Called when the protocol version on the received packet doensn't match
181 // current protocol version of the connection.
182 virtual void OnProtocolVersionMismatch(QuicVersion version
) {}
184 // Called when the complete header of a packet has been parsed.
185 virtual void OnPacketHeader(const QuicPacketHeader
& header
) {}
187 // Called when a StreamFrame has been parsed.
188 virtual void OnStreamFrame(const QuicStreamFrame
& frame
) {}
190 // Called when a AckFrame has been parsed.
191 virtual void OnAckFrame(const QuicAckFrame
& frame
) {}
193 // Called when a StopWaitingFrame has been parsed.
194 virtual void OnStopWaitingFrame(const QuicStopWaitingFrame
& frame
) {}
196 // Called when a Ping has been parsed.
197 virtual void OnPingFrame(const QuicPingFrame
& frame
) {}
199 // Called when a GoAway has been parsed.
200 virtual void OnGoAwayFrame(const QuicGoAwayFrame
& frame
) {}
202 // Called when a RstStreamFrame has been parsed.
203 virtual void OnRstStreamFrame(const QuicRstStreamFrame
& frame
) {}
205 // Called when a ConnectionCloseFrame has been parsed.
206 virtual void OnConnectionCloseFrame(
207 const QuicConnectionCloseFrame
& frame
) {}
209 // Called when a WindowUpdate has been parsed.
210 virtual void OnWindowUpdateFrame(const QuicWindowUpdateFrame
& frame
) {}
212 // Called when a BlockedFrame has been parsed.
213 virtual void OnBlockedFrame(const QuicBlockedFrame
& frame
) {}
215 // Called when a public reset packet has been received.
216 virtual void OnPublicResetPacket(const QuicPublicResetPacket
& packet
) {}
218 // Called when a version negotiation packet has been received.
219 virtual void OnVersionNegotiationPacket(
220 const QuicVersionNegotiationPacket
& packet
) {}
222 // Called after a packet has been successfully parsed which results
223 // in the revival of a packet via FEC.
224 virtual void OnRevivedPacket(const QuicPacketHeader
& revived_header
,
225 base::StringPiece payload
) {}
227 // Called when the connection is closed.
228 virtual void OnConnectionClosed(QuicErrorCode error
, bool from_peer
) {}
230 // Called when the version negotiation is successful.
231 virtual void OnSuccessfulVersionNegotiation(const QuicVersion
& version
) {}
233 // Called when a CachedNetworkParameters is sent to the client.
234 virtual void OnSendConnectionState(
235 const CachedNetworkParameters
& cached_network_params
) {}
237 // Called when resuming previous connection state.
238 virtual void OnResumeConnectionState(
239 const CachedNetworkParameters
& cached_network_params
) {}
242 class NET_EXPORT_PRIVATE QuicConnectionHelperInterface
{
244 virtual ~QuicConnectionHelperInterface() {}
246 // Returns a QuicClock to be used for all time related functions.
247 virtual const QuicClock
* GetClock() const = 0;
249 // Returns a QuicRandom to be used for all random number related functions.
250 virtual QuicRandom
* GetRandomGenerator() = 0;
252 // Creates a new platform-specific alarm which will be configured to
253 // notify |delegate| when the alarm fires. Caller takes ownership
254 // of the new alarm, which will not yet be "set" to fire.
255 virtual QuicAlarm
* CreateAlarm(QuicAlarm::Delegate
* delegate
) = 0;
258 class NET_EXPORT_PRIVATE QuicConnection
259 : public QuicFramerVisitorInterface
,
260 public QuicBlockedWriterInterface
,
261 public QuicPacketGenerator::DelegateInterface
,
262 public QuicSentPacketManager::NetworkChangeVisitor
{
267 BUNDLE_PENDING_ACK
= 2,
270 class PacketWriterFactory
{
272 virtual ~PacketWriterFactory() {}
274 virtual QuicPacketWriter
* Create(QuicConnection
* connection
) const = 0;
277 // Constructs a new QuicConnection for |connection_id| and |address|. Invokes
278 // writer_factory->Create() to get a writer; |owns_writer| specifies whether
279 // the connection takes ownership of the returned writer. |helper| must
280 // outlive this connection.
281 QuicConnection(QuicConnectionId connection_id
,
283 QuicConnectionHelperInterface
* helper
,
284 const PacketWriterFactory
& writer_factory
,
286 Perspective perspective
,
288 const QuicVersionVector
& supported_versions
);
289 ~QuicConnection() override
;
291 // Sets connection parameters from the supplied |config|.
292 void SetFromConfig(const QuicConfig
& config
);
294 // Called by the session when sending connection state to the client.
295 virtual void OnSendConnectionState(
296 const CachedNetworkParameters
& cached_network_params
);
298 // Called by the Session when the client has provided CachedNetworkParameters.
299 virtual void ResumeConnectionState(
300 const CachedNetworkParameters
& cached_network_params
,
301 bool max_bandwidth_resumption
);
303 // Sets the number of active streams on the connection for congestion control.
304 void SetNumOpenStreams(size_t num_streams
);
306 // Send the data in |data| to the peer in as few packets as possible.
307 // Returns a pair with the number of bytes consumed from data, and a boolean
308 // indicating if the fin bit was consumed. This does not indicate the data
309 // has been sent on the wire: it may have been turned into a packet and queued
310 // if the socket was unexpectedly blocked. |fec_protection| indicates if
311 // data is to be FEC protected. Note that data that is sent immediately
312 // following MUST_FEC_PROTECT data may get protected by falling within the
314 // If |delegate| is provided, then it will be informed once ACKs have been
315 // received for all the packets written in this call.
316 // The |delegate| is not owned by the QuicConnection and must outlive it.
317 QuicConsumedData
SendStreamData(QuicStreamId id
,
318 const QuicIOVector
& iov
,
319 QuicStreamOffset offset
,
321 FecProtection fec_protection
,
322 QuicAckNotifier::DelegateInterface
* delegate
);
324 // Send a RST_STREAM frame to the peer.
325 virtual void SendRstStream(QuicStreamId id
,
326 QuicRstStreamErrorCode error
,
327 QuicStreamOffset bytes_written
);
329 // Send a BLOCKED frame to the peer.
330 virtual void SendBlocked(QuicStreamId id
);
332 // Send a WINDOW_UPDATE frame to the peer.
333 virtual void SendWindowUpdate(QuicStreamId id
,
334 QuicStreamOffset byte_offset
);
336 // Sends the connection close packet without affecting the state of the
337 // connection. This should only be called if the session is actively being
338 // destroyed: otherwise call SendConnectionCloseWithDetails instead.
339 virtual void SendConnectionClosePacket(QuicErrorCode error
,
340 const std::string
& details
);
342 // Sends a connection close frame to the peer, and closes the connection by
343 // calling CloseConnection(notifying the visitor as it does so).
344 virtual void SendConnectionClose(QuicErrorCode error
);
345 virtual void SendConnectionCloseWithDetails(QuicErrorCode error
,
346 const std::string
& details
);
347 // Notifies the visitor of the close and marks the connection as disconnected.
348 void CloseConnection(QuicErrorCode error
, bool from_peer
) override
;
349 virtual void SendGoAway(QuicErrorCode error
,
350 QuicStreamId last_good_stream_id
,
351 const std::string
& reason
);
353 // Returns statistics tracked for this connection.
354 const QuicConnectionStats
& GetStats();
356 // Processes an incoming UDP packet (consisting of a QuicEncryptedPacket) from
357 // the peer. If processing this packet permits a packet to be revived from
358 // its FEC group that packet will be revived and processed.
359 // In a client, the packet may be "stray" and have a different connection ID
360 // than that of this connection.
361 virtual void ProcessUdpPacket(const IPEndPoint
& self_address
,
362 const IPEndPoint
& peer_address
,
363 const QuicEncryptedPacket
& packet
);
365 // QuicBlockedWriterInterface
366 // Called when the underlying connection becomes writable to allow queued
368 void OnCanWrite() override
;
370 // Called when an error occurs while attempting to write a packet to the
372 void OnWriteError(int error_code
);
374 // If the socket is not blocked, writes queued packets.
375 void WriteIfNotBlocked();
377 // Set the packet writer.
378 void SetQuicPacketWriter(QuicPacketWriter
* writer
, bool owns_writer
) {
380 owns_writer_
= owns_writer
;
384 void SetSelfAddress(IPEndPoint address
) { self_address_
= address
; }
386 // The version of the protocol this connection is using.
387 QuicVersion
version() const { return framer_
.version(); }
389 // The versions of the protocol that this connection supports.
390 const QuicVersionVector
& supported_versions() const {
391 return framer_
.supported_versions();
394 // From QuicFramerVisitorInterface
395 void OnError(QuicFramer
* framer
) override
;
396 bool OnProtocolVersionMismatch(QuicVersion received_version
) override
;
397 void OnPacket() override
;
398 void OnPublicResetPacket(const QuicPublicResetPacket
& packet
) override
;
399 void OnVersionNegotiationPacket(
400 const QuicVersionNegotiationPacket
& packet
) override
;
401 void OnRevivedPacket() override
;
402 bool OnUnauthenticatedPublicHeader(
403 const QuicPacketPublicHeader
& header
) override
;
404 bool OnUnauthenticatedHeader(const QuicPacketHeader
& header
) override
;
405 void OnDecryptedPacket(EncryptionLevel level
) override
;
406 bool OnPacketHeader(const QuicPacketHeader
& header
) override
;
407 void OnFecProtectedPayload(base::StringPiece payload
) override
;
408 bool OnStreamFrame(const QuicStreamFrame
& frame
) override
;
409 bool OnAckFrame(const QuicAckFrame
& frame
) override
;
410 bool OnStopWaitingFrame(const QuicStopWaitingFrame
& frame
) override
;
411 bool OnPingFrame(const QuicPingFrame
& frame
) override
;
412 bool OnRstStreamFrame(const QuicRstStreamFrame
& frame
) override
;
413 bool OnConnectionCloseFrame(const QuicConnectionCloseFrame
& frame
) override
;
414 bool OnGoAwayFrame(const QuicGoAwayFrame
& frame
) override
;
415 bool OnWindowUpdateFrame(const QuicWindowUpdateFrame
& frame
) override
;
416 bool OnBlockedFrame(const QuicBlockedFrame
& frame
) override
;
417 void OnFecData(const QuicFecData
& fec
) override
;
418 void OnPacketComplete() override
;
420 // QuicPacketGenerator::DelegateInterface
421 bool ShouldGeneratePacket(HasRetransmittableData retransmittable
,
422 IsHandshake handshake
) override
;
423 void PopulateAckFrame(QuicAckFrame
* ack
) override
;
424 void PopulateStopWaitingFrame(QuicStopWaitingFrame
* stop_waiting
) override
;
425 void OnSerializedPacket(const SerializedPacket
& packet
) override
;
426 void OnResetFecGroup() override
;
428 // QuicSentPacketManager::NetworkChangeVisitor
429 void OnCongestionWindowChange() override
;
430 void OnRttChange() override
;
432 // Called by the crypto stream when the handshake completes. In the server's
433 // case this is when the SHLO has been ACKed. Clients call this on receipt of
435 void OnHandshakeComplete();
438 void set_visitor(QuicConnectionVisitorInterface
* visitor
) {
441 void set_debug_visitor(QuicConnectionDebugVisitor
* debug_visitor
) {
442 debug_visitor_
= debug_visitor
;
443 packet_generator_
.set_debug_delegate(debug_visitor
);
444 sent_packet_manager_
.set_debug_delegate(debug_visitor
);
446 const IPEndPoint
& self_address() const { return self_address_
; }
447 const IPEndPoint
& peer_address() const { return peer_address_
; }
448 QuicConnectionId
connection_id() const { return connection_id_
; }
449 const QuicClock
* clock() const { return clock_
; }
450 QuicRandom
* random_generator() const { return random_generator_
; }
451 QuicByteCount
max_packet_length() const;
452 void set_max_packet_length(QuicByteCount length
);
453 size_t mtu_probe_count() const { return mtu_probe_count_
; }
455 bool connected() const { return connected_
; }
457 // Must only be called on client connections.
458 const QuicVersionVector
& server_supported_versions() const {
459 DCHECK_EQ(Perspective::IS_CLIENT
, perspective_
);
460 return server_supported_versions_
;
463 size_t NumFecGroups() const { return group_map_
.size(); }
466 size_t NumQueuedPackets() const { return queued_packets_
.size(); }
468 QuicEncryptedPacket
* ReleaseConnectionClosePacket() {
469 return connection_close_packet_
.release();
472 // Returns true if the underlying UDP socket is writable, there is
473 // no queued data and the connection is not congestion-control
475 bool CanWriteStreamData();
477 // Returns true if the connection has queued packets or frames.
478 bool HasQueuedData() const;
480 // Sets the overall and idle state connection timeouts.
481 void SetNetworkTimeouts(QuicTime::Delta overall_timeout
,
482 QuicTime::Delta idle_timeout
);
484 // If the connection has timed out, this will close the connection.
485 // Otherwise, it will reschedule the timeout alarm.
486 void CheckForTimeout();
488 // Sends a ping, and resets the ping alarm.
491 // Sets up a packet with an QuicAckFrame and sends it out.
494 // Called when an RTO fires. Resets the retransmission alarm if there are
495 // remaining unacked packets.
496 void OnRetransmissionTimeout();
498 // Called when a data packet is sent. Starts an alarm if the data sent in
499 // |sequence_number| was FEC protected.
500 void MaybeSetFecAlarm(QuicPacketSequenceNumber sequence_number
);
502 // Retransmits all unacked packets with retransmittable frames if
503 // |retransmission_type| is ALL_UNACKED_PACKETS, otherwise retransmits only
504 // initially encrypted packets. Used when the negotiated protocol version is
505 // different from what was initially assumed and when the initial encryption
507 void RetransmitUnackedPackets(TransmissionType retransmission_type
);
509 // Calls |sent_packet_manager_|'s NeuterUnencryptedPackets. Used when the
510 // connection becomes forward secure and hasn't received acks for all packets.
511 void NeuterUnencryptedPackets();
513 // Changes the encrypter used for level |level| to |encrypter|. The function
514 // takes ownership of |encrypter|.
515 void SetEncrypter(EncryptionLevel level
, QuicEncrypter
* encrypter
);
517 // SetDefaultEncryptionLevel sets the encryption level that will be applied
519 void SetDefaultEncryptionLevel(EncryptionLevel level
);
521 // SetDecrypter sets the primary decrypter, replacing any that already exists,
522 // and takes ownership. If an alternative decrypter is in place then the
523 // function DCHECKs. This is intended for cases where one knows that future
524 // packets will be using the new decrypter and the previous decrypter is now
525 // obsolete. |level| indicates the encryption level of the new decrypter.
526 void SetDecrypter(EncryptionLevel level
, QuicDecrypter
* decrypter
);
528 // SetAlternativeDecrypter sets a decrypter that may be used to decrypt
529 // future packets and takes ownership of it. |level| indicates the encryption
530 // level of the decrypter. If |latch_once_used| is true, then the first time
531 // that the decrypter is successful it will replace the primary decrypter.
532 // Otherwise both decrypters will remain active and the primary decrypter
533 // will be the one last used.
534 void SetAlternativeDecrypter(EncryptionLevel level
,
535 QuicDecrypter
* decrypter
,
536 bool latch_once_used
);
538 const QuicDecrypter
* decrypter() const;
539 const QuicDecrypter
* alternative_decrypter() const;
541 Perspective
perspective() const { return perspective_
; }
543 // Allow easy overriding of truncated connection IDs.
544 void set_can_truncate_connection_ids(bool can
) {
545 can_truncate_connection_ids_
= can
;
548 // Returns the underlying sent packet manager.
549 const QuicSentPacketManager
& sent_packet_manager() const {
550 return sent_packet_manager_
;
553 bool CanWrite(HasRetransmittableData retransmittable
);
555 // Stores current batch state for connection, puts the connection
556 // into batch mode, and destruction restores the stored batch state.
557 // While the bundler is in scope, any generated frames are bundled
558 // as densely as possible into packets. In addition, this bundler
559 // can be configured to ensure that an ACK frame is included in the
560 // first packet created, if there's new ack information to be sent.
561 class ScopedPacketBundler
{
563 // In addition to all outgoing frames being bundled when the
564 // bundler is in scope, setting |include_ack| to true ensures that
565 // an ACK frame is opportunistically bundled with the first
567 ScopedPacketBundler(QuicConnection
* connection
, AckBundling send_ack
);
568 ~ScopedPacketBundler();
571 QuicConnection
* connection_
;
572 bool already_in_batch_mode_
;
575 // Delays setting the retransmission alarm until the scope is exited.
576 // When nested, only the outermost scheduler will set the alarm, and inner
577 // ones have no effect.
578 class NET_EXPORT_PRIVATE ScopedRetransmissionScheduler
{
580 explicit ScopedRetransmissionScheduler(QuicConnection
* connection
);
581 ~ScopedRetransmissionScheduler();
584 QuicConnection
* connection_
;
585 // Set to the connection's delay_setting_retransmission_alarm_ value in the
586 // constructor and when true, causes this class to do nothing.
587 const bool already_delayed_
;
590 QuicPacketSequenceNumber
sequence_number_of_last_sent_packet() const {
591 return sequence_number_of_last_sent_packet_
;
594 QuicPacketWriter
* writer() { return writer_
; }
595 const QuicPacketWriter
* writer() const { return writer_
; }
597 bool is_secure() const { return is_secure_
; }
599 // Sends an MTU discovery packet of size |target_mtu|. If the packet is
600 // acknowledged by the peer, the maximum packet size will be increased to
602 void SendMtuDiscoveryPacket(QuicByteCount target_mtu
);
604 // Sends an MTU discovery packet of size |mtu_discovery_target_| and updates
605 // the MTU discovery alarm.
608 // Return the name of the cipher of the primary decrypter of the framer.
609 const char* cipher_name() const { return framer_
.decrypter()->cipher_name(); }
610 // Return the id of the cipher of the primary decrypter of the framer.
611 uint32
cipher_id() const { return framer_
.decrypter()->cipher_id(); }
614 // Packets which have not been written to the wire.
615 // Owns the QuicPacket* packet.
616 struct QueuedPacket
{
617 QueuedPacket(SerializedPacket packet
,
618 EncryptionLevel level
);
619 QueuedPacket(SerializedPacket packet
,
620 EncryptionLevel level
,
621 TransmissionType transmission_type
,
622 QuicPacketSequenceNumber original_sequence_number
);
624 SerializedPacket serialized_packet
;
625 const EncryptionLevel encryption_level
;
626 TransmissionType transmission_type
;
627 // The packet's original sequence number if it is a retransmission.
628 // Otherwise it must be 0.
629 QuicPacketSequenceNumber original_sequence_number
;
632 // Do any work which logically would be done in OnPacket but can not be
633 // safely done until the packet is validated. Returns true if the packet
634 // can be handled, false otherwise.
635 virtual bool ProcessValidatedPacket();
637 // Send a packet to the peer, and takes ownership of the packet if the packet
638 // cannot be written immediately.
639 virtual void SendOrQueuePacket(QueuedPacket packet
);
641 QuicConnectionHelperInterface
* helper() { return helper_
; }
643 // Selects and updates the version of the protocol being used by selecting a
644 // version from |available_versions| which is also supported. Returns true if
645 // such a version exists, false otherwise.
646 bool SelectMutualVersion(const QuicVersionVector
& available_versions
);
648 bool peer_port_changed() const { return peer_port_changed_
; }
651 friend class test::QuicConnectionPeer
;
652 friend class test::PacketSavingConnection
;
654 typedef std::list
<QueuedPacket
> QueuedPacketList
;
655 typedef std::map
<QuicFecGroupNumber
, QuicFecGroup
*> FecGroupMap
;
657 // Writes the given packet to socket, encrypted with packet's
658 // encryption_level. Returns true on successful write, and false if the writer
659 // was blocked and the write needs to be tried again. Notifies the
660 // SentPacketManager when the write is successful and sets
661 // retransmittable frames to nullptr.
662 // Saves the connection close packet for later transmission, even if the
663 // writer is write blocked.
664 bool WritePacket(QueuedPacket
* packet
);
666 // Does the main work of WritePacket, but does not delete the packet or
667 // retransmittable frames upon success.
668 bool WritePacketInner(QueuedPacket
* packet
);
670 // Make sure an ack we got from our peer is sane.
671 bool ValidateAckFrame(const QuicAckFrame
& incoming_ack
);
673 // Make sure a stop waiting we got from our peer is sane.
674 bool ValidateStopWaitingFrame(const QuicStopWaitingFrame
& stop_waiting
);
676 // Sends a version negotiation packet to the peer.
677 void SendVersionNegotiationPacket();
679 // Clears any accumulated frames from the last received packet.
680 void ClearLastFrames();
682 // Closes the connection if the sent or received packet manager are tracking
683 // too many outstanding packets.
684 void MaybeCloseIfTooManyOutstandingPackets();
686 // Writes as many queued packets as possible. The connection must not be
687 // blocked when this is called.
688 void WriteQueuedPackets();
690 // Writes as many pending retransmissions as possible.
691 void WritePendingRetransmissions();
693 // Returns true if the packet should be discarded and not sent.
694 bool ShouldDiscardPacket(const QueuedPacket
& packet
);
696 // Queues |packet| in the hopes that it can be decrypted in the
697 // future, when a new key is installed.
698 void QueueUndecryptablePacket(const QuicEncryptedPacket
& packet
);
700 // Attempts to process any queued undecryptable packets.
701 void MaybeProcessUndecryptablePackets();
703 // If a packet can be revived from the current FEC group, then
704 // revive and process the packet.
705 void MaybeProcessRevivedPacket();
707 void ProcessAckFrame(const QuicAckFrame
& incoming_ack
);
709 void ProcessStopWaitingFrame(const QuicStopWaitingFrame
& stop_waiting
);
711 // Queues an ack or sets the ack alarm when an incoming packet arrives that
713 void MaybeQueueAck();
715 // Checks if the last packet should instigate an ack.
716 bool ShouldLastPacketInstigateAck() const;
718 // Checks if the peer is waiting for packets that have been given up on, and
719 // therefore an ack frame should be sent with a larger least_unacked.
720 void UpdateStopWaitingCount();
722 // Sends any packets which are a response to the last packet, including both
723 // acks and pending writes if an ack opened the congestion window.
724 void MaybeSendInResponseToPacket();
726 // Gets the least unacked sequence number, which is the next sequence number
727 // to be sent if there are no outstanding packets.
728 QuicPacketSequenceNumber
GetLeastUnacked() const;
730 // Get the FEC group associate with the last processed packet or nullptr, if
731 // the group has already been deleted.
732 QuicFecGroup
* GetFecGroup();
734 // Closes any FEC groups protecting packets before |sequence_number|.
735 void CloseFecGroupsBefore(QuicPacketSequenceNumber sequence_number
);
737 // Sets the timeout alarm to the appropriate value, if any.
738 void SetTimeoutAlarm();
740 // Sets the ping alarm to the appropriate value, if any.
743 // Sets the retransmission alarm based on SentPacketManager.
744 void SetRetransmissionAlarm();
746 // Sets the MTU discovery alarm if necessary.
747 void MaybeSetMtuAlarm();
749 // On arrival of a new packet, checks to see if the socket addresses have
750 // changed since the last packet we saw on this connection.
751 void CheckForAddressMigration(const IPEndPoint
& self_address
,
752 const IPEndPoint
& peer_address
);
754 HasRetransmittableData
IsRetransmittable(const QueuedPacket
& packet
);
755 bool IsConnectionClose(const QueuedPacket
& packet
);
758 QuicConnectionHelperInterface
* helper_
; // Not owned.
759 QuicPacketWriter
* writer_
; // Owned or not depending on |owns_writer_|.
761 // Encryption level for new packets. Should only be changed via
762 // SetDefaultEncryptionLevel().
763 EncryptionLevel encryption_level_
;
764 bool has_forward_secure_encrypter_
;
765 // The sequence number of the first packet which will be encrypted with the
766 // foward-secure encrypter, even if the peer has not started sending
767 // forward-secure packets.
768 QuicPacketSequenceNumber first_required_forward_secure_packet_
;
769 const QuicClock
* clock_
;
770 QuicRandom
* random_generator_
;
772 const QuicConnectionId connection_id_
;
773 // Address on the last successfully processed packet received from the
775 IPEndPoint self_address_
;
776 IPEndPoint peer_address_
;
778 // TODO(fayang): Use migrating_peer_address_ instead of migrating_peer_ip_
779 // and migrating_peer_port_ once FLAGS_quic_allow_ip_migration is deprecated.
780 // Used to store latest peer IP address for IP address migration.
781 IPAddressNumber migrating_peer_ip_
;
782 // Used to store latest peer port to possibly migrate to later.
783 uint16 migrating_peer_port_
;
785 // True if the last packet has gotten far enough in the framer to be
787 bool last_packet_decrypted_
;
788 bool last_packet_revived_
; // True if the last packet was revived from FEC.
789 QuicByteCount last_size_
; // Size of the last received packet.
790 EncryptionLevel last_decrypted_packet_level_
;
791 QuicPacketHeader last_header_
;
792 std::vector
<QuicStreamFrame
> last_stream_frames_
;
793 std::vector
<QuicAckFrame
> last_ack_frames_
;
794 std::vector
<QuicStopWaitingFrame
> last_stop_waiting_frames_
;
795 std::vector
<QuicRstStreamFrame
> last_rst_frames_
;
796 std::vector
<QuicGoAwayFrame
> last_goaway_frames_
;
797 std::vector
<QuicWindowUpdateFrame
> last_window_update_frames_
;
798 std::vector
<QuicBlockedFrame
> last_blocked_frames_
;
799 std::vector
<QuicPingFrame
> last_ping_frames_
;
800 std::vector
<QuicConnectionCloseFrame
> last_close_frames_
;
801 bool should_last_packet_instigate_acks_
;
803 // Track some peer state so we can do less bookkeeping
804 // Largest sequence sent by the peer which had an ack frame (latest ack info).
805 QuicPacketSequenceNumber largest_seen_packet_with_ack_
;
807 // Largest sequence number sent by the peer which had a stop waiting frame.
808 QuicPacketSequenceNumber largest_seen_packet_with_stop_waiting_
;
810 // Collection of packets which were received before encryption was
811 // established, but which could not be decrypted. We buffer these on
812 // the assumption that they could not be processed because they were
813 // sent with the INITIAL encryption and the CHLO message was lost.
814 std::deque
<QuicEncryptedPacket
*> undecryptable_packets_
;
816 // Maximum number of undecryptable packets the connection will store.
817 size_t max_undecryptable_packets_
;
819 // When the version negotiation packet could not be sent because the socket
820 // was not writable, this is set to true.
821 bool pending_version_negotiation_packet_
;
823 // When packets could not be sent because the socket was not writable,
824 // they are added to this list. All corresponding frames are in
825 // unacked_packets_ if they are to be retransmitted.
826 QueuedPacketList queued_packets_
;
828 // Contains the connection close packet if the connection has been closed.
829 scoped_ptr
<QuicEncryptedPacket
> connection_close_packet_
;
831 // When true, the connection does not send a close packet on timeout.
832 bool silent_close_enabled_
;
834 FecGroupMap group_map_
;
836 QuicReceivedPacketManager received_packet_manager_
;
837 QuicSentEntropyManager sent_entropy_manager_
;
839 // Indicates whether an ack should be sent the next time we try to write.
841 // Indicates how many consecutive packets have arrived without sending an ack.
842 QuicPacketCount num_packets_received_since_last_ack_sent_
;
843 // Indicates how many consecutive times an ack has arrived which indicates
844 // the peer needs to stop waiting for some packets.
845 int stop_waiting_count_
;
847 // Indicates the retransmit alarm is going to be set by the
848 // ScopedRetransmitAlarmDelayer
849 bool delay_setting_retransmission_alarm_
;
850 // Indicates the retransmission alarm needs to be set.
851 bool pending_retransmission_alarm_
;
853 // An alarm that fires when an ACK should be sent to the peer.
854 scoped_ptr
<QuicAlarm
> ack_alarm_
;
855 // An alarm that fires when a packet needs to be retransmitted.
856 scoped_ptr
<QuicAlarm
> retransmission_alarm_
;
857 // An alarm that is scheduled when the SentPacketManager requires a delay
858 // before sending packets and fires when the packet may be sent.
859 scoped_ptr
<QuicAlarm
> send_alarm_
;
860 // An alarm that is scheduled when the connection can still write and there
861 // may be more data to send.
862 scoped_ptr
<QuicAlarm
> resume_writes_alarm_
;
863 // An alarm that fires when the connection may have timed out.
864 scoped_ptr
<QuicAlarm
> timeout_alarm_
;
865 // An alarm that fires when a ping should be sent.
866 scoped_ptr
<QuicAlarm
> ping_alarm_
;
867 // An alarm that fires when an MTU probe should be sent.
868 scoped_ptr
<QuicAlarm
> mtu_discovery_alarm_
;
870 // Neither visitor is owned by this class.
871 QuicConnectionVisitorInterface
* visitor_
;
872 QuicConnectionDebugVisitor
* debug_visitor_
;
874 QuicPacketGenerator packet_generator_
;
876 // An alarm that fires when an FEC packet should be sent.
877 scoped_ptr
<QuicAlarm
> fec_alarm_
;
879 // Network idle time before we kill of this connection.
880 QuicTime::Delta idle_network_timeout_
;
881 // Overall connection timeout.
882 QuicTime::Delta overall_connection_timeout_
;
884 // Statistics for this session.
885 QuicConnectionStats stats_
;
887 // The time that we got a packet for this connection.
888 // This is used for timeouts, and does not indicate the packet was processed.
889 QuicTime time_of_last_received_packet_
;
891 // The last time this connection began sending a new (non-retransmitted)
893 QuicTime time_of_last_sent_new_packet_
;
895 // Sequence number of the last sent packet. Packets are guaranteed to be sent
896 // in sequence number order.
897 QuicPacketSequenceNumber sequence_number_of_last_sent_packet_
;
899 // Sent packet manager which tracks the status of packets sent by this
900 // connection and contains the send and receive algorithms to determine when
902 QuicSentPacketManager sent_packet_manager_
;
904 // The state of connection in version negotiation finite state machine.
905 QuicVersionNegotiationState version_negotiation_state_
;
907 // Tracks if the connection was created by the server or the client.
908 Perspective perspective_
;
910 // True by default. False if we've received or sent an explicit connection
914 // Set to true if the UDP packet headers have a new IP address for the peer.
915 // If true, do not perform connection migration.
916 bool peer_ip_changed_
;
918 // Set to true if the UDP packet headers have a new port for the peer.
919 // If true, and the IP has not changed, then we can migrate the connection.
920 bool peer_port_changed_
;
922 // Set to true if the UDP packet headers are addressed to a different IP.
923 // We do not support connection migration when the self IP changed.
924 bool self_ip_changed_
;
926 // Set to true if the UDP packet headers are addressed to a different port.
927 // We do not support connection migration when the self port changed.
928 bool self_port_changed_
;
930 // Set to false if the connection should not send truncated connection IDs to
931 // the peer, even if the peer supports it.
932 bool can_truncate_connection_ids_
;
934 // If non-empty this contains the set of versions received in a
935 // version negotiation packet.
936 QuicVersionVector server_supported_versions_
;
938 // True if this is a secure QUIC connection.
941 // The size of the packet we are targeting while doing path MTU discovery.
942 QuicByteCount mtu_discovery_target_
;
944 // The number of MTU probes already sent.
945 size_t mtu_probe_count_
;
947 // The number of packets between MTU probes.
948 QuicPacketCount packets_between_mtu_probes_
;
950 // The sequence number of the packet after which the next MTU probe will be
952 QuicPacketSequenceNumber next_mtu_probe_at_
;
954 // The size of the largest packet received from peer.
955 QuicByteCount largest_received_packet_size_
;
957 DISALLOW_COPY_AND_ASSIGN(QuicConnection
);
962 #endif // NET_QUIC_QUIC_CONNECTION_H_