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 "quiche/quic/core/quic_framer.h"
6
7 #include <sys/types.h>
8
9 #include <cstddef>
10 #include <cstdint>
11 #include <limits>
12 #include <memory>
13 #include <string>
14 #include <utility>
15
16 #include "absl/base/attributes.h"
17 #include "absl/base/macros.h"
18 #include "absl/base/optimization.h"
19 #include "absl/cleanup/cleanup.h"
20 #include "absl/strings/escaping.h"
21 #include "absl/strings/numbers.h"
22 #include "absl/strings/str_cat.h"
23 #include "absl/strings/str_split.h"
24 #include "absl/strings/string_view.h"
25 #include "absl/types/optional.h"
26 #include "quiche/quic/core/crypto/crypto_framer.h"
27 #include "quiche/quic/core/crypto/crypto_handshake.h"
28 #include "quiche/quic/core/crypto/crypto_handshake_message.h"
29 #include "quiche/quic/core/crypto/crypto_protocol.h"
30 #include "quiche/quic/core/crypto/crypto_utils.h"
31 #include "quiche/quic/core/crypto/null_decrypter.h"
32 #include "quiche/quic/core/crypto/null_encrypter.h"
33 #include "quiche/quic/core/crypto/quic_decrypter.h"
34 #include "quiche/quic/core/crypto/quic_encrypter.h"
35 #include "quiche/quic/core/crypto/quic_random.h"
36 #include "quiche/quic/core/frames/quic_ack_frequency_frame.h"
37 #include "quiche/quic/core/quic_connection_context.h"
38 #include "quiche/quic/core/quic_connection_id.h"
39 #include "quiche/quic/core/quic_constants.h"
40 #include "quiche/quic/core/quic_data_reader.h"
41 #include "quiche/quic/core/quic_data_writer.h"
42 #include "quiche/quic/core/quic_error_codes.h"
43 #include "quiche/quic/core/quic_packets.h"
44 #include "quiche/quic/core/quic_socket_address_coder.h"
45 #include "quiche/quic/core/quic_stream_frame_data_producer.h"
46 #include "quiche/quic/core/quic_time.h"
47 #include "quiche/quic/core/quic_types.h"
48 #include "quiche/quic/core/quic_utils.h"
49 #include "quiche/quic/core/quic_versions.h"
50 #include "quiche/quic/platform/api/quic_bug_tracker.h"
51 #include "quiche/quic/platform/api/quic_client_stats.h"
52 #include "quiche/quic/platform/api/quic_flag_utils.h"
53 #include "quiche/quic/platform/api/quic_flags.h"
54 #include "quiche/quic/platform/api/quic_ip_address_family.h"
55 #include "quiche/quic/platform/api/quic_logging.h"
56 #include "quiche/quic/platform/api/quic_stack_trace.h"
57 #include "quiche/common/quiche_text_utils.h"
58
59 namespace quic {
60
61 namespace {
62
63 #define ENDPOINT \
64 (perspective_ == Perspective::IS_SERVER ? "Server: " : "Client: ")
65
66 // Number of bits the packet number length bits are shifted from the right
67 // edge of the header.
68 const uint8_t kPublicHeaderSequenceNumberShift = 4;
69
70 // There are two interpretations for the Frame Type byte in the QUIC protocol,
71 // resulting in two Frame Types: Special Frame Types and Regular Frame Types.
72 //
73 // Regular Frame Types use the Frame Type byte simply. Currently defined
74 // Regular Frame Types are:
75 // Padding : 0b 00000000 (0x00)
76 // ResetStream : 0b 00000001 (0x01)
77 // ConnectionClose : 0b 00000010 (0x02)
78 // GoAway : 0b 00000011 (0x03)
79 // WindowUpdate : 0b 00000100 (0x04)
80 // Blocked : 0b 00000101 (0x05)
81 //
82 // Special Frame Types encode both a Frame Type and corresponding flags
83 // all in the Frame Type byte. Currently defined Special Frame Types
84 // are:
85 // Stream : 0b 1xxxxxxx
86 // Ack : 0b 01xxxxxx
87 //
88 // Semantics of the flag bits above (the x bits) depends on the frame type.
89
90 // Masks to determine if the frame type is a special use
91 // and for specific special frame types.
92 const uint8_t kQuicFrameTypeBrokenMask = 0xE0; // 0b 11100000
93 const uint8_t kQuicFrameTypeSpecialMask = 0xC0; // 0b 11000000
94 const uint8_t kQuicFrameTypeStreamMask = 0x80;
95 const uint8_t kQuicFrameTypeAckMask = 0x40;
96 static_assert(kQuicFrameTypeSpecialMask ==
97 (kQuicFrameTypeStreamMask | kQuicFrameTypeAckMask),
98 "Invalid kQuicFrameTypeSpecialMask");
99
100 // The stream type format is 1FDOOOSS, where
101 // F is the fin bit.
102 // D is the data length bit (0 or 2 bytes).
103 // OO/OOO are the size of the offset.
104 // SS is the size of the stream ID.
105 // Note that the stream encoding can not be determined by inspection. It can
106 // be determined only by knowing the QUIC Version.
107 // Stream frame relative shifts and masks for interpreting the stream flags.
108 // StreamID may be 1, 2, 3, or 4 bytes.
109 const uint8_t kQuicStreamIdShift = 2;
110 const uint8_t kQuicStreamIDLengthMask = 0x03;
111
112 // Offset may be 0, 2, 4, or 8 bytes.
113 const uint8_t kQuicStreamShift = 3;
114 const uint8_t kQuicStreamOffsetMask = 0x07;
115
116 // Data length may be 0 or 2 bytes.
117 const uint8_t kQuicStreamDataLengthShift = 1;
118 const uint8_t kQuicStreamDataLengthMask = 0x01;
119
120 // Fin bit may be set or not.
121 const uint8_t kQuicStreamFinShift = 1;
122 const uint8_t kQuicStreamFinMask = 0x01;
123
124 // The format is 01M0LLOO, where
125 // M if set, there are multiple ack blocks in the frame.
126 // LL is the size of the largest ack field.
127 // OO is the size of the ack blocks offset field.
128 // packet number size shift used in AckFrames.
129 const uint8_t kQuicSequenceNumberLengthNumBits = 2;
130 const uint8_t kActBlockLengthOffset = 0;
131 const uint8_t kLargestAckedOffset = 2;
132
133 // Acks may have only one ack block.
134 const uint8_t kQuicHasMultipleAckBlocksOffset = 5;
135
136 // Timestamps are 4 bytes followed by 2 bytes.
137 const uint8_t kQuicNumTimestampsLength = 1;
138 const uint8_t kQuicFirstTimestampLength = 4;
139 const uint8_t kQuicTimestampLength = 2;
140 // Gaps between packet numbers are 1 byte.
141 const uint8_t kQuicTimestampPacketNumberGapLength = 1;
142
143 // Maximum length of encoded error strings.
144 const int kMaxErrorStringLength = 256;
145
146 const uint8_t kConnectionIdLengthAdjustment = 3;
147 const uint8_t kDestinationConnectionIdLengthMask = 0xF0;
148 const uint8_t kSourceConnectionIdLengthMask = 0x0F;
149
150 // Returns the absolute value of the difference between |a| and |b|.
Delta(uint64_t a,uint64_t b)151 uint64_t Delta(uint64_t a, uint64_t b) {
152 // Since these are unsigned numbers, we can't just return abs(a - b)
153 if (a < b) {
154 return b - a;
155 }
156 return a - b;
157 }
158
ClosestTo(uint64_t target,uint64_t a,uint64_t b)159 uint64_t ClosestTo(uint64_t target, uint64_t a, uint64_t b) {
160 return (Delta(target, a) < Delta(target, b)) ? a : b;
161 }
162
ReadSequenceNumberLength(uint8_t flags)163 QuicPacketNumberLength ReadSequenceNumberLength(uint8_t flags) {
164 switch (flags & PACKET_FLAGS_8BYTE_PACKET) {
165 case PACKET_FLAGS_8BYTE_PACKET:
166 return PACKET_6BYTE_PACKET_NUMBER;
167 case PACKET_FLAGS_4BYTE_PACKET:
168 return PACKET_4BYTE_PACKET_NUMBER;
169 case PACKET_FLAGS_2BYTE_PACKET:
170 return PACKET_2BYTE_PACKET_NUMBER;
171 case PACKET_FLAGS_1BYTE_PACKET:
172 return PACKET_1BYTE_PACKET_NUMBER;
173 default:
174 QUIC_BUG(quic_bug_10850_1) << "Unreachable case statement.";
175 return PACKET_6BYTE_PACKET_NUMBER;
176 }
177 }
178
ReadAckPacketNumberLength(uint8_t flags)179 QuicPacketNumberLength ReadAckPacketNumberLength(uint8_t flags) {
180 switch (flags & PACKET_FLAGS_8BYTE_PACKET) {
181 case PACKET_FLAGS_8BYTE_PACKET:
182 return PACKET_6BYTE_PACKET_NUMBER;
183 case PACKET_FLAGS_4BYTE_PACKET:
184 return PACKET_4BYTE_PACKET_NUMBER;
185 case PACKET_FLAGS_2BYTE_PACKET:
186 return PACKET_2BYTE_PACKET_NUMBER;
187 case PACKET_FLAGS_1BYTE_PACKET:
188 return PACKET_1BYTE_PACKET_NUMBER;
189 default:
190 QUIC_BUG(quic_bug_10850_2) << "Unreachable case statement.";
191 return PACKET_6BYTE_PACKET_NUMBER;
192 }
193 }
194
PacketNumberLengthToOnWireValue(QuicPacketNumberLength packet_number_length)195 uint8_t PacketNumberLengthToOnWireValue(
196 QuicPacketNumberLength packet_number_length) {
197 return packet_number_length - 1;
198 }
199
GetShortHeaderPacketNumberLength(uint8_t type)200 QuicPacketNumberLength GetShortHeaderPacketNumberLength(uint8_t type) {
201 QUICHE_DCHECK(!(type & FLAGS_LONG_HEADER));
202 return static_cast<QuicPacketNumberLength>((type & 0x03) + 1);
203 }
204
LongHeaderTypeToOnWireValue(QuicLongHeaderType type,const ParsedQuicVersion & version)205 uint8_t LongHeaderTypeToOnWireValue(QuicLongHeaderType type,
206 const ParsedQuicVersion& version) {
207 switch (type) {
208 case INITIAL:
209 return version.UsesV2PacketTypes() ? (1 << 4) : 0;
210 case ZERO_RTT_PROTECTED:
211 return version.UsesV2PacketTypes() ? (2 << 4) : (1 << 4);
212 case HANDSHAKE:
213 return version.UsesV2PacketTypes() ? (3 << 4) : (2 << 4);
214 case RETRY:
215 return version.UsesV2PacketTypes() ? 0 : (3 << 4);
216 case VERSION_NEGOTIATION:
217 return 0xF0; // Value does not matter
218 default:
219 QUIC_BUG(quic_bug_10850_3) << "Invalid long header type: " << type;
220 return 0xFF;
221 }
222 }
223
GetLongHeaderType(uint8_t type,const ParsedQuicVersion & version)224 QuicLongHeaderType GetLongHeaderType(uint8_t type,
225 const ParsedQuicVersion& version) {
226 QUICHE_DCHECK((type & FLAGS_LONG_HEADER));
227 switch ((type & 0x30) >> 4) {
228 case 0:
229 return version.UsesV2PacketTypes() ? RETRY : INITIAL;
230 case 1:
231 return version.UsesV2PacketTypes() ? INITIAL : ZERO_RTT_PROTECTED;
232 case 2:
233 return version.UsesV2PacketTypes() ? ZERO_RTT_PROTECTED : HANDSHAKE;
234 case 3:
235 return version.UsesV2PacketTypes() ? HANDSHAKE : RETRY;
236 default:
237 QUIC_BUG(quic_bug_10850_4) << "Unreachable statement";
238 return INVALID_PACKET_TYPE;
239 }
240 }
241
GetLongHeaderPacketNumberLength(uint8_t type)242 QuicPacketNumberLength GetLongHeaderPacketNumberLength(uint8_t type) {
243 return static_cast<QuicPacketNumberLength>((type & 0x03) + 1);
244 }
245
246 // Used to get packet number space before packet gets decrypted.
GetPacketNumberSpace(const QuicPacketHeader & header)247 PacketNumberSpace GetPacketNumberSpace(const QuicPacketHeader& header) {
248 switch (header.form) {
249 case GOOGLE_QUIC_PACKET:
250 QUIC_BUG(quic_bug_10850_5)
251 << "Try to get packet number space of Google QUIC packet";
252 break;
253 case IETF_QUIC_SHORT_HEADER_PACKET:
254 return APPLICATION_DATA;
255 case IETF_QUIC_LONG_HEADER_PACKET:
256 switch (header.long_packet_type) {
257 case INITIAL:
258 return INITIAL_DATA;
259 case HANDSHAKE:
260 return HANDSHAKE_DATA;
261 case ZERO_RTT_PROTECTED:
262 return APPLICATION_DATA;
263 case VERSION_NEGOTIATION:
264 case RETRY:
265 case INVALID_PACKET_TYPE:
266 QUIC_BUG(quic_bug_10850_6)
267 << "Try to get packet number space of long header type: "
268 << QuicUtils::QuicLongHeaderTypetoString(header.long_packet_type);
269 break;
270 }
271 }
272
273 return NUM_PACKET_NUMBER_SPACES;
274 }
275
GetEncryptionLevel(const QuicPacketHeader & header)276 EncryptionLevel GetEncryptionLevel(const QuicPacketHeader& header) {
277 switch (header.form) {
278 case GOOGLE_QUIC_PACKET:
279 QUIC_BUG(quic_bug_10850_7)
280 << "Cannot determine EncryptionLevel from Google QUIC header";
281 break;
282 case IETF_QUIC_SHORT_HEADER_PACKET:
283 return ENCRYPTION_FORWARD_SECURE;
284 case IETF_QUIC_LONG_HEADER_PACKET:
285 switch (header.long_packet_type) {
286 case INITIAL:
287 return ENCRYPTION_INITIAL;
288 case HANDSHAKE:
289 return ENCRYPTION_HANDSHAKE;
290 case ZERO_RTT_PROTECTED:
291 return ENCRYPTION_ZERO_RTT;
292 case VERSION_NEGOTIATION:
293 case RETRY:
294 case INVALID_PACKET_TYPE:
295 QUIC_BUG(quic_bug_10850_8)
296 << "No encryption used with type "
297 << QuicUtils::QuicLongHeaderTypetoString(header.long_packet_type);
298 }
299 }
300 return NUM_ENCRYPTION_LEVELS;
301 }
302
TruncateErrorString(absl::string_view error)303 absl::string_view TruncateErrorString(absl::string_view error) {
304 if (error.length() <= kMaxErrorStringLength) {
305 return error;
306 }
307 return absl::string_view(error.data(), kMaxErrorStringLength);
308 }
309
TruncatedErrorStringSize(const absl::string_view & error)310 size_t TruncatedErrorStringSize(const absl::string_view& error) {
311 if (error.length() < kMaxErrorStringLength) {
312 return error.length();
313 }
314 return kMaxErrorStringLength;
315 }
316
GetConnectionIdLengthValue(uint8_t length)317 uint8_t GetConnectionIdLengthValue(uint8_t length) {
318 if (length == 0) {
319 return 0;
320 }
321 return static_cast<uint8_t>(length - kConnectionIdLengthAdjustment);
322 }
323
IsValidPacketNumberLength(QuicPacketNumberLength packet_number_length)324 bool IsValidPacketNumberLength(QuicPacketNumberLength packet_number_length) {
325 size_t length = packet_number_length;
326 return length == 1 || length == 2 || length == 4 || length == 6 ||
327 length == 8;
328 }
329
IsValidFullPacketNumber(uint64_t full_packet_number,ParsedQuicVersion version)330 bool IsValidFullPacketNumber(uint64_t full_packet_number,
331 ParsedQuicVersion version) {
332 return full_packet_number > 0 || version.HasIetfQuicFrames();
333 }
334
AppendIetfConnectionIds(bool version_flag,bool use_length_prefix,QuicConnectionId destination_connection_id,QuicConnectionId source_connection_id,QuicDataWriter * writer)335 bool AppendIetfConnectionIds(bool version_flag, bool use_length_prefix,
336 QuicConnectionId destination_connection_id,
337 QuicConnectionId source_connection_id,
338 QuicDataWriter* writer) {
339 if (!version_flag) {
340 return writer->WriteConnectionId(destination_connection_id);
341 }
342
343 if (use_length_prefix) {
344 return writer->WriteLengthPrefixedConnectionId(destination_connection_id) &&
345 writer->WriteLengthPrefixedConnectionId(source_connection_id);
346 }
347
348 // Compute connection ID length byte.
349 uint8_t dcil = GetConnectionIdLengthValue(destination_connection_id.length());
350 uint8_t scil = GetConnectionIdLengthValue(source_connection_id.length());
351 uint8_t connection_id_length = dcil << 4 | scil;
352
353 return writer->WriteUInt8(connection_id_length) &&
354 writer->WriteConnectionId(destination_connection_id) &&
355 writer->WriteConnectionId(source_connection_id);
356 }
357
358 enum class DroppedPacketReason {
359 // General errors
360 INVALID_PUBLIC_HEADER,
361 VERSION_MISMATCH,
362 // Version negotiation packet errors
363 INVALID_VERSION_NEGOTIATION_PACKET,
364 // Public reset packet errors, pre-v44
365 INVALID_PUBLIC_RESET_PACKET,
366 // Data packet errors
367 INVALID_PACKET_NUMBER,
368 INVALID_DIVERSIFICATION_NONCE,
369 DECRYPTION_FAILURE,
370 NUM_REASONS,
371 };
372
RecordDroppedPacketReason(DroppedPacketReason reason)373 void RecordDroppedPacketReason(DroppedPacketReason reason) {
374 QUIC_CLIENT_HISTOGRAM_ENUM("QuicDroppedPacketReason", reason,
375 DroppedPacketReason::NUM_REASONS,
376 "The reason a packet was not processed. Recorded "
377 "each time such a packet is dropped");
378 }
379
GetIetfPacketHeaderFormat(uint8_t type_byte)380 PacketHeaderFormat GetIetfPacketHeaderFormat(uint8_t type_byte) {
381 return type_byte & FLAGS_LONG_HEADER ? IETF_QUIC_LONG_HEADER_PACKET
382 : IETF_QUIC_SHORT_HEADER_PACKET;
383 }
384
GenerateErrorString(std::string initial_error_string,QuicErrorCode quic_error_code)385 std::string GenerateErrorString(std::string initial_error_string,
386 QuicErrorCode quic_error_code) {
387 if (quic_error_code == QUIC_IETF_GQUIC_ERROR_MISSING) {
388 // QUIC_IETF_GQUIC_ERROR_MISSING is special -- it means not to encode
389 // the error value in the string.
390 return initial_error_string;
391 }
392 return absl::StrCat(std::to_string(static_cast<unsigned>(quic_error_code)),
393 ":", initial_error_string);
394 }
395
396 // Return the minimum size of the ECN fields in an ACK frame
AckEcnCountSize(const QuicAckFrame & ack_frame)397 size_t AckEcnCountSize(const QuicAckFrame& ack_frame) {
398 if (!ack_frame.ecn_counters.has_value()) {
399 return 0;
400 }
401 return (QuicDataWriter::GetVarInt62Len(ack_frame.ecn_counters->ect0) +
402 QuicDataWriter::GetVarInt62Len(ack_frame.ecn_counters->ect1) +
403 QuicDataWriter::GetVarInt62Len(ack_frame.ecn_counters->ce));
404 }
405
406 } // namespace
407
QuicFramer(const ParsedQuicVersionVector & supported_versions,QuicTime creation_time,Perspective perspective,uint8_t expected_server_connection_id_length)408 QuicFramer::QuicFramer(const ParsedQuicVersionVector& supported_versions,
409 QuicTime creation_time, Perspective perspective,
410 uint8_t expected_server_connection_id_length)
411 : visitor_(nullptr),
412 error_(QUIC_NO_ERROR),
413 last_serialized_server_connection_id_(EmptyQuicConnectionId()),
414 last_serialized_client_connection_id_(EmptyQuicConnectionId()),
415 version_(ParsedQuicVersion::Unsupported()),
416 supported_versions_(supported_versions),
417 decrypter_level_(ENCRYPTION_INITIAL),
418 alternative_decrypter_level_(NUM_ENCRYPTION_LEVELS),
419 alternative_decrypter_latch_(false),
420 perspective_(perspective),
421 validate_flags_(true),
422 process_timestamps_(false),
423 max_receive_timestamps_per_ack_(std::numeric_limits<uint32_t>::max()),
424 receive_timestamps_exponent_(0),
425 creation_time_(creation_time),
426 last_timestamp_(QuicTime::Delta::Zero()),
427 support_key_update_for_connection_(false),
428 current_key_phase_bit_(false),
429 potential_peer_key_update_attempt_count_(0),
430 first_sending_packet_number_(FirstSendingPacketNumber()),
431 data_producer_(nullptr),
432 infer_packet_header_type_from_version_(perspective ==
433 Perspective::IS_CLIENT),
434 expected_server_connection_id_length_(
435 expected_server_connection_id_length),
436 expected_client_connection_id_length_(0),
437 supports_multiple_packet_number_spaces_(false),
438 last_written_packet_number_length_(0),
439 peer_ack_delay_exponent_(kDefaultAckDelayExponent),
440 local_ack_delay_exponent_(kDefaultAckDelayExponent),
441 current_received_frame_type_(0),
442 previously_received_frame_type_(0) {
443 QUICHE_DCHECK(!supported_versions.empty());
444 version_ = supported_versions_[0];
445 QUICHE_DCHECK(version_.IsKnown())
446 << ParsedQuicVersionVectorToString(supported_versions_);
447 }
448
~QuicFramer()449 QuicFramer::~QuicFramer() {}
450
451 // static
GetMinStreamFrameSize(QuicTransportVersion version,QuicStreamId stream_id,QuicStreamOffset offset,bool last_frame_in_packet,size_t data_length)452 size_t QuicFramer::GetMinStreamFrameSize(QuicTransportVersion version,
453 QuicStreamId stream_id,
454 QuicStreamOffset offset,
455 bool last_frame_in_packet,
456 size_t data_length) {
457 if (VersionHasIetfQuicFrames(version)) {
458 return kQuicFrameTypeSize + QuicDataWriter::GetVarInt62Len(stream_id) +
459 (last_frame_in_packet
460 ? 0
461 : QuicDataWriter::GetVarInt62Len(data_length)) +
462 (offset != 0 ? QuicDataWriter::GetVarInt62Len(offset) : 0);
463 }
464 return kQuicFrameTypeSize + GetStreamIdSize(stream_id) +
465 GetStreamOffsetSize(offset) +
466 (last_frame_in_packet ? 0 : kQuicStreamPayloadLengthSize);
467 }
468
469 // static
GetMinCryptoFrameSize(QuicStreamOffset offset,QuicPacketLength data_length)470 size_t QuicFramer::GetMinCryptoFrameSize(QuicStreamOffset offset,
471 QuicPacketLength data_length) {
472 return kQuicFrameTypeSize + QuicDataWriter::GetVarInt62Len(offset) +
473 QuicDataWriter::GetVarInt62Len(data_length);
474 }
475
476 // static
GetMessageFrameSize(QuicTransportVersion version,bool last_frame_in_packet,QuicByteCount length)477 size_t QuicFramer::GetMessageFrameSize(QuicTransportVersion version,
478 bool last_frame_in_packet,
479 QuicByteCount length) {
480 QUIC_BUG_IF(quic_bug_12975_1, !VersionSupportsMessageFrames(version))
481 << "Try to serialize MESSAGE frame in " << version;
482 return kQuicFrameTypeSize +
483 (last_frame_in_packet ? 0 : QuicDataWriter::GetVarInt62Len(length)) +
484 length;
485 }
486
487 // static
GetMinAckFrameSize(QuicTransportVersion version,const QuicAckFrame & ack_frame,uint32_t local_ack_delay_exponent,bool use_ietf_ack_with_receive_timestamp)488 size_t QuicFramer::GetMinAckFrameSize(
489 QuicTransportVersion version, const QuicAckFrame& ack_frame,
490 uint32_t local_ack_delay_exponent,
491 bool use_ietf_ack_with_receive_timestamp) {
492 if (VersionHasIetfQuicFrames(version)) {
493 // The minimal ack frame consists of the following fields: Largest
494 // Acknowledged, ACK Delay, 0 ACK Block Count, First ACK Block and either 0
495 // Timestamp Range Count or ECN counts.
496 // Type byte + largest acked.
497 size_t min_size =
498 kQuicFrameTypeSize +
499 QuicDataWriter::GetVarInt62Len(LargestAcked(ack_frame).ToUint64());
500 // Ack delay.
501 min_size += QuicDataWriter::GetVarInt62Len(
502 ack_frame.ack_delay_time.ToMicroseconds() >> local_ack_delay_exponent);
503 // 0 ack block count.
504 min_size += QuicDataWriter::GetVarInt62Len(0);
505 // First ack block.
506 min_size += QuicDataWriter::GetVarInt62Len(
507 ack_frame.packets.Empty() ? 0
508 : ack_frame.packets.rbegin()->Length() - 1);
509
510 if (use_ietf_ack_with_receive_timestamp) {
511 // 0 Timestamp Range Count.
512 min_size += QuicDataWriter::GetVarInt62Len(0);
513 } else {
514 min_size += AckEcnCountSize(ack_frame);
515 }
516 return min_size;
517 }
518 return kQuicFrameTypeSize +
519 GetMinPacketNumberLength(LargestAcked(ack_frame)) +
520 kQuicDeltaTimeLargestObservedSize + kQuicNumTimestampsSize;
521 }
522
523 // static
GetStopWaitingFrameSize(QuicPacketNumberLength packet_number_length)524 size_t QuicFramer::GetStopWaitingFrameSize(
525 QuicPacketNumberLength packet_number_length) {
526 size_t min_size = kQuicFrameTypeSize + packet_number_length;
527 return min_size;
528 }
529
530 // static
GetRstStreamFrameSize(QuicTransportVersion version,const QuicRstStreamFrame & frame)531 size_t QuicFramer::GetRstStreamFrameSize(QuicTransportVersion version,
532 const QuicRstStreamFrame& frame) {
533 if (VersionHasIetfQuicFrames(version)) {
534 return QuicDataWriter::GetVarInt62Len(frame.stream_id) +
535 QuicDataWriter::GetVarInt62Len(frame.byte_offset) +
536 kQuicFrameTypeSize +
537 QuicDataWriter::GetVarInt62Len(frame.ietf_error_code);
538 }
539 return kQuicFrameTypeSize + kQuicMaxStreamIdSize + kQuicMaxStreamOffsetSize +
540 kQuicErrorCodeSize;
541 }
542
543 // static
GetConnectionCloseFrameSize(QuicTransportVersion version,const QuicConnectionCloseFrame & frame)544 size_t QuicFramer::GetConnectionCloseFrameSize(
545 QuicTransportVersion version, const QuicConnectionCloseFrame& frame) {
546 if (!VersionHasIetfQuicFrames(version)) {
547 // Not IETF QUIC, return Google QUIC CONNECTION CLOSE frame size.
548 return kQuicFrameTypeSize + kQuicErrorCodeSize +
549 kQuicErrorDetailsLengthSize +
550 TruncatedErrorStringSize(frame.error_details);
551 }
552
553 // Prepend the extra error information to the string and get the result's
554 // length.
555 const size_t truncated_error_string_size = TruncatedErrorStringSize(
556 GenerateErrorString(frame.error_details, frame.quic_error_code));
557
558 const size_t frame_size =
559 truncated_error_string_size +
560 QuicDataWriter::GetVarInt62Len(truncated_error_string_size) +
561 kQuicFrameTypeSize +
562 QuicDataWriter::GetVarInt62Len(frame.wire_error_code);
563 if (frame.close_type == IETF_QUIC_APPLICATION_CONNECTION_CLOSE) {
564 return frame_size;
565 }
566 // The Transport close frame has the transport_close_frame_type, so include
567 // its length.
568 return frame_size +
569 QuicDataWriter::GetVarInt62Len(frame.transport_close_frame_type);
570 }
571
572 // static
GetMinGoAwayFrameSize()573 size_t QuicFramer::GetMinGoAwayFrameSize() {
574 return kQuicFrameTypeSize + kQuicErrorCodeSize + kQuicErrorDetailsLengthSize +
575 kQuicMaxStreamIdSize;
576 }
577
578 // static
GetWindowUpdateFrameSize(QuicTransportVersion version,const QuicWindowUpdateFrame & frame)579 size_t QuicFramer::GetWindowUpdateFrameSize(
580 QuicTransportVersion version, const QuicWindowUpdateFrame& frame) {
581 if (!VersionHasIetfQuicFrames(version)) {
582 return kQuicFrameTypeSize + kQuicMaxStreamIdSize + kQuicMaxStreamOffsetSize;
583 }
584 if (frame.stream_id == QuicUtils::GetInvalidStreamId(version)) {
585 // Frame would be a MAX DATA frame, which has only a Maximum Data field.
586 return kQuicFrameTypeSize + QuicDataWriter::GetVarInt62Len(frame.max_data);
587 }
588 // Frame would be MAX STREAM DATA, has Maximum Stream Data and Stream ID
589 // fields.
590 return kQuicFrameTypeSize + QuicDataWriter::GetVarInt62Len(frame.max_data) +
591 QuicDataWriter::GetVarInt62Len(frame.stream_id);
592 }
593
594 // static
GetMaxStreamsFrameSize(QuicTransportVersion version,const QuicMaxStreamsFrame & frame)595 size_t QuicFramer::GetMaxStreamsFrameSize(QuicTransportVersion version,
596 const QuicMaxStreamsFrame& frame) {
597 if (!VersionHasIetfQuicFrames(version)) {
598 QUIC_BUG(quic_bug_10850_9)
599 << "In version " << version
600 << ", which does not support IETF Frames, and tried to serialize "
601 "MaxStreams Frame.";
602 }
603 return kQuicFrameTypeSize +
604 QuicDataWriter::GetVarInt62Len(frame.stream_count);
605 }
606
607 // static
GetStreamsBlockedFrameSize(QuicTransportVersion version,const QuicStreamsBlockedFrame & frame)608 size_t QuicFramer::GetStreamsBlockedFrameSize(
609 QuicTransportVersion version, const QuicStreamsBlockedFrame& frame) {
610 if (!VersionHasIetfQuicFrames(version)) {
611 QUIC_BUG(quic_bug_10850_10)
612 << "In version " << version
613 << ", which does not support IETF frames, and tried to serialize "
614 "StreamsBlocked Frame.";
615 }
616
617 return kQuicFrameTypeSize +
618 QuicDataWriter::GetVarInt62Len(frame.stream_count);
619 }
620
621 // static
GetBlockedFrameSize(QuicTransportVersion version,const QuicBlockedFrame & frame)622 size_t QuicFramer::GetBlockedFrameSize(QuicTransportVersion version,
623 const QuicBlockedFrame& frame) {
624 if (!VersionHasIetfQuicFrames(version)) {
625 return kQuicFrameTypeSize + kQuicMaxStreamIdSize;
626 }
627 if (frame.stream_id == QuicUtils::GetInvalidStreamId(version)) {
628 // return size of IETF QUIC Blocked frame
629 return kQuicFrameTypeSize + QuicDataWriter::GetVarInt62Len(frame.offset);
630 }
631 // return size of IETF QUIC Stream Blocked frame.
632 return kQuicFrameTypeSize + QuicDataWriter::GetVarInt62Len(frame.offset) +
633 QuicDataWriter::GetVarInt62Len(frame.stream_id);
634 }
635
636 // static
GetStopSendingFrameSize(const QuicStopSendingFrame & frame)637 size_t QuicFramer::GetStopSendingFrameSize(const QuicStopSendingFrame& frame) {
638 return kQuicFrameTypeSize + QuicDataWriter::GetVarInt62Len(frame.stream_id) +
639 QuicDataWriter::GetVarInt62Len(frame.ietf_error_code);
640 }
641
642 // static
GetAckFrequencyFrameSize(const QuicAckFrequencyFrame & frame)643 size_t QuicFramer::GetAckFrequencyFrameSize(
644 const QuicAckFrequencyFrame& frame) {
645 return QuicDataWriter::GetVarInt62Len(IETF_ACK_FREQUENCY) +
646 QuicDataWriter::GetVarInt62Len(frame.sequence_number) +
647 QuicDataWriter::GetVarInt62Len(frame.packet_tolerance) +
648 QuicDataWriter::GetVarInt62Len(frame.max_ack_delay.ToMicroseconds()) +
649 // One byte for encoding boolean
650 1;
651 }
652
653 // static
GetPathChallengeFrameSize(const QuicPathChallengeFrame & frame)654 size_t QuicFramer::GetPathChallengeFrameSize(
655 const QuicPathChallengeFrame& frame) {
656 return kQuicFrameTypeSize + sizeof(frame.data_buffer);
657 }
658
659 // static
GetPathResponseFrameSize(const QuicPathResponseFrame & frame)660 size_t QuicFramer::GetPathResponseFrameSize(
661 const QuicPathResponseFrame& frame) {
662 return kQuicFrameTypeSize + sizeof(frame.data_buffer);
663 }
664
665 // static
GetRetransmittableControlFrameSize(QuicTransportVersion version,const QuicFrame & frame)666 size_t QuicFramer::GetRetransmittableControlFrameSize(
667 QuicTransportVersion version, const QuicFrame& frame) {
668 switch (frame.type) {
669 case PING_FRAME:
670 // Ping has no payload.
671 return kQuicFrameTypeSize;
672 case RST_STREAM_FRAME:
673 return GetRstStreamFrameSize(version, *frame.rst_stream_frame);
674 case CONNECTION_CLOSE_FRAME:
675 return GetConnectionCloseFrameSize(version,
676 *frame.connection_close_frame);
677 case GOAWAY_FRAME:
678 return GetMinGoAwayFrameSize() +
679 TruncatedErrorStringSize(frame.goaway_frame->reason_phrase);
680 case WINDOW_UPDATE_FRAME:
681 // For IETF QUIC, this could be either a MAX DATA or MAX STREAM DATA.
682 // GetWindowUpdateFrameSize figures this out and returns the correct
683 // length.
684 return GetWindowUpdateFrameSize(version, frame.window_update_frame);
685 case BLOCKED_FRAME:
686 return GetBlockedFrameSize(version, frame.blocked_frame);
687 case NEW_CONNECTION_ID_FRAME:
688 return GetNewConnectionIdFrameSize(*frame.new_connection_id_frame);
689 case RETIRE_CONNECTION_ID_FRAME:
690 return GetRetireConnectionIdFrameSize(*frame.retire_connection_id_frame);
691 case NEW_TOKEN_FRAME:
692 return GetNewTokenFrameSize(*frame.new_token_frame);
693 case MAX_STREAMS_FRAME:
694 return GetMaxStreamsFrameSize(version, frame.max_streams_frame);
695 case STREAMS_BLOCKED_FRAME:
696 return GetStreamsBlockedFrameSize(version, frame.streams_blocked_frame);
697 case PATH_RESPONSE_FRAME:
698 return GetPathResponseFrameSize(frame.path_response_frame);
699 case PATH_CHALLENGE_FRAME:
700 return GetPathChallengeFrameSize(frame.path_challenge_frame);
701 case STOP_SENDING_FRAME:
702 return GetStopSendingFrameSize(frame.stop_sending_frame);
703 case HANDSHAKE_DONE_FRAME:
704 // HANDSHAKE_DONE has no payload.
705 return kQuicFrameTypeSize;
706 case ACK_FREQUENCY_FRAME:
707 return GetAckFrequencyFrameSize(*frame.ack_frequency_frame);
708 case STREAM_FRAME:
709 case ACK_FRAME:
710 case STOP_WAITING_FRAME:
711 case MTU_DISCOVERY_FRAME:
712 case PADDING_FRAME:
713 case MESSAGE_FRAME:
714 case CRYPTO_FRAME:
715 case NUM_FRAME_TYPES:
716 QUICHE_DCHECK(false);
717 return 0;
718 }
719
720 // Not reachable, but some Chrome compilers can't figure that out. *sigh*
721 QUICHE_DCHECK(false);
722 return 0;
723 }
724
725 // static
GetStreamIdSize(QuicStreamId stream_id)726 size_t QuicFramer::GetStreamIdSize(QuicStreamId stream_id) {
727 // Sizes are 1 through 4 bytes.
728 for (int i = 1; i <= 4; ++i) {
729 stream_id >>= 8;
730 if (stream_id == 0) {
731 return i;
732 }
733 }
734 QUIC_BUG(quic_bug_10850_11) << "Failed to determine StreamIDSize.";
735 return 4;
736 }
737
738 // static
GetStreamOffsetSize(QuicStreamOffset offset)739 size_t QuicFramer::GetStreamOffsetSize(QuicStreamOffset offset) {
740 // 0 is a special case.
741 if (offset == 0) {
742 return 0;
743 }
744 // 2 through 8 are the remaining sizes.
745 offset >>= 8;
746 for (int i = 2; i <= 8; ++i) {
747 offset >>= 8;
748 if (offset == 0) {
749 return i;
750 }
751 }
752 QUIC_BUG(quic_bug_10850_12) << "Failed to determine StreamOffsetSize.";
753 return 8;
754 }
755
756 // static
GetNewConnectionIdFrameSize(const QuicNewConnectionIdFrame & frame)757 size_t QuicFramer::GetNewConnectionIdFrameSize(
758 const QuicNewConnectionIdFrame& frame) {
759 return kQuicFrameTypeSize +
760 QuicDataWriter::GetVarInt62Len(frame.sequence_number) +
761 QuicDataWriter::GetVarInt62Len(frame.retire_prior_to) +
762 kConnectionIdLengthSize + frame.connection_id.length() +
763 sizeof(frame.stateless_reset_token);
764 }
765
766 // static
GetRetireConnectionIdFrameSize(const QuicRetireConnectionIdFrame & frame)767 size_t QuicFramer::GetRetireConnectionIdFrameSize(
768 const QuicRetireConnectionIdFrame& frame) {
769 return kQuicFrameTypeSize +
770 QuicDataWriter::GetVarInt62Len(frame.sequence_number);
771 }
772
773 // static
GetNewTokenFrameSize(const QuicNewTokenFrame & frame)774 size_t QuicFramer::GetNewTokenFrameSize(const QuicNewTokenFrame& frame) {
775 return kQuicFrameTypeSize +
776 QuicDataWriter::GetVarInt62Len(frame.token.length()) +
777 frame.token.length();
778 }
779
780 // TODO(nharper): Change this method to take a ParsedQuicVersion.
IsSupportedTransportVersion(const QuicTransportVersion version) const781 bool QuicFramer::IsSupportedTransportVersion(
782 const QuicTransportVersion version) const {
783 for (const ParsedQuicVersion& supported_version : supported_versions_) {
784 if (version == supported_version.transport_version) {
785 return true;
786 }
787 }
788 return false;
789 }
790
IsSupportedVersion(const ParsedQuicVersion version) const791 bool QuicFramer::IsSupportedVersion(const ParsedQuicVersion version) const {
792 for (const ParsedQuicVersion& supported_version : supported_versions_) {
793 if (version == supported_version) {
794 return true;
795 }
796 }
797 return false;
798 }
799
GetSerializedFrameLength(const QuicFrame & frame,size_t free_bytes,bool first_frame,bool last_frame,QuicPacketNumberLength packet_number_length)800 size_t QuicFramer::GetSerializedFrameLength(
801 const QuicFrame& frame, size_t free_bytes, bool first_frame,
802 bool last_frame, QuicPacketNumberLength packet_number_length) {
803 // Prevent a rare crash reported in b/19458523.
804 if (frame.type == ACK_FRAME && frame.ack_frame == nullptr) {
805 QUIC_BUG(quic_bug_10850_13)
806 << "Cannot compute the length of a null ack frame. free_bytes:"
807 << free_bytes << " first_frame:" << first_frame
808 << " last_frame:" << last_frame
809 << " seq num length:" << packet_number_length;
810 set_error(QUIC_INTERNAL_ERROR);
811 visitor_->OnError(this);
812 return 0;
813 }
814 if (frame.type == PADDING_FRAME) {
815 if (frame.padding_frame.num_padding_bytes == -1) {
816 // Full padding to the end of the packet.
817 return free_bytes;
818 } else {
819 // Lite padding.
820 return free_bytes <
821 static_cast<size_t>(frame.padding_frame.num_padding_bytes)
822 ? free_bytes
823 : frame.padding_frame.num_padding_bytes;
824 }
825 }
826
827 size_t frame_len =
828 ComputeFrameLength(frame, last_frame, packet_number_length);
829 if (frame_len <= free_bytes) {
830 // Frame fits within packet. Note that acks may be truncated.
831 return frame_len;
832 }
833 // Only truncate the first frame in a packet, so if subsequent ones go
834 // over, stop including more frames.
835 if (!first_frame) {
836 return 0;
837 }
838 bool can_truncate =
839 frame.type == ACK_FRAME &&
840 free_bytes >=
841 GetMinAckFrameSize(version_.transport_version, *frame.ack_frame,
842 local_ack_delay_exponent_,
843 UseIetfAckWithReceiveTimestamp(*frame.ack_frame));
844 if (can_truncate) {
845 // Truncate the frame so the packet will not exceed kMaxOutgoingPacketSize.
846 // Note that we may not use every byte of the writer in this case.
847 QUIC_DLOG(INFO) << ENDPOINT
848 << "Truncating large frame, free bytes: " << free_bytes;
849 return free_bytes;
850 }
851 return 0;
852 }
853
AckFrameInfo()854 QuicFramer::AckFrameInfo::AckFrameInfo()
855 : max_block_length(0), first_block_length(0), num_ack_blocks(0) {}
856
857 QuicFramer::AckFrameInfo::AckFrameInfo(const AckFrameInfo& other) = default;
858
~AckFrameInfo()859 QuicFramer::AckFrameInfo::~AckFrameInfo() {}
860
WriteIetfLongHeaderLength(const QuicPacketHeader & header,QuicDataWriter * writer,size_t length_field_offset,EncryptionLevel level)861 bool QuicFramer::WriteIetfLongHeaderLength(const QuicPacketHeader& header,
862 QuicDataWriter* writer,
863 size_t length_field_offset,
864 EncryptionLevel level) {
865 if (!QuicVersionHasLongHeaderLengths(transport_version()) ||
866 !header.version_flag || length_field_offset == 0) {
867 return true;
868 }
869 if (writer->length() < length_field_offset ||
870 writer->length() - length_field_offset <
871 quiche::kQuicheDefaultLongHeaderLengthLength) {
872 set_detailed_error("Invalid length_field_offset.");
873 QUIC_BUG(quic_bug_10850_14) << "Invalid length_field_offset.";
874 return false;
875 }
876 size_t length_to_write = writer->length() - length_field_offset -
877 quiche::kQuicheDefaultLongHeaderLengthLength;
878 // Add length of auth tag.
879 length_to_write = GetCiphertextSize(level, length_to_write);
880
881 QuicDataWriter length_writer(writer->length() - length_field_offset,
882 writer->data() + length_field_offset);
883 if (!length_writer.WriteVarInt62WithForcedLength(
884 length_to_write, quiche::kQuicheDefaultLongHeaderLengthLength)) {
885 set_detailed_error("Failed to overwrite long header length.");
886 QUIC_BUG(quic_bug_10850_15) << "Failed to overwrite long header length.";
887 return false;
888 }
889 return true;
890 }
891
BuildDataPacket(const QuicPacketHeader & header,const QuicFrames & frames,char * buffer,size_t packet_length,EncryptionLevel level)892 size_t QuicFramer::BuildDataPacket(const QuicPacketHeader& header,
893 const QuicFrames& frames, char* buffer,
894 size_t packet_length,
895 EncryptionLevel level) {
896 QUIC_BUG_IF(quic_bug_12975_2,
897 header.version_flag && version().HasIetfInvariantHeader() &&
898 header.long_packet_type == RETRY && !frames.empty())
899 << "IETF RETRY packets cannot contain frames " << header;
900 QuicDataWriter writer(packet_length, buffer);
901 size_t length_field_offset = 0;
902 if (!AppendPacketHeader(header, &writer, &length_field_offset)) {
903 QUIC_BUG(quic_bug_10850_16) << "AppendPacketHeader failed";
904 return 0;
905 }
906
907 if (VersionHasIetfQuicFrames(transport_version())) {
908 if (AppendIetfFrames(frames, &writer) == 0) {
909 return 0;
910 }
911 if (!WriteIetfLongHeaderLength(header, &writer, length_field_offset,
912 level)) {
913 return 0;
914 }
915 return writer.length();
916 }
917
918 size_t i = 0;
919 for (const QuicFrame& frame : frames) {
920 // Determine if we should write stream frame length in header.
921 const bool last_frame_in_packet = i == frames.size() - 1;
922 if (!AppendTypeByte(frame, last_frame_in_packet, &writer)) {
923 QUIC_BUG(quic_bug_10850_17) << "AppendTypeByte failed";
924 return 0;
925 }
926
927 switch (frame.type) {
928 case PADDING_FRAME:
929 if (!AppendPaddingFrame(frame.padding_frame, &writer)) {
930 QUIC_BUG(quic_bug_10850_18)
931 << "AppendPaddingFrame of "
932 << frame.padding_frame.num_padding_bytes << " failed";
933 return 0;
934 }
935 break;
936 case STREAM_FRAME:
937 if (!AppendStreamFrame(frame.stream_frame, last_frame_in_packet,
938 &writer)) {
939 QUIC_BUG(quic_bug_10850_19) << "AppendStreamFrame failed";
940 return 0;
941 }
942 break;
943 case ACK_FRAME:
944 if (!AppendAckFrameAndTypeByte(*frame.ack_frame, &writer)) {
945 QUIC_BUG(quic_bug_10850_20)
946 << "AppendAckFrameAndTypeByte failed: " << detailed_error_;
947 return 0;
948 }
949 break;
950 case STOP_WAITING_FRAME:
951 if (!AppendStopWaitingFrame(header, frame.stop_waiting_frame,
952 &writer)) {
953 QUIC_BUG(quic_bug_10850_21) << "AppendStopWaitingFrame failed";
954 return 0;
955 }
956 break;
957 case MTU_DISCOVERY_FRAME:
958 // MTU discovery frames are serialized as ping frames.
959 ABSL_FALLTHROUGH_INTENDED;
960 case PING_FRAME:
961 // Ping has no payload.
962 break;
963 case RST_STREAM_FRAME:
964 if (!AppendRstStreamFrame(*frame.rst_stream_frame, &writer)) {
965 QUIC_BUG(quic_bug_10850_22) << "AppendRstStreamFrame failed";
966 return 0;
967 }
968 break;
969 case CONNECTION_CLOSE_FRAME:
970 if (!AppendConnectionCloseFrame(*frame.connection_close_frame,
971 &writer)) {
972 QUIC_BUG(quic_bug_10850_23) << "AppendConnectionCloseFrame failed";
973 return 0;
974 }
975 break;
976 case GOAWAY_FRAME:
977 if (!AppendGoAwayFrame(*frame.goaway_frame, &writer)) {
978 QUIC_BUG(quic_bug_10850_24) << "AppendGoAwayFrame failed";
979 return 0;
980 }
981 break;
982 case WINDOW_UPDATE_FRAME:
983 if (!AppendWindowUpdateFrame(frame.window_update_frame, &writer)) {
984 QUIC_BUG(quic_bug_10850_25) << "AppendWindowUpdateFrame failed";
985 return 0;
986 }
987 break;
988 case BLOCKED_FRAME:
989 if (!AppendBlockedFrame(frame.blocked_frame, &writer)) {
990 QUIC_BUG(quic_bug_10850_26) << "AppendBlockedFrame failed";
991 return 0;
992 }
993 break;
994 case NEW_CONNECTION_ID_FRAME:
995 set_detailed_error(
996 "Attempt to append NEW_CONNECTION_ID frame and not in IETF QUIC.");
997 return RaiseError(QUIC_INTERNAL_ERROR);
998 case RETIRE_CONNECTION_ID_FRAME:
999 set_detailed_error(
1000 "Attempt to append RETIRE_CONNECTION_ID frame and not in IETF "
1001 "QUIC.");
1002 return RaiseError(QUIC_INTERNAL_ERROR);
1003 case NEW_TOKEN_FRAME:
1004 set_detailed_error(
1005 "Attempt to append NEW_TOKEN_ID frame and not in IETF QUIC.");
1006 return RaiseError(QUIC_INTERNAL_ERROR);
1007 case MAX_STREAMS_FRAME:
1008 set_detailed_error(
1009 "Attempt to append MAX_STREAMS frame and not in IETF QUIC.");
1010 return RaiseError(QUIC_INTERNAL_ERROR);
1011 case STREAMS_BLOCKED_FRAME:
1012 set_detailed_error(
1013 "Attempt to append STREAMS_BLOCKED frame and not in IETF QUIC.");
1014 return RaiseError(QUIC_INTERNAL_ERROR);
1015 case PATH_RESPONSE_FRAME:
1016 set_detailed_error(
1017 "Attempt to append PATH_RESPONSE frame and not in IETF QUIC.");
1018 return RaiseError(QUIC_INTERNAL_ERROR);
1019 case PATH_CHALLENGE_FRAME:
1020 set_detailed_error(
1021 "Attempt to append PATH_CHALLENGE frame and not in IETF QUIC.");
1022 return RaiseError(QUIC_INTERNAL_ERROR);
1023 case STOP_SENDING_FRAME:
1024 set_detailed_error(
1025 "Attempt to append STOP_SENDING frame and not in IETF QUIC.");
1026 return RaiseError(QUIC_INTERNAL_ERROR);
1027 case MESSAGE_FRAME:
1028 if (!AppendMessageFrameAndTypeByte(*frame.message_frame,
1029 last_frame_in_packet, &writer)) {
1030 QUIC_BUG(quic_bug_10850_27) << "AppendMessageFrame failed";
1031 return 0;
1032 }
1033 break;
1034 case CRYPTO_FRAME:
1035 if (!QuicVersionUsesCryptoFrames(version_.transport_version)) {
1036 set_detailed_error(
1037 "Attempt to append CRYPTO frame in version prior to 47.");
1038 return RaiseError(QUIC_INTERNAL_ERROR);
1039 }
1040 if (!AppendCryptoFrame(*frame.crypto_frame, &writer)) {
1041 QUIC_BUG(quic_bug_10850_28) << "AppendCryptoFrame failed";
1042 return 0;
1043 }
1044 break;
1045 case HANDSHAKE_DONE_FRAME:
1046 // HANDSHAKE_DONE has no payload.
1047 break;
1048 default:
1049 RaiseError(QUIC_INVALID_FRAME_DATA);
1050 QUIC_BUG(quic_bug_10850_29) << "QUIC_INVALID_FRAME_DATA";
1051 return 0;
1052 }
1053 ++i;
1054 }
1055
1056 if (!WriteIetfLongHeaderLength(header, &writer, length_field_offset, level)) {
1057 return 0;
1058 }
1059
1060 return writer.length();
1061 }
1062
AppendIetfFrames(const QuicFrames & frames,QuicDataWriter * writer)1063 size_t QuicFramer::AppendIetfFrames(const QuicFrames& frames,
1064 QuicDataWriter* writer) {
1065 size_t i = 0;
1066 for (const QuicFrame& frame : frames) {
1067 // Determine if we should write stream frame length in header.
1068 const bool last_frame_in_packet = i == frames.size() - 1;
1069 if (!AppendIetfFrameType(frame, last_frame_in_packet, writer)) {
1070 QUIC_BUG(quic_bug_10850_30)
1071 << "AppendIetfFrameType failed: " << detailed_error();
1072 return 0;
1073 }
1074
1075 switch (frame.type) {
1076 case PADDING_FRAME:
1077 if (!AppendPaddingFrame(frame.padding_frame, writer)) {
1078 QUIC_BUG(quic_bug_10850_31) << "AppendPaddingFrame of "
1079 << frame.padding_frame.num_padding_bytes
1080 << " failed: " << detailed_error();
1081 return 0;
1082 }
1083 break;
1084 case STREAM_FRAME:
1085 if (!AppendStreamFrame(frame.stream_frame, last_frame_in_packet,
1086 writer)) {
1087 QUIC_BUG(quic_bug_10850_32)
1088 << "AppendStreamFrame " << frame.stream_frame
1089 << " failed: " << detailed_error();
1090 return 0;
1091 }
1092 break;
1093 case ACK_FRAME:
1094 if (!AppendIetfAckFrameAndTypeByte(*frame.ack_frame, writer)) {
1095 QUIC_BUG(quic_bug_10850_33)
1096 << "AppendIetfAckFrameAndTypeByte failed: " << detailed_error();
1097 return 0;
1098 }
1099 break;
1100 case STOP_WAITING_FRAME:
1101 set_detailed_error(
1102 "Attempt to append STOP WAITING frame in IETF QUIC.");
1103 RaiseError(QUIC_INTERNAL_ERROR);
1104 QUIC_BUG(quic_bug_10850_34) << detailed_error();
1105 return 0;
1106 case MTU_DISCOVERY_FRAME:
1107 // MTU discovery frames are serialized as ping frames.
1108 ABSL_FALLTHROUGH_INTENDED;
1109 case PING_FRAME:
1110 // Ping has no payload.
1111 break;
1112 case RST_STREAM_FRAME:
1113 if (!AppendRstStreamFrame(*frame.rst_stream_frame, writer)) {
1114 QUIC_BUG(quic_bug_10850_35)
1115 << "AppendRstStreamFrame failed: " << detailed_error();
1116 return 0;
1117 }
1118 break;
1119 case CONNECTION_CLOSE_FRAME:
1120 if (!AppendIetfConnectionCloseFrame(*frame.connection_close_frame,
1121 writer)) {
1122 QUIC_BUG(quic_bug_10850_36)
1123 << "AppendIetfConnectionCloseFrame failed: " << detailed_error();
1124 return 0;
1125 }
1126 break;
1127 case GOAWAY_FRAME:
1128 set_detailed_error("Attempt to append GOAWAY frame in IETF QUIC.");
1129 RaiseError(QUIC_INTERNAL_ERROR);
1130 QUIC_BUG(quic_bug_10850_37) << detailed_error();
1131 return 0;
1132 case WINDOW_UPDATE_FRAME:
1133 // Depending on whether there is a stream ID or not, will be either a
1134 // MAX STREAM DATA frame or a MAX DATA frame.
1135 if (frame.window_update_frame.stream_id ==
1136 QuicUtils::GetInvalidStreamId(transport_version())) {
1137 if (!AppendMaxDataFrame(frame.window_update_frame, writer)) {
1138 QUIC_BUG(quic_bug_10850_38)
1139 << "AppendMaxDataFrame failed: " << detailed_error();
1140 return 0;
1141 }
1142 } else {
1143 if (!AppendMaxStreamDataFrame(frame.window_update_frame, writer)) {
1144 QUIC_BUG(quic_bug_10850_39)
1145 << "AppendMaxStreamDataFrame failed: " << detailed_error();
1146 return 0;
1147 }
1148 }
1149 break;
1150 case BLOCKED_FRAME:
1151 if (!AppendBlockedFrame(frame.blocked_frame, writer)) {
1152 QUIC_BUG(quic_bug_10850_40)
1153 << "AppendBlockedFrame failed: " << detailed_error();
1154 return 0;
1155 }
1156 break;
1157 case MAX_STREAMS_FRAME:
1158 if (!AppendMaxStreamsFrame(frame.max_streams_frame, writer)) {
1159 QUIC_BUG(quic_bug_10850_41)
1160 << "AppendMaxStreamsFrame failed: " << detailed_error();
1161 return 0;
1162 }
1163 break;
1164 case STREAMS_BLOCKED_FRAME:
1165 if (!AppendStreamsBlockedFrame(frame.streams_blocked_frame, writer)) {
1166 QUIC_BUG(quic_bug_10850_42)
1167 << "AppendStreamsBlockedFrame failed: " << detailed_error();
1168 return 0;
1169 }
1170 break;
1171 case NEW_CONNECTION_ID_FRAME:
1172 if (!AppendNewConnectionIdFrame(*frame.new_connection_id_frame,
1173 writer)) {
1174 QUIC_BUG(quic_bug_10850_43)
1175 << "AppendNewConnectionIdFrame failed: " << detailed_error();
1176 return 0;
1177 }
1178 break;
1179 case RETIRE_CONNECTION_ID_FRAME:
1180 if (!AppendRetireConnectionIdFrame(*frame.retire_connection_id_frame,
1181 writer)) {
1182 QUIC_BUG(quic_bug_10850_44)
1183 << "AppendRetireConnectionIdFrame failed: " << detailed_error();
1184 return 0;
1185 }
1186 break;
1187 case NEW_TOKEN_FRAME:
1188 if (!AppendNewTokenFrame(*frame.new_token_frame, writer)) {
1189 QUIC_BUG(quic_bug_10850_45)
1190 << "AppendNewTokenFrame failed: " << detailed_error();
1191 return 0;
1192 }
1193 break;
1194 case STOP_SENDING_FRAME:
1195 if (!AppendStopSendingFrame(frame.stop_sending_frame, writer)) {
1196 QUIC_BUG(quic_bug_10850_46)
1197 << "AppendStopSendingFrame failed: " << detailed_error();
1198 return 0;
1199 }
1200 break;
1201 case PATH_CHALLENGE_FRAME:
1202 if (!AppendPathChallengeFrame(frame.path_challenge_frame, writer)) {
1203 QUIC_BUG(quic_bug_10850_47)
1204 << "AppendPathChallengeFrame failed: " << detailed_error();
1205 return 0;
1206 }
1207 break;
1208 case PATH_RESPONSE_FRAME:
1209 if (!AppendPathResponseFrame(frame.path_response_frame, writer)) {
1210 QUIC_BUG(quic_bug_10850_48)
1211 << "AppendPathResponseFrame failed: " << detailed_error();
1212 return 0;
1213 }
1214 break;
1215 case MESSAGE_FRAME:
1216 if (!AppendMessageFrameAndTypeByte(*frame.message_frame,
1217 last_frame_in_packet, writer)) {
1218 QUIC_BUG(quic_bug_10850_49)
1219 << "AppendMessageFrame failed: " << detailed_error();
1220 return 0;
1221 }
1222 break;
1223 case CRYPTO_FRAME:
1224 if (!AppendCryptoFrame(*frame.crypto_frame, writer)) {
1225 QUIC_BUG(quic_bug_10850_50)
1226 << "AppendCryptoFrame failed: " << detailed_error();
1227 return 0;
1228 }
1229 break;
1230 case HANDSHAKE_DONE_FRAME:
1231 // HANDSHAKE_DONE has no payload.
1232 break;
1233 case ACK_FREQUENCY_FRAME:
1234 if (!AppendAckFrequencyFrame(*frame.ack_frequency_frame, writer)) {
1235 QUIC_BUG(quic_bug_10850_51)
1236 << "AppendAckFrequencyFrame failed: " << detailed_error();
1237 return 0;
1238 }
1239 break;
1240 default:
1241 set_detailed_error("Tried to append unknown frame type.");
1242 RaiseError(QUIC_INVALID_FRAME_DATA);
1243 QUIC_BUG(quic_bug_10850_52)
1244 << "QUIC_INVALID_FRAME_DATA: " << frame.type;
1245 return 0;
1246 }
1247 ++i;
1248 }
1249
1250 return writer->length();
1251 }
1252
1253 // static
BuildPublicResetPacket(const QuicPublicResetPacket & packet)1254 std::unique_ptr<QuicEncryptedPacket> QuicFramer::BuildPublicResetPacket(
1255 const QuicPublicResetPacket& packet) {
1256 CryptoHandshakeMessage reset;
1257 reset.set_tag(kPRST);
1258 reset.SetValue(kRNON, packet.nonce_proof);
1259 if (packet.client_address.host().address_family() !=
1260 IpAddressFamily::IP_UNSPEC) {
1261 // packet.client_address is non-empty.
1262 QuicSocketAddressCoder address_coder(packet.client_address);
1263 std::string serialized_address = address_coder.Encode();
1264 if (serialized_address.empty()) {
1265 return nullptr;
1266 }
1267 reset.SetStringPiece(kCADR, serialized_address);
1268 }
1269 if (!packet.endpoint_id.empty()) {
1270 reset.SetStringPiece(kEPID, packet.endpoint_id);
1271 }
1272 const QuicData& reset_serialized = reset.GetSerialized();
1273
1274 size_t len = kPublicFlagsSize + packet.connection_id.length() +
1275 reset_serialized.length();
1276 std::unique_ptr<char[]> buffer(new char[len]);
1277 QuicDataWriter writer(len, buffer.get());
1278
1279 uint8_t flags = static_cast<uint8_t>(PACKET_PUBLIC_FLAGS_RST |
1280 PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID);
1281 // This hack makes post-v33 public reset packet look like pre-v33 packets.
1282 flags |= static_cast<uint8_t>(PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID_OLD);
1283 if (!writer.WriteUInt8(flags)) {
1284 return nullptr;
1285 }
1286
1287 if (!writer.WriteConnectionId(packet.connection_id)) {
1288 return nullptr;
1289 }
1290
1291 if (!writer.WriteBytes(reset_serialized.data(), reset_serialized.length())) {
1292 return nullptr;
1293 }
1294
1295 return std::make_unique<QuicEncryptedPacket>(buffer.release(), len, true);
1296 }
1297
1298 // static
GetMinStatelessResetPacketLength()1299 size_t QuicFramer::GetMinStatelessResetPacketLength() {
1300 // 5 bytes (40 bits) = 2 Fixed Bits (01) + 38 Unpredictable bits
1301 return 5 + kStatelessResetTokenLength;
1302 }
1303
1304 // static
BuildIetfStatelessResetPacket(QuicConnectionId connection_id,size_t received_packet_length,StatelessResetToken stateless_reset_token)1305 std::unique_ptr<QuicEncryptedPacket> QuicFramer::BuildIetfStatelessResetPacket(
1306 QuicConnectionId connection_id, size_t received_packet_length,
1307 StatelessResetToken stateless_reset_token) {
1308 return BuildIetfStatelessResetPacket(connection_id, received_packet_length,
1309 stateless_reset_token,
1310 QuicRandom::GetInstance());
1311 }
1312
1313 // static
BuildIetfStatelessResetPacket(QuicConnectionId,size_t received_packet_length,StatelessResetToken stateless_reset_token,QuicRandom * random)1314 std::unique_ptr<QuicEncryptedPacket> QuicFramer::BuildIetfStatelessResetPacket(
1315 QuicConnectionId /*connection_id*/, size_t received_packet_length,
1316 StatelessResetToken stateless_reset_token, QuicRandom* random) {
1317 QUIC_DVLOG(1) << "Building IETF stateless reset packet.";
1318 if (received_packet_length <= GetMinStatelessResetPacketLength()) {
1319 QUICHE_DLOG(ERROR)
1320 << "Tried to build stateless reset packet with received packet "
1321 "length "
1322 << received_packet_length;
1323 return nullptr;
1324 }
1325 // To ensure stateless reset is indistinguishable from a valid packet,
1326 // include the max connection ID length.
1327 size_t len = std::min(received_packet_length - 1,
1328 GetMinStatelessResetPacketLength() + 1 +
1329 kQuicMaxConnectionIdWithLengthPrefixLength);
1330 std::unique_ptr<char[]> buffer(new char[len]);
1331 QuicDataWriter writer(len, buffer.get());
1332 // Append random bytes. This randomness only exists to prevent middleboxes
1333 // from comparing the entire packet to a known value. Therefore it has no
1334 // cryptographic use, and does not need a secure cryptographic pseudo-random
1335 // number generator. It's therefore safe to use WriteInsecureRandomBytes.
1336 const size_t random_bytes_size = len - kStatelessResetTokenLength;
1337 if (!writer.WriteInsecureRandomBytes(random, random_bytes_size)) {
1338 QUIC_BUG(362045737_2) << "Failed to append random bytes of length: "
1339 << random_bytes_size;
1340 return nullptr;
1341 }
1342 // Change first 2 fixed bits to 01.
1343 buffer[0] &= ~FLAGS_LONG_HEADER;
1344 buffer[0] |= FLAGS_FIXED_BIT;
1345
1346 // Append stateless reset token.
1347 if (!writer.WriteBytes(&stateless_reset_token,
1348 sizeof(stateless_reset_token))) {
1349 QUIC_BUG(362045737_3) << "Failed to write stateless reset token";
1350 return nullptr;
1351 }
1352 return std::make_unique<QuicEncryptedPacket>(buffer.release(), len,
1353 /*owns_buffer=*/true);
1354 }
1355
1356 // static
BuildVersionNegotiationPacket(QuicConnectionId server_connection_id,QuicConnectionId client_connection_id,bool ietf_quic,bool use_length_prefix,const ParsedQuicVersionVector & versions)1357 std::unique_ptr<QuicEncryptedPacket> QuicFramer::BuildVersionNegotiationPacket(
1358 QuicConnectionId server_connection_id,
1359 QuicConnectionId client_connection_id, bool ietf_quic,
1360 bool use_length_prefix, const ParsedQuicVersionVector& versions) {
1361 QUIC_CODE_COUNT(quic_build_version_negotiation);
1362 if (use_length_prefix) {
1363 QUICHE_DCHECK(ietf_quic);
1364 QUIC_CODE_COUNT(quic_build_version_negotiation_ietf);
1365 } else if (ietf_quic) {
1366 QUIC_CODE_COUNT(quic_build_version_negotiation_old_ietf);
1367 } else {
1368 QUIC_CODE_COUNT(quic_build_version_negotiation_old_gquic);
1369 }
1370 ParsedQuicVersionVector wire_versions = versions;
1371 // Add a version reserved for negotiation as suggested by the
1372 // "Using Reserved Versions" section of draft-ietf-quic-transport.
1373 if (wire_versions.empty()) {
1374 // Ensure that version negotiation packets we send have at least two
1375 // versions. This guarantees that, under all circumstances, all QUIC
1376 // packets we send are at least 14 bytes long.
1377 wire_versions = {QuicVersionReservedForNegotiation(),
1378 QuicVersionReservedForNegotiation()};
1379 } else {
1380 // This is not uniformely distributed but is acceptable since no security
1381 // depends on this randomness.
1382 size_t version_index = 0;
1383 const bool disable_randomness =
1384 GetQuicFlag(quic_disable_version_negotiation_grease_randomness);
1385 if (!disable_randomness) {
1386 version_index =
1387 QuicRandom::GetInstance()->RandUint64() % (wire_versions.size() + 1);
1388 }
1389 wire_versions.insert(wire_versions.begin() + version_index,
1390 QuicVersionReservedForNegotiation());
1391 }
1392 if (ietf_quic) {
1393 return BuildIetfVersionNegotiationPacket(
1394 use_length_prefix, server_connection_id, client_connection_id,
1395 wire_versions);
1396 }
1397
1398 // The GQUIC encoding does not support encoding client connection IDs.
1399 QUICHE_DCHECK(client_connection_id.IsEmpty());
1400 // The GQUIC encoding does not support length-prefixed connection IDs.
1401 QUICHE_DCHECK(!use_length_prefix);
1402
1403 QUICHE_DCHECK(!wire_versions.empty());
1404 size_t len = kPublicFlagsSize + server_connection_id.length() +
1405 wire_versions.size() * kQuicVersionSize;
1406 std::unique_ptr<char[]> buffer(new char[len]);
1407 QuicDataWriter writer(len, buffer.get());
1408
1409 uint8_t flags = static_cast<uint8_t>(
1410 PACKET_PUBLIC_FLAGS_VERSION | PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID |
1411 PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID_OLD);
1412 if (!writer.WriteUInt8(flags)) {
1413 return nullptr;
1414 }
1415
1416 if (!writer.WriteConnectionId(server_connection_id)) {
1417 return nullptr;
1418 }
1419
1420 for (const ParsedQuicVersion& version : wire_versions) {
1421 if (!writer.WriteUInt32(CreateQuicVersionLabel(version))) {
1422 return nullptr;
1423 }
1424 }
1425
1426 return std::make_unique<QuicEncryptedPacket>(buffer.release(), len, true);
1427 }
1428
1429 // static
1430 std::unique_ptr<QuicEncryptedPacket>
BuildIetfVersionNegotiationPacket(bool use_length_prefix,QuicConnectionId server_connection_id,QuicConnectionId client_connection_id,const ParsedQuicVersionVector & versions)1431 QuicFramer::BuildIetfVersionNegotiationPacket(
1432 bool use_length_prefix, QuicConnectionId server_connection_id,
1433 QuicConnectionId client_connection_id,
1434 const ParsedQuicVersionVector& versions) {
1435 QUIC_DVLOG(1) << "Building IETF version negotiation packet with"
1436 << (use_length_prefix ? "" : "out")
1437 << " length prefix, server_connection_id "
1438 << server_connection_id << " client_connection_id "
1439 << client_connection_id << " versions "
1440 << ParsedQuicVersionVectorToString(versions);
1441 QUICHE_DCHECK(!versions.empty());
1442 size_t len = kPacketHeaderTypeSize + kConnectionIdLengthSize +
1443 client_connection_id.length() + server_connection_id.length() +
1444 (versions.size() + 1) * kQuicVersionSize;
1445 if (use_length_prefix) {
1446 // When using length-prefixed connection IDs, packets carry two lengths
1447 // instead of one.
1448 len += kConnectionIdLengthSize;
1449 }
1450 std::unique_ptr<char[]> buffer(new char[len]);
1451 QuicDataWriter writer(len, buffer.get());
1452
1453 // TODO(fayang): Randomly select a value for the type.
1454 uint8_t type = static_cast<uint8_t>(FLAGS_LONG_HEADER | FLAGS_FIXED_BIT);
1455 if (!writer.WriteUInt8(type)) {
1456 return nullptr;
1457 }
1458
1459 if (!writer.WriteUInt32(0)) {
1460 return nullptr;
1461 }
1462
1463 if (!AppendIetfConnectionIds(true, use_length_prefix, client_connection_id,
1464 server_connection_id, &writer)) {
1465 return nullptr;
1466 }
1467
1468 for (const ParsedQuicVersion& version : versions) {
1469 if (!writer.WriteUInt32(CreateQuicVersionLabel(version))) {
1470 return nullptr;
1471 }
1472 }
1473
1474 return std::make_unique<QuicEncryptedPacket>(buffer.release(), len, true);
1475 }
1476
ProcessPacket(const QuicEncryptedPacket & packet)1477 bool QuicFramer::ProcessPacket(const QuicEncryptedPacket& packet) {
1478 QUICHE_DCHECK(!is_processing_packet_) << ENDPOINT << "Nested ProcessPacket";
1479 is_processing_packet_ = true;
1480 bool result = ProcessPacketInternal(packet);
1481 is_processing_packet_ = false;
1482 return result;
1483 }
1484
ProcessPacketInternal(const QuicEncryptedPacket & packet)1485 bool QuicFramer::ProcessPacketInternal(const QuicEncryptedPacket& packet) {
1486 QuicDataReader reader(packet.data(), packet.length());
1487
1488 bool packet_has_ietf_packet_header = false;
1489 if (infer_packet_header_type_from_version_) {
1490 packet_has_ietf_packet_header = version_.HasIetfInvariantHeader();
1491 } else if (!reader.IsDoneReading()) {
1492 uint8_t type = reader.PeekByte();
1493 packet_has_ietf_packet_header = QuicUtils::IsIetfPacketHeader(type);
1494 }
1495 if (packet_has_ietf_packet_header) {
1496 QUIC_DVLOG(1) << ENDPOINT << "Processing IETF QUIC packet.";
1497 }
1498
1499 visitor_->OnPacket();
1500
1501 QuicPacketHeader header;
1502 if (!ProcessPublicHeader(&reader, packet_has_ietf_packet_header, &header)) {
1503 QUICHE_DCHECK_NE("", detailed_error_);
1504 QUIC_DVLOG(1) << ENDPOINT << "Unable to process public header. Error: "
1505 << detailed_error_;
1506 QUICHE_DCHECK_NE("", detailed_error_);
1507 RecordDroppedPacketReason(DroppedPacketReason::INVALID_PUBLIC_HEADER);
1508 return RaiseError(QUIC_INVALID_PACKET_HEADER);
1509 }
1510
1511 if (!visitor_->OnUnauthenticatedPublicHeader(header)) {
1512 // The visitor suppresses further processing of the packet.
1513 return true;
1514 }
1515
1516 if (IsVersionNegotiation(header, packet_has_ietf_packet_header)) {
1517 if (perspective_ == Perspective::IS_CLIENT) {
1518 QUIC_DVLOG(1) << "Client received version negotiation packet";
1519 return ProcessVersionNegotiationPacket(&reader, header);
1520 } else {
1521 QUIC_DLOG(ERROR) << "Server received version negotiation packet";
1522 set_detailed_error("Server received version negotiation packet.");
1523 return RaiseError(QUIC_INVALID_VERSION_NEGOTIATION_PACKET);
1524 }
1525 }
1526
1527 if (header.version_flag && header.version != version_) {
1528 if (perspective_ == Perspective::IS_SERVER) {
1529 if (!visitor_->OnProtocolVersionMismatch(header.version)) {
1530 RecordDroppedPacketReason(DroppedPacketReason::VERSION_MISMATCH);
1531 return true;
1532 }
1533 } else {
1534 // A client received a packet of a different version but that packet is
1535 // not a version negotiation packet. It is therefore invalid and dropped.
1536 QUIC_DLOG(ERROR) << "Client received unexpected version "
1537 << ParsedQuicVersionToString(header.version)
1538 << " instead of " << ParsedQuicVersionToString(version_);
1539 set_detailed_error("Client received unexpected version.");
1540 return RaiseError(QUIC_PACKET_WRONG_VERSION);
1541 }
1542 }
1543
1544 bool rv;
1545 if (header.long_packet_type == RETRY) {
1546 rv = ProcessRetryPacket(&reader, header);
1547 } else if (header.reset_flag) {
1548 rv = ProcessPublicResetPacket(&reader, header);
1549 } else if (packet.length() <= kMaxIncomingPacketSize) {
1550 // The optimized decryption algorithm implementations run faster when
1551 // operating on aligned memory.
1552 ABSL_CACHELINE_ALIGNED char buffer[kMaxIncomingPacketSize];
1553 if (packet_has_ietf_packet_header) {
1554 rv = ProcessIetfDataPacket(&reader, &header, packet, buffer,
1555 ABSL_ARRAYSIZE(buffer));
1556 } else {
1557 rv = ProcessDataPacket(&reader, &header, packet, buffer,
1558 ABSL_ARRAYSIZE(buffer));
1559 }
1560 } else {
1561 std::unique_ptr<char[]> large_buffer(new char[packet.length()]);
1562 if (packet_has_ietf_packet_header) {
1563 rv = ProcessIetfDataPacket(&reader, &header, packet, large_buffer.get(),
1564 packet.length());
1565 } else {
1566 rv = ProcessDataPacket(&reader, &header, packet, large_buffer.get(),
1567 packet.length());
1568 }
1569 QUIC_BUG_IF(quic_bug_10850_53, rv)
1570 << "QUIC should never successfully process packets larger"
1571 << "than kMaxIncomingPacketSize. packet size:" << packet.length();
1572 }
1573 return rv;
1574 }
1575
ProcessVersionNegotiationPacket(QuicDataReader * reader,const QuicPacketHeader & header)1576 bool QuicFramer::ProcessVersionNegotiationPacket(
1577 QuicDataReader* reader, const QuicPacketHeader& header) {
1578 QUICHE_DCHECK_EQ(Perspective::IS_CLIENT, perspective_);
1579
1580 QuicVersionNegotiationPacket packet(
1581 GetServerConnectionIdAsRecipient(header, perspective_));
1582 // Try reading at least once to raise error if the packet is invalid.
1583 do {
1584 QuicVersionLabel version_label;
1585 if (!ProcessVersionLabel(reader, &version_label)) {
1586 set_detailed_error("Unable to read supported version in negotiation.");
1587 RecordDroppedPacketReason(
1588 DroppedPacketReason::INVALID_VERSION_NEGOTIATION_PACKET);
1589 return RaiseError(QUIC_INVALID_VERSION_NEGOTIATION_PACKET);
1590 }
1591 ParsedQuicVersion parsed_version = ParseQuicVersionLabel(version_label);
1592 if (parsed_version != UnsupportedQuicVersion()) {
1593 packet.versions.push_back(parsed_version);
1594 }
1595 } while (!reader->IsDoneReading());
1596
1597 QUIC_DLOG(INFO) << ENDPOINT << "parsed version negotiation: "
1598 << ParsedQuicVersionVectorToString(packet.versions);
1599
1600 visitor_->OnVersionNegotiationPacket(packet);
1601 return true;
1602 }
1603
ProcessRetryPacket(QuicDataReader * reader,const QuicPacketHeader & header)1604 bool QuicFramer::ProcessRetryPacket(QuicDataReader* reader,
1605 const QuicPacketHeader& header) {
1606 QUICHE_DCHECK_EQ(Perspective::IS_CLIENT, perspective_);
1607 if (drop_incoming_retry_packets_) {
1608 QUIC_DLOG(INFO) << "Ignoring received RETRY packet";
1609 return true;
1610 }
1611
1612 if (version_.UsesTls()) {
1613 QUICHE_DCHECK(version_.HasLengthPrefixedConnectionIds()) << version_;
1614 const size_t bytes_remaining = reader->BytesRemaining();
1615 if (bytes_remaining <= kRetryIntegrityTagLength) {
1616 set_detailed_error("Retry packet too short to parse integrity tag.");
1617 return false;
1618 }
1619 const size_t retry_token_length =
1620 bytes_remaining - kRetryIntegrityTagLength;
1621 QUICHE_DCHECK_GT(retry_token_length, 0u);
1622 absl::string_view retry_token;
1623 if (!reader->ReadStringPiece(&retry_token, retry_token_length)) {
1624 set_detailed_error("Failed to read retry token.");
1625 return false;
1626 }
1627 absl::string_view retry_without_tag = reader->PreviouslyReadPayload();
1628 absl::string_view integrity_tag = reader->ReadRemainingPayload();
1629 QUICHE_DCHECK_EQ(integrity_tag.length(), kRetryIntegrityTagLength);
1630 visitor_->OnRetryPacket(EmptyQuicConnectionId(),
1631 header.source_connection_id, retry_token,
1632 integrity_tag, retry_without_tag);
1633 return true;
1634 }
1635
1636 QuicConnectionId original_destination_connection_id;
1637 if (version_.HasLengthPrefixedConnectionIds()) {
1638 // Parse Original Destination Connection ID.
1639 if (!reader->ReadLengthPrefixedConnectionId(
1640 &original_destination_connection_id)) {
1641 set_detailed_error("Unable to read Original Destination ConnectionId.");
1642 return false;
1643 }
1644 } else {
1645 // Parse Original Destination Connection ID Length.
1646 uint8_t odcil = header.type_byte & 0xf;
1647 if (odcil != 0) {
1648 odcil += kConnectionIdLengthAdjustment;
1649 }
1650
1651 // Parse Original Destination Connection ID.
1652 if (!reader->ReadConnectionId(&original_destination_connection_id, odcil)) {
1653 set_detailed_error("Unable to read Original Destination ConnectionId.");
1654 return false;
1655 }
1656 }
1657
1658 if (!QuicUtils::IsConnectionIdValidForVersion(
1659 original_destination_connection_id, transport_version())) {
1660 set_detailed_error(
1661 "Received Original Destination ConnectionId with invalid length.");
1662 return false;
1663 }
1664
1665 absl::string_view retry_token = reader->ReadRemainingPayload();
1666 visitor_->OnRetryPacket(original_destination_connection_id,
1667 header.source_connection_id, retry_token,
1668 /*retry_integrity_tag=*/absl::string_view(),
1669 /*retry_without_tag=*/absl::string_view());
1670 return true;
1671 }
1672
1673 // Seeks the current packet to check for a coalesced packet at the end.
1674 // If the IETF length field only spans part of the outer packet,
1675 // then there is a coalesced packet after this one.
MaybeProcessCoalescedPacket(const QuicDataReader & encrypted_reader,uint64_t remaining_bytes_length,const QuicPacketHeader & header)1676 void QuicFramer::MaybeProcessCoalescedPacket(
1677 const QuicDataReader& encrypted_reader, uint64_t remaining_bytes_length,
1678 const QuicPacketHeader& header) {
1679 if (header.remaining_packet_length >= remaining_bytes_length) {
1680 // There is no coalesced packet.
1681 return;
1682 }
1683
1684 absl::string_view remaining_data = encrypted_reader.PeekRemainingPayload();
1685 QUICHE_DCHECK_EQ(remaining_data.length(), remaining_bytes_length);
1686
1687 const char* coalesced_data =
1688 remaining_data.data() + header.remaining_packet_length;
1689 uint64_t coalesced_data_length =
1690 remaining_bytes_length - header.remaining_packet_length;
1691 QuicDataReader coalesced_reader(coalesced_data, coalesced_data_length);
1692
1693 QuicPacketHeader coalesced_header;
1694 if (!ProcessIetfPacketHeader(&coalesced_reader, &coalesced_header)) {
1695 // Some implementations pad their INITIAL packets by sending random invalid
1696 // data after the INITIAL, and that is allowed by the specification. If we
1697 // fail to parse a subsequent coalesced packet, simply ignore it.
1698 QUIC_DLOG(INFO) << ENDPOINT
1699 << "Failed to parse received coalesced header of length "
1700 << coalesced_data_length
1701 << " with error: " << detailed_error_ << ": "
1702 << absl::BytesToHexString(absl::string_view(
1703 coalesced_data, coalesced_data_length))
1704 << " previous header was " << header;
1705 return;
1706 }
1707
1708 if (coalesced_header.destination_connection_id !=
1709 header.destination_connection_id) {
1710 // Drop coalesced packets with mismatched connection IDs.
1711 QUIC_DLOG(INFO) << ENDPOINT << "Received mismatched coalesced header "
1712 << coalesced_header << " previous header was " << header;
1713 QUIC_CODE_COUNT(
1714 quic_received_coalesced_packets_with_mismatched_connection_id);
1715 return;
1716 }
1717
1718 QuicEncryptedPacket coalesced_packet(coalesced_data, coalesced_data_length,
1719 /*owns_buffer=*/false);
1720 visitor_->OnCoalescedPacket(coalesced_packet);
1721 }
1722
MaybeProcessIetfLength(QuicDataReader * encrypted_reader,QuicPacketHeader * header)1723 bool QuicFramer::MaybeProcessIetfLength(QuicDataReader* encrypted_reader,
1724 QuicPacketHeader* header) {
1725 if (!QuicVersionHasLongHeaderLengths(header->version.transport_version) ||
1726 header->form != IETF_QUIC_LONG_HEADER_PACKET ||
1727 (header->long_packet_type != INITIAL &&
1728 header->long_packet_type != HANDSHAKE &&
1729 header->long_packet_type != ZERO_RTT_PROTECTED)) {
1730 return true;
1731 }
1732 header->length_length = encrypted_reader->PeekVarInt62Length();
1733 if (!encrypted_reader->ReadVarInt62(&header->remaining_packet_length)) {
1734 set_detailed_error("Unable to read long header payload length.");
1735 return RaiseError(QUIC_INVALID_PACKET_HEADER);
1736 }
1737 uint64_t remaining_bytes_length = encrypted_reader->BytesRemaining();
1738 if (header->remaining_packet_length > remaining_bytes_length) {
1739 set_detailed_error("Long header payload length longer than packet.");
1740 return RaiseError(QUIC_INVALID_PACKET_HEADER);
1741 }
1742
1743 MaybeProcessCoalescedPacket(*encrypted_reader, remaining_bytes_length,
1744 *header);
1745
1746 if (!encrypted_reader->TruncateRemaining(header->remaining_packet_length)) {
1747 set_detailed_error("Length TruncateRemaining failed.");
1748 QUIC_BUG(quic_bug_10850_54) << "Length TruncateRemaining failed.";
1749 return RaiseError(QUIC_INVALID_PACKET_HEADER);
1750 }
1751 return true;
1752 }
1753
ProcessIetfDataPacket(QuicDataReader * encrypted_reader,QuicPacketHeader * header,const QuicEncryptedPacket & packet,char * decrypted_buffer,size_t buffer_length)1754 bool QuicFramer::ProcessIetfDataPacket(QuicDataReader* encrypted_reader,
1755 QuicPacketHeader* header,
1756 const QuicEncryptedPacket& packet,
1757 char* decrypted_buffer,
1758 size_t buffer_length) {
1759 QUICHE_DCHECK_NE(GOOGLE_QUIC_PACKET, header->form);
1760 QUICHE_DCHECK(!header->has_possible_stateless_reset_token);
1761 header->length_length = quiche::VARIABLE_LENGTH_INTEGER_LENGTH_0;
1762 header->remaining_packet_length = 0;
1763 if (header->form == IETF_QUIC_SHORT_HEADER_PACKET &&
1764 perspective_ == Perspective::IS_CLIENT) {
1765 // Peek possible stateless reset token. Will only be used on decryption
1766 // failure.
1767 absl::string_view remaining = encrypted_reader->PeekRemainingPayload();
1768 if (remaining.length() >= sizeof(header->possible_stateless_reset_token)) {
1769 header->has_possible_stateless_reset_token = true;
1770 memcpy(&header->possible_stateless_reset_token,
1771 &remaining.data()[remaining.length() -
1772 sizeof(header->possible_stateless_reset_token)],
1773 sizeof(header->possible_stateless_reset_token));
1774 }
1775 }
1776
1777 if (!MaybeProcessIetfLength(encrypted_reader, header)) {
1778 return false;
1779 }
1780
1781 absl::string_view associated_data;
1782 std::vector<char> ad_storage;
1783 QuicPacketNumber base_packet_number;
1784 if (header->form == IETF_QUIC_SHORT_HEADER_PACKET ||
1785 header->long_packet_type != VERSION_NEGOTIATION) {
1786 QUICHE_DCHECK(header->form == IETF_QUIC_SHORT_HEADER_PACKET ||
1787 header->long_packet_type == INITIAL ||
1788 header->long_packet_type == HANDSHAKE ||
1789 header->long_packet_type == ZERO_RTT_PROTECTED);
1790 // Process packet number.
1791 if (supports_multiple_packet_number_spaces_) {
1792 PacketNumberSpace pn_space = GetPacketNumberSpace(*header);
1793 if (pn_space == NUM_PACKET_NUMBER_SPACES) {
1794 return RaiseError(QUIC_INVALID_PACKET_HEADER);
1795 }
1796 base_packet_number = largest_decrypted_packet_numbers_[pn_space];
1797 } else {
1798 base_packet_number = largest_packet_number_;
1799 }
1800 uint64_t full_packet_number;
1801 bool hp_removal_failed = false;
1802 if (version_.HasHeaderProtection()) {
1803 if (!RemoveHeaderProtection(encrypted_reader, packet, header,
1804 &full_packet_number, &ad_storage)) {
1805 hp_removal_failed = true;
1806 }
1807 associated_data = absl::string_view(ad_storage.data(), ad_storage.size());
1808 } else if (!ProcessAndCalculatePacketNumber(
1809 encrypted_reader, header->packet_number_length,
1810 base_packet_number, &full_packet_number)) {
1811 set_detailed_error("Unable to read packet number.");
1812 RecordDroppedPacketReason(DroppedPacketReason::INVALID_PACKET_NUMBER);
1813 return RaiseError(QUIC_INVALID_PACKET_HEADER);
1814 }
1815
1816 if (hp_removal_failed ||
1817 !IsValidFullPacketNumber(full_packet_number, version())) {
1818 if (IsIetfStatelessResetPacket(*header)) {
1819 // This is a stateless reset packet.
1820 QuicIetfStatelessResetPacket reset_packet(
1821 *header, header->possible_stateless_reset_token);
1822 visitor_->OnAuthenticatedIetfStatelessResetPacket(reset_packet);
1823 return true;
1824 }
1825 if (hp_removal_failed) {
1826 const EncryptionLevel decryption_level = GetEncryptionLevel(*header);
1827 const bool has_decryption_key = decrypter_[decryption_level] != nullptr;
1828 visitor_->OnUndecryptablePacket(
1829 QuicEncryptedPacket(encrypted_reader->FullPayload()),
1830 decryption_level, has_decryption_key);
1831 RecordDroppedPacketReason(DroppedPacketReason::DECRYPTION_FAILURE);
1832 set_detailed_error(absl::StrCat(
1833 "Unable to decrypt ", EncryptionLevelToString(decryption_level),
1834 " header protection", has_decryption_key ? "" : " (missing key)",
1835 "."));
1836 return RaiseError(QUIC_DECRYPTION_FAILURE);
1837 }
1838 RecordDroppedPacketReason(DroppedPacketReason::INVALID_PACKET_NUMBER);
1839 set_detailed_error("packet numbers cannot be 0.");
1840 return RaiseError(QUIC_INVALID_PACKET_HEADER);
1841 }
1842 header->packet_number = QuicPacketNumber(full_packet_number);
1843 }
1844
1845 // A nonce should only present in SHLO from the server to the client when
1846 // using QUIC crypto.
1847 if (header->form == IETF_QUIC_LONG_HEADER_PACKET &&
1848 header->long_packet_type == ZERO_RTT_PROTECTED &&
1849 perspective_ == Perspective::IS_CLIENT &&
1850 version_.handshake_protocol == PROTOCOL_QUIC_CRYPTO) {
1851 if (!encrypted_reader->ReadBytes(
1852 reinterpret_cast<uint8_t*>(last_nonce_.data()),
1853 last_nonce_.size())) {
1854 set_detailed_error("Unable to read nonce.");
1855 RecordDroppedPacketReason(
1856 DroppedPacketReason::INVALID_DIVERSIFICATION_NONCE);
1857 return RaiseError(QUIC_INVALID_PACKET_HEADER);
1858 }
1859
1860 header->nonce = &last_nonce_;
1861 } else {
1862 header->nonce = nullptr;
1863 }
1864
1865 if (!visitor_->OnUnauthenticatedHeader(*header)) {
1866 set_detailed_error(
1867 "Visitor asked to stop processing of unauthenticated header.");
1868 return false;
1869 }
1870
1871 absl::string_view encrypted = encrypted_reader->ReadRemainingPayload();
1872 if (!version_.HasHeaderProtection()) {
1873 associated_data = GetAssociatedDataFromEncryptedPacket(
1874 version_.transport_version, packet,
1875 GetIncludedDestinationConnectionIdLength(*header),
1876 GetIncludedSourceConnectionIdLength(*header), header->version_flag,
1877 header->nonce != nullptr, header->packet_number_length,
1878 header->retry_token_length_length, header->retry_token.length(),
1879 header->length_length);
1880 }
1881
1882 size_t decrypted_length = 0;
1883 EncryptionLevel decrypted_level;
1884 if (!DecryptPayload(packet.length(), encrypted, associated_data, *header,
1885 decrypted_buffer, buffer_length, &decrypted_length,
1886 &decrypted_level)) {
1887 if (IsIetfStatelessResetPacket(*header)) {
1888 // This is a stateless reset packet.
1889 QuicIetfStatelessResetPacket reset_packet(
1890 *header, header->possible_stateless_reset_token);
1891 visitor_->OnAuthenticatedIetfStatelessResetPacket(reset_packet);
1892 return true;
1893 }
1894 const EncryptionLevel decryption_level = GetEncryptionLevel(*header);
1895 const bool has_decryption_key = version_.KnowsWhichDecrypterToUse() &&
1896 decrypter_[decryption_level] != nullptr;
1897 visitor_->OnUndecryptablePacket(
1898 QuicEncryptedPacket(encrypted_reader->FullPayload()), decryption_level,
1899 has_decryption_key);
1900 set_detailed_error(absl::StrCat(
1901 "Unable to decrypt ", EncryptionLevelToString(decryption_level),
1902 " payload with reconstructed packet number ",
1903 header->packet_number.ToString(), " (largest decrypted was ",
1904 base_packet_number.ToString(), ")",
1905 has_decryption_key || !version_.KnowsWhichDecrypterToUse()
1906 ? ""
1907 : " (missing key)",
1908 "."));
1909 RecordDroppedPacketReason(DroppedPacketReason::DECRYPTION_FAILURE);
1910 return RaiseError(QUIC_DECRYPTION_FAILURE);
1911 }
1912 QuicDataReader reader(decrypted_buffer, decrypted_length);
1913
1914 // Remember decrypted_payload in the current connection context until the end
1915 // of this function.
1916 auto* connection_context = QuicConnectionContext::Current();
1917 if (connection_context != nullptr) {
1918 connection_context->process_packet_context.decrypted_payload =
1919 reader.FullPayload();
1920 connection_context->process_packet_context.current_frame_offset = 0;
1921 }
1922 auto clear_decrypted_payload = absl::MakeCleanup([&]() {
1923 if (connection_context != nullptr) {
1924 connection_context->process_packet_context.decrypted_payload =
1925 absl::string_view();
1926 }
1927 });
1928
1929 // Update the largest packet number after we have decrypted the packet
1930 // so we are confident is not attacker controlled.
1931 if (supports_multiple_packet_number_spaces_) {
1932 largest_decrypted_packet_numbers_[QuicUtils::GetPacketNumberSpace(
1933 decrypted_level)]
1934 .UpdateMax(header->packet_number);
1935 } else {
1936 largest_packet_number_.UpdateMax(header->packet_number);
1937 }
1938
1939 if (!visitor_->OnPacketHeader(*header)) {
1940 RecordDroppedPacketReason(DroppedPacketReason::INVALID_PACKET_NUMBER);
1941 // The visitor suppresses further processing of the packet.
1942 return true;
1943 }
1944
1945 if (packet.length() > kMaxIncomingPacketSize) {
1946 set_detailed_error("Packet too large.");
1947 return RaiseError(QUIC_PACKET_TOO_LARGE);
1948 }
1949
1950 // Handle the payload.
1951 if (VersionHasIetfQuicFrames(version_.transport_version)) {
1952 current_received_frame_type_ = 0;
1953 previously_received_frame_type_ = 0;
1954 if (!ProcessIetfFrameData(&reader, *header, decrypted_level)) {
1955 current_received_frame_type_ = 0;
1956 previously_received_frame_type_ = 0;
1957 QUICHE_DCHECK_NE(QUIC_NO_ERROR,
1958 error_); // ProcessIetfFrameData sets the error.
1959 QUICHE_DCHECK_NE("", detailed_error_);
1960 QUIC_DLOG(WARNING) << ENDPOINT << "Unable to process frame data. Error: "
1961 << detailed_error_;
1962 return false;
1963 }
1964 current_received_frame_type_ = 0;
1965 previously_received_frame_type_ = 0;
1966 } else {
1967 if (!ProcessFrameData(&reader, *header)) {
1968 QUICHE_DCHECK_NE(QUIC_NO_ERROR,
1969 error_); // ProcessFrameData sets the error.
1970 QUICHE_DCHECK_NE("", detailed_error_);
1971 QUIC_DLOG(WARNING) << ENDPOINT << "Unable to process frame data. Error: "
1972 << detailed_error_;
1973 return false;
1974 }
1975 }
1976
1977 visitor_->OnPacketComplete();
1978 return true;
1979 }
1980
ProcessDataPacket(QuicDataReader * encrypted_reader,QuicPacketHeader * header,const QuicEncryptedPacket & packet,char * decrypted_buffer,size_t buffer_length)1981 bool QuicFramer::ProcessDataPacket(QuicDataReader* encrypted_reader,
1982 QuicPacketHeader* header,
1983 const QuicEncryptedPacket& packet,
1984 char* decrypted_buffer,
1985 size_t buffer_length) {
1986 if (!ProcessUnauthenticatedHeader(encrypted_reader, header)) {
1987 QUICHE_DCHECK_NE("", detailed_error_);
1988 QUIC_DVLOG(1)
1989 << ENDPOINT
1990 << "Unable to process packet header. Stopping parsing. Error: "
1991 << detailed_error_;
1992 RecordDroppedPacketReason(DroppedPacketReason::INVALID_PACKET_NUMBER);
1993 return false;
1994 }
1995
1996 absl::string_view encrypted = encrypted_reader->ReadRemainingPayload();
1997 absl::string_view associated_data = GetAssociatedDataFromEncryptedPacket(
1998 version_.transport_version, packet,
1999 GetIncludedDestinationConnectionIdLength(*header),
2000 GetIncludedSourceConnectionIdLength(*header), header->version_flag,
2001 header->nonce != nullptr, header->packet_number_length,
2002 header->retry_token_length_length, header->retry_token.length(),
2003 header->length_length);
2004
2005 size_t decrypted_length = 0;
2006 EncryptionLevel decrypted_level;
2007 if (!DecryptPayload(packet.length(), encrypted, associated_data, *header,
2008 decrypted_buffer, buffer_length, &decrypted_length,
2009 &decrypted_level)) {
2010 const EncryptionLevel decryption_level = decrypter_level_;
2011 // This version uses trial decryption so we always report to our visitor
2012 // that we are not certain we have the correct decryption key.
2013 const bool has_decryption_key = false;
2014 visitor_->OnUndecryptablePacket(
2015 QuicEncryptedPacket(encrypted_reader->FullPayload()), decryption_level,
2016 has_decryption_key);
2017 RecordDroppedPacketReason(DroppedPacketReason::DECRYPTION_FAILURE);
2018 set_detailed_error(absl::StrCat("Unable to decrypt ",
2019 EncryptionLevelToString(decryption_level),
2020 " payload."));
2021 return RaiseError(QUIC_DECRYPTION_FAILURE);
2022 }
2023
2024 QuicDataReader reader(decrypted_buffer, decrypted_length);
2025
2026 // Update the largest packet number after we have decrypted the packet
2027 // so we are confident is not attacker controlled.
2028 if (supports_multiple_packet_number_spaces_) {
2029 largest_decrypted_packet_numbers_[QuicUtils::GetPacketNumberSpace(
2030 decrypted_level)]
2031 .UpdateMax(header->packet_number);
2032 } else {
2033 largest_packet_number_.UpdateMax(header->packet_number);
2034 }
2035
2036 if (!visitor_->OnPacketHeader(*header)) {
2037 // The visitor suppresses further processing of the packet.
2038 return true;
2039 }
2040
2041 if (packet.length() > kMaxIncomingPacketSize) {
2042 set_detailed_error("Packet too large.");
2043 return RaiseError(QUIC_PACKET_TOO_LARGE);
2044 }
2045
2046 // Handle the payload.
2047 if (!ProcessFrameData(&reader, *header)) {
2048 QUICHE_DCHECK_NE(QUIC_NO_ERROR,
2049 error_); // ProcessFrameData sets the error.
2050 QUICHE_DCHECK_NE("", detailed_error_);
2051 QUIC_DLOG(WARNING) << ENDPOINT << "Unable to process frame data. Error: "
2052 << detailed_error_;
2053 return false;
2054 }
2055
2056 visitor_->OnPacketComplete();
2057 return true;
2058 }
2059
ProcessPublicResetPacket(QuicDataReader * reader,const QuicPacketHeader & header)2060 bool QuicFramer::ProcessPublicResetPacket(QuicDataReader* reader,
2061 const QuicPacketHeader& header) {
2062 QuicPublicResetPacket packet(
2063 GetServerConnectionIdAsRecipient(header, perspective_));
2064
2065 std::unique_ptr<CryptoHandshakeMessage> reset(
2066 CryptoFramer::ParseMessage(reader->ReadRemainingPayload()));
2067 if (!reset) {
2068 set_detailed_error("Unable to read reset message.");
2069 RecordDroppedPacketReason(DroppedPacketReason::INVALID_PUBLIC_RESET_PACKET);
2070 return RaiseError(QUIC_INVALID_PUBLIC_RST_PACKET);
2071 }
2072 if (reset->tag() != kPRST) {
2073 set_detailed_error("Incorrect message tag.");
2074 RecordDroppedPacketReason(DroppedPacketReason::INVALID_PUBLIC_RESET_PACKET);
2075 return RaiseError(QUIC_INVALID_PUBLIC_RST_PACKET);
2076 }
2077
2078 if (reset->GetUint64(kRNON, &packet.nonce_proof) != QUIC_NO_ERROR) {
2079 set_detailed_error("Unable to read nonce proof.");
2080 RecordDroppedPacketReason(DroppedPacketReason::INVALID_PUBLIC_RESET_PACKET);
2081 return RaiseError(QUIC_INVALID_PUBLIC_RST_PACKET);
2082 }
2083 // TODO(satyamshekhar): validate nonce to protect against DoS.
2084
2085 absl::string_view address;
2086 if (reset->GetStringPiece(kCADR, &address)) {
2087 QuicSocketAddressCoder address_coder;
2088 if (address_coder.Decode(address.data(), address.length())) {
2089 packet.client_address =
2090 QuicSocketAddress(address_coder.ip(), address_coder.port());
2091 }
2092 }
2093
2094 absl::string_view endpoint_id;
2095 if (perspective_ == Perspective::IS_CLIENT &&
2096 reset->GetStringPiece(kEPID, &endpoint_id)) {
2097 packet.endpoint_id = std::string(endpoint_id);
2098 packet.endpoint_id += '\0';
2099 }
2100
2101 visitor_->OnPublicResetPacket(packet);
2102 return true;
2103 }
2104
IsIetfStatelessResetPacket(const QuicPacketHeader & header) const2105 bool QuicFramer::IsIetfStatelessResetPacket(
2106 const QuicPacketHeader& header) const {
2107 QUIC_BUG_IF(quic_bug_12975_3, header.has_possible_stateless_reset_token &&
2108 perspective_ != Perspective::IS_CLIENT)
2109 << "has_possible_stateless_reset_token can only be true at client side.";
2110 return header.form == IETF_QUIC_SHORT_HEADER_PACKET &&
2111 header.has_possible_stateless_reset_token &&
2112 visitor_->IsValidStatelessResetToken(
2113 header.possible_stateless_reset_token);
2114 }
2115
HasEncrypterOfEncryptionLevel(EncryptionLevel level) const2116 bool QuicFramer::HasEncrypterOfEncryptionLevel(EncryptionLevel level) const {
2117 return encrypter_[level] != nullptr;
2118 }
2119
HasDecrypterOfEncryptionLevel(EncryptionLevel level) const2120 bool QuicFramer::HasDecrypterOfEncryptionLevel(EncryptionLevel level) const {
2121 return decrypter_[level] != nullptr;
2122 }
2123
HasAnEncrypterForSpace(PacketNumberSpace space) const2124 bool QuicFramer::HasAnEncrypterForSpace(PacketNumberSpace space) const {
2125 switch (space) {
2126 case INITIAL_DATA:
2127 return HasEncrypterOfEncryptionLevel(ENCRYPTION_INITIAL);
2128 case HANDSHAKE_DATA:
2129 return HasEncrypterOfEncryptionLevel(ENCRYPTION_HANDSHAKE);
2130 case APPLICATION_DATA:
2131 return HasEncrypterOfEncryptionLevel(ENCRYPTION_ZERO_RTT) ||
2132 HasEncrypterOfEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
2133 case NUM_PACKET_NUMBER_SPACES:
2134 break;
2135 }
2136 QUIC_BUG(quic_bug_10850_55)
2137 << ENDPOINT
2138 << "Try to send data of space: " << PacketNumberSpaceToString(space);
2139 return false;
2140 }
2141
GetEncryptionLevelToSendApplicationData() const2142 EncryptionLevel QuicFramer::GetEncryptionLevelToSendApplicationData() const {
2143 if (!HasAnEncrypterForSpace(APPLICATION_DATA)) {
2144 QUIC_BUG(quic_bug_12975_4)
2145 << "Tried to get encryption level to send application data with no "
2146 "encrypter available.";
2147 return NUM_ENCRYPTION_LEVELS;
2148 }
2149 if (HasEncrypterOfEncryptionLevel(ENCRYPTION_FORWARD_SECURE)) {
2150 return ENCRYPTION_FORWARD_SECURE;
2151 }
2152 QUICHE_DCHECK(HasEncrypterOfEncryptionLevel(ENCRYPTION_ZERO_RTT));
2153 return ENCRYPTION_ZERO_RTT;
2154 }
2155
AppendPacketHeader(const QuicPacketHeader & header,QuicDataWriter * writer,size_t * length_field_offset)2156 bool QuicFramer::AppendPacketHeader(const QuicPacketHeader& header,
2157 QuicDataWriter* writer,
2158 size_t* length_field_offset) {
2159 if (version().HasIetfInvariantHeader()) {
2160 return AppendIetfPacketHeader(header, writer, length_field_offset);
2161 }
2162 QUIC_DVLOG(1) << ENDPOINT << "Appending header: " << header;
2163 uint8_t public_flags = 0;
2164 if (header.reset_flag) {
2165 public_flags |= PACKET_PUBLIC_FLAGS_RST;
2166 }
2167 if (header.version_flag) {
2168 public_flags |= PACKET_PUBLIC_FLAGS_VERSION;
2169 }
2170
2171 public_flags |= GetPacketNumberFlags(header.packet_number_length)
2172 << kPublicHeaderSequenceNumberShift;
2173
2174 if (header.nonce != nullptr) {
2175 QUICHE_DCHECK_EQ(Perspective::IS_SERVER, perspective_);
2176 public_flags |= PACKET_PUBLIC_FLAGS_NONCE;
2177 }
2178
2179 QuicConnectionId server_connection_id =
2180 GetServerConnectionIdAsSender(header, perspective_);
2181 QuicConnectionIdIncluded server_connection_id_included =
2182 GetServerConnectionIdIncludedAsSender(header, perspective_);
2183 QUICHE_DCHECK_EQ(CONNECTION_ID_ABSENT,
2184 GetClientConnectionIdIncludedAsSender(header, perspective_))
2185 << ENDPOINT << ParsedQuicVersionToString(version_)
2186 << " invalid header: " << header;
2187
2188 switch (server_connection_id_included) {
2189 case CONNECTION_ID_ABSENT:
2190 if (!writer->WriteUInt8(public_flags |
2191 PACKET_PUBLIC_FLAGS_0BYTE_CONNECTION_ID)) {
2192 return false;
2193 }
2194 break;
2195 case CONNECTION_ID_PRESENT:
2196 QUIC_BUG_IF(quic_bug_12975_5,
2197 !QuicUtils::IsConnectionIdValidForVersion(
2198 server_connection_id, transport_version()))
2199 << "AppendPacketHeader: attempted to use connection ID "
2200 << server_connection_id << " which is invalid with version "
2201 << version();
2202
2203 public_flags |= PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID;
2204 if (perspective_ == Perspective::IS_CLIENT) {
2205 public_flags |= PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID_OLD;
2206 }
2207 if (!writer->WriteUInt8(public_flags) ||
2208 !writer->WriteConnectionId(server_connection_id)) {
2209 return false;
2210 }
2211 break;
2212 }
2213 last_serialized_server_connection_id_ = server_connection_id;
2214
2215 if (header.version_flag) {
2216 QUICHE_DCHECK_EQ(Perspective::IS_CLIENT, perspective_);
2217 QuicVersionLabel version_label = CreateQuicVersionLabel(version_);
2218 if (!writer->WriteUInt32(version_label)) {
2219 return false;
2220 }
2221
2222 QUIC_DVLOG(1) << ENDPOINT << "label = '"
2223 << QuicVersionLabelToString(version_label) << "'";
2224 }
2225
2226 if (header.nonce != nullptr &&
2227 !writer->WriteBytes(header.nonce, kDiversificationNonceSize)) {
2228 return false;
2229 }
2230
2231 if (!AppendPacketNumber(header.packet_number_length, header.packet_number,
2232 writer)) {
2233 return false;
2234 }
2235
2236 return true;
2237 }
2238
AppendIetfHeaderTypeByte(const QuicPacketHeader & header,QuicDataWriter * writer)2239 bool QuicFramer::AppendIetfHeaderTypeByte(const QuicPacketHeader& header,
2240 QuicDataWriter* writer) {
2241 uint8_t type = 0;
2242 if (header.version_flag) {
2243 type = static_cast<uint8_t>(
2244 FLAGS_LONG_HEADER | FLAGS_FIXED_BIT |
2245 LongHeaderTypeToOnWireValue(header.long_packet_type, version_) |
2246 PacketNumberLengthToOnWireValue(header.packet_number_length));
2247 } else {
2248 type = static_cast<uint8_t>(
2249 FLAGS_FIXED_BIT | (current_key_phase_bit_ ? FLAGS_KEY_PHASE_BIT : 0) |
2250 PacketNumberLengthToOnWireValue(header.packet_number_length));
2251 }
2252 return writer->WriteUInt8(type);
2253 }
2254
AppendIetfPacketHeader(const QuicPacketHeader & header,QuicDataWriter * writer,size_t * length_field_offset)2255 bool QuicFramer::AppendIetfPacketHeader(const QuicPacketHeader& header,
2256 QuicDataWriter* writer,
2257 size_t* length_field_offset) {
2258 QUIC_DVLOG(1) << ENDPOINT << "Appending IETF header: " << header;
2259 QuicConnectionId server_connection_id =
2260 GetServerConnectionIdAsSender(header, perspective_);
2261 QUIC_BUG_IF(quic_bug_12975_6, !QuicUtils::IsConnectionIdValidForVersion(
2262 server_connection_id, transport_version()))
2263 << "AppendIetfPacketHeader: attempted to use connection ID "
2264 << server_connection_id << " which is invalid with version " << version();
2265 if (!AppendIetfHeaderTypeByte(header, writer)) {
2266 return false;
2267 }
2268
2269 if (header.version_flag) {
2270 QUICHE_DCHECK_NE(VERSION_NEGOTIATION, header.long_packet_type)
2271 << "QuicFramer::AppendIetfPacketHeader does not support sending "
2272 "version negotiation packets, use "
2273 "QuicFramer::BuildVersionNegotiationPacket instead "
2274 << header;
2275 // Append version for long header.
2276 QuicVersionLabel version_label = CreateQuicVersionLabel(version_);
2277 if (!writer->WriteUInt32(version_label)) {
2278 return false;
2279 }
2280 }
2281
2282 // Append connection ID.
2283 if (!AppendIetfConnectionIds(
2284 header.version_flag, version_.HasLengthPrefixedConnectionIds(),
2285 header.destination_connection_id_included != CONNECTION_ID_ABSENT
2286 ? header.destination_connection_id
2287 : EmptyQuicConnectionId(),
2288 header.source_connection_id_included != CONNECTION_ID_ABSENT
2289 ? header.source_connection_id
2290 : EmptyQuicConnectionId(),
2291 writer)) {
2292 return false;
2293 }
2294
2295 last_serialized_server_connection_id_ = server_connection_id;
2296 if (version_.SupportsClientConnectionIds()) {
2297 last_serialized_client_connection_id_ =
2298 GetClientConnectionIdAsSender(header, perspective_);
2299 }
2300
2301 // TODO(b/141924462) Remove this QUIC_BUG once we do support sending RETRY.
2302 QUIC_BUG_IF(quic_bug_12975_7,
2303 header.version_flag && header.long_packet_type == RETRY)
2304 << "Sending IETF RETRY packets is not currently supported " << header;
2305
2306 if (QuicVersionHasLongHeaderLengths(transport_version()) &&
2307 header.version_flag) {
2308 if (header.long_packet_type == INITIAL) {
2309 QUICHE_DCHECK_NE(quiche::VARIABLE_LENGTH_INTEGER_LENGTH_0,
2310 header.retry_token_length_length)
2311 << ENDPOINT << ParsedQuicVersionToString(version_)
2312 << " bad retry token length length in header: " << header;
2313 // Write retry token length.
2314 if (!writer->WriteVarInt62WithForcedLength(
2315 header.retry_token.length(), header.retry_token_length_length)) {
2316 return false;
2317 }
2318 // Write retry token.
2319 if (!header.retry_token.empty() &&
2320 !writer->WriteStringPiece(header.retry_token)) {
2321 return false;
2322 }
2323 }
2324 if (length_field_offset != nullptr) {
2325 *length_field_offset = writer->length();
2326 }
2327 // Add fake length to reserve two bytes to add length in later.
2328 writer->WriteVarInt62(256);
2329 } else if (length_field_offset != nullptr) {
2330 *length_field_offset = 0;
2331 }
2332
2333 // Append packet number.
2334 if (!AppendPacketNumber(header.packet_number_length, header.packet_number,
2335 writer)) {
2336 return false;
2337 }
2338 last_written_packet_number_length_ = header.packet_number_length;
2339
2340 if (!header.version_flag) {
2341 return true;
2342 }
2343
2344 if (header.nonce != nullptr) {
2345 QUICHE_DCHECK(header.version_flag);
2346 QUICHE_DCHECK_EQ(ZERO_RTT_PROTECTED, header.long_packet_type);
2347 QUICHE_DCHECK_EQ(Perspective::IS_SERVER, perspective_);
2348 if (!writer->WriteBytes(header.nonce, kDiversificationNonceSize)) {
2349 return false;
2350 }
2351 }
2352
2353 return true;
2354 }
2355
CalculateTimestampFromWire(uint32_t time_delta_us)2356 const QuicTime::Delta QuicFramer::CalculateTimestampFromWire(
2357 uint32_t time_delta_us) {
2358 // The new time_delta might have wrapped to the next epoch, or it
2359 // might have reverse wrapped to the previous epoch, or it might
2360 // remain in the same epoch. Select the time closest to the previous
2361 // time.
2362 //
2363 // epoch_delta is the delta between epochs. A delta is 4 bytes of
2364 // microseconds.
2365 const uint64_t epoch_delta = UINT64_C(1) << 32;
2366 uint64_t epoch = last_timestamp_.ToMicroseconds() & ~(epoch_delta - 1);
2367 // Wrapping is safe here because a wrapped value will not be ClosestTo below.
2368 uint64_t prev_epoch = epoch - epoch_delta;
2369 uint64_t next_epoch = epoch + epoch_delta;
2370
2371 uint64_t time = ClosestTo(
2372 last_timestamp_.ToMicroseconds(), epoch + time_delta_us,
2373 ClosestTo(last_timestamp_.ToMicroseconds(), prev_epoch + time_delta_us,
2374 next_epoch + time_delta_us));
2375
2376 return QuicTime::Delta::FromMicroseconds(time);
2377 }
2378
CalculatePacketNumberFromWire(QuicPacketNumberLength packet_number_length,QuicPacketNumber base_packet_number,uint64_t packet_number) const2379 uint64_t QuicFramer::CalculatePacketNumberFromWire(
2380 QuicPacketNumberLength packet_number_length,
2381 QuicPacketNumber base_packet_number, uint64_t packet_number) const {
2382 // The new packet number might have wrapped to the next epoch, or
2383 // it might have reverse wrapped to the previous epoch, or it might
2384 // remain in the same epoch. Select the packet number closest to the
2385 // next expected packet number, the previous packet number plus 1.
2386
2387 // epoch_delta is the delta between epochs the packet number was serialized
2388 // with, so the correct value is likely the same epoch as the last sequence
2389 // number or an adjacent epoch.
2390 if (!base_packet_number.IsInitialized()) {
2391 return packet_number;
2392 }
2393 const uint64_t epoch_delta = UINT64_C(1) << (8 * packet_number_length);
2394 uint64_t next_packet_number = base_packet_number.ToUint64() + 1;
2395 uint64_t epoch = base_packet_number.ToUint64() & ~(epoch_delta - 1);
2396 uint64_t prev_epoch = epoch - epoch_delta;
2397 uint64_t next_epoch = epoch + epoch_delta;
2398
2399 return ClosestTo(next_packet_number, epoch + packet_number,
2400 ClosestTo(next_packet_number, prev_epoch + packet_number,
2401 next_epoch + packet_number));
2402 }
2403
ProcessPublicHeader(QuicDataReader * reader,bool packet_has_ietf_packet_header,QuicPacketHeader * header)2404 bool QuicFramer::ProcessPublicHeader(QuicDataReader* reader,
2405 bool packet_has_ietf_packet_header,
2406 QuicPacketHeader* header) {
2407 if (packet_has_ietf_packet_header) {
2408 return ProcessIetfPacketHeader(reader, header);
2409 }
2410 uint8_t public_flags;
2411 if (!reader->ReadBytes(&public_flags, 1)) {
2412 set_detailed_error("Unable to read public flags.");
2413 return false;
2414 }
2415
2416 header->reset_flag = (public_flags & PACKET_PUBLIC_FLAGS_RST) != 0;
2417 header->version_flag = (public_flags & PACKET_PUBLIC_FLAGS_VERSION) != 0;
2418
2419 if (validate_flags_ && !header->version_flag &&
2420 public_flags > PACKET_PUBLIC_FLAGS_MAX) {
2421 set_detailed_error("Illegal public flags value.");
2422 return false;
2423 }
2424
2425 if (header->reset_flag && header->version_flag) {
2426 set_detailed_error("Got version flag in reset packet");
2427 return false;
2428 }
2429
2430 QuicConnectionId* header_connection_id = &header->destination_connection_id;
2431 QuicConnectionIdIncluded* header_connection_id_included =
2432 &header->destination_connection_id_included;
2433 if (perspective_ == Perspective::IS_CLIENT) {
2434 header_connection_id = &header->source_connection_id;
2435 header_connection_id_included = &header->source_connection_id_included;
2436 }
2437 switch (public_flags & PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID) {
2438 case PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID:
2439 if (!reader->ReadConnectionId(header_connection_id,
2440 kQuicDefaultConnectionIdLength)) {
2441 set_detailed_error("Unable to read ConnectionId.");
2442 return false;
2443 }
2444 *header_connection_id_included = CONNECTION_ID_PRESENT;
2445 break;
2446 case PACKET_PUBLIC_FLAGS_0BYTE_CONNECTION_ID:
2447 *header_connection_id_included = CONNECTION_ID_ABSENT;
2448 *header_connection_id = last_serialized_server_connection_id_;
2449 break;
2450 }
2451
2452 header->packet_number_length = ReadSequenceNumberLength(
2453 public_flags >> kPublicHeaderSequenceNumberShift);
2454
2455 // Read the version only if the packet is from the client.
2456 // version flag from the server means version negotiation packet.
2457 if (header->version_flag && perspective_ == Perspective::IS_SERVER) {
2458 QuicVersionLabel version_label;
2459 if (!ProcessVersionLabel(reader, &version_label)) {
2460 set_detailed_error("Unable to read protocol version.");
2461 return false;
2462 }
2463 // If the version from the new packet is the same as the version of this
2464 // framer, then the public flags should be set to something we understand.
2465 // If not, this raises an error.
2466 ParsedQuicVersion version = ParseQuicVersionLabel(version_label);
2467 if (version == version_ && public_flags > PACKET_PUBLIC_FLAGS_MAX) {
2468 set_detailed_error("Illegal public flags value.");
2469 return false;
2470 }
2471 header->version = version;
2472 }
2473
2474 // A nonce should only be present in packets from the server to the client,
2475 // which are neither version negotiation nor public reset packets.
2476 if (public_flags & PACKET_PUBLIC_FLAGS_NONCE &&
2477 !(public_flags & PACKET_PUBLIC_FLAGS_VERSION) &&
2478 !(public_flags & PACKET_PUBLIC_FLAGS_RST) &&
2479 // The nonce flag from a client is ignored and is assumed to be an older
2480 // client indicating an eight-byte connection ID.
2481 perspective_ == Perspective::IS_CLIENT) {
2482 if (!reader->ReadBytes(reinterpret_cast<uint8_t*>(last_nonce_.data()),
2483 last_nonce_.size())) {
2484 set_detailed_error("Unable to read nonce.");
2485 return false;
2486 }
2487 header->nonce = &last_nonce_;
2488 } else {
2489 header->nonce = nullptr;
2490 }
2491
2492 return true;
2493 }
2494
2495 // static
GetMinPacketNumberLength(QuicPacketNumber packet_number)2496 QuicPacketNumberLength QuicFramer::GetMinPacketNumberLength(
2497 QuicPacketNumber packet_number) {
2498 QUICHE_DCHECK(packet_number.IsInitialized());
2499 if (packet_number < QuicPacketNumber(1 << (PACKET_1BYTE_PACKET_NUMBER * 8))) {
2500 return PACKET_1BYTE_PACKET_NUMBER;
2501 } else if (packet_number <
2502 QuicPacketNumber(1 << (PACKET_2BYTE_PACKET_NUMBER * 8))) {
2503 return PACKET_2BYTE_PACKET_NUMBER;
2504 } else if (packet_number <
2505 QuicPacketNumber(UINT64_C(1)
2506 << (PACKET_4BYTE_PACKET_NUMBER * 8))) {
2507 return PACKET_4BYTE_PACKET_NUMBER;
2508 } else {
2509 return PACKET_6BYTE_PACKET_NUMBER;
2510 }
2511 }
2512
2513 // static
GetPacketNumberFlags(QuicPacketNumberLength packet_number_length)2514 uint8_t QuicFramer::GetPacketNumberFlags(
2515 QuicPacketNumberLength packet_number_length) {
2516 switch (packet_number_length) {
2517 case PACKET_1BYTE_PACKET_NUMBER:
2518 return PACKET_FLAGS_1BYTE_PACKET;
2519 case PACKET_2BYTE_PACKET_NUMBER:
2520 return PACKET_FLAGS_2BYTE_PACKET;
2521 case PACKET_4BYTE_PACKET_NUMBER:
2522 return PACKET_FLAGS_4BYTE_PACKET;
2523 case PACKET_6BYTE_PACKET_NUMBER:
2524 case PACKET_8BYTE_PACKET_NUMBER:
2525 return PACKET_FLAGS_8BYTE_PACKET;
2526 default:
2527 QUIC_BUG(quic_bug_10850_56) << "Unreachable case statement.";
2528 return PACKET_FLAGS_8BYTE_PACKET;
2529 }
2530 }
2531
2532 // static
GetAckFrameInfo(const QuicAckFrame & frame)2533 QuicFramer::AckFrameInfo QuicFramer::GetAckFrameInfo(
2534 const QuicAckFrame& frame) {
2535 AckFrameInfo new_ack_info;
2536 if (frame.packets.Empty()) {
2537 return new_ack_info;
2538 }
2539 // The first block is the last interval. It isn't encoded with the gap-length
2540 // encoding, so skip it.
2541 new_ack_info.first_block_length = frame.packets.LastIntervalLength();
2542 auto itr = frame.packets.rbegin();
2543 QuicPacketNumber previous_start = itr->min();
2544 new_ack_info.max_block_length = itr->Length();
2545 ++itr;
2546
2547 // Don't do any more work after getting information for 256 ACK blocks; any
2548 // more can't be encoded anyway.
2549 for (; itr != frame.packets.rend() &&
2550 new_ack_info.num_ack_blocks < std::numeric_limits<uint8_t>::max();
2551 previous_start = itr->min(), ++itr) {
2552 const auto& interval = *itr;
2553 const QuicPacketCount total_gap = previous_start - interval.max();
2554 new_ack_info.num_ack_blocks +=
2555 (total_gap + std::numeric_limits<uint8_t>::max() - 1) /
2556 std::numeric_limits<uint8_t>::max();
2557 new_ack_info.max_block_length =
2558 std::max(new_ack_info.max_block_length, interval.Length());
2559 }
2560 return new_ack_info;
2561 }
2562
ProcessUnauthenticatedHeader(QuicDataReader * encrypted_reader,QuicPacketHeader * header)2563 bool QuicFramer::ProcessUnauthenticatedHeader(QuicDataReader* encrypted_reader,
2564 QuicPacketHeader* header) {
2565 QuicPacketNumber base_packet_number;
2566 if (supports_multiple_packet_number_spaces_) {
2567 PacketNumberSpace pn_space = GetPacketNumberSpace(*header);
2568 if (pn_space == NUM_PACKET_NUMBER_SPACES) {
2569 set_detailed_error("Unable to determine packet number space.");
2570 return RaiseError(QUIC_INVALID_PACKET_HEADER);
2571 }
2572 base_packet_number = largest_decrypted_packet_numbers_[pn_space];
2573 } else {
2574 base_packet_number = largest_packet_number_;
2575 }
2576 uint64_t full_packet_number;
2577 if (!ProcessAndCalculatePacketNumber(
2578 encrypted_reader, header->packet_number_length, base_packet_number,
2579 &full_packet_number)) {
2580 set_detailed_error("Unable to read packet number.");
2581 return RaiseError(QUIC_INVALID_PACKET_HEADER);
2582 }
2583
2584 if (!IsValidFullPacketNumber(full_packet_number, version())) {
2585 set_detailed_error("packet numbers cannot be 0.");
2586 return RaiseError(QUIC_INVALID_PACKET_HEADER);
2587 }
2588 header->packet_number = QuicPacketNumber(full_packet_number);
2589
2590 if (!visitor_->OnUnauthenticatedHeader(*header)) {
2591 set_detailed_error(
2592 "Visitor asked to stop processing of unauthenticated header.");
2593 return false;
2594 }
2595 // The function we are in is called because the framer believes that it is
2596 // processing a packet that uses the non-IETF (i.e. Google QUIC) packet header
2597 // type. Usually, the framer makes that decision based on the framer's
2598 // version, but when the framer is used with Perspective::IS_SERVER, then
2599 // before version negotiation is complete (specifically, before
2600 // InferPacketHeaderTypeFromVersion is called), this decision is made based on
2601 // the type byte of the packet.
2602 //
2603 // If the framer's version KnowsWhichDecrypterToUse, then that version expects
2604 // to use the IETF packet header type. If that's the case and we're in this
2605 // function, then the packet received is invalid: the framer was expecting an
2606 // IETF packet header and didn't get one.
2607 if (version().KnowsWhichDecrypterToUse()) {
2608 set_detailed_error("Invalid public header type for expected version.");
2609 return RaiseError(QUIC_INVALID_PACKET_HEADER);
2610 }
2611 return true;
2612 }
2613
ProcessIetfHeaderTypeByte(QuicDataReader * reader,QuicPacketHeader * header)2614 bool QuicFramer::ProcessIetfHeaderTypeByte(QuicDataReader* reader,
2615 QuicPacketHeader* header) {
2616 uint8_t type;
2617 if (!reader->ReadBytes(&type, 1)) {
2618 set_detailed_error("Unable to read first byte.");
2619 return false;
2620 }
2621 header->type_byte = type;
2622 // Determine whether this is a long or short header.
2623 header->form = GetIetfPacketHeaderFormat(type);
2624 if (header->form == IETF_QUIC_LONG_HEADER_PACKET) {
2625 // Version is always present in long headers.
2626 header->version_flag = true;
2627 // In versions that do not support client connection IDs, we mark the
2628 // corresponding connection ID as absent.
2629 header->destination_connection_id_included =
2630 (perspective_ == Perspective::IS_SERVER ||
2631 version_.SupportsClientConnectionIds())
2632 ? CONNECTION_ID_PRESENT
2633 : CONNECTION_ID_ABSENT;
2634 header->source_connection_id_included =
2635 (perspective_ == Perspective::IS_CLIENT ||
2636 version_.SupportsClientConnectionIds())
2637 ? CONNECTION_ID_PRESENT
2638 : CONNECTION_ID_ABSENT;
2639 // Read version tag.
2640 QuicVersionLabel version_label;
2641 if (!ProcessVersionLabel(reader, &version_label)) {
2642 set_detailed_error("Unable to read protocol version.");
2643 return false;
2644 }
2645 if (!version_label) {
2646 // Version label is 0 indicating this is a version negotiation packet.
2647 header->long_packet_type = VERSION_NEGOTIATION;
2648 } else {
2649 header->version = ParseQuicVersionLabel(version_label);
2650 if (header->version.IsKnown()) {
2651 if (!(type & FLAGS_FIXED_BIT)) {
2652 set_detailed_error("Fixed bit is 0 in long header.");
2653 return false;
2654 }
2655 header->long_packet_type = GetLongHeaderType(type, header->version);
2656 switch (header->long_packet_type) {
2657 case INVALID_PACKET_TYPE:
2658 set_detailed_error("Illegal long header type value.");
2659 return false;
2660 case RETRY:
2661 if (!version().SupportsRetry()) {
2662 set_detailed_error("RETRY not supported in this version.");
2663 return false;
2664 }
2665 if (perspective_ == Perspective::IS_SERVER) {
2666 set_detailed_error("Client-initiated RETRY is invalid.");
2667 return false;
2668 }
2669 break;
2670 default:
2671 if (!header->version.HasHeaderProtection()) {
2672 header->packet_number_length =
2673 GetLongHeaderPacketNumberLength(type);
2674 }
2675 break;
2676 }
2677 }
2678 }
2679
2680 QUIC_DVLOG(1) << ENDPOINT << "Received IETF long header: "
2681 << QuicUtils::QuicLongHeaderTypetoString(
2682 header->long_packet_type);
2683 return true;
2684 }
2685
2686 QUIC_DVLOG(1) << ENDPOINT << "Received IETF short header";
2687 // Version is not present in short headers.
2688 header->version_flag = false;
2689 // In versions that do not support client connection IDs, the client will not
2690 // receive destination connection IDs.
2691 header->destination_connection_id_included =
2692 (perspective_ == Perspective::IS_SERVER ||
2693 version_.SupportsClientConnectionIds())
2694 ? CONNECTION_ID_PRESENT
2695 : CONNECTION_ID_ABSENT;
2696 header->source_connection_id_included = CONNECTION_ID_ABSENT;
2697 if (!(type & FLAGS_FIXED_BIT)) {
2698 set_detailed_error("Fixed bit is 0 in short header.");
2699 return false;
2700 }
2701 if (!version_.HasHeaderProtection()) {
2702 header->packet_number_length = GetShortHeaderPacketNumberLength(type);
2703 }
2704 QUIC_DVLOG(1) << "packet_number_length = " << header->packet_number_length;
2705 return true;
2706 }
2707
2708 // static
ProcessVersionLabel(QuicDataReader * reader,QuicVersionLabel * version_label)2709 bool QuicFramer::ProcessVersionLabel(QuicDataReader* reader,
2710 QuicVersionLabel* version_label) {
2711 if (!reader->ReadUInt32(version_label)) {
2712 return false;
2713 }
2714 return true;
2715 }
2716
2717 // static
ProcessAndValidateIetfConnectionIdLength(QuicDataReader * reader,ParsedQuicVersion version,Perspective perspective,bool should_update_expected_server_connection_id_length,uint8_t * expected_server_connection_id_length,uint8_t * destination_connection_id_length,uint8_t * source_connection_id_length,std::string * detailed_error)2718 bool QuicFramer::ProcessAndValidateIetfConnectionIdLength(
2719 QuicDataReader* reader, ParsedQuicVersion version, Perspective perspective,
2720 bool should_update_expected_server_connection_id_length,
2721 uint8_t* expected_server_connection_id_length,
2722 uint8_t* destination_connection_id_length,
2723 uint8_t* source_connection_id_length, std::string* detailed_error) {
2724 uint8_t connection_id_lengths_byte;
2725 if (!reader->ReadBytes(&connection_id_lengths_byte, 1)) {
2726 *detailed_error = "Unable to read ConnectionId length.";
2727 return false;
2728 }
2729 uint8_t dcil =
2730 (connection_id_lengths_byte & kDestinationConnectionIdLengthMask) >> 4;
2731 if (dcil != 0) {
2732 dcil += kConnectionIdLengthAdjustment;
2733 }
2734 uint8_t scil = connection_id_lengths_byte & kSourceConnectionIdLengthMask;
2735 if (scil != 0) {
2736 scil += kConnectionIdLengthAdjustment;
2737 }
2738 if (should_update_expected_server_connection_id_length) {
2739 uint8_t server_connection_id_length =
2740 perspective == Perspective::IS_SERVER ? dcil : scil;
2741 if (*expected_server_connection_id_length != server_connection_id_length) {
2742 QUIC_DVLOG(1) << "Updating expected_server_connection_id_length: "
2743 << static_cast<int>(*expected_server_connection_id_length)
2744 << " -> " << static_cast<int>(server_connection_id_length);
2745 *expected_server_connection_id_length = server_connection_id_length;
2746 }
2747 }
2748 if (!should_update_expected_server_connection_id_length &&
2749 (dcil != *destination_connection_id_length ||
2750 scil != *source_connection_id_length) &&
2751 version.IsKnown() && !version.AllowsVariableLengthConnectionIds()) {
2752 QUIC_DVLOG(1) << "dcil: " << static_cast<uint32_t>(dcil)
2753 << ", scil: " << static_cast<uint32_t>(scil);
2754 *detailed_error = "Invalid ConnectionId length.";
2755 return false;
2756 }
2757 *destination_connection_id_length = dcil;
2758 *source_connection_id_length = scil;
2759 return true;
2760 }
2761
ValidateReceivedConnectionIds(const QuicPacketHeader & header)2762 bool QuicFramer::ValidateReceivedConnectionIds(const QuicPacketHeader& header) {
2763 bool skip_server_connection_id_validation =
2764 perspective_ == Perspective::IS_CLIENT &&
2765 header.form == IETF_QUIC_SHORT_HEADER_PACKET;
2766 if (!skip_server_connection_id_validation &&
2767 !QuicUtils::IsConnectionIdValidForVersion(
2768 GetServerConnectionIdAsRecipient(header, perspective_),
2769 transport_version())) {
2770 set_detailed_error("Received server connection ID with invalid length.");
2771 return false;
2772 }
2773
2774 bool skip_client_connection_id_validation =
2775 perspective_ == Perspective::IS_SERVER &&
2776 header.form == IETF_QUIC_SHORT_HEADER_PACKET;
2777 if (!skip_client_connection_id_validation &&
2778 version_.SupportsClientConnectionIds() &&
2779 !QuicUtils::IsConnectionIdValidForVersion(
2780 GetClientConnectionIdAsRecipient(header, perspective_),
2781 transport_version())) {
2782 set_detailed_error("Received client connection ID with invalid length.");
2783 return false;
2784 }
2785 return true;
2786 }
2787
ProcessIetfPacketHeader(QuicDataReader * reader,QuicPacketHeader * header)2788 bool QuicFramer::ProcessIetfPacketHeader(QuicDataReader* reader,
2789 QuicPacketHeader* header) {
2790 if (version_.HasLengthPrefixedConnectionIds()) {
2791 uint8_t expected_destination_connection_id_length =
2792 perspective_ == Perspective::IS_CLIENT
2793 ? expected_client_connection_id_length_
2794 : expected_server_connection_id_length_;
2795 QuicVersionLabel version_label;
2796 bool has_length_prefix;
2797 std::string detailed_error;
2798 QuicErrorCode parse_result = QuicFramer::ParsePublicHeader(
2799 reader, expected_destination_connection_id_length,
2800 version_.HasIetfInvariantHeader(), &header->type_byte, &header->form,
2801 &header->version_flag, &has_length_prefix, &version_label,
2802 &header->version, &header->destination_connection_id,
2803 &header->source_connection_id, &header->long_packet_type,
2804 &header->retry_token_length_length, &header->retry_token,
2805 &detailed_error);
2806 if (parse_result != QUIC_NO_ERROR) {
2807 set_detailed_error(detailed_error);
2808 return false;
2809 }
2810 header->destination_connection_id_included = CONNECTION_ID_PRESENT;
2811 header->source_connection_id_included =
2812 header->version_flag ? CONNECTION_ID_PRESENT : CONNECTION_ID_ABSENT;
2813
2814 if (!ValidateReceivedConnectionIds(*header)) {
2815 return false;
2816 }
2817
2818 if (header->version_flag &&
2819 header->long_packet_type != VERSION_NEGOTIATION &&
2820 !(header->type_byte & FLAGS_FIXED_BIT)) {
2821 set_detailed_error("Fixed bit is 0 in long header.");
2822 return false;
2823 }
2824 if (!header->version_flag && !(header->type_byte & FLAGS_FIXED_BIT)) {
2825 set_detailed_error("Fixed bit is 0 in short header.");
2826 return false;
2827 }
2828 if (!header->version_flag) {
2829 if (!version_.HasHeaderProtection()) {
2830 header->packet_number_length =
2831 GetShortHeaderPacketNumberLength(header->type_byte);
2832 }
2833 return true;
2834 }
2835 if (header->long_packet_type == RETRY) {
2836 if (!version().SupportsRetry()) {
2837 set_detailed_error("RETRY not supported in this version.");
2838 return false;
2839 }
2840 if (perspective_ == Perspective::IS_SERVER) {
2841 set_detailed_error("Client-initiated RETRY is invalid.");
2842 return false;
2843 }
2844 return true;
2845 }
2846 if (header->version.IsKnown() && !header->version.HasHeaderProtection()) {
2847 header->packet_number_length =
2848 GetLongHeaderPacketNumberLength(header->type_byte);
2849 }
2850
2851 return true;
2852 }
2853
2854 if (!ProcessIetfHeaderTypeByte(reader, header)) {
2855 return false;
2856 }
2857
2858 uint8_t destination_connection_id_length =
2859 header->destination_connection_id_included == CONNECTION_ID_PRESENT
2860 ? (perspective_ == Perspective::IS_SERVER
2861 ? expected_server_connection_id_length_
2862 : expected_client_connection_id_length_)
2863 : 0;
2864 uint8_t source_connection_id_length =
2865 header->source_connection_id_included == CONNECTION_ID_PRESENT
2866 ? (perspective_ == Perspective::IS_CLIENT
2867 ? expected_server_connection_id_length_
2868 : expected_client_connection_id_length_)
2869 : 0;
2870 if (header->form == IETF_QUIC_LONG_HEADER_PACKET) {
2871 if (!ProcessAndValidateIetfConnectionIdLength(
2872 reader, header->version, perspective_,
2873 /*should_update_expected_server_connection_id_length=*/false,
2874 &expected_server_connection_id_length_,
2875 &destination_connection_id_length, &source_connection_id_length,
2876 &detailed_error_)) {
2877 return false;
2878 }
2879 }
2880
2881 // Read connection ID.
2882 if (!reader->ReadConnectionId(&header->destination_connection_id,
2883 destination_connection_id_length)) {
2884 set_detailed_error("Unable to read destination connection ID.");
2885 return false;
2886 }
2887
2888 if (!reader->ReadConnectionId(&header->source_connection_id,
2889 source_connection_id_length)) {
2890 set_detailed_error("Unable to read source connection ID.");
2891 return false;
2892 }
2893
2894 if (header->source_connection_id_included == CONNECTION_ID_ABSENT) {
2895 if (!header->source_connection_id.IsEmpty()) {
2896 QUICHE_DCHECK(!version_.SupportsClientConnectionIds());
2897 set_detailed_error("Client connection ID not supported in this version.");
2898 return false;
2899 }
2900 }
2901
2902 return ValidateReceivedConnectionIds(*header);
2903 }
2904
ProcessAndCalculatePacketNumber(QuicDataReader * reader,QuicPacketNumberLength packet_number_length,QuicPacketNumber base_packet_number,uint64_t * packet_number)2905 bool QuicFramer::ProcessAndCalculatePacketNumber(
2906 QuicDataReader* reader, QuicPacketNumberLength packet_number_length,
2907 QuicPacketNumber base_packet_number, uint64_t* packet_number) {
2908 uint64_t wire_packet_number;
2909 if (!reader->ReadBytesToUInt64(packet_number_length, &wire_packet_number)) {
2910 return false;
2911 }
2912
2913 // TODO(ianswett): Explore the usefulness of trying multiple packet numbers
2914 // in case the first guess is incorrect.
2915 *packet_number = CalculatePacketNumberFromWire(
2916 packet_number_length, base_packet_number, wire_packet_number);
2917 return true;
2918 }
2919
ProcessFrameData(QuicDataReader * reader,const QuicPacketHeader & header)2920 bool QuicFramer::ProcessFrameData(QuicDataReader* reader,
2921 const QuicPacketHeader& header) {
2922 QUICHE_DCHECK(!VersionHasIetfQuicFrames(version_.transport_version))
2923 << "IETF QUIC Framing negotiated but attempting to process frames as "
2924 "non-IETF QUIC.";
2925 if (reader->IsDoneReading()) {
2926 set_detailed_error("Packet has no frames.");
2927 return RaiseError(QUIC_MISSING_PAYLOAD);
2928 }
2929 QUIC_DVLOG(2) << ENDPOINT << "Processing packet with header " << header;
2930 while (!reader->IsDoneReading()) {
2931 uint8_t frame_type;
2932 if (!reader->ReadBytes(&frame_type, 1)) {
2933 set_detailed_error("Unable to read frame type.");
2934 return RaiseError(QUIC_INVALID_FRAME_DATA);
2935 }
2936 const uint8_t special_mask = version_.HasIetfInvariantHeader()
2937 ? kQuicFrameTypeSpecialMask
2938 : kQuicFrameTypeBrokenMask;
2939 if (frame_type & special_mask) {
2940 // Stream Frame
2941 if (frame_type & kQuicFrameTypeStreamMask) {
2942 QuicStreamFrame frame;
2943 if (!ProcessStreamFrame(reader, frame_type, &frame)) {
2944 return RaiseError(QUIC_INVALID_STREAM_DATA);
2945 }
2946 QUIC_DVLOG(2) << ENDPOINT << "Processing stream frame " << frame;
2947 if (!visitor_->OnStreamFrame(frame)) {
2948 QUIC_DVLOG(1) << ENDPOINT
2949 << "Visitor asked to stop further processing.";
2950 // Returning true since there was no parsing error.
2951 return true;
2952 }
2953 continue;
2954 }
2955
2956 // Ack Frame
2957 if (frame_type & kQuicFrameTypeAckMask) {
2958 if (!ProcessAckFrame(reader, frame_type)) {
2959 return RaiseError(QUIC_INVALID_ACK_DATA);
2960 }
2961 QUIC_DVLOG(2) << ENDPOINT << "Processing ACK frame";
2962 continue;
2963 }
2964
2965 // This was a special frame type that did not match any
2966 // of the known ones. Error.
2967 set_detailed_error("Illegal frame type.");
2968 QUIC_DLOG(WARNING) << ENDPOINT << "Illegal frame type: "
2969 << static_cast<int>(frame_type);
2970 return RaiseError(QUIC_INVALID_FRAME_DATA);
2971 }
2972
2973 switch (frame_type) {
2974 case PADDING_FRAME: {
2975 QuicPaddingFrame frame;
2976 ProcessPaddingFrame(reader, &frame);
2977 QUIC_DVLOG(2) << ENDPOINT << "Processing padding frame " << frame;
2978 if (!visitor_->OnPaddingFrame(frame)) {
2979 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
2980 // Returning true since there was no parsing error.
2981 return true;
2982 }
2983 continue;
2984 }
2985
2986 case RST_STREAM_FRAME: {
2987 QuicRstStreamFrame frame;
2988 if (!ProcessRstStreamFrame(reader, &frame)) {
2989 return RaiseError(QUIC_INVALID_RST_STREAM_DATA);
2990 }
2991 QUIC_DVLOG(2) << ENDPOINT << "Processing reset stream frame " << frame;
2992 if (!visitor_->OnRstStreamFrame(frame)) {
2993 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
2994 // Returning true since there was no parsing error.
2995 return true;
2996 }
2997 continue;
2998 }
2999
3000 case CONNECTION_CLOSE_FRAME: {
3001 QuicConnectionCloseFrame frame;
3002 if (!ProcessConnectionCloseFrame(reader, &frame)) {
3003 return RaiseError(QUIC_INVALID_CONNECTION_CLOSE_DATA);
3004 }
3005
3006 QUIC_DVLOG(2) << ENDPOINT << "Processing connection close frame "
3007 << frame;
3008 if (!visitor_->OnConnectionCloseFrame(frame)) {
3009 QUIC_DVLOG(1) << ENDPOINT
3010 << "Visitor asked to stop further processing.";
3011 // Returning true since there was no parsing error.
3012 return true;
3013 }
3014 continue;
3015 }
3016
3017 case GOAWAY_FRAME: {
3018 QuicGoAwayFrame goaway_frame;
3019 if (!ProcessGoAwayFrame(reader, &goaway_frame)) {
3020 return RaiseError(QUIC_INVALID_GOAWAY_DATA);
3021 }
3022 QUIC_DVLOG(2) << ENDPOINT << "Processing go away frame "
3023 << goaway_frame;
3024 if (!visitor_->OnGoAwayFrame(goaway_frame)) {
3025 QUIC_DVLOG(1) << ENDPOINT
3026 << "Visitor asked to stop further processing.";
3027 // Returning true since there was no parsing error.
3028 return true;
3029 }
3030 continue;
3031 }
3032
3033 case WINDOW_UPDATE_FRAME: {
3034 QuicWindowUpdateFrame window_update_frame;
3035 if (!ProcessWindowUpdateFrame(reader, &window_update_frame)) {
3036 return RaiseError(QUIC_INVALID_WINDOW_UPDATE_DATA);
3037 }
3038 QUIC_DVLOG(2) << ENDPOINT << "Processing window update frame "
3039 << window_update_frame;
3040 if (!visitor_->OnWindowUpdateFrame(window_update_frame)) {
3041 QUIC_DVLOG(1) << ENDPOINT
3042 << "Visitor asked to stop further processing.";
3043 // Returning true since there was no parsing error.
3044 return true;
3045 }
3046 continue;
3047 }
3048
3049 case BLOCKED_FRAME: {
3050 QuicBlockedFrame blocked_frame;
3051 if (!ProcessBlockedFrame(reader, &blocked_frame)) {
3052 return RaiseError(QUIC_INVALID_BLOCKED_DATA);
3053 }
3054 QUIC_DVLOG(2) << ENDPOINT << "Processing blocked frame "
3055 << blocked_frame;
3056 if (!visitor_->OnBlockedFrame(blocked_frame)) {
3057 QUIC_DVLOG(1) << ENDPOINT
3058 << "Visitor asked to stop further processing.";
3059 // Returning true since there was no parsing error.
3060 return true;
3061 }
3062 continue;
3063 }
3064
3065 case STOP_WAITING_FRAME: {
3066 QuicStopWaitingFrame stop_waiting_frame;
3067 if (!ProcessStopWaitingFrame(reader, header, &stop_waiting_frame)) {
3068 return RaiseError(QUIC_INVALID_STOP_WAITING_DATA);
3069 }
3070 QUIC_DVLOG(2) << ENDPOINT << "Processing stop waiting frame "
3071 << stop_waiting_frame;
3072 if (!visitor_->OnStopWaitingFrame(stop_waiting_frame)) {
3073 QUIC_DVLOG(1) << ENDPOINT
3074 << "Visitor asked to stop further processing.";
3075 // Returning true since there was no parsing error.
3076 return true;
3077 }
3078 continue;
3079 }
3080 case PING_FRAME: {
3081 // Ping has no payload.
3082 QuicPingFrame ping_frame;
3083 if (!visitor_->OnPingFrame(ping_frame)) {
3084 QUIC_DVLOG(1) << ENDPOINT
3085 << "Visitor asked to stop further processing.";
3086 // Returning true since there was no parsing error.
3087 return true;
3088 }
3089 QUIC_DVLOG(2) << ENDPOINT << "Processing ping frame " << ping_frame;
3090 continue;
3091 }
3092 case IETF_EXTENSION_MESSAGE_NO_LENGTH:
3093 ABSL_FALLTHROUGH_INTENDED;
3094 case IETF_EXTENSION_MESSAGE: {
3095 QuicMessageFrame message_frame;
3096 if (!ProcessMessageFrame(reader,
3097 frame_type == IETF_EXTENSION_MESSAGE_NO_LENGTH,
3098 &message_frame)) {
3099 return RaiseError(QUIC_INVALID_MESSAGE_DATA);
3100 }
3101 QUIC_DVLOG(2) << ENDPOINT << "Processing message frame "
3102 << message_frame;
3103 if (!visitor_->OnMessageFrame(message_frame)) {
3104 QUIC_DVLOG(1) << ENDPOINT
3105 << "Visitor asked to stop further processing.";
3106 // Returning true since there was no parsing error.
3107 return true;
3108 }
3109 break;
3110 }
3111 case CRYPTO_FRAME: {
3112 if (!QuicVersionUsesCryptoFrames(version_.transport_version)) {
3113 set_detailed_error("Illegal frame type.");
3114 return RaiseError(QUIC_INVALID_FRAME_DATA);
3115 }
3116 QuicCryptoFrame frame;
3117 if (!ProcessCryptoFrame(reader, GetEncryptionLevel(header), &frame)) {
3118 return RaiseError(QUIC_INVALID_FRAME_DATA);
3119 }
3120 QUIC_DVLOG(2) << ENDPOINT << "Processing crypto frame " << frame;
3121 if (!visitor_->OnCryptoFrame(frame)) {
3122 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3123 // Returning true since there was no parsing error.
3124 return true;
3125 }
3126 break;
3127 }
3128 case HANDSHAKE_DONE_FRAME: {
3129 // HANDSHAKE_DONE has no payload.
3130 QuicHandshakeDoneFrame handshake_done_frame;
3131 QUIC_DVLOG(2) << ENDPOINT << "Processing handshake done frame "
3132 << handshake_done_frame;
3133 if (!visitor_->OnHandshakeDoneFrame(handshake_done_frame)) {
3134 QUIC_DVLOG(1) << ENDPOINT
3135 << "Visitor asked to stop further processing.";
3136 // Returning true since there was no parsing error.
3137 return true;
3138 }
3139 break;
3140 }
3141
3142 default:
3143 set_detailed_error("Illegal frame type.");
3144 QUIC_DLOG(WARNING) << ENDPOINT << "Illegal frame type: "
3145 << static_cast<int>(frame_type);
3146 return RaiseError(QUIC_INVALID_FRAME_DATA);
3147 }
3148 }
3149
3150 return true;
3151 }
3152
3153 // static
IsIetfFrameTypeExpectedForEncryptionLevel(uint64_t frame_type,EncryptionLevel level)3154 bool QuicFramer::IsIetfFrameTypeExpectedForEncryptionLevel(
3155 uint64_t frame_type, EncryptionLevel level) {
3156 // IETF_CRYPTO is allowed for any level here and is separately checked in
3157 // QuicCryptoStream::OnCryptoFrame.
3158 switch (level) {
3159 case ENCRYPTION_INITIAL:
3160 case ENCRYPTION_HANDSHAKE:
3161 return frame_type == IETF_CRYPTO || frame_type == IETF_ACK ||
3162 frame_type == IETF_ACK_ECN ||
3163 frame_type == IETF_ACK_RECEIVE_TIMESTAMPS ||
3164 frame_type == IETF_PING || frame_type == IETF_PADDING ||
3165 frame_type == IETF_CONNECTION_CLOSE;
3166 case ENCRYPTION_ZERO_RTT:
3167 return !(frame_type == IETF_ACK || frame_type == IETF_ACK_ECN ||
3168 frame_type == IETF_ACK_RECEIVE_TIMESTAMPS ||
3169 frame_type == IETF_HANDSHAKE_DONE ||
3170 frame_type == IETF_NEW_TOKEN ||
3171 frame_type == IETF_PATH_RESPONSE ||
3172 frame_type == IETF_RETIRE_CONNECTION_ID);
3173 case ENCRYPTION_FORWARD_SECURE:
3174 return true;
3175 default:
3176 QUIC_BUG(quic_bug_10850_57) << "Unknown encryption level: " << level;
3177 }
3178 return false;
3179 }
3180
ProcessIetfFrameData(QuicDataReader * reader,const QuicPacketHeader & header,EncryptionLevel decrypted_level)3181 bool QuicFramer::ProcessIetfFrameData(QuicDataReader* reader,
3182 const QuicPacketHeader& header,
3183 EncryptionLevel decrypted_level) {
3184 QUICHE_DCHECK(VersionHasIetfQuicFrames(version_.transport_version))
3185 << "Attempt to process frames as IETF frames but version ("
3186 << version_.transport_version << ") does not support IETF Framing.";
3187
3188 if (reader->IsDoneReading()) {
3189 set_detailed_error("Packet has no frames.");
3190 return RaiseError(QUIC_MISSING_PAYLOAD);
3191 }
3192
3193 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF packet with header " << header;
3194 auto* connection_context = QuicConnectionContext::Current();
3195 while (!reader->IsDoneReading()) {
3196 if (connection_context != nullptr) {
3197 connection_context->process_packet_context.current_frame_offset =
3198 connection_context->process_packet_context.decrypted_payload.size() -
3199 reader->BytesRemaining();
3200 }
3201 uint64_t frame_type;
3202 // Will be the number of bytes into which frame_type was encoded.
3203 size_t encoded_bytes = reader->BytesRemaining();
3204 if (!reader->ReadVarInt62(&frame_type)) {
3205 set_detailed_error("Unable to read frame type.");
3206 return RaiseError(QUIC_INVALID_FRAME_DATA);
3207 }
3208 if (!IsIetfFrameTypeExpectedForEncryptionLevel(frame_type,
3209 decrypted_level)) {
3210 set_detailed_error(absl::StrCat(
3211 "IETF frame type ",
3212 QuicIetfFrameTypeString(static_cast<QuicIetfFrameType>(frame_type)),
3213 " is unexpected at encryption level ",
3214 EncryptionLevelToString(decrypted_level)));
3215 return RaiseError(IETF_QUIC_PROTOCOL_VIOLATION);
3216 }
3217 previously_received_frame_type_ = current_received_frame_type_;
3218 current_received_frame_type_ = frame_type;
3219
3220 // Is now the number of bytes into which the frame type was encoded.
3221 encoded_bytes -= reader->BytesRemaining();
3222
3223 // Check that the frame type is minimally encoded.
3224 if (encoded_bytes !=
3225 static_cast<size_t>(QuicDataWriter::GetVarInt62Len(frame_type))) {
3226 // The frame type was not minimally encoded.
3227 set_detailed_error("Frame type not minimally encoded.");
3228 return RaiseError(IETF_QUIC_PROTOCOL_VIOLATION);
3229 }
3230
3231 if (IS_IETF_STREAM_FRAME(frame_type)) {
3232 QuicStreamFrame frame;
3233 if (!ProcessIetfStreamFrame(reader, frame_type, &frame)) {
3234 return RaiseError(QUIC_INVALID_STREAM_DATA);
3235 }
3236 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF stream frame " << frame;
3237 if (!visitor_->OnStreamFrame(frame)) {
3238 QUIC_DVLOG(1) << ENDPOINT
3239 << "Visitor asked to stop further processing.";
3240 // Returning true since there was no parsing error.
3241 return true;
3242 }
3243 } else {
3244 switch (frame_type) {
3245 case IETF_PADDING: {
3246 QuicPaddingFrame frame;
3247 ProcessPaddingFrame(reader, &frame);
3248 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF padding frame "
3249 << frame;
3250 if (!visitor_->OnPaddingFrame(frame)) {
3251 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3252 // Returning true since there was no parsing error.
3253 return true;
3254 }
3255 break;
3256 }
3257 case IETF_RST_STREAM: {
3258 QuicRstStreamFrame frame;
3259 if (!ProcessIetfResetStreamFrame(reader, &frame)) {
3260 return RaiseError(QUIC_INVALID_RST_STREAM_DATA);
3261 }
3262 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF reset stream frame "
3263 << frame;
3264 if (!visitor_->OnRstStreamFrame(frame)) {
3265 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3266 // Returning true since there was no parsing error.
3267 return true;
3268 }
3269 break;
3270 }
3271 case IETF_APPLICATION_CLOSE:
3272 case IETF_CONNECTION_CLOSE: {
3273 QuicConnectionCloseFrame frame;
3274 if (!ProcessIetfConnectionCloseFrame(
3275 reader,
3276 (frame_type == IETF_CONNECTION_CLOSE)
3277 ? IETF_QUIC_TRANSPORT_CONNECTION_CLOSE
3278 : IETF_QUIC_APPLICATION_CONNECTION_CLOSE,
3279 &frame)) {
3280 return RaiseError(QUIC_INVALID_CONNECTION_CLOSE_DATA);
3281 }
3282 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF connection close frame "
3283 << frame;
3284 if (!visitor_->OnConnectionCloseFrame(frame)) {
3285 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3286 // Returning true since there was no parsing error.
3287 return true;
3288 }
3289 break;
3290 }
3291 case IETF_MAX_DATA: {
3292 QuicWindowUpdateFrame frame;
3293 if (!ProcessMaxDataFrame(reader, &frame)) {
3294 return RaiseError(QUIC_INVALID_MAX_DATA_FRAME_DATA);
3295 }
3296 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF max data frame "
3297 << frame;
3298 if (!visitor_->OnWindowUpdateFrame(frame)) {
3299 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3300 // Returning true since there was no parsing error.
3301 return true;
3302 }
3303 break;
3304 }
3305 case IETF_MAX_STREAM_DATA: {
3306 QuicWindowUpdateFrame frame;
3307 if (!ProcessMaxStreamDataFrame(reader, &frame)) {
3308 return RaiseError(QUIC_INVALID_MAX_STREAM_DATA_FRAME_DATA);
3309 }
3310 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF max stream data frame "
3311 << frame;
3312 if (!visitor_->OnWindowUpdateFrame(frame)) {
3313 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3314 // Returning true since there was no parsing error.
3315 return true;
3316 }
3317 break;
3318 }
3319 case IETF_MAX_STREAMS_BIDIRECTIONAL:
3320 case IETF_MAX_STREAMS_UNIDIRECTIONAL: {
3321 QuicMaxStreamsFrame frame;
3322 if (!ProcessMaxStreamsFrame(reader, &frame, frame_type)) {
3323 return RaiseError(QUIC_MAX_STREAMS_DATA);
3324 }
3325 QUIC_CODE_COUNT_N(quic_max_streams_received, 1, 2);
3326 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF max streams frame "
3327 << frame;
3328 if (!visitor_->OnMaxStreamsFrame(frame)) {
3329 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3330 // Returning true since there was no parsing error.
3331 return true;
3332 }
3333 break;
3334 }
3335 case IETF_PING: {
3336 // Ping has no payload.
3337 QuicPingFrame ping_frame;
3338 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF ping frame "
3339 << ping_frame;
3340 if (!visitor_->OnPingFrame(ping_frame)) {
3341 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3342 // Returning true since there was no parsing error.
3343 return true;
3344 }
3345 break;
3346 }
3347 case IETF_DATA_BLOCKED: {
3348 QuicBlockedFrame frame;
3349 if (!ProcessDataBlockedFrame(reader, &frame)) {
3350 return RaiseError(QUIC_INVALID_BLOCKED_DATA);
3351 }
3352 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF blocked frame "
3353 << frame;
3354 if (!visitor_->OnBlockedFrame(frame)) {
3355 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3356 // Returning true since there was no parsing error.
3357 return true;
3358 }
3359 break;
3360 }
3361 case IETF_STREAM_DATA_BLOCKED: {
3362 QuicBlockedFrame frame;
3363 if (!ProcessStreamDataBlockedFrame(reader, &frame)) {
3364 return RaiseError(QUIC_INVALID_STREAM_BLOCKED_DATA);
3365 }
3366 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF stream blocked frame "
3367 << frame;
3368 if (!visitor_->OnBlockedFrame(frame)) {
3369 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3370 // Returning true since there was no parsing error.
3371 return true;
3372 }
3373 break;
3374 }
3375 case IETF_STREAMS_BLOCKED_UNIDIRECTIONAL:
3376 case IETF_STREAMS_BLOCKED_BIDIRECTIONAL: {
3377 QuicStreamsBlockedFrame frame;
3378 if (!ProcessStreamsBlockedFrame(reader, &frame, frame_type)) {
3379 return RaiseError(QUIC_STREAMS_BLOCKED_DATA);
3380 }
3381 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF streams blocked frame "
3382 << frame;
3383 if (!visitor_->OnStreamsBlockedFrame(frame)) {
3384 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3385 // Returning true since there was no parsing error.
3386 return true;
3387 }
3388 break;
3389 }
3390 case IETF_NEW_CONNECTION_ID: {
3391 QuicNewConnectionIdFrame frame;
3392 if (!ProcessNewConnectionIdFrame(reader, &frame)) {
3393 return RaiseError(QUIC_INVALID_NEW_CONNECTION_ID_DATA);
3394 }
3395 QUIC_DVLOG(2) << ENDPOINT
3396 << "Processing IETF new connection ID frame " << frame;
3397 if (!visitor_->OnNewConnectionIdFrame(frame)) {
3398 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3399 // Returning true since there was no parsing error.
3400 return true;
3401 }
3402 break;
3403 }
3404 case IETF_RETIRE_CONNECTION_ID: {
3405 QuicRetireConnectionIdFrame frame;
3406 if (!ProcessRetireConnectionIdFrame(reader, &frame)) {
3407 return RaiseError(QUIC_INVALID_RETIRE_CONNECTION_ID_DATA);
3408 }
3409 QUIC_DVLOG(2) << ENDPOINT
3410 << "Processing IETF retire connection ID frame "
3411 << frame;
3412 if (!visitor_->OnRetireConnectionIdFrame(frame)) {
3413 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3414 // Returning true since there was no parsing error.
3415 return true;
3416 }
3417 break;
3418 }
3419 case IETF_NEW_TOKEN: {
3420 QuicNewTokenFrame frame;
3421 if (!ProcessNewTokenFrame(reader, &frame)) {
3422 return RaiseError(QUIC_INVALID_NEW_TOKEN);
3423 }
3424 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF new token frame "
3425 << frame;
3426 if (!visitor_->OnNewTokenFrame(frame)) {
3427 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3428 // Returning true since there was no parsing error.
3429 return true;
3430 }
3431 break;
3432 }
3433 case IETF_STOP_SENDING: {
3434 QuicStopSendingFrame frame;
3435 if (!ProcessStopSendingFrame(reader, &frame)) {
3436 return RaiseError(QUIC_INVALID_STOP_SENDING_FRAME_DATA);
3437 }
3438 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF stop sending frame "
3439 << frame;
3440 if (!visitor_->OnStopSendingFrame(frame)) {
3441 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3442 // Returning true since there was no parsing error.
3443 return true;
3444 }
3445 break;
3446 }
3447 case IETF_ACK_RECEIVE_TIMESTAMPS:
3448 if (!process_timestamps_) {
3449 set_detailed_error("Unsupported frame type.");
3450 QUIC_DLOG(WARNING)
3451 << ENDPOINT << "IETF_ACK_RECEIVE_TIMESTAMPS not supported";
3452 return RaiseError(QUIC_INVALID_FRAME_DATA);
3453 }
3454 ABSL_FALLTHROUGH_INTENDED;
3455 case IETF_ACK_ECN:
3456 case IETF_ACK: {
3457 QuicAckFrame frame;
3458 if (!ProcessIetfAckFrame(reader, frame_type, &frame)) {
3459 return RaiseError(QUIC_INVALID_ACK_DATA);
3460 }
3461 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF ACK frame " << frame;
3462 break;
3463 }
3464 case IETF_PATH_CHALLENGE: {
3465 QuicPathChallengeFrame frame;
3466 if (!ProcessPathChallengeFrame(reader, &frame)) {
3467 return RaiseError(QUIC_INVALID_PATH_CHALLENGE_DATA);
3468 }
3469 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF path challenge frame "
3470 << frame;
3471 if (!visitor_->OnPathChallengeFrame(frame)) {
3472 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3473 // Returning true since there was no parsing error.
3474 return true;
3475 }
3476 break;
3477 }
3478 case IETF_PATH_RESPONSE: {
3479 QuicPathResponseFrame frame;
3480 if (!ProcessPathResponseFrame(reader, &frame)) {
3481 return RaiseError(QUIC_INVALID_PATH_RESPONSE_DATA);
3482 }
3483 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF path response frame "
3484 << frame;
3485 if (!visitor_->OnPathResponseFrame(frame)) {
3486 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3487 // Returning true since there was no parsing error.
3488 return true;
3489 }
3490 break;
3491 }
3492 case IETF_EXTENSION_MESSAGE_NO_LENGTH_V99:
3493 ABSL_FALLTHROUGH_INTENDED;
3494 case IETF_EXTENSION_MESSAGE_V99: {
3495 QuicMessageFrame message_frame;
3496 if (!ProcessMessageFrame(
3497 reader, frame_type == IETF_EXTENSION_MESSAGE_NO_LENGTH_V99,
3498 &message_frame)) {
3499 return RaiseError(QUIC_INVALID_MESSAGE_DATA);
3500 }
3501 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF message frame "
3502 << message_frame;
3503 if (!visitor_->OnMessageFrame(message_frame)) {
3504 QUIC_DVLOG(1) << ENDPOINT
3505 << "Visitor asked to stop further processing.";
3506 // Returning true since there was no parsing error.
3507 return true;
3508 }
3509 break;
3510 }
3511 case IETF_CRYPTO: {
3512 QuicCryptoFrame frame;
3513 if (!ProcessCryptoFrame(reader, GetEncryptionLevel(header), &frame)) {
3514 return RaiseError(QUIC_INVALID_FRAME_DATA);
3515 }
3516 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF crypto frame " << frame;
3517 if (!visitor_->OnCryptoFrame(frame)) {
3518 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3519 // Returning true since there was no parsing error.
3520 return true;
3521 }
3522 break;
3523 }
3524 case IETF_HANDSHAKE_DONE: {
3525 // HANDSHAKE_DONE has no payload.
3526 QuicHandshakeDoneFrame handshake_done_frame;
3527 if (!visitor_->OnHandshakeDoneFrame(handshake_done_frame)) {
3528 QUIC_DVLOG(1) << ENDPOINT
3529 << "Visitor asked to stop further processing.";
3530 // Returning true since there was no parsing error.
3531 return true;
3532 }
3533 QUIC_DVLOG(2) << ENDPOINT << "Processing handshake done frame "
3534 << handshake_done_frame;
3535 break;
3536 }
3537 case IETF_ACK_FREQUENCY: {
3538 QuicAckFrequencyFrame frame;
3539 if (!ProcessAckFrequencyFrame(reader, &frame)) {
3540 return RaiseError(QUIC_INVALID_FRAME_DATA);
3541 }
3542 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF ack frequency frame "
3543 << frame;
3544 if (!visitor_->OnAckFrequencyFrame(frame)) {
3545 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3546 // Returning true since there was no parsing error.
3547 return true;
3548 }
3549 break;
3550 }
3551 default:
3552 set_detailed_error("Illegal frame type.");
3553 QUIC_DLOG(WARNING)
3554 << ENDPOINT
3555 << "Illegal frame type: " << static_cast<int>(frame_type);
3556 return RaiseError(QUIC_INVALID_FRAME_DATA);
3557 }
3558 }
3559 }
3560 return true;
3561 }
3562
3563 namespace {
3564 // Create a mask that sets the last |num_bits| to 1 and the rest to 0.
GetMaskFromNumBits(uint8_t num_bits)3565 inline uint8_t GetMaskFromNumBits(uint8_t num_bits) {
3566 return (1u << num_bits) - 1;
3567 }
3568
3569 // Extract |num_bits| from |flags| offset by |offset|.
ExtractBits(uint8_t flags,uint8_t num_bits,uint8_t offset)3570 uint8_t ExtractBits(uint8_t flags, uint8_t num_bits, uint8_t offset) {
3571 return (flags >> offset) & GetMaskFromNumBits(num_bits);
3572 }
3573
3574 // Extract the bit at position |offset| from |flags| as a bool.
ExtractBit(uint8_t flags,uint8_t offset)3575 bool ExtractBit(uint8_t flags, uint8_t offset) {
3576 return ((flags >> offset) & GetMaskFromNumBits(1)) != 0;
3577 }
3578
3579 // Set |num_bits|, offset by |offset| to |val| in |flags|.
SetBits(uint8_t * flags,uint8_t val,uint8_t num_bits,uint8_t offset)3580 void SetBits(uint8_t* flags, uint8_t val, uint8_t num_bits, uint8_t offset) {
3581 QUICHE_DCHECK_LE(val, GetMaskFromNumBits(num_bits));
3582 *flags |= val << offset;
3583 }
3584
3585 // Set the bit at position |offset| to |val| in |flags|.
SetBit(uint8_t * flags,bool val,uint8_t offset)3586 void SetBit(uint8_t* flags, bool val, uint8_t offset) {
3587 SetBits(flags, val ? 1 : 0, 1, offset);
3588 }
3589 } // namespace
3590
ProcessStreamFrame(QuicDataReader * reader,uint8_t frame_type,QuicStreamFrame * frame)3591 bool QuicFramer::ProcessStreamFrame(QuicDataReader* reader, uint8_t frame_type,
3592 QuicStreamFrame* frame) {
3593 uint8_t stream_flags = frame_type;
3594
3595 uint8_t stream_id_length = 0;
3596 uint8_t offset_length = 4;
3597 bool has_data_length = true;
3598 stream_flags &= ~kQuicFrameTypeStreamMask;
3599
3600 // Read from right to left: StreamID, Offset, Data Length, Fin.
3601 stream_id_length = (stream_flags & kQuicStreamIDLengthMask) + 1;
3602 stream_flags >>= kQuicStreamIdShift;
3603
3604 offset_length = (stream_flags & kQuicStreamOffsetMask);
3605 // There is no encoding for 1 byte, only 0 and 2 through 8.
3606 if (offset_length > 0) {
3607 offset_length += 1;
3608 }
3609 stream_flags >>= kQuicStreamShift;
3610
3611 has_data_length =
3612 (stream_flags & kQuicStreamDataLengthMask) == kQuicStreamDataLengthMask;
3613 stream_flags >>= kQuicStreamDataLengthShift;
3614
3615 frame->fin = (stream_flags & kQuicStreamFinMask) == kQuicStreamFinShift;
3616
3617 uint64_t stream_id;
3618 if (!reader->ReadBytesToUInt64(stream_id_length, &stream_id)) {
3619 set_detailed_error("Unable to read stream_id.");
3620 return false;
3621 }
3622 frame->stream_id = static_cast<QuicStreamId>(stream_id);
3623
3624 if (!reader->ReadBytesToUInt64(offset_length, &frame->offset)) {
3625 set_detailed_error("Unable to read offset.");
3626 return false;
3627 }
3628
3629 // TODO(ianswett): Don't use absl::string_view as an intermediary.
3630 absl::string_view data;
3631 if (has_data_length) {
3632 if (!reader->ReadStringPiece16(&data)) {
3633 set_detailed_error("Unable to read frame data.");
3634 return false;
3635 }
3636 } else {
3637 if (!reader->ReadStringPiece(&data, reader->BytesRemaining())) {
3638 set_detailed_error("Unable to read frame data.");
3639 return false;
3640 }
3641 }
3642 frame->data_buffer = data.data();
3643 frame->data_length = static_cast<uint16_t>(data.length());
3644
3645 return true;
3646 }
3647
ProcessIetfStreamFrame(QuicDataReader * reader,uint8_t frame_type,QuicStreamFrame * frame)3648 bool QuicFramer::ProcessIetfStreamFrame(QuicDataReader* reader,
3649 uint8_t frame_type,
3650 QuicStreamFrame* frame) {
3651 // Read stream id from the frame. It's always present.
3652 if (!ReadUint32FromVarint62(reader, IETF_STREAM, &frame->stream_id)) {
3653 return false;
3654 }
3655
3656 // If we have a data offset, read it. If not, set to 0.
3657 if (frame_type & IETF_STREAM_FRAME_OFF_BIT) {
3658 if (!reader->ReadVarInt62(&frame->offset)) {
3659 set_detailed_error("Unable to read stream data offset.");
3660 return false;
3661 }
3662 } else {
3663 // no offset in the frame, ensure it's 0 in the Frame.
3664 frame->offset = 0;
3665 }
3666
3667 // If we have a data length, read it. If not, set to 0.
3668 if (frame_type & IETF_STREAM_FRAME_LEN_BIT) {
3669 uint64_t length;
3670 if (!reader->ReadVarInt62(&length)) {
3671 set_detailed_error("Unable to read stream data length.");
3672 return false;
3673 }
3674 if (length > std::numeric_limits<decltype(frame->data_length)>::max()) {
3675 set_detailed_error("Stream data length is too large.");
3676 return false;
3677 }
3678 frame->data_length = length;
3679 } else {
3680 // no length in the frame, it is the number of bytes remaining in the
3681 // packet.
3682 frame->data_length = reader->BytesRemaining();
3683 }
3684
3685 if (frame_type & IETF_STREAM_FRAME_FIN_BIT) {
3686 frame->fin = true;
3687 } else {
3688 frame->fin = false;
3689 }
3690
3691 // TODO(ianswett): Don't use absl::string_view as an intermediary.
3692 absl::string_view data;
3693 if (!reader->ReadStringPiece(&data, frame->data_length)) {
3694 set_detailed_error("Unable to read frame data.");
3695 return false;
3696 }
3697 frame->data_buffer = data.data();
3698 QUICHE_DCHECK_EQ(frame->data_length, data.length());
3699
3700 return true;
3701 }
3702
ProcessCryptoFrame(QuicDataReader * reader,EncryptionLevel encryption_level,QuicCryptoFrame * frame)3703 bool QuicFramer::ProcessCryptoFrame(QuicDataReader* reader,
3704 EncryptionLevel encryption_level,
3705 QuicCryptoFrame* frame) {
3706 frame->level = encryption_level;
3707 if (!reader->ReadVarInt62(&frame->offset)) {
3708 set_detailed_error("Unable to read crypto data offset.");
3709 return false;
3710 }
3711 uint64_t len;
3712 if (!reader->ReadVarInt62(&len) ||
3713 len > std::numeric_limits<QuicPacketLength>::max()) {
3714 set_detailed_error("Invalid data length.");
3715 return false;
3716 }
3717 frame->data_length = len;
3718
3719 // TODO(ianswett): Don't use absl::string_view as an intermediary.
3720 absl::string_view data;
3721 if (!reader->ReadStringPiece(&data, frame->data_length)) {
3722 set_detailed_error("Unable to read frame data.");
3723 return false;
3724 }
3725 frame->data_buffer = data.data();
3726 return true;
3727 }
3728
ProcessAckFrequencyFrame(QuicDataReader * reader,QuicAckFrequencyFrame * frame)3729 bool QuicFramer::ProcessAckFrequencyFrame(QuicDataReader* reader,
3730 QuicAckFrequencyFrame* frame) {
3731 if (!reader->ReadVarInt62(&frame->sequence_number)) {
3732 set_detailed_error("Unable to read sequence number.");
3733 return false;
3734 }
3735
3736 if (!reader->ReadVarInt62(&frame->packet_tolerance)) {
3737 set_detailed_error("Unable to read packet tolerance.");
3738 return false;
3739 }
3740 if (frame->packet_tolerance == 0) {
3741 set_detailed_error("Invalid packet tolerance.");
3742 return false;
3743 }
3744 uint64_t max_ack_delay_us;
3745 if (!reader->ReadVarInt62(&max_ack_delay_us)) {
3746 set_detailed_error("Unable to read max_ack_delay_us.");
3747 return false;
3748 }
3749 constexpr uint64_t kMaxAckDelayUsBound = 1u << 24;
3750 if (max_ack_delay_us > kMaxAckDelayUsBound) {
3751 set_detailed_error("Invalid max_ack_delay_us.");
3752 return false;
3753 }
3754 frame->max_ack_delay = QuicTime::Delta::FromMicroseconds(max_ack_delay_us);
3755
3756 uint8_t ignore_order;
3757 if (!reader->ReadUInt8(&ignore_order)) {
3758 set_detailed_error("Unable to read ignore_order.");
3759 return false;
3760 }
3761 if (ignore_order > 1) {
3762 set_detailed_error("Invalid ignore_order.");
3763 return false;
3764 }
3765 frame->ignore_order = ignore_order;
3766
3767 return true;
3768 }
3769
ProcessAckFrame(QuicDataReader * reader,uint8_t frame_type)3770 bool QuicFramer::ProcessAckFrame(QuicDataReader* reader, uint8_t frame_type) {
3771 const bool has_ack_blocks =
3772 ExtractBit(frame_type, kQuicHasMultipleAckBlocksOffset);
3773 uint8_t num_ack_blocks = 0;
3774 uint8_t num_received_packets = 0;
3775
3776 // Determine the two lengths from the frame type: largest acked length,
3777 // ack block length.
3778 const QuicPacketNumberLength ack_block_length =
3779 ReadAckPacketNumberLength(ExtractBits(
3780 frame_type, kQuicSequenceNumberLengthNumBits, kActBlockLengthOffset));
3781 const QuicPacketNumberLength largest_acked_length =
3782 ReadAckPacketNumberLength(ExtractBits(
3783 frame_type, kQuicSequenceNumberLengthNumBits, kLargestAckedOffset));
3784
3785 uint64_t largest_acked;
3786 if (!reader->ReadBytesToUInt64(largest_acked_length, &largest_acked)) {
3787 set_detailed_error("Unable to read largest acked.");
3788 return false;
3789 }
3790
3791 if (largest_acked < first_sending_packet_number_.ToUint64()) {
3792 // Connection always sends packet starting from kFirstSendingPacketNumber >
3793 // 0, peer has observed an unsent packet.
3794 set_detailed_error("Largest acked is 0.");
3795 return false;
3796 }
3797
3798 uint64_t ack_delay_time_us;
3799 if (!reader->ReadUFloat16(&ack_delay_time_us)) {
3800 set_detailed_error("Unable to read ack delay time.");
3801 return false;
3802 }
3803
3804 if (!visitor_->OnAckFrameStart(
3805 QuicPacketNumber(largest_acked),
3806 ack_delay_time_us == kUFloat16MaxValue
3807 ? QuicTime::Delta::Infinite()
3808 : QuicTime::Delta::FromMicroseconds(ack_delay_time_us))) {
3809 // The visitor suppresses further processing of the packet. Although this is
3810 // not a parsing error, returns false as this is in middle of processing an
3811 // ack frame,
3812 set_detailed_error("Visitor suppresses further processing of ack frame.");
3813 return false;
3814 }
3815
3816 if (has_ack_blocks && !reader->ReadUInt8(&num_ack_blocks)) {
3817 set_detailed_error("Unable to read num of ack blocks.");
3818 return false;
3819 }
3820
3821 uint64_t first_block_length;
3822 if (!reader->ReadBytesToUInt64(ack_block_length, &first_block_length)) {
3823 set_detailed_error("Unable to read first ack block length.");
3824 return false;
3825 }
3826
3827 if (first_block_length == 0) {
3828 set_detailed_error("First block length is zero.");
3829 return false;
3830 }
3831 bool first_ack_block_underflow = first_block_length > largest_acked + 1;
3832 if (first_block_length + first_sending_packet_number_.ToUint64() >
3833 largest_acked + 1) {
3834 first_ack_block_underflow = true;
3835 }
3836 if (first_ack_block_underflow) {
3837 set_detailed_error(absl::StrCat("Underflow with first ack block length ",
3838 first_block_length, " largest acked is ",
3839 largest_acked, ".")
3840 .c_str());
3841 return false;
3842 }
3843
3844 uint64_t first_received = largest_acked + 1 - first_block_length;
3845 if (!visitor_->OnAckRange(QuicPacketNumber(first_received),
3846 QuicPacketNumber(largest_acked + 1))) {
3847 // The visitor suppresses further processing of the packet. Although
3848 // this is not a parsing error, returns false as this is in middle
3849 // of processing an ack frame,
3850 set_detailed_error("Visitor suppresses further processing of ack frame.");
3851 return false;
3852 }
3853
3854 if (num_ack_blocks > 0) {
3855 for (size_t i = 0; i < num_ack_blocks; ++i) {
3856 uint8_t gap = 0;
3857 if (!reader->ReadUInt8(&gap)) {
3858 set_detailed_error("Unable to read gap to next ack block.");
3859 return false;
3860 }
3861 uint64_t current_block_length;
3862 if (!reader->ReadBytesToUInt64(ack_block_length, ¤t_block_length)) {
3863 set_detailed_error("Unable to ack block length.");
3864 return false;
3865 }
3866 bool ack_block_underflow = first_received < gap + current_block_length;
3867 if (first_received < gap + current_block_length +
3868 first_sending_packet_number_.ToUint64()) {
3869 ack_block_underflow = true;
3870 }
3871 if (ack_block_underflow) {
3872 set_detailed_error(absl::StrCat("Underflow with ack block length ",
3873 current_block_length,
3874 ", end of block is ",
3875 first_received - gap, ".")
3876 .c_str());
3877 return false;
3878 }
3879
3880 first_received -= (gap + current_block_length);
3881 if (current_block_length > 0) {
3882 if (!visitor_->OnAckRange(
3883 QuicPacketNumber(first_received),
3884 QuicPacketNumber(first_received) + current_block_length)) {
3885 // The visitor suppresses further processing of the packet. Although
3886 // this is not a parsing error, returns false as this is in middle
3887 // of processing an ack frame,
3888 set_detailed_error(
3889 "Visitor suppresses further processing of ack frame.");
3890 return false;
3891 }
3892 }
3893 }
3894 }
3895
3896 if (!reader->ReadUInt8(&num_received_packets)) {
3897 set_detailed_error("Unable to read num received packets.");
3898 return false;
3899 }
3900
3901 if (!ProcessTimestampsInAckFrame(num_received_packets,
3902 QuicPacketNumber(largest_acked), reader)) {
3903 return false;
3904 }
3905
3906 // Done processing the ACK frame.
3907 absl::optional<QuicEcnCounts> ecn_counts = absl::nullopt;
3908 if (!visitor_->OnAckFrameEnd(QuicPacketNumber(first_received), ecn_counts)) {
3909 set_detailed_error(
3910 "Error occurs when visitor finishes processing the ACK frame.");
3911 return false;
3912 }
3913
3914 return true;
3915 }
3916
ProcessTimestampsInAckFrame(uint8_t num_received_packets,QuicPacketNumber largest_acked,QuicDataReader * reader)3917 bool QuicFramer::ProcessTimestampsInAckFrame(uint8_t num_received_packets,
3918 QuicPacketNumber largest_acked,
3919 QuicDataReader* reader) {
3920 if (num_received_packets == 0) {
3921 return true;
3922 }
3923 uint8_t delta_from_largest_observed;
3924 if (!reader->ReadUInt8(&delta_from_largest_observed)) {
3925 set_detailed_error("Unable to read sequence delta in received packets.");
3926 return false;
3927 }
3928
3929 if (largest_acked.ToUint64() <= delta_from_largest_observed) {
3930 set_detailed_error(
3931 absl::StrCat("delta_from_largest_observed too high: ",
3932 delta_from_largest_observed,
3933 ", largest_acked: ", largest_acked.ToUint64())
3934 .c_str());
3935 return false;
3936 }
3937
3938 // Time delta from the framer creation.
3939 uint32_t time_delta_us;
3940 if (!reader->ReadUInt32(&time_delta_us)) {
3941 set_detailed_error("Unable to read time delta in received packets.");
3942 return false;
3943 }
3944
3945 QuicPacketNumber seq_num = largest_acked - delta_from_largest_observed;
3946 if (process_timestamps_) {
3947 last_timestamp_ = CalculateTimestampFromWire(time_delta_us);
3948
3949 visitor_->OnAckTimestamp(seq_num, creation_time_ + last_timestamp_);
3950 }
3951
3952 for (uint8_t i = 1; i < num_received_packets; ++i) {
3953 if (!reader->ReadUInt8(&delta_from_largest_observed)) {
3954 set_detailed_error("Unable to read sequence delta in received packets.");
3955 return false;
3956 }
3957 if (largest_acked.ToUint64() <= delta_from_largest_observed) {
3958 set_detailed_error(
3959 absl::StrCat("delta_from_largest_observed too high: ",
3960 delta_from_largest_observed,
3961 ", largest_acked: ", largest_acked.ToUint64())
3962 .c_str());
3963 return false;
3964 }
3965 seq_num = largest_acked - delta_from_largest_observed;
3966
3967 // Time delta from the previous timestamp.
3968 uint64_t incremental_time_delta_us;
3969 if (!reader->ReadUFloat16(&incremental_time_delta_us)) {
3970 set_detailed_error(
3971 "Unable to read incremental time delta in received packets.");
3972 return false;
3973 }
3974
3975 if (process_timestamps_) {
3976 last_timestamp_ = last_timestamp_ + QuicTime::Delta::FromMicroseconds(
3977 incremental_time_delta_us);
3978 visitor_->OnAckTimestamp(seq_num, creation_time_ + last_timestamp_);
3979 }
3980 }
3981 return true;
3982 }
3983
ProcessIetfAckFrame(QuicDataReader * reader,uint64_t frame_type,QuicAckFrame * ack_frame)3984 bool QuicFramer::ProcessIetfAckFrame(QuicDataReader* reader,
3985 uint64_t frame_type,
3986 QuicAckFrame* ack_frame) {
3987 uint64_t largest_acked;
3988 if (!reader->ReadVarInt62(&largest_acked)) {
3989 set_detailed_error("Unable to read largest acked.");
3990 return false;
3991 }
3992 if (largest_acked < first_sending_packet_number_.ToUint64()) {
3993 // Connection always sends packet starting from kFirstSendingPacketNumber >
3994 // 0, peer has observed an unsent packet.
3995 set_detailed_error("Largest acked is 0.");
3996 return false;
3997 }
3998 ack_frame->largest_acked = static_cast<QuicPacketNumber>(largest_acked);
3999 uint64_t ack_delay_time_in_us;
4000 if (!reader->ReadVarInt62(&ack_delay_time_in_us)) {
4001 set_detailed_error("Unable to read ack delay time.");
4002 return false;
4003 }
4004
4005 if (ack_delay_time_in_us >=
4006 (quiche::kVarInt62MaxValue >> peer_ack_delay_exponent_)) {
4007 ack_frame->ack_delay_time = QuicTime::Delta::Infinite();
4008 } else {
4009 ack_delay_time_in_us = (ack_delay_time_in_us << peer_ack_delay_exponent_);
4010 ack_frame->ack_delay_time =
4011 QuicTime::Delta::FromMicroseconds(ack_delay_time_in_us);
4012 }
4013 if (!visitor_->OnAckFrameStart(QuicPacketNumber(largest_acked),
4014 ack_frame->ack_delay_time)) {
4015 // The visitor suppresses further processing of the packet. Although this is
4016 // not a parsing error, returns false as this is in middle of processing an
4017 // ACK frame.
4018 set_detailed_error("Visitor suppresses further processing of ACK frame.");
4019 return false;
4020 }
4021
4022 // Get number of ACK blocks from the packet.
4023 uint64_t ack_block_count;
4024 if (!reader->ReadVarInt62(&ack_block_count)) {
4025 set_detailed_error("Unable to read ack block count.");
4026 return false;
4027 }
4028 // There always is a first ACK block, which is the (number of packets being
4029 // acked)-1, up to and including the packet at largest_acked. Therefore if the
4030 // value is 0, then only largest is acked. If it is 1, then largest-1,
4031 // largest] are acked, etc
4032 uint64_t ack_block_value;
4033 if (!reader->ReadVarInt62(&ack_block_value)) {
4034 set_detailed_error("Unable to read first ack block length.");
4035 return false;
4036 }
4037 // Calculate the packets being acked in the first block.
4038 // +1 because AddRange implementation requires [low,high)
4039 uint64_t block_high = largest_acked + 1;
4040 uint64_t block_low = largest_acked - ack_block_value;
4041
4042 // ack_block_value is the number of packets preceding the
4043 // largest_acked packet which are in the block being acked. Thus,
4044 // its maximum value is largest_acked-1. Test this, reporting an
4045 // error if the value is wrong.
4046 if (ack_block_value + first_sending_packet_number_.ToUint64() >
4047 largest_acked) {
4048 set_detailed_error(absl::StrCat("Underflow with first ack block length ",
4049 ack_block_value + 1, " largest acked is ",
4050 largest_acked, ".")
4051 .c_str());
4052 return false;
4053 }
4054
4055 if (!visitor_->OnAckRange(QuicPacketNumber(block_low),
4056 QuicPacketNumber(block_high))) {
4057 // The visitor suppresses further processing of the packet. Although
4058 // this is not a parsing error, returns false as this is in middle
4059 // of processing an ACK frame.
4060 set_detailed_error("Visitor suppresses further processing of ACK frame.");
4061 return false;
4062 }
4063
4064 while (ack_block_count != 0) {
4065 uint64_t gap_block_value;
4066 // Get the sizes of the gap and ack blocks,
4067 if (!reader->ReadVarInt62(&gap_block_value)) {
4068 set_detailed_error("Unable to read gap block value.");
4069 return false;
4070 }
4071 // It's an error if the gap is larger than the space from packet
4072 // number 0 to the start of the block that's just been acked, PLUS
4073 // there must be space for at least 1 packet to be acked. For
4074 // example, if block_low is 10 and gap_block_value is 9, it means
4075 // the gap block is 10 packets long, leaving no room for a packet
4076 // to be acked. Thus, gap_block_value+2 can not be larger than
4077 // block_low.
4078 // The test is written this way to detect wrap-arounds.
4079 if ((gap_block_value + 2) > block_low) {
4080 set_detailed_error(
4081 absl::StrCat("Underflow with gap block length ", gap_block_value + 1,
4082 " previous ack block start is ", block_low, ".")
4083 .c_str());
4084 return false;
4085 }
4086
4087 // Adjust block_high to be the top of the next ack block.
4088 // There is a gap of |gap_block_value| packets between the bottom
4089 // of ack block N and top of block N+1. Note that gap_block_value
4090 // is he size of the gap minus 1 (per the QUIC protocol), and
4091 // block_high is the packet number of the first packet of the gap
4092 // (per the implementation of OnAckRange/AddAckRange, below).
4093 block_high = block_low - 1 - gap_block_value;
4094
4095 if (!reader->ReadVarInt62(&ack_block_value)) {
4096 set_detailed_error("Unable to read ack block value.");
4097 return false;
4098 }
4099 if (ack_block_value + first_sending_packet_number_.ToUint64() >
4100 (block_high - 1)) {
4101 set_detailed_error(
4102 absl::StrCat("Underflow with ack block length ", ack_block_value + 1,
4103 " latest ack block end is ", block_high - 1, ".")
4104 .c_str());
4105 return false;
4106 }
4107 // Calculate the low end of the new nth ack block. The +1 is
4108 // because the encoded value is the blocksize-1.
4109 block_low = block_high - 1 - ack_block_value;
4110 if (!visitor_->OnAckRange(QuicPacketNumber(block_low),
4111 QuicPacketNumber(block_high))) {
4112 // The visitor suppresses further processing of the packet. Although
4113 // this is not a parsing error, returns false as this is in middle
4114 // of processing an ACK frame.
4115 set_detailed_error("Visitor suppresses further processing of ACK frame.");
4116 return false;
4117 }
4118
4119 // Another one done.
4120 ack_block_count--;
4121 }
4122
4123 QUICHE_DCHECK(!ack_frame->ecn_counters.has_value());
4124 if (frame_type == IETF_ACK_RECEIVE_TIMESTAMPS) {
4125 QUICHE_DCHECK(process_timestamps_);
4126 if (!ProcessIetfTimestampsInAckFrame(ack_frame->largest_acked, reader)) {
4127 return false;
4128 }
4129 } else if (frame_type == IETF_ACK_ECN) {
4130 ack_frame->ecn_counters = QuicEcnCounts();
4131 if (!reader->ReadVarInt62(&ack_frame->ecn_counters->ect0)) {
4132 set_detailed_error("Unable to read ack ect_0_count.");
4133 return false;
4134 }
4135 if (!reader->ReadVarInt62(&ack_frame->ecn_counters->ect1)) {
4136 set_detailed_error("Unable to read ack ect_1_count.");
4137 return false;
4138 }
4139 if (!reader->ReadVarInt62(&ack_frame->ecn_counters->ce)) {
4140 set_detailed_error("Unable to read ack ecn_ce_count.");
4141 return false;
4142 }
4143 if (GetQuicRestartFlag(quic_receive_ecn)) {
4144 QUIC_RESTART_FLAG_COUNT_N(quic_receive_ecn, 2, 3);
4145 }
4146 }
4147
4148 if (!visitor_->OnAckFrameEnd(QuicPacketNumber(block_low),
4149 ack_frame->ecn_counters)) {
4150 set_detailed_error(
4151 "Error occurs when visitor finishes processing the ACK frame.");
4152 return false;
4153 }
4154
4155 return true;
4156 }
4157
ProcessIetfTimestampsInAckFrame(QuicPacketNumber largest_acked,QuicDataReader * reader)4158 bool QuicFramer::ProcessIetfTimestampsInAckFrame(QuicPacketNumber largest_acked,
4159 QuicDataReader* reader) {
4160 uint64_t timestamp_range_count;
4161 if (!reader->ReadVarInt62(×tamp_range_count)) {
4162 set_detailed_error("Unable to read receive timestamp range count.");
4163 return false;
4164 }
4165 if (timestamp_range_count == 0) {
4166 return true;
4167 }
4168
4169 QuicPacketNumber packet_number = largest_acked;
4170
4171 // Iterate through all timestamp ranges, each of which represents a block of
4172 // contiguous packets for which receive timestamps are being reported. Each
4173 // range is of the form:
4174 //
4175 // Timestamp Range {
4176 // Gap (i),
4177 // Timestamp Delta Count (i),
4178 // Timestamp Delta (i) ...,
4179 // }
4180 for (uint64_t i = 0; i < timestamp_range_count; i++) {
4181 uint64_t gap;
4182 if (!reader->ReadVarInt62(&gap)) {
4183 set_detailed_error("Unable to read receive timestamp gap.");
4184 return false;
4185 }
4186 if (packet_number.ToUint64() < gap) {
4187 set_detailed_error("Receive timestamp gap too high.");
4188 return false;
4189 }
4190 packet_number = packet_number - gap;
4191 uint64_t timestamp_count;
4192 if (!reader->ReadVarInt62(×tamp_count)) {
4193 set_detailed_error("Unable to read receive timestamp count.");
4194 return false;
4195 }
4196 if (packet_number.ToUint64() < timestamp_count) {
4197 set_detailed_error("Receive timestamp count too high.");
4198 return false;
4199 }
4200 for (uint64_t j = 0; j < timestamp_count; j++) {
4201 uint64_t timestamp_delta;
4202 if (!reader->ReadVarInt62(×tamp_delta)) {
4203 set_detailed_error("Unable to read receive timestamp delta.");
4204 return false;
4205 }
4206 // The first timestamp delta is relative to framer creation time; whereas
4207 // subsequent deltas are relative to the previous delta in decreasing
4208 // packet order.
4209 timestamp_delta = timestamp_delta << receive_timestamps_exponent_;
4210 if (i == 0 && j == 0) {
4211 last_timestamp_ = QuicTime::Delta::FromMicroseconds(timestamp_delta);
4212 } else {
4213 last_timestamp_ = last_timestamp_ -
4214 QuicTime::Delta::FromMicroseconds(timestamp_delta);
4215 if (last_timestamp_ < QuicTime::Delta::Zero()) {
4216 set_detailed_error("Receive timestamp delta too high.");
4217 return false;
4218 }
4219 }
4220 visitor_->OnAckTimestamp(packet_number, creation_time_ + last_timestamp_);
4221 packet_number--;
4222 }
4223 packet_number--;
4224 }
4225 return true;
4226 }
4227
ProcessStopWaitingFrame(QuicDataReader * reader,const QuicPacketHeader & header,QuicStopWaitingFrame * stop_waiting)4228 bool QuicFramer::ProcessStopWaitingFrame(QuicDataReader* reader,
4229 const QuicPacketHeader& header,
4230 QuicStopWaitingFrame* stop_waiting) {
4231 uint64_t least_unacked_delta;
4232 if (!reader->ReadBytesToUInt64(header.packet_number_length,
4233 &least_unacked_delta)) {
4234 set_detailed_error("Unable to read least unacked delta.");
4235 return false;
4236 }
4237 if (header.packet_number.ToUint64() <= least_unacked_delta) {
4238 set_detailed_error("Invalid unacked delta.");
4239 return false;
4240 }
4241 stop_waiting->least_unacked = header.packet_number - least_unacked_delta;
4242
4243 return true;
4244 }
4245
ProcessRstStreamFrame(QuicDataReader * reader,QuicRstStreamFrame * frame)4246 bool QuicFramer::ProcessRstStreamFrame(QuicDataReader* reader,
4247 QuicRstStreamFrame* frame) {
4248 if (!reader->ReadUInt32(&frame->stream_id)) {
4249 set_detailed_error("Unable to read stream_id.");
4250 return false;
4251 }
4252
4253 if (!reader->ReadUInt64(&frame->byte_offset)) {
4254 set_detailed_error("Unable to read rst stream sent byte offset.");
4255 return false;
4256 }
4257
4258 uint32_t error_code;
4259 if (!reader->ReadUInt32(&error_code)) {
4260 set_detailed_error("Unable to read rst stream error code.");
4261 return false;
4262 }
4263
4264 if (error_code >= QUIC_STREAM_LAST_ERROR) {
4265 // Ignore invalid stream error code if any.
4266 error_code = QUIC_STREAM_LAST_ERROR;
4267 }
4268
4269 frame->error_code = static_cast<QuicRstStreamErrorCode>(error_code);
4270
4271 return true;
4272 }
4273
ProcessConnectionCloseFrame(QuicDataReader * reader,QuicConnectionCloseFrame * frame)4274 bool QuicFramer::ProcessConnectionCloseFrame(QuicDataReader* reader,
4275 QuicConnectionCloseFrame* frame) {
4276 uint32_t error_code;
4277 frame->close_type = GOOGLE_QUIC_CONNECTION_CLOSE;
4278
4279 if (!reader->ReadUInt32(&error_code)) {
4280 set_detailed_error("Unable to read connection close error code.");
4281 return false;
4282 }
4283
4284 // For Google QUIC connection closes, |wire_error_code| and |quic_error_code|
4285 // must have the same value.
4286 frame->wire_error_code = error_code;
4287 frame->quic_error_code = static_cast<QuicErrorCode>(error_code);
4288
4289 absl::string_view error_details;
4290 if (!reader->ReadStringPiece16(&error_details)) {
4291 set_detailed_error("Unable to read connection close error details.");
4292 return false;
4293 }
4294 frame->error_details = std::string(error_details);
4295
4296 return true;
4297 }
4298
ProcessGoAwayFrame(QuicDataReader * reader,QuicGoAwayFrame * frame)4299 bool QuicFramer::ProcessGoAwayFrame(QuicDataReader* reader,
4300 QuicGoAwayFrame* frame) {
4301 uint32_t error_code;
4302 if (!reader->ReadUInt32(&error_code)) {
4303 set_detailed_error("Unable to read go away error code.");
4304 return false;
4305 }
4306
4307 frame->error_code = static_cast<QuicErrorCode>(error_code);
4308
4309 uint32_t stream_id;
4310 if (!reader->ReadUInt32(&stream_id)) {
4311 set_detailed_error("Unable to read last good stream id.");
4312 return false;
4313 }
4314 frame->last_good_stream_id = static_cast<QuicStreamId>(stream_id);
4315
4316 absl::string_view reason_phrase;
4317 if (!reader->ReadStringPiece16(&reason_phrase)) {
4318 set_detailed_error("Unable to read goaway reason.");
4319 return false;
4320 }
4321 frame->reason_phrase = std::string(reason_phrase);
4322
4323 return true;
4324 }
4325
ProcessWindowUpdateFrame(QuicDataReader * reader,QuicWindowUpdateFrame * frame)4326 bool QuicFramer::ProcessWindowUpdateFrame(QuicDataReader* reader,
4327 QuicWindowUpdateFrame* frame) {
4328 if (!reader->ReadUInt32(&frame->stream_id)) {
4329 set_detailed_error("Unable to read stream_id.");
4330 return false;
4331 }
4332
4333 if (!reader->ReadUInt64(&frame->max_data)) {
4334 set_detailed_error("Unable to read window byte_offset.");
4335 return false;
4336 }
4337
4338 return true;
4339 }
4340
ProcessBlockedFrame(QuicDataReader * reader,QuicBlockedFrame * frame)4341 bool QuicFramer::ProcessBlockedFrame(QuicDataReader* reader,
4342 QuicBlockedFrame* frame) {
4343 QUICHE_DCHECK(!VersionHasIetfQuicFrames(version_.transport_version))
4344 << "Attempt to process non-IETF QUIC frames in an IETF QUIC version.";
4345
4346 if (!reader->ReadUInt32(&frame->stream_id)) {
4347 set_detailed_error("Unable to read stream_id.");
4348 return false;
4349 }
4350
4351 return true;
4352 }
4353
ProcessPaddingFrame(QuicDataReader * reader,QuicPaddingFrame * frame)4354 void QuicFramer::ProcessPaddingFrame(QuicDataReader* reader,
4355 QuicPaddingFrame* frame) {
4356 // Type byte has been read.
4357 frame->num_padding_bytes = 1;
4358 uint8_t next_byte;
4359 while (!reader->IsDoneReading() && reader->PeekByte() == 0x00) {
4360 reader->ReadBytes(&next_byte, 1);
4361 QUICHE_DCHECK_EQ(0x00, next_byte);
4362 ++frame->num_padding_bytes;
4363 }
4364 }
4365
ProcessMessageFrame(QuicDataReader * reader,bool no_message_length,QuicMessageFrame * frame)4366 bool QuicFramer::ProcessMessageFrame(QuicDataReader* reader,
4367 bool no_message_length,
4368 QuicMessageFrame* frame) {
4369 if (no_message_length) {
4370 absl::string_view remaining(reader->ReadRemainingPayload());
4371 frame->data = remaining.data();
4372 frame->message_length = remaining.length();
4373 return true;
4374 }
4375
4376 uint64_t message_length;
4377 if (!reader->ReadVarInt62(&message_length)) {
4378 set_detailed_error("Unable to read message length");
4379 return false;
4380 }
4381
4382 absl::string_view message_piece;
4383 if (!reader->ReadStringPiece(&message_piece, message_length)) {
4384 set_detailed_error("Unable to read message data");
4385 return false;
4386 }
4387
4388 frame->data = message_piece.data();
4389 frame->message_length = message_length;
4390
4391 return true;
4392 }
4393
4394 // static
GetAssociatedDataFromEncryptedPacket(QuicTransportVersion version,const QuicEncryptedPacket & encrypted,uint8_t destination_connection_id_length,uint8_t source_connection_id_length,bool includes_version,bool includes_diversification_nonce,QuicPacketNumberLength packet_number_length,quiche::QuicheVariableLengthIntegerLength retry_token_length_length,uint64_t retry_token_length,quiche::QuicheVariableLengthIntegerLength length_length)4395 absl::string_view QuicFramer::GetAssociatedDataFromEncryptedPacket(
4396 QuicTransportVersion version, const QuicEncryptedPacket& encrypted,
4397 uint8_t destination_connection_id_length,
4398 uint8_t source_connection_id_length, bool includes_version,
4399 bool includes_diversification_nonce,
4400 QuicPacketNumberLength packet_number_length,
4401 quiche::QuicheVariableLengthIntegerLength retry_token_length_length,
4402 uint64_t retry_token_length,
4403 quiche::QuicheVariableLengthIntegerLength length_length) {
4404 // TODO(ianswett): This is identical to QuicData::AssociatedData.
4405 return absl::string_view(
4406 encrypted.data(),
4407 GetStartOfEncryptedData(version, destination_connection_id_length,
4408 source_connection_id_length, includes_version,
4409 includes_diversification_nonce,
4410 packet_number_length, retry_token_length_length,
4411 retry_token_length, length_length));
4412 }
4413
SetDecrypter(EncryptionLevel level,std::unique_ptr<QuicDecrypter> decrypter)4414 void QuicFramer::SetDecrypter(EncryptionLevel level,
4415 std::unique_ptr<QuicDecrypter> decrypter) {
4416 QUICHE_DCHECK_GE(level, decrypter_level_);
4417 QUICHE_DCHECK(!version_.KnowsWhichDecrypterToUse());
4418 QUIC_DVLOG(1) << ENDPOINT << "Setting decrypter from level "
4419 << decrypter_level_ << " to " << level;
4420 decrypter_[decrypter_level_] = nullptr;
4421 decrypter_[level] = std::move(decrypter);
4422 decrypter_level_ = level;
4423 }
4424
SetAlternativeDecrypter(EncryptionLevel level,std::unique_ptr<QuicDecrypter> decrypter,bool latch_once_used)4425 void QuicFramer::SetAlternativeDecrypter(
4426 EncryptionLevel level, std::unique_ptr<QuicDecrypter> decrypter,
4427 bool latch_once_used) {
4428 QUICHE_DCHECK_NE(level, decrypter_level_);
4429 QUICHE_DCHECK(!version_.KnowsWhichDecrypterToUse());
4430 QUIC_DVLOG(1) << ENDPOINT << "Setting alternative decrypter from level "
4431 << alternative_decrypter_level_ << " to " << level;
4432 if (alternative_decrypter_level_ != NUM_ENCRYPTION_LEVELS) {
4433 decrypter_[alternative_decrypter_level_] = nullptr;
4434 }
4435 decrypter_[level] = std::move(decrypter);
4436 alternative_decrypter_level_ = level;
4437 alternative_decrypter_latch_ = latch_once_used;
4438 }
4439
InstallDecrypter(EncryptionLevel level,std::unique_ptr<QuicDecrypter> decrypter)4440 void QuicFramer::InstallDecrypter(EncryptionLevel level,
4441 std::unique_ptr<QuicDecrypter> decrypter) {
4442 QUICHE_DCHECK(version_.KnowsWhichDecrypterToUse());
4443 QUIC_DVLOG(1) << ENDPOINT << "Installing decrypter at level " << level;
4444 decrypter_[level] = std::move(decrypter);
4445 }
4446
RemoveDecrypter(EncryptionLevel level)4447 void QuicFramer::RemoveDecrypter(EncryptionLevel level) {
4448 QUICHE_DCHECK(version_.KnowsWhichDecrypterToUse());
4449 QUIC_DVLOG(1) << ENDPOINT << "Removing decrypter at level " << level;
4450 decrypter_[level] = nullptr;
4451 }
4452
SetKeyUpdateSupportForConnection(bool enabled)4453 void QuicFramer::SetKeyUpdateSupportForConnection(bool enabled) {
4454 QUIC_DVLOG(1) << ENDPOINT << "SetKeyUpdateSupportForConnection: " << enabled;
4455 support_key_update_for_connection_ = enabled;
4456 }
4457
DiscardPreviousOneRttKeys()4458 void QuicFramer::DiscardPreviousOneRttKeys() {
4459 QUICHE_DCHECK(support_key_update_for_connection_);
4460 QUIC_DVLOG(1) << ENDPOINT << "Discarding previous set of 1-RTT keys";
4461 previous_decrypter_ = nullptr;
4462 }
4463
DoKeyUpdate(KeyUpdateReason reason)4464 bool QuicFramer::DoKeyUpdate(KeyUpdateReason reason) {
4465 QUICHE_DCHECK(support_key_update_for_connection_);
4466 if (!next_decrypter_) {
4467 // If key update is locally initiated, next decrypter might not be created
4468 // yet.
4469 next_decrypter_ = visitor_->AdvanceKeysAndCreateCurrentOneRttDecrypter();
4470 }
4471 std::unique_ptr<QuicEncrypter> next_encrypter =
4472 visitor_->CreateCurrentOneRttEncrypter();
4473 if (!next_decrypter_ || !next_encrypter) {
4474 QUIC_BUG(quic_bug_10850_58) << "Failed to create next crypters";
4475 return false;
4476 }
4477 key_update_performed_ = true;
4478 current_key_phase_bit_ = !current_key_phase_bit_;
4479 QUIC_DLOG(INFO) << ENDPOINT << "DoKeyUpdate: new current_key_phase_bit_="
4480 << current_key_phase_bit_;
4481 current_key_phase_first_received_packet_number_.Clear();
4482 previous_decrypter_ = std::move(decrypter_[ENCRYPTION_FORWARD_SECURE]);
4483 decrypter_[ENCRYPTION_FORWARD_SECURE] = std::move(next_decrypter_);
4484 encrypter_[ENCRYPTION_FORWARD_SECURE] = std::move(next_encrypter);
4485 switch (reason) {
4486 case KeyUpdateReason::kInvalid:
4487 QUIC_CODE_COUNT(quic_key_update_invalid);
4488 break;
4489 case KeyUpdateReason::kRemote:
4490 QUIC_CODE_COUNT(quic_key_update_remote);
4491 break;
4492 case KeyUpdateReason::kLocalForTests:
4493 QUIC_CODE_COUNT(quic_key_update_local_for_tests);
4494 break;
4495 case KeyUpdateReason::kLocalForInteropRunner:
4496 QUIC_CODE_COUNT(quic_key_update_local_for_interop_runner);
4497 break;
4498 case KeyUpdateReason::kLocalAeadConfidentialityLimit:
4499 QUIC_CODE_COUNT(quic_key_update_local_aead_confidentiality_limit);
4500 break;
4501 case KeyUpdateReason::kLocalKeyUpdateLimitOverride:
4502 QUIC_CODE_COUNT(quic_key_update_local_limit_override);
4503 break;
4504 }
4505 visitor_->OnKeyUpdate(reason);
4506 return true;
4507 }
4508
PotentialPeerKeyUpdateAttemptCount() const4509 QuicPacketCount QuicFramer::PotentialPeerKeyUpdateAttemptCount() const {
4510 return potential_peer_key_update_attempt_count_;
4511 }
4512
GetDecrypter(EncryptionLevel level) const4513 const QuicDecrypter* QuicFramer::GetDecrypter(EncryptionLevel level) const {
4514 QUICHE_DCHECK(version_.KnowsWhichDecrypterToUse());
4515 return decrypter_[level].get();
4516 }
4517
decrypter() const4518 const QuicDecrypter* QuicFramer::decrypter() const {
4519 return decrypter_[decrypter_level_].get();
4520 }
4521
alternative_decrypter() const4522 const QuicDecrypter* QuicFramer::alternative_decrypter() const {
4523 if (alternative_decrypter_level_ == NUM_ENCRYPTION_LEVELS) {
4524 return nullptr;
4525 }
4526 return decrypter_[alternative_decrypter_level_].get();
4527 }
4528
SetEncrypter(EncryptionLevel level,std::unique_ptr<QuicEncrypter> encrypter)4529 void QuicFramer::SetEncrypter(EncryptionLevel level,
4530 std::unique_ptr<QuicEncrypter> encrypter) {
4531 QUICHE_DCHECK_GE(level, 0);
4532 QUICHE_DCHECK_LT(level, NUM_ENCRYPTION_LEVELS);
4533 QUIC_DVLOG(1) << ENDPOINT << "Setting encrypter at level " << level;
4534 encrypter_[level] = std::move(encrypter);
4535 }
4536
RemoveEncrypter(EncryptionLevel level)4537 void QuicFramer::RemoveEncrypter(EncryptionLevel level) {
4538 QUIC_DVLOG(1) << ENDPOINT << "Removing encrypter of " << level;
4539 encrypter_[level] = nullptr;
4540 }
4541
SetInitialObfuscators(QuicConnectionId connection_id)4542 void QuicFramer::SetInitialObfuscators(QuicConnectionId connection_id) {
4543 CrypterPair crypters;
4544 CryptoUtils::CreateInitialObfuscators(perspective_, version_, connection_id,
4545 &crypters);
4546 encrypter_[ENCRYPTION_INITIAL] = std::move(crypters.encrypter);
4547 decrypter_[ENCRYPTION_INITIAL] = std::move(crypters.decrypter);
4548 }
4549
EncryptInPlace(EncryptionLevel level,QuicPacketNumber packet_number,size_t ad_len,size_t total_len,size_t buffer_len,char * buffer)4550 size_t QuicFramer::EncryptInPlace(EncryptionLevel level,
4551 QuicPacketNumber packet_number, size_t ad_len,
4552 size_t total_len, size_t buffer_len,
4553 char* buffer) {
4554 QUICHE_DCHECK(packet_number.IsInitialized());
4555 if (encrypter_[level] == nullptr) {
4556 QUIC_BUG(quic_bug_10850_59)
4557 << ENDPOINT
4558 << "Attempted to encrypt in place without encrypter at level " << level;
4559 RaiseError(QUIC_ENCRYPTION_FAILURE);
4560 return 0;
4561 }
4562
4563 size_t output_length = 0;
4564 if (!encrypter_[level]->EncryptPacket(
4565 packet_number.ToUint64(),
4566 absl::string_view(buffer, ad_len), // Associated data
4567 absl::string_view(buffer + ad_len,
4568 total_len - ad_len), // Plaintext
4569 buffer + ad_len, // Destination buffer
4570 &output_length, buffer_len - ad_len)) {
4571 RaiseError(QUIC_ENCRYPTION_FAILURE);
4572 return 0;
4573 }
4574 if (version_.HasHeaderProtection() &&
4575 !ApplyHeaderProtection(level, buffer, ad_len + output_length, ad_len)) {
4576 QUIC_DLOG(ERROR) << "Applying header protection failed.";
4577 RaiseError(QUIC_ENCRYPTION_FAILURE);
4578 return 0;
4579 }
4580
4581 return ad_len + output_length;
4582 }
4583
4584 namespace {
4585
4586 const size_t kHPSampleLen = 16;
4587
IsLongHeader(uint8_t type_byte)4588 constexpr bool IsLongHeader(uint8_t type_byte) {
4589 return (type_byte & FLAGS_LONG_HEADER) != 0;
4590 }
4591
4592 } // namespace
4593
ApplyHeaderProtection(EncryptionLevel level,char * buffer,size_t buffer_len,size_t ad_len)4594 bool QuicFramer::ApplyHeaderProtection(EncryptionLevel level, char* buffer,
4595 size_t buffer_len, size_t ad_len) {
4596 QuicDataReader buffer_reader(buffer, buffer_len);
4597 QuicDataWriter buffer_writer(buffer_len, buffer);
4598 // The sample starts 4 bytes after the start of the packet number.
4599 if (ad_len < last_written_packet_number_length_) {
4600 return false;
4601 }
4602 size_t pn_offset = ad_len - last_written_packet_number_length_;
4603 // Sample the ciphertext and generate the mask to use for header protection.
4604 size_t sample_offset = pn_offset + 4;
4605 QuicDataReader sample_reader(buffer, buffer_len);
4606 absl::string_view sample;
4607 if (!sample_reader.Seek(sample_offset) ||
4608 !sample_reader.ReadStringPiece(&sample, kHPSampleLen)) {
4609 QUIC_BUG(quic_bug_10850_60)
4610 << "Not enough bytes to sample: sample_offset " << sample_offset
4611 << ", sample len: " << kHPSampleLen << ", buffer len: " << buffer_len;
4612 return false;
4613 }
4614
4615 if (encrypter_[level] == nullptr) {
4616 QUIC_BUG(quic_bug_12975_8)
4617 << ENDPOINT
4618 << "Attempted to apply header protection without encrypter at level "
4619 << level << " using " << version_;
4620 return false;
4621 }
4622
4623 std::string mask = encrypter_[level]->GenerateHeaderProtectionMask(sample);
4624 if (mask.empty()) {
4625 QUIC_BUG(quic_bug_10850_61) << "Unable to generate header protection mask.";
4626 return false;
4627 }
4628 QuicDataReader mask_reader(mask.data(), mask.size());
4629
4630 // Apply the mask to the 4 or 5 least significant bits of the first byte.
4631 uint8_t bitmask = 0x1f;
4632 uint8_t type_byte;
4633 if (!buffer_reader.ReadUInt8(&type_byte)) {
4634 return false;
4635 }
4636 QuicLongHeaderType header_type;
4637 if (IsLongHeader(type_byte)) {
4638 bitmask = 0x0f;
4639 header_type = GetLongHeaderType(type_byte, version_);
4640 if (header_type == INVALID_PACKET_TYPE) {
4641 return false;
4642 }
4643 }
4644 uint8_t mask_byte;
4645 if (!mask_reader.ReadUInt8(&mask_byte) ||
4646 !buffer_writer.WriteUInt8(type_byte ^ (mask_byte & bitmask))) {
4647 return false;
4648 }
4649
4650 // Adjust |pn_offset| to account for the diversification nonce.
4651 if (IsLongHeader(type_byte) && header_type == ZERO_RTT_PROTECTED &&
4652 perspective_ == Perspective::IS_SERVER &&
4653 version_.handshake_protocol == PROTOCOL_QUIC_CRYPTO) {
4654 if (pn_offset <= kDiversificationNonceSize) {
4655 QUIC_BUG(quic_bug_10850_62)
4656 << "Expected diversification nonce, but not enough bytes";
4657 return false;
4658 }
4659 pn_offset -= kDiversificationNonceSize;
4660 }
4661 // Advance the reader and writer to the packet number. Both the reader and
4662 // writer have each read/written one byte.
4663 if (!buffer_writer.Seek(pn_offset - 1) ||
4664 !buffer_reader.Seek(pn_offset - 1)) {
4665 return false;
4666 }
4667 // Apply the rest of the mask to the packet number.
4668 for (size_t i = 0; i < last_written_packet_number_length_; ++i) {
4669 uint8_t buffer_byte;
4670 uint8_t pn_mask_byte;
4671 if (!mask_reader.ReadUInt8(&pn_mask_byte) ||
4672 !buffer_reader.ReadUInt8(&buffer_byte) ||
4673 !buffer_writer.WriteUInt8(buffer_byte ^ pn_mask_byte)) {
4674 return false;
4675 }
4676 }
4677 return true;
4678 }
4679
RemoveHeaderProtection(QuicDataReader * reader,const QuicEncryptedPacket & packet,QuicPacketHeader * header,uint64_t * full_packet_number,std::vector<char> * associated_data)4680 bool QuicFramer::RemoveHeaderProtection(QuicDataReader* reader,
4681 const QuicEncryptedPacket& packet,
4682 QuicPacketHeader* header,
4683 uint64_t* full_packet_number,
4684 std::vector<char>* associated_data) {
4685 EncryptionLevel expected_decryption_level = GetEncryptionLevel(*header);
4686 QuicDecrypter* decrypter = decrypter_[expected_decryption_level].get();
4687 if (decrypter == nullptr) {
4688 QUIC_DVLOG(1)
4689 << ENDPOINT
4690 << "No decrypter available for removing header protection at level "
4691 << expected_decryption_level;
4692 return false;
4693 }
4694
4695 bool has_diversification_nonce =
4696 header->form == IETF_QUIC_LONG_HEADER_PACKET &&
4697 header->long_packet_type == ZERO_RTT_PROTECTED &&
4698 perspective_ == Perspective::IS_CLIENT &&
4699 version_.handshake_protocol == PROTOCOL_QUIC_CRYPTO;
4700
4701 // Read a sample from the ciphertext and compute the mask to use for header
4702 // protection.
4703 absl::string_view remaining_packet = reader->PeekRemainingPayload();
4704 QuicDataReader sample_reader(remaining_packet);
4705
4706 // The sample starts 4 bytes after the start of the packet number.
4707 absl::string_view pn;
4708 if (!sample_reader.ReadStringPiece(&pn, 4)) {
4709 QUIC_DVLOG(1) << "Not enough data to sample";
4710 return false;
4711 }
4712 if (has_diversification_nonce) {
4713 // In Google QUIC, the diversification nonce comes between the packet number
4714 // and the sample.
4715 if (!sample_reader.Seek(kDiversificationNonceSize)) {
4716 QUIC_DVLOG(1) << "No diversification nonce to skip over";
4717 return false;
4718 }
4719 }
4720 std::string mask = decrypter->GenerateHeaderProtectionMask(&sample_reader);
4721 QuicDataReader mask_reader(mask.data(), mask.size());
4722 if (mask.empty()) {
4723 QUIC_DVLOG(1) << "Failed to compute mask";
4724 return false;
4725 }
4726
4727 // Unmask the rest of the type byte.
4728 uint8_t bitmask = 0x1f;
4729 if (IsLongHeader(header->type_byte)) {
4730 bitmask = 0x0f;
4731 }
4732 uint8_t mask_byte;
4733 if (!mask_reader.ReadUInt8(&mask_byte)) {
4734 QUIC_DVLOG(1) << "No first byte to read from mask";
4735 return false;
4736 }
4737 header->type_byte ^= (mask_byte & bitmask);
4738
4739 // Compute the packet number length.
4740 header->packet_number_length =
4741 static_cast<QuicPacketNumberLength>((header->type_byte & 0x03) + 1);
4742
4743 char pn_buffer[IETF_MAX_PACKET_NUMBER_LENGTH] = {};
4744 QuicDataWriter pn_writer(ABSL_ARRAYSIZE(pn_buffer), pn_buffer);
4745
4746 // Read the (protected) packet number from the reader and unmask the packet
4747 // number.
4748 for (size_t i = 0; i < header->packet_number_length; ++i) {
4749 uint8_t protected_pn_byte, pn_mask_byte;
4750 if (!mask_reader.ReadUInt8(&pn_mask_byte) ||
4751 !reader->ReadUInt8(&protected_pn_byte) ||
4752 !pn_writer.WriteUInt8(protected_pn_byte ^ pn_mask_byte)) {
4753 QUIC_DVLOG(1) << "Failed to unmask packet number";
4754 return false;
4755 }
4756 }
4757 QuicDataReader packet_number_reader(pn_writer.data(), pn_writer.length());
4758 QuicPacketNumber base_packet_number;
4759 if (supports_multiple_packet_number_spaces_) {
4760 PacketNumberSpace pn_space = GetPacketNumberSpace(*header);
4761 if (pn_space == NUM_PACKET_NUMBER_SPACES) {
4762 return false;
4763 }
4764 base_packet_number = largest_decrypted_packet_numbers_[pn_space];
4765 } else {
4766 base_packet_number = largest_packet_number_;
4767 }
4768 if (!ProcessAndCalculatePacketNumber(
4769 &packet_number_reader, header->packet_number_length,
4770 base_packet_number, full_packet_number)) {
4771 return false;
4772 }
4773
4774 // Get the associated data, and apply the same unmasking operations to it.
4775 absl::string_view ad = GetAssociatedDataFromEncryptedPacket(
4776 version_.transport_version, packet,
4777 GetIncludedDestinationConnectionIdLength(*header),
4778 GetIncludedSourceConnectionIdLength(*header), header->version_flag,
4779 has_diversification_nonce, header->packet_number_length,
4780 header->retry_token_length_length, header->retry_token.length(),
4781 header->length_length);
4782 *associated_data = std::vector<char>(ad.begin(), ad.end());
4783 QuicDataWriter ad_writer(associated_data->size(), associated_data->data());
4784
4785 // Apply the unmasked type byte and packet number to |associated_data|.
4786 if (!ad_writer.WriteUInt8(header->type_byte)) {
4787 return false;
4788 }
4789 // Put the packet number at the end of the AD, or if there's a diversification
4790 // nonce, before that (which is at the end of the AD).
4791 size_t seek_len = ad_writer.remaining() - header->packet_number_length;
4792 if (has_diversification_nonce) {
4793 seek_len -= kDiversificationNonceSize;
4794 }
4795 if (!ad_writer.Seek(seek_len) ||
4796 !ad_writer.WriteBytes(pn_writer.data(), pn_writer.length())) {
4797 QUIC_DVLOG(1) << "Failed to apply unmasking operations to AD";
4798 return false;
4799 }
4800
4801 return true;
4802 }
4803
EncryptPayload(EncryptionLevel level,QuicPacketNumber packet_number,const QuicPacket & packet,char * buffer,size_t buffer_len)4804 size_t QuicFramer::EncryptPayload(EncryptionLevel level,
4805 QuicPacketNumber packet_number,
4806 const QuicPacket& packet, char* buffer,
4807 size_t buffer_len) {
4808 QUICHE_DCHECK(packet_number.IsInitialized());
4809 if (encrypter_[level] == nullptr) {
4810 QUIC_BUG(quic_bug_10850_63)
4811 << ENDPOINT << "Attempted to encrypt without encrypter at level "
4812 << level;
4813 RaiseError(QUIC_ENCRYPTION_FAILURE);
4814 return 0;
4815 }
4816
4817 absl::string_view associated_data =
4818 packet.AssociatedData(version_.transport_version);
4819 // Copy in the header, because the encrypter only populates the encrypted
4820 // plaintext content.
4821 const size_t ad_len = associated_data.length();
4822 if (packet.length() < ad_len) {
4823 QUIC_BUG(quic_bug_10850_64)
4824 << ENDPOINT << "packet is shorter than associated data length. version:"
4825 << version() << ", packet length:" << packet.length()
4826 << ", associated data length:" << ad_len;
4827 RaiseError(QUIC_ENCRYPTION_FAILURE);
4828 return 0;
4829 }
4830 memmove(buffer, associated_data.data(), ad_len);
4831 // Encrypt the plaintext into the buffer.
4832 size_t output_length = 0;
4833 if (!encrypter_[level]->EncryptPacket(
4834 packet_number.ToUint64(), associated_data,
4835 packet.Plaintext(version_.transport_version), buffer + ad_len,
4836 &output_length, buffer_len - ad_len)) {
4837 RaiseError(QUIC_ENCRYPTION_FAILURE);
4838 return 0;
4839 }
4840 if (version_.HasHeaderProtection() &&
4841 !ApplyHeaderProtection(level, buffer, ad_len + output_length, ad_len)) {
4842 QUIC_DLOG(ERROR) << "Applying header protection failed.";
4843 RaiseError(QUIC_ENCRYPTION_FAILURE);
4844 return 0;
4845 }
4846
4847 return ad_len + output_length;
4848 }
4849
GetCiphertextSize(EncryptionLevel level,size_t plaintext_size) const4850 size_t QuicFramer::GetCiphertextSize(EncryptionLevel level,
4851 size_t plaintext_size) const {
4852 if (encrypter_[level] == nullptr) {
4853 QUIC_BUG(quic_bug_10850_65)
4854 << ENDPOINT
4855 << "Attempted to get ciphertext size without encrypter at level "
4856 << level << " using " << version_;
4857 return plaintext_size;
4858 }
4859 return encrypter_[level]->GetCiphertextSize(plaintext_size);
4860 }
4861
GetMaxPlaintextSize(size_t ciphertext_size)4862 size_t QuicFramer::GetMaxPlaintextSize(size_t ciphertext_size) {
4863 // In order to keep the code simple, we don't have the current encryption
4864 // level to hand. Both the NullEncrypter and AES-GCM have a tag length of 12.
4865 size_t min_plaintext_size = ciphertext_size;
4866
4867 for (int i = ENCRYPTION_INITIAL; i < NUM_ENCRYPTION_LEVELS; i++) {
4868 if (encrypter_[i] != nullptr) {
4869 size_t size = encrypter_[i]->GetMaxPlaintextSize(ciphertext_size);
4870 if (size < min_plaintext_size) {
4871 min_plaintext_size = size;
4872 }
4873 }
4874 }
4875
4876 return min_plaintext_size;
4877 }
4878
GetOneRttEncrypterConfidentialityLimit() const4879 QuicPacketCount QuicFramer::GetOneRttEncrypterConfidentialityLimit() const {
4880 if (!encrypter_[ENCRYPTION_FORWARD_SECURE]) {
4881 QUIC_BUG(quic_bug_10850_66) << "1-RTT encrypter not set";
4882 return 0;
4883 }
4884 return encrypter_[ENCRYPTION_FORWARD_SECURE]->GetConfidentialityLimit();
4885 }
4886
DecryptPayload(size_t udp_packet_length,absl::string_view encrypted,absl::string_view associated_data,const QuicPacketHeader & header,char * decrypted_buffer,size_t buffer_length,size_t * decrypted_length,EncryptionLevel * decrypted_level)4887 bool QuicFramer::DecryptPayload(size_t udp_packet_length,
4888 absl::string_view encrypted,
4889 absl::string_view associated_data,
4890 const QuicPacketHeader& header,
4891 char* decrypted_buffer, size_t buffer_length,
4892 size_t* decrypted_length,
4893 EncryptionLevel* decrypted_level) {
4894 if (!EncryptionLevelIsValid(decrypter_level_)) {
4895 QUIC_BUG(quic_bug_10850_67)
4896 << "Attempted to decrypt with bad decrypter_level_";
4897 return false;
4898 }
4899 EncryptionLevel level = decrypter_level_;
4900 QuicDecrypter* decrypter = decrypter_[level].get();
4901 QuicDecrypter* alternative_decrypter = nullptr;
4902 bool key_phase_parsed = false;
4903 bool key_phase;
4904 bool attempt_key_update = false;
4905 if (version().KnowsWhichDecrypterToUse()) {
4906 if (header.form == GOOGLE_QUIC_PACKET) {
4907 QUIC_BUG(quic_bug_10850_68)
4908 << "Attempted to decrypt GOOGLE_QUIC_PACKET with a version that "
4909 "knows which decrypter to use";
4910 return false;
4911 }
4912 level = GetEncryptionLevel(header);
4913 if (!EncryptionLevelIsValid(level)) {
4914 QUIC_BUG(quic_bug_10850_69) << "Attempted to decrypt with bad level";
4915 return false;
4916 }
4917 decrypter = decrypter_[level].get();
4918 if (decrypter == nullptr) {
4919 return false;
4920 }
4921 if (level == ENCRYPTION_ZERO_RTT &&
4922 perspective_ == Perspective::IS_CLIENT && header.nonce != nullptr) {
4923 decrypter->SetDiversificationNonce(*header.nonce);
4924 }
4925 if (support_key_update_for_connection_ &&
4926 header.form == IETF_QUIC_SHORT_HEADER_PACKET) {
4927 QUICHE_DCHECK(version().UsesTls());
4928 QUICHE_DCHECK_EQ(level, ENCRYPTION_FORWARD_SECURE);
4929 key_phase = (header.type_byte & FLAGS_KEY_PHASE_BIT) != 0;
4930 key_phase_parsed = true;
4931 QUIC_DVLOG(1) << ENDPOINT << "packet " << header.packet_number
4932 << " received key_phase=" << key_phase
4933 << " current_key_phase_bit_=" << current_key_phase_bit_;
4934 if (key_phase != current_key_phase_bit_) {
4935 if ((current_key_phase_first_received_packet_number_.IsInitialized() &&
4936 header.packet_number >
4937 current_key_phase_first_received_packet_number_) ||
4938 (!current_key_phase_first_received_packet_number_.IsInitialized() &&
4939 !key_update_performed_)) {
4940 if (!next_decrypter_) {
4941 next_decrypter_ =
4942 visitor_->AdvanceKeysAndCreateCurrentOneRttDecrypter();
4943 if (!next_decrypter_) {
4944 QUIC_BUG(quic_bug_10850_70) << "Failed to create next_decrypter";
4945 return false;
4946 }
4947 }
4948 QUIC_DVLOG(1) << ENDPOINT << "packet " << header.packet_number
4949 << " attempt_key_update=true";
4950 attempt_key_update = true;
4951 potential_peer_key_update_attempt_count_++;
4952 decrypter = next_decrypter_.get();
4953 } else {
4954 if (previous_decrypter_) {
4955 QUIC_DVLOG(1) << ENDPOINT
4956 << "trying previous_decrypter_ for packet "
4957 << header.packet_number;
4958 decrypter = previous_decrypter_.get();
4959 } else {
4960 QUIC_DVLOG(1) << ENDPOINT << "dropping packet "
4961 << header.packet_number << " with old key phase";
4962 return false;
4963 }
4964 }
4965 }
4966 }
4967 } else if (alternative_decrypter_level_ != NUM_ENCRYPTION_LEVELS) {
4968 if (!EncryptionLevelIsValid(alternative_decrypter_level_)) {
4969 QUIC_BUG(quic_bug_10850_71)
4970 << "Attempted to decrypt with bad alternative_decrypter_level_";
4971 return false;
4972 }
4973 alternative_decrypter = decrypter_[alternative_decrypter_level_].get();
4974 }
4975
4976 if (decrypter == nullptr) {
4977 QUIC_BUG(quic_bug_10850_72)
4978 << "Attempting to decrypt without decrypter, encryption level:" << level
4979 << " version:" << version();
4980 return false;
4981 }
4982
4983 bool success = decrypter->DecryptPacket(
4984 header.packet_number.ToUint64(), associated_data, encrypted,
4985 decrypted_buffer, decrypted_length, buffer_length);
4986 if (success) {
4987 visitor_->OnDecryptedPacket(udp_packet_length, level);
4988 if (level == ENCRYPTION_ZERO_RTT &&
4989 current_key_phase_first_received_packet_number_.IsInitialized() &&
4990 header.packet_number >
4991 current_key_phase_first_received_packet_number_) {
4992 set_detailed_error(absl::StrCat(
4993 "Decrypted a 0-RTT packet with a packet number ",
4994 header.packet_number.ToString(),
4995 " which is higher than a 1-RTT packet number ",
4996 current_key_phase_first_received_packet_number_.ToString()));
4997 return RaiseError(QUIC_INVALID_0RTT_PACKET_NUMBER_OUT_OF_ORDER);
4998 }
4999 *decrypted_level = level;
5000 potential_peer_key_update_attempt_count_ = 0;
5001 if (attempt_key_update) {
5002 if (!DoKeyUpdate(KeyUpdateReason::kRemote)) {
5003 set_detailed_error("Key update failed due to internal error");
5004 return RaiseError(QUIC_INTERNAL_ERROR);
5005 }
5006 QUICHE_DCHECK_EQ(current_key_phase_bit_, key_phase);
5007 }
5008 if (key_phase_parsed &&
5009 !current_key_phase_first_received_packet_number_.IsInitialized() &&
5010 key_phase == current_key_phase_bit_) {
5011 // Set packet number for current key phase if it hasn't been initialized
5012 // yet. This is set outside of attempt_key_update since the key update
5013 // may have been initiated locally, and in that case we don't know yet
5014 // which packet number from the remote side to use until we receive a
5015 // packet with that phase.
5016 QUIC_DVLOG(1) << ENDPOINT
5017 << "current_key_phase_first_received_packet_number_ = "
5018 << header.packet_number;
5019 current_key_phase_first_received_packet_number_ = header.packet_number;
5020 visitor_->OnDecryptedFirstPacketInKeyPhase();
5021 }
5022 } else if (alternative_decrypter != nullptr) {
5023 if (header.nonce != nullptr) {
5024 QUICHE_DCHECK_EQ(perspective_, Perspective::IS_CLIENT);
5025 alternative_decrypter->SetDiversificationNonce(*header.nonce);
5026 }
5027 bool try_alternative_decryption = true;
5028 if (alternative_decrypter_level_ == ENCRYPTION_ZERO_RTT) {
5029 if (perspective_ == Perspective::IS_CLIENT) {
5030 if (header.nonce == nullptr) {
5031 // Can not use INITIAL decryption without a diversification nonce.
5032 try_alternative_decryption = false;
5033 }
5034 } else {
5035 QUICHE_DCHECK(header.nonce == nullptr);
5036 }
5037 }
5038
5039 if (try_alternative_decryption) {
5040 success = alternative_decrypter->DecryptPacket(
5041 header.packet_number.ToUint64(), associated_data, encrypted,
5042 decrypted_buffer, decrypted_length, buffer_length);
5043 }
5044 if (success) {
5045 visitor_->OnDecryptedPacket(udp_packet_length,
5046 alternative_decrypter_level_);
5047 *decrypted_level = decrypter_level_;
5048 if (alternative_decrypter_latch_) {
5049 if (!EncryptionLevelIsValid(alternative_decrypter_level_)) {
5050 QUIC_BUG(quic_bug_10850_73)
5051 << "Attempted to latch alternate decrypter with bad "
5052 "alternative_decrypter_level_";
5053 return false;
5054 }
5055 // Switch to the alternative decrypter and latch so that we cannot
5056 // switch back.
5057 decrypter_level_ = alternative_decrypter_level_;
5058 alternative_decrypter_level_ = NUM_ENCRYPTION_LEVELS;
5059 } else {
5060 // Switch the alternative decrypter so that we use it first next time.
5061 EncryptionLevel alt_level = alternative_decrypter_level_;
5062 alternative_decrypter_level_ = decrypter_level_;
5063 decrypter_level_ = alt_level;
5064 }
5065 }
5066 }
5067
5068 if (!success) {
5069 QUIC_DVLOG(1) << ENDPOINT << "DecryptPacket failed for: " << header;
5070 return false;
5071 }
5072
5073 return true;
5074 }
5075
GetIetfAckFrameSize(const QuicAckFrame & frame)5076 size_t QuicFramer::GetIetfAckFrameSize(const QuicAckFrame& frame) {
5077 // Type byte, largest_acked, and delay_time are straight-forward.
5078 size_t ack_frame_size = kQuicFrameTypeSize;
5079 QuicPacketNumber largest_acked = LargestAcked(frame);
5080 ack_frame_size += QuicDataWriter::GetVarInt62Len(largest_acked.ToUint64());
5081 uint64_t ack_delay_time_us;
5082 ack_delay_time_us = frame.ack_delay_time.ToMicroseconds();
5083 ack_delay_time_us = ack_delay_time_us >> local_ack_delay_exponent_;
5084 ack_frame_size += QuicDataWriter::GetVarInt62Len(ack_delay_time_us);
5085
5086 if (frame.packets.Empty() || frame.packets.Max() != largest_acked) {
5087 QUIC_BUG(quic_bug_10850_74) << "Malformed ack frame";
5088 // ACK frame serialization will fail and connection will be closed.
5089 return ack_frame_size;
5090 }
5091
5092 // Ack block count.
5093 ack_frame_size +=
5094 QuicDataWriter::GetVarInt62Len(frame.packets.NumIntervals() - 1);
5095
5096 // First Ack range.
5097 auto iter = frame.packets.rbegin();
5098 ack_frame_size += QuicDataWriter::GetVarInt62Len(iter->Length() - 1);
5099 QuicPacketNumber previous_smallest = iter->min();
5100 ++iter;
5101
5102 // Ack blocks.
5103 for (; iter != frame.packets.rend(); ++iter) {
5104 const uint64_t gap = previous_smallest - iter->max() - 1;
5105 const uint64_t ack_range = iter->Length() - 1;
5106 ack_frame_size += (QuicDataWriter::GetVarInt62Len(gap) +
5107 QuicDataWriter::GetVarInt62Len(ack_range));
5108 previous_smallest = iter->min();
5109 }
5110
5111 if (UseIetfAckWithReceiveTimestamp(frame)) {
5112 ack_frame_size += GetIetfAckFrameTimestampSize(frame);
5113 } else {
5114 ack_frame_size += AckEcnCountSize(frame);
5115 }
5116
5117 return ack_frame_size;
5118 }
5119
GetIetfAckFrameTimestampSize(const QuicAckFrame & ack)5120 size_t QuicFramer::GetIetfAckFrameTimestampSize(const QuicAckFrame& ack) {
5121 QUICHE_DCHECK(!ack.received_packet_times.empty());
5122 std::string detailed_error;
5123 absl::InlinedVector<AckTimestampRange, 2> timestamp_ranges =
5124 GetAckTimestampRanges(ack, detailed_error);
5125 if (!detailed_error.empty()) {
5126 return 0;
5127 }
5128
5129 int64_t size =
5130 FrameAckTimestampRanges(ack, timestamp_ranges, /*writer=*/nullptr);
5131 return std::max<int64_t>(0, size);
5132 }
5133
GetAckFrameSize(const QuicAckFrame & ack,QuicPacketNumberLength)5134 size_t QuicFramer::GetAckFrameSize(
5135 const QuicAckFrame& ack, QuicPacketNumberLength /*packet_number_length*/) {
5136 QUICHE_DCHECK(!ack.packets.Empty());
5137 size_t ack_size = 0;
5138
5139 if (VersionHasIetfQuicFrames(version_.transport_version)) {
5140 return GetIetfAckFrameSize(ack);
5141 }
5142 AckFrameInfo ack_info = GetAckFrameInfo(ack);
5143 QuicPacketNumberLength ack_block_length =
5144 GetMinPacketNumberLength(QuicPacketNumber(ack_info.max_block_length));
5145
5146 ack_size = GetMinAckFrameSize(version_.transport_version, ack,
5147 local_ack_delay_exponent_,
5148 UseIetfAckWithReceiveTimestamp(ack));
5149 // First ack block length.
5150 ack_size += ack_block_length;
5151 if (ack_info.num_ack_blocks != 0) {
5152 ack_size += kNumberOfAckBlocksSize;
5153 ack_size += std::min(ack_info.num_ack_blocks, kMaxAckBlocks) *
5154 (ack_block_length + PACKET_1BYTE_PACKET_NUMBER);
5155 }
5156
5157 // Include timestamps.
5158 if (process_timestamps_) {
5159 ack_size += GetAckFrameTimeStampSize(ack);
5160 }
5161
5162 return ack_size;
5163 }
5164
GetAckFrameTimeStampSize(const QuicAckFrame & ack)5165 size_t QuicFramer::GetAckFrameTimeStampSize(const QuicAckFrame& ack) {
5166 if (ack.received_packet_times.empty()) {
5167 return 0;
5168 }
5169
5170 return kQuicNumTimestampsLength + kQuicFirstTimestampLength +
5171 (kQuicTimestampLength + kQuicTimestampPacketNumberGapLength) *
5172 (ack.received_packet_times.size() - 1);
5173 }
5174
ComputeFrameLength(const QuicFrame & frame,bool last_frame_in_packet,QuicPacketNumberLength packet_number_length)5175 size_t QuicFramer::ComputeFrameLength(
5176 const QuicFrame& frame, bool last_frame_in_packet,
5177 QuicPacketNumberLength packet_number_length) {
5178 switch (frame.type) {
5179 case STREAM_FRAME:
5180 return GetMinStreamFrameSize(
5181 version_.transport_version, frame.stream_frame.stream_id,
5182 frame.stream_frame.offset, last_frame_in_packet,
5183 frame.stream_frame.data_length) +
5184 frame.stream_frame.data_length;
5185 case CRYPTO_FRAME:
5186 return GetMinCryptoFrameSize(frame.crypto_frame->offset,
5187 frame.crypto_frame->data_length) +
5188 frame.crypto_frame->data_length;
5189 case ACK_FRAME: {
5190 return GetAckFrameSize(*frame.ack_frame, packet_number_length);
5191 }
5192 case STOP_WAITING_FRAME:
5193 return GetStopWaitingFrameSize(packet_number_length);
5194 case MTU_DISCOVERY_FRAME:
5195 // MTU discovery frames are serialized as ping frames.
5196 return kQuicFrameTypeSize;
5197 case MESSAGE_FRAME:
5198 return GetMessageFrameSize(version_.transport_version,
5199 last_frame_in_packet,
5200 frame.message_frame->message_length);
5201 case PADDING_FRAME:
5202 QUICHE_DCHECK(false);
5203 return 0;
5204 default:
5205 return GetRetransmittableControlFrameSize(version_.transport_version,
5206 frame);
5207 }
5208 }
5209
AppendTypeByte(const QuicFrame & frame,bool last_frame_in_packet,QuicDataWriter * writer)5210 bool QuicFramer::AppendTypeByte(const QuicFrame& frame,
5211 bool last_frame_in_packet,
5212 QuicDataWriter* writer) {
5213 if (VersionHasIetfQuicFrames(version_.transport_version)) {
5214 return AppendIetfFrameType(frame, last_frame_in_packet, writer);
5215 }
5216 uint8_t type_byte = 0;
5217 switch (frame.type) {
5218 case STREAM_FRAME:
5219 type_byte =
5220 GetStreamFrameTypeByte(frame.stream_frame, last_frame_in_packet);
5221 break;
5222 case ACK_FRAME:
5223 return true;
5224 case MTU_DISCOVERY_FRAME:
5225 type_byte = static_cast<uint8_t>(PING_FRAME);
5226 break;
5227 case NEW_CONNECTION_ID_FRAME:
5228 set_detailed_error(
5229 "Attempt to append NEW_CONNECTION_ID frame and not in IETF QUIC.");
5230 return RaiseError(QUIC_INTERNAL_ERROR);
5231 case RETIRE_CONNECTION_ID_FRAME:
5232 set_detailed_error(
5233 "Attempt to append RETIRE_CONNECTION_ID frame and not in IETF QUIC.");
5234 return RaiseError(QUIC_INTERNAL_ERROR);
5235 case NEW_TOKEN_FRAME:
5236 set_detailed_error(
5237 "Attempt to append NEW_TOKEN frame and not in IETF QUIC.");
5238 return RaiseError(QUIC_INTERNAL_ERROR);
5239 case MAX_STREAMS_FRAME:
5240 set_detailed_error(
5241 "Attempt to append MAX_STREAMS frame and not in IETF QUIC.");
5242 return RaiseError(QUIC_INTERNAL_ERROR);
5243 case STREAMS_BLOCKED_FRAME:
5244 set_detailed_error(
5245 "Attempt to append STREAMS_BLOCKED frame and not in IETF QUIC.");
5246 return RaiseError(QUIC_INTERNAL_ERROR);
5247 case PATH_RESPONSE_FRAME:
5248 set_detailed_error(
5249 "Attempt to append PATH_RESPONSE frame and not in IETF QUIC.");
5250 return RaiseError(QUIC_INTERNAL_ERROR);
5251 case PATH_CHALLENGE_FRAME:
5252 set_detailed_error(
5253 "Attempt to append PATH_CHALLENGE frame and not in IETF QUIC.");
5254 return RaiseError(QUIC_INTERNAL_ERROR);
5255 case STOP_SENDING_FRAME:
5256 set_detailed_error(
5257 "Attempt to append STOP_SENDING frame and not in IETF QUIC.");
5258 return RaiseError(QUIC_INTERNAL_ERROR);
5259 case MESSAGE_FRAME:
5260 return true;
5261
5262 default:
5263 type_byte = static_cast<uint8_t>(frame.type);
5264 break;
5265 }
5266
5267 return writer->WriteUInt8(type_byte);
5268 }
5269
AppendIetfFrameType(const QuicFrame & frame,bool last_frame_in_packet,QuicDataWriter * writer)5270 bool QuicFramer::AppendIetfFrameType(const QuicFrame& frame,
5271 bool last_frame_in_packet,
5272 QuicDataWriter* writer) {
5273 uint8_t type_byte = 0;
5274 switch (frame.type) {
5275 case PADDING_FRAME:
5276 type_byte = IETF_PADDING;
5277 break;
5278 case RST_STREAM_FRAME:
5279 type_byte = IETF_RST_STREAM;
5280 break;
5281 case CONNECTION_CLOSE_FRAME:
5282 switch (frame.connection_close_frame->close_type) {
5283 case IETF_QUIC_APPLICATION_CONNECTION_CLOSE:
5284 type_byte = IETF_APPLICATION_CLOSE;
5285 break;
5286 case IETF_QUIC_TRANSPORT_CONNECTION_CLOSE:
5287 type_byte = IETF_CONNECTION_CLOSE;
5288 break;
5289 default:
5290 set_detailed_error(absl::StrCat(
5291 "Invalid QuicConnectionCloseFrame type: ",
5292 static_cast<int>(frame.connection_close_frame->close_type)));
5293 return RaiseError(QUIC_INTERNAL_ERROR);
5294 }
5295 break;
5296 case GOAWAY_FRAME:
5297 set_detailed_error(
5298 "Attempt to create non-IETF QUIC GOAWAY frame in IETF QUIC.");
5299 return RaiseError(QUIC_INTERNAL_ERROR);
5300 case WINDOW_UPDATE_FRAME:
5301 // Depending on whether there is a stream ID or not, will be either a
5302 // MAX_STREAM_DATA frame or a MAX_DATA frame.
5303 if (frame.window_update_frame.stream_id ==
5304 QuicUtils::GetInvalidStreamId(transport_version())) {
5305 type_byte = IETF_MAX_DATA;
5306 } else {
5307 type_byte = IETF_MAX_STREAM_DATA;
5308 }
5309 break;
5310 case BLOCKED_FRAME:
5311 if (frame.blocked_frame.stream_id ==
5312 QuicUtils::GetInvalidStreamId(transport_version())) {
5313 type_byte = IETF_DATA_BLOCKED;
5314 } else {
5315 type_byte = IETF_STREAM_DATA_BLOCKED;
5316 }
5317 break;
5318 case STOP_WAITING_FRAME:
5319 set_detailed_error(
5320 "Attempt to append type byte of STOP WAITING frame in IETF QUIC.");
5321 return RaiseError(QUIC_INTERNAL_ERROR);
5322 case PING_FRAME:
5323 type_byte = IETF_PING;
5324 break;
5325 case STREAM_FRAME:
5326 type_byte =
5327 GetStreamFrameTypeByte(frame.stream_frame, last_frame_in_packet);
5328 break;
5329 case ACK_FRAME:
5330 // Do nothing here, AppendIetfAckFrameAndTypeByte() will put the type byte
5331 // in the buffer.
5332 return true;
5333 case MTU_DISCOVERY_FRAME:
5334 // The path MTU discovery frame is encoded as a PING frame on the wire.
5335 type_byte = IETF_PING;
5336 break;
5337 case NEW_CONNECTION_ID_FRAME:
5338 type_byte = IETF_NEW_CONNECTION_ID;
5339 break;
5340 case RETIRE_CONNECTION_ID_FRAME:
5341 type_byte = IETF_RETIRE_CONNECTION_ID;
5342 break;
5343 case NEW_TOKEN_FRAME:
5344 type_byte = IETF_NEW_TOKEN;
5345 break;
5346 case MAX_STREAMS_FRAME:
5347 if (frame.max_streams_frame.unidirectional) {
5348 type_byte = IETF_MAX_STREAMS_UNIDIRECTIONAL;
5349 } else {
5350 type_byte = IETF_MAX_STREAMS_BIDIRECTIONAL;
5351 }
5352 break;
5353 case STREAMS_BLOCKED_FRAME:
5354 if (frame.streams_blocked_frame.unidirectional) {
5355 type_byte = IETF_STREAMS_BLOCKED_UNIDIRECTIONAL;
5356 } else {
5357 type_byte = IETF_STREAMS_BLOCKED_BIDIRECTIONAL;
5358 }
5359 break;
5360 case PATH_RESPONSE_FRAME:
5361 type_byte = IETF_PATH_RESPONSE;
5362 break;
5363 case PATH_CHALLENGE_FRAME:
5364 type_byte = IETF_PATH_CHALLENGE;
5365 break;
5366 case STOP_SENDING_FRAME:
5367 type_byte = IETF_STOP_SENDING;
5368 break;
5369 case MESSAGE_FRAME:
5370 return true;
5371 case CRYPTO_FRAME:
5372 type_byte = IETF_CRYPTO;
5373 break;
5374 case HANDSHAKE_DONE_FRAME:
5375 type_byte = IETF_HANDSHAKE_DONE;
5376 break;
5377 case ACK_FREQUENCY_FRAME:
5378 type_byte = IETF_ACK_FREQUENCY;
5379 break;
5380 default:
5381 QUIC_BUG(quic_bug_10850_75)
5382 << "Attempt to generate a frame type for an unsupported value: "
5383 << frame.type;
5384 return false;
5385 }
5386 return writer->WriteVarInt62(type_byte);
5387 }
5388
5389 // static
AppendPacketNumber(QuicPacketNumberLength packet_number_length,QuicPacketNumber packet_number,QuicDataWriter * writer)5390 bool QuicFramer::AppendPacketNumber(QuicPacketNumberLength packet_number_length,
5391 QuicPacketNumber packet_number,
5392 QuicDataWriter* writer) {
5393 QUICHE_DCHECK(packet_number.IsInitialized());
5394 if (!IsValidPacketNumberLength(packet_number_length)) {
5395 QUIC_BUG(quic_bug_10850_76)
5396 << "Invalid packet_number_length: " << packet_number_length;
5397 return false;
5398 }
5399 return writer->WriteBytesToUInt64(packet_number_length,
5400 packet_number.ToUint64());
5401 }
5402
5403 // static
AppendStreamId(size_t stream_id_length,QuicStreamId stream_id,QuicDataWriter * writer)5404 bool QuicFramer::AppendStreamId(size_t stream_id_length, QuicStreamId stream_id,
5405 QuicDataWriter* writer) {
5406 if (stream_id_length == 0 || stream_id_length > 4) {
5407 QUIC_BUG(quic_bug_10850_77)
5408 << "Invalid stream_id_length: " << stream_id_length;
5409 return false;
5410 }
5411 return writer->WriteBytesToUInt64(stream_id_length, stream_id);
5412 }
5413
5414 // static
AppendStreamOffset(size_t offset_length,QuicStreamOffset offset,QuicDataWriter * writer)5415 bool QuicFramer::AppendStreamOffset(size_t offset_length,
5416 QuicStreamOffset offset,
5417 QuicDataWriter* writer) {
5418 if (offset_length == 1 || offset_length > 8) {
5419 QUIC_BUG(quic_bug_10850_78)
5420 << "Invalid stream_offset_length: " << offset_length;
5421 return false;
5422 }
5423
5424 return writer->WriteBytesToUInt64(offset_length, offset);
5425 }
5426
5427 // static
AppendAckBlock(uint8_t gap,QuicPacketNumberLength length_length,uint64_t length,QuicDataWriter * writer)5428 bool QuicFramer::AppendAckBlock(uint8_t gap,
5429 QuicPacketNumberLength length_length,
5430 uint64_t length, QuicDataWriter* writer) {
5431 if (length == 0) {
5432 if (!IsValidPacketNumberLength(length_length)) {
5433 QUIC_BUG(quic_bug_10850_79)
5434 << "Invalid packet_number_length: " << length_length;
5435 return false;
5436 }
5437 return writer->WriteUInt8(gap) &&
5438 writer->WriteBytesToUInt64(length_length, length);
5439 }
5440 return writer->WriteUInt8(gap) &&
5441 AppendPacketNumber(length_length, QuicPacketNumber(length), writer);
5442 }
5443
AppendStreamFrame(const QuicStreamFrame & frame,bool no_stream_frame_length,QuicDataWriter * writer)5444 bool QuicFramer::AppendStreamFrame(const QuicStreamFrame& frame,
5445 bool no_stream_frame_length,
5446 QuicDataWriter* writer) {
5447 if (VersionHasIetfQuicFrames(version_.transport_version)) {
5448 return AppendIetfStreamFrame(frame, no_stream_frame_length, writer);
5449 }
5450 if (!AppendStreamId(GetStreamIdSize(frame.stream_id), frame.stream_id,
5451 writer)) {
5452 QUIC_BUG(quic_bug_10850_80) << "Writing stream id size failed.";
5453 return false;
5454 }
5455 if (!AppendStreamOffset(GetStreamOffsetSize(frame.offset), frame.offset,
5456 writer)) {
5457 QUIC_BUG(quic_bug_10850_81) << "Writing offset size failed.";
5458 return false;
5459 }
5460 if (!no_stream_frame_length) {
5461 static_assert(
5462 std::numeric_limits<decltype(frame.data_length)>::max() <=
5463 std::numeric_limits<uint16_t>::max(),
5464 "If frame.data_length can hold more than a uint16_t than we need to "
5465 "check that frame.data_length <= std::numeric_limits<uint16_t>::max()");
5466 if (!writer->WriteUInt16(static_cast<uint16_t>(frame.data_length))) {
5467 QUIC_BUG(quic_bug_10850_82) << "Writing stream frame length failed";
5468 return false;
5469 }
5470 }
5471
5472 if (data_producer_ != nullptr) {
5473 QUICHE_DCHECK_EQ(nullptr, frame.data_buffer);
5474 if (frame.data_length == 0) {
5475 return true;
5476 }
5477 if (data_producer_->WriteStreamData(frame.stream_id, frame.offset,
5478 frame.data_length,
5479 writer) != WRITE_SUCCESS) {
5480 QUIC_BUG(quic_bug_10850_83) << "Writing frame data failed.";
5481 return false;
5482 }
5483 return true;
5484 }
5485
5486 if (!writer->WriteBytes(frame.data_buffer, frame.data_length)) {
5487 QUIC_BUG(quic_bug_10850_84) << "Writing frame data failed.";
5488 return false;
5489 }
5490 return true;
5491 }
5492
AppendNewTokenFrame(const QuicNewTokenFrame & frame,QuicDataWriter * writer)5493 bool QuicFramer::AppendNewTokenFrame(const QuicNewTokenFrame& frame,
5494 QuicDataWriter* writer) {
5495 if (!writer->WriteVarInt62(static_cast<uint64_t>(frame.token.length()))) {
5496 set_detailed_error("Writing token length failed.");
5497 return false;
5498 }
5499 if (!writer->WriteBytes(frame.token.data(), frame.token.length())) {
5500 set_detailed_error("Writing token buffer failed.");
5501 return false;
5502 }
5503 return true;
5504 }
5505
ProcessNewTokenFrame(QuicDataReader * reader,QuicNewTokenFrame * frame)5506 bool QuicFramer::ProcessNewTokenFrame(QuicDataReader* reader,
5507 QuicNewTokenFrame* frame) {
5508 uint64_t length;
5509 if (!reader->ReadVarInt62(&length)) {
5510 set_detailed_error("Unable to read new token length.");
5511 return false;
5512 }
5513 if (length > kMaxNewTokenTokenLength) {
5514 set_detailed_error("Token length larger than maximum.");
5515 return false;
5516 }
5517
5518 // TODO(ianswett): Don't use absl::string_view as an intermediary.
5519 absl::string_view data;
5520 if (!reader->ReadStringPiece(&data, length)) {
5521 set_detailed_error("Unable to read new token data.");
5522 return false;
5523 }
5524 frame->token = std::string(data);
5525 return true;
5526 }
5527
5528 // Add a new ietf-format stream frame.
5529 // Bits controlling whether there is a frame-length and frame-offset
5530 // are in the QuicStreamFrame.
AppendIetfStreamFrame(const QuicStreamFrame & frame,bool last_frame_in_packet,QuicDataWriter * writer)5531 bool QuicFramer::AppendIetfStreamFrame(const QuicStreamFrame& frame,
5532 bool last_frame_in_packet,
5533 QuicDataWriter* writer) {
5534 if (!writer->WriteVarInt62(static_cast<uint64_t>(frame.stream_id))) {
5535 set_detailed_error("Writing stream id failed.");
5536 return false;
5537 }
5538
5539 if (frame.offset != 0) {
5540 if (!writer->WriteVarInt62(static_cast<uint64_t>(frame.offset))) {
5541 set_detailed_error("Writing data offset failed.");
5542 return false;
5543 }
5544 }
5545
5546 if (!last_frame_in_packet) {
5547 if (!writer->WriteVarInt62(frame.data_length)) {
5548 set_detailed_error("Writing data length failed.");
5549 return false;
5550 }
5551 }
5552
5553 if (frame.data_length == 0) {
5554 return true;
5555 }
5556 if (data_producer_ == nullptr) {
5557 if (!writer->WriteBytes(frame.data_buffer, frame.data_length)) {
5558 set_detailed_error("Writing frame data failed.");
5559 return false;
5560 }
5561 } else {
5562 QUICHE_DCHECK_EQ(nullptr, frame.data_buffer);
5563
5564 if (data_producer_->WriteStreamData(frame.stream_id, frame.offset,
5565 frame.data_length,
5566 writer) != WRITE_SUCCESS) {
5567 set_detailed_error("Writing frame data from producer failed.");
5568 return false;
5569 }
5570 }
5571 return true;
5572 }
5573
AppendCryptoFrame(const QuicCryptoFrame & frame,QuicDataWriter * writer)5574 bool QuicFramer::AppendCryptoFrame(const QuicCryptoFrame& frame,
5575 QuicDataWriter* writer) {
5576 if (!writer->WriteVarInt62(static_cast<uint64_t>(frame.offset))) {
5577 set_detailed_error("Writing data offset failed.");
5578 return false;
5579 }
5580 if (!writer->WriteVarInt62(static_cast<uint64_t>(frame.data_length))) {
5581 set_detailed_error("Writing data length failed.");
5582 return false;
5583 }
5584 if (data_producer_ == nullptr) {
5585 if (frame.data_buffer == nullptr ||
5586 !writer->WriteBytes(frame.data_buffer, frame.data_length)) {
5587 set_detailed_error("Writing frame data failed.");
5588 return false;
5589 }
5590 } else {
5591 QUICHE_DCHECK_EQ(nullptr, frame.data_buffer);
5592 if (!data_producer_->WriteCryptoData(frame.level, frame.offset,
5593 frame.data_length, writer)) {
5594 return false;
5595 }
5596 }
5597 return true;
5598 }
5599
AppendAckFrequencyFrame(const QuicAckFrequencyFrame & frame,QuicDataWriter * writer)5600 bool QuicFramer::AppendAckFrequencyFrame(const QuicAckFrequencyFrame& frame,
5601 QuicDataWriter* writer) {
5602 if (!writer->WriteVarInt62(frame.sequence_number)) {
5603 set_detailed_error("Writing sequence number failed.");
5604 return false;
5605 }
5606 if (!writer->WriteVarInt62(frame.packet_tolerance)) {
5607 set_detailed_error("Writing packet tolerance failed.");
5608 return false;
5609 }
5610 if (!writer->WriteVarInt62(
5611 static_cast<uint64_t>(frame.max_ack_delay.ToMicroseconds()))) {
5612 set_detailed_error("Writing max_ack_delay_us failed.");
5613 return false;
5614 }
5615 if (!writer->WriteUInt8(static_cast<uint8_t>(frame.ignore_order))) {
5616 set_detailed_error("Writing ignore_order failed.");
5617 return false;
5618 }
5619
5620 return true;
5621 }
5622
set_version(const ParsedQuicVersion version)5623 void QuicFramer::set_version(const ParsedQuicVersion version) {
5624 QUICHE_DCHECK(IsSupportedVersion(version))
5625 << ParsedQuicVersionToString(version);
5626 version_ = version;
5627 }
5628
AppendAckFrameAndTypeByte(const QuicAckFrame & frame,QuicDataWriter * writer)5629 bool QuicFramer::AppendAckFrameAndTypeByte(const QuicAckFrame& frame,
5630 QuicDataWriter* writer) {
5631 if (VersionHasIetfQuicFrames(transport_version())) {
5632 return AppendIetfAckFrameAndTypeByte(frame, writer);
5633 }
5634
5635 const AckFrameInfo new_ack_info = GetAckFrameInfo(frame);
5636 QuicPacketNumber largest_acked = LargestAcked(frame);
5637 QuicPacketNumberLength largest_acked_length =
5638 GetMinPacketNumberLength(largest_acked);
5639 QuicPacketNumberLength ack_block_length =
5640 GetMinPacketNumberLength(QuicPacketNumber(new_ack_info.max_block_length));
5641 // Calculate available bytes for timestamps and ack blocks.
5642 int32_t available_timestamp_and_ack_block_bytes =
5643 writer->capacity() - writer->length() - ack_block_length -
5644 GetMinAckFrameSize(version_.transport_version, frame,
5645 local_ack_delay_exponent_,
5646 UseIetfAckWithReceiveTimestamp(frame)) -
5647 (new_ack_info.num_ack_blocks != 0 ? kNumberOfAckBlocksSize : 0);
5648 QUICHE_DCHECK_LE(0, available_timestamp_and_ack_block_bytes);
5649
5650 uint8_t type_byte = 0;
5651 SetBit(&type_byte, new_ack_info.num_ack_blocks != 0,
5652 kQuicHasMultipleAckBlocksOffset);
5653
5654 SetBits(&type_byte, GetPacketNumberFlags(largest_acked_length),
5655 kQuicSequenceNumberLengthNumBits, kLargestAckedOffset);
5656
5657 SetBits(&type_byte, GetPacketNumberFlags(ack_block_length),
5658 kQuicSequenceNumberLengthNumBits, kActBlockLengthOffset);
5659
5660 type_byte |= kQuicFrameTypeAckMask;
5661
5662 if (!writer->WriteUInt8(type_byte)) {
5663 return false;
5664 }
5665
5666 size_t max_num_ack_blocks = available_timestamp_and_ack_block_bytes /
5667 (ack_block_length + PACKET_1BYTE_PACKET_NUMBER);
5668
5669 // Number of ack blocks.
5670 size_t num_ack_blocks =
5671 std::min(new_ack_info.num_ack_blocks, max_num_ack_blocks);
5672 if (num_ack_blocks > std::numeric_limits<uint8_t>::max()) {
5673 num_ack_blocks = std::numeric_limits<uint8_t>::max();
5674 }
5675
5676 // Largest acked.
5677 if (!AppendPacketNumber(largest_acked_length, largest_acked, writer)) {
5678 return false;
5679 }
5680
5681 // Largest acked delta time.
5682 uint64_t ack_delay_time_us = kUFloat16MaxValue;
5683 if (!frame.ack_delay_time.IsInfinite()) {
5684 QUICHE_DCHECK_LE(0u, frame.ack_delay_time.ToMicroseconds());
5685 ack_delay_time_us = frame.ack_delay_time.ToMicroseconds();
5686 }
5687 if (!writer->WriteUFloat16(ack_delay_time_us)) {
5688 return false;
5689 }
5690
5691 if (num_ack_blocks > 0) {
5692 if (!writer->WriteBytes(&num_ack_blocks, 1)) {
5693 return false;
5694 }
5695 }
5696
5697 // First ack block length.
5698 if (!AppendPacketNumber(ack_block_length,
5699 QuicPacketNumber(new_ack_info.first_block_length),
5700 writer)) {
5701 return false;
5702 }
5703
5704 // Ack blocks.
5705 if (num_ack_blocks > 0) {
5706 size_t num_ack_blocks_written = 0;
5707 // Append, in descending order from the largest ACKed packet, a series of
5708 // ACK blocks that represents the successfully acknoweldged packets. Each
5709 // appended gap/block length represents a descending delta from the previous
5710 // block. i.e.:
5711 // |--- length ---|--- gap ---|--- length ---|--- gap ---|--- largest ---|
5712 // For gaps larger than can be represented by a single encoded gap, a 0
5713 // length gap of the maximum is used, i.e.:
5714 // |--- length ---|--- gap ---|- 0 -|--- gap ---|--- largest ---|
5715 auto itr = frame.packets.rbegin();
5716 QuicPacketNumber previous_start = itr->min();
5717 ++itr;
5718
5719 for (;
5720 itr != frame.packets.rend() && num_ack_blocks_written < num_ack_blocks;
5721 previous_start = itr->min(), ++itr) {
5722 const auto& interval = *itr;
5723 const uint64_t total_gap = previous_start - interval.max();
5724 const size_t num_encoded_gaps =
5725 (total_gap + std::numeric_limits<uint8_t>::max() - 1) /
5726 std::numeric_limits<uint8_t>::max();
5727
5728 // Append empty ACK blocks because the gap is longer than a single gap.
5729 for (size_t i = 1;
5730 i < num_encoded_gaps && num_ack_blocks_written < num_ack_blocks;
5731 ++i) {
5732 if (!AppendAckBlock(std::numeric_limits<uint8_t>::max(),
5733 ack_block_length, 0, writer)) {
5734 return false;
5735 }
5736 ++num_ack_blocks_written;
5737 }
5738 if (num_ack_blocks_written >= num_ack_blocks) {
5739 if (ABSL_PREDICT_FALSE(num_ack_blocks_written != num_ack_blocks)) {
5740 QUIC_BUG(quic_bug_10850_85)
5741 << "Wrote " << num_ack_blocks_written << ", expected to write "
5742 << num_ack_blocks;
5743 }
5744 break;
5745 }
5746
5747 const uint8_t last_gap =
5748 total_gap -
5749 (num_encoded_gaps - 1) * std::numeric_limits<uint8_t>::max();
5750 // Append the final ACK block with a non-empty size.
5751 if (!AppendAckBlock(last_gap, ack_block_length, interval.Length(),
5752 writer)) {
5753 return false;
5754 }
5755 ++num_ack_blocks_written;
5756 }
5757 QUICHE_DCHECK_EQ(num_ack_blocks, num_ack_blocks_written);
5758 }
5759 // Timestamps.
5760 // If we don't process timestamps or if we don't have enough available space
5761 // to append all the timestamps, don't append any of them.
5762 if (process_timestamps_ && writer->capacity() - writer->length() >=
5763 GetAckFrameTimeStampSize(frame)) {
5764 if (!AppendTimestampsToAckFrame(frame, writer)) {
5765 return false;
5766 }
5767 } else {
5768 uint8_t num_received_packets = 0;
5769 if (!writer->WriteBytes(&num_received_packets, 1)) {
5770 return false;
5771 }
5772 }
5773
5774 return true;
5775 }
5776
AppendTimestampsToAckFrame(const QuicAckFrame & frame,QuicDataWriter * writer)5777 bool QuicFramer::AppendTimestampsToAckFrame(const QuicAckFrame& frame,
5778 QuicDataWriter* writer) {
5779 QUICHE_DCHECK_GE(std::numeric_limits<uint8_t>::max(),
5780 frame.received_packet_times.size());
5781 // num_received_packets is only 1 byte.
5782 if (frame.received_packet_times.size() >
5783 std::numeric_limits<uint8_t>::max()) {
5784 return false;
5785 }
5786
5787 uint8_t num_received_packets = frame.received_packet_times.size();
5788 if (!writer->WriteBytes(&num_received_packets, 1)) {
5789 return false;
5790 }
5791 if (num_received_packets == 0) {
5792 return true;
5793 }
5794
5795 auto it = frame.received_packet_times.begin();
5796 QuicPacketNumber packet_number = it->first;
5797 uint64_t delta_from_largest_observed = LargestAcked(frame) - packet_number;
5798
5799 QUICHE_DCHECK_GE(std::numeric_limits<uint8_t>::max(),
5800 delta_from_largest_observed);
5801 if (delta_from_largest_observed > std::numeric_limits<uint8_t>::max()) {
5802 return false;
5803 }
5804
5805 if (!writer->WriteUInt8(delta_from_largest_observed)) {
5806 return false;
5807 }
5808
5809 // Use the lowest 4 bytes of the time delta from the creation_time_.
5810 const uint64_t time_epoch_delta_us = UINT64_C(1) << 32;
5811 uint32_t time_delta_us =
5812 static_cast<uint32_t>((it->second - creation_time_).ToMicroseconds() &
5813 (time_epoch_delta_us - 1));
5814 if (!writer->WriteUInt32(time_delta_us)) {
5815 return false;
5816 }
5817
5818 QuicTime prev_time = it->second;
5819
5820 for (++it; it != frame.received_packet_times.end(); ++it) {
5821 packet_number = it->first;
5822 delta_from_largest_observed = LargestAcked(frame) - packet_number;
5823
5824 if (delta_from_largest_observed > std::numeric_limits<uint8_t>::max()) {
5825 return false;
5826 }
5827
5828 if (!writer->WriteUInt8(delta_from_largest_observed)) {
5829 return false;
5830 }
5831
5832 uint64_t frame_time_delta_us = (it->second - prev_time).ToMicroseconds();
5833 prev_time = it->second;
5834 if (!writer->WriteUFloat16(frame_time_delta_us)) {
5835 return false;
5836 }
5837 }
5838 return true;
5839 }
5840
5841 absl::InlinedVector<QuicFramer::AckTimestampRange, 2>
GetAckTimestampRanges(const QuicAckFrame & frame,std::string & detailed_error) const5842 QuicFramer::GetAckTimestampRanges(const QuicAckFrame& frame,
5843 std::string& detailed_error) const {
5844 detailed_error = "";
5845 if (frame.received_packet_times.empty()) {
5846 return {};
5847 }
5848
5849 absl::InlinedVector<AckTimestampRange, 2> timestamp_ranges;
5850
5851 for (size_t r = 0; r < std::min<size_t>(max_receive_timestamps_per_ack_,
5852 frame.received_packet_times.size());
5853 ++r) {
5854 const size_t i = frame.received_packet_times.size() - 1 - r;
5855 const QuicPacketNumber packet_number = frame.received_packet_times[i].first;
5856 const QuicTime receive_timestamp = frame.received_packet_times[i].second;
5857
5858 if (timestamp_ranges.empty()) {
5859 if (receive_timestamp < creation_time_ ||
5860 LargestAcked(frame) < packet_number) {
5861 detailed_error =
5862 "The first packet is either received earlier than framer creation "
5863 "time, or larger than largest acked packet.";
5864 QUIC_BUG(quic_framer_ack_ts_first_packet_bad)
5865 << detailed_error << " receive_timestamp:" << receive_timestamp
5866 << ", framer_creation_time:" << creation_time_
5867 << ", packet_number:" << packet_number
5868 << ", largest_acked:" << LargestAcked(frame);
5869 return {};
5870 }
5871 timestamp_ranges.push_back(AckTimestampRange());
5872 timestamp_ranges.back().gap = LargestAcked(frame) - packet_number;
5873 timestamp_ranges.back().range_begin = i;
5874 timestamp_ranges.back().range_end = i;
5875 continue;
5876 }
5877
5878 const size_t prev_i = timestamp_ranges.back().range_end;
5879 const QuicPacketNumber prev_packet_number =
5880 frame.received_packet_times[prev_i].first;
5881 const QuicTime prev_receive_timestamp =
5882 frame.received_packet_times[prev_i].second;
5883
5884 QUIC_DVLOG(3) << "prev_packet_number:" << prev_packet_number
5885 << ", packet_number:" << packet_number;
5886 if (prev_receive_timestamp < receive_timestamp ||
5887 prev_packet_number <= packet_number) {
5888 detailed_error = "Packet number and/or receive time not in order.";
5889 QUIC_BUG(quic_framer_ack_ts_packet_out_of_order)
5890 << detailed_error << " packet_number:" << packet_number
5891 << ", receive_timestamp:" << receive_timestamp
5892 << ", prev_packet_number:" << prev_packet_number
5893 << ", prev_receive_timestamp:" << prev_receive_timestamp;
5894 return {};
5895 }
5896
5897 if (prev_packet_number == packet_number + 1) {
5898 timestamp_ranges.back().range_end = i;
5899 } else {
5900 timestamp_ranges.push_back(AckTimestampRange());
5901 timestamp_ranges.back().gap = prev_packet_number - 2 - packet_number;
5902 timestamp_ranges.back().range_begin = i;
5903 timestamp_ranges.back().range_end = i;
5904 }
5905 }
5906
5907 return timestamp_ranges;
5908 }
5909
FrameAckTimestampRanges(const QuicAckFrame & frame,const absl::InlinedVector<AckTimestampRange,2> & timestamp_ranges,QuicDataWriter * writer) const5910 int64_t QuicFramer::FrameAckTimestampRanges(
5911 const QuicAckFrame& frame,
5912 const absl::InlinedVector<AckTimestampRange, 2>& timestamp_ranges,
5913 QuicDataWriter* writer) const {
5914 int64_t size = 0;
5915 auto maybe_write_var_int62 = [&](uint64_t value) {
5916 size += QuicDataWriter::GetVarInt62Len(value);
5917 if (writer != nullptr && !writer->WriteVarInt62(value)) {
5918 return false;
5919 }
5920 return true;
5921 };
5922
5923 if (!maybe_write_var_int62(timestamp_ranges.size())) {
5924 return -1;
5925 }
5926
5927 // |effective_prev_time| is the exponent-encoded timestamp of the previous
5928 // packet.
5929 absl::optional<QuicTime> effective_prev_time;
5930 for (const AckTimestampRange& range : timestamp_ranges) {
5931 QUIC_DVLOG(3) << "Range: gap:" << range.gap << ", beg:" << range.range_begin
5932 << ", end:" << range.range_end;
5933 if (!maybe_write_var_int62(range.gap)) {
5934 return -1;
5935 }
5936
5937 if (!maybe_write_var_int62(range.range_begin - range.range_end + 1)) {
5938 return -1;
5939 }
5940
5941 for (int64_t i = range.range_begin; i >= range.range_end; --i) {
5942 const QuicTime receive_timestamp = frame.received_packet_times[i].second;
5943 uint64_t time_delta;
5944 if (effective_prev_time.has_value()) {
5945 time_delta =
5946 (*effective_prev_time - receive_timestamp).ToMicroseconds();
5947 QUIC_DVLOG(3) << "time_delta:" << time_delta
5948 << ", exponent:" << receive_timestamps_exponent_
5949 << ", effective_prev_time:" << *effective_prev_time
5950 << ", recv_time:" << receive_timestamp;
5951 time_delta = time_delta >> receive_timestamps_exponent_;
5952 effective_prev_time = effective_prev_time.value() -
5953 QuicTime::Delta::FromMicroseconds(
5954 time_delta << receive_timestamps_exponent_);
5955 } else {
5956 // The first delta is from framer creation to the current receive
5957 // timestamp (forward in time), whereas in the common case subsequent
5958 // deltas move backwards in time.
5959 time_delta = (receive_timestamp - creation_time_).ToMicroseconds();
5960 QUIC_DVLOG(3) << "First time_delta:" << time_delta
5961 << ", exponent:" << receive_timestamps_exponent_
5962 << ", recv_time:" << receive_timestamp
5963 << ", creation_time:" << creation_time_;
5964 // Round up the first exponent-encoded time delta so that the next
5965 // receive timestamp is guaranteed to be decreasing.
5966 time_delta = ((time_delta - 1) >> receive_timestamps_exponent_) + 1;
5967 effective_prev_time =
5968 creation_time_ + QuicTime::Delta::FromMicroseconds(
5969 time_delta << receive_timestamps_exponent_);
5970 }
5971
5972 if (!maybe_write_var_int62(time_delta)) {
5973 return -1;
5974 }
5975 }
5976 }
5977
5978 return size;
5979 }
5980
AppendIetfTimestampsToAckFrame(const QuicAckFrame & frame,QuicDataWriter * writer)5981 bool QuicFramer::AppendIetfTimestampsToAckFrame(const QuicAckFrame& frame,
5982 QuicDataWriter* writer) {
5983 QUICHE_DCHECK(!frame.received_packet_times.empty());
5984 std::string detailed_error;
5985 const absl::InlinedVector<AckTimestampRange, 2> timestamp_ranges =
5986 GetAckTimestampRanges(frame, detailed_error);
5987 if (!detailed_error.empty()) {
5988 set_detailed_error(std::move(detailed_error));
5989 return false;
5990 }
5991
5992 // Compute the size first using a null writer.
5993 int64_t size =
5994 FrameAckTimestampRanges(frame, timestamp_ranges, /*writer=*/nullptr);
5995 if (size > static_cast<int64_t>(writer->capacity() - writer->length())) {
5996 QUIC_DVLOG(1) << "Insufficient room to write IETF ack receive timestamps. "
5997 "size_remain:"
5998 << (writer->capacity() - writer->length())
5999 << ", size_needed:" << size;
6000 // Write a Timestamp Range Count of 0.
6001 return writer->WriteVarInt62(0);
6002 }
6003
6004 return FrameAckTimestampRanges(frame, timestamp_ranges, writer) > 0;
6005 }
6006
AppendStopWaitingFrame(const QuicPacketHeader & header,const QuicStopWaitingFrame & frame,QuicDataWriter * writer)6007 bool QuicFramer::AppendStopWaitingFrame(const QuicPacketHeader& header,
6008 const QuicStopWaitingFrame& frame,
6009 QuicDataWriter* writer) {
6010 QUICHE_DCHECK(!version_.HasIetfInvariantHeader());
6011 QUICHE_DCHECK(frame.least_unacked.IsInitialized());
6012 QUICHE_DCHECK_GE(header.packet_number, frame.least_unacked);
6013 const uint64_t least_unacked_delta =
6014 header.packet_number - frame.least_unacked;
6015 const uint64_t length_shift = header.packet_number_length * 8;
6016
6017 if (least_unacked_delta >> length_shift > 0) {
6018 QUIC_BUG(quic_bug_10850_86)
6019 << "packet_number_length " << header.packet_number_length
6020 << " is too small for least_unacked_delta: " << least_unacked_delta
6021 << " packet_number:" << header.packet_number
6022 << " least_unacked:" << frame.least_unacked
6023 << " version:" << version_.transport_version;
6024 return false;
6025 }
6026 if (least_unacked_delta == 0) {
6027 return writer->WriteBytesToUInt64(header.packet_number_length,
6028 least_unacked_delta);
6029 }
6030 if (!AppendPacketNumber(header.packet_number_length,
6031 QuicPacketNumber(least_unacked_delta), writer)) {
6032 QUIC_BUG(quic_bug_10850_87)
6033 << " seq failed: " << header.packet_number_length;
6034 return false;
6035 }
6036
6037 return true;
6038 }
6039
AppendIetfAckFrameAndTypeByte(const QuicAckFrame & frame,QuicDataWriter * writer)6040 bool QuicFramer::AppendIetfAckFrameAndTypeByte(const QuicAckFrame& frame,
6041 QuicDataWriter* writer) {
6042 uint8_t type = IETF_ACK;
6043 uint64_t ecn_size = 0;
6044 if (UseIetfAckWithReceiveTimestamp(frame)) {
6045 type = IETF_ACK_RECEIVE_TIMESTAMPS;
6046 } else if (frame.ecn_counters.has_value()) {
6047 // Change frame type to ACK_ECN if any ECN count is available.
6048 type = IETF_ACK_ECN;
6049 ecn_size = AckEcnCountSize(frame);
6050 }
6051
6052 if (!writer->WriteVarInt62(type)) {
6053 set_detailed_error("No room for frame-type");
6054 return false;
6055 }
6056
6057 QuicPacketNumber largest_acked = LargestAcked(frame);
6058 if (!writer->WriteVarInt62(largest_acked.ToUint64())) {
6059 set_detailed_error("No room for largest-acked in ack frame");
6060 return false;
6061 }
6062
6063 uint64_t ack_delay_time_us = quiche::kVarInt62MaxValue;
6064 if (!frame.ack_delay_time.IsInfinite()) {
6065 QUICHE_DCHECK_LE(0u, frame.ack_delay_time.ToMicroseconds());
6066 ack_delay_time_us = frame.ack_delay_time.ToMicroseconds();
6067 ack_delay_time_us = ack_delay_time_us >> local_ack_delay_exponent_;
6068 }
6069
6070 if (!writer->WriteVarInt62(ack_delay_time_us)) {
6071 set_detailed_error("No room for ack-delay in ack frame");
6072 return false;
6073 }
6074
6075 if (frame.packets.Empty() || frame.packets.Max() != largest_acked) {
6076 QUIC_BUG(quic_bug_10850_88) << "Malformed ack frame: " << frame;
6077 set_detailed_error("Malformed ack frame");
6078 return false;
6079 }
6080
6081 // Latch ack_block_count for potential truncation.
6082 const uint64_t ack_block_count = frame.packets.NumIntervals() - 1;
6083 QuicDataWriter count_writer(QuicDataWriter::GetVarInt62Len(ack_block_count),
6084 writer->data() + writer->length());
6085 if (!writer->WriteVarInt62(ack_block_count)) {
6086 set_detailed_error("No room for ack block count in ack frame");
6087 return false;
6088 }
6089 auto iter = frame.packets.rbegin();
6090 if (!writer->WriteVarInt62(iter->Length() - 1)) {
6091 set_detailed_error("No room for first ack block in ack frame");
6092 return false;
6093 }
6094 QuicPacketNumber previous_smallest = iter->min();
6095 ++iter;
6096 // Append remaining ACK blocks.
6097 uint64_t appended_ack_blocks = 0;
6098 for (; iter != frame.packets.rend(); ++iter) {
6099 const uint64_t gap = previous_smallest - iter->max() - 1;
6100 const uint64_t ack_range = iter->Length() - 1;
6101
6102 if (type == IETF_ACK_RECEIVE_TIMESTAMPS &&
6103 writer->remaining() <
6104 static_cast<size_t>(QuicDataWriter::GetVarInt62Len(gap) +
6105 QuicDataWriter::GetVarInt62Len(ack_range) +
6106 QuicDataWriter::GetVarInt62Len(0))) {
6107 // If we write this ACK range we won't have space for a timestamp range
6108 // count of 0.
6109 break;
6110 } else if (writer->remaining() < ecn_size ||
6111 writer->remaining() - ecn_size <
6112 static_cast<size_t>(
6113 QuicDataWriter::GetVarInt62Len(gap) +
6114 QuicDataWriter::GetVarInt62Len(ack_range))) {
6115 // ACK range does not fit, truncate it.
6116 break;
6117 }
6118 const bool success =
6119 writer->WriteVarInt62(gap) && writer->WriteVarInt62(ack_range);
6120 QUICHE_DCHECK(success);
6121 previous_smallest = iter->min();
6122 ++appended_ack_blocks;
6123 }
6124
6125 if (appended_ack_blocks < ack_block_count) {
6126 // Truncation is needed, rewrite the ack block count.
6127 if (QuicDataWriter::GetVarInt62Len(appended_ack_blocks) !=
6128 QuicDataWriter::GetVarInt62Len(ack_block_count) ||
6129 !count_writer.WriteVarInt62(appended_ack_blocks)) {
6130 // This should never happen as ack_block_count is limited by
6131 // max_ack_ranges_.
6132 QUIC_BUG(quic_bug_10850_89)
6133 << "Ack frame truncation fails. ack_block_count: " << ack_block_count
6134 << ", appended count: " << appended_ack_blocks;
6135 set_detailed_error("ACK frame truncation fails");
6136 return false;
6137 }
6138 QUIC_DLOG(INFO) << ENDPOINT << "ACK ranges get truncated from "
6139 << ack_block_count << " to " << appended_ack_blocks;
6140 }
6141
6142 if (type == IETF_ACK_ECN) {
6143 // Encode the ECN counts.
6144 if (!writer->WriteVarInt62(frame.ecn_counters->ect0)) {
6145 set_detailed_error("No room for ect_0_count in ack frame");
6146 return false;
6147 }
6148 if (!writer->WriteVarInt62(frame.ecn_counters->ect1)) {
6149 set_detailed_error("No room for ect_1_count in ack frame");
6150 return false;
6151 }
6152 if (!writer->WriteVarInt62(frame.ecn_counters->ce)) {
6153 set_detailed_error("No room for ecn_ce_count in ack frame");
6154 return false;
6155 }
6156 }
6157
6158 if (type == IETF_ACK_RECEIVE_TIMESTAMPS) {
6159 if (!AppendIetfTimestampsToAckFrame(frame, writer)) {
6160 return false;
6161 }
6162 }
6163
6164 return true;
6165 }
6166
AppendRstStreamFrame(const QuicRstStreamFrame & frame,QuicDataWriter * writer)6167 bool QuicFramer::AppendRstStreamFrame(const QuicRstStreamFrame& frame,
6168 QuicDataWriter* writer) {
6169 if (VersionHasIetfQuicFrames(version_.transport_version)) {
6170 return AppendIetfResetStreamFrame(frame, writer);
6171 }
6172 if (!writer->WriteUInt32(frame.stream_id)) {
6173 return false;
6174 }
6175
6176 if (!writer->WriteUInt64(frame.byte_offset)) {
6177 return false;
6178 }
6179
6180 uint32_t error_code = static_cast<uint32_t>(frame.error_code);
6181 if (!writer->WriteUInt32(error_code)) {
6182 return false;
6183 }
6184
6185 return true;
6186 }
6187
AppendConnectionCloseFrame(const QuicConnectionCloseFrame & frame,QuicDataWriter * writer)6188 bool QuicFramer::AppendConnectionCloseFrame(
6189 const QuicConnectionCloseFrame& frame, QuicDataWriter* writer) {
6190 if (VersionHasIetfQuicFrames(version_.transport_version)) {
6191 return AppendIetfConnectionCloseFrame(frame, writer);
6192 }
6193 uint32_t error_code = static_cast<uint32_t>(frame.wire_error_code);
6194 if (!writer->WriteUInt32(error_code)) {
6195 return false;
6196 }
6197 if (!writer->WriteStringPiece16(TruncateErrorString(frame.error_details))) {
6198 return false;
6199 }
6200 return true;
6201 }
6202
AppendGoAwayFrame(const QuicGoAwayFrame & frame,QuicDataWriter * writer)6203 bool QuicFramer::AppendGoAwayFrame(const QuicGoAwayFrame& frame,
6204 QuicDataWriter* writer) {
6205 uint32_t error_code = static_cast<uint32_t>(frame.error_code);
6206 if (!writer->WriteUInt32(error_code)) {
6207 return false;
6208 }
6209 uint32_t stream_id = static_cast<uint32_t>(frame.last_good_stream_id);
6210 if (!writer->WriteUInt32(stream_id)) {
6211 return false;
6212 }
6213 if (!writer->WriteStringPiece16(TruncateErrorString(frame.reason_phrase))) {
6214 return false;
6215 }
6216 return true;
6217 }
6218
AppendWindowUpdateFrame(const QuicWindowUpdateFrame & frame,QuicDataWriter * writer)6219 bool QuicFramer::AppendWindowUpdateFrame(const QuicWindowUpdateFrame& frame,
6220 QuicDataWriter* writer) {
6221 uint32_t stream_id = static_cast<uint32_t>(frame.stream_id);
6222 if (!writer->WriteUInt32(stream_id)) {
6223 return false;
6224 }
6225 if (!writer->WriteUInt64(frame.max_data)) {
6226 return false;
6227 }
6228 return true;
6229 }
6230
AppendBlockedFrame(const QuicBlockedFrame & frame,QuicDataWriter * writer)6231 bool QuicFramer::AppendBlockedFrame(const QuicBlockedFrame& frame,
6232 QuicDataWriter* writer) {
6233 if (VersionHasIetfQuicFrames(version_.transport_version)) {
6234 if (frame.stream_id == QuicUtils::GetInvalidStreamId(transport_version())) {
6235 return AppendDataBlockedFrame(frame, writer);
6236 }
6237 return AppendStreamDataBlockedFrame(frame, writer);
6238 }
6239 uint32_t stream_id = static_cast<uint32_t>(frame.stream_id);
6240 if (!writer->WriteUInt32(stream_id)) {
6241 return false;
6242 }
6243 return true;
6244 }
6245
AppendPaddingFrame(const QuicPaddingFrame & frame,QuicDataWriter * writer)6246 bool QuicFramer::AppendPaddingFrame(const QuicPaddingFrame& frame,
6247 QuicDataWriter* writer) {
6248 if (frame.num_padding_bytes == 0) {
6249 return false;
6250 }
6251 if (frame.num_padding_bytes < 0) {
6252 QUIC_BUG_IF(quic_bug_12975_9, frame.num_padding_bytes != -1);
6253 writer->WritePadding();
6254 return true;
6255 }
6256 // Please note, num_padding_bytes includes type byte which has been written.
6257 return writer->WritePaddingBytes(frame.num_padding_bytes - 1);
6258 }
6259
AppendMessageFrameAndTypeByte(const QuicMessageFrame & frame,bool last_frame_in_packet,QuicDataWriter * writer)6260 bool QuicFramer::AppendMessageFrameAndTypeByte(const QuicMessageFrame& frame,
6261 bool last_frame_in_packet,
6262 QuicDataWriter* writer) {
6263 uint8_t type_byte;
6264 if (VersionHasIetfQuicFrames(version_.transport_version)) {
6265 type_byte = last_frame_in_packet ? IETF_EXTENSION_MESSAGE_NO_LENGTH_V99
6266 : IETF_EXTENSION_MESSAGE_V99;
6267 } else {
6268 type_byte = last_frame_in_packet ? IETF_EXTENSION_MESSAGE_NO_LENGTH
6269 : IETF_EXTENSION_MESSAGE;
6270 }
6271 if (!writer->WriteUInt8(type_byte)) {
6272 return false;
6273 }
6274 if (!last_frame_in_packet && !writer->WriteVarInt62(frame.message_length)) {
6275 return false;
6276 }
6277 for (const auto& slice : frame.message_data) {
6278 if (!writer->WriteBytes(slice.data(), slice.length())) {
6279 return false;
6280 }
6281 }
6282 return true;
6283 }
6284
RaiseError(QuicErrorCode error)6285 bool QuicFramer::RaiseError(QuicErrorCode error) {
6286 QUIC_DLOG(INFO) << ENDPOINT << "Error: " << QuicErrorCodeToString(error)
6287 << " detail: " << detailed_error_;
6288 set_error(error);
6289 if (visitor_) {
6290 visitor_->OnError(this);
6291 }
6292 return false;
6293 }
6294
IsVersionNegotiation(const QuicPacketHeader & header,bool packet_has_ietf_packet_header) const6295 bool QuicFramer::IsVersionNegotiation(
6296 const QuicPacketHeader& header, bool packet_has_ietf_packet_header) const {
6297 if (!packet_has_ietf_packet_header &&
6298 perspective_ == Perspective::IS_CLIENT) {
6299 return header.version_flag;
6300 }
6301 if (header.form == IETF_QUIC_SHORT_HEADER_PACKET) {
6302 return false;
6303 }
6304 return header.long_packet_type == VERSION_NEGOTIATION;
6305 }
6306
AppendIetfConnectionCloseFrame(const QuicConnectionCloseFrame & frame,QuicDataWriter * writer)6307 bool QuicFramer::AppendIetfConnectionCloseFrame(
6308 const QuicConnectionCloseFrame& frame, QuicDataWriter* writer) {
6309 if (frame.close_type != IETF_QUIC_TRANSPORT_CONNECTION_CLOSE &&
6310 frame.close_type != IETF_QUIC_APPLICATION_CONNECTION_CLOSE) {
6311 QUIC_BUG(quic_bug_10850_90)
6312 << "Invalid close_type for writing IETF CONNECTION CLOSE.";
6313 set_detailed_error("Invalid close_type for writing IETF CONNECTION CLOSE.");
6314 return false;
6315 }
6316
6317 if (!writer->WriteVarInt62(frame.wire_error_code)) {
6318 set_detailed_error("Can not write connection close frame error code");
6319 return false;
6320 }
6321
6322 if (frame.close_type == IETF_QUIC_TRANSPORT_CONNECTION_CLOSE) {
6323 // Write the frame-type of the frame causing the error only
6324 // if it's a CONNECTION_CLOSE/Transport.
6325 if (!writer->WriteVarInt62(frame.transport_close_frame_type)) {
6326 set_detailed_error("Writing frame type failed.");
6327 return false;
6328 }
6329 }
6330
6331 // There may be additional error information available in the extracted error
6332 // code. Encode the error information in the reason phrase and serialize the
6333 // result.
6334 std::string final_error_string =
6335 GenerateErrorString(frame.error_details, frame.quic_error_code);
6336 if (!writer->WriteStringPieceVarInt62(
6337 TruncateErrorString(final_error_string))) {
6338 set_detailed_error("Can not write connection close phrase");
6339 return false;
6340 }
6341 return true;
6342 }
6343
ProcessIetfConnectionCloseFrame(QuicDataReader * reader,QuicConnectionCloseType type,QuicConnectionCloseFrame * frame)6344 bool QuicFramer::ProcessIetfConnectionCloseFrame(
6345 QuicDataReader* reader, QuicConnectionCloseType type,
6346 QuicConnectionCloseFrame* frame) {
6347 frame->close_type = type;
6348
6349 uint64_t error_code;
6350 if (!reader->ReadVarInt62(&error_code)) {
6351 set_detailed_error("Unable to read connection close error code.");
6352 return false;
6353 }
6354
6355 frame->wire_error_code = error_code;
6356
6357 if (type == IETF_QUIC_TRANSPORT_CONNECTION_CLOSE) {
6358 // The frame-type of the frame causing the error is present only
6359 // if it's a CONNECTION_CLOSE/Transport.
6360 if (!reader->ReadVarInt62(&frame->transport_close_frame_type)) {
6361 set_detailed_error("Unable to read connection close frame type.");
6362 return false;
6363 }
6364 }
6365
6366 uint64_t phrase_length;
6367 if (!reader->ReadVarInt62(&phrase_length)) {
6368 set_detailed_error("Unable to read connection close error details.");
6369 return false;
6370 }
6371
6372 absl::string_view phrase;
6373 if (!reader->ReadStringPiece(&phrase, static_cast<size_t>(phrase_length))) {
6374 set_detailed_error("Unable to read connection close error details.");
6375 return false;
6376 }
6377 frame->error_details = std::string(phrase);
6378
6379 // The frame may have an extracted error code in it. Look for it and
6380 // extract it. If it's not present, MaybeExtract will return
6381 // QUIC_IETF_GQUIC_ERROR_MISSING.
6382 MaybeExtractQuicErrorCode(frame);
6383 return true;
6384 }
6385
6386 // IETF Quic Path Challenge/Response frames.
ProcessPathChallengeFrame(QuicDataReader * reader,QuicPathChallengeFrame * frame)6387 bool QuicFramer::ProcessPathChallengeFrame(QuicDataReader* reader,
6388 QuicPathChallengeFrame* frame) {
6389 if (!reader->ReadBytes(frame->data_buffer.data(),
6390 frame->data_buffer.size())) {
6391 set_detailed_error("Can not read path challenge data.");
6392 return false;
6393 }
6394 return true;
6395 }
6396
ProcessPathResponseFrame(QuicDataReader * reader,QuicPathResponseFrame * frame)6397 bool QuicFramer::ProcessPathResponseFrame(QuicDataReader* reader,
6398 QuicPathResponseFrame* frame) {
6399 if (!reader->ReadBytes(frame->data_buffer.data(),
6400 frame->data_buffer.size())) {
6401 set_detailed_error("Can not read path response data.");
6402 return false;
6403 }
6404 return true;
6405 }
6406
AppendPathChallengeFrame(const QuicPathChallengeFrame & frame,QuicDataWriter * writer)6407 bool QuicFramer::AppendPathChallengeFrame(const QuicPathChallengeFrame& frame,
6408 QuicDataWriter* writer) {
6409 if (!writer->WriteBytes(frame.data_buffer.data(), frame.data_buffer.size())) {
6410 set_detailed_error("Writing Path Challenge data failed.");
6411 return false;
6412 }
6413 return true;
6414 }
6415
AppendPathResponseFrame(const QuicPathResponseFrame & frame,QuicDataWriter * writer)6416 bool QuicFramer::AppendPathResponseFrame(const QuicPathResponseFrame& frame,
6417 QuicDataWriter* writer) {
6418 if (!writer->WriteBytes(frame.data_buffer.data(), frame.data_buffer.size())) {
6419 set_detailed_error("Writing Path Response data failed.");
6420 return false;
6421 }
6422 return true;
6423 }
6424
6425 // Add a new ietf-format stream reset frame.
6426 // General format is
6427 // stream id
6428 // application error code
6429 // final offset
AppendIetfResetStreamFrame(const QuicRstStreamFrame & frame,QuicDataWriter * writer)6430 bool QuicFramer::AppendIetfResetStreamFrame(const QuicRstStreamFrame& frame,
6431 QuicDataWriter* writer) {
6432 if (!writer->WriteVarInt62(static_cast<uint64_t>(frame.stream_id))) {
6433 set_detailed_error("Writing reset-stream stream id failed.");
6434 return false;
6435 }
6436 if (!writer->WriteVarInt62(static_cast<uint64_t>(frame.ietf_error_code))) {
6437 set_detailed_error("Writing reset-stream error code failed.");
6438 return false;
6439 }
6440 if (!writer->WriteVarInt62(static_cast<uint64_t>(frame.byte_offset))) {
6441 set_detailed_error("Writing reset-stream final-offset failed.");
6442 return false;
6443 }
6444 return true;
6445 }
6446
ProcessIetfResetStreamFrame(QuicDataReader * reader,QuicRstStreamFrame * frame)6447 bool QuicFramer::ProcessIetfResetStreamFrame(QuicDataReader* reader,
6448 QuicRstStreamFrame* frame) {
6449 // Get Stream ID from frame. ReadVarIntStreamID returns false
6450 // if either A) there is a read error or B) the resulting value of
6451 // the Stream ID is larger than the maximum allowed value.
6452 if (!ReadUint32FromVarint62(reader, IETF_RST_STREAM, &frame->stream_id)) {
6453 return false;
6454 }
6455
6456 if (!reader->ReadVarInt62(&frame->ietf_error_code)) {
6457 set_detailed_error("Unable to read rst stream error code.");
6458 return false;
6459 }
6460
6461 frame->error_code =
6462 IetfResetStreamErrorCodeToRstStreamErrorCode(frame->ietf_error_code);
6463
6464 if (!reader->ReadVarInt62(&frame->byte_offset)) {
6465 set_detailed_error("Unable to read rst stream sent byte offset.");
6466 return false;
6467 }
6468 return true;
6469 }
6470
ProcessStopSendingFrame(QuicDataReader * reader,QuicStopSendingFrame * stop_sending_frame)6471 bool QuicFramer::ProcessStopSendingFrame(
6472 QuicDataReader* reader, QuicStopSendingFrame* stop_sending_frame) {
6473 if (!ReadUint32FromVarint62(reader, IETF_STOP_SENDING,
6474 &stop_sending_frame->stream_id)) {
6475 return false;
6476 }
6477
6478 if (!reader->ReadVarInt62(&stop_sending_frame->ietf_error_code)) {
6479 set_detailed_error("Unable to read stop sending application error code.");
6480 return false;
6481 }
6482
6483 stop_sending_frame->error_code = IetfResetStreamErrorCodeToRstStreamErrorCode(
6484 stop_sending_frame->ietf_error_code);
6485 return true;
6486 }
6487
AppendStopSendingFrame(const QuicStopSendingFrame & stop_sending_frame,QuicDataWriter * writer)6488 bool QuicFramer::AppendStopSendingFrame(
6489 const QuicStopSendingFrame& stop_sending_frame, QuicDataWriter* writer) {
6490 if (!writer->WriteVarInt62(stop_sending_frame.stream_id)) {
6491 set_detailed_error("Can not write stop sending stream id");
6492 return false;
6493 }
6494 if (!writer->WriteVarInt62(
6495 static_cast<uint64_t>(stop_sending_frame.ietf_error_code))) {
6496 set_detailed_error("Can not write application error code");
6497 return false;
6498 }
6499 return true;
6500 }
6501
6502 // Append/process IETF-Format MAX_DATA Frame
AppendMaxDataFrame(const QuicWindowUpdateFrame & frame,QuicDataWriter * writer)6503 bool QuicFramer::AppendMaxDataFrame(const QuicWindowUpdateFrame& frame,
6504 QuicDataWriter* writer) {
6505 if (!writer->WriteVarInt62(frame.max_data)) {
6506 set_detailed_error("Can not write MAX_DATA byte-offset");
6507 return false;
6508 }
6509 return true;
6510 }
6511
ProcessMaxDataFrame(QuicDataReader * reader,QuicWindowUpdateFrame * frame)6512 bool QuicFramer::ProcessMaxDataFrame(QuicDataReader* reader,
6513 QuicWindowUpdateFrame* frame) {
6514 frame->stream_id = QuicUtils::GetInvalidStreamId(transport_version());
6515 if (!reader->ReadVarInt62(&frame->max_data)) {
6516 set_detailed_error("Can not read MAX_DATA byte-offset");
6517 return false;
6518 }
6519 return true;
6520 }
6521
6522 // Append/process IETF-Format MAX_STREAM_DATA Frame
AppendMaxStreamDataFrame(const QuicWindowUpdateFrame & frame,QuicDataWriter * writer)6523 bool QuicFramer::AppendMaxStreamDataFrame(const QuicWindowUpdateFrame& frame,
6524 QuicDataWriter* writer) {
6525 if (!writer->WriteVarInt62(frame.stream_id)) {
6526 set_detailed_error("Can not write MAX_STREAM_DATA stream id");
6527 return false;
6528 }
6529 if (!writer->WriteVarInt62(frame.max_data)) {
6530 set_detailed_error("Can not write MAX_STREAM_DATA byte-offset");
6531 return false;
6532 }
6533 return true;
6534 }
6535
ProcessMaxStreamDataFrame(QuicDataReader * reader,QuicWindowUpdateFrame * frame)6536 bool QuicFramer::ProcessMaxStreamDataFrame(QuicDataReader* reader,
6537 QuicWindowUpdateFrame* frame) {
6538 if (!ReadUint32FromVarint62(reader, IETF_MAX_STREAM_DATA,
6539 &frame->stream_id)) {
6540 return false;
6541 }
6542 if (!reader->ReadVarInt62(&frame->max_data)) {
6543 set_detailed_error("Can not read MAX_STREAM_DATA byte-count");
6544 return false;
6545 }
6546 return true;
6547 }
6548
AppendMaxStreamsFrame(const QuicMaxStreamsFrame & frame,QuicDataWriter * writer)6549 bool QuicFramer::AppendMaxStreamsFrame(const QuicMaxStreamsFrame& frame,
6550 QuicDataWriter* writer) {
6551 if (!writer->WriteVarInt62(frame.stream_count)) {
6552 set_detailed_error("Can not write MAX_STREAMS stream count");
6553 return false;
6554 }
6555 return true;
6556 }
6557
ProcessMaxStreamsFrame(QuicDataReader * reader,QuicMaxStreamsFrame * frame,uint64_t frame_type)6558 bool QuicFramer::ProcessMaxStreamsFrame(QuicDataReader* reader,
6559 QuicMaxStreamsFrame* frame,
6560 uint64_t frame_type) {
6561 if (!ReadUint32FromVarint62(reader,
6562 static_cast<QuicIetfFrameType>(frame_type),
6563 &frame->stream_count)) {
6564 return false;
6565 }
6566 frame->unidirectional = (frame_type == IETF_MAX_STREAMS_UNIDIRECTIONAL);
6567 return true;
6568 }
6569
AppendDataBlockedFrame(const QuicBlockedFrame & frame,QuicDataWriter * writer)6570 bool QuicFramer::AppendDataBlockedFrame(const QuicBlockedFrame& frame,
6571 QuicDataWriter* writer) {
6572 if (!writer->WriteVarInt62(frame.offset)) {
6573 set_detailed_error("Can not write blocked offset.");
6574 return false;
6575 }
6576 return true;
6577 }
6578
ProcessDataBlockedFrame(QuicDataReader * reader,QuicBlockedFrame * frame)6579 bool QuicFramer::ProcessDataBlockedFrame(QuicDataReader* reader,
6580 QuicBlockedFrame* frame) {
6581 // Indicates that it is a BLOCKED frame (as opposed to STREAM_BLOCKED).
6582 frame->stream_id = QuicUtils::GetInvalidStreamId(transport_version());
6583 if (!reader->ReadVarInt62(&frame->offset)) {
6584 set_detailed_error("Can not read blocked offset.");
6585 return false;
6586 }
6587 return true;
6588 }
6589
AppendStreamDataBlockedFrame(const QuicBlockedFrame & frame,QuicDataWriter * writer)6590 bool QuicFramer::AppendStreamDataBlockedFrame(const QuicBlockedFrame& frame,
6591 QuicDataWriter* writer) {
6592 if (!writer->WriteVarInt62(frame.stream_id)) {
6593 set_detailed_error("Can not write stream blocked stream id.");
6594 return false;
6595 }
6596 if (!writer->WriteVarInt62(frame.offset)) {
6597 set_detailed_error("Can not write stream blocked offset.");
6598 return false;
6599 }
6600 return true;
6601 }
6602
ProcessStreamDataBlockedFrame(QuicDataReader * reader,QuicBlockedFrame * frame)6603 bool QuicFramer::ProcessStreamDataBlockedFrame(QuicDataReader* reader,
6604 QuicBlockedFrame* frame) {
6605 if (!ReadUint32FromVarint62(reader, IETF_STREAM_DATA_BLOCKED,
6606 &frame->stream_id)) {
6607 return false;
6608 }
6609 if (!reader->ReadVarInt62(&frame->offset)) {
6610 set_detailed_error("Can not read stream blocked offset.");
6611 return false;
6612 }
6613 return true;
6614 }
6615
AppendStreamsBlockedFrame(const QuicStreamsBlockedFrame & frame,QuicDataWriter * writer)6616 bool QuicFramer::AppendStreamsBlockedFrame(const QuicStreamsBlockedFrame& frame,
6617 QuicDataWriter* writer) {
6618 if (!writer->WriteVarInt62(frame.stream_count)) {
6619 set_detailed_error("Can not write STREAMS_BLOCKED stream count");
6620 return false;
6621 }
6622 return true;
6623 }
6624
ProcessStreamsBlockedFrame(QuicDataReader * reader,QuicStreamsBlockedFrame * frame,uint64_t frame_type)6625 bool QuicFramer::ProcessStreamsBlockedFrame(QuicDataReader* reader,
6626 QuicStreamsBlockedFrame* frame,
6627 uint64_t frame_type) {
6628 if (!ReadUint32FromVarint62(reader,
6629 static_cast<QuicIetfFrameType>(frame_type),
6630 &frame->stream_count)) {
6631 return false;
6632 }
6633 if (frame->stream_count > QuicUtils::GetMaxStreamCount()) {
6634 // If stream count is such that the resulting stream ID would exceed our
6635 // implementation limit, generate an error.
6636 set_detailed_error(
6637 "STREAMS_BLOCKED stream count exceeds implementation limit.");
6638 return false;
6639 }
6640 frame->unidirectional = (frame_type == IETF_STREAMS_BLOCKED_UNIDIRECTIONAL);
6641 return true;
6642 }
6643
AppendNewConnectionIdFrame(const QuicNewConnectionIdFrame & frame,QuicDataWriter * writer)6644 bool QuicFramer::AppendNewConnectionIdFrame(
6645 const QuicNewConnectionIdFrame& frame, QuicDataWriter* writer) {
6646 if (!writer->WriteVarInt62(frame.sequence_number)) {
6647 set_detailed_error("Can not write New Connection ID sequence number");
6648 return false;
6649 }
6650 if (!writer->WriteVarInt62(frame.retire_prior_to)) {
6651 set_detailed_error("Can not write New Connection ID retire_prior_to");
6652 return false;
6653 }
6654 if (!writer->WriteLengthPrefixedConnectionId(frame.connection_id)) {
6655 set_detailed_error("Can not write New Connection ID frame connection ID");
6656 return false;
6657 }
6658
6659 if (!writer->WriteBytes(
6660 static_cast<const void*>(&frame.stateless_reset_token),
6661 sizeof(frame.stateless_reset_token))) {
6662 set_detailed_error("Can not write New Connection ID Reset Token");
6663 return false;
6664 }
6665 return true;
6666 }
6667
ProcessNewConnectionIdFrame(QuicDataReader * reader,QuicNewConnectionIdFrame * frame)6668 bool QuicFramer::ProcessNewConnectionIdFrame(QuicDataReader* reader,
6669 QuicNewConnectionIdFrame* frame) {
6670 if (!reader->ReadVarInt62(&frame->sequence_number)) {
6671 set_detailed_error(
6672 "Unable to read new connection ID frame sequence number.");
6673 return false;
6674 }
6675
6676 if (!reader->ReadVarInt62(&frame->retire_prior_to)) {
6677 set_detailed_error(
6678 "Unable to read new connection ID frame retire_prior_to.");
6679 return false;
6680 }
6681 if (frame->retire_prior_to > frame->sequence_number) {
6682 set_detailed_error("Retire_prior_to > sequence_number.");
6683 return false;
6684 }
6685
6686 if (!reader->ReadLengthPrefixedConnectionId(&frame->connection_id)) {
6687 set_detailed_error("Unable to read new connection ID frame connection id.");
6688 return false;
6689 }
6690
6691 if (!QuicUtils::IsConnectionIdValidForVersion(frame->connection_id,
6692 transport_version())) {
6693 set_detailed_error("Invalid new connection ID length for version.");
6694 return false;
6695 }
6696
6697 if (!reader->ReadBytes(&frame->stateless_reset_token,
6698 sizeof(frame->stateless_reset_token))) {
6699 set_detailed_error("Can not read new connection ID frame reset token.");
6700 return false;
6701 }
6702 return true;
6703 }
6704
AppendRetireConnectionIdFrame(const QuicRetireConnectionIdFrame & frame,QuicDataWriter * writer)6705 bool QuicFramer::AppendRetireConnectionIdFrame(
6706 const QuicRetireConnectionIdFrame& frame, QuicDataWriter* writer) {
6707 if (!writer->WriteVarInt62(frame.sequence_number)) {
6708 set_detailed_error("Can not write Retire Connection ID sequence number");
6709 return false;
6710 }
6711 return true;
6712 }
6713
ProcessRetireConnectionIdFrame(QuicDataReader * reader,QuicRetireConnectionIdFrame * frame)6714 bool QuicFramer::ProcessRetireConnectionIdFrame(
6715 QuicDataReader* reader, QuicRetireConnectionIdFrame* frame) {
6716 if (!reader->ReadVarInt62(&frame->sequence_number)) {
6717 set_detailed_error(
6718 "Unable to read retire connection ID frame sequence number.");
6719 return false;
6720 }
6721 return true;
6722 }
6723
ReadUint32FromVarint62(QuicDataReader * reader,QuicIetfFrameType type,QuicStreamId * id)6724 bool QuicFramer::ReadUint32FromVarint62(QuicDataReader* reader,
6725 QuicIetfFrameType type,
6726 QuicStreamId* id) {
6727 uint64_t temp_uint64;
6728 if (!reader->ReadVarInt62(&temp_uint64)) {
6729 set_detailed_error("Unable to read " + QuicIetfFrameTypeString(type) +
6730 " frame stream id/count.");
6731 return false;
6732 }
6733 if (temp_uint64 > kMaxQuicStreamId) {
6734 set_detailed_error("Stream id/count of " + QuicIetfFrameTypeString(type) +
6735 "frame is too large.");
6736 return false;
6737 }
6738 *id = static_cast<uint32_t>(temp_uint64);
6739 return true;
6740 }
6741
GetStreamFrameTypeByte(const QuicStreamFrame & frame,bool last_frame_in_packet) const6742 uint8_t QuicFramer::GetStreamFrameTypeByte(const QuicStreamFrame& frame,
6743 bool last_frame_in_packet) const {
6744 if (VersionHasIetfQuicFrames(version_.transport_version)) {
6745 return GetIetfStreamFrameTypeByte(frame, last_frame_in_packet);
6746 }
6747 uint8_t type_byte = 0;
6748 // Fin bit.
6749 type_byte |= frame.fin ? kQuicStreamFinMask : 0;
6750
6751 // Data Length bit.
6752 type_byte <<= kQuicStreamDataLengthShift;
6753 type_byte |= last_frame_in_packet ? 0 : kQuicStreamDataLengthMask;
6754
6755 // Offset 3 bits.
6756 type_byte <<= kQuicStreamShift;
6757 const size_t offset_len = GetStreamOffsetSize(frame.offset);
6758 if (offset_len > 0) {
6759 type_byte |= offset_len - 1;
6760 }
6761
6762 // stream id 2 bits.
6763 type_byte <<= kQuicStreamIdShift;
6764 type_byte |= GetStreamIdSize(frame.stream_id) - 1;
6765 type_byte |= kQuicFrameTypeStreamMask; // Set Stream Frame Type to 1.
6766
6767 return type_byte;
6768 }
6769
GetIetfStreamFrameTypeByte(const QuicStreamFrame & frame,bool last_frame_in_packet) const6770 uint8_t QuicFramer::GetIetfStreamFrameTypeByte(
6771 const QuicStreamFrame& frame, bool last_frame_in_packet) const {
6772 QUICHE_DCHECK(VersionHasIetfQuicFrames(version_.transport_version));
6773 uint8_t type_byte = IETF_STREAM;
6774 if (!last_frame_in_packet) {
6775 type_byte |= IETF_STREAM_FRAME_LEN_BIT;
6776 }
6777 if (frame.offset != 0) {
6778 type_byte |= IETF_STREAM_FRAME_OFF_BIT;
6779 }
6780 if (frame.fin) {
6781 type_byte |= IETF_STREAM_FRAME_FIN_BIT;
6782 }
6783 return type_byte;
6784 }
6785
InferPacketHeaderTypeFromVersion()6786 void QuicFramer::InferPacketHeaderTypeFromVersion() {
6787 // This function should only be called when server connection negotiates the
6788 // version.
6789 QUICHE_DCHECK_EQ(perspective_, Perspective::IS_SERVER);
6790 QUICHE_DCHECK(!infer_packet_header_type_from_version_);
6791 infer_packet_header_type_from_version_ = true;
6792 }
6793
EnableMultiplePacketNumberSpacesSupport()6794 void QuicFramer::EnableMultiplePacketNumberSpacesSupport() {
6795 if (supports_multiple_packet_number_spaces_) {
6796 QUIC_BUG(quic_bug_10850_91)
6797 << "Multiple packet number spaces has already been enabled";
6798 return;
6799 }
6800 if (largest_packet_number_.IsInitialized()) {
6801 QUIC_BUG(quic_bug_10850_92)
6802 << "Try to enable multiple packet number spaces support after any "
6803 "packet has been received.";
6804 return;
6805 }
6806
6807 supports_multiple_packet_number_spaces_ = true;
6808 }
6809
6810 // static
ParsePublicHeaderDispatcher(const QuicEncryptedPacket & packet,uint8_t expected_destination_connection_id_length,PacketHeaderFormat * format,QuicLongHeaderType * long_packet_type,bool * version_present,bool * has_length_prefix,QuicVersionLabel * version_label,ParsedQuicVersion * parsed_version,QuicConnectionId * destination_connection_id,QuicConnectionId * source_connection_id,absl::optional<absl::string_view> * retry_token,std::string * detailed_error)6811 QuicErrorCode QuicFramer::ParsePublicHeaderDispatcher(
6812 const QuicEncryptedPacket& packet,
6813 uint8_t expected_destination_connection_id_length,
6814 PacketHeaderFormat* format, QuicLongHeaderType* long_packet_type,
6815 bool* version_present, bool* has_length_prefix,
6816 QuicVersionLabel* version_label, ParsedQuicVersion* parsed_version,
6817 QuicConnectionId* destination_connection_id,
6818 QuicConnectionId* source_connection_id,
6819 absl::optional<absl::string_view>* retry_token,
6820 std::string* detailed_error) {
6821 QuicDataReader reader(packet.data(), packet.length());
6822 if (reader.IsDoneReading()) {
6823 *detailed_error = "Unable to read first byte.";
6824 return QUIC_INVALID_PACKET_HEADER;
6825 }
6826 const uint8_t first_byte = reader.PeekByte();
6827 if ((first_byte & FLAGS_LONG_HEADER) == 0 &&
6828 (first_byte & FLAGS_FIXED_BIT) == 0 &&
6829 (first_byte & FLAGS_DEMULTIPLEXING_BIT) == 0) {
6830 // All versions of Google QUIC up to and including Q043 set
6831 // FLAGS_DEMULTIPLEXING_BIT to one on all client-to-server packets. Q044
6832 // and Q045 were never default-enabled in production. All subsequent
6833 // versions of Google QUIC (starting with Q046) require FLAGS_FIXED_BIT to
6834 // be set to one on all packets. All versions of IETF QUIC (since
6835 // draft-ietf-quic-transport-17 which was earlier than the first IETF QUIC
6836 // version that was deployed in production by any implementation) also
6837 // require FLAGS_FIXED_BIT to be set to one on all packets. If a packet
6838 // has the FLAGS_LONG_HEADER bit set to one, it could be a first flight
6839 // from an unknown future version that allows the other two bits to be set
6840 // to zero. Based on this, packets that have all three of those bits set
6841 // to zero are known to be invalid.
6842 *detailed_error = "Invalid flags.";
6843 return QUIC_INVALID_PACKET_HEADER;
6844 }
6845 const bool ietf_format = QuicUtils::IsIetfPacketHeader(first_byte);
6846 uint8_t unused_first_byte;
6847 quiche::QuicheVariableLengthIntegerLength retry_token_length_length;
6848 absl::string_view maybe_retry_token;
6849 QuicErrorCode error_code = ParsePublicHeader(
6850 &reader, expected_destination_connection_id_length, ietf_format,
6851 &unused_first_byte, format, version_present, has_length_prefix,
6852 version_label, parsed_version, destination_connection_id,
6853 source_connection_id, long_packet_type, &retry_token_length_length,
6854 &maybe_retry_token, detailed_error);
6855 if (retry_token_length_length != quiche::VARIABLE_LENGTH_INTEGER_LENGTH_0) {
6856 *retry_token = maybe_retry_token;
6857 } else {
6858 retry_token->reset();
6859 }
6860 return error_code;
6861 }
6862
6863 // static
ParsePublicHeaderDispatcherShortHeaderLengthUnknown(const QuicEncryptedPacket & packet,PacketHeaderFormat * format,QuicLongHeaderType * long_packet_type,bool * version_present,bool * has_length_prefix,QuicVersionLabel * version_label,ParsedQuicVersion * parsed_version,QuicConnectionId * destination_connection_id,QuicConnectionId * source_connection_id,absl::optional<absl::string_view> * retry_token,std::string * detailed_error,ConnectionIdGeneratorInterface & generator)6864 QuicErrorCode QuicFramer::ParsePublicHeaderDispatcherShortHeaderLengthUnknown(
6865 const QuicEncryptedPacket& packet, PacketHeaderFormat* format,
6866 QuicLongHeaderType* long_packet_type, bool* version_present,
6867 bool* has_length_prefix, QuicVersionLabel* version_label,
6868 ParsedQuicVersion* parsed_version,
6869 QuicConnectionId* destination_connection_id,
6870 QuicConnectionId* source_connection_id,
6871 absl::optional<absl::string_view>* retry_token, std::string* detailed_error,
6872 ConnectionIdGeneratorInterface& generator) {
6873 QuicDataReader reader(packet.data(), packet.length());
6874 // Get the first two bytes.
6875 if (reader.BytesRemaining() < 2) {
6876 *detailed_error = "Unable to read first two bytes.";
6877 return QUIC_INVALID_PACKET_HEADER;
6878 }
6879 uint8_t two_bytes[2];
6880 reader.ReadBytes(two_bytes, 2);
6881 uint8_t expected_destination_connection_id_length =
6882 (!QuicUtils::IsIetfPacketHeader(two_bytes[0]) ||
6883 two_bytes[0] & FLAGS_LONG_HEADER)
6884 ? 0
6885 : generator.ConnectionIdLength(two_bytes[1]);
6886 return ParsePublicHeaderDispatcher(
6887 packet, expected_destination_connection_id_length, format,
6888 long_packet_type, version_present, has_length_prefix, version_label,
6889 parsed_version, destination_connection_id, source_connection_id,
6890 retry_token, detailed_error);
6891 }
6892
6893 // static
ParsePublicHeaderGoogleQuic(QuicDataReader * reader,uint8_t * first_byte,PacketHeaderFormat * format,bool * version_present,QuicVersionLabel * version_label,ParsedQuicVersion * parsed_version,QuicConnectionId * destination_connection_id,std::string * detailed_error)6894 QuicErrorCode QuicFramer::ParsePublicHeaderGoogleQuic(
6895 QuicDataReader* reader, uint8_t* first_byte, PacketHeaderFormat* format,
6896 bool* version_present, QuicVersionLabel* version_label,
6897 ParsedQuicVersion* parsed_version,
6898 QuicConnectionId* destination_connection_id, std::string* detailed_error) {
6899 *format = GOOGLE_QUIC_PACKET;
6900 *version_present = (*first_byte & PACKET_PUBLIC_FLAGS_VERSION) != 0;
6901 uint8_t destination_connection_id_length = 0;
6902 if ((*first_byte & PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID) != 0) {
6903 destination_connection_id_length = kQuicDefaultConnectionIdLength;
6904 }
6905 if (!reader->ReadConnectionId(destination_connection_id,
6906 destination_connection_id_length)) {
6907 *detailed_error = "Unable to read ConnectionId.";
6908 return QUIC_INVALID_PACKET_HEADER;
6909 }
6910 if (*version_present) {
6911 if (!ProcessVersionLabel(reader, version_label)) {
6912 *detailed_error = "Unable to read protocol version.";
6913 return QUIC_INVALID_PACKET_HEADER;
6914 }
6915 *parsed_version = ParseQuicVersionLabel(*version_label);
6916 }
6917 return QUIC_NO_ERROR;
6918 }
6919
6920 namespace {
6921
6922 const QuicVersionLabel kProxVersionLabel = 0x50524F58; // "PROX"
6923
PacketHasLengthPrefixedConnectionIds(const QuicDataReader & reader,ParsedQuicVersion parsed_version,QuicVersionLabel version_label,uint8_t first_byte)6924 inline bool PacketHasLengthPrefixedConnectionIds(
6925 const QuicDataReader& reader, ParsedQuicVersion parsed_version,
6926 QuicVersionLabel version_label, uint8_t first_byte) {
6927 if (parsed_version.IsKnown()) {
6928 return parsed_version.HasLengthPrefixedConnectionIds();
6929 }
6930
6931 // Received unsupported version, check known old unsupported versions.
6932 if (QuicVersionLabelUses4BitConnectionIdLength(version_label)) {
6933 return false;
6934 }
6935
6936 // Received unknown version, check connection ID length byte.
6937 if (reader.IsDoneReading()) {
6938 // This check is required to safely peek the connection ID length byte.
6939 return true;
6940 }
6941 const uint8_t connection_id_length_byte = reader.PeekByte();
6942
6943 // Check for packets produced by older versions of
6944 // QuicFramer::WriteClientVersionNegotiationProbePacket
6945 if (first_byte == 0xc0 && (connection_id_length_byte & 0x0f) == 0 &&
6946 connection_id_length_byte >= 0x50 && version_label == 0xcabadaba) {
6947 return false;
6948 }
6949
6950 // Check for munged packets with version tag PROX.
6951 if ((connection_id_length_byte & 0x0f) == 0 &&
6952 connection_id_length_byte >= 0x20 && version_label == kProxVersionLabel) {
6953 return false;
6954 }
6955
6956 return true;
6957 }
6958
ParseLongHeaderConnectionIds(QuicDataReader & reader,bool has_length_prefix,QuicVersionLabel version_label,QuicConnectionId & destination_connection_id,QuicConnectionId & source_connection_id,std::string & detailed_error)6959 inline bool ParseLongHeaderConnectionIds(
6960 QuicDataReader& reader, bool has_length_prefix,
6961 QuicVersionLabel version_label, QuicConnectionId& destination_connection_id,
6962 QuicConnectionId& source_connection_id, std::string& detailed_error) {
6963 if (has_length_prefix) {
6964 if (!reader.ReadLengthPrefixedConnectionId(&destination_connection_id)) {
6965 detailed_error = "Unable to read destination connection ID.";
6966 return false;
6967 }
6968 if (!reader.ReadLengthPrefixedConnectionId(&source_connection_id)) {
6969 if (version_label == kProxVersionLabel) {
6970 // The "PROX" version does not follow the length-prefixed invariants,
6971 // and can therefore attempt to read a payload byte and interpret it
6972 // as the source connection ID length, which could fail to parse.
6973 // In that scenario we keep the source connection ID empty but mark
6974 // parsing as successful.
6975 return true;
6976 }
6977 detailed_error = "Unable to read source connection ID.";
6978 return false;
6979 }
6980 } else {
6981 // Parse connection ID lengths.
6982 uint8_t connection_id_lengths_byte;
6983 if (!reader.ReadUInt8(&connection_id_lengths_byte)) {
6984 detailed_error = "Unable to read connection ID lengths.";
6985 return false;
6986 }
6987 uint8_t destination_connection_id_length =
6988 (connection_id_lengths_byte & kDestinationConnectionIdLengthMask) >> 4;
6989 if (destination_connection_id_length != 0) {
6990 destination_connection_id_length += kConnectionIdLengthAdjustment;
6991 }
6992 uint8_t source_connection_id_length =
6993 connection_id_lengths_byte & kSourceConnectionIdLengthMask;
6994 if (source_connection_id_length != 0) {
6995 source_connection_id_length += kConnectionIdLengthAdjustment;
6996 }
6997
6998 // Read destination connection ID.
6999 if (!reader.ReadConnectionId(&destination_connection_id,
7000 destination_connection_id_length)) {
7001 detailed_error = "Unable to read destination connection ID.";
7002 return false;
7003 }
7004
7005 // Read source connection ID.
7006 if (!reader.ReadConnectionId(&source_connection_id,
7007 source_connection_id_length)) {
7008 detailed_error = "Unable to read source connection ID.";
7009 return false;
7010 }
7011 }
7012 return true;
7013 }
7014
7015 } // namespace
7016
7017 // static
ParsePublicHeader(QuicDataReader * reader,uint8_t expected_destination_connection_id_length,bool ietf_format,uint8_t * first_byte,PacketHeaderFormat * format,bool * version_present,bool * has_length_prefix,QuicVersionLabel * version_label,ParsedQuicVersion * parsed_version,QuicConnectionId * destination_connection_id,QuicConnectionId * source_connection_id,QuicLongHeaderType * long_packet_type,quiche::QuicheVariableLengthIntegerLength * retry_token_length_length,absl::string_view * retry_token,std::string * detailed_error)7018 QuicErrorCode QuicFramer::ParsePublicHeader(
7019 QuicDataReader* reader, uint8_t expected_destination_connection_id_length,
7020 bool ietf_format, uint8_t* first_byte, PacketHeaderFormat* format,
7021 bool* version_present, bool* has_length_prefix,
7022 QuicVersionLabel* version_label, ParsedQuicVersion* parsed_version,
7023 QuicConnectionId* destination_connection_id,
7024 QuicConnectionId* source_connection_id,
7025 QuicLongHeaderType* long_packet_type,
7026 quiche::QuicheVariableLengthIntegerLength* retry_token_length_length,
7027 absl::string_view* retry_token, std::string* detailed_error) {
7028 *version_present = false;
7029 *has_length_prefix = false;
7030 *version_label = 0;
7031 *parsed_version = UnsupportedQuicVersion();
7032 *source_connection_id = EmptyQuicConnectionId();
7033 *long_packet_type = INVALID_PACKET_TYPE;
7034 *retry_token_length_length = quiche::VARIABLE_LENGTH_INTEGER_LENGTH_0;
7035 *retry_token = absl::string_view();
7036 *detailed_error = "";
7037
7038 if (!reader->ReadUInt8(first_byte)) {
7039 *detailed_error = "Unable to read first byte.";
7040 return QUIC_INVALID_PACKET_HEADER;
7041 }
7042
7043 if (!ietf_format) {
7044 return ParsePublicHeaderGoogleQuic(
7045 reader, first_byte, format, version_present, version_label,
7046 parsed_version, destination_connection_id, detailed_error);
7047 }
7048
7049 *format = GetIetfPacketHeaderFormat(*first_byte);
7050
7051 if (*format == IETF_QUIC_SHORT_HEADER_PACKET) {
7052 if (!reader->ReadConnectionId(destination_connection_id,
7053 expected_destination_connection_id_length)) {
7054 *detailed_error = "Unable to read destination connection ID.";
7055 return QUIC_INVALID_PACKET_HEADER;
7056 }
7057 return QUIC_NO_ERROR;
7058 }
7059
7060 QUICHE_DCHECK_EQ(IETF_QUIC_LONG_HEADER_PACKET, *format);
7061 *version_present = true;
7062 if (!ProcessVersionLabel(reader, version_label)) {
7063 *detailed_error = "Unable to read protocol version.";
7064 return QUIC_INVALID_PACKET_HEADER;
7065 }
7066
7067 if (*version_label == 0) {
7068 *long_packet_type = VERSION_NEGOTIATION;
7069 }
7070
7071 // Parse version.
7072 *parsed_version = ParseQuicVersionLabel(*version_label);
7073
7074 // Figure out which IETF QUIC invariants this packet follows.
7075 *has_length_prefix = PacketHasLengthPrefixedConnectionIds(
7076 *reader, *parsed_version, *version_label, *first_byte);
7077
7078 // Parse connection IDs.
7079 if (!ParseLongHeaderConnectionIds(*reader, *has_length_prefix, *version_label,
7080 *destination_connection_id,
7081 *source_connection_id, *detailed_error)) {
7082 return QUIC_INVALID_PACKET_HEADER;
7083 }
7084
7085 if (!parsed_version->IsKnown()) {
7086 // Skip parsing of long packet type and retry token for unknown versions.
7087 return QUIC_NO_ERROR;
7088 }
7089
7090 // Parse long packet type.
7091 *long_packet_type = GetLongHeaderType(*first_byte, *parsed_version);
7092
7093 switch (*long_packet_type) {
7094 case INVALID_PACKET_TYPE:
7095 *detailed_error = "Unable to parse long packet type.";
7096 return QUIC_INVALID_PACKET_HEADER;
7097 case INITIAL:
7098 if (!parsed_version->SupportsRetry()) {
7099 // Retry token is only present on initial packets for some versions.
7100 return QUIC_NO_ERROR;
7101 }
7102 break;
7103 default:
7104 return QUIC_NO_ERROR;
7105 }
7106
7107 *retry_token_length_length = reader->PeekVarInt62Length();
7108 uint64_t retry_token_length;
7109 if (!reader->ReadVarInt62(&retry_token_length)) {
7110 *retry_token_length_length = quiche::VARIABLE_LENGTH_INTEGER_LENGTH_0;
7111 *detailed_error = "Unable to read retry token length.";
7112 return QUIC_INVALID_PACKET_HEADER;
7113 }
7114
7115 if (!reader->ReadStringPiece(retry_token, retry_token_length)) {
7116 *detailed_error = "Unable to read retry token.";
7117 return QUIC_INVALID_PACKET_HEADER;
7118 }
7119
7120 return QUIC_NO_ERROR;
7121 }
7122
7123 // static
WriteClientVersionNegotiationProbePacket(char * packet_bytes,QuicByteCount packet_length,const char * destination_connection_id_bytes,uint8_t destination_connection_id_length)7124 bool QuicFramer::WriteClientVersionNegotiationProbePacket(
7125 char* packet_bytes, QuicByteCount packet_length,
7126 const char* destination_connection_id_bytes,
7127 uint8_t destination_connection_id_length) {
7128 if (packet_bytes == nullptr) {
7129 QUIC_BUG(quic_bug_10850_93) << "Invalid packet_bytes";
7130 return false;
7131 }
7132 if (packet_length < kMinPacketSizeForVersionNegotiation ||
7133 packet_length > 65535) {
7134 QUIC_BUG(quic_bug_10850_94) << "Invalid packet_length";
7135 return false;
7136 }
7137 if (destination_connection_id_length > kQuicMaxConnectionId4BitLength ||
7138 destination_connection_id_length < kQuicDefaultConnectionIdLength) {
7139 QUIC_BUG(quic_bug_10850_95) << "Invalid connection_id_length";
7140 return false;
7141 }
7142 // clang-format off
7143 const unsigned char packet_start_bytes[] = {
7144 // IETF long header with fixed bit set, type initial, all-0 encrypted bits.
7145 0xc0,
7146 // Version, part of the IETF space reserved for negotiation.
7147 // This intentionally differs from QuicVersionReservedForNegotiation()
7148 // to allow differentiating them over the wire.
7149 0xca, 0xba, 0xda, 0xda,
7150 };
7151 // clang-format on
7152 static_assert(sizeof(packet_start_bytes) == 5, "bad packet_start_bytes size");
7153 QuicDataWriter writer(packet_length, packet_bytes);
7154 if (!writer.WriteBytes(packet_start_bytes, sizeof(packet_start_bytes))) {
7155 QUIC_BUG(quic_bug_10850_96) << "Failed to write packet start";
7156 return false;
7157 }
7158
7159 QuicConnectionId destination_connection_id(destination_connection_id_bytes,
7160 destination_connection_id_length);
7161 if (!AppendIetfConnectionIds(
7162 /*version_flag=*/true, /*use_length_prefix=*/true,
7163 destination_connection_id, EmptyQuicConnectionId(), &writer)) {
7164 QUIC_BUG(quic_bug_10850_97) << "Failed to write connection IDs";
7165 return false;
7166 }
7167 // Add 8 bytes of zeroes followed by 8 bytes of ones to ensure that this does
7168 // not parse with any known version. The zeroes make sure that packet numbers,
7169 // retry token lengths and payload lengths are parsed as zero, and if the
7170 // zeroes are treated as padding frames, 0xff is known to not parse as a
7171 // valid frame type.
7172 if (!writer.WriteUInt64(0) ||
7173 !writer.WriteUInt64(std::numeric_limits<uint64_t>::max())) {
7174 QUIC_BUG(quic_bug_10850_98) << "Failed to write 18 bytes";
7175 return false;
7176 }
7177 // Make sure the polite greeting below is padded to a 16-byte boundary to
7178 // make it easier to read in tcpdump.
7179 while (writer.length() % 16 != 0) {
7180 if (!writer.WriteUInt8(0)) {
7181 QUIC_BUG(quic_bug_10850_99) << "Failed to write padding byte";
7182 return false;
7183 }
7184 }
7185 // Add a polite greeting in case a human sees this in tcpdump.
7186 static const char polite_greeting[] =
7187 "This packet only exists to trigger IETF QUIC version negotiation. "
7188 "Please respond with a Version Negotiation packet indicating what "
7189 "versions you support. Thank you and have a nice day.";
7190 if (!writer.WriteBytes(polite_greeting, sizeof(polite_greeting))) {
7191 QUIC_BUG(quic_bug_10850_100) << "Failed to write polite greeting";
7192 return false;
7193 }
7194 // Fill the rest of the packet with zeroes.
7195 writer.WritePadding();
7196 QUICHE_DCHECK_EQ(0u, writer.remaining());
7197 return true;
7198 }
7199
7200 // static
ParseServerVersionNegotiationProbeResponse(const char * packet_bytes,QuicByteCount packet_length,char * source_connection_id_bytes,uint8_t * source_connection_id_length_out,std::string * detailed_error)7201 bool QuicFramer::ParseServerVersionNegotiationProbeResponse(
7202 const char* packet_bytes, QuicByteCount packet_length,
7203 char* source_connection_id_bytes, uint8_t* source_connection_id_length_out,
7204 std::string* detailed_error) {
7205 if (detailed_error == nullptr) {
7206 QUIC_BUG(quic_bug_10850_101) << "Invalid error_details";
7207 return false;
7208 }
7209 *detailed_error = "";
7210 if (packet_bytes == nullptr) {
7211 *detailed_error = "Invalid packet_bytes";
7212 return false;
7213 }
7214 if (packet_length < 6) {
7215 *detailed_error = "Invalid packet_length";
7216 return false;
7217 }
7218 if (source_connection_id_bytes == nullptr) {
7219 *detailed_error = "Invalid source_connection_id_bytes";
7220 return false;
7221 }
7222 if (source_connection_id_length_out == nullptr) {
7223 *detailed_error = "Invalid source_connection_id_length_out";
7224 return false;
7225 }
7226 QuicDataReader reader(packet_bytes, packet_length);
7227 uint8_t type_byte = 0;
7228 if (!reader.ReadUInt8(&type_byte)) {
7229 *detailed_error = "Failed to read type byte";
7230 return false;
7231 }
7232 if ((type_byte & 0x80) == 0) {
7233 *detailed_error = "Packet does not have long header";
7234 return false;
7235 }
7236 uint32_t version = 0;
7237 if (!reader.ReadUInt32(&version)) {
7238 *detailed_error = "Failed to read version";
7239 return false;
7240 }
7241 if (version != 0) {
7242 *detailed_error = "Packet is not a version negotiation packet";
7243 return false;
7244 }
7245
7246 QuicConnectionId destination_connection_id, source_connection_id;
7247 if (!reader.ReadLengthPrefixedConnectionId(&destination_connection_id)) {
7248 *detailed_error = "Failed to read destination connection ID";
7249 return false;
7250 }
7251 if (!reader.ReadLengthPrefixedConnectionId(&source_connection_id)) {
7252 *detailed_error = "Failed to read source connection ID";
7253 return false;
7254 }
7255
7256 if (destination_connection_id.length() != 0) {
7257 *detailed_error = "Received unexpected destination connection ID length";
7258 return false;
7259 }
7260 if (*source_connection_id_length_out < source_connection_id.length()) {
7261 *detailed_error =
7262 absl::StrCat("*source_connection_id_length_out too small ",
7263 static_cast<int>(*source_connection_id_length_out), " < ",
7264 static_cast<int>(source_connection_id.length()));
7265 return false;
7266 }
7267
7268 memcpy(source_connection_id_bytes, source_connection_id.data(),
7269 source_connection_id.length());
7270 *source_connection_id_length_out = source_connection_id.length();
7271
7272 return true;
7273 }
7274
7275 // Look for and parse the error code from the "<quic_error_code>:" text that
7276 // may be present at the start of the CONNECTION_CLOSE error details string.
7277 // This text, inserted by the peer if it's using Google's QUIC implementation,
7278 // contains additional error information that narrows down the exact error. If
7279 // the string is not found, or is not properly formed, it returns
7280 // ErrorCode::QUIC_IETF_GQUIC_ERROR_MISSING
MaybeExtractQuicErrorCode(QuicConnectionCloseFrame * frame)7281 void MaybeExtractQuicErrorCode(QuicConnectionCloseFrame* frame) {
7282 std::vector<absl::string_view> ed = absl::StrSplit(frame->error_details, ':');
7283 uint64_t extracted_error_code;
7284 if (ed.size() < 2 || !quiche::QuicheTextUtils::IsAllDigits(ed[0]) ||
7285 !absl::SimpleAtoi(ed[0], &extracted_error_code)) {
7286 if (frame->close_type == IETF_QUIC_TRANSPORT_CONNECTION_CLOSE &&
7287 frame->wire_error_code == NO_IETF_QUIC_ERROR) {
7288 frame->quic_error_code = QUIC_NO_ERROR;
7289 } else {
7290 frame->quic_error_code = QUIC_IETF_GQUIC_ERROR_MISSING;
7291 }
7292 return;
7293 }
7294 // Return the error code (numeric) and the error details string without the
7295 // error code prefix. Note that Split returns everything up to, but not
7296 // including, the split character, so the length of ed[0] is just the number
7297 // of digits in the error number. In removing the prefix, 1 is added to the
7298 // length to account for the :
7299 absl::string_view x = absl::string_view(frame->error_details);
7300 x.remove_prefix(ed[0].length() + 1);
7301 frame->error_details = std::string(x);
7302 frame->quic_error_code = static_cast<QuicErrorCode>(extracted_error_code);
7303 }
7304
7305 #undef ENDPOINT // undef for jumbo builds
7306 } // namespace quic
7307