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. 4 5 #include "net/quic/quic_framer.h" 6 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" 18 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; 26 27 namespace net { 28 29 namespace { 30 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); 40 41 const QuicConnectionId k1ByteConnectionIdMask = GG_UINT64_C(0x00000000000000FF); 42 const QuicConnectionId k4ByteConnectionIdMask = GG_UINT64_C(0x00000000FFFFFFFF); 43 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; 47 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. 51 // 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) 60 // 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 65 // CongestionFeedback : 0b 001xxxxx 66 // 67 // Semantics of the flag bits above (the x bits) depends on the frame type. 68 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; 74 const uint8 kQuicFrameTypeCongestionFeedbackMask = 0x20; 75 76 // Stream frame relative shifts and masks for interpreting the stream flags. 77 // StreamID may be 1, 2, 3, or 4 bytes. 78 const uint8 kQuicStreamIdShift = 2; 79 const uint8 kQuicStreamIDLengthMask = 0x03; 80 81 // Offset may be 0, 2, 3, 4, 5, 6, 7, 8 bytes. 82 const uint8 kQuicStreamOffsetShift = 3; 83 const uint8 kQuicStreamOffsetMask = 0x07; 84 85 // Data length may be 0 or 2 bytes. 86 const uint8 kQuicStreamDataLengthShift = 1; 87 const uint8 kQuicStreamDataLengthMask = 0x01; 88 89 // Fin bit may be set or not. 90 const uint8 kQuicStreamFinShift = 1; 91 const uint8 kQuicStreamFinMask = 0x01; 92 93 // Sequence number size shift used in AckFrames. 94 const uint8 kQuicSequenceNumberLengthShift = 2; 95 96 // Acks may be truncated. 97 const uint8 kQuicAckTruncatedShift = 1; 98 const uint8 kQuicAckTruncatedMask = 0x01; 99 100 // Acks may not have any nacks. 101 const uint8 kQuicHasNacksMask = 0x01; 102 103 // Returns the absolute value of the difference between |a| and |b|. 104 QuicPacketSequenceNumber Delta(QuicPacketSequenceNumber a, 105 QuicPacketSequenceNumber b) { 106 // Since these are unsigned numbers, we can't just return abs(a - b) 107 if (a < b) { 108 return b - a; 109 } 110 return a - b; 111 } 112 113 QuicPacketSequenceNumber ClosestTo(QuicPacketSequenceNumber target, 114 QuicPacketSequenceNumber a, 115 QuicPacketSequenceNumber b) { 116 return (Delta(target, a) < Delta(target, b)) ? a : b; 117 } 118 119 QuicSequenceNumberLength ReadSequenceNumberLength(uint8 flags) { 120 switch (flags & PACKET_FLAGS_6BYTE_SEQUENCE) { 121 case PACKET_FLAGS_6BYTE_SEQUENCE: 122 return PACKET_6BYTE_SEQUENCE_NUMBER; 123 case PACKET_FLAGS_4BYTE_SEQUENCE: 124 return PACKET_4BYTE_SEQUENCE_NUMBER; 125 case PACKET_FLAGS_2BYTE_SEQUENCE: 126 return PACKET_2BYTE_SEQUENCE_NUMBER; 127 case PACKET_FLAGS_1BYTE_SEQUENCE: 128 return PACKET_1BYTE_SEQUENCE_NUMBER; 129 default: 130 LOG(DFATAL) << "Unreachable case statement."; 131 return PACKET_6BYTE_SEQUENCE_NUMBER; 132 } 133 } 134 135 } // namespace 136 137 bool QuicFramerVisitorInterface::OnWindowUpdateFrame( 138 const QuicWindowUpdateFrame& frame) { 139 return true; 140 } 141 142 bool QuicFramerVisitorInterface::OnBlockedFrame(const QuicBlockedFrame& frame) { 143 return true; 144 } 145 146 QuicFramer::QuicFramer(const QuicVersionVector& supported_versions, 147 QuicTime creation_time, 148 bool is_server) 149 : visitor_(NULL), 150 fec_builder_(NULL), 151 entropy_calculator_(NULL), 152 error_(QUIC_NO_ERROR), 153 last_sequence_number_(0), 154 last_serialized_connection_id_(0), 155 supported_versions_(supported_versions), 156 decrypter_level_(ENCRYPTION_NONE), 157 alternative_decrypter_level_(ENCRYPTION_NONE), 158 alternative_decrypter_latch_(false), 159 is_server_(is_server), 160 validate_flags_(true), 161 creation_time_(creation_time), 162 last_timestamp_(QuicTime::Delta::Zero()) { 163 DCHECK(!supported_versions.empty()); 164 quic_version_ = supported_versions_[0]; 165 decrypter_.reset(QuicDecrypter::Create(kNULL)); 166 encrypter_[ENCRYPTION_NONE].reset( 167 QuicEncrypter::Create(kNULL)); 168 } 169 170 QuicFramer::~QuicFramer() {} 171 172 // static 173 size_t QuicFramer::GetMinStreamFrameSize(QuicStreamId stream_id, 174 QuicStreamOffset offset, 175 bool last_frame_in_packet, 176 InFecGroup is_in_fec_group) { 177 bool no_stream_frame_length = last_frame_in_packet && 178 is_in_fec_group == NOT_IN_FEC_GROUP; 179 return kQuicFrameTypeSize + GetStreamIdSize(stream_id) + 180 GetStreamOffsetSize(offset) + 181 (no_stream_frame_length ? 0 : kQuicStreamPayloadLengthSize); 182 } 183 184 // static 185 size_t QuicFramer::GetMinAckFrameSize( 186 QuicSequenceNumberLength sequence_number_length, 187 QuicSequenceNumberLength largest_observed_length) { 188 return kQuicFrameTypeSize + kQuicEntropyHashSize + 189 largest_observed_length + kQuicDeltaTimeLargestObservedSize; 190 } 191 192 // static 193 size_t QuicFramer::GetStopWaitingFrameSize( 194 QuicSequenceNumberLength sequence_number_length) { 195 return kQuicFrameTypeSize + kQuicEntropyHashSize + 196 sequence_number_length; 197 } 198 199 // static 200 size_t QuicFramer::GetMinRstStreamFrameSize() { 201 return kQuicFrameTypeSize + kQuicMaxStreamIdSize + 202 kQuicMaxStreamOffsetSize + kQuicErrorCodeSize + 203 kQuicErrorDetailsLengthSize; 204 } 205 206 // static 207 size_t QuicFramer::GetMinConnectionCloseFrameSize() { 208 return kQuicFrameTypeSize + kQuicErrorCodeSize + kQuicErrorDetailsLengthSize; 209 } 210 211 // static 212 size_t QuicFramer::GetMinGoAwayFrameSize() { 213 return kQuicFrameTypeSize + kQuicErrorCodeSize + kQuicErrorDetailsLengthSize + 214 kQuicMaxStreamIdSize; 215 } 216 217 // static 218 size_t QuicFramer::GetWindowUpdateFrameSize() { 219 return kQuicFrameTypeSize + kQuicMaxStreamIdSize + kQuicMaxStreamOffsetSize; 220 } 221 222 // static 223 size_t QuicFramer::GetBlockedFrameSize() { 224 return kQuicFrameTypeSize + kQuicMaxStreamIdSize; 225 } 226 227 // static 228 size_t QuicFramer::GetStreamIdSize(QuicStreamId stream_id) { 229 // Sizes are 1 through 4 bytes. 230 for (int i = 1; i <= 4; ++i) { 231 stream_id >>= 8; 232 if (stream_id == 0) { 233 return i; 234 } 235 } 236 LOG(DFATAL) << "Failed to determine StreamIDSize."; 237 return 4; 238 } 239 240 // static 241 size_t QuicFramer::GetStreamOffsetSize(QuicStreamOffset offset) { 242 // 0 is a special case. 243 if (offset == 0) { 244 return 0; 245 } 246 // 2 through 8 are the remaining sizes. 247 offset >>= 8; 248 for (int i = 2; i <= 8; ++i) { 249 offset >>= 8; 250 if (offset == 0) { 251 return i; 252 } 253 } 254 LOG(DFATAL) << "Failed to determine StreamOffsetSize."; 255 return 8; 256 } 257 258 // static 259 size_t QuicFramer::GetVersionNegotiationPacketSize(size_t number_versions) { 260 return kPublicFlagsSize + PACKET_8BYTE_CONNECTION_ID + 261 number_versions * kQuicVersionSize; 262 } 263 264 bool QuicFramer::IsSupportedVersion(const QuicVersion version) const { 265 for (size_t i = 0; i < supported_versions_.size(); ++i) { 266 if (version == supported_versions_[i]) { 267 return true; 268 } 269 } 270 return false; 271 } 272 273 size_t QuicFramer::GetSerializedFrameLength( 274 const QuicFrame& frame, 275 size_t free_bytes, 276 bool first_frame, 277 bool last_frame, 278 InFecGroup is_in_fec_group, 279 QuicSequenceNumberLength sequence_number_length) { 280 if (frame.type == PADDING_FRAME) { 281 // PADDING implies end of packet. 282 return free_bytes; 283 } 284 size_t frame_len = 285 ComputeFrameLength(frame, last_frame, is_in_fec_group, 286 sequence_number_length); 287 if (frame_len <= free_bytes) { 288 // Frame fits within packet. Note that acks may be truncated. 289 return frame_len; 290 } 291 // Only truncate the first frame in a packet, so if subsequent ones go 292 // over, stop including more frames. 293 if (!first_frame) { 294 return 0; 295 } 296 bool can_truncate = frame.type == ACK_FRAME && 297 free_bytes >= GetMinAckFrameSize(PACKET_6BYTE_SEQUENCE_NUMBER, 298 PACKET_6BYTE_SEQUENCE_NUMBER); 299 if (can_truncate) { 300 // Truncate the frame so the packet will not exceed kMaxPacketSize. 301 // Note that we may not use every byte of the writer in this case. 302 DVLOG(1) << "Truncating large frame, free bytes: " << free_bytes; 303 return free_bytes; 304 } 305 if (!FLAGS_quic_allow_oversized_packets_for_test) { 306 return 0; 307 } 308 LOG(DFATAL) << "Packet size too small to fit frame."; 309 return frame_len; 310 } 311 312 QuicFramer::AckFrameInfo::AckFrameInfo() : max_delta(0) {} 313 314 QuicFramer::AckFrameInfo::~AckFrameInfo() {} 315 316 QuicPacketEntropyHash QuicFramer::GetPacketEntropyHash( 317 const QuicPacketHeader& header) const { 318 return header.entropy_flag << (header.packet_sequence_number % 8); 319 } 320 321 SerializedPacket QuicFramer::BuildDataPacket( 322 const QuicPacketHeader& header, 323 const QuicFrames& frames, 324 size_t packet_size) { 325 QuicDataWriter writer(packet_size); 326 const SerializedPacket kNoPacket( 327 0, PACKET_1BYTE_SEQUENCE_NUMBER, NULL, 0, NULL); 328 if (!AppendPacketHeader(header, &writer)) { 329 LOG(DFATAL) << "AppendPacketHeader failed"; 330 return kNoPacket; 331 } 332 333 for (size_t i = 0; i < frames.size(); ++i) { 334 const QuicFrame& frame = frames[i]; 335 336 // Determine if we should write stream frame length in header. 337 const bool no_stream_frame_length = 338 (header.is_in_fec_group == NOT_IN_FEC_GROUP) && 339 (i == frames.size() - 1); 340 if (!AppendTypeByte(frame, no_stream_frame_length, &writer)) { 341 LOG(DFATAL) << "AppendTypeByte failed"; 342 return kNoPacket; 343 } 344 345 switch (frame.type) { 346 case PADDING_FRAME: 347 writer.WritePadding(); 348 break; 349 case STREAM_FRAME: 350 if (!AppendStreamFrame( 351 *frame.stream_frame, no_stream_frame_length, &writer)) { 352 LOG(DFATAL) << "AppendStreamFrame failed"; 353 return kNoPacket; 354 } 355 break; 356 case ACK_FRAME: 357 if (!AppendAckFrameAndTypeByte( 358 header, *frame.ack_frame, &writer)) { 359 LOG(DFATAL) << "AppendAckFrameAndTypeByte failed"; 360 return kNoPacket; 361 } 362 break; 363 case CONGESTION_FEEDBACK_FRAME: 364 if (!AppendCongestionFeedbackFrame( 365 *frame.congestion_feedback_frame, &writer)) { 366 LOG(DFATAL) << "AppendCongestionFeedbackFrame failed"; 367 return kNoPacket; 368 } 369 break; 370 case STOP_WAITING_FRAME: 371 if (!AppendStopWaitingFrame( 372 header, *frame.stop_waiting_frame, &writer)) { 373 LOG(DFATAL) << "AppendStopWaitingFrame failed"; 374 return kNoPacket; 375 } 376 break; 377 case PING_FRAME: 378 if (quic_version_ == QUIC_VERSION_16) { 379 LOG(DFATAL) << "Attempt to add a PingFrame in " 380 << QuicVersionToString(quic_version_); 381 return kNoPacket; 382 } 383 // Ping has no payload. 384 break; 385 case RST_STREAM_FRAME: 386 if (!AppendRstStreamFrame(*frame.rst_stream_frame, &writer)) { 387 LOG(DFATAL) << "AppendRstStreamFrame failed"; 388 return kNoPacket; 389 } 390 break; 391 case CONNECTION_CLOSE_FRAME: 392 if (!AppendConnectionCloseFrame( 393 *frame.connection_close_frame, &writer)) { 394 LOG(DFATAL) << "AppendConnectionCloseFrame failed"; 395 return kNoPacket; 396 } 397 break; 398 case GOAWAY_FRAME: 399 if (!AppendGoAwayFrame(*frame.goaway_frame, &writer)) { 400 LOG(DFATAL) << "AppendGoAwayFrame failed"; 401 return kNoPacket; 402 } 403 break; 404 case WINDOW_UPDATE_FRAME: 405 if (!AppendWindowUpdateFrame(*frame.window_update_frame, &writer)) { 406 LOG(DFATAL) << "AppendWindowUpdateFrame failed"; 407 return kNoPacket; 408 } 409 break; 410 case BLOCKED_FRAME: 411 if (!AppendBlockedFrame(*frame.blocked_frame, &writer)) { 412 LOG(DFATAL) << "AppendBlockedFrame failed"; 413 return kNoPacket; 414 } 415 break; 416 default: 417 RaiseError(QUIC_INVALID_FRAME_DATA); 418 LOG(DFATAL) << "QUIC_INVALID_FRAME_DATA"; 419 return kNoPacket; 420 } 421 } 422 423 // Save the length before writing, because take clears it. 424 const size_t len = writer.length(); 425 // Less than or equal because truncated acks end up with max_plaintex_size 426 // length, even though they're typically slightly shorter. 427 DCHECK_LE(len, packet_size); 428 QuicPacket* packet = QuicPacket::NewDataPacket( 429 writer.take(), len, true, header.public_header.connection_id_length, 430 header.public_header.version_flag, 431 header.public_header.sequence_number_length); 432 433 if (fec_builder_) { 434 fec_builder_->OnBuiltFecProtectedPayload(header, 435 packet->FecProtectedData()); 436 } 437 438 return SerializedPacket(header.packet_sequence_number, 439 header.public_header.sequence_number_length, packet, 440 GetPacketEntropyHash(header), NULL); 441 } 442 443 SerializedPacket QuicFramer::BuildFecPacket(const QuicPacketHeader& header, 444 const QuicFecData& fec) { 445 DCHECK_EQ(IN_FEC_GROUP, header.is_in_fec_group); 446 DCHECK_NE(0u, header.fec_group); 447 size_t len = GetPacketHeaderSize(header); 448 len += fec.redundancy.length(); 449 450 QuicDataWriter writer(len); 451 const SerializedPacket kNoPacket( 452 0, PACKET_1BYTE_SEQUENCE_NUMBER, NULL, 0, NULL); 453 if (!AppendPacketHeader(header, &writer)) { 454 LOG(DFATAL) << "AppendPacketHeader failed"; 455 return kNoPacket; 456 } 457 458 if (!writer.WriteBytes(fec.redundancy.data(), fec.redundancy.length())) { 459 LOG(DFATAL) << "Failed to add FEC"; 460 return kNoPacket; 461 } 462 463 return SerializedPacket( 464 header.packet_sequence_number, 465 header.public_header.sequence_number_length, 466 QuicPacket::NewFecPacket(writer.take(), len, true, 467 header.public_header.connection_id_length, 468 header.public_header.version_flag, 469 header.public_header.sequence_number_length), 470 GetPacketEntropyHash(header), NULL); 471 } 472 473 // static 474 QuicEncryptedPacket* QuicFramer::BuildPublicResetPacket( 475 const QuicPublicResetPacket& packet) { 476 DCHECK(packet.public_header.reset_flag); 477 478 CryptoHandshakeMessage reset; 479 reset.set_tag(kPRST); 480 reset.SetValue(kRNON, packet.nonce_proof); 481 reset.SetValue(kRSEQ, packet.rejected_sequence_number); 482 if (!packet.client_address.address().empty()) { 483 // packet.client_address is non-empty. 484 QuicSocketAddressCoder address_coder(packet.client_address); 485 string serialized_address = address_coder.Encode(); 486 if (serialized_address.empty()) { 487 return NULL; 488 } 489 reset.SetStringPiece(kCADR, serialized_address); 490 } 491 const QuicData& reset_serialized = reset.GetSerialized(); 492 493 size_t len = 494 kPublicFlagsSize + PACKET_8BYTE_CONNECTION_ID + reset_serialized.length(); 495 QuicDataWriter writer(len); 496 497 uint8 flags = static_cast<uint8>(PACKET_PUBLIC_FLAGS_RST | 498 PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID); 499 if (!writer.WriteUInt8(flags)) { 500 return NULL; 501 } 502 503 if (!writer.WriteUInt64(packet.public_header.connection_id)) { 504 return NULL; 505 } 506 507 if (!writer.WriteBytes(reset_serialized.data(), reset_serialized.length())) { 508 return NULL; 509 } 510 511 return new QuicEncryptedPacket(writer.take(), len, true); 512 } 513 514 QuicEncryptedPacket* QuicFramer::BuildVersionNegotiationPacket( 515 const QuicPacketPublicHeader& header, 516 const QuicVersionVector& supported_versions) { 517 DCHECK(header.version_flag); 518 size_t len = GetVersionNegotiationPacketSize(supported_versions.size()); 519 QuicDataWriter writer(len); 520 521 uint8 flags = static_cast<uint8>(PACKET_PUBLIC_FLAGS_VERSION | 522 PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID); 523 if (!writer.WriteUInt8(flags)) { 524 return NULL; 525 } 526 527 if (!writer.WriteUInt64(header.connection_id)) { 528 return NULL; 529 } 530 531 for (size_t i = 0; i < supported_versions.size(); ++i) { 532 if (!writer.WriteUInt32(QuicVersionToQuicTag(supported_versions[i]))) { 533 return NULL; 534 } 535 } 536 537 return new QuicEncryptedPacket(writer.take(), len, true); 538 } 539 540 bool QuicFramer::ProcessPacket(const QuicEncryptedPacket& packet) { 541 DCHECK(!reader_.get()); 542 reader_.reset(new QuicDataReader(packet.data(), packet.length())); 543 544 visitor_->OnPacket(); 545 546 // First parse the public header. 547 QuicPacketPublicHeader public_header; 548 if (!ProcessPublicHeader(&public_header)) { 549 DLOG(WARNING) << "Unable to process public header."; 550 DCHECK_NE("", detailed_error_); 551 return RaiseError(QUIC_INVALID_PACKET_HEADER); 552 } 553 554 if (!visitor_->OnUnauthenticatedPublicHeader(public_header)) { 555 // The visitor suppresses further processing of the packet. 556 reader_.reset(NULL); 557 return true; 558 } 559 560 if (is_server_ && public_header.version_flag && 561 public_header.versions[0] != quic_version_) { 562 if (!visitor_->OnProtocolVersionMismatch(public_header.versions[0])) { 563 reader_.reset(NULL); 564 return true; 565 } 566 } 567 568 bool rv; 569 if (!is_server_ && public_header.version_flag) { 570 rv = ProcessVersionNegotiationPacket(&public_header); 571 } else if (public_header.reset_flag) { 572 rv = ProcessPublicResetPacket(public_header); 573 } else { 574 rv = ProcessDataPacket(public_header, packet); 575 } 576 577 reader_.reset(NULL); 578 return rv; 579 } 580 581 bool QuicFramer::ProcessVersionNegotiationPacket( 582 QuicPacketPublicHeader* public_header) { 583 DCHECK(!is_server_); 584 // Try reading at least once to raise error if the packet is invalid. 585 do { 586 QuicTag version; 587 if (!reader_->ReadBytes(&version, kQuicVersionSize)) { 588 set_detailed_error("Unable to read supported version in negotiation."); 589 return RaiseError(QUIC_INVALID_VERSION_NEGOTIATION_PACKET); 590 } 591 public_header->versions.push_back(QuicTagToQuicVersion(version)); 592 } while (!reader_->IsDoneReading()); 593 594 visitor_->OnVersionNegotiationPacket(*public_header); 595 return true; 596 } 597 598 bool QuicFramer::ProcessDataPacket( 599 const QuicPacketPublicHeader& public_header, 600 const QuicEncryptedPacket& packet) { 601 QuicPacketHeader header(public_header); 602 if (!ProcessPacketHeader(&header, packet)) { 603 DLOG(WARNING) << "Unable to process data packet header."; 604 return false; 605 } 606 607 if (!visitor_->OnPacketHeader(header)) { 608 // The visitor suppresses further processing of the packet. 609 return true; 610 } 611 612 if (packet.length() > kMaxPacketSize) { 613 DLOG(WARNING) << "Packet too large: " << packet.length(); 614 return RaiseError(QUIC_PACKET_TOO_LARGE); 615 } 616 617 // Handle the payload. 618 if (!header.fec_flag) { 619 if (header.is_in_fec_group == IN_FEC_GROUP) { 620 StringPiece payload = reader_->PeekRemainingPayload(); 621 visitor_->OnFecProtectedPayload(payload); 622 } 623 if (!ProcessFrameData(header)) { 624 DCHECK_NE(QUIC_NO_ERROR, error_); // ProcessFrameData sets the error. 625 DLOG(WARNING) << "Unable to process frame data."; 626 return false; 627 } 628 } else { 629 QuicFecData fec_data; 630 fec_data.fec_group = header.fec_group; 631 fec_data.redundancy = reader_->ReadRemainingPayload(); 632 visitor_->OnFecData(fec_data); 633 } 634 635 visitor_->OnPacketComplete(); 636 return true; 637 } 638 639 bool QuicFramer::ProcessPublicResetPacket( 640 const QuicPacketPublicHeader& public_header) { 641 QuicPublicResetPacket packet(public_header); 642 643 scoped_ptr<CryptoHandshakeMessage> reset( 644 CryptoFramer::ParseMessage(reader_->ReadRemainingPayload())); 645 if (!reset.get()) { 646 set_detailed_error("Unable to read reset message."); 647 return RaiseError(QUIC_INVALID_PUBLIC_RST_PACKET); 648 } 649 if (reset->tag() != kPRST) { 650 set_detailed_error("Incorrect message tag."); 651 return RaiseError(QUIC_INVALID_PUBLIC_RST_PACKET); 652 } 653 654 if (reset->GetUint64(kRNON, &packet.nonce_proof) != QUIC_NO_ERROR) { 655 set_detailed_error("Unable to read nonce proof."); 656 return RaiseError(QUIC_INVALID_PUBLIC_RST_PACKET); 657 } 658 // TODO(satyamshekhar): validate nonce to protect against DoS. 659 660 if (reset->GetUint64(kRSEQ, &packet.rejected_sequence_number) != 661 QUIC_NO_ERROR) { 662 set_detailed_error("Unable to read rejected sequence number."); 663 return RaiseError(QUIC_INVALID_PUBLIC_RST_PACKET); 664 } 665 666 StringPiece address; 667 if (reset->GetStringPiece(kCADR, &address)) { 668 QuicSocketAddressCoder address_coder; 669 if (address_coder.Decode(address.data(), address.length())) { 670 packet.client_address = IPEndPoint(address_coder.ip(), 671 address_coder.port()); 672 } 673 } 674 675 visitor_->OnPublicResetPacket(packet); 676 return true; 677 } 678 679 bool QuicFramer::ProcessRevivedPacket(QuicPacketHeader* header, 680 StringPiece payload) { 681 DCHECK(!reader_.get()); 682 683 visitor_->OnRevivedPacket(); 684 685 header->entropy_hash = GetPacketEntropyHash(*header); 686 687 if (!visitor_->OnPacketHeader(*header)) { 688 return true; 689 } 690 691 if (payload.length() > kMaxPacketSize) { 692 set_detailed_error("Revived packet too large."); 693 return RaiseError(QUIC_PACKET_TOO_LARGE); 694 } 695 696 reader_.reset(new QuicDataReader(payload.data(), payload.length())); 697 if (!ProcessFrameData(*header)) { 698 DCHECK_NE(QUIC_NO_ERROR, error_); // ProcessFrameData sets the error. 699 DLOG(WARNING) << "Unable to process frame data."; 700 return false; 701 } 702 703 visitor_->OnPacketComplete(); 704 reader_.reset(NULL); 705 return true; 706 } 707 708 bool QuicFramer::AppendPacketHeader(const QuicPacketHeader& header, 709 QuicDataWriter* writer) { 710 DVLOG(1) << "Appending header: " << header; 711 DCHECK(header.fec_group > 0 || header.is_in_fec_group == NOT_IN_FEC_GROUP); 712 uint8 public_flags = 0; 713 if (header.public_header.reset_flag) { 714 public_flags |= PACKET_PUBLIC_FLAGS_RST; 715 } 716 if (header.public_header.version_flag) { 717 public_flags |= PACKET_PUBLIC_FLAGS_VERSION; 718 } 719 720 public_flags |= 721 GetSequenceNumberFlags(header.public_header.sequence_number_length) 722 << kPublicHeaderSequenceNumberShift; 723 724 switch (header.public_header.connection_id_length) { 725 case PACKET_0BYTE_CONNECTION_ID: 726 if (!writer->WriteUInt8( 727 public_flags | PACKET_PUBLIC_FLAGS_0BYTE_CONNECTION_ID)) { 728 return false; 729 } 730 break; 731 case PACKET_1BYTE_CONNECTION_ID: 732 if (!writer->WriteUInt8( 733 public_flags | PACKET_PUBLIC_FLAGS_1BYTE_CONNECTION_ID)) { 734 return false; 735 } 736 if (!writer->WriteUInt8( 737 header.public_header.connection_id & k1ByteConnectionIdMask)) { 738 return false; 739 } 740 break; 741 case PACKET_4BYTE_CONNECTION_ID: 742 if (!writer->WriteUInt8( 743 public_flags | PACKET_PUBLIC_FLAGS_4BYTE_CONNECTION_ID)) { 744 return false; 745 } 746 if (!writer->WriteUInt32( 747 header.public_header.connection_id & k4ByteConnectionIdMask)) { 748 return false; 749 } 750 break; 751 case PACKET_8BYTE_CONNECTION_ID: 752 if (!writer->WriteUInt8( 753 public_flags | PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID)) { 754 return false; 755 } 756 if (!writer->WriteUInt64(header.public_header.connection_id)) { 757 return false; 758 } 759 break; 760 } 761 last_serialized_connection_id_ = header.public_header.connection_id; 762 763 if (header.public_header.version_flag) { 764 DCHECK(!is_server_); 765 writer->WriteUInt32(QuicVersionToQuicTag(quic_version_)); 766 } 767 768 if (!AppendPacketSequenceNumber(header.public_header.sequence_number_length, 769 header.packet_sequence_number, writer)) { 770 return false; 771 } 772 773 uint8 private_flags = 0; 774 if (header.entropy_flag) { 775 private_flags |= PACKET_PRIVATE_FLAGS_ENTROPY; 776 } 777 if (header.is_in_fec_group == IN_FEC_GROUP) { 778 private_flags |= PACKET_PRIVATE_FLAGS_FEC_GROUP; 779 } 780 if (header.fec_flag) { 781 private_flags |= PACKET_PRIVATE_FLAGS_FEC; 782 } 783 if (!writer->WriteUInt8(private_flags)) { 784 return false; 785 } 786 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_GE(header.packet_sequence_number, header.fec_group); 791 DCHECK_GT(255u, header.packet_sequence_number - header.fec_group); 792 // Offset from the current packet sequence number to the first fec 793 // protected packet. 794 uint8 first_fec_protected_packet_offset = 795 header.packet_sequence_number - header.fec_group; 796 if (!writer->WriteBytes(&first_fec_protected_packet_offset, 1)) { 797 return false; 798 } 799 } 800 801 return true; 802 } 803 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. 810 // 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; 818 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)); 824 825 return QuicTime::Delta::FromMicroseconds(time); 826 } 827 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. 835 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; 845 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)); 851 } 852 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; 859 } 860 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; 864 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; 869 } 870 871 if (public_header->reset_flag && public_header->version_flag) { 872 set_detailed_error("Got version flag in reset packet"); 873 return false; 874 } 875 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; 881 } 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; 891 } 892 if ((public_header->connection_id & k4ByteConnectionIdMask) != 893 (last_serialized_connection_id_ & k4ByteConnectionIdMask)) { 894 set_detailed_error("Truncated 4 byte ConnectionId does not match " 895 "previous connection_id."); 896 return false; 897 } 898 public_header->connection_id_length = PACKET_4BYTE_CONNECTION_ID; 899 public_header->connection_id = last_serialized_connection_id_; 900 break; 901 case PACKET_PUBLIC_FLAGS_1BYTE_CONNECTION_ID: 902 if (!reader_->ReadBytes(&public_header->connection_id, 903 PACKET_1BYTE_CONNECTION_ID)) { 904 set_detailed_error("Unable to read ConnectionId."); 905 return false; 906 } 907 if ((public_header->connection_id & k1ByteConnectionIdMask) != 908 (last_serialized_connection_id_ & k1ByteConnectionIdMask)) { 909 set_detailed_error("Truncated 1 byte ConnectionId does not match " 910 "previous connection_id."); 911 return false; 912 } 913 public_header->connection_id_length = PACKET_1BYTE_CONNECTION_ID; 914 public_header->connection_id = last_serialized_connection_id_; 915 break; 916 case PACKET_PUBLIC_FLAGS_0BYTE_CONNECTION_ID: 917 public_header->connection_id_length = PACKET_0BYTE_CONNECTION_ID; 918 public_header->connection_id = last_serialized_connection_id_; 919 break; 920 } 921 922 public_header->sequence_number_length = 923 ReadSequenceNumberLength( 924 public_flags >> kPublicHeaderSequenceNumberShift); 925 926 // Read the version only if the packet is from the client. 927 // version flag from the server means version negotiation packet. 928 if (public_header->version_flag && is_server_) { 929 QuicTag version_tag; 930 if (!reader_->ReadUInt32(&version_tag)) { 931 set_detailed_error("Unable to read protocol version."); 932 return false; 933 } 934 935 // If the version from the new packet is the same as the version of this 936 // framer, then the public flags should be set to something we understand. 937 // If not, this raises an error. 938 QuicVersion version = QuicTagToQuicVersion(version_tag); 939 if (version == quic_version_ && public_flags > PACKET_PUBLIC_FLAGS_MAX) { 940 set_detailed_error("Illegal public flags value."); 941 return false; 942 } 943 public_header->versions.push_back(version); 944 } 945 return true; 946 } 947 948 // static 949 QuicSequenceNumberLength QuicFramer::GetMinSequenceNumberLength( 950 QuicPacketSequenceNumber sequence_number) { 951 if (sequence_number < 1 << (PACKET_1BYTE_SEQUENCE_NUMBER * 8)) { 952 return PACKET_1BYTE_SEQUENCE_NUMBER; 953 } else if (sequence_number < 1 << (PACKET_2BYTE_SEQUENCE_NUMBER * 8)) { 954 return PACKET_2BYTE_SEQUENCE_NUMBER; 955 } else if (sequence_number < 956 GG_UINT64_C(1) << (PACKET_4BYTE_SEQUENCE_NUMBER * 8)) { 957 return PACKET_4BYTE_SEQUENCE_NUMBER; 958 } else { 959 return PACKET_6BYTE_SEQUENCE_NUMBER; 960 } 961 } 962 963 // static 964 uint8 QuicFramer::GetSequenceNumberFlags( 965 QuicSequenceNumberLength sequence_number_length) { 966 switch (sequence_number_length) { 967 case PACKET_1BYTE_SEQUENCE_NUMBER: 968 return PACKET_FLAGS_1BYTE_SEQUENCE; 969 case PACKET_2BYTE_SEQUENCE_NUMBER: 970 return PACKET_FLAGS_2BYTE_SEQUENCE; 971 case PACKET_4BYTE_SEQUENCE_NUMBER: 972 return PACKET_FLAGS_4BYTE_SEQUENCE; 973 case PACKET_6BYTE_SEQUENCE_NUMBER: 974 return PACKET_FLAGS_6BYTE_SEQUENCE; 975 default: 976 LOG(DFATAL) << "Unreachable case statement."; 977 return PACKET_FLAGS_6BYTE_SEQUENCE; 978 } 979 } 980 981 // static 982 QuicFramer::AckFrameInfo QuicFramer::GetAckFrameInfo( 983 const QuicAckFrame& frame) { 984 AckFrameInfo ack_info; 985 if (!frame.missing_packets.empty()) { 986 DCHECK_GE(frame.largest_observed, *frame.missing_packets.rbegin()); 987 size_t cur_range_length = 0; 988 SequenceNumberSet::const_iterator iter = frame.missing_packets.begin(); 989 QuicPacketSequenceNumber last_missing = *iter; 990 ++iter; 991 for (; iter != frame.missing_packets.end(); ++iter) { 992 if (cur_range_length != numeric_limits<uint8>::max() && 993 *iter == (last_missing + 1)) { 994 ++cur_range_length; 995 } else { 996 ack_info.nack_ranges[last_missing - cur_range_length] = 997 cur_range_length; 998 cur_range_length = 0; 999 } 1000 ack_info.max_delta = max(ack_info.max_delta, *iter - last_missing); 1001 last_missing = *iter; 1002 } 1003 // Include the last nack range. 1004 ack_info.nack_ranges[last_missing - cur_range_length] = cur_range_length; 1005 // Include the range to the largest observed. 1006 ack_info.max_delta = max(ack_info.max_delta, 1007 frame.largest_observed - last_missing); 1008 } 1009 return ack_info; 1010 } 1011 1012 bool QuicFramer::ProcessPacketHeader( 1013 QuicPacketHeader* header, 1014 const QuicEncryptedPacket& packet) { 1015 if (!ProcessPacketSequenceNumber(header->public_header.sequence_number_length, 1016 &header->packet_sequence_number)) { 1017 set_detailed_error("Unable to read sequence number."); 1018 return RaiseError(QUIC_INVALID_PACKET_HEADER); 1019 } 1020 1021 if (header->packet_sequence_number == 0u) { 1022 set_detailed_error("Packet sequence numbers cannot be 0."); 1023 return RaiseError(QUIC_INVALID_PACKET_HEADER); 1024 } 1025 1026 if (!visitor_->OnUnauthenticatedHeader(*header)) { 1027 return false; 1028 } 1029 1030 if (!DecryptPayload(*header, packet)) { 1031 set_detailed_error("Unable to decrypt payload."); 1032 return RaiseError(QUIC_DECRYPTION_FAILURE); 1033 } 1034 1035 uint8 private_flags; 1036 if (!reader_->ReadBytes(&private_flags, 1)) { 1037 set_detailed_error("Unable to read private flags."); 1038 return RaiseError(QUIC_INVALID_PACKET_HEADER); 1039 } 1040 1041 if (private_flags > PACKET_PRIVATE_FLAGS_MAX) { 1042 set_detailed_error("Illegal private flags value."); 1043 return RaiseError(QUIC_INVALID_PACKET_HEADER); 1044 } 1045 1046 header->entropy_flag = (private_flags & PACKET_PRIVATE_FLAGS_ENTROPY) != 0; 1047 header->fec_flag = (private_flags & PACKET_PRIVATE_FLAGS_FEC) != 0; 1048 1049 if ((private_flags & PACKET_PRIVATE_FLAGS_FEC_GROUP) != 0) { 1050 header->is_in_fec_group = IN_FEC_GROUP; 1051 uint8 first_fec_protected_packet_offset; 1052 if (!reader_->ReadBytes(&first_fec_protected_packet_offset, 1)) { 1053 set_detailed_error("Unable to read first fec protected packet offset."); 1054 return RaiseError(QUIC_INVALID_PACKET_HEADER); 1055 } 1056 if (first_fec_protected_packet_offset >= header->packet_sequence_number) { 1057 set_detailed_error("First fec protected packet offset must be less " 1058 "than the sequence number."); 1059 return RaiseError(QUIC_INVALID_PACKET_HEADER); 1060 } 1061 header->fec_group = 1062 header->packet_sequence_number - first_fec_protected_packet_offset; 1063 } 1064 1065 header->entropy_hash = GetPacketEntropyHash(*header); 1066 // Set the last sequence number after we have decrypted the packet 1067 // so we are confident is not attacker controlled. 1068 last_sequence_number_ = header->packet_sequence_number; 1069 return true; 1070 } 1071 1072 bool QuicFramer::ProcessPacketSequenceNumber( 1073 QuicSequenceNumberLength sequence_number_length, 1074 QuicPacketSequenceNumber* sequence_number) { 1075 QuicPacketSequenceNumber wire_sequence_number = 0u; 1076 if (!reader_->ReadBytes(&wire_sequence_number, sequence_number_length)) { 1077 return false; 1078 } 1079 1080 // TODO(ianswett): Explore the usefulness of trying multiple sequence numbers 1081 // in case the first guess is incorrect. 1082 *sequence_number = 1083 CalculatePacketSequenceNumberFromWire(sequence_number_length, 1084 wire_sequence_number); 1085 return true; 1086 } 1087 1088 bool QuicFramer::ProcessFrameData(const QuicPacketHeader& header) { 1089 if (reader_->IsDoneReading()) { 1090 set_detailed_error("Packet has no frames."); 1091 return RaiseError(QUIC_MISSING_PAYLOAD); 1092 } 1093 while (!reader_->IsDoneReading()) { 1094 uint8 frame_type; 1095 if (!reader_->ReadBytes(&frame_type, 1)) { 1096 set_detailed_error("Unable to read frame type."); 1097 return RaiseError(QUIC_INVALID_FRAME_DATA); 1098 } 1099 1100 if (frame_type & kQuicFrameTypeSpecialMask) { 1101 // Stream Frame 1102 if (frame_type & kQuicFrameTypeStreamMask) { 1103 QuicStreamFrame frame; 1104 if (!ProcessStreamFrame(frame_type, &frame)) { 1105 return RaiseError(QUIC_INVALID_STREAM_DATA); 1106 } 1107 if (!visitor_->OnStreamFrame(frame)) { 1108 DVLOG(1) << "Visitor asked to stop further processing."; 1109 // Returning true since there was no parsing error. 1110 return true; 1111 } 1112 continue; 1113 } 1114 1115 // Ack Frame 1116 if (frame_type & kQuicFrameTypeAckMask) { 1117 QuicAckFrame frame; 1118 if (!ProcessAckFrame(frame_type, &frame)) { 1119 return RaiseError(QUIC_INVALID_ACK_DATA); 1120 } 1121 if (!visitor_->OnAckFrame(frame)) { 1122 DVLOG(1) << "Visitor asked to stop further processing."; 1123 // Returning true since there was no parsing error. 1124 return true; 1125 } 1126 continue; 1127 } 1128 1129 // Congestion Feedback Frame 1130 if (frame_type & kQuicFrameTypeCongestionFeedbackMask) { 1131 if (quic_version_ > QUIC_VERSION_22) { 1132 set_detailed_error("Congestion Feedback Frame has been deprecated."); 1133 DLOG(WARNING) << "Congestion Feedback Frame has been deprecated."; 1134 } 1135 QuicCongestionFeedbackFrame frame; 1136 if (!ProcessCongestionFeedbackFrame(&frame)) { 1137 return RaiseError(QUIC_INVALID_CONGESTION_FEEDBACK_DATA); 1138 } 1139 if (!visitor_->OnCongestionFeedbackFrame(frame)) { 1140 DVLOG(1) << "Visitor asked to stop further processing."; 1141 // Returning true since there was no parsing error. 1142 return true; 1143 } 1144 continue; 1145 } 1146 1147 // This was a special frame type that did not match any 1148 // of the known ones. Error. 1149 set_detailed_error("Illegal frame type."); 1150 DLOG(WARNING) << "Illegal frame type: " 1151 << static_cast<int>(frame_type); 1152 return RaiseError(QUIC_INVALID_FRAME_DATA); 1153 } 1154 1155 switch (frame_type) { 1156 case PADDING_FRAME: 1157 // We're done with the packet. 1158 return true; 1159 1160 case RST_STREAM_FRAME: { 1161 QuicRstStreamFrame frame; 1162 if (!ProcessRstStreamFrame(&frame)) { 1163 return RaiseError(QUIC_INVALID_RST_STREAM_DATA); 1164 } 1165 if (!visitor_->OnRstStreamFrame(frame)) { 1166 DVLOG(1) << "Visitor asked to stop further processing."; 1167 // Returning true since there was no parsing error. 1168 return true; 1169 } 1170 continue; 1171 } 1172 1173 case CONNECTION_CLOSE_FRAME: { 1174 QuicConnectionCloseFrame frame; 1175 if (!ProcessConnectionCloseFrame(&frame)) { 1176 return RaiseError(QUIC_INVALID_CONNECTION_CLOSE_DATA); 1177 } 1178 1179 if (!visitor_->OnConnectionCloseFrame(frame)) { 1180 DVLOG(1) << "Visitor asked to stop further processing."; 1181 // Returning true since there was no parsing error. 1182 return true; 1183 } 1184 continue; 1185 } 1186 1187 case GOAWAY_FRAME: { 1188 QuicGoAwayFrame goaway_frame; 1189 if (!ProcessGoAwayFrame(&goaway_frame)) { 1190 return RaiseError(QUIC_INVALID_GOAWAY_DATA); 1191 } 1192 if (!visitor_->OnGoAwayFrame(goaway_frame)) { 1193 DVLOG(1) << "Visitor asked to stop further processing."; 1194 // Returning true since there was no parsing error. 1195 return true; 1196 } 1197 continue; 1198 } 1199 1200 case WINDOW_UPDATE_FRAME: { 1201 QuicWindowUpdateFrame window_update_frame; 1202 if (!ProcessWindowUpdateFrame(&window_update_frame)) { 1203 return RaiseError(QUIC_INVALID_WINDOW_UPDATE_DATA); 1204 } 1205 if (!visitor_->OnWindowUpdateFrame(window_update_frame)) { 1206 DVLOG(1) << "Visitor asked to stop further processing."; 1207 // Returning true since there was no parsing error. 1208 return true; 1209 } 1210 continue; 1211 } 1212 1213 case BLOCKED_FRAME: { 1214 QuicBlockedFrame blocked_frame; 1215 if (!ProcessBlockedFrame(&blocked_frame)) { 1216 return RaiseError(QUIC_INVALID_BLOCKED_DATA); 1217 } 1218 if (!visitor_->OnBlockedFrame(blocked_frame)) { 1219 DVLOG(1) << "Visitor asked to stop further processing."; 1220 // Returning true since there was no parsing error. 1221 return true; 1222 } 1223 continue; 1224 } 1225 1226 case STOP_WAITING_FRAME: { 1227 QuicStopWaitingFrame stop_waiting_frame; 1228 if (!ProcessStopWaitingFrame(header, &stop_waiting_frame)) { 1229 return RaiseError(QUIC_INVALID_STOP_WAITING_DATA); 1230 } 1231 if (!visitor_->OnStopWaitingFrame(stop_waiting_frame)) { 1232 DVLOG(1) << "Visitor asked to stop further processing."; 1233 // Returning true since there was no parsing error. 1234 return true; 1235 } 1236 continue; 1237 } 1238 case PING_FRAME: { 1239 if (quic_version_ == QUIC_VERSION_16) { 1240 LOG(DFATAL) << "Trying to read a Ping in " 1241 << QuicVersionToString(quic_version_); 1242 return RaiseError(QUIC_INTERNAL_ERROR); 1243 } 1244 // Ping has no payload. 1245 QuicPingFrame ping_frame; 1246 if (!visitor_->OnPingFrame(ping_frame)) { 1247 DVLOG(1) << "Visitor asked to stop further processing."; 1248 // Returning true since there was no parsing error. 1249 return true; 1250 } 1251 continue; 1252 } 1253 1254 default: 1255 set_detailed_error("Illegal frame type."); 1256 DLOG(WARNING) << "Illegal frame type: " 1257 << static_cast<int>(frame_type); 1258 return RaiseError(QUIC_INVALID_FRAME_DATA); 1259 } 1260 } 1261 1262 return true; 1263 } 1264 1265 bool QuicFramer::ProcessStreamFrame(uint8 frame_type, 1266 QuicStreamFrame* frame) { 1267 uint8 stream_flags = frame_type; 1268 1269 stream_flags &= ~kQuicFrameTypeStreamMask; 1270 1271 // Read from right to left: StreamID, Offset, Data Length, Fin. 1272 const uint8 stream_id_length = (stream_flags & kQuicStreamIDLengthMask) + 1; 1273 stream_flags >>= kQuicStreamIdShift; 1274 1275 uint8 offset_length = (stream_flags & kQuicStreamOffsetMask); 1276 // There is no encoding for 1 byte, only 0 and 2 through 8. 1277 if (offset_length > 0) { 1278 offset_length += 1; 1279 } 1280 stream_flags >>= kQuicStreamOffsetShift; 1281 1282 bool has_data_length = 1283 (stream_flags & kQuicStreamDataLengthMask) == kQuicStreamDataLengthMask; 1284 stream_flags >>= kQuicStreamDataLengthShift; 1285 1286 frame->fin = (stream_flags & kQuicStreamFinMask) == kQuicStreamFinShift; 1287 1288 frame->stream_id = 0; 1289 if (!reader_->ReadBytes(&frame->stream_id, stream_id_length)) { 1290 set_detailed_error("Unable to read stream_id."); 1291 return false; 1292 } 1293 1294 frame->offset = 0; 1295 if (!reader_->ReadBytes(&frame->offset, offset_length)) { 1296 set_detailed_error("Unable to read offset."); 1297 return false; 1298 } 1299 1300 StringPiece frame_data; 1301 if (has_data_length) { 1302 if (!reader_->ReadStringPiece16(&frame_data)) { 1303 set_detailed_error("Unable to read frame data."); 1304 return false; 1305 } 1306 } else { 1307 if (!reader_->ReadStringPiece(&frame_data, reader_->BytesRemaining())) { 1308 set_detailed_error("Unable to read frame data."); 1309 return false; 1310 } 1311 } 1312 // Point frame to the right data. 1313 frame->data.Clear(); 1314 if (!frame_data.empty()) { 1315 frame->data.Append(const_cast<char*>(frame_data.data()), frame_data.size()); 1316 } 1317 1318 return true; 1319 } 1320 1321 bool QuicFramer::ProcessAckFrame(uint8 frame_type, QuicAckFrame* ack_frame) { 1322 // Determine the three lengths from the frame type: largest observed length, 1323 // missing sequence number length, and missing range length. 1324 const QuicSequenceNumberLength missing_sequence_number_length = 1325 ReadSequenceNumberLength(frame_type); 1326 frame_type >>= kQuicSequenceNumberLengthShift; 1327 const QuicSequenceNumberLength largest_observed_sequence_number_length = 1328 ReadSequenceNumberLength(frame_type); 1329 frame_type >>= kQuicSequenceNumberLengthShift; 1330 ack_frame->is_truncated = frame_type & kQuicAckTruncatedMask; 1331 frame_type >>= kQuicAckTruncatedShift; 1332 bool has_nacks = frame_type & kQuicHasNacksMask; 1333 1334 if (!reader_->ReadBytes(&ack_frame->entropy_hash, 1)) { 1335 set_detailed_error("Unable to read entropy hash for received packets."); 1336 return false; 1337 } 1338 1339 if (!reader_->ReadBytes(&ack_frame->largest_observed, 1340 largest_observed_sequence_number_length)) { 1341 set_detailed_error("Unable to read largest observed."); 1342 return false; 1343 } 1344 1345 uint64 delta_time_largest_observed_us; 1346 if (!reader_->ReadUFloat16(&delta_time_largest_observed_us)) { 1347 set_detailed_error("Unable to read delta time largest observed."); 1348 return false; 1349 } 1350 1351 if (delta_time_largest_observed_us == kUFloat16MaxValue) { 1352 ack_frame->delta_time_largest_observed = QuicTime::Delta::Infinite(); 1353 } else { 1354 ack_frame->delta_time_largest_observed = 1355 QuicTime::Delta::FromMicroseconds(delta_time_largest_observed_us); 1356 } 1357 1358 if (!ProcessTimestampsInAckFrame(ack_frame)) { 1359 return false; 1360 } 1361 1362 if (!has_nacks) { 1363 return true; 1364 } 1365 1366 uint8 num_missing_ranges; 1367 if (!reader_->ReadBytes(&num_missing_ranges, 1)) { 1368 set_detailed_error("Unable to read num missing packet ranges."); 1369 return false; 1370 } 1371 1372 QuicPacketSequenceNumber last_sequence_number = ack_frame->largest_observed; 1373 for (size_t i = 0; i < num_missing_ranges; ++i) { 1374 QuicPacketSequenceNumber missing_delta = 0; 1375 if (!reader_->ReadBytes(&missing_delta, missing_sequence_number_length)) { 1376 set_detailed_error("Unable to read missing sequence number delta."); 1377 return false; 1378 } 1379 last_sequence_number -= missing_delta; 1380 QuicPacketSequenceNumber range_length = 0; 1381 if (!reader_->ReadBytes(&range_length, PACKET_1BYTE_SEQUENCE_NUMBER)) { 1382 set_detailed_error("Unable to read missing sequence number range."); 1383 return false; 1384 } 1385 for (size_t i = 0; i <= range_length; ++i) { 1386 ack_frame->missing_packets.insert(last_sequence_number - i); 1387 } 1388 // Subtract an extra 1 to ensure ranges are represented efficiently and 1389 // can't overlap by 1 sequence number. This allows a missing_delta of 0 1390 // to represent an adjacent nack range. 1391 last_sequence_number -= (range_length + 1); 1392 } 1393 1394 // Parse the revived packets list. 1395 uint8 num_revived_packets; 1396 if (!reader_->ReadBytes(&num_revived_packets, 1)) { 1397 set_detailed_error("Unable to read num revived packets."); 1398 return false; 1399 } 1400 1401 for (size_t i = 0; i < num_revived_packets; ++i) { 1402 QuicPacketSequenceNumber revived_packet = 0; 1403 if (!reader_->ReadBytes(&revived_packet, 1404 largest_observed_sequence_number_length)) { 1405 set_detailed_error("Unable to read revived packet."); 1406 return false; 1407 } 1408 1409 ack_frame->revived_packets.insert(revived_packet); 1410 } 1411 1412 return true; 1413 } 1414 1415 bool QuicFramer::ProcessTimestampsInAckFrame(QuicAckFrame* ack_frame) { 1416 if (version() > QUIC_VERSION_22 && !ack_frame->is_truncated) { 1417 uint8 num_received_packets; 1418 if (!reader_->ReadBytes(&num_received_packets, 1)) { 1419 set_detailed_error("Unable to read num received packets."); 1420 return false; 1421 } 1422 1423 if (num_received_packets > 0) { 1424 uint8 delta_from_largest_observed; 1425 if (!reader_->ReadBytes(&delta_from_largest_observed, 1426 PACKET_1BYTE_SEQUENCE_NUMBER)) { 1427 set_detailed_error( 1428 "Unable to read sequence delta in received packets."); 1429 return false; 1430 } 1431 QuicPacketSequenceNumber seq_num = ack_frame->largest_observed - 1432 delta_from_largest_observed; 1433 1434 // Time delta from the framer creation. 1435 uint32 time_delta_us; 1436 if (!reader_->ReadBytes(&time_delta_us, sizeof(time_delta_us))) { 1437 set_detailed_error("Unable to read time delta in received packets."); 1438 return false; 1439 } 1440 1441 last_timestamp_ = CalculateTimestampFromWire(time_delta_us); 1442 1443 ack_frame->received_packet_times.push_back( 1444 make_pair(seq_num, creation_time_.Add(last_timestamp_))); 1445 1446 for (uint8 i = 1; i < num_received_packets; ++i) { 1447 if (!reader_->ReadBytes(&delta_from_largest_observed, 1448 PACKET_1BYTE_SEQUENCE_NUMBER)) { 1449 set_detailed_error( 1450 "Unable to read sequence delta in received packets."); 1451 return false; 1452 } 1453 seq_num = ack_frame->largest_observed - delta_from_largest_observed; 1454 1455 // Time delta from the previous timestamp. 1456 uint64 incremental_time_delta_us; 1457 if (!reader_->ReadUFloat16(&incremental_time_delta_us)) { 1458 set_detailed_error( 1459 "Unable to read incremental time delta in received packets."); 1460 return false; 1461 } 1462 1463 last_timestamp_ = last_timestamp_.Add( 1464 QuicTime::Delta::FromMicroseconds(incremental_time_delta_us)); 1465 ack_frame->received_packet_times.push_back( 1466 make_pair(seq_num, creation_time_.Add(last_timestamp_))); 1467 } 1468 } 1469 } 1470 return true; 1471 } 1472 1473 bool QuicFramer::ProcessStopWaitingFrame(const QuicPacketHeader& header, 1474 QuicStopWaitingFrame* stop_waiting) { 1475 if (!reader_->ReadBytes(&stop_waiting->entropy_hash, 1)) { 1476 set_detailed_error("Unable to read entropy hash for sent packets."); 1477 return false; 1478 } 1479 1480 QuicPacketSequenceNumber least_unacked_delta = 0; 1481 if (!reader_->ReadBytes(&least_unacked_delta, 1482 header.public_header.sequence_number_length)) { 1483 set_detailed_error("Unable to read least unacked delta."); 1484 return false; 1485 } 1486 DCHECK_GE(header.packet_sequence_number, least_unacked_delta); 1487 stop_waiting->least_unacked = 1488 header.packet_sequence_number - least_unacked_delta; 1489 1490 return true; 1491 } 1492 1493 bool QuicFramer::ProcessCongestionFeedbackFrame( 1494 QuicCongestionFeedbackFrame* frame) { 1495 uint8 feedback_type; 1496 if (!reader_->ReadBytes(&feedback_type, 1)) { 1497 set_detailed_error("Unable to read congestion feedback type."); 1498 return false; 1499 } 1500 frame->type = 1501 static_cast<CongestionFeedbackType>(feedback_type); 1502 1503 switch (frame->type) { 1504 case kTCP: { 1505 CongestionFeedbackMessageTCP* tcp = &frame->tcp; 1506 uint16 receive_window = 0; 1507 if (!reader_->ReadUInt16(&receive_window)) { 1508 set_detailed_error("Unable to read receive window."); 1509 return false; 1510 } 1511 // Simple bit packing, don't send the 4 least significant bits. 1512 tcp->receive_window = static_cast<QuicByteCount>(receive_window) << 4; 1513 break; 1514 } 1515 default: 1516 set_detailed_error("Illegal congestion feedback type."); 1517 DLOG(WARNING) << "Illegal congestion feedback type: " 1518 << frame->type; 1519 return RaiseError(QUIC_INVALID_FRAME_DATA); 1520 } 1521 1522 return true; 1523 } 1524 1525 bool QuicFramer::ProcessRstStreamFrame(QuicRstStreamFrame* frame) { 1526 if (!reader_->ReadUInt32(&frame->stream_id)) { 1527 set_detailed_error("Unable to read stream_id."); 1528 return false; 1529 } 1530 1531 if (!reader_->ReadUInt64(&frame->byte_offset)) { 1532 set_detailed_error("Unable to read rst stream sent byte offset."); 1533 return false; 1534 } 1535 1536 uint32 error_code; 1537 if (!reader_->ReadUInt32(&error_code)) { 1538 set_detailed_error("Unable to read rst stream error code."); 1539 return false; 1540 } 1541 1542 if (error_code >= QUIC_STREAM_LAST_ERROR || 1543 error_code < QUIC_STREAM_NO_ERROR) { 1544 set_detailed_error("Invalid rst stream error code."); 1545 return false; 1546 } 1547 1548 frame->error_code = static_cast<QuicRstStreamErrorCode>(error_code); 1549 1550 StringPiece error_details; 1551 if (!reader_->ReadStringPiece16(&error_details)) { 1552 set_detailed_error("Unable to read rst stream error details."); 1553 return false; 1554 } 1555 frame->error_details = error_details.as_string(); 1556 1557 return true; 1558 } 1559 1560 bool QuicFramer::ProcessConnectionCloseFrame(QuicConnectionCloseFrame* frame) { 1561 uint32 error_code; 1562 if (!reader_->ReadUInt32(&error_code)) { 1563 set_detailed_error("Unable to read connection close error code."); 1564 return false; 1565 } 1566 1567 if (error_code >= QUIC_LAST_ERROR || 1568 error_code < QUIC_NO_ERROR) { 1569 set_detailed_error("Invalid error code."); 1570 return false; 1571 } 1572 1573 frame->error_code = static_cast<QuicErrorCode>(error_code); 1574 1575 StringPiece error_details; 1576 if (!reader_->ReadStringPiece16(&error_details)) { 1577 set_detailed_error("Unable to read connection close error details."); 1578 return false; 1579 } 1580 frame->error_details = error_details.as_string(); 1581 1582 return true; 1583 } 1584 1585 bool QuicFramer::ProcessGoAwayFrame(QuicGoAwayFrame* frame) { 1586 uint32 error_code; 1587 if (!reader_->ReadUInt32(&error_code)) { 1588 set_detailed_error("Unable to read go away error code."); 1589 return false; 1590 } 1591 frame->error_code = static_cast<QuicErrorCode>(error_code); 1592 1593 if (error_code >= QUIC_LAST_ERROR || 1594 error_code < QUIC_NO_ERROR) { 1595 set_detailed_error("Invalid error code."); 1596 return false; 1597 } 1598 1599 uint32 stream_id; 1600 if (!reader_->ReadUInt32(&stream_id)) { 1601 set_detailed_error("Unable to read last good stream id."); 1602 return false; 1603 } 1604 frame->last_good_stream_id = static_cast<QuicStreamId>(stream_id); 1605 1606 StringPiece reason_phrase; 1607 if (!reader_->ReadStringPiece16(&reason_phrase)) { 1608 set_detailed_error("Unable to read goaway reason."); 1609 return false; 1610 } 1611 frame->reason_phrase = reason_phrase.as_string(); 1612 1613 return true; 1614 } 1615 1616 bool QuicFramer::ProcessWindowUpdateFrame(QuicWindowUpdateFrame* frame) { 1617 if (!reader_->ReadUInt32(&frame->stream_id)) { 1618 set_detailed_error("Unable to read stream_id."); 1619 return false; 1620 } 1621 1622 if (!reader_->ReadUInt64(&frame->byte_offset)) { 1623 set_detailed_error("Unable to read window byte_offset."); 1624 return false; 1625 } 1626 1627 return true; 1628 } 1629 1630 bool QuicFramer::ProcessBlockedFrame(QuicBlockedFrame* frame) { 1631 if (!reader_->ReadUInt32(&frame->stream_id)) { 1632 set_detailed_error("Unable to read stream_id."); 1633 return false; 1634 } 1635 1636 return true; 1637 } 1638 1639 // static 1640 StringPiece QuicFramer::GetAssociatedDataFromEncryptedPacket( 1641 const QuicEncryptedPacket& encrypted, 1642 QuicConnectionIdLength connection_id_length, 1643 bool includes_version, 1644 QuicSequenceNumberLength sequence_number_length) { 1645 return StringPiece( 1646 encrypted.data() + kStartOfHashData, GetStartOfEncryptedData( 1647 connection_id_length, includes_version, sequence_number_length) 1648 - kStartOfHashData); 1649 } 1650 1651 void QuicFramer::SetDecrypter(QuicDecrypter* decrypter, 1652 EncryptionLevel level) { 1653 DCHECK(alternative_decrypter_.get() == NULL); 1654 DCHECK_GE(level, decrypter_level_); 1655 decrypter_.reset(decrypter); 1656 decrypter_level_ = level; 1657 } 1658 1659 void QuicFramer::SetAlternativeDecrypter(QuicDecrypter* decrypter, 1660 EncryptionLevel level, 1661 bool latch_once_used) { 1662 alternative_decrypter_.reset(decrypter); 1663 alternative_decrypter_level_ = level; 1664 alternative_decrypter_latch_ = latch_once_used; 1665 } 1666 1667 const QuicDecrypter* QuicFramer::decrypter() const { 1668 return decrypter_.get(); 1669 } 1670 1671 const QuicDecrypter* QuicFramer::alternative_decrypter() const { 1672 return alternative_decrypter_.get(); 1673 } 1674 1675 void QuicFramer::SetEncrypter(EncryptionLevel level, 1676 QuicEncrypter* encrypter) { 1677 DCHECK_GE(level, 0); 1678 DCHECK_LT(level, NUM_ENCRYPTION_LEVELS); 1679 encrypter_[level].reset(encrypter); 1680 } 1681 1682 const QuicEncrypter* QuicFramer::encrypter(EncryptionLevel level) const { 1683 DCHECK_GE(level, 0); 1684 DCHECK_LT(level, NUM_ENCRYPTION_LEVELS); 1685 DCHECK(encrypter_[level].get() != NULL); 1686 return encrypter_[level].get(); 1687 } 1688 1689 QuicEncryptedPacket* QuicFramer::EncryptPacket( 1690 EncryptionLevel level, 1691 QuicPacketSequenceNumber packet_sequence_number, 1692 const QuicPacket& packet) { 1693 DCHECK(encrypter_[level].get() != NULL); 1694 1695 scoped_ptr<QuicData> out(encrypter_[level]->EncryptPacket( 1696 packet_sequence_number, packet.AssociatedData(), packet.Plaintext())); 1697 if (out.get() == NULL) { 1698 RaiseError(QUIC_ENCRYPTION_FAILURE); 1699 return NULL; 1700 } 1701 StringPiece header_data = packet.BeforePlaintext(); 1702 size_t len = header_data.length() + out->length(); 1703 char* buffer = new char[len]; 1704 // TODO(rch): eliminate this buffer copy by passing in a buffer to Encrypt(). 1705 memcpy(buffer, header_data.data(), header_data.length()); 1706 memcpy(buffer + header_data.length(), out->data(), out->length()); 1707 return new QuicEncryptedPacket(buffer, len, true); 1708 } 1709 1710 size_t QuicFramer::GetMaxPlaintextSize(size_t ciphertext_size) { 1711 // In order to keep the code simple, we don't have the current encryption 1712 // level to hand. Both the NullEncrypter and AES-GCM have a tag length of 12. 1713 size_t min_plaintext_size = ciphertext_size; 1714 1715 for (int i = ENCRYPTION_NONE; i < NUM_ENCRYPTION_LEVELS; i++) { 1716 if (encrypter_[i].get() != NULL) { 1717 size_t size = encrypter_[i]->GetMaxPlaintextSize(ciphertext_size); 1718 if (size < min_plaintext_size) { 1719 min_plaintext_size = size; 1720 } 1721 } 1722 } 1723 1724 return min_plaintext_size; 1725 } 1726 1727 bool QuicFramer::DecryptPayload(const QuicPacketHeader& header, 1728 const QuicEncryptedPacket& packet) { 1729 StringPiece encrypted; 1730 if (!reader_->ReadStringPiece(&encrypted, reader_->BytesRemaining())) { 1731 return false; 1732 } 1733 DCHECK(decrypter_.get() != NULL); 1734 decrypted_.reset(decrypter_->DecryptPacket( 1735 header.packet_sequence_number, 1736 GetAssociatedDataFromEncryptedPacket( 1737 packet, 1738 header.public_header.connection_id_length, 1739 header.public_header.version_flag, 1740 header.public_header.sequence_number_length), 1741 encrypted)); 1742 if (decrypted_.get() != NULL) { 1743 visitor_->OnDecryptedPacket(decrypter_level_); 1744 } else if (alternative_decrypter_.get() != NULL) { 1745 decrypted_.reset(alternative_decrypter_->DecryptPacket( 1746 header.packet_sequence_number, 1747 GetAssociatedDataFromEncryptedPacket( 1748 packet, 1749 header.public_header.connection_id_length, 1750 header.public_header.version_flag, 1751 header.public_header.sequence_number_length), 1752 encrypted)); 1753 if (decrypted_.get() != NULL) { 1754 visitor_->OnDecryptedPacket(alternative_decrypter_level_); 1755 if (alternative_decrypter_latch_) { 1756 // Switch to the alternative decrypter and latch so that we cannot 1757 // switch back. 1758 decrypter_.reset(alternative_decrypter_.release()); 1759 decrypter_level_ = alternative_decrypter_level_; 1760 alternative_decrypter_level_ = ENCRYPTION_NONE; 1761 } else { 1762 // Switch the alternative decrypter so that we use it first next time. 1763 decrypter_.swap(alternative_decrypter_); 1764 EncryptionLevel level = alternative_decrypter_level_; 1765 alternative_decrypter_level_ = decrypter_level_; 1766 decrypter_level_ = level; 1767 } 1768 } 1769 } 1770 1771 if (decrypted_.get() == NULL) { 1772 DLOG(WARNING) << "DecryptPacket failed for sequence_number:" 1773 << header.packet_sequence_number; 1774 return false; 1775 } 1776 1777 reader_.reset(new QuicDataReader(decrypted_->data(), decrypted_->length())); 1778 return true; 1779 } 1780 1781 size_t QuicFramer::GetAckFrameSize( 1782 const QuicAckFrame& ack, 1783 QuicSequenceNumberLength sequence_number_length) { 1784 AckFrameInfo ack_info = GetAckFrameInfo(ack); 1785 QuicSequenceNumberLength largest_observed_length = 1786 GetMinSequenceNumberLength(ack.largest_observed); 1787 QuicSequenceNumberLength missing_sequence_number_length = 1788 GetMinSequenceNumberLength(ack_info.max_delta); 1789 1790 size_t ack_size = GetMinAckFrameSize(sequence_number_length, 1791 largest_observed_length); 1792 if (!ack_info.nack_ranges.empty()) { 1793 ack_size += kNumberOfNackRangesSize + kNumberOfRevivedPacketsSize; 1794 ack_size += min(ack_info.nack_ranges.size(), kMaxNackRanges) * 1795 (missing_sequence_number_length + PACKET_1BYTE_SEQUENCE_NUMBER); 1796 ack_size += min(ack.revived_packets.size(), 1797 kMaxRevivedPackets) * largest_observed_length; 1798 } 1799 1800 // In version 23, if the ack will be truncated due to too many nack ranges, 1801 // then do not include the number of timestamps (1 byte). 1802 if (version() > QUIC_VERSION_22 && 1803 ack_info.nack_ranges.size() <= kMaxNackRanges) { 1804 // 1 byte for the number of timestamps. 1805 ack_size += 1; 1806 if (ack.received_packet_times.size() > 0) { 1807 // 1 byte for sequence number, 4 bytes for timestamp for the first 1808 // packet. 1809 ack_size += 5; 1810 1811 // 1 byte for sequence number, 2 bytes for timestamp for the other 1812 // packets. 1813 ack_size += 3 * (ack.received_packet_times.size() - 1); 1814 } 1815 } 1816 1817 return ack_size; 1818 } 1819 1820 size_t QuicFramer::ComputeFrameLength( 1821 const QuicFrame& frame, 1822 bool last_frame_in_packet, 1823 InFecGroup is_in_fec_group, 1824 QuicSequenceNumberLength sequence_number_length) { 1825 switch (frame.type) { 1826 case STREAM_FRAME: 1827 return GetMinStreamFrameSize(frame.stream_frame->stream_id, 1828 frame.stream_frame->offset, 1829 last_frame_in_packet, 1830 is_in_fec_group) + 1831 frame.stream_frame->data.TotalBufferSize(); 1832 case ACK_FRAME: { 1833 return GetAckFrameSize(*frame.ack_frame, sequence_number_length); 1834 } 1835 case CONGESTION_FEEDBACK_FRAME: { 1836 size_t len = kQuicFrameTypeSize; 1837 const QuicCongestionFeedbackFrame& congestion_feedback = 1838 *frame.congestion_feedback_frame; 1839 len += 1; // Congestion feedback type. 1840 1841 switch (congestion_feedback.type) { 1842 case kTCP: 1843 len += 2; // Receive window. 1844 break; 1845 default: 1846 set_detailed_error("Illegal feedback type."); 1847 DVLOG(1) << "Illegal feedback type: " << congestion_feedback.type; 1848 break; 1849 } 1850 return len; 1851 } 1852 case STOP_WAITING_FRAME: 1853 return GetStopWaitingFrameSize(sequence_number_length); 1854 case PING_FRAME: 1855 // Ping has no payload. 1856 return kQuicFrameTypeSize; 1857 case RST_STREAM_FRAME: 1858 return GetMinRstStreamFrameSize() + 1859 frame.rst_stream_frame->error_details.size(); 1860 case CONNECTION_CLOSE_FRAME: 1861 return GetMinConnectionCloseFrameSize() + 1862 frame.connection_close_frame->error_details.size(); 1863 case GOAWAY_FRAME: 1864 return GetMinGoAwayFrameSize() + frame.goaway_frame->reason_phrase.size(); 1865 case WINDOW_UPDATE_FRAME: 1866 return GetWindowUpdateFrameSize(); 1867 case BLOCKED_FRAME: 1868 return GetBlockedFrameSize(); 1869 case PADDING_FRAME: 1870 DCHECK(false); 1871 return 0; 1872 case NUM_FRAME_TYPES: 1873 DCHECK(false); 1874 return 0; 1875 } 1876 1877 // Not reachable, but some Chrome compilers can't figure that out. *sigh* 1878 DCHECK(false); 1879 return 0; 1880 } 1881 1882 bool QuicFramer::AppendTypeByte(const QuicFrame& frame, 1883 bool no_stream_frame_length, 1884 QuicDataWriter* writer) { 1885 uint8 type_byte = 0; 1886 switch (frame.type) { 1887 case STREAM_FRAME: { 1888 if (frame.stream_frame == NULL) { 1889 LOG(DFATAL) << "Failed to append STREAM frame with no stream_frame."; 1890 } 1891 // Fin bit. 1892 type_byte |= frame.stream_frame->fin ? kQuicStreamFinMask : 0; 1893 1894 // Data Length bit. 1895 type_byte <<= kQuicStreamDataLengthShift; 1896 type_byte |= no_stream_frame_length ? 0: kQuicStreamDataLengthMask; 1897 1898 // Offset 3 bits. 1899 type_byte <<= kQuicStreamOffsetShift; 1900 const size_t offset_len = GetStreamOffsetSize(frame.stream_frame->offset); 1901 if (offset_len > 0) { 1902 type_byte |= offset_len - 1; 1903 } 1904 1905 // stream id 2 bits. 1906 type_byte <<= kQuicStreamIdShift; 1907 type_byte |= GetStreamIdSize(frame.stream_frame->stream_id) - 1; 1908 type_byte |= kQuicFrameTypeStreamMask; // Set Stream Frame Type to 1. 1909 break; 1910 } 1911 case ACK_FRAME: 1912 return true; 1913 case CONGESTION_FEEDBACK_FRAME: { 1914 // TODO(ianswett): Use extra 5 bits in the congestion feedback framing. 1915 type_byte = kQuicFrameTypeCongestionFeedbackMask; 1916 break; 1917 } 1918 default: 1919 type_byte = frame.type; 1920 break; 1921 } 1922 1923 return writer->WriteUInt8(type_byte); 1924 } 1925 1926 // static 1927 bool QuicFramer::AppendPacketSequenceNumber( 1928 QuicSequenceNumberLength sequence_number_length, 1929 QuicPacketSequenceNumber packet_sequence_number, 1930 QuicDataWriter* writer) { 1931 // Ensure the entire sequence number can be written. 1932 if (writer->capacity() - writer->length() < 1933 static_cast<size_t>(sequence_number_length)) { 1934 return false; 1935 } 1936 switch (sequence_number_length) { 1937 case PACKET_1BYTE_SEQUENCE_NUMBER: 1938 return writer->WriteUInt8( 1939 packet_sequence_number & k1ByteSequenceNumberMask); 1940 break; 1941 case PACKET_2BYTE_SEQUENCE_NUMBER: 1942 return writer->WriteUInt16( 1943 packet_sequence_number & k2ByteSequenceNumberMask); 1944 break; 1945 case PACKET_4BYTE_SEQUENCE_NUMBER: 1946 return writer->WriteUInt32( 1947 packet_sequence_number & k4ByteSequenceNumberMask); 1948 break; 1949 case PACKET_6BYTE_SEQUENCE_NUMBER: 1950 return writer->WriteUInt48( 1951 packet_sequence_number & k6ByteSequenceNumberMask); 1952 break; 1953 default: 1954 DCHECK(false) << "sequence_number_length: " << sequence_number_length; 1955 return false; 1956 } 1957 } 1958 1959 bool QuicFramer::AppendStreamFrame( 1960 const QuicStreamFrame& frame, 1961 bool no_stream_frame_length, 1962 QuicDataWriter* writer) { 1963 if (!writer->WriteBytes(&frame.stream_id, GetStreamIdSize(frame.stream_id))) { 1964 LOG(DFATAL) << "Writing stream id size failed."; 1965 return false; 1966 } 1967 if (!writer->WriteBytes(&frame.offset, GetStreamOffsetSize(frame.offset))) { 1968 LOG(DFATAL) << "Writing offset size failed."; 1969 return false; 1970 } 1971 if (!no_stream_frame_length) { 1972 if (!writer->WriteUInt16(frame.data.TotalBufferSize())) { 1973 LOG(DFATAL) << "Writing stream frame length failed"; 1974 return false; 1975 } 1976 } 1977 1978 if (!writer->WriteIOVector(frame.data)) { 1979 LOG(DFATAL) << "Writing frame data failed."; 1980 return false; 1981 } 1982 return true; 1983 } 1984 1985 // static 1986 void QuicFramer::set_version(const QuicVersion version) { 1987 DCHECK(IsSupportedVersion(version)) << QuicVersionToString(version); 1988 quic_version_ = version; 1989 } 1990 1991 bool QuicFramer::AppendAckFrameAndTypeByte( 1992 const QuicPacketHeader& header, 1993 const QuicAckFrame& frame, 1994 QuicDataWriter* writer) { 1995 AckFrameInfo ack_info = GetAckFrameInfo(frame); 1996 QuicPacketSequenceNumber ack_largest_observed = frame.largest_observed; 1997 QuicSequenceNumberLength largest_observed_length = 1998 GetMinSequenceNumberLength(ack_largest_observed); 1999 QuicSequenceNumberLength missing_sequence_number_length = 2000 GetMinSequenceNumberLength(ack_info.max_delta); 2001 // Determine whether we need to truncate ranges. 2002 size_t available_range_bytes = writer->capacity() - writer->length() - 2003 kNumberOfRevivedPacketsSize - kNumberOfNackRangesSize - 2004 GetMinAckFrameSize(header.public_header.sequence_number_length, 2005 largest_observed_length); 2006 size_t max_num_ranges = available_range_bytes / 2007 (missing_sequence_number_length + PACKET_1BYTE_SEQUENCE_NUMBER); 2008 max_num_ranges = min(kMaxNackRanges, max_num_ranges); 2009 bool truncated = ack_info.nack_ranges.size() > max_num_ranges; 2010 DVLOG_IF(1, truncated) << "Truncating ack from " 2011 << ack_info.nack_ranges.size() << " ranges to " 2012 << max_num_ranges; 2013 // Write out the type byte by setting the low order bits and doing shifts 2014 // to make room for the next bit flags to be set. 2015 // Whether there are any nacks. 2016 uint8 type_byte = ack_info.nack_ranges.empty() ? 0 : kQuicHasNacksMask; 2017 2018 // truncating bit. 2019 type_byte <<= kQuicAckTruncatedShift; 2020 type_byte |= truncated ? kQuicAckTruncatedMask : 0; 2021 2022 // Largest observed sequence number length. 2023 type_byte <<= kQuicSequenceNumberLengthShift; 2024 type_byte |= GetSequenceNumberFlags(largest_observed_length); 2025 2026 // Missing sequence number length. 2027 type_byte <<= kQuicSequenceNumberLengthShift; 2028 type_byte |= GetSequenceNumberFlags(missing_sequence_number_length); 2029 2030 type_byte |= kQuicFrameTypeAckMask; 2031 2032 if (!writer->WriteUInt8(type_byte)) { 2033 return false; 2034 } 2035 2036 QuicPacketEntropyHash ack_entropy_hash = frame.entropy_hash; 2037 NackRangeMap::reverse_iterator ack_iter = ack_info.nack_ranges.rbegin(); 2038 if (truncated) { 2039 // Skip the nack ranges which the truncated ack won't include and set 2040 // a correct largest observed for the truncated ack. 2041 for (size_t i = 1; i < (ack_info.nack_ranges.size() - max_num_ranges); 2042 ++i) { 2043 ++ack_iter; 2044 } 2045 // If the last range is followed by acks, include them. 2046 // If the last range is followed by another range, specify the end of the 2047 // range as the largest_observed. 2048 ack_largest_observed = ack_iter->first - 1; 2049 // Also update the entropy so it matches the largest observed. 2050 ack_entropy_hash = entropy_calculator_->EntropyHash(ack_largest_observed); 2051 ++ack_iter; 2052 } 2053 2054 if (!writer->WriteUInt8(ack_entropy_hash)) { 2055 return false; 2056 } 2057 2058 if (!AppendPacketSequenceNumber(largest_observed_length, 2059 ack_largest_observed, writer)) { 2060 return false; 2061 } 2062 2063 uint64 delta_time_largest_observed_us = kUFloat16MaxValue; 2064 if (!frame.delta_time_largest_observed.IsInfinite()) { 2065 DCHECK_LE(0u, frame.delta_time_largest_observed.ToMicroseconds()); 2066 delta_time_largest_observed_us = 2067 frame.delta_time_largest_observed.ToMicroseconds(); 2068 } 2069 2070 if (!writer->WriteUFloat16(delta_time_largest_observed_us)) { 2071 return false; 2072 } 2073 2074 // Timestamp goes at the end of the required fields. 2075 if (version() > QUIC_VERSION_22 && !truncated) { 2076 if (!AppendTimestampToAckFrame(frame, writer)) { 2077 return false; 2078 } 2079 } 2080 2081 if (ack_info.nack_ranges.empty()) { 2082 return true; 2083 } 2084 2085 const uint8 num_missing_ranges = 2086 min(ack_info.nack_ranges.size(), max_num_ranges); 2087 if (!writer->WriteBytes(&num_missing_ranges, 1)) { 2088 return false; 2089 } 2090 2091 int num_ranges_written = 0; 2092 QuicPacketSequenceNumber last_sequence_written = ack_largest_observed; 2093 for (; ack_iter != ack_info.nack_ranges.rend(); ++ack_iter) { 2094 // Calculate the delta to the last number in the range. 2095 QuicPacketSequenceNumber missing_delta = 2096 last_sequence_written - (ack_iter->first + ack_iter->second); 2097 if (!AppendPacketSequenceNumber(missing_sequence_number_length, 2098 missing_delta, writer)) { 2099 return false; 2100 } 2101 if (!AppendPacketSequenceNumber(PACKET_1BYTE_SEQUENCE_NUMBER, 2102 ack_iter->second, writer)) { 2103 return false; 2104 } 2105 // Subtract 1 so a missing_delta of 0 means an adjacent range. 2106 last_sequence_written = ack_iter->first - 1; 2107 ++num_ranges_written; 2108 } 2109 DCHECK_EQ(num_missing_ranges, num_ranges_written); 2110 2111 // Append revived packets. 2112 // If not all the revived packets fit, only mention the ones that do. 2113 uint8 num_revived_packets = min(frame.revived_packets.size(), 2114 kMaxRevivedPackets); 2115 num_revived_packets = min( 2116 static_cast<size_t>(num_revived_packets), 2117 (writer->capacity() - writer->length()) / largest_observed_length); 2118 if (!writer->WriteBytes(&num_revived_packets, 1)) { 2119 return false; 2120 } 2121 2122 SequenceNumberSet::const_iterator iter = frame.revived_packets.begin(); 2123 for (int i = 0; i < num_revived_packets; ++i, ++iter) { 2124 LOG_IF(DFATAL, !ContainsKey(frame.missing_packets, *iter)); 2125 if (!AppendPacketSequenceNumber(largest_observed_length, 2126 *iter, writer)) { 2127 return false; 2128 } 2129 } 2130 2131 return true; 2132 } 2133 2134 bool QuicFramer::AppendCongestionFeedbackFrame( 2135 const QuicCongestionFeedbackFrame& frame, 2136 QuicDataWriter* writer) { 2137 if (!writer->WriteBytes(&frame.type, 1)) { 2138 return false; 2139 } 2140 2141 switch (frame.type) { 2142 case kTCP: { 2143 const CongestionFeedbackMessageTCP& tcp = frame.tcp; 2144 DCHECK_LE(tcp.receive_window, 1u << 20); 2145 // Simple bit packing, don't send the 4 least significant bits. 2146 uint16 receive_window = static_cast<uint16>(tcp.receive_window >> 4); 2147 if (!writer->WriteUInt16(receive_window)) { 2148 return false; 2149 } 2150 break; 2151 } 2152 default: 2153 return false; 2154 } 2155 2156 return true; 2157 } 2158 2159 bool QuicFramer::AppendTimestampToAckFrame(const QuicAckFrame& frame, 2160 QuicDataWriter* writer) { 2161 DCHECK_GE(version(), QUIC_VERSION_23); 2162 DCHECK_GE(numeric_limits<uint8>::max(), frame.received_packet_times.size()); 2163 // num_received_packets is only 1 byte. 2164 if (frame.received_packet_times.size() > numeric_limits<uint8>::max()) { 2165 return false; 2166 } 2167 2168 uint8 num_received_packets = frame.received_packet_times.size(); 2169 2170 if (!writer->WriteBytes(&num_received_packets, 1)) { 2171 return false; 2172 } 2173 if (num_received_packets == 0) { 2174 return true; 2175 } 2176 2177 PacketTimeList::const_iterator it = frame.received_packet_times.begin(); 2178 QuicPacketSequenceNumber sequence_number = it->first; 2179 QuicPacketSequenceNumber delta_from_largest_observed = 2180 frame.largest_observed - sequence_number; 2181 2182 DCHECK_GE(numeric_limits<uint8>::max(), delta_from_largest_observed); 2183 if (delta_from_largest_observed > numeric_limits<uint8>::max()) { 2184 return false; 2185 } 2186 2187 if (!writer->WriteUInt8( 2188 delta_from_largest_observed & k1ByteSequenceNumberMask)) { 2189 return false; 2190 } 2191 2192 // Use the lowest 4 bytes of the time delta from the creation_time_. 2193 const uint64 time_epoch_delta_us = GG_UINT64_C(1) << 32; 2194 uint32 time_delta_us = 2195 static_cast<uint32>(it->second.Subtract(creation_time_).ToMicroseconds() 2196 & (time_epoch_delta_us - 1)); 2197 if (!writer->WriteBytes(&time_delta_us, sizeof(time_delta_us))) { 2198 return false; 2199 } 2200 2201 QuicTime prev_time = it->second; 2202 2203 for (++it; it != frame.received_packet_times.end(); ++it) { 2204 sequence_number = it->first; 2205 delta_from_largest_observed = frame.largest_observed - sequence_number; 2206 2207 if (delta_from_largest_observed > numeric_limits<uint8>::max()) { 2208 return false; 2209 } 2210 2211 if (!writer->WriteUInt8( 2212 delta_from_largest_observed & k1ByteSequenceNumberMask)) { 2213 return false; 2214 } 2215 2216 uint64 time_delta_us = it->second.Subtract(prev_time).ToMicroseconds(); 2217 prev_time = it->second; 2218 if (!writer->WriteUFloat16(time_delta_us)) { 2219 return false; 2220 } 2221 } 2222 return true; 2223 } 2224 2225 bool QuicFramer::AppendStopWaitingFrame( 2226 const QuicPacketHeader& header, 2227 const QuicStopWaitingFrame& frame, 2228 QuicDataWriter* writer) { 2229 DCHECK_GE(header.packet_sequence_number, frame.least_unacked); 2230 const QuicPacketSequenceNumber least_unacked_delta = 2231 header.packet_sequence_number - frame.least_unacked; 2232 const QuicPacketSequenceNumber length_shift = 2233 header.public_header.sequence_number_length * 8; 2234 if (!writer->WriteUInt8(frame.entropy_hash)) { 2235 LOG(DFATAL) << " hash failed"; 2236 return false; 2237 } 2238 2239 if (least_unacked_delta >> length_shift > 0) { 2240 LOG(DFATAL) << "sequence_number_length " 2241 << header.public_header.sequence_number_length 2242 << " is too small for least_unacked_delta: " 2243 << least_unacked_delta; 2244 return false; 2245 } 2246 if (!AppendPacketSequenceNumber(header.public_header.sequence_number_length, 2247 least_unacked_delta, writer)) { 2248 LOG(DFATAL) << " seq failed: " 2249 << header.public_header.sequence_number_length; 2250 return false; 2251 } 2252 2253 return true; 2254 } 2255 2256 bool QuicFramer::AppendRstStreamFrame( 2257 const QuicRstStreamFrame& frame, 2258 QuicDataWriter* writer) { 2259 if (!writer->WriteUInt32(frame.stream_id)) { 2260 return false; 2261 } 2262 2263 if (!writer->WriteUInt64(frame.byte_offset)) { 2264 return false; 2265 } 2266 2267 uint32 error_code = static_cast<uint32>(frame.error_code); 2268 if (!writer->WriteUInt32(error_code)) { 2269 return false; 2270 } 2271 2272 if (!writer->WriteStringPiece16(frame.error_details)) { 2273 return false; 2274 } 2275 return true; 2276 } 2277 2278 bool QuicFramer::AppendConnectionCloseFrame( 2279 const QuicConnectionCloseFrame& frame, 2280 QuicDataWriter* writer) { 2281 uint32 error_code = static_cast<uint32>(frame.error_code); 2282 if (!writer->WriteUInt32(error_code)) { 2283 return false; 2284 } 2285 if (!writer->WriteStringPiece16(frame.error_details)) { 2286 return false; 2287 } 2288 return true; 2289 } 2290 2291 bool QuicFramer::AppendGoAwayFrame(const QuicGoAwayFrame& frame, 2292 QuicDataWriter* writer) { 2293 uint32 error_code = static_cast<uint32>(frame.error_code); 2294 if (!writer->WriteUInt32(error_code)) { 2295 return false; 2296 } 2297 uint32 stream_id = static_cast<uint32>(frame.last_good_stream_id); 2298 if (!writer->WriteUInt32(stream_id)) { 2299 return false; 2300 } 2301 if (!writer->WriteStringPiece16(frame.reason_phrase)) { 2302 return false; 2303 } 2304 return true; 2305 } 2306 2307 bool QuicFramer::AppendWindowUpdateFrame(const QuicWindowUpdateFrame& frame, 2308 QuicDataWriter* writer) { 2309 uint32 stream_id = static_cast<uint32>(frame.stream_id); 2310 if (!writer->WriteUInt32(stream_id)) { 2311 return false; 2312 } 2313 if (!writer->WriteUInt64(frame.byte_offset)) { 2314 return false; 2315 } 2316 return true; 2317 } 2318 2319 bool QuicFramer::AppendBlockedFrame(const QuicBlockedFrame& frame, 2320 QuicDataWriter* writer) { 2321 uint32 stream_id = static_cast<uint32>(frame.stream_id); 2322 if (!writer->WriteUInt32(stream_id)) { 2323 return false; 2324 } 2325 return true; 2326 } 2327 2328 bool QuicFramer::RaiseError(QuicErrorCode error) { 2329 DVLOG(1) << "Error detail: " << detailed_error_; 2330 set_error(error); 2331 visitor_->OnError(this); 2332 reader_.reset(NULL); 2333 return false; 2334 } 2335 2336 } // namespace net 2337