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