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