Add logging.store and logging.uploadStored to thunk.js for Hangouts.
[chromium-blink-merge.git] / net / quic / quic_framer.cc
blobbabdea4451390626ac29b2d63258b91ab09d9eb0
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 QuicFramer::QuicFramer(const QuicVersionVector& supported_versions,
139 QuicTime creation_time,
140 Perspective perspective)
141 : visitor_(nullptr),
142 entropy_calculator_(nullptr),
143 error_(QUIC_NO_ERROR),
144 last_sequence_number_(0),
145 last_serialized_connection_id_(0),
146 supported_versions_(supported_versions),
147 decrypter_level_(ENCRYPTION_NONE),
148 alternative_decrypter_level_(ENCRYPTION_NONE),
149 alternative_decrypter_latch_(false),
150 perspective_(perspective),
151 validate_flags_(true),
152 creation_time_(creation_time),
153 last_timestamp_(QuicTime::Delta::Zero()) {
154 DCHECK(!supported_versions.empty());
155 quic_version_ = supported_versions_[0];
156 decrypter_.reset(QuicDecrypter::Create(kNULL));
157 encrypter_[ENCRYPTION_NONE].reset(QuicEncrypter::Create(kNULL));
160 QuicFramer::~QuicFramer() {}
162 // static
163 size_t QuicFramer::GetMinStreamFrameSize(QuicStreamId stream_id,
164 QuicStreamOffset offset,
165 bool last_frame_in_packet,
166 InFecGroup is_in_fec_group) {
167 bool no_stream_frame_length = last_frame_in_packet &&
168 is_in_fec_group == NOT_IN_FEC_GROUP;
169 return kQuicFrameTypeSize + GetStreamIdSize(stream_id) +
170 GetStreamOffsetSize(offset) +
171 (no_stream_frame_length ? 0 : kQuicStreamPayloadLengthSize);
174 // static
175 size_t QuicFramer::GetMinAckFrameSize(
176 QuicSequenceNumberLength sequence_number_length,
177 QuicSequenceNumberLength largest_observed_length) {
178 return kQuicFrameTypeSize + kQuicEntropyHashSize +
179 largest_observed_length + kQuicDeltaTimeLargestObservedSize;
182 // static
183 size_t QuicFramer::GetStopWaitingFrameSize(
184 QuicSequenceNumberLength sequence_number_length) {
185 return kQuicFrameTypeSize + kQuicEntropyHashSize +
186 sequence_number_length;
189 // static
190 size_t QuicFramer::GetMinRstStreamFrameSize() {
191 return kQuicFrameTypeSize + kQuicMaxStreamIdSize +
192 kQuicMaxStreamOffsetSize + kQuicErrorCodeSize +
193 kQuicErrorDetailsLengthSize;
196 // static
197 size_t QuicFramer::GetRstStreamFrameSize() {
198 return kQuicFrameTypeSize + kQuicMaxStreamIdSize + kQuicMaxStreamOffsetSize +
199 kQuicErrorCodeSize;
202 // static
203 size_t QuicFramer::GetMinConnectionCloseFrameSize() {
204 return kQuicFrameTypeSize + kQuicErrorCodeSize + kQuicErrorDetailsLengthSize;
207 // static
208 size_t QuicFramer::GetMinGoAwayFrameSize() {
209 return kQuicFrameTypeSize + kQuicErrorCodeSize + kQuicErrorDetailsLengthSize +
210 kQuicMaxStreamIdSize;
213 // static
214 size_t QuicFramer::GetWindowUpdateFrameSize() {
215 return kQuicFrameTypeSize + kQuicMaxStreamIdSize + kQuicMaxStreamOffsetSize;
218 // static
219 size_t QuicFramer::GetBlockedFrameSize() {
220 return kQuicFrameTypeSize + kQuicMaxStreamIdSize;
223 // static
224 size_t QuicFramer::GetStreamIdSize(QuicStreamId stream_id) {
225 // Sizes are 1 through 4 bytes.
226 for (int i = 1; i <= 4; ++i) {
227 stream_id >>= 8;
228 if (stream_id == 0) {
229 return i;
232 LOG(DFATAL) << "Failed to determine StreamIDSize.";
233 return 4;
236 // static
237 size_t QuicFramer::GetStreamOffsetSize(QuicStreamOffset offset) {
238 // 0 is a special case.
239 if (offset == 0) {
240 return 0;
242 // 2 through 8 are the remaining sizes.
243 offset >>= 8;
244 for (int i = 2; i <= 8; ++i) {
245 offset >>= 8;
246 if (offset == 0) {
247 return i;
250 LOG(DFATAL) << "Failed to determine StreamOffsetSize.";
251 return 8;
254 // static
255 size_t QuicFramer::GetVersionNegotiationPacketSize(size_t number_versions) {
256 return kPublicFlagsSize + PACKET_8BYTE_CONNECTION_ID +
257 number_versions * kQuicVersionSize;
260 bool QuicFramer::IsSupportedVersion(const QuicVersion version) const {
261 for (size_t i = 0; i < supported_versions_.size(); ++i) {
262 if (version == supported_versions_[i]) {
263 return true;
266 return false;
269 size_t QuicFramer::GetSerializedFrameLength(
270 const QuicFrame& frame,
271 size_t free_bytes,
272 bool first_frame,
273 bool last_frame,
274 InFecGroup is_in_fec_group,
275 QuicSequenceNumberLength sequence_number_length) {
276 // Prevent a rare crash reported in b/19458523.
277 if (frame.stream_frame == nullptr) {
278 LOG(DFATAL) << "Cannot compute the length of a null frame. "
279 << "type:" << frame.type << "free_bytes:" << free_bytes
280 << " first_frame:" << first_frame
281 << " last_frame:" << last_frame
282 << " is_in_fec:" << is_in_fec_group
283 << " seq num length:" << sequence_number_length;
284 set_error(QUIC_INTERNAL_ERROR);
285 visitor_->OnError(this);
286 return false;
288 if (frame.type == PADDING_FRAME) {
289 // PADDING implies end of packet.
290 return free_bytes;
292 size_t frame_len =
293 ComputeFrameLength(frame, last_frame, is_in_fec_group,
294 sequence_number_length);
295 if (frame_len <= free_bytes) {
296 // Frame fits within packet. Note that acks may be truncated.
297 return frame_len;
299 // Only truncate the first frame in a packet, so if subsequent ones go
300 // over, stop including more frames.
301 if (!first_frame) {
302 return 0;
304 bool can_truncate = frame.type == ACK_FRAME &&
305 free_bytes >= GetMinAckFrameSize(PACKET_6BYTE_SEQUENCE_NUMBER,
306 PACKET_6BYTE_SEQUENCE_NUMBER);
307 if (can_truncate) {
308 // Truncate the frame so the packet will not exceed kMaxPacketSize.
309 // Note that we may not use every byte of the writer in this case.
310 DVLOG(1) << "Truncating large frame, free bytes: " << free_bytes;
311 return free_bytes;
313 if (!FLAGS_quic_allow_oversized_packets_for_test) {
314 return 0;
316 LOG(DFATAL) << "Packet size too small to fit frame.";
317 return frame_len;
320 QuicFramer::AckFrameInfo::AckFrameInfo() : max_delta(0) {}
322 QuicFramer::AckFrameInfo::~AckFrameInfo() {}
324 // static
325 QuicPacketEntropyHash QuicFramer::GetPacketEntropyHash(
326 const QuicPacketHeader& header) {
327 return header.entropy_flag << (header.packet_sequence_number % 8);
330 QuicPacket* QuicFramer::BuildDataPacket(const QuicPacketHeader& header,
331 const QuicFrames& frames,
332 char* buffer,
333 size_t packet_length) {
334 QuicDataWriter writer(packet_length, buffer);
335 if (!AppendPacketHeader(header, &writer)) {
336 LOG(DFATAL) << "AppendPacketHeader failed";
337 return nullptr;
340 size_t i = 0;
341 for (const QuicFrame& frame : frames) {
342 // Determine if we should write stream frame length in header.
343 const bool no_stream_frame_length =
344 (header.is_in_fec_group == NOT_IN_FEC_GROUP) &&
345 (i == frames.size() - 1);
346 if (!AppendTypeByte(frame, no_stream_frame_length, &writer)) {
347 LOG(DFATAL) << "AppendTypeByte failed";
348 return nullptr;
351 switch (frame.type) {
352 case PADDING_FRAME:
353 writer.WritePadding();
354 break;
355 case STREAM_FRAME:
356 if (!AppendStreamFrame(
357 *frame.stream_frame, no_stream_frame_length, &writer)) {
358 LOG(DFATAL) << "AppendStreamFrame failed";
359 return nullptr;
361 break;
362 case ACK_FRAME:
363 if (!AppendAckFrameAndTypeByte(
364 header, *frame.ack_frame, &writer)) {
365 LOG(DFATAL) << "AppendAckFrameAndTypeByte failed";
366 return nullptr;
368 break;
369 case STOP_WAITING_FRAME:
370 if (!AppendStopWaitingFrame(
371 header, *frame.stop_waiting_frame, &writer)) {
372 LOG(DFATAL) << "AppendStopWaitingFrame failed";
373 return nullptr;
375 break;
376 case PING_FRAME:
377 // Ping has no payload.
378 break;
379 case RST_STREAM_FRAME:
380 if (!AppendRstStreamFrame(*frame.rst_stream_frame, &writer)) {
381 LOG(DFATAL) << "AppendRstStreamFrame failed";
382 return nullptr;
384 break;
385 case CONNECTION_CLOSE_FRAME:
386 if (!AppendConnectionCloseFrame(
387 *frame.connection_close_frame, &writer)) {
388 LOG(DFATAL) << "AppendConnectionCloseFrame failed";
389 return nullptr;
391 break;
392 case GOAWAY_FRAME:
393 if (!AppendGoAwayFrame(*frame.goaway_frame, &writer)) {
394 LOG(DFATAL) << "AppendGoAwayFrame failed";
395 return nullptr;
397 break;
398 case WINDOW_UPDATE_FRAME:
399 if (!AppendWindowUpdateFrame(*frame.window_update_frame, &writer)) {
400 LOG(DFATAL) << "AppendWindowUpdateFrame failed";
401 return nullptr;
403 break;
404 case BLOCKED_FRAME:
405 if (!AppendBlockedFrame(*frame.blocked_frame, &writer)) {
406 LOG(DFATAL) << "AppendBlockedFrame failed";
407 return nullptr;
409 break;
410 default:
411 RaiseError(QUIC_INVALID_FRAME_DATA);
412 LOG(DFATAL) << "QUIC_INVALID_FRAME_DATA";
413 return nullptr;
415 ++i;
418 QuicPacket* packet =
419 new QuicPacket(writer.data(), writer.length(), false,
420 header.public_header.connection_id_length,
421 header.public_header.version_flag,
422 header.public_header.sequence_number_length);
424 return packet;
427 QuicPacket* QuicFramer::BuildFecPacket(const QuicPacketHeader& header,
428 const QuicFecData& fec) {
429 DCHECK_EQ(IN_FEC_GROUP, header.is_in_fec_group);
430 DCHECK_NE(0u, header.fec_group);
431 size_t len = GetPacketHeaderSize(header);
432 len += fec.redundancy.length();
434 scoped_ptr<char[]> buffer(new char[len]);
435 QuicDataWriter writer(len, buffer.get());
436 if (!AppendPacketHeader(header, &writer)) {
437 LOG(DFATAL) << "AppendPacketHeader failed";
438 return nullptr;
441 if (!writer.WriteBytes(fec.redundancy.data(), fec.redundancy.length())) {
442 LOG(DFATAL) << "Failed to add FEC";
443 return nullptr;
446 return new QuicPacket(buffer.release(), len, true,
447 header.public_header.connection_id_length,
448 header.public_header.version_flag,
449 header.public_header.sequence_number_length);
452 // static
453 QuicEncryptedPacket* QuicFramer::BuildPublicResetPacket(
454 const QuicPublicResetPacket& packet) {
455 DCHECK(packet.public_header.reset_flag);
457 CryptoHandshakeMessage reset;
458 reset.set_tag(kPRST);
459 reset.SetValue(kRNON, packet.nonce_proof);
460 reset.SetValue(kRSEQ, packet.rejected_sequence_number);
461 if (!packet.client_address.address().empty()) {
462 // packet.client_address is non-empty.
463 QuicSocketAddressCoder address_coder(packet.client_address);
464 string serialized_address = address_coder.Encode();
465 if (serialized_address.empty()) {
466 return nullptr;
468 reset.SetStringPiece(kCADR, serialized_address);
470 const QuicData& reset_serialized = reset.GetSerialized();
472 size_t len =
473 kPublicFlagsSize + PACKET_8BYTE_CONNECTION_ID + reset_serialized.length();
474 scoped_ptr<char[]> buffer(new char[len]);
475 QuicDataWriter writer(len, buffer.get());
477 uint8 flags = static_cast<uint8>(PACKET_PUBLIC_FLAGS_RST |
478 PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID);
479 if (!writer.WriteUInt8(flags)) {
480 return nullptr;
483 if (!writer.WriteUInt64(packet.public_header.connection_id)) {
484 return nullptr;
487 if (!writer.WriteBytes(reset_serialized.data(), reset_serialized.length())) {
488 return nullptr;
491 return new QuicEncryptedPacket(buffer.release(), len, true);
494 QuicEncryptedPacket* QuicFramer::BuildVersionNegotiationPacket(
495 const QuicPacketPublicHeader& header,
496 const QuicVersionVector& supported_versions) {
497 DCHECK(header.version_flag);
498 size_t len = GetVersionNegotiationPacketSize(supported_versions.size());
499 scoped_ptr<char[]> buffer(new char[len]);
500 QuicDataWriter writer(len, buffer.get());
502 uint8 flags = static_cast<uint8>(PACKET_PUBLIC_FLAGS_VERSION |
503 PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID);
504 if (!writer.WriteUInt8(flags)) {
505 return nullptr;
508 if (!writer.WriteUInt64(header.connection_id)) {
509 return nullptr;
512 for (size_t i = 0; i < supported_versions.size(); ++i) {
513 if (!writer.WriteUInt32(QuicVersionToQuicTag(supported_versions[i]))) {
514 return nullptr;
518 return new QuicEncryptedPacket(buffer.release(), len, true);
521 bool QuicFramer::ProcessPacket(const QuicEncryptedPacket& packet) {
522 DCHECK(!reader_.get());
523 reader_.reset(new QuicDataReader(packet.data(), packet.length()));
525 visitor_->OnPacket();
527 // First parse the public header.
528 QuicPacketPublicHeader public_header;
529 if (!ProcessPublicHeader(&public_header)) {
530 DLOG(WARNING) << "Unable to process public header.";
531 DCHECK_NE("", detailed_error_);
532 return RaiseError(QUIC_INVALID_PACKET_HEADER);
535 if (!visitor_->OnUnauthenticatedPublicHeader(public_header)) {
536 // The visitor suppresses further processing of the packet.
537 reader_.reset(nullptr);
538 return true;
541 if (perspective_ == Perspective::IS_SERVER && public_header.version_flag &&
542 public_header.versions[0] != quic_version_) {
543 if (!visitor_->OnProtocolVersionMismatch(public_header.versions[0])) {
544 reader_.reset(nullptr);
545 return true;
549 bool rv;
550 if (perspective_ == Perspective::IS_CLIENT && public_header.version_flag) {
551 rv = ProcessVersionNegotiationPacket(&public_header);
552 } else if (public_header.reset_flag) {
553 rv = ProcessPublicResetPacket(public_header);
554 } else if (packet.length() <= kMaxPacketSize) {
555 char buffer[kMaxPacketSize];
556 rv = ProcessDataPacket(public_header, packet, buffer, kMaxPacketSize);
557 } else {
558 scoped_ptr<char[]> large_buffer(new char[packet.length()]);
559 rv = ProcessDataPacket(public_header, packet, large_buffer.get(),
560 packet.length());
561 LOG_IF(DFATAL, rv) << "QUIC should never successfully process packets "
562 << "larger than kMaxPacketSize. packet size:"
563 << packet.length();
566 reader_.reset(nullptr);
567 return rv;
570 bool QuicFramer::ProcessVersionNegotiationPacket(
571 QuicPacketPublicHeader* public_header) {
572 DCHECK_EQ(Perspective::IS_CLIENT, perspective_);
573 // Try reading at least once to raise error if the packet is invalid.
574 do {
575 QuicTag version;
576 if (!reader_->ReadBytes(&version, kQuicVersionSize)) {
577 set_detailed_error("Unable to read supported version in negotiation.");
578 return RaiseError(QUIC_INVALID_VERSION_NEGOTIATION_PACKET);
580 public_header->versions.push_back(QuicTagToQuicVersion(version));
581 } while (!reader_->IsDoneReading());
583 visitor_->OnVersionNegotiationPacket(*public_header);
584 return true;
587 bool QuicFramer::ProcessDataPacket(const QuicPacketPublicHeader& public_header,
588 const QuicEncryptedPacket& packet,
589 char* decrypted_buffer,
590 size_t buffer_length) {
591 QuicPacketHeader header(public_header);
592 if (!ProcessPacketHeader(&header, packet, decrypted_buffer, buffer_length)) {
593 DLOG(WARNING) << "Unable to process packet header. Stopping parsing.";
594 return false;
597 if (!visitor_->OnPacketHeader(header)) {
598 // The visitor suppresses further processing of the packet.
599 return true;
602 if (packet.length() > kMaxPacketSize) {
603 DLOG(WARNING) << "Packet too large: " << packet.length();
604 return RaiseError(QUIC_PACKET_TOO_LARGE);
607 // Handle the payload.
608 if (!header.fec_flag) {
609 if (header.is_in_fec_group == IN_FEC_GROUP) {
610 StringPiece payload = reader_->PeekRemainingPayload();
611 visitor_->OnFecProtectedPayload(payload);
613 if (!ProcessFrameData(header)) {
614 DCHECK_NE(QUIC_NO_ERROR, error_); // ProcessFrameData sets the error.
615 DLOG(WARNING) << "Unable to process frame data.";
616 return false;
618 } else {
619 QuicFecData fec_data;
620 fec_data.fec_group = header.fec_group;
621 fec_data.redundancy = reader_->ReadRemainingPayload();
622 visitor_->OnFecData(fec_data);
625 visitor_->OnPacketComplete();
626 return true;
629 bool QuicFramer::ProcessPublicResetPacket(
630 const QuicPacketPublicHeader& public_header) {
631 QuicPublicResetPacket packet(public_header);
633 scoped_ptr<CryptoHandshakeMessage> reset(
634 CryptoFramer::ParseMessage(reader_->ReadRemainingPayload()));
635 if (!reset.get()) {
636 set_detailed_error("Unable to read reset message.");
637 return RaiseError(QUIC_INVALID_PUBLIC_RST_PACKET);
639 if (reset->tag() != kPRST) {
640 set_detailed_error("Incorrect message tag.");
641 return RaiseError(QUIC_INVALID_PUBLIC_RST_PACKET);
644 if (reset->GetUint64(kRNON, &packet.nonce_proof) != QUIC_NO_ERROR) {
645 set_detailed_error("Unable to read nonce proof.");
646 return RaiseError(QUIC_INVALID_PUBLIC_RST_PACKET);
648 // TODO(satyamshekhar): validate nonce to protect against DoS.
650 if (reset->GetUint64(kRSEQ, &packet.rejected_sequence_number) !=
651 QUIC_NO_ERROR) {
652 set_detailed_error("Unable to read rejected sequence number.");
653 return RaiseError(QUIC_INVALID_PUBLIC_RST_PACKET);
656 StringPiece address;
657 if (reset->GetStringPiece(kCADR, &address)) {
658 QuicSocketAddressCoder address_coder;
659 if (address_coder.Decode(address.data(), address.length())) {
660 packet.client_address = IPEndPoint(address_coder.ip(),
661 address_coder.port());
665 visitor_->OnPublicResetPacket(packet);
666 return true;
669 bool QuicFramer::ProcessRevivedPacket(QuicPacketHeader* header,
670 StringPiece payload) {
671 DCHECK(!reader_.get());
673 visitor_->OnRevivedPacket();
675 header->entropy_hash = GetPacketEntropyHash(*header);
677 if (!visitor_->OnPacketHeader(*header)) {
678 return true;
681 if (payload.length() > kMaxPacketSize) {
682 set_detailed_error("Revived packet too large.");
683 return RaiseError(QUIC_PACKET_TOO_LARGE);
686 reader_.reset(new QuicDataReader(payload.data(), payload.length()));
687 if (!ProcessFrameData(*header)) {
688 DCHECK_NE(QUIC_NO_ERROR, error_); // ProcessFrameData sets the error.
689 DLOG(WARNING) << "Unable to process frame data.";
690 return false;
693 visitor_->OnPacketComplete();
694 reader_.reset(nullptr);
695 return true;
698 bool QuicFramer::AppendPacketHeader(const QuicPacketHeader& header,
699 QuicDataWriter* writer) {
700 DVLOG(1) << "Appending header: " << header;
701 DCHECK(header.fec_group > 0 || header.is_in_fec_group == NOT_IN_FEC_GROUP);
702 uint8 public_flags = 0;
703 if (header.public_header.reset_flag) {
704 public_flags |= PACKET_PUBLIC_FLAGS_RST;
706 if (header.public_header.version_flag) {
707 public_flags |= PACKET_PUBLIC_FLAGS_VERSION;
710 public_flags |=
711 GetSequenceNumberFlags(header.public_header.sequence_number_length)
712 << kPublicHeaderSequenceNumberShift;
714 switch (header.public_header.connection_id_length) {
715 case PACKET_0BYTE_CONNECTION_ID:
716 if (!writer->WriteUInt8(
717 public_flags | PACKET_PUBLIC_FLAGS_0BYTE_CONNECTION_ID)) {
718 return false;
720 break;
721 case PACKET_1BYTE_CONNECTION_ID:
722 if (!writer->WriteUInt8(
723 public_flags | PACKET_PUBLIC_FLAGS_1BYTE_CONNECTION_ID)) {
724 return false;
726 if (!writer->WriteUInt8(
727 header.public_header.connection_id & k1ByteConnectionIdMask)) {
728 return false;
730 break;
731 case PACKET_4BYTE_CONNECTION_ID:
732 if (!writer->WriteUInt8(
733 public_flags | PACKET_PUBLIC_FLAGS_4BYTE_CONNECTION_ID)) {
734 return false;
736 if (!writer->WriteUInt32(
737 header.public_header.connection_id & k4ByteConnectionIdMask)) {
738 return false;
740 break;
741 case PACKET_8BYTE_CONNECTION_ID:
742 if (!writer->WriteUInt8(
743 public_flags | PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID)) {
744 return false;
746 if (!writer->WriteUInt64(header.public_header.connection_id)) {
747 return false;
749 break;
751 last_serialized_connection_id_ = header.public_header.connection_id;
753 if (header.public_header.version_flag) {
754 DCHECK_EQ(Perspective::IS_CLIENT, perspective_);
755 QuicTag tag = QuicVersionToQuicTag(quic_version_);
756 writer->WriteUInt32(tag);
757 DVLOG(1) << "version = " << quic_version_ << ", tag = '"
758 << QuicUtils::TagToString(tag) << "'";
761 if (!AppendPacketSequenceNumber(header.public_header.sequence_number_length,
762 header.packet_sequence_number, writer)) {
763 return false;
766 uint8 private_flags = 0;
767 if (header.entropy_flag) {
768 private_flags |= PACKET_PRIVATE_FLAGS_ENTROPY;
770 if (header.is_in_fec_group == IN_FEC_GROUP) {
771 private_flags |= PACKET_PRIVATE_FLAGS_FEC_GROUP;
773 if (header.fec_flag) {
774 private_flags |= PACKET_PRIVATE_FLAGS_FEC;
776 if (!writer->WriteUInt8(private_flags)) {
777 return false;
780 // The FEC group number is the sequence number of the first fec
781 // protected packet, or 0 if this packet is not protected.
782 if (header.is_in_fec_group == IN_FEC_GROUP) {
783 DCHECK_LE(header.fec_group, header.packet_sequence_number);
784 DCHECK_LT(header.packet_sequence_number - header.fec_group, 255u);
785 // Offset from the current packet sequence number to the first fec
786 // protected packet.
787 uint8 first_fec_protected_packet_offset =
788 static_cast<uint8>(header.packet_sequence_number - header.fec_group);
789 if (!writer->WriteBytes(&first_fec_protected_packet_offset, 1)) {
790 return false;
794 return true;
797 const QuicTime::Delta QuicFramer::CalculateTimestampFromWire(
798 uint32 time_delta_us) {
799 // The new time_delta might have wrapped to the next epoch, or it
800 // might have reverse wrapped to the previous epoch, or it might
801 // remain in the same epoch. Select the time closest to the previous
802 // time.
804 // epoch_delta is the delta between epochs. A delta is 4 bytes of
805 // microseconds.
806 const uint64 epoch_delta = UINT64_C(1) << 32;
807 uint64 epoch = last_timestamp_.ToMicroseconds() & ~(epoch_delta - 1);
808 // Wrapping is safe here because a wrapped value will not be ClosestTo below.
809 uint64 prev_epoch = epoch - epoch_delta;
810 uint64 next_epoch = epoch + epoch_delta;
812 uint64 time = ClosestTo(last_timestamp_.ToMicroseconds(),
813 epoch + time_delta_us,
814 ClosestTo(last_timestamp_.ToMicroseconds(),
815 prev_epoch + time_delta_us,
816 next_epoch + time_delta_us));
818 return QuicTime::Delta::FromMicroseconds(time);
821 QuicPacketSequenceNumber QuicFramer::CalculatePacketSequenceNumberFromWire(
822 QuicSequenceNumberLength sequence_number_length,
823 QuicPacketSequenceNumber packet_sequence_number) const {
824 // The new sequence number might have wrapped to the next epoch, or
825 // it might have reverse wrapped to the previous epoch, or it might
826 // remain in the same epoch. Select the sequence number closest to the
827 // next expected sequence number, the previous sequence number plus 1.
829 // epoch_delta is the delta between epochs the sequence number was serialized
830 // with, so the correct value is likely the same epoch as the last sequence
831 // number or an adjacent epoch.
832 const QuicPacketSequenceNumber epoch_delta =
833 UINT64_C(1) << (8 * sequence_number_length);
834 QuicPacketSequenceNumber next_sequence_number = last_sequence_number_ + 1;
835 QuicPacketSequenceNumber epoch = last_sequence_number_ & ~(epoch_delta - 1);
836 QuicPacketSequenceNumber prev_epoch = epoch - epoch_delta;
837 QuicPacketSequenceNumber next_epoch = epoch + epoch_delta;
839 return ClosestTo(next_sequence_number,
840 epoch + packet_sequence_number,
841 ClosestTo(next_sequence_number,
842 prev_epoch + packet_sequence_number,
843 next_epoch + packet_sequence_number));
846 bool QuicFramer::ProcessPublicHeader(
847 QuicPacketPublicHeader* public_header) {
848 uint8 public_flags;
849 if (!reader_->ReadBytes(&public_flags, 1)) {
850 set_detailed_error("Unable to read public flags.");
851 return false;
854 public_header->reset_flag = (public_flags & PACKET_PUBLIC_FLAGS_RST) != 0;
855 public_header->version_flag =
856 (public_flags & PACKET_PUBLIC_FLAGS_VERSION) != 0;
858 if (validate_flags_ &&
859 !public_header->version_flag && public_flags > PACKET_PUBLIC_FLAGS_MAX) {
860 set_detailed_error("Illegal public flags value.");
861 return false;
864 if (public_header->reset_flag && public_header->version_flag) {
865 set_detailed_error("Got version flag in reset packet");
866 return false;
869 switch (public_flags & PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID) {
870 case PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID:
871 if (!reader_->ReadUInt64(&public_header->connection_id)) {
872 set_detailed_error("Unable to read ConnectionId.");
873 return false;
875 public_header->connection_id_length = PACKET_8BYTE_CONNECTION_ID;
876 break;
877 case PACKET_PUBLIC_FLAGS_4BYTE_CONNECTION_ID:
878 // If the connection_id is truncated, expect to read the last serialized
879 // connection_id.
880 if (!reader_->ReadBytes(&public_header->connection_id,
881 PACKET_4BYTE_CONNECTION_ID)) {
882 set_detailed_error("Unable to read ConnectionId.");
883 return false;
885 if (last_serialized_connection_id_ &&
886 (public_header->connection_id & k4ByteConnectionIdMask) !=
887 (last_serialized_connection_id_ & k4ByteConnectionIdMask)) {
888 set_detailed_error("Truncated 4 byte ConnectionId does not match "
889 "previous connection_id.");
890 return false;
892 public_header->connection_id_length = PACKET_4BYTE_CONNECTION_ID;
893 public_header->connection_id = last_serialized_connection_id_;
894 break;
895 case PACKET_PUBLIC_FLAGS_1BYTE_CONNECTION_ID:
896 if (!reader_->ReadBytes(&public_header->connection_id,
897 PACKET_1BYTE_CONNECTION_ID)) {
898 set_detailed_error("Unable to read ConnectionId.");
899 return false;
901 if (last_serialized_connection_id_ &&
902 (public_header->connection_id & k1ByteConnectionIdMask) !=
903 (last_serialized_connection_id_ & k1ByteConnectionIdMask)) {
904 set_detailed_error("Truncated 1 byte ConnectionId does not match "
905 "previous connection_id.");
906 return false;
908 public_header->connection_id_length = PACKET_1BYTE_CONNECTION_ID;
909 public_header->connection_id = last_serialized_connection_id_;
910 break;
911 case PACKET_PUBLIC_FLAGS_0BYTE_CONNECTION_ID:
912 public_header->connection_id_length = PACKET_0BYTE_CONNECTION_ID;
913 public_header->connection_id = last_serialized_connection_id_;
914 break;
917 public_header->sequence_number_length =
918 ReadSequenceNumberLength(
919 public_flags >> kPublicHeaderSequenceNumberShift);
921 // Read the version only if the packet is from the client.
922 // version flag from the server means version negotiation packet.
923 if (public_header->version_flag && perspective_ == Perspective::IS_SERVER) {
924 QuicTag version_tag;
925 if (!reader_->ReadUInt32(&version_tag)) {
926 set_detailed_error("Unable to read protocol version.");
927 return false;
930 // If the version from the new packet is the same as the version of this
931 // framer, then the public flags should be set to something we understand.
932 // If not, this raises an error.
933 QuicVersion version = QuicTagToQuicVersion(version_tag);
934 if (version == quic_version_ && public_flags > PACKET_PUBLIC_FLAGS_MAX) {
935 set_detailed_error("Illegal public flags value.");
936 return false;
938 public_header->versions.push_back(version);
940 return true;
943 // static
944 QuicSequenceNumberLength QuicFramer::GetMinSequenceNumberLength(
945 QuicPacketSequenceNumber sequence_number) {
946 if (sequence_number < 1 << (PACKET_1BYTE_SEQUENCE_NUMBER * 8)) {
947 return PACKET_1BYTE_SEQUENCE_NUMBER;
948 } else if (sequence_number < 1 << (PACKET_2BYTE_SEQUENCE_NUMBER * 8)) {
949 return PACKET_2BYTE_SEQUENCE_NUMBER;
950 } else if (sequence_number <
951 UINT64_C(1) << (PACKET_4BYTE_SEQUENCE_NUMBER * 8)) {
952 return PACKET_4BYTE_SEQUENCE_NUMBER;
953 } else {
954 return PACKET_6BYTE_SEQUENCE_NUMBER;
958 // static
959 uint8 QuicFramer::GetSequenceNumberFlags(
960 QuicSequenceNumberLength sequence_number_length) {
961 switch (sequence_number_length) {
962 case PACKET_1BYTE_SEQUENCE_NUMBER:
963 return PACKET_FLAGS_1BYTE_SEQUENCE;
964 case PACKET_2BYTE_SEQUENCE_NUMBER:
965 return PACKET_FLAGS_2BYTE_SEQUENCE;
966 case PACKET_4BYTE_SEQUENCE_NUMBER:
967 return PACKET_FLAGS_4BYTE_SEQUENCE;
968 case PACKET_6BYTE_SEQUENCE_NUMBER:
969 return PACKET_FLAGS_6BYTE_SEQUENCE;
970 default:
971 LOG(DFATAL) << "Unreachable case statement.";
972 return PACKET_FLAGS_6BYTE_SEQUENCE;
976 // static
977 QuicFramer::AckFrameInfo QuicFramer::GetAckFrameInfo(
978 const QuicAckFrame& frame) {
979 AckFrameInfo ack_info;
980 if (frame.missing_packets.empty()) {
981 return ack_info;
983 DCHECK_GE(frame.largest_observed, *frame.missing_packets.rbegin());
984 size_t cur_range_length = 0;
985 SequenceNumberSet::const_iterator iter = frame.missing_packets.begin();
986 QuicPacketSequenceNumber last_missing = *iter;
987 ++iter;
988 for (; iter != frame.missing_packets.end(); ++iter) {
989 if (cur_range_length < numeric_limits<uint8>::max() &&
990 *iter == (last_missing + 1)) {
991 ++cur_range_length;
992 } else {
993 ack_info.nack_ranges[last_missing - cur_range_length] =
994 static_cast<uint8>(cur_range_length);
995 cur_range_length = 0;
997 ack_info.max_delta = max(ack_info.max_delta, *iter - last_missing);
998 last_missing = *iter;
1000 // Include the last nack range.
1001 ack_info.nack_ranges[last_missing - cur_range_length] =
1002 static_cast<uint8>(cur_range_length);
1003 // Include the range to the largest observed.
1004 ack_info.max_delta =
1005 max(ack_info.max_delta, frame.largest_observed - last_missing);
1006 return ack_info;
1009 bool QuicFramer::ProcessPacketHeader(QuicPacketHeader* header,
1010 const QuicEncryptedPacket& packet,
1011 char* decrypted_buffer,
1012 size_t buffer_length) {
1013 if (!ProcessPacketSequenceNumber(header->public_header.sequence_number_length,
1014 &header->packet_sequence_number)) {
1015 set_detailed_error("Unable to read sequence number.");
1016 return RaiseError(QUIC_INVALID_PACKET_HEADER);
1019 if (header->packet_sequence_number == 0u) {
1020 set_detailed_error("Packet sequence numbers cannot be 0.");
1021 return RaiseError(QUIC_INVALID_PACKET_HEADER);
1024 if (!visitor_->OnUnauthenticatedHeader(*header)) {
1025 return false;
1028 if (!DecryptPayload(*header, packet, decrypted_buffer, buffer_length)) {
1029 set_detailed_error("Unable to decrypt payload.");
1030 return RaiseError(QUIC_DECRYPTION_FAILURE);
1033 uint8 private_flags;
1034 if (!reader_->ReadBytes(&private_flags, 1)) {
1035 set_detailed_error("Unable to read private flags.");
1036 return RaiseError(QUIC_INVALID_PACKET_HEADER);
1039 if (private_flags > PACKET_PRIVATE_FLAGS_MAX) {
1040 set_detailed_error("Illegal private flags value.");
1041 return RaiseError(QUIC_INVALID_PACKET_HEADER);
1044 header->entropy_flag = (private_flags & PACKET_PRIVATE_FLAGS_ENTROPY) != 0;
1045 header->fec_flag = (private_flags & PACKET_PRIVATE_FLAGS_FEC) != 0;
1047 if ((private_flags & PACKET_PRIVATE_FLAGS_FEC_GROUP) != 0) {
1048 header->is_in_fec_group = IN_FEC_GROUP;
1049 uint8 first_fec_protected_packet_offset;
1050 if (!reader_->ReadBytes(&first_fec_protected_packet_offset, 1)) {
1051 set_detailed_error("Unable to read first fec protected packet offset.");
1052 return RaiseError(QUIC_INVALID_PACKET_HEADER);
1054 if (first_fec_protected_packet_offset >= header->packet_sequence_number) {
1055 set_detailed_error("First fec protected packet offset must be less "
1056 "than the sequence number.");
1057 return RaiseError(QUIC_INVALID_PACKET_HEADER);
1059 header->fec_group =
1060 header->packet_sequence_number - first_fec_protected_packet_offset;
1063 header->entropy_hash = GetPacketEntropyHash(*header);
1064 // Set the last sequence number after we have decrypted the packet
1065 // so we are confident is not attacker controlled.
1066 last_sequence_number_ = header->packet_sequence_number;
1067 return true;
1070 bool QuicFramer::ProcessPacketSequenceNumber(
1071 QuicSequenceNumberLength sequence_number_length,
1072 QuicPacketSequenceNumber* sequence_number) {
1073 QuicPacketSequenceNumber wire_sequence_number = 0u;
1074 if (!reader_->ReadBytes(&wire_sequence_number, sequence_number_length)) {
1075 return false;
1078 // TODO(ianswett): Explore the usefulness of trying multiple sequence numbers
1079 // in case the first guess is incorrect.
1080 *sequence_number =
1081 CalculatePacketSequenceNumberFromWire(sequence_number_length,
1082 wire_sequence_number);
1083 return true;
1086 bool QuicFramer::ProcessFrameData(const QuicPacketHeader& header) {
1087 if (reader_->IsDoneReading()) {
1088 set_detailed_error("Packet has no frames.");
1089 return RaiseError(QUIC_MISSING_PAYLOAD);
1091 while (!reader_->IsDoneReading()) {
1092 uint8 frame_type;
1093 if (!reader_->ReadBytes(&frame_type, 1)) {
1094 set_detailed_error("Unable to read frame type.");
1095 return RaiseError(QUIC_INVALID_FRAME_DATA);
1098 if (frame_type & kQuicFrameTypeSpecialMask) {
1099 // Stream Frame
1100 if (frame_type & kQuicFrameTypeStreamMask) {
1101 QuicStreamFrame frame;
1102 if (!ProcessStreamFrame(frame_type, &frame)) {
1103 return RaiseError(QUIC_INVALID_STREAM_DATA);
1105 if (!visitor_->OnStreamFrame(frame)) {
1106 DVLOG(1) << "Visitor asked to stop further processing.";
1107 // Returning true since there was no parsing error.
1108 return true;
1110 continue;
1113 // Ack Frame
1114 if (frame_type & kQuicFrameTypeAckMask) {
1115 QuicAckFrame frame;
1116 if (!ProcessAckFrame(frame_type, &frame)) {
1117 return RaiseError(QUIC_INVALID_ACK_DATA);
1119 if (!visitor_->OnAckFrame(frame)) {
1120 DVLOG(1) << "Visitor asked to stop further processing.";
1121 // Returning true since there was no parsing error.
1122 return true;
1124 continue;
1127 // This was a special frame type that did not match any
1128 // of the known ones. Error.
1129 set_detailed_error("Illegal frame type.");
1130 DLOG(WARNING) << "Illegal frame type: "
1131 << static_cast<int>(frame_type);
1132 return RaiseError(QUIC_INVALID_FRAME_DATA);
1135 switch (frame_type) {
1136 case PADDING_FRAME:
1137 // We're done with the packet.
1138 return true;
1140 case RST_STREAM_FRAME: {
1141 QuicRstStreamFrame frame;
1142 if (!ProcessRstStreamFrame(&frame)) {
1143 return RaiseError(QUIC_INVALID_RST_STREAM_DATA);
1145 if (!visitor_->OnRstStreamFrame(frame)) {
1146 DVLOG(1) << "Visitor asked to stop further processing.";
1147 // Returning true since there was no parsing error.
1148 return true;
1150 continue;
1153 case CONNECTION_CLOSE_FRAME: {
1154 QuicConnectionCloseFrame frame;
1155 if (!ProcessConnectionCloseFrame(&frame)) {
1156 return RaiseError(QUIC_INVALID_CONNECTION_CLOSE_DATA);
1159 if (!visitor_->OnConnectionCloseFrame(frame)) {
1160 DVLOG(1) << "Visitor asked to stop further processing.";
1161 // Returning true since there was no parsing error.
1162 return true;
1164 continue;
1167 case GOAWAY_FRAME: {
1168 QuicGoAwayFrame goaway_frame;
1169 if (!ProcessGoAwayFrame(&goaway_frame)) {
1170 return RaiseError(QUIC_INVALID_GOAWAY_DATA);
1172 if (!visitor_->OnGoAwayFrame(goaway_frame)) {
1173 DVLOG(1) << "Visitor asked to stop further processing.";
1174 // Returning true since there was no parsing error.
1175 return true;
1177 continue;
1180 case WINDOW_UPDATE_FRAME: {
1181 QuicWindowUpdateFrame window_update_frame;
1182 if (!ProcessWindowUpdateFrame(&window_update_frame)) {
1183 return RaiseError(QUIC_INVALID_WINDOW_UPDATE_DATA);
1185 if (!visitor_->OnWindowUpdateFrame(window_update_frame)) {
1186 DVLOG(1) << "Visitor asked to stop further processing.";
1187 // Returning true since there was no parsing error.
1188 return true;
1190 continue;
1193 case BLOCKED_FRAME: {
1194 QuicBlockedFrame blocked_frame;
1195 if (!ProcessBlockedFrame(&blocked_frame)) {
1196 return RaiseError(QUIC_INVALID_BLOCKED_DATA);
1198 if (!visitor_->OnBlockedFrame(blocked_frame)) {
1199 DVLOG(1) << "Visitor asked to stop further processing.";
1200 // Returning true since there was no parsing error.
1201 return true;
1203 continue;
1206 case STOP_WAITING_FRAME: {
1207 QuicStopWaitingFrame stop_waiting_frame;
1208 if (!ProcessStopWaitingFrame(header, &stop_waiting_frame)) {
1209 return RaiseError(QUIC_INVALID_STOP_WAITING_DATA);
1211 if (!visitor_->OnStopWaitingFrame(stop_waiting_frame)) {
1212 DVLOG(1) << "Visitor asked to stop further processing.";
1213 // Returning true since there was no parsing error.
1214 return true;
1216 continue;
1218 case PING_FRAME: {
1219 // Ping has no payload.
1220 QuicPingFrame ping_frame;
1221 if (!visitor_->OnPingFrame(ping_frame)) {
1222 DVLOG(1) << "Visitor asked to stop further processing.";
1223 // Returning true since there was no parsing error.
1224 return true;
1226 continue;
1229 default:
1230 set_detailed_error("Illegal frame type.");
1231 DLOG(WARNING) << "Illegal frame type: "
1232 << static_cast<int>(frame_type);
1233 return RaiseError(QUIC_INVALID_FRAME_DATA);
1237 return true;
1240 bool QuicFramer::ProcessStreamFrame(uint8 frame_type,
1241 QuicStreamFrame* frame) {
1242 uint8 stream_flags = frame_type;
1244 stream_flags &= ~kQuicFrameTypeStreamMask;
1246 // Read from right to left: StreamID, Offset, Data Length, Fin.
1247 const uint8 stream_id_length = (stream_flags & kQuicStreamIDLengthMask) + 1;
1248 stream_flags >>= kQuicStreamIdShift;
1250 uint8 offset_length = (stream_flags & kQuicStreamOffsetMask);
1251 // There is no encoding for 1 byte, only 0 and 2 through 8.
1252 if (offset_length > 0) {
1253 offset_length += 1;
1255 stream_flags >>= kQuicStreamOffsetShift;
1257 bool has_data_length =
1258 (stream_flags & kQuicStreamDataLengthMask) == kQuicStreamDataLengthMask;
1259 stream_flags >>= kQuicStreamDataLengthShift;
1261 frame->fin = (stream_flags & kQuicStreamFinMask) == kQuicStreamFinShift;
1263 frame->stream_id = 0;
1264 if (!reader_->ReadBytes(&frame->stream_id, stream_id_length)) {
1265 set_detailed_error("Unable to read stream_id.");
1266 return false;
1269 frame->offset = 0;
1270 if (!reader_->ReadBytes(&frame->offset, offset_length)) {
1271 set_detailed_error("Unable to read offset.");
1272 return false;
1275 if (has_data_length) {
1276 if (!reader_->ReadStringPiece16(&frame->data)) {
1277 set_detailed_error("Unable to read frame data.");
1278 return false;
1280 } else {
1281 if (!reader_->ReadStringPiece(&frame->data, reader_->BytesRemaining())) {
1282 set_detailed_error("Unable to read frame data.");
1283 return false;
1287 return true;
1290 bool QuicFramer::ProcessAckFrame(uint8 frame_type, QuicAckFrame* ack_frame) {
1291 // Determine the three lengths from the frame type: largest observed length,
1292 // missing sequence number length, and missing range length.
1293 const QuicSequenceNumberLength missing_sequence_number_length =
1294 ReadSequenceNumberLength(frame_type);
1295 frame_type >>= kQuicSequenceNumberLengthShift;
1296 const QuicSequenceNumberLength largest_observed_sequence_number_length =
1297 ReadSequenceNumberLength(frame_type);
1298 frame_type >>= kQuicSequenceNumberLengthShift;
1299 ack_frame->is_truncated = frame_type & kQuicAckTruncatedMask;
1300 frame_type >>= kQuicAckTruncatedShift;
1301 bool has_nacks = frame_type & kQuicHasNacksMask;
1303 if (!reader_->ReadBytes(&ack_frame->entropy_hash, 1)) {
1304 set_detailed_error("Unable to read entropy hash for received packets.");
1305 return false;
1308 if (!reader_->ReadBytes(&ack_frame->largest_observed,
1309 largest_observed_sequence_number_length)) {
1310 set_detailed_error("Unable to read largest observed.");
1311 return false;
1314 uint64 delta_time_largest_observed_us;
1315 if (!reader_->ReadUFloat16(&delta_time_largest_observed_us)) {
1316 set_detailed_error("Unable to read delta time largest observed.");
1317 return false;
1320 if (delta_time_largest_observed_us == kUFloat16MaxValue) {
1321 ack_frame->delta_time_largest_observed = QuicTime::Delta::Infinite();
1322 } else {
1323 ack_frame->delta_time_largest_observed =
1324 QuicTime::Delta::FromMicroseconds(delta_time_largest_observed_us);
1327 if (!ProcessTimestampsInAckFrame(ack_frame)) {
1328 return false;
1331 if (!has_nacks) {
1332 return true;
1335 uint8 num_missing_ranges;
1336 if (!reader_->ReadBytes(&num_missing_ranges, 1)) {
1337 set_detailed_error("Unable to read num missing packet ranges.");
1338 return false;
1341 QuicPacketSequenceNumber last_sequence_number = ack_frame->largest_observed;
1342 for (size_t i = 0; i < num_missing_ranges; ++i) {
1343 QuicPacketSequenceNumber missing_delta = 0;
1344 if (!reader_->ReadBytes(&missing_delta, missing_sequence_number_length)) {
1345 set_detailed_error("Unable to read missing sequence number delta.");
1346 return false;
1348 last_sequence_number -= missing_delta;
1349 QuicPacketSequenceNumber range_length = 0;
1350 if (!reader_->ReadBytes(&range_length, PACKET_1BYTE_SEQUENCE_NUMBER)) {
1351 set_detailed_error("Unable to read missing sequence number range.");
1352 return false;
1354 for (size_t j = 0; j <= range_length; ++j) {
1355 ack_frame->missing_packets.insert(last_sequence_number - j);
1357 // Subtract an extra 1 to ensure ranges are represented efficiently and
1358 // can't overlap by 1 sequence number. This allows a missing_delta of 0
1359 // to represent an adjacent nack range.
1360 last_sequence_number -= (range_length + 1);
1363 // Parse the revived packets list.
1364 uint8 num_revived_packets;
1365 if (!reader_->ReadBytes(&num_revived_packets, 1)) {
1366 set_detailed_error("Unable to read num revived packets.");
1367 return false;
1370 for (size_t i = 0; i < num_revived_packets; ++i) {
1371 QuicPacketSequenceNumber revived_packet = 0;
1372 if (!reader_->ReadBytes(&revived_packet,
1373 largest_observed_sequence_number_length)) {
1374 set_detailed_error("Unable to read revived packet.");
1375 return false;
1378 ack_frame->revived_packets.insert(revived_packet);
1381 return true;
1384 bool QuicFramer::ProcessTimestampsInAckFrame(QuicAckFrame* ack_frame) {
1385 if (ack_frame->is_truncated) {
1386 return true;
1388 uint8 num_received_packets;
1389 if (!reader_->ReadBytes(&num_received_packets, 1)) {
1390 set_detailed_error("Unable to read num received packets.");
1391 return false;
1394 if (num_received_packets > 0) {
1395 uint8 delta_from_largest_observed;
1396 if (!reader_->ReadBytes(&delta_from_largest_observed,
1397 PACKET_1BYTE_SEQUENCE_NUMBER)) {
1398 set_detailed_error("Unable to read sequence delta in received packets.");
1399 return false;
1401 QuicPacketSequenceNumber seq_num =
1402 ack_frame->largest_observed - delta_from_largest_observed;
1404 // Time delta from the framer creation.
1405 uint32 time_delta_us;
1406 if (!reader_->ReadBytes(&time_delta_us, sizeof(time_delta_us))) {
1407 set_detailed_error("Unable to read time delta in received packets.");
1408 return false;
1411 last_timestamp_ = CalculateTimestampFromWire(time_delta_us);
1413 ack_frame->received_packet_times.push_back(
1414 std::make_pair(seq_num, creation_time_.Add(last_timestamp_)));
1416 for (uint8 i = 1; i < num_received_packets; ++i) {
1417 if (!reader_->ReadBytes(&delta_from_largest_observed,
1418 PACKET_1BYTE_SEQUENCE_NUMBER)) {
1419 set_detailed_error(
1420 "Unable to read sequence delta in received packets.");
1421 return false;
1423 seq_num = ack_frame->largest_observed - delta_from_largest_observed;
1425 // Time delta from the previous timestamp.
1426 uint64 incremental_time_delta_us;
1427 if (!reader_->ReadUFloat16(&incremental_time_delta_us)) {
1428 set_detailed_error(
1429 "Unable to read incremental time delta in received packets.");
1430 return false;
1433 last_timestamp_ = last_timestamp_.Add(
1434 QuicTime::Delta::FromMicroseconds(incremental_time_delta_us));
1435 ack_frame->received_packet_times.push_back(
1436 std::make_pair(seq_num, creation_time_.Add(last_timestamp_)));
1439 return true;
1442 bool QuicFramer::ProcessStopWaitingFrame(const QuicPacketHeader& header,
1443 QuicStopWaitingFrame* stop_waiting) {
1444 if (!reader_->ReadBytes(&stop_waiting->entropy_hash, 1)) {
1445 set_detailed_error("Unable to read entropy hash for sent packets.");
1446 return false;
1449 QuicPacketSequenceNumber least_unacked_delta = 0;
1450 if (!reader_->ReadBytes(&least_unacked_delta,
1451 header.public_header.sequence_number_length)) {
1452 set_detailed_error("Unable to read least unacked delta.");
1453 return false;
1455 DCHECK_GE(header.packet_sequence_number, least_unacked_delta);
1456 stop_waiting->least_unacked =
1457 header.packet_sequence_number - least_unacked_delta;
1459 return true;
1462 bool QuicFramer::ProcessRstStreamFrame(QuicRstStreamFrame* frame) {
1463 if (!reader_->ReadUInt32(&frame->stream_id)) {
1464 set_detailed_error("Unable to read stream_id.");
1465 return false;
1468 if (!reader_->ReadUInt64(&frame->byte_offset)) {
1469 set_detailed_error("Unable to read rst stream sent byte offset.");
1470 return false;
1473 uint32 error_code;
1474 if (!reader_->ReadUInt32(&error_code)) {
1475 set_detailed_error("Unable to read rst stream error code.");
1476 return false;
1479 if (error_code >= QUIC_STREAM_LAST_ERROR) {
1480 set_detailed_error("Invalid rst stream error code.");
1481 return false;
1484 frame->error_code = static_cast<QuicRstStreamErrorCode>(error_code);
1485 if (quic_version_ <= QUIC_VERSION_24) {
1486 StringPiece error_details;
1487 if (!reader_->ReadStringPiece16(&error_details)) {
1488 set_detailed_error("Unable to read rst stream error details.");
1489 return false;
1491 frame->error_details = error_details.as_string();
1494 return true;
1497 bool QuicFramer::ProcessConnectionCloseFrame(QuicConnectionCloseFrame* frame) {
1498 uint32 error_code;
1499 if (!reader_->ReadUInt32(&error_code)) {
1500 set_detailed_error("Unable to read connection close error code.");
1501 return false;
1504 if (error_code >= QUIC_LAST_ERROR) {
1505 set_detailed_error("Invalid error code.");
1506 return false;
1509 frame->error_code = static_cast<QuicErrorCode>(error_code);
1511 StringPiece error_details;
1512 if (!reader_->ReadStringPiece16(&error_details)) {
1513 set_detailed_error("Unable to read connection close error details.");
1514 return false;
1516 frame->error_details = error_details.as_string();
1518 return true;
1521 bool QuicFramer::ProcessGoAwayFrame(QuicGoAwayFrame* frame) {
1522 uint32 error_code;
1523 if (!reader_->ReadUInt32(&error_code)) {
1524 set_detailed_error("Unable to read go away error code.");
1525 return false;
1527 frame->error_code = static_cast<QuicErrorCode>(error_code);
1529 if (error_code >= QUIC_LAST_ERROR) {
1530 set_detailed_error("Invalid error code.");
1531 return false;
1534 uint32 stream_id;
1535 if (!reader_->ReadUInt32(&stream_id)) {
1536 set_detailed_error("Unable to read last good stream id.");
1537 return false;
1539 frame->last_good_stream_id = static_cast<QuicStreamId>(stream_id);
1541 StringPiece reason_phrase;
1542 if (!reader_->ReadStringPiece16(&reason_phrase)) {
1543 set_detailed_error("Unable to read goaway reason.");
1544 return false;
1546 frame->reason_phrase = reason_phrase.as_string();
1548 return true;
1551 bool QuicFramer::ProcessWindowUpdateFrame(QuicWindowUpdateFrame* frame) {
1552 if (!reader_->ReadUInt32(&frame->stream_id)) {
1553 set_detailed_error("Unable to read stream_id.");
1554 return false;
1557 if (!reader_->ReadUInt64(&frame->byte_offset)) {
1558 set_detailed_error("Unable to read window byte_offset.");
1559 return false;
1562 return true;
1565 bool QuicFramer::ProcessBlockedFrame(QuicBlockedFrame* frame) {
1566 if (!reader_->ReadUInt32(&frame->stream_id)) {
1567 set_detailed_error("Unable to read stream_id.");
1568 return false;
1571 return true;
1574 // static
1575 StringPiece QuicFramer::GetAssociatedDataFromEncryptedPacket(
1576 const QuicEncryptedPacket& encrypted,
1577 QuicConnectionIdLength connection_id_length,
1578 bool includes_version,
1579 QuicSequenceNumberLength sequence_number_length) {
1580 return StringPiece(
1581 encrypted.data() + kStartOfHashData, GetStartOfEncryptedData(
1582 connection_id_length, includes_version, sequence_number_length)
1583 - kStartOfHashData);
1586 void QuicFramer::SetDecrypter(QuicDecrypter* decrypter,
1587 EncryptionLevel level) {
1588 DCHECK(alternative_decrypter_.get() == nullptr);
1589 DCHECK_GE(level, decrypter_level_);
1590 decrypter_.reset(decrypter);
1591 decrypter_level_ = level;
1594 void QuicFramer::SetAlternativeDecrypter(QuicDecrypter* decrypter,
1595 EncryptionLevel level,
1596 bool latch_once_used) {
1597 alternative_decrypter_.reset(decrypter);
1598 alternative_decrypter_level_ = level;
1599 alternative_decrypter_latch_ = latch_once_used;
1602 const QuicDecrypter* QuicFramer::decrypter() const {
1603 return decrypter_.get();
1606 const QuicDecrypter* QuicFramer::alternative_decrypter() const {
1607 return alternative_decrypter_.get();
1610 void QuicFramer::SetEncrypter(EncryptionLevel level,
1611 QuicEncrypter* encrypter) {
1612 DCHECK_GE(level, 0);
1613 DCHECK_LT(level, NUM_ENCRYPTION_LEVELS);
1614 encrypter_[level].reset(encrypter);
1617 QuicEncryptedPacket* QuicFramer::EncryptPacket(
1618 EncryptionLevel level,
1619 QuicPacketSequenceNumber packet_sequence_number,
1620 const QuicPacket& packet,
1621 char* buffer,
1622 size_t buffer_len) {
1623 DCHECK(encrypter_[level].get() != nullptr);
1625 const size_t encrypted_len =
1626 encrypter_[level]->GetCiphertextSize(packet.Plaintext().length());
1627 StringPiece header_data = packet.BeforePlaintext();
1628 const size_t total_len = header_data.length() + encrypted_len;
1630 char* encryption_buffer = buffer;
1631 // Allocate a large enough buffer for the header and the encrypted data.
1632 const bool is_new_buffer = total_len > buffer_len;
1633 if (is_new_buffer) {
1634 if (!FLAGS_quic_allow_oversized_packets_for_test) {
1635 LOG(DFATAL) << "Buffer of length:" << buffer_len
1636 << " is not large enough to encrypt length " << total_len;
1637 return nullptr;
1639 encryption_buffer = new char[total_len];
1641 // Copy in the header, because the encrypter only populates the encrypted
1642 // plaintext content.
1643 memcpy(encryption_buffer, header_data.data(), header_data.length());
1644 // Encrypt the plaintext into the buffer.
1645 size_t output_length = 0;
1646 if (!encrypter_[level]->EncryptPacket(
1647 packet_sequence_number, packet.AssociatedData(), packet.Plaintext(),
1648 encryption_buffer + header_data.length(), &output_length,
1649 encrypted_len)) {
1650 RaiseError(QUIC_ENCRYPTION_FAILURE);
1651 return nullptr;
1654 return new QuicEncryptedPacket(
1655 encryption_buffer, header_data.length() + output_length, is_new_buffer);
1658 size_t QuicFramer::GetMaxPlaintextSize(size_t ciphertext_size) {
1659 // In order to keep the code simple, we don't have the current encryption
1660 // level to hand. Both the NullEncrypter and AES-GCM have a tag length of 12.
1661 size_t min_plaintext_size = ciphertext_size;
1663 for (int i = ENCRYPTION_NONE; i < NUM_ENCRYPTION_LEVELS; i++) {
1664 if (encrypter_[i].get() != nullptr) {
1665 size_t size = encrypter_[i]->GetMaxPlaintextSize(ciphertext_size);
1666 if (size < min_plaintext_size) {
1667 min_plaintext_size = size;
1672 return min_plaintext_size;
1675 bool QuicFramer::DecryptPayload(const QuicPacketHeader& header,
1676 const QuicEncryptedPacket& packet,
1677 char* decrypted_buffer,
1678 size_t buffer_length) {
1679 StringPiece encrypted = reader_->ReadRemainingPayload();
1680 DCHECK(decrypter_.get() != nullptr);
1681 const StringPiece& associated_data = GetAssociatedDataFromEncryptedPacket(
1682 packet, header.public_header.connection_id_length,
1683 header.public_header.version_flag,
1684 header.public_header.sequence_number_length);
1685 size_t decrypted_length = 0;
1686 bool success = decrypter_->DecryptPacket(
1687 header.packet_sequence_number, associated_data, encrypted,
1688 decrypted_buffer, &decrypted_length, buffer_length);
1689 if (success) {
1690 visitor_->OnDecryptedPacket(decrypter_level_);
1691 } else if (alternative_decrypter_.get() != nullptr) {
1692 success = alternative_decrypter_->DecryptPacket(
1693 header.packet_sequence_number, associated_data, encrypted,
1694 decrypted_buffer, &decrypted_length, buffer_length);
1695 if (success) {
1696 visitor_->OnDecryptedPacket(alternative_decrypter_level_);
1697 if (alternative_decrypter_latch_) {
1698 // Switch to the alternative decrypter and latch so that we cannot
1699 // switch back.
1700 decrypter_.reset(alternative_decrypter_.release());
1701 decrypter_level_ = alternative_decrypter_level_;
1702 alternative_decrypter_level_ = ENCRYPTION_NONE;
1703 } else {
1704 // Switch the alternative decrypter so that we use it first next time.
1705 decrypter_.swap(alternative_decrypter_);
1706 EncryptionLevel level = alternative_decrypter_level_;
1707 alternative_decrypter_level_ = decrypter_level_;
1708 decrypter_level_ = level;
1713 if (!success) {
1714 DLOG(WARNING) << "DecryptPacket failed for sequence_number:"
1715 << header.packet_sequence_number;
1716 return false;
1719 reader_.reset(new QuicDataReader(decrypted_buffer, decrypted_length));
1720 return true;
1723 size_t QuicFramer::GetAckFrameSize(
1724 const QuicAckFrame& ack,
1725 QuicSequenceNumberLength sequence_number_length) {
1726 AckFrameInfo ack_info = GetAckFrameInfo(ack);
1727 QuicSequenceNumberLength largest_observed_length =
1728 GetMinSequenceNumberLength(ack.largest_observed);
1729 QuicSequenceNumberLength missing_sequence_number_length =
1730 GetMinSequenceNumberLength(ack_info.max_delta);
1732 size_t ack_size = GetMinAckFrameSize(sequence_number_length,
1733 largest_observed_length);
1734 if (!ack_info.nack_ranges.empty()) {
1735 ack_size += kNumberOfNackRangesSize + kNumberOfRevivedPacketsSize;
1736 ack_size += min(ack_info.nack_ranges.size(), kMaxNackRanges) *
1737 (missing_sequence_number_length + PACKET_1BYTE_SEQUENCE_NUMBER);
1738 ack_size += min(ack.revived_packets.size(),
1739 kMaxRevivedPackets) * largest_observed_length;
1742 // In version 23, if the ack will be truncated due to too many nack ranges,
1743 // then do not include the number of timestamps (1 byte).
1744 if (ack_info.nack_ranges.size() <= kMaxNackRanges) {
1745 // 1 byte for the number of timestamps.
1746 ack_size += 1;
1747 if (ack.received_packet_times.size() > 0) {
1748 // 1 byte for sequence number, 4 bytes for timestamp for the first
1749 // packet.
1750 ack_size += 5;
1752 // 1 byte for sequence number, 2 bytes for timestamp for the other
1753 // packets.
1754 ack_size += 3 * (ack.received_packet_times.size() - 1);
1758 return ack_size;
1761 size_t QuicFramer::ComputeFrameLength(
1762 const QuicFrame& frame,
1763 bool last_frame_in_packet,
1764 InFecGroup is_in_fec_group,
1765 QuicSequenceNumberLength sequence_number_length) {
1766 switch (frame.type) {
1767 case STREAM_FRAME:
1768 return GetMinStreamFrameSize(frame.stream_frame->stream_id,
1769 frame.stream_frame->offset,
1770 last_frame_in_packet, is_in_fec_group) +
1771 frame.stream_frame->data.length();
1772 case ACK_FRAME: {
1773 return GetAckFrameSize(*frame.ack_frame, sequence_number_length);
1775 case STOP_WAITING_FRAME:
1776 return GetStopWaitingFrameSize(sequence_number_length);
1777 case PING_FRAME:
1778 // Ping has no payload.
1779 return kQuicFrameTypeSize;
1780 case RST_STREAM_FRAME:
1781 if (quic_version_ <= QUIC_VERSION_24) {
1782 return GetMinRstStreamFrameSize() +
1783 frame.rst_stream_frame->error_details.size();
1785 return GetRstStreamFrameSize();
1786 case CONNECTION_CLOSE_FRAME:
1787 return GetMinConnectionCloseFrameSize() +
1788 frame.connection_close_frame->error_details.size();
1789 case GOAWAY_FRAME:
1790 return GetMinGoAwayFrameSize() + frame.goaway_frame->reason_phrase.size();
1791 case WINDOW_UPDATE_FRAME:
1792 return GetWindowUpdateFrameSize();
1793 case BLOCKED_FRAME:
1794 return GetBlockedFrameSize();
1795 case PADDING_FRAME:
1796 DCHECK(false);
1797 return 0;
1798 case NUM_FRAME_TYPES:
1799 DCHECK(false);
1800 return 0;
1803 // Not reachable, but some Chrome compilers can't figure that out. *sigh*
1804 DCHECK(false);
1805 return 0;
1808 bool QuicFramer::AppendTypeByte(const QuicFrame& frame,
1809 bool no_stream_frame_length,
1810 QuicDataWriter* writer) {
1811 uint8 type_byte = 0;
1812 switch (frame.type) {
1813 case STREAM_FRAME: {
1814 if (frame.stream_frame == nullptr) {
1815 LOG(DFATAL) << "Failed to append STREAM frame with no stream_frame.";
1817 // Fin bit.
1818 type_byte |= frame.stream_frame->fin ? kQuicStreamFinMask : 0;
1820 // Data Length bit.
1821 type_byte <<= kQuicStreamDataLengthShift;
1822 type_byte |= no_stream_frame_length ? 0: kQuicStreamDataLengthMask;
1824 // Offset 3 bits.
1825 type_byte <<= kQuicStreamOffsetShift;
1826 const size_t offset_len = GetStreamOffsetSize(frame.stream_frame->offset);
1827 if (offset_len > 0) {
1828 type_byte |= offset_len - 1;
1831 // stream id 2 bits.
1832 type_byte <<= kQuicStreamIdShift;
1833 type_byte |= GetStreamIdSize(frame.stream_frame->stream_id) - 1;
1834 type_byte |= kQuicFrameTypeStreamMask; // Set Stream Frame Type to 1.
1835 break;
1837 case ACK_FRAME:
1838 return true;
1839 default:
1840 type_byte = static_cast<uint8>(frame.type);
1841 break;
1844 return writer->WriteUInt8(type_byte);
1847 // static
1848 bool QuicFramer::AppendPacketSequenceNumber(
1849 QuicSequenceNumberLength sequence_number_length,
1850 QuicPacketSequenceNumber packet_sequence_number,
1851 QuicDataWriter* writer) {
1852 // Ensure the entire sequence number can be written.
1853 if (writer->capacity() - writer->length() <
1854 static_cast<size_t>(sequence_number_length)) {
1855 return false;
1857 switch (sequence_number_length) {
1858 case PACKET_1BYTE_SEQUENCE_NUMBER:
1859 return writer->WriteUInt8(
1860 packet_sequence_number & k1ByteSequenceNumberMask);
1861 break;
1862 case PACKET_2BYTE_SEQUENCE_NUMBER:
1863 return writer->WriteUInt16(
1864 packet_sequence_number & k2ByteSequenceNumberMask);
1865 break;
1866 case PACKET_4BYTE_SEQUENCE_NUMBER:
1867 return writer->WriteUInt32(
1868 packet_sequence_number & k4ByteSequenceNumberMask);
1869 break;
1870 case PACKET_6BYTE_SEQUENCE_NUMBER:
1871 return writer->WriteUInt48(
1872 packet_sequence_number & k6ByteSequenceNumberMask);
1873 break;
1874 default:
1875 DCHECK(false) << "sequence_number_length: " << sequence_number_length;
1876 return false;
1880 bool QuicFramer::AppendStreamFrame(
1881 const QuicStreamFrame& frame,
1882 bool no_stream_frame_length,
1883 QuicDataWriter* writer) {
1884 if (!writer->WriteBytes(&frame.stream_id, GetStreamIdSize(frame.stream_id))) {
1885 LOG(DFATAL) << "Writing stream id size failed.";
1886 return false;
1888 if (!writer->WriteBytes(&frame.offset, GetStreamOffsetSize(frame.offset))) {
1889 LOG(DFATAL) << "Writing offset size failed.";
1890 return false;
1892 if (!no_stream_frame_length) {
1893 if ((frame.data.size() > numeric_limits<uint16>::max()) ||
1894 !writer->WriteUInt16(static_cast<uint16>(frame.data.size()))) {
1895 LOG(DFATAL) << "Writing stream frame length failed";
1896 return false;
1900 if (!writer->WriteBytes(frame.data.data(), frame.data.size())) {
1901 LOG(DFATAL) << "Writing frame data failed.";
1902 return false;
1904 return true;
1907 void QuicFramer::set_version(const QuicVersion version) {
1908 DCHECK(IsSupportedVersion(version)) << QuicVersionToString(version);
1909 quic_version_ = version;
1912 bool QuicFramer::AppendAckFrameAndTypeByte(
1913 const QuicPacketHeader& header,
1914 const QuicAckFrame& frame,
1915 QuicDataWriter* writer) {
1916 AckFrameInfo ack_info = GetAckFrameInfo(frame);
1917 QuicPacketSequenceNumber ack_largest_observed = frame.largest_observed;
1918 QuicSequenceNumberLength largest_observed_length =
1919 GetMinSequenceNumberLength(ack_largest_observed);
1920 QuicSequenceNumberLength missing_sequence_number_length =
1921 GetMinSequenceNumberLength(ack_info.max_delta);
1922 // Determine whether we need to truncate ranges.
1923 size_t available_range_bytes = writer->capacity() - writer->length() -
1924 kNumberOfRevivedPacketsSize - kNumberOfNackRangesSize -
1925 GetMinAckFrameSize(header.public_header.sequence_number_length,
1926 largest_observed_length);
1927 size_t max_num_ranges = available_range_bytes /
1928 (missing_sequence_number_length + PACKET_1BYTE_SEQUENCE_NUMBER);
1929 max_num_ranges = min(kMaxNackRanges, max_num_ranges);
1930 bool truncated = ack_info.nack_ranges.size() > max_num_ranges;
1931 DVLOG_IF(1, truncated) << "Truncating ack from "
1932 << ack_info.nack_ranges.size() << " ranges to "
1933 << max_num_ranges;
1934 // Write out the type byte by setting the low order bits and doing shifts
1935 // to make room for the next bit flags to be set.
1936 // Whether there are any nacks.
1937 uint8 type_byte = ack_info.nack_ranges.empty() ? 0 : kQuicHasNacksMask;
1939 // truncating bit.
1940 type_byte <<= kQuicAckTruncatedShift;
1941 type_byte |= truncated ? kQuicAckTruncatedMask : 0;
1943 // Largest observed sequence number length.
1944 type_byte <<= kQuicSequenceNumberLengthShift;
1945 type_byte |= GetSequenceNumberFlags(largest_observed_length);
1947 // Missing sequence number length.
1948 type_byte <<= kQuicSequenceNumberLengthShift;
1949 type_byte |= GetSequenceNumberFlags(missing_sequence_number_length);
1951 type_byte |= kQuicFrameTypeAckMask;
1953 if (!writer->WriteUInt8(type_byte)) {
1954 return false;
1957 QuicPacketEntropyHash ack_entropy_hash = frame.entropy_hash;
1958 NackRangeMap::reverse_iterator ack_iter = ack_info.nack_ranges.rbegin();
1959 if (truncated) {
1960 // Skip the nack ranges which the truncated ack won't include and set
1961 // a correct largest observed for the truncated ack.
1962 for (size_t i = 1; i < (ack_info.nack_ranges.size() - max_num_ranges);
1963 ++i) {
1964 ++ack_iter;
1966 // If the last range is followed by acks, include them.
1967 // If the last range is followed by another range, specify the end of the
1968 // range as the largest_observed.
1969 ack_largest_observed = ack_iter->first - 1;
1970 // Also update the entropy so it matches the largest observed.
1971 ack_entropy_hash = entropy_calculator_->EntropyHash(ack_largest_observed);
1972 ++ack_iter;
1975 if (!writer->WriteUInt8(ack_entropy_hash)) {
1976 return false;
1979 if (!AppendPacketSequenceNumber(largest_observed_length,
1980 ack_largest_observed, writer)) {
1981 return false;
1984 uint64 delta_time_largest_observed_us = kUFloat16MaxValue;
1985 if (!frame.delta_time_largest_observed.IsInfinite()) {
1986 DCHECK_LE(0u, frame.delta_time_largest_observed.ToMicroseconds());
1987 delta_time_largest_observed_us =
1988 frame.delta_time_largest_observed.ToMicroseconds();
1991 if (!writer->WriteUFloat16(delta_time_largest_observed_us)) {
1992 return false;
1995 // Timestamp goes at the end of the required fields.
1996 if (!truncated) {
1997 if (!AppendTimestampToAckFrame(frame, writer)) {
1998 return false;
2002 if (ack_info.nack_ranges.empty()) {
2003 return true;
2006 const uint8 num_missing_ranges =
2007 static_cast<uint8>(min(ack_info.nack_ranges.size(), max_num_ranges));
2008 if (!writer->WriteBytes(&num_missing_ranges, 1)) {
2009 return false;
2012 int num_ranges_written = 0;
2013 QuicPacketSequenceNumber last_sequence_written = ack_largest_observed;
2014 for (; ack_iter != ack_info.nack_ranges.rend(); ++ack_iter) {
2015 // Calculate the delta to the last number in the range.
2016 QuicPacketSequenceNumber missing_delta =
2017 last_sequence_written - (ack_iter->first + ack_iter->second);
2018 if (!AppendPacketSequenceNumber(missing_sequence_number_length,
2019 missing_delta, writer)) {
2020 return false;
2022 if (!AppendPacketSequenceNumber(PACKET_1BYTE_SEQUENCE_NUMBER,
2023 ack_iter->second, writer)) {
2024 return false;
2026 // Subtract 1 so a missing_delta of 0 means an adjacent range.
2027 last_sequence_written = ack_iter->first - 1;
2028 ++num_ranges_written;
2030 DCHECK_EQ(num_missing_ranges, num_ranges_written);
2032 // Append revived packets.
2033 // If not all the revived packets fit, only mention the ones that do.
2034 uint8 num_revived_packets =
2035 static_cast<uint8>(min(frame.revived_packets.size(), kMaxRevivedPackets));
2036 num_revived_packets = static_cast<uint8>(min(
2037 static_cast<size_t>(num_revived_packets),
2038 (writer->capacity() - writer->length()) / largest_observed_length));
2039 if (!writer->WriteBytes(&num_revived_packets, 1)) {
2040 return false;
2043 SequenceNumberSet::const_iterator iter = frame.revived_packets.begin();
2044 for (int i = 0; i < num_revived_packets; ++i, ++iter) {
2045 LOG_IF(DFATAL, !ContainsKey(frame.missing_packets, *iter));
2046 if (!AppendPacketSequenceNumber(largest_observed_length,
2047 *iter, writer)) {
2048 return false;
2052 return true;
2055 bool QuicFramer::AppendTimestampToAckFrame(const QuicAckFrame& frame,
2056 QuicDataWriter* writer) {
2057 DCHECK_GE(numeric_limits<uint8>::max(), frame.received_packet_times.size());
2058 // num_received_packets is only 1 byte.
2059 if (frame.received_packet_times.size() > numeric_limits<uint8>::max()) {
2060 return false;
2063 uint8 num_received_packets = frame.received_packet_times.size();
2065 if (!writer->WriteBytes(&num_received_packets, 1)) {
2066 return false;
2068 if (num_received_packets == 0) {
2069 return true;
2072 PacketTimeList::const_iterator it = frame.received_packet_times.begin();
2073 QuicPacketSequenceNumber sequence_number = it->first;
2074 QuicPacketSequenceNumber delta_from_largest_observed =
2075 frame.largest_observed - sequence_number;
2077 DCHECK_GE(numeric_limits<uint8>::max(), delta_from_largest_observed);
2078 if (delta_from_largest_observed > numeric_limits<uint8>::max()) {
2079 return false;
2082 if (!writer->WriteUInt8(
2083 delta_from_largest_observed & k1ByteSequenceNumberMask)) {
2084 return false;
2087 // Use the lowest 4 bytes of the time delta from the creation_time_.
2088 const uint64 time_epoch_delta_us = UINT64_C(1) << 32;
2089 uint32 time_delta_us =
2090 static_cast<uint32>(it->second.Subtract(creation_time_).ToMicroseconds()
2091 & (time_epoch_delta_us - 1));
2092 if (!writer->WriteBytes(&time_delta_us, sizeof(time_delta_us))) {
2093 return false;
2096 QuicTime prev_time = it->second;
2098 for (++it; it != frame.received_packet_times.end(); ++it) {
2099 sequence_number = it->first;
2100 delta_from_largest_observed = frame.largest_observed - sequence_number;
2102 if (delta_from_largest_observed > numeric_limits<uint8>::max()) {
2103 return false;
2106 if (!writer->WriteUInt8(
2107 delta_from_largest_observed & k1ByteSequenceNumberMask)) {
2108 return false;
2111 uint64 frame_time_delta_us =
2112 it->second.Subtract(prev_time).ToMicroseconds();
2113 prev_time = it->second;
2114 if (!writer->WriteUFloat16(frame_time_delta_us)) {
2115 return false;
2118 return true;
2121 bool QuicFramer::AppendStopWaitingFrame(
2122 const QuicPacketHeader& header,
2123 const QuicStopWaitingFrame& frame,
2124 QuicDataWriter* writer) {
2125 DCHECK_GE(header.packet_sequence_number, frame.least_unacked);
2126 const QuicPacketSequenceNumber least_unacked_delta =
2127 header.packet_sequence_number - frame.least_unacked;
2128 const QuicPacketSequenceNumber length_shift =
2129 header.public_header.sequence_number_length * 8;
2130 if (!writer->WriteUInt8(frame.entropy_hash)) {
2131 LOG(DFATAL) << " hash failed";
2132 return false;
2135 if (least_unacked_delta >> length_shift > 0) {
2136 LOG(DFATAL) << "sequence_number_length "
2137 << header.public_header.sequence_number_length
2138 << " is too small for least_unacked_delta: "
2139 << least_unacked_delta;
2140 return false;
2142 if (!AppendPacketSequenceNumber(header.public_header.sequence_number_length,
2143 least_unacked_delta, writer)) {
2144 LOG(DFATAL) << " seq failed: "
2145 << header.public_header.sequence_number_length;
2146 return false;
2149 return true;
2152 bool QuicFramer::AppendRstStreamFrame(const QuicRstStreamFrame& frame,
2153 QuicDataWriter* writer) {
2154 if (!writer->WriteUInt32(frame.stream_id)) {
2155 return false;
2158 if (!writer->WriteUInt64(frame.byte_offset)) {
2159 return false;
2162 uint32 error_code = static_cast<uint32>(frame.error_code);
2163 if (!writer->WriteUInt32(error_code)) {
2164 return false;
2167 if (quic_version_ <= QUIC_VERSION_24) {
2168 if (!writer->WriteStringPiece16(frame.error_details)) {
2169 return false;
2172 return true;
2175 bool QuicFramer::AppendConnectionCloseFrame(
2176 const QuicConnectionCloseFrame& frame,
2177 QuicDataWriter* writer) {
2178 uint32 error_code = static_cast<uint32>(frame.error_code);
2179 if (!writer->WriteUInt32(error_code)) {
2180 return false;
2182 if (!writer->WriteStringPiece16(frame.error_details)) {
2183 return false;
2185 return true;
2188 bool QuicFramer::AppendGoAwayFrame(const QuicGoAwayFrame& frame,
2189 QuicDataWriter* writer) {
2190 uint32 error_code = static_cast<uint32>(frame.error_code);
2191 if (!writer->WriteUInt32(error_code)) {
2192 return false;
2194 uint32 stream_id = static_cast<uint32>(frame.last_good_stream_id);
2195 if (!writer->WriteUInt32(stream_id)) {
2196 return false;
2198 if (!writer->WriteStringPiece16(frame.reason_phrase)) {
2199 return false;
2201 return true;
2204 bool QuicFramer::AppendWindowUpdateFrame(const QuicWindowUpdateFrame& frame,
2205 QuicDataWriter* writer) {
2206 uint32 stream_id = static_cast<uint32>(frame.stream_id);
2207 if (!writer->WriteUInt32(stream_id)) {
2208 return false;
2210 if (!writer->WriteUInt64(frame.byte_offset)) {
2211 return false;
2213 return true;
2216 bool QuicFramer::AppendBlockedFrame(const QuicBlockedFrame& frame,
2217 QuicDataWriter* writer) {
2218 uint32 stream_id = static_cast<uint32>(frame.stream_id);
2219 if (!writer->WriteUInt32(stream_id)) {
2220 return false;
2222 return true;
2225 bool QuicFramer::RaiseError(QuicErrorCode error) {
2226 DVLOG(1) << "Error: " << QuicUtils::ErrorToString(error)
2227 << " detail: " << detailed_error_;
2228 set_error(error);
2229 visitor_->OnError(this);
2230 reader_.reset(nullptr);
2231 return false;
2234 } // namespace net