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