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 #include "net/quic/quic_framer.h"
      6 
      7 #include "base/containers/hash_tables.h"
      8 #include "net/quic/crypto/quic_decrypter.h"
      9 #include "net/quic/crypto/quic_encrypter.h"
     10 #include "net/quic/quic_data_reader.h"
     11 #include "net/quic/quic_data_writer.h"
     12 
     13 using base::StringPiece;
     14 using std::make_pair;
     15 using std::map;
     16 using std::numeric_limits;
     17 using std::string;
     18 
     19 namespace net {
     20 
     21 namespace {
     22 
     23 // Mask to select the lowest 48 bits of a sequence number.
     24 const QuicPacketSequenceNumber k6ByteSequenceNumberMask =
     25     GG_UINT64_C(0x0000FFFFFFFFFFFF);
     26 const QuicPacketSequenceNumber k4ByteSequenceNumberMask =
     27     GG_UINT64_C(0x00000000FFFFFFFF);
     28 const QuicPacketSequenceNumber k2ByteSequenceNumberMask =
     29     GG_UINT64_C(0x000000000000FFFF);
     30 const QuicPacketSequenceNumber k1ByteSequenceNumberMask =
     31     GG_UINT64_C(0x00000000000000FF);
     32 
     33 const QuicGuid k1ByteGuidMask = GG_UINT64_C(0x00000000000000FF);
     34 const QuicGuid k4ByteGuidMask = GG_UINT64_C(0x00000000FFFFFFFF);
     35 
     36 // Mask to determine if it's a special frame type(Stream, Ack, or
     37 // Congestion Control) by checking if the first bit is 0, then shifting right.
     38 const uint8 kQuicFrameType0BitMask = 0x01;
     39 
     40 // Default frame type shift and mask.
     41 const uint8 kQuicDefaultFrameTypeShift = 3;
     42 const uint8 kQuicDefaultFrameTypeMask = 0x07;
     43 
     44 // Stream frame relative shifts and masks for interpreting the stream flags.
     45 // StreamID may be 1, 2, 3, or 4 bytes.
     46 const uint8 kQuicStreamIdShift = 2;
     47 const uint8 kQuicStreamIDLengthMask = 0x03;
     48 
     49 // Offset may be 0, 2, 3, 4, 5, 6, 7, 8 bytes.
     50 const uint8 kQuicStreamOffsetShift = 3;
     51 const uint8 kQuicStreamOffsetMask = 0x07;
     52 
     53 // Data length may be 0 or 2 bytes.
     54 const uint8 kQuicStreamDataLengthShift = 1;
     55 const uint8 kQuicStreamDataLengthMask = 0x01;
     56 
     57 // Fin bit may be set or not.
     58 const uint8 kQuicStreamFinShift = 1;
     59 const uint8 kQuicStreamFinMask = 0x01;
     60 
     61 
     62 const uint32 kInvalidDeltaTime = 0xffffffff;
     63 
     64 // Returns the absolute value of the difference between |a| and |b|.
     65 QuicPacketSequenceNumber Delta(QuicPacketSequenceNumber a,
     66                                QuicPacketSequenceNumber b) {
     67   // Since these are unsigned numbers, we can't just return abs(a - b)
     68   if (a < b) {
     69     return b - a;
     70   }
     71   return a - b;
     72 }
     73 
     74 QuicPacketSequenceNumber ClosestTo(QuicPacketSequenceNumber target,
     75                                    QuicPacketSequenceNumber a,
     76                                    QuicPacketSequenceNumber b) {
     77   return (Delta(target, a) < Delta(target, b)) ? a : b;
     78 }
     79 
     80 }  // namespace
     81 
     82 QuicFramer::QuicFramer(QuicVersion version,
     83                        QuicTime creation_time,
     84                        bool is_server)
     85     : visitor_(NULL),
     86       fec_builder_(NULL),
     87       error_(QUIC_NO_ERROR),
     88       last_sequence_number_(0),
     89       last_serialized_guid_(0),
     90       quic_version_(version),
     91       decrypter_(QuicDecrypter::Create(kNULL)),
     92       alternative_decrypter_latch_(false),
     93       is_server_(is_server),
     94       creation_time_(creation_time) {
     95   DCHECK(IsSupportedVersion(version));
     96   encrypter_[ENCRYPTION_NONE].reset(QuicEncrypter::Create(kNULL));
     97 }
     98 
     99 QuicFramer::~QuicFramer() {}
    100 
    101 // static
    102 size_t QuicFramer::GetMinStreamFrameSize(QuicVersion version,
    103                                          QuicStreamId stream_id,
    104                                          QuicStreamOffset offset,
    105                                          bool last_frame_in_packet) {
    106   return kQuicFrameTypeSize + GetStreamIdSize(stream_id) +
    107       GetStreamOffsetSize(offset) +
    108       (last_frame_in_packet ? 0 : kQuicStreamPayloadLengthSize);
    109 }
    110 
    111 // static
    112 size_t QuicFramer::GetMinAckFrameSize() {
    113   return kQuicFrameTypeSize + kQuicEntropyHashSize +
    114       PACKET_6BYTE_SEQUENCE_NUMBER + kQuicEntropyHashSize +
    115       PACKET_6BYTE_SEQUENCE_NUMBER + kQuicDeltaTimeLargestObservedSize +
    116       kNumberOfMissingPacketsSize;
    117 }
    118 
    119 // static
    120 size_t QuicFramer::GetMinRstStreamFrameSize() {
    121   return kQuicFrameTypeSize + kQuicMaxStreamIdSize + kQuicErrorCodeSize +
    122       kQuicErrorDetailsLengthSize;
    123 }
    124 
    125 // static
    126 size_t QuicFramer::GetMinConnectionCloseFrameSize() {
    127   return kQuicFrameTypeSize + kQuicErrorCodeSize + kQuicErrorDetailsLengthSize +
    128       GetMinAckFrameSize();
    129 }
    130 
    131 // static
    132 size_t QuicFramer::GetMinGoAwayFrameSize() {
    133   return kQuicFrameTypeSize + kQuicErrorCodeSize + kQuicErrorDetailsLengthSize +
    134       kQuicMaxStreamIdSize;
    135 }
    136 
    137 // static
    138 // TODO(satyamshekhar): 16 - Crypto hash for integrity. Not a static value. Use
    139 // QuicEncrypter::GetMaxPlaintextSize.
    140 // 16 is a conservative estimate in the case of AEAD_AES_128_GCM_12, which uses
    141 // 12-byte tags.
    142 size_t QuicFramer::GetMaxUnackedPackets(QuicPacketHeader header) {
    143   return (kMaxPacketSize - GetPacketHeaderSize(header) -
    144           GetMinAckFrameSize() - 16) / PACKET_6BYTE_SEQUENCE_NUMBER;
    145 }
    146 
    147 // static
    148 size_t QuicFramer::GetStreamIdSize(QuicStreamId stream_id) {
    149   // Sizes are 1 through 4 bytes.
    150   for (int i = 1; i <= 4; ++i) {
    151     stream_id >>= 8;
    152     if (stream_id == 0) {
    153       return i;
    154     }
    155   }
    156   LOG(DFATAL) << "Failed to determine StreamIDSize.";
    157   return 4;
    158 }
    159 
    160 // static
    161 size_t QuicFramer::GetStreamOffsetSize(QuicStreamOffset offset) {
    162   // 0 is a special case.
    163   if (offset == 0) {
    164     return 0;
    165   }
    166   // 2 through 8 are the remaining sizes.
    167   offset >>= 8;
    168   for (int i = 2; i <= 8; ++i) {
    169     offset >>= 8;
    170     if (offset == 0) {
    171       return i;
    172     }
    173   }
    174   LOG(DFATAL) << "Failed to determine StreamOffsetSize.";
    175   return 8;
    176 }
    177 
    178 // static
    179 size_t QuicFramer::GetVersionNegotiationPacketSize(size_t number_versions) {
    180   return kPublicFlagsSize + PACKET_8BYTE_GUID +
    181       number_versions * kQuicVersionSize;
    182 }
    183 
    184 // static
    185 bool QuicFramer::CanTruncate(const QuicFrame& frame, size_t free_bytes) {
    186   // TODO(ianswett): GetMinConnectionCloseFrameSize may be incorrect, because
    187   // checking for it here results in frames not being added, but the resulting
    188   // frames do actually fit.
    189   if ((frame.type == ACK_FRAME || frame.type == CONNECTION_CLOSE_FRAME) &&
    190           free_bytes >= GetMinAckFrameSize()) {
    191     return true;
    192   }
    193   return false;
    194 }
    195 
    196 bool QuicFramer::IsSupportedVersion(const QuicVersion version) const {
    197   for (size_t i = 0; i < arraysize(kSupportedQuicVersions); ++i) {
    198     if (version == kSupportedQuicVersions[i]) {
    199       return true;
    200     }
    201   }
    202   return false;
    203 }
    204 
    205 size_t QuicFramer::GetSerializedFrameLength(
    206     const QuicFrame& frame, size_t free_bytes, bool first_frame) {
    207   if (frame.type == PADDING_FRAME) {
    208     // PADDING implies end of packet.
    209     return free_bytes;
    210   }
    211   // See if it fits as the non-last frame.
    212   size_t frame_len = ComputeFrameLength(frame, false);
    213   // STREAM frames save two bytes when they're the last frame in the packet.
    214   if (frame_len > free_bytes && frame.type == STREAM_FRAME) {
    215     frame_len = ComputeFrameLength(frame, true);
    216   }
    217   if (frame_len > free_bytes) {
    218     // Only truncate the first frame in a packet, so if subsequent ones go
    219     // over, stop including more frames.
    220     if (!first_frame) {
    221       return 0;
    222     }
    223     if (CanTruncate(frame, free_bytes)) {
    224       // Truncate the frame so the packet will not exceed kMaxPacketSize.
    225       // Note that we may not use every byte of the writer in this case.
    226       DLOG(INFO) << "Truncating large frame";
    227       return free_bytes;
    228     }
    229   }
    230   return frame_len;
    231 }
    232 
    233 QuicPacketEntropyHash QuicFramer::GetPacketEntropyHash(
    234     const QuicPacketHeader& header) const {
    235   if (!header.entropy_flag) {
    236     // TODO(satyamshekhar): Return some more better value here (something that
    237     // is not a constant).
    238     return 0;
    239   }
    240   return 1 << (header.packet_sequence_number % 8);
    241 }
    242 
    243 SerializedPacket QuicFramer::BuildUnsizedDataPacket(
    244     const QuicPacketHeader& header,
    245     const QuicFrames& frames) {
    246   const size_t max_plaintext_size = GetMaxPlaintextSize(kMaxPacketSize);
    247   size_t packet_size = GetPacketHeaderSize(header);
    248   for (size_t i = 0; i < frames.size(); ++i) {
    249     DCHECK_LE(packet_size, max_plaintext_size);
    250     const size_t frame_size = GetSerializedFrameLength(
    251         frames[i], max_plaintext_size - packet_size, i == 0);
    252     DCHECK(frame_size);
    253     packet_size += frame_size;
    254   }
    255   return BuildDataPacket(header, frames, packet_size);
    256 }
    257 
    258 SerializedPacket QuicFramer::BuildDataPacket(
    259     const QuicPacketHeader& header,
    260     const QuicFrames& frames,
    261     size_t packet_size) {
    262   QuicDataWriter writer(packet_size);
    263   const SerializedPacket kNoPacket(0, NULL, 0, NULL);
    264   if (!WritePacketHeader(header, &writer)) {
    265     return kNoPacket;
    266   }
    267 
    268   for (size_t i = 0; i < frames.size(); ++i) {
    269     const QuicFrame& frame = frames[i];
    270 
    271     const bool last_frame_in_packet = i == (frames.size() - 1);
    272     if (!AppendTypeByte(frame, last_frame_in_packet, &writer)) {
    273       return kNoPacket;
    274     }
    275 
    276     switch (frame.type) {
    277       case PADDING_FRAME:
    278         writer.WritePadding();
    279         break;
    280       case STREAM_FRAME:
    281         if (!AppendStreamFramePayload(
    282             *frame.stream_frame, last_frame_in_packet, &writer)) {
    283           return kNoPacket;
    284         }
    285         break;
    286       case ACK_FRAME:
    287         if (!AppendAckFramePayload(*frame.ack_frame, &writer)) {
    288           return kNoPacket;
    289         }
    290         break;
    291       case CONGESTION_FEEDBACK_FRAME:
    292         if (!AppendQuicCongestionFeedbackFramePayload(
    293                 *frame.congestion_feedback_frame, &writer)) {
    294           return kNoPacket;
    295         }
    296         break;
    297       case RST_STREAM_FRAME:
    298         if (!AppendRstStreamFramePayload(*frame.rst_stream_frame, &writer)) {
    299           return kNoPacket;
    300         }
    301         break;
    302       case CONNECTION_CLOSE_FRAME:
    303         if (!AppendConnectionCloseFramePayload(
    304                 *frame.connection_close_frame, &writer)) {
    305           return kNoPacket;
    306         }
    307         break;
    308       case GOAWAY_FRAME:
    309         if (!AppendGoAwayFramePayload(*frame.goaway_frame, &writer)) {
    310           return kNoPacket;
    311         }
    312         break;
    313       default:
    314         RaiseError(QUIC_INVALID_FRAME_DATA);
    315         return kNoPacket;
    316     }
    317   }
    318 
    319   // Save the length before writing, because take clears it.
    320   const size_t len = writer.length();
    321   // Less than or equal because truncated acks end up with max_plaintex_size
    322   // length, even though they're typically slightly shorter.
    323   DCHECK_LE(len, packet_size);
    324   QuicPacket* packet = QuicPacket::NewDataPacket(
    325       writer.take(), len, true, header.public_header.guid_length,
    326       header.public_header.version_flag,
    327       header.public_header.sequence_number_length);
    328 
    329   if (fec_builder_) {
    330     fec_builder_->OnBuiltFecProtectedPayload(header,
    331                                              packet->FecProtectedData());
    332   }
    333 
    334   return SerializedPacket(header.packet_sequence_number, packet,
    335                           GetPacketEntropyHash(header), NULL);
    336 }
    337 
    338 SerializedPacket QuicFramer::BuildFecPacket(const QuicPacketHeader& header,
    339                                             const QuicFecData& fec) {
    340   DCHECK_EQ(IN_FEC_GROUP, header.is_in_fec_group);
    341   DCHECK_NE(0u, header.fec_group);
    342   size_t len = GetPacketHeaderSize(header);
    343   len += fec.redundancy.length();
    344 
    345   QuicDataWriter writer(len);
    346   SerializedPacket kNoPacket = SerializedPacket(0, NULL, 0, NULL);
    347   if (!WritePacketHeader(header, &writer)) {
    348     return kNoPacket;
    349   }
    350 
    351   if (!writer.WriteBytes(fec.redundancy.data(), fec.redundancy.length())) {
    352     return kNoPacket;
    353   }
    354 
    355   return SerializedPacket(
    356       header.packet_sequence_number,
    357       QuicPacket::NewFecPacket(writer.take(), len, true,
    358                                header.public_header.guid_length,
    359                                header.public_header.version_flag,
    360                                header.public_header.sequence_number_length),
    361       GetPacketEntropyHash(header), NULL);
    362 }
    363 
    364 // static
    365 QuicEncryptedPacket* QuicFramer::BuildPublicResetPacket(
    366     const QuicPublicResetPacket& packet) {
    367   DCHECK(packet.public_header.reset_flag);
    368   size_t len = GetPublicResetPacketSize();
    369   QuicDataWriter writer(len);
    370 
    371   uint8 flags = static_cast<uint8>(PACKET_PUBLIC_FLAGS_RST |
    372                                    PACKET_PUBLIC_FLAGS_8BYTE_GUID |
    373                                    PACKET_PUBLIC_FLAGS_6BYTE_SEQUENCE);
    374   if (!writer.WriteUInt8(flags)) {
    375     return NULL;
    376   }
    377 
    378   if (!writer.WriteUInt64(packet.public_header.guid)) {
    379     return NULL;
    380   }
    381 
    382   if (!writer.WriteUInt64(packet.nonce_proof)) {
    383     return NULL;
    384   }
    385 
    386   if (!AppendPacketSequenceNumber(PACKET_6BYTE_SEQUENCE_NUMBER,
    387                                   packet.rejected_sequence_number,
    388                                   &writer)) {
    389     return NULL;
    390   }
    391 
    392   return new QuicEncryptedPacket(writer.take(), len, true);
    393 }
    394 
    395 QuicEncryptedPacket* QuicFramer::BuildVersionNegotiationPacket(
    396     const QuicPacketPublicHeader& header,
    397     const QuicVersionVector& supported_versions) {
    398   DCHECK(header.version_flag);
    399   size_t len = GetVersionNegotiationPacketSize(supported_versions.size());
    400   QuicDataWriter writer(len);
    401 
    402   uint8 flags = static_cast<uint8>(PACKET_PUBLIC_FLAGS_VERSION |
    403                                    PACKET_PUBLIC_FLAGS_8BYTE_GUID |
    404                                    PACKET_PUBLIC_FLAGS_6BYTE_SEQUENCE);
    405   if (!writer.WriteUInt8(flags)) {
    406     return NULL;
    407   }
    408 
    409   if (!writer.WriteUInt64(header.guid)) {
    410     return NULL;
    411   }
    412 
    413   for (size_t i = 0; i < supported_versions.size(); ++i) {
    414     if (!writer.WriteUInt32(QuicVersionToQuicTag(supported_versions[i]))) {
    415       return NULL;
    416     }
    417   }
    418 
    419   return new QuicEncryptedPacket(writer.take(), len, true);
    420 }
    421 
    422 bool QuicFramer::ProcessPacket(const QuicEncryptedPacket& packet) {
    423   // TODO(satyamshekhar): Don't RaiseError (and close the connection) for
    424   // invalid (unauthenticated) packets.
    425   DCHECK(!reader_.get());
    426   reader_.reset(new QuicDataReader(packet.data(), packet.length()));
    427 
    428   visitor_->OnPacket();
    429 
    430   // First parse the public header.
    431   QuicPacketPublicHeader public_header;
    432   if (!ProcessPublicHeader(&public_header)) {
    433     DLOG(WARNING) << "Unable to process public header.";
    434     return RaiseError(QUIC_INVALID_PACKET_HEADER);
    435   }
    436 
    437   if (is_server_ && public_header.version_flag &&
    438       public_header.versions[0] != quic_version_) {
    439     if (!visitor_->OnProtocolVersionMismatch(public_header.versions[0])) {
    440       reader_.reset(NULL);
    441       return true;
    442     }
    443   }
    444 
    445   bool rv;
    446   if (!is_server_ && public_header.version_flag) {
    447     rv = ProcessVersionNegotiationPacket(&public_header);
    448   } else if (public_header.reset_flag) {
    449     rv = ProcessPublicResetPacket(public_header);
    450   } else {
    451     rv = ProcessDataPacket(public_header, packet);
    452   }
    453 
    454   reader_.reset(NULL);
    455   return rv;
    456 }
    457 
    458 bool QuicFramer::ProcessVersionNegotiationPacket(
    459     QuicPacketPublicHeader* public_header) {
    460   DCHECK(!is_server_);
    461   // Try reading at least once to raise error if the packet is invalid.
    462   do {
    463     QuicTag version;
    464     if (!reader_->ReadBytes(&version, kQuicVersionSize)) {
    465       set_detailed_error("Unable to read supported version in negotiation.");
    466       return RaiseError(QUIC_INVALID_VERSION_NEGOTIATION_PACKET);
    467     }
    468     public_header->versions.push_back(QuicTagToQuicVersion(version));
    469   } while (!reader_->IsDoneReading());
    470 
    471   visitor_->OnVersionNegotiationPacket(*public_header);
    472   return true;
    473 }
    474 
    475 bool QuicFramer::ProcessDataPacket(
    476     const QuicPacketPublicHeader& public_header,
    477     const QuicEncryptedPacket& packet) {
    478   QuicPacketHeader header(public_header);
    479   if (!ProcessPacketHeader(&header, packet)) {
    480     DCHECK_NE(QUIC_NO_ERROR, error_);  // ProcessPacketHeader sets the error.
    481     DLOG(WARNING) << "Unable to process data packet header.";
    482     return false;
    483   }
    484 
    485   if (!visitor_->OnPacketHeader(header)) {
    486     // The visitor suppresses further processing of the packet.
    487     return true;
    488   }
    489 
    490   if (packet.length() > kMaxPacketSize) {
    491     DLOG(WARNING) << "Packet too large: " << packet.length();
    492     return RaiseError(QUIC_PACKET_TOO_LARGE);
    493   }
    494 
    495   // Handle the payload.
    496   if (!header.fec_flag) {
    497     if (header.is_in_fec_group == IN_FEC_GROUP) {
    498       StringPiece payload = reader_->PeekRemainingPayload();
    499       visitor_->OnFecProtectedPayload(payload);
    500     }
    501     if (!ProcessFrameData()) {
    502       DCHECK_NE(QUIC_NO_ERROR, error_);  // ProcessFrameData sets the error.
    503       DLOG(WARNING) << "Unable to process frame data.";
    504       return false;
    505     }
    506   } else {
    507     QuicFecData fec_data;
    508     fec_data.fec_group = header.fec_group;
    509     fec_data.redundancy = reader_->ReadRemainingPayload();
    510     visitor_->OnFecData(fec_data);
    511   }
    512 
    513   visitor_->OnPacketComplete();
    514   return true;
    515 }
    516 
    517 bool QuicFramer::ProcessPublicResetPacket(
    518     const QuicPacketPublicHeader& public_header) {
    519   QuicPublicResetPacket packet(public_header);
    520   if (!reader_->ReadUInt64(&packet.nonce_proof)) {
    521     set_detailed_error("Unable to read nonce proof.");
    522     return RaiseError(QUIC_INVALID_PUBLIC_RST_PACKET);
    523   }
    524   // TODO(satyamshekhar): validate nonce to protect against DoS.
    525 
    526   if (!reader_->ReadUInt48(&packet.rejected_sequence_number)) {
    527     set_detailed_error("Unable to read rejected sequence number.");
    528     return RaiseError(QUIC_INVALID_PUBLIC_RST_PACKET);
    529   }
    530   visitor_->OnPublicResetPacket(packet);
    531   return true;
    532 }
    533 
    534 bool QuicFramer::ProcessRevivedPacket(QuicPacketHeader* header,
    535                                       StringPiece payload) {
    536   DCHECK(!reader_.get());
    537 
    538   visitor_->OnRevivedPacket();
    539 
    540   header->entropy_hash = GetPacketEntropyHash(*header);
    541 
    542   if (!visitor_->OnPacketHeader(*header)) {
    543     return true;
    544   }
    545 
    546   if (payload.length() > kMaxPacketSize) {
    547     set_detailed_error("Revived packet too large.");
    548     return RaiseError(QUIC_PACKET_TOO_LARGE);
    549   }
    550 
    551   reader_.reset(new QuicDataReader(payload.data(), payload.length()));
    552   if (!ProcessFrameData()) {
    553     DCHECK_NE(QUIC_NO_ERROR, error_);  // ProcessFrameData sets the error.
    554     DLOG(WARNING) << "Unable to process frame data.";
    555     return false;
    556   }
    557 
    558   visitor_->OnPacketComplete();
    559   reader_.reset(NULL);
    560   return true;
    561 }
    562 
    563 bool QuicFramer::WritePacketHeader(const QuicPacketHeader& header,
    564                                    QuicDataWriter* writer) {
    565   DCHECK(header.fec_group > 0 || header.is_in_fec_group == NOT_IN_FEC_GROUP);
    566   uint8 public_flags = 0;
    567   if (header.public_header.reset_flag) {
    568     public_flags |= PACKET_PUBLIC_FLAGS_RST;
    569   }
    570   if (header.public_header.version_flag) {
    571     public_flags |= PACKET_PUBLIC_FLAGS_VERSION;
    572   }
    573   switch (header.public_header.sequence_number_length) {
    574     case PACKET_1BYTE_SEQUENCE_NUMBER:
    575       public_flags |= PACKET_PUBLIC_FLAGS_1BYTE_SEQUENCE;
    576       break;
    577     case PACKET_2BYTE_SEQUENCE_NUMBER:
    578       public_flags |= PACKET_PUBLIC_FLAGS_2BYTE_SEQUENCE;
    579       break;
    580     case PACKET_4BYTE_SEQUENCE_NUMBER:
    581       public_flags |= PACKET_PUBLIC_FLAGS_4BYTE_SEQUENCE;
    582       break;
    583     case PACKET_6BYTE_SEQUENCE_NUMBER:
    584       public_flags |= PACKET_PUBLIC_FLAGS_6BYTE_SEQUENCE;
    585       break;
    586   }
    587 
    588   switch (header.public_header.guid_length) {
    589     case PACKET_0BYTE_GUID:
    590       if (!writer->WriteUInt8(public_flags | PACKET_PUBLIC_FLAGS_0BYTE_GUID)) {
    591         return false;
    592       }
    593       break;
    594     case PACKET_1BYTE_GUID:
    595       if (!writer->WriteUInt8(public_flags | PACKET_PUBLIC_FLAGS_1BYTE_GUID)) {
    596          return false;
    597       }
    598       if (!writer->WriteUInt8(header.public_header.guid & k1ByteGuidMask)) {
    599            return false;
    600       }
    601       break;
    602     case PACKET_4BYTE_GUID:
    603       if (!writer->WriteUInt8(public_flags | PACKET_PUBLIC_FLAGS_4BYTE_GUID)) {
    604          return false;
    605       }
    606       if (!writer->WriteUInt32(header.public_header.guid & k4ByteGuidMask)) {
    607         return false;
    608       }
    609       break;
    610     case PACKET_8BYTE_GUID:
    611       if (!writer->WriteUInt8(public_flags | PACKET_PUBLIC_FLAGS_8BYTE_GUID)) {
    612         return false;
    613       }
    614       if (!writer->WriteUInt64(header.public_header.guid)) {
    615         return false;
    616       }
    617       break;
    618   }
    619   last_serialized_guid_ = header.public_header.guid;
    620 
    621   if (header.public_header.version_flag) {
    622     DCHECK(!is_server_);
    623     writer->WriteUInt32(QuicVersionToQuicTag(quic_version_));
    624   }
    625 
    626   if (!AppendPacketSequenceNumber(header.public_header.sequence_number_length,
    627                                   header.packet_sequence_number, writer)) {
    628     return false;
    629   }
    630 
    631   uint8 private_flags = 0;
    632   if (header.entropy_flag) {
    633     private_flags |= PACKET_PRIVATE_FLAGS_ENTROPY;
    634   }
    635   if (header.is_in_fec_group == IN_FEC_GROUP) {
    636     private_flags |= PACKET_PRIVATE_FLAGS_FEC_GROUP;
    637   }
    638   if (header.fec_flag) {
    639     private_flags |= PACKET_PRIVATE_FLAGS_FEC;
    640   }
    641   if (!writer->WriteUInt8(private_flags)) {
    642     return false;
    643   }
    644 
    645   // The FEC group number is the sequence number of the first fec
    646   // protected packet, or 0 if this packet is not protected.
    647   if (header.is_in_fec_group == IN_FEC_GROUP) {
    648     DCHECK_GE(header.packet_sequence_number, header.fec_group);
    649     DCHECK_GT(255u, header.packet_sequence_number - header.fec_group);
    650     // Offset from the current packet sequence number to the first fec
    651     // protected packet.
    652     uint8 first_fec_protected_packet_offset =
    653         header.packet_sequence_number - header.fec_group;
    654     if (!writer->WriteBytes(&first_fec_protected_packet_offset, 1)) {
    655       return false;
    656     }
    657   }
    658 
    659   return true;
    660 }
    661 
    662 QuicPacketSequenceNumber QuicFramer::CalculatePacketSequenceNumberFromWire(
    663     QuicSequenceNumberLength sequence_number_length,
    664     QuicPacketSequenceNumber packet_sequence_number) const {
    665   // The new sequence number might have wrapped to the next epoch, or
    666   // it might have reverse wrapped to the previous epoch, or it might
    667   // remain in the same epoch.  Select the sequence number closest to the
    668   // next expected sequence number, the previous sequence number plus 1.
    669 
    670   // epoch_delta is the delta between epochs the sequence number was serialized
    671   // with, so the correct value is likely the same epoch as the last sequence
    672   // number or an adjacent epoch.
    673   const QuicPacketSequenceNumber epoch_delta =
    674       GG_UINT64_C(1) << (8 * sequence_number_length);
    675   QuicPacketSequenceNumber next_sequence_number = last_sequence_number_ + 1;
    676   QuicPacketSequenceNumber epoch = last_sequence_number_ & ~(epoch_delta - 1);
    677   QuicPacketSequenceNumber prev_epoch = epoch - epoch_delta;
    678   QuicPacketSequenceNumber next_epoch = epoch + epoch_delta;
    679 
    680   return ClosestTo(next_sequence_number,
    681                    epoch + packet_sequence_number,
    682                    ClosestTo(next_sequence_number,
    683                              prev_epoch + packet_sequence_number,
    684                              next_epoch + packet_sequence_number));
    685 }
    686 
    687 bool QuicFramer::ProcessPublicHeader(
    688     QuicPacketPublicHeader* public_header) {
    689   uint8 public_flags;
    690   if (!reader_->ReadBytes(&public_flags, 1)) {
    691     set_detailed_error("Unable to read public flags.");
    692     return false;
    693   }
    694 
    695   public_header->reset_flag = (public_flags & PACKET_PUBLIC_FLAGS_RST) != 0;
    696   public_header->version_flag =
    697       (public_flags & PACKET_PUBLIC_FLAGS_VERSION) != 0;
    698 
    699   if (!public_header->version_flag && public_flags > PACKET_PUBLIC_FLAGS_MAX) {
    700     set_detailed_error("Illegal public flags value.");
    701     return false;
    702   }
    703 
    704   if (public_header->reset_flag && public_header->version_flag) {
    705     set_detailed_error("Got version flag in reset packet");
    706     return false;
    707   }
    708 
    709   switch (public_flags & PACKET_PUBLIC_FLAGS_8BYTE_GUID) {
    710     case PACKET_PUBLIC_FLAGS_8BYTE_GUID:
    711       if (!reader_->ReadUInt64(&public_header->guid)) {
    712         set_detailed_error("Unable to read GUID.");
    713         return false;
    714       }
    715       public_header->guid_length = PACKET_8BYTE_GUID;
    716       break;
    717     case PACKET_PUBLIC_FLAGS_4BYTE_GUID:
    718       // If the guid is truncated, expect to read the last serialized guid.
    719       if (!reader_->ReadBytes(&public_header->guid, PACKET_4BYTE_GUID)) {
    720         set_detailed_error("Unable to read GUID.");
    721         return false;
    722       }
    723       if ((public_header->guid & k4ByteGuidMask) !=
    724           (last_serialized_guid_ & k4ByteGuidMask)) {
    725         set_detailed_error(
    726             "Truncated 4 byte GUID does not match previous guid.");
    727         return false;
    728       }
    729       public_header->guid_length = PACKET_4BYTE_GUID;
    730       public_header->guid = last_serialized_guid_;
    731       break;
    732     case PACKET_PUBLIC_FLAGS_1BYTE_GUID:
    733       if (!reader_->ReadBytes(&public_header->guid, PACKET_1BYTE_GUID)) {
    734         set_detailed_error("Unable to read GUID.");
    735         return false;
    736       }
    737       if ((public_header->guid & k1ByteGuidMask) !=
    738           (last_serialized_guid_ & k1ByteGuidMask)) {
    739         set_detailed_error(
    740             "Truncated 1 byte GUID does not match previous guid.");
    741         return false;
    742       }
    743       public_header->guid_length = PACKET_1BYTE_GUID;
    744       public_header->guid = last_serialized_guid_;
    745       break;
    746     case PACKET_PUBLIC_FLAGS_0BYTE_GUID:
    747       public_header->guid_length = PACKET_0BYTE_GUID;
    748       public_header->guid = last_serialized_guid_;
    749       break;
    750   }
    751 
    752   switch (public_flags & PACKET_PUBLIC_FLAGS_6BYTE_SEQUENCE) {
    753     case PACKET_PUBLIC_FLAGS_6BYTE_SEQUENCE:
    754       public_header->sequence_number_length = PACKET_6BYTE_SEQUENCE_NUMBER;
    755       break;
    756     case PACKET_PUBLIC_FLAGS_4BYTE_SEQUENCE:
    757       public_header->sequence_number_length = PACKET_4BYTE_SEQUENCE_NUMBER;
    758       break;
    759     case PACKET_PUBLIC_FLAGS_2BYTE_SEQUENCE:
    760       public_header->sequence_number_length = PACKET_2BYTE_SEQUENCE_NUMBER;
    761       break;
    762     case PACKET_PUBLIC_FLAGS_1BYTE_SEQUENCE:
    763       public_header->sequence_number_length = PACKET_1BYTE_SEQUENCE_NUMBER;
    764       break;
    765   }
    766 
    767   // Read the version only if the packet is from the client.
    768   // version flag from the server means version negotiation packet.
    769   if (public_header->version_flag && is_server_) {
    770     QuicTag version_tag;
    771     if (!reader_->ReadUInt32(&version_tag)) {
    772       set_detailed_error("Unable to read protocol version.");
    773       return false;
    774     }
    775 
    776     // If the version from the new packet is the same as the version of this
    777     // framer, then the public flags should be set to something we understand.
    778     // If not, this raises an error.
    779     QuicVersion version = QuicTagToQuicVersion(version_tag);
    780     if (version == quic_version_ && public_flags > PACKET_PUBLIC_FLAGS_MAX) {
    781       set_detailed_error("Illegal public flags value.");
    782       return false;
    783     }
    784     public_header->versions.push_back(version);
    785   }
    786   return true;
    787 }
    788 
    789 // static
    790 bool QuicFramer::ReadGuidFromPacket(const QuicEncryptedPacket& packet,
    791                                     QuicGuid* guid) {
    792   QuicDataReader reader(packet.data(), packet.length());
    793   uint8 public_flags;
    794   if (!reader.ReadBytes(&public_flags, 1)) {
    795     return false;
    796   }
    797   // Ensure it's an 8 byte guid.
    798   if ((public_flags & PACKET_PUBLIC_FLAGS_8BYTE_GUID) !=
    799           PACKET_PUBLIC_FLAGS_8BYTE_GUID) {
    800     return false;
    801   }
    802 
    803   return reader.ReadUInt64(guid);
    804 }
    805 
    806 bool QuicFramer::ProcessPacketHeader(
    807     QuicPacketHeader* header,
    808     const QuicEncryptedPacket& packet) {
    809   if (!ProcessPacketSequenceNumber(header->public_header.sequence_number_length,
    810                                    &header->packet_sequence_number)) {
    811     set_detailed_error("Unable to read sequence number.");
    812     return RaiseError(QUIC_INVALID_PACKET_HEADER);
    813   }
    814 
    815   if (header->packet_sequence_number == 0u) {
    816     set_detailed_error("Packet sequence numbers cannot be 0.");
    817     return RaiseError(QUIC_INVALID_PACKET_HEADER);
    818   }
    819 
    820   if (!DecryptPayload(*header, packet)) {
    821     set_detailed_error("Unable to decrypt payload.");
    822     return RaiseError(QUIC_DECRYPTION_FAILURE);
    823   }
    824 
    825   uint8 private_flags;
    826   if (!reader_->ReadBytes(&private_flags, 1)) {
    827     set_detailed_error("Unable to read private flags.");
    828     return RaiseError(QUIC_INVALID_PACKET_HEADER);
    829   }
    830 
    831   if (private_flags > PACKET_PRIVATE_FLAGS_MAX) {
    832     set_detailed_error("Illegal private flags value.");
    833     return RaiseError(QUIC_INVALID_PACKET_HEADER);
    834   }
    835 
    836   header->entropy_flag = (private_flags & PACKET_PRIVATE_FLAGS_ENTROPY) != 0;
    837   header->fec_flag = (private_flags & PACKET_PRIVATE_FLAGS_FEC) != 0;
    838 
    839   if ((private_flags & PACKET_PRIVATE_FLAGS_FEC_GROUP) != 0) {
    840     header->is_in_fec_group = IN_FEC_GROUP;
    841     uint8 first_fec_protected_packet_offset;
    842     if (!reader_->ReadBytes(&first_fec_protected_packet_offset, 1)) {
    843       set_detailed_error("Unable to read first fec protected packet offset.");
    844       return RaiseError(QUIC_INVALID_PACKET_HEADER);
    845     }
    846     if (first_fec_protected_packet_offset >= header->packet_sequence_number) {
    847       set_detailed_error("First fec protected packet offset must be less "
    848                          "than the sequence number.");
    849       return RaiseError(QUIC_INVALID_PACKET_HEADER);
    850     }
    851     header->fec_group =
    852         header->packet_sequence_number - first_fec_protected_packet_offset;
    853   }
    854 
    855   header->entropy_hash = GetPacketEntropyHash(*header);
    856   // Set the last sequence number after we have decrypted the packet
    857   // so we are confident is not attacker controlled.
    858   last_sequence_number_ = header->packet_sequence_number;
    859   return true;
    860 }
    861 
    862 bool QuicFramer::ProcessPacketSequenceNumber(
    863     QuicSequenceNumberLength sequence_number_length,
    864     QuicPacketSequenceNumber* sequence_number) {
    865   QuicPacketSequenceNumber wire_sequence_number = 0u;
    866   if (!reader_->ReadBytes(&wire_sequence_number, sequence_number_length)) {
    867     return false;
    868   }
    869 
    870   // TODO(ianswett): Explore the usefulness of trying multiple sequence numbers
    871   // in case the first guess is incorrect.
    872   *sequence_number =
    873       CalculatePacketSequenceNumberFromWire(sequence_number_length,
    874                                             wire_sequence_number);
    875   return true;
    876 }
    877 
    878 bool QuicFramer::ProcessFrameData() {
    879   if (reader_->IsDoneReading()) {
    880     set_detailed_error("Unable to read frame type.");
    881     return RaiseError(QUIC_INVALID_FRAME_DATA);
    882   }
    883   while (!reader_->IsDoneReading()) {
    884     uint8 frame_type;
    885     if (!reader_->ReadBytes(&frame_type, 1)) {
    886       set_detailed_error("Unable to read frame type.");
    887       return RaiseError(QUIC_INVALID_FRAME_DATA);
    888     }
    889 
    890     if ((frame_type & kQuicFrameType0BitMask) == 0) {
    891       QuicStreamFrame frame;
    892       if (!ProcessStreamFrame(frame_type, &frame)) {
    893         return RaiseError(QUIC_INVALID_FRAME_DATA);
    894       }
    895       if (!visitor_->OnStreamFrame(frame)) {
    896         DLOG(INFO) << "Visitor asked to stop further processing.";
    897         // Returning true since there was no parsing error.
    898         return true;
    899       }
    900       continue;
    901     }
    902 
    903     frame_type >>= 1;
    904     if ((frame_type & kQuicFrameType0BitMask) == 0) {
    905       QuicAckFrame frame;
    906       if (!ProcessAckFrame(&frame)) {
    907         return RaiseError(QUIC_INVALID_FRAME_DATA);
    908       }
    909       if (!visitor_->OnAckFrame(frame)) {
    910         DLOG(INFO) << "Visitor asked to stop further processing.";
    911         // Returning true since there was no parsing error.
    912         return true;
    913       }
    914       continue;
    915     }
    916 
    917     frame_type >>= 1;
    918     if ((frame_type & kQuicFrameType0BitMask) == 0) {
    919       QuicCongestionFeedbackFrame frame;
    920       if (!ProcessQuicCongestionFeedbackFrame(&frame)) {
    921         return RaiseError(QUIC_INVALID_FRAME_DATA);
    922       }
    923       if (!visitor_->OnCongestionFeedbackFrame(frame)) {
    924         DLOG(INFO) << "Visitor asked to stop further processing.";
    925         // Returning true since there was no parsing error.
    926         return true;
    927       }
    928       continue;
    929     }
    930 
    931     frame_type >>= 1;
    932 
    933     switch (frame_type) {
    934       // STREAM_FRAME, ACK_FRAME, and CONGESTION_FEEDBACK_FRAME are handled
    935       // above.
    936       case PADDING_FRAME:
    937         // We're done with the packet
    938         return true;
    939 
    940       case RST_STREAM_FRAME: {
    941         QuicRstStreamFrame frame;
    942         if (!ProcessRstStreamFrame(&frame)) {
    943           return RaiseError(QUIC_INVALID_RST_STREAM_DATA);
    944         }
    945         if (!visitor_->OnRstStreamFrame(frame)) {
    946           DLOG(INFO) << "Visitor asked to stop further processing.";
    947           // Returning true since there was no parsing error.
    948           return true;
    949         }
    950         continue;
    951       }
    952 
    953       case CONNECTION_CLOSE_FRAME: {
    954         QuicConnectionCloseFrame frame;
    955         if (!ProcessConnectionCloseFrame(&frame)) {
    956           return RaiseError(QUIC_INVALID_CONNECTION_CLOSE_DATA);
    957         }
    958 
    959         if (!visitor_->OnAckFrame(frame.ack_frame)) {
    960           DLOG(INFO) << "Visitor asked to stop further processing.";
    961           // Returning true since there was no parsing error.
    962           return true;
    963         }
    964 
    965         if (!visitor_->OnConnectionCloseFrame(frame)) {
    966           DLOG(INFO) << "Visitor asked to stop further processing.";
    967           // Returning true since there was no parsing error.
    968           return true;
    969         }
    970         continue;
    971       }
    972 
    973       case GOAWAY_FRAME: {
    974         QuicGoAwayFrame goaway_frame;
    975         if (!ProcessGoAwayFrame(&goaway_frame)) {
    976           return RaiseError(QUIC_INVALID_GOAWAY_DATA);
    977         }
    978         if (!visitor_->OnGoAwayFrame(goaway_frame)) {
    979           DLOG(INFO) << "Visitor asked to stop further processing.";
    980           // Returning true since there was no parsing error.
    981           return true;
    982         }
    983         continue;
    984       }
    985 
    986       set_detailed_error("Illegal frame type.");
    987       DLOG(WARNING) << "Illegal frame type: "
    988                     << static_cast<int>(frame_type);
    989       return RaiseError(QUIC_INVALID_FRAME_DATA);
    990     }
    991   }
    992 
    993   return true;
    994 }
    995 
    996 bool QuicFramer::ProcessStreamFrame(uint8 frame_type,
    997                                     QuicStreamFrame* frame) {
    998   uint8 stream_flags = frame_type >> 1;
    999   // Read from right to left: StreamID, Offset, Data Length, Fin.
   1000   const uint8 stream_id_length = (stream_flags & kQuicStreamIDLengthMask) + 1;
   1001   stream_flags >>= kQuicStreamIdShift;
   1002 
   1003   uint8 offset_length = (stream_flags & kQuicStreamOffsetMask);
   1004   // There is no encoding for 1 byte, only 0 and 2 through 8.
   1005   if (offset_length > 0) {
   1006     offset_length += 1;
   1007   }
   1008   stream_flags >>= kQuicStreamOffsetShift;
   1009 
   1010   bool has_data_length =
   1011       (stream_flags & kQuicStreamDataLengthMask) == kQuicStreamDataLengthMask;
   1012   stream_flags >>= kQuicStreamDataLengthShift;
   1013 
   1014   frame->fin = (stream_flags & kQuicStreamFinMask) == kQuicStreamFinShift;
   1015 
   1016   frame->stream_id = 0;
   1017   if (!reader_->ReadBytes(&frame->stream_id, stream_id_length)) {
   1018     set_detailed_error("Unable to read stream_id.");
   1019     return false;
   1020   }
   1021 
   1022   frame->offset = 0;
   1023   if (!reader_->ReadBytes(&frame->offset, offset_length)) {
   1024     set_detailed_error("Unable to read offset.");
   1025     return false;
   1026   }
   1027 
   1028   if (has_data_length) {
   1029     if (!reader_->ReadStringPiece16(&frame->data)) {
   1030       set_detailed_error("Unable to read frame data.");
   1031       return false;
   1032     }
   1033   } else {
   1034     if (!reader_->ReadStringPiece(&frame->data, reader_->BytesRemaining())) {
   1035       set_detailed_error("Unable to read frame data.");
   1036       return false;
   1037     }
   1038   }
   1039 
   1040   return true;
   1041 }
   1042 
   1043 bool QuicFramer::ProcessAckFrame(QuicAckFrame* frame) {
   1044   if (!ProcessSentInfo(&frame->sent_info)) {
   1045     return false;
   1046   }
   1047   if (!ProcessReceivedInfo(&frame->received_info)) {
   1048     return false;
   1049   }
   1050   return true;
   1051 }
   1052 
   1053 bool QuicFramer::ProcessReceivedInfo(ReceivedPacketInfo* received_info) {
   1054   if (!reader_->ReadBytes(&received_info->entropy_hash, 1)) {
   1055     set_detailed_error("Unable to read entropy hash for received packets.");
   1056     return false;
   1057   }
   1058 
   1059   if (!ProcessPacketSequenceNumber(PACKET_6BYTE_SEQUENCE_NUMBER,
   1060                                    &received_info->largest_observed)) {
   1061      set_detailed_error("Unable to read largest observed.");
   1062      return false;
   1063   }
   1064 
   1065   uint32 delta_time_largest_observed_us;
   1066   if (!reader_->ReadUInt32(&delta_time_largest_observed_us)) {
   1067     set_detailed_error("Unable to read delta time largest observed.");
   1068     return false;
   1069   }
   1070 
   1071   if (delta_time_largest_observed_us == kInvalidDeltaTime) {
   1072     received_info->delta_time_largest_observed = QuicTime::Delta::Infinite();
   1073   } else {
   1074     received_info->delta_time_largest_observed =
   1075         QuicTime::Delta::FromMicroseconds(delta_time_largest_observed_us);
   1076   }
   1077 
   1078   uint8 num_missing_packets;
   1079   if (!reader_->ReadBytes(&num_missing_packets, 1)) {
   1080     set_detailed_error("Unable to read num missing packets.");
   1081     return false;
   1082   }
   1083 
   1084   for (int i = 0; i < num_missing_packets; ++i) {
   1085     QuicPacketSequenceNumber sequence_number;
   1086     if (!ProcessPacketSequenceNumber(PACKET_6BYTE_SEQUENCE_NUMBER,
   1087                                      &sequence_number)) {
   1088       set_detailed_error("Unable to read sequence number in missing packets.");
   1089       return false;
   1090     }
   1091     received_info->missing_packets.insert(sequence_number);
   1092   }
   1093 
   1094   return true;
   1095 }
   1096 
   1097 bool QuicFramer::ProcessSentInfo(SentPacketInfo* sent_info) {
   1098   if (!reader_->ReadBytes(&sent_info->entropy_hash, 1)) {
   1099     set_detailed_error("Unable to read entropy hash for sent packets.");
   1100     return false;
   1101   }
   1102 
   1103   if (!ProcessPacketSequenceNumber(PACKET_6BYTE_SEQUENCE_NUMBER,
   1104                                    &sent_info->least_unacked)) {
   1105     set_detailed_error("Unable to read least unacked.");
   1106     return false;
   1107   }
   1108 
   1109   return true;
   1110 }
   1111 
   1112 bool QuicFramer::ProcessQuicCongestionFeedbackFrame(
   1113     QuicCongestionFeedbackFrame* frame) {
   1114   uint8 feedback_type;
   1115   if (!reader_->ReadBytes(&feedback_type, 1)) {
   1116     set_detailed_error("Unable to read congestion feedback type.");
   1117     return false;
   1118   }
   1119   frame->type =
   1120       static_cast<CongestionFeedbackType>(feedback_type);
   1121 
   1122   switch (frame->type) {
   1123     case kInterArrival: {
   1124       CongestionFeedbackMessageInterArrival* inter_arrival =
   1125           &frame->inter_arrival;
   1126       if (!reader_->ReadUInt16(
   1127               &inter_arrival->accumulated_number_of_lost_packets)) {
   1128         set_detailed_error(
   1129             "Unable to read accumulated number of lost packets.");
   1130         return false;
   1131       }
   1132       uint8 num_received_packets;
   1133       if (!reader_->ReadBytes(&num_received_packets, 1)) {
   1134         set_detailed_error("Unable to read num received packets.");
   1135         return false;
   1136       }
   1137 
   1138       if (num_received_packets > 0u) {
   1139         uint64 smallest_received;
   1140         if (!ProcessPacketSequenceNumber(PACKET_6BYTE_SEQUENCE_NUMBER,
   1141                                          &smallest_received)) {
   1142           set_detailed_error("Unable to read smallest received.");
   1143           return false;
   1144         }
   1145 
   1146         uint64 time_received_us;
   1147         if (!reader_->ReadUInt64(&time_received_us)) {
   1148           set_detailed_error("Unable to read time received.");
   1149           return false;
   1150         }
   1151         QuicTime time_received = creation_time_.Add(
   1152             QuicTime::Delta::FromMicroseconds(time_received_us));
   1153 
   1154         inter_arrival->received_packet_times.insert(
   1155             make_pair(smallest_received, time_received));
   1156 
   1157         for (int i = 0; i < num_received_packets - 1; ++i) {
   1158           uint16 sequence_delta;
   1159           if (!reader_->ReadUInt16(&sequence_delta)) {
   1160             set_detailed_error(
   1161                 "Unable to read sequence delta in received packets.");
   1162             return false;
   1163           }
   1164 
   1165           int32 time_delta_us;
   1166           if (!reader_->ReadBytes(&time_delta_us, sizeof(time_delta_us))) {
   1167             set_detailed_error(
   1168                 "Unable to read time delta in received packets.");
   1169             return false;
   1170           }
   1171           QuicPacketSequenceNumber packet = smallest_received + sequence_delta;
   1172           inter_arrival->received_packet_times.insert(
   1173               make_pair(packet, time_received.Add(
   1174                   QuicTime::Delta::FromMicroseconds(time_delta_us))));
   1175         }
   1176       }
   1177       break;
   1178     }
   1179     case kFixRate: {
   1180       uint32 bitrate = 0;
   1181       if (!reader_->ReadUInt32(&bitrate)) {
   1182         set_detailed_error("Unable to read bitrate.");
   1183         return false;
   1184       }
   1185       frame->fix_rate.bitrate = QuicBandwidth::FromBytesPerSecond(bitrate);
   1186       break;
   1187     }
   1188     case kTCP: {
   1189       CongestionFeedbackMessageTCP* tcp = &frame->tcp;
   1190       if (!reader_->ReadUInt16(&tcp->accumulated_number_of_lost_packets)) {
   1191         set_detailed_error(
   1192             "Unable to read accumulated number of lost packets.");
   1193         return false;
   1194       }
   1195       uint16 receive_window = 0;
   1196       if (!reader_->ReadUInt16(&receive_window)) {
   1197         set_detailed_error("Unable to read receive window.");
   1198         return false;
   1199       }
   1200       // Simple bit packing, don't send the 4 least significant bits.
   1201       tcp->receive_window = static_cast<QuicByteCount>(receive_window) << 4;
   1202       break;
   1203     }
   1204     default:
   1205       set_detailed_error("Illegal congestion feedback type.");
   1206       DLOG(WARNING) << "Illegal congestion feedback type: "
   1207                     << frame->type;
   1208       return RaiseError(QUIC_INVALID_FRAME_DATA);
   1209   }
   1210 
   1211   return true;
   1212 }
   1213 
   1214 bool QuicFramer::ProcessRstStreamFrame(QuicRstStreamFrame* frame) {
   1215   if (!reader_->ReadUInt32(&frame->stream_id)) {
   1216     set_detailed_error("Unable to read stream_id.");
   1217     return false;
   1218   }
   1219 
   1220   uint32 error_code;
   1221   if (!reader_->ReadUInt32(&error_code)) {
   1222     set_detailed_error("Unable to read rst stream error code.");
   1223     return false;
   1224   }
   1225 
   1226   if (error_code >= QUIC_STREAM_LAST_ERROR ||
   1227       error_code < QUIC_STREAM_NO_ERROR) {
   1228     set_detailed_error("Invalid rst stream error code.");
   1229     return false;
   1230   }
   1231 
   1232   frame->error_code = static_cast<QuicRstStreamErrorCode>(error_code);
   1233 
   1234   StringPiece error_details;
   1235   if (!reader_->ReadStringPiece16(&error_details)) {
   1236     set_detailed_error("Unable to read rst stream error details.");
   1237     return false;
   1238   }
   1239   frame->error_details = error_details.as_string();
   1240 
   1241   return true;
   1242 }
   1243 
   1244 bool QuicFramer::ProcessConnectionCloseFrame(QuicConnectionCloseFrame* frame) {
   1245   uint32 error_code;
   1246   if (!reader_->ReadUInt32(&error_code)) {
   1247     set_detailed_error("Unable to read connection close error code.");
   1248     return false;
   1249   }
   1250 
   1251   if (error_code >= QUIC_LAST_ERROR ||
   1252          error_code < QUIC_NO_ERROR) {
   1253     set_detailed_error("Invalid error code.");
   1254     return false;
   1255   }
   1256 
   1257   frame->error_code = static_cast<QuicErrorCode>(error_code);
   1258 
   1259   StringPiece error_details;
   1260   if (!reader_->ReadStringPiece16(&error_details)) {
   1261     set_detailed_error("Unable to read connection close error details.");
   1262     return false;
   1263   }
   1264   frame->error_details = error_details.as_string();
   1265 
   1266   if (!ProcessAckFrame(&frame->ack_frame)) {
   1267     DLOG(WARNING) << "Unable to process ack frame.";
   1268     return false;
   1269   }
   1270 
   1271   return true;
   1272 }
   1273 
   1274 bool QuicFramer::ProcessGoAwayFrame(QuicGoAwayFrame* frame) {
   1275   uint32 error_code;
   1276   if (!reader_->ReadUInt32(&error_code)) {
   1277     set_detailed_error("Unable to read go away error code.");
   1278     return false;
   1279   }
   1280   frame->error_code = static_cast<QuicErrorCode>(error_code);
   1281 
   1282   if (error_code >= QUIC_LAST_ERROR ||
   1283       error_code < QUIC_NO_ERROR) {
   1284     set_detailed_error("Invalid error code.");
   1285     return false;
   1286   }
   1287 
   1288   uint32 stream_id;
   1289   if (!reader_->ReadUInt32(&stream_id)) {
   1290     set_detailed_error("Unable to read last good stream id.");
   1291     return false;
   1292   }
   1293   frame->last_good_stream_id = static_cast<QuicStreamId>(stream_id);
   1294 
   1295   StringPiece reason_phrase;
   1296   if (!reader_->ReadStringPiece16(&reason_phrase)) {
   1297     set_detailed_error("Unable to read goaway reason.");
   1298     return false;
   1299   }
   1300   frame->reason_phrase = reason_phrase.as_string();
   1301 
   1302   return true;
   1303 }
   1304 
   1305 // static
   1306 StringPiece QuicFramer::GetAssociatedDataFromEncryptedPacket(
   1307     const QuicEncryptedPacket& encrypted,
   1308     QuicGuidLength guid_length,
   1309     bool includes_version,
   1310     QuicSequenceNumberLength sequence_number_length) {
   1311   return StringPiece(encrypted.data() + kStartOfHashData,
   1312                      GetStartOfEncryptedData(
   1313                          guid_length, includes_version, sequence_number_length)
   1314                      - kStartOfHashData);
   1315 }
   1316 
   1317 void QuicFramer::SetDecrypter(QuicDecrypter* decrypter) {
   1318   DCHECK(alternative_decrypter_.get() == NULL);
   1319   decrypter_.reset(decrypter);
   1320 }
   1321 
   1322 void QuicFramer::SetAlternativeDecrypter(QuicDecrypter* decrypter,
   1323                                          bool latch_once_used) {
   1324   alternative_decrypter_.reset(decrypter);
   1325   alternative_decrypter_latch_ = latch_once_used;
   1326 }
   1327 
   1328 const QuicDecrypter* QuicFramer::decrypter() const {
   1329   return decrypter_.get();
   1330 }
   1331 
   1332 const QuicDecrypter* QuicFramer::alternative_decrypter() const {
   1333   return alternative_decrypter_.get();
   1334 }
   1335 
   1336 void QuicFramer::SetEncrypter(EncryptionLevel level,
   1337                               QuicEncrypter* encrypter) {
   1338   DCHECK_GE(level, 0);
   1339   DCHECK_LT(level, NUM_ENCRYPTION_LEVELS);
   1340   encrypter_[level].reset(encrypter);
   1341 }
   1342 
   1343 const QuicEncrypter* QuicFramer::encrypter(EncryptionLevel level) const {
   1344   DCHECK_GE(level, 0);
   1345   DCHECK_LT(level, NUM_ENCRYPTION_LEVELS);
   1346   DCHECK(encrypter_[level].get() != NULL);
   1347   return encrypter_[level].get();
   1348 }
   1349 
   1350 void QuicFramer::SwapCryptersForTest(QuicFramer* other) {
   1351   for (int i = ENCRYPTION_NONE; i < NUM_ENCRYPTION_LEVELS; i++) {
   1352     encrypter_[i].swap(other->encrypter_[i]);
   1353   }
   1354   decrypter_.swap(other->decrypter_);
   1355   alternative_decrypter_.swap(other->alternative_decrypter_);
   1356 
   1357   const bool other_latch = other->alternative_decrypter_latch_;
   1358   other->alternative_decrypter_latch_ = alternative_decrypter_latch_;
   1359   alternative_decrypter_latch_ = other_latch;
   1360 }
   1361 
   1362 QuicEncryptedPacket* QuicFramer::EncryptPacket(
   1363     EncryptionLevel level,
   1364     QuicPacketSequenceNumber packet_sequence_number,
   1365     const QuicPacket& packet) {
   1366   DCHECK(encrypter_[level].get() != NULL);
   1367 
   1368   scoped_ptr<QuicData> out(encrypter_[level]->EncryptPacket(
   1369       packet_sequence_number, packet.AssociatedData(), packet.Plaintext()));
   1370   if (out.get() == NULL) {
   1371     RaiseError(QUIC_ENCRYPTION_FAILURE);
   1372     return NULL;
   1373   }
   1374   StringPiece header_data = packet.BeforePlaintext();
   1375   size_t len =  header_data.length() + out->length();
   1376   char* buffer = new char[len];
   1377   // TODO(rch): eliminate this buffer copy by passing in a buffer to Encrypt().
   1378   memcpy(buffer, header_data.data(), header_data.length());
   1379   memcpy(buffer + header_data.length(), out->data(), out->length());
   1380   return new QuicEncryptedPacket(buffer, len, true);
   1381 }
   1382 
   1383 size_t QuicFramer::GetMaxPlaintextSize(size_t ciphertext_size) {
   1384   // In order to keep the code simple, we don't have the current encryption
   1385   // level to hand. At the moment, the NullEncrypter has a tag length of 16
   1386   // bytes and AES-GCM has a tag length of 12. We take the minimum plaintext
   1387   // length just to be safe.
   1388   size_t min_plaintext_size = ciphertext_size;
   1389 
   1390   for (int i = ENCRYPTION_NONE; i < NUM_ENCRYPTION_LEVELS; i++) {
   1391     if (encrypter_[i].get() != NULL) {
   1392       size_t size = encrypter_[i]->GetMaxPlaintextSize(ciphertext_size);
   1393       if (size < min_plaintext_size) {
   1394         min_plaintext_size = size;
   1395       }
   1396     }
   1397   }
   1398 
   1399   return min_plaintext_size;
   1400 }
   1401 
   1402 bool QuicFramer::DecryptPayload(const QuicPacketHeader& header,
   1403                                 const QuicEncryptedPacket& packet) {
   1404   StringPiece encrypted;
   1405   if (!reader_->ReadStringPiece(&encrypted, reader_->BytesRemaining())) {
   1406     return false;
   1407   }
   1408   DCHECK(decrypter_.get() != NULL);
   1409   decrypted_.reset(decrypter_->DecryptPacket(
   1410       header.packet_sequence_number,
   1411       GetAssociatedDataFromEncryptedPacket(
   1412           packet,
   1413           header.public_header.guid_length,
   1414           header.public_header.version_flag,
   1415           header.public_header.sequence_number_length),
   1416       encrypted));
   1417   if  (decrypted_.get() == NULL && alternative_decrypter_.get() != NULL) {
   1418     decrypted_.reset(alternative_decrypter_->DecryptPacket(
   1419         header.packet_sequence_number,
   1420         GetAssociatedDataFromEncryptedPacket(
   1421             packet,
   1422             header.public_header.guid_length,
   1423             header.public_header.version_flag,
   1424             header.public_header.sequence_number_length),
   1425         encrypted));
   1426     if (decrypted_.get() != NULL) {
   1427       if (alternative_decrypter_latch_) {
   1428         // Switch to the alternative decrypter and latch so that we cannot
   1429         // switch back.
   1430         decrypter_.reset(alternative_decrypter_.release());
   1431       } else {
   1432         // Switch the alternative decrypter so that we use it first next time.
   1433         decrypter_.swap(alternative_decrypter_);
   1434       }
   1435     }
   1436   }
   1437 
   1438   if  (decrypted_.get() == NULL) {
   1439     return false;
   1440   }
   1441 
   1442   reader_.reset(new QuicDataReader(decrypted_->data(), decrypted_->length()));
   1443   return true;
   1444 }
   1445 
   1446 size_t QuicFramer::ComputeFrameLength(const QuicFrame& frame,
   1447                                       bool last_frame_in_packet) {
   1448   switch (frame.type) {
   1449     case STREAM_FRAME:
   1450       return GetMinStreamFrameSize(quic_version_,
   1451                                    frame.stream_frame->stream_id,
   1452                                    frame.stream_frame->offset,
   1453                                    last_frame_in_packet) +
   1454           frame.stream_frame->data.size();
   1455     case ACK_FRAME: {
   1456       const QuicAckFrame& ack = *frame.ack_frame;
   1457       return GetMinAckFrameSize() + PACKET_6BYTE_SEQUENCE_NUMBER *
   1458           ack.received_info.missing_packets.size();
   1459     }
   1460     case CONGESTION_FEEDBACK_FRAME: {
   1461       size_t len = kQuicFrameTypeSize;
   1462       const QuicCongestionFeedbackFrame& congestion_feedback =
   1463           *frame.congestion_feedback_frame;
   1464       len += 1;  // Congestion feedback type.
   1465 
   1466       switch (congestion_feedback.type) {
   1467         case kInterArrival: {
   1468           const CongestionFeedbackMessageInterArrival& inter_arrival =
   1469               congestion_feedback.inter_arrival;
   1470           len += 2;
   1471           len += 1;  // Number received packets.
   1472           if (inter_arrival.received_packet_times.size() > 0) {
   1473             len += PACKET_6BYTE_SEQUENCE_NUMBER;  // Smallest received.
   1474             len += 8;  // Time.
   1475             // 2 bytes per sequence number delta plus 4 bytes per delta time.
   1476             len += PACKET_6BYTE_SEQUENCE_NUMBER *
   1477                 (inter_arrival.received_packet_times.size() - 1);
   1478           }
   1479           break;
   1480         }
   1481         case kFixRate:
   1482           len += 4;
   1483           break;
   1484         case kTCP:
   1485           len += 4;
   1486           break;
   1487         default:
   1488           set_detailed_error("Illegal feedback type.");
   1489           DLOG(INFO) << "Illegal feedback type: " << congestion_feedback.type;
   1490           break;
   1491       }
   1492       return len;
   1493     }
   1494     case RST_STREAM_FRAME:
   1495       return GetMinRstStreamFrameSize() +
   1496           frame.rst_stream_frame->error_details.size();
   1497     case CONNECTION_CLOSE_FRAME: {
   1498       const QuicAckFrame& ack = frame.connection_close_frame->ack_frame;
   1499       return GetMinConnectionCloseFrameSize() +
   1500           frame.connection_close_frame->error_details.size() +
   1501           PACKET_6BYTE_SEQUENCE_NUMBER *
   1502           ack.received_info.missing_packets.size();
   1503     }
   1504     case GOAWAY_FRAME:
   1505       return GetMinGoAwayFrameSize() + frame.goaway_frame->reason_phrase.size();
   1506     case PADDING_FRAME:
   1507       DCHECK(false);
   1508       return 0;
   1509     case NUM_FRAME_TYPES:
   1510       DCHECK(false);
   1511       return 0;
   1512   }
   1513 
   1514   // Not reachable, but some Chrome compilers can't figure that out.  *sigh*
   1515   DCHECK(false);
   1516   return 0;
   1517 }
   1518 
   1519 bool QuicFramer::AppendTypeByte(const QuicFrame& frame,
   1520                                 bool last_frame_in_packet,
   1521                                 QuicDataWriter* writer) {
   1522   uint8 type_byte = 0;
   1523   switch (frame.type) {
   1524     case STREAM_FRAME: {
   1525       if (frame.stream_frame == NULL) {
   1526         LOG(DFATAL) << "Failed to append STREAM frame with no stream_frame.";
   1527       }
   1528       // Fin bit.
   1529       type_byte |= frame.stream_frame->fin ? kQuicStreamFinMask : 0;
   1530 
   1531       // Data Length bit.
   1532       type_byte <<= kQuicStreamDataLengthShift;
   1533       type_byte |= last_frame_in_packet ? 0 : kQuicStreamDataLengthMask;
   1534 
   1535       // Offset 3 bits.
   1536       type_byte <<= kQuicStreamOffsetShift;
   1537       const size_t offset_len = GetStreamOffsetSize(frame.stream_frame->offset);
   1538       if (offset_len > 0) {
   1539         type_byte |= offset_len - 1;
   1540       }
   1541 
   1542       // stream id 2 bits.
   1543       type_byte <<= kQuicStreamIdShift;
   1544       type_byte |= GetStreamIdSize(frame.stream_frame->stream_id) - 1;
   1545 
   1546       type_byte <<= 1;  // Leaves the last bit as a 0.
   1547       break;
   1548     }
   1549     case ACK_FRAME: {
   1550       // TODO(ianswett): Use extra 5 bits in the ack framing.
   1551       type_byte = 0x01;
   1552       break;
   1553     }
   1554     case CONGESTION_FEEDBACK_FRAME: {
   1555       // TODO(ianswett): Use extra 5 bits in the congestion feedback framing.
   1556       type_byte = 0x03;
   1557       break;
   1558     }
   1559     default:
   1560       type_byte =
   1561           frame.type << kQuicDefaultFrameTypeShift | kQuicDefaultFrameTypeMask;
   1562       break;
   1563   }
   1564 
   1565   return writer->WriteUInt8(type_byte);
   1566 }
   1567 
   1568 // static
   1569 bool QuicFramer::AppendPacketSequenceNumber(
   1570     QuicSequenceNumberLength sequence_number_length,
   1571     QuicPacketSequenceNumber packet_sequence_number,
   1572     QuicDataWriter* writer) {
   1573   // Ensure the entire sequence number can be written.
   1574   if (writer->capacity() - writer->length() <
   1575       static_cast<size_t>(sequence_number_length)) {
   1576     return false;
   1577   }
   1578   switch (sequence_number_length) {
   1579     case PACKET_1BYTE_SEQUENCE_NUMBER:
   1580       return writer->WriteUInt8(
   1581           packet_sequence_number & k1ByteSequenceNumberMask);
   1582       break;
   1583     case PACKET_2BYTE_SEQUENCE_NUMBER:
   1584       return writer->WriteUInt16(
   1585           packet_sequence_number & k2ByteSequenceNumberMask);
   1586       break;
   1587     case PACKET_4BYTE_SEQUENCE_NUMBER:
   1588       return writer->WriteUInt32(
   1589           packet_sequence_number & k4ByteSequenceNumberMask);
   1590       break;
   1591     case PACKET_6BYTE_SEQUENCE_NUMBER:
   1592       return writer->WriteUInt48(
   1593           packet_sequence_number & k6ByteSequenceNumberMask);
   1594       break;
   1595     default:
   1596       NOTREACHED() << "sequence_number_length: " << sequence_number_length;
   1597       return false;
   1598   }
   1599 }
   1600 
   1601 bool QuicFramer::AppendStreamFramePayload(
   1602     const QuicStreamFrame& frame,
   1603     bool last_frame_in_packet,
   1604     QuicDataWriter* writer) {
   1605   if (!writer->WriteBytes(&frame.stream_id, GetStreamIdSize(frame.stream_id))) {
   1606     return false;
   1607   }
   1608   if (!writer->WriteBytes(&frame.offset, GetStreamOffsetSize(frame.offset))) {
   1609     return false;
   1610   }
   1611   if (!last_frame_in_packet) {
   1612     if (!writer->WriteUInt16(frame.data.size())) {
   1613       return false;
   1614     }
   1615   }
   1616   if (!writer->WriteBytes(frame.data.data(), frame.data.size())) {
   1617     return false;
   1618   }
   1619   return true;
   1620 }
   1621 
   1622 QuicPacketSequenceNumber QuicFramer::CalculateLargestObserved(
   1623     const SequenceNumberSet& missing_packets,
   1624     SequenceNumberSet::const_iterator largest_written) {
   1625   SequenceNumberSet::const_iterator it = largest_written;
   1626   QuicPacketSequenceNumber previous_missing = *it;
   1627   ++it;
   1628 
   1629   // See if the next thing is a gap in the missing packets: if it's a
   1630   // non-missing packet we can return it.
   1631   if (it != missing_packets.end() && previous_missing + 1 != *it) {
   1632     return *it - 1;
   1633   }
   1634 
   1635   // Otherwise return the largest missing packet, as indirectly observed.
   1636   return *largest_written;
   1637 }
   1638 
   1639 // TODO(ianswett): Use varints or another more compact approach for all deltas.
   1640 bool QuicFramer::AppendAckFramePayload(
   1641     const QuicAckFrame& frame,
   1642     QuicDataWriter* writer) {
   1643   // TODO(satyamshekhar): Decide how often we really should send this
   1644   // entropy_hash update.
   1645   if (!writer->WriteUInt8(frame.sent_info.entropy_hash)) {
   1646     return false;
   1647   }
   1648 
   1649   if (!AppendPacketSequenceNumber(PACKET_6BYTE_SEQUENCE_NUMBER,
   1650                                   frame.sent_info.least_unacked, writer)) {
   1651     return false;
   1652   }
   1653 
   1654   size_t received_entropy_offset = writer->length();
   1655   if (!writer->WriteUInt8(frame.received_info.entropy_hash)) {
   1656     return false;
   1657   }
   1658 
   1659   size_t largest_observed_offset = writer->length();
   1660   if (!AppendPacketSequenceNumber(PACKET_6BYTE_SEQUENCE_NUMBER,
   1661                                   frame.received_info.largest_observed,
   1662                                   writer)) {
   1663     return false;
   1664   }
   1665   uint32 delta_time_largest_observed_us = kInvalidDeltaTime;
   1666   if (!frame.received_info.delta_time_largest_observed.IsInfinite()) {
   1667     delta_time_largest_observed_us =
   1668         frame.received_info.delta_time_largest_observed.ToMicroseconds();
   1669   }
   1670 
   1671   size_t delta_time_largest_observed_offset = writer->length();
   1672   if (!writer->WriteUInt32(delta_time_largest_observed_us)) {
   1673     return false;
   1674   }
   1675 
   1676   // We don't check for overflowing uint8 here, because we only can fit 192 acks
   1677   // per packet, so if we overflow we will be truncated.
   1678   uint8 num_missing_packets = frame.received_info.missing_packets.size();
   1679   size_t num_missing_packets_offset = writer->length();
   1680   if (!writer->WriteBytes(&num_missing_packets, 1)) {
   1681     return false;
   1682   }
   1683 
   1684   SequenceNumberSet::const_iterator it =
   1685       frame.received_info.missing_packets.begin();
   1686   int num_missing_packets_written = 0;
   1687   for (; it != frame.received_info.missing_packets.end(); ++it) {
   1688     if (!AppendPacketSequenceNumber(PACKET_6BYTE_SEQUENCE_NUMBER,
   1689                                     *it, writer)) {
   1690       // We are truncating.
   1691       QuicPacketSequenceNumber largest_observed =
   1692           CalculateLargestObserved(frame.received_info.missing_packets, --it);
   1693       // Overwrite entropy hash for received packets.
   1694       writer->WriteUInt8ToOffset(
   1695           entropy_calculator_->EntropyHash(largest_observed),
   1696           received_entropy_offset);
   1697       // Overwrite largest_observed.
   1698       writer->WriteUInt48ToOffset(largest_observed & k6ByteSequenceNumberMask,
   1699                                   largest_observed_offset);
   1700       writer->WriteUInt32ToOffset(kInvalidDeltaTime,
   1701                                   delta_time_largest_observed_offset);
   1702       writer->WriteUInt8ToOffset(num_missing_packets_written,
   1703                                  num_missing_packets_offset);
   1704       return true;
   1705     }
   1706     ++num_missing_packets_written;
   1707     DCHECK_GE(numeric_limits<uint8>::max(), num_missing_packets_written);
   1708   }
   1709 
   1710   return true;
   1711 }
   1712 
   1713 bool QuicFramer::AppendQuicCongestionFeedbackFramePayload(
   1714     const QuicCongestionFeedbackFrame& frame,
   1715     QuicDataWriter* writer) {
   1716   if (!writer->WriteBytes(&frame.type, 1)) {
   1717     return false;
   1718   }
   1719 
   1720   switch (frame.type) {
   1721     case kInterArrival: {
   1722       const CongestionFeedbackMessageInterArrival& inter_arrival =
   1723           frame.inter_arrival;
   1724       if (!writer->WriteUInt16(
   1725               inter_arrival.accumulated_number_of_lost_packets)) {
   1726         return false;
   1727       }
   1728       DCHECK_GE(numeric_limits<uint8>::max(),
   1729                 inter_arrival.received_packet_times.size());
   1730       if (inter_arrival.received_packet_times.size() >
   1731           numeric_limits<uint8>::max()) {
   1732         return false;
   1733       }
   1734       // TODO(ianswett): Make num_received_packets a varint.
   1735       uint8 num_received_packets =
   1736           inter_arrival.received_packet_times.size();
   1737       if (!writer->WriteBytes(&num_received_packets, 1)) {
   1738         return false;
   1739       }
   1740       if (num_received_packets > 0) {
   1741         TimeMap::const_iterator it =
   1742             inter_arrival.received_packet_times.begin();
   1743 
   1744         QuicPacketSequenceNumber lowest_sequence = it->first;
   1745         if (!AppendPacketSequenceNumber(PACKET_6BYTE_SEQUENCE_NUMBER,
   1746                                         lowest_sequence, writer)) {
   1747           return false;
   1748         }
   1749 
   1750         QuicTime lowest_time = it->second;
   1751         if (!writer->WriteUInt64(
   1752                 lowest_time.Subtract(creation_time_).ToMicroseconds())) {
   1753           return false;
   1754         }
   1755 
   1756         for (++it; it != inter_arrival.received_packet_times.end(); ++it) {
   1757           QuicPacketSequenceNumber sequence_delta = it->first - lowest_sequence;
   1758           DCHECK_GE(numeric_limits<uint16>::max(), sequence_delta);
   1759           if (sequence_delta > numeric_limits<uint16>::max()) {
   1760             return false;
   1761           }
   1762           if (!writer->WriteUInt16(static_cast<uint16>(sequence_delta))) {
   1763             return false;
   1764           }
   1765 
   1766           int32 time_delta_us =
   1767               it->second.Subtract(lowest_time).ToMicroseconds();
   1768           if (!writer->WriteBytes(&time_delta_us, sizeof(time_delta_us))) {
   1769             return false;
   1770           }
   1771         }
   1772       }
   1773       break;
   1774     }
   1775     case kFixRate: {
   1776       const CongestionFeedbackMessageFixRate& fix_rate =
   1777           frame.fix_rate;
   1778       if (!writer->WriteUInt32(fix_rate.bitrate.ToBytesPerSecond())) {
   1779         return false;
   1780       }
   1781       break;
   1782     }
   1783     case kTCP: {
   1784       const CongestionFeedbackMessageTCP& tcp = frame.tcp;
   1785       DCHECK_LE(tcp.receive_window, 1u << 20);
   1786       // Simple bit packing, don't send the 4 least significant bits.
   1787       uint16 receive_window = static_cast<uint16>(tcp.receive_window >> 4);
   1788       if (!writer->WriteUInt16(tcp.accumulated_number_of_lost_packets)) {
   1789         return false;
   1790       }
   1791       if (!writer->WriteUInt16(receive_window)) {
   1792         return false;
   1793       }
   1794       break;
   1795     }
   1796     default:
   1797       return false;
   1798   }
   1799 
   1800   return true;
   1801 }
   1802 
   1803 bool QuicFramer::AppendRstStreamFramePayload(
   1804         const QuicRstStreamFrame& frame,
   1805         QuicDataWriter* writer) {
   1806   if (!writer->WriteUInt32(frame.stream_id)) {
   1807     return false;
   1808   }
   1809 
   1810   uint32 error_code = static_cast<uint32>(frame.error_code);
   1811   if (!writer->WriteUInt32(error_code)) {
   1812     return false;
   1813   }
   1814 
   1815   if (!writer->WriteStringPiece16(frame.error_details)) {
   1816     return false;
   1817   }
   1818   return true;
   1819 }
   1820 
   1821 bool QuicFramer::AppendConnectionCloseFramePayload(
   1822     const QuicConnectionCloseFrame& frame,
   1823     QuicDataWriter* writer) {
   1824   uint32 error_code = static_cast<uint32>(frame.error_code);
   1825   if (!writer->WriteUInt32(error_code)) {
   1826     return false;
   1827   }
   1828   if (!writer->WriteStringPiece16(frame.error_details)) {
   1829     return false;
   1830   }
   1831   AppendAckFramePayload(frame.ack_frame, writer);
   1832   return true;
   1833 }
   1834 
   1835 bool QuicFramer::AppendGoAwayFramePayload(const QuicGoAwayFrame& frame,
   1836                                           QuicDataWriter* writer) {
   1837   uint32 error_code = static_cast<uint32>(frame.error_code);
   1838   if (!writer->WriteUInt32(error_code)) {
   1839     return false;
   1840   }
   1841   uint32 stream_id = static_cast<uint32>(frame.last_good_stream_id);
   1842   if (!writer->WriteUInt32(stream_id)) {
   1843     return false;
   1844   }
   1845   if (!writer->WriteStringPiece16(frame.reason_phrase)) {
   1846     return false;
   1847   }
   1848   return true;
   1849 }
   1850 
   1851 bool QuicFramer::RaiseError(QuicErrorCode error) {
   1852   DLOG(INFO) << detailed_error_;
   1853   set_error(error);
   1854   visitor_->OnError(this);
   1855   reader_.reset(NULL);
   1856   return false;
   1857 }
   1858 
   1859 }  // namespace net
   1860