Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(203)

Side by Side Diff: net/quic/quic_connection.h

Issue 2193073003: Move shared files in net/quic/ into net/quic/core/ (Closed) Base URL: https://chromium.googlesource.com/chromium/src.git@master
Patch Set: io_thread_unittest.cc Created 4 years, 4 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
« no previous file with comments | « net/quic/quic_config_test.cc ('k') | net/quic/quic_connection.cc » ('j') | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
(Empty)
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 <stdint.h>
21
22 #include <deque>
23 #include <list>
24 #include <map>
25 #include <memory>
26 #include <queue>
27 #include <string>
28 #include <vector>
29
30 #include "base/logging.h"
31 #include "base/macros.h"
32 #include "base/strings/string_piece.h"
33 #include "net/base/ip_address.h"
34 #include "net/base/ip_endpoint.h"
35 #include "net/quic/crypto/quic_decrypter.h"
36 #include "net/quic/quic_alarm.h"
37 #include "net/quic/quic_alarm_factory.h"
38 #include "net/quic/quic_blocked_writer_interface.h"
39 #include "net/quic/quic_connection_stats.h"
40 #include "net/quic/quic_framer.h"
41 #include "net/quic/quic_multipath_sent_packet_manager.h"
42 #include "net/quic/quic_one_block_arena.h"
43 #include "net/quic/quic_packet_creator.h"
44 #include "net/quic/quic_packet_generator.h"
45 #include "net/quic/quic_packet_writer.h"
46 #include "net/quic/quic_protocol.h"
47 #include "net/quic/quic_received_packet_manager.h"
48 #include "net/quic/quic_sent_entropy_manager.h"
49 #include "net/quic/quic_sent_packet_manager_interface.h"
50 #include "net/quic/quic_time.h"
51 #include "net/quic/quic_types.h"
52
53 namespace net {
54
55 class QuicClock;
56 class QuicConfig;
57 class QuicConnection;
58 class QuicEncrypter;
59 class QuicRandom;
60
61 namespace test {
62 class PacketSavingConnection;
63 class QuicConnectionPeer;
64 } // namespace test
65
66 // The initial number of packets between MTU probes. After each attempt the
67 // number is doubled.
68 const QuicPacketCount kPacketsBetweenMtuProbesBase = 100;
69
70 // The number of MTU probes that get sent before giving up.
71 const size_t kMtuDiscoveryAttempts = 3;
72
73 // Ensure that exponential back-off does not result in an integer overflow.
74 // The number of packets can be potentially capped, but that is not useful at
75 // current kMtuDiscoveryAttempts value, and hence is not implemented at present.
76 static_assert(kMtuDiscoveryAttempts + 8 < 8 * sizeof(QuicPacketNumber),
77 "The number of MTU discovery attempts is too high");
78 static_assert(kPacketsBetweenMtuProbesBase < (1 << 8),
79 "The initial number of packets between MTU probes is too high");
80
81 // The incresed packet size targeted when doing path MTU discovery.
82 const QuicByteCount kMtuDiscoveryTargetPacketSizeHigh = 1450;
83 const QuicByteCount kMtuDiscoveryTargetPacketSizeLow = 1430;
84
85 static_assert(kMtuDiscoveryTargetPacketSizeLow <= kMaxPacketSize,
86 "MTU discovery target is too large");
87 static_assert(kMtuDiscoveryTargetPacketSizeHigh <= kMaxPacketSize,
88 "MTU discovery target is too large");
89
90 static_assert(kMtuDiscoveryTargetPacketSizeLow > kDefaultMaxPacketSize,
91 "MTU discovery target does not exceed the default packet size");
92 static_assert(kMtuDiscoveryTargetPacketSizeHigh > kDefaultMaxPacketSize,
93 "MTU discovery target does not exceed the default packet size");
94
95 // Class that receives callbacks from the connection when frames are received
96 // and when other interesting events happen.
97 class NET_EXPORT_PRIVATE QuicConnectionVisitorInterface {
98 public:
99 virtual ~QuicConnectionVisitorInterface() {}
100
101 // A simple visitor interface for dealing with a data frame.
102 virtual void OnStreamFrame(const QuicStreamFrame& frame) = 0;
103
104 // The session should process the WINDOW_UPDATE frame, adjusting both stream
105 // and connection level flow control windows.
106 virtual void OnWindowUpdateFrame(const QuicWindowUpdateFrame& frame) = 0;
107
108 // A BLOCKED frame indicates the peer is flow control blocked
109 // on a specified stream.
110 virtual void OnBlockedFrame(const QuicBlockedFrame& frame) = 0;
111
112 // Called when the stream is reset by the peer.
113 virtual void OnRstStream(const QuicRstStreamFrame& frame) = 0;
114
115 // Called when the connection is going away according to the peer.
116 virtual void OnGoAway(const QuicGoAwayFrame& frame) = 0;
117
118 // Called when the connection is closed either locally by the framer, or
119 // remotely by the peer.
120 virtual void OnConnectionClosed(QuicErrorCode error,
121 const std::string& error_details,
122 ConnectionCloseSource source) = 0;
123
124 // Called when the connection failed to write because the socket was blocked.
125 virtual void OnWriteBlocked() = 0;
126
127 // Called once a specific QUIC version is agreed by both endpoints.
128 virtual void OnSuccessfulVersionNegotiation(const QuicVersion& version) = 0;
129
130 // Called when a blocked socket becomes writable.
131 virtual void OnCanWrite() = 0;
132
133 // Called when the connection experiences a change in congestion window.
134 virtual void OnCongestionWindowChange(QuicTime now) = 0;
135
136 // Called when the connection receives a packet from a migrated client.
137 virtual void OnConnectionMigration(PeerAddressChangeType type) = 0;
138
139 // Called when the peer seems unreachable over the current path.
140 virtual void OnPathDegrading() = 0;
141
142 // Called after OnStreamFrame, OnRstStream, OnGoAway, OnWindowUpdateFrame,
143 // OnBlockedFrame, and OnCanWrite to allow post-processing once the work has
144 // been done.
145 virtual void PostProcessAfterData() = 0;
146
147 // Called to ask if the visitor wants to schedule write resumption as it both
148 // has pending data to write, and is able to write (e.g. based on flow control
149 // limits).
150 // Writes may be pending because they were write-blocked, congestion-throttled
151 // or yielded to other connections.
152 virtual bool WillingAndAbleToWrite() const = 0;
153
154 // Called to ask if any handshake messages are pending in this visitor.
155 virtual bool HasPendingHandshake() const = 0;
156
157 // Called to ask if any streams are open in this visitor, excluding the
158 // reserved crypto and headers stream.
159 virtual bool HasOpenDynamicStreams() const = 0;
160 };
161
162 // Interface which gets callbacks from the QuicConnection at interesting
163 // points. Implementations must not mutate the state of the connection
164 // as a result of these callbacks.
165 class NET_EXPORT_PRIVATE QuicConnectionDebugVisitor
166 : public QuicSentPacketManagerInterface::DebugDelegate {
167 public:
168 ~QuicConnectionDebugVisitor() override {}
169
170 // Called when a packet has been sent.
171 virtual void OnPacketSent(const SerializedPacket& serialized_packet,
172 QuicPathId original_path_id,
173 QuicPacketNumber original_packet_number,
174 TransmissionType transmission_type,
175 QuicTime sent_time) {}
176
177 // Called when a packet has been received, but before it is
178 // validated or parsed.
179 virtual void OnPacketReceived(const IPEndPoint& self_address,
180 const IPEndPoint& peer_address,
181 const QuicEncryptedPacket& packet) {}
182
183 // Called when the unauthenticated portion of the header has been parsed.
184 virtual void OnUnauthenticatedHeader(const QuicPacketHeader& header) {}
185
186 // Called when a packet is received with a connection id that does not
187 // match the ID of this connection.
188 virtual void OnIncorrectConnectionId(QuicConnectionId connection_id) {}
189
190 // Called when an undecryptable packet has been received.
191 virtual void OnUndecryptablePacket() {}
192
193 // Called when a duplicate packet has been received.
194 virtual void OnDuplicatePacket(QuicPacketNumber packet_number) {}
195
196 // Called when the protocol version on the received packet doensn't match
197 // current protocol version of the connection.
198 virtual void OnProtocolVersionMismatch(QuicVersion version) {}
199
200 // Called when the complete header of a packet has been parsed.
201 virtual void OnPacketHeader(const QuicPacketHeader& header) {}
202
203 // Called when a StreamFrame has been parsed.
204 virtual void OnStreamFrame(const QuicStreamFrame& frame) {}
205
206 // Called when a AckFrame has been parsed.
207 virtual void OnAckFrame(const QuicAckFrame& frame) {}
208
209 // Called when a StopWaitingFrame has been parsed.
210 virtual void OnStopWaitingFrame(const QuicStopWaitingFrame& frame) {}
211
212 // Called when a QuicPaddingFrame has been parsed.
213 virtual void OnPaddingFrame(const QuicPaddingFrame& frame) {}
214
215 // Called when a Ping has been parsed.
216 virtual void OnPingFrame(const QuicPingFrame& frame) {}
217
218 // Called when a GoAway has been parsed.
219 virtual void OnGoAwayFrame(const QuicGoAwayFrame& frame) {}
220
221 // Called when a RstStreamFrame has been parsed.
222 virtual void OnRstStreamFrame(const QuicRstStreamFrame& frame) {}
223
224 // Called when a ConnectionCloseFrame has been parsed.
225 virtual void OnConnectionCloseFrame(const QuicConnectionCloseFrame& frame) {}
226
227 // Called when a WindowUpdate has been parsed.
228 virtual void OnWindowUpdateFrame(const QuicWindowUpdateFrame& frame) {}
229
230 // Called when a BlockedFrame has been parsed.
231 virtual void OnBlockedFrame(const QuicBlockedFrame& frame) {}
232
233 // Called when a PathCloseFrame has been parsed.
234 virtual void OnPathCloseFrame(const QuicPathCloseFrame& frame) {}
235
236 // Called when a public reset packet has been received.
237 virtual void OnPublicResetPacket(const QuicPublicResetPacket& packet) {}
238
239 // Called when a version negotiation packet has been received.
240 virtual void OnVersionNegotiationPacket(
241 const QuicVersionNegotiationPacket& packet) {}
242
243 // Called when the connection is closed.
244 virtual void OnConnectionClosed(QuicErrorCode error,
245 const std::string& error_details,
246 ConnectionCloseSource source) {}
247
248 // Called when the version negotiation is successful.
249 virtual void OnSuccessfulVersionNegotiation(const QuicVersion& version) {}
250
251 // Called when a CachedNetworkParameters is sent to the client.
252 virtual void OnSendConnectionState(
253 const CachedNetworkParameters& cached_network_params) {}
254
255 // Called when a CachedNetworkParameters are recieved from the client.
256 virtual void OnReceiveConnectionState(
257 const CachedNetworkParameters& cached_network_params) {}
258
259 // Called when the connection parameters are set from the supplied
260 // |config|.
261 virtual void OnSetFromConfig(const QuicConfig& config) {}
262
263 // Called when RTT may have changed, including when an RTT is read from
264 // the config.
265 virtual void OnRttChanged(QuicTime::Delta rtt) const {}
266 };
267
268 // QuicConnections currently use around 1KB of polymorphic types which would
269 // ordinarily be on the heap. Instead, store them inline in an arena.
270 using QuicConnectionArena = QuicOneBlockArena<1024>;
271
272 class NET_EXPORT_PRIVATE QuicConnectionHelperInterface {
273 public:
274 virtual ~QuicConnectionHelperInterface() {}
275
276 // Returns a QuicClock to be used for all time related functions.
277 virtual const QuicClock* GetClock() const = 0;
278
279 // Returns a QuicRandom to be used for all random number related functions.
280 virtual QuicRandom* GetRandomGenerator() = 0;
281
282 // Returns a QuicBufferAllocator to be used for all stream frame buffers.
283 virtual QuicBufferAllocator* GetBufferAllocator() = 0;
284 };
285
286 class NET_EXPORT_PRIVATE QuicConnection
287 : public QuicFramerVisitorInterface,
288 public QuicBlockedWriterInterface,
289 public QuicPacketGenerator::DelegateInterface,
290 public QuicSentPacketManagerInterface::NetworkChangeVisitor {
291 public:
292 enum AckBundling {
293 // Send an ack if it's already queued in the connection.
294 SEND_ACK_IF_QUEUED,
295 // Always send an ack.
296 SEND_ACK,
297 // Bundle an ack with outgoing data.
298 SEND_ACK_IF_PENDING,
299 };
300
301 enum AckMode { TCP_ACKING, ACK_DECIMATION, ACK_DECIMATION_WITH_REORDERING };
302
303 // Constructs a new QuicConnection for |connection_id| and |address| using
304 // |writer| to write packets. |owns_writer| specifies whether the connection
305 // takes ownership of |writer|. |helper| must outlive this connection.
306 QuicConnection(QuicConnectionId connection_id,
307 IPEndPoint address,
308 QuicConnectionHelperInterface* helper,
309 QuicAlarmFactory* alarm_factory,
310 QuicPacketWriter* writer,
311 bool owns_writer,
312 Perspective perspective,
313 const QuicVersionVector& supported_versions);
314 ~QuicConnection() override;
315
316 // Sets connection parameters from the supplied |config|.
317 void SetFromConfig(const QuicConfig& config);
318
319 // Called by the session when sending connection state to the client.
320 virtual void OnSendConnectionState(
321 const CachedNetworkParameters& cached_network_params);
322
323 // Called by the session when receiving connection state from the client.
324 virtual void OnReceiveConnectionState(
325 const CachedNetworkParameters& cached_network_params);
326
327 // Called by the Session when the client has provided CachedNetworkParameters.
328 virtual void ResumeConnectionState(
329 const CachedNetworkParameters& cached_network_params,
330 bool max_bandwidth_resumption);
331
332 // Called by the Session when a max pacing rate for the connection is needed.
333 virtual void SetMaxPacingRate(QuicBandwidth max_pacing_rate);
334
335 // Sets the number of active streams on the connection for congestion control.
336 void SetNumOpenStreams(size_t num_streams);
337
338 // Send the data in |data| to the peer in as few packets as possible.
339 // Returns a pair with the number of bytes consumed from data, and a boolean
340 // indicating if the fin bit was consumed. This does not indicate the data
341 // has been sent on the wire: it may have been turned into a packet and queued
342 // if the socket was unexpectedly blocked.
343 // If |listener| is provided, then it will be informed once ACKs have been
344 // received for all the packets written in this call.
345 // The |listener| is not owned by the QuicConnection and must outlive it.
346 virtual QuicConsumedData SendStreamData(QuicStreamId id,
347 QuicIOVector iov,
348 QuicStreamOffset offset,
349 bool fin,
350 QuicAckListenerInterface* listener);
351
352 // Send a RST_STREAM frame to the peer.
353 virtual void SendRstStream(QuicStreamId id,
354 QuicRstStreamErrorCode error,
355 QuicStreamOffset bytes_written);
356
357 // Send a BLOCKED frame to the peer.
358 virtual void SendBlocked(QuicStreamId id);
359
360 // Send a WINDOW_UPDATE frame to the peer.
361 virtual void SendWindowUpdate(QuicStreamId id, QuicStreamOffset byte_offset);
362
363 // Send a PATH_CLOSE frame to the peer.
364 virtual void SendPathClose(QuicPathId path_id);
365
366 // Closes the connection.
367 // |connection_close_behavior| determines whether or not a connection close
368 // packet is sent to the peer.
369 virtual void CloseConnection(
370 QuicErrorCode error,
371 const std::string& details,
372 ConnectionCloseBehavior connection_close_behavior);
373
374 // Sends a GOAWAY frame. Does nothing if a GOAWAY frame has already been sent.
375 virtual void SendGoAway(QuicErrorCode error,
376 QuicStreamId last_good_stream_id,
377 const std::string& reason);
378
379 // Returns statistics tracked for this connection.
380 const QuicConnectionStats& GetStats();
381
382 // Processes an incoming UDP packet (consisting of a QuicEncryptedPacket) from
383 // the peer.
384 // In a client, the packet may be "stray" and have a different connection ID
385 // than that of this connection.
386 virtual void ProcessUdpPacket(const IPEndPoint& self_address,
387 const IPEndPoint& peer_address,
388 const QuicReceivedPacket& packet);
389
390 // QuicBlockedWriterInterface
391 // Called when the underlying connection becomes writable to allow queued
392 // writes to happen.
393 void OnCanWrite() override;
394
395 // Called when an error occurs while attempting to write a packet to the
396 // network.
397 void OnWriteError(int error_code);
398
399 // If the socket is not blocked, writes queued packets.
400 void WriteIfNotBlocked();
401
402 // If the socket is not blocked, writes queued packets and bundles any pending
403 // ACKs.
404 void WriteAndBundleAcksIfNotBlocked();
405
406 // Set the packet writer.
407 void SetQuicPacketWriter(QuicPacketWriter* writer, bool owns_writer) {
408 DCHECK(writer != nullptr);
409 if (writer_ != nullptr && owns_writer_) {
410 delete writer_;
411 }
412 writer_ = writer;
413 owns_writer_ = owns_writer;
414 }
415
416 // Set self address.
417 void SetSelfAddress(IPEndPoint address) { self_address_ = address; }
418
419 // The version of the protocol this connection is using.
420 QuicVersion version() const { return framer_.version(); }
421
422 // The versions of the protocol that this connection supports.
423 const QuicVersionVector& supported_versions() const {
424 return framer_.supported_versions();
425 }
426
427 // From QuicFramerVisitorInterface
428 void OnError(QuicFramer* framer) override;
429 bool OnProtocolVersionMismatch(QuicVersion received_version) override;
430 void OnPacket() override;
431 void OnPublicResetPacket(const QuicPublicResetPacket& packet) override;
432 void OnVersionNegotiationPacket(
433 const QuicVersionNegotiationPacket& packet) override;
434 bool OnUnauthenticatedPublicHeader(
435 const QuicPacketPublicHeader& header) override;
436 bool OnUnauthenticatedHeader(const QuicPacketHeader& header) override;
437 void OnDecryptedPacket(EncryptionLevel level) override;
438 bool OnPacketHeader(const QuicPacketHeader& header) override;
439 bool OnStreamFrame(const QuicStreamFrame& frame) override;
440 bool OnAckFrame(const QuicAckFrame& frame) override;
441 bool OnStopWaitingFrame(const QuicStopWaitingFrame& frame) override;
442 bool OnPaddingFrame(const QuicPaddingFrame& frame) override;
443 bool OnPingFrame(const QuicPingFrame& frame) override;
444 bool OnRstStreamFrame(const QuicRstStreamFrame& frame) override;
445 bool OnConnectionCloseFrame(const QuicConnectionCloseFrame& frame) override;
446 bool OnGoAwayFrame(const QuicGoAwayFrame& frame) override;
447 bool OnWindowUpdateFrame(const QuicWindowUpdateFrame& frame) override;
448 bool OnBlockedFrame(const QuicBlockedFrame& frame) override;
449 bool OnPathCloseFrame(const QuicPathCloseFrame& frame) override;
450 void OnPacketComplete() override;
451
452 // QuicConnectionCloseDelegateInterface
453 void OnUnrecoverableError(QuicErrorCode error,
454 const std::string& error_details,
455 ConnectionCloseSource source) override;
456
457 // QuicPacketGenerator::DelegateInterface
458 bool ShouldGeneratePacket(HasRetransmittableData retransmittable,
459 IsHandshake handshake) override;
460 const QuicFrame GetUpdatedAckFrame() override;
461 void PopulateStopWaitingFrame(QuicStopWaitingFrame* stop_waiting) override;
462
463 // QuicPacketCreator::DelegateInterface
464 void OnSerializedPacket(SerializedPacket* packet) override;
465
466 // QuicSentPacketManager::NetworkChangeVisitor
467 void OnCongestionChange() override;
468 void OnPathDegrading() override;
469 void OnPathMtuIncreased(QuicPacketLength packet_size) override;
470
471 // Called by the crypto stream when the handshake completes. In the server's
472 // case this is when the SHLO has been ACKed. Clients call this on receipt of
473 // the SHLO.
474 void OnHandshakeComplete();
475
476 // Accessors
477 void set_visitor(QuicConnectionVisitorInterface* visitor) {
478 visitor_ = visitor;
479 }
480 void set_debug_visitor(QuicConnectionDebugVisitor* debug_visitor) {
481 debug_visitor_ = debug_visitor;
482 sent_packet_manager_->SetDebugDelegate(debug_visitor);
483 }
484 // Used in Chromium, but not internally.
485 void set_creator_debug_delegate(QuicPacketCreator::DebugDelegate* visitor) {
486 packet_generator_.set_debug_delegate(visitor);
487 }
488 const IPEndPoint& self_address() const { return self_address_; }
489 const IPEndPoint& peer_address() const { return peer_address_; }
490 QuicConnectionId connection_id() const { return connection_id_; }
491 const QuicClock* clock() const { return clock_; }
492 QuicRandom* random_generator() const { return random_generator_; }
493 QuicByteCount max_packet_length() const;
494 void SetMaxPacketLength(QuicByteCount length);
495
496 size_t mtu_probe_count() const { return mtu_probe_count_; }
497
498 bool connected() const { return connected_; }
499
500 bool goaway_sent() const { return goaway_sent_; }
501
502 bool goaway_received() const { return goaway_received_; }
503
504 // Must only be called on client connections.
505 const QuicVersionVector& server_supported_versions() const {
506 DCHECK_EQ(Perspective::IS_CLIENT, perspective_);
507 return server_supported_versions_;
508 }
509
510 // Testing only.
511 size_t NumQueuedPackets() const { return queued_packets_.size(); }
512
513 // Once called, any sent crypto packets to be saved as the
514 // termination packet, for use with stateless rejections.
515 void EnableSavingCryptoPackets();
516
517 // Returns true if the underlying UDP socket is writable, there is
518 // no queued data and the connection is not congestion-control
519 // blocked.
520 bool CanWriteStreamData();
521
522 // Returns true if the connection has queued packets or frames.
523 bool HasQueuedData() const;
524
525 // Sets the handshake and idle state connection timeouts.
526 void SetNetworkTimeouts(QuicTime::Delta handshake_timeout,
527 QuicTime::Delta idle_timeout);
528
529 // If the connection has timed out, this will close the connection.
530 // Otherwise, it will reschedule the timeout alarm.
531 void CheckForTimeout();
532
533 // Called when the ping alarm fires. Causes a ping frame to be sent only
534 // if the retransmission alarm is not running.
535 void OnPingTimeout();
536
537 // Sends a ping frame.
538 void SendPing();
539
540 // Sets up a packet with an QuicAckFrame and sends it out.
541 void SendAck();
542
543 // Called when an RTO fires. Resets the retransmission alarm if there are
544 // remaining unacked packets.
545 void OnRetransmissionTimeout();
546
547 // Retransmits all unacked packets with retransmittable frames if
548 // |retransmission_type| is ALL_UNACKED_PACKETS, otherwise retransmits only
549 // initially encrypted packets. Used when the negotiated protocol version is
550 // different from what was initially assumed and when the initial encryption
551 // changes.
552 void RetransmitUnackedPackets(TransmissionType retransmission_type);
553
554 // Calls |sent_packet_manager_|'s NeuterUnencryptedPackets. Used when the
555 // connection becomes forward secure and hasn't received acks for all packets.
556 void NeuterUnencryptedPackets();
557
558 // Changes the encrypter used for level |level| to |encrypter|. The function
559 // takes ownership of |encrypter|.
560 void SetEncrypter(EncryptionLevel level, QuicEncrypter* encrypter);
561
562 // SetNonceForPublicHeader sets the nonce that will be transmitted in the
563 // public header of each packet encrypted at the initial encryption level
564 // decrypted. This should only be called on the server side.
565 void SetDiversificationNonce(const DiversificationNonce nonce);
566
567 // SetDefaultEncryptionLevel sets the encryption level that will be applied
568 // to new packets.
569 void SetDefaultEncryptionLevel(EncryptionLevel level);
570
571 // SetDecrypter sets the primary decrypter, replacing any that already exists,
572 // and takes ownership. If an alternative decrypter is in place then the
573 // function DCHECKs. This is intended for cases where one knows that future
574 // packets will be using the new decrypter and the previous decrypter is now
575 // obsolete. |level| indicates the encryption level of the new decrypter.
576 void SetDecrypter(EncryptionLevel level, QuicDecrypter* decrypter);
577
578 // SetAlternativeDecrypter sets a decrypter that may be used to decrypt
579 // future packets and takes ownership of it. |level| indicates the encryption
580 // level of the decrypter. If |latch_once_used| is true, then the first time
581 // that the decrypter is successful it will replace the primary decrypter.
582 // Otherwise both decrypters will remain active and the primary decrypter
583 // will be the one last used.
584 void SetAlternativeDecrypter(EncryptionLevel level,
585 QuicDecrypter* decrypter,
586 bool latch_once_used);
587
588 const QuicDecrypter* decrypter() const;
589 const QuicDecrypter* alternative_decrypter() const;
590
591 Perspective perspective() const { return perspective_; }
592
593 // Allow easy overriding of truncated connection IDs.
594 void set_can_truncate_connection_ids(bool can) {
595 can_truncate_connection_ids_ = can;
596 }
597
598 // Returns the underlying sent packet manager.
599 const QuicSentPacketManagerInterface& sent_packet_manager() const {
600 return *sent_packet_manager_;
601 }
602
603 bool CanWrite(HasRetransmittableData retransmittable);
604
605 // Stores current batch state for connection, puts the connection
606 // into batch mode, and destruction restores the stored batch state.
607 // While the bundler is in scope, any generated frames are bundled
608 // as densely as possible into packets. In addition, this bundler
609 // can be configured to ensure that an ACK frame is included in the
610 // first packet created, if there's new ack information to be sent.
611 class NET_EXPORT_PRIVATE ScopedPacketBundler {
612 public:
613 // In addition to all outgoing frames being bundled when the
614 // bundler is in scope, setting |include_ack| to true ensures that
615 // an ACK frame is opportunistically bundled with the first
616 // outgoing packet.
617 ScopedPacketBundler(QuicConnection* connection, AckBundling send_ack);
618 ~ScopedPacketBundler();
619
620 private:
621 bool ShouldSendAck(AckBundling ack_mode) const;
622
623 QuicConnection* connection_;
624 bool already_in_batch_mode_;
625 };
626
627 // Delays setting the retransmission alarm until the scope is exited.
628 // When nested, only the outermost scheduler will set the alarm, and inner
629 // ones have no effect.
630 class NET_EXPORT_PRIVATE ScopedRetransmissionScheduler {
631 public:
632 explicit ScopedRetransmissionScheduler(QuicConnection* connection);
633 ~ScopedRetransmissionScheduler();
634
635 private:
636 QuicConnection* connection_;
637 // Set to the connection's delay_setting_retransmission_alarm_ value in the
638 // constructor and when true, causes this class to do nothing.
639 const bool already_delayed_;
640 };
641
642 QuicPacketNumber packet_number_of_last_sent_packet() const {
643 return packet_number_of_last_sent_packet_;
644 }
645
646 QuicPacketWriter* writer() { return writer_; }
647 const QuicPacketWriter* writer() const { return writer_; }
648
649 // Sends an MTU discovery packet of size |target_mtu|. If the packet is
650 // acknowledged by the peer, the maximum packet size will be increased to
651 // |target_mtu|.
652 void SendMtuDiscoveryPacket(QuicByteCount target_mtu);
653
654 // Sends an MTU discovery packet of size |mtu_discovery_target_| and updates
655 // the MTU discovery alarm.
656 void DiscoverMtu();
657
658 // Return the name of the cipher of the primary decrypter of the framer.
659 const char* cipher_name() const { return framer_.decrypter()->cipher_name(); }
660 // Return the id of the cipher of the primary decrypter of the framer.
661 uint32_t cipher_id() const { return framer_.decrypter()->cipher_id(); }
662
663 std::vector<std::unique_ptr<QuicEncryptedPacket>>* termination_packets() {
664 return termination_packets_.get();
665 }
666
667 bool ack_queued() const { return ack_queued_; }
668
669 bool ack_frame_updated() const;
670
671 QuicConnectionHelperInterface* helper() { return helper_; }
672 QuicAlarmFactory* alarm_factory() { return alarm_factory_; }
673
674 base::StringPiece GetCurrentPacket();
675
676 const QuicPacketGenerator& packet_generator() const {
677 return packet_generator_;
678 }
679
680 EncryptionLevel encryption_level() const { return encryption_level_; }
681
682 const IPEndPoint& last_packet_source_address() const {
683 return last_packet_source_address_;
684 }
685
686 protected:
687 // Calls cancel() on all the alarms owned by this connection.
688 void CancelAllAlarms();
689
690 // Send a packet to the peer, and takes ownership of the packet if the packet
691 // cannot be written immediately.
692 virtual void SendOrQueuePacket(SerializedPacket* packet);
693
694 // Called after a packet is received from a new peer address on existing
695 // |path_id| and is decrypted. Starts validation of peer's address change.
696 virtual void StartPeerMigration(QuicPathId path_id,
697 PeerAddressChangeType peer_migration_type);
698
699 // Called when a peer address migration is validated on |path_id|.
700 virtual void OnPeerMigrationValidated(QuicPathId path_id);
701
702 // Selects and updates the version of the protocol being used by selecting a
703 // version from |available_versions| which is also supported. Returns true if
704 // such a version exists, false otherwise.
705 bool SelectMutualVersion(const QuicVersionVector& available_versions);
706
707 // Returns the current per-packet options for the connection.
708 PerPacketOptions* per_packet_options() { return per_packet_options_; }
709 // Sets the current per-packet options for the connection. The QuicConnection
710 // does not take ownership of |options|; |options| must live for as long as
711 // the QuicConnection is in use.
712 void set_per_packet_options(PerPacketOptions* options) {
713 per_packet_options_ = options;
714 }
715
716 // If |defer| is true, configures the connection to defer sending packets in
717 // response to an ACK to the SendAlarm. If |defer| is false, packets may be
718 // sent immediately after receiving an ACK.
719 void set_defer_send_in_response_to_packets(bool defer) {
720 defer_send_in_response_to_packets_ = defer;
721 }
722
723 PeerAddressChangeType active_peer_migration_type() {
724 return active_peer_migration_type_;
725 }
726
727 // Sends the connection close packet to the peer.
728 virtual void SendConnectionClosePacket(QuicErrorCode error,
729 const std::string& details);
730
731 private:
732 friend class test::QuicConnectionPeer;
733 friend class test::PacketSavingConnection;
734
735 typedef std::list<SerializedPacket> QueuedPacketList;
736
737 // Notifies the visitor of the close and marks the connection as disconnected.
738 // Does not send a connection close frame to the peer.
739 void TearDownLocalConnectionState(QuicErrorCode error,
740 const std::string& details,
741 ConnectionCloseSource source);
742
743 // Writes the given packet to socket, encrypted with packet's
744 // encryption_level. Returns true on successful write, and false if the writer
745 // was blocked and the write needs to be tried again. Notifies the
746 // SentPacketManager when the write is successful and sets
747 // retransmittable frames to nullptr.
748 // Saves the connection close packet for later transmission, even if the
749 // writer is write blocked.
750 bool WritePacket(SerializedPacket* packet);
751
752 // Make sure an ack we got from our peer is sane.
753 // Returns nullptr for valid acks or an error std::string if it was invalid.
754 const char* ValidateAckFrame(const QuicAckFrame& incoming_ack);
755
756 // Make sure a stop waiting we got from our peer is sane.
757 // Returns nullptr if the frame is valid or an error std::string if it was
758 // invalid.
759 const char* ValidateStopWaitingFrame(
760 const QuicStopWaitingFrame& stop_waiting);
761
762 // Sends a version negotiation packet to the peer.
763 void SendVersionNegotiationPacket();
764
765 // Clears any accumulated frames from the last received packet.
766 void ClearLastFrames();
767
768 // Deletes and clears any queued packets.
769 void ClearQueuedPackets();
770
771 // Closes the connection if the sent or received packet manager are tracking
772 // too many outstanding packets.
773 void MaybeCloseIfTooManyOutstandingPackets();
774
775 // Writes as many queued packets as possible. The connection must not be
776 // blocked when this is called.
777 void WriteQueuedPackets();
778
779 // Writes as many pending retransmissions as possible.
780 void WritePendingRetransmissions();
781
782 // Returns true if the packet should be discarded and not sent.
783 bool ShouldDiscardPacket(const SerializedPacket& packet);
784
785 // Queues |packet| in the hopes that it can be decrypted in the
786 // future, when a new key is installed.
787 void QueueUndecryptablePacket(const QuicEncryptedPacket& packet);
788
789 // Attempts to process any queued undecryptable packets.
790 void MaybeProcessUndecryptablePackets();
791
792 void ProcessAckFrame(const QuicAckFrame& incoming_ack);
793
794 void ProcessStopWaitingFrame(const QuicStopWaitingFrame& stop_waiting);
795
796 // Sends any packets which are a response to the last packet, including both
797 // acks and pending writes if an ack opened the congestion window.
798 void MaybeSendInResponseToPacket();
799
800 // Queue an ack or set the ack alarm if needed. |was_missing| is true if
801 // the most recently received packet was formerly missing.
802 void MaybeQueueAck(bool was_missing);
803
804 // Gets the least unacked packet number of |path_id|, which is the next packet
805 // number to be sent if there are no outstanding packets.
806 QuicPacketNumber GetLeastUnacked(QuicPathId path_id) const;
807
808 // Sets the timeout alarm to the appropriate value, if any.
809 void SetTimeoutAlarm();
810
811 // Sets the ping alarm to the appropriate value, if any.
812 void SetPingAlarm();
813
814 // Sets the retransmission alarm based on SentPacketManager.
815 void SetRetransmissionAlarm();
816
817 // Sets the MTU discovery alarm if necessary.
818 void MaybeSetMtuAlarm();
819
820 // On arrival of a new packet, checks to see if the socket addresses have
821 // changed since the last packet we saw on this connection.
822 void CheckForAddressMigration(const IPEndPoint& self_address,
823 const IPEndPoint& peer_address);
824
825 HasRetransmittableData IsRetransmittable(const SerializedPacket& packet);
826 bool IsTerminationPacket(const SerializedPacket& packet);
827
828 // Set the size of the packet we are targeting while doing path MTU discovery.
829 void SetMtuDiscoveryTarget(QuicByteCount target);
830
831 // Validates the potential maximum packet size, and reduces it if it exceeds
832 // the largest supported by the protocol or the packet writer.
833 QuicByteCount LimitMaxPacketSize(QuicByteCount suggested_max_packet_size);
834
835 // Called when |path_id| is considered as closed because either a PATH_CLOSE
836 // frame is sent or received. Stops receiving packets on closed path. Drops
837 // receive side of a closed path, and packets with retransmittable frames on a
838 // closed path are marked as retransmissions which will be transmitted on
839 // other paths.
840 // TODO(fayang): complete OnPathClosed once QuicMultipathSentPacketManager and
841 // QuicMultipathReceivedPacketManager are landed in QuicConnection.
842 void OnPathClosed(QuicPathId path_id);
843
844 // Do any work which logically would be done in OnPacket but can not be
845 // safely done until the packet is validated. Returns true if packet can be
846 // handled, false otherwise.
847 bool ProcessValidatedPacket(const QuicPacketHeader& header);
848
849 // Consider receiving crypto frame on non crypto stream as memory corruption.
850 bool MaybeConsiderAsMemoryCorruption(const QuicStreamFrame& frame);
851
852 const QuicTime::Delta DelayedAckTime();
853
854 QuicFramer framer_;
855 QuicConnectionHelperInterface* helper_; // Not owned.
856 QuicAlarmFactory* alarm_factory_; // Not owned.
857 PerPacketOptions* per_packet_options_; // Not owned.
858 QuicPacketWriter* writer_; // Owned or not depending on |owns_writer_|.
859 bool owns_writer_;
860 // Encryption level for new packets. Should only be changed via
861 // SetDefaultEncryptionLevel().
862 EncryptionLevel encryption_level_;
863 bool has_forward_secure_encrypter_;
864 // The packet number of the first packet which will be encrypted with the
865 // foward-secure encrypter, even if the peer has not started sending
866 // forward-secure packets.
867 QuicPacketNumber first_required_forward_secure_packet_;
868 const QuicClock* clock_;
869 QuicRandom* random_generator_;
870
871 const QuicConnectionId connection_id_;
872 // Address on the last successfully processed packet received from the
873 // client.
874 IPEndPoint self_address_;
875 IPEndPoint peer_address_;
876
877 // Records change type when the peer initiates migration to a new peer
878 // address. Reset to NO_CHANGE after peer migration is validated.
879 PeerAddressChangeType active_peer_migration_type_;
880
881 // Records highest sent packet number when peer migration is started.
882 QuicPacketNumber highest_packet_sent_before_peer_migration_;
883
884 // True if the last packet has gotten far enough in the framer to be
885 // decrypted.
886 bool last_packet_decrypted_;
887 QuicByteCount last_size_; // Size of the last received packet.
888 // TODO(rch): remove this when b/27221014 is fixed.
889 const char* current_packet_data_; // UDP payload of packet currently being
890 // parsed or nullptr.
891 EncryptionLevel last_decrypted_packet_level_;
892 QuicPacketHeader last_header_;
893 QuicStopWaitingFrame last_stop_waiting_frame_;
894 bool should_last_packet_instigate_acks_;
895
896 // Track some peer state so we can do less bookkeeping
897 // Largest sequence sent by the peer which had an ack frame (latest ack info).
898 QuicPacketNumber largest_seen_packet_with_ack_;
899
900 // Largest packet number sent by the peer which had a stop waiting frame.
901 QuicPacketNumber largest_seen_packet_with_stop_waiting_;
902
903 // Collection of packets which were received before encryption was
904 // established, but which could not be decrypted. We buffer these on
905 // the assumption that they could not be processed because they were
906 // sent with the INITIAL encryption and the CHLO message was lost.
907 std::deque<QuicEncryptedPacket*> undecryptable_packets_;
908
909 // Maximum number of undecryptable packets the connection will store.
910 size_t max_undecryptable_packets_;
911
912 // When the version negotiation packet could not be sent because the socket
913 // was not writable, this is set to true.
914 bool pending_version_negotiation_packet_;
915
916 // When packets could not be sent because the socket was not writable,
917 // they are added to this std::list. All corresponding frames are in
918 // unacked_packets_ if they are to be retransmitted. Packets encrypted_buffer
919 // fields are owned by the QueuedPacketList, in order to ensure they outlast
920 // the original scope of the SerializedPacket.
921 QueuedPacketList queued_packets_;
922
923 // If true, then crypto packets will be saved as termination packets.
924 bool save_crypto_packets_as_termination_packets_;
925
926 // Contains the connection close packets if the connection has been closed.
927 std::unique_ptr<std::vector<std::unique_ptr<QuicEncryptedPacket>>>
928 termination_packets_;
929
930 // Determines whether or not a connection close packet is sent to the peer
931 // after idle timeout due to lack of network activity.
932 // This is particularly important on mobile, where waking up the radio is
933 // undesirable.
934 ConnectionCloseBehavior idle_timeout_connection_close_behavior_;
935
936 // When true, close the QUIC connection after 5 RTOs. Due to the min rto of
937 // 200ms, this is over 5 seconds.
938 bool close_connection_after_five_rtos_;
939
940 QuicReceivedPacketManager received_packet_manager_;
941 QuicSentEntropyManager sent_entropy_manager_;
942
943 // Indicates whether an ack should be sent the next time we try to write.
944 bool ack_queued_;
945 // How many retransmittable packets have arrived without sending an ack.
946 QuicPacketCount num_retransmittable_packets_received_since_last_ack_sent_;
947 // Whether there were missing packets in the last sent ack.
948 bool last_ack_had_missing_packets_;
949 // How many consecutive packets have arrived without sending an ack.
950 QuicPacketCount num_packets_received_since_last_ack_sent_;
951 // Indicates how many consecutive times an ack has arrived which indicates
952 // the peer needs to stop waiting for some packets.
953 int stop_waiting_count_;
954 // Indicates the current ack mode, defaults to acking every 2 packets.
955 AckMode ack_mode_;
956 // The max delay in fraction of min_rtt to use when sending decimated acks.
957 float ack_decimation_delay_;
958
959 // Indicates the retransmit alarm is going to be set by the
960 // ScopedRetransmitAlarmDelayer
961 bool delay_setting_retransmission_alarm_;
962 // Indicates the retransmission alarm needs to be set.
963 bool pending_retransmission_alarm_;
964
965 // If true, defer sending data in response to received packets to the
966 // SendAlarm.
967 bool defer_send_in_response_to_packets_;
968
969 // Arena to store class implementations within the QuicConnection.
970 QuicConnectionArena arena_;
971
972 // An alarm that fires when an ACK should be sent to the peer.
973 QuicArenaScopedPtr<QuicAlarm> ack_alarm_;
974 // An alarm that fires when a packet needs to be retransmitted.
975 QuicArenaScopedPtr<QuicAlarm> retransmission_alarm_;
976 // An alarm that is scheduled when the SentPacketManager requires a delay
977 // before sending packets and fires when the packet may be sent.
978 QuicArenaScopedPtr<QuicAlarm> send_alarm_;
979 // An alarm that is scheduled when the connection can still write and there
980 // may be more data to send.
981 // TODO(ianswett): Remove resume_writes_alarm when deprecating
982 // FLAGS_quic_only_one_sending_alarm
983 QuicArenaScopedPtr<QuicAlarm> resume_writes_alarm_;
984 // An alarm that fires when the connection may have timed out.
985 QuicArenaScopedPtr<QuicAlarm> timeout_alarm_;
986 // An alarm that fires when a ping should be sent.
987 QuicArenaScopedPtr<QuicAlarm> ping_alarm_;
988 // An alarm that fires when an MTU probe should be sent.
989 QuicArenaScopedPtr<QuicAlarm> mtu_discovery_alarm_;
990
991 // Neither visitor is owned by this class.
992 QuicConnectionVisitorInterface* visitor_;
993 QuicConnectionDebugVisitor* debug_visitor_;
994
995 QuicPacketGenerator packet_generator_;
996
997 // Network idle time before this connection is closed.
998 QuicTime::Delta idle_network_timeout_;
999 // The connection will wait this long for the handshake to complete.
1000 QuicTime::Delta handshake_timeout_;
1001
1002 // Statistics for this session.
1003 QuicConnectionStats stats_;
1004
1005 // The time that we got a packet for this connection.
1006 // This is used for timeouts, and does not indicate the packet was processed.
1007 QuicTime time_of_last_received_packet_;
1008
1009 // The last time this connection began sending a new (non-retransmitted)
1010 // packet.
1011 QuicTime time_of_last_sent_new_packet_;
1012
1013 // The the send time of the first retransmittable packet sent after
1014 // |time_of_last_received_packet_|.
1015 QuicTime last_send_for_timeout_;
1016
1017 // packet number of the last sent packet. Packets are guaranteed to be sent
1018 // in packet number order.
1019 QuicPacketNumber packet_number_of_last_sent_packet_;
1020
1021 // Sent packet manager which tracks the status of packets sent by this
1022 // connection and contains the send and receive algorithms to determine when
1023 // to send packets.
1024 std::unique_ptr<QuicSentPacketManagerInterface> sent_packet_manager_;
1025
1026 // The state of connection in version negotiation finite state machine.
1027 QuicVersionNegotiationState version_negotiation_state_;
1028
1029 // Tracks if the connection was created by the server or the client.
1030 Perspective perspective_;
1031
1032 // True by default. False if we've received or sent an explicit connection
1033 // close.
1034 bool connected_;
1035
1036 // Destination address of the last received packet.
1037 IPEndPoint last_packet_destination_address_;
1038
1039 // Source address of the last received packet.
1040 IPEndPoint last_packet_source_address_;
1041
1042 // Set to false if the connection should not send truncated connection IDs to
1043 // the peer, even if the peer supports it.
1044 bool can_truncate_connection_ids_;
1045
1046 // If non-empty this contains the set of versions received in a
1047 // version negotiation packet.
1048 QuicVersionVector server_supported_versions_;
1049
1050 // The size of the packet we are targeting while doing path MTU discovery.
1051 QuicByteCount mtu_discovery_target_;
1052
1053 // The number of MTU probes already sent.
1054 size_t mtu_probe_count_;
1055
1056 // The number of packets between MTU probes.
1057 QuicPacketCount packets_between_mtu_probes_;
1058
1059 // The packet number of the packet after which the next MTU probe will be
1060 // sent.
1061 QuicPacketNumber next_mtu_probe_at_;
1062
1063 // The size of the largest packet received from peer.
1064 QuicByteCount largest_received_packet_size_;
1065
1066 // Whether a GoAway has been sent.
1067 bool goaway_sent_;
1068
1069 // Whether a GoAway has been received.
1070 bool goaway_received_;
1071
1072 // If true, multipath is enabled for this connection.
1073 bool multipath_enabled_;
1074
1075 DISALLOW_COPY_AND_ASSIGN(QuicConnection);
1076 };
1077
1078 } // namespace net
1079
1080 #endif // NET_QUIC_QUIC_CONNECTION_H_
OLDNEW
« no previous file with comments | « net/quic/quic_config_test.cc ('k') | net/quic/quic_connection.cc » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698