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 QuicDataReader
reader(packet
.data(), packet
.length());
525 visitor_
->OnPacket();
527 // First parse the public header.
528 QuicPacketPublicHeader public_header
;
529 if (!ProcessPublicHeader(&reader
, &public_header
)) {
530 DLOG(WARNING
) << "Unable to process public header.";
531 DCHECK_NE("", detailed_error_
);
532 return RaiseError(QUIC_INVALID_PACKET_HEADER
);
535 if (!visitor_
->OnUnauthenticatedPublicHeader(public_header
)) {
536 // The visitor suppresses further processing of the packet.
540 if (perspective_
== Perspective::IS_SERVER
&& public_header
.version_flag
&&
541 public_header
.versions
[0] != quic_version_
) {
542 if (!visitor_
->OnProtocolVersionMismatch(public_header
.versions
[0])) {
548 if (perspective_
== Perspective::IS_CLIENT
&& public_header
.version_flag
) {
549 rv
= ProcessVersionNegotiationPacket(&reader
, &public_header
);
550 } else if (public_header
.reset_flag
) {
551 rv
= ProcessPublicResetPacket(&reader
, public_header
);
552 } else if (packet
.length() <= kMaxPacketSize
) {
553 char buffer
[kMaxPacketSize
];
554 rv
= ProcessDataPacket(&reader
, public_header
, packet
, buffer
,
557 scoped_ptr
<char[]> large_buffer(new char[packet
.length()]);
558 rv
= ProcessDataPacket(&reader
, public_header
, packet
, large_buffer
.get(),
560 LOG_IF(DFATAL
, rv
) << "QUIC should never successfully process packets "
561 << "larger than kMaxPacketSize. packet size:"
568 bool QuicFramer::ProcessVersionNegotiationPacket(
569 QuicDataReader
* reader
,
570 QuicPacketPublicHeader
* public_header
) {
571 DCHECK_EQ(Perspective::IS_CLIENT
, perspective_
);
572 // Try reading at least once to raise error if the packet is invalid.
575 if (!reader
->ReadBytes(&version
, kQuicVersionSize
)) {
576 set_detailed_error("Unable to read supported version in negotiation.");
577 return RaiseError(QUIC_INVALID_VERSION_NEGOTIATION_PACKET
);
579 public_header
->versions
.push_back(QuicTagToQuicVersion(version
));
580 } while (!reader
->IsDoneReading());
582 visitor_
->OnVersionNegotiationPacket(*public_header
);
586 bool QuicFramer::ProcessDataPacket(QuicDataReader
* encrypted_reader
,
587 const QuicPacketPublicHeader
& public_header
,
588 const QuicEncryptedPacket
& packet
,
589 char* decrypted_buffer
,
590 size_t buffer_length
) {
591 QuicPacketHeader
header(public_header
);
592 if (!ProcessUnauthenticatedHeader(encrypted_reader
, &header
)) {
593 DLOG(WARNING
) << "Unable to process packet header. Stopping parsing.";
597 size_t decrypted_length
= 0;
598 if (!DecryptPayload(encrypted_reader
, header
, packet
, decrypted_buffer
,
599 buffer_length
, &decrypted_length
)) {
600 set_detailed_error("Unable to decrypt payload.");
601 return RaiseError(QUIC_DECRYPTION_FAILURE
);
604 QuicDataReader
reader(decrypted_buffer
, decrypted_length
);
605 if (!ProcessAuthenticatedHeader(&reader
, &header
)) {
606 DLOG(WARNING
) << "Unable to process packet header. Stopping parsing.";
610 if (!visitor_
->OnPacketHeader(header
)) {
611 // The visitor suppresses further processing of the packet.
615 if (packet
.length() > kMaxPacketSize
) {
616 DLOG(WARNING
) << "Packet too large: " << packet
.length();
617 return RaiseError(QUIC_PACKET_TOO_LARGE
);
620 // Handle the payload.
621 if (!header
.fec_flag
) {
622 if (header
.is_in_fec_group
== IN_FEC_GROUP
) {
623 StringPiece payload
= reader
.PeekRemainingPayload();
624 visitor_
->OnFecProtectedPayload(payload
);
626 if (!ProcessFrameData(&reader
, header
)) {
627 DCHECK_NE(QUIC_NO_ERROR
, error_
); // ProcessFrameData sets the error.
628 DLOG(WARNING
) << "Unable to process frame data.";
632 QuicFecData fec_data
;
633 fec_data
.fec_group
= header
.fec_group
;
634 fec_data
.redundancy
= reader
.ReadRemainingPayload();
635 visitor_
->OnFecData(fec_data
);
638 visitor_
->OnPacketComplete();
642 bool QuicFramer::ProcessPublicResetPacket(
643 QuicDataReader
* reader
,
644 const QuicPacketPublicHeader
& public_header
) {
645 QuicPublicResetPacket
packet(public_header
);
647 scoped_ptr
<CryptoHandshakeMessage
> reset(
648 CryptoFramer::ParseMessage(reader
->ReadRemainingPayload()));
650 set_detailed_error("Unable to read reset message.");
651 return RaiseError(QUIC_INVALID_PUBLIC_RST_PACKET
);
653 if (reset
->tag() != kPRST
) {
654 set_detailed_error("Incorrect message tag.");
655 return RaiseError(QUIC_INVALID_PUBLIC_RST_PACKET
);
658 if (reset
->GetUint64(kRNON
, &packet
.nonce_proof
) != QUIC_NO_ERROR
) {
659 set_detailed_error("Unable to read nonce proof.");
660 return RaiseError(QUIC_INVALID_PUBLIC_RST_PACKET
);
662 // TODO(satyamshekhar): validate nonce to protect against DoS.
664 if (reset
->GetUint64(kRSEQ
, &packet
.rejected_sequence_number
) !=
666 set_detailed_error("Unable to read rejected sequence number.");
667 return RaiseError(QUIC_INVALID_PUBLIC_RST_PACKET
);
671 if (reset
->GetStringPiece(kCADR
, &address
)) {
672 QuicSocketAddressCoder address_coder
;
673 if (address_coder
.Decode(address
.data(), address
.length())) {
674 packet
.client_address
= IPEndPoint(address_coder
.ip(),
675 address_coder
.port());
679 visitor_
->OnPublicResetPacket(packet
);
683 bool QuicFramer::ProcessRevivedPacket(QuicPacketHeader
* header
,
684 StringPiece payload
) {
685 visitor_
->OnRevivedPacket();
687 header
->entropy_hash
= GetPacketEntropyHash(*header
);
689 if (!visitor_
->OnPacketHeader(*header
)) {
693 if (payload
.length() > kMaxPacketSize
) {
694 set_detailed_error("Revived packet too large.");
695 return RaiseError(QUIC_PACKET_TOO_LARGE
);
698 QuicDataReader
reader(payload
.data(), payload
.length());
699 if (!ProcessFrameData(&reader
, *header
)) {
700 DCHECK_NE(QUIC_NO_ERROR
, error_
); // ProcessFrameData sets the error.
701 DLOG(WARNING
) << "Unable to process frame data.";
705 visitor_
->OnPacketComplete();
709 bool QuicFramer::AppendPacketHeader(const QuicPacketHeader
& header
,
710 QuicDataWriter
* writer
) {
711 DVLOG(1) << "Appending header: " << header
;
712 DCHECK(header
.fec_group
> 0 || header
.is_in_fec_group
== NOT_IN_FEC_GROUP
);
713 uint8 public_flags
= 0;
714 if (header
.public_header
.reset_flag
) {
715 public_flags
|= PACKET_PUBLIC_FLAGS_RST
;
717 if (header
.public_header
.version_flag
) {
718 public_flags
|= PACKET_PUBLIC_FLAGS_VERSION
;
722 GetSequenceNumberFlags(header
.public_header
.sequence_number_length
)
723 << kPublicHeaderSequenceNumberShift
;
725 switch (header
.public_header
.connection_id_length
) {
726 case PACKET_0BYTE_CONNECTION_ID
:
727 if (!writer
->WriteUInt8(
728 public_flags
| PACKET_PUBLIC_FLAGS_0BYTE_CONNECTION_ID
)) {
732 case PACKET_1BYTE_CONNECTION_ID
:
733 if (!writer
->WriteUInt8(
734 public_flags
| PACKET_PUBLIC_FLAGS_1BYTE_CONNECTION_ID
)) {
737 if (!writer
->WriteUInt8(
738 header
.public_header
.connection_id
& k1ByteConnectionIdMask
)) {
742 case PACKET_4BYTE_CONNECTION_ID
:
743 if (!writer
->WriteUInt8(
744 public_flags
| PACKET_PUBLIC_FLAGS_4BYTE_CONNECTION_ID
)) {
747 if (!writer
->WriteUInt32(
748 header
.public_header
.connection_id
& k4ByteConnectionIdMask
)) {
752 case PACKET_8BYTE_CONNECTION_ID
:
753 if (!writer
->WriteUInt8(
754 public_flags
| PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID
)) {
757 if (!writer
->WriteUInt64(header
.public_header
.connection_id
)) {
762 last_serialized_connection_id_
= header
.public_header
.connection_id
;
764 if (header
.public_header
.version_flag
) {
765 DCHECK_EQ(Perspective::IS_CLIENT
, perspective_
);
766 QuicTag tag
= QuicVersionToQuicTag(quic_version_
);
767 writer
->WriteUInt32(tag
);
768 DVLOG(1) << "version = " << quic_version_
<< ", tag = '"
769 << QuicUtils::TagToString(tag
) << "'";
772 if (!AppendPacketSequenceNumber(header
.public_header
.sequence_number_length
,
773 header
.packet_sequence_number
, writer
)) {
777 uint8 private_flags
= 0;
778 if (header
.entropy_flag
) {
779 private_flags
|= PACKET_PRIVATE_FLAGS_ENTROPY
;
781 if (header
.is_in_fec_group
== IN_FEC_GROUP
) {
782 private_flags
|= PACKET_PRIVATE_FLAGS_FEC_GROUP
;
784 if (header
.fec_flag
) {
785 private_flags
|= PACKET_PRIVATE_FLAGS_FEC
;
787 if (!writer
->WriteUInt8(private_flags
)) {
791 // The FEC group number is the sequence number of the first fec
792 // protected packet, or 0 if this packet is not protected.
793 if (header
.is_in_fec_group
== IN_FEC_GROUP
) {
794 DCHECK_LE(header
.fec_group
, header
.packet_sequence_number
);
795 DCHECK_LT(header
.packet_sequence_number
- header
.fec_group
, 255u);
796 // Offset from the current packet sequence number to the first fec
798 uint8 first_fec_protected_packet_offset
=
799 static_cast<uint8
>(header
.packet_sequence_number
- header
.fec_group
);
800 if (!writer
->WriteBytes(&first_fec_protected_packet_offset
, 1)) {
808 const QuicTime::Delta
QuicFramer::CalculateTimestampFromWire(
809 uint32 time_delta_us
) {
810 // The new time_delta might have wrapped to the next epoch, or it
811 // might have reverse wrapped to the previous epoch, or it might
812 // remain in the same epoch. Select the time closest to the previous
815 // epoch_delta is the delta between epochs. A delta is 4 bytes of
817 const uint64 epoch_delta
= UINT64_C(1) << 32;
818 uint64 epoch
= last_timestamp_
.ToMicroseconds() & ~(epoch_delta
- 1);
819 // Wrapping is safe here because a wrapped value will not be ClosestTo below.
820 uint64 prev_epoch
= epoch
- epoch_delta
;
821 uint64 next_epoch
= epoch
+ epoch_delta
;
823 uint64 time
= ClosestTo(last_timestamp_
.ToMicroseconds(),
824 epoch
+ time_delta_us
,
825 ClosestTo(last_timestamp_
.ToMicroseconds(),
826 prev_epoch
+ time_delta_us
,
827 next_epoch
+ time_delta_us
));
829 return QuicTime::Delta::FromMicroseconds(time
);
832 QuicPacketSequenceNumber
QuicFramer::CalculatePacketSequenceNumberFromWire(
833 QuicSequenceNumberLength sequence_number_length
,
834 QuicPacketSequenceNumber packet_sequence_number
) const {
835 // The new sequence number might have wrapped to the next epoch, or
836 // it might have reverse wrapped to the previous epoch, or it might
837 // remain in the same epoch. Select the sequence number closest to the
838 // next expected sequence number, the previous sequence number plus 1.
840 // epoch_delta is the delta between epochs the sequence number was serialized
841 // with, so the correct value is likely the same epoch as the last sequence
842 // number or an adjacent epoch.
843 const QuicPacketSequenceNumber epoch_delta
=
844 UINT64_C(1) << (8 * sequence_number_length
);
845 QuicPacketSequenceNumber next_sequence_number
= last_sequence_number_
+ 1;
846 QuicPacketSequenceNumber epoch
= last_sequence_number_
& ~(epoch_delta
- 1);
847 QuicPacketSequenceNumber prev_epoch
= epoch
- epoch_delta
;
848 QuicPacketSequenceNumber next_epoch
= epoch
+ epoch_delta
;
850 return ClosestTo(next_sequence_number
,
851 epoch
+ packet_sequence_number
,
852 ClosestTo(next_sequence_number
,
853 prev_epoch
+ packet_sequence_number
,
854 next_epoch
+ packet_sequence_number
));
857 bool QuicFramer::ProcessPublicHeader(QuicDataReader
* reader
,
858 QuicPacketPublicHeader
* public_header
) {
860 if (!reader
->ReadBytes(&public_flags
, 1)) {
861 set_detailed_error("Unable to read public flags.");
865 public_header
->reset_flag
= (public_flags
& PACKET_PUBLIC_FLAGS_RST
) != 0;
866 public_header
->version_flag
=
867 (public_flags
& PACKET_PUBLIC_FLAGS_VERSION
) != 0;
869 if (validate_flags_
&&
870 !public_header
->version_flag
&& public_flags
> PACKET_PUBLIC_FLAGS_MAX
) {
871 set_detailed_error("Illegal public flags value.");
875 if (public_header
->reset_flag
&& public_header
->version_flag
) {
876 set_detailed_error("Got version flag in reset packet");
880 switch (public_flags
& PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID
) {
881 case PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID
:
882 if (!reader
->ReadUInt64(&public_header
->connection_id
)) {
883 set_detailed_error("Unable to read ConnectionId.");
886 public_header
->connection_id_length
= PACKET_8BYTE_CONNECTION_ID
;
888 case PACKET_PUBLIC_FLAGS_4BYTE_CONNECTION_ID
:
889 // If the connection_id is truncated, expect to read the last serialized
891 if (!reader
->ReadBytes(&public_header
->connection_id
,
892 PACKET_4BYTE_CONNECTION_ID
)) {
893 set_detailed_error("Unable to read ConnectionId.");
896 if (last_serialized_connection_id_
&&
897 (public_header
->connection_id
& k4ByteConnectionIdMask
) !=
898 (last_serialized_connection_id_
& k4ByteConnectionIdMask
)) {
899 set_detailed_error("Truncated 4 byte ConnectionId does not match "
900 "previous connection_id.");
903 public_header
->connection_id_length
= PACKET_4BYTE_CONNECTION_ID
;
904 public_header
->connection_id
= last_serialized_connection_id_
;
906 case PACKET_PUBLIC_FLAGS_1BYTE_CONNECTION_ID
:
907 if (!reader
->ReadBytes(&public_header
->connection_id
,
908 PACKET_1BYTE_CONNECTION_ID
)) {
909 set_detailed_error("Unable to read ConnectionId.");
912 if (last_serialized_connection_id_
&&
913 (public_header
->connection_id
& k1ByteConnectionIdMask
) !=
914 (last_serialized_connection_id_
& k1ByteConnectionIdMask
)) {
915 set_detailed_error("Truncated 1 byte ConnectionId does not match "
916 "previous connection_id.");
919 public_header
->connection_id_length
= PACKET_1BYTE_CONNECTION_ID
;
920 public_header
->connection_id
= last_serialized_connection_id_
;
922 case PACKET_PUBLIC_FLAGS_0BYTE_CONNECTION_ID
:
923 public_header
->connection_id_length
= PACKET_0BYTE_CONNECTION_ID
;
924 public_header
->connection_id
= last_serialized_connection_id_
;
928 public_header
->sequence_number_length
=
929 ReadSequenceNumberLength(
930 public_flags
>> kPublicHeaderSequenceNumberShift
);
932 // Read the version only if the packet is from the client.
933 // version flag from the server means version negotiation packet.
934 if (public_header
->version_flag
&& perspective_
== Perspective::IS_SERVER
) {
936 if (!reader
->ReadUInt32(&version_tag
)) {
937 set_detailed_error("Unable to read protocol version.");
941 // If the version from the new packet is the same as the version of this
942 // framer, then the public flags should be set to something we understand.
943 // If not, this raises an error.
944 QuicVersion version
= QuicTagToQuicVersion(version_tag
);
945 if (version
== quic_version_
&& public_flags
> PACKET_PUBLIC_FLAGS_MAX
) {
946 set_detailed_error("Illegal public flags value.");
949 public_header
->versions
.push_back(version
);
955 QuicSequenceNumberLength
QuicFramer::GetMinSequenceNumberLength(
956 QuicPacketSequenceNumber sequence_number
) {
957 if (sequence_number
< 1 << (PACKET_1BYTE_SEQUENCE_NUMBER
* 8)) {
958 return PACKET_1BYTE_SEQUENCE_NUMBER
;
959 } else if (sequence_number
< 1 << (PACKET_2BYTE_SEQUENCE_NUMBER
* 8)) {
960 return PACKET_2BYTE_SEQUENCE_NUMBER
;
961 } else if (sequence_number
<
962 UINT64_C(1) << (PACKET_4BYTE_SEQUENCE_NUMBER
* 8)) {
963 return PACKET_4BYTE_SEQUENCE_NUMBER
;
965 return PACKET_6BYTE_SEQUENCE_NUMBER
;
970 uint8
QuicFramer::GetSequenceNumberFlags(
971 QuicSequenceNumberLength sequence_number_length
) {
972 switch (sequence_number_length
) {
973 case PACKET_1BYTE_SEQUENCE_NUMBER
:
974 return PACKET_FLAGS_1BYTE_SEQUENCE
;
975 case PACKET_2BYTE_SEQUENCE_NUMBER
:
976 return PACKET_FLAGS_2BYTE_SEQUENCE
;
977 case PACKET_4BYTE_SEQUENCE_NUMBER
:
978 return PACKET_FLAGS_4BYTE_SEQUENCE
;
979 case PACKET_6BYTE_SEQUENCE_NUMBER
:
980 return PACKET_FLAGS_6BYTE_SEQUENCE
;
982 LOG(DFATAL
) << "Unreachable case statement.";
983 return PACKET_FLAGS_6BYTE_SEQUENCE
;
988 QuicFramer::AckFrameInfo
QuicFramer::GetAckFrameInfo(
989 const QuicAckFrame
& frame
) {
990 AckFrameInfo ack_info
;
991 if (frame
.missing_packets
.empty()) {
994 DCHECK_GE(frame
.largest_observed
, *frame
.missing_packets
.rbegin());
995 size_t cur_range_length
= 0;
996 SequenceNumberSet::const_iterator iter
= frame
.missing_packets
.begin();
997 QuicPacketSequenceNumber last_missing
= *iter
;
999 for (; iter
!= frame
.missing_packets
.end(); ++iter
) {
1000 if (cur_range_length
< numeric_limits
<uint8
>::max() &&
1001 *iter
== (last_missing
+ 1)) {
1004 ack_info
.nack_ranges
[last_missing
- cur_range_length
] =
1005 static_cast<uint8
>(cur_range_length
);
1006 cur_range_length
= 0;
1008 ack_info
.max_delta
= max(ack_info
.max_delta
, *iter
- last_missing
);
1009 last_missing
= *iter
;
1011 // Include the last nack range.
1012 ack_info
.nack_ranges
[last_missing
- cur_range_length
] =
1013 static_cast<uint8
>(cur_range_length
);
1014 // Include the range to the largest observed.
1015 ack_info
.max_delta
=
1016 max(ack_info
.max_delta
, frame
.largest_observed
- last_missing
);
1020 bool QuicFramer::ProcessUnauthenticatedHeader(QuicDataReader
* encrypted_reader
,
1021 QuicPacketHeader
* header
) {
1022 if (!ProcessPacketSequenceNumber(encrypted_reader
,
1023 header
->public_header
.sequence_number_length
,
1024 &header
->packet_sequence_number
)) {
1025 set_detailed_error("Unable to read sequence number.");
1026 return RaiseError(QUIC_INVALID_PACKET_HEADER
);
1029 if (header
->packet_sequence_number
== 0u) {
1030 set_detailed_error("Packet sequence numbers cannot be 0.");
1031 return RaiseError(QUIC_INVALID_PACKET_HEADER
);
1034 if (!visitor_
->OnUnauthenticatedHeader(*header
)) {
1040 bool QuicFramer::ProcessAuthenticatedHeader(QuicDataReader
* reader
,
1041 QuicPacketHeader
* header
) {
1042 uint8 private_flags
;
1043 if (!reader
->ReadBytes(&private_flags
, 1)) {
1044 set_detailed_error("Unable to read private flags.");
1045 return RaiseError(QUIC_INVALID_PACKET_HEADER
);
1048 if (private_flags
> PACKET_PRIVATE_FLAGS_MAX
) {
1049 set_detailed_error("Illegal private flags value.");
1050 return RaiseError(QUIC_INVALID_PACKET_HEADER
);
1053 header
->entropy_flag
= (private_flags
& PACKET_PRIVATE_FLAGS_ENTROPY
) != 0;
1054 header
->fec_flag
= (private_flags
& PACKET_PRIVATE_FLAGS_FEC
) != 0;
1056 if ((private_flags
& PACKET_PRIVATE_FLAGS_FEC_GROUP
) != 0) {
1057 header
->is_in_fec_group
= IN_FEC_GROUP
;
1058 uint8 first_fec_protected_packet_offset
;
1059 if (!reader
->ReadBytes(&first_fec_protected_packet_offset
, 1)) {
1060 set_detailed_error("Unable to read first fec protected packet offset.");
1061 return RaiseError(QUIC_INVALID_PACKET_HEADER
);
1063 if (first_fec_protected_packet_offset
>= header
->packet_sequence_number
) {
1064 set_detailed_error("First fec protected packet offset must be less "
1065 "than the sequence number.");
1066 return RaiseError(QUIC_INVALID_PACKET_HEADER
);
1069 header
->packet_sequence_number
- first_fec_protected_packet_offset
;
1072 header
->entropy_hash
= GetPacketEntropyHash(*header
);
1073 // Set the last sequence number after we have decrypted the packet
1074 // so we are confident is not attacker controlled.
1075 last_sequence_number_
= header
->packet_sequence_number
;
1079 bool QuicFramer::ProcessPacketSequenceNumber(
1080 QuicDataReader
* reader
,
1081 QuicSequenceNumberLength sequence_number_length
,
1082 QuicPacketSequenceNumber
* sequence_number
) {
1083 QuicPacketSequenceNumber wire_sequence_number
= 0u;
1084 if (!reader
->ReadBytes(&wire_sequence_number
, sequence_number_length
)) {
1088 // TODO(ianswett): Explore the usefulness of trying multiple sequence numbers
1089 // in case the first guess is incorrect.
1091 CalculatePacketSequenceNumberFromWire(sequence_number_length
,
1092 wire_sequence_number
);
1096 bool QuicFramer::ProcessFrameData(QuicDataReader
* reader
,
1097 const QuicPacketHeader
& header
) {
1098 if (reader
->IsDoneReading()) {
1099 set_detailed_error("Packet has no frames.");
1100 return RaiseError(QUIC_MISSING_PAYLOAD
);
1102 while (!reader
->IsDoneReading()) {
1104 if (!reader
->ReadBytes(&frame_type
, 1)) {
1105 set_detailed_error("Unable to read frame type.");
1106 return RaiseError(QUIC_INVALID_FRAME_DATA
);
1109 if (frame_type
& kQuicFrameTypeSpecialMask
) {
1111 if (frame_type
& kQuicFrameTypeStreamMask
) {
1112 QuicStreamFrame frame
;
1113 if (!ProcessStreamFrame(reader
, frame_type
, &frame
)) {
1114 return RaiseError(QUIC_INVALID_STREAM_DATA
);
1116 if (!visitor_
->OnStreamFrame(frame
)) {
1117 DVLOG(1) << "Visitor asked to stop further processing.";
1118 // Returning true since there was no parsing error.
1125 if (frame_type
& kQuicFrameTypeAckMask
) {
1127 if (!ProcessAckFrame(reader
, frame_type
, &frame
)) {
1128 return RaiseError(QUIC_INVALID_ACK_DATA
);
1130 if (!visitor_
->OnAckFrame(frame
)) {
1131 DVLOG(1) << "Visitor asked to stop further processing.";
1132 // Returning true since there was no parsing error.
1138 // This was a special frame type that did not match any
1139 // of the known ones. Error.
1140 set_detailed_error("Illegal frame type.");
1141 DLOG(WARNING
) << "Illegal frame type: "
1142 << static_cast<int>(frame_type
);
1143 return RaiseError(QUIC_INVALID_FRAME_DATA
);
1146 switch (frame_type
) {
1148 // We're done with the packet.
1151 case RST_STREAM_FRAME
: {
1152 QuicRstStreamFrame frame
;
1153 if (!ProcessRstStreamFrame(reader
, &frame
)) {
1154 return RaiseError(QUIC_INVALID_RST_STREAM_DATA
);
1156 if (!visitor_
->OnRstStreamFrame(frame
)) {
1157 DVLOG(1) << "Visitor asked to stop further processing.";
1158 // Returning true since there was no parsing error.
1164 case CONNECTION_CLOSE_FRAME
: {
1165 QuicConnectionCloseFrame frame
;
1166 if (!ProcessConnectionCloseFrame(reader
, &frame
)) {
1167 return RaiseError(QUIC_INVALID_CONNECTION_CLOSE_DATA
);
1170 if (!visitor_
->OnConnectionCloseFrame(frame
)) {
1171 DVLOG(1) << "Visitor asked to stop further processing.";
1172 // Returning true since there was no parsing error.
1178 case GOAWAY_FRAME
: {
1179 QuicGoAwayFrame goaway_frame
;
1180 if (!ProcessGoAwayFrame(reader
, &goaway_frame
)) {
1181 return RaiseError(QUIC_INVALID_GOAWAY_DATA
);
1183 if (!visitor_
->OnGoAwayFrame(goaway_frame
)) {
1184 DVLOG(1) << "Visitor asked to stop further processing.";
1185 // Returning true since there was no parsing error.
1191 case WINDOW_UPDATE_FRAME
: {
1192 QuicWindowUpdateFrame window_update_frame
;
1193 if (!ProcessWindowUpdateFrame(reader
, &window_update_frame
)) {
1194 return RaiseError(QUIC_INVALID_WINDOW_UPDATE_DATA
);
1196 if (!visitor_
->OnWindowUpdateFrame(window_update_frame
)) {
1197 DVLOG(1) << "Visitor asked to stop further processing.";
1198 // Returning true since there was no parsing error.
1204 case BLOCKED_FRAME
: {
1205 QuicBlockedFrame blocked_frame
;
1206 if (!ProcessBlockedFrame(reader
, &blocked_frame
)) {
1207 return RaiseError(QUIC_INVALID_BLOCKED_DATA
);
1209 if (!visitor_
->OnBlockedFrame(blocked_frame
)) {
1210 DVLOG(1) << "Visitor asked to stop further processing.";
1211 // Returning true since there was no parsing error.
1217 case STOP_WAITING_FRAME
: {
1218 QuicStopWaitingFrame stop_waiting_frame
;
1219 if (!ProcessStopWaitingFrame(reader
, header
, &stop_waiting_frame
)) {
1220 return RaiseError(QUIC_INVALID_STOP_WAITING_DATA
);
1222 if (!visitor_
->OnStopWaitingFrame(stop_waiting_frame
)) {
1223 DVLOG(1) << "Visitor asked to stop further processing.";
1224 // Returning true since there was no parsing error.
1230 // Ping has no payload.
1231 QuicPingFrame ping_frame
;
1232 if (!visitor_
->OnPingFrame(ping_frame
)) {
1233 DVLOG(1) << "Visitor asked to stop further processing.";
1234 // Returning true since there was no parsing error.
1241 set_detailed_error("Illegal frame type.");
1242 DLOG(WARNING
) << "Illegal frame type: "
1243 << static_cast<int>(frame_type
);
1244 return RaiseError(QUIC_INVALID_FRAME_DATA
);
1251 bool QuicFramer::ProcessStreamFrame(QuicDataReader
* reader
,
1253 QuicStreamFrame
* frame
) {
1254 uint8 stream_flags
= frame_type
;
1256 stream_flags
&= ~kQuicFrameTypeStreamMask
;
1258 // Read from right to left: StreamID, Offset, Data Length, Fin.
1259 const uint8 stream_id_length
= (stream_flags
& kQuicStreamIDLengthMask
) + 1;
1260 stream_flags
>>= kQuicStreamIdShift
;
1262 uint8 offset_length
= (stream_flags
& kQuicStreamOffsetMask
);
1263 // There is no encoding for 1 byte, only 0 and 2 through 8.
1264 if (offset_length
> 0) {
1267 stream_flags
>>= kQuicStreamOffsetShift
;
1269 bool has_data_length
=
1270 (stream_flags
& kQuicStreamDataLengthMask
) == kQuicStreamDataLengthMask
;
1271 stream_flags
>>= kQuicStreamDataLengthShift
;
1273 frame
->fin
= (stream_flags
& kQuicStreamFinMask
) == kQuicStreamFinShift
;
1275 frame
->stream_id
= 0;
1276 if (!reader
->ReadBytes(&frame
->stream_id
, stream_id_length
)) {
1277 set_detailed_error("Unable to read stream_id.");
1282 if (!reader
->ReadBytes(&frame
->offset
, offset_length
)) {
1283 set_detailed_error("Unable to read offset.");
1287 if (has_data_length
) {
1288 if (!reader
->ReadStringPiece16(&frame
->data
)) {
1289 set_detailed_error("Unable to read frame data.");
1293 if (!reader
->ReadStringPiece(&frame
->data
, reader
->BytesRemaining())) {
1294 set_detailed_error("Unable to read frame data.");
1302 bool QuicFramer::ProcessAckFrame(QuicDataReader
* reader
,
1304 QuicAckFrame
* ack_frame
) {
1305 // Determine the three lengths from the frame type: largest observed length,
1306 // missing sequence number length, and missing range length.
1307 const QuicSequenceNumberLength missing_sequence_number_length
=
1308 ReadSequenceNumberLength(frame_type
);
1309 frame_type
>>= kQuicSequenceNumberLengthShift
;
1310 const QuicSequenceNumberLength largest_observed_sequence_number_length
=
1311 ReadSequenceNumberLength(frame_type
);
1312 frame_type
>>= kQuicSequenceNumberLengthShift
;
1313 ack_frame
->is_truncated
= frame_type
& kQuicAckTruncatedMask
;
1314 frame_type
>>= kQuicAckTruncatedShift
;
1315 bool has_nacks
= frame_type
& kQuicHasNacksMask
;
1317 if (!reader
->ReadBytes(&ack_frame
->entropy_hash
, 1)) {
1318 set_detailed_error("Unable to read entropy hash for received packets.");
1322 if (!reader
->ReadBytes(&ack_frame
->largest_observed
,
1323 largest_observed_sequence_number_length
)) {
1324 set_detailed_error("Unable to read largest observed.");
1328 uint64 delta_time_largest_observed_us
;
1329 if (!reader
->ReadUFloat16(&delta_time_largest_observed_us
)) {
1330 set_detailed_error("Unable to read delta time largest observed.");
1334 if (delta_time_largest_observed_us
== kUFloat16MaxValue
) {
1335 ack_frame
->delta_time_largest_observed
= QuicTime::Delta::Infinite();
1337 ack_frame
->delta_time_largest_observed
=
1338 QuicTime::Delta::FromMicroseconds(delta_time_largest_observed_us
);
1341 if (!ProcessTimestampsInAckFrame(reader
, ack_frame
)) {
1349 uint8 num_missing_ranges
;
1350 if (!reader
->ReadBytes(&num_missing_ranges
, 1)) {
1351 set_detailed_error("Unable to read num missing packet ranges.");
1355 QuicPacketSequenceNumber last_sequence_number
= ack_frame
->largest_observed
;
1356 for (size_t i
= 0; i
< num_missing_ranges
; ++i
) {
1357 QuicPacketSequenceNumber missing_delta
= 0;
1358 if (!reader
->ReadBytes(&missing_delta
, missing_sequence_number_length
)) {
1359 set_detailed_error("Unable to read missing sequence number delta.");
1362 last_sequence_number
-= missing_delta
;
1363 QuicPacketSequenceNumber range_length
= 0;
1364 if (!reader
->ReadBytes(&range_length
, PACKET_1BYTE_SEQUENCE_NUMBER
)) {
1365 set_detailed_error("Unable to read missing sequence number range.");
1368 for (size_t j
= 0; j
<= range_length
; ++j
) {
1369 ack_frame
->missing_packets
.insert(last_sequence_number
- j
);
1371 // Subtract an extra 1 to ensure ranges are represented efficiently and
1372 // can't overlap by 1 sequence number. This allows a missing_delta of 0
1373 // to represent an adjacent nack range.
1374 last_sequence_number
-= (range_length
+ 1);
1377 // Parse the revived packets list.
1378 uint8 num_revived_packets
;
1379 if (!reader
->ReadBytes(&num_revived_packets
, 1)) {
1380 set_detailed_error("Unable to read num revived packets.");
1384 for (size_t i
= 0; i
< num_revived_packets
; ++i
) {
1385 QuicPacketSequenceNumber revived_packet
= 0;
1386 if (!reader
->ReadBytes(&revived_packet
,
1387 largest_observed_sequence_number_length
)) {
1388 set_detailed_error("Unable to read revived packet.");
1392 ack_frame
->revived_packets
.insert(revived_packet
);
1398 bool QuicFramer::ProcessTimestampsInAckFrame(QuicDataReader
* reader
,
1399 QuicAckFrame
* ack_frame
) {
1400 if (ack_frame
->is_truncated
) {
1403 uint8 num_received_packets
;
1404 if (!reader
->ReadBytes(&num_received_packets
, 1)) {
1405 set_detailed_error("Unable to read num received packets.");
1409 if (num_received_packets
> 0) {
1410 uint8 delta_from_largest_observed
;
1411 if (!reader
->ReadBytes(&delta_from_largest_observed
,
1412 PACKET_1BYTE_SEQUENCE_NUMBER
)) {
1413 set_detailed_error("Unable to read sequence delta in received packets.");
1416 QuicPacketSequenceNumber seq_num
=
1417 ack_frame
->largest_observed
- delta_from_largest_observed
;
1419 // Time delta from the framer creation.
1420 uint32 time_delta_us
;
1421 if (!reader
->ReadBytes(&time_delta_us
, sizeof(time_delta_us
))) {
1422 set_detailed_error("Unable to read time delta in received packets.");
1426 last_timestamp_
= CalculateTimestampFromWire(time_delta_us
);
1428 ack_frame
->received_packet_times
.push_back(
1429 std::make_pair(seq_num
, creation_time_
.Add(last_timestamp_
)));
1431 for (uint8 i
= 1; i
< num_received_packets
; ++i
) {
1432 if (!reader
->ReadBytes(&delta_from_largest_observed
,
1433 PACKET_1BYTE_SEQUENCE_NUMBER
)) {
1435 "Unable to read sequence delta in received packets.");
1438 seq_num
= ack_frame
->largest_observed
- delta_from_largest_observed
;
1440 // Time delta from the previous timestamp.
1441 uint64 incremental_time_delta_us
;
1442 if (!reader
->ReadUFloat16(&incremental_time_delta_us
)) {
1444 "Unable to read incremental time delta in received packets.");
1448 last_timestamp_
= last_timestamp_
.Add(
1449 QuicTime::Delta::FromMicroseconds(incremental_time_delta_us
));
1450 ack_frame
->received_packet_times
.push_back(
1451 std::make_pair(seq_num
, creation_time_
.Add(last_timestamp_
)));
1457 bool QuicFramer::ProcessStopWaitingFrame(QuicDataReader
* reader
,
1458 const QuicPacketHeader
& header
,
1459 QuicStopWaitingFrame
* stop_waiting
) {
1460 if (!reader
->ReadBytes(&stop_waiting
->entropy_hash
, 1)) {
1461 set_detailed_error("Unable to read entropy hash for sent packets.");
1465 QuicPacketSequenceNumber least_unacked_delta
= 0;
1466 if (!reader
->ReadBytes(&least_unacked_delta
,
1467 header
.public_header
.sequence_number_length
)) {
1468 set_detailed_error("Unable to read least unacked delta.");
1471 DCHECK_GE(header
.packet_sequence_number
, least_unacked_delta
);
1472 stop_waiting
->least_unacked
=
1473 header
.packet_sequence_number
- least_unacked_delta
;
1478 bool QuicFramer::ProcessRstStreamFrame(QuicDataReader
* reader
,
1479 QuicRstStreamFrame
* frame
) {
1480 if (!reader
->ReadUInt32(&frame
->stream_id
)) {
1481 set_detailed_error("Unable to read stream_id.");
1485 if (!reader
->ReadUInt64(&frame
->byte_offset
)) {
1486 set_detailed_error("Unable to read rst stream sent byte offset.");
1491 if (!reader
->ReadUInt32(&error_code
)) {
1492 set_detailed_error("Unable to read rst stream error code.");
1496 if (error_code
>= QUIC_STREAM_LAST_ERROR
) {
1497 set_detailed_error("Invalid rst stream error code.");
1501 frame
->error_code
= static_cast<QuicRstStreamErrorCode
>(error_code
);
1502 if (quic_version_
<= QUIC_VERSION_24
) {
1503 StringPiece error_details
;
1504 if (!reader
->ReadStringPiece16(&error_details
)) {
1505 set_detailed_error("Unable to read rst stream error details.");
1508 frame
->error_details
= error_details
.as_string();
1514 bool QuicFramer::ProcessConnectionCloseFrame(QuicDataReader
* reader
,
1515 QuicConnectionCloseFrame
* frame
) {
1517 if (!reader
->ReadUInt32(&error_code
)) {
1518 set_detailed_error("Unable to read connection close error code.");
1522 if (error_code
>= QUIC_LAST_ERROR
) {
1523 set_detailed_error("Invalid error code.");
1527 frame
->error_code
= static_cast<QuicErrorCode
>(error_code
);
1529 StringPiece error_details
;
1530 if (!reader
->ReadStringPiece16(&error_details
)) {
1531 set_detailed_error("Unable to read connection close error details.");
1534 frame
->error_details
= error_details
.as_string();
1539 bool QuicFramer::ProcessGoAwayFrame(QuicDataReader
* reader
,
1540 QuicGoAwayFrame
* frame
) {
1542 if (!reader
->ReadUInt32(&error_code
)) {
1543 set_detailed_error("Unable to read go away error code.");
1546 frame
->error_code
= static_cast<QuicErrorCode
>(error_code
);
1548 if (error_code
>= QUIC_LAST_ERROR
) {
1549 set_detailed_error("Invalid error code.");
1554 if (!reader
->ReadUInt32(&stream_id
)) {
1555 set_detailed_error("Unable to read last good stream id.");
1558 frame
->last_good_stream_id
= static_cast<QuicStreamId
>(stream_id
);
1560 StringPiece reason_phrase
;
1561 if (!reader
->ReadStringPiece16(&reason_phrase
)) {
1562 set_detailed_error("Unable to read goaway reason.");
1565 frame
->reason_phrase
= reason_phrase
.as_string();
1570 bool QuicFramer::ProcessWindowUpdateFrame(QuicDataReader
* reader
,
1571 QuicWindowUpdateFrame
* frame
) {
1572 if (!reader
->ReadUInt32(&frame
->stream_id
)) {
1573 set_detailed_error("Unable to read stream_id.");
1577 if (!reader
->ReadUInt64(&frame
->byte_offset
)) {
1578 set_detailed_error("Unable to read window byte_offset.");
1585 bool QuicFramer::ProcessBlockedFrame(QuicDataReader
* reader
,
1586 QuicBlockedFrame
* frame
) {
1587 if (!reader
->ReadUInt32(&frame
->stream_id
)) {
1588 set_detailed_error("Unable to read stream_id.");
1596 StringPiece
QuicFramer::GetAssociatedDataFromEncryptedPacket(
1597 const QuicEncryptedPacket
& encrypted
,
1598 QuicConnectionIdLength connection_id_length
,
1599 bool includes_version
,
1600 QuicSequenceNumberLength sequence_number_length
) {
1602 encrypted
.data() + kStartOfHashData
, GetStartOfEncryptedData(
1603 connection_id_length
, includes_version
, sequence_number_length
)
1604 - kStartOfHashData
);
1607 void QuicFramer::SetDecrypter(EncryptionLevel level
, QuicDecrypter
* decrypter
) {
1608 DCHECK(alternative_decrypter_
.get() == nullptr);
1609 DCHECK_GE(level
, decrypter_level_
);
1610 decrypter_
.reset(decrypter
);
1611 decrypter_level_
= level
;
1614 void QuicFramer::SetAlternativeDecrypter(EncryptionLevel level
,
1615 QuicDecrypter
* decrypter
,
1616 bool latch_once_used
) {
1617 alternative_decrypter_
.reset(decrypter
);
1618 alternative_decrypter_level_
= level
;
1619 alternative_decrypter_latch_
= latch_once_used
;
1622 const QuicDecrypter
* QuicFramer::decrypter() const {
1623 return decrypter_
.get();
1626 const QuicDecrypter
* QuicFramer::alternative_decrypter() const {
1627 return alternative_decrypter_
.get();
1630 void QuicFramer::SetEncrypter(EncryptionLevel level
,
1631 QuicEncrypter
* encrypter
) {
1632 DCHECK_GE(level
, 0);
1633 DCHECK_LT(level
, NUM_ENCRYPTION_LEVELS
);
1634 encrypter_
[level
].reset(encrypter
);
1637 QuicEncryptedPacket
* QuicFramer::EncryptPayload(
1638 EncryptionLevel level
,
1639 QuicPacketSequenceNumber packet_sequence_number
,
1640 const QuicPacket
& packet
,
1642 size_t buffer_len
) {
1643 DCHECK(encrypter_
[level
].get() != nullptr);
1645 const size_t encrypted_len
=
1646 encrypter_
[level
]->GetCiphertextSize(packet
.Plaintext().length());
1647 StringPiece header_data
= packet
.BeforePlaintext();
1648 const size_t total_len
= header_data
.length() + encrypted_len
;
1650 char* encryption_buffer
= buffer
;
1651 // Allocate a large enough buffer for the header and the encrypted data.
1652 const bool is_new_buffer
= total_len
> buffer_len
;
1653 if (is_new_buffer
) {
1654 if (!FLAGS_quic_allow_oversized_packets_for_test
) {
1655 LOG(DFATAL
) << "Buffer of length:" << buffer_len
1656 << " is not large enough to encrypt length " << total_len
;
1659 encryption_buffer
= new char[total_len
];
1661 // Copy in the header, because the encrypter only populates the encrypted
1662 // plaintext content.
1663 memcpy(encryption_buffer
, header_data
.data(), header_data
.length());
1664 // Encrypt the plaintext into the buffer.
1665 size_t output_length
= 0;
1666 if (!encrypter_
[level
]->EncryptPacket(
1667 packet_sequence_number
, packet
.AssociatedData(), packet
.Plaintext(),
1668 encryption_buffer
+ header_data
.length(), &output_length
,
1670 RaiseError(QUIC_ENCRYPTION_FAILURE
);
1674 return new QuicEncryptedPacket(
1675 encryption_buffer
, header_data
.length() + output_length
, is_new_buffer
);
1678 size_t QuicFramer::GetMaxPlaintextSize(size_t ciphertext_size
) {
1679 // In order to keep the code simple, we don't have the current encryption
1680 // level to hand. Both the NullEncrypter and AES-GCM have a tag length of 12.
1681 size_t min_plaintext_size
= ciphertext_size
;
1683 for (int i
= ENCRYPTION_NONE
; i
< NUM_ENCRYPTION_LEVELS
; i
++) {
1684 if (encrypter_
[i
].get() != nullptr) {
1685 size_t size
= encrypter_
[i
]->GetMaxPlaintextSize(ciphertext_size
);
1686 if (size
< min_plaintext_size
) {
1687 min_plaintext_size
= size
;
1692 return min_plaintext_size
;
1695 bool QuicFramer::DecryptPayload(QuicDataReader
* encrypted_reader
,
1696 const QuicPacketHeader
& header
,
1697 const QuicEncryptedPacket
& packet
,
1698 char* decrypted_buffer
,
1699 size_t buffer_length
,
1700 size_t* decrypted_length
) {
1701 StringPiece encrypted
= encrypted_reader
->ReadRemainingPayload();
1702 DCHECK(decrypter_
.get() != nullptr);
1703 const StringPiece
& associated_data
= GetAssociatedDataFromEncryptedPacket(
1704 packet
, header
.public_header
.connection_id_length
,
1705 header
.public_header
.version_flag
,
1706 header
.public_header
.sequence_number_length
);
1707 bool success
= decrypter_
->DecryptPacket(
1708 header
.packet_sequence_number
, associated_data
, encrypted
,
1709 decrypted_buffer
, decrypted_length
, buffer_length
);
1711 visitor_
->OnDecryptedPacket(decrypter_level_
);
1712 } else if (alternative_decrypter_
.get() != nullptr) {
1713 success
= alternative_decrypter_
->DecryptPacket(
1714 header
.packet_sequence_number
, associated_data
, encrypted
,
1715 decrypted_buffer
, decrypted_length
, buffer_length
);
1717 visitor_
->OnDecryptedPacket(alternative_decrypter_level_
);
1718 if (alternative_decrypter_latch_
) {
1719 // Switch to the alternative decrypter and latch so that we cannot
1721 decrypter_
.reset(alternative_decrypter_
.release());
1722 decrypter_level_
= alternative_decrypter_level_
;
1723 alternative_decrypter_level_
= ENCRYPTION_NONE
;
1725 // Switch the alternative decrypter so that we use it first next time.
1726 decrypter_
.swap(alternative_decrypter_
);
1727 EncryptionLevel level
= alternative_decrypter_level_
;
1728 alternative_decrypter_level_
= decrypter_level_
;
1729 decrypter_level_
= level
;
1735 DLOG(WARNING
) << "DecryptPacket failed for sequence_number:"
1736 << header
.packet_sequence_number
;
1743 size_t QuicFramer::GetAckFrameSize(
1744 const QuicAckFrame
& ack
,
1745 QuicSequenceNumberLength sequence_number_length
) {
1746 AckFrameInfo ack_info
= GetAckFrameInfo(ack
);
1747 QuicSequenceNumberLength largest_observed_length
=
1748 GetMinSequenceNumberLength(ack
.largest_observed
);
1749 QuicSequenceNumberLength missing_sequence_number_length
=
1750 GetMinSequenceNumberLength(ack_info
.max_delta
);
1752 size_t ack_size
= GetMinAckFrameSize(largest_observed_length
);
1753 if (!ack_info
.nack_ranges
.empty()) {
1754 ack_size
+= kNumberOfNackRangesSize
+ kNumberOfRevivedPacketsSize
;
1755 ack_size
+= min(ack_info
.nack_ranges
.size(), kMaxNackRanges
) *
1756 (missing_sequence_number_length
+ PACKET_1BYTE_SEQUENCE_NUMBER
);
1757 ack_size
+= min(ack
.revived_packets
.size(),
1758 kMaxRevivedPackets
) * largest_observed_length
;
1761 // In version 23, if the ack will be truncated due to too many nack ranges,
1762 // then do not include the number of timestamps (1 byte).
1763 if (ack_info
.nack_ranges
.size() <= kMaxNackRanges
) {
1764 // 1 byte for the number of timestamps.
1766 if (ack
.received_packet_times
.size() > 0) {
1767 // 1 byte for sequence number, 4 bytes for timestamp for the first
1771 // 1 byte for sequence number, 2 bytes for timestamp for the other
1773 ack_size
+= 3 * (ack
.received_packet_times
.size() - 1);
1780 size_t QuicFramer::ComputeFrameLength(
1781 const QuicFrame
& frame
,
1782 bool last_frame_in_packet
,
1783 InFecGroup is_in_fec_group
,
1784 QuicSequenceNumberLength sequence_number_length
) {
1785 switch (frame
.type
) {
1787 return GetMinStreamFrameSize(frame
.stream_frame
->stream_id
,
1788 frame
.stream_frame
->offset
,
1789 last_frame_in_packet
, is_in_fec_group
) +
1790 frame
.stream_frame
->data
.length();
1792 return GetAckFrameSize(*frame
.ack_frame
, sequence_number_length
);
1794 case STOP_WAITING_FRAME
:
1795 return GetStopWaitingFrameSize(sequence_number_length
);
1796 case MTU_DISCOVERY_FRAME
:
1797 // MTU discovery frames are serialized as ping frames.
1799 // Ping has no payload.
1800 return kQuicFrameTypeSize
;
1801 case RST_STREAM_FRAME
:
1802 if (quic_version_
<= QUIC_VERSION_24
) {
1803 return GetMinRstStreamFrameSize() +
1804 frame
.rst_stream_frame
->error_details
.size();
1806 return GetRstStreamFrameSize();
1807 case CONNECTION_CLOSE_FRAME
:
1808 return GetMinConnectionCloseFrameSize() +
1809 frame
.connection_close_frame
->error_details
.size();
1811 return GetMinGoAwayFrameSize() + frame
.goaway_frame
->reason_phrase
.size();
1812 case WINDOW_UPDATE_FRAME
:
1813 return GetWindowUpdateFrameSize();
1815 return GetBlockedFrameSize();
1819 case NUM_FRAME_TYPES
:
1824 // Not reachable, but some Chrome compilers can't figure that out. *sigh*
1829 bool QuicFramer::AppendTypeByte(const QuicFrame
& frame
,
1830 bool no_stream_frame_length
,
1831 QuicDataWriter
* writer
) {
1832 uint8 type_byte
= 0;
1833 switch (frame
.type
) {
1834 case STREAM_FRAME
: {
1835 if (frame
.stream_frame
== nullptr) {
1836 LOG(DFATAL
) << "Failed to append STREAM frame with no stream_frame.";
1839 type_byte
|= frame
.stream_frame
->fin
? kQuicStreamFinMask
: 0;
1842 type_byte
<<= kQuicStreamDataLengthShift
;
1843 type_byte
|= no_stream_frame_length
? 0: kQuicStreamDataLengthMask
;
1846 type_byte
<<= kQuicStreamOffsetShift
;
1847 const size_t offset_len
= GetStreamOffsetSize(frame
.stream_frame
->offset
);
1848 if (offset_len
> 0) {
1849 type_byte
|= offset_len
- 1;
1852 // stream id 2 bits.
1853 type_byte
<<= kQuicStreamIdShift
;
1854 type_byte
|= GetStreamIdSize(frame
.stream_frame
->stream_id
) - 1;
1855 type_byte
|= kQuicFrameTypeStreamMask
; // Set Stream Frame Type to 1.
1860 case MTU_DISCOVERY_FRAME
:
1861 type_byte
= static_cast<uint8
>(PING_FRAME
);
1864 type_byte
= static_cast<uint8
>(frame
.type
);
1868 return writer
->WriteUInt8(type_byte
);
1872 bool QuicFramer::AppendPacketSequenceNumber(
1873 QuicSequenceNumberLength sequence_number_length
,
1874 QuicPacketSequenceNumber packet_sequence_number
,
1875 QuicDataWriter
* writer
) {
1876 // Ensure the entire sequence number can be written.
1877 if (writer
->capacity() - writer
->length() <
1878 static_cast<size_t>(sequence_number_length
)) {
1881 switch (sequence_number_length
) {
1882 case PACKET_1BYTE_SEQUENCE_NUMBER
:
1883 return writer
->WriteUInt8(
1884 packet_sequence_number
& k1ByteSequenceNumberMask
);
1886 case PACKET_2BYTE_SEQUENCE_NUMBER
:
1887 return writer
->WriteUInt16(
1888 packet_sequence_number
& k2ByteSequenceNumberMask
);
1890 case PACKET_4BYTE_SEQUENCE_NUMBER
:
1891 return writer
->WriteUInt32(
1892 packet_sequence_number
& k4ByteSequenceNumberMask
);
1894 case PACKET_6BYTE_SEQUENCE_NUMBER
:
1895 return writer
->WriteUInt48(
1896 packet_sequence_number
& k6ByteSequenceNumberMask
);
1899 DCHECK(false) << "sequence_number_length: " << sequence_number_length
;
1904 bool QuicFramer::AppendStreamFrame(
1905 const QuicStreamFrame
& frame
,
1906 bool no_stream_frame_length
,
1907 QuicDataWriter
* writer
) {
1908 if (!writer
->WriteBytes(&frame
.stream_id
, GetStreamIdSize(frame
.stream_id
))) {
1909 LOG(DFATAL
) << "Writing stream id size failed.";
1912 if (!writer
->WriteBytes(&frame
.offset
, GetStreamOffsetSize(frame
.offset
))) {
1913 LOG(DFATAL
) << "Writing offset size failed.";
1916 if (!no_stream_frame_length
) {
1917 if ((frame
.data
.size() > numeric_limits
<uint16
>::max()) ||
1918 !writer
->WriteUInt16(static_cast<uint16
>(frame
.data
.size()))) {
1919 LOG(DFATAL
) << "Writing stream frame length failed";
1924 if (!writer
->WriteBytes(frame
.data
.data(), frame
.data
.size())) {
1925 LOG(DFATAL
) << "Writing frame data failed.";
1931 void QuicFramer::set_version(const QuicVersion version
) {
1932 DCHECK(IsSupportedVersion(version
)) << QuicVersionToString(version
);
1933 quic_version_
= version
;
1936 bool QuicFramer::AppendAckFrameAndTypeByte(
1937 const QuicPacketHeader
& header
,
1938 const QuicAckFrame
& frame
,
1939 QuicDataWriter
* writer
) {
1940 AckFrameInfo ack_info
= GetAckFrameInfo(frame
);
1941 QuicPacketSequenceNumber ack_largest_observed
= frame
.largest_observed
;
1942 QuicSequenceNumberLength largest_observed_length
=
1943 GetMinSequenceNumberLength(ack_largest_observed
);
1944 QuicSequenceNumberLength missing_sequence_number_length
=
1945 GetMinSequenceNumberLength(ack_info
.max_delta
);
1946 // Determine whether we need to truncate ranges.
1947 size_t available_range_bytes
=
1948 writer
->capacity() - writer
->length() - kNumberOfRevivedPacketsSize
-
1949 kNumberOfNackRangesSize
- GetMinAckFrameSize(largest_observed_length
);
1950 size_t max_num_ranges
= available_range_bytes
/
1951 (missing_sequence_number_length
+ PACKET_1BYTE_SEQUENCE_NUMBER
);
1952 max_num_ranges
= min(kMaxNackRanges
, max_num_ranges
);
1953 bool truncated
= ack_info
.nack_ranges
.size() > max_num_ranges
;
1954 DVLOG_IF(1, truncated
) << "Truncating ack from "
1955 << ack_info
.nack_ranges
.size() << " ranges to "
1957 // Write out the type byte by setting the low order bits and doing shifts
1958 // to make room for the next bit flags to be set.
1959 // Whether there are any nacks.
1960 uint8 type_byte
= ack_info
.nack_ranges
.empty() ? 0 : kQuicHasNacksMask
;
1963 type_byte
<<= kQuicAckTruncatedShift
;
1964 type_byte
|= truncated
? kQuicAckTruncatedMask
: 0;
1966 // Largest observed sequence number length.
1967 type_byte
<<= kQuicSequenceNumberLengthShift
;
1968 type_byte
|= GetSequenceNumberFlags(largest_observed_length
);
1970 // Missing sequence number length.
1971 type_byte
<<= kQuicSequenceNumberLengthShift
;
1972 type_byte
|= GetSequenceNumberFlags(missing_sequence_number_length
);
1974 type_byte
|= kQuicFrameTypeAckMask
;
1976 if (!writer
->WriteUInt8(type_byte
)) {
1980 QuicPacketEntropyHash ack_entropy_hash
= frame
.entropy_hash
;
1981 NackRangeMap::reverse_iterator ack_iter
= ack_info
.nack_ranges
.rbegin();
1983 // Skip the nack ranges which the truncated ack won't include and set
1984 // a correct largest observed for the truncated ack.
1985 for (size_t i
= 1; i
< (ack_info
.nack_ranges
.size() - max_num_ranges
);
1989 // If the last range is followed by acks, include them.
1990 // If the last range is followed by another range, specify the end of the
1991 // range as the largest_observed.
1992 ack_largest_observed
= ack_iter
->first
- 1;
1993 // Also update the entropy so it matches the largest observed.
1994 ack_entropy_hash
= entropy_calculator_
->EntropyHash(ack_largest_observed
);
1998 if (!writer
->WriteUInt8(ack_entropy_hash
)) {
2002 if (!AppendPacketSequenceNumber(largest_observed_length
,
2003 ack_largest_observed
, writer
)) {
2007 uint64 delta_time_largest_observed_us
= kUFloat16MaxValue
;
2008 if (!frame
.delta_time_largest_observed
.IsInfinite()) {
2009 DCHECK_LE(0u, frame
.delta_time_largest_observed
.ToMicroseconds());
2010 delta_time_largest_observed_us
=
2011 frame
.delta_time_largest_observed
.ToMicroseconds();
2014 if (!writer
->WriteUFloat16(delta_time_largest_observed_us
)) {
2018 // Timestamp goes at the end of the required fields.
2020 if (!AppendTimestampToAckFrame(frame
, writer
)) {
2025 if (ack_info
.nack_ranges
.empty()) {
2029 const uint8 num_missing_ranges
=
2030 static_cast<uint8
>(min(ack_info
.nack_ranges
.size(), max_num_ranges
));
2031 if (!writer
->WriteBytes(&num_missing_ranges
, 1)) {
2035 int num_ranges_written
= 0;
2036 QuicPacketSequenceNumber last_sequence_written
= ack_largest_observed
;
2037 for (; ack_iter
!= ack_info
.nack_ranges
.rend(); ++ack_iter
) {
2038 // Calculate the delta to the last number in the range.
2039 QuicPacketSequenceNumber missing_delta
=
2040 last_sequence_written
- (ack_iter
->first
+ ack_iter
->second
);
2041 if (!AppendPacketSequenceNumber(missing_sequence_number_length
,
2042 missing_delta
, writer
)) {
2045 if (!AppendPacketSequenceNumber(PACKET_1BYTE_SEQUENCE_NUMBER
,
2046 ack_iter
->second
, writer
)) {
2049 // Subtract 1 so a missing_delta of 0 means an adjacent range.
2050 last_sequence_written
= ack_iter
->first
- 1;
2051 ++num_ranges_written
;
2053 DCHECK_EQ(num_missing_ranges
, num_ranges_written
);
2055 // Append revived packets.
2056 // If not all the revived packets fit, only mention the ones that do.
2057 uint8 num_revived_packets
=
2058 static_cast<uint8
>(min(frame
.revived_packets
.size(), kMaxRevivedPackets
));
2059 num_revived_packets
= static_cast<uint8
>(min(
2060 static_cast<size_t>(num_revived_packets
),
2061 (writer
->capacity() - writer
->length()) / largest_observed_length
));
2062 if (!writer
->WriteBytes(&num_revived_packets
, 1)) {
2066 SequenceNumberSet::const_iterator iter
= frame
.revived_packets
.begin();
2067 for (int i
= 0; i
< num_revived_packets
; ++i
, ++iter
) {
2068 LOG_IF(DFATAL
, !ContainsKey(frame
.missing_packets
, *iter
));
2069 if (!AppendPacketSequenceNumber(largest_observed_length
,
2078 bool QuicFramer::AppendTimestampToAckFrame(const QuicAckFrame
& frame
,
2079 QuicDataWriter
* writer
) {
2080 DCHECK_GE(numeric_limits
<uint8
>::max(), frame
.received_packet_times
.size());
2081 // num_received_packets is only 1 byte.
2082 if (frame
.received_packet_times
.size() > numeric_limits
<uint8
>::max()) {
2086 uint8 num_received_packets
= frame
.received_packet_times
.size();
2088 if (!writer
->WriteBytes(&num_received_packets
, 1)) {
2091 if (num_received_packets
== 0) {
2095 PacketTimeList::const_iterator it
= frame
.received_packet_times
.begin();
2096 QuicPacketSequenceNumber sequence_number
= it
->first
;
2097 QuicPacketSequenceNumber delta_from_largest_observed
=
2098 frame
.largest_observed
- sequence_number
;
2100 DCHECK_GE(numeric_limits
<uint8
>::max(), delta_from_largest_observed
);
2101 if (delta_from_largest_observed
> numeric_limits
<uint8
>::max()) {
2105 if (!writer
->WriteUInt8(
2106 delta_from_largest_observed
& k1ByteSequenceNumberMask
)) {
2110 // Use the lowest 4 bytes of the time delta from the creation_time_.
2111 const uint64 time_epoch_delta_us
= UINT64_C(1) << 32;
2112 uint32 time_delta_us
=
2113 static_cast<uint32
>(it
->second
.Subtract(creation_time_
).ToMicroseconds()
2114 & (time_epoch_delta_us
- 1));
2115 if (!writer
->WriteBytes(&time_delta_us
, sizeof(time_delta_us
))) {
2119 QuicTime prev_time
= it
->second
;
2121 for (++it
; it
!= frame
.received_packet_times
.end(); ++it
) {
2122 sequence_number
= it
->first
;
2123 delta_from_largest_observed
= frame
.largest_observed
- sequence_number
;
2125 if (delta_from_largest_observed
> numeric_limits
<uint8
>::max()) {
2129 if (!writer
->WriteUInt8(
2130 delta_from_largest_observed
& k1ByteSequenceNumberMask
)) {
2134 uint64 frame_time_delta_us
=
2135 it
->second
.Subtract(prev_time
).ToMicroseconds();
2136 prev_time
= it
->second
;
2137 if (!writer
->WriteUFloat16(frame_time_delta_us
)) {
2144 bool QuicFramer::AppendStopWaitingFrame(
2145 const QuicPacketHeader
& header
,
2146 const QuicStopWaitingFrame
& frame
,
2147 QuicDataWriter
* writer
) {
2148 DCHECK_GE(header
.packet_sequence_number
, frame
.least_unacked
);
2149 const QuicPacketSequenceNumber least_unacked_delta
=
2150 header
.packet_sequence_number
- frame
.least_unacked
;
2151 const QuicPacketSequenceNumber length_shift
=
2152 header
.public_header
.sequence_number_length
* 8;
2153 if (!writer
->WriteUInt8(frame
.entropy_hash
)) {
2154 LOG(DFATAL
) << " hash failed";
2158 if (least_unacked_delta
>> length_shift
> 0) {
2159 LOG(DFATAL
) << "sequence_number_length "
2160 << header
.public_header
.sequence_number_length
2161 << " is too small for least_unacked_delta: "
2162 << least_unacked_delta
;
2165 if (!AppendPacketSequenceNumber(header
.public_header
.sequence_number_length
,
2166 least_unacked_delta
, writer
)) {
2167 LOG(DFATAL
) << " seq failed: "
2168 << header
.public_header
.sequence_number_length
;
2175 bool QuicFramer::AppendRstStreamFrame(const QuicRstStreamFrame
& frame
,
2176 QuicDataWriter
* writer
) {
2177 if (!writer
->WriteUInt32(frame
.stream_id
)) {
2181 if (!writer
->WriteUInt64(frame
.byte_offset
)) {
2185 uint32 error_code
= static_cast<uint32
>(frame
.error_code
);
2186 if (!writer
->WriteUInt32(error_code
)) {
2190 if (quic_version_
<= QUIC_VERSION_24
) {
2191 if (!writer
->WriteStringPiece16(frame
.error_details
)) {
2198 bool QuicFramer::AppendConnectionCloseFrame(
2199 const QuicConnectionCloseFrame
& frame
,
2200 QuicDataWriter
* writer
) {
2201 uint32 error_code
= static_cast<uint32
>(frame
.error_code
);
2202 if (!writer
->WriteUInt32(error_code
)) {
2205 if (!writer
->WriteStringPiece16(frame
.error_details
)) {
2211 bool QuicFramer::AppendGoAwayFrame(const QuicGoAwayFrame
& frame
,
2212 QuicDataWriter
* writer
) {
2213 uint32 error_code
= static_cast<uint32
>(frame
.error_code
);
2214 if (!writer
->WriteUInt32(error_code
)) {
2217 uint32 stream_id
= static_cast<uint32
>(frame
.last_good_stream_id
);
2218 if (!writer
->WriteUInt32(stream_id
)) {
2221 if (!writer
->WriteStringPiece16(frame
.reason_phrase
)) {
2227 bool QuicFramer::AppendWindowUpdateFrame(const QuicWindowUpdateFrame
& frame
,
2228 QuicDataWriter
* writer
) {
2229 uint32 stream_id
= static_cast<uint32
>(frame
.stream_id
);
2230 if (!writer
->WriteUInt32(stream_id
)) {
2233 if (!writer
->WriteUInt64(frame
.byte_offset
)) {
2239 bool QuicFramer::AppendBlockedFrame(const QuicBlockedFrame
& frame
,
2240 QuicDataWriter
* writer
) {
2241 uint32 stream_id
= static_cast<uint32
>(frame
.stream_id
);
2242 if (!writer
->WriteUInt32(stream_id
)) {
2248 bool QuicFramer::RaiseError(QuicErrorCode error
) {
2249 DVLOG(1) << "Error: " << QuicUtils::ErrorToString(error
)
2250 << " detail: " << detailed_error_
;
2252 visitor_
->OnError(this);