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 PacketNumberQueue::const_iterator iter
= frame
.missing_packets
.begin();
993 // TODO(jdorfman): Switch this logic to use the intervals in PacketNumberQueue
994 // instead of reconstructing them from the sequence.
995 QuicPacketNumber last_missing
= *iter
;
997 for (; iter
!= frame
.missing_packets
.end(); ++iter
) {
998 if (cur_range_length
< numeric_limits
<uint8
>::max() &&
999 *iter
== (last_missing
+ 1)) {
1002 ack_info
.nack_ranges
[last_missing
- cur_range_length
] =
1003 static_cast<uint8
>(cur_range_length
);
1004 cur_range_length
= 0;
1006 ack_info
.max_delta
= max(ack_info
.max_delta
, *iter
- last_missing
);
1007 last_missing
= *iter
;
1009 // Include the last nack range.
1010 ack_info
.nack_ranges
[last_missing
- cur_range_length
] =
1011 static_cast<uint8
>(cur_range_length
);
1012 // Include the range to the largest observed.
1013 ack_info
.max_delta
=
1014 max(ack_info
.max_delta
, frame
.largest_observed
- last_missing
);
1018 bool QuicFramer::ProcessUnauthenticatedHeader(QuicDataReader
* encrypted_reader
,
1019 QuicPacketHeader
* header
) {
1020 if (!ProcessPacketSequenceNumber(encrypted_reader
,
1021 header
->public_header
.packet_number_length
,
1022 &header
->packet_packet_number
)) {
1023 set_detailed_error("Unable to read packet number.");
1024 return RaiseError(QUIC_INVALID_PACKET_HEADER
);
1027 if (header
->packet_packet_number
== 0u) {
1028 set_detailed_error("packet numbers cannot be 0.");
1029 return RaiseError(QUIC_INVALID_PACKET_HEADER
);
1032 if (!visitor_
->OnUnauthenticatedHeader(*header
)) {
1038 bool QuicFramer::ProcessAuthenticatedHeader(QuicDataReader
* reader
,
1039 QuicPacketHeader
* header
) {
1040 uint8 private_flags
;
1041 if (!reader
->ReadBytes(&private_flags
, 1)) {
1042 set_detailed_error("Unable to read private flags.");
1043 return RaiseError(QUIC_INVALID_PACKET_HEADER
);
1046 if (private_flags
> PACKET_PRIVATE_FLAGS_MAX
) {
1047 set_detailed_error("Illegal private flags value.");
1048 return RaiseError(QUIC_INVALID_PACKET_HEADER
);
1051 header
->entropy_flag
= (private_flags
& PACKET_PRIVATE_FLAGS_ENTROPY
) != 0;
1052 header
->fec_flag
= (private_flags
& PACKET_PRIVATE_FLAGS_FEC
) != 0;
1054 if ((private_flags
& PACKET_PRIVATE_FLAGS_FEC_GROUP
) != 0) {
1055 header
->is_in_fec_group
= IN_FEC_GROUP
;
1056 uint8 first_fec_protected_packet_offset
;
1057 if (!reader
->ReadBytes(&first_fec_protected_packet_offset
, 1)) {
1058 set_detailed_error("Unable to read first fec protected packet offset.");
1059 return RaiseError(QUIC_INVALID_PACKET_HEADER
);
1061 if (first_fec_protected_packet_offset
>= header
->packet_packet_number
) {
1063 "First fec protected packet offset must be less "
1064 "than the packet number.");
1065 return RaiseError(QUIC_INVALID_PACKET_HEADER
);
1068 header
->packet_packet_number
- first_fec_protected_packet_offset
;
1071 header
->entropy_hash
= GetPacketEntropyHash(*header
);
1072 // Set the last packet number after we have decrypted the packet
1073 // so we are confident is not attacker controlled.
1074 last_packet_number_
= header
->packet_packet_number
;
1078 bool QuicFramer::ProcessPacketSequenceNumber(
1079 QuicDataReader
* reader
,
1080 QuicPacketNumberLength packet_number_length
,
1081 QuicPacketNumber
* packet_number
) {
1082 QuicPacketNumber wire_packet_number
= 0u;
1083 if (!reader
->ReadBytes(&wire_packet_number
, packet_number_length
)) {
1087 // TODO(ianswett): Explore the usefulness of trying multiple packet numbers
1088 // in case the first guess is incorrect.
1090 CalculatePacketNumberFromWire(packet_number_length
, wire_packet_number
);
1094 bool QuicFramer::ProcessFrameData(QuicDataReader
* reader
,
1095 const QuicPacketHeader
& header
) {
1096 if (reader
->IsDoneReading()) {
1097 set_detailed_error("Packet has no frames.");
1098 return RaiseError(QUIC_MISSING_PAYLOAD
);
1100 while (!reader
->IsDoneReading()) {
1102 if (!reader
->ReadBytes(&frame_type
, 1)) {
1103 set_detailed_error("Unable to read frame type.");
1104 return RaiseError(QUIC_INVALID_FRAME_DATA
);
1107 if (frame_type
& kQuicFrameTypeSpecialMask
) {
1109 if (frame_type
& kQuicFrameTypeStreamMask
) {
1110 QuicStreamFrame frame
;
1111 if (!ProcessStreamFrame(reader
, frame_type
, &frame
)) {
1112 return RaiseError(QUIC_INVALID_STREAM_DATA
);
1114 if (!visitor_
->OnStreamFrame(frame
)) {
1115 DVLOG(1) << "Visitor asked to stop further processing.";
1116 // Returning true since there was no parsing error.
1123 if (frame_type
& kQuicFrameTypeAckMask
) {
1125 if (!ProcessAckFrame(reader
, frame_type
, &frame
)) {
1126 return RaiseError(QUIC_INVALID_ACK_DATA
);
1128 if (!visitor_
->OnAckFrame(frame
)) {
1129 DVLOG(1) << "Visitor asked to stop further processing.";
1130 // Returning true since there was no parsing error.
1136 // This was a special frame type that did not match any
1137 // of the known ones. Error.
1138 set_detailed_error("Illegal frame type.");
1139 DLOG(WARNING
) << "Illegal frame type: "
1140 << static_cast<int>(frame_type
);
1141 return RaiseError(QUIC_INVALID_FRAME_DATA
);
1144 switch (frame_type
) {
1146 // We're done with the packet.
1149 case RST_STREAM_FRAME
: {
1150 QuicRstStreamFrame frame
;
1151 if (!ProcessRstStreamFrame(reader
, &frame
)) {
1152 return RaiseError(QUIC_INVALID_RST_STREAM_DATA
);
1154 if (!visitor_
->OnRstStreamFrame(frame
)) {
1155 DVLOG(1) << "Visitor asked to stop further processing.";
1156 // Returning true since there was no parsing error.
1162 case CONNECTION_CLOSE_FRAME
: {
1163 QuicConnectionCloseFrame frame
;
1164 if (!ProcessConnectionCloseFrame(reader
, &frame
)) {
1165 return RaiseError(QUIC_INVALID_CONNECTION_CLOSE_DATA
);
1168 if (!visitor_
->OnConnectionCloseFrame(frame
)) {
1169 DVLOG(1) << "Visitor asked to stop further processing.";
1170 // Returning true since there was no parsing error.
1176 case GOAWAY_FRAME
: {
1177 QuicGoAwayFrame goaway_frame
;
1178 if (!ProcessGoAwayFrame(reader
, &goaway_frame
)) {
1179 return RaiseError(QUIC_INVALID_GOAWAY_DATA
);
1181 if (!visitor_
->OnGoAwayFrame(goaway_frame
)) {
1182 DVLOG(1) << "Visitor asked to stop further processing.";
1183 // Returning true since there was no parsing error.
1189 case WINDOW_UPDATE_FRAME
: {
1190 QuicWindowUpdateFrame window_update_frame
;
1191 if (!ProcessWindowUpdateFrame(reader
, &window_update_frame
)) {
1192 return RaiseError(QUIC_INVALID_WINDOW_UPDATE_DATA
);
1194 if (!visitor_
->OnWindowUpdateFrame(window_update_frame
)) {
1195 DVLOG(1) << "Visitor asked to stop further processing.";
1196 // Returning true since there was no parsing error.
1202 case BLOCKED_FRAME
: {
1203 QuicBlockedFrame blocked_frame
;
1204 if (!ProcessBlockedFrame(reader
, &blocked_frame
)) {
1205 return RaiseError(QUIC_INVALID_BLOCKED_DATA
);
1207 if (!visitor_
->OnBlockedFrame(blocked_frame
)) {
1208 DVLOG(1) << "Visitor asked to stop further processing.";
1209 // Returning true since there was no parsing error.
1215 case STOP_WAITING_FRAME
: {
1216 QuicStopWaitingFrame stop_waiting_frame
;
1217 if (!ProcessStopWaitingFrame(reader
, header
, &stop_waiting_frame
)) {
1218 return RaiseError(QUIC_INVALID_STOP_WAITING_DATA
);
1220 if (!visitor_
->OnStopWaitingFrame(stop_waiting_frame
)) {
1221 DVLOG(1) << "Visitor asked to stop further processing.";
1222 // Returning true since there was no parsing error.
1228 // Ping has no payload.
1229 QuicPingFrame ping_frame
;
1230 if (!visitor_
->OnPingFrame(ping_frame
)) {
1231 DVLOG(1) << "Visitor asked to stop further processing.";
1232 // Returning true since there was no parsing error.
1239 set_detailed_error("Illegal frame type.");
1240 DLOG(WARNING
) << "Illegal frame type: "
1241 << static_cast<int>(frame_type
);
1242 return RaiseError(QUIC_INVALID_FRAME_DATA
);
1249 bool QuicFramer::ProcessStreamFrame(QuicDataReader
* reader
,
1251 QuicStreamFrame
* frame
) {
1252 uint8 stream_flags
= frame_type
;
1254 stream_flags
&= ~kQuicFrameTypeStreamMask
;
1256 // Read from right to left: StreamID, Offset, Data Length, Fin.
1257 const uint8 stream_id_length
= (stream_flags
& kQuicStreamIDLengthMask
) + 1;
1258 stream_flags
>>= kQuicStreamIdShift
;
1260 uint8 offset_length
= (stream_flags
& kQuicStreamOffsetMask
);
1261 // There is no encoding for 1 byte, only 0 and 2 through 8.
1262 if (offset_length
> 0) {
1265 stream_flags
>>= kQuicStreamOffsetShift
;
1267 bool has_data_length
=
1268 (stream_flags
& kQuicStreamDataLengthMask
) == kQuicStreamDataLengthMask
;
1269 stream_flags
>>= kQuicStreamDataLengthShift
;
1271 frame
->fin
= (stream_flags
& kQuicStreamFinMask
) == kQuicStreamFinShift
;
1273 frame
->stream_id
= 0;
1274 if (!reader
->ReadBytes(&frame
->stream_id
, stream_id_length
)) {
1275 set_detailed_error("Unable to read stream_id.");
1280 if (!reader
->ReadBytes(&frame
->offset
, offset_length
)) {
1281 set_detailed_error("Unable to read offset.");
1285 if (has_data_length
) {
1286 if (!reader
->ReadStringPiece16(&frame
->data
)) {
1287 set_detailed_error("Unable to read frame data.");
1291 if (!reader
->ReadStringPiece(&frame
->data
, reader
->BytesRemaining())) {
1292 set_detailed_error("Unable to read frame data.");
1300 bool QuicFramer::ProcessAckFrame(QuicDataReader
* reader
,
1302 QuicAckFrame
* ack_frame
) {
1303 // Determine the three lengths from the frame type: largest observed length,
1304 // missing packet number length, and missing range length.
1305 const QuicPacketNumberLength missing_packet_number_length
=
1306 ReadSequenceNumberLength(frame_type
);
1307 frame_type
>>= kQuicSequenceNumberLengthShift
;
1308 const QuicPacketNumberLength largest_observed_packet_number_length
=
1309 ReadSequenceNumberLength(frame_type
);
1310 frame_type
>>= kQuicSequenceNumberLengthShift
;
1311 ack_frame
->is_truncated
= frame_type
& kQuicAckTruncatedMask
;
1312 frame_type
>>= kQuicAckTruncatedShift
;
1313 bool has_nacks
= frame_type
& kQuicHasNacksMask
;
1315 if (!reader
->ReadBytes(&ack_frame
->entropy_hash
, 1)) {
1316 set_detailed_error("Unable to read entropy hash for received packets.");
1320 if (!reader
->ReadBytes(&ack_frame
->largest_observed
,
1321 largest_observed_packet_number_length
)) {
1322 set_detailed_error("Unable to read largest observed.");
1326 uint64 delta_time_largest_observed_us
;
1327 if (!reader
->ReadUFloat16(&delta_time_largest_observed_us
)) {
1328 set_detailed_error("Unable to read delta time largest observed.");
1332 if (delta_time_largest_observed_us
== kUFloat16MaxValue
) {
1333 ack_frame
->delta_time_largest_observed
= QuicTime::Delta::Infinite();
1335 ack_frame
->delta_time_largest_observed
=
1336 QuicTime::Delta::FromMicroseconds(delta_time_largest_observed_us
);
1339 if (!ProcessTimestampsInAckFrame(reader
, ack_frame
)) {
1347 uint8 num_missing_ranges
;
1348 if (!reader
->ReadBytes(&num_missing_ranges
, 1)) {
1349 set_detailed_error("Unable to read num missing packet ranges.");
1353 QuicPacketNumber last_packet_number
= ack_frame
->largest_observed
;
1354 for (size_t i
= 0; i
< num_missing_ranges
; ++i
) {
1355 QuicPacketNumber missing_delta
= 0;
1356 if (!reader
->ReadBytes(&missing_delta
, missing_packet_number_length
)) {
1357 set_detailed_error("Unable to read missing packet number delta.");
1360 last_packet_number
-= missing_delta
;
1361 QuicPacketNumber range_length
= 0;
1362 if (!reader
->ReadBytes(&range_length
, PACKET_1BYTE_PACKET_NUMBER
)) {
1363 set_detailed_error("Unable to read missing packet number range.");
1366 ack_frame
->missing_packets
.Add(last_packet_number
- range_length
,
1367 last_packet_number
+ 1);
1368 // Subtract an extra 1 to ensure ranges are represented efficiently and
1369 // can't overlap by 1 packet number. This allows a missing_delta of 0
1370 // to represent an adjacent nack range.
1371 last_packet_number
-= (range_length
+ 1);
1374 // Parse the revived packets list.
1375 uint8 num_revived_packets
;
1376 if (!reader
->ReadBytes(&num_revived_packets
, 1)) {
1377 set_detailed_error("Unable to read num revived packets.");
1381 for (size_t i
= 0; i
< num_revived_packets
; ++i
) {
1382 QuicPacketNumber revived_packet
= 0;
1383 if (!reader
->ReadBytes(&revived_packet
,
1384 largest_observed_packet_number_length
)) {
1385 set_detailed_error("Unable to read revived packet.");
1389 ack_frame
->revived_packets
.insert(revived_packet
);
1395 bool QuicFramer::ProcessTimestampsInAckFrame(QuicDataReader
* reader
,
1396 QuicAckFrame
* ack_frame
) {
1397 if (ack_frame
->is_truncated
) {
1400 uint8 num_received_packets
;
1401 if (!reader
->ReadBytes(&num_received_packets
, 1)) {
1402 set_detailed_error("Unable to read num received packets.");
1406 if (num_received_packets
> 0) {
1407 uint8 delta_from_largest_observed
;
1408 if (!reader
->ReadBytes(&delta_from_largest_observed
,
1409 PACKET_1BYTE_PACKET_NUMBER
)) {
1410 set_detailed_error("Unable to read sequence delta in received packets.");
1413 QuicPacketNumber seq_num
=
1414 ack_frame
->largest_observed
- delta_from_largest_observed
;
1416 // Time delta from the framer creation.
1417 uint32 time_delta_us
;
1418 if (!reader
->ReadBytes(&time_delta_us
, sizeof(time_delta_us
))) {
1419 set_detailed_error("Unable to read time delta in received packets.");
1423 last_timestamp_
= CalculateTimestampFromWire(time_delta_us
);
1425 ack_frame
->received_packet_times
.push_back(
1426 std::make_pair(seq_num
, creation_time_
.Add(last_timestamp_
)));
1428 for (uint8 i
= 1; i
< num_received_packets
; ++i
) {
1429 if (!reader
->ReadBytes(&delta_from_largest_observed
,
1430 PACKET_1BYTE_PACKET_NUMBER
)) {
1432 "Unable to read sequence delta in received packets.");
1435 seq_num
= ack_frame
->largest_observed
- delta_from_largest_observed
;
1437 // Time delta from the previous timestamp.
1438 uint64 incremental_time_delta_us
;
1439 if (!reader
->ReadUFloat16(&incremental_time_delta_us
)) {
1441 "Unable to read incremental time delta in received packets.");
1445 last_timestamp_
= last_timestamp_
.Add(
1446 QuicTime::Delta::FromMicroseconds(incremental_time_delta_us
));
1447 ack_frame
->received_packet_times
.push_back(
1448 std::make_pair(seq_num
, creation_time_
.Add(last_timestamp_
)));
1454 bool QuicFramer::ProcessStopWaitingFrame(QuicDataReader
* reader
,
1455 const QuicPacketHeader
& header
,
1456 QuicStopWaitingFrame
* stop_waiting
) {
1457 if (!reader
->ReadBytes(&stop_waiting
->entropy_hash
, 1)) {
1458 set_detailed_error("Unable to read entropy hash for sent packets.");
1462 QuicPacketNumber least_unacked_delta
= 0;
1463 if (!reader
->ReadBytes(&least_unacked_delta
,
1464 header
.public_header
.packet_number_length
)) {
1465 set_detailed_error("Unable to read least unacked delta.");
1468 DCHECK_GE(header
.packet_packet_number
, least_unacked_delta
);
1469 stop_waiting
->least_unacked
=
1470 header
.packet_packet_number
- least_unacked_delta
;
1475 bool QuicFramer::ProcessRstStreamFrame(QuicDataReader
* reader
,
1476 QuicRstStreamFrame
* frame
) {
1477 if (!reader
->ReadUInt32(&frame
->stream_id
)) {
1478 set_detailed_error("Unable to read stream_id.");
1482 if (!reader
->ReadUInt64(&frame
->byte_offset
)) {
1483 set_detailed_error("Unable to read rst stream sent byte offset.");
1488 if (!reader
->ReadUInt32(&error_code
)) {
1489 set_detailed_error("Unable to read rst stream error code.");
1493 if (error_code
>= QUIC_STREAM_LAST_ERROR
) {
1494 set_detailed_error("Invalid rst stream error code.");
1498 frame
->error_code
= static_cast<QuicRstStreamErrorCode
>(error_code
);
1499 if (quic_version_
<= QUIC_VERSION_24
) {
1500 StringPiece error_details
;
1501 if (!reader
->ReadStringPiece16(&error_details
)) {
1502 set_detailed_error("Unable to read rst stream error details.");
1505 frame
->error_details
= error_details
.as_string();
1511 bool QuicFramer::ProcessConnectionCloseFrame(QuicDataReader
* reader
,
1512 QuicConnectionCloseFrame
* frame
) {
1514 if (!reader
->ReadUInt32(&error_code
)) {
1515 set_detailed_error("Unable to read connection close error code.");
1519 if (error_code
>= QUIC_LAST_ERROR
) {
1520 set_detailed_error("Invalid error code.");
1524 frame
->error_code
= static_cast<QuicErrorCode
>(error_code
);
1526 StringPiece error_details
;
1527 if (!reader
->ReadStringPiece16(&error_details
)) {
1528 set_detailed_error("Unable to read connection close error details.");
1531 frame
->error_details
= error_details
.as_string();
1536 bool QuicFramer::ProcessGoAwayFrame(QuicDataReader
* reader
,
1537 QuicGoAwayFrame
* frame
) {
1539 if (!reader
->ReadUInt32(&error_code
)) {
1540 set_detailed_error("Unable to read go away error code.");
1543 frame
->error_code
= static_cast<QuicErrorCode
>(error_code
);
1545 if (error_code
>= QUIC_LAST_ERROR
) {
1546 set_detailed_error("Invalid error code.");
1551 if (!reader
->ReadUInt32(&stream_id
)) {
1552 set_detailed_error("Unable to read last good stream id.");
1555 frame
->last_good_stream_id
= static_cast<QuicStreamId
>(stream_id
);
1557 StringPiece reason_phrase
;
1558 if (!reader
->ReadStringPiece16(&reason_phrase
)) {
1559 set_detailed_error("Unable to read goaway reason.");
1562 frame
->reason_phrase
= reason_phrase
.as_string();
1567 bool QuicFramer::ProcessWindowUpdateFrame(QuicDataReader
* reader
,
1568 QuicWindowUpdateFrame
* frame
) {
1569 if (!reader
->ReadUInt32(&frame
->stream_id
)) {
1570 set_detailed_error("Unable to read stream_id.");
1574 if (!reader
->ReadUInt64(&frame
->byte_offset
)) {
1575 set_detailed_error("Unable to read window byte_offset.");
1582 bool QuicFramer::ProcessBlockedFrame(QuicDataReader
* reader
,
1583 QuicBlockedFrame
* frame
) {
1584 if (!reader
->ReadUInt32(&frame
->stream_id
)) {
1585 set_detailed_error("Unable to read stream_id.");
1593 StringPiece
QuicFramer::GetAssociatedDataFromEncryptedPacket(
1594 const QuicEncryptedPacket
& encrypted
,
1595 QuicConnectionIdLength connection_id_length
,
1596 bool includes_version
,
1597 QuicPacketNumberLength packet_number_length
) {
1599 encrypted
.data() + kStartOfHashData
,
1600 GetStartOfEncryptedData(connection_id_length
, includes_version
,
1601 packet_number_length
) -
1605 void QuicFramer::SetDecrypter(EncryptionLevel level
, QuicDecrypter
* decrypter
) {
1606 DCHECK(alternative_decrypter_
.get() == nullptr);
1607 DCHECK_GE(level
, decrypter_level_
);
1608 decrypter_
.reset(decrypter
);
1609 decrypter_level_
= level
;
1612 void QuicFramer::SetAlternativeDecrypter(EncryptionLevel level
,
1613 QuicDecrypter
* decrypter
,
1614 bool latch_once_used
) {
1615 alternative_decrypter_
.reset(decrypter
);
1616 alternative_decrypter_level_
= level
;
1617 alternative_decrypter_latch_
= latch_once_used
;
1620 const QuicDecrypter
* QuicFramer::decrypter() const {
1621 return decrypter_
.get();
1624 const QuicDecrypter
* QuicFramer::alternative_decrypter() const {
1625 return alternative_decrypter_
.get();
1628 void QuicFramer::SetEncrypter(EncryptionLevel level
,
1629 QuicEncrypter
* encrypter
) {
1630 DCHECK_GE(level
, 0);
1631 DCHECK_LT(level
, NUM_ENCRYPTION_LEVELS
);
1632 encrypter_
[level
].reset(encrypter
);
1635 QuicEncryptedPacket
* QuicFramer::EncryptPayload(
1636 EncryptionLevel level
,
1637 QuicPacketNumber packet_packet_number
,
1638 const QuicPacket
& packet
,
1640 size_t buffer_len
) {
1641 DCHECK(encrypter_
[level
].get() != nullptr);
1643 const size_t encrypted_len
=
1644 encrypter_
[level
]->GetCiphertextSize(packet
.Plaintext().length());
1645 StringPiece header_data
= packet
.BeforePlaintext();
1646 const size_t total_len
= header_data
.length() + encrypted_len
;
1648 char* encryption_buffer
= buffer
;
1649 // Allocate a large enough buffer for the header and the encrypted data.
1650 const bool is_new_buffer
= total_len
> buffer_len
;
1651 if (is_new_buffer
) {
1652 if (!FLAGS_quic_allow_oversized_packets_for_test
) {
1653 LOG(DFATAL
) << "Buffer of length:" << buffer_len
1654 << " is not large enough to encrypt length " << total_len
;
1657 encryption_buffer
= new char[total_len
];
1659 // Copy in the header, because the encrypter only populates the encrypted
1660 // plaintext content.
1661 memcpy(encryption_buffer
, header_data
.data(), header_data
.length());
1662 // Encrypt the plaintext into the buffer.
1663 size_t output_length
= 0;
1664 if (!encrypter_
[level
]->EncryptPacket(
1665 packet_packet_number
, packet
.AssociatedData(), packet
.Plaintext(),
1666 encryption_buffer
+ header_data
.length(), &output_length
,
1668 RaiseError(QUIC_ENCRYPTION_FAILURE
);
1672 return new QuicEncryptedPacket(
1673 encryption_buffer
, header_data
.length() + output_length
, is_new_buffer
);
1676 size_t QuicFramer::GetMaxPlaintextSize(size_t ciphertext_size
) {
1677 // In order to keep the code simple, we don't have the current encryption
1678 // level to hand. Both the NullEncrypter and AES-GCM have a tag length of 12.
1679 size_t min_plaintext_size
= ciphertext_size
;
1681 for (int i
= ENCRYPTION_NONE
; i
< NUM_ENCRYPTION_LEVELS
; i
++) {
1682 if (encrypter_
[i
].get() != nullptr) {
1683 size_t size
= encrypter_
[i
]->GetMaxPlaintextSize(ciphertext_size
);
1684 if (size
< min_plaintext_size
) {
1685 min_plaintext_size
= size
;
1690 return min_plaintext_size
;
1693 bool QuicFramer::DecryptPayload(QuicDataReader
* encrypted_reader
,
1694 const QuicPacketHeader
& header
,
1695 const QuicEncryptedPacket
& packet
,
1696 char* decrypted_buffer
,
1697 size_t buffer_length
,
1698 size_t* decrypted_length
) {
1699 StringPiece encrypted
= encrypted_reader
->ReadRemainingPayload();
1700 DCHECK(decrypter_
.get() != nullptr);
1701 const StringPiece
& associated_data
= GetAssociatedDataFromEncryptedPacket(
1702 packet
, header
.public_header
.connection_id_length
,
1703 header
.public_header
.version_flag
,
1704 header
.public_header
.packet_number_length
);
1705 bool success
= decrypter_
->DecryptPacket(
1706 header
.packet_packet_number
, associated_data
, encrypted
, decrypted_buffer
,
1707 decrypted_length
, buffer_length
);
1709 visitor_
->OnDecryptedPacket(decrypter_level_
);
1710 } else if (alternative_decrypter_
.get() != nullptr) {
1711 success
= alternative_decrypter_
->DecryptPacket(
1712 header
.packet_packet_number
, associated_data
, encrypted
,
1713 decrypted_buffer
, decrypted_length
, buffer_length
);
1715 visitor_
->OnDecryptedPacket(alternative_decrypter_level_
);
1716 if (alternative_decrypter_latch_
) {
1717 // Switch to the alternative decrypter and latch so that we cannot
1719 decrypter_
.reset(alternative_decrypter_
.release());
1720 decrypter_level_
= alternative_decrypter_level_
;
1721 alternative_decrypter_level_
= ENCRYPTION_NONE
;
1723 // Switch the alternative decrypter so that we use it first next time.
1724 decrypter_
.swap(alternative_decrypter_
);
1725 EncryptionLevel level
= alternative_decrypter_level_
;
1726 alternative_decrypter_level_
= decrypter_level_
;
1727 decrypter_level_
= level
;
1733 DLOG(WARNING
) << "DecryptPacket failed for packet_number:"
1734 << header
.packet_packet_number
;
1741 size_t QuicFramer::GetAckFrameSize(
1742 const QuicAckFrame
& ack
,
1743 QuicPacketNumberLength packet_number_length
) {
1744 AckFrameInfo ack_info
= GetAckFrameInfo(ack
);
1745 QuicPacketNumberLength largest_observed_length
=
1746 GetMinSequenceNumberLength(ack
.largest_observed
);
1747 QuicPacketNumberLength missing_packet_number_length
=
1748 GetMinSequenceNumberLength(ack_info
.max_delta
);
1750 size_t ack_size
= GetMinAckFrameSize(largest_observed_length
);
1751 if (!ack_info
.nack_ranges
.empty()) {
1752 ack_size
+= kNumberOfNackRangesSize
+ kNumberOfRevivedPacketsSize
;
1753 ack_size
+= min(ack_info
.nack_ranges
.size(), kMaxNackRanges
) *
1754 (missing_packet_number_length
+ PACKET_1BYTE_PACKET_NUMBER
);
1755 ack_size
+= min(ack
.revived_packets
.size(),
1756 kMaxRevivedPackets
) * largest_observed_length
;
1759 // In version 23, if the ack will be truncated due to too many nack ranges,
1760 // then do not include the number of timestamps (1 byte).
1761 if (ack_info
.nack_ranges
.size() <= kMaxNackRanges
) {
1762 // 1 byte for the number of timestamps.
1764 if (ack
.received_packet_times
.size() > 0) {
1765 // 1 byte for packet number, 4 bytes for timestamp for the first
1769 // 1 byte for packet number, 2 bytes for timestamp for the other
1771 ack_size
+= 3 * (ack
.received_packet_times
.size() - 1);
1778 size_t QuicFramer::ComputeFrameLength(
1779 const QuicFrame
& frame
,
1780 bool last_frame_in_packet
,
1781 InFecGroup is_in_fec_group
,
1782 QuicPacketNumberLength packet_number_length
) {
1783 switch (frame
.type
) {
1785 return GetMinStreamFrameSize(frame
.stream_frame
->stream_id
,
1786 frame
.stream_frame
->offset
,
1787 last_frame_in_packet
, is_in_fec_group
) +
1788 frame
.stream_frame
->data
.length();
1790 return GetAckFrameSize(*frame
.ack_frame
, packet_number_length
);
1792 case STOP_WAITING_FRAME
:
1793 return GetStopWaitingFrameSize(packet_number_length
);
1794 case MTU_DISCOVERY_FRAME
:
1795 // MTU discovery frames are serialized as ping frames.
1797 // Ping has no payload.
1798 return kQuicFrameTypeSize
;
1799 case RST_STREAM_FRAME
:
1800 if (quic_version_
<= QUIC_VERSION_24
) {
1801 return GetMinRstStreamFrameSize() +
1802 frame
.rst_stream_frame
->error_details
.size();
1804 return GetRstStreamFrameSize();
1805 case CONNECTION_CLOSE_FRAME
:
1806 return GetMinConnectionCloseFrameSize() +
1807 frame
.connection_close_frame
->error_details
.size();
1809 return GetMinGoAwayFrameSize() + frame
.goaway_frame
->reason_phrase
.size();
1810 case WINDOW_UPDATE_FRAME
:
1811 return GetWindowUpdateFrameSize();
1813 return GetBlockedFrameSize();
1817 case NUM_FRAME_TYPES
:
1822 // Not reachable, but some Chrome compilers can't figure that out. *sigh*
1827 bool QuicFramer::AppendTypeByte(const QuicFrame
& frame
,
1828 bool no_stream_frame_length
,
1829 QuicDataWriter
* writer
) {
1830 uint8 type_byte
= 0;
1831 switch (frame
.type
) {
1832 case STREAM_FRAME
: {
1833 if (frame
.stream_frame
== nullptr) {
1834 LOG(DFATAL
) << "Failed to append STREAM frame with no stream_frame.";
1837 type_byte
|= frame
.stream_frame
->fin
? kQuicStreamFinMask
: 0;
1840 type_byte
<<= kQuicStreamDataLengthShift
;
1841 type_byte
|= no_stream_frame_length
? 0: kQuicStreamDataLengthMask
;
1844 type_byte
<<= kQuicStreamOffsetShift
;
1845 const size_t offset_len
= GetStreamOffsetSize(frame
.stream_frame
->offset
);
1846 if (offset_len
> 0) {
1847 type_byte
|= offset_len
- 1;
1850 // stream id 2 bits.
1851 type_byte
<<= kQuicStreamIdShift
;
1852 type_byte
|= GetStreamIdSize(frame
.stream_frame
->stream_id
) - 1;
1853 type_byte
|= kQuicFrameTypeStreamMask
; // Set Stream Frame Type to 1.
1858 case MTU_DISCOVERY_FRAME
:
1859 type_byte
= static_cast<uint8
>(PING_FRAME
);
1862 type_byte
= static_cast<uint8
>(frame
.type
);
1866 return writer
->WriteUInt8(type_byte
);
1870 bool QuicFramer::AppendPacketSequenceNumber(
1871 QuicPacketNumberLength packet_number_length
,
1872 QuicPacketNumber packet_packet_number
,
1873 QuicDataWriter
* writer
) {
1874 // Ensure the entire packet number can be written.
1875 if (writer
->capacity() - writer
->length() <
1876 static_cast<size_t>(packet_number_length
)) {
1879 switch (packet_number_length
) {
1880 case PACKET_1BYTE_PACKET_NUMBER
:
1881 return writer
->WriteUInt8(packet_packet_number
&
1882 k1ByteSequenceNumberMask
);
1884 case PACKET_2BYTE_PACKET_NUMBER
:
1885 return writer
->WriteUInt16(packet_packet_number
&
1886 k2ByteSequenceNumberMask
);
1888 case PACKET_4BYTE_PACKET_NUMBER
:
1889 return writer
->WriteUInt32(packet_packet_number
&
1890 k4ByteSequenceNumberMask
);
1892 case PACKET_6BYTE_PACKET_NUMBER
:
1893 return writer
->WriteUInt48(packet_packet_number
&
1894 k6ByteSequenceNumberMask
);
1897 DCHECK(false) << "packet_number_length: " << packet_number_length
;
1902 bool QuicFramer::AppendStreamFrame(
1903 const QuicStreamFrame
& frame
,
1904 bool no_stream_frame_length
,
1905 QuicDataWriter
* writer
) {
1906 if (!writer
->WriteBytes(&frame
.stream_id
, GetStreamIdSize(frame
.stream_id
))) {
1907 LOG(DFATAL
) << "Writing stream id size failed.";
1910 if (!writer
->WriteBytes(&frame
.offset
, GetStreamOffsetSize(frame
.offset
))) {
1911 LOG(DFATAL
) << "Writing offset size failed.";
1914 if (!no_stream_frame_length
) {
1915 if ((frame
.data
.size() > numeric_limits
<uint16
>::max()) ||
1916 !writer
->WriteUInt16(static_cast<uint16
>(frame
.data
.size()))) {
1917 LOG(DFATAL
) << "Writing stream frame length failed";
1922 if (!writer
->WriteBytes(frame
.data
.data(), frame
.data
.size())) {
1923 LOG(DFATAL
) << "Writing frame data failed.";
1929 void QuicFramer::set_version(const QuicVersion version
) {
1930 DCHECK(IsSupportedVersion(version
)) << QuicVersionToString(version
);
1931 quic_version_
= version
;
1934 bool QuicFramer::AppendAckFrameAndTypeByte(
1935 const QuicPacketHeader
& header
,
1936 const QuicAckFrame
& frame
,
1937 QuicDataWriter
* writer
) {
1938 AckFrameInfo ack_info
= GetAckFrameInfo(frame
);
1939 QuicPacketNumber ack_largest_observed
= frame
.largest_observed
;
1940 QuicPacketNumberLength largest_observed_length
=
1941 GetMinSequenceNumberLength(ack_largest_observed
);
1942 QuicPacketNumberLength missing_packet_number_length
=
1943 GetMinSequenceNumberLength(ack_info
.max_delta
);
1944 // Determine whether we need to truncate ranges.
1945 size_t available_range_bytes
=
1946 writer
->capacity() - writer
->length() - kNumberOfRevivedPacketsSize
-
1947 kNumberOfNackRangesSize
- GetMinAckFrameSize(largest_observed_length
);
1948 size_t max_num_ranges
=
1949 available_range_bytes
/
1950 (missing_packet_number_length
+ PACKET_1BYTE_PACKET_NUMBER
);
1951 max_num_ranges
= min(kMaxNackRanges
, max_num_ranges
);
1952 bool truncated
= ack_info
.nack_ranges
.size() > max_num_ranges
;
1953 DVLOG_IF(1, truncated
) << "Truncating ack from "
1954 << ack_info
.nack_ranges
.size() << " ranges to "
1956 // Write out the type byte by setting the low order bits and doing shifts
1957 // to make room for the next bit flags to be set.
1958 // Whether there are any nacks.
1959 uint8 type_byte
= ack_info
.nack_ranges
.empty() ? 0 : kQuicHasNacksMask
;
1962 type_byte
<<= kQuicAckTruncatedShift
;
1963 type_byte
|= truncated
? kQuicAckTruncatedMask
: 0;
1965 // Largest observed packet number length.
1966 type_byte
<<= kQuicSequenceNumberLengthShift
;
1967 type_byte
|= GetSequenceNumberFlags(largest_observed_length
);
1969 // Missing packet number length.
1970 type_byte
<<= kQuicSequenceNumberLengthShift
;
1971 type_byte
|= GetSequenceNumberFlags(missing_packet_number_length
);
1973 type_byte
|= kQuicFrameTypeAckMask
;
1975 if (!writer
->WriteUInt8(type_byte
)) {
1979 QuicPacketEntropyHash ack_entropy_hash
= frame
.entropy_hash
;
1980 NackRangeMap::reverse_iterator ack_iter
= ack_info
.nack_ranges
.rbegin();
1982 // Skip the nack ranges which the truncated ack won't include and set
1983 // a correct largest observed for the truncated ack.
1984 for (size_t i
= 1; i
< (ack_info
.nack_ranges
.size() - max_num_ranges
);
1988 // If the last range is followed by acks, include them.
1989 // If the last range is followed by another range, specify the end of the
1990 // range as the largest_observed.
1991 ack_largest_observed
= ack_iter
->first
- 1;
1992 // Also update the entropy so it matches the largest observed.
1993 ack_entropy_hash
= entropy_calculator_
->EntropyHash(ack_largest_observed
);
1997 if (!writer
->WriteUInt8(ack_entropy_hash
)) {
2001 if (!AppendPacketSequenceNumber(largest_observed_length
,
2002 ack_largest_observed
, writer
)) {
2006 uint64 delta_time_largest_observed_us
= kUFloat16MaxValue
;
2007 if (!frame
.delta_time_largest_observed
.IsInfinite()) {
2008 DCHECK_LE(0u, frame
.delta_time_largest_observed
.ToMicroseconds());
2009 delta_time_largest_observed_us
=
2010 frame
.delta_time_largest_observed
.ToMicroseconds();
2013 if (!writer
->WriteUFloat16(delta_time_largest_observed_us
)) {
2017 // Timestamp goes at the end of the required fields.
2019 if (!AppendTimestampToAckFrame(frame
, writer
)) {
2024 if (ack_info
.nack_ranges
.empty()) {
2028 const uint8 num_missing_ranges
=
2029 static_cast<uint8
>(min(ack_info
.nack_ranges
.size(), max_num_ranges
));
2030 if (!writer
->WriteBytes(&num_missing_ranges
, 1)) {
2034 int num_ranges_written
= 0;
2035 QuicPacketNumber last_sequence_written
= ack_largest_observed
;
2036 for (; ack_iter
!= ack_info
.nack_ranges
.rend(); ++ack_iter
) {
2037 // Calculate the delta to the last number in the range.
2038 QuicPacketNumber missing_delta
=
2039 last_sequence_written
- (ack_iter
->first
+ ack_iter
->second
);
2040 if (!AppendPacketSequenceNumber(missing_packet_number_length
, missing_delta
,
2044 if (!AppendPacketSequenceNumber(PACKET_1BYTE_PACKET_NUMBER
,
2045 ack_iter
->second
, writer
)) {
2048 // Subtract 1 so a missing_delta of 0 means an adjacent range.
2049 last_sequence_written
= ack_iter
->first
- 1;
2050 ++num_ranges_written
;
2052 DCHECK_EQ(num_missing_ranges
, num_ranges_written
);
2054 // Append revived packets.
2055 // If not all the revived packets fit, only mention the ones that do.
2056 uint8 num_revived_packets
=
2057 static_cast<uint8
>(min(frame
.revived_packets
.size(), kMaxRevivedPackets
));
2058 num_revived_packets
= static_cast<uint8
>(min(
2059 static_cast<size_t>(num_revived_packets
),
2060 (writer
->capacity() - writer
->length()) / largest_observed_length
));
2061 if (!writer
->WriteBytes(&num_revived_packets
, 1)) {
2065 PacketNumberSet::const_iterator iter
= frame
.revived_packets
.begin();
2066 for (int i
= 0; i
< num_revived_packets
; ++i
, ++iter
) {
2067 LOG_IF(DFATAL
, !frame
.missing_packets
.Contains(*iter
));
2068 if (!AppendPacketSequenceNumber(largest_observed_length
,
2077 bool QuicFramer::AppendTimestampToAckFrame(const QuicAckFrame
& frame
,
2078 QuicDataWriter
* writer
) {
2079 DCHECK_GE(numeric_limits
<uint8
>::max(), frame
.received_packet_times
.size());
2080 // num_received_packets is only 1 byte.
2081 if (frame
.received_packet_times
.size() > numeric_limits
<uint8
>::max()) {
2085 uint8 num_received_packets
= frame
.received_packet_times
.size();
2087 if (!writer
->WriteBytes(&num_received_packets
, 1)) {
2090 if (num_received_packets
== 0) {
2094 PacketTimeList::const_iterator it
= frame
.received_packet_times
.begin();
2095 QuicPacketNumber packet_number
= it
->first
;
2096 QuicPacketNumber delta_from_largest_observed
=
2097 frame
.largest_observed
- packet_number
;
2099 DCHECK_GE(numeric_limits
<uint8
>::max(), delta_from_largest_observed
);
2100 if (delta_from_largest_observed
> numeric_limits
<uint8
>::max()) {
2104 if (!writer
->WriteUInt8(
2105 delta_from_largest_observed
& k1ByteSequenceNumberMask
)) {
2109 // Use the lowest 4 bytes of the time delta from the creation_time_.
2110 const uint64 time_epoch_delta_us
= UINT64_C(1) << 32;
2111 uint32 time_delta_us
=
2112 static_cast<uint32
>(it
->second
.Subtract(creation_time_
).ToMicroseconds()
2113 & (time_epoch_delta_us
- 1));
2114 if (!writer
->WriteBytes(&time_delta_us
, sizeof(time_delta_us
))) {
2118 QuicTime prev_time
= it
->second
;
2120 for (++it
; it
!= frame
.received_packet_times
.end(); ++it
) {
2121 packet_number
= it
->first
;
2122 delta_from_largest_observed
= frame
.largest_observed
- packet_number
;
2124 if (delta_from_largest_observed
> numeric_limits
<uint8
>::max()) {
2128 if (!writer
->WriteUInt8(
2129 delta_from_largest_observed
& k1ByteSequenceNumberMask
)) {
2133 uint64 frame_time_delta_us
=
2134 it
->second
.Subtract(prev_time
).ToMicroseconds();
2135 prev_time
= it
->second
;
2136 if (!writer
->WriteUFloat16(frame_time_delta_us
)) {
2143 bool QuicFramer::AppendStopWaitingFrame(
2144 const QuicPacketHeader
& header
,
2145 const QuicStopWaitingFrame
& frame
,
2146 QuicDataWriter
* writer
) {
2147 DCHECK_GE(header
.packet_packet_number
, frame
.least_unacked
);
2148 const QuicPacketNumber least_unacked_delta
=
2149 header
.packet_packet_number
- frame
.least_unacked
;
2150 const QuicPacketNumber length_shift
=
2151 header
.public_header
.packet_number_length
* 8;
2152 if (!writer
->WriteUInt8(frame
.entropy_hash
)) {
2153 LOG(DFATAL
) << " hash failed";
2157 if (least_unacked_delta
>> length_shift
> 0) {
2158 LOG(DFATAL
) << "packet_number_length "
2159 << header
.public_header
.packet_number_length
2160 << " is too small for least_unacked_delta: "
2161 << least_unacked_delta
;
2164 if (!AppendPacketSequenceNumber(header
.public_header
.packet_number_length
,
2165 least_unacked_delta
, writer
)) {
2166 LOG(DFATAL
) << " seq failed: " << header
.public_header
.packet_number_length
;
2173 bool QuicFramer::AppendRstStreamFrame(const QuicRstStreamFrame
& frame
,
2174 QuicDataWriter
* writer
) {
2175 if (!writer
->WriteUInt32(frame
.stream_id
)) {
2179 if (!writer
->WriteUInt64(frame
.byte_offset
)) {
2183 uint32 error_code
= static_cast<uint32
>(frame
.error_code
);
2184 if (!writer
->WriteUInt32(error_code
)) {
2188 if (quic_version_
<= QUIC_VERSION_24
) {
2189 if (!writer
->WriteStringPiece16(frame
.error_details
)) {
2196 bool QuicFramer::AppendConnectionCloseFrame(
2197 const QuicConnectionCloseFrame
& frame
,
2198 QuicDataWriter
* writer
) {
2199 uint32 error_code
= static_cast<uint32
>(frame
.error_code
);
2200 if (!writer
->WriteUInt32(error_code
)) {
2203 if (!writer
->WriteStringPiece16(frame
.error_details
)) {
2209 bool QuicFramer::AppendGoAwayFrame(const QuicGoAwayFrame
& frame
,
2210 QuicDataWriter
* writer
) {
2211 uint32 error_code
= static_cast<uint32
>(frame
.error_code
);
2212 if (!writer
->WriteUInt32(error_code
)) {
2215 uint32 stream_id
= static_cast<uint32
>(frame
.last_good_stream_id
);
2216 if (!writer
->WriteUInt32(stream_id
)) {
2219 if (!writer
->WriteStringPiece16(frame
.reason_phrase
)) {
2225 bool QuicFramer::AppendWindowUpdateFrame(const QuicWindowUpdateFrame
& frame
,
2226 QuicDataWriter
* writer
) {
2227 uint32 stream_id
= static_cast<uint32
>(frame
.stream_id
);
2228 if (!writer
->WriteUInt32(stream_id
)) {
2231 if (!writer
->WriteUInt64(frame
.byte_offset
)) {
2237 bool QuicFramer::AppendBlockedFrame(const QuicBlockedFrame
& frame
,
2238 QuicDataWriter
* writer
) {
2239 uint32 stream_id
= static_cast<uint32
>(frame
.stream_id
);
2240 if (!writer
->WriteUInt32(stream_id
)) {
2246 bool QuicFramer::RaiseError(QuicErrorCode error
) {
2247 DVLOG(1) << "Error: " << QuicUtils::ErrorToString(error
)
2248 << " detail: " << detailed_error_
;
2250 visitor_
->OnError(this);