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