1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "net/quic/quic_framer.h"
9 #include "base/basictypes.h"
10 #include "base/logging.h"
11 #include "base/stl_util.h"
12 #include "net/quic/crypto/crypto_framer.h"
13 #include "net/quic/crypto/crypto_handshake_message.h"
14 #include "net/quic/crypto/crypto_protocol.h"
15 #include "net/quic/crypto/quic_decrypter.h"
16 #include "net/quic/crypto/quic_encrypter.h"
17 #include "net/quic/quic_data_reader.h"
18 #include "net/quic/quic_data_writer.h"
19 #include "net/quic/quic_flags.h"
20 #include "net/quic/quic_socket_address_coder.h"
21 #include "net/quic/quic_utils.h"
23 using base::StringPiece
;
27 using std::numeric_limits
;
34 // Mask to select the lowest 48 bits of a sequence number.
35 const QuicPacketSequenceNumber k6ByteSequenceNumberMask
=
36 UINT64_C(0x0000FFFFFFFFFFFF);
37 const QuicPacketSequenceNumber k4ByteSequenceNumberMask
=
38 UINT64_C(0x00000000FFFFFFFF);
39 const QuicPacketSequenceNumber k2ByteSequenceNumberMask
=
40 UINT64_C(0x000000000000FFFF);
41 const QuicPacketSequenceNumber k1ByteSequenceNumberMask
=
42 UINT64_C(0x00000000000000FF);
44 const QuicConnectionId k1ByteConnectionIdMask
= UINT64_C(0x00000000000000FF);
45 const QuicConnectionId k4ByteConnectionIdMask
= UINT64_C(0x00000000FFFFFFFF);
47 // Number of bits the sequence number length bits are shifted from the right
48 // edge of the public header.
49 const uint8 kPublicHeaderSequenceNumberShift
= 4;
51 // New Frame Types, QUIC v. >= 10:
52 // There are two interpretations for the Frame Type byte in the QUIC protocol,
53 // resulting in two Frame Types: Special Frame Types and Regular Frame Types.
55 // Regular Frame Types use the Frame Type byte simply. Currently defined
56 // Regular Frame Types are:
57 // Padding : 0b 00000000 (0x00)
58 // ResetStream : 0b 00000001 (0x01)
59 // ConnectionClose : 0b 00000010 (0x02)
60 // GoAway : 0b 00000011 (0x03)
61 // WindowUpdate : 0b 00000100 (0x04)
62 // Blocked : 0b 00000101 (0x05)
64 // Special Frame Types encode both a Frame Type and corresponding flags
65 // all in the Frame Type byte. Currently defined Special Frame Types are:
66 // Stream : 0b 1xxxxxxx
69 // Semantics of the flag bits above (the x bits) depends on the frame type.
71 // Masks to determine if the frame type is a special use
72 // and for specific special frame types.
73 const uint8 kQuicFrameTypeSpecialMask
= 0xE0; // 0b 11100000
74 const uint8 kQuicFrameTypeStreamMask
= 0x80;
75 const uint8 kQuicFrameTypeAckMask
= 0x40;
77 // Stream frame relative shifts and masks for interpreting the stream flags.
78 // StreamID may be 1, 2, 3, or 4 bytes.
79 const uint8 kQuicStreamIdShift
= 2;
80 const uint8 kQuicStreamIDLengthMask
= 0x03;
82 // Offset may be 0, 2, 3, 4, 5, 6, 7, 8 bytes.
83 const uint8 kQuicStreamOffsetShift
= 3;
84 const uint8 kQuicStreamOffsetMask
= 0x07;
86 // Data length may be 0 or 2 bytes.
87 const uint8 kQuicStreamDataLengthShift
= 1;
88 const uint8 kQuicStreamDataLengthMask
= 0x01;
90 // Fin bit may be set or not.
91 const uint8 kQuicStreamFinShift
= 1;
92 const uint8 kQuicStreamFinMask
= 0x01;
94 // Sequence number size shift used in AckFrames.
95 const uint8 kQuicSequenceNumberLengthShift
= 2;
97 // Acks may be truncated.
98 const uint8 kQuicAckTruncatedShift
= 1;
99 const uint8 kQuicAckTruncatedMask
= 0x01;
101 // Acks may not have any nacks.
102 const uint8 kQuicHasNacksMask
= 0x01;
104 // Returns the absolute value of the difference between |a| and |b|.
105 QuicPacketSequenceNumber
Delta(QuicPacketSequenceNumber a
,
106 QuicPacketSequenceNumber b
) {
107 // Since these are unsigned numbers, we can't just return abs(a - b)
114 QuicPacketSequenceNumber
ClosestTo(QuicPacketSequenceNumber target
,
115 QuicPacketSequenceNumber a
,
116 QuicPacketSequenceNumber b
) {
117 return (Delta(target
, a
) < Delta(target
, b
)) ? a
: b
;
120 QuicSequenceNumberLength
ReadSequenceNumberLength(uint8 flags
) {
121 switch (flags
& PACKET_FLAGS_6BYTE_SEQUENCE
) {
122 case PACKET_FLAGS_6BYTE_SEQUENCE
:
123 return PACKET_6BYTE_SEQUENCE_NUMBER
;
124 case PACKET_FLAGS_4BYTE_SEQUENCE
:
125 return PACKET_4BYTE_SEQUENCE_NUMBER
;
126 case PACKET_FLAGS_2BYTE_SEQUENCE
:
127 return PACKET_2BYTE_SEQUENCE_NUMBER
;
128 case PACKET_FLAGS_1BYTE_SEQUENCE
:
129 return PACKET_1BYTE_SEQUENCE_NUMBER
;
131 LOG(DFATAL
) << "Unreachable case statement.";
132 return PACKET_6BYTE_SEQUENCE_NUMBER
;
138 QuicFramer::QuicFramer(const QuicVersionVector
& supported_versions
,
139 QuicTime creation_time
,
140 Perspective perspective
)
142 entropy_calculator_(nullptr),
143 error_(QUIC_NO_ERROR
),
144 last_sequence_number_(0),
145 last_serialized_connection_id_(0),
146 supported_versions_(supported_versions
),
147 decrypter_level_(ENCRYPTION_NONE
),
148 alternative_decrypter_level_(ENCRYPTION_NONE
),
149 alternative_decrypter_latch_(false),
150 perspective_(perspective
),
151 validate_flags_(true),
152 creation_time_(creation_time
),
153 last_timestamp_(QuicTime::Delta::Zero()) {
154 DCHECK(!supported_versions
.empty());
155 quic_version_
= supported_versions_
[0];
156 decrypter_
.reset(QuicDecrypter::Create(kNULL
));
157 encrypter_
[ENCRYPTION_NONE
].reset(QuicEncrypter::Create(kNULL
));
160 QuicFramer::~QuicFramer() {}
163 size_t QuicFramer::GetMinStreamFrameSize(QuicStreamId stream_id
,
164 QuicStreamOffset offset
,
165 bool last_frame_in_packet
,
166 InFecGroup is_in_fec_group
) {
167 bool no_stream_frame_length
= last_frame_in_packet
&&
168 is_in_fec_group
== NOT_IN_FEC_GROUP
;
169 return kQuicFrameTypeSize
+ GetStreamIdSize(stream_id
) +
170 GetStreamOffsetSize(offset
) +
171 (no_stream_frame_length
? 0 : kQuicStreamPayloadLengthSize
);
175 size_t QuicFramer::GetMinAckFrameSize(
176 QuicSequenceNumberLength largest_observed_length
) {
177 return kQuicFrameTypeSize
+ kQuicEntropyHashSize
+
178 largest_observed_length
+ kQuicDeltaTimeLargestObservedSize
;
182 size_t QuicFramer::GetStopWaitingFrameSize(
183 QuicSequenceNumberLength sequence_number_length
) {
184 return kQuicFrameTypeSize
+ kQuicEntropyHashSize
+
185 sequence_number_length
;
189 size_t QuicFramer::GetMinRstStreamFrameSize() {
190 return kQuicFrameTypeSize
+ kQuicMaxStreamIdSize
+
191 kQuicMaxStreamOffsetSize
+ kQuicErrorCodeSize
+
192 kQuicErrorDetailsLengthSize
;
196 size_t QuicFramer::GetRstStreamFrameSize() {
197 return kQuicFrameTypeSize
+ kQuicMaxStreamIdSize
+ kQuicMaxStreamOffsetSize
+
202 size_t QuicFramer::GetMinConnectionCloseFrameSize() {
203 return kQuicFrameTypeSize
+ kQuicErrorCodeSize
+ kQuicErrorDetailsLengthSize
;
207 size_t QuicFramer::GetMinGoAwayFrameSize() {
208 return kQuicFrameTypeSize
+ kQuicErrorCodeSize
+ kQuicErrorDetailsLengthSize
+
209 kQuicMaxStreamIdSize
;
213 size_t QuicFramer::GetWindowUpdateFrameSize() {
214 return kQuicFrameTypeSize
+ kQuicMaxStreamIdSize
+ kQuicMaxStreamOffsetSize
;
218 size_t QuicFramer::GetBlockedFrameSize() {
219 return kQuicFrameTypeSize
+ kQuicMaxStreamIdSize
;
223 size_t QuicFramer::GetStreamIdSize(QuicStreamId stream_id
) {
224 // Sizes are 1 through 4 bytes.
225 for (int i
= 1; i
<= 4; ++i
) {
227 if (stream_id
== 0) {
231 LOG(DFATAL
) << "Failed to determine StreamIDSize.";
236 size_t QuicFramer::GetStreamOffsetSize(QuicStreamOffset offset
) {
237 // 0 is a special case.
241 // 2 through 8 are the remaining sizes.
243 for (int i
= 2; i
<= 8; ++i
) {
249 LOG(DFATAL
) << "Failed to determine StreamOffsetSize.";
254 size_t QuicFramer::GetVersionNegotiationPacketSize(size_t number_versions
) {
255 return kPublicFlagsSize
+ PACKET_8BYTE_CONNECTION_ID
+
256 number_versions
* kQuicVersionSize
;
259 bool QuicFramer::IsSupportedVersion(const QuicVersion version
) const {
260 for (size_t i
= 0; i
< supported_versions_
.size(); ++i
) {
261 if (version
== supported_versions_
[i
]) {
268 size_t QuicFramer::GetSerializedFrameLength(
269 const QuicFrame
& frame
,
273 InFecGroup is_in_fec_group
,
274 QuicSequenceNumberLength sequence_number_length
) {
275 // Prevent a rare crash reported in b/19458523.
276 if (frame
.stream_frame
== nullptr) {
277 LOG(DFATAL
) << "Cannot compute the length of a null frame. "
278 << "type:" << frame
.type
<< "free_bytes:" << free_bytes
279 << " first_frame:" << first_frame
280 << " last_frame:" << last_frame
281 << " is_in_fec:" << is_in_fec_group
282 << " seq num length:" << sequence_number_length
;
283 set_error(QUIC_INTERNAL_ERROR
);
284 visitor_
->OnError(this);
287 if (frame
.type
== PADDING_FRAME
) {
288 // PADDING implies end of packet.
292 ComputeFrameLength(frame
, last_frame
, is_in_fec_group
,
293 sequence_number_length
);
294 if (frame_len
<= free_bytes
) {
295 // Frame fits within packet. Note that acks may be truncated.
298 // Only truncate the first frame in a packet, so if subsequent ones go
299 // over, stop including more frames.
304 frame
.type
== ACK_FRAME
&&
305 free_bytes
>= GetMinAckFrameSize(PACKET_6BYTE_SEQUENCE_NUMBER
);
307 // Truncate the frame so the packet will not exceed kMaxPacketSize.
308 // Note that we may not use every byte of the writer in this case.
309 DVLOG(1) << "Truncating large frame, free bytes: " << free_bytes
;
312 if (!FLAGS_quic_allow_oversized_packets_for_test
) {
315 LOG(DFATAL
) << "Packet size too small to fit frame.";
319 QuicFramer::AckFrameInfo::AckFrameInfo() : max_delta(0) {}
321 QuicFramer::AckFrameInfo::~AckFrameInfo() {}
324 QuicPacketEntropyHash
QuicFramer::GetPacketEntropyHash(
325 const QuicPacketHeader
& header
) {
326 return header
.entropy_flag
<< (header
.packet_sequence_number
% 8);
329 QuicPacket
* QuicFramer::BuildDataPacket(const QuicPacketHeader
& header
,
330 const QuicFrames
& frames
,
332 size_t packet_length
) {
333 QuicDataWriter
writer(packet_length
, buffer
);
334 if (!AppendPacketHeader(header
, &writer
)) {
335 LOG(DFATAL
) << "AppendPacketHeader failed";
340 for (const QuicFrame
& frame
: frames
) {
341 // Determine if we should write stream frame length in header.
342 const bool no_stream_frame_length
=
343 (header
.is_in_fec_group
== NOT_IN_FEC_GROUP
) &&
344 (i
== frames
.size() - 1);
345 if (!AppendTypeByte(frame
, no_stream_frame_length
, &writer
)) {
346 LOG(DFATAL
) << "AppendTypeByte failed";
350 switch (frame
.type
) {
352 writer
.WritePadding();
355 if (!AppendStreamFrame(
356 *frame
.stream_frame
, no_stream_frame_length
, &writer
)) {
357 LOG(DFATAL
) << "AppendStreamFrame failed";
362 if (!AppendAckFrameAndTypeByte(
363 header
, *frame
.ack_frame
, &writer
)) {
364 LOG(DFATAL
) << "AppendAckFrameAndTypeByte failed";
368 case STOP_WAITING_FRAME
:
369 if (!AppendStopWaitingFrame(
370 header
, *frame
.stop_waiting_frame
, &writer
)) {
371 LOG(DFATAL
) << "AppendStopWaitingFrame failed";
375 case MTU_DISCOVERY_FRAME
:
376 // MTU discovery frames are serialized as ping frames.
378 // Ping has no payload.
380 case RST_STREAM_FRAME
:
381 if (!AppendRstStreamFrame(*frame
.rst_stream_frame
, &writer
)) {
382 LOG(DFATAL
) << "AppendRstStreamFrame failed";
386 case CONNECTION_CLOSE_FRAME
:
387 if (!AppendConnectionCloseFrame(
388 *frame
.connection_close_frame
, &writer
)) {
389 LOG(DFATAL
) << "AppendConnectionCloseFrame failed";
394 if (!AppendGoAwayFrame(*frame
.goaway_frame
, &writer
)) {
395 LOG(DFATAL
) << "AppendGoAwayFrame failed";
399 case WINDOW_UPDATE_FRAME
:
400 if (!AppendWindowUpdateFrame(*frame
.window_update_frame
, &writer
)) {
401 LOG(DFATAL
) << "AppendWindowUpdateFrame failed";
406 if (!AppendBlockedFrame(*frame
.blocked_frame
, &writer
)) {
407 LOG(DFATAL
) << "AppendBlockedFrame failed";
412 RaiseError(QUIC_INVALID_FRAME_DATA
);
413 LOG(DFATAL
) << "QUIC_INVALID_FRAME_DATA";
420 new QuicPacket(writer
.data(), writer
.length(), false,
421 header
.public_header
.connection_id_length
,
422 header
.public_header
.version_flag
,
423 header
.public_header
.sequence_number_length
);
428 QuicPacket
* QuicFramer::BuildFecPacket(const QuicPacketHeader
& header
,
429 const QuicFecData
& fec
) {
430 DCHECK_EQ(IN_FEC_GROUP
, header
.is_in_fec_group
);
431 DCHECK_NE(0u, header
.fec_group
);
432 size_t len
= GetPacketHeaderSize(header
);
433 len
+= fec
.redundancy
.length();
435 scoped_ptr
<char[]> buffer(new char[len
]);
436 QuicDataWriter
writer(len
, buffer
.get());
437 if (!AppendPacketHeader(header
, &writer
)) {
438 LOG(DFATAL
) << "AppendPacketHeader failed";
442 if (!writer
.WriteBytes(fec
.redundancy
.data(), fec
.redundancy
.length())) {
443 LOG(DFATAL
) << "Failed to add FEC";
447 return new QuicPacket(buffer
.release(), len
, true,
448 header
.public_header
.connection_id_length
,
449 header
.public_header
.version_flag
,
450 header
.public_header
.sequence_number_length
);
454 QuicEncryptedPacket
* QuicFramer::BuildPublicResetPacket(
455 const QuicPublicResetPacket
& packet
) {
456 DCHECK(packet
.public_header
.reset_flag
);
458 CryptoHandshakeMessage reset
;
459 reset
.set_tag(kPRST
);
460 reset
.SetValue(kRNON
, packet
.nonce_proof
);
461 reset
.SetValue(kRSEQ
, packet
.rejected_sequence_number
);
462 if (!packet
.client_address
.address().empty()) {
463 // packet.client_address is non-empty.
464 QuicSocketAddressCoder
address_coder(packet
.client_address
);
465 string serialized_address
= address_coder
.Encode();
466 if (serialized_address
.empty()) {
469 reset
.SetStringPiece(kCADR
, serialized_address
);
471 const QuicData
& reset_serialized
= reset
.GetSerialized();
474 kPublicFlagsSize
+ PACKET_8BYTE_CONNECTION_ID
+ reset_serialized
.length();
475 scoped_ptr
<char[]> buffer(new char[len
]);
476 QuicDataWriter
writer(len
, buffer
.get());
478 uint8 flags
= static_cast<uint8
>(PACKET_PUBLIC_FLAGS_RST
|
479 PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID
);
480 if (!writer
.WriteUInt8(flags
)) {
484 if (!writer
.WriteUInt64(packet
.public_header
.connection_id
)) {
488 if (!writer
.WriteBytes(reset_serialized
.data(), reset_serialized
.length())) {
492 return new QuicEncryptedPacket(buffer
.release(), len
, true);
495 QuicEncryptedPacket
* QuicFramer::BuildVersionNegotiationPacket(
496 const QuicPacketPublicHeader
& header
,
497 const QuicVersionVector
& supported_versions
) {
498 DCHECK(header
.version_flag
);
499 size_t len
= GetVersionNegotiationPacketSize(supported_versions
.size());
500 scoped_ptr
<char[]> buffer(new char[len
]);
501 QuicDataWriter
writer(len
, buffer
.get());
503 uint8 flags
= static_cast<uint8
>(PACKET_PUBLIC_FLAGS_VERSION
|
504 PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID
);
505 if (!writer
.WriteUInt8(flags
)) {
509 if (!writer
.WriteUInt64(header
.connection_id
)) {
513 for (size_t i
= 0; i
< supported_versions
.size(); ++i
) {
514 if (!writer
.WriteUInt32(QuicVersionToQuicTag(supported_versions
[i
]))) {
519 return new QuicEncryptedPacket(buffer
.release(), len
, true);
522 bool QuicFramer::ProcessPacket(const QuicEncryptedPacket
& packet
) {
523 DCHECK(!reader_
.get());
524 reader_
.reset(new QuicDataReader(packet
.data(), packet
.length()));
526 visitor_
->OnPacket();
528 // First parse the public header.
529 QuicPacketPublicHeader public_header
;
530 if (!ProcessPublicHeader(&public_header
)) {
531 DLOG(WARNING
) << "Unable to process public header.";
532 DCHECK_NE("", detailed_error_
);
533 return RaiseError(QUIC_INVALID_PACKET_HEADER
);
536 if (!visitor_
->OnUnauthenticatedPublicHeader(public_header
)) {
537 // The visitor suppresses further processing of the packet.
538 reader_
.reset(nullptr);
542 if (perspective_
== Perspective::IS_SERVER
&& public_header
.version_flag
&&
543 public_header
.versions
[0] != quic_version_
) {
544 if (!visitor_
->OnProtocolVersionMismatch(public_header
.versions
[0])) {
545 reader_
.reset(nullptr);
551 if (perspective_
== Perspective::IS_CLIENT
&& public_header
.version_flag
) {
552 rv
= ProcessVersionNegotiationPacket(&public_header
);
553 } else if (public_header
.reset_flag
) {
554 rv
= ProcessPublicResetPacket(public_header
);
555 } else if (packet
.length() <= kMaxPacketSize
) {
556 char buffer
[kMaxPacketSize
];
557 rv
= ProcessDataPacket(public_header
, packet
, buffer
, kMaxPacketSize
);
559 scoped_ptr
<char[]> large_buffer(new char[packet
.length()]);
560 rv
= ProcessDataPacket(public_header
, packet
, large_buffer
.get(),
562 LOG_IF(DFATAL
, rv
) << "QUIC should never successfully process packets "
563 << "larger than kMaxPacketSize. packet size:"
567 reader_
.reset(nullptr);
571 bool QuicFramer::ProcessVersionNegotiationPacket(
572 QuicPacketPublicHeader
* public_header
) {
573 DCHECK_EQ(Perspective::IS_CLIENT
, perspective_
);
574 // Try reading at least once to raise error if the packet is invalid.
577 if (!reader_
->ReadBytes(&version
, kQuicVersionSize
)) {
578 set_detailed_error("Unable to read supported version in negotiation.");
579 return RaiseError(QUIC_INVALID_VERSION_NEGOTIATION_PACKET
);
581 public_header
->versions
.push_back(QuicTagToQuicVersion(version
));
582 } while (!reader_
->IsDoneReading());
584 visitor_
->OnVersionNegotiationPacket(*public_header
);
588 bool QuicFramer::ProcessDataPacket(const QuicPacketPublicHeader
& public_header
,
589 const QuicEncryptedPacket
& packet
,
590 char* decrypted_buffer
,
591 size_t buffer_length
) {
592 QuicPacketHeader
header(public_header
);
593 if (!ProcessPacketHeader(&header
, packet
, decrypted_buffer
, buffer_length
)) {
594 DLOG(WARNING
) << "Unable to process packet header. Stopping parsing.";
598 if (!visitor_
->OnPacketHeader(header
)) {
599 // The visitor suppresses further processing of the packet.
603 if (packet
.length() > kMaxPacketSize
) {
604 DLOG(WARNING
) << "Packet too large: " << packet
.length();
605 return RaiseError(QUIC_PACKET_TOO_LARGE
);
608 // Handle the payload.
609 if (!header
.fec_flag
) {
610 if (header
.is_in_fec_group
== IN_FEC_GROUP
) {
611 StringPiece payload
= reader_
->PeekRemainingPayload();
612 visitor_
->OnFecProtectedPayload(payload
);
614 if (!ProcessFrameData(header
)) {
615 DCHECK_NE(QUIC_NO_ERROR
, error_
); // ProcessFrameData sets the error.
616 DLOG(WARNING
) << "Unable to process frame data.";
620 QuicFecData fec_data
;
621 fec_data
.fec_group
= header
.fec_group
;
622 fec_data
.redundancy
= reader_
->ReadRemainingPayload();
623 visitor_
->OnFecData(fec_data
);
626 visitor_
->OnPacketComplete();
630 bool QuicFramer::ProcessPublicResetPacket(
631 const QuicPacketPublicHeader
& public_header
) {
632 QuicPublicResetPacket
packet(public_header
);
634 scoped_ptr
<CryptoHandshakeMessage
> reset(
635 CryptoFramer::ParseMessage(reader_
->ReadRemainingPayload()));
637 set_detailed_error("Unable to read reset message.");
638 return RaiseError(QUIC_INVALID_PUBLIC_RST_PACKET
);
640 if (reset
->tag() != kPRST
) {
641 set_detailed_error("Incorrect message tag.");
642 return RaiseError(QUIC_INVALID_PUBLIC_RST_PACKET
);
645 if (reset
->GetUint64(kRNON
, &packet
.nonce_proof
) != QUIC_NO_ERROR
) {
646 set_detailed_error("Unable to read nonce proof.");
647 return RaiseError(QUIC_INVALID_PUBLIC_RST_PACKET
);
649 // TODO(satyamshekhar): validate nonce to protect against DoS.
651 if (reset
->GetUint64(kRSEQ
, &packet
.rejected_sequence_number
) !=
653 set_detailed_error("Unable to read rejected sequence number.");
654 return RaiseError(QUIC_INVALID_PUBLIC_RST_PACKET
);
658 if (reset
->GetStringPiece(kCADR
, &address
)) {
659 QuicSocketAddressCoder address_coder
;
660 if (address_coder
.Decode(address
.data(), address
.length())) {
661 packet
.client_address
= IPEndPoint(address_coder
.ip(),
662 address_coder
.port());
666 visitor_
->OnPublicResetPacket(packet
);
670 bool QuicFramer::ProcessRevivedPacket(QuicPacketHeader
* header
,
671 StringPiece payload
) {
672 DCHECK(!reader_
.get());
674 visitor_
->OnRevivedPacket();
676 header
->entropy_hash
= GetPacketEntropyHash(*header
);
678 if (!visitor_
->OnPacketHeader(*header
)) {
682 if (payload
.length() > kMaxPacketSize
) {
683 set_detailed_error("Revived packet too large.");
684 return RaiseError(QUIC_PACKET_TOO_LARGE
);
687 reader_
.reset(new QuicDataReader(payload
.data(), payload
.length()));
688 if (!ProcessFrameData(*header
)) {
689 DCHECK_NE(QUIC_NO_ERROR
, error_
); // ProcessFrameData sets the error.
690 DLOG(WARNING
) << "Unable to process frame data.";
694 visitor_
->OnPacketComplete();
695 reader_
.reset(nullptr);
699 bool QuicFramer::AppendPacketHeader(const QuicPacketHeader
& header
,
700 QuicDataWriter
* writer
) {
701 DVLOG(1) << "Appending header: " << header
;
702 DCHECK(header
.fec_group
> 0 || header
.is_in_fec_group
== NOT_IN_FEC_GROUP
);
703 uint8 public_flags
= 0;
704 if (header
.public_header
.reset_flag
) {
705 public_flags
|= PACKET_PUBLIC_FLAGS_RST
;
707 if (header
.public_header
.version_flag
) {
708 public_flags
|= PACKET_PUBLIC_FLAGS_VERSION
;
712 GetSequenceNumberFlags(header
.public_header
.sequence_number_length
)
713 << kPublicHeaderSequenceNumberShift
;
715 switch (header
.public_header
.connection_id_length
) {
716 case PACKET_0BYTE_CONNECTION_ID
:
717 if (!writer
->WriteUInt8(
718 public_flags
| PACKET_PUBLIC_FLAGS_0BYTE_CONNECTION_ID
)) {
722 case PACKET_1BYTE_CONNECTION_ID
:
723 if (!writer
->WriteUInt8(
724 public_flags
| PACKET_PUBLIC_FLAGS_1BYTE_CONNECTION_ID
)) {
727 if (!writer
->WriteUInt8(
728 header
.public_header
.connection_id
& k1ByteConnectionIdMask
)) {
732 case PACKET_4BYTE_CONNECTION_ID
:
733 if (!writer
->WriteUInt8(
734 public_flags
| PACKET_PUBLIC_FLAGS_4BYTE_CONNECTION_ID
)) {
737 if (!writer
->WriteUInt32(
738 header
.public_header
.connection_id
& k4ByteConnectionIdMask
)) {
742 case PACKET_8BYTE_CONNECTION_ID
:
743 if (!writer
->WriteUInt8(
744 public_flags
| PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID
)) {
747 if (!writer
->WriteUInt64(header
.public_header
.connection_id
)) {
752 last_serialized_connection_id_
= header
.public_header
.connection_id
;
754 if (header
.public_header
.version_flag
) {
755 DCHECK_EQ(Perspective::IS_CLIENT
, perspective_
);
756 QuicTag tag
= QuicVersionToQuicTag(quic_version_
);
757 writer
->WriteUInt32(tag
);
758 DVLOG(1) << "version = " << quic_version_
<< ", tag = '"
759 << QuicUtils::TagToString(tag
) << "'";
762 if (!AppendPacketSequenceNumber(header
.public_header
.sequence_number_length
,
763 header
.packet_sequence_number
, writer
)) {
767 uint8 private_flags
= 0;
768 if (header
.entropy_flag
) {
769 private_flags
|= PACKET_PRIVATE_FLAGS_ENTROPY
;
771 if (header
.is_in_fec_group
== IN_FEC_GROUP
) {
772 private_flags
|= PACKET_PRIVATE_FLAGS_FEC_GROUP
;
774 if (header
.fec_flag
) {
775 private_flags
|= PACKET_PRIVATE_FLAGS_FEC
;
777 if (!writer
->WriteUInt8(private_flags
)) {
781 // The FEC group number is the sequence number of the first fec
782 // protected packet, or 0 if this packet is not protected.
783 if (header
.is_in_fec_group
== IN_FEC_GROUP
) {
784 DCHECK_LE(header
.fec_group
, header
.packet_sequence_number
);
785 DCHECK_LT(header
.packet_sequence_number
- header
.fec_group
, 255u);
786 // Offset from the current packet sequence number to the first fec
788 uint8 first_fec_protected_packet_offset
=
789 static_cast<uint8
>(header
.packet_sequence_number
- header
.fec_group
);
790 if (!writer
->WriteBytes(&first_fec_protected_packet_offset
, 1)) {
798 const QuicTime::Delta
QuicFramer::CalculateTimestampFromWire(
799 uint32 time_delta_us
) {
800 // The new time_delta might have wrapped to the next epoch, or it
801 // might have reverse wrapped to the previous epoch, or it might
802 // remain in the same epoch. Select the time closest to the previous
805 // epoch_delta is the delta between epochs. A delta is 4 bytes of
807 const uint64 epoch_delta
= UINT64_C(1) << 32;
808 uint64 epoch
= last_timestamp_
.ToMicroseconds() & ~(epoch_delta
- 1);
809 // Wrapping is safe here because a wrapped value will not be ClosestTo below.
810 uint64 prev_epoch
= epoch
- epoch_delta
;
811 uint64 next_epoch
= epoch
+ epoch_delta
;
813 uint64 time
= ClosestTo(last_timestamp_
.ToMicroseconds(),
814 epoch
+ time_delta_us
,
815 ClosestTo(last_timestamp_
.ToMicroseconds(),
816 prev_epoch
+ time_delta_us
,
817 next_epoch
+ time_delta_us
));
819 return QuicTime::Delta::FromMicroseconds(time
);
822 QuicPacketSequenceNumber
QuicFramer::CalculatePacketSequenceNumberFromWire(
823 QuicSequenceNumberLength sequence_number_length
,
824 QuicPacketSequenceNumber packet_sequence_number
) const {
825 // The new sequence number might have wrapped to the next epoch, or
826 // it might have reverse wrapped to the previous epoch, or it might
827 // remain in the same epoch. Select the sequence number closest to the
828 // next expected sequence number, the previous sequence number plus 1.
830 // epoch_delta is the delta between epochs the sequence number was serialized
831 // with, so the correct value is likely the same epoch as the last sequence
832 // number or an adjacent epoch.
833 const QuicPacketSequenceNumber epoch_delta
=
834 UINT64_C(1) << (8 * sequence_number_length
);
835 QuicPacketSequenceNumber next_sequence_number
= last_sequence_number_
+ 1;
836 QuicPacketSequenceNumber epoch
= last_sequence_number_
& ~(epoch_delta
- 1);
837 QuicPacketSequenceNumber prev_epoch
= epoch
- epoch_delta
;
838 QuicPacketSequenceNumber next_epoch
= epoch
+ epoch_delta
;
840 return ClosestTo(next_sequence_number
,
841 epoch
+ packet_sequence_number
,
842 ClosestTo(next_sequence_number
,
843 prev_epoch
+ packet_sequence_number
,
844 next_epoch
+ packet_sequence_number
));
847 bool QuicFramer::ProcessPublicHeader(
848 QuicPacketPublicHeader
* public_header
) {
850 if (!reader_
->ReadBytes(&public_flags
, 1)) {
851 set_detailed_error("Unable to read public flags.");
855 public_header
->reset_flag
= (public_flags
& PACKET_PUBLIC_FLAGS_RST
) != 0;
856 public_header
->version_flag
=
857 (public_flags
& PACKET_PUBLIC_FLAGS_VERSION
) != 0;
859 if (validate_flags_
&&
860 !public_header
->version_flag
&& public_flags
> PACKET_PUBLIC_FLAGS_MAX
) {
861 set_detailed_error("Illegal public flags value.");
865 if (public_header
->reset_flag
&& public_header
->version_flag
) {
866 set_detailed_error("Got version flag in reset packet");
870 switch (public_flags
& PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID
) {
871 case PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID
:
872 if (!reader_
->ReadUInt64(&public_header
->connection_id
)) {
873 set_detailed_error("Unable to read ConnectionId.");
876 public_header
->connection_id_length
= PACKET_8BYTE_CONNECTION_ID
;
878 case PACKET_PUBLIC_FLAGS_4BYTE_CONNECTION_ID
:
879 // If the connection_id is truncated, expect to read the last serialized
881 if (!reader_
->ReadBytes(&public_header
->connection_id
,
882 PACKET_4BYTE_CONNECTION_ID
)) {
883 set_detailed_error("Unable to read ConnectionId.");
886 if (last_serialized_connection_id_
&&
887 (public_header
->connection_id
& k4ByteConnectionIdMask
) !=
888 (last_serialized_connection_id_
& k4ByteConnectionIdMask
)) {
889 set_detailed_error("Truncated 4 byte ConnectionId does not match "
890 "previous connection_id.");
893 public_header
->connection_id_length
= PACKET_4BYTE_CONNECTION_ID
;
894 public_header
->connection_id
= last_serialized_connection_id_
;
896 case PACKET_PUBLIC_FLAGS_1BYTE_CONNECTION_ID
:
897 if (!reader_
->ReadBytes(&public_header
->connection_id
,
898 PACKET_1BYTE_CONNECTION_ID
)) {
899 set_detailed_error("Unable to read ConnectionId.");
902 if (last_serialized_connection_id_
&&
903 (public_header
->connection_id
& k1ByteConnectionIdMask
) !=
904 (last_serialized_connection_id_
& k1ByteConnectionIdMask
)) {
905 set_detailed_error("Truncated 1 byte ConnectionId does not match "
906 "previous connection_id.");
909 public_header
->connection_id_length
= PACKET_1BYTE_CONNECTION_ID
;
910 public_header
->connection_id
= last_serialized_connection_id_
;
912 case PACKET_PUBLIC_FLAGS_0BYTE_CONNECTION_ID
:
913 public_header
->connection_id_length
= PACKET_0BYTE_CONNECTION_ID
;
914 public_header
->connection_id
= last_serialized_connection_id_
;
918 public_header
->sequence_number_length
=
919 ReadSequenceNumberLength(
920 public_flags
>> kPublicHeaderSequenceNumberShift
);
922 // Read the version only if the packet is from the client.
923 // version flag from the server means version negotiation packet.
924 if (public_header
->version_flag
&& perspective_
== Perspective::IS_SERVER
) {
926 if (!reader_
->ReadUInt32(&version_tag
)) {
927 set_detailed_error("Unable to read protocol version.");
931 // If the version from the new packet is the same as the version of this
932 // framer, then the public flags should be set to something we understand.
933 // If not, this raises an error.
934 QuicVersion version
= QuicTagToQuicVersion(version_tag
);
935 if (version
== quic_version_
&& public_flags
> PACKET_PUBLIC_FLAGS_MAX
) {
936 set_detailed_error("Illegal public flags value.");
939 public_header
->versions
.push_back(version
);
945 QuicSequenceNumberLength
QuicFramer::GetMinSequenceNumberLength(
946 QuicPacketSequenceNumber sequence_number
) {
947 if (sequence_number
< 1 << (PACKET_1BYTE_SEQUENCE_NUMBER
* 8)) {
948 return PACKET_1BYTE_SEQUENCE_NUMBER
;
949 } else if (sequence_number
< 1 << (PACKET_2BYTE_SEQUENCE_NUMBER
* 8)) {
950 return PACKET_2BYTE_SEQUENCE_NUMBER
;
951 } else if (sequence_number
<
952 UINT64_C(1) << (PACKET_4BYTE_SEQUENCE_NUMBER
* 8)) {
953 return PACKET_4BYTE_SEQUENCE_NUMBER
;
955 return PACKET_6BYTE_SEQUENCE_NUMBER
;
960 uint8
QuicFramer::GetSequenceNumberFlags(
961 QuicSequenceNumberLength sequence_number_length
) {
962 switch (sequence_number_length
) {
963 case PACKET_1BYTE_SEQUENCE_NUMBER
:
964 return PACKET_FLAGS_1BYTE_SEQUENCE
;
965 case PACKET_2BYTE_SEQUENCE_NUMBER
:
966 return PACKET_FLAGS_2BYTE_SEQUENCE
;
967 case PACKET_4BYTE_SEQUENCE_NUMBER
:
968 return PACKET_FLAGS_4BYTE_SEQUENCE
;
969 case PACKET_6BYTE_SEQUENCE_NUMBER
:
970 return PACKET_FLAGS_6BYTE_SEQUENCE
;
972 LOG(DFATAL
) << "Unreachable case statement.";
973 return PACKET_FLAGS_6BYTE_SEQUENCE
;
978 QuicFramer::AckFrameInfo
QuicFramer::GetAckFrameInfo(
979 const QuicAckFrame
& frame
) {
980 AckFrameInfo ack_info
;
981 if (frame
.missing_packets
.empty()) {
984 DCHECK_GE(frame
.largest_observed
, *frame
.missing_packets
.rbegin());
985 size_t cur_range_length
= 0;
986 SequenceNumberSet::const_iterator iter
= frame
.missing_packets
.begin();
987 QuicPacketSequenceNumber last_missing
= *iter
;
989 for (; iter
!= frame
.missing_packets
.end(); ++iter
) {
990 if (cur_range_length
< numeric_limits
<uint8
>::max() &&
991 *iter
== (last_missing
+ 1)) {
994 ack_info
.nack_ranges
[last_missing
- cur_range_length
] =
995 static_cast<uint8
>(cur_range_length
);
996 cur_range_length
= 0;
998 ack_info
.max_delta
= max(ack_info
.max_delta
, *iter
- last_missing
);
999 last_missing
= *iter
;
1001 // Include the last nack range.
1002 ack_info
.nack_ranges
[last_missing
- cur_range_length
] =
1003 static_cast<uint8
>(cur_range_length
);
1004 // Include the range to the largest observed.
1005 ack_info
.max_delta
=
1006 max(ack_info
.max_delta
, frame
.largest_observed
- last_missing
);
1010 bool QuicFramer::ProcessPacketHeader(QuicPacketHeader
* header
,
1011 const QuicEncryptedPacket
& packet
,
1012 char* decrypted_buffer
,
1013 size_t buffer_length
) {
1014 if (!ProcessPacketSequenceNumber(header
->public_header
.sequence_number_length
,
1015 &header
->packet_sequence_number
)) {
1016 set_detailed_error("Unable to read sequence number.");
1017 return RaiseError(QUIC_INVALID_PACKET_HEADER
);
1020 if (header
->packet_sequence_number
== 0u) {
1021 set_detailed_error("Packet sequence numbers cannot be 0.");
1022 return RaiseError(QUIC_INVALID_PACKET_HEADER
);
1025 if (!visitor_
->OnUnauthenticatedHeader(*header
)) {
1029 if (!DecryptPayload(*header
, packet
, decrypted_buffer
, buffer_length
)) {
1030 set_detailed_error("Unable to decrypt payload.");
1031 return RaiseError(QUIC_DECRYPTION_FAILURE
);
1034 uint8 private_flags
;
1035 if (!reader_
->ReadBytes(&private_flags
, 1)) {
1036 set_detailed_error("Unable to read private flags.");
1037 return RaiseError(QUIC_INVALID_PACKET_HEADER
);
1040 if (private_flags
> PACKET_PRIVATE_FLAGS_MAX
) {
1041 set_detailed_error("Illegal private flags value.");
1042 return RaiseError(QUIC_INVALID_PACKET_HEADER
);
1045 header
->entropy_flag
= (private_flags
& PACKET_PRIVATE_FLAGS_ENTROPY
) != 0;
1046 header
->fec_flag
= (private_flags
& PACKET_PRIVATE_FLAGS_FEC
) != 0;
1048 if ((private_flags
& PACKET_PRIVATE_FLAGS_FEC_GROUP
) != 0) {
1049 header
->is_in_fec_group
= IN_FEC_GROUP
;
1050 uint8 first_fec_protected_packet_offset
;
1051 if (!reader_
->ReadBytes(&first_fec_protected_packet_offset
, 1)) {
1052 set_detailed_error("Unable to read first fec protected packet offset.");
1053 return RaiseError(QUIC_INVALID_PACKET_HEADER
);
1055 if (first_fec_protected_packet_offset
>= header
->packet_sequence_number
) {
1056 set_detailed_error("First fec protected packet offset must be less "
1057 "than the sequence number.");
1058 return RaiseError(QUIC_INVALID_PACKET_HEADER
);
1061 header
->packet_sequence_number
- first_fec_protected_packet_offset
;
1064 header
->entropy_hash
= GetPacketEntropyHash(*header
);
1065 // Set the last sequence number after we have decrypted the packet
1066 // so we are confident is not attacker controlled.
1067 last_sequence_number_
= header
->packet_sequence_number
;
1071 bool QuicFramer::ProcessPacketSequenceNumber(
1072 QuicSequenceNumberLength sequence_number_length
,
1073 QuicPacketSequenceNumber
* sequence_number
) {
1074 QuicPacketSequenceNumber wire_sequence_number
= 0u;
1075 if (!reader_
->ReadBytes(&wire_sequence_number
, sequence_number_length
)) {
1079 // TODO(ianswett): Explore the usefulness of trying multiple sequence numbers
1080 // in case the first guess is incorrect.
1082 CalculatePacketSequenceNumberFromWire(sequence_number_length
,
1083 wire_sequence_number
);
1087 bool QuicFramer::ProcessFrameData(const QuicPacketHeader
& header
) {
1088 if (reader_
->IsDoneReading()) {
1089 set_detailed_error("Packet has no frames.");
1090 return RaiseError(QUIC_MISSING_PAYLOAD
);
1092 while (!reader_
->IsDoneReading()) {
1094 if (!reader_
->ReadBytes(&frame_type
, 1)) {
1095 set_detailed_error("Unable to read frame type.");
1096 return RaiseError(QUIC_INVALID_FRAME_DATA
);
1099 if (frame_type
& kQuicFrameTypeSpecialMask
) {
1101 if (frame_type
& kQuicFrameTypeStreamMask
) {
1102 QuicStreamFrame frame
;
1103 if (!ProcessStreamFrame(frame_type
, &frame
)) {
1104 return RaiseError(QUIC_INVALID_STREAM_DATA
);
1106 if (!visitor_
->OnStreamFrame(frame
)) {
1107 DVLOG(1) << "Visitor asked to stop further processing.";
1108 // Returning true since there was no parsing error.
1115 if (frame_type
& kQuicFrameTypeAckMask
) {
1117 if (!ProcessAckFrame(frame_type
, &frame
)) {
1118 return RaiseError(QUIC_INVALID_ACK_DATA
);
1120 if (!visitor_
->OnAckFrame(frame
)) {
1121 DVLOG(1) << "Visitor asked to stop further processing.";
1122 // Returning true since there was no parsing error.
1128 // This was a special frame type that did not match any
1129 // of the known ones. Error.
1130 set_detailed_error("Illegal frame type.");
1131 DLOG(WARNING
) << "Illegal frame type: "
1132 << static_cast<int>(frame_type
);
1133 return RaiseError(QUIC_INVALID_FRAME_DATA
);
1136 switch (frame_type
) {
1138 // We're done with the packet.
1141 case RST_STREAM_FRAME
: {
1142 QuicRstStreamFrame frame
;
1143 if (!ProcessRstStreamFrame(&frame
)) {
1144 return RaiseError(QUIC_INVALID_RST_STREAM_DATA
);
1146 if (!visitor_
->OnRstStreamFrame(frame
)) {
1147 DVLOG(1) << "Visitor asked to stop further processing.";
1148 // Returning true since there was no parsing error.
1154 case CONNECTION_CLOSE_FRAME
: {
1155 QuicConnectionCloseFrame frame
;
1156 if (!ProcessConnectionCloseFrame(&frame
)) {
1157 return RaiseError(QUIC_INVALID_CONNECTION_CLOSE_DATA
);
1160 if (!visitor_
->OnConnectionCloseFrame(frame
)) {
1161 DVLOG(1) << "Visitor asked to stop further processing.";
1162 // Returning true since there was no parsing error.
1168 case GOAWAY_FRAME
: {
1169 QuicGoAwayFrame goaway_frame
;
1170 if (!ProcessGoAwayFrame(&goaway_frame
)) {
1171 return RaiseError(QUIC_INVALID_GOAWAY_DATA
);
1173 if (!visitor_
->OnGoAwayFrame(goaway_frame
)) {
1174 DVLOG(1) << "Visitor asked to stop further processing.";
1175 // Returning true since there was no parsing error.
1181 case WINDOW_UPDATE_FRAME
: {
1182 QuicWindowUpdateFrame window_update_frame
;
1183 if (!ProcessWindowUpdateFrame(&window_update_frame
)) {
1184 return RaiseError(QUIC_INVALID_WINDOW_UPDATE_DATA
);
1186 if (!visitor_
->OnWindowUpdateFrame(window_update_frame
)) {
1187 DVLOG(1) << "Visitor asked to stop further processing.";
1188 // Returning true since there was no parsing error.
1194 case BLOCKED_FRAME
: {
1195 QuicBlockedFrame blocked_frame
;
1196 if (!ProcessBlockedFrame(&blocked_frame
)) {
1197 return RaiseError(QUIC_INVALID_BLOCKED_DATA
);
1199 if (!visitor_
->OnBlockedFrame(blocked_frame
)) {
1200 DVLOG(1) << "Visitor asked to stop further processing.";
1201 // Returning true since there was no parsing error.
1207 case STOP_WAITING_FRAME
: {
1208 QuicStopWaitingFrame stop_waiting_frame
;
1209 if (!ProcessStopWaitingFrame(header
, &stop_waiting_frame
)) {
1210 return RaiseError(QUIC_INVALID_STOP_WAITING_DATA
);
1212 if (!visitor_
->OnStopWaitingFrame(stop_waiting_frame
)) {
1213 DVLOG(1) << "Visitor asked to stop further processing.";
1214 // Returning true since there was no parsing error.
1220 // Ping has no payload.
1221 QuicPingFrame ping_frame
;
1222 if (!visitor_
->OnPingFrame(ping_frame
)) {
1223 DVLOG(1) << "Visitor asked to stop further processing.";
1224 // Returning true since there was no parsing error.
1231 set_detailed_error("Illegal frame type.");
1232 DLOG(WARNING
) << "Illegal frame type: "
1233 << static_cast<int>(frame_type
);
1234 return RaiseError(QUIC_INVALID_FRAME_DATA
);
1241 bool QuicFramer::ProcessStreamFrame(uint8 frame_type
,
1242 QuicStreamFrame
* frame
) {
1243 uint8 stream_flags
= frame_type
;
1245 stream_flags
&= ~kQuicFrameTypeStreamMask
;
1247 // Read from right to left: StreamID, Offset, Data Length, Fin.
1248 const uint8 stream_id_length
= (stream_flags
& kQuicStreamIDLengthMask
) + 1;
1249 stream_flags
>>= kQuicStreamIdShift
;
1251 uint8 offset_length
= (stream_flags
& kQuicStreamOffsetMask
);
1252 // There is no encoding for 1 byte, only 0 and 2 through 8.
1253 if (offset_length
> 0) {
1256 stream_flags
>>= kQuicStreamOffsetShift
;
1258 bool has_data_length
=
1259 (stream_flags
& kQuicStreamDataLengthMask
) == kQuicStreamDataLengthMask
;
1260 stream_flags
>>= kQuicStreamDataLengthShift
;
1262 frame
->fin
= (stream_flags
& kQuicStreamFinMask
) == kQuicStreamFinShift
;
1264 frame
->stream_id
= 0;
1265 if (!reader_
->ReadBytes(&frame
->stream_id
, stream_id_length
)) {
1266 set_detailed_error("Unable to read stream_id.");
1271 if (!reader_
->ReadBytes(&frame
->offset
, offset_length
)) {
1272 set_detailed_error("Unable to read offset.");
1276 if (has_data_length
) {
1277 if (!reader_
->ReadStringPiece16(&frame
->data
)) {
1278 set_detailed_error("Unable to read frame data.");
1282 if (!reader_
->ReadStringPiece(&frame
->data
, reader_
->BytesRemaining())) {
1283 set_detailed_error("Unable to read frame data.");
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
) {
1389 uint8 num_received_packets
;
1390 if (!reader_
->ReadBytes(&num_received_packets
, 1)) {
1391 set_detailed_error("Unable to read num received packets.");
1395 if (num_received_packets
> 0) {
1396 uint8 delta_from_largest_observed
;
1397 if (!reader_
->ReadBytes(&delta_from_largest_observed
,
1398 PACKET_1BYTE_SEQUENCE_NUMBER
)) {
1399 set_detailed_error("Unable to read sequence delta in received packets.");
1402 QuicPacketSequenceNumber seq_num
=
1403 ack_frame
->largest_observed
- delta_from_largest_observed
;
1405 // Time delta from the framer creation.
1406 uint32 time_delta_us
;
1407 if (!reader_
->ReadBytes(&time_delta_us
, sizeof(time_delta_us
))) {
1408 set_detailed_error("Unable to read time delta in received packets.");
1412 last_timestamp_
= CalculateTimestampFromWire(time_delta_us
);
1414 ack_frame
->received_packet_times
.push_back(
1415 std::make_pair(seq_num
, creation_time_
.Add(last_timestamp_
)));
1417 for (uint8 i
= 1; i
< num_received_packets
; ++i
) {
1418 if (!reader_
->ReadBytes(&delta_from_largest_observed
,
1419 PACKET_1BYTE_SEQUENCE_NUMBER
)) {
1421 "Unable to read sequence delta in received packets.");
1424 seq_num
= ack_frame
->largest_observed
- delta_from_largest_observed
;
1426 // Time delta from the previous timestamp.
1427 uint64 incremental_time_delta_us
;
1428 if (!reader_
->ReadUFloat16(&incremental_time_delta_us
)) {
1430 "Unable to read incremental time delta in received packets.");
1434 last_timestamp_
= last_timestamp_
.Add(
1435 QuicTime::Delta::FromMicroseconds(incremental_time_delta_us
));
1436 ack_frame
->received_packet_times
.push_back(
1437 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(EncryptionLevel level
, QuicDecrypter
* decrypter
) {
1588 DCHECK(alternative_decrypter_
.get() == nullptr);
1589 DCHECK_GE(level
, decrypter_level_
);
1590 decrypter_
.reset(decrypter
);
1591 decrypter_level_
= level
;
1594 void QuicFramer::SetAlternativeDecrypter(EncryptionLevel level
,
1595 QuicDecrypter
* decrypter
,
1596 bool latch_once_used
) {
1597 alternative_decrypter_
.reset(decrypter
);
1598 alternative_decrypter_level_
= level
;
1599 alternative_decrypter_latch_
= latch_once_used
;
1602 const QuicDecrypter
* QuicFramer::decrypter() const {
1603 return decrypter_
.get();
1606 const QuicDecrypter
* QuicFramer::alternative_decrypter() const {
1607 return alternative_decrypter_
.get();
1610 void QuicFramer::SetEncrypter(EncryptionLevel level
,
1611 QuicEncrypter
* encrypter
) {
1612 DCHECK_GE(level
, 0);
1613 DCHECK_LT(level
, NUM_ENCRYPTION_LEVELS
);
1614 encrypter_
[level
].reset(encrypter
);
1617 QuicEncryptedPacket
* QuicFramer::EncryptPayload(
1618 EncryptionLevel level
,
1619 QuicPacketSequenceNumber packet_sequence_number
,
1620 const QuicPacket
& packet
,
1622 size_t buffer_len
) {
1623 DCHECK(encrypter_
[level
].get() != nullptr);
1625 const size_t encrypted_len
=
1626 encrypter_
[level
]->GetCiphertextSize(packet
.Plaintext().length());
1627 StringPiece header_data
= packet
.BeforePlaintext();
1628 const size_t total_len
= header_data
.length() + encrypted_len
;
1630 char* encryption_buffer
= buffer
;
1631 // Allocate a large enough buffer for the header and the encrypted data.
1632 const bool is_new_buffer
= total_len
> buffer_len
;
1633 if (is_new_buffer
) {
1634 if (!FLAGS_quic_allow_oversized_packets_for_test
) {
1635 LOG(DFATAL
) << "Buffer of length:" << buffer_len
1636 << " is not large enough to encrypt length " << total_len
;
1639 encryption_buffer
= new char[total_len
];
1641 // Copy in the header, because the encrypter only populates the encrypted
1642 // plaintext content.
1643 memcpy(encryption_buffer
, header_data
.data(), header_data
.length());
1644 // Encrypt the plaintext into the buffer.
1645 size_t output_length
= 0;
1646 if (!encrypter_
[level
]->EncryptPacket(
1647 packet_sequence_number
, packet
.AssociatedData(), packet
.Plaintext(),
1648 encryption_buffer
+ header_data
.length(), &output_length
,
1650 RaiseError(QUIC_ENCRYPTION_FAILURE
);
1654 return new QuicEncryptedPacket(
1655 encryption_buffer
, header_data
.length() + output_length
, is_new_buffer
);
1658 size_t QuicFramer::GetMaxPlaintextSize(size_t ciphertext_size
) {
1659 // In order to keep the code simple, we don't have the current encryption
1660 // level to hand. Both the NullEncrypter and AES-GCM have a tag length of 12.
1661 size_t min_plaintext_size
= ciphertext_size
;
1663 for (int i
= ENCRYPTION_NONE
; i
< NUM_ENCRYPTION_LEVELS
; i
++) {
1664 if (encrypter_
[i
].get() != nullptr) {
1665 size_t size
= encrypter_
[i
]->GetMaxPlaintextSize(ciphertext_size
);
1666 if (size
< min_plaintext_size
) {
1667 min_plaintext_size
= size
;
1672 return min_plaintext_size
;
1675 bool QuicFramer::DecryptPayload(const QuicPacketHeader
& header
,
1676 const QuicEncryptedPacket
& packet
,
1677 char* decrypted_buffer
,
1678 size_t buffer_length
) {
1679 StringPiece encrypted
= reader_
->ReadRemainingPayload();
1680 DCHECK(decrypter_
.get() != nullptr);
1681 const StringPiece
& associated_data
= GetAssociatedDataFromEncryptedPacket(
1682 packet
, header
.public_header
.connection_id_length
,
1683 header
.public_header
.version_flag
,
1684 header
.public_header
.sequence_number_length
);
1685 size_t decrypted_length
= 0;
1686 bool success
= decrypter_
->DecryptPacket(
1687 header
.packet_sequence_number
, associated_data
, encrypted
,
1688 decrypted_buffer
, &decrypted_length
, buffer_length
);
1690 visitor_
->OnDecryptedPacket(decrypter_level_
);
1691 } else if (alternative_decrypter_
.get() != nullptr) {
1692 success
= alternative_decrypter_
->DecryptPacket(
1693 header
.packet_sequence_number
, associated_data
, encrypted
,
1694 decrypted_buffer
, &decrypted_length
, buffer_length
);
1696 visitor_
->OnDecryptedPacket(alternative_decrypter_level_
);
1697 if (alternative_decrypter_latch_
) {
1698 // Switch to the alternative decrypter and latch so that we cannot
1700 decrypter_
.reset(alternative_decrypter_
.release());
1701 decrypter_level_
= alternative_decrypter_level_
;
1702 alternative_decrypter_level_
= ENCRYPTION_NONE
;
1704 // Switch the alternative decrypter so that we use it first next time.
1705 decrypter_
.swap(alternative_decrypter_
);
1706 EncryptionLevel level
= alternative_decrypter_level_
;
1707 alternative_decrypter_level_
= decrypter_level_
;
1708 decrypter_level_
= level
;
1714 DLOG(WARNING
) << "DecryptPacket failed for sequence_number:"
1715 << header
.packet_sequence_number
;
1719 reader_
.reset(new QuicDataReader(decrypted_buffer
, decrypted_length
));
1723 size_t QuicFramer::GetAckFrameSize(
1724 const QuicAckFrame
& ack
,
1725 QuicSequenceNumberLength sequence_number_length
) {
1726 AckFrameInfo ack_info
= GetAckFrameInfo(ack
);
1727 QuicSequenceNumberLength largest_observed_length
=
1728 GetMinSequenceNumberLength(ack
.largest_observed
);
1729 QuicSequenceNumberLength missing_sequence_number_length
=
1730 GetMinSequenceNumberLength(ack_info
.max_delta
);
1732 size_t ack_size
= GetMinAckFrameSize(largest_observed_length
);
1733 if (!ack_info
.nack_ranges
.empty()) {
1734 ack_size
+= kNumberOfNackRangesSize
+ kNumberOfRevivedPacketsSize
;
1735 ack_size
+= min(ack_info
.nack_ranges
.size(), kMaxNackRanges
) *
1736 (missing_sequence_number_length
+ PACKET_1BYTE_SEQUENCE_NUMBER
);
1737 ack_size
+= min(ack
.revived_packets
.size(),
1738 kMaxRevivedPackets
) * largest_observed_length
;
1741 // In version 23, if the ack will be truncated due to too many nack ranges,
1742 // then do not include the number of timestamps (1 byte).
1743 if (ack_info
.nack_ranges
.size() <= kMaxNackRanges
) {
1744 // 1 byte for the number of timestamps.
1746 if (ack
.received_packet_times
.size() > 0) {
1747 // 1 byte for sequence number, 4 bytes for timestamp for the first
1751 // 1 byte for sequence number, 2 bytes for timestamp for the other
1753 ack_size
+= 3 * (ack
.received_packet_times
.size() - 1);
1760 size_t QuicFramer::ComputeFrameLength(
1761 const QuicFrame
& frame
,
1762 bool last_frame_in_packet
,
1763 InFecGroup is_in_fec_group
,
1764 QuicSequenceNumberLength sequence_number_length
) {
1765 switch (frame
.type
) {
1767 return GetMinStreamFrameSize(frame
.stream_frame
->stream_id
,
1768 frame
.stream_frame
->offset
,
1769 last_frame_in_packet
, is_in_fec_group
) +
1770 frame
.stream_frame
->data
.length();
1772 return GetAckFrameSize(*frame
.ack_frame
, sequence_number_length
);
1774 case STOP_WAITING_FRAME
:
1775 return GetStopWaitingFrameSize(sequence_number_length
);
1776 case MTU_DISCOVERY_FRAME
:
1777 // MTU discovery frames are serialized as ping frames.
1779 // Ping has no payload.
1780 return kQuicFrameTypeSize
;
1781 case RST_STREAM_FRAME
:
1782 if (quic_version_
<= QUIC_VERSION_24
) {
1783 return GetMinRstStreamFrameSize() +
1784 frame
.rst_stream_frame
->error_details
.size();
1786 return GetRstStreamFrameSize();
1787 case CONNECTION_CLOSE_FRAME
:
1788 return GetMinConnectionCloseFrameSize() +
1789 frame
.connection_close_frame
->error_details
.size();
1791 return GetMinGoAwayFrameSize() + frame
.goaway_frame
->reason_phrase
.size();
1792 case WINDOW_UPDATE_FRAME
:
1793 return GetWindowUpdateFrameSize();
1795 return GetBlockedFrameSize();
1799 case NUM_FRAME_TYPES
:
1804 // Not reachable, but some Chrome compilers can't figure that out. *sigh*
1809 bool QuicFramer::AppendTypeByte(const QuicFrame
& frame
,
1810 bool no_stream_frame_length
,
1811 QuicDataWriter
* writer
) {
1812 uint8 type_byte
= 0;
1813 switch (frame
.type
) {
1814 case STREAM_FRAME
: {
1815 if (frame
.stream_frame
== nullptr) {
1816 LOG(DFATAL
) << "Failed to append STREAM frame with no stream_frame.";
1819 type_byte
|= frame
.stream_frame
->fin
? kQuicStreamFinMask
: 0;
1822 type_byte
<<= kQuicStreamDataLengthShift
;
1823 type_byte
|= no_stream_frame_length
? 0: kQuicStreamDataLengthMask
;
1826 type_byte
<<= kQuicStreamOffsetShift
;
1827 const size_t offset_len
= GetStreamOffsetSize(frame
.stream_frame
->offset
);
1828 if (offset_len
> 0) {
1829 type_byte
|= offset_len
- 1;
1832 // stream id 2 bits.
1833 type_byte
<<= kQuicStreamIdShift
;
1834 type_byte
|= GetStreamIdSize(frame
.stream_frame
->stream_id
) - 1;
1835 type_byte
|= kQuicFrameTypeStreamMask
; // Set Stream Frame Type to 1.
1840 case MTU_DISCOVERY_FRAME
:
1841 type_byte
= static_cast<uint8
>(PING_FRAME
);
1844 type_byte
= static_cast<uint8
>(frame
.type
);
1848 return writer
->WriteUInt8(type_byte
);
1852 bool QuicFramer::AppendPacketSequenceNumber(
1853 QuicSequenceNumberLength sequence_number_length
,
1854 QuicPacketSequenceNumber packet_sequence_number
,
1855 QuicDataWriter
* writer
) {
1856 // Ensure the entire sequence number can be written.
1857 if (writer
->capacity() - writer
->length() <
1858 static_cast<size_t>(sequence_number_length
)) {
1861 switch (sequence_number_length
) {
1862 case PACKET_1BYTE_SEQUENCE_NUMBER
:
1863 return writer
->WriteUInt8(
1864 packet_sequence_number
& k1ByteSequenceNumberMask
);
1866 case PACKET_2BYTE_SEQUENCE_NUMBER
:
1867 return writer
->WriteUInt16(
1868 packet_sequence_number
& k2ByteSequenceNumberMask
);
1870 case PACKET_4BYTE_SEQUENCE_NUMBER
:
1871 return writer
->WriteUInt32(
1872 packet_sequence_number
& k4ByteSequenceNumberMask
);
1874 case PACKET_6BYTE_SEQUENCE_NUMBER
:
1875 return writer
->WriteUInt48(
1876 packet_sequence_number
& k6ByteSequenceNumberMask
);
1879 DCHECK(false) << "sequence_number_length: " << sequence_number_length
;
1884 bool QuicFramer::AppendStreamFrame(
1885 const QuicStreamFrame
& frame
,
1886 bool no_stream_frame_length
,
1887 QuicDataWriter
* writer
) {
1888 if (!writer
->WriteBytes(&frame
.stream_id
, GetStreamIdSize(frame
.stream_id
))) {
1889 LOG(DFATAL
) << "Writing stream id size failed.";
1892 if (!writer
->WriteBytes(&frame
.offset
, GetStreamOffsetSize(frame
.offset
))) {
1893 LOG(DFATAL
) << "Writing offset size failed.";
1896 if (!no_stream_frame_length
) {
1897 if ((frame
.data
.size() > numeric_limits
<uint16
>::max()) ||
1898 !writer
->WriteUInt16(static_cast<uint16
>(frame
.data
.size()))) {
1899 LOG(DFATAL
) << "Writing stream frame length failed";
1904 if (!writer
->WriteBytes(frame
.data
.data(), frame
.data
.size())) {
1905 LOG(DFATAL
) << "Writing frame data failed.";
1911 void QuicFramer::set_version(const QuicVersion version
) {
1912 DCHECK(IsSupportedVersion(version
)) << QuicVersionToString(version
);
1913 quic_version_
= version
;
1916 bool QuicFramer::AppendAckFrameAndTypeByte(
1917 const QuicPacketHeader
& header
,
1918 const QuicAckFrame
& frame
,
1919 QuicDataWriter
* writer
) {
1920 AckFrameInfo ack_info
= GetAckFrameInfo(frame
);
1921 QuicPacketSequenceNumber ack_largest_observed
= frame
.largest_observed
;
1922 QuicSequenceNumberLength largest_observed_length
=
1923 GetMinSequenceNumberLength(ack_largest_observed
);
1924 QuicSequenceNumberLength missing_sequence_number_length
=
1925 GetMinSequenceNumberLength(ack_info
.max_delta
);
1926 // Determine whether we need to truncate ranges.
1927 size_t available_range_bytes
=
1928 writer
->capacity() - writer
->length() - kNumberOfRevivedPacketsSize
-
1929 kNumberOfNackRangesSize
- GetMinAckFrameSize(largest_observed_length
);
1930 size_t max_num_ranges
= available_range_bytes
/
1931 (missing_sequence_number_length
+ PACKET_1BYTE_SEQUENCE_NUMBER
);
1932 max_num_ranges
= min(kMaxNackRanges
, max_num_ranges
);
1933 bool truncated
= ack_info
.nack_ranges
.size() > max_num_ranges
;
1934 DVLOG_IF(1, truncated
) << "Truncating ack from "
1935 << ack_info
.nack_ranges
.size() << " ranges to "
1937 // Write out the type byte by setting the low order bits and doing shifts
1938 // to make room for the next bit flags to be set.
1939 // Whether there are any nacks.
1940 uint8 type_byte
= ack_info
.nack_ranges
.empty() ? 0 : kQuicHasNacksMask
;
1943 type_byte
<<= kQuicAckTruncatedShift
;
1944 type_byte
|= truncated
? kQuicAckTruncatedMask
: 0;
1946 // Largest observed sequence number length.
1947 type_byte
<<= kQuicSequenceNumberLengthShift
;
1948 type_byte
|= GetSequenceNumberFlags(largest_observed_length
);
1950 // Missing sequence number length.
1951 type_byte
<<= kQuicSequenceNumberLengthShift
;
1952 type_byte
|= GetSequenceNumberFlags(missing_sequence_number_length
);
1954 type_byte
|= kQuicFrameTypeAckMask
;
1956 if (!writer
->WriteUInt8(type_byte
)) {
1960 QuicPacketEntropyHash ack_entropy_hash
= frame
.entropy_hash
;
1961 NackRangeMap::reverse_iterator ack_iter
= ack_info
.nack_ranges
.rbegin();
1963 // Skip the nack ranges which the truncated ack won't include and set
1964 // a correct largest observed for the truncated ack.
1965 for (size_t i
= 1; i
< (ack_info
.nack_ranges
.size() - max_num_ranges
);
1969 // If the last range is followed by acks, include them.
1970 // If the last range is followed by another range, specify the end of the
1971 // range as the largest_observed.
1972 ack_largest_observed
= ack_iter
->first
- 1;
1973 // Also update the entropy so it matches the largest observed.
1974 ack_entropy_hash
= entropy_calculator_
->EntropyHash(ack_largest_observed
);
1978 if (!writer
->WriteUInt8(ack_entropy_hash
)) {
1982 if (!AppendPacketSequenceNumber(largest_observed_length
,
1983 ack_largest_observed
, writer
)) {
1987 uint64 delta_time_largest_observed_us
= kUFloat16MaxValue
;
1988 if (!frame
.delta_time_largest_observed
.IsInfinite()) {
1989 DCHECK_LE(0u, frame
.delta_time_largest_observed
.ToMicroseconds());
1990 delta_time_largest_observed_us
=
1991 frame
.delta_time_largest_observed
.ToMicroseconds();
1994 if (!writer
->WriteUFloat16(delta_time_largest_observed_us
)) {
1998 // Timestamp goes at the end of the required fields.
2000 if (!AppendTimestampToAckFrame(frame
, writer
)) {
2005 if (ack_info
.nack_ranges
.empty()) {
2009 const uint8 num_missing_ranges
=
2010 static_cast<uint8
>(min(ack_info
.nack_ranges
.size(), max_num_ranges
));
2011 if (!writer
->WriteBytes(&num_missing_ranges
, 1)) {
2015 int num_ranges_written
= 0;
2016 QuicPacketSequenceNumber last_sequence_written
= ack_largest_observed
;
2017 for (; ack_iter
!= ack_info
.nack_ranges
.rend(); ++ack_iter
) {
2018 // Calculate the delta to the last number in the range.
2019 QuicPacketSequenceNumber missing_delta
=
2020 last_sequence_written
- (ack_iter
->first
+ ack_iter
->second
);
2021 if (!AppendPacketSequenceNumber(missing_sequence_number_length
,
2022 missing_delta
, writer
)) {
2025 if (!AppendPacketSequenceNumber(PACKET_1BYTE_SEQUENCE_NUMBER
,
2026 ack_iter
->second
, writer
)) {
2029 // Subtract 1 so a missing_delta of 0 means an adjacent range.
2030 last_sequence_written
= ack_iter
->first
- 1;
2031 ++num_ranges_written
;
2033 DCHECK_EQ(num_missing_ranges
, num_ranges_written
);
2035 // Append revived packets.
2036 // If not all the revived packets fit, only mention the ones that do.
2037 uint8 num_revived_packets
=
2038 static_cast<uint8
>(min(frame
.revived_packets
.size(), kMaxRevivedPackets
));
2039 num_revived_packets
= static_cast<uint8
>(min(
2040 static_cast<size_t>(num_revived_packets
),
2041 (writer
->capacity() - writer
->length()) / largest_observed_length
));
2042 if (!writer
->WriteBytes(&num_revived_packets
, 1)) {
2046 SequenceNumberSet::const_iterator iter
= frame
.revived_packets
.begin();
2047 for (int i
= 0; i
< num_revived_packets
; ++i
, ++iter
) {
2048 LOG_IF(DFATAL
, !ContainsKey(frame
.missing_packets
, *iter
));
2049 if (!AppendPacketSequenceNumber(largest_observed_length
,
2058 bool QuicFramer::AppendTimestampToAckFrame(const QuicAckFrame
& frame
,
2059 QuicDataWriter
* writer
) {
2060 DCHECK_GE(numeric_limits
<uint8
>::max(), frame
.received_packet_times
.size());
2061 // num_received_packets is only 1 byte.
2062 if (frame
.received_packet_times
.size() > numeric_limits
<uint8
>::max()) {
2066 uint8 num_received_packets
= frame
.received_packet_times
.size();
2068 if (!writer
->WriteBytes(&num_received_packets
, 1)) {
2071 if (num_received_packets
== 0) {
2075 PacketTimeList::const_iterator it
= frame
.received_packet_times
.begin();
2076 QuicPacketSequenceNumber sequence_number
= it
->first
;
2077 QuicPacketSequenceNumber delta_from_largest_observed
=
2078 frame
.largest_observed
- sequence_number
;
2080 DCHECK_GE(numeric_limits
<uint8
>::max(), delta_from_largest_observed
);
2081 if (delta_from_largest_observed
> numeric_limits
<uint8
>::max()) {
2085 if (!writer
->WriteUInt8(
2086 delta_from_largest_observed
& k1ByteSequenceNumberMask
)) {
2090 // Use the lowest 4 bytes of the time delta from the creation_time_.
2091 const uint64 time_epoch_delta_us
= UINT64_C(1) << 32;
2092 uint32 time_delta_us
=
2093 static_cast<uint32
>(it
->second
.Subtract(creation_time_
).ToMicroseconds()
2094 & (time_epoch_delta_us
- 1));
2095 if (!writer
->WriteBytes(&time_delta_us
, sizeof(time_delta_us
))) {
2099 QuicTime prev_time
= it
->second
;
2101 for (++it
; it
!= frame
.received_packet_times
.end(); ++it
) {
2102 sequence_number
= it
->first
;
2103 delta_from_largest_observed
= frame
.largest_observed
- sequence_number
;
2105 if (delta_from_largest_observed
> numeric_limits
<uint8
>::max()) {
2109 if (!writer
->WriteUInt8(
2110 delta_from_largest_observed
& k1ByteSequenceNumberMask
)) {
2114 uint64 frame_time_delta_us
=
2115 it
->second
.Subtract(prev_time
).ToMicroseconds();
2116 prev_time
= it
->second
;
2117 if (!writer
->WriteUFloat16(frame_time_delta_us
)) {
2124 bool QuicFramer::AppendStopWaitingFrame(
2125 const QuicPacketHeader
& header
,
2126 const QuicStopWaitingFrame
& frame
,
2127 QuicDataWriter
* writer
) {
2128 DCHECK_GE(header
.packet_sequence_number
, frame
.least_unacked
);
2129 const QuicPacketSequenceNumber least_unacked_delta
=
2130 header
.packet_sequence_number
- frame
.least_unacked
;
2131 const QuicPacketSequenceNumber length_shift
=
2132 header
.public_header
.sequence_number_length
* 8;
2133 if (!writer
->WriteUInt8(frame
.entropy_hash
)) {
2134 LOG(DFATAL
) << " hash failed";
2138 if (least_unacked_delta
>> length_shift
> 0) {
2139 LOG(DFATAL
) << "sequence_number_length "
2140 << header
.public_header
.sequence_number_length
2141 << " is too small for least_unacked_delta: "
2142 << least_unacked_delta
;
2145 if (!AppendPacketSequenceNumber(header
.public_header
.sequence_number_length
,
2146 least_unacked_delta
, writer
)) {
2147 LOG(DFATAL
) << " seq failed: "
2148 << header
.public_header
.sequence_number_length
;
2155 bool QuicFramer::AppendRstStreamFrame(const QuicRstStreamFrame
& frame
,
2156 QuicDataWriter
* writer
) {
2157 if (!writer
->WriteUInt32(frame
.stream_id
)) {
2161 if (!writer
->WriteUInt64(frame
.byte_offset
)) {
2165 uint32 error_code
= static_cast<uint32
>(frame
.error_code
);
2166 if (!writer
->WriteUInt32(error_code
)) {
2170 if (quic_version_
<= QUIC_VERSION_24
) {
2171 if (!writer
->WriteStringPiece16(frame
.error_details
)) {
2178 bool QuicFramer::AppendConnectionCloseFrame(
2179 const QuicConnectionCloseFrame
& frame
,
2180 QuicDataWriter
* writer
) {
2181 uint32 error_code
= static_cast<uint32
>(frame
.error_code
);
2182 if (!writer
->WriteUInt32(error_code
)) {
2185 if (!writer
->WriteStringPiece16(frame
.error_details
)) {
2191 bool QuicFramer::AppendGoAwayFrame(const QuicGoAwayFrame
& frame
,
2192 QuicDataWriter
* writer
) {
2193 uint32 error_code
= static_cast<uint32
>(frame
.error_code
);
2194 if (!writer
->WriteUInt32(error_code
)) {
2197 uint32 stream_id
= static_cast<uint32
>(frame
.last_good_stream_id
);
2198 if (!writer
->WriteUInt32(stream_id
)) {
2201 if (!writer
->WriteStringPiece16(frame
.reason_phrase
)) {
2207 bool QuicFramer::AppendWindowUpdateFrame(const QuicWindowUpdateFrame
& frame
,
2208 QuicDataWriter
* writer
) {
2209 uint32 stream_id
= static_cast<uint32
>(frame
.stream_id
);
2210 if (!writer
->WriteUInt32(stream_id
)) {
2213 if (!writer
->WriteUInt64(frame
.byte_offset
)) {
2219 bool QuicFramer::AppendBlockedFrame(const QuicBlockedFrame
& frame
,
2220 QuicDataWriter
* writer
) {
2221 uint32 stream_id
= static_cast<uint32
>(frame
.stream_id
);
2222 if (!writer
->WriteUInt32(stream_id
)) {
2228 bool QuicFramer::RaiseError(QuicErrorCode error
) {
2229 DVLOG(1) << "Error: " << QuicUtils::ErrorToString(error
)
2230 << " detail: " << detailed_error_
;
2232 visitor_
->OnError(this);
2233 reader_
.reset(nullptr);