Updating trunk VERSION from 2139.0 to 2140.0
[chromium-blink-merge.git] / net / quic / quic_connection.h
blob0f083536d6c84a44e2e922540018df2bd311b7a2
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 when the connection experiences a change in congestion window.
98 virtual void OnCongestionWindowChange(QuicTime now) = 0;
100 // Called to ask if the visitor wants to schedule write resumption as it both
101 // has pending data to write, and is able to write (e.g. based on flow control
102 // limits).
103 // Writes may be pending because they were write-blocked, congestion-throttled
104 // or yielded to other connections.
105 virtual bool WillingAndAbleToWrite() const = 0;
107 // Called to ask if any handshake messages are pending in this visitor.
108 virtual bool HasPendingHandshake() const = 0;
110 // Called to ask if any streams are open in this visitor, excluding the
111 // reserved crypto and headers stream.
112 virtual bool HasOpenDataStreams() const = 0;
115 // Interface which gets callbacks from the QuicConnection at interesting
116 // points. Implementations must not mutate the state of the connection
117 // as a result of these callbacks.
118 class NET_EXPORT_PRIVATE QuicConnectionDebugVisitor
119 : public QuicPacketGenerator::DebugDelegate,
120 public QuicSentPacketManager::DebugDelegate {
121 public:
122 virtual ~QuicConnectionDebugVisitor() {}
124 // Called when a packet has been sent.
125 virtual void OnPacketSent(QuicPacketSequenceNumber sequence_number,
126 EncryptionLevel level,
127 TransmissionType transmission_type,
128 const QuicEncryptedPacket& packet,
129 WriteResult result) {}
131 // Called when the contents of a packet have been retransmitted as
132 // a new packet.
133 virtual void OnPacketRetransmitted(
134 QuicPacketSequenceNumber old_sequence_number,
135 QuicPacketSequenceNumber new_sequence_number) {}
137 // Called when a packet has been received, but before it is
138 // validated or parsed.
139 virtual void OnPacketReceived(const IPEndPoint& self_address,
140 const IPEndPoint& peer_address,
141 const QuicEncryptedPacket& packet) {}
143 // Called when a packet is received with a connection id that does not
144 // match the ID of this connection.
145 virtual void OnIncorrectConnectionId(
146 QuicConnectionId connection_id) {}
148 // Called when an undecryptable packet has been received.
149 virtual void OnUndecryptablePacket() {}
151 // Called when a duplicate packet has been received.
152 virtual void OnDuplicatePacket(QuicPacketSequenceNumber sequence_number) {}
154 // Called when the protocol version on the received packet doensn't match
155 // current protocol version of the connection.
156 virtual void OnProtocolVersionMismatch(QuicVersion version) {}
158 // Called when the complete header of a packet has been parsed.
159 virtual void OnPacketHeader(const QuicPacketHeader& header) {}
161 // Called when a StreamFrame has been parsed.
162 virtual void OnStreamFrame(const QuicStreamFrame& frame) {}
164 // Called when a AckFrame has been parsed.
165 virtual void OnAckFrame(const QuicAckFrame& frame) {}
167 // Called when a CongestionFeedbackFrame has been parsed.
168 virtual void OnCongestionFeedbackFrame(
169 const QuicCongestionFeedbackFrame& frame) {}
171 // Called when a StopWaitingFrame has been parsed.
172 virtual void OnStopWaitingFrame(const QuicStopWaitingFrame& frame) {}
174 // Called when a Ping has been parsed.
175 virtual void OnPingFrame(const QuicPingFrame& frame) {}
177 // Called when a GoAway has been parsed.
178 virtual void OnGoAwayFrame(const QuicGoAwayFrame& frame) {}
180 // Called when a RstStreamFrame has been parsed.
181 virtual void OnRstStreamFrame(const QuicRstStreamFrame& frame) {}
183 // Called when a ConnectionCloseFrame has been parsed.
184 virtual void OnConnectionCloseFrame(
185 const QuicConnectionCloseFrame& frame) {}
187 // Called when a WindowUpdate has been parsed.
188 virtual void OnWindowUpdateFrame(const QuicWindowUpdateFrame& frame) {}
190 // Called when a BlockedFrame has been parsed.
191 virtual void OnBlockedFrame(const QuicBlockedFrame& frame) {}
193 // Called when a public reset packet has been received.
194 virtual void OnPublicResetPacket(const QuicPublicResetPacket& packet) {}
196 // Called when a version negotiation packet has been received.
197 virtual void OnVersionNegotiationPacket(
198 const QuicVersionNegotiationPacket& packet) {}
200 // Called after a packet has been successfully parsed which results
201 // in the revival of a packet via FEC.
202 virtual void OnRevivedPacket(const QuicPacketHeader& revived_header,
203 base::StringPiece payload) {}
205 // Called when the connection is closed.
206 virtual void OnConnectionClosed(QuicErrorCode error, bool from_peer) {}
209 class NET_EXPORT_PRIVATE QuicConnectionHelperInterface {
210 public:
211 virtual ~QuicConnectionHelperInterface() {}
213 // Returns a QuicClock to be used for all time related functions.
214 virtual const QuicClock* GetClock() const = 0;
216 // Returns a QuicRandom to be used for all random number related functions.
217 virtual QuicRandom* GetRandomGenerator() = 0;
219 // Creates a new platform-specific alarm which will be configured to
220 // notify |delegate| when the alarm fires. Caller takes ownership
221 // of the new alarm, which will not yet be "set" to fire.
222 virtual QuicAlarm* CreateAlarm(QuicAlarm::Delegate* delegate) = 0;
225 class NET_EXPORT_PRIVATE QuicConnection
226 : public QuicFramerVisitorInterface,
227 public QuicBlockedWriterInterface,
228 public QuicPacketGenerator::DelegateInterface,
229 public QuicSentPacketManager::NetworkChangeVisitor {
230 public:
231 enum PacketType {
232 NORMAL,
233 QUEUED,
234 CONNECTION_CLOSE
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 bool is_server,
260 const QuicVersionVector& supported_versions);
261 virtual ~QuicConnection();
263 // Sets connection parameters from the supplied |config|.
264 void SetFromConfig(const QuicConfig& config);
266 // Send the data in |data| to the peer in as few packets as possible.
267 // Returns a pair with the number of bytes consumed from data, and a boolean
268 // indicating if the fin bit was consumed. This does not indicate the data
269 // has been sent on the wire: it may have been turned into a packet and queued
270 // if the socket was unexpectedly blocked. |fec_protection| indicates if
271 // data is to be FEC protected. Note that data that is sent immediately
272 // following MUST_FEC_PROTECT data may get protected by falling within the
273 // same FEC group.
274 // If |delegate| is provided, then it will be informed once ACKs have been
275 // received for all the packets written in this call.
276 // The |delegate| is not owned by the QuicConnection and must outlive it.
277 QuicConsumedData SendStreamData(QuicStreamId id,
278 const IOVector& data,
279 QuicStreamOffset offset,
280 bool fin,
281 FecProtection fec_protection,
282 QuicAckNotifier::DelegateInterface* delegate);
284 // Send a RST_STREAM frame to the peer.
285 virtual void SendRstStream(QuicStreamId id,
286 QuicRstStreamErrorCode error,
287 QuicStreamOffset bytes_written);
289 // Send a BLOCKED frame to the peer.
290 virtual void SendBlocked(QuicStreamId id);
292 // Send a WINDOW_UPDATE frame to the peer.
293 virtual void SendWindowUpdate(QuicStreamId id,
294 QuicStreamOffset byte_offset);
296 // Sends the connection close packet without affecting the state of the
297 // connection. This should only be called if the session is actively being
298 // destroyed: otherwise call SendConnectionCloseWithDetails instead.
299 virtual void SendConnectionClosePacket(QuicErrorCode error,
300 const std::string& details);
302 // Sends a connection close frame to the peer, and closes the connection by
303 // calling CloseConnection(notifying the visitor as it does so).
304 virtual void SendConnectionClose(QuicErrorCode error);
305 virtual void SendConnectionCloseWithDetails(QuicErrorCode error,
306 const std::string& details);
307 // Notifies the visitor of the close and marks the connection as disconnected.
308 virtual void CloseConnection(QuicErrorCode error, bool from_peer) OVERRIDE;
309 virtual void SendGoAway(QuicErrorCode error,
310 QuicStreamId last_good_stream_id,
311 const std::string& reason);
313 // Returns statistics tracked for this connection.
314 const QuicConnectionStats& GetStats();
316 // Processes an incoming UDP packet (consisting of a QuicEncryptedPacket) from
317 // the peer. If processing this packet permits a packet to be revived from
318 // its FEC group that packet will be revived and processed.
319 virtual void ProcessUdpPacket(const IPEndPoint& self_address,
320 const IPEndPoint& peer_address,
321 const QuicEncryptedPacket& packet);
323 // QuicBlockedWriterInterface
324 // Called when the underlying connection becomes writable to allow queued
325 // writes to happen.
326 virtual void OnCanWrite() OVERRIDE;
328 // Called when an error occurs while attempting to write a packet to the
329 // network.
330 void OnWriteError(int error_code);
332 // If the socket is not blocked, writes queued packets.
333 void WriteIfNotBlocked();
335 // The version of the protocol this connection is using.
336 QuicVersion version() const { return framer_.version(); }
338 // The versions of the protocol that this connection supports.
339 const QuicVersionVector& supported_versions() const {
340 return framer_.supported_versions();
343 // From QuicFramerVisitorInterface
344 virtual void OnError(QuicFramer* framer) OVERRIDE;
345 virtual bool OnProtocolVersionMismatch(QuicVersion received_version) OVERRIDE;
346 virtual void OnPacket() OVERRIDE;
347 virtual void OnPublicResetPacket(
348 const QuicPublicResetPacket& packet) OVERRIDE;
349 virtual void OnVersionNegotiationPacket(
350 const QuicVersionNegotiationPacket& packet) OVERRIDE;
351 virtual void OnRevivedPacket() OVERRIDE;
352 virtual bool OnUnauthenticatedPublicHeader(
353 const QuicPacketPublicHeader& header) OVERRIDE;
354 virtual bool OnUnauthenticatedHeader(const QuicPacketHeader& header) OVERRIDE;
355 virtual void OnDecryptedPacket(EncryptionLevel level) OVERRIDE;
356 virtual bool OnPacketHeader(const QuicPacketHeader& header) OVERRIDE;
357 virtual void OnFecProtectedPayload(base::StringPiece payload) OVERRIDE;
358 virtual bool OnStreamFrame(const QuicStreamFrame& frame) OVERRIDE;
359 virtual bool OnAckFrame(const QuicAckFrame& frame) OVERRIDE;
360 virtual bool OnCongestionFeedbackFrame(
361 const QuicCongestionFeedbackFrame& frame) OVERRIDE;
362 virtual bool OnStopWaitingFrame(const QuicStopWaitingFrame& frame) OVERRIDE;
363 virtual bool OnPingFrame(const QuicPingFrame& frame) OVERRIDE;
364 virtual bool OnRstStreamFrame(const QuicRstStreamFrame& frame) OVERRIDE;
365 virtual bool OnConnectionCloseFrame(
366 const QuicConnectionCloseFrame& frame) OVERRIDE;
367 virtual bool OnGoAwayFrame(const QuicGoAwayFrame& frame) OVERRIDE;
368 virtual bool OnWindowUpdateFrame(const QuicWindowUpdateFrame& frame) OVERRIDE;
369 virtual bool OnBlockedFrame(const QuicBlockedFrame& frame) OVERRIDE;
370 virtual void OnFecData(const QuicFecData& fec) OVERRIDE;
371 virtual void OnPacketComplete() OVERRIDE;
373 // QuicPacketGenerator::DelegateInterface
374 virtual bool ShouldGeneratePacket(TransmissionType transmission_type,
375 HasRetransmittableData retransmittable,
376 IsHandshake handshake) OVERRIDE;
377 virtual QuicAckFrame* CreateAckFrame() OVERRIDE;
378 virtual QuicCongestionFeedbackFrame* CreateFeedbackFrame() OVERRIDE;
379 virtual QuicStopWaitingFrame* CreateStopWaitingFrame() OVERRIDE;
380 virtual bool OnSerializedPacket(const SerializedPacket& packet) OVERRIDE;
382 // QuicSentPacketManager::NetworkChangeVisitor
383 virtual void OnCongestionWindowChange(
384 QuicByteCount congestion_window) OVERRIDE;
386 // Called by the crypto stream when the handshake completes. In the server's
387 // case this is when the SHLO has been ACKed. Clients call this on receipt of
388 // the SHLO.
389 void OnHandshakeComplete();
391 // Accessors
392 void set_visitor(QuicConnectionVisitorInterface* visitor) {
393 visitor_ = visitor;
395 // This method takes ownership of |debug_visitor|.
396 void set_debug_visitor(QuicConnectionDebugVisitor* debug_visitor) {
397 debug_visitor_.reset(debug_visitor);
398 packet_generator_.set_debug_delegate(debug_visitor);
399 sent_packet_manager_.set_debug_delegate(debug_visitor);
401 const IPEndPoint& self_address() const { return self_address_; }
402 const IPEndPoint& peer_address() const { return peer_address_; }
403 QuicConnectionId connection_id() const { return connection_id_; }
404 const QuicClock* clock() const { return clock_; }
405 QuicRandom* random_generator() const { return random_generator_; }
406 size_t max_packet_length() const;
407 void set_max_packet_length(size_t length);
409 bool connected() const { return connected_; }
411 // Must only be called on client connections.
412 const QuicVersionVector& server_supported_versions() const {
413 DCHECK(!is_server_);
414 return server_supported_versions_;
417 size_t NumFecGroups() const { return group_map_.size(); }
419 // Testing only.
420 size_t NumQueuedPackets() const { return queued_packets_.size(); }
422 QuicEncryptedPacket* ReleaseConnectionClosePacket() {
423 return connection_close_packet_.release();
426 // Returns true if the underlying UDP socket is writable, there is
427 // no queued data and the connection is not congestion-control
428 // blocked.
429 bool CanWriteStreamData();
431 // Returns true if the connection has queued packets or frames.
432 bool HasQueuedData() const;
434 // Sets (or resets) the idle state connection timeout. Also, checks and times
435 // out the connection if network timer has expired for |timeout|.
436 void SetIdleNetworkTimeout(QuicTime::Delta timeout);
437 // Sets (or resets) the total time delta the connection can be alive for.
438 // Also, checks and times out the connection if timer has expired for
439 // |timeout|. Used to limit the time a connection can be alive before crypto
440 // handshake finishes.
441 void SetOverallConnectionTimeout(QuicTime::Delta timeout);
443 // If the connection has timed out, this will close the connection and return
444 // true. Otherwise, it will return false and will reset the timeout alarm.
445 bool CheckForTimeout();
447 // Sends a ping, and resets the ping alarm.
448 void SendPing();
450 // Sets up a packet with an QuicAckFrame and sends it out.
451 void SendAck();
453 // Called when an RTO fires. Resets the retransmission alarm if there are
454 // remaining unacked packets.
455 void OnRetransmissionTimeout();
457 // Retransmits all unacked packets with retransmittable frames if
458 // |retransmission_type| is ALL_PACKETS, otherwise retransmits only initially
459 // encrypted packets. Used when the negotiated protocol version is different
460 // from what was initially assumed and when the visitor wants to re-transmit
461 // initially encrypted packets when the initial encrypter changes.
462 void RetransmitUnackedPackets(RetransmissionType retransmission_type);
464 // Calls |sent_packet_manager_|'s NeuterUnencryptedPackets. Used when the
465 // connection becomes forward secure and hasn't received acks for all packets.
466 void NeuterUnencryptedPackets();
468 // Changes the encrypter used for level |level| to |encrypter|. The function
469 // takes ownership of |encrypter|.
470 void SetEncrypter(EncryptionLevel level, QuicEncrypter* encrypter);
471 const QuicEncrypter* encrypter(EncryptionLevel level) const;
473 // SetDefaultEncryptionLevel sets the encryption level that will be applied
474 // to new packets.
475 void SetDefaultEncryptionLevel(EncryptionLevel level);
477 // SetDecrypter sets the primary decrypter, replacing any that already exists,
478 // and takes ownership. If an alternative decrypter is in place then the
479 // function DCHECKs. This is intended for cases where one knows that future
480 // packets will be using the new decrypter and the previous decrypter is now
481 // obsolete. |level| indicates the encryption level of the new decrypter.
482 void SetDecrypter(QuicDecrypter* decrypter, EncryptionLevel level);
484 // SetAlternativeDecrypter sets a decrypter that may be used to decrypt
485 // future packets and takes ownership of it. |level| indicates the encryption
486 // level of the decrypter. If |latch_once_used| is true, then the first time
487 // that the decrypter is successful it will replace the primary decrypter.
488 // Otherwise both decrypters will remain active and the primary decrypter
489 // will be the one last used.
490 void SetAlternativeDecrypter(QuicDecrypter* decrypter,
491 EncryptionLevel level,
492 bool latch_once_used);
494 const QuicDecrypter* decrypter() const;
495 const QuicDecrypter* alternative_decrypter() const;
497 bool is_server() const { return is_server_; }
499 // Returns the underlying sent packet manager.
500 const QuicSentPacketManager& sent_packet_manager() const {
501 return sent_packet_manager_;
504 bool CanWrite(HasRetransmittableData retransmittable);
506 // Stores current batch state for connection, puts the connection
507 // into batch mode, and destruction restores the stored batch state.
508 // While the bundler is in scope, any generated frames are bundled
509 // as densely as possible into packets. In addition, this bundler
510 // can be configured to ensure that an ACK frame is included in the
511 // first packet created, if there's new ack information to be sent.
512 class ScopedPacketBundler {
513 public:
514 // In addition to all outgoing frames being bundled when the
515 // bundler is in scope, setting |include_ack| to true ensures that
516 // an ACK frame is opportunistically bundled with the first
517 // outgoing packet.
518 ScopedPacketBundler(QuicConnection* connection, AckBundling send_ack);
519 ~ScopedPacketBundler();
521 private:
522 QuicConnection* connection_;
523 bool already_in_batch_mode_;
526 protected:
527 // Do any work which logically would be done in OnPacket but can not be
528 // safely done until the packet is validated. Returns true if the packet
529 // can be handled, false otherwise.
530 virtual bool ProcessValidatedPacket();
532 // Send a packet to the peer using encryption |level|. If |sequence_number|
533 // is present in the |retransmission_map_|, then contents of this packet will
534 // be retransmitted with a new sequence number if it's not acked by the peer.
535 // Deletes |packet| if WritePacket call succeeds, or transfers ownership to
536 // QueuedPacket, ultimately deleted in WriteQueuedPackets. Updates the
537 // entropy map corresponding to |sequence_number| using |entropy_hash|.
538 // |transmission_type| and |retransmittable| are supplied to the congestion
539 // manager, and when |forced| is true, it bypasses the congestion manager.
540 // TODO(wtc): none of the callers check the return value.
541 virtual bool SendOrQueuePacket(EncryptionLevel level,
542 const SerializedPacket& packet,
543 TransmissionType transmission_type);
545 QuicConnectionHelperInterface* helper() { return helper_; }
547 // Selects and updates the version of the protocol being used by selecting a
548 // version from |available_versions| which is also supported. Returns true if
549 // such a version exists, false otherwise.
550 bool SelectMutualVersion(const QuicVersionVector& available_versions);
552 QuicPacketWriter* writer() { return writer_; }
554 bool peer_port_changed() const { return peer_port_changed_; }
556 QuicPacketSequenceNumber sequence_number_of_last_sent_packet() const {
557 return sequence_number_of_last_sent_packet_;
560 private:
561 friend class test::QuicConnectionPeer;
563 // Packets which have not been written to the wire.
564 // Owns the QuicPacket* packet.
565 struct QueuedPacket {
566 QueuedPacket(SerializedPacket packet,
567 EncryptionLevel level,
568 TransmissionType transmission_type);
570 QuicPacketSequenceNumber sequence_number;
571 QuicPacket* packet;
572 const EncryptionLevel encryption_level;
573 TransmissionType transmission_type;
574 HasRetransmittableData retransmittable;
575 IsHandshake handshake;
576 PacketType type;
577 QuicByteCount length;
580 typedef std::list<QueuedPacket> QueuedPacketList;
581 typedef std::map<QuicFecGroupNumber, QuicFecGroup*> FecGroupMap;
583 // Writes the given packet to socket, encrypted with packet's
584 // encryption_level. Returns true on successful write. Behavior is undefined
585 // if connection is not established or broken. A return value of true means
586 // the packet was transmitted and may be destroyed. If the packet is
587 // retransmittable, WritePacket sets up retransmission for a successful write.
588 // If packet is FORCE, then it will be sent immediately and the send scheduler
589 // will not be consulted.
590 bool WritePacket(QueuedPacket packet);
592 // Make sure an ack we got from our peer is sane.
593 bool ValidateAckFrame(const QuicAckFrame& incoming_ack);
595 // Make sure a stop waiting we got from our peer is sane.
596 bool ValidateStopWaitingFrame(const QuicStopWaitingFrame& stop_waiting);
598 // Sends a version negotiation packet to the peer.
599 void SendVersionNegotiationPacket();
601 // Clears any accumulated frames from the last received packet.
602 void ClearLastFrames();
604 // Writes as many queued packets as possible. The connection must not be
605 // blocked when this is called.
606 void WriteQueuedPackets();
608 // Writes as many pending retransmissions as possible.
609 void WritePendingRetransmissions();
611 // Returns true if the packet should be discarded and not sent.
612 bool ShouldDiscardPacket(EncryptionLevel level,
613 QuicPacketSequenceNumber sequence_number,
614 HasRetransmittableData retransmittable);
616 // Queues |packet| in the hopes that it can be decrypted in the
617 // future, when a new key is installed.
618 void QueueUndecryptablePacket(const QuicEncryptedPacket& packet);
620 // Attempts to process any queued undecryptable packets.
621 void MaybeProcessUndecryptablePackets();
623 // If a packet can be revived from the current FEC group, then
624 // revive and process the packet.
625 void MaybeProcessRevivedPacket();
627 void ProcessAckFrame(const QuicAckFrame& incoming_ack);
629 void ProcessStopWaitingFrame(const QuicStopWaitingFrame& stop_waiting);
631 // Update |stop_waiting| for an outgoing ack.
632 void UpdateStopWaiting(QuicStopWaitingFrame* stop_waiting);
634 // Queues an ack or sets the ack alarm when an incoming packet arrives that
635 // should be acked.
636 void MaybeQueueAck();
638 // Checks if the last packet should instigate an ack.
639 bool ShouldLastPacketInstigateAck() const;
641 // Checks if the peer is waiting for packets that have been given up on, and
642 // therefore an ack frame should be sent with a larger least_unacked.
643 void UpdateStopWaitingCount();
645 // Sends any packets which are a response to the last packet, including both
646 // acks and pending writes if an ack opened the congestion window.
647 void MaybeSendInResponseToPacket();
649 // Gets the least unacked sequence number, which is the next sequence number
650 // to be sent if there are no outstanding packets.
651 QuicPacketSequenceNumber GetLeastUnacked() const;
653 // Get the FEC group associate with the last processed packet or NULL, if the
654 // group has already been deleted.
655 QuicFecGroup* GetFecGroup();
657 // Closes any FEC groups protecting packets before |sequence_number|.
658 void CloseFecGroupsBefore(QuicPacketSequenceNumber sequence_number);
660 // Sets the ping alarm to the appropriate value, if any.
661 void SetPingAlarm();
663 // On arrival of a new packet, checks to see if the socket addresses have
664 // changed since the last packet we saw on this connection.
665 void CheckForAddressMigration(const IPEndPoint& self_address,
666 const IPEndPoint& peer_address);
668 QuicFramer framer_;
669 QuicConnectionHelperInterface* helper_; // Not owned.
670 QuicPacketWriter* writer_; // Owned or not depending on |owns_writer_|.
671 bool owns_writer_;
672 EncryptionLevel encryption_level_;
673 const QuicClock* clock_;
674 QuicRandom* random_generator_;
676 const QuicConnectionId connection_id_;
677 // Address on the last successfully processed packet received from the
678 // client.
679 IPEndPoint self_address_;
680 IPEndPoint peer_address_;
681 // Used to store latest peer port to possibly migrate to later.
682 int migrating_peer_port_;
684 bool last_packet_revived_; // True if the last packet was revived from FEC.
685 size_t last_size_; // Size of the last received packet.
686 EncryptionLevel last_decrypted_packet_level_;
687 QuicPacketHeader last_header_;
688 std::vector<QuicStreamFrame> last_stream_frames_;
689 std::vector<QuicAckFrame> last_ack_frames_;
690 std::vector<QuicCongestionFeedbackFrame> last_congestion_frames_;
691 std::vector<QuicStopWaitingFrame> last_stop_waiting_frames_;
692 std::vector<QuicRstStreamFrame> last_rst_frames_;
693 std::vector<QuicGoAwayFrame> last_goaway_frames_;
694 std::vector<QuicWindowUpdateFrame> last_window_update_frames_;
695 std::vector<QuicBlockedFrame> last_blocked_frames_;
696 std::vector<QuicConnectionCloseFrame> last_close_frames_;
698 QuicCongestionFeedbackFrame outgoing_congestion_feedback_;
700 // Track some peer state so we can do less bookkeeping
701 // Largest sequence sent by the peer which had an ack frame (latest ack info).
702 QuicPacketSequenceNumber largest_seen_packet_with_ack_;
704 // Largest sequence number sent by the peer which had a stop waiting frame.
705 QuicPacketSequenceNumber largest_seen_packet_with_stop_waiting_;
707 // Collection of packets which were received before encryption was
708 // established, but which could not be decrypted. We buffer these on
709 // the assumption that they could not be processed because they were
710 // sent with the INITIAL encryption and the CHLO message was lost.
711 std::deque<QuicEncryptedPacket*> undecryptable_packets_;
713 // When the version negotiation packet could not be sent because the socket
714 // was not writable, this is set to true.
715 bool pending_version_negotiation_packet_;
717 // When packets could not be sent because the socket was not writable,
718 // they are added to this list. All corresponding frames are in
719 // unacked_packets_ if they are to be retransmitted.
720 QueuedPacketList queued_packets_;
722 // Contains the connection close packet if the connection has been closed.
723 scoped_ptr<QuicEncryptedPacket> connection_close_packet_;
725 FecGroupMap group_map_;
727 QuicReceivedPacketManager received_packet_manager_;
728 QuicSentEntropyManager sent_entropy_manager_;
730 // Indicates whether an ack should be sent the next time we try to write.
731 bool ack_queued_;
732 // Indicates how many consecutive times an ack has arrived which indicates
733 // the peer needs to stop waiting for some packets.
734 int stop_waiting_count_;
736 // An alarm that fires when an ACK should be sent to the peer.
737 scoped_ptr<QuicAlarm> ack_alarm_;
738 // An alarm that fires when a packet needs to be retransmitted.
739 scoped_ptr<QuicAlarm> retransmission_alarm_;
740 // An alarm that is scheduled when the sent scheduler requires a
741 // a delay before sending packets and fires when the packet may be sent.
742 scoped_ptr<QuicAlarm> send_alarm_;
743 // An alarm that is scheduled when the connection can still write and there
744 // may be more data to send.
745 scoped_ptr<QuicAlarm> resume_writes_alarm_;
746 // An alarm that fires when the connection may have timed out.
747 scoped_ptr<QuicAlarm> timeout_alarm_;
748 // An alarm that fires when a ping should be sent.
749 scoped_ptr<QuicAlarm> ping_alarm_;
751 QuicConnectionVisitorInterface* visitor_;
752 scoped_ptr<QuicConnectionDebugVisitor> debug_visitor_;
753 QuicPacketGenerator packet_generator_;
755 // Network idle time before we kill of this connection.
756 QuicTime::Delta idle_network_timeout_;
757 // Overall connection timeout.
758 QuicTime::Delta overall_connection_timeout_;
760 // Statistics for this session.
761 QuicConnectionStats stats_;
763 // The time that we got a packet for this connection.
764 // This is used for timeouts, and does not indicate the packet was processed.
765 QuicTime time_of_last_received_packet_;
767 // The last time a new (non-retransmitted) packet was sent for this
768 // connection.
769 QuicTime time_of_last_sent_new_packet_;
771 // Sequence number of the last sent packet. Packets are guaranteed to be sent
772 // in sequence number order.
773 QuicPacketSequenceNumber sequence_number_of_last_sent_packet_;
775 // Sent packet manager which tracks the status of packets sent by this
776 // connection and contains the send and receive algorithms to determine when
777 // to send packets.
778 QuicSentPacketManager sent_packet_manager_;
780 // The state of connection in version negotiation finite state machine.
781 QuicVersionNegotiationState version_negotiation_state_;
783 // Tracks if the connection was created by the server.
784 bool is_server_;
786 // True by default. False if we've received or sent an explicit connection
787 // close.
788 bool connected_;
790 // Set to true if the UDP packet headers have a new IP address for the peer.
791 // If true, do not perform connection migration.
792 bool peer_ip_changed_;
794 // Set to true if the UDP packet headers have a new port for the peer.
795 // If true, and the IP has not changed, then we can migrate the connection.
796 bool peer_port_changed_;
798 // Set to true if the UDP packet headers are addressed to a different IP.
799 // We do not support connection migration when the self IP changed.
800 bool self_ip_changed_;
802 // Set to true if the UDP packet headers are addressed to a different port.
803 // We do not support connection migration when the self port changed.
804 bool self_port_changed_;
806 // If non-empty this contains the set of versions received in a
807 // version negotiation packet.
808 QuicVersionVector server_supported_versions_;
810 DISALLOW_COPY_AND_ASSIGN(QuicConnection);
813 } // namespace net
815 #endif // NET_QUIC_QUIC_CONNECTION_H_