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"
18 #include "net/quic/quic_utils.h"
20 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
66 // Semantics of the flag bits above (the x bits) depends on the frame type.
68 // Masks to determine if the frame type is a special use
69 // and for specific special frame types.
70 const uint8 kQuicFrameTypeSpecialMask
= 0xE0; // 0b 11100000
71 const uint8 kQuicFrameTypeStreamMask
= 0x80;
72 const uint8 kQuicFrameTypeAckMask
= 0x40;
74 // Stream frame relative shifts and masks for interpreting the stream flags.
75 // StreamID may be 1, 2, 3, or 4 bytes.
76 const uint8 kQuicStreamIdShift
= 2;
77 const uint8 kQuicStreamIDLengthMask
= 0x03;
79 // Offset may be 0, 2, 3, 4, 5, 6, 7, 8 bytes.
80 const uint8 kQuicStreamOffsetShift
= 3;
81 const uint8 kQuicStreamOffsetMask
= 0x07;
83 // Data length may be 0 or 2 bytes.
84 const uint8 kQuicStreamDataLengthShift
= 1;
85 const uint8 kQuicStreamDataLengthMask
= 0x01;
87 // Fin bit may be set or not.
88 const uint8 kQuicStreamFinShift
= 1;
89 const uint8 kQuicStreamFinMask
= 0x01;
91 // Sequence number size shift used in AckFrames.
92 const uint8 kQuicSequenceNumberLengthShift
= 2;
94 // Acks may be truncated.
95 const uint8 kQuicAckTruncatedShift
= 1;
96 const uint8 kQuicAckTruncatedMask
= 0x01;
98 // Acks may not have any nacks.
99 const uint8 kQuicHasNacksMask
= 0x01;
101 // Returns the absolute value of the difference between |a| and |b|.
102 QuicPacketSequenceNumber
Delta(QuicPacketSequenceNumber a
,
103 QuicPacketSequenceNumber b
) {
104 // Since these are unsigned numbers, we can't just return abs(a - b)
111 QuicPacketSequenceNumber
ClosestTo(QuicPacketSequenceNumber target
,
112 QuicPacketSequenceNumber a
,
113 QuicPacketSequenceNumber b
) {
114 return (Delta(target
, a
) < Delta(target
, b
)) ? a
: b
;
117 QuicSequenceNumberLength
ReadSequenceNumberLength(uint8 flags
) {
118 switch (flags
& PACKET_FLAGS_6BYTE_SEQUENCE
) {
119 case PACKET_FLAGS_6BYTE_SEQUENCE
:
120 return PACKET_6BYTE_SEQUENCE_NUMBER
;
121 case PACKET_FLAGS_4BYTE_SEQUENCE
:
122 return PACKET_4BYTE_SEQUENCE_NUMBER
;
123 case PACKET_FLAGS_2BYTE_SEQUENCE
:
124 return PACKET_2BYTE_SEQUENCE_NUMBER
;
125 case PACKET_FLAGS_1BYTE_SEQUENCE
:
126 return PACKET_1BYTE_SEQUENCE_NUMBER
;
128 LOG(DFATAL
) << "Unreachable case statement.";
129 return PACKET_6BYTE_SEQUENCE_NUMBER
;
135 bool QuicFramerVisitorInterface::OnWindowUpdateFrame(
136 const QuicWindowUpdateFrame
& frame
) {
140 bool QuicFramerVisitorInterface::OnBlockedFrame(const QuicBlockedFrame
& frame
) {
144 QuicFramer::QuicFramer(const QuicVersionVector
& supported_versions
,
145 QuicTime creation_time
,
146 Perspective perspective
)
148 fec_builder_(nullptr),
149 entropy_calculator_(nullptr),
150 error_(QUIC_NO_ERROR
),
151 last_sequence_number_(0),
152 last_serialized_connection_id_(0),
153 supported_versions_(supported_versions
),
154 decrypter_level_(ENCRYPTION_NONE
),
155 alternative_decrypter_level_(ENCRYPTION_NONE
),
156 alternative_decrypter_latch_(false),
157 perspective_(perspective
),
158 validate_flags_(true),
159 creation_time_(creation_time
),
160 last_timestamp_(QuicTime::Delta::Zero()) {
161 DCHECK(!supported_versions
.empty());
162 quic_version_
= supported_versions_
[0];
163 decrypter_
.reset(QuicDecrypter::Create(kNULL
));
164 encrypter_
[ENCRYPTION_NONE
].reset(QuicEncrypter::Create(kNULL
));
167 QuicFramer::~QuicFramer() {}
170 size_t QuicFramer::GetMinStreamFrameSize(QuicStreamId stream_id
,
171 QuicStreamOffset offset
,
172 bool last_frame_in_packet
,
173 InFecGroup is_in_fec_group
) {
174 bool no_stream_frame_length
= last_frame_in_packet
&&
175 is_in_fec_group
== NOT_IN_FEC_GROUP
;
176 return kQuicFrameTypeSize
+ GetStreamIdSize(stream_id
) +
177 GetStreamOffsetSize(offset
) +
178 (no_stream_frame_length
? 0 : kQuicStreamPayloadLengthSize
);
182 size_t QuicFramer::GetMinAckFrameSize(
183 QuicSequenceNumberLength sequence_number_length
,
184 QuicSequenceNumberLength largest_observed_length
) {
185 return kQuicFrameTypeSize
+ kQuicEntropyHashSize
+
186 largest_observed_length
+ kQuicDeltaTimeLargestObservedSize
;
190 size_t QuicFramer::GetStopWaitingFrameSize(
191 QuicSequenceNumberLength sequence_number_length
) {
192 return kQuicFrameTypeSize
+ kQuicEntropyHashSize
+
193 sequence_number_length
;
197 size_t QuicFramer::GetMinRstStreamFrameSize() {
198 return kQuicFrameTypeSize
+ kQuicMaxStreamIdSize
+
199 kQuicMaxStreamOffsetSize
+ kQuicErrorCodeSize
+
200 kQuicErrorDetailsLengthSize
;
204 size_t QuicFramer::GetMinConnectionCloseFrameSize() {
205 return kQuicFrameTypeSize
+ kQuicErrorCodeSize
+ kQuicErrorDetailsLengthSize
;
209 size_t QuicFramer::GetMinGoAwayFrameSize() {
210 return kQuicFrameTypeSize
+ kQuicErrorCodeSize
+ kQuicErrorDetailsLengthSize
+
211 kQuicMaxStreamIdSize
;
215 size_t QuicFramer::GetWindowUpdateFrameSize() {
216 return kQuicFrameTypeSize
+ kQuicMaxStreamIdSize
+ kQuicMaxStreamOffsetSize
;
220 size_t QuicFramer::GetBlockedFrameSize() {
221 return kQuicFrameTypeSize
+ kQuicMaxStreamIdSize
;
225 size_t QuicFramer::GetStreamIdSize(QuicStreamId stream_id
) {
226 // Sizes are 1 through 4 bytes.
227 for (int i
= 1; i
<= 4; ++i
) {
229 if (stream_id
== 0) {
233 LOG(DFATAL
) << "Failed to determine StreamIDSize.";
238 size_t QuicFramer::GetStreamOffsetSize(QuicStreamOffset offset
) {
239 // 0 is a special case.
243 // 2 through 8 are the remaining sizes.
245 for (int i
= 2; i
<= 8; ++i
) {
251 LOG(DFATAL
) << "Failed to determine StreamOffsetSize.";
256 size_t QuicFramer::GetVersionNegotiationPacketSize(size_t number_versions
) {
257 return kPublicFlagsSize
+ PACKET_8BYTE_CONNECTION_ID
+
258 number_versions
* kQuicVersionSize
;
261 bool QuicFramer::IsSupportedVersion(const QuicVersion version
) const {
262 for (size_t i
= 0; i
< supported_versions_
.size(); ++i
) {
263 if (version
== supported_versions_
[i
]) {
270 size_t QuicFramer::GetSerializedFrameLength(
271 const QuicFrame
& frame
,
275 InFecGroup is_in_fec_group
,
276 QuicSequenceNumberLength sequence_number_length
) {
277 if (frame
.type
== PADDING_FRAME
) {
278 // PADDING implies end of packet.
282 ComputeFrameLength(frame
, last_frame
, is_in_fec_group
,
283 sequence_number_length
);
284 if (frame_len
<= free_bytes
) {
285 // Frame fits within packet. Note that acks may be truncated.
288 // Only truncate the first frame in a packet, so if subsequent ones go
289 // over, stop including more frames.
293 bool can_truncate
= frame
.type
== ACK_FRAME
&&
294 free_bytes
>= GetMinAckFrameSize(PACKET_6BYTE_SEQUENCE_NUMBER
,
295 PACKET_6BYTE_SEQUENCE_NUMBER
);
297 // Truncate the frame so the packet will not exceed kMaxPacketSize.
298 // Note that we may not use every byte of the writer in this case.
299 DVLOG(1) << "Truncating large frame, free bytes: " << free_bytes
;
302 if (!FLAGS_quic_allow_oversized_packets_for_test
) {
305 LOG(DFATAL
) << "Packet size too small to fit frame.";
309 QuicFramer::AckFrameInfo::AckFrameInfo() : max_delta(0) {}
311 QuicFramer::AckFrameInfo::~AckFrameInfo() {}
314 QuicPacketEntropyHash
QuicFramer::GetPacketEntropyHash(
315 const QuicPacketHeader
& header
) {
316 return header
.entropy_flag
<< (header
.packet_sequence_number
% 8);
319 QuicPacket
* QuicFramer::BuildDataPacket(const QuicPacketHeader
& header
,
320 const QuicFrames
& frames
,
322 size_t packet_length
) {
323 QuicDataWriter
writer(packet_length
, buffer
);
324 if (!AppendPacketHeader(header
, &writer
)) {
325 LOG(DFATAL
) << "AppendPacketHeader failed";
330 for (const QuicFrame
& frame
: frames
) {
331 // Determine if we should write stream frame length in header.
332 const bool no_stream_frame_length
=
333 (header
.is_in_fec_group
== NOT_IN_FEC_GROUP
) &&
334 (i
== frames
.size() - 1);
335 if (!AppendTypeByte(frame
, no_stream_frame_length
, &writer
)) {
336 LOG(DFATAL
) << "AppendTypeByte failed";
340 switch (frame
.type
) {
342 writer
.WritePadding();
345 if (!AppendStreamFrame(
346 *frame
.stream_frame
, no_stream_frame_length
, &writer
)) {
347 LOG(DFATAL
) << "AppendStreamFrame failed";
352 if (!AppendAckFrameAndTypeByte(
353 header
, *frame
.ack_frame
, &writer
)) {
354 LOG(DFATAL
) << "AppendAckFrameAndTypeByte failed";
358 case STOP_WAITING_FRAME
:
359 if (!AppendStopWaitingFrame(
360 header
, *frame
.stop_waiting_frame
, &writer
)) {
361 LOG(DFATAL
) << "AppendStopWaitingFrame failed";
366 // Ping has no payload.
368 case RST_STREAM_FRAME
:
369 if (!AppendRstStreamFrame(*frame
.rst_stream_frame
, &writer
)) {
370 LOG(DFATAL
) << "AppendRstStreamFrame failed";
374 case CONNECTION_CLOSE_FRAME
:
375 if (!AppendConnectionCloseFrame(
376 *frame
.connection_close_frame
, &writer
)) {
377 LOG(DFATAL
) << "AppendConnectionCloseFrame failed";
382 if (!AppendGoAwayFrame(*frame
.goaway_frame
, &writer
)) {
383 LOG(DFATAL
) << "AppendGoAwayFrame failed";
387 case WINDOW_UPDATE_FRAME
:
388 if (!AppendWindowUpdateFrame(*frame
.window_update_frame
, &writer
)) {
389 LOG(DFATAL
) << "AppendWindowUpdateFrame failed";
394 if (!AppendBlockedFrame(*frame
.blocked_frame
, &writer
)) {
395 LOG(DFATAL
) << "AppendBlockedFrame failed";
400 RaiseError(QUIC_INVALID_FRAME_DATA
);
401 LOG(DFATAL
) << "QUIC_INVALID_FRAME_DATA";
408 new QuicPacket(writer
.data(), writer
.length(), false,
409 header
.public_header
.connection_id_length
,
410 header
.public_header
.version_flag
,
411 header
.public_header
.sequence_number_length
);
414 fec_builder_
->OnBuiltFecProtectedPayload(header
,
415 packet
->FecProtectedData());
421 QuicPacket
* QuicFramer::BuildFecPacket(const QuicPacketHeader
& header
,
422 const QuicFecData
& fec
) {
423 DCHECK_EQ(IN_FEC_GROUP
, header
.is_in_fec_group
);
424 DCHECK_NE(0u, header
.fec_group
);
425 size_t len
= GetPacketHeaderSize(header
);
426 len
+= fec
.redundancy
.length();
428 scoped_ptr
<char[]> buffer(new char[len
]);
429 QuicDataWriter
writer(len
, buffer
.get());
430 if (!AppendPacketHeader(header
, &writer
)) {
431 LOG(DFATAL
) << "AppendPacketHeader failed";
435 if (!writer
.WriteBytes(fec
.redundancy
.data(), fec
.redundancy
.length())) {
436 LOG(DFATAL
) << "Failed to add FEC";
440 return new QuicPacket(buffer
.release(), len
, true,
441 header
.public_header
.connection_id_length
,
442 header
.public_header
.version_flag
,
443 header
.public_header
.sequence_number_length
);
447 QuicEncryptedPacket
* QuicFramer::BuildPublicResetPacket(
448 const QuicPublicResetPacket
& packet
) {
449 DCHECK(packet
.public_header
.reset_flag
);
451 CryptoHandshakeMessage reset
;
452 reset
.set_tag(kPRST
);
453 reset
.SetValue(kRNON
, packet
.nonce_proof
);
454 reset
.SetValue(kRSEQ
, packet
.rejected_sequence_number
);
455 if (!packet
.client_address
.address().empty()) {
456 // packet.client_address is non-empty.
457 QuicSocketAddressCoder
address_coder(packet
.client_address
);
458 string serialized_address
= address_coder
.Encode();
459 if (serialized_address
.empty()) {
462 reset
.SetStringPiece(kCADR
, serialized_address
);
464 const QuicData
& reset_serialized
= reset
.GetSerialized();
467 kPublicFlagsSize
+ PACKET_8BYTE_CONNECTION_ID
+ reset_serialized
.length();
468 scoped_ptr
<char[]> buffer(new char[len
]);
469 QuicDataWriter
writer(len
, buffer
.get());
471 uint8 flags
= static_cast<uint8
>(PACKET_PUBLIC_FLAGS_RST
|
472 PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID
);
473 if (!writer
.WriteUInt8(flags
)) {
477 if (!writer
.WriteUInt64(packet
.public_header
.connection_id
)) {
481 if (!writer
.WriteBytes(reset_serialized
.data(), reset_serialized
.length())) {
485 return new QuicEncryptedPacket(buffer
.release(), len
, true);
488 QuicEncryptedPacket
* QuicFramer::BuildVersionNegotiationPacket(
489 const QuicPacketPublicHeader
& header
,
490 const QuicVersionVector
& supported_versions
) {
491 DCHECK(header
.version_flag
);
492 size_t len
= GetVersionNegotiationPacketSize(supported_versions
.size());
493 scoped_ptr
<char[]> buffer(new char[len
]);
494 QuicDataWriter
writer(len
, buffer
.get());
496 uint8 flags
= static_cast<uint8
>(PACKET_PUBLIC_FLAGS_VERSION
|
497 PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID
);
498 if (!writer
.WriteUInt8(flags
)) {
502 if (!writer
.WriteUInt64(header
.connection_id
)) {
506 for (size_t i
= 0; i
< supported_versions
.size(); ++i
) {
507 if (!writer
.WriteUInt32(QuicVersionToQuicTag(supported_versions
[i
]))) {
512 return new QuicEncryptedPacket(buffer
.release(), len
, true);
515 bool QuicFramer::ProcessPacket(const QuicEncryptedPacket
& packet
) {
516 DCHECK(!reader_
.get());
517 reader_
.reset(new QuicDataReader(packet
.data(), packet
.length()));
519 visitor_
->OnPacket();
521 // First parse the public header.
522 QuicPacketPublicHeader public_header
;
523 if (!ProcessPublicHeader(&public_header
)) {
524 DLOG(WARNING
) << "Unable to process public header.";
525 DCHECK_NE("", detailed_error_
);
526 return RaiseError(QUIC_INVALID_PACKET_HEADER
);
529 if (!visitor_
->OnUnauthenticatedPublicHeader(public_header
)) {
530 // The visitor suppresses further processing of the packet.
531 reader_
.reset(nullptr);
535 if (perspective_
== Perspective::IS_SERVER
&& public_header
.version_flag
&&
536 public_header
.versions
[0] != quic_version_
) {
537 if (!visitor_
->OnProtocolVersionMismatch(public_header
.versions
[0])) {
538 reader_
.reset(nullptr);
544 if (perspective_
== Perspective::IS_CLIENT
&& public_header
.version_flag
) {
545 rv
= ProcessVersionNegotiationPacket(&public_header
);
546 } else if (public_header
.reset_flag
) {
547 rv
= ProcessPublicResetPacket(public_header
);
548 } else if (packet
.length() <= kMaxPacketSize
) {
549 char buffer
[kMaxPacketSize
];
550 rv
= ProcessDataPacket(public_header
, packet
, buffer
, kMaxPacketSize
);
552 scoped_ptr
<char[]> large_buffer(new char[packet
.length()]);
553 rv
= ProcessDataPacket(public_header
, packet
, large_buffer
.get(),
555 LOG_IF(DFATAL
, rv
) << "QUIC should never successfully process packets "
556 << "larger than kMaxPacketSize. packet size:"
560 reader_
.reset(nullptr);
564 bool QuicFramer::ProcessVersionNegotiationPacket(
565 QuicPacketPublicHeader
* public_header
) {
566 DCHECK_EQ(Perspective::IS_CLIENT
, perspective_
);
567 // Try reading at least once to raise error if the packet is invalid.
570 if (!reader_
->ReadBytes(&version
, kQuicVersionSize
)) {
571 set_detailed_error("Unable to read supported version in negotiation.");
572 return RaiseError(QUIC_INVALID_VERSION_NEGOTIATION_PACKET
);
574 public_header
->versions
.push_back(QuicTagToQuicVersion(version
));
575 } while (!reader_
->IsDoneReading());
577 visitor_
->OnVersionNegotiationPacket(*public_header
);
581 bool QuicFramer::ProcessDataPacket(const QuicPacketPublicHeader
& public_header
,
582 const QuicEncryptedPacket
& packet
,
583 char* decrypted_buffer
,
584 size_t buffer_length
) {
585 QuicPacketHeader
header(public_header
);
586 if (!ProcessPacketHeader(&header
, packet
, decrypted_buffer
, buffer_length
)) {
587 DLOG(WARNING
) << "Unable to process data packet header.";
591 if (!visitor_
->OnPacketHeader(header
)) {
592 // The visitor suppresses further processing of the packet.
596 if (packet
.length() > kMaxPacketSize
) {
597 DLOG(WARNING
) << "Packet too large: " << packet
.length();
598 return RaiseError(QUIC_PACKET_TOO_LARGE
);
601 // Handle the payload.
602 if (!header
.fec_flag
) {
603 if (header
.is_in_fec_group
== IN_FEC_GROUP
) {
604 StringPiece payload
= reader_
->PeekRemainingPayload();
605 visitor_
->OnFecProtectedPayload(payload
);
607 if (!ProcessFrameData(header
)) {
608 DCHECK_NE(QUIC_NO_ERROR
, error_
); // ProcessFrameData sets the error.
609 DLOG(WARNING
) << "Unable to process frame data.";
613 QuicFecData fec_data
;
614 fec_data
.fec_group
= header
.fec_group
;
615 fec_data
.redundancy
= reader_
->ReadRemainingPayload();
616 visitor_
->OnFecData(fec_data
);
619 visitor_
->OnPacketComplete();
623 bool QuicFramer::ProcessPublicResetPacket(
624 const QuicPacketPublicHeader
& public_header
) {
625 QuicPublicResetPacket
packet(public_header
);
627 scoped_ptr
<CryptoHandshakeMessage
> reset(
628 CryptoFramer::ParseMessage(reader_
->ReadRemainingPayload()));
630 set_detailed_error("Unable to read reset message.");
631 return RaiseError(QUIC_INVALID_PUBLIC_RST_PACKET
);
633 if (reset
->tag() != kPRST
) {
634 set_detailed_error("Incorrect message tag.");
635 return RaiseError(QUIC_INVALID_PUBLIC_RST_PACKET
);
638 if (reset
->GetUint64(kRNON
, &packet
.nonce_proof
) != QUIC_NO_ERROR
) {
639 set_detailed_error("Unable to read nonce proof.");
640 return RaiseError(QUIC_INVALID_PUBLIC_RST_PACKET
);
642 // TODO(satyamshekhar): validate nonce to protect against DoS.
644 if (reset
->GetUint64(kRSEQ
, &packet
.rejected_sequence_number
) !=
646 set_detailed_error("Unable to read rejected sequence number.");
647 return RaiseError(QUIC_INVALID_PUBLIC_RST_PACKET
);
651 if (reset
->GetStringPiece(kCADR
, &address
)) {
652 QuicSocketAddressCoder address_coder
;
653 if (address_coder
.Decode(address
.data(), address
.length())) {
654 packet
.client_address
= IPEndPoint(address_coder
.ip(),
655 address_coder
.port());
659 visitor_
->OnPublicResetPacket(packet
);
663 bool QuicFramer::ProcessRevivedPacket(QuicPacketHeader
* header
,
664 StringPiece payload
) {
665 DCHECK(!reader_
.get());
667 visitor_
->OnRevivedPacket();
669 header
->entropy_hash
= GetPacketEntropyHash(*header
);
671 if (!visitor_
->OnPacketHeader(*header
)) {
675 if (payload
.length() > kMaxPacketSize
) {
676 set_detailed_error("Revived packet too large.");
677 return RaiseError(QUIC_PACKET_TOO_LARGE
);
680 reader_
.reset(new QuicDataReader(payload
.data(), payload
.length()));
681 if (!ProcessFrameData(*header
)) {
682 DCHECK_NE(QUIC_NO_ERROR
, error_
); // ProcessFrameData sets the error.
683 DLOG(WARNING
) << "Unable to process frame data.";
687 visitor_
->OnPacketComplete();
688 reader_
.reset(nullptr);
692 bool QuicFramer::AppendPacketHeader(const QuicPacketHeader
& header
,
693 QuicDataWriter
* writer
) {
694 DVLOG(1) << "Appending header: " << header
;
695 DCHECK(header
.fec_group
> 0 || header
.is_in_fec_group
== NOT_IN_FEC_GROUP
);
696 uint8 public_flags
= 0;
697 if (header
.public_header
.reset_flag
) {
698 public_flags
|= PACKET_PUBLIC_FLAGS_RST
;
700 if (header
.public_header
.version_flag
) {
701 public_flags
|= PACKET_PUBLIC_FLAGS_VERSION
;
705 GetSequenceNumberFlags(header
.public_header
.sequence_number_length
)
706 << kPublicHeaderSequenceNumberShift
;
708 switch (header
.public_header
.connection_id_length
) {
709 case PACKET_0BYTE_CONNECTION_ID
:
710 if (!writer
->WriteUInt8(
711 public_flags
| PACKET_PUBLIC_FLAGS_0BYTE_CONNECTION_ID
)) {
715 case PACKET_1BYTE_CONNECTION_ID
:
716 if (!writer
->WriteUInt8(
717 public_flags
| PACKET_PUBLIC_FLAGS_1BYTE_CONNECTION_ID
)) {
720 if (!writer
->WriteUInt8(
721 header
.public_header
.connection_id
& k1ByteConnectionIdMask
)) {
725 case PACKET_4BYTE_CONNECTION_ID
:
726 if (!writer
->WriteUInt8(
727 public_flags
| PACKET_PUBLIC_FLAGS_4BYTE_CONNECTION_ID
)) {
730 if (!writer
->WriteUInt32(
731 header
.public_header
.connection_id
& k4ByteConnectionIdMask
)) {
735 case PACKET_8BYTE_CONNECTION_ID
:
736 if (!writer
->WriteUInt8(
737 public_flags
| PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID
)) {
740 if (!writer
->WriteUInt64(header
.public_header
.connection_id
)) {
745 last_serialized_connection_id_
= header
.public_header
.connection_id
;
747 if (header
.public_header
.version_flag
) {
748 DCHECK_EQ(Perspective::IS_CLIENT
, perspective_
);
749 QuicTag tag
= QuicVersionToQuicTag(quic_version_
);
750 writer
->WriteUInt32(tag
);
751 DVLOG(1) << "version = " << quic_version_
752 << ", tag = '" << QuicUtils::TagToString(tag
) << "'";
755 if (!AppendPacketSequenceNumber(header
.public_header
.sequence_number_length
,
756 header
.packet_sequence_number
, writer
)) {
760 uint8 private_flags
= 0;
761 if (header
.entropy_flag
) {
762 private_flags
|= PACKET_PRIVATE_FLAGS_ENTROPY
;
764 if (header
.is_in_fec_group
== IN_FEC_GROUP
) {
765 private_flags
|= PACKET_PRIVATE_FLAGS_FEC_GROUP
;
767 if (header
.fec_flag
) {
768 private_flags
|= PACKET_PRIVATE_FLAGS_FEC
;
770 if (!writer
->WriteUInt8(private_flags
)) {
774 // The FEC group number is the sequence number of the first fec
775 // protected packet, or 0 if this packet is not protected.
776 if (header
.is_in_fec_group
== IN_FEC_GROUP
) {
777 DCHECK_LE(header
.fec_group
, header
.packet_sequence_number
);
778 DCHECK_LT(header
.packet_sequence_number
- header
.fec_group
, 255u);
779 // Offset from the current packet sequence number to the first fec
781 uint8 first_fec_protected_packet_offset
=
782 static_cast<uint8
>(header
.packet_sequence_number
- header
.fec_group
);
783 if (!writer
->WriteBytes(&first_fec_protected_packet_offset
, 1)) {
791 const QuicTime::Delta
QuicFramer::CalculateTimestampFromWire(
792 uint32 time_delta_us
) {
793 // The new time_delta might have wrapped to the next epoch, or it
794 // might have reverse wrapped to the previous epoch, or it might
795 // remain in the same epoch. Select the time closest to the previous
798 // epoch_delta is the delta between epochs. A delta is 4 bytes of
800 const uint64 epoch_delta
= GG_UINT64_C(1) << 32;
801 uint64 epoch
= last_timestamp_
.ToMicroseconds() & ~(epoch_delta
- 1);
802 // Wrapping is safe here because a wrapped value will not be ClosestTo below.
803 uint64 prev_epoch
= epoch
- epoch_delta
;
804 uint64 next_epoch
= epoch
+ epoch_delta
;
806 uint64 time
= ClosestTo(last_timestamp_
.ToMicroseconds(),
807 epoch
+ time_delta_us
,
808 ClosestTo(last_timestamp_
.ToMicroseconds(),
809 prev_epoch
+ time_delta_us
,
810 next_epoch
+ time_delta_us
));
812 return QuicTime::Delta::FromMicroseconds(time
);
815 QuicPacketSequenceNumber
QuicFramer::CalculatePacketSequenceNumberFromWire(
816 QuicSequenceNumberLength sequence_number_length
,
817 QuicPacketSequenceNumber packet_sequence_number
) const {
818 // The new sequence number might have wrapped to the next epoch, or
819 // it might have reverse wrapped to the previous epoch, or it might
820 // remain in the same epoch. Select the sequence number closest to the
821 // next expected sequence number, the previous sequence number plus 1.
823 // epoch_delta is the delta between epochs the sequence number was serialized
824 // with, so the correct value is likely the same epoch as the last sequence
825 // number or an adjacent epoch.
826 const QuicPacketSequenceNumber epoch_delta
=
827 GG_UINT64_C(1) << (8 * sequence_number_length
);
828 QuicPacketSequenceNumber next_sequence_number
= last_sequence_number_
+ 1;
829 QuicPacketSequenceNumber epoch
= last_sequence_number_
& ~(epoch_delta
- 1);
830 QuicPacketSequenceNumber prev_epoch
= epoch
- epoch_delta
;
831 QuicPacketSequenceNumber next_epoch
= epoch
+ epoch_delta
;
833 return ClosestTo(next_sequence_number
,
834 epoch
+ packet_sequence_number
,
835 ClosestTo(next_sequence_number
,
836 prev_epoch
+ packet_sequence_number
,
837 next_epoch
+ packet_sequence_number
));
840 bool QuicFramer::ProcessPublicHeader(
841 QuicPacketPublicHeader
* public_header
) {
843 if (!reader_
->ReadBytes(&public_flags
, 1)) {
844 set_detailed_error("Unable to read public flags.");
848 public_header
->reset_flag
= (public_flags
& PACKET_PUBLIC_FLAGS_RST
) != 0;
849 public_header
->version_flag
=
850 (public_flags
& PACKET_PUBLIC_FLAGS_VERSION
) != 0;
852 if (validate_flags_
&&
853 !public_header
->version_flag
&& public_flags
> PACKET_PUBLIC_FLAGS_MAX
) {
854 set_detailed_error("Illegal public flags value.");
858 if (public_header
->reset_flag
&& public_header
->version_flag
) {
859 set_detailed_error("Got version flag in reset packet");
863 switch (public_flags
& PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID
) {
864 case PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID
:
865 if (!reader_
->ReadUInt64(&public_header
->connection_id
)) {
866 set_detailed_error("Unable to read ConnectionId.");
869 public_header
->connection_id_length
= PACKET_8BYTE_CONNECTION_ID
;
871 case PACKET_PUBLIC_FLAGS_4BYTE_CONNECTION_ID
:
872 // If the connection_id is truncated, expect to read the last serialized
874 if (!reader_
->ReadBytes(&public_header
->connection_id
,
875 PACKET_4BYTE_CONNECTION_ID
)) {
876 set_detailed_error("Unable to read ConnectionId.");
879 if (last_serialized_connection_id_
&&
880 (public_header
->connection_id
& k4ByteConnectionIdMask
) !=
881 (last_serialized_connection_id_
& k4ByteConnectionIdMask
)) {
882 set_detailed_error("Truncated 4 byte ConnectionId does not match "
883 "previous connection_id.");
886 public_header
->connection_id_length
= PACKET_4BYTE_CONNECTION_ID
;
887 public_header
->connection_id
= last_serialized_connection_id_
;
889 case PACKET_PUBLIC_FLAGS_1BYTE_CONNECTION_ID
:
890 if (!reader_
->ReadBytes(&public_header
->connection_id
,
891 PACKET_1BYTE_CONNECTION_ID
)) {
892 set_detailed_error("Unable to read ConnectionId.");
895 if (last_serialized_connection_id_
&&
896 (public_header
->connection_id
& k1ByteConnectionIdMask
) !=
897 (last_serialized_connection_id_
& k1ByteConnectionIdMask
)) {
898 set_detailed_error("Truncated 1 byte ConnectionId does not match "
899 "previous connection_id.");
902 public_header
->connection_id_length
= PACKET_1BYTE_CONNECTION_ID
;
903 public_header
->connection_id
= last_serialized_connection_id_
;
905 case PACKET_PUBLIC_FLAGS_0BYTE_CONNECTION_ID
:
906 public_header
->connection_id_length
= PACKET_0BYTE_CONNECTION_ID
;
907 public_header
->connection_id
= last_serialized_connection_id_
;
911 public_header
->sequence_number_length
=
912 ReadSequenceNumberLength(
913 public_flags
>> kPublicHeaderSequenceNumberShift
);
915 // Read the version only if the packet is from the client.
916 // version flag from the server means version negotiation packet.
917 if (public_header
->version_flag
&& perspective_
== Perspective::IS_SERVER
) {
919 if (!reader_
->ReadUInt32(&version_tag
)) {
920 set_detailed_error("Unable to read protocol version.");
924 // If the version from the new packet is the same as the version of this
925 // framer, then the public flags should be set to something we understand.
926 // If not, this raises an error.
927 QuicVersion version
= QuicTagToQuicVersion(version_tag
);
928 if (version
== quic_version_
&& public_flags
> PACKET_PUBLIC_FLAGS_MAX
) {
929 set_detailed_error("Illegal public flags value.");
932 public_header
->versions
.push_back(version
);
938 QuicSequenceNumberLength
QuicFramer::GetMinSequenceNumberLength(
939 QuicPacketSequenceNumber sequence_number
) {
940 if (sequence_number
< 1 << (PACKET_1BYTE_SEQUENCE_NUMBER
* 8)) {
941 return PACKET_1BYTE_SEQUENCE_NUMBER
;
942 } else if (sequence_number
< 1 << (PACKET_2BYTE_SEQUENCE_NUMBER
* 8)) {
943 return PACKET_2BYTE_SEQUENCE_NUMBER
;
944 } else if (sequence_number
<
945 GG_UINT64_C(1) << (PACKET_4BYTE_SEQUENCE_NUMBER
* 8)) {
946 return PACKET_4BYTE_SEQUENCE_NUMBER
;
948 return PACKET_6BYTE_SEQUENCE_NUMBER
;
953 uint8
QuicFramer::GetSequenceNumberFlags(
954 QuicSequenceNumberLength sequence_number_length
) {
955 switch (sequence_number_length
) {
956 case PACKET_1BYTE_SEQUENCE_NUMBER
:
957 return PACKET_FLAGS_1BYTE_SEQUENCE
;
958 case PACKET_2BYTE_SEQUENCE_NUMBER
:
959 return PACKET_FLAGS_2BYTE_SEQUENCE
;
960 case PACKET_4BYTE_SEQUENCE_NUMBER
:
961 return PACKET_FLAGS_4BYTE_SEQUENCE
;
962 case PACKET_6BYTE_SEQUENCE_NUMBER
:
963 return PACKET_FLAGS_6BYTE_SEQUENCE
;
965 LOG(DFATAL
) << "Unreachable case statement.";
966 return PACKET_FLAGS_6BYTE_SEQUENCE
;
971 QuicFramer::AckFrameInfo
QuicFramer::GetAckFrameInfo(
972 const QuicAckFrame
& frame
) {
973 AckFrameInfo ack_info
;
974 if (frame
.missing_packets
.empty()) {
977 DCHECK_GE(frame
.largest_observed
, *frame
.missing_packets
.rbegin());
978 size_t cur_range_length
= 0;
979 SequenceNumberSet::const_iterator iter
= frame
.missing_packets
.begin();
980 QuicPacketSequenceNumber last_missing
= *iter
;
982 for (; iter
!= frame
.missing_packets
.end(); ++iter
) {
983 if (cur_range_length
< numeric_limits
<uint8
>::max() &&
984 *iter
== (last_missing
+ 1)) {
987 ack_info
.nack_ranges
[last_missing
- cur_range_length
] =
988 static_cast<uint8
>(cur_range_length
);
989 cur_range_length
= 0;
991 ack_info
.max_delta
= max(ack_info
.max_delta
, *iter
- last_missing
);
992 last_missing
= *iter
;
994 // Include the last nack range.
995 ack_info
.nack_ranges
[last_missing
- cur_range_length
] =
996 static_cast<uint8
>(cur_range_length
);
997 // Include the range to the largest observed.
999 max(ack_info
.max_delta
, frame
.largest_observed
- last_missing
);
1003 bool QuicFramer::ProcessPacketHeader(QuicPacketHeader
* header
,
1004 const QuicEncryptedPacket
& packet
,
1005 char* decrypted_buffer
,
1006 size_t buffer_length
) {
1007 if (!ProcessPacketSequenceNumber(header
->public_header
.sequence_number_length
,
1008 &header
->packet_sequence_number
)) {
1009 set_detailed_error("Unable to read sequence number.");
1010 return RaiseError(QUIC_INVALID_PACKET_HEADER
);
1013 if (header
->packet_sequence_number
== 0u) {
1014 set_detailed_error("Packet sequence numbers cannot be 0.");
1015 return RaiseError(QUIC_INVALID_PACKET_HEADER
);
1018 if (!visitor_
->OnUnauthenticatedHeader(*header
)) {
1022 if (!DecryptPayload(*header
, packet
, decrypted_buffer
, buffer_length
)) {
1023 set_detailed_error("Unable to decrypt payload.");
1024 return RaiseError(QUIC_DECRYPTION_FAILURE
);
1027 uint8 private_flags
;
1028 if (!reader_
->ReadBytes(&private_flags
, 1)) {
1029 set_detailed_error("Unable to read private flags.");
1030 return RaiseError(QUIC_INVALID_PACKET_HEADER
);
1033 if (private_flags
> PACKET_PRIVATE_FLAGS_MAX
) {
1034 set_detailed_error("Illegal private flags value.");
1035 return RaiseError(QUIC_INVALID_PACKET_HEADER
);
1038 header
->entropy_flag
= (private_flags
& PACKET_PRIVATE_FLAGS_ENTROPY
) != 0;
1039 header
->fec_flag
= (private_flags
& PACKET_PRIVATE_FLAGS_FEC
) != 0;
1041 if ((private_flags
& PACKET_PRIVATE_FLAGS_FEC_GROUP
) != 0) {
1042 header
->is_in_fec_group
= IN_FEC_GROUP
;
1043 uint8 first_fec_protected_packet_offset
;
1044 if (!reader_
->ReadBytes(&first_fec_protected_packet_offset
, 1)) {
1045 set_detailed_error("Unable to read first fec protected packet offset.");
1046 return RaiseError(QUIC_INVALID_PACKET_HEADER
);
1048 if (first_fec_protected_packet_offset
>= header
->packet_sequence_number
) {
1049 set_detailed_error("First fec protected packet offset must be less "
1050 "than the sequence number.");
1051 return RaiseError(QUIC_INVALID_PACKET_HEADER
);
1054 header
->packet_sequence_number
- first_fec_protected_packet_offset
;
1057 header
->entropy_hash
= GetPacketEntropyHash(*header
);
1058 // Set the last sequence number after we have decrypted the packet
1059 // so we are confident is not attacker controlled.
1060 last_sequence_number_
= header
->packet_sequence_number
;
1064 bool QuicFramer::ProcessPacketSequenceNumber(
1065 QuicSequenceNumberLength sequence_number_length
,
1066 QuicPacketSequenceNumber
* sequence_number
) {
1067 QuicPacketSequenceNumber wire_sequence_number
= 0u;
1068 if (!reader_
->ReadBytes(&wire_sequence_number
, sequence_number_length
)) {
1072 // TODO(ianswett): Explore the usefulness of trying multiple sequence numbers
1073 // in case the first guess is incorrect.
1075 CalculatePacketSequenceNumberFromWire(sequence_number_length
,
1076 wire_sequence_number
);
1080 bool QuicFramer::ProcessFrameData(const QuicPacketHeader
& header
) {
1081 if (reader_
->IsDoneReading()) {
1082 set_detailed_error("Packet has no frames.");
1083 return RaiseError(QUIC_MISSING_PAYLOAD
);
1085 while (!reader_
->IsDoneReading()) {
1087 if (!reader_
->ReadBytes(&frame_type
, 1)) {
1088 set_detailed_error("Unable to read frame type.");
1089 return RaiseError(QUIC_INVALID_FRAME_DATA
);
1092 if (frame_type
& kQuicFrameTypeSpecialMask
) {
1094 if (frame_type
& kQuicFrameTypeStreamMask
) {
1095 QuicStreamFrame frame
;
1096 if (!ProcessStreamFrame(frame_type
, &frame
)) {
1097 return RaiseError(QUIC_INVALID_STREAM_DATA
);
1099 if (!visitor_
->OnStreamFrame(frame
)) {
1100 DVLOG(1) << "Visitor asked to stop further processing.";
1101 // Returning true since there was no parsing error.
1108 if (frame_type
& kQuicFrameTypeAckMask
) {
1110 if (!ProcessAckFrame(frame_type
, &frame
)) {
1111 return RaiseError(QUIC_INVALID_ACK_DATA
);
1113 if (!visitor_
->OnAckFrame(frame
)) {
1114 DVLOG(1) << "Visitor asked to stop further processing.";
1115 // Returning true since there was no parsing error.
1121 // This was a special frame type that did not match any
1122 // of the known ones. Error.
1123 set_detailed_error("Illegal frame type.");
1124 DLOG(WARNING
) << "Illegal frame type: "
1125 << static_cast<int>(frame_type
);
1126 return RaiseError(QUIC_INVALID_FRAME_DATA
);
1129 switch (frame_type
) {
1131 // We're done with the packet.
1134 case RST_STREAM_FRAME
: {
1135 QuicRstStreamFrame frame
;
1136 if (!ProcessRstStreamFrame(&frame
)) {
1137 return RaiseError(QUIC_INVALID_RST_STREAM_DATA
);
1139 if (!visitor_
->OnRstStreamFrame(frame
)) {
1140 DVLOG(1) << "Visitor asked to stop further processing.";
1141 // Returning true since there was no parsing error.
1147 case CONNECTION_CLOSE_FRAME
: {
1148 QuicConnectionCloseFrame frame
;
1149 if (!ProcessConnectionCloseFrame(&frame
)) {
1150 return RaiseError(QUIC_INVALID_CONNECTION_CLOSE_DATA
);
1153 if (!visitor_
->OnConnectionCloseFrame(frame
)) {
1154 DVLOG(1) << "Visitor asked to stop further processing.";
1155 // Returning true since there was no parsing error.
1161 case GOAWAY_FRAME
: {
1162 QuicGoAwayFrame goaway_frame
;
1163 if (!ProcessGoAwayFrame(&goaway_frame
)) {
1164 return RaiseError(QUIC_INVALID_GOAWAY_DATA
);
1166 if (!visitor_
->OnGoAwayFrame(goaway_frame
)) {
1167 DVLOG(1) << "Visitor asked to stop further processing.";
1168 // Returning true since there was no parsing error.
1174 case WINDOW_UPDATE_FRAME
: {
1175 QuicWindowUpdateFrame window_update_frame
;
1176 if (!ProcessWindowUpdateFrame(&window_update_frame
)) {
1177 return RaiseError(QUIC_INVALID_WINDOW_UPDATE_DATA
);
1179 if (!visitor_
->OnWindowUpdateFrame(window_update_frame
)) {
1180 DVLOG(1) << "Visitor asked to stop further processing.";
1181 // Returning true since there was no parsing error.
1187 case BLOCKED_FRAME
: {
1188 QuicBlockedFrame blocked_frame
;
1189 if (!ProcessBlockedFrame(&blocked_frame
)) {
1190 return RaiseError(QUIC_INVALID_BLOCKED_DATA
);
1192 if (!visitor_
->OnBlockedFrame(blocked_frame
)) {
1193 DVLOG(1) << "Visitor asked to stop further processing.";
1194 // Returning true since there was no parsing error.
1200 case STOP_WAITING_FRAME
: {
1201 QuicStopWaitingFrame stop_waiting_frame
;
1202 if (!ProcessStopWaitingFrame(header
, &stop_waiting_frame
)) {
1203 return RaiseError(QUIC_INVALID_STOP_WAITING_DATA
);
1205 if (!visitor_
->OnStopWaitingFrame(stop_waiting_frame
)) {
1206 DVLOG(1) << "Visitor asked to stop further processing.";
1207 // Returning true since there was no parsing error.
1213 // Ping has no payload.
1214 QuicPingFrame ping_frame
;
1215 if (!visitor_
->OnPingFrame(ping_frame
)) {
1216 DVLOG(1) << "Visitor asked to stop further processing.";
1217 // Returning true since there was no parsing error.
1224 set_detailed_error("Illegal frame type.");
1225 DLOG(WARNING
) << "Illegal frame type: "
1226 << static_cast<int>(frame_type
);
1227 return RaiseError(QUIC_INVALID_FRAME_DATA
);
1234 bool QuicFramer::ProcessStreamFrame(uint8 frame_type
,
1235 QuicStreamFrame
* frame
) {
1236 uint8 stream_flags
= frame_type
;
1238 stream_flags
&= ~kQuicFrameTypeStreamMask
;
1240 // Read from right to left: StreamID, Offset, Data Length, Fin.
1241 const uint8 stream_id_length
= (stream_flags
& kQuicStreamIDLengthMask
) + 1;
1242 stream_flags
>>= kQuicStreamIdShift
;
1244 uint8 offset_length
= (stream_flags
& kQuicStreamOffsetMask
);
1245 // There is no encoding for 1 byte, only 0 and 2 through 8.
1246 if (offset_length
> 0) {
1249 stream_flags
>>= kQuicStreamOffsetShift
;
1251 bool has_data_length
=
1252 (stream_flags
& kQuicStreamDataLengthMask
) == kQuicStreamDataLengthMask
;
1253 stream_flags
>>= kQuicStreamDataLengthShift
;
1255 frame
->fin
= (stream_flags
& kQuicStreamFinMask
) == kQuicStreamFinShift
;
1257 frame
->stream_id
= 0;
1258 if (!reader_
->ReadBytes(&frame
->stream_id
, stream_id_length
)) {
1259 set_detailed_error("Unable to read stream_id.");
1264 if (!reader_
->ReadBytes(&frame
->offset
, offset_length
)) {
1265 set_detailed_error("Unable to read offset.");
1269 StringPiece frame_data
;
1270 if (has_data_length
) {
1271 if (!reader_
->ReadStringPiece16(&frame_data
)) {
1272 set_detailed_error("Unable to read frame data.");
1276 if (!reader_
->ReadStringPiece(&frame_data
, reader_
->BytesRemaining())) {
1277 set_detailed_error("Unable to read frame data.");
1281 // Point frame to the right data.
1282 frame
->data
.Clear();
1283 if (!frame_data
.empty()) {
1284 frame
->data
.Append(const_cast<char*>(frame_data
.data()), frame_data
.size());
1290 bool QuicFramer::ProcessAckFrame(uint8 frame_type
, QuicAckFrame
* ack_frame
) {
1291 // Determine the three lengths from the frame type: largest observed length,
1292 // missing sequence number length, and missing range length.
1293 const QuicSequenceNumberLength missing_sequence_number_length
=
1294 ReadSequenceNumberLength(frame_type
);
1295 frame_type
>>= kQuicSequenceNumberLengthShift
;
1296 const QuicSequenceNumberLength largest_observed_sequence_number_length
=
1297 ReadSequenceNumberLength(frame_type
);
1298 frame_type
>>= kQuicSequenceNumberLengthShift
;
1299 ack_frame
->is_truncated
= frame_type
& kQuicAckTruncatedMask
;
1300 frame_type
>>= kQuicAckTruncatedShift
;
1301 bool has_nacks
= frame_type
& kQuicHasNacksMask
;
1303 if (!reader_
->ReadBytes(&ack_frame
->entropy_hash
, 1)) {
1304 set_detailed_error("Unable to read entropy hash for received packets.");
1308 if (!reader_
->ReadBytes(&ack_frame
->largest_observed
,
1309 largest_observed_sequence_number_length
)) {
1310 set_detailed_error("Unable to read largest observed.");
1314 uint64 delta_time_largest_observed_us
;
1315 if (!reader_
->ReadUFloat16(&delta_time_largest_observed_us
)) {
1316 set_detailed_error("Unable to read delta time largest observed.");
1320 if (delta_time_largest_observed_us
== kUFloat16MaxValue
) {
1321 ack_frame
->delta_time_largest_observed
= QuicTime::Delta::Infinite();
1323 ack_frame
->delta_time_largest_observed
=
1324 QuicTime::Delta::FromMicroseconds(delta_time_largest_observed_us
);
1327 if (!ProcessTimestampsInAckFrame(ack_frame
)) {
1335 uint8 num_missing_ranges
;
1336 if (!reader_
->ReadBytes(&num_missing_ranges
, 1)) {
1337 set_detailed_error("Unable to read num missing packet ranges.");
1341 QuicPacketSequenceNumber last_sequence_number
= ack_frame
->largest_observed
;
1342 for (size_t i
= 0; i
< num_missing_ranges
; ++i
) {
1343 QuicPacketSequenceNumber missing_delta
= 0;
1344 if (!reader_
->ReadBytes(&missing_delta
, missing_sequence_number_length
)) {
1345 set_detailed_error("Unable to read missing sequence number delta.");
1348 last_sequence_number
-= missing_delta
;
1349 QuicPacketSequenceNumber range_length
= 0;
1350 if (!reader_
->ReadBytes(&range_length
, PACKET_1BYTE_SEQUENCE_NUMBER
)) {
1351 set_detailed_error("Unable to read missing sequence number range.");
1354 for (size_t j
= 0; j
<= range_length
; ++j
) {
1355 ack_frame
->missing_packets
.insert(last_sequence_number
- j
);
1357 // Subtract an extra 1 to ensure ranges are represented efficiently and
1358 // can't overlap by 1 sequence number. This allows a missing_delta of 0
1359 // to represent an adjacent nack range.
1360 last_sequence_number
-= (range_length
+ 1);
1363 // Parse the revived packets list.
1364 uint8 num_revived_packets
;
1365 if (!reader_
->ReadBytes(&num_revived_packets
, 1)) {
1366 set_detailed_error("Unable to read num revived packets.");
1370 for (size_t i
= 0; i
< num_revived_packets
; ++i
) {
1371 QuicPacketSequenceNumber revived_packet
= 0;
1372 if (!reader_
->ReadBytes(&revived_packet
,
1373 largest_observed_sequence_number_length
)) {
1374 set_detailed_error("Unable to read revived packet.");
1378 ack_frame
->revived_packets
.insert(revived_packet
);
1384 bool QuicFramer::ProcessTimestampsInAckFrame(QuicAckFrame
* ack_frame
) {
1385 if (!ack_frame
->is_truncated
) {
1386 uint8 num_received_packets
;
1387 if (!reader_
->ReadBytes(&num_received_packets
, 1)) {
1388 set_detailed_error("Unable to read num received packets.");
1392 if (num_received_packets
> 0) {
1393 uint8 delta_from_largest_observed
;
1394 if (!reader_
->ReadBytes(&delta_from_largest_observed
,
1395 PACKET_1BYTE_SEQUENCE_NUMBER
)) {
1397 "Unable to read sequence delta in received packets.");
1400 QuicPacketSequenceNumber seq_num
= ack_frame
->largest_observed
-
1401 delta_from_largest_observed
;
1403 // Time delta from the framer creation.
1404 uint32 time_delta_us
;
1405 if (!reader_
->ReadBytes(&time_delta_us
, sizeof(time_delta_us
))) {
1406 set_detailed_error("Unable to read time delta in received packets.");
1410 last_timestamp_
= CalculateTimestampFromWire(time_delta_us
);
1412 ack_frame
->received_packet_times
.push_back(
1413 std::make_pair(seq_num
, creation_time_
.Add(last_timestamp_
)));
1415 for (uint8 i
= 1; i
< num_received_packets
; ++i
) {
1416 if (!reader_
->ReadBytes(&delta_from_largest_observed
,
1417 PACKET_1BYTE_SEQUENCE_NUMBER
)) {
1419 "Unable to read sequence delta in received packets.");
1422 seq_num
= ack_frame
->largest_observed
- delta_from_largest_observed
;
1424 // Time delta from the previous timestamp.
1425 uint64 incremental_time_delta_us
;
1426 if (!reader_
->ReadUFloat16(&incremental_time_delta_us
)) {
1428 "Unable to read incremental time delta in received packets.");
1432 last_timestamp_
= last_timestamp_
.Add(
1433 QuicTime::Delta::FromMicroseconds(incremental_time_delta_us
));
1434 ack_frame
->received_packet_times
.push_back(
1435 std::make_pair(seq_num
, creation_time_
.Add(last_timestamp_
)));
1442 bool QuicFramer::ProcessStopWaitingFrame(const QuicPacketHeader
& header
,
1443 QuicStopWaitingFrame
* stop_waiting
) {
1444 if (!reader_
->ReadBytes(&stop_waiting
->entropy_hash
, 1)) {
1445 set_detailed_error("Unable to read entropy hash for sent packets.");
1449 QuicPacketSequenceNumber least_unacked_delta
= 0;
1450 if (!reader_
->ReadBytes(&least_unacked_delta
,
1451 header
.public_header
.sequence_number_length
)) {
1452 set_detailed_error("Unable to read least unacked delta.");
1455 DCHECK_GE(header
.packet_sequence_number
, least_unacked_delta
);
1456 stop_waiting
->least_unacked
=
1457 header
.packet_sequence_number
- least_unacked_delta
;
1462 bool QuicFramer::ProcessRstStreamFrame(QuicRstStreamFrame
* frame
) {
1463 if (!reader_
->ReadUInt32(&frame
->stream_id
)) {
1464 set_detailed_error("Unable to read stream_id.");
1468 if (!reader_
->ReadUInt64(&frame
->byte_offset
)) {
1469 set_detailed_error("Unable to read rst stream sent byte offset.");
1474 if (!reader_
->ReadUInt32(&error_code
)) {
1475 set_detailed_error("Unable to read rst stream error code.");
1479 if (error_code
>= QUIC_STREAM_LAST_ERROR
) {
1480 set_detailed_error("Invalid rst stream error code.");
1484 frame
->error_code
= static_cast<QuicRstStreamErrorCode
>(error_code
);
1486 StringPiece error_details
;
1487 if (!reader_
->ReadStringPiece16(&error_details
)) {
1488 set_detailed_error("Unable to read rst stream error details.");
1491 frame
->error_details
= error_details
.as_string();
1496 bool QuicFramer::ProcessConnectionCloseFrame(QuicConnectionCloseFrame
* frame
) {
1498 if (!reader_
->ReadUInt32(&error_code
)) {
1499 set_detailed_error("Unable to read connection close error code.");
1503 if (error_code
>= QUIC_LAST_ERROR
) {
1504 set_detailed_error("Invalid error code.");
1508 frame
->error_code
= static_cast<QuicErrorCode
>(error_code
);
1510 StringPiece error_details
;
1511 if (!reader_
->ReadStringPiece16(&error_details
)) {
1512 set_detailed_error("Unable to read connection close error details.");
1515 frame
->error_details
= error_details
.as_string();
1520 bool QuicFramer::ProcessGoAwayFrame(QuicGoAwayFrame
* frame
) {
1522 if (!reader_
->ReadUInt32(&error_code
)) {
1523 set_detailed_error("Unable to read go away error code.");
1526 frame
->error_code
= static_cast<QuicErrorCode
>(error_code
);
1528 if (error_code
>= QUIC_LAST_ERROR
) {
1529 set_detailed_error("Invalid error code.");
1534 if (!reader_
->ReadUInt32(&stream_id
)) {
1535 set_detailed_error("Unable to read last good stream id.");
1538 frame
->last_good_stream_id
= static_cast<QuicStreamId
>(stream_id
);
1540 StringPiece reason_phrase
;
1541 if (!reader_
->ReadStringPiece16(&reason_phrase
)) {
1542 set_detailed_error("Unable to read goaway reason.");
1545 frame
->reason_phrase
= reason_phrase
.as_string();
1550 bool QuicFramer::ProcessWindowUpdateFrame(QuicWindowUpdateFrame
* frame
) {
1551 if (!reader_
->ReadUInt32(&frame
->stream_id
)) {
1552 set_detailed_error("Unable to read stream_id.");
1556 if (!reader_
->ReadUInt64(&frame
->byte_offset
)) {
1557 set_detailed_error("Unable to read window byte_offset.");
1564 bool QuicFramer::ProcessBlockedFrame(QuicBlockedFrame
* frame
) {
1565 if (!reader_
->ReadUInt32(&frame
->stream_id
)) {
1566 set_detailed_error("Unable to read stream_id.");
1574 StringPiece
QuicFramer::GetAssociatedDataFromEncryptedPacket(
1575 const QuicEncryptedPacket
& encrypted
,
1576 QuicConnectionIdLength connection_id_length
,
1577 bool includes_version
,
1578 QuicSequenceNumberLength sequence_number_length
) {
1580 encrypted
.data() + kStartOfHashData
, GetStartOfEncryptedData(
1581 connection_id_length
, includes_version
, sequence_number_length
)
1582 - kStartOfHashData
);
1585 void QuicFramer::SetDecrypter(QuicDecrypter
* decrypter
,
1586 EncryptionLevel level
) {
1587 DCHECK(alternative_decrypter_
.get() == nullptr);
1588 DCHECK_GE(level
, decrypter_level_
);
1589 decrypter_
.reset(decrypter
);
1590 decrypter_level_
= level
;
1593 void QuicFramer::SetAlternativeDecrypter(QuicDecrypter
* decrypter
,
1594 EncryptionLevel level
,
1595 bool latch_once_used
) {
1596 alternative_decrypter_
.reset(decrypter
);
1597 alternative_decrypter_level_
= level
;
1598 alternative_decrypter_latch_
= latch_once_used
;
1601 const QuicDecrypter
* QuicFramer::decrypter() const {
1602 return decrypter_
.get();
1605 const QuicDecrypter
* QuicFramer::alternative_decrypter() const {
1606 return alternative_decrypter_
.get();
1609 void QuicFramer::SetEncrypter(EncryptionLevel level
,
1610 QuicEncrypter
* encrypter
) {
1611 DCHECK_GE(level
, 0);
1612 DCHECK_LT(level
, NUM_ENCRYPTION_LEVELS
);
1613 encrypter_
[level
].reset(encrypter
);
1616 QuicEncryptedPacket
* QuicFramer::EncryptPacket(
1617 EncryptionLevel level
,
1618 QuicPacketSequenceNumber packet_sequence_number
,
1619 const QuicPacket
& packet
) {
1620 DCHECK(encrypter_
[level
].get() != nullptr);
1622 // Allocate a large enough buffer for the header and the encrypted data.
1623 const size_t encrypted_len
=
1624 encrypter_
[level
]->GetCiphertextSize(packet
.Plaintext().length());
1625 StringPiece header_data
= packet
.BeforePlaintext();
1626 const size_t len
= header_data
.length() + encrypted_len
;
1627 // TODO(ianswett): Consider allocating this on the stack in the typical case.
1628 char* buffer
= new char[len
];
1629 // Copy in the header, because the encrypter only populates the encrypted
1630 // plaintext content.
1631 memcpy(buffer
, header_data
.data(), header_data
.length());
1632 // Encrypt the plaintext into the buffer.
1633 size_t output_length
= 0;
1634 if (!encrypter_
[level
]->EncryptPacket(
1635 packet_sequence_number
, packet
.AssociatedData(), packet
.Plaintext(),
1636 buffer
+ header_data
.length(), &output_length
, encrypted_len
)) {
1637 RaiseError(QUIC_ENCRYPTION_FAILURE
);
1641 return new QuicEncryptedPacket(buffer
, header_data
.length() + output_length
,
1645 size_t QuicFramer::GetMaxPlaintextSize(size_t ciphertext_size
) {
1646 // In order to keep the code simple, we don't have the current encryption
1647 // level to hand. Both the NullEncrypter and AES-GCM have a tag length of 12.
1648 size_t min_plaintext_size
= ciphertext_size
;
1650 for (int i
= ENCRYPTION_NONE
; i
< NUM_ENCRYPTION_LEVELS
; i
++) {
1651 if (encrypter_
[i
].get() != nullptr) {
1652 size_t size
= encrypter_
[i
]->GetMaxPlaintextSize(ciphertext_size
);
1653 if (size
< min_plaintext_size
) {
1654 min_plaintext_size
= size
;
1659 return min_plaintext_size
;
1662 bool QuicFramer::DecryptPayload(const QuicPacketHeader
& header
,
1663 const QuicEncryptedPacket
& packet
,
1664 char* decrypted_buffer
,
1665 size_t buffer_length
) {
1666 StringPiece encrypted
= reader_
->ReadRemainingPayload();
1667 DCHECK(decrypter_
.get() != nullptr);
1668 const StringPiece
& associated_data
= GetAssociatedDataFromEncryptedPacket(
1669 packet
, header
.public_header
.connection_id_length
,
1670 header
.public_header
.version_flag
,
1671 header
.public_header
.sequence_number_length
);
1672 size_t decrypted_length
= 0;
1673 bool success
= decrypter_
->DecryptPacket(
1674 header
.packet_sequence_number
, associated_data
, encrypted
,
1675 decrypted_buffer
, &decrypted_length
, buffer_length
);
1677 visitor_
->OnDecryptedPacket(decrypter_level_
);
1678 } else if (alternative_decrypter_
.get() != nullptr) {
1679 success
= alternative_decrypter_
->DecryptPacket(
1680 header
.packet_sequence_number
, associated_data
, encrypted
,
1681 decrypted_buffer
, &decrypted_length
, buffer_length
);
1683 visitor_
->OnDecryptedPacket(alternative_decrypter_level_
);
1684 if (alternative_decrypter_latch_
) {
1685 // Switch to the alternative decrypter and latch so that we cannot
1687 decrypter_
.reset(alternative_decrypter_
.release());
1688 decrypter_level_
= alternative_decrypter_level_
;
1689 alternative_decrypter_level_
= ENCRYPTION_NONE
;
1691 // Switch the alternative decrypter so that we use it first next time.
1692 decrypter_
.swap(alternative_decrypter_
);
1693 EncryptionLevel level
= alternative_decrypter_level_
;
1694 alternative_decrypter_level_
= decrypter_level_
;
1695 decrypter_level_
= level
;
1701 DLOG(WARNING
) << "DecryptPacket failed for sequence_number:"
1702 << header
.packet_sequence_number
;
1706 reader_
.reset(new QuicDataReader(decrypted_buffer
, decrypted_length
));
1710 size_t QuicFramer::GetAckFrameSize(
1711 const QuicAckFrame
& ack
,
1712 QuicSequenceNumberLength sequence_number_length
) {
1713 AckFrameInfo ack_info
= GetAckFrameInfo(ack
);
1714 QuicSequenceNumberLength largest_observed_length
=
1715 GetMinSequenceNumberLength(ack
.largest_observed
);
1716 QuicSequenceNumberLength missing_sequence_number_length
=
1717 GetMinSequenceNumberLength(ack_info
.max_delta
);
1719 size_t ack_size
= GetMinAckFrameSize(sequence_number_length
,
1720 largest_observed_length
);
1721 if (!ack_info
.nack_ranges
.empty()) {
1722 ack_size
+= kNumberOfNackRangesSize
+ kNumberOfRevivedPacketsSize
;
1723 ack_size
+= min(ack_info
.nack_ranges
.size(), kMaxNackRanges
) *
1724 (missing_sequence_number_length
+ PACKET_1BYTE_SEQUENCE_NUMBER
);
1725 ack_size
+= min(ack
.revived_packets
.size(),
1726 kMaxRevivedPackets
) * largest_observed_length
;
1729 // In version 23, if the ack will be truncated due to too many nack ranges,
1730 // then do not include the number of timestamps (1 byte).
1731 if (ack_info
.nack_ranges
.size() <= kMaxNackRanges
) {
1732 // 1 byte for the number of timestamps.
1734 if (ack
.received_packet_times
.size() > 0) {
1735 // 1 byte for sequence number, 4 bytes for timestamp for the first
1739 // 1 byte for sequence number, 2 bytes for timestamp for the other
1741 ack_size
+= 3 * (ack
.received_packet_times
.size() - 1);
1748 size_t QuicFramer::ComputeFrameLength(
1749 const QuicFrame
& frame
,
1750 bool last_frame_in_packet
,
1751 InFecGroup is_in_fec_group
,
1752 QuicSequenceNumberLength sequence_number_length
) {
1753 switch (frame
.type
) {
1755 return GetMinStreamFrameSize(frame
.stream_frame
->stream_id
,
1756 frame
.stream_frame
->offset
,
1757 last_frame_in_packet
,
1759 frame
.stream_frame
->data
.TotalBufferSize();
1761 return GetAckFrameSize(*frame
.ack_frame
, sequence_number_length
);
1763 case STOP_WAITING_FRAME
:
1764 return GetStopWaitingFrameSize(sequence_number_length
);
1766 // Ping has no payload.
1767 return kQuicFrameTypeSize
;
1768 case RST_STREAM_FRAME
:
1769 return GetMinRstStreamFrameSize() +
1770 frame
.rst_stream_frame
->error_details
.size();
1771 case CONNECTION_CLOSE_FRAME
:
1772 return GetMinConnectionCloseFrameSize() +
1773 frame
.connection_close_frame
->error_details
.size();
1775 return GetMinGoAwayFrameSize() + frame
.goaway_frame
->reason_phrase
.size();
1776 case WINDOW_UPDATE_FRAME
:
1777 return GetWindowUpdateFrameSize();
1779 return GetBlockedFrameSize();
1783 case NUM_FRAME_TYPES
:
1788 // Not reachable, but some Chrome compilers can't figure that out. *sigh*
1793 bool QuicFramer::AppendTypeByte(const QuicFrame
& frame
,
1794 bool no_stream_frame_length
,
1795 QuicDataWriter
* writer
) {
1796 uint8 type_byte
= 0;
1797 switch (frame
.type
) {
1798 case STREAM_FRAME
: {
1799 if (frame
.stream_frame
== nullptr) {
1800 LOG(DFATAL
) << "Failed to append STREAM frame with no stream_frame.";
1803 type_byte
|= frame
.stream_frame
->fin
? kQuicStreamFinMask
: 0;
1806 type_byte
<<= kQuicStreamDataLengthShift
;
1807 type_byte
|= no_stream_frame_length
? 0: kQuicStreamDataLengthMask
;
1810 type_byte
<<= kQuicStreamOffsetShift
;
1811 const size_t offset_len
= GetStreamOffsetSize(frame
.stream_frame
->offset
);
1812 if (offset_len
> 0) {
1813 type_byte
|= offset_len
- 1;
1816 // stream id 2 bits.
1817 type_byte
<<= kQuicStreamIdShift
;
1818 type_byte
|= GetStreamIdSize(frame
.stream_frame
->stream_id
) - 1;
1819 type_byte
|= kQuicFrameTypeStreamMask
; // Set Stream Frame Type to 1.
1825 type_byte
= static_cast<uint8
>(frame
.type
);
1829 return writer
->WriteUInt8(type_byte
);
1833 bool QuicFramer::AppendPacketSequenceNumber(
1834 QuicSequenceNumberLength sequence_number_length
,
1835 QuicPacketSequenceNumber packet_sequence_number
,
1836 QuicDataWriter
* writer
) {
1837 // Ensure the entire sequence number can be written.
1838 if (writer
->capacity() - writer
->length() <
1839 static_cast<size_t>(sequence_number_length
)) {
1842 switch (sequence_number_length
) {
1843 case PACKET_1BYTE_SEQUENCE_NUMBER
:
1844 return writer
->WriteUInt8(
1845 packet_sequence_number
& k1ByteSequenceNumberMask
);
1847 case PACKET_2BYTE_SEQUENCE_NUMBER
:
1848 return writer
->WriteUInt16(
1849 packet_sequence_number
& k2ByteSequenceNumberMask
);
1851 case PACKET_4BYTE_SEQUENCE_NUMBER
:
1852 return writer
->WriteUInt32(
1853 packet_sequence_number
& k4ByteSequenceNumberMask
);
1855 case PACKET_6BYTE_SEQUENCE_NUMBER
:
1856 return writer
->WriteUInt48(
1857 packet_sequence_number
& k6ByteSequenceNumberMask
);
1860 DCHECK(false) << "sequence_number_length: " << sequence_number_length
;
1865 bool QuicFramer::AppendStreamFrame(
1866 const QuicStreamFrame
& frame
,
1867 bool no_stream_frame_length
,
1868 QuicDataWriter
* writer
) {
1869 if (!writer
->WriteBytes(&frame
.stream_id
, GetStreamIdSize(frame
.stream_id
))) {
1870 LOG(DFATAL
) << "Writing stream id size failed.";
1873 if (!writer
->WriteBytes(&frame
.offset
, GetStreamOffsetSize(frame
.offset
))) {
1874 LOG(DFATAL
) << "Writing offset size failed.";
1877 if (!no_stream_frame_length
) {
1878 if ((frame
.data
.TotalBufferSize() > numeric_limits
<uint16
>::max()) ||
1879 !writer
->WriteUInt16(
1880 static_cast<uint16
>(frame
.data
.TotalBufferSize()))) {
1881 LOG(DFATAL
) << "Writing stream frame length failed";
1886 if (!writer
->WriteIOVector(frame
.data
)) {
1887 LOG(DFATAL
) << "Writing frame data failed.";
1894 void QuicFramer::set_version(const QuicVersion version
) {
1895 DCHECK(IsSupportedVersion(version
)) << QuicVersionToString(version
);
1896 quic_version_
= version
;
1899 bool QuicFramer::AppendAckFrameAndTypeByte(
1900 const QuicPacketHeader
& header
,
1901 const QuicAckFrame
& frame
,
1902 QuicDataWriter
* writer
) {
1903 AckFrameInfo ack_info
= GetAckFrameInfo(frame
);
1904 QuicPacketSequenceNumber ack_largest_observed
= frame
.largest_observed
;
1905 QuicSequenceNumberLength largest_observed_length
=
1906 GetMinSequenceNumberLength(ack_largest_observed
);
1907 QuicSequenceNumberLength missing_sequence_number_length
=
1908 GetMinSequenceNumberLength(ack_info
.max_delta
);
1909 // Determine whether we need to truncate ranges.
1910 size_t available_range_bytes
= writer
->capacity() - writer
->length() -
1911 kNumberOfRevivedPacketsSize
- kNumberOfNackRangesSize
-
1912 GetMinAckFrameSize(header
.public_header
.sequence_number_length
,
1913 largest_observed_length
);
1914 size_t max_num_ranges
= available_range_bytes
/
1915 (missing_sequence_number_length
+ PACKET_1BYTE_SEQUENCE_NUMBER
);
1916 max_num_ranges
= min(kMaxNackRanges
, max_num_ranges
);
1917 bool truncated
= ack_info
.nack_ranges
.size() > max_num_ranges
;
1918 DVLOG_IF(1, truncated
) << "Truncating ack from "
1919 << ack_info
.nack_ranges
.size() << " ranges to "
1921 // Write out the type byte by setting the low order bits and doing shifts
1922 // to make room for the next bit flags to be set.
1923 // Whether there are any nacks.
1924 uint8 type_byte
= ack_info
.nack_ranges
.empty() ? 0 : kQuicHasNacksMask
;
1927 type_byte
<<= kQuicAckTruncatedShift
;
1928 type_byte
|= truncated
? kQuicAckTruncatedMask
: 0;
1930 // Largest observed sequence number length.
1931 type_byte
<<= kQuicSequenceNumberLengthShift
;
1932 type_byte
|= GetSequenceNumberFlags(largest_observed_length
);
1934 // Missing sequence number length.
1935 type_byte
<<= kQuicSequenceNumberLengthShift
;
1936 type_byte
|= GetSequenceNumberFlags(missing_sequence_number_length
);
1938 type_byte
|= kQuicFrameTypeAckMask
;
1940 if (!writer
->WriteUInt8(type_byte
)) {
1944 QuicPacketEntropyHash ack_entropy_hash
= frame
.entropy_hash
;
1945 NackRangeMap::reverse_iterator ack_iter
= ack_info
.nack_ranges
.rbegin();
1947 // Skip the nack ranges which the truncated ack won't include and set
1948 // a correct largest observed for the truncated ack.
1949 for (size_t i
= 1; i
< (ack_info
.nack_ranges
.size() - max_num_ranges
);
1953 // If the last range is followed by acks, include them.
1954 // If the last range is followed by another range, specify the end of the
1955 // range as the largest_observed.
1956 ack_largest_observed
= ack_iter
->first
- 1;
1957 // Also update the entropy so it matches the largest observed.
1958 ack_entropy_hash
= entropy_calculator_
->EntropyHash(ack_largest_observed
);
1962 if (!writer
->WriteUInt8(ack_entropy_hash
)) {
1966 if (!AppendPacketSequenceNumber(largest_observed_length
,
1967 ack_largest_observed
, writer
)) {
1971 uint64 delta_time_largest_observed_us
= kUFloat16MaxValue
;
1972 if (!frame
.delta_time_largest_observed
.IsInfinite()) {
1973 DCHECK_LE(0u, frame
.delta_time_largest_observed
.ToMicroseconds());
1974 delta_time_largest_observed_us
=
1975 frame
.delta_time_largest_observed
.ToMicroseconds();
1978 if (!writer
->WriteUFloat16(delta_time_largest_observed_us
)) {
1982 // Timestamp goes at the end of the required fields.
1984 if (!AppendTimestampToAckFrame(frame
, writer
)) {
1989 if (ack_info
.nack_ranges
.empty()) {
1993 const uint8 num_missing_ranges
=
1994 static_cast<uint8
>(min(ack_info
.nack_ranges
.size(), max_num_ranges
));
1995 if (!writer
->WriteBytes(&num_missing_ranges
, 1)) {
1999 int num_ranges_written
= 0;
2000 QuicPacketSequenceNumber last_sequence_written
= ack_largest_observed
;
2001 for (; ack_iter
!= ack_info
.nack_ranges
.rend(); ++ack_iter
) {
2002 // Calculate the delta to the last number in the range.
2003 QuicPacketSequenceNumber missing_delta
=
2004 last_sequence_written
- (ack_iter
->first
+ ack_iter
->second
);
2005 if (!AppendPacketSequenceNumber(missing_sequence_number_length
,
2006 missing_delta
, writer
)) {
2009 if (!AppendPacketSequenceNumber(PACKET_1BYTE_SEQUENCE_NUMBER
,
2010 ack_iter
->second
, writer
)) {
2013 // Subtract 1 so a missing_delta of 0 means an adjacent range.
2014 last_sequence_written
= ack_iter
->first
- 1;
2015 ++num_ranges_written
;
2017 DCHECK_EQ(num_missing_ranges
, num_ranges_written
);
2019 // Append revived packets.
2020 // If not all the revived packets fit, only mention the ones that do.
2021 uint8 num_revived_packets
=
2022 static_cast<uint8
>(min(frame
.revived_packets
.size(), kMaxRevivedPackets
));
2023 num_revived_packets
= static_cast<uint8
>(min(
2024 static_cast<size_t>(num_revived_packets
),
2025 (writer
->capacity() - writer
->length()) / largest_observed_length
));
2026 if (!writer
->WriteBytes(&num_revived_packets
, 1)) {
2030 SequenceNumberSet::const_iterator iter
= frame
.revived_packets
.begin();
2031 for (int i
= 0; i
< num_revived_packets
; ++i
, ++iter
) {
2032 LOG_IF(DFATAL
, !ContainsKey(frame
.missing_packets
, *iter
));
2033 if (!AppendPacketSequenceNumber(largest_observed_length
,
2042 bool QuicFramer::AppendTimestampToAckFrame(const QuicAckFrame
& frame
,
2043 QuicDataWriter
* writer
) {
2044 DCHECK_GE(version(), QUIC_VERSION_23
);
2045 DCHECK_GE(numeric_limits
<uint8
>::max(), frame
.received_packet_times
.size());
2046 // num_received_packets is only 1 byte.
2047 if (frame
.received_packet_times
.size() > numeric_limits
<uint8
>::max()) {
2051 uint8 num_received_packets
= frame
.received_packet_times
.size();
2053 if (!writer
->WriteBytes(&num_received_packets
, 1)) {
2056 if (num_received_packets
== 0) {
2060 PacketTimeList::const_iterator it
= frame
.received_packet_times
.begin();
2061 QuicPacketSequenceNumber sequence_number
= it
->first
;
2062 QuicPacketSequenceNumber delta_from_largest_observed
=
2063 frame
.largest_observed
- sequence_number
;
2065 DCHECK_GE(numeric_limits
<uint8
>::max(), delta_from_largest_observed
);
2066 if (delta_from_largest_observed
> numeric_limits
<uint8
>::max()) {
2070 if (!writer
->WriteUInt8(
2071 delta_from_largest_observed
& k1ByteSequenceNumberMask
)) {
2075 // Use the lowest 4 bytes of the time delta from the creation_time_.
2076 const uint64 time_epoch_delta_us
= GG_UINT64_C(1) << 32;
2077 uint32 time_delta_us
=
2078 static_cast<uint32
>(it
->second
.Subtract(creation_time_
).ToMicroseconds()
2079 & (time_epoch_delta_us
- 1));
2080 if (!writer
->WriteBytes(&time_delta_us
, sizeof(time_delta_us
))) {
2084 QuicTime prev_time
= it
->second
;
2086 for (++it
; it
!= frame
.received_packet_times
.end(); ++it
) {
2087 sequence_number
= it
->first
;
2088 delta_from_largest_observed
= frame
.largest_observed
- sequence_number
;
2090 if (delta_from_largest_observed
> numeric_limits
<uint8
>::max()) {
2094 if (!writer
->WriteUInt8(
2095 delta_from_largest_observed
& k1ByteSequenceNumberMask
)) {
2099 uint64 frame_time_delta_us
=
2100 it
->second
.Subtract(prev_time
).ToMicroseconds();
2101 prev_time
= it
->second
;
2102 if (!writer
->WriteUFloat16(frame_time_delta_us
)) {
2109 bool QuicFramer::AppendStopWaitingFrame(
2110 const QuicPacketHeader
& header
,
2111 const QuicStopWaitingFrame
& frame
,
2112 QuicDataWriter
* writer
) {
2113 DCHECK_GE(header
.packet_sequence_number
, frame
.least_unacked
);
2114 const QuicPacketSequenceNumber least_unacked_delta
=
2115 header
.packet_sequence_number
- frame
.least_unacked
;
2116 const QuicPacketSequenceNumber length_shift
=
2117 header
.public_header
.sequence_number_length
* 8;
2118 if (!writer
->WriteUInt8(frame
.entropy_hash
)) {
2119 LOG(DFATAL
) << " hash failed";
2123 if (least_unacked_delta
>> length_shift
> 0) {
2124 LOG(DFATAL
) << "sequence_number_length "
2125 << header
.public_header
.sequence_number_length
2126 << " is too small for least_unacked_delta: "
2127 << least_unacked_delta
;
2130 if (!AppendPacketSequenceNumber(header
.public_header
.sequence_number_length
,
2131 least_unacked_delta
, writer
)) {
2132 LOG(DFATAL
) << " seq failed: "
2133 << header
.public_header
.sequence_number_length
;
2140 bool QuicFramer::AppendRstStreamFrame(
2141 const QuicRstStreamFrame
& frame
,
2142 QuicDataWriter
* writer
) {
2143 if (!writer
->WriteUInt32(frame
.stream_id
)) {
2147 if (!writer
->WriteUInt64(frame
.byte_offset
)) {
2151 uint32 error_code
= static_cast<uint32
>(frame
.error_code
);
2152 if (!writer
->WriteUInt32(error_code
)) {
2156 if (!writer
->WriteStringPiece16(frame
.error_details
)) {
2162 bool QuicFramer::AppendConnectionCloseFrame(
2163 const QuicConnectionCloseFrame
& frame
,
2164 QuicDataWriter
* writer
) {
2165 uint32 error_code
= static_cast<uint32
>(frame
.error_code
);
2166 if (!writer
->WriteUInt32(error_code
)) {
2169 if (!writer
->WriteStringPiece16(frame
.error_details
)) {
2175 bool QuicFramer::AppendGoAwayFrame(const QuicGoAwayFrame
& frame
,
2176 QuicDataWriter
* writer
) {
2177 uint32 error_code
= static_cast<uint32
>(frame
.error_code
);
2178 if (!writer
->WriteUInt32(error_code
)) {
2181 uint32 stream_id
= static_cast<uint32
>(frame
.last_good_stream_id
);
2182 if (!writer
->WriteUInt32(stream_id
)) {
2185 if (!writer
->WriteStringPiece16(frame
.reason_phrase
)) {
2191 bool QuicFramer::AppendWindowUpdateFrame(const QuicWindowUpdateFrame
& frame
,
2192 QuicDataWriter
* writer
) {
2193 uint32 stream_id
= static_cast<uint32
>(frame
.stream_id
);
2194 if (!writer
->WriteUInt32(stream_id
)) {
2197 if (!writer
->WriteUInt64(frame
.byte_offset
)) {
2203 bool QuicFramer::AppendBlockedFrame(const QuicBlockedFrame
& frame
,
2204 QuicDataWriter
* writer
) {
2205 uint32 stream_id
= static_cast<uint32
>(frame
.stream_id
);
2206 if (!writer
->WriteUInt32(stream_id
)) {
2212 bool QuicFramer::RaiseError(QuicErrorCode error
) {
2213 DVLOG(1) << "Error detail: " << detailed_error_
;
2215 visitor_
->OnError(this);
2216 reader_
.reset(nullptr);