Include all dupe types (event when value is zero) in scan stats.
[chromium-blink-merge.git] / net / quic / quic_framer.cc
blob26eb3140b1cc9556e22ef97853c1abf8c547b928
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 <stdint.h>
9 #include "base/basictypes.h"
10 #include "base/logging.h"
11 #include "base/stl_util.h"
12 #include "net/quic/crypto/crypto_framer.h"
13 #include "net/quic/crypto/crypto_handshake_message.h"
14 #include "net/quic/crypto/crypto_protocol.h"
15 #include "net/quic/crypto/quic_decrypter.h"
16 #include "net/quic/crypto/quic_encrypter.h"
17 #include "net/quic/quic_data_reader.h"
18 #include "net/quic/quic_data_writer.h"
19 #include "net/quic/quic_flags.h"
20 #include "net/quic/quic_socket_address_coder.h"
21 #include "net/quic/quic_utils.h"
23 using base::StringPiece;
24 using std::map;
25 using std::max;
26 using std::min;
27 using std::numeric_limits;
28 using std::string;
30 namespace net {
32 namespace {
34 // Mask to select the lowest 48 bits of a sequence number.
35 const QuicPacketSequenceNumber k6ByteSequenceNumberMask =
36 UINT64_C(0x0000FFFFFFFFFFFF);
37 const QuicPacketSequenceNumber k4ByteSequenceNumberMask =
38 UINT64_C(0x00000000FFFFFFFF);
39 const QuicPacketSequenceNumber k2ByteSequenceNumberMask =
40 UINT64_C(0x000000000000FFFF);
41 const QuicPacketSequenceNumber k1ByteSequenceNumberMask =
42 UINT64_C(0x00000000000000FF);
44 const QuicConnectionId k1ByteConnectionIdMask = UINT64_C(0x00000000000000FF);
45 const QuicConnectionId k4ByteConnectionIdMask = UINT64_C(0x00000000FFFFFFFF);
47 // Number of bits the sequence number length bits are shifted from the right
48 // edge of the public header.
49 const uint8 kPublicHeaderSequenceNumberShift = 4;
51 // New Frame Types, QUIC v. >= 10:
52 // There are two interpretations for the Frame Type byte in the QUIC protocol,
53 // resulting in two Frame Types: Special Frame Types and Regular Frame Types.
55 // Regular Frame Types use the Frame Type byte simply. Currently defined
56 // Regular Frame Types are:
57 // Padding : 0b 00000000 (0x00)
58 // ResetStream : 0b 00000001 (0x01)
59 // ConnectionClose : 0b 00000010 (0x02)
60 // GoAway : 0b 00000011 (0x03)
61 // WindowUpdate : 0b 00000100 (0x04)
62 // Blocked : 0b 00000101 (0x05)
64 // Special Frame Types encode both a Frame Type and corresponding flags
65 // all in the Frame Type byte. Currently defined Special Frame Types are:
66 // Stream : 0b 1xxxxxxx
67 // Ack : 0b 01xxxxxx
69 // Semantics of the flag bits above (the x bits) depends on the frame type.
71 // Masks to determine if the frame type is a special use
72 // and for specific special frame types.
73 const uint8 kQuicFrameTypeSpecialMask = 0xE0; // 0b 11100000
74 const uint8 kQuicFrameTypeStreamMask = 0x80;
75 const uint8 kQuicFrameTypeAckMask = 0x40;
77 // Stream frame relative shifts and masks for interpreting the stream flags.
78 // StreamID may be 1, 2, 3, or 4 bytes.
79 const uint8 kQuicStreamIdShift = 2;
80 const uint8 kQuicStreamIDLengthMask = 0x03;
82 // Offset may be 0, 2, 3, 4, 5, 6, 7, 8 bytes.
83 const uint8 kQuicStreamOffsetShift = 3;
84 const uint8 kQuicStreamOffsetMask = 0x07;
86 // Data length may be 0 or 2 bytes.
87 const uint8 kQuicStreamDataLengthShift = 1;
88 const uint8 kQuicStreamDataLengthMask = 0x01;
90 // Fin bit may be set or not.
91 const uint8 kQuicStreamFinShift = 1;
92 const uint8 kQuicStreamFinMask = 0x01;
94 // Sequence number size shift used in AckFrames.
95 const uint8 kQuicSequenceNumberLengthShift = 2;
97 // Acks may be truncated.
98 const uint8 kQuicAckTruncatedShift = 1;
99 const uint8 kQuicAckTruncatedMask = 0x01;
101 // Acks may not have any nacks.
102 const uint8 kQuicHasNacksMask = 0x01;
104 // Returns the absolute value of the difference between |a| and |b|.
105 QuicPacketSequenceNumber Delta(QuicPacketSequenceNumber a,
106 QuicPacketSequenceNumber b) {
107 // Since these are unsigned numbers, we can't just return abs(a - b)
108 if (a < b) {
109 return b - a;
111 return a - b;
114 QuicPacketSequenceNumber ClosestTo(QuicPacketSequenceNumber target,
115 QuicPacketSequenceNumber a,
116 QuicPacketSequenceNumber b) {
117 return (Delta(target, a) < Delta(target, b)) ? a : b;
120 QuicSequenceNumberLength ReadSequenceNumberLength(uint8 flags) {
121 switch (flags & PACKET_FLAGS_6BYTE_SEQUENCE) {
122 case PACKET_FLAGS_6BYTE_SEQUENCE:
123 return PACKET_6BYTE_SEQUENCE_NUMBER;
124 case PACKET_FLAGS_4BYTE_SEQUENCE:
125 return PACKET_4BYTE_SEQUENCE_NUMBER;
126 case PACKET_FLAGS_2BYTE_SEQUENCE:
127 return PACKET_2BYTE_SEQUENCE_NUMBER;
128 case PACKET_FLAGS_1BYTE_SEQUENCE:
129 return PACKET_1BYTE_SEQUENCE_NUMBER;
130 default:
131 LOG(DFATAL) << "Unreachable case statement.";
132 return PACKET_6BYTE_SEQUENCE_NUMBER;
136 } // namespace
138 bool QuicFramerVisitorInterface::OnWindowUpdateFrame(
139 const QuicWindowUpdateFrame& frame) {
140 return true;
143 bool QuicFramerVisitorInterface::OnBlockedFrame(const QuicBlockedFrame& frame) {
144 return true;
147 QuicFramer::QuicFramer(const QuicVersionVector& supported_versions,
148 QuicTime creation_time,
149 Perspective perspective)
150 : visitor_(nullptr),
151 entropy_calculator_(nullptr),
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 perspective_(perspective),
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(QuicEncrypter::Create(kNULL));
169 QuicFramer::~QuicFramer() {}
171 // static
172 size_t QuicFramer::GetMinStreamFrameSize(QuicStreamId stream_id,
173 QuicStreamOffset offset,
174 bool last_frame_in_packet,
175 InFecGroup is_in_fec_group) {
176 bool no_stream_frame_length = last_frame_in_packet &&
177 is_in_fec_group == NOT_IN_FEC_GROUP;
178 return kQuicFrameTypeSize + GetStreamIdSize(stream_id) +
179 GetStreamOffsetSize(offset) +
180 (no_stream_frame_length ? 0 : kQuicStreamPayloadLengthSize);
183 // static
184 size_t QuicFramer::GetMinAckFrameSize(
185 QuicSequenceNumberLength sequence_number_length,
186 QuicSequenceNumberLength largest_observed_length) {
187 return kQuicFrameTypeSize + kQuicEntropyHashSize +
188 largest_observed_length + kQuicDeltaTimeLargestObservedSize;
191 // static
192 size_t QuicFramer::GetStopWaitingFrameSize(
193 QuicSequenceNumberLength sequence_number_length) {
194 return kQuicFrameTypeSize + kQuicEntropyHashSize +
195 sequence_number_length;
198 // static
199 size_t QuicFramer::GetMinRstStreamFrameSize() {
200 return kQuicFrameTypeSize + kQuicMaxStreamIdSize +
201 kQuicMaxStreamOffsetSize + kQuicErrorCodeSize +
202 kQuicErrorDetailsLengthSize;
205 // static
206 size_t QuicFramer::GetRstStreamFrameSize() {
207 return kQuicFrameTypeSize + kQuicMaxStreamIdSize + kQuicMaxStreamOffsetSize +
208 kQuicErrorCodeSize;
211 // static
212 size_t QuicFramer::GetMinConnectionCloseFrameSize() {
213 return kQuicFrameTypeSize + kQuicErrorCodeSize + kQuicErrorDetailsLengthSize;
216 // static
217 size_t QuicFramer::GetMinGoAwayFrameSize() {
218 return kQuicFrameTypeSize + kQuicErrorCodeSize + kQuicErrorDetailsLengthSize +
219 kQuicMaxStreamIdSize;
222 // static
223 size_t QuicFramer::GetWindowUpdateFrameSize() {
224 return kQuicFrameTypeSize + kQuicMaxStreamIdSize + kQuicMaxStreamOffsetSize;
227 // static
228 size_t QuicFramer::GetBlockedFrameSize() {
229 return kQuicFrameTypeSize + kQuicMaxStreamIdSize;
232 // static
233 size_t QuicFramer::GetStreamIdSize(QuicStreamId stream_id) {
234 // Sizes are 1 through 4 bytes.
235 for (int i = 1; i <= 4; ++i) {
236 stream_id >>= 8;
237 if (stream_id == 0) {
238 return i;
241 LOG(DFATAL) << "Failed to determine StreamIDSize.";
242 return 4;
245 // static
246 size_t QuicFramer::GetStreamOffsetSize(QuicStreamOffset offset) {
247 // 0 is a special case.
248 if (offset == 0) {
249 return 0;
251 // 2 through 8 are the remaining sizes.
252 offset >>= 8;
253 for (int i = 2; i <= 8; ++i) {
254 offset >>= 8;
255 if (offset == 0) {
256 return i;
259 LOG(DFATAL) << "Failed to determine StreamOffsetSize.";
260 return 8;
263 // static
264 size_t QuicFramer::GetVersionNegotiationPacketSize(size_t number_versions) {
265 return kPublicFlagsSize + PACKET_8BYTE_CONNECTION_ID +
266 number_versions * kQuicVersionSize;
269 bool QuicFramer::IsSupportedVersion(const QuicVersion version) const {
270 for (size_t i = 0; i < supported_versions_.size(); ++i) {
271 if (version == supported_versions_[i]) {
272 return true;
275 return false;
278 size_t QuicFramer::GetSerializedFrameLength(
279 const QuicFrame& frame,
280 size_t free_bytes,
281 bool first_frame,
282 bool last_frame,
283 InFecGroup is_in_fec_group,
284 QuicSequenceNumberLength sequence_number_length) {
285 // Prevent a rare crash reported in b/19458523.
286 if (frame.stream_frame == nullptr) {
287 LOG(DFATAL) << "Cannot compute the length of a null frame. "
288 << "type:" << frame.type << "free_bytes:" << free_bytes
289 << " first_frame:" << first_frame
290 << " last_frame:" << last_frame
291 << " is_in_fec:" << is_in_fec_group
292 << " seq num length:" << sequence_number_length;
293 set_error(QUIC_INTERNAL_ERROR);
294 visitor_->OnError(this);
295 return false;
297 if (frame.type == PADDING_FRAME) {
298 // PADDING implies end of packet.
299 return free_bytes;
301 size_t frame_len =
302 ComputeFrameLength(frame, last_frame, is_in_fec_group,
303 sequence_number_length);
304 if (frame_len <= free_bytes) {
305 // Frame fits within packet. Note that acks may be truncated.
306 return frame_len;
308 // Only truncate the first frame in a packet, so if subsequent ones go
309 // over, stop including more frames.
310 if (!first_frame) {
311 return 0;
313 bool can_truncate = frame.type == ACK_FRAME &&
314 free_bytes >= GetMinAckFrameSize(PACKET_6BYTE_SEQUENCE_NUMBER,
315 PACKET_6BYTE_SEQUENCE_NUMBER);
316 if (can_truncate) {
317 // Truncate the frame so the packet will not exceed kMaxPacketSize.
318 // Note that we may not use every byte of the writer in this case.
319 DVLOG(1) << "Truncating large frame, free bytes: " << free_bytes;
320 return free_bytes;
322 if (!FLAGS_quic_allow_oversized_packets_for_test) {
323 return 0;
325 LOG(DFATAL) << "Packet size too small to fit frame.";
326 return frame_len;
329 QuicFramer::AckFrameInfo::AckFrameInfo() : max_delta(0) {}
331 QuicFramer::AckFrameInfo::~AckFrameInfo() {}
333 // static
334 QuicPacketEntropyHash QuicFramer::GetPacketEntropyHash(
335 const QuicPacketHeader& header) {
336 return header.entropy_flag << (header.packet_sequence_number % 8);
339 QuicPacket* QuicFramer::BuildDataPacket(const QuicPacketHeader& header,
340 const QuicFrames& frames,
341 char* buffer,
342 size_t packet_length) {
343 QuicDataWriter writer(packet_length, buffer);
344 if (!AppendPacketHeader(header, &writer)) {
345 LOG(DFATAL) << "AppendPacketHeader failed";
346 return nullptr;
349 size_t i = 0;
350 for (const QuicFrame& frame : frames) {
351 // Determine if we should write stream frame length in header.
352 const bool no_stream_frame_length =
353 (header.is_in_fec_group == NOT_IN_FEC_GROUP) &&
354 (i == frames.size() - 1);
355 if (!AppendTypeByte(frame, no_stream_frame_length, &writer)) {
356 LOG(DFATAL) << "AppendTypeByte failed";
357 return nullptr;
360 switch (frame.type) {
361 case PADDING_FRAME:
362 writer.WritePadding();
363 break;
364 case STREAM_FRAME:
365 if (!AppendStreamFrame(
366 *frame.stream_frame, no_stream_frame_length, &writer)) {
367 LOG(DFATAL) << "AppendStreamFrame failed";
368 return nullptr;
370 break;
371 case ACK_FRAME:
372 if (!AppendAckFrameAndTypeByte(
373 header, *frame.ack_frame, &writer)) {
374 LOG(DFATAL) << "AppendAckFrameAndTypeByte failed";
375 return nullptr;
377 break;
378 case STOP_WAITING_FRAME:
379 if (!AppendStopWaitingFrame(
380 header, *frame.stop_waiting_frame, &writer)) {
381 LOG(DFATAL) << "AppendStopWaitingFrame failed";
382 return nullptr;
384 break;
385 case PING_FRAME:
386 // Ping has no payload.
387 break;
388 case RST_STREAM_FRAME:
389 if (!AppendRstStreamFrame(*frame.rst_stream_frame, &writer)) {
390 LOG(DFATAL) << "AppendRstStreamFrame failed";
391 return nullptr;
393 break;
394 case CONNECTION_CLOSE_FRAME:
395 if (!AppendConnectionCloseFrame(
396 *frame.connection_close_frame, &writer)) {
397 LOG(DFATAL) << "AppendConnectionCloseFrame failed";
398 return nullptr;
400 break;
401 case GOAWAY_FRAME:
402 if (!AppendGoAwayFrame(*frame.goaway_frame, &writer)) {
403 LOG(DFATAL) << "AppendGoAwayFrame failed";
404 return nullptr;
406 break;
407 case WINDOW_UPDATE_FRAME:
408 if (!AppendWindowUpdateFrame(*frame.window_update_frame, &writer)) {
409 LOG(DFATAL) << "AppendWindowUpdateFrame failed";
410 return nullptr;
412 break;
413 case BLOCKED_FRAME:
414 if (!AppendBlockedFrame(*frame.blocked_frame, &writer)) {
415 LOG(DFATAL) << "AppendBlockedFrame failed";
416 return nullptr;
418 break;
419 default:
420 RaiseError(QUIC_INVALID_FRAME_DATA);
421 LOG(DFATAL) << "QUIC_INVALID_FRAME_DATA";
422 return nullptr;
424 ++i;
427 QuicPacket* packet =
428 new QuicPacket(writer.data(), writer.length(), false,
429 header.public_header.connection_id_length,
430 header.public_header.version_flag,
431 header.public_header.sequence_number_length);
433 return packet;
436 QuicPacket* QuicFramer::BuildFecPacket(const QuicPacketHeader& header,
437 const QuicFecData& fec) {
438 DCHECK_EQ(IN_FEC_GROUP, header.is_in_fec_group);
439 DCHECK_NE(0u, header.fec_group);
440 size_t len = GetPacketHeaderSize(header);
441 len += fec.redundancy.length();
443 scoped_ptr<char[]> buffer(new char[len]);
444 QuicDataWriter writer(len, buffer.get());
445 if (!AppendPacketHeader(header, &writer)) {
446 LOG(DFATAL) << "AppendPacketHeader failed";
447 return nullptr;
450 if (!writer.WriteBytes(fec.redundancy.data(), fec.redundancy.length())) {
451 LOG(DFATAL) << "Failed to add FEC";
452 return nullptr;
455 return new QuicPacket(buffer.release(), len, true,
456 header.public_header.connection_id_length,
457 header.public_header.version_flag,
458 header.public_header.sequence_number_length);
461 // static
462 QuicEncryptedPacket* QuicFramer::BuildPublicResetPacket(
463 const QuicPublicResetPacket& packet) {
464 DCHECK(packet.public_header.reset_flag);
466 CryptoHandshakeMessage reset;
467 reset.set_tag(kPRST);
468 reset.SetValue(kRNON, packet.nonce_proof);
469 reset.SetValue(kRSEQ, packet.rejected_sequence_number);
470 if (!packet.client_address.address().empty()) {
471 // packet.client_address is non-empty.
472 QuicSocketAddressCoder address_coder(packet.client_address);
473 string serialized_address = address_coder.Encode();
474 if (serialized_address.empty()) {
475 return nullptr;
477 reset.SetStringPiece(kCADR, serialized_address);
479 const QuicData& reset_serialized = reset.GetSerialized();
481 size_t len =
482 kPublicFlagsSize + PACKET_8BYTE_CONNECTION_ID + reset_serialized.length();
483 scoped_ptr<char[]> buffer(new char[len]);
484 QuicDataWriter writer(len, buffer.get());
486 uint8 flags = static_cast<uint8>(PACKET_PUBLIC_FLAGS_RST |
487 PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID);
488 if (!writer.WriteUInt8(flags)) {
489 return nullptr;
492 if (!writer.WriteUInt64(packet.public_header.connection_id)) {
493 return nullptr;
496 if (!writer.WriteBytes(reset_serialized.data(), reset_serialized.length())) {
497 return nullptr;
500 return new QuicEncryptedPacket(buffer.release(), len, true);
503 QuicEncryptedPacket* QuicFramer::BuildVersionNegotiationPacket(
504 const QuicPacketPublicHeader& header,
505 const QuicVersionVector& supported_versions) {
506 DCHECK(header.version_flag);
507 size_t len = GetVersionNegotiationPacketSize(supported_versions.size());
508 scoped_ptr<char[]> buffer(new char[len]);
509 QuicDataWriter writer(len, buffer.get());
511 uint8 flags = static_cast<uint8>(PACKET_PUBLIC_FLAGS_VERSION |
512 PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID);
513 if (!writer.WriteUInt8(flags)) {
514 return nullptr;
517 if (!writer.WriteUInt64(header.connection_id)) {
518 return nullptr;
521 for (size_t i = 0; i < supported_versions.size(); ++i) {
522 if (!writer.WriteUInt32(QuicVersionToQuicTag(supported_versions[i]))) {
523 return nullptr;
527 return new QuicEncryptedPacket(buffer.release(), len, true);
530 bool QuicFramer::ProcessPacket(const QuicEncryptedPacket& packet) {
531 DCHECK(!reader_.get());
532 reader_.reset(new QuicDataReader(packet.data(), packet.length()));
534 visitor_->OnPacket();
536 // First parse the public header.
537 QuicPacketPublicHeader public_header;
538 if (!ProcessPublicHeader(&public_header)) {
539 DLOG(WARNING) << "Unable to process public header.";
540 DCHECK_NE("", detailed_error_);
541 return RaiseError(QUIC_INVALID_PACKET_HEADER);
544 if (!visitor_->OnUnauthenticatedPublicHeader(public_header)) {
545 // The visitor suppresses further processing of the packet.
546 reader_.reset(nullptr);
547 return true;
550 if (perspective_ == Perspective::IS_SERVER && public_header.version_flag &&
551 public_header.versions[0] != quic_version_) {
552 if (!visitor_->OnProtocolVersionMismatch(public_header.versions[0])) {
553 reader_.reset(nullptr);
554 return true;
558 bool rv;
559 if (perspective_ == Perspective::IS_CLIENT && public_header.version_flag) {
560 rv = ProcessVersionNegotiationPacket(&public_header);
561 } else if (public_header.reset_flag) {
562 rv = ProcessPublicResetPacket(public_header);
563 } else if (packet.length() <= kMaxPacketSize) {
564 char buffer[kMaxPacketSize];
565 rv = ProcessDataPacket(public_header, packet, buffer, kMaxPacketSize);
566 } else {
567 scoped_ptr<char[]> large_buffer(new char[packet.length()]);
568 rv = ProcessDataPacket(public_header, packet, large_buffer.get(),
569 packet.length());
570 LOG_IF(DFATAL, rv) << "QUIC should never successfully process packets "
571 << "larger than kMaxPacketSize. packet size:"
572 << packet.length();
575 reader_.reset(nullptr);
576 return rv;
579 bool QuicFramer::ProcessVersionNegotiationPacket(
580 QuicPacketPublicHeader* public_header) {
581 DCHECK_EQ(Perspective::IS_CLIENT, perspective_);
582 // Try reading at least once to raise error if the packet is invalid.
583 do {
584 QuicTag version;
585 if (!reader_->ReadBytes(&version, kQuicVersionSize)) {
586 set_detailed_error("Unable to read supported version in negotiation.");
587 return RaiseError(QUIC_INVALID_VERSION_NEGOTIATION_PACKET);
589 public_header->versions.push_back(QuicTagToQuicVersion(version));
590 } while (!reader_->IsDoneReading());
592 visitor_->OnVersionNegotiationPacket(*public_header);
593 return true;
596 bool QuicFramer::ProcessDataPacket(const QuicPacketPublicHeader& public_header,
597 const QuicEncryptedPacket& packet,
598 char* decrypted_buffer,
599 size_t buffer_length) {
600 QuicPacketHeader header(public_header);
601 if (!ProcessPacketHeader(&header, packet, decrypted_buffer, buffer_length)) {
602 DLOG(WARNING) << "Unable to process packet header. Stopping parsing.";
603 return false;
606 if (!visitor_->OnPacketHeader(header)) {
607 // The visitor suppresses further processing of the packet.
608 return true;
611 if (packet.length() > kMaxPacketSize) {
612 DLOG(WARNING) << "Packet too large: " << packet.length();
613 return RaiseError(QUIC_PACKET_TOO_LARGE);
616 // Handle the payload.
617 if (!header.fec_flag) {
618 if (header.is_in_fec_group == IN_FEC_GROUP) {
619 StringPiece payload = reader_->PeekRemainingPayload();
620 visitor_->OnFecProtectedPayload(payload);
622 if (!ProcessFrameData(header)) {
623 DCHECK_NE(QUIC_NO_ERROR, error_); // ProcessFrameData sets the error.
624 DLOG(WARNING) << "Unable to process frame data.";
625 return false;
627 } else {
628 QuicFecData fec_data;
629 fec_data.fec_group = header.fec_group;
630 fec_data.redundancy = reader_->ReadRemainingPayload();
631 visitor_->OnFecData(fec_data);
634 visitor_->OnPacketComplete();
635 return true;
638 bool QuicFramer::ProcessPublicResetPacket(
639 const QuicPacketPublicHeader& public_header) {
640 QuicPublicResetPacket packet(public_header);
642 scoped_ptr<CryptoHandshakeMessage> reset(
643 CryptoFramer::ParseMessage(reader_->ReadRemainingPayload()));
644 if (!reset.get()) {
645 set_detailed_error("Unable to read reset message.");
646 return RaiseError(QUIC_INVALID_PUBLIC_RST_PACKET);
648 if (reset->tag() != kPRST) {
649 set_detailed_error("Incorrect message tag.");
650 return RaiseError(QUIC_INVALID_PUBLIC_RST_PACKET);
653 if (reset->GetUint64(kRNON, &packet.nonce_proof) != QUIC_NO_ERROR) {
654 set_detailed_error("Unable to read nonce proof.");
655 return RaiseError(QUIC_INVALID_PUBLIC_RST_PACKET);
657 // TODO(satyamshekhar): validate nonce to protect against DoS.
659 if (reset->GetUint64(kRSEQ, &packet.rejected_sequence_number) !=
660 QUIC_NO_ERROR) {
661 set_detailed_error("Unable to read rejected sequence number.");
662 return RaiseError(QUIC_INVALID_PUBLIC_RST_PACKET);
665 StringPiece address;
666 if (reset->GetStringPiece(kCADR, &address)) {
667 QuicSocketAddressCoder address_coder;
668 if (address_coder.Decode(address.data(), address.length())) {
669 packet.client_address = IPEndPoint(address_coder.ip(),
670 address_coder.port());
674 visitor_->OnPublicResetPacket(packet);
675 return true;
678 bool QuicFramer::ProcessRevivedPacket(QuicPacketHeader* header,
679 StringPiece payload) {
680 DCHECK(!reader_.get());
682 visitor_->OnRevivedPacket();
684 header->entropy_hash = GetPacketEntropyHash(*header);
686 if (!visitor_->OnPacketHeader(*header)) {
687 return true;
690 if (payload.length() > kMaxPacketSize) {
691 set_detailed_error("Revived packet too large.");
692 return RaiseError(QUIC_PACKET_TOO_LARGE);
695 reader_.reset(new QuicDataReader(payload.data(), payload.length()));
696 if (!ProcessFrameData(*header)) {
697 DCHECK_NE(QUIC_NO_ERROR, error_); // ProcessFrameData sets the error.
698 DLOG(WARNING) << "Unable to process frame data.";
699 return false;
702 visitor_->OnPacketComplete();
703 reader_.reset(nullptr);
704 return true;
707 bool QuicFramer::AppendPacketHeader(const QuicPacketHeader& header,
708 QuicDataWriter* writer) {
709 DVLOG(1) << "Appending header: " << header;
710 DCHECK(header.fec_group > 0 || header.is_in_fec_group == NOT_IN_FEC_GROUP);
711 uint8 public_flags = 0;
712 if (header.public_header.reset_flag) {
713 public_flags |= PACKET_PUBLIC_FLAGS_RST;
715 if (header.public_header.version_flag) {
716 public_flags |= PACKET_PUBLIC_FLAGS_VERSION;
719 public_flags |=
720 GetSequenceNumberFlags(header.public_header.sequence_number_length)
721 << kPublicHeaderSequenceNumberShift;
723 switch (header.public_header.connection_id_length) {
724 case PACKET_0BYTE_CONNECTION_ID:
725 if (!writer->WriteUInt8(
726 public_flags | PACKET_PUBLIC_FLAGS_0BYTE_CONNECTION_ID)) {
727 return false;
729 break;
730 case PACKET_1BYTE_CONNECTION_ID:
731 if (!writer->WriteUInt8(
732 public_flags | PACKET_PUBLIC_FLAGS_1BYTE_CONNECTION_ID)) {
733 return false;
735 if (!writer->WriteUInt8(
736 header.public_header.connection_id & k1ByteConnectionIdMask)) {
737 return false;
739 break;
740 case PACKET_4BYTE_CONNECTION_ID:
741 if (!writer->WriteUInt8(
742 public_flags | PACKET_PUBLIC_FLAGS_4BYTE_CONNECTION_ID)) {
743 return false;
745 if (!writer->WriteUInt32(
746 header.public_header.connection_id & k4ByteConnectionIdMask)) {
747 return false;
749 break;
750 case PACKET_8BYTE_CONNECTION_ID:
751 if (!writer->WriteUInt8(
752 public_flags | PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID)) {
753 return false;
755 if (!writer->WriteUInt64(header.public_header.connection_id)) {
756 return false;
758 break;
760 last_serialized_connection_id_ = header.public_header.connection_id;
762 if (header.public_header.version_flag) {
763 DCHECK_EQ(Perspective::IS_CLIENT, perspective_);
764 QuicTag tag = QuicVersionToQuicTag(quic_version_);
765 writer->WriteUInt32(tag);
766 DVLOG(1) << "version = " << quic_version_ << ", tag = '"
767 << QuicUtils::TagToString(tag) << "'";
770 if (!AppendPacketSequenceNumber(header.public_header.sequence_number_length,
771 header.packet_sequence_number, writer)) {
772 return false;
775 uint8 private_flags = 0;
776 if (header.entropy_flag) {
777 private_flags |= PACKET_PRIVATE_FLAGS_ENTROPY;
779 if (header.is_in_fec_group == IN_FEC_GROUP) {
780 private_flags |= PACKET_PRIVATE_FLAGS_FEC_GROUP;
782 if (header.fec_flag) {
783 private_flags |= PACKET_PRIVATE_FLAGS_FEC;
785 if (!writer->WriteUInt8(private_flags)) {
786 return false;
789 // The FEC group number is the sequence number of the first fec
790 // protected packet, or 0 if this packet is not protected.
791 if (header.is_in_fec_group == IN_FEC_GROUP) {
792 DCHECK_LE(header.fec_group, header.packet_sequence_number);
793 DCHECK_LT(header.packet_sequence_number - header.fec_group, 255u);
794 // Offset from the current packet sequence number to the first fec
795 // protected packet.
796 uint8 first_fec_protected_packet_offset =
797 static_cast<uint8>(header.packet_sequence_number - header.fec_group);
798 if (!writer->WriteBytes(&first_fec_protected_packet_offset, 1)) {
799 return false;
803 return true;
806 const QuicTime::Delta QuicFramer::CalculateTimestampFromWire(
807 uint32 time_delta_us) {
808 // The new time_delta might have wrapped to the next epoch, or it
809 // might have reverse wrapped to the previous epoch, or it might
810 // remain in the same epoch. Select the time closest to the previous
811 // time.
813 // epoch_delta is the delta between epochs. A delta is 4 bytes of
814 // microseconds.
815 const uint64 epoch_delta = UINT64_C(1) << 32;
816 uint64 epoch = last_timestamp_.ToMicroseconds() & ~(epoch_delta - 1);
817 // Wrapping is safe here because a wrapped value will not be ClosestTo below.
818 uint64 prev_epoch = epoch - epoch_delta;
819 uint64 next_epoch = epoch + epoch_delta;
821 uint64 time = ClosestTo(last_timestamp_.ToMicroseconds(),
822 epoch + time_delta_us,
823 ClosestTo(last_timestamp_.ToMicroseconds(),
824 prev_epoch + time_delta_us,
825 next_epoch + time_delta_us));
827 return QuicTime::Delta::FromMicroseconds(time);
830 QuicPacketSequenceNumber QuicFramer::CalculatePacketSequenceNumberFromWire(
831 QuicSequenceNumberLength sequence_number_length,
832 QuicPacketSequenceNumber packet_sequence_number) const {
833 // The new sequence number might have wrapped to the next epoch, or
834 // it might have reverse wrapped to the previous epoch, or it might
835 // remain in the same epoch. Select the sequence number closest to the
836 // next expected sequence number, the previous sequence number plus 1.
838 // epoch_delta is the delta between epochs the sequence number was serialized
839 // with, so the correct value is likely the same epoch as the last sequence
840 // number or an adjacent epoch.
841 const QuicPacketSequenceNumber epoch_delta =
842 UINT64_C(1) << (8 * sequence_number_length);
843 QuicPacketSequenceNumber next_sequence_number = last_sequence_number_ + 1;
844 QuicPacketSequenceNumber epoch = last_sequence_number_ & ~(epoch_delta - 1);
845 QuicPacketSequenceNumber prev_epoch = epoch - epoch_delta;
846 QuicPacketSequenceNumber next_epoch = epoch + epoch_delta;
848 return ClosestTo(next_sequence_number,
849 epoch + packet_sequence_number,
850 ClosestTo(next_sequence_number,
851 prev_epoch + packet_sequence_number,
852 next_epoch + packet_sequence_number));
855 bool QuicFramer::ProcessPublicHeader(
856 QuicPacketPublicHeader* public_header) {
857 uint8 public_flags;
858 if (!reader_->ReadBytes(&public_flags, 1)) {
859 set_detailed_error("Unable to read public flags.");
860 return false;
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.");
870 return false;
873 if (public_header->reset_flag && public_header->version_flag) {
874 set_detailed_error("Got version flag in reset packet");
875 return false;
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.");
882 return false;
884 public_header->connection_id_length = PACKET_8BYTE_CONNECTION_ID;
885 break;
886 case PACKET_PUBLIC_FLAGS_4BYTE_CONNECTION_ID:
887 // If the connection_id is truncated, expect to read the last serialized
888 // connection_id.
889 if (!reader_->ReadBytes(&public_header->connection_id,
890 PACKET_4BYTE_CONNECTION_ID)) {
891 set_detailed_error("Unable to read ConnectionId.");
892 return false;
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.");
899 return false;
901 public_header->connection_id_length = PACKET_4BYTE_CONNECTION_ID;
902 public_header->connection_id = last_serialized_connection_id_;
903 break;
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.");
908 return false;
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.");
915 return false;
917 public_header->connection_id_length = PACKET_1BYTE_CONNECTION_ID;
918 public_header->connection_id = last_serialized_connection_id_;
919 break;
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_;
923 break;
926 public_header->sequence_number_length =
927 ReadSequenceNumberLength(
928 public_flags >> kPublicHeaderSequenceNumberShift);
930 // Read the version only if the packet is from the client.
931 // version flag from the server means version negotiation packet.
932 if (public_header->version_flag && perspective_ == Perspective::IS_SERVER) {
933 QuicTag version_tag;
934 if (!reader_->ReadUInt32(&version_tag)) {
935 set_detailed_error("Unable to read protocol version.");
936 return false;
939 // If the version from the new packet is the same as the version of this
940 // framer, then the public flags should be set to something we understand.
941 // If not, this raises an error.
942 QuicVersion version = QuicTagToQuicVersion(version_tag);
943 if (version == quic_version_ && public_flags > PACKET_PUBLIC_FLAGS_MAX) {
944 set_detailed_error("Illegal public flags value.");
945 return false;
947 public_header->versions.push_back(version);
949 return true;
952 // static
953 QuicSequenceNumberLength QuicFramer::GetMinSequenceNumberLength(
954 QuicPacketSequenceNumber sequence_number) {
955 if (sequence_number < 1 << (PACKET_1BYTE_SEQUENCE_NUMBER * 8)) {
956 return PACKET_1BYTE_SEQUENCE_NUMBER;
957 } else if (sequence_number < 1 << (PACKET_2BYTE_SEQUENCE_NUMBER * 8)) {
958 return PACKET_2BYTE_SEQUENCE_NUMBER;
959 } else if (sequence_number <
960 UINT64_C(1) << (PACKET_4BYTE_SEQUENCE_NUMBER * 8)) {
961 return PACKET_4BYTE_SEQUENCE_NUMBER;
962 } else {
963 return PACKET_6BYTE_SEQUENCE_NUMBER;
967 // static
968 uint8 QuicFramer::GetSequenceNumberFlags(
969 QuicSequenceNumberLength sequence_number_length) {
970 switch (sequence_number_length) {
971 case PACKET_1BYTE_SEQUENCE_NUMBER:
972 return PACKET_FLAGS_1BYTE_SEQUENCE;
973 case PACKET_2BYTE_SEQUENCE_NUMBER:
974 return PACKET_FLAGS_2BYTE_SEQUENCE;
975 case PACKET_4BYTE_SEQUENCE_NUMBER:
976 return PACKET_FLAGS_4BYTE_SEQUENCE;
977 case PACKET_6BYTE_SEQUENCE_NUMBER:
978 return PACKET_FLAGS_6BYTE_SEQUENCE;
979 default:
980 LOG(DFATAL) << "Unreachable case statement.";
981 return PACKET_FLAGS_6BYTE_SEQUENCE;
985 // static
986 QuicFramer::AckFrameInfo QuicFramer::GetAckFrameInfo(
987 const QuicAckFrame& frame) {
988 AckFrameInfo ack_info;
989 if (frame.missing_packets.empty()) {
990 return ack_info;
992 DCHECK_GE(frame.largest_observed, *frame.missing_packets.rbegin());
993 size_t cur_range_length = 0;
994 SequenceNumberSet::const_iterator iter = frame.missing_packets.begin();
995 QuicPacketSequenceNumber last_missing = *iter;
996 ++iter;
997 for (; iter != frame.missing_packets.end(); ++iter) {
998 if (cur_range_length < numeric_limits<uint8>::max() &&
999 *iter == (last_missing + 1)) {
1000 ++cur_range_length;
1001 } else {
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);
1015 return ack_info;
1018 bool QuicFramer::ProcessPacketHeader(QuicPacketHeader* header,
1019 const QuicEncryptedPacket& packet,
1020 char* decrypted_buffer,
1021 size_t buffer_length) {
1022 if (!ProcessPacketSequenceNumber(header->public_header.sequence_number_length,
1023 &header->packet_sequence_number)) {
1024 set_detailed_error("Unable to read sequence number.");
1025 return RaiseError(QUIC_INVALID_PACKET_HEADER);
1028 if (header->packet_sequence_number == 0u) {
1029 set_detailed_error("Packet sequence numbers cannot be 0.");
1030 return RaiseError(QUIC_INVALID_PACKET_HEADER);
1033 if (!visitor_->OnUnauthenticatedHeader(*header)) {
1034 return false;
1037 if (!DecryptPayload(*header, packet, decrypted_buffer, buffer_length)) {
1038 set_detailed_error("Unable to decrypt payload.");
1039 return RaiseError(QUIC_DECRYPTION_FAILURE);
1042 uint8 private_flags;
1043 if (!reader_->ReadBytes(&private_flags, 1)) {
1044 set_detailed_error("Unable to read private flags.");
1045 return RaiseError(QUIC_INVALID_PACKET_HEADER);
1048 if (private_flags > PACKET_PRIVATE_FLAGS_MAX) {
1049 set_detailed_error("Illegal private flags value.");
1050 return RaiseError(QUIC_INVALID_PACKET_HEADER);
1053 header->entropy_flag = (private_flags & PACKET_PRIVATE_FLAGS_ENTROPY) != 0;
1054 header->fec_flag = (private_flags & PACKET_PRIVATE_FLAGS_FEC) != 0;
1056 if ((private_flags & PACKET_PRIVATE_FLAGS_FEC_GROUP) != 0) {
1057 header->is_in_fec_group = IN_FEC_GROUP;
1058 uint8 first_fec_protected_packet_offset;
1059 if (!reader_->ReadBytes(&first_fec_protected_packet_offset, 1)) {
1060 set_detailed_error("Unable to read first fec protected packet offset.");
1061 return RaiseError(QUIC_INVALID_PACKET_HEADER);
1063 if (first_fec_protected_packet_offset >= header->packet_sequence_number) {
1064 set_detailed_error("First fec protected packet offset must be less "
1065 "than the sequence number.");
1066 return RaiseError(QUIC_INVALID_PACKET_HEADER);
1068 header->fec_group =
1069 header->packet_sequence_number - first_fec_protected_packet_offset;
1072 header->entropy_hash = GetPacketEntropyHash(*header);
1073 // Set the last sequence number after we have decrypted the packet
1074 // so we are confident is not attacker controlled.
1075 last_sequence_number_ = header->packet_sequence_number;
1076 return true;
1079 bool QuicFramer::ProcessPacketSequenceNumber(
1080 QuicSequenceNumberLength sequence_number_length,
1081 QuicPacketSequenceNumber* sequence_number) {
1082 QuicPacketSequenceNumber wire_sequence_number = 0u;
1083 if (!reader_->ReadBytes(&wire_sequence_number, sequence_number_length)) {
1084 return false;
1087 // TODO(ianswett): Explore the usefulness of trying multiple sequence numbers
1088 // in case the first guess is incorrect.
1089 *sequence_number =
1090 CalculatePacketSequenceNumberFromWire(sequence_number_length,
1091 wire_sequence_number);
1092 return true;
1095 bool QuicFramer::ProcessFrameData(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()) {
1101 uint8 frame_type;
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) {
1108 // Stream Frame
1109 if (frame_type & kQuicFrameTypeStreamMask) {
1110 QuicStreamFrame frame;
1111 if (!ProcessStreamFrame(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.
1117 return true;
1119 continue;
1122 // Ack Frame
1123 if (frame_type & kQuicFrameTypeAckMask) {
1124 QuicAckFrame frame;
1125 if (!ProcessAckFrame(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.
1131 return true;
1133 continue;
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) {
1145 case PADDING_FRAME:
1146 // We're done with the packet.
1147 return true;
1149 case RST_STREAM_FRAME: {
1150 QuicRstStreamFrame frame;
1151 if (!ProcessRstStreamFrame(&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.
1157 return true;
1159 continue;
1162 case CONNECTION_CLOSE_FRAME: {
1163 QuicConnectionCloseFrame frame;
1164 if (!ProcessConnectionCloseFrame(&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.
1171 return true;
1173 continue;
1176 case GOAWAY_FRAME: {
1177 QuicGoAwayFrame goaway_frame;
1178 if (!ProcessGoAwayFrame(&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.
1184 return true;
1186 continue;
1189 case WINDOW_UPDATE_FRAME: {
1190 QuicWindowUpdateFrame window_update_frame;
1191 if (!ProcessWindowUpdateFrame(&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.
1197 return true;
1199 continue;
1202 case BLOCKED_FRAME: {
1203 QuicBlockedFrame blocked_frame;
1204 if (!ProcessBlockedFrame(&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.
1210 return true;
1212 continue;
1215 case STOP_WAITING_FRAME: {
1216 QuicStopWaitingFrame stop_waiting_frame;
1217 if (!ProcessStopWaitingFrame(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.
1223 return true;
1225 continue;
1227 case PING_FRAME: {
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.
1233 return true;
1235 continue;
1238 default:
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);
1246 return true;
1249 bool QuicFramer::ProcessStreamFrame(uint8 frame_type,
1250 QuicStreamFrame* frame) {
1251 uint8 stream_flags = frame_type;
1253 stream_flags &= ~kQuicFrameTypeStreamMask;
1255 // Read from right to left: StreamID, Offset, Data Length, Fin.
1256 const uint8 stream_id_length = (stream_flags & kQuicStreamIDLengthMask) + 1;
1257 stream_flags >>= kQuicStreamIdShift;
1259 uint8 offset_length = (stream_flags & kQuicStreamOffsetMask);
1260 // There is no encoding for 1 byte, only 0 and 2 through 8.
1261 if (offset_length > 0) {
1262 offset_length += 1;
1264 stream_flags >>= kQuicStreamOffsetShift;
1266 bool has_data_length =
1267 (stream_flags & kQuicStreamDataLengthMask) == kQuicStreamDataLengthMask;
1268 stream_flags >>= kQuicStreamDataLengthShift;
1270 frame->fin = (stream_flags & kQuicStreamFinMask) == kQuicStreamFinShift;
1272 frame->stream_id = 0;
1273 if (!reader_->ReadBytes(&frame->stream_id, stream_id_length)) {
1274 set_detailed_error("Unable to read stream_id.");
1275 return false;
1278 frame->offset = 0;
1279 if (!reader_->ReadBytes(&frame->offset, offset_length)) {
1280 set_detailed_error("Unable to read offset.");
1281 return false;
1284 if (has_data_length) {
1285 if (!reader_->ReadStringPiece16(&frame->data)) {
1286 set_detailed_error("Unable to read frame data.");
1287 return false;
1289 } else {
1290 if (!reader_->ReadStringPiece(&frame->data, reader_->BytesRemaining())) {
1291 set_detailed_error("Unable to read frame data.");
1292 return false;
1296 return true;
1299 bool QuicFramer::ProcessAckFrame(uint8 frame_type, QuicAckFrame* ack_frame) {
1300 // Determine the three lengths from the frame type: largest observed length,
1301 // missing sequence number length, and missing range length.
1302 const QuicSequenceNumberLength missing_sequence_number_length =
1303 ReadSequenceNumberLength(frame_type);
1304 frame_type >>= kQuicSequenceNumberLengthShift;
1305 const QuicSequenceNumberLength largest_observed_sequence_number_length =
1306 ReadSequenceNumberLength(frame_type);
1307 frame_type >>= kQuicSequenceNumberLengthShift;
1308 ack_frame->is_truncated = frame_type & kQuicAckTruncatedMask;
1309 frame_type >>= kQuicAckTruncatedShift;
1310 bool has_nacks = frame_type & kQuicHasNacksMask;
1312 if (!reader_->ReadBytes(&ack_frame->entropy_hash, 1)) {
1313 set_detailed_error("Unable to read entropy hash for received packets.");
1314 return false;
1317 if (!reader_->ReadBytes(&ack_frame->largest_observed,
1318 largest_observed_sequence_number_length)) {
1319 set_detailed_error("Unable to read largest observed.");
1320 return false;
1323 uint64 delta_time_largest_observed_us;
1324 if (!reader_->ReadUFloat16(&delta_time_largest_observed_us)) {
1325 set_detailed_error("Unable to read delta time largest observed.");
1326 return false;
1329 if (delta_time_largest_observed_us == kUFloat16MaxValue) {
1330 ack_frame->delta_time_largest_observed = QuicTime::Delta::Infinite();
1331 } else {
1332 ack_frame->delta_time_largest_observed =
1333 QuicTime::Delta::FromMicroseconds(delta_time_largest_observed_us);
1336 if (!ProcessTimestampsInAckFrame(ack_frame)) {
1337 return false;
1340 if (!has_nacks) {
1341 return true;
1344 uint8 num_missing_ranges;
1345 if (!reader_->ReadBytes(&num_missing_ranges, 1)) {
1346 set_detailed_error("Unable to read num missing packet ranges.");
1347 return false;
1350 QuicPacketSequenceNumber last_sequence_number = ack_frame->largest_observed;
1351 for (size_t i = 0; i < num_missing_ranges; ++i) {
1352 QuicPacketSequenceNumber missing_delta = 0;
1353 if (!reader_->ReadBytes(&missing_delta, missing_sequence_number_length)) {
1354 set_detailed_error("Unable to read missing sequence number delta.");
1355 return false;
1357 last_sequence_number -= missing_delta;
1358 QuicPacketSequenceNumber range_length = 0;
1359 if (!reader_->ReadBytes(&range_length, PACKET_1BYTE_SEQUENCE_NUMBER)) {
1360 set_detailed_error("Unable to read missing sequence number range.");
1361 return false;
1363 for (size_t j = 0; j <= range_length; ++j) {
1364 ack_frame->missing_packets.insert(last_sequence_number - j);
1366 // Subtract an extra 1 to ensure ranges are represented efficiently and
1367 // can't overlap by 1 sequence number. This allows a missing_delta of 0
1368 // to represent an adjacent nack range.
1369 last_sequence_number -= (range_length + 1);
1372 // Parse the revived packets list.
1373 uint8 num_revived_packets;
1374 if (!reader_->ReadBytes(&num_revived_packets, 1)) {
1375 set_detailed_error("Unable to read num revived packets.");
1376 return false;
1379 for (size_t i = 0; i < num_revived_packets; ++i) {
1380 QuicPacketSequenceNumber revived_packet = 0;
1381 if (!reader_->ReadBytes(&revived_packet,
1382 largest_observed_sequence_number_length)) {
1383 set_detailed_error("Unable to read revived packet.");
1384 return false;
1387 ack_frame->revived_packets.insert(revived_packet);
1390 return true;
1393 bool QuicFramer::ProcessTimestampsInAckFrame(QuicAckFrame* ack_frame) {
1394 if (ack_frame->is_truncated) {
1395 return true;
1397 uint8 num_received_packets;
1398 if (!reader_->ReadBytes(&num_received_packets, 1)) {
1399 set_detailed_error("Unable to read num received packets.");
1400 return false;
1403 if (num_received_packets > 0) {
1404 uint8 delta_from_largest_observed;
1405 if (!reader_->ReadBytes(&delta_from_largest_observed,
1406 PACKET_1BYTE_SEQUENCE_NUMBER)) {
1407 set_detailed_error("Unable to read sequence delta in received packets.");
1408 return false;
1410 QuicPacketSequenceNumber seq_num =
1411 ack_frame->largest_observed - delta_from_largest_observed;
1413 // Time delta from the framer creation.
1414 uint32 time_delta_us;
1415 if (!reader_->ReadBytes(&time_delta_us, sizeof(time_delta_us))) {
1416 set_detailed_error("Unable to read time delta in received packets.");
1417 return false;
1420 last_timestamp_ = CalculateTimestampFromWire(time_delta_us);
1422 ack_frame->received_packet_times.push_back(
1423 std::make_pair(seq_num, creation_time_.Add(last_timestamp_)));
1425 for (uint8 i = 1; i < num_received_packets; ++i) {
1426 if (!reader_->ReadBytes(&delta_from_largest_observed,
1427 PACKET_1BYTE_SEQUENCE_NUMBER)) {
1428 set_detailed_error(
1429 "Unable to read sequence delta in received packets.");
1430 return false;
1432 seq_num = ack_frame->largest_observed - delta_from_largest_observed;
1434 // Time delta from the previous timestamp.
1435 uint64 incremental_time_delta_us;
1436 if (!reader_->ReadUFloat16(&incremental_time_delta_us)) {
1437 set_detailed_error(
1438 "Unable to read incremental time delta in received packets.");
1439 return false;
1442 last_timestamp_ = last_timestamp_.Add(
1443 QuicTime::Delta::FromMicroseconds(incremental_time_delta_us));
1444 ack_frame->received_packet_times.push_back(
1445 std::make_pair(seq_num, creation_time_.Add(last_timestamp_)));
1448 return true;
1451 bool QuicFramer::ProcessStopWaitingFrame(const QuicPacketHeader& header,
1452 QuicStopWaitingFrame* stop_waiting) {
1453 if (!reader_->ReadBytes(&stop_waiting->entropy_hash, 1)) {
1454 set_detailed_error("Unable to read entropy hash for sent packets.");
1455 return false;
1458 QuicPacketSequenceNumber least_unacked_delta = 0;
1459 if (!reader_->ReadBytes(&least_unacked_delta,
1460 header.public_header.sequence_number_length)) {
1461 set_detailed_error("Unable to read least unacked delta.");
1462 return false;
1464 DCHECK_GE(header.packet_sequence_number, least_unacked_delta);
1465 stop_waiting->least_unacked =
1466 header.packet_sequence_number - least_unacked_delta;
1468 return true;
1471 bool QuicFramer::ProcessRstStreamFrame(QuicRstStreamFrame* frame) {
1472 if (!reader_->ReadUInt32(&frame->stream_id)) {
1473 set_detailed_error("Unable to read stream_id.");
1474 return false;
1477 if (!reader_->ReadUInt64(&frame->byte_offset)) {
1478 set_detailed_error("Unable to read rst stream sent byte offset.");
1479 return false;
1482 uint32 error_code;
1483 if (!reader_->ReadUInt32(&error_code)) {
1484 set_detailed_error("Unable to read rst stream error code.");
1485 return false;
1488 if (error_code >= QUIC_STREAM_LAST_ERROR) {
1489 set_detailed_error("Invalid rst stream error code.");
1490 return false;
1493 frame->error_code = static_cast<QuicRstStreamErrorCode>(error_code);
1494 if (quic_version_ <= QUIC_VERSION_24) {
1495 StringPiece error_details;
1496 if (!reader_->ReadStringPiece16(&error_details)) {
1497 set_detailed_error("Unable to read rst stream error details.");
1498 return false;
1500 frame->error_details = error_details.as_string();
1503 return true;
1506 bool QuicFramer::ProcessConnectionCloseFrame(QuicConnectionCloseFrame* frame) {
1507 uint32 error_code;
1508 if (!reader_->ReadUInt32(&error_code)) {
1509 set_detailed_error("Unable to read connection close error code.");
1510 return false;
1513 if (error_code >= QUIC_LAST_ERROR) {
1514 set_detailed_error("Invalid error code.");
1515 return false;
1518 frame->error_code = static_cast<QuicErrorCode>(error_code);
1520 StringPiece error_details;
1521 if (!reader_->ReadStringPiece16(&error_details)) {
1522 set_detailed_error("Unable to read connection close error details.");
1523 return false;
1525 frame->error_details = error_details.as_string();
1527 return true;
1530 bool QuicFramer::ProcessGoAwayFrame(QuicGoAwayFrame* frame) {
1531 uint32 error_code;
1532 if (!reader_->ReadUInt32(&error_code)) {
1533 set_detailed_error("Unable to read go away error code.");
1534 return false;
1536 frame->error_code = static_cast<QuicErrorCode>(error_code);
1538 if (error_code >= QUIC_LAST_ERROR) {
1539 set_detailed_error("Invalid error code.");
1540 return false;
1543 uint32 stream_id;
1544 if (!reader_->ReadUInt32(&stream_id)) {
1545 set_detailed_error("Unable to read last good stream id.");
1546 return false;
1548 frame->last_good_stream_id = static_cast<QuicStreamId>(stream_id);
1550 StringPiece reason_phrase;
1551 if (!reader_->ReadStringPiece16(&reason_phrase)) {
1552 set_detailed_error("Unable to read goaway reason.");
1553 return false;
1555 frame->reason_phrase = reason_phrase.as_string();
1557 return true;
1560 bool QuicFramer::ProcessWindowUpdateFrame(QuicWindowUpdateFrame* frame) {
1561 if (!reader_->ReadUInt32(&frame->stream_id)) {
1562 set_detailed_error("Unable to read stream_id.");
1563 return false;
1566 if (!reader_->ReadUInt64(&frame->byte_offset)) {
1567 set_detailed_error("Unable to read window byte_offset.");
1568 return false;
1571 return true;
1574 bool QuicFramer::ProcessBlockedFrame(QuicBlockedFrame* frame) {
1575 if (!reader_->ReadUInt32(&frame->stream_id)) {
1576 set_detailed_error("Unable to read stream_id.");
1577 return false;
1580 return true;
1583 // static
1584 StringPiece QuicFramer::GetAssociatedDataFromEncryptedPacket(
1585 const QuicEncryptedPacket& encrypted,
1586 QuicConnectionIdLength connection_id_length,
1587 bool includes_version,
1588 QuicSequenceNumberLength sequence_number_length) {
1589 return StringPiece(
1590 encrypted.data() + kStartOfHashData, GetStartOfEncryptedData(
1591 connection_id_length, includes_version, sequence_number_length)
1592 - kStartOfHashData);
1595 void QuicFramer::SetDecrypter(QuicDecrypter* decrypter,
1596 EncryptionLevel level) {
1597 DCHECK(alternative_decrypter_.get() == nullptr);
1598 DCHECK_GE(level, decrypter_level_);
1599 decrypter_.reset(decrypter);
1600 decrypter_level_ = level;
1603 void QuicFramer::SetAlternativeDecrypter(QuicDecrypter* decrypter,
1604 EncryptionLevel level,
1605 bool latch_once_used) {
1606 alternative_decrypter_.reset(decrypter);
1607 alternative_decrypter_level_ = level;
1608 alternative_decrypter_latch_ = latch_once_used;
1611 const QuicDecrypter* QuicFramer::decrypter() const {
1612 return decrypter_.get();
1615 const QuicDecrypter* QuicFramer::alternative_decrypter() const {
1616 return alternative_decrypter_.get();
1619 void QuicFramer::SetEncrypter(EncryptionLevel level,
1620 QuicEncrypter* encrypter) {
1621 DCHECK_GE(level, 0);
1622 DCHECK_LT(level, NUM_ENCRYPTION_LEVELS);
1623 encrypter_[level].reset(encrypter);
1626 QuicEncryptedPacket* QuicFramer::EncryptPacket(
1627 EncryptionLevel level,
1628 QuicPacketSequenceNumber packet_sequence_number,
1629 const QuicPacket& packet,
1630 char* buffer,
1631 size_t buffer_len) {
1632 DCHECK(encrypter_[level].get() != nullptr);
1634 const size_t encrypted_len =
1635 encrypter_[level]->GetCiphertextSize(packet.Plaintext().length());
1636 StringPiece header_data = packet.BeforePlaintext();
1637 const size_t total_len = header_data.length() + encrypted_len;
1639 char* encryption_buffer = buffer;
1640 // Allocate a large enough buffer for the header and the encrypted data.
1641 const bool is_new_buffer = total_len > buffer_len;
1642 if (is_new_buffer) {
1643 if (!FLAGS_quic_allow_oversized_packets_for_test) {
1644 LOG(DFATAL) << "Buffer of length:" << buffer_len
1645 << " is not large enough to encrypt length " << total_len;
1646 return nullptr;
1648 encryption_buffer = new char[total_len];
1650 // Copy in the header, because the encrypter only populates the encrypted
1651 // plaintext content.
1652 memcpy(encryption_buffer, header_data.data(), header_data.length());
1653 // Encrypt the plaintext into the buffer.
1654 size_t output_length = 0;
1655 if (!encrypter_[level]->EncryptPacket(
1656 packet_sequence_number, packet.AssociatedData(), packet.Plaintext(),
1657 encryption_buffer + header_data.length(), &output_length,
1658 encrypted_len)) {
1659 RaiseError(QUIC_ENCRYPTION_FAILURE);
1660 return nullptr;
1663 return new QuicEncryptedPacket(
1664 encryption_buffer, header_data.length() + output_length, is_new_buffer);
1667 size_t QuicFramer::GetMaxPlaintextSize(size_t ciphertext_size) {
1668 // In order to keep the code simple, we don't have the current encryption
1669 // level to hand. Both the NullEncrypter and AES-GCM have a tag length of 12.
1670 size_t min_plaintext_size = ciphertext_size;
1672 for (int i = ENCRYPTION_NONE; i < NUM_ENCRYPTION_LEVELS; i++) {
1673 if (encrypter_[i].get() != nullptr) {
1674 size_t size = encrypter_[i]->GetMaxPlaintextSize(ciphertext_size);
1675 if (size < min_plaintext_size) {
1676 min_plaintext_size = size;
1681 return min_plaintext_size;
1684 bool QuicFramer::DecryptPayload(const QuicPacketHeader& header,
1685 const QuicEncryptedPacket& packet,
1686 char* decrypted_buffer,
1687 size_t buffer_length) {
1688 StringPiece encrypted = reader_->ReadRemainingPayload();
1689 DCHECK(decrypter_.get() != nullptr);
1690 const StringPiece& associated_data = GetAssociatedDataFromEncryptedPacket(
1691 packet, header.public_header.connection_id_length,
1692 header.public_header.version_flag,
1693 header.public_header.sequence_number_length);
1694 size_t decrypted_length = 0;
1695 bool success = decrypter_->DecryptPacket(
1696 header.packet_sequence_number, associated_data, encrypted,
1697 decrypted_buffer, &decrypted_length, buffer_length);
1698 if (success) {
1699 visitor_->OnDecryptedPacket(decrypter_level_);
1700 } else if (alternative_decrypter_.get() != nullptr) {
1701 success = alternative_decrypter_->DecryptPacket(
1702 header.packet_sequence_number, associated_data, encrypted,
1703 decrypted_buffer, &decrypted_length, buffer_length);
1704 if (success) {
1705 visitor_->OnDecryptedPacket(alternative_decrypter_level_);
1706 if (alternative_decrypter_latch_) {
1707 // Switch to the alternative decrypter and latch so that we cannot
1708 // switch back.
1709 decrypter_.reset(alternative_decrypter_.release());
1710 decrypter_level_ = alternative_decrypter_level_;
1711 alternative_decrypter_level_ = ENCRYPTION_NONE;
1712 } else {
1713 // Switch the alternative decrypter so that we use it first next time.
1714 decrypter_.swap(alternative_decrypter_);
1715 EncryptionLevel level = alternative_decrypter_level_;
1716 alternative_decrypter_level_ = decrypter_level_;
1717 decrypter_level_ = level;
1722 if (!success) {
1723 DLOG(WARNING) << "DecryptPacket failed for sequence_number:"
1724 << header.packet_sequence_number;
1725 return false;
1728 reader_.reset(new QuicDataReader(decrypted_buffer, decrypted_length));
1729 return true;
1732 size_t QuicFramer::GetAckFrameSize(
1733 const QuicAckFrame& ack,
1734 QuicSequenceNumberLength sequence_number_length) {
1735 AckFrameInfo ack_info = GetAckFrameInfo(ack);
1736 QuicSequenceNumberLength largest_observed_length =
1737 GetMinSequenceNumberLength(ack.largest_observed);
1738 QuicSequenceNumberLength missing_sequence_number_length =
1739 GetMinSequenceNumberLength(ack_info.max_delta);
1741 size_t ack_size = GetMinAckFrameSize(sequence_number_length,
1742 largest_observed_length);
1743 if (!ack_info.nack_ranges.empty()) {
1744 ack_size += kNumberOfNackRangesSize + kNumberOfRevivedPacketsSize;
1745 ack_size += min(ack_info.nack_ranges.size(), kMaxNackRanges) *
1746 (missing_sequence_number_length + PACKET_1BYTE_SEQUENCE_NUMBER);
1747 ack_size += min(ack.revived_packets.size(),
1748 kMaxRevivedPackets) * largest_observed_length;
1751 // In version 23, if the ack will be truncated due to too many nack ranges,
1752 // then do not include the number of timestamps (1 byte).
1753 if (ack_info.nack_ranges.size() <= kMaxNackRanges) {
1754 // 1 byte for the number of timestamps.
1755 ack_size += 1;
1756 if (ack.received_packet_times.size() > 0) {
1757 // 1 byte for sequence number, 4 bytes for timestamp for the first
1758 // packet.
1759 ack_size += 5;
1761 // 1 byte for sequence number, 2 bytes for timestamp for the other
1762 // packets.
1763 ack_size += 3 * (ack.received_packet_times.size() - 1);
1767 return ack_size;
1770 size_t QuicFramer::ComputeFrameLength(
1771 const QuicFrame& frame,
1772 bool last_frame_in_packet,
1773 InFecGroup is_in_fec_group,
1774 QuicSequenceNumberLength sequence_number_length) {
1775 switch (frame.type) {
1776 case STREAM_FRAME:
1777 return GetMinStreamFrameSize(frame.stream_frame->stream_id,
1778 frame.stream_frame->offset,
1779 last_frame_in_packet, is_in_fec_group) +
1780 frame.stream_frame->data.length();
1781 case ACK_FRAME: {
1782 return GetAckFrameSize(*frame.ack_frame, sequence_number_length);
1784 case STOP_WAITING_FRAME:
1785 return GetStopWaitingFrameSize(sequence_number_length);
1786 case PING_FRAME:
1787 // Ping has no payload.
1788 return kQuicFrameTypeSize;
1789 case RST_STREAM_FRAME:
1790 if (quic_version_ <= QUIC_VERSION_24) {
1791 return GetMinRstStreamFrameSize() +
1792 frame.rst_stream_frame->error_details.size();
1794 return GetRstStreamFrameSize();
1795 case CONNECTION_CLOSE_FRAME:
1796 return GetMinConnectionCloseFrameSize() +
1797 frame.connection_close_frame->error_details.size();
1798 case GOAWAY_FRAME:
1799 return GetMinGoAwayFrameSize() + frame.goaway_frame->reason_phrase.size();
1800 case WINDOW_UPDATE_FRAME:
1801 return GetWindowUpdateFrameSize();
1802 case BLOCKED_FRAME:
1803 return GetBlockedFrameSize();
1804 case PADDING_FRAME:
1805 DCHECK(false);
1806 return 0;
1807 case NUM_FRAME_TYPES:
1808 DCHECK(false);
1809 return 0;
1812 // Not reachable, but some Chrome compilers can't figure that out. *sigh*
1813 DCHECK(false);
1814 return 0;
1817 bool QuicFramer::AppendTypeByte(const QuicFrame& frame,
1818 bool no_stream_frame_length,
1819 QuicDataWriter* writer) {
1820 uint8 type_byte = 0;
1821 switch (frame.type) {
1822 case STREAM_FRAME: {
1823 if (frame.stream_frame == nullptr) {
1824 LOG(DFATAL) << "Failed to append STREAM frame with no stream_frame.";
1826 // Fin bit.
1827 type_byte |= frame.stream_frame->fin ? kQuicStreamFinMask : 0;
1829 // Data Length bit.
1830 type_byte <<= kQuicStreamDataLengthShift;
1831 type_byte |= no_stream_frame_length ? 0: kQuicStreamDataLengthMask;
1833 // Offset 3 bits.
1834 type_byte <<= kQuicStreamOffsetShift;
1835 const size_t offset_len = GetStreamOffsetSize(frame.stream_frame->offset);
1836 if (offset_len > 0) {
1837 type_byte |= offset_len - 1;
1840 // stream id 2 bits.
1841 type_byte <<= kQuicStreamIdShift;
1842 type_byte |= GetStreamIdSize(frame.stream_frame->stream_id) - 1;
1843 type_byte |= kQuicFrameTypeStreamMask; // Set Stream Frame Type to 1.
1844 break;
1846 case ACK_FRAME:
1847 return true;
1848 default:
1849 type_byte = static_cast<uint8>(frame.type);
1850 break;
1853 return writer->WriteUInt8(type_byte);
1856 // static
1857 bool QuicFramer::AppendPacketSequenceNumber(
1858 QuicSequenceNumberLength sequence_number_length,
1859 QuicPacketSequenceNumber packet_sequence_number,
1860 QuicDataWriter* writer) {
1861 // Ensure the entire sequence number can be written.
1862 if (writer->capacity() - writer->length() <
1863 static_cast<size_t>(sequence_number_length)) {
1864 return false;
1866 switch (sequence_number_length) {
1867 case PACKET_1BYTE_SEQUENCE_NUMBER:
1868 return writer->WriteUInt8(
1869 packet_sequence_number & k1ByteSequenceNumberMask);
1870 break;
1871 case PACKET_2BYTE_SEQUENCE_NUMBER:
1872 return writer->WriteUInt16(
1873 packet_sequence_number & k2ByteSequenceNumberMask);
1874 break;
1875 case PACKET_4BYTE_SEQUENCE_NUMBER:
1876 return writer->WriteUInt32(
1877 packet_sequence_number & k4ByteSequenceNumberMask);
1878 break;
1879 case PACKET_6BYTE_SEQUENCE_NUMBER:
1880 return writer->WriteUInt48(
1881 packet_sequence_number & k6ByteSequenceNumberMask);
1882 break;
1883 default:
1884 DCHECK(false) << "sequence_number_length: " << sequence_number_length;
1885 return false;
1889 bool QuicFramer::AppendStreamFrame(
1890 const QuicStreamFrame& frame,
1891 bool no_stream_frame_length,
1892 QuicDataWriter* writer) {
1893 if (!writer->WriteBytes(&frame.stream_id, GetStreamIdSize(frame.stream_id))) {
1894 LOG(DFATAL) << "Writing stream id size failed.";
1895 return false;
1897 if (!writer->WriteBytes(&frame.offset, GetStreamOffsetSize(frame.offset))) {
1898 LOG(DFATAL) << "Writing offset size failed.";
1899 return false;
1901 if (!no_stream_frame_length) {
1902 if ((frame.data.size() > numeric_limits<uint16>::max()) ||
1903 !writer->WriteUInt16(static_cast<uint16>(frame.data.size()))) {
1904 LOG(DFATAL) << "Writing stream frame length failed";
1905 return false;
1909 if (!writer->WriteBytes(frame.data.data(), frame.data.size())) {
1910 LOG(DFATAL) << "Writing frame data failed.";
1911 return false;
1913 return true;
1916 void QuicFramer::set_version(const QuicVersion version) {
1917 DCHECK(IsSupportedVersion(version)) << QuicVersionToString(version);
1918 quic_version_ = version;
1921 bool QuicFramer::AppendAckFrameAndTypeByte(
1922 const QuicPacketHeader& header,
1923 const QuicAckFrame& frame,
1924 QuicDataWriter* writer) {
1925 AckFrameInfo ack_info = GetAckFrameInfo(frame);
1926 QuicPacketSequenceNumber ack_largest_observed = frame.largest_observed;
1927 QuicSequenceNumberLength largest_observed_length =
1928 GetMinSequenceNumberLength(ack_largest_observed);
1929 QuicSequenceNumberLength missing_sequence_number_length =
1930 GetMinSequenceNumberLength(ack_info.max_delta);
1931 // Determine whether we need to truncate ranges.
1932 size_t available_range_bytes = writer->capacity() - writer->length() -
1933 kNumberOfRevivedPacketsSize - kNumberOfNackRangesSize -
1934 GetMinAckFrameSize(header.public_header.sequence_number_length,
1935 largest_observed_length);
1936 size_t max_num_ranges = available_range_bytes /
1937 (missing_sequence_number_length + PACKET_1BYTE_SEQUENCE_NUMBER);
1938 max_num_ranges = min(kMaxNackRanges, max_num_ranges);
1939 bool truncated = ack_info.nack_ranges.size() > max_num_ranges;
1940 DVLOG_IF(1, truncated) << "Truncating ack from "
1941 << ack_info.nack_ranges.size() << " ranges to "
1942 << max_num_ranges;
1943 // Write out the type byte by setting the low order bits and doing shifts
1944 // to make room for the next bit flags to be set.
1945 // Whether there are any nacks.
1946 uint8 type_byte = ack_info.nack_ranges.empty() ? 0 : kQuicHasNacksMask;
1948 // truncating bit.
1949 type_byte <<= kQuicAckTruncatedShift;
1950 type_byte |= truncated ? kQuicAckTruncatedMask : 0;
1952 // Largest observed sequence number length.
1953 type_byte <<= kQuicSequenceNumberLengthShift;
1954 type_byte |= GetSequenceNumberFlags(largest_observed_length);
1956 // Missing sequence number length.
1957 type_byte <<= kQuicSequenceNumberLengthShift;
1958 type_byte |= GetSequenceNumberFlags(missing_sequence_number_length);
1960 type_byte |= kQuicFrameTypeAckMask;
1962 if (!writer->WriteUInt8(type_byte)) {
1963 return false;
1966 QuicPacketEntropyHash ack_entropy_hash = frame.entropy_hash;
1967 NackRangeMap::reverse_iterator ack_iter = ack_info.nack_ranges.rbegin();
1968 if (truncated) {
1969 // Skip the nack ranges which the truncated ack won't include and set
1970 // a correct largest observed for the truncated ack.
1971 for (size_t i = 1; i < (ack_info.nack_ranges.size() - max_num_ranges);
1972 ++i) {
1973 ++ack_iter;
1975 // If the last range is followed by acks, include them.
1976 // If the last range is followed by another range, specify the end of the
1977 // range as the largest_observed.
1978 ack_largest_observed = ack_iter->first - 1;
1979 // Also update the entropy so it matches the largest observed.
1980 ack_entropy_hash = entropy_calculator_->EntropyHash(ack_largest_observed);
1981 ++ack_iter;
1984 if (!writer->WriteUInt8(ack_entropy_hash)) {
1985 return false;
1988 if (!AppendPacketSequenceNumber(largest_observed_length,
1989 ack_largest_observed, writer)) {
1990 return false;
1993 uint64 delta_time_largest_observed_us = kUFloat16MaxValue;
1994 if (!frame.delta_time_largest_observed.IsInfinite()) {
1995 DCHECK_LE(0u, frame.delta_time_largest_observed.ToMicroseconds());
1996 delta_time_largest_observed_us =
1997 frame.delta_time_largest_observed.ToMicroseconds();
2000 if (!writer->WriteUFloat16(delta_time_largest_observed_us)) {
2001 return false;
2004 // Timestamp goes at the end of the required fields.
2005 if (!truncated) {
2006 if (!AppendTimestampToAckFrame(frame, writer)) {
2007 return false;
2011 if (ack_info.nack_ranges.empty()) {
2012 return true;
2015 const uint8 num_missing_ranges =
2016 static_cast<uint8>(min(ack_info.nack_ranges.size(), max_num_ranges));
2017 if (!writer->WriteBytes(&num_missing_ranges, 1)) {
2018 return false;
2021 int num_ranges_written = 0;
2022 QuicPacketSequenceNumber last_sequence_written = ack_largest_observed;
2023 for (; ack_iter != ack_info.nack_ranges.rend(); ++ack_iter) {
2024 // Calculate the delta to the last number in the range.
2025 QuicPacketSequenceNumber missing_delta =
2026 last_sequence_written - (ack_iter->first + ack_iter->second);
2027 if (!AppendPacketSequenceNumber(missing_sequence_number_length,
2028 missing_delta, writer)) {
2029 return false;
2031 if (!AppendPacketSequenceNumber(PACKET_1BYTE_SEQUENCE_NUMBER,
2032 ack_iter->second, writer)) {
2033 return false;
2035 // Subtract 1 so a missing_delta of 0 means an adjacent range.
2036 last_sequence_written = ack_iter->first - 1;
2037 ++num_ranges_written;
2039 DCHECK_EQ(num_missing_ranges, num_ranges_written);
2041 // Append revived packets.
2042 // If not all the revived packets fit, only mention the ones that do.
2043 uint8 num_revived_packets =
2044 static_cast<uint8>(min(frame.revived_packets.size(), kMaxRevivedPackets));
2045 num_revived_packets = static_cast<uint8>(min(
2046 static_cast<size_t>(num_revived_packets),
2047 (writer->capacity() - writer->length()) / largest_observed_length));
2048 if (!writer->WriteBytes(&num_revived_packets, 1)) {
2049 return false;
2052 SequenceNumberSet::const_iterator iter = frame.revived_packets.begin();
2053 for (int i = 0; i < num_revived_packets; ++i, ++iter) {
2054 LOG_IF(DFATAL, !ContainsKey(frame.missing_packets, *iter));
2055 if (!AppendPacketSequenceNumber(largest_observed_length,
2056 *iter, writer)) {
2057 return false;
2061 return true;
2064 bool QuicFramer::AppendTimestampToAckFrame(const QuicAckFrame& frame,
2065 QuicDataWriter* writer) {
2066 DCHECK_GE(numeric_limits<uint8>::max(), frame.received_packet_times.size());
2067 // num_received_packets is only 1 byte.
2068 if (frame.received_packet_times.size() > numeric_limits<uint8>::max()) {
2069 return false;
2072 uint8 num_received_packets = frame.received_packet_times.size();
2074 if (!writer->WriteBytes(&num_received_packets, 1)) {
2075 return false;
2077 if (num_received_packets == 0) {
2078 return true;
2081 PacketTimeList::const_iterator it = frame.received_packet_times.begin();
2082 QuicPacketSequenceNumber sequence_number = it->first;
2083 QuicPacketSequenceNumber delta_from_largest_observed =
2084 frame.largest_observed - sequence_number;
2086 DCHECK_GE(numeric_limits<uint8>::max(), delta_from_largest_observed);
2087 if (delta_from_largest_observed > numeric_limits<uint8>::max()) {
2088 return false;
2091 if (!writer->WriteUInt8(
2092 delta_from_largest_observed & k1ByteSequenceNumberMask)) {
2093 return false;
2096 // Use the lowest 4 bytes of the time delta from the creation_time_.
2097 const uint64 time_epoch_delta_us = UINT64_C(1) << 32;
2098 uint32 time_delta_us =
2099 static_cast<uint32>(it->second.Subtract(creation_time_).ToMicroseconds()
2100 & (time_epoch_delta_us - 1));
2101 if (!writer->WriteBytes(&time_delta_us, sizeof(time_delta_us))) {
2102 return false;
2105 QuicTime prev_time = it->second;
2107 for (++it; it != frame.received_packet_times.end(); ++it) {
2108 sequence_number = it->first;
2109 delta_from_largest_observed = frame.largest_observed - sequence_number;
2111 if (delta_from_largest_observed > numeric_limits<uint8>::max()) {
2112 return false;
2115 if (!writer->WriteUInt8(
2116 delta_from_largest_observed & k1ByteSequenceNumberMask)) {
2117 return false;
2120 uint64 frame_time_delta_us =
2121 it->second.Subtract(prev_time).ToMicroseconds();
2122 prev_time = it->second;
2123 if (!writer->WriteUFloat16(frame_time_delta_us)) {
2124 return false;
2127 return true;
2130 bool QuicFramer::AppendStopWaitingFrame(
2131 const QuicPacketHeader& header,
2132 const QuicStopWaitingFrame& frame,
2133 QuicDataWriter* writer) {
2134 DCHECK_GE(header.packet_sequence_number, frame.least_unacked);
2135 const QuicPacketSequenceNumber least_unacked_delta =
2136 header.packet_sequence_number - frame.least_unacked;
2137 const QuicPacketSequenceNumber length_shift =
2138 header.public_header.sequence_number_length * 8;
2139 if (!writer->WriteUInt8(frame.entropy_hash)) {
2140 LOG(DFATAL) << " hash failed";
2141 return false;
2144 if (least_unacked_delta >> length_shift > 0) {
2145 LOG(DFATAL) << "sequence_number_length "
2146 << header.public_header.sequence_number_length
2147 << " is too small for least_unacked_delta: "
2148 << least_unacked_delta;
2149 return false;
2151 if (!AppendPacketSequenceNumber(header.public_header.sequence_number_length,
2152 least_unacked_delta, writer)) {
2153 LOG(DFATAL) << " seq failed: "
2154 << header.public_header.sequence_number_length;
2155 return false;
2158 return true;
2161 bool QuicFramer::AppendRstStreamFrame(const QuicRstStreamFrame& frame,
2162 QuicDataWriter* writer) {
2163 if (!writer->WriteUInt32(frame.stream_id)) {
2164 return false;
2167 if (!writer->WriteUInt64(frame.byte_offset)) {
2168 return false;
2171 uint32 error_code = static_cast<uint32>(frame.error_code);
2172 if (!writer->WriteUInt32(error_code)) {
2173 return false;
2176 if (quic_version_ <= QUIC_VERSION_24) {
2177 if (!writer->WriteStringPiece16(frame.error_details)) {
2178 return false;
2181 return true;
2184 bool QuicFramer::AppendConnectionCloseFrame(
2185 const QuicConnectionCloseFrame& frame,
2186 QuicDataWriter* writer) {
2187 uint32 error_code = static_cast<uint32>(frame.error_code);
2188 if (!writer->WriteUInt32(error_code)) {
2189 return false;
2191 if (!writer->WriteStringPiece16(frame.error_details)) {
2192 return false;
2194 return true;
2197 bool QuicFramer::AppendGoAwayFrame(const QuicGoAwayFrame& frame,
2198 QuicDataWriter* writer) {
2199 uint32 error_code = static_cast<uint32>(frame.error_code);
2200 if (!writer->WriteUInt32(error_code)) {
2201 return false;
2203 uint32 stream_id = static_cast<uint32>(frame.last_good_stream_id);
2204 if (!writer->WriteUInt32(stream_id)) {
2205 return false;
2207 if (!writer->WriteStringPiece16(frame.reason_phrase)) {
2208 return false;
2210 return true;
2213 bool QuicFramer::AppendWindowUpdateFrame(const QuicWindowUpdateFrame& frame,
2214 QuicDataWriter* writer) {
2215 uint32 stream_id = static_cast<uint32>(frame.stream_id);
2216 if (!writer->WriteUInt32(stream_id)) {
2217 return false;
2219 if (!writer->WriteUInt64(frame.byte_offset)) {
2220 return false;
2222 return true;
2225 bool QuicFramer::AppendBlockedFrame(const QuicBlockedFrame& frame,
2226 QuicDataWriter* writer) {
2227 uint32 stream_id = static_cast<uint32>(frame.stream_id);
2228 if (!writer->WriteUInt32(stream_id)) {
2229 return false;
2231 return true;
2234 bool QuicFramer::RaiseError(QuicErrorCode error) {
2235 DVLOG(1) << "Error: " << QuicUtils::ErrorToString(error)
2236 << " detail: " << detailed_error_;
2237 set_error(error);
2238 visitor_->OnError(this);
2239 reader_.reset(nullptr);
2240 return false;
2243 } // namespace net