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