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