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