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
) {}
247 // Called when RTT may have changed, including when an RTT is read from
249 virtual void OnRttChanged(QuicTime::Delta rtt
) const {}
252 class NET_EXPORT_PRIVATE QuicConnectionHelperInterface
{
254 virtual ~QuicConnectionHelperInterface() {}
256 // Returns a QuicClock to be used for all time related functions.
257 virtual const QuicClock
* GetClock() const = 0;
259 // Returns a QuicRandom to be used for all random number related functions.
260 virtual QuicRandom
* GetRandomGenerator() = 0;
262 // Creates a new platform-specific alarm which will be configured to
263 // notify |delegate| when the alarm fires. Caller takes ownership
264 // of the new alarm, which will not yet be "set" to fire.
265 virtual QuicAlarm
* CreateAlarm(QuicAlarm::Delegate
* delegate
) = 0;
268 class NET_EXPORT_PRIVATE QuicConnection
269 : public QuicFramerVisitorInterface
,
270 public QuicBlockedWriterInterface
,
271 public QuicPacketGenerator::DelegateInterface
,
272 public QuicSentPacketManager::NetworkChangeVisitor
{
277 BUNDLE_PENDING_ACK
= 2,
280 class PacketWriterFactory
{
282 virtual ~PacketWriterFactory() {}
284 virtual QuicPacketWriter
* Create(QuicConnection
* connection
) const = 0;
287 // Constructs a new QuicConnection for |connection_id| and |address|. Invokes
288 // writer_factory->Create() to get a writer; |owns_writer| specifies whether
289 // the connection takes ownership of the returned writer. |helper| must
290 // outlive this connection.
291 QuicConnection(QuicConnectionId connection_id
,
293 QuicConnectionHelperInterface
* helper
,
294 const PacketWriterFactory
& writer_factory
,
296 Perspective perspective
,
298 const QuicVersionVector
& supported_versions
);
299 ~QuicConnection() override
;
301 // Sets connection parameters from the supplied |config|.
302 void SetFromConfig(const QuicConfig
& config
);
304 // Called by the session when sending connection state to the client.
305 virtual void OnSendConnectionState(
306 const CachedNetworkParameters
& cached_network_params
);
308 // Called by the Session when the client has provided CachedNetworkParameters.
309 virtual void ResumeConnectionState(
310 const CachedNetworkParameters
& cached_network_params
,
311 bool max_bandwidth_resumption
);
313 // Sets the number of active streams on the connection for congestion control.
314 void SetNumOpenStreams(size_t num_streams
);
316 // Send the data in |data| to the peer in as few packets as possible.
317 // Returns a pair with the number of bytes consumed from data, and a boolean
318 // indicating if the fin bit was consumed. This does not indicate the data
319 // has been sent on the wire: it may have been turned into a packet and queued
320 // if the socket was unexpectedly blocked. |fec_protection| indicates if
321 // data is to be FEC protected. Note that data that is sent immediately
322 // following MUST_FEC_PROTECT data may get protected by falling within the
324 // If |delegate| is provided, then it will be informed once ACKs have been
325 // received for all the packets written in this call.
326 // The |delegate| is not owned by the QuicConnection and must outlive it.
327 QuicConsumedData
SendStreamData(QuicStreamId id
,
328 const QuicIOVector
& iov
,
329 QuicStreamOffset offset
,
331 FecProtection fec_protection
,
332 QuicAckNotifier::DelegateInterface
* delegate
);
334 // Send a RST_STREAM frame to the peer.
335 virtual void SendRstStream(QuicStreamId id
,
336 QuicRstStreamErrorCode error
,
337 QuicStreamOffset bytes_written
);
339 // Send a BLOCKED frame to the peer.
340 virtual void SendBlocked(QuicStreamId id
);
342 // Send a WINDOW_UPDATE frame to the peer.
343 virtual void SendWindowUpdate(QuicStreamId id
,
344 QuicStreamOffset byte_offset
);
346 // Sends the connection close packet without affecting the state of the
347 // connection. This should only be called if the session is actively being
348 // destroyed: otherwise call SendConnectionCloseWithDetails instead.
349 virtual void SendConnectionClosePacket(QuicErrorCode error
,
350 const std::string
& details
);
352 // Sends a connection close frame to the peer, and closes the connection by
353 // calling CloseConnection(notifying the visitor as it does so).
354 virtual void SendConnectionClose(QuicErrorCode error
);
355 virtual void SendConnectionCloseWithDetails(QuicErrorCode error
,
356 const std::string
& details
);
357 // Notifies the visitor of the close and marks the connection as disconnected.
358 void CloseConnection(QuicErrorCode error
, bool from_peer
) override
;
360 // Sends a GOAWAY frame. Does nothing if a GOAWAY frame has already been sent.
361 virtual void SendGoAway(QuicErrorCode error
,
362 QuicStreamId last_good_stream_id
,
363 const std::string
& reason
);
365 // Returns statistics tracked for this connection.
366 const QuicConnectionStats
& GetStats();
368 // Processes an incoming UDP packet (consisting of a QuicEncryptedPacket) from
369 // the peer. If processing this packet permits a packet to be revived from
370 // its FEC group that packet will be revived and processed.
371 // In a client, the packet may be "stray" and have a different connection ID
372 // than that of this connection.
373 virtual void ProcessUdpPacket(const IPEndPoint
& self_address
,
374 const IPEndPoint
& peer_address
,
375 const QuicEncryptedPacket
& packet
);
377 // QuicBlockedWriterInterface
378 // Called when the underlying connection becomes writable to allow queued
380 void OnCanWrite() override
;
382 // Called when an error occurs while attempting to write a packet to the
384 void OnWriteError(int error_code
);
386 // If the socket is not blocked, writes queued packets.
387 void WriteIfNotBlocked();
389 // Set the packet writer.
390 void SetQuicPacketWriter(QuicPacketWriter
* writer
, bool owns_writer
) {
392 owns_writer_
= owns_writer
;
396 void SetSelfAddress(IPEndPoint address
) { self_address_
= address
; }
398 // The version of the protocol this connection is using.
399 QuicVersion
version() const { return framer_
.version(); }
401 // The versions of the protocol that this connection supports.
402 const QuicVersionVector
& supported_versions() const {
403 return framer_
.supported_versions();
406 // From QuicFramerVisitorInterface
407 void OnError(QuicFramer
* framer
) override
;
408 bool OnProtocolVersionMismatch(QuicVersion received_version
) override
;
409 void OnPacket() override
;
410 void OnPublicResetPacket(const QuicPublicResetPacket
& packet
) override
;
411 void OnVersionNegotiationPacket(
412 const QuicVersionNegotiationPacket
& packet
) override
;
413 void OnRevivedPacket() override
;
414 bool OnUnauthenticatedPublicHeader(
415 const QuicPacketPublicHeader
& header
) override
;
416 bool OnUnauthenticatedHeader(const QuicPacketHeader
& header
) override
;
417 void OnDecryptedPacket(EncryptionLevel level
) override
;
418 bool OnPacketHeader(const QuicPacketHeader
& header
) override
;
419 void OnFecProtectedPayload(base::StringPiece payload
) override
;
420 bool OnStreamFrame(const QuicStreamFrame
& frame
) override
;
421 bool OnAckFrame(const QuicAckFrame
& frame
) override
;
422 bool OnStopWaitingFrame(const QuicStopWaitingFrame
& frame
) override
;
423 bool OnPingFrame(const QuicPingFrame
& frame
) override
;
424 bool OnRstStreamFrame(const QuicRstStreamFrame
& frame
) override
;
425 bool OnConnectionCloseFrame(const QuicConnectionCloseFrame
& frame
) override
;
426 bool OnGoAwayFrame(const QuicGoAwayFrame
& frame
) override
;
427 bool OnWindowUpdateFrame(const QuicWindowUpdateFrame
& frame
) override
;
428 bool OnBlockedFrame(const QuicBlockedFrame
& frame
) override
;
429 void OnFecData(const QuicFecData
& fec
) override
;
430 void OnPacketComplete() override
;
432 // QuicPacketGenerator::DelegateInterface
433 bool ShouldGeneratePacket(HasRetransmittableData retransmittable
,
434 IsHandshake handshake
) override
;
435 void PopulateAckFrame(QuicAckFrame
* ack
) override
;
436 void PopulateStopWaitingFrame(QuicStopWaitingFrame
* stop_waiting
) override
;
437 void OnSerializedPacket(const SerializedPacket
& packet
) override
;
438 void OnResetFecGroup() override
;
440 // QuicSentPacketManager::NetworkChangeVisitor
441 void OnCongestionWindowChange() override
;
442 void OnRttChange() override
;
444 // Called by the crypto stream when the handshake completes. In the server's
445 // case this is when the SHLO has been ACKed. Clients call this on receipt of
447 void OnHandshakeComplete();
450 void set_visitor(QuicConnectionVisitorInterface
* visitor
) {
453 void set_debug_visitor(QuicConnectionDebugVisitor
* debug_visitor
) {
454 debug_visitor_
= debug_visitor
;
455 packet_generator_
.set_debug_delegate(debug_visitor
);
456 sent_packet_manager_
.set_debug_delegate(debug_visitor
);
458 const IPEndPoint
& self_address() const { return self_address_
; }
459 const IPEndPoint
& peer_address() const { return peer_address_
; }
460 QuicConnectionId
connection_id() const { return connection_id_
; }
461 const QuicClock
* clock() const { return clock_
; }
462 QuicRandom
* random_generator() const { return random_generator_
; }
463 QuicByteCount
max_packet_length() const;
464 void SetMaxPacketLength(QuicByteCount length
);
466 size_t mtu_probe_count() const { return mtu_probe_count_
; }
468 bool connected() const { return connected_
; }
470 bool goaway_sent() const { return goaway_sent_
; }
472 bool goaway_received() const { return goaway_received_
; }
474 // Must only be called on client connections.
475 const QuicVersionVector
& server_supported_versions() const {
476 DCHECK_EQ(Perspective::IS_CLIENT
, perspective_
);
477 return server_supported_versions_
;
480 size_t NumFecGroups() const { return group_map_
.size(); }
483 size_t NumQueuedPackets() const { return queued_packets_
.size(); }
485 QuicEncryptedPacket
* ReleaseConnectionClosePacket() {
486 return connection_close_packet_
.release();
489 // Returns true if the underlying UDP socket is writable, there is
490 // no queued data and the connection is not congestion-control
492 bool CanWriteStreamData();
494 // Returns true if the connection has queued packets or frames.
495 bool HasQueuedData() const;
497 // Sets the overall and idle state connection timeouts.
498 void SetNetworkTimeouts(QuicTime::Delta overall_timeout
,
499 QuicTime::Delta idle_timeout
);
501 // If the connection has timed out, this will close the connection.
502 // Otherwise, it will reschedule the timeout alarm.
503 void CheckForTimeout();
505 // Sends a ping, and resets the ping alarm.
508 // Sets up a packet with an QuicAckFrame and sends it out.
511 // Called when an RTO fires. Resets the retransmission alarm if there are
512 // remaining unacked packets.
513 void OnRetransmissionTimeout();
515 // Called when a data packet is sent. Starts an alarm if the data sent in
516 // |packet_number| was FEC protected.
517 void MaybeSetFecAlarm(QuicPacketNumber packet_number
);
519 // Retransmits all unacked packets with retransmittable frames if
520 // |retransmission_type| is ALL_UNACKED_PACKETS, otherwise retransmits only
521 // initially encrypted packets. Used when the negotiated protocol version is
522 // different from what was initially assumed and when the initial encryption
524 void RetransmitUnackedPackets(TransmissionType retransmission_type
);
526 // Calls |sent_packet_manager_|'s NeuterUnencryptedPackets. Used when the
527 // connection becomes forward secure and hasn't received acks for all packets.
528 void NeuterUnencryptedPackets();
530 // Changes the encrypter used for level |level| to |encrypter|. The function
531 // takes ownership of |encrypter|.
532 void SetEncrypter(EncryptionLevel level
, QuicEncrypter
* encrypter
);
534 // SetDefaultEncryptionLevel sets the encryption level that will be applied
536 void SetDefaultEncryptionLevel(EncryptionLevel level
);
538 // SetDecrypter sets the primary decrypter, replacing any that already exists,
539 // and takes ownership. If an alternative decrypter is in place then the
540 // function DCHECKs. This is intended for cases where one knows that future
541 // packets will be using the new decrypter and the previous decrypter is now
542 // obsolete. |level| indicates the encryption level of the new decrypter.
543 void SetDecrypter(EncryptionLevel level
, QuicDecrypter
* decrypter
);
545 // SetAlternativeDecrypter sets a decrypter that may be used to decrypt
546 // future packets and takes ownership of it. |level| indicates the encryption
547 // level of the decrypter. If |latch_once_used| is true, then the first time
548 // that the decrypter is successful it will replace the primary decrypter.
549 // Otherwise both decrypters will remain active and the primary decrypter
550 // will be the one last used.
551 void SetAlternativeDecrypter(EncryptionLevel level
,
552 QuicDecrypter
* decrypter
,
553 bool latch_once_used
);
555 const QuicDecrypter
* decrypter() const;
556 const QuicDecrypter
* alternative_decrypter() const;
558 Perspective
perspective() const { return perspective_
; }
560 // Allow easy overriding of truncated connection IDs.
561 void set_can_truncate_connection_ids(bool can
) {
562 can_truncate_connection_ids_
= can
;
565 // Returns the underlying sent packet manager.
566 const QuicSentPacketManager
& sent_packet_manager() const {
567 return sent_packet_manager_
;
570 bool CanWrite(HasRetransmittableData retransmittable
);
572 // Stores current batch state for connection, puts the connection
573 // into batch mode, and destruction restores the stored batch state.
574 // While the bundler is in scope, any generated frames are bundled
575 // as densely as possible into packets. In addition, this bundler
576 // can be configured to ensure that an ACK frame is included in the
577 // first packet created, if there's new ack information to be sent.
578 class ScopedPacketBundler
{
580 // In addition to all outgoing frames being bundled when the
581 // bundler is in scope, setting |include_ack| to true ensures that
582 // an ACK frame is opportunistically bundled with the first
584 ScopedPacketBundler(QuicConnection
* connection
, AckBundling send_ack
);
585 ~ScopedPacketBundler();
588 QuicConnection
* connection_
;
589 bool already_in_batch_mode_
;
592 // Delays setting the retransmission alarm until the scope is exited.
593 // When nested, only the outermost scheduler will set the alarm, and inner
594 // ones have no effect.
595 class NET_EXPORT_PRIVATE ScopedRetransmissionScheduler
{
597 explicit ScopedRetransmissionScheduler(QuicConnection
* connection
);
598 ~ScopedRetransmissionScheduler();
601 QuicConnection
* connection_
;
602 // Set to the connection's delay_setting_retransmission_alarm_ value in the
603 // constructor and when true, causes this class to do nothing.
604 const bool already_delayed_
;
607 QuicPacketNumber
packet_number_of_last_sent_packet() const {
608 return packet_number_of_last_sent_packet_
;
611 QuicPacketWriter
* writer() { return writer_
; }
612 const QuicPacketWriter
* writer() const { return writer_
; }
614 bool is_secure() const { return is_secure_
; }
616 // Sends an MTU discovery packet of size |target_mtu|. If the packet is
617 // acknowledged by the peer, the maximum packet size will be increased to
619 void SendMtuDiscoveryPacket(QuicByteCount target_mtu
);
621 // Sends an MTU discovery packet of size |mtu_discovery_target_| and updates
622 // the MTU discovery alarm.
625 // Return the name of the cipher of the primary decrypter of the framer.
626 const char* cipher_name() const { return framer_
.decrypter()->cipher_name(); }
627 // Return the id of the cipher of the primary decrypter of the framer.
628 uint32
cipher_id() const { return framer_
.decrypter()->cipher_id(); }
631 // Packets which have not been written to the wire.
632 // Owns the QuicPacket* packet.
633 struct QueuedPacket
{
634 QueuedPacket(SerializedPacket packet
,
635 EncryptionLevel level
);
636 QueuedPacket(SerializedPacket packet
,
637 EncryptionLevel level
,
638 TransmissionType transmission_type
,
639 QuicPacketNumber original_packet_number
);
641 SerializedPacket serialized_packet
;
642 const EncryptionLevel encryption_level
;
643 TransmissionType transmission_type
;
644 // The packet's original packet number if it is a retransmission.
645 // Otherwise it must be 0.
646 QuicPacketNumber original_packet_number
;
649 // Do any work which logically would be done in OnPacket but can not be
650 // safely done until the packet is validated. Returns true if the packet
651 // can be handled, false otherwise.
652 virtual bool ProcessValidatedPacket();
654 // Send a packet to the peer, and takes ownership of the packet if the packet
655 // cannot be written immediately.
656 virtual void SendOrQueuePacket(QueuedPacket packet
);
658 QuicConnectionHelperInterface
* helper() { return helper_
; }
660 // Selects and updates the version of the protocol being used by selecting a
661 // version from |available_versions| which is also supported. Returns true if
662 // such a version exists, false otherwise.
663 bool SelectMutualVersion(const QuicVersionVector
& available_versions
);
665 bool peer_ip_changed() const { return peer_ip_changed_
; }
667 bool peer_port_changed() const { return peer_port_changed_
; }
670 friend class test::QuicConnectionPeer
;
671 friend class test::PacketSavingConnection
;
673 typedef std::list
<QueuedPacket
> QueuedPacketList
;
674 typedef std::map
<QuicFecGroupNumber
, QuicFecGroup
*> FecGroupMap
;
676 // Writes the given packet to socket, encrypted with packet's
677 // encryption_level. Returns true on successful write, and false if the writer
678 // was blocked and the write needs to be tried again. Notifies the
679 // SentPacketManager when the write is successful and sets
680 // retransmittable frames to nullptr.
681 // Saves the connection close packet for later transmission, even if the
682 // writer is write blocked.
683 bool WritePacket(QueuedPacket
* packet
);
685 // Does the main work of WritePacket, but does not delete the packet or
686 // retransmittable frames upon success.
687 bool WritePacketInner(QueuedPacket
* packet
);
689 // Make sure an ack we got from our peer is sane.
690 bool ValidateAckFrame(const QuicAckFrame
& incoming_ack
);
692 // Make sure a stop waiting we got from our peer is sane.
693 bool ValidateStopWaitingFrame(const QuicStopWaitingFrame
& stop_waiting
);
695 // Sends a version negotiation packet to the peer.
696 void SendVersionNegotiationPacket();
698 // Clears any accumulated frames from the last received packet.
699 void ClearLastFrames();
701 // Deletes and clears any QueuedPackets.
702 void ClearQueuedPackets();
704 // Closes the connection if the sent or received packet manager are tracking
705 // too many outstanding packets.
706 void MaybeCloseIfTooManyOutstandingPackets();
708 // Writes as many queued packets as possible. The connection must not be
709 // blocked when this is called.
710 void WriteQueuedPackets();
712 // Writes as many pending retransmissions as possible.
713 void WritePendingRetransmissions();
715 // Returns true if the packet should be discarded and not sent.
716 bool ShouldDiscardPacket(const QueuedPacket
& packet
);
718 // Queues |packet| in the hopes that it can be decrypted in the
719 // future, when a new key is installed.
720 void QueueUndecryptablePacket(const QuicEncryptedPacket
& packet
);
722 // Attempts to process any queued undecryptable packets.
723 void MaybeProcessUndecryptablePackets();
725 // If a packet can be revived from the current FEC group, then
726 // revive and process the packet.
727 void MaybeProcessRevivedPacket();
729 void ProcessAckFrame(const QuicAckFrame
& incoming_ack
);
731 void ProcessStopWaitingFrame(const QuicStopWaitingFrame
& stop_waiting
);
733 // Queues an ack or sets the ack alarm when an incoming packet arrives that
735 void MaybeQueueAck();
737 // Checks if the last packet should instigate an ack.
738 bool ShouldLastPacketInstigateAck() const;
740 // Sends any packets which are a response to the last packet, including both
741 // acks and pending writes if an ack opened the congestion window.
742 void MaybeSendInResponseToPacket();
744 // Gets the least unacked packet number, which is the next packet number
745 // to be sent if there are no outstanding packets.
746 QuicPacketNumber
GetLeastUnacked() const;
748 // Get the FEC group associate with the last processed packet or nullptr, if
749 // the group has already been deleted.
750 QuicFecGroup
* GetFecGroup();
752 // Closes any FEC groups protecting packets before |packet_number|.
753 void CloseFecGroupsBefore(QuicPacketNumber packet_number
);
755 // Sets the timeout alarm to the appropriate value, if any.
756 void SetTimeoutAlarm();
758 // Sets the ping alarm to the appropriate value, if any.
761 // Sets the retransmission alarm based on SentPacketManager.
762 void SetRetransmissionAlarm();
764 // Sets the MTU discovery alarm if necessary.
765 void MaybeSetMtuAlarm();
767 // On arrival of a new packet, checks to see if the socket addresses have
768 // changed since the last packet we saw on this connection.
769 void CheckForAddressMigration(const IPEndPoint
& self_address
,
770 const IPEndPoint
& peer_address
);
772 HasRetransmittableData
IsRetransmittable(const QueuedPacket
& packet
);
773 bool IsConnectionClose(const QueuedPacket
& packet
);
775 // Set the size of the packet we are targeting while doing path MTU discovery.
776 void SetMtuDiscoveryTarget(QuicByteCount target
);
778 // Validates the potential maximum packet size, and reduces it if it exceeds
779 // the largest supported by the protocol or the packet writer.
780 QuicByteCount
LimitMaxPacketSize(QuicByteCount suggested_max_packet_size
);
783 QuicConnectionHelperInterface
* helper_
; // Not owned.
784 QuicPacketWriter
* writer_
; // Owned or not depending on |owns_writer_|.
786 // Encryption level for new packets. Should only be changed via
787 // SetDefaultEncryptionLevel().
788 EncryptionLevel encryption_level_
;
789 bool has_forward_secure_encrypter_
;
790 // The packet number of the first packet which will be encrypted with the
791 // foward-secure encrypter, even if the peer has not started sending
792 // forward-secure packets.
793 QuicPacketNumber first_required_forward_secure_packet_
;
794 const QuicClock
* clock_
;
795 QuicRandom
* random_generator_
;
797 const QuicConnectionId connection_id_
;
798 // Address on the last successfully processed packet received from the
800 IPEndPoint self_address_
;
801 IPEndPoint peer_address_
;
803 // Used to store latest peer IP address for IP address migration.
804 IPAddressNumber migrating_peer_ip_
;
805 // Used to store latest peer port to possibly migrate to later.
806 uint16 migrating_peer_port_
;
808 // True if the last packet has gotten far enough in the framer to be
810 bool last_packet_decrypted_
;
811 bool last_packet_revived_
; // True if the last packet was revived from FEC.
812 QuicByteCount last_size_
; // Size of the last received packet.
813 EncryptionLevel last_decrypted_packet_level_
;
814 QuicPacketHeader last_header_
;
815 QuicStopWaitingFrame last_stop_waiting_frame_
;
816 bool should_last_packet_instigate_acks_
;
818 // Track some peer state so we can do less bookkeeping
819 // Largest sequence sent by the peer which had an ack frame (latest ack info).
820 QuicPacketNumber largest_seen_packet_with_ack_
;
822 // Largest packet number sent by the peer which had a stop waiting frame.
823 QuicPacketNumber largest_seen_packet_with_stop_waiting_
;
825 // Collection of packets which were received before encryption was
826 // established, but which could not be decrypted. We buffer these on
827 // the assumption that they could not be processed because they were
828 // sent with the INITIAL encryption and the CHLO message was lost.
829 std::deque
<QuicEncryptedPacket
*> undecryptable_packets_
;
831 // Maximum number of undecryptable packets the connection will store.
832 size_t max_undecryptable_packets_
;
834 // When the version negotiation packet could not be sent because the socket
835 // was not writable, this is set to true.
836 bool pending_version_negotiation_packet_
;
838 // When packets could not be sent because the socket was not writable,
839 // they are added to this list. All corresponding frames are in
840 // unacked_packets_ if they are to be retransmitted.
841 QueuedPacketList queued_packets_
;
843 // Contains the connection close packet if the connection has been closed.
844 scoped_ptr
<QuicEncryptedPacket
> connection_close_packet_
;
846 // When true, the connection does not send a close packet on timeout.
847 bool silent_close_enabled_
;
849 FecGroupMap group_map_
;
851 QuicReceivedPacketManager received_packet_manager_
;
852 QuicSentEntropyManager sent_entropy_manager_
;
854 // Indicates whether an ack should be sent the next time we try to write.
856 // Indicates how many consecutive packets have arrived without sending an ack.
857 QuicPacketCount num_packets_received_since_last_ack_sent_
;
858 // Indicates how many consecutive times an ack has arrived which indicates
859 // the peer needs to stop waiting for some packets.
860 int stop_waiting_count_
;
862 // Indicates the retransmit alarm is going to be set by the
863 // ScopedRetransmitAlarmDelayer
864 bool delay_setting_retransmission_alarm_
;
865 // Indicates the retransmission alarm needs to be set.
866 bool pending_retransmission_alarm_
;
868 // An alarm that fires when an ACK should be sent to the peer.
869 scoped_ptr
<QuicAlarm
> ack_alarm_
;
870 // An alarm that fires when a packet needs to be retransmitted.
871 scoped_ptr
<QuicAlarm
> retransmission_alarm_
;
872 // An alarm that is scheduled when the SentPacketManager requires a delay
873 // before sending packets and fires when the packet may be sent.
874 scoped_ptr
<QuicAlarm
> send_alarm_
;
875 // An alarm that is scheduled when the connection can still write and there
876 // may be more data to send.
877 scoped_ptr
<QuicAlarm
> resume_writes_alarm_
;
878 // An alarm that fires when the connection may have timed out.
879 scoped_ptr
<QuicAlarm
> timeout_alarm_
;
880 // An alarm that fires when a ping should be sent.
881 scoped_ptr
<QuicAlarm
> ping_alarm_
;
882 // An alarm that fires when an MTU probe should be sent.
883 scoped_ptr
<QuicAlarm
> mtu_discovery_alarm_
;
885 // Neither visitor is owned by this class.
886 QuicConnectionVisitorInterface
* visitor_
;
887 QuicConnectionDebugVisitor
* debug_visitor_
;
889 QuicPacketGenerator packet_generator_
;
891 // An alarm that fires when an FEC packet should be sent.
892 scoped_ptr
<QuicAlarm
> fec_alarm_
;
894 // Network idle time before we kill of this connection.
895 QuicTime::Delta idle_network_timeout_
;
896 // Overall connection timeout.
897 QuicTime::Delta overall_connection_timeout_
;
899 // Statistics for this session.
900 QuicConnectionStats stats_
;
902 // The time that we got a packet for this connection.
903 // This is used for timeouts, and does not indicate the packet was processed.
904 QuicTime time_of_last_received_packet_
;
906 // The last time this connection began sending a new (non-retransmitted)
908 QuicTime time_of_last_sent_new_packet_
;
910 // packet number of the last sent packet. Packets are guaranteed to be sent
911 // in packet number order.
912 QuicPacketNumber packet_number_of_last_sent_packet_
;
914 // Sent packet manager which tracks the status of packets sent by this
915 // connection and contains the send and receive algorithms to determine when
917 QuicSentPacketManager sent_packet_manager_
;
919 // The state of connection in version negotiation finite state machine.
920 QuicVersionNegotiationState version_negotiation_state_
;
922 // Tracks if the connection was created by the server or the client.
923 Perspective perspective_
;
925 // True by default. False if we've received or sent an explicit connection
929 // Set to true if the UDP packet headers have a new IP address for the peer.
930 bool peer_ip_changed_
;
932 // Set to true if the UDP packet headers have a new port for the peer.
933 bool peer_port_changed_
;
935 // Set to true if the UDP packet headers are addressed to a different IP.
936 // We do not support connection migration when the self IP changed.
937 bool self_ip_changed_
;
939 // Set to true if the UDP packet headers are addressed to a different port.
940 // We do not support connection migration when the self port changed.
941 bool self_port_changed_
;
943 // Set to false if the connection should not send truncated connection IDs to
944 // the peer, even if the peer supports it.
945 bool can_truncate_connection_ids_
;
947 // If non-empty this contains the set of versions received in a
948 // version negotiation packet.
949 QuicVersionVector server_supported_versions_
;
951 // True if this is a secure QUIC connection.
954 // The size of the packet we are targeting while doing path MTU discovery.
955 QuicByteCount mtu_discovery_target_
;
957 // The number of MTU probes already sent.
958 size_t mtu_probe_count_
;
960 // The number of packets between MTU probes.
961 QuicPacketCount packets_between_mtu_probes_
;
963 // The packet number of the packet after which the next MTU probe will be
965 QuicPacketNumber next_mtu_probe_at_
;
967 // The size of the largest packet received from peer.
968 QuicByteCount largest_received_packet_size_
;
970 // Whether a GoAway has been sent.
973 // Whether a GoAway has been received.
974 bool goaway_received_
;
976 DISALLOW_COPY_AND_ASSIGN(QuicConnection
);
981 #endif // NET_QUIC_QUIC_CONNECTION_H_