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