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