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