Update broken references to image assets
[chromium-blink-merge.git] / net / quic / quic_connection.h
blob3e35736938b41d0fbecaa2d0986416cf187a91f6
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 //
5 // The entity that handles framing writes for a Quic client or server.
6 // Each QuicSession will have a connection associated with it.
7 //
8 // On the server side, the Dispatcher handles the raw reads, and hands off
9 // packets via ProcessUdpPacket for framing and processing.
11 // On the client side, the Connection handles the raw reads, as well as the
12 // processing.
14 // Note: this class is not thread-safe.
16 #ifndef NET_QUIC_QUIC_CONNECTION_H_
17 #define NET_QUIC_QUIC_CONNECTION_H_
19 #include <stddef.h>
20 #include <deque>
21 #include <list>
22 #include <map>
23 #include <queue>
24 #include <string>
25 #include <vector>
27 #include "base/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"
48 namespace net {
50 class QuicClock;
51 class QuicConfig;
52 class QuicConnection;
53 class QuicDecrypter;
54 class QuicEncrypter;
55 class QuicFecGroup;
56 class QuicRandom;
58 namespace test {
59 class PacketSavingConnection;
60 class QuicConnectionPeer;
61 } // namespace test
63 // The initial number of packets between MTU probes. After each attempt the
64 // number is doubled.
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 {
95 public:
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
133 // limits).
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 {
152 public:
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 {
243 public:
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 {
263 public:
264 enum AckBundling {
265 NO_ACK = 0,
266 SEND_ACK = 1,
267 BUNDLE_PENDING_ACK = 2,
270 class PacketWriterFactory {
271 public:
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,
282 IPEndPoint address,
283 QuicConnectionHelperInterface* helper,
284 const PacketWriterFactory& writer_factory,
285 bool owns_writer,
286 Perspective perspective,
287 bool is_secure,
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
313 // same FEC group.
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,
320 bool fin,
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;
350 // Sends a GOAWAY frame. Does nothing if a GOAWAY frame has already been sent.
351 virtual void SendGoAway(QuicErrorCode error,
352 QuicStreamId last_good_stream_id,
353 const std::string& reason);
355 // Returns statistics tracked for this connection.
356 const QuicConnectionStats& GetStats();
358 // Processes an incoming UDP packet (consisting of a QuicEncryptedPacket) from
359 // the peer. If processing this packet permits a packet to be revived from
360 // its FEC group that packet will be revived and processed.
361 // In a client, the packet may be "stray" and have a different connection ID
362 // than that of this connection.
363 virtual void ProcessUdpPacket(const IPEndPoint& self_address,
364 const IPEndPoint& peer_address,
365 const QuicEncryptedPacket& packet);
367 // QuicBlockedWriterInterface
368 // Called when the underlying connection becomes writable to allow queued
369 // writes to happen.
370 void OnCanWrite() override;
372 // Called when an error occurs while attempting to write a packet to the
373 // network.
374 void OnWriteError(int error_code);
376 // If the socket is not blocked, writes queued packets.
377 void WriteIfNotBlocked();
379 // Set the packet writer.
380 void SetQuicPacketWriter(QuicPacketWriter* writer, bool owns_writer) {
381 writer_ = writer;
382 owns_writer_ = owns_writer;
385 // Set self address.
386 void SetSelfAddress(IPEndPoint address) { self_address_ = address; }
388 // The version of the protocol this connection is using.
389 QuicVersion version() const { return framer_.version(); }
391 // The versions of the protocol that this connection supports.
392 const QuicVersionVector& supported_versions() const {
393 return framer_.supported_versions();
396 // From QuicFramerVisitorInterface
397 void OnError(QuicFramer* framer) override;
398 bool OnProtocolVersionMismatch(QuicVersion received_version) override;
399 void OnPacket() override;
400 void OnPublicResetPacket(const QuicPublicResetPacket& packet) override;
401 void OnVersionNegotiationPacket(
402 const QuicVersionNegotiationPacket& packet) override;
403 void OnRevivedPacket() override;
404 bool OnUnauthenticatedPublicHeader(
405 const QuicPacketPublicHeader& header) override;
406 bool OnUnauthenticatedHeader(const QuicPacketHeader& header) override;
407 void OnDecryptedPacket(EncryptionLevel level) override;
408 bool OnPacketHeader(const QuicPacketHeader& header) override;
409 void OnFecProtectedPayload(base::StringPiece payload) override;
410 bool OnStreamFrame(const QuicStreamFrame& frame) override;
411 bool OnAckFrame(const QuicAckFrame& frame) override;
412 bool OnStopWaitingFrame(const QuicStopWaitingFrame& frame) override;
413 bool OnPingFrame(const QuicPingFrame& frame) override;
414 bool OnRstStreamFrame(const QuicRstStreamFrame& frame) override;
415 bool OnConnectionCloseFrame(const QuicConnectionCloseFrame& frame) override;
416 bool OnGoAwayFrame(const QuicGoAwayFrame& frame) override;
417 bool OnWindowUpdateFrame(const QuicWindowUpdateFrame& frame) override;
418 bool OnBlockedFrame(const QuicBlockedFrame& frame) override;
419 void OnFecData(const QuicFecData& fec) override;
420 void OnPacketComplete() override;
422 // QuicPacketGenerator::DelegateInterface
423 bool ShouldGeneratePacket(HasRetransmittableData retransmittable,
424 IsHandshake handshake) override;
425 void PopulateAckFrame(QuicAckFrame* ack) override;
426 void PopulateStopWaitingFrame(QuicStopWaitingFrame* stop_waiting) override;
427 void OnSerializedPacket(const SerializedPacket& packet) override;
428 void OnResetFecGroup() override;
430 // QuicSentPacketManager::NetworkChangeVisitor
431 void OnCongestionWindowChange() override;
432 void OnRttChange() override;
434 // Called by the crypto stream when the handshake completes. In the server's
435 // case this is when the SHLO has been ACKed. Clients call this on receipt of
436 // the SHLO.
437 void OnHandshakeComplete();
439 // Accessors
440 void set_visitor(QuicConnectionVisitorInterface* visitor) {
441 visitor_ = visitor;
443 void set_debug_visitor(QuicConnectionDebugVisitor* debug_visitor) {
444 debug_visitor_ = debug_visitor;
445 packet_generator_.set_debug_delegate(debug_visitor);
446 sent_packet_manager_.set_debug_delegate(debug_visitor);
448 const IPEndPoint& self_address() const { return self_address_; }
449 const IPEndPoint& peer_address() const { return peer_address_; }
450 QuicConnectionId connection_id() const { return connection_id_; }
451 const QuicClock* clock() const { return clock_; }
452 QuicRandom* random_generator() const { return random_generator_; }
453 QuicByteCount max_packet_length() const;
454 void set_max_packet_length(QuicByteCount length);
456 size_t mtu_probe_count() const { return mtu_probe_count_; }
458 bool connected() const { return connected_; }
460 bool goaway_sent() const { return goaway_sent_; }
462 bool goaway_received() const { return goaway_received_; }
464 // Must only be called on client connections.
465 const QuicVersionVector& server_supported_versions() const {
466 DCHECK_EQ(Perspective::IS_CLIENT, perspective_);
467 return server_supported_versions_;
470 size_t NumFecGroups() const { return group_map_.size(); }
472 // Testing only.
473 size_t NumQueuedPackets() const { return queued_packets_.size(); }
475 QuicEncryptedPacket* ReleaseConnectionClosePacket() {
476 return connection_close_packet_.release();
479 // Returns true if the underlying UDP socket is writable, there is
480 // no queued data and the connection is not congestion-control
481 // blocked.
482 bool CanWriteStreamData();
484 // Returns true if the connection has queued packets or frames.
485 bool HasQueuedData() const;
487 // Sets the overall and idle state connection timeouts.
488 void SetNetworkTimeouts(QuicTime::Delta overall_timeout,
489 QuicTime::Delta idle_timeout);
491 // If the connection has timed out, this will close the connection.
492 // Otherwise, it will reschedule the timeout alarm.
493 void CheckForTimeout();
495 // Sends a ping, and resets the ping alarm.
496 void SendPing();
498 // Sets up a packet with an QuicAckFrame and sends it out.
499 void SendAck();
501 // Called when an RTO fires. Resets the retransmission alarm if there are
502 // remaining unacked packets.
503 void OnRetransmissionTimeout();
505 // Called when a data packet is sent. Starts an alarm if the data sent in
506 // |sequence_number| was FEC protected.
507 void MaybeSetFecAlarm(QuicPacketSequenceNumber sequence_number);
509 // Retransmits all unacked packets with retransmittable frames if
510 // |retransmission_type| is ALL_UNACKED_PACKETS, otherwise retransmits only
511 // initially encrypted packets. Used when the negotiated protocol version is
512 // different from what was initially assumed and when the initial encryption
513 // changes.
514 void RetransmitUnackedPackets(TransmissionType retransmission_type);
516 // Calls |sent_packet_manager_|'s NeuterUnencryptedPackets. Used when the
517 // connection becomes forward secure and hasn't received acks for all packets.
518 void NeuterUnencryptedPackets();
520 // Changes the encrypter used for level |level| to |encrypter|. The function
521 // takes ownership of |encrypter|.
522 void SetEncrypter(EncryptionLevel level, QuicEncrypter* encrypter);
524 // SetDefaultEncryptionLevel sets the encryption level that will be applied
525 // to new packets.
526 void SetDefaultEncryptionLevel(EncryptionLevel level);
528 // SetDecrypter sets the primary decrypter, replacing any that already exists,
529 // and takes ownership. If an alternative decrypter is in place then the
530 // function DCHECKs. This is intended for cases where one knows that future
531 // packets will be using the new decrypter and the previous decrypter is now
532 // obsolete. |level| indicates the encryption level of the new decrypter.
533 void SetDecrypter(EncryptionLevel level, QuicDecrypter* decrypter);
535 // SetAlternativeDecrypter sets a decrypter that may be used to decrypt
536 // future packets and takes ownership of it. |level| indicates the encryption
537 // level of the decrypter. If |latch_once_used| is true, then the first time
538 // that the decrypter is successful it will replace the primary decrypter.
539 // Otherwise both decrypters will remain active and the primary decrypter
540 // will be the one last used.
541 void SetAlternativeDecrypter(EncryptionLevel level,
542 QuicDecrypter* decrypter,
543 bool latch_once_used);
545 const QuicDecrypter* decrypter() const;
546 const QuicDecrypter* alternative_decrypter() const;
548 Perspective perspective() const { return perspective_; }
550 // Allow easy overriding of truncated connection IDs.
551 void set_can_truncate_connection_ids(bool can) {
552 can_truncate_connection_ids_ = can;
555 // Returns the underlying sent packet manager.
556 const QuicSentPacketManager& sent_packet_manager() const {
557 return sent_packet_manager_;
560 bool CanWrite(HasRetransmittableData retransmittable);
562 // Stores current batch state for connection, puts the connection
563 // into batch mode, and destruction restores the stored batch state.
564 // While the bundler is in scope, any generated frames are bundled
565 // as densely as possible into packets. In addition, this bundler
566 // can be configured to ensure that an ACK frame is included in the
567 // first packet created, if there's new ack information to be sent.
568 class ScopedPacketBundler {
569 public:
570 // In addition to all outgoing frames being bundled when the
571 // bundler is in scope, setting |include_ack| to true ensures that
572 // an ACK frame is opportunistically bundled with the first
573 // outgoing packet.
574 ScopedPacketBundler(QuicConnection* connection, AckBundling send_ack);
575 ~ScopedPacketBundler();
577 private:
578 QuicConnection* connection_;
579 bool already_in_batch_mode_;
582 // Delays setting the retransmission alarm until the scope is exited.
583 // When nested, only the outermost scheduler will set the alarm, and inner
584 // ones have no effect.
585 class NET_EXPORT_PRIVATE ScopedRetransmissionScheduler {
586 public:
587 explicit ScopedRetransmissionScheduler(QuicConnection* connection);
588 ~ScopedRetransmissionScheduler();
590 private:
591 QuicConnection* connection_;
592 // Set to the connection's delay_setting_retransmission_alarm_ value in the
593 // constructor and when true, causes this class to do nothing.
594 const bool already_delayed_;
597 QuicPacketSequenceNumber sequence_number_of_last_sent_packet() const {
598 return sequence_number_of_last_sent_packet_;
601 QuicPacketWriter* writer() { return writer_; }
602 const QuicPacketWriter* writer() const { return writer_; }
604 bool is_secure() const { return is_secure_; }
606 // Sends an MTU discovery packet of size |target_mtu|. If the packet is
607 // acknowledged by the peer, the maximum packet size will be increased to
608 // |target_mtu|.
609 void SendMtuDiscoveryPacket(QuicByteCount target_mtu);
611 // Sends an MTU discovery packet of size |mtu_discovery_target_| and updates
612 // the MTU discovery alarm.
613 void DiscoverMtu();
615 // Return the name of the cipher of the primary decrypter of the framer.
616 const char* cipher_name() const { return framer_.decrypter()->cipher_name(); }
617 // Return the id of the cipher of the primary decrypter of the framer.
618 uint32 cipher_id() const { return framer_.decrypter()->cipher_id(); }
620 protected:
621 // Packets which have not been written to the wire.
622 // Owns the QuicPacket* packet.
623 struct QueuedPacket {
624 QueuedPacket(SerializedPacket packet,
625 EncryptionLevel level);
626 QueuedPacket(SerializedPacket packet,
627 EncryptionLevel level,
628 TransmissionType transmission_type,
629 QuicPacketSequenceNumber original_sequence_number);
631 SerializedPacket serialized_packet;
632 const EncryptionLevel encryption_level;
633 TransmissionType transmission_type;
634 // The packet's original sequence number if it is a retransmission.
635 // Otherwise it must be 0.
636 QuicPacketSequenceNumber original_sequence_number;
639 // Do any work which logically would be done in OnPacket but can not be
640 // safely done until the packet is validated. Returns true if the packet
641 // can be handled, false otherwise.
642 virtual bool ProcessValidatedPacket();
644 // Send a packet to the peer, and takes ownership of the packet if the packet
645 // cannot be written immediately.
646 virtual void SendOrQueuePacket(QueuedPacket packet);
648 QuicConnectionHelperInterface* helper() { return helper_; }
650 // Selects and updates the version of the protocol being used by selecting a
651 // version from |available_versions| which is also supported. Returns true if
652 // such a version exists, false otherwise.
653 bool SelectMutualVersion(const QuicVersionVector& available_versions);
655 bool peer_port_changed() const { return peer_port_changed_; }
657 private:
658 friend class test::QuicConnectionPeer;
659 friend class test::PacketSavingConnection;
661 typedef std::list<QueuedPacket> QueuedPacketList;
662 typedef std::map<QuicFecGroupNumber, QuicFecGroup*> FecGroupMap;
664 // Writes the given packet to socket, encrypted with packet's
665 // encryption_level. Returns true on successful write, and false if the writer
666 // was blocked and the write needs to be tried again. Notifies the
667 // SentPacketManager when the write is successful and sets
668 // retransmittable frames to nullptr.
669 // Saves the connection close packet for later transmission, even if the
670 // writer is write blocked.
671 bool WritePacket(QueuedPacket* packet);
673 // Does the main work of WritePacket, but does not delete the packet or
674 // retransmittable frames upon success.
675 bool WritePacketInner(QueuedPacket* packet);
677 // Make sure an ack we got from our peer is sane.
678 bool ValidateAckFrame(const QuicAckFrame& incoming_ack);
680 // Make sure a stop waiting we got from our peer is sane.
681 bool ValidateStopWaitingFrame(const QuicStopWaitingFrame& stop_waiting);
683 // Sends a version negotiation packet to the peer.
684 void SendVersionNegotiationPacket();
686 // Clears any accumulated frames from the last received packet.
687 void ClearLastFrames();
689 // Closes the connection if the sent or received packet manager are tracking
690 // too many outstanding packets.
691 void MaybeCloseIfTooManyOutstandingPackets();
693 // Writes as many queued packets as possible. The connection must not be
694 // blocked when this is called.
695 void WriteQueuedPackets();
697 // Writes as many pending retransmissions as possible.
698 void WritePendingRetransmissions();
700 // Returns true if the packet should be discarded and not sent.
701 bool ShouldDiscardPacket(const QueuedPacket& packet);
703 // Queues |packet| in the hopes that it can be decrypted in the
704 // future, when a new key is installed.
705 void QueueUndecryptablePacket(const QuicEncryptedPacket& packet);
707 // Attempts to process any queued undecryptable packets.
708 void MaybeProcessUndecryptablePackets();
710 // If a packet can be revived from the current FEC group, then
711 // revive and process the packet.
712 void MaybeProcessRevivedPacket();
714 void ProcessAckFrame(const QuicAckFrame& incoming_ack);
716 void ProcessStopWaitingFrame(const QuicStopWaitingFrame& stop_waiting);
718 // Queues an ack or sets the ack alarm when an incoming packet arrives that
719 // should be acked.
720 void MaybeQueueAck();
722 // Checks if the last packet should instigate an ack.
723 bool ShouldLastPacketInstigateAck() const;
725 // Checks if the peer is waiting for packets that have been given up on, and
726 // therefore an ack frame should be sent with a larger least_unacked.
727 void UpdateStopWaitingCount();
729 // Sends any packets which are a response to the last packet, including both
730 // acks and pending writes if an ack opened the congestion window.
731 void MaybeSendInResponseToPacket();
733 // Gets the least unacked sequence number, which is the next sequence number
734 // to be sent if there are no outstanding packets.
735 QuicPacketSequenceNumber GetLeastUnacked() const;
737 // Get the FEC group associate with the last processed packet or nullptr, if
738 // the group has already been deleted.
739 QuicFecGroup* GetFecGroup();
741 // Closes any FEC groups protecting packets before |sequence_number|.
742 void CloseFecGroupsBefore(QuicPacketSequenceNumber sequence_number);
744 // Sets the timeout alarm to the appropriate value, if any.
745 void SetTimeoutAlarm();
747 // Sets the ping alarm to the appropriate value, if any.
748 void SetPingAlarm();
750 // Sets the retransmission alarm based on SentPacketManager.
751 void SetRetransmissionAlarm();
753 // Sets the MTU discovery alarm if necessary.
754 void MaybeSetMtuAlarm();
756 // On arrival of a new packet, checks to see if the socket addresses have
757 // changed since the last packet we saw on this connection.
758 void CheckForAddressMigration(const IPEndPoint& self_address,
759 const IPEndPoint& peer_address);
761 HasRetransmittableData IsRetransmittable(const QueuedPacket& packet);
762 bool IsConnectionClose(const QueuedPacket& packet);
764 QuicFramer framer_;
765 QuicConnectionHelperInterface* helper_; // Not owned.
766 QuicPacketWriter* writer_; // Owned or not depending on |owns_writer_|.
767 bool owns_writer_;
768 // Encryption level for new packets. Should only be changed via
769 // SetDefaultEncryptionLevel().
770 EncryptionLevel encryption_level_;
771 bool has_forward_secure_encrypter_;
772 // The sequence number of the first packet which will be encrypted with the
773 // foward-secure encrypter, even if the peer has not started sending
774 // forward-secure packets.
775 QuicPacketSequenceNumber first_required_forward_secure_packet_;
776 const QuicClock* clock_;
777 QuicRandom* random_generator_;
779 const QuicConnectionId connection_id_;
780 // Address on the last successfully processed packet received from the
781 // client.
782 IPEndPoint self_address_;
783 IPEndPoint peer_address_;
785 // TODO(fayang): Use migrating_peer_address_ instead of migrating_peer_ip_
786 // and migrating_peer_port_ once FLAGS_quic_allow_ip_migration is deprecated.
787 // Used to store latest peer IP address for IP address migration.
788 IPAddressNumber migrating_peer_ip_;
789 // Used to store latest peer port to possibly migrate to later.
790 uint16 migrating_peer_port_;
792 // True if the last packet has gotten far enough in the framer to be
793 // decrypted.
794 bool last_packet_decrypted_;
795 bool last_packet_revived_; // True if the last packet was revived from FEC.
796 QuicByteCount last_size_; // Size of the last received packet.
797 EncryptionLevel last_decrypted_packet_level_;
798 QuicPacketHeader last_header_;
799 std::vector<QuicStreamFrame> last_stream_frames_;
800 std::vector<QuicAckFrame> last_ack_frames_;
801 std::vector<QuicStopWaitingFrame> last_stop_waiting_frames_;
802 std::vector<QuicRstStreamFrame> last_rst_frames_;
803 std::vector<QuicGoAwayFrame> last_goaway_frames_;
804 std::vector<QuicWindowUpdateFrame> last_window_update_frames_;
805 std::vector<QuicBlockedFrame> last_blocked_frames_;
806 std::vector<QuicPingFrame> last_ping_frames_;
807 std::vector<QuicConnectionCloseFrame> last_close_frames_;
808 bool should_last_packet_instigate_acks_;
810 // Track some peer state so we can do less bookkeeping
811 // Largest sequence sent by the peer which had an ack frame (latest ack info).
812 QuicPacketSequenceNumber largest_seen_packet_with_ack_;
814 // Largest sequence number sent by the peer which had a stop waiting frame.
815 QuicPacketSequenceNumber largest_seen_packet_with_stop_waiting_;
817 // Collection of packets which were received before encryption was
818 // established, but which could not be decrypted. We buffer these on
819 // the assumption that they could not be processed because they were
820 // sent with the INITIAL encryption and the CHLO message was lost.
821 std::deque<QuicEncryptedPacket*> undecryptable_packets_;
823 // Maximum number of undecryptable packets the connection will store.
824 size_t max_undecryptable_packets_;
826 // When the version negotiation packet could not be sent because the socket
827 // was not writable, this is set to true.
828 bool pending_version_negotiation_packet_;
830 // When packets could not be sent because the socket was not writable,
831 // they are added to this list. All corresponding frames are in
832 // unacked_packets_ if they are to be retransmitted.
833 QueuedPacketList queued_packets_;
835 // Contains the connection close packet if the connection has been closed.
836 scoped_ptr<QuicEncryptedPacket> connection_close_packet_;
838 // When true, the connection does not send a close packet on timeout.
839 bool silent_close_enabled_;
841 FecGroupMap group_map_;
843 QuicReceivedPacketManager received_packet_manager_;
844 QuicSentEntropyManager sent_entropy_manager_;
846 // Indicates whether an ack should be sent the next time we try to write.
847 bool ack_queued_;
848 // Indicates how many consecutive packets have arrived without sending an ack.
849 QuicPacketCount num_packets_received_since_last_ack_sent_;
850 // Indicates how many consecutive times an ack has arrived which indicates
851 // the peer needs to stop waiting for some packets.
852 int stop_waiting_count_;
854 // Indicates the retransmit alarm is going to be set by the
855 // ScopedRetransmitAlarmDelayer
856 bool delay_setting_retransmission_alarm_;
857 // Indicates the retransmission alarm needs to be set.
858 bool pending_retransmission_alarm_;
860 // An alarm that fires when an ACK should be sent to the peer.
861 scoped_ptr<QuicAlarm> ack_alarm_;
862 // An alarm that fires when a packet needs to be retransmitted.
863 scoped_ptr<QuicAlarm> retransmission_alarm_;
864 // An alarm that is scheduled when the SentPacketManager requires a delay
865 // before sending packets and fires when the packet may be sent.
866 scoped_ptr<QuicAlarm> send_alarm_;
867 // An alarm that is scheduled when the connection can still write and there
868 // may be more data to send.
869 scoped_ptr<QuicAlarm> resume_writes_alarm_;
870 // An alarm that fires when the connection may have timed out.
871 scoped_ptr<QuicAlarm> timeout_alarm_;
872 // An alarm that fires when a ping should be sent.
873 scoped_ptr<QuicAlarm> ping_alarm_;
874 // An alarm that fires when an MTU probe should be sent.
875 scoped_ptr<QuicAlarm> mtu_discovery_alarm_;
877 // Neither visitor is owned by this class.
878 QuicConnectionVisitorInterface* visitor_;
879 QuicConnectionDebugVisitor* debug_visitor_;
881 QuicPacketGenerator packet_generator_;
883 // An alarm that fires when an FEC packet should be sent.
884 scoped_ptr<QuicAlarm> fec_alarm_;
886 // Network idle time before we kill of this connection.
887 QuicTime::Delta idle_network_timeout_;
888 // Overall connection timeout.
889 QuicTime::Delta overall_connection_timeout_;
891 // Statistics for this session.
892 QuicConnectionStats stats_;
894 // The time that we got a packet for this connection.
895 // This is used for timeouts, and does not indicate the packet was processed.
896 QuicTime time_of_last_received_packet_;
898 // The last time this connection began sending a new (non-retransmitted)
899 // packet.
900 QuicTime time_of_last_sent_new_packet_;
902 // Sequence number of the last sent packet. Packets are guaranteed to be sent
903 // in sequence number order.
904 QuicPacketSequenceNumber sequence_number_of_last_sent_packet_;
906 // Sent packet manager which tracks the status of packets sent by this
907 // connection and contains the send and receive algorithms to determine when
908 // to send packets.
909 QuicSentPacketManager sent_packet_manager_;
911 // The state of connection in version negotiation finite state machine.
912 QuicVersionNegotiationState version_negotiation_state_;
914 // Tracks if the connection was created by the server or the client.
915 Perspective perspective_;
917 // True by default. False if we've received or sent an explicit connection
918 // close.
919 bool connected_;
921 // Set to true if the UDP packet headers have a new IP address for the peer.
922 // If true, do not perform connection migration.
923 bool peer_ip_changed_;
925 // Set to true if the UDP packet headers have a new port for the peer.
926 // If true, and the IP has not changed, then we can migrate the connection.
927 bool peer_port_changed_;
929 // Set to true if the UDP packet headers are addressed to a different IP.
930 // We do not support connection migration when the self IP changed.
931 bool self_ip_changed_;
933 // Set to true if the UDP packet headers are addressed to a different port.
934 // We do not support connection migration when the self port changed.
935 bool self_port_changed_;
937 // Set to false if the connection should not send truncated connection IDs to
938 // the peer, even if the peer supports it.
939 bool can_truncate_connection_ids_;
941 // If non-empty this contains the set of versions received in a
942 // version negotiation packet.
943 QuicVersionVector server_supported_versions_;
945 // True if this is a secure QUIC connection.
946 bool is_secure_;
948 // The size of the packet we are targeting while doing path MTU discovery.
949 QuicByteCount mtu_discovery_target_;
951 // The number of MTU probes already sent.
952 size_t mtu_probe_count_;
954 // The number of packets between MTU probes.
955 QuicPacketCount packets_between_mtu_probes_;
957 // The sequence number of the packet after which the next MTU probe will be
958 // sent.
959 QuicPacketSequenceNumber next_mtu_probe_at_;
961 // The size of the largest packet received from peer.
962 QuicByteCount largest_received_packet_size_;
964 // Whether a GoAway has been sent.
965 bool goaway_sent_;
967 // Whether a GoAway has been received.
968 bool goaway_received_;
970 DISALLOW_COPY_AND_ASSIGN(QuicConnection);
973 } // namespace net
975 #endif // NET_QUIC_QUIC_CONNECTION_H_