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