Add Wi-FI SSID to captive portal interstitial.
[chromium-blink-merge.git] / net / quic / quic_framer.cc
blob5cde3c23fcf3851ca7612ca13075fa524fe4d59c
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::make_pair;
21 using std::map;
22 using std::max;
23 using std::min;
24 using std::numeric_limits;
25 using std::string;
27 namespace net {
29 namespace {
31 // Mask to select the lowest 48 bits of a sequence number.
32 const QuicPacketSequenceNumber k6ByteSequenceNumberMask =
33 GG_UINT64_C(0x0000FFFFFFFFFFFF);
34 const QuicPacketSequenceNumber k4ByteSequenceNumberMask =
35 GG_UINT64_C(0x00000000FFFFFFFF);
36 const QuicPacketSequenceNumber k2ByteSequenceNumberMask =
37 GG_UINT64_C(0x000000000000FFFF);
38 const QuicPacketSequenceNumber k1ByteSequenceNumberMask =
39 GG_UINT64_C(0x00000000000000FF);
41 const QuicConnectionId k1ByteConnectionIdMask = GG_UINT64_C(0x00000000000000FF);
42 const QuicConnectionId k4ByteConnectionIdMask = GG_UINT64_C(0x00000000FFFFFFFF);
44 // Number of bits the sequence number length bits are shifted from the right
45 // edge of the public header.
46 const uint8 kPublicHeaderSequenceNumberShift = 4;
48 // New Frame Types, QUIC v. >= 10:
49 // There are two interpretations for the Frame Type byte in the QUIC protocol,
50 // resulting in two Frame Types: Special Frame Types and Regular Frame Types.
52 // Regular Frame Types use the Frame Type byte simply. Currently defined
53 // Regular Frame Types are:
54 // Padding : 0b 00000000 (0x00)
55 // ResetStream : 0b 00000001 (0x01)
56 // ConnectionClose : 0b 00000010 (0x02)
57 // GoAway : 0b 00000011 (0x03)
58 // WindowUpdate : 0b 00000100 (0x04)
59 // Blocked : 0b 00000101 (0x05)
61 // Special Frame Types encode both a Frame Type and corresponding flags
62 // all in the Frame Type byte. Currently defined Special Frame Types are:
63 // Stream : 0b 1xxxxxxx
64 // Ack : 0b 01xxxxxx
66 // Semantics of the flag bits above (the x bits) depends on the frame type.
68 // Masks to determine if the frame type is a special use
69 // and for specific special frame types.
70 const uint8 kQuicFrameTypeSpecialMask = 0xE0; // 0b 11100000
71 const uint8 kQuicFrameTypeStreamMask = 0x80;
72 const uint8 kQuicFrameTypeAckMask = 0x40;
74 // Stream frame relative shifts and masks for interpreting the stream flags.
75 // StreamID may be 1, 2, 3, or 4 bytes.
76 const uint8 kQuicStreamIdShift = 2;
77 const uint8 kQuicStreamIDLengthMask = 0x03;
79 // Offset may be 0, 2, 3, 4, 5, 6, 7, 8 bytes.
80 const uint8 kQuicStreamOffsetShift = 3;
81 const uint8 kQuicStreamOffsetMask = 0x07;
83 // Data length may be 0 or 2 bytes.
84 const uint8 kQuicStreamDataLengthShift = 1;
85 const uint8 kQuicStreamDataLengthMask = 0x01;
87 // Fin bit may be set or not.
88 const uint8 kQuicStreamFinShift = 1;
89 const uint8 kQuicStreamFinMask = 0x01;
91 // Sequence number size shift used in AckFrames.
92 const uint8 kQuicSequenceNumberLengthShift = 2;
94 // Acks may be truncated.
95 const uint8 kQuicAckTruncatedShift = 1;
96 const uint8 kQuicAckTruncatedMask = 0x01;
98 // Acks may not have any nacks.
99 const uint8 kQuicHasNacksMask = 0x01;
101 // Returns the absolute value of the difference between |a| and |b|.
102 QuicPacketSequenceNumber Delta(QuicPacketSequenceNumber a,
103 QuicPacketSequenceNumber b) {
104 // Since these are unsigned numbers, we can't just return abs(a - b)
105 if (a < b) {
106 return b - a;
108 return a - b;
111 QuicPacketSequenceNumber ClosestTo(QuicPacketSequenceNumber target,
112 QuicPacketSequenceNumber a,
113 QuicPacketSequenceNumber b) {
114 return (Delta(target, a) < Delta(target, b)) ? a : b;
117 QuicSequenceNumberLength ReadSequenceNumberLength(uint8 flags) {
118 switch (flags & PACKET_FLAGS_6BYTE_SEQUENCE) {
119 case PACKET_FLAGS_6BYTE_SEQUENCE:
120 return PACKET_6BYTE_SEQUENCE_NUMBER;
121 case PACKET_FLAGS_4BYTE_SEQUENCE:
122 return PACKET_4BYTE_SEQUENCE_NUMBER;
123 case PACKET_FLAGS_2BYTE_SEQUENCE:
124 return PACKET_2BYTE_SEQUENCE_NUMBER;
125 case PACKET_FLAGS_1BYTE_SEQUENCE:
126 return PACKET_1BYTE_SEQUENCE_NUMBER;
127 default:
128 LOG(DFATAL) << "Unreachable case statement.";
129 return PACKET_6BYTE_SEQUENCE_NUMBER;
133 } // namespace
135 bool QuicFramerVisitorInterface::OnWindowUpdateFrame(
136 const QuicWindowUpdateFrame& frame) {
137 return true;
140 bool QuicFramerVisitorInterface::OnBlockedFrame(const QuicBlockedFrame& frame) {
141 return true;
144 QuicFramer::QuicFramer(const QuicVersionVector& supported_versions,
145 QuicTime creation_time,
146 bool is_server)
147 : visitor_(nullptr),
148 fec_builder_(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 is_server_(is_server),
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::GetMinConnectionCloseFrameSize() {
205 return kQuicFrameTypeSize + kQuicErrorCodeSize + kQuicErrorDetailsLengthSize;
208 // static
209 size_t QuicFramer::GetMinGoAwayFrameSize() {
210 return kQuicFrameTypeSize + kQuicErrorCodeSize + kQuicErrorDetailsLengthSize +
211 kQuicMaxStreamIdSize;
214 // static
215 size_t QuicFramer::GetWindowUpdateFrameSize() {
216 return kQuicFrameTypeSize + kQuicMaxStreamIdSize + kQuicMaxStreamOffsetSize;
219 // static
220 size_t QuicFramer::GetBlockedFrameSize() {
221 return kQuicFrameTypeSize + kQuicMaxStreamIdSize;
224 // static
225 size_t QuicFramer::GetStreamIdSize(QuicStreamId stream_id) {
226 // Sizes are 1 through 4 bytes.
227 for (int i = 1; i <= 4; ++i) {
228 stream_id >>= 8;
229 if (stream_id == 0) {
230 return i;
233 LOG(DFATAL) << "Failed to determine StreamIDSize.";
234 return 4;
237 // static
238 size_t QuicFramer::GetStreamOffsetSize(QuicStreamOffset offset) {
239 // 0 is a special case.
240 if (offset == 0) {
241 return 0;
243 // 2 through 8 are the remaining sizes.
244 offset >>= 8;
245 for (int i = 2; i <= 8; ++i) {
246 offset >>= 8;
247 if (offset == 0) {
248 return i;
251 LOG(DFATAL) << "Failed to determine StreamOffsetSize.";
252 return 8;
255 // static
256 size_t QuicFramer::GetVersionNegotiationPacketSize(size_t number_versions) {
257 return kPublicFlagsSize + PACKET_8BYTE_CONNECTION_ID +
258 number_versions * kQuicVersionSize;
261 bool QuicFramer::IsSupportedVersion(const QuicVersion version) const {
262 for (size_t i = 0; i < supported_versions_.size(); ++i) {
263 if (version == supported_versions_[i]) {
264 return true;
267 return false;
270 size_t QuicFramer::GetSerializedFrameLength(
271 const QuicFrame& frame,
272 size_t free_bytes,
273 bool first_frame,
274 bool last_frame,
275 InFecGroup is_in_fec_group,
276 QuicSequenceNumberLength sequence_number_length) {
277 if (frame.type == PADDING_FRAME) {
278 // PADDING implies end of packet.
279 return free_bytes;
281 size_t frame_len =
282 ComputeFrameLength(frame, last_frame, is_in_fec_group,
283 sequence_number_length);
284 if (frame_len <= free_bytes) {
285 // Frame fits within packet. Note that acks may be truncated.
286 return frame_len;
288 // Only truncate the first frame in a packet, so if subsequent ones go
289 // over, stop including more frames.
290 if (!first_frame) {
291 return 0;
293 bool can_truncate = frame.type == ACK_FRAME &&
294 free_bytes >= GetMinAckFrameSize(PACKET_6BYTE_SEQUENCE_NUMBER,
295 PACKET_6BYTE_SEQUENCE_NUMBER);
296 if (can_truncate) {
297 // Truncate the frame so the packet will not exceed kMaxPacketSize.
298 // Note that we may not use every byte of the writer in this case.
299 DVLOG(1) << "Truncating large frame, free bytes: " << free_bytes;
300 return free_bytes;
302 if (!FLAGS_quic_allow_oversized_packets_for_test) {
303 return 0;
305 LOG(DFATAL) << "Packet size too small to fit frame.";
306 return frame_len;
309 QuicFramer::AckFrameInfo::AckFrameInfo() : max_delta(0) {}
311 QuicFramer::AckFrameInfo::~AckFrameInfo() {}
313 QuicPacketEntropyHash QuicFramer::GetPacketEntropyHash(
314 const QuicPacketHeader& header) const {
315 return header.entropy_flag << (header.packet_sequence_number % 8);
318 SerializedPacket QuicFramer::BuildDataPacket(
319 const QuicPacketHeader& header,
320 const QuicFrames& frames,
321 size_t packet_size) {
322 QuicDataWriter writer(packet_size);
323 const SerializedPacket kNoPacket(0, PACKET_1BYTE_SEQUENCE_NUMBER, nullptr, 0,
324 nullptr);
325 if (!AppendPacketHeader(header, &writer)) {
326 LOG(DFATAL) << "AppendPacketHeader failed";
327 return kNoPacket;
330 for (size_t i = 0; i < frames.size(); ++i) {
331 const QuicFrame& frame = frames[i];
333 // Determine if we should write stream frame length in header.
334 const bool no_stream_frame_length =
335 (header.is_in_fec_group == NOT_IN_FEC_GROUP) &&
336 (i == frames.size() - 1);
337 if (!AppendTypeByte(frame, no_stream_frame_length, &writer)) {
338 LOG(DFATAL) << "AppendTypeByte failed";
339 return kNoPacket;
342 switch (frame.type) {
343 case PADDING_FRAME:
344 writer.WritePadding();
345 break;
346 case STREAM_FRAME:
347 if (!AppendStreamFrame(
348 *frame.stream_frame, no_stream_frame_length, &writer)) {
349 LOG(DFATAL) << "AppendStreamFrame failed";
350 return kNoPacket;
352 break;
353 case ACK_FRAME:
354 if (!AppendAckFrameAndTypeByte(
355 header, *frame.ack_frame, &writer)) {
356 LOG(DFATAL) << "AppendAckFrameAndTypeByte failed";
357 return kNoPacket;
359 break;
360 case STOP_WAITING_FRAME:
361 if (!AppendStopWaitingFrame(
362 header, *frame.stop_waiting_frame, &writer)) {
363 LOG(DFATAL) << "AppendStopWaitingFrame failed";
364 return kNoPacket;
366 break;
367 case PING_FRAME:
368 // Ping has no payload.
369 break;
370 case RST_STREAM_FRAME:
371 if (!AppendRstStreamFrame(*frame.rst_stream_frame, &writer)) {
372 LOG(DFATAL) << "AppendRstStreamFrame failed";
373 return kNoPacket;
375 break;
376 case CONNECTION_CLOSE_FRAME:
377 if (!AppendConnectionCloseFrame(
378 *frame.connection_close_frame, &writer)) {
379 LOG(DFATAL) << "AppendConnectionCloseFrame failed";
380 return kNoPacket;
382 break;
383 case GOAWAY_FRAME:
384 if (!AppendGoAwayFrame(*frame.goaway_frame, &writer)) {
385 LOG(DFATAL) << "AppendGoAwayFrame failed";
386 return kNoPacket;
388 break;
389 case WINDOW_UPDATE_FRAME:
390 if (!AppendWindowUpdateFrame(*frame.window_update_frame, &writer)) {
391 LOG(DFATAL) << "AppendWindowUpdateFrame failed";
392 return kNoPacket;
394 break;
395 case BLOCKED_FRAME:
396 if (!AppendBlockedFrame(*frame.blocked_frame, &writer)) {
397 LOG(DFATAL) << "AppendBlockedFrame failed";
398 return kNoPacket;
400 break;
401 default:
402 RaiseError(QUIC_INVALID_FRAME_DATA);
403 LOG(DFATAL) << "QUIC_INVALID_FRAME_DATA";
404 return kNoPacket;
408 // Save the length before writing, because take clears it.
409 const size_t len = writer.length();
410 // Less than or equal because truncated acks end up with max_plaintex_size
411 // length, even though they're typically slightly shorter.
412 DCHECK_LE(len, packet_size);
413 QuicPacket* packet = QuicPacket::NewDataPacket(
414 writer.take(), len, true, header.public_header.connection_id_length,
415 header.public_header.version_flag,
416 header.public_header.sequence_number_length);
418 if (fec_builder_) {
419 fec_builder_->OnBuiltFecProtectedPayload(header,
420 packet->FecProtectedData());
423 return SerializedPacket(header.packet_sequence_number,
424 header.public_header.sequence_number_length, packet,
425 GetPacketEntropyHash(header), nullptr);
428 SerializedPacket QuicFramer::BuildFecPacket(const QuicPacketHeader& header,
429 const QuicFecData& fec) {
430 DCHECK_EQ(IN_FEC_GROUP, header.is_in_fec_group);
431 DCHECK_NE(0u, header.fec_group);
432 size_t len = GetPacketHeaderSize(header);
433 len += fec.redundancy.length();
435 QuicDataWriter writer(len);
436 const SerializedPacket kNoPacket(0, PACKET_1BYTE_SEQUENCE_NUMBER, nullptr, 0,
437 nullptr);
438 if (!AppendPacketHeader(header, &writer)) {
439 LOG(DFATAL) << "AppendPacketHeader failed";
440 return kNoPacket;
443 if (!writer.WriteBytes(fec.redundancy.data(), fec.redundancy.length())) {
444 LOG(DFATAL) << "Failed to add FEC";
445 return kNoPacket;
448 return SerializedPacket(
449 header.packet_sequence_number,
450 header.public_header.sequence_number_length,
451 QuicPacket::NewFecPacket(writer.take(), len, true,
452 header.public_header.connection_id_length,
453 header.public_header.version_flag,
454 header.public_header.sequence_number_length),
455 GetPacketEntropyHash(header), nullptr);
458 // static
459 QuicEncryptedPacket* QuicFramer::BuildPublicResetPacket(
460 const QuicPublicResetPacket& packet) {
461 DCHECK(packet.public_header.reset_flag);
463 CryptoHandshakeMessage reset;
464 reset.set_tag(kPRST);
465 reset.SetValue(kRNON, packet.nonce_proof);
466 reset.SetValue(kRSEQ, packet.rejected_sequence_number);
467 if (!packet.client_address.address().empty()) {
468 // packet.client_address is non-empty.
469 QuicSocketAddressCoder address_coder(packet.client_address);
470 string serialized_address = address_coder.Encode();
471 if (serialized_address.empty()) {
472 return nullptr;
474 reset.SetStringPiece(kCADR, serialized_address);
476 const QuicData& reset_serialized = reset.GetSerialized();
478 size_t len =
479 kPublicFlagsSize + PACKET_8BYTE_CONNECTION_ID + reset_serialized.length();
480 QuicDataWriter writer(len);
482 uint8 flags = static_cast<uint8>(PACKET_PUBLIC_FLAGS_RST |
483 PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID);
484 if (!writer.WriteUInt8(flags)) {
485 return nullptr;
488 if (!writer.WriteUInt64(packet.public_header.connection_id)) {
489 return nullptr;
492 if (!writer.WriteBytes(reset_serialized.data(), reset_serialized.length())) {
493 return nullptr;
496 return new QuicEncryptedPacket(writer.take(), len, true);
499 QuicEncryptedPacket* QuicFramer::BuildVersionNegotiationPacket(
500 const QuicPacketPublicHeader& header,
501 const QuicVersionVector& supported_versions) {
502 DCHECK(header.version_flag);
503 size_t len = GetVersionNegotiationPacketSize(supported_versions.size());
504 QuicDataWriter writer(len);
506 uint8 flags = static_cast<uint8>(PACKET_PUBLIC_FLAGS_VERSION |
507 PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID);
508 if (!writer.WriteUInt8(flags)) {
509 return nullptr;
512 if (!writer.WriteUInt64(header.connection_id)) {
513 return nullptr;
516 for (size_t i = 0; i < supported_versions.size(); ++i) {
517 if (!writer.WriteUInt32(QuicVersionToQuicTag(supported_versions[i]))) {
518 return nullptr;
522 return new QuicEncryptedPacket(writer.take(), len, true);
525 bool QuicFramer::ProcessPacket(const QuicEncryptedPacket& packet) {
526 DCHECK(!reader_.get());
527 reader_.reset(new QuicDataReader(packet.data(), packet.length()));
529 visitor_->OnPacket();
531 // First parse the public header.
532 QuicPacketPublicHeader public_header;
533 if (!ProcessPublicHeader(&public_header)) {
534 DLOG(WARNING) << "Unable to process public header.";
535 DCHECK_NE("", detailed_error_);
536 return RaiseError(QUIC_INVALID_PACKET_HEADER);
539 if (!visitor_->OnUnauthenticatedPublicHeader(public_header)) {
540 // The visitor suppresses further processing of the packet.
541 reader_.reset(nullptr);
542 return true;
545 if (is_server_ && public_header.version_flag &&
546 public_header.versions[0] != quic_version_) {
547 if (!visitor_->OnProtocolVersionMismatch(public_header.versions[0])) {
548 reader_.reset(nullptr);
549 return true;
553 bool rv;
554 if (!is_server_ && public_header.version_flag) {
555 rv = ProcessVersionNegotiationPacket(&public_header);
556 } else if (public_header.reset_flag) {
557 rv = ProcessPublicResetPacket(public_header);
558 } else {
559 rv = ProcessDataPacket(public_header, packet);
562 reader_.reset(nullptr);
563 return rv;
566 bool QuicFramer::ProcessVersionNegotiationPacket(
567 QuicPacketPublicHeader* public_header) {
568 DCHECK(!is_server_);
569 // Try reading at least once to raise error if the packet is invalid.
570 do {
571 QuicTag version;
572 if (!reader_->ReadBytes(&version, kQuicVersionSize)) {
573 set_detailed_error("Unable to read supported version in negotiation.");
574 return RaiseError(QUIC_INVALID_VERSION_NEGOTIATION_PACKET);
576 public_header->versions.push_back(QuicTagToQuicVersion(version));
577 } while (!reader_->IsDoneReading());
579 visitor_->OnVersionNegotiationPacket(*public_header);
580 return true;
583 bool QuicFramer::ProcessDataPacket(
584 const QuicPacketPublicHeader& public_header,
585 const QuicEncryptedPacket& packet) {
586 QuicPacketHeader header(public_header);
587 if (!ProcessPacketHeader(&header, packet)) {
588 DLOG(WARNING) << "Unable to process data packet header.";
589 return false;
592 if (!visitor_->OnPacketHeader(header)) {
593 // The visitor suppresses further processing of the packet.
594 return true;
597 if (packet.length() > kMaxPacketSize) {
598 DLOG(WARNING) << "Packet too large: " << packet.length();
599 return RaiseError(QUIC_PACKET_TOO_LARGE);
602 // Handle the payload.
603 if (!header.fec_flag) {
604 if (header.is_in_fec_group == IN_FEC_GROUP) {
605 StringPiece payload = reader_->PeekRemainingPayload();
606 visitor_->OnFecProtectedPayload(payload);
608 if (!ProcessFrameData(header)) {
609 DCHECK_NE(QUIC_NO_ERROR, error_); // ProcessFrameData sets the error.
610 DLOG(WARNING) << "Unable to process frame data.";
611 return false;
613 } else {
614 QuicFecData fec_data;
615 fec_data.fec_group = header.fec_group;
616 fec_data.redundancy = reader_->ReadRemainingPayload();
617 visitor_->OnFecData(fec_data);
620 visitor_->OnPacketComplete();
621 return true;
624 bool QuicFramer::ProcessPublicResetPacket(
625 const QuicPacketPublicHeader& public_header) {
626 QuicPublicResetPacket packet(public_header);
628 scoped_ptr<CryptoHandshakeMessage> reset(
629 CryptoFramer::ParseMessage(reader_->ReadRemainingPayload()));
630 if (!reset.get()) {
631 set_detailed_error("Unable to read reset message.");
632 return RaiseError(QUIC_INVALID_PUBLIC_RST_PACKET);
634 if (reset->tag() != kPRST) {
635 set_detailed_error("Incorrect message tag.");
636 return RaiseError(QUIC_INVALID_PUBLIC_RST_PACKET);
639 if (reset->GetUint64(kRNON, &packet.nonce_proof) != QUIC_NO_ERROR) {
640 set_detailed_error("Unable to read nonce proof.");
641 return RaiseError(QUIC_INVALID_PUBLIC_RST_PACKET);
643 // TODO(satyamshekhar): validate nonce to protect against DoS.
645 if (reset->GetUint64(kRSEQ, &packet.rejected_sequence_number) !=
646 QUIC_NO_ERROR) {
647 set_detailed_error("Unable to read rejected sequence number.");
648 return RaiseError(QUIC_INVALID_PUBLIC_RST_PACKET);
651 StringPiece address;
652 if (reset->GetStringPiece(kCADR, &address)) {
653 QuicSocketAddressCoder address_coder;
654 if (address_coder.Decode(address.data(), address.length())) {
655 packet.client_address = IPEndPoint(address_coder.ip(),
656 address_coder.port());
660 visitor_->OnPublicResetPacket(packet);
661 return true;
664 bool QuicFramer::ProcessRevivedPacket(QuicPacketHeader* header,
665 StringPiece payload) {
666 DCHECK(!reader_.get());
668 visitor_->OnRevivedPacket();
670 header->entropy_hash = GetPacketEntropyHash(*header);
672 if (!visitor_->OnPacketHeader(*header)) {
673 return true;
676 if (payload.length() > kMaxPacketSize) {
677 set_detailed_error("Revived packet too large.");
678 return RaiseError(QUIC_PACKET_TOO_LARGE);
681 reader_.reset(new QuicDataReader(payload.data(), payload.length()));
682 if (!ProcessFrameData(*header)) {
683 DCHECK_NE(QUIC_NO_ERROR, error_); // ProcessFrameData sets the error.
684 DLOG(WARNING) << "Unable to process frame data.";
685 return false;
688 visitor_->OnPacketComplete();
689 reader_.reset(nullptr);
690 return true;
693 bool QuicFramer::AppendPacketHeader(const QuicPacketHeader& header,
694 QuicDataWriter* writer) {
695 DVLOG(1) << "Appending header: " << header;
696 DCHECK(header.fec_group > 0 || header.is_in_fec_group == NOT_IN_FEC_GROUP);
697 uint8 public_flags = 0;
698 if (header.public_header.reset_flag) {
699 public_flags |= PACKET_PUBLIC_FLAGS_RST;
701 if (header.public_header.version_flag) {
702 public_flags |= PACKET_PUBLIC_FLAGS_VERSION;
705 public_flags |=
706 GetSequenceNumberFlags(header.public_header.sequence_number_length)
707 << kPublicHeaderSequenceNumberShift;
709 switch (header.public_header.connection_id_length) {
710 case PACKET_0BYTE_CONNECTION_ID:
711 if (!writer->WriteUInt8(
712 public_flags | PACKET_PUBLIC_FLAGS_0BYTE_CONNECTION_ID)) {
713 return false;
715 break;
716 case PACKET_1BYTE_CONNECTION_ID:
717 if (!writer->WriteUInt8(
718 public_flags | PACKET_PUBLIC_FLAGS_1BYTE_CONNECTION_ID)) {
719 return false;
721 if (!writer->WriteUInt8(
722 header.public_header.connection_id & k1ByteConnectionIdMask)) {
723 return false;
725 break;
726 case PACKET_4BYTE_CONNECTION_ID:
727 if (!writer->WriteUInt8(
728 public_flags | PACKET_PUBLIC_FLAGS_4BYTE_CONNECTION_ID)) {
729 return false;
731 if (!writer->WriteUInt32(
732 header.public_header.connection_id & k4ByteConnectionIdMask)) {
733 return false;
735 break;
736 case PACKET_8BYTE_CONNECTION_ID:
737 if (!writer->WriteUInt8(
738 public_flags | PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID)) {
739 return false;
741 if (!writer->WriteUInt64(header.public_header.connection_id)) {
742 return false;
744 break;
746 last_serialized_connection_id_ = header.public_header.connection_id;
748 if (header.public_header.version_flag) {
749 DCHECK(!is_server_);
750 writer->WriteUInt32(QuicVersionToQuicTag(quic_version_));
753 if (!AppendPacketSequenceNumber(header.public_header.sequence_number_length,
754 header.packet_sequence_number, writer)) {
755 return false;
758 uint8 private_flags = 0;
759 if (header.entropy_flag) {
760 private_flags |= PACKET_PRIVATE_FLAGS_ENTROPY;
762 if (header.is_in_fec_group == IN_FEC_GROUP) {
763 private_flags |= PACKET_PRIVATE_FLAGS_FEC_GROUP;
765 if (header.fec_flag) {
766 private_flags |= PACKET_PRIVATE_FLAGS_FEC;
768 if (!writer->WriteUInt8(private_flags)) {
769 return false;
772 // The FEC group number is the sequence number of the first fec
773 // protected packet, or 0 if this packet is not protected.
774 if (header.is_in_fec_group == IN_FEC_GROUP) {
775 DCHECK_LE(header.fec_group, header.packet_sequence_number);
776 DCHECK_LT(header.packet_sequence_number - header.fec_group, 255u);
777 // Offset from the current packet sequence number to the first fec
778 // protected packet.
779 uint8 first_fec_protected_packet_offset =
780 static_cast<uint8>(header.packet_sequence_number - header.fec_group);
781 if (!writer->WriteBytes(&first_fec_protected_packet_offset, 1)) {
782 return false;
786 return true;
789 const QuicTime::Delta QuicFramer::CalculateTimestampFromWire(
790 uint32 time_delta_us) {
791 // The new time_delta might have wrapped to the next epoch, or it
792 // might have reverse wrapped to the previous epoch, or it might
793 // remain in the same epoch. Select the time closest to the previous
794 // time.
796 // epoch_delta is the delta between epochs. A delta is 4 bytes of
797 // microseconds.
798 const uint64 epoch_delta = GG_UINT64_C(1) << 32;
799 uint64 epoch = last_timestamp_.ToMicroseconds() & ~(epoch_delta - 1);
800 // Wrapping is safe here because a wrapped value will not be ClosestTo below.
801 uint64 prev_epoch = epoch - epoch_delta;
802 uint64 next_epoch = epoch + epoch_delta;
804 uint64 time = ClosestTo(last_timestamp_.ToMicroseconds(),
805 epoch + time_delta_us,
806 ClosestTo(last_timestamp_.ToMicroseconds(),
807 prev_epoch + time_delta_us,
808 next_epoch + time_delta_us));
810 return QuicTime::Delta::FromMicroseconds(time);
813 QuicPacketSequenceNumber QuicFramer::CalculatePacketSequenceNumberFromWire(
814 QuicSequenceNumberLength sequence_number_length,
815 QuicPacketSequenceNumber packet_sequence_number) const {
816 // The new sequence number might have wrapped to the next epoch, or
817 // it might have reverse wrapped to the previous epoch, or it might
818 // remain in the same epoch. Select the sequence number closest to the
819 // next expected sequence number, the previous sequence number plus 1.
821 // epoch_delta is the delta between epochs the sequence number was serialized
822 // with, so the correct value is likely the same epoch as the last sequence
823 // number or an adjacent epoch.
824 const QuicPacketSequenceNumber epoch_delta =
825 GG_UINT64_C(1) << (8 * sequence_number_length);
826 QuicPacketSequenceNumber next_sequence_number = last_sequence_number_ + 1;
827 QuicPacketSequenceNumber epoch = last_sequence_number_ & ~(epoch_delta - 1);
828 QuicPacketSequenceNumber prev_epoch = epoch - epoch_delta;
829 QuicPacketSequenceNumber next_epoch = epoch + epoch_delta;
831 return ClosestTo(next_sequence_number,
832 epoch + packet_sequence_number,
833 ClosestTo(next_sequence_number,
834 prev_epoch + packet_sequence_number,
835 next_epoch + packet_sequence_number));
838 bool QuicFramer::ProcessPublicHeader(
839 QuicPacketPublicHeader* public_header) {
840 uint8 public_flags;
841 if (!reader_->ReadBytes(&public_flags, 1)) {
842 set_detailed_error("Unable to read public flags.");
843 return false;
846 public_header->reset_flag = (public_flags & PACKET_PUBLIC_FLAGS_RST) != 0;
847 public_header->version_flag =
848 (public_flags & PACKET_PUBLIC_FLAGS_VERSION) != 0;
850 if (validate_flags_ &&
851 !public_header->version_flag && public_flags > PACKET_PUBLIC_FLAGS_MAX) {
852 set_detailed_error("Illegal public flags value.");
853 return false;
856 if (public_header->reset_flag && public_header->version_flag) {
857 set_detailed_error("Got version flag in reset packet");
858 return false;
861 switch (public_flags & PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID) {
862 case PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID:
863 if (!reader_->ReadUInt64(&public_header->connection_id)) {
864 set_detailed_error("Unable to read ConnectionId.");
865 return false;
867 public_header->connection_id_length = PACKET_8BYTE_CONNECTION_ID;
868 break;
869 case PACKET_PUBLIC_FLAGS_4BYTE_CONNECTION_ID:
870 // If the connection_id is truncated, expect to read the last serialized
871 // connection_id.
872 if (!reader_->ReadBytes(&public_header->connection_id,
873 PACKET_4BYTE_CONNECTION_ID)) {
874 set_detailed_error("Unable to read ConnectionId.");
875 return false;
877 if (last_serialized_connection_id_ &&
878 (public_header->connection_id & k4ByteConnectionIdMask) !=
879 (last_serialized_connection_id_ & k4ByteConnectionIdMask)) {
880 set_detailed_error("Truncated 4 byte ConnectionId does not match "
881 "previous connection_id.");
882 return false;
884 public_header->connection_id_length = PACKET_4BYTE_CONNECTION_ID;
885 public_header->connection_id = last_serialized_connection_id_;
886 break;
887 case PACKET_PUBLIC_FLAGS_1BYTE_CONNECTION_ID:
888 if (!reader_->ReadBytes(&public_header->connection_id,
889 PACKET_1BYTE_CONNECTION_ID)) {
890 set_detailed_error("Unable to read ConnectionId.");
891 return false;
893 if (last_serialized_connection_id_ &&
894 (public_header->connection_id & k1ByteConnectionIdMask) !=
895 (last_serialized_connection_id_ & k1ByteConnectionIdMask)) {
896 set_detailed_error("Truncated 1 byte ConnectionId does not match "
897 "previous connection_id.");
898 return false;
900 public_header->connection_id_length = PACKET_1BYTE_CONNECTION_ID;
901 public_header->connection_id = last_serialized_connection_id_;
902 break;
903 case PACKET_PUBLIC_FLAGS_0BYTE_CONNECTION_ID:
904 public_header->connection_id_length = PACKET_0BYTE_CONNECTION_ID;
905 public_header->connection_id = last_serialized_connection_id_;
906 break;
909 public_header->sequence_number_length =
910 ReadSequenceNumberLength(
911 public_flags >> kPublicHeaderSequenceNumberShift);
913 // Read the version only if the packet is from the client.
914 // version flag from the server means version negotiation packet.
915 if (public_header->version_flag && is_server_) {
916 QuicTag version_tag;
917 if (!reader_->ReadUInt32(&version_tag)) {
918 set_detailed_error("Unable to read protocol version.");
919 return false;
922 // If the version from the new packet is the same as the version of this
923 // framer, then the public flags should be set to something we understand.
924 // If not, this raises an error.
925 QuicVersion version = QuicTagToQuicVersion(version_tag);
926 if (version == quic_version_ && public_flags > PACKET_PUBLIC_FLAGS_MAX) {
927 set_detailed_error("Illegal public flags value.");
928 return false;
930 public_header->versions.push_back(version);
932 return true;
935 // static
936 QuicSequenceNumberLength QuicFramer::GetMinSequenceNumberLength(
937 QuicPacketSequenceNumber sequence_number) {
938 if (sequence_number < 1 << (PACKET_1BYTE_SEQUENCE_NUMBER * 8)) {
939 return PACKET_1BYTE_SEQUENCE_NUMBER;
940 } else if (sequence_number < 1 << (PACKET_2BYTE_SEQUENCE_NUMBER * 8)) {
941 return PACKET_2BYTE_SEQUENCE_NUMBER;
942 } else if (sequence_number <
943 GG_UINT64_C(1) << (PACKET_4BYTE_SEQUENCE_NUMBER * 8)) {
944 return PACKET_4BYTE_SEQUENCE_NUMBER;
945 } else {
946 return PACKET_6BYTE_SEQUENCE_NUMBER;
950 // static
951 uint8 QuicFramer::GetSequenceNumberFlags(
952 QuicSequenceNumberLength sequence_number_length) {
953 switch (sequence_number_length) {
954 case PACKET_1BYTE_SEQUENCE_NUMBER:
955 return PACKET_FLAGS_1BYTE_SEQUENCE;
956 case PACKET_2BYTE_SEQUENCE_NUMBER:
957 return PACKET_FLAGS_2BYTE_SEQUENCE;
958 case PACKET_4BYTE_SEQUENCE_NUMBER:
959 return PACKET_FLAGS_4BYTE_SEQUENCE;
960 case PACKET_6BYTE_SEQUENCE_NUMBER:
961 return PACKET_FLAGS_6BYTE_SEQUENCE;
962 default:
963 LOG(DFATAL) << "Unreachable case statement.";
964 return PACKET_FLAGS_6BYTE_SEQUENCE;
968 // static
969 QuicFramer::AckFrameInfo QuicFramer::GetAckFrameInfo(
970 const QuicAckFrame& frame) {
971 AckFrameInfo ack_info;
972 if (frame.missing_packets.empty()) {
973 return ack_info;
975 DCHECK_GE(frame.largest_observed, *frame.missing_packets.rbegin());
976 size_t cur_range_length = 0;
977 SequenceNumberSet::const_iterator iter = frame.missing_packets.begin();
978 QuicPacketSequenceNumber last_missing = *iter;
979 ++iter;
980 for (; iter != frame.missing_packets.end(); ++iter) {
981 if (cur_range_length < numeric_limits<uint8>::max() &&
982 *iter == (last_missing + 1)) {
983 ++cur_range_length;
984 } else {
985 ack_info.nack_ranges[last_missing - cur_range_length] =
986 static_cast<uint8>(cur_range_length);
987 cur_range_length = 0;
989 ack_info.max_delta = max(ack_info.max_delta, *iter - last_missing);
990 last_missing = *iter;
992 // Include the last nack range.
993 ack_info.nack_ranges[last_missing - cur_range_length] =
994 static_cast<uint8>(cur_range_length);
995 // Include the range to the largest observed.
996 ack_info.max_delta =
997 max(ack_info.max_delta, frame.largest_observed - last_missing);
998 return ack_info;
1001 bool QuicFramer::ProcessPacketHeader(
1002 QuicPacketHeader* header,
1003 const QuicEncryptedPacket& packet) {
1004 if (!ProcessPacketSequenceNumber(header->public_header.sequence_number_length,
1005 &header->packet_sequence_number)) {
1006 set_detailed_error("Unable to read sequence number.");
1007 return RaiseError(QUIC_INVALID_PACKET_HEADER);
1010 if (header->packet_sequence_number == 0u) {
1011 set_detailed_error("Packet sequence numbers cannot be 0.");
1012 return RaiseError(QUIC_INVALID_PACKET_HEADER);
1015 if (!visitor_->OnUnauthenticatedHeader(*header)) {
1016 return false;
1019 if (!DecryptPayload(*header, packet)) {
1020 set_detailed_error("Unable to decrypt payload.");
1021 return RaiseError(QUIC_DECRYPTION_FAILURE);
1024 uint8 private_flags;
1025 if (!reader_->ReadBytes(&private_flags, 1)) {
1026 set_detailed_error("Unable to read private flags.");
1027 return RaiseError(QUIC_INVALID_PACKET_HEADER);
1030 if (private_flags > PACKET_PRIVATE_FLAGS_MAX) {
1031 set_detailed_error("Illegal private flags value.");
1032 return RaiseError(QUIC_INVALID_PACKET_HEADER);
1035 header->entropy_flag = (private_flags & PACKET_PRIVATE_FLAGS_ENTROPY) != 0;
1036 header->fec_flag = (private_flags & PACKET_PRIVATE_FLAGS_FEC) != 0;
1038 if ((private_flags & PACKET_PRIVATE_FLAGS_FEC_GROUP) != 0) {
1039 header->is_in_fec_group = IN_FEC_GROUP;
1040 uint8 first_fec_protected_packet_offset;
1041 if (!reader_->ReadBytes(&first_fec_protected_packet_offset, 1)) {
1042 set_detailed_error("Unable to read first fec protected packet offset.");
1043 return RaiseError(QUIC_INVALID_PACKET_HEADER);
1045 if (first_fec_protected_packet_offset >= header->packet_sequence_number) {
1046 set_detailed_error("First fec protected packet offset must be less "
1047 "than the sequence number.");
1048 return RaiseError(QUIC_INVALID_PACKET_HEADER);
1050 header->fec_group =
1051 header->packet_sequence_number - first_fec_protected_packet_offset;
1054 header->entropy_hash = GetPacketEntropyHash(*header);
1055 // Set the last sequence number after we have decrypted the packet
1056 // so we are confident is not attacker controlled.
1057 last_sequence_number_ = header->packet_sequence_number;
1058 return true;
1061 bool QuicFramer::ProcessPacketSequenceNumber(
1062 QuicSequenceNumberLength sequence_number_length,
1063 QuicPacketSequenceNumber* sequence_number) {
1064 QuicPacketSequenceNumber wire_sequence_number = 0u;
1065 if (!reader_->ReadBytes(&wire_sequence_number, sequence_number_length)) {
1066 return false;
1069 // TODO(ianswett): Explore the usefulness of trying multiple sequence numbers
1070 // in case the first guess is incorrect.
1071 *sequence_number =
1072 CalculatePacketSequenceNumberFromWire(sequence_number_length,
1073 wire_sequence_number);
1074 return true;
1077 bool QuicFramer::ProcessFrameData(const QuicPacketHeader& header) {
1078 if (reader_->IsDoneReading()) {
1079 set_detailed_error("Packet has no frames.");
1080 return RaiseError(QUIC_MISSING_PAYLOAD);
1082 while (!reader_->IsDoneReading()) {
1083 uint8 frame_type;
1084 if (!reader_->ReadBytes(&frame_type, 1)) {
1085 set_detailed_error("Unable to read frame type.");
1086 return RaiseError(QUIC_INVALID_FRAME_DATA);
1089 if (frame_type & kQuicFrameTypeSpecialMask) {
1090 // Stream Frame
1091 if (frame_type & kQuicFrameTypeStreamMask) {
1092 QuicStreamFrame frame;
1093 if (!ProcessStreamFrame(frame_type, &frame)) {
1094 return RaiseError(QUIC_INVALID_STREAM_DATA);
1096 if (!visitor_->OnStreamFrame(frame)) {
1097 DVLOG(1) << "Visitor asked to stop further processing.";
1098 // Returning true since there was no parsing error.
1099 return true;
1101 continue;
1104 // Ack Frame
1105 if (frame_type & kQuicFrameTypeAckMask) {
1106 QuicAckFrame frame;
1107 if (!ProcessAckFrame(frame_type, &frame)) {
1108 return RaiseError(QUIC_INVALID_ACK_DATA);
1110 if (!visitor_->OnAckFrame(frame)) {
1111 DVLOG(1) << "Visitor asked to stop further processing.";
1112 // Returning true since there was no parsing error.
1113 return true;
1115 continue;
1118 // This was a special frame type that did not match any
1119 // of the known ones. Error.
1120 set_detailed_error("Illegal frame type.");
1121 DLOG(WARNING) << "Illegal frame type: "
1122 << static_cast<int>(frame_type);
1123 return RaiseError(QUIC_INVALID_FRAME_DATA);
1126 switch (frame_type) {
1127 case PADDING_FRAME:
1128 // We're done with the packet.
1129 return true;
1131 case RST_STREAM_FRAME: {
1132 QuicRstStreamFrame frame;
1133 if (!ProcessRstStreamFrame(&frame)) {
1134 return RaiseError(QUIC_INVALID_RST_STREAM_DATA);
1136 if (!visitor_->OnRstStreamFrame(frame)) {
1137 DVLOG(1) << "Visitor asked to stop further processing.";
1138 // Returning true since there was no parsing error.
1139 return true;
1141 continue;
1144 case CONNECTION_CLOSE_FRAME: {
1145 QuicConnectionCloseFrame frame;
1146 if (!ProcessConnectionCloseFrame(&frame)) {
1147 return RaiseError(QUIC_INVALID_CONNECTION_CLOSE_DATA);
1150 if (!visitor_->OnConnectionCloseFrame(frame)) {
1151 DVLOG(1) << "Visitor asked to stop further processing.";
1152 // Returning true since there was no parsing error.
1153 return true;
1155 continue;
1158 case GOAWAY_FRAME: {
1159 QuicGoAwayFrame goaway_frame;
1160 if (!ProcessGoAwayFrame(&goaway_frame)) {
1161 return RaiseError(QUIC_INVALID_GOAWAY_DATA);
1163 if (!visitor_->OnGoAwayFrame(goaway_frame)) {
1164 DVLOG(1) << "Visitor asked to stop further processing.";
1165 // Returning true since there was no parsing error.
1166 return true;
1168 continue;
1171 case WINDOW_UPDATE_FRAME: {
1172 QuicWindowUpdateFrame window_update_frame;
1173 if (!ProcessWindowUpdateFrame(&window_update_frame)) {
1174 return RaiseError(QUIC_INVALID_WINDOW_UPDATE_DATA);
1176 if (!visitor_->OnWindowUpdateFrame(window_update_frame)) {
1177 DVLOG(1) << "Visitor asked to stop further processing.";
1178 // Returning true since there was no parsing error.
1179 return true;
1181 continue;
1184 case BLOCKED_FRAME: {
1185 QuicBlockedFrame blocked_frame;
1186 if (!ProcessBlockedFrame(&blocked_frame)) {
1187 return RaiseError(QUIC_INVALID_BLOCKED_DATA);
1189 if (!visitor_->OnBlockedFrame(blocked_frame)) {
1190 DVLOG(1) << "Visitor asked to stop further processing.";
1191 // Returning true since there was no parsing error.
1192 return true;
1194 continue;
1197 case STOP_WAITING_FRAME: {
1198 QuicStopWaitingFrame stop_waiting_frame;
1199 if (!ProcessStopWaitingFrame(header, &stop_waiting_frame)) {
1200 return RaiseError(QUIC_INVALID_STOP_WAITING_DATA);
1202 if (!visitor_->OnStopWaitingFrame(stop_waiting_frame)) {
1203 DVLOG(1) << "Visitor asked to stop further processing.";
1204 // Returning true since there was no parsing error.
1205 return true;
1207 continue;
1209 case PING_FRAME: {
1210 // Ping has no payload.
1211 QuicPingFrame ping_frame;
1212 if (!visitor_->OnPingFrame(ping_frame)) {
1213 DVLOG(1) << "Visitor asked to stop further processing.";
1214 // Returning true since there was no parsing error.
1215 return true;
1217 continue;
1220 default:
1221 set_detailed_error("Illegal frame type.");
1222 DLOG(WARNING) << "Illegal frame type: "
1223 << static_cast<int>(frame_type);
1224 return RaiseError(QUIC_INVALID_FRAME_DATA);
1228 return true;
1231 bool QuicFramer::ProcessStreamFrame(uint8 frame_type,
1232 QuicStreamFrame* frame) {
1233 uint8 stream_flags = frame_type;
1235 stream_flags &= ~kQuicFrameTypeStreamMask;
1237 // Read from right to left: StreamID, Offset, Data Length, Fin.
1238 const uint8 stream_id_length = (stream_flags & kQuicStreamIDLengthMask) + 1;
1239 stream_flags >>= kQuicStreamIdShift;
1241 uint8 offset_length = (stream_flags & kQuicStreamOffsetMask);
1242 // There is no encoding for 1 byte, only 0 and 2 through 8.
1243 if (offset_length > 0) {
1244 offset_length += 1;
1246 stream_flags >>= kQuicStreamOffsetShift;
1248 bool has_data_length =
1249 (stream_flags & kQuicStreamDataLengthMask) == kQuicStreamDataLengthMask;
1250 stream_flags >>= kQuicStreamDataLengthShift;
1252 frame->fin = (stream_flags & kQuicStreamFinMask) == kQuicStreamFinShift;
1254 frame->stream_id = 0;
1255 if (!reader_->ReadBytes(&frame->stream_id, stream_id_length)) {
1256 set_detailed_error("Unable to read stream_id.");
1257 return false;
1260 frame->offset = 0;
1261 if (!reader_->ReadBytes(&frame->offset, offset_length)) {
1262 set_detailed_error("Unable to read offset.");
1263 return false;
1266 StringPiece frame_data;
1267 if (has_data_length) {
1268 if (!reader_->ReadStringPiece16(&frame_data)) {
1269 set_detailed_error("Unable to read frame data.");
1270 return false;
1272 } else {
1273 if (!reader_->ReadStringPiece(&frame_data, reader_->BytesRemaining())) {
1274 set_detailed_error("Unable to read frame data.");
1275 return false;
1278 // Point frame to the right data.
1279 frame->data.Clear();
1280 if (!frame_data.empty()) {
1281 frame->data.Append(const_cast<char*>(frame_data.data()), frame_data.size());
1284 return true;
1287 bool QuicFramer::ProcessAckFrame(uint8 frame_type, QuicAckFrame* ack_frame) {
1288 // Determine the three lengths from the frame type: largest observed length,
1289 // missing sequence number length, and missing range length.
1290 const QuicSequenceNumberLength missing_sequence_number_length =
1291 ReadSequenceNumberLength(frame_type);
1292 frame_type >>= kQuicSequenceNumberLengthShift;
1293 const QuicSequenceNumberLength largest_observed_sequence_number_length =
1294 ReadSequenceNumberLength(frame_type);
1295 frame_type >>= kQuicSequenceNumberLengthShift;
1296 ack_frame->is_truncated = frame_type & kQuicAckTruncatedMask;
1297 frame_type >>= kQuicAckTruncatedShift;
1298 bool has_nacks = frame_type & kQuicHasNacksMask;
1300 if (!reader_->ReadBytes(&ack_frame->entropy_hash, 1)) {
1301 set_detailed_error("Unable to read entropy hash for received packets.");
1302 return false;
1305 if (!reader_->ReadBytes(&ack_frame->largest_observed,
1306 largest_observed_sequence_number_length)) {
1307 set_detailed_error("Unable to read largest observed.");
1308 return false;
1311 uint64 delta_time_largest_observed_us;
1312 if (!reader_->ReadUFloat16(&delta_time_largest_observed_us)) {
1313 set_detailed_error("Unable to read delta time largest observed.");
1314 return false;
1317 if (delta_time_largest_observed_us == kUFloat16MaxValue) {
1318 ack_frame->delta_time_largest_observed = QuicTime::Delta::Infinite();
1319 } else {
1320 ack_frame->delta_time_largest_observed =
1321 QuicTime::Delta::FromMicroseconds(delta_time_largest_observed_us);
1324 if (!ProcessTimestampsInAckFrame(ack_frame)) {
1325 return false;
1328 if (!has_nacks) {
1329 return true;
1332 uint8 num_missing_ranges;
1333 if (!reader_->ReadBytes(&num_missing_ranges, 1)) {
1334 set_detailed_error("Unable to read num missing packet ranges.");
1335 return false;
1338 QuicPacketSequenceNumber last_sequence_number = ack_frame->largest_observed;
1339 for (size_t i = 0; i < num_missing_ranges; ++i) {
1340 QuicPacketSequenceNumber missing_delta = 0;
1341 if (!reader_->ReadBytes(&missing_delta, missing_sequence_number_length)) {
1342 set_detailed_error("Unable to read missing sequence number delta.");
1343 return false;
1345 last_sequence_number -= missing_delta;
1346 QuicPacketSequenceNumber range_length = 0;
1347 if (!reader_->ReadBytes(&range_length, PACKET_1BYTE_SEQUENCE_NUMBER)) {
1348 set_detailed_error("Unable to read missing sequence number range.");
1349 return false;
1351 for (size_t i = 0; i <= range_length; ++i) {
1352 ack_frame->missing_packets.insert(last_sequence_number - i);
1354 // Subtract an extra 1 to ensure ranges are represented efficiently and
1355 // can't overlap by 1 sequence number. This allows a missing_delta of 0
1356 // to represent an adjacent nack range.
1357 last_sequence_number -= (range_length + 1);
1360 // Parse the revived packets list.
1361 uint8 num_revived_packets;
1362 if (!reader_->ReadBytes(&num_revived_packets, 1)) {
1363 set_detailed_error("Unable to read num revived packets.");
1364 return false;
1367 for (size_t i = 0; i < num_revived_packets; ++i) {
1368 QuicPacketSequenceNumber revived_packet = 0;
1369 if (!reader_->ReadBytes(&revived_packet,
1370 largest_observed_sequence_number_length)) {
1371 set_detailed_error("Unable to read revived packet.");
1372 return false;
1375 ack_frame->revived_packets.insert(revived_packet);
1378 return true;
1381 bool QuicFramer::ProcessTimestampsInAckFrame(QuicAckFrame* ack_frame) {
1382 if (!ack_frame->is_truncated) {
1383 uint8 num_received_packets;
1384 if (!reader_->ReadBytes(&num_received_packets, 1)) {
1385 set_detailed_error("Unable to read num received packets.");
1386 return false;
1389 if (num_received_packets > 0) {
1390 uint8 delta_from_largest_observed;
1391 if (!reader_->ReadBytes(&delta_from_largest_observed,
1392 PACKET_1BYTE_SEQUENCE_NUMBER)) {
1393 set_detailed_error(
1394 "Unable to read sequence delta in received packets.");
1395 return false;
1397 QuicPacketSequenceNumber seq_num = ack_frame->largest_observed -
1398 delta_from_largest_observed;
1400 // Time delta from the framer creation.
1401 uint32 time_delta_us;
1402 if (!reader_->ReadBytes(&time_delta_us, sizeof(time_delta_us))) {
1403 set_detailed_error("Unable to read time delta in received packets.");
1404 return false;
1407 last_timestamp_ = CalculateTimestampFromWire(time_delta_us);
1409 ack_frame->received_packet_times.push_back(
1410 make_pair(seq_num, creation_time_.Add(last_timestamp_)));
1412 for (uint8 i = 1; i < num_received_packets; ++i) {
1413 if (!reader_->ReadBytes(&delta_from_largest_observed,
1414 PACKET_1BYTE_SEQUENCE_NUMBER)) {
1415 set_detailed_error(
1416 "Unable to read sequence delta in received packets.");
1417 return false;
1419 seq_num = ack_frame->largest_observed - delta_from_largest_observed;
1421 // Time delta from the previous timestamp.
1422 uint64 incremental_time_delta_us;
1423 if (!reader_->ReadUFloat16(&incremental_time_delta_us)) {
1424 set_detailed_error(
1425 "Unable to read incremental time delta in received packets.");
1426 return false;
1429 last_timestamp_ = last_timestamp_.Add(
1430 QuicTime::Delta::FromMicroseconds(incremental_time_delta_us));
1431 ack_frame->received_packet_times.push_back(
1432 make_pair(seq_num, creation_time_.Add(last_timestamp_)));
1436 return true;
1439 bool QuicFramer::ProcessStopWaitingFrame(const QuicPacketHeader& header,
1440 QuicStopWaitingFrame* stop_waiting) {
1441 if (!reader_->ReadBytes(&stop_waiting->entropy_hash, 1)) {
1442 set_detailed_error("Unable to read entropy hash for sent packets.");
1443 return false;
1446 QuicPacketSequenceNumber least_unacked_delta = 0;
1447 if (!reader_->ReadBytes(&least_unacked_delta,
1448 header.public_header.sequence_number_length)) {
1449 set_detailed_error("Unable to read least unacked delta.");
1450 return false;
1452 DCHECK_GE(header.packet_sequence_number, least_unacked_delta);
1453 stop_waiting->least_unacked =
1454 header.packet_sequence_number - least_unacked_delta;
1456 return true;
1459 bool QuicFramer::ProcessRstStreamFrame(QuicRstStreamFrame* frame) {
1460 if (!reader_->ReadUInt32(&frame->stream_id)) {
1461 set_detailed_error("Unable to read stream_id.");
1462 return false;
1465 if (!reader_->ReadUInt64(&frame->byte_offset)) {
1466 set_detailed_error("Unable to read rst stream sent byte offset.");
1467 return false;
1470 uint32 error_code;
1471 if (!reader_->ReadUInt32(&error_code)) {
1472 set_detailed_error("Unable to read rst stream error code.");
1473 return false;
1476 if (error_code >= QUIC_STREAM_LAST_ERROR) {
1477 set_detailed_error("Invalid rst stream error code.");
1478 return false;
1481 frame->error_code = static_cast<QuicRstStreamErrorCode>(error_code);
1483 StringPiece error_details;
1484 if (!reader_->ReadStringPiece16(&error_details)) {
1485 set_detailed_error("Unable to read rst stream error details.");
1486 return false;
1488 frame->error_details = error_details.as_string();
1490 return true;
1493 bool QuicFramer::ProcessConnectionCloseFrame(QuicConnectionCloseFrame* frame) {
1494 uint32 error_code;
1495 if (!reader_->ReadUInt32(&error_code)) {
1496 set_detailed_error("Unable to read connection close error code.");
1497 return false;
1500 if (error_code >= QUIC_LAST_ERROR) {
1501 set_detailed_error("Invalid error code.");
1502 return false;
1505 frame->error_code = static_cast<QuicErrorCode>(error_code);
1507 StringPiece error_details;
1508 if (!reader_->ReadStringPiece16(&error_details)) {
1509 set_detailed_error("Unable to read connection close error details.");
1510 return false;
1512 frame->error_details = error_details.as_string();
1514 return true;
1517 bool QuicFramer::ProcessGoAwayFrame(QuicGoAwayFrame* frame) {
1518 uint32 error_code;
1519 if (!reader_->ReadUInt32(&error_code)) {
1520 set_detailed_error("Unable to read go away error code.");
1521 return false;
1523 frame->error_code = static_cast<QuicErrorCode>(error_code);
1525 if (error_code >= QUIC_LAST_ERROR) {
1526 set_detailed_error("Invalid error code.");
1527 return false;
1530 uint32 stream_id;
1531 if (!reader_->ReadUInt32(&stream_id)) {
1532 set_detailed_error("Unable to read last good stream id.");
1533 return false;
1535 frame->last_good_stream_id = static_cast<QuicStreamId>(stream_id);
1537 StringPiece reason_phrase;
1538 if (!reader_->ReadStringPiece16(&reason_phrase)) {
1539 set_detailed_error("Unable to read goaway reason.");
1540 return false;
1542 frame->reason_phrase = reason_phrase.as_string();
1544 return true;
1547 bool QuicFramer::ProcessWindowUpdateFrame(QuicWindowUpdateFrame* frame) {
1548 if (!reader_->ReadUInt32(&frame->stream_id)) {
1549 set_detailed_error("Unable to read stream_id.");
1550 return false;
1553 if (!reader_->ReadUInt64(&frame->byte_offset)) {
1554 set_detailed_error("Unable to read window byte_offset.");
1555 return false;
1558 return true;
1561 bool QuicFramer::ProcessBlockedFrame(QuicBlockedFrame* frame) {
1562 if (!reader_->ReadUInt32(&frame->stream_id)) {
1563 set_detailed_error("Unable to read stream_id.");
1564 return false;
1567 return true;
1570 // static
1571 StringPiece QuicFramer::GetAssociatedDataFromEncryptedPacket(
1572 const QuicEncryptedPacket& encrypted,
1573 QuicConnectionIdLength connection_id_length,
1574 bool includes_version,
1575 QuicSequenceNumberLength sequence_number_length) {
1576 return StringPiece(
1577 encrypted.data() + kStartOfHashData, GetStartOfEncryptedData(
1578 connection_id_length, includes_version, sequence_number_length)
1579 - kStartOfHashData);
1582 void QuicFramer::SetDecrypter(QuicDecrypter* decrypter,
1583 EncryptionLevel level) {
1584 DCHECK(alternative_decrypter_.get() == nullptr);
1585 DCHECK_GE(level, decrypter_level_);
1586 decrypter_.reset(decrypter);
1587 decrypter_level_ = level;
1590 void QuicFramer::SetAlternativeDecrypter(QuicDecrypter* decrypter,
1591 EncryptionLevel level,
1592 bool latch_once_used) {
1593 alternative_decrypter_.reset(decrypter);
1594 alternative_decrypter_level_ = level;
1595 alternative_decrypter_latch_ = latch_once_used;
1598 const QuicDecrypter* QuicFramer::decrypter() const {
1599 return decrypter_.get();
1602 const QuicDecrypter* QuicFramer::alternative_decrypter() const {
1603 return alternative_decrypter_.get();
1606 void QuicFramer::SetEncrypter(EncryptionLevel level,
1607 QuicEncrypter* encrypter) {
1608 DCHECK_GE(level, 0);
1609 DCHECK_LT(level, NUM_ENCRYPTION_LEVELS);
1610 encrypter_[level].reset(encrypter);
1613 const QuicEncrypter* QuicFramer::encrypter(EncryptionLevel level) const {
1614 DCHECK_GE(level, 0);
1615 DCHECK_LT(level, NUM_ENCRYPTION_LEVELS);
1616 DCHECK(encrypter_[level].get() != nullptr);
1617 return encrypter_[level].get();
1620 QuicEncryptedPacket* QuicFramer::EncryptPacket(
1621 EncryptionLevel level,
1622 QuicPacketSequenceNumber packet_sequence_number,
1623 const QuicPacket& packet) {
1624 DCHECK(encrypter_[level].get() != nullptr);
1626 scoped_ptr<QuicData> out(encrypter_[level]->EncryptPacket(
1627 packet_sequence_number, packet.AssociatedData(), packet.Plaintext()));
1628 if (out.get() == nullptr) {
1629 RaiseError(QUIC_ENCRYPTION_FAILURE);
1630 return nullptr;
1632 StringPiece header_data = packet.BeforePlaintext();
1633 size_t len = header_data.length() + out->length();
1634 char* buffer = new char[len];
1635 // TODO(rch): eliminate this buffer copy by passing in a buffer to Encrypt().
1636 memcpy(buffer, header_data.data(), header_data.length());
1637 memcpy(buffer + header_data.length(), out->data(), out->length());
1638 return new QuicEncryptedPacket(buffer, len, true);
1641 size_t QuicFramer::GetMaxPlaintextSize(size_t ciphertext_size) {
1642 // In order to keep the code simple, we don't have the current encryption
1643 // level to hand. Both the NullEncrypter and AES-GCM have a tag length of 12.
1644 size_t min_plaintext_size = ciphertext_size;
1646 for (int i = ENCRYPTION_NONE; i < NUM_ENCRYPTION_LEVELS; i++) {
1647 if (encrypter_[i].get() != nullptr) {
1648 size_t size = encrypter_[i]->GetMaxPlaintextSize(ciphertext_size);
1649 if (size < min_plaintext_size) {
1650 min_plaintext_size = size;
1655 return min_plaintext_size;
1658 bool QuicFramer::DecryptPayload(const QuicPacketHeader& header,
1659 const QuicEncryptedPacket& packet) {
1660 StringPiece encrypted;
1661 if (!reader_->ReadStringPiece(&encrypted, reader_->BytesRemaining())) {
1662 return false;
1664 DCHECK(decrypter_.get() != nullptr);
1665 decrypted_.reset(decrypter_->DecryptPacket(
1666 header.packet_sequence_number,
1667 GetAssociatedDataFromEncryptedPacket(
1668 packet,
1669 header.public_header.connection_id_length,
1670 header.public_header.version_flag,
1671 header.public_header.sequence_number_length),
1672 encrypted));
1673 if (decrypted_.get() != nullptr) {
1674 visitor_->OnDecryptedPacket(decrypter_level_);
1675 } else if (alternative_decrypter_.get() != nullptr) {
1676 decrypted_.reset(alternative_decrypter_->DecryptPacket(
1677 header.packet_sequence_number,
1678 GetAssociatedDataFromEncryptedPacket(
1679 packet,
1680 header.public_header.connection_id_length,
1681 header.public_header.version_flag,
1682 header.public_header.sequence_number_length),
1683 encrypted));
1684 if (decrypted_.get() != nullptr) {
1685 visitor_->OnDecryptedPacket(alternative_decrypter_level_);
1686 if (alternative_decrypter_latch_) {
1687 // Switch to the alternative decrypter and latch so that we cannot
1688 // switch back.
1689 decrypter_.reset(alternative_decrypter_.release());
1690 decrypter_level_ = alternative_decrypter_level_;
1691 alternative_decrypter_level_ = ENCRYPTION_NONE;
1692 } else {
1693 // Switch the alternative decrypter so that we use it first next time.
1694 decrypter_.swap(alternative_decrypter_);
1695 EncryptionLevel level = alternative_decrypter_level_;
1696 alternative_decrypter_level_ = decrypter_level_;
1697 decrypter_level_ = level;
1702 if (decrypted_.get() == nullptr) {
1703 DLOG(WARNING) << "DecryptPacket failed for sequence_number:"
1704 << header.packet_sequence_number;
1705 return false;
1708 reader_.reset(new QuicDataReader(decrypted_->data(), decrypted_->length()));
1709 return true;
1712 size_t QuicFramer::GetAckFrameSize(
1713 const QuicAckFrame& ack,
1714 QuicSequenceNumberLength sequence_number_length) {
1715 AckFrameInfo ack_info = GetAckFrameInfo(ack);
1716 QuicSequenceNumberLength largest_observed_length =
1717 GetMinSequenceNumberLength(ack.largest_observed);
1718 QuicSequenceNumberLength missing_sequence_number_length =
1719 GetMinSequenceNumberLength(ack_info.max_delta);
1721 size_t ack_size = GetMinAckFrameSize(sequence_number_length,
1722 largest_observed_length);
1723 if (!ack_info.nack_ranges.empty()) {
1724 ack_size += kNumberOfNackRangesSize + kNumberOfRevivedPacketsSize;
1725 ack_size += min(ack_info.nack_ranges.size(), kMaxNackRanges) *
1726 (missing_sequence_number_length + PACKET_1BYTE_SEQUENCE_NUMBER);
1727 ack_size += min(ack.revived_packets.size(),
1728 kMaxRevivedPackets) * largest_observed_length;
1731 // In version 23, if the ack will be truncated due to too many nack ranges,
1732 // then do not include the number of timestamps (1 byte).
1733 if (ack_info.nack_ranges.size() <= kMaxNackRanges) {
1734 // 1 byte for the number of timestamps.
1735 ack_size += 1;
1736 if (ack.received_packet_times.size() > 0) {
1737 // 1 byte for sequence number, 4 bytes for timestamp for the first
1738 // packet.
1739 ack_size += 5;
1741 // 1 byte for sequence number, 2 bytes for timestamp for the other
1742 // packets.
1743 ack_size += 3 * (ack.received_packet_times.size() - 1);
1747 return ack_size;
1750 size_t QuicFramer::ComputeFrameLength(
1751 const QuicFrame& frame,
1752 bool last_frame_in_packet,
1753 InFecGroup is_in_fec_group,
1754 QuicSequenceNumberLength sequence_number_length) {
1755 switch (frame.type) {
1756 case STREAM_FRAME:
1757 return GetMinStreamFrameSize(frame.stream_frame->stream_id,
1758 frame.stream_frame->offset,
1759 last_frame_in_packet,
1760 is_in_fec_group) +
1761 frame.stream_frame->data.TotalBufferSize();
1762 case ACK_FRAME: {
1763 return GetAckFrameSize(*frame.ack_frame, sequence_number_length);
1765 case STOP_WAITING_FRAME:
1766 return GetStopWaitingFrameSize(sequence_number_length);
1767 case PING_FRAME:
1768 // Ping has no payload.
1769 return kQuicFrameTypeSize;
1770 case RST_STREAM_FRAME:
1771 return GetMinRstStreamFrameSize() +
1772 frame.rst_stream_frame->error_details.size();
1773 case CONNECTION_CLOSE_FRAME:
1774 return GetMinConnectionCloseFrameSize() +
1775 frame.connection_close_frame->error_details.size();
1776 case GOAWAY_FRAME:
1777 return GetMinGoAwayFrameSize() + frame.goaway_frame->reason_phrase.size();
1778 case WINDOW_UPDATE_FRAME:
1779 return GetWindowUpdateFrameSize();
1780 case BLOCKED_FRAME:
1781 return GetBlockedFrameSize();
1782 case PADDING_FRAME:
1783 DCHECK(false);
1784 return 0;
1785 case NUM_FRAME_TYPES:
1786 DCHECK(false);
1787 return 0;
1790 // Not reachable, but some Chrome compilers can't figure that out. *sigh*
1791 DCHECK(false);
1792 return 0;
1795 bool QuicFramer::AppendTypeByte(const QuicFrame& frame,
1796 bool no_stream_frame_length,
1797 QuicDataWriter* writer) {
1798 uint8 type_byte = 0;
1799 switch (frame.type) {
1800 case STREAM_FRAME: {
1801 if (frame.stream_frame == nullptr) {
1802 LOG(DFATAL) << "Failed to append STREAM frame with no stream_frame.";
1804 // Fin bit.
1805 type_byte |= frame.stream_frame->fin ? kQuicStreamFinMask : 0;
1807 // Data Length bit.
1808 type_byte <<= kQuicStreamDataLengthShift;
1809 type_byte |= no_stream_frame_length ? 0: kQuicStreamDataLengthMask;
1811 // Offset 3 bits.
1812 type_byte <<= kQuicStreamOffsetShift;
1813 const size_t offset_len = GetStreamOffsetSize(frame.stream_frame->offset);
1814 if (offset_len > 0) {
1815 type_byte |= offset_len - 1;
1818 // stream id 2 bits.
1819 type_byte <<= kQuicStreamIdShift;
1820 type_byte |= GetStreamIdSize(frame.stream_frame->stream_id) - 1;
1821 type_byte |= kQuicFrameTypeStreamMask; // Set Stream Frame Type to 1.
1822 break;
1824 case ACK_FRAME:
1825 return true;
1826 default:
1827 type_byte = static_cast<uint8>(frame.type);
1828 break;
1831 return writer->WriteUInt8(type_byte);
1834 // static
1835 bool QuicFramer::AppendPacketSequenceNumber(
1836 QuicSequenceNumberLength sequence_number_length,
1837 QuicPacketSequenceNumber packet_sequence_number,
1838 QuicDataWriter* writer) {
1839 // Ensure the entire sequence number can be written.
1840 if (writer->capacity() - writer->length() <
1841 static_cast<size_t>(sequence_number_length)) {
1842 return false;
1844 switch (sequence_number_length) {
1845 case PACKET_1BYTE_SEQUENCE_NUMBER:
1846 return writer->WriteUInt8(
1847 packet_sequence_number & k1ByteSequenceNumberMask);
1848 break;
1849 case PACKET_2BYTE_SEQUENCE_NUMBER:
1850 return writer->WriteUInt16(
1851 packet_sequence_number & k2ByteSequenceNumberMask);
1852 break;
1853 case PACKET_4BYTE_SEQUENCE_NUMBER:
1854 return writer->WriteUInt32(
1855 packet_sequence_number & k4ByteSequenceNumberMask);
1856 break;
1857 case PACKET_6BYTE_SEQUENCE_NUMBER:
1858 return writer->WriteUInt48(
1859 packet_sequence_number & k6ByteSequenceNumberMask);
1860 break;
1861 default:
1862 DCHECK(false) << "sequence_number_length: " << sequence_number_length;
1863 return false;
1867 bool QuicFramer::AppendStreamFrame(
1868 const QuicStreamFrame& frame,
1869 bool no_stream_frame_length,
1870 QuicDataWriter* writer) {
1871 if (!writer->WriteBytes(&frame.stream_id, GetStreamIdSize(frame.stream_id))) {
1872 LOG(DFATAL) << "Writing stream id size failed.";
1873 return false;
1875 if (!writer->WriteBytes(&frame.offset, GetStreamOffsetSize(frame.offset))) {
1876 LOG(DFATAL) << "Writing offset size failed.";
1877 return false;
1879 if (!no_stream_frame_length) {
1880 if ((frame.data.TotalBufferSize() > numeric_limits<uint16>::max()) ||
1881 !writer->WriteUInt16(
1882 static_cast<uint16>(frame.data.TotalBufferSize()))) {
1883 LOG(DFATAL) << "Writing stream frame length failed";
1884 return false;
1888 if (!writer->WriteIOVector(frame.data)) {
1889 LOG(DFATAL) << "Writing frame data failed.";
1890 return false;
1892 return true;
1895 // static
1896 void QuicFramer::set_version(const QuicVersion version) {
1897 DCHECK(IsSupportedVersion(version)) << QuicVersionToString(version);
1898 quic_version_ = version;
1901 bool QuicFramer::AppendAckFrameAndTypeByte(
1902 const QuicPacketHeader& header,
1903 const QuicAckFrame& frame,
1904 QuicDataWriter* writer) {
1905 AckFrameInfo ack_info = GetAckFrameInfo(frame);
1906 QuicPacketSequenceNumber ack_largest_observed = frame.largest_observed;
1907 QuicSequenceNumberLength largest_observed_length =
1908 GetMinSequenceNumberLength(ack_largest_observed);
1909 QuicSequenceNumberLength missing_sequence_number_length =
1910 GetMinSequenceNumberLength(ack_info.max_delta);
1911 // Determine whether we need to truncate ranges.
1912 size_t available_range_bytes = writer->capacity() - writer->length() -
1913 kNumberOfRevivedPacketsSize - kNumberOfNackRangesSize -
1914 GetMinAckFrameSize(header.public_header.sequence_number_length,
1915 largest_observed_length);
1916 size_t max_num_ranges = available_range_bytes /
1917 (missing_sequence_number_length + PACKET_1BYTE_SEQUENCE_NUMBER);
1918 max_num_ranges = min(kMaxNackRanges, max_num_ranges);
1919 bool truncated = ack_info.nack_ranges.size() > max_num_ranges;
1920 DVLOG_IF(1, truncated) << "Truncating ack from "
1921 << ack_info.nack_ranges.size() << " ranges to "
1922 << max_num_ranges;
1923 // Write out the type byte by setting the low order bits and doing shifts
1924 // to make room for the next bit flags to be set.
1925 // Whether there are any nacks.
1926 uint8 type_byte = ack_info.nack_ranges.empty() ? 0 : kQuicHasNacksMask;
1928 // truncating bit.
1929 type_byte <<= kQuicAckTruncatedShift;
1930 type_byte |= truncated ? kQuicAckTruncatedMask : 0;
1932 // Largest observed sequence number length.
1933 type_byte <<= kQuicSequenceNumberLengthShift;
1934 type_byte |= GetSequenceNumberFlags(largest_observed_length);
1936 // Missing sequence number length.
1937 type_byte <<= kQuicSequenceNumberLengthShift;
1938 type_byte |= GetSequenceNumberFlags(missing_sequence_number_length);
1940 type_byte |= kQuicFrameTypeAckMask;
1942 if (!writer->WriteUInt8(type_byte)) {
1943 return false;
1946 QuicPacketEntropyHash ack_entropy_hash = frame.entropy_hash;
1947 NackRangeMap::reverse_iterator ack_iter = ack_info.nack_ranges.rbegin();
1948 if (truncated) {
1949 // Skip the nack ranges which the truncated ack won't include and set
1950 // a correct largest observed for the truncated ack.
1951 for (size_t i = 1; i < (ack_info.nack_ranges.size() - max_num_ranges);
1952 ++i) {
1953 ++ack_iter;
1955 // If the last range is followed by acks, include them.
1956 // If the last range is followed by another range, specify the end of the
1957 // range as the largest_observed.
1958 ack_largest_observed = ack_iter->first - 1;
1959 // Also update the entropy so it matches the largest observed.
1960 ack_entropy_hash = entropy_calculator_->EntropyHash(ack_largest_observed);
1961 ++ack_iter;
1964 if (!writer->WriteUInt8(ack_entropy_hash)) {
1965 return false;
1968 if (!AppendPacketSequenceNumber(largest_observed_length,
1969 ack_largest_observed, writer)) {
1970 return false;
1973 uint64 delta_time_largest_observed_us = kUFloat16MaxValue;
1974 if (!frame.delta_time_largest_observed.IsInfinite()) {
1975 DCHECK_LE(0u, frame.delta_time_largest_observed.ToMicroseconds());
1976 delta_time_largest_observed_us =
1977 frame.delta_time_largest_observed.ToMicroseconds();
1980 if (!writer->WriteUFloat16(delta_time_largest_observed_us)) {
1981 return false;
1984 // Timestamp goes at the end of the required fields.
1985 if (!truncated) {
1986 if (!AppendTimestampToAckFrame(frame, writer)) {
1987 return false;
1991 if (ack_info.nack_ranges.empty()) {
1992 return true;
1995 const uint8 num_missing_ranges =
1996 static_cast<uint8>(min(ack_info.nack_ranges.size(), max_num_ranges));
1997 if (!writer->WriteBytes(&num_missing_ranges, 1)) {
1998 return false;
2001 int num_ranges_written = 0;
2002 QuicPacketSequenceNumber last_sequence_written = ack_largest_observed;
2003 for (; ack_iter != ack_info.nack_ranges.rend(); ++ack_iter) {
2004 // Calculate the delta to the last number in the range.
2005 QuicPacketSequenceNumber missing_delta =
2006 last_sequence_written - (ack_iter->first + ack_iter->second);
2007 if (!AppendPacketSequenceNumber(missing_sequence_number_length,
2008 missing_delta, writer)) {
2009 return false;
2011 if (!AppendPacketSequenceNumber(PACKET_1BYTE_SEQUENCE_NUMBER,
2012 ack_iter->second, writer)) {
2013 return false;
2015 // Subtract 1 so a missing_delta of 0 means an adjacent range.
2016 last_sequence_written = ack_iter->first - 1;
2017 ++num_ranges_written;
2019 DCHECK_EQ(num_missing_ranges, num_ranges_written);
2021 // Append revived packets.
2022 // If not all the revived packets fit, only mention the ones that do.
2023 uint8 num_revived_packets =
2024 static_cast<uint8>(min(frame.revived_packets.size(), kMaxRevivedPackets));
2025 num_revived_packets = static_cast<uint8>(min(
2026 static_cast<size_t>(num_revived_packets),
2027 (writer->capacity() - writer->length()) / largest_observed_length));
2028 if (!writer->WriteBytes(&num_revived_packets, 1)) {
2029 return false;
2032 SequenceNumberSet::const_iterator iter = frame.revived_packets.begin();
2033 for (int i = 0; i < num_revived_packets; ++i, ++iter) {
2034 LOG_IF(DFATAL, !ContainsKey(frame.missing_packets, *iter));
2035 if (!AppendPacketSequenceNumber(largest_observed_length,
2036 *iter, writer)) {
2037 return false;
2041 return true;
2044 bool QuicFramer::AppendTimestampToAckFrame(const QuicAckFrame& frame,
2045 QuicDataWriter* writer) {
2046 DCHECK_GE(version(), QUIC_VERSION_23);
2047 DCHECK_GE(numeric_limits<uint8>::max(), frame.received_packet_times.size());
2048 // num_received_packets is only 1 byte.
2049 if (frame.received_packet_times.size() > numeric_limits<uint8>::max()) {
2050 return false;
2053 uint8 num_received_packets = frame.received_packet_times.size();
2055 if (!writer->WriteBytes(&num_received_packets, 1)) {
2056 return false;
2058 if (num_received_packets == 0) {
2059 return true;
2062 PacketTimeList::const_iterator it = frame.received_packet_times.begin();
2063 QuicPacketSequenceNumber sequence_number = it->first;
2064 QuicPacketSequenceNumber delta_from_largest_observed =
2065 frame.largest_observed - sequence_number;
2067 DCHECK_GE(numeric_limits<uint8>::max(), delta_from_largest_observed);
2068 if (delta_from_largest_observed > numeric_limits<uint8>::max()) {
2069 return false;
2072 if (!writer->WriteUInt8(
2073 delta_from_largest_observed & k1ByteSequenceNumberMask)) {
2074 return false;
2077 // Use the lowest 4 bytes of the time delta from the creation_time_.
2078 const uint64 time_epoch_delta_us = GG_UINT64_C(1) << 32;
2079 uint32 time_delta_us =
2080 static_cast<uint32>(it->second.Subtract(creation_time_).ToMicroseconds()
2081 & (time_epoch_delta_us - 1));
2082 if (!writer->WriteBytes(&time_delta_us, sizeof(time_delta_us))) {
2083 return false;
2086 QuicTime prev_time = it->second;
2088 for (++it; it != frame.received_packet_times.end(); ++it) {
2089 sequence_number = it->first;
2090 delta_from_largest_observed = frame.largest_observed - sequence_number;
2092 if (delta_from_largest_observed > numeric_limits<uint8>::max()) {
2093 return false;
2096 if (!writer->WriteUInt8(
2097 delta_from_largest_observed & k1ByteSequenceNumberMask)) {
2098 return false;
2101 uint64 time_delta_us = it->second.Subtract(prev_time).ToMicroseconds();
2102 prev_time = it->second;
2103 if (!writer->WriteUFloat16(time_delta_us)) {
2104 return false;
2107 return true;
2110 bool QuicFramer::AppendStopWaitingFrame(
2111 const QuicPacketHeader& header,
2112 const QuicStopWaitingFrame& frame,
2113 QuicDataWriter* writer) {
2114 DCHECK_GE(header.packet_sequence_number, frame.least_unacked);
2115 const QuicPacketSequenceNumber least_unacked_delta =
2116 header.packet_sequence_number - frame.least_unacked;
2117 const QuicPacketSequenceNumber length_shift =
2118 header.public_header.sequence_number_length * 8;
2119 if (!writer->WriteUInt8(frame.entropy_hash)) {
2120 LOG(DFATAL) << " hash failed";
2121 return false;
2124 if (least_unacked_delta >> length_shift > 0) {
2125 LOG(DFATAL) << "sequence_number_length "
2126 << header.public_header.sequence_number_length
2127 << " is too small for least_unacked_delta: "
2128 << least_unacked_delta;
2129 return false;
2131 if (!AppendPacketSequenceNumber(header.public_header.sequence_number_length,
2132 least_unacked_delta, writer)) {
2133 LOG(DFATAL) << " seq failed: "
2134 << header.public_header.sequence_number_length;
2135 return false;
2138 return true;
2141 bool QuicFramer::AppendRstStreamFrame(
2142 const QuicRstStreamFrame& frame,
2143 QuicDataWriter* writer) {
2144 if (!writer->WriteUInt32(frame.stream_id)) {
2145 return false;
2148 if (!writer->WriteUInt64(frame.byte_offset)) {
2149 return false;
2152 uint32 error_code = static_cast<uint32>(frame.error_code);
2153 if (!writer->WriteUInt32(error_code)) {
2154 return false;
2157 if (!writer->WriteStringPiece16(frame.error_details)) {
2158 return false;
2160 return true;
2163 bool QuicFramer::AppendConnectionCloseFrame(
2164 const QuicConnectionCloseFrame& frame,
2165 QuicDataWriter* writer) {
2166 uint32 error_code = static_cast<uint32>(frame.error_code);
2167 if (!writer->WriteUInt32(error_code)) {
2168 return false;
2170 if (!writer->WriteStringPiece16(frame.error_details)) {
2171 return false;
2173 return true;
2176 bool QuicFramer::AppendGoAwayFrame(const QuicGoAwayFrame& frame,
2177 QuicDataWriter* writer) {
2178 uint32 error_code = static_cast<uint32>(frame.error_code);
2179 if (!writer->WriteUInt32(error_code)) {
2180 return false;
2182 uint32 stream_id = static_cast<uint32>(frame.last_good_stream_id);
2183 if (!writer->WriteUInt32(stream_id)) {
2184 return false;
2186 if (!writer->WriteStringPiece16(frame.reason_phrase)) {
2187 return false;
2189 return true;
2192 bool QuicFramer::AppendWindowUpdateFrame(const QuicWindowUpdateFrame& frame,
2193 QuicDataWriter* writer) {
2194 uint32 stream_id = static_cast<uint32>(frame.stream_id);
2195 if (!writer->WriteUInt32(stream_id)) {
2196 return false;
2198 if (!writer->WriteUInt64(frame.byte_offset)) {
2199 return false;
2201 return true;
2204 bool QuicFramer::AppendBlockedFrame(const QuicBlockedFrame& frame,
2205 QuicDataWriter* writer) {
2206 uint32 stream_id = static_cast<uint32>(frame.stream_id);
2207 if (!writer->WriteUInt32(stream_id)) {
2208 return false;
2210 return true;
2213 bool QuicFramer::RaiseError(QuicErrorCode error) {
2214 DVLOG(1) << "Error detail: " << detailed_error_;
2215 set_error(error);
2216 visitor_->OnError(this);
2217 reader_.reset(nullptr);
2218 return false;
2221 } // namespace net