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 #ifndef QUICHE_QUIC_CORE_QUIC_FRAMER_H_ 6 #define QUICHE_QUIC_CORE_QUIC_FRAMER_H_ 7 8 #include <cstddef> 9 #include <cstdint> 10 #include <memory> 11 #include <string> 12 13 #include "absl/strings/string_view.h" 14 #include "quiche/quic/core/connection_id_generator.h" 15 #include "quiche/quic/core/crypto/quic_decrypter.h" 16 #include "quiche/quic/core/crypto/quic_encrypter.h" 17 #include "quiche/quic/core/crypto/quic_random.h" 18 #include "quiche/quic/core/quic_connection_id.h" 19 #include "quiche/quic/core/quic_packets.h" 20 #include "quiche/quic/core/quic_types.h" 21 #include "quiche/quic/platform/api/quic_export.h" 22 23 namespace quic { 24 25 namespace test { 26 class QuicFramerPeer; 27 } // namespace test 28 29 class QuicDataReader; 30 class QuicDataWriter; 31 class QuicFramer; 32 class QuicStreamFrameDataProducer; 33 34 // Number of bytes reserved for the frame type preceding each frame. 35 const size_t kQuicFrameTypeSize = 1; 36 // Number of bytes reserved for error code. 37 const size_t kQuicErrorCodeSize = 4; 38 // Number of bytes reserved to denote the length of error details field. 39 const size_t kQuicErrorDetailsLengthSize = 2; 40 41 // Maximum number of bytes reserved for stream id. 42 const size_t kQuicMaxStreamIdSize = 4; 43 // Maximum number of bytes reserved for byte offset in stream frame. 44 const size_t kQuicMaxStreamOffsetSize = 8; 45 // Number of bytes reserved to store payload length in stream frame. 46 const size_t kQuicStreamPayloadLengthSize = 2; 47 // Number of bytes to reserve for IQ Error codes (for the Connection Close, 48 // Application Close, and Reset Stream frames). 49 const size_t kQuicIetfQuicErrorCodeSize = 2; 50 // Minimum size of the IETF QUIC Error Phrase's length field 51 const size_t kIetfQuicMinErrorPhraseLengthSize = 1; 52 53 // Size in bytes reserved for the delta time of the largest observed 54 // packet number in ack frames. 55 const size_t kQuicDeltaTimeLargestObservedSize = 2; 56 // Size in bytes reserved for the number of received packets with timestamps. 57 const size_t kQuicNumTimestampsSize = 1; 58 // Size in bytes reserved for the number of missing packets in ack frames. 59 const size_t kNumberOfNackRangesSize = 1; 60 // Size in bytes reserved for the number of ack blocks in ack frames. 61 const size_t kNumberOfAckBlocksSize = 1; 62 // Maximum number of missing packet ranges that can fit within an ack frame. 63 const size_t kMaxNackRanges = (1 << (kNumberOfNackRangesSize * 8)) - 1; 64 // Maximum number of ack blocks that can fit within an ack frame. 65 const size_t kMaxAckBlocks = (1 << (kNumberOfAckBlocksSize * 8)) - 1; 66 67 // This class receives callbacks from the framer when packets 68 // are processed. 69 class QUICHE_EXPORT QuicFramerVisitorInterface { 70 public: ~QuicFramerVisitorInterface()71 virtual ~QuicFramerVisitorInterface() {} 72 73 // Called if an error is detected in the QUIC protocol. 74 virtual void OnError(QuicFramer* framer) = 0; 75 76 // Called only when |perspective_| is IS_SERVER and the framer gets a 77 // packet with version flag true and the version on the packet doesn't match 78 // |quic_version_|. The visitor should return true after it updates the 79 // version of the |framer_| to |received_version| or false to stop processing 80 // this packet. 81 virtual bool OnProtocolVersionMismatch( 82 ParsedQuicVersion received_version) = 0; 83 84 // Called when a new packet has been received, before it 85 // has been validated or processed. 86 virtual void OnPacket() = 0; 87 88 // Called only when |perspective_| is IS_CLIENT and a version negotiation 89 // packet has been parsed. 90 virtual void OnVersionNegotiationPacket( 91 const QuicVersionNegotiationPacket& packet) = 0; 92 93 // Called only when |perspective_| is IS_CLIENT and a retry packet has been 94 // parsed. |new_connection_id| contains the value of the Source Connection 95 // ID field, and |retry_token| contains the value of the Retry Token field. 96 // On versions where UsesTls() is false, 97 // |original_connection_id| contains the value of the Original Destination 98 // Connection ID field, and both |retry_integrity_tag| and 99 // |retry_without_tag| are empty. 100 // On versions where UsesTls() is true, 101 // |original_connection_id| is empty, |retry_integrity_tag| contains the 102 // value of the Retry Integrity Tag field, and |retry_without_tag| contains 103 // the entire RETRY packet except the Retry Integrity Tag field. 104 virtual void OnRetryPacket(QuicConnectionId original_connection_id, 105 QuicConnectionId new_connection_id, 106 absl::string_view retry_token, 107 absl::string_view retry_integrity_tag, 108 absl::string_view retry_without_tag) = 0; 109 110 // Called when all fields except packet number has been parsed, but has not 111 // been authenticated. If it returns false, framing for this packet will 112 // cease. 113 virtual bool OnUnauthenticatedPublicHeader( 114 const QuicPacketHeader& header) = 0; 115 116 // Called when the unauthenticated portion of the header has been parsed. 117 // If OnUnauthenticatedHeader returns false, framing for this packet will 118 // cease. 119 virtual bool OnUnauthenticatedHeader(const QuicPacketHeader& header) = 0; 120 121 // Called when a packet has been decrypted. |length| is the packet length, 122 // and |level| is the encryption level of the packet. 123 virtual void OnDecryptedPacket(size_t length, EncryptionLevel level) = 0; 124 125 // Called when the complete header of a packet had been parsed. 126 // If OnPacketHeader returns false, framing for this packet will cease. 127 virtual bool OnPacketHeader(const QuicPacketHeader& header) = 0; 128 129 // Called when the packet being processed contains multiple IETF QUIC packets, 130 // which is due to there being more data after what is covered by the length 131 // field. |packet| contains the remaining data which can be processed. 132 // Note that this is called when the framer parses the length field, before 133 // it attempts to decrypt the first payload. It is the visitor's 134 // responsibility to buffer the packet and call ProcessPacket on it 135 // after the framer is done parsing the current payload. |packet| does not 136 // own its internal buffer, the visitor should make a copy of it. 137 virtual void OnCoalescedPacket(const QuicEncryptedPacket& packet) = 0; 138 139 // Called when the packet being processed failed to decrypt. 140 // |has_decryption_key| indicates whether the framer knew which decryption 141 // key to use for this packet and already had a suitable key. 142 virtual void OnUndecryptablePacket(const QuicEncryptedPacket& packet, 143 EncryptionLevel decryption_level, 144 bool has_decryption_key) = 0; 145 146 // Called when a StreamFrame has been parsed. 147 virtual bool OnStreamFrame(const QuicStreamFrame& frame) = 0; 148 149 // Called when a CRYPTO frame has been parsed. 150 virtual bool OnCryptoFrame(const QuicCryptoFrame& frame) = 0; 151 152 // Called when largest acked of an AckFrame has been parsed. 153 virtual bool OnAckFrameStart(QuicPacketNumber largest_acked, 154 QuicTime::Delta ack_delay_time) = 0; 155 156 // Called when ack range [start, end) of an AckFrame has been parsed. 157 virtual bool OnAckRange(QuicPacketNumber start, QuicPacketNumber end) = 0; 158 159 // Called when a timestamp in the AckFrame has been parsed. 160 virtual bool OnAckTimestamp(QuicPacketNumber packet_number, 161 QuicTime timestamp) = 0; 162 163 // Called after the last ack range in an AckFrame has been parsed. 164 // |start| is the starting value of the last ack range. |ecn_counts| are 165 // the reported ECN counts in the ack frame, if present. 166 virtual bool OnAckFrameEnd( 167 QuicPacketNumber start, 168 const std::optional<QuicEcnCounts>& ecn_counts) = 0; 169 170 // Called when a StopWaitingFrame has been parsed. 171 virtual bool OnStopWaitingFrame(const QuicStopWaitingFrame& frame) = 0; 172 173 // Called when a QuicPaddingFrame has been parsed. 174 virtual bool OnPaddingFrame(const QuicPaddingFrame& frame) = 0; 175 176 // Called when a PingFrame has been parsed. 177 virtual bool OnPingFrame(const QuicPingFrame& frame) = 0; 178 179 // Called when a RstStreamFrame has been parsed. 180 virtual bool OnRstStreamFrame(const QuicRstStreamFrame& frame) = 0; 181 182 // Called when a ConnectionCloseFrame, of any type, has been parsed. 183 virtual bool OnConnectionCloseFrame( 184 const QuicConnectionCloseFrame& frame) = 0; 185 186 // Called when a StopSendingFrame has been parsed. 187 virtual bool OnStopSendingFrame(const QuicStopSendingFrame& frame) = 0; 188 189 // Called when a PathChallengeFrame has been parsed. 190 virtual bool OnPathChallengeFrame(const QuicPathChallengeFrame& frame) = 0; 191 192 // Called when a PathResponseFrame has been parsed. 193 virtual bool OnPathResponseFrame(const QuicPathResponseFrame& frame) = 0; 194 195 // Called when a GoAwayFrame has been parsed. 196 virtual bool OnGoAwayFrame(const QuicGoAwayFrame& frame) = 0; 197 198 // Called when a WindowUpdateFrame has been parsed. 199 virtual bool OnWindowUpdateFrame(const QuicWindowUpdateFrame& frame) = 0; 200 201 // Called when a BlockedFrame has been parsed. 202 virtual bool OnBlockedFrame(const QuicBlockedFrame& frame) = 0; 203 204 // Called when a NewConnectionIdFrame has been parsed. 205 virtual bool OnNewConnectionIdFrame( 206 const QuicNewConnectionIdFrame& frame) = 0; 207 208 // Called when a RetireConnectionIdFrame has been parsed. 209 virtual bool OnRetireConnectionIdFrame( 210 const QuicRetireConnectionIdFrame& frame) = 0; 211 212 // Called when a NewTokenFrame has been parsed. 213 virtual bool OnNewTokenFrame(const QuicNewTokenFrame& frame) = 0; 214 215 // Called when a message frame has been parsed. 216 virtual bool OnMessageFrame(const QuicMessageFrame& frame) = 0; 217 218 // Called when a handshake done frame has been parsed. 219 virtual bool OnHandshakeDoneFrame(const QuicHandshakeDoneFrame& frame) = 0; 220 221 // Called when an AckFrequencyFrame has been parsed. 222 virtual bool OnAckFrequencyFrame(const QuicAckFrequencyFrame& frame) = 0; 223 224 // Called when a packet has been completely processed. 225 virtual void OnPacketComplete() = 0; 226 227 // Called to check whether |token| is a valid stateless reset token. 228 virtual bool IsValidStatelessResetToken( 229 const StatelessResetToken& token) const = 0; 230 231 // Called when an IETF stateless reset packet has been parsed and validated 232 // with the stateless reset token. 233 virtual void OnAuthenticatedIetfStatelessResetPacket( 234 const QuicIetfStatelessResetPacket& packet) = 0; 235 236 // Called when an IETF MaxStreams frame has been parsed. 237 virtual bool OnMaxStreamsFrame(const QuicMaxStreamsFrame& frame) = 0; 238 239 // Called when an IETF StreamsBlocked frame has been parsed. 240 virtual bool OnStreamsBlockedFrame(const QuicStreamsBlockedFrame& frame) = 0; 241 242 // Called when a Key Phase Update has been initiated. This is called for both 243 // locally and peer initiated key updates. If the key update was locally 244 // initiated, this does not indicate the peer has received the key update yet. 245 virtual void OnKeyUpdate(KeyUpdateReason reason) = 0; 246 247 // Called on the first decrypted packet in each key phase (including the 248 // first key phase.) 249 virtual void OnDecryptedFirstPacketInKeyPhase() = 0; 250 251 // Called when the framer needs to generate a decrypter for the next key 252 // phase. Each call should generate the key for phase n+1. 253 virtual std::unique_ptr<QuicDecrypter> 254 AdvanceKeysAndCreateCurrentOneRttDecrypter() = 0; 255 256 // Called when the framer needs to generate an encrypter. The key corresponds 257 // to the key phase of the last decrypter returned by 258 // AdvanceKeysAndCreateCurrentOneRttDecrypter(). 259 virtual std::unique_ptr<QuicEncrypter> CreateCurrentOneRttEncrypter() = 0; 260 }; 261 262 // Class for parsing and constructing QUIC packets. It has a 263 // QuicFramerVisitorInterface that is called when packets are parsed. 264 class QUICHE_EXPORT QuicFramer { 265 public: 266 // Constructs a new framer that installs a kNULL QuicEncrypter and 267 // QuicDecrypter for level ENCRYPTION_INITIAL. |supported_versions| specifies 268 // the list of supported QUIC versions. |quic_version_| is set to the maximum 269 // version in |supported_versions|. 270 QuicFramer(const ParsedQuicVersionVector& supported_versions, 271 QuicTime creation_time, Perspective perspective, 272 uint8_t expected_server_connection_id_length); 273 QuicFramer(const QuicFramer&) = delete; 274 QuicFramer& operator=(const QuicFramer&) = delete; 275 276 virtual ~QuicFramer(); 277 278 // Returns true if |version| is a supported protocol version. 279 bool IsSupportedVersion(const ParsedQuicVersion version) const; 280 281 // Set callbacks to be called from the framer. A visitor must be set, or 282 // else the framer will likely crash. It is acceptable for the visitor 283 // to do nothing. If this is called multiple times, only the last visitor 284 // will be used. set_visitor(QuicFramerVisitorInterface * visitor)285 void set_visitor(QuicFramerVisitorInterface* visitor) { visitor_ = visitor; } 286 supported_versions()287 const ParsedQuicVersionVector& supported_versions() const { 288 return supported_versions_; 289 } 290 transport_version()291 QuicTransportVersion transport_version() const { 292 return version_.transport_version; 293 } 294 version()295 ParsedQuicVersion version() const { return version_; } 296 297 void set_version(const ParsedQuicVersion version); 298 299 // Does not QUICHE_DCHECK for supported version. Used by tests to set 300 // unsupported version to trigger version negotiation. set_version_for_tests(const ParsedQuicVersion version)301 void set_version_for_tests(const ParsedQuicVersion version) { 302 version_ = version; 303 } 304 error()305 QuicErrorCode error() const { return error_; } 306 307 // Allows enabling or disabling of timestamp processing and serialization. 308 // TODO(ianswett): Remove the const once timestamps are negotiated via 309 // transport params. set_process_timestamps(bool process_timestamps)310 void set_process_timestamps(bool process_timestamps) const { 311 process_timestamps_ = process_timestamps; 312 } 313 314 // Sets the max number of receive timestamps to send per ACK frame. 315 // TODO(wub): Remove the const once timestamps are negotiated via 316 // transport params. set_max_receive_timestamps_per_ack(uint32_t max_timestamps)317 void set_max_receive_timestamps_per_ack(uint32_t max_timestamps) const { 318 max_receive_timestamps_per_ack_ = max_timestamps; 319 } 320 321 // Sets the exponent to use when writing/reading ACK receive timestamps. set_receive_timestamps_exponent(uint32_t exponent)322 void set_receive_timestamps_exponent(uint32_t exponent) const { 323 receive_timestamps_exponent_ = exponent; 324 } 325 326 // Pass a UDP packet into the framer for parsing. 327 // Return true if the packet was processed successfully. |packet| must be a 328 // single, complete UDP packet (not a frame of a packet). This packet 329 // might be null padded past the end of the payload, which will be correctly 330 // ignored. 331 bool ProcessPacket(const QuicEncryptedPacket& packet); 332 333 // Whether we are in the middle of a call to this->ProcessPacket. is_processing_packet()334 bool is_processing_packet() const { return is_processing_packet_; } 335 336 // Largest size in bytes of all stream frame fields without the payload. 337 static size_t GetMinStreamFrameSize(QuicTransportVersion version, 338 QuicStreamId stream_id, 339 QuicStreamOffset offset, 340 bool last_frame_in_packet, 341 size_t data_length); 342 // Returns the overhead of framing a CRYPTO frame with the specific offset and 343 // data length provided, but not counting the size of the data payload. 344 static size_t GetMinCryptoFrameSize(QuicStreamOffset offset, 345 QuicPacketLength data_length); 346 static size_t GetMessageFrameSize(bool last_frame_in_packet, 347 QuicByteCount length); 348 // Size in bytes of all ack frame fields without the missing packets or ack 349 // blocks. 350 static size_t GetMinAckFrameSize(QuicTransportVersion version, 351 const QuicAckFrame& ack_frame, 352 uint32_t local_ack_delay_exponent, 353 bool use_ietf_ack_with_receive_timestamp); 354 // Size in bytes of a stop waiting frame. 355 static size_t GetStopWaitingFrameSize( 356 QuicPacketNumberLength packet_number_length); 357 // Size in bytes of all reset stream frame fields. 358 static size_t GetRstStreamFrameSize(QuicTransportVersion version, 359 const QuicRstStreamFrame& frame); 360 // Size in bytes of all ack frenquency frame fields. 361 static size_t GetAckFrequencyFrameSize(const QuicAckFrequencyFrame& frame); 362 // Size in bytes of all connection close frame fields, including the error 363 // details. 364 static size_t GetConnectionCloseFrameSize( 365 QuicTransportVersion version, const QuicConnectionCloseFrame& frame); 366 // Size in bytes of all GoAway frame fields without the reason phrase. 367 static size_t GetMinGoAwayFrameSize(); 368 // Size in bytes of all WindowUpdate frame fields. 369 // For version 99, determines whether a MAX DATA or MAX STREAM DATA frame will 370 // be generated and calculates the appropriate size. 371 static size_t GetWindowUpdateFrameSize(QuicTransportVersion version, 372 const QuicWindowUpdateFrame& frame); 373 // Size in bytes of all MaxStreams frame fields. 374 static size_t GetMaxStreamsFrameSize(QuicTransportVersion version, 375 const QuicMaxStreamsFrame& frame); 376 // Size in bytes of all StreamsBlocked frame fields. 377 static size_t GetStreamsBlockedFrameSize( 378 QuicTransportVersion version, const QuicStreamsBlockedFrame& frame); 379 // Size in bytes of all Blocked frame fields. 380 static size_t GetBlockedFrameSize(QuicTransportVersion version, 381 const QuicBlockedFrame& frame); 382 // Size in bytes of PathChallenge frame. 383 static size_t GetPathChallengeFrameSize(const QuicPathChallengeFrame& frame); 384 // Size in bytes of PathResponse frame. 385 static size_t GetPathResponseFrameSize(const QuicPathResponseFrame& frame); 386 // Size in bytes required to serialize the stream id. 387 static size_t GetStreamIdSize(QuicStreamId stream_id); 388 // Size in bytes required to serialize the stream offset. 389 static size_t GetStreamOffsetSize(QuicStreamOffset offset); 390 // Size in bytes for a serialized new connection id frame 391 static size_t GetNewConnectionIdFrameSize( 392 const QuicNewConnectionIdFrame& frame); 393 394 // Size in bytes for a serialized retire connection id frame 395 static size_t GetRetireConnectionIdFrameSize( 396 const QuicRetireConnectionIdFrame& frame); 397 398 // Size in bytes for a serialized new token frame 399 static size_t GetNewTokenFrameSize(const QuicNewTokenFrame& frame); 400 401 // Size in bytes required for a serialized stop sending frame. 402 static size_t GetStopSendingFrameSize(const QuicStopSendingFrame& frame); 403 404 // Size in bytes required for a serialized retransmittable control |frame|. 405 static size_t GetRetransmittableControlFrameSize(QuicTransportVersion version, 406 const QuicFrame& frame); 407 408 // Returns the number of bytes added to the packet for the specified frame, 409 // and 0 if the frame doesn't fit. Includes the header size for the first 410 // frame. 411 size_t GetSerializedFrameLength(const QuicFrame& frame, size_t free_bytes, 412 bool first_frame_in_packet, 413 bool last_frame_in_packet, 414 QuicPacketNumberLength packet_number_length); 415 416 // Returns the associated data from the encrypted packet |encrypted| as a 417 // stringpiece. 418 static absl::string_view GetAssociatedDataFromEncryptedPacket( 419 QuicTransportVersion version, const QuicEncryptedPacket& encrypted, 420 uint8_t destination_connection_id_length, 421 uint8_t source_connection_id_length, bool includes_version, 422 bool includes_diversification_nonce, 423 QuicPacketNumberLength packet_number_length, 424 quiche::QuicheVariableLengthIntegerLength retry_token_length_length, 425 uint64_t retry_token_length, 426 quiche::QuicheVariableLengthIntegerLength length_length); 427 428 // Parses the unencrypted fields in a QUIC header using |reader| as input, 429 // stores the result in the other parameters. 430 // |expected_destination_connection_id_length| is only used for short headers. 431 // When server connection IDs are generated by a 432 // ConnectionIdGeneartor interface, and callers need an accurate 433 // Destination Connection ID for short header packets, call 434 // ParsePublicHeaderDispatcherShortHeaderLengthUnknown() instead. 435 static QuicErrorCode ParsePublicHeader( 436 QuicDataReader* reader, uint8_t expected_destination_connection_id_length, 437 bool ietf_format, uint8_t* first_byte, PacketHeaderFormat* format, 438 bool* version_present, bool* has_length_prefix, 439 QuicVersionLabel* version_label, ParsedQuicVersion* parsed_version, 440 QuicConnectionId* destination_connection_id, 441 QuicConnectionId* source_connection_id, 442 QuicLongHeaderType* long_packet_type, 443 quiche::QuicheVariableLengthIntegerLength* retry_token_length_length, 444 absl::string_view* retry_token, std::string* detailed_error); 445 446 // Parses the unencrypted fields in |packet| and stores them in the other 447 // parameters. This can only be called on the server. 448 // |expected_destination_connection_id_length| is only used 449 // for short headers. When callers need an accurate Destination Connection ID 450 // specifically for short header packets, call 451 // ParsePublicHeaderDispatcherShortHeaderLengthUnknown() instead. 452 static QuicErrorCode ParsePublicHeaderDispatcher( 453 const QuicEncryptedPacket& packet, 454 uint8_t expected_destination_connection_id_length, 455 PacketHeaderFormat* format, QuicLongHeaderType* long_packet_type, 456 bool* version_present, bool* has_length_prefix, 457 QuicVersionLabel* version_label, ParsedQuicVersion* parsed_version, 458 QuicConnectionId* destination_connection_id, 459 QuicConnectionId* source_connection_id, 460 std::optional<absl::string_view>* retry_token, 461 std::string* detailed_error); 462 463 // Parses the unencrypted fields in |packet| and stores them in the other 464 // parameters. The only callers that should use this method are ones where 465 // (1) the short-header connection ID length is only known by looking at the 466 // connection ID itself (and |generator| can provide the answer), and (2) 467 // the caller is interested in the parsed contents even if the packet has a 468 // short header. Some callers are only interested in parsing long header 469 // packets to peer into the handshake, and should use 470 // ParsePublicHeaderDispatcher instead. 471 static QuicErrorCode ParsePublicHeaderDispatcherShortHeaderLengthUnknown( 472 const QuicEncryptedPacket& packet, PacketHeaderFormat* format, 473 QuicLongHeaderType* long_packet_type, bool* version_present, 474 bool* has_length_prefix, QuicVersionLabel* version_label, 475 ParsedQuicVersion* parsed_version, 476 QuicConnectionId* destination_connection_id, 477 QuicConnectionId* source_connection_id, 478 std::optional<absl::string_view>* retry_token, 479 std::string* detailed_error, ConnectionIdGeneratorInterface& generator); 480 481 // Serializes a packet containing |frames| into |buffer|. 482 // Returns the length of the packet, which must not be longer than 483 // |packet_length|. Returns 0 if it fails to serialize. 484 size_t BuildDataPacket(const QuicPacketHeader& header, 485 const QuicFrames& frames, char* buffer, 486 size_t packet_length, EncryptionLevel level); 487 488 // Returns a new public reset packet. 489 static std::unique_ptr<QuicEncryptedPacket> BuildPublicResetPacket( 490 const QuicPublicResetPacket& packet); 491 492 // Returns the minimal stateless reset packet length. 493 static size_t GetMinStatelessResetPacketLength(); 494 495 // Returns a new IETF stateless reset packet. 496 static std::unique_ptr<QuicEncryptedPacket> BuildIetfStatelessResetPacket( 497 QuicConnectionId connection_id, size_t received_packet_length, 498 StatelessResetToken stateless_reset_token); 499 500 // Returns a new IETF stateless reset packet with random bytes generated from 501 // |random|->InsecureRandBytes(). NOTE: the first two bits of the random bytes 502 // will be modified to 01b to make it look like a short header packet. 503 static std::unique_ptr<QuicEncryptedPacket> BuildIetfStatelessResetPacket( 504 QuicConnectionId connection_id, size_t received_packet_length, 505 StatelessResetToken stateless_reset_token, QuicRandom* random); 506 507 // Returns a new version negotiation packet. 508 static std::unique_ptr<QuicEncryptedPacket> BuildVersionNegotiationPacket( 509 QuicConnectionId server_connection_id, 510 QuicConnectionId client_connection_id, bool ietf_quic, 511 bool use_length_prefix, const ParsedQuicVersionVector& versions); 512 513 // Returns a new IETF version negotiation packet. 514 static std::unique_ptr<QuicEncryptedPacket> BuildIetfVersionNegotiationPacket( 515 bool use_length_prefix, QuicConnectionId server_connection_id, 516 QuicConnectionId client_connection_id, 517 const ParsedQuicVersionVector& versions); 518 519 // If header.version_flag is set, the version in the 520 // packet will be set -- but it will be set from version_ not 521 // header.versions. 522 bool AppendIetfHeaderTypeByte(const QuicPacketHeader& header, 523 QuicDataWriter* writer); 524 bool AppendIetfPacketHeader(const QuicPacketHeader& header, 525 QuicDataWriter* writer, 526 size_t* length_field_offset); 527 bool WriteIetfLongHeaderLength(const QuicPacketHeader& header, 528 QuicDataWriter* writer, 529 size_t length_field_offset, 530 EncryptionLevel level); 531 bool AppendTypeByte(const QuicFrame& frame, bool last_frame_in_packet, 532 QuicDataWriter* writer); 533 bool AppendIetfFrameType(const QuicFrame& frame, bool last_frame_in_packet, 534 QuicDataWriter* writer); 535 size_t AppendIetfFrames(const QuicFrames& frames, QuicDataWriter* writer); 536 bool AppendStreamFrame(const QuicStreamFrame& frame, 537 bool no_stream_frame_length, QuicDataWriter* writer); 538 bool AppendCryptoFrame(const QuicCryptoFrame& frame, QuicDataWriter* writer); 539 bool AppendAckFrequencyFrame(const QuicAckFrequencyFrame& frame, 540 QuicDataWriter* writer); 541 542 // SetDecrypter sets the primary decrypter, replacing any that already exists. 543 // If an alternative decrypter is in place then the function QUICHE_DCHECKs. 544 // This is intended for cases where one knows that future packets will be 545 // using the new decrypter and the previous decrypter is now obsolete. |level| 546 // indicates the encryption level of the new decrypter. 547 void SetDecrypter(EncryptionLevel level, 548 std::unique_ptr<QuicDecrypter> decrypter); 549 550 // SetAlternativeDecrypter sets a decrypter that may be used to decrypt 551 // future packets. |level| indicates the encryption level of the decrypter. If 552 // |latch_once_used| is true, then the first time that the decrypter is 553 // successful it will replace the primary decrypter. Otherwise both 554 // decrypters will remain active and the primary decrypter will be the one 555 // last used. 556 void SetAlternativeDecrypter(EncryptionLevel level, 557 std::unique_ptr<QuicDecrypter> decrypter, 558 bool latch_once_used); 559 560 void InstallDecrypter(EncryptionLevel level, 561 std::unique_ptr<QuicDecrypter> decrypter); 562 void RemoveDecrypter(EncryptionLevel level); 563 564 // Enables key update support. 565 void SetKeyUpdateSupportForConnection(bool enabled); 566 // Discard the decrypter for the previous key phase. 567 void DiscardPreviousOneRttKeys(); 568 // Update the key phase. 569 bool DoKeyUpdate(KeyUpdateReason reason); 570 // Returns the count of packets received that appeared to attempt a key 571 // update but failed decryption which have been received since the last 572 // successfully decrypted packet. 573 QuicPacketCount PotentialPeerKeyUpdateAttemptCount() const; 574 575 const QuicDecrypter* GetDecrypter(EncryptionLevel level) const; 576 const QuicDecrypter* decrypter() const; 577 const QuicDecrypter* alternative_decrypter() const; 578 579 // Changes the encrypter used for level |level| to |encrypter|. 580 void SetEncrypter(EncryptionLevel level, 581 std::unique_ptr<QuicEncrypter> encrypter); 582 583 // Called to remove encrypter of encryption |level|. 584 void RemoveEncrypter(EncryptionLevel level); 585 586 // Sets the encrypter and decrypter for the ENCRYPTION_INITIAL level. 587 void SetInitialObfuscators(QuicConnectionId connection_id); 588 589 // Encrypts a payload in |buffer|. |ad_len| is the length of the associated 590 // data. |total_len| is the length of the associated data plus plaintext. 591 // |buffer_len| is the full length of the allocated buffer. 592 size_t EncryptInPlace(EncryptionLevel level, QuicPacketNumber packet_number, 593 size_t ad_len, size_t total_len, size_t buffer_len, 594 char* buffer); 595 596 // Returns the length of the data encrypted into |buffer| if |buffer_len| is 597 // long enough, and otherwise 0. 598 size_t EncryptPayload(EncryptionLevel level, QuicPacketNumber packet_number, 599 const QuicPacket& packet, char* buffer, 600 size_t buffer_len); 601 602 // Returns the length of the ciphertext that would be generated by encrypting 603 // to plaintext of size |plaintext_size| at the given level. 604 size_t GetCiphertextSize(EncryptionLevel level, size_t plaintext_size) const; 605 606 // Returns the maximum length of plaintext that can be encrypted 607 // to ciphertext no larger than |ciphertext_size|. 608 size_t GetMaxPlaintextSize(size_t ciphertext_size); 609 610 // Returns the maximum number of packets that can be safely encrypted with 611 // the active AEAD. 1-RTT keys must be set before calling this method. 612 QuicPacketCount GetOneRttEncrypterConfidentialityLimit() const; 613 detailed_error()614 const std::string& detailed_error() { return detailed_error_; } 615 616 // The minimum packet number length required to represent |packet_number|. 617 static QuicPacketNumberLength GetMinPacketNumberLength( 618 QuicPacketNumber packet_number); 619 SetSupportedVersions(const ParsedQuicVersionVector & versions)620 void SetSupportedVersions(const ParsedQuicVersionVector& versions) { 621 supported_versions_ = versions; 622 version_ = versions[0]; 623 } 624 625 // Returns true if |header| is considered as an stateless reset packet. 626 bool IsIetfStatelessResetPacket(const QuicPacketHeader& header) const; 627 628 // Returns true if encrypter of |level| is available. 629 bool HasEncrypterOfEncryptionLevel(EncryptionLevel level) const; 630 // Returns true if decrypter of |level| is available. 631 bool HasDecrypterOfEncryptionLevel(EncryptionLevel level) const; 632 633 // Returns true if an encrypter of |space| is available. 634 bool HasAnEncrypterForSpace(PacketNumberSpace space) const; 635 636 // Returns the encryption level to send application data. This should be only 637 // called with available encrypter for application data. 638 EncryptionLevel GetEncryptionLevelToSendApplicationData() const; 639 set_validate_flags(bool value)640 void set_validate_flags(bool value) { validate_flags_ = value; } 641 perspective()642 Perspective perspective() const { return perspective_; } 643 data_producer()644 QuicStreamFrameDataProducer* data_producer() const { return data_producer_; } 645 set_data_producer(QuicStreamFrameDataProducer * data_producer)646 void set_data_producer(QuicStreamFrameDataProducer* data_producer) { 647 data_producer_ = data_producer; 648 } 649 creation_time()650 QuicTime creation_time() const { return creation_time_; } 651 first_sending_packet_number()652 QuicPacketNumber first_sending_packet_number() const { 653 return first_sending_packet_number_; 654 } 655 current_received_frame_type()656 uint64_t current_received_frame_type() const { 657 return current_received_frame_type_; 658 } 659 previously_received_frame_type()660 uint64_t previously_received_frame_type() const { 661 return previously_received_frame_type_; 662 } 663 664 // The connection ID length the framer expects on incoming IETF short headers 665 // on the server. GetExpectedServerConnectionIdLength()666 uint8_t GetExpectedServerConnectionIdLength() { 667 return expected_server_connection_id_length_; 668 } 669 670 // Change the expected destination connection ID length for short headers on 671 // the client. SetExpectedClientConnectionIdLength(uint8_t expected_client_connection_id_length)672 void SetExpectedClientConnectionIdLength( 673 uint8_t expected_client_connection_id_length) { 674 expected_client_connection_id_length_ = 675 expected_client_connection_id_length; 676 } 677 678 void EnableMultiplePacketNumberSpacesSupport(); 679 680 // Writes an array of bytes that, if sent as a UDP datagram, will trigger 681 // IETF QUIC Version Negotiation on servers. The bytes will be written to 682 // |packet_bytes|, which must point to |packet_length| bytes of memory. 683 // |packet_length| must be in the range [1200, 65535]. 684 // |destination_connection_id_bytes| will be sent as the destination 685 // connection ID, and must point to |destination_connection_id_length| bytes 686 // of memory. |destination_connection_id_length| must be in the range [8,18]. 687 // When targeting Google servers, it is recommended to use a 688 // |destination_connection_id_length| of 8. 689 static bool WriteClientVersionNegotiationProbePacket( 690 char* packet_bytes, QuicByteCount packet_length, 691 const char* destination_connection_id_bytes, 692 uint8_t destination_connection_id_length); 693 694 // Parses a packet which a QUIC server sent in response to a packet sent by 695 // WriteClientVersionNegotiationProbePacket. |packet_bytes| must point to 696 // |packet_length| bytes in memory which represent the response. 697 // |packet_length| must be greater or equal to 6. This method will fill in 698 // |source_connection_id_bytes| which must point to at least 699 // |*source_connection_id_length_out| bytes in memory. 700 // |*source_connection_id_length_out| must be at least 18. 701 // |*source_connection_id_length_out| will contain the length of the received 702 // source connection ID, which on success will match the contents of the 703 // destination connection ID passed in to 704 // WriteClientVersionNegotiationProbePacket. In the case of a failure, 705 // |detailed_error| will be filled in with an explanation of what failed. 706 static bool ParseServerVersionNegotiationProbeResponse( 707 const char* packet_bytes, QuicByteCount packet_length, 708 char* source_connection_id_bytes, 709 uint8_t* source_connection_id_length_out, std::string* detailed_error); 710 set_local_ack_delay_exponent(uint32_t exponent)711 void set_local_ack_delay_exponent(uint32_t exponent) { 712 local_ack_delay_exponent_ = exponent; 713 } local_ack_delay_exponent()714 uint32_t local_ack_delay_exponent() const { 715 return local_ack_delay_exponent_; 716 } 717 set_peer_ack_delay_exponent(uint32_t exponent)718 void set_peer_ack_delay_exponent(uint32_t exponent) { 719 peer_ack_delay_exponent_ = exponent; 720 } peer_ack_delay_exponent()721 uint32_t peer_ack_delay_exponent() const { return peer_ack_delay_exponent_; } 722 set_drop_incoming_retry_packets(bool drop_incoming_retry_packets)723 void set_drop_incoming_retry_packets(bool drop_incoming_retry_packets) { 724 drop_incoming_retry_packets_ = drop_incoming_retry_packets; 725 } 726 727 private: 728 friend class test::QuicFramerPeer; 729 730 using NackRangeMap = std::map<QuicPacketNumber, uint8_t>; 731 732 // AckTimestampRange is a data structure derived from a QuicAckFrame. It is 733 // used to serialize timestamps in a IETF_ACK_RECEIVE_TIMESTAMPS frame. 734 struct QUICHE_EXPORT AckTimestampRange { 735 QuicPacketCount gap; 736 // |range_begin| and |range_end| are index(es) in 737 // QuicAckFrame.received_packet_times, representing a continuous range of 738 // packet numbers in descending order. |range_begin| >= |range_end|. 739 int64_t range_begin; // Inclusive 740 int64_t range_end; // Inclusive 741 }; 742 absl::InlinedVector<AckTimestampRange, 2> GetAckTimestampRanges( 743 const QuicAckFrame& frame, std::string& detailed_error) const; 744 int64_t FrameAckTimestampRanges( 745 const QuicAckFrame& frame, 746 const absl::InlinedVector<AckTimestampRange, 2>& timestamp_ranges, 747 QuicDataWriter* writer) const; 748 749 struct QUICHE_EXPORT AckFrameInfo { 750 AckFrameInfo(); 751 AckFrameInfo(const AckFrameInfo& other); 752 ~AckFrameInfo(); 753 754 // The maximum ack block length. 755 QuicPacketCount max_block_length; 756 // Length of first ack block. 757 QuicPacketCount first_block_length; 758 // Number of ACK blocks needed for the ACK frame. 759 size_t num_ack_blocks; 760 }; 761 762 // Applies header protection to an IETF QUIC packet header in |buffer| using 763 // the encrypter for level |level|. The buffer has |buffer_len| bytes of data, 764 // with the first protected packet bytes starting at |ad_len|. 765 bool ApplyHeaderProtection(EncryptionLevel level, char* buffer, 766 size_t buffer_len, size_t ad_len); 767 768 // Removes header protection from an IETF QUIC packet header. 769 // 770 // The packet number from the header is read from |reader|, where the packet 771 // number is the next contents in |reader|. |reader| is only advanced by the 772 // length of the packet number, but it is also used to peek the sample needed 773 // for removing header protection. 774 // 775 // Properties needed for removing header protection are read from |header|. 776 // The packet number length and type byte are written to |header|. 777 // 778 // The packet number, after removing header protection and decoding it, is 779 // written to |full_packet_number|. Finally, the header, with header 780 // protection removed, is written to |associated_data| to be used in packet 781 // decryption. |packet| is used in computing the asociated data. 782 bool RemoveHeaderProtection(QuicDataReader* reader, 783 const QuicEncryptedPacket& packet, 784 QuicPacketHeader* header, 785 uint64_t* full_packet_number, 786 std::vector<char>* associated_data); 787 788 bool ProcessIetfDataPacket(QuicDataReader* encrypted_reader, 789 QuicPacketHeader* header, 790 const QuicEncryptedPacket& packet, 791 char* decrypted_buffer, size_t buffer_length); 792 793 bool ProcessVersionNegotiationPacket(QuicDataReader* reader, 794 const QuicPacketHeader& header); 795 796 bool ProcessRetryPacket(QuicDataReader* reader, 797 const QuicPacketHeader& header); 798 799 void MaybeProcessCoalescedPacket(const QuicDataReader& encrypted_reader, 800 uint64_t remaining_bytes_length, 801 const QuicPacketHeader& header); 802 803 bool MaybeProcessIetfLength(QuicDataReader* encrypted_reader, 804 QuicPacketHeader* header); 805 806 // Processes the version label in the packet header. 807 static bool ProcessVersionLabel(QuicDataReader* reader, 808 QuicVersionLabel* version_label); 809 810 // Validates and updates |destination_connection_id_length| and 811 // |source_connection_id_length|. When 812 // |should_update_expected_server_connection_id_length| is true, length 813 // validation is disabled and |expected_server_connection_id_length| is set 814 // to the appropriate length. 815 // TODO(b/133873272) refactor this method. 816 static bool ProcessAndValidateIetfConnectionIdLength( 817 QuicDataReader* reader, ParsedQuicVersion version, 818 Perspective perspective, 819 bool should_update_expected_server_connection_id_length, 820 uint8_t* expected_server_connection_id_length, 821 uint8_t* destination_connection_id_length, 822 uint8_t* source_connection_id_length, std::string* detailed_error); 823 824 bool ProcessIetfHeaderTypeByte(QuicDataReader* reader, 825 QuicPacketHeader* header); 826 bool ProcessIetfPacketHeader(QuicDataReader* reader, 827 QuicPacketHeader* header); 828 829 // First processes possibly truncated packet number. Calculates the full 830 // packet number from the truncated one and the last seen packet number, and 831 // stores it to |packet_number|. 832 bool ProcessAndCalculatePacketNumber( 833 QuicDataReader* reader, QuicPacketNumberLength packet_number_length, 834 QuicPacketNumber base_packet_number, uint64_t* packet_number); 835 bool ProcessFrameData(QuicDataReader* reader, const QuicPacketHeader& header); 836 837 static bool IsIetfFrameTypeExpectedForEncryptionLevel(uint64_t frame_type, 838 EncryptionLevel level); 839 840 bool ProcessIetfFrameData(QuicDataReader* reader, 841 const QuicPacketHeader& header, 842 EncryptionLevel decrypted_level); 843 bool ProcessStreamFrame(QuicDataReader* reader, uint8_t frame_type, 844 QuicStreamFrame* frame); 845 bool ProcessAckFrame(QuicDataReader* reader, uint8_t frame_type); 846 bool ProcessTimestampsInAckFrame(uint8_t num_received_packets, 847 QuicPacketNumber largest_acked, 848 QuicDataReader* reader); 849 bool ProcessIetfAckFrame(QuicDataReader* reader, uint64_t frame_type, 850 QuicAckFrame* ack_frame); 851 bool ProcessIetfTimestampsInAckFrame(QuicPacketNumber largest_acked, 852 QuicDataReader* reader); 853 bool ProcessStopWaitingFrame(QuicDataReader* reader, 854 const QuicPacketHeader& header, 855 QuicStopWaitingFrame* stop_waiting); 856 bool ProcessRstStreamFrame(QuicDataReader* reader, QuicRstStreamFrame* frame); 857 bool ProcessConnectionCloseFrame(QuicDataReader* reader, 858 QuicConnectionCloseFrame* frame); 859 bool ProcessGoAwayFrame(QuicDataReader* reader, QuicGoAwayFrame* frame); 860 bool ProcessWindowUpdateFrame(QuicDataReader* reader, 861 QuicWindowUpdateFrame* frame); 862 bool ProcessBlockedFrame(QuicDataReader* reader, QuicBlockedFrame* frame); 863 void ProcessPaddingFrame(QuicDataReader* reader, QuicPaddingFrame* frame); 864 bool ProcessMessageFrame(QuicDataReader* reader, bool no_message_length, 865 QuicMessageFrame* frame); 866 867 bool DecryptPayload(size_t udp_packet_length, absl::string_view encrypted, 868 absl::string_view associated_data, 869 const QuicPacketHeader& header, char* decrypted_buffer, 870 size_t buffer_length, size_t* decrypted_length, 871 EncryptionLevel* decrypted_level); 872 873 // Returns the full packet number from the truncated 874 // wire format version and the last seen packet number. 875 uint64_t CalculatePacketNumberFromWire( 876 QuicPacketNumberLength packet_number_length, 877 QuicPacketNumber base_packet_number, uint64_t packet_number) const; 878 879 // Returns the QuicTime::Delta corresponding to the time from when the framer 880 // was created. 881 const QuicTime::Delta CalculateTimestampFromWire(uint32_t time_delta_us); 882 883 // Computes the wire size in bytes of time stamps in |ack|. 884 size_t GetAckFrameTimeStampSize(const QuicAckFrame& ack); 885 size_t GetIetfAckFrameTimestampSize(const QuicAckFrame& ack); 886 887 // Computes the wire size in bytes of the |ack| frame. 888 size_t GetAckFrameSize(const QuicAckFrame& ack, 889 QuicPacketNumberLength packet_number_length); 890 // Computes the wire-size, in bytes, of the |frame| ack frame, for IETF Quic. 891 size_t GetIetfAckFrameSize(const QuicAckFrame& frame); 892 893 // Computes the wire size in bytes of the |ack| frame. 894 size_t GetAckFrameSize(const QuicAckFrame& ack); 895 896 // Computes the wire size in bytes of the payload of |frame|. 897 size_t ComputeFrameLength(const QuicFrame& frame, bool last_frame_in_packet, 898 QuicPacketNumberLength packet_number_length); 899 900 static bool AppendPacketNumber(QuicPacketNumberLength packet_number_length, 901 QuicPacketNumber packet_number, 902 QuicDataWriter* writer); 903 static bool AppendStreamId(size_t stream_id_length, QuicStreamId stream_id, 904 QuicDataWriter* writer); 905 static bool AppendStreamOffset(size_t offset_length, QuicStreamOffset offset, 906 QuicDataWriter* writer); 907 908 // Appends a single ACK block to |writer| and returns true if the block was 909 // successfully appended. 910 static bool AppendAckBlock(uint8_t gap, QuicPacketNumberLength length_length, 911 uint64_t length, QuicDataWriter* writer); 912 913 static uint8_t GetPacketNumberFlags( 914 QuicPacketNumberLength packet_number_length); 915 916 static AckFrameInfo GetAckFrameInfo(const QuicAckFrame& frame); 917 918 static QuicErrorCode ParsePublicHeaderGoogleQuic( 919 QuicDataReader* reader, uint8_t* first_byte, PacketHeaderFormat* format, 920 bool* version_present, QuicVersionLabel* version_label, 921 ParsedQuicVersion* parsed_version, 922 QuicConnectionId* destination_connection_id, std::string* detailed_error); 923 924 bool ValidateReceivedConnectionIds(const QuicPacketHeader& header); 925 926 // The Append* methods attempt to write the provided header or frame using the 927 // |writer|, and return true if successful. 928 929 bool AppendAckFrameAndTypeByte(const QuicAckFrame& frame, 930 QuicDataWriter* writer); 931 bool AppendTimestampsToAckFrame(const QuicAckFrame& frame, 932 QuicDataWriter* writer); 933 934 // Append IETF format ACK frame. 935 // 936 // AppendIetfAckFrameAndTypeByte adds the IETF type byte and the body 937 // of the frame. 938 bool AppendIetfAckFrameAndTypeByte(const QuicAckFrame& frame, 939 QuicDataWriter* writer); 940 bool AppendIetfTimestampsToAckFrame(const QuicAckFrame& frame, 941 QuicDataWriter* writer); 942 943 bool AppendStopWaitingFrame(const QuicPacketHeader& header, 944 const QuicStopWaitingFrame& frame, 945 QuicDataWriter* writer); 946 bool AppendRstStreamFrame(const QuicRstStreamFrame& frame, 947 QuicDataWriter* writer); 948 bool AppendConnectionCloseFrame(const QuicConnectionCloseFrame& frame, 949 QuicDataWriter* writer); 950 bool AppendGoAwayFrame(const QuicGoAwayFrame& frame, QuicDataWriter* writer); 951 bool AppendWindowUpdateFrame(const QuicWindowUpdateFrame& frame, 952 QuicDataWriter* writer); 953 bool AppendBlockedFrame(const QuicBlockedFrame& frame, 954 QuicDataWriter* writer); 955 bool AppendPaddingFrame(const QuicPaddingFrame& frame, 956 QuicDataWriter* writer); 957 bool AppendMessageFrameAndTypeByte(const QuicMessageFrame& frame, 958 bool last_frame_in_packet, 959 QuicDataWriter* writer); 960 961 // IETF frame processing methods. 962 bool ProcessIetfStreamFrame(QuicDataReader* reader, uint8_t frame_type, 963 QuicStreamFrame* frame); 964 bool ProcessIetfConnectionCloseFrame(QuicDataReader* reader, 965 QuicConnectionCloseType type, 966 QuicConnectionCloseFrame* frame); 967 bool ProcessPathChallengeFrame(QuicDataReader* reader, 968 QuicPathChallengeFrame* frame); 969 bool ProcessPathResponseFrame(QuicDataReader* reader, 970 QuicPathResponseFrame* frame); 971 bool ProcessIetfResetStreamFrame(QuicDataReader* reader, 972 QuicRstStreamFrame* frame); 973 bool ProcessStopSendingFrame(QuicDataReader* reader, 974 QuicStopSendingFrame* stop_sending_frame); 975 bool ProcessCryptoFrame(QuicDataReader* reader, 976 EncryptionLevel encryption_level, 977 QuicCryptoFrame* frame); 978 bool ProcessAckFrequencyFrame(QuicDataReader* reader, 979 QuicAckFrequencyFrame* frame); 980 // IETF frame appending methods. All methods append the type byte as well. 981 bool AppendIetfStreamFrame(const QuicStreamFrame& frame, 982 bool last_frame_in_packet, QuicDataWriter* writer); 983 bool AppendIetfConnectionCloseFrame(const QuicConnectionCloseFrame& frame, 984 QuicDataWriter* writer); 985 bool AppendPathChallengeFrame(const QuicPathChallengeFrame& frame, 986 QuicDataWriter* writer); 987 bool AppendPathResponseFrame(const QuicPathResponseFrame& frame, 988 QuicDataWriter* writer); 989 bool AppendIetfResetStreamFrame(const QuicRstStreamFrame& frame, 990 QuicDataWriter* writer); 991 bool AppendStopSendingFrame(const QuicStopSendingFrame& stop_sending_frame, 992 QuicDataWriter* writer); 993 994 // Append/consume IETF-Format MAX_DATA and MAX_STREAM_DATA frames 995 bool AppendMaxDataFrame(const QuicWindowUpdateFrame& frame, 996 QuicDataWriter* writer); 997 bool AppendMaxStreamDataFrame(const QuicWindowUpdateFrame& frame, 998 QuicDataWriter* writer); 999 bool ProcessMaxDataFrame(QuicDataReader* reader, 1000 QuicWindowUpdateFrame* frame); 1001 bool ProcessMaxStreamDataFrame(QuicDataReader* reader, 1002 QuicWindowUpdateFrame* frame); 1003 1004 bool AppendMaxStreamsFrame(const QuicMaxStreamsFrame& frame, 1005 QuicDataWriter* writer); 1006 bool ProcessMaxStreamsFrame(QuicDataReader* reader, 1007 QuicMaxStreamsFrame* frame, uint64_t frame_type); 1008 1009 bool AppendDataBlockedFrame(const QuicBlockedFrame& frame, 1010 QuicDataWriter* writer); 1011 bool ProcessDataBlockedFrame(QuicDataReader* reader, QuicBlockedFrame* frame); 1012 1013 bool AppendStreamDataBlockedFrame(const QuicBlockedFrame& frame, 1014 QuicDataWriter* writer); 1015 bool ProcessStreamDataBlockedFrame(QuicDataReader* reader, 1016 QuicBlockedFrame* frame); 1017 1018 bool AppendStreamsBlockedFrame(const QuicStreamsBlockedFrame& frame, 1019 QuicDataWriter* writer); 1020 bool ProcessStreamsBlockedFrame(QuicDataReader* reader, 1021 QuicStreamsBlockedFrame* frame, 1022 uint64_t frame_type); 1023 1024 bool AppendNewConnectionIdFrame(const QuicNewConnectionIdFrame& frame, 1025 QuicDataWriter* writer); 1026 bool ProcessNewConnectionIdFrame(QuicDataReader* reader, 1027 QuicNewConnectionIdFrame* frame); 1028 bool AppendRetireConnectionIdFrame(const QuicRetireConnectionIdFrame& frame, 1029 QuicDataWriter* writer); 1030 bool ProcessRetireConnectionIdFrame(QuicDataReader* reader, 1031 QuicRetireConnectionIdFrame* frame); 1032 1033 bool AppendNewTokenFrame(const QuicNewTokenFrame& frame, 1034 QuicDataWriter* writer); 1035 bool ProcessNewTokenFrame(QuicDataReader* reader, QuicNewTokenFrame* frame); 1036 1037 bool RaiseError(QuicErrorCode error); 1038 1039 // Returns true if |header| indicates a version negotiation packet. 1040 bool IsVersionNegotiation(const QuicPacketHeader& header) const; 1041 1042 // Calculates and returns type byte of stream frame. 1043 uint8_t GetStreamFrameTypeByte(const QuicStreamFrame& frame, 1044 bool last_frame_in_packet) const; 1045 uint8_t GetIetfStreamFrameTypeByte(const QuicStreamFrame& frame, 1046 bool last_frame_in_packet) const; 1047 set_error(QuicErrorCode error)1048 void set_error(QuicErrorCode error) { error_ = error; } 1049 set_detailed_error(const char * error)1050 void set_detailed_error(const char* error) { detailed_error_ = error; } set_detailed_error(std::string error)1051 void set_detailed_error(std::string error) { detailed_error_ = error; } 1052 1053 // Returns false if the reading fails. 1054 bool ReadUint32FromVarint62(QuicDataReader* reader, QuicIetfFrameType type, 1055 QuicStreamId* id); 1056 1057 bool ProcessPacketInternal(const QuicEncryptedPacket& packet); 1058 1059 // Determine whether the given QuicAckFrame should be serialized with a 1060 // IETF_ACK_RECEIVE_TIMESTAMPS frame type. UseIetfAckWithReceiveTimestamp(const QuicAckFrame & frame)1061 bool UseIetfAckWithReceiveTimestamp(const QuicAckFrame& frame) const { 1062 return VersionHasIetfQuicFrames(version_.transport_version) && 1063 process_timestamps_ && 1064 std::min<uint64_t>(max_receive_timestamps_per_ack_, 1065 frame.received_packet_times.size()) > 0; 1066 } 1067 1068 std::string detailed_error_; 1069 QuicFramerVisitorInterface* visitor_; 1070 QuicErrorCode error_; 1071 // Updated by ProcessPacketHeader when it succeeds decrypting a larger packet. 1072 QuicPacketNumber largest_packet_number_; 1073 // Largest successfully decrypted packet number per packet number space. Only 1074 // used when supports_multiple_packet_number_spaces_ is true. 1075 QuicPacketNumber largest_decrypted_packet_numbers_[NUM_PACKET_NUMBER_SPACES]; 1076 // Last server connection ID seen on the wire. 1077 QuicConnectionId last_serialized_server_connection_id_; 1078 // Version of the protocol being used. 1079 ParsedQuicVersion version_; 1080 // This vector contains QUIC versions which we currently support. 1081 // This should be ordered such that the highest supported version is the first 1082 // element, with subsequent elements in descending order (versions can be 1083 // skipped as necessary). 1084 ParsedQuicVersionVector supported_versions_; 1085 // Decrypters used to decrypt packets during parsing. 1086 std::unique_ptr<QuicDecrypter> decrypter_[NUM_ENCRYPTION_LEVELS]; 1087 // The encryption level of the primary decrypter to use in |decrypter_|. 1088 EncryptionLevel decrypter_level_; 1089 // The encryption level of the alternative decrypter to use in |decrypter_|. 1090 // When set to NUM_ENCRYPTION_LEVELS, indicates that there is no alternative 1091 // decrypter. 1092 EncryptionLevel alternative_decrypter_level_; 1093 // |alternative_decrypter_latch_| is true if, when the decrypter at 1094 // |alternative_decrypter_level_| successfully decrypts a packet, we should 1095 // install it as the only decrypter. 1096 bool alternative_decrypter_latch_; 1097 // Encrypters used to encrypt packets via EncryptPayload(). 1098 std::unique_ptr<QuicEncrypter> encrypter_[NUM_ENCRYPTION_LEVELS]; 1099 // Tracks if the framer is being used by the entity that received the 1100 // connection or the entity that initiated it. 1101 Perspective perspective_; 1102 // If false, skip validation that the public flags are set to legal values. 1103 bool validate_flags_; 1104 // The diversification nonce from the last received packet. 1105 DiversificationNonce last_nonce_; 1106 // If true, send and process timestamps in the ACK frame. 1107 // TODO(ianswett): Remove the mutables once set_process_timestamps and 1108 // set_receive_timestamp_exponent_ aren't const. 1109 mutable bool process_timestamps_; 1110 // The max number of receive timestamps to send per ACK frame. 1111 mutable uint32_t max_receive_timestamps_per_ack_; 1112 // The exponent to use when writing/reading ACK receive timestamps. 1113 mutable uint32_t receive_timestamps_exponent_; 1114 // The creation time of the connection, used to calculate timestamps. 1115 QuicTime creation_time_; 1116 // The last timestamp received if process_timestamps_ is true. 1117 QuicTime::Delta last_timestamp_; 1118 1119 // Whether IETF QUIC Key Update is supported on this connection. 1120 bool support_key_update_for_connection_; 1121 // The value of the current key phase bit, which is toggled when the keys are 1122 // changed. 1123 bool current_key_phase_bit_; 1124 // Whether we have performed a key update at least once. 1125 bool key_update_performed_ = false; 1126 // Tracks the first packet received in the current key phase. Will be 1127 // uninitialized before the first one-RTT packet has been received or after a 1128 // locally initiated key update but before the first packet from the peer in 1129 // the new key phase is received. 1130 QuicPacketNumber current_key_phase_first_received_packet_number_; 1131 // Counts the number of packets received that might have been failed key 1132 // update attempts. Reset to zero every time a packet is successfully 1133 // decrypted. 1134 QuicPacketCount potential_peer_key_update_attempt_count_; 1135 // Decrypter for the previous key phase. Will be null if in the first key 1136 // phase or previous keys have been discarded. 1137 std::unique_ptr<QuicDecrypter> previous_decrypter_; 1138 // Decrypter for the next key phase. May be null if next keys haven't been 1139 // generated yet. 1140 std::unique_ptr<QuicDecrypter> next_decrypter_; 1141 1142 // If this is a framer of a connection, this is the packet number of first 1143 // sending packet. If this is a framer of a framer of dispatcher, this is the 1144 // packet number of sent packets (for those which have packet number). 1145 const QuicPacketNumber first_sending_packet_number_; 1146 1147 // If not null, framer asks data_producer_ to write stream frame data. Not 1148 // owned. TODO(fayang): Consider add data producer to framer's constructor. 1149 QuicStreamFrameDataProducer* data_producer_; 1150 1151 // Whether we are in the middle of a call to this->ProcessPacket. 1152 bool is_processing_packet_ = false; 1153 1154 // IETF short headers contain a destination connection ID but do not 1155 // encode its length. These variables contains the length we expect to read. 1156 // This is also used to validate the long header destination connection ID 1157 // lengths in older versions of QUIC. 1158 uint8_t expected_server_connection_id_length_; 1159 uint8_t expected_client_connection_id_length_; 1160 1161 // Indicates whether this framer supports multiple packet number spaces. 1162 bool supports_multiple_packet_number_spaces_; 1163 1164 // Indicates whether received RETRY packets should be dropped. 1165 bool drop_incoming_retry_packets_ = false; 1166 1167 // The length in bytes of the last packet number written to an IETF-framed 1168 // packet. 1169 size_t last_written_packet_number_length_; 1170 1171 // The amount to shift the ack timestamp in ACK frames. The default is 3. 1172 // Local_ is the amount this node shifts timestamps in ACK frames it 1173 // generates. it is sent to the peer in a transport parameter negotiation. 1174 // Peer_ is the amount the peer shifts timestamps when it sends ACK frames to 1175 // this node. This node "unshifts" by this amount. The value is received from 1176 // the peer in the transport parameter negotiation. IETF QUIC only. 1177 uint32_t peer_ack_delay_exponent_; 1178 uint32_t local_ack_delay_exponent_; 1179 1180 // The type of received IETF frame currently being processed. 0 when not 1181 // processing a frame or when processing Google QUIC frames. Used to populate 1182 // the Transport Connection Close when there is an error during frame 1183 // processing. 1184 uint64_t current_received_frame_type_; 1185 1186 // TODO(haoyuewang) Remove this debug utility. 1187 // The type of the IETF frame preceding the frame currently being processed. 0 1188 // when not processing a frame or only 1 frame has been processed. 1189 uint64_t previously_received_frame_type_; 1190 }; 1191 1192 // Look for and parse the error code from the "<quic_error_code>:" text that 1193 // may be present at the start of the CONNECTION_CLOSE error details string. 1194 // This text, inserted by the peer if it's using Google's QUIC implementation, 1195 // contains additional error information that narrows down the exact error. The 1196 // extracted error code and (possibly updated) error_details string are returned 1197 // in |*frame|. If an error code is not found in the error details, then 1198 // frame->quic_error_code is set to 1199 // QuicErrorCode::QUIC_IETF_GQUIC_ERROR_MISSING. If there is an error code in 1200 // the string then it is removed from the string. 1201 QUICHE_EXPORT void MaybeExtractQuicErrorCode(QuicConnectionCloseFrame* frame); 1202 1203 } // namespace quic 1204 1205 #endif // QUICHE_QUIC_CORE_QUIC_FRAMER_H_ 1206