blob: c9eabcb7ff3a170235abcf03296ed61611ffe207 [file] [log] [blame]
QUICHE teama6ef0a62019-03-07 20:34:33 -05001// Copyright (c) 2012 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include "net/third_party/quiche/src/quic/core/quic_framer.h"
6
7#include <cstddef>
8#include <cstdint>
haoyuewang6a6a0ff2020-06-23 16:32:26 -07009#include <limits>
QUICHE teama6ef0a62019-03-07 20:34:33 -050010#include <memory>
vasilvv872e7a32019-03-12 16:42:44 -070011#include <string>
bnc463f2352019-10-10 04:49:34 -070012#include <utility>
QUICHE teama6ef0a62019-03-07 20:34:33 -050013
14#include "net/third_party/quiche/src/quic/core/crypto/crypto_framer.h"
nharper55fa6132019-05-07 19:37:21 -070015#include "net/third_party/quiche/src/quic/core/crypto/crypto_handshake.h"
QUICHE teama6ef0a62019-03-07 20:34:33 -050016#include "net/third_party/quiche/src/quic/core/crypto/crypto_handshake_message.h"
17#include "net/third_party/quiche/src/quic/core/crypto/crypto_protocol.h"
nharper55fa6132019-05-07 19:37:21 -070018#include "net/third_party/quiche/src/quic/core/crypto/crypto_utils.h"
QUICHE teama6ef0a62019-03-07 20:34:33 -050019#include "net/third_party/quiche/src/quic/core/crypto/null_decrypter.h"
20#include "net/third_party/quiche/src/quic/core/crypto/null_encrypter.h"
21#include "net/third_party/quiche/src/quic/core/crypto/quic_decrypter.h"
22#include "net/third_party/quiche/src/quic/core/crypto/quic_encrypter.h"
23#include "net/third_party/quiche/src/quic/core/crypto/quic_random.h"
haoyuewang6a6a0ff2020-06-23 16:32:26 -070024#include "net/third_party/quiche/src/quic/core/frames/quic_ack_frequency_frame.h"
QUICHE teama6ef0a62019-03-07 20:34:33 -050025#include "net/third_party/quiche/src/quic/core/quic_connection_id.h"
26#include "net/third_party/quiche/src/quic/core/quic_constants.h"
27#include "net/third_party/quiche/src/quic/core/quic_data_reader.h"
28#include "net/third_party/quiche/src/quic/core/quic_data_writer.h"
ianswett97b690b2019-05-02 15:12:43 -070029#include "net/third_party/quiche/src/quic/core/quic_error_codes.h"
dschinazib953d022019-08-01 18:05:58 -070030#include "net/third_party/quiche/src/quic/core/quic_packets.h"
QUICHE teama6ef0a62019-03-07 20:34:33 -050031#include "net/third_party/quiche/src/quic/core/quic_socket_address_coder.h"
32#include "net/third_party/quiche/src/quic/core/quic_stream_frame_data_producer.h"
haoyuewang6a6a0ff2020-06-23 16:32:26 -070033#include "net/third_party/quiche/src/quic/core/quic_time.h"
QUICHE teama6ef0a62019-03-07 20:34:33 -050034#include "net/third_party/quiche/src/quic/core/quic_types.h"
35#include "net/third_party/quiche/src/quic/core/quic_utils.h"
36#include "net/third_party/quiche/src/quic/core/quic_versions.h"
37#include "net/third_party/quiche/src/quic/platform/api/quic_aligned.h"
38#include "net/third_party/quiche/src/quic/platform/api/quic_bug_tracker.h"
39#include "net/third_party/quiche/src/quic/platform/api/quic_client_stats.h"
QUICHE teama6ef0a62019-03-07 20:34:33 -050040#include "net/third_party/quiche/src/quic/platform/api/quic_fallthrough.h"
41#include "net/third_party/quiche/src/quic/platform/api/quic_flag_utils.h"
42#include "net/third_party/quiche/src/quic/platform/api/quic_flags.h"
43#include "net/third_party/quiche/src/quic/platform/api/quic_logging.h"
44#include "net/third_party/quiche/src/quic/platform/api/quic_map_util.h"
QUICHE teama6ef0a62019-03-07 20:34:33 -050045#include "net/third_party/quiche/src/quic/platform/api/quic_stack_trace.h"
bnc4e9283d2019-12-17 07:08:57 -080046#include "net/third_party/quiche/src/common/platform/api/quiche_arraysize.h"
dmcardlecf0bfcf2019-12-13 08:08:21 -080047#include "net/third_party/quiche/src/common/platform/api/quiche_str_cat.h"
48#include "net/third_party/quiche/src/common/platform/api/quiche_string_piece.h"
49#include "net/third_party/quiche/src/common/platform/api/quiche_text_utils.h"
QUICHE teama6ef0a62019-03-07 20:34:33 -050050
51namespace quic {
52
53namespace {
54
55#define ENDPOINT \
56 (perspective_ == Perspective::IS_SERVER ? "Server: " : "Client: ")
57
QUICHE teama6ef0a62019-03-07 20:34:33 -050058// Number of bits the packet number length bits are shifted from the right
59// edge of the header.
60const uint8_t kPublicHeaderSequenceNumberShift = 4;
61
62// There are two interpretations for the Frame Type byte in the QUIC protocol,
63// resulting in two Frame Types: Special Frame Types and Regular Frame Types.
64//
65// Regular Frame Types use the Frame Type byte simply. Currently defined
66// Regular Frame Types are:
67// Padding : 0b 00000000 (0x00)
68// ResetStream : 0b 00000001 (0x01)
69// ConnectionClose : 0b 00000010 (0x02)
70// GoAway : 0b 00000011 (0x03)
71// WindowUpdate : 0b 00000100 (0x04)
72// Blocked : 0b 00000101 (0x05)
73//
74// Special Frame Types encode both a Frame Type and corresponding flags
75// all in the Frame Type byte. Currently defined Special Frame Types
76// are:
77// Stream : 0b 1xxxxxxx
78// Ack : 0b 01xxxxxx
79//
80// Semantics of the flag bits above (the x bits) depends on the frame type.
81
82// Masks to determine if the frame type is a special use
83// and for specific special frame types.
84const uint8_t kQuicFrameTypeBrokenMask = 0xE0; // 0b 11100000
85const uint8_t kQuicFrameTypeSpecialMask = 0xC0; // 0b 11000000
86const uint8_t kQuicFrameTypeStreamMask = 0x80;
87const uint8_t kQuicFrameTypeAckMask = 0x40;
88static_assert(kQuicFrameTypeSpecialMask ==
89 (kQuicFrameTypeStreamMask | kQuicFrameTypeAckMask),
90 "Invalid kQuicFrameTypeSpecialMask");
91
92// The stream type format is 1FDOOOSS, where
93// F is the fin bit.
94// D is the data length bit (0 or 2 bytes).
95// OO/OOO are the size of the offset.
96// SS is the size of the stream ID.
97// Note that the stream encoding can not be determined by inspection. It can
98// be determined only by knowing the QUIC Version.
99// Stream frame relative shifts and masks for interpreting the stream flags.
100// StreamID may be 1, 2, 3, or 4 bytes.
101const uint8_t kQuicStreamIdShift = 2;
102const uint8_t kQuicStreamIDLengthMask = 0x03;
103
104// Offset may be 0, 2, 4, or 8 bytes.
105const uint8_t kQuicStreamShift = 3;
106const uint8_t kQuicStreamOffsetMask = 0x07;
107
108// Data length may be 0 or 2 bytes.
109const uint8_t kQuicStreamDataLengthShift = 1;
110const uint8_t kQuicStreamDataLengthMask = 0x01;
111
112// Fin bit may be set or not.
113const uint8_t kQuicStreamFinShift = 1;
114const uint8_t kQuicStreamFinMask = 0x01;
115
116// The format is 01M0LLOO, where
117// M if set, there are multiple ack blocks in the frame.
118// LL is the size of the largest ack field.
119// OO is the size of the ack blocks offset field.
120// packet number size shift used in AckFrames.
121const uint8_t kQuicSequenceNumberLengthNumBits = 2;
122const uint8_t kActBlockLengthOffset = 0;
123const uint8_t kLargestAckedOffset = 2;
124
125// Acks may have only one ack block.
126const uint8_t kQuicHasMultipleAckBlocksOffset = 5;
127
128// Timestamps are 4 bytes followed by 2 bytes.
129const uint8_t kQuicNumTimestampsLength = 1;
130const uint8_t kQuicFirstTimestampLength = 4;
131const uint8_t kQuicTimestampLength = 2;
132// Gaps between packet numbers are 1 byte.
133const uint8_t kQuicTimestampPacketNumberGapLength = 1;
134
135// Maximum length of encoded error strings.
136const int kMaxErrorStringLength = 256;
137
138const uint8_t kConnectionIdLengthAdjustment = 3;
139const uint8_t kDestinationConnectionIdLengthMask = 0xF0;
140const uint8_t kSourceConnectionIdLengthMask = 0x0F;
141
142// Returns the absolute value of the difference between |a| and |b|.
143uint64_t Delta(uint64_t a, uint64_t b) {
144 // Since these are unsigned numbers, we can't just return abs(a - b)
145 if (a < b) {
146 return b - a;
147 }
148 return a - b;
149}
150
151uint64_t ClosestTo(uint64_t target, uint64_t a, uint64_t b) {
152 return (Delta(target, a) < Delta(target, b)) ? a : b;
153}
154
QUICHE teama6ef0a62019-03-07 20:34:33 -0500155QuicPacketNumberLength ReadSequenceNumberLength(uint8_t flags) {
156 switch (flags & PACKET_FLAGS_8BYTE_PACKET) {
157 case PACKET_FLAGS_8BYTE_PACKET:
158 return PACKET_6BYTE_PACKET_NUMBER;
159 case PACKET_FLAGS_4BYTE_PACKET:
160 return PACKET_4BYTE_PACKET_NUMBER;
161 case PACKET_FLAGS_2BYTE_PACKET:
162 return PACKET_2BYTE_PACKET_NUMBER;
163 case PACKET_FLAGS_1BYTE_PACKET:
164 return PACKET_1BYTE_PACKET_NUMBER;
165 default:
166 QUIC_BUG << "Unreachable case statement.";
167 return PACKET_6BYTE_PACKET_NUMBER;
168 }
169}
170
dschinazi17d42422019-06-18 16:35:07 -0700171QuicPacketNumberLength ReadAckPacketNumberLength(
dschinazi17d42422019-06-18 16:35:07 -0700172 uint8_t flags) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500173 switch (flags & PACKET_FLAGS_8BYTE_PACKET) {
174 case PACKET_FLAGS_8BYTE_PACKET:
175 return PACKET_6BYTE_PACKET_NUMBER;
176 case PACKET_FLAGS_4BYTE_PACKET:
177 return PACKET_4BYTE_PACKET_NUMBER;
178 case PACKET_FLAGS_2BYTE_PACKET:
179 return PACKET_2BYTE_PACKET_NUMBER;
180 case PACKET_FLAGS_1BYTE_PACKET:
181 return PACKET_1BYTE_PACKET_NUMBER;
182 default:
183 QUIC_BUG << "Unreachable case statement.";
184 return PACKET_6BYTE_PACKET_NUMBER;
185 }
186}
187
188uint8_t PacketNumberLengthToOnWireValue(
QUICHE teama6ef0a62019-03-07 20:34:33 -0500189 QuicPacketNumberLength packet_number_length) {
fayang36825da2019-08-21 14:01:27 -0700190 return packet_number_length - 1;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500191}
192
fayang36825da2019-08-21 14:01:27 -0700193QuicPacketNumberLength GetShortHeaderPacketNumberLength(uint8_t type) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500194 DCHECK(!(type & FLAGS_LONG_HEADER));
fayang36825da2019-08-21 14:01:27 -0700195 return static_cast<QuicPacketNumberLength>((type & 0x03) + 1);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500196}
197
fayang36825da2019-08-21 14:01:27 -0700198uint8_t LongHeaderTypeToOnWireValue(QuicLongHeaderType type) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500199 switch (type) {
200 case INITIAL:
fayang36825da2019-08-21 14:01:27 -0700201 return 0;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500202 case ZERO_RTT_PROTECTED:
fayang36825da2019-08-21 14:01:27 -0700203 return 1 << 4;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500204 case HANDSHAKE:
fayang36825da2019-08-21 14:01:27 -0700205 return 2 << 4;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500206 case RETRY:
fayang36825da2019-08-21 14:01:27 -0700207 return 3 << 4;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500208 case VERSION_NEGOTIATION:
209 return 0xF0; // Value does not matter
210 default:
211 QUIC_BUG << "Invalid long header type: " << type;
212 return 0xFF;
213 }
214}
215
fayang36825da2019-08-21 14:01:27 -0700216bool GetLongHeaderType(uint8_t type, QuicLongHeaderType* long_header_type) {
217 DCHECK((type & FLAGS_LONG_HEADER));
218 switch ((type & 0x30) >> 4) {
219 case 0:
QUICHE teama6ef0a62019-03-07 20:34:33 -0500220 *long_header_type = INITIAL;
221 break;
fayang36825da2019-08-21 14:01:27 -0700222 case 1:
QUICHE teama6ef0a62019-03-07 20:34:33 -0500223 *long_header_type = ZERO_RTT_PROTECTED;
224 break;
fayang36825da2019-08-21 14:01:27 -0700225 case 2:
QUICHE teama6ef0a62019-03-07 20:34:33 -0500226 *long_header_type = HANDSHAKE;
227 break;
fayang36825da2019-08-21 14:01:27 -0700228 case 3:
QUICHE teama6ef0a62019-03-07 20:34:33 -0500229 *long_header_type = RETRY;
230 break;
231 default:
fayang36825da2019-08-21 14:01:27 -0700232 QUIC_BUG << "Unreachable statement";
QUICHE teama6ef0a62019-03-07 20:34:33 -0500233 *long_header_type = INVALID_PACKET_TYPE;
234 return false;
235 }
236 return true;
237}
238
fayang36825da2019-08-21 14:01:27 -0700239QuicPacketNumberLength GetLongHeaderPacketNumberLength(uint8_t type) {
240 return static_cast<QuicPacketNumberLength>((type & 0x03) + 1);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500241}
242
QUICHE team10b22a12019-03-21 15:31:42 -0700243// Used to get packet number space before packet gets decrypted.
244PacketNumberSpace GetPacketNumberSpace(const QuicPacketHeader& header) {
245 switch (header.form) {
246 case GOOGLE_QUIC_PACKET:
247 QUIC_BUG << "Try to get packet number space of Google QUIC packet";
248 break;
249 case IETF_QUIC_SHORT_HEADER_PACKET:
250 return APPLICATION_DATA;
251 case IETF_QUIC_LONG_HEADER_PACKET:
252 switch (header.long_packet_type) {
253 case INITIAL:
254 return INITIAL_DATA;
255 case HANDSHAKE:
256 return HANDSHAKE_DATA;
257 case ZERO_RTT_PROTECTED:
258 return APPLICATION_DATA;
259 case VERSION_NEGOTIATION:
260 case RETRY:
261 case INVALID_PACKET_TYPE:
262 QUIC_BUG << "Try to get packet number space of long header type: "
263 << QuicUtils::QuicLongHeaderTypetoString(
264 header.long_packet_type);
265 break;
266 }
267 }
268
269 return NUM_PACKET_NUMBER_SPACES;
270}
271
zhongyi546cc452019-04-12 15:27:49 -0700272EncryptionLevel GetEncryptionLevel(const QuicPacketHeader& header) {
273 switch (header.form) {
274 case GOOGLE_QUIC_PACKET:
275 QUIC_BUG << "Cannot determine EncryptionLevel from Google QUIC header";
276 break;
277 case IETF_QUIC_SHORT_HEADER_PACKET:
278 return ENCRYPTION_FORWARD_SECURE;
279 case IETF_QUIC_LONG_HEADER_PACKET:
280 switch (header.long_packet_type) {
281 case INITIAL:
282 return ENCRYPTION_INITIAL;
283 case HANDSHAKE:
284 return ENCRYPTION_HANDSHAKE;
285 case ZERO_RTT_PROTECTED:
286 return ENCRYPTION_ZERO_RTT;
287 case VERSION_NEGOTIATION:
288 case RETRY:
289 case INVALID_PACKET_TYPE:
290 QUIC_BUG << "No encryption used with type "
291 << QuicUtils::QuicLongHeaderTypetoString(
292 header.long_packet_type);
293 }
294 }
295 return NUM_ENCRYPTION_LEVELS;
296}
297
dmcardlecf0bfcf2019-12-13 08:08:21 -0800298quiche::QuicheStringPiece TruncateErrorString(quiche::QuicheStringPiece error) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500299 if (error.length() <= kMaxErrorStringLength) {
300 return error;
301 }
dmcardlecf0bfcf2019-12-13 08:08:21 -0800302 return quiche::QuicheStringPiece(error.data(), kMaxErrorStringLength);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500303}
304
dmcardlecf0bfcf2019-12-13 08:08:21 -0800305size_t TruncatedErrorStringSize(const quiche::QuicheStringPiece& error) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500306 if (error.length() < kMaxErrorStringLength) {
307 return error.length();
308 }
309 return kMaxErrorStringLength;
310}
311
312uint8_t GetConnectionIdLengthValue(QuicConnectionIdLength length) {
313 if (length == 0) {
314 return 0;
315 }
316 return static_cast<uint8_t>(length - kConnectionIdLengthAdjustment);
317}
318
319bool IsValidPacketNumberLength(QuicPacketNumberLength packet_number_length) {
320 size_t length = packet_number_length;
321 return length == 1 || length == 2 || length == 4 || length == 6 ||
322 length == 8;
323}
324
325bool IsValidFullPacketNumber(uint64_t full_packet_number,
dschinazi40f0b3d2020-02-19 17:54:05 -0800326 ParsedQuicVersion version) {
327 return full_packet_number > 0 || version.HasIetfQuicFrames();
QUICHE teama6ef0a62019-03-07 20:34:33 -0500328}
329
dschinazi1f485a12019-05-13 11:57:01 -0700330bool AppendIetfConnectionIds(bool version_flag,
dschinazi48ac9192019-07-31 00:07:26 -0700331 bool use_length_prefix,
dschinazi1f485a12019-05-13 11:57:01 -0700332 QuicConnectionId destination_connection_id,
333 QuicConnectionId source_connection_id,
334 QuicDataWriter* writer) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500335 if (!version_flag) {
336 return writer->WriteConnectionId(destination_connection_id);
337 }
338
dschinazi48ac9192019-07-31 00:07:26 -0700339 if (use_length_prefix) {
340 return writer->WriteLengthPrefixedConnectionId(destination_connection_id) &&
341 writer->WriteLengthPrefixedConnectionId(source_connection_id);
342 }
343
QUICHE teama6ef0a62019-03-07 20:34:33 -0500344 // Compute connection ID length byte.
345 uint8_t dcil = GetConnectionIdLengthValue(
346 static_cast<QuicConnectionIdLength>(destination_connection_id.length()));
347 uint8_t scil = GetConnectionIdLengthValue(
348 static_cast<QuicConnectionIdLength>(source_connection_id.length()));
349 uint8_t connection_id_length = dcil << 4 | scil;
350
351 return writer->WriteUInt8(connection_id_length) &&
352 writer->WriteConnectionId(destination_connection_id) &&
353 writer->WriteConnectionId(source_connection_id);
354}
355
356enum class DroppedPacketReason {
357 // General errors
358 INVALID_PUBLIC_HEADER,
359 VERSION_MISMATCH,
360 // Version negotiation packet errors
361 INVALID_VERSION_NEGOTIATION_PACKET,
362 // Public reset packet errors, pre-v44
363 INVALID_PUBLIC_RESET_PACKET,
364 // Data packet errors
365 INVALID_PACKET_NUMBER,
366 INVALID_DIVERSIFICATION_NONCE,
367 DECRYPTION_FAILURE,
368 NUM_REASONS,
369};
370
371void RecordDroppedPacketReason(DroppedPacketReason reason) {
372 QUIC_CLIENT_HISTOGRAM_ENUM("QuicDroppedPacketReason", reason,
373 DroppedPacketReason::NUM_REASONS,
374 "The reason a packet was not processed. Recorded "
375 "each time such a packet is dropped");
376}
377
fayangccbab732019-05-13 10:11:25 -0700378PacketHeaderFormat GetIetfPacketHeaderFormat(uint8_t type_byte) {
379 return type_byte & FLAGS_LONG_HEADER ? IETF_QUIC_LONG_HEADER_PACKET
380 : IETF_QUIC_SHORT_HEADER_PACKET;
381}
382
fkastenholzb4dade72019-08-05 06:54:20 -0700383std::string GenerateErrorString(std::string initial_error_string,
384 QuicErrorCode quic_error_code) {
385 if (quic_error_code == QUIC_IETF_GQUIC_ERROR_MISSING) {
386 // QUIC_IETF_GQUIC_ERROR_MISSING is special -- it means not to encode
387 // the error value in the string.
388 return initial_error_string;
389 }
dmcardlecf0bfcf2019-12-13 08:08:21 -0800390 return quiche::QuicheStrCat(
391 std::to_string(static_cast<unsigned>(quic_error_code)), ":",
392 initial_error_string);
fkastenholzb4dade72019-08-05 06:54:20 -0700393}
394
QUICHE teama6ef0a62019-03-07 20:34:33 -0500395} // namespace
396
397QuicFramer::QuicFramer(const ParsedQuicVersionVector& supported_versions,
398 QuicTime creation_time,
399 Perspective perspective,
dschinazi8ff74822019-05-28 16:37:20 -0700400 uint8_t expected_server_connection_id_length)
QUICHE teama6ef0a62019-03-07 20:34:33 -0500401 : visitor_(nullptr),
402 error_(QUIC_NO_ERROR),
dschinazi7b9278c2019-05-20 07:36:21 -0700403 last_serialized_server_connection_id_(EmptyQuicConnectionId()),
dschinazi346b7ce2019-06-05 01:38:18 -0700404 last_serialized_client_connection_id_(EmptyQuicConnectionId()),
dschinazi5c1d7d82020-07-29 16:42:50 -0700405 version_(ParsedQuicVersion::Unsupported()),
QUICHE teama6ef0a62019-03-07 20:34:33 -0500406 supported_versions_(supported_versions),
QUICHE team6987b4a2019-03-15 16:23:04 -0700407 decrypter_level_(ENCRYPTION_INITIAL),
QUICHE team76086e42019-03-25 15:12:29 -0700408 alternative_decrypter_level_(NUM_ENCRYPTION_LEVELS),
QUICHE teama6ef0a62019-03-07 20:34:33 -0500409 alternative_decrypter_latch_(false),
410 perspective_(perspective),
411 validate_flags_(true),
412 process_timestamps_(false),
413 creation_time_(creation_time),
414 last_timestamp_(QuicTime::Delta::Zero()),
415 first_sending_packet_number_(FirstSendingPacketNumber()),
416 data_producer_(nullptr),
417 infer_packet_header_type_from_version_(perspective ==
418 Perspective::IS_CLIENT),
dschinazi8ff74822019-05-28 16:37:20 -0700419 expected_server_connection_id_length_(
420 expected_server_connection_id_length),
dschinazi346b7ce2019-06-05 01:38:18 -0700421 expected_client_connection_id_length_(0),
nharper55fa6132019-05-07 19:37:21 -0700422 supports_multiple_packet_number_spaces_(false),
fkastenholz4dc4ba32019-07-30 09:55:25 -0700423 last_written_packet_number_length_(0),
424 peer_ack_delay_exponent_(kDefaultAckDelayExponent),
fkastenholza3660102019-08-28 05:19:24 -0700425 local_ack_delay_exponent_(kDefaultAckDelayExponent),
426 current_received_frame_type_(0) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500427 DCHECK(!supported_versions.empty());
428 version_ = supported_versions_[0];
dschinazi4f95c402020-02-18 13:39:12 -0800429 DCHECK(version_.IsKnown())
dschinazi577b5482020-01-13 15:40:43 -0800430 << ParsedQuicVersionVectorToString(supported_versions_);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500431}
432
433QuicFramer::~QuicFramer() {}
434
435// static
436size_t QuicFramer::GetMinStreamFrameSize(QuicTransportVersion version,
437 QuicStreamId stream_id,
438 QuicStreamOffset offset,
439 bool last_frame_in_packet,
fkastenholzabfd9ec2019-10-31 07:59:12 -0700440 size_t data_length) {
fkastenholz305e1732019-06-18 05:01:22 -0700441 if (VersionHasIetfQuicFrames(version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500442 return kQuicFrameTypeSize + QuicDataWriter::GetVarInt62Len(stream_id) +
443 (last_frame_in_packet
444 ? 0
445 : QuicDataWriter::GetVarInt62Len(data_length)) +
446 (offset != 0 ? QuicDataWriter::GetVarInt62Len(offset) : 0);
447 }
448 return kQuicFrameTypeSize + GetStreamIdSize(stream_id) +
renjietang488201d2019-12-17 13:40:49 -0800449 GetStreamOffsetSize(offset) +
QUICHE teama6ef0a62019-03-07 20:34:33 -0500450 (last_frame_in_packet ? 0 : kQuicStreamPayloadLengthSize);
451}
452
453// static
454size_t QuicFramer::GetMinCryptoFrameSize(QuicStreamOffset offset,
455 QuicPacketLength data_length) {
456 return kQuicFrameTypeSize + QuicDataWriter::GetVarInt62Len(offset) +
457 QuicDataWriter::GetVarInt62Len(data_length);
458}
459
460// static
461size_t QuicFramer::GetMessageFrameSize(QuicTransportVersion version,
462 bool last_frame_in_packet,
463 QuicByteCount length) {
fayangd4291e42019-05-30 10:31:21 -0700464 QUIC_BUG_IF(!VersionSupportsMessageFrames(version))
QUICHE teama6ef0a62019-03-07 20:34:33 -0500465 << "Try to serialize MESSAGE frame in " << version;
466 return kQuicFrameTypeSize +
467 (last_frame_in_packet ? 0 : QuicDataWriter::GetVarInt62Len(length)) +
468 length;
469}
470
471// static
fayang43697fd2020-04-21 11:13:43 -0700472size_t QuicFramer::GetMinAckFrameSize(QuicTransportVersion version,
473 const QuicAckFrame& ack_frame,
474 uint32_t local_ack_delay_exponent) {
fkastenholz305e1732019-06-18 05:01:22 -0700475 if (VersionHasIetfQuicFrames(version)) {
fayang91c23d72020-03-09 12:35:05 -0700476 // The minimal ack frame consists of the following fields: Largest
477 // Acknowledged, ACK Delay, 0 ACK Block Count, First ACK Block and ECN
478 // counts.
479 // Type byte + largest acked.
480 size_t min_size =
481 kQuicFrameTypeSize +
482 QuicDataWriter::GetVarInt62Len(LargestAcked(ack_frame).ToUint64());
483 // Ack delay.
484 min_size += QuicDataWriter::GetVarInt62Len(
485 ack_frame.ack_delay_time.ToMicroseconds() >> local_ack_delay_exponent);
486 // 0 ack block count.
487 min_size += QuicDataWriter::GetVarInt62Len(0);
488 // First ack block.
489 min_size += QuicDataWriter::GetVarInt62Len(
490 ack_frame.packets.Empty() ? 0
491 : ack_frame.packets.rbegin()->Length() - 1);
492 // ECN counts.
493 if (ack_frame.ecn_counters_populated &&
494 (ack_frame.ect_0_count || ack_frame.ect_1_count ||
495 ack_frame.ecn_ce_count)) {
496 min_size += (QuicDataWriter::GetVarInt62Len(ack_frame.ect_0_count) +
497 QuicDataWriter::GetVarInt62Len(ack_frame.ect_1_count) +
498 QuicDataWriter::GetVarInt62Len(ack_frame.ecn_ce_count));
499 }
500 return min_size;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500501 }
fayang43697fd2020-04-21 11:13:43 -0700502 return kQuicFrameTypeSize +
503 GetMinPacketNumberLength(LargestAcked(ack_frame)) +
504 kQuicDeltaTimeLargestObservedSize + kQuicNumTimestampsSize;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500505}
506
507// static
508size_t QuicFramer::GetStopWaitingFrameSize(
QUICHE teama6ef0a62019-03-07 20:34:33 -0500509 QuicPacketNumberLength packet_number_length) {
510 size_t min_size = kQuicFrameTypeSize + packet_number_length;
511 return min_size;
512}
513
514// static
515size_t QuicFramer::GetRstStreamFrameSize(QuicTransportVersion version,
516 const QuicRstStreamFrame& frame) {
fkastenholz305e1732019-06-18 05:01:22 -0700517 if (VersionHasIetfQuicFrames(version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500518 return QuicDataWriter::GetVarInt62Len(frame.stream_id) +
519 QuicDataWriter::GetVarInt62Len(frame.byte_offset) +
fkastenholz07300e52019-07-16 11:51:37 -0700520 kQuicFrameTypeSize +
521 QuicDataWriter::GetVarInt62Len(frame.ietf_error_code);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500522 }
523 return kQuicFrameTypeSize + kQuicMaxStreamIdSize + kQuicMaxStreamOffsetSize +
524 kQuicErrorCodeSize;
525}
526
527// static
fkastenholza037b8b2019-05-07 06:00:05 -0700528size_t QuicFramer::GetConnectionCloseFrameSize(
QUICHE teama6ef0a62019-03-07 20:34:33 -0500529 QuicTransportVersion version,
530 const QuicConnectionCloseFrame& frame) {
fkastenholz305e1732019-06-18 05:01:22 -0700531 if (!VersionHasIetfQuicFrames(version)) {
532 // Not IETF QUIC, return Google QUIC CONNECTION CLOSE frame size.
fkastenholza037b8b2019-05-07 06:00:05 -0700533 return kQuicFrameTypeSize + kQuicErrorCodeSize +
534 kQuicErrorDetailsLengthSize +
535 TruncatedErrorStringSize(frame.error_details);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500536 }
fkastenholzb4dade72019-08-05 06:54:20 -0700537
538 // Prepend the extra error information to the string and get the result's
539 // length.
540 const size_t truncated_error_string_size = TruncatedErrorStringSize(
bnc77e77b82020-04-05 10:36:49 -0700541 GenerateErrorString(frame.error_details, frame.quic_error_code));
fkastenholzb4dade72019-08-05 06:54:20 -0700542
fkastenholza037b8b2019-05-07 06:00:05 -0700543 const size_t frame_size =
544 truncated_error_string_size +
545 QuicDataWriter::GetVarInt62Len(truncated_error_string_size) +
fkastenholz88d08f42019-09-06 07:38:04 -0700546 kQuicFrameTypeSize +
bnc77e77b82020-04-05 10:36:49 -0700547 QuicDataWriter::GetVarInt62Len(frame.wire_error_code);
fkastenholza037b8b2019-05-07 06:00:05 -0700548 if (frame.close_type == IETF_QUIC_APPLICATION_CONNECTION_CLOSE) {
549 return frame_size;
550 }
fkastenholzb4dade72019-08-05 06:54:20 -0700551 // The Transport close frame has the transport_close_frame_type, so include
552 // its length.
fkastenholza037b8b2019-05-07 06:00:05 -0700553 return frame_size +
554 QuicDataWriter::GetVarInt62Len(frame.transport_close_frame_type);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500555}
556
557// static
QUICHE teama6ef0a62019-03-07 20:34:33 -0500558size_t QuicFramer::GetMinGoAwayFrameSize() {
559 return kQuicFrameTypeSize + kQuicErrorCodeSize + kQuicErrorDetailsLengthSize +
560 kQuicMaxStreamIdSize;
561}
562
563// static
564size_t QuicFramer::GetWindowUpdateFrameSize(
565 QuicTransportVersion version,
566 const QuicWindowUpdateFrame& frame) {
fkastenholz305e1732019-06-18 05:01:22 -0700567 if (!VersionHasIetfQuicFrames(version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500568 return kQuicFrameTypeSize + kQuicMaxStreamIdSize + kQuicMaxStreamOffsetSize;
569 }
570 if (frame.stream_id == QuicUtils::GetInvalidStreamId(version)) {
571 // Frame would be a MAX DATA frame, which has only a Maximum Data field.
renjietangd088eab2019-11-21 14:54:41 -0800572 return kQuicFrameTypeSize + QuicDataWriter::GetVarInt62Len(frame.max_data);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500573 }
574 // Frame would be MAX STREAM DATA, has Maximum Stream Data and Stream ID
575 // fields.
renjietangd088eab2019-11-21 14:54:41 -0800576 return kQuicFrameTypeSize + QuicDataWriter::GetVarInt62Len(frame.max_data) +
QUICHE teama6ef0a62019-03-07 20:34:33 -0500577 QuicDataWriter::GetVarInt62Len(frame.stream_id);
578}
579
580// static
581size_t QuicFramer::GetMaxStreamsFrameSize(QuicTransportVersion version,
fkastenholz3c4eabf2019-04-22 07:49:59 -0700582 const QuicMaxStreamsFrame& frame) {
fkastenholz305e1732019-06-18 05:01:22 -0700583 if (!VersionHasIetfQuicFrames(version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500584 QUIC_BUG << "In version " << version
fkastenholz305e1732019-06-18 05:01:22 -0700585 << ", which does not support IETF Frames, and tried to serialize "
586 "MaxStreams Frame.";
QUICHE teama6ef0a62019-03-07 20:34:33 -0500587 }
fkastenholz3c4eabf2019-04-22 07:49:59 -0700588 return kQuicFrameTypeSize +
589 QuicDataWriter::GetVarInt62Len(frame.stream_count);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500590}
591
592// static
593size_t QuicFramer::GetStreamsBlockedFrameSize(
594 QuicTransportVersion version,
fkastenholz3c4eabf2019-04-22 07:49:59 -0700595 const QuicStreamsBlockedFrame& frame) {
fkastenholz305e1732019-06-18 05:01:22 -0700596 if (!VersionHasIetfQuicFrames(version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500597 QUIC_BUG << "In version " << version
fkastenholz305e1732019-06-18 05:01:22 -0700598 << ", which does not support IETF frames, and tried to serialize "
599 "StreamsBlocked Frame.";
QUICHE teama6ef0a62019-03-07 20:34:33 -0500600 }
601
fkastenholz3c4eabf2019-04-22 07:49:59 -0700602 return kQuicFrameTypeSize +
603 QuicDataWriter::GetVarInt62Len(frame.stream_count);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500604}
605
606// static
607size_t QuicFramer::GetBlockedFrameSize(QuicTransportVersion version,
608 const QuicBlockedFrame& frame) {
fkastenholz305e1732019-06-18 05:01:22 -0700609 if (!VersionHasIetfQuicFrames(version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500610 return kQuicFrameTypeSize + kQuicMaxStreamIdSize;
611 }
612 if (frame.stream_id == QuicUtils::GetInvalidStreamId(version)) {
613 // return size of IETF QUIC Blocked frame
614 return kQuicFrameTypeSize + QuicDataWriter::GetVarInt62Len(frame.offset);
615 }
616 // return size of IETF QUIC Stream Blocked frame.
617 return kQuicFrameTypeSize + QuicDataWriter::GetVarInt62Len(frame.offset) +
618 QuicDataWriter::GetVarInt62Len(frame.stream_id);
619}
620
621// static
622size_t QuicFramer::GetStopSendingFrameSize(const QuicStopSendingFrame& frame) {
623 return kQuicFrameTypeSize + QuicDataWriter::GetVarInt62Len(frame.stream_id) +
fkastenholz733552e2019-07-16 11:16:58 -0700624 QuicDataWriter::GetVarInt62Len(frame.application_error_code);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500625}
626
627// static
haoyuewang6a6a0ff2020-06-23 16:32:26 -0700628size_t QuicFramer::GetAckFrequencyFrameSize(
629 const QuicAckFrequencyFrame& frame) {
630 return QuicDataWriter::GetVarInt62Len(IETF_ACK_FREQUENCY) +
631 QuicDataWriter::GetVarInt62Len(frame.sequence_number) +
632 QuicDataWriter::GetVarInt62Len(frame.packet_tolerance) +
633 QuicDataWriter::GetVarInt62Len(frame.max_ack_delay.ToMicroseconds()) +
634 // One byte for encoding boolean
635 1;
636}
637
638// static
QUICHE teama6ef0a62019-03-07 20:34:33 -0500639size_t QuicFramer::GetPathChallengeFrameSize(
640 const QuicPathChallengeFrame& frame) {
641 return kQuicFrameTypeSize + sizeof(frame.data_buffer);
642}
643
644// static
645size_t QuicFramer::GetPathResponseFrameSize(
646 const QuicPathResponseFrame& frame) {
647 return kQuicFrameTypeSize + sizeof(frame.data_buffer);
648}
649
650// static
651size_t QuicFramer::GetRetransmittableControlFrameSize(
652 QuicTransportVersion version,
653 const QuicFrame& frame) {
654 switch (frame.type) {
655 case PING_FRAME:
656 // Ping has no payload.
657 return kQuicFrameTypeSize;
658 case RST_STREAM_FRAME:
659 return GetRstStreamFrameSize(version, *frame.rst_stream_frame);
660 case CONNECTION_CLOSE_FRAME:
fkastenholza037b8b2019-05-07 06:00:05 -0700661 return GetConnectionCloseFrameSize(version,
662 *frame.connection_close_frame);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500663 case GOAWAY_FRAME:
664 return GetMinGoAwayFrameSize() +
665 TruncatedErrorStringSize(frame.goaway_frame->reason_phrase);
666 case WINDOW_UPDATE_FRAME:
fkastenholz305e1732019-06-18 05:01:22 -0700667 // For IETF QUIC, this could be either a MAX DATA or MAX STREAM DATA.
QUICHE teama6ef0a62019-03-07 20:34:33 -0500668 // GetWindowUpdateFrameSize figures this out and returns the correct
669 // length.
670 return GetWindowUpdateFrameSize(version, *frame.window_update_frame);
671 case BLOCKED_FRAME:
672 return GetBlockedFrameSize(version, *frame.blocked_frame);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500673 case NEW_CONNECTION_ID_FRAME:
674 return GetNewConnectionIdFrameSize(*frame.new_connection_id_frame);
675 case RETIRE_CONNECTION_ID_FRAME:
676 return GetRetireConnectionIdFrameSize(*frame.retire_connection_id_frame);
677 case NEW_TOKEN_FRAME:
678 return GetNewTokenFrameSize(*frame.new_token_frame);
fkastenholz3c4eabf2019-04-22 07:49:59 -0700679 case MAX_STREAMS_FRAME:
680 return GetMaxStreamsFrameSize(version, frame.max_streams_frame);
681 case STREAMS_BLOCKED_FRAME:
682 return GetStreamsBlockedFrameSize(version, frame.streams_blocked_frame);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500683 case PATH_RESPONSE_FRAME:
684 return GetPathResponseFrameSize(*frame.path_response_frame);
685 case PATH_CHALLENGE_FRAME:
686 return GetPathChallengeFrameSize(*frame.path_challenge_frame);
687 case STOP_SENDING_FRAME:
688 return GetStopSendingFrameSize(*frame.stop_sending_frame);
fayang01062942020-01-22 07:23:23 -0800689 case HANDSHAKE_DONE_FRAME:
690 // HANDSHAKE_DONE has no payload.
691 return kQuicFrameTypeSize;
haoyuewang6a6a0ff2020-06-23 16:32:26 -0700692 case ACK_FREQUENCY_FRAME:
693 return GetAckFrequencyFrameSize(*frame.ack_frequency_frame);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500694 case STREAM_FRAME:
695 case ACK_FRAME:
696 case STOP_WAITING_FRAME:
697 case MTU_DISCOVERY_FRAME:
698 case PADDING_FRAME:
699 case MESSAGE_FRAME:
700 case CRYPTO_FRAME:
701 case NUM_FRAME_TYPES:
702 DCHECK(false);
703 return 0;
704 }
705
706 // Not reachable, but some Chrome compilers can't figure that out. *sigh*
707 DCHECK(false);
708 return 0;
709}
710
711// static
712size_t QuicFramer::GetStreamIdSize(QuicStreamId stream_id) {
713 // Sizes are 1 through 4 bytes.
714 for (int i = 1; i <= 4; ++i) {
715 stream_id >>= 8;
716 if (stream_id == 0) {
717 return i;
718 }
719 }
720 QUIC_BUG << "Failed to determine StreamIDSize.";
721 return 4;
722}
723
724// static
renjietang488201d2019-12-17 13:40:49 -0800725size_t QuicFramer::GetStreamOffsetSize(QuicStreamOffset offset) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500726 // 0 is a special case.
727 if (offset == 0) {
728 return 0;
729 }
730 // 2 through 8 are the remaining sizes.
731 offset >>= 8;
732 for (int i = 2; i <= 8; ++i) {
733 offset >>= 8;
734 if (offset == 0) {
735 return i;
736 }
737 }
738 QUIC_BUG << "Failed to determine StreamOffsetSize.";
739 return 8;
740}
741
742// static
743size_t QuicFramer::GetNewConnectionIdFrameSize(
744 const QuicNewConnectionIdFrame& frame) {
745 return kQuicFrameTypeSize +
746 QuicDataWriter::GetVarInt62Len(frame.sequence_number) +
fkastenholz1c19fc22019-07-12 11:06:19 -0700747 QuicDataWriter::GetVarInt62Len(frame.retire_prior_to) +
QUICHE teama6ef0a62019-03-07 20:34:33 -0500748 kConnectionIdLengthSize + frame.connection_id.length() +
749 sizeof(frame.stateless_reset_token);
750}
751
752// static
753size_t QuicFramer::GetRetireConnectionIdFrameSize(
754 const QuicRetireConnectionIdFrame& frame) {
755 return kQuicFrameTypeSize +
756 QuicDataWriter::GetVarInt62Len(frame.sequence_number);
757}
758
759// static
760size_t QuicFramer::GetNewTokenFrameSize(const QuicNewTokenFrame& frame) {
761 return kQuicFrameTypeSize +
762 QuicDataWriter::GetVarInt62Len(frame.token.length()) +
763 frame.token.length();
764}
765
766// TODO(nharper): Change this method to take a ParsedQuicVersion.
767bool QuicFramer::IsSupportedTransportVersion(
768 const QuicTransportVersion version) const {
QUICHE team6a5a8aa2020-08-19 14:57:24 -0700769 for (const ParsedQuicVersion& supported_version : supported_versions_) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500770 if (version == supported_version.transport_version) {
771 return true;
772 }
773 }
774 return false;
775}
776
777bool QuicFramer::IsSupportedVersion(const ParsedQuicVersion version) const {
778 for (const ParsedQuicVersion& supported_version : supported_versions_) {
779 if (version == supported_version) {
780 return true;
781 }
782 }
783 return false;
784}
785
786size_t QuicFramer::GetSerializedFrameLength(
787 const QuicFrame& frame,
788 size_t free_bytes,
789 bool first_frame,
790 bool last_frame,
791 QuicPacketNumberLength packet_number_length) {
792 // Prevent a rare crash reported in b/19458523.
793 if (frame.type == ACK_FRAME && frame.ack_frame == nullptr) {
794 QUIC_BUG << "Cannot compute the length of a null ack frame. free_bytes:"
795 << free_bytes << " first_frame:" << first_frame
796 << " last_frame:" << last_frame
797 << " seq num length:" << packet_number_length;
798 set_error(QUIC_INTERNAL_ERROR);
799 visitor_->OnError(this);
800 return 0;
801 }
802 if (frame.type == PADDING_FRAME) {
803 if (frame.padding_frame.num_padding_bytes == -1) {
804 // Full padding to the end of the packet.
805 return free_bytes;
806 } else {
807 // Lite padding.
808 return free_bytes <
809 static_cast<size_t>(frame.padding_frame.num_padding_bytes)
810 ? free_bytes
811 : frame.padding_frame.num_padding_bytes;
812 }
813 }
814
815 size_t frame_len =
816 ComputeFrameLength(frame, last_frame, packet_number_length);
817 if (frame_len <= free_bytes) {
818 // Frame fits within packet. Note that acks may be truncated.
819 return frame_len;
820 }
821 // Only truncate the first frame in a packet, so if subsequent ones go
822 // over, stop including more frames.
823 if (!first_frame) {
824 return 0;
825 }
826 bool can_truncate =
827 frame.type == ACK_FRAME &&
fayang43697fd2020-04-21 11:13:43 -0700828 free_bytes >= GetMinAckFrameSize(version_.transport_version,
829 *frame.ack_frame,
830 local_ack_delay_exponent_);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500831 if (can_truncate) {
dschinazi66dea072019-04-09 11:41:06 -0700832 // Truncate the frame so the packet will not exceed kMaxOutgoingPacketSize.
QUICHE teama6ef0a62019-03-07 20:34:33 -0500833 // Note that we may not use every byte of the writer in this case.
834 QUIC_DLOG(INFO) << ENDPOINT
835 << "Truncating large frame, free bytes: " << free_bytes;
836 return free_bytes;
837 }
838 return 0;
839}
840
841QuicFramer::AckFrameInfo::AckFrameInfo()
842 : max_block_length(0), first_block_length(0), num_ack_blocks(0) {}
843
844QuicFramer::AckFrameInfo::AckFrameInfo(const AckFrameInfo& other) = default;
845
846QuicFramer::AckFrameInfo::~AckFrameInfo() {}
847
848bool QuicFramer::WriteIetfLongHeaderLength(const QuicPacketHeader& header,
849 QuicDataWriter* writer,
850 size_t length_field_offset,
851 EncryptionLevel level) {
852 if (!QuicVersionHasLongHeaderLengths(transport_version()) ||
853 !header.version_flag || length_field_offset == 0) {
854 return true;
855 }
856 if (writer->length() < length_field_offset ||
857 writer->length() - length_field_offset <
858 kQuicDefaultLongHeaderLengthLength) {
859 set_detailed_error("Invalid length_field_offset.");
860 QUIC_BUG << "Invalid length_field_offset.";
861 return false;
862 }
863 size_t length_to_write = writer->length() - length_field_offset -
864 kQuicDefaultLongHeaderLengthLength;
865 // Add length of auth tag.
866 length_to_write = GetCiphertextSize(level, length_to_write);
867
868 QuicDataWriter length_writer(writer->length() - length_field_offset,
869 writer->data() + length_field_offset);
870 if (!length_writer.WriteVarInt62(length_to_write,
871 kQuicDefaultLongHeaderLengthLength)) {
872 set_detailed_error("Failed to overwrite long header length.");
873 QUIC_BUG << "Failed to overwrite long header length.";
874 return false;
875 }
876 return true;
877}
878
879size_t QuicFramer::BuildDataPacket(const QuicPacketHeader& header,
880 const QuicFrames& frames,
881 char* buffer,
882 size_t packet_length,
883 EncryptionLevel level) {
dschinaziecad9642019-10-01 10:44:17 -0700884 QUIC_BUG_IF(header.version_flag &&
885 VersionHasIetfInvariantHeader(transport_version()) &&
886 header.long_packet_type == RETRY && !frames.empty())
887 << "IETF RETRY packets cannot contain frames " << header;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500888 QuicDataWriter writer(packet_length, buffer);
889 size_t length_field_offset = 0;
890 if (!AppendPacketHeader(header, &writer, &length_field_offset)) {
891 QUIC_BUG << "AppendPacketHeader failed";
892 return 0;
893 }
894
fkastenholz305e1732019-06-18 05:01:22 -0700895 if (VersionHasIetfQuicFrames(transport_version())) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500896 if (AppendIetfFrames(frames, &writer) == 0) {
897 return 0;
898 }
899 if (!WriteIetfLongHeaderLength(header, &writer, length_field_offset,
900 level)) {
901 return 0;
902 }
903 return writer.length();
904 }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500905
906 size_t i = 0;
907 for (const QuicFrame& frame : frames) {
908 // Determine if we should write stream frame length in header.
909 const bool last_frame_in_packet = i == frames.size() - 1;
910 if (!AppendTypeByte(frame, last_frame_in_packet, &writer)) {
911 QUIC_BUG << "AppendTypeByte failed";
912 return 0;
913 }
914
915 switch (frame.type) {
916 case PADDING_FRAME:
917 if (!AppendPaddingFrame(frame.padding_frame, &writer)) {
918 QUIC_BUG << "AppendPaddingFrame of "
919 << frame.padding_frame.num_padding_bytes << " failed";
920 return 0;
921 }
922 break;
923 case STREAM_FRAME:
924 if (!AppendStreamFrame(frame.stream_frame, last_frame_in_packet,
925 &writer)) {
926 QUIC_BUG << "AppendStreamFrame failed";
927 return 0;
928 }
929 break;
930 case ACK_FRAME:
931 if (!AppendAckFrameAndTypeByte(*frame.ack_frame, &writer)) {
932 QUIC_BUG << "AppendAckFrameAndTypeByte failed: " << detailed_error_;
933 return 0;
934 }
935 break;
936 case STOP_WAITING_FRAME:
937 if (!AppendStopWaitingFrame(header, frame.stop_waiting_frame,
938 &writer)) {
939 QUIC_BUG << "AppendStopWaitingFrame failed";
940 return 0;
941 }
942 break;
943 case MTU_DISCOVERY_FRAME:
944 // MTU discovery frames are serialized as ping frames.
945 QUIC_FALLTHROUGH_INTENDED;
946 case PING_FRAME:
947 // Ping has no payload.
948 break;
949 case RST_STREAM_FRAME:
950 if (!AppendRstStreamFrame(*frame.rst_stream_frame, &writer)) {
951 QUIC_BUG << "AppendRstStreamFrame failed";
952 return 0;
953 }
954 break;
955 case CONNECTION_CLOSE_FRAME:
956 if (!AppendConnectionCloseFrame(*frame.connection_close_frame,
957 &writer)) {
958 QUIC_BUG << "AppendConnectionCloseFrame failed";
959 return 0;
960 }
961 break;
962 case GOAWAY_FRAME:
963 if (!AppendGoAwayFrame(*frame.goaway_frame, &writer)) {
964 QUIC_BUG << "AppendGoAwayFrame failed";
965 return 0;
966 }
967 break;
968 case WINDOW_UPDATE_FRAME:
969 if (!AppendWindowUpdateFrame(*frame.window_update_frame, &writer)) {
970 QUIC_BUG << "AppendWindowUpdateFrame failed";
971 return 0;
972 }
973 break;
974 case BLOCKED_FRAME:
975 if (!AppendBlockedFrame(*frame.blocked_frame, &writer)) {
976 QUIC_BUG << "AppendBlockedFrame failed";
977 return 0;
978 }
979 break;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500980 case NEW_CONNECTION_ID_FRAME:
981 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -0700982 "Attempt to append NEW_CONNECTION_ID frame and not in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -0500983 return RaiseError(QUIC_INTERNAL_ERROR);
984 case RETIRE_CONNECTION_ID_FRAME:
985 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -0700986 "Attempt to append RETIRE_CONNECTION_ID frame and not in IETF "
987 "QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -0500988 return RaiseError(QUIC_INTERNAL_ERROR);
989 case NEW_TOKEN_FRAME:
990 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -0700991 "Attempt to append NEW_TOKEN_ID frame and not in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -0500992 return RaiseError(QUIC_INTERNAL_ERROR);
fkastenholz3c4eabf2019-04-22 07:49:59 -0700993 case MAX_STREAMS_FRAME:
QUICHE teama6ef0a62019-03-07 20:34:33 -0500994 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -0700995 "Attempt to append MAX_STREAMS frame and not in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -0500996 return RaiseError(QUIC_INTERNAL_ERROR);
fkastenholz3c4eabf2019-04-22 07:49:59 -0700997 case STREAMS_BLOCKED_FRAME:
QUICHE teama6ef0a62019-03-07 20:34:33 -0500998 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -0700999 "Attempt to append STREAMS_BLOCKED frame and not in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05001000 return RaiseError(QUIC_INTERNAL_ERROR);
1001 case PATH_RESPONSE_FRAME:
1002 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -07001003 "Attempt to append PATH_RESPONSE frame and not in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05001004 return RaiseError(QUIC_INTERNAL_ERROR);
1005 case PATH_CHALLENGE_FRAME:
1006 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -07001007 "Attempt to append PATH_CHALLENGE frame and not in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05001008 return RaiseError(QUIC_INTERNAL_ERROR);
1009 case STOP_SENDING_FRAME:
1010 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -07001011 "Attempt to append STOP_SENDING frame and not in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05001012 return RaiseError(QUIC_INTERNAL_ERROR);
1013 case MESSAGE_FRAME:
1014 if (!AppendMessageFrameAndTypeByte(*frame.message_frame,
1015 last_frame_in_packet, &writer)) {
1016 QUIC_BUG << "AppendMessageFrame failed";
1017 return 0;
1018 }
1019 break;
1020 case CRYPTO_FRAME:
QUICHE teamea740082019-03-11 17:58:43 -07001021 if (!QuicVersionUsesCryptoFrames(version_.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001022 set_detailed_error(
1023 "Attempt to append CRYPTO frame in version prior to 47.");
1024 return RaiseError(QUIC_INTERNAL_ERROR);
1025 }
1026 if (!AppendCryptoFrame(*frame.crypto_frame, &writer)) {
1027 QUIC_BUG << "AppendCryptoFrame failed";
1028 return 0;
1029 }
1030 break;
fayang5c362882020-06-16 07:39:39 -07001031 case HANDSHAKE_DONE_FRAME:
1032 // HANDSHAKE_DONE has no payload.
1033 break;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001034 default:
1035 RaiseError(QUIC_INVALID_FRAME_DATA);
1036 QUIC_BUG << "QUIC_INVALID_FRAME_DATA";
1037 return 0;
1038 }
1039 ++i;
1040 }
1041
dschinazid1428492019-09-17 23:59:30 -07001042 if (!WriteIetfLongHeaderLength(header, &writer, length_field_offset, level)) {
1043 return 0;
1044 }
1045
QUICHE teama6ef0a62019-03-07 20:34:33 -05001046 return writer.length();
1047}
1048
1049size_t QuicFramer::AppendIetfFrames(const QuicFrames& frames,
1050 QuicDataWriter* writer) {
1051 size_t i = 0;
1052 for (const QuicFrame& frame : frames) {
1053 // Determine if we should write stream frame length in header.
1054 const bool last_frame_in_packet = i == frames.size() - 1;
haoyuewangbe38a7d2020-06-23 10:18:35 -07001055 if (!AppendIetfFrameType(frame, last_frame_in_packet, writer)) {
1056 QUIC_BUG << "AppendIetfFrameType failed: " << detailed_error();
QUICHE teama6ef0a62019-03-07 20:34:33 -05001057 return 0;
1058 }
1059
1060 switch (frame.type) {
1061 case PADDING_FRAME:
1062 if (!AppendPaddingFrame(frame.padding_frame, writer)) {
1063 QUIC_BUG << "AppendPaddingFrame of "
1064 << frame.padding_frame.num_padding_bytes
1065 << " failed: " << detailed_error();
1066 return 0;
1067 }
1068 break;
1069 case STREAM_FRAME:
1070 if (!AppendStreamFrame(frame.stream_frame, last_frame_in_packet,
1071 writer)) {
1072 QUIC_BUG << "AppendStreamFrame failed: " << detailed_error();
1073 return 0;
1074 }
1075 break;
1076 case ACK_FRAME:
1077 if (!AppendIetfAckFrameAndTypeByte(*frame.ack_frame, writer)) {
QUICHE team4fe0b942019-03-08 09:25:06 -05001078 QUIC_BUG << "AppendIetfAckFrameAndTypeByte failed: "
1079 << detailed_error();
QUICHE teama6ef0a62019-03-07 20:34:33 -05001080 return 0;
1081 }
1082 break;
1083 case STOP_WAITING_FRAME:
1084 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -07001085 "Attempt to append STOP WAITING frame in IETF QUIC.");
dschinazi4a64ab62019-10-01 12:54:00 -07001086 RaiseError(QUIC_INTERNAL_ERROR);
1087 QUIC_BUG << detailed_error();
1088 return 0;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001089 case MTU_DISCOVERY_FRAME:
1090 // MTU discovery frames are serialized as ping frames.
1091 QUIC_FALLTHROUGH_INTENDED;
1092 case PING_FRAME:
1093 // Ping has no payload.
1094 break;
1095 case RST_STREAM_FRAME:
1096 if (!AppendRstStreamFrame(*frame.rst_stream_frame, writer)) {
1097 QUIC_BUG << "AppendRstStreamFrame failed: " << detailed_error();
1098 return 0;
1099 }
1100 break;
1101 case CONNECTION_CLOSE_FRAME:
fkastenholz72f509b2019-04-10 09:17:49 -07001102 if (!AppendIetfConnectionCloseFrame(*frame.connection_close_frame,
1103 writer)) {
1104 QUIC_BUG << "AppendIetfConnectionCloseFrame failed: "
1105 << detailed_error();
QUICHE teama6ef0a62019-03-07 20:34:33 -05001106 return 0;
1107 }
1108 break;
1109 case GOAWAY_FRAME:
fkastenholz305e1732019-06-18 05:01:22 -07001110 set_detailed_error("Attempt to append GOAWAY frame in IETF QUIC.");
dschinazi4a64ab62019-10-01 12:54:00 -07001111 RaiseError(QUIC_INTERNAL_ERROR);
1112 QUIC_BUG << detailed_error();
1113 return 0;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001114 case WINDOW_UPDATE_FRAME:
1115 // Depending on whether there is a stream ID or not, will be either a
1116 // MAX STREAM DATA frame or a MAX DATA frame.
1117 if (frame.window_update_frame->stream_id ==
1118 QuicUtils::GetInvalidStreamId(transport_version())) {
1119 if (!AppendMaxDataFrame(*frame.window_update_frame, writer)) {
1120 QUIC_BUG << "AppendMaxDataFrame failed: " << detailed_error();
1121 return 0;
1122 }
1123 } else {
1124 if (!AppendMaxStreamDataFrame(*frame.window_update_frame, writer)) {
1125 QUIC_BUG << "AppendMaxStreamDataFrame failed: " << detailed_error();
1126 return 0;
1127 }
1128 }
1129 break;
1130 case BLOCKED_FRAME:
1131 if (!AppendBlockedFrame(*frame.blocked_frame, writer)) {
1132 QUIC_BUG << "AppendBlockedFrame failed: " << detailed_error();
1133 return 0;
1134 }
1135 break;
fkastenholz3c4eabf2019-04-22 07:49:59 -07001136 case MAX_STREAMS_FRAME:
1137 if (!AppendMaxStreamsFrame(frame.max_streams_frame, writer)) {
dschinazi4a64ab62019-10-01 12:54:00 -07001138 QUIC_BUG << "AppendMaxStreamsFrame failed: " << detailed_error();
QUICHE teama6ef0a62019-03-07 20:34:33 -05001139 return 0;
1140 }
1141 break;
fkastenholz3c4eabf2019-04-22 07:49:59 -07001142 case STREAMS_BLOCKED_FRAME:
1143 if (!AppendStreamsBlockedFrame(frame.streams_blocked_frame, writer)) {
dschinazi4a64ab62019-10-01 12:54:00 -07001144 QUIC_BUG << "AppendStreamsBlockedFrame failed: " << detailed_error();
QUICHE teama6ef0a62019-03-07 20:34:33 -05001145 return 0;
1146 }
1147 break;
1148 case NEW_CONNECTION_ID_FRAME:
1149 if (!AppendNewConnectionIdFrame(*frame.new_connection_id_frame,
1150 writer)) {
1151 QUIC_BUG << "AppendNewConnectionIdFrame failed: " << detailed_error();
1152 return 0;
1153 }
1154 break;
1155 case RETIRE_CONNECTION_ID_FRAME:
1156 if (!AppendRetireConnectionIdFrame(*frame.retire_connection_id_frame,
1157 writer)) {
1158 QUIC_BUG << "AppendRetireConnectionIdFrame failed: "
1159 << detailed_error();
1160 return 0;
1161 }
1162 break;
1163 case NEW_TOKEN_FRAME:
1164 if (!AppendNewTokenFrame(*frame.new_token_frame, writer)) {
1165 QUIC_BUG << "AppendNewTokenFrame failed: " << detailed_error();
1166 return 0;
1167 }
1168 break;
1169 case STOP_SENDING_FRAME:
1170 if (!AppendStopSendingFrame(*frame.stop_sending_frame, writer)) {
1171 QUIC_BUG << "AppendStopSendingFrame failed: " << detailed_error();
1172 return 0;
1173 }
1174 break;
1175 case PATH_CHALLENGE_FRAME:
1176 if (!AppendPathChallengeFrame(*frame.path_challenge_frame, writer)) {
1177 QUIC_BUG << "AppendPathChallengeFrame failed: " << detailed_error();
1178 return 0;
1179 }
1180 break;
1181 case PATH_RESPONSE_FRAME:
1182 if (!AppendPathResponseFrame(*frame.path_response_frame, writer)) {
1183 QUIC_BUG << "AppendPathResponseFrame failed: " << detailed_error();
1184 return 0;
1185 }
1186 break;
1187 case MESSAGE_FRAME:
1188 if (!AppendMessageFrameAndTypeByte(*frame.message_frame,
1189 last_frame_in_packet, writer)) {
1190 QUIC_BUG << "AppendMessageFrame failed: " << detailed_error();
1191 return 0;
1192 }
1193 break;
1194 case CRYPTO_FRAME:
1195 if (!AppendCryptoFrame(*frame.crypto_frame, writer)) {
1196 QUIC_BUG << "AppendCryptoFrame failed: " << detailed_error();
1197 return 0;
1198 }
1199 break;
fayang01062942020-01-22 07:23:23 -08001200 case HANDSHAKE_DONE_FRAME:
1201 // HANDSHAKE_DONE has no payload.
1202 break;
haoyuewang6a6a0ff2020-06-23 16:32:26 -07001203 case ACK_FREQUENCY_FRAME:
1204 if (!AppendAckFrequencyFrame(*frame.ack_frequency_frame, writer)) {
1205 QUIC_BUG << "AppendAckFrequencyFrame failed: " << detailed_error();
1206 return 0;
1207 }
1208 break;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001209 default:
QUICHE teama6ef0a62019-03-07 20:34:33 -05001210 set_detailed_error("Tried to append unknown frame type.");
dschinazi4a64ab62019-10-01 12:54:00 -07001211 RaiseError(QUIC_INVALID_FRAME_DATA);
1212 QUIC_BUG << "QUIC_INVALID_FRAME_DATA: " << frame.type;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001213 return 0;
1214 }
1215 ++i;
1216 }
1217
1218 return writer->length();
1219}
1220
QUICHE teama6ef0a62019-03-07 20:34:33 -05001221// static
1222std::unique_ptr<QuicEncryptedPacket> QuicFramer::BuildPublicResetPacket(
1223 const QuicPublicResetPacket& packet) {
1224 CryptoHandshakeMessage reset;
1225 reset.set_tag(kPRST);
1226 reset.SetValue(kRNON, packet.nonce_proof);
1227 if (packet.client_address.host().address_family() !=
1228 IpAddressFamily::IP_UNSPEC) {
1229 // packet.client_address is non-empty.
1230 QuicSocketAddressCoder address_coder(packet.client_address);
vasilvvc48c8712019-03-11 13:38:16 -07001231 std::string serialized_address = address_coder.Encode();
QUICHE teama6ef0a62019-03-07 20:34:33 -05001232 if (serialized_address.empty()) {
1233 return nullptr;
1234 }
1235 reset.SetStringPiece(kCADR, serialized_address);
1236 }
1237 if (!packet.endpoint_id.empty()) {
1238 reset.SetStringPiece(kEPID, packet.endpoint_id);
1239 }
1240 const QuicData& reset_serialized = reset.GetSerialized();
1241
1242 size_t len = kPublicFlagsSize + packet.connection_id.length() +
1243 reset_serialized.length();
1244 std::unique_ptr<char[]> buffer(new char[len]);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001245 QuicDataWriter writer(len, buffer.get());
1246
1247 uint8_t flags = static_cast<uint8_t>(PACKET_PUBLIC_FLAGS_RST |
1248 PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID);
1249 // This hack makes post-v33 public reset packet look like pre-v33 packets.
1250 flags |= static_cast<uint8_t>(PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID_OLD);
1251 if (!writer.WriteUInt8(flags)) {
1252 return nullptr;
1253 }
1254
1255 if (!writer.WriteConnectionId(packet.connection_id)) {
1256 return nullptr;
1257 }
1258
1259 if (!writer.WriteBytes(reset_serialized.data(), reset_serialized.length())) {
1260 return nullptr;
1261 }
1262
vasilvv0fc587f2019-09-06 13:33:08 -07001263 return std::make_unique<QuicEncryptedPacket>(buffer.release(), len, true);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001264}
1265
1266// static
1267std::unique_ptr<QuicEncryptedPacket> QuicFramer::BuildIetfStatelessResetPacket(
dschinazi17d42422019-06-18 16:35:07 -07001268 QuicConnectionId /*connection_id*/,
QUICHE teama6ef0a62019-03-07 20:34:33 -05001269 QuicUint128 stateless_reset_token) {
1270 QUIC_DVLOG(1) << "Building IETF stateless reset packet.";
1271 size_t len = kPacketHeaderTypeSize + kMinRandomBytesLengthInStatelessReset +
1272 sizeof(stateless_reset_token);
1273 std::unique_ptr<char[]> buffer(new char[len]);
1274 QuicDataWriter writer(len, buffer.get());
1275
1276 uint8_t type = 0;
1277 type |= FLAGS_FIXED_BIT;
1278 type |= FLAGS_SHORT_HEADER_RESERVED_1;
1279 type |= FLAGS_SHORT_HEADER_RESERVED_2;
fayang36825da2019-08-21 14:01:27 -07001280 type |= PacketNumberLengthToOnWireValue(PACKET_1BYTE_PACKET_NUMBER);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001281
1282 // Append type byte.
1283 if (!writer.WriteUInt8(type)) {
1284 return nullptr;
1285 }
1286 // Append random bytes.
1287 if (!writer.WriteRandomBytes(QuicRandom::GetInstance(),
1288 kMinRandomBytesLengthInStatelessReset)) {
1289 return nullptr;
1290 }
1291
1292 // Append stateless reset token.
1293 if (!writer.WriteBytes(&stateless_reset_token,
1294 sizeof(stateless_reset_token))) {
1295 return nullptr;
1296 }
vasilvv0fc587f2019-09-06 13:33:08 -07001297 return std::make_unique<QuicEncryptedPacket>(buffer.release(), len, true);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001298}
1299
1300// static
1301std::unique_ptr<QuicEncryptedPacket> QuicFramer::BuildVersionNegotiationPacket(
dschinazi8ff74822019-05-28 16:37:20 -07001302 QuicConnectionId server_connection_id,
dschinazib417d602019-05-29 13:08:45 -07001303 QuicConnectionId client_connection_id,
QUICHE teama6ef0a62019-03-07 20:34:33 -05001304 bool ietf_quic,
dschinazi48ac9192019-07-31 00:07:26 -07001305 bool use_length_prefix,
QUICHE teama6ef0a62019-03-07 20:34:33 -05001306 const ParsedQuicVersionVector& versions) {
dschinazi1ac22cc2019-06-25 11:47:50 -07001307 ParsedQuicVersionVector wire_versions = versions;
dschinazi5fc6d0c2019-11-26 16:22:05 -08001308 // Add a version reserved for negotiation as suggested by the
1309 // "Using Reserved Versions" section of draft-ietf-quic-transport.
1310 if (wire_versions.empty()) {
1311 // Ensure that version negotiation packets we send have at least two
1312 // versions. This guarantees that, under all circumstances, all QUIC
1313 // packets we send are at least 14 bytes long.
1314 wire_versions = {QuicVersionReservedForNegotiation(),
1315 QuicVersionReservedForNegotiation()};
dschinazi1ac22cc2019-06-25 11:47:50 -07001316 } else {
dschinazi5fc6d0c2019-11-26 16:22:05 -08001317 // This is not uniformely distributed but is acceptable since no security
1318 // depends on this randomness.
1319 size_t version_index = 0;
1320 const bool disable_randomness =
1321 GetQuicFlag(FLAGS_quic_disable_version_negotiation_grease_randomness);
1322 if (!disable_randomness) {
1323 version_index =
1324 QuicRandom::GetInstance()->RandUint64() % (wire_versions.size() + 1);
dschinazi1ac22cc2019-06-25 11:47:50 -07001325 }
dschinazi5fc6d0c2019-11-26 16:22:05 -08001326 wire_versions.insert(wire_versions.begin() + version_index,
1327 QuicVersionReservedForNegotiation());
dschinazi1ac22cc2019-06-25 11:47:50 -07001328 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001329 if (ietf_quic) {
dschinazi1ac22cc2019-06-25 11:47:50 -07001330 return BuildIetfVersionNegotiationPacket(
dschinazi48ac9192019-07-31 00:07:26 -07001331 use_length_prefix, server_connection_id, client_connection_id,
1332 wire_versions);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001333 }
dschinazib417d602019-05-29 13:08:45 -07001334
1335 // The GQUIC encoding does not support encoding client connection IDs.
1336 DCHECK(client_connection_id.IsEmpty());
dschinazi48ac9192019-07-31 00:07:26 -07001337 // The GQUIC encoding does not support length-prefixed connection IDs.
1338 DCHECK(!use_length_prefix);
dschinazib417d602019-05-29 13:08:45 -07001339
dschinazi1ac22cc2019-06-25 11:47:50 -07001340 DCHECK(!wire_versions.empty());
dschinazi8ff74822019-05-28 16:37:20 -07001341 size_t len = kPublicFlagsSize + server_connection_id.length() +
dschinazi1ac22cc2019-06-25 11:47:50 -07001342 wire_versions.size() * kQuicVersionSize;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001343 std::unique_ptr<char[]> buffer(new char[len]);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001344 QuicDataWriter writer(len, buffer.get());
1345
1346 uint8_t flags = static_cast<uint8_t>(
1347 PACKET_PUBLIC_FLAGS_VERSION | PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID |
QUICHE teama6ef0a62019-03-07 20:34:33 -05001348 PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID_OLD);
1349 if (!writer.WriteUInt8(flags)) {
1350 return nullptr;
1351 }
1352
dschinazi8ff74822019-05-28 16:37:20 -07001353 if (!writer.WriteConnectionId(server_connection_id)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001354 return nullptr;
1355 }
1356
dschinazi1ac22cc2019-06-25 11:47:50 -07001357 for (const ParsedQuicVersion& version : wire_versions) {
nharpereaab5ad2019-05-31 12:23:25 -07001358 if (!writer.WriteUInt32(CreateQuicVersionLabel(version))) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001359 return nullptr;
1360 }
1361 }
1362
vasilvv0fc587f2019-09-06 13:33:08 -07001363 return std::make_unique<QuicEncryptedPacket>(buffer.release(), len, true);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001364}
1365
1366// static
1367std::unique_ptr<QuicEncryptedPacket>
1368QuicFramer::BuildIetfVersionNegotiationPacket(
dschinazi48ac9192019-07-31 00:07:26 -07001369 bool use_length_prefix,
dschinazib417d602019-05-29 13:08:45 -07001370 QuicConnectionId server_connection_id,
1371 QuicConnectionId client_connection_id,
QUICHE teama6ef0a62019-03-07 20:34:33 -05001372 const ParsedQuicVersionVector& versions) {
dschinazi48ac9192019-07-31 00:07:26 -07001373 QUIC_DVLOG(1) << "Building IETF version negotiation packet with"
1374 << (use_length_prefix ? "" : "out")
1375 << " length prefix, server_connection_id "
1376 << server_connection_id << " client_connection_id "
1377 << client_connection_id << " versions "
dschinazi5a354c92019-05-09 12:18:53 -07001378 << ParsedQuicVersionVectorToString(versions);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001379 DCHECK(!versions.empty());
1380 size_t len = kPacketHeaderTypeSize + kConnectionIdLengthSize +
dschinazib417d602019-05-29 13:08:45 -07001381 client_connection_id.length() + server_connection_id.length() +
QUICHE teama6ef0a62019-03-07 20:34:33 -05001382 (versions.size() + 1) * kQuicVersionSize;
dschinazi48ac9192019-07-31 00:07:26 -07001383 if (use_length_prefix) {
1384 // When using length-prefixed connection IDs, packets carry two lengths
1385 // instead of one.
1386 len += kConnectionIdLengthSize;
1387 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001388 std::unique_ptr<char[]> buffer(new char[len]);
1389 QuicDataWriter writer(len, buffer.get());
1390
1391 // TODO(fayang): Randomly select a value for the type.
dschinazi0366de92019-06-18 20:00:27 -07001392 uint8_t type = static_cast<uint8_t>(FLAGS_LONG_HEADER | FLAGS_FIXED_BIT);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001393 if (!writer.WriteUInt8(type)) {
1394 return nullptr;
1395 }
1396
1397 if (!writer.WriteUInt32(0)) {
1398 return nullptr;
1399 }
1400
dschinazi48ac9192019-07-31 00:07:26 -07001401 if (!AppendIetfConnectionIds(true, use_length_prefix, client_connection_id,
1402 server_connection_id, &writer)) {
dschinazi1f485a12019-05-13 11:57:01 -07001403 return nullptr;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001404 }
1405
1406 for (const ParsedQuicVersion& version : versions) {
nharpereaab5ad2019-05-31 12:23:25 -07001407 if (!writer.WriteUInt32(CreateQuicVersionLabel(version))) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001408 return nullptr;
1409 }
1410 }
1411
vasilvv0fc587f2019-09-06 13:33:08 -07001412 return std::make_unique<QuicEncryptedPacket>(buffer.release(), len, true);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001413}
1414
1415bool QuicFramer::ProcessPacket(const QuicEncryptedPacket& packet) {
1416 QuicDataReader reader(packet.data(), packet.length());
1417
1418 bool packet_has_ietf_packet_header = false;
1419 if (infer_packet_header_type_from_version_) {
1420 packet_has_ietf_packet_header =
fayangd4291e42019-05-30 10:31:21 -07001421 VersionHasIetfInvariantHeader(version_.transport_version);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001422 } else if (!reader.IsDoneReading()) {
1423 uint8_t type = reader.PeekByte();
1424 packet_has_ietf_packet_header = QuicUtils::IsIetfPacketHeader(type);
1425 }
1426 if (packet_has_ietf_packet_header) {
1427 QUIC_DVLOG(1) << ENDPOINT << "Processing IETF QUIC packet.";
1428 }
1429
1430 visitor_->OnPacket();
1431
1432 QuicPacketHeader header;
1433 if (!ProcessPublicHeader(&reader, packet_has_ietf_packet_header, &header)) {
1434 DCHECK_NE("", detailed_error_);
1435 QUIC_DVLOG(1) << ENDPOINT << "Unable to process public header. Error: "
1436 << detailed_error_;
1437 DCHECK_NE("", detailed_error_);
1438 RecordDroppedPacketReason(DroppedPacketReason::INVALID_PUBLIC_HEADER);
1439 return RaiseError(QUIC_INVALID_PACKET_HEADER);
1440 }
1441
1442 if (!visitor_->OnUnauthenticatedPublicHeader(header)) {
1443 // The visitor suppresses further processing of the packet.
1444 return true;
1445 }
1446
dschinazie0df3f72019-05-06 16:37:51 -07001447 if (IsVersionNegotiation(header, packet_has_ietf_packet_header)) {
dschinazi072da7c2019-05-07 17:57:42 -07001448 if (perspective_ == Perspective::IS_CLIENT) {
1449 QUIC_DVLOG(1) << "Client received version negotiation packet";
1450 return ProcessVersionNegotiationPacket(&reader, header);
1451 } else {
1452 QUIC_DLOG(ERROR) << "Server received version negotiation packet";
1453 set_detailed_error("Server received version negotiation packet.");
1454 return RaiseError(QUIC_INVALID_VERSION_NEGOTIATION_PACKET);
1455 }
dschinazie0df3f72019-05-06 16:37:51 -07001456 }
1457
1458 if (header.version_flag && header.version != version_) {
1459 if (perspective_ == Perspective::IS_SERVER) {
fayang8aba1ff2019-06-21 12:00:54 -07001460 if (!visitor_->OnProtocolVersionMismatch(header.version)) {
dschinazie0df3f72019-05-06 16:37:51 -07001461 RecordDroppedPacketReason(DroppedPacketReason::VERSION_MISMATCH);
1462 return true;
1463 }
1464 } else {
1465 // A client received a packet of a different version but that packet is
1466 // not a version negotiation packet. It is therefore invalid and dropped.
1467 QUIC_DLOG(ERROR) << "Client received unexpected version "
1468 << ParsedQuicVersionToString(header.version)
1469 << " instead of " << ParsedQuicVersionToString(version_);
1470 set_detailed_error("Client received unexpected version.");
1471 return RaiseError(QUIC_INVALID_VERSION);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001472 }
1473 }
1474
1475 bool rv;
dschinazie0df3f72019-05-06 16:37:51 -07001476 if (header.long_packet_type == RETRY) {
dschinazi244f6dc2019-05-06 15:45:16 -07001477 rv = ProcessRetryPacket(&reader, header);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001478 } else if (header.reset_flag) {
1479 rv = ProcessPublicResetPacket(&reader, header);
dschinazie8d7fa72019-04-05 14:44:40 -07001480 } else if (packet.length() <= kMaxIncomingPacketSize) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001481 // The optimized decryption algorithm implementations run faster when
1482 // operating on aligned memory.
dschinazie8d7fa72019-04-05 14:44:40 -07001483 QUIC_CACHELINE_ALIGNED char buffer[kMaxIncomingPacketSize];
QUICHE teama6ef0a62019-03-07 20:34:33 -05001484 if (packet_has_ietf_packet_header) {
1485 rv = ProcessIetfDataPacket(&reader, &header, packet, buffer,
bnc4e9283d2019-12-17 07:08:57 -08001486 QUICHE_ARRAYSIZE(buffer));
QUICHE teama6ef0a62019-03-07 20:34:33 -05001487 } else {
dschinazie8d7fa72019-04-05 14:44:40 -07001488 rv = ProcessDataPacket(&reader, &header, packet, buffer,
bnc4e9283d2019-12-17 07:08:57 -08001489 QUICHE_ARRAYSIZE(buffer));
QUICHE teama6ef0a62019-03-07 20:34:33 -05001490 }
1491 } else {
1492 std::unique_ptr<char[]> large_buffer(new char[packet.length()]);
1493 if (packet_has_ietf_packet_header) {
1494 rv = ProcessIetfDataPacket(&reader, &header, packet, large_buffer.get(),
1495 packet.length());
1496 } else {
1497 rv = ProcessDataPacket(&reader, &header, packet, large_buffer.get(),
1498 packet.length());
1499 }
1500 QUIC_BUG_IF(rv) << "QUIC should never successfully process packets larger"
dschinazie8d7fa72019-04-05 14:44:40 -07001501 << "than kMaxIncomingPacketSize. packet size:"
1502 << packet.length();
QUICHE teama6ef0a62019-03-07 20:34:33 -05001503 }
1504 return rv;
1505}
1506
1507bool QuicFramer::ProcessVersionNegotiationPacket(
1508 QuicDataReader* reader,
1509 const QuicPacketHeader& header) {
1510 DCHECK_EQ(Perspective::IS_CLIENT, perspective_);
1511
QUICHE team2252b702019-05-14 23:55:14 -04001512 QuicVersionNegotiationPacket packet(
1513 GetServerConnectionIdAsRecipient(header, perspective_));
QUICHE teama6ef0a62019-03-07 20:34:33 -05001514 // Try reading at least once to raise error if the packet is invalid.
1515 do {
1516 QuicVersionLabel version_label;
fayang40315542019-05-09 09:19:09 -07001517 if (!ProcessVersionLabel(reader, &version_label)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001518 set_detailed_error("Unable to read supported version in negotiation.");
1519 RecordDroppedPacketReason(
1520 DroppedPacketReason::INVALID_VERSION_NEGOTIATION_PACKET);
1521 return RaiseError(QUIC_INVALID_VERSION_NEGOTIATION_PACKET);
1522 }
nharper4fd11052019-06-04 14:23:22 -07001523 ParsedQuicVersion parsed_version = ParseQuicVersionLabel(version_label);
1524 if (parsed_version != UnsupportedQuicVersion()) {
1525 packet.versions.push_back(parsed_version);
1526 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001527 } while (!reader->IsDoneReading());
1528
dschinazi5a354c92019-05-09 12:18:53 -07001529 QUIC_DLOG(INFO) << ENDPOINT << "parsed version negotiation: "
1530 << ParsedQuicVersionVectorToString(packet.versions);
1531
QUICHE teama6ef0a62019-03-07 20:34:33 -05001532 visitor_->OnVersionNegotiationPacket(packet);
1533 return true;
1534}
1535
dschinazi244f6dc2019-05-06 15:45:16 -07001536bool QuicFramer::ProcessRetryPacket(QuicDataReader* reader,
1537 const QuicPacketHeader& header) {
1538 DCHECK_EQ(Perspective::IS_CLIENT, perspective_);
1539
dschinazi278efae2020-01-28 17:03:09 -08001540 if (version_.HasRetryIntegrityTag()) {
1541 DCHECK(version_.HasLengthPrefixedConnectionIds()) << version_;
1542 const size_t bytes_remaining = reader->BytesRemaining();
1543 if (bytes_remaining <= kRetryIntegrityTagLength) {
1544 set_detailed_error("Retry packet too short to parse integrity tag.");
1545 return false;
1546 }
1547 const size_t retry_token_length =
1548 bytes_remaining - kRetryIntegrityTagLength;
1549 DCHECK_GT(retry_token_length, 0u);
1550 quiche::QuicheStringPiece retry_token;
1551 if (!reader->ReadStringPiece(&retry_token, retry_token_length)) {
1552 set_detailed_error("Failed to read retry token.");
1553 return false;
1554 }
1555 quiche::QuicheStringPiece retry_without_tag =
1556 reader->PreviouslyReadPayload();
1557 quiche::QuicheStringPiece integrity_tag = reader->ReadRemainingPayload();
1558 DCHECK_EQ(integrity_tag.length(), kRetryIntegrityTagLength);
1559 visitor_->OnRetryPacket(EmptyQuicConnectionId(),
1560 header.source_connection_id, retry_token,
1561 integrity_tag, retry_without_tag);
1562 return true;
1563 }
1564
dschinazi244f6dc2019-05-06 15:45:16 -07001565 QuicConnectionId original_destination_connection_id;
dschinazi48ac9192019-07-31 00:07:26 -07001566 if (version_.HasLengthPrefixedConnectionIds()) {
1567 // Parse Original Destination Connection ID.
1568 if (!reader->ReadLengthPrefixedConnectionId(
1569 &original_destination_connection_id)) {
1570 set_detailed_error("Unable to read Original Destination ConnectionId.");
1571 return false;
1572 }
1573 } else {
1574 // Parse Original Destination Connection ID Length.
1575 uint8_t odcil = header.type_byte & 0xf;
1576 if (odcil != 0) {
1577 odcil += kConnectionIdLengthAdjustment;
1578 }
1579
1580 // Parse Original Destination Connection ID.
1581 if (!reader->ReadConnectionId(&original_destination_connection_id, odcil)) {
1582 set_detailed_error("Unable to read Original Destination ConnectionId.");
1583 return false;
1584 }
dschinazi244f6dc2019-05-06 15:45:16 -07001585 }
1586
dschinazib953d022019-08-01 18:05:58 -07001587 if (!QuicUtils::IsConnectionIdValidForVersion(
1588 original_destination_connection_id, transport_version())) {
1589 set_detailed_error(
1590 "Received Original Destination ConnectionId with invalid length.");
1591 return false;
1592 }
1593
dmcardlecf0bfcf2019-12-13 08:08:21 -08001594 quiche::QuicheStringPiece retry_token = reader->ReadRemainingPayload();
dschinazi244f6dc2019-05-06 15:45:16 -07001595 visitor_->OnRetryPacket(original_destination_connection_id,
dschinazi278efae2020-01-28 17:03:09 -08001596 header.source_connection_id, retry_token,
1597 /*retry_integrity_tag=*/quiche::QuicheStringPiece(),
1598 /*retry_without_tag=*/quiche::QuicheStringPiece());
dschinazi244f6dc2019-05-06 15:45:16 -07001599 return true;
1600}
1601
QUICHE teama6ef0a62019-03-07 20:34:33 -05001602// Seeks the current packet to check for a coalesced packet at the end.
1603// If the IETF length field only spans part of the outer packet,
1604// then there is a coalesced packet after this one.
1605void QuicFramer::MaybeProcessCoalescedPacket(
1606 const QuicDataReader& encrypted_reader,
1607 uint64_t remaining_bytes_length,
1608 const QuicPacketHeader& header) {
1609 if (header.remaining_packet_length >= remaining_bytes_length) {
1610 // There is no coalesced packet.
1611 return;
1612 }
1613
dmcardlecf0bfcf2019-12-13 08:08:21 -08001614 quiche::QuicheStringPiece remaining_data =
1615 encrypted_reader.PeekRemainingPayload();
QUICHE teama6ef0a62019-03-07 20:34:33 -05001616 DCHECK_EQ(remaining_data.length(), remaining_bytes_length);
1617
1618 const char* coalesced_data =
1619 remaining_data.data() + header.remaining_packet_length;
1620 uint64_t coalesced_data_length =
1621 remaining_bytes_length - header.remaining_packet_length;
1622 QuicDataReader coalesced_reader(coalesced_data, coalesced_data_length);
1623
1624 QuicPacketHeader coalesced_header;
1625 if (!ProcessIetfPacketHeader(&coalesced_reader, &coalesced_header)) {
fayangd1160ff2020-02-26 11:57:09 -08001626 // Some implementations pad their INITIAL packets by sending random invalid
1627 // data after the INITIAL, and that is allowed by the specification. If we
1628 // fail to parse a subsequent coalesced packet, simply ignore it.
1629 QUIC_DLOG(INFO) << ENDPOINT
1630 << "Failed to parse received coalesced header of length "
1631 << coalesced_data_length
1632 << " with error: " << detailed_error_ << ": "
1633 << quiche::QuicheTextUtils::HexEncode(coalesced_data,
1634 coalesced_data_length)
1635 << " previous header was " << header;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001636 return;
1637 }
1638
fayang2e445862020-04-06 08:39:22 -07001639 if (coalesced_header.destination_connection_id !=
1640 header.destination_connection_id) {
1641 // Drop coalesced packets with mismatched connection IDs.
1642 QUIC_DLOG(INFO) << ENDPOINT << "Received mismatched coalesced header "
fayangd1160ff2020-02-26 11:57:09 -08001643 << coalesced_header << " previous header was " << header;
fayang2e445862020-04-06 08:39:22 -07001644 QUIC_CODE_COUNT(
1645 quic_received_coalesced_packets_with_mismatched_connection_id);
1646 return;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001647 }
1648
1649 QuicEncryptedPacket coalesced_packet(coalesced_data, coalesced_data_length,
1650 /*owns_buffer=*/false);
1651 visitor_->OnCoalescedPacket(coalesced_packet);
1652}
1653
1654bool QuicFramer::MaybeProcessIetfLength(QuicDataReader* encrypted_reader,
1655 QuicPacketHeader* header) {
1656 if (!QuicVersionHasLongHeaderLengths(header->version.transport_version) ||
1657 header->form != IETF_QUIC_LONG_HEADER_PACKET ||
1658 (header->long_packet_type != INITIAL &&
1659 header->long_packet_type != HANDSHAKE &&
1660 header->long_packet_type != ZERO_RTT_PROTECTED)) {
1661 return true;
1662 }
1663 header->length_length = encrypted_reader->PeekVarInt62Length();
1664 if (!encrypted_reader->ReadVarInt62(&header->remaining_packet_length)) {
1665 set_detailed_error("Unable to read long header payload length.");
1666 return RaiseError(QUIC_INVALID_PACKET_HEADER);
1667 }
1668 uint64_t remaining_bytes_length = encrypted_reader->BytesRemaining();
1669 if (header->remaining_packet_length > remaining_bytes_length) {
1670 set_detailed_error("Long header payload length longer than packet.");
1671 return RaiseError(QUIC_INVALID_PACKET_HEADER);
1672 }
1673
1674 MaybeProcessCoalescedPacket(*encrypted_reader, remaining_bytes_length,
1675 *header);
1676
1677 if (!encrypted_reader->TruncateRemaining(header->remaining_packet_length)) {
1678 set_detailed_error("Length TruncateRemaining failed.");
1679 QUIC_BUG << "Length TruncateRemaining failed.";
1680 return RaiseError(QUIC_INVALID_PACKET_HEADER);
1681 }
1682 return true;
1683}
1684
1685bool QuicFramer::ProcessIetfDataPacket(QuicDataReader* encrypted_reader,
1686 QuicPacketHeader* header,
1687 const QuicEncryptedPacket& packet,
1688 char* decrypted_buffer,
1689 size_t buffer_length) {
1690 DCHECK_NE(GOOGLE_QUIC_PACKET, header->form);
1691 DCHECK(!header->has_possible_stateless_reset_token);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001692 header->length_length = VARIABLE_LENGTH_INTEGER_LENGTH_0;
1693 header->remaining_packet_length = 0;
1694 if (header->form == IETF_QUIC_SHORT_HEADER_PACKET &&
1695 perspective_ == Perspective::IS_CLIENT) {
1696 // Peek possible stateless reset token. Will only be used on decryption
1697 // failure.
dmcardlecf0bfcf2019-12-13 08:08:21 -08001698 quiche::QuicheStringPiece remaining =
1699 encrypted_reader->PeekRemainingPayload();
QUICHE teama6ef0a62019-03-07 20:34:33 -05001700 if (remaining.length() >= sizeof(header->possible_stateless_reset_token)) {
1701 header->has_possible_stateless_reset_token = true;
1702 memcpy(&header->possible_stateless_reset_token,
1703 &remaining.data()[remaining.length() -
1704 sizeof(header->possible_stateless_reset_token)],
1705 sizeof(header->possible_stateless_reset_token));
1706 }
1707 }
1708
QUICHE teama6ef0a62019-03-07 20:34:33 -05001709 if (!MaybeProcessIetfLength(encrypted_reader, header)) {
1710 return false;
1711 }
1712
dmcardlecf0bfcf2019-12-13 08:08:21 -08001713 quiche::QuicheStringPiece associated_data;
nharper55fa6132019-05-07 19:37:21 -07001714 std::vector<char> ad_storage;
dschinazi101d2eb2020-07-06 19:42:34 -07001715 QuicPacketNumber base_packet_number;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001716 if (header->form == IETF_QUIC_SHORT_HEADER_PACKET ||
1717 header->long_packet_type != VERSION_NEGOTIATION) {
dschinazi072da7c2019-05-07 17:57:42 -07001718 DCHECK(header->form == IETF_QUIC_SHORT_HEADER_PACKET ||
1719 header->long_packet_type == INITIAL ||
1720 header->long_packet_type == HANDSHAKE ||
1721 header->long_packet_type == ZERO_RTT_PROTECTED);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001722 // Process packet number.
QUICHE team10b22a12019-03-21 15:31:42 -07001723 if (supports_multiple_packet_number_spaces_) {
nharper55fa6132019-05-07 19:37:21 -07001724 PacketNumberSpace pn_space = GetPacketNumberSpace(*header);
1725 if (pn_space == NUM_PACKET_NUMBER_SPACES) {
1726 return RaiseError(QUIC_INVALID_PACKET_HEADER);
1727 }
1728 base_packet_number = largest_decrypted_packet_numbers_[pn_space];
QUICHE team10b22a12019-03-21 15:31:42 -07001729 } else {
1730 base_packet_number = largest_packet_number_;
1731 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001732 uint64_t full_packet_number;
nharper55fa6132019-05-07 19:37:21 -07001733 bool hp_removal_failed = false;
1734 if (version_.HasHeaderProtection()) {
1735 if (!RemoveHeaderProtection(encrypted_reader, packet, header,
1736 &full_packet_number, &ad_storage)) {
1737 hp_removal_failed = true;
1738 }
dmcardlecf0bfcf2019-12-13 08:08:21 -08001739 associated_data =
1740 quiche::QuicheStringPiece(ad_storage.data(), ad_storage.size());
nharper55fa6132019-05-07 19:37:21 -07001741 } else if (!ProcessAndCalculatePacketNumber(
1742 encrypted_reader, header->packet_number_length,
1743 base_packet_number, &full_packet_number)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001744 set_detailed_error("Unable to read packet number.");
1745 RecordDroppedPacketReason(DroppedPacketReason::INVALID_PACKET_NUMBER);
1746 return RaiseError(QUIC_INVALID_PACKET_HEADER);
1747 }
1748
nharper55fa6132019-05-07 19:37:21 -07001749 if (hp_removal_failed ||
dschinazi40f0b3d2020-02-19 17:54:05 -08001750 !IsValidFullPacketNumber(full_packet_number, version())) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001751 if (IsIetfStatelessResetPacket(*header)) {
1752 // This is a stateless reset packet.
1753 QuicIetfStatelessResetPacket packet(
1754 *header, header->possible_stateless_reset_token);
1755 visitor_->OnAuthenticatedIetfStatelessResetPacket(packet);
1756 return true;
1757 }
nharper55fa6132019-05-07 19:37:21 -07001758 if (hp_removal_failed) {
wub13d75452019-11-05 07:24:56 -08001759 const EncryptionLevel decryption_level = GetEncryptionLevel(*header);
1760 const bool has_decryption_key = decrypter_[decryption_level] != nullptr;
1761 visitor_->OnUndecryptablePacket(
1762 QuicEncryptedPacket(encrypted_reader->FullPayload()),
1763 decryption_level, has_decryption_key);
dschinaziba3d7be2020-05-06 15:54:34 -07001764 RecordDroppedPacketReason(DroppedPacketReason::DECRYPTION_FAILURE);
dschinazi163bda22020-04-01 13:34:43 -07001765 set_detailed_error(quiche::QuicheStrCat(
1766 "Unable to decrypt ", EncryptionLevelToString(decryption_level),
1767 " header protection", has_decryption_key ? "" : " (missing key)",
1768 "."));
nharper55fa6132019-05-07 19:37:21 -07001769 return RaiseError(QUIC_DECRYPTION_FAILURE);
1770 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001771 RecordDroppedPacketReason(DroppedPacketReason::INVALID_PACKET_NUMBER);
1772 set_detailed_error("packet numbers cannot be 0.");
1773 return RaiseError(QUIC_INVALID_PACKET_HEADER);
1774 }
1775 header->packet_number = QuicPacketNumber(full_packet_number);
1776 }
1777
1778 // A nonce should only present in SHLO from the server to the client when
1779 // using QUIC crypto.
1780 if (header->form == IETF_QUIC_LONG_HEADER_PACKET &&
1781 header->long_packet_type == ZERO_RTT_PROTECTED &&
1782 perspective_ == Perspective::IS_CLIENT &&
1783 version_.handshake_protocol == PROTOCOL_QUIC_CRYPTO) {
1784 if (!encrypted_reader->ReadBytes(
1785 reinterpret_cast<uint8_t*>(last_nonce_.data()),
1786 last_nonce_.size())) {
1787 set_detailed_error("Unable to read nonce.");
1788 RecordDroppedPacketReason(
1789 DroppedPacketReason::INVALID_DIVERSIFICATION_NONCE);
1790 return RaiseError(QUIC_INVALID_PACKET_HEADER);
1791 }
1792
1793 header->nonce = &last_nonce_;
1794 } else {
1795 header->nonce = nullptr;
1796 }
1797
1798 if (!visitor_->OnUnauthenticatedHeader(*header)) {
1799 set_detailed_error(
1800 "Visitor asked to stop processing of unauthenticated header.");
1801 return false;
1802 }
1803
dmcardlecf0bfcf2019-12-13 08:08:21 -08001804 quiche::QuicheStringPiece encrypted =
1805 encrypted_reader->ReadRemainingPayload();
nharper55fa6132019-05-07 19:37:21 -07001806 if (!version_.HasHeaderProtection()) {
1807 associated_data = GetAssociatedDataFromEncryptedPacket(
1808 version_.transport_version, packet,
1809 GetIncludedDestinationConnectionIdLength(*header),
1810 GetIncludedSourceConnectionIdLength(*header), header->version_flag,
1811 header->nonce != nullptr, header->packet_number_length,
1812 header->retry_token_length_length, header->retry_token.length(),
1813 header->length_length);
1814 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001815
1816 size_t decrypted_length = 0;
QUICHE team10b22a12019-03-21 15:31:42 -07001817 EncryptionLevel decrypted_level;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001818 if (!DecryptPayload(encrypted, associated_data, *header, decrypted_buffer,
QUICHE team10b22a12019-03-21 15:31:42 -07001819 buffer_length, &decrypted_length, &decrypted_level)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001820 if (IsIetfStatelessResetPacket(*header)) {
1821 // This is a stateless reset packet.
1822 QuicIetfStatelessResetPacket packet(
1823 *header, header->possible_stateless_reset_token);
1824 visitor_->OnAuthenticatedIetfStatelessResetPacket(packet);
1825 return true;
1826 }
wub13d75452019-11-05 07:24:56 -08001827 const EncryptionLevel decryption_level = GetEncryptionLevel(*header);
1828 const bool has_decryption_key = version_.KnowsWhichDecrypterToUse() &&
1829 decrypter_[decryption_level] != nullptr;
1830 visitor_->OnUndecryptablePacket(
1831 QuicEncryptedPacket(encrypted_reader->FullPayload()), decryption_level,
1832 has_decryption_key);
dschinazi163bda22020-04-01 13:34:43 -07001833 set_detailed_error(quiche::QuicheStrCat(
1834 "Unable to decrypt ", EncryptionLevelToString(decryption_level),
dschinazi101d2eb2020-07-06 19:42:34 -07001835 " payload with reconstructed packet number ",
1836 header->packet_number.ToString(), " (largest decrypted was ",
1837 base_packet_number.ToString(), ")",
dschinazi163bda22020-04-01 13:34:43 -07001838 has_decryption_key || !version_.KnowsWhichDecrypterToUse()
1839 ? ""
1840 : " (missing key)",
1841 "."));
QUICHE teama6ef0a62019-03-07 20:34:33 -05001842 RecordDroppedPacketReason(DroppedPacketReason::DECRYPTION_FAILURE);
1843 return RaiseError(QUIC_DECRYPTION_FAILURE);
1844 }
1845 QuicDataReader reader(decrypted_buffer, decrypted_length);
1846
1847 // Update the largest packet number after we have decrypted the packet
1848 // so we are confident is not attacker controlled.
QUICHE team10b22a12019-03-21 15:31:42 -07001849 if (supports_multiple_packet_number_spaces_) {
1850 largest_decrypted_packet_numbers_[QuicUtils::GetPacketNumberSpace(
1851 decrypted_level)]
1852 .UpdateMax(header->packet_number);
1853 } else {
1854 largest_packet_number_.UpdateMax(header->packet_number);
1855 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001856
1857 if (!visitor_->OnPacketHeader(*header)) {
1858 RecordDroppedPacketReason(DroppedPacketReason::INVALID_PACKET_NUMBER);
1859 // The visitor suppresses further processing of the packet.
1860 return true;
1861 }
1862
dschinazie8d7fa72019-04-05 14:44:40 -07001863 if (packet.length() > kMaxIncomingPacketSize) {
1864 set_detailed_error("Packet too large.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05001865 return RaiseError(QUIC_PACKET_TOO_LARGE);
1866 }
1867
1868 // Handle the payload.
fkastenholz305e1732019-06-18 05:01:22 -07001869 if (VersionHasIetfQuicFrames(version_.transport_version)) {
fkastenholza3660102019-08-28 05:19:24 -07001870 current_received_frame_type_ = 0;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001871 if (!ProcessIetfFrameData(&reader, *header)) {
fkastenholza3660102019-08-28 05:19:24 -07001872 current_received_frame_type_ = 0;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001873 DCHECK_NE(QUIC_NO_ERROR, error_); // ProcessIetfFrameData sets the error.
1874 DCHECK_NE("", detailed_error_);
1875 QUIC_DLOG(WARNING) << ENDPOINT << "Unable to process frame data. Error: "
1876 << detailed_error_;
1877 return false;
1878 }
fkastenholza3660102019-08-28 05:19:24 -07001879 current_received_frame_type_ = 0;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001880 } else {
1881 if (!ProcessFrameData(&reader, *header)) {
1882 DCHECK_NE(QUIC_NO_ERROR, error_); // ProcessFrameData sets the error.
1883 DCHECK_NE("", detailed_error_);
1884 QUIC_DLOG(WARNING) << ENDPOINT << "Unable to process frame data. Error: "
1885 << detailed_error_;
1886 return false;
1887 }
1888 }
1889
1890 visitor_->OnPacketComplete();
1891 return true;
1892}
1893
1894bool QuicFramer::ProcessDataPacket(QuicDataReader* encrypted_reader,
1895 QuicPacketHeader* header,
1896 const QuicEncryptedPacket& packet,
1897 char* decrypted_buffer,
1898 size_t buffer_length) {
1899 if (!ProcessUnauthenticatedHeader(encrypted_reader, header)) {
1900 DCHECK_NE("", detailed_error_);
1901 QUIC_DVLOG(1)
1902 << ENDPOINT
1903 << "Unable to process packet header. Stopping parsing. Error: "
1904 << detailed_error_;
1905 RecordDroppedPacketReason(DroppedPacketReason::INVALID_PACKET_NUMBER);
1906 return false;
1907 }
1908
dmcardlecf0bfcf2019-12-13 08:08:21 -08001909 quiche::QuicheStringPiece encrypted =
1910 encrypted_reader->ReadRemainingPayload();
1911 quiche::QuicheStringPiece associated_data =
1912 GetAssociatedDataFromEncryptedPacket(
1913 version_.transport_version, packet,
1914 GetIncludedDestinationConnectionIdLength(*header),
1915 GetIncludedSourceConnectionIdLength(*header), header->version_flag,
1916 header->nonce != nullptr, header->packet_number_length,
1917 header->retry_token_length_length, header->retry_token.length(),
1918 header->length_length);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001919
1920 size_t decrypted_length = 0;
QUICHE team10b22a12019-03-21 15:31:42 -07001921 EncryptionLevel decrypted_level;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001922 if (!DecryptPayload(encrypted, associated_data, *header, decrypted_buffer,
QUICHE team10b22a12019-03-21 15:31:42 -07001923 buffer_length, &decrypted_length, &decrypted_level)) {
wub13d75452019-11-05 07:24:56 -08001924 const EncryptionLevel decryption_level = decrypter_level_;
1925 // This version uses trial decryption so we always report to our visitor
1926 // that we are not certain we have the correct decryption key.
1927 const bool has_decryption_key = false;
1928 visitor_->OnUndecryptablePacket(
1929 QuicEncryptedPacket(encrypted_reader->FullPayload()), decryption_level,
1930 has_decryption_key);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001931 RecordDroppedPacketReason(DroppedPacketReason::DECRYPTION_FAILURE);
dschinazi163bda22020-04-01 13:34:43 -07001932 set_detailed_error(quiche::QuicheStrCat(
1933 "Unable to decrypt ", EncryptionLevelToString(decryption_level),
1934 " payload."));
QUICHE teama6ef0a62019-03-07 20:34:33 -05001935 return RaiseError(QUIC_DECRYPTION_FAILURE);
1936 }
1937
1938 QuicDataReader reader(decrypted_buffer, decrypted_length);
1939
1940 // Update the largest packet number after we have decrypted the packet
1941 // so we are confident is not attacker controlled.
QUICHE team10b22a12019-03-21 15:31:42 -07001942 if (supports_multiple_packet_number_spaces_) {
1943 largest_decrypted_packet_numbers_[QuicUtils::GetPacketNumberSpace(
1944 decrypted_level)]
1945 .UpdateMax(header->packet_number);
1946 } else {
1947 largest_packet_number_.UpdateMax(header->packet_number);
1948 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001949
1950 if (!visitor_->OnPacketHeader(*header)) {
1951 // The visitor suppresses further processing of the packet.
1952 return true;
1953 }
1954
dschinazie8d7fa72019-04-05 14:44:40 -07001955 if (packet.length() > kMaxIncomingPacketSize) {
1956 set_detailed_error("Packet too large.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05001957 return RaiseError(QUIC_PACKET_TOO_LARGE);
1958 }
1959
1960 // Handle the payload.
1961 if (!ProcessFrameData(&reader, *header)) {
1962 DCHECK_NE(QUIC_NO_ERROR, error_); // ProcessFrameData sets the error.
1963 DCHECK_NE("", detailed_error_);
1964 QUIC_DLOG(WARNING) << ENDPOINT << "Unable to process frame data. Error: "
1965 << detailed_error_;
1966 return false;
1967 }
1968
1969 visitor_->OnPacketComplete();
1970 return true;
1971}
1972
1973bool QuicFramer::ProcessPublicResetPacket(QuicDataReader* reader,
1974 const QuicPacketHeader& header) {
QUICHE team2252b702019-05-14 23:55:14 -04001975 QuicPublicResetPacket packet(
1976 GetServerConnectionIdAsRecipient(header, perspective_));
QUICHE teama6ef0a62019-03-07 20:34:33 -05001977
1978 std::unique_ptr<CryptoHandshakeMessage> reset(
1979 CryptoFramer::ParseMessage(reader->ReadRemainingPayload()));
wub07a2b072019-10-24 11:23:20 -07001980 if (!reset) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001981 set_detailed_error("Unable to read reset message.");
1982 RecordDroppedPacketReason(DroppedPacketReason::INVALID_PUBLIC_RESET_PACKET);
1983 return RaiseError(QUIC_INVALID_PUBLIC_RST_PACKET);
1984 }
1985 if (reset->tag() != kPRST) {
1986 set_detailed_error("Incorrect message tag.");
1987 RecordDroppedPacketReason(DroppedPacketReason::INVALID_PUBLIC_RESET_PACKET);
1988 return RaiseError(QUIC_INVALID_PUBLIC_RST_PACKET);
1989 }
1990
1991 if (reset->GetUint64(kRNON, &packet.nonce_proof) != QUIC_NO_ERROR) {
1992 set_detailed_error("Unable to read nonce proof.");
1993 RecordDroppedPacketReason(DroppedPacketReason::INVALID_PUBLIC_RESET_PACKET);
1994 return RaiseError(QUIC_INVALID_PUBLIC_RST_PACKET);
1995 }
1996 // TODO(satyamshekhar): validate nonce to protect against DoS.
1997
dmcardlecf0bfcf2019-12-13 08:08:21 -08001998 quiche::QuicheStringPiece address;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001999 if (reset->GetStringPiece(kCADR, &address)) {
2000 QuicSocketAddressCoder address_coder;
2001 if (address_coder.Decode(address.data(), address.length())) {
2002 packet.client_address =
2003 QuicSocketAddress(address_coder.ip(), address_coder.port());
2004 }
2005 }
2006
dmcardlecf0bfcf2019-12-13 08:08:21 -08002007 quiche::QuicheStringPiece endpoint_id;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002008 if (perspective_ == Perspective::IS_CLIENT &&
2009 reset->GetStringPiece(kEPID, &endpoint_id)) {
vasilvvc48c8712019-03-11 13:38:16 -07002010 packet.endpoint_id = std::string(endpoint_id);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002011 packet.endpoint_id += '\0';
2012 }
2013
2014 visitor_->OnPublicResetPacket(packet);
2015 return true;
2016}
2017
2018bool QuicFramer::IsIetfStatelessResetPacket(
2019 const QuicPacketHeader& header) const {
2020 QUIC_BUG_IF(header.has_possible_stateless_reset_token &&
2021 perspective_ != Perspective::IS_CLIENT)
2022 << "has_possible_stateless_reset_token can only be true at client side.";
2023 return header.form == IETF_QUIC_SHORT_HEADER_PACKET &&
2024 header.has_possible_stateless_reset_token &&
2025 visitor_->IsValidStatelessResetToken(
2026 header.possible_stateless_reset_token);
2027}
2028
2029bool QuicFramer::HasEncrypterOfEncryptionLevel(EncryptionLevel level) const {
2030 return encrypter_[level] != nullptr;
2031}
2032
fayang750b54f2020-06-18 06:26:54 -07002033bool QuicFramer::HasDecrypterOfEncryptionLevel(EncryptionLevel level) const {
2034 return decrypter_[level] != nullptr;
2035}
2036
QUICHE teama6ef0a62019-03-07 20:34:33 -05002037bool QuicFramer::AppendPacketHeader(const QuicPacketHeader& header,
2038 QuicDataWriter* writer,
2039 size_t* length_field_offset) {
fayangd4291e42019-05-30 10:31:21 -07002040 if (VersionHasIetfInvariantHeader(transport_version())) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002041 return AppendIetfPacketHeader(header, writer, length_field_offset);
2042 }
2043 QUIC_DVLOG(1) << ENDPOINT << "Appending header: " << header;
2044 uint8_t public_flags = 0;
2045 if (header.reset_flag) {
2046 public_flags |= PACKET_PUBLIC_FLAGS_RST;
2047 }
2048 if (header.version_flag) {
2049 public_flags |= PACKET_PUBLIC_FLAGS_VERSION;
2050 }
2051
2052 public_flags |= GetPacketNumberFlags(header.packet_number_length)
2053 << kPublicHeaderSequenceNumberShift;
2054
2055 if (header.nonce != nullptr) {
2056 DCHECK_EQ(Perspective::IS_SERVER, perspective_);
2057 public_flags |= PACKET_PUBLIC_FLAGS_NONCE;
2058 }
QUICHE team2252b702019-05-14 23:55:14 -04002059
dschinazi7b9278c2019-05-20 07:36:21 -07002060 QuicConnectionId server_connection_id =
QUICHE team2252b702019-05-14 23:55:14 -04002061 GetServerConnectionIdAsSender(header, perspective_);
dschinazi7b9278c2019-05-20 07:36:21 -07002062 QuicConnectionIdIncluded server_connection_id_included =
QUICHE team2252b702019-05-14 23:55:14 -04002063 GetServerConnectionIdIncludedAsSender(header, perspective_);
2064 DCHECK_EQ(CONNECTION_ID_ABSENT,
dschinazic075ffa2019-06-27 16:17:37 -07002065 GetClientConnectionIdIncludedAsSender(header, perspective_))
2066 << ENDPOINT << ParsedQuicVersionToString(version_)
2067 << " invalid header: " << header;
QUICHE team2252b702019-05-14 23:55:14 -04002068
dschinazi7b9278c2019-05-20 07:36:21 -07002069 switch (server_connection_id_included) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002070 case CONNECTION_ID_ABSENT:
2071 if (!writer->WriteUInt8(public_flags |
2072 PACKET_PUBLIC_FLAGS_0BYTE_CONNECTION_ID)) {
2073 return false;
2074 }
2075 break;
2076 case CONNECTION_ID_PRESENT:
2077 QUIC_BUG_IF(!QuicUtils::IsConnectionIdValidForVersion(
dschinazi7b9278c2019-05-20 07:36:21 -07002078 server_connection_id, transport_version()))
QUICHE teama6ef0a62019-03-07 20:34:33 -05002079 << "AppendPacketHeader: attempted to use connection ID "
dschinazi7b9278c2019-05-20 07:36:21 -07002080 << server_connection_id << " which is invalid with version "
QUICHE teama6ef0a62019-03-07 20:34:33 -05002081 << QuicVersionToString(transport_version());
2082
2083 public_flags |= PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID;
2084 if (perspective_ == Perspective::IS_CLIENT) {
2085 public_flags |= PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID_OLD;
2086 }
2087 if (!writer->WriteUInt8(public_flags) ||
dschinazi7b9278c2019-05-20 07:36:21 -07002088 !writer->WriteConnectionId(server_connection_id)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002089 return false;
2090 }
2091 break;
2092 }
dschinazi7b9278c2019-05-20 07:36:21 -07002093 last_serialized_server_connection_id_ = server_connection_id;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002094
2095 if (header.version_flag) {
2096 DCHECK_EQ(Perspective::IS_CLIENT, perspective_);
2097 QuicVersionLabel version_label = CreateQuicVersionLabel(version_);
nharpereaab5ad2019-05-31 12:23:25 -07002098 if (!writer->WriteUInt32(version_label)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002099 return false;
2100 }
2101
2102 QUIC_DVLOG(1) << ENDPOINT << "label = '"
2103 << QuicVersionLabelToString(version_label) << "'";
2104 }
2105
2106 if (header.nonce != nullptr &&
2107 !writer->WriteBytes(header.nonce, kDiversificationNonceSize)) {
2108 return false;
2109 }
2110
2111 if (!AppendPacketNumber(header.packet_number_length, header.packet_number,
2112 writer)) {
2113 return false;
2114 }
2115
2116 return true;
2117}
2118
2119bool QuicFramer::AppendIetfHeaderTypeByte(const QuicPacketHeader& header,
2120 QuicDataWriter* writer) {
2121 uint8_t type = 0;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002122 if (header.version_flag) {
2123 type = static_cast<uint8_t>(
fayang36825da2019-08-21 14:01:27 -07002124 FLAGS_LONG_HEADER | FLAGS_FIXED_BIT |
2125 LongHeaderTypeToOnWireValue(header.long_packet_type) |
2126 PacketNumberLengthToOnWireValue(header.packet_number_length));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002127 } else {
fayang36825da2019-08-21 14:01:27 -07002128 type = static_cast<uint8_t>(
2129 FLAGS_FIXED_BIT |
2130 PacketNumberLengthToOnWireValue(header.packet_number_length));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002131 }
2132 return writer->WriteUInt8(type);
2133}
2134
2135bool QuicFramer::AppendIetfPacketHeader(const QuicPacketHeader& header,
2136 QuicDataWriter* writer,
2137 size_t* length_field_offset) {
2138 QUIC_DVLOG(1) << ENDPOINT << "Appending IETF header: " << header;
QUICHE team2252b702019-05-14 23:55:14 -04002139 QuicConnectionId server_connection_id =
2140 GetServerConnectionIdAsSender(header, perspective_);
2141 QUIC_BUG_IF(!QuicUtils::IsConnectionIdValidForVersion(server_connection_id,
2142 transport_version()))
QUICHE teama6ef0a62019-03-07 20:34:33 -05002143 << "AppendIetfPacketHeader: attempted to use connection ID "
QUICHE team2252b702019-05-14 23:55:14 -04002144 << server_connection_id << " which is invalid with version "
QUICHE teama6ef0a62019-03-07 20:34:33 -05002145 << QuicVersionToString(transport_version());
2146 if (!AppendIetfHeaderTypeByte(header, writer)) {
2147 return false;
2148 }
2149
2150 if (header.version_flag) {
dschinaziecad9642019-10-01 10:44:17 -07002151 DCHECK_NE(VERSION_NEGOTIATION, header.long_packet_type)
2152 << "QuicFramer::AppendIetfPacketHeader does not support sending "
2153 "version negotiation packets, use "
2154 "QuicFramer::BuildVersionNegotiationPacket instead "
2155 << header;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002156 // Append version for long header.
2157 QuicVersionLabel version_label = CreateQuicVersionLabel(version_);
nharpereaab5ad2019-05-31 12:23:25 -07002158 if (!writer->WriteUInt32(version_label)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002159 return false;
2160 }
2161 }
2162
2163 // Append connection ID.
dschinazi1f485a12019-05-13 11:57:01 -07002164 if (!AppendIetfConnectionIds(
dschinazi48ac9192019-07-31 00:07:26 -07002165 header.version_flag, version_.HasLengthPrefixedConnectionIds(),
dschinazi1f485a12019-05-13 11:57:01 -07002166 header.destination_connection_id_included != CONNECTION_ID_ABSENT
2167 ? header.destination_connection_id
2168 : EmptyQuicConnectionId(),
2169 header.source_connection_id_included != CONNECTION_ID_ABSENT
2170 ? header.source_connection_id
2171 : EmptyQuicConnectionId(),
2172 writer)) {
2173 return false;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002174 }
dschinazi1f485a12019-05-13 11:57:01 -07002175
dschinazi7b9278c2019-05-20 07:36:21 -07002176 last_serialized_server_connection_id_ = server_connection_id;
dschinazi346b7ce2019-06-05 01:38:18 -07002177 if (version_.SupportsClientConnectionIds()) {
2178 last_serialized_client_connection_id_ =
2179 GetClientConnectionIdAsSender(header, perspective_);
2180 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002181
dschinaziecad9642019-10-01 10:44:17 -07002182 // TODO(b/141924462) Remove this QUIC_BUG once we do support sending RETRY.
2183 QUIC_BUG_IF(header.version_flag && header.long_packet_type == RETRY)
2184 << "Sending IETF RETRY packets is not currently supported " << header;
2185
QUICHE teama6ef0a62019-03-07 20:34:33 -05002186 if (QuicVersionHasLongHeaderLengths(transport_version()) &&
2187 header.version_flag) {
2188 if (header.long_packet_type == INITIAL) {
dschinazic075ffa2019-06-27 16:17:37 -07002189 DCHECK_NE(VARIABLE_LENGTH_INTEGER_LENGTH_0,
2190 header.retry_token_length_length)
2191 << ENDPOINT << ParsedQuicVersionToString(version_)
2192 << " bad retry token length length in header: " << header;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002193 // Write retry token length.
2194 if (!writer->WriteVarInt62(header.retry_token.length(),
2195 header.retry_token_length_length)) {
2196 return false;
2197 }
2198 // Write retry token.
2199 if (!header.retry_token.empty() &&
2200 !writer->WriteStringPiece(header.retry_token)) {
2201 return false;
2202 }
2203 }
2204 if (length_field_offset != nullptr) {
2205 *length_field_offset = writer->length();
2206 }
2207 // Add fake length to reserve two bytes to add length in later.
2208 writer->WriteVarInt62(256);
2209 } else if (length_field_offset != nullptr) {
2210 *length_field_offset = 0;
2211 }
2212
2213 // Append packet number.
2214 if (!AppendPacketNumber(header.packet_number_length, header.packet_number,
2215 writer)) {
2216 return false;
2217 }
nharper55fa6132019-05-07 19:37:21 -07002218 last_written_packet_number_length_ = header.packet_number_length;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002219
2220 if (!header.version_flag) {
2221 return true;
2222 }
2223
2224 if (header.nonce != nullptr) {
2225 DCHECK(header.version_flag);
2226 DCHECK_EQ(ZERO_RTT_PROTECTED, header.long_packet_type);
2227 DCHECK_EQ(Perspective::IS_SERVER, perspective_);
2228 if (!writer->WriteBytes(header.nonce, kDiversificationNonceSize)) {
2229 return false;
2230 }
2231 }
2232
2233 return true;
2234}
2235
2236const QuicTime::Delta QuicFramer::CalculateTimestampFromWire(
2237 uint32_t time_delta_us) {
2238 // The new time_delta might have wrapped to the next epoch, or it
2239 // might have reverse wrapped to the previous epoch, or it might
2240 // remain in the same epoch. Select the time closest to the previous
2241 // time.
2242 //
2243 // epoch_delta is the delta between epochs. A delta is 4 bytes of
2244 // microseconds.
2245 const uint64_t epoch_delta = UINT64_C(1) << 32;
2246 uint64_t epoch = last_timestamp_.ToMicroseconds() & ~(epoch_delta - 1);
2247 // Wrapping is safe here because a wrapped value will not be ClosestTo below.
2248 uint64_t prev_epoch = epoch - epoch_delta;
2249 uint64_t next_epoch = epoch + epoch_delta;
2250
2251 uint64_t time = ClosestTo(
2252 last_timestamp_.ToMicroseconds(), epoch + time_delta_us,
2253 ClosestTo(last_timestamp_.ToMicroseconds(), prev_epoch + time_delta_us,
2254 next_epoch + time_delta_us));
2255
2256 return QuicTime::Delta::FromMicroseconds(time);
2257}
2258
2259uint64_t QuicFramer::CalculatePacketNumberFromWire(
2260 QuicPacketNumberLength packet_number_length,
2261 QuicPacketNumber base_packet_number,
2262 uint64_t packet_number) const {
2263 // The new packet number might have wrapped to the next epoch, or
2264 // it might have reverse wrapped to the previous epoch, or it might
2265 // remain in the same epoch. Select the packet number closest to the
2266 // next expected packet number, the previous packet number plus 1.
2267
2268 // epoch_delta is the delta between epochs the packet number was serialized
2269 // with, so the correct value is likely the same epoch as the last sequence
2270 // number or an adjacent epoch.
2271 if (!base_packet_number.IsInitialized()) {
2272 return packet_number;
2273 }
2274 const uint64_t epoch_delta = UINT64_C(1) << (8 * packet_number_length);
2275 uint64_t next_packet_number = base_packet_number.ToUint64() + 1;
2276 uint64_t epoch = base_packet_number.ToUint64() & ~(epoch_delta - 1);
2277 uint64_t prev_epoch = epoch - epoch_delta;
2278 uint64_t next_epoch = epoch + epoch_delta;
2279
2280 return ClosestTo(next_packet_number, epoch + packet_number,
2281 ClosestTo(next_packet_number, prev_epoch + packet_number,
2282 next_epoch + packet_number));
2283}
2284
2285bool QuicFramer::ProcessPublicHeader(QuicDataReader* reader,
2286 bool packet_has_ietf_packet_header,
2287 QuicPacketHeader* header) {
2288 if (packet_has_ietf_packet_header) {
2289 return ProcessIetfPacketHeader(reader, header);
2290 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002291 uint8_t public_flags;
2292 if (!reader->ReadBytes(&public_flags, 1)) {
2293 set_detailed_error("Unable to read public flags.");
2294 return false;
2295 }
2296
2297 header->reset_flag = (public_flags & PACKET_PUBLIC_FLAGS_RST) != 0;
2298 header->version_flag = (public_flags & PACKET_PUBLIC_FLAGS_VERSION) != 0;
2299
2300 if (validate_flags_ && !header->version_flag &&
2301 public_flags > PACKET_PUBLIC_FLAGS_MAX) {
2302 set_detailed_error("Illegal public flags value.");
2303 return false;
2304 }
2305
2306 if (header->reset_flag && header->version_flag) {
2307 set_detailed_error("Got version flag in reset packet");
2308 return false;
2309 }
2310
QUICHE team2252b702019-05-14 23:55:14 -04002311 QuicConnectionId* header_connection_id = &header->destination_connection_id;
2312 QuicConnectionIdIncluded* header_connection_id_included =
2313 &header->destination_connection_id_included;
dschinazi5e1a7b22019-07-31 12:23:21 -07002314 if (perspective_ == Perspective::IS_CLIENT) {
QUICHE team2252b702019-05-14 23:55:14 -04002315 header_connection_id = &header->source_connection_id;
2316 header_connection_id_included = &header->source_connection_id_included;
2317 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002318 switch (public_flags & PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID) {
2319 case PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID:
QUICHE team2252b702019-05-14 23:55:14 -04002320 if (!reader->ReadConnectionId(header_connection_id,
QUICHE teama6ef0a62019-03-07 20:34:33 -05002321 kQuicDefaultConnectionIdLength)) {
2322 set_detailed_error("Unable to read ConnectionId.");
2323 return false;
2324 }
QUICHE team2252b702019-05-14 23:55:14 -04002325 *header_connection_id_included = CONNECTION_ID_PRESENT;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002326 break;
2327 case PACKET_PUBLIC_FLAGS_0BYTE_CONNECTION_ID:
QUICHE team2252b702019-05-14 23:55:14 -04002328 *header_connection_id_included = CONNECTION_ID_ABSENT;
dschinazi7b9278c2019-05-20 07:36:21 -07002329 *header_connection_id = last_serialized_server_connection_id_;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002330 break;
2331 }
2332
2333 header->packet_number_length = ReadSequenceNumberLength(
2334 public_flags >> kPublicHeaderSequenceNumberShift);
2335
2336 // Read the version only if the packet is from the client.
2337 // version flag from the server means version negotiation packet.
2338 if (header->version_flag && perspective_ == Perspective::IS_SERVER) {
2339 QuicVersionLabel version_label;
fayang40315542019-05-09 09:19:09 -07002340 if (!ProcessVersionLabel(reader, &version_label)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002341 set_detailed_error("Unable to read protocol version.");
2342 return false;
2343 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002344 // If the version from the new packet is the same as the version of this
2345 // framer, then the public flags should be set to something we understand.
2346 // If not, this raises an error.
QUICHE teama6ef0a62019-03-07 20:34:33 -05002347 ParsedQuicVersion version = ParseQuicVersionLabel(version_label);
2348 if (version == version_ && public_flags > PACKET_PUBLIC_FLAGS_MAX) {
2349 set_detailed_error("Illegal public flags value.");
2350 return false;
2351 }
2352 header->version = version;
2353 }
2354
2355 // A nonce should only be present in packets from the server to the client,
2356 // which are neither version negotiation nor public reset packets.
2357 if (public_flags & PACKET_PUBLIC_FLAGS_NONCE &&
2358 !(public_flags & PACKET_PUBLIC_FLAGS_VERSION) &&
2359 !(public_flags & PACKET_PUBLIC_FLAGS_RST) &&
2360 // The nonce flag from a client is ignored and is assumed to be an older
2361 // client indicating an eight-byte connection ID.
2362 perspective_ == Perspective::IS_CLIENT) {
2363 if (!reader->ReadBytes(reinterpret_cast<uint8_t*>(last_nonce_.data()),
2364 last_nonce_.size())) {
2365 set_detailed_error("Unable to read nonce.");
2366 return false;
2367 }
2368 header->nonce = &last_nonce_;
2369 } else {
2370 header->nonce = nullptr;
2371 }
2372
2373 return true;
2374}
2375
2376// static
2377QuicPacketNumberLength QuicFramer::GetMinPacketNumberLength(
QUICHE teama6ef0a62019-03-07 20:34:33 -05002378 QuicPacketNumber packet_number) {
2379 DCHECK(packet_number.IsInitialized());
2380 if (packet_number < QuicPacketNumber(1 << (PACKET_1BYTE_PACKET_NUMBER * 8))) {
2381 return PACKET_1BYTE_PACKET_NUMBER;
2382 } else if (packet_number <
2383 QuicPacketNumber(1 << (PACKET_2BYTE_PACKET_NUMBER * 8))) {
2384 return PACKET_2BYTE_PACKET_NUMBER;
2385 } else if (packet_number <
2386 QuicPacketNumber(UINT64_C(1)
2387 << (PACKET_4BYTE_PACKET_NUMBER * 8))) {
2388 return PACKET_4BYTE_PACKET_NUMBER;
2389 } else {
2390 return PACKET_6BYTE_PACKET_NUMBER;
2391 }
2392}
2393
2394// static
2395uint8_t QuicFramer::GetPacketNumberFlags(
2396 QuicPacketNumberLength packet_number_length) {
2397 switch (packet_number_length) {
2398 case PACKET_1BYTE_PACKET_NUMBER:
2399 return PACKET_FLAGS_1BYTE_PACKET;
2400 case PACKET_2BYTE_PACKET_NUMBER:
2401 return PACKET_FLAGS_2BYTE_PACKET;
2402 case PACKET_4BYTE_PACKET_NUMBER:
2403 return PACKET_FLAGS_4BYTE_PACKET;
2404 case PACKET_6BYTE_PACKET_NUMBER:
2405 case PACKET_8BYTE_PACKET_NUMBER:
2406 return PACKET_FLAGS_8BYTE_PACKET;
2407 default:
2408 QUIC_BUG << "Unreachable case statement.";
2409 return PACKET_FLAGS_8BYTE_PACKET;
2410 }
2411}
2412
2413// static
2414QuicFramer::AckFrameInfo QuicFramer::GetAckFrameInfo(
2415 const QuicAckFrame& frame) {
2416 AckFrameInfo new_ack_info;
2417 if (frame.packets.Empty()) {
2418 return new_ack_info;
2419 }
2420 // The first block is the last interval. It isn't encoded with the gap-length
2421 // encoding, so skip it.
2422 new_ack_info.first_block_length = frame.packets.LastIntervalLength();
2423 auto itr = frame.packets.rbegin();
2424 QuicPacketNumber previous_start = itr->min();
wub13d75452019-11-05 07:24:56 -08002425 new_ack_info.max_block_length = itr->Length();
QUICHE teama6ef0a62019-03-07 20:34:33 -05002426 ++itr;
2427
2428 // Don't do any more work after getting information for 256 ACK blocks; any
2429 // more can't be encoded anyway.
2430 for (; itr != frame.packets.rend() &&
2431 new_ack_info.num_ack_blocks < std::numeric_limits<uint8_t>::max();
2432 previous_start = itr->min(), ++itr) {
2433 const auto& interval = *itr;
2434 const QuicPacketCount total_gap = previous_start - interval.max();
2435 new_ack_info.num_ack_blocks +=
2436 (total_gap + std::numeric_limits<uint8_t>::max() - 1) /
2437 std::numeric_limits<uint8_t>::max();
wub13d75452019-11-05 07:24:56 -08002438 new_ack_info.max_block_length =
2439 std::max(new_ack_info.max_block_length, interval.Length());
QUICHE teama6ef0a62019-03-07 20:34:33 -05002440 }
2441 return new_ack_info;
2442}
2443
2444bool QuicFramer::ProcessUnauthenticatedHeader(QuicDataReader* encrypted_reader,
2445 QuicPacketHeader* header) {
QUICHE team10b22a12019-03-21 15:31:42 -07002446 QuicPacketNumber base_packet_number;
2447 if (supports_multiple_packet_number_spaces_) {
nharper55fa6132019-05-07 19:37:21 -07002448 PacketNumberSpace pn_space = GetPacketNumberSpace(*header);
2449 if (pn_space == NUM_PACKET_NUMBER_SPACES) {
2450 set_detailed_error("Unable to determine packet number space.");
2451 return RaiseError(QUIC_INVALID_PACKET_HEADER);
2452 }
2453 base_packet_number = largest_decrypted_packet_numbers_[pn_space];
QUICHE team10b22a12019-03-21 15:31:42 -07002454 } else {
2455 base_packet_number = largest_packet_number_;
2456 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002457 uint64_t full_packet_number;
2458 if (!ProcessAndCalculatePacketNumber(
2459 encrypted_reader, header->packet_number_length, base_packet_number,
2460 &full_packet_number)) {
2461 set_detailed_error("Unable to read packet number.");
2462 return RaiseError(QUIC_INVALID_PACKET_HEADER);
2463 }
2464
dschinazi40f0b3d2020-02-19 17:54:05 -08002465 if (!IsValidFullPacketNumber(full_packet_number, version())) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002466 set_detailed_error("packet numbers cannot be 0.");
2467 return RaiseError(QUIC_INVALID_PACKET_HEADER);
2468 }
2469 header->packet_number = QuicPacketNumber(full_packet_number);
2470
2471 if (!visitor_->OnUnauthenticatedHeader(*header)) {
2472 set_detailed_error(
2473 "Visitor asked to stop processing of unauthenticated header.");
2474 return false;
2475 }
nharper3f283562019-05-02 16:37:12 -07002476 // The function we are in is called because the framer believes that it is
2477 // processing a packet that uses the non-IETF (i.e. Google QUIC) packet header
2478 // type. Usually, the framer makes that decision based on the framer's
2479 // version, but when the framer is used with Perspective::IS_SERVER, then
2480 // before version negotiation is complete (specifically, before
2481 // InferPacketHeaderTypeFromVersion is called), this decision is made based on
2482 // the type byte of the packet.
2483 //
2484 // If the framer's version KnowsWhichDecrypterToUse, then that version expects
2485 // to use the IETF packet header type. If that's the case and we're in this
2486 // function, then the packet received is invalid: the framer was expecting an
2487 // IETF packet header and didn't get one.
2488 if (version().KnowsWhichDecrypterToUse()) {
nharpera745e392019-04-19 12:05:15 -07002489 set_detailed_error("Invalid public header type for expected version.");
2490 return RaiseError(QUIC_INVALID_PACKET_HEADER);
2491 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002492 return true;
2493}
2494
2495bool QuicFramer::ProcessIetfHeaderTypeByte(QuicDataReader* reader,
2496 QuicPacketHeader* header) {
2497 uint8_t type;
2498 if (!reader->ReadBytes(&type, 1)) {
dschinazi48ac9192019-07-31 00:07:26 -07002499 set_detailed_error("Unable to read first byte.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05002500 return false;
2501 }
dschinazi244f6dc2019-05-06 15:45:16 -07002502 header->type_byte = type;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002503 // Determine whether this is a long or short header.
fayangccbab732019-05-13 10:11:25 -07002504 header->form = GetIetfPacketHeaderFormat(type);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002505 if (header->form == IETF_QUIC_LONG_HEADER_PACKET) {
2506 // Version is always present in long headers.
2507 header->version_flag = true;
dschinazi346b7ce2019-06-05 01:38:18 -07002508 // In versions that do not support client connection IDs, we mark the
2509 // corresponding connection ID as absent.
QUICHE teama6ef0a62019-03-07 20:34:33 -05002510 header->destination_connection_id_included =
dschinazi346b7ce2019-06-05 01:38:18 -07002511 (perspective_ == Perspective::IS_SERVER ||
2512 version_.SupportsClientConnectionIds())
2513 ? CONNECTION_ID_PRESENT
2514 : CONNECTION_ID_ABSENT;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002515 header->source_connection_id_included =
dschinazi346b7ce2019-06-05 01:38:18 -07002516 (perspective_ == Perspective::IS_CLIENT ||
2517 version_.SupportsClientConnectionIds())
2518 ? CONNECTION_ID_PRESENT
2519 : CONNECTION_ID_ABSENT;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002520 // Read version tag.
2521 QuicVersionLabel version_label;
fayang40315542019-05-09 09:19:09 -07002522 if (!ProcessVersionLabel(reader, &version_label)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002523 set_detailed_error("Unable to read protocol version.");
2524 return false;
2525 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002526 if (!version_label) {
2527 // Version label is 0 indicating this is a version negotiation packet.
2528 header->long_packet_type = VERSION_NEGOTIATION;
2529 } else {
2530 header->version = ParseQuicVersionLabel(version_label);
dschinazi5c1d7d82020-07-29 16:42:50 -07002531 if (header->version.IsKnown()) {
fayang36825da2019-08-21 14:01:27 -07002532 if (!(type & FLAGS_FIXED_BIT)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002533 set_detailed_error("Fixed bit is 0 in long header.");
2534 return false;
2535 }
fayang36825da2019-08-21 14:01:27 -07002536 if (!GetLongHeaderType(type, &header->long_packet_type)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002537 set_detailed_error("Illegal long header type value.");
2538 return false;
2539 }
dschinazi244f6dc2019-05-06 15:45:16 -07002540 if (header->long_packet_type == RETRY) {
2541 if (!version().SupportsRetry()) {
2542 set_detailed_error("RETRY not supported in this version.");
2543 return false;
2544 }
2545 if (perspective_ == Perspective::IS_SERVER) {
2546 set_detailed_error("Client-initiated RETRY is invalid.");
2547 return false;
2548 }
nharper55fa6132019-05-07 19:37:21 -07002549 } else if (!header->version.HasHeaderProtection()) {
fayang36825da2019-08-21 14:01:27 -07002550 header->packet_number_length = GetLongHeaderPacketNumberLength(type);
nharper2ceb97c2019-04-19 11:38:59 -07002551 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002552 }
2553 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002554
2555 QUIC_DVLOG(1) << ENDPOINT << "Received IETF long header: "
2556 << QuicUtils::QuicLongHeaderTypetoString(
2557 header->long_packet_type);
2558 return true;
2559 }
2560
2561 QUIC_DVLOG(1) << ENDPOINT << "Received IETF short header";
2562 // Version is not present in short headers.
2563 header->version_flag = false;
dschinazi346b7ce2019-06-05 01:38:18 -07002564 // In versions that do not support client connection IDs, the client will not
2565 // receive destination connection IDs.
QUICHE teama6ef0a62019-03-07 20:34:33 -05002566 header->destination_connection_id_included =
dschinazi346b7ce2019-06-05 01:38:18 -07002567 (perspective_ == Perspective::IS_SERVER ||
2568 version_.SupportsClientConnectionIds())
2569 ? CONNECTION_ID_PRESENT
2570 : CONNECTION_ID_ABSENT;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002571 header->source_connection_id_included = CONNECTION_ID_ABSENT;
fayang36825da2019-08-21 14:01:27 -07002572 if (!(type & FLAGS_FIXED_BIT)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002573 set_detailed_error("Fixed bit is 0 in short header.");
2574 return false;
2575 }
dschinazidc770fc2020-01-13 15:42:41 -08002576 if (!version_.HasHeaderProtection()) {
fayang36825da2019-08-21 14:01:27 -07002577 header->packet_number_length = GetShortHeaderPacketNumberLength(type);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002578 }
2579 QUIC_DVLOG(1) << "packet_number_length = " << header->packet_number_length;
2580 return true;
2581}
2582
fayang40315542019-05-09 09:19:09 -07002583// static
2584bool QuicFramer::ProcessVersionLabel(QuicDataReader* reader,
2585 QuicVersionLabel* version_label) {
nharpereaab5ad2019-05-31 12:23:25 -07002586 if (!reader->ReadUInt32(version_label)) {
fayang40315542019-05-09 09:19:09 -07002587 return false;
2588 }
fayang40315542019-05-09 09:19:09 -07002589 return true;
2590}
2591
2592// static
fayangccbab732019-05-13 10:11:25 -07002593bool QuicFramer::ProcessAndValidateIetfConnectionIdLength(
2594 QuicDataReader* reader,
fayang40315542019-05-09 09:19:09 -07002595 ParsedQuicVersion version,
dschinazi334f0232019-05-29 16:08:53 -07002596 Perspective perspective,
dschinazi8ff74822019-05-28 16:37:20 -07002597 bool should_update_expected_server_connection_id_length,
2598 uint8_t* expected_server_connection_id_length,
fayang40315542019-05-09 09:19:09 -07002599 uint8_t* destination_connection_id_length,
fayangccbab732019-05-13 10:11:25 -07002600 uint8_t* source_connection_id_length,
2601 std::string* detailed_error) {
2602 uint8_t connection_id_lengths_byte;
2603 if (!reader->ReadBytes(&connection_id_lengths_byte, 1)) {
2604 *detailed_error = "Unable to read ConnectionId length.";
2605 return false;
2606 }
fayang40315542019-05-09 09:19:09 -07002607 uint8_t dcil =
2608 (connection_id_lengths_byte & kDestinationConnectionIdLengthMask) >> 4;
2609 if (dcil != 0) {
2610 dcil += kConnectionIdLengthAdjustment;
2611 }
fayang40315542019-05-09 09:19:09 -07002612 uint8_t scil = connection_id_lengths_byte & kSourceConnectionIdLengthMask;
2613 if (scil != 0) {
2614 scil += kConnectionIdLengthAdjustment;
2615 }
dschinazi334f0232019-05-29 16:08:53 -07002616 if (should_update_expected_server_connection_id_length) {
2617 uint8_t server_connection_id_length =
2618 perspective == Perspective::IS_SERVER ? dcil : scil;
2619 if (*expected_server_connection_id_length != server_connection_id_length) {
2620 QUIC_DVLOG(1) << "Updating expected_server_connection_id_length: "
2621 << static_cast<int>(*expected_server_connection_id_length)
2622 << " -> " << static_cast<int>(server_connection_id_length);
2623 *expected_server_connection_id_length = server_connection_id_length;
2624 }
2625 }
dschinazi8ff74822019-05-28 16:37:20 -07002626 if (!should_update_expected_server_connection_id_length &&
fayangde8a2222019-05-16 10:52:39 -07002627 (dcil != *destination_connection_id_length ||
fayang40315542019-05-09 09:19:09 -07002628 scil != *source_connection_id_length) &&
dschinazi97da52b2020-01-13 15:44:43 -08002629 version.IsKnown() && !version.AllowsVariableLengthConnectionIds()) {
fayang40315542019-05-09 09:19:09 -07002630 QUIC_DVLOG(1) << "dcil: " << static_cast<uint32_t>(dcil)
2631 << ", scil: " << static_cast<uint32_t>(scil);
fayangccbab732019-05-13 10:11:25 -07002632 *detailed_error = "Invalid ConnectionId length.";
fayang40315542019-05-09 09:19:09 -07002633 return false;
2634 }
2635 *destination_connection_id_length = dcil;
2636 *source_connection_id_length = scil;
2637 return true;
2638}
2639
dschinazib953d022019-08-01 18:05:58 -07002640bool QuicFramer::ValidateReceivedConnectionIds(const QuicPacketHeader& header) {
2641 if (!QuicUtils::IsConnectionIdValidForVersion(
2642 GetServerConnectionIdAsRecipient(header, perspective_),
2643 transport_version())) {
2644 set_detailed_error("Received server connection ID with invalid length.");
2645 return false;
2646 }
2647
2648 if (version_.SupportsClientConnectionIds() &&
2649 !QuicUtils::IsConnectionIdValidForVersion(
2650 GetClientConnectionIdAsRecipient(header, perspective_),
2651 transport_version())) {
2652 set_detailed_error("Received client connection ID with invalid length.");
2653 return false;
2654 }
2655 return true;
2656}
2657
QUICHE teama6ef0a62019-03-07 20:34:33 -05002658bool QuicFramer::ProcessIetfPacketHeader(QuicDataReader* reader,
2659 QuicPacketHeader* header) {
dschinazi48ac9192019-07-31 00:07:26 -07002660 if (version_.HasLengthPrefixedConnectionIds()) {
2661 uint8_t expected_destination_connection_id_length =
2662 perspective_ == Perspective::IS_CLIENT
2663 ? expected_client_connection_id_length_
2664 : expected_server_connection_id_length_;
2665 QuicVersionLabel version_label;
2666 bool has_length_prefix;
2667 std::string detailed_error;
2668 QuicErrorCode parse_result = QuicFramer::ParsePublicHeader(
2669 reader, expected_destination_connection_id_length,
2670 VersionHasIetfInvariantHeader(version_.transport_version),
2671 &header->type_byte, &header->form, &header->version_flag,
2672 &has_length_prefix, &version_label, &header->version,
2673 &header->destination_connection_id, &header->source_connection_id,
2674 &header->long_packet_type, &header->retry_token_length_length,
2675 &header->retry_token, &detailed_error);
2676 if (parse_result != QUIC_NO_ERROR) {
2677 set_detailed_error(detailed_error);
2678 return false;
2679 }
2680 header->destination_connection_id_included = CONNECTION_ID_PRESENT;
2681 header->source_connection_id_included =
2682 header->version_flag ? CONNECTION_ID_PRESENT : CONNECTION_ID_ABSENT;
2683 if (header->source_connection_id_included == CONNECTION_ID_ABSENT) {
2684 DCHECK(header->source_connection_id.IsEmpty());
2685 if (perspective_ == Perspective::IS_CLIENT) {
2686 header->source_connection_id = last_serialized_server_connection_id_;
2687 } else {
2688 header->source_connection_id = last_serialized_client_connection_id_;
2689 }
2690 }
dschinazib953d022019-08-01 18:05:58 -07002691
2692 if (!ValidateReceivedConnectionIds(*header)) {
2693 return false;
2694 }
2695
dschinazi48ac9192019-07-31 00:07:26 -07002696 if (header->version_flag &&
fayang36825da2019-08-21 14:01:27 -07002697 header->long_packet_type != VERSION_NEGOTIATION &&
dschinazi48ac9192019-07-31 00:07:26 -07002698 !(header->type_byte & FLAGS_FIXED_BIT)) {
2699 set_detailed_error("Fixed bit is 0 in long header.");
2700 return false;
2701 }
fayang36825da2019-08-21 14:01:27 -07002702 if (!header->version_flag && !(header->type_byte & FLAGS_FIXED_BIT)) {
dschinazi48ac9192019-07-31 00:07:26 -07002703 set_detailed_error("Fixed bit is 0 in short header.");
2704 return false;
2705 }
2706 if (!header->version_flag) {
fayang36825da2019-08-21 14:01:27 -07002707 if (!version_.HasHeaderProtection()) {
2708 header->packet_number_length =
2709 GetShortHeaderPacketNumberLength(header->type_byte);
dschinazi48ac9192019-07-31 00:07:26 -07002710 }
2711 return true;
2712 }
2713 if (header->long_packet_type == RETRY) {
2714 if (!version().SupportsRetry()) {
2715 set_detailed_error("RETRY not supported in this version.");
2716 return false;
2717 }
2718 if (perspective_ == Perspective::IS_SERVER) {
2719 set_detailed_error("Client-initiated RETRY is invalid.");
2720 return false;
2721 }
2722 return true;
2723 }
dschinazi97da52b2020-01-13 15:44:43 -08002724 if (header->version.IsKnown() && !header->version.HasHeaderProtection()) {
fayang36825da2019-08-21 14:01:27 -07002725 header->packet_number_length =
2726 GetLongHeaderPacketNumberLength(header->type_byte);
dschinazi48ac9192019-07-31 00:07:26 -07002727 }
2728
2729 return true;
2730 }
2731
QUICHE teama6ef0a62019-03-07 20:34:33 -05002732 if (!ProcessIetfHeaderTypeByte(reader, header)) {
2733 return false;
2734 }
2735
2736 uint8_t destination_connection_id_length =
2737 header->destination_connection_id_included == CONNECTION_ID_PRESENT
dschinazi346b7ce2019-06-05 01:38:18 -07002738 ? (perspective_ == Perspective::IS_SERVER
2739 ? expected_server_connection_id_length_
2740 : expected_client_connection_id_length_)
QUICHE teama6ef0a62019-03-07 20:34:33 -05002741 : 0;
2742 uint8_t source_connection_id_length =
2743 header->source_connection_id_included == CONNECTION_ID_PRESENT
dschinazi346b7ce2019-06-05 01:38:18 -07002744 ? (perspective_ == Perspective::IS_CLIENT
2745 ? expected_server_connection_id_length_
2746 : expected_client_connection_id_length_)
QUICHE teama6ef0a62019-03-07 20:34:33 -05002747 : 0;
2748 if (header->form == IETF_QUIC_LONG_HEADER_PACKET) {
fayangccbab732019-05-13 10:11:25 -07002749 if (!ProcessAndValidateIetfConnectionIdLength(
dschinazi334f0232019-05-29 16:08:53 -07002750 reader, header->version, perspective_,
fayang91475c42019-06-19 08:04:26 -07002751 /*should_update_expected_server_connection_id_length=*/false,
dschinazi8ff74822019-05-28 16:37:20 -07002752 &expected_server_connection_id_length_,
2753 &destination_connection_id_length, &source_connection_id_length,
2754 &detailed_error_)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002755 return false;
2756 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002757 }
2758
2759 // Read connection ID.
2760 if (!reader->ReadConnectionId(&header->destination_connection_id,
2761 destination_connection_id_length)) {
dschinazi48ac9192019-07-31 00:07:26 -07002762 set_detailed_error("Unable to read destination connection ID.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05002763 return false;
2764 }
2765
2766 if (!reader->ReadConnectionId(&header->source_connection_id,
2767 source_connection_id_length)) {
dschinazi48ac9192019-07-31 00:07:26 -07002768 set_detailed_error("Unable to read source connection ID.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05002769 return false;
2770 }
2771
dschinazi5e1a7b22019-07-31 12:23:21 -07002772 if (header->source_connection_id_included == CONNECTION_ID_ABSENT) {
2773 if (!header->source_connection_id.IsEmpty()) {
2774 DCHECK(!version_.SupportsClientConnectionIds());
2775 set_detailed_error("Client connection ID not supported in this version.");
2776 return false;
QUICHE team2252b702019-05-14 23:55:14 -04002777 }
dschinazi5e1a7b22019-07-31 12:23:21 -07002778 if (perspective_ == Perspective::IS_CLIENT) {
2779 header->source_connection_id = last_serialized_server_connection_id_;
2780 } else {
2781 header->source_connection_id = last_serialized_client_connection_id_;
QUICHE team2252b702019-05-14 23:55:14 -04002782 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002783 }
2784
dschinazib953d022019-08-01 18:05:58 -07002785 return ValidateReceivedConnectionIds(*header);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002786}
2787
2788bool QuicFramer::ProcessAndCalculatePacketNumber(
2789 QuicDataReader* reader,
2790 QuicPacketNumberLength packet_number_length,
2791 QuicPacketNumber base_packet_number,
2792 uint64_t* packet_number) {
2793 uint64_t wire_packet_number;
2794 if (!reader->ReadBytesToUInt64(packet_number_length, &wire_packet_number)) {
2795 return false;
2796 }
2797
2798 // TODO(ianswett): Explore the usefulness of trying multiple packet numbers
2799 // in case the first guess is incorrect.
2800 *packet_number = CalculatePacketNumberFromWire(
2801 packet_number_length, base_packet_number, wire_packet_number);
2802 return true;
2803}
2804
2805bool QuicFramer::ProcessFrameData(QuicDataReader* reader,
2806 const QuicPacketHeader& header) {
fkastenholz305e1732019-06-18 05:01:22 -07002807 DCHECK(!VersionHasIetfQuicFrames(version_.transport_version))
2808 << "IETF QUIC Framing negotiated but attempting to process frames as "
2809 "non-IETF QUIC.";
QUICHE teama6ef0a62019-03-07 20:34:33 -05002810 if (reader->IsDoneReading()) {
2811 set_detailed_error("Packet has no frames.");
2812 return RaiseError(QUIC_MISSING_PAYLOAD);
2813 }
dschinazi118934b2019-06-13 18:09:08 -07002814 QUIC_DVLOG(2) << ENDPOINT << "Processing packet with header " << header;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002815 while (!reader->IsDoneReading()) {
2816 uint8_t frame_type;
2817 if (!reader->ReadBytes(&frame_type, 1)) {
2818 set_detailed_error("Unable to read frame type.");
2819 return RaiseError(QUIC_INVALID_FRAME_DATA);
2820 }
dschinazi5c1d7d82020-07-29 16:42:50 -07002821 const uint8_t special_mask = version_.HasIetfInvariantHeader()
2822 ? kQuicFrameTypeSpecialMask
2823 : kQuicFrameTypeBrokenMask;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002824 if (frame_type & special_mask) {
2825 // Stream Frame
2826 if (frame_type & kQuicFrameTypeStreamMask) {
2827 QuicStreamFrame frame;
2828 if (!ProcessStreamFrame(reader, frame_type, &frame)) {
2829 return RaiseError(QUIC_INVALID_STREAM_DATA);
2830 }
dschinazi118934b2019-06-13 18:09:08 -07002831 QUIC_DVLOG(2) << ENDPOINT << "Processing stream frame " << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002832 if (!visitor_->OnStreamFrame(frame)) {
2833 QUIC_DVLOG(1) << ENDPOINT
2834 << "Visitor asked to stop further processing.";
2835 // Returning true since there was no parsing error.
2836 return true;
2837 }
2838 continue;
2839 }
2840
2841 // Ack Frame
2842 if (frame_type & kQuicFrameTypeAckMask) {
2843 if (!ProcessAckFrame(reader, frame_type)) {
2844 return RaiseError(QUIC_INVALID_ACK_DATA);
2845 }
dschinazi118934b2019-06-13 18:09:08 -07002846 QUIC_DVLOG(2) << ENDPOINT << "Processing ACK frame";
QUICHE teama6ef0a62019-03-07 20:34:33 -05002847 continue;
2848 }
2849
2850 // This was a special frame type that did not match any
2851 // of the known ones. Error.
2852 set_detailed_error("Illegal frame type.");
2853 QUIC_DLOG(WARNING) << ENDPOINT << "Illegal frame type: "
2854 << static_cast<int>(frame_type);
2855 return RaiseError(QUIC_INVALID_FRAME_DATA);
2856 }
2857
2858 switch (frame_type) {
2859 case PADDING_FRAME: {
2860 QuicPaddingFrame frame;
2861 ProcessPaddingFrame(reader, &frame);
dschinazi118934b2019-06-13 18:09:08 -07002862 QUIC_DVLOG(2) << ENDPOINT << "Processing padding frame " << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002863 if (!visitor_->OnPaddingFrame(frame)) {
2864 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
2865 // Returning true since there was no parsing error.
2866 return true;
2867 }
2868 continue;
2869 }
2870
2871 case RST_STREAM_FRAME: {
2872 QuicRstStreamFrame frame;
2873 if (!ProcessRstStreamFrame(reader, &frame)) {
2874 return RaiseError(QUIC_INVALID_RST_STREAM_DATA);
2875 }
dschinazi118934b2019-06-13 18:09:08 -07002876 QUIC_DVLOG(2) << ENDPOINT << "Processing reset stream frame " << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002877 if (!visitor_->OnRstStreamFrame(frame)) {
2878 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
2879 // Returning true since there was no parsing error.
2880 return true;
2881 }
2882 continue;
2883 }
2884
2885 case CONNECTION_CLOSE_FRAME: {
2886 QuicConnectionCloseFrame frame;
2887 if (!ProcessConnectionCloseFrame(reader, &frame)) {
2888 return RaiseError(QUIC_INVALID_CONNECTION_CLOSE_DATA);
2889 }
2890
dschinazi118934b2019-06-13 18:09:08 -07002891 QUIC_DVLOG(2) << ENDPOINT << "Processing connection close frame "
2892 << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002893 if (!visitor_->OnConnectionCloseFrame(frame)) {
2894 QUIC_DVLOG(1) << ENDPOINT
2895 << "Visitor asked to stop further processing.";
2896 // Returning true since there was no parsing error.
2897 return true;
2898 }
2899 continue;
2900 }
2901
2902 case GOAWAY_FRAME: {
2903 QuicGoAwayFrame goaway_frame;
2904 if (!ProcessGoAwayFrame(reader, &goaway_frame)) {
2905 return RaiseError(QUIC_INVALID_GOAWAY_DATA);
2906 }
dschinazi118934b2019-06-13 18:09:08 -07002907 QUIC_DVLOG(2) << ENDPOINT << "Processing go away frame "
2908 << goaway_frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002909 if (!visitor_->OnGoAwayFrame(goaway_frame)) {
2910 QUIC_DVLOG(1) << ENDPOINT
2911 << "Visitor asked to stop further processing.";
2912 // Returning true since there was no parsing error.
2913 return true;
2914 }
2915 continue;
2916 }
2917
2918 case WINDOW_UPDATE_FRAME: {
2919 QuicWindowUpdateFrame window_update_frame;
2920 if (!ProcessWindowUpdateFrame(reader, &window_update_frame)) {
2921 return RaiseError(QUIC_INVALID_WINDOW_UPDATE_DATA);
2922 }
dschinazi118934b2019-06-13 18:09:08 -07002923 QUIC_DVLOG(2) << ENDPOINT << "Processing window update frame "
2924 << window_update_frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002925 if (!visitor_->OnWindowUpdateFrame(window_update_frame)) {
2926 QUIC_DVLOG(1) << ENDPOINT
2927 << "Visitor asked to stop further processing.";
2928 // Returning true since there was no parsing error.
2929 return true;
2930 }
2931 continue;
2932 }
2933
2934 case BLOCKED_FRAME: {
2935 QuicBlockedFrame blocked_frame;
2936 if (!ProcessBlockedFrame(reader, &blocked_frame)) {
2937 return RaiseError(QUIC_INVALID_BLOCKED_DATA);
2938 }
dschinazi118934b2019-06-13 18:09:08 -07002939 QUIC_DVLOG(2) << ENDPOINT << "Processing blocked frame "
2940 << blocked_frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002941 if (!visitor_->OnBlockedFrame(blocked_frame)) {
2942 QUIC_DVLOG(1) << ENDPOINT
2943 << "Visitor asked to stop further processing.";
2944 // Returning true since there was no parsing error.
2945 return true;
2946 }
2947 continue;
2948 }
2949
2950 case STOP_WAITING_FRAME: {
ianswett97b690b2019-05-02 15:12:43 -07002951 if (GetQuicReloadableFlag(quic_do_not_accept_stop_waiting) &&
dschinazi5c1d7d82020-07-29 16:42:50 -07002952 version_.HasIetfInvariantHeader()) {
ianswett97b690b2019-05-02 15:12:43 -07002953 QUIC_RELOADABLE_FLAG_COUNT(quic_do_not_accept_stop_waiting);
2954 set_detailed_error("STOP WAITING not supported in version 44+.");
2955 return RaiseError(QUIC_INVALID_STOP_WAITING_DATA);
2956 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002957 QuicStopWaitingFrame stop_waiting_frame;
2958 if (!ProcessStopWaitingFrame(reader, header, &stop_waiting_frame)) {
2959 return RaiseError(QUIC_INVALID_STOP_WAITING_DATA);
2960 }
dschinazi118934b2019-06-13 18:09:08 -07002961 QUIC_DVLOG(2) << ENDPOINT << "Processing stop waiting frame "
2962 << stop_waiting_frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002963 if (!visitor_->OnStopWaitingFrame(stop_waiting_frame)) {
2964 QUIC_DVLOG(1) << ENDPOINT
2965 << "Visitor asked to stop further processing.";
2966 // Returning true since there was no parsing error.
2967 return true;
2968 }
2969 continue;
2970 }
2971 case PING_FRAME: {
2972 // Ping has no payload.
2973 QuicPingFrame ping_frame;
2974 if (!visitor_->OnPingFrame(ping_frame)) {
2975 QUIC_DVLOG(1) << ENDPOINT
2976 << "Visitor asked to stop further processing.";
2977 // Returning true since there was no parsing error.
2978 return true;
2979 }
dschinazi118934b2019-06-13 18:09:08 -07002980 QUIC_DVLOG(2) << ENDPOINT << "Processing ping frame " << ping_frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002981 continue;
2982 }
2983 case IETF_EXTENSION_MESSAGE_NO_LENGTH:
2984 QUIC_FALLTHROUGH_INTENDED;
2985 case IETF_EXTENSION_MESSAGE: {
2986 QuicMessageFrame message_frame;
2987 if (!ProcessMessageFrame(reader,
2988 frame_type == IETF_EXTENSION_MESSAGE_NO_LENGTH,
2989 &message_frame)) {
2990 return RaiseError(QUIC_INVALID_MESSAGE_DATA);
2991 }
dschinazi118934b2019-06-13 18:09:08 -07002992 QUIC_DVLOG(2) << ENDPOINT << "Processing message frame "
2993 << message_frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002994 if (!visitor_->OnMessageFrame(message_frame)) {
2995 QUIC_DVLOG(1) << ENDPOINT
2996 << "Visitor asked to stop further processing.";
2997 // Returning true since there was no parsing error.
2998 return true;
2999 }
3000 break;
3001 }
3002 case CRYPTO_FRAME: {
QUICHE teamea740082019-03-11 17:58:43 -07003003 if (!QuicVersionUsesCryptoFrames(version_.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05003004 set_detailed_error("Illegal frame type.");
3005 return RaiseError(QUIC_INVALID_FRAME_DATA);
3006 }
3007 QuicCryptoFrame frame;
renjietang15dfaa82020-01-03 16:13:38 -08003008 if (!ProcessCryptoFrame(reader, GetEncryptionLevel(header), &frame)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05003009 return RaiseError(QUIC_INVALID_FRAME_DATA);
3010 }
dschinazi118934b2019-06-13 18:09:08 -07003011 QUIC_DVLOG(2) << ENDPOINT << "Processing crypto frame " << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003012 if (!visitor_->OnCryptoFrame(frame)) {
3013 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3014 // Returning true since there was no parsing error.
3015 return true;
3016 }
3017 break;
3018 }
fayang5c362882020-06-16 07:39:39 -07003019 case HANDSHAKE_DONE_FRAME: {
3020 // HANDSHAKE_DONE has no payload.
3021 QuicHandshakeDoneFrame handshake_done_frame;
3022 QUIC_DVLOG(2) << ENDPOINT << "Processing handshake done frame "
3023 << handshake_done_frame;
3024 if (!visitor_->OnHandshakeDoneFrame(handshake_done_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 break;
3031 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05003032
3033 default:
3034 set_detailed_error("Illegal frame type.");
3035 QUIC_DLOG(WARNING) << ENDPOINT << "Illegal frame type: "
3036 << static_cast<int>(frame_type);
3037 return RaiseError(QUIC_INVALID_FRAME_DATA);
3038 }
3039 }
3040
3041 return true;
3042}
3043
3044bool QuicFramer::ProcessIetfFrameData(QuicDataReader* reader,
3045 const QuicPacketHeader& header) {
fkastenholz305e1732019-06-18 05:01:22 -07003046 DCHECK(VersionHasIetfQuicFrames(version_.transport_version))
3047 << "Attempt to process frames as IETF frames but version ("
3048 << version_.transport_version << ") does not support IETF Framing.";
3049
QUICHE teama6ef0a62019-03-07 20:34:33 -05003050 if (reader->IsDoneReading()) {
3051 set_detailed_error("Packet has no frames.");
3052 return RaiseError(QUIC_MISSING_PAYLOAD);
3053 }
dschinazi118934b2019-06-13 18:09:08 -07003054
3055 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF packet with header " << header;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003056 while (!reader->IsDoneReading()) {
3057 uint64_t frame_type;
3058 // Will be the number of bytes into which frame_type was encoded.
3059 size_t encoded_bytes = reader->BytesRemaining();
3060 if (!reader->ReadVarInt62(&frame_type)) {
3061 set_detailed_error("Unable to read frame type.");
3062 return RaiseError(QUIC_INVALID_FRAME_DATA);
3063 }
fkastenholza3660102019-08-28 05:19:24 -07003064 current_received_frame_type_ = frame_type;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003065
3066 // Is now the number of bytes into which the frame type was encoded.
3067 encoded_bytes -= reader->BytesRemaining();
3068
3069 // Check that the frame type is minimally encoded.
3070 if (encoded_bytes !=
3071 static_cast<size_t>(QuicDataWriter::GetVarInt62Len(frame_type))) {
3072 // The frame type was not minimally encoded.
3073 set_detailed_error("Frame type not minimally encoded.");
3074 return RaiseError(IETF_QUIC_PROTOCOL_VIOLATION);
3075 }
3076
3077 if (IS_IETF_STREAM_FRAME(frame_type)) {
3078 QuicStreamFrame frame;
3079 if (!ProcessIetfStreamFrame(reader, frame_type, &frame)) {
3080 return RaiseError(QUIC_INVALID_STREAM_DATA);
3081 }
dschinazi118934b2019-06-13 18:09:08 -07003082 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF stream frame " << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003083 if (!visitor_->OnStreamFrame(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 } else {
3090 switch (frame_type) {
3091 case IETF_PADDING: {
3092 QuicPaddingFrame frame;
3093 ProcessPaddingFrame(reader, &frame);
dschinazi118934b2019-06-13 18:09:08 -07003094 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF padding frame "
3095 << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003096 if (!visitor_->OnPaddingFrame(frame)) {
3097 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3098 // Returning true since there was no parsing error.
3099 return true;
3100 }
3101 break;
3102 }
3103 case IETF_RST_STREAM: {
3104 QuicRstStreamFrame frame;
3105 if (!ProcessIetfResetStreamFrame(reader, &frame)) {
3106 return RaiseError(QUIC_INVALID_RST_STREAM_DATA);
3107 }
dschinazi118934b2019-06-13 18:09:08 -07003108 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF reset stream frame "
3109 << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003110 if (!visitor_->OnRstStreamFrame(frame)) {
3111 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3112 // Returning true since there was no parsing error.
3113 return true;
3114 }
3115 break;
3116 }
fkastenholz04bd4f32019-04-16 12:24:38 -07003117 case IETF_APPLICATION_CLOSE:
QUICHE teama6ef0a62019-03-07 20:34:33 -05003118 case IETF_CONNECTION_CLOSE: {
3119 QuicConnectionCloseFrame frame;
fkastenholze9d71a82019-04-09 05:12:13 -07003120 if (!ProcessIetfConnectionCloseFrame(
fkastenholz04bd4f32019-04-16 12:24:38 -07003121 reader,
3122 (frame_type == IETF_CONNECTION_CLOSE)
3123 ? IETF_QUIC_TRANSPORT_CONNECTION_CLOSE
3124 : IETF_QUIC_APPLICATION_CONNECTION_CLOSE,
3125 &frame)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05003126 return RaiseError(QUIC_INVALID_CONNECTION_CLOSE_DATA);
3127 }
dschinazi118934b2019-06-13 18:09:08 -07003128 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF connection close frame "
3129 << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003130 if (!visitor_->OnConnectionCloseFrame(frame)) {
3131 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3132 // Returning true since there was no parsing error.
3133 return true;
3134 }
3135 break;
3136 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05003137 case IETF_MAX_DATA: {
3138 QuicWindowUpdateFrame frame;
3139 if (!ProcessMaxDataFrame(reader, &frame)) {
3140 return RaiseError(QUIC_INVALID_MAX_DATA_FRAME_DATA);
3141 }
dschinazi118934b2019-06-13 18:09:08 -07003142 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF max data frame "
3143 << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003144 if (!visitor_->OnWindowUpdateFrame(frame)) {
3145 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3146 // Returning true since there was no parsing error.
3147 return true;
3148 }
3149 break;
3150 }
3151 case IETF_MAX_STREAM_DATA: {
3152 QuicWindowUpdateFrame frame;
3153 if (!ProcessMaxStreamDataFrame(reader, &frame)) {
3154 return RaiseError(QUIC_INVALID_MAX_STREAM_DATA_FRAME_DATA);
3155 }
dschinazi118934b2019-06-13 18:09:08 -07003156 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF max stream data frame "
3157 << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003158 if (!visitor_->OnWindowUpdateFrame(frame)) {
3159 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3160 // Returning true since there was no parsing error.
3161 return true;
3162 }
3163 break;
3164 }
3165 case IETF_MAX_STREAMS_BIDIRECTIONAL:
3166 case IETF_MAX_STREAMS_UNIDIRECTIONAL: {
fkastenholz3c4eabf2019-04-22 07:49:59 -07003167 QuicMaxStreamsFrame frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003168 if (!ProcessMaxStreamsFrame(reader, &frame, frame_type)) {
fkastenholz3c4eabf2019-04-22 07:49:59 -07003169 return RaiseError(QUIC_MAX_STREAMS_DATA);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003170 }
fkastenholz3c4eabf2019-04-22 07:49:59 -07003171 QUIC_CODE_COUNT_N(quic_max_streams_received, 1, 2);
dschinazi118934b2019-06-13 18:09:08 -07003172 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF max streams frame "
3173 << frame;
fkastenholz3c4eabf2019-04-22 07:49:59 -07003174 if (!visitor_->OnMaxStreamsFrame(frame)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05003175 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3176 // Returning true since there was no parsing error.
3177 return true;
3178 }
3179 break;
3180 }
3181 case IETF_PING: {
3182 // Ping has no payload.
3183 QuicPingFrame ping_frame;
dschinazi118934b2019-06-13 18:09:08 -07003184 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF ping frame "
3185 << ping_frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003186 if (!visitor_->OnPingFrame(ping_frame)) {
3187 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3188 // Returning true since there was no parsing error.
3189 return true;
3190 }
3191 break;
3192 }
ianswett2f077442019-12-12 11:51:24 -08003193 case IETF_DATA_BLOCKED: {
QUICHE teama6ef0a62019-03-07 20:34:33 -05003194 QuicBlockedFrame frame;
renjietangf8a9c8c2020-03-19 16:47:03 -07003195 if (!ProcessDataBlockedFrame(reader, &frame)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05003196 return RaiseError(QUIC_INVALID_BLOCKED_DATA);
3197 }
dschinazi118934b2019-06-13 18:09:08 -07003198 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF blocked frame "
3199 << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003200 if (!visitor_->OnBlockedFrame(frame)) {
3201 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3202 // Returning true since there was no parsing error.
3203 return true;
3204 }
3205 break;
3206 }
ianswett2f077442019-12-12 11:51:24 -08003207 case IETF_STREAM_DATA_BLOCKED: {
QUICHE teama6ef0a62019-03-07 20:34:33 -05003208 QuicBlockedFrame frame;
renjietangf8a9c8c2020-03-19 16:47:03 -07003209 if (!ProcessStreamDataBlockedFrame(reader, &frame)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05003210 return RaiseError(QUIC_INVALID_STREAM_BLOCKED_DATA);
3211 }
dschinazi118934b2019-06-13 18:09:08 -07003212 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF stream blocked frame "
3213 << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003214 if (!visitor_->OnBlockedFrame(frame)) {
3215 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3216 // Returning true since there was no parsing error.
3217 return true;
3218 }
3219 break;
3220 }
3221 case IETF_STREAMS_BLOCKED_UNIDIRECTIONAL:
3222 case IETF_STREAMS_BLOCKED_BIDIRECTIONAL: {
fkastenholz3c4eabf2019-04-22 07:49:59 -07003223 QuicStreamsBlockedFrame frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003224 if (!ProcessStreamsBlockedFrame(reader, &frame, frame_type)) {
fkastenholz3c4eabf2019-04-22 07:49:59 -07003225 return RaiseError(QUIC_STREAMS_BLOCKED_DATA);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003226 }
dschinazi118934b2019-06-13 18:09:08 -07003227 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF streams blocked frame "
3228 << frame;
fkastenholz3c4eabf2019-04-22 07:49:59 -07003229 if (!visitor_->OnStreamsBlockedFrame(frame)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05003230 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3231 // Returning true since there was no parsing error.
3232 return true;
3233 }
3234 break;
3235 }
3236 case IETF_NEW_CONNECTION_ID: {
3237 QuicNewConnectionIdFrame frame;
3238 if (!ProcessNewConnectionIdFrame(reader, &frame)) {
3239 return RaiseError(QUIC_INVALID_NEW_CONNECTION_ID_DATA);
3240 }
dschinazi118934b2019-06-13 18:09:08 -07003241 QUIC_DVLOG(2) << ENDPOINT
3242 << "Processing IETF new connection ID frame " << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003243 if (!visitor_->OnNewConnectionIdFrame(frame)) {
3244 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3245 // Returning true since there was no parsing error.
3246 return true;
3247 }
3248 break;
3249 }
3250 case IETF_RETIRE_CONNECTION_ID: {
3251 QuicRetireConnectionIdFrame frame;
3252 if (!ProcessRetireConnectionIdFrame(reader, &frame)) {
3253 return RaiseError(QUIC_INVALID_RETIRE_CONNECTION_ID_DATA);
3254 }
dschinazi118934b2019-06-13 18:09:08 -07003255 QUIC_DVLOG(2) << ENDPOINT
3256 << "Processing IETF retire connection ID frame "
3257 << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003258 if (!visitor_->OnRetireConnectionIdFrame(frame)) {
3259 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3260 // Returning true since there was no parsing error.
3261 return true;
3262 }
3263 break;
3264 }
3265 case IETF_NEW_TOKEN: {
3266 QuicNewTokenFrame frame;
3267 if (!ProcessNewTokenFrame(reader, &frame)) {
3268 return RaiseError(QUIC_INVALID_NEW_TOKEN);
3269 }
dschinazi118934b2019-06-13 18:09:08 -07003270 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF new token frame "
3271 << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003272 if (!visitor_->OnNewTokenFrame(frame)) {
3273 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3274 // Returning true since there was no parsing error.
3275 return true;
3276 }
3277 break;
3278 }
3279 case IETF_STOP_SENDING: {
3280 QuicStopSendingFrame frame;
3281 if (!ProcessStopSendingFrame(reader, &frame)) {
3282 return RaiseError(QUIC_INVALID_STOP_SENDING_FRAME_DATA);
3283 }
dschinazi118934b2019-06-13 18:09:08 -07003284 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF stop sending frame "
3285 << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003286 if (!visitor_->OnStopSendingFrame(frame)) {
3287 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3288 // Returning true since there was no parsing error.
3289 return true;
3290 }
3291 break;
3292 }
3293 case IETF_ACK_ECN:
3294 case IETF_ACK: {
3295 QuicAckFrame frame;
3296 if (!ProcessIetfAckFrame(reader, frame_type, &frame)) {
3297 return RaiseError(QUIC_INVALID_ACK_DATA);
3298 }
dschinazi118934b2019-06-13 18:09:08 -07003299 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF ACK frame " << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003300 break;
3301 }
3302 case IETF_PATH_CHALLENGE: {
3303 QuicPathChallengeFrame frame;
3304 if (!ProcessPathChallengeFrame(reader, &frame)) {
3305 return RaiseError(QUIC_INVALID_PATH_CHALLENGE_DATA);
3306 }
dschinazi118934b2019-06-13 18:09:08 -07003307 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF path challenge frame "
3308 << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003309 if (!visitor_->OnPathChallengeFrame(frame)) {
3310 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3311 // Returning true since there was no parsing error.
3312 return true;
3313 }
3314 break;
3315 }
3316 case IETF_PATH_RESPONSE: {
3317 QuicPathResponseFrame frame;
3318 if (!ProcessPathResponseFrame(reader, &frame)) {
3319 return RaiseError(QUIC_INVALID_PATH_RESPONSE_DATA);
3320 }
dschinazi118934b2019-06-13 18:09:08 -07003321 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF path response frame "
3322 << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003323 if (!visitor_->OnPathResponseFrame(frame)) {
3324 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3325 // Returning true since there was no parsing error.
3326 return true;
3327 }
3328 break;
3329 }
dschinazicd86dd12019-11-14 10:11:13 -08003330 case IETF_EXTENSION_MESSAGE_NO_LENGTH_V99:
QUICHE teama6ef0a62019-03-07 20:34:33 -05003331 QUIC_FALLTHROUGH_INTENDED;
dschinazicd86dd12019-11-14 10:11:13 -08003332 case IETF_EXTENSION_MESSAGE_V99: {
QUICHE teama6ef0a62019-03-07 20:34:33 -05003333 QuicMessageFrame message_frame;
3334 if (!ProcessMessageFrame(
dschinazicd86dd12019-11-14 10:11:13 -08003335 reader, frame_type == IETF_EXTENSION_MESSAGE_NO_LENGTH_V99,
QUICHE teama6ef0a62019-03-07 20:34:33 -05003336 &message_frame)) {
3337 return RaiseError(QUIC_INVALID_MESSAGE_DATA);
3338 }
dschinazi118934b2019-06-13 18:09:08 -07003339 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF message frame "
3340 << message_frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003341 if (!visitor_->OnMessageFrame(message_frame)) {
3342 QUIC_DVLOG(1) << ENDPOINT
3343 << "Visitor asked to stop further processing.";
3344 // Returning true since there was no parsing error.
3345 return true;
3346 }
3347 break;
3348 }
3349 case IETF_CRYPTO: {
3350 QuicCryptoFrame frame;
renjietang15dfaa82020-01-03 16:13:38 -08003351 if (!ProcessCryptoFrame(reader, GetEncryptionLevel(header), &frame)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05003352 return RaiseError(QUIC_INVALID_FRAME_DATA);
3353 }
dschinazi118934b2019-06-13 18:09:08 -07003354 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF crypto frame " << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003355 if (!visitor_->OnCryptoFrame(frame)) {
3356 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3357 // Returning true since there was no parsing error.
3358 return true;
3359 }
3360 break;
3361 }
fayang01062942020-01-22 07:23:23 -08003362 case IETF_HANDSHAKE_DONE: {
3363 // HANDSHAKE_DONE has no payload.
3364 QuicHandshakeDoneFrame handshake_done_frame;
3365 if (!visitor_->OnHandshakeDoneFrame(handshake_done_frame)) {
3366 QUIC_DVLOG(1) << ENDPOINT
3367 << "Visitor asked to stop further processing.";
3368 // Returning true since there was no parsing error.
3369 return true;
3370 }
3371 QUIC_DVLOG(2) << ENDPOINT << "Processing handshake done frame "
3372 << handshake_done_frame;
3373 break;
3374 }
haoyuewang6a6a0ff2020-06-23 16:32:26 -07003375 case IETF_ACK_FREQUENCY: {
3376 QuicAckFrequencyFrame frame;
3377 if (!ProcessAckFrequencyFrame(reader, &frame)) {
3378 return RaiseError(QUIC_INVALID_FRAME_DATA);
3379 }
3380 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF ack frequency frame "
3381 << frame;
3382 if (!visitor_->OnAckFrequencyFrame(frame)) {
3383 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3384 // Returning true since there was no parsing error.
3385 return true;
3386 }
3387 break;
3388 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05003389 default:
3390 set_detailed_error("Illegal frame type.");
3391 QUIC_DLOG(WARNING)
3392 << ENDPOINT
3393 << "Illegal frame type: " << static_cast<int>(frame_type);
3394 return RaiseError(QUIC_INVALID_FRAME_DATA);
3395 }
3396 }
3397 }
3398 return true;
3399}
3400
3401namespace {
3402// Create a mask that sets the last |num_bits| to 1 and the rest to 0.
3403inline uint8_t GetMaskFromNumBits(uint8_t num_bits) {
3404 return (1u << num_bits) - 1;
3405}
3406
3407// Extract |num_bits| from |flags| offset by |offset|.
3408uint8_t ExtractBits(uint8_t flags, uint8_t num_bits, uint8_t offset) {
3409 return (flags >> offset) & GetMaskFromNumBits(num_bits);
3410}
3411
3412// Extract the bit at position |offset| from |flags| as a bool.
3413bool ExtractBit(uint8_t flags, uint8_t offset) {
3414 return ((flags >> offset) & GetMaskFromNumBits(1)) != 0;
3415}
3416
3417// Set |num_bits|, offset by |offset| to |val| in |flags|.
3418void SetBits(uint8_t* flags, uint8_t val, uint8_t num_bits, uint8_t offset) {
3419 DCHECK_LE(val, GetMaskFromNumBits(num_bits));
3420 *flags |= val << offset;
3421}
3422
3423// Set the bit at position |offset| to |val| in |flags|.
3424void SetBit(uint8_t* flags, bool val, uint8_t offset) {
3425 SetBits(flags, val ? 1 : 0, 1, offset);
3426}
3427} // namespace
3428
3429bool QuicFramer::ProcessStreamFrame(QuicDataReader* reader,
3430 uint8_t frame_type,
3431 QuicStreamFrame* frame) {
3432 uint8_t stream_flags = frame_type;
3433
3434 uint8_t stream_id_length = 0;
3435 uint8_t offset_length = 4;
3436 bool has_data_length = true;
3437 stream_flags &= ~kQuicFrameTypeStreamMask;
3438
3439 // Read from right to left: StreamID, Offset, Data Length, Fin.
3440 stream_id_length = (stream_flags & kQuicStreamIDLengthMask) + 1;
3441 stream_flags >>= kQuicStreamIdShift;
3442
3443 offset_length = (stream_flags & kQuicStreamOffsetMask);
3444 // There is no encoding for 1 byte, only 0 and 2 through 8.
3445 if (offset_length > 0) {
3446 offset_length += 1;
3447 }
3448 stream_flags >>= kQuicStreamShift;
3449
3450 has_data_length =
3451 (stream_flags & kQuicStreamDataLengthMask) == kQuicStreamDataLengthMask;
3452 stream_flags >>= kQuicStreamDataLengthShift;
3453
3454 frame->fin = (stream_flags & kQuicStreamFinMask) == kQuicStreamFinShift;
3455
3456 uint64_t stream_id;
3457 if (!reader->ReadBytesToUInt64(stream_id_length, &stream_id)) {
3458 set_detailed_error("Unable to read stream_id.");
3459 return false;
3460 }
3461 frame->stream_id = static_cast<QuicStreamId>(stream_id);
3462
3463 if (!reader->ReadBytesToUInt64(offset_length, &frame->offset)) {
3464 set_detailed_error("Unable to read offset.");
3465 return false;
3466 }
3467
dmcardlecf0bfcf2019-12-13 08:08:21 -08003468 // TODO(ianswett): Don't use quiche::QuicheStringPiece as an intermediary.
3469 quiche::QuicheStringPiece data;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003470 if (has_data_length) {
3471 if (!reader->ReadStringPiece16(&data)) {
3472 set_detailed_error("Unable to read frame data.");
3473 return false;
3474 }
3475 } else {
3476 if (!reader->ReadStringPiece(&data, reader->BytesRemaining())) {
3477 set_detailed_error("Unable to read frame data.");
3478 return false;
3479 }
3480 }
3481 frame->data_buffer = data.data();
3482 frame->data_length = static_cast<uint16_t>(data.length());
3483
3484 return true;
3485}
3486
3487bool QuicFramer::ProcessIetfStreamFrame(QuicDataReader* reader,
3488 uint8_t frame_type,
3489 QuicStreamFrame* frame) {
3490 // Read stream id from the frame. It's always present.
renjietangd077f8c2020-03-23 17:22:09 -07003491 if (!ReadUint32FromVarint62(reader, IETF_STREAM, &frame->stream_id)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05003492 return false;
3493 }
3494
3495 // If we have a data offset, read it. If not, set to 0.
3496 if (frame_type & IETF_STREAM_FRAME_OFF_BIT) {
3497 if (!reader->ReadVarInt62(&frame->offset)) {
3498 set_detailed_error("Unable to read stream data offset.");
3499 return false;
3500 }
3501 } else {
3502 // no offset in the frame, ensure it's 0 in the Frame.
3503 frame->offset = 0;
3504 }
3505
3506 // If we have a data length, read it. If not, set to 0.
3507 if (frame_type & IETF_STREAM_FRAME_LEN_BIT) {
dschinazi5c70d482020-04-27 15:58:16 -07003508 uint64_t length;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003509 if (!reader->ReadVarInt62(&length)) {
3510 set_detailed_error("Unable to read stream data length.");
3511 return false;
3512 }
dschinazi5c70d482020-04-27 15:58:16 -07003513 if (length > std::numeric_limits<decltype(frame->data_length)>::max()) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05003514 set_detailed_error("Stream data length is too large.");
3515 return false;
3516 }
3517 frame->data_length = length;
3518 } else {
3519 // no length in the frame, it is the number of bytes remaining in the
3520 // packet.
3521 frame->data_length = reader->BytesRemaining();
3522 }
3523
3524 if (frame_type & IETF_STREAM_FRAME_FIN_BIT) {
3525 frame->fin = true;
3526 } else {
3527 frame->fin = false;
3528 }
3529
dmcardlecf0bfcf2019-12-13 08:08:21 -08003530 // TODO(ianswett): Don't use quiche::QuicheStringPiece as an intermediary.
3531 quiche::QuicheStringPiece data;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003532 if (!reader->ReadStringPiece(&data, frame->data_length)) {
3533 set_detailed_error("Unable to read frame data.");
3534 return false;
3535 }
3536 frame->data_buffer = data.data();
dschinazi5c70d482020-04-27 15:58:16 -07003537 DCHECK_EQ(frame->data_length, data.length());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003538
3539 return true;
3540}
3541
3542bool QuicFramer::ProcessCryptoFrame(QuicDataReader* reader,
renjietang15dfaa82020-01-03 16:13:38 -08003543 EncryptionLevel encryption_level,
QUICHE teama6ef0a62019-03-07 20:34:33 -05003544 QuicCryptoFrame* frame) {
renjietang15dfaa82020-01-03 16:13:38 -08003545 frame->level = encryption_level;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003546 if (!reader->ReadVarInt62(&frame->offset)) {
3547 set_detailed_error("Unable to read crypto data offset.");
3548 return false;
3549 }
3550 uint64_t len;
3551 if (!reader->ReadVarInt62(&len) ||
3552 len > std::numeric_limits<QuicPacketLength>::max()) {
3553 set_detailed_error("Invalid data length.");
3554 return false;
3555 }
3556 frame->data_length = len;
3557
dmcardlecf0bfcf2019-12-13 08:08:21 -08003558 // TODO(ianswett): Don't use quiche::QuicheStringPiece as an intermediary.
3559 quiche::QuicheStringPiece data;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003560 if (!reader->ReadStringPiece(&data, frame->data_length)) {
3561 set_detailed_error("Unable to read frame data.");
3562 return false;
3563 }
3564 frame->data_buffer = data.data();
3565 return true;
3566}
3567
haoyuewang6a6a0ff2020-06-23 16:32:26 -07003568bool QuicFramer::ProcessAckFrequencyFrame(QuicDataReader* reader,
3569 QuicAckFrequencyFrame* frame) {
3570 if (!reader->ReadVarInt62(&frame->sequence_number)) {
3571 set_detailed_error("Unable to read sequence number.");
3572 return false;
3573 }
3574
3575 if (!reader->ReadVarInt62(&frame->packet_tolerance)) {
3576 set_detailed_error("Unable to read packet tolerance.");
3577 return false;
3578 }
3579 if (frame->packet_tolerance == 0) {
3580 set_detailed_error("Invalid packet tolerance.");
3581 return false;
3582 }
3583 uint64_t max_ack_delay_us;
3584 if (!reader->ReadVarInt62(&max_ack_delay_us)) {
3585 set_detailed_error("Unable to read max_ack_delay_us.");
3586 return false;
3587 }
3588 constexpr uint64_t kMaxAckDelayUsBound = 1u << 24;
3589 if (max_ack_delay_us > kMaxAckDelayUsBound) {
3590 set_detailed_error("Invalid max_ack_delay_us.");
3591 return false;
3592 }
3593 frame->max_ack_delay = QuicTime::Delta::FromMicroseconds(max_ack_delay_us);
3594
3595 uint8_t ignore_order;
3596 if (!reader->ReadUInt8(&ignore_order)) {
3597 set_detailed_error("Unable to read ignore_order.");
3598 return false;
3599 }
3600 if (ignore_order > 1) {
3601 set_detailed_error("Invalid ignore_order.");
3602 return false;
3603 }
3604 frame->ignore_order = ignore_order;
3605
3606 return true;
3607}
3608
QUICHE teama6ef0a62019-03-07 20:34:33 -05003609bool QuicFramer::ProcessAckFrame(QuicDataReader* reader, uint8_t frame_type) {
3610 const bool has_ack_blocks =
3611 ExtractBit(frame_type, kQuicHasMultipleAckBlocksOffset);
3612 uint8_t num_ack_blocks = 0;
3613 uint8_t num_received_packets = 0;
3614
3615 // Determine the two lengths from the frame type: largest acked length,
3616 // ack block length.
3617 const QuicPacketNumberLength ack_block_length = ReadAckPacketNumberLength(
QUICHE teama6ef0a62019-03-07 20:34:33 -05003618 ExtractBits(frame_type, kQuicSequenceNumberLengthNumBits,
3619 kActBlockLengthOffset));
3620 const QuicPacketNumberLength largest_acked_length = ReadAckPacketNumberLength(
QUICHE teama6ef0a62019-03-07 20:34:33 -05003621 ExtractBits(frame_type, kQuicSequenceNumberLengthNumBits,
3622 kLargestAckedOffset));
3623
3624 uint64_t largest_acked;
3625 if (!reader->ReadBytesToUInt64(largest_acked_length, &largest_acked)) {
3626 set_detailed_error("Unable to read largest acked.");
3627 return false;
3628 }
3629
3630 if (largest_acked < first_sending_packet_number_.ToUint64()) {
3631 // Connection always sends packet starting from kFirstSendingPacketNumber >
3632 // 0, peer has observed an unsent packet.
3633 set_detailed_error("Largest acked is 0.");
3634 return false;
3635 }
3636
3637 uint64_t ack_delay_time_us;
3638 if (!reader->ReadUFloat16(&ack_delay_time_us)) {
3639 set_detailed_error("Unable to read ack delay time.");
3640 return false;
3641 }
3642
3643 if (!visitor_->OnAckFrameStart(
3644 QuicPacketNumber(largest_acked),
3645 ack_delay_time_us == kUFloat16MaxValue
3646 ? QuicTime::Delta::Infinite()
3647 : QuicTime::Delta::FromMicroseconds(ack_delay_time_us))) {
3648 // The visitor suppresses further processing of the packet. Although this is
3649 // not a parsing error, returns false as this is in middle of processing an
3650 // ack frame,
3651 set_detailed_error("Visitor suppresses further processing of ack frame.");
3652 return false;
3653 }
3654
3655 if (has_ack_blocks && !reader->ReadUInt8(&num_ack_blocks)) {
3656 set_detailed_error("Unable to read num of ack blocks.");
3657 return false;
3658 }
3659
3660 uint64_t first_block_length;
3661 if (!reader->ReadBytesToUInt64(ack_block_length, &first_block_length)) {
3662 set_detailed_error("Unable to read first ack block length.");
3663 return false;
3664 }
3665
3666 if (first_block_length == 0) {
3667 set_detailed_error("First block length is zero.");
3668 return false;
3669 }
3670 bool first_ack_block_underflow = first_block_length > largest_acked + 1;
3671 if (first_block_length + first_sending_packet_number_.ToUint64() >
3672 largest_acked + 1) {
3673 first_ack_block_underflow = true;
3674 }
3675 if (first_ack_block_underflow) {
dmcardlecf0bfcf2019-12-13 08:08:21 -08003676 set_detailed_error(
3677 quiche::QuicheStrCat("Underflow with first ack block length ",
3678 first_block_length, " largest acked is ",
3679 largest_acked, ".")
3680 .c_str());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003681 return false;
3682 }
3683
3684 uint64_t first_received = largest_acked + 1 - first_block_length;
3685 if (!visitor_->OnAckRange(QuicPacketNumber(first_received),
3686 QuicPacketNumber(largest_acked + 1))) {
3687 // The visitor suppresses further processing of the packet. Although
3688 // this is not a parsing error, returns false as this is in middle
3689 // of processing an ack frame,
3690 set_detailed_error("Visitor suppresses further processing of ack frame.");
3691 return false;
3692 }
3693
3694 if (num_ack_blocks > 0) {
3695 for (size_t i = 0; i < num_ack_blocks; ++i) {
3696 uint8_t gap = 0;
3697 if (!reader->ReadUInt8(&gap)) {
3698 set_detailed_error("Unable to read gap to next ack block.");
3699 return false;
3700 }
3701 uint64_t current_block_length;
3702 if (!reader->ReadBytesToUInt64(ack_block_length, &current_block_length)) {
3703 set_detailed_error("Unable to ack block length.");
3704 return false;
3705 }
3706 bool ack_block_underflow = first_received < gap + current_block_length;
3707 if (first_received < gap + current_block_length +
3708 first_sending_packet_number_.ToUint64()) {
3709 ack_block_underflow = true;
3710 }
3711 if (ack_block_underflow) {
3712 set_detailed_error(
dmcardlecf0bfcf2019-12-13 08:08:21 -08003713 quiche::QuicheStrCat("Underflow with ack block length ",
3714 current_block_length, ", end of block is ",
3715 first_received - gap, ".")
QUICHE teama6ef0a62019-03-07 20:34:33 -05003716 .c_str());
3717 return false;
3718 }
3719
3720 first_received -= (gap + current_block_length);
3721 if (current_block_length > 0) {
3722 if (!visitor_->OnAckRange(
3723 QuicPacketNumber(first_received),
3724 QuicPacketNumber(first_received) + current_block_length)) {
3725 // The visitor suppresses further processing of the packet. Although
3726 // this is not a parsing error, returns false as this is in middle
3727 // of processing an ack frame,
3728 set_detailed_error(
3729 "Visitor suppresses further processing of ack frame.");
3730 return false;
3731 }
3732 }
3733 }
3734 }
3735
3736 if (!reader->ReadUInt8(&num_received_packets)) {
3737 set_detailed_error("Unable to read num received packets.");
3738 return false;
3739 }
3740
3741 if (!ProcessTimestampsInAckFrame(num_received_packets,
3742 QuicPacketNumber(largest_acked), reader)) {
3743 return false;
3744 }
3745
3746 // Done processing the ACK frame.
fayang533cb1b2020-01-28 08:05:08 -08003747 if (!visitor_->OnAckFrameEnd(QuicPacketNumber(first_received))) {
3748 set_detailed_error(
3749 "Error occurs when visitor finishes processing the ACK frame.");
3750 return false;
3751 }
3752
3753 return true;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003754}
3755
3756bool QuicFramer::ProcessTimestampsInAckFrame(uint8_t num_received_packets,
3757 QuicPacketNumber largest_acked,
3758 QuicDataReader* reader) {
3759 if (num_received_packets == 0) {
3760 return true;
3761 }
3762 uint8_t delta_from_largest_observed;
3763 if (!reader->ReadUInt8(&delta_from_largest_observed)) {
3764 set_detailed_error("Unable to read sequence delta in received packets.");
3765 return false;
3766 }
3767
3768 if (largest_acked.ToUint64() <= delta_from_largest_observed) {
dmcardlecf0bfcf2019-12-13 08:08:21 -08003769 set_detailed_error(
3770 quiche::QuicheStrCat("delta_from_largest_observed too high: ",
3771 delta_from_largest_observed,
3772 ", largest_acked: ", largest_acked.ToUint64())
3773 .c_str());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003774 return false;
3775 }
3776
3777 // Time delta from the framer creation.
3778 uint32_t time_delta_us;
3779 if (!reader->ReadUInt32(&time_delta_us)) {
3780 set_detailed_error("Unable to read time delta in received packets.");
3781 return false;
3782 }
3783
3784 QuicPacketNumber seq_num = largest_acked - delta_from_largest_observed;
3785 if (process_timestamps_) {
3786 last_timestamp_ = CalculateTimestampFromWire(time_delta_us);
3787
3788 visitor_->OnAckTimestamp(seq_num, creation_time_ + last_timestamp_);
3789 }
3790
3791 for (uint8_t i = 1; i < num_received_packets; ++i) {
3792 if (!reader->ReadUInt8(&delta_from_largest_observed)) {
3793 set_detailed_error("Unable to read sequence delta in received packets.");
3794 return false;
3795 }
3796 if (largest_acked.ToUint64() <= delta_from_largest_observed) {
3797 set_detailed_error(
dmcardlecf0bfcf2019-12-13 08:08:21 -08003798 quiche::QuicheStrCat("delta_from_largest_observed too high: ",
3799 delta_from_largest_observed,
3800 ", largest_acked: ", largest_acked.ToUint64())
QUICHE teama6ef0a62019-03-07 20:34:33 -05003801 .c_str());
3802 return false;
3803 }
3804 seq_num = largest_acked - delta_from_largest_observed;
3805
3806 // Time delta from the previous timestamp.
3807 uint64_t incremental_time_delta_us;
3808 if (!reader->ReadUFloat16(&incremental_time_delta_us)) {
3809 set_detailed_error(
3810 "Unable to read incremental time delta in received packets.");
3811 return false;
3812 }
3813
3814 if (process_timestamps_) {
3815 last_timestamp_ = last_timestamp_ + QuicTime::Delta::FromMicroseconds(
3816 incremental_time_delta_us);
3817 visitor_->OnAckTimestamp(seq_num, creation_time_ + last_timestamp_);
3818 }
3819 }
3820 return true;
3821}
3822
3823bool QuicFramer::ProcessIetfAckFrame(QuicDataReader* reader,
3824 uint64_t frame_type,
3825 QuicAckFrame* ack_frame) {
3826 uint64_t largest_acked;
3827 if (!reader->ReadVarInt62(&largest_acked)) {
3828 set_detailed_error("Unable to read largest acked.");
3829 return false;
3830 }
3831 if (largest_acked < first_sending_packet_number_.ToUint64()) {
3832 // Connection always sends packet starting from kFirstSendingPacketNumber >
3833 // 0, peer has observed an unsent packet.
3834 set_detailed_error("Largest acked is 0.");
3835 return false;
3836 }
3837 ack_frame->largest_acked = static_cast<QuicPacketNumber>(largest_acked);
3838 uint64_t ack_delay_time_in_us;
3839 if (!reader->ReadVarInt62(&ack_delay_time_in_us)) {
3840 set_detailed_error("Unable to read ack delay time.");
3841 return false;
3842 }
3843
fayang3371b092019-12-04 07:08:52 -08003844 if (ack_delay_time_in_us >= (kVarInt62MaxValue >> peer_ack_delay_exponent_)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05003845 ack_frame->ack_delay_time = QuicTime::Delta::Infinite();
3846 } else {
fkastenholz4dc4ba32019-07-30 09:55:25 -07003847 ack_delay_time_in_us = (ack_delay_time_in_us << peer_ack_delay_exponent_);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003848 ack_frame->ack_delay_time =
3849 QuicTime::Delta::FromMicroseconds(ack_delay_time_in_us);
3850 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05003851 if (!visitor_->OnAckFrameStart(QuicPacketNumber(largest_acked),
3852 ack_frame->ack_delay_time)) {
3853 // The visitor suppresses further processing of the packet. Although this is
3854 // not a parsing error, returns false as this is in middle of processing an
3855 // ACK frame.
3856 set_detailed_error("Visitor suppresses further processing of ACK frame.");
3857 return false;
3858 }
3859
3860 // Get number of ACK blocks from the packet.
3861 uint64_t ack_block_count;
3862 if (!reader->ReadVarInt62(&ack_block_count)) {
3863 set_detailed_error("Unable to read ack block count.");
3864 return false;
3865 }
3866 // There always is a first ACK block, which is the (number of packets being
3867 // acked)-1, up to and including the packet at largest_acked. Therefore if the
3868 // value is 0, then only largest is acked. If it is 1, then largest-1,
3869 // largest] are acked, etc
3870 uint64_t ack_block_value;
3871 if (!reader->ReadVarInt62(&ack_block_value)) {
3872 set_detailed_error("Unable to read first ack block length.");
3873 return false;
3874 }
3875 // Calculate the packets being acked in the first block.
3876 // +1 because AddRange implementation requires [low,high)
3877 uint64_t block_high = largest_acked + 1;
3878 uint64_t block_low = largest_acked - ack_block_value;
3879
3880 // ack_block_value is the number of packets preceding the
3881 // largest_acked packet which are in the block being acked. Thus,
3882 // its maximum value is largest_acked-1. Test this, reporting an
3883 // error if the value is wrong.
3884 if (ack_block_value + first_sending_packet_number_.ToUint64() >
3885 largest_acked) {
dmcardlecf0bfcf2019-12-13 08:08:21 -08003886 set_detailed_error(
3887 quiche::QuicheStrCat("Underflow with first ack block length ",
3888 ack_block_value + 1, " largest acked is ",
3889 largest_acked, ".")
3890 .c_str());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003891 return false;
3892 }
3893
3894 if (!visitor_->OnAckRange(QuicPacketNumber(block_low),
3895 QuicPacketNumber(block_high))) {
3896 // The visitor suppresses further processing of the packet. Although
3897 // this is not a parsing error, returns false as this is in middle
3898 // of processing an ACK frame.
3899 set_detailed_error("Visitor suppresses further processing of ACK frame.");
3900 return false;
3901 }
3902
3903 while (ack_block_count != 0) {
3904 uint64_t gap_block_value;
3905 // Get the sizes of the gap and ack blocks,
3906 if (!reader->ReadVarInt62(&gap_block_value)) {
3907 set_detailed_error("Unable to read gap block value.");
3908 return false;
3909 }
3910 // It's an error if the gap is larger than the space from packet
3911 // number 0 to the start of the block that's just been acked, PLUS
3912 // there must be space for at least 1 packet to be acked. For
3913 // example, if block_low is 10 and gap_block_value is 9, it means
3914 // the gap block is 10 packets long, leaving no room for a packet
3915 // to be acked. Thus, gap_block_value+2 can not be larger than
3916 // block_low.
3917 // The test is written this way to detect wrap-arounds.
3918 if ((gap_block_value + 2) > block_low) {
3919 set_detailed_error(
dmcardlecf0bfcf2019-12-13 08:08:21 -08003920 quiche::QuicheStrCat("Underflow with gap block length ",
3921 gap_block_value + 1,
3922 " previous ack block start is ", block_low, ".")
QUICHE teama6ef0a62019-03-07 20:34:33 -05003923 .c_str());
3924 return false;
3925 }
3926
3927 // Adjust block_high to be the top of the next ack block.
3928 // There is a gap of |gap_block_value| packets between the bottom
3929 // of ack block N and top of block N+1. Note that gap_block_value
3930 // is he size of the gap minus 1 (per the QUIC protocol), and
3931 // block_high is the packet number of the first packet of the gap
3932 // (per the implementation of OnAckRange/AddAckRange, below).
3933 block_high = block_low - 1 - gap_block_value;
3934
3935 if (!reader->ReadVarInt62(&ack_block_value)) {
3936 set_detailed_error("Unable to read ack block value.");
3937 return false;
3938 }
3939 if (ack_block_value + first_sending_packet_number_.ToUint64() >
3940 (block_high - 1)) {
3941 set_detailed_error(
dmcardlecf0bfcf2019-12-13 08:08:21 -08003942 quiche::QuicheStrCat("Underflow with ack block length ",
3943 ack_block_value + 1, " latest ack block end is ",
3944 block_high - 1, ".")
QUICHE teama6ef0a62019-03-07 20:34:33 -05003945 .c_str());
3946 return false;
3947 }
3948 // Calculate the low end of the new nth ack block. The +1 is
3949 // because the encoded value is the blocksize-1.
3950 block_low = block_high - 1 - ack_block_value;
3951 if (!visitor_->OnAckRange(QuicPacketNumber(block_low),
3952 QuicPacketNumber(block_high))) {
3953 // The visitor suppresses further processing of the packet. Although
3954 // this is not a parsing error, returns false as this is in middle
3955 // of processing an ACK frame.
3956 set_detailed_error("Visitor suppresses further processing of ACK frame.");
3957 return false;
3958 }
3959
3960 // Another one done.
3961 ack_block_count--;
3962 }
3963
fayang91c23d72020-03-09 12:35:05 -07003964 if (frame_type == IETF_ACK_ECN) {
3965 ack_frame->ecn_counters_populated = true;
3966 if (!reader->ReadVarInt62(&ack_frame->ect_0_count)) {
3967 set_detailed_error("Unable to read ack ect_0_count.");
3968 return false;
3969 }
3970 if (!reader->ReadVarInt62(&ack_frame->ect_1_count)) {
3971 set_detailed_error("Unable to read ack ect_1_count.");
3972 return false;
3973 }
3974 if (!reader->ReadVarInt62(&ack_frame->ecn_ce_count)) {
3975 set_detailed_error("Unable to read ack ecn_ce_count.");
3976 return false;
3977 }
3978 } else {
3979 ack_frame->ecn_counters_populated = false;
3980 ack_frame->ect_0_count = 0;
3981 ack_frame->ect_1_count = 0;
3982 ack_frame->ecn_ce_count = 0;
3983 }
3984 // TODO(fayang): Report ECN counts to visitor when they are actually used.
fayang533cb1b2020-01-28 08:05:08 -08003985 if (!visitor_->OnAckFrameEnd(QuicPacketNumber(block_low))) {
3986 set_detailed_error(
3987 "Error occurs when visitor finishes processing the ACK frame.");
3988 return false;
3989 }
3990
3991 return true;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003992}
3993
3994bool QuicFramer::ProcessStopWaitingFrame(QuicDataReader* reader,
3995 const QuicPacketHeader& header,
3996 QuicStopWaitingFrame* stop_waiting) {
3997 uint64_t least_unacked_delta;
3998 if (!reader->ReadBytesToUInt64(header.packet_number_length,
3999 &least_unacked_delta)) {
4000 set_detailed_error("Unable to read least unacked delta.");
4001 return false;
4002 }
4003 if (header.packet_number.ToUint64() <= least_unacked_delta) {
4004 set_detailed_error("Invalid unacked delta.");
4005 return false;
4006 }
4007 stop_waiting->least_unacked = header.packet_number - least_unacked_delta;
4008
4009 return true;
4010}
4011
4012bool QuicFramer::ProcessRstStreamFrame(QuicDataReader* reader,
4013 QuicRstStreamFrame* frame) {
4014 if (!reader->ReadUInt32(&frame->stream_id)) {
4015 set_detailed_error("Unable to read stream_id.");
4016 return false;
4017 }
4018
4019 if (!reader->ReadUInt64(&frame->byte_offset)) {
4020 set_detailed_error("Unable to read rst stream sent byte offset.");
4021 return false;
4022 }
4023
4024 uint32_t error_code;
4025 if (!reader->ReadUInt32(&error_code)) {
4026 set_detailed_error("Unable to read rst stream error code.");
4027 return false;
4028 }
4029
4030 if (error_code >= QUIC_STREAM_LAST_ERROR) {
4031 // Ignore invalid stream error code if any.
4032 error_code = QUIC_STREAM_LAST_ERROR;
4033 }
4034
4035 frame->error_code = static_cast<QuicRstStreamErrorCode>(error_code);
4036
4037 return true;
4038}
4039
4040bool QuicFramer::ProcessConnectionCloseFrame(QuicDataReader* reader,
4041 QuicConnectionCloseFrame* frame) {
4042 uint32_t error_code;
fkastenholze9d71a82019-04-09 05:12:13 -07004043 frame->close_type = GOOGLE_QUIC_CONNECTION_CLOSE;
4044
QUICHE teama6ef0a62019-03-07 20:34:33 -05004045 if (!reader->ReadUInt32(&error_code)) {
4046 set_detailed_error("Unable to read connection close error code.");
4047 return false;
4048 }
4049
4050 if (error_code >= QUIC_LAST_ERROR) {
4051 // Ignore invalid QUIC error code if any.
4052 error_code = QUIC_LAST_ERROR;
4053 }
4054
bnc77e77b82020-04-05 10:36:49 -07004055 // For Google QUIC connection closes, |wire_error_code| and |quic_error_code|
4056 // must have the same value.
4057 frame->wire_error_code = error_code;
fkastenholze9d71a82019-04-09 05:12:13 -07004058 frame->quic_error_code = static_cast<QuicErrorCode>(error_code);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004059
dmcardlecf0bfcf2019-12-13 08:08:21 -08004060 quiche::QuicheStringPiece error_details;
QUICHE teama6ef0a62019-03-07 20:34:33 -05004061 if (!reader->ReadStringPiece16(&error_details)) {
4062 set_detailed_error("Unable to read connection close error details.");
4063 return false;
4064 }
vasilvvc48c8712019-03-11 13:38:16 -07004065 frame->error_details = std::string(error_details);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004066
4067 return true;
4068}
4069
4070bool QuicFramer::ProcessGoAwayFrame(QuicDataReader* reader,
4071 QuicGoAwayFrame* frame) {
4072 uint32_t error_code;
4073 if (!reader->ReadUInt32(&error_code)) {
4074 set_detailed_error("Unable to read go away error code.");
4075 return false;
4076 }
4077
4078 if (error_code >= QUIC_LAST_ERROR) {
4079 // Ignore invalid QUIC error code if any.
4080 error_code = QUIC_LAST_ERROR;
4081 }
4082 frame->error_code = static_cast<QuicErrorCode>(error_code);
4083
4084 uint32_t stream_id;
4085 if (!reader->ReadUInt32(&stream_id)) {
4086 set_detailed_error("Unable to read last good stream id.");
4087 return false;
4088 }
4089 frame->last_good_stream_id = static_cast<QuicStreamId>(stream_id);
4090
dmcardlecf0bfcf2019-12-13 08:08:21 -08004091 quiche::QuicheStringPiece reason_phrase;
QUICHE teama6ef0a62019-03-07 20:34:33 -05004092 if (!reader->ReadStringPiece16(&reason_phrase)) {
4093 set_detailed_error("Unable to read goaway reason.");
4094 return false;
4095 }
vasilvvc48c8712019-03-11 13:38:16 -07004096 frame->reason_phrase = std::string(reason_phrase);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004097
4098 return true;
4099}
4100
4101bool QuicFramer::ProcessWindowUpdateFrame(QuicDataReader* reader,
4102 QuicWindowUpdateFrame* frame) {
4103 if (!reader->ReadUInt32(&frame->stream_id)) {
4104 set_detailed_error("Unable to read stream_id.");
4105 return false;
4106 }
4107
renjietangd088eab2019-11-21 14:54:41 -08004108 if (!reader->ReadUInt64(&frame->max_data)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05004109 set_detailed_error("Unable to read window byte_offset.");
4110 return false;
4111 }
4112
4113 return true;
4114}
4115
4116bool QuicFramer::ProcessBlockedFrame(QuicDataReader* reader,
4117 QuicBlockedFrame* frame) {
fkastenholz305e1732019-06-18 05:01:22 -07004118 DCHECK(!VersionHasIetfQuicFrames(version_.transport_version))
4119 << "Attempt to process non-IETF QUIC frames in an IETF QUIC version.";
QUICHE teama6ef0a62019-03-07 20:34:33 -05004120
4121 if (!reader->ReadUInt32(&frame->stream_id)) {
4122 set_detailed_error("Unable to read stream_id.");
4123 return false;
4124 }
4125
4126 return true;
4127}
4128
4129void QuicFramer::ProcessPaddingFrame(QuicDataReader* reader,
4130 QuicPaddingFrame* frame) {
4131 // Type byte has been read.
4132 frame->num_padding_bytes = 1;
4133 uint8_t next_byte;
4134 while (!reader->IsDoneReading() && reader->PeekByte() == 0x00) {
4135 reader->ReadBytes(&next_byte, 1);
4136 DCHECK_EQ(0x00, next_byte);
4137 ++frame->num_padding_bytes;
4138 }
4139}
4140
4141bool QuicFramer::ProcessMessageFrame(QuicDataReader* reader,
4142 bool no_message_length,
4143 QuicMessageFrame* frame) {
4144 if (no_message_length) {
dmcardlecf0bfcf2019-12-13 08:08:21 -08004145 quiche::QuicheStringPiece remaining(reader->ReadRemainingPayload());
QUICHE teama6ef0a62019-03-07 20:34:33 -05004146 frame->data = remaining.data();
4147 frame->message_length = remaining.length();
4148 return true;
4149 }
4150
4151 uint64_t message_length;
4152 if (!reader->ReadVarInt62(&message_length)) {
4153 set_detailed_error("Unable to read message length");
4154 return false;
4155 }
4156
dmcardlecf0bfcf2019-12-13 08:08:21 -08004157 quiche::QuicheStringPiece message_piece;
QUICHE teama6ef0a62019-03-07 20:34:33 -05004158 if (!reader->ReadStringPiece(&message_piece, message_length)) {
4159 set_detailed_error("Unable to read message data");
4160 return false;
4161 }
4162
4163 frame->data = message_piece.data();
4164 frame->message_length = message_length;
4165
4166 return true;
4167}
4168
4169// static
dmcardlecf0bfcf2019-12-13 08:08:21 -08004170quiche::QuicheStringPiece QuicFramer::GetAssociatedDataFromEncryptedPacket(
QUICHE teama6ef0a62019-03-07 20:34:33 -05004171 QuicTransportVersion version,
4172 const QuicEncryptedPacket& encrypted,
4173 QuicConnectionIdLength destination_connection_id_length,
4174 QuicConnectionIdLength source_connection_id_length,
4175 bool includes_version,
4176 bool includes_diversification_nonce,
4177 QuicPacketNumberLength packet_number_length,
4178 QuicVariableLengthIntegerLength retry_token_length_length,
4179 uint64_t retry_token_length,
4180 QuicVariableLengthIntegerLength length_length) {
4181 // TODO(ianswett): This is identical to QuicData::AssociatedData.
dmcardlecf0bfcf2019-12-13 08:08:21 -08004182 return quiche::QuicheStringPiece(
QUICHE teama6ef0a62019-03-07 20:34:33 -05004183 encrypted.data(),
4184 GetStartOfEncryptedData(version, destination_connection_id_length,
4185 source_connection_id_length, includes_version,
4186 includes_diversification_nonce,
4187 packet_number_length, retry_token_length_length,
4188 retry_token_length, length_length));
4189}
4190
4191void QuicFramer::SetDecrypter(EncryptionLevel level,
4192 std::unique_ptr<QuicDecrypter> decrypter) {
QUICHE team76086e42019-03-25 15:12:29 -07004193 DCHECK_EQ(alternative_decrypter_level_, NUM_ENCRYPTION_LEVELS);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004194 DCHECK_GE(level, decrypter_level_);
zhongyi546cc452019-04-12 15:27:49 -07004195 DCHECK(!version_.KnowsWhichDecrypterToUse());
dschinazi4b5a68a2019-08-15 15:45:36 -07004196 QUIC_DVLOG(1) << ENDPOINT << "Setting decrypter from level "
renjietangb4ebb1d2020-05-27 18:15:51 -07004197 << decrypter_level_ << " to " << level;
QUICHE team76086e42019-03-25 15:12:29 -07004198 decrypter_[decrypter_level_] = nullptr;
4199 decrypter_[level] = std::move(decrypter);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004200 decrypter_level_ = level;
4201}
4202
4203void QuicFramer::SetAlternativeDecrypter(
4204 EncryptionLevel level,
4205 std::unique_ptr<QuicDecrypter> decrypter,
4206 bool latch_once_used) {
QUICHE team76086e42019-03-25 15:12:29 -07004207 DCHECK_NE(level, decrypter_level_);
zhongyi546cc452019-04-12 15:27:49 -07004208 DCHECK(!version_.KnowsWhichDecrypterToUse());
dschinazi4b5a68a2019-08-15 15:45:36 -07004209 QUIC_DVLOG(1) << ENDPOINT << "Setting alternative decrypter from level "
renjietangb4ebb1d2020-05-27 18:15:51 -07004210 << alternative_decrypter_level_ << " to " << level;
QUICHE team76086e42019-03-25 15:12:29 -07004211 if (alternative_decrypter_level_ != NUM_ENCRYPTION_LEVELS) {
4212 decrypter_[alternative_decrypter_level_] = nullptr;
4213 }
4214 decrypter_[level] = std::move(decrypter);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004215 alternative_decrypter_level_ = level;
4216 alternative_decrypter_latch_ = latch_once_used;
4217}
4218
zhongyi546cc452019-04-12 15:27:49 -07004219void QuicFramer::InstallDecrypter(EncryptionLevel level,
4220 std::unique_ptr<QuicDecrypter> decrypter) {
4221 DCHECK(version_.KnowsWhichDecrypterToUse());
renjietangb4ebb1d2020-05-27 18:15:51 -07004222 QUIC_DVLOG(1) << ENDPOINT << "Installing decrypter at level " << level;
zhongyi546cc452019-04-12 15:27:49 -07004223 decrypter_[level] = std::move(decrypter);
4224}
4225
4226void QuicFramer::RemoveDecrypter(EncryptionLevel level) {
4227 DCHECK(version_.KnowsWhichDecrypterToUse());
renjietangb4ebb1d2020-05-27 18:15:51 -07004228 QUIC_DVLOG(1) << ENDPOINT << "Removing decrypter at level " << level;
zhongyi546cc452019-04-12 15:27:49 -07004229 decrypter_[level] = nullptr;
4230}
4231
4232const QuicDecrypter* QuicFramer::GetDecrypter(EncryptionLevel level) const {
4233 DCHECK(version_.KnowsWhichDecrypterToUse());
4234 return decrypter_[level].get();
4235}
4236
QUICHE teama6ef0a62019-03-07 20:34:33 -05004237const QuicDecrypter* QuicFramer::decrypter() const {
QUICHE team76086e42019-03-25 15:12:29 -07004238 return decrypter_[decrypter_level_].get();
QUICHE teama6ef0a62019-03-07 20:34:33 -05004239}
4240
4241const QuicDecrypter* QuicFramer::alternative_decrypter() const {
QUICHE team76086e42019-03-25 15:12:29 -07004242 if (alternative_decrypter_level_ == NUM_ENCRYPTION_LEVELS) {
4243 return nullptr;
4244 }
4245 return decrypter_[alternative_decrypter_level_].get();
QUICHE teama6ef0a62019-03-07 20:34:33 -05004246}
4247
4248void QuicFramer::SetEncrypter(EncryptionLevel level,
4249 std::unique_ptr<QuicEncrypter> encrypter) {
4250 DCHECK_GE(level, 0);
4251 DCHECK_LT(level, NUM_ENCRYPTION_LEVELS);
renjietangb4ebb1d2020-05-27 18:15:51 -07004252 QUIC_DVLOG(1) << ENDPOINT << "Setting encrypter at level " << level;
QUICHE teama6ef0a62019-03-07 20:34:33 -05004253 encrypter_[level] = std::move(encrypter);
4254}
4255
fayangb296fb82020-02-11 08:14:28 -08004256void QuicFramer::RemoveEncrypter(EncryptionLevel level) {
renjietangb4ebb1d2020-05-27 18:15:51 -07004257 QUIC_DVLOG(1) << ENDPOINT << "Removing encrypter of " << level;
fayangb296fb82020-02-11 08:14:28 -08004258 encrypter_[level] = nullptr;
4259}
4260
nharper4a5a76c2019-09-13 13:44:37 -07004261void QuicFramer::SetInitialObfuscators(QuicConnectionId connection_id) {
4262 CrypterPair crypters;
4263 CryptoUtils::CreateInitialObfuscators(perspective_, version_, connection_id,
4264 &crypters);
4265 encrypter_[ENCRYPTION_INITIAL] = std::move(crypters.encrypter);
4266 decrypter_[ENCRYPTION_INITIAL] = std::move(crypters.decrypter);
4267}
4268
QUICHE teama6ef0a62019-03-07 20:34:33 -05004269size_t QuicFramer::EncryptInPlace(EncryptionLevel level,
4270 QuicPacketNumber packet_number,
4271 size_t ad_len,
4272 size_t total_len,
4273 size_t buffer_len,
4274 char* buffer) {
4275 DCHECK(packet_number.IsInitialized());
dschinazi2c5386e2019-04-16 16:37:37 -07004276 if (encrypter_[level] == nullptr) {
4277 QUIC_BUG << ENDPOINT
4278 << "Attempted to encrypt in place without encrypter at level "
renjietangb4ebb1d2020-05-27 18:15:51 -07004279 << level;
dschinazi2c5386e2019-04-16 16:37:37 -07004280 RaiseError(QUIC_ENCRYPTION_FAILURE);
4281 return 0;
4282 }
4283
QUICHE teama6ef0a62019-03-07 20:34:33 -05004284 size_t output_length = 0;
4285 if (!encrypter_[level]->EncryptPacket(
4286 packet_number.ToUint64(),
dmcardlecf0bfcf2019-12-13 08:08:21 -08004287 quiche::QuicheStringPiece(buffer, ad_len), // Associated data
4288 quiche::QuicheStringPiece(buffer + ad_len,
4289 total_len - ad_len), // Plaintext
4290 buffer + ad_len, // Destination buffer
QUICHE teama6ef0a62019-03-07 20:34:33 -05004291 &output_length, buffer_len - ad_len)) {
4292 RaiseError(QUIC_ENCRYPTION_FAILURE);
4293 return 0;
4294 }
nharper55fa6132019-05-07 19:37:21 -07004295 if (version_.HasHeaderProtection() &&
4296 !ApplyHeaderProtection(level, buffer, ad_len + output_length, ad_len)) {
4297 QUIC_DLOG(ERROR) << "Applying header protection failed.";
4298 RaiseError(QUIC_ENCRYPTION_FAILURE);
4299 return 0;
4300 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004301
4302 return ad_len + output_length;
4303}
4304
nharper55fa6132019-05-07 19:37:21 -07004305namespace {
4306
4307const size_t kHPSampleLen = 16;
4308
4309constexpr bool IsLongHeader(uint8_t type_byte) {
4310 return (type_byte & FLAGS_LONG_HEADER) != 0;
4311}
4312
4313} // namespace
4314
4315bool QuicFramer::ApplyHeaderProtection(EncryptionLevel level,
4316 char* buffer,
4317 size_t buffer_len,
4318 size_t ad_len) {
4319 QuicDataReader buffer_reader(buffer, buffer_len);
4320 QuicDataWriter buffer_writer(buffer_len, buffer);
4321 // The sample starts 4 bytes after the start of the packet number.
4322 if (ad_len < last_written_packet_number_length_) {
4323 return false;
4324 }
4325 size_t pn_offset = ad_len - last_written_packet_number_length_;
4326 // Sample the ciphertext and generate the mask to use for header protection.
4327 size_t sample_offset = pn_offset + 4;
4328 QuicDataReader sample_reader(buffer, buffer_len);
dmcardlecf0bfcf2019-12-13 08:08:21 -08004329 quiche::QuicheStringPiece sample;
nharper55fa6132019-05-07 19:37:21 -07004330 if (!sample_reader.Seek(sample_offset) ||
4331 !sample_reader.ReadStringPiece(&sample, kHPSampleLen)) {
4332 QUIC_BUG << "Not enough bytes to sample: sample_offset " << sample_offset
4333 << ", sample len: " << kHPSampleLen
4334 << ", buffer len: " << buffer_len;
4335 return false;
4336 }
4337
dschinazida9fafd2020-03-16 15:32:55 -07004338 if (encrypter_[level] == nullptr) {
4339 QUIC_BUG
4340 << ENDPOINT
4341 << "Attempted to apply header protection without encrypter at level "
renjietangb4ebb1d2020-05-27 18:15:51 -07004342 << level << " using " << version_;
dschinazida9fafd2020-03-16 15:32:55 -07004343 return false;
4344 }
4345
nharper55fa6132019-05-07 19:37:21 -07004346 std::string mask = encrypter_[level]->GenerateHeaderProtectionMask(sample);
4347 if (mask.empty()) {
4348 QUIC_BUG << "Unable to generate header protection mask.";
4349 return false;
4350 }
4351 QuicDataReader mask_reader(mask.data(), mask.size());
4352
4353 // Apply the mask to the 4 or 5 least significant bits of the first byte.
4354 uint8_t bitmask = 0x1f;
4355 uint8_t type_byte;
4356 if (!buffer_reader.ReadUInt8(&type_byte)) {
4357 return false;
4358 }
4359 QuicLongHeaderType header_type;
4360 if (IsLongHeader(type_byte)) {
4361 bitmask = 0x0f;
fayang36825da2019-08-21 14:01:27 -07004362 if (!GetLongHeaderType(type_byte, &header_type)) {
nharper55fa6132019-05-07 19:37:21 -07004363 return false;
4364 }
4365 }
4366 uint8_t mask_byte;
4367 if (!mask_reader.ReadUInt8(&mask_byte) ||
4368 !buffer_writer.WriteUInt8(type_byte ^ (mask_byte & bitmask))) {
4369 return false;
4370 }
4371
4372 // Adjust |pn_offset| to account for the diversification nonce.
4373 if (IsLongHeader(type_byte) && header_type == ZERO_RTT_PROTECTED &&
4374 perspective_ == Perspective::IS_SERVER &&
4375 version_.handshake_protocol == PROTOCOL_QUIC_CRYPTO) {
4376 if (pn_offset <= kDiversificationNonceSize) {
4377 QUIC_BUG << "Expected diversification nonce, but not enough bytes";
4378 return false;
4379 }
4380 pn_offset -= kDiversificationNonceSize;
4381 }
4382 // Advance the reader and writer to the packet number. Both the reader and
4383 // writer have each read/written one byte.
4384 if (!buffer_writer.Seek(pn_offset - 1) ||
4385 !buffer_reader.Seek(pn_offset - 1)) {
4386 return false;
4387 }
4388 // Apply the rest of the mask to the packet number.
4389 for (size_t i = 0; i < last_written_packet_number_length_; ++i) {
4390 uint8_t buffer_byte;
4391 uint8_t mask_byte;
4392 if (!mask_reader.ReadUInt8(&mask_byte) ||
4393 !buffer_reader.ReadUInt8(&buffer_byte) ||
4394 !buffer_writer.WriteUInt8(buffer_byte ^ mask_byte)) {
4395 return false;
4396 }
4397 }
4398 return true;
4399}
4400
4401bool QuicFramer::RemoveHeaderProtection(QuicDataReader* reader,
4402 const QuicEncryptedPacket& packet,
4403 QuicPacketHeader* header,
4404 uint64_t* full_packet_number,
4405 std::vector<char>* associated_data) {
4406 EncryptionLevel expected_decryption_level = GetEncryptionLevel(*header);
4407 QuicDecrypter* decrypter = decrypter_[expected_decryption_level].get();
4408 if (decrypter == nullptr) {
4409 QUIC_DVLOG(1)
dschinazi4b5a68a2019-08-15 15:45:36 -07004410 << ENDPOINT
nharper55fa6132019-05-07 19:37:21 -07004411 << "No decrypter available for removing header protection at level "
renjietangb4ebb1d2020-05-27 18:15:51 -07004412 << expected_decryption_level;
nharper55fa6132019-05-07 19:37:21 -07004413 return false;
4414 }
4415
4416 bool has_diversification_nonce =
4417 header->form == IETF_QUIC_LONG_HEADER_PACKET &&
4418 header->long_packet_type == ZERO_RTT_PROTECTED &&
4419 perspective_ == Perspective::IS_CLIENT &&
4420 version_.handshake_protocol == PROTOCOL_QUIC_CRYPTO;
4421
4422 // Read a sample from the ciphertext and compute the mask to use for header
4423 // protection.
dmcardlecf0bfcf2019-12-13 08:08:21 -08004424 quiche::QuicheStringPiece remaining_packet = reader->PeekRemainingPayload();
nharper55fa6132019-05-07 19:37:21 -07004425 QuicDataReader sample_reader(remaining_packet);
4426
4427 // The sample starts 4 bytes after the start of the packet number.
dmcardlecf0bfcf2019-12-13 08:08:21 -08004428 quiche::QuicheStringPiece pn;
nharper55fa6132019-05-07 19:37:21 -07004429 if (!sample_reader.ReadStringPiece(&pn, 4)) {
4430 QUIC_DVLOG(1) << "Not enough data to sample";
4431 return false;
4432 }
4433 if (has_diversification_nonce) {
4434 // In Google QUIC, the diversification nonce comes between the packet number
4435 // and the sample.
4436 if (!sample_reader.Seek(kDiversificationNonceSize)) {
4437 QUIC_DVLOG(1) << "No diversification nonce to skip over";
4438 return false;
4439 }
4440 }
4441 std::string mask = decrypter->GenerateHeaderProtectionMask(&sample_reader);
4442 QuicDataReader mask_reader(mask.data(), mask.size());
4443 if (mask.empty()) {
4444 QUIC_DVLOG(1) << "Failed to compute mask";
4445 return false;
4446 }
4447
4448 // Unmask the rest of the type byte.
4449 uint8_t bitmask = 0x1f;
4450 if (IsLongHeader(header->type_byte)) {
4451 bitmask = 0x0f;
4452 }
4453 uint8_t mask_byte;
4454 if (!mask_reader.ReadUInt8(&mask_byte)) {
4455 QUIC_DVLOG(1) << "No first byte to read from mask";
4456 return false;
4457 }
4458 header->type_byte ^= (mask_byte & bitmask);
4459
4460 // Compute the packet number length.
4461 header->packet_number_length =
4462 static_cast<QuicPacketNumberLength>((header->type_byte & 0x03) + 1);
4463
4464 char pn_buffer[IETF_MAX_PACKET_NUMBER_LENGTH] = {};
bnc4e9283d2019-12-17 07:08:57 -08004465 QuicDataWriter pn_writer(QUICHE_ARRAYSIZE(pn_buffer), pn_buffer);
nharper55fa6132019-05-07 19:37:21 -07004466
4467 // Read the (protected) packet number from the reader and unmask the packet
4468 // number.
4469 for (size_t i = 0; i < header->packet_number_length; ++i) {
4470 uint8_t protected_pn_byte, mask_byte;
4471 if (!mask_reader.ReadUInt8(&mask_byte) ||
4472 !reader->ReadUInt8(&protected_pn_byte) ||
4473 !pn_writer.WriteUInt8(protected_pn_byte ^ mask_byte)) {
4474 QUIC_DVLOG(1) << "Failed to unmask packet number";
4475 return false;
4476 }
4477 }
4478 QuicDataReader packet_number_reader(pn_writer.data(), pn_writer.length());
4479 QuicPacketNumber base_packet_number;
4480 if (supports_multiple_packet_number_spaces_) {
4481 PacketNumberSpace pn_space = GetPacketNumberSpace(*header);
4482 if (pn_space == NUM_PACKET_NUMBER_SPACES) {
4483 return false;
4484 }
4485 base_packet_number = largest_decrypted_packet_numbers_[pn_space];
4486 } else {
4487 base_packet_number = largest_packet_number_;
4488 }
4489 if (!ProcessAndCalculatePacketNumber(
4490 &packet_number_reader, header->packet_number_length,
4491 base_packet_number, full_packet_number)) {
4492 return false;
4493 }
4494
4495 // Get the associated data, and apply the same unmasking operations to it.
dmcardlecf0bfcf2019-12-13 08:08:21 -08004496 quiche::QuicheStringPiece ad = GetAssociatedDataFromEncryptedPacket(
nharper55fa6132019-05-07 19:37:21 -07004497 version_.transport_version, packet,
4498 GetIncludedDestinationConnectionIdLength(*header),
4499 GetIncludedSourceConnectionIdLength(*header), header->version_flag,
4500 has_diversification_nonce, header->packet_number_length,
4501 header->retry_token_length_length, header->retry_token.length(),
4502 header->length_length);
4503 *associated_data = std::vector<char>(ad.begin(), ad.end());
4504 QuicDataWriter ad_writer(associated_data->size(), associated_data->data());
4505
4506 // Apply the unmasked type byte and packet number to |associated_data|.
4507 if (!ad_writer.WriteUInt8(header->type_byte)) {
4508 return false;
4509 }
4510 // Put the packet number at the end of the AD, or if there's a diversification
4511 // nonce, before that (which is at the end of the AD).
4512 size_t seek_len = ad_writer.remaining() - header->packet_number_length;
4513 if (has_diversification_nonce) {
4514 seek_len -= kDiversificationNonceSize;
4515 }
4516 if (!ad_writer.Seek(seek_len) ||
4517 !ad_writer.WriteBytes(pn_writer.data(), pn_writer.length())) {
4518 QUIC_DVLOG(1) << "Failed to apply unmasking operations to AD";
4519 return false;
4520 }
4521
4522 return true;
4523}
4524
QUICHE teama6ef0a62019-03-07 20:34:33 -05004525size_t QuicFramer::EncryptPayload(EncryptionLevel level,
4526 QuicPacketNumber packet_number,
4527 const QuicPacket& packet,
4528 char* buffer,
4529 size_t buffer_len) {
4530 DCHECK(packet_number.IsInitialized());
dschinazi2c5386e2019-04-16 16:37:37 -07004531 if (encrypter_[level] == nullptr) {
4532 QUIC_BUG << ENDPOINT << "Attempted to encrypt without encrypter at level "
renjietangb4ebb1d2020-05-27 18:15:51 -07004533 << level;
dschinazi2c5386e2019-04-16 16:37:37 -07004534 RaiseError(QUIC_ENCRYPTION_FAILURE);
4535 return 0;
4536 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004537
dmcardlecf0bfcf2019-12-13 08:08:21 -08004538 quiche::QuicheStringPiece associated_data =
QUICHE teama6ef0a62019-03-07 20:34:33 -05004539 packet.AssociatedData(version_.transport_version);
4540 // Copy in the header, because the encrypter only populates the encrypted
4541 // plaintext content.
4542 const size_t ad_len = associated_data.length();
wubdec17c22020-06-04 13:13:50 -07004543 if (packet.length() < ad_len) {
4544 QUIC_BUG << ENDPOINT
4545 << "packet is shorter than associated data length. version:"
4546 << version() << ", packet length:" << packet.length()
4547 << ", associated data length:" << ad_len;
4548 RaiseError(QUIC_ENCRYPTION_FAILURE);
4549 return 0;
4550 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004551 memmove(buffer, associated_data.data(), ad_len);
4552 // Encrypt the plaintext into the buffer.
4553 size_t output_length = 0;
4554 if (!encrypter_[level]->EncryptPacket(
4555 packet_number.ToUint64(), associated_data,
4556 packet.Plaintext(version_.transport_version), buffer + ad_len,
4557 &output_length, buffer_len - ad_len)) {
4558 RaiseError(QUIC_ENCRYPTION_FAILURE);
4559 return 0;
4560 }
nharper55fa6132019-05-07 19:37:21 -07004561 if (version_.HasHeaderProtection() &&
4562 !ApplyHeaderProtection(level, buffer, ad_len + output_length, ad_len)) {
4563 QUIC_DLOG(ERROR) << "Applying header protection failed.";
4564 RaiseError(QUIC_ENCRYPTION_FAILURE);
4565 return 0;
4566 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004567
4568 return ad_len + output_length;
4569}
4570
4571size_t QuicFramer::GetCiphertextSize(EncryptionLevel level,
4572 size_t plaintext_size) const {
dschinazida9fafd2020-03-16 15:32:55 -07004573 if (encrypter_[level] == nullptr) {
4574 QUIC_BUG << ENDPOINT
4575 << "Attempted to get ciphertext size without encrypter at level "
renjietangb4ebb1d2020-05-27 18:15:51 -07004576 << level << " using " << version_;
dschinazida9fafd2020-03-16 15:32:55 -07004577 return plaintext_size;
4578 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004579 return encrypter_[level]->GetCiphertextSize(plaintext_size);
4580}
4581
4582size_t QuicFramer::GetMaxPlaintextSize(size_t ciphertext_size) {
4583 // In order to keep the code simple, we don't have the current encryption
4584 // level to hand. Both the NullEncrypter and AES-GCM have a tag length of 12.
4585 size_t min_plaintext_size = ciphertext_size;
4586
QUICHE team6987b4a2019-03-15 16:23:04 -07004587 for (int i = ENCRYPTION_INITIAL; i < NUM_ENCRYPTION_LEVELS; i++) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05004588 if (encrypter_[i] != nullptr) {
4589 size_t size = encrypter_[i]->GetMaxPlaintextSize(ciphertext_size);
4590 if (size < min_plaintext_size) {
4591 min_plaintext_size = size;
4592 }
4593 }
4594 }
4595
4596 return min_plaintext_size;
4597}
4598
dmcardlecf0bfcf2019-12-13 08:08:21 -08004599bool QuicFramer::DecryptPayload(quiche::QuicheStringPiece encrypted,
4600 quiche::QuicheStringPiece associated_data,
QUICHE teama6ef0a62019-03-07 20:34:33 -05004601 const QuicPacketHeader& header,
4602 char* decrypted_buffer,
4603 size_t buffer_length,
QUICHE team10b22a12019-03-21 15:31:42 -07004604 size_t* decrypted_length,
4605 EncryptionLevel* decrypted_level) {
nharper855d2172019-05-02 16:17:46 -07004606 if (!EncryptionLevelIsValid(decrypter_level_)) {
4607 QUIC_BUG << "Attempted to decrypt with bad decrypter_level_";
4608 return false;
4609 }
zhongyi546cc452019-04-12 15:27:49 -07004610 EncryptionLevel level = decrypter_level_;
4611 QuicDecrypter* decrypter = decrypter_[level].get();
QUICHE team76086e42019-03-25 15:12:29 -07004612 QuicDecrypter* alternative_decrypter = nullptr;
zhongyi546cc452019-04-12 15:27:49 -07004613 if (version().KnowsWhichDecrypterToUse()) {
nharper855d2172019-05-02 16:17:46 -07004614 if (header.form == GOOGLE_QUIC_PACKET) {
4615 QUIC_BUG << "Attempted to decrypt GOOGLE_QUIC_PACKET with a version that "
4616 "knows which decrypter to use";
4617 return false;
4618 }
zhongyi546cc452019-04-12 15:27:49 -07004619 level = GetEncryptionLevel(header);
nharper855d2172019-05-02 16:17:46 -07004620 if (!EncryptionLevelIsValid(level)) {
4621 QUIC_BUG << "Attempted to decrypt with bad level";
4622 return false;
4623 }
zhongyi546cc452019-04-12 15:27:49 -07004624 decrypter = decrypter_[level].get();
4625 if (decrypter == nullptr) {
4626 return false;
4627 }
4628 if (level == ENCRYPTION_ZERO_RTT &&
4629 perspective_ == Perspective::IS_CLIENT && header.nonce != nullptr) {
4630 decrypter->SetDiversificationNonce(*header.nonce);
4631 }
4632 } else if (alternative_decrypter_level_ != NUM_ENCRYPTION_LEVELS) {
nharper855d2172019-05-02 16:17:46 -07004633 if (!EncryptionLevelIsValid(alternative_decrypter_level_)) {
4634 QUIC_BUG << "Attempted to decrypt with bad alternative_decrypter_level_";
4635 return false;
4636 }
QUICHE team76086e42019-03-25 15:12:29 -07004637 alternative_decrypter = decrypter_[alternative_decrypter_level_].get();
4638 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004639
nharper855d2172019-05-02 16:17:46 -07004640 if (decrypter == nullptr) {
ianswettf919fb22019-05-13 06:42:11 -07004641 QUIC_BUG << "Attempting to decrypt without decrypter, encryption level:"
4642 << level << " version:" << version();
nharper855d2172019-05-02 16:17:46 -07004643 return false;
4644 }
zhongyi546cc452019-04-12 15:27:49 -07004645
4646 bool success = decrypter->DecryptPacket(
QUICHE teama6ef0a62019-03-07 20:34:33 -05004647 header.packet_number.ToUint64(), associated_data, encrypted,
4648 decrypted_buffer, decrypted_length, buffer_length);
4649 if (success) {
zhongyi546cc452019-04-12 15:27:49 -07004650 visitor_->OnDecryptedPacket(level);
4651 *decrypted_level = level;
QUICHE team76086e42019-03-25 15:12:29 -07004652 } else if (alternative_decrypter != nullptr) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05004653 if (header.nonce != nullptr) {
4654 DCHECK_EQ(perspective_, Perspective::IS_CLIENT);
QUICHE team76086e42019-03-25 15:12:29 -07004655 alternative_decrypter->SetDiversificationNonce(*header.nonce);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004656 }
4657 bool try_alternative_decryption = true;
4658 if (alternative_decrypter_level_ == ENCRYPTION_ZERO_RTT) {
4659 if (perspective_ == Perspective::IS_CLIENT) {
4660 if (header.nonce == nullptr) {
4661 // Can not use INITIAL decryption without a diversification nonce.
4662 try_alternative_decryption = false;
4663 }
4664 } else {
4665 DCHECK(header.nonce == nullptr);
4666 }
4667 }
4668
4669 if (try_alternative_decryption) {
QUICHE team76086e42019-03-25 15:12:29 -07004670 success = alternative_decrypter->DecryptPacket(
QUICHE teama6ef0a62019-03-07 20:34:33 -05004671 header.packet_number.ToUint64(), associated_data, encrypted,
4672 decrypted_buffer, decrypted_length, buffer_length);
4673 }
4674 if (success) {
4675 visitor_->OnDecryptedPacket(alternative_decrypter_level_);
QUICHE team10b22a12019-03-21 15:31:42 -07004676 *decrypted_level = decrypter_level_;
QUICHE teama6ef0a62019-03-07 20:34:33 -05004677 if (alternative_decrypter_latch_) {
nharper855d2172019-05-02 16:17:46 -07004678 if (!EncryptionLevelIsValid(alternative_decrypter_level_)) {
4679 QUIC_BUG << "Attempted to latch alternate decrypter with bad "
4680 "alternative_decrypter_level_";
4681 return false;
4682 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004683 // Switch to the alternative decrypter and latch so that we cannot
4684 // switch back.
QUICHE teama6ef0a62019-03-07 20:34:33 -05004685 decrypter_level_ = alternative_decrypter_level_;
QUICHE team76086e42019-03-25 15:12:29 -07004686 alternative_decrypter_level_ = NUM_ENCRYPTION_LEVELS;
QUICHE teama6ef0a62019-03-07 20:34:33 -05004687 } else {
4688 // Switch the alternative decrypter so that we use it first next time.
QUICHE teama6ef0a62019-03-07 20:34:33 -05004689 EncryptionLevel level = alternative_decrypter_level_;
4690 alternative_decrypter_level_ = decrypter_level_;
4691 decrypter_level_ = level;
4692 }
4693 }
4694 }
4695
4696 if (!success) {
dschinazi965ce092019-05-23 06:29:01 -07004697 QUIC_DVLOG(1) << ENDPOINT << "DecryptPacket failed for: " << header;
QUICHE teama6ef0a62019-03-07 20:34:33 -05004698 return false;
4699 }
4700
4701 return true;
4702}
4703
4704size_t QuicFramer::GetIetfAckFrameSize(const QuicAckFrame& frame) {
4705 // Type byte, largest_acked, and delay_time are straight-forward.
4706 size_t ack_frame_size = kQuicFrameTypeSize;
4707 QuicPacketNumber largest_acked = LargestAcked(frame);
4708 ack_frame_size += QuicDataWriter::GetVarInt62Len(largest_acked.ToUint64());
4709 uint64_t ack_delay_time_us;
4710 ack_delay_time_us = frame.ack_delay_time.ToMicroseconds();
fkastenholz4dc4ba32019-07-30 09:55:25 -07004711 ack_delay_time_us = ack_delay_time_us >> local_ack_delay_exponent_;
QUICHE teama6ef0a62019-03-07 20:34:33 -05004712 ack_frame_size += QuicDataWriter::GetVarInt62Len(ack_delay_time_us);
4713
fayang91c23d72020-03-09 12:35:05 -07004714 if (frame.packets.Empty() || frame.packets.Max() != largest_acked) {
4715 QUIC_BUG << "Malformed ack frame";
4716 // ACK frame serialization will fail and connection will be closed.
4717 return ack_frame_size;
4718 }
4719
4720 // Ack block count.
4721 ack_frame_size +=
4722 QuicDataWriter::GetVarInt62Len(frame.packets.NumIntervals() - 1);
4723
4724 // First Ack range.
4725 auto iter = frame.packets.rbegin();
4726 ack_frame_size += QuicDataWriter::GetVarInt62Len(iter->Length() - 1);
4727 QuicPacketNumber previous_smallest = iter->min();
4728 ++iter;
4729
4730 // Ack blocks.
4731 for (; iter != frame.packets.rend(); ++iter) {
4732 const uint64_t gap = previous_smallest - iter->max() - 1;
4733 const uint64_t ack_range = iter->Length() - 1;
4734 ack_frame_size += (QuicDataWriter::GetVarInt62Len(gap) +
4735 QuicDataWriter::GetVarInt62Len(ack_range));
4736 previous_smallest = iter->min();
4737 }
4738
4739 // ECN counts.
QUICHE teama6ef0a62019-03-07 20:34:33 -05004740 if (frame.ecn_counters_populated &&
4741 (frame.ect_0_count || frame.ect_1_count || frame.ecn_ce_count)) {
4742 ack_frame_size += QuicDataWriter::GetVarInt62Len(frame.ect_0_count);
4743 ack_frame_size += QuicDataWriter::GetVarInt62Len(frame.ect_1_count);
4744 ack_frame_size += QuicDataWriter::GetVarInt62Len(frame.ecn_ce_count);
4745 }
4746
QUICHE teama6ef0a62019-03-07 20:34:33 -05004747 return ack_frame_size;
4748}
4749
4750size_t QuicFramer::GetAckFrameSize(
4751 const QuicAckFrame& ack,
dschinazi17d42422019-06-18 16:35:07 -07004752 QuicPacketNumberLength /*packet_number_length*/) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05004753 DCHECK(!ack.packets.Empty());
4754 size_t ack_size = 0;
4755
fkastenholz305e1732019-06-18 05:01:22 -07004756 if (VersionHasIetfQuicFrames(version_.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05004757 return GetIetfAckFrameSize(ack);
4758 }
4759 AckFrameInfo ack_info = GetAckFrameInfo(ack);
renjietang488201d2019-12-17 13:40:49 -08004760 QuicPacketNumberLength ack_block_length =
4761 GetMinPacketNumberLength(QuicPacketNumber(ack_info.max_block_length));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004762
fayang43697fd2020-04-21 11:13:43 -07004763 ack_size = GetMinAckFrameSize(version_.transport_version, ack,
4764 local_ack_delay_exponent_);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004765 // First ack block length.
4766 ack_size += ack_block_length;
4767 if (ack_info.num_ack_blocks != 0) {
4768 ack_size += kNumberOfAckBlocksSize;
4769 ack_size += std::min(ack_info.num_ack_blocks, kMaxAckBlocks) *
4770 (ack_block_length + PACKET_1BYTE_PACKET_NUMBER);
4771 }
4772
4773 // Include timestamps.
4774 if (process_timestamps_) {
4775 ack_size += GetAckFrameTimeStampSize(ack);
4776 }
4777
4778 return ack_size;
4779}
4780
4781size_t QuicFramer::GetAckFrameTimeStampSize(const QuicAckFrame& ack) {
4782 if (ack.received_packet_times.empty()) {
4783 return 0;
4784 }
4785
4786 return kQuicNumTimestampsLength + kQuicFirstTimestampLength +
4787 (kQuicTimestampLength + kQuicTimestampPacketNumberGapLength) *
4788 (ack.received_packet_times.size() - 1);
4789}
4790
4791size_t QuicFramer::ComputeFrameLength(
4792 const QuicFrame& frame,
4793 bool last_frame_in_packet,
4794 QuicPacketNumberLength packet_number_length) {
4795 switch (frame.type) {
4796 case STREAM_FRAME:
4797 return GetMinStreamFrameSize(
4798 version_.transport_version, frame.stream_frame.stream_id,
4799 frame.stream_frame.offset, last_frame_in_packet,
4800 frame.stream_frame.data_length) +
4801 frame.stream_frame.data_length;
4802 case CRYPTO_FRAME:
4803 return GetMinCryptoFrameSize(frame.crypto_frame->offset,
4804 frame.crypto_frame->data_length) +
4805 frame.crypto_frame->data_length;
4806 case ACK_FRAME: {
4807 return GetAckFrameSize(*frame.ack_frame, packet_number_length);
4808 }
4809 case STOP_WAITING_FRAME:
renjietang488201d2019-12-17 13:40:49 -08004810 return GetStopWaitingFrameSize(packet_number_length);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004811 case MTU_DISCOVERY_FRAME:
4812 // MTU discovery frames are serialized as ping frames.
4813 return kQuicFrameTypeSize;
4814 case MESSAGE_FRAME:
4815 return GetMessageFrameSize(version_.transport_version,
4816 last_frame_in_packet,
4817 frame.message_frame->message_length);
4818 case PADDING_FRAME:
4819 DCHECK(false);
4820 return 0;
4821 default:
4822 return GetRetransmittableControlFrameSize(version_.transport_version,
4823 frame);
4824 }
4825}
4826
4827bool QuicFramer::AppendTypeByte(const QuicFrame& frame,
4828 bool last_frame_in_packet,
4829 QuicDataWriter* writer) {
fkastenholz305e1732019-06-18 05:01:22 -07004830 if (VersionHasIetfQuicFrames(version_.transport_version)) {
haoyuewangbe38a7d2020-06-23 10:18:35 -07004831 return AppendIetfFrameType(frame, last_frame_in_packet, writer);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004832 }
4833 uint8_t type_byte = 0;
4834 switch (frame.type) {
4835 case STREAM_FRAME:
4836 type_byte =
4837 GetStreamFrameTypeByte(frame.stream_frame, last_frame_in_packet);
4838 break;
4839 case ACK_FRAME:
4840 return true;
4841 case MTU_DISCOVERY_FRAME:
4842 type_byte = static_cast<uint8_t>(PING_FRAME);
4843 break;
QUICHE teama6ef0a62019-03-07 20:34:33 -05004844 case NEW_CONNECTION_ID_FRAME:
4845 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -07004846 "Attempt to append NEW_CONNECTION_ID frame and not in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05004847 return RaiseError(QUIC_INTERNAL_ERROR);
4848 case RETIRE_CONNECTION_ID_FRAME:
4849 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -07004850 "Attempt to append RETIRE_CONNECTION_ID frame and not in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05004851 return RaiseError(QUIC_INTERNAL_ERROR);
4852 case NEW_TOKEN_FRAME:
4853 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -07004854 "Attempt to append NEW_TOKEN frame and not in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05004855 return RaiseError(QUIC_INTERNAL_ERROR);
fkastenholz3c4eabf2019-04-22 07:49:59 -07004856 case MAX_STREAMS_FRAME:
QUICHE teama6ef0a62019-03-07 20:34:33 -05004857 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -07004858 "Attempt to append MAX_STREAMS frame and not in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05004859 return RaiseError(QUIC_INTERNAL_ERROR);
fkastenholz3c4eabf2019-04-22 07:49:59 -07004860 case STREAMS_BLOCKED_FRAME:
QUICHE teama6ef0a62019-03-07 20:34:33 -05004861 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -07004862 "Attempt to append STREAMS_BLOCKED frame and not in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05004863 return RaiseError(QUIC_INTERNAL_ERROR);
4864 case PATH_RESPONSE_FRAME:
4865 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -07004866 "Attempt to append PATH_RESPONSE frame and not in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05004867 return RaiseError(QUIC_INTERNAL_ERROR);
4868 case PATH_CHALLENGE_FRAME:
4869 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -07004870 "Attempt to append PATH_CHALLENGE frame and not in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05004871 return RaiseError(QUIC_INTERNAL_ERROR);
4872 case STOP_SENDING_FRAME:
4873 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -07004874 "Attempt to append STOP_SENDING frame and not in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05004875 return RaiseError(QUIC_INTERNAL_ERROR);
4876 case MESSAGE_FRAME:
4877 return true;
4878
4879 default:
4880 type_byte = static_cast<uint8_t>(frame.type);
4881 break;
4882 }
4883
4884 return writer->WriteUInt8(type_byte);
4885}
4886
haoyuewangbe38a7d2020-06-23 10:18:35 -07004887bool QuicFramer::AppendIetfFrameType(const QuicFrame& frame,
4888 bool last_frame_in_packet,
4889 QuicDataWriter* writer) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05004890 uint8_t type_byte = 0;
4891 switch (frame.type) {
4892 case PADDING_FRAME:
4893 type_byte = IETF_PADDING;
4894 break;
4895 case RST_STREAM_FRAME:
4896 type_byte = IETF_RST_STREAM;
4897 break;
4898 case CONNECTION_CLOSE_FRAME:
fkastenholz72f509b2019-04-10 09:17:49 -07004899 switch (frame.connection_close_frame->close_type) {
4900 case IETF_QUIC_APPLICATION_CONNECTION_CLOSE:
4901 type_byte = IETF_APPLICATION_CLOSE;
4902 break;
4903 case IETF_QUIC_TRANSPORT_CONNECTION_CLOSE:
4904 type_byte = IETF_CONNECTION_CLOSE;
4905 break;
4906 default:
wubdec17c22020-06-04 13:13:50 -07004907 set_detailed_error(quiche::QuicheStrCat(
4908 "Invalid QuicConnectionCloseFrame type: ",
4909 static_cast<int>(frame.connection_close_frame->close_type)));
fkastenholz72f509b2019-04-10 09:17:49 -07004910 return RaiseError(QUIC_INTERNAL_ERROR);
4911 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004912 break;
4913 case GOAWAY_FRAME:
4914 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -07004915 "Attempt to create non-IETF QUIC GOAWAY frame in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05004916 return RaiseError(QUIC_INTERNAL_ERROR);
4917 case WINDOW_UPDATE_FRAME:
4918 // Depending on whether there is a stream ID or not, will be either a
4919 // MAX_STREAM_DATA frame or a MAX_DATA frame.
4920 if (frame.window_update_frame->stream_id ==
4921 QuicUtils::GetInvalidStreamId(transport_version())) {
4922 type_byte = IETF_MAX_DATA;
4923 } else {
4924 type_byte = IETF_MAX_STREAM_DATA;
4925 }
4926 break;
4927 case BLOCKED_FRAME:
4928 if (frame.blocked_frame->stream_id ==
4929 QuicUtils::GetInvalidStreamId(transport_version())) {
ianswett2f077442019-12-12 11:51:24 -08004930 type_byte = IETF_DATA_BLOCKED;
QUICHE teama6ef0a62019-03-07 20:34:33 -05004931 } else {
ianswett2f077442019-12-12 11:51:24 -08004932 type_byte = IETF_STREAM_DATA_BLOCKED;
QUICHE teama6ef0a62019-03-07 20:34:33 -05004933 }
4934 break;
4935 case STOP_WAITING_FRAME:
4936 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -07004937 "Attempt to append type byte of STOP WAITING frame in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05004938 return RaiseError(QUIC_INTERNAL_ERROR);
4939 case PING_FRAME:
4940 type_byte = IETF_PING;
4941 break;
4942 case STREAM_FRAME:
4943 type_byte =
4944 GetStreamFrameTypeByte(frame.stream_frame, last_frame_in_packet);
4945 break;
4946 case ACK_FRAME:
4947 // Do nothing here, AppendIetfAckFrameAndTypeByte() will put the type byte
4948 // in the buffer.
4949 return true;
4950 case MTU_DISCOVERY_FRAME:
4951 // The path MTU discovery frame is encoded as a PING frame on the wire.
4952 type_byte = IETF_PING;
4953 break;
QUICHE teama6ef0a62019-03-07 20:34:33 -05004954 case NEW_CONNECTION_ID_FRAME:
4955 type_byte = IETF_NEW_CONNECTION_ID;
4956 break;
4957 case RETIRE_CONNECTION_ID_FRAME:
4958 type_byte = IETF_RETIRE_CONNECTION_ID;
4959 break;
4960 case NEW_TOKEN_FRAME:
4961 type_byte = IETF_NEW_TOKEN;
4962 break;
fkastenholz3c4eabf2019-04-22 07:49:59 -07004963 case MAX_STREAMS_FRAME:
4964 if (frame.max_streams_frame.unidirectional) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05004965 type_byte = IETF_MAX_STREAMS_UNIDIRECTIONAL;
fkastenholz3c4eabf2019-04-22 07:49:59 -07004966 } else {
4967 type_byte = IETF_MAX_STREAMS_BIDIRECTIONAL;
QUICHE teama6ef0a62019-03-07 20:34:33 -05004968 }
4969 break;
fkastenholz3c4eabf2019-04-22 07:49:59 -07004970 case STREAMS_BLOCKED_FRAME:
4971 if (frame.streams_blocked_frame.unidirectional) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05004972 type_byte = IETF_STREAMS_BLOCKED_UNIDIRECTIONAL;
fkastenholz3c4eabf2019-04-22 07:49:59 -07004973 } else {
4974 type_byte = IETF_STREAMS_BLOCKED_BIDIRECTIONAL;
QUICHE teama6ef0a62019-03-07 20:34:33 -05004975 }
4976 break;
4977 case PATH_RESPONSE_FRAME:
4978 type_byte = IETF_PATH_RESPONSE;
4979 break;
4980 case PATH_CHALLENGE_FRAME:
4981 type_byte = IETF_PATH_CHALLENGE;
4982 break;
4983 case STOP_SENDING_FRAME:
4984 type_byte = IETF_STOP_SENDING;
4985 break;
4986 case MESSAGE_FRAME:
4987 return true;
4988 case CRYPTO_FRAME:
4989 type_byte = IETF_CRYPTO;
4990 break;
fayang01062942020-01-22 07:23:23 -08004991 case HANDSHAKE_DONE_FRAME:
4992 type_byte = IETF_HANDSHAKE_DONE;
4993 break;
haoyuewang6a6a0ff2020-06-23 16:32:26 -07004994 case ACK_FREQUENCY_FRAME:
4995 type_byte = IETF_ACK_FREQUENCY;
4996 break;
QUICHE teama6ef0a62019-03-07 20:34:33 -05004997 default:
4998 QUIC_BUG << "Attempt to generate a frame type for an unsupported value: "
4999 << frame.type;
5000 return false;
5001 }
haoyuewangbe38a7d2020-06-23 10:18:35 -07005002 return writer->WriteVarInt62(type_byte);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005003}
5004
5005// static
5006bool QuicFramer::AppendPacketNumber(QuicPacketNumberLength packet_number_length,
5007 QuicPacketNumber packet_number,
5008 QuicDataWriter* writer) {
5009 DCHECK(packet_number.IsInitialized());
5010 if (!IsValidPacketNumberLength(packet_number_length)) {
5011 QUIC_BUG << "Invalid packet_number_length: " << packet_number_length;
5012 return false;
5013 }
5014 return writer->WriteBytesToUInt64(packet_number_length,
5015 packet_number.ToUint64());
5016}
5017
5018// static
5019bool QuicFramer::AppendStreamId(size_t stream_id_length,
5020 QuicStreamId stream_id,
5021 QuicDataWriter* writer) {
5022 if (stream_id_length == 0 || stream_id_length > 4) {
5023 QUIC_BUG << "Invalid stream_id_length: " << stream_id_length;
5024 return false;
5025 }
5026 return writer->WriteBytesToUInt64(stream_id_length, stream_id);
5027}
5028
5029// static
5030bool QuicFramer::AppendStreamOffset(size_t offset_length,
5031 QuicStreamOffset offset,
5032 QuicDataWriter* writer) {
5033 if (offset_length == 1 || offset_length > 8) {
5034 QUIC_BUG << "Invalid stream_offset_length: " << offset_length;
5035 return false;
5036 }
5037
5038 return writer->WriteBytesToUInt64(offset_length, offset);
5039}
5040
5041// static
5042bool QuicFramer::AppendAckBlock(uint8_t gap,
5043 QuicPacketNumberLength length_length,
5044 uint64_t length,
5045 QuicDataWriter* writer) {
5046 if (length == 0) {
5047 if (!IsValidPacketNumberLength(length_length)) {
5048 QUIC_BUG << "Invalid packet_number_length: " << length_length;
5049 return false;
5050 }
5051 return writer->WriteUInt8(gap) &&
5052 writer->WriteBytesToUInt64(length_length, length);
5053 }
5054 return writer->WriteUInt8(gap) &&
5055 AppendPacketNumber(length_length, QuicPacketNumber(length), writer);
5056}
5057
5058bool QuicFramer::AppendStreamFrame(const QuicStreamFrame& frame,
5059 bool no_stream_frame_length,
5060 QuicDataWriter* writer) {
fkastenholz305e1732019-06-18 05:01:22 -07005061 if (VersionHasIetfQuicFrames(version_.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005062 return AppendIetfStreamFrame(frame, no_stream_frame_length, writer);
5063 }
5064 if (!AppendStreamId(GetStreamIdSize(frame.stream_id), frame.stream_id,
5065 writer)) {
5066 QUIC_BUG << "Writing stream id size failed.";
5067 return false;
5068 }
renjietang488201d2019-12-17 13:40:49 -08005069 if (!AppendStreamOffset(GetStreamOffsetSize(frame.offset), frame.offset,
5070 writer)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005071 QUIC_BUG << "Writing offset size failed.";
5072 return false;
5073 }
5074 if (!no_stream_frame_length) {
dschinazi878cfb52019-06-17 17:12:58 -07005075 static_assert(
wubeff50282019-06-19 09:04:30 -07005076 std::numeric_limits<decltype(frame.data_length)>::max() <=
dschinazi878cfb52019-06-17 17:12:58 -07005077 std::numeric_limits<uint16_t>::max(),
5078 "If frame.data_length can hold more than a uint16_t than we need to "
5079 "check that frame.data_length <= std::numeric_limits<uint16_t>::max()");
5080 if (!writer->WriteUInt16(static_cast<uint16_t>(frame.data_length))) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005081 QUIC_BUG << "Writing stream frame length failed";
5082 return false;
5083 }
5084 }
5085
5086 if (data_producer_ != nullptr) {
5087 DCHECK_EQ(nullptr, frame.data_buffer);
5088 if (frame.data_length == 0) {
5089 return true;
5090 }
5091 if (data_producer_->WriteStreamData(frame.stream_id, frame.offset,
5092 frame.data_length,
5093 writer) != WRITE_SUCCESS) {
5094 QUIC_BUG << "Writing frame data failed.";
5095 return false;
5096 }
5097 return true;
5098 }
5099
5100 if (!writer->WriteBytes(frame.data_buffer, frame.data_length)) {
5101 QUIC_BUG << "Writing frame data failed.";
5102 return false;
5103 }
5104 return true;
5105}
5106
QUICHE teama6ef0a62019-03-07 20:34:33 -05005107bool QuicFramer::AppendNewTokenFrame(const QuicNewTokenFrame& frame,
5108 QuicDataWriter* writer) {
5109 if (!writer->WriteVarInt62(static_cast<uint64_t>(frame.token.length()))) {
5110 set_detailed_error("Writing token length failed.");
5111 return false;
5112 }
5113 if (!writer->WriteBytes(frame.token.data(), frame.token.length())) {
5114 set_detailed_error("Writing token buffer failed.");
5115 return false;
5116 }
5117 return true;
5118}
5119
5120bool QuicFramer::ProcessNewTokenFrame(QuicDataReader* reader,
5121 QuicNewTokenFrame* frame) {
5122 uint64_t length;
5123 if (!reader->ReadVarInt62(&length)) {
5124 set_detailed_error("Unable to read new token length.");
5125 return false;
5126 }
5127 if (length > kMaxNewTokenTokenLength) {
5128 set_detailed_error("Token length larger than maximum.");
5129 return false;
5130 }
5131
dmcardlecf0bfcf2019-12-13 08:08:21 -08005132 // TODO(ianswett): Don't use quiche::QuicheStringPiece as an intermediary.
5133 quiche::QuicheStringPiece data;
QUICHE teama6ef0a62019-03-07 20:34:33 -05005134 if (!reader->ReadStringPiece(&data, length)) {
5135 set_detailed_error("Unable to read new token data.");
5136 return false;
5137 }
vasilvvc48c8712019-03-11 13:38:16 -07005138 frame->token = std::string(data);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005139 return true;
5140}
5141
5142// Add a new ietf-format stream frame.
5143// Bits controlling whether there is a frame-length and frame-offset
5144// are in the QuicStreamFrame.
5145bool QuicFramer::AppendIetfStreamFrame(const QuicStreamFrame& frame,
5146 bool last_frame_in_packet,
5147 QuicDataWriter* writer) {
5148 if (!writer->WriteVarInt62(static_cast<uint64_t>(frame.stream_id))) {
5149 set_detailed_error("Writing stream id failed.");
5150 return false;
5151 }
5152
5153 if (frame.offset != 0) {
5154 if (!writer->WriteVarInt62(static_cast<uint64_t>(frame.offset))) {
5155 set_detailed_error("Writing data offset failed.");
5156 return false;
5157 }
5158 }
5159
5160 if (!last_frame_in_packet) {
5161 if (!writer->WriteVarInt62(frame.data_length)) {
5162 set_detailed_error("Writing data length failed.");
5163 return false;
5164 }
5165 }
5166
5167 if (frame.data_length == 0) {
5168 return true;
5169 }
5170 if (data_producer_ == nullptr) {
5171 if (!writer->WriteBytes(frame.data_buffer, frame.data_length)) {
5172 set_detailed_error("Writing frame data failed.");
5173 return false;
5174 }
5175 } else {
5176 DCHECK_EQ(nullptr, frame.data_buffer);
5177
5178 if (data_producer_->WriteStreamData(frame.stream_id, frame.offset,
5179 frame.data_length,
5180 writer) != WRITE_SUCCESS) {
5181 set_detailed_error("Writing frame data failed.");
5182 return false;
5183 }
5184 }
5185 return true;
5186}
5187
5188bool QuicFramer::AppendCryptoFrame(const QuicCryptoFrame& frame,
5189 QuicDataWriter* writer) {
5190 if (!writer->WriteVarInt62(static_cast<uint64_t>(frame.offset))) {
5191 set_detailed_error("Writing data offset failed.");
5192 return false;
5193 }
5194 if (!writer->WriteVarInt62(static_cast<uint64_t>(frame.data_length))) {
5195 set_detailed_error("Writing data length failed.");
5196 return false;
5197 }
5198 if (data_producer_ == nullptr) {
5199 if (frame.data_buffer == nullptr ||
5200 !writer->WriteBytes(frame.data_buffer, frame.data_length)) {
5201 set_detailed_error("Writing frame data failed.");
5202 return false;
5203 }
5204 } else {
5205 DCHECK_EQ(nullptr, frame.data_buffer);
5206 if (!data_producer_->WriteCryptoData(frame.level, frame.offset,
5207 frame.data_length, writer)) {
5208 return false;
5209 }
5210 }
5211 return true;
5212}
5213
haoyuewang6a6a0ff2020-06-23 16:32:26 -07005214bool QuicFramer::AppendAckFrequencyFrame(const QuicAckFrequencyFrame& frame,
5215 QuicDataWriter* writer) {
5216 if (!writer->WriteVarInt62(frame.sequence_number)) {
5217 set_detailed_error("Writing sequence number failed.");
5218 return false;
5219 }
5220 if (!writer->WriteVarInt62(frame.packet_tolerance)) {
5221 set_detailed_error("Writing packet tolerance failed.");
5222 return false;
5223 }
5224 if (!writer->WriteVarInt62(
5225 static_cast<uint64_t>(frame.max_ack_delay.ToMicroseconds()))) {
5226 set_detailed_error("Writing max_ack_delay_us failed.");
5227 return false;
5228 }
5229 if (!writer->WriteUInt8(static_cast<uint8_t>(frame.ignore_order))) {
5230 set_detailed_error("Writing ignore_order failed.");
5231 return false;
5232 }
5233
5234 return true;
5235}
5236
QUICHE teama6ef0a62019-03-07 20:34:33 -05005237void QuicFramer::set_version(const ParsedQuicVersion version) {
5238 DCHECK(IsSupportedVersion(version)) << ParsedQuicVersionToString(version);
5239 version_ = version;
5240}
5241
5242bool QuicFramer::AppendAckFrameAndTypeByte(const QuicAckFrame& frame,
5243 QuicDataWriter* writer) {
fkastenholz305e1732019-06-18 05:01:22 -07005244 if (VersionHasIetfQuicFrames(transport_version())) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005245 return AppendIetfAckFrameAndTypeByte(frame, writer);
5246 }
5247
5248 const AckFrameInfo new_ack_info = GetAckFrameInfo(frame);
5249 QuicPacketNumber largest_acked = LargestAcked(frame);
5250 QuicPacketNumberLength largest_acked_length =
renjietang488201d2019-12-17 13:40:49 -08005251 GetMinPacketNumberLength(largest_acked);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005252 QuicPacketNumberLength ack_block_length =
renjietang488201d2019-12-17 13:40:49 -08005253 GetMinPacketNumberLength(QuicPacketNumber(new_ack_info.max_block_length));
QUICHE teama6ef0a62019-03-07 20:34:33 -05005254 // Calculate available bytes for timestamps and ack blocks.
5255 int32_t available_timestamp_and_ack_block_bytes =
5256 writer->capacity() - writer->length() - ack_block_length -
fayanga66f6842020-03-06 08:58:55 -08005257 GetMinAckFrameSize(version_.transport_version, frame,
fayang43697fd2020-04-21 11:13:43 -07005258 local_ack_delay_exponent_) -
QUICHE teama6ef0a62019-03-07 20:34:33 -05005259 (new_ack_info.num_ack_blocks != 0 ? kNumberOfAckBlocksSize : 0);
5260 DCHECK_LE(0, available_timestamp_and_ack_block_bytes);
5261
QUICHE teama6ef0a62019-03-07 20:34:33 -05005262 uint8_t type_byte = 0;
5263 SetBit(&type_byte, new_ack_info.num_ack_blocks != 0,
5264 kQuicHasMultipleAckBlocksOffset);
5265
5266 SetBits(&type_byte, GetPacketNumberFlags(largest_acked_length),
5267 kQuicSequenceNumberLengthNumBits, kLargestAckedOffset);
5268
5269 SetBits(&type_byte, GetPacketNumberFlags(ack_block_length),
5270 kQuicSequenceNumberLengthNumBits, kActBlockLengthOffset);
5271
5272 type_byte |= kQuicFrameTypeAckMask;
5273
5274 if (!writer->WriteUInt8(type_byte)) {
5275 return false;
5276 }
5277
5278 size_t max_num_ack_blocks = available_timestamp_and_ack_block_bytes /
5279 (ack_block_length + PACKET_1BYTE_PACKET_NUMBER);
5280
5281 // Number of ack blocks.
5282 size_t num_ack_blocks =
5283 std::min(new_ack_info.num_ack_blocks, max_num_ack_blocks);
5284 if (num_ack_blocks > std::numeric_limits<uint8_t>::max()) {
5285 num_ack_blocks = std::numeric_limits<uint8_t>::max();
5286 }
5287
5288 // Largest acked.
5289 if (!AppendPacketNumber(largest_acked_length, largest_acked, writer)) {
5290 return false;
5291 }
5292
5293 // Largest acked delta time.
5294 uint64_t ack_delay_time_us = kUFloat16MaxValue;
5295 if (!frame.ack_delay_time.IsInfinite()) {
5296 DCHECK_LE(0u, frame.ack_delay_time.ToMicroseconds());
5297 ack_delay_time_us = frame.ack_delay_time.ToMicroseconds();
5298 }
5299 if (!writer->WriteUFloat16(ack_delay_time_us)) {
5300 return false;
5301 }
5302
5303 if (num_ack_blocks > 0) {
5304 if (!writer->WriteBytes(&num_ack_blocks, 1)) {
5305 return false;
5306 }
5307 }
5308
5309 // First ack block length.
5310 if (!AppendPacketNumber(ack_block_length,
5311 QuicPacketNumber(new_ack_info.first_block_length),
5312 writer)) {
5313 return false;
5314 }
5315
5316 // Ack blocks.
5317 if (num_ack_blocks > 0) {
5318 size_t num_ack_blocks_written = 0;
5319 // Append, in descending order from the largest ACKed packet, a series of
5320 // ACK blocks that represents the successfully acknoweldged packets. Each
5321 // appended gap/block length represents a descending delta from the previous
5322 // block. i.e.:
5323 // |--- length ---|--- gap ---|--- length ---|--- gap ---|--- largest ---|
5324 // For gaps larger than can be represented by a single encoded gap, a 0
5325 // length gap of the maximum is used, i.e.:
5326 // |--- length ---|--- gap ---|- 0 -|--- gap ---|--- largest ---|
5327 auto itr = frame.packets.rbegin();
5328 QuicPacketNumber previous_start = itr->min();
5329 ++itr;
5330
5331 for (;
5332 itr != frame.packets.rend() && num_ack_blocks_written < num_ack_blocks;
5333 previous_start = itr->min(), ++itr) {
5334 const auto& interval = *itr;
5335 const uint64_t total_gap = previous_start - interval.max();
5336 const size_t num_encoded_gaps =
5337 (total_gap + std::numeric_limits<uint8_t>::max() - 1) /
5338 std::numeric_limits<uint8_t>::max();
QUICHE teama6ef0a62019-03-07 20:34:33 -05005339
5340 // Append empty ACK blocks because the gap is longer than a single gap.
5341 for (size_t i = 1;
5342 i < num_encoded_gaps && num_ack_blocks_written < num_ack_blocks;
5343 ++i) {
5344 if (!AppendAckBlock(std::numeric_limits<uint8_t>::max(),
5345 ack_block_length, 0, writer)) {
5346 return false;
5347 }
5348 ++num_ack_blocks_written;
5349 }
5350 if (num_ack_blocks_written >= num_ack_blocks) {
5351 if (QUIC_PREDICT_FALSE(num_ack_blocks_written != num_ack_blocks)) {
5352 QUIC_BUG << "Wrote " << num_ack_blocks_written
5353 << ", expected to write " << num_ack_blocks;
5354 }
5355 break;
5356 }
5357
5358 const uint8_t last_gap =
5359 total_gap -
5360 (num_encoded_gaps - 1) * std::numeric_limits<uint8_t>::max();
5361 // Append the final ACK block with a non-empty size.
wub13d75452019-11-05 07:24:56 -08005362 if (!AppendAckBlock(last_gap, ack_block_length, interval.Length(),
5363 writer)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005364 return false;
5365 }
5366 ++num_ack_blocks_written;
5367 }
5368 DCHECK_EQ(num_ack_blocks, num_ack_blocks_written);
5369 }
5370 // Timestamps.
5371 // If we don't process timestamps or if we don't have enough available space
5372 // to append all the timestamps, don't append any of them.
5373 if (process_timestamps_ && writer->capacity() - writer->length() >=
5374 GetAckFrameTimeStampSize(frame)) {
5375 if (!AppendTimestampsToAckFrame(frame, writer)) {
5376 return false;
5377 }
5378 } else {
5379 uint8_t num_received_packets = 0;
5380 if (!writer->WriteBytes(&num_received_packets, 1)) {
5381 return false;
5382 }
5383 }
5384
5385 return true;
5386}
5387
5388bool QuicFramer::AppendTimestampsToAckFrame(const QuicAckFrame& frame,
5389 QuicDataWriter* writer) {
5390 DCHECK_GE(std::numeric_limits<uint8_t>::max(),
5391 frame.received_packet_times.size());
5392 // num_received_packets is only 1 byte.
5393 if (frame.received_packet_times.size() >
5394 std::numeric_limits<uint8_t>::max()) {
5395 return false;
5396 }
5397
5398 uint8_t num_received_packets = frame.received_packet_times.size();
5399 if (!writer->WriteBytes(&num_received_packets, 1)) {
5400 return false;
5401 }
5402 if (num_received_packets == 0) {
5403 return true;
5404 }
5405
5406 auto it = frame.received_packet_times.begin();
5407 QuicPacketNumber packet_number = it->first;
5408 uint64_t delta_from_largest_observed = LargestAcked(frame) - packet_number;
5409
5410 DCHECK_GE(std::numeric_limits<uint8_t>::max(), delta_from_largest_observed);
5411 if (delta_from_largest_observed > std::numeric_limits<uint8_t>::max()) {
5412 return false;
5413 }
5414
5415 if (!writer->WriteUInt8(delta_from_largest_observed)) {
5416 return false;
5417 }
5418
5419 // Use the lowest 4 bytes of the time delta from the creation_time_.
5420 const uint64_t time_epoch_delta_us = UINT64_C(1) << 32;
5421 uint32_t time_delta_us =
5422 static_cast<uint32_t>((it->second - creation_time_).ToMicroseconds() &
5423 (time_epoch_delta_us - 1));
5424 if (!writer->WriteUInt32(time_delta_us)) {
5425 return false;
5426 }
5427
5428 QuicTime prev_time = it->second;
5429
5430 for (++it; it != frame.received_packet_times.end(); ++it) {
5431 packet_number = it->first;
5432 delta_from_largest_observed = LargestAcked(frame) - packet_number;
5433
5434 if (delta_from_largest_observed > std::numeric_limits<uint8_t>::max()) {
5435 return false;
5436 }
5437
5438 if (!writer->WriteUInt8(delta_from_largest_observed)) {
5439 return false;
5440 }
5441
5442 uint64_t frame_time_delta_us = (it->second - prev_time).ToMicroseconds();
5443 prev_time = it->second;
5444 if (!writer->WriteUFloat16(frame_time_delta_us)) {
5445 return false;
5446 }
5447 }
5448 return true;
5449}
5450
5451bool QuicFramer::AppendStopWaitingFrame(const QuicPacketHeader& header,
5452 const QuicStopWaitingFrame& frame,
5453 QuicDataWriter* writer) {
fayangd4291e42019-05-30 10:31:21 -07005454 DCHECK(!VersionHasIetfInvariantHeader(version_.transport_version));
bncbe885272020-01-16 11:10:48 -08005455 DCHECK(frame.least_unacked.IsInitialized());
5456 DCHECK_GE(header.packet_number, frame.least_unacked);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005457 const uint64_t least_unacked_delta =
5458 header.packet_number - frame.least_unacked;
5459 const uint64_t length_shift = header.packet_number_length * 8;
5460
5461 if (least_unacked_delta >> length_shift > 0) {
5462 QUIC_BUG << "packet_number_length " << header.packet_number_length
5463 << " is too small for least_unacked_delta: " << least_unacked_delta
5464 << " packet_number:" << header.packet_number
5465 << " least_unacked:" << frame.least_unacked
5466 << " version:" << version_.transport_version;
5467 return false;
5468 }
5469 if (least_unacked_delta == 0) {
5470 return writer->WriteBytesToUInt64(header.packet_number_length,
5471 least_unacked_delta);
5472 }
5473 if (!AppendPacketNumber(header.packet_number_length,
5474 QuicPacketNumber(least_unacked_delta), writer)) {
5475 QUIC_BUG << " seq failed: " << header.packet_number_length;
5476 return false;
5477 }
5478
5479 return true;
5480}
5481
QUICHE teama6ef0a62019-03-07 20:34:33 -05005482bool QuicFramer::AppendIetfAckFrameAndTypeByte(const QuicAckFrame& frame,
5483 QuicDataWriter* writer) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005484 uint8_t type = IETF_ACK;
fayang91c23d72020-03-09 12:35:05 -07005485 uint64_t ecn_size = 0;
QUICHE teama6ef0a62019-03-07 20:34:33 -05005486 if (frame.ecn_counters_populated &&
5487 (frame.ect_0_count || frame.ect_1_count || frame.ecn_ce_count)) {
fayang91c23d72020-03-09 12:35:05 -07005488 // Change frame type to ACK_ECN if any ECN count is available.
QUICHE teama6ef0a62019-03-07 20:34:33 -05005489 type = IETF_ACK_ECN;
fayang91c23d72020-03-09 12:35:05 -07005490 ecn_size = (QuicDataWriter::GetVarInt62Len(frame.ect_0_count) +
5491 QuicDataWriter::GetVarInt62Len(frame.ect_1_count) +
5492 QuicDataWriter::GetVarInt62Len(frame.ecn_ce_count));
QUICHE teama6ef0a62019-03-07 20:34:33 -05005493 }
5494
haoyuewangbe38a7d2020-06-23 10:18:35 -07005495 if (!writer->WriteVarInt62(type)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005496 set_detailed_error("No room for frame-type");
5497 return false;
5498 }
5499
5500 QuicPacketNumber largest_acked = LargestAcked(frame);
5501 if (!writer->WriteVarInt62(largest_acked.ToUint64())) {
5502 set_detailed_error("No room for largest-acked in ack frame");
5503 return false;
5504 }
5505
5506 uint64_t ack_delay_time_us = kVarInt62MaxValue;
5507 if (!frame.ack_delay_time.IsInfinite()) {
5508 DCHECK_LE(0u, frame.ack_delay_time.ToMicroseconds());
5509 ack_delay_time_us = frame.ack_delay_time.ToMicroseconds();
fkastenholz4dc4ba32019-07-30 09:55:25 -07005510 ack_delay_time_us = ack_delay_time_us >> local_ack_delay_exponent_;
QUICHE teama6ef0a62019-03-07 20:34:33 -05005511 }
5512
5513 if (!writer->WriteVarInt62(ack_delay_time_us)) {
5514 set_detailed_error("No room for ack-delay in ack frame");
5515 return false;
5516 }
fayang91c23d72020-03-09 12:35:05 -07005517
5518 if (frame.packets.Empty() || frame.packets.Max() != largest_acked) {
5519 QUIC_BUG << "Malformed ack frame: " << frame;
5520 set_detailed_error("Malformed ack frame");
5521 return false;
5522 }
5523
5524 // Latch ack_block_count for potential truncation.
5525 const uint64_t ack_block_count = frame.packets.NumIntervals() - 1;
5526 QuicDataWriter count_writer(QuicDataWriter::GetVarInt62Len(ack_block_count),
5527 writer->data() + writer->length());
5528 if (!writer->WriteVarInt62(ack_block_count)) {
5529 set_detailed_error("No room for ack block count in ack frame");
5530 return false;
5531 }
5532 auto iter = frame.packets.rbegin();
5533 if (!writer->WriteVarInt62(iter->Length() - 1)) {
5534 set_detailed_error("No room for first ack block in ack frame");
5535 return false;
5536 }
5537 QuicPacketNumber previous_smallest = iter->min();
5538 ++iter;
5539 // Append remaining ACK blocks.
5540 uint64_t appended_ack_blocks = 0;
5541 for (; iter != frame.packets.rend(); ++iter) {
5542 const uint64_t gap = previous_smallest - iter->max() - 1;
5543 const uint64_t ack_range = iter->Length() - 1;
5544
5545 if (writer->remaining() < ecn_size ||
danzh25da9192020-05-01 15:53:28 -07005546 static_cast<size_t>(writer->remaining() - ecn_size) <
fayang91c23d72020-03-09 12:35:05 -07005547 QuicDataWriter::GetVarInt62Len(gap) +
5548 QuicDataWriter::GetVarInt62Len(ack_range)) {
5549 // ACK range does not fit, truncate it.
5550 break;
5551 }
5552 const bool success =
5553 writer->WriteVarInt62(gap) && writer->WriteVarInt62(ack_range);
5554 DCHECK(success);
5555 previous_smallest = iter->min();
5556 ++appended_ack_blocks;
5557 }
5558
5559 if (appended_ack_blocks < ack_block_count) {
5560 // Truncation is needed, rewrite the ack block count.
5561 if (QuicDataWriter::GetVarInt62Len(appended_ack_blocks) !=
5562 QuicDataWriter::GetVarInt62Len(ack_block_count) ||
5563 !count_writer.WriteVarInt62(appended_ack_blocks)) {
5564 // This should never happen as ack_block_count is limited by
5565 // max_ack_ranges_.
5566 QUIC_BUG << "Ack frame truncation fails. ack_block_count: "
5567 << ack_block_count
5568 << ", appended count: " << appended_ack_blocks;
5569 set_detailed_error("ACK frame truncation fails");
5570 return false;
5571 }
5572 QUIC_DLOG(INFO) << ENDPOINT << "ACK ranges get truncated from "
5573 << ack_block_count << " to " << appended_ack_blocks;
5574 }
5575
QUICHE teama6ef0a62019-03-07 20:34:33 -05005576 if (type == IETF_ACK_ECN) {
fayang91c23d72020-03-09 12:35:05 -07005577 // Encode the ECN counts.
QUICHE teama6ef0a62019-03-07 20:34:33 -05005578 if (!writer->WriteVarInt62(frame.ect_0_count)) {
5579 set_detailed_error("No room for ect_0_count in ack frame");
5580 return false;
5581 }
5582 if (!writer->WriteVarInt62(frame.ect_1_count)) {
5583 set_detailed_error("No room for ect_1_count in ack frame");
5584 return false;
5585 }
5586 if (!writer->WriteVarInt62(frame.ecn_ce_count)) {
5587 set_detailed_error("No room for ecn_ce_count in ack frame");
5588 return false;
5589 }
5590 }
5591
QUICHE teama6ef0a62019-03-07 20:34:33 -05005592 return true;
5593}
5594
5595bool QuicFramer::AppendRstStreamFrame(const QuicRstStreamFrame& frame,
5596 QuicDataWriter* writer) {
fkastenholz305e1732019-06-18 05:01:22 -07005597 if (VersionHasIetfQuicFrames(version_.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005598 return AppendIetfResetStreamFrame(frame, writer);
5599 }
5600 if (!writer->WriteUInt32(frame.stream_id)) {
5601 return false;
5602 }
5603
5604 if (!writer->WriteUInt64(frame.byte_offset)) {
5605 return false;
5606 }
5607
5608 uint32_t error_code = static_cast<uint32_t>(frame.error_code);
5609 if (!writer->WriteUInt32(error_code)) {
5610 return false;
5611 }
5612
5613 return true;
5614}
5615
5616bool QuicFramer::AppendConnectionCloseFrame(
5617 const QuicConnectionCloseFrame& frame,
5618 QuicDataWriter* writer) {
fkastenholz305e1732019-06-18 05:01:22 -07005619 if (VersionHasIetfQuicFrames(version_.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005620 return AppendIetfConnectionCloseFrame(frame, writer);
5621 }
bnc77e77b82020-04-05 10:36:49 -07005622 uint32_t error_code = static_cast<uint32_t>(frame.wire_error_code);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005623 if (!writer->WriteUInt32(error_code)) {
5624 return false;
5625 }
5626 if (!writer->WriteStringPiece16(TruncateErrorString(frame.error_details))) {
5627 return false;
5628 }
5629 return true;
5630}
5631
5632bool QuicFramer::AppendGoAwayFrame(const QuicGoAwayFrame& frame,
5633 QuicDataWriter* writer) {
5634 uint32_t error_code = static_cast<uint32_t>(frame.error_code);
5635 if (!writer->WriteUInt32(error_code)) {
5636 return false;
5637 }
5638 uint32_t stream_id = static_cast<uint32_t>(frame.last_good_stream_id);
5639 if (!writer->WriteUInt32(stream_id)) {
5640 return false;
5641 }
5642 if (!writer->WriteStringPiece16(TruncateErrorString(frame.reason_phrase))) {
5643 return false;
5644 }
5645 return true;
5646}
5647
5648bool QuicFramer::AppendWindowUpdateFrame(const QuicWindowUpdateFrame& frame,
5649 QuicDataWriter* writer) {
5650 uint32_t stream_id = static_cast<uint32_t>(frame.stream_id);
5651 if (!writer->WriteUInt32(stream_id)) {
5652 return false;
5653 }
renjietangd088eab2019-11-21 14:54:41 -08005654 if (!writer->WriteUInt64(frame.max_data)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005655 return false;
5656 }
5657 return true;
5658}
5659
5660bool QuicFramer::AppendBlockedFrame(const QuicBlockedFrame& frame,
5661 QuicDataWriter* writer) {
fkastenholz305e1732019-06-18 05:01:22 -07005662 if (VersionHasIetfQuicFrames(version_.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005663 if (frame.stream_id == QuicUtils::GetInvalidStreamId(transport_version())) {
renjietangf8a9c8c2020-03-19 16:47:03 -07005664 return AppendDataBlockedFrame(frame, writer);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005665 }
renjietangf8a9c8c2020-03-19 16:47:03 -07005666 return AppendStreamDataBlockedFrame(frame, writer);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005667 }
5668 uint32_t stream_id = static_cast<uint32_t>(frame.stream_id);
5669 if (!writer->WriteUInt32(stream_id)) {
5670 return false;
5671 }
5672 return true;
5673}
5674
5675bool QuicFramer::AppendPaddingFrame(const QuicPaddingFrame& frame,
5676 QuicDataWriter* writer) {
5677 if (frame.num_padding_bytes == 0) {
5678 return false;
5679 }
5680 if (frame.num_padding_bytes < 0) {
5681 QUIC_BUG_IF(frame.num_padding_bytes != -1);
5682 writer->WritePadding();
5683 return true;
5684 }
5685 // Please note, num_padding_bytes includes type byte which has been written.
5686 return writer->WritePaddingBytes(frame.num_padding_bytes - 1);
5687}
5688
5689bool QuicFramer::AppendMessageFrameAndTypeByte(const QuicMessageFrame& frame,
5690 bool last_frame_in_packet,
5691 QuicDataWriter* writer) {
dschinazicd86dd12019-11-14 10:11:13 -08005692 uint8_t type_byte;
5693 if (VersionHasIetfQuicFrames(version_.transport_version)) {
5694 type_byte = last_frame_in_packet ? IETF_EXTENSION_MESSAGE_NO_LENGTH_V99
5695 : IETF_EXTENSION_MESSAGE_V99;
5696 } else {
5697 type_byte = last_frame_in_packet ? IETF_EXTENSION_MESSAGE_NO_LENGTH
5698 : IETF_EXTENSION_MESSAGE;
5699 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05005700 if (!writer->WriteUInt8(type_byte)) {
5701 return false;
5702 }
5703 if (!last_frame_in_packet && !writer->WriteVarInt62(frame.message_length)) {
5704 return false;
5705 }
5706 for (const auto& slice : frame.message_data) {
5707 if (!writer->WriteBytes(slice.data(), slice.length())) {
5708 return false;
5709 }
5710 }
5711 return true;
5712}
5713
5714bool QuicFramer::RaiseError(QuicErrorCode error) {
5715 QUIC_DLOG(INFO) << ENDPOINT << "Error: " << QuicErrorCodeToString(error)
5716 << " detail: " << detailed_error_;
5717 set_error(error);
nharper55fa6132019-05-07 19:37:21 -07005718 if (visitor_) {
5719 visitor_->OnError(this);
5720 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05005721 return false;
5722}
5723
5724bool QuicFramer::IsVersionNegotiation(
5725 const QuicPacketHeader& header,
5726 bool packet_has_ietf_packet_header) const {
dschinazi072da7c2019-05-07 17:57:42 -07005727 if (!packet_has_ietf_packet_header &&
5728 perspective_ == Perspective::IS_CLIENT) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005729 return header.version_flag;
5730 }
5731 if (header.form == IETF_QUIC_SHORT_HEADER_PACKET) {
5732 return false;
5733 }
5734 return header.long_packet_type == VERSION_NEGOTIATION;
5735}
5736
QUICHE teama6ef0a62019-03-07 20:34:33 -05005737bool QuicFramer::AppendIetfConnectionCloseFrame(
5738 const QuicConnectionCloseFrame& frame,
5739 QuicDataWriter* writer) {
fkastenholz72f509b2019-04-10 09:17:49 -07005740 if (frame.close_type != IETF_QUIC_TRANSPORT_CONNECTION_CLOSE &&
5741 frame.close_type != IETF_QUIC_APPLICATION_CONNECTION_CLOSE) {
5742 QUIC_BUG << "Invalid close_type for writing IETF CONNECTION CLOSE.";
5743 set_detailed_error("Invalid close_type for writing IETF CONNECTION CLOSE.");
5744 return false;
5745 }
5746
bnc77e77b82020-04-05 10:36:49 -07005747 if (!writer->WriteVarInt62(frame.wire_error_code)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005748 set_detailed_error("Can not write connection close frame error code");
5749 return false;
5750 }
fkastenholze9d71a82019-04-09 05:12:13 -07005751
fkastenholz72f509b2019-04-10 09:17:49 -07005752 if (frame.close_type == IETF_QUIC_TRANSPORT_CONNECTION_CLOSE) {
5753 // Write the frame-type of the frame causing the error only
5754 // if it's a CONNECTION_CLOSE/Transport.
5755 if (!writer->WriteVarInt62(frame.transport_close_frame_type)) {
5756 set_detailed_error("Writing frame type failed.");
5757 return false;
5758 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05005759 }
5760
fkastenholzb4dade72019-08-05 06:54:20 -07005761 // There may be additional error information available in the extracted error
5762 // code. Encode the error information in the reason phrase and serialize the
5763 // result.
5764 std::string final_error_string =
bnc77e77b82020-04-05 10:36:49 -07005765 GenerateErrorString(frame.error_details, frame.quic_error_code);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005766 if (!writer->WriteStringPieceVarInt62(
fkastenholzb4dade72019-08-05 06:54:20 -07005767 TruncateErrorString(final_error_string))) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005768 set_detailed_error("Can not write connection close phrase");
5769 return false;
5770 }
5771 return true;
5772}
5773
QUICHE teama6ef0a62019-03-07 20:34:33 -05005774bool QuicFramer::ProcessIetfConnectionCloseFrame(
5775 QuicDataReader* reader,
fkastenholze9d71a82019-04-09 05:12:13 -07005776 QuicConnectionCloseType type,
QUICHE teama6ef0a62019-03-07 20:34:33 -05005777 QuicConnectionCloseFrame* frame) {
fkastenholze9d71a82019-04-09 05:12:13 -07005778 frame->close_type = type;
fkastenholzb4dade72019-08-05 06:54:20 -07005779
fkastenholz88d08f42019-09-06 07:38:04 -07005780 uint64_t error_code;
fkastenholzd57d3f92019-07-16 09:05:17 -07005781 if (!reader->ReadVarInt62(&error_code)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005782 set_detailed_error("Unable to read connection close error code.");
5783 return false;
5784 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05005785
bnc77e77b82020-04-05 10:36:49 -07005786 frame->wire_error_code = error_code;
fkastenholzb4dade72019-08-05 06:54:20 -07005787
fkastenholz72f509b2019-04-10 09:17:49 -07005788 if (type == IETF_QUIC_TRANSPORT_CONNECTION_CLOSE) {
5789 // The frame-type of the frame causing the error is present only
5790 // if it's a CONNECTION_CLOSE/Transport.
5791 if (!reader->ReadVarInt62(&frame->transport_close_frame_type)) {
5792 set_detailed_error("Unable to read connection close frame type.");
5793 return false;
5794 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05005795 }
5796
5797 uint64_t phrase_length;
5798 if (!reader->ReadVarInt62(&phrase_length)) {
5799 set_detailed_error("Unable to read connection close error details.");
5800 return false;
5801 }
fkastenholzb4dade72019-08-05 06:54:20 -07005802
dmcardlecf0bfcf2019-12-13 08:08:21 -08005803 quiche::QuicheStringPiece phrase;
QUICHE teama6ef0a62019-03-07 20:34:33 -05005804 if (!reader->ReadStringPiece(&phrase, static_cast<size_t>(phrase_length))) {
5805 set_detailed_error("Unable to read connection close error details.");
5806 return false;
5807 }
vasilvvc48c8712019-03-11 13:38:16 -07005808 frame->error_details = std::string(phrase);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005809
fkastenholzb4dade72019-08-05 06:54:20 -07005810 // The frame may have an extracted error code in it. Look for it and
5811 // extract it. If it's not present, MaybeExtract will return
5812 // QUIC_IETF_GQUIC_ERROR_MISSING.
fkastenholz488a4622019-08-26 06:24:46 -07005813 MaybeExtractQuicErrorCode(frame);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005814 return true;
5815}
5816
5817// IETF Quic Path Challenge/Response frames.
5818bool QuicFramer::ProcessPathChallengeFrame(QuicDataReader* reader,
5819 QuicPathChallengeFrame* frame) {
5820 if (!reader->ReadBytes(frame->data_buffer.data(),
5821 frame->data_buffer.size())) {
5822 set_detailed_error("Can not read path challenge data.");
5823 return false;
5824 }
5825 return true;
5826}
5827
5828bool QuicFramer::ProcessPathResponseFrame(QuicDataReader* reader,
5829 QuicPathResponseFrame* frame) {
5830 if (!reader->ReadBytes(frame->data_buffer.data(),
5831 frame->data_buffer.size())) {
5832 set_detailed_error("Can not read path response data.");
5833 return false;
5834 }
5835 return true;
5836}
5837
5838bool QuicFramer::AppendPathChallengeFrame(const QuicPathChallengeFrame& frame,
5839 QuicDataWriter* writer) {
5840 if (!writer->WriteBytes(frame.data_buffer.data(), frame.data_buffer.size())) {
5841 set_detailed_error("Writing Path Challenge data failed.");
5842 return false;
5843 }
5844 return true;
5845}
5846
5847bool QuicFramer::AppendPathResponseFrame(const QuicPathResponseFrame& frame,
5848 QuicDataWriter* writer) {
5849 if (!writer->WriteBytes(frame.data_buffer.data(), frame.data_buffer.size())) {
5850 set_detailed_error("Writing Path Response data failed.");
5851 return false;
5852 }
5853 return true;
5854}
5855
5856// Add a new ietf-format stream reset frame.
5857// General format is
5858// stream id
5859// application error code
5860// final offset
5861bool QuicFramer::AppendIetfResetStreamFrame(const QuicRstStreamFrame& frame,
5862 QuicDataWriter* writer) {
5863 if (!writer->WriteVarInt62(static_cast<uint64_t>(frame.stream_id))) {
5864 set_detailed_error("Writing reset-stream stream id failed.");
5865 return false;
5866 }
fkastenholz07300e52019-07-16 11:51:37 -07005867 if (!writer->WriteVarInt62(static_cast<uint64_t>(frame.ietf_error_code))) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005868 set_detailed_error("Writing reset-stream error code failed.");
5869 return false;
5870 }
5871 if (!writer->WriteVarInt62(static_cast<uint64_t>(frame.byte_offset))) {
5872 set_detailed_error("Writing reset-stream final-offset failed.");
5873 return false;
5874 }
5875 return true;
5876}
5877
5878bool QuicFramer::ProcessIetfResetStreamFrame(QuicDataReader* reader,
5879 QuicRstStreamFrame* frame) {
5880 // Get Stream ID from frame. ReadVarIntStreamID returns false
5881 // if either A) there is a read error or B) the resulting value of
5882 // the Stream ID is larger than the maximum allowed value.
renjietangd077f8c2020-03-23 17:22:09 -07005883 if (!ReadUint32FromVarint62(reader, IETF_RST_STREAM, &frame->stream_id)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005884 return false;
5885 }
5886
bnc1b5ac122020-04-10 07:03:37 -07005887 if (!reader->ReadVarInt62(&frame->ietf_error_code)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005888 set_detailed_error("Unable to read rst stream error code.");
5889 return false;
5890 }
bnc1b5ac122020-04-10 07:03:37 -07005891
bnc1b5ac122020-04-10 07:03:37 -07005892 frame->error_code =
bnccb0ffbc2020-04-13 10:53:11 -07005893 IetfResetStreamErrorCodeToRstStreamErrorCode(frame->ietf_error_code);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005894
5895 if (!reader->ReadVarInt62(&frame->byte_offset)) {
5896 set_detailed_error("Unable to read rst stream sent byte offset.");
5897 return false;
5898 }
5899 return true;
5900}
5901
5902bool QuicFramer::ProcessStopSendingFrame(
5903 QuicDataReader* reader,
5904 QuicStopSendingFrame* stop_sending_frame) {
renjietangd077f8c2020-03-23 17:22:09 -07005905 if (!ReadUint32FromVarint62(reader, IETF_STOP_SENDING,
5906 &stop_sending_frame->stream_id)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005907 return false;
5908 }
5909
fkastenholz733552e2019-07-16 11:16:58 -07005910 uint64_t error_code;
5911 if (!reader->ReadVarInt62(&error_code)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005912 set_detailed_error("Unable to read stop sending application error code.");
5913 return false;
5914 }
fkastenholz733552e2019-07-16 11:16:58 -07005915 // TODO(fkastenholz): when error codes go to uint64_t, remove this.
5916 if (error_code > 0xffff) {
5917 stop_sending_frame->application_error_code = 0xffff;
5918 QUIC_DLOG(ERROR) << "Stop sending error code (" << error_code
5919 << ") > 0xffff";
5920 } else {
5921 stop_sending_frame->application_error_code =
5922 static_cast<uint16_t>(error_code);
5923 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05005924 return true;
5925}
5926
5927bool QuicFramer::AppendStopSendingFrame(
5928 const QuicStopSendingFrame& stop_sending_frame,
5929 QuicDataWriter* writer) {
5930 if (!writer->WriteVarInt62(stop_sending_frame.stream_id)) {
5931 set_detailed_error("Can not write stop sending stream id");
5932 return false;
5933 }
fkastenholz733552e2019-07-16 11:16:58 -07005934 if (!writer->WriteVarInt62(
5935 static_cast<uint64_t>(stop_sending_frame.application_error_code))) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005936 set_detailed_error("Can not write application error code");
5937 return false;
5938 }
5939 return true;
5940}
5941
5942// Append/process IETF-Format MAX_DATA Frame
5943bool QuicFramer::AppendMaxDataFrame(const QuicWindowUpdateFrame& frame,
5944 QuicDataWriter* writer) {
renjietangd088eab2019-11-21 14:54:41 -08005945 if (!writer->WriteVarInt62(frame.max_data)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005946 set_detailed_error("Can not write MAX_DATA byte-offset");
5947 return false;
5948 }
5949 return true;
5950}
5951
5952bool QuicFramer::ProcessMaxDataFrame(QuicDataReader* reader,
5953 QuicWindowUpdateFrame* frame) {
5954 frame->stream_id = QuicUtils::GetInvalidStreamId(transport_version());
renjietangd088eab2019-11-21 14:54:41 -08005955 if (!reader->ReadVarInt62(&frame->max_data)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005956 set_detailed_error("Can not read MAX_DATA byte-offset");
5957 return false;
5958 }
5959 return true;
5960}
5961
5962// Append/process IETF-Format MAX_STREAM_DATA Frame
5963bool QuicFramer::AppendMaxStreamDataFrame(const QuicWindowUpdateFrame& frame,
5964 QuicDataWriter* writer) {
5965 if (!writer->WriteVarInt62(frame.stream_id)) {
5966 set_detailed_error("Can not write MAX_STREAM_DATA stream id");
5967 return false;
5968 }
renjietangd088eab2019-11-21 14:54:41 -08005969 if (!writer->WriteVarInt62(frame.max_data)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005970 set_detailed_error("Can not write MAX_STREAM_DATA byte-offset");
5971 return false;
5972 }
5973 return true;
5974}
5975
5976bool QuicFramer::ProcessMaxStreamDataFrame(QuicDataReader* reader,
5977 QuicWindowUpdateFrame* frame) {
renjietangd077f8c2020-03-23 17:22:09 -07005978 if (!ReadUint32FromVarint62(reader, IETF_MAX_STREAM_DATA,
5979 &frame->stream_id)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005980 return false;
5981 }
renjietangd088eab2019-11-21 14:54:41 -08005982 if (!reader->ReadVarInt62(&frame->max_data)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005983 set_detailed_error("Can not read MAX_STREAM_DATA byte-count");
5984 return false;
5985 }
5986 return true;
5987}
5988
fkastenholz3c4eabf2019-04-22 07:49:59 -07005989bool QuicFramer::AppendMaxStreamsFrame(const QuicMaxStreamsFrame& frame,
QUICHE teama6ef0a62019-03-07 20:34:33 -05005990 QuicDataWriter* writer) {
fkastenholz3c4eabf2019-04-22 07:49:59 -07005991 if (!writer->WriteVarInt62(frame.stream_count)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005992 set_detailed_error("Can not write MAX_STREAMS stream count");
5993 return false;
5994 }
5995 return true;
5996}
5997
5998bool QuicFramer::ProcessMaxStreamsFrame(QuicDataReader* reader,
fkastenholz3c4eabf2019-04-22 07:49:59 -07005999 QuicMaxStreamsFrame* frame,
QUICHE teama6ef0a62019-03-07 20:34:33 -05006000 uint64_t frame_type) {
renjietangd077f8c2020-03-23 17:22:09 -07006001 if (!ReadUint32FromVarint62(reader,
6002 static_cast<QuicIetfFrameType>(frame_type),
6003 &frame->stream_count)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05006004 return false;
6005 }
fkastenholz3c4eabf2019-04-22 07:49:59 -07006006 frame->unidirectional = (frame_type == IETF_MAX_STREAMS_UNIDIRECTIONAL);
6007 return true;
QUICHE teama6ef0a62019-03-07 20:34:33 -05006008}
6009
renjietangf8a9c8c2020-03-19 16:47:03 -07006010bool QuicFramer::AppendDataBlockedFrame(const QuicBlockedFrame& frame,
QUICHE teama6ef0a62019-03-07 20:34:33 -05006011 QuicDataWriter* writer) {
6012 if (!writer->WriteVarInt62(frame.offset)) {
6013 set_detailed_error("Can not write blocked offset.");
6014 return false;
6015 }
6016 return true;
6017}
6018
renjietangf8a9c8c2020-03-19 16:47:03 -07006019bool QuicFramer::ProcessDataBlockedFrame(QuicDataReader* reader,
QUICHE teama6ef0a62019-03-07 20:34:33 -05006020 QuicBlockedFrame* frame) {
6021 // Indicates that it is a BLOCKED frame (as opposed to STREAM_BLOCKED).
6022 frame->stream_id = QuicUtils::GetInvalidStreamId(transport_version());
6023 if (!reader->ReadVarInt62(&frame->offset)) {
6024 set_detailed_error("Can not read blocked offset.");
6025 return false;
6026 }
6027 return true;
6028}
6029
renjietangf8a9c8c2020-03-19 16:47:03 -07006030bool QuicFramer::AppendStreamDataBlockedFrame(const QuicBlockedFrame& frame,
6031 QuicDataWriter* writer) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05006032 if (!writer->WriteVarInt62(frame.stream_id)) {
6033 set_detailed_error("Can not write stream blocked stream id.");
6034 return false;
6035 }
6036 if (!writer->WriteVarInt62(frame.offset)) {
6037 set_detailed_error("Can not write stream blocked offset.");
6038 return false;
6039 }
6040 return true;
6041}
6042
renjietangf8a9c8c2020-03-19 16:47:03 -07006043bool QuicFramer::ProcessStreamDataBlockedFrame(QuicDataReader* reader,
6044 QuicBlockedFrame* frame) {
renjietangd077f8c2020-03-23 17:22:09 -07006045 if (!ReadUint32FromVarint62(reader, IETF_STREAM_DATA_BLOCKED,
6046 &frame->stream_id)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05006047 return false;
6048 }
6049 if (!reader->ReadVarInt62(&frame->offset)) {
6050 set_detailed_error("Can not read stream blocked offset.");
6051 return false;
6052 }
6053 return true;
6054}
6055
fkastenholz3c4eabf2019-04-22 07:49:59 -07006056bool QuicFramer::AppendStreamsBlockedFrame(const QuicStreamsBlockedFrame& frame,
6057 QuicDataWriter* writer) {
6058 if (!writer->WriteVarInt62(frame.stream_count)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05006059 set_detailed_error("Can not write STREAMS_BLOCKED stream count");
6060 return false;
6061 }
6062 return true;
6063}
6064
6065bool QuicFramer::ProcessStreamsBlockedFrame(QuicDataReader* reader,
fkastenholz3c4eabf2019-04-22 07:49:59 -07006066 QuicStreamsBlockedFrame* frame,
QUICHE teama6ef0a62019-03-07 20:34:33 -05006067 uint64_t frame_type) {
renjietangd077f8c2020-03-23 17:22:09 -07006068 if (!ReadUint32FromVarint62(reader,
6069 static_cast<QuicIetfFrameType>(frame_type),
6070 &frame->stream_count)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05006071 return false;
6072 }
renjietangb885a122020-03-20 08:24:16 -07006073 if (frame->stream_count > QuicUtils::GetMaxStreamCount()) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05006074 // If stream count is such that the resulting stream ID would exceed our
6075 // implementation limit, generate an error.
6076 set_detailed_error(
6077 "STREAMS_BLOCKED stream count exceeds implementation limit.");
6078 return false;
6079 }
renjietangb885a122020-03-20 08:24:16 -07006080 frame->unidirectional = (frame_type == IETF_STREAMS_BLOCKED_UNIDIRECTIONAL);
fkastenholz3c4eabf2019-04-22 07:49:59 -07006081 return true;
QUICHE teama6ef0a62019-03-07 20:34:33 -05006082}
6083
6084bool QuicFramer::AppendNewConnectionIdFrame(
6085 const QuicNewConnectionIdFrame& frame,
6086 QuicDataWriter* writer) {
6087 if (!writer->WriteVarInt62(frame.sequence_number)) {
6088 set_detailed_error("Can not write New Connection ID sequence number");
6089 return false;
6090 }
fkastenholz1c19fc22019-07-12 11:06:19 -07006091 if (!writer->WriteVarInt62(frame.retire_prior_to)) {
6092 set_detailed_error("Can not write New Connection ID retire_prior_to");
6093 return false;
6094 }
dschinazicf5b1e22019-07-17 18:35:17 -07006095 if (!writer->WriteLengthPrefixedConnectionId(frame.connection_id)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05006096 set_detailed_error("Can not write New Connection ID frame connection ID");
6097 return false;
6098 }
6099
6100 if (!writer->WriteBytes(
6101 static_cast<const void*>(&frame.stateless_reset_token),
6102 sizeof(frame.stateless_reset_token))) {
6103 set_detailed_error("Can not write New Connection ID Reset Token");
6104 return false;
6105 }
6106 return true;
6107}
6108
6109bool QuicFramer::ProcessNewConnectionIdFrame(QuicDataReader* reader,
6110 QuicNewConnectionIdFrame* frame) {
6111 if (!reader->ReadVarInt62(&frame->sequence_number)) {
6112 set_detailed_error(
6113 "Unable to read new connection ID frame sequence number.");
6114 return false;
6115 }
6116
fkastenholz1c19fc22019-07-12 11:06:19 -07006117 if (!reader->ReadVarInt62(&frame->retire_prior_to)) {
6118 set_detailed_error(
6119 "Unable to read new connection ID frame retire_prior_to.");
6120 return false;
6121 }
6122 if (frame->retire_prior_to > frame->sequence_number) {
6123 set_detailed_error("Retire_prior_to > sequence_number.");
6124 return false;
6125 }
dschinazicf5b1e22019-07-17 18:35:17 -07006126
6127 if (!reader->ReadLengthPrefixedConnectionId(&frame->connection_id)) {
6128 set_detailed_error("Unable to read new connection ID frame connection id.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05006129 return false;
6130 }
6131
dschinazicf5b1e22019-07-17 18:35:17 -07006132 if (!QuicUtils::IsConnectionIdValidForVersion(frame->connection_id,
6133 transport_version())) {
QUICHE team0131a5b2019-03-20 15:23:27 -07006134 set_detailed_error("Invalid new connection ID length for version.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05006135 return false;
6136 }
6137
QUICHE teama6ef0a62019-03-07 20:34:33 -05006138 if (!reader->ReadBytes(&frame->stateless_reset_token,
6139 sizeof(frame->stateless_reset_token))) {
6140 set_detailed_error("Can not read new connection ID frame reset token.");
6141 return false;
6142 }
6143 return true;
6144}
6145
6146bool QuicFramer::AppendRetireConnectionIdFrame(
6147 const QuicRetireConnectionIdFrame& frame,
6148 QuicDataWriter* writer) {
6149 if (!writer->WriteVarInt62(frame.sequence_number)) {
6150 set_detailed_error("Can not write Retire Connection ID sequence number");
6151 return false;
6152 }
6153 return true;
6154}
6155
6156bool QuicFramer::ProcessRetireConnectionIdFrame(
6157 QuicDataReader* reader,
6158 QuicRetireConnectionIdFrame* frame) {
6159 if (!reader->ReadVarInt62(&frame->sequence_number)) {
6160 set_detailed_error(
6161 "Unable to read retire connection ID frame sequence number.");
6162 return false;
6163 }
6164 return true;
6165}
6166
renjietangd077f8c2020-03-23 17:22:09 -07006167bool QuicFramer::ReadUint32FromVarint62(QuicDataReader* reader,
6168 QuicIetfFrameType type,
6169 QuicStreamId* id) {
6170 uint64_t temp_uint64;
6171 if (!reader->ReadVarInt62(&temp_uint64)) {
6172 set_detailed_error("Unable to read " + QuicIetfFrameTypeString(type) +
6173 " frame stream id/count.");
6174 return false;
6175 }
6176 if (temp_uint64 > kMaxQuicStreamId) {
6177 set_detailed_error("Stream id/count of " + QuicIetfFrameTypeString(type) +
6178 "frame is too large.");
6179 return false;
6180 }
6181 *id = static_cast<uint32_t>(temp_uint64);
6182 return true;
6183}
6184
QUICHE teama6ef0a62019-03-07 20:34:33 -05006185uint8_t QuicFramer::GetStreamFrameTypeByte(const QuicStreamFrame& frame,
6186 bool last_frame_in_packet) const {
fkastenholz305e1732019-06-18 05:01:22 -07006187 if (VersionHasIetfQuicFrames(version_.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05006188 return GetIetfStreamFrameTypeByte(frame, last_frame_in_packet);
6189 }
6190 uint8_t type_byte = 0;
6191 // Fin bit.
6192 type_byte |= frame.fin ? kQuicStreamFinMask : 0;
6193
6194 // Data Length bit.
6195 type_byte <<= kQuicStreamDataLengthShift;
6196 type_byte |= last_frame_in_packet ? 0 : kQuicStreamDataLengthMask;
6197
6198 // Offset 3 bits.
6199 type_byte <<= kQuicStreamShift;
renjietang488201d2019-12-17 13:40:49 -08006200 const size_t offset_len = GetStreamOffsetSize(frame.offset);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006201 if (offset_len > 0) {
6202 type_byte |= offset_len - 1;
6203 }
6204
6205 // stream id 2 bits.
6206 type_byte <<= kQuicStreamIdShift;
6207 type_byte |= GetStreamIdSize(frame.stream_id) - 1;
6208 type_byte |= kQuicFrameTypeStreamMask; // Set Stream Frame Type to 1.
6209
6210 return type_byte;
6211}
6212
6213uint8_t QuicFramer::GetIetfStreamFrameTypeByte(
6214 const QuicStreamFrame& frame,
6215 bool last_frame_in_packet) const {
fkastenholz305e1732019-06-18 05:01:22 -07006216 DCHECK(VersionHasIetfQuicFrames(version_.transport_version));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006217 uint8_t type_byte = IETF_STREAM;
6218 if (!last_frame_in_packet) {
6219 type_byte |= IETF_STREAM_FRAME_LEN_BIT;
6220 }
6221 if (frame.offset != 0) {
6222 type_byte |= IETF_STREAM_FRAME_OFF_BIT;
6223 }
6224 if (frame.fin) {
6225 type_byte |= IETF_STREAM_FRAME_FIN_BIT;
6226 }
6227 return type_byte;
6228}
6229
6230void QuicFramer::InferPacketHeaderTypeFromVersion() {
6231 // This function should only be called when server connection negotiates the
6232 // version.
bncbe885272020-01-16 11:10:48 -08006233 DCHECK_EQ(perspective_, Perspective::IS_SERVER);
6234 DCHECK(!infer_packet_header_type_from_version_);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006235 infer_packet_header_type_from_version_ = true;
6236}
6237
QUICHE team10b22a12019-03-21 15:31:42 -07006238void QuicFramer::EnableMultiplePacketNumberSpacesSupport() {
6239 if (supports_multiple_packet_number_spaces_) {
6240 QUIC_BUG << "Multiple packet number spaces has already been enabled";
6241 return;
6242 }
6243 if (largest_packet_number_.IsInitialized()) {
6244 QUIC_BUG << "Try to enable multiple packet number spaces support after any "
6245 "packet has been received.";
6246 return;
6247 }
6248
6249 supports_multiple_packet_number_spaces_ = true;
6250}
6251
fayangccbab732019-05-13 10:11:25 -07006252// static
dschinazi48ac9192019-07-31 00:07:26 -07006253QuicErrorCode QuicFramer::ParsePublicHeaderDispatcher(
6254 const QuicEncryptedPacket& packet,
6255 uint8_t expected_destination_connection_id_length,
6256 PacketHeaderFormat* format,
fayange3f2f7b2019-09-19 17:01:57 -07006257 QuicLongHeaderType* long_packet_type,
dschinazi48ac9192019-07-31 00:07:26 -07006258 bool* version_present,
6259 bool* has_length_prefix,
6260 QuicVersionLabel* version_label,
6261 ParsedQuicVersion* parsed_version,
6262 QuicConnectionId* destination_connection_id,
6263 QuicConnectionId* source_connection_id,
6264 bool* retry_token_present,
dmcardlecf0bfcf2019-12-13 08:08:21 -08006265 quiche::QuicheStringPiece* retry_token,
dschinazi48ac9192019-07-31 00:07:26 -07006266 std::string* detailed_error) {
6267 QuicDataReader reader(packet.data(), packet.length());
6268 if (reader.IsDoneReading()) {
6269 *detailed_error = "Unable to read first byte.";
6270 return QUIC_INVALID_PACKET_HEADER;
6271 }
6272 const uint8_t first_byte = reader.PeekByte();
6273 const bool ietf_format = QuicUtils::IsIetfPacketHeader(first_byte);
6274 uint8_t unused_first_byte;
6275 QuicVariableLengthIntegerLength retry_token_length_length;
fayange3f2f7b2019-09-19 17:01:57 -07006276 QuicErrorCode error_code = ParsePublicHeader(
dschinazi48ac9192019-07-31 00:07:26 -07006277 &reader, expected_destination_connection_id_length, ietf_format,
6278 &unused_first_byte, format, version_present, has_length_prefix,
6279 version_label, parsed_version, destination_connection_id,
fayange3f2f7b2019-09-19 17:01:57 -07006280 source_connection_id, long_packet_type, &retry_token_length_length,
dschinazi48ac9192019-07-31 00:07:26 -07006281 retry_token, detailed_error);
6282 *retry_token_present =
6283 retry_token_length_length != VARIABLE_LENGTH_INTEGER_LENGTH_0;
6284 return error_code;
6285}
6286
6287// static
6288QuicErrorCode QuicFramer::ParsePublicHeaderGoogleQuic(
6289 QuicDataReader* reader,
6290 uint8_t* first_byte,
6291 PacketHeaderFormat* format,
6292 bool* version_present,
6293 QuicVersionLabel* version_label,
dschinazi243eabc2019-08-05 16:15:29 -07006294 ParsedQuicVersion* parsed_version,
dschinazi48ac9192019-07-31 00:07:26 -07006295 QuicConnectionId* destination_connection_id,
6296 std::string* detailed_error) {
6297 *format = GOOGLE_QUIC_PACKET;
6298 *version_present = (*first_byte & PACKET_PUBLIC_FLAGS_VERSION) != 0;
6299 uint8_t destination_connection_id_length = 0;
6300 if ((*first_byte & PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID) != 0) {
6301 destination_connection_id_length = kQuicDefaultConnectionIdLength;
6302 }
6303 if (!reader->ReadConnectionId(destination_connection_id,
6304 destination_connection_id_length)) {
6305 *detailed_error = "Unable to read ConnectionId.";
6306 return QUIC_INVALID_PACKET_HEADER;
6307 }
dschinazi243eabc2019-08-05 16:15:29 -07006308 if (*version_present) {
6309 if (!ProcessVersionLabel(reader, version_label)) {
6310 *detailed_error = "Unable to read protocol version.";
6311 return QUIC_INVALID_PACKET_HEADER;
6312 }
6313 *parsed_version = ParseQuicVersionLabel(*version_label);
dschinazi48ac9192019-07-31 00:07:26 -07006314 }
6315 return QUIC_NO_ERROR;
6316}
6317
6318namespace {
6319
dschinazi81eb4e02019-09-27 17:12:17 -07006320const QuicVersionLabel kProxVersionLabel = 0x50524F58; // "PROX"
6321
dschinazi48ac9192019-07-31 00:07:26 -07006322inline bool PacketHasLengthPrefixedConnectionIds(
6323 const QuicDataReader& reader,
6324 ParsedQuicVersion parsed_version,
6325 QuicVersionLabel version_label,
6326 uint8_t first_byte) {
dschinazi5c1d7d82020-07-29 16:42:50 -07006327 if (parsed_version.IsKnown()) {
dschinazi48ac9192019-07-31 00:07:26 -07006328 return parsed_version.HasLengthPrefixedConnectionIds();
6329 }
6330
6331 // Received unsupported version, check known old unsupported versions.
6332 if (QuicVersionLabelUses4BitConnectionIdLength(version_label)) {
6333 return false;
6334 }
6335
6336 // Received unknown version, check connection ID length byte.
6337 if (reader.IsDoneReading()) {
6338 // This check is required to safely peek the connection ID length byte.
6339 return true;
6340 }
6341 const uint8_t connection_id_length_byte = reader.PeekByte();
6342
6343 // Check for packets produced by older versions of
6344 // QuicFramer::WriteClientVersionNegotiationProbePacket
6345 if (first_byte == 0xc0 && (connection_id_length_byte & 0x0f) == 0 &&
6346 connection_id_length_byte >= 0x50 && version_label == 0xcabadaba) {
6347 return false;
6348 }
6349
6350 // Check for munged packets with version tag PROX.
6351 if ((connection_id_length_byte & 0x0f) == 0 &&
dschinazi81eb4e02019-09-27 17:12:17 -07006352 connection_id_length_byte >= 0x20 && version_label == kProxVersionLabel) {
dschinazi48ac9192019-07-31 00:07:26 -07006353 return false;
6354 }
6355
6356 return true;
6357}
6358
6359inline bool ParseLongHeaderConnectionIds(
6360 QuicDataReader* reader,
6361 bool has_length_prefix,
dschinazi81eb4e02019-09-27 17:12:17 -07006362 QuicVersionLabel version_label,
dschinazi48ac9192019-07-31 00:07:26 -07006363 QuicConnectionId* destination_connection_id,
6364 QuicConnectionId* source_connection_id,
6365 std::string* detailed_error) {
6366 if (has_length_prefix) {
6367 if (!reader->ReadLengthPrefixedConnectionId(destination_connection_id)) {
6368 *detailed_error = "Unable to read destination connection ID.";
6369 return false;
6370 }
6371 if (!reader->ReadLengthPrefixedConnectionId(source_connection_id)) {
dschinazi68fad8e2019-11-04 10:07:21 -08006372 if (version_label == kProxVersionLabel) {
dschinazi81eb4e02019-09-27 17:12:17 -07006373 // The "PROX" version does not follow the length-prefixed invariants,
6374 // and can therefore attempt to read a payload byte and interpret it
6375 // as the source connection ID length, which could fail to parse.
6376 // In that scenario we keep the source connection ID empty but mark
6377 // parsing as successful.
6378 return true;
6379 }
dschinazi48ac9192019-07-31 00:07:26 -07006380 *detailed_error = "Unable to read source connection ID.";
6381 return false;
6382 }
6383 } else {
6384 // Parse connection ID lengths.
6385 uint8_t connection_id_lengths_byte;
6386 if (!reader->ReadUInt8(&connection_id_lengths_byte)) {
6387 *detailed_error = "Unable to read connection ID lengths.";
6388 return false;
6389 }
6390 uint8_t destination_connection_id_length =
6391 (connection_id_lengths_byte & kDestinationConnectionIdLengthMask) >> 4;
6392 if (destination_connection_id_length != 0) {
6393 destination_connection_id_length += kConnectionIdLengthAdjustment;
6394 }
6395 uint8_t source_connection_id_length =
6396 connection_id_lengths_byte & kSourceConnectionIdLengthMask;
6397 if (source_connection_id_length != 0) {
6398 source_connection_id_length += kConnectionIdLengthAdjustment;
6399 }
6400
6401 // Read destination connection ID.
6402 if (!reader->ReadConnectionId(destination_connection_id,
6403 destination_connection_id_length)) {
6404 *detailed_error = "Unable to read destination connection ID.";
6405 return false;
6406 }
6407
6408 // Read source connection ID.
6409 if (!reader->ReadConnectionId(source_connection_id,
6410 source_connection_id_length)) {
6411 *detailed_error = "Unable to read source connection ID.";
6412 return false;
6413 }
6414 }
6415 return true;
6416}
6417
6418} // namespace
6419
6420// static
6421QuicErrorCode QuicFramer::ParsePublicHeader(
6422 QuicDataReader* reader,
6423 uint8_t expected_destination_connection_id_length,
6424 bool ietf_format,
6425 uint8_t* first_byte,
6426 PacketHeaderFormat* format,
6427 bool* version_present,
6428 bool* has_length_prefix,
6429 QuicVersionLabel* version_label,
6430 ParsedQuicVersion* parsed_version,
6431 QuicConnectionId* destination_connection_id,
6432 QuicConnectionId* source_connection_id,
6433 QuicLongHeaderType* long_packet_type,
6434 QuicVariableLengthIntegerLength* retry_token_length_length,
dmcardlecf0bfcf2019-12-13 08:08:21 -08006435 quiche::QuicheStringPiece* retry_token,
dschinazi48ac9192019-07-31 00:07:26 -07006436 std::string* detailed_error) {
6437 *version_present = false;
6438 *has_length_prefix = false;
6439 *version_label = 0;
6440 *parsed_version = UnsupportedQuicVersion();
6441 *source_connection_id = EmptyQuicConnectionId();
6442 *long_packet_type = INVALID_PACKET_TYPE;
6443 *retry_token_length_length = VARIABLE_LENGTH_INTEGER_LENGTH_0;
dmcardlecf0bfcf2019-12-13 08:08:21 -08006444 *retry_token = quiche::QuicheStringPiece();
dschinazi48ac9192019-07-31 00:07:26 -07006445 *detailed_error = "";
6446
6447 if (!reader->ReadUInt8(first_byte)) {
6448 *detailed_error = "Unable to read first byte.";
6449 return QUIC_INVALID_PACKET_HEADER;
6450 }
6451
6452 if (!ietf_format) {
6453 return ParsePublicHeaderGoogleQuic(
6454 reader, first_byte, format, version_present, version_label,
dschinazi243eabc2019-08-05 16:15:29 -07006455 parsed_version, destination_connection_id, detailed_error);
dschinazi48ac9192019-07-31 00:07:26 -07006456 }
6457
6458 *format = GetIetfPacketHeaderFormat(*first_byte);
6459
6460 if (*format == IETF_QUIC_SHORT_HEADER_PACKET) {
6461 // Read destination connection ID using
6462 // expected_destination_connection_id_length to determine its length.
6463 if (!reader->ReadConnectionId(destination_connection_id,
6464 expected_destination_connection_id_length)) {
6465 *detailed_error = "Unable to read destination connection ID.";
6466 return QUIC_INVALID_PACKET_HEADER;
6467 }
6468 return QUIC_NO_ERROR;
6469 }
6470
6471 DCHECK_EQ(IETF_QUIC_LONG_HEADER_PACKET, *format);
6472 *version_present = true;
6473 if (!ProcessVersionLabel(reader, version_label)) {
6474 *detailed_error = "Unable to read protocol version.";
6475 return QUIC_INVALID_PACKET_HEADER;
6476 }
6477
6478 if (*version_label == 0) {
6479 *long_packet_type = VERSION_NEGOTIATION;
6480 }
6481
6482 // Parse version.
6483 *parsed_version = ParseQuicVersionLabel(*version_label);
6484
6485 // Figure out which IETF QUIC invariants this packet follows.
6486 *has_length_prefix = PacketHasLengthPrefixedConnectionIds(
6487 *reader, *parsed_version, *version_label, *first_byte);
6488
6489 // Parse connection IDs.
dschinazi81eb4e02019-09-27 17:12:17 -07006490 if (!ParseLongHeaderConnectionIds(reader, *has_length_prefix, *version_label,
dschinazi48ac9192019-07-31 00:07:26 -07006491 destination_connection_id,
6492 source_connection_id, detailed_error)) {
6493 return QUIC_INVALID_PACKET_HEADER;
6494 }
6495
dschinazi5c1d7d82020-07-29 16:42:50 -07006496 if (!parsed_version->IsKnown()) {
dschinazi48ac9192019-07-31 00:07:26 -07006497 // Skip parsing of long packet type and retry token for unknown versions.
6498 return QUIC_NO_ERROR;
6499 }
6500
6501 // Parse long packet type.
fayang36825da2019-08-21 14:01:27 -07006502 if (!GetLongHeaderType(*first_byte, long_packet_type)) {
dschinazi48ac9192019-07-31 00:07:26 -07006503 *detailed_error = "Unable to parse long packet type.";
6504 return QUIC_INVALID_PACKET_HEADER;
6505 }
6506
6507 if (!parsed_version->SupportsRetry() || *long_packet_type != INITIAL) {
6508 // Retry token is only present on initial packets for some versions.
6509 return QUIC_NO_ERROR;
6510 }
6511
6512 *retry_token_length_length = reader->PeekVarInt62Length();
6513 uint64_t retry_token_length;
6514 if (!reader->ReadVarInt62(&retry_token_length)) {
6515 *retry_token_length_length = VARIABLE_LENGTH_INTEGER_LENGTH_0;
6516 *detailed_error = "Unable to read retry token length.";
6517 return QUIC_INVALID_PACKET_HEADER;
6518 }
6519
6520 if (!reader->ReadStringPiece(retry_token, retry_token_length)) {
6521 *detailed_error = "Unable to read retry token.";
6522 return QUIC_INVALID_PACKET_HEADER;
6523 }
6524
6525 return QUIC_NO_ERROR;
6526}
6527
6528// static
dschinazide0f6dc2019-05-15 16:10:11 -07006529bool QuicFramer::WriteClientVersionNegotiationProbePacket(
6530 char* packet_bytes,
6531 QuicByteCount packet_length,
6532 const char* destination_connection_id_bytes,
6533 uint8_t destination_connection_id_length) {
6534 if (packet_bytes == nullptr) {
6535 QUIC_BUG << "Invalid packet_bytes";
6536 return false;
6537 }
6538 if (packet_length < kMinPacketSizeForVersionNegotiation ||
6539 packet_length > 65535) {
6540 QUIC_BUG << "Invalid packet_length";
6541 return false;
6542 }
dschinazib012d212019-08-01 18:07:26 -07006543 if (destination_connection_id_length > kQuicMaxConnectionId4BitLength ||
dschinazi19dc2b52019-07-17 19:54:43 -07006544 destination_connection_id_length <
6545 kQuicMinimumInitialConnectionIdLength) {
dschinazide0f6dc2019-05-15 16:10:11 -07006546 QUIC_BUG << "Invalid connection_id_length";
6547 return false;
6548 }
dschinazi48ac9192019-07-31 00:07:26 -07006549 const bool use_length_prefix =
6550 GetQuicFlag(FLAGS_quic_prober_uses_length_prefixed_connection_ids);
6551 const uint8_t last_version_byte = use_length_prefix ? 0xda : 0xba;
dschinazide0f6dc2019-05-15 16:10:11 -07006552 // clang-format off
dschinazi48ac9192019-07-31 00:07:26 -07006553 const unsigned char packet_start_bytes[] = {
dschinazide0f6dc2019-05-15 16:10:11 -07006554 // IETF long header with fixed bit set, type initial, all-0 encrypted bits.
6555 0xc0,
6556 // Version, part of the IETF space reserved for negotiation.
6557 // This intentionally differs from QuicVersionReservedForNegotiation()
6558 // to allow differentiating them over the wire.
dschinazi48ac9192019-07-31 00:07:26 -07006559 0xca, 0xba, 0xda, last_version_byte,
dschinazide0f6dc2019-05-15 16:10:11 -07006560 };
6561 // clang-format on
6562 static_assert(sizeof(packet_start_bytes) == 5, "bad packet_start_bytes size");
6563 QuicDataWriter writer(packet_length, packet_bytes);
6564 if (!writer.WriteBytes(packet_start_bytes, sizeof(packet_start_bytes))) {
6565 QUIC_BUG << "Failed to write packet start";
6566 return false;
6567 }
6568
6569 QuicConnectionId destination_connection_id(destination_connection_id_bytes,
6570 destination_connection_id_length);
dschinazi48ac9192019-07-31 00:07:26 -07006571 if (!AppendIetfConnectionIds(
6572 /*version_flag=*/true, use_length_prefix, destination_connection_id,
6573 EmptyQuicConnectionId(), &writer)) {
dschinazide0f6dc2019-05-15 16:10:11 -07006574 QUIC_BUG << "Failed to write connection IDs";
6575 return false;
6576 }
6577 // Add 8 bytes of zeroes followed by 8 bytes of ones to ensure that this does
6578 // not parse with any known version. The zeroes make sure that packet numbers,
6579 // retry token lengths and payload lengths are parsed as zero, and if the
6580 // zeroes are treated as padding frames, 0xff is known to not parse as a
6581 // valid frame type.
6582 if (!writer.WriteUInt64(0) ||
6583 !writer.WriteUInt64(std::numeric_limits<uint64_t>::max())) {
6584 QUIC_BUG << "Failed to write 18 bytes";
6585 return false;
6586 }
6587 // Make sure the polite greeting below is padded to a 16-byte boundary to
6588 // make it easier to read in tcpdump.
6589 while (writer.length() % 16 != 0) {
6590 if (!writer.WriteUInt8(0)) {
6591 QUIC_BUG << "Failed to write padding byte";
6592 return false;
6593 }
6594 }
6595 // Add a polite greeting in case a human sees this in tcpdump.
6596 static const char polite_greeting[] =
6597 "This packet only exists to trigger IETF QUIC version negotiation. "
6598 "Please respond with a Version Negotiation packet indicating what "
6599 "versions you support. Thank you and have a nice day.";
6600 if (!writer.WriteBytes(polite_greeting, sizeof(polite_greeting))) {
6601 QUIC_BUG << "Failed to write polite greeting";
6602 return false;
6603 }
6604 // Fill the rest of the packet with zeroes.
6605 writer.WritePadding();
6606 DCHECK_EQ(0u, writer.remaining());
6607 return true;
6608}
6609
6610// static
6611bool QuicFramer::ParseServerVersionNegotiationProbeResponse(
6612 const char* packet_bytes,
6613 QuicByteCount packet_length,
6614 char* source_connection_id_bytes,
6615 uint8_t* source_connection_id_length_out,
6616 std::string* detailed_error) {
6617 if (detailed_error == nullptr) {
6618 QUIC_BUG << "Invalid error_details";
6619 return false;
6620 }
6621 *detailed_error = "";
6622 if (packet_bytes == nullptr) {
6623 *detailed_error = "Invalid packet_bytes";
6624 return false;
6625 }
6626 if (packet_length < 6) {
6627 *detailed_error = "Invalid packet_length";
6628 return false;
6629 }
6630 if (source_connection_id_bytes == nullptr) {
6631 *detailed_error = "Invalid source_connection_id_bytes";
6632 return false;
6633 }
6634 if (source_connection_id_length_out == nullptr) {
6635 *detailed_error = "Invalid source_connection_id_length_out";
6636 return false;
6637 }
6638 QuicDataReader reader(packet_bytes, packet_length);
6639 uint8_t type_byte = 0;
6640 if (!reader.ReadUInt8(&type_byte)) {
6641 *detailed_error = "Failed to read type byte";
6642 return false;
6643 }
6644 if ((type_byte & 0x80) == 0) {
6645 *detailed_error = "Packet does not have long header";
6646 return false;
6647 }
6648 uint32_t version = 0;
6649 if (!reader.ReadUInt32(&version)) {
6650 *detailed_error = "Failed to read version";
6651 return false;
6652 }
6653 if (version != 0) {
6654 *detailed_error = "Packet is not a version negotiation packet";
6655 return false;
6656 }
dschinazi48ac9192019-07-31 00:07:26 -07006657 const bool use_length_prefix =
6658 GetQuicFlag(FLAGS_quic_prober_uses_length_prefixed_connection_ids);
dschinazide0f6dc2019-05-15 16:10:11 -07006659 QuicConnectionId destination_connection_id, source_connection_id;
dschinazi48ac9192019-07-31 00:07:26 -07006660 if (use_length_prefix) {
6661 if (!reader.ReadLengthPrefixedConnectionId(&destination_connection_id)) {
6662 *detailed_error = "Failed to read destination connection ID";
6663 return false;
6664 }
6665 if (!reader.ReadLengthPrefixedConnectionId(&source_connection_id)) {
6666 *detailed_error = "Failed to read source connection ID";
6667 return false;
6668 }
6669 } else {
6670 uint8_t expected_server_connection_id_length = 0,
6671 destination_connection_id_length = 0,
6672 source_connection_id_length = 0;
6673 if (!ProcessAndValidateIetfConnectionIdLength(
6674 &reader, UnsupportedQuicVersion(), Perspective::IS_CLIENT,
6675 /*should_update_expected_server_connection_id_length=*/true,
6676 &expected_server_connection_id_length,
6677 &destination_connection_id_length, &source_connection_id_length,
6678 detailed_error)) {
6679 return false;
6680 }
6681 if (!reader.ReadConnectionId(&destination_connection_id,
6682 destination_connection_id_length)) {
6683 *detailed_error = "Failed to read destination connection ID";
6684 return false;
6685 }
6686 if (!reader.ReadConnectionId(&source_connection_id,
6687 source_connection_id_length)) {
6688 *detailed_error = "Failed to read source connection ID";
6689 return false;
6690 }
dschinazide0f6dc2019-05-15 16:10:11 -07006691 }
dschinazi48ac9192019-07-31 00:07:26 -07006692
6693 if (destination_connection_id.length() != 0) {
6694 *detailed_error = "Received unexpected destination connection ID length";
dschinazide0f6dc2019-05-15 16:10:11 -07006695 return false;
6696 }
6697
6698 memcpy(source_connection_id_bytes, source_connection_id.data(),
dschinazi48ac9192019-07-31 00:07:26 -07006699 source_connection_id.length());
6700 *source_connection_id_length_out = source_connection_id.length();
dschinazide0f6dc2019-05-15 16:10:11 -07006701
6702 return true;
6703}
6704
fkastenholzb4dade72019-08-05 06:54:20 -07006705// Look for and parse the error code from the "<quic_error_code>:" text that
6706// may be present at the start of the CONNECTION_CLOSE error details string.
6707// This text, inserted by the peer if it's using Google's QUIC implementation,
6708// contains additional error information that narrows down the exact error. If
6709// the string is not found, or is not properly formed, it returns
6710// ErrorCode::QUIC_IETF_GQUIC_ERROR_MISSING
fkastenholz488a4622019-08-26 06:24:46 -07006711void MaybeExtractQuicErrorCode(QuicConnectionCloseFrame* frame) {
dmcardlecf0bfcf2019-12-13 08:08:21 -08006712 std::vector<quiche::QuicheStringPiece> ed =
6713 quiche::QuicheTextUtils::Split(frame->error_details, ':');
fkastenholzb4dade72019-08-05 06:54:20 -07006714 uint64_t extracted_error_code;
dmcardlecf0bfcf2019-12-13 08:08:21 -08006715 if (ed.size() < 2 || !quiche::QuicheTextUtils::IsAllDigits(ed[0]) ||
6716 !quiche::QuicheTextUtils::StringToUint64(ed[0], &extracted_error_code)) {
dschinazidce90b02019-10-14 18:19:54 -07006717 if (frame->close_type == IETF_QUIC_TRANSPORT_CONNECTION_CLOSE &&
bnc77e77b82020-04-05 10:36:49 -07006718 frame->wire_error_code == NO_IETF_QUIC_ERROR) {
6719 frame->quic_error_code = QUIC_NO_ERROR;
dschinazidce90b02019-10-14 18:19:54 -07006720 } else {
bnc77e77b82020-04-05 10:36:49 -07006721 frame->quic_error_code = QUIC_IETF_GQUIC_ERROR_MISSING;
dschinazidce90b02019-10-14 18:19:54 -07006722 }
fkastenholz488a4622019-08-26 06:24:46 -07006723 return;
fkastenholzb4dade72019-08-05 06:54:20 -07006724 }
fkastenholz488a4622019-08-26 06:24:46 -07006725 // Return the error code (numeric) and the error details string without the
6726 // error code prefix. Note that Split returns everything up to, but not
6727 // including, the split character, so the length of ed[0] is just the number
6728 // of digits in the error number. In removing the prefix, 1 is added to the
6729 // length to account for the :
dmcardlecf0bfcf2019-12-13 08:08:21 -08006730 quiche::QuicheStringPiece x = quiche::QuicheStringPiece(frame->error_details);
fkastenholz488a4622019-08-26 06:24:46 -07006731 x.remove_prefix(ed[0].length() + 1);
6732 frame->error_details = std::string(x);
bnc77e77b82020-04-05 10:36:49 -07006733 frame->quic_error_code = static_cast<QuicErrorCode>(extracted_error_code);
fkastenholzb4dade72019-08-05 06:54:20 -07006734}
6735
QUICHE teama6ef0a62019-03-07 20:34:33 -05006736#undef ENDPOINT // undef for jumbo builds
6737} // namespace quic