Implement keycode text conversion functions for Ozone.
[chromium-blink-merge.git] / net / quic / quic_framer.cc
blobdb0d39dd88077f5f7a8fa167db1a3be100ee0b73
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/basictypes.h"
8 #include "base/logging.h"
9 #include "base/stl_util.h"
10 #include "net/quic/crypto/crypto_framer.h"
11 #include "net/quic/crypto/crypto_handshake_message.h"
12 #include "net/quic/crypto/crypto_protocol.h"
13 #include "net/quic/crypto/quic_decrypter.h"
14 #include "net/quic/crypto/quic_encrypter.h"
15 #include "net/quic/quic_data_reader.h"
16 #include "net/quic/quic_data_writer.h"
17 #include "net/quic/quic_flags.h"
18 #include "net/quic/quic_socket_address_coder.h"
19 #include "net/quic/quic_utils.h"
21 using base::StringPiece;
22 using std::map;
23 using std::max;
24 using std::min;
25 using std::numeric_limits;
26 using std::string;
28 namespace net {
30 namespace {
32 // Mask to select the lowest 48 bits of a sequence number.
33 const QuicPacketSequenceNumber k6ByteSequenceNumberMask =
34 GG_UINT64_C(0x0000FFFFFFFFFFFF);
35 const QuicPacketSequenceNumber k4ByteSequenceNumberMask =
36 GG_UINT64_C(0x00000000FFFFFFFF);
37 const QuicPacketSequenceNumber k2ByteSequenceNumberMask =
38 GG_UINT64_C(0x000000000000FFFF);
39 const QuicPacketSequenceNumber k1ByteSequenceNumberMask =
40 GG_UINT64_C(0x00000000000000FF);
42 const QuicConnectionId k1ByteConnectionIdMask = GG_UINT64_C(0x00000000000000FF);
43 const QuicConnectionId k4ByteConnectionIdMask = GG_UINT64_C(0x00000000FFFFFFFF);
45 // Number of bits the sequence number length bits are shifted from the right
46 // edge of the public header.
47 const uint8 kPublicHeaderSequenceNumberShift = 4;
49 // New Frame Types, QUIC v. >= 10:
50 // There are two interpretations for the Frame Type byte in the QUIC protocol,
51 // resulting in two Frame Types: Special Frame Types and Regular Frame Types.
53 // Regular Frame Types use the Frame Type byte simply. Currently defined
54 // Regular Frame Types are:
55 // Padding : 0b 00000000 (0x00)
56 // ResetStream : 0b 00000001 (0x01)
57 // ConnectionClose : 0b 00000010 (0x02)
58 // GoAway : 0b 00000011 (0x03)
59 // WindowUpdate : 0b 00000100 (0x04)
60 // Blocked : 0b 00000101 (0x05)
62 // Special Frame Types encode both a Frame Type and corresponding flags
63 // all in the Frame Type byte. Currently defined Special Frame Types are:
64 // Stream : 0b 1xxxxxxx
65 // Ack : 0b 01xxxxxx
67 // Semantics of the flag bits above (the x bits) depends on the frame type.
69 // Masks to determine if the frame type is a special use
70 // and for specific special frame types.
71 const uint8 kQuicFrameTypeSpecialMask = 0xE0; // 0b 11100000
72 const uint8 kQuicFrameTypeStreamMask = 0x80;
73 const uint8 kQuicFrameTypeAckMask = 0x40;
75 // Stream frame relative shifts and masks for interpreting the stream flags.
76 // StreamID may be 1, 2, 3, or 4 bytes.
77 const uint8 kQuicStreamIdShift = 2;
78 const uint8 kQuicStreamIDLengthMask = 0x03;
80 // Offset may be 0, 2, 3, 4, 5, 6, 7, 8 bytes.
81 const uint8 kQuicStreamOffsetShift = 3;
82 const uint8 kQuicStreamOffsetMask = 0x07;
84 // Data length may be 0 or 2 bytes.
85 const uint8 kQuicStreamDataLengthShift = 1;
86 const uint8 kQuicStreamDataLengthMask = 0x01;
88 // Fin bit may be set or not.
89 const uint8 kQuicStreamFinShift = 1;
90 const uint8 kQuicStreamFinMask = 0x01;
92 // Sequence number size shift used in AckFrames.
93 const uint8 kQuicSequenceNumberLengthShift = 2;
95 // Acks may be truncated.
96 const uint8 kQuicAckTruncatedShift = 1;
97 const uint8 kQuicAckTruncatedMask = 0x01;
99 // Acks may not have any nacks.
100 const uint8 kQuicHasNacksMask = 0x01;
102 // Returns the absolute value of the difference between |a| and |b|.
103 QuicPacketSequenceNumber Delta(QuicPacketSequenceNumber a,
104 QuicPacketSequenceNumber b) {
105 // Since these are unsigned numbers, we can't just return abs(a - b)
106 if (a < b) {
107 return b - a;
109 return a - b;
112 QuicPacketSequenceNumber ClosestTo(QuicPacketSequenceNumber target,
113 QuicPacketSequenceNumber a,
114 QuicPacketSequenceNumber b) {
115 return (Delta(target, a) < Delta(target, b)) ? a : b;
118 QuicSequenceNumberLength ReadSequenceNumberLength(uint8 flags) {
119 switch (flags & PACKET_FLAGS_6BYTE_SEQUENCE) {
120 case PACKET_FLAGS_6BYTE_SEQUENCE:
121 return PACKET_6BYTE_SEQUENCE_NUMBER;
122 case PACKET_FLAGS_4BYTE_SEQUENCE:
123 return PACKET_4BYTE_SEQUENCE_NUMBER;
124 case PACKET_FLAGS_2BYTE_SEQUENCE:
125 return PACKET_2BYTE_SEQUENCE_NUMBER;
126 case PACKET_FLAGS_1BYTE_SEQUENCE:
127 return PACKET_1BYTE_SEQUENCE_NUMBER;
128 default:
129 LOG(DFATAL) << "Unreachable case statement.";
130 return PACKET_6BYTE_SEQUENCE_NUMBER;
134 } // namespace
136 bool QuicFramerVisitorInterface::OnWindowUpdateFrame(
137 const QuicWindowUpdateFrame& frame) {
138 return true;
141 bool QuicFramerVisitorInterface::OnBlockedFrame(const QuicBlockedFrame& frame) {
142 return true;
145 QuicFramer::QuicFramer(const QuicVersionVector& supported_versions,
146 QuicTime creation_time,
147 Perspective perspective)
148 : visitor_(nullptr),
149 entropy_calculator_(nullptr),
150 error_(QUIC_NO_ERROR),
151 last_sequence_number_(0),
152 last_serialized_connection_id_(0),
153 supported_versions_(supported_versions),
154 decrypter_level_(ENCRYPTION_NONE),
155 alternative_decrypter_level_(ENCRYPTION_NONE),
156 alternative_decrypter_latch_(false),
157 perspective_(perspective),
158 validate_flags_(true),
159 creation_time_(creation_time),
160 last_timestamp_(QuicTime::Delta::Zero()) {
161 DCHECK(!supported_versions.empty());
162 quic_version_ = supported_versions_[0];
163 decrypter_.reset(QuicDecrypter::Create(kNULL));
164 encrypter_[ENCRYPTION_NONE].reset(QuicEncrypter::Create(kNULL));
167 QuicFramer::~QuicFramer() {}
169 // static
170 size_t QuicFramer::GetMinStreamFrameSize(QuicStreamId stream_id,
171 QuicStreamOffset offset,
172 bool last_frame_in_packet,
173 InFecGroup is_in_fec_group) {
174 bool no_stream_frame_length = last_frame_in_packet &&
175 is_in_fec_group == NOT_IN_FEC_GROUP;
176 return kQuicFrameTypeSize + GetStreamIdSize(stream_id) +
177 GetStreamOffsetSize(offset) +
178 (no_stream_frame_length ? 0 : kQuicStreamPayloadLengthSize);
181 // static
182 size_t QuicFramer::GetMinAckFrameSize(
183 QuicSequenceNumberLength sequence_number_length,
184 QuicSequenceNumberLength largest_observed_length) {
185 return kQuicFrameTypeSize + kQuicEntropyHashSize +
186 largest_observed_length + kQuicDeltaTimeLargestObservedSize;
189 // static
190 size_t QuicFramer::GetStopWaitingFrameSize(
191 QuicSequenceNumberLength sequence_number_length) {
192 return kQuicFrameTypeSize + kQuicEntropyHashSize +
193 sequence_number_length;
196 // static
197 size_t QuicFramer::GetMinRstStreamFrameSize() {
198 return kQuicFrameTypeSize + kQuicMaxStreamIdSize +
199 kQuicMaxStreamOffsetSize + kQuicErrorCodeSize +
200 kQuicErrorDetailsLengthSize;
203 // static
204 size_t QuicFramer::GetRstStreamFrameSize() {
205 return kQuicFrameTypeSize + kQuicMaxStreamIdSize + kQuicMaxStreamOffsetSize +
206 kQuicErrorCodeSize;
209 // static
210 size_t QuicFramer::GetMinConnectionCloseFrameSize() {
211 return kQuicFrameTypeSize + kQuicErrorCodeSize + kQuicErrorDetailsLengthSize;
214 // static
215 size_t QuicFramer::GetMinGoAwayFrameSize() {
216 return kQuicFrameTypeSize + kQuicErrorCodeSize + kQuicErrorDetailsLengthSize +
217 kQuicMaxStreamIdSize;
220 // static
221 size_t QuicFramer::GetWindowUpdateFrameSize() {
222 return kQuicFrameTypeSize + kQuicMaxStreamIdSize + kQuicMaxStreamOffsetSize;
225 // static
226 size_t QuicFramer::GetBlockedFrameSize() {
227 return kQuicFrameTypeSize + kQuicMaxStreamIdSize;
230 // static
231 size_t QuicFramer::GetStreamIdSize(QuicStreamId stream_id) {
232 // Sizes are 1 through 4 bytes.
233 for (int i = 1; i <= 4; ++i) {
234 stream_id >>= 8;
235 if (stream_id == 0) {
236 return i;
239 LOG(DFATAL) << "Failed to determine StreamIDSize.";
240 return 4;
243 // static
244 size_t QuicFramer::GetStreamOffsetSize(QuicStreamOffset offset) {
245 // 0 is a special case.
246 if (offset == 0) {
247 return 0;
249 // 2 through 8 are the remaining sizes.
250 offset >>= 8;
251 for (int i = 2; i <= 8; ++i) {
252 offset >>= 8;
253 if (offset == 0) {
254 return i;
257 LOG(DFATAL) << "Failed to determine StreamOffsetSize.";
258 return 8;
261 // static
262 size_t QuicFramer::GetVersionNegotiationPacketSize(size_t number_versions) {
263 return kPublicFlagsSize + PACKET_8BYTE_CONNECTION_ID +
264 number_versions * kQuicVersionSize;
267 bool QuicFramer::IsSupportedVersion(const QuicVersion version) const {
268 for (size_t i = 0; i < supported_versions_.size(); ++i) {
269 if (version == supported_versions_[i]) {
270 return true;
273 return false;
276 size_t QuicFramer::GetSerializedFrameLength(
277 const QuicFrame& frame,
278 size_t free_bytes,
279 bool first_frame,
280 bool last_frame,
281 InFecGroup is_in_fec_group,
282 QuicSequenceNumberLength sequence_number_length) {
283 // Prevent a rare crash reported in b/19458523.
284 if (frame.stream_frame == nullptr) {
285 LOG(DFATAL) << "Cannot compute the length of a null frame. "
286 << "type:" << frame.type << "free_bytes:" << free_bytes
287 << " first_frame:" << first_frame
288 << " last_frame:" << last_frame
289 << " is_in_fec:" << is_in_fec_group
290 << " seq num length:" << sequence_number_length;
291 set_error(QUIC_INTERNAL_ERROR);
292 visitor_->OnError(this);
293 return false;
295 if (frame.type == PADDING_FRAME) {
296 // PADDING implies end of packet.
297 return free_bytes;
299 size_t frame_len =
300 ComputeFrameLength(frame, last_frame, is_in_fec_group,
301 sequence_number_length);
302 if (frame_len <= free_bytes) {
303 // Frame fits within packet. Note that acks may be truncated.
304 return frame_len;
306 // Only truncate the first frame in a packet, so if subsequent ones go
307 // over, stop including more frames.
308 if (!first_frame) {
309 return 0;
311 bool can_truncate = frame.type == ACK_FRAME &&
312 free_bytes >= GetMinAckFrameSize(PACKET_6BYTE_SEQUENCE_NUMBER,
313 PACKET_6BYTE_SEQUENCE_NUMBER);
314 if (can_truncate) {
315 // Truncate the frame so the packet will not exceed kMaxPacketSize.
316 // Note that we may not use every byte of the writer in this case.
317 DVLOG(1) << "Truncating large frame, free bytes: " << free_bytes;
318 return free_bytes;
320 if (!FLAGS_quic_allow_oversized_packets_for_test) {
321 return 0;
323 LOG(DFATAL) << "Packet size too small to fit frame.";
324 return frame_len;
327 QuicFramer::AckFrameInfo::AckFrameInfo() : max_delta(0) {}
329 QuicFramer::AckFrameInfo::~AckFrameInfo() {}
331 // static
332 QuicPacketEntropyHash QuicFramer::GetPacketEntropyHash(
333 const QuicPacketHeader& header) {
334 return header.entropy_flag << (header.packet_sequence_number % 8);
337 QuicPacket* QuicFramer::BuildDataPacket(const QuicPacketHeader& header,
338 const QuicFrames& frames,
339 char* buffer,
340 size_t packet_length) {
341 QuicDataWriter writer(packet_length, buffer);
342 if (!AppendPacketHeader(header, &writer)) {
343 LOG(DFATAL) << "AppendPacketHeader failed";
344 return nullptr;
347 size_t i = 0;
348 for (const QuicFrame& frame : frames) {
349 // Determine if we should write stream frame length in header.
350 const bool no_stream_frame_length =
351 (header.is_in_fec_group == NOT_IN_FEC_GROUP) &&
352 (i == frames.size() - 1);
353 if (!AppendTypeByte(frame, no_stream_frame_length, &writer)) {
354 LOG(DFATAL) << "AppendTypeByte failed";
355 return nullptr;
358 switch (frame.type) {
359 case PADDING_FRAME:
360 writer.WritePadding();
361 break;
362 case STREAM_FRAME:
363 if (!AppendStreamFrame(
364 *frame.stream_frame, no_stream_frame_length, &writer)) {
365 LOG(DFATAL) << "AppendStreamFrame failed";
366 return nullptr;
368 break;
369 case ACK_FRAME:
370 if (!AppendAckFrameAndTypeByte(
371 header, *frame.ack_frame, &writer)) {
372 LOG(DFATAL) << "AppendAckFrameAndTypeByte failed";
373 return nullptr;
375 break;
376 case STOP_WAITING_FRAME:
377 if (!AppendStopWaitingFrame(
378 header, *frame.stop_waiting_frame, &writer)) {
379 LOG(DFATAL) << "AppendStopWaitingFrame failed";
380 return nullptr;
382 break;
383 case PING_FRAME:
384 // Ping has no payload.
385 break;
386 case RST_STREAM_FRAME:
387 if (!AppendRstStreamFrame(*frame.rst_stream_frame, &writer)) {
388 LOG(DFATAL) << "AppendRstStreamFrame failed";
389 return nullptr;
391 break;
392 case CONNECTION_CLOSE_FRAME:
393 if (!AppendConnectionCloseFrame(
394 *frame.connection_close_frame, &writer)) {
395 LOG(DFATAL) << "AppendConnectionCloseFrame failed";
396 return nullptr;
398 break;
399 case GOAWAY_FRAME:
400 if (!AppendGoAwayFrame(*frame.goaway_frame, &writer)) {
401 LOG(DFATAL) << "AppendGoAwayFrame failed";
402 return nullptr;
404 break;
405 case WINDOW_UPDATE_FRAME:
406 if (!AppendWindowUpdateFrame(*frame.window_update_frame, &writer)) {
407 LOG(DFATAL) << "AppendWindowUpdateFrame failed";
408 return nullptr;
410 break;
411 case BLOCKED_FRAME:
412 if (!AppendBlockedFrame(*frame.blocked_frame, &writer)) {
413 LOG(DFATAL) << "AppendBlockedFrame failed";
414 return nullptr;
416 break;
417 default:
418 RaiseError(QUIC_INVALID_FRAME_DATA);
419 LOG(DFATAL) << "QUIC_INVALID_FRAME_DATA";
420 return nullptr;
422 ++i;
425 QuicPacket* packet =
426 new QuicPacket(writer.data(), writer.length(), false,
427 header.public_header.connection_id_length,
428 header.public_header.version_flag,
429 header.public_header.sequence_number_length);
431 return packet;
434 QuicPacket* QuicFramer::BuildFecPacket(const QuicPacketHeader& header,
435 const QuicFecData& fec) {
436 DCHECK_EQ(IN_FEC_GROUP, header.is_in_fec_group);
437 DCHECK_NE(0u, header.fec_group);
438 size_t len = GetPacketHeaderSize(header);
439 len += fec.redundancy.length();
441 scoped_ptr<char[]> buffer(new char[len]);
442 QuicDataWriter writer(len, buffer.get());
443 if (!AppendPacketHeader(header, &writer)) {
444 LOG(DFATAL) << "AppendPacketHeader failed";
445 return nullptr;
448 if (!writer.WriteBytes(fec.redundancy.data(), fec.redundancy.length())) {
449 LOG(DFATAL) << "Failed to add FEC";
450 return nullptr;
453 return new QuicPacket(buffer.release(), len, true,
454 header.public_header.connection_id_length,
455 header.public_header.version_flag,
456 header.public_header.sequence_number_length);
459 // static
460 QuicEncryptedPacket* QuicFramer::BuildPublicResetPacket(
461 const QuicPublicResetPacket& packet) {
462 DCHECK(packet.public_header.reset_flag);
464 CryptoHandshakeMessage reset;
465 reset.set_tag(kPRST);
466 reset.SetValue(kRNON, packet.nonce_proof);
467 reset.SetValue(kRSEQ, packet.rejected_sequence_number);
468 if (!packet.client_address.address().empty()) {
469 // packet.client_address is non-empty.
470 QuicSocketAddressCoder address_coder(packet.client_address);
471 string serialized_address = address_coder.Encode();
472 if (serialized_address.empty()) {
473 return nullptr;
475 reset.SetStringPiece(kCADR, serialized_address);
477 const QuicData& reset_serialized = reset.GetSerialized();
479 size_t len =
480 kPublicFlagsSize + PACKET_8BYTE_CONNECTION_ID + reset_serialized.length();
481 scoped_ptr<char[]> buffer(new char[len]);
482 QuicDataWriter writer(len, buffer.get());
484 uint8 flags = static_cast<uint8>(PACKET_PUBLIC_FLAGS_RST |
485 PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID);
486 if (!writer.WriteUInt8(flags)) {
487 return nullptr;
490 if (!writer.WriteUInt64(packet.public_header.connection_id)) {
491 return nullptr;
494 if (!writer.WriteBytes(reset_serialized.data(), reset_serialized.length())) {
495 return nullptr;
498 return new QuicEncryptedPacket(buffer.release(), len, true);
501 QuicEncryptedPacket* QuicFramer::BuildVersionNegotiationPacket(
502 const QuicPacketPublicHeader& header,
503 const QuicVersionVector& supported_versions) {
504 DCHECK(header.version_flag);
505 size_t len = GetVersionNegotiationPacketSize(supported_versions.size());
506 scoped_ptr<char[]> buffer(new char[len]);
507 QuicDataWriter writer(len, buffer.get());
509 uint8 flags = static_cast<uint8>(PACKET_PUBLIC_FLAGS_VERSION |
510 PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID);
511 if (!writer.WriteUInt8(flags)) {
512 return nullptr;
515 if (!writer.WriteUInt64(header.connection_id)) {
516 return nullptr;
519 for (size_t i = 0; i < supported_versions.size(); ++i) {
520 if (!writer.WriteUInt32(QuicVersionToQuicTag(supported_versions[i]))) {
521 return nullptr;
525 return new QuicEncryptedPacket(buffer.release(), len, true);
528 bool QuicFramer::ProcessPacket(const QuicEncryptedPacket& packet) {
529 DCHECK(!reader_.get());
530 reader_.reset(new QuicDataReader(packet.data(), packet.length()));
532 visitor_->OnPacket();
534 // First parse the public header.
535 QuicPacketPublicHeader public_header;
536 if (!ProcessPublicHeader(&public_header)) {
537 DLOG(WARNING) << "Unable to process public header.";
538 DCHECK_NE("", detailed_error_);
539 return RaiseError(QUIC_INVALID_PACKET_HEADER);
542 if (!visitor_->OnUnauthenticatedPublicHeader(public_header)) {
543 // The visitor suppresses further processing of the packet.
544 reader_.reset(nullptr);
545 return true;
548 if (perspective_ == Perspective::IS_SERVER && public_header.version_flag &&
549 public_header.versions[0] != quic_version_) {
550 if (!visitor_->OnProtocolVersionMismatch(public_header.versions[0])) {
551 reader_.reset(nullptr);
552 return true;
556 bool rv;
557 if (perspective_ == Perspective::IS_CLIENT && public_header.version_flag) {
558 rv = ProcessVersionNegotiationPacket(&public_header);
559 } else if (public_header.reset_flag) {
560 rv = ProcessPublicResetPacket(public_header);
561 } else if (packet.length() <= kMaxPacketSize) {
562 char buffer[kMaxPacketSize];
563 rv = ProcessDataPacket(public_header, packet, buffer, kMaxPacketSize);
564 } else {
565 scoped_ptr<char[]> large_buffer(new char[packet.length()]);
566 rv = ProcessDataPacket(public_header, packet, large_buffer.get(),
567 packet.length());
568 LOG_IF(DFATAL, rv) << "QUIC should never successfully process packets "
569 << "larger than kMaxPacketSize. packet size:"
570 << packet.length();
573 reader_.reset(nullptr);
574 return rv;
577 bool QuicFramer::ProcessVersionNegotiationPacket(
578 QuicPacketPublicHeader* public_header) {
579 DCHECK_EQ(Perspective::IS_CLIENT, perspective_);
580 // Try reading at least once to raise error if the packet is invalid.
581 do {
582 QuicTag version;
583 if (!reader_->ReadBytes(&version, kQuicVersionSize)) {
584 set_detailed_error("Unable to read supported version in negotiation.");
585 return RaiseError(QUIC_INVALID_VERSION_NEGOTIATION_PACKET);
587 public_header->versions.push_back(QuicTagToQuicVersion(version));
588 } while (!reader_->IsDoneReading());
590 visitor_->OnVersionNegotiationPacket(*public_header);
591 return true;
594 bool QuicFramer::ProcessDataPacket(const QuicPacketPublicHeader& public_header,
595 const QuicEncryptedPacket& packet,
596 char* decrypted_buffer,
597 size_t buffer_length) {
598 QuicPacketHeader header(public_header);
599 if (!ProcessPacketHeader(&header, packet, decrypted_buffer, buffer_length)) {
600 DLOG(WARNING) << "Unable to process packet header. Stopping parsing.";
601 return false;
604 if (!visitor_->OnPacketHeader(header)) {
605 // The visitor suppresses further processing of the packet.
606 return true;
609 if (packet.length() > kMaxPacketSize) {
610 DLOG(WARNING) << "Packet too large: " << packet.length();
611 return RaiseError(QUIC_PACKET_TOO_LARGE);
614 // Handle the payload.
615 if (!header.fec_flag) {
616 if (header.is_in_fec_group == IN_FEC_GROUP) {
617 StringPiece payload = reader_->PeekRemainingPayload();
618 visitor_->OnFecProtectedPayload(payload);
620 if (!ProcessFrameData(header)) {
621 DCHECK_NE(QUIC_NO_ERROR, error_); // ProcessFrameData sets the error.
622 DLOG(WARNING) << "Unable to process frame data.";
623 return false;
625 } else {
626 QuicFecData fec_data;
627 fec_data.fec_group = header.fec_group;
628 fec_data.redundancy = reader_->ReadRemainingPayload();
629 visitor_->OnFecData(fec_data);
632 visitor_->OnPacketComplete();
633 return true;
636 bool QuicFramer::ProcessPublicResetPacket(
637 const QuicPacketPublicHeader& public_header) {
638 QuicPublicResetPacket packet(public_header);
640 scoped_ptr<CryptoHandshakeMessage> reset(
641 CryptoFramer::ParseMessage(reader_->ReadRemainingPayload()));
642 if (!reset.get()) {
643 set_detailed_error("Unable to read reset message.");
644 return RaiseError(QUIC_INVALID_PUBLIC_RST_PACKET);
646 if (reset->tag() != kPRST) {
647 set_detailed_error("Incorrect message tag.");
648 return RaiseError(QUIC_INVALID_PUBLIC_RST_PACKET);
651 if (reset->GetUint64(kRNON, &packet.nonce_proof) != QUIC_NO_ERROR) {
652 set_detailed_error("Unable to read nonce proof.");
653 return RaiseError(QUIC_INVALID_PUBLIC_RST_PACKET);
655 // TODO(satyamshekhar): validate nonce to protect against DoS.
657 if (reset->GetUint64(kRSEQ, &packet.rejected_sequence_number) !=
658 QUIC_NO_ERROR) {
659 set_detailed_error("Unable to read rejected sequence number.");
660 return RaiseError(QUIC_INVALID_PUBLIC_RST_PACKET);
663 StringPiece address;
664 if (reset->GetStringPiece(kCADR, &address)) {
665 QuicSocketAddressCoder address_coder;
666 if (address_coder.Decode(address.data(), address.length())) {
667 packet.client_address = IPEndPoint(address_coder.ip(),
668 address_coder.port());
672 visitor_->OnPublicResetPacket(packet);
673 return true;
676 bool QuicFramer::ProcessRevivedPacket(QuicPacketHeader* header,
677 StringPiece payload) {
678 DCHECK(!reader_.get());
680 visitor_->OnRevivedPacket();
682 header->entropy_hash = GetPacketEntropyHash(*header);
684 if (!visitor_->OnPacketHeader(*header)) {
685 return true;
688 if (payload.length() > kMaxPacketSize) {
689 set_detailed_error("Revived packet too large.");
690 return RaiseError(QUIC_PACKET_TOO_LARGE);
693 reader_.reset(new QuicDataReader(payload.data(), payload.length()));
694 if (!ProcessFrameData(*header)) {
695 DCHECK_NE(QUIC_NO_ERROR, error_); // ProcessFrameData sets the error.
696 DLOG(WARNING) << "Unable to process frame data.";
697 return false;
700 visitor_->OnPacketComplete();
701 reader_.reset(nullptr);
702 return true;
705 bool QuicFramer::AppendPacketHeader(const QuicPacketHeader& header,
706 QuicDataWriter* writer) {
707 DVLOG(1) << "Appending header: " << header;
708 DCHECK(header.fec_group > 0 || header.is_in_fec_group == NOT_IN_FEC_GROUP);
709 uint8 public_flags = 0;
710 if (header.public_header.reset_flag) {
711 public_flags |= PACKET_PUBLIC_FLAGS_RST;
713 if (header.public_header.version_flag) {
714 public_flags |= PACKET_PUBLIC_FLAGS_VERSION;
717 public_flags |=
718 GetSequenceNumberFlags(header.public_header.sequence_number_length)
719 << kPublicHeaderSequenceNumberShift;
721 switch (header.public_header.connection_id_length) {
722 case PACKET_0BYTE_CONNECTION_ID:
723 if (!writer->WriteUInt8(
724 public_flags | PACKET_PUBLIC_FLAGS_0BYTE_CONNECTION_ID)) {
725 return false;
727 break;
728 case PACKET_1BYTE_CONNECTION_ID:
729 if (!writer->WriteUInt8(
730 public_flags | PACKET_PUBLIC_FLAGS_1BYTE_CONNECTION_ID)) {
731 return false;
733 if (!writer->WriteUInt8(
734 header.public_header.connection_id & k1ByteConnectionIdMask)) {
735 return false;
737 break;
738 case PACKET_4BYTE_CONNECTION_ID:
739 if (!writer->WriteUInt8(
740 public_flags | PACKET_PUBLIC_FLAGS_4BYTE_CONNECTION_ID)) {
741 return false;
743 if (!writer->WriteUInt32(
744 header.public_header.connection_id & k4ByteConnectionIdMask)) {
745 return false;
747 break;
748 case PACKET_8BYTE_CONNECTION_ID:
749 if (!writer->WriteUInt8(
750 public_flags | PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID)) {
751 return false;
753 if (!writer->WriteUInt64(header.public_header.connection_id)) {
754 return false;
756 break;
758 last_serialized_connection_id_ = header.public_header.connection_id;
760 if (header.public_header.version_flag) {
761 DCHECK_EQ(Perspective::IS_CLIENT, perspective_);
762 QuicTag tag = QuicVersionToQuicTag(quic_version_);
763 writer->WriteUInt32(tag);
764 DVLOG(1) << "version = " << quic_version_ << ", tag = '"
765 << QuicUtils::TagToString(tag) << "'";
768 if (!AppendPacketSequenceNumber(header.public_header.sequence_number_length,
769 header.packet_sequence_number, writer)) {
770 return false;
773 uint8 private_flags = 0;
774 if (header.entropy_flag) {
775 private_flags |= PACKET_PRIVATE_FLAGS_ENTROPY;
777 if (header.is_in_fec_group == IN_FEC_GROUP) {
778 private_flags |= PACKET_PRIVATE_FLAGS_FEC_GROUP;
780 if (header.fec_flag) {
781 private_flags |= PACKET_PRIVATE_FLAGS_FEC;
783 if (!writer->WriteUInt8(private_flags)) {
784 return false;
787 // The FEC group number is the sequence number of the first fec
788 // protected packet, or 0 if this packet is not protected.
789 if (header.is_in_fec_group == IN_FEC_GROUP) {
790 DCHECK_LE(header.fec_group, header.packet_sequence_number);
791 DCHECK_LT(header.packet_sequence_number - header.fec_group, 255u);
792 // Offset from the current packet sequence number to the first fec
793 // protected packet.
794 uint8 first_fec_protected_packet_offset =
795 static_cast<uint8>(header.packet_sequence_number - header.fec_group);
796 if (!writer->WriteBytes(&first_fec_protected_packet_offset, 1)) {
797 return false;
801 return true;
804 const QuicTime::Delta QuicFramer::CalculateTimestampFromWire(
805 uint32 time_delta_us) {
806 // The new time_delta might have wrapped to the next epoch, or it
807 // might have reverse wrapped to the previous epoch, or it might
808 // remain in the same epoch. Select the time closest to the previous
809 // time.
811 // epoch_delta is the delta between epochs. A delta is 4 bytes of
812 // microseconds.
813 const uint64 epoch_delta = GG_UINT64_C(1) << 32;
814 uint64 epoch = last_timestamp_.ToMicroseconds() & ~(epoch_delta - 1);
815 // Wrapping is safe here because a wrapped value will not be ClosestTo below.
816 uint64 prev_epoch = epoch - epoch_delta;
817 uint64 next_epoch = epoch + epoch_delta;
819 uint64 time = ClosestTo(last_timestamp_.ToMicroseconds(),
820 epoch + time_delta_us,
821 ClosestTo(last_timestamp_.ToMicroseconds(),
822 prev_epoch + time_delta_us,
823 next_epoch + time_delta_us));
825 return QuicTime::Delta::FromMicroseconds(time);
828 QuicPacketSequenceNumber QuicFramer::CalculatePacketSequenceNumberFromWire(
829 QuicSequenceNumberLength sequence_number_length,
830 QuicPacketSequenceNumber packet_sequence_number) const {
831 // The new sequence number might have wrapped to the next epoch, or
832 // it might have reverse wrapped to the previous epoch, or it might
833 // remain in the same epoch. Select the sequence number closest to the
834 // next expected sequence number, the previous sequence number plus 1.
836 // epoch_delta is the delta between epochs the sequence number was serialized
837 // with, so the correct value is likely the same epoch as the last sequence
838 // number or an adjacent epoch.
839 const QuicPacketSequenceNumber epoch_delta =
840 GG_UINT64_C(1) << (8 * sequence_number_length);
841 QuicPacketSequenceNumber next_sequence_number = last_sequence_number_ + 1;
842 QuicPacketSequenceNumber epoch = last_sequence_number_ & ~(epoch_delta - 1);
843 QuicPacketSequenceNumber prev_epoch = epoch - epoch_delta;
844 QuicPacketSequenceNumber next_epoch = epoch + epoch_delta;
846 return ClosestTo(next_sequence_number,
847 epoch + packet_sequence_number,
848 ClosestTo(next_sequence_number,
849 prev_epoch + packet_sequence_number,
850 next_epoch + packet_sequence_number));
853 bool QuicFramer::ProcessPublicHeader(
854 QuicPacketPublicHeader* public_header) {
855 uint8 public_flags;
856 if (!reader_->ReadBytes(&public_flags, 1)) {
857 set_detailed_error("Unable to read public flags.");
858 return false;
861 public_header->reset_flag = (public_flags & PACKET_PUBLIC_FLAGS_RST) != 0;
862 public_header->version_flag =
863 (public_flags & PACKET_PUBLIC_FLAGS_VERSION) != 0;
865 if (validate_flags_ &&
866 !public_header->version_flag && public_flags > PACKET_PUBLIC_FLAGS_MAX) {
867 set_detailed_error("Illegal public flags value.");
868 return false;
871 if (public_header->reset_flag && public_header->version_flag) {
872 set_detailed_error("Got version flag in reset packet");
873 return false;
876 switch (public_flags & PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID) {
877 case PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID:
878 if (!reader_->ReadUInt64(&public_header->connection_id)) {
879 set_detailed_error("Unable to read ConnectionId.");
880 return false;
882 public_header->connection_id_length = PACKET_8BYTE_CONNECTION_ID;
883 break;
884 case PACKET_PUBLIC_FLAGS_4BYTE_CONNECTION_ID:
885 // If the connection_id is truncated, expect to read the last serialized
886 // connection_id.
887 if (!reader_->ReadBytes(&public_header->connection_id,
888 PACKET_4BYTE_CONNECTION_ID)) {
889 set_detailed_error("Unable to read ConnectionId.");
890 return false;
892 if (last_serialized_connection_id_ &&
893 (public_header->connection_id & k4ByteConnectionIdMask) !=
894 (last_serialized_connection_id_ & k4ByteConnectionIdMask)) {
895 set_detailed_error("Truncated 4 byte ConnectionId does not match "
896 "previous connection_id.");
897 return false;
899 public_header->connection_id_length = PACKET_4BYTE_CONNECTION_ID;
900 public_header->connection_id = last_serialized_connection_id_;
901 break;
902 case PACKET_PUBLIC_FLAGS_1BYTE_CONNECTION_ID:
903 if (!reader_->ReadBytes(&public_header->connection_id,
904 PACKET_1BYTE_CONNECTION_ID)) {
905 set_detailed_error("Unable to read ConnectionId.");
906 return false;
908 if (last_serialized_connection_id_ &&
909 (public_header->connection_id & k1ByteConnectionIdMask) !=
910 (last_serialized_connection_id_ & k1ByteConnectionIdMask)) {
911 set_detailed_error("Truncated 1 byte ConnectionId does not match "
912 "previous connection_id.");
913 return false;
915 public_header->connection_id_length = PACKET_1BYTE_CONNECTION_ID;
916 public_header->connection_id = last_serialized_connection_id_;
917 break;
918 case PACKET_PUBLIC_FLAGS_0BYTE_CONNECTION_ID:
919 public_header->connection_id_length = PACKET_0BYTE_CONNECTION_ID;
920 public_header->connection_id = last_serialized_connection_id_;
921 break;
924 public_header->sequence_number_length =
925 ReadSequenceNumberLength(
926 public_flags >> kPublicHeaderSequenceNumberShift);
928 // Read the version only if the packet is from the client.
929 // version flag from the server means version negotiation packet.
930 if (public_header->version_flag && perspective_ == Perspective::IS_SERVER) {
931 QuicTag version_tag;
932 if (!reader_->ReadUInt32(&version_tag)) {
933 set_detailed_error("Unable to read protocol version.");
934 return false;
937 // If the version from the new packet is the same as the version of this
938 // framer, then the public flags should be set to something we understand.
939 // If not, this raises an error.
940 QuicVersion version = QuicTagToQuicVersion(version_tag);
941 if (version == quic_version_ && public_flags > PACKET_PUBLIC_FLAGS_MAX) {
942 set_detailed_error("Illegal public flags value.");
943 return false;
945 public_header->versions.push_back(version);
947 return true;
950 // static
951 QuicSequenceNumberLength QuicFramer::GetMinSequenceNumberLength(
952 QuicPacketSequenceNumber sequence_number) {
953 if (sequence_number < 1 << (PACKET_1BYTE_SEQUENCE_NUMBER * 8)) {
954 return PACKET_1BYTE_SEQUENCE_NUMBER;
955 } else if (sequence_number < 1 << (PACKET_2BYTE_SEQUENCE_NUMBER * 8)) {
956 return PACKET_2BYTE_SEQUENCE_NUMBER;
957 } else if (sequence_number <
958 GG_UINT64_C(1) << (PACKET_4BYTE_SEQUENCE_NUMBER * 8)) {
959 return PACKET_4BYTE_SEQUENCE_NUMBER;
960 } else {
961 return PACKET_6BYTE_SEQUENCE_NUMBER;
965 // static
966 uint8 QuicFramer::GetSequenceNumberFlags(
967 QuicSequenceNumberLength sequence_number_length) {
968 switch (sequence_number_length) {
969 case PACKET_1BYTE_SEQUENCE_NUMBER:
970 return PACKET_FLAGS_1BYTE_SEQUENCE;
971 case PACKET_2BYTE_SEQUENCE_NUMBER:
972 return PACKET_FLAGS_2BYTE_SEQUENCE;
973 case PACKET_4BYTE_SEQUENCE_NUMBER:
974 return PACKET_FLAGS_4BYTE_SEQUENCE;
975 case PACKET_6BYTE_SEQUENCE_NUMBER:
976 return PACKET_FLAGS_6BYTE_SEQUENCE;
977 default:
978 LOG(DFATAL) << "Unreachable case statement.";
979 return PACKET_FLAGS_6BYTE_SEQUENCE;
983 // static
984 QuicFramer::AckFrameInfo QuicFramer::GetAckFrameInfo(
985 const QuicAckFrame& frame) {
986 AckFrameInfo ack_info;
987 if (frame.missing_packets.empty()) {
988 return ack_info;
990 DCHECK_GE(frame.largest_observed, *frame.missing_packets.rbegin());
991 size_t cur_range_length = 0;
992 SequenceNumberSet::const_iterator iter = frame.missing_packets.begin();
993 QuicPacketSequenceNumber last_missing = *iter;
994 ++iter;
995 for (; iter != frame.missing_packets.end(); ++iter) {
996 if (cur_range_length < numeric_limits<uint8>::max() &&
997 *iter == (last_missing + 1)) {
998 ++cur_range_length;
999 } else {
1000 ack_info.nack_ranges[last_missing - cur_range_length] =
1001 static_cast<uint8>(cur_range_length);
1002 cur_range_length = 0;
1004 ack_info.max_delta = max(ack_info.max_delta, *iter - last_missing);
1005 last_missing = *iter;
1007 // Include the last nack range.
1008 ack_info.nack_ranges[last_missing - cur_range_length] =
1009 static_cast<uint8>(cur_range_length);
1010 // Include the range to the largest observed.
1011 ack_info.max_delta =
1012 max(ack_info.max_delta, frame.largest_observed - last_missing);
1013 return ack_info;
1016 bool QuicFramer::ProcessPacketHeader(QuicPacketHeader* header,
1017 const QuicEncryptedPacket& packet,
1018 char* decrypted_buffer,
1019 size_t buffer_length) {
1020 if (!ProcessPacketSequenceNumber(header->public_header.sequence_number_length,
1021 &header->packet_sequence_number)) {
1022 set_detailed_error("Unable to read sequence number.");
1023 return RaiseError(QUIC_INVALID_PACKET_HEADER);
1026 if (header->packet_sequence_number == 0u) {
1027 set_detailed_error("Packet sequence numbers cannot be 0.");
1028 return RaiseError(QUIC_INVALID_PACKET_HEADER);
1031 if (!visitor_->OnUnauthenticatedHeader(*header)) {
1032 return false;
1035 if (!DecryptPayload(*header, packet, decrypted_buffer, buffer_length)) {
1036 set_detailed_error("Unable to decrypt payload.");
1037 return RaiseError(QUIC_DECRYPTION_FAILURE);
1040 uint8 private_flags;
1041 if (!reader_->ReadBytes(&private_flags, 1)) {
1042 set_detailed_error("Unable to read private flags.");
1043 return RaiseError(QUIC_INVALID_PACKET_HEADER);
1046 if (private_flags > PACKET_PRIVATE_FLAGS_MAX) {
1047 set_detailed_error("Illegal private flags value.");
1048 return RaiseError(QUIC_INVALID_PACKET_HEADER);
1051 header->entropy_flag = (private_flags & PACKET_PRIVATE_FLAGS_ENTROPY) != 0;
1052 header->fec_flag = (private_flags & PACKET_PRIVATE_FLAGS_FEC) != 0;
1054 if ((private_flags & PACKET_PRIVATE_FLAGS_FEC_GROUP) != 0) {
1055 header->is_in_fec_group = IN_FEC_GROUP;
1056 uint8 first_fec_protected_packet_offset;
1057 if (!reader_->ReadBytes(&first_fec_protected_packet_offset, 1)) {
1058 set_detailed_error("Unable to read first fec protected packet offset.");
1059 return RaiseError(QUIC_INVALID_PACKET_HEADER);
1061 if (first_fec_protected_packet_offset >= header->packet_sequence_number) {
1062 set_detailed_error("First fec protected packet offset must be less "
1063 "than the sequence number.");
1064 return RaiseError(QUIC_INVALID_PACKET_HEADER);
1066 header->fec_group =
1067 header->packet_sequence_number - first_fec_protected_packet_offset;
1070 header->entropy_hash = GetPacketEntropyHash(*header);
1071 // Set the last sequence number after we have decrypted the packet
1072 // so we are confident is not attacker controlled.
1073 last_sequence_number_ = header->packet_sequence_number;
1074 return true;
1077 bool QuicFramer::ProcessPacketSequenceNumber(
1078 QuicSequenceNumberLength sequence_number_length,
1079 QuicPacketSequenceNumber* sequence_number) {
1080 QuicPacketSequenceNumber wire_sequence_number = 0u;
1081 if (!reader_->ReadBytes(&wire_sequence_number, sequence_number_length)) {
1082 return false;
1085 // TODO(ianswett): Explore the usefulness of trying multiple sequence numbers
1086 // in case the first guess is incorrect.
1087 *sequence_number =
1088 CalculatePacketSequenceNumberFromWire(sequence_number_length,
1089 wire_sequence_number);
1090 return true;
1093 bool QuicFramer::ProcessFrameData(const QuicPacketHeader& header) {
1094 if (reader_->IsDoneReading()) {
1095 set_detailed_error("Packet has no frames.");
1096 return RaiseError(QUIC_MISSING_PAYLOAD);
1098 while (!reader_->IsDoneReading()) {
1099 uint8 frame_type;
1100 if (!reader_->ReadBytes(&frame_type, 1)) {
1101 set_detailed_error("Unable to read frame type.");
1102 return RaiseError(QUIC_INVALID_FRAME_DATA);
1105 if (frame_type & kQuicFrameTypeSpecialMask) {
1106 // Stream Frame
1107 if (frame_type & kQuicFrameTypeStreamMask) {
1108 QuicStreamFrame frame;
1109 if (!ProcessStreamFrame(frame_type, &frame)) {
1110 return RaiseError(QUIC_INVALID_STREAM_DATA);
1112 if (!visitor_->OnStreamFrame(frame)) {
1113 DVLOG(1) << "Visitor asked to stop further processing.";
1114 // Returning true since there was no parsing error.
1115 return true;
1117 continue;
1120 // Ack Frame
1121 if (frame_type & kQuicFrameTypeAckMask) {
1122 QuicAckFrame frame;
1123 if (!ProcessAckFrame(frame_type, &frame)) {
1124 return RaiseError(QUIC_INVALID_ACK_DATA);
1126 if (!visitor_->OnAckFrame(frame)) {
1127 DVLOG(1) << "Visitor asked to stop further processing.";
1128 // Returning true since there was no parsing error.
1129 return true;
1131 continue;
1134 // This was a special frame type that did not match any
1135 // of the known ones. Error.
1136 set_detailed_error("Illegal frame type.");
1137 DLOG(WARNING) << "Illegal frame type: "
1138 << static_cast<int>(frame_type);
1139 return RaiseError(QUIC_INVALID_FRAME_DATA);
1142 switch (frame_type) {
1143 case PADDING_FRAME:
1144 // We're done with the packet.
1145 return true;
1147 case RST_STREAM_FRAME: {
1148 QuicRstStreamFrame frame;
1149 if (!ProcessRstStreamFrame(&frame)) {
1150 return RaiseError(QUIC_INVALID_RST_STREAM_DATA);
1152 if (!visitor_->OnRstStreamFrame(frame)) {
1153 DVLOG(1) << "Visitor asked to stop further processing.";
1154 // Returning true since there was no parsing error.
1155 return true;
1157 continue;
1160 case CONNECTION_CLOSE_FRAME: {
1161 QuicConnectionCloseFrame frame;
1162 if (!ProcessConnectionCloseFrame(&frame)) {
1163 return RaiseError(QUIC_INVALID_CONNECTION_CLOSE_DATA);
1166 if (!visitor_->OnConnectionCloseFrame(frame)) {
1167 DVLOG(1) << "Visitor asked to stop further processing.";
1168 // Returning true since there was no parsing error.
1169 return true;
1171 continue;
1174 case GOAWAY_FRAME: {
1175 QuicGoAwayFrame goaway_frame;
1176 if (!ProcessGoAwayFrame(&goaway_frame)) {
1177 return RaiseError(QUIC_INVALID_GOAWAY_DATA);
1179 if (!visitor_->OnGoAwayFrame(goaway_frame)) {
1180 DVLOG(1) << "Visitor asked to stop further processing.";
1181 // Returning true since there was no parsing error.
1182 return true;
1184 continue;
1187 case WINDOW_UPDATE_FRAME: {
1188 QuicWindowUpdateFrame window_update_frame;
1189 if (!ProcessWindowUpdateFrame(&window_update_frame)) {
1190 return RaiseError(QUIC_INVALID_WINDOW_UPDATE_DATA);
1192 if (!visitor_->OnWindowUpdateFrame(window_update_frame)) {
1193 DVLOG(1) << "Visitor asked to stop further processing.";
1194 // Returning true since there was no parsing error.
1195 return true;
1197 continue;
1200 case BLOCKED_FRAME: {
1201 QuicBlockedFrame blocked_frame;
1202 if (!ProcessBlockedFrame(&blocked_frame)) {
1203 return RaiseError(QUIC_INVALID_BLOCKED_DATA);
1205 if (!visitor_->OnBlockedFrame(blocked_frame)) {
1206 DVLOG(1) << "Visitor asked to stop further processing.";
1207 // Returning true since there was no parsing error.
1208 return true;
1210 continue;
1213 case STOP_WAITING_FRAME: {
1214 QuicStopWaitingFrame stop_waiting_frame;
1215 if (!ProcessStopWaitingFrame(header, &stop_waiting_frame)) {
1216 return RaiseError(QUIC_INVALID_STOP_WAITING_DATA);
1218 if (!visitor_->OnStopWaitingFrame(stop_waiting_frame)) {
1219 DVLOG(1) << "Visitor asked to stop further processing.";
1220 // Returning true since there was no parsing error.
1221 return true;
1223 continue;
1225 case PING_FRAME: {
1226 // Ping has no payload.
1227 QuicPingFrame ping_frame;
1228 if (!visitor_->OnPingFrame(ping_frame)) {
1229 DVLOG(1) << "Visitor asked to stop further processing.";
1230 // Returning true since there was no parsing error.
1231 return true;
1233 continue;
1236 default:
1237 set_detailed_error("Illegal frame type.");
1238 DLOG(WARNING) << "Illegal frame type: "
1239 << static_cast<int>(frame_type);
1240 return RaiseError(QUIC_INVALID_FRAME_DATA);
1244 return true;
1247 bool QuicFramer::ProcessStreamFrame(uint8 frame_type,
1248 QuicStreamFrame* frame) {
1249 uint8 stream_flags = frame_type;
1251 stream_flags &= ~kQuicFrameTypeStreamMask;
1253 // Read from right to left: StreamID, Offset, Data Length, Fin.
1254 const uint8 stream_id_length = (stream_flags & kQuicStreamIDLengthMask) + 1;
1255 stream_flags >>= kQuicStreamIdShift;
1257 uint8 offset_length = (stream_flags & kQuicStreamOffsetMask);
1258 // There is no encoding for 1 byte, only 0 and 2 through 8.
1259 if (offset_length > 0) {
1260 offset_length += 1;
1262 stream_flags >>= kQuicStreamOffsetShift;
1264 bool has_data_length =
1265 (stream_flags & kQuicStreamDataLengthMask) == kQuicStreamDataLengthMask;
1266 stream_flags >>= kQuicStreamDataLengthShift;
1268 frame->fin = (stream_flags & kQuicStreamFinMask) == kQuicStreamFinShift;
1270 frame->stream_id = 0;
1271 if (!reader_->ReadBytes(&frame->stream_id, stream_id_length)) {
1272 set_detailed_error("Unable to read stream_id.");
1273 return false;
1276 frame->offset = 0;
1277 if (!reader_->ReadBytes(&frame->offset, offset_length)) {
1278 set_detailed_error("Unable to read offset.");
1279 return false;
1282 StringPiece frame_data;
1283 if (has_data_length) {
1284 if (!reader_->ReadStringPiece16(&frame_data)) {
1285 set_detailed_error("Unable to read frame data.");
1286 return false;
1288 } else {
1289 if (!reader_->ReadStringPiece(&frame_data, reader_->BytesRemaining())) {
1290 set_detailed_error("Unable to read frame data.");
1291 return false;
1294 // Point frame to the right data.
1295 frame->data.Clear();
1296 if (!frame_data.empty()) {
1297 frame->data.Append(const_cast<char*>(frame_data.data()), frame_data.size());
1300 return true;
1303 bool QuicFramer::ProcessAckFrame(uint8 frame_type, QuicAckFrame* ack_frame) {
1304 // Determine the three lengths from the frame type: largest observed length,
1305 // missing sequence number length, and missing range length.
1306 const QuicSequenceNumberLength missing_sequence_number_length =
1307 ReadSequenceNumberLength(frame_type);
1308 frame_type >>= kQuicSequenceNumberLengthShift;
1309 const QuicSequenceNumberLength largest_observed_sequence_number_length =
1310 ReadSequenceNumberLength(frame_type);
1311 frame_type >>= kQuicSequenceNumberLengthShift;
1312 ack_frame->is_truncated = frame_type & kQuicAckTruncatedMask;
1313 frame_type >>= kQuicAckTruncatedShift;
1314 bool has_nacks = frame_type & kQuicHasNacksMask;
1316 if (!reader_->ReadBytes(&ack_frame->entropy_hash, 1)) {
1317 set_detailed_error("Unable to read entropy hash for received packets.");
1318 return false;
1321 if (!reader_->ReadBytes(&ack_frame->largest_observed,
1322 largest_observed_sequence_number_length)) {
1323 set_detailed_error("Unable to read largest observed.");
1324 return false;
1327 uint64 delta_time_largest_observed_us;
1328 if (!reader_->ReadUFloat16(&delta_time_largest_observed_us)) {
1329 set_detailed_error("Unable to read delta time largest observed.");
1330 return false;
1333 if (delta_time_largest_observed_us == kUFloat16MaxValue) {
1334 ack_frame->delta_time_largest_observed = QuicTime::Delta::Infinite();
1335 } else {
1336 ack_frame->delta_time_largest_observed =
1337 QuicTime::Delta::FromMicroseconds(delta_time_largest_observed_us);
1340 if (!ProcessTimestampsInAckFrame(ack_frame)) {
1341 return false;
1344 if (!has_nacks) {
1345 return true;
1348 uint8 num_missing_ranges;
1349 if (!reader_->ReadBytes(&num_missing_ranges, 1)) {
1350 set_detailed_error("Unable to read num missing packet ranges.");
1351 return false;
1354 QuicPacketSequenceNumber last_sequence_number = ack_frame->largest_observed;
1355 for (size_t i = 0; i < num_missing_ranges; ++i) {
1356 QuicPacketSequenceNumber missing_delta = 0;
1357 if (!reader_->ReadBytes(&missing_delta, missing_sequence_number_length)) {
1358 set_detailed_error("Unable to read missing sequence number delta.");
1359 return false;
1361 last_sequence_number -= missing_delta;
1362 QuicPacketSequenceNumber range_length = 0;
1363 if (!reader_->ReadBytes(&range_length, PACKET_1BYTE_SEQUENCE_NUMBER)) {
1364 set_detailed_error("Unable to read missing sequence number range.");
1365 return false;
1367 for (size_t j = 0; j <= range_length; ++j) {
1368 ack_frame->missing_packets.insert(last_sequence_number - j);
1370 // Subtract an extra 1 to ensure ranges are represented efficiently and
1371 // can't overlap by 1 sequence number. This allows a missing_delta of 0
1372 // to represent an adjacent nack range.
1373 last_sequence_number -= (range_length + 1);
1376 // Parse the revived packets list.
1377 uint8 num_revived_packets;
1378 if (!reader_->ReadBytes(&num_revived_packets, 1)) {
1379 set_detailed_error("Unable to read num revived packets.");
1380 return false;
1383 for (size_t i = 0; i < num_revived_packets; ++i) {
1384 QuicPacketSequenceNumber revived_packet = 0;
1385 if (!reader_->ReadBytes(&revived_packet,
1386 largest_observed_sequence_number_length)) {
1387 set_detailed_error("Unable to read revived packet.");
1388 return false;
1391 ack_frame->revived_packets.insert(revived_packet);
1394 return true;
1397 bool QuicFramer::ProcessTimestampsInAckFrame(QuicAckFrame* ack_frame) {
1398 if (ack_frame->is_truncated) {
1399 return true;
1401 uint8 num_received_packets;
1402 if (!reader_->ReadBytes(&num_received_packets, 1)) {
1403 set_detailed_error("Unable to read num received packets.");
1404 return false;
1407 if (num_received_packets > 0) {
1408 uint8 delta_from_largest_observed;
1409 if (!reader_->ReadBytes(&delta_from_largest_observed,
1410 PACKET_1BYTE_SEQUENCE_NUMBER)) {
1411 set_detailed_error("Unable to read sequence delta in received packets.");
1412 return false;
1414 QuicPacketSequenceNumber seq_num =
1415 ack_frame->largest_observed - delta_from_largest_observed;
1417 // Time delta from the framer creation.
1418 uint32 time_delta_us;
1419 if (!reader_->ReadBytes(&time_delta_us, sizeof(time_delta_us))) {
1420 set_detailed_error("Unable to read time delta in received packets.");
1421 return false;
1424 last_timestamp_ = CalculateTimestampFromWire(time_delta_us);
1426 ack_frame->received_packet_times.push_back(
1427 std::make_pair(seq_num, creation_time_.Add(last_timestamp_)));
1429 for (uint8 i = 1; i < num_received_packets; ++i) {
1430 if (!reader_->ReadBytes(&delta_from_largest_observed,
1431 PACKET_1BYTE_SEQUENCE_NUMBER)) {
1432 set_detailed_error(
1433 "Unable to read sequence delta in received packets.");
1434 return false;
1436 seq_num = ack_frame->largest_observed - delta_from_largest_observed;
1438 // Time delta from the previous timestamp.
1439 uint64 incremental_time_delta_us;
1440 if (!reader_->ReadUFloat16(&incremental_time_delta_us)) {
1441 set_detailed_error(
1442 "Unable to read incremental time delta in received packets.");
1443 return false;
1446 last_timestamp_ = last_timestamp_.Add(
1447 QuicTime::Delta::FromMicroseconds(incremental_time_delta_us));
1448 ack_frame->received_packet_times.push_back(
1449 std::make_pair(seq_num, creation_time_.Add(last_timestamp_)));
1452 return true;
1455 bool QuicFramer::ProcessStopWaitingFrame(const QuicPacketHeader& header,
1456 QuicStopWaitingFrame* stop_waiting) {
1457 if (!reader_->ReadBytes(&stop_waiting->entropy_hash, 1)) {
1458 set_detailed_error("Unable to read entropy hash for sent packets.");
1459 return false;
1462 QuicPacketSequenceNumber least_unacked_delta = 0;
1463 if (!reader_->ReadBytes(&least_unacked_delta,
1464 header.public_header.sequence_number_length)) {
1465 set_detailed_error("Unable to read least unacked delta.");
1466 return false;
1468 DCHECK_GE(header.packet_sequence_number, least_unacked_delta);
1469 stop_waiting->least_unacked =
1470 header.packet_sequence_number - least_unacked_delta;
1472 return true;
1475 bool QuicFramer::ProcessRstStreamFrame(QuicRstStreamFrame* frame) {
1476 if (!reader_->ReadUInt32(&frame->stream_id)) {
1477 set_detailed_error("Unable to read stream_id.");
1478 return false;
1481 if (!reader_->ReadUInt64(&frame->byte_offset)) {
1482 set_detailed_error("Unable to read rst stream sent byte offset.");
1483 return false;
1486 uint32 error_code;
1487 if (!reader_->ReadUInt32(&error_code)) {
1488 set_detailed_error("Unable to read rst stream error code.");
1489 return false;
1492 if (error_code >= QUIC_STREAM_LAST_ERROR) {
1493 set_detailed_error("Invalid rst stream error code.");
1494 return false;
1497 frame->error_code = static_cast<QuicRstStreamErrorCode>(error_code);
1498 if (quic_version_ <= QUIC_VERSION_24) {
1499 StringPiece error_details;
1500 if (!reader_->ReadStringPiece16(&error_details)) {
1501 set_detailed_error("Unable to read rst stream error details.");
1502 return false;
1504 frame->error_details = error_details.as_string();
1507 return true;
1510 bool QuicFramer::ProcessConnectionCloseFrame(QuicConnectionCloseFrame* frame) {
1511 uint32 error_code;
1512 if (!reader_->ReadUInt32(&error_code)) {
1513 set_detailed_error("Unable to read connection close error code.");
1514 return false;
1517 if (error_code >= QUIC_LAST_ERROR) {
1518 set_detailed_error("Invalid error code.");
1519 return false;
1522 frame->error_code = static_cast<QuicErrorCode>(error_code);
1524 StringPiece error_details;
1525 if (!reader_->ReadStringPiece16(&error_details)) {
1526 set_detailed_error("Unable to read connection close error details.");
1527 return false;
1529 frame->error_details = error_details.as_string();
1531 return true;
1534 bool QuicFramer::ProcessGoAwayFrame(QuicGoAwayFrame* frame) {
1535 uint32 error_code;
1536 if (!reader_->ReadUInt32(&error_code)) {
1537 set_detailed_error("Unable to read go away error code.");
1538 return false;
1540 frame->error_code = static_cast<QuicErrorCode>(error_code);
1542 if (error_code >= QUIC_LAST_ERROR) {
1543 set_detailed_error("Invalid error code.");
1544 return false;
1547 uint32 stream_id;
1548 if (!reader_->ReadUInt32(&stream_id)) {
1549 set_detailed_error("Unable to read last good stream id.");
1550 return false;
1552 frame->last_good_stream_id = static_cast<QuicStreamId>(stream_id);
1554 StringPiece reason_phrase;
1555 if (!reader_->ReadStringPiece16(&reason_phrase)) {
1556 set_detailed_error("Unable to read goaway reason.");
1557 return false;
1559 frame->reason_phrase = reason_phrase.as_string();
1561 return true;
1564 bool QuicFramer::ProcessWindowUpdateFrame(QuicWindowUpdateFrame* frame) {
1565 if (!reader_->ReadUInt32(&frame->stream_id)) {
1566 set_detailed_error("Unable to read stream_id.");
1567 return false;
1570 if (!reader_->ReadUInt64(&frame->byte_offset)) {
1571 set_detailed_error("Unable to read window byte_offset.");
1572 return false;
1575 return true;
1578 bool QuicFramer::ProcessBlockedFrame(QuicBlockedFrame* frame) {
1579 if (!reader_->ReadUInt32(&frame->stream_id)) {
1580 set_detailed_error("Unable to read stream_id.");
1581 return false;
1584 return true;
1587 // static
1588 StringPiece QuicFramer::GetAssociatedDataFromEncryptedPacket(
1589 const QuicEncryptedPacket& encrypted,
1590 QuicConnectionIdLength connection_id_length,
1591 bool includes_version,
1592 QuicSequenceNumberLength sequence_number_length) {
1593 return StringPiece(
1594 encrypted.data() + kStartOfHashData, GetStartOfEncryptedData(
1595 connection_id_length, includes_version, sequence_number_length)
1596 - kStartOfHashData);
1599 void QuicFramer::SetDecrypter(QuicDecrypter* decrypter,
1600 EncryptionLevel level) {
1601 DCHECK(alternative_decrypter_.get() == nullptr);
1602 DCHECK_GE(level, decrypter_level_);
1603 decrypter_.reset(decrypter);
1604 decrypter_level_ = level;
1607 void QuicFramer::SetAlternativeDecrypter(QuicDecrypter* decrypter,
1608 EncryptionLevel level,
1609 bool latch_once_used) {
1610 alternative_decrypter_.reset(decrypter);
1611 alternative_decrypter_level_ = level;
1612 alternative_decrypter_latch_ = latch_once_used;
1615 const QuicDecrypter* QuicFramer::decrypter() const {
1616 return decrypter_.get();
1619 const QuicDecrypter* QuicFramer::alternative_decrypter() const {
1620 return alternative_decrypter_.get();
1623 void QuicFramer::SetEncrypter(EncryptionLevel level,
1624 QuicEncrypter* encrypter) {
1625 DCHECK_GE(level, 0);
1626 DCHECK_LT(level, NUM_ENCRYPTION_LEVELS);
1627 encrypter_[level].reset(encrypter);
1630 QuicEncryptedPacket* QuicFramer::EncryptPacket(
1631 EncryptionLevel level,
1632 QuicPacketSequenceNumber packet_sequence_number,
1633 const QuicPacket& packet,
1634 char* buffer,
1635 size_t buffer_len) {
1636 DCHECK(encrypter_[level].get() != nullptr);
1638 const size_t encrypted_len =
1639 encrypter_[level]->GetCiphertextSize(packet.Plaintext().length());
1640 StringPiece header_data = packet.BeforePlaintext();
1641 const size_t total_len = header_data.length() + encrypted_len;
1643 char* encryption_buffer = buffer;
1644 // Allocate a large enough buffer for the header and the encrypted data.
1645 const bool is_new_buffer = total_len > buffer_len;
1646 if (is_new_buffer) {
1647 if (!FLAGS_quic_allow_oversized_packets_for_test) {
1648 LOG(DFATAL) << "Buffer of length:" << buffer_len
1649 << " is not large enough to encrypt length " << total_len;
1650 return nullptr;
1652 encryption_buffer = new char[total_len];
1654 // Copy in the header, because the encrypter only populates the encrypted
1655 // plaintext content.
1656 memcpy(encryption_buffer, header_data.data(), header_data.length());
1657 // Encrypt the plaintext into the buffer.
1658 size_t output_length = 0;
1659 if (!encrypter_[level]->EncryptPacket(
1660 packet_sequence_number, packet.AssociatedData(), packet.Plaintext(),
1661 encryption_buffer + header_data.length(), &output_length,
1662 encrypted_len)) {
1663 RaiseError(QUIC_ENCRYPTION_FAILURE);
1664 return nullptr;
1667 return new QuicEncryptedPacket(
1668 encryption_buffer, header_data.length() + output_length, is_new_buffer);
1671 size_t QuicFramer::GetMaxPlaintextSize(size_t ciphertext_size) {
1672 // In order to keep the code simple, we don't have the current encryption
1673 // level to hand. Both the NullEncrypter and AES-GCM have a tag length of 12.
1674 size_t min_plaintext_size = ciphertext_size;
1676 for (int i = ENCRYPTION_NONE; i < NUM_ENCRYPTION_LEVELS; i++) {
1677 if (encrypter_[i].get() != nullptr) {
1678 size_t size = encrypter_[i]->GetMaxPlaintextSize(ciphertext_size);
1679 if (size < min_plaintext_size) {
1680 min_plaintext_size = size;
1685 return min_plaintext_size;
1688 bool QuicFramer::DecryptPayload(const QuicPacketHeader& header,
1689 const QuicEncryptedPacket& packet,
1690 char* decrypted_buffer,
1691 size_t buffer_length) {
1692 StringPiece encrypted = reader_->ReadRemainingPayload();
1693 DCHECK(decrypter_.get() != nullptr);
1694 const StringPiece& associated_data = GetAssociatedDataFromEncryptedPacket(
1695 packet, header.public_header.connection_id_length,
1696 header.public_header.version_flag,
1697 header.public_header.sequence_number_length);
1698 size_t decrypted_length = 0;
1699 bool success = decrypter_->DecryptPacket(
1700 header.packet_sequence_number, associated_data, encrypted,
1701 decrypted_buffer, &decrypted_length, buffer_length);
1702 if (success) {
1703 visitor_->OnDecryptedPacket(decrypter_level_);
1704 } else if (alternative_decrypter_.get() != nullptr) {
1705 success = alternative_decrypter_->DecryptPacket(
1706 header.packet_sequence_number, associated_data, encrypted,
1707 decrypted_buffer, &decrypted_length, buffer_length);
1708 if (success) {
1709 visitor_->OnDecryptedPacket(alternative_decrypter_level_);
1710 if (alternative_decrypter_latch_) {
1711 // Switch to the alternative decrypter and latch so that we cannot
1712 // switch back.
1713 decrypter_.reset(alternative_decrypter_.release());
1714 decrypter_level_ = alternative_decrypter_level_;
1715 alternative_decrypter_level_ = ENCRYPTION_NONE;
1716 } else {
1717 // Switch the alternative decrypter so that we use it first next time.
1718 decrypter_.swap(alternative_decrypter_);
1719 EncryptionLevel level = alternative_decrypter_level_;
1720 alternative_decrypter_level_ = decrypter_level_;
1721 decrypter_level_ = level;
1726 if (!success) {
1727 DLOG(WARNING) << "DecryptPacket failed for sequence_number:"
1728 << header.packet_sequence_number;
1729 return false;
1732 reader_.reset(new QuicDataReader(decrypted_buffer, decrypted_length));
1733 return true;
1736 size_t QuicFramer::GetAckFrameSize(
1737 const QuicAckFrame& ack,
1738 QuicSequenceNumberLength sequence_number_length) {
1739 AckFrameInfo ack_info = GetAckFrameInfo(ack);
1740 QuicSequenceNumberLength largest_observed_length =
1741 GetMinSequenceNumberLength(ack.largest_observed);
1742 QuicSequenceNumberLength missing_sequence_number_length =
1743 GetMinSequenceNumberLength(ack_info.max_delta);
1745 size_t ack_size = GetMinAckFrameSize(sequence_number_length,
1746 largest_observed_length);
1747 if (!ack_info.nack_ranges.empty()) {
1748 ack_size += kNumberOfNackRangesSize + kNumberOfRevivedPacketsSize;
1749 ack_size += min(ack_info.nack_ranges.size(), kMaxNackRanges) *
1750 (missing_sequence_number_length + PACKET_1BYTE_SEQUENCE_NUMBER);
1751 ack_size += min(ack.revived_packets.size(),
1752 kMaxRevivedPackets) * largest_observed_length;
1755 // In version 23, if the ack will be truncated due to too many nack ranges,
1756 // then do not include the number of timestamps (1 byte).
1757 if (ack_info.nack_ranges.size() <= kMaxNackRanges) {
1758 // 1 byte for the number of timestamps.
1759 ack_size += 1;
1760 if (ack.received_packet_times.size() > 0) {
1761 // 1 byte for sequence number, 4 bytes for timestamp for the first
1762 // packet.
1763 ack_size += 5;
1765 // 1 byte for sequence number, 2 bytes for timestamp for the other
1766 // packets.
1767 ack_size += 3 * (ack.received_packet_times.size() - 1);
1771 return ack_size;
1774 size_t QuicFramer::ComputeFrameLength(
1775 const QuicFrame& frame,
1776 bool last_frame_in_packet,
1777 InFecGroup is_in_fec_group,
1778 QuicSequenceNumberLength sequence_number_length) {
1779 switch (frame.type) {
1780 case STREAM_FRAME:
1781 return GetMinStreamFrameSize(frame.stream_frame->stream_id,
1782 frame.stream_frame->offset,
1783 last_frame_in_packet,
1784 is_in_fec_group) +
1785 frame.stream_frame->data.TotalBufferSize();
1786 case ACK_FRAME: {
1787 return GetAckFrameSize(*frame.ack_frame, sequence_number_length);
1789 case STOP_WAITING_FRAME:
1790 return GetStopWaitingFrameSize(sequence_number_length);
1791 case PING_FRAME:
1792 // Ping has no payload.
1793 return kQuicFrameTypeSize;
1794 case RST_STREAM_FRAME:
1795 if (quic_version_ <= QUIC_VERSION_24) {
1796 return GetMinRstStreamFrameSize() +
1797 frame.rst_stream_frame->error_details.size();
1799 return GetRstStreamFrameSize();
1800 case CONNECTION_CLOSE_FRAME:
1801 return GetMinConnectionCloseFrameSize() +
1802 frame.connection_close_frame->error_details.size();
1803 case GOAWAY_FRAME:
1804 return GetMinGoAwayFrameSize() + frame.goaway_frame->reason_phrase.size();
1805 case WINDOW_UPDATE_FRAME:
1806 return GetWindowUpdateFrameSize();
1807 case BLOCKED_FRAME:
1808 return GetBlockedFrameSize();
1809 case PADDING_FRAME:
1810 DCHECK(false);
1811 return 0;
1812 case NUM_FRAME_TYPES:
1813 DCHECK(false);
1814 return 0;
1817 // Not reachable, but some Chrome compilers can't figure that out. *sigh*
1818 DCHECK(false);
1819 return 0;
1822 bool QuicFramer::AppendTypeByte(const QuicFrame& frame,
1823 bool no_stream_frame_length,
1824 QuicDataWriter* writer) {
1825 uint8 type_byte = 0;
1826 switch (frame.type) {
1827 case STREAM_FRAME: {
1828 if (frame.stream_frame == nullptr) {
1829 LOG(DFATAL) << "Failed to append STREAM frame with no stream_frame.";
1831 // Fin bit.
1832 type_byte |= frame.stream_frame->fin ? kQuicStreamFinMask : 0;
1834 // Data Length bit.
1835 type_byte <<= kQuicStreamDataLengthShift;
1836 type_byte |= no_stream_frame_length ? 0: kQuicStreamDataLengthMask;
1838 // Offset 3 bits.
1839 type_byte <<= kQuicStreamOffsetShift;
1840 const size_t offset_len = GetStreamOffsetSize(frame.stream_frame->offset);
1841 if (offset_len > 0) {
1842 type_byte |= offset_len - 1;
1845 // stream id 2 bits.
1846 type_byte <<= kQuicStreamIdShift;
1847 type_byte |= GetStreamIdSize(frame.stream_frame->stream_id) - 1;
1848 type_byte |= kQuicFrameTypeStreamMask; // Set Stream Frame Type to 1.
1849 break;
1851 case ACK_FRAME:
1852 return true;
1853 default:
1854 type_byte = static_cast<uint8>(frame.type);
1855 break;
1858 return writer->WriteUInt8(type_byte);
1861 // static
1862 bool QuicFramer::AppendPacketSequenceNumber(
1863 QuicSequenceNumberLength sequence_number_length,
1864 QuicPacketSequenceNumber packet_sequence_number,
1865 QuicDataWriter* writer) {
1866 // Ensure the entire sequence number can be written.
1867 if (writer->capacity() - writer->length() <
1868 static_cast<size_t>(sequence_number_length)) {
1869 return false;
1871 switch (sequence_number_length) {
1872 case PACKET_1BYTE_SEQUENCE_NUMBER:
1873 return writer->WriteUInt8(
1874 packet_sequence_number & k1ByteSequenceNumberMask);
1875 break;
1876 case PACKET_2BYTE_SEQUENCE_NUMBER:
1877 return writer->WriteUInt16(
1878 packet_sequence_number & k2ByteSequenceNumberMask);
1879 break;
1880 case PACKET_4BYTE_SEQUENCE_NUMBER:
1881 return writer->WriteUInt32(
1882 packet_sequence_number & k4ByteSequenceNumberMask);
1883 break;
1884 case PACKET_6BYTE_SEQUENCE_NUMBER:
1885 return writer->WriteUInt48(
1886 packet_sequence_number & k6ByteSequenceNumberMask);
1887 break;
1888 default:
1889 DCHECK(false) << "sequence_number_length: " << sequence_number_length;
1890 return false;
1894 bool QuicFramer::AppendStreamFrame(
1895 const QuicStreamFrame& frame,
1896 bool no_stream_frame_length,
1897 QuicDataWriter* writer) {
1898 if (!writer->WriteBytes(&frame.stream_id, GetStreamIdSize(frame.stream_id))) {
1899 LOG(DFATAL) << "Writing stream id size failed.";
1900 return false;
1902 if (!writer->WriteBytes(&frame.offset, GetStreamOffsetSize(frame.offset))) {
1903 LOG(DFATAL) << "Writing offset size failed.";
1904 return false;
1906 if (!no_stream_frame_length) {
1907 if ((frame.data.TotalBufferSize() > numeric_limits<uint16>::max()) ||
1908 !writer->WriteUInt16(
1909 static_cast<uint16>(frame.data.TotalBufferSize()))) {
1910 LOG(DFATAL) << "Writing stream frame length failed";
1911 return false;
1915 if (!writer->WriteIOVector(frame.data)) {
1916 LOG(DFATAL) << "Writing frame data failed.";
1917 return false;
1919 return true;
1922 void QuicFramer::set_version(const QuicVersion version) {
1923 DCHECK(IsSupportedVersion(version)) << QuicVersionToString(version);
1924 quic_version_ = version;
1927 bool QuicFramer::AppendAckFrameAndTypeByte(
1928 const QuicPacketHeader& header,
1929 const QuicAckFrame& frame,
1930 QuicDataWriter* writer) {
1931 AckFrameInfo ack_info = GetAckFrameInfo(frame);
1932 QuicPacketSequenceNumber ack_largest_observed = frame.largest_observed;
1933 QuicSequenceNumberLength largest_observed_length =
1934 GetMinSequenceNumberLength(ack_largest_observed);
1935 QuicSequenceNumberLength missing_sequence_number_length =
1936 GetMinSequenceNumberLength(ack_info.max_delta);
1937 // Determine whether we need to truncate ranges.
1938 size_t available_range_bytes = writer->capacity() - writer->length() -
1939 kNumberOfRevivedPacketsSize - kNumberOfNackRangesSize -
1940 GetMinAckFrameSize(header.public_header.sequence_number_length,
1941 largest_observed_length);
1942 size_t max_num_ranges = available_range_bytes /
1943 (missing_sequence_number_length + PACKET_1BYTE_SEQUENCE_NUMBER);
1944 max_num_ranges = min(kMaxNackRanges, max_num_ranges);
1945 bool truncated = ack_info.nack_ranges.size() > max_num_ranges;
1946 DVLOG_IF(1, truncated) << "Truncating ack from "
1947 << ack_info.nack_ranges.size() << " ranges to "
1948 << max_num_ranges;
1949 // Write out the type byte by setting the low order bits and doing shifts
1950 // to make room for the next bit flags to be set.
1951 // Whether there are any nacks.
1952 uint8 type_byte = ack_info.nack_ranges.empty() ? 0 : kQuicHasNacksMask;
1954 // truncating bit.
1955 type_byte <<= kQuicAckTruncatedShift;
1956 type_byte |= truncated ? kQuicAckTruncatedMask : 0;
1958 // Largest observed sequence number length.
1959 type_byte <<= kQuicSequenceNumberLengthShift;
1960 type_byte |= GetSequenceNumberFlags(largest_observed_length);
1962 // Missing sequence number length.
1963 type_byte <<= kQuicSequenceNumberLengthShift;
1964 type_byte |= GetSequenceNumberFlags(missing_sequence_number_length);
1966 type_byte |= kQuicFrameTypeAckMask;
1968 if (!writer->WriteUInt8(type_byte)) {
1969 return false;
1972 QuicPacketEntropyHash ack_entropy_hash = frame.entropy_hash;
1973 NackRangeMap::reverse_iterator ack_iter = ack_info.nack_ranges.rbegin();
1974 if (truncated) {
1975 // Skip the nack ranges which the truncated ack won't include and set
1976 // a correct largest observed for the truncated ack.
1977 for (size_t i = 1; i < (ack_info.nack_ranges.size() - max_num_ranges);
1978 ++i) {
1979 ++ack_iter;
1981 // If the last range is followed by acks, include them.
1982 // If the last range is followed by another range, specify the end of the
1983 // range as the largest_observed.
1984 ack_largest_observed = ack_iter->first - 1;
1985 // Also update the entropy so it matches the largest observed.
1986 ack_entropy_hash = entropy_calculator_->EntropyHash(ack_largest_observed);
1987 ++ack_iter;
1990 if (!writer->WriteUInt8(ack_entropy_hash)) {
1991 return false;
1994 if (!AppendPacketSequenceNumber(largest_observed_length,
1995 ack_largest_observed, writer)) {
1996 return false;
1999 uint64 delta_time_largest_observed_us = kUFloat16MaxValue;
2000 if (!frame.delta_time_largest_observed.IsInfinite()) {
2001 DCHECK_LE(0u, frame.delta_time_largest_observed.ToMicroseconds());
2002 delta_time_largest_observed_us =
2003 frame.delta_time_largest_observed.ToMicroseconds();
2006 if (!writer->WriteUFloat16(delta_time_largest_observed_us)) {
2007 return false;
2010 // Timestamp goes at the end of the required fields.
2011 if (!truncated) {
2012 if (!AppendTimestampToAckFrame(frame, writer)) {
2013 return false;
2017 if (ack_info.nack_ranges.empty()) {
2018 return true;
2021 const uint8 num_missing_ranges =
2022 static_cast<uint8>(min(ack_info.nack_ranges.size(), max_num_ranges));
2023 if (!writer->WriteBytes(&num_missing_ranges, 1)) {
2024 return false;
2027 int num_ranges_written = 0;
2028 QuicPacketSequenceNumber last_sequence_written = ack_largest_observed;
2029 for (; ack_iter != ack_info.nack_ranges.rend(); ++ack_iter) {
2030 // Calculate the delta to the last number in the range.
2031 QuicPacketSequenceNumber missing_delta =
2032 last_sequence_written - (ack_iter->first + ack_iter->second);
2033 if (!AppendPacketSequenceNumber(missing_sequence_number_length,
2034 missing_delta, writer)) {
2035 return false;
2037 if (!AppendPacketSequenceNumber(PACKET_1BYTE_SEQUENCE_NUMBER,
2038 ack_iter->second, writer)) {
2039 return false;
2041 // Subtract 1 so a missing_delta of 0 means an adjacent range.
2042 last_sequence_written = ack_iter->first - 1;
2043 ++num_ranges_written;
2045 DCHECK_EQ(num_missing_ranges, num_ranges_written);
2047 // Append revived packets.
2048 // If not all the revived packets fit, only mention the ones that do.
2049 uint8 num_revived_packets =
2050 static_cast<uint8>(min(frame.revived_packets.size(), kMaxRevivedPackets));
2051 num_revived_packets = static_cast<uint8>(min(
2052 static_cast<size_t>(num_revived_packets),
2053 (writer->capacity() - writer->length()) / largest_observed_length));
2054 if (!writer->WriteBytes(&num_revived_packets, 1)) {
2055 return false;
2058 SequenceNumberSet::const_iterator iter = frame.revived_packets.begin();
2059 for (int i = 0; i < num_revived_packets; ++i, ++iter) {
2060 LOG_IF(DFATAL, !ContainsKey(frame.missing_packets, *iter));
2061 if (!AppendPacketSequenceNumber(largest_observed_length,
2062 *iter, writer)) {
2063 return false;
2067 return true;
2070 bool QuicFramer::AppendTimestampToAckFrame(const QuicAckFrame& frame,
2071 QuicDataWriter* writer) {
2072 DCHECK_GE(numeric_limits<uint8>::max(), frame.received_packet_times.size());
2073 // num_received_packets is only 1 byte.
2074 if (frame.received_packet_times.size() > numeric_limits<uint8>::max()) {
2075 return false;
2078 uint8 num_received_packets = frame.received_packet_times.size();
2080 if (!writer->WriteBytes(&num_received_packets, 1)) {
2081 return false;
2083 if (num_received_packets == 0) {
2084 return true;
2087 PacketTimeList::const_iterator it = frame.received_packet_times.begin();
2088 QuicPacketSequenceNumber sequence_number = it->first;
2089 QuicPacketSequenceNumber delta_from_largest_observed =
2090 frame.largest_observed - sequence_number;
2092 DCHECK_GE(numeric_limits<uint8>::max(), delta_from_largest_observed);
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 // Use the lowest 4 bytes of the time delta from the creation_time_.
2103 const uint64 time_epoch_delta_us = GG_UINT64_C(1) << 32;
2104 uint32 time_delta_us =
2105 static_cast<uint32>(it->second.Subtract(creation_time_).ToMicroseconds()
2106 & (time_epoch_delta_us - 1));
2107 if (!writer->WriteBytes(&time_delta_us, sizeof(time_delta_us))) {
2108 return false;
2111 QuicTime prev_time = it->second;
2113 for (++it; it != frame.received_packet_times.end(); ++it) {
2114 sequence_number = it->first;
2115 delta_from_largest_observed = frame.largest_observed - sequence_number;
2117 if (delta_from_largest_observed > numeric_limits<uint8>::max()) {
2118 return false;
2121 if (!writer->WriteUInt8(
2122 delta_from_largest_observed & k1ByteSequenceNumberMask)) {
2123 return false;
2126 uint64 frame_time_delta_us =
2127 it->second.Subtract(prev_time).ToMicroseconds();
2128 prev_time = it->second;
2129 if (!writer->WriteUFloat16(frame_time_delta_us)) {
2130 return false;
2133 return true;
2136 bool QuicFramer::AppendStopWaitingFrame(
2137 const QuicPacketHeader& header,
2138 const QuicStopWaitingFrame& frame,
2139 QuicDataWriter* writer) {
2140 DCHECK_GE(header.packet_sequence_number, frame.least_unacked);
2141 const QuicPacketSequenceNumber least_unacked_delta =
2142 header.packet_sequence_number - frame.least_unacked;
2143 const QuicPacketSequenceNumber length_shift =
2144 header.public_header.sequence_number_length * 8;
2145 if (!writer->WriteUInt8(frame.entropy_hash)) {
2146 LOG(DFATAL) << " hash failed";
2147 return false;
2150 if (least_unacked_delta >> length_shift > 0) {
2151 LOG(DFATAL) << "sequence_number_length "
2152 << header.public_header.sequence_number_length
2153 << " is too small for least_unacked_delta: "
2154 << least_unacked_delta;
2155 return false;
2157 if (!AppendPacketSequenceNumber(header.public_header.sequence_number_length,
2158 least_unacked_delta, writer)) {
2159 LOG(DFATAL) << " seq failed: "
2160 << header.public_header.sequence_number_length;
2161 return false;
2164 return true;
2167 bool QuicFramer::AppendRstStreamFrame(const QuicRstStreamFrame& frame,
2168 QuicDataWriter* writer) {
2169 if (!writer->WriteUInt32(frame.stream_id)) {
2170 return false;
2173 if (!writer->WriteUInt64(frame.byte_offset)) {
2174 return false;
2177 uint32 error_code = static_cast<uint32>(frame.error_code);
2178 if (!writer->WriteUInt32(error_code)) {
2179 return false;
2182 if (quic_version_ <= QUIC_VERSION_24) {
2183 if (!writer->WriteStringPiece16(frame.error_details)) {
2184 return false;
2187 return true;
2190 bool QuicFramer::AppendConnectionCloseFrame(
2191 const QuicConnectionCloseFrame& frame,
2192 QuicDataWriter* writer) {
2193 uint32 error_code = static_cast<uint32>(frame.error_code);
2194 if (!writer->WriteUInt32(error_code)) {
2195 return false;
2197 if (!writer->WriteStringPiece16(frame.error_details)) {
2198 return false;
2200 return true;
2203 bool QuicFramer::AppendGoAwayFrame(const QuicGoAwayFrame& frame,
2204 QuicDataWriter* writer) {
2205 uint32 error_code = static_cast<uint32>(frame.error_code);
2206 if (!writer->WriteUInt32(error_code)) {
2207 return false;
2209 uint32 stream_id = static_cast<uint32>(frame.last_good_stream_id);
2210 if (!writer->WriteUInt32(stream_id)) {
2211 return false;
2213 if (!writer->WriteStringPiece16(frame.reason_phrase)) {
2214 return false;
2216 return true;
2219 bool QuicFramer::AppendWindowUpdateFrame(const QuicWindowUpdateFrame& frame,
2220 QuicDataWriter* writer) {
2221 uint32 stream_id = static_cast<uint32>(frame.stream_id);
2222 if (!writer->WriteUInt32(stream_id)) {
2223 return false;
2225 if (!writer->WriteUInt64(frame.byte_offset)) {
2226 return false;
2228 return true;
2231 bool QuicFramer::AppendBlockedFrame(const QuicBlockedFrame& frame,
2232 QuicDataWriter* writer) {
2233 uint32 stream_id = static_cast<uint32>(frame.stream_id);
2234 if (!writer->WriteUInt32(stream_id)) {
2235 return false;
2237 return true;
2240 bool QuicFramer::RaiseError(QuicErrorCode error) {
2241 DVLOG(1) << "Error: " << QuicUtils::ErrorToString(error)
2242 << " detail: " << detailed_error_;
2243 set_error(error);
2244 visitor_->OnError(this);
2245 reader_.reset(nullptr);
2246 return false;
2249 } // namespace net