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