quic_protocol.h revision 1320f92c476a1ad9d19dba2a48c72b75566198e9
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#ifndef NET_QUIC_QUIC_PROTOCOL_H_
6#define NET_QUIC_QUIC_PROTOCOL_H_
7
8#include <stddef.h>
9#include <limits>
10#include <list>
11#include <map>
12#include <ostream>
13#include <set>
14#include <string>
15#include <utility>
16#include <vector>
17
18#include "base/basictypes.h"
19#include "base/containers/hash_tables.h"
20#include "base/logging.h"
21#include "base/strings/string_piece.h"
22#include "net/base/int128.h"
23#include "net/base/ip_endpoint.h"
24#include "net/base/net_export.h"
25#include "net/quic/iovector.h"
26#include "net/quic/quic_bandwidth.h"
27#include "net/quic/quic_time.h"
28
29namespace net {
30
31class QuicAckNotifier;
32class QuicPacket;
33struct QuicPacketHeader;
34
35typedef uint64 QuicConnectionId;
36typedef uint32 QuicStreamId;
37typedef uint64 QuicStreamOffset;
38typedef uint64 QuicPacketSequenceNumber;
39typedef QuicPacketSequenceNumber QuicFecGroupNumber;
40typedef uint64 QuicPublicResetNonceProof;
41typedef uint8 QuicPacketEntropyHash;
42typedef uint32 QuicHeaderId;
43// QuicTag is the type of a tag in the wire protocol.
44typedef uint32 QuicTag;
45typedef std::vector<QuicTag> QuicTagVector;
46typedef std::map<QuicTag, std::string> QuicTagValueMap;
47// TODO(rtenneti): Didn't use SpdyPriority because SpdyPriority is uint8 and
48// QuicPriority is uint32. Use SpdyPriority when we change the QUIC_VERSION.
49typedef uint32 QuicPriority;
50
51// TODO(rch): Consider Quic specific names for these constants.
52// Default and initial maximum size in bytes of a QUIC packet.
53const QuicByteCount kDefaultMaxPacketSize = 1350;
54// The maximum packet size of any QUIC packet, based on ethernet's max size,
55// minus the IP and UDP headers. IPv6 has a 40 byte header, UPD adds an
56// additional 8 bytes.  This is a total overhead of 48 bytes.  Ethernet's
57// max packet size is 1500 bytes,  1500 - 48 = 1452.
58const QuicByteCount kMaxPacketSize = 1452;
59// Default maximum packet size used in Linux TCP implementations.
60const QuicByteCount kDefaultTCPMSS = 1460;
61
62// Maximum size of the initial congestion window in packets.
63const size_t kDefaultInitialWindow = 10;
64const uint32 kMaxInitialWindow = 100;
65
66// Default size of initial flow control window, for both stream and session.
67const uint32 kDefaultFlowControlSendWindow = 16 * 1024;  // 16 KB
68
69// Maximum size of the congestion window, in packets, for TCP congestion control
70// algorithms.
71const size_t kMaxTcpCongestionWindow = 200;
72
73// Size of the socket receive buffer in bytes.
74const QuicByteCount kDefaultSocketReceiveBuffer = 256 * 1024;
75
76// Don't allow a client to suggest an RTT longer than 15 seconds.
77const uint32 kMaxInitialRoundTripTimeUs = 15 * kNumMicrosPerSecond;
78
79// Maximum number of open streams per connection.
80const size_t kDefaultMaxStreamsPerConnection = 100;
81
82// Number of bytes reserved for public flags in the packet header.
83const size_t kPublicFlagsSize = 1;
84// Number of bytes reserved for version number in the packet header.
85const size_t kQuicVersionSize = 4;
86// Number of bytes reserved for private flags in the packet header.
87const size_t kPrivateFlagsSize = 1;
88// Number of bytes reserved for FEC group in the packet header.
89const size_t kFecGroupSize = 1;
90
91// Signifies that the QuicPacket will contain version of the protocol.
92const bool kIncludeVersion = true;
93
94// Index of the first byte in a QUIC packet which is used in hash calculation.
95const size_t kStartOfHashData = 0;
96
97// Limit on the delta between stream IDs.
98const QuicStreamId kMaxStreamIdDelta = 200;
99// Limit on the delta between header IDs.
100const QuicHeaderId kMaxHeaderIdDelta = 200;
101
102// Reserved ID for the crypto stream.
103const QuicStreamId kCryptoStreamId = 1;
104
105// Reserved ID for the headers stream.
106const QuicStreamId kHeadersStreamId = 3;
107
108// Maximum delayed ack time, in ms.
109const int kMaxDelayedAckTimeMs = 25;
110
111// The default idle timeout before the crypto handshake succeeds.
112const int64 kDefaultInitialTimeoutSecs = 120;  // 2 mins.
113// The maximum idle timeout that can be negotiated.
114const int64 kMaximumIdleTimeoutSecs = 60 * 10;  // 10 minutes.
115// The default timeout for a connection until the crypto handshake succeeds.
116const int64 kDefaultMaxTimeForCryptoHandshakeSecs = 10;  // 10 secs.
117
118// Default ping timeout.
119const int64 kPingTimeoutSecs = 15;  // 15 secs.
120
121// Minimum number of RTTs between Server Config Updates (SCUP) sent to client.
122const int kMinIntervalBetweenServerConfigUpdatesRTTs = 10;
123
124// Minimum time between Server Config Updates (SCUP) sent to client.
125const int kMinIntervalBetweenServerConfigUpdatesMs = 1000;
126
127// Multiplier that allows server to accept slightly more streams than
128// negotiated in handshake.
129const float kMaxStreamsMultiplier = 1.1f;
130
131// We define an unsigned 16-bit floating point value, inspired by IEEE floats
132// (http://en.wikipedia.org/wiki/Half_precision_floating-point_format),
133// with 5-bit exponent (bias 1), 11-bit mantissa (effective 12 with hidden
134// bit) and denormals, but without signs, transfinites or fractions. Wire format
135// 16 bits (little-endian byte order) are split into exponent (high 5) and
136// mantissa (low 11) and decoded as:
137//   uint64 value;
138//   if (exponent == 0) value = mantissa;
139//   else value = (mantissa | 1 << 11) << (exponent - 1)
140const int kUFloat16ExponentBits = 5;
141const int kUFloat16MaxExponent = (1 << kUFloat16ExponentBits) - 2;  // 30
142const int kUFloat16MantissaBits = 16 - kUFloat16ExponentBits;  // 11
143const int kUFloat16MantissaEffectiveBits = kUFloat16MantissaBits + 1;  // 12
144const uint64 kUFloat16MaxValue =  // 0x3FFC0000000
145    ((GG_UINT64_C(1) << kUFloat16MantissaEffectiveBits) - 1) <<
146    kUFloat16MaxExponent;
147
148enum TransmissionType {
149  NOT_RETRANSMISSION,
150  FIRST_TRANSMISSION_TYPE = NOT_RETRANSMISSION,
151  HANDSHAKE_RETRANSMISSION,  // Retransmits due to handshake timeouts.
152  ALL_UNACKED_RETRANSMISSION,  // Retransmits all unacked packets.
153  ALL_INITIAL_RETRANSMISSION,  // Retransmits all initially encrypted packets.
154  LOSS_RETRANSMISSION,  // Retransmits due to loss detection.
155  RTO_RETRANSMISSION,  // Retransmits due to retransmit time out.
156  TLP_RETRANSMISSION,  // Tail loss probes.
157  LAST_TRANSMISSION_TYPE = TLP_RETRANSMISSION,
158};
159
160enum HasRetransmittableData {
161  NO_RETRANSMITTABLE_DATA,
162  HAS_RETRANSMITTABLE_DATA,
163};
164
165enum IsHandshake {
166  NOT_HANDSHAKE,
167  IS_HANDSHAKE
168};
169
170// Indicates FEC protection level for data being written.
171enum FecProtection {
172  MUST_FEC_PROTECT,  // Callee must FEC protect this data.
173  MAY_FEC_PROTECT    // Callee does not have to but may FEC protect this data.
174};
175
176// Indicates FEC policy.
177enum FecPolicy {
178  FEC_PROTECT_ALWAYS,   // All data in the stream should be FEC protected.
179  FEC_PROTECT_OPTIONAL  // Data in the stream does not need FEC protection.
180};
181
182enum QuicFrameType {
183  // Regular frame types. The values set here cannot change without the
184  // introduction of a new QUIC version.
185  PADDING_FRAME = 0,
186  RST_STREAM_FRAME = 1,
187  CONNECTION_CLOSE_FRAME = 2,
188  GOAWAY_FRAME = 3,
189  WINDOW_UPDATE_FRAME = 4,
190  BLOCKED_FRAME = 5,
191  STOP_WAITING_FRAME = 6,
192  PING_FRAME = 7,
193
194  // STREAM, ACK, and CONGESTION_FEEDBACK frames are special frames. They are
195  // encoded differently on the wire and their values do not need to be stable.
196  STREAM_FRAME,
197  ACK_FRAME,
198  CONGESTION_FEEDBACK_FRAME,
199  NUM_FRAME_TYPES
200};
201
202enum QuicConnectionIdLength {
203  PACKET_0BYTE_CONNECTION_ID = 0,
204  PACKET_1BYTE_CONNECTION_ID = 1,
205  PACKET_4BYTE_CONNECTION_ID = 4,
206  PACKET_8BYTE_CONNECTION_ID = 8
207};
208
209enum InFecGroup {
210  NOT_IN_FEC_GROUP,
211  IN_FEC_GROUP,
212};
213
214enum QuicSequenceNumberLength {
215  PACKET_1BYTE_SEQUENCE_NUMBER = 1,
216  PACKET_2BYTE_SEQUENCE_NUMBER = 2,
217  PACKET_4BYTE_SEQUENCE_NUMBER = 4,
218  PACKET_6BYTE_SEQUENCE_NUMBER = 6
219};
220
221// Used to indicate a QuicSequenceNumberLength using two flag bits.
222enum QuicSequenceNumberLengthFlags {
223  PACKET_FLAGS_1BYTE_SEQUENCE = 0,  // 00
224  PACKET_FLAGS_2BYTE_SEQUENCE = 1,  // 01
225  PACKET_FLAGS_4BYTE_SEQUENCE = 1 << 1,  // 10
226  PACKET_FLAGS_6BYTE_SEQUENCE = 1 << 1 | 1,  // 11
227};
228
229// The public flags are specified in one byte.
230enum QuicPacketPublicFlags {
231  PACKET_PUBLIC_FLAGS_NONE = 0,
232
233  // Bit 0: Does the packet header contains version info?
234  PACKET_PUBLIC_FLAGS_VERSION = 1 << 0,
235
236  // Bit 1: Is this packet a public reset packet?
237  PACKET_PUBLIC_FLAGS_RST = 1 << 1,
238
239  // Bits 2 and 3 specify the length of the ConnectionId as follows:
240  // ----00--: 0 bytes
241  // ----01--: 1 byte
242  // ----10--: 4 bytes
243  // ----11--: 8 bytes
244  PACKET_PUBLIC_FLAGS_0BYTE_CONNECTION_ID = 0,
245  PACKET_PUBLIC_FLAGS_1BYTE_CONNECTION_ID = 1 << 2,
246  PACKET_PUBLIC_FLAGS_4BYTE_CONNECTION_ID = 1 << 3,
247  PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID = 1 << 3 | 1 << 2,
248
249  // Bits 4 and 5 describe the packet sequence number length as follows:
250  // --00----: 1 byte
251  // --01----: 2 bytes
252  // --10----: 4 bytes
253  // --11----: 6 bytes
254  PACKET_PUBLIC_FLAGS_1BYTE_SEQUENCE = PACKET_FLAGS_1BYTE_SEQUENCE << 4,
255  PACKET_PUBLIC_FLAGS_2BYTE_SEQUENCE = PACKET_FLAGS_2BYTE_SEQUENCE << 4,
256  PACKET_PUBLIC_FLAGS_4BYTE_SEQUENCE = PACKET_FLAGS_4BYTE_SEQUENCE << 4,
257  PACKET_PUBLIC_FLAGS_6BYTE_SEQUENCE = PACKET_FLAGS_6BYTE_SEQUENCE << 4,
258
259  // All bits set (bits 6 and 7 are not currently used): 00111111
260  PACKET_PUBLIC_FLAGS_MAX = (1 << 6) - 1
261};
262
263// The private flags are specified in one byte.
264enum QuicPacketPrivateFlags {
265  PACKET_PRIVATE_FLAGS_NONE = 0,
266
267  // Bit 0: Does this packet contain an entropy bit?
268  PACKET_PRIVATE_FLAGS_ENTROPY = 1 << 0,
269
270  // Bit 1: Payload is part of an FEC group?
271  PACKET_PRIVATE_FLAGS_FEC_GROUP = 1 << 1,
272
273  // Bit 2: Payload is FEC as opposed to frames?
274  PACKET_PRIVATE_FLAGS_FEC = 1 << 2,
275
276  // All bits set (bits 3-7 are not currently used): 00000111
277  PACKET_PRIVATE_FLAGS_MAX = (1 << 3) - 1
278};
279
280// The available versions of QUIC. Guaranteed that the integer value of the enum
281// will match the version number.
282// When adding a new version to this enum you should add it to
283// kSupportedQuicVersions (if appropriate), and also add a new case to the
284// helper methods QuicVersionToQuicTag, QuicTagToQuicVersion, and
285// QuicVersionToString.
286enum QuicVersion {
287  // Special case to indicate unknown/unsupported QUIC version.
288  QUIC_VERSION_UNSUPPORTED = 0,
289
290  QUIC_VERSION_16 = 16,  // STOP_WAITING frame.
291  QUIC_VERSION_18 = 18,  // PING frame.
292  QUIC_VERSION_19 = 19,  // Connection level flow control.
293  QUIC_VERSION_21 = 21,  // Headers/crypto streams are flow controlled.
294  QUIC_VERSION_22 = 22,  // Send Server Config Update messages on crypto stream.
295  QUIC_VERSION_23 = 23,  // Timestamp in the ack frame.
296};
297
298// This vector contains QUIC versions which we currently support.
299// This should be ordered such that the highest supported version is the first
300// element, with subsequent elements in descending order (versions can be
301// skipped as necessary).
302//
303// IMPORTANT: if you are adding to this list, follow the instructions at
304// http://sites/quic/adding-and-removing-versions
305static const QuicVersion kSupportedQuicVersions[] = {QUIC_VERSION_23,
306                                                     QUIC_VERSION_22,
307                                                     QUIC_VERSION_21,
308                                                     QUIC_VERSION_19,
309                                                     QUIC_VERSION_18,
310                                                     QUIC_VERSION_16};
311
312typedef std::vector<QuicVersion> QuicVersionVector;
313
314// Returns a vector of QUIC versions in kSupportedQuicVersions.
315NET_EXPORT_PRIVATE QuicVersionVector QuicSupportedVersions();
316
317// QuicTag is written to and read from the wire, but we prefer to use
318// the more readable QuicVersion at other levels.
319// Helper function which translates from a QuicVersion to a QuicTag. Returns 0
320// if QuicVersion is unsupported.
321NET_EXPORT_PRIVATE QuicTag QuicVersionToQuicTag(const QuicVersion version);
322
323// Returns appropriate QuicVersion from a QuicTag.
324// Returns QUIC_VERSION_UNSUPPORTED if version_tag cannot be understood.
325NET_EXPORT_PRIVATE QuicVersion QuicTagToQuicVersion(const QuicTag version_tag);
326
327// Helper function which translates from a QuicVersion to a string.
328// Returns strings corresponding to enum names (e.g. QUIC_VERSION_6).
329NET_EXPORT_PRIVATE std::string QuicVersionToString(const QuicVersion version);
330
331// Returns comma separated list of string representations of QuicVersion enum
332// values in the supplied |versions| vector.
333NET_EXPORT_PRIVATE std::string QuicVersionVectorToString(
334    const QuicVersionVector& versions);
335
336// Version and Crypto tags are written to the wire with a big-endian
337// representation of the name of the tag.  For example
338// the client hello tag (CHLO) will be written as the
339// following 4 bytes: 'C' 'H' 'L' 'O'.  Since it is
340// stored in memory as a little endian uint32, we need
341// to reverse the order of the bytes.
342
343// MakeQuicTag returns a value given the four bytes. For example:
344//   MakeQuicTag('C', 'H', 'L', 'O');
345NET_EXPORT_PRIVATE QuicTag MakeQuicTag(char a, char b, char c, char d);
346
347// Returns true if the tag vector contains the specified tag.
348NET_EXPORT_PRIVATE bool ContainsQuicTag(const QuicTagVector& tag_vector,
349                                        QuicTag tag);
350
351// Size in bytes of the data or fec packet header.
352NET_EXPORT_PRIVATE size_t GetPacketHeaderSize(const QuicPacketHeader& header);
353
354NET_EXPORT_PRIVATE size_t GetPacketHeaderSize(
355    QuicConnectionIdLength connection_id_length,
356    bool include_version,
357    QuicSequenceNumberLength sequence_number_length,
358    InFecGroup is_in_fec_group);
359
360// Index of the first byte in a QUIC packet of FEC protected data.
361NET_EXPORT_PRIVATE size_t GetStartOfFecProtectedData(
362    QuicConnectionIdLength connection_id_length,
363    bool include_version,
364    QuicSequenceNumberLength sequence_number_length);
365// Index of the first byte in a QUIC packet of encrypted data.
366NET_EXPORT_PRIVATE size_t GetStartOfEncryptedData(
367    QuicConnectionIdLength connection_id_length,
368    bool include_version,
369    QuicSequenceNumberLength sequence_number_length);
370
371enum QuicRstStreamErrorCode {
372  QUIC_STREAM_NO_ERROR = 0,
373
374  // There was some error which halted stream processing.
375  QUIC_ERROR_PROCESSING_STREAM,
376  // We got two fin or reset offsets which did not match.
377  QUIC_MULTIPLE_TERMINATION_OFFSETS,
378  // We got bad payload and can not respond to it at the protocol level.
379  QUIC_BAD_APPLICATION_PAYLOAD,
380  // Stream closed due to connection error. No reset frame is sent when this
381  // happens.
382  QUIC_STREAM_CONNECTION_ERROR,
383  // GoAway frame sent. No more stream can be created.
384  QUIC_STREAM_PEER_GOING_AWAY,
385  // The stream has been cancelled.
386  QUIC_STREAM_CANCELLED,
387  // Sending a RST to allow for proper flow control accounting.
388  QUIC_RST_FLOW_CONTROL_ACCOUNTING,
389
390  // No error. Used as bound while iterating.
391  QUIC_STREAM_LAST_ERROR,
392};
393
394// Because receiving an unknown QuicRstStreamErrorCode results in connection
395// teardown, we use this to make sure any errors predating a given version are
396// downgraded to the most appropriate existing error.
397NET_EXPORT_PRIVATE QuicRstStreamErrorCode AdjustErrorForVersion(
398    QuicRstStreamErrorCode error_code,
399    QuicVersion version);
400
401// These values must remain stable as they are uploaded to UMA histograms.
402// To add a new error code, use the current value of QUIC_LAST_ERROR and
403// increment QUIC_LAST_ERROR.
404enum QuicErrorCode {
405  QUIC_NO_ERROR = 0,
406
407  // Connection has reached an invalid state.
408  QUIC_INTERNAL_ERROR = 1,
409  // There were data frames after the a fin or reset.
410  QUIC_STREAM_DATA_AFTER_TERMINATION = 2,
411  // Control frame is malformed.
412  QUIC_INVALID_PACKET_HEADER = 3,
413  // Frame data is malformed.
414  QUIC_INVALID_FRAME_DATA = 4,
415  // The packet contained no payload.
416  QUIC_MISSING_PAYLOAD = 48,
417  // FEC data is malformed.
418  QUIC_INVALID_FEC_DATA = 5,
419  // STREAM frame data is malformed.
420  QUIC_INVALID_STREAM_DATA = 46,
421  // STREAM frame data is not encrypted.
422  QUIC_UNENCRYPTED_STREAM_DATA = 61,
423  // RST_STREAM frame data is malformed.
424  QUIC_INVALID_RST_STREAM_DATA = 6,
425  // CONNECTION_CLOSE frame data is malformed.
426  QUIC_INVALID_CONNECTION_CLOSE_DATA = 7,
427  // GOAWAY frame data is malformed.
428  QUIC_INVALID_GOAWAY_DATA = 8,
429  // WINDOW_UPDATE frame data is malformed.
430  QUIC_INVALID_WINDOW_UPDATE_DATA = 57,
431  // BLOCKED frame data is malformed.
432  QUIC_INVALID_BLOCKED_DATA = 58,
433  // STOP_WAITING frame data is malformed.
434  QUIC_INVALID_STOP_WAITING_DATA = 60,
435  // ACK frame data is malformed.
436  QUIC_INVALID_ACK_DATA = 9,
437  // CONGESTION_FEEDBACK frame data is malformed.
438  QUIC_INVALID_CONGESTION_FEEDBACK_DATA = 47,
439  // Version negotiation packet is malformed.
440  QUIC_INVALID_VERSION_NEGOTIATION_PACKET = 10,
441  // Public RST packet is malformed.
442  QUIC_INVALID_PUBLIC_RST_PACKET = 11,
443  // There was an error decrypting.
444  QUIC_DECRYPTION_FAILURE = 12,
445  // There was an error encrypting.
446  QUIC_ENCRYPTION_FAILURE = 13,
447  // The packet exceeded kMaxPacketSize.
448  QUIC_PACKET_TOO_LARGE = 14,
449  // Data was sent for a stream which did not exist.
450  QUIC_PACKET_FOR_NONEXISTENT_STREAM = 15,
451  // The peer is going away.  May be a client or server.
452  QUIC_PEER_GOING_AWAY = 16,
453  // A stream ID was invalid.
454  QUIC_INVALID_STREAM_ID = 17,
455  // A priority was invalid.
456  QUIC_INVALID_PRIORITY = 49,
457  // Too many streams already open.
458  QUIC_TOO_MANY_OPEN_STREAMS = 18,
459  // The peer must send a FIN/RST for each stream, and has not been doing so.
460  QUIC_TOO_MANY_UNFINISHED_STREAMS = 66,
461  // Received public reset for this connection.
462  QUIC_PUBLIC_RESET = 19,
463  // Invalid protocol version.
464  QUIC_INVALID_VERSION = 20,
465
466  // deprecated: QUIC_STREAM_RST_BEFORE_HEADERS_DECOMPRESSED = 21
467
468  // The Header ID for a stream was too far from the previous.
469  QUIC_INVALID_HEADER_ID = 22,
470  // Negotiable parameter received during handshake had invalid value.
471  QUIC_INVALID_NEGOTIATED_VALUE = 23,
472  // There was an error decompressing data.
473  QUIC_DECOMPRESSION_FAILURE = 24,
474  // We hit our prenegotiated (or default) timeout
475  QUIC_CONNECTION_TIMED_OUT = 25,
476  // We hit our overall connection timeout
477  QUIC_CONNECTION_OVERALL_TIMED_OUT = 67,
478  // There was an error encountered migrating addresses
479  QUIC_ERROR_MIGRATING_ADDRESS = 26,
480  // There was an error while writing to the socket.
481  QUIC_PACKET_WRITE_ERROR = 27,
482  // There was an error while reading from the socket.
483  QUIC_PACKET_READ_ERROR = 51,
484  // We received a STREAM_FRAME with no data and no fin flag set.
485  QUIC_INVALID_STREAM_FRAME = 50,
486  // We received invalid data on the headers stream.
487  QUIC_INVALID_HEADERS_STREAM_DATA = 56,
488  // The peer received too much data, violating flow control.
489  QUIC_FLOW_CONTROL_RECEIVED_TOO_MUCH_DATA = 59,
490  // The peer sent too much data, violating flow control.
491  QUIC_FLOW_CONTROL_SENT_TOO_MUCH_DATA = 63,
492  // The peer received an invalid flow control window.
493  QUIC_FLOW_CONTROL_INVALID_WINDOW = 64,
494  // The connection has been IP pooled into an existing connection.
495  QUIC_CONNECTION_IP_POOLED = 62,
496
497  // Crypto errors.
498
499  // Hanshake failed.
500  QUIC_HANDSHAKE_FAILED = 28,
501  // Handshake message contained out of order tags.
502  QUIC_CRYPTO_TAGS_OUT_OF_ORDER = 29,
503  // Handshake message contained too many entries.
504  QUIC_CRYPTO_TOO_MANY_ENTRIES = 30,
505  // Handshake message contained an invalid value length.
506  QUIC_CRYPTO_INVALID_VALUE_LENGTH = 31,
507  // A crypto message was received after the handshake was complete.
508  QUIC_CRYPTO_MESSAGE_AFTER_HANDSHAKE_COMPLETE = 32,
509  // A crypto message was received with an illegal message tag.
510  QUIC_INVALID_CRYPTO_MESSAGE_TYPE = 33,
511  // A crypto message was received with an illegal parameter.
512  QUIC_INVALID_CRYPTO_MESSAGE_PARAMETER = 34,
513  // An invalid channel id signature was supplied.
514  QUIC_INVALID_CHANNEL_ID_SIGNATURE = 52,
515  // A crypto message was received with a mandatory parameter missing.
516  QUIC_CRYPTO_MESSAGE_PARAMETER_NOT_FOUND = 35,
517  // A crypto message was received with a parameter that has no overlap
518  // with the local parameter.
519  QUIC_CRYPTO_MESSAGE_PARAMETER_NO_OVERLAP = 36,
520  // A crypto message was received that contained a parameter with too few
521  // values.
522  QUIC_CRYPTO_MESSAGE_INDEX_NOT_FOUND = 37,
523  // An internal error occured in crypto processing.
524  QUIC_CRYPTO_INTERNAL_ERROR = 38,
525  // A crypto handshake message specified an unsupported version.
526  QUIC_CRYPTO_VERSION_NOT_SUPPORTED = 39,
527  // There was no intersection between the crypto primitives supported by the
528  // peer and ourselves.
529  QUIC_CRYPTO_NO_SUPPORT = 40,
530  // The server rejected our client hello messages too many times.
531  QUIC_CRYPTO_TOO_MANY_REJECTS = 41,
532  // The client rejected the server's certificate chain or signature.
533  QUIC_PROOF_INVALID = 42,
534  // A crypto message was received with a duplicate tag.
535  QUIC_CRYPTO_DUPLICATE_TAG = 43,
536  // A crypto message was received with the wrong encryption level (i.e. it
537  // should have been encrypted but was not.)
538  QUIC_CRYPTO_ENCRYPTION_LEVEL_INCORRECT = 44,
539  // The server config for a server has expired.
540  QUIC_CRYPTO_SERVER_CONFIG_EXPIRED = 45,
541  // We failed to setup the symmetric keys for a connection.
542  QUIC_CRYPTO_SYMMETRIC_KEY_SETUP_FAILED = 53,
543  // A handshake message arrived, but we are still validating the
544  // previous handshake message.
545  QUIC_CRYPTO_MESSAGE_WHILE_VALIDATING_CLIENT_HELLO = 54,
546  // A server config update arrived before the handshake is complete.
547  QUIC_CRYPTO_UPDATE_BEFORE_HANDSHAKE_COMPLETE = 65,
548  // This connection involved a version negotiation which appears to have been
549  // tampered with.
550  QUIC_VERSION_NEGOTIATION_MISMATCH = 55,
551
552  // No error. Used as bound while iterating.
553  QUIC_LAST_ERROR = 68,
554};
555
556struct NET_EXPORT_PRIVATE QuicPacketPublicHeader {
557  QuicPacketPublicHeader();
558  explicit QuicPacketPublicHeader(const QuicPacketPublicHeader& other);
559  ~QuicPacketPublicHeader();
560
561  // Universal header. All QuicPacket headers will have a connection_id and
562  // public flags.
563  QuicConnectionId connection_id;
564  QuicConnectionIdLength connection_id_length;
565  bool reset_flag;
566  bool version_flag;
567  QuicSequenceNumberLength sequence_number_length;
568  QuicVersionVector versions;
569};
570
571// Header for Data or FEC packets.
572struct NET_EXPORT_PRIVATE QuicPacketHeader {
573  QuicPacketHeader();
574  explicit QuicPacketHeader(const QuicPacketPublicHeader& header);
575
576  NET_EXPORT_PRIVATE friend std::ostream& operator<<(
577      std::ostream& os, const QuicPacketHeader& s);
578
579  QuicPacketPublicHeader public_header;
580  bool fec_flag;
581  bool entropy_flag;
582  QuicPacketEntropyHash entropy_hash;
583  QuicPacketSequenceNumber packet_sequence_number;
584  InFecGroup is_in_fec_group;
585  QuicFecGroupNumber fec_group;
586};
587
588struct NET_EXPORT_PRIVATE QuicPublicResetPacket {
589  QuicPublicResetPacket();
590  explicit QuicPublicResetPacket(const QuicPacketPublicHeader& header);
591
592  QuicPacketPublicHeader public_header;
593  QuicPublicResetNonceProof nonce_proof;
594  QuicPacketSequenceNumber rejected_sequence_number;
595  IPEndPoint client_address;
596};
597
598enum QuicVersionNegotiationState {
599  START_NEGOTIATION = 0,
600  // Server-side this implies we've sent a version negotiation packet and are
601  // waiting on the client to select a compatible version.  Client-side this
602  // implies we've gotten a version negotiation packet, are retransmitting the
603  // initial packets with a supported version and are waiting for our first
604  // packet from the server.
605  NEGOTIATION_IN_PROGRESS,
606  // This indicates this endpoint has received a packet from the peer with a
607  // version this endpoint supports.  Version negotiation is complete, and the
608  // version number will no longer be sent with future packets.
609  NEGOTIATED_VERSION
610};
611
612typedef QuicPacketPublicHeader QuicVersionNegotiationPacket;
613
614// A padding frame contains no payload.
615struct NET_EXPORT_PRIVATE QuicPaddingFrame {
616};
617
618// A ping frame contains no payload, though it is retransmittable,
619// and ACK'd just like other normal frames.
620struct NET_EXPORT_PRIVATE QuicPingFrame {
621};
622
623struct NET_EXPORT_PRIVATE QuicStreamFrame {
624  QuicStreamFrame();
625  QuicStreamFrame(const QuicStreamFrame& frame);
626  QuicStreamFrame(QuicStreamId stream_id,
627                  bool fin,
628                  QuicStreamOffset offset,
629                  IOVector data);
630
631  NET_EXPORT_PRIVATE friend std::ostream& operator<<(
632      std::ostream& os, const QuicStreamFrame& s);
633
634  // Returns a copy of the IOVector |data| as a heap-allocated string.
635  // Caller must take ownership of the returned string.
636  std::string* GetDataAsString() const;
637
638  QuicStreamId stream_id;
639  bool fin;
640  QuicStreamOffset offset;  // Location of this data in the stream.
641  IOVector data;
642
643  // If this is set, then when this packet is ACKed the AckNotifier will be
644  // informed.
645  QuicAckNotifier* notifier;
646};
647
648// TODO(ianswett): Re-evaluate the trade-offs of hash_set vs set when framing
649// is finalized.
650typedef std::set<QuicPacketSequenceNumber> SequenceNumberSet;
651typedef std::list<QuicPacketSequenceNumber> SequenceNumberList;
652
653typedef std::list<
654    std::pair<QuicPacketSequenceNumber, QuicTime> > PacketTimeList;
655
656struct NET_EXPORT_PRIVATE QuicStopWaitingFrame {
657  QuicStopWaitingFrame();
658  ~QuicStopWaitingFrame();
659
660  NET_EXPORT_PRIVATE friend std::ostream& operator<<(
661      std::ostream& os, const QuicStopWaitingFrame& s);
662  // Entropy hash of all packets up to, but not including, the least unacked
663  // packet.
664  QuicPacketEntropyHash entropy_hash;
665  // The lowest packet we've sent which is unacked, and we expect an ack for.
666  QuicPacketSequenceNumber least_unacked;
667};
668
669struct NET_EXPORT_PRIVATE QuicAckFrame {
670  QuicAckFrame();
671  ~QuicAckFrame();
672
673  NET_EXPORT_PRIVATE friend std::ostream& operator<<(
674      std::ostream& os, const QuicAckFrame& s);
675
676  // Entropy hash of all packets up to largest observed not including missing
677  // packets.
678  QuicPacketEntropyHash entropy_hash;
679
680  // The highest packet sequence number we've observed from the peer.
681  //
682  // In general, this should be the largest packet number we've received.  In
683  // the case of truncated acks, we may have to advertise a lower "upper bound"
684  // than largest received, to avoid implicitly acking missing packets that
685  // don't fit in the missing packet list due to size limitations.  In this
686  // case, largest_observed may be a packet which is also in the missing packets
687  // list.
688  QuicPacketSequenceNumber largest_observed;
689
690  // Time elapsed since largest_observed was received until this Ack frame was
691  // sent.
692  QuicTime::Delta delta_time_largest_observed;
693
694  // TODO(satyamshekhar): Can be optimized using an interval set like data
695  // structure.
696  // The set of packets which we're expecting and have not received.
697  SequenceNumberSet missing_packets;
698
699  // Whether the ack had to be truncated when sent.
700  bool is_truncated;
701
702  // Packets which have been revived via FEC.
703  // All of these must also be in missing_packets.
704  SequenceNumberSet revived_packets;
705
706  // List of <sequence_number, time> for when packets arrived.
707  PacketTimeList received_packet_times;
708};
709
710// True if the sequence number is greater than largest_observed or is listed
711// as missing.
712// Always returns false for sequence numbers less than least_unacked.
713bool NET_EXPORT_PRIVATE IsAwaitingPacket(
714    const QuicAckFrame& ack_frame,
715    QuicPacketSequenceNumber sequence_number);
716
717// Inserts missing packets between [lower, higher).
718void NET_EXPORT_PRIVATE InsertMissingPacketsBetween(
719    QuicAckFrame* ack_frame,
720    QuicPacketSequenceNumber lower,
721    QuicPacketSequenceNumber higher);
722
723// Defines for all types of congestion feedback that will be negotiated in QUIC,
724// kTCP MUST be supported by all QUIC implementations to guarantee 100%
725// compatibility.
726// TODO(cyr): Remove this when removing QUIC_VERSION_22.
727enum CongestionFeedbackType {
728  kTCP,  // Used to mimic TCP.
729};
730
731// Defines for all types of congestion control algorithms that can be used in
732// QUIC. Note that this is separate from the congestion feedback type -
733// some congestion control algorithms may use the same feedback type
734// (Reno and Cubic are the classic example for that).
735enum CongestionControlType {
736  kCubic,
737  kReno,
738  kBBR,
739};
740
741enum LossDetectionType {
742  kNack,  // Used to mimic TCP's loss detection.
743  kTime,  // Time based loss detection.
744};
745
746// TODO(cyr): Remove this when removing QUIC_VERSION_22.
747struct NET_EXPORT_PRIVATE CongestionFeedbackMessageTCP {
748  CongestionFeedbackMessageTCP();
749
750  QuicByteCount receive_window;
751};
752
753// TODO(cyr): Remove this when removing QUIC_VERSION_22.
754struct NET_EXPORT_PRIVATE QuicCongestionFeedbackFrame {
755  QuicCongestionFeedbackFrame();
756  ~QuicCongestionFeedbackFrame();
757
758  NET_EXPORT_PRIVATE friend std::ostream& operator<<(
759      std::ostream& os, const QuicCongestionFeedbackFrame& c);
760
761  CongestionFeedbackType type;
762  // This should really be a union, but since the timestamp struct
763  // is non-trivial, C++ prohibits it.
764  CongestionFeedbackMessageTCP tcp;
765};
766
767struct NET_EXPORT_PRIVATE QuicRstStreamFrame {
768  QuicRstStreamFrame();
769  QuicRstStreamFrame(QuicStreamId stream_id,
770                     QuicRstStreamErrorCode error_code,
771                     QuicStreamOffset bytes_written);
772
773  NET_EXPORT_PRIVATE friend std::ostream& operator<<(
774      std::ostream& os, const QuicRstStreamFrame& r);
775
776  QuicStreamId stream_id;
777  QuicRstStreamErrorCode error_code;
778  std::string error_details;
779
780  // Used to update flow control windows. On termination of a stream, both
781  // endpoints must inform the peer of the number of bytes they have sent on
782  // that stream. This can be done through normal termination (data packet with
783  // FIN) or through a RST.
784  QuicStreamOffset byte_offset;
785};
786
787struct NET_EXPORT_PRIVATE QuicConnectionCloseFrame {
788  QuicConnectionCloseFrame();
789
790  NET_EXPORT_PRIVATE friend std::ostream& operator<<(
791      std::ostream& os, const QuicConnectionCloseFrame& c);
792
793  QuicErrorCode error_code;
794  std::string error_details;
795};
796
797struct NET_EXPORT_PRIVATE QuicGoAwayFrame {
798  QuicGoAwayFrame();
799  QuicGoAwayFrame(QuicErrorCode error_code,
800                  QuicStreamId last_good_stream_id,
801                  const std::string& reason);
802
803  NET_EXPORT_PRIVATE friend std::ostream& operator<<(
804      std::ostream& os, const QuicGoAwayFrame& g);
805
806  QuicErrorCode error_code;
807  QuicStreamId last_good_stream_id;
808  std::string reason_phrase;
809};
810
811// Flow control updates per-stream and at the connection levoel.
812// Based on SPDY's WINDOW_UPDATE frame, but uses an absolute byte offset rather
813// than a window delta.
814// TODO(rjshade): A possible future optimization is to make stream_id and
815//                byte_offset variable length, similar to stream frames.
816struct NET_EXPORT_PRIVATE QuicWindowUpdateFrame {
817  QuicWindowUpdateFrame() {}
818  QuicWindowUpdateFrame(QuicStreamId stream_id, QuicStreamOffset byte_offset);
819
820  NET_EXPORT_PRIVATE friend std::ostream& operator<<(
821      std::ostream& os, const QuicWindowUpdateFrame& w);
822
823  // The stream this frame applies to.  0 is a special case meaning the overall
824  // connection rather than a specific stream.
825  QuicStreamId stream_id;
826
827  // Byte offset in the stream or connection. The receiver of this frame must
828  // not send data which would result in this offset being exceeded.
829  QuicStreamOffset byte_offset;
830};
831
832// The BLOCKED frame is used to indicate to the remote endpoint that this
833// endpoint believes itself to be flow-control blocked but otherwise ready to
834// send data. The BLOCKED frame is purely advisory and optional.
835// Based on SPDY's BLOCKED frame (undocumented as of 2014-01-28).
836struct NET_EXPORT_PRIVATE QuicBlockedFrame {
837  QuicBlockedFrame() {}
838  explicit QuicBlockedFrame(QuicStreamId stream_id);
839
840  NET_EXPORT_PRIVATE friend std::ostream& operator<<(
841      std::ostream& os, const QuicBlockedFrame& b);
842
843  // The stream this frame applies to.  0 is a special case meaning the overall
844  // connection rather than a specific stream.
845  QuicStreamId stream_id;
846};
847
848// EncryptionLevel enumerates the stages of encryption that a QUIC connection
849// progresses through. When retransmitting a packet, the encryption level needs
850// to be specified so that it is retransmitted at a level which the peer can
851// understand.
852enum EncryptionLevel {
853  ENCRYPTION_NONE = 0,
854  ENCRYPTION_INITIAL = 1,
855  ENCRYPTION_FORWARD_SECURE = 2,
856
857  NUM_ENCRYPTION_LEVELS,
858};
859
860struct NET_EXPORT_PRIVATE QuicFrame {
861  QuicFrame();
862  explicit QuicFrame(QuicPaddingFrame* padding_frame);
863  explicit QuicFrame(QuicStreamFrame* stream_frame);
864  explicit QuicFrame(QuicAckFrame* frame);
865
866  // TODO(cyr): Remove this when removing QUIC_VERSION_22.
867  explicit QuicFrame(QuicCongestionFeedbackFrame* frame);
868
869  explicit QuicFrame(QuicRstStreamFrame* frame);
870  explicit QuicFrame(QuicConnectionCloseFrame* frame);
871  explicit QuicFrame(QuicStopWaitingFrame* frame);
872  explicit QuicFrame(QuicPingFrame* frame);
873  explicit QuicFrame(QuicGoAwayFrame* frame);
874  explicit QuicFrame(QuicWindowUpdateFrame* frame);
875  explicit QuicFrame(QuicBlockedFrame* frame);
876
877  NET_EXPORT_PRIVATE friend std::ostream& operator<<(
878      std::ostream& os, const QuicFrame& frame);
879
880  QuicFrameType type;
881  union {
882    QuicPaddingFrame* padding_frame;
883    QuicStreamFrame* stream_frame;
884    QuicAckFrame* ack_frame;
885
886    // TODO(cyr): Remove this when removing QUIC_VERSION_22.
887    QuicCongestionFeedbackFrame* congestion_feedback_frame;
888    QuicStopWaitingFrame* stop_waiting_frame;
889
890    QuicPingFrame* ping_frame;
891    QuicRstStreamFrame* rst_stream_frame;
892    QuicConnectionCloseFrame* connection_close_frame;
893    QuicGoAwayFrame* goaway_frame;
894    QuicWindowUpdateFrame* window_update_frame;
895    QuicBlockedFrame* blocked_frame;
896  };
897};
898
899typedef std::vector<QuicFrame> QuicFrames;
900
901struct NET_EXPORT_PRIVATE QuicFecData {
902  QuicFecData();
903
904  // The FEC group number is also the sequence number of the first
905  // FEC protected packet.  The last protected packet's sequence number will
906  // be one less than the sequence number of the FEC packet.
907  QuicFecGroupNumber fec_group;
908  base::StringPiece redundancy;
909};
910
911class NET_EXPORT_PRIVATE QuicData {
912 public:
913  QuicData(const char* buffer, size_t length);
914  QuicData(char* buffer, size_t length, bool owns_buffer);
915  virtual ~QuicData();
916
917  base::StringPiece AsStringPiece() const {
918    return base::StringPiece(data(), length());
919  }
920
921  const char* data() const { return buffer_; }
922  size_t length() const { return length_; }
923
924 private:
925  const char* buffer_;
926  size_t length_;
927  bool owns_buffer_;
928
929  DISALLOW_COPY_AND_ASSIGN(QuicData);
930};
931
932class NET_EXPORT_PRIVATE QuicPacket : public QuicData {
933 public:
934  static QuicPacket* NewDataPacket(
935      char* buffer,
936      size_t length,
937      bool owns_buffer,
938      QuicConnectionIdLength connection_id_length,
939      bool includes_version,
940      QuicSequenceNumberLength sequence_number_length) {
941    return new QuicPacket(buffer, length, owns_buffer, connection_id_length,
942                          includes_version, sequence_number_length, false);
943  }
944
945  static QuicPacket* NewFecPacket(
946      char* buffer,
947      size_t length,
948      bool owns_buffer,
949      QuicConnectionIdLength connection_id_length,
950      bool includes_version,
951      QuicSequenceNumberLength sequence_number_length) {
952    return new QuicPacket(buffer, length, owns_buffer, connection_id_length,
953                          includes_version, sequence_number_length, true);
954  }
955
956  base::StringPiece FecProtectedData() const;
957  base::StringPiece AssociatedData() const;
958  base::StringPiece BeforePlaintext() const;
959  base::StringPiece Plaintext() const;
960
961  bool is_fec_packet() const { return is_fec_packet_; }
962
963  char* mutable_data() { return buffer_; }
964
965 private:
966  QuicPacket(char* buffer,
967             size_t length,
968             bool owns_buffer,
969             QuicConnectionIdLength connection_id_length,
970             bool includes_version,
971             QuicSequenceNumberLength sequence_number_length,
972             bool is_fec_packet);
973
974  char* buffer_;
975  const bool is_fec_packet_;
976  const QuicConnectionIdLength connection_id_length_;
977  const bool includes_version_;
978  const QuicSequenceNumberLength sequence_number_length_;
979
980  DISALLOW_COPY_AND_ASSIGN(QuicPacket);
981};
982
983class NET_EXPORT_PRIVATE QuicEncryptedPacket : public QuicData {
984 public:
985  QuicEncryptedPacket(const char* buffer, size_t length);
986  QuicEncryptedPacket(char* buffer, size_t length, bool owns_buffer);
987
988  // Clones the packet into a new packet which owns the buffer.
989  QuicEncryptedPacket* Clone() const;
990
991  // By default, gtest prints the raw bytes of an object. The bool data
992  // member (in the base class QuicData) causes this object to have padding
993  // bytes, which causes the default gtest object printer to read
994  // uninitialize memory. So we need to teach gtest how to print this object.
995  NET_EXPORT_PRIVATE friend std::ostream& operator<<(
996      std::ostream& os, const QuicEncryptedPacket& s);
997
998 private:
999  DISALLOW_COPY_AND_ASSIGN(QuicEncryptedPacket);
1000};
1001
1002class NET_EXPORT_PRIVATE RetransmittableFrames {
1003 public:
1004  RetransmittableFrames();
1005  ~RetransmittableFrames();
1006
1007  // Allocates a local copy of the referenced StringPiece has QuicStreamFrame
1008  // use it.
1009  // Takes ownership of |stream_frame|.
1010  const QuicFrame& AddStreamFrame(QuicStreamFrame* stream_frame);
1011  // Takes ownership of the frame inside |frame|.
1012  const QuicFrame& AddNonStreamFrame(const QuicFrame& frame);
1013  const QuicFrames& frames() const { return frames_; }
1014
1015  IsHandshake HasCryptoHandshake() const {
1016    return has_crypto_handshake_;
1017  }
1018
1019  void set_encryption_level(EncryptionLevel level);
1020  EncryptionLevel encryption_level() const {
1021    return encryption_level_;
1022  }
1023
1024 private:
1025  QuicFrames frames_;
1026  EncryptionLevel encryption_level_;
1027  IsHandshake has_crypto_handshake_;
1028  // Data referenced by the StringPiece of a QuicStreamFrame.
1029  std::vector<std::string*> stream_data_;
1030
1031  DISALLOW_COPY_AND_ASSIGN(RetransmittableFrames);
1032};
1033
1034struct NET_EXPORT_PRIVATE SerializedPacket {
1035  SerializedPacket(QuicPacketSequenceNumber sequence_number,
1036                   QuicSequenceNumberLength sequence_number_length,
1037                   QuicPacket* packet,
1038                   QuicPacketEntropyHash entropy_hash,
1039                   RetransmittableFrames* retransmittable_frames);
1040  ~SerializedPacket();
1041
1042  QuicPacketSequenceNumber sequence_number;
1043  QuicSequenceNumberLength sequence_number_length;
1044  QuicPacket* packet;
1045  QuicPacketEntropyHash entropy_hash;
1046  RetransmittableFrames* retransmittable_frames;
1047
1048  // If set, these will be called when this packet is ACKed by the peer.
1049  std::set<QuicAckNotifier*> notifiers;
1050};
1051
1052struct NET_EXPORT_PRIVATE TransmissionInfo {
1053  // Used by STL when assigning into a map.
1054  TransmissionInfo();
1055
1056  // Constructs a Transmission with a new all_tranmissions set
1057  // containing |sequence_number|.
1058  TransmissionInfo(RetransmittableFrames* retransmittable_frames,
1059                   QuicSequenceNumberLength sequence_number_length);
1060
1061  // Constructs a Transmission with the specified |all_tranmissions| set
1062  // and inserts |sequence_number| into it.
1063  TransmissionInfo(RetransmittableFrames* retransmittable_frames,
1064                   QuicSequenceNumberLength sequence_number_length,
1065                   TransmissionType transmission_type,
1066                   SequenceNumberList* all_transmissions);
1067
1068  RetransmittableFrames* retransmittable_frames;
1069  QuicSequenceNumberLength sequence_number_length;
1070  // Zero when the packet is serialized, non-zero once it's sent.
1071  QuicTime sent_time;
1072  // Zero when the packet is serialized, non-zero once it's sent.
1073  QuicByteCount bytes_sent;
1074  size_t nack_count;
1075  // Reason why this packet was transmitted.
1076  TransmissionType transmission_type;
1077  // Stores the sequence numbers of all transmissions of this packet.
1078  // Must always be NULL or have multiple elements.
1079  SequenceNumberList* all_transmissions;
1080  // In flight packets have not been abandoned or lost.
1081  bool in_flight;
1082  // True if the packet can never be acked, so it can be removed.
1083  bool is_unackable;
1084};
1085
1086}  // namespace net
1087
1088#endif  // NET_QUIC_QUIC_PROTOCOL_H_
1089