ozone: evdev: Sync caps lock LED state to evdev
[chromium-blink-merge.git] / net / quic / quic_framer.cc
blob4d387cf4183d87a178512ff460dd45bd291cd15d
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "net/quic/quic_framer.h"
7 #include "base/containers/hash_tables.h"
8 #include "base/stl_util.h"
9 #include "net/quic/crypto/crypto_framer.h"
10 #include "net/quic/crypto/crypto_handshake_message.h"
11 #include "net/quic/crypto/crypto_protocol.h"
12 #include "net/quic/crypto/quic_decrypter.h"
13 #include "net/quic/crypto/quic_encrypter.h"
14 #include "net/quic/quic_data_reader.h"
15 #include "net/quic/quic_data_writer.h"
16 #include "net/quic/quic_flags.h"
17 #include "net/quic/quic_socket_address_coder.h"
19 using base::StringPiece;
20 using std::map;
21 using std::max;
22 using std::min;
23 using std::numeric_limits;
24 using std::string;
26 namespace net {
28 namespace {
30 // Mask to select the lowest 48 bits of a sequence number.
31 const QuicPacketSequenceNumber k6ByteSequenceNumberMask =
32 GG_UINT64_C(0x0000FFFFFFFFFFFF);
33 const QuicPacketSequenceNumber k4ByteSequenceNumberMask =
34 GG_UINT64_C(0x00000000FFFFFFFF);
35 const QuicPacketSequenceNumber k2ByteSequenceNumberMask =
36 GG_UINT64_C(0x000000000000FFFF);
37 const QuicPacketSequenceNumber k1ByteSequenceNumberMask =
38 GG_UINT64_C(0x00000000000000FF);
40 const QuicConnectionId k1ByteConnectionIdMask = GG_UINT64_C(0x00000000000000FF);
41 const QuicConnectionId k4ByteConnectionIdMask = GG_UINT64_C(0x00000000FFFFFFFF);
43 // Number of bits the sequence number length bits are shifted from the right
44 // edge of the public header.
45 const uint8 kPublicHeaderSequenceNumberShift = 4;
47 // New Frame Types, QUIC v. >= 10:
48 // There are two interpretations for the Frame Type byte in the QUIC protocol,
49 // resulting in two Frame Types: Special Frame Types and Regular Frame Types.
51 // Regular Frame Types use the Frame Type byte simply. Currently defined
52 // Regular Frame Types are:
53 // Padding : 0b 00000000 (0x00)
54 // ResetStream : 0b 00000001 (0x01)
55 // ConnectionClose : 0b 00000010 (0x02)
56 // GoAway : 0b 00000011 (0x03)
57 // WindowUpdate : 0b 00000100 (0x04)
58 // Blocked : 0b 00000101 (0x05)
60 // Special Frame Types encode both a Frame Type and corresponding flags
61 // all in the Frame Type byte. Currently defined Special Frame Types are:
62 // Stream : 0b 1xxxxxxx
63 // Ack : 0b 01xxxxxx
65 // Semantics of the flag bits above (the x bits) depends on the frame type.
67 // Masks to determine if the frame type is a special use
68 // and for specific special frame types.
69 const uint8 kQuicFrameTypeSpecialMask = 0xE0; // 0b 11100000
70 const uint8 kQuicFrameTypeStreamMask = 0x80;
71 const uint8 kQuicFrameTypeAckMask = 0x40;
73 // Stream frame relative shifts and masks for interpreting the stream flags.
74 // StreamID may be 1, 2, 3, or 4 bytes.
75 const uint8 kQuicStreamIdShift = 2;
76 const uint8 kQuicStreamIDLengthMask = 0x03;
78 // Offset may be 0, 2, 3, 4, 5, 6, 7, 8 bytes.
79 const uint8 kQuicStreamOffsetShift = 3;
80 const uint8 kQuicStreamOffsetMask = 0x07;
82 // Data length may be 0 or 2 bytes.
83 const uint8 kQuicStreamDataLengthShift = 1;
84 const uint8 kQuicStreamDataLengthMask = 0x01;
86 // Fin bit may be set or not.
87 const uint8 kQuicStreamFinShift = 1;
88 const uint8 kQuicStreamFinMask = 0x01;
90 // Sequence number size shift used in AckFrames.
91 const uint8 kQuicSequenceNumberLengthShift = 2;
93 // Acks may be truncated.
94 const uint8 kQuicAckTruncatedShift = 1;
95 const uint8 kQuicAckTruncatedMask = 0x01;
97 // Acks may not have any nacks.
98 const uint8 kQuicHasNacksMask = 0x01;
100 // Returns the absolute value of the difference between |a| and |b|.
101 QuicPacketSequenceNumber Delta(QuicPacketSequenceNumber a,
102 QuicPacketSequenceNumber b) {
103 // Since these are unsigned numbers, we can't just return abs(a - b)
104 if (a < b) {
105 return b - a;
107 return a - b;
110 QuicPacketSequenceNumber ClosestTo(QuicPacketSequenceNumber target,
111 QuicPacketSequenceNumber a,
112 QuicPacketSequenceNumber b) {
113 return (Delta(target, a) < Delta(target, b)) ? a : b;
116 QuicSequenceNumberLength ReadSequenceNumberLength(uint8 flags) {
117 switch (flags & PACKET_FLAGS_6BYTE_SEQUENCE) {
118 case PACKET_FLAGS_6BYTE_SEQUENCE:
119 return PACKET_6BYTE_SEQUENCE_NUMBER;
120 case PACKET_FLAGS_4BYTE_SEQUENCE:
121 return PACKET_4BYTE_SEQUENCE_NUMBER;
122 case PACKET_FLAGS_2BYTE_SEQUENCE:
123 return PACKET_2BYTE_SEQUENCE_NUMBER;
124 case PACKET_FLAGS_1BYTE_SEQUENCE:
125 return PACKET_1BYTE_SEQUENCE_NUMBER;
126 default:
127 LOG(DFATAL) << "Unreachable case statement.";
128 return PACKET_6BYTE_SEQUENCE_NUMBER;
132 } // namespace
134 bool QuicFramerVisitorInterface::OnWindowUpdateFrame(
135 const QuicWindowUpdateFrame& frame) {
136 return true;
139 bool QuicFramerVisitorInterface::OnBlockedFrame(const QuicBlockedFrame& frame) {
140 return true;
143 QuicFramer::QuicFramer(const QuicVersionVector& supported_versions,
144 QuicTime creation_time,
145 bool is_server)
146 : visitor_(nullptr),
147 fec_builder_(nullptr),
148 entropy_calculator_(nullptr),
149 error_(QUIC_NO_ERROR),
150 last_sequence_number_(0),
151 last_serialized_connection_id_(0),
152 supported_versions_(supported_versions),
153 decrypter_level_(ENCRYPTION_NONE),
154 alternative_decrypter_level_(ENCRYPTION_NONE),
155 alternative_decrypter_latch_(false),
156 is_server_(is_server),
157 validate_flags_(true),
158 creation_time_(creation_time),
159 last_timestamp_(QuicTime::Delta::Zero()) {
160 DCHECK(!supported_versions.empty());
161 quic_version_ = supported_versions_[0];
162 decrypter_.reset(QuicDecrypter::Create(kNULL));
163 encrypter_[ENCRYPTION_NONE].reset(QuicEncrypter::Create(kNULL));
166 QuicFramer::~QuicFramer() {}
168 // static
169 size_t QuicFramer::GetMinStreamFrameSize(QuicStreamId stream_id,
170 QuicStreamOffset offset,
171 bool last_frame_in_packet,
172 InFecGroup is_in_fec_group) {
173 bool no_stream_frame_length = last_frame_in_packet &&
174 is_in_fec_group == NOT_IN_FEC_GROUP;
175 return kQuicFrameTypeSize + GetStreamIdSize(stream_id) +
176 GetStreamOffsetSize(offset) +
177 (no_stream_frame_length ? 0 : kQuicStreamPayloadLengthSize);
180 // static
181 size_t QuicFramer::GetMinAckFrameSize(
182 QuicSequenceNumberLength sequence_number_length,
183 QuicSequenceNumberLength largest_observed_length) {
184 return kQuicFrameTypeSize + kQuicEntropyHashSize +
185 largest_observed_length + kQuicDeltaTimeLargestObservedSize;
188 // static
189 size_t QuicFramer::GetStopWaitingFrameSize(
190 QuicSequenceNumberLength sequence_number_length) {
191 return kQuicFrameTypeSize + kQuicEntropyHashSize +
192 sequence_number_length;
195 // static
196 size_t QuicFramer::GetMinRstStreamFrameSize() {
197 return kQuicFrameTypeSize + kQuicMaxStreamIdSize +
198 kQuicMaxStreamOffsetSize + kQuicErrorCodeSize +
199 kQuicErrorDetailsLengthSize;
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 if (frame.type == PADDING_FRAME) {
277 // PADDING implies end of packet.
278 return free_bytes;
280 size_t frame_len =
281 ComputeFrameLength(frame, last_frame, is_in_fec_group,
282 sequence_number_length);
283 if (frame_len <= free_bytes) {
284 // Frame fits within packet. Note that acks may be truncated.
285 return frame_len;
287 // Only truncate the first frame in a packet, so if subsequent ones go
288 // over, stop including more frames.
289 if (!first_frame) {
290 return 0;
292 bool can_truncate = frame.type == ACK_FRAME &&
293 free_bytes >= GetMinAckFrameSize(PACKET_6BYTE_SEQUENCE_NUMBER,
294 PACKET_6BYTE_SEQUENCE_NUMBER);
295 if (can_truncate) {
296 // Truncate the frame so the packet will not exceed kMaxPacketSize.
297 // Note that we may not use every byte of the writer in this case.
298 DVLOG(1) << "Truncating large frame, free bytes: " << free_bytes;
299 return free_bytes;
301 if (!FLAGS_quic_allow_oversized_packets_for_test) {
302 return 0;
304 LOG(DFATAL) << "Packet size too small to fit frame.";
305 return frame_len;
308 QuicFramer::AckFrameInfo::AckFrameInfo() : max_delta(0) {}
310 QuicFramer::AckFrameInfo::~AckFrameInfo() {}
312 // static
313 QuicPacketEntropyHash QuicFramer::GetPacketEntropyHash(
314 const QuicPacketHeader& header) {
315 return header.entropy_flag << (header.packet_sequence_number % 8);
318 QuicPacket* QuicFramer::BuildDataPacket(const QuicPacketHeader& header,
319 const QuicFrames& frames,
320 char* buffer,
321 size_t packet_length) {
322 QuicDataWriter writer(packet_length, buffer);
323 if (!AppendPacketHeader(header, &writer)) {
324 LOG(DFATAL) << "AppendPacketHeader failed";
325 return nullptr;
328 size_t i = 0;
329 for (const QuicFrame& frame : frames) {
330 // Determine if we should write stream frame length in header.
331 const bool no_stream_frame_length =
332 (header.is_in_fec_group == NOT_IN_FEC_GROUP) &&
333 (i == frames.size() - 1);
334 if (!AppendTypeByte(frame, no_stream_frame_length, &writer)) {
335 LOG(DFATAL) << "AppendTypeByte failed";
336 return nullptr;
339 switch (frame.type) {
340 case PADDING_FRAME:
341 writer.WritePadding();
342 break;
343 case STREAM_FRAME:
344 if (!AppendStreamFrame(
345 *frame.stream_frame, no_stream_frame_length, &writer)) {
346 LOG(DFATAL) << "AppendStreamFrame failed";
347 return nullptr;
349 break;
350 case ACK_FRAME:
351 if (!AppendAckFrameAndTypeByte(
352 header, *frame.ack_frame, &writer)) {
353 LOG(DFATAL) << "AppendAckFrameAndTypeByte failed";
354 return nullptr;
356 break;
357 case STOP_WAITING_FRAME:
358 if (!AppendStopWaitingFrame(
359 header, *frame.stop_waiting_frame, &writer)) {
360 LOG(DFATAL) << "AppendStopWaitingFrame failed";
361 return nullptr;
363 break;
364 case PING_FRAME:
365 // Ping has no payload.
366 break;
367 case RST_STREAM_FRAME:
368 if (!AppendRstStreamFrame(*frame.rst_stream_frame, &writer)) {
369 LOG(DFATAL) << "AppendRstStreamFrame failed";
370 return nullptr;
372 break;
373 case CONNECTION_CLOSE_FRAME:
374 if (!AppendConnectionCloseFrame(
375 *frame.connection_close_frame, &writer)) {
376 LOG(DFATAL) << "AppendConnectionCloseFrame failed";
377 return nullptr;
379 break;
380 case GOAWAY_FRAME:
381 if (!AppendGoAwayFrame(*frame.goaway_frame, &writer)) {
382 LOG(DFATAL) << "AppendGoAwayFrame failed";
383 return nullptr;
385 break;
386 case WINDOW_UPDATE_FRAME:
387 if (!AppendWindowUpdateFrame(*frame.window_update_frame, &writer)) {
388 LOG(DFATAL) << "AppendWindowUpdateFrame failed";
389 return nullptr;
391 break;
392 case BLOCKED_FRAME:
393 if (!AppendBlockedFrame(*frame.blocked_frame, &writer)) {
394 LOG(DFATAL) << "AppendBlockedFrame failed";
395 return nullptr;
397 break;
398 default:
399 RaiseError(QUIC_INVALID_FRAME_DATA);
400 LOG(DFATAL) << "QUIC_INVALID_FRAME_DATA";
401 return nullptr;
403 ++i;
406 QuicPacket* packet =
407 new QuicPacket(writer.data(), writer.length(), false,
408 header.public_header.connection_id_length,
409 header.public_header.version_flag,
410 header.public_header.sequence_number_length);
412 if (fec_builder_) {
413 fec_builder_->OnBuiltFecProtectedPayload(header,
414 packet->FecProtectedData());
417 return packet;
420 QuicPacket* QuicFramer::BuildFecPacket(const QuicPacketHeader& header,
421 const QuicFecData& fec) {
422 DCHECK_EQ(IN_FEC_GROUP, header.is_in_fec_group);
423 DCHECK_NE(0u, header.fec_group);
424 size_t len = GetPacketHeaderSize(header);
425 len += fec.redundancy.length();
427 scoped_ptr<char[]> buffer(new char[len]);
428 QuicDataWriter writer(len, buffer.get());
429 if (!AppendPacketHeader(header, &writer)) {
430 LOG(DFATAL) << "AppendPacketHeader failed";
431 return nullptr;
434 if (!writer.WriteBytes(fec.redundancy.data(), fec.redundancy.length())) {
435 LOG(DFATAL) << "Failed to add FEC";
436 return nullptr;
439 return new QuicPacket(buffer.release(), len, true,
440 header.public_header.connection_id_length,
441 header.public_header.version_flag,
442 header.public_header.sequence_number_length);
445 // static
446 QuicEncryptedPacket* QuicFramer::BuildPublicResetPacket(
447 const QuicPublicResetPacket& packet) {
448 DCHECK(packet.public_header.reset_flag);
450 CryptoHandshakeMessage reset;
451 reset.set_tag(kPRST);
452 reset.SetValue(kRNON, packet.nonce_proof);
453 reset.SetValue(kRSEQ, packet.rejected_sequence_number);
454 if (!packet.client_address.address().empty()) {
455 // packet.client_address is non-empty.
456 QuicSocketAddressCoder address_coder(packet.client_address);
457 string serialized_address = address_coder.Encode();
458 if (serialized_address.empty()) {
459 return nullptr;
461 reset.SetStringPiece(kCADR, serialized_address);
463 const QuicData& reset_serialized = reset.GetSerialized();
465 size_t len =
466 kPublicFlagsSize + PACKET_8BYTE_CONNECTION_ID + reset_serialized.length();
467 scoped_ptr<char[]> buffer(new char[len]);
468 QuicDataWriter writer(len, buffer.get());
470 uint8 flags = static_cast<uint8>(PACKET_PUBLIC_FLAGS_RST |
471 PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID);
472 if (!writer.WriteUInt8(flags)) {
473 return nullptr;
476 if (!writer.WriteUInt64(packet.public_header.connection_id)) {
477 return nullptr;
480 if (!writer.WriteBytes(reset_serialized.data(), reset_serialized.length())) {
481 return nullptr;
484 return new QuicEncryptedPacket(buffer.release(), len, true);
487 QuicEncryptedPacket* QuicFramer::BuildVersionNegotiationPacket(
488 const QuicPacketPublicHeader& header,
489 const QuicVersionVector& supported_versions) {
490 DCHECK(header.version_flag);
491 size_t len = GetVersionNegotiationPacketSize(supported_versions.size());
492 scoped_ptr<char[]> buffer(new char[len]);
493 QuicDataWriter writer(len, buffer.get());
495 uint8 flags = static_cast<uint8>(PACKET_PUBLIC_FLAGS_VERSION |
496 PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID);
497 if (!writer.WriteUInt8(flags)) {
498 return nullptr;
501 if (!writer.WriteUInt64(header.connection_id)) {
502 return nullptr;
505 for (size_t i = 0; i < supported_versions.size(); ++i) {
506 if (!writer.WriteUInt32(QuicVersionToQuicTag(supported_versions[i]))) {
507 return nullptr;
511 return new QuicEncryptedPacket(buffer.release(), len, true);
514 bool QuicFramer::ProcessPacket(const QuicEncryptedPacket& packet) {
515 DCHECK(!reader_.get());
516 reader_.reset(new QuicDataReader(packet.data(), packet.length()));
518 visitor_->OnPacket();
520 // First parse the public header.
521 QuicPacketPublicHeader public_header;
522 if (!ProcessPublicHeader(&public_header)) {
523 DLOG(WARNING) << "Unable to process public header.";
524 DCHECK_NE("", detailed_error_);
525 return RaiseError(QUIC_INVALID_PACKET_HEADER);
528 if (!visitor_->OnUnauthenticatedPublicHeader(public_header)) {
529 // The visitor suppresses further processing of the packet.
530 reader_.reset(nullptr);
531 return true;
534 if (is_server_ && public_header.version_flag &&
535 public_header.versions[0] != quic_version_) {
536 if (!visitor_->OnProtocolVersionMismatch(public_header.versions[0])) {
537 reader_.reset(nullptr);
538 return true;
542 bool rv;
543 if (!is_server_ && public_header.version_flag) {
544 rv = ProcessVersionNegotiationPacket(&public_header);
545 } else if (public_header.reset_flag) {
546 rv = ProcessPublicResetPacket(public_header);
547 } else if (packet.length() <= kMaxPacketSize) {
548 char buffer[kMaxPacketSize];
549 rv = ProcessDataPacket(public_header, packet, buffer, kMaxPacketSize);
550 } else {
551 scoped_ptr<char[]> large_buffer(new char[packet.length()]);
552 rv = ProcessDataPacket(public_header, packet, large_buffer.get(),
553 packet.length());
554 LOG_IF(DFATAL, rv) << "QUIC should never successfully process packets "
555 << "larger than kMaxPacketSize. packet size:"
556 << packet.length();
559 reader_.reset(nullptr);
560 return rv;
563 bool QuicFramer::ProcessVersionNegotiationPacket(
564 QuicPacketPublicHeader* public_header) {
565 DCHECK(!is_server_);
566 // Try reading at least once to raise error if the packet is invalid.
567 do {
568 QuicTag version;
569 if (!reader_->ReadBytes(&version, kQuicVersionSize)) {
570 set_detailed_error("Unable to read supported version in negotiation.");
571 return RaiseError(QUIC_INVALID_VERSION_NEGOTIATION_PACKET);
573 public_header->versions.push_back(QuicTagToQuicVersion(version));
574 } while (!reader_->IsDoneReading());
576 visitor_->OnVersionNegotiationPacket(*public_header);
577 return true;
580 bool QuicFramer::ProcessDataPacket(const QuicPacketPublicHeader& public_header,
581 const QuicEncryptedPacket& packet,
582 char* decrypted_buffer,
583 size_t buffer_length) {
584 QuicPacketHeader header(public_header);
585 if (!ProcessPacketHeader(&header, packet, decrypted_buffer, buffer_length)) {
586 DLOG(WARNING) << "Unable to process data packet header.";
587 return false;
590 if (!visitor_->OnPacketHeader(header)) {
591 // The visitor suppresses further processing of the packet.
592 return true;
595 if (packet.length() > kMaxPacketSize) {
596 DLOG(WARNING) << "Packet too large: " << packet.length();
597 return RaiseError(QUIC_PACKET_TOO_LARGE);
600 // Handle the payload.
601 if (!header.fec_flag) {
602 if (header.is_in_fec_group == IN_FEC_GROUP) {
603 StringPiece payload = reader_->PeekRemainingPayload();
604 visitor_->OnFecProtectedPayload(payload);
606 if (!ProcessFrameData(header)) {
607 DCHECK_NE(QUIC_NO_ERROR, error_); // ProcessFrameData sets the error.
608 DLOG(WARNING) << "Unable to process frame data.";
609 return false;
611 } else {
612 QuicFecData fec_data;
613 fec_data.fec_group = header.fec_group;
614 fec_data.redundancy = reader_->ReadRemainingPayload();
615 visitor_->OnFecData(fec_data);
618 visitor_->OnPacketComplete();
619 return true;
622 bool QuicFramer::ProcessPublicResetPacket(
623 const QuicPacketPublicHeader& public_header) {
624 QuicPublicResetPacket packet(public_header);
626 scoped_ptr<CryptoHandshakeMessage> reset(
627 CryptoFramer::ParseMessage(reader_->ReadRemainingPayload()));
628 if (!reset.get()) {
629 set_detailed_error("Unable to read reset message.");
630 return RaiseError(QUIC_INVALID_PUBLIC_RST_PACKET);
632 if (reset->tag() != kPRST) {
633 set_detailed_error("Incorrect message tag.");
634 return RaiseError(QUIC_INVALID_PUBLIC_RST_PACKET);
637 if (reset->GetUint64(kRNON, &packet.nonce_proof) != QUIC_NO_ERROR) {
638 set_detailed_error("Unable to read nonce proof.");
639 return RaiseError(QUIC_INVALID_PUBLIC_RST_PACKET);
641 // TODO(satyamshekhar): validate nonce to protect against DoS.
643 if (reset->GetUint64(kRSEQ, &packet.rejected_sequence_number) !=
644 QUIC_NO_ERROR) {
645 set_detailed_error("Unable to read rejected sequence number.");
646 return RaiseError(QUIC_INVALID_PUBLIC_RST_PACKET);
649 StringPiece address;
650 if (reset->GetStringPiece(kCADR, &address)) {
651 QuicSocketAddressCoder address_coder;
652 if (address_coder.Decode(address.data(), address.length())) {
653 packet.client_address = IPEndPoint(address_coder.ip(),
654 address_coder.port());
658 visitor_->OnPublicResetPacket(packet);
659 return true;
662 bool QuicFramer::ProcessRevivedPacket(QuicPacketHeader* header,
663 StringPiece payload) {
664 DCHECK(!reader_.get());
666 visitor_->OnRevivedPacket();
668 header->entropy_hash = GetPacketEntropyHash(*header);
670 if (!visitor_->OnPacketHeader(*header)) {
671 return true;
674 if (payload.length() > kMaxPacketSize) {
675 set_detailed_error("Revived packet too large.");
676 return RaiseError(QUIC_PACKET_TOO_LARGE);
679 reader_.reset(new QuicDataReader(payload.data(), payload.length()));
680 if (!ProcessFrameData(*header)) {
681 DCHECK_NE(QUIC_NO_ERROR, error_); // ProcessFrameData sets the error.
682 DLOG(WARNING) << "Unable to process frame data.";
683 return false;
686 visitor_->OnPacketComplete();
687 reader_.reset(nullptr);
688 return true;
691 bool QuicFramer::AppendPacketHeader(const QuicPacketHeader& header,
692 QuicDataWriter* writer) {
693 DVLOG(1) << "Appending header: " << header;
694 DCHECK(header.fec_group > 0 || header.is_in_fec_group == NOT_IN_FEC_GROUP);
695 uint8 public_flags = 0;
696 if (header.public_header.reset_flag) {
697 public_flags |= PACKET_PUBLIC_FLAGS_RST;
699 if (header.public_header.version_flag) {
700 public_flags |= PACKET_PUBLIC_FLAGS_VERSION;
703 public_flags |=
704 GetSequenceNumberFlags(header.public_header.sequence_number_length)
705 << kPublicHeaderSequenceNumberShift;
707 switch (header.public_header.connection_id_length) {
708 case PACKET_0BYTE_CONNECTION_ID:
709 if (!writer->WriteUInt8(
710 public_flags | PACKET_PUBLIC_FLAGS_0BYTE_CONNECTION_ID)) {
711 return false;
713 break;
714 case PACKET_1BYTE_CONNECTION_ID:
715 if (!writer->WriteUInt8(
716 public_flags | PACKET_PUBLIC_FLAGS_1BYTE_CONNECTION_ID)) {
717 return false;
719 if (!writer->WriteUInt8(
720 header.public_header.connection_id & k1ByteConnectionIdMask)) {
721 return false;
723 break;
724 case PACKET_4BYTE_CONNECTION_ID:
725 if (!writer->WriteUInt8(
726 public_flags | PACKET_PUBLIC_FLAGS_4BYTE_CONNECTION_ID)) {
727 return false;
729 if (!writer->WriteUInt32(
730 header.public_header.connection_id & k4ByteConnectionIdMask)) {
731 return false;
733 break;
734 case PACKET_8BYTE_CONNECTION_ID:
735 if (!writer->WriteUInt8(
736 public_flags | PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID)) {
737 return false;
739 if (!writer->WriteUInt64(header.public_header.connection_id)) {
740 return false;
742 break;
744 last_serialized_connection_id_ = header.public_header.connection_id;
746 if (header.public_header.version_flag) {
747 DCHECK(!is_server_);
748 writer->WriteUInt32(QuicVersionToQuicTag(quic_version_));
751 if (!AppendPacketSequenceNumber(header.public_header.sequence_number_length,
752 header.packet_sequence_number, writer)) {
753 return false;
756 uint8 private_flags = 0;
757 if (header.entropy_flag) {
758 private_flags |= PACKET_PRIVATE_FLAGS_ENTROPY;
760 if (header.is_in_fec_group == IN_FEC_GROUP) {
761 private_flags |= PACKET_PRIVATE_FLAGS_FEC_GROUP;
763 if (header.fec_flag) {
764 private_flags |= PACKET_PRIVATE_FLAGS_FEC;
766 if (!writer->WriteUInt8(private_flags)) {
767 return false;
770 // The FEC group number is the sequence number of the first fec
771 // protected packet, or 0 if this packet is not protected.
772 if (header.is_in_fec_group == IN_FEC_GROUP) {
773 DCHECK_LE(header.fec_group, header.packet_sequence_number);
774 DCHECK_LT(header.packet_sequence_number - header.fec_group, 255u);
775 // Offset from the current packet sequence number to the first fec
776 // protected packet.
777 uint8 first_fec_protected_packet_offset =
778 static_cast<uint8>(header.packet_sequence_number - header.fec_group);
779 if (!writer->WriteBytes(&first_fec_protected_packet_offset, 1)) {
780 return false;
784 return true;
787 const QuicTime::Delta QuicFramer::CalculateTimestampFromWire(
788 uint32 time_delta_us) {
789 // The new time_delta might have wrapped to the next epoch, or it
790 // might have reverse wrapped to the previous epoch, or it might
791 // remain in the same epoch. Select the time closest to the previous
792 // time.
794 // epoch_delta is the delta between epochs. A delta is 4 bytes of
795 // microseconds.
796 const uint64 epoch_delta = GG_UINT64_C(1) << 32;
797 uint64 epoch = last_timestamp_.ToMicroseconds() & ~(epoch_delta - 1);
798 // Wrapping is safe here because a wrapped value will not be ClosestTo below.
799 uint64 prev_epoch = epoch - epoch_delta;
800 uint64 next_epoch = epoch + epoch_delta;
802 uint64 time = ClosestTo(last_timestamp_.ToMicroseconds(),
803 epoch + time_delta_us,
804 ClosestTo(last_timestamp_.ToMicroseconds(),
805 prev_epoch + time_delta_us,
806 next_epoch + time_delta_us));
808 return QuicTime::Delta::FromMicroseconds(time);
811 QuicPacketSequenceNumber QuicFramer::CalculatePacketSequenceNumberFromWire(
812 QuicSequenceNumberLength sequence_number_length,
813 QuicPacketSequenceNumber packet_sequence_number) const {
814 // The new sequence number might have wrapped to the next epoch, or
815 // it might have reverse wrapped to the previous epoch, or it might
816 // remain in the same epoch. Select the sequence number closest to the
817 // next expected sequence number, the previous sequence number plus 1.
819 // epoch_delta is the delta between epochs the sequence number was serialized
820 // with, so the correct value is likely the same epoch as the last sequence
821 // number or an adjacent epoch.
822 const QuicPacketSequenceNumber epoch_delta =
823 GG_UINT64_C(1) << (8 * sequence_number_length);
824 QuicPacketSequenceNumber next_sequence_number = last_sequence_number_ + 1;
825 QuicPacketSequenceNumber epoch = last_sequence_number_ & ~(epoch_delta - 1);
826 QuicPacketSequenceNumber prev_epoch = epoch - epoch_delta;
827 QuicPacketSequenceNumber next_epoch = epoch + epoch_delta;
829 return ClosestTo(next_sequence_number,
830 epoch + packet_sequence_number,
831 ClosestTo(next_sequence_number,
832 prev_epoch + packet_sequence_number,
833 next_epoch + packet_sequence_number));
836 bool QuicFramer::ProcessPublicHeader(
837 QuicPacketPublicHeader* public_header) {
838 uint8 public_flags;
839 if (!reader_->ReadBytes(&public_flags, 1)) {
840 set_detailed_error("Unable to read public flags.");
841 return false;
844 public_header->reset_flag = (public_flags & PACKET_PUBLIC_FLAGS_RST) != 0;
845 public_header->version_flag =
846 (public_flags & PACKET_PUBLIC_FLAGS_VERSION) != 0;
848 if (validate_flags_ &&
849 !public_header->version_flag && public_flags > PACKET_PUBLIC_FLAGS_MAX) {
850 set_detailed_error("Illegal public flags value.");
851 return false;
854 if (public_header->reset_flag && public_header->version_flag) {
855 set_detailed_error("Got version flag in reset packet");
856 return false;
859 switch (public_flags & PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID) {
860 case PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID:
861 if (!reader_->ReadUInt64(&public_header->connection_id)) {
862 set_detailed_error("Unable to read ConnectionId.");
863 return false;
865 public_header->connection_id_length = PACKET_8BYTE_CONNECTION_ID;
866 break;
867 case PACKET_PUBLIC_FLAGS_4BYTE_CONNECTION_ID:
868 // If the connection_id is truncated, expect to read the last serialized
869 // connection_id.
870 if (!reader_->ReadBytes(&public_header->connection_id,
871 PACKET_4BYTE_CONNECTION_ID)) {
872 set_detailed_error("Unable to read ConnectionId.");
873 return false;
875 if (last_serialized_connection_id_ &&
876 (public_header->connection_id & k4ByteConnectionIdMask) !=
877 (last_serialized_connection_id_ & k4ByteConnectionIdMask)) {
878 set_detailed_error("Truncated 4 byte ConnectionId does not match "
879 "previous connection_id.");
880 return false;
882 public_header->connection_id_length = PACKET_4BYTE_CONNECTION_ID;
883 public_header->connection_id = last_serialized_connection_id_;
884 break;
885 case PACKET_PUBLIC_FLAGS_1BYTE_CONNECTION_ID:
886 if (!reader_->ReadBytes(&public_header->connection_id,
887 PACKET_1BYTE_CONNECTION_ID)) {
888 set_detailed_error("Unable to read ConnectionId.");
889 return false;
891 if (last_serialized_connection_id_ &&
892 (public_header->connection_id & k1ByteConnectionIdMask) !=
893 (last_serialized_connection_id_ & k1ByteConnectionIdMask)) {
894 set_detailed_error("Truncated 1 byte ConnectionId does not match "
895 "previous connection_id.");
896 return false;
898 public_header->connection_id_length = PACKET_1BYTE_CONNECTION_ID;
899 public_header->connection_id = last_serialized_connection_id_;
900 break;
901 case PACKET_PUBLIC_FLAGS_0BYTE_CONNECTION_ID:
902 public_header->connection_id_length = PACKET_0BYTE_CONNECTION_ID;
903 public_header->connection_id = last_serialized_connection_id_;
904 break;
907 public_header->sequence_number_length =
908 ReadSequenceNumberLength(
909 public_flags >> kPublicHeaderSequenceNumberShift);
911 // Read the version only if the packet is from the client.
912 // version flag from the server means version negotiation packet.
913 if (public_header->version_flag && is_server_) {
914 QuicTag version_tag;
915 if (!reader_->ReadUInt32(&version_tag)) {
916 set_detailed_error("Unable to read protocol version.");
917 return false;
920 // If the version from the new packet is the same as the version of this
921 // framer, then the public flags should be set to something we understand.
922 // If not, this raises an error.
923 QuicVersion version = QuicTagToQuicVersion(version_tag);
924 if (version == quic_version_ && public_flags > PACKET_PUBLIC_FLAGS_MAX) {
925 set_detailed_error("Illegal public flags value.");
926 return false;
928 public_header->versions.push_back(version);
930 return true;
933 // static
934 QuicSequenceNumberLength QuicFramer::GetMinSequenceNumberLength(
935 QuicPacketSequenceNumber sequence_number) {
936 if (sequence_number < 1 << (PACKET_1BYTE_SEQUENCE_NUMBER * 8)) {
937 return PACKET_1BYTE_SEQUENCE_NUMBER;
938 } else if (sequence_number < 1 << (PACKET_2BYTE_SEQUENCE_NUMBER * 8)) {
939 return PACKET_2BYTE_SEQUENCE_NUMBER;
940 } else if (sequence_number <
941 GG_UINT64_C(1) << (PACKET_4BYTE_SEQUENCE_NUMBER * 8)) {
942 return PACKET_4BYTE_SEQUENCE_NUMBER;
943 } else {
944 return PACKET_6BYTE_SEQUENCE_NUMBER;
948 // static
949 uint8 QuicFramer::GetSequenceNumberFlags(
950 QuicSequenceNumberLength sequence_number_length) {
951 switch (sequence_number_length) {
952 case PACKET_1BYTE_SEQUENCE_NUMBER:
953 return PACKET_FLAGS_1BYTE_SEQUENCE;
954 case PACKET_2BYTE_SEQUENCE_NUMBER:
955 return PACKET_FLAGS_2BYTE_SEQUENCE;
956 case PACKET_4BYTE_SEQUENCE_NUMBER:
957 return PACKET_FLAGS_4BYTE_SEQUENCE;
958 case PACKET_6BYTE_SEQUENCE_NUMBER:
959 return PACKET_FLAGS_6BYTE_SEQUENCE;
960 default:
961 LOG(DFATAL) << "Unreachable case statement.";
962 return PACKET_FLAGS_6BYTE_SEQUENCE;
966 // static
967 QuicFramer::AckFrameInfo QuicFramer::GetAckFrameInfo(
968 const QuicAckFrame& frame) {
969 AckFrameInfo ack_info;
970 if (frame.missing_packets.empty()) {
971 return ack_info;
973 DCHECK_GE(frame.largest_observed, *frame.missing_packets.rbegin());
974 size_t cur_range_length = 0;
975 SequenceNumberSet::const_iterator iter = frame.missing_packets.begin();
976 QuicPacketSequenceNumber last_missing = *iter;
977 ++iter;
978 for (; iter != frame.missing_packets.end(); ++iter) {
979 if (cur_range_length < numeric_limits<uint8>::max() &&
980 *iter == (last_missing + 1)) {
981 ++cur_range_length;
982 } else {
983 ack_info.nack_ranges[last_missing - cur_range_length] =
984 static_cast<uint8>(cur_range_length);
985 cur_range_length = 0;
987 ack_info.max_delta = max(ack_info.max_delta, *iter - last_missing);
988 last_missing = *iter;
990 // Include the last nack range.
991 ack_info.nack_ranges[last_missing - cur_range_length] =
992 static_cast<uint8>(cur_range_length);
993 // Include the range to the largest observed.
994 ack_info.max_delta =
995 max(ack_info.max_delta, frame.largest_observed - last_missing);
996 return ack_info;
999 bool QuicFramer::ProcessPacketHeader(QuicPacketHeader* header,
1000 const QuicEncryptedPacket& packet,
1001 char* decrypted_buffer,
1002 size_t buffer_length) {
1003 if (!ProcessPacketSequenceNumber(header->public_header.sequence_number_length,
1004 &header->packet_sequence_number)) {
1005 set_detailed_error("Unable to read sequence number.");
1006 return RaiseError(QUIC_INVALID_PACKET_HEADER);
1009 if (header->packet_sequence_number == 0u) {
1010 set_detailed_error("Packet sequence numbers cannot be 0.");
1011 return RaiseError(QUIC_INVALID_PACKET_HEADER);
1014 if (!visitor_->OnUnauthenticatedHeader(*header)) {
1015 return false;
1018 if (!DecryptPayload(*header, packet, decrypted_buffer, buffer_length)) {
1019 set_detailed_error("Unable to decrypt payload.");
1020 return RaiseError(QUIC_DECRYPTION_FAILURE);
1023 uint8 private_flags;
1024 if (!reader_->ReadBytes(&private_flags, 1)) {
1025 set_detailed_error("Unable to read private flags.");
1026 return RaiseError(QUIC_INVALID_PACKET_HEADER);
1029 if (private_flags > PACKET_PRIVATE_FLAGS_MAX) {
1030 set_detailed_error("Illegal private flags value.");
1031 return RaiseError(QUIC_INVALID_PACKET_HEADER);
1034 header->entropy_flag = (private_flags & PACKET_PRIVATE_FLAGS_ENTROPY) != 0;
1035 header->fec_flag = (private_flags & PACKET_PRIVATE_FLAGS_FEC) != 0;
1037 if ((private_flags & PACKET_PRIVATE_FLAGS_FEC_GROUP) != 0) {
1038 header->is_in_fec_group = IN_FEC_GROUP;
1039 uint8 first_fec_protected_packet_offset;
1040 if (!reader_->ReadBytes(&first_fec_protected_packet_offset, 1)) {
1041 set_detailed_error("Unable to read first fec protected packet offset.");
1042 return RaiseError(QUIC_INVALID_PACKET_HEADER);
1044 if (first_fec_protected_packet_offset >= header->packet_sequence_number) {
1045 set_detailed_error("First fec protected packet offset must be less "
1046 "than the sequence number.");
1047 return RaiseError(QUIC_INVALID_PACKET_HEADER);
1049 header->fec_group =
1050 header->packet_sequence_number - first_fec_protected_packet_offset;
1053 header->entropy_hash = GetPacketEntropyHash(*header);
1054 // Set the last sequence number after we have decrypted the packet
1055 // so we are confident is not attacker controlled.
1056 last_sequence_number_ = header->packet_sequence_number;
1057 return true;
1060 bool QuicFramer::ProcessPacketSequenceNumber(
1061 QuicSequenceNumberLength sequence_number_length,
1062 QuicPacketSequenceNumber* sequence_number) {
1063 QuicPacketSequenceNumber wire_sequence_number = 0u;
1064 if (!reader_->ReadBytes(&wire_sequence_number, sequence_number_length)) {
1065 return false;
1068 // TODO(ianswett): Explore the usefulness of trying multiple sequence numbers
1069 // in case the first guess is incorrect.
1070 *sequence_number =
1071 CalculatePacketSequenceNumberFromWire(sequence_number_length,
1072 wire_sequence_number);
1073 return true;
1076 bool QuicFramer::ProcessFrameData(const QuicPacketHeader& header) {
1077 if (reader_->IsDoneReading()) {
1078 set_detailed_error("Packet has no frames.");
1079 return RaiseError(QUIC_MISSING_PAYLOAD);
1081 while (!reader_->IsDoneReading()) {
1082 uint8 frame_type;
1083 if (!reader_->ReadBytes(&frame_type, 1)) {
1084 set_detailed_error("Unable to read frame type.");
1085 return RaiseError(QUIC_INVALID_FRAME_DATA);
1088 if (frame_type & kQuicFrameTypeSpecialMask) {
1089 // Stream Frame
1090 if (frame_type & kQuicFrameTypeStreamMask) {
1091 QuicStreamFrame frame;
1092 if (!ProcessStreamFrame(frame_type, &frame)) {
1093 return RaiseError(QUIC_INVALID_STREAM_DATA);
1095 if (!visitor_->OnStreamFrame(frame)) {
1096 DVLOG(1) << "Visitor asked to stop further processing.";
1097 // Returning true since there was no parsing error.
1098 return true;
1100 continue;
1103 // Ack Frame
1104 if (frame_type & kQuicFrameTypeAckMask) {
1105 QuicAckFrame frame;
1106 if (!ProcessAckFrame(frame_type, &frame)) {
1107 return RaiseError(QUIC_INVALID_ACK_DATA);
1109 if (!visitor_->OnAckFrame(frame)) {
1110 DVLOG(1) << "Visitor asked to stop further processing.";
1111 // Returning true since there was no parsing error.
1112 return true;
1114 continue;
1117 // This was a special frame type that did not match any
1118 // of the known ones. Error.
1119 set_detailed_error("Illegal frame type.");
1120 DLOG(WARNING) << "Illegal frame type: "
1121 << static_cast<int>(frame_type);
1122 return RaiseError(QUIC_INVALID_FRAME_DATA);
1125 switch (frame_type) {
1126 case PADDING_FRAME:
1127 // We're done with the packet.
1128 return true;
1130 case RST_STREAM_FRAME: {
1131 QuicRstStreamFrame frame;
1132 if (!ProcessRstStreamFrame(&frame)) {
1133 return RaiseError(QUIC_INVALID_RST_STREAM_DATA);
1135 if (!visitor_->OnRstStreamFrame(frame)) {
1136 DVLOG(1) << "Visitor asked to stop further processing.";
1137 // Returning true since there was no parsing error.
1138 return true;
1140 continue;
1143 case CONNECTION_CLOSE_FRAME: {
1144 QuicConnectionCloseFrame frame;
1145 if (!ProcessConnectionCloseFrame(&frame)) {
1146 return RaiseError(QUIC_INVALID_CONNECTION_CLOSE_DATA);
1149 if (!visitor_->OnConnectionCloseFrame(frame)) {
1150 DVLOG(1) << "Visitor asked to stop further processing.";
1151 // Returning true since there was no parsing error.
1152 return true;
1154 continue;
1157 case GOAWAY_FRAME: {
1158 QuicGoAwayFrame goaway_frame;
1159 if (!ProcessGoAwayFrame(&goaway_frame)) {
1160 return RaiseError(QUIC_INVALID_GOAWAY_DATA);
1162 if (!visitor_->OnGoAwayFrame(goaway_frame)) {
1163 DVLOG(1) << "Visitor asked to stop further processing.";
1164 // Returning true since there was no parsing error.
1165 return true;
1167 continue;
1170 case WINDOW_UPDATE_FRAME: {
1171 QuicWindowUpdateFrame window_update_frame;
1172 if (!ProcessWindowUpdateFrame(&window_update_frame)) {
1173 return RaiseError(QUIC_INVALID_WINDOW_UPDATE_DATA);
1175 if (!visitor_->OnWindowUpdateFrame(window_update_frame)) {
1176 DVLOG(1) << "Visitor asked to stop further processing.";
1177 // Returning true since there was no parsing error.
1178 return true;
1180 continue;
1183 case BLOCKED_FRAME: {
1184 QuicBlockedFrame blocked_frame;
1185 if (!ProcessBlockedFrame(&blocked_frame)) {
1186 return RaiseError(QUIC_INVALID_BLOCKED_DATA);
1188 if (!visitor_->OnBlockedFrame(blocked_frame)) {
1189 DVLOG(1) << "Visitor asked to stop further processing.";
1190 // Returning true since there was no parsing error.
1191 return true;
1193 continue;
1196 case STOP_WAITING_FRAME: {
1197 QuicStopWaitingFrame stop_waiting_frame;
1198 if (!ProcessStopWaitingFrame(header, &stop_waiting_frame)) {
1199 return RaiseError(QUIC_INVALID_STOP_WAITING_DATA);
1201 if (!visitor_->OnStopWaitingFrame(stop_waiting_frame)) {
1202 DVLOG(1) << "Visitor asked to stop further processing.";
1203 // Returning true since there was no parsing error.
1204 return true;
1206 continue;
1208 case PING_FRAME: {
1209 // Ping has no payload.
1210 QuicPingFrame ping_frame;
1211 if (!visitor_->OnPingFrame(ping_frame)) {
1212 DVLOG(1) << "Visitor asked to stop further processing.";
1213 // Returning true since there was no parsing error.
1214 return true;
1216 continue;
1219 default:
1220 set_detailed_error("Illegal frame type.");
1221 DLOG(WARNING) << "Illegal frame type: "
1222 << static_cast<int>(frame_type);
1223 return RaiseError(QUIC_INVALID_FRAME_DATA);
1227 return true;
1230 bool QuicFramer::ProcessStreamFrame(uint8 frame_type,
1231 QuicStreamFrame* frame) {
1232 uint8 stream_flags = frame_type;
1234 stream_flags &= ~kQuicFrameTypeStreamMask;
1236 // Read from right to left: StreamID, Offset, Data Length, Fin.
1237 const uint8 stream_id_length = (stream_flags & kQuicStreamIDLengthMask) + 1;
1238 stream_flags >>= kQuicStreamIdShift;
1240 uint8 offset_length = (stream_flags & kQuicStreamOffsetMask);
1241 // There is no encoding for 1 byte, only 0 and 2 through 8.
1242 if (offset_length > 0) {
1243 offset_length += 1;
1245 stream_flags >>= kQuicStreamOffsetShift;
1247 bool has_data_length =
1248 (stream_flags & kQuicStreamDataLengthMask) == kQuicStreamDataLengthMask;
1249 stream_flags >>= kQuicStreamDataLengthShift;
1251 frame->fin = (stream_flags & kQuicStreamFinMask) == kQuicStreamFinShift;
1253 frame->stream_id = 0;
1254 if (!reader_->ReadBytes(&frame->stream_id, stream_id_length)) {
1255 set_detailed_error("Unable to read stream_id.");
1256 return false;
1259 frame->offset = 0;
1260 if (!reader_->ReadBytes(&frame->offset, offset_length)) {
1261 set_detailed_error("Unable to read offset.");
1262 return false;
1265 StringPiece frame_data;
1266 if (has_data_length) {
1267 if (!reader_->ReadStringPiece16(&frame_data)) {
1268 set_detailed_error("Unable to read frame data.");
1269 return false;
1271 } else {
1272 if (!reader_->ReadStringPiece(&frame_data, reader_->BytesRemaining())) {
1273 set_detailed_error("Unable to read frame data.");
1274 return false;
1277 // Point frame to the right data.
1278 frame->data.Clear();
1279 if (!frame_data.empty()) {
1280 frame->data.Append(const_cast<char*>(frame_data.data()), frame_data.size());
1283 return true;
1286 bool QuicFramer::ProcessAckFrame(uint8 frame_type, QuicAckFrame* ack_frame) {
1287 // Determine the three lengths from the frame type: largest observed length,
1288 // missing sequence number length, and missing range length.
1289 const QuicSequenceNumberLength missing_sequence_number_length =
1290 ReadSequenceNumberLength(frame_type);
1291 frame_type >>= kQuicSequenceNumberLengthShift;
1292 const QuicSequenceNumberLength largest_observed_sequence_number_length =
1293 ReadSequenceNumberLength(frame_type);
1294 frame_type >>= kQuicSequenceNumberLengthShift;
1295 ack_frame->is_truncated = frame_type & kQuicAckTruncatedMask;
1296 frame_type >>= kQuicAckTruncatedShift;
1297 bool has_nacks = frame_type & kQuicHasNacksMask;
1299 if (!reader_->ReadBytes(&ack_frame->entropy_hash, 1)) {
1300 set_detailed_error("Unable to read entropy hash for received packets.");
1301 return false;
1304 if (!reader_->ReadBytes(&ack_frame->largest_observed,
1305 largest_observed_sequence_number_length)) {
1306 set_detailed_error("Unable to read largest observed.");
1307 return false;
1310 uint64 delta_time_largest_observed_us;
1311 if (!reader_->ReadUFloat16(&delta_time_largest_observed_us)) {
1312 set_detailed_error("Unable to read delta time largest observed.");
1313 return false;
1316 if (delta_time_largest_observed_us == kUFloat16MaxValue) {
1317 ack_frame->delta_time_largest_observed = QuicTime::Delta::Infinite();
1318 } else {
1319 ack_frame->delta_time_largest_observed =
1320 QuicTime::Delta::FromMicroseconds(delta_time_largest_observed_us);
1323 if (!ProcessTimestampsInAckFrame(ack_frame)) {
1324 return false;
1327 if (!has_nacks) {
1328 return true;
1331 uint8 num_missing_ranges;
1332 if (!reader_->ReadBytes(&num_missing_ranges, 1)) {
1333 set_detailed_error("Unable to read num missing packet ranges.");
1334 return false;
1337 QuicPacketSequenceNumber last_sequence_number = ack_frame->largest_observed;
1338 for (size_t i = 0; i < num_missing_ranges; ++i) {
1339 QuicPacketSequenceNumber missing_delta = 0;
1340 if (!reader_->ReadBytes(&missing_delta, missing_sequence_number_length)) {
1341 set_detailed_error("Unable to read missing sequence number delta.");
1342 return false;
1344 last_sequence_number -= missing_delta;
1345 QuicPacketSequenceNumber range_length = 0;
1346 if (!reader_->ReadBytes(&range_length, PACKET_1BYTE_SEQUENCE_NUMBER)) {
1347 set_detailed_error("Unable to read missing sequence number range.");
1348 return false;
1350 for (size_t j = 0; j <= range_length; ++j) {
1351 ack_frame->missing_packets.insert(last_sequence_number - j);
1353 // Subtract an extra 1 to ensure ranges are represented efficiently and
1354 // can't overlap by 1 sequence number. This allows a missing_delta of 0
1355 // to represent an adjacent nack range.
1356 last_sequence_number -= (range_length + 1);
1359 // Parse the revived packets list.
1360 uint8 num_revived_packets;
1361 if (!reader_->ReadBytes(&num_revived_packets, 1)) {
1362 set_detailed_error("Unable to read num revived packets.");
1363 return false;
1366 for (size_t i = 0; i < num_revived_packets; ++i) {
1367 QuicPacketSequenceNumber revived_packet = 0;
1368 if (!reader_->ReadBytes(&revived_packet,
1369 largest_observed_sequence_number_length)) {
1370 set_detailed_error("Unable to read revived packet.");
1371 return false;
1374 ack_frame->revived_packets.insert(revived_packet);
1377 return true;
1380 bool QuicFramer::ProcessTimestampsInAckFrame(QuicAckFrame* ack_frame) {
1381 if (!ack_frame->is_truncated) {
1382 uint8 num_received_packets;
1383 if (!reader_->ReadBytes(&num_received_packets, 1)) {
1384 set_detailed_error("Unable to read num received packets.");
1385 return false;
1388 if (num_received_packets > 0) {
1389 uint8 delta_from_largest_observed;
1390 if (!reader_->ReadBytes(&delta_from_largest_observed,
1391 PACKET_1BYTE_SEQUENCE_NUMBER)) {
1392 set_detailed_error(
1393 "Unable to read sequence delta in received packets.");
1394 return false;
1396 QuicPacketSequenceNumber seq_num = ack_frame->largest_observed -
1397 delta_from_largest_observed;
1399 // Time delta from the framer creation.
1400 uint32 time_delta_us;
1401 if (!reader_->ReadBytes(&time_delta_us, sizeof(time_delta_us))) {
1402 set_detailed_error("Unable to read time delta in received packets.");
1403 return false;
1406 last_timestamp_ = CalculateTimestampFromWire(time_delta_us);
1408 ack_frame->received_packet_times.push_back(
1409 std::make_pair(seq_num, creation_time_.Add(last_timestamp_)));
1411 for (uint8 i = 1; i < num_received_packets; ++i) {
1412 if (!reader_->ReadBytes(&delta_from_largest_observed,
1413 PACKET_1BYTE_SEQUENCE_NUMBER)) {
1414 set_detailed_error(
1415 "Unable to read sequence delta in received packets.");
1416 return false;
1418 seq_num = ack_frame->largest_observed - delta_from_largest_observed;
1420 // Time delta from the previous timestamp.
1421 uint64 incremental_time_delta_us;
1422 if (!reader_->ReadUFloat16(&incremental_time_delta_us)) {
1423 set_detailed_error(
1424 "Unable to read incremental time delta in received packets.");
1425 return false;
1428 last_timestamp_ = last_timestamp_.Add(
1429 QuicTime::Delta::FromMicroseconds(incremental_time_delta_us));
1430 ack_frame->received_packet_times.push_back(
1431 std::make_pair(seq_num, creation_time_.Add(last_timestamp_)));
1435 return true;
1438 bool QuicFramer::ProcessStopWaitingFrame(const QuicPacketHeader& header,
1439 QuicStopWaitingFrame* stop_waiting) {
1440 if (!reader_->ReadBytes(&stop_waiting->entropy_hash, 1)) {
1441 set_detailed_error("Unable to read entropy hash for sent packets.");
1442 return false;
1445 QuicPacketSequenceNumber least_unacked_delta = 0;
1446 if (!reader_->ReadBytes(&least_unacked_delta,
1447 header.public_header.sequence_number_length)) {
1448 set_detailed_error("Unable to read least unacked delta.");
1449 return false;
1451 DCHECK_GE(header.packet_sequence_number, least_unacked_delta);
1452 stop_waiting->least_unacked =
1453 header.packet_sequence_number - least_unacked_delta;
1455 return true;
1458 bool QuicFramer::ProcessRstStreamFrame(QuicRstStreamFrame* frame) {
1459 if (!reader_->ReadUInt32(&frame->stream_id)) {
1460 set_detailed_error("Unable to read stream_id.");
1461 return false;
1464 if (!reader_->ReadUInt64(&frame->byte_offset)) {
1465 set_detailed_error("Unable to read rst stream sent byte offset.");
1466 return false;
1469 uint32 error_code;
1470 if (!reader_->ReadUInt32(&error_code)) {
1471 set_detailed_error("Unable to read rst stream error code.");
1472 return false;
1475 if (error_code >= QUIC_STREAM_LAST_ERROR) {
1476 set_detailed_error("Invalid rst stream error code.");
1477 return false;
1480 frame->error_code = static_cast<QuicRstStreamErrorCode>(error_code);
1482 StringPiece error_details;
1483 if (!reader_->ReadStringPiece16(&error_details)) {
1484 set_detailed_error("Unable to read rst stream error details.");
1485 return false;
1487 frame->error_details = error_details.as_string();
1489 return true;
1492 bool QuicFramer::ProcessConnectionCloseFrame(QuicConnectionCloseFrame* frame) {
1493 uint32 error_code;
1494 if (!reader_->ReadUInt32(&error_code)) {
1495 set_detailed_error("Unable to read connection close error code.");
1496 return false;
1499 if (error_code >= QUIC_LAST_ERROR) {
1500 set_detailed_error("Invalid error code.");
1501 return false;
1504 frame->error_code = static_cast<QuicErrorCode>(error_code);
1506 StringPiece error_details;
1507 if (!reader_->ReadStringPiece16(&error_details)) {
1508 set_detailed_error("Unable to read connection close error details.");
1509 return false;
1511 frame->error_details = error_details.as_string();
1513 return true;
1516 bool QuicFramer::ProcessGoAwayFrame(QuicGoAwayFrame* frame) {
1517 uint32 error_code;
1518 if (!reader_->ReadUInt32(&error_code)) {
1519 set_detailed_error("Unable to read go away error code.");
1520 return false;
1522 frame->error_code = static_cast<QuicErrorCode>(error_code);
1524 if (error_code >= QUIC_LAST_ERROR) {
1525 set_detailed_error("Invalid error code.");
1526 return false;
1529 uint32 stream_id;
1530 if (!reader_->ReadUInt32(&stream_id)) {
1531 set_detailed_error("Unable to read last good stream id.");
1532 return false;
1534 frame->last_good_stream_id = static_cast<QuicStreamId>(stream_id);
1536 StringPiece reason_phrase;
1537 if (!reader_->ReadStringPiece16(&reason_phrase)) {
1538 set_detailed_error("Unable to read goaway reason.");
1539 return false;
1541 frame->reason_phrase = reason_phrase.as_string();
1543 return true;
1546 bool QuicFramer::ProcessWindowUpdateFrame(QuicWindowUpdateFrame* frame) {
1547 if (!reader_->ReadUInt32(&frame->stream_id)) {
1548 set_detailed_error("Unable to read stream_id.");
1549 return false;
1552 if (!reader_->ReadUInt64(&frame->byte_offset)) {
1553 set_detailed_error("Unable to read window byte_offset.");
1554 return false;
1557 return true;
1560 bool QuicFramer::ProcessBlockedFrame(QuicBlockedFrame* frame) {
1561 if (!reader_->ReadUInt32(&frame->stream_id)) {
1562 set_detailed_error("Unable to read stream_id.");
1563 return false;
1566 return true;
1569 // static
1570 StringPiece QuicFramer::GetAssociatedDataFromEncryptedPacket(
1571 const QuicEncryptedPacket& encrypted,
1572 QuicConnectionIdLength connection_id_length,
1573 bool includes_version,
1574 QuicSequenceNumberLength sequence_number_length) {
1575 return StringPiece(
1576 encrypted.data() + kStartOfHashData, GetStartOfEncryptedData(
1577 connection_id_length, includes_version, sequence_number_length)
1578 - kStartOfHashData);
1581 void QuicFramer::SetDecrypter(QuicDecrypter* decrypter,
1582 EncryptionLevel level) {
1583 DCHECK(alternative_decrypter_.get() == nullptr);
1584 DCHECK_GE(level, decrypter_level_);
1585 decrypter_.reset(decrypter);
1586 decrypter_level_ = level;
1589 void QuicFramer::SetAlternativeDecrypter(QuicDecrypter* decrypter,
1590 EncryptionLevel level,
1591 bool latch_once_used) {
1592 alternative_decrypter_.reset(decrypter);
1593 alternative_decrypter_level_ = level;
1594 alternative_decrypter_latch_ = latch_once_used;
1597 const QuicDecrypter* QuicFramer::decrypter() const {
1598 return decrypter_.get();
1601 const QuicDecrypter* QuicFramer::alternative_decrypter() const {
1602 return alternative_decrypter_.get();
1605 void QuicFramer::SetEncrypter(EncryptionLevel level,
1606 QuicEncrypter* encrypter) {
1607 DCHECK_GE(level, 0);
1608 DCHECK_LT(level, NUM_ENCRYPTION_LEVELS);
1609 encrypter_[level].reset(encrypter);
1612 const QuicEncrypter* QuicFramer::encrypter(EncryptionLevel level) const {
1613 DCHECK_GE(level, 0);
1614 DCHECK_LT(level, NUM_ENCRYPTION_LEVELS);
1615 DCHECK(encrypter_[level].get() != nullptr);
1616 return encrypter_[level].get();
1619 QuicEncryptedPacket* QuicFramer::EncryptPacket(
1620 EncryptionLevel level,
1621 QuicPacketSequenceNumber packet_sequence_number,
1622 const QuicPacket& packet) {
1623 DCHECK(encrypter_[level].get() != nullptr);
1625 // Allocate a large enough buffer for the header and the encrypted data.
1626 const size_t encrypted_len =
1627 encrypter_[level]->GetCiphertextSize(packet.Plaintext().length());
1628 StringPiece header_data = packet.BeforePlaintext();
1629 const size_t len = header_data.length() + encrypted_len;
1630 // TODO(ianswett): Consider allocating this on the stack in the typical case.
1631 char* buffer = new char[len];
1632 // Copy in the header, because the encrypter only populates the encrypted
1633 // plaintext content.
1634 memcpy(buffer, header_data.data(), header_data.length());
1635 // Encrypt the plaintext into the buffer.
1636 size_t output_length = 0;
1637 if (!encrypter_[level]->EncryptPacket(
1638 packet_sequence_number, packet.AssociatedData(), packet.Plaintext(),
1639 buffer + header_data.length(), &output_length, encrypted_len)) {
1640 RaiseError(QUIC_ENCRYPTION_FAILURE);
1641 return nullptr;
1644 return new QuicEncryptedPacket(buffer, header_data.length() + output_length,
1645 true);
1648 size_t QuicFramer::GetMaxPlaintextSize(size_t ciphertext_size) {
1649 // In order to keep the code simple, we don't have the current encryption
1650 // level to hand. Both the NullEncrypter and AES-GCM have a tag length of 12.
1651 size_t min_plaintext_size = ciphertext_size;
1653 for (int i = ENCRYPTION_NONE; i < NUM_ENCRYPTION_LEVELS; i++) {
1654 if (encrypter_[i].get() != nullptr) {
1655 size_t size = encrypter_[i]->GetMaxPlaintextSize(ciphertext_size);
1656 if (size < min_plaintext_size) {
1657 min_plaintext_size = size;
1662 return min_plaintext_size;
1665 bool QuicFramer::DecryptPayload(const QuicPacketHeader& header,
1666 const QuicEncryptedPacket& packet,
1667 char* decrypted_buffer,
1668 size_t buffer_length) {
1669 StringPiece encrypted = reader_->ReadRemainingPayload();
1670 DCHECK(decrypter_.get() != nullptr);
1671 const StringPiece& associated_data = GetAssociatedDataFromEncryptedPacket(
1672 packet, header.public_header.connection_id_length,
1673 header.public_header.version_flag,
1674 header.public_header.sequence_number_length);
1675 size_t decrypted_length = 0;
1676 bool success = decrypter_->DecryptPacket(
1677 header.packet_sequence_number, associated_data, encrypted,
1678 decrypted_buffer, &decrypted_length, buffer_length);
1679 if (success) {
1680 visitor_->OnDecryptedPacket(decrypter_level_);
1681 } else if (alternative_decrypter_.get() != nullptr) {
1682 success = alternative_decrypter_->DecryptPacket(
1683 header.packet_sequence_number, associated_data, encrypted,
1684 decrypted_buffer, &decrypted_length, buffer_length);
1685 if (success) {
1686 visitor_->OnDecryptedPacket(alternative_decrypter_level_);
1687 if (alternative_decrypter_latch_) {
1688 // Switch to the alternative decrypter and latch so that we cannot
1689 // switch back.
1690 decrypter_.reset(alternative_decrypter_.release());
1691 decrypter_level_ = alternative_decrypter_level_;
1692 alternative_decrypter_level_ = ENCRYPTION_NONE;
1693 } else {
1694 // Switch the alternative decrypter so that we use it first next time.
1695 decrypter_.swap(alternative_decrypter_);
1696 EncryptionLevel level = alternative_decrypter_level_;
1697 alternative_decrypter_level_ = decrypter_level_;
1698 decrypter_level_ = level;
1703 if (!success) {
1704 DLOG(WARNING) << "DecryptPacket failed for sequence_number:"
1705 << header.packet_sequence_number;
1706 return false;
1709 reader_.reset(new QuicDataReader(decrypted_buffer, decrypted_length));
1710 return true;
1713 size_t QuicFramer::GetAckFrameSize(
1714 const QuicAckFrame& ack,
1715 QuicSequenceNumberLength sequence_number_length) {
1716 AckFrameInfo ack_info = GetAckFrameInfo(ack);
1717 QuicSequenceNumberLength largest_observed_length =
1718 GetMinSequenceNumberLength(ack.largest_observed);
1719 QuicSequenceNumberLength missing_sequence_number_length =
1720 GetMinSequenceNumberLength(ack_info.max_delta);
1722 size_t ack_size = GetMinAckFrameSize(sequence_number_length,
1723 largest_observed_length);
1724 if (!ack_info.nack_ranges.empty()) {
1725 ack_size += kNumberOfNackRangesSize + kNumberOfRevivedPacketsSize;
1726 ack_size += min(ack_info.nack_ranges.size(), kMaxNackRanges) *
1727 (missing_sequence_number_length + PACKET_1BYTE_SEQUENCE_NUMBER);
1728 ack_size += min(ack.revived_packets.size(),
1729 kMaxRevivedPackets) * largest_observed_length;
1732 // In version 23, if the ack will be truncated due to too many nack ranges,
1733 // then do not include the number of timestamps (1 byte).
1734 if (ack_info.nack_ranges.size() <= kMaxNackRanges) {
1735 // 1 byte for the number of timestamps.
1736 ack_size += 1;
1737 if (ack.received_packet_times.size() > 0) {
1738 // 1 byte for sequence number, 4 bytes for timestamp for the first
1739 // packet.
1740 ack_size += 5;
1742 // 1 byte for sequence number, 2 bytes for timestamp for the other
1743 // packets.
1744 ack_size += 3 * (ack.received_packet_times.size() - 1);
1748 return ack_size;
1751 size_t QuicFramer::ComputeFrameLength(
1752 const QuicFrame& frame,
1753 bool last_frame_in_packet,
1754 InFecGroup is_in_fec_group,
1755 QuicSequenceNumberLength sequence_number_length) {
1756 switch (frame.type) {
1757 case STREAM_FRAME:
1758 return GetMinStreamFrameSize(frame.stream_frame->stream_id,
1759 frame.stream_frame->offset,
1760 last_frame_in_packet,
1761 is_in_fec_group) +
1762 frame.stream_frame->data.TotalBufferSize();
1763 case ACK_FRAME: {
1764 return GetAckFrameSize(*frame.ack_frame, sequence_number_length);
1766 case STOP_WAITING_FRAME:
1767 return GetStopWaitingFrameSize(sequence_number_length);
1768 case PING_FRAME:
1769 // Ping has no payload.
1770 return kQuicFrameTypeSize;
1771 case RST_STREAM_FRAME:
1772 return GetMinRstStreamFrameSize() +
1773 frame.rst_stream_frame->error_details.size();
1774 case CONNECTION_CLOSE_FRAME:
1775 return GetMinConnectionCloseFrameSize() +
1776 frame.connection_close_frame->error_details.size();
1777 case GOAWAY_FRAME:
1778 return GetMinGoAwayFrameSize() + frame.goaway_frame->reason_phrase.size();
1779 case WINDOW_UPDATE_FRAME:
1780 return GetWindowUpdateFrameSize();
1781 case BLOCKED_FRAME:
1782 return GetBlockedFrameSize();
1783 case PADDING_FRAME:
1784 DCHECK(false);
1785 return 0;
1786 case NUM_FRAME_TYPES:
1787 DCHECK(false);
1788 return 0;
1791 // Not reachable, but some Chrome compilers can't figure that out. *sigh*
1792 DCHECK(false);
1793 return 0;
1796 bool QuicFramer::AppendTypeByte(const QuicFrame& frame,
1797 bool no_stream_frame_length,
1798 QuicDataWriter* writer) {
1799 uint8 type_byte = 0;
1800 switch (frame.type) {
1801 case STREAM_FRAME: {
1802 if (frame.stream_frame == nullptr) {
1803 LOG(DFATAL) << "Failed to append STREAM frame with no stream_frame.";
1805 // Fin bit.
1806 type_byte |= frame.stream_frame->fin ? kQuicStreamFinMask : 0;
1808 // Data Length bit.
1809 type_byte <<= kQuicStreamDataLengthShift;
1810 type_byte |= no_stream_frame_length ? 0: kQuicStreamDataLengthMask;
1812 // Offset 3 bits.
1813 type_byte <<= kQuicStreamOffsetShift;
1814 const size_t offset_len = GetStreamOffsetSize(frame.stream_frame->offset);
1815 if (offset_len > 0) {
1816 type_byte |= offset_len - 1;
1819 // stream id 2 bits.
1820 type_byte <<= kQuicStreamIdShift;
1821 type_byte |= GetStreamIdSize(frame.stream_frame->stream_id) - 1;
1822 type_byte |= kQuicFrameTypeStreamMask; // Set Stream Frame Type to 1.
1823 break;
1825 case ACK_FRAME:
1826 return true;
1827 default:
1828 type_byte = static_cast<uint8>(frame.type);
1829 break;
1832 return writer->WriteUInt8(type_byte);
1835 // static
1836 bool QuicFramer::AppendPacketSequenceNumber(
1837 QuicSequenceNumberLength sequence_number_length,
1838 QuicPacketSequenceNumber packet_sequence_number,
1839 QuicDataWriter* writer) {
1840 // Ensure the entire sequence number can be written.
1841 if (writer->capacity() - writer->length() <
1842 static_cast<size_t>(sequence_number_length)) {
1843 return false;
1845 switch (sequence_number_length) {
1846 case PACKET_1BYTE_SEQUENCE_NUMBER:
1847 return writer->WriteUInt8(
1848 packet_sequence_number & k1ByteSequenceNumberMask);
1849 break;
1850 case PACKET_2BYTE_SEQUENCE_NUMBER:
1851 return writer->WriteUInt16(
1852 packet_sequence_number & k2ByteSequenceNumberMask);
1853 break;
1854 case PACKET_4BYTE_SEQUENCE_NUMBER:
1855 return writer->WriteUInt32(
1856 packet_sequence_number & k4ByteSequenceNumberMask);
1857 break;
1858 case PACKET_6BYTE_SEQUENCE_NUMBER:
1859 return writer->WriteUInt48(
1860 packet_sequence_number & k6ByteSequenceNumberMask);
1861 break;
1862 default:
1863 DCHECK(false) << "sequence_number_length: " << sequence_number_length;
1864 return false;
1868 bool QuicFramer::AppendStreamFrame(
1869 const QuicStreamFrame& frame,
1870 bool no_stream_frame_length,
1871 QuicDataWriter* writer) {
1872 if (!writer->WriteBytes(&frame.stream_id, GetStreamIdSize(frame.stream_id))) {
1873 LOG(DFATAL) << "Writing stream id size failed.";
1874 return false;
1876 if (!writer->WriteBytes(&frame.offset, GetStreamOffsetSize(frame.offset))) {
1877 LOG(DFATAL) << "Writing offset size failed.";
1878 return false;
1880 if (!no_stream_frame_length) {
1881 if ((frame.data.TotalBufferSize() > numeric_limits<uint16>::max()) ||
1882 !writer->WriteUInt16(
1883 static_cast<uint16>(frame.data.TotalBufferSize()))) {
1884 LOG(DFATAL) << "Writing stream frame length failed";
1885 return false;
1889 if (!writer->WriteIOVector(frame.data)) {
1890 LOG(DFATAL) << "Writing frame data failed.";
1891 return false;
1893 return true;
1896 // static
1897 void QuicFramer::set_version(const QuicVersion version) {
1898 DCHECK(IsSupportedVersion(version)) << QuicVersionToString(version);
1899 quic_version_ = version;
1902 bool QuicFramer::AppendAckFrameAndTypeByte(
1903 const QuicPacketHeader& header,
1904 const QuicAckFrame& frame,
1905 QuicDataWriter* writer) {
1906 AckFrameInfo ack_info = GetAckFrameInfo(frame);
1907 QuicPacketSequenceNumber ack_largest_observed = frame.largest_observed;
1908 QuicSequenceNumberLength largest_observed_length =
1909 GetMinSequenceNumberLength(ack_largest_observed);
1910 QuicSequenceNumberLength missing_sequence_number_length =
1911 GetMinSequenceNumberLength(ack_info.max_delta);
1912 // Determine whether we need to truncate ranges.
1913 size_t available_range_bytes = writer->capacity() - writer->length() -
1914 kNumberOfRevivedPacketsSize - kNumberOfNackRangesSize -
1915 GetMinAckFrameSize(header.public_header.sequence_number_length,
1916 largest_observed_length);
1917 size_t max_num_ranges = available_range_bytes /
1918 (missing_sequence_number_length + PACKET_1BYTE_SEQUENCE_NUMBER);
1919 max_num_ranges = min(kMaxNackRanges, max_num_ranges);
1920 bool truncated = ack_info.nack_ranges.size() > max_num_ranges;
1921 DVLOG_IF(1, truncated) << "Truncating ack from "
1922 << ack_info.nack_ranges.size() << " ranges to "
1923 << max_num_ranges;
1924 // Write out the type byte by setting the low order bits and doing shifts
1925 // to make room for the next bit flags to be set.
1926 // Whether there are any nacks.
1927 uint8 type_byte = ack_info.nack_ranges.empty() ? 0 : kQuicHasNacksMask;
1929 // truncating bit.
1930 type_byte <<= kQuicAckTruncatedShift;
1931 type_byte |= truncated ? kQuicAckTruncatedMask : 0;
1933 // Largest observed sequence number length.
1934 type_byte <<= kQuicSequenceNumberLengthShift;
1935 type_byte |= GetSequenceNumberFlags(largest_observed_length);
1937 // Missing sequence number length.
1938 type_byte <<= kQuicSequenceNumberLengthShift;
1939 type_byte |= GetSequenceNumberFlags(missing_sequence_number_length);
1941 type_byte |= kQuicFrameTypeAckMask;
1943 if (!writer->WriteUInt8(type_byte)) {
1944 return false;
1947 QuicPacketEntropyHash ack_entropy_hash = frame.entropy_hash;
1948 NackRangeMap::reverse_iterator ack_iter = ack_info.nack_ranges.rbegin();
1949 if (truncated) {
1950 // Skip the nack ranges which the truncated ack won't include and set
1951 // a correct largest observed for the truncated ack.
1952 for (size_t i = 1; i < (ack_info.nack_ranges.size() - max_num_ranges);
1953 ++i) {
1954 ++ack_iter;
1956 // If the last range is followed by acks, include them.
1957 // If the last range is followed by another range, specify the end of the
1958 // range as the largest_observed.
1959 ack_largest_observed = ack_iter->first - 1;
1960 // Also update the entropy so it matches the largest observed.
1961 ack_entropy_hash = entropy_calculator_->EntropyHash(ack_largest_observed);
1962 ++ack_iter;
1965 if (!writer->WriteUInt8(ack_entropy_hash)) {
1966 return false;
1969 if (!AppendPacketSequenceNumber(largest_observed_length,
1970 ack_largest_observed, writer)) {
1971 return false;
1974 uint64 delta_time_largest_observed_us = kUFloat16MaxValue;
1975 if (!frame.delta_time_largest_observed.IsInfinite()) {
1976 DCHECK_LE(0u, frame.delta_time_largest_observed.ToMicroseconds());
1977 delta_time_largest_observed_us =
1978 frame.delta_time_largest_observed.ToMicroseconds();
1981 if (!writer->WriteUFloat16(delta_time_largest_observed_us)) {
1982 return false;
1985 // Timestamp goes at the end of the required fields.
1986 if (!truncated) {
1987 if (!AppendTimestampToAckFrame(frame, writer)) {
1988 return false;
1992 if (ack_info.nack_ranges.empty()) {
1993 return true;
1996 const uint8 num_missing_ranges =
1997 static_cast<uint8>(min(ack_info.nack_ranges.size(), max_num_ranges));
1998 if (!writer->WriteBytes(&num_missing_ranges, 1)) {
1999 return false;
2002 int num_ranges_written = 0;
2003 QuicPacketSequenceNumber last_sequence_written = ack_largest_observed;
2004 for (; ack_iter != ack_info.nack_ranges.rend(); ++ack_iter) {
2005 // Calculate the delta to the last number in the range.
2006 QuicPacketSequenceNumber missing_delta =
2007 last_sequence_written - (ack_iter->first + ack_iter->second);
2008 if (!AppendPacketSequenceNumber(missing_sequence_number_length,
2009 missing_delta, writer)) {
2010 return false;
2012 if (!AppendPacketSequenceNumber(PACKET_1BYTE_SEQUENCE_NUMBER,
2013 ack_iter->second, writer)) {
2014 return false;
2016 // Subtract 1 so a missing_delta of 0 means an adjacent range.
2017 last_sequence_written = ack_iter->first - 1;
2018 ++num_ranges_written;
2020 DCHECK_EQ(num_missing_ranges, num_ranges_written);
2022 // Append revived packets.
2023 // If not all the revived packets fit, only mention the ones that do.
2024 uint8 num_revived_packets =
2025 static_cast<uint8>(min(frame.revived_packets.size(), kMaxRevivedPackets));
2026 num_revived_packets = static_cast<uint8>(min(
2027 static_cast<size_t>(num_revived_packets),
2028 (writer->capacity() - writer->length()) / largest_observed_length));
2029 if (!writer->WriteBytes(&num_revived_packets, 1)) {
2030 return false;
2033 SequenceNumberSet::const_iterator iter = frame.revived_packets.begin();
2034 for (int i = 0; i < num_revived_packets; ++i, ++iter) {
2035 LOG_IF(DFATAL, !ContainsKey(frame.missing_packets, *iter));
2036 if (!AppendPacketSequenceNumber(largest_observed_length,
2037 *iter, writer)) {
2038 return false;
2042 return true;
2045 bool QuicFramer::AppendTimestampToAckFrame(const QuicAckFrame& frame,
2046 QuicDataWriter* writer) {
2047 DCHECK_GE(version(), QUIC_VERSION_23);
2048 DCHECK_GE(numeric_limits<uint8>::max(), frame.received_packet_times.size());
2049 // num_received_packets is only 1 byte.
2050 if (frame.received_packet_times.size() > numeric_limits<uint8>::max()) {
2051 return false;
2054 uint8 num_received_packets = frame.received_packet_times.size();
2056 if (!writer->WriteBytes(&num_received_packets, 1)) {
2057 return false;
2059 if (num_received_packets == 0) {
2060 return true;
2063 PacketTimeList::const_iterator it = frame.received_packet_times.begin();
2064 QuicPacketSequenceNumber sequence_number = it->first;
2065 QuicPacketSequenceNumber delta_from_largest_observed =
2066 frame.largest_observed - sequence_number;
2068 DCHECK_GE(numeric_limits<uint8>::max(), delta_from_largest_observed);
2069 if (delta_from_largest_observed > numeric_limits<uint8>::max()) {
2070 return false;
2073 if (!writer->WriteUInt8(
2074 delta_from_largest_observed & k1ByteSequenceNumberMask)) {
2075 return false;
2078 // Use the lowest 4 bytes of the time delta from the creation_time_.
2079 const uint64 time_epoch_delta_us = GG_UINT64_C(1) << 32;
2080 uint32 time_delta_us =
2081 static_cast<uint32>(it->second.Subtract(creation_time_).ToMicroseconds()
2082 & (time_epoch_delta_us - 1));
2083 if (!writer->WriteBytes(&time_delta_us, sizeof(time_delta_us))) {
2084 return false;
2087 QuicTime prev_time = it->second;
2089 for (++it; it != frame.received_packet_times.end(); ++it) {
2090 sequence_number = it->first;
2091 delta_from_largest_observed = frame.largest_observed - sequence_number;
2093 if (delta_from_largest_observed > numeric_limits<uint8>::max()) {
2094 return false;
2097 if (!writer->WriteUInt8(
2098 delta_from_largest_observed & k1ByteSequenceNumberMask)) {
2099 return false;
2102 uint64 frame_time_delta_us =
2103 it->second.Subtract(prev_time).ToMicroseconds();
2104 prev_time = it->second;
2105 if (!writer->WriteUFloat16(frame_time_delta_us)) {
2106 return false;
2109 return true;
2112 bool QuicFramer::AppendStopWaitingFrame(
2113 const QuicPacketHeader& header,
2114 const QuicStopWaitingFrame& frame,
2115 QuicDataWriter* writer) {
2116 DCHECK_GE(header.packet_sequence_number, frame.least_unacked);
2117 const QuicPacketSequenceNumber least_unacked_delta =
2118 header.packet_sequence_number - frame.least_unacked;
2119 const QuicPacketSequenceNumber length_shift =
2120 header.public_header.sequence_number_length * 8;
2121 if (!writer->WriteUInt8(frame.entropy_hash)) {
2122 LOG(DFATAL) << " hash failed";
2123 return false;
2126 if (least_unacked_delta >> length_shift > 0) {
2127 LOG(DFATAL) << "sequence_number_length "
2128 << header.public_header.sequence_number_length
2129 << " is too small for least_unacked_delta: "
2130 << least_unacked_delta;
2131 return false;
2133 if (!AppendPacketSequenceNumber(header.public_header.sequence_number_length,
2134 least_unacked_delta, writer)) {
2135 LOG(DFATAL) << " seq failed: "
2136 << header.public_header.sequence_number_length;
2137 return false;
2140 return true;
2143 bool QuicFramer::AppendRstStreamFrame(
2144 const QuicRstStreamFrame& frame,
2145 QuicDataWriter* writer) {
2146 if (!writer->WriteUInt32(frame.stream_id)) {
2147 return false;
2150 if (!writer->WriteUInt64(frame.byte_offset)) {
2151 return false;
2154 uint32 error_code = static_cast<uint32>(frame.error_code);
2155 if (!writer->WriteUInt32(error_code)) {
2156 return false;
2159 if (!writer->WriteStringPiece16(frame.error_details)) {
2160 return false;
2162 return true;
2165 bool QuicFramer::AppendConnectionCloseFrame(
2166 const QuicConnectionCloseFrame& frame,
2167 QuicDataWriter* writer) {
2168 uint32 error_code = static_cast<uint32>(frame.error_code);
2169 if (!writer->WriteUInt32(error_code)) {
2170 return false;
2172 if (!writer->WriteStringPiece16(frame.error_details)) {
2173 return false;
2175 return true;
2178 bool QuicFramer::AppendGoAwayFrame(const QuicGoAwayFrame& frame,
2179 QuicDataWriter* writer) {
2180 uint32 error_code = static_cast<uint32>(frame.error_code);
2181 if (!writer->WriteUInt32(error_code)) {
2182 return false;
2184 uint32 stream_id = static_cast<uint32>(frame.last_good_stream_id);
2185 if (!writer->WriteUInt32(stream_id)) {
2186 return false;
2188 if (!writer->WriteStringPiece16(frame.reason_phrase)) {
2189 return false;
2191 return true;
2194 bool QuicFramer::AppendWindowUpdateFrame(const QuicWindowUpdateFrame& frame,
2195 QuicDataWriter* writer) {
2196 uint32 stream_id = static_cast<uint32>(frame.stream_id);
2197 if (!writer->WriteUInt32(stream_id)) {
2198 return false;
2200 if (!writer->WriteUInt64(frame.byte_offset)) {
2201 return false;
2203 return true;
2206 bool QuicFramer::AppendBlockedFrame(const QuicBlockedFrame& frame,
2207 QuicDataWriter* writer) {
2208 uint32 stream_id = static_cast<uint32>(frame.stream_id);
2209 if (!writer->WriteUInt32(stream_id)) {
2210 return false;
2212 return true;
2215 bool QuicFramer::RaiseError(QuicErrorCode error) {
2216 DVLOG(1) << "Error detail: " << detailed_error_;
2217 set_error(error);
2218 visitor_->OnError(this);
2219 reader_.reset(nullptr);
2220 return false;
2223 } // namespace net