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