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
;
137 bool QuicFramerVisitorInterface::OnWindowUpdateFrame(
138 const QuicWindowUpdateFrame
& frame
) {
142 bool QuicFramerVisitorInterface::OnBlockedFrame(const QuicBlockedFrame
& frame
) {
146 QuicFramer::QuicFramer(const QuicVersionVector
& supported_versions
,
147 QuicTime creation_time
,
150 fec_builder_(nullptr),
151 entropy_calculator_(nullptr),
152 error_(QUIC_NO_ERROR
),
153 last_sequence_number_(0),
154 last_serialized_connection_id_(0),
155 supported_versions_(supported_versions
),
156 decrypter_level_(ENCRYPTION_NONE
),
157 alternative_decrypter_level_(ENCRYPTION_NONE
),
158 alternative_decrypter_latch_(false),
159 is_server_(is_server
),
160 validate_flags_(true),
161 creation_time_(creation_time
),
162 last_timestamp_(QuicTime::Delta::Zero()) {
163 DCHECK(!supported_versions
.empty());
164 quic_version_
= supported_versions_
[0];
165 decrypter_
.reset(QuicDecrypter::Create(kNULL
));
166 encrypter_
[ENCRYPTION_NONE
].reset(QuicEncrypter::Create(kNULL
));
169 QuicFramer::~QuicFramer() {}
172 size_t QuicFramer::GetMinStreamFrameSize(QuicStreamId stream_id
,
173 QuicStreamOffset offset
,
174 bool last_frame_in_packet
,
175 InFecGroup is_in_fec_group
) {
176 bool no_stream_frame_length
= last_frame_in_packet
&&
177 is_in_fec_group
== NOT_IN_FEC_GROUP
;
178 return kQuicFrameTypeSize
+ GetStreamIdSize(stream_id
) +
179 GetStreamOffsetSize(offset
) +
180 (no_stream_frame_length
? 0 : kQuicStreamPayloadLengthSize
);
184 size_t QuicFramer::GetMinAckFrameSize(
185 QuicSequenceNumberLength sequence_number_length
,
186 QuicSequenceNumberLength largest_observed_length
) {
187 return kQuicFrameTypeSize
+ kQuicEntropyHashSize
+
188 largest_observed_length
+ kQuicDeltaTimeLargestObservedSize
;
192 size_t QuicFramer::GetStopWaitingFrameSize(
193 QuicSequenceNumberLength sequence_number_length
) {
194 return kQuicFrameTypeSize
+ kQuicEntropyHashSize
+
195 sequence_number_length
;
199 size_t QuicFramer::GetMinRstStreamFrameSize() {
200 return kQuicFrameTypeSize
+ kQuicMaxStreamIdSize
+
201 kQuicMaxStreamOffsetSize
+ kQuicErrorCodeSize
+
202 kQuicErrorDetailsLengthSize
;
206 size_t QuicFramer::GetMinConnectionCloseFrameSize() {
207 return kQuicFrameTypeSize
+ kQuicErrorCodeSize
+ kQuicErrorDetailsLengthSize
;
211 size_t QuicFramer::GetMinGoAwayFrameSize() {
212 return kQuicFrameTypeSize
+ kQuicErrorCodeSize
+ kQuicErrorDetailsLengthSize
+
213 kQuicMaxStreamIdSize
;
217 size_t QuicFramer::GetWindowUpdateFrameSize() {
218 return kQuicFrameTypeSize
+ kQuicMaxStreamIdSize
+ kQuicMaxStreamOffsetSize
;
222 size_t QuicFramer::GetBlockedFrameSize() {
223 return kQuicFrameTypeSize
+ kQuicMaxStreamIdSize
;
227 size_t QuicFramer::GetStreamIdSize(QuicStreamId stream_id
) {
228 // Sizes are 1 through 4 bytes.
229 for (int i
= 1; i
<= 4; ++i
) {
231 if (stream_id
== 0) {
235 LOG(DFATAL
) << "Failed to determine StreamIDSize.";
240 size_t QuicFramer::GetStreamOffsetSize(QuicStreamOffset offset
) {
241 // 0 is a special case.
245 // 2 through 8 are the remaining sizes.
247 for (int i
= 2; i
<= 8; ++i
) {
253 LOG(DFATAL
) << "Failed to determine StreamOffsetSize.";
258 size_t QuicFramer::GetVersionNegotiationPacketSize(size_t number_versions
) {
259 return kPublicFlagsSize
+ PACKET_8BYTE_CONNECTION_ID
+
260 number_versions
* kQuicVersionSize
;
263 bool QuicFramer::IsSupportedVersion(const QuicVersion version
) const {
264 for (size_t i
= 0; i
< supported_versions_
.size(); ++i
) {
265 if (version
== supported_versions_
[i
]) {
272 size_t QuicFramer::GetSerializedFrameLength(
273 const QuicFrame
& frame
,
277 InFecGroup is_in_fec_group
,
278 QuicSequenceNumberLength sequence_number_length
) {
279 if (frame
.type
== PADDING_FRAME
) {
280 // PADDING implies end of packet.
284 ComputeFrameLength(frame
, last_frame
, is_in_fec_group
,
285 sequence_number_length
);
286 if (frame_len
<= free_bytes
) {
287 // Frame fits within packet. Note that acks may be truncated.
290 // Only truncate the first frame in a packet, so if subsequent ones go
291 // over, stop including more frames.
295 bool can_truncate
= frame
.type
== ACK_FRAME
&&
296 free_bytes
>= GetMinAckFrameSize(PACKET_6BYTE_SEQUENCE_NUMBER
,
297 PACKET_6BYTE_SEQUENCE_NUMBER
);
299 // Truncate the frame so the packet will not exceed kMaxPacketSize.
300 // Note that we may not use every byte of the writer in this case.
301 DVLOG(1) << "Truncating large frame, free bytes: " << free_bytes
;
304 if (!FLAGS_quic_allow_oversized_packets_for_test
) {
307 LOG(DFATAL
) << "Packet size too small to fit frame.";
311 QuicFramer::AckFrameInfo::AckFrameInfo() : max_delta(0) {}
313 QuicFramer::AckFrameInfo::~AckFrameInfo() {}
315 QuicPacketEntropyHash
QuicFramer::GetPacketEntropyHash(
316 const QuicPacketHeader
& header
) const {
317 return header
.entropy_flag
<< (header
.packet_sequence_number
% 8);
320 SerializedPacket
QuicFramer::BuildDataPacket(
321 const QuicPacketHeader
& header
,
322 const QuicFrames
& frames
,
323 size_t packet_size
) {
324 QuicDataWriter
writer(packet_size
);
325 const SerializedPacket
kNoPacket(0, PACKET_1BYTE_SEQUENCE_NUMBER
, nullptr, 0,
327 if (!AppendPacketHeader(header
, &writer
)) {
328 LOG(DFATAL
) << "AppendPacketHeader failed";
332 for (size_t i
= 0; i
< frames
.size(); ++i
) {
333 const QuicFrame
& frame
= frames
[i
];
335 // Determine if we should write stream frame length in header.
336 const bool no_stream_frame_length
=
337 (header
.is_in_fec_group
== NOT_IN_FEC_GROUP
) &&
338 (i
== frames
.size() - 1);
339 if (!AppendTypeByte(frame
, no_stream_frame_length
, &writer
)) {
340 LOG(DFATAL
) << "AppendTypeByte failed";
344 switch (frame
.type
) {
346 writer
.WritePadding();
349 if (!AppendStreamFrame(
350 *frame
.stream_frame
, no_stream_frame_length
, &writer
)) {
351 LOG(DFATAL
) << "AppendStreamFrame failed";
356 if (!AppendAckFrameAndTypeByte(
357 header
, *frame
.ack_frame
, &writer
)) {
358 LOG(DFATAL
) << "AppendAckFrameAndTypeByte failed";
362 case CONGESTION_FEEDBACK_FRAME
:
363 if (!AppendCongestionFeedbackFrame(
364 *frame
.congestion_feedback_frame
, &writer
)) {
365 LOG(DFATAL
) << "AppendCongestionFeedbackFrame failed";
369 case STOP_WAITING_FRAME
:
370 if (!AppendStopWaitingFrame(
371 header
, *frame
.stop_waiting_frame
, &writer
)) {
372 LOG(DFATAL
) << "AppendStopWaitingFrame failed";
377 // Ping has no payload.
379 case RST_STREAM_FRAME
:
380 if (!AppendRstStreamFrame(*frame
.rst_stream_frame
, &writer
)) {
381 LOG(DFATAL
) << "AppendRstStreamFrame failed";
385 case CONNECTION_CLOSE_FRAME
:
386 if (!AppendConnectionCloseFrame(
387 *frame
.connection_close_frame
, &writer
)) {
388 LOG(DFATAL
) << "AppendConnectionCloseFrame failed";
393 if (!AppendGoAwayFrame(*frame
.goaway_frame
, &writer
)) {
394 LOG(DFATAL
) << "AppendGoAwayFrame failed";
398 case WINDOW_UPDATE_FRAME
:
399 if (!AppendWindowUpdateFrame(*frame
.window_update_frame
, &writer
)) {
400 LOG(DFATAL
) << "AppendWindowUpdateFrame failed";
405 if (!AppendBlockedFrame(*frame
.blocked_frame
, &writer
)) {
406 LOG(DFATAL
) << "AppendBlockedFrame failed";
411 RaiseError(QUIC_INVALID_FRAME_DATA
);
412 LOG(DFATAL
) << "QUIC_INVALID_FRAME_DATA";
417 // Save the length before writing, because take clears it.
418 const size_t len
= writer
.length();
419 // Less than or equal because truncated acks end up with max_plaintex_size
420 // length, even though they're typically slightly shorter.
421 DCHECK_LE(len
, packet_size
);
422 QuicPacket
* packet
= QuicPacket::NewDataPacket(
423 writer
.take(), len
, true, header
.public_header
.connection_id_length
,
424 header
.public_header
.version_flag
,
425 header
.public_header
.sequence_number_length
);
428 fec_builder_
->OnBuiltFecProtectedPayload(header
,
429 packet
->FecProtectedData());
432 return SerializedPacket(header
.packet_sequence_number
,
433 header
.public_header
.sequence_number_length
, packet
,
434 GetPacketEntropyHash(header
), nullptr);
437 SerializedPacket
QuicFramer::BuildFecPacket(const QuicPacketHeader
& header
,
438 const QuicFecData
& fec
) {
439 DCHECK_EQ(IN_FEC_GROUP
, header
.is_in_fec_group
);
440 DCHECK_NE(0u, header
.fec_group
);
441 size_t len
= GetPacketHeaderSize(header
);
442 len
+= fec
.redundancy
.length();
444 QuicDataWriter
writer(len
);
445 const SerializedPacket
kNoPacket(0, PACKET_1BYTE_SEQUENCE_NUMBER
, nullptr, 0,
447 if (!AppendPacketHeader(header
, &writer
)) {
448 LOG(DFATAL
) << "AppendPacketHeader failed";
452 if (!writer
.WriteBytes(fec
.redundancy
.data(), fec
.redundancy
.length())) {
453 LOG(DFATAL
) << "Failed to add FEC";
457 return SerializedPacket(
458 header
.packet_sequence_number
,
459 header
.public_header
.sequence_number_length
,
460 QuicPacket::NewFecPacket(writer
.take(), len
, true,
461 header
.public_header
.connection_id_length
,
462 header
.public_header
.version_flag
,
463 header
.public_header
.sequence_number_length
),
464 GetPacketEntropyHash(header
), nullptr);
468 QuicEncryptedPacket
* QuicFramer::BuildPublicResetPacket(
469 const QuicPublicResetPacket
& packet
) {
470 DCHECK(packet
.public_header
.reset_flag
);
472 CryptoHandshakeMessage reset
;
473 reset
.set_tag(kPRST
);
474 reset
.SetValue(kRNON
, packet
.nonce_proof
);
475 reset
.SetValue(kRSEQ
, packet
.rejected_sequence_number
);
476 if (!packet
.client_address
.address().empty()) {
477 // packet.client_address is non-empty.
478 QuicSocketAddressCoder
address_coder(packet
.client_address
);
479 string serialized_address
= address_coder
.Encode();
480 if (serialized_address
.empty()) {
483 reset
.SetStringPiece(kCADR
, serialized_address
);
485 const QuicData
& reset_serialized
= reset
.GetSerialized();
488 kPublicFlagsSize
+ PACKET_8BYTE_CONNECTION_ID
+ reset_serialized
.length();
489 QuicDataWriter
writer(len
);
491 uint8 flags
= static_cast<uint8
>(PACKET_PUBLIC_FLAGS_RST
|
492 PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID
);
493 if (!writer
.WriteUInt8(flags
)) {
497 if (!writer
.WriteUInt64(packet
.public_header
.connection_id
)) {
501 if (!writer
.WriteBytes(reset_serialized
.data(), reset_serialized
.length())) {
505 return new QuicEncryptedPacket(writer
.take(), len
, true);
508 QuicEncryptedPacket
* QuicFramer::BuildVersionNegotiationPacket(
509 const QuicPacketPublicHeader
& header
,
510 const QuicVersionVector
& supported_versions
) {
511 DCHECK(header
.version_flag
);
512 size_t len
= GetVersionNegotiationPacketSize(supported_versions
.size());
513 QuicDataWriter
writer(len
);
515 uint8 flags
= static_cast<uint8
>(PACKET_PUBLIC_FLAGS_VERSION
|
516 PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID
);
517 if (!writer
.WriteUInt8(flags
)) {
521 if (!writer
.WriteUInt64(header
.connection_id
)) {
525 for (size_t i
= 0; i
< supported_versions
.size(); ++i
) {
526 if (!writer
.WriteUInt32(QuicVersionToQuicTag(supported_versions
[i
]))) {
531 return new QuicEncryptedPacket(writer
.take(), len
, true);
534 bool QuicFramer::ProcessPacket(const QuicEncryptedPacket
& packet
) {
535 DCHECK(!reader_
.get());
536 reader_
.reset(new QuicDataReader(packet
.data(), packet
.length()));
538 visitor_
->OnPacket();
540 // First parse the public header.
541 QuicPacketPublicHeader public_header
;
542 if (!ProcessPublicHeader(&public_header
)) {
543 DLOG(WARNING
) << "Unable to process public header.";
544 DCHECK_NE("", detailed_error_
);
545 return RaiseError(QUIC_INVALID_PACKET_HEADER
);
548 if (!visitor_
->OnUnauthenticatedPublicHeader(public_header
)) {
549 // The visitor suppresses further processing of the packet.
550 reader_
.reset(nullptr);
554 if (is_server_
&& public_header
.version_flag
&&
555 public_header
.versions
[0] != quic_version_
) {
556 if (!visitor_
->OnProtocolVersionMismatch(public_header
.versions
[0])) {
557 reader_
.reset(nullptr);
563 if (!is_server_
&& public_header
.version_flag
) {
564 rv
= ProcessVersionNegotiationPacket(&public_header
);
565 } else if (public_header
.reset_flag
) {
566 rv
= ProcessPublicResetPacket(public_header
);
568 rv
= ProcessDataPacket(public_header
, packet
);
571 reader_
.reset(nullptr);
575 bool QuicFramer::ProcessVersionNegotiationPacket(
576 QuicPacketPublicHeader
* public_header
) {
578 // Try reading at least once to raise error if the packet is invalid.
581 if (!reader_
->ReadBytes(&version
, kQuicVersionSize
)) {
582 set_detailed_error("Unable to read supported version in negotiation.");
583 return RaiseError(QUIC_INVALID_VERSION_NEGOTIATION_PACKET
);
585 public_header
->versions
.push_back(QuicTagToQuicVersion(version
));
586 } while (!reader_
->IsDoneReading());
588 visitor_
->OnVersionNegotiationPacket(*public_header
);
592 bool QuicFramer::ProcessDataPacket(
593 const QuicPacketPublicHeader
& public_header
,
594 const QuicEncryptedPacket
& packet
) {
595 QuicPacketHeader
header(public_header
);
596 if (!ProcessPacketHeader(&header
, packet
)) {
597 DLOG(WARNING
) << "Unable to process data packet header.";
601 if (!visitor_
->OnPacketHeader(header
)) {
602 // The visitor suppresses further processing of the packet.
606 if (packet
.length() > kMaxPacketSize
) {
607 DLOG(WARNING
) << "Packet too large: " << packet
.length();
608 return RaiseError(QUIC_PACKET_TOO_LARGE
);
611 // Handle the payload.
612 if (!header
.fec_flag
) {
613 if (header
.is_in_fec_group
== IN_FEC_GROUP
) {
614 StringPiece payload
= reader_
->PeekRemainingPayload();
615 visitor_
->OnFecProtectedPayload(payload
);
617 if (!ProcessFrameData(header
)) {
618 DCHECK_NE(QUIC_NO_ERROR
, error_
); // ProcessFrameData sets the error.
619 DLOG(WARNING
) << "Unable to process frame data.";
623 QuicFecData fec_data
;
624 fec_data
.fec_group
= header
.fec_group
;
625 fec_data
.redundancy
= reader_
->ReadRemainingPayload();
626 visitor_
->OnFecData(fec_data
);
629 visitor_
->OnPacketComplete();
633 bool QuicFramer::ProcessPublicResetPacket(
634 const QuicPacketPublicHeader
& public_header
) {
635 QuicPublicResetPacket
packet(public_header
);
637 scoped_ptr
<CryptoHandshakeMessage
> reset(
638 CryptoFramer::ParseMessage(reader_
->ReadRemainingPayload()));
640 set_detailed_error("Unable to read reset message.");
641 return RaiseError(QUIC_INVALID_PUBLIC_RST_PACKET
);
643 if (reset
->tag() != kPRST
) {
644 set_detailed_error("Incorrect message tag.");
645 return RaiseError(QUIC_INVALID_PUBLIC_RST_PACKET
);
648 if (reset
->GetUint64(kRNON
, &packet
.nonce_proof
) != QUIC_NO_ERROR
) {
649 set_detailed_error("Unable to read nonce proof.");
650 return RaiseError(QUIC_INVALID_PUBLIC_RST_PACKET
);
652 // TODO(satyamshekhar): validate nonce to protect against DoS.
654 if (reset
->GetUint64(kRSEQ
, &packet
.rejected_sequence_number
) !=
656 set_detailed_error("Unable to read rejected sequence number.");
657 return RaiseError(QUIC_INVALID_PUBLIC_RST_PACKET
);
661 if (reset
->GetStringPiece(kCADR
, &address
)) {
662 QuicSocketAddressCoder address_coder
;
663 if (address_coder
.Decode(address
.data(), address
.length())) {
664 packet
.client_address
= IPEndPoint(address_coder
.ip(),
665 address_coder
.port());
669 visitor_
->OnPublicResetPacket(packet
);
673 bool QuicFramer::ProcessRevivedPacket(QuicPacketHeader
* header
,
674 StringPiece payload
) {
675 DCHECK(!reader_
.get());
677 visitor_
->OnRevivedPacket();
679 header
->entropy_hash
= GetPacketEntropyHash(*header
);
681 if (!visitor_
->OnPacketHeader(*header
)) {
685 if (payload
.length() > kMaxPacketSize
) {
686 set_detailed_error("Revived packet too large.");
687 return RaiseError(QUIC_PACKET_TOO_LARGE
);
690 reader_
.reset(new QuicDataReader(payload
.data(), payload
.length()));
691 if (!ProcessFrameData(*header
)) {
692 DCHECK_NE(QUIC_NO_ERROR
, error_
); // ProcessFrameData sets the error.
693 DLOG(WARNING
) << "Unable to process frame data.";
697 visitor_
->OnPacketComplete();
698 reader_
.reset(nullptr);
702 bool QuicFramer::AppendPacketHeader(const QuicPacketHeader
& header
,
703 QuicDataWriter
* writer
) {
704 DVLOG(1) << "Appending header: " << header
;
705 DCHECK(header
.fec_group
> 0 || header
.is_in_fec_group
== NOT_IN_FEC_GROUP
);
706 uint8 public_flags
= 0;
707 if (header
.public_header
.reset_flag
) {
708 public_flags
|= PACKET_PUBLIC_FLAGS_RST
;
710 if (header
.public_header
.version_flag
) {
711 public_flags
|= PACKET_PUBLIC_FLAGS_VERSION
;
715 GetSequenceNumberFlags(header
.public_header
.sequence_number_length
)
716 << kPublicHeaderSequenceNumberShift
;
718 switch (header
.public_header
.connection_id_length
) {
719 case PACKET_0BYTE_CONNECTION_ID
:
720 if (!writer
->WriteUInt8(
721 public_flags
| PACKET_PUBLIC_FLAGS_0BYTE_CONNECTION_ID
)) {
725 case PACKET_1BYTE_CONNECTION_ID
:
726 if (!writer
->WriteUInt8(
727 public_flags
| PACKET_PUBLIC_FLAGS_1BYTE_CONNECTION_ID
)) {
730 if (!writer
->WriteUInt8(
731 header
.public_header
.connection_id
& k1ByteConnectionIdMask
)) {
735 case PACKET_4BYTE_CONNECTION_ID
:
736 if (!writer
->WriteUInt8(
737 public_flags
| PACKET_PUBLIC_FLAGS_4BYTE_CONNECTION_ID
)) {
740 if (!writer
->WriteUInt32(
741 header
.public_header
.connection_id
& k4ByteConnectionIdMask
)) {
745 case PACKET_8BYTE_CONNECTION_ID
:
746 if (!writer
->WriteUInt8(
747 public_flags
| PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID
)) {
750 if (!writer
->WriteUInt64(header
.public_header
.connection_id
)) {
755 last_serialized_connection_id_
= header
.public_header
.connection_id
;
757 if (header
.public_header
.version_flag
) {
759 writer
->WriteUInt32(QuicVersionToQuicTag(quic_version_
));
762 if (!AppendPacketSequenceNumber(header
.public_header
.sequence_number_length
,
763 header
.packet_sequence_number
, writer
)) {
767 uint8 private_flags
= 0;
768 if (header
.entropy_flag
) {
769 private_flags
|= PACKET_PRIVATE_FLAGS_ENTROPY
;
771 if (header
.is_in_fec_group
== IN_FEC_GROUP
) {
772 private_flags
|= PACKET_PRIVATE_FLAGS_FEC_GROUP
;
774 if (header
.fec_flag
) {
775 private_flags
|= PACKET_PRIVATE_FLAGS_FEC
;
777 if (!writer
->WriteUInt8(private_flags
)) {
781 // The FEC group number is the sequence number of the first fec
782 // protected packet, or 0 if this packet is not protected.
783 if (header
.is_in_fec_group
== IN_FEC_GROUP
) {
784 DCHECK_LE(header
.fec_group
, header
.packet_sequence_number
);
785 DCHECK_LT(header
.packet_sequence_number
- header
.fec_group
, 255u);
786 // Offset from the current packet sequence number to the first fec
788 uint8 first_fec_protected_packet_offset
=
789 static_cast<uint8
>(header
.packet_sequence_number
- header
.fec_group
);
790 if (!writer
->WriteBytes(&first_fec_protected_packet_offset
, 1)) {
798 const QuicTime::Delta
QuicFramer::CalculateTimestampFromWire(
799 uint32 time_delta_us
) {
800 // The new time_delta might have wrapped to the next epoch, or it
801 // might have reverse wrapped to the previous epoch, or it might
802 // remain in the same epoch. Select the time closest to the previous
805 // epoch_delta is the delta between epochs. A delta is 4 bytes of
807 const uint64 epoch_delta
= GG_UINT64_C(1) << 32;
808 uint64 epoch
= last_timestamp_
.ToMicroseconds() & ~(epoch_delta
- 1);
809 // Wrapping is safe here because a wrapped value will not be ClosestTo below.
810 uint64 prev_epoch
= epoch
- epoch_delta
;
811 uint64 next_epoch
= epoch
+ epoch_delta
;
813 uint64 time
= ClosestTo(last_timestamp_
.ToMicroseconds(),
814 epoch
+ time_delta_us
,
815 ClosestTo(last_timestamp_
.ToMicroseconds(),
816 prev_epoch
+ time_delta_us
,
817 next_epoch
+ time_delta_us
));
819 return QuicTime::Delta::FromMicroseconds(time
);
822 QuicPacketSequenceNumber
QuicFramer::CalculatePacketSequenceNumberFromWire(
823 QuicSequenceNumberLength sequence_number_length
,
824 QuicPacketSequenceNumber packet_sequence_number
) const {
825 // The new sequence number might have wrapped to the next epoch, or
826 // it might have reverse wrapped to the previous epoch, or it might
827 // remain in the same epoch. Select the sequence number closest to the
828 // next expected sequence number, the previous sequence number plus 1.
830 // epoch_delta is the delta between epochs the sequence number was serialized
831 // with, so the correct value is likely the same epoch as the last sequence
832 // number or an adjacent epoch.
833 const QuicPacketSequenceNumber epoch_delta
=
834 GG_UINT64_C(1) << (8 * sequence_number_length
);
835 QuicPacketSequenceNumber next_sequence_number
= last_sequence_number_
+ 1;
836 QuicPacketSequenceNumber epoch
= last_sequence_number_
& ~(epoch_delta
- 1);
837 QuicPacketSequenceNumber prev_epoch
= epoch
- epoch_delta
;
838 QuicPacketSequenceNumber next_epoch
= epoch
+ epoch_delta
;
840 return ClosestTo(next_sequence_number
,
841 epoch
+ packet_sequence_number
,
842 ClosestTo(next_sequence_number
,
843 prev_epoch
+ packet_sequence_number
,
844 next_epoch
+ packet_sequence_number
));
847 bool QuicFramer::ProcessPublicHeader(
848 QuicPacketPublicHeader
* public_header
) {
850 if (!reader_
->ReadBytes(&public_flags
, 1)) {
851 set_detailed_error("Unable to read public flags.");
855 public_header
->reset_flag
= (public_flags
& PACKET_PUBLIC_FLAGS_RST
) != 0;
856 public_header
->version_flag
=
857 (public_flags
& PACKET_PUBLIC_FLAGS_VERSION
) != 0;
859 if (validate_flags_
&&
860 !public_header
->version_flag
&& public_flags
> PACKET_PUBLIC_FLAGS_MAX
) {
861 set_detailed_error("Illegal public flags value.");
865 if (public_header
->reset_flag
&& public_header
->version_flag
) {
866 set_detailed_error("Got version flag in reset packet");
870 switch (public_flags
& PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID
) {
871 case PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID
:
872 if (!reader_
->ReadUInt64(&public_header
->connection_id
)) {
873 set_detailed_error("Unable to read ConnectionId.");
876 public_header
->connection_id_length
= PACKET_8BYTE_CONNECTION_ID
;
878 case PACKET_PUBLIC_FLAGS_4BYTE_CONNECTION_ID
:
879 // If the connection_id is truncated, expect to read the last serialized
881 if (!reader_
->ReadBytes(&public_header
->connection_id
,
882 PACKET_4BYTE_CONNECTION_ID
)) {
883 set_detailed_error("Unable to read ConnectionId.");
886 if (last_serialized_connection_id_
&&
887 (public_header
->connection_id
& k4ByteConnectionIdMask
) !=
888 (last_serialized_connection_id_
& k4ByteConnectionIdMask
)) {
889 set_detailed_error("Truncated 4 byte ConnectionId does not match "
890 "previous connection_id.");
893 public_header
->connection_id_length
= PACKET_4BYTE_CONNECTION_ID
;
894 public_header
->connection_id
= last_serialized_connection_id_
;
896 case PACKET_PUBLIC_FLAGS_1BYTE_CONNECTION_ID
:
897 if (!reader_
->ReadBytes(&public_header
->connection_id
,
898 PACKET_1BYTE_CONNECTION_ID
)) {
899 set_detailed_error("Unable to read ConnectionId.");
902 if (last_serialized_connection_id_
&&
903 (public_header
->connection_id
& k1ByteConnectionIdMask
) !=
904 (last_serialized_connection_id_
& k1ByteConnectionIdMask
)) {
905 set_detailed_error("Truncated 1 byte ConnectionId does not match "
906 "previous connection_id.");
909 public_header
->connection_id_length
= PACKET_1BYTE_CONNECTION_ID
;
910 public_header
->connection_id
= last_serialized_connection_id_
;
912 case PACKET_PUBLIC_FLAGS_0BYTE_CONNECTION_ID
:
913 public_header
->connection_id_length
= PACKET_0BYTE_CONNECTION_ID
;
914 public_header
->connection_id
= last_serialized_connection_id_
;
918 public_header
->sequence_number_length
=
919 ReadSequenceNumberLength(
920 public_flags
>> kPublicHeaderSequenceNumberShift
);
922 // Read the version only if the packet is from the client.
923 // version flag from the server means version negotiation packet.
924 if (public_header
->version_flag
&& is_server_
) {
926 if (!reader_
->ReadUInt32(&version_tag
)) {
927 set_detailed_error("Unable to read protocol version.");
931 // If the version from the new packet is the same as the version of this
932 // framer, then the public flags should be set to something we understand.
933 // If not, this raises an error.
934 QuicVersion version
= QuicTagToQuicVersion(version_tag
);
935 if (version
== quic_version_
&& public_flags
> PACKET_PUBLIC_FLAGS_MAX
) {
936 set_detailed_error("Illegal public flags value.");
939 public_header
->versions
.push_back(version
);
945 QuicSequenceNumberLength
QuicFramer::GetMinSequenceNumberLength(
946 QuicPacketSequenceNumber sequence_number
) {
947 if (sequence_number
< 1 << (PACKET_1BYTE_SEQUENCE_NUMBER
* 8)) {
948 return PACKET_1BYTE_SEQUENCE_NUMBER
;
949 } else if (sequence_number
< 1 << (PACKET_2BYTE_SEQUENCE_NUMBER
* 8)) {
950 return PACKET_2BYTE_SEQUENCE_NUMBER
;
951 } else if (sequence_number
<
952 GG_UINT64_C(1) << (PACKET_4BYTE_SEQUENCE_NUMBER
* 8)) {
953 return PACKET_4BYTE_SEQUENCE_NUMBER
;
955 return PACKET_6BYTE_SEQUENCE_NUMBER
;
960 uint8
QuicFramer::GetSequenceNumberFlags(
961 QuicSequenceNumberLength sequence_number_length
) {
962 switch (sequence_number_length
) {
963 case PACKET_1BYTE_SEQUENCE_NUMBER
:
964 return PACKET_FLAGS_1BYTE_SEQUENCE
;
965 case PACKET_2BYTE_SEQUENCE_NUMBER
:
966 return PACKET_FLAGS_2BYTE_SEQUENCE
;
967 case PACKET_4BYTE_SEQUENCE_NUMBER
:
968 return PACKET_FLAGS_4BYTE_SEQUENCE
;
969 case PACKET_6BYTE_SEQUENCE_NUMBER
:
970 return PACKET_FLAGS_6BYTE_SEQUENCE
;
972 LOG(DFATAL
) << "Unreachable case statement.";
973 return PACKET_FLAGS_6BYTE_SEQUENCE
;
978 QuicFramer::AckFrameInfo
QuicFramer::GetAckFrameInfo(
979 const QuicAckFrame
& frame
) {
980 AckFrameInfo ack_info
;
981 if (frame
.missing_packets
.empty()) {
984 DCHECK_GE(frame
.largest_observed
, *frame
.missing_packets
.rbegin());
985 size_t cur_range_length
= 0;
986 SequenceNumberSet::const_iterator iter
= frame
.missing_packets
.begin();
987 QuicPacketSequenceNumber last_missing
= *iter
;
989 for (; iter
!= frame
.missing_packets
.end(); ++iter
) {
990 if (cur_range_length
< numeric_limits
<uint8
>::max() &&
991 *iter
== (last_missing
+ 1)) {
994 ack_info
.nack_ranges
[last_missing
- cur_range_length
] =
995 static_cast<uint8
>(cur_range_length
);
996 cur_range_length
= 0;
998 ack_info
.max_delta
= max(ack_info
.max_delta
, *iter
- last_missing
);
999 last_missing
= *iter
;
1001 // Include the last nack range.
1002 ack_info
.nack_ranges
[last_missing
- cur_range_length
] =
1003 static_cast<uint8
>(cur_range_length
);
1004 // Include the range to the largest observed.
1005 ack_info
.max_delta
=
1006 max(ack_info
.max_delta
, frame
.largest_observed
- last_missing
);
1010 bool QuicFramer::ProcessPacketHeader(
1011 QuicPacketHeader
* header
,
1012 const QuicEncryptedPacket
& packet
) {
1013 if (!ProcessPacketSequenceNumber(header
->public_header
.sequence_number_length
,
1014 &header
->packet_sequence_number
)) {
1015 set_detailed_error("Unable to read sequence number.");
1016 return RaiseError(QUIC_INVALID_PACKET_HEADER
);
1019 if (header
->packet_sequence_number
== 0u) {
1020 set_detailed_error("Packet sequence numbers cannot be 0.");
1021 return RaiseError(QUIC_INVALID_PACKET_HEADER
);
1024 if (!visitor_
->OnUnauthenticatedHeader(*header
)) {
1028 if (!DecryptPayload(*header
, packet
)) {
1029 set_detailed_error("Unable to decrypt payload.");
1030 return RaiseError(QUIC_DECRYPTION_FAILURE
);
1033 uint8 private_flags
;
1034 if (!reader_
->ReadBytes(&private_flags
, 1)) {
1035 set_detailed_error("Unable to read private flags.");
1036 return RaiseError(QUIC_INVALID_PACKET_HEADER
);
1039 if (private_flags
> PACKET_PRIVATE_FLAGS_MAX
) {
1040 set_detailed_error("Illegal private flags value.");
1041 return RaiseError(QUIC_INVALID_PACKET_HEADER
);
1044 header
->entropy_flag
= (private_flags
& PACKET_PRIVATE_FLAGS_ENTROPY
) != 0;
1045 header
->fec_flag
= (private_flags
& PACKET_PRIVATE_FLAGS_FEC
) != 0;
1047 if ((private_flags
& PACKET_PRIVATE_FLAGS_FEC_GROUP
) != 0) {
1048 header
->is_in_fec_group
= IN_FEC_GROUP
;
1049 uint8 first_fec_protected_packet_offset
;
1050 if (!reader_
->ReadBytes(&first_fec_protected_packet_offset
, 1)) {
1051 set_detailed_error("Unable to read first fec protected packet offset.");
1052 return RaiseError(QUIC_INVALID_PACKET_HEADER
);
1054 if (first_fec_protected_packet_offset
>= header
->packet_sequence_number
) {
1055 set_detailed_error("First fec protected packet offset must be less "
1056 "than the sequence number.");
1057 return RaiseError(QUIC_INVALID_PACKET_HEADER
);
1060 header
->packet_sequence_number
- first_fec_protected_packet_offset
;
1063 header
->entropy_hash
= GetPacketEntropyHash(*header
);
1064 // Set the last sequence number after we have decrypted the packet
1065 // so we are confident is not attacker controlled.
1066 last_sequence_number_
= header
->packet_sequence_number
;
1070 bool QuicFramer::ProcessPacketSequenceNumber(
1071 QuicSequenceNumberLength sequence_number_length
,
1072 QuicPacketSequenceNumber
* sequence_number
) {
1073 QuicPacketSequenceNumber wire_sequence_number
= 0u;
1074 if (!reader_
->ReadBytes(&wire_sequence_number
, sequence_number_length
)) {
1078 // TODO(ianswett): Explore the usefulness of trying multiple sequence numbers
1079 // in case the first guess is incorrect.
1081 CalculatePacketSequenceNumberFromWire(sequence_number_length
,
1082 wire_sequence_number
);
1086 bool QuicFramer::ProcessFrameData(const QuicPacketHeader
& header
) {
1087 if (reader_
->IsDoneReading()) {
1088 set_detailed_error("Packet has no frames.");
1089 return RaiseError(QUIC_MISSING_PAYLOAD
);
1091 while (!reader_
->IsDoneReading()) {
1093 if (!reader_
->ReadBytes(&frame_type
, 1)) {
1094 set_detailed_error("Unable to read frame type.");
1095 return RaiseError(QUIC_INVALID_FRAME_DATA
);
1098 if (frame_type
& kQuicFrameTypeSpecialMask
) {
1100 if (frame_type
& kQuicFrameTypeStreamMask
) {
1101 QuicStreamFrame frame
;
1102 if (!ProcessStreamFrame(frame_type
, &frame
)) {
1103 return RaiseError(QUIC_INVALID_STREAM_DATA
);
1105 if (!visitor_
->OnStreamFrame(frame
)) {
1106 DVLOG(1) << "Visitor asked to stop further processing.";
1107 // Returning true since there was no parsing error.
1114 if (frame_type
& kQuicFrameTypeAckMask
) {
1116 if (!ProcessAckFrame(frame_type
, &frame
)) {
1117 return RaiseError(QUIC_INVALID_ACK_DATA
);
1119 if (!visitor_
->OnAckFrame(frame
)) {
1120 DVLOG(1) << "Visitor asked to stop further processing.";
1121 // Returning true since there was no parsing error.
1127 // Congestion Feedback Frame
1128 if (frame_type
& kQuicFrameTypeCongestionFeedbackMask
) {
1129 if (quic_version_
> QUIC_VERSION_22
) {
1130 set_detailed_error("Congestion Feedback Frame has been deprecated.");
1131 DLOG(WARNING
) << "Congestion Feedback Frame has been deprecated.";
1133 QuicCongestionFeedbackFrame frame
;
1134 if (!ProcessCongestionFeedbackFrame(&frame
)) {
1135 return RaiseError(QUIC_INVALID_CONGESTION_FEEDBACK_DATA
);
1137 if (!visitor_
->OnCongestionFeedbackFrame(frame
)) {
1138 DVLOG(1) << "Visitor asked to stop further processing.";
1139 // Returning true since there was no parsing error.
1145 // This was a special frame type that did not match any
1146 // of the known ones. Error.
1147 set_detailed_error("Illegal frame type.");
1148 DLOG(WARNING
) << "Illegal frame type: "
1149 << static_cast<int>(frame_type
);
1150 return RaiseError(QUIC_INVALID_FRAME_DATA
);
1153 switch (frame_type
) {
1155 // We're done with the packet.
1158 case RST_STREAM_FRAME
: {
1159 QuicRstStreamFrame frame
;
1160 if (!ProcessRstStreamFrame(&frame
)) {
1161 return RaiseError(QUIC_INVALID_RST_STREAM_DATA
);
1163 if (!visitor_
->OnRstStreamFrame(frame
)) {
1164 DVLOG(1) << "Visitor asked to stop further processing.";
1165 // Returning true since there was no parsing error.
1171 case CONNECTION_CLOSE_FRAME
: {
1172 QuicConnectionCloseFrame frame
;
1173 if (!ProcessConnectionCloseFrame(&frame
)) {
1174 return RaiseError(QUIC_INVALID_CONNECTION_CLOSE_DATA
);
1177 if (!visitor_
->OnConnectionCloseFrame(frame
)) {
1178 DVLOG(1) << "Visitor asked to stop further processing.";
1179 // Returning true since there was no parsing error.
1185 case GOAWAY_FRAME
: {
1186 QuicGoAwayFrame goaway_frame
;
1187 if (!ProcessGoAwayFrame(&goaway_frame
)) {
1188 return RaiseError(QUIC_INVALID_GOAWAY_DATA
);
1190 if (!visitor_
->OnGoAwayFrame(goaway_frame
)) {
1191 DVLOG(1) << "Visitor asked to stop further processing.";
1192 // Returning true since there was no parsing error.
1198 case WINDOW_UPDATE_FRAME
: {
1199 QuicWindowUpdateFrame window_update_frame
;
1200 if (!ProcessWindowUpdateFrame(&window_update_frame
)) {
1201 return RaiseError(QUIC_INVALID_WINDOW_UPDATE_DATA
);
1203 if (!visitor_
->OnWindowUpdateFrame(window_update_frame
)) {
1204 DVLOG(1) << "Visitor asked to stop further processing.";
1205 // Returning true since there was no parsing error.
1211 case BLOCKED_FRAME
: {
1212 QuicBlockedFrame blocked_frame
;
1213 if (!ProcessBlockedFrame(&blocked_frame
)) {
1214 return RaiseError(QUIC_INVALID_BLOCKED_DATA
);
1216 if (!visitor_
->OnBlockedFrame(blocked_frame
)) {
1217 DVLOG(1) << "Visitor asked to stop further processing.";
1218 // Returning true since there was no parsing error.
1224 case STOP_WAITING_FRAME
: {
1225 QuicStopWaitingFrame stop_waiting_frame
;
1226 if (!ProcessStopWaitingFrame(header
, &stop_waiting_frame
)) {
1227 return RaiseError(QUIC_INVALID_STOP_WAITING_DATA
);
1229 if (!visitor_
->OnStopWaitingFrame(stop_waiting_frame
)) {
1230 DVLOG(1) << "Visitor asked to stop further processing.";
1231 // Returning true since there was no parsing error.
1237 // Ping has no payload.
1238 QuicPingFrame ping_frame
;
1239 if (!visitor_
->OnPingFrame(ping_frame
)) {
1240 DVLOG(1) << "Visitor asked to stop further processing.";
1241 // Returning true since there was no parsing error.
1248 set_detailed_error("Illegal frame type.");
1249 DLOG(WARNING
) << "Illegal frame type: "
1250 << static_cast<int>(frame_type
);
1251 return RaiseError(QUIC_INVALID_FRAME_DATA
);
1258 bool QuicFramer::ProcessStreamFrame(uint8 frame_type
,
1259 QuicStreamFrame
* frame
) {
1260 uint8 stream_flags
= frame_type
;
1262 stream_flags
&= ~kQuicFrameTypeStreamMask
;
1264 // Read from right to left: StreamID, Offset, Data Length, Fin.
1265 const uint8 stream_id_length
= (stream_flags
& kQuicStreamIDLengthMask
) + 1;
1266 stream_flags
>>= kQuicStreamIdShift
;
1268 uint8 offset_length
= (stream_flags
& kQuicStreamOffsetMask
);
1269 // There is no encoding for 1 byte, only 0 and 2 through 8.
1270 if (offset_length
> 0) {
1273 stream_flags
>>= kQuicStreamOffsetShift
;
1275 bool has_data_length
=
1276 (stream_flags
& kQuicStreamDataLengthMask
) == kQuicStreamDataLengthMask
;
1277 stream_flags
>>= kQuicStreamDataLengthShift
;
1279 frame
->fin
= (stream_flags
& kQuicStreamFinMask
) == kQuicStreamFinShift
;
1281 frame
->stream_id
= 0;
1282 if (!reader_
->ReadBytes(&frame
->stream_id
, stream_id_length
)) {
1283 set_detailed_error("Unable to read stream_id.");
1288 if (!reader_
->ReadBytes(&frame
->offset
, offset_length
)) {
1289 set_detailed_error("Unable to read offset.");
1293 StringPiece frame_data
;
1294 if (has_data_length
) {
1295 if (!reader_
->ReadStringPiece16(&frame_data
)) {
1296 set_detailed_error("Unable to read frame data.");
1300 if (!reader_
->ReadStringPiece(&frame_data
, reader_
->BytesRemaining())) {
1301 set_detailed_error("Unable to read frame data.");
1305 // Point frame to the right data.
1306 frame
->data
.Clear();
1307 if (!frame_data
.empty()) {
1308 frame
->data
.Append(const_cast<char*>(frame_data
.data()), frame_data
.size());
1314 bool QuicFramer::ProcessAckFrame(uint8 frame_type
, QuicAckFrame
* ack_frame
) {
1315 // Determine the three lengths from the frame type: largest observed length,
1316 // missing sequence number length, and missing range length.
1317 const QuicSequenceNumberLength missing_sequence_number_length
=
1318 ReadSequenceNumberLength(frame_type
);
1319 frame_type
>>= kQuicSequenceNumberLengthShift
;
1320 const QuicSequenceNumberLength largest_observed_sequence_number_length
=
1321 ReadSequenceNumberLength(frame_type
);
1322 frame_type
>>= kQuicSequenceNumberLengthShift
;
1323 ack_frame
->is_truncated
= frame_type
& kQuicAckTruncatedMask
;
1324 frame_type
>>= kQuicAckTruncatedShift
;
1325 bool has_nacks
= frame_type
& kQuicHasNacksMask
;
1327 if (!reader_
->ReadBytes(&ack_frame
->entropy_hash
, 1)) {
1328 set_detailed_error("Unable to read entropy hash for received packets.");
1332 if (!reader_
->ReadBytes(&ack_frame
->largest_observed
,
1333 largest_observed_sequence_number_length
)) {
1334 set_detailed_error("Unable to read largest observed.");
1338 uint64 delta_time_largest_observed_us
;
1339 if (!reader_
->ReadUFloat16(&delta_time_largest_observed_us
)) {
1340 set_detailed_error("Unable to read delta time largest observed.");
1344 if (delta_time_largest_observed_us
== kUFloat16MaxValue
) {
1345 ack_frame
->delta_time_largest_observed
= QuicTime::Delta::Infinite();
1347 ack_frame
->delta_time_largest_observed
=
1348 QuicTime::Delta::FromMicroseconds(delta_time_largest_observed_us
);
1351 if (!ProcessTimestampsInAckFrame(ack_frame
)) {
1359 uint8 num_missing_ranges
;
1360 if (!reader_
->ReadBytes(&num_missing_ranges
, 1)) {
1361 set_detailed_error("Unable to read num missing packet ranges.");
1365 QuicPacketSequenceNumber last_sequence_number
= ack_frame
->largest_observed
;
1366 for (size_t i
= 0; i
< num_missing_ranges
; ++i
) {
1367 QuicPacketSequenceNumber missing_delta
= 0;
1368 if (!reader_
->ReadBytes(&missing_delta
, missing_sequence_number_length
)) {
1369 set_detailed_error("Unable to read missing sequence number delta.");
1372 last_sequence_number
-= missing_delta
;
1373 QuicPacketSequenceNumber range_length
= 0;
1374 if (!reader_
->ReadBytes(&range_length
, PACKET_1BYTE_SEQUENCE_NUMBER
)) {
1375 set_detailed_error("Unable to read missing sequence number range.");
1378 for (size_t i
= 0; i
<= range_length
; ++i
) {
1379 ack_frame
->missing_packets
.insert(last_sequence_number
- i
);
1381 // Subtract an extra 1 to ensure ranges are represented efficiently and
1382 // can't overlap by 1 sequence number. This allows a missing_delta of 0
1383 // to represent an adjacent nack range.
1384 last_sequence_number
-= (range_length
+ 1);
1387 // Parse the revived packets list.
1388 uint8 num_revived_packets
;
1389 if (!reader_
->ReadBytes(&num_revived_packets
, 1)) {
1390 set_detailed_error("Unable to read num revived packets.");
1394 for (size_t i
= 0; i
< num_revived_packets
; ++i
) {
1395 QuicPacketSequenceNumber revived_packet
= 0;
1396 if (!reader_
->ReadBytes(&revived_packet
,
1397 largest_observed_sequence_number_length
)) {
1398 set_detailed_error("Unable to read revived packet.");
1402 ack_frame
->revived_packets
.insert(revived_packet
);
1408 bool QuicFramer::ProcessTimestampsInAckFrame(QuicAckFrame
* ack_frame
) {
1409 if (version() > QUIC_VERSION_22
&& !ack_frame
->is_truncated
) {
1410 uint8 num_received_packets
;
1411 if (!reader_
->ReadBytes(&num_received_packets
, 1)) {
1412 set_detailed_error("Unable to read num received packets.");
1416 if (num_received_packets
> 0) {
1417 uint8 delta_from_largest_observed
;
1418 if (!reader_
->ReadBytes(&delta_from_largest_observed
,
1419 PACKET_1BYTE_SEQUENCE_NUMBER
)) {
1421 "Unable to read sequence delta in received packets.");
1424 QuicPacketSequenceNumber seq_num
= ack_frame
->largest_observed
-
1425 delta_from_largest_observed
;
1427 // Time delta from the framer creation.
1428 uint32 time_delta_us
;
1429 if (!reader_
->ReadBytes(&time_delta_us
, sizeof(time_delta_us
))) {
1430 set_detailed_error("Unable to read time delta in received packets.");
1434 last_timestamp_
= CalculateTimestampFromWire(time_delta_us
);
1436 ack_frame
->received_packet_times
.push_back(
1437 make_pair(seq_num
, creation_time_
.Add(last_timestamp_
)));
1439 for (uint8 i
= 1; i
< num_received_packets
; ++i
) {
1440 if (!reader_
->ReadBytes(&delta_from_largest_observed
,
1441 PACKET_1BYTE_SEQUENCE_NUMBER
)) {
1443 "Unable to read sequence delta in received packets.");
1446 seq_num
= ack_frame
->largest_observed
- delta_from_largest_observed
;
1448 // Time delta from the previous timestamp.
1449 uint64 incremental_time_delta_us
;
1450 if (!reader_
->ReadUFloat16(&incremental_time_delta_us
)) {
1452 "Unable to read incremental time delta in received packets.");
1456 last_timestamp_
= last_timestamp_
.Add(
1457 QuicTime::Delta::FromMicroseconds(incremental_time_delta_us
));
1458 ack_frame
->received_packet_times
.push_back(
1459 make_pair(seq_num
, creation_time_
.Add(last_timestamp_
)));
1466 bool QuicFramer::ProcessStopWaitingFrame(const QuicPacketHeader
& header
,
1467 QuicStopWaitingFrame
* stop_waiting
) {
1468 if (!reader_
->ReadBytes(&stop_waiting
->entropy_hash
, 1)) {
1469 set_detailed_error("Unable to read entropy hash for sent packets.");
1473 QuicPacketSequenceNumber least_unacked_delta
= 0;
1474 if (!reader_
->ReadBytes(&least_unacked_delta
,
1475 header
.public_header
.sequence_number_length
)) {
1476 set_detailed_error("Unable to read least unacked delta.");
1479 DCHECK_GE(header
.packet_sequence_number
, least_unacked_delta
);
1480 stop_waiting
->least_unacked
=
1481 header
.packet_sequence_number
- least_unacked_delta
;
1486 bool QuicFramer::ProcessCongestionFeedbackFrame(
1487 QuicCongestionFeedbackFrame
* frame
) {
1488 uint8 feedback_type
;
1489 if (!reader_
->ReadBytes(&feedback_type
, 1)) {
1490 set_detailed_error("Unable to read congestion feedback type.");
1494 static_cast<CongestionFeedbackType
>(feedback_type
);
1496 switch (frame
->type
) {
1498 CongestionFeedbackMessageTCP
* tcp
= &frame
->tcp
;
1499 uint16 receive_window
= 0;
1500 if (!reader_
->ReadUInt16(&receive_window
)) {
1501 set_detailed_error("Unable to read receive window.");
1504 // Simple bit packing, don't send the 4 least significant bits.
1505 tcp
->receive_window
= static_cast<QuicByteCount
>(receive_window
) << 4;
1509 set_detailed_error("Illegal congestion feedback type.");
1510 DLOG(WARNING
) << "Illegal congestion feedback type: "
1512 return RaiseError(QUIC_INVALID_FRAME_DATA
);
1518 bool QuicFramer::ProcessRstStreamFrame(QuicRstStreamFrame
* frame
) {
1519 if (!reader_
->ReadUInt32(&frame
->stream_id
)) {
1520 set_detailed_error("Unable to read stream_id.");
1524 if (!reader_
->ReadUInt64(&frame
->byte_offset
)) {
1525 set_detailed_error("Unable to read rst stream sent byte offset.");
1530 if (!reader_
->ReadUInt32(&error_code
)) {
1531 set_detailed_error("Unable to read rst stream error code.");
1535 if (error_code
>= QUIC_STREAM_LAST_ERROR
) {
1536 set_detailed_error("Invalid rst stream error code.");
1540 frame
->error_code
= static_cast<QuicRstStreamErrorCode
>(error_code
);
1542 StringPiece error_details
;
1543 if (!reader_
->ReadStringPiece16(&error_details
)) {
1544 set_detailed_error("Unable to read rst stream error details.");
1547 frame
->error_details
= error_details
.as_string();
1552 bool QuicFramer::ProcessConnectionCloseFrame(QuicConnectionCloseFrame
* frame
) {
1554 if (!reader_
->ReadUInt32(&error_code
)) {
1555 set_detailed_error("Unable to read connection close error code.");
1559 if (error_code
>= QUIC_LAST_ERROR
) {
1560 set_detailed_error("Invalid error code.");
1564 frame
->error_code
= static_cast<QuicErrorCode
>(error_code
);
1566 StringPiece error_details
;
1567 if (!reader_
->ReadStringPiece16(&error_details
)) {
1568 set_detailed_error("Unable to read connection close error details.");
1571 frame
->error_details
= error_details
.as_string();
1576 bool QuicFramer::ProcessGoAwayFrame(QuicGoAwayFrame
* frame
) {
1578 if (!reader_
->ReadUInt32(&error_code
)) {
1579 set_detailed_error("Unable to read go away error code.");
1582 frame
->error_code
= static_cast<QuicErrorCode
>(error_code
);
1584 if (error_code
>= QUIC_LAST_ERROR
) {
1585 set_detailed_error("Invalid error code.");
1590 if (!reader_
->ReadUInt32(&stream_id
)) {
1591 set_detailed_error("Unable to read last good stream id.");
1594 frame
->last_good_stream_id
= static_cast<QuicStreamId
>(stream_id
);
1596 StringPiece reason_phrase
;
1597 if (!reader_
->ReadStringPiece16(&reason_phrase
)) {
1598 set_detailed_error("Unable to read goaway reason.");
1601 frame
->reason_phrase
= reason_phrase
.as_string();
1606 bool QuicFramer::ProcessWindowUpdateFrame(QuicWindowUpdateFrame
* frame
) {
1607 if (!reader_
->ReadUInt32(&frame
->stream_id
)) {
1608 set_detailed_error("Unable to read stream_id.");
1612 if (!reader_
->ReadUInt64(&frame
->byte_offset
)) {
1613 set_detailed_error("Unable to read window byte_offset.");
1620 bool QuicFramer::ProcessBlockedFrame(QuicBlockedFrame
* frame
) {
1621 if (!reader_
->ReadUInt32(&frame
->stream_id
)) {
1622 set_detailed_error("Unable to read stream_id.");
1630 StringPiece
QuicFramer::GetAssociatedDataFromEncryptedPacket(
1631 const QuicEncryptedPacket
& encrypted
,
1632 QuicConnectionIdLength connection_id_length
,
1633 bool includes_version
,
1634 QuicSequenceNumberLength sequence_number_length
) {
1636 encrypted
.data() + kStartOfHashData
, GetStartOfEncryptedData(
1637 connection_id_length
, includes_version
, sequence_number_length
)
1638 - kStartOfHashData
);
1641 void QuicFramer::SetDecrypter(QuicDecrypter
* decrypter
,
1642 EncryptionLevel level
) {
1643 DCHECK(alternative_decrypter_
.get() == nullptr);
1644 DCHECK_GE(level
, decrypter_level_
);
1645 decrypter_
.reset(decrypter
);
1646 decrypter_level_
= level
;
1649 void QuicFramer::SetAlternativeDecrypter(QuicDecrypter
* decrypter
,
1650 EncryptionLevel level
,
1651 bool latch_once_used
) {
1652 alternative_decrypter_
.reset(decrypter
);
1653 alternative_decrypter_level_
= level
;
1654 alternative_decrypter_latch_
= latch_once_used
;
1657 const QuicDecrypter
* QuicFramer::decrypter() const {
1658 return decrypter_
.get();
1661 const QuicDecrypter
* QuicFramer::alternative_decrypter() const {
1662 return alternative_decrypter_
.get();
1665 void QuicFramer::SetEncrypter(EncryptionLevel level
,
1666 QuicEncrypter
* encrypter
) {
1667 DCHECK_GE(level
, 0);
1668 DCHECK_LT(level
, NUM_ENCRYPTION_LEVELS
);
1669 encrypter_
[level
].reset(encrypter
);
1672 const QuicEncrypter
* QuicFramer::encrypter(EncryptionLevel level
) const {
1673 DCHECK_GE(level
, 0);
1674 DCHECK_LT(level
, NUM_ENCRYPTION_LEVELS
);
1675 DCHECK(encrypter_
[level
].get() != nullptr);
1676 return encrypter_
[level
].get();
1679 QuicEncryptedPacket
* QuicFramer::EncryptPacket(
1680 EncryptionLevel level
,
1681 QuicPacketSequenceNumber packet_sequence_number
,
1682 const QuicPacket
& packet
) {
1683 DCHECK(encrypter_
[level
].get() != nullptr);
1685 scoped_ptr
<QuicData
> out(encrypter_
[level
]->EncryptPacket(
1686 packet_sequence_number
, packet
.AssociatedData(), packet
.Plaintext()));
1687 if (out
.get() == nullptr) {
1688 RaiseError(QUIC_ENCRYPTION_FAILURE
);
1691 StringPiece header_data
= packet
.BeforePlaintext();
1692 size_t len
= header_data
.length() + out
->length();
1693 char* buffer
= new char[len
];
1694 // TODO(rch): eliminate this buffer copy by passing in a buffer to Encrypt().
1695 memcpy(buffer
, header_data
.data(), header_data
.length());
1696 memcpy(buffer
+ header_data
.length(), out
->data(), out
->length());
1697 return new QuicEncryptedPacket(buffer
, len
, true);
1700 size_t QuicFramer::GetMaxPlaintextSize(size_t ciphertext_size
) {
1701 // In order to keep the code simple, we don't have the current encryption
1702 // level to hand. Both the NullEncrypter and AES-GCM have a tag length of 12.
1703 size_t min_plaintext_size
= ciphertext_size
;
1705 for (int i
= ENCRYPTION_NONE
; i
< NUM_ENCRYPTION_LEVELS
; i
++) {
1706 if (encrypter_
[i
].get() != nullptr) {
1707 size_t size
= encrypter_
[i
]->GetMaxPlaintextSize(ciphertext_size
);
1708 if (size
< min_plaintext_size
) {
1709 min_plaintext_size
= size
;
1714 return min_plaintext_size
;
1717 bool QuicFramer::DecryptPayload(const QuicPacketHeader
& header
,
1718 const QuicEncryptedPacket
& packet
) {
1719 StringPiece encrypted
;
1720 if (!reader_
->ReadStringPiece(&encrypted
, reader_
->BytesRemaining())) {
1723 DCHECK(decrypter_
.get() != nullptr);
1724 decrypted_
.reset(decrypter_
->DecryptPacket(
1725 header
.packet_sequence_number
,
1726 GetAssociatedDataFromEncryptedPacket(
1728 header
.public_header
.connection_id_length
,
1729 header
.public_header
.version_flag
,
1730 header
.public_header
.sequence_number_length
),
1732 if (decrypted_
.get() != nullptr) {
1733 visitor_
->OnDecryptedPacket(decrypter_level_
);
1734 } else if (alternative_decrypter_
.get() != nullptr) {
1735 decrypted_
.reset(alternative_decrypter_
->DecryptPacket(
1736 header
.packet_sequence_number
,
1737 GetAssociatedDataFromEncryptedPacket(
1739 header
.public_header
.connection_id_length
,
1740 header
.public_header
.version_flag
,
1741 header
.public_header
.sequence_number_length
),
1743 if (decrypted_
.get() != nullptr) {
1744 visitor_
->OnDecryptedPacket(alternative_decrypter_level_
);
1745 if (alternative_decrypter_latch_
) {
1746 // Switch to the alternative decrypter and latch so that we cannot
1748 decrypter_
.reset(alternative_decrypter_
.release());
1749 decrypter_level_
= alternative_decrypter_level_
;
1750 alternative_decrypter_level_
= ENCRYPTION_NONE
;
1752 // Switch the alternative decrypter so that we use it first next time.
1753 decrypter_
.swap(alternative_decrypter_
);
1754 EncryptionLevel level
= alternative_decrypter_level_
;
1755 alternative_decrypter_level_
= decrypter_level_
;
1756 decrypter_level_
= level
;
1761 if (decrypted_
.get() == nullptr) {
1762 DLOG(WARNING
) << "DecryptPacket failed for sequence_number:"
1763 << header
.packet_sequence_number
;
1767 reader_
.reset(new QuicDataReader(decrypted_
->data(), decrypted_
->length()));
1771 size_t QuicFramer::GetAckFrameSize(
1772 const QuicAckFrame
& ack
,
1773 QuicSequenceNumberLength sequence_number_length
) {
1774 AckFrameInfo ack_info
= GetAckFrameInfo(ack
);
1775 QuicSequenceNumberLength largest_observed_length
=
1776 GetMinSequenceNumberLength(ack
.largest_observed
);
1777 QuicSequenceNumberLength missing_sequence_number_length
=
1778 GetMinSequenceNumberLength(ack_info
.max_delta
);
1780 size_t ack_size
= GetMinAckFrameSize(sequence_number_length
,
1781 largest_observed_length
);
1782 if (!ack_info
.nack_ranges
.empty()) {
1783 ack_size
+= kNumberOfNackRangesSize
+ kNumberOfRevivedPacketsSize
;
1784 ack_size
+= min(ack_info
.nack_ranges
.size(), kMaxNackRanges
) *
1785 (missing_sequence_number_length
+ PACKET_1BYTE_SEQUENCE_NUMBER
);
1786 ack_size
+= min(ack
.revived_packets
.size(),
1787 kMaxRevivedPackets
) * largest_observed_length
;
1790 // In version 23, if the ack will be truncated due to too many nack ranges,
1791 // then do not include the number of timestamps (1 byte).
1792 if (version() > QUIC_VERSION_22
&&
1793 ack_info
.nack_ranges
.size() <= kMaxNackRanges
) {
1794 // 1 byte for the number of timestamps.
1796 if (ack
.received_packet_times
.size() > 0) {
1797 // 1 byte for sequence number, 4 bytes for timestamp for the first
1801 // 1 byte for sequence number, 2 bytes for timestamp for the other
1803 ack_size
+= 3 * (ack
.received_packet_times
.size() - 1);
1810 size_t QuicFramer::ComputeFrameLength(
1811 const QuicFrame
& frame
,
1812 bool last_frame_in_packet
,
1813 InFecGroup is_in_fec_group
,
1814 QuicSequenceNumberLength sequence_number_length
) {
1815 switch (frame
.type
) {
1817 return GetMinStreamFrameSize(frame
.stream_frame
->stream_id
,
1818 frame
.stream_frame
->offset
,
1819 last_frame_in_packet
,
1821 frame
.stream_frame
->data
.TotalBufferSize();
1823 return GetAckFrameSize(*frame
.ack_frame
, sequence_number_length
);
1825 case CONGESTION_FEEDBACK_FRAME
: {
1826 size_t len
= kQuicFrameTypeSize
;
1827 const QuicCongestionFeedbackFrame
& congestion_feedback
=
1828 *frame
.congestion_feedback_frame
;
1829 len
+= 1; // Congestion feedback type.
1831 switch (congestion_feedback
.type
) {
1833 len
+= 2; // Receive window.
1836 set_detailed_error("Illegal feedback type.");
1837 DVLOG(1) << "Illegal feedback type: " << congestion_feedback
.type
;
1842 case STOP_WAITING_FRAME
:
1843 return GetStopWaitingFrameSize(sequence_number_length
);
1845 // Ping has no payload.
1846 return kQuicFrameTypeSize
;
1847 case RST_STREAM_FRAME
:
1848 return GetMinRstStreamFrameSize() +
1849 frame
.rst_stream_frame
->error_details
.size();
1850 case CONNECTION_CLOSE_FRAME
:
1851 return GetMinConnectionCloseFrameSize() +
1852 frame
.connection_close_frame
->error_details
.size();
1854 return GetMinGoAwayFrameSize() + frame
.goaway_frame
->reason_phrase
.size();
1855 case WINDOW_UPDATE_FRAME
:
1856 return GetWindowUpdateFrameSize();
1858 return GetBlockedFrameSize();
1862 case NUM_FRAME_TYPES
:
1867 // Not reachable, but some Chrome compilers can't figure that out. *sigh*
1872 bool QuicFramer::AppendTypeByte(const QuicFrame
& frame
,
1873 bool no_stream_frame_length
,
1874 QuicDataWriter
* writer
) {
1875 uint8 type_byte
= 0;
1876 switch (frame
.type
) {
1877 case STREAM_FRAME
: {
1878 if (frame
.stream_frame
== nullptr) {
1879 LOG(DFATAL
) << "Failed to append STREAM frame with no stream_frame.";
1882 type_byte
|= frame
.stream_frame
->fin
? kQuicStreamFinMask
: 0;
1885 type_byte
<<= kQuicStreamDataLengthShift
;
1886 type_byte
|= no_stream_frame_length
? 0: kQuicStreamDataLengthMask
;
1889 type_byte
<<= kQuicStreamOffsetShift
;
1890 const size_t offset_len
= GetStreamOffsetSize(frame
.stream_frame
->offset
);
1891 if (offset_len
> 0) {
1892 type_byte
|= offset_len
- 1;
1895 // stream id 2 bits.
1896 type_byte
<<= kQuicStreamIdShift
;
1897 type_byte
|= GetStreamIdSize(frame
.stream_frame
->stream_id
) - 1;
1898 type_byte
|= kQuicFrameTypeStreamMask
; // Set Stream Frame Type to 1.
1903 case CONGESTION_FEEDBACK_FRAME
: {
1904 // TODO(ianswett): Use extra 5 bits in the congestion feedback framing.
1905 type_byte
= kQuicFrameTypeCongestionFeedbackMask
;
1909 type_byte
= static_cast<uint8
>(frame
.type
);
1913 return writer
->WriteUInt8(type_byte
);
1917 bool QuicFramer::AppendPacketSequenceNumber(
1918 QuicSequenceNumberLength sequence_number_length
,
1919 QuicPacketSequenceNumber packet_sequence_number
,
1920 QuicDataWriter
* writer
) {
1921 // Ensure the entire sequence number can be written.
1922 if (writer
->capacity() - writer
->length() <
1923 static_cast<size_t>(sequence_number_length
)) {
1926 switch (sequence_number_length
) {
1927 case PACKET_1BYTE_SEQUENCE_NUMBER
:
1928 return writer
->WriteUInt8(
1929 packet_sequence_number
& k1ByteSequenceNumberMask
);
1931 case PACKET_2BYTE_SEQUENCE_NUMBER
:
1932 return writer
->WriteUInt16(
1933 packet_sequence_number
& k2ByteSequenceNumberMask
);
1935 case PACKET_4BYTE_SEQUENCE_NUMBER
:
1936 return writer
->WriteUInt32(
1937 packet_sequence_number
& k4ByteSequenceNumberMask
);
1939 case PACKET_6BYTE_SEQUENCE_NUMBER
:
1940 return writer
->WriteUInt48(
1941 packet_sequence_number
& k6ByteSequenceNumberMask
);
1944 DCHECK(false) << "sequence_number_length: " << sequence_number_length
;
1949 bool QuicFramer::AppendStreamFrame(
1950 const QuicStreamFrame
& frame
,
1951 bool no_stream_frame_length
,
1952 QuicDataWriter
* writer
) {
1953 if (!writer
->WriteBytes(&frame
.stream_id
, GetStreamIdSize(frame
.stream_id
))) {
1954 LOG(DFATAL
) << "Writing stream id size failed.";
1957 if (!writer
->WriteBytes(&frame
.offset
, GetStreamOffsetSize(frame
.offset
))) {
1958 LOG(DFATAL
) << "Writing offset size failed.";
1961 if (!no_stream_frame_length
) {
1962 if ((frame
.data
.TotalBufferSize() > numeric_limits
<uint16
>::max()) ||
1963 !writer
->WriteUInt16(
1964 static_cast<uint16
>(frame
.data
.TotalBufferSize()))) {
1965 LOG(DFATAL
) << "Writing stream frame length failed";
1970 if (!writer
->WriteIOVector(frame
.data
)) {
1971 LOG(DFATAL
) << "Writing frame data failed.";
1978 void QuicFramer::set_version(const QuicVersion version
) {
1979 DCHECK(IsSupportedVersion(version
)) << QuicVersionToString(version
);
1980 quic_version_
= version
;
1983 bool QuicFramer::AppendAckFrameAndTypeByte(
1984 const QuicPacketHeader
& header
,
1985 const QuicAckFrame
& frame
,
1986 QuicDataWriter
* writer
) {
1987 AckFrameInfo ack_info
= GetAckFrameInfo(frame
);
1988 QuicPacketSequenceNumber ack_largest_observed
= frame
.largest_observed
;
1989 QuicSequenceNumberLength largest_observed_length
=
1990 GetMinSequenceNumberLength(ack_largest_observed
);
1991 QuicSequenceNumberLength missing_sequence_number_length
=
1992 GetMinSequenceNumberLength(ack_info
.max_delta
);
1993 // Determine whether we need to truncate ranges.
1994 size_t available_range_bytes
= writer
->capacity() - writer
->length() -
1995 kNumberOfRevivedPacketsSize
- kNumberOfNackRangesSize
-
1996 GetMinAckFrameSize(header
.public_header
.sequence_number_length
,
1997 largest_observed_length
);
1998 size_t max_num_ranges
= available_range_bytes
/
1999 (missing_sequence_number_length
+ PACKET_1BYTE_SEQUENCE_NUMBER
);
2000 max_num_ranges
= min(kMaxNackRanges
, max_num_ranges
);
2001 bool truncated
= ack_info
.nack_ranges
.size() > max_num_ranges
;
2002 DVLOG_IF(1, truncated
) << "Truncating ack from "
2003 << ack_info
.nack_ranges
.size() << " ranges to "
2005 // Write out the type byte by setting the low order bits and doing shifts
2006 // to make room for the next bit flags to be set.
2007 // Whether there are any nacks.
2008 uint8 type_byte
= ack_info
.nack_ranges
.empty() ? 0 : kQuicHasNacksMask
;
2011 type_byte
<<= kQuicAckTruncatedShift
;
2012 type_byte
|= truncated
? kQuicAckTruncatedMask
: 0;
2014 // Largest observed sequence number length.
2015 type_byte
<<= kQuicSequenceNumberLengthShift
;
2016 type_byte
|= GetSequenceNumberFlags(largest_observed_length
);
2018 // Missing sequence number length.
2019 type_byte
<<= kQuicSequenceNumberLengthShift
;
2020 type_byte
|= GetSequenceNumberFlags(missing_sequence_number_length
);
2022 type_byte
|= kQuicFrameTypeAckMask
;
2024 if (!writer
->WriteUInt8(type_byte
)) {
2028 QuicPacketEntropyHash ack_entropy_hash
= frame
.entropy_hash
;
2029 NackRangeMap::reverse_iterator ack_iter
= ack_info
.nack_ranges
.rbegin();
2031 // Skip the nack ranges which the truncated ack won't include and set
2032 // a correct largest observed for the truncated ack.
2033 for (size_t i
= 1; i
< (ack_info
.nack_ranges
.size() - max_num_ranges
);
2037 // If the last range is followed by acks, include them.
2038 // If the last range is followed by another range, specify the end of the
2039 // range as the largest_observed.
2040 ack_largest_observed
= ack_iter
->first
- 1;
2041 // Also update the entropy so it matches the largest observed.
2042 ack_entropy_hash
= entropy_calculator_
->EntropyHash(ack_largest_observed
);
2046 if (!writer
->WriteUInt8(ack_entropy_hash
)) {
2050 if (!AppendPacketSequenceNumber(largest_observed_length
,
2051 ack_largest_observed
, writer
)) {
2055 uint64 delta_time_largest_observed_us
= kUFloat16MaxValue
;
2056 if (!frame
.delta_time_largest_observed
.IsInfinite()) {
2057 DCHECK_LE(0u, frame
.delta_time_largest_observed
.ToMicroseconds());
2058 delta_time_largest_observed_us
=
2059 frame
.delta_time_largest_observed
.ToMicroseconds();
2062 if (!writer
->WriteUFloat16(delta_time_largest_observed_us
)) {
2066 // Timestamp goes at the end of the required fields.
2067 if (version() > QUIC_VERSION_22
&& !truncated
) {
2068 if (!AppendTimestampToAckFrame(frame
, writer
)) {
2073 if (ack_info
.nack_ranges
.empty()) {
2077 const uint8 num_missing_ranges
=
2078 static_cast<uint8
>(min(ack_info
.nack_ranges
.size(), max_num_ranges
));
2079 if (!writer
->WriteBytes(&num_missing_ranges
, 1)) {
2083 int num_ranges_written
= 0;
2084 QuicPacketSequenceNumber last_sequence_written
= ack_largest_observed
;
2085 for (; ack_iter
!= ack_info
.nack_ranges
.rend(); ++ack_iter
) {
2086 // Calculate the delta to the last number in the range.
2087 QuicPacketSequenceNumber missing_delta
=
2088 last_sequence_written
- (ack_iter
->first
+ ack_iter
->second
);
2089 if (!AppendPacketSequenceNumber(missing_sequence_number_length
,
2090 missing_delta
, writer
)) {
2093 if (!AppendPacketSequenceNumber(PACKET_1BYTE_SEQUENCE_NUMBER
,
2094 ack_iter
->second
, writer
)) {
2097 // Subtract 1 so a missing_delta of 0 means an adjacent range.
2098 last_sequence_written
= ack_iter
->first
- 1;
2099 ++num_ranges_written
;
2101 DCHECK_EQ(num_missing_ranges
, num_ranges_written
);
2103 // Append revived packets.
2104 // If not all the revived packets fit, only mention the ones that do.
2105 uint8 num_revived_packets
=
2106 static_cast<uint8
>(min(frame
.revived_packets
.size(), kMaxRevivedPackets
));
2107 num_revived_packets
= static_cast<uint8
>(min(
2108 static_cast<size_t>(num_revived_packets
),
2109 (writer
->capacity() - writer
->length()) / largest_observed_length
));
2110 if (!writer
->WriteBytes(&num_revived_packets
, 1)) {
2114 SequenceNumberSet::const_iterator iter
= frame
.revived_packets
.begin();
2115 for (int i
= 0; i
< num_revived_packets
; ++i
, ++iter
) {
2116 LOG_IF(DFATAL
, !ContainsKey(frame
.missing_packets
, *iter
));
2117 if (!AppendPacketSequenceNumber(largest_observed_length
,
2126 bool QuicFramer::AppendCongestionFeedbackFrame(
2127 const QuicCongestionFeedbackFrame
& frame
,
2128 QuicDataWriter
* writer
) {
2129 if (!writer
->WriteBytes(&frame
.type
, 1)) {
2133 switch (frame
.type
) {
2135 const CongestionFeedbackMessageTCP
& tcp
= frame
.tcp
;
2136 DCHECK_LE(tcp
.receive_window
, 1u << 20);
2137 // Simple bit packing, don't send the 4 least significant bits.
2138 uint16 receive_window
= static_cast<uint16
>(tcp
.receive_window
>> 4);
2139 if (!writer
->WriteUInt16(receive_window
)) {
2151 bool QuicFramer::AppendTimestampToAckFrame(const QuicAckFrame
& frame
,
2152 QuicDataWriter
* writer
) {
2153 DCHECK_GE(version(), QUIC_VERSION_23
);
2154 DCHECK_GE(numeric_limits
<uint8
>::max(), frame
.received_packet_times
.size());
2155 // num_received_packets is only 1 byte.
2156 if (frame
.received_packet_times
.size() > numeric_limits
<uint8
>::max()) {
2160 uint8 num_received_packets
= frame
.received_packet_times
.size();
2162 if (!writer
->WriteBytes(&num_received_packets
, 1)) {
2165 if (num_received_packets
== 0) {
2169 PacketTimeList::const_iterator it
= frame
.received_packet_times
.begin();
2170 QuicPacketSequenceNumber sequence_number
= it
->first
;
2171 QuicPacketSequenceNumber delta_from_largest_observed
=
2172 frame
.largest_observed
- sequence_number
;
2174 DCHECK_GE(numeric_limits
<uint8
>::max(), delta_from_largest_observed
);
2175 if (delta_from_largest_observed
> numeric_limits
<uint8
>::max()) {
2179 if (!writer
->WriteUInt8(
2180 delta_from_largest_observed
& k1ByteSequenceNumberMask
)) {
2184 // Use the lowest 4 bytes of the time delta from the creation_time_.
2185 const uint64 time_epoch_delta_us
= GG_UINT64_C(1) << 32;
2186 uint32 time_delta_us
=
2187 static_cast<uint32
>(it
->second
.Subtract(creation_time_
).ToMicroseconds()
2188 & (time_epoch_delta_us
- 1));
2189 if (!writer
->WriteBytes(&time_delta_us
, sizeof(time_delta_us
))) {
2193 QuicTime prev_time
= it
->second
;
2195 for (++it
; it
!= frame
.received_packet_times
.end(); ++it
) {
2196 sequence_number
= it
->first
;
2197 delta_from_largest_observed
= frame
.largest_observed
- sequence_number
;
2199 if (delta_from_largest_observed
> numeric_limits
<uint8
>::max()) {
2203 if (!writer
->WriteUInt8(
2204 delta_from_largest_observed
& k1ByteSequenceNumberMask
)) {
2208 uint64 time_delta_us
= it
->second
.Subtract(prev_time
).ToMicroseconds();
2209 prev_time
= it
->second
;
2210 if (!writer
->WriteUFloat16(time_delta_us
)) {
2217 bool QuicFramer::AppendStopWaitingFrame(
2218 const QuicPacketHeader
& header
,
2219 const QuicStopWaitingFrame
& frame
,
2220 QuicDataWriter
* writer
) {
2221 DCHECK_GE(header
.packet_sequence_number
, frame
.least_unacked
);
2222 const QuicPacketSequenceNumber least_unacked_delta
=
2223 header
.packet_sequence_number
- frame
.least_unacked
;
2224 const QuicPacketSequenceNumber length_shift
=
2225 header
.public_header
.sequence_number_length
* 8;
2226 if (!writer
->WriteUInt8(frame
.entropy_hash
)) {
2227 LOG(DFATAL
) << " hash failed";
2231 if (least_unacked_delta
>> length_shift
> 0) {
2232 LOG(DFATAL
) << "sequence_number_length "
2233 << header
.public_header
.sequence_number_length
2234 << " is too small for least_unacked_delta: "
2235 << least_unacked_delta
;
2238 if (!AppendPacketSequenceNumber(header
.public_header
.sequence_number_length
,
2239 least_unacked_delta
, writer
)) {
2240 LOG(DFATAL
) << " seq failed: "
2241 << header
.public_header
.sequence_number_length
;
2248 bool QuicFramer::AppendRstStreamFrame(
2249 const QuicRstStreamFrame
& frame
,
2250 QuicDataWriter
* writer
) {
2251 if (!writer
->WriteUInt32(frame
.stream_id
)) {
2255 if (!writer
->WriteUInt64(frame
.byte_offset
)) {
2259 uint32 error_code
= static_cast<uint32
>(frame
.error_code
);
2260 if (!writer
->WriteUInt32(error_code
)) {
2264 if (!writer
->WriteStringPiece16(frame
.error_details
)) {
2270 bool QuicFramer::AppendConnectionCloseFrame(
2271 const QuicConnectionCloseFrame
& frame
,
2272 QuicDataWriter
* writer
) {
2273 uint32 error_code
= static_cast<uint32
>(frame
.error_code
);
2274 if (!writer
->WriteUInt32(error_code
)) {
2277 if (!writer
->WriteStringPiece16(frame
.error_details
)) {
2283 bool QuicFramer::AppendGoAwayFrame(const QuicGoAwayFrame
& frame
,
2284 QuicDataWriter
* writer
) {
2285 uint32 error_code
= static_cast<uint32
>(frame
.error_code
);
2286 if (!writer
->WriteUInt32(error_code
)) {
2289 uint32 stream_id
= static_cast<uint32
>(frame
.last_good_stream_id
);
2290 if (!writer
->WriteUInt32(stream_id
)) {
2293 if (!writer
->WriteStringPiece16(frame
.reason_phrase
)) {
2299 bool QuicFramer::AppendWindowUpdateFrame(const QuicWindowUpdateFrame
& frame
,
2300 QuicDataWriter
* writer
) {
2301 uint32 stream_id
= static_cast<uint32
>(frame
.stream_id
);
2302 if (!writer
->WriteUInt32(stream_id
)) {
2305 if (!writer
->WriteUInt64(frame
.byte_offset
)) {
2311 bool QuicFramer::AppendBlockedFrame(const QuicBlockedFrame
& frame
,
2312 QuicDataWriter
* writer
) {
2313 uint32 stream_id
= static_cast<uint32
>(frame
.stream_id
);
2314 if (!writer
->WriteUInt32(stream_id
)) {
2320 bool QuicFramer::RaiseError(QuicErrorCode error
) {
2321 DVLOG(1) << "Error detail: " << detailed_error_
;
2323 visitor_
->OnError(this);
2324 reader_
.reset(nullptr);