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.
5 #include "net/quic/quic_framer.h"
7 #include "base/containers/hash_tables.h"
8 #include "base/stl_util.h"
9 #include "net/quic/crypto/crypto_framer.h"
10 #include "net/quic/crypto/crypto_handshake_message.h"
11 #include "net/quic/crypto/crypto_protocol.h"
12 #include "net/quic/crypto/quic_decrypter.h"
13 #include "net/quic/crypto/quic_encrypter.h"
14 #include "net/quic/quic_data_reader.h"
15 #include "net/quic/quic_data_writer.h"
16 #include "net/quic/quic_flags.h"
17 #include "net/quic/quic_socket_address_coder.h"
19 using base::StringPiece
;
24 using std::numeric_limits
;
31 // Mask to select the lowest 48 bits of a sequence number.
32 const QuicPacketSequenceNumber k6ByteSequenceNumberMask
=
33 GG_UINT64_C(0x0000FFFFFFFFFFFF);
34 const QuicPacketSequenceNumber k4ByteSequenceNumberMask
=
35 GG_UINT64_C(0x00000000FFFFFFFF);
36 const QuicPacketSequenceNumber k2ByteSequenceNumberMask
=
37 GG_UINT64_C(0x000000000000FFFF);
38 const QuicPacketSequenceNumber k1ByteSequenceNumberMask
=
39 GG_UINT64_C(0x00000000000000FF);
41 const QuicConnectionId k1ByteConnectionIdMask
= GG_UINT64_C(0x00000000000000FF);
42 const QuicConnectionId k4ByteConnectionIdMask
= GG_UINT64_C(0x00000000FFFFFFFF);
44 // Number of bits the sequence number length bits are shifted from the right
45 // edge of the public header.
46 const uint8 kPublicHeaderSequenceNumberShift
= 4;
48 // New Frame Types, QUIC v. >= 10:
49 // There are two interpretations for the Frame Type byte in the QUIC protocol,
50 // resulting in two Frame Types: Special Frame Types and Regular Frame Types.
52 // Regular Frame Types use the Frame Type byte simply. Currently defined
53 // Regular Frame Types are:
54 // Padding : 0b 00000000 (0x00)
55 // ResetStream : 0b 00000001 (0x01)
56 // ConnectionClose : 0b 00000010 (0x02)
57 // GoAway : 0b 00000011 (0x03)
58 // WindowUpdate : 0b 00000100 (0x04)
59 // Blocked : 0b 00000101 (0x05)
61 // Special Frame Types encode both a Frame Type and corresponding flags
62 // all in the Frame Type byte. Currently defined Special Frame Types are:
63 // Stream : 0b 1xxxxxxx
65 // CongestionFeedback : 0b 001xxxxx
67 // Semantics of the flag bits above (the x bits) depends on the frame type.
69 // Masks to determine if the frame type is a special use
70 // and for specific special frame types.
71 const uint8 kQuicFrameTypeSpecialMask
= 0xE0; // 0b 11100000
72 const uint8 kQuicFrameTypeStreamMask
= 0x80;
73 const uint8 kQuicFrameTypeAckMask
= 0x40;
74 const uint8 kQuicFrameTypeCongestionFeedbackMask
= 0x20;
76 // Stream frame relative shifts and masks for interpreting the stream flags.
77 // StreamID may be 1, 2, 3, or 4 bytes.
78 const uint8 kQuicStreamIdShift
= 2;
79 const uint8 kQuicStreamIDLengthMask
= 0x03;
81 // Offset may be 0, 2, 3, 4, 5, 6, 7, 8 bytes.
82 const uint8 kQuicStreamOffsetShift
= 3;
83 const uint8 kQuicStreamOffsetMask
= 0x07;
85 // Data length may be 0 or 2 bytes.
86 const uint8 kQuicStreamDataLengthShift
= 1;
87 const uint8 kQuicStreamDataLengthMask
= 0x01;
89 // Fin bit may be set or not.
90 const uint8 kQuicStreamFinShift
= 1;
91 const uint8 kQuicStreamFinMask
= 0x01;
93 // Sequence number size shift used in AckFrames.
94 const uint8 kQuicSequenceNumberLengthShift
= 2;
96 // Acks may be truncated.
97 const uint8 kQuicAckTruncatedShift
= 1;
98 const uint8 kQuicAckTruncatedMask
= 0x01;
100 // Acks may not have any nacks.
101 const uint8 kQuicHasNacksMask
= 0x01;
103 // Returns the absolute value of the difference between |a| and |b|.
104 QuicPacketSequenceNumber
Delta(QuicPacketSequenceNumber a
,
105 QuicPacketSequenceNumber b
) {
106 // Since these are unsigned numbers, we can't just return abs(a - b)
113 QuicPacketSequenceNumber
ClosestTo(QuicPacketSequenceNumber target
,
114 QuicPacketSequenceNumber a
,
115 QuicPacketSequenceNumber b
) {
116 return (Delta(target
, a
) < Delta(target
, b
)) ? a
: b
;
119 QuicSequenceNumberLength
ReadSequenceNumberLength(uint8 flags
) {
120 switch (flags
& PACKET_FLAGS_6BYTE_SEQUENCE
) {
121 case PACKET_FLAGS_6BYTE_SEQUENCE
:
122 return PACKET_6BYTE_SEQUENCE_NUMBER
;
123 case PACKET_FLAGS_4BYTE_SEQUENCE
:
124 return PACKET_4BYTE_SEQUENCE_NUMBER
;
125 case PACKET_FLAGS_2BYTE_SEQUENCE
:
126 return PACKET_2BYTE_SEQUENCE_NUMBER
;
127 case PACKET_FLAGS_1BYTE_SEQUENCE
:
128 return PACKET_1BYTE_SEQUENCE_NUMBER
;
130 LOG(DFATAL
) << "Unreachable case statement.";
131 return PACKET_6BYTE_SEQUENCE_NUMBER
;
135 bool CanTruncate(const QuicFrame
& frame
, size_t free_bytes
) {
136 if ((frame
.type
== ACK_FRAME
|| frame
.type
== CONNECTION_CLOSE_FRAME
) &&
138 QuicFramer::GetMinAckFrameSize(PACKET_6BYTE_SEQUENCE_NUMBER
,
139 PACKET_6BYTE_SEQUENCE_NUMBER
)) {
147 bool QuicFramerVisitorInterface::OnWindowUpdateFrame(
148 const QuicWindowUpdateFrame
& frame
) {
152 bool QuicFramerVisitorInterface::OnBlockedFrame(const QuicBlockedFrame
& frame
) {
156 QuicFramer::QuicFramer(const QuicVersionVector
& supported_versions
,
157 QuicTime creation_time
,
161 entropy_calculator_(NULL
),
162 error_(QUIC_NO_ERROR
),
163 last_sequence_number_(0),
164 last_serialized_connection_id_(0),
165 supported_versions_(supported_versions
),
166 decrypter_level_(ENCRYPTION_NONE
),
167 alternative_decrypter_level_(ENCRYPTION_NONE
),
168 alternative_decrypter_latch_(false),
169 is_server_(is_server
),
170 validate_flags_(true),
171 creation_time_(creation_time
) {
172 DCHECK(!supported_versions
.empty());
173 quic_version_
= supported_versions_
[0];
174 decrypter_
.reset(QuicDecrypter::Create(kNULL
));
175 encrypter_
[ENCRYPTION_NONE
].reset(
176 QuicEncrypter::Create(kNULL
));
179 QuicFramer::~QuicFramer() {}
182 size_t QuicFramer::GetMinStreamFrameSize(QuicStreamId stream_id
,
183 QuicStreamOffset offset
,
184 bool last_frame_in_packet
,
185 InFecGroup is_in_fec_group
) {
186 bool no_stream_frame_length
= last_frame_in_packet
&&
187 is_in_fec_group
== NOT_IN_FEC_GROUP
;
188 return kQuicFrameTypeSize
+ GetStreamIdSize(stream_id
) +
189 GetStreamOffsetSize(offset
) +
190 (no_stream_frame_length
? 0 : kQuicStreamPayloadLengthSize
);
194 size_t QuicFramer::GetMinAckFrameSize(
195 QuicSequenceNumberLength sequence_number_length
,
196 QuicSequenceNumberLength largest_observed_length
) {
197 return kQuicFrameTypeSize
+ kQuicEntropyHashSize
+
198 largest_observed_length
+ kQuicDeltaTimeLargestObservedSize
;
202 size_t QuicFramer::GetStopWaitingFrameSize(
203 QuicSequenceNumberLength sequence_number_length
) {
204 return kQuicFrameTypeSize
+ kQuicEntropyHashSize
+
205 sequence_number_length
;
209 size_t QuicFramer::GetMinRstStreamFrameSize() {
210 return kQuicFrameTypeSize
+ kQuicMaxStreamIdSize
+
211 kQuicMaxStreamOffsetSize
+ kQuicErrorCodeSize
+
212 kQuicErrorDetailsLengthSize
;
216 size_t QuicFramer::GetMinConnectionCloseFrameSize() {
217 return kQuicFrameTypeSize
+ kQuicErrorCodeSize
+ kQuicErrorDetailsLengthSize
;
221 size_t QuicFramer::GetMinGoAwayFrameSize() {
222 return kQuicFrameTypeSize
+ kQuicErrorCodeSize
+ kQuicErrorDetailsLengthSize
+
223 kQuicMaxStreamIdSize
;
227 size_t QuicFramer::GetWindowUpdateFrameSize() {
228 return kQuicFrameTypeSize
+ kQuicMaxStreamIdSize
+ kQuicMaxStreamOffsetSize
;
232 size_t QuicFramer::GetBlockedFrameSize() {
233 return kQuicFrameTypeSize
+ kQuicMaxStreamIdSize
;
237 size_t QuicFramer::GetStreamIdSize(QuicStreamId stream_id
) {
238 // Sizes are 1 through 4 bytes.
239 for (int i
= 1; i
<= 4; ++i
) {
241 if (stream_id
== 0) {
245 LOG(DFATAL
) << "Failed to determine StreamIDSize.";
250 size_t QuicFramer::GetStreamOffsetSize(QuicStreamOffset offset
) {
251 // 0 is a special case.
255 // 2 through 8 are the remaining sizes.
257 for (int i
= 2; i
<= 8; ++i
) {
263 LOG(DFATAL
) << "Failed to determine StreamOffsetSize.";
268 size_t QuicFramer::GetVersionNegotiationPacketSize(size_t number_versions
) {
269 return kPublicFlagsSize
+ PACKET_8BYTE_CONNECTION_ID
+
270 number_versions
* kQuicVersionSize
;
273 bool QuicFramer::IsSupportedVersion(const QuicVersion version
) const {
274 for (size_t i
= 0; i
< supported_versions_
.size(); ++i
) {
275 if (version
== supported_versions_
[i
]) {
282 size_t QuicFramer::GetSerializedFrameLength(
283 const QuicFrame
& frame
,
287 InFecGroup is_in_fec_group
,
288 QuicSequenceNumberLength sequence_number_length
) {
289 if (frame
.type
== PADDING_FRAME
) {
290 // PADDING implies end of packet.
294 ComputeFrameLength(frame
, last_frame
, is_in_fec_group
,
295 sequence_number_length
);
296 if (frame_len
<= free_bytes
) {
297 // Frame fits within packet. Note that acks may be truncated.
300 // Only truncate the first frame in a packet, so if subsequent ones go
301 // over, stop including more frames.
305 if (CanTruncate(frame
, free_bytes
)) {
306 // Truncate the frame so the packet will not exceed kMaxPacketSize.
307 // Note that we may not use every byte of the writer in this case.
308 DVLOG(1) << "Truncating large frame, free bytes: " << free_bytes
;
311 if (!FLAGS_quic_allow_oversized_packets_for_test
) {
314 LOG(DFATAL
) << "Packet size too small to fit frame.";
318 QuicFramer::AckFrameInfo::AckFrameInfo() : max_delta(0) {}
320 QuicFramer::AckFrameInfo::~AckFrameInfo() {}
322 QuicPacketEntropyHash
QuicFramer::GetPacketEntropyHash(
323 const QuicPacketHeader
& header
) const {
324 return header
.entropy_flag
<< (header
.packet_sequence_number
% 8);
327 SerializedPacket
QuicFramer::BuildDataPacket(
328 const QuicPacketHeader
& header
,
329 const QuicFrames
& frames
,
330 size_t packet_size
) {
331 QuicDataWriter
writer(packet_size
);
332 const SerializedPacket
kNoPacket(
333 0, PACKET_1BYTE_SEQUENCE_NUMBER
, NULL
, 0, NULL
);
334 if (!AppendPacketHeader(header
, &writer
)) {
335 LOG(DFATAL
) << "AppendPacketHeader failed";
339 for (size_t i
= 0; i
< frames
.size(); ++i
) {
340 const QuicFrame
& frame
= frames
[i
];
342 // Determine if we should write stream frame length in header.
343 const bool no_stream_frame_length
=
344 (header
.is_in_fec_group
== NOT_IN_FEC_GROUP
) &&
345 (i
== frames
.size() - 1);
346 if (!AppendTypeByte(frame
, no_stream_frame_length
, &writer
)) {
347 LOG(DFATAL
) << "AppendTypeByte failed";
351 switch (frame
.type
) {
353 writer
.WritePadding();
356 if (!AppendStreamFrame(
357 *frame
.stream_frame
, no_stream_frame_length
, &writer
)) {
358 LOG(DFATAL
) << "AppendStreamFrame failed";
363 if (!AppendAckFrameAndTypeByte(
364 header
, *frame
.ack_frame
, &writer
)) {
365 LOG(DFATAL
) << "AppendAckFrameAndTypeByte failed";
369 case CONGESTION_FEEDBACK_FRAME
:
370 if (!AppendCongestionFeedbackFrame(
371 *frame
.congestion_feedback_frame
, &writer
)) {
372 LOG(DFATAL
) << "AppendCongestionFeedbackFrame failed";
376 case STOP_WAITING_FRAME
:
377 if (!AppendStopWaitingFrame(
378 header
, *frame
.stop_waiting_frame
, &writer
)) {
379 LOG(DFATAL
) << "AppendStopWaitingFrame failed";
384 if (quic_version_
== QUIC_VERSION_16
) {
385 LOG(DFATAL
) << "Attempt to add a PingFrame in "
386 << QuicVersionToString(quic_version_
);
389 // Ping has no payload.
391 case RST_STREAM_FRAME
:
392 if (!AppendRstStreamFrame(*frame
.rst_stream_frame
, &writer
)) {
393 LOG(DFATAL
) << "AppendRstStreamFrame failed";
397 case CONNECTION_CLOSE_FRAME
:
398 if (!AppendConnectionCloseFrame(
399 *frame
.connection_close_frame
, &writer
)) {
400 LOG(DFATAL
) << "AppendConnectionCloseFrame failed";
405 if (!AppendGoAwayFrame(*frame
.goaway_frame
, &writer
)) {
406 LOG(DFATAL
) << "AppendGoAwayFrame failed";
410 case WINDOW_UPDATE_FRAME
:
411 if (!AppendWindowUpdateFrame(*frame
.window_update_frame
, &writer
)) {
412 LOG(DFATAL
) << "AppendWindowUpdateFrame failed";
417 if (!AppendBlockedFrame(*frame
.blocked_frame
, &writer
)) {
418 LOG(DFATAL
) << "AppendBlockedFrame failed";
423 RaiseError(QUIC_INVALID_FRAME_DATA
);
424 LOG(DFATAL
) << "QUIC_INVALID_FRAME_DATA";
429 // Save the length before writing, because take clears it.
430 const size_t len
= writer
.length();
431 // Less than or equal because truncated acks end up with max_plaintex_size
432 // length, even though they're typically slightly shorter.
433 DCHECK_LE(len
, packet_size
);
434 QuicPacket
* packet
= QuicPacket::NewDataPacket(
435 writer
.take(), len
, true, header
.public_header
.connection_id_length
,
436 header
.public_header
.version_flag
,
437 header
.public_header
.sequence_number_length
);
440 fec_builder_
->OnBuiltFecProtectedPayload(header
,
441 packet
->FecProtectedData());
444 return SerializedPacket(header
.packet_sequence_number
,
445 header
.public_header
.sequence_number_length
, packet
,
446 GetPacketEntropyHash(header
), NULL
);
449 SerializedPacket
QuicFramer::BuildFecPacket(const QuicPacketHeader
& header
,
450 const QuicFecData
& fec
) {
451 DCHECK_EQ(IN_FEC_GROUP
, header
.is_in_fec_group
);
452 DCHECK_NE(0u, header
.fec_group
);
453 size_t len
= GetPacketHeaderSize(header
);
454 len
+= fec
.redundancy
.length();
456 QuicDataWriter
writer(len
);
457 const SerializedPacket
kNoPacket(
458 0, PACKET_1BYTE_SEQUENCE_NUMBER
, NULL
, 0, NULL
);
459 if (!AppendPacketHeader(header
, &writer
)) {
460 LOG(DFATAL
) << "AppendPacketHeader failed";
464 if (!writer
.WriteBytes(fec
.redundancy
.data(), fec
.redundancy
.length())) {
465 LOG(DFATAL
) << "Failed to add FEC";
469 return SerializedPacket(
470 header
.packet_sequence_number
,
471 header
.public_header
.sequence_number_length
,
472 QuicPacket::NewFecPacket(writer
.take(), len
, true,
473 header
.public_header
.connection_id_length
,
474 header
.public_header
.version_flag
,
475 header
.public_header
.sequence_number_length
),
476 GetPacketEntropyHash(header
), NULL
);
480 QuicEncryptedPacket
* QuicFramer::BuildPublicResetPacket(
481 const QuicPublicResetPacket
& packet
) {
482 DCHECK(packet
.public_header
.reset_flag
);
484 CryptoHandshakeMessage reset
;
485 reset
.set_tag(kPRST
);
486 reset
.SetValue(kRNON
, packet
.nonce_proof
);
487 reset
.SetValue(kRSEQ
, packet
.rejected_sequence_number
);
488 if (!packet
.client_address
.address().empty()) {
489 // packet.client_address is non-empty.
490 QuicSocketAddressCoder
address_coder(packet
.client_address
);
491 string serialized_address
= address_coder
.Encode();
492 if (serialized_address
.empty()) {
495 reset
.SetStringPiece(kCADR
, serialized_address
);
497 const QuicData
& reset_serialized
= reset
.GetSerialized();
500 kPublicFlagsSize
+ PACKET_8BYTE_CONNECTION_ID
+ reset_serialized
.length();
501 QuicDataWriter
writer(len
);
503 uint8 flags
= static_cast<uint8
>(PACKET_PUBLIC_FLAGS_RST
|
504 PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID
);
505 if (!writer
.WriteUInt8(flags
)) {
509 if (!writer
.WriteUInt64(packet
.public_header
.connection_id
)) {
513 if (!writer
.WriteBytes(reset_serialized
.data(), reset_serialized
.length())) {
517 return new QuicEncryptedPacket(writer
.take(), len
, true);
520 QuicEncryptedPacket
* QuicFramer::BuildVersionNegotiationPacket(
521 const QuicPacketPublicHeader
& header
,
522 const QuicVersionVector
& supported_versions
) {
523 DCHECK(header
.version_flag
);
524 size_t len
= GetVersionNegotiationPacketSize(supported_versions
.size());
525 QuicDataWriter
writer(len
);
527 uint8 flags
= static_cast<uint8
>(PACKET_PUBLIC_FLAGS_VERSION
|
528 PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID
);
529 if (!writer
.WriteUInt8(flags
)) {
533 if (!writer
.WriteUInt64(header
.connection_id
)) {
537 for (size_t i
= 0; i
< supported_versions
.size(); ++i
) {
538 if (!writer
.WriteUInt32(QuicVersionToQuicTag(supported_versions
[i
]))) {
543 return new QuicEncryptedPacket(writer
.take(), len
, true);
546 bool QuicFramer::ProcessPacket(const QuicEncryptedPacket
& packet
) {
547 DCHECK(!reader_
.get());
548 reader_
.reset(new QuicDataReader(packet
.data(), packet
.length()));
550 visitor_
->OnPacket();
552 // First parse the public header.
553 QuicPacketPublicHeader public_header
;
554 if (!ProcessPublicHeader(&public_header
)) {
555 DLOG(WARNING
) << "Unable to process public header.";
556 DCHECK_NE("", detailed_error_
);
557 return RaiseError(QUIC_INVALID_PACKET_HEADER
);
560 if (!visitor_
->OnUnauthenticatedPublicHeader(public_header
)) {
561 // The visitor suppresses further processing of the packet.
566 if (is_server_
&& public_header
.version_flag
&&
567 public_header
.versions
[0] != quic_version_
) {
568 if (!visitor_
->OnProtocolVersionMismatch(public_header
.versions
[0])) {
575 if (!is_server_
&& public_header
.version_flag
) {
576 rv
= ProcessVersionNegotiationPacket(&public_header
);
577 } else if (public_header
.reset_flag
) {
578 rv
= ProcessPublicResetPacket(public_header
);
580 rv
= ProcessDataPacket(public_header
, packet
);
587 bool QuicFramer::ProcessVersionNegotiationPacket(
588 QuicPacketPublicHeader
* public_header
) {
590 // Try reading at least once to raise error if the packet is invalid.
593 if (!reader_
->ReadBytes(&version
, kQuicVersionSize
)) {
594 set_detailed_error("Unable to read supported version in negotiation.");
595 return RaiseError(QUIC_INVALID_VERSION_NEGOTIATION_PACKET
);
597 public_header
->versions
.push_back(QuicTagToQuicVersion(version
));
598 } while (!reader_
->IsDoneReading());
600 visitor_
->OnVersionNegotiationPacket(*public_header
);
604 bool QuicFramer::ProcessDataPacket(
605 const QuicPacketPublicHeader
& public_header
,
606 const QuicEncryptedPacket
& packet
) {
607 QuicPacketHeader
header(public_header
);
608 if (!ProcessPacketHeader(&header
, packet
)) {
609 DLOG(WARNING
) << "Unable to process data packet header.";
613 if (!visitor_
->OnPacketHeader(header
)) {
614 // The visitor suppresses further processing of the packet.
618 if (packet
.length() > kMaxPacketSize
) {
619 DLOG(WARNING
) << "Packet too large: " << packet
.length();
620 return RaiseError(QUIC_PACKET_TOO_LARGE
);
623 // Handle the payload.
624 if (!header
.fec_flag
) {
625 if (header
.is_in_fec_group
== IN_FEC_GROUP
) {
626 StringPiece payload
= reader_
->PeekRemainingPayload();
627 visitor_
->OnFecProtectedPayload(payload
);
629 if (!ProcessFrameData(header
)) {
630 DCHECK_NE(QUIC_NO_ERROR
, error_
); // ProcessFrameData sets the error.
631 DLOG(WARNING
) << "Unable to process frame data.";
635 QuicFecData fec_data
;
636 fec_data
.fec_group
= header
.fec_group
;
637 fec_data
.redundancy
= reader_
->ReadRemainingPayload();
638 visitor_
->OnFecData(fec_data
);
641 visitor_
->OnPacketComplete();
645 bool QuicFramer::ProcessPublicResetPacket(
646 const QuicPacketPublicHeader
& public_header
) {
647 QuicPublicResetPacket
packet(public_header
);
649 scoped_ptr
<CryptoHandshakeMessage
> reset(
650 CryptoFramer::ParseMessage(reader_
->ReadRemainingPayload()));
652 set_detailed_error("Unable to read reset message.");
653 return RaiseError(QUIC_INVALID_PUBLIC_RST_PACKET
);
655 if (reset
->tag() != kPRST
) {
656 set_detailed_error("Incorrect message tag.");
657 return RaiseError(QUIC_INVALID_PUBLIC_RST_PACKET
);
660 if (reset
->GetUint64(kRNON
, &packet
.nonce_proof
) != QUIC_NO_ERROR
) {
661 set_detailed_error("Unable to read nonce proof.");
662 return RaiseError(QUIC_INVALID_PUBLIC_RST_PACKET
);
664 // TODO(satyamshekhar): validate nonce to protect against DoS.
666 if (reset
->GetUint64(kRSEQ
, &packet
.rejected_sequence_number
) !=
668 set_detailed_error("Unable to read rejected sequence number.");
669 return RaiseError(QUIC_INVALID_PUBLIC_RST_PACKET
);
673 if (reset
->GetStringPiece(kCADR
, &address
)) {
674 QuicSocketAddressCoder address_coder
;
675 if (address_coder
.Decode(address
.data(), address
.length())) {
676 packet
.client_address
= IPEndPoint(address_coder
.ip(),
677 address_coder
.port());
681 visitor_
->OnPublicResetPacket(packet
);
685 bool QuicFramer::ProcessRevivedPacket(QuicPacketHeader
* header
,
686 StringPiece payload
) {
687 DCHECK(!reader_
.get());
689 visitor_
->OnRevivedPacket();
691 header
->entropy_hash
= GetPacketEntropyHash(*header
);
693 if (!visitor_
->OnPacketHeader(*header
)) {
697 if (payload
.length() > kMaxPacketSize
) {
698 set_detailed_error("Revived packet too large.");
699 return RaiseError(QUIC_PACKET_TOO_LARGE
);
702 reader_
.reset(new QuicDataReader(payload
.data(), payload
.length()));
703 if (!ProcessFrameData(*header
)) {
704 DCHECK_NE(QUIC_NO_ERROR
, error_
); // ProcessFrameData sets the error.
705 DLOG(WARNING
) << "Unable to process frame data.";
709 visitor_
->OnPacketComplete();
714 bool QuicFramer::AppendPacketHeader(const QuicPacketHeader
& header
,
715 QuicDataWriter
* writer
) {
716 DVLOG(1) << "Appending header: " << header
;
717 DCHECK(header
.fec_group
> 0 || header
.is_in_fec_group
== NOT_IN_FEC_GROUP
);
718 uint8 public_flags
= 0;
719 if (header
.public_header
.reset_flag
) {
720 public_flags
|= PACKET_PUBLIC_FLAGS_RST
;
722 if (header
.public_header
.version_flag
) {
723 public_flags
|= PACKET_PUBLIC_FLAGS_VERSION
;
727 GetSequenceNumberFlags(header
.public_header
.sequence_number_length
)
728 << kPublicHeaderSequenceNumberShift
;
730 switch (header
.public_header
.connection_id_length
) {
731 case PACKET_0BYTE_CONNECTION_ID
:
732 if (!writer
->WriteUInt8(
733 public_flags
| PACKET_PUBLIC_FLAGS_0BYTE_CONNECTION_ID
)) {
737 case PACKET_1BYTE_CONNECTION_ID
:
738 if (!writer
->WriteUInt8(
739 public_flags
| PACKET_PUBLIC_FLAGS_1BYTE_CONNECTION_ID
)) {
742 if (!writer
->WriteUInt8(
743 header
.public_header
.connection_id
& k1ByteConnectionIdMask
)) {
747 case PACKET_4BYTE_CONNECTION_ID
:
748 if (!writer
->WriteUInt8(
749 public_flags
| PACKET_PUBLIC_FLAGS_4BYTE_CONNECTION_ID
)) {
752 if (!writer
->WriteUInt32(
753 header
.public_header
.connection_id
& k4ByteConnectionIdMask
)) {
757 case PACKET_8BYTE_CONNECTION_ID
:
758 if (!writer
->WriteUInt8(
759 public_flags
| PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID
)) {
762 if (!writer
->WriteUInt64(header
.public_header
.connection_id
)) {
767 last_serialized_connection_id_
= header
.public_header
.connection_id
;
769 if (header
.public_header
.version_flag
) {
771 writer
->WriteUInt32(QuicVersionToQuicTag(quic_version_
));
774 if (!AppendPacketSequenceNumber(header
.public_header
.sequence_number_length
,
775 header
.packet_sequence_number
, writer
)) {
779 uint8 private_flags
= 0;
780 if (header
.entropy_flag
) {
781 private_flags
|= PACKET_PRIVATE_FLAGS_ENTROPY
;
783 if (header
.is_in_fec_group
== IN_FEC_GROUP
) {
784 private_flags
|= PACKET_PRIVATE_FLAGS_FEC_GROUP
;
786 if (header
.fec_flag
) {
787 private_flags
|= PACKET_PRIVATE_FLAGS_FEC
;
789 if (!writer
->WriteUInt8(private_flags
)) {
793 // The FEC group number is the sequence number of the first fec
794 // protected packet, or 0 if this packet is not protected.
795 if (header
.is_in_fec_group
== IN_FEC_GROUP
) {
796 DCHECK_GE(header
.packet_sequence_number
, header
.fec_group
);
797 DCHECK_GT(255u, header
.packet_sequence_number
- header
.fec_group
);
798 // Offset from the current packet sequence number to the first fec
800 uint8 first_fec_protected_packet_offset
=
801 header
.packet_sequence_number
- header
.fec_group
;
802 if (!writer
->WriteBytes(&first_fec_protected_packet_offset
, 1)) {
810 QuicPacketSequenceNumber
QuicFramer::CalculatePacketSequenceNumberFromWire(
811 QuicSequenceNumberLength sequence_number_length
,
812 QuicPacketSequenceNumber packet_sequence_number
) const {
813 // The new sequence number might have wrapped to the next epoch, or
814 // it might have reverse wrapped to the previous epoch, or it might
815 // remain in the same epoch. Select the sequence number closest to the
816 // next expected sequence number, the previous sequence number plus 1.
818 // epoch_delta is the delta between epochs the sequence number was serialized
819 // with, so the correct value is likely the same epoch as the last sequence
820 // number or an adjacent epoch.
821 const QuicPacketSequenceNumber epoch_delta
=
822 GG_UINT64_C(1) << (8 * sequence_number_length
);
823 QuicPacketSequenceNumber next_sequence_number
= last_sequence_number_
+ 1;
824 QuicPacketSequenceNumber epoch
= last_sequence_number_
& ~(epoch_delta
- 1);
825 QuicPacketSequenceNumber prev_epoch
= epoch
- epoch_delta
;
826 QuicPacketSequenceNumber next_epoch
= epoch
+ epoch_delta
;
828 return ClosestTo(next_sequence_number
,
829 epoch
+ packet_sequence_number
,
830 ClosestTo(next_sequence_number
,
831 prev_epoch
+ packet_sequence_number
,
832 next_epoch
+ packet_sequence_number
));
835 bool QuicFramer::ProcessPublicHeader(
836 QuicPacketPublicHeader
* public_header
) {
838 if (!reader_
->ReadBytes(&public_flags
, 1)) {
839 set_detailed_error("Unable to read public flags.");
843 public_header
->reset_flag
= (public_flags
& PACKET_PUBLIC_FLAGS_RST
) != 0;
844 public_header
->version_flag
=
845 (public_flags
& PACKET_PUBLIC_FLAGS_VERSION
) != 0;
847 if (validate_flags_
&&
848 !public_header
->version_flag
&& public_flags
> PACKET_PUBLIC_FLAGS_MAX
) {
849 set_detailed_error("Illegal public flags value.");
853 if (public_header
->reset_flag
&& public_header
->version_flag
) {
854 set_detailed_error("Got version flag in reset packet");
858 switch (public_flags
& PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID
) {
859 case PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID
:
860 if (!reader_
->ReadUInt64(&public_header
->connection_id
)) {
861 set_detailed_error("Unable to read ConnectionId.");
864 public_header
->connection_id_length
= PACKET_8BYTE_CONNECTION_ID
;
866 case PACKET_PUBLIC_FLAGS_4BYTE_CONNECTION_ID
:
867 // If the connection_id is truncated, expect to read the last serialized
869 if (!reader_
->ReadBytes(&public_header
->connection_id
,
870 PACKET_4BYTE_CONNECTION_ID
)) {
871 set_detailed_error("Unable to read ConnectionId.");
874 if ((public_header
->connection_id
& k4ByteConnectionIdMask
) !=
875 (last_serialized_connection_id_
& k4ByteConnectionIdMask
)) {
876 set_detailed_error("Truncated 4 byte ConnectionId does not match "
877 "previous connection_id.");
880 public_header
->connection_id_length
= PACKET_4BYTE_CONNECTION_ID
;
881 public_header
->connection_id
= last_serialized_connection_id_
;
883 case PACKET_PUBLIC_FLAGS_1BYTE_CONNECTION_ID
:
884 if (!reader_
->ReadBytes(&public_header
->connection_id
,
885 PACKET_1BYTE_CONNECTION_ID
)) {
886 set_detailed_error("Unable to read ConnectionId.");
889 if ((public_header
->connection_id
& k1ByteConnectionIdMask
) !=
890 (last_serialized_connection_id_
& k1ByteConnectionIdMask
)) {
891 set_detailed_error("Truncated 1 byte ConnectionId does not match "
892 "previous connection_id.");
895 public_header
->connection_id_length
= PACKET_1BYTE_CONNECTION_ID
;
896 public_header
->connection_id
= last_serialized_connection_id_
;
898 case PACKET_PUBLIC_FLAGS_0BYTE_CONNECTION_ID
:
899 public_header
->connection_id_length
= PACKET_0BYTE_CONNECTION_ID
;
900 public_header
->connection_id
= last_serialized_connection_id_
;
904 public_header
->sequence_number_length
=
905 ReadSequenceNumberLength(
906 public_flags
>> kPublicHeaderSequenceNumberShift
);
908 // Read the version only if the packet is from the client.
909 // version flag from the server means version negotiation packet.
910 if (public_header
->version_flag
&& is_server_
) {
912 if (!reader_
->ReadUInt32(&version_tag
)) {
913 set_detailed_error("Unable to read protocol version.");
917 // If the version from the new packet is the same as the version of this
918 // framer, then the public flags should be set to something we understand.
919 // If not, this raises an error.
920 QuicVersion version
= QuicTagToQuicVersion(version_tag
);
921 if (version
== quic_version_
&& public_flags
> PACKET_PUBLIC_FLAGS_MAX
) {
922 set_detailed_error("Illegal public flags value.");
925 public_header
->versions
.push_back(version
);
931 QuicSequenceNumberLength
QuicFramer::GetMinSequenceNumberLength(
932 QuicPacketSequenceNumber sequence_number
) {
933 if (sequence_number
< 1 << (PACKET_1BYTE_SEQUENCE_NUMBER
* 8)) {
934 return PACKET_1BYTE_SEQUENCE_NUMBER
;
935 } else if (sequence_number
< 1 << (PACKET_2BYTE_SEQUENCE_NUMBER
* 8)) {
936 return PACKET_2BYTE_SEQUENCE_NUMBER
;
937 } else if (sequence_number
<
938 GG_UINT64_C(1) << (PACKET_4BYTE_SEQUENCE_NUMBER
* 8)) {
939 return PACKET_4BYTE_SEQUENCE_NUMBER
;
941 return PACKET_6BYTE_SEQUENCE_NUMBER
;
946 uint8
QuicFramer::GetSequenceNumberFlags(
947 QuicSequenceNumberLength sequence_number_length
) {
948 switch (sequence_number_length
) {
949 case PACKET_1BYTE_SEQUENCE_NUMBER
:
950 return PACKET_FLAGS_1BYTE_SEQUENCE
;
951 case PACKET_2BYTE_SEQUENCE_NUMBER
:
952 return PACKET_FLAGS_2BYTE_SEQUENCE
;
953 case PACKET_4BYTE_SEQUENCE_NUMBER
:
954 return PACKET_FLAGS_4BYTE_SEQUENCE
;
955 case PACKET_6BYTE_SEQUENCE_NUMBER
:
956 return PACKET_FLAGS_6BYTE_SEQUENCE
;
958 LOG(DFATAL
) << "Unreachable case statement.";
959 return PACKET_FLAGS_6BYTE_SEQUENCE
;
964 QuicFramer::AckFrameInfo
QuicFramer::GetAckFrameInfo(
965 const QuicAckFrame
& frame
) {
966 AckFrameInfo ack_info
;
967 if (!frame
.missing_packets
.empty()) {
968 DCHECK_GE(frame
.largest_observed
, *frame
.missing_packets
.rbegin());
969 size_t cur_range_length
= 0;
970 SequenceNumberSet::const_iterator iter
= frame
.missing_packets
.begin();
971 QuicPacketSequenceNumber last_missing
= *iter
;
973 for (; iter
!= frame
.missing_packets
.end(); ++iter
) {
974 if (cur_range_length
!= numeric_limits
<uint8
>::max() &&
975 *iter
== (last_missing
+ 1)) {
978 ack_info
.nack_ranges
[last_missing
- cur_range_length
]
980 cur_range_length
= 0;
982 ack_info
.max_delta
= max(ack_info
.max_delta
, *iter
- last_missing
);
983 last_missing
= *iter
;
985 // Include the last nack range.
986 ack_info
.nack_ranges
[last_missing
- cur_range_length
] =
988 // Include the range to the largest observed.
989 ack_info
.max_delta
= max(ack_info
.max_delta
,
990 frame
.largest_observed
- last_missing
);
995 bool QuicFramer::ProcessPacketHeader(
996 QuicPacketHeader
* header
,
997 const QuicEncryptedPacket
& packet
) {
998 if (!ProcessPacketSequenceNumber(header
->public_header
.sequence_number_length
,
999 &header
->packet_sequence_number
)) {
1000 set_detailed_error("Unable to read sequence number.");
1001 return RaiseError(QUIC_INVALID_PACKET_HEADER
);
1004 if (header
->packet_sequence_number
== 0u) {
1005 set_detailed_error("Packet sequence numbers cannot be 0.");
1006 return RaiseError(QUIC_INVALID_PACKET_HEADER
);
1009 if (!visitor_
->OnUnauthenticatedHeader(*header
)) {
1013 if (!DecryptPayload(*header
, packet
)) {
1014 set_detailed_error("Unable to decrypt payload.");
1015 return RaiseError(QUIC_DECRYPTION_FAILURE
);
1018 uint8 private_flags
;
1019 if (!reader_
->ReadBytes(&private_flags
, 1)) {
1020 set_detailed_error("Unable to read private flags.");
1021 return RaiseError(QUIC_INVALID_PACKET_HEADER
);
1024 if (private_flags
> PACKET_PRIVATE_FLAGS_MAX
) {
1025 set_detailed_error("Illegal private flags value.");
1026 return RaiseError(QUIC_INVALID_PACKET_HEADER
);
1029 header
->entropy_flag
= (private_flags
& PACKET_PRIVATE_FLAGS_ENTROPY
) != 0;
1030 header
->fec_flag
= (private_flags
& PACKET_PRIVATE_FLAGS_FEC
) != 0;
1032 if ((private_flags
& PACKET_PRIVATE_FLAGS_FEC_GROUP
) != 0) {
1033 header
->is_in_fec_group
= IN_FEC_GROUP
;
1034 uint8 first_fec_protected_packet_offset
;
1035 if (!reader_
->ReadBytes(&first_fec_protected_packet_offset
, 1)) {
1036 set_detailed_error("Unable to read first fec protected packet offset.");
1037 return RaiseError(QUIC_INVALID_PACKET_HEADER
);
1039 if (first_fec_protected_packet_offset
>= header
->packet_sequence_number
) {
1040 set_detailed_error("First fec protected packet offset must be less "
1041 "than the sequence number.");
1042 return RaiseError(QUIC_INVALID_PACKET_HEADER
);
1045 header
->packet_sequence_number
- first_fec_protected_packet_offset
;
1048 header
->entropy_hash
= GetPacketEntropyHash(*header
);
1049 // Set the last sequence number after we have decrypted the packet
1050 // so we are confident is not attacker controlled.
1051 last_sequence_number_
= header
->packet_sequence_number
;
1055 bool QuicFramer::ProcessPacketSequenceNumber(
1056 QuicSequenceNumberLength sequence_number_length
,
1057 QuicPacketSequenceNumber
* sequence_number
) {
1058 QuicPacketSequenceNumber wire_sequence_number
= 0u;
1059 if (!reader_
->ReadBytes(&wire_sequence_number
, sequence_number_length
)) {
1063 // TODO(ianswett): Explore the usefulness of trying multiple sequence numbers
1064 // in case the first guess is incorrect.
1066 CalculatePacketSequenceNumberFromWire(sequence_number_length
,
1067 wire_sequence_number
);
1071 bool QuicFramer::ProcessFrameData(const QuicPacketHeader
& header
) {
1072 if (reader_
->IsDoneReading()) {
1073 set_detailed_error("Packet has no frames.");
1074 return RaiseError(QUIC_MISSING_PAYLOAD
);
1076 while (!reader_
->IsDoneReading()) {
1078 if (!reader_
->ReadBytes(&frame_type
, 1)) {
1079 set_detailed_error("Unable to read frame type.");
1080 return RaiseError(QUIC_INVALID_FRAME_DATA
);
1083 if (frame_type
& kQuicFrameTypeSpecialMask
) {
1085 if (frame_type
& kQuicFrameTypeStreamMask
) {
1086 QuicStreamFrame frame
;
1087 if (!ProcessStreamFrame(frame_type
, &frame
)) {
1088 return RaiseError(QUIC_INVALID_STREAM_DATA
);
1090 if (!visitor_
->OnStreamFrame(frame
)) {
1091 DVLOG(1) << "Visitor asked to stop further processing.";
1092 // Returning true since there was no parsing error.
1099 if (frame_type
& kQuicFrameTypeAckMask
) {
1101 if (!ProcessAckFrame(frame_type
, &frame
)) {
1102 return RaiseError(QUIC_INVALID_ACK_DATA
);
1104 if (!visitor_
->OnAckFrame(frame
)) {
1105 DVLOG(1) << "Visitor asked to stop further processing.";
1106 // Returning true since there was no parsing error.
1112 // Congestion Feedback Frame
1113 if (frame_type
& kQuicFrameTypeCongestionFeedbackMask
) {
1114 QuicCongestionFeedbackFrame frame
;
1115 if (!ProcessQuicCongestionFeedbackFrame(&frame
)) {
1116 return RaiseError(QUIC_INVALID_CONGESTION_FEEDBACK_DATA
);
1118 if (!visitor_
->OnCongestionFeedbackFrame(frame
)) {
1119 DVLOG(1) << "Visitor asked to stop further processing.";
1120 // Returning true since there was no parsing error.
1126 // This was a special frame type that did not match any
1127 // of the known ones. Error.
1128 set_detailed_error("Illegal frame type.");
1129 DLOG(WARNING
) << "Illegal frame type: "
1130 << static_cast<int>(frame_type
);
1131 return RaiseError(QUIC_INVALID_FRAME_DATA
);
1134 switch (frame_type
) {
1136 // We're done with the packet.
1139 case RST_STREAM_FRAME
: {
1140 QuicRstStreamFrame frame
;
1141 if (!ProcessRstStreamFrame(&frame
)) {
1142 return RaiseError(QUIC_INVALID_RST_STREAM_DATA
);
1144 if (!visitor_
->OnRstStreamFrame(frame
)) {
1145 DVLOG(1) << "Visitor asked to stop further processing.";
1146 // Returning true since there was no parsing error.
1152 case CONNECTION_CLOSE_FRAME
: {
1153 QuicConnectionCloseFrame frame
;
1154 if (!ProcessConnectionCloseFrame(&frame
)) {
1155 return RaiseError(QUIC_INVALID_CONNECTION_CLOSE_DATA
);
1158 if (!visitor_
->OnConnectionCloseFrame(frame
)) {
1159 DVLOG(1) << "Visitor asked to stop further processing.";
1160 // Returning true since there was no parsing error.
1166 case GOAWAY_FRAME
: {
1167 QuicGoAwayFrame goaway_frame
;
1168 if (!ProcessGoAwayFrame(&goaway_frame
)) {
1169 return RaiseError(QUIC_INVALID_GOAWAY_DATA
);
1171 if (!visitor_
->OnGoAwayFrame(goaway_frame
)) {
1172 DVLOG(1) << "Visitor asked to stop further processing.";
1173 // Returning true since there was no parsing error.
1179 case WINDOW_UPDATE_FRAME
: {
1180 QuicWindowUpdateFrame window_update_frame
;
1181 if (!ProcessWindowUpdateFrame(&window_update_frame
)) {
1182 return RaiseError(QUIC_INVALID_WINDOW_UPDATE_DATA
);
1184 if (!visitor_
->OnWindowUpdateFrame(window_update_frame
)) {
1185 DVLOG(1) << "Visitor asked to stop further processing.";
1186 // Returning true since there was no parsing error.
1192 case BLOCKED_FRAME
: {
1193 QuicBlockedFrame blocked_frame
;
1194 if (!ProcessBlockedFrame(&blocked_frame
)) {
1195 return RaiseError(QUIC_INVALID_BLOCKED_DATA
);
1197 if (!visitor_
->OnBlockedFrame(blocked_frame
)) {
1198 DVLOG(1) << "Visitor asked to stop further processing.";
1199 // Returning true since there was no parsing error.
1205 case STOP_WAITING_FRAME
: {
1206 QuicStopWaitingFrame stop_waiting_frame
;
1207 if (!ProcessStopWaitingFrame(header
, &stop_waiting_frame
)) {
1208 return RaiseError(QUIC_INVALID_STOP_WAITING_DATA
);
1210 if (!visitor_
->OnStopWaitingFrame(stop_waiting_frame
)) {
1211 DVLOG(1) << "Visitor asked to stop further processing.";
1212 // Returning true since there was no parsing error.
1218 if (quic_version_
== QUIC_VERSION_16
) {
1219 LOG(DFATAL
) << "Trying to read a Ping in "
1220 << QuicVersionToString(quic_version_
);
1221 return RaiseError(QUIC_INTERNAL_ERROR
);
1223 // Ping has no payload.
1224 QuicPingFrame ping_frame
;
1225 if (!visitor_
->OnPingFrame(ping_frame
)) {
1226 DVLOG(1) << "Visitor asked to stop further processing.";
1227 // Returning true since there was no parsing error.
1234 set_detailed_error("Illegal frame type.");
1235 DLOG(WARNING
) << "Illegal frame type: "
1236 << static_cast<int>(frame_type
);
1237 return RaiseError(QUIC_INVALID_FRAME_DATA
);
1244 bool QuicFramer::ProcessStreamFrame(uint8 frame_type
,
1245 QuicStreamFrame
* frame
) {
1246 uint8 stream_flags
= frame_type
;
1248 stream_flags
&= ~kQuicFrameTypeStreamMask
;
1250 // Read from right to left: StreamID, Offset, Data Length, Fin.
1251 const uint8 stream_id_length
= (stream_flags
& kQuicStreamIDLengthMask
) + 1;
1252 stream_flags
>>= kQuicStreamIdShift
;
1254 uint8 offset_length
= (stream_flags
& kQuicStreamOffsetMask
);
1255 // There is no encoding for 1 byte, only 0 and 2 through 8.
1256 if (offset_length
> 0) {
1259 stream_flags
>>= kQuicStreamOffsetShift
;
1261 bool has_data_length
=
1262 (stream_flags
& kQuicStreamDataLengthMask
) == kQuicStreamDataLengthMask
;
1263 stream_flags
>>= kQuicStreamDataLengthShift
;
1265 frame
->fin
= (stream_flags
& kQuicStreamFinMask
) == kQuicStreamFinShift
;
1267 frame
->stream_id
= 0;
1268 if (!reader_
->ReadBytes(&frame
->stream_id
, stream_id_length
)) {
1269 set_detailed_error("Unable to read stream_id.");
1274 if (!reader_
->ReadBytes(&frame
->offset
, offset_length
)) {
1275 set_detailed_error("Unable to read offset.");
1279 StringPiece frame_data
;
1280 if (has_data_length
) {
1281 if (!reader_
->ReadStringPiece16(&frame_data
)) {
1282 set_detailed_error("Unable to read frame data.");
1286 if (!reader_
->ReadStringPiece(&frame_data
, reader_
->BytesRemaining())) {
1287 set_detailed_error("Unable to read frame data.");
1291 // Point frame to the right data.
1292 frame
->data
.Clear();
1293 if (!frame_data
.empty()) {
1294 frame
->data
.Append(const_cast<char*>(frame_data
.data()), frame_data
.size());
1300 bool QuicFramer::ProcessAckFrame(uint8 frame_type
, QuicAckFrame
* ack_frame
) {
1301 // Determine the three lengths from the frame type: largest observed length,
1302 // missing sequence number length, and missing range length.
1303 const QuicSequenceNumberLength missing_sequence_number_length
=
1304 ReadSequenceNumberLength(frame_type
);
1305 frame_type
>>= kQuicSequenceNumberLengthShift
;
1306 const QuicSequenceNumberLength largest_observed_sequence_number_length
=
1307 ReadSequenceNumberLength(frame_type
);
1308 frame_type
>>= kQuicSequenceNumberLengthShift
;
1309 ack_frame
->is_truncated
= frame_type
& kQuicAckTruncatedMask
;
1310 frame_type
>>= kQuicAckTruncatedShift
;
1311 bool has_nacks
= frame_type
& kQuicHasNacksMask
;
1313 if (!reader_
->ReadBytes(&ack_frame
->entropy_hash
, 1)) {
1314 set_detailed_error("Unable to read entropy hash for received packets.");
1318 if (!reader_
->ReadBytes(&ack_frame
->largest_observed
,
1319 largest_observed_sequence_number_length
)) {
1320 set_detailed_error("Unable to read largest observed.");
1324 uint64 delta_time_largest_observed_us
;
1325 if (!reader_
->ReadUFloat16(&delta_time_largest_observed_us
)) {
1326 set_detailed_error("Unable to read delta time largest observed.");
1330 if (delta_time_largest_observed_us
== kUFloat16MaxValue
) {
1331 ack_frame
->delta_time_largest_observed
= QuicTime::Delta::Infinite();
1333 ack_frame
->delta_time_largest_observed
=
1334 QuicTime::Delta::FromMicroseconds(delta_time_largest_observed_us
);
1341 uint8 num_missing_ranges
;
1342 if (!reader_
->ReadBytes(&num_missing_ranges
, 1)) {
1343 set_detailed_error("Unable to read num missing packet ranges.");
1347 QuicPacketSequenceNumber last_sequence_number
= ack_frame
->largest_observed
;
1348 for (size_t i
= 0; i
< num_missing_ranges
; ++i
) {
1349 QuicPacketSequenceNumber missing_delta
= 0;
1350 if (!reader_
->ReadBytes(&missing_delta
, missing_sequence_number_length
)) {
1351 set_detailed_error("Unable to read missing sequence number delta.");
1354 last_sequence_number
-= missing_delta
;
1355 QuicPacketSequenceNumber range_length
= 0;
1356 if (!reader_
->ReadBytes(&range_length
, PACKET_1BYTE_SEQUENCE_NUMBER
)) {
1357 set_detailed_error("Unable to read missing sequence number range.");
1360 for (size_t i
= 0; i
<= range_length
; ++i
) {
1361 ack_frame
->missing_packets
.insert(last_sequence_number
- i
);
1363 // Subtract an extra 1 to ensure ranges are represented efficiently and
1364 // can't overlap by 1 sequence number. This allows a missing_delta of 0
1365 // to represent an adjacent nack range.
1366 last_sequence_number
-= (range_length
+ 1);
1369 // Parse the revived packets list.
1370 uint8 num_revived_packets
;
1371 if (!reader_
->ReadBytes(&num_revived_packets
, 1)) {
1372 set_detailed_error("Unable to read num revived packets.");
1376 for (size_t i
= 0; i
< num_revived_packets
; ++i
) {
1377 QuicPacketSequenceNumber revived_packet
= 0;
1378 if (!reader_
->ReadBytes(&revived_packet
,
1379 largest_observed_sequence_number_length
)) {
1380 set_detailed_error("Unable to read revived packet.");
1384 ack_frame
->revived_packets
.insert(revived_packet
);
1390 bool QuicFramer::ProcessStopWaitingFrame(const QuicPacketHeader
& header
,
1391 QuicStopWaitingFrame
* stop_waiting
) {
1392 if (!reader_
->ReadBytes(&stop_waiting
->entropy_hash
, 1)) {
1393 set_detailed_error("Unable to read entropy hash for sent packets.");
1397 QuicPacketSequenceNumber least_unacked_delta
= 0;
1398 if (!reader_
->ReadBytes(&least_unacked_delta
,
1399 header
.public_header
.sequence_number_length
)) {
1400 set_detailed_error("Unable to read least unacked delta.");
1403 DCHECK_GE(header
.packet_sequence_number
, least_unacked_delta
);
1404 stop_waiting
->least_unacked
=
1405 header
.packet_sequence_number
- least_unacked_delta
;
1410 bool QuicFramer::ProcessQuicCongestionFeedbackFrame(
1411 QuicCongestionFeedbackFrame
* frame
) {
1412 uint8 feedback_type
;
1413 if (!reader_
->ReadBytes(&feedback_type
, 1)) {
1414 set_detailed_error("Unable to read congestion feedback type.");
1418 static_cast<CongestionFeedbackType
>(feedback_type
);
1420 switch (frame
->type
) {
1422 CongestionFeedbackMessageTimestamp
* timestamp
= &frame
->timestamp
;
1423 uint8 num_received_packets
;
1424 if (!reader_
->ReadBytes(&num_received_packets
, 1)) {
1425 set_detailed_error("Unable to read num received packets.");
1429 if (num_received_packets
> 0u) {
1430 uint64 smallest_received
;
1431 if (!ProcessPacketSequenceNumber(PACKET_6BYTE_SEQUENCE_NUMBER
,
1432 &smallest_received
)) {
1433 set_detailed_error("Unable to read smallest received.");
1437 uint64 time_received_us
;
1438 if (!reader_
->ReadUInt64(&time_received_us
)) {
1439 set_detailed_error("Unable to read time received.");
1442 QuicTime time_received
= creation_time_
.Add(
1443 QuicTime::Delta::FromMicroseconds(time_received_us
));
1445 timestamp
->received_packet_times
.insert(
1446 make_pair(smallest_received
, time_received
));
1448 for (uint8 i
= 0; i
< num_received_packets
- 1; ++i
) {
1449 uint16 sequence_delta
;
1450 if (!reader_
->ReadUInt16(&sequence_delta
)) {
1452 "Unable to read sequence delta in received packets.");
1456 int32 time_delta_us
;
1457 if (!reader_
->ReadBytes(&time_delta_us
, sizeof(time_delta_us
))) {
1459 "Unable to read time delta in received packets.");
1462 QuicPacketSequenceNumber packet
= smallest_received
+ sequence_delta
;
1463 timestamp
->received_packet_times
.insert(
1464 make_pair(packet
, time_received
.Add(
1465 QuicTime::Delta::FromMicroseconds(time_delta_us
))));
1471 CongestionFeedbackMessageTCP
* tcp
= &frame
->tcp
;
1472 uint16 receive_window
= 0;
1473 if (!reader_
->ReadUInt16(&receive_window
)) {
1474 set_detailed_error("Unable to read receive window.");
1477 // Simple bit packing, don't send the 4 least significant bits.
1478 tcp
->receive_window
= static_cast<QuicByteCount
>(receive_window
) << 4;
1482 set_detailed_error("Illegal congestion feedback type.");
1483 DLOG(WARNING
) << "Illegal congestion feedback type: "
1485 return RaiseError(QUIC_INVALID_FRAME_DATA
);
1491 bool QuicFramer::ProcessRstStreamFrame(QuicRstStreamFrame
* frame
) {
1492 if (!reader_
->ReadUInt32(&frame
->stream_id
)) {
1493 set_detailed_error("Unable to read stream_id.");
1497 if (!reader_
->ReadUInt64(&frame
->byte_offset
)) {
1498 set_detailed_error("Unable to read rst stream sent byte offset.");
1503 if (!reader_
->ReadUInt32(&error_code
)) {
1504 set_detailed_error("Unable to read rst stream error code.");
1508 if (error_code
>= QUIC_STREAM_LAST_ERROR
||
1509 error_code
< QUIC_STREAM_NO_ERROR
) {
1510 set_detailed_error("Invalid rst stream error code.");
1514 frame
->error_code
= static_cast<QuicRstStreamErrorCode
>(error_code
);
1516 StringPiece error_details
;
1517 if (!reader_
->ReadStringPiece16(&error_details
)) {
1518 set_detailed_error("Unable to read rst stream error details.");
1521 frame
->error_details
= error_details
.as_string();
1526 bool QuicFramer::ProcessConnectionCloseFrame(QuicConnectionCloseFrame
* frame
) {
1528 if (!reader_
->ReadUInt32(&error_code
)) {
1529 set_detailed_error("Unable to read connection close error code.");
1533 if (error_code
>= QUIC_LAST_ERROR
||
1534 error_code
< QUIC_NO_ERROR
) {
1535 set_detailed_error("Invalid error code.");
1539 frame
->error_code
= static_cast<QuicErrorCode
>(error_code
);
1541 StringPiece error_details
;
1542 if (!reader_
->ReadStringPiece16(&error_details
)) {
1543 set_detailed_error("Unable to read connection close error details.");
1546 frame
->error_details
= error_details
.as_string();
1551 bool QuicFramer::ProcessGoAwayFrame(QuicGoAwayFrame
* frame
) {
1553 if (!reader_
->ReadUInt32(&error_code
)) {
1554 set_detailed_error("Unable to read go away error code.");
1557 frame
->error_code
= static_cast<QuicErrorCode
>(error_code
);
1559 if (error_code
>= QUIC_LAST_ERROR
||
1560 error_code
< QUIC_NO_ERROR
) {
1561 set_detailed_error("Invalid error code.");
1566 if (!reader_
->ReadUInt32(&stream_id
)) {
1567 set_detailed_error("Unable to read last good stream id.");
1570 frame
->last_good_stream_id
= static_cast<QuicStreamId
>(stream_id
);
1572 StringPiece reason_phrase
;
1573 if (!reader_
->ReadStringPiece16(&reason_phrase
)) {
1574 set_detailed_error("Unable to read goaway reason.");
1577 frame
->reason_phrase
= reason_phrase
.as_string();
1582 bool QuicFramer::ProcessWindowUpdateFrame(QuicWindowUpdateFrame
* frame
) {
1583 if (!reader_
->ReadUInt32(&frame
->stream_id
)) {
1584 set_detailed_error("Unable to read stream_id.");
1588 if (!reader_
->ReadUInt64(&frame
->byte_offset
)) {
1589 set_detailed_error("Unable to read window byte_offset.");
1596 bool QuicFramer::ProcessBlockedFrame(QuicBlockedFrame
* frame
) {
1597 if (!reader_
->ReadUInt32(&frame
->stream_id
)) {
1598 set_detailed_error("Unable to read stream_id.");
1606 StringPiece
QuicFramer::GetAssociatedDataFromEncryptedPacket(
1607 const QuicEncryptedPacket
& encrypted
,
1608 QuicConnectionIdLength connection_id_length
,
1609 bool includes_version
,
1610 QuicSequenceNumberLength sequence_number_length
) {
1612 encrypted
.data() + kStartOfHashData
, GetStartOfEncryptedData(
1613 connection_id_length
, includes_version
, sequence_number_length
)
1614 - kStartOfHashData
);
1617 void QuicFramer::SetDecrypter(QuicDecrypter
* decrypter
,
1618 EncryptionLevel level
) {
1619 DCHECK(alternative_decrypter_
.get() == NULL
);
1620 DCHECK_GE(level
, decrypter_level_
);
1621 decrypter_
.reset(decrypter
);
1622 decrypter_level_
= level
;
1625 void QuicFramer::SetAlternativeDecrypter(QuicDecrypter
* decrypter
,
1626 EncryptionLevel level
,
1627 bool latch_once_used
) {
1628 alternative_decrypter_
.reset(decrypter
);
1629 alternative_decrypter_level_
= level
;
1630 alternative_decrypter_latch_
= latch_once_used
;
1633 const QuicDecrypter
* QuicFramer::decrypter() const {
1634 return decrypter_
.get();
1637 const QuicDecrypter
* QuicFramer::alternative_decrypter() const {
1638 return alternative_decrypter_
.get();
1641 void QuicFramer::SetEncrypter(EncryptionLevel level
,
1642 QuicEncrypter
* encrypter
) {
1643 DCHECK_GE(level
, 0);
1644 DCHECK_LT(level
, NUM_ENCRYPTION_LEVELS
);
1645 encrypter_
[level
].reset(encrypter
);
1648 const QuicEncrypter
* QuicFramer::encrypter(EncryptionLevel level
) const {
1649 DCHECK_GE(level
, 0);
1650 DCHECK_LT(level
, NUM_ENCRYPTION_LEVELS
);
1651 DCHECK(encrypter_
[level
].get() != NULL
);
1652 return encrypter_
[level
].get();
1655 QuicEncryptedPacket
* QuicFramer::EncryptPacket(
1656 EncryptionLevel level
,
1657 QuicPacketSequenceNumber packet_sequence_number
,
1658 const QuicPacket
& packet
) {
1659 DCHECK(encrypter_
[level
].get() != NULL
);
1661 scoped_ptr
<QuicData
> out(encrypter_
[level
]->EncryptPacket(
1662 packet_sequence_number
, packet
.AssociatedData(), packet
.Plaintext()));
1663 if (out
.get() == NULL
) {
1664 RaiseError(QUIC_ENCRYPTION_FAILURE
);
1667 StringPiece header_data
= packet
.BeforePlaintext();
1668 size_t len
= header_data
.length() + out
->length();
1669 char* buffer
= new char[len
];
1670 // TODO(rch): eliminate this buffer copy by passing in a buffer to Encrypt().
1671 memcpy(buffer
, header_data
.data(), header_data
.length());
1672 memcpy(buffer
+ header_data
.length(), out
->data(), out
->length());
1673 return new QuicEncryptedPacket(buffer
, len
, true);
1676 size_t QuicFramer::GetMaxPlaintextSize(size_t ciphertext_size
) {
1677 // In order to keep the code simple, we don't have the current encryption
1678 // level to hand. Both the NullEncrypter and AES-GCM have a tag length of 12.
1679 size_t min_plaintext_size
= ciphertext_size
;
1681 for (int i
= ENCRYPTION_NONE
; i
< NUM_ENCRYPTION_LEVELS
; i
++) {
1682 if (encrypter_
[i
].get() != NULL
) {
1683 size_t size
= encrypter_
[i
]->GetMaxPlaintextSize(ciphertext_size
);
1684 if (size
< min_plaintext_size
) {
1685 min_plaintext_size
= size
;
1690 return min_plaintext_size
;
1693 bool QuicFramer::DecryptPayload(const QuicPacketHeader
& header
,
1694 const QuicEncryptedPacket
& packet
) {
1695 StringPiece encrypted
;
1696 if (!reader_
->ReadStringPiece(&encrypted
, reader_
->BytesRemaining())) {
1699 DCHECK(decrypter_
.get() != NULL
);
1700 decrypted_
.reset(decrypter_
->DecryptPacket(
1701 header
.packet_sequence_number
,
1702 GetAssociatedDataFromEncryptedPacket(
1704 header
.public_header
.connection_id_length
,
1705 header
.public_header
.version_flag
,
1706 header
.public_header
.sequence_number_length
),
1708 if (decrypted_
.get() != NULL
) {
1709 visitor_
->OnDecryptedPacket(decrypter_level_
);
1710 } else if (alternative_decrypter_
.get() != NULL
) {
1711 decrypted_
.reset(alternative_decrypter_
->DecryptPacket(
1712 header
.packet_sequence_number
,
1713 GetAssociatedDataFromEncryptedPacket(
1715 header
.public_header
.connection_id_length
,
1716 header
.public_header
.version_flag
,
1717 header
.public_header
.sequence_number_length
),
1719 if (decrypted_
.get() != NULL
) {
1720 visitor_
->OnDecryptedPacket(alternative_decrypter_level_
);
1721 if (alternative_decrypter_latch_
) {
1722 // Switch to the alternative decrypter and latch so that we cannot
1724 decrypter_
.reset(alternative_decrypter_
.release());
1725 decrypter_level_
= alternative_decrypter_level_
;
1726 alternative_decrypter_level_
= ENCRYPTION_NONE
;
1728 // Switch the alternative decrypter so that we use it first next time.
1729 decrypter_
.swap(alternative_decrypter_
);
1730 EncryptionLevel level
= alternative_decrypter_level_
;
1731 alternative_decrypter_level_
= decrypter_level_
;
1732 decrypter_level_
= level
;
1737 if (decrypted_
.get() == NULL
) {
1738 DLOG(WARNING
) << "DecryptPacket failed for sequence_number:"
1739 << header
.packet_sequence_number
;
1743 reader_
.reset(new QuicDataReader(decrypted_
->data(), decrypted_
->length()));
1747 size_t QuicFramer::GetAckFrameSize(
1748 const QuicAckFrame
& ack
,
1749 QuicSequenceNumberLength sequence_number_length
) {
1750 AckFrameInfo ack_info
= GetAckFrameInfo(ack
);
1751 QuicSequenceNumberLength largest_observed_length
=
1752 GetMinSequenceNumberLength(ack
.largest_observed
);
1753 QuicSequenceNumberLength missing_sequence_number_length
=
1754 GetMinSequenceNumberLength(ack_info
.max_delta
);
1756 size_t ack_size
= GetMinAckFrameSize(sequence_number_length
,
1757 largest_observed_length
);
1758 if (!ack_info
.nack_ranges
.empty()) {
1759 ack_size
+= kNumberOfNackRangesSize
+ kNumberOfRevivedPacketsSize
;
1760 ack_size
+= min(ack_info
.nack_ranges
.size(), kMaxNackRanges
) *
1761 (missing_sequence_number_length
+ PACKET_1BYTE_SEQUENCE_NUMBER
);
1762 ack_size
+= min(ack
.revived_packets
.size(),
1763 kMaxRevivedPackets
) * largest_observed_length
;
1768 size_t QuicFramer::ComputeFrameLength(
1769 const QuicFrame
& frame
,
1770 bool last_frame_in_packet
,
1771 InFecGroup is_in_fec_group
,
1772 QuicSequenceNumberLength sequence_number_length
) {
1773 switch (frame
.type
) {
1775 return GetMinStreamFrameSize(frame
.stream_frame
->stream_id
,
1776 frame
.stream_frame
->offset
,
1777 last_frame_in_packet
,
1779 frame
.stream_frame
->data
.TotalBufferSize();
1781 return GetAckFrameSize(*frame
.ack_frame
, sequence_number_length
);
1783 case CONGESTION_FEEDBACK_FRAME
: {
1784 size_t len
= kQuicFrameTypeSize
;
1785 const QuicCongestionFeedbackFrame
& congestion_feedback
=
1786 *frame
.congestion_feedback_frame
;
1787 len
+= 1; // Congestion feedback type.
1789 switch (congestion_feedback
.type
) {
1791 const CongestionFeedbackMessageTimestamp
& timestamp
=
1792 congestion_feedback
.timestamp
;
1793 len
+= 1; // Number received packets.
1794 if (!timestamp
.received_packet_times
.empty()) {
1795 len
+= PACKET_6BYTE_SEQUENCE_NUMBER
; // Smallest received.
1797 // 2 bytes per sequence number delta plus 4 bytes per delta time.
1798 len
+= PACKET_6BYTE_SEQUENCE_NUMBER
*
1799 (timestamp
.received_packet_times
.size() - 1);
1804 len
+= 2; // Receive window.
1807 set_detailed_error("Illegal feedback type.");
1808 DVLOG(1) << "Illegal feedback type: " << congestion_feedback
.type
;
1813 case STOP_WAITING_FRAME
:
1814 return GetStopWaitingFrameSize(sequence_number_length
);
1816 // Ping has no payload.
1817 return kQuicFrameTypeSize
;
1818 case RST_STREAM_FRAME
:
1819 return GetMinRstStreamFrameSize() +
1820 frame
.rst_stream_frame
->error_details
.size();
1821 case CONNECTION_CLOSE_FRAME
:
1822 return GetMinConnectionCloseFrameSize() +
1823 frame
.connection_close_frame
->error_details
.size();
1825 return GetMinGoAwayFrameSize() + frame
.goaway_frame
->reason_phrase
.size();
1826 case WINDOW_UPDATE_FRAME
:
1827 return GetWindowUpdateFrameSize();
1829 return GetBlockedFrameSize();
1833 case NUM_FRAME_TYPES
:
1838 // Not reachable, but some Chrome compilers can't figure that out. *sigh*
1843 bool QuicFramer::AppendTypeByte(const QuicFrame
& frame
,
1844 bool no_stream_frame_length
,
1845 QuicDataWriter
* writer
) {
1846 uint8 type_byte
= 0;
1847 switch (frame
.type
) {
1848 case STREAM_FRAME
: {
1849 if (frame
.stream_frame
== NULL
) {
1850 LOG(DFATAL
) << "Failed to append STREAM frame with no stream_frame.";
1853 type_byte
|= frame
.stream_frame
->fin
? kQuicStreamFinMask
: 0;
1856 type_byte
<<= kQuicStreamDataLengthShift
;
1857 type_byte
|= no_stream_frame_length
? 0: kQuicStreamDataLengthMask
;
1860 type_byte
<<= kQuicStreamOffsetShift
;
1861 const size_t offset_len
= GetStreamOffsetSize(frame
.stream_frame
->offset
);
1862 if (offset_len
> 0) {
1863 type_byte
|= offset_len
- 1;
1866 // stream id 2 bits.
1867 type_byte
<<= kQuicStreamIdShift
;
1868 type_byte
|= GetStreamIdSize(frame
.stream_frame
->stream_id
) - 1;
1869 type_byte
|= kQuicFrameTypeStreamMask
; // Set Stream Frame Type to 1.
1874 case CONGESTION_FEEDBACK_FRAME
: {
1875 // TODO(ianswett): Use extra 5 bits in the congestion feedback framing.
1876 type_byte
= kQuicFrameTypeCongestionFeedbackMask
;
1880 type_byte
= frame
.type
;
1884 return writer
->WriteUInt8(type_byte
);
1888 bool QuicFramer::AppendPacketSequenceNumber(
1889 QuicSequenceNumberLength sequence_number_length
,
1890 QuicPacketSequenceNumber packet_sequence_number
,
1891 QuicDataWriter
* writer
) {
1892 // Ensure the entire sequence number can be written.
1893 if (writer
->capacity() - writer
->length() <
1894 static_cast<size_t>(sequence_number_length
)) {
1897 switch (sequence_number_length
) {
1898 case PACKET_1BYTE_SEQUENCE_NUMBER
:
1899 return writer
->WriteUInt8(
1900 packet_sequence_number
& k1ByteSequenceNumberMask
);
1902 case PACKET_2BYTE_SEQUENCE_NUMBER
:
1903 return writer
->WriteUInt16(
1904 packet_sequence_number
& k2ByteSequenceNumberMask
);
1906 case PACKET_4BYTE_SEQUENCE_NUMBER
:
1907 return writer
->WriteUInt32(
1908 packet_sequence_number
& k4ByteSequenceNumberMask
);
1910 case PACKET_6BYTE_SEQUENCE_NUMBER
:
1911 return writer
->WriteUInt48(
1912 packet_sequence_number
& k6ByteSequenceNumberMask
);
1915 DCHECK(false) << "sequence_number_length: " << sequence_number_length
;
1920 bool QuicFramer::AppendStreamFrame(
1921 const QuicStreamFrame
& frame
,
1922 bool no_stream_frame_length
,
1923 QuicDataWriter
* writer
) {
1924 if (!writer
->WriteBytes(&frame
.stream_id
, GetStreamIdSize(frame
.stream_id
))) {
1925 LOG(DFATAL
) << "Writing stream id size failed.";
1928 if (!writer
->WriteBytes(&frame
.offset
, GetStreamOffsetSize(frame
.offset
))) {
1929 LOG(DFATAL
) << "Writing offset size failed.";
1932 if (!no_stream_frame_length
) {
1933 if (!writer
->WriteUInt16(frame
.data
.TotalBufferSize())) {
1934 LOG(DFATAL
) << "Writing stream frame length failed";
1939 if (!writer
->WriteIOVector(frame
.data
)) {
1940 LOG(DFATAL
) << "Writing frame data failed.";
1947 void QuicFramer::set_version(const QuicVersion version
) {
1948 DCHECK(IsSupportedVersion(version
)) << QuicVersionToString(version
);
1949 quic_version_
= version
;
1952 bool QuicFramer::AppendAckFrameAndTypeByte(
1953 const QuicPacketHeader
& header
,
1954 const QuicAckFrame
& frame
,
1955 QuicDataWriter
* writer
) {
1956 AckFrameInfo ack_info
= GetAckFrameInfo(frame
);
1957 QuicPacketSequenceNumber ack_largest_observed
= frame
.largest_observed
;
1958 QuicSequenceNumberLength largest_observed_length
=
1959 GetMinSequenceNumberLength(ack_largest_observed
);
1960 QuicSequenceNumberLength missing_sequence_number_length
=
1961 GetMinSequenceNumberLength(ack_info
.max_delta
);
1962 // Determine whether we need to truncate ranges.
1963 size_t available_range_bytes
= writer
->capacity() - writer
->length() -
1964 kNumberOfRevivedPacketsSize
- kNumberOfNackRangesSize
-
1965 GetMinAckFrameSize(header
.public_header
.sequence_number_length
,
1966 largest_observed_length
);
1967 size_t max_num_ranges
= available_range_bytes
/
1968 (missing_sequence_number_length
+ PACKET_1BYTE_SEQUENCE_NUMBER
);
1969 max_num_ranges
= min(kMaxNackRanges
, max_num_ranges
);
1970 bool truncated
= ack_info
.nack_ranges
.size() > max_num_ranges
;
1971 DVLOG_IF(1, truncated
) << "Truncating ack from "
1972 << ack_info
.nack_ranges
.size() << " ranges to "
1974 // Write out the type byte by setting the low order bits and doing shifts
1975 // to make room for the next bit flags to be set.
1976 // Whether there are any nacks.
1977 uint8 type_byte
= ack_info
.nack_ranges
.empty() ? 0 : kQuicHasNacksMask
;
1980 type_byte
<<= kQuicAckTruncatedShift
;
1981 type_byte
|= truncated
? kQuicAckTruncatedMask
: 0;
1983 // Largest observed sequence number length.
1984 type_byte
<<= kQuicSequenceNumberLengthShift
;
1985 type_byte
|= GetSequenceNumberFlags(largest_observed_length
);
1987 // Missing sequence number length.
1988 type_byte
<<= kQuicSequenceNumberLengthShift
;
1989 type_byte
|= GetSequenceNumberFlags(missing_sequence_number_length
);
1991 type_byte
|= kQuicFrameTypeAckMask
;
1993 if (!writer
->WriteUInt8(type_byte
)) {
1997 QuicPacketEntropyHash ack_entropy_hash
= frame
.entropy_hash
;
1998 NackRangeMap::reverse_iterator ack_iter
= ack_info
.nack_ranges
.rbegin();
2000 // Skip the nack ranges which the truncated ack won't include and set
2001 // a correct largest observed for the truncated ack.
2002 for (size_t i
= 1; i
< (ack_info
.nack_ranges
.size() - max_num_ranges
);
2006 // If the last range is followed by acks, include them.
2007 // If the last range is followed by another range, specify the end of the
2008 // range as the largest_observed.
2009 ack_largest_observed
= ack_iter
->first
- 1;
2010 // Also update the entropy so it matches the largest observed.
2011 ack_entropy_hash
= entropy_calculator_
->EntropyHash(ack_largest_observed
);
2015 if (!writer
->WriteUInt8(ack_entropy_hash
)) {
2019 if (!AppendPacketSequenceNumber(largest_observed_length
,
2020 ack_largest_observed
, writer
)) {
2024 uint64 delta_time_largest_observed_us
= kUFloat16MaxValue
;
2025 if (!frame
.delta_time_largest_observed
.IsInfinite()) {
2026 DCHECK_LE(0u, frame
.delta_time_largest_observed
.ToMicroseconds());
2027 delta_time_largest_observed_us
=
2028 frame
.delta_time_largest_observed
.ToMicroseconds();
2031 if (!writer
->WriteUFloat16(delta_time_largest_observed_us
)) {
2035 if (ack_info
.nack_ranges
.empty()) {
2039 const uint8 num_missing_ranges
=
2040 min(ack_info
.nack_ranges
.size(), max_num_ranges
);
2041 if (!writer
->WriteBytes(&num_missing_ranges
, 1)) {
2045 int num_ranges_written
= 0;
2046 QuicPacketSequenceNumber last_sequence_written
= ack_largest_observed
;
2047 for (; ack_iter
!= ack_info
.nack_ranges
.rend(); ++ack_iter
) {
2048 // Calculate the delta to the last number in the range.
2049 QuicPacketSequenceNumber missing_delta
=
2050 last_sequence_written
- (ack_iter
->first
+ ack_iter
->second
);
2051 if (!AppendPacketSequenceNumber(missing_sequence_number_length
,
2052 missing_delta
, writer
)) {
2055 if (!AppendPacketSequenceNumber(PACKET_1BYTE_SEQUENCE_NUMBER
,
2056 ack_iter
->second
, writer
)) {
2059 // Subtract 1 so a missing_delta of 0 means an adjacent range.
2060 last_sequence_written
= ack_iter
->first
- 1;
2061 ++num_ranges_written
;
2063 DCHECK_EQ(num_missing_ranges
, num_ranges_written
);
2065 // Append revived packets.
2066 // If not all the revived packets fit, only mention the ones that do.
2067 uint8 num_revived_packets
= min(frame
.revived_packets
.size(),
2068 kMaxRevivedPackets
);
2069 num_revived_packets
= min(
2070 static_cast<size_t>(num_revived_packets
),
2071 (writer
->capacity() - writer
->length()) / largest_observed_length
);
2072 if (!writer
->WriteBytes(&num_revived_packets
, 1)) {
2076 SequenceNumberSet::const_iterator iter
= frame
.revived_packets
.begin();
2077 for (int i
= 0; i
< num_revived_packets
; ++i
, ++iter
) {
2078 LOG_IF(DFATAL
, !ContainsKey(frame
.missing_packets
, *iter
));
2079 if (!AppendPacketSequenceNumber(largest_observed_length
,
2088 bool QuicFramer::AppendCongestionFeedbackFrame(
2089 const QuicCongestionFeedbackFrame
& frame
,
2090 QuicDataWriter
* writer
) {
2091 if (!writer
->WriteBytes(&frame
.type
, 1)) {
2095 switch (frame
.type
) {
2097 return AppendTimestampFrame(frame
, writer
);
2100 const CongestionFeedbackMessageTCP
& tcp
= frame
.tcp
;
2101 DCHECK_LE(tcp
.receive_window
, 1u << 20);
2102 // Simple bit packing, don't send the 4 least significant bits.
2103 uint16 receive_window
= static_cast<uint16
>(tcp
.receive_window
>> 4);
2104 if (!writer
->WriteUInt16(receive_window
)) {
2116 bool QuicFramer::AppendTimestampFrame(
2117 const QuicCongestionFeedbackFrame
& frame
,
2118 QuicDataWriter
* writer
) {
2119 const CongestionFeedbackMessageTimestamp
& timestamp
= frame
.timestamp
;
2120 DCHECK_GE(numeric_limits
<uint8
>::max(),
2121 timestamp
.received_packet_times
.size());
2122 if (timestamp
.received_packet_times
.size() > numeric_limits
<uint8
>::max()) {
2125 uint8 num_received_packets
= timestamp
.received_packet_times
.size();
2126 if (!writer
->WriteBytes(&num_received_packets
, 1)) {
2129 if (num_received_packets
> 0) {
2130 TimeMap::const_iterator it
= timestamp
.received_packet_times
.begin();
2132 QuicPacketSequenceNumber lowest_sequence
= it
->first
;
2133 if (!AppendPacketSequenceNumber(PACKET_6BYTE_SEQUENCE_NUMBER
,
2134 lowest_sequence
, writer
)) {
2138 QuicTime lowest_time
= it
->second
;
2139 if (!writer
->WriteUInt64(
2140 lowest_time
.Subtract(creation_time_
).ToMicroseconds())) {
2144 for (++it
; it
!= timestamp
.received_packet_times
.end(); ++it
) {
2145 QuicPacketSequenceNumber sequence_delta
= it
->first
- lowest_sequence
;
2146 DCHECK_GE(numeric_limits
<uint16
>::max(), sequence_delta
);
2147 if (sequence_delta
> numeric_limits
<uint16
>::max()) {
2150 if (!writer
->WriteUInt16(static_cast<uint16
>(sequence_delta
))) {
2154 int32 time_delta_us
= it
->second
.Subtract(lowest_time
).ToMicroseconds();
2155 if (!writer
->WriteBytes(&time_delta_us
, sizeof(time_delta_us
))) {
2163 bool QuicFramer::AppendStopWaitingFrame(
2164 const QuicPacketHeader
& header
,
2165 const QuicStopWaitingFrame
& frame
,
2166 QuicDataWriter
* writer
) {
2167 DCHECK_GE(header
.packet_sequence_number
, frame
.least_unacked
);
2168 const QuicPacketSequenceNumber least_unacked_delta
=
2169 header
.packet_sequence_number
- frame
.least_unacked
;
2170 const QuicPacketSequenceNumber length_shift
=
2171 header
.public_header
.sequence_number_length
* 8;
2172 if (!writer
->WriteUInt8(frame
.entropy_hash
)) {
2173 LOG(DFATAL
) << " hash failed";
2177 if (least_unacked_delta
>> length_shift
> 0) {
2178 LOG(DFATAL
) << "sequence_number_length "
2179 << header
.public_header
.sequence_number_length
2180 << " is too small for least_unacked_delta: "
2181 << least_unacked_delta
;
2184 if (!AppendPacketSequenceNumber(header
.public_header
.sequence_number_length
,
2185 least_unacked_delta
, writer
)) {
2186 LOG(DFATAL
) << " seq failed: "
2187 << header
.public_header
.sequence_number_length
;
2194 bool QuicFramer::AppendRstStreamFrame(
2195 const QuicRstStreamFrame
& frame
,
2196 QuicDataWriter
* writer
) {
2197 if (!writer
->WriteUInt32(frame
.stream_id
)) {
2201 if (!writer
->WriteUInt64(frame
.byte_offset
)) {
2205 uint32 error_code
= static_cast<uint32
>(frame
.error_code
);
2206 if (!writer
->WriteUInt32(error_code
)) {
2210 if (!writer
->WriteStringPiece16(frame
.error_details
)) {
2216 bool QuicFramer::AppendConnectionCloseFrame(
2217 const QuicConnectionCloseFrame
& frame
,
2218 QuicDataWriter
* writer
) {
2219 uint32 error_code
= static_cast<uint32
>(frame
.error_code
);
2220 if (!writer
->WriteUInt32(error_code
)) {
2223 if (!writer
->WriteStringPiece16(frame
.error_details
)) {
2229 bool QuicFramer::AppendGoAwayFrame(const QuicGoAwayFrame
& frame
,
2230 QuicDataWriter
* writer
) {
2231 uint32 error_code
= static_cast<uint32
>(frame
.error_code
);
2232 if (!writer
->WriteUInt32(error_code
)) {
2235 uint32 stream_id
= static_cast<uint32
>(frame
.last_good_stream_id
);
2236 if (!writer
->WriteUInt32(stream_id
)) {
2239 if (!writer
->WriteStringPiece16(frame
.reason_phrase
)) {
2245 bool QuicFramer::AppendWindowUpdateFrame(const QuicWindowUpdateFrame
& frame
,
2246 QuicDataWriter
* writer
) {
2247 uint32 stream_id
= static_cast<uint32
>(frame
.stream_id
);
2248 if (!writer
->WriteUInt32(stream_id
)) {
2251 if (!writer
->WriteUInt64(frame
.byte_offset
)) {
2257 bool QuicFramer::AppendBlockedFrame(const QuicBlockedFrame
& frame
,
2258 QuicDataWriter
* writer
) {
2259 uint32 stream_id
= static_cast<uint32
>(frame
.stream_id
);
2260 if (!writer
->WriteUInt32(stream_id
)) {
2266 bool QuicFramer::RaiseError(QuicErrorCode error
) {
2267 DVLOG(1) << "Error detail: " << detailed_error_
;
2269 visitor_
->OnError(this);
2270 reader_
.reset(NULL
);