Add missing mandoline dependencies.
[chromium-blink-merge.git] / net / quic / quic_connection.h
blobb7bbdd7af191fa401b53fe1942f575c98be37fe4
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/iovector.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 // Class that receives callbacks from the connection when frames are received
64 // and when other interesting events happen.
65 class NET_EXPORT_PRIVATE QuicConnectionVisitorInterface {
66 public:
67 virtual ~QuicConnectionVisitorInterface() {}
69 // A simple visitor interface for dealing with data frames.
70 virtual void OnStreamFrames(const std::vector<QuicStreamFrame>& frames) = 0;
72 // The session should process all WINDOW_UPDATE frames, adjusting both stream
73 // and connection level flow control windows.
74 virtual void OnWindowUpdateFrames(
75 const std::vector<QuicWindowUpdateFrame>& frames) = 0;
77 // BLOCKED frames tell us that the peer believes it is flow control blocked on
78 // a specified stream. If the session at this end disagrees, something has
79 // gone wrong with our flow control accounting.
80 virtual void OnBlockedFrames(const std::vector<QuicBlockedFrame>& frames) = 0;
82 // Called when the stream is reset by the peer.
83 virtual void OnRstStream(const QuicRstStreamFrame& frame) = 0;
85 // Called when the connection is going away according to the peer.
86 virtual void OnGoAway(const QuicGoAwayFrame& frame) = 0;
88 // Called when the connection is closed either locally by the framer, or
89 // remotely by the peer.
90 virtual void OnConnectionClosed(QuicErrorCode error, bool from_peer) = 0;
92 // Called when the connection failed to write because the socket was blocked.
93 virtual void OnWriteBlocked() = 0;
95 // Called once a specific QUIC version is agreed by both endpoints.
96 virtual void OnSuccessfulVersionNegotiation(const QuicVersion& version) = 0;
98 // Called when a blocked socket becomes writable.
99 virtual void OnCanWrite() = 0;
101 // Called when the connection experiences a change in congestion window.
102 virtual void OnCongestionWindowChange(QuicTime now) = 0;
104 // Called to ask if the visitor wants to schedule write resumption as it both
105 // has pending data to write, and is able to write (e.g. based on flow control
106 // limits).
107 // Writes may be pending because they were write-blocked, congestion-throttled
108 // or yielded to other connections.
109 virtual bool WillingAndAbleToWrite() const = 0;
111 // Called to ask if any handshake messages are pending in this visitor.
112 virtual bool HasPendingHandshake() const = 0;
114 // Called to ask if any streams are open in this visitor, excluding the
115 // reserved crypto and headers stream.
116 virtual bool HasOpenDataStreams() const = 0;
119 // Interface which gets callbacks from the QuicConnection at interesting
120 // points. Implementations must not mutate the state of the connection
121 // as a result of these callbacks.
122 class NET_EXPORT_PRIVATE QuicConnectionDebugVisitor
123 : public QuicPacketGenerator::DebugDelegate,
124 public QuicSentPacketManager::DebugDelegate {
125 public:
126 ~QuicConnectionDebugVisitor() override {}
128 // Called when a packet has been sent.
129 virtual void OnPacketSent(const SerializedPacket& serialized_packet,
130 QuicPacketSequenceNumber original_sequence_number,
131 EncryptionLevel level,
132 TransmissionType transmission_type,
133 const QuicEncryptedPacket& packet,
134 QuicTime sent_time) {}
136 // Called when a packet has been received, but before it is
137 // validated or parsed.
138 virtual void OnPacketReceived(const IPEndPoint& self_address,
139 const IPEndPoint& peer_address,
140 const QuicEncryptedPacket& packet) {}
142 // Called when a packet is received with a connection id that does not
143 // match the ID of this connection.
144 virtual void OnIncorrectConnectionId(
145 QuicConnectionId connection_id) {}
147 // Called when an undecryptable packet has been received.
148 virtual void OnUndecryptablePacket() {}
150 // Called when a duplicate packet has been received.
151 virtual void OnDuplicatePacket(QuicPacketSequenceNumber sequence_number) {}
153 // Called when the protocol version on the received packet doensn't match
154 // current protocol version of the connection.
155 virtual void OnProtocolVersionMismatch(QuicVersion version) {}
157 // Called when the complete header of a packet has been parsed.
158 virtual void OnPacketHeader(const QuicPacketHeader& header) {}
160 // Called when a StreamFrame has been parsed.
161 virtual void OnStreamFrame(const QuicStreamFrame& frame) {}
163 // Called when a AckFrame has been parsed.
164 virtual void OnAckFrame(const QuicAckFrame& frame) {}
166 // Called when a StopWaitingFrame has been parsed.
167 virtual void OnStopWaitingFrame(const QuicStopWaitingFrame& frame) {}
169 // Called when a Ping has been parsed.
170 virtual void OnPingFrame(const QuicPingFrame& frame) {}
172 // Called when a GoAway has been parsed.
173 virtual void OnGoAwayFrame(const QuicGoAwayFrame& frame) {}
175 // Called when a RstStreamFrame has been parsed.
176 virtual void OnRstStreamFrame(const QuicRstStreamFrame& frame) {}
178 // Called when a ConnectionCloseFrame has been parsed.
179 virtual void OnConnectionCloseFrame(
180 const QuicConnectionCloseFrame& frame) {}
182 // Called when a WindowUpdate has been parsed.
183 virtual void OnWindowUpdateFrame(const QuicWindowUpdateFrame& frame) {}
185 // Called when a BlockedFrame has been parsed.
186 virtual void OnBlockedFrame(const QuicBlockedFrame& frame) {}
188 // Called when a public reset packet has been received.
189 virtual void OnPublicResetPacket(const QuicPublicResetPacket& packet) {}
191 // Called when a version negotiation packet has been received.
192 virtual void OnVersionNegotiationPacket(
193 const QuicVersionNegotiationPacket& packet) {}
195 // Called after a packet has been successfully parsed which results
196 // in the revival of a packet via FEC.
197 virtual void OnRevivedPacket(const QuicPacketHeader& revived_header,
198 base::StringPiece payload) {}
200 // Called when the connection is closed.
201 virtual void OnConnectionClosed(QuicErrorCode error, bool from_peer) {}
203 // Called when the version negotiation is successful.
204 virtual void OnSuccessfulVersionNegotiation(const QuicVersion& version) {}
206 // Called when a CachedNetworkParameters is sent to the client.
207 virtual void OnSendConnectionState(
208 const CachedNetworkParameters& cached_network_params) {}
210 // Called when resuming previous connection state.
211 virtual void OnResumeConnectionState(
212 const CachedNetworkParameters& cached_network_params) {}
215 class NET_EXPORT_PRIVATE QuicConnectionHelperInterface {
216 public:
217 virtual ~QuicConnectionHelperInterface() {}
219 // Returns a QuicClock to be used for all time related functions.
220 virtual const QuicClock* GetClock() const = 0;
222 // Returns a QuicRandom to be used for all random number related functions.
223 virtual QuicRandom* GetRandomGenerator() = 0;
225 // Creates a new platform-specific alarm which will be configured to
226 // notify |delegate| when the alarm fires. Caller takes ownership
227 // of the new alarm, which will not yet be "set" to fire.
228 virtual QuicAlarm* CreateAlarm(QuicAlarm::Delegate* delegate) = 0;
231 class NET_EXPORT_PRIVATE QuicConnection
232 : public QuicFramerVisitorInterface,
233 public QuicBlockedWriterInterface,
234 public QuicPacketGenerator::DelegateInterface,
235 public QuicSentPacketManager::NetworkChangeVisitor {
236 public:
237 enum AckBundling {
238 NO_ACK = 0,
239 SEND_ACK = 1,
240 BUNDLE_PENDING_ACK = 2,
243 class PacketWriterFactory {
244 public:
245 virtual ~PacketWriterFactory() {}
247 virtual QuicPacketWriter* Create(QuicConnection* connection) const = 0;
250 // Constructs a new QuicConnection for |connection_id| and |address|. Invokes
251 // writer_factory->Create() to get a writer; |owns_writer| specifies whether
252 // the connection takes ownership of the returned writer. |helper| must
253 // outlive this connection.
254 QuicConnection(QuicConnectionId connection_id,
255 IPEndPoint address,
256 QuicConnectionHelperInterface* helper,
257 const PacketWriterFactory& writer_factory,
258 bool owns_writer,
259 Perspective perspective,
260 bool is_secure,
261 const QuicVersionVector& supported_versions);
262 ~QuicConnection() override;
264 // Sets connection parameters from the supplied |config|.
265 void SetFromConfig(const QuicConfig& config);
267 // Called by the session when sending connection state to the client.
268 virtual void OnSendConnectionState(
269 const CachedNetworkParameters& cached_network_params);
271 // Called by the Session when the client has provided CachedNetworkParameters.
272 // Returns true if this changes the initial connection state.
273 virtual bool ResumeConnectionState(
274 const CachedNetworkParameters& cached_network_params,
275 bool max_bandwidth_resumption);
277 // Sets the number of active streams on the connection for congestion control.
278 void SetNumOpenStreams(size_t num_streams);
280 // Send the data in |data| to the peer in as few packets as possible.
281 // Returns a pair with the number of bytes consumed from data, and a boolean
282 // indicating if the fin bit was consumed. This does not indicate the data
283 // has been sent on the wire: it may have been turned into a packet and queued
284 // if the socket was unexpectedly blocked. |fec_protection| indicates if
285 // data is to be FEC protected. Note that data that is sent immediately
286 // following MUST_FEC_PROTECT data may get protected by falling within the
287 // same FEC group.
288 // If |delegate| is provided, then it will be informed once ACKs have been
289 // received for all the packets written in this call.
290 // The |delegate| is not owned by the QuicConnection and must outlive it.
291 QuicConsumedData SendStreamData(QuicStreamId id,
292 const IOVector& data,
293 QuicStreamOffset offset,
294 bool fin,
295 FecProtection fec_protection,
296 QuicAckNotifier::DelegateInterface* delegate);
298 // Send a RST_STREAM frame to the peer.
299 virtual void SendRstStream(QuicStreamId id,
300 QuicRstStreamErrorCode error,
301 QuicStreamOffset bytes_written);
303 // Send a BLOCKED frame to the peer.
304 virtual void SendBlocked(QuicStreamId id);
306 // Send a WINDOW_UPDATE frame to the peer.
307 virtual void SendWindowUpdate(QuicStreamId id,
308 QuicStreamOffset byte_offset);
310 // Sends the connection close packet without affecting the state of the
311 // connection. This should only be called if the session is actively being
312 // destroyed: otherwise call SendConnectionCloseWithDetails instead.
313 virtual void SendConnectionClosePacket(QuicErrorCode error,
314 const std::string& details);
316 // Sends a connection close frame to the peer, and closes the connection by
317 // calling CloseConnection(notifying the visitor as it does so).
318 virtual void SendConnectionClose(QuicErrorCode error);
319 virtual void SendConnectionCloseWithDetails(QuicErrorCode error,
320 const std::string& details);
321 // Notifies the visitor of the close and marks the connection as disconnected.
322 void CloseConnection(QuicErrorCode error, bool from_peer) override;
323 virtual void SendGoAway(QuicErrorCode error,
324 QuicStreamId last_good_stream_id,
325 const std::string& reason);
327 // Returns statistics tracked for this connection.
328 const QuicConnectionStats& GetStats();
330 // Processes an incoming UDP packet (consisting of a QuicEncryptedPacket) from
331 // the peer. If processing this packet permits a packet to be revived from
332 // its FEC group that packet will be revived and processed.
333 // In a client, the packet may be "stray" and have a different connection ID
334 // than that of this connection.
335 virtual void ProcessUdpPacket(const IPEndPoint& self_address,
336 const IPEndPoint& peer_address,
337 const QuicEncryptedPacket& packet);
339 // QuicBlockedWriterInterface
340 // Called when the underlying connection becomes writable to allow queued
341 // writes to happen.
342 void OnCanWrite() override;
344 // Called when an error occurs while attempting to write a packet to the
345 // network.
346 void OnWriteError(int error_code);
348 // If the socket is not blocked, writes queued packets.
349 void WriteIfNotBlocked();
351 // The version of the protocol this connection is using.
352 QuicVersion version() const { return framer_.version(); }
354 // The versions of the protocol that this connection supports.
355 const QuicVersionVector& supported_versions() const {
356 return framer_.supported_versions();
359 // From QuicFramerVisitorInterface
360 void OnError(QuicFramer* framer) override;
361 bool OnProtocolVersionMismatch(QuicVersion received_version) override;
362 void OnPacket() override;
363 void OnPublicResetPacket(const QuicPublicResetPacket& packet) override;
364 void OnVersionNegotiationPacket(
365 const QuicVersionNegotiationPacket& packet) override;
366 void OnRevivedPacket() override;
367 bool OnUnauthenticatedPublicHeader(
368 const QuicPacketPublicHeader& header) override;
369 bool OnUnauthenticatedHeader(const QuicPacketHeader& header) override;
370 void OnDecryptedPacket(EncryptionLevel level) override;
371 bool OnPacketHeader(const QuicPacketHeader& header) override;
372 void OnFecProtectedPayload(base::StringPiece payload) override;
373 bool OnStreamFrame(const QuicStreamFrame& frame) override;
374 bool OnAckFrame(const QuicAckFrame& frame) override;
375 bool OnStopWaitingFrame(const QuicStopWaitingFrame& frame) override;
376 bool OnPingFrame(const QuicPingFrame& frame) override;
377 bool OnRstStreamFrame(const QuicRstStreamFrame& frame) override;
378 bool OnConnectionCloseFrame(const QuicConnectionCloseFrame& frame) override;
379 bool OnGoAwayFrame(const QuicGoAwayFrame& frame) override;
380 bool OnWindowUpdateFrame(const QuicWindowUpdateFrame& frame) override;
381 bool OnBlockedFrame(const QuicBlockedFrame& frame) override;
382 void OnFecData(const QuicFecData& fec) override;
383 void OnPacketComplete() override;
385 // QuicPacketGenerator::DelegateInterface
386 bool ShouldGeneratePacket(HasRetransmittableData retransmittable,
387 IsHandshake handshake) override;
388 void PopulateAckFrame(QuicAckFrame* ack) override;
389 void PopulateStopWaitingFrame(QuicStopWaitingFrame* stop_waiting) override;
390 void OnSerializedPacket(const SerializedPacket& packet) override;
391 void OnResetFecGroup() override;
393 // QuicSentPacketManager::NetworkChangeVisitor
394 void OnCongestionWindowChange() override;
395 void OnRttChange() override;
397 // Called by the crypto stream when the handshake completes. In the server's
398 // case this is when the SHLO has been ACKed. Clients call this on receipt of
399 // the SHLO.
400 void OnHandshakeComplete();
402 // Accessors
403 void set_visitor(QuicConnectionVisitorInterface* visitor) {
404 visitor_ = visitor;
406 void set_debug_visitor(QuicConnectionDebugVisitor* debug_visitor) {
407 debug_visitor_ = debug_visitor;
408 packet_generator_.set_debug_delegate(debug_visitor);
409 sent_packet_manager_.set_debug_delegate(debug_visitor);
411 const IPEndPoint& self_address() const { return self_address_; }
412 const IPEndPoint& peer_address() const { return peer_address_; }
413 QuicConnectionId connection_id() const { return connection_id_; }
414 const QuicClock* clock() const { return clock_; }
415 QuicRandom* random_generator() const { return random_generator_; }
416 QuicByteCount max_packet_length() const;
417 void set_max_packet_length(QuicByteCount length);
419 bool connected() const { return connected_; }
421 // Must only be called on client connections.
422 const QuicVersionVector& server_supported_versions() const {
423 DCHECK_EQ(Perspective::IS_CLIENT, perspective_);
424 return server_supported_versions_;
427 size_t NumFecGroups() const { return group_map_.size(); }
429 // Testing only.
430 size_t NumQueuedPackets() const { return queued_packets_.size(); }
432 QuicEncryptedPacket* ReleaseConnectionClosePacket() {
433 return connection_close_packet_.release();
436 // Returns true if the underlying UDP socket is writable, there is
437 // no queued data and the connection is not congestion-control
438 // blocked.
439 bool CanWriteStreamData();
441 // Returns true if the connection has queued packets or frames.
442 bool HasQueuedData() const;
444 // Sets the overall and idle state connection timeouts.
445 void SetNetworkTimeouts(QuicTime::Delta overall_timeout,
446 QuicTime::Delta idle_timeout);
448 // If the connection has timed out, this will close the connection.
449 // Otherwise, it will reschedule the timeout alarm.
450 void CheckForTimeout();
452 // Sends a ping, and resets the ping alarm.
453 void SendPing();
455 // Sets up a packet with an QuicAckFrame and sends it out.
456 void SendAck();
458 // Called when an RTO fires. Resets the retransmission alarm if there are
459 // remaining unacked packets.
460 void OnRetransmissionTimeout();
462 // Called when a data packet is sent. Starts an alarm if the data sent in
463 // |sequence_number| was FEC protected.
464 void MaybeSetFecAlarm(QuicPacketSequenceNumber sequence_number);
466 // Retransmits all unacked packets with retransmittable frames if
467 // |retransmission_type| is ALL_UNACKED_PACKETS, otherwise retransmits only
468 // initially encrypted packets. Used when the negotiated protocol version is
469 // different from what was initially assumed and when the initial encryption
470 // changes.
471 void RetransmitUnackedPackets(TransmissionType retransmission_type);
473 // Calls |sent_packet_manager_|'s NeuterUnencryptedPackets. Used when the
474 // connection becomes forward secure and hasn't received acks for all packets.
475 void NeuterUnencryptedPackets();
477 // Changes the encrypter used for level |level| to |encrypter|. The function
478 // takes ownership of |encrypter|.
479 void SetEncrypter(EncryptionLevel level, QuicEncrypter* encrypter);
481 // SetDefaultEncryptionLevel sets the encryption level that will be applied
482 // to new packets.
483 void SetDefaultEncryptionLevel(EncryptionLevel level);
485 // SetDecrypter sets the primary decrypter, replacing any that already exists,
486 // and takes ownership. If an alternative decrypter is in place then the
487 // function DCHECKs. This is intended for cases where one knows that future
488 // packets will be using the new decrypter and the previous decrypter is now
489 // obsolete. |level| indicates the encryption level of the new decrypter.
490 void SetDecrypter(QuicDecrypter* decrypter, EncryptionLevel level);
492 // SetAlternativeDecrypter sets a decrypter that may be used to decrypt
493 // future packets and takes ownership of it. |level| indicates the encryption
494 // level of the decrypter. If |latch_once_used| is true, then the first time
495 // that the decrypter is successful it will replace the primary decrypter.
496 // Otherwise both decrypters will remain active and the primary decrypter
497 // will be the one last used.
498 void SetAlternativeDecrypter(QuicDecrypter* decrypter,
499 EncryptionLevel level,
500 bool latch_once_used);
502 const QuicDecrypter* decrypter() const;
503 const QuicDecrypter* alternative_decrypter() const;
505 Perspective perspective() const { return perspective_; }
507 // Allow easy overriding of truncated connection IDs.
508 void set_can_truncate_connection_ids(bool can) {
509 can_truncate_connection_ids_ = can;
512 // Returns the underlying sent packet manager.
513 const QuicSentPacketManager& sent_packet_manager() const {
514 return sent_packet_manager_;
517 bool CanWrite(HasRetransmittableData retransmittable);
519 // Stores current batch state for connection, puts the connection
520 // into batch mode, and destruction restores the stored batch state.
521 // While the bundler is in scope, any generated frames are bundled
522 // as densely as possible into packets. In addition, this bundler
523 // can be configured to ensure that an ACK frame is included in the
524 // first packet created, if there's new ack information to be sent.
525 class ScopedPacketBundler {
526 public:
527 // In addition to all outgoing frames being bundled when the
528 // bundler is in scope, setting |include_ack| to true ensures that
529 // an ACK frame is opportunistically bundled with the first
530 // outgoing packet.
531 ScopedPacketBundler(QuicConnection* connection, AckBundling send_ack);
532 ~ScopedPacketBundler();
534 private:
535 QuicConnection* connection_;
536 bool already_in_batch_mode_;
539 QuicPacketSequenceNumber sequence_number_of_last_sent_packet() const {
540 return sequence_number_of_last_sent_packet_;
542 const QuicPacketWriter* writer() const { return writer_; }
544 bool is_secure() const { return is_secure_; }
546 protected:
547 // Packets which have not been written to the wire.
548 // Owns the QuicPacket* packet.
549 struct QueuedPacket {
550 QueuedPacket(SerializedPacket packet,
551 EncryptionLevel level);
552 QueuedPacket(SerializedPacket packet,
553 EncryptionLevel level,
554 TransmissionType transmission_type,
555 QuicPacketSequenceNumber original_sequence_number);
557 SerializedPacket serialized_packet;
558 const EncryptionLevel encryption_level;
559 TransmissionType transmission_type;
560 // The packet's original sequence number if it is a retransmission.
561 // Otherwise it must be 0.
562 QuicPacketSequenceNumber original_sequence_number;
565 // Do any work which logically would be done in OnPacket but can not be
566 // safely done until the packet is validated. Returns true if the packet
567 // can be handled, false otherwise.
568 virtual bool ProcessValidatedPacket();
570 // Send a packet to the peer, and takes ownership of the packet if the packet
571 // cannot be written immediately.
572 virtual void SendOrQueuePacket(QueuedPacket packet);
574 QuicConnectionHelperInterface* helper() { return helper_; }
576 // Selects and updates the version of the protocol being used by selecting a
577 // version from |available_versions| which is also supported. Returns true if
578 // such a version exists, false otherwise.
579 bool SelectMutualVersion(const QuicVersionVector& available_versions);
581 QuicPacketWriter* writer() { return writer_; }
583 bool peer_port_changed() const { return peer_port_changed_; }
585 private:
586 friend class test::QuicConnectionPeer;
587 friend class test::PacketSavingConnection;
589 typedef std::list<QueuedPacket> QueuedPacketList;
590 typedef std::map<QuicFecGroupNumber, QuicFecGroup*> FecGroupMap;
592 // Writes the given packet to socket, encrypted with packet's
593 // encryption_level. Returns true on successful write, and false if the writer
594 // was blocked and the write needs to be tried again. Notifies the
595 // SentPacketManager when the write is successful and sets
596 // retransmittable frames to nullptr.
597 // Saves the connection close packet for later transmission, even if the
598 // writer is write blocked.
599 bool WritePacket(QueuedPacket* packet);
601 // Does the main work of WritePacket, but does not delete the packet or
602 // retransmittable frames upon success.
603 bool WritePacketInner(QueuedPacket* packet);
605 // Make sure an ack we got from our peer is sane.
606 bool ValidateAckFrame(const QuicAckFrame& incoming_ack);
608 // Make sure a stop waiting we got from our peer is sane.
609 bool ValidateStopWaitingFrame(const QuicStopWaitingFrame& stop_waiting);
611 // Sends a version negotiation packet to the peer.
612 void SendVersionNegotiationPacket();
614 // Clears any accumulated frames from the last received packet.
615 void ClearLastFrames();
617 // Closes the connection if the sent or received packet manager are tracking
618 // too many outstanding packets.
619 void MaybeCloseIfTooManyOutstandingPackets();
621 // Writes as many queued packets as possible. The connection must not be
622 // blocked when this is called.
623 void WriteQueuedPackets();
625 // Writes as many pending retransmissions as possible.
626 void WritePendingRetransmissions();
628 // Returns true if the packet should be discarded and not sent.
629 bool ShouldDiscardPacket(const QueuedPacket& packet);
631 // Queues |packet| in the hopes that it can be decrypted in the
632 // future, when a new key is installed.
633 void QueueUndecryptablePacket(const QuicEncryptedPacket& packet);
635 // Attempts to process any queued undecryptable packets.
636 void MaybeProcessUndecryptablePackets();
638 // If a packet can be revived from the current FEC group, then
639 // revive and process the packet.
640 void MaybeProcessRevivedPacket();
642 void ProcessAckFrame(const QuicAckFrame& incoming_ack);
644 void ProcessStopWaitingFrame(const QuicStopWaitingFrame& stop_waiting);
646 // Queues an ack or sets the ack alarm when an incoming packet arrives that
647 // should be acked.
648 void MaybeQueueAck();
650 // Checks if the last packet should instigate an ack.
651 bool ShouldLastPacketInstigateAck() const;
653 // Checks if the peer is waiting for packets that have been given up on, and
654 // therefore an ack frame should be sent with a larger least_unacked.
655 void UpdateStopWaitingCount();
657 // Sends any packets which are a response to the last packet, including both
658 // acks and pending writes if an ack opened the congestion window.
659 void MaybeSendInResponseToPacket();
661 // Gets the least unacked sequence number, which is the next sequence number
662 // to be sent if there are no outstanding packets.
663 QuicPacketSequenceNumber GetLeastUnacked() const;
665 // Get the FEC group associate with the last processed packet or nullptr, if
666 // the group has already been deleted.
667 QuicFecGroup* GetFecGroup();
669 // Closes any FEC groups protecting packets before |sequence_number|.
670 void CloseFecGroupsBefore(QuicPacketSequenceNumber sequence_number);
672 // Sets the timeout alarm to the appropriate value, if any.
673 void SetTimeoutAlarm();
675 // Sets the ping alarm to the appropriate value, if any.
676 void SetPingAlarm();
678 // On arrival of a new packet, checks to see if the socket addresses have
679 // changed since the last packet we saw on this connection.
680 void CheckForAddressMigration(const IPEndPoint& self_address,
681 const IPEndPoint& peer_address);
683 HasRetransmittableData IsRetransmittable(const QueuedPacket& packet);
684 bool IsConnectionClose(const QueuedPacket& packet);
686 QuicFramer framer_;
687 QuicConnectionHelperInterface* helper_; // Not owned.
688 QuicPacketWriter* writer_; // Owned or not depending on |owns_writer_|.
689 bool owns_writer_;
690 // Encryption level for new packets. Should only be changed via
691 // SetDefaultEncryptionLevel().
692 EncryptionLevel encryption_level_;
693 bool has_forward_secure_encrypter_;
694 // The sequence number of the first packet which will be encrypted with the
695 // foward-secure encrypter, even if the peer has not started sending
696 // forward-secure packets.
697 QuicPacketSequenceNumber first_required_forward_secure_packet_;
698 const QuicClock* clock_;
699 QuicRandom* random_generator_;
701 const QuicConnectionId connection_id_;
702 // Address on the last successfully processed packet received from the
703 // client.
704 IPEndPoint self_address_;
705 IPEndPoint peer_address_;
706 // Used to store latest peer port to possibly migrate to later.
707 uint16 migrating_peer_port_;
709 // True if the last packet has gotten far enough in the framer to be
710 // decrypted.
711 bool last_packet_decrypted_;
712 bool last_packet_revived_; // True if the last packet was revived from FEC.
713 QuicByteCount last_size_; // Size of the last received packet.
714 EncryptionLevel last_decrypted_packet_level_;
715 QuicPacketHeader last_header_;
716 std::vector<QuicStreamFrame> last_stream_frames_;
717 std::vector<QuicAckFrame> last_ack_frames_;
718 std::vector<QuicStopWaitingFrame> last_stop_waiting_frames_;
719 std::vector<QuicRstStreamFrame> last_rst_frames_;
720 std::vector<QuicGoAwayFrame> last_goaway_frames_;
721 std::vector<QuicWindowUpdateFrame> last_window_update_frames_;
722 std::vector<QuicBlockedFrame> last_blocked_frames_;
723 std::vector<QuicPingFrame> last_ping_frames_;
724 std::vector<QuicConnectionCloseFrame> last_close_frames_;
726 // Track some peer state so we can do less bookkeeping
727 // Largest sequence sent by the peer which had an ack frame (latest ack info).
728 QuicPacketSequenceNumber largest_seen_packet_with_ack_;
730 // Largest sequence number sent by the peer which had a stop waiting frame.
731 QuicPacketSequenceNumber largest_seen_packet_with_stop_waiting_;
733 // Collection of packets which were received before encryption was
734 // established, but which could not be decrypted. We buffer these on
735 // the assumption that they could not be processed because they were
736 // sent with the INITIAL encryption and the CHLO message was lost.
737 std::deque<QuicEncryptedPacket*> undecryptable_packets_;
739 // Maximum number of undecryptable packets the connection will store.
740 size_t max_undecryptable_packets_;
742 // When the version negotiation packet could not be sent because the socket
743 // was not writable, this is set to true.
744 bool pending_version_negotiation_packet_;
746 // When packets could not be sent because the socket was not writable,
747 // they are added to this list. All corresponding frames are in
748 // unacked_packets_ if they are to be retransmitted.
749 QueuedPacketList queued_packets_;
751 // Contains the connection close packet if the connection has been closed.
752 scoped_ptr<QuicEncryptedPacket> connection_close_packet_;
754 // When true, the connection does not send a close packet on timeout.
755 bool silent_close_enabled_;
757 FecGroupMap group_map_;
759 QuicReceivedPacketManager received_packet_manager_;
760 QuicSentEntropyManager sent_entropy_manager_;
762 // Indicates whether an ack should be sent the next time we try to write.
763 bool ack_queued_;
764 // Indicates how many consecutive packets have arrived without sending an ack.
765 QuicPacketCount num_packets_received_since_last_ack_sent_;
766 // Indicates how many consecutive times an ack has arrived which indicates
767 // the peer needs to stop waiting for some packets.
768 int stop_waiting_count_;
770 // An alarm that fires when an ACK should be sent to the peer.
771 scoped_ptr<QuicAlarm> ack_alarm_;
772 // An alarm that fires when a packet needs to be retransmitted.
773 scoped_ptr<QuicAlarm> retransmission_alarm_;
774 // An alarm that is scheduled when the SentPacketManager requires a delay
775 // before sending packets and fires when the packet may be sent.
776 scoped_ptr<QuicAlarm> send_alarm_;
777 // An alarm that is scheduled when the connection can still write and there
778 // may be more data to send.
779 scoped_ptr<QuicAlarm> resume_writes_alarm_;
780 // An alarm that fires when the connection may have timed out.
781 scoped_ptr<QuicAlarm> timeout_alarm_;
782 // An alarm that fires when a ping should be sent.
783 scoped_ptr<QuicAlarm> ping_alarm_;
785 // Neither visitor is owned by this class.
786 QuicConnectionVisitorInterface* visitor_;
787 QuicConnectionDebugVisitor* debug_visitor_;
789 QuicPacketGenerator packet_generator_;
791 // An alarm that fires when an FEC packet should be sent.
792 scoped_ptr<QuicAlarm> fec_alarm_;
794 // Network idle time before we kill of this connection.
795 QuicTime::Delta idle_network_timeout_;
796 // Overall connection timeout.
797 QuicTime::Delta overall_connection_timeout_;
799 // Statistics for this session.
800 QuicConnectionStats stats_;
802 // The time that we got a packet for this connection.
803 // This is used for timeouts, and does not indicate the packet was processed.
804 QuicTime time_of_last_received_packet_;
806 // The last time this connection began sending a new (non-retransmitted)
807 // packet.
808 QuicTime time_of_last_sent_new_packet_;
810 // Sequence number of the last sent packet. Packets are guaranteed to be sent
811 // in sequence number order.
812 QuicPacketSequenceNumber sequence_number_of_last_sent_packet_;
814 // Sent packet manager which tracks the status of packets sent by this
815 // connection and contains the send and receive algorithms to determine when
816 // to send packets.
817 QuicSentPacketManager sent_packet_manager_;
819 // The state of connection in version negotiation finite state machine.
820 QuicVersionNegotiationState version_negotiation_state_;
822 // Tracks if the connection was created by the server or the client.
823 Perspective perspective_;
825 // True by default. False if we've received or sent an explicit connection
826 // close.
827 bool connected_;
829 // Set to true if the UDP packet headers have a new IP address for the peer.
830 // If true, do not perform connection migration.
831 bool peer_ip_changed_;
833 // Set to true if the UDP packet headers have a new port for the peer.
834 // If true, and the IP has not changed, then we can migrate the connection.
835 bool peer_port_changed_;
837 // Set to true if the UDP packet headers are addressed to a different IP.
838 // We do not support connection migration when the self IP changed.
839 bool self_ip_changed_;
841 // Set to true if the UDP packet headers are addressed to a different port.
842 // We do not support connection migration when the self port changed.
843 bool self_port_changed_;
845 // Set to false if the connection should not send truncated connection IDs to
846 // the peer, even if the peer supports it.
847 bool can_truncate_connection_ids_;
849 // If non-empty this contains the set of versions received in a
850 // version negotiation packet.
851 QuicVersionVector server_supported_versions_;
853 // True if this is a secure QUIC connection.
854 bool is_secure_;
856 DISALLOW_COPY_AND_ASSIGN(QuicConnection);
859 } // namespace net
861 #endif // NET_QUIC_QUIC_CONNECTION_H_