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