1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "net/quic/quic_framer.h"
7 #include "base/containers/hash_tables.h"
8 #include "base/stl_util.h"
9 #include "net/quic/crypto/crypto_framer.h"
10 #include "net/quic/crypto/crypto_handshake_message.h"
11 #include "net/quic/crypto/crypto_protocol.h"
12 #include "net/quic/crypto/quic_decrypter.h"
13 #include "net/quic/crypto/quic_encrypter.h"
14 #include "net/quic/quic_data_reader.h"
15 #include "net/quic/quic_data_writer.h"
16 #include "net/quic/quic_flags.h"
17 #include "net/quic/quic_socket_address_coder.h"
19 using base::StringPiece
;
24 using std::numeric_limits
;
31 // Mask to select the lowest 48 bits of a sequence number.
32 const QuicPacketSequenceNumber k6ByteSequenceNumberMask
=
33 GG_UINT64_C(0x0000FFFFFFFFFFFF);
34 const QuicPacketSequenceNumber k4ByteSequenceNumberMask
=
35 GG_UINT64_C(0x00000000FFFFFFFF);
36 const QuicPacketSequenceNumber k2ByteSequenceNumberMask
=
37 GG_UINT64_C(0x000000000000FFFF);
38 const QuicPacketSequenceNumber k1ByteSequenceNumberMask
=
39 GG_UINT64_C(0x00000000000000FF);
41 const QuicConnectionId k1ByteConnectionIdMask
= GG_UINT64_C(0x00000000000000FF);
42 const QuicConnectionId k4ByteConnectionIdMask
= GG_UINT64_C(0x00000000FFFFFFFF);
44 // Number of bits the sequence 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
65 // CongestionFeedback : 0b 001xxxxx
67 // Semantics of the flag bits above (the x bits) depends on the frame type.
69 // Masks to determine if the frame type is a special use
70 // and for specific special frame types.
71 const uint8 kQuicFrameTypeSpecialMask
= 0xE0; // 0b 11100000
72 const uint8 kQuicFrameTypeStreamMask
= 0x80;
73 const uint8 kQuicFrameTypeAckMask
= 0x40;
74 const uint8 kQuicFrameTypeCongestionFeedbackMask
= 0x20;
76 // Stream frame relative shifts and masks for interpreting the stream flags.
77 // StreamID may be 1, 2, 3, or 4 bytes.
78 const uint8 kQuicStreamIdShift
= 2;
79 const uint8 kQuicStreamIDLengthMask
= 0x03;
81 // Offset may be 0, 2, 3, 4, 5, 6, 7, 8 bytes.
82 const uint8 kQuicStreamOffsetShift
= 3;
83 const uint8 kQuicStreamOffsetMask
= 0x07;
85 // Data length may be 0 or 2 bytes.
86 const uint8 kQuicStreamDataLengthShift
= 1;
87 const uint8 kQuicStreamDataLengthMask
= 0x01;
89 // Fin bit may be set or not.
90 const uint8 kQuicStreamFinShift
= 1;
91 const uint8 kQuicStreamFinMask
= 0x01;
93 // Sequence number size shift used in AckFrames.
94 const uint8 kQuicSequenceNumberLengthShift
= 2;
96 // Acks may be truncated.
97 const uint8 kQuicAckTruncatedShift
= 1;
98 const uint8 kQuicAckTruncatedMask
= 0x01;
100 // Acks may not have any nacks.
101 const uint8 kQuicHasNacksMask
= 0x01;
103 // Returns the absolute value of the difference between |a| and |b|.
104 QuicPacketSequenceNumber
Delta(QuicPacketSequenceNumber a
,
105 QuicPacketSequenceNumber b
) {
106 // Since these are unsigned numbers, we can't just return abs(a - b)
113 QuicPacketSequenceNumber
ClosestTo(QuicPacketSequenceNumber target
,
114 QuicPacketSequenceNumber a
,
115 QuicPacketSequenceNumber b
) {
116 return (Delta(target
, a
) < Delta(target
, b
)) ? a
: b
;
119 QuicSequenceNumberLength
ReadSequenceNumberLength(uint8 flags
) {
120 switch (flags
& PACKET_FLAGS_6BYTE_SEQUENCE
) {
121 case PACKET_FLAGS_6BYTE_SEQUENCE
:
122 return PACKET_6BYTE_SEQUENCE_NUMBER
;
123 case PACKET_FLAGS_4BYTE_SEQUENCE
:
124 return PACKET_4BYTE_SEQUENCE_NUMBER
;
125 case PACKET_FLAGS_2BYTE_SEQUENCE
:
126 return PACKET_2BYTE_SEQUENCE_NUMBER
;
127 case PACKET_FLAGS_1BYTE_SEQUENCE
:
128 return PACKET_1BYTE_SEQUENCE_NUMBER
;
130 LOG(DFATAL
) << "Unreachable case statement.";
131 return PACKET_6BYTE_SEQUENCE_NUMBER
;
137 bool QuicFramerVisitorInterface::OnWindowUpdateFrame(
138 const QuicWindowUpdateFrame
& frame
) {
142 bool QuicFramerVisitorInterface::OnBlockedFrame(const QuicBlockedFrame
& frame
) {
146 QuicFramer::QuicFramer(const QuicVersionVector
& supported_versions
,
147 QuicTime creation_time
,
151 entropy_calculator_(NULL
),
152 error_(QUIC_NO_ERROR
),
153 last_sequence_number_(0),
154 last_serialized_connection_id_(0),
155 supported_versions_(supported_versions
),
156 decrypter_level_(ENCRYPTION_NONE
),
157 alternative_decrypter_level_(ENCRYPTION_NONE
),
158 alternative_decrypter_latch_(false),
159 is_server_(is_server
),
160 validate_flags_(true),
161 creation_time_(creation_time
),
162 last_timestamp_(QuicTime::Delta::Zero()) {
163 DCHECK(!supported_versions
.empty());
164 quic_version_
= supported_versions_
[0];
165 decrypter_
.reset(QuicDecrypter::Create(kNULL
));
166 encrypter_
[ENCRYPTION_NONE
].reset(
167 QuicEncrypter::Create(kNULL
));
170 QuicFramer::~QuicFramer() {}
173 size_t QuicFramer::GetMinStreamFrameSize(QuicStreamId stream_id
,
174 QuicStreamOffset offset
,
175 bool last_frame_in_packet
,
176 InFecGroup is_in_fec_group
) {
177 bool no_stream_frame_length
= last_frame_in_packet
&&
178 is_in_fec_group
== NOT_IN_FEC_GROUP
;
179 return kQuicFrameTypeSize
+ GetStreamIdSize(stream_id
) +
180 GetStreamOffsetSize(offset
) +
181 (no_stream_frame_length
? 0 : kQuicStreamPayloadLengthSize
);
185 size_t QuicFramer::GetMinAckFrameSize(
186 QuicSequenceNumberLength sequence_number_length
,
187 QuicSequenceNumberLength largest_observed_length
) {
188 return kQuicFrameTypeSize
+ kQuicEntropyHashSize
+
189 largest_observed_length
+ kQuicDeltaTimeLargestObservedSize
;
193 size_t QuicFramer::GetStopWaitingFrameSize(
194 QuicSequenceNumberLength sequence_number_length
) {
195 return kQuicFrameTypeSize
+ kQuicEntropyHashSize
+
196 sequence_number_length
;
200 size_t QuicFramer::GetMinRstStreamFrameSize() {
201 return kQuicFrameTypeSize
+ kQuicMaxStreamIdSize
+
202 kQuicMaxStreamOffsetSize
+ kQuicErrorCodeSize
+
203 kQuicErrorDetailsLengthSize
;
207 size_t QuicFramer::GetMinConnectionCloseFrameSize() {
208 return kQuicFrameTypeSize
+ kQuicErrorCodeSize
+ kQuicErrorDetailsLengthSize
;
212 size_t QuicFramer::GetMinGoAwayFrameSize() {
213 return kQuicFrameTypeSize
+ kQuicErrorCodeSize
+ kQuicErrorDetailsLengthSize
+
214 kQuicMaxStreamIdSize
;
218 size_t QuicFramer::GetWindowUpdateFrameSize() {
219 return kQuicFrameTypeSize
+ kQuicMaxStreamIdSize
+ kQuicMaxStreamOffsetSize
;
223 size_t QuicFramer::GetBlockedFrameSize() {
224 return kQuicFrameTypeSize
+ kQuicMaxStreamIdSize
;
228 size_t QuicFramer::GetStreamIdSize(QuicStreamId stream_id
) {
229 // Sizes are 1 through 4 bytes.
230 for (int i
= 1; i
<= 4; ++i
) {
232 if (stream_id
== 0) {
236 LOG(DFATAL
) << "Failed to determine StreamIDSize.";
241 size_t QuicFramer::GetStreamOffsetSize(QuicStreamOffset offset
) {
242 // 0 is a special case.
246 // 2 through 8 are the remaining sizes.
248 for (int i
= 2; i
<= 8; ++i
) {
254 LOG(DFATAL
) << "Failed to determine StreamOffsetSize.";
259 size_t QuicFramer::GetVersionNegotiationPacketSize(size_t number_versions
) {
260 return kPublicFlagsSize
+ PACKET_8BYTE_CONNECTION_ID
+
261 number_versions
* kQuicVersionSize
;
264 bool QuicFramer::IsSupportedVersion(const QuicVersion version
) const {
265 for (size_t i
= 0; i
< supported_versions_
.size(); ++i
) {
266 if (version
== supported_versions_
[i
]) {
273 size_t QuicFramer::GetSerializedFrameLength(
274 const QuicFrame
& frame
,
278 InFecGroup is_in_fec_group
,
279 QuicSequenceNumberLength sequence_number_length
) {
280 if (frame
.type
== PADDING_FRAME
) {
281 // PADDING implies end of packet.
285 ComputeFrameLength(frame
, last_frame
, is_in_fec_group
,
286 sequence_number_length
);
287 if (frame_len
<= free_bytes
) {
288 // Frame fits within packet. Note that acks may be truncated.
291 // Only truncate the first frame in a packet, so if subsequent ones go
292 // over, stop including more frames.
296 bool can_truncate
= frame
.type
== ACK_FRAME
&&
297 free_bytes
>= GetMinAckFrameSize(PACKET_6BYTE_SEQUENCE_NUMBER
,
298 PACKET_6BYTE_SEQUENCE_NUMBER
);
300 // Truncate the frame so the packet will not exceed kMaxPacketSize.
301 // Note that we may not use every byte of the writer in this case.
302 DVLOG(1) << "Truncating large frame, free bytes: " << free_bytes
;
305 if (!FLAGS_quic_allow_oversized_packets_for_test
) {
308 LOG(DFATAL
) << "Packet size too small to fit frame.";
312 QuicFramer::AckFrameInfo::AckFrameInfo() : max_delta(0) {}
314 QuicFramer::AckFrameInfo::~AckFrameInfo() {}
316 QuicPacketEntropyHash
QuicFramer::GetPacketEntropyHash(
317 const QuicPacketHeader
& header
) const {
318 return header
.entropy_flag
<< (header
.packet_sequence_number
% 8);
321 SerializedPacket
QuicFramer::BuildDataPacket(
322 const QuicPacketHeader
& header
,
323 const QuicFrames
& frames
,
324 size_t packet_size
) {
325 QuicDataWriter
writer(packet_size
);
326 const SerializedPacket
kNoPacket(
327 0, PACKET_1BYTE_SEQUENCE_NUMBER
, NULL
, 0, NULL
);
328 if (!AppendPacketHeader(header
, &writer
)) {
329 LOG(DFATAL
) << "AppendPacketHeader failed";
333 for (size_t i
= 0; i
< frames
.size(); ++i
) {
334 const QuicFrame
& frame
= frames
[i
];
336 // Determine if we should write stream frame length in header.
337 const bool no_stream_frame_length
=
338 (header
.is_in_fec_group
== NOT_IN_FEC_GROUP
) &&
339 (i
== frames
.size() - 1);
340 if (!AppendTypeByte(frame
, no_stream_frame_length
, &writer
)) {
341 LOG(DFATAL
) << "AppendTypeByte failed";
345 switch (frame
.type
) {
347 writer
.WritePadding();
350 if (!AppendStreamFrame(
351 *frame
.stream_frame
, no_stream_frame_length
, &writer
)) {
352 LOG(DFATAL
) << "AppendStreamFrame failed";
357 if (!AppendAckFrameAndTypeByte(
358 header
, *frame
.ack_frame
, &writer
)) {
359 LOG(DFATAL
) << "AppendAckFrameAndTypeByte failed";
363 case CONGESTION_FEEDBACK_FRAME
:
364 if (!AppendCongestionFeedbackFrame(
365 *frame
.congestion_feedback_frame
, &writer
)) {
366 LOG(DFATAL
) << "AppendCongestionFeedbackFrame failed";
370 case STOP_WAITING_FRAME
:
371 if (!AppendStopWaitingFrame(
372 header
, *frame
.stop_waiting_frame
, &writer
)) {
373 LOG(DFATAL
) << "AppendStopWaitingFrame failed";
378 if (quic_version_
== QUIC_VERSION_16
) {
379 LOG(DFATAL
) << "Attempt to add a PingFrame in "
380 << QuicVersionToString(quic_version_
);
383 // Ping has no payload.
385 case RST_STREAM_FRAME
:
386 if (!AppendRstStreamFrame(*frame
.rst_stream_frame
, &writer
)) {
387 LOG(DFATAL
) << "AppendRstStreamFrame failed";
391 case CONNECTION_CLOSE_FRAME
:
392 if (!AppendConnectionCloseFrame(
393 *frame
.connection_close_frame
, &writer
)) {
394 LOG(DFATAL
) << "AppendConnectionCloseFrame failed";
399 if (!AppendGoAwayFrame(*frame
.goaway_frame
, &writer
)) {
400 LOG(DFATAL
) << "AppendGoAwayFrame failed";
404 case WINDOW_UPDATE_FRAME
:
405 if (!AppendWindowUpdateFrame(*frame
.window_update_frame
, &writer
)) {
406 LOG(DFATAL
) << "AppendWindowUpdateFrame failed";
411 if (!AppendBlockedFrame(*frame
.blocked_frame
, &writer
)) {
412 LOG(DFATAL
) << "AppendBlockedFrame failed";
417 RaiseError(QUIC_INVALID_FRAME_DATA
);
418 LOG(DFATAL
) << "QUIC_INVALID_FRAME_DATA";
423 // Save the length before writing, because take clears it.
424 const size_t len
= writer
.length();
425 // Less than or equal because truncated acks end up with max_plaintex_size
426 // length, even though they're typically slightly shorter.
427 DCHECK_LE(len
, packet_size
);
428 QuicPacket
* packet
= QuicPacket::NewDataPacket(
429 writer
.take(), len
, true, header
.public_header
.connection_id_length
,
430 header
.public_header
.version_flag
,
431 header
.public_header
.sequence_number_length
);
434 fec_builder_
->OnBuiltFecProtectedPayload(header
,
435 packet
->FecProtectedData());
438 return SerializedPacket(header
.packet_sequence_number
,
439 header
.public_header
.sequence_number_length
, packet
,
440 GetPacketEntropyHash(header
), NULL
);
443 SerializedPacket
QuicFramer::BuildFecPacket(const QuicPacketHeader
& header
,
444 const QuicFecData
& fec
) {
445 DCHECK_EQ(IN_FEC_GROUP
, header
.is_in_fec_group
);
446 DCHECK_NE(0u, header
.fec_group
);
447 size_t len
= GetPacketHeaderSize(header
);
448 len
+= fec
.redundancy
.length();
450 QuicDataWriter
writer(len
);
451 const SerializedPacket
kNoPacket(
452 0, PACKET_1BYTE_SEQUENCE_NUMBER
, NULL
, 0, NULL
);
453 if (!AppendPacketHeader(header
, &writer
)) {
454 LOG(DFATAL
) << "AppendPacketHeader failed";
458 if (!writer
.WriteBytes(fec
.redundancy
.data(), fec
.redundancy
.length())) {
459 LOG(DFATAL
) << "Failed to add FEC";
463 return SerializedPacket(
464 header
.packet_sequence_number
,
465 header
.public_header
.sequence_number_length
,
466 QuicPacket::NewFecPacket(writer
.take(), len
, true,
467 header
.public_header
.connection_id_length
,
468 header
.public_header
.version_flag
,
469 header
.public_header
.sequence_number_length
),
470 GetPacketEntropyHash(header
), NULL
);
474 QuicEncryptedPacket
* QuicFramer::BuildPublicResetPacket(
475 const QuicPublicResetPacket
& packet
) {
476 DCHECK(packet
.public_header
.reset_flag
);
478 CryptoHandshakeMessage reset
;
479 reset
.set_tag(kPRST
);
480 reset
.SetValue(kRNON
, packet
.nonce_proof
);
481 reset
.SetValue(kRSEQ
, packet
.rejected_sequence_number
);
482 if (!packet
.client_address
.address().empty()) {
483 // packet.client_address is non-empty.
484 QuicSocketAddressCoder
address_coder(packet
.client_address
);
485 string serialized_address
= address_coder
.Encode();
486 if (serialized_address
.empty()) {
489 reset
.SetStringPiece(kCADR
, serialized_address
);
491 const QuicData
& reset_serialized
= reset
.GetSerialized();
494 kPublicFlagsSize
+ PACKET_8BYTE_CONNECTION_ID
+ reset_serialized
.length();
495 QuicDataWriter
writer(len
);
497 uint8 flags
= static_cast<uint8
>(PACKET_PUBLIC_FLAGS_RST
|
498 PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID
);
499 if (!writer
.WriteUInt8(flags
)) {
503 if (!writer
.WriteUInt64(packet
.public_header
.connection_id
)) {
507 if (!writer
.WriteBytes(reset_serialized
.data(), reset_serialized
.length())) {
511 return new QuicEncryptedPacket(writer
.take(), len
, true);
514 QuicEncryptedPacket
* QuicFramer::BuildVersionNegotiationPacket(
515 const QuicPacketPublicHeader
& header
,
516 const QuicVersionVector
& supported_versions
) {
517 DCHECK(header
.version_flag
);
518 size_t len
= GetVersionNegotiationPacketSize(supported_versions
.size());
519 QuicDataWriter
writer(len
);
521 uint8 flags
= static_cast<uint8
>(PACKET_PUBLIC_FLAGS_VERSION
|
522 PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID
);
523 if (!writer
.WriteUInt8(flags
)) {
527 if (!writer
.WriteUInt64(header
.connection_id
)) {
531 for (size_t i
= 0; i
< supported_versions
.size(); ++i
) {
532 if (!writer
.WriteUInt32(QuicVersionToQuicTag(supported_versions
[i
]))) {
537 return new QuicEncryptedPacket(writer
.take(), len
, true);
540 bool QuicFramer::ProcessPacket(const QuicEncryptedPacket
& packet
) {
541 DCHECK(!reader_
.get());
542 reader_
.reset(new QuicDataReader(packet
.data(), packet
.length()));
544 visitor_
->OnPacket();
546 // First parse the public header.
547 QuicPacketPublicHeader public_header
;
548 if (!ProcessPublicHeader(&public_header
)) {
549 DLOG(WARNING
) << "Unable to process public header.";
550 DCHECK_NE("", detailed_error_
);
551 return RaiseError(QUIC_INVALID_PACKET_HEADER
);
554 if (!visitor_
->OnUnauthenticatedPublicHeader(public_header
)) {
555 // The visitor suppresses further processing of the packet.
560 if (is_server_
&& public_header
.version_flag
&&
561 public_header
.versions
[0] != quic_version_
) {
562 if (!visitor_
->OnProtocolVersionMismatch(public_header
.versions
[0])) {
569 if (!is_server_
&& public_header
.version_flag
) {
570 rv
= ProcessVersionNegotiationPacket(&public_header
);
571 } else if (public_header
.reset_flag
) {
572 rv
= ProcessPublicResetPacket(public_header
);
574 rv
= ProcessDataPacket(public_header
, packet
);
581 bool QuicFramer::ProcessVersionNegotiationPacket(
582 QuicPacketPublicHeader
* public_header
) {
584 // Try reading at least once to raise error if the packet is invalid.
587 if (!reader_
->ReadBytes(&version
, kQuicVersionSize
)) {
588 set_detailed_error("Unable to read supported version in negotiation.");
589 return RaiseError(QUIC_INVALID_VERSION_NEGOTIATION_PACKET
);
591 public_header
->versions
.push_back(QuicTagToQuicVersion(version
));
592 } while (!reader_
->IsDoneReading());
594 visitor_
->OnVersionNegotiationPacket(*public_header
);
598 bool QuicFramer::ProcessDataPacket(
599 const QuicPacketPublicHeader
& public_header
,
600 const QuicEncryptedPacket
& packet
) {
601 QuicPacketHeader
header(public_header
);
602 if (!ProcessPacketHeader(&header
, packet
)) {
603 DLOG(WARNING
) << "Unable to process data packet header.";
607 if (!visitor_
->OnPacketHeader(header
)) {
608 // The visitor suppresses further processing of the packet.
612 if (packet
.length() > kMaxPacketSize
) {
613 DLOG(WARNING
) << "Packet too large: " << packet
.length();
614 return RaiseError(QUIC_PACKET_TOO_LARGE
);
617 // Handle the payload.
618 if (!header
.fec_flag
) {
619 if (header
.is_in_fec_group
== IN_FEC_GROUP
) {
620 StringPiece payload
= reader_
->PeekRemainingPayload();
621 visitor_
->OnFecProtectedPayload(payload
);
623 if (!ProcessFrameData(header
)) {
624 DCHECK_NE(QUIC_NO_ERROR
, error_
); // ProcessFrameData sets the error.
625 DLOG(WARNING
) << "Unable to process frame data.";
629 QuicFecData fec_data
;
630 fec_data
.fec_group
= header
.fec_group
;
631 fec_data
.redundancy
= reader_
->ReadRemainingPayload();
632 visitor_
->OnFecData(fec_data
);
635 visitor_
->OnPacketComplete();
639 bool QuicFramer::ProcessPublicResetPacket(
640 const QuicPacketPublicHeader
& public_header
) {
641 QuicPublicResetPacket
packet(public_header
);
643 scoped_ptr
<CryptoHandshakeMessage
> reset(
644 CryptoFramer::ParseMessage(reader_
->ReadRemainingPayload()));
646 set_detailed_error("Unable to read reset message.");
647 return RaiseError(QUIC_INVALID_PUBLIC_RST_PACKET
);
649 if (reset
->tag() != kPRST
) {
650 set_detailed_error("Incorrect message tag.");
651 return RaiseError(QUIC_INVALID_PUBLIC_RST_PACKET
);
654 if (reset
->GetUint64(kRNON
, &packet
.nonce_proof
) != QUIC_NO_ERROR
) {
655 set_detailed_error("Unable to read nonce proof.");
656 return RaiseError(QUIC_INVALID_PUBLIC_RST_PACKET
);
658 // TODO(satyamshekhar): validate nonce to protect against DoS.
660 if (reset
->GetUint64(kRSEQ
, &packet
.rejected_sequence_number
) !=
662 set_detailed_error("Unable to read rejected sequence number.");
663 return RaiseError(QUIC_INVALID_PUBLIC_RST_PACKET
);
667 if (reset
->GetStringPiece(kCADR
, &address
)) {
668 QuicSocketAddressCoder address_coder
;
669 if (address_coder
.Decode(address
.data(), address
.length())) {
670 packet
.client_address
= IPEndPoint(address_coder
.ip(),
671 address_coder
.port());
675 visitor_
->OnPublicResetPacket(packet
);
679 bool QuicFramer::ProcessRevivedPacket(QuicPacketHeader
* header
,
680 StringPiece payload
) {
681 DCHECK(!reader_
.get());
683 visitor_
->OnRevivedPacket();
685 header
->entropy_hash
= GetPacketEntropyHash(*header
);
687 if (!visitor_
->OnPacketHeader(*header
)) {
691 if (payload
.length() > kMaxPacketSize
) {
692 set_detailed_error("Revived packet too large.");
693 return RaiseError(QUIC_PACKET_TOO_LARGE
);
696 reader_
.reset(new QuicDataReader(payload
.data(), payload
.length()));
697 if (!ProcessFrameData(*header
)) {
698 DCHECK_NE(QUIC_NO_ERROR
, error_
); // ProcessFrameData sets the error.
699 DLOG(WARNING
) << "Unable to process frame data.";
703 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
.sequence_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
) {
765 writer
->WriteUInt32(QuicVersionToQuicTag(quic_version_
));
768 if (!AppendPacketSequenceNumber(header
.public_header
.sequence_number_length
,
769 header
.packet_sequence_number
, writer
)) {
773 uint8 private_flags
= 0;
774 if (header
.entropy_flag
) {
775 private_flags
|= PACKET_PRIVATE_FLAGS_ENTROPY
;
777 if (header
.is_in_fec_group
== IN_FEC_GROUP
) {
778 private_flags
|= PACKET_PRIVATE_FLAGS_FEC_GROUP
;
780 if (header
.fec_flag
) {
781 private_flags
|= PACKET_PRIVATE_FLAGS_FEC
;
783 if (!writer
->WriteUInt8(private_flags
)) {
787 // The FEC group number is the sequence number of the first fec
788 // protected packet, or 0 if this packet is not protected.
789 if (header
.is_in_fec_group
== IN_FEC_GROUP
) {
790 DCHECK_GE(header
.packet_sequence_number
, header
.fec_group
);
791 DCHECK_GT(255u, header
.packet_sequence_number
- header
.fec_group
);
792 // Offset from the current packet sequence number to the first fec
794 uint8 first_fec_protected_packet_offset
=
795 header
.packet_sequence_number
- header
.fec_group
;
796 if (!writer
->WriteBytes(&first_fec_protected_packet_offset
, 1)) {
804 const QuicTime::Delta
QuicFramer::CalculateTimestampFromWire(
805 uint32 time_delta_us
) {
806 // The new time_delta might have wrapped to the next epoch, or it
807 // might have reverse wrapped to the previous epoch, or it might
808 // remain in the same epoch. Select the time closest to the previous
811 // epoch_delta is the delta between epochs. A delta is 4 bytes of
813 const uint64 epoch_delta
= GG_UINT64_C(1) << 32;
814 uint64 epoch
= last_timestamp_
.ToMicroseconds() & ~(epoch_delta
- 1);
815 // Wrapping is safe here because a wrapped value will not be ClosestTo below.
816 uint64 prev_epoch
= epoch
- epoch_delta
;
817 uint64 next_epoch
= epoch
+ epoch_delta
;
819 uint64 time
= ClosestTo(last_timestamp_
.ToMicroseconds(),
820 epoch
+ time_delta_us
,
821 ClosestTo(last_timestamp_
.ToMicroseconds(),
822 prev_epoch
+ time_delta_us
,
823 next_epoch
+ time_delta_us
));
825 return QuicTime::Delta::FromMicroseconds(time
);
828 QuicPacketSequenceNumber
QuicFramer::CalculatePacketSequenceNumberFromWire(
829 QuicSequenceNumberLength sequence_number_length
,
830 QuicPacketSequenceNumber packet_sequence_number
) const {
831 // The new sequence number might have wrapped to the next epoch, or
832 // it might have reverse wrapped to the previous epoch, or it might
833 // remain in the same epoch. Select the sequence number closest to the
834 // next expected sequence number, the previous sequence number plus 1.
836 // epoch_delta is the delta between epochs the sequence number was serialized
837 // with, so the correct value is likely the same epoch as the last sequence
838 // number or an adjacent epoch.
839 const QuicPacketSequenceNumber epoch_delta
=
840 GG_UINT64_C(1) << (8 * sequence_number_length
);
841 QuicPacketSequenceNumber next_sequence_number
= last_sequence_number_
+ 1;
842 QuicPacketSequenceNumber epoch
= last_sequence_number_
& ~(epoch_delta
- 1);
843 QuicPacketSequenceNumber prev_epoch
= epoch
- epoch_delta
;
844 QuicPacketSequenceNumber next_epoch
= epoch
+ epoch_delta
;
846 return ClosestTo(next_sequence_number
,
847 epoch
+ packet_sequence_number
,
848 ClosestTo(next_sequence_number
,
849 prev_epoch
+ packet_sequence_number
,
850 next_epoch
+ packet_sequence_number
));
853 bool QuicFramer::ProcessPublicHeader(
854 QuicPacketPublicHeader
* public_header
) {
856 if (!reader_
->ReadBytes(&public_flags
, 1)) {
857 set_detailed_error("Unable to read public flags.");
861 public_header
->reset_flag
= (public_flags
& PACKET_PUBLIC_FLAGS_RST
) != 0;
862 public_header
->version_flag
=
863 (public_flags
& PACKET_PUBLIC_FLAGS_VERSION
) != 0;
865 if (validate_flags_
&&
866 !public_header
->version_flag
&& public_flags
> PACKET_PUBLIC_FLAGS_MAX
) {
867 set_detailed_error("Illegal public flags value.");
871 if (public_header
->reset_flag
&& public_header
->version_flag
) {
872 set_detailed_error("Got version flag in reset packet");
876 switch (public_flags
& PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID
) {
877 case PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID
:
878 if (!reader_
->ReadUInt64(&public_header
->connection_id
)) {
879 set_detailed_error("Unable to read ConnectionId.");
882 public_header
->connection_id_length
= PACKET_8BYTE_CONNECTION_ID
;
884 case PACKET_PUBLIC_FLAGS_4BYTE_CONNECTION_ID
:
885 // If the connection_id is truncated, expect to read the last serialized
887 if (!reader_
->ReadBytes(&public_header
->connection_id
,
888 PACKET_4BYTE_CONNECTION_ID
)) {
889 set_detailed_error("Unable to read ConnectionId.");
892 if ((public_header
->connection_id
& k4ByteConnectionIdMask
) !=
893 (last_serialized_connection_id_
& k4ByteConnectionIdMask
)) {
894 set_detailed_error("Truncated 4 byte ConnectionId does not match "
895 "previous connection_id.");
898 public_header
->connection_id_length
= PACKET_4BYTE_CONNECTION_ID
;
899 public_header
->connection_id
= last_serialized_connection_id_
;
901 case PACKET_PUBLIC_FLAGS_1BYTE_CONNECTION_ID
:
902 if (!reader_
->ReadBytes(&public_header
->connection_id
,
903 PACKET_1BYTE_CONNECTION_ID
)) {
904 set_detailed_error("Unable to read ConnectionId.");
907 if ((public_header
->connection_id
& k1ByteConnectionIdMask
) !=
908 (last_serialized_connection_id_
& k1ByteConnectionIdMask
)) {
909 set_detailed_error("Truncated 1 byte ConnectionId does not match "
910 "previous connection_id.");
913 public_header
->connection_id_length
= PACKET_1BYTE_CONNECTION_ID
;
914 public_header
->connection_id
= last_serialized_connection_id_
;
916 case PACKET_PUBLIC_FLAGS_0BYTE_CONNECTION_ID
:
917 public_header
->connection_id_length
= PACKET_0BYTE_CONNECTION_ID
;
918 public_header
->connection_id
= last_serialized_connection_id_
;
922 public_header
->sequence_number_length
=
923 ReadSequenceNumberLength(
924 public_flags
>> kPublicHeaderSequenceNumberShift
);
926 // Read the version only if the packet is from the client.
927 // version flag from the server means version negotiation packet.
928 if (public_header
->version_flag
&& is_server_
) {
930 if (!reader_
->ReadUInt32(&version_tag
)) {
931 set_detailed_error("Unable to read protocol version.");
935 // If the version from the new packet is the same as the version of this
936 // framer, then the public flags should be set to something we understand.
937 // If not, this raises an error.
938 QuicVersion version
= QuicTagToQuicVersion(version_tag
);
939 if (version
== quic_version_
&& public_flags
> PACKET_PUBLIC_FLAGS_MAX
) {
940 set_detailed_error("Illegal public flags value.");
943 public_header
->versions
.push_back(version
);
949 QuicSequenceNumberLength
QuicFramer::GetMinSequenceNumberLength(
950 QuicPacketSequenceNumber sequence_number
) {
951 if (sequence_number
< 1 << (PACKET_1BYTE_SEQUENCE_NUMBER
* 8)) {
952 return PACKET_1BYTE_SEQUENCE_NUMBER
;
953 } else if (sequence_number
< 1 << (PACKET_2BYTE_SEQUENCE_NUMBER
* 8)) {
954 return PACKET_2BYTE_SEQUENCE_NUMBER
;
955 } else if (sequence_number
<
956 GG_UINT64_C(1) << (PACKET_4BYTE_SEQUENCE_NUMBER
* 8)) {
957 return PACKET_4BYTE_SEQUENCE_NUMBER
;
959 return PACKET_6BYTE_SEQUENCE_NUMBER
;
964 uint8
QuicFramer::GetSequenceNumberFlags(
965 QuicSequenceNumberLength sequence_number_length
) {
966 switch (sequence_number_length
) {
967 case PACKET_1BYTE_SEQUENCE_NUMBER
:
968 return PACKET_FLAGS_1BYTE_SEQUENCE
;
969 case PACKET_2BYTE_SEQUENCE_NUMBER
:
970 return PACKET_FLAGS_2BYTE_SEQUENCE
;
971 case PACKET_4BYTE_SEQUENCE_NUMBER
:
972 return PACKET_FLAGS_4BYTE_SEQUENCE
;
973 case PACKET_6BYTE_SEQUENCE_NUMBER
:
974 return PACKET_FLAGS_6BYTE_SEQUENCE
;
976 LOG(DFATAL
) << "Unreachable case statement.";
977 return PACKET_FLAGS_6BYTE_SEQUENCE
;
982 QuicFramer::AckFrameInfo
QuicFramer::GetAckFrameInfo(
983 const QuicAckFrame
& frame
) {
984 AckFrameInfo ack_info
;
985 if (!frame
.missing_packets
.empty()) {
986 DCHECK_GE(frame
.largest_observed
, *frame
.missing_packets
.rbegin());
987 size_t cur_range_length
= 0;
988 SequenceNumberSet::const_iterator iter
= frame
.missing_packets
.begin();
989 QuicPacketSequenceNumber last_missing
= *iter
;
991 for (; iter
!= frame
.missing_packets
.end(); ++iter
) {
992 if (cur_range_length
!= numeric_limits
<uint8
>::max() &&
993 *iter
== (last_missing
+ 1)) {
996 ack_info
.nack_ranges
[last_missing
- cur_range_length
] =
998 cur_range_length
= 0;
1000 ack_info
.max_delta
= max(ack_info
.max_delta
, *iter
- last_missing
);
1001 last_missing
= *iter
;
1003 // Include the last nack range.
1004 ack_info
.nack_ranges
[last_missing
- cur_range_length
] = cur_range_length
;
1005 // Include the range to the largest observed.
1006 ack_info
.max_delta
= max(ack_info
.max_delta
,
1007 frame
.largest_observed
- last_missing
);
1012 bool QuicFramer::ProcessPacketHeader(
1013 QuicPacketHeader
* header
,
1014 const QuicEncryptedPacket
& packet
) {
1015 if (!ProcessPacketSequenceNumber(header
->public_header
.sequence_number_length
,
1016 &header
->packet_sequence_number
)) {
1017 set_detailed_error("Unable to read sequence number.");
1018 return RaiseError(QUIC_INVALID_PACKET_HEADER
);
1021 if (header
->packet_sequence_number
== 0u) {
1022 set_detailed_error("Packet sequence numbers cannot be 0.");
1023 return RaiseError(QUIC_INVALID_PACKET_HEADER
);
1026 if (!visitor_
->OnUnauthenticatedHeader(*header
)) {
1030 if (!DecryptPayload(*header
, packet
)) {
1031 set_detailed_error("Unable to decrypt payload.");
1032 return RaiseError(QUIC_DECRYPTION_FAILURE
);
1035 uint8 private_flags
;
1036 if (!reader_
->ReadBytes(&private_flags
, 1)) {
1037 set_detailed_error("Unable to read private flags.");
1038 return RaiseError(QUIC_INVALID_PACKET_HEADER
);
1041 if (private_flags
> PACKET_PRIVATE_FLAGS_MAX
) {
1042 set_detailed_error("Illegal private flags value.");
1043 return RaiseError(QUIC_INVALID_PACKET_HEADER
);
1046 header
->entropy_flag
= (private_flags
& PACKET_PRIVATE_FLAGS_ENTROPY
) != 0;
1047 header
->fec_flag
= (private_flags
& PACKET_PRIVATE_FLAGS_FEC
) != 0;
1049 if ((private_flags
& PACKET_PRIVATE_FLAGS_FEC_GROUP
) != 0) {
1050 header
->is_in_fec_group
= IN_FEC_GROUP
;
1051 uint8 first_fec_protected_packet_offset
;
1052 if (!reader_
->ReadBytes(&first_fec_protected_packet_offset
, 1)) {
1053 set_detailed_error("Unable to read first fec protected packet offset.");
1054 return RaiseError(QUIC_INVALID_PACKET_HEADER
);
1056 if (first_fec_protected_packet_offset
>= header
->packet_sequence_number
) {
1057 set_detailed_error("First fec protected packet offset must be less "
1058 "than the sequence number.");
1059 return RaiseError(QUIC_INVALID_PACKET_HEADER
);
1062 header
->packet_sequence_number
- first_fec_protected_packet_offset
;
1065 header
->entropy_hash
= GetPacketEntropyHash(*header
);
1066 // Set the last sequence number after we have decrypted the packet
1067 // so we are confident is not attacker controlled.
1068 last_sequence_number_
= header
->packet_sequence_number
;
1072 bool QuicFramer::ProcessPacketSequenceNumber(
1073 QuicSequenceNumberLength sequence_number_length
,
1074 QuicPacketSequenceNumber
* sequence_number
) {
1075 QuicPacketSequenceNumber wire_sequence_number
= 0u;
1076 if (!reader_
->ReadBytes(&wire_sequence_number
, sequence_number_length
)) {
1080 // TODO(ianswett): Explore the usefulness of trying multiple sequence numbers
1081 // in case the first guess is incorrect.
1083 CalculatePacketSequenceNumberFromWire(sequence_number_length
,
1084 wire_sequence_number
);
1088 bool QuicFramer::ProcessFrameData(const QuicPacketHeader
& header
) {
1089 if (reader_
->IsDoneReading()) {
1090 set_detailed_error("Packet has no frames.");
1091 return RaiseError(QUIC_MISSING_PAYLOAD
);
1093 while (!reader_
->IsDoneReading()) {
1095 if (!reader_
->ReadBytes(&frame_type
, 1)) {
1096 set_detailed_error("Unable to read frame type.");
1097 return RaiseError(QUIC_INVALID_FRAME_DATA
);
1100 if (frame_type
& kQuicFrameTypeSpecialMask
) {
1102 if (frame_type
& kQuicFrameTypeStreamMask
) {
1103 QuicStreamFrame frame
;
1104 if (!ProcessStreamFrame(frame_type
, &frame
)) {
1105 return RaiseError(QUIC_INVALID_STREAM_DATA
);
1107 if (!visitor_
->OnStreamFrame(frame
)) {
1108 DVLOG(1) << "Visitor asked to stop further processing.";
1109 // Returning true since there was no parsing error.
1116 if (frame_type
& kQuicFrameTypeAckMask
) {
1118 if (!ProcessAckFrame(frame_type
, &frame
)) {
1119 return RaiseError(QUIC_INVALID_ACK_DATA
);
1121 if (!visitor_
->OnAckFrame(frame
)) {
1122 DVLOG(1) << "Visitor asked to stop further processing.";
1123 // Returning true since there was no parsing error.
1129 // Congestion Feedback Frame
1130 if (frame_type
& kQuicFrameTypeCongestionFeedbackMask
) {
1131 if (quic_version_
> QUIC_VERSION_22
) {
1132 set_detailed_error("Congestion Feedback Frame has been deprecated.");
1133 DLOG(WARNING
) << "Congestion Feedback Frame has been deprecated.";
1135 QuicCongestionFeedbackFrame frame
;
1136 if (!ProcessCongestionFeedbackFrame(&frame
)) {
1137 return RaiseError(QUIC_INVALID_CONGESTION_FEEDBACK_DATA
);
1139 if (!visitor_
->OnCongestionFeedbackFrame(frame
)) {
1140 DVLOG(1) << "Visitor asked to stop further processing.";
1141 // Returning true since there was no parsing error.
1147 // This was a special frame type that did not match any
1148 // of the known ones. Error.
1149 set_detailed_error("Illegal frame type.");
1150 DLOG(WARNING
) << "Illegal frame type: "
1151 << static_cast<int>(frame_type
);
1152 return RaiseError(QUIC_INVALID_FRAME_DATA
);
1155 switch (frame_type
) {
1157 // We're done with the packet.
1160 case RST_STREAM_FRAME
: {
1161 QuicRstStreamFrame frame
;
1162 if (!ProcessRstStreamFrame(&frame
)) {
1163 return RaiseError(QUIC_INVALID_RST_STREAM_DATA
);
1165 if (!visitor_
->OnRstStreamFrame(frame
)) {
1166 DVLOG(1) << "Visitor asked to stop further processing.";
1167 // Returning true since there was no parsing error.
1173 case CONNECTION_CLOSE_FRAME
: {
1174 QuicConnectionCloseFrame frame
;
1175 if (!ProcessConnectionCloseFrame(&frame
)) {
1176 return RaiseError(QUIC_INVALID_CONNECTION_CLOSE_DATA
);
1179 if (!visitor_
->OnConnectionCloseFrame(frame
)) {
1180 DVLOG(1) << "Visitor asked to stop further processing.";
1181 // Returning true since there was no parsing error.
1187 case GOAWAY_FRAME
: {
1188 QuicGoAwayFrame goaway_frame
;
1189 if (!ProcessGoAwayFrame(&goaway_frame
)) {
1190 return RaiseError(QUIC_INVALID_GOAWAY_DATA
);
1192 if (!visitor_
->OnGoAwayFrame(goaway_frame
)) {
1193 DVLOG(1) << "Visitor asked to stop further processing.";
1194 // Returning true since there was no parsing error.
1200 case WINDOW_UPDATE_FRAME
: {
1201 QuicWindowUpdateFrame window_update_frame
;
1202 if (!ProcessWindowUpdateFrame(&window_update_frame
)) {
1203 return RaiseError(QUIC_INVALID_WINDOW_UPDATE_DATA
);
1205 if (!visitor_
->OnWindowUpdateFrame(window_update_frame
)) {
1206 DVLOG(1) << "Visitor asked to stop further processing.";
1207 // Returning true since there was no parsing error.
1213 case BLOCKED_FRAME
: {
1214 QuicBlockedFrame blocked_frame
;
1215 if (!ProcessBlockedFrame(&blocked_frame
)) {
1216 return RaiseError(QUIC_INVALID_BLOCKED_DATA
);
1218 if (!visitor_
->OnBlockedFrame(blocked_frame
)) {
1219 DVLOG(1) << "Visitor asked to stop further processing.";
1220 // Returning true since there was no parsing error.
1226 case STOP_WAITING_FRAME
: {
1227 QuicStopWaitingFrame stop_waiting_frame
;
1228 if (!ProcessStopWaitingFrame(header
, &stop_waiting_frame
)) {
1229 return RaiseError(QUIC_INVALID_STOP_WAITING_DATA
);
1231 if (!visitor_
->OnStopWaitingFrame(stop_waiting_frame
)) {
1232 DVLOG(1) << "Visitor asked to stop further processing.";
1233 // Returning true since there was no parsing error.
1239 if (quic_version_
== QUIC_VERSION_16
) {
1240 LOG(DFATAL
) << "Trying to read a Ping in "
1241 << QuicVersionToString(quic_version_
);
1242 return RaiseError(QUIC_INTERNAL_ERROR
);
1244 // Ping has no payload.
1245 QuicPingFrame ping_frame
;
1246 if (!visitor_
->OnPingFrame(ping_frame
)) {
1247 DVLOG(1) << "Visitor asked to stop further processing.";
1248 // Returning true since there was no parsing error.
1255 set_detailed_error("Illegal frame type.");
1256 DLOG(WARNING
) << "Illegal frame type: "
1257 << static_cast<int>(frame_type
);
1258 return RaiseError(QUIC_INVALID_FRAME_DATA
);
1265 bool QuicFramer::ProcessStreamFrame(uint8 frame_type
,
1266 QuicStreamFrame
* frame
) {
1267 uint8 stream_flags
= frame_type
;
1269 stream_flags
&= ~kQuicFrameTypeStreamMask
;
1271 // Read from right to left: StreamID, Offset, Data Length, Fin.
1272 const uint8 stream_id_length
= (stream_flags
& kQuicStreamIDLengthMask
) + 1;
1273 stream_flags
>>= kQuicStreamIdShift
;
1275 uint8 offset_length
= (stream_flags
& kQuicStreamOffsetMask
);
1276 // There is no encoding for 1 byte, only 0 and 2 through 8.
1277 if (offset_length
> 0) {
1280 stream_flags
>>= kQuicStreamOffsetShift
;
1282 bool has_data_length
=
1283 (stream_flags
& kQuicStreamDataLengthMask
) == kQuicStreamDataLengthMask
;
1284 stream_flags
>>= kQuicStreamDataLengthShift
;
1286 frame
->fin
= (stream_flags
& kQuicStreamFinMask
) == kQuicStreamFinShift
;
1288 frame
->stream_id
= 0;
1289 if (!reader_
->ReadBytes(&frame
->stream_id
, stream_id_length
)) {
1290 set_detailed_error("Unable to read stream_id.");
1295 if (!reader_
->ReadBytes(&frame
->offset
, offset_length
)) {
1296 set_detailed_error("Unable to read offset.");
1300 StringPiece frame_data
;
1301 if (has_data_length
) {
1302 if (!reader_
->ReadStringPiece16(&frame_data
)) {
1303 set_detailed_error("Unable to read frame data.");
1307 if (!reader_
->ReadStringPiece(&frame_data
, reader_
->BytesRemaining())) {
1308 set_detailed_error("Unable to read frame data.");
1312 // Point frame to the right data.
1313 frame
->data
.Clear();
1314 if (!frame_data
.empty()) {
1315 frame
->data
.Append(const_cast<char*>(frame_data
.data()), frame_data
.size());
1321 bool QuicFramer::ProcessAckFrame(uint8 frame_type
, QuicAckFrame
* ack_frame
) {
1322 // Determine the three lengths from the frame type: largest observed length,
1323 // missing sequence number length, and missing range length.
1324 const QuicSequenceNumberLength missing_sequence_number_length
=
1325 ReadSequenceNumberLength(frame_type
);
1326 frame_type
>>= kQuicSequenceNumberLengthShift
;
1327 const QuicSequenceNumberLength largest_observed_sequence_number_length
=
1328 ReadSequenceNumberLength(frame_type
);
1329 frame_type
>>= kQuicSequenceNumberLengthShift
;
1330 ack_frame
->is_truncated
= frame_type
& kQuicAckTruncatedMask
;
1331 frame_type
>>= kQuicAckTruncatedShift
;
1332 bool has_nacks
= frame_type
& kQuicHasNacksMask
;
1334 if (!reader_
->ReadBytes(&ack_frame
->entropy_hash
, 1)) {
1335 set_detailed_error("Unable to read entropy hash for received packets.");
1339 if (!reader_
->ReadBytes(&ack_frame
->largest_observed
,
1340 largest_observed_sequence_number_length
)) {
1341 set_detailed_error("Unable to read largest observed.");
1345 uint64 delta_time_largest_observed_us
;
1346 if (!reader_
->ReadUFloat16(&delta_time_largest_observed_us
)) {
1347 set_detailed_error("Unable to read delta time largest observed.");
1351 if (delta_time_largest_observed_us
== kUFloat16MaxValue
) {
1352 ack_frame
->delta_time_largest_observed
= QuicTime::Delta::Infinite();
1354 ack_frame
->delta_time_largest_observed
=
1355 QuicTime::Delta::FromMicroseconds(delta_time_largest_observed_us
);
1358 if (!ProcessTimestampsInAckFrame(ack_frame
)) {
1366 uint8 num_missing_ranges
;
1367 if (!reader_
->ReadBytes(&num_missing_ranges
, 1)) {
1368 set_detailed_error("Unable to read num missing packet ranges.");
1372 QuicPacketSequenceNumber last_sequence_number
= ack_frame
->largest_observed
;
1373 for (size_t i
= 0; i
< num_missing_ranges
; ++i
) {
1374 QuicPacketSequenceNumber missing_delta
= 0;
1375 if (!reader_
->ReadBytes(&missing_delta
, missing_sequence_number_length
)) {
1376 set_detailed_error("Unable to read missing sequence number delta.");
1379 last_sequence_number
-= missing_delta
;
1380 QuicPacketSequenceNumber range_length
= 0;
1381 if (!reader_
->ReadBytes(&range_length
, PACKET_1BYTE_SEQUENCE_NUMBER
)) {
1382 set_detailed_error("Unable to read missing sequence number range.");
1385 for (size_t i
= 0; i
<= range_length
; ++i
) {
1386 ack_frame
->missing_packets
.insert(last_sequence_number
- i
);
1388 // Subtract an extra 1 to ensure ranges are represented efficiently and
1389 // can't overlap by 1 sequence number. This allows a missing_delta of 0
1390 // to represent an adjacent nack range.
1391 last_sequence_number
-= (range_length
+ 1);
1394 // Parse the revived packets list.
1395 uint8 num_revived_packets
;
1396 if (!reader_
->ReadBytes(&num_revived_packets
, 1)) {
1397 set_detailed_error("Unable to read num revived packets.");
1401 for (size_t i
= 0; i
< num_revived_packets
; ++i
) {
1402 QuicPacketSequenceNumber revived_packet
= 0;
1403 if (!reader_
->ReadBytes(&revived_packet
,
1404 largest_observed_sequence_number_length
)) {
1405 set_detailed_error("Unable to read revived packet.");
1409 ack_frame
->revived_packets
.insert(revived_packet
);
1415 bool QuicFramer::ProcessTimestampsInAckFrame(QuicAckFrame
* ack_frame
) {
1416 if (version() > QUIC_VERSION_22
&& !ack_frame
->is_truncated
) {
1417 uint8 num_received_packets
;
1418 if (!reader_
->ReadBytes(&num_received_packets
, 1)) {
1419 set_detailed_error("Unable to read num received packets.");
1423 if (num_received_packets
> 0) {
1424 uint8 delta_from_largest_observed
;
1425 if (!reader_
->ReadBytes(&delta_from_largest_observed
,
1426 PACKET_1BYTE_SEQUENCE_NUMBER
)) {
1428 "Unable to read sequence delta in received packets.");
1431 QuicPacketSequenceNumber seq_num
= ack_frame
->largest_observed
-
1432 delta_from_largest_observed
;
1434 // Time delta from the framer creation.
1435 uint32 time_delta_us
;
1436 if (!reader_
->ReadBytes(&time_delta_us
, sizeof(time_delta_us
))) {
1437 set_detailed_error("Unable to read time delta in received packets.");
1441 last_timestamp_
= CalculateTimestampFromWire(time_delta_us
);
1443 ack_frame
->received_packet_times
.push_back(
1444 make_pair(seq_num
, creation_time_
.Add(last_timestamp_
)));
1446 for (uint8 i
= 1; i
< num_received_packets
; ++i
) {
1447 if (!reader_
->ReadBytes(&delta_from_largest_observed
,
1448 PACKET_1BYTE_SEQUENCE_NUMBER
)) {
1450 "Unable to read sequence delta in received packets.");
1453 seq_num
= ack_frame
->largest_observed
- delta_from_largest_observed
;
1455 // Time delta from the previous timestamp.
1456 uint64 incremental_time_delta_us
;
1457 if (!reader_
->ReadUFloat16(&incremental_time_delta_us
)) {
1459 "Unable to read incremental time delta in received packets.");
1463 last_timestamp_
= last_timestamp_
.Add(
1464 QuicTime::Delta::FromMicroseconds(incremental_time_delta_us
));
1465 ack_frame
->received_packet_times
.push_back(
1466 make_pair(seq_num
, creation_time_
.Add(last_timestamp_
)));
1473 bool QuicFramer::ProcessStopWaitingFrame(const QuicPacketHeader
& header
,
1474 QuicStopWaitingFrame
* stop_waiting
) {
1475 if (!reader_
->ReadBytes(&stop_waiting
->entropy_hash
, 1)) {
1476 set_detailed_error("Unable to read entropy hash for sent packets.");
1480 QuicPacketSequenceNumber least_unacked_delta
= 0;
1481 if (!reader_
->ReadBytes(&least_unacked_delta
,
1482 header
.public_header
.sequence_number_length
)) {
1483 set_detailed_error("Unable to read least unacked delta.");
1486 DCHECK_GE(header
.packet_sequence_number
, least_unacked_delta
);
1487 stop_waiting
->least_unacked
=
1488 header
.packet_sequence_number
- least_unacked_delta
;
1493 bool QuicFramer::ProcessCongestionFeedbackFrame(
1494 QuicCongestionFeedbackFrame
* frame
) {
1495 uint8 feedback_type
;
1496 if (!reader_
->ReadBytes(&feedback_type
, 1)) {
1497 set_detailed_error("Unable to read congestion feedback type.");
1501 static_cast<CongestionFeedbackType
>(feedback_type
);
1503 switch (frame
->type
) {
1505 CongestionFeedbackMessageTCP
* tcp
= &frame
->tcp
;
1506 uint16 receive_window
= 0;
1507 if (!reader_
->ReadUInt16(&receive_window
)) {
1508 set_detailed_error("Unable to read receive window.");
1511 // Simple bit packing, don't send the 4 least significant bits.
1512 tcp
->receive_window
= static_cast<QuicByteCount
>(receive_window
) << 4;
1516 set_detailed_error("Illegal congestion feedback type.");
1517 DLOG(WARNING
) << "Illegal congestion feedback type: "
1519 return RaiseError(QUIC_INVALID_FRAME_DATA
);
1525 bool QuicFramer::ProcessRstStreamFrame(QuicRstStreamFrame
* frame
) {
1526 if (!reader_
->ReadUInt32(&frame
->stream_id
)) {
1527 set_detailed_error("Unable to read stream_id.");
1531 if (!reader_
->ReadUInt64(&frame
->byte_offset
)) {
1532 set_detailed_error("Unable to read rst stream sent byte offset.");
1537 if (!reader_
->ReadUInt32(&error_code
)) {
1538 set_detailed_error("Unable to read rst stream error code.");
1542 if (error_code
>= QUIC_STREAM_LAST_ERROR
||
1543 error_code
< QUIC_STREAM_NO_ERROR
) {
1544 set_detailed_error("Invalid rst stream error code.");
1548 frame
->error_code
= static_cast<QuicRstStreamErrorCode
>(error_code
);
1550 StringPiece error_details
;
1551 if (!reader_
->ReadStringPiece16(&error_details
)) {
1552 set_detailed_error("Unable to read rst stream error details.");
1555 frame
->error_details
= error_details
.as_string();
1560 bool QuicFramer::ProcessConnectionCloseFrame(QuicConnectionCloseFrame
* frame
) {
1562 if (!reader_
->ReadUInt32(&error_code
)) {
1563 set_detailed_error("Unable to read connection close error code.");
1567 if (error_code
>= QUIC_LAST_ERROR
||
1568 error_code
< QUIC_NO_ERROR
) {
1569 set_detailed_error("Invalid error code.");
1573 frame
->error_code
= static_cast<QuicErrorCode
>(error_code
);
1575 StringPiece error_details
;
1576 if (!reader_
->ReadStringPiece16(&error_details
)) {
1577 set_detailed_error("Unable to read connection close error details.");
1580 frame
->error_details
= error_details
.as_string();
1585 bool QuicFramer::ProcessGoAwayFrame(QuicGoAwayFrame
* frame
) {
1587 if (!reader_
->ReadUInt32(&error_code
)) {
1588 set_detailed_error("Unable to read go away error code.");
1591 frame
->error_code
= static_cast<QuicErrorCode
>(error_code
);
1593 if (error_code
>= QUIC_LAST_ERROR
||
1594 error_code
< QUIC_NO_ERROR
) {
1595 set_detailed_error("Invalid error code.");
1600 if (!reader_
->ReadUInt32(&stream_id
)) {
1601 set_detailed_error("Unable to read last good stream id.");
1604 frame
->last_good_stream_id
= static_cast<QuicStreamId
>(stream_id
);
1606 StringPiece reason_phrase
;
1607 if (!reader_
->ReadStringPiece16(&reason_phrase
)) {
1608 set_detailed_error("Unable to read goaway reason.");
1611 frame
->reason_phrase
= reason_phrase
.as_string();
1616 bool QuicFramer::ProcessWindowUpdateFrame(QuicWindowUpdateFrame
* frame
) {
1617 if (!reader_
->ReadUInt32(&frame
->stream_id
)) {
1618 set_detailed_error("Unable to read stream_id.");
1622 if (!reader_
->ReadUInt64(&frame
->byte_offset
)) {
1623 set_detailed_error("Unable to read window byte_offset.");
1630 bool QuicFramer::ProcessBlockedFrame(QuicBlockedFrame
* frame
) {
1631 if (!reader_
->ReadUInt32(&frame
->stream_id
)) {
1632 set_detailed_error("Unable to read stream_id.");
1640 StringPiece
QuicFramer::GetAssociatedDataFromEncryptedPacket(
1641 const QuicEncryptedPacket
& encrypted
,
1642 QuicConnectionIdLength connection_id_length
,
1643 bool includes_version
,
1644 QuicSequenceNumberLength sequence_number_length
) {
1646 encrypted
.data() + kStartOfHashData
, GetStartOfEncryptedData(
1647 connection_id_length
, includes_version
, sequence_number_length
)
1648 - kStartOfHashData
);
1651 void QuicFramer::SetDecrypter(QuicDecrypter
* decrypter
,
1652 EncryptionLevel level
) {
1653 DCHECK(alternative_decrypter_
.get() == NULL
);
1654 DCHECK_GE(level
, decrypter_level_
);
1655 decrypter_
.reset(decrypter
);
1656 decrypter_level_
= level
;
1659 void QuicFramer::SetAlternativeDecrypter(QuicDecrypter
* decrypter
,
1660 EncryptionLevel level
,
1661 bool latch_once_used
) {
1662 alternative_decrypter_
.reset(decrypter
);
1663 alternative_decrypter_level_
= level
;
1664 alternative_decrypter_latch_
= latch_once_used
;
1667 const QuicDecrypter
* QuicFramer::decrypter() const {
1668 return decrypter_
.get();
1671 const QuicDecrypter
* QuicFramer::alternative_decrypter() const {
1672 return alternative_decrypter_
.get();
1675 void QuicFramer::SetEncrypter(EncryptionLevel level
,
1676 QuicEncrypter
* encrypter
) {
1677 DCHECK_GE(level
, 0);
1678 DCHECK_LT(level
, NUM_ENCRYPTION_LEVELS
);
1679 encrypter_
[level
].reset(encrypter
);
1682 const QuicEncrypter
* QuicFramer::encrypter(EncryptionLevel level
) const {
1683 DCHECK_GE(level
, 0);
1684 DCHECK_LT(level
, NUM_ENCRYPTION_LEVELS
);
1685 DCHECK(encrypter_
[level
].get() != NULL
);
1686 return encrypter_
[level
].get();
1689 QuicEncryptedPacket
* QuicFramer::EncryptPacket(
1690 EncryptionLevel level
,
1691 QuicPacketSequenceNumber packet_sequence_number
,
1692 const QuicPacket
& packet
) {
1693 DCHECK(encrypter_
[level
].get() != NULL
);
1695 scoped_ptr
<QuicData
> out(encrypter_
[level
]->EncryptPacket(
1696 packet_sequence_number
, packet
.AssociatedData(), packet
.Plaintext()));
1697 if (out
.get() == NULL
) {
1698 RaiseError(QUIC_ENCRYPTION_FAILURE
);
1701 StringPiece header_data
= packet
.BeforePlaintext();
1702 size_t len
= header_data
.length() + out
->length();
1703 char* buffer
= new char[len
];
1704 // TODO(rch): eliminate this buffer copy by passing in a buffer to Encrypt().
1705 memcpy(buffer
, header_data
.data(), header_data
.length());
1706 memcpy(buffer
+ header_data
.length(), out
->data(), out
->length());
1707 return new QuicEncryptedPacket(buffer
, len
, true);
1710 size_t QuicFramer::GetMaxPlaintextSize(size_t ciphertext_size
) {
1711 // In order to keep the code simple, we don't have the current encryption
1712 // level to hand. Both the NullEncrypter and AES-GCM have a tag length of 12.
1713 size_t min_plaintext_size
= ciphertext_size
;
1715 for (int i
= ENCRYPTION_NONE
; i
< NUM_ENCRYPTION_LEVELS
; i
++) {
1716 if (encrypter_
[i
].get() != NULL
) {
1717 size_t size
= encrypter_
[i
]->GetMaxPlaintextSize(ciphertext_size
);
1718 if (size
< min_plaintext_size
) {
1719 min_plaintext_size
= size
;
1724 return min_plaintext_size
;
1727 bool QuicFramer::DecryptPayload(const QuicPacketHeader
& header
,
1728 const QuicEncryptedPacket
& packet
) {
1729 StringPiece encrypted
;
1730 if (!reader_
->ReadStringPiece(&encrypted
, reader_
->BytesRemaining())) {
1733 DCHECK(decrypter_
.get() != NULL
);
1734 decrypted_
.reset(decrypter_
->DecryptPacket(
1735 header
.packet_sequence_number
,
1736 GetAssociatedDataFromEncryptedPacket(
1738 header
.public_header
.connection_id_length
,
1739 header
.public_header
.version_flag
,
1740 header
.public_header
.sequence_number_length
),
1742 if (decrypted_
.get() != NULL
) {
1743 visitor_
->OnDecryptedPacket(decrypter_level_
);
1744 } else if (alternative_decrypter_
.get() != NULL
) {
1745 decrypted_
.reset(alternative_decrypter_
->DecryptPacket(
1746 header
.packet_sequence_number
,
1747 GetAssociatedDataFromEncryptedPacket(
1749 header
.public_header
.connection_id_length
,
1750 header
.public_header
.version_flag
,
1751 header
.public_header
.sequence_number_length
),
1753 if (decrypted_
.get() != NULL
) {
1754 visitor_
->OnDecryptedPacket(alternative_decrypter_level_
);
1755 if (alternative_decrypter_latch_
) {
1756 // Switch to the alternative decrypter and latch so that we cannot
1758 decrypter_
.reset(alternative_decrypter_
.release());
1759 decrypter_level_
= alternative_decrypter_level_
;
1760 alternative_decrypter_level_
= ENCRYPTION_NONE
;
1762 // Switch the alternative decrypter so that we use it first next time.
1763 decrypter_
.swap(alternative_decrypter_
);
1764 EncryptionLevel level
= alternative_decrypter_level_
;
1765 alternative_decrypter_level_
= decrypter_level_
;
1766 decrypter_level_
= level
;
1771 if (decrypted_
.get() == NULL
) {
1772 DLOG(WARNING
) << "DecryptPacket failed for sequence_number:"
1773 << header
.packet_sequence_number
;
1777 reader_
.reset(new QuicDataReader(decrypted_
->data(), decrypted_
->length()));
1781 size_t QuicFramer::GetAckFrameSize(
1782 const QuicAckFrame
& ack
,
1783 QuicSequenceNumberLength sequence_number_length
) {
1784 AckFrameInfo ack_info
= GetAckFrameInfo(ack
);
1785 QuicSequenceNumberLength largest_observed_length
=
1786 GetMinSequenceNumberLength(ack
.largest_observed
);
1787 QuicSequenceNumberLength missing_sequence_number_length
=
1788 GetMinSequenceNumberLength(ack_info
.max_delta
);
1790 size_t ack_size
= GetMinAckFrameSize(sequence_number_length
,
1791 largest_observed_length
);
1792 if (!ack_info
.nack_ranges
.empty()) {
1793 ack_size
+= kNumberOfNackRangesSize
+ kNumberOfRevivedPacketsSize
;
1794 ack_size
+= min(ack_info
.nack_ranges
.size(), kMaxNackRanges
) *
1795 (missing_sequence_number_length
+ PACKET_1BYTE_SEQUENCE_NUMBER
);
1796 ack_size
+= min(ack
.revived_packets
.size(),
1797 kMaxRevivedPackets
) * largest_observed_length
;
1800 // In version 23, if the ack will be truncated due to too many nack ranges,
1801 // then do not include the number of timestamps (1 byte).
1802 if (version() > QUIC_VERSION_22
&&
1803 ack_info
.nack_ranges
.size() <= kMaxNackRanges
) {
1804 // 1 byte for the number of timestamps.
1806 if (ack
.received_packet_times
.size() > 0) {
1807 // 1 byte for sequence number, 4 bytes for timestamp for the first
1811 // 1 byte for sequence number, 2 bytes for timestamp for the other
1813 ack_size
+= 3 * (ack
.received_packet_times
.size() - 1);
1820 size_t QuicFramer::ComputeFrameLength(
1821 const QuicFrame
& frame
,
1822 bool last_frame_in_packet
,
1823 InFecGroup is_in_fec_group
,
1824 QuicSequenceNumberLength sequence_number_length
) {
1825 switch (frame
.type
) {
1827 return GetMinStreamFrameSize(frame
.stream_frame
->stream_id
,
1828 frame
.stream_frame
->offset
,
1829 last_frame_in_packet
,
1831 frame
.stream_frame
->data
.TotalBufferSize();
1833 return GetAckFrameSize(*frame
.ack_frame
, sequence_number_length
);
1835 case CONGESTION_FEEDBACK_FRAME
: {
1836 size_t len
= kQuicFrameTypeSize
;
1837 const QuicCongestionFeedbackFrame
& congestion_feedback
=
1838 *frame
.congestion_feedback_frame
;
1839 len
+= 1; // Congestion feedback type.
1841 switch (congestion_feedback
.type
) {
1843 len
+= 2; // Receive window.
1846 set_detailed_error("Illegal feedback type.");
1847 DVLOG(1) << "Illegal feedback type: " << congestion_feedback
.type
;
1852 case STOP_WAITING_FRAME
:
1853 return GetStopWaitingFrameSize(sequence_number_length
);
1855 // Ping has no payload.
1856 return kQuicFrameTypeSize
;
1857 case RST_STREAM_FRAME
:
1858 return GetMinRstStreamFrameSize() +
1859 frame
.rst_stream_frame
->error_details
.size();
1860 case CONNECTION_CLOSE_FRAME
:
1861 return GetMinConnectionCloseFrameSize() +
1862 frame
.connection_close_frame
->error_details
.size();
1864 return GetMinGoAwayFrameSize() + frame
.goaway_frame
->reason_phrase
.size();
1865 case WINDOW_UPDATE_FRAME
:
1866 return GetWindowUpdateFrameSize();
1868 return GetBlockedFrameSize();
1872 case NUM_FRAME_TYPES
:
1877 // Not reachable, but some Chrome compilers can't figure that out. *sigh*
1882 bool QuicFramer::AppendTypeByte(const QuicFrame
& frame
,
1883 bool no_stream_frame_length
,
1884 QuicDataWriter
* writer
) {
1885 uint8 type_byte
= 0;
1886 switch (frame
.type
) {
1887 case STREAM_FRAME
: {
1888 if (frame
.stream_frame
== NULL
) {
1889 LOG(DFATAL
) << "Failed to append STREAM frame with no stream_frame.";
1892 type_byte
|= frame
.stream_frame
->fin
? kQuicStreamFinMask
: 0;
1895 type_byte
<<= kQuicStreamDataLengthShift
;
1896 type_byte
|= no_stream_frame_length
? 0: kQuicStreamDataLengthMask
;
1899 type_byte
<<= kQuicStreamOffsetShift
;
1900 const size_t offset_len
= GetStreamOffsetSize(frame
.stream_frame
->offset
);
1901 if (offset_len
> 0) {
1902 type_byte
|= offset_len
- 1;
1905 // stream id 2 bits.
1906 type_byte
<<= kQuicStreamIdShift
;
1907 type_byte
|= GetStreamIdSize(frame
.stream_frame
->stream_id
) - 1;
1908 type_byte
|= kQuicFrameTypeStreamMask
; // Set Stream Frame Type to 1.
1913 case CONGESTION_FEEDBACK_FRAME
: {
1914 // TODO(ianswett): Use extra 5 bits in the congestion feedback framing.
1915 type_byte
= kQuicFrameTypeCongestionFeedbackMask
;
1919 type_byte
= frame
.type
;
1923 return writer
->WriteUInt8(type_byte
);
1927 bool QuicFramer::AppendPacketSequenceNumber(
1928 QuicSequenceNumberLength sequence_number_length
,
1929 QuicPacketSequenceNumber packet_sequence_number
,
1930 QuicDataWriter
* writer
) {
1931 // Ensure the entire sequence number can be written.
1932 if (writer
->capacity() - writer
->length() <
1933 static_cast<size_t>(sequence_number_length
)) {
1936 switch (sequence_number_length
) {
1937 case PACKET_1BYTE_SEQUENCE_NUMBER
:
1938 return writer
->WriteUInt8(
1939 packet_sequence_number
& k1ByteSequenceNumberMask
);
1941 case PACKET_2BYTE_SEQUENCE_NUMBER
:
1942 return writer
->WriteUInt16(
1943 packet_sequence_number
& k2ByteSequenceNumberMask
);
1945 case PACKET_4BYTE_SEQUENCE_NUMBER
:
1946 return writer
->WriteUInt32(
1947 packet_sequence_number
& k4ByteSequenceNumberMask
);
1949 case PACKET_6BYTE_SEQUENCE_NUMBER
:
1950 return writer
->WriteUInt48(
1951 packet_sequence_number
& k6ByteSequenceNumberMask
);
1954 DCHECK(false) << "sequence_number_length: " << sequence_number_length
;
1959 bool QuicFramer::AppendStreamFrame(
1960 const QuicStreamFrame
& frame
,
1961 bool no_stream_frame_length
,
1962 QuicDataWriter
* writer
) {
1963 if (!writer
->WriteBytes(&frame
.stream_id
, GetStreamIdSize(frame
.stream_id
))) {
1964 LOG(DFATAL
) << "Writing stream id size failed.";
1967 if (!writer
->WriteBytes(&frame
.offset
, GetStreamOffsetSize(frame
.offset
))) {
1968 LOG(DFATAL
) << "Writing offset size failed.";
1971 if (!no_stream_frame_length
) {
1972 if (!writer
->WriteUInt16(frame
.data
.TotalBufferSize())) {
1973 LOG(DFATAL
) << "Writing stream frame length failed";
1978 if (!writer
->WriteIOVector(frame
.data
)) {
1979 LOG(DFATAL
) << "Writing frame data failed.";
1986 void QuicFramer::set_version(const QuicVersion version
) {
1987 DCHECK(IsSupportedVersion(version
)) << QuicVersionToString(version
);
1988 quic_version_
= version
;
1991 bool QuicFramer::AppendAckFrameAndTypeByte(
1992 const QuicPacketHeader
& header
,
1993 const QuicAckFrame
& frame
,
1994 QuicDataWriter
* writer
) {
1995 AckFrameInfo ack_info
= GetAckFrameInfo(frame
);
1996 QuicPacketSequenceNumber ack_largest_observed
= frame
.largest_observed
;
1997 QuicSequenceNumberLength largest_observed_length
=
1998 GetMinSequenceNumberLength(ack_largest_observed
);
1999 QuicSequenceNumberLength missing_sequence_number_length
=
2000 GetMinSequenceNumberLength(ack_info
.max_delta
);
2001 // Determine whether we need to truncate ranges.
2002 size_t available_range_bytes
= writer
->capacity() - writer
->length() -
2003 kNumberOfRevivedPacketsSize
- kNumberOfNackRangesSize
-
2004 GetMinAckFrameSize(header
.public_header
.sequence_number_length
,
2005 largest_observed_length
);
2006 size_t max_num_ranges
= available_range_bytes
/
2007 (missing_sequence_number_length
+ PACKET_1BYTE_SEQUENCE_NUMBER
);
2008 max_num_ranges
= min(kMaxNackRanges
, max_num_ranges
);
2009 bool truncated
= ack_info
.nack_ranges
.size() > max_num_ranges
;
2010 DVLOG_IF(1, truncated
) << "Truncating ack from "
2011 << ack_info
.nack_ranges
.size() << " ranges to "
2013 // Write out the type byte by setting the low order bits and doing shifts
2014 // to make room for the next bit flags to be set.
2015 // Whether there are any nacks.
2016 uint8 type_byte
= ack_info
.nack_ranges
.empty() ? 0 : kQuicHasNacksMask
;
2019 type_byte
<<= kQuicAckTruncatedShift
;
2020 type_byte
|= truncated
? kQuicAckTruncatedMask
: 0;
2022 // Largest observed sequence number length.
2023 type_byte
<<= kQuicSequenceNumberLengthShift
;
2024 type_byte
|= GetSequenceNumberFlags(largest_observed_length
);
2026 // Missing sequence number length.
2027 type_byte
<<= kQuicSequenceNumberLengthShift
;
2028 type_byte
|= GetSequenceNumberFlags(missing_sequence_number_length
);
2030 type_byte
|= kQuicFrameTypeAckMask
;
2032 if (!writer
->WriteUInt8(type_byte
)) {
2036 QuicPacketEntropyHash ack_entropy_hash
= frame
.entropy_hash
;
2037 NackRangeMap::reverse_iterator ack_iter
= ack_info
.nack_ranges
.rbegin();
2039 // Skip the nack ranges which the truncated ack won't include and set
2040 // a correct largest observed for the truncated ack.
2041 for (size_t i
= 1; i
< (ack_info
.nack_ranges
.size() - max_num_ranges
);
2045 // If the last range is followed by acks, include them.
2046 // If the last range is followed by another range, specify the end of the
2047 // range as the largest_observed.
2048 ack_largest_observed
= ack_iter
->first
- 1;
2049 // Also update the entropy so it matches the largest observed.
2050 ack_entropy_hash
= entropy_calculator_
->EntropyHash(ack_largest_observed
);
2054 if (!writer
->WriteUInt8(ack_entropy_hash
)) {
2058 if (!AppendPacketSequenceNumber(largest_observed_length
,
2059 ack_largest_observed
, writer
)) {
2063 uint64 delta_time_largest_observed_us
= kUFloat16MaxValue
;
2064 if (!frame
.delta_time_largest_observed
.IsInfinite()) {
2065 DCHECK_LE(0u, frame
.delta_time_largest_observed
.ToMicroseconds());
2066 delta_time_largest_observed_us
=
2067 frame
.delta_time_largest_observed
.ToMicroseconds();
2070 if (!writer
->WriteUFloat16(delta_time_largest_observed_us
)) {
2074 // Timestamp goes at the end of the required fields.
2075 if (version() > QUIC_VERSION_22
&& !truncated
) {
2076 if (!AppendTimestampToAckFrame(frame
, writer
)) {
2081 if (ack_info
.nack_ranges
.empty()) {
2085 const uint8 num_missing_ranges
=
2086 min(ack_info
.nack_ranges
.size(), max_num_ranges
);
2087 if (!writer
->WriteBytes(&num_missing_ranges
, 1)) {
2091 int num_ranges_written
= 0;
2092 QuicPacketSequenceNumber last_sequence_written
= ack_largest_observed
;
2093 for (; ack_iter
!= ack_info
.nack_ranges
.rend(); ++ack_iter
) {
2094 // Calculate the delta to the last number in the range.
2095 QuicPacketSequenceNumber missing_delta
=
2096 last_sequence_written
- (ack_iter
->first
+ ack_iter
->second
);
2097 if (!AppendPacketSequenceNumber(missing_sequence_number_length
,
2098 missing_delta
, writer
)) {
2101 if (!AppendPacketSequenceNumber(PACKET_1BYTE_SEQUENCE_NUMBER
,
2102 ack_iter
->second
, writer
)) {
2105 // Subtract 1 so a missing_delta of 0 means an adjacent range.
2106 last_sequence_written
= ack_iter
->first
- 1;
2107 ++num_ranges_written
;
2109 DCHECK_EQ(num_missing_ranges
, num_ranges_written
);
2111 // Append revived packets.
2112 // If not all the revived packets fit, only mention the ones that do.
2113 uint8 num_revived_packets
= min(frame
.revived_packets
.size(),
2114 kMaxRevivedPackets
);
2115 num_revived_packets
= min(
2116 static_cast<size_t>(num_revived_packets
),
2117 (writer
->capacity() - writer
->length()) / largest_observed_length
);
2118 if (!writer
->WriteBytes(&num_revived_packets
, 1)) {
2122 SequenceNumberSet::const_iterator iter
= frame
.revived_packets
.begin();
2123 for (int i
= 0; i
< num_revived_packets
; ++i
, ++iter
) {
2124 LOG_IF(DFATAL
, !ContainsKey(frame
.missing_packets
, *iter
));
2125 if (!AppendPacketSequenceNumber(largest_observed_length
,
2134 bool QuicFramer::AppendCongestionFeedbackFrame(
2135 const QuicCongestionFeedbackFrame
& frame
,
2136 QuicDataWriter
* writer
) {
2137 if (!writer
->WriteBytes(&frame
.type
, 1)) {
2141 switch (frame
.type
) {
2143 const CongestionFeedbackMessageTCP
& tcp
= frame
.tcp
;
2144 DCHECK_LE(tcp
.receive_window
, 1u << 20);
2145 // Simple bit packing, don't send the 4 least significant bits.
2146 uint16 receive_window
= static_cast<uint16
>(tcp
.receive_window
>> 4);
2147 if (!writer
->WriteUInt16(receive_window
)) {
2159 bool QuicFramer::AppendTimestampToAckFrame(const QuicAckFrame
& frame
,
2160 QuicDataWriter
* writer
) {
2161 DCHECK_GE(version(), QUIC_VERSION_23
);
2162 DCHECK_GE(numeric_limits
<uint8
>::max(), frame
.received_packet_times
.size());
2163 // num_received_packets is only 1 byte.
2164 if (frame
.received_packet_times
.size() > numeric_limits
<uint8
>::max()) {
2168 uint8 num_received_packets
= frame
.received_packet_times
.size();
2170 if (!writer
->WriteBytes(&num_received_packets
, 1)) {
2173 if (num_received_packets
== 0) {
2177 PacketTimeList::const_iterator it
= frame
.received_packet_times
.begin();
2178 QuicPacketSequenceNumber sequence_number
= it
->first
;
2179 QuicPacketSequenceNumber delta_from_largest_observed
=
2180 frame
.largest_observed
- sequence_number
;
2182 DCHECK_GE(numeric_limits
<uint8
>::max(), delta_from_largest_observed
);
2183 if (delta_from_largest_observed
> numeric_limits
<uint8
>::max()) {
2187 if (!writer
->WriteUInt8(
2188 delta_from_largest_observed
& k1ByteSequenceNumberMask
)) {
2192 // Use the lowest 4 bytes of the time delta from the creation_time_.
2193 const uint64 time_epoch_delta_us
= GG_UINT64_C(1) << 32;
2194 uint32 time_delta_us
=
2195 static_cast<uint32
>(it
->second
.Subtract(creation_time_
).ToMicroseconds()
2196 & (time_epoch_delta_us
- 1));
2197 if (!writer
->WriteBytes(&time_delta_us
, sizeof(time_delta_us
))) {
2201 QuicTime prev_time
= it
->second
;
2203 for (++it
; it
!= frame
.received_packet_times
.end(); ++it
) {
2204 sequence_number
= it
->first
;
2205 delta_from_largest_observed
= frame
.largest_observed
- sequence_number
;
2207 if (delta_from_largest_observed
> numeric_limits
<uint8
>::max()) {
2211 if (!writer
->WriteUInt8(
2212 delta_from_largest_observed
& k1ByteSequenceNumberMask
)) {
2216 uint64 time_delta_us
= it
->second
.Subtract(prev_time
).ToMicroseconds();
2217 prev_time
= it
->second
;
2218 if (!writer
->WriteUFloat16(time_delta_us
)) {
2225 bool QuicFramer::AppendStopWaitingFrame(
2226 const QuicPacketHeader
& header
,
2227 const QuicStopWaitingFrame
& frame
,
2228 QuicDataWriter
* writer
) {
2229 DCHECK_GE(header
.packet_sequence_number
, frame
.least_unacked
);
2230 const QuicPacketSequenceNumber least_unacked_delta
=
2231 header
.packet_sequence_number
- frame
.least_unacked
;
2232 const QuicPacketSequenceNumber length_shift
=
2233 header
.public_header
.sequence_number_length
* 8;
2234 if (!writer
->WriteUInt8(frame
.entropy_hash
)) {
2235 LOG(DFATAL
) << " hash failed";
2239 if (least_unacked_delta
>> length_shift
> 0) {
2240 LOG(DFATAL
) << "sequence_number_length "
2241 << header
.public_header
.sequence_number_length
2242 << " is too small for least_unacked_delta: "
2243 << least_unacked_delta
;
2246 if (!AppendPacketSequenceNumber(header
.public_header
.sequence_number_length
,
2247 least_unacked_delta
, writer
)) {
2248 LOG(DFATAL
) << " seq failed: "
2249 << header
.public_header
.sequence_number_length
;
2256 bool QuicFramer::AppendRstStreamFrame(
2257 const QuicRstStreamFrame
& frame
,
2258 QuicDataWriter
* writer
) {
2259 if (!writer
->WriteUInt32(frame
.stream_id
)) {
2263 if (!writer
->WriteUInt64(frame
.byte_offset
)) {
2267 uint32 error_code
= static_cast<uint32
>(frame
.error_code
);
2268 if (!writer
->WriteUInt32(error_code
)) {
2272 if (!writer
->WriteStringPiece16(frame
.error_details
)) {
2278 bool QuicFramer::AppendConnectionCloseFrame(
2279 const QuicConnectionCloseFrame
& frame
,
2280 QuicDataWriter
* writer
) {
2281 uint32 error_code
= static_cast<uint32
>(frame
.error_code
);
2282 if (!writer
->WriteUInt32(error_code
)) {
2285 if (!writer
->WriteStringPiece16(frame
.error_details
)) {
2291 bool QuicFramer::AppendGoAwayFrame(const QuicGoAwayFrame
& frame
,
2292 QuicDataWriter
* writer
) {
2293 uint32 error_code
= static_cast<uint32
>(frame
.error_code
);
2294 if (!writer
->WriteUInt32(error_code
)) {
2297 uint32 stream_id
= static_cast<uint32
>(frame
.last_good_stream_id
);
2298 if (!writer
->WriteUInt32(stream_id
)) {
2301 if (!writer
->WriteStringPiece16(frame
.reason_phrase
)) {
2307 bool QuicFramer::AppendWindowUpdateFrame(const QuicWindowUpdateFrame
& frame
,
2308 QuicDataWriter
* writer
) {
2309 uint32 stream_id
= static_cast<uint32
>(frame
.stream_id
);
2310 if (!writer
->WriteUInt32(stream_id
)) {
2313 if (!writer
->WriteUInt64(frame
.byte_offset
)) {
2319 bool QuicFramer::AppendBlockedFrame(const QuicBlockedFrame
& frame
,
2320 QuicDataWriter
* writer
) {
2321 uint32 stream_id
= static_cast<uint32
>(frame
.stream_id
);
2322 if (!writer
->WriteUInt32(stream_id
)) {
2328 bool QuicFramer::RaiseError(QuicErrorCode error
) {
2329 DVLOG(1) << "Error detail: " << detailed_error_
;
2331 visitor_
->OnError(this);
2332 reader_
.reset(NULL
);