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/basictypes.h"
8 #include "base/logging.h"
9 #include "base/stl_util.h"
10 #include "net/quic/crypto/crypto_framer.h"
11 #include "net/quic/crypto/crypto_handshake_message.h"
12 #include "net/quic/crypto/crypto_protocol.h"
13 #include "net/quic/crypto/quic_decrypter.h"
14 #include "net/quic/crypto/quic_encrypter.h"
15 #include "net/quic/quic_data_reader.h"
16 #include "net/quic/quic_data_writer.h"
17 #include "net/quic/quic_flags.h"
18 #include "net/quic/quic_socket_address_coder.h"
19 #include "net/quic/quic_utils.h"
21 using base::StringPiece
;
25 using std::numeric_limits
;
32 // Mask to select the lowest 48 bits of a sequence number.
33 const QuicPacketSequenceNumber k6ByteSequenceNumberMask
=
34 GG_UINT64_C(0x0000FFFFFFFFFFFF);
35 const QuicPacketSequenceNumber k4ByteSequenceNumberMask
=
36 GG_UINT64_C(0x00000000FFFFFFFF);
37 const QuicPacketSequenceNumber k2ByteSequenceNumberMask
=
38 GG_UINT64_C(0x000000000000FFFF);
39 const QuicPacketSequenceNumber k1ByteSequenceNumberMask
=
40 GG_UINT64_C(0x00000000000000FF);
42 const QuicConnectionId k1ByteConnectionIdMask
= GG_UINT64_C(0x00000000000000FF);
43 const QuicConnectionId k4ByteConnectionIdMask
= GG_UINT64_C(0x00000000FFFFFFFF);
45 // Number of bits the sequence number length bits are shifted from the right
46 // edge of the public header.
47 const uint8 kPublicHeaderSequenceNumberShift
= 4;
49 // New Frame Types, QUIC v. >= 10:
50 // There are two interpretations for the Frame Type byte in the QUIC protocol,
51 // resulting in two Frame Types: Special Frame Types and Regular Frame Types.
53 // Regular Frame Types use the Frame Type byte simply. Currently defined
54 // Regular Frame Types are:
55 // Padding : 0b 00000000 (0x00)
56 // ResetStream : 0b 00000001 (0x01)
57 // ConnectionClose : 0b 00000010 (0x02)
58 // GoAway : 0b 00000011 (0x03)
59 // WindowUpdate : 0b 00000100 (0x04)
60 // Blocked : 0b 00000101 (0x05)
62 // Special Frame Types encode both a Frame Type and corresponding flags
63 // all in the Frame Type byte. Currently defined Special Frame Types are:
64 // Stream : 0b 1xxxxxxx
67 // Semantics of the flag bits above (the x bits) depends on the frame type.
69 // Masks to determine if the frame type is a special use
70 // and for specific special frame types.
71 const uint8 kQuicFrameTypeSpecialMask
= 0xE0; // 0b 11100000
72 const uint8 kQuicFrameTypeStreamMask
= 0x80;
73 const uint8 kQuicFrameTypeAckMask
= 0x40;
75 // Stream frame relative shifts and masks for interpreting the stream flags.
76 // StreamID may be 1, 2, 3, or 4 bytes.
77 const uint8 kQuicStreamIdShift
= 2;
78 const uint8 kQuicStreamIDLengthMask
= 0x03;
80 // Offset may be 0, 2, 3, 4, 5, 6, 7, 8 bytes.
81 const uint8 kQuicStreamOffsetShift
= 3;
82 const uint8 kQuicStreamOffsetMask
= 0x07;
84 // Data length may be 0 or 2 bytes.
85 const uint8 kQuicStreamDataLengthShift
= 1;
86 const uint8 kQuicStreamDataLengthMask
= 0x01;
88 // Fin bit may be set or not.
89 const uint8 kQuicStreamFinShift
= 1;
90 const uint8 kQuicStreamFinMask
= 0x01;
92 // Sequence number size shift used in AckFrames.
93 const uint8 kQuicSequenceNumberLengthShift
= 2;
95 // Acks may be truncated.
96 const uint8 kQuicAckTruncatedShift
= 1;
97 const uint8 kQuicAckTruncatedMask
= 0x01;
99 // Acks may not have any nacks.
100 const uint8 kQuicHasNacksMask
= 0x01;
102 // Returns the absolute value of the difference between |a| and |b|.
103 QuicPacketSequenceNumber
Delta(QuicPacketSequenceNumber a
,
104 QuicPacketSequenceNumber b
) {
105 // Since these are unsigned numbers, we can't just return abs(a - b)
112 QuicPacketSequenceNumber
ClosestTo(QuicPacketSequenceNumber target
,
113 QuicPacketSequenceNumber a
,
114 QuicPacketSequenceNumber b
) {
115 return (Delta(target
, a
) < Delta(target
, b
)) ? a
: b
;
118 QuicSequenceNumberLength
ReadSequenceNumberLength(uint8 flags
) {
119 switch (flags
& PACKET_FLAGS_6BYTE_SEQUENCE
) {
120 case PACKET_FLAGS_6BYTE_SEQUENCE
:
121 return PACKET_6BYTE_SEQUENCE_NUMBER
;
122 case PACKET_FLAGS_4BYTE_SEQUENCE
:
123 return PACKET_4BYTE_SEQUENCE_NUMBER
;
124 case PACKET_FLAGS_2BYTE_SEQUENCE
:
125 return PACKET_2BYTE_SEQUENCE_NUMBER
;
126 case PACKET_FLAGS_1BYTE_SEQUENCE
:
127 return PACKET_1BYTE_SEQUENCE_NUMBER
;
129 LOG(DFATAL
) << "Unreachable case statement.";
130 return PACKET_6BYTE_SEQUENCE_NUMBER
;
136 bool QuicFramerVisitorInterface::OnWindowUpdateFrame(
137 const QuicWindowUpdateFrame
& frame
) {
141 bool QuicFramerVisitorInterface::OnBlockedFrame(const QuicBlockedFrame
& frame
) {
145 QuicFramer::QuicFramer(const QuicVersionVector
& supported_versions
,
146 QuicTime creation_time
,
147 Perspective perspective
)
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::GetRstStreamFrameSize() {
205 return kQuicFrameTypeSize
+ kQuicMaxStreamIdSize
+ kQuicMaxStreamOffsetSize
+
210 size_t QuicFramer::GetMinConnectionCloseFrameSize() {
211 return kQuicFrameTypeSize
+ kQuicErrorCodeSize
+ kQuicErrorDetailsLengthSize
;
215 size_t QuicFramer::GetMinGoAwayFrameSize() {
216 return kQuicFrameTypeSize
+ kQuicErrorCodeSize
+ kQuicErrorDetailsLengthSize
+
217 kQuicMaxStreamIdSize
;
221 size_t QuicFramer::GetWindowUpdateFrameSize() {
222 return kQuicFrameTypeSize
+ kQuicMaxStreamIdSize
+ kQuicMaxStreamOffsetSize
;
226 size_t QuicFramer::GetBlockedFrameSize() {
227 return kQuicFrameTypeSize
+ kQuicMaxStreamIdSize
;
231 size_t QuicFramer::GetStreamIdSize(QuicStreamId stream_id
) {
232 // Sizes are 1 through 4 bytes.
233 for (int i
= 1; i
<= 4; ++i
) {
235 if (stream_id
== 0) {
239 LOG(DFATAL
) << "Failed to determine StreamIDSize.";
244 size_t QuicFramer::GetStreamOffsetSize(QuicStreamOffset offset
) {
245 // 0 is a special case.
249 // 2 through 8 are the remaining sizes.
251 for (int i
= 2; i
<= 8; ++i
) {
257 LOG(DFATAL
) << "Failed to determine StreamOffsetSize.";
262 size_t QuicFramer::GetVersionNegotiationPacketSize(size_t number_versions
) {
263 return kPublicFlagsSize
+ PACKET_8BYTE_CONNECTION_ID
+
264 number_versions
* kQuicVersionSize
;
267 bool QuicFramer::IsSupportedVersion(const QuicVersion version
) const {
268 for (size_t i
= 0; i
< supported_versions_
.size(); ++i
) {
269 if (version
== supported_versions_
[i
]) {
276 size_t QuicFramer::GetSerializedFrameLength(
277 const QuicFrame
& frame
,
281 InFecGroup is_in_fec_group
,
282 QuicSequenceNumberLength sequence_number_length
) {
283 if (frame
.type
== PADDING_FRAME
) {
284 // PADDING implies end of packet.
288 ComputeFrameLength(frame
, last_frame
, is_in_fec_group
,
289 sequence_number_length
);
290 if (frame_len
<= free_bytes
) {
291 // Frame fits within packet. Note that acks may be truncated.
294 // Only truncate the first frame in a packet, so if subsequent ones go
295 // over, stop including more frames.
299 bool can_truncate
= frame
.type
== ACK_FRAME
&&
300 free_bytes
>= GetMinAckFrameSize(PACKET_6BYTE_SEQUENCE_NUMBER
,
301 PACKET_6BYTE_SEQUENCE_NUMBER
);
303 // Truncate the frame so the packet will not exceed kMaxPacketSize.
304 // Note that we may not use every byte of the writer in this case.
305 DVLOG(1) << "Truncating large frame, free bytes: " << free_bytes
;
308 if (!FLAGS_quic_allow_oversized_packets_for_test
) {
311 LOG(DFATAL
) << "Packet size too small to fit frame.";
315 QuicFramer::AckFrameInfo::AckFrameInfo() : max_delta(0) {}
317 QuicFramer::AckFrameInfo::~AckFrameInfo() {}
320 QuicPacketEntropyHash
QuicFramer::GetPacketEntropyHash(
321 const QuicPacketHeader
& header
) {
322 return header
.entropy_flag
<< (header
.packet_sequence_number
% 8);
325 QuicPacket
* QuicFramer::BuildDataPacket(const QuicPacketHeader
& header
,
326 const QuicFrames
& frames
,
328 size_t packet_length
) {
329 QuicDataWriter
writer(packet_length
, buffer
);
330 if (!AppendPacketHeader(header
, &writer
)) {
331 LOG(DFATAL
) << "AppendPacketHeader failed";
336 for (const QuicFrame
& frame
: frames
) {
337 // Determine if we should write stream frame length in header.
338 const bool no_stream_frame_length
=
339 (header
.is_in_fec_group
== NOT_IN_FEC_GROUP
) &&
340 (i
== frames
.size() - 1);
341 if (!AppendTypeByte(frame
, no_stream_frame_length
, &writer
)) {
342 LOG(DFATAL
) << "AppendTypeByte failed";
346 switch (frame
.type
) {
348 writer
.WritePadding();
351 if (!AppendStreamFrame(
352 *frame
.stream_frame
, no_stream_frame_length
, &writer
)) {
353 LOG(DFATAL
) << "AppendStreamFrame failed";
358 if (!AppendAckFrameAndTypeByte(
359 header
, *frame
.ack_frame
, &writer
)) {
360 LOG(DFATAL
) << "AppendAckFrameAndTypeByte failed";
364 case STOP_WAITING_FRAME
:
365 if (!AppendStopWaitingFrame(
366 header
, *frame
.stop_waiting_frame
, &writer
)) {
367 LOG(DFATAL
) << "AppendStopWaitingFrame failed";
372 // Ping has no payload.
374 case RST_STREAM_FRAME
:
375 if (!AppendRstStreamFrame(*frame
.rst_stream_frame
, &writer
)) {
376 LOG(DFATAL
) << "AppendRstStreamFrame failed";
380 case CONNECTION_CLOSE_FRAME
:
381 if (!AppendConnectionCloseFrame(
382 *frame
.connection_close_frame
, &writer
)) {
383 LOG(DFATAL
) << "AppendConnectionCloseFrame failed";
388 if (!AppendGoAwayFrame(*frame
.goaway_frame
, &writer
)) {
389 LOG(DFATAL
) << "AppendGoAwayFrame failed";
393 case WINDOW_UPDATE_FRAME
:
394 if (!AppendWindowUpdateFrame(*frame
.window_update_frame
, &writer
)) {
395 LOG(DFATAL
) << "AppendWindowUpdateFrame failed";
400 if (!AppendBlockedFrame(*frame
.blocked_frame
, &writer
)) {
401 LOG(DFATAL
) << "AppendBlockedFrame failed";
406 RaiseError(QUIC_INVALID_FRAME_DATA
);
407 LOG(DFATAL
) << "QUIC_INVALID_FRAME_DATA";
414 new QuicPacket(writer
.data(), writer
.length(), false,
415 header
.public_header
.connection_id_length
,
416 header
.public_header
.version_flag
,
417 header
.public_header
.sequence_number_length
);
422 QuicPacket
* QuicFramer::BuildFecPacket(const QuicPacketHeader
& header
,
423 const QuicFecData
& fec
) {
424 DCHECK_EQ(IN_FEC_GROUP
, header
.is_in_fec_group
);
425 DCHECK_NE(0u, header
.fec_group
);
426 size_t len
= GetPacketHeaderSize(header
);
427 len
+= fec
.redundancy
.length();
429 scoped_ptr
<char[]> buffer(new char[len
]);
430 QuicDataWriter
writer(len
, buffer
.get());
431 if (!AppendPacketHeader(header
, &writer
)) {
432 LOG(DFATAL
) << "AppendPacketHeader failed";
436 if (!writer
.WriteBytes(fec
.redundancy
.data(), fec
.redundancy
.length())) {
437 LOG(DFATAL
) << "Failed to add FEC";
441 return new QuicPacket(buffer
.release(), len
, true,
442 header
.public_header
.connection_id_length
,
443 header
.public_header
.version_flag
,
444 header
.public_header
.sequence_number_length
);
448 QuicEncryptedPacket
* QuicFramer::BuildPublicResetPacket(
449 const QuicPublicResetPacket
& packet
) {
450 DCHECK(packet
.public_header
.reset_flag
);
452 CryptoHandshakeMessage reset
;
453 reset
.set_tag(kPRST
);
454 reset
.SetValue(kRNON
, packet
.nonce_proof
);
455 reset
.SetValue(kRSEQ
, packet
.rejected_sequence_number
);
456 if (!packet
.client_address
.address().empty()) {
457 // packet.client_address is non-empty.
458 QuicSocketAddressCoder
address_coder(packet
.client_address
);
459 string serialized_address
= address_coder
.Encode();
460 if (serialized_address
.empty()) {
463 reset
.SetStringPiece(kCADR
, serialized_address
);
465 const QuicData
& reset_serialized
= reset
.GetSerialized();
468 kPublicFlagsSize
+ PACKET_8BYTE_CONNECTION_ID
+ reset_serialized
.length();
469 scoped_ptr
<char[]> buffer(new char[len
]);
470 QuicDataWriter
writer(len
, buffer
.get());
472 uint8 flags
= static_cast<uint8
>(PACKET_PUBLIC_FLAGS_RST
|
473 PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID
);
474 if (!writer
.WriteUInt8(flags
)) {
478 if (!writer
.WriteUInt64(packet
.public_header
.connection_id
)) {
482 if (!writer
.WriteBytes(reset_serialized
.data(), reset_serialized
.length())) {
486 return new QuicEncryptedPacket(buffer
.release(), len
, true);
489 QuicEncryptedPacket
* QuicFramer::BuildVersionNegotiationPacket(
490 const QuicPacketPublicHeader
& header
,
491 const QuicVersionVector
& supported_versions
) {
492 DCHECK(header
.version_flag
);
493 size_t len
= GetVersionNegotiationPacketSize(supported_versions
.size());
494 scoped_ptr
<char[]> buffer(new char[len
]);
495 QuicDataWriter
writer(len
, buffer
.get());
497 uint8 flags
= static_cast<uint8
>(PACKET_PUBLIC_FLAGS_VERSION
|
498 PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID
);
499 if (!writer
.WriteUInt8(flags
)) {
503 if (!writer
.WriteUInt64(header
.connection_id
)) {
507 for (size_t i
= 0; i
< supported_versions
.size(); ++i
) {
508 if (!writer
.WriteUInt32(QuicVersionToQuicTag(supported_versions
[i
]))) {
513 return new QuicEncryptedPacket(buffer
.release(), len
, true);
516 bool QuicFramer::ProcessPacket(const QuicEncryptedPacket
& packet
) {
517 DCHECK(!reader_
.get());
518 reader_
.reset(new QuicDataReader(packet
.data(), packet
.length()));
520 visitor_
->OnPacket();
522 // First parse the public header.
523 QuicPacketPublicHeader public_header
;
524 if (!ProcessPublicHeader(&public_header
)) {
525 DLOG(WARNING
) << "Unable to process public header.";
526 DCHECK_NE("", detailed_error_
);
527 return RaiseError(QUIC_INVALID_PACKET_HEADER
);
530 if (!visitor_
->OnUnauthenticatedPublicHeader(public_header
)) {
531 // The visitor suppresses further processing of the packet.
532 reader_
.reset(nullptr);
536 if (perspective_
== Perspective::IS_SERVER
&& public_header
.version_flag
&&
537 public_header
.versions
[0] != quic_version_
) {
538 if (!visitor_
->OnProtocolVersionMismatch(public_header
.versions
[0])) {
539 reader_
.reset(nullptr);
545 if (perspective_
== Perspective::IS_CLIENT
&& public_header
.version_flag
) {
546 rv
= ProcessVersionNegotiationPacket(&public_header
);
547 } else if (public_header
.reset_flag
) {
548 rv
= ProcessPublicResetPacket(public_header
);
549 } else if (packet
.length() <= kMaxPacketSize
) {
550 char buffer
[kMaxPacketSize
];
551 rv
= ProcessDataPacket(public_header
, packet
, buffer
, kMaxPacketSize
);
553 scoped_ptr
<char[]> large_buffer(new char[packet
.length()]);
554 rv
= ProcessDataPacket(public_header
, packet
, large_buffer
.get(),
556 LOG_IF(DFATAL
, rv
) << "QUIC should never successfully process packets "
557 << "larger than kMaxPacketSize. packet size:"
561 reader_
.reset(nullptr);
565 bool QuicFramer::ProcessVersionNegotiationPacket(
566 QuicPacketPublicHeader
* public_header
) {
567 DCHECK_EQ(Perspective::IS_CLIENT
, perspective_
);
568 // Try reading at least once to raise error if the packet is invalid.
571 if (!reader_
->ReadBytes(&version
, kQuicVersionSize
)) {
572 set_detailed_error("Unable to read supported version in negotiation.");
573 return RaiseError(QUIC_INVALID_VERSION_NEGOTIATION_PACKET
);
575 public_header
->versions
.push_back(QuicTagToQuicVersion(version
));
576 } while (!reader_
->IsDoneReading());
578 visitor_
->OnVersionNegotiationPacket(*public_header
);
582 bool QuicFramer::ProcessDataPacket(const QuicPacketPublicHeader
& public_header
,
583 const QuicEncryptedPacket
& packet
,
584 char* decrypted_buffer
,
585 size_t buffer_length
) {
586 QuicPacketHeader
header(public_header
);
587 if (!ProcessPacketHeader(&header
, packet
, decrypted_buffer
, buffer_length
)) {
588 DLOG(WARNING
) << "Unable to process data packet header.";
592 if (!visitor_
->OnPacketHeader(header
)) {
593 // The visitor suppresses further processing of the packet.
597 if (packet
.length() > kMaxPacketSize
) {
598 DLOG(WARNING
) << "Packet too large: " << packet
.length();
599 return RaiseError(QUIC_PACKET_TOO_LARGE
);
602 // Handle the payload.
603 if (!header
.fec_flag
) {
604 if (header
.is_in_fec_group
== IN_FEC_GROUP
) {
605 StringPiece payload
= reader_
->PeekRemainingPayload();
606 visitor_
->OnFecProtectedPayload(payload
);
608 if (!ProcessFrameData(header
)) {
609 DCHECK_NE(QUIC_NO_ERROR
, error_
); // ProcessFrameData sets the error.
610 DLOG(WARNING
) << "Unable to process frame data.";
614 QuicFecData fec_data
;
615 fec_data
.fec_group
= header
.fec_group
;
616 fec_data
.redundancy
= reader_
->ReadRemainingPayload();
617 visitor_
->OnFecData(fec_data
);
620 visitor_
->OnPacketComplete();
624 bool QuicFramer::ProcessPublicResetPacket(
625 const QuicPacketPublicHeader
& public_header
) {
626 QuicPublicResetPacket
packet(public_header
);
628 scoped_ptr
<CryptoHandshakeMessage
> reset(
629 CryptoFramer::ParseMessage(reader_
->ReadRemainingPayload()));
631 set_detailed_error("Unable to read reset message.");
632 return RaiseError(QUIC_INVALID_PUBLIC_RST_PACKET
);
634 if (reset
->tag() != kPRST
) {
635 set_detailed_error("Incorrect message tag.");
636 return RaiseError(QUIC_INVALID_PUBLIC_RST_PACKET
);
639 if (reset
->GetUint64(kRNON
, &packet
.nonce_proof
) != QUIC_NO_ERROR
) {
640 set_detailed_error("Unable to read nonce proof.");
641 return RaiseError(QUIC_INVALID_PUBLIC_RST_PACKET
);
643 // TODO(satyamshekhar): validate nonce to protect against DoS.
645 if (reset
->GetUint64(kRSEQ
, &packet
.rejected_sequence_number
) !=
647 set_detailed_error("Unable to read rejected sequence number.");
648 return RaiseError(QUIC_INVALID_PUBLIC_RST_PACKET
);
652 if (reset
->GetStringPiece(kCADR
, &address
)) {
653 QuicSocketAddressCoder address_coder
;
654 if (address_coder
.Decode(address
.data(), address
.length())) {
655 packet
.client_address
= IPEndPoint(address_coder
.ip(),
656 address_coder
.port());
660 visitor_
->OnPublicResetPacket(packet
);
664 bool QuicFramer::ProcessRevivedPacket(QuicPacketHeader
* header
,
665 StringPiece payload
) {
666 DCHECK(!reader_
.get());
668 visitor_
->OnRevivedPacket();
670 header
->entropy_hash
= GetPacketEntropyHash(*header
);
672 if (!visitor_
->OnPacketHeader(*header
)) {
676 if (payload
.length() > kMaxPacketSize
) {
677 set_detailed_error("Revived packet too large.");
678 return RaiseError(QUIC_PACKET_TOO_LARGE
);
681 reader_
.reset(new QuicDataReader(payload
.data(), payload
.length()));
682 if (!ProcessFrameData(*header
)) {
683 DCHECK_NE(QUIC_NO_ERROR
, error_
); // ProcessFrameData sets the error.
684 DLOG(WARNING
) << "Unable to process frame data.";
688 visitor_
->OnPacketComplete();
689 reader_
.reset(nullptr);
693 bool QuicFramer::AppendPacketHeader(const QuicPacketHeader
& header
,
694 QuicDataWriter
* writer
) {
695 DVLOG(1) << "Appending header: " << header
;
696 DCHECK(header
.fec_group
> 0 || header
.is_in_fec_group
== NOT_IN_FEC_GROUP
);
697 uint8 public_flags
= 0;
698 if (header
.public_header
.reset_flag
) {
699 public_flags
|= PACKET_PUBLIC_FLAGS_RST
;
701 if (header
.public_header
.version_flag
) {
702 public_flags
|= PACKET_PUBLIC_FLAGS_VERSION
;
706 GetSequenceNumberFlags(header
.public_header
.sequence_number_length
)
707 << kPublicHeaderSequenceNumberShift
;
709 switch (header
.public_header
.connection_id_length
) {
710 case PACKET_0BYTE_CONNECTION_ID
:
711 if (!writer
->WriteUInt8(
712 public_flags
| PACKET_PUBLIC_FLAGS_0BYTE_CONNECTION_ID
)) {
716 case PACKET_1BYTE_CONNECTION_ID
:
717 if (!writer
->WriteUInt8(
718 public_flags
| PACKET_PUBLIC_FLAGS_1BYTE_CONNECTION_ID
)) {
721 if (!writer
->WriteUInt8(
722 header
.public_header
.connection_id
& k1ByteConnectionIdMask
)) {
726 case PACKET_4BYTE_CONNECTION_ID
:
727 if (!writer
->WriteUInt8(
728 public_flags
| PACKET_PUBLIC_FLAGS_4BYTE_CONNECTION_ID
)) {
731 if (!writer
->WriteUInt32(
732 header
.public_header
.connection_id
& k4ByteConnectionIdMask
)) {
736 case PACKET_8BYTE_CONNECTION_ID
:
737 if (!writer
->WriteUInt8(
738 public_flags
| PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID
)) {
741 if (!writer
->WriteUInt64(header
.public_header
.connection_id
)) {
746 last_serialized_connection_id_
= header
.public_header
.connection_id
;
748 if (header
.public_header
.version_flag
) {
749 DCHECK_EQ(Perspective::IS_CLIENT
, perspective_
);
750 QuicTag tag
= QuicVersionToQuicTag(quic_version_
);
751 writer
->WriteUInt32(tag
);
752 DVLOG(1) << "version = " << quic_version_
<< ", tag = '"
753 << QuicUtils::TagToString(tag
) << "'";
756 if (!AppendPacketSequenceNumber(header
.public_header
.sequence_number_length
,
757 header
.packet_sequence_number
, writer
)) {
761 uint8 private_flags
= 0;
762 if (header
.entropy_flag
) {
763 private_flags
|= PACKET_PRIVATE_FLAGS_ENTROPY
;
765 if (header
.is_in_fec_group
== IN_FEC_GROUP
) {
766 private_flags
|= PACKET_PRIVATE_FLAGS_FEC_GROUP
;
768 if (header
.fec_flag
) {
769 private_flags
|= PACKET_PRIVATE_FLAGS_FEC
;
771 if (!writer
->WriteUInt8(private_flags
)) {
775 // The FEC group number is the sequence number of the first fec
776 // protected packet, or 0 if this packet is not protected.
777 if (header
.is_in_fec_group
== IN_FEC_GROUP
) {
778 DCHECK_LE(header
.fec_group
, header
.packet_sequence_number
);
779 DCHECK_LT(header
.packet_sequence_number
- header
.fec_group
, 255u);
780 // Offset from the current packet sequence number to the first fec
782 uint8 first_fec_protected_packet_offset
=
783 static_cast<uint8
>(header
.packet_sequence_number
- header
.fec_group
);
784 if (!writer
->WriteBytes(&first_fec_protected_packet_offset
, 1)) {
792 const QuicTime::Delta
QuicFramer::CalculateTimestampFromWire(
793 uint32 time_delta_us
) {
794 // The new time_delta might have wrapped to the next epoch, or it
795 // might have reverse wrapped to the previous epoch, or it might
796 // remain in the same epoch. Select the time closest to the previous
799 // epoch_delta is the delta between epochs. A delta is 4 bytes of
801 const uint64 epoch_delta
= GG_UINT64_C(1) << 32;
802 uint64 epoch
= last_timestamp_
.ToMicroseconds() & ~(epoch_delta
- 1);
803 // Wrapping is safe here because a wrapped value will not be ClosestTo below.
804 uint64 prev_epoch
= epoch
- epoch_delta
;
805 uint64 next_epoch
= epoch
+ epoch_delta
;
807 uint64 time
= ClosestTo(last_timestamp_
.ToMicroseconds(),
808 epoch
+ time_delta_us
,
809 ClosestTo(last_timestamp_
.ToMicroseconds(),
810 prev_epoch
+ time_delta_us
,
811 next_epoch
+ time_delta_us
));
813 return QuicTime::Delta::FromMicroseconds(time
);
816 QuicPacketSequenceNumber
QuicFramer::CalculatePacketSequenceNumberFromWire(
817 QuicSequenceNumberLength sequence_number_length
,
818 QuicPacketSequenceNumber packet_sequence_number
) const {
819 // The new sequence number might have wrapped to the next epoch, or
820 // it might have reverse wrapped to the previous epoch, or it might
821 // remain in the same epoch. Select the sequence number closest to the
822 // next expected sequence number, the previous sequence number plus 1.
824 // epoch_delta is the delta between epochs the sequence number was serialized
825 // with, so the correct value is likely the same epoch as the last sequence
826 // number or an adjacent epoch.
827 const QuicPacketSequenceNumber epoch_delta
=
828 GG_UINT64_C(1) << (8 * sequence_number_length
);
829 QuicPacketSequenceNumber next_sequence_number
= last_sequence_number_
+ 1;
830 QuicPacketSequenceNumber epoch
= last_sequence_number_
& ~(epoch_delta
- 1);
831 QuicPacketSequenceNumber prev_epoch
= epoch
- epoch_delta
;
832 QuicPacketSequenceNumber next_epoch
= epoch
+ epoch_delta
;
834 return ClosestTo(next_sequence_number
,
835 epoch
+ packet_sequence_number
,
836 ClosestTo(next_sequence_number
,
837 prev_epoch
+ packet_sequence_number
,
838 next_epoch
+ packet_sequence_number
));
841 bool QuicFramer::ProcessPublicHeader(
842 QuicPacketPublicHeader
* public_header
) {
844 if (!reader_
->ReadBytes(&public_flags
, 1)) {
845 set_detailed_error("Unable to read public flags.");
849 public_header
->reset_flag
= (public_flags
& PACKET_PUBLIC_FLAGS_RST
) != 0;
850 public_header
->version_flag
=
851 (public_flags
& PACKET_PUBLIC_FLAGS_VERSION
) != 0;
853 if (validate_flags_
&&
854 !public_header
->version_flag
&& public_flags
> PACKET_PUBLIC_FLAGS_MAX
) {
855 set_detailed_error("Illegal public flags value.");
859 if (public_header
->reset_flag
&& public_header
->version_flag
) {
860 set_detailed_error("Got version flag in reset packet");
864 switch (public_flags
& PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID
) {
865 case PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID
:
866 if (!reader_
->ReadUInt64(&public_header
->connection_id
)) {
867 set_detailed_error("Unable to read ConnectionId.");
870 public_header
->connection_id_length
= PACKET_8BYTE_CONNECTION_ID
;
872 case PACKET_PUBLIC_FLAGS_4BYTE_CONNECTION_ID
:
873 // If the connection_id is truncated, expect to read the last serialized
875 if (!reader_
->ReadBytes(&public_header
->connection_id
,
876 PACKET_4BYTE_CONNECTION_ID
)) {
877 set_detailed_error("Unable to read ConnectionId.");
880 if (last_serialized_connection_id_
&&
881 (public_header
->connection_id
& k4ByteConnectionIdMask
) !=
882 (last_serialized_connection_id_
& k4ByteConnectionIdMask
)) {
883 set_detailed_error("Truncated 4 byte ConnectionId does not match "
884 "previous connection_id.");
887 public_header
->connection_id_length
= PACKET_4BYTE_CONNECTION_ID
;
888 public_header
->connection_id
= last_serialized_connection_id_
;
890 case PACKET_PUBLIC_FLAGS_1BYTE_CONNECTION_ID
:
891 if (!reader_
->ReadBytes(&public_header
->connection_id
,
892 PACKET_1BYTE_CONNECTION_ID
)) {
893 set_detailed_error("Unable to read ConnectionId.");
896 if (last_serialized_connection_id_
&&
897 (public_header
->connection_id
& k1ByteConnectionIdMask
) !=
898 (last_serialized_connection_id_
& k1ByteConnectionIdMask
)) {
899 set_detailed_error("Truncated 1 byte ConnectionId does not match "
900 "previous connection_id.");
903 public_header
->connection_id_length
= PACKET_1BYTE_CONNECTION_ID
;
904 public_header
->connection_id
= last_serialized_connection_id_
;
906 case PACKET_PUBLIC_FLAGS_0BYTE_CONNECTION_ID
:
907 public_header
->connection_id_length
= PACKET_0BYTE_CONNECTION_ID
;
908 public_header
->connection_id
= last_serialized_connection_id_
;
912 public_header
->sequence_number_length
=
913 ReadSequenceNumberLength(
914 public_flags
>> kPublicHeaderSequenceNumberShift
);
916 // Read the version only if the packet is from the client.
917 // version flag from the server means version negotiation packet.
918 if (public_header
->version_flag
&& perspective_
== Perspective::IS_SERVER
) {
920 if (!reader_
->ReadUInt32(&version_tag
)) {
921 set_detailed_error("Unable to read protocol version.");
925 // If the version from the new packet is the same as the version of this
926 // framer, then the public flags should be set to something we understand.
927 // If not, this raises an error.
928 QuicVersion version
= QuicTagToQuicVersion(version_tag
);
929 if (version
== quic_version_
&& public_flags
> PACKET_PUBLIC_FLAGS_MAX
) {
930 set_detailed_error("Illegal public flags value.");
933 public_header
->versions
.push_back(version
);
939 QuicSequenceNumberLength
QuicFramer::GetMinSequenceNumberLength(
940 QuicPacketSequenceNumber sequence_number
) {
941 if (sequence_number
< 1 << (PACKET_1BYTE_SEQUENCE_NUMBER
* 8)) {
942 return PACKET_1BYTE_SEQUENCE_NUMBER
;
943 } else if (sequence_number
< 1 << (PACKET_2BYTE_SEQUENCE_NUMBER
* 8)) {
944 return PACKET_2BYTE_SEQUENCE_NUMBER
;
945 } else if (sequence_number
<
946 GG_UINT64_C(1) << (PACKET_4BYTE_SEQUENCE_NUMBER
* 8)) {
947 return PACKET_4BYTE_SEQUENCE_NUMBER
;
949 return PACKET_6BYTE_SEQUENCE_NUMBER
;
954 uint8
QuicFramer::GetSequenceNumberFlags(
955 QuicSequenceNumberLength sequence_number_length
) {
956 switch (sequence_number_length
) {
957 case PACKET_1BYTE_SEQUENCE_NUMBER
:
958 return PACKET_FLAGS_1BYTE_SEQUENCE
;
959 case PACKET_2BYTE_SEQUENCE_NUMBER
:
960 return PACKET_FLAGS_2BYTE_SEQUENCE
;
961 case PACKET_4BYTE_SEQUENCE_NUMBER
:
962 return PACKET_FLAGS_4BYTE_SEQUENCE
;
963 case PACKET_6BYTE_SEQUENCE_NUMBER
:
964 return PACKET_FLAGS_6BYTE_SEQUENCE
;
966 LOG(DFATAL
) << "Unreachable case statement.";
967 return PACKET_FLAGS_6BYTE_SEQUENCE
;
972 QuicFramer::AckFrameInfo
QuicFramer::GetAckFrameInfo(
973 const QuicAckFrame
& frame
) {
974 AckFrameInfo ack_info
;
975 if (frame
.missing_packets
.empty()) {
978 DCHECK_GE(frame
.largest_observed
, *frame
.missing_packets
.rbegin());
979 size_t cur_range_length
= 0;
980 SequenceNumberSet::const_iterator iter
= frame
.missing_packets
.begin();
981 QuicPacketSequenceNumber last_missing
= *iter
;
983 for (; iter
!= frame
.missing_packets
.end(); ++iter
) {
984 if (cur_range_length
< numeric_limits
<uint8
>::max() &&
985 *iter
== (last_missing
+ 1)) {
988 ack_info
.nack_ranges
[last_missing
- cur_range_length
] =
989 static_cast<uint8
>(cur_range_length
);
990 cur_range_length
= 0;
992 ack_info
.max_delta
= max(ack_info
.max_delta
, *iter
- last_missing
);
993 last_missing
= *iter
;
995 // Include the last nack range.
996 ack_info
.nack_ranges
[last_missing
- cur_range_length
] =
997 static_cast<uint8
>(cur_range_length
);
998 // Include the range to the largest observed.
1000 max(ack_info
.max_delta
, frame
.largest_observed
- last_missing
);
1004 bool QuicFramer::ProcessPacketHeader(QuicPacketHeader
* header
,
1005 const QuicEncryptedPacket
& packet
,
1006 char* decrypted_buffer
,
1007 size_t buffer_length
) {
1008 if (!ProcessPacketSequenceNumber(header
->public_header
.sequence_number_length
,
1009 &header
->packet_sequence_number
)) {
1010 set_detailed_error("Unable to read sequence number.");
1011 return RaiseError(QUIC_INVALID_PACKET_HEADER
);
1014 if (header
->packet_sequence_number
== 0u) {
1015 set_detailed_error("Packet sequence numbers cannot be 0.");
1016 return RaiseError(QUIC_INVALID_PACKET_HEADER
);
1019 if (!visitor_
->OnUnauthenticatedHeader(*header
)) {
1023 if (!DecryptPayload(*header
, packet
, decrypted_buffer
, buffer_length
)) {
1024 set_detailed_error("Unable to decrypt payload.");
1025 return RaiseError(QUIC_DECRYPTION_FAILURE
);
1028 uint8 private_flags
;
1029 if (!reader_
->ReadBytes(&private_flags
, 1)) {
1030 set_detailed_error("Unable to read private flags.");
1031 return RaiseError(QUIC_INVALID_PACKET_HEADER
);
1034 if (private_flags
> PACKET_PRIVATE_FLAGS_MAX
) {
1035 set_detailed_error("Illegal private flags value.");
1036 return RaiseError(QUIC_INVALID_PACKET_HEADER
);
1039 header
->entropy_flag
= (private_flags
& PACKET_PRIVATE_FLAGS_ENTROPY
) != 0;
1040 header
->fec_flag
= (private_flags
& PACKET_PRIVATE_FLAGS_FEC
) != 0;
1042 if ((private_flags
& PACKET_PRIVATE_FLAGS_FEC_GROUP
) != 0) {
1043 header
->is_in_fec_group
= IN_FEC_GROUP
;
1044 uint8 first_fec_protected_packet_offset
;
1045 if (!reader_
->ReadBytes(&first_fec_protected_packet_offset
, 1)) {
1046 set_detailed_error("Unable to read first fec protected packet offset.");
1047 return RaiseError(QUIC_INVALID_PACKET_HEADER
);
1049 if (first_fec_protected_packet_offset
>= header
->packet_sequence_number
) {
1050 set_detailed_error("First fec protected packet offset must be less "
1051 "than the sequence number.");
1052 return RaiseError(QUIC_INVALID_PACKET_HEADER
);
1055 header
->packet_sequence_number
- first_fec_protected_packet_offset
;
1058 header
->entropy_hash
= GetPacketEntropyHash(*header
);
1059 // Set the last sequence number after we have decrypted the packet
1060 // so we are confident is not attacker controlled.
1061 last_sequence_number_
= header
->packet_sequence_number
;
1065 bool QuicFramer::ProcessPacketSequenceNumber(
1066 QuicSequenceNumberLength sequence_number_length
,
1067 QuicPacketSequenceNumber
* sequence_number
) {
1068 QuicPacketSequenceNumber wire_sequence_number
= 0u;
1069 if (!reader_
->ReadBytes(&wire_sequence_number
, sequence_number_length
)) {
1073 // TODO(ianswett): Explore the usefulness of trying multiple sequence numbers
1074 // in case the first guess is incorrect.
1076 CalculatePacketSequenceNumberFromWire(sequence_number_length
,
1077 wire_sequence_number
);
1081 bool QuicFramer::ProcessFrameData(const QuicPacketHeader
& header
) {
1082 if (reader_
->IsDoneReading()) {
1083 set_detailed_error("Packet has no frames.");
1084 return RaiseError(QUIC_MISSING_PAYLOAD
);
1086 while (!reader_
->IsDoneReading()) {
1088 if (!reader_
->ReadBytes(&frame_type
, 1)) {
1089 set_detailed_error("Unable to read frame type.");
1090 return RaiseError(QUIC_INVALID_FRAME_DATA
);
1093 if (frame_type
& kQuicFrameTypeSpecialMask
) {
1095 if (frame_type
& kQuicFrameTypeStreamMask
) {
1096 QuicStreamFrame frame
;
1097 if (!ProcessStreamFrame(frame_type
, &frame
)) {
1098 return RaiseError(QUIC_INVALID_STREAM_DATA
);
1100 if (!visitor_
->OnStreamFrame(frame
)) {
1101 DVLOG(1) << "Visitor asked to stop further processing.";
1102 // Returning true since there was no parsing error.
1109 if (frame_type
& kQuicFrameTypeAckMask
) {
1111 if (!ProcessAckFrame(frame_type
, &frame
)) {
1112 return RaiseError(QUIC_INVALID_ACK_DATA
);
1114 if (!visitor_
->OnAckFrame(frame
)) {
1115 DVLOG(1) << "Visitor asked to stop further processing.";
1116 // Returning true since there was no parsing error.
1122 // This was a special frame type that did not match any
1123 // of the known ones. Error.
1124 set_detailed_error("Illegal frame type.");
1125 DLOG(WARNING
) << "Illegal frame type: "
1126 << static_cast<int>(frame_type
);
1127 return RaiseError(QUIC_INVALID_FRAME_DATA
);
1130 switch (frame_type
) {
1132 // We're done with the packet.
1135 case RST_STREAM_FRAME
: {
1136 QuicRstStreamFrame frame
;
1137 if (!ProcessRstStreamFrame(&frame
)) {
1138 return RaiseError(QUIC_INVALID_RST_STREAM_DATA
);
1140 if (!visitor_
->OnRstStreamFrame(frame
)) {
1141 DVLOG(1) << "Visitor asked to stop further processing.";
1142 // Returning true since there was no parsing error.
1148 case CONNECTION_CLOSE_FRAME
: {
1149 QuicConnectionCloseFrame frame
;
1150 if (!ProcessConnectionCloseFrame(&frame
)) {
1151 return RaiseError(QUIC_INVALID_CONNECTION_CLOSE_DATA
);
1154 if (!visitor_
->OnConnectionCloseFrame(frame
)) {
1155 DVLOG(1) << "Visitor asked to stop further processing.";
1156 // Returning true since there was no parsing error.
1162 case GOAWAY_FRAME
: {
1163 QuicGoAwayFrame goaway_frame
;
1164 if (!ProcessGoAwayFrame(&goaway_frame
)) {
1165 return RaiseError(QUIC_INVALID_GOAWAY_DATA
);
1167 if (!visitor_
->OnGoAwayFrame(goaway_frame
)) {
1168 DVLOG(1) << "Visitor asked to stop further processing.";
1169 // Returning true since there was no parsing error.
1175 case WINDOW_UPDATE_FRAME
: {
1176 QuicWindowUpdateFrame window_update_frame
;
1177 if (!ProcessWindowUpdateFrame(&window_update_frame
)) {
1178 return RaiseError(QUIC_INVALID_WINDOW_UPDATE_DATA
);
1180 if (!visitor_
->OnWindowUpdateFrame(window_update_frame
)) {
1181 DVLOG(1) << "Visitor asked to stop further processing.";
1182 // Returning true since there was no parsing error.
1188 case BLOCKED_FRAME
: {
1189 QuicBlockedFrame blocked_frame
;
1190 if (!ProcessBlockedFrame(&blocked_frame
)) {
1191 return RaiseError(QUIC_INVALID_BLOCKED_DATA
);
1193 if (!visitor_
->OnBlockedFrame(blocked_frame
)) {
1194 DVLOG(1) << "Visitor asked to stop further processing.";
1195 // Returning true since there was no parsing error.
1201 case STOP_WAITING_FRAME
: {
1202 QuicStopWaitingFrame stop_waiting_frame
;
1203 if (!ProcessStopWaitingFrame(header
, &stop_waiting_frame
)) {
1204 return RaiseError(QUIC_INVALID_STOP_WAITING_DATA
);
1206 if (!visitor_
->OnStopWaitingFrame(stop_waiting_frame
)) {
1207 DVLOG(1) << "Visitor asked to stop further processing.";
1208 // Returning true since there was no parsing error.
1214 // Ping has no payload.
1215 QuicPingFrame ping_frame
;
1216 if (!visitor_
->OnPingFrame(ping_frame
)) {
1217 DVLOG(1) << "Visitor asked to stop further processing.";
1218 // Returning true since there was no parsing error.
1225 set_detailed_error("Illegal frame type.");
1226 DLOG(WARNING
) << "Illegal frame type: "
1227 << static_cast<int>(frame_type
);
1228 return RaiseError(QUIC_INVALID_FRAME_DATA
);
1235 bool QuicFramer::ProcessStreamFrame(uint8 frame_type
,
1236 QuicStreamFrame
* frame
) {
1237 uint8 stream_flags
= frame_type
;
1239 stream_flags
&= ~kQuicFrameTypeStreamMask
;
1241 // Read from right to left: StreamID, Offset, Data Length, Fin.
1242 const uint8 stream_id_length
= (stream_flags
& kQuicStreamIDLengthMask
) + 1;
1243 stream_flags
>>= kQuicStreamIdShift
;
1245 uint8 offset_length
= (stream_flags
& kQuicStreamOffsetMask
);
1246 // There is no encoding for 1 byte, only 0 and 2 through 8.
1247 if (offset_length
> 0) {
1250 stream_flags
>>= kQuicStreamOffsetShift
;
1252 bool has_data_length
=
1253 (stream_flags
& kQuicStreamDataLengthMask
) == kQuicStreamDataLengthMask
;
1254 stream_flags
>>= kQuicStreamDataLengthShift
;
1256 frame
->fin
= (stream_flags
& kQuicStreamFinMask
) == kQuicStreamFinShift
;
1258 frame
->stream_id
= 0;
1259 if (!reader_
->ReadBytes(&frame
->stream_id
, stream_id_length
)) {
1260 set_detailed_error("Unable to read stream_id.");
1265 if (!reader_
->ReadBytes(&frame
->offset
, offset_length
)) {
1266 set_detailed_error("Unable to read offset.");
1270 StringPiece frame_data
;
1271 if (has_data_length
) {
1272 if (!reader_
->ReadStringPiece16(&frame_data
)) {
1273 set_detailed_error("Unable to read frame data.");
1277 if (!reader_
->ReadStringPiece(&frame_data
, reader_
->BytesRemaining())) {
1278 set_detailed_error("Unable to read frame data.");
1282 // Point frame to the right data.
1283 frame
->data
.Clear();
1284 if (!frame_data
.empty()) {
1285 frame
->data
.Append(const_cast<char*>(frame_data
.data()), frame_data
.size());
1291 bool QuicFramer::ProcessAckFrame(uint8 frame_type
, QuicAckFrame
* ack_frame
) {
1292 // Determine the three lengths from the frame type: largest observed length,
1293 // missing sequence number length, and missing range length.
1294 const QuicSequenceNumberLength missing_sequence_number_length
=
1295 ReadSequenceNumberLength(frame_type
);
1296 frame_type
>>= kQuicSequenceNumberLengthShift
;
1297 const QuicSequenceNumberLength largest_observed_sequence_number_length
=
1298 ReadSequenceNumberLength(frame_type
);
1299 frame_type
>>= kQuicSequenceNumberLengthShift
;
1300 ack_frame
->is_truncated
= frame_type
& kQuicAckTruncatedMask
;
1301 frame_type
>>= kQuicAckTruncatedShift
;
1302 bool has_nacks
= frame_type
& kQuicHasNacksMask
;
1304 if (!reader_
->ReadBytes(&ack_frame
->entropy_hash
, 1)) {
1305 set_detailed_error("Unable to read entropy hash for received packets.");
1309 if (!reader_
->ReadBytes(&ack_frame
->largest_observed
,
1310 largest_observed_sequence_number_length
)) {
1311 set_detailed_error("Unable to read largest observed.");
1315 uint64 delta_time_largest_observed_us
;
1316 if (!reader_
->ReadUFloat16(&delta_time_largest_observed_us
)) {
1317 set_detailed_error("Unable to read delta time largest observed.");
1321 if (delta_time_largest_observed_us
== kUFloat16MaxValue
) {
1322 ack_frame
->delta_time_largest_observed
= QuicTime::Delta::Infinite();
1324 ack_frame
->delta_time_largest_observed
=
1325 QuicTime::Delta::FromMicroseconds(delta_time_largest_observed_us
);
1328 if (!ProcessTimestampsInAckFrame(ack_frame
)) {
1336 uint8 num_missing_ranges
;
1337 if (!reader_
->ReadBytes(&num_missing_ranges
, 1)) {
1338 set_detailed_error("Unable to read num missing packet ranges.");
1342 QuicPacketSequenceNumber last_sequence_number
= ack_frame
->largest_observed
;
1343 for (size_t i
= 0; i
< num_missing_ranges
; ++i
) {
1344 QuicPacketSequenceNumber missing_delta
= 0;
1345 if (!reader_
->ReadBytes(&missing_delta
, missing_sequence_number_length
)) {
1346 set_detailed_error("Unable to read missing sequence number delta.");
1349 last_sequence_number
-= missing_delta
;
1350 QuicPacketSequenceNumber range_length
= 0;
1351 if (!reader_
->ReadBytes(&range_length
, PACKET_1BYTE_SEQUENCE_NUMBER
)) {
1352 set_detailed_error("Unable to read missing sequence number range.");
1355 for (size_t j
= 0; j
<= range_length
; ++j
) {
1356 ack_frame
->missing_packets
.insert(last_sequence_number
- j
);
1358 // Subtract an extra 1 to ensure ranges are represented efficiently and
1359 // can't overlap by 1 sequence number. This allows a missing_delta of 0
1360 // to represent an adjacent nack range.
1361 last_sequence_number
-= (range_length
+ 1);
1364 // Parse the revived packets list.
1365 uint8 num_revived_packets
;
1366 if (!reader_
->ReadBytes(&num_revived_packets
, 1)) {
1367 set_detailed_error("Unable to read num revived packets.");
1371 for (size_t i
= 0; i
< num_revived_packets
; ++i
) {
1372 QuicPacketSequenceNumber revived_packet
= 0;
1373 if (!reader_
->ReadBytes(&revived_packet
,
1374 largest_observed_sequence_number_length
)) {
1375 set_detailed_error("Unable to read revived packet.");
1379 ack_frame
->revived_packets
.insert(revived_packet
);
1385 bool QuicFramer::ProcessTimestampsInAckFrame(QuicAckFrame
* ack_frame
) {
1386 if (!ack_frame
->is_truncated
) {
1387 uint8 num_received_packets
;
1388 if (!reader_
->ReadBytes(&num_received_packets
, 1)) {
1389 set_detailed_error("Unable to read num received packets.");
1393 if (num_received_packets
> 0) {
1394 uint8 delta_from_largest_observed
;
1395 if (!reader_
->ReadBytes(&delta_from_largest_observed
,
1396 PACKET_1BYTE_SEQUENCE_NUMBER
)) {
1398 "Unable to read sequence delta in received packets.");
1401 QuicPacketSequenceNumber seq_num
= ack_frame
->largest_observed
-
1402 delta_from_largest_observed
;
1404 // Time delta from the framer creation.
1405 uint32 time_delta_us
;
1406 if (!reader_
->ReadBytes(&time_delta_us
, sizeof(time_delta_us
))) {
1407 set_detailed_error("Unable to read time delta in received packets.");
1411 last_timestamp_
= CalculateTimestampFromWire(time_delta_us
);
1413 ack_frame
->received_packet_times
.push_back(
1414 std::make_pair(seq_num
, creation_time_
.Add(last_timestamp_
)));
1416 for (uint8 i
= 1; i
< num_received_packets
; ++i
) {
1417 if (!reader_
->ReadBytes(&delta_from_largest_observed
,
1418 PACKET_1BYTE_SEQUENCE_NUMBER
)) {
1420 "Unable to read sequence delta in received packets.");
1423 seq_num
= ack_frame
->largest_observed
- delta_from_largest_observed
;
1425 // Time delta from the previous timestamp.
1426 uint64 incremental_time_delta_us
;
1427 if (!reader_
->ReadUFloat16(&incremental_time_delta_us
)) {
1429 "Unable to read incremental time delta in received packets.");
1433 last_timestamp_
= last_timestamp_
.Add(
1434 QuicTime::Delta::FromMicroseconds(incremental_time_delta_us
));
1435 ack_frame
->received_packet_times
.push_back(
1436 std::make_pair(seq_num
, creation_time_
.Add(last_timestamp_
)));
1443 bool QuicFramer::ProcessStopWaitingFrame(const QuicPacketHeader
& header
,
1444 QuicStopWaitingFrame
* stop_waiting
) {
1445 if (!reader_
->ReadBytes(&stop_waiting
->entropy_hash
, 1)) {
1446 set_detailed_error("Unable to read entropy hash for sent packets.");
1450 QuicPacketSequenceNumber least_unacked_delta
= 0;
1451 if (!reader_
->ReadBytes(&least_unacked_delta
,
1452 header
.public_header
.sequence_number_length
)) {
1453 set_detailed_error("Unable to read least unacked delta.");
1456 DCHECK_GE(header
.packet_sequence_number
, least_unacked_delta
);
1457 stop_waiting
->least_unacked
=
1458 header
.packet_sequence_number
- least_unacked_delta
;
1463 bool QuicFramer::ProcessRstStreamFrame(QuicRstStreamFrame
* frame
) {
1464 if (!reader_
->ReadUInt32(&frame
->stream_id
)) {
1465 set_detailed_error("Unable to read stream_id.");
1469 if (!reader_
->ReadUInt64(&frame
->byte_offset
)) {
1470 set_detailed_error("Unable to read rst stream sent byte offset.");
1475 if (!reader_
->ReadUInt32(&error_code
)) {
1476 set_detailed_error("Unable to read rst stream error code.");
1480 if (error_code
>= QUIC_STREAM_LAST_ERROR
) {
1481 set_detailed_error("Invalid rst stream error code.");
1485 frame
->error_code
= static_cast<QuicRstStreamErrorCode
>(error_code
);
1486 if (quic_version_
<= QUIC_VERSION_24
) {
1487 StringPiece error_details
;
1488 if (!reader_
->ReadStringPiece16(&error_details
)) {
1489 set_detailed_error("Unable to read rst stream error details.");
1492 frame
->error_details
= error_details
.as_string();
1498 bool QuicFramer::ProcessConnectionCloseFrame(QuicConnectionCloseFrame
* frame
) {
1500 if (!reader_
->ReadUInt32(&error_code
)) {
1501 set_detailed_error("Unable to read connection close error code.");
1505 if (error_code
>= QUIC_LAST_ERROR
) {
1506 set_detailed_error("Invalid error code.");
1510 frame
->error_code
= static_cast<QuicErrorCode
>(error_code
);
1512 StringPiece error_details
;
1513 if (!reader_
->ReadStringPiece16(&error_details
)) {
1514 set_detailed_error("Unable to read connection close error details.");
1517 frame
->error_details
= error_details
.as_string();
1522 bool QuicFramer::ProcessGoAwayFrame(QuicGoAwayFrame
* frame
) {
1524 if (!reader_
->ReadUInt32(&error_code
)) {
1525 set_detailed_error("Unable to read go away error code.");
1528 frame
->error_code
= static_cast<QuicErrorCode
>(error_code
);
1530 if (error_code
>= QUIC_LAST_ERROR
) {
1531 set_detailed_error("Invalid error code.");
1536 if (!reader_
->ReadUInt32(&stream_id
)) {
1537 set_detailed_error("Unable to read last good stream id.");
1540 frame
->last_good_stream_id
= static_cast<QuicStreamId
>(stream_id
);
1542 StringPiece reason_phrase
;
1543 if (!reader_
->ReadStringPiece16(&reason_phrase
)) {
1544 set_detailed_error("Unable to read goaway reason.");
1547 frame
->reason_phrase
= reason_phrase
.as_string();
1552 bool QuicFramer::ProcessWindowUpdateFrame(QuicWindowUpdateFrame
* frame
) {
1553 if (!reader_
->ReadUInt32(&frame
->stream_id
)) {
1554 set_detailed_error("Unable to read stream_id.");
1558 if (!reader_
->ReadUInt64(&frame
->byte_offset
)) {
1559 set_detailed_error("Unable to read window byte_offset.");
1566 bool QuicFramer::ProcessBlockedFrame(QuicBlockedFrame
* frame
) {
1567 if (!reader_
->ReadUInt32(&frame
->stream_id
)) {
1568 set_detailed_error("Unable to read stream_id.");
1576 StringPiece
QuicFramer::GetAssociatedDataFromEncryptedPacket(
1577 const QuicEncryptedPacket
& encrypted
,
1578 QuicConnectionIdLength connection_id_length
,
1579 bool includes_version
,
1580 QuicSequenceNumberLength sequence_number_length
) {
1582 encrypted
.data() + kStartOfHashData
, GetStartOfEncryptedData(
1583 connection_id_length
, includes_version
, sequence_number_length
)
1584 - kStartOfHashData
);
1587 void QuicFramer::SetDecrypter(QuicDecrypter
* decrypter
,
1588 EncryptionLevel level
) {
1589 DCHECK(alternative_decrypter_
.get() == nullptr);
1590 DCHECK_GE(level
, decrypter_level_
);
1591 decrypter_
.reset(decrypter
);
1592 decrypter_level_
= level
;
1595 void QuicFramer::SetAlternativeDecrypter(QuicDecrypter
* decrypter
,
1596 EncryptionLevel level
,
1597 bool latch_once_used
) {
1598 alternative_decrypter_
.reset(decrypter
);
1599 alternative_decrypter_level_
= level
;
1600 alternative_decrypter_latch_
= latch_once_used
;
1603 const QuicDecrypter
* QuicFramer::decrypter() const {
1604 return decrypter_
.get();
1607 const QuicDecrypter
* QuicFramer::alternative_decrypter() const {
1608 return alternative_decrypter_
.get();
1611 void QuicFramer::SetEncrypter(EncryptionLevel level
,
1612 QuicEncrypter
* encrypter
) {
1613 DCHECK_GE(level
, 0);
1614 DCHECK_LT(level
, NUM_ENCRYPTION_LEVELS
);
1615 encrypter_
[level
].reset(encrypter
);
1618 QuicEncryptedPacket
* QuicFramer::EncryptPacket(
1619 EncryptionLevel level
,
1620 QuicPacketSequenceNumber packet_sequence_number
,
1621 const QuicPacket
& packet
) {
1622 DCHECK(encrypter_
[level
].get() != nullptr);
1624 // Allocate a large enough buffer for the header and the encrypted data.
1625 const size_t encrypted_len
=
1626 encrypter_
[level
]->GetCiphertextSize(packet
.Plaintext().length());
1627 StringPiece header_data
= packet
.BeforePlaintext();
1628 const size_t len
= header_data
.length() + encrypted_len
;
1629 // TODO(ianswett): Consider allocating this on the stack in the typical case.
1630 char* buffer
= new char[len
];
1631 // Copy in the header, because the encrypter only populates the encrypted
1632 // plaintext content.
1633 memcpy(buffer
, header_data
.data(), header_data
.length());
1634 // Encrypt the plaintext into the buffer.
1635 size_t output_length
= 0;
1636 if (!encrypter_
[level
]->EncryptPacket(
1637 packet_sequence_number
, packet
.AssociatedData(), packet
.Plaintext(),
1638 buffer
+ header_data
.length(), &output_length
, encrypted_len
)) {
1639 RaiseError(QUIC_ENCRYPTION_FAILURE
);
1643 return new QuicEncryptedPacket(buffer
, header_data
.length() + output_length
,
1647 size_t QuicFramer::GetMaxPlaintextSize(size_t ciphertext_size
) {
1648 // In order to keep the code simple, we don't have the current encryption
1649 // level to hand. Both the NullEncrypter and AES-GCM have a tag length of 12.
1650 size_t min_plaintext_size
= ciphertext_size
;
1652 for (int i
= ENCRYPTION_NONE
; i
< NUM_ENCRYPTION_LEVELS
; i
++) {
1653 if (encrypter_
[i
].get() != nullptr) {
1654 size_t size
= encrypter_
[i
]->GetMaxPlaintextSize(ciphertext_size
);
1655 if (size
< min_plaintext_size
) {
1656 min_plaintext_size
= size
;
1661 return min_plaintext_size
;
1664 bool QuicFramer::DecryptPayload(const QuicPacketHeader
& header
,
1665 const QuicEncryptedPacket
& packet
,
1666 char* decrypted_buffer
,
1667 size_t buffer_length
) {
1668 StringPiece encrypted
= reader_
->ReadRemainingPayload();
1669 DCHECK(decrypter_
.get() != nullptr);
1670 const StringPiece
& associated_data
= GetAssociatedDataFromEncryptedPacket(
1671 packet
, header
.public_header
.connection_id_length
,
1672 header
.public_header
.version_flag
,
1673 header
.public_header
.sequence_number_length
);
1674 size_t decrypted_length
= 0;
1675 bool success
= decrypter_
->DecryptPacket(
1676 header
.packet_sequence_number
, associated_data
, encrypted
,
1677 decrypted_buffer
, &decrypted_length
, buffer_length
);
1679 visitor_
->OnDecryptedPacket(decrypter_level_
);
1680 } else if (alternative_decrypter_
.get() != nullptr) {
1681 success
= alternative_decrypter_
->DecryptPacket(
1682 header
.packet_sequence_number
, associated_data
, encrypted
,
1683 decrypted_buffer
, &decrypted_length
, buffer_length
);
1685 visitor_
->OnDecryptedPacket(alternative_decrypter_level_
);
1686 if (alternative_decrypter_latch_
) {
1687 // Switch to the alternative decrypter and latch so that we cannot
1689 decrypter_
.reset(alternative_decrypter_
.release());
1690 decrypter_level_
= alternative_decrypter_level_
;
1691 alternative_decrypter_level_
= ENCRYPTION_NONE
;
1693 // Switch the alternative decrypter so that we use it first next time.
1694 decrypter_
.swap(alternative_decrypter_
);
1695 EncryptionLevel level
= alternative_decrypter_level_
;
1696 alternative_decrypter_level_
= decrypter_level_
;
1697 decrypter_level_
= level
;
1703 DLOG(WARNING
) << "DecryptPacket failed for sequence_number:"
1704 << header
.packet_sequence_number
;
1708 reader_
.reset(new QuicDataReader(decrypted_buffer
, decrypted_length
));
1712 size_t QuicFramer::GetAckFrameSize(
1713 const QuicAckFrame
& ack
,
1714 QuicSequenceNumberLength sequence_number_length
) {
1715 AckFrameInfo ack_info
= GetAckFrameInfo(ack
);
1716 QuicSequenceNumberLength largest_observed_length
=
1717 GetMinSequenceNumberLength(ack
.largest_observed
);
1718 QuicSequenceNumberLength missing_sequence_number_length
=
1719 GetMinSequenceNumberLength(ack_info
.max_delta
);
1721 size_t ack_size
= GetMinAckFrameSize(sequence_number_length
,
1722 largest_observed_length
);
1723 if (!ack_info
.nack_ranges
.empty()) {
1724 ack_size
+= kNumberOfNackRangesSize
+ kNumberOfRevivedPacketsSize
;
1725 ack_size
+= min(ack_info
.nack_ranges
.size(), kMaxNackRanges
) *
1726 (missing_sequence_number_length
+ PACKET_1BYTE_SEQUENCE_NUMBER
);
1727 ack_size
+= min(ack
.revived_packets
.size(),
1728 kMaxRevivedPackets
) * largest_observed_length
;
1731 // In version 23, if the ack will be truncated due to too many nack ranges,
1732 // then do not include the number of timestamps (1 byte).
1733 if (ack_info
.nack_ranges
.size() <= kMaxNackRanges
) {
1734 // 1 byte for the number of timestamps.
1736 if (ack
.received_packet_times
.size() > 0) {
1737 // 1 byte for sequence number, 4 bytes for timestamp for the first
1741 // 1 byte for sequence number, 2 bytes for timestamp for the other
1743 ack_size
+= 3 * (ack
.received_packet_times
.size() - 1);
1750 size_t QuicFramer::ComputeFrameLength(
1751 const QuicFrame
& frame
,
1752 bool last_frame_in_packet
,
1753 InFecGroup is_in_fec_group
,
1754 QuicSequenceNumberLength sequence_number_length
) {
1755 switch (frame
.type
) {
1757 return GetMinStreamFrameSize(frame
.stream_frame
->stream_id
,
1758 frame
.stream_frame
->offset
,
1759 last_frame_in_packet
,
1761 frame
.stream_frame
->data
.TotalBufferSize();
1763 return GetAckFrameSize(*frame
.ack_frame
, sequence_number_length
);
1765 case STOP_WAITING_FRAME
:
1766 return GetStopWaitingFrameSize(sequence_number_length
);
1768 // Ping has no payload.
1769 return kQuicFrameTypeSize
;
1770 case RST_STREAM_FRAME
:
1771 if (quic_version_
<= QUIC_VERSION_24
) {
1772 return GetMinRstStreamFrameSize() +
1773 frame
.rst_stream_frame
->error_details
.size();
1775 return GetRstStreamFrameSize();
1776 case CONNECTION_CLOSE_FRAME
:
1777 return GetMinConnectionCloseFrameSize() +
1778 frame
.connection_close_frame
->error_details
.size();
1780 return GetMinGoAwayFrameSize() + frame
.goaway_frame
->reason_phrase
.size();
1781 case WINDOW_UPDATE_FRAME
:
1782 return GetWindowUpdateFrameSize();
1784 return GetBlockedFrameSize();
1788 case NUM_FRAME_TYPES
:
1793 // Not reachable, but some Chrome compilers can't figure that out. *sigh*
1798 bool QuicFramer::AppendTypeByte(const QuicFrame
& frame
,
1799 bool no_stream_frame_length
,
1800 QuicDataWriter
* writer
) {
1801 uint8 type_byte
= 0;
1802 switch (frame
.type
) {
1803 case STREAM_FRAME
: {
1804 if (frame
.stream_frame
== nullptr) {
1805 LOG(DFATAL
) << "Failed to append STREAM frame with no stream_frame.";
1808 type_byte
|= frame
.stream_frame
->fin
? kQuicStreamFinMask
: 0;
1811 type_byte
<<= kQuicStreamDataLengthShift
;
1812 type_byte
|= no_stream_frame_length
? 0: kQuicStreamDataLengthMask
;
1815 type_byte
<<= kQuicStreamOffsetShift
;
1816 const size_t offset_len
= GetStreamOffsetSize(frame
.stream_frame
->offset
);
1817 if (offset_len
> 0) {
1818 type_byte
|= offset_len
- 1;
1821 // stream id 2 bits.
1822 type_byte
<<= kQuicStreamIdShift
;
1823 type_byte
|= GetStreamIdSize(frame
.stream_frame
->stream_id
) - 1;
1824 type_byte
|= kQuicFrameTypeStreamMask
; // Set Stream Frame Type to 1.
1830 type_byte
= static_cast<uint8
>(frame
.type
);
1834 return writer
->WriteUInt8(type_byte
);
1838 bool QuicFramer::AppendPacketSequenceNumber(
1839 QuicSequenceNumberLength sequence_number_length
,
1840 QuicPacketSequenceNumber packet_sequence_number
,
1841 QuicDataWriter
* writer
) {
1842 // Ensure the entire sequence number can be written.
1843 if (writer
->capacity() - writer
->length() <
1844 static_cast<size_t>(sequence_number_length
)) {
1847 switch (sequence_number_length
) {
1848 case PACKET_1BYTE_SEQUENCE_NUMBER
:
1849 return writer
->WriteUInt8(
1850 packet_sequence_number
& k1ByteSequenceNumberMask
);
1852 case PACKET_2BYTE_SEQUENCE_NUMBER
:
1853 return writer
->WriteUInt16(
1854 packet_sequence_number
& k2ByteSequenceNumberMask
);
1856 case PACKET_4BYTE_SEQUENCE_NUMBER
:
1857 return writer
->WriteUInt32(
1858 packet_sequence_number
& k4ByteSequenceNumberMask
);
1860 case PACKET_6BYTE_SEQUENCE_NUMBER
:
1861 return writer
->WriteUInt48(
1862 packet_sequence_number
& k6ByteSequenceNumberMask
);
1865 DCHECK(false) << "sequence_number_length: " << sequence_number_length
;
1870 bool QuicFramer::AppendStreamFrame(
1871 const QuicStreamFrame
& frame
,
1872 bool no_stream_frame_length
,
1873 QuicDataWriter
* writer
) {
1874 if (!writer
->WriteBytes(&frame
.stream_id
, GetStreamIdSize(frame
.stream_id
))) {
1875 LOG(DFATAL
) << "Writing stream id size failed.";
1878 if (!writer
->WriteBytes(&frame
.offset
, GetStreamOffsetSize(frame
.offset
))) {
1879 LOG(DFATAL
) << "Writing offset size failed.";
1882 if (!no_stream_frame_length
) {
1883 if ((frame
.data
.TotalBufferSize() > numeric_limits
<uint16
>::max()) ||
1884 !writer
->WriteUInt16(
1885 static_cast<uint16
>(frame
.data
.TotalBufferSize()))) {
1886 LOG(DFATAL
) << "Writing stream frame length failed";
1891 if (!writer
->WriteIOVector(frame
.data
)) {
1892 LOG(DFATAL
) << "Writing frame data failed.";
1898 void QuicFramer::set_version(const QuicVersion version
) {
1899 DCHECK(IsSupportedVersion(version
)) << QuicVersionToString(version
);
1900 quic_version_
= version
;
1903 bool QuicFramer::AppendAckFrameAndTypeByte(
1904 const QuicPacketHeader
& header
,
1905 const QuicAckFrame
& frame
,
1906 QuicDataWriter
* writer
) {
1907 AckFrameInfo ack_info
= GetAckFrameInfo(frame
);
1908 QuicPacketSequenceNumber ack_largest_observed
= frame
.largest_observed
;
1909 QuicSequenceNumberLength largest_observed_length
=
1910 GetMinSequenceNumberLength(ack_largest_observed
);
1911 QuicSequenceNumberLength missing_sequence_number_length
=
1912 GetMinSequenceNumberLength(ack_info
.max_delta
);
1913 // Determine whether we need to truncate ranges.
1914 size_t available_range_bytes
= writer
->capacity() - writer
->length() -
1915 kNumberOfRevivedPacketsSize
- kNumberOfNackRangesSize
-
1916 GetMinAckFrameSize(header
.public_header
.sequence_number_length
,
1917 largest_observed_length
);
1918 size_t max_num_ranges
= available_range_bytes
/
1919 (missing_sequence_number_length
+ PACKET_1BYTE_SEQUENCE_NUMBER
);
1920 max_num_ranges
= min(kMaxNackRanges
, max_num_ranges
);
1921 bool truncated
= ack_info
.nack_ranges
.size() > max_num_ranges
;
1922 DVLOG_IF(1, truncated
) << "Truncating ack from "
1923 << ack_info
.nack_ranges
.size() << " ranges to "
1925 // Write out the type byte by setting the low order bits and doing shifts
1926 // to make room for the next bit flags to be set.
1927 // Whether there are any nacks.
1928 uint8 type_byte
= ack_info
.nack_ranges
.empty() ? 0 : kQuicHasNacksMask
;
1931 type_byte
<<= kQuicAckTruncatedShift
;
1932 type_byte
|= truncated
? kQuicAckTruncatedMask
: 0;
1934 // Largest observed sequence number length.
1935 type_byte
<<= kQuicSequenceNumberLengthShift
;
1936 type_byte
|= GetSequenceNumberFlags(largest_observed_length
);
1938 // Missing sequence number length.
1939 type_byte
<<= kQuicSequenceNumberLengthShift
;
1940 type_byte
|= GetSequenceNumberFlags(missing_sequence_number_length
);
1942 type_byte
|= kQuicFrameTypeAckMask
;
1944 if (!writer
->WriteUInt8(type_byte
)) {
1948 QuicPacketEntropyHash ack_entropy_hash
= frame
.entropy_hash
;
1949 NackRangeMap::reverse_iterator ack_iter
= ack_info
.nack_ranges
.rbegin();
1951 // Skip the nack ranges which the truncated ack won't include and set
1952 // a correct largest observed for the truncated ack.
1953 for (size_t i
= 1; i
< (ack_info
.nack_ranges
.size() - max_num_ranges
);
1957 // If the last range is followed by acks, include them.
1958 // If the last range is followed by another range, specify the end of the
1959 // range as the largest_observed.
1960 ack_largest_observed
= ack_iter
->first
- 1;
1961 // Also update the entropy so it matches the largest observed.
1962 ack_entropy_hash
= entropy_calculator_
->EntropyHash(ack_largest_observed
);
1966 if (!writer
->WriteUInt8(ack_entropy_hash
)) {
1970 if (!AppendPacketSequenceNumber(largest_observed_length
,
1971 ack_largest_observed
, writer
)) {
1975 uint64 delta_time_largest_observed_us
= kUFloat16MaxValue
;
1976 if (!frame
.delta_time_largest_observed
.IsInfinite()) {
1977 DCHECK_LE(0u, frame
.delta_time_largest_observed
.ToMicroseconds());
1978 delta_time_largest_observed_us
=
1979 frame
.delta_time_largest_observed
.ToMicroseconds();
1982 if (!writer
->WriteUFloat16(delta_time_largest_observed_us
)) {
1986 // Timestamp goes at the end of the required fields.
1988 if (!AppendTimestampToAckFrame(frame
, writer
)) {
1993 if (ack_info
.nack_ranges
.empty()) {
1997 const uint8 num_missing_ranges
=
1998 static_cast<uint8
>(min(ack_info
.nack_ranges
.size(), max_num_ranges
));
1999 if (!writer
->WriteBytes(&num_missing_ranges
, 1)) {
2003 int num_ranges_written
= 0;
2004 QuicPacketSequenceNumber last_sequence_written
= ack_largest_observed
;
2005 for (; ack_iter
!= ack_info
.nack_ranges
.rend(); ++ack_iter
) {
2006 // Calculate the delta to the last number in the range.
2007 QuicPacketSequenceNumber missing_delta
=
2008 last_sequence_written
- (ack_iter
->first
+ ack_iter
->second
);
2009 if (!AppendPacketSequenceNumber(missing_sequence_number_length
,
2010 missing_delta
, writer
)) {
2013 if (!AppendPacketSequenceNumber(PACKET_1BYTE_SEQUENCE_NUMBER
,
2014 ack_iter
->second
, writer
)) {
2017 // Subtract 1 so a missing_delta of 0 means an adjacent range.
2018 last_sequence_written
= ack_iter
->first
- 1;
2019 ++num_ranges_written
;
2021 DCHECK_EQ(num_missing_ranges
, num_ranges_written
);
2023 // Append revived packets.
2024 // If not all the revived packets fit, only mention the ones that do.
2025 uint8 num_revived_packets
=
2026 static_cast<uint8
>(min(frame
.revived_packets
.size(), kMaxRevivedPackets
));
2027 num_revived_packets
= static_cast<uint8
>(min(
2028 static_cast<size_t>(num_revived_packets
),
2029 (writer
->capacity() - writer
->length()) / largest_observed_length
));
2030 if (!writer
->WriteBytes(&num_revived_packets
, 1)) {
2034 SequenceNumberSet::const_iterator iter
= frame
.revived_packets
.begin();
2035 for (int i
= 0; i
< num_revived_packets
; ++i
, ++iter
) {
2036 LOG_IF(DFATAL
, !ContainsKey(frame
.missing_packets
, *iter
));
2037 if (!AppendPacketSequenceNumber(largest_observed_length
,
2046 bool QuicFramer::AppendTimestampToAckFrame(const QuicAckFrame
& frame
,
2047 QuicDataWriter
* writer
) {
2048 DCHECK_GE(version(), QUIC_VERSION_23
);
2049 DCHECK_GE(numeric_limits
<uint8
>::max(), frame
.received_packet_times
.size());
2050 // num_received_packets is only 1 byte.
2051 if (frame
.received_packet_times
.size() > numeric_limits
<uint8
>::max()) {
2055 uint8 num_received_packets
= frame
.received_packet_times
.size();
2057 if (!writer
->WriteBytes(&num_received_packets
, 1)) {
2060 if (num_received_packets
== 0) {
2064 PacketTimeList::const_iterator it
= frame
.received_packet_times
.begin();
2065 QuicPacketSequenceNumber sequence_number
= it
->first
;
2066 QuicPacketSequenceNumber delta_from_largest_observed
=
2067 frame
.largest_observed
- sequence_number
;
2069 DCHECK_GE(numeric_limits
<uint8
>::max(), delta_from_largest_observed
);
2070 if (delta_from_largest_observed
> numeric_limits
<uint8
>::max()) {
2074 if (!writer
->WriteUInt8(
2075 delta_from_largest_observed
& k1ByteSequenceNumberMask
)) {
2079 // Use the lowest 4 bytes of the time delta from the creation_time_.
2080 const uint64 time_epoch_delta_us
= GG_UINT64_C(1) << 32;
2081 uint32 time_delta_us
=
2082 static_cast<uint32
>(it
->second
.Subtract(creation_time_
).ToMicroseconds()
2083 & (time_epoch_delta_us
- 1));
2084 if (!writer
->WriteBytes(&time_delta_us
, sizeof(time_delta_us
))) {
2088 QuicTime prev_time
= it
->second
;
2090 for (++it
; it
!= frame
.received_packet_times
.end(); ++it
) {
2091 sequence_number
= it
->first
;
2092 delta_from_largest_observed
= frame
.largest_observed
- sequence_number
;
2094 if (delta_from_largest_observed
> numeric_limits
<uint8
>::max()) {
2098 if (!writer
->WriteUInt8(
2099 delta_from_largest_observed
& k1ByteSequenceNumberMask
)) {
2103 uint64 frame_time_delta_us
=
2104 it
->second
.Subtract(prev_time
).ToMicroseconds();
2105 prev_time
= it
->second
;
2106 if (!writer
->WriteUFloat16(frame_time_delta_us
)) {
2113 bool QuicFramer::AppendStopWaitingFrame(
2114 const QuicPacketHeader
& header
,
2115 const QuicStopWaitingFrame
& frame
,
2116 QuicDataWriter
* writer
) {
2117 DCHECK_GE(header
.packet_sequence_number
, frame
.least_unacked
);
2118 const QuicPacketSequenceNumber least_unacked_delta
=
2119 header
.packet_sequence_number
- frame
.least_unacked
;
2120 const QuicPacketSequenceNumber length_shift
=
2121 header
.public_header
.sequence_number_length
* 8;
2122 if (!writer
->WriteUInt8(frame
.entropy_hash
)) {
2123 LOG(DFATAL
) << " hash failed";
2127 if (least_unacked_delta
>> length_shift
> 0) {
2128 LOG(DFATAL
) << "sequence_number_length "
2129 << header
.public_header
.sequence_number_length
2130 << " is too small for least_unacked_delta: "
2131 << least_unacked_delta
;
2134 if (!AppendPacketSequenceNumber(header
.public_header
.sequence_number_length
,
2135 least_unacked_delta
, writer
)) {
2136 LOG(DFATAL
) << " seq failed: "
2137 << header
.public_header
.sequence_number_length
;
2144 bool QuicFramer::AppendRstStreamFrame(const QuicRstStreamFrame
& frame
,
2145 QuicDataWriter
* writer
) {
2146 if (!writer
->WriteUInt32(frame
.stream_id
)) {
2150 if (!writer
->WriteUInt64(frame
.byte_offset
)) {
2154 uint32 error_code
= static_cast<uint32
>(frame
.error_code
);
2155 if (!writer
->WriteUInt32(error_code
)) {
2159 if (quic_version_
<= QUIC_VERSION_24
) {
2160 if (!writer
->WriteStringPiece16(frame
.error_details
)) {
2167 bool QuicFramer::AppendConnectionCloseFrame(
2168 const QuicConnectionCloseFrame
& frame
,
2169 QuicDataWriter
* writer
) {
2170 uint32 error_code
= static_cast<uint32
>(frame
.error_code
);
2171 if (!writer
->WriteUInt32(error_code
)) {
2174 if (!writer
->WriteStringPiece16(frame
.error_details
)) {
2180 bool QuicFramer::AppendGoAwayFrame(const QuicGoAwayFrame
& frame
,
2181 QuicDataWriter
* writer
) {
2182 uint32 error_code
= static_cast<uint32
>(frame
.error_code
);
2183 if (!writer
->WriteUInt32(error_code
)) {
2186 uint32 stream_id
= static_cast<uint32
>(frame
.last_good_stream_id
);
2187 if (!writer
->WriteUInt32(stream_id
)) {
2190 if (!writer
->WriteStringPiece16(frame
.reason_phrase
)) {
2196 bool QuicFramer::AppendWindowUpdateFrame(const QuicWindowUpdateFrame
& frame
,
2197 QuicDataWriter
* writer
) {
2198 uint32 stream_id
= static_cast<uint32
>(frame
.stream_id
);
2199 if (!writer
->WriteUInt32(stream_id
)) {
2202 if (!writer
->WriteUInt64(frame
.byte_offset
)) {
2208 bool QuicFramer::AppendBlockedFrame(const QuicBlockedFrame
& frame
,
2209 QuicDataWriter
* writer
) {
2210 uint32 stream_id
= static_cast<uint32
>(frame
.stream_id
);
2211 if (!writer
->WriteUInt32(stream_id
)) {
2217 bool QuicFramer::RaiseError(QuicErrorCode error
) {
2218 DVLOG(1) << "Error: " << QuicUtils::ErrorToString(error
)
2219 << " detail: " << detailed_error_
;
2221 visitor_
->OnError(this);
2222 reader_
.reset(nullptr);