quic_protocol.h revision f8ee788a64d60abd8f2d742a5fdedde054ecd910
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.
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,  // Current version.
283};
284
285// This vector contains QUIC versions which we currently support.
286// This should be ordered such that the highest supported version is the first
287// element, with subsequent elements in descending order (versions can be
288// skipped as necessary).
289//
290// IMPORTANT: if you are addding to this list, follow the instructions at
291// http://sites/quic/adding-and-removing-versions
292static const QuicVersion kSupportedQuicVersions[] = {QUIC_VERSION_19,
293                                                     QUIC_VERSION_18,
294                                                     QUIC_VERSION_17,
295                                                     QUIC_VERSION_16,
296                                                     QUIC_VERSION_15};
297
298typedef std::vector<QuicVersion> QuicVersionVector;
299
300// Returns a vector of QUIC versions in kSupportedQuicVersions.
301NET_EXPORT_PRIVATE QuicVersionVector QuicSupportedVersions();
302
303// QuicTag is written to and read from the wire, but we prefer to use
304// the more readable QuicVersion at other levels.
305// Helper function which translates from a QuicVersion to a QuicTag. Returns 0
306// if QuicVersion is unsupported.
307NET_EXPORT_PRIVATE QuicTag QuicVersionToQuicTag(const QuicVersion version);
308
309// Returns appropriate QuicVersion from a QuicTag.
310// Returns QUIC_VERSION_UNSUPPORTED if version_tag cannot be understood.
311NET_EXPORT_PRIVATE QuicVersion QuicTagToQuicVersion(const QuicTag version_tag);
312
313// Helper function which translates from a QuicVersion to a string.
314// Returns strings corresponding to enum names (e.g. QUIC_VERSION_6).
315NET_EXPORT_PRIVATE std::string QuicVersionToString(const QuicVersion version);
316
317// Returns comma separated list of string representations of QuicVersion enum
318// values in the supplied |versions| vector.
319NET_EXPORT_PRIVATE std::string QuicVersionVectorToString(
320    const QuicVersionVector& versions);
321
322// Version and Crypto tags are written to the wire with a big-endian
323// representation of the name of the tag.  For example
324// the client hello tag (CHLO) will be written as the
325// following 4 bytes: 'C' 'H' 'L' 'O'.  Since it is
326// stored in memory as a little endian uint32, we need
327// to reverse the order of the bytes.
328
329// MakeQuicTag returns a value given the four bytes. For example:
330//   MakeQuicTag('C', 'H', 'L', 'O');
331NET_EXPORT_PRIVATE QuicTag MakeQuicTag(char a, char b, char c, char d);
332
333// Returns true if the tag vector contains the specified tag.
334bool ContainsQuicTag(const QuicTagVector& tag_vector, QuicTag tag);
335
336// Size in bytes of the data or fec packet header.
337NET_EXPORT_PRIVATE size_t GetPacketHeaderSize(const QuicPacketHeader& header);
338
339NET_EXPORT_PRIVATE size_t GetPacketHeaderSize(
340    QuicConnectionIdLength connection_id_length,
341    bool include_version,
342    QuicSequenceNumberLength sequence_number_length,
343    InFecGroup is_in_fec_group);
344
345// Index of the first byte in a QUIC packet of FEC protected data.
346NET_EXPORT_PRIVATE size_t GetStartOfFecProtectedData(
347    QuicConnectionIdLength connection_id_length,
348    bool include_version,
349    QuicSequenceNumberLength sequence_number_length);
350// Index of the first byte in a QUIC packet of encrypted data.
351NET_EXPORT_PRIVATE size_t GetStartOfEncryptedData(
352    QuicConnectionIdLength connection_id_length,
353    bool include_version,
354    QuicSequenceNumberLength sequence_number_length);
355
356enum QuicRstStreamErrorCode {
357  QUIC_STREAM_NO_ERROR = 0,
358
359  // There was some error which halted stream processing.
360  QUIC_ERROR_PROCESSING_STREAM,
361  // We got two fin or reset offsets which did not match.
362  QUIC_MULTIPLE_TERMINATION_OFFSETS,
363  // We got bad payload and can not respond to it at the protocol level.
364  QUIC_BAD_APPLICATION_PAYLOAD,
365  // Stream closed due to connection error. No reset frame is sent when this
366  // happens.
367  QUIC_STREAM_CONNECTION_ERROR,
368  // GoAway frame sent. No more stream can be created.
369  QUIC_STREAM_PEER_GOING_AWAY,
370  // The stream has been cancelled.
371  QUIC_STREAM_CANCELLED,
372  // Sending a RST to allow for proper flow control accounting.
373  QUIC_RST_FLOW_CONTROL_ACCOUNTING,
374
375  // No error. Used as bound while iterating.
376  QUIC_STREAM_LAST_ERROR,
377};
378
379// Because receiving an unknown QuicRstStreamErrorCode results in connection
380// teardown, we use this to make sure any errors predating a given version are
381// downgraded to the most appropriate existing error.
382NET_EXPORT_PRIVATE QuicRstStreamErrorCode AdjustErrorForVersion(
383    QuicRstStreamErrorCode error_code,
384    QuicVersion version);
385
386// These values must remain stable as they are uploaded to UMA histograms.
387// To add a new error code, use the current value of QUIC_LAST_ERROR and
388// increment QUIC_LAST_ERROR.
389enum QuicErrorCode {
390  QUIC_NO_ERROR = 0,
391
392  // Connection has reached an invalid state.
393  QUIC_INTERNAL_ERROR = 1,
394  // There were data frames after the a fin or reset.
395  QUIC_STREAM_DATA_AFTER_TERMINATION = 2,
396  // Control frame is malformed.
397  QUIC_INVALID_PACKET_HEADER = 3,
398  // Frame data is malformed.
399  QUIC_INVALID_FRAME_DATA = 4,
400  // The packet contained no payload.
401  QUIC_MISSING_PAYLOAD = 48,
402  // FEC data is malformed.
403  QUIC_INVALID_FEC_DATA = 5,
404  // STREAM frame data is malformed.
405  QUIC_INVALID_STREAM_DATA = 46,
406  // STREAM frame data is not encrypted.
407  QUIC_UNENCRYPTED_STREAM_DATA = 61,
408  // RST_STREAM frame data is malformed.
409  QUIC_INVALID_RST_STREAM_DATA = 6,
410  // CONNECTION_CLOSE frame data is malformed.
411  QUIC_INVALID_CONNECTION_CLOSE_DATA = 7,
412  // GOAWAY frame data is malformed.
413  QUIC_INVALID_GOAWAY_DATA = 8,
414  // WINDOW_UPDATE frame data is malformed.
415  QUIC_INVALID_WINDOW_UPDATE_DATA = 57,
416  // BLOCKED frame data is malformed.
417  QUIC_INVALID_BLOCKED_DATA = 58,
418  // STOP_WAITING frame data is malformed.
419  QUIC_INVALID_STOP_WAITING_DATA = 60,
420  // ACK frame data is malformed.
421  QUIC_INVALID_ACK_DATA = 9,
422  // CONGESTION_FEEDBACK frame data is malformed.
423  QUIC_INVALID_CONGESTION_FEEDBACK_DATA = 47,
424  // Version negotiation packet is malformed.
425  QUIC_INVALID_VERSION_NEGOTIATION_PACKET = 10,
426  // Public RST packet is malformed.
427  QUIC_INVALID_PUBLIC_RST_PACKET = 11,
428  // There was an error decrypting.
429  QUIC_DECRYPTION_FAILURE = 12,
430  // There was an error encrypting.
431  QUIC_ENCRYPTION_FAILURE = 13,
432  // The packet exceeded kMaxPacketSize.
433  QUIC_PACKET_TOO_LARGE = 14,
434  // Data was sent for a stream which did not exist.
435  QUIC_PACKET_FOR_NONEXISTENT_STREAM = 15,
436  // The peer is going away.  May be a client or server.
437  QUIC_PEER_GOING_AWAY = 16,
438  // A stream ID was invalid.
439  QUIC_INVALID_STREAM_ID = 17,
440  // A priority was invalid.
441  QUIC_INVALID_PRIORITY = 49,
442  // Too many streams already open.
443  QUIC_TOO_MANY_OPEN_STREAMS = 18,
444  // Received public reset for this connection.
445  QUIC_PUBLIC_RESET = 19,
446  // Invalid protocol version.
447  QUIC_INVALID_VERSION = 20,
448
449  // deprecated: QUIC_STREAM_RST_BEFORE_HEADERS_DECOMPRESSED = 21
450
451  // The Header ID for a stream was too far from the previous.
452  QUIC_INVALID_HEADER_ID = 22,
453  // Negotiable parameter received during handshake had invalid value.
454  QUIC_INVALID_NEGOTIATED_VALUE = 23,
455  // There was an error decompressing data.
456  QUIC_DECOMPRESSION_FAILURE = 24,
457  // We hit our prenegotiated (or default) timeout
458  QUIC_CONNECTION_TIMED_OUT = 25,
459  // There was an error encountered migrating addresses
460  QUIC_ERROR_MIGRATING_ADDRESS = 26,
461  // There was an error while writing to the socket.
462  QUIC_PACKET_WRITE_ERROR = 27,
463  // There was an error while reading from the socket.
464  QUIC_PACKET_READ_ERROR = 51,
465  // We received a STREAM_FRAME with no data and no fin flag set.
466  QUIC_INVALID_STREAM_FRAME = 50,
467  // We received invalid data on the headers stream.
468  QUIC_INVALID_HEADERS_STREAM_DATA = 56,
469  // The peer received too much data, violating flow control.
470  QUIC_FLOW_CONTROL_RECEIVED_TOO_MUCH_DATA = 59,
471  // The peer sent too much data, violating flow control.
472  QUIC_FLOW_CONTROL_SENT_TOO_MUCH_DATA = 63,
473  // The peer received an invalid flow control window.
474  QUIC_FLOW_CONTROL_INVALID_WINDOW = 64,
475  // The connection has been IP pooled into an existing connection.
476  QUIC_CONNECTION_IP_POOLED = 62,
477
478  // Crypto errors.
479
480  // Hanshake failed.
481  QUIC_HANDSHAKE_FAILED = 28,
482  // Handshake message contained out of order tags.
483  QUIC_CRYPTO_TAGS_OUT_OF_ORDER = 29,
484  // Handshake message contained too many entries.
485  QUIC_CRYPTO_TOO_MANY_ENTRIES = 30,
486  // Handshake message contained an invalid value length.
487  QUIC_CRYPTO_INVALID_VALUE_LENGTH = 31,
488  // A crypto message was received after the handshake was complete.
489  QUIC_CRYPTO_MESSAGE_AFTER_HANDSHAKE_COMPLETE = 32,
490  // A crypto message was received with an illegal message tag.
491  QUIC_INVALID_CRYPTO_MESSAGE_TYPE = 33,
492  // A crypto message was received with an illegal parameter.
493  QUIC_INVALID_CRYPTO_MESSAGE_PARAMETER = 34,
494  // An invalid channel id signature was supplied.
495  QUIC_INVALID_CHANNEL_ID_SIGNATURE = 52,
496  // A crypto message was received with a mandatory parameter missing.
497  QUIC_CRYPTO_MESSAGE_PARAMETER_NOT_FOUND = 35,
498  // A crypto message was received with a parameter that has no overlap
499  // with the local parameter.
500  QUIC_CRYPTO_MESSAGE_PARAMETER_NO_OVERLAP = 36,
501  // A crypto message was received that contained a parameter with too few
502  // values.
503  QUIC_CRYPTO_MESSAGE_INDEX_NOT_FOUND = 37,
504  // An internal error occured in crypto processing.
505  QUIC_CRYPTO_INTERNAL_ERROR = 38,
506  // A crypto handshake message specified an unsupported version.
507  QUIC_CRYPTO_VERSION_NOT_SUPPORTED = 39,
508  // There was no intersection between the crypto primitives supported by the
509  // peer and ourselves.
510  QUIC_CRYPTO_NO_SUPPORT = 40,
511  // The server rejected our client hello messages too many times.
512  QUIC_CRYPTO_TOO_MANY_REJECTS = 41,
513  // The client rejected the server's certificate chain or signature.
514  QUIC_PROOF_INVALID = 42,
515  // A crypto message was received with a duplicate tag.
516  QUIC_CRYPTO_DUPLICATE_TAG = 43,
517  // A crypto message was received with the wrong encryption level (i.e. it
518  // should have been encrypted but was not.)
519  QUIC_CRYPTO_ENCRYPTION_LEVEL_INCORRECT = 44,
520  // The server config for a server has expired.
521  QUIC_CRYPTO_SERVER_CONFIG_EXPIRED = 45,
522  // We failed to setup the symmetric keys for a connection.
523  QUIC_CRYPTO_SYMMETRIC_KEY_SETUP_FAILED = 53,
524  // A handshake message arrived, but we are still validating the
525  // previous handshake message.
526  QUIC_CRYPTO_MESSAGE_WHILE_VALIDATING_CLIENT_HELLO = 54,
527  // This connection involved a version negotiation which appears to have been
528  // tampered with.
529  QUIC_VERSION_NEGOTIATION_MISMATCH = 55,
530
531  // No error. Used as bound while iterating.
532  QUIC_LAST_ERROR = 65,
533};
534
535struct NET_EXPORT_PRIVATE QuicPacketPublicHeader {
536  QuicPacketPublicHeader();
537  explicit QuicPacketPublicHeader(const QuicPacketPublicHeader& other);
538  ~QuicPacketPublicHeader();
539
540  // Universal header. All QuicPacket headers will have a connection_id and
541  // public flags.
542  QuicConnectionId connection_id;
543  QuicConnectionIdLength connection_id_length;
544  bool reset_flag;
545  bool version_flag;
546  QuicSequenceNumberLength sequence_number_length;
547  QuicVersionVector versions;
548};
549
550// Header for Data or FEC packets.
551struct NET_EXPORT_PRIVATE QuicPacketHeader {
552  QuicPacketHeader();
553  explicit QuicPacketHeader(const QuicPacketPublicHeader& header);
554
555  NET_EXPORT_PRIVATE friend std::ostream& operator<<(
556      std::ostream& os, const QuicPacketHeader& s);
557
558  QuicPacketPublicHeader public_header;
559  bool fec_flag;
560  bool entropy_flag;
561  QuicPacketEntropyHash entropy_hash;
562  QuicPacketSequenceNumber packet_sequence_number;
563  InFecGroup is_in_fec_group;
564  QuicFecGroupNumber fec_group;
565};
566
567struct NET_EXPORT_PRIVATE QuicPublicResetPacket {
568  QuicPublicResetPacket();
569  explicit QuicPublicResetPacket(const QuicPacketPublicHeader& header);
570
571  QuicPacketPublicHeader public_header;
572  QuicPublicResetNonceProof nonce_proof;
573  QuicPacketSequenceNumber rejected_sequence_number;
574  IPEndPoint client_address;
575};
576
577enum QuicVersionNegotiationState {
578  START_NEGOTIATION = 0,
579  // Server-side this implies we've sent a version negotiation packet and are
580  // waiting on the client to select a compatible version.  Client-side this
581  // implies we've gotten a version negotiation packet, are retransmitting the
582  // initial packets with a supported version and are waiting for our first
583  // packet from the server.
584  NEGOTIATION_IN_PROGRESS,
585  // This indicates this endpoint has received a packet from the peer with a
586  // version this endpoint supports.  Version negotiation is complete, and the
587  // version number will no longer be sent with future packets.
588  NEGOTIATED_VERSION
589};
590
591typedef QuicPacketPublicHeader QuicVersionNegotiationPacket;
592
593// A padding frame contains no payload.
594struct NET_EXPORT_PRIVATE QuicPaddingFrame {
595};
596
597// A ping frame contains no payload, though it is retransmittable,
598// and ACK'd just like other normal frames.
599struct NET_EXPORT_PRIVATE QuicPingFrame {
600};
601
602struct NET_EXPORT_PRIVATE QuicStreamFrame {
603  QuicStreamFrame();
604  QuicStreamFrame(const QuicStreamFrame& frame);
605  QuicStreamFrame(QuicStreamId stream_id,
606                  bool fin,
607                  QuicStreamOffset offset,
608                  IOVector data);
609
610  NET_EXPORT_PRIVATE friend std::ostream& operator<<(
611      std::ostream& os, const QuicStreamFrame& s);
612
613  // Returns a copy of the IOVector |data| as a heap-allocated string.
614  // Caller must take ownership of the returned string.
615  std::string* GetDataAsString() const;
616
617  QuicStreamId stream_id;
618  bool fin;
619  QuicStreamOffset offset;  // Location of this data in the stream.
620  IOVector data;
621
622  // If this is set, then when this packet is ACKed the AckNotifier will be
623  // informed.
624  QuicAckNotifier* notifier;
625};
626
627// TODO(ianswett): Re-evaluate the trade-offs of hash_set vs set when framing
628// is finalized.
629typedef std::set<QuicPacketSequenceNumber> SequenceNumberSet;
630// TODO(pwestin): Add a way to enforce the max size of this map.
631typedef std::map<QuicPacketSequenceNumber, QuicTime> TimeMap;
632
633struct NET_EXPORT_PRIVATE ReceivedPacketInfo {
634  ReceivedPacketInfo();
635  ~ReceivedPacketInfo();
636
637  NET_EXPORT_PRIVATE friend std::ostream& operator<<(
638      std::ostream& os, const ReceivedPacketInfo& s);
639
640  // Entropy hash of all packets up to largest observed not including missing
641  // packets.
642  QuicPacketEntropyHash entropy_hash;
643
644  // The highest packet sequence number we've observed from the peer.
645  //
646  // In general, this should be the largest packet number we've received.  In
647  // the case of truncated acks, we may have to advertise a lower "upper bound"
648  // than largest received, to avoid implicitly acking missing packets that
649  // don't fit in the missing packet list due to size limitations.  In this
650  // case, largest_observed may be a packet which is also in the missing packets
651  // list.
652  QuicPacketSequenceNumber largest_observed;
653
654  // Time elapsed since largest_observed was received until this Ack frame was
655  // sent.
656  QuicTime::Delta delta_time_largest_observed;
657
658  // TODO(satyamshekhar): Can be optimized using an interval set like data
659  // structure.
660  // The set of packets which we're expecting and have not received.
661  SequenceNumberSet missing_packets;
662
663  // Whether the ack had to be truncated when sent.
664  bool is_truncated;
665
666  // Packets which have been revived via FEC.
667  // All of these must also be in missing_packets.
668  SequenceNumberSet revived_packets;
669};
670
671// True if the sequence number is greater than largest_observed or is listed
672// as missing.
673// Always returns false for sequence numbers less than least_unacked.
674bool NET_EXPORT_PRIVATE IsAwaitingPacket(
675    const ReceivedPacketInfo& received_info,
676    QuicPacketSequenceNumber sequence_number);
677
678// Inserts missing packets between [lower, higher).
679void NET_EXPORT_PRIVATE InsertMissingPacketsBetween(
680    ReceivedPacketInfo* received_info,
681    QuicPacketSequenceNumber lower,
682    QuicPacketSequenceNumber higher);
683
684struct NET_EXPORT_PRIVATE QuicStopWaitingFrame {
685  QuicStopWaitingFrame();
686  ~QuicStopWaitingFrame();
687
688  NET_EXPORT_PRIVATE friend std::ostream& operator<<(
689      std::ostream& os, const QuicStopWaitingFrame& s);
690
691  // Entropy hash of all packets up to, but not including, the least unacked
692  // packet.
693  QuicPacketEntropyHash entropy_hash;
694  // The lowest packet we've sent which is unacked, and we expect an ack for.
695  QuicPacketSequenceNumber least_unacked;
696};
697
698struct NET_EXPORT_PRIVATE QuicAckFrame {
699  QuicAckFrame();
700
701  NET_EXPORT_PRIVATE friend std::ostream& operator<<(
702      std::ostream& os, const QuicAckFrame& s);
703
704  QuicStopWaitingFrame sent_info;
705  ReceivedPacketInfo received_info;
706};
707
708// Defines for all types of congestion feedback that will be negotiated in QUIC,
709// kTCP MUST be supported by all QUIC implementations to guarantee 100%
710// compatibility.
711enum CongestionFeedbackType {
712  kTCP,  // Used to mimic TCP.
713  kInterArrival,  // Use additional inter arrival information.
714  kFixRate,  // Provided for testing.
715  kTCPBBR,  // BBR implementation based on TCP congestion feedback.
716};
717
718enum LossDetectionType {
719  kNack,  // Used to mimic TCP's loss detection.
720  kTime,  // Time based loss detection.
721};
722
723struct NET_EXPORT_PRIVATE CongestionFeedbackMessageTCP {
724  CongestionFeedbackMessageTCP();
725
726  QuicByteCount receive_window;
727};
728
729struct NET_EXPORT_PRIVATE CongestionFeedbackMessageInterArrival {
730  CongestionFeedbackMessageInterArrival();
731  ~CongestionFeedbackMessageInterArrival();
732
733  // The set of received packets since the last feedback was sent, along with
734  // their arrival times.
735  TimeMap received_packet_times;
736};
737
738struct NET_EXPORT_PRIVATE CongestionFeedbackMessageFixRate {
739  CongestionFeedbackMessageFixRate();
740  QuicBandwidth bitrate;
741};
742
743struct NET_EXPORT_PRIVATE QuicCongestionFeedbackFrame {
744  QuicCongestionFeedbackFrame();
745  ~QuicCongestionFeedbackFrame();
746
747  NET_EXPORT_PRIVATE friend std::ostream& operator<<(
748      std::ostream& os, const QuicCongestionFeedbackFrame& c);
749
750  CongestionFeedbackType type;
751  // This should really be a union, but since the inter arrival struct
752  // is non-trivial, C++ prohibits it.
753  CongestionFeedbackMessageTCP tcp;
754  CongestionFeedbackMessageInterArrival inter_arrival;
755  CongestionFeedbackMessageFixRate fix_rate;
756};
757
758struct NET_EXPORT_PRIVATE QuicRstStreamFrame {
759  QuicRstStreamFrame();
760  QuicRstStreamFrame(QuicStreamId stream_id,
761                     QuicRstStreamErrorCode error_code,
762                     QuicStreamOffset bytes_written);
763
764  NET_EXPORT_PRIVATE friend std::ostream& operator<<(
765      std::ostream& os, const QuicRstStreamFrame& r);
766
767  QuicStreamId stream_id;
768  QuicRstStreamErrorCode error_code;
769  std::string error_details;
770
771  // Used to update flow control windows. On termination of a stream, both
772  // endpoints must inform the peer of the number of bytes they have sent on
773  // that stream. This can be done through normal termination (data packet with
774  // FIN) or through a RST.
775  QuicStreamOffset byte_offset;
776};
777
778struct NET_EXPORT_PRIVATE QuicConnectionCloseFrame {
779  QuicConnectionCloseFrame();
780
781  NET_EXPORT_PRIVATE friend std::ostream& operator<<(
782      std::ostream& os, const QuicConnectionCloseFrame& c);
783
784  QuicErrorCode error_code;
785  std::string error_details;
786};
787
788struct NET_EXPORT_PRIVATE QuicGoAwayFrame {
789  QuicGoAwayFrame();
790  QuicGoAwayFrame(QuicErrorCode error_code,
791                  QuicStreamId last_good_stream_id,
792                  const std::string& reason);
793
794  NET_EXPORT_PRIVATE friend std::ostream& operator<<(
795      std::ostream& os, const QuicGoAwayFrame& g);
796
797  QuicErrorCode error_code;
798  QuicStreamId last_good_stream_id;
799  std::string reason_phrase;
800};
801
802// Flow control updates per-stream and at the connection levoel.
803// Based on SPDY's WINDOW_UPDATE frame, but uses an absolute byte offset rather
804// than a window delta.
805// TODO(rjshade): A possible future optimization is to make stream_id and
806//                byte_offset variable length, similar to stream frames.
807struct NET_EXPORT_PRIVATE QuicWindowUpdateFrame {
808  QuicWindowUpdateFrame() {}
809  QuicWindowUpdateFrame(QuicStreamId stream_id, QuicStreamOffset byte_offset);
810
811  NET_EXPORT_PRIVATE friend std::ostream& operator<<(
812      std::ostream& os, const QuicWindowUpdateFrame& w);
813
814  // The stream this frame applies to.  0 is a special case meaning the overall
815  // connection rather than a specific stream.
816  QuicStreamId stream_id;
817
818  // Byte offset in the stream or connection. The receiver of this frame must
819  // not send data which would result in this offset being exceeded.
820  QuicStreamOffset byte_offset;
821};
822
823// The BLOCKED frame is used to indicate to the remote endpoint that this
824// endpoint believes itself to be flow-control blocked but otherwise ready to
825// send data. The BLOCKED frame is purely advisory and optional.
826// Based on SPDY's BLOCKED frame (undocumented as of 2014-01-28).
827struct NET_EXPORT_PRIVATE QuicBlockedFrame {
828  QuicBlockedFrame() {}
829  explicit QuicBlockedFrame(QuicStreamId stream_id);
830
831  NET_EXPORT_PRIVATE friend std::ostream& operator<<(
832      std::ostream& os, const QuicBlockedFrame& b);
833
834  // The stream this frame applies to.  0 is a special case meaning the overall
835  // connection rather than a specific stream.
836  QuicStreamId stream_id;
837};
838
839// EncryptionLevel enumerates the stages of encryption that a QUIC connection
840// progresses through. When retransmitting a packet, the encryption level needs
841// to be specified so that it is retransmitted at a level which the peer can
842// understand.
843enum EncryptionLevel {
844  ENCRYPTION_NONE = 0,
845  ENCRYPTION_INITIAL = 1,
846  ENCRYPTION_FORWARD_SECURE = 2,
847
848  NUM_ENCRYPTION_LEVELS,
849};
850
851struct NET_EXPORT_PRIVATE QuicFrame {
852  QuicFrame();
853  explicit QuicFrame(QuicPaddingFrame* padding_frame);
854  explicit QuicFrame(QuicStreamFrame* stream_frame);
855  explicit QuicFrame(QuicAckFrame* frame);
856  explicit QuicFrame(QuicCongestionFeedbackFrame* frame);
857  explicit QuicFrame(QuicRstStreamFrame* frame);
858  explicit QuicFrame(QuicConnectionCloseFrame* frame);
859  explicit QuicFrame(QuicStopWaitingFrame* frame);
860  explicit QuicFrame(QuicPingFrame* frame);
861  explicit QuicFrame(QuicGoAwayFrame* frame);
862  explicit QuicFrame(QuicWindowUpdateFrame* frame);
863  explicit QuicFrame(QuicBlockedFrame* frame);
864
865  NET_EXPORT_PRIVATE friend std::ostream& operator<<(
866      std::ostream& os, const QuicFrame& frame);
867
868  QuicFrameType type;
869  union {
870    QuicPaddingFrame* padding_frame;
871    QuicStreamFrame* stream_frame;
872    QuicAckFrame* ack_frame;
873    QuicCongestionFeedbackFrame* congestion_feedback_frame;
874    QuicStopWaitingFrame* stop_waiting_frame;
875    QuicPingFrame* ping_frame;
876    QuicRstStreamFrame* rst_stream_frame;
877    QuicConnectionCloseFrame* connection_close_frame;
878    QuicGoAwayFrame* goaway_frame;
879    QuicWindowUpdateFrame* window_update_frame;
880    QuicBlockedFrame* blocked_frame;
881  };
882};
883
884typedef std::vector<QuicFrame> QuicFrames;
885
886struct NET_EXPORT_PRIVATE QuicFecData {
887  QuicFecData();
888
889  // The FEC group number is also the sequence number of the first
890  // FEC protected packet.  The last protected packet's sequence number will
891  // be one less than the sequence number of the FEC packet.
892  QuicFecGroupNumber fec_group;
893  base::StringPiece redundancy;
894};
895
896class NET_EXPORT_PRIVATE QuicData {
897 public:
898  QuicData(const char* buffer, size_t length);
899  QuicData(char* buffer, size_t length, bool owns_buffer);
900  virtual ~QuicData();
901
902  base::StringPiece AsStringPiece() const {
903    return base::StringPiece(data(), length());
904  }
905
906  const char* data() const { return buffer_; }
907  size_t length() const { return length_; }
908
909 private:
910  const char* buffer_;
911  size_t length_;
912  bool owns_buffer_;
913
914  DISALLOW_COPY_AND_ASSIGN(QuicData);
915};
916
917class NET_EXPORT_PRIVATE QuicPacket : public QuicData {
918 public:
919  static QuicPacket* NewDataPacket(
920      char* buffer,
921      size_t length,
922      bool owns_buffer,
923      QuicConnectionIdLength connection_id_length,
924      bool includes_version,
925      QuicSequenceNumberLength sequence_number_length) {
926    return new QuicPacket(buffer, length, owns_buffer, connection_id_length,
927                          includes_version, sequence_number_length, false);
928  }
929
930  static QuicPacket* NewFecPacket(
931      char* buffer,
932      size_t length,
933      bool owns_buffer,
934      QuicConnectionIdLength connection_id_length,
935      bool includes_version,
936      QuicSequenceNumberLength sequence_number_length) {
937    return new QuicPacket(buffer, length, owns_buffer, connection_id_length,
938                          includes_version, sequence_number_length, true);
939  }
940
941  base::StringPiece FecProtectedData() const;
942  base::StringPiece AssociatedData() const;
943  base::StringPiece BeforePlaintext() const;
944  base::StringPiece Plaintext() const;
945
946  bool is_fec_packet() const { return is_fec_packet_; }
947
948  char* mutable_data() { return buffer_; }
949
950 private:
951  QuicPacket(char* buffer,
952             size_t length,
953             bool owns_buffer,
954             QuicConnectionIdLength connection_id_length,
955             bool includes_version,
956             QuicSequenceNumberLength sequence_number_length,
957             bool is_fec_packet);
958
959  char* buffer_;
960  const bool is_fec_packet_;
961  const QuicConnectionIdLength connection_id_length_;
962  const bool includes_version_;
963  const QuicSequenceNumberLength sequence_number_length_;
964
965  DISALLOW_COPY_AND_ASSIGN(QuicPacket);
966};
967
968class NET_EXPORT_PRIVATE QuicEncryptedPacket : public QuicData {
969 public:
970  QuicEncryptedPacket(const char* buffer, size_t length);
971  QuicEncryptedPacket(char* buffer, size_t length, bool owns_buffer);
972
973  // Clones the packet into a new packet which owns the buffer.
974  QuicEncryptedPacket* Clone() const;
975
976  // By default, gtest prints the raw bytes of an object. The bool data
977  // member (in the base class QuicData) causes this object to have padding
978  // bytes, which causes the default gtest object printer to read
979  // uninitialize memory. So we need to teach gtest how to print this object.
980  NET_EXPORT_PRIVATE friend std::ostream& operator<<(
981      std::ostream& os, const QuicEncryptedPacket& s);
982
983 private:
984  DISALLOW_COPY_AND_ASSIGN(QuicEncryptedPacket);
985};
986
987class NET_EXPORT_PRIVATE RetransmittableFrames {
988 public:
989  RetransmittableFrames();
990  ~RetransmittableFrames();
991
992  // Allocates a local copy of the referenced StringPiece has QuicStreamFrame
993  // use it.
994  // Takes ownership of |stream_frame|.
995  const QuicFrame& AddStreamFrame(QuicStreamFrame* stream_frame);
996  // Takes ownership of the frame inside |frame|.
997  const QuicFrame& AddNonStreamFrame(const QuicFrame& frame);
998  const QuicFrames& frames() const { return frames_; }
999
1000  IsHandshake HasCryptoHandshake() const;
1001
1002  void set_encryption_level(EncryptionLevel level);
1003  EncryptionLevel encryption_level() const {
1004    return encryption_level_;
1005  }
1006
1007 private:
1008  QuicFrames frames_;
1009  EncryptionLevel encryption_level_;
1010  // Data referenced by the StringPiece of a QuicStreamFrame.
1011  std::vector<std::string*> stream_data_;
1012
1013  DISALLOW_COPY_AND_ASSIGN(RetransmittableFrames);
1014};
1015
1016struct NET_EXPORT_PRIVATE SerializedPacket {
1017  SerializedPacket(QuicPacketSequenceNumber sequence_number,
1018                   QuicSequenceNumberLength sequence_number_length,
1019                   QuicPacket* packet,
1020                   QuicPacketEntropyHash entropy_hash,
1021                   RetransmittableFrames* retransmittable_frames);
1022  ~SerializedPacket();
1023
1024  QuicPacketSequenceNumber sequence_number;
1025  QuicSequenceNumberLength sequence_number_length;
1026  QuicPacket* packet;
1027  QuicPacketEntropyHash entropy_hash;
1028  RetransmittableFrames* retransmittable_frames;
1029
1030  // If set, these will be called when this packet is ACKed by the peer.
1031  std::set<QuicAckNotifier*> notifiers;
1032};
1033
1034struct NET_EXPORT_PRIVATE TransmissionInfo {
1035  // Used by STL when assigning into a map.
1036  TransmissionInfo();
1037
1038  // Constructs a Transmission with a new all_tranmissions set
1039  // containing |sequence_number|.
1040  TransmissionInfo(RetransmittableFrames* retransmittable_frames,
1041                   QuicPacketSequenceNumber sequence_number,
1042                   QuicSequenceNumberLength sequence_number_length);
1043
1044  // Constructs a Transmission with the specified |all_tranmissions| set
1045  // and inserts |sequence_number| into it.
1046  TransmissionInfo(RetransmittableFrames* retransmittable_frames,
1047                   QuicPacketSequenceNumber sequence_number,
1048                   QuicSequenceNumberLength sequence_number_length,
1049                   TransmissionType transmission_type,
1050                   SequenceNumberSet* all_transmissions);
1051
1052  RetransmittableFrames* retransmittable_frames;
1053  QuicSequenceNumberLength sequence_number_length;
1054  // Zero when the packet is serialized, non-zero once it's sent.
1055  QuicTime sent_time;
1056  // Zero when the packet is serialized, non-zero once it's sent.
1057  QuicByteCount bytes_sent;
1058  size_t nack_count;
1059  // Reason why this packet was transmitted.
1060  TransmissionType transmission_type;
1061  // Stores the sequence numbers of all transmissions of this packet.
1062  // Can never be null.
1063  SequenceNumberSet* all_transmissions;
1064  // In flight packets have not been abandoned or lost.
1065  bool in_flight;
1066};
1067
1068}  // namespace net
1069
1070#endif  // NET_QUIC_QUIC_PROTOCOL_H_
1071