Hookup the PDF extension to the chrome extensions zoom API
[chromium-blink-merge.git] / net / quic / quic_connection.h
blob52ee6bb65d07d3b01afc52e5d7d917489dc864cf
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/logging.h"
28 #include "net/base/iovec.h"
29 #include "net/base/ip_endpoint.h"
30 #include "net/quic/iovector.h"
31 #include "net/quic/quic_ack_notifier.h"
32 #include "net/quic/quic_ack_notifier_manager.h"
33 #include "net/quic/quic_alarm.h"
34 #include "net/quic/quic_blocked_writer_interface.h"
35 #include "net/quic/quic_connection_stats.h"
36 #include "net/quic/quic_packet_creator.h"
37 #include "net/quic/quic_packet_generator.h"
38 #include "net/quic/quic_packet_writer.h"
39 #include "net/quic/quic_protocol.h"
40 #include "net/quic/quic_received_packet_manager.h"
41 #include "net/quic/quic_sent_entropy_manager.h"
42 #include "net/quic/quic_sent_packet_manager.h"
43 #include "net/quic/quic_types.h"
45 namespace net {
47 class QuicClock;
48 class QuicConfig;
49 class QuicConnection;
50 class QuicDecrypter;
51 class QuicEncrypter;
52 class QuicFecGroup;
53 class QuicRandom;
55 namespace test {
56 class QuicConnectionPeer;
57 } // namespace test
59 // Class that receives callbacks from the connection when frames are received
60 // and when other interesting events happen.
61 class NET_EXPORT_PRIVATE QuicConnectionVisitorInterface {
62 public:
63 virtual ~QuicConnectionVisitorInterface() {}
65 // A simple visitor interface for dealing with data frames.
66 virtual void OnStreamFrames(const std::vector<QuicStreamFrame>& frames) = 0;
68 // The session should process all WINDOW_UPDATE frames, adjusting both stream
69 // and connection level flow control windows.
70 virtual void OnWindowUpdateFrames(
71 const std::vector<QuicWindowUpdateFrame>& frames) = 0;
73 // BLOCKED frames tell us that the peer believes it is flow control blocked on
74 // a specified stream. If the session at this end disagrees, something has
75 // gone wrong with our flow control accounting.
76 virtual void OnBlockedFrames(const std::vector<QuicBlockedFrame>& frames) = 0;
78 // Called when the stream is reset by the peer.
79 virtual void OnRstStream(const QuicRstStreamFrame& frame) = 0;
81 // Called when the connection is going away according to the peer.
82 virtual void OnGoAway(const QuicGoAwayFrame& frame) = 0;
84 // Called when the connection is closed either locally by the framer, or
85 // remotely by the peer.
86 virtual void OnConnectionClosed(QuicErrorCode error, bool from_peer) = 0;
88 // Called when the connection failed to write because the socket was blocked.
89 virtual void OnWriteBlocked() = 0;
91 // Called once a specific QUIC version is agreed by both endpoints.
92 virtual void OnSuccessfulVersionNegotiation(const QuicVersion& version) = 0;
94 // Called when a blocked socket becomes writable.
95 virtual void OnCanWrite() = 0;
97 // Called to ask if the visitor wants to schedule write resumption as it both
98 // has pending data to write, and is able to write (e.g. based on flow control
99 // limits).
100 // Writes may be pending because they were write-blocked, congestion-throttled
101 // or yielded to other connections.
102 virtual bool WillingAndAbleToWrite() const = 0;
104 // Called to ask if any handshake messages are pending in this visitor.
105 virtual bool HasPendingHandshake() const = 0;
107 // Called to ask if any streams are open in this visitor, excluding the
108 // reserved crypto and headers stream.
109 virtual bool HasOpenDataStreams() const = 0;
112 // Interface which gets callbacks from the QuicConnection at interesting
113 // points. Implementations must not mutate the state of the connection
114 // as a result of these callbacks.
115 class NET_EXPORT_PRIVATE QuicConnectionDebugVisitor
116 : public QuicPacketGenerator::DebugDelegate,
117 public QuicSentPacketManager::DebugDelegate {
118 public:
119 virtual ~QuicConnectionDebugVisitor() {}
121 // Called when a packet has been sent.
122 virtual void OnPacketSent(QuicPacketSequenceNumber sequence_number,
123 EncryptionLevel level,
124 TransmissionType transmission_type,
125 const QuicEncryptedPacket& packet,
126 WriteResult result) {}
128 // Called when the contents of a packet have been retransmitted as
129 // a new packet.
130 virtual void OnPacketRetransmitted(
131 QuicPacketSequenceNumber old_sequence_number,
132 QuicPacketSequenceNumber new_sequence_number) {}
134 // Called when a packet has been received, but before it is
135 // validated or parsed.
136 virtual void OnPacketReceived(const IPEndPoint& self_address,
137 const IPEndPoint& peer_address,
138 const QuicEncryptedPacket& packet) {}
140 // Called when the protocol version on the received packet doensn't match
141 // current protocol version of the connection.
142 virtual void OnProtocolVersionMismatch(QuicVersion version) {}
144 // Called when the complete header of a packet has been parsed.
145 virtual void OnPacketHeader(const QuicPacketHeader& header) {}
147 // Called when a StreamFrame has been parsed.
148 virtual void OnStreamFrame(const QuicStreamFrame& frame) {}
150 // Called when a AckFrame has been parsed.
151 virtual void OnAckFrame(const QuicAckFrame& frame) {}
153 // Called when a CongestionFeedbackFrame has been parsed.
154 virtual void OnCongestionFeedbackFrame(
155 const QuicCongestionFeedbackFrame& frame) {}
157 // Called when a StopWaitingFrame has been parsed.
158 virtual void OnStopWaitingFrame(const QuicStopWaitingFrame& frame) {}
160 // Called when a Ping has been parsed.
161 virtual void OnPingFrame(const QuicPingFrame& frame) {}
163 // Called when a GoAway has been parsed.
164 virtual void OnGoAwayFrame(const QuicGoAwayFrame& frame) {}
166 // Called when a RstStreamFrame has been parsed.
167 virtual void OnRstStreamFrame(const QuicRstStreamFrame& frame) {}
169 // Called when a ConnectionCloseFrame has been parsed.
170 virtual void OnConnectionCloseFrame(
171 const QuicConnectionCloseFrame& frame) {}
173 // Called when a WindowUpdate has been parsed.
174 virtual void OnWindowUpdateFrame(const QuicWindowUpdateFrame& frame) {}
176 // Called when a BlockedFrame has been parsed.
177 virtual void OnBlockedFrame(const QuicBlockedFrame& frame) {}
179 // Called when a public reset packet has been received.
180 virtual void OnPublicResetPacket(const QuicPublicResetPacket& packet) {}
182 // Called when a version negotiation packet has been received.
183 virtual void OnVersionNegotiationPacket(
184 const QuicVersionNegotiationPacket& packet) {}
186 // Called after a packet has been successfully parsed which results
187 // in the revival of a packet via FEC.
188 virtual void OnRevivedPacket(const QuicPacketHeader& revived_header,
189 base::StringPiece payload) {}
192 class NET_EXPORT_PRIVATE QuicConnectionHelperInterface {
193 public:
194 virtual ~QuicConnectionHelperInterface() {}
196 // Returns a QuicClock to be used for all time related functions.
197 virtual const QuicClock* GetClock() const = 0;
199 // Returns a QuicRandom to be used for all random number related functions.
200 virtual QuicRandom* GetRandomGenerator() = 0;
202 // Creates a new platform-specific alarm which will be configured to
203 // notify |delegate| when the alarm fires. Caller takes ownership
204 // of the new alarm, which will not yet be "set" to fire.
205 virtual QuicAlarm* CreateAlarm(QuicAlarm::Delegate* delegate) = 0;
208 class NET_EXPORT_PRIVATE QuicConnection
209 : public QuicFramerVisitorInterface,
210 public QuicBlockedWriterInterface,
211 public QuicPacketGenerator::DelegateInterface {
212 public:
213 enum PacketType {
214 NORMAL,
215 QUEUED,
216 CONNECTION_CLOSE
219 enum AckBundling {
220 NO_ACK = 0,
221 SEND_ACK = 1,
222 BUNDLE_PENDING_ACK = 2,
225 // Constructs a new QuicConnection for |connection_id| and |address|.
226 // |helper| and |writer| must outlive this connection.
227 QuicConnection(QuicConnectionId connection_id,
228 IPEndPoint address,
229 QuicConnectionHelperInterface* helper,
230 QuicPacketWriter* writer,
231 bool is_server,
232 const QuicVersionVector& supported_versions);
233 virtual ~QuicConnection();
235 // Sets connection parameters from the supplied |config|.
236 void SetFromConfig(const QuicConfig& config);
238 // Send the data in |data| to the peer in as few packets as possible.
239 // Returns a pair with the number of bytes consumed from data, and a boolean
240 // indicating if the fin bit was consumed. This does not indicate the data
241 // has been sent on the wire: it may have been turned into a packet and queued
242 // if the socket was unexpectedly blocked. |fec_protection| indicates if
243 // data is to be FEC protected. Note that data that is sent immediately
244 // following MUST_FEC_PROTECT data may get protected by falling within the
245 // same FEC group.
246 // If |delegate| is provided, then it will be informed once ACKs have been
247 // received for all the packets written in this call.
248 // The |delegate| is not owned by the QuicConnection and must outlive it.
249 QuicConsumedData SendStreamData(QuicStreamId id,
250 const IOVector& data,
251 QuicStreamOffset offset,
252 bool fin,
253 FecProtection fec_protection,
254 QuicAckNotifier::DelegateInterface* delegate);
256 // Send a RST_STREAM frame to the peer.
257 virtual void SendRstStream(QuicStreamId id,
258 QuicRstStreamErrorCode error,
259 QuicStreamOffset bytes_written);
261 // Send a BLOCKED frame to the peer.
262 virtual void SendBlocked(QuicStreamId id);
264 // Send a WINDOW_UPDATE frame to the peer.
265 virtual void SendWindowUpdate(QuicStreamId id,
266 QuicStreamOffset byte_offset);
268 // Sends the connection close packet without affecting the state of the
269 // connection. This should only be called if the session is actively being
270 // destroyed: otherwise call SendConnectionCloseWithDetails instead.
271 virtual void SendConnectionClosePacket(QuicErrorCode error,
272 const std::string& details);
274 // Sends a connection close frame to the peer, and closes the connection by
275 // calling CloseConnection(notifying the visitor as it does so).
276 virtual void SendConnectionClose(QuicErrorCode error);
277 virtual void SendConnectionCloseWithDetails(QuicErrorCode error,
278 const std::string& details);
279 // Notifies the visitor of the close and marks the connection as disconnected.
280 virtual void CloseConnection(QuicErrorCode error, bool from_peer) OVERRIDE;
281 virtual void SendGoAway(QuicErrorCode error,
282 QuicStreamId last_good_stream_id,
283 const std::string& reason);
285 // Returns statistics tracked for this connection.
286 const QuicConnectionStats& GetStats();
288 // Processes an incoming UDP packet (consisting of a QuicEncryptedPacket) from
289 // the peer. If processing this packet permits a packet to be revived from
290 // its FEC group that packet will be revived and processed.
291 virtual void ProcessUdpPacket(const IPEndPoint& self_address,
292 const IPEndPoint& peer_address,
293 const QuicEncryptedPacket& packet);
295 // QuicBlockedWriterInterface
296 // Called when the underlying connection becomes writable to allow queued
297 // writes to happen.
298 virtual void OnCanWrite() OVERRIDE;
300 // Called when a packet has been finally sent to the network.
301 bool OnPacketSent(WriteResult result);
303 // If the socket is not blocked, writes queued packets.
304 void WriteIfNotBlocked();
306 // Do any work which logically would be done in OnPacket but can not be
307 // safely done until the packet is validated. Returns true if the packet
308 // can be handled, false otherwise.
309 virtual bool ProcessValidatedPacket();
311 // The version of the protocol this connection is using.
312 QuicVersion version() const { return framer_.version(); }
314 // The versions of the protocol that this connection supports.
315 const QuicVersionVector& supported_versions() const {
316 return framer_.supported_versions();
319 // From QuicFramerVisitorInterface
320 virtual void OnError(QuicFramer* framer) OVERRIDE;
321 virtual bool OnProtocolVersionMismatch(QuicVersion received_version) OVERRIDE;
322 virtual void OnPacket() OVERRIDE;
323 virtual void OnPublicResetPacket(
324 const QuicPublicResetPacket& packet) OVERRIDE;
325 virtual void OnVersionNegotiationPacket(
326 const QuicVersionNegotiationPacket& packet) OVERRIDE;
327 virtual void OnRevivedPacket() OVERRIDE;
328 virtual bool OnUnauthenticatedPublicHeader(
329 const QuicPacketPublicHeader& header) OVERRIDE;
330 virtual bool OnUnauthenticatedHeader(const QuicPacketHeader& header) OVERRIDE;
331 virtual void OnDecryptedPacket(EncryptionLevel level) OVERRIDE;
332 virtual bool OnPacketHeader(const QuicPacketHeader& header) OVERRIDE;
333 virtual void OnFecProtectedPayload(base::StringPiece payload) OVERRIDE;
334 virtual bool OnStreamFrame(const QuicStreamFrame& frame) OVERRIDE;
335 virtual bool OnAckFrame(const QuicAckFrame& frame) OVERRIDE;
336 virtual bool OnCongestionFeedbackFrame(
337 const QuicCongestionFeedbackFrame& frame) OVERRIDE;
338 virtual bool OnStopWaitingFrame(const QuicStopWaitingFrame& frame) OVERRIDE;
339 virtual bool OnPingFrame(const QuicPingFrame& frame) OVERRIDE;
340 virtual bool OnRstStreamFrame(const QuicRstStreamFrame& frame) OVERRIDE;
341 virtual bool OnConnectionCloseFrame(
342 const QuicConnectionCloseFrame& frame) OVERRIDE;
343 virtual bool OnGoAwayFrame(const QuicGoAwayFrame& frame) OVERRIDE;
344 virtual bool OnWindowUpdateFrame(const QuicWindowUpdateFrame& frame) OVERRIDE;
345 virtual bool OnBlockedFrame(const QuicBlockedFrame& frame) OVERRIDE;
346 virtual void OnFecData(const QuicFecData& fec) OVERRIDE;
347 virtual void OnPacketComplete() OVERRIDE;
349 // QuicPacketGenerator::DelegateInterface
350 virtual bool ShouldGeneratePacket(TransmissionType transmission_type,
351 HasRetransmittableData retransmittable,
352 IsHandshake handshake) OVERRIDE;
353 virtual QuicAckFrame* CreateAckFrame() OVERRIDE;
354 virtual QuicCongestionFeedbackFrame* CreateFeedbackFrame() OVERRIDE;
355 virtual QuicStopWaitingFrame* CreateStopWaitingFrame() OVERRIDE;
356 virtual bool OnSerializedPacket(const SerializedPacket& packet) OVERRIDE;
358 // Accessors
359 void set_visitor(QuicConnectionVisitorInterface* visitor) {
360 visitor_ = visitor;
362 void set_debug_visitor(QuicConnectionDebugVisitor* debug_visitor) {
363 debug_visitor_ = debug_visitor;
364 packet_generator_.set_debug_delegate(debug_visitor);
365 sent_packet_manager_.set_debug_delegate(debug_visitor);
367 const IPEndPoint& self_address() const { return self_address_; }
368 const IPEndPoint& peer_address() const { return peer_address_; }
369 QuicConnectionId connection_id() const { return connection_id_; }
370 const QuicClock* clock() const { return clock_; }
371 QuicRandom* random_generator() const { return random_generator_; }
372 size_t max_packet_length() const;
373 void set_max_packet_length(size_t length);
375 bool connected() const { return connected_; }
377 // Must only be called on client connections.
378 const QuicVersionVector& server_supported_versions() const {
379 DCHECK(!is_server_);
380 return server_supported_versions_;
383 size_t NumFecGroups() const { return group_map_.size(); }
385 // Testing only.
386 size_t NumQueuedPackets() const { return queued_packets_.size(); }
388 QuicEncryptedPacket* ReleaseConnectionClosePacket() {
389 return connection_close_packet_.release();
392 // Returns true if the underlying UDP socket is writable, there is
393 // no queued data and the connection is not congestion-control
394 // blocked.
395 bool CanWriteStreamData();
397 // Returns true if the connection has queued packets or frames.
398 bool HasQueuedData() const;
400 // Sets (or resets) the idle state connection timeout. Also, checks and times
401 // out the connection if network timer has expired for |timeout|.
402 void SetIdleNetworkTimeout(QuicTime::Delta timeout);
403 // Sets (or resets) the total time delta the connection can be alive for.
404 // Also, checks and times out the connection if timer has expired for
405 // |timeout|. Used to limit the time a connection can be alive before crypto
406 // handshake finishes.
407 void SetOverallConnectionTimeout(QuicTime::Delta timeout);
409 // If the connection has timed out, this will close the connection and return
410 // true. Otherwise, it will return false and will reset the timeout alarm.
411 bool CheckForTimeout();
413 // Sends a ping, and resets the ping alarm.
414 void SendPing();
416 // Sets up a packet with an QuicAckFrame and sends it out.
417 void SendAck();
419 // Called when an RTO fires. Resets the retransmission alarm if there are
420 // remaining unacked packets.
421 void OnRetransmissionTimeout();
423 // Retransmits all unacked packets with retransmittable frames if
424 // |retransmission_type| is ALL_PACKETS, otherwise retransmits only initially
425 // encrypted packets. Used when the negotiated protocol version is different
426 // from what was initially assumed and when the visitor wants to re-transmit
427 // initially encrypted packets when the initial encrypter changes.
428 void RetransmitUnackedPackets(RetransmissionType retransmission_type);
430 // Calls |sent_packet_manager_|'s NeuterUnencryptedPackets. Used when the
431 // connection becomes forward secure and hasn't received acks for all packets.
432 void NeuterUnencryptedPackets();
434 // Changes the encrypter used for level |level| to |encrypter|. The function
435 // takes ownership of |encrypter|.
436 void SetEncrypter(EncryptionLevel level, QuicEncrypter* encrypter);
437 const QuicEncrypter* encrypter(EncryptionLevel level) const;
439 // SetDefaultEncryptionLevel sets the encryption level that will be applied
440 // to new packets.
441 void SetDefaultEncryptionLevel(EncryptionLevel level);
443 // SetDecrypter sets the primary decrypter, replacing any that already exists,
444 // and takes ownership. If an alternative decrypter is in place then the
445 // function DCHECKs. This is intended for cases where one knows that future
446 // packets will be using the new decrypter and the previous decrypter is now
447 // obsolete. |level| indicates the encryption level of the new decrypter.
448 void SetDecrypter(QuicDecrypter* decrypter, EncryptionLevel level);
450 // SetAlternativeDecrypter sets a decrypter that may be used to decrypt
451 // future packets and takes ownership of it. |level| indicates the encryption
452 // level of the decrypter. If |latch_once_used| is true, then the first time
453 // that the decrypter is successful it will replace the primary decrypter.
454 // Otherwise both decrypters will remain active and the primary decrypter
455 // will be the one last used.
456 void SetAlternativeDecrypter(QuicDecrypter* decrypter,
457 EncryptionLevel level,
458 bool latch_once_used);
460 const QuicDecrypter* decrypter() const;
461 const QuicDecrypter* alternative_decrypter() const;
463 bool is_server() const { return is_server_; }
465 // Returns the underlying sent packet manager.
466 const QuicSentPacketManager& sent_packet_manager() const {
467 return sent_packet_manager_;
470 bool CanWrite(HasRetransmittableData retransmittable);
472 // Stores current batch state for connection, puts the connection
473 // into batch mode, and destruction restores the stored batch state.
474 // While the bundler is in scope, any generated frames are bundled
475 // as densely as possible into packets. In addition, this bundler
476 // can be configured to ensure that an ACK frame is included in the
477 // first packet created, if there's new ack information to be sent.
478 class ScopedPacketBundler {
479 public:
480 // In addition to all outgoing frames being bundled when the
481 // bundler is in scope, setting |include_ack| to true ensures that
482 // an ACK frame is opportunistically bundled with the first
483 // outgoing packet.
484 ScopedPacketBundler(QuicConnection* connection, AckBundling send_ack);
485 ~ScopedPacketBundler();
487 private:
488 QuicConnection* connection_;
489 bool already_in_batch_mode_;
492 protected:
493 // Send a packet to the peer using encryption |level|. If |sequence_number|
494 // is present in the |retransmission_map_|, then contents of this packet will
495 // be retransmitted with a new sequence number if it's not acked by the peer.
496 // Deletes |packet| if WritePacket call succeeds, or transfers ownership to
497 // QueuedPacket, ultimately deleted in WriteQueuedPackets. Updates the
498 // entropy map corresponding to |sequence_number| using |entropy_hash|.
499 // |transmission_type| and |retransmittable| are supplied to the congestion
500 // manager, and when |forced| is true, it bypasses the congestion manager.
501 // TODO(wtc): none of the callers check the return value.
502 virtual bool SendOrQueuePacket(EncryptionLevel level,
503 const SerializedPacket& packet,
504 TransmissionType transmission_type);
506 QuicConnectionHelperInterface* helper() { return helper_; }
508 // Selects and updates the version of the protocol being used by selecting a
509 // version from |available_versions| which is also supported. Returns true if
510 // such a version exists, false otherwise.
511 bool SelectMutualVersion(const QuicVersionVector& available_versions);
513 QuicPacketWriter* writer() { return writer_; }
515 bool peer_port_changed() const { return peer_port_changed_; }
517 const QuicReceivedPacketManager& received_packet_manager() {
518 return received_packet_manager_;
521 QuicPacketSequenceNumber sequence_number_of_last_sent_packet() const {
522 return sequence_number_of_last_sent_packet_;
525 private:
526 friend class test::QuicConnectionPeer;
528 // Packets which have not been written to the wire.
529 // Owns the QuicPacket* packet.
530 struct QueuedPacket {
531 QueuedPacket(SerializedPacket packet,
532 EncryptionLevel level,
533 TransmissionType transmission_type);
535 QuicPacketSequenceNumber sequence_number;
536 QuicPacket* packet;
537 const EncryptionLevel encryption_level;
538 TransmissionType transmission_type;
539 HasRetransmittableData retransmittable;
540 IsHandshake handshake;
541 PacketType type;
542 QuicByteCount length;
545 typedef std::list<QueuedPacket> QueuedPacketList;
546 typedef std::map<QuicFecGroupNumber, QuicFecGroup*> FecGroupMap;
548 // Writes the given packet to socket, encrypted with packet's
549 // encryption_level. Returns true on successful write. Behavior is undefined
550 // if connection is not established or broken. A return value of true means
551 // the packet was transmitted and may be destroyed. If the packet is
552 // retransmittable, WritePacket sets up retransmission for a successful write.
553 // If packet is FORCE, then it will be sent immediately and the send scheduler
554 // will not be consulted.
555 bool WritePacket(QueuedPacket packet);
557 // Make sure an ack we got from our peer is sane.
558 bool ValidateAckFrame(const QuicAckFrame& incoming_ack);
560 // Make sure a stop waiting we got from our peer is sane.
561 bool ValidateStopWaitingFrame(const QuicStopWaitingFrame& stop_waiting);
563 // Sends a version negotiation packet to the peer.
564 void SendVersionNegotiationPacket();
566 // Clears any accumulated frames from the last received packet.
567 void ClearLastFrames();
569 // Writes as many queued packets as possible. The connection must not be
570 // blocked when this is called.
571 void WriteQueuedPackets();
573 // Writes as many pending retransmissions as possible.
574 void WritePendingRetransmissions();
576 // Returns true if the packet should be discarded and not sent.
577 bool ShouldDiscardPacket(EncryptionLevel level,
578 QuicPacketSequenceNumber sequence_number,
579 HasRetransmittableData retransmittable);
581 // Queues |packet| in the hopes that it can be decrypted in the
582 // future, when a new key is installed.
583 void QueueUndecryptablePacket(const QuicEncryptedPacket& packet);
585 // Attempts to process any queued undecryptable packets.
586 void MaybeProcessUndecryptablePackets();
588 // If a packet can be revived from the current FEC group, then
589 // revive and process the packet.
590 void MaybeProcessRevivedPacket();
592 void ProcessAckFrame(const QuicAckFrame& incoming_ack);
594 void ProcessStopWaitingFrame(const QuicStopWaitingFrame& stop_waiting);
596 // Update |stop_waiting| for an outgoing ack.
597 void UpdateStopWaiting(QuicStopWaitingFrame* stop_waiting);
599 // Queues an ack or sets the ack alarm when an incoming packet arrives that
600 // should be acked.
601 void MaybeQueueAck();
603 // Checks if the last packet should instigate an ack.
604 bool ShouldLastPacketInstigateAck() const;
606 // Checks if the peer is waiting for packets that have been given up on, and
607 // therefore an ack frame should be sent with a larger least_unacked.
608 void UpdateStopWaitingCount();
610 // Sends any packets which are a response to the last packet, including both
611 // acks and pending writes if an ack opened the congestion window.
612 void MaybeSendInResponseToPacket();
614 // Gets the least unacked sequence number, which is the next sequence number
615 // to be sent if there are no outstanding packets.
616 QuicPacketSequenceNumber GetLeastUnacked() const;
618 // Get the FEC group associate with the last processed packet or NULL, if the
619 // group has already been deleted.
620 QuicFecGroup* GetFecGroup();
622 // Closes any FEC groups protecting packets before |sequence_number|.
623 void CloseFecGroupsBefore(QuicPacketSequenceNumber sequence_number);
625 // Sets the ping alarm to the appropriate value, if any.
626 void SetPingAlarm();
628 // On arrival of a new packet, checks to see if the socket addresses have
629 // changed since the last packet we saw on this connection.
630 void CheckForAddressMigration(const IPEndPoint& self_address,
631 const IPEndPoint& peer_address);
633 QuicFramer framer_;
634 QuicConnectionHelperInterface* helper_; // Not owned.
635 QuicPacketWriter* writer_; // Not owned.
636 EncryptionLevel encryption_level_;
637 const QuicClock* clock_;
638 QuicRandom* random_generator_;
640 const QuicConnectionId connection_id_;
641 // Address on the last successfully processed packet received from the
642 // client.
643 IPEndPoint self_address_;
644 IPEndPoint peer_address_;
645 // Used to store latest peer port to possibly migrate to later.
646 int migrating_peer_port_;
648 bool last_packet_revived_; // True if the last packet was revived from FEC.
649 size_t last_size_; // Size of the last received packet.
650 EncryptionLevel last_decrypted_packet_level_;
651 QuicPacketHeader last_header_;
652 std::vector<QuicStreamFrame> last_stream_frames_;
653 std::vector<QuicAckFrame> last_ack_frames_;
654 std::vector<QuicCongestionFeedbackFrame> last_congestion_frames_;
655 std::vector<QuicStopWaitingFrame> last_stop_waiting_frames_;
656 std::vector<QuicRstStreamFrame> last_rst_frames_;
657 std::vector<QuicGoAwayFrame> last_goaway_frames_;
658 std::vector<QuicWindowUpdateFrame> last_window_update_frames_;
659 std::vector<QuicBlockedFrame> last_blocked_frames_;
660 std::vector<QuicConnectionCloseFrame> last_close_frames_;
662 QuicCongestionFeedbackFrame outgoing_congestion_feedback_;
664 // Track some peer state so we can do less bookkeeping
665 // Largest sequence sent by the peer which had an ack frame (latest ack info).
666 QuicPacketSequenceNumber largest_seen_packet_with_ack_;
668 // Largest sequence number sent by the peer which had a stop waiting frame.
669 QuicPacketSequenceNumber largest_seen_packet_with_stop_waiting_;
671 // Collection of packets which were received before encryption was
672 // established, but which could not be decrypted. We buffer these on
673 // the assumption that they could not be processed because they were
674 // sent with the INITIAL encryption and the CHLO message was lost.
675 std::deque<QuicEncryptedPacket*> undecryptable_packets_;
677 // When the version negotiation packet could not be sent because the socket
678 // was not writable, this is set to true.
679 bool pending_version_negotiation_packet_;
681 // When packets could not be sent because the socket was not writable,
682 // they are added to this list. All corresponding frames are in
683 // unacked_packets_ if they are to be retransmitted.
684 QueuedPacketList queued_packets_;
686 // Contains information about the current write in progress, if any.
687 scoped_ptr<QueuedPacket> pending_write_;
689 // Contains the connection close packet if the connection has been closed.
690 scoped_ptr<QuicEncryptedPacket> connection_close_packet_;
692 FecGroupMap group_map_;
694 QuicReceivedPacketManager received_packet_manager_;
695 QuicSentEntropyManager sent_entropy_manager_;
697 // Indicates whether an ack should be sent the next time we try to write.
698 bool ack_queued_;
699 // Indicates how many consecutive times an ack has arrived which indicates
700 // the peer needs to stop waiting for some packets.
701 int stop_waiting_count_;
703 // An alarm that fires when an ACK should be sent to the peer.
704 scoped_ptr<QuicAlarm> ack_alarm_;
705 // An alarm that fires when a packet needs to be retransmitted.
706 scoped_ptr<QuicAlarm> retransmission_alarm_;
707 // An alarm that is scheduled when the sent scheduler requires a
708 // a delay before sending packets and fires when the packet may be sent.
709 scoped_ptr<QuicAlarm> send_alarm_;
710 // An alarm that is scheduled when the connection can still write and there
711 // may be more data to send.
712 scoped_ptr<QuicAlarm> resume_writes_alarm_;
713 // An alarm that fires when the connection may have timed out.
714 scoped_ptr<QuicAlarm> timeout_alarm_;
715 // An alarm that fires when a ping should be sent.
716 scoped_ptr<QuicAlarm> ping_alarm_;
718 QuicConnectionVisitorInterface* visitor_;
719 QuicConnectionDebugVisitor* debug_visitor_;
720 QuicPacketGenerator packet_generator_;
722 // Network idle time before we kill of this connection.
723 QuicTime::Delta idle_network_timeout_;
724 // Overall connection timeout.
725 QuicTime::Delta overall_connection_timeout_;
727 // Statistics for this session.
728 QuicConnectionStats stats_;
730 // The time that we got a packet for this connection.
731 // This is used for timeouts, and does not indicate the packet was processed.
732 QuicTime time_of_last_received_packet_;
734 // The last time a new (non-retransmitted) packet was sent for this
735 // connection.
736 QuicTime time_of_last_sent_new_packet_;
738 // Sequence number of the last sent packet. Packets are guaranteed to be sent
739 // in sequence number order.
740 QuicPacketSequenceNumber sequence_number_of_last_sent_packet_;
742 // Sent packet manager which tracks the status of packets sent by this
743 // connection and contains the send and receive algorithms to determine when
744 // to send packets.
745 QuicSentPacketManager sent_packet_manager_;
747 // The state of connection in version negotiation finite state machine.
748 QuicVersionNegotiationState version_negotiation_state_;
750 // Tracks if the connection was created by the server.
751 bool is_server_;
753 // True by default. False if we've received or sent an explicit connection
754 // close.
755 bool connected_;
757 // Set to true if the UDP packet headers have a new IP address for the peer.
758 // If true, do not perform connection migration.
759 bool peer_ip_changed_;
761 // Set to true if the UDP packet headers have a new port for the peer.
762 // If true, and the IP has not changed, then we can migrate the connection.
763 bool peer_port_changed_;
765 // Set to true if the UDP packet headers are addressed to a different IP.
766 // We do not support connection migration when the self IP changed.
767 bool self_ip_changed_;
769 // Set to true if the UDP packet headers are addressed to a different port.
770 // We do not support connection migration when the self port changed.
771 bool self_port_changed_;
773 // If non-empty this contains the set of versions received in a
774 // version negotiation packet.
775 QuicVersionVector server_supported_versions_;
777 DISALLOW_COPY_AND_ASSIGN(QuicConnection);
780 } // namespace net
782 #endif // NET_QUIC_QUIC_CONNECTION_H_