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/compiler_specific.h"
11 #include "base/logging.h"
12 #include "base/stl_util.h"
13 #include "net/quic/crypto/crypto_framer.h"
14 #include "net/quic/crypto/crypto_handshake_message.h"
15 #include "net/quic/crypto/crypto_protocol.h"
16 #include "net/quic/crypto/quic_decrypter.h"
17 #include "net/quic/crypto/quic_encrypter.h"
18 #include "net/quic/quic_data_reader.h"
19 #include "net/quic/quic_data_writer.h"
20 #include "net/quic/quic_flags.h"
21 #include "net/quic/quic_socket_address_coder.h"
22 #include "net/quic/quic_utils.h"
24 using base::StringPiece
;
28 using std::numeric_limits
;
35 // Mask to select the lowest 48 bits of a packet number.
36 const QuicPacketNumber k6ByteSequenceNumberMask
= UINT64_C(0x0000FFFFFFFFFFFF);
37 const QuicPacketNumber k4ByteSequenceNumberMask
= UINT64_C(0x00000000FFFFFFFF);
38 const QuicPacketNumber k2ByteSequenceNumberMask
= UINT64_C(0x000000000000FFFF);
39 const QuicPacketNumber k1ByteSequenceNumberMask
= UINT64_C(0x00000000000000FF);
41 const QuicConnectionId k1ByteConnectionIdMask
= UINT64_C(0x00000000000000FF);
42 const QuicConnectionId k4ByteConnectionIdMask
= UINT64_C(0x00000000FFFFFFFF);
44 // Number of bits the packet number length bits are shifted from the right
45 // edge of the public header.
46 const uint8 kPublicHeaderSequenceNumberShift
= 4;
48 // New Frame Types, QUIC v. >= 10:
49 // There are two interpretations for the Frame Type byte in the QUIC protocol,
50 // resulting in two Frame Types: Special Frame Types and Regular Frame Types.
52 // Regular Frame Types use the Frame Type byte simply. Currently defined
53 // Regular Frame Types are:
54 // Padding : 0b 00000000 (0x00)
55 // ResetStream : 0b 00000001 (0x01)
56 // ConnectionClose : 0b 00000010 (0x02)
57 // GoAway : 0b 00000011 (0x03)
58 // WindowUpdate : 0b 00000100 (0x04)
59 // Blocked : 0b 00000101 (0x05)
61 // Special Frame Types encode both a Frame Type and corresponding flags
62 // all in the Frame Type byte. Currently defined Special Frame Types are:
63 // Stream : 0b 1xxxxxxx
66 // Semantics of the flag bits above (the x bits) depends on the frame type.
68 // Masks to determine if the frame type is a special use
69 // and for specific special frame types.
70 const uint8 kQuicFrameTypeSpecialMask
= 0xE0; // 0b 11100000
71 const uint8 kQuicFrameTypeStreamMask
= 0x80;
72 const uint8 kQuicFrameTypeAckMask
= 0x40;
74 // Stream frame relative shifts and masks for interpreting the stream flags.
75 // StreamID may be 1, 2, 3, or 4 bytes.
76 const uint8 kQuicStreamIdShift
= 2;
77 const uint8 kQuicStreamIDLengthMask
= 0x03;
79 // Offset may be 0, 2, 3, 4, 5, 6, 7, 8 bytes.
80 const uint8 kQuicStreamOffsetShift
= 3;
81 const uint8 kQuicStreamOffsetMask
= 0x07;
83 // Data length may be 0 or 2 bytes.
84 const uint8 kQuicStreamDataLengthShift
= 1;
85 const uint8 kQuicStreamDataLengthMask
= 0x01;
87 // Fin bit may be set or not.
88 const uint8 kQuicStreamFinShift
= 1;
89 const uint8 kQuicStreamFinMask
= 0x01;
91 // packet number size shift used in AckFrames.
92 const uint8 kQuicSequenceNumberLengthShift
= 2;
94 // Acks may be truncated.
95 const uint8 kQuicAckTruncatedShift
= 1;
96 const uint8 kQuicAckTruncatedMask
= 0x01;
98 // Acks may not have any nacks.
99 const uint8 kQuicHasNacksMask
= 0x01;
101 // Returns the absolute value of the difference between |a| and |b|.
102 QuicPacketNumber
Delta(QuicPacketNumber a
, QuicPacketNumber b
) {
103 // Since these are unsigned numbers, we can't just return abs(a - b)
110 QuicPacketNumber
ClosestTo(QuicPacketNumber target
,
112 QuicPacketNumber b
) {
113 return (Delta(target
, a
) < Delta(target
, b
)) ? a
: b
;
116 QuicPacketNumberLength
ReadSequenceNumberLength(uint8 flags
) {
117 switch (flags
& PACKET_FLAGS_6BYTE_PACKET
) {
118 case PACKET_FLAGS_6BYTE_PACKET
:
119 return PACKET_6BYTE_PACKET_NUMBER
;
120 case PACKET_FLAGS_4BYTE_PACKET
:
121 return PACKET_4BYTE_PACKET_NUMBER
;
122 case PACKET_FLAGS_2BYTE_PACKET
:
123 return PACKET_2BYTE_PACKET_NUMBER
;
124 case PACKET_FLAGS_1BYTE_PACKET
:
125 return PACKET_1BYTE_PACKET_NUMBER
;
127 LOG(DFATAL
) << "Unreachable case statement.";
128 return PACKET_6BYTE_PACKET_NUMBER
;
134 QuicFramer::QuicFramer(const QuicVersionVector
& supported_versions
,
135 QuicTime creation_time
,
136 Perspective perspective
)
138 entropy_calculator_(nullptr),
139 error_(QUIC_NO_ERROR
),
140 last_packet_number_(0),
141 last_serialized_connection_id_(0),
142 supported_versions_(supported_versions
),
143 decrypter_level_(ENCRYPTION_NONE
),
144 alternative_decrypter_level_(ENCRYPTION_NONE
),
145 alternative_decrypter_latch_(false),
146 perspective_(perspective
),
147 validate_flags_(true),
148 creation_time_(creation_time
),
149 last_timestamp_(QuicTime::Delta::Zero()) {
150 DCHECK(!supported_versions
.empty());
151 quic_version_
= supported_versions_
[0];
152 decrypter_
.reset(QuicDecrypter::Create(kNULL
));
153 encrypter_
[ENCRYPTION_NONE
].reset(QuicEncrypter::Create(kNULL
));
156 QuicFramer::~QuicFramer() {}
159 size_t QuicFramer::GetMinStreamFrameSize(QuicStreamId stream_id
,
160 QuicStreamOffset offset
,
161 bool last_frame_in_packet
,
162 InFecGroup is_in_fec_group
) {
163 bool no_stream_frame_length
= last_frame_in_packet
&&
164 is_in_fec_group
== NOT_IN_FEC_GROUP
;
165 return kQuicFrameTypeSize
+ GetStreamIdSize(stream_id
) +
166 GetStreamOffsetSize(offset
) +
167 (no_stream_frame_length
? 0 : kQuicStreamPayloadLengthSize
);
171 size_t QuicFramer::GetMinAckFrameSize(
172 QuicPacketNumberLength largest_observed_length
) {
173 return kQuicFrameTypeSize
+ kQuicEntropyHashSize
+
174 largest_observed_length
+ kQuicDeltaTimeLargestObservedSize
;
178 size_t QuicFramer::GetStopWaitingFrameSize(
179 QuicPacketNumberLength packet_number_length
) {
180 return kQuicFrameTypeSize
+ kQuicEntropyHashSize
+ packet_number_length
;
184 size_t QuicFramer::GetMinRstStreamFrameSize() {
185 return kQuicFrameTypeSize
+ kQuicMaxStreamIdSize
+
186 kQuicMaxStreamOffsetSize
+ kQuicErrorCodeSize
+
187 kQuicErrorDetailsLengthSize
;
191 size_t QuicFramer::GetRstStreamFrameSize() {
192 return kQuicFrameTypeSize
+ kQuicMaxStreamIdSize
+ kQuicMaxStreamOffsetSize
+
197 size_t QuicFramer::GetMinConnectionCloseFrameSize() {
198 return kQuicFrameTypeSize
+ kQuicErrorCodeSize
+ kQuicErrorDetailsLengthSize
;
202 size_t QuicFramer::GetMinGoAwayFrameSize() {
203 return kQuicFrameTypeSize
+ kQuicErrorCodeSize
+ kQuicErrorDetailsLengthSize
+
204 kQuicMaxStreamIdSize
;
208 size_t QuicFramer::GetWindowUpdateFrameSize() {
209 return kQuicFrameTypeSize
+ kQuicMaxStreamIdSize
+ kQuicMaxStreamOffsetSize
;
213 size_t QuicFramer::GetBlockedFrameSize() {
214 return kQuicFrameTypeSize
+ kQuicMaxStreamIdSize
;
218 size_t QuicFramer::GetStreamIdSize(QuicStreamId stream_id
) {
219 // Sizes are 1 through 4 bytes.
220 for (int i
= 1; i
<= 4; ++i
) {
222 if (stream_id
== 0) {
226 LOG(DFATAL
) << "Failed to determine StreamIDSize.";
231 size_t QuicFramer::GetStreamOffsetSize(QuicStreamOffset offset
) {
232 // 0 is a special case.
236 // 2 through 8 are the remaining sizes.
238 for (int i
= 2; i
<= 8; ++i
) {
244 LOG(DFATAL
) << "Failed to determine StreamOffsetSize.";
249 size_t QuicFramer::GetVersionNegotiationPacketSize(size_t number_versions
) {
250 return kPublicFlagsSize
+ PACKET_8BYTE_CONNECTION_ID
+
251 number_versions
* kQuicVersionSize
;
254 bool QuicFramer::IsSupportedVersion(const QuicVersion version
) const {
255 for (size_t i
= 0; i
< supported_versions_
.size(); ++i
) {
256 if (version
== supported_versions_
[i
]) {
263 size_t QuicFramer::GetSerializedFrameLength(
264 const QuicFrame
& frame
,
268 InFecGroup is_in_fec_group
,
269 QuicPacketNumberLength packet_number_length
) {
270 // Prevent a rare crash reported in b/19458523.
271 if (frame
.stream_frame
== nullptr) {
272 LOG(DFATAL
) << "Cannot compute the length of a null frame. "
273 << "type:" << frame
.type
<< "free_bytes:" << free_bytes
274 << " first_frame:" << first_frame
275 << " last_frame:" << last_frame
276 << " is_in_fec:" << is_in_fec_group
277 << " seq num length:" << packet_number_length
;
278 set_error(QUIC_INTERNAL_ERROR
);
279 visitor_
->OnError(this);
282 if (frame
.type
== PADDING_FRAME
) {
283 // PADDING implies end of packet.
286 size_t frame_len
= ComputeFrameLength(frame
, last_frame
, is_in_fec_group
,
287 packet_number_length
);
288 if (frame_len
<= free_bytes
) {
289 // Frame fits within packet. Note that acks may be truncated.
292 // Only truncate the first frame in a packet, so if subsequent ones go
293 // over, stop including more frames.
298 frame
.type
== ACK_FRAME
&&
299 free_bytes
>= GetMinAckFrameSize(PACKET_6BYTE_PACKET_NUMBER
);
301 // Truncate the frame so the packet will not exceed kMaxPacketSize.
302 // Note that we may not use every byte of the writer in this case.
303 DVLOG(1) << "Truncating large frame, free bytes: " << free_bytes
;
306 if (!FLAGS_quic_allow_oversized_packets_for_test
) {
309 LOG(DFATAL
) << "Packet size too small to fit frame.";
313 QuicFramer::AckFrameInfo::AckFrameInfo() : max_delta(0) {}
315 QuicFramer::AckFrameInfo::~AckFrameInfo() {}
318 QuicPacketEntropyHash
QuicFramer::GetPacketEntropyHash(
319 const QuicPacketHeader
& header
) {
320 return header
.entropy_flag
<< (header
.packet_packet_number
% 8);
323 QuicPacket
* QuicFramer::BuildDataPacket(const QuicPacketHeader
& header
,
324 const QuicFrames
& frames
,
326 size_t packet_length
) {
327 QuicDataWriter
writer(packet_length
, buffer
);
328 if (!AppendPacketHeader(header
, &writer
)) {
329 LOG(DFATAL
) << "AppendPacketHeader failed";
334 for (const QuicFrame
& frame
: frames
) {
335 // Determine if we should write stream frame length in header.
336 const bool no_stream_frame_length
=
337 (header
.is_in_fec_group
== NOT_IN_FEC_GROUP
) &&
338 (i
== frames
.size() - 1);
339 if (!AppendTypeByte(frame
, no_stream_frame_length
, &writer
)) {
340 LOG(DFATAL
) << "AppendTypeByte failed";
344 switch (frame
.type
) {
346 writer
.WritePadding();
349 if (!AppendStreamFrame(
350 *frame
.stream_frame
, no_stream_frame_length
, &writer
)) {
351 LOG(DFATAL
) << "AppendStreamFrame failed";
356 if (!AppendAckFrameAndTypeByte(
357 header
, *frame
.ack_frame
, &writer
)) {
358 LOG(DFATAL
) << "AppendAckFrameAndTypeByte failed";
362 case STOP_WAITING_FRAME
:
363 if (!AppendStopWaitingFrame(
364 header
, *frame
.stop_waiting_frame
, &writer
)) {
365 LOG(DFATAL
) << "AppendStopWaitingFrame failed";
369 case MTU_DISCOVERY_FRAME
:
370 // MTU discovery frames are serialized as ping frames.
372 // Ping has no payload.
374 case RST_STREAM_FRAME
:
375 if (!AppendRstStreamFrame(*frame
.rst_stream_frame
, &writer
)) {
376 LOG(DFATAL
) << "AppendRstStreamFrame failed";
380 case CONNECTION_CLOSE_FRAME
:
381 if (!AppendConnectionCloseFrame(
382 *frame
.connection_close_frame
, &writer
)) {
383 LOG(DFATAL
) << "AppendConnectionCloseFrame failed";
388 if (!AppendGoAwayFrame(*frame
.goaway_frame
, &writer
)) {
389 LOG(DFATAL
) << "AppendGoAwayFrame failed";
393 case WINDOW_UPDATE_FRAME
:
394 if (!AppendWindowUpdateFrame(*frame
.window_update_frame
, &writer
)) {
395 LOG(DFATAL
) << "AppendWindowUpdateFrame failed";
400 if (!AppendBlockedFrame(*frame
.blocked_frame
, &writer
)) {
401 LOG(DFATAL
) << "AppendBlockedFrame failed";
406 RaiseError(QUIC_INVALID_FRAME_DATA
);
407 LOG(DFATAL
) << "QUIC_INVALID_FRAME_DATA";
414 new QuicPacket(writer
.data(), writer
.length(), false,
415 header
.public_header
.connection_id_length
,
416 header
.public_header
.version_flag
,
417 header
.public_header
.packet_number_length
);
422 QuicPacket
* QuicFramer::BuildFecPacket(const QuicPacketHeader
& header
,
423 const QuicFecData
& fec
) {
424 DCHECK_EQ(IN_FEC_GROUP
, header
.is_in_fec_group
);
425 DCHECK_NE(0u, header
.fec_group
);
426 size_t len
= GetPacketHeaderSize(header
);
427 len
+= fec
.redundancy
.length();
429 scoped_ptr
<char[]> buffer(new char[len
]);
430 QuicDataWriter
writer(len
, buffer
.get());
431 if (!AppendPacketHeader(header
, &writer
)) {
432 LOG(DFATAL
) << "AppendPacketHeader failed";
436 if (!writer
.WriteBytes(fec
.redundancy
.data(), fec
.redundancy
.length())) {
437 LOG(DFATAL
) << "Failed to add FEC";
441 return new QuicPacket(buffer
.release(), len
, true,
442 header
.public_header
.connection_id_length
,
443 header
.public_header
.version_flag
,
444 header
.public_header
.packet_number_length
);
448 QuicEncryptedPacket
* QuicFramer::BuildPublicResetPacket(
449 const QuicPublicResetPacket
& packet
) {
450 DCHECK(packet
.public_header
.reset_flag
);
452 CryptoHandshakeMessage reset
;
453 reset
.set_tag(kPRST
);
454 reset
.SetValue(kRNON
, packet
.nonce_proof
);
455 reset
.SetValue(kRSEQ
, packet
.rejected_packet_number
);
456 if (!packet
.client_address
.address().empty()) {
457 // packet.client_address is non-empty.
458 QuicSocketAddressCoder
address_coder(packet
.client_address
);
459 string serialized_address
= address_coder
.Encode();
460 if (serialized_address
.empty()) {
463 reset
.SetStringPiece(kCADR
, serialized_address
);
465 const QuicData
& reset_serialized
= reset
.GetSerialized();
468 kPublicFlagsSize
+ PACKET_8BYTE_CONNECTION_ID
+ reset_serialized
.length();
469 scoped_ptr
<char[]> buffer(new char[len
]);
470 QuicDataWriter
writer(len
, buffer
.get());
472 uint8 flags
= static_cast<uint8
>(PACKET_PUBLIC_FLAGS_RST
|
473 PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID
);
474 if (!writer
.WriteUInt8(flags
)) {
478 if (!writer
.WriteUInt64(packet
.public_header
.connection_id
)) {
482 if (!writer
.WriteBytes(reset_serialized
.data(), reset_serialized
.length())) {
486 return new QuicEncryptedPacket(buffer
.release(), len
, true);
489 QuicEncryptedPacket
* QuicFramer::BuildVersionNegotiationPacket(
490 const QuicPacketPublicHeader
& header
,
491 const QuicVersionVector
& supported_versions
) {
492 DCHECK(header
.version_flag
);
493 size_t len
= GetVersionNegotiationPacketSize(supported_versions
.size());
494 scoped_ptr
<char[]> buffer(new char[len
]);
495 QuicDataWriter
writer(len
, buffer
.get());
497 uint8 flags
= static_cast<uint8
>(PACKET_PUBLIC_FLAGS_VERSION
|
498 PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID
);
499 if (!writer
.WriteUInt8(flags
)) {
503 if (!writer
.WriteUInt64(header
.connection_id
)) {
507 for (size_t i
= 0; i
< supported_versions
.size(); ++i
) {
508 if (!writer
.WriteUInt32(QuicVersionToQuicTag(supported_versions
[i
]))) {
513 return new QuicEncryptedPacket(buffer
.release(), len
, true);
516 bool QuicFramer::ProcessPacket(const QuicEncryptedPacket
& packet
) {
517 QuicDataReader
reader(packet
.data(), packet
.length());
519 visitor_
->OnPacket();
521 // First parse the public header.
522 QuicPacketPublicHeader public_header
;
523 if (!ProcessPublicHeader(&reader
, &public_header
)) {
524 DLOG(WARNING
) << "Unable to process public header.";
525 DCHECK_NE("", detailed_error_
);
526 return RaiseError(QUIC_INVALID_PACKET_HEADER
);
529 if (!visitor_
->OnUnauthenticatedPublicHeader(public_header
)) {
530 // The visitor suppresses further processing of the packet.
534 if (perspective_
== Perspective::IS_SERVER
&& public_header
.version_flag
&&
535 public_header
.versions
[0] != quic_version_
) {
536 if (!visitor_
->OnProtocolVersionMismatch(public_header
.versions
[0])) {
542 if (perspective_
== Perspective::IS_CLIENT
&& public_header
.version_flag
) {
543 rv
= ProcessVersionNegotiationPacket(&reader
, &public_header
);
544 } else if (public_header
.reset_flag
) {
545 rv
= ProcessPublicResetPacket(&reader
, public_header
);
546 } else if (packet
.length() <= kMaxPacketSize
) {
547 // The optimized decryption algorithm implementations run faster when
548 // operating on aligned memory.
550 // TODO(rtenneti): Change the default 64 alignas value (used the default
551 // value from CACHELINE_SIZE).
552 ALIGNAS(64) char buffer
[kMaxPacketSize
];
553 rv
= ProcessDataPacket(&reader
, public_header
, packet
, buffer
,
556 scoped_ptr
<char[]> large_buffer(new char[packet
.length()]);
557 rv
= ProcessDataPacket(&reader
, public_header
, packet
, large_buffer
.get(),
559 LOG_IF(DFATAL
, rv
) << "QUIC should never successfully process packets "
560 << "larger than kMaxPacketSize. packet size:"
567 bool QuicFramer::ProcessVersionNegotiationPacket(
568 QuicDataReader
* reader
,
569 QuicPacketPublicHeader
* public_header
) {
570 DCHECK_EQ(Perspective::IS_CLIENT
, perspective_
);
571 // Try reading at least once to raise error if the packet is invalid.
574 if (!reader
->ReadBytes(&version
, kQuicVersionSize
)) {
575 set_detailed_error("Unable to read supported version in negotiation.");
576 return RaiseError(QUIC_INVALID_VERSION_NEGOTIATION_PACKET
);
578 public_header
->versions
.push_back(QuicTagToQuicVersion(version
));
579 } while (!reader
->IsDoneReading());
581 visitor_
->OnVersionNegotiationPacket(*public_header
);
585 bool QuicFramer::ProcessDataPacket(QuicDataReader
* encrypted_reader
,
586 const QuicPacketPublicHeader
& public_header
,
587 const QuicEncryptedPacket
& packet
,
588 char* decrypted_buffer
,
589 size_t buffer_length
) {
590 QuicPacketHeader
header(public_header
);
591 if (!ProcessUnauthenticatedHeader(encrypted_reader
, &header
)) {
592 DLOG(WARNING
) << "Unable to process packet header. Stopping parsing.";
596 size_t decrypted_length
= 0;
597 if (!DecryptPayload(encrypted_reader
, header
, packet
, decrypted_buffer
,
598 buffer_length
, &decrypted_length
)) {
599 set_detailed_error("Unable to decrypt payload.");
600 return RaiseError(QUIC_DECRYPTION_FAILURE
);
603 QuicDataReader
reader(decrypted_buffer
, decrypted_length
);
604 if (!ProcessAuthenticatedHeader(&reader
, &header
)) {
605 DLOG(WARNING
) << "Unable to process packet header. Stopping parsing.";
609 if (!visitor_
->OnPacketHeader(header
)) {
610 // The visitor suppresses further processing of the packet.
614 if (packet
.length() > kMaxPacketSize
) {
615 DLOG(WARNING
) << "Packet too large: " << packet
.length();
616 return RaiseError(QUIC_PACKET_TOO_LARGE
);
619 // Handle the payload.
620 if (!header
.fec_flag
) {
621 if (header
.is_in_fec_group
== IN_FEC_GROUP
) {
622 StringPiece payload
= reader
.PeekRemainingPayload();
623 visitor_
->OnFecProtectedPayload(payload
);
625 if (!ProcessFrameData(&reader
, header
)) {
626 DCHECK_NE(QUIC_NO_ERROR
, error_
); // ProcessFrameData sets the error.
627 DLOG(WARNING
) << "Unable to process frame data.";
631 QuicFecData fec_data
;
632 fec_data
.fec_group
= header
.fec_group
;
633 fec_data
.redundancy
= reader
.ReadRemainingPayload();
634 visitor_
->OnFecData(fec_data
);
637 visitor_
->OnPacketComplete();
641 bool QuicFramer::ProcessPublicResetPacket(
642 QuicDataReader
* reader
,
643 const QuicPacketPublicHeader
& public_header
) {
644 QuicPublicResetPacket
packet(public_header
);
646 scoped_ptr
<CryptoHandshakeMessage
> reset(
647 CryptoFramer::ParseMessage(reader
->ReadRemainingPayload()));
649 set_detailed_error("Unable to read reset message.");
650 return RaiseError(QUIC_INVALID_PUBLIC_RST_PACKET
);
652 if (reset
->tag() != kPRST
) {
653 set_detailed_error("Incorrect message tag.");
654 return RaiseError(QUIC_INVALID_PUBLIC_RST_PACKET
);
657 if (reset
->GetUint64(kRNON
, &packet
.nonce_proof
) != QUIC_NO_ERROR
) {
658 set_detailed_error("Unable to read nonce proof.");
659 return RaiseError(QUIC_INVALID_PUBLIC_RST_PACKET
);
661 // TODO(satyamshekhar): validate nonce to protect against DoS.
663 if (reset
->GetUint64(kRSEQ
, &packet
.rejected_packet_number
) !=
665 set_detailed_error("Unable to read rejected packet number.");
666 return RaiseError(QUIC_INVALID_PUBLIC_RST_PACKET
);
670 if (reset
->GetStringPiece(kCADR
, &address
)) {
671 QuicSocketAddressCoder address_coder
;
672 if (address_coder
.Decode(address
.data(), address
.length())) {
673 packet
.client_address
= IPEndPoint(address_coder
.ip(),
674 address_coder
.port());
678 visitor_
->OnPublicResetPacket(packet
);
682 bool QuicFramer::ProcessRevivedPacket(QuicPacketHeader
* header
,
683 StringPiece payload
) {
684 visitor_
->OnRevivedPacket();
686 header
->entropy_hash
= GetPacketEntropyHash(*header
);
688 if (!visitor_
->OnPacketHeader(*header
)) {
692 if (payload
.length() > kMaxPacketSize
) {
693 set_detailed_error("Revived packet too large.");
694 return RaiseError(QUIC_PACKET_TOO_LARGE
);
697 QuicDataReader
reader(payload
.data(), payload
.length());
698 if (!ProcessFrameData(&reader
, *header
)) {
699 DCHECK_NE(QUIC_NO_ERROR
, error_
); // ProcessFrameData sets the error.
700 DLOG(WARNING
) << "Unable to process frame data.";
704 visitor_
->OnPacketComplete();
708 bool QuicFramer::AppendPacketHeader(const QuicPacketHeader
& header
,
709 QuicDataWriter
* writer
) {
710 DVLOG(1) << "Appending header: " << header
;
711 DCHECK(header
.fec_group
> 0 || header
.is_in_fec_group
== NOT_IN_FEC_GROUP
);
712 uint8 public_flags
= 0;
713 if (header
.public_header
.reset_flag
) {
714 public_flags
|= PACKET_PUBLIC_FLAGS_RST
;
716 if (header
.public_header
.version_flag
) {
717 public_flags
|= PACKET_PUBLIC_FLAGS_VERSION
;
721 GetSequenceNumberFlags(header
.public_header
.packet_number_length
)
722 << kPublicHeaderSequenceNumberShift
;
724 switch (header
.public_header
.connection_id_length
) {
725 case PACKET_0BYTE_CONNECTION_ID
:
726 if (!writer
->WriteUInt8(
727 public_flags
| PACKET_PUBLIC_FLAGS_0BYTE_CONNECTION_ID
)) {
731 case PACKET_1BYTE_CONNECTION_ID
:
732 if (!writer
->WriteUInt8(
733 public_flags
| PACKET_PUBLIC_FLAGS_1BYTE_CONNECTION_ID
)) {
736 if (!writer
->WriteUInt8(
737 header
.public_header
.connection_id
& k1ByteConnectionIdMask
)) {
741 case PACKET_4BYTE_CONNECTION_ID
:
742 if (!writer
->WriteUInt8(
743 public_flags
| PACKET_PUBLIC_FLAGS_4BYTE_CONNECTION_ID
)) {
746 if (!writer
->WriteUInt32(
747 header
.public_header
.connection_id
& k4ByteConnectionIdMask
)) {
751 case PACKET_8BYTE_CONNECTION_ID
:
752 if (!writer
->WriteUInt8(
753 public_flags
| PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID
)) {
756 if (!writer
->WriteUInt64(header
.public_header
.connection_id
)) {
761 last_serialized_connection_id_
= header
.public_header
.connection_id
;
763 if (header
.public_header
.version_flag
) {
764 DCHECK_EQ(Perspective::IS_CLIENT
, perspective_
);
765 QuicTag tag
= QuicVersionToQuicTag(quic_version_
);
766 writer
->WriteUInt32(tag
);
767 DVLOG(1) << "version = " << quic_version_
<< ", tag = '"
768 << QuicUtils::TagToString(tag
) << "'";
771 if (!AppendPacketSequenceNumber(header
.public_header
.packet_number_length
,
772 header
.packet_packet_number
, writer
)) {
776 uint8 private_flags
= 0;
777 if (header
.entropy_flag
) {
778 private_flags
|= PACKET_PRIVATE_FLAGS_ENTROPY
;
780 if (header
.is_in_fec_group
== IN_FEC_GROUP
) {
781 private_flags
|= PACKET_PRIVATE_FLAGS_FEC_GROUP
;
783 if (header
.fec_flag
) {
784 private_flags
|= PACKET_PRIVATE_FLAGS_FEC
;
786 if (!writer
->WriteUInt8(private_flags
)) {
790 // The FEC group number is the packet number of the first fec
791 // protected packet, or 0 if this packet is not protected.
792 if (header
.is_in_fec_group
== IN_FEC_GROUP
) {
793 DCHECK_LE(header
.fec_group
, header
.packet_packet_number
);
794 DCHECK_LT(header
.packet_packet_number
- header
.fec_group
, 255u);
795 // Offset from the current packet number to the first fec
797 uint8 first_fec_protected_packet_offset
=
798 static_cast<uint8
>(header
.packet_packet_number
- header
.fec_group
);
799 if (!writer
->WriteBytes(&first_fec_protected_packet_offset
, 1)) {
807 const QuicTime::Delta
QuicFramer::CalculateTimestampFromWire(
808 uint32 time_delta_us
) {
809 // The new time_delta might have wrapped to the next epoch, or it
810 // might have reverse wrapped to the previous epoch, or it might
811 // remain in the same epoch. Select the time closest to the previous
814 // epoch_delta is the delta between epochs. A delta is 4 bytes of
816 const uint64 epoch_delta
= UINT64_C(1) << 32;
817 uint64 epoch
= last_timestamp_
.ToMicroseconds() & ~(epoch_delta
- 1);
818 // Wrapping is safe here because a wrapped value will not be ClosestTo below.
819 uint64 prev_epoch
= epoch
- epoch_delta
;
820 uint64 next_epoch
= epoch
+ epoch_delta
;
822 uint64 time
= ClosestTo(last_timestamp_
.ToMicroseconds(),
823 epoch
+ time_delta_us
,
824 ClosestTo(last_timestamp_
.ToMicroseconds(),
825 prev_epoch
+ time_delta_us
,
826 next_epoch
+ time_delta_us
));
828 return QuicTime::Delta::FromMicroseconds(time
);
831 QuicPacketNumber
QuicFramer::CalculatePacketNumberFromWire(
832 QuicPacketNumberLength packet_number_length
,
833 QuicPacketNumber packet_packet_number
) const {
834 // The new packet number might have wrapped to the next epoch, or
835 // it might have reverse wrapped to the previous epoch, or it might
836 // remain in the same epoch. Select the packet number closest to the
837 // next expected packet number, the previous packet number plus 1.
839 // epoch_delta is the delta between epochs the packet number was serialized
840 // with, so the correct value is likely the same epoch as the last sequence
841 // number or an adjacent epoch.
842 const QuicPacketNumber epoch_delta
= UINT64_C(1)
843 << (8 * packet_number_length
);
844 QuicPacketNumber next_packet_number
= last_packet_number_
+ 1;
845 QuicPacketNumber epoch
= last_packet_number_
& ~(epoch_delta
- 1);
846 QuicPacketNumber prev_epoch
= epoch
- epoch_delta
;
847 QuicPacketNumber next_epoch
= epoch
+ epoch_delta
;
850 next_packet_number
, epoch
+ packet_packet_number
,
851 ClosestTo(next_packet_number
, prev_epoch
+ packet_packet_number
,
852 next_epoch
+ packet_packet_number
));
855 bool QuicFramer::ProcessPublicHeader(QuicDataReader
* reader
,
856 QuicPacketPublicHeader
* public_header
) {
858 if (!reader
->ReadBytes(&public_flags
, 1)) {
859 set_detailed_error("Unable to read public flags.");
863 public_header
->reset_flag
= (public_flags
& PACKET_PUBLIC_FLAGS_RST
) != 0;
864 public_header
->version_flag
=
865 (public_flags
& PACKET_PUBLIC_FLAGS_VERSION
) != 0;
867 if (validate_flags_
&&
868 !public_header
->version_flag
&& public_flags
> PACKET_PUBLIC_FLAGS_MAX
) {
869 set_detailed_error("Illegal public flags value.");
873 if (public_header
->reset_flag
&& public_header
->version_flag
) {
874 set_detailed_error("Got version flag in reset packet");
878 switch (public_flags
& PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID
) {
879 case PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID
:
880 if (!reader
->ReadUInt64(&public_header
->connection_id
)) {
881 set_detailed_error("Unable to read ConnectionId.");
884 public_header
->connection_id_length
= PACKET_8BYTE_CONNECTION_ID
;
886 case PACKET_PUBLIC_FLAGS_4BYTE_CONNECTION_ID
:
887 // If the connection_id is truncated, expect to read the last serialized
889 if (!reader
->ReadBytes(&public_header
->connection_id
,
890 PACKET_4BYTE_CONNECTION_ID
)) {
891 set_detailed_error("Unable to read ConnectionId.");
894 if (last_serialized_connection_id_
&&
895 (public_header
->connection_id
& k4ByteConnectionIdMask
) !=
896 (last_serialized_connection_id_
& k4ByteConnectionIdMask
)) {
897 set_detailed_error("Truncated 4 byte ConnectionId does not match "
898 "previous connection_id.");
901 public_header
->connection_id_length
= PACKET_4BYTE_CONNECTION_ID
;
902 public_header
->connection_id
= last_serialized_connection_id_
;
904 case PACKET_PUBLIC_FLAGS_1BYTE_CONNECTION_ID
:
905 if (!reader
->ReadBytes(&public_header
->connection_id
,
906 PACKET_1BYTE_CONNECTION_ID
)) {
907 set_detailed_error("Unable to read ConnectionId.");
910 if (last_serialized_connection_id_
&&
911 (public_header
->connection_id
& k1ByteConnectionIdMask
) !=
912 (last_serialized_connection_id_
& k1ByteConnectionIdMask
)) {
913 set_detailed_error("Truncated 1 byte ConnectionId does not match "
914 "previous connection_id.");
917 public_header
->connection_id_length
= PACKET_1BYTE_CONNECTION_ID
;
918 public_header
->connection_id
= last_serialized_connection_id_
;
920 case PACKET_PUBLIC_FLAGS_0BYTE_CONNECTION_ID
:
921 public_header
->connection_id_length
= PACKET_0BYTE_CONNECTION_ID
;
922 public_header
->connection_id
= last_serialized_connection_id_
;
926 public_header
->packet_number_length
= ReadSequenceNumberLength(
927 public_flags
>> kPublicHeaderSequenceNumberShift
);
929 // Read the version only if the packet is from the client.
930 // version flag from the server means version negotiation packet.
931 if (public_header
->version_flag
&& perspective_
== Perspective::IS_SERVER
) {
933 if (!reader
->ReadUInt32(&version_tag
)) {
934 set_detailed_error("Unable to read protocol version.");
938 // If the version from the new packet is the same as the version of this
939 // framer, then the public flags should be set to something we understand.
940 // If not, this raises an error.
941 QuicVersion version
= QuicTagToQuicVersion(version_tag
);
942 if (version
== quic_version_
&& public_flags
> PACKET_PUBLIC_FLAGS_MAX
) {
943 set_detailed_error("Illegal public flags value.");
946 public_header
->versions
.push_back(version
);
952 QuicPacketNumberLength
QuicFramer::GetMinSequenceNumberLength(
953 QuicPacketNumber packet_number
) {
954 if (packet_number
< 1 << (PACKET_1BYTE_PACKET_NUMBER
* 8)) {
955 return PACKET_1BYTE_PACKET_NUMBER
;
956 } else if (packet_number
< 1 << (PACKET_2BYTE_PACKET_NUMBER
* 8)) {
957 return PACKET_2BYTE_PACKET_NUMBER
;
958 } else if (packet_number
< UINT64_C(1) << (PACKET_4BYTE_PACKET_NUMBER
* 8)) {
959 return PACKET_4BYTE_PACKET_NUMBER
;
961 return PACKET_6BYTE_PACKET_NUMBER
;
966 uint8
QuicFramer::GetSequenceNumberFlags(
967 QuicPacketNumberLength packet_number_length
) {
968 switch (packet_number_length
) {
969 case PACKET_1BYTE_PACKET_NUMBER
:
970 return PACKET_FLAGS_1BYTE_PACKET
;
971 case PACKET_2BYTE_PACKET_NUMBER
:
972 return PACKET_FLAGS_2BYTE_PACKET
;
973 case PACKET_4BYTE_PACKET_NUMBER
:
974 return PACKET_FLAGS_4BYTE_PACKET
;
975 case PACKET_6BYTE_PACKET_NUMBER
:
976 return PACKET_FLAGS_6BYTE_PACKET
;
978 LOG(DFATAL
) << "Unreachable case statement.";
979 return PACKET_FLAGS_6BYTE_PACKET
;
984 QuicFramer::AckFrameInfo
QuicFramer::GetAckFrameInfo(
985 const QuicAckFrame
& frame
) {
986 AckFrameInfo ack_info
;
987 if (frame
.missing_packets
.Empty()) {
990 DCHECK_GE(frame
.largest_observed
, frame
.missing_packets
.Max());
991 size_t cur_range_length
= 0;
992 PacketNumberSet::const_iterator iter
= frame
.missing_packets
.begin();
993 QuicPacketNumber last_missing
= *iter
;
995 for (; iter
!= frame
.missing_packets
.end(); ++iter
) {
996 if (cur_range_length
< numeric_limits
<uint8
>::max() &&
997 *iter
== (last_missing
+ 1)) {
1000 ack_info
.nack_ranges
[last_missing
- cur_range_length
] =
1001 static_cast<uint8
>(cur_range_length
);
1002 cur_range_length
= 0;
1004 ack_info
.max_delta
= max(ack_info
.max_delta
, *iter
- last_missing
);
1005 last_missing
= *iter
;
1007 // Include the last nack range.
1008 ack_info
.nack_ranges
[last_missing
- cur_range_length
] =
1009 static_cast<uint8
>(cur_range_length
);
1010 // Include the range to the largest observed.
1011 ack_info
.max_delta
=
1012 max(ack_info
.max_delta
, frame
.largest_observed
- last_missing
);
1016 bool QuicFramer::ProcessUnauthenticatedHeader(QuicDataReader
* encrypted_reader
,
1017 QuicPacketHeader
* header
) {
1018 if (!ProcessPacketSequenceNumber(encrypted_reader
,
1019 header
->public_header
.packet_number_length
,
1020 &header
->packet_packet_number
)) {
1021 set_detailed_error("Unable to read packet number.");
1022 return RaiseError(QUIC_INVALID_PACKET_HEADER
);
1025 if (header
->packet_packet_number
== 0u) {
1026 set_detailed_error("packet numbers cannot be 0.");
1027 return RaiseError(QUIC_INVALID_PACKET_HEADER
);
1030 if (!visitor_
->OnUnauthenticatedHeader(*header
)) {
1036 bool QuicFramer::ProcessAuthenticatedHeader(QuicDataReader
* reader
,
1037 QuicPacketHeader
* header
) {
1038 uint8 private_flags
;
1039 if (!reader
->ReadBytes(&private_flags
, 1)) {
1040 set_detailed_error("Unable to read private flags.");
1041 return RaiseError(QUIC_INVALID_PACKET_HEADER
);
1044 if (private_flags
> PACKET_PRIVATE_FLAGS_MAX
) {
1045 set_detailed_error("Illegal private flags value.");
1046 return RaiseError(QUIC_INVALID_PACKET_HEADER
);
1049 header
->entropy_flag
= (private_flags
& PACKET_PRIVATE_FLAGS_ENTROPY
) != 0;
1050 header
->fec_flag
= (private_flags
& PACKET_PRIVATE_FLAGS_FEC
) != 0;
1052 if ((private_flags
& PACKET_PRIVATE_FLAGS_FEC_GROUP
) != 0) {
1053 header
->is_in_fec_group
= IN_FEC_GROUP
;
1054 uint8 first_fec_protected_packet_offset
;
1055 if (!reader
->ReadBytes(&first_fec_protected_packet_offset
, 1)) {
1056 set_detailed_error("Unable to read first fec protected packet offset.");
1057 return RaiseError(QUIC_INVALID_PACKET_HEADER
);
1059 if (first_fec_protected_packet_offset
>= header
->packet_packet_number
) {
1061 "First fec protected packet offset must be less "
1062 "than the packet number.");
1063 return RaiseError(QUIC_INVALID_PACKET_HEADER
);
1066 header
->packet_packet_number
- first_fec_protected_packet_offset
;
1069 header
->entropy_hash
= GetPacketEntropyHash(*header
);
1070 // Set the last packet number after we have decrypted the packet
1071 // so we are confident is not attacker controlled.
1072 last_packet_number_
= header
->packet_packet_number
;
1076 bool QuicFramer::ProcessPacketSequenceNumber(
1077 QuicDataReader
* reader
,
1078 QuicPacketNumberLength packet_number_length
,
1079 QuicPacketNumber
* packet_number
) {
1080 QuicPacketNumber wire_packet_number
= 0u;
1081 if (!reader
->ReadBytes(&wire_packet_number
, packet_number_length
)) {
1085 // TODO(ianswett): Explore the usefulness of trying multiple packet numbers
1086 // in case the first guess is incorrect.
1088 CalculatePacketNumberFromWire(packet_number_length
, wire_packet_number
);
1092 bool QuicFramer::ProcessFrameData(QuicDataReader
* reader
,
1093 const QuicPacketHeader
& header
) {
1094 if (reader
->IsDoneReading()) {
1095 set_detailed_error("Packet has no frames.");
1096 return RaiseError(QUIC_MISSING_PAYLOAD
);
1098 while (!reader
->IsDoneReading()) {
1100 if (!reader
->ReadBytes(&frame_type
, 1)) {
1101 set_detailed_error("Unable to read frame type.");
1102 return RaiseError(QUIC_INVALID_FRAME_DATA
);
1105 if (frame_type
& kQuicFrameTypeSpecialMask
) {
1107 if (frame_type
& kQuicFrameTypeStreamMask
) {
1108 QuicStreamFrame frame
;
1109 if (!ProcessStreamFrame(reader
, frame_type
, &frame
)) {
1110 return RaiseError(QUIC_INVALID_STREAM_DATA
);
1112 if (!visitor_
->OnStreamFrame(frame
)) {
1113 DVLOG(1) << "Visitor asked to stop further processing.";
1114 // Returning true since there was no parsing error.
1121 if (frame_type
& kQuicFrameTypeAckMask
) {
1123 if (!ProcessAckFrame(reader
, frame_type
, &frame
)) {
1124 return RaiseError(QUIC_INVALID_ACK_DATA
);
1126 if (!visitor_
->OnAckFrame(frame
)) {
1127 DVLOG(1) << "Visitor asked to stop further processing.";
1128 // Returning true since there was no parsing error.
1134 // This was a special frame type that did not match any
1135 // of the known ones. Error.
1136 set_detailed_error("Illegal frame type.");
1137 DLOG(WARNING
) << "Illegal frame type: "
1138 << static_cast<int>(frame_type
);
1139 return RaiseError(QUIC_INVALID_FRAME_DATA
);
1142 switch (frame_type
) {
1144 // We're done with the packet.
1147 case RST_STREAM_FRAME
: {
1148 QuicRstStreamFrame frame
;
1149 if (!ProcessRstStreamFrame(reader
, &frame
)) {
1150 return RaiseError(QUIC_INVALID_RST_STREAM_DATA
);
1152 if (!visitor_
->OnRstStreamFrame(frame
)) {
1153 DVLOG(1) << "Visitor asked to stop further processing.";
1154 // Returning true since there was no parsing error.
1160 case CONNECTION_CLOSE_FRAME
: {
1161 QuicConnectionCloseFrame frame
;
1162 if (!ProcessConnectionCloseFrame(reader
, &frame
)) {
1163 return RaiseError(QUIC_INVALID_CONNECTION_CLOSE_DATA
);
1166 if (!visitor_
->OnConnectionCloseFrame(frame
)) {
1167 DVLOG(1) << "Visitor asked to stop further processing.";
1168 // Returning true since there was no parsing error.
1174 case GOAWAY_FRAME
: {
1175 QuicGoAwayFrame goaway_frame
;
1176 if (!ProcessGoAwayFrame(reader
, &goaway_frame
)) {
1177 return RaiseError(QUIC_INVALID_GOAWAY_DATA
);
1179 if (!visitor_
->OnGoAwayFrame(goaway_frame
)) {
1180 DVLOG(1) << "Visitor asked to stop further processing.";
1181 // Returning true since there was no parsing error.
1187 case WINDOW_UPDATE_FRAME
: {
1188 QuicWindowUpdateFrame window_update_frame
;
1189 if (!ProcessWindowUpdateFrame(reader
, &window_update_frame
)) {
1190 return RaiseError(QUIC_INVALID_WINDOW_UPDATE_DATA
);
1192 if (!visitor_
->OnWindowUpdateFrame(window_update_frame
)) {
1193 DVLOG(1) << "Visitor asked to stop further processing.";
1194 // Returning true since there was no parsing error.
1200 case BLOCKED_FRAME
: {
1201 QuicBlockedFrame blocked_frame
;
1202 if (!ProcessBlockedFrame(reader
, &blocked_frame
)) {
1203 return RaiseError(QUIC_INVALID_BLOCKED_DATA
);
1205 if (!visitor_
->OnBlockedFrame(blocked_frame
)) {
1206 DVLOG(1) << "Visitor asked to stop further processing.";
1207 // Returning true since there was no parsing error.
1213 case STOP_WAITING_FRAME
: {
1214 QuicStopWaitingFrame stop_waiting_frame
;
1215 if (!ProcessStopWaitingFrame(reader
, header
, &stop_waiting_frame
)) {
1216 return RaiseError(QUIC_INVALID_STOP_WAITING_DATA
);
1218 if (!visitor_
->OnStopWaitingFrame(stop_waiting_frame
)) {
1219 DVLOG(1) << "Visitor asked to stop further processing.";
1220 // Returning true since there was no parsing error.
1226 // Ping has no payload.
1227 QuicPingFrame ping_frame
;
1228 if (!visitor_
->OnPingFrame(ping_frame
)) {
1229 DVLOG(1) << "Visitor asked to stop further processing.";
1230 // Returning true since there was no parsing error.
1237 set_detailed_error("Illegal frame type.");
1238 DLOG(WARNING
) << "Illegal frame type: "
1239 << static_cast<int>(frame_type
);
1240 return RaiseError(QUIC_INVALID_FRAME_DATA
);
1247 bool QuicFramer::ProcessStreamFrame(QuicDataReader
* reader
,
1249 QuicStreamFrame
* frame
) {
1250 uint8 stream_flags
= frame_type
;
1252 stream_flags
&= ~kQuicFrameTypeStreamMask
;
1254 // Read from right to left: StreamID, Offset, Data Length, Fin.
1255 const uint8 stream_id_length
= (stream_flags
& kQuicStreamIDLengthMask
) + 1;
1256 stream_flags
>>= kQuicStreamIdShift
;
1258 uint8 offset_length
= (stream_flags
& kQuicStreamOffsetMask
);
1259 // There is no encoding for 1 byte, only 0 and 2 through 8.
1260 if (offset_length
> 0) {
1263 stream_flags
>>= kQuicStreamOffsetShift
;
1265 bool has_data_length
=
1266 (stream_flags
& kQuicStreamDataLengthMask
) == kQuicStreamDataLengthMask
;
1267 stream_flags
>>= kQuicStreamDataLengthShift
;
1269 frame
->fin
= (stream_flags
& kQuicStreamFinMask
) == kQuicStreamFinShift
;
1271 frame
->stream_id
= 0;
1272 if (!reader
->ReadBytes(&frame
->stream_id
, stream_id_length
)) {
1273 set_detailed_error("Unable to read stream_id.");
1278 if (!reader
->ReadBytes(&frame
->offset
, offset_length
)) {
1279 set_detailed_error("Unable to read offset.");
1283 if (has_data_length
) {
1284 if (!reader
->ReadStringPiece16(&frame
->data
)) {
1285 set_detailed_error("Unable to read frame data.");
1289 if (!reader
->ReadStringPiece(&frame
->data
, reader
->BytesRemaining())) {
1290 set_detailed_error("Unable to read frame data.");
1298 bool QuicFramer::ProcessAckFrame(QuicDataReader
* reader
,
1300 QuicAckFrame
* ack_frame
) {
1301 // Determine the three lengths from the frame type: largest observed length,
1302 // missing packet number length, and missing range length.
1303 const QuicPacketNumberLength missing_packet_number_length
=
1304 ReadSequenceNumberLength(frame_type
);
1305 frame_type
>>= kQuicSequenceNumberLengthShift
;
1306 const QuicPacketNumberLength largest_observed_packet_number_length
=
1307 ReadSequenceNumberLength(frame_type
);
1308 frame_type
>>= kQuicSequenceNumberLengthShift
;
1309 ack_frame
->is_truncated
= frame_type
& kQuicAckTruncatedMask
;
1310 frame_type
>>= kQuicAckTruncatedShift
;
1311 bool has_nacks
= frame_type
& kQuicHasNacksMask
;
1313 if (!reader
->ReadBytes(&ack_frame
->entropy_hash
, 1)) {
1314 set_detailed_error("Unable to read entropy hash for received packets.");
1318 if (!reader
->ReadBytes(&ack_frame
->largest_observed
,
1319 largest_observed_packet_number_length
)) {
1320 set_detailed_error("Unable to read largest observed.");
1324 uint64 delta_time_largest_observed_us
;
1325 if (!reader
->ReadUFloat16(&delta_time_largest_observed_us
)) {
1326 set_detailed_error("Unable to read delta time largest observed.");
1330 if (delta_time_largest_observed_us
== kUFloat16MaxValue
) {
1331 ack_frame
->delta_time_largest_observed
= QuicTime::Delta::Infinite();
1333 ack_frame
->delta_time_largest_observed
=
1334 QuicTime::Delta::FromMicroseconds(delta_time_largest_observed_us
);
1337 if (!ProcessTimestampsInAckFrame(reader
, ack_frame
)) {
1345 uint8 num_missing_ranges
;
1346 if (!reader
->ReadBytes(&num_missing_ranges
, 1)) {
1347 set_detailed_error("Unable to read num missing packet ranges.");
1351 QuicPacketNumber last_packet_number
= ack_frame
->largest_observed
;
1352 for (size_t i
= 0; i
< num_missing_ranges
; ++i
) {
1353 QuicPacketNumber missing_delta
= 0;
1354 if (!reader
->ReadBytes(&missing_delta
, missing_packet_number_length
)) {
1355 set_detailed_error("Unable to read missing packet number delta.");
1358 last_packet_number
-= missing_delta
;
1359 QuicPacketNumber range_length
= 0;
1360 if (!reader
->ReadBytes(&range_length
, PACKET_1BYTE_PACKET_NUMBER
)) {
1361 set_detailed_error("Unable to read missing packet number range.");
1364 ack_frame
->missing_packets
.Add(last_packet_number
- range_length
,
1365 last_packet_number
+ 1);
1366 // Subtract an extra 1 to ensure ranges are represented efficiently and
1367 // can't overlap by 1 packet number. This allows a missing_delta of 0
1368 // to represent an adjacent nack range.
1369 last_packet_number
-= (range_length
+ 1);
1372 // Parse the revived packets list.
1373 uint8 num_revived_packets
;
1374 if (!reader
->ReadBytes(&num_revived_packets
, 1)) {
1375 set_detailed_error("Unable to read num revived packets.");
1379 for (size_t i
= 0; i
< num_revived_packets
; ++i
) {
1380 QuicPacketNumber revived_packet
= 0;
1381 if (!reader
->ReadBytes(&revived_packet
,
1382 largest_observed_packet_number_length
)) {
1383 set_detailed_error("Unable to read revived packet.");
1387 ack_frame
->revived_packets
.insert(revived_packet
);
1393 bool QuicFramer::ProcessTimestampsInAckFrame(QuicDataReader
* reader
,
1394 QuicAckFrame
* ack_frame
) {
1395 if (ack_frame
->is_truncated
) {
1398 uint8 num_received_packets
;
1399 if (!reader
->ReadBytes(&num_received_packets
, 1)) {
1400 set_detailed_error("Unable to read num received packets.");
1404 if (num_received_packets
> 0) {
1405 uint8 delta_from_largest_observed
;
1406 if (!reader
->ReadBytes(&delta_from_largest_observed
,
1407 PACKET_1BYTE_PACKET_NUMBER
)) {
1408 set_detailed_error("Unable to read sequence delta in received packets.");
1411 QuicPacketNumber seq_num
=
1412 ack_frame
->largest_observed
- delta_from_largest_observed
;
1414 // Time delta from the framer creation.
1415 uint32 time_delta_us
;
1416 if (!reader
->ReadBytes(&time_delta_us
, sizeof(time_delta_us
))) {
1417 set_detailed_error("Unable to read time delta in received packets.");
1421 last_timestamp_
= CalculateTimestampFromWire(time_delta_us
);
1423 ack_frame
->received_packet_times
.push_back(
1424 std::make_pair(seq_num
, creation_time_
.Add(last_timestamp_
)));
1426 for (uint8 i
= 1; i
< num_received_packets
; ++i
) {
1427 if (!reader
->ReadBytes(&delta_from_largest_observed
,
1428 PACKET_1BYTE_PACKET_NUMBER
)) {
1430 "Unable to read sequence delta in received packets.");
1433 seq_num
= ack_frame
->largest_observed
- delta_from_largest_observed
;
1435 // Time delta from the previous timestamp.
1436 uint64 incremental_time_delta_us
;
1437 if (!reader
->ReadUFloat16(&incremental_time_delta_us
)) {
1439 "Unable to read incremental time delta in received packets.");
1443 last_timestamp_
= last_timestamp_
.Add(
1444 QuicTime::Delta::FromMicroseconds(incremental_time_delta_us
));
1445 ack_frame
->received_packet_times
.push_back(
1446 std::make_pair(seq_num
, creation_time_
.Add(last_timestamp_
)));
1452 bool QuicFramer::ProcessStopWaitingFrame(QuicDataReader
* reader
,
1453 const QuicPacketHeader
& header
,
1454 QuicStopWaitingFrame
* stop_waiting
) {
1455 if (!reader
->ReadBytes(&stop_waiting
->entropy_hash
, 1)) {
1456 set_detailed_error("Unable to read entropy hash for sent packets.");
1460 QuicPacketNumber least_unacked_delta
= 0;
1461 if (!reader
->ReadBytes(&least_unacked_delta
,
1462 header
.public_header
.packet_number_length
)) {
1463 set_detailed_error("Unable to read least unacked delta.");
1466 DCHECK_GE(header
.packet_packet_number
, least_unacked_delta
);
1467 stop_waiting
->least_unacked
=
1468 header
.packet_packet_number
- least_unacked_delta
;
1473 bool QuicFramer::ProcessRstStreamFrame(QuicDataReader
* reader
,
1474 QuicRstStreamFrame
* frame
) {
1475 if (!reader
->ReadUInt32(&frame
->stream_id
)) {
1476 set_detailed_error("Unable to read stream_id.");
1480 if (!reader
->ReadUInt64(&frame
->byte_offset
)) {
1481 set_detailed_error("Unable to read rst stream sent byte offset.");
1486 if (!reader
->ReadUInt32(&error_code
)) {
1487 set_detailed_error("Unable to read rst stream error code.");
1491 if (error_code
>= QUIC_STREAM_LAST_ERROR
) {
1492 set_detailed_error("Invalid rst stream error code.");
1496 frame
->error_code
= static_cast<QuicRstStreamErrorCode
>(error_code
);
1497 if (quic_version_
<= QUIC_VERSION_24
) {
1498 StringPiece error_details
;
1499 if (!reader
->ReadStringPiece16(&error_details
)) {
1500 set_detailed_error("Unable to read rst stream error details.");
1503 frame
->error_details
= error_details
.as_string();
1509 bool QuicFramer::ProcessConnectionCloseFrame(QuicDataReader
* reader
,
1510 QuicConnectionCloseFrame
* frame
) {
1512 if (!reader
->ReadUInt32(&error_code
)) {
1513 set_detailed_error("Unable to read connection close error code.");
1517 if (error_code
>= QUIC_LAST_ERROR
) {
1518 set_detailed_error("Invalid error code.");
1522 frame
->error_code
= static_cast<QuicErrorCode
>(error_code
);
1524 StringPiece error_details
;
1525 if (!reader
->ReadStringPiece16(&error_details
)) {
1526 set_detailed_error("Unable to read connection close error details.");
1529 frame
->error_details
= error_details
.as_string();
1534 bool QuicFramer::ProcessGoAwayFrame(QuicDataReader
* reader
,
1535 QuicGoAwayFrame
* frame
) {
1537 if (!reader
->ReadUInt32(&error_code
)) {
1538 set_detailed_error("Unable to read go away error code.");
1541 frame
->error_code
= static_cast<QuicErrorCode
>(error_code
);
1543 if (error_code
>= QUIC_LAST_ERROR
) {
1544 set_detailed_error("Invalid error code.");
1549 if (!reader
->ReadUInt32(&stream_id
)) {
1550 set_detailed_error("Unable to read last good stream id.");
1553 frame
->last_good_stream_id
= static_cast<QuicStreamId
>(stream_id
);
1555 StringPiece reason_phrase
;
1556 if (!reader
->ReadStringPiece16(&reason_phrase
)) {
1557 set_detailed_error("Unable to read goaway reason.");
1560 frame
->reason_phrase
= reason_phrase
.as_string();
1565 bool QuicFramer::ProcessWindowUpdateFrame(QuicDataReader
* reader
,
1566 QuicWindowUpdateFrame
* frame
) {
1567 if (!reader
->ReadUInt32(&frame
->stream_id
)) {
1568 set_detailed_error("Unable to read stream_id.");
1572 if (!reader
->ReadUInt64(&frame
->byte_offset
)) {
1573 set_detailed_error("Unable to read window byte_offset.");
1580 bool QuicFramer::ProcessBlockedFrame(QuicDataReader
* reader
,
1581 QuicBlockedFrame
* frame
) {
1582 if (!reader
->ReadUInt32(&frame
->stream_id
)) {
1583 set_detailed_error("Unable to read stream_id.");
1591 StringPiece
QuicFramer::GetAssociatedDataFromEncryptedPacket(
1592 const QuicEncryptedPacket
& encrypted
,
1593 QuicConnectionIdLength connection_id_length
,
1594 bool includes_version
,
1595 QuicPacketNumberLength packet_number_length
) {
1597 encrypted
.data() + kStartOfHashData
,
1598 GetStartOfEncryptedData(connection_id_length
, includes_version
,
1599 packet_number_length
) -
1603 void QuicFramer::SetDecrypter(EncryptionLevel level
, QuicDecrypter
* decrypter
) {
1604 DCHECK(alternative_decrypter_
.get() == nullptr);
1605 DCHECK_GE(level
, decrypter_level_
);
1606 decrypter_
.reset(decrypter
);
1607 decrypter_level_
= level
;
1610 void QuicFramer::SetAlternativeDecrypter(EncryptionLevel level
,
1611 QuicDecrypter
* decrypter
,
1612 bool latch_once_used
) {
1613 alternative_decrypter_
.reset(decrypter
);
1614 alternative_decrypter_level_
= level
;
1615 alternative_decrypter_latch_
= latch_once_used
;
1618 const QuicDecrypter
* QuicFramer::decrypter() const {
1619 return decrypter_
.get();
1622 const QuicDecrypter
* QuicFramer::alternative_decrypter() const {
1623 return alternative_decrypter_
.get();
1626 void QuicFramer::SetEncrypter(EncryptionLevel level
,
1627 QuicEncrypter
* encrypter
) {
1628 DCHECK_GE(level
, 0);
1629 DCHECK_LT(level
, NUM_ENCRYPTION_LEVELS
);
1630 encrypter_
[level
].reset(encrypter
);
1633 QuicEncryptedPacket
* QuicFramer::EncryptPayload(
1634 EncryptionLevel level
,
1635 QuicPacketNumber packet_packet_number
,
1636 const QuicPacket
& packet
,
1638 size_t buffer_len
) {
1639 DCHECK(encrypter_
[level
].get() != nullptr);
1641 const size_t encrypted_len
=
1642 encrypter_
[level
]->GetCiphertextSize(packet
.Plaintext().length());
1643 StringPiece header_data
= packet
.BeforePlaintext();
1644 const size_t total_len
= header_data
.length() + encrypted_len
;
1646 char* encryption_buffer
= buffer
;
1647 // Allocate a large enough buffer for the header and the encrypted data.
1648 const bool is_new_buffer
= total_len
> buffer_len
;
1649 if (is_new_buffer
) {
1650 if (!FLAGS_quic_allow_oversized_packets_for_test
) {
1651 LOG(DFATAL
) << "Buffer of length:" << buffer_len
1652 << " is not large enough to encrypt length " << total_len
;
1655 encryption_buffer
= new char[total_len
];
1657 // Copy in the header, because the encrypter only populates the encrypted
1658 // plaintext content.
1659 memcpy(encryption_buffer
, header_data
.data(), header_data
.length());
1660 // Encrypt the plaintext into the buffer.
1661 size_t output_length
= 0;
1662 if (!encrypter_
[level
]->EncryptPacket(
1663 packet_packet_number
, packet
.AssociatedData(), packet
.Plaintext(),
1664 encryption_buffer
+ header_data
.length(), &output_length
,
1666 RaiseError(QUIC_ENCRYPTION_FAILURE
);
1670 return new QuicEncryptedPacket(
1671 encryption_buffer
, header_data
.length() + output_length
, is_new_buffer
);
1674 size_t QuicFramer::GetMaxPlaintextSize(size_t ciphertext_size
) {
1675 // In order to keep the code simple, we don't have the current encryption
1676 // level to hand. Both the NullEncrypter and AES-GCM have a tag length of 12.
1677 size_t min_plaintext_size
= ciphertext_size
;
1679 for (int i
= ENCRYPTION_NONE
; i
< NUM_ENCRYPTION_LEVELS
; i
++) {
1680 if (encrypter_
[i
].get() != nullptr) {
1681 size_t size
= encrypter_
[i
]->GetMaxPlaintextSize(ciphertext_size
);
1682 if (size
< min_plaintext_size
) {
1683 min_plaintext_size
= size
;
1688 return min_plaintext_size
;
1691 bool QuicFramer::DecryptPayload(QuicDataReader
* encrypted_reader
,
1692 const QuicPacketHeader
& header
,
1693 const QuicEncryptedPacket
& packet
,
1694 char* decrypted_buffer
,
1695 size_t buffer_length
,
1696 size_t* decrypted_length
) {
1697 StringPiece encrypted
= encrypted_reader
->ReadRemainingPayload();
1698 DCHECK(decrypter_
.get() != nullptr);
1699 const StringPiece
& associated_data
= GetAssociatedDataFromEncryptedPacket(
1700 packet
, header
.public_header
.connection_id_length
,
1701 header
.public_header
.version_flag
,
1702 header
.public_header
.packet_number_length
);
1703 bool success
= decrypter_
->DecryptPacket(
1704 header
.packet_packet_number
, associated_data
, encrypted
, decrypted_buffer
,
1705 decrypted_length
, buffer_length
);
1707 visitor_
->OnDecryptedPacket(decrypter_level_
);
1708 } else if (alternative_decrypter_
.get() != nullptr) {
1709 success
= alternative_decrypter_
->DecryptPacket(
1710 header
.packet_packet_number
, associated_data
, encrypted
,
1711 decrypted_buffer
, decrypted_length
, buffer_length
);
1713 visitor_
->OnDecryptedPacket(alternative_decrypter_level_
);
1714 if (alternative_decrypter_latch_
) {
1715 // Switch to the alternative decrypter and latch so that we cannot
1717 decrypter_
.reset(alternative_decrypter_
.release());
1718 decrypter_level_
= alternative_decrypter_level_
;
1719 alternative_decrypter_level_
= ENCRYPTION_NONE
;
1721 // Switch the alternative decrypter so that we use it first next time.
1722 decrypter_
.swap(alternative_decrypter_
);
1723 EncryptionLevel level
= alternative_decrypter_level_
;
1724 alternative_decrypter_level_
= decrypter_level_
;
1725 decrypter_level_
= level
;
1731 DLOG(WARNING
) << "DecryptPacket failed for packet_number:"
1732 << header
.packet_packet_number
;
1739 size_t QuicFramer::GetAckFrameSize(
1740 const QuicAckFrame
& ack
,
1741 QuicPacketNumberLength packet_number_length
) {
1742 AckFrameInfo ack_info
= GetAckFrameInfo(ack
);
1743 QuicPacketNumberLength largest_observed_length
=
1744 GetMinSequenceNumberLength(ack
.largest_observed
);
1745 QuicPacketNumberLength missing_packet_number_length
=
1746 GetMinSequenceNumberLength(ack_info
.max_delta
);
1748 size_t ack_size
= GetMinAckFrameSize(largest_observed_length
);
1749 if (!ack_info
.nack_ranges
.empty()) {
1750 ack_size
+= kNumberOfNackRangesSize
+ kNumberOfRevivedPacketsSize
;
1751 ack_size
+= min(ack_info
.nack_ranges
.size(), kMaxNackRanges
) *
1752 (missing_packet_number_length
+ PACKET_1BYTE_PACKET_NUMBER
);
1753 ack_size
+= min(ack
.revived_packets
.size(),
1754 kMaxRevivedPackets
) * largest_observed_length
;
1757 // In version 23, if the ack will be truncated due to too many nack ranges,
1758 // then do not include the number of timestamps (1 byte).
1759 if (ack_info
.nack_ranges
.size() <= kMaxNackRanges
) {
1760 // 1 byte for the number of timestamps.
1762 if (ack
.received_packet_times
.size() > 0) {
1763 // 1 byte for packet number, 4 bytes for timestamp for the first
1767 // 1 byte for packet number, 2 bytes for timestamp for the other
1769 ack_size
+= 3 * (ack
.received_packet_times
.size() - 1);
1776 size_t QuicFramer::ComputeFrameLength(
1777 const QuicFrame
& frame
,
1778 bool last_frame_in_packet
,
1779 InFecGroup is_in_fec_group
,
1780 QuicPacketNumberLength packet_number_length
) {
1781 switch (frame
.type
) {
1783 return GetMinStreamFrameSize(frame
.stream_frame
->stream_id
,
1784 frame
.stream_frame
->offset
,
1785 last_frame_in_packet
, is_in_fec_group
) +
1786 frame
.stream_frame
->data
.length();
1788 return GetAckFrameSize(*frame
.ack_frame
, packet_number_length
);
1790 case STOP_WAITING_FRAME
:
1791 return GetStopWaitingFrameSize(packet_number_length
);
1792 case MTU_DISCOVERY_FRAME
:
1793 // MTU discovery frames are serialized as ping frames.
1795 // Ping has no payload.
1796 return kQuicFrameTypeSize
;
1797 case RST_STREAM_FRAME
:
1798 if (quic_version_
<= QUIC_VERSION_24
) {
1799 return GetMinRstStreamFrameSize() +
1800 frame
.rst_stream_frame
->error_details
.size();
1802 return GetRstStreamFrameSize();
1803 case CONNECTION_CLOSE_FRAME
:
1804 return GetMinConnectionCloseFrameSize() +
1805 frame
.connection_close_frame
->error_details
.size();
1807 return GetMinGoAwayFrameSize() + frame
.goaway_frame
->reason_phrase
.size();
1808 case WINDOW_UPDATE_FRAME
:
1809 return GetWindowUpdateFrameSize();
1811 return GetBlockedFrameSize();
1815 case NUM_FRAME_TYPES
:
1820 // Not reachable, but some Chrome compilers can't figure that out. *sigh*
1825 bool QuicFramer::AppendTypeByte(const QuicFrame
& frame
,
1826 bool no_stream_frame_length
,
1827 QuicDataWriter
* writer
) {
1828 uint8 type_byte
= 0;
1829 switch (frame
.type
) {
1830 case STREAM_FRAME
: {
1831 if (frame
.stream_frame
== nullptr) {
1832 LOG(DFATAL
) << "Failed to append STREAM frame with no stream_frame.";
1835 type_byte
|= frame
.stream_frame
->fin
? kQuicStreamFinMask
: 0;
1838 type_byte
<<= kQuicStreamDataLengthShift
;
1839 type_byte
|= no_stream_frame_length
? 0: kQuicStreamDataLengthMask
;
1842 type_byte
<<= kQuicStreamOffsetShift
;
1843 const size_t offset_len
= GetStreamOffsetSize(frame
.stream_frame
->offset
);
1844 if (offset_len
> 0) {
1845 type_byte
|= offset_len
- 1;
1848 // stream id 2 bits.
1849 type_byte
<<= kQuicStreamIdShift
;
1850 type_byte
|= GetStreamIdSize(frame
.stream_frame
->stream_id
) - 1;
1851 type_byte
|= kQuicFrameTypeStreamMask
; // Set Stream Frame Type to 1.
1856 case MTU_DISCOVERY_FRAME
:
1857 type_byte
= static_cast<uint8
>(PING_FRAME
);
1860 type_byte
= static_cast<uint8
>(frame
.type
);
1864 return writer
->WriteUInt8(type_byte
);
1868 bool QuicFramer::AppendPacketSequenceNumber(
1869 QuicPacketNumberLength packet_number_length
,
1870 QuicPacketNumber packet_packet_number
,
1871 QuicDataWriter
* writer
) {
1872 // Ensure the entire packet number can be written.
1873 if (writer
->capacity() - writer
->length() <
1874 static_cast<size_t>(packet_number_length
)) {
1877 switch (packet_number_length
) {
1878 case PACKET_1BYTE_PACKET_NUMBER
:
1879 return writer
->WriteUInt8(packet_packet_number
&
1880 k1ByteSequenceNumberMask
);
1882 case PACKET_2BYTE_PACKET_NUMBER
:
1883 return writer
->WriteUInt16(packet_packet_number
&
1884 k2ByteSequenceNumberMask
);
1886 case PACKET_4BYTE_PACKET_NUMBER
:
1887 return writer
->WriteUInt32(packet_packet_number
&
1888 k4ByteSequenceNumberMask
);
1890 case PACKET_6BYTE_PACKET_NUMBER
:
1891 return writer
->WriteUInt48(packet_packet_number
&
1892 k6ByteSequenceNumberMask
);
1895 DCHECK(false) << "packet_number_length: " << packet_number_length
;
1900 bool QuicFramer::AppendStreamFrame(
1901 const QuicStreamFrame
& frame
,
1902 bool no_stream_frame_length
,
1903 QuicDataWriter
* writer
) {
1904 if (!writer
->WriteBytes(&frame
.stream_id
, GetStreamIdSize(frame
.stream_id
))) {
1905 LOG(DFATAL
) << "Writing stream id size failed.";
1908 if (!writer
->WriteBytes(&frame
.offset
, GetStreamOffsetSize(frame
.offset
))) {
1909 LOG(DFATAL
) << "Writing offset size failed.";
1912 if (!no_stream_frame_length
) {
1913 if ((frame
.data
.size() > numeric_limits
<uint16
>::max()) ||
1914 !writer
->WriteUInt16(static_cast<uint16
>(frame
.data
.size()))) {
1915 LOG(DFATAL
) << "Writing stream frame length failed";
1920 if (!writer
->WriteBytes(frame
.data
.data(), frame
.data
.size())) {
1921 LOG(DFATAL
) << "Writing frame data failed.";
1927 void QuicFramer::set_version(const QuicVersion version
) {
1928 DCHECK(IsSupportedVersion(version
)) << QuicVersionToString(version
);
1929 quic_version_
= version
;
1932 bool QuicFramer::AppendAckFrameAndTypeByte(
1933 const QuicPacketHeader
& header
,
1934 const QuicAckFrame
& frame
,
1935 QuicDataWriter
* writer
) {
1936 AckFrameInfo ack_info
= GetAckFrameInfo(frame
);
1937 QuicPacketNumber ack_largest_observed
= frame
.largest_observed
;
1938 QuicPacketNumberLength largest_observed_length
=
1939 GetMinSequenceNumberLength(ack_largest_observed
);
1940 QuicPacketNumberLength missing_packet_number_length
=
1941 GetMinSequenceNumberLength(ack_info
.max_delta
);
1942 // Determine whether we need to truncate ranges.
1943 size_t available_range_bytes
=
1944 writer
->capacity() - writer
->length() - kNumberOfRevivedPacketsSize
-
1945 kNumberOfNackRangesSize
- GetMinAckFrameSize(largest_observed_length
);
1946 size_t max_num_ranges
=
1947 available_range_bytes
/
1948 (missing_packet_number_length
+ PACKET_1BYTE_PACKET_NUMBER
);
1949 max_num_ranges
= min(kMaxNackRanges
, max_num_ranges
);
1950 bool truncated
= ack_info
.nack_ranges
.size() > max_num_ranges
;
1951 DVLOG_IF(1, truncated
) << "Truncating ack from "
1952 << ack_info
.nack_ranges
.size() << " ranges to "
1954 // Write out the type byte by setting the low order bits and doing shifts
1955 // to make room for the next bit flags to be set.
1956 // Whether there are any nacks.
1957 uint8 type_byte
= ack_info
.nack_ranges
.empty() ? 0 : kQuicHasNacksMask
;
1960 type_byte
<<= kQuicAckTruncatedShift
;
1961 type_byte
|= truncated
? kQuicAckTruncatedMask
: 0;
1963 // Largest observed packet number length.
1964 type_byte
<<= kQuicSequenceNumberLengthShift
;
1965 type_byte
|= GetSequenceNumberFlags(largest_observed_length
);
1967 // Missing packet number length.
1968 type_byte
<<= kQuicSequenceNumberLengthShift
;
1969 type_byte
|= GetSequenceNumberFlags(missing_packet_number_length
);
1971 type_byte
|= kQuicFrameTypeAckMask
;
1973 if (!writer
->WriteUInt8(type_byte
)) {
1977 QuicPacketEntropyHash ack_entropy_hash
= frame
.entropy_hash
;
1978 NackRangeMap::reverse_iterator ack_iter
= ack_info
.nack_ranges
.rbegin();
1980 // Skip the nack ranges which the truncated ack won't include and set
1981 // a correct largest observed for the truncated ack.
1982 for (size_t i
= 1; i
< (ack_info
.nack_ranges
.size() - max_num_ranges
);
1986 // If the last range is followed by acks, include them.
1987 // If the last range is followed by another range, specify the end of the
1988 // range as the largest_observed.
1989 ack_largest_observed
= ack_iter
->first
- 1;
1990 // Also update the entropy so it matches the largest observed.
1991 ack_entropy_hash
= entropy_calculator_
->EntropyHash(ack_largest_observed
);
1995 if (!writer
->WriteUInt8(ack_entropy_hash
)) {
1999 if (!AppendPacketSequenceNumber(largest_observed_length
,
2000 ack_largest_observed
, writer
)) {
2004 uint64 delta_time_largest_observed_us
= kUFloat16MaxValue
;
2005 if (!frame
.delta_time_largest_observed
.IsInfinite()) {
2006 DCHECK_LE(0u, frame
.delta_time_largest_observed
.ToMicroseconds());
2007 delta_time_largest_observed_us
=
2008 frame
.delta_time_largest_observed
.ToMicroseconds();
2011 if (!writer
->WriteUFloat16(delta_time_largest_observed_us
)) {
2015 // Timestamp goes at the end of the required fields.
2017 if (!AppendTimestampToAckFrame(frame
, writer
)) {
2022 if (ack_info
.nack_ranges
.empty()) {
2026 const uint8 num_missing_ranges
=
2027 static_cast<uint8
>(min(ack_info
.nack_ranges
.size(), max_num_ranges
));
2028 if (!writer
->WriteBytes(&num_missing_ranges
, 1)) {
2032 int num_ranges_written
= 0;
2033 QuicPacketNumber last_sequence_written
= ack_largest_observed
;
2034 for (; ack_iter
!= ack_info
.nack_ranges
.rend(); ++ack_iter
) {
2035 // Calculate the delta to the last number in the range.
2036 QuicPacketNumber missing_delta
=
2037 last_sequence_written
- (ack_iter
->first
+ ack_iter
->second
);
2038 if (!AppendPacketSequenceNumber(missing_packet_number_length
, missing_delta
,
2042 if (!AppendPacketSequenceNumber(PACKET_1BYTE_PACKET_NUMBER
,
2043 ack_iter
->second
, writer
)) {
2046 // Subtract 1 so a missing_delta of 0 means an adjacent range.
2047 last_sequence_written
= ack_iter
->first
- 1;
2048 ++num_ranges_written
;
2050 DCHECK_EQ(num_missing_ranges
, num_ranges_written
);
2052 // Append revived packets.
2053 // If not all the revived packets fit, only mention the ones that do.
2054 uint8 num_revived_packets
=
2055 static_cast<uint8
>(min(frame
.revived_packets
.size(), kMaxRevivedPackets
));
2056 num_revived_packets
= static_cast<uint8
>(min(
2057 static_cast<size_t>(num_revived_packets
),
2058 (writer
->capacity() - writer
->length()) / largest_observed_length
));
2059 if (!writer
->WriteBytes(&num_revived_packets
, 1)) {
2063 PacketNumberSet::const_iterator iter
= frame
.revived_packets
.begin();
2064 for (int i
= 0; i
< num_revived_packets
; ++i
, ++iter
) {
2065 LOG_IF(DFATAL
, !frame
.missing_packets
.Contains(*iter
));
2066 if (!AppendPacketSequenceNumber(largest_observed_length
,
2075 bool QuicFramer::AppendTimestampToAckFrame(const QuicAckFrame
& frame
,
2076 QuicDataWriter
* writer
) {
2077 DCHECK_GE(numeric_limits
<uint8
>::max(), frame
.received_packet_times
.size());
2078 // num_received_packets is only 1 byte.
2079 if (frame
.received_packet_times
.size() > numeric_limits
<uint8
>::max()) {
2083 uint8 num_received_packets
= frame
.received_packet_times
.size();
2085 if (!writer
->WriteBytes(&num_received_packets
, 1)) {
2088 if (num_received_packets
== 0) {
2092 PacketTimeList::const_iterator it
= frame
.received_packet_times
.begin();
2093 QuicPacketNumber packet_number
= it
->first
;
2094 QuicPacketNumber delta_from_largest_observed
=
2095 frame
.largest_observed
- packet_number
;
2097 DCHECK_GE(numeric_limits
<uint8
>::max(), delta_from_largest_observed
);
2098 if (delta_from_largest_observed
> numeric_limits
<uint8
>::max()) {
2102 if (!writer
->WriteUInt8(
2103 delta_from_largest_observed
& k1ByteSequenceNumberMask
)) {
2107 // Use the lowest 4 bytes of the time delta from the creation_time_.
2108 const uint64 time_epoch_delta_us
= UINT64_C(1) << 32;
2109 uint32 time_delta_us
=
2110 static_cast<uint32
>(it
->second
.Subtract(creation_time_
).ToMicroseconds()
2111 & (time_epoch_delta_us
- 1));
2112 if (!writer
->WriteBytes(&time_delta_us
, sizeof(time_delta_us
))) {
2116 QuicTime prev_time
= it
->second
;
2118 for (++it
; it
!= frame
.received_packet_times
.end(); ++it
) {
2119 packet_number
= it
->first
;
2120 delta_from_largest_observed
= frame
.largest_observed
- packet_number
;
2122 if (delta_from_largest_observed
> numeric_limits
<uint8
>::max()) {
2126 if (!writer
->WriteUInt8(
2127 delta_from_largest_observed
& k1ByteSequenceNumberMask
)) {
2131 uint64 frame_time_delta_us
=
2132 it
->second
.Subtract(prev_time
).ToMicroseconds();
2133 prev_time
= it
->second
;
2134 if (!writer
->WriteUFloat16(frame_time_delta_us
)) {
2141 bool QuicFramer::AppendStopWaitingFrame(
2142 const QuicPacketHeader
& header
,
2143 const QuicStopWaitingFrame
& frame
,
2144 QuicDataWriter
* writer
) {
2145 DCHECK_GE(header
.packet_packet_number
, frame
.least_unacked
);
2146 const QuicPacketNumber least_unacked_delta
=
2147 header
.packet_packet_number
- frame
.least_unacked
;
2148 const QuicPacketNumber length_shift
=
2149 header
.public_header
.packet_number_length
* 8;
2150 if (!writer
->WriteUInt8(frame
.entropy_hash
)) {
2151 LOG(DFATAL
) << " hash failed";
2155 if (least_unacked_delta
>> length_shift
> 0) {
2156 LOG(DFATAL
) << "packet_number_length "
2157 << header
.public_header
.packet_number_length
2158 << " is too small for least_unacked_delta: "
2159 << least_unacked_delta
;
2162 if (!AppendPacketSequenceNumber(header
.public_header
.packet_number_length
,
2163 least_unacked_delta
, writer
)) {
2164 LOG(DFATAL
) << " seq failed: " << header
.public_header
.packet_number_length
;
2171 bool QuicFramer::AppendRstStreamFrame(const QuicRstStreamFrame
& frame
,
2172 QuicDataWriter
* writer
) {
2173 if (!writer
->WriteUInt32(frame
.stream_id
)) {
2177 if (!writer
->WriteUInt64(frame
.byte_offset
)) {
2181 uint32 error_code
= static_cast<uint32
>(frame
.error_code
);
2182 if (!writer
->WriteUInt32(error_code
)) {
2186 if (quic_version_
<= QUIC_VERSION_24
) {
2187 if (!writer
->WriteStringPiece16(frame
.error_details
)) {
2194 bool QuicFramer::AppendConnectionCloseFrame(
2195 const QuicConnectionCloseFrame
& frame
,
2196 QuicDataWriter
* writer
) {
2197 uint32 error_code
= static_cast<uint32
>(frame
.error_code
);
2198 if (!writer
->WriteUInt32(error_code
)) {
2201 if (!writer
->WriteStringPiece16(frame
.error_details
)) {
2207 bool QuicFramer::AppendGoAwayFrame(const QuicGoAwayFrame
& frame
,
2208 QuicDataWriter
* writer
) {
2209 uint32 error_code
= static_cast<uint32
>(frame
.error_code
);
2210 if (!writer
->WriteUInt32(error_code
)) {
2213 uint32 stream_id
= static_cast<uint32
>(frame
.last_good_stream_id
);
2214 if (!writer
->WriteUInt32(stream_id
)) {
2217 if (!writer
->WriteStringPiece16(frame
.reason_phrase
)) {
2223 bool QuicFramer::AppendWindowUpdateFrame(const QuicWindowUpdateFrame
& frame
,
2224 QuicDataWriter
* writer
) {
2225 uint32 stream_id
= static_cast<uint32
>(frame
.stream_id
);
2226 if (!writer
->WriteUInt32(stream_id
)) {
2229 if (!writer
->WriteUInt64(frame
.byte_offset
)) {
2235 bool QuicFramer::AppendBlockedFrame(const QuicBlockedFrame
& frame
,
2236 QuicDataWriter
* writer
) {
2237 uint32 stream_id
= static_cast<uint32
>(frame
.stream_id
);
2238 if (!writer
->WriteUInt32(stream_id
)) {
2244 bool QuicFramer::RaiseError(QuicErrorCode error
) {
2245 DVLOG(1) << "Error: " << QuicUtils::ErrorToString(error
)
2246 << " detail: " << detailed_error_
;
2248 visitor_
->OnError(this);