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. 10 // 11 // On the client side, the Connection handles the raw reads, as well as the 12 // processing. 13 // 14 // Note: this class is not thread-safe. 15 16 #ifndef NET_QUIC_QUIC_CONNECTION_H_ 17 #define NET_QUIC_QUIC_CONNECTION_H_ 18 19 #include <stddef.h> 20 #include <deque> 21 #include <list> 22 #include <map> 23 #include <queue> 24 #include <string> 25 #include <vector> 26 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_time.h" 44 #include "net/quic/quic_types.h" 45 46 namespace net { 47 48 class QuicClock; 49 class QuicConfig; 50 class QuicConnection; 51 class QuicDecrypter; 52 class QuicEncrypter; 53 class QuicFecGroup; 54 class QuicRandom; 55 56 namespace test { 57 class PacketSavingConnection; 58 class QuicConnectionPeer; 59 } // namespace test 60 61 // Class that receives callbacks from the connection when frames are received 62 // and when other interesting events happen. 63 class NET_EXPORT_PRIVATE QuicConnectionVisitorInterface { 64 public: 65 virtual ~QuicConnectionVisitorInterface() {} 66 67 // A simple visitor interface for dealing with data frames. 68 virtual void OnStreamFrames(const std::vector<QuicStreamFrame>& frames) = 0; 69 70 // The session should process all WINDOW_UPDATE frames, adjusting both stream 71 // and connection level flow control windows. 72 virtual void OnWindowUpdateFrames( 73 const std::vector<QuicWindowUpdateFrame>& frames) = 0; 74 75 // BLOCKED frames tell us that the peer believes it is flow control blocked on 76 // a specified stream. If the session at this end disagrees, something has 77 // gone wrong with our flow control accounting. 78 virtual void OnBlockedFrames(const std::vector<QuicBlockedFrame>& frames) = 0; 79 80 // Called when the stream is reset by the peer. 81 virtual void OnRstStream(const QuicRstStreamFrame& frame) = 0; 82 83 // Called when the connection is going away according to the peer. 84 virtual void OnGoAway(const QuicGoAwayFrame& frame) = 0; 85 86 // Called when the connection is closed either locally by the framer, or 87 // remotely by the peer. 88 virtual void OnConnectionClosed(QuicErrorCode error, bool from_peer) = 0; 89 90 // Called when the connection failed to write because the socket was blocked. 91 virtual void OnWriteBlocked() = 0; 92 93 // Called once a specific QUIC version is agreed by both endpoints. 94 virtual void OnSuccessfulVersionNegotiation(const QuicVersion& version) = 0; 95 96 // Called when a blocked socket becomes writable. 97 virtual void OnCanWrite() = 0; 98 99 // Called when the connection experiences a change in congestion window. 100 virtual void OnCongestionWindowChange(QuicTime now) = 0; 101 102 // Called to ask if the visitor wants to schedule write resumption as it both 103 // has pending data to write, and is able to write (e.g. based on flow control 104 // limits). 105 // Writes may be pending because they were write-blocked, congestion-throttled 106 // or yielded to other connections. 107 virtual bool WillingAndAbleToWrite() const = 0; 108 109 // Called to ask if any handshake messages are pending in this visitor. 110 virtual bool HasPendingHandshake() const = 0; 111 112 // Called to ask if any streams are open in this visitor, excluding the 113 // reserved crypto and headers stream. 114 virtual bool HasOpenDataStreams() const = 0; 115 }; 116 117 // Interface which gets callbacks from the QuicConnection at interesting 118 // points. Implementations must not mutate the state of the connection 119 // as a result of these callbacks. 120 class NET_EXPORT_PRIVATE QuicConnectionDebugVisitor 121 : public QuicPacketGenerator::DebugDelegate, 122 public QuicSentPacketManager::DebugDelegate { 123 public: 124 virtual ~QuicConnectionDebugVisitor() {} 125 126 // Called when a packet has been sent. 127 virtual void OnPacketSent(QuicPacketSequenceNumber sequence_number, 128 EncryptionLevel level, 129 TransmissionType transmission_type, 130 const QuicEncryptedPacket& packet, 131 WriteResult result) {} 132 133 // Called when the contents of a packet have been retransmitted as 134 // a new packet. 135 virtual void OnPacketRetransmitted( 136 QuicPacketSequenceNumber old_sequence_number, 137 QuicPacketSequenceNumber new_sequence_number) {} 138 139 // Called when a packet has been received, but before it is 140 // validated or parsed. 141 virtual void OnPacketReceived(const IPEndPoint& self_address, 142 const IPEndPoint& peer_address, 143 const QuicEncryptedPacket& packet) {} 144 145 // Called when a packet is received with a connection id that does not 146 // match the ID of this connection. 147 virtual void OnIncorrectConnectionId( 148 QuicConnectionId connection_id) {} 149 150 // Called when an undecryptable packet has been received. 151 virtual void OnUndecryptablePacket() {} 152 153 // Called when a duplicate packet has been received. 154 virtual void OnDuplicatePacket(QuicPacketSequenceNumber sequence_number) {} 155 156 // Called when the protocol version on the received packet doensn't match 157 // current protocol version of the connection. 158 virtual void OnProtocolVersionMismatch(QuicVersion version) {} 159 160 // Called when the complete header of a packet has been parsed. 161 virtual void OnPacketHeader(const QuicPacketHeader& header) {} 162 163 // Called when a StreamFrame has been parsed. 164 virtual void OnStreamFrame(const QuicStreamFrame& frame) {} 165 166 // Called when a AckFrame has been parsed. 167 virtual void OnAckFrame(const QuicAckFrame& frame) {} 168 169 // Called when a CongestionFeedbackFrame has been parsed. 170 virtual void OnCongestionFeedbackFrame( 171 const QuicCongestionFeedbackFrame& frame) {} 172 173 // Called when a StopWaitingFrame has been parsed. 174 virtual void OnStopWaitingFrame(const QuicStopWaitingFrame& frame) {} 175 176 // Called when a Ping has been parsed. 177 virtual void OnPingFrame(const QuicPingFrame& frame) {} 178 179 // Called when a GoAway has been parsed. 180 virtual void OnGoAwayFrame(const QuicGoAwayFrame& frame) {} 181 182 // Called when a RstStreamFrame has been parsed. 183 virtual void OnRstStreamFrame(const QuicRstStreamFrame& frame) {} 184 185 // Called when a ConnectionCloseFrame has been parsed. 186 virtual void OnConnectionCloseFrame( 187 const QuicConnectionCloseFrame& frame) {} 188 189 // Called when a WindowUpdate has been parsed. 190 virtual void OnWindowUpdateFrame(const QuicWindowUpdateFrame& frame) {} 191 192 // Called when a BlockedFrame has been parsed. 193 virtual void OnBlockedFrame(const QuicBlockedFrame& frame) {} 194 195 // Called when a public reset packet has been received. 196 virtual void OnPublicResetPacket(const QuicPublicResetPacket& packet) {} 197 198 // Called when a version negotiation packet has been received. 199 virtual void OnVersionNegotiationPacket( 200 const QuicVersionNegotiationPacket& packet) {} 201 202 // Called after a packet has been successfully parsed which results 203 // in the revival of a packet via FEC. 204 virtual void OnRevivedPacket(const QuicPacketHeader& revived_header, 205 base::StringPiece payload) {} 206 207 // Called when the connection is closed. 208 virtual void OnConnectionClosed(QuicErrorCode error, bool from_peer) {} 209 210 // Called when the version negotiation is successful. 211 virtual void OnSuccessfulVersionNegotiation(const QuicVersion& version) {} 212 }; 213 214 class NET_EXPORT_PRIVATE QuicConnectionHelperInterface { 215 public: 216 virtual ~QuicConnectionHelperInterface() {} 217 218 // Returns a QuicClock to be used for all time related functions. 219 virtual const QuicClock* GetClock() const = 0; 220 221 // Returns a QuicRandom to be used for all random number related functions. 222 virtual QuicRandom* GetRandomGenerator() = 0; 223 224 // Creates a new platform-specific alarm which will be configured to 225 // notify |delegate| when the alarm fires. Caller takes ownership 226 // of the new alarm, which will not yet be "set" to fire. 227 virtual QuicAlarm* CreateAlarm(QuicAlarm::Delegate* delegate) = 0; 228 }; 229 230 class NET_EXPORT_PRIVATE QuicConnection 231 : public QuicFramerVisitorInterface, 232 public QuicBlockedWriterInterface, 233 public QuicPacketGenerator::DelegateInterface, 234 public QuicSentPacketManager::NetworkChangeVisitor { 235 public: 236 enum AckBundling { 237 NO_ACK = 0, 238 SEND_ACK = 1, 239 BUNDLE_PENDING_ACK = 2, 240 }; 241 242 class PacketWriterFactory { 243 public: 244 virtual ~PacketWriterFactory() {} 245 246 virtual QuicPacketWriter* Create(QuicConnection* connection) const = 0; 247 }; 248 249 // Constructs a new QuicConnection for |connection_id| and |address|. Invokes 250 // writer_factory->Create() to get a writer; |owns_writer| specifies whether 251 // the connection takes ownership of the returned writer. |helper| must 252 // outlive this connection. 253 QuicConnection(QuicConnectionId connection_id, 254 IPEndPoint address, 255 QuicConnectionHelperInterface* helper, 256 const PacketWriterFactory& writer_factory, 257 bool owns_writer, 258 bool is_server, 259 const QuicVersionVector& supported_versions); 260 virtual ~QuicConnection(); 261 262 // Sets connection parameters from the supplied |config|. 263 void SetFromConfig(const QuicConfig& config); 264 265 // Send the data in |data| to the peer in as few packets as possible. 266 // Returns a pair with the number of bytes consumed from data, and a boolean 267 // indicating if the fin bit was consumed. This does not indicate the data 268 // has been sent on the wire: it may have been turned into a packet and queued 269 // if the socket was unexpectedly blocked. |fec_protection| indicates if 270 // data is to be FEC protected. Note that data that is sent immediately 271 // following MUST_FEC_PROTECT data may get protected by falling within the 272 // same FEC group. 273 // If |delegate| is provided, then it will be informed once ACKs have been 274 // received for all the packets written in this call. 275 // The |delegate| is not owned by the QuicConnection and must outlive it. 276 QuicConsumedData SendStreamData(QuicStreamId id, 277 const IOVector& data, 278 QuicStreamOffset offset, 279 bool fin, 280 FecProtection fec_protection, 281 QuicAckNotifier::DelegateInterface* delegate); 282 283 // Send a RST_STREAM frame to the peer. 284 virtual void SendRstStream(QuicStreamId id, 285 QuicRstStreamErrorCode error, 286 QuicStreamOffset bytes_written); 287 288 // Send a BLOCKED frame to the peer. 289 virtual void SendBlocked(QuicStreamId id); 290 291 // Send a WINDOW_UPDATE frame to the peer. 292 virtual void SendWindowUpdate(QuicStreamId id, 293 QuicStreamOffset byte_offset); 294 295 // Sends the connection close packet without affecting the state of the 296 // connection. This should only be called if the session is actively being 297 // destroyed: otherwise call SendConnectionCloseWithDetails instead. 298 virtual void SendConnectionClosePacket(QuicErrorCode error, 299 const std::string& details); 300 301 // Sends a connection close frame to the peer, and closes the connection by 302 // calling CloseConnection(notifying the visitor as it does so). 303 virtual void SendConnectionClose(QuicErrorCode error); 304 virtual void SendConnectionCloseWithDetails(QuicErrorCode error, 305 const std::string& details); 306 // Notifies the visitor of the close and marks the connection as disconnected. 307 virtual void CloseConnection(QuicErrorCode error, bool from_peer) OVERRIDE; 308 virtual void SendGoAway(QuicErrorCode error, 309 QuicStreamId last_good_stream_id, 310 const std::string& reason); 311 312 // Returns statistics tracked for this connection. 313 const QuicConnectionStats& GetStats(); 314 315 // Processes an incoming UDP packet (consisting of a QuicEncryptedPacket) from 316 // the peer. If processing this packet permits a packet to be revived from 317 // its FEC group that packet will be revived and processed. 318 virtual void ProcessUdpPacket(const IPEndPoint& self_address, 319 const IPEndPoint& peer_address, 320 const QuicEncryptedPacket& packet); 321 322 // QuicBlockedWriterInterface 323 // Called when the underlying connection becomes writable to allow queued 324 // writes to happen. 325 virtual void OnCanWrite() OVERRIDE; 326 327 // Called when an error occurs while attempting to write a packet to the 328 // network. 329 void OnWriteError(int error_code); 330 331 // If the socket is not blocked, writes queued packets. 332 void WriteIfNotBlocked(); 333 334 // The version of the protocol this connection is using. 335 QuicVersion version() const { return framer_.version(); } 336 337 // The versions of the protocol that this connection supports. 338 const QuicVersionVector& supported_versions() const { 339 return framer_.supported_versions(); 340 } 341 342 // From QuicFramerVisitorInterface 343 virtual void OnError(QuicFramer* framer) OVERRIDE; 344 virtual bool OnProtocolVersionMismatch(QuicVersion received_version) OVERRIDE; 345 virtual void OnPacket() OVERRIDE; 346 virtual void OnPublicResetPacket( 347 const QuicPublicResetPacket& packet) OVERRIDE; 348 virtual void OnVersionNegotiationPacket( 349 const QuicVersionNegotiationPacket& packet) OVERRIDE; 350 virtual void OnRevivedPacket() OVERRIDE; 351 virtual bool OnUnauthenticatedPublicHeader( 352 const QuicPacketPublicHeader& header) OVERRIDE; 353 virtual bool OnUnauthenticatedHeader(const QuicPacketHeader& header) OVERRIDE; 354 virtual void OnDecryptedPacket(EncryptionLevel level) OVERRIDE; 355 virtual bool OnPacketHeader(const QuicPacketHeader& header) OVERRIDE; 356 virtual void OnFecProtectedPayload(base::StringPiece payload) OVERRIDE; 357 virtual bool OnStreamFrame(const QuicStreamFrame& frame) OVERRIDE; 358 virtual bool OnAckFrame(const QuicAckFrame& frame) OVERRIDE; 359 virtual bool OnCongestionFeedbackFrame( 360 const QuicCongestionFeedbackFrame& frame) OVERRIDE; 361 virtual bool OnStopWaitingFrame(const QuicStopWaitingFrame& frame) OVERRIDE; 362 virtual bool OnPingFrame(const QuicPingFrame& frame) OVERRIDE; 363 virtual bool OnRstStreamFrame(const QuicRstStreamFrame& frame) OVERRIDE; 364 virtual bool OnConnectionCloseFrame( 365 const QuicConnectionCloseFrame& frame) OVERRIDE; 366 virtual bool OnGoAwayFrame(const QuicGoAwayFrame& frame) OVERRIDE; 367 virtual bool OnWindowUpdateFrame(const QuicWindowUpdateFrame& frame) OVERRIDE; 368 virtual bool OnBlockedFrame(const QuicBlockedFrame& frame) OVERRIDE; 369 virtual void OnFecData(const QuicFecData& fec) OVERRIDE; 370 virtual void OnPacketComplete() OVERRIDE; 371 372 // QuicPacketGenerator::DelegateInterface 373 virtual bool ShouldGeneratePacket(TransmissionType transmission_type, 374 HasRetransmittableData retransmittable, 375 IsHandshake handshake) OVERRIDE; 376 virtual QuicAckFrame* CreateAckFrame() OVERRIDE; 377 virtual QuicCongestionFeedbackFrame* CreateFeedbackFrame() OVERRIDE; 378 virtual QuicStopWaitingFrame* CreateStopWaitingFrame() OVERRIDE; 379 virtual void OnSerializedPacket(const SerializedPacket& packet) OVERRIDE; 380 381 // QuicSentPacketManager::NetworkChangeVisitor 382 virtual void OnCongestionWindowChange( 383 QuicByteCount congestion_window) OVERRIDE; 384 385 // Called by the crypto stream when the handshake completes. In the server's 386 // case this is when the SHLO has been ACKed. Clients call this on receipt of 387 // the SHLO. 388 void OnHandshakeComplete(); 389 390 // Accessors 391 void set_visitor(QuicConnectionVisitorInterface* visitor) { 392 visitor_ = visitor; 393 } 394 // This method takes ownership of |debug_visitor|. 395 void set_debug_visitor(QuicConnectionDebugVisitor* debug_visitor) { 396 debug_visitor_.reset(debug_visitor); 397 packet_generator_.set_debug_delegate(debug_visitor); 398 sent_packet_manager_.set_debug_delegate(debug_visitor); 399 } 400 const IPEndPoint& self_address() const { return self_address_; } 401 const IPEndPoint& peer_address() const { return peer_address_; } 402 QuicConnectionId connection_id() const { return connection_id_; } 403 const QuicClock* clock() const { return clock_; } 404 QuicRandom* random_generator() const { return random_generator_; } 405 size_t max_packet_length() const; 406 void set_max_packet_length(size_t length); 407 408 bool connected() const { return connected_; } 409 410 // Must only be called on client connections. 411 const QuicVersionVector& server_supported_versions() const { 412 DCHECK(!is_server_); 413 return server_supported_versions_; 414 } 415 416 size_t NumFecGroups() const { return group_map_.size(); } 417 418 // Testing only. 419 size_t NumQueuedPackets() const { return queued_packets_.size(); } 420 421 QuicEncryptedPacket* ReleaseConnectionClosePacket() { 422 return connection_close_packet_.release(); 423 } 424 425 // Returns true if the underlying UDP socket is writable, there is 426 // no queued data and the connection is not congestion-control 427 // blocked. 428 bool CanWriteStreamData(); 429 430 // Returns true if the connection has queued packets or frames. 431 bool HasQueuedData() const; 432 433 // Sets (or resets) the idle state connection timeout. Also, checks and times 434 // out the connection if network timer has expired for |timeout|. 435 void SetIdleNetworkTimeout(QuicTime::Delta timeout); 436 // Sets (or resets) the total time delta the connection can be alive for. 437 // Also, checks and times out the connection if timer has expired for 438 // |timeout|. Used to limit the time a connection can be alive before crypto 439 // handshake finishes. 440 void SetOverallConnectionTimeout(QuicTime::Delta timeout); 441 442 // If the connection has timed out, this will close the connection and return 443 // true. Otherwise, it will return false and will reset the timeout alarm. 444 bool CheckForTimeout(); 445 446 // Sends a ping, and resets the ping alarm. 447 void SendPing(); 448 449 // Sets up a packet with an QuicAckFrame and sends it out. 450 void SendAck(); 451 452 // Called when an RTO fires. Resets the retransmission alarm if there are 453 // remaining unacked packets. 454 void OnRetransmissionTimeout(); 455 456 // Retransmits all unacked packets with retransmittable frames if 457 // |retransmission_type| is ALL_UNACKED_PACKETS, otherwise retransmits only 458 // initially encrypted packets. Used when the negotiated protocol version is 459 // different from what was initially assumed and when the initial encryption 460 // changes. 461 void RetransmitUnackedPackets(TransmissionType retransmission_type); 462 463 // Calls |sent_packet_manager_|'s NeuterUnencryptedPackets. Used when the 464 // connection becomes forward secure and hasn't received acks for all packets. 465 void NeuterUnencryptedPackets(); 466 467 // Changes the encrypter used for level |level| to |encrypter|. The function 468 // takes ownership of |encrypter|. 469 void SetEncrypter(EncryptionLevel level, QuicEncrypter* encrypter); 470 const QuicEncrypter* encrypter(EncryptionLevel level) const; 471 472 // SetDefaultEncryptionLevel sets the encryption level that will be applied 473 // to new packets. 474 void SetDefaultEncryptionLevel(EncryptionLevel level); 475 476 // SetDecrypter sets the primary decrypter, replacing any that already exists, 477 // and takes ownership. If an alternative decrypter is in place then the 478 // function DCHECKs. This is intended for cases where one knows that future 479 // packets will be using the new decrypter and the previous decrypter is now 480 // obsolete. |level| indicates the encryption level of the new decrypter. 481 void SetDecrypter(QuicDecrypter* decrypter, EncryptionLevel level); 482 483 // SetAlternativeDecrypter sets a decrypter that may be used to decrypt 484 // future packets and takes ownership of it. |level| indicates the encryption 485 // level of the decrypter. If |latch_once_used| is true, then the first time 486 // that the decrypter is successful it will replace the primary decrypter. 487 // Otherwise both decrypters will remain active and the primary decrypter 488 // will be the one last used. 489 void SetAlternativeDecrypter(QuicDecrypter* decrypter, 490 EncryptionLevel level, 491 bool latch_once_used); 492 493 const QuicDecrypter* decrypter() const; 494 const QuicDecrypter* alternative_decrypter() const; 495 496 bool is_server() const { return is_server_; } 497 498 // Returns the underlying sent packet manager. 499 const QuicSentPacketManager& sent_packet_manager() const { 500 return sent_packet_manager_; 501 } 502 503 bool CanWrite(HasRetransmittableData retransmittable); 504 505 // Stores current batch state for connection, puts the connection 506 // into batch mode, and destruction restores the stored batch state. 507 // While the bundler is in scope, any generated frames are bundled 508 // as densely as possible into packets. In addition, this bundler 509 // can be configured to ensure that an ACK frame is included in the 510 // first packet created, if there's new ack information to be sent. 511 class ScopedPacketBundler { 512 public: 513 // In addition to all outgoing frames being bundled when the 514 // bundler is in scope, setting |include_ack| to true ensures that 515 // an ACK frame is opportunistically bundled with the first 516 // outgoing packet. 517 ScopedPacketBundler(QuicConnection* connection, AckBundling send_ack); 518 ~ScopedPacketBundler(); 519 520 private: 521 QuicConnection* connection_; 522 bool already_in_batch_mode_; 523 }; 524 525 protected: 526 // Packets which have not been written to the wire. 527 // Owns the QuicPacket* packet. 528 struct QueuedPacket { 529 QueuedPacket(SerializedPacket packet, 530 EncryptionLevel level); 531 QueuedPacket(SerializedPacket packet, 532 EncryptionLevel level, 533 TransmissionType transmission_type, 534 QuicPacketSequenceNumber original_sequence_number); 535 536 SerializedPacket serialized_packet; 537 const EncryptionLevel encryption_level; 538 TransmissionType transmission_type; 539 // The packet's original sequence number if it is a retransmission. 540 // Otherwise it must be 0. 541 QuicPacketSequenceNumber original_sequence_number; 542 }; 543 544 // Do any work which logically would be done in OnPacket but can not be 545 // safely done until the packet is validated. Returns true if the packet 546 // can be handled, false otherwise. 547 virtual bool ProcessValidatedPacket(); 548 549 // Send a packet to the peer, and takes ownership of the packet if the packet 550 // cannot be written immediately. 551 virtual void SendOrQueuePacket(QueuedPacket packet); 552 553 QuicConnectionHelperInterface* helper() { return helper_; } 554 555 // Selects and updates the version of the protocol being used by selecting a 556 // version from |available_versions| which is also supported. Returns true if 557 // such a version exists, false otherwise. 558 bool SelectMutualVersion(const QuicVersionVector& available_versions); 559 560 QuicPacketWriter* writer() { return writer_; } 561 562 bool peer_port_changed() const { return peer_port_changed_; } 563 564 QuicPacketSequenceNumber sequence_number_of_last_sent_packet() const { 565 return sequence_number_of_last_sent_packet_; 566 } 567 568 private: 569 friend class test::QuicConnectionPeer; 570 friend class test::PacketSavingConnection; 571 572 typedef std::list<QueuedPacket> QueuedPacketList; 573 typedef std::map<QuicFecGroupNumber, QuicFecGroup*> FecGroupMap; 574 575 // Writes the given packet to socket, encrypted with packet's 576 // encryption_level. Returns true on successful write, and false if the writer 577 // was blocked and the write needs to be tried again. Notifies the 578 // SentPacketManager when the write is successful and sets 579 // retransmittable frames to NULL. 580 // Saves the connection close packet for later transmission, even if the 581 // writer is write blocked. 582 bool WritePacket(QueuedPacket* packet); 583 584 // Does the main work of WritePacket, but does not delete the packet or 585 // retransmittable frames upon success. 586 bool WritePacketInner(QueuedPacket* packet); 587 588 // Make sure an ack we got from our peer is sane. 589 bool ValidateAckFrame(const QuicAckFrame& incoming_ack); 590 591 // Make sure a stop waiting we got from our peer is sane. 592 bool ValidateStopWaitingFrame(const QuicStopWaitingFrame& stop_waiting); 593 594 // Sends a version negotiation packet to the peer. 595 void SendVersionNegotiationPacket(); 596 597 // Clears any accumulated frames from the last received packet. 598 void ClearLastFrames(); 599 600 // Writes as many queued packets as possible. The connection must not be 601 // blocked when this is called. 602 void WriteQueuedPackets(); 603 604 // Writes as many pending retransmissions as possible. 605 void WritePendingRetransmissions(); 606 607 // Returns true if the packet should be discarded and not sent. 608 bool ShouldDiscardPacket(const QueuedPacket& packet); 609 610 // Queues |packet| in the hopes that it can be decrypted in the 611 // future, when a new key is installed. 612 void QueueUndecryptablePacket(const QuicEncryptedPacket& packet); 613 614 // Attempts to process any queued undecryptable packets. 615 void MaybeProcessUndecryptablePackets(); 616 617 // If a packet can be revived from the current FEC group, then 618 // revive and process the packet. 619 void MaybeProcessRevivedPacket(); 620 621 void ProcessAckFrame(const QuicAckFrame& incoming_ack); 622 623 void ProcessStopWaitingFrame(const QuicStopWaitingFrame& stop_waiting); 624 625 // Update |stop_waiting| for an outgoing ack. 626 void UpdateStopWaiting(QuicStopWaitingFrame* stop_waiting); 627 628 // Queues an ack or sets the ack alarm when an incoming packet arrives that 629 // should be acked. 630 void MaybeQueueAck(); 631 632 // Checks if the last packet should instigate an ack. 633 bool ShouldLastPacketInstigateAck() const; 634 635 // Checks if the peer is waiting for packets that have been given up on, and 636 // therefore an ack frame should be sent with a larger least_unacked. 637 void UpdateStopWaitingCount(); 638 639 // Sends any packets which are a response to the last packet, including both 640 // acks and pending writes if an ack opened the congestion window. 641 void MaybeSendInResponseToPacket(); 642 643 // Gets the least unacked sequence number, which is the next sequence number 644 // to be sent if there are no outstanding packets. 645 QuicPacketSequenceNumber GetLeastUnacked() const; 646 647 // Get the FEC group associate with the last processed packet or NULL, if the 648 // group has already been deleted. 649 QuicFecGroup* GetFecGroup(); 650 651 // Closes any FEC groups protecting packets before |sequence_number|. 652 void CloseFecGroupsBefore(QuicPacketSequenceNumber sequence_number); 653 654 // Sets the ping alarm to the appropriate value, if any. 655 void SetPingAlarm(); 656 657 // On arrival of a new packet, checks to see if the socket addresses have 658 // changed since the last packet we saw on this connection. 659 void CheckForAddressMigration(const IPEndPoint& self_address, 660 const IPEndPoint& peer_address); 661 662 HasRetransmittableData IsRetransmittable(const QueuedPacket& packet); 663 bool IsConnectionClose(QueuedPacket packet); 664 665 QuicFramer framer_; 666 QuicConnectionHelperInterface* helper_; // Not owned. 667 QuicPacketWriter* writer_; // Owned or not depending on |owns_writer_|. 668 bool owns_writer_; 669 EncryptionLevel encryption_level_; 670 const QuicClock* clock_; 671 QuicRandom* random_generator_; 672 673 const QuicConnectionId connection_id_; 674 // Address on the last successfully processed packet received from the 675 // client. 676 IPEndPoint self_address_; 677 IPEndPoint peer_address_; 678 // Used to store latest peer port to possibly migrate to later. 679 int migrating_peer_port_; 680 681 bool last_packet_revived_; // True if the last packet was revived from FEC. 682 size_t last_size_; // Size of the last received packet. 683 EncryptionLevel last_decrypted_packet_level_; 684 QuicPacketHeader last_header_; 685 std::vector<QuicStreamFrame> last_stream_frames_; 686 std::vector<QuicAckFrame> last_ack_frames_; 687 std::vector<QuicCongestionFeedbackFrame> last_congestion_frames_; 688 std::vector<QuicStopWaitingFrame> last_stop_waiting_frames_; 689 std::vector<QuicRstStreamFrame> last_rst_frames_; 690 std::vector<QuicGoAwayFrame> last_goaway_frames_; 691 std::vector<QuicWindowUpdateFrame> last_window_update_frames_; 692 std::vector<QuicBlockedFrame> last_blocked_frames_; 693 std::vector<QuicPingFrame> last_ping_frames_; 694 std::vector<QuicConnectionCloseFrame> last_close_frames_; 695 696 QuicCongestionFeedbackFrame outgoing_congestion_feedback_; 697 698 // Track some peer state so we can do less bookkeeping 699 // Largest sequence sent by the peer which had an ack frame (latest ack info). 700 QuicPacketSequenceNumber largest_seen_packet_with_ack_; 701 702 // Largest sequence number sent by the peer which had a stop waiting frame. 703 QuicPacketSequenceNumber largest_seen_packet_with_stop_waiting_; 704 705 // Collection of packets which were received before encryption was 706 // established, but which could not be decrypted. We buffer these on 707 // the assumption that they could not be processed because they were 708 // sent with the INITIAL encryption and the CHLO message was lost. 709 std::deque<QuicEncryptedPacket*> undecryptable_packets_; 710 711 // When the version negotiation packet could not be sent because the socket 712 // was not writable, this is set to true. 713 bool pending_version_negotiation_packet_; 714 715 // When packets could not be sent because the socket was not writable, 716 // they are added to this list. All corresponding frames are in 717 // unacked_packets_ if they are to be retransmitted. 718 QueuedPacketList queued_packets_; 719 720 // Contains the connection close packet if the connection has been closed. 721 scoped_ptr<QuicEncryptedPacket> connection_close_packet_; 722 723 FecGroupMap group_map_; 724 725 QuicReceivedPacketManager received_packet_manager_; 726 QuicSentEntropyManager sent_entropy_manager_; 727 728 // Indicates whether an ack should be sent the next time we try to write. 729 bool ack_queued_; 730 // Indicates how many consecutive packets have arrived without sending an ack. 731 uint32 num_packets_received_since_last_ack_sent_; 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_; 735 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_; 750 751 QuicConnectionVisitorInterface* visitor_; 752 scoped_ptr<QuicConnectionDebugVisitor> debug_visitor_; 753 QuicPacketGenerator packet_generator_; 754 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_; 759 760 // Statistics for this session. 761 QuicConnectionStats stats_; 762 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_; 766 767 // The last time a new (non-retransmitted) packet was sent for this 768 // connection. 769 QuicTime time_of_last_sent_new_packet_; 770 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_; 774 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_; 779 780 // The state of connection in version negotiation finite state machine. 781 QuicVersionNegotiationState version_negotiation_state_; 782 783 // Tracks if the connection was created by the server. 784 bool is_server_; 785 786 // True by default. False if we've received or sent an explicit connection 787 // close. 788 bool connected_; 789 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_; 793 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_; 797 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_; 801 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_; 805 806 // If non-empty this contains the set of versions received in a 807 // version negotiation packet. 808 QuicVersionVector server_supported_versions_; 809 810 DISALLOW_COPY_AND_ASSIGN(QuicConnection); 811 }; 812 813 } // namespace net 814 815 #endif // NET_QUIC_QUIC_CONNECTION_H_ 816