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