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"
9 #include "base/basictypes.h"
10 #include "base/logging.h"
11 #include "base/stl_util.h"
12 #include "net/quic/crypto/crypto_framer.h"
13 #include "net/quic/crypto/crypto_handshake_message.h"
14 #include "net/quic/crypto/crypto_protocol.h"
15 #include "net/quic/crypto/quic_decrypter.h"
16 #include "net/quic/crypto/quic_encrypter.h"
17 #include "net/quic/quic_data_reader.h"
18 #include "net/quic/quic_data_writer.h"
19 #include "net/quic/quic_flags.h"
20 #include "net/quic/quic_socket_address_coder.h"
21 #include "net/quic/quic_utils.h"
23 using base::StringPiece
;
27 using std::numeric_limits
;
34 // Mask to select the lowest 48 bits of a sequence number.
35 const QuicPacketSequenceNumber k6ByteSequenceNumberMask
=
36 UINT64_C(0x0000FFFFFFFFFFFF);
37 const QuicPacketSequenceNumber k4ByteSequenceNumberMask
=
38 UINT64_C(0x00000000FFFFFFFF);
39 const QuicPacketSequenceNumber k2ByteSequenceNumberMask
=
40 UINT64_C(0x000000000000FFFF);
41 const QuicPacketSequenceNumber k1ByteSequenceNumberMask
=
42 UINT64_C(0x00000000000000FF);
44 const QuicConnectionId k1ByteConnectionIdMask
= UINT64_C(0x00000000000000FF);
45 const QuicConnectionId k4ByteConnectionIdMask
= UINT64_C(0x00000000FFFFFFFF);
47 // Number of bits the sequence number length bits are shifted from the right
48 // edge of the public header.
49 const uint8 kPublicHeaderSequenceNumberShift
= 4;
51 // New Frame Types, QUIC v. >= 10:
52 // There are two interpretations for the Frame Type byte in the QUIC protocol,
53 // resulting in two Frame Types: Special Frame Types and Regular Frame Types.
55 // Regular Frame Types use the Frame Type byte simply. Currently defined
56 // Regular Frame Types are:
57 // Padding : 0b 00000000 (0x00)
58 // ResetStream : 0b 00000001 (0x01)
59 // ConnectionClose : 0b 00000010 (0x02)
60 // GoAway : 0b 00000011 (0x03)
61 // WindowUpdate : 0b 00000100 (0x04)
62 // Blocked : 0b 00000101 (0x05)
64 // Special Frame Types encode both a Frame Type and corresponding flags
65 // all in the Frame Type byte. Currently defined Special Frame Types are:
66 // Stream : 0b 1xxxxxxx
69 // Semantics of the flag bits above (the x bits) depends on the frame type.
71 // Masks to determine if the frame type is a special use
72 // and for specific special frame types.
73 const uint8 kQuicFrameTypeSpecialMask
= 0xE0; // 0b 11100000
74 const uint8 kQuicFrameTypeStreamMask
= 0x80;
75 const uint8 kQuicFrameTypeAckMask
= 0x40;
77 // Stream frame relative shifts and masks for interpreting the stream flags.
78 // StreamID may be 1, 2, 3, or 4 bytes.
79 const uint8 kQuicStreamIdShift
= 2;
80 const uint8 kQuicStreamIDLengthMask
= 0x03;
82 // Offset may be 0, 2, 3, 4, 5, 6, 7, 8 bytes.
83 const uint8 kQuicStreamOffsetShift
= 3;
84 const uint8 kQuicStreamOffsetMask
= 0x07;
86 // Data length may be 0 or 2 bytes.
87 const uint8 kQuicStreamDataLengthShift
= 1;
88 const uint8 kQuicStreamDataLengthMask
= 0x01;
90 // Fin bit may be set or not.
91 const uint8 kQuicStreamFinShift
= 1;
92 const uint8 kQuicStreamFinMask
= 0x01;
94 // Sequence number size shift used in AckFrames.
95 const uint8 kQuicSequenceNumberLengthShift
= 2;
97 // Acks may be truncated.
98 const uint8 kQuicAckTruncatedShift
= 1;
99 const uint8 kQuicAckTruncatedMask
= 0x01;
101 // Acks may not have any nacks.
102 const uint8 kQuicHasNacksMask
= 0x01;
104 // Returns the absolute value of the difference between |a| and |b|.
105 QuicPacketSequenceNumber
Delta(QuicPacketSequenceNumber a
,
106 QuicPacketSequenceNumber b
) {
107 // Since these are unsigned numbers, we can't just return abs(a - b)
114 QuicPacketSequenceNumber
ClosestTo(QuicPacketSequenceNumber target
,
115 QuicPacketSequenceNumber a
,
116 QuicPacketSequenceNumber b
) {
117 return (Delta(target
, a
) < Delta(target
, b
)) ? a
: b
;
120 QuicSequenceNumberLength
ReadSequenceNumberLength(uint8 flags
) {
121 switch (flags
& PACKET_FLAGS_6BYTE_SEQUENCE
) {
122 case PACKET_FLAGS_6BYTE_SEQUENCE
:
123 return PACKET_6BYTE_SEQUENCE_NUMBER
;
124 case PACKET_FLAGS_4BYTE_SEQUENCE
:
125 return PACKET_4BYTE_SEQUENCE_NUMBER
;
126 case PACKET_FLAGS_2BYTE_SEQUENCE
:
127 return PACKET_2BYTE_SEQUENCE_NUMBER
;
128 case PACKET_FLAGS_1BYTE_SEQUENCE
:
129 return PACKET_1BYTE_SEQUENCE_NUMBER
;
131 LOG(DFATAL
) << "Unreachable case statement.";
132 return PACKET_6BYTE_SEQUENCE_NUMBER
;
138 bool QuicFramerVisitorInterface::OnWindowUpdateFrame(
139 const QuicWindowUpdateFrame
& frame
) {
143 bool QuicFramerVisitorInterface::OnBlockedFrame(const QuicBlockedFrame
& frame
) {
147 QuicFramer::QuicFramer(const QuicVersionVector
& supported_versions
,
148 QuicTime creation_time
,
149 Perspective perspective
)
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 perspective_(perspective
),
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::GetRstStreamFrameSize() {
207 return kQuicFrameTypeSize
+ kQuicMaxStreamIdSize
+ kQuicMaxStreamOffsetSize
+
212 size_t QuicFramer::GetMinConnectionCloseFrameSize() {
213 return kQuicFrameTypeSize
+ kQuicErrorCodeSize
+ kQuicErrorDetailsLengthSize
;
217 size_t QuicFramer::GetMinGoAwayFrameSize() {
218 return kQuicFrameTypeSize
+ kQuicErrorCodeSize
+ kQuicErrorDetailsLengthSize
+
219 kQuicMaxStreamIdSize
;
223 size_t QuicFramer::GetWindowUpdateFrameSize() {
224 return kQuicFrameTypeSize
+ kQuicMaxStreamIdSize
+ kQuicMaxStreamOffsetSize
;
228 size_t QuicFramer::GetBlockedFrameSize() {
229 return kQuicFrameTypeSize
+ kQuicMaxStreamIdSize
;
233 size_t QuicFramer::GetStreamIdSize(QuicStreamId stream_id
) {
234 // Sizes are 1 through 4 bytes.
235 for (int i
= 1; i
<= 4; ++i
) {
237 if (stream_id
== 0) {
241 LOG(DFATAL
) << "Failed to determine StreamIDSize.";
246 size_t QuicFramer::GetStreamOffsetSize(QuicStreamOffset offset
) {
247 // 0 is a special case.
251 // 2 through 8 are the remaining sizes.
253 for (int i
= 2; i
<= 8; ++i
) {
259 LOG(DFATAL
) << "Failed to determine StreamOffsetSize.";
264 size_t QuicFramer::GetVersionNegotiationPacketSize(size_t number_versions
) {
265 return kPublicFlagsSize
+ PACKET_8BYTE_CONNECTION_ID
+
266 number_versions
* kQuicVersionSize
;
269 bool QuicFramer::IsSupportedVersion(const QuicVersion version
) const {
270 for (size_t i
= 0; i
< supported_versions_
.size(); ++i
) {
271 if (version
== supported_versions_
[i
]) {
278 size_t QuicFramer::GetSerializedFrameLength(
279 const QuicFrame
& frame
,
283 InFecGroup is_in_fec_group
,
284 QuicSequenceNumberLength sequence_number_length
) {
285 // Prevent a rare crash reported in b/19458523.
286 if (frame
.stream_frame
== nullptr) {
287 LOG(DFATAL
) << "Cannot compute the length of a null frame. "
288 << "type:" << frame
.type
<< "free_bytes:" << free_bytes
289 << " first_frame:" << first_frame
290 << " last_frame:" << last_frame
291 << " is_in_fec:" << is_in_fec_group
292 << " seq num length:" << sequence_number_length
;
293 set_error(QUIC_INTERNAL_ERROR
);
294 visitor_
->OnError(this);
297 if (frame
.type
== PADDING_FRAME
) {
298 // PADDING implies end of packet.
302 ComputeFrameLength(frame
, last_frame
, is_in_fec_group
,
303 sequence_number_length
);
304 if (frame_len
<= free_bytes
) {
305 // Frame fits within packet. Note that acks may be truncated.
308 // Only truncate the first frame in a packet, so if subsequent ones go
309 // over, stop including more frames.
313 bool can_truncate
= frame
.type
== ACK_FRAME
&&
314 free_bytes
>= GetMinAckFrameSize(PACKET_6BYTE_SEQUENCE_NUMBER
,
315 PACKET_6BYTE_SEQUENCE_NUMBER
);
317 // Truncate the frame so the packet will not exceed kMaxPacketSize.
318 // Note that we may not use every byte of the writer in this case.
319 DVLOG(1) << "Truncating large frame, free bytes: " << free_bytes
;
322 if (!FLAGS_quic_allow_oversized_packets_for_test
) {
325 LOG(DFATAL
) << "Packet size too small to fit frame.";
329 QuicFramer::AckFrameInfo::AckFrameInfo() : max_delta(0) {}
331 QuicFramer::AckFrameInfo::~AckFrameInfo() {}
334 QuicPacketEntropyHash
QuicFramer::GetPacketEntropyHash(
335 const QuicPacketHeader
& header
) {
336 return header
.entropy_flag
<< (header
.packet_sequence_number
% 8);
339 QuicPacket
* QuicFramer::BuildDataPacket(const QuicPacketHeader
& header
,
340 const QuicFrames
& frames
,
342 size_t packet_length
) {
343 QuicDataWriter
writer(packet_length
, buffer
);
344 if (!AppendPacketHeader(header
, &writer
)) {
345 LOG(DFATAL
) << "AppendPacketHeader failed";
350 for (const QuicFrame
& frame
: frames
) {
351 // Determine if we should write stream frame length in header.
352 const bool no_stream_frame_length
=
353 (header
.is_in_fec_group
== NOT_IN_FEC_GROUP
) &&
354 (i
== frames
.size() - 1);
355 if (!AppendTypeByte(frame
, no_stream_frame_length
, &writer
)) {
356 LOG(DFATAL
) << "AppendTypeByte failed";
360 switch (frame
.type
) {
362 writer
.WritePadding();
365 if (!AppendStreamFrame(
366 *frame
.stream_frame
, no_stream_frame_length
, &writer
)) {
367 LOG(DFATAL
) << "AppendStreamFrame failed";
372 if (!AppendAckFrameAndTypeByte(
373 header
, *frame
.ack_frame
, &writer
)) {
374 LOG(DFATAL
) << "AppendAckFrameAndTypeByte failed";
378 case STOP_WAITING_FRAME
:
379 if (!AppendStopWaitingFrame(
380 header
, *frame
.stop_waiting_frame
, &writer
)) {
381 LOG(DFATAL
) << "AppendStopWaitingFrame failed";
386 // Ping has no payload.
388 case RST_STREAM_FRAME
:
389 if (!AppendRstStreamFrame(*frame
.rst_stream_frame
, &writer
)) {
390 LOG(DFATAL
) << "AppendRstStreamFrame failed";
394 case CONNECTION_CLOSE_FRAME
:
395 if (!AppendConnectionCloseFrame(
396 *frame
.connection_close_frame
, &writer
)) {
397 LOG(DFATAL
) << "AppendConnectionCloseFrame failed";
402 if (!AppendGoAwayFrame(*frame
.goaway_frame
, &writer
)) {
403 LOG(DFATAL
) << "AppendGoAwayFrame failed";
407 case WINDOW_UPDATE_FRAME
:
408 if (!AppendWindowUpdateFrame(*frame
.window_update_frame
, &writer
)) {
409 LOG(DFATAL
) << "AppendWindowUpdateFrame failed";
414 if (!AppendBlockedFrame(*frame
.blocked_frame
, &writer
)) {
415 LOG(DFATAL
) << "AppendBlockedFrame failed";
420 RaiseError(QUIC_INVALID_FRAME_DATA
);
421 LOG(DFATAL
) << "QUIC_INVALID_FRAME_DATA";
428 new QuicPacket(writer
.data(), writer
.length(), false,
429 header
.public_header
.connection_id_length
,
430 header
.public_header
.version_flag
,
431 header
.public_header
.sequence_number_length
);
436 QuicPacket
* QuicFramer::BuildFecPacket(const QuicPacketHeader
& header
,
437 const QuicFecData
& fec
) {
438 DCHECK_EQ(IN_FEC_GROUP
, header
.is_in_fec_group
);
439 DCHECK_NE(0u, header
.fec_group
);
440 size_t len
= GetPacketHeaderSize(header
);
441 len
+= fec
.redundancy
.length();
443 scoped_ptr
<char[]> buffer(new char[len
]);
444 QuicDataWriter
writer(len
, buffer
.get());
445 if (!AppendPacketHeader(header
, &writer
)) {
446 LOG(DFATAL
) << "AppendPacketHeader failed";
450 if (!writer
.WriteBytes(fec
.redundancy
.data(), fec
.redundancy
.length())) {
451 LOG(DFATAL
) << "Failed to add FEC";
455 return new QuicPacket(buffer
.release(), len
, true,
456 header
.public_header
.connection_id_length
,
457 header
.public_header
.version_flag
,
458 header
.public_header
.sequence_number_length
);
462 QuicEncryptedPacket
* QuicFramer::BuildPublicResetPacket(
463 const QuicPublicResetPacket
& packet
) {
464 DCHECK(packet
.public_header
.reset_flag
);
466 CryptoHandshakeMessage reset
;
467 reset
.set_tag(kPRST
);
468 reset
.SetValue(kRNON
, packet
.nonce_proof
);
469 reset
.SetValue(kRSEQ
, packet
.rejected_sequence_number
);
470 if (!packet
.client_address
.address().empty()) {
471 // packet.client_address is non-empty.
472 QuicSocketAddressCoder
address_coder(packet
.client_address
);
473 string serialized_address
= address_coder
.Encode();
474 if (serialized_address
.empty()) {
477 reset
.SetStringPiece(kCADR
, serialized_address
);
479 const QuicData
& reset_serialized
= reset
.GetSerialized();
482 kPublicFlagsSize
+ PACKET_8BYTE_CONNECTION_ID
+ reset_serialized
.length();
483 scoped_ptr
<char[]> buffer(new char[len
]);
484 QuicDataWriter
writer(len
, buffer
.get());
486 uint8 flags
= static_cast<uint8
>(PACKET_PUBLIC_FLAGS_RST
|
487 PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID
);
488 if (!writer
.WriteUInt8(flags
)) {
492 if (!writer
.WriteUInt64(packet
.public_header
.connection_id
)) {
496 if (!writer
.WriteBytes(reset_serialized
.data(), reset_serialized
.length())) {
500 return new QuicEncryptedPacket(buffer
.release(), len
, true);
503 QuicEncryptedPacket
* QuicFramer::BuildVersionNegotiationPacket(
504 const QuicPacketPublicHeader
& header
,
505 const QuicVersionVector
& supported_versions
) {
506 DCHECK(header
.version_flag
);
507 size_t len
= GetVersionNegotiationPacketSize(supported_versions
.size());
508 scoped_ptr
<char[]> buffer(new char[len
]);
509 QuicDataWriter
writer(len
, buffer
.get());
511 uint8 flags
= static_cast<uint8
>(PACKET_PUBLIC_FLAGS_VERSION
|
512 PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID
);
513 if (!writer
.WriteUInt8(flags
)) {
517 if (!writer
.WriteUInt64(header
.connection_id
)) {
521 for (size_t i
= 0; i
< supported_versions
.size(); ++i
) {
522 if (!writer
.WriteUInt32(QuicVersionToQuicTag(supported_versions
[i
]))) {
527 return new QuicEncryptedPacket(buffer
.release(), len
, true);
530 bool QuicFramer::ProcessPacket(const QuicEncryptedPacket
& packet
) {
531 DCHECK(!reader_
.get());
532 reader_
.reset(new QuicDataReader(packet
.data(), packet
.length()));
534 visitor_
->OnPacket();
536 // First parse the public header.
537 QuicPacketPublicHeader public_header
;
538 if (!ProcessPublicHeader(&public_header
)) {
539 DLOG(WARNING
) << "Unable to process public header.";
540 DCHECK_NE("", detailed_error_
);
541 return RaiseError(QUIC_INVALID_PACKET_HEADER
);
544 if (!visitor_
->OnUnauthenticatedPublicHeader(public_header
)) {
545 // The visitor suppresses further processing of the packet.
546 reader_
.reset(nullptr);
550 if (perspective_
== Perspective::IS_SERVER
&& public_header
.version_flag
&&
551 public_header
.versions
[0] != quic_version_
) {
552 if (!visitor_
->OnProtocolVersionMismatch(public_header
.versions
[0])) {
553 reader_
.reset(nullptr);
559 if (perspective_
== Perspective::IS_CLIENT
&& public_header
.version_flag
) {
560 rv
= ProcessVersionNegotiationPacket(&public_header
);
561 } else if (public_header
.reset_flag
) {
562 rv
= ProcessPublicResetPacket(public_header
);
563 } else if (packet
.length() <= kMaxPacketSize
) {
564 char buffer
[kMaxPacketSize
];
565 rv
= ProcessDataPacket(public_header
, packet
, buffer
, kMaxPacketSize
);
567 scoped_ptr
<char[]> large_buffer(new char[packet
.length()]);
568 rv
= ProcessDataPacket(public_header
, packet
, large_buffer
.get(),
570 LOG_IF(DFATAL
, rv
) << "QUIC should never successfully process packets "
571 << "larger than kMaxPacketSize. packet size:"
575 reader_
.reset(nullptr);
579 bool QuicFramer::ProcessVersionNegotiationPacket(
580 QuicPacketPublicHeader
* public_header
) {
581 DCHECK_EQ(Perspective::IS_CLIENT
, perspective_
);
582 // Try reading at least once to raise error if the packet is invalid.
585 if (!reader_
->ReadBytes(&version
, kQuicVersionSize
)) {
586 set_detailed_error("Unable to read supported version in negotiation.");
587 return RaiseError(QUIC_INVALID_VERSION_NEGOTIATION_PACKET
);
589 public_header
->versions
.push_back(QuicTagToQuicVersion(version
));
590 } while (!reader_
->IsDoneReading());
592 visitor_
->OnVersionNegotiationPacket(*public_header
);
596 bool QuicFramer::ProcessDataPacket(const QuicPacketPublicHeader
& public_header
,
597 const QuicEncryptedPacket
& packet
,
598 char* decrypted_buffer
,
599 size_t buffer_length
) {
600 QuicPacketHeader
header(public_header
);
601 if (!ProcessPacketHeader(&header
, packet
, decrypted_buffer
, buffer_length
)) {
602 DLOG(WARNING
) << "Unable to process packet header. Stopping parsing.";
606 if (!visitor_
->OnPacketHeader(header
)) {
607 // The visitor suppresses further processing of the packet.
611 if (packet
.length() > kMaxPacketSize
) {
612 DLOG(WARNING
) << "Packet too large: " << packet
.length();
613 return RaiseError(QUIC_PACKET_TOO_LARGE
);
616 // Handle the payload.
617 if (!header
.fec_flag
) {
618 if (header
.is_in_fec_group
== IN_FEC_GROUP
) {
619 StringPiece payload
= reader_
->PeekRemainingPayload();
620 visitor_
->OnFecProtectedPayload(payload
);
622 if (!ProcessFrameData(header
)) {
623 DCHECK_NE(QUIC_NO_ERROR
, error_
); // ProcessFrameData sets the error.
624 DLOG(WARNING
) << "Unable to process frame data.";
628 QuicFecData fec_data
;
629 fec_data
.fec_group
= header
.fec_group
;
630 fec_data
.redundancy
= reader_
->ReadRemainingPayload();
631 visitor_
->OnFecData(fec_data
);
634 visitor_
->OnPacketComplete();
638 bool QuicFramer::ProcessPublicResetPacket(
639 const QuicPacketPublicHeader
& public_header
) {
640 QuicPublicResetPacket
packet(public_header
);
642 scoped_ptr
<CryptoHandshakeMessage
> reset(
643 CryptoFramer::ParseMessage(reader_
->ReadRemainingPayload()));
645 set_detailed_error("Unable to read reset message.");
646 return RaiseError(QUIC_INVALID_PUBLIC_RST_PACKET
);
648 if (reset
->tag() != kPRST
) {
649 set_detailed_error("Incorrect message tag.");
650 return RaiseError(QUIC_INVALID_PUBLIC_RST_PACKET
);
653 if (reset
->GetUint64(kRNON
, &packet
.nonce_proof
) != QUIC_NO_ERROR
) {
654 set_detailed_error("Unable to read nonce proof.");
655 return RaiseError(QUIC_INVALID_PUBLIC_RST_PACKET
);
657 // TODO(satyamshekhar): validate nonce to protect against DoS.
659 if (reset
->GetUint64(kRSEQ
, &packet
.rejected_sequence_number
) !=
661 set_detailed_error("Unable to read rejected sequence number.");
662 return RaiseError(QUIC_INVALID_PUBLIC_RST_PACKET
);
666 if (reset
->GetStringPiece(kCADR
, &address
)) {
667 QuicSocketAddressCoder address_coder
;
668 if (address_coder
.Decode(address
.data(), address
.length())) {
669 packet
.client_address
= IPEndPoint(address_coder
.ip(),
670 address_coder
.port());
674 visitor_
->OnPublicResetPacket(packet
);
678 bool QuicFramer::ProcessRevivedPacket(QuicPacketHeader
* header
,
679 StringPiece payload
) {
680 DCHECK(!reader_
.get());
682 visitor_
->OnRevivedPacket();
684 header
->entropy_hash
= GetPacketEntropyHash(*header
);
686 if (!visitor_
->OnPacketHeader(*header
)) {
690 if (payload
.length() > kMaxPacketSize
) {
691 set_detailed_error("Revived packet too large.");
692 return RaiseError(QUIC_PACKET_TOO_LARGE
);
695 reader_
.reset(new QuicDataReader(payload
.data(), payload
.length()));
696 if (!ProcessFrameData(*header
)) {
697 DCHECK_NE(QUIC_NO_ERROR
, error_
); // ProcessFrameData sets the error.
698 DLOG(WARNING
) << "Unable to process frame data.";
702 visitor_
->OnPacketComplete();
703 reader_
.reset(nullptr);
707 bool QuicFramer::AppendPacketHeader(const QuicPacketHeader
& header
,
708 QuicDataWriter
* writer
) {
709 DVLOG(1) << "Appending header: " << header
;
710 DCHECK(header
.fec_group
> 0 || header
.is_in_fec_group
== NOT_IN_FEC_GROUP
);
711 uint8 public_flags
= 0;
712 if (header
.public_header
.reset_flag
) {
713 public_flags
|= PACKET_PUBLIC_FLAGS_RST
;
715 if (header
.public_header
.version_flag
) {
716 public_flags
|= PACKET_PUBLIC_FLAGS_VERSION
;
720 GetSequenceNumberFlags(header
.public_header
.sequence_number_length
)
721 << kPublicHeaderSequenceNumberShift
;
723 switch (header
.public_header
.connection_id_length
) {
724 case PACKET_0BYTE_CONNECTION_ID
:
725 if (!writer
->WriteUInt8(
726 public_flags
| PACKET_PUBLIC_FLAGS_0BYTE_CONNECTION_ID
)) {
730 case PACKET_1BYTE_CONNECTION_ID
:
731 if (!writer
->WriteUInt8(
732 public_flags
| PACKET_PUBLIC_FLAGS_1BYTE_CONNECTION_ID
)) {
735 if (!writer
->WriteUInt8(
736 header
.public_header
.connection_id
& k1ByteConnectionIdMask
)) {
740 case PACKET_4BYTE_CONNECTION_ID
:
741 if (!writer
->WriteUInt8(
742 public_flags
| PACKET_PUBLIC_FLAGS_4BYTE_CONNECTION_ID
)) {
745 if (!writer
->WriteUInt32(
746 header
.public_header
.connection_id
& k4ByteConnectionIdMask
)) {
750 case PACKET_8BYTE_CONNECTION_ID
:
751 if (!writer
->WriteUInt8(
752 public_flags
| PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID
)) {
755 if (!writer
->WriteUInt64(header
.public_header
.connection_id
)) {
760 last_serialized_connection_id_
= header
.public_header
.connection_id
;
762 if (header
.public_header
.version_flag
) {
763 DCHECK_EQ(Perspective::IS_CLIENT
, perspective_
);
764 QuicTag tag
= QuicVersionToQuicTag(quic_version_
);
765 writer
->WriteUInt32(tag
);
766 DVLOG(1) << "version = " << quic_version_
<< ", tag = '"
767 << QuicUtils::TagToString(tag
) << "'";
770 if (!AppendPacketSequenceNumber(header
.public_header
.sequence_number_length
,
771 header
.packet_sequence_number
, writer
)) {
775 uint8 private_flags
= 0;
776 if (header
.entropy_flag
) {
777 private_flags
|= PACKET_PRIVATE_FLAGS_ENTROPY
;
779 if (header
.is_in_fec_group
== IN_FEC_GROUP
) {
780 private_flags
|= PACKET_PRIVATE_FLAGS_FEC_GROUP
;
782 if (header
.fec_flag
) {
783 private_flags
|= PACKET_PRIVATE_FLAGS_FEC
;
785 if (!writer
->WriteUInt8(private_flags
)) {
789 // The FEC group number is the sequence number of the first fec
790 // protected packet, or 0 if this packet is not protected.
791 if (header
.is_in_fec_group
== IN_FEC_GROUP
) {
792 DCHECK_LE(header
.fec_group
, header
.packet_sequence_number
);
793 DCHECK_LT(header
.packet_sequence_number
- header
.fec_group
, 255u);
794 // Offset from the current packet sequence number to the first fec
796 uint8 first_fec_protected_packet_offset
=
797 static_cast<uint8
>(header
.packet_sequence_number
- header
.fec_group
);
798 if (!writer
->WriteBytes(&first_fec_protected_packet_offset
, 1)) {
806 const QuicTime::Delta
QuicFramer::CalculateTimestampFromWire(
807 uint32 time_delta_us
) {
808 // The new time_delta might have wrapped to the next epoch, or it
809 // might have reverse wrapped to the previous epoch, or it might
810 // remain in the same epoch. Select the time closest to the previous
813 // epoch_delta is the delta between epochs. A delta is 4 bytes of
815 const uint64 epoch_delta
= UINT64_C(1) << 32;
816 uint64 epoch
= last_timestamp_
.ToMicroseconds() & ~(epoch_delta
- 1);
817 // Wrapping is safe here because a wrapped value will not be ClosestTo below.
818 uint64 prev_epoch
= epoch
- epoch_delta
;
819 uint64 next_epoch
= epoch
+ epoch_delta
;
821 uint64 time
= ClosestTo(last_timestamp_
.ToMicroseconds(),
822 epoch
+ time_delta_us
,
823 ClosestTo(last_timestamp_
.ToMicroseconds(),
824 prev_epoch
+ time_delta_us
,
825 next_epoch
+ time_delta_us
));
827 return QuicTime::Delta::FromMicroseconds(time
);
830 QuicPacketSequenceNumber
QuicFramer::CalculatePacketSequenceNumberFromWire(
831 QuicSequenceNumberLength sequence_number_length
,
832 QuicPacketSequenceNumber packet_sequence_number
) const {
833 // The new sequence number might have wrapped to the next epoch, or
834 // it might have reverse wrapped to the previous epoch, or it might
835 // remain in the same epoch. Select the sequence number closest to the
836 // next expected sequence number, the previous sequence number plus 1.
838 // epoch_delta is the delta between epochs the sequence number was serialized
839 // with, so the correct value is likely the same epoch as the last sequence
840 // number or an adjacent epoch.
841 const QuicPacketSequenceNumber epoch_delta
=
842 UINT64_C(1) << (8 * sequence_number_length
);
843 QuicPacketSequenceNumber next_sequence_number
= last_sequence_number_
+ 1;
844 QuicPacketSequenceNumber epoch
= last_sequence_number_
& ~(epoch_delta
- 1);
845 QuicPacketSequenceNumber prev_epoch
= epoch
- epoch_delta
;
846 QuicPacketSequenceNumber next_epoch
= epoch
+ epoch_delta
;
848 return ClosestTo(next_sequence_number
,
849 epoch
+ packet_sequence_number
,
850 ClosestTo(next_sequence_number
,
851 prev_epoch
+ packet_sequence_number
,
852 next_epoch
+ packet_sequence_number
));
855 bool QuicFramer::ProcessPublicHeader(
856 QuicPacketPublicHeader
* public_header
) {
858 if (!reader_
->ReadBytes(&public_flags
, 1)) {
859 set_detailed_error("Unable to read public flags.");
863 public_header
->reset_flag
= (public_flags
& PACKET_PUBLIC_FLAGS_RST
) != 0;
864 public_header
->version_flag
=
865 (public_flags
& PACKET_PUBLIC_FLAGS_VERSION
) != 0;
867 if (validate_flags_
&&
868 !public_header
->version_flag
&& public_flags
> PACKET_PUBLIC_FLAGS_MAX
) {
869 set_detailed_error("Illegal public flags value.");
873 if (public_header
->reset_flag
&& public_header
->version_flag
) {
874 set_detailed_error("Got version flag in reset packet");
878 switch (public_flags
& PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID
) {
879 case PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID
:
880 if (!reader_
->ReadUInt64(&public_header
->connection_id
)) {
881 set_detailed_error("Unable to read ConnectionId.");
884 public_header
->connection_id_length
= PACKET_8BYTE_CONNECTION_ID
;
886 case PACKET_PUBLIC_FLAGS_4BYTE_CONNECTION_ID
:
887 // If the connection_id is truncated, expect to read the last serialized
889 if (!reader_
->ReadBytes(&public_header
->connection_id
,
890 PACKET_4BYTE_CONNECTION_ID
)) {
891 set_detailed_error("Unable to read ConnectionId.");
894 if (last_serialized_connection_id_
&&
895 (public_header
->connection_id
& k4ByteConnectionIdMask
) !=
896 (last_serialized_connection_id_
& k4ByteConnectionIdMask
)) {
897 set_detailed_error("Truncated 4 byte ConnectionId does not match "
898 "previous connection_id.");
901 public_header
->connection_id_length
= PACKET_4BYTE_CONNECTION_ID
;
902 public_header
->connection_id
= last_serialized_connection_id_
;
904 case PACKET_PUBLIC_FLAGS_1BYTE_CONNECTION_ID
:
905 if (!reader_
->ReadBytes(&public_header
->connection_id
,
906 PACKET_1BYTE_CONNECTION_ID
)) {
907 set_detailed_error("Unable to read ConnectionId.");
910 if (last_serialized_connection_id_
&&
911 (public_header
->connection_id
& k1ByteConnectionIdMask
) !=
912 (last_serialized_connection_id_
& k1ByteConnectionIdMask
)) {
913 set_detailed_error("Truncated 1 byte ConnectionId does not match "
914 "previous connection_id.");
917 public_header
->connection_id_length
= PACKET_1BYTE_CONNECTION_ID
;
918 public_header
->connection_id
= last_serialized_connection_id_
;
920 case PACKET_PUBLIC_FLAGS_0BYTE_CONNECTION_ID
:
921 public_header
->connection_id_length
= PACKET_0BYTE_CONNECTION_ID
;
922 public_header
->connection_id
= last_serialized_connection_id_
;
926 public_header
->sequence_number_length
=
927 ReadSequenceNumberLength(
928 public_flags
>> kPublicHeaderSequenceNumberShift
);
930 // Read the version only if the packet is from the client.
931 // version flag from the server means version negotiation packet.
932 if (public_header
->version_flag
&& perspective_
== Perspective::IS_SERVER
) {
934 if (!reader_
->ReadUInt32(&version_tag
)) {
935 set_detailed_error("Unable to read protocol version.");
939 // If the version from the new packet is the same as the version of this
940 // framer, then the public flags should be set to something we understand.
941 // If not, this raises an error.
942 QuicVersion version
= QuicTagToQuicVersion(version_tag
);
943 if (version
== quic_version_
&& public_flags
> PACKET_PUBLIC_FLAGS_MAX
) {
944 set_detailed_error("Illegal public flags value.");
947 public_header
->versions
.push_back(version
);
953 QuicSequenceNumberLength
QuicFramer::GetMinSequenceNumberLength(
954 QuicPacketSequenceNumber sequence_number
) {
955 if (sequence_number
< 1 << (PACKET_1BYTE_SEQUENCE_NUMBER
* 8)) {
956 return PACKET_1BYTE_SEQUENCE_NUMBER
;
957 } else if (sequence_number
< 1 << (PACKET_2BYTE_SEQUENCE_NUMBER
* 8)) {
958 return PACKET_2BYTE_SEQUENCE_NUMBER
;
959 } else if (sequence_number
<
960 UINT64_C(1) << (PACKET_4BYTE_SEQUENCE_NUMBER
* 8)) {
961 return PACKET_4BYTE_SEQUENCE_NUMBER
;
963 return PACKET_6BYTE_SEQUENCE_NUMBER
;
968 uint8
QuicFramer::GetSequenceNumberFlags(
969 QuicSequenceNumberLength sequence_number_length
) {
970 switch (sequence_number_length
) {
971 case PACKET_1BYTE_SEQUENCE_NUMBER
:
972 return PACKET_FLAGS_1BYTE_SEQUENCE
;
973 case PACKET_2BYTE_SEQUENCE_NUMBER
:
974 return PACKET_FLAGS_2BYTE_SEQUENCE
;
975 case PACKET_4BYTE_SEQUENCE_NUMBER
:
976 return PACKET_FLAGS_4BYTE_SEQUENCE
;
977 case PACKET_6BYTE_SEQUENCE_NUMBER
:
978 return PACKET_FLAGS_6BYTE_SEQUENCE
;
980 LOG(DFATAL
) << "Unreachable case statement.";
981 return PACKET_FLAGS_6BYTE_SEQUENCE
;
986 QuicFramer::AckFrameInfo
QuicFramer::GetAckFrameInfo(
987 const QuicAckFrame
& frame
) {
988 AckFrameInfo ack_info
;
989 if (frame
.missing_packets
.empty()) {
992 DCHECK_GE(frame
.largest_observed
, *frame
.missing_packets
.rbegin());
993 size_t cur_range_length
= 0;
994 SequenceNumberSet::const_iterator iter
= frame
.missing_packets
.begin();
995 QuicPacketSequenceNumber last_missing
= *iter
;
997 for (; iter
!= frame
.missing_packets
.end(); ++iter
) {
998 if (cur_range_length
< numeric_limits
<uint8
>::max() &&
999 *iter
== (last_missing
+ 1)) {
1002 ack_info
.nack_ranges
[last_missing
- cur_range_length
] =
1003 static_cast<uint8
>(cur_range_length
);
1004 cur_range_length
= 0;
1006 ack_info
.max_delta
= max(ack_info
.max_delta
, *iter
- last_missing
);
1007 last_missing
= *iter
;
1009 // Include the last nack range.
1010 ack_info
.nack_ranges
[last_missing
- cur_range_length
] =
1011 static_cast<uint8
>(cur_range_length
);
1012 // Include the range to the largest observed.
1013 ack_info
.max_delta
=
1014 max(ack_info
.max_delta
, frame
.largest_observed
- last_missing
);
1018 bool QuicFramer::ProcessPacketHeader(QuicPacketHeader
* header
,
1019 const QuicEncryptedPacket
& packet
,
1020 char* decrypted_buffer
,
1021 size_t buffer_length
) {
1022 if (!ProcessPacketSequenceNumber(header
->public_header
.sequence_number_length
,
1023 &header
->packet_sequence_number
)) {
1024 set_detailed_error("Unable to read sequence number.");
1025 return RaiseError(QUIC_INVALID_PACKET_HEADER
);
1028 if (header
->packet_sequence_number
== 0u) {
1029 set_detailed_error("Packet sequence numbers cannot be 0.");
1030 return RaiseError(QUIC_INVALID_PACKET_HEADER
);
1033 if (!visitor_
->OnUnauthenticatedHeader(*header
)) {
1037 if (!DecryptPayload(*header
, packet
, decrypted_buffer
, buffer_length
)) {
1038 set_detailed_error("Unable to decrypt payload.");
1039 return RaiseError(QUIC_DECRYPTION_FAILURE
);
1042 uint8 private_flags
;
1043 if (!reader_
->ReadBytes(&private_flags
, 1)) {
1044 set_detailed_error("Unable to read private flags.");
1045 return RaiseError(QUIC_INVALID_PACKET_HEADER
);
1048 if (private_flags
> PACKET_PRIVATE_FLAGS_MAX
) {
1049 set_detailed_error("Illegal private flags value.");
1050 return RaiseError(QUIC_INVALID_PACKET_HEADER
);
1053 header
->entropy_flag
= (private_flags
& PACKET_PRIVATE_FLAGS_ENTROPY
) != 0;
1054 header
->fec_flag
= (private_flags
& PACKET_PRIVATE_FLAGS_FEC
) != 0;
1056 if ((private_flags
& PACKET_PRIVATE_FLAGS_FEC_GROUP
) != 0) {
1057 header
->is_in_fec_group
= IN_FEC_GROUP
;
1058 uint8 first_fec_protected_packet_offset
;
1059 if (!reader_
->ReadBytes(&first_fec_protected_packet_offset
, 1)) {
1060 set_detailed_error("Unable to read first fec protected packet offset.");
1061 return RaiseError(QUIC_INVALID_PACKET_HEADER
);
1063 if (first_fec_protected_packet_offset
>= header
->packet_sequence_number
) {
1064 set_detailed_error("First fec protected packet offset must be less "
1065 "than the sequence number.");
1066 return RaiseError(QUIC_INVALID_PACKET_HEADER
);
1069 header
->packet_sequence_number
- first_fec_protected_packet_offset
;
1072 header
->entropy_hash
= GetPacketEntropyHash(*header
);
1073 // Set the last sequence number after we have decrypted the packet
1074 // so we are confident is not attacker controlled.
1075 last_sequence_number_
= header
->packet_sequence_number
;
1079 bool QuicFramer::ProcessPacketSequenceNumber(
1080 QuicSequenceNumberLength sequence_number_length
,
1081 QuicPacketSequenceNumber
* sequence_number
) {
1082 QuicPacketSequenceNumber wire_sequence_number
= 0u;
1083 if (!reader_
->ReadBytes(&wire_sequence_number
, sequence_number_length
)) {
1087 // TODO(ianswett): Explore the usefulness of trying multiple sequence numbers
1088 // in case the first guess is incorrect.
1090 CalculatePacketSequenceNumberFromWire(sequence_number_length
,
1091 wire_sequence_number
);
1095 bool QuicFramer::ProcessFrameData(const QuicPacketHeader
& header
) {
1096 if (reader_
->IsDoneReading()) {
1097 set_detailed_error("Packet has no frames.");
1098 return RaiseError(QUIC_MISSING_PAYLOAD
);
1100 while (!reader_
->IsDoneReading()) {
1102 if (!reader_
->ReadBytes(&frame_type
, 1)) {
1103 set_detailed_error("Unable to read frame type.");
1104 return RaiseError(QUIC_INVALID_FRAME_DATA
);
1107 if (frame_type
& kQuicFrameTypeSpecialMask
) {
1109 if (frame_type
& kQuicFrameTypeStreamMask
) {
1110 QuicStreamFrame frame
;
1111 if (!ProcessStreamFrame(frame_type
, &frame
)) {
1112 return RaiseError(QUIC_INVALID_STREAM_DATA
);
1114 if (!visitor_
->OnStreamFrame(frame
)) {
1115 DVLOG(1) << "Visitor asked to stop further processing.";
1116 // Returning true since there was no parsing error.
1123 if (frame_type
& kQuicFrameTypeAckMask
) {
1125 if (!ProcessAckFrame(frame_type
, &frame
)) {
1126 return RaiseError(QUIC_INVALID_ACK_DATA
);
1128 if (!visitor_
->OnAckFrame(frame
)) {
1129 DVLOG(1) << "Visitor asked to stop further processing.";
1130 // Returning true since there was no parsing error.
1136 // This was a special frame type that did not match any
1137 // of the known ones. Error.
1138 set_detailed_error("Illegal frame type.");
1139 DLOG(WARNING
) << "Illegal frame type: "
1140 << static_cast<int>(frame_type
);
1141 return RaiseError(QUIC_INVALID_FRAME_DATA
);
1144 switch (frame_type
) {
1146 // We're done with the packet.
1149 case RST_STREAM_FRAME
: {
1150 QuicRstStreamFrame frame
;
1151 if (!ProcessRstStreamFrame(&frame
)) {
1152 return RaiseError(QUIC_INVALID_RST_STREAM_DATA
);
1154 if (!visitor_
->OnRstStreamFrame(frame
)) {
1155 DVLOG(1) << "Visitor asked to stop further processing.";
1156 // Returning true since there was no parsing error.
1162 case CONNECTION_CLOSE_FRAME
: {
1163 QuicConnectionCloseFrame frame
;
1164 if (!ProcessConnectionCloseFrame(&frame
)) {
1165 return RaiseError(QUIC_INVALID_CONNECTION_CLOSE_DATA
);
1168 if (!visitor_
->OnConnectionCloseFrame(frame
)) {
1169 DVLOG(1) << "Visitor asked to stop further processing.";
1170 // Returning true since there was no parsing error.
1176 case GOAWAY_FRAME
: {
1177 QuicGoAwayFrame goaway_frame
;
1178 if (!ProcessGoAwayFrame(&goaway_frame
)) {
1179 return RaiseError(QUIC_INVALID_GOAWAY_DATA
);
1181 if (!visitor_
->OnGoAwayFrame(goaway_frame
)) {
1182 DVLOG(1) << "Visitor asked to stop further processing.";
1183 // Returning true since there was no parsing error.
1189 case WINDOW_UPDATE_FRAME
: {
1190 QuicWindowUpdateFrame window_update_frame
;
1191 if (!ProcessWindowUpdateFrame(&window_update_frame
)) {
1192 return RaiseError(QUIC_INVALID_WINDOW_UPDATE_DATA
);
1194 if (!visitor_
->OnWindowUpdateFrame(window_update_frame
)) {
1195 DVLOG(1) << "Visitor asked to stop further processing.";
1196 // Returning true since there was no parsing error.
1202 case BLOCKED_FRAME
: {
1203 QuicBlockedFrame blocked_frame
;
1204 if (!ProcessBlockedFrame(&blocked_frame
)) {
1205 return RaiseError(QUIC_INVALID_BLOCKED_DATA
);
1207 if (!visitor_
->OnBlockedFrame(blocked_frame
)) {
1208 DVLOG(1) << "Visitor asked to stop further processing.";
1209 // Returning true since there was no parsing error.
1215 case STOP_WAITING_FRAME
: {
1216 QuicStopWaitingFrame stop_waiting_frame
;
1217 if (!ProcessStopWaitingFrame(header
, &stop_waiting_frame
)) {
1218 return RaiseError(QUIC_INVALID_STOP_WAITING_DATA
);
1220 if (!visitor_
->OnStopWaitingFrame(stop_waiting_frame
)) {
1221 DVLOG(1) << "Visitor asked to stop further processing.";
1222 // Returning true since there was no parsing error.
1228 // Ping has no payload.
1229 QuicPingFrame ping_frame
;
1230 if (!visitor_
->OnPingFrame(ping_frame
)) {
1231 DVLOG(1) << "Visitor asked to stop further processing.";
1232 // Returning true since there was no parsing error.
1239 set_detailed_error("Illegal frame type.");
1240 DLOG(WARNING
) << "Illegal frame type: "
1241 << static_cast<int>(frame_type
);
1242 return RaiseError(QUIC_INVALID_FRAME_DATA
);
1249 bool QuicFramer::ProcessStreamFrame(uint8 frame_type
,
1250 QuicStreamFrame
* frame
) {
1251 uint8 stream_flags
= frame_type
;
1253 stream_flags
&= ~kQuicFrameTypeStreamMask
;
1255 // Read from right to left: StreamID, Offset, Data Length, Fin.
1256 const uint8 stream_id_length
= (stream_flags
& kQuicStreamIDLengthMask
) + 1;
1257 stream_flags
>>= kQuicStreamIdShift
;
1259 uint8 offset_length
= (stream_flags
& kQuicStreamOffsetMask
);
1260 // There is no encoding for 1 byte, only 0 and 2 through 8.
1261 if (offset_length
> 0) {
1264 stream_flags
>>= kQuicStreamOffsetShift
;
1266 bool has_data_length
=
1267 (stream_flags
& kQuicStreamDataLengthMask
) == kQuicStreamDataLengthMask
;
1268 stream_flags
>>= kQuicStreamDataLengthShift
;
1270 frame
->fin
= (stream_flags
& kQuicStreamFinMask
) == kQuicStreamFinShift
;
1272 frame
->stream_id
= 0;
1273 if (!reader_
->ReadBytes(&frame
->stream_id
, stream_id_length
)) {
1274 set_detailed_error("Unable to read stream_id.");
1279 if (!reader_
->ReadBytes(&frame
->offset
, offset_length
)) {
1280 set_detailed_error("Unable to read offset.");
1284 StringPiece frame_data
;
1285 if (has_data_length
) {
1286 if (!reader_
->ReadStringPiece16(&frame_data
)) {
1287 set_detailed_error("Unable to read frame data.");
1291 if (!reader_
->ReadStringPiece(&frame_data
, reader_
->BytesRemaining())) {
1292 set_detailed_error("Unable to read frame data.");
1296 // Point frame to the right data.
1297 frame
->data
.Clear();
1298 if (!frame_data
.empty()) {
1299 frame
->data
.Append(const_cast<char*>(frame_data
.data()), frame_data
.size());
1305 bool QuicFramer::ProcessAckFrame(uint8 frame_type
, QuicAckFrame
* ack_frame
) {
1306 // Determine the three lengths from the frame type: largest observed length,
1307 // missing sequence number length, and missing range length.
1308 const QuicSequenceNumberLength missing_sequence_number_length
=
1309 ReadSequenceNumberLength(frame_type
);
1310 frame_type
>>= kQuicSequenceNumberLengthShift
;
1311 const QuicSequenceNumberLength largest_observed_sequence_number_length
=
1312 ReadSequenceNumberLength(frame_type
);
1313 frame_type
>>= kQuicSequenceNumberLengthShift
;
1314 ack_frame
->is_truncated
= frame_type
& kQuicAckTruncatedMask
;
1315 frame_type
>>= kQuicAckTruncatedShift
;
1316 bool has_nacks
= frame_type
& kQuicHasNacksMask
;
1318 if (!reader_
->ReadBytes(&ack_frame
->entropy_hash
, 1)) {
1319 set_detailed_error("Unable to read entropy hash for received packets.");
1323 if (!reader_
->ReadBytes(&ack_frame
->largest_observed
,
1324 largest_observed_sequence_number_length
)) {
1325 set_detailed_error("Unable to read largest observed.");
1329 uint64 delta_time_largest_observed_us
;
1330 if (!reader_
->ReadUFloat16(&delta_time_largest_observed_us
)) {
1331 set_detailed_error("Unable to read delta time largest observed.");
1335 if (delta_time_largest_observed_us
== kUFloat16MaxValue
) {
1336 ack_frame
->delta_time_largest_observed
= QuicTime::Delta::Infinite();
1338 ack_frame
->delta_time_largest_observed
=
1339 QuicTime::Delta::FromMicroseconds(delta_time_largest_observed_us
);
1342 if (!ProcessTimestampsInAckFrame(ack_frame
)) {
1350 uint8 num_missing_ranges
;
1351 if (!reader_
->ReadBytes(&num_missing_ranges
, 1)) {
1352 set_detailed_error("Unable to read num missing packet ranges.");
1356 QuicPacketSequenceNumber last_sequence_number
= ack_frame
->largest_observed
;
1357 for (size_t i
= 0; i
< num_missing_ranges
; ++i
) {
1358 QuicPacketSequenceNumber missing_delta
= 0;
1359 if (!reader_
->ReadBytes(&missing_delta
, missing_sequence_number_length
)) {
1360 set_detailed_error("Unable to read missing sequence number delta.");
1363 last_sequence_number
-= missing_delta
;
1364 QuicPacketSequenceNumber range_length
= 0;
1365 if (!reader_
->ReadBytes(&range_length
, PACKET_1BYTE_SEQUENCE_NUMBER
)) {
1366 set_detailed_error("Unable to read missing sequence number range.");
1369 for (size_t j
= 0; j
<= range_length
; ++j
) {
1370 ack_frame
->missing_packets
.insert(last_sequence_number
- j
);
1372 // Subtract an extra 1 to ensure ranges are represented efficiently and
1373 // can't overlap by 1 sequence number. This allows a missing_delta of 0
1374 // to represent an adjacent nack range.
1375 last_sequence_number
-= (range_length
+ 1);
1378 // Parse the revived packets list.
1379 uint8 num_revived_packets
;
1380 if (!reader_
->ReadBytes(&num_revived_packets
, 1)) {
1381 set_detailed_error("Unable to read num revived packets.");
1385 for (size_t i
= 0; i
< num_revived_packets
; ++i
) {
1386 QuicPacketSequenceNumber revived_packet
= 0;
1387 if (!reader_
->ReadBytes(&revived_packet
,
1388 largest_observed_sequence_number_length
)) {
1389 set_detailed_error("Unable to read revived packet.");
1393 ack_frame
->revived_packets
.insert(revived_packet
);
1399 bool QuicFramer::ProcessTimestampsInAckFrame(QuicAckFrame
* ack_frame
) {
1400 if (ack_frame
->is_truncated
) {
1403 uint8 num_received_packets
;
1404 if (!reader_
->ReadBytes(&num_received_packets
, 1)) {
1405 set_detailed_error("Unable to read num received packets.");
1409 if (num_received_packets
> 0) {
1410 uint8 delta_from_largest_observed
;
1411 if (!reader_
->ReadBytes(&delta_from_largest_observed
,
1412 PACKET_1BYTE_SEQUENCE_NUMBER
)) {
1413 set_detailed_error("Unable to read sequence delta in received packets.");
1416 QuicPacketSequenceNumber seq_num
=
1417 ack_frame
->largest_observed
- delta_from_largest_observed
;
1419 // Time delta from the framer creation.
1420 uint32 time_delta_us
;
1421 if (!reader_
->ReadBytes(&time_delta_us
, sizeof(time_delta_us
))) {
1422 set_detailed_error("Unable to read time delta in received packets.");
1426 last_timestamp_
= CalculateTimestampFromWire(time_delta_us
);
1428 ack_frame
->received_packet_times
.push_back(
1429 std::make_pair(seq_num
, creation_time_
.Add(last_timestamp_
)));
1431 for (uint8 i
= 1; i
< num_received_packets
; ++i
) {
1432 if (!reader_
->ReadBytes(&delta_from_largest_observed
,
1433 PACKET_1BYTE_SEQUENCE_NUMBER
)) {
1435 "Unable to read sequence delta in received packets.");
1438 seq_num
= ack_frame
->largest_observed
- delta_from_largest_observed
;
1440 // Time delta from the previous timestamp.
1441 uint64 incremental_time_delta_us
;
1442 if (!reader_
->ReadUFloat16(&incremental_time_delta_us
)) {
1444 "Unable to read incremental time delta in received packets.");
1448 last_timestamp_
= last_timestamp_
.Add(
1449 QuicTime::Delta::FromMicroseconds(incremental_time_delta_us
));
1450 ack_frame
->received_packet_times
.push_back(
1451 std::make_pair(seq_num
, creation_time_
.Add(last_timestamp_
)));
1457 bool QuicFramer::ProcessStopWaitingFrame(const QuicPacketHeader
& header
,
1458 QuicStopWaitingFrame
* stop_waiting
) {
1459 if (!reader_
->ReadBytes(&stop_waiting
->entropy_hash
, 1)) {
1460 set_detailed_error("Unable to read entropy hash for sent packets.");
1464 QuicPacketSequenceNumber least_unacked_delta
= 0;
1465 if (!reader_
->ReadBytes(&least_unacked_delta
,
1466 header
.public_header
.sequence_number_length
)) {
1467 set_detailed_error("Unable to read least unacked delta.");
1470 DCHECK_GE(header
.packet_sequence_number
, least_unacked_delta
);
1471 stop_waiting
->least_unacked
=
1472 header
.packet_sequence_number
- least_unacked_delta
;
1477 bool QuicFramer::ProcessRstStreamFrame(QuicRstStreamFrame
* frame
) {
1478 if (!reader_
->ReadUInt32(&frame
->stream_id
)) {
1479 set_detailed_error("Unable to read stream_id.");
1483 if (!reader_
->ReadUInt64(&frame
->byte_offset
)) {
1484 set_detailed_error("Unable to read rst stream sent byte offset.");
1489 if (!reader_
->ReadUInt32(&error_code
)) {
1490 set_detailed_error("Unable to read rst stream error code.");
1494 if (error_code
>= QUIC_STREAM_LAST_ERROR
) {
1495 set_detailed_error("Invalid rst stream error code.");
1499 frame
->error_code
= static_cast<QuicRstStreamErrorCode
>(error_code
);
1500 if (quic_version_
<= QUIC_VERSION_24
) {
1501 StringPiece error_details
;
1502 if (!reader_
->ReadStringPiece16(&error_details
)) {
1503 set_detailed_error("Unable to read rst stream error details.");
1506 frame
->error_details
= error_details
.as_string();
1512 bool QuicFramer::ProcessConnectionCloseFrame(QuicConnectionCloseFrame
* frame
) {
1514 if (!reader_
->ReadUInt32(&error_code
)) {
1515 set_detailed_error("Unable to read connection close error code.");
1519 if (error_code
>= QUIC_LAST_ERROR
) {
1520 set_detailed_error("Invalid error code.");
1524 frame
->error_code
= static_cast<QuicErrorCode
>(error_code
);
1526 StringPiece error_details
;
1527 if (!reader_
->ReadStringPiece16(&error_details
)) {
1528 set_detailed_error("Unable to read connection close error details.");
1531 frame
->error_details
= error_details
.as_string();
1536 bool QuicFramer::ProcessGoAwayFrame(QuicGoAwayFrame
* frame
) {
1538 if (!reader_
->ReadUInt32(&error_code
)) {
1539 set_detailed_error("Unable to read go away error code.");
1542 frame
->error_code
= static_cast<QuicErrorCode
>(error_code
);
1544 if (error_code
>= QUIC_LAST_ERROR
) {
1545 set_detailed_error("Invalid error code.");
1550 if (!reader_
->ReadUInt32(&stream_id
)) {
1551 set_detailed_error("Unable to read last good stream id.");
1554 frame
->last_good_stream_id
= static_cast<QuicStreamId
>(stream_id
);
1556 StringPiece reason_phrase
;
1557 if (!reader_
->ReadStringPiece16(&reason_phrase
)) {
1558 set_detailed_error("Unable to read goaway reason.");
1561 frame
->reason_phrase
= reason_phrase
.as_string();
1566 bool QuicFramer::ProcessWindowUpdateFrame(QuicWindowUpdateFrame
* frame
) {
1567 if (!reader_
->ReadUInt32(&frame
->stream_id
)) {
1568 set_detailed_error("Unable to read stream_id.");
1572 if (!reader_
->ReadUInt64(&frame
->byte_offset
)) {
1573 set_detailed_error("Unable to read window byte_offset.");
1580 bool QuicFramer::ProcessBlockedFrame(QuicBlockedFrame
* frame
) {
1581 if (!reader_
->ReadUInt32(&frame
->stream_id
)) {
1582 set_detailed_error("Unable to read stream_id.");
1590 StringPiece
QuicFramer::GetAssociatedDataFromEncryptedPacket(
1591 const QuicEncryptedPacket
& encrypted
,
1592 QuicConnectionIdLength connection_id_length
,
1593 bool includes_version
,
1594 QuicSequenceNumberLength sequence_number_length
) {
1596 encrypted
.data() + kStartOfHashData
, GetStartOfEncryptedData(
1597 connection_id_length
, includes_version
, sequence_number_length
)
1598 - kStartOfHashData
);
1601 void QuicFramer::SetDecrypter(QuicDecrypter
* decrypter
,
1602 EncryptionLevel level
) {
1603 DCHECK(alternative_decrypter_
.get() == nullptr);
1604 DCHECK_GE(level
, decrypter_level_
);
1605 decrypter_
.reset(decrypter
);
1606 decrypter_level_
= level
;
1609 void QuicFramer::SetAlternativeDecrypter(QuicDecrypter
* decrypter
,
1610 EncryptionLevel level
,
1611 bool latch_once_used
) {
1612 alternative_decrypter_
.reset(decrypter
);
1613 alternative_decrypter_level_
= level
;
1614 alternative_decrypter_latch_
= latch_once_used
;
1617 const QuicDecrypter
* QuicFramer::decrypter() const {
1618 return decrypter_
.get();
1621 const QuicDecrypter
* QuicFramer::alternative_decrypter() const {
1622 return alternative_decrypter_
.get();
1625 void QuicFramer::SetEncrypter(EncryptionLevel level
,
1626 QuicEncrypter
* encrypter
) {
1627 DCHECK_GE(level
, 0);
1628 DCHECK_LT(level
, NUM_ENCRYPTION_LEVELS
);
1629 encrypter_
[level
].reset(encrypter
);
1632 QuicEncryptedPacket
* QuicFramer::EncryptPacket(
1633 EncryptionLevel level
,
1634 QuicPacketSequenceNumber packet_sequence_number
,
1635 const QuicPacket
& packet
,
1637 size_t buffer_len
) {
1638 DCHECK(encrypter_
[level
].get() != nullptr);
1640 const size_t encrypted_len
=
1641 encrypter_
[level
]->GetCiphertextSize(packet
.Plaintext().length());
1642 StringPiece header_data
= packet
.BeforePlaintext();
1643 const size_t total_len
= header_data
.length() + encrypted_len
;
1645 char* encryption_buffer
= buffer
;
1646 // Allocate a large enough buffer for the header and the encrypted data.
1647 const bool is_new_buffer
= total_len
> buffer_len
;
1648 if (is_new_buffer
) {
1649 if (!FLAGS_quic_allow_oversized_packets_for_test
) {
1650 LOG(DFATAL
) << "Buffer of length:" << buffer_len
1651 << " is not large enough to encrypt length " << total_len
;
1654 encryption_buffer
= new char[total_len
];
1656 // Copy in the header, because the encrypter only populates the encrypted
1657 // plaintext content.
1658 memcpy(encryption_buffer
, header_data
.data(), header_data
.length());
1659 // Encrypt the plaintext into the buffer.
1660 size_t output_length
= 0;
1661 if (!encrypter_
[level
]->EncryptPacket(
1662 packet_sequence_number
, packet
.AssociatedData(), packet
.Plaintext(),
1663 encryption_buffer
+ header_data
.length(), &output_length
,
1665 RaiseError(QUIC_ENCRYPTION_FAILURE
);
1669 return new QuicEncryptedPacket(
1670 encryption_buffer
, header_data
.length() + output_length
, is_new_buffer
);
1673 size_t QuicFramer::GetMaxPlaintextSize(size_t ciphertext_size
) {
1674 // In order to keep the code simple, we don't have the current encryption
1675 // level to hand. Both the NullEncrypter and AES-GCM have a tag length of 12.
1676 size_t min_plaintext_size
= ciphertext_size
;
1678 for (int i
= ENCRYPTION_NONE
; i
< NUM_ENCRYPTION_LEVELS
; i
++) {
1679 if (encrypter_
[i
].get() != nullptr) {
1680 size_t size
= encrypter_
[i
]->GetMaxPlaintextSize(ciphertext_size
);
1681 if (size
< min_plaintext_size
) {
1682 min_plaintext_size
= size
;
1687 return min_plaintext_size
;
1690 bool QuicFramer::DecryptPayload(const QuicPacketHeader
& header
,
1691 const QuicEncryptedPacket
& packet
,
1692 char* decrypted_buffer
,
1693 size_t buffer_length
) {
1694 StringPiece encrypted
= reader_
->ReadRemainingPayload();
1695 DCHECK(decrypter_
.get() != nullptr);
1696 const StringPiece
& associated_data
= GetAssociatedDataFromEncryptedPacket(
1697 packet
, header
.public_header
.connection_id_length
,
1698 header
.public_header
.version_flag
,
1699 header
.public_header
.sequence_number_length
);
1700 size_t decrypted_length
= 0;
1701 bool success
= decrypter_
->DecryptPacket(
1702 header
.packet_sequence_number
, associated_data
, encrypted
,
1703 decrypted_buffer
, &decrypted_length
, buffer_length
);
1705 visitor_
->OnDecryptedPacket(decrypter_level_
);
1706 } else if (alternative_decrypter_
.get() != nullptr) {
1707 success
= alternative_decrypter_
->DecryptPacket(
1708 header
.packet_sequence_number
, associated_data
, encrypted
,
1709 decrypted_buffer
, &decrypted_length
, buffer_length
);
1711 visitor_
->OnDecryptedPacket(alternative_decrypter_level_
);
1712 if (alternative_decrypter_latch_
) {
1713 // Switch to the alternative decrypter and latch so that we cannot
1715 decrypter_
.reset(alternative_decrypter_
.release());
1716 decrypter_level_
= alternative_decrypter_level_
;
1717 alternative_decrypter_level_
= ENCRYPTION_NONE
;
1719 // Switch the alternative decrypter so that we use it first next time.
1720 decrypter_
.swap(alternative_decrypter_
);
1721 EncryptionLevel level
= alternative_decrypter_level_
;
1722 alternative_decrypter_level_
= decrypter_level_
;
1723 decrypter_level_
= level
;
1729 DLOG(WARNING
) << "DecryptPacket failed for sequence_number:"
1730 << header
.packet_sequence_number
;
1734 reader_
.reset(new QuicDataReader(decrypted_buffer
, decrypted_length
));
1738 size_t QuicFramer::GetAckFrameSize(
1739 const QuicAckFrame
& ack
,
1740 QuicSequenceNumberLength sequence_number_length
) {
1741 AckFrameInfo ack_info
= GetAckFrameInfo(ack
);
1742 QuicSequenceNumberLength largest_observed_length
=
1743 GetMinSequenceNumberLength(ack
.largest_observed
);
1744 QuicSequenceNumberLength missing_sequence_number_length
=
1745 GetMinSequenceNumberLength(ack_info
.max_delta
);
1747 size_t ack_size
= GetMinAckFrameSize(sequence_number_length
,
1748 largest_observed_length
);
1749 if (!ack_info
.nack_ranges
.empty()) {
1750 ack_size
+= kNumberOfNackRangesSize
+ kNumberOfRevivedPacketsSize
;
1751 ack_size
+= min(ack_info
.nack_ranges
.size(), kMaxNackRanges
) *
1752 (missing_sequence_number_length
+ PACKET_1BYTE_SEQUENCE_NUMBER
);
1753 ack_size
+= min(ack
.revived_packets
.size(),
1754 kMaxRevivedPackets
) * largest_observed_length
;
1757 // In version 23, if the ack will be truncated due to too many nack ranges,
1758 // then do not include the number of timestamps (1 byte).
1759 if (ack_info
.nack_ranges
.size() <= kMaxNackRanges
) {
1760 // 1 byte for the number of timestamps.
1762 if (ack
.received_packet_times
.size() > 0) {
1763 // 1 byte for sequence number, 4 bytes for timestamp for the first
1767 // 1 byte for sequence number, 2 bytes for timestamp for the other
1769 ack_size
+= 3 * (ack
.received_packet_times
.size() - 1);
1776 size_t QuicFramer::ComputeFrameLength(
1777 const QuicFrame
& frame
,
1778 bool last_frame_in_packet
,
1779 InFecGroup is_in_fec_group
,
1780 QuicSequenceNumberLength sequence_number_length
) {
1781 switch (frame
.type
) {
1783 return GetMinStreamFrameSize(frame
.stream_frame
->stream_id
,
1784 frame
.stream_frame
->offset
,
1785 last_frame_in_packet
,
1787 frame
.stream_frame
->data
.TotalBufferSize();
1789 return GetAckFrameSize(*frame
.ack_frame
, sequence_number_length
);
1791 case STOP_WAITING_FRAME
:
1792 return GetStopWaitingFrameSize(sequence_number_length
);
1794 // Ping has no payload.
1795 return kQuicFrameTypeSize
;
1796 case RST_STREAM_FRAME
:
1797 if (quic_version_
<= QUIC_VERSION_24
) {
1798 return GetMinRstStreamFrameSize() +
1799 frame
.rst_stream_frame
->error_details
.size();
1801 return GetRstStreamFrameSize();
1802 case CONNECTION_CLOSE_FRAME
:
1803 return GetMinConnectionCloseFrameSize() +
1804 frame
.connection_close_frame
->error_details
.size();
1806 return GetMinGoAwayFrameSize() + frame
.goaway_frame
->reason_phrase
.size();
1807 case WINDOW_UPDATE_FRAME
:
1808 return GetWindowUpdateFrameSize();
1810 return GetBlockedFrameSize();
1814 case NUM_FRAME_TYPES
:
1819 // Not reachable, but some Chrome compilers can't figure that out. *sigh*
1824 bool QuicFramer::AppendTypeByte(const QuicFrame
& frame
,
1825 bool no_stream_frame_length
,
1826 QuicDataWriter
* writer
) {
1827 uint8 type_byte
= 0;
1828 switch (frame
.type
) {
1829 case STREAM_FRAME
: {
1830 if (frame
.stream_frame
== nullptr) {
1831 LOG(DFATAL
) << "Failed to append STREAM frame with no stream_frame.";
1834 type_byte
|= frame
.stream_frame
->fin
? kQuicStreamFinMask
: 0;
1837 type_byte
<<= kQuicStreamDataLengthShift
;
1838 type_byte
|= no_stream_frame_length
? 0: kQuicStreamDataLengthMask
;
1841 type_byte
<<= kQuicStreamOffsetShift
;
1842 const size_t offset_len
= GetStreamOffsetSize(frame
.stream_frame
->offset
);
1843 if (offset_len
> 0) {
1844 type_byte
|= offset_len
- 1;
1847 // stream id 2 bits.
1848 type_byte
<<= kQuicStreamIdShift
;
1849 type_byte
|= GetStreamIdSize(frame
.stream_frame
->stream_id
) - 1;
1850 type_byte
|= kQuicFrameTypeStreamMask
; // Set Stream Frame Type to 1.
1856 type_byte
= static_cast<uint8
>(frame
.type
);
1860 return writer
->WriteUInt8(type_byte
);
1864 bool QuicFramer::AppendPacketSequenceNumber(
1865 QuicSequenceNumberLength sequence_number_length
,
1866 QuicPacketSequenceNumber packet_sequence_number
,
1867 QuicDataWriter
* writer
) {
1868 // Ensure the entire sequence number can be written.
1869 if (writer
->capacity() - writer
->length() <
1870 static_cast<size_t>(sequence_number_length
)) {
1873 switch (sequence_number_length
) {
1874 case PACKET_1BYTE_SEQUENCE_NUMBER
:
1875 return writer
->WriteUInt8(
1876 packet_sequence_number
& k1ByteSequenceNumberMask
);
1878 case PACKET_2BYTE_SEQUENCE_NUMBER
:
1879 return writer
->WriteUInt16(
1880 packet_sequence_number
& k2ByteSequenceNumberMask
);
1882 case PACKET_4BYTE_SEQUENCE_NUMBER
:
1883 return writer
->WriteUInt32(
1884 packet_sequence_number
& k4ByteSequenceNumberMask
);
1886 case PACKET_6BYTE_SEQUENCE_NUMBER
:
1887 return writer
->WriteUInt48(
1888 packet_sequence_number
& k6ByteSequenceNumberMask
);
1891 DCHECK(false) << "sequence_number_length: " << sequence_number_length
;
1896 bool QuicFramer::AppendStreamFrame(
1897 const QuicStreamFrame
& frame
,
1898 bool no_stream_frame_length
,
1899 QuicDataWriter
* writer
) {
1900 if (!writer
->WriteBytes(&frame
.stream_id
, GetStreamIdSize(frame
.stream_id
))) {
1901 LOG(DFATAL
) << "Writing stream id size failed.";
1904 if (!writer
->WriteBytes(&frame
.offset
, GetStreamOffsetSize(frame
.offset
))) {
1905 LOG(DFATAL
) << "Writing offset size failed.";
1908 if (!no_stream_frame_length
) {
1909 if ((frame
.data
.TotalBufferSize() > numeric_limits
<uint16
>::max()) ||
1910 !writer
->WriteUInt16(
1911 static_cast<uint16
>(frame
.data
.TotalBufferSize()))) {
1912 LOG(DFATAL
) << "Writing stream frame length failed";
1917 if (!writer
->WriteIOVector(frame
.data
)) {
1918 LOG(DFATAL
) << "Writing frame data failed.";
1924 void QuicFramer::set_version(const QuicVersion version
) {
1925 DCHECK(IsSupportedVersion(version
)) << QuicVersionToString(version
);
1926 quic_version_
= version
;
1929 bool QuicFramer::AppendAckFrameAndTypeByte(
1930 const QuicPacketHeader
& header
,
1931 const QuicAckFrame
& frame
,
1932 QuicDataWriter
* writer
) {
1933 AckFrameInfo ack_info
= GetAckFrameInfo(frame
);
1934 QuicPacketSequenceNumber ack_largest_observed
= frame
.largest_observed
;
1935 QuicSequenceNumberLength largest_observed_length
=
1936 GetMinSequenceNumberLength(ack_largest_observed
);
1937 QuicSequenceNumberLength missing_sequence_number_length
=
1938 GetMinSequenceNumberLength(ack_info
.max_delta
);
1939 // Determine whether we need to truncate ranges.
1940 size_t available_range_bytes
= writer
->capacity() - writer
->length() -
1941 kNumberOfRevivedPacketsSize
- kNumberOfNackRangesSize
-
1942 GetMinAckFrameSize(header
.public_header
.sequence_number_length
,
1943 largest_observed_length
);
1944 size_t max_num_ranges
= available_range_bytes
/
1945 (missing_sequence_number_length
+ PACKET_1BYTE_SEQUENCE_NUMBER
);
1946 max_num_ranges
= min(kMaxNackRanges
, max_num_ranges
);
1947 bool truncated
= ack_info
.nack_ranges
.size() > max_num_ranges
;
1948 DVLOG_IF(1, truncated
) << "Truncating ack from "
1949 << ack_info
.nack_ranges
.size() << " ranges to "
1951 // Write out the type byte by setting the low order bits and doing shifts
1952 // to make room for the next bit flags to be set.
1953 // Whether there are any nacks.
1954 uint8 type_byte
= ack_info
.nack_ranges
.empty() ? 0 : kQuicHasNacksMask
;
1957 type_byte
<<= kQuicAckTruncatedShift
;
1958 type_byte
|= truncated
? kQuicAckTruncatedMask
: 0;
1960 // Largest observed sequence number length.
1961 type_byte
<<= kQuicSequenceNumberLengthShift
;
1962 type_byte
|= GetSequenceNumberFlags(largest_observed_length
);
1964 // Missing sequence number length.
1965 type_byte
<<= kQuicSequenceNumberLengthShift
;
1966 type_byte
|= GetSequenceNumberFlags(missing_sequence_number_length
);
1968 type_byte
|= kQuicFrameTypeAckMask
;
1970 if (!writer
->WriteUInt8(type_byte
)) {
1974 QuicPacketEntropyHash ack_entropy_hash
= frame
.entropy_hash
;
1975 NackRangeMap::reverse_iterator ack_iter
= ack_info
.nack_ranges
.rbegin();
1977 // Skip the nack ranges which the truncated ack won't include and set
1978 // a correct largest observed for the truncated ack.
1979 for (size_t i
= 1; i
< (ack_info
.nack_ranges
.size() - max_num_ranges
);
1983 // If the last range is followed by acks, include them.
1984 // If the last range is followed by another range, specify the end of the
1985 // range as the largest_observed.
1986 ack_largest_observed
= ack_iter
->first
- 1;
1987 // Also update the entropy so it matches the largest observed.
1988 ack_entropy_hash
= entropy_calculator_
->EntropyHash(ack_largest_observed
);
1992 if (!writer
->WriteUInt8(ack_entropy_hash
)) {
1996 if (!AppendPacketSequenceNumber(largest_observed_length
,
1997 ack_largest_observed
, writer
)) {
2001 uint64 delta_time_largest_observed_us
= kUFloat16MaxValue
;
2002 if (!frame
.delta_time_largest_observed
.IsInfinite()) {
2003 DCHECK_LE(0u, frame
.delta_time_largest_observed
.ToMicroseconds());
2004 delta_time_largest_observed_us
=
2005 frame
.delta_time_largest_observed
.ToMicroseconds();
2008 if (!writer
->WriteUFloat16(delta_time_largest_observed_us
)) {
2012 // Timestamp goes at the end of the required fields.
2014 if (!AppendTimestampToAckFrame(frame
, writer
)) {
2019 if (ack_info
.nack_ranges
.empty()) {
2023 const uint8 num_missing_ranges
=
2024 static_cast<uint8
>(min(ack_info
.nack_ranges
.size(), max_num_ranges
));
2025 if (!writer
->WriteBytes(&num_missing_ranges
, 1)) {
2029 int num_ranges_written
= 0;
2030 QuicPacketSequenceNumber last_sequence_written
= ack_largest_observed
;
2031 for (; ack_iter
!= ack_info
.nack_ranges
.rend(); ++ack_iter
) {
2032 // Calculate the delta to the last number in the range.
2033 QuicPacketSequenceNumber missing_delta
=
2034 last_sequence_written
- (ack_iter
->first
+ ack_iter
->second
);
2035 if (!AppendPacketSequenceNumber(missing_sequence_number_length
,
2036 missing_delta
, writer
)) {
2039 if (!AppendPacketSequenceNumber(PACKET_1BYTE_SEQUENCE_NUMBER
,
2040 ack_iter
->second
, writer
)) {
2043 // Subtract 1 so a missing_delta of 0 means an adjacent range.
2044 last_sequence_written
= ack_iter
->first
- 1;
2045 ++num_ranges_written
;
2047 DCHECK_EQ(num_missing_ranges
, num_ranges_written
);
2049 // Append revived packets.
2050 // If not all the revived packets fit, only mention the ones that do.
2051 uint8 num_revived_packets
=
2052 static_cast<uint8
>(min(frame
.revived_packets
.size(), kMaxRevivedPackets
));
2053 num_revived_packets
= static_cast<uint8
>(min(
2054 static_cast<size_t>(num_revived_packets
),
2055 (writer
->capacity() - writer
->length()) / largest_observed_length
));
2056 if (!writer
->WriteBytes(&num_revived_packets
, 1)) {
2060 SequenceNumberSet::const_iterator iter
= frame
.revived_packets
.begin();
2061 for (int i
= 0; i
< num_revived_packets
; ++i
, ++iter
) {
2062 LOG_IF(DFATAL
, !ContainsKey(frame
.missing_packets
, *iter
));
2063 if (!AppendPacketSequenceNumber(largest_observed_length
,
2072 bool QuicFramer::AppendTimestampToAckFrame(const QuicAckFrame
& frame
,
2073 QuicDataWriter
* writer
) {
2074 DCHECK_GE(numeric_limits
<uint8
>::max(), frame
.received_packet_times
.size());
2075 // num_received_packets is only 1 byte.
2076 if (frame
.received_packet_times
.size() > numeric_limits
<uint8
>::max()) {
2080 uint8 num_received_packets
= frame
.received_packet_times
.size();
2082 if (!writer
->WriteBytes(&num_received_packets
, 1)) {
2085 if (num_received_packets
== 0) {
2089 PacketTimeList::const_iterator it
= frame
.received_packet_times
.begin();
2090 QuicPacketSequenceNumber sequence_number
= it
->first
;
2091 QuicPacketSequenceNumber delta_from_largest_observed
=
2092 frame
.largest_observed
- sequence_number
;
2094 DCHECK_GE(numeric_limits
<uint8
>::max(), delta_from_largest_observed
);
2095 if (delta_from_largest_observed
> numeric_limits
<uint8
>::max()) {
2099 if (!writer
->WriteUInt8(
2100 delta_from_largest_observed
& k1ByteSequenceNumberMask
)) {
2104 // Use the lowest 4 bytes of the time delta from the creation_time_.
2105 const uint64 time_epoch_delta_us
= UINT64_C(1) << 32;
2106 uint32 time_delta_us
=
2107 static_cast<uint32
>(it
->second
.Subtract(creation_time_
).ToMicroseconds()
2108 & (time_epoch_delta_us
- 1));
2109 if (!writer
->WriteBytes(&time_delta_us
, sizeof(time_delta_us
))) {
2113 QuicTime prev_time
= it
->second
;
2115 for (++it
; it
!= frame
.received_packet_times
.end(); ++it
) {
2116 sequence_number
= it
->first
;
2117 delta_from_largest_observed
= frame
.largest_observed
- sequence_number
;
2119 if (delta_from_largest_observed
> numeric_limits
<uint8
>::max()) {
2123 if (!writer
->WriteUInt8(
2124 delta_from_largest_observed
& k1ByteSequenceNumberMask
)) {
2128 uint64 frame_time_delta_us
=
2129 it
->second
.Subtract(prev_time
).ToMicroseconds();
2130 prev_time
= it
->second
;
2131 if (!writer
->WriteUFloat16(frame_time_delta_us
)) {
2138 bool QuicFramer::AppendStopWaitingFrame(
2139 const QuicPacketHeader
& header
,
2140 const QuicStopWaitingFrame
& frame
,
2141 QuicDataWriter
* writer
) {
2142 DCHECK_GE(header
.packet_sequence_number
, frame
.least_unacked
);
2143 const QuicPacketSequenceNumber least_unacked_delta
=
2144 header
.packet_sequence_number
- frame
.least_unacked
;
2145 const QuicPacketSequenceNumber length_shift
=
2146 header
.public_header
.sequence_number_length
* 8;
2147 if (!writer
->WriteUInt8(frame
.entropy_hash
)) {
2148 LOG(DFATAL
) << " hash failed";
2152 if (least_unacked_delta
>> length_shift
> 0) {
2153 LOG(DFATAL
) << "sequence_number_length "
2154 << header
.public_header
.sequence_number_length
2155 << " is too small for least_unacked_delta: "
2156 << least_unacked_delta
;
2159 if (!AppendPacketSequenceNumber(header
.public_header
.sequence_number_length
,
2160 least_unacked_delta
, writer
)) {
2161 LOG(DFATAL
) << " seq failed: "
2162 << header
.public_header
.sequence_number_length
;
2169 bool QuicFramer::AppendRstStreamFrame(const QuicRstStreamFrame
& frame
,
2170 QuicDataWriter
* writer
) {
2171 if (!writer
->WriteUInt32(frame
.stream_id
)) {
2175 if (!writer
->WriteUInt64(frame
.byte_offset
)) {
2179 uint32 error_code
= static_cast<uint32
>(frame
.error_code
);
2180 if (!writer
->WriteUInt32(error_code
)) {
2184 if (quic_version_
<= QUIC_VERSION_24
) {
2185 if (!writer
->WriteStringPiece16(frame
.error_details
)) {
2192 bool QuicFramer::AppendConnectionCloseFrame(
2193 const QuicConnectionCloseFrame
& frame
,
2194 QuicDataWriter
* writer
) {
2195 uint32 error_code
= static_cast<uint32
>(frame
.error_code
);
2196 if (!writer
->WriteUInt32(error_code
)) {
2199 if (!writer
->WriteStringPiece16(frame
.error_details
)) {
2205 bool QuicFramer::AppendGoAwayFrame(const QuicGoAwayFrame
& frame
,
2206 QuicDataWriter
* writer
) {
2207 uint32 error_code
= static_cast<uint32
>(frame
.error_code
);
2208 if (!writer
->WriteUInt32(error_code
)) {
2211 uint32 stream_id
= static_cast<uint32
>(frame
.last_good_stream_id
);
2212 if (!writer
->WriteUInt32(stream_id
)) {
2215 if (!writer
->WriteStringPiece16(frame
.reason_phrase
)) {
2221 bool QuicFramer::AppendWindowUpdateFrame(const QuicWindowUpdateFrame
& frame
,
2222 QuicDataWriter
* writer
) {
2223 uint32 stream_id
= static_cast<uint32
>(frame
.stream_id
);
2224 if (!writer
->WriteUInt32(stream_id
)) {
2227 if (!writer
->WriteUInt64(frame
.byte_offset
)) {
2233 bool QuicFramer::AppendBlockedFrame(const QuicBlockedFrame
& frame
,
2234 QuicDataWriter
* writer
) {
2235 uint32 stream_id
= static_cast<uint32
>(frame
.stream_id
);
2236 if (!writer
->WriteUInt32(stream_id
)) {
2242 bool QuicFramer::RaiseError(QuicErrorCode error
) {
2243 DVLOG(1) << "Error: " << QuicUtils::ErrorToString(error
)
2244 << " detail: " << detailed_error_
;
2246 visitor_
->OnError(this);
2247 reader_
.reset(nullptr);