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