blob: e33dc00d21118823df187c253424ce41931bdb99 [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>
9#include <memory>
vasilvv872e7a32019-03-12 16:42:44 -070010#include <string>
QUICHE teama6ef0a62019-03-07 20:34:33 -050011
12#include "net/third_party/quiche/src/quic/core/crypto/crypto_framer.h"
nharper55fa6132019-05-07 19:37:21 -070013#include "net/third_party/quiche/src/quic/core/crypto/crypto_handshake.h"
QUICHE teama6ef0a62019-03-07 20:34:33 -050014#include "net/third_party/quiche/src/quic/core/crypto/crypto_handshake_message.h"
15#include "net/third_party/quiche/src/quic/core/crypto/crypto_protocol.h"
nharper55fa6132019-05-07 19:37:21 -070016#include "net/third_party/quiche/src/quic/core/crypto/crypto_utils.h"
QUICHE teama6ef0a62019-03-07 20:34:33 -050017#include "net/third_party/quiche/src/quic/core/crypto/null_decrypter.h"
18#include "net/third_party/quiche/src/quic/core/crypto/null_encrypter.h"
19#include "net/third_party/quiche/src/quic/core/crypto/quic_decrypter.h"
20#include "net/third_party/quiche/src/quic/core/crypto/quic_encrypter.h"
21#include "net/third_party/quiche/src/quic/core/crypto/quic_random.h"
22#include "net/third_party/quiche/src/quic/core/quic_connection_id.h"
23#include "net/third_party/quiche/src/quic/core/quic_constants.h"
24#include "net/third_party/quiche/src/quic/core/quic_data_reader.h"
25#include "net/third_party/quiche/src/quic/core/quic_data_writer.h"
ianswett97b690b2019-05-02 15:12:43 -070026#include "net/third_party/quiche/src/quic/core/quic_error_codes.h"
dschinazib953d022019-08-01 18:05:58 -070027#include "net/third_party/quiche/src/quic/core/quic_packets.h"
QUICHE teama6ef0a62019-03-07 20:34:33 -050028#include "net/third_party/quiche/src/quic/core/quic_socket_address_coder.h"
29#include "net/third_party/quiche/src/quic/core/quic_stream_frame_data_producer.h"
30#include "net/third_party/quiche/src/quic/core/quic_types.h"
31#include "net/third_party/quiche/src/quic/core/quic_utils.h"
32#include "net/third_party/quiche/src/quic/core/quic_versions.h"
33#include "net/third_party/quiche/src/quic/platform/api/quic_aligned.h"
dschinazie8d7fa72019-04-05 14:44:40 -070034#include "net/third_party/quiche/src/quic/platform/api/quic_arraysize.h"
QUICHE teama6ef0a62019-03-07 20:34:33 -050035#include "net/third_party/quiche/src/quic/platform/api/quic_bug_tracker.h"
36#include "net/third_party/quiche/src/quic/platform/api/quic_client_stats.h"
QUICHE teama6ef0a62019-03-07 20:34:33 -050037#include "net/third_party/quiche/src/quic/platform/api/quic_fallthrough.h"
38#include "net/third_party/quiche/src/quic/platform/api/quic_flag_utils.h"
39#include "net/third_party/quiche/src/quic/platform/api/quic_flags.h"
40#include "net/third_party/quiche/src/quic/platform/api/quic_logging.h"
41#include "net/third_party/quiche/src/quic/platform/api/quic_map_util.h"
42#include "net/third_party/quiche/src/quic/platform/api/quic_ptr_util.h"
43#include "net/third_party/quiche/src/quic/platform/api/quic_stack_trace.h"
44#include "net/third_party/quiche/src/quic/platform/api/quic_str_cat.h"
QUICHE teama6ef0a62019-03-07 20:34:33 -050045#include "net/third_party/quiche/src/quic/platform/api/quic_text_utils.h"
46
47namespace quic {
48
49namespace {
50
51#define ENDPOINT \
52 (perspective_ == Perspective::IS_SERVER ? "Server: " : "Client: ")
53
QUICHE teama6ef0a62019-03-07 20:34:33 -050054// Number of bits the packet number length bits are shifted from the right
55// edge of the header.
56const uint8_t kPublicHeaderSequenceNumberShift = 4;
57
58// There are two interpretations for the Frame Type byte in the QUIC protocol,
59// resulting in two Frame Types: Special Frame Types and Regular Frame Types.
60//
61// Regular Frame Types use the Frame Type byte simply. Currently defined
62// Regular Frame Types are:
63// Padding : 0b 00000000 (0x00)
64// ResetStream : 0b 00000001 (0x01)
65// ConnectionClose : 0b 00000010 (0x02)
66// GoAway : 0b 00000011 (0x03)
67// WindowUpdate : 0b 00000100 (0x04)
68// Blocked : 0b 00000101 (0x05)
69//
70// Special Frame Types encode both a Frame Type and corresponding flags
71// all in the Frame Type byte. Currently defined Special Frame Types
72// are:
73// Stream : 0b 1xxxxxxx
74// Ack : 0b 01xxxxxx
75//
76// Semantics of the flag bits above (the x bits) depends on the frame type.
77
78// Masks to determine if the frame type is a special use
79// and for specific special frame types.
80const uint8_t kQuicFrameTypeBrokenMask = 0xE0; // 0b 11100000
81const uint8_t kQuicFrameTypeSpecialMask = 0xC0; // 0b 11000000
82const uint8_t kQuicFrameTypeStreamMask = 0x80;
83const uint8_t kQuicFrameTypeAckMask = 0x40;
84static_assert(kQuicFrameTypeSpecialMask ==
85 (kQuicFrameTypeStreamMask | kQuicFrameTypeAckMask),
86 "Invalid kQuicFrameTypeSpecialMask");
87
88// The stream type format is 1FDOOOSS, where
89// F is the fin bit.
90// D is the data length bit (0 or 2 bytes).
91// OO/OOO are the size of the offset.
92// SS is the size of the stream ID.
93// Note that the stream encoding can not be determined by inspection. It can
94// be determined only by knowing the QUIC Version.
95// Stream frame relative shifts and masks for interpreting the stream flags.
96// StreamID may be 1, 2, 3, or 4 bytes.
97const uint8_t kQuicStreamIdShift = 2;
98const uint8_t kQuicStreamIDLengthMask = 0x03;
99
100// Offset may be 0, 2, 4, or 8 bytes.
101const uint8_t kQuicStreamShift = 3;
102const uint8_t kQuicStreamOffsetMask = 0x07;
103
104// Data length may be 0 or 2 bytes.
105const uint8_t kQuicStreamDataLengthShift = 1;
106const uint8_t kQuicStreamDataLengthMask = 0x01;
107
108// Fin bit may be set or not.
109const uint8_t kQuicStreamFinShift = 1;
110const uint8_t kQuicStreamFinMask = 0x01;
111
112// The format is 01M0LLOO, where
113// M if set, there are multiple ack blocks in the frame.
114// LL is the size of the largest ack field.
115// OO is the size of the ack blocks offset field.
116// packet number size shift used in AckFrames.
117const uint8_t kQuicSequenceNumberLengthNumBits = 2;
118const uint8_t kActBlockLengthOffset = 0;
119const uint8_t kLargestAckedOffset = 2;
120
121// Acks may have only one ack block.
122const uint8_t kQuicHasMultipleAckBlocksOffset = 5;
123
124// Timestamps are 4 bytes followed by 2 bytes.
125const uint8_t kQuicNumTimestampsLength = 1;
126const uint8_t kQuicFirstTimestampLength = 4;
127const uint8_t kQuicTimestampLength = 2;
128// Gaps between packet numbers are 1 byte.
129const uint8_t kQuicTimestampPacketNumberGapLength = 1;
130
131// Maximum length of encoded error strings.
132const int kMaxErrorStringLength = 256;
133
134const uint8_t kConnectionIdLengthAdjustment = 3;
135const uint8_t kDestinationConnectionIdLengthMask = 0xF0;
136const uint8_t kSourceConnectionIdLengthMask = 0x0F;
137
138// Returns the absolute value of the difference between |a| and |b|.
139uint64_t Delta(uint64_t a, uint64_t b) {
140 // Since these are unsigned numbers, we can't just return abs(a - b)
141 if (a < b) {
142 return b - a;
143 }
144 return a - b;
145}
146
147uint64_t ClosestTo(uint64_t target, uint64_t a, uint64_t b) {
148 return (Delta(target, a) < Delta(target, b)) ? a : b;
149}
150
151uint64_t PacketNumberIntervalLength(
152 const QuicInterval<QuicPacketNumber>& interval) {
153 if (interval.Empty()) {
154 return 0u;
155 }
156 return interval.max() - interval.min();
157}
158
159QuicPacketNumberLength ReadSequenceNumberLength(uint8_t flags) {
160 switch (flags & PACKET_FLAGS_8BYTE_PACKET) {
161 case PACKET_FLAGS_8BYTE_PACKET:
162 return PACKET_6BYTE_PACKET_NUMBER;
163 case PACKET_FLAGS_4BYTE_PACKET:
164 return PACKET_4BYTE_PACKET_NUMBER;
165 case PACKET_FLAGS_2BYTE_PACKET:
166 return PACKET_2BYTE_PACKET_NUMBER;
167 case PACKET_FLAGS_1BYTE_PACKET:
168 return PACKET_1BYTE_PACKET_NUMBER;
169 default:
170 QUIC_BUG << "Unreachable case statement.";
171 return PACKET_6BYTE_PACKET_NUMBER;
172 }
173}
174
dschinazi17d42422019-06-18 16:35:07 -0700175QuicPacketNumberLength ReadAckPacketNumberLength(
176 QuicTransportVersion /*version*/,
177 uint8_t flags) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500178 switch (flags & PACKET_FLAGS_8BYTE_PACKET) {
179 case PACKET_FLAGS_8BYTE_PACKET:
180 return PACKET_6BYTE_PACKET_NUMBER;
181 case PACKET_FLAGS_4BYTE_PACKET:
182 return PACKET_4BYTE_PACKET_NUMBER;
183 case PACKET_FLAGS_2BYTE_PACKET:
184 return PACKET_2BYTE_PACKET_NUMBER;
185 case PACKET_FLAGS_1BYTE_PACKET:
186 return PACKET_1BYTE_PACKET_NUMBER;
187 default:
188 QUIC_BUG << "Unreachable case statement.";
189 return PACKET_6BYTE_PACKET_NUMBER;
190 }
191}
192
193uint8_t PacketNumberLengthToOnWireValue(
QUICHE teama6ef0a62019-03-07 20:34:33 -0500194 QuicPacketNumberLength packet_number_length) {
fayang36825da2019-08-21 14:01:27 -0700195 return packet_number_length - 1;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500196}
197
fayang36825da2019-08-21 14:01:27 -0700198QuicPacketNumberLength GetShortHeaderPacketNumberLength(uint8_t type) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500199 DCHECK(!(type & FLAGS_LONG_HEADER));
fayang36825da2019-08-21 14:01:27 -0700200 return static_cast<QuicPacketNumberLength>((type & 0x03) + 1);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500201}
202
fayang36825da2019-08-21 14:01:27 -0700203uint8_t LongHeaderTypeToOnWireValue(QuicLongHeaderType type) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500204 switch (type) {
205 case INITIAL:
fayang36825da2019-08-21 14:01:27 -0700206 return 0;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500207 case ZERO_RTT_PROTECTED:
fayang36825da2019-08-21 14:01:27 -0700208 return 1 << 4;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500209 case HANDSHAKE:
fayang36825da2019-08-21 14:01:27 -0700210 return 2 << 4;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500211 case RETRY:
fayang36825da2019-08-21 14:01:27 -0700212 return 3 << 4;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500213 case VERSION_NEGOTIATION:
214 return 0xF0; // Value does not matter
215 default:
216 QUIC_BUG << "Invalid long header type: " << type;
217 return 0xFF;
218 }
219}
220
fayang36825da2019-08-21 14:01:27 -0700221bool GetLongHeaderType(uint8_t type, QuicLongHeaderType* long_header_type) {
222 DCHECK((type & FLAGS_LONG_HEADER));
223 switch ((type & 0x30) >> 4) {
224 case 0:
QUICHE teama6ef0a62019-03-07 20:34:33 -0500225 *long_header_type = INITIAL;
226 break;
fayang36825da2019-08-21 14:01:27 -0700227 case 1:
QUICHE teama6ef0a62019-03-07 20:34:33 -0500228 *long_header_type = ZERO_RTT_PROTECTED;
229 break;
fayang36825da2019-08-21 14:01:27 -0700230 case 2:
QUICHE teama6ef0a62019-03-07 20:34:33 -0500231 *long_header_type = HANDSHAKE;
232 break;
fayang36825da2019-08-21 14:01:27 -0700233 case 3:
QUICHE teama6ef0a62019-03-07 20:34:33 -0500234 *long_header_type = RETRY;
235 break;
236 default:
fayang36825da2019-08-21 14:01:27 -0700237 QUIC_BUG << "Unreachable statement";
QUICHE teama6ef0a62019-03-07 20:34:33 -0500238 *long_header_type = INVALID_PACKET_TYPE;
239 return false;
240 }
241 return true;
242}
243
fayang36825da2019-08-21 14:01:27 -0700244QuicPacketNumberLength GetLongHeaderPacketNumberLength(uint8_t type) {
245 return static_cast<QuicPacketNumberLength>((type & 0x03) + 1);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500246}
247
QUICHE team10b22a12019-03-21 15:31:42 -0700248// Used to get packet number space before packet gets decrypted.
249PacketNumberSpace GetPacketNumberSpace(const QuicPacketHeader& header) {
250 switch (header.form) {
251 case GOOGLE_QUIC_PACKET:
252 QUIC_BUG << "Try to get packet number space of Google QUIC packet";
253 break;
254 case IETF_QUIC_SHORT_HEADER_PACKET:
255 return APPLICATION_DATA;
256 case IETF_QUIC_LONG_HEADER_PACKET:
257 switch (header.long_packet_type) {
258 case INITIAL:
259 return INITIAL_DATA;
260 case HANDSHAKE:
261 return HANDSHAKE_DATA;
262 case ZERO_RTT_PROTECTED:
263 return APPLICATION_DATA;
264 case VERSION_NEGOTIATION:
265 case RETRY:
266 case INVALID_PACKET_TYPE:
267 QUIC_BUG << "Try to get packet number space of long header type: "
268 << QuicUtils::QuicLongHeaderTypetoString(
269 header.long_packet_type);
270 break;
271 }
272 }
273
274 return NUM_PACKET_NUMBER_SPACES;
275}
276
zhongyi546cc452019-04-12 15:27:49 -0700277EncryptionLevel GetEncryptionLevel(const QuicPacketHeader& header) {
278 switch (header.form) {
279 case GOOGLE_QUIC_PACKET:
280 QUIC_BUG << "Cannot determine EncryptionLevel from Google QUIC header";
281 break;
282 case IETF_QUIC_SHORT_HEADER_PACKET:
283 return ENCRYPTION_FORWARD_SECURE;
284 case IETF_QUIC_LONG_HEADER_PACKET:
285 switch (header.long_packet_type) {
286 case INITIAL:
287 return ENCRYPTION_INITIAL;
288 case HANDSHAKE:
289 return ENCRYPTION_HANDSHAKE;
290 case ZERO_RTT_PROTECTED:
291 return ENCRYPTION_ZERO_RTT;
292 case VERSION_NEGOTIATION:
293 case RETRY:
294 case INVALID_PACKET_TYPE:
295 QUIC_BUG << "No encryption used with type "
296 << QuicUtils::QuicLongHeaderTypetoString(
297 header.long_packet_type);
298 }
299 }
300 return NUM_ENCRYPTION_LEVELS;
301}
302
QUICHE teama6ef0a62019-03-07 20:34:33 -0500303QuicStringPiece TruncateErrorString(QuicStringPiece error) {
304 if (error.length() <= kMaxErrorStringLength) {
305 return error;
306 }
307 return QuicStringPiece(error.data(), kMaxErrorStringLength);
308}
309
310size_t TruncatedErrorStringSize(const QuicStringPiece& error) {
311 if (error.length() < kMaxErrorStringLength) {
312 return error.length();
313 }
314 return kMaxErrorStringLength;
315}
316
317uint8_t GetConnectionIdLengthValue(QuicConnectionIdLength length) {
318 if (length == 0) {
319 return 0;
320 }
321 return static_cast<uint8_t>(length - kConnectionIdLengthAdjustment);
322}
323
324bool IsValidPacketNumberLength(QuicPacketNumberLength packet_number_length) {
325 size_t length = packet_number_length;
326 return length == 1 || length == 2 || length == 4 || length == 6 ||
327 length == 8;
328}
329
330bool IsValidFullPacketNumber(uint64_t full_packet_number,
331 QuicTransportVersion version) {
QUICHE team577718a2019-03-20 09:00:59 -0700332 return full_packet_number > 0 || version == QUIC_VERSION_99;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500333}
334
dschinazi1f485a12019-05-13 11:57:01 -0700335bool AppendIetfConnectionIds(bool version_flag,
dschinazi48ac9192019-07-31 00:07:26 -0700336 bool use_length_prefix,
dschinazi1f485a12019-05-13 11:57:01 -0700337 QuicConnectionId destination_connection_id,
338 QuicConnectionId source_connection_id,
339 QuicDataWriter* writer) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500340 if (!version_flag) {
341 return writer->WriteConnectionId(destination_connection_id);
342 }
343
dschinazi48ac9192019-07-31 00:07:26 -0700344 if (use_length_prefix) {
345 return writer->WriteLengthPrefixedConnectionId(destination_connection_id) &&
346 writer->WriteLengthPrefixedConnectionId(source_connection_id);
347 }
348
QUICHE teama6ef0a62019-03-07 20:34:33 -0500349 // Compute connection ID length byte.
350 uint8_t dcil = GetConnectionIdLengthValue(
351 static_cast<QuicConnectionIdLength>(destination_connection_id.length()));
352 uint8_t scil = GetConnectionIdLengthValue(
353 static_cast<QuicConnectionIdLength>(source_connection_id.length()));
354 uint8_t connection_id_length = dcil << 4 | scil;
355
356 return writer->WriteUInt8(connection_id_length) &&
357 writer->WriteConnectionId(destination_connection_id) &&
358 writer->WriteConnectionId(source_connection_id);
359}
360
361enum class DroppedPacketReason {
362 // General errors
363 INVALID_PUBLIC_HEADER,
364 VERSION_MISMATCH,
365 // Version negotiation packet errors
366 INVALID_VERSION_NEGOTIATION_PACKET,
367 // Public reset packet errors, pre-v44
368 INVALID_PUBLIC_RESET_PACKET,
369 // Data packet errors
370 INVALID_PACKET_NUMBER,
371 INVALID_DIVERSIFICATION_NONCE,
372 DECRYPTION_FAILURE,
373 NUM_REASONS,
374};
375
376void RecordDroppedPacketReason(DroppedPacketReason reason) {
377 QUIC_CLIENT_HISTOGRAM_ENUM("QuicDroppedPacketReason", reason,
378 DroppedPacketReason::NUM_REASONS,
379 "The reason a packet was not processed. Recorded "
380 "each time such a packet is dropped");
381}
382
fayangccbab732019-05-13 10:11:25 -0700383PacketHeaderFormat GetIetfPacketHeaderFormat(uint8_t type_byte) {
384 return type_byte & FLAGS_LONG_HEADER ? IETF_QUIC_LONG_HEADER_PACKET
385 : IETF_QUIC_SHORT_HEADER_PACKET;
386}
387
fkastenholzb4dade72019-08-05 06:54:20 -0700388std::string GenerateErrorString(std::string initial_error_string,
389 QuicErrorCode quic_error_code) {
390 if (quic_error_code == QUIC_IETF_GQUIC_ERROR_MISSING) {
391 // QUIC_IETF_GQUIC_ERROR_MISSING is special -- it means not to encode
392 // the error value in the string.
393 return initial_error_string;
394 }
395 return QuicStrCat(std::to_string(static_cast<unsigned>(quic_error_code)), ":",
396 initial_error_string);
397}
398
QUICHE teama6ef0a62019-03-07 20:34:33 -0500399} // namespace
400
401QuicFramer::QuicFramer(const ParsedQuicVersionVector& supported_versions,
402 QuicTime creation_time,
403 Perspective perspective,
dschinazi8ff74822019-05-28 16:37:20 -0700404 uint8_t expected_server_connection_id_length)
QUICHE teama6ef0a62019-03-07 20:34:33 -0500405 : visitor_(nullptr),
406 error_(QUIC_NO_ERROR),
dschinazi7b9278c2019-05-20 07:36:21 -0700407 last_serialized_server_connection_id_(EmptyQuicConnectionId()),
dschinazi346b7ce2019-06-05 01:38:18 -0700408 last_serialized_client_connection_id_(EmptyQuicConnectionId()),
QUICHE teama6ef0a62019-03-07 20:34:33 -0500409 version_(PROTOCOL_UNSUPPORTED, QUIC_VERSION_UNSUPPORTED),
410 supported_versions_(supported_versions),
QUICHE team6987b4a2019-03-15 16:23:04 -0700411 decrypter_level_(ENCRYPTION_INITIAL),
QUICHE team76086e42019-03-25 15:12:29 -0700412 alternative_decrypter_level_(NUM_ENCRYPTION_LEVELS),
QUICHE teama6ef0a62019-03-07 20:34:33 -0500413 alternative_decrypter_latch_(false),
414 perspective_(perspective),
415 validate_flags_(true),
416 process_timestamps_(false),
417 creation_time_(creation_time),
418 last_timestamp_(QuicTime::Delta::Zero()),
419 first_sending_packet_number_(FirstSendingPacketNumber()),
420 data_producer_(nullptr),
421 infer_packet_header_type_from_version_(perspective ==
422 Perspective::IS_CLIENT),
dschinazi8ff74822019-05-28 16:37:20 -0700423 expected_server_connection_id_length_(
424 expected_server_connection_id_length),
dschinazi346b7ce2019-06-05 01:38:18 -0700425 expected_client_connection_id_length_(0),
nharper55fa6132019-05-07 19:37:21 -0700426 supports_multiple_packet_number_spaces_(false),
nharperc6b99512019-09-19 11:13:48 -0700427 framer_doesnt_create_initial_encrypter_(
428 GetQuicReloadableFlag(quic_framer_doesnt_create_initial_encrypter)),
fkastenholz4dc4ba32019-07-30 09:55:25 -0700429 last_written_packet_number_length_(0),
430 peer_ack_delay_exponent_(kDefaultAckDelayExponent),
fkastenholza3660102019-08-28 05:19:24 -0700431 local_ack_delay_exponent_(kDefaultAckDelayExponent),
432 current_received_frame_type_(0) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500433 DCHECK(!supported_versions.empty());
434 version_ = supported_versions_[0];
nharperc6b99512019-09-19 11:13:48 -0700435 if (!framer_doesnt_create_initial_encrypter_) {
436 decrypter_[ENCRYPTION_INITIAL] =
437 std::make_unique<NullDecrypter>(perspective);
438 encrypter_[ENCRYPTION_INITIAL] =
439 std::make_unique<NullEncrypter>(perspective);
440 } else {
441 QUIC_RELOADABLE_FLAG_COUNT(quic_framer_doesnt_create_initial_encrypter);
442 }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500443}
444
445QuicFramer::~QuicFramer() {}
446
447// static
448size_t QuicFramer::GetMinStreamFrameSize(QuicTransportVersion version,
449 QuicStreamId stream_id,
450 QuicStreamOffset offset,
451 bool last_frame_in_packet,
452 QuicPacketLength data_length) {
fkastenholz305e1732019-06-18 05:01:22 -0700453 if (VersionHasIetfQuicFrames(version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500454 return kQuicFrameTypeSize + QuicDataWriter::GetVarInt62Len(stream_id) +
455 (last_frame_in_packet
456 ? 0
457 : QuicDataWriter::GetVarInt62Len(data_length)) +
458 (offset != 0 ? QuicDataWriter::GetVarInt62Len(offset) : 0);
459 }
460 return kQuicFrameTypeSize + GetStreamIdSize(stream_id) +
461 GetStreamOffsetSize(version, offset) +
462 (last_frame_in_packet ? 0 : kQuicStreamPayloadLengthSize);
463}
464
465// static
466size_t QuicFramer::GetMinCryptoFrameSize(QuicStreamOffset offset,
467 QuicPacketLength data_length) {
468 return kQuicFrameTypeSize + QuicDataWriter::GetVarInt62Len(offset) +
469 QuicDataWriter::GetVarInt62Len(data_length);
470}
471
472// static
473size_t QuicFramer::GetMessageFrameSize(QuicTransportVersion version,
474 bool last_frame_in_packet,
475 QuicByteCount length) {
fayangd4291e42019-05-30 10:31:21 -0700476 QUIC_BUG_IF(!VersionSupportsMessageFrames(version))
QUICHE teama6ef0a62019-03-07 20:34:33 -0500477 << "Try to serialize MESSAGE frame in " << version;
478 return kQuicFrameTypeSize +
479 (last_frame_in_packet ? 0 : QuicDataWriter::GetVarInt62Len(length)) +
480 length;
481}
482
483// static
484size_t QuicFramer::GetMinAckFrameSize(
485 QuicTransportVersion version,
486 QuicPacketNumberLength largest_observed_length) {
fkastenholz305e1732019-06-18 05:01:22 -0700487 if (VersionHasIetfQuicFrames(version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500488 // The minimal ack frame consists of the following four fields: Largest
489 // Acknowledged, ACK Delay, ACK Block Count, and First ACK Block. Minimum
490 // size of each is 1 byte.
491 return kQuicFrameTypeSize + 4;
492 }
493 size_t min_size = kQuicFrameTypeSize + largest_observed_length +
494 kQuicDeltaTimeLargestObservedSize;
495 return min_size + kQuicNumTimestampsSize;
496}
497
498// static
499size_t QuicFramer::GetStopWaitingFrameSize(
dschinazi17d42422019-06-18 16:35:07 -0700500 QuicTransportVersion /*version*/,
QUICHE teama6ef0a62019-03-07 20:34:33 -0500501 QuicPacketNumberLength packet_number_length) {
502 size_t min_size = kQuicFrameTypeSize + packet_number_length;
503 return min_size;
504}
505
506// static
507size_t QuicFramer::GetRstStreamFrameSize(QuicTransportVersion version,
508 const QuicRstStreamFrame& frame) {
fkastenholz305e1732019-06-18 05:01:22 -0700509 if (VersionHasIetfQuicFrames(version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500510 return QuicDataWriter::GetVarInt62Len(frame.stream_id) +
511 QuicDataWriter::GetVarInt62Len(frame.byte_offset) +
fkastenholz07300e52019-07-16 11:51:37 -0700512 kQuicFrameTypeSize +
513 QuicDataWriter::GetVarInt62Len(frame.ietf_error_code);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500514 }
515 return kQuicFrameTypeSize + kQuicMaxStreamIdSize + kQuicMaxStreamOffsetSize +
516 kQuicErrorCodeSize;
517}
518
519// static
fkastenholza037b8b2019-05-07 06:00:05 -0700520size_t QuicFramer::GetConnectionCloseFrameSize(
QUICHE teama6ef0a62019-03-07 20:34:33 -0500521 QuicTransportVersion version,
522 const QuicConnectionCloseFrame& frame) {
fkastenholz305e1732019-06-18 05:01:22 -0700523 if (!VersionHasIetfQuicFrames(version)) {
524 // Not IETF QUIC, return Google QUIC CONNECTION CLOSE frame size.
fkastenholza037b8b2019-05-07 06:00:05 -0700525 return kQuicFrameTypeSize + kQuicErrorCodeSize +
526 kQuicErrorDetailsLengthSize +
527 TruncatedErrorStringSize(frame.error_details);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500528 }
fkastenholzb4dade72019-08-05 06:54:20 -0700529
530 // Prepend the extra error information to the string and get the result's
531 // length.
532 const size_t truncated_error_string_size = TruncatedErrorStringSize(
533 GenerateErrorString(frame.error_details, frame.extracted_error_code));
534
fkastenholza037b8b2019-05-07 06:00:05 -0700535 const size_t frame_size =
536 truncated_error_string_size +
537 QuicDataWriter::GetVarInt62Len(truncated_error_string_size) +
fkastenholz88d08f42019-09-06 07:38:04 -0700538 kQuicFrameTypeSize +
539 QuicDataWriter::GetVarInt62Len(
540 (frame.close_type == IETF_QUIC_TRANSPORT_CONNECTION_CLOSE)
541 ? frame.transport_error_code
542 : frame.application_error_code);
fkastenholza037b8b2019-05-07 06:00:05 -0700543 if (frame.close_type == IETF_QUIC_APPLICATION_CONNECTION_CLOSE) {
544 return frame_size;
545 }
fkastenholzb4dade72019-08-05 06:54:20 -0700546 // The Transport close frame has the transport_close_frame_type, so include
547 // its length.
fkastenholza037b8b2019-05-07 06:00:05 -0700548 return frame_size +
549 QuicDataWriter::GetVarInt62Len(frame.transport_close_frame_type);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500550}
551
552// static
QUICHE teama6ef0a62019-03-07 20:34:33 -0500553size_t QuicFramer::GetMinGoAwayFrameSize() {
554 return kQuicFrameTypeSize + kQuicErrorCodeSize + kQuicErrorDetailsLengthSize +
555 kQuicMaxStreamIdSize;
556}
557
558// static
559size_t QuicFramer::GetWindowUpdateFrameSize(
560 QuicTransportVersion version,
561 const QuicWindowUpdateFrame& frame) {
fkastenholz305e1732019-06-18 05:01:22 -0700562 if (!VersionHasIetfQuicFrames(version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500563 return kQuicFrameTypeSize + kQuicMaxStreamIdSize + kQuicMaxStreamOffsetSize;
564 }
565 if (frame.stream_id == QuicUtils::GetInvalidStreamId(version)) {
566 // Frame would be a MAX DATA frame, which has only a Maximum Data field.
567 return kQuicFrameTypeSize +
568 QuicDataWriter::GetVarInt62Len(frame.byte_offset);
569 }
570 // Frame would be MAX STREAM DATA, has Maximum Stream Data and Stream ID
571 // fields.
572 return kQuicFrameTypeSize +
573 QuicDataWriter::GetVarInt62Len(frame.byte_offset) +
574 QuicDataWriter::GetVarInt62Len(frame.stream_id);
575}
576
577// static
578size_t QuicFramer::GetMaxStreamsFrameSize(QuicTransportVersion version,
fkastenholz3c4eabf2019-04-22 07:49:59 -0700579 const QuicMaxStreamsFrame& frame) {
fkastenholz305e1732019-06-18 05:01:22 -0700580 if (!VersionHasIetfQuicFrames(version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500581 QUIC_BUG << "In version " << version
fkastenholz305e1732019-06-18 05:01:22 -0700582 << ", which does not support IETF Frames, and tried to serialize "
583 "MaxStreams Frame.";
QUICHE teama6ef0a62019-03-07 20:34:33 -0500584 }
fkastenholz3c4eabf2019-04-22 07:49:59 -0700585 return kQuicFrameTypeSize +
586 QuicDataWriter::GetVarInt62Len(frame.stream_count);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500587}
588
589// static
590size_t QuicFramer::GetStreamsBlockedFrameSize(
591 QuicTransportVersion version,
fkastenholz3c4eabf2019-04-22 07:49:59 -0700592 const QuicStreamsBlockedFrame& frame) {
fkastenholz305e1732019-06-18 05:01:22 -0700593 if (!VersionHasIetfQuicFrames(version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500594 QUIC_BUG << "In version " << version
fkastenholz305e1732019-06-18 05:01:22 -0700595 << ", which does not support IETF frames, and tried to serialize "
596 "StreamsBlocked Frame.";
QUICHE teama6ef0a62019-03-07 20:34:33 -0500597 }
598
fkastenholz3c4eabf2019-04-22 07:49:59 -0700599 return kQuicFrameTypeSize +
600 QuicDataWriter::GetVarInt62Len(frame.stream_count);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500601}
602
603// static
604size_t QuicFramer::GetBlockedFrameSize(QuicTransportVersion version,
605 const QuicBlockedFrame& frame) {
fkastenholz305e1732019-06-18 05:01:22 -0700606 if (!VersionHasIetfQuicFrames(version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500607 return kQuicFrameTypeSize + kQuicMaxStreamIdSize;
608 }
609 if (frame.stream_id == QuicUtils::GetInvalidStreamId(version)) {
610 // return size of IETF QUIC Blocked frame
611 return kQuicFrameTypeSize + QuicDataWriter::GetVarInt62Len(frame.offset);
612 }
613 // return size of IETF QUIC Stream Blocked frame.
614 return kQuicFrameTypeSize + QuicDataWriter::GetVarInt62Len(frame.offset) +
615 QuicDataWriter::GetVarInt62Len(frame.stream_id);
616}
617
618// static
619size_t QuicFramer::GetStopSendingFrameSize(const QuicStopSendingFrame& frame) {
620 return kQuicFrameTypeSize + QuicDataWriter::GetVarInt62Len(frame.stream_id) +
fkastenholz733552e2019-07-16 11:16:58 -0700621 QuicDataWriter::GetVarInt62Len(frame.application_error_code);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500622}
623
624// static
625size_t QuicFramer::GetPathChallengeFrameSize(
626 const QuicPathChallengeFrame& frame) {
627 return kQuicFrameTypeSize + sizeof(frame.data_buffer);
628}
629
630// static
631size_t QuicFramer::GetPathResponseFrameSize(
632 const QuicPathResponseFrame& frame) {
633 return kQuicFrameTypeSize + sizeof(frame.data_buffer);
634}
635
636// static
637size_t QuicFramer::GetRetransmittableControlFrameSize(
638 QuicTransportVersion version,
639 const QuicFrame& frame) {
640 switch (frame.type) {
641 case PING_FRAME:
642 // Ping has no payload.
643 return kQuicFrameTypeSize;
644 case RST_STREAM_FRAME:
645 return GetRstStreamFrameSize(version, *frame.rst_stream_frame);
646 case CONNECTION_CLOSE_FRAME:
fkastenholza037b8b2019-05-07 06:00:05 -0700647 return GetConnectionCloseFrameSize(version,
648 *frame.connection_close_frame);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500649 case GOAWAY_FRAME:
650 return GetMinGoAwayFrameSize() +
651 TruncatedErrorStringSize(frame.goaway_frame->reason_phrase);
652 case WINDOW_UPDATE_FRAME:
fkastenholz305e1732019-06-18 05:01:22 -0700653 // For IETF QUIC, this could be either a MAX DATA or MAX STREAM DATA.
QUICHE teama6ef0a62019-03-07 20:34:33 -0500654 // GetWindowUpdateFrameSize figures this out and returns the correct
655 // length.
656 return GetWindowUpdateFrameSize(version, *frame.window_update_frame);
657 case BLOCKED_FRAME:
658 return GetBlockedFrameSize(version, *frame.blocked_frame);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500659 case NEW_CONNECTION_ID_FRAME:
660 return GetNewConnectionIdFrameSize(*frame.new_connection_id_frame);
661 case RETIRE_CONNECTION_ID_FRAME:
662 return GetRetireConnectionIdFrameSize(*frame.retire_connection_id_frame);
663 case NEW_TOKEN_FRAME:
664 return GetNewTokenFrameSize(*frame.new_token_frame);
fkastenholz3c4eabf2019-04-22 07:49:59 -0700665 case MAX_STREAMS_FRAME:
666 return GetMaxStreamsFrameSize(version, frame.max_streams_frame);
667 case STREAMS_BLOCKED_FRAME:
668 return GetStreamsBlockedFrameSize(version, frame.streams_blocked_frame);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500669 case PATH_RESPONSE_FRAME:
670 return GetPathResponseFrameSize(*frame.path_response_frame);
671 case PATH_CHALLENGE_FRAME:
672 return GetPathChallengeFrameSize(*frame.path_challenge_frame);
673 case STOP_SENDING_FRAME:
674 return GetStopSendingFrameSize(*frame.stop_sending_frame);
675
676 case STREAM_FRAME:
677 case ACK_FRAME:
678 case STOP_WAITING_FRAME:
679 case MTU_DISCOVERY_FRAME:
680 case PADDING_FRAME:
681 case MESSAGE_FRAME:
682 case CRYPTO_FRAME:
683 case NUM_FRAME_TYPES:
684 DCHECK(false);
685 return 0;
686 }
687
688 // Not reachable, but some Chrome compilers can't figure that out. *sigh*
689 DCHECK(false);
690 return 0;
691}
692
693// static
694size_t QuicFramer::GetStreamIdSize(QuicStreamId stream_id) {
695 // Sizes are 1 through 4 bytes.
696 for (int i = 1; i <= 4; ++i) {
697 stream_id >>= 8;
698 if (stream_id == 0) {
699 return i;
700 }
701 }
702 QUIC_BUG << "Failed to determine StreamIDSize.";
703 return 4;
704}
705
706// static
dschinazi17d42422019-06-18 16:35:07 -0700707size_t QuicFramer::GetStreamOffsetSize(QuicTransportVersion /*version*/,
QUICHE teama6ef0a62019-03-07 20:34:33 -0500708 QuicStreamOffset offset) {
709 // 0 is a special case.
710 if (offset == 0) {
711 return 0;
712 }
713 // 2 through 8 are the remaining sizes.
714 offset >>= 8;
715 for (int i = 2; i <= 8; ++i) {
716 offset >>= 8;
717 if (offset == 0) {
718 return i;
719 }
720 }
721 QUIC_BUG << "Failed to determine StreamOffsetSize.";
722 return 8;
723}
724
725// static
726size_t QuicFramer::GetNewConnectionIdFrameSize(
727 const QuicNewConnectionIdFrame& frame) {
728 return kQuicFrameTypeSize +
729 QuicDataWriter::GetVarInt62Len(frame.sequence_number) +
fkastenholz1c19fc22019-07-12 11:06:19 -0700730 QuicDataWriter::GetVarInt62Len(frame.retire_prior_to) +
QUICHE teama6ef0a62019-03-07 20:34:33 -0500731 kConnectionIdLengthSize + frame.connection_id.length() +
732 sizeof(frame.stateless_reset_token);
733}
734
735// static
736size_t QuicFramer::GetRetireConnectionIdFrameSize(
737 const QuicRetireConnectionIdFrame& frame) {
738 return kQuicFrameTypeSize +
739 QuicDataWriter::GetVarInt62Len(frame.sequence_number);
740}
741
742// static
743size_t QuicFramer::GetNewTokenFrameSize(const QuicNewTokenFrame& frame) {
744 return kQuicFrameTypeSize +
745 QuicDataWriter::GetVarInt62Len(frame.token.length()) +
746 frame.token.length();
747}
748
749// TODO(nharper): Change this method to take a ParsedQuicVersion.
750bool QuicFramer::IsSupportedTransportVersion(
751 const QuicTransportVersion version) const {
752 for (ParsedQuicVersion supported_version : supported_versions_) {
753 if (version == supported_version.transport_version) {
754 return true;
755 }
756 }
757 return false;
758}
759
760bool QuicFramer::IsSupportedVersion(const ParsedQuicVersion version) const {
761 for (const ParsedQuicVersion& supported_version : supported_versions_) {
762 if (version == supported_version) {
763 return true;
764 }
765 }
766 return false;
767}
768
769size_t QuicFramer::GetSerializedFrameLength(
770 const QuicFrame& frame,
771 size_t free_bytes,
772 bool first_frame,
773 bool last_frame,
774 QuicPacketNumberLength packet_number_length) {
775 // Prevent a rare crash reported in b/19458523.
776 if (frame.type == ACK_FRAME && frame.ack_frame == nullptr) {
777 QUIC_BUG << "Cannot compute the length of a null ack frame. free_bytes:"
778 << free_bytes << " first_frame:" << first_frame
779 << " last_frame:" << last_frame
780 << " seq num length:" << packet_number_length;
781 set_error(QUIC_INTERNAL_ERROR);
782 visitor_->OnError(this);
783 return 0;
784 }
785 if (frame.type == PADDING_FRAME) {
786 if (frame.padding_frame.num_padding_bytes == -1) {
787 // Full padding to the end of the packet.
788 return free_bytes;
789 } else {
790 // Lite padding.
791 return free_bytes <
792 static_cast<size_t>(frame.padding_frame.num_padding_bytes)
793 ? free_bytes
794 : frame.padding_frame.num_padding_bytes;
795 }
796 }
797
798 size_t frame_len =
799 ComputeFrameLength(frame, last_frame, packet_number_length);
800 if (frame_len <= free_bytes) {
801 // Frame fits within packet. Note that acks may be truncated.
802 return frame_len;
803 }
804 // Only truncate the first frame in a packet, so if subsequent ones go
805 // over, stop including more frames.
806 if (!first_frame) {
807 return 0;
808 }
809 bool can_truncate =
810 frame.type == ACK_FRAME &&
811 free_bytes >= GetMinAckFrameSize(version_.transport_version,
812 PACKET_6BYTE_PACKET_NUMBER);
813 if (can_truncate) {
dschinazi66dea072019-04-09 11:41:06 -0700814 // Truncate the frame so the packet will not exceed kMaxOutgoingPacketSize.
QUICHE teama6ef0a62019-03-07 20:34:33 -0500815 // Note that we may not use every byte of the writer in this case.
816 QUIC_DLOG(INFO) << ENDPOINT
817 << "Truncating large frame, free bytes: " << free_bytes;
818 return free_bytes;
819 }
820 return 0;
821}
822
823QuicFramer::AckFrameInfo::AckFrameInfo()
824 : max_block_length(0), first_block_length(0), num_ack_blocks(0) {}
825
826QuicFramer::AckFrameInfo::AckFrameInfo(const AckFrameInfo& other) = default;
827
828QuicFramer::AckFrameInfo::~AckFrameInfo() {}
829
830bool QuicFramer::WriteIetfLongHeaderLength(const QuicPacketHeader& header,
831 QuicDataWriter* writer,
832 size_t length_field_offset,
833 EncryptionLevel level) {
834 if (!QuicVersionHasLongHeaderLengths(transport_version()) ||
835 !header.version_flag || length_field_offset == 0) {
836 return true;
837 }
838 if (writer->length() < length_field_offset ||
839 writer->length() - length_field_offset <
840 kQuicDefaultLongHeaderLengthLength) {
841 set_detailed_error("Invalid length_field_offset.");
842 QUIC_BUG << "Invalid length_field_offset.";
843 return false;
844 }
845 size_t length_to_write = writer->length() - length_field_offset -
846 kQuicDefaultLongHeaderLengthLength;
847 // Add length of auth tag.
848 length_to_write = GetCiphertextSize(level, length_to_write);
849
850 QuicDataWriter length_writer(writer->length() - length_field_offset,
851 writer->data() + length_field_offset);
852 if (!length_writer.WriteVarInt62(length_to_write,
853 kQuicDefaultLongHeaderLengthLength)) {
854 set_detailed_error("Failed to overwrite long header length.");
855 QUIC_BUG << "Failed to overwrite long header length.";
856 return false;
857 }
858 return true;
859}
860
861size_t QuicFramer::BuildDataPacket(const QuicPacketHeader& header,
862 const QuicFrames& frames,
863 char* buffer,
864 size_t packet_length,
865 EncryptionLevel level) {
866 QuicDataWriter writer(packet_length, buffer);
867 size_t length_field_offset = 0;
868 if (!AppendPacketHeader(header, &writer, &length_field_offset)) {
869 QUIC_BUG << "AppendPacketHeader failed";
870 return 0;
871 }
872
fkastenholz305e1732019-06-18 05:01:22 -0700873 if (VersionHasIetfQuicFrames(transport_version())) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500874 if (AppendIetfFrames(frames, &writer) == 0) {
875 return 0;
876 }
877 if (!WriteIetfLongHeaderLength(header, &writer, length_field_offset,
878 level)) {
879 return 0;
880 }
881 return writer.length();
882 }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500883
884 size_t i = 0;
885 for (const QuicFrame& frame : frames) {
886 // Determine if we should write stream frame length in header.
887 const bool last_frame_in_packet = i == frames.size() - 1;
888 if (!AppendTypeByte(frame, last_frame_in_packet, &writer)) {
889 QUIC_BUG << "AppendTypeByte failed";
890 return 0;
891 }
892
893 switch (frame.type) {
894 case PADDING_FRAME:
895 if (!AppendPaddingFrame(frame.padding_frame, &writer)) {
896 QUIC_BUG << "AppendPaddingFrame of "
897 << frame.padding_frame.num_padding_bytes << " failed";
898 return 0;
899 }
900 break;
901 case STREAM_FRAME:
902 if (!AppendStreamFrame(frame.stream_frame, last_frame_in_packet,
903 &writer)) {
904 QUIC_BUG << "AppendStreamFrame failed";
905 return 0;
906 }
907 break;
908 case ACK_FRAME:
909 if (!AppendAckFrameAndTypeByte(*frame.ack_frame, &writer)) {
910 QUIC_BUG << "AppendAckFrameAndTypeByte failed: " << detailed_error_;
911 return 0;
912 }
913 break;
914 case STOP_WAITING_FRAME:
915 if (!AppendStopWaitingFrame(header, frame.stop_waiting_frame,
916 &writer)) {
917 QUIC_BUG << "AppendStopWaitingFrame failed";
918 return 0;
919 }
920 break;
921 case MTU_DISCOVERY_FRAME:
922 // MTU discovery frames are serialized as ping frames.
923 QUIC_FALLTHROUGH_INTENDED;
924 case PING_FRAME:
925 // Ping has no payload.
926 break;
927 case RST_STREAM_FRAME:
928 if (!AppendRstStreamFrame(*frame.rst_stream_frame, &writer)) {
929 QUIC_BUG << "AppendRstStreamFrame failed";
930 return 0;
931 }
932 break;
933 case CONNECTION_CLOSE_FRAME:
934 if (!AppendConnectionCloseFrame(*frame.connection_close_frame,
935 &writer)) {
936 QUIC_BUG << "AppendConnectionCloseFrame failed";
937 return 0;
938 }
939 break;
940 case GOAWAY_FRAME:
941 if (!AppendGoAwayFrame(*frame.goaway_frame, &writer)) {
942 QUIC_BUG << "AppendGoAwayFrame failed";
943 return 0;
944 }
945 break;
946 case WINDOW_UPDATE_FRAME:
947 if (!AppendWindowUpdateFrame(*frame.window_update_frame, &writer)) {
948 QUIC_BUG << "AppendWindowUpdateFrame failed";
949 return 0;
950 }
951 break;
952 case BLOCKED_FRAME:
953 if (!AppendBlockedFrame(*frame.blocked_frame, &writer)) {
954 QUIC_BUG << "AppendBlockedFrame failed";
955 return 0;
956 }
957 break;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500958 case NEW_CONNECTION_ID_FRAME:
959 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -0700960 "Attempt to append NEW_CONNECTION_ID frame and not in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -0500961 return RaiseError(QUIC_INTERNAL_ERROR);
962 case RETIRE_CONNECTION_ID_FRAME:
963 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -0700964 "Attempt to append RETIRE_CONNECTION_ID frame and not in IETF "
965 "QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -0500966 return RaiseError(QUIC_INTERNAL_ERROR);
967 case NEW_TOKEN_FRAME:
968 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -0700969 "Attempt to append NEW_TOKEN_ID frame and not in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -0500970 return RaiseError(QUIC_INTERNAL_ERROR);
fkastenholz3c4eabf2019-04-22 07:49:59 -0700971 case MAX_STREAMS_FRAME:
QUICHE teama6ef0a62019-03-07 20:34:33 -0500972 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -0700973 "Attempt to append MAX_STREAMS frame and not in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -0500974 return RaiseError(QUIC_INTERNAL_ERROR);
fkastenholz3c4eabf2019-04-22 07:49:59 -0700975 case STREAMS_BLOCKED_FRAME:
QUICHE teama6ef0a62019-03-07 20:34:33 -0500976 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -0700977 "Attempt to append STREAMS_BLOCKED frame and not in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -0500978 return RaiseError(QUIC_INTERNAL_ERROR);
979 case PATH_RESPONSE_FRAME:
980 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -0700981 "Attempt to append PATH_RESPONSE frame and not in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -0500982 return RaiseError(QUIC_INTERNAL_ERROR);
983 case PATH_CHALLENGE_FRAME:
984 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -0700985 "Attempt to append PATH_CHALLENGE frame and not in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -0500986 return RaiseError(QUIC_INTERNAL_ERROR);
987 case STOP_SENDING_FRAME:
988 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -0700989 "Attempt to append STOP_SENDING frame and not in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -0500990 return RaiseError(QUIC_INTERNAL_ERROR);
991 case MESSAGE_FRAME:
992 if (!AppendMessageFrameAndTypeByte(*frame.message_frame,
993 last_frame_in_packet, &writer)) {
994 QUIC_BUG << "AppendMessageFrame failed";
995 return 0;
996 }
997 break;
998 case CRYPTO_FRAME:
QUICHE teamea740082019-03-11 17:58:43 -0700999 if (!QuicVersionUsesCryptoFrames(version_.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001000 set_detailed_error(
1001 "Attempt to append CRYPTO frame in version prior to 47.");
1002 return RaiseError(QUIC_INTERNAL_ERROR);
1003 }
1004 if (!AppendCryptoFrame(*frame.crypto_frame, &writer)) {
1005 QUIC_BUG << "AppendCryptoFrame failed";
1006 return 0;
1007 }
1008 break;
1009 default:
1010 RaiseError(QUIC_INVALID_FRAME_DATA);
1011 QUIC_BUG << "QUIC_INVALID_FRAME_DATA";
1012 return 0;
1013 }
1014 ++i;
1015 }
1016
dschinazid1428492019-09-17 23:59:30 -07001017 if (!WriteIetfLongHeaderLength(header, &writer, length_field_offset, level)) {
1018 return 0;
1019 }
1020
QUICHE teama6ef0a62019-03-07 20:34:33 -05001021 return writer.length();
1022}
1023
1024size_t QuicFramer::AppendIetfFrames(const QuicFrames& frames,
1025 QuicDataWriter* writer) {
1026 size_t i = 0;
1027 for (const QuicFrame& frame : frames) {
1028 // Determine if we should write stream frame length in header.
1029 const bool last_frame_in_packet = i == frames.size() - 1;
1030 if (!AppendIetfTypeByte(frame, last_frame_in_packet, writer)) {
1031 QUIC_BUG << "AppendIetfTypeByte failed: " << detailed_error();
1032 return 0;
1033 }
1034
1035 switch (frame.type) {
1036 case PADDING_FRAME:
1037 if (!AppendPaddingFrame(frame.padding_frame, writer)) {
1038 QUIC_BUG << "AppendPaddingFrame of "
1039 << frame.padding_frame.num_padding_bytes
1040 << " failed: " << detailed_error();
1041 return 0;
1042 }
1043 break;
1044 case STREAM_FRAME:
1045 if (!AppendStreamFrame(frame.stream_frame, last_frame_in_packet,
1046 writer)) {
1047 QUIC_BUG << "AppendStreamFrame failed: " << detailed_error();
1048 return 0;
1049 }
1050 break;
1051 case ACK_FRAME:
1052 if (!AppendIetfAckFrameAndTypeByte(*frame.ack_frame, writer)) {
QUICHE team4fe0b942019-03-08 09:25:06 -05001053 QUIC_BUG << "AppendIetfAckFrameAndTypeByte failed: "
1054 << detailed_error();
QUICHE teama6ef0a62019-03-07 20:34:33 -05001055 return 0;
1056 }
1057 break;
1058 case STOP_WAITING_FRAME:
1059 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -07001060 "Attempt to append STOP WAITING frame in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05001061 return RaiseError(QUIC_INTERNAL_ERROR);
1062 case MTU_DISCOVERY_FRAME:
1063 // MTU discovery frames are serialized as ping frames.
1064 QUIC_FALLTHROUGH_INTENDED;
1065 case PING_FRAME:
1066 // Ping has no payload.
1067 break;
1068 case RST_STREAM_FRAME:
1069 if (!AppendRstStreamFrame(*frame.rst_stream_frame, writer)) {
1070 QUIC_BUG << "AppendRstStreamFrame failed: " << detailed_error();
1071 return 0;
1072 }
1073 break;
1074 case CONNECTION_CLOSE_FRAME:
fkastenholz72f509b2019-04-10 09:17:49 -07001075 if (!AppendIetfConnectionCloseFrame(*frame.connection_close_frame,
1076 writer)) {
1077 QUIC_BUG << "AppendIetfConnectionCloseFrame failed: "
1078 << detailed_error();
QUICHE teama6ef0a62019-03-07 20:34:33 -05001079 return 0;
1080 }
1081 break;
1082 case GOAWAY_FRAME:
fkastenholz305e1732019-06-18 05:01:22 -07001083 set_detailed_error("Attempt to append GOAWAY frame in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05001084 return RaiseError(QUIC_INTERNAL_ERROR);
1085 case WINDOW_UPDATE_FRAME:
1086 // Depending on whether there is a stream ID or not, will be either a
1087 // MAX STREAM DATA frame or a MAX DATA frame.
1088 if (frame.window_update_frame->stream_id ==
1089 QuicUtils::GetInvalidStreamId(transport_version())) {
1090 if (!AppendMaxDataFrame(*frame.window_update_frame, writer)) {
1091 QUIC_BUG << "AppendMaxDataFrame failed: " << detailed_error();
1092 return 0;
1093 }
1094 } else {
1095 if (!AppendMaxStreamDataFrame(*frame.window_update_frame, writer)) {
1096 QUIC_BUG << "AppendMaxStreamDataFrame failed: " << detailed_error();
1097 return 0;
1098 }
1099 }
1100 break;
1101 case BLOCKED_FRAME:
1102 if (!AppendBlockedFrame(*frame.blocked_frame, writer)) {
1103 QUIC_BUG << "AppendBlockedFrame failed: " << detailed_error();
1104 return 0;
1105 }
1106 break;
fkastenholz3c4eabf2019-04-22 07:49:59 -07001107 case MAX_STREAMS_FRAME:
1108 if (!AppendMaxStreamsFrame(frame.max_streams_frame, writer)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001109 QUIC_BUG << "AppendMaxStreamsFrame failed" << detailed_error();
1110 return 0;
1111 }
1112 break;
fkastenholz3c4eabf2019-04-22 07:49:59 -07001113 case STREAMS_BLOCKED_FRAME:
1114 if (!AppendStreamsBlockedFrame(frame.streams_blocked_frame, writer)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001115 QUIC_BUG << "AppendStreamsBlockedFrame failed" << detailed_error();
1116 return 0;
1117 }
1118 break;
1119 case NEW_CONNECTION_ID_FRAME:
1120 if (!AppendNewConnectionIdFrame(*frame.new_connection_id_frame,
1121 writer)) {
1122 QUIC_BUG << "AppendNewConnectionIdFrame failed: " << detailed_error();
1123 return 0;
1124 }
1125 break;
1126 case RETIRE_CONNECTION_ID_FRAME:
1127 if (!AppendRetireConnectionIdFrame(*frame.retire_connection_id_frame,
1128 writer)) {
1129 QUIC_BUG << "AppendRetireConnectionIdFrame failed: "
1130 << detailed_error();
1131 return 0;
1132 }
1133 break;
1134 case NEW_TOKEN_FRAME:
1135 if (!AppendNewTokenFrame(*frame.new_token_frame, writer)) {
1136 QUIC_BUG << "AppendNewTokenFrame failed: " << detailed_error();
1137 return 0;
1138 }
1139 break;
1140 case STOP_SENDING_FRAME:
1141 if (!AppendStopSendingFrame(*frame.stop_sending_frame, writer)) {
1142 QUIC_BUG << "AppendStopSendingFrame failed: " << detailed_error();
1143 return 0;
1144 }
1145 break;
1146 case PATH_CHALLENGE_FRAME:
1147 if (!AppendPathChallengeFrame(*frame.path_challenge_frame, writer)) {
1148 QUIC_BUG << "AppendPathChallengeFrame failed: " << detailed_error();
1149 return 0;
1150 }
1151 break;
1152 case PATH_RESPONSE_FRAME:
1153 if (!AppendPathResponseFrame(*frame.path_response_frame, writer)) {
1154 QUIC_BUG << "AppendPathResponseFrame failed: " << detailed_error();
1155 return 0;
1156 }
1157 break;
1158 case MESSAGE_FRAME:
1159 if (!AppendMessageFrameAndTypeByte(*frame.message_frame,
1160 last_frame_in_packet, writer)) {
1161 QUIC_BUG << "AppendMessageFrame failed: " << detailed_error();
1162 return 0;
1163 }
1164 break;
1165 case CRYPTO_FRAME:
1166 if (!AppendCryptoFrame(*frame.crypto_frame, writer)) {
1167 QUIC_BUG << "AppendCryptoFrame failed: " << detailed_error();
1168 return 0;
1169 }
1170 break;
1171 default:
1172 RaiseError(QUIC_INVALID_FRAME_DATA);
1173 set_detailed_error("Tried to append unknown frame type.");
1174 QUIC_BUG << "QUIC_INVALID_FRAME_DATA";
1175 return 0;
1176 }
1177 ++i;
1178 }
1179
1180 return writer->length();
1181}
1182
rch67cb9df2019-03-26 16:52:07 -07001183size_t QuicFramer::BuildConnectivityProbingPacket(
QUICHE teama6ef0a62019-03-07 20:34:33 -05001184 const QuicPacketHeader& header,
1185 char* buffer,
1186 size_t packet_length,
1187 EncryptionLevel level) {
1188 QuicFrames frames;
1189
1190 // Write a PING frame, which has no data payload.
1191 QuicPingFrame ping_frame;
1192 frames.push_back(QuicFrame(ping_frame));
1193
1194 // Add padding to the rest of the packet.
1195 QuicPaddingFrame padding_frame;
1196 frames.push_back(QuicFrame(padding_frame));
1197
1198 return BuildDataPacket(header, frames, buffer, packet_length, level);
1199}
1200
QUICHE teama6ef0a62019-03-07 20:34:33 -05001201size_t QuicFramer::BuildPaddedPathChallengePacket(
1202 const QuicPacketHeader& header,
1203 char* buffer,
1204 size_t packet_length,
1205 QuicPathFrameBuffer* payload,
1206 QuicRandom* randomizer,
1207 EncryptionLevel level) {
fkastenholz305e1732019-06-18 05:01:22 -07001208 if (!VersionHasIetfQuicFrames(version_.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001209 QUIC_BUG << "Attempt to build a PATH_CHALLENGE Connectivity Probing "
1210 "packet and not doing IETF QUIC";
1211 return 0;
1212 }
1213 QuicFrames frames;
1214
1215 // Write a PATH_CHALLENGE frame, which has a random 8-byte payload
1216 randomizer->RandBytes(payload->data(), payload->size());
1217
1218 QuicPathChallengeFrame path_challenge_frame(0, *payload);
1219 frames.push_back(QuicFrame(&path_challenge_frame));
1220
1221 // Add padding to the rest of the packet in order to assess Path MTU
1222 // characteristics.
1223 QuicPaddingFrame padding_frame;
1224 frames.push_back(QuicFrame(padding_frame));
1225
1226 return BuildDataPacket(header, frames, buffer, packet_length, level);
1227}
1228
1229size_t QuicFramer::BuildPathResponsePacket(
1230 const QuicPacketHeader& header,
1231 char* buffer,
1232 size_t packet_length,
1233 const QuicDeque<QuicPathFrameBuffer>& payloads,
1234 const bool is_padded,
1235 EncryptionLevel level) {
1236 if (payloads.empty()) {
1237 QUIC_BUG
1238 << "Attempt to generate connectivity response with no request payloads";
1239 return 0;
1240 }
fkastenholz305e1732019-06-18 05:01:22 -07001241 if (!VersionHasIetfQuicFrames(version_.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001242 QUIC_BUG << "Attempt to build a PATH_RESPONSE Connectivity Probing "
1243 "packet and not doing IETF QUIC";
1244 return 0;
1245 }
1246
1247 std::vector<std::unique_ptr<QuicPathResponseFrame>> path_response_frames;
1248 for (const QuicPathFrameBuffer& payload : payloads) {
1249 // Note that the control frame ID can be 0 since this is not retransmitted.
1250 path_response_frames.push_back(
vasilvv0fc587f2019-09-06 13:33:08 -07001251 std::make_unique<QuicPathResponseFrame>(0, payload));
QUICHE teama6ef0a62019-03-07 20:34:33 -05001252 }
1253
1254 QuicFrames frames;
1255 for (const std::unique_ptr<QuicPathResponseFrame>& path_response_frame :
1256 path_response_frames) {
1257 frames.push_back(QuicFrame(path_response_frame.get()));
1258 }
1259
1260 if (is_padded) {
1261 // Add padding to the rest of the packet in order to assess Path MTU
1262 // characteristics.
1263 QuicPaddingFrame padding_frame;
1264 frames.push_back(QuicFrame(padding_frame));
1265 }
1266
1267 return BuildDataPacket(header, frames, buffer, packet_length, level);
1268}
1269
1270// static
1271std::unique_ptr<QuicEncryptedPacket> QuicFramer::BuildPublicResetPacket(
1272 const QuicPublicResetPacket& packet) {
1273 CryptoHandshakeMessage reset;
1274 reset.set_tag(kPRST);
1275 reset.SetValue(kRNON, packet.nonce_proof);
1276 if (packet.client_address.host().address_family() !=
1277 IpAddressFamily::IP_UNSPEC) {
1278 // packet.client_address is non-empty.
1279 QuicSocketAddressCoder address_coder(packet.client_address);
vasilvvc48c8712019-03-11 13:38:16 -07001280 std::string serialized_address = address_coder.Encode();
QUICHE teama6ef0a62019-03-07 20:34:33 -05001281 if (serialized_address.empty()) {
1282 return nullptr;
1283 }
1284 reset.SetStringPiece(kCADR, serialized_address);
1285 }
1286 if (!packet.endpoint_id.empty()) {
1287 reset.SetStringPiece(kEPID, packet.endpoint_id);
1288 }
1289 const QuicData& reset_serialized = reset.GetSerialized();
1290
1291 size_t len = kPublicFlagsSize + packet.connection_id.length() +
1292 reset_serialized.length();
1293 std::unique_ptr<char[]> buffer(new char[len]);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001294 QuicDataWriter writer(len, buffer.get());
1295
1296 uint8_t flags = static_cast<uint8_t>(PACKET_PUBLIC_FLAGS_RST |
1297 PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID);
1298 // This hack makes post-v33 public reset packet look like pre-v33 packets.
1299 flags |= static_cast<uint8_t>(PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID_OLD);
1300 if (!writer.WriteUInt8(flags)) {
1301 return nullptr;
1302 }
1303
1304 if (!writer.WriteConnectionId(packet.connection_id)) {
1305 return nullptr;
1306 }
1307
1308 if (!writer.WriteBytes(reset_serialized.data(), reset_serialized.length())) {
1309 return nullptr;
1310 }
1311
vasilvv0fc587f2019-09-06 13:33:08 -07001312 return std::make_unique<QuicEncryptedPacket>(buffer.release(), len, true);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001313}
1314
1315// static
1316std::unique_ptr<QuicEncryptedPacket> QuicFramer::BuildIetfStatelessResetPacket(
dschinazi17d42422019-06-18 16:35:07 -07001317 QuicConnectionId /*connection_id*/,
QUICHE teama6ef0a62019-03-07 20:34:33 -05001318 QuicUint128 stateless_reset_token) {
1319 QUIC_DVLOG(1) << "Building IETF stateless reset packet.";
1320 size_t len = kPacketHeaderTypeSize + kMinRandomBytesLengthInStatelessReset +
1321 sizeof(stateless_reset_token);
1322 std::unique_ptr<char[]> buffer(new char[len]);
1323 QuicDataWriter writer(len, buffer.get());
1324
1325 uint8_t type = 0;
1326 type |= FLAGS_FIXED_BIT;
1327 type |= FLAGS_SHORT_HEADER_RESERVED_1;
1328 type |= FLAGS_SHORT_HEADER_RESERVED_2;
fayang36825da2019-08-21 14:01:27 -07001329 type |= PacketNumberLengthToOnWireValue(PACKET_1BYTE_PACKET_NUMBER);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001330
1331 // Append type byte.
1332 if (!writer.WriteUInt8(type)) {
1333 return nullptr;
1334 }
1335 // Append random bytes.
1336 if (!writer.WriteRandomBytes(QuicRandom::GetInstance(),
1337 kMinRandomBytesLengthInStatelessReset)) {
1338 return nullptr;
1339 }
1340
1341 // Append stateless reset token.
1342 if (!writer.WriteBytes(&stateless_reset_token,
1343 sizeof(stateless_reset_token))) {
1344 return nullptr;
1345 }
vasilvv0fc587f2019-09-06 13:33:08 -07001346 return std::make_unique<QuicEncryptedPacket>(buffer.release(), len, true);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001347}
1348
1349// static
1350std::unique_ptr<QuicEncryptedPacket> QuicFramer::BuildVersionNegotiationPacket(
dschinazi8ff74822019-05-28 16:37:20 -07001351 QuicConnectionId server_connection_id,
dschinazib417d602019-05-29 13:08:45 -07001352 QuicConnectionId client_connection_id,
QUICHE teama6ef0a62019-03-07 20:34:33 -05001353 bool ietf_quic,
dschinazi48ac9192019-07-31 00:07:26 -07001354 bool use_length_prefix,
QUICHE teama6ef0a62019-03-07 20:34:33 -05001355 const ParsedQuicVersionVector& versions) {
dschinazi1ac22cc2019-06-25 11:47:50 -07001356 ParsedQuicVersionVector wire_versions = versions;
1357 if (!GetQuicReloadableFlag(quic_version_negotiation_grease)) {
1358 if (wire_versions.empty()) {
1359 wire_versions = {QuicVersionReservedForNegotiation()};
1360 }
1361 } else {
1362 // Add a version reserved for negotiation as suggested by the
1363 // "Using Reserved Versions" section of draft-ietf-quic-transport.
1364 QUIC_RELOADABLE_FLAG_COUNT_N(quic_version_negotiation_grease, 1, 2);
1365 if (wire_versions.empty()) {
1366 // Ensure that version negotiation packets we send have at least two
1367 // versions. This guarantees that, under all circumstances, all QUIC
1368 // packets we send are at least 14 bytes long.
1369 wire_versions = {QuicVersionReservedForNegotiation(),
1370 QuicVersionReservedForNegotiation()};
1371 } else {
1372 // This is not uniformely distributed but is acceptable since no security
1373 // depends on this randomness.
1374 size_t version_index = 0;
1375 const bool disable_randomness =
1376 GetQuicFlag(FLAGS_quic_disable_version_negotiation_grease_randomness);
1377 if (!disable_randomness) {
1378 version_index = QuicRandom::GetInstance()->RandUint64() %
1379 (wire_versions.size() + 1);
1380 }
1381 wire_versions.insert(wire_versions.begin() + version_index,
1382 QuicVersionReservedForNegotiation());
1383 }
1384 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001385 if (ietf_quic) {
dschinazi1ac22cc2019-06-25 11:47:50 -07001386 return BuildIetfVersionNegotiationPacket(
dschinazi48ac9192019-07-31 00:07:26 -07001387 use_length_prefix, server_connection_id, client_connection_id,
1388 wire_versions);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001389 }
dschinazib417d602019-05-29 13:08:45 -07001390
1391 // The GQUIC encoding does not support encoding client connection IDs.
1392 DCHECK(client_connection_id.IsEmpty());
dschinazi48ac9192019-07-31 00:07:26 -07001393 // The GQUIC encoding does not support length-prefixed connection IDs.
1394 DCHECK(!use_length_prefix);
dschinazib417d602019-05-29 13:08:45 -07001395
dschinazi1ac22cc2019-06-25 11:47:50 -07001396 DCHECK(!wire_versions.empty());
dschinazi8ff74822019-05-28 16:37:20 -07001397 size_t len = kPublicFlagsSize + server_connection_id.length() +
dschinazi1ac22cc2019-06-25 11:47:50 -07001398 wire_versions.size() * kQuicVersionSize;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001399 std::unique_ptr<char[]> buffer(new char[len]);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001400 QuicDataWriter writer(len, buffer.get());
1401
1402 uint8_t flags = static_cast<uint8_t>(
1403 PACKET_PUBLIC_FLAGS_VERSION | PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID |
1404 // TODO(rch): Remove this QUIC_VERSION_32 is retired.
1405 PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID_OLD);
1406 if (!writer.WriteUInt8(flags)) {
1407 return nullptr;
1408 }
1409
dschinazi8ff74822019-05-28 16:37:20 -07001410 if (!writer.WriteConnectionId(server_connection_id)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001411 return nullptr;
1412 }
1413
dschinazi1ac22cc2019-06-25 11:47:50 -07001414 for (const ParsedQuicVersion& version : wire_versions) {
nharpereaab5ad2019-05-31 12:23:25 -07001415 if (!writer.WriteUInt32(CreateQuicVersionLabel(version))) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001416 return nullptr;
1417 }
1418 }
1419
vasilvv0fc587f2019-09-06 13:33:08 -07001420 return std::make_unique<QuicEncryptedPacket>(buffer.release(), len, true);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001421}
1422
1423// static
1424std::unique_ptr<QuicEncryptedPacket>
1425QuicFramer::BuildIetfVersionNegotiationPacket(
dschinazi48ac9192019-07-31 00:07:26 -07001426 bool use_length_prefix,
dschinazib417d602019-05-29 13:08:45 -07001427 QuicConnectionId server_connection_id,
1428 QuicConnectionId client_connection_id,
QUICHE teama6ef0a62019-03-07 20:34:33 -05001429 const ParsedQuicVersionVector& versions) {
dschinazi48ac9192019-07-31 00:07:26 -07001430 QUIC_DVLOG(1) << "Building IETF version negotiation packet with"
1431 << (use_length_prefix ? "" : "out")
1432 << " length prefix, server_connection_id "
1433 << server_connection_id << " client_connection_id "
1434 << client_connection_id << " versions "
dschinazi5a354c92019-05-09 12:18:53 -07001435 << ParsedQuicVersionVectorToString(versions);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001436 DCHECK(!versions.empty());
1437 size_t len = kPacketHeaderTypeSize + kConnectionIdLengthSize +
dschinazib417d602019-05-29 13:08:45 -07001438 client_connection_id.length() + server_connection_id.length() +
QUICHE teama6ef0a62019-03-07 20:34:33 -05001439 (versions.size() + 1) * kQuicVersionSize;
dschinazi48ac9192019-07-31 00:07:26 -07001440 if (use_length_prefix) {
1441 // When using length-prefixed connection IDs, packets carry two lengths
1442 // instead of one.
1443 len += kConnectionIdLengthSize;
1444 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001445 std::unique_ptr<char[]> buffer(new char[len]);
1446 QuicDataWriter writer(len, buffer.get());
1447
1448 // TODO(fayang): Randomly select a value for the type.
dschinazi0366de92019-06-18 20:00:27 -07001449 uint8_t type = static_cast<uint8_t>(FLAGS_LONG_HEADER | FLAGS_FIXED_BIT);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001450 if (!writer.WriteUInt8(type)) {
1451 return nullptr;
1452 }
1453
1454 if (!writer.WriteUInt32(0)) {
1455 return nullptr;
1456 }
1457
dschinazi48ac9192019-07-31 00:07:26 -07001458 if (!AppendIetfConnectionIds(true, use_length_prefix, client_connection_id,
1459 server_connection_id, &writer)) {
dschinazi1f485a12019-05-13 11:57:01 -07001460 return nullptr;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001461 }
1462
1463 for (const ParsedQuicVersion& version : versions) {
nharpereaab5ad2019-05-31 12:23:25 -07001464 if (!writer.WriteUInt32(CreateQuicVersionLabel(version))) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001465 return nullptr;
1466 }
1467 }
1468
vasilvv0fc587f2019-09-06 13:33:08 -07001469 return std::make_unique<QuicEncryptedPacket>(buffer.release(), len, true);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001470}
1471
1472bool QuicFramer::ProcessPacket(const QuicEncryptedPacket& packet) {
1473 QuicDataReader reader(packet.data(), packet.length());
1474
1475 bool packet_has_ietf_packet_header = false;
1476 if (infer_packet_header_type_from_version_) {
1477 packet_has_ietf_packet_header =
fayangd4291e42019-05-30 10:31:21 -07001478 VersionHasIetfInvariantHeader(version_.transport_version);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001479 } else if (!reader.IsDoneReading()) {
1480 uint8_t type = reader.PeekByte();
1481 packet_has_ietf_packet_header = QuicUtils::IsIetfPacketHeader(type);
1482 }
1483 if (packet_has_ietf_packet_header) {
1484 QUIC_DVLOG(1) << ENDPOINT << "Processing IETF QUIC packet.";
1485 }
1486
1487 visitor_->OnPacket();
1488
1489 QuicPacketHeader header;
1490 if (!ProcessPublicHeader(&reader, packet_has_ietf_packet_header, &header)) {
1491 DCHECK_NE("", detailed_error_);
1492 QUIC_DVLOG(1) << ENDPOINT << "Unable to process public header. Error: "
1493 << detailed_error_;
1494 DCHECK_NE("", detailed_error_);
1495 RecordDroppedPacketReason(DroppedPacketReason::INVALID_PUBLIC_HEADER);
1496 return RaiseError(QUIC_INVALID_PACKET_HEADER);
1497 }
1498
1499 if (!visitor_->OnUnauthenticatedPublicHeader(header)) {
1500 // The visitor suppresses further processing of the packet.
1501 return true;
1502 }
1503
dschinazie0df3f72019-05-06 16:37:51 -07001504 if (IsVersionNegotiation(header, packet_has_ietf_packet_header)) {
dschinazi072da7c2019-05-07 17:57:42 -07001505 if (perspective_ == Perspective::IS_CLIENT) {
1506 QUIC_DVLOG(1) << "Client received version negotiation packet";
1507 return ProcessVersionNegotiationPacket(&reader, header);
1508 } else {
1509 QUIC_DLOG(ERROR) << "Server received version negotiation packet";
1510 set_detailed_error("Server received version negotiation packet.");
1511 return RaiseError(QUIC_INVALID_VERSION_NEGOTIATION_PACKET);
1512 }
dschinazie0df3f72019-05-06 16:37:51 -07001513 }
1514
1515 if (header.version_flag && header.version != version_) {
1516 if (perspective_ == Perspective::IS_SERVER) {
fayang8aba1ff2019-06-21 12:00:54 -07001517 if (!visitor_->OnProtocolVersionMismatch(header.version)) {
dschinazie0df3f72019-05-06 16:37:51 -07001518 RecordDroppedPacketReason(DroppedPacketReason::VERSION_MISMATCH);
1519 return true;
1520 }
1521 } else {
1522 // A client received a packet of a different version but that packet is
1523 // not a version negotiation packet. It is therefore invalid and dropped.
1524 QUIC_DLOG(ERROR) << "Client received unexpected version "
1525 << ParsedQuicVersionToString(header.version)
1526 << " instead of " << ParsedQuicVersionToString(version_);
1527 set_detailed_error("Client received unexpected version.");
1528 return RaiseError(QUIC_INVALID_VERSION);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001529 }
1530 }
1531
1532 bool rv;
dschinazie0df3f72019-05-06 16:37:51 -07001533 if (header.long_packet_type == RETRY) {
dschinazi244f6dc2019-05-06 15:45:16 -07001534 rv = ProcessRetryPacket(&reader, header);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001535 } else if (header.reset_flag) {
1536 rv = ProcessPublicResetPacket(&reader, header);
dschinazie8d7fa72019-04-05 14:44:40 -07001537 } else if (packet.length() <= kMaxIncomingPacketSize) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001538 // The optimized decryption algorithm implementations run faster when
1539 // operating on aligned memory.
dschinazie8d7fa72019-04-05 14:44:40 -07001540 QUIC_CACHELINE_ALIGNED char buffer[kMaxIncomingPacketSize];
QUICHE teama6ef0a62019-03-07 20:34:33 -05001541 if (packet_has_ietf_packet_header) {
1542 rv = ProcessIetfDataPacket(&reader, &header, packet, buffer,
dschinazie8d7fa72019-04-05 14:44:40 -07001543 QUIC_ARRAYSIZE(buffer));
QUICHE teama6ef0a62019-03-07 20:34:33 -05001544 } else {
dschinazie8d7fa72019-04-05 14:44:40 -07001545 rv = ProcessDataPacket(&reader, &header, packet, buffer,
1546 QUIC_ARRAYSIZE(buffer));
QUICHE teama6ef0a62019-03-07 20:34:33 -05001547 }
1548 } else {
1549 std::unique_ptr<char[]> large_buffer(new char[packet.length()]);
1550 if (packet_has_ietf_packet_header) {
1551 rv = ProcessIetfDataPacket(&reader, &header, packet, large_buffer.get(),
1552 packet.length());
1553 } else {
1554 rv = ProcessDataPacket(&reader, &header, packet, large_buffer.get(),
1555 packet.length());
1556 }
1557 QUIC_BUG_IF(rv) << "QUIC should never successfully process packets larger"
dschinazie8d7fa72019-04-05 14:44:40 -07001558 << "than kMaxIncomingPacketSize. packet size:"
1559 << packet.length();
QUICHE teama6ef0a62019-03-07 20:34:33 -05001560 }
1561 return rv;
1562}
1563
1564bool QuicFramer::ProcessVersionNegotiationPacket(
1565 QuicDataReader* reader,
1566 const QuicPacketHeader& header) {
1567 DCHECK_EQ(Perspective::IS_CLIENT, perspective_);
1568
QUICHE team2252b702019-05-14 23:55:14 -04001569 QuicVersionNegotiationPacket packet(
1570 GetServerConnectionIdAsRecipient(header, perspective_));
QUICHE teama6ef0a62019-03-07 20:34:33 -05001571 // Try reading at least once to raise error if the packet is invalid.
1572 do {
1573 QuicVersionLabel version_label;
fayang40315542019-05-09 09:19:09 -07001574 if (!ProcessVersionLabel(reader, &version_label)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001575 set_detailed_error("Unable to read supported version in negotiation.");
1576 RecordDroppedPacketReason(
1577 DroppedPacketReason::INVALID_VERSION_NEGOTIATION_PACKET);
1578 return RaiseError(QUIC_INVALID_VERSION_NEGOTIATION_PACKET);
1579 }
nharper4fd11052019-06-04 14:23:22 -07001580 ParsedQuicVersion parsed_version = ParseQuicVersionLabel(version_label);
1581 if (parsed_version != UnsupportedQuicVersion()) {
1582 packet.versions.push_back(parsed_version);
1583 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001584 } while (!reader->IsDoneReading());
1585
dschinazi5a354c92019-05-09 12:18:53 -07001586 QUIC_DLOG(INFO) << ENDPOINT << "parsed version negotiation: "
1587 << ParsedQuicVersionVectorToString(packet.versions);
1588
QUICHE teama6ef0a62019-03-07 20:34:33 -05001589 visitor_->OnVersionNegotiationPacket(packet);
1590 return true;
1591}
1592
dschinazi244f6dc2019-05-06 15:45:16 -07001593bool QuicFramer::ProcessRetryPacket(QuicDataReader* reader,
1594 const QuicPacketHeader& header) {
1595 DCHECK_EQ(Perspective::IS_CLIENT, perspective_);
1596
dschinazi244f6dc2019-05-06 15:45:16 -07001597 QuicConnectionId original_destination_connection_id;
dschinazi48ac9192019-07-31 00:07:26 -07001598 if (version_.HasLengthPrefixedConnectionIds()) {
1599 // Parse Original Destination Connection ID.
1600 if (!reader->ReadLengthPrefixedConnectionId(
1601 &original_destination_connection_id)) {
1602 set_detailed_error("Unable to read Original Destination ConnectionId.");
1603 return false;
1604 }
1605 } else {
1606 // Parse Original Destination Connection ID Length.
1607 uint8_t odcil = header.type_byte & 0xf;
1608 if (odcil != 0) {
1609 odcil += kConnectionIdLengthAdjustment;
1610 }
1611
1612 // Parse Original Destination Connection ID.
1613 if (!reader->ReadConnectionId(&original_destination_connection_id, odcil)) {
1614 set_detailed_error("Unable to read Original Destination ConnectionId.");
1615 return false;
1616 }
dschinazi244f6dc2019-05-06 15:45:16 -07001617 }
1618
dschinazib953d022019-08-01 18:05:58 -07001619 if (!QuicUtils::IsConnectionIdValidForVersion(
1620 original_destination_connection_id, transport_version())) {
1621 set_detailed_error(
1622 "Received Original Destination ConnectionId with invalid length.");
1623 return false;
1624 }
1625
dschinazi244f6dc2019-05-06 15:45:16 -07001626 QuicStringPiece retry_token = reader->ReadRemainingPayload();
1627 visitor_->OnRetryPacket(original_destination_connection_id,
1628 header.source_connection_id, retry_token);
1629 return true;
1630}
1631
QUICHE teama6ef0a62019-03-07 20:34:33 -05001632// Seeks the current packet to check for a coalesced packet at the end.
1633// If the IETF length field only spans part of the outer packet,
1634// then there is a coalesced packet after this one.
1635void QuicFramer::MaybeProcessCoalescedPacket(
1636 const QuicDataReader& encrypted_reader,
1637 uint64_t remaining_bytes_length,
1638 const QuicPacketHeader& header) {
1639 if (header.remaining_packet_length >= remaining_bytes_length) {
1640 // There is no coalesced packet.
1641 return;
1642 }
1643
1644 QuicStringPiece remaining_data = encrypted_reader.PeekRemainingPayload();
1645 DCHECK_EQ(remaining_data.length(), remaining_bytes_length);
1646
1647 const char* coalesced_data =
1648 remaining_data.data() + header.remaining_packet_length;
1649 uint64_t coalesced_data_length =
1650 remaining_bytes_length - header.remaining_packet_length;
1651 QuicDataReader coalesced_reader(coalesced_data, coalesced_data_length);
1652
1653 QuicPacketHeader coalesced_header;
1654 if (!ProcessIetfPacketHeader(&coalesced_reader, &coalesced_header)) {
1655 QUIC_PEER_BUG << ENDPOINT
1656 << "Failed to parse received coalesced header of length "
1657 << coalesced_data_length << ": "
1658 << QuicTextUtils::HexEncode(coalesced_data,
1659 coalesced_data_length)
1660 << " previous header was " << header;
1661 return;
1662 }
1663
1664 if (coalesced_header.destination_connection_id !=
1665 header.destination_connection_id ||
1666 (coalesced_header.form != IETF_QUIC_SHORT_HEADER_PACKET &&
1667 coalesced_header.version != header.version)) {
1668 QUIC_PEER_BUG << ENDPOINT << "Received mismatched coalesced header "
1669 << coalesced_header << " previous header was " << header;
1670 return;
1671 }
1672
1673 QuicEncryptedPacket coalesced_packet(coalesced_data, coalesced_data_length,
1674 /*owns_buffer=*/false);
1675 visitor_->OnCoalescedPacket(coalesced_packet);
1676}
1677
1678bool QuicFramer::MaybeProcessIetfLength(QuicDataReader* encrypted_reader,
1679 QuicPacketHeader* header) {
1680 if (!QuicVersionHasLongHeaderLengths(header->version.transport_version) ||
1681 header->form != IETF_QUIC_LONG_HEADER_PACKET ||
1682 (header->long_packet_type != INITIAL &&
1683 header->long_packet_type != HANDSHAKE &&
1684 header->long_packet_type != ZERO_RTT_PROTECTED)) {
1685 return true;
1686 }
1687 header->length_length = encrypted_reader->PeekVarInt62Length();
1688 if (!encrypted_reader->ReadVarInt62(&header->remaining_packet_length)) {
1689 set_detailed_error("Unable to read long header payload length.");
1690 return RaiseError(QUIC_INVALID_PACKET_HEADER);
1691 }
1692 uint64_t remaining_bytes_length = encrypted_reader->BytesRemaining();
1693 if (header->remaining_packet_length > remaining_bytes_length) {
1694 set_detailed_error("Long header payload length longer than packet.");
1695 return RaiseError(QUIC_INVALID_PACKET_HEADER);
1696 }
1697
1698 MaybeProcessCoalescedPacket(*encrypted_reader, remaining_bytes_length,
1699 *header);
1700
1701 if (!encrypted_reader->TruncateRemaining(header->remaining_packet_length)) {
1702 set_detailed_error("Length TruncateRemaining failed.");
1703 QUIC_BUG << "Length TruncateRemaining failed.";
1704 return RaiseError(QUIC_INVALID_PACKET_HEADER);
1705 }
1706 return true;
1707}
1708
1709bool QuicFramer::ProcessIetfDataPacket(QuicDataReader* encrypted_reader,
1710 QuicPacketHeader* header,
1711 const QuicEncryptedPacket& packet,
1712 char* decrypted_buffer,
1713 size_t buffer_length) {
1714 DCHECK_NE(GOOGLE_QUIC_PACKET, header->form);
1715 DCHECK(!header->has_possible_stateless_reset_token);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001716 header->length_length = VARIABLE_LENGTH_INTEGER_LENGTH_0;
1717 header->remaining_packet_length = 0;
1718 if (header->form == IETF_QUIC_SHORT_HEADER_PACKET &&
1719 perspective_ == Perspective::IS_CLIENT) {
1720 // Peek possible stateless reset token. Will only be used on decryption
1721 // failure.
1722 QuicStringPiece remaining = encrypted_reader->PeekRemainingPayload();
1723 if (remaining.length() >= sizeof(header->possible_stateless_reset_token)) {
1724 header->has_possible_stateless_reset_token = true;
1725 memcpy(&header->possible_stateless_reset_token,
1726 &remaining.data()[remaining.length() -
1727 sizeof(header->possible_stateless_reset_token)],
1728 sizeof(header->possible_stateless_reset_token));
1729 }
1730 }
1731
QUICHE teama6ef0a62019-03-07 20:34:33 -05001732 if (!MaybeProcessIetfLength(encrypted_reader, header)) {
1733 return false;
1734 }
1735
nharper55fa6132019-05-07 19:37:21 -07001736 QuicStringPiece associated_data;
1737 std::vector<char> ad_storage;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001738 if (header->form == IETF_QUIC_SHORT_HEADER_PACKET ||
1739 header->long_packet_type != VERSION_NEGOTIATION) {
dschinazi072da7c2019-05-07 17:57:42 -07001740 DCHECK(header->form == IETF_QUIC_SHORT_HEADER_PACKET ||
1741 header->long_packet_type == INITIAL ||
1742 header->long_packet_type == HANDSHAKE ||
1743 header->long_packet_type == ZERO_RTT_PROTECTED);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001744 // Process packet number.
QUICHE team10b22a12019-03-21 15:31:42 -07001745 QuicPacketNumber base_packet_number;
1746 if (supports_multiple_packet_number_spaces_) {
nharper55fa6132019-05-07 19:37:21 -07001747 PacketNumberSpace pn_space = GetPacketNumberSpace(*header);
1748 if (pn_space == NUM_PACKET_NUMBER_SPACES) {
1749 return RaiseError(QUIC_INVALID_PACKET_HEADER);
1750 }
1751 base_packet_number = largest_decrypted_packet_numbers_[pn_space];
QUICHE team10b22a12019-03-21 15:31:42 -07001752 } else {
1753 base_packet_number = largest_packet_number_;
1754 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001755 uint64_t full_packet_number;
nharper55fa6132019-05-07 19:37:21 -07001756 bool hp_removal_failed = false;
1757 if (version_.HasHeaderProtection()) {
1758 if (!RemoveHeaderProtection(encrypted_reader, packet, header,
1759 &full_packet_number, &ad_storage)) {
1760 hp_removal_failed = true;
1761 }
1762 associated_data = QuicStringPiece(ad_storage.data(), ad_storage.size());
1763 } else if (!ProcessAndCalculatePacketNumber(
1764 encrypted_reader, header->packet_number_length,
1765 base_packet_number, &full_packet_number)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001766 set_detailed_error("Unable to read packet number.");
1767 RecordDroppedPacketReason(DroppedPacketReason::INVALID_PACKET_NUMBER);
1768 return RaiseError(QUIC_INVALID_PACKET_HEADER);
1769 }
1770
nharper55fa6132019-05-07 19:37:21 -07001771 if (hp_removal_failed ||
1772 !IsValidFullPacketNumber(full_packet_number, transport_version())) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001773 if (IsIetfStatelessResetPacket(*header)) {
1774 // This is a stateless reset packet.
1775 QuicIetfStatelessResetPacket packet(
1776 *header, header->possible_stateless_reset_token);
1777 visitor_->OnAuthenticatedIetfStatelessResetPacket(packet);
1778 return true;
1779 }
nharper55fa6132019-05-07 19:37:21 -07001780 if (hp_removal_failed) {
dschinazi4b5a68a2019-08-15 15:45:36 -07001781 if (GetQuicRestartFlag(quic_framer_uses_undecryptable_upcall)) {
1782 QUIC_RESTART_FLAG_COUNT_N(quic_framer_uses_undecryptable_upcall, 5,
1783 7);
1784 const EncryptionLevel decryption_level = GetEncryptionLevel(*header);
1785 const bool has_decryption_key =
1786 decrypter_[decryption_level] != nullptr;
1787 visitor_->OnUndecryptablePacket(
1788 QuicEncryptedPacket(encrypted_reader->FullPayload()),
1789 decryption_level, has_decryption_key);
1790 }
nharper55fa6132019-05-07 19:37:21 -07001791 set_detailed_error("Unable to decrypt header protection.");
1792 return RaiseError(QUIC_DECRYPTION_FAILURE);
1793 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001794 RecordDroppedPacketReason(DroppedPacketReason::INVALID_PACKET_NUMBER);
1795 set_detailed_error("packet numbers cannot be 0.");
1796 return RaiseError(QUIC_INVALID_PACKET_HEADER);
1797 }
1798 header->packet_number = QuicPacketNumber(full_packet_number);
1799 }
1800
1801 // A nonce should only present in SHLO from the server to the client when
1802 // using QUIC crypto.
1803 if (header->form == IETF_QUIC_LONG_HEADER_PACKET &&
1804 header->long_packet_type == ZERO_RTT_PROTECTED &&
1805 perspective_ == Perspective::IS_CLIENT &&
1806 version_.handshake_protocol == PROTOCOL_QUIC_CRYPTO) {
1807 if (!encrypted_reader->ReadBytes(
1808 reinterpret_cast<uint8_t*>(last_nonce_.data()),
1809 last_nonce_.size())) {
1810 set_detailed_error("Unable to read nonce.");
1811 RecordDroppedPacketReason(
1812 DroppedPacketReason::INVALID_DIVERSIFICATION_NONCE);
1813 return RaiseError(QUIC_INVALID_PACKET_HEADER);
1814 }
1815
1816 header->nonce = &last_nonce_;
1817 } else {
1818 header->nonce = nullptr;
1819 }
1820
1821 if (!visitor_->OnUnauthenticatedHeader(*header)) {
1822 set_detailed_error(
1823 "Visitor asked to stop processing of unauthenticated header.");
1824 return false;
1825 }
1826
1827 QuicStringPiece encrypted = encrypted_reader->ReadRemainingPayload();
nharper55fa6132019-05-07 19:37:21 -07001828 if (!version_.HasHeaderProtection()) {
1829 associated_data = GetAssociatedDataFromEncryptedPacket(
1830 version_.transport_version, packet,
1831 GetIncludedDestinationConnectionIdLength(*header),
1832 GetIncludedSourceConnectionIdLength(*header), header->version_flag,
1833 header->nonce != nullptr, header->packet_number_length,
1834 header->retry_token_length_length, header->retry_token.length(),
1835 header->length_length);
1836 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001837
1838 size_t decrypted_length = 0;
QUICHE team10b22a12019-03-21 15:31:42 -07001839 EncryptionLevel decrypted_level;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001840 if (!DecryptPayload(encrypted, associated_data, *header, decrypted_buffer,
QUICHE team10b22a12019-03-21 15:31:42 -07001841 buffer_length, &decrypted_length, &decrypted_level)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001842 if (IsIetfStatelessResetPacket(*header)) {
1843 // This is a stateless reset packet.
1844 QuicIetfStatelessResetPacket packet(
1845 *header, header->possible_stateless_reset_token);
1846 visitor_->OnAuthenticatedIetfStatelessResetPacket(packet);
1847 return true;
1848 }
dschinazi4b5a68a2019-08-15 15:45:36 -07001849 if (GetQuicRestartFlag(quic_framer_uses_undecryptable_upcall)) {
1850 QUIC_RESTART_FLAG_COUNT_N(quic_framer_uses_undecryptable_upcall, 6, 7);
1851 const EncryptionLevel decryption_level = GetEncryptionLevel(*header);
1852 const bool has_decryption_key = version_.KnowsWhichDecrypterToUse() &&
1853 decrypter_[decryption_level] != nullptr;
1854 visitor_->OnUndecryptablePacket(
1855 QuicEncryptedPacket(encrypted_reader->FullPayload()),
1856 decryption_level, has_decryption_key);
1857 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001858 set_detailed_error("Unable to decrypt payload.");
1859 RecordDroppedPacketReason(DroppedPacketReason::DECRYPTION_FAILURE);
1860 return RaiseError(QUIC_DECRYPTION_FAILURE);
1861 }
1862 QuicDataReader reader(decrypted_buffer, decrypted_length);
1863
1864 // Update the largest packet number after we have decrypted the packet
1865 // so we are confident is not attacker controlled.
QUICHE team10b22a12019-03-21 15:31:42 -07001866 if (supports_multiple_packet_number_spaces_) {
1867 largest_decrypted_packet_numbers_[QuicUtils::GetPacketNumberSpace(
1868 decrypted_level)]
1869 .UpdateMax(header->packet_number);
1870 } else {
1871 largest_packet_number_.UpdateMax(header->packet_number);
1872 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001873
1874 if (!visitor_->OnPacketHeader(*header)) {
1875 RecordDroppedPacketReason(DroppedPacketReason::INVALID_PACKET_NUMBER);
1876 // The visitor suppresses further processing of the packet.
1877 return true;
1878 }
1879
dschinazie8d7fa72019-04-05 14:44:40 -07001880 if (packet.length() > kMaxIncomingPacketSize) {
1881 set_detailed_error("Packet too large.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05001882 return RaiseError(QUIC_PACKET_TOO_LARGE);
1883 }
1884
1885 // Handle the payload.
fkastenholz305e1732019-06-18 05:01:22 -07001886 if (VersionHasIetfQuicFrames(version_.transport_version)) {
fkastenholza3660102019-08-28 05:19:24 -07001887 current_received_frame_type_ = 0;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001888 if (!ProcessIetfFrameData(&reader, *header)) {
fkastenholza3660102019-08-28 05:19:24 -07001889 current_received_frame_type_ = 0;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001890 DCHECK_NE(QUIC_NO_ERROR, error_); // ProcessIetfFrameData sets the error.
1891 DCHECK_NE("", detailed_error_);
1892 QUIC_DLOG(WARNING) << ENDPOINT << "Unable to process frame data. Error: "
1893 << detailed_error_;
1894 return false;
1895 }
fkastenholza3660102019-08-28 05:19:24 -07001896 current_received_frame_type_ = 0;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001897 } else {
1898 if (!ProcessFrameData(&reader, *header)) {
1899 DCHECK_NE(QUIC_NO_ERROR, error_); // ProcessFrameData sets the error.
1900 DCHECK_NE("", detailed_error_);
1901 QUIC_DLOG(WARNING) << ENDPOINT << "Unable to process frame data. Error: "
1902 << detailed_error_;
1903 return false;
1904 }
1905 }
1906
1907 visitor_->OnPacketComplete();
1908 return true;
1909}
1910
1911bool QuicFramer::ProcessDataPacket(QuicDataReader* encrypted_reader,
1912 QuicPacketHeader* header,
1913 const QuicEncryptedPacket& packet,
1914 char* decrypted_buffer,
1915 size_t buffer_length) {
1916 if (!ProcessUnauthenticatedHeader(encrypted_reader, header)) {
1917 DCHECK_NE("", detailed_error_);
1918 QUIC_DVLOG(1)
1919 << ENDPOINT
1920 << "Unable to process packet header. Stopping parsing. Error: "
1921 << detailed_error_;
1922 RecordDroppedPacketReason(DroppedPacketReason::INVALID_PACKET_NUMBER);
1923 return false;
1924 }
1925
1926 QuicStringPiece encrypted = encrypted_reader->ReadRemainingPayload();
1927 QuicStringPiece associated_data = GetAssociatedDataFromEncryptedPacket(
1928 version_.transport_version, packet,
1929 GetIncludedDestinationConnectionIdLength(*header),
1930 GetIncludedSourceConnectionIdLength(*header), header->version_flag,
1931 header->nonce != nullptr, header->packet_number_length,
1932 header->retry_token_length_length, header->retry_token.length(),
1933 header->length_length);
1934
1935 size_t decrypted_length = 0;
QUICHE team10b22a12019-03-21 15:31:42 -07001936 EncryptionLevel decrypted_level;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001937 if (!DecryptPayload(encrypted, associated_data, *header, decrypted_buffer,
QUICHE team10b22a12019-03-21 15:31:42 -07001938 buffer_length, &decrypted_length, &decrypted_level)) {
dschinazi4b5a68a2019-08-15 15:45:36 -07001939 if (GetQuicRestartFlag(quic_framer_uses_undecryptable_upcall)) {
1940 QUIC_RESTART_FLAG_COUNT_N(quic_framer_uses_undecryptable_upcall, 7, 7);
1941 const EncryptionLevel decryption_level = decrypter_level_;
1942 // This version uses trial decryption so we always report to our visitor
1943 // that we are not certain we have the correct decryption key.
1944 const bool has_decryption_key = false;
1945 visitor_->OnUndecryptablePacket(
1946 QuicEncryptedPacket(encrypted_reader->FullPayload()),
1947 decryption_level, has_decryption_key);
1948 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001949 RecordDroppedPacketReason(DroppedPacketReason::DECRYPTION_FAILURE);
1950 set_detailed_error("Unable to decrypt payload.");
1951 return RaiseError(QUIC_DECRYPTION_FAILURE);
1952 }
1953
1954 QuicDataReader reader(decrypted_buffer, decrypted_length);
1955
1956 // Update the largest packet number after we have decrypted the packet
1957 // so we are confident is not attacker controlled.
QUICHE team10b22a12019-03-21 15:31:42 -07001958 if (supports_multiple_packet_number_spaces_) {
1959 largest_decrypted_packet_numbers_[QuicUtils::GetPacketNumberSpace(
1960 decrypted_level)]
1961 .UpdateMax(header->packet_number);
1962 } else {
1963 largest_packet_number_.UpdateMax(header->packet_number);
1964 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001965
1966 if (!visitor_->OnPacketHeader(*header)) {
1967 // The visitor suppresses further processing of the packet.
1968 return true;
1969 }
1970
dschinazie8d7fa72019-04-05 14:44:40 -07001971 if (packet.length() > kMaxIncomingPacketSize) {
1972 set_detailed_error("Packet too large.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05001973 return RaiseError(QUIC_PACKET_TOO_LARGE);
1974 }
1975
1976 // Handle the payload.
1977 if (!ProcessFrameData(&reader, *header)) {
1978 DCHECK_NE(QUIC_NO_ERROR, error_); // ProcessFrameData sets the error.
1979 DCHECK_NE("", detailed_error_);
1980 QUIC_DLOG(WARNING) << ENDPOINT << "Unable to process frame data. Error: "
1981 << detailed_error_;
1982 return false;
1983 }
1984
1985 visitor_->OnPacketComplete();
1986 return true;
1987}
1988
1989bool QuicFramer::ProcessPublicResetPacket(QuicDataReader* reader,
1990 const QuicPacketHeader& header) {
QUICHE team2252b702019-05-14 23:55:14 -04001991 QuicPublicResetPacket packet(
1992 GetServerConnectionIdAsRecipient(header, perspective_));
QUICHE teama6ef0a62019-03-07 20:34:33 -05001993
1994 std::unique_ptr<CryptoHandshakeMessage> reset(
1995 CryptoFramer::ParseMessage(reader->ReadRemainingPayload()));
1996 if (!reset.get()) {
1997 set_detailed_error("Unable to read reset message.");
1998 RecordDroppedPacketReason(DroppedPacketReason::INVALID_PUBLIC_RESET_PACKET);
1999 return RaiseError(QUIC_INVALID_PUBLIC_RST_PACKET);
2000 }
2001 if (reset->tag() != kPRST) {
2002 set_detailed_error("Incorrect message tag.");
2003 RecordDroppedPacketReason(DroppedPacketReason::INVALID_PUBLIC_RESET_PACKET);
2004 return RaiseError(QUIC_INVALID_PUBLIC_RST_PACKET);
2005 }
2006
2007 if (reset->GetUint64(kRNON, &packet.nonce_proof) != QUIC_NO_ERROR) {
2008 set_detailed_error("Unable to read nonce proof.");
2009 RecordDroppedPacketReason(DroppedPacketReason::INVALID_PUBLIC_RESET_PACKET);
2010 return RaiseError(QUIC_INVALID_PUBLIC_RST_PACKET);
2011 }
2012 // TODO(satyamshekhar): validate nonce to protect against DoS.
2013
2014 QuicStringPiece address;
2015 if (reset->GetStringPiece(kCADR, &address)) {
2016 QuicSocketAddressCoder address_coder;
2017 if (address_coder.Decode(address.data(), address.length())) {
2018 packet.client_address =
2019 QuicSocketAddress(address_coder.ip(), address_coder.port());
2020 }
2021 }
2022
2023 QuicStringPiece endpoint_id;
2024 if (perspective_ == Perspective::IS_CLIENT &&
2025 reset->GetStringPiece(kEPID, &endpoint_id)) {
vasilvvc48c8712019-03-11 13:38:16 -07002026 packet.endpoint_id = std::string(endpoint_id);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002027 packet.endpoint_id += '\0';
2028 }
2029
2030 visitor_->OnPublicResetPacket(packet);
2031 return true;
2032}
2033
2034bool QuicFramer::IsIetfStatelessResetPacket(
2035 const QuicPacketHeader& header) const {
2036 QUIC_BUG_IF(header.has_possible_stateless_reset_token &&
2037 perspective_ != Perspective::IS_CLIENT)
2038 << "has_possible_stateless_reset_token can only be true at client side.";
2039 return header.form == IETF_QUIC_SHORT_HEADER_PACKET &&
2040 header.has_possible_stateless_reset_token &&
2041 visitor_->IsValidStatelessResetToken(
2042 header.possible_stateless_reset_token);
2043}
2044
2045bool QuicFramer::HasEncrypterOfEncryptionLevel(EncryptionLevel level) const {
2046 return encrypter_[level] != nullptr;
2047}
2048
2049bool QuicFramer::AppendPacketHeader(const QuicPacketHeader& header,
2050 QuicDataWriter* writer,
2051 size_t* length_field_offset) {
fayangd4291e42019-05-30 10:31:21 -07002052 if (VersionHasIetfInvariantHeader(transport_version())) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002053 return AppendIetfPacketHeader(header, writer, length_field_offset);
2054 }
2055 QUIC_DVLOG(1) << ENDPOINT << "Appending header: " << header;
2056 uint8_t public_flags = 0;
2057 if (header.reset_flag) {
2058 public_flags |= PACKET_PUBLIC_FLAGS_RST;
2059 }
2060 if (header.version_flag) {
2061 public_flags |= PACKET_PUBLIC_FLAGS_VERSION;
2062 }
2063
2064 public_flags |= GetPacketNumberFlags(header.packet_number_length)
2065 << kPublicHeaderSequenceNumberShift;
2066
2067 if (header.nonce != nullptr) {
2068 DCHECK_EQ(Perspective::IS_SERVER, perspective_);
2069 public_flags |= PACKET_PUBLIC_FLAGS_NONCE;
2070 }
QUICHE team2252b702019-05-14 23:55:14 -04002071
dschinazi7b9278c2019-05-20 07:36:21 -07002072 QuicConnectionId server_connection_id =
QUICHE team2252b702019-05-14 23:55:14 -04002073 GetServerConnectionIdAsSender(header, perspective_);
dschinazi7b9278c2019-05-20 07:36:21 -07002074 QuicConnectionIdIncluded server_connection_id_included =
QUICHE team2252b702019-05-14 23:55:14 -04002075 GetServerConnectionIdIncludedAsSender(header, perspective_);
2076 DCHECK_EQ(CONNECTION_ID_ABSENT,
dschinazic075ffa2019-06-27 16:17:37 -07002077 GetClientConnectionIdIncludedAsSender(header, perspective_))
2078 << ENDPOINT << ParsedQuicVersionToString(version_)
2079 << " invalid header: " << header;
QUICHE team2252b702019-05-14 23:55:14 -04002080
dschinazi7b9278c2019-05-20 07:36:21 -07002081 switch (server_connection_id_included) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002082 case CONNECTION_ID_ABSENT:
2083 if (!writer->WriteUInt8(public_flags |
2084 PACKET_PUBLIC_FLAGS_0BYTE_CONNECTION_ID)) {
2085 return false;
2086 }
2087 break;
2088 case CONNECTION_ID_PRESENT:
2089 QUIC_BUG_IF(!QuicUtils::IsConnectionIdValidForVersion(
dschinazi7b9278c2019-05-20 07:36:21 -07002090 server_connection_id, transport_version()))
QUICHE teama6ef0a62019-03-07 20:34:33 -05002091 << "AppendPacketHeader: attempted to use connection ID "
dschinazi7b9278c2019-05-20 07:36:21 -07002092 << server_connection_id << " which is invalid with version "
QUICHE teama6ef0a62019-03-07 20:34:33 -05002093 << QuicVersionToString(transport_version());
2094
2095 public_flags |= PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID;
2096 if (perspective_ == Perspective::IS_CLIENT) {
2097 public_flags |= PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID_OLD;
2098 }
2099 if (!writer->WriteUInt8(public_flags) ||
dschinazi7b9278c2019-05-20 07:36:21 -07002100 !writer->WriteConnectionId(server_connection_id)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002101 return false;
2102 }
2103 break;
2104 }
dschinazi7b9278c2019-05-20 07:36:21 -07002105 last_serialized_server_connection_id_ = server_connection_id;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002106
2107 if (header.version_flag) {
2108 DCHECK_EQ(Perspective::IS_CLIENT, perspective_);
2109 QuicVersionLabel version_label = CreateQuicVersionLabel(version_);
nharpereaab5ad2019-05-31 12:23:25 -07002110 if (!writer->WriteUInt32(version_label)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002111 return false;
2112 }
2113
2114 QUIC_DVLOG(1) << ENDPOINT << "label = '"
2115 << QuicVersionLabelToString(version_label) << "'";
2116 }
2117
2118 if (header.nonce != nullptr &&
2119 !writer->WriteBytes(header.nonce, kDiversificationNonceSize)) {
2120 return false;
2121 }
2122
2123 if (!AppendPacketNumber(header.packet_number_length, header.packet_number,
2124 writer)) {
2125 return false;
2126 }
2127
2128 return true;
2129}
2130
2131bool QuicFramer::AppendIetfHeaderTypeByte(const QuicPacketHeader& header,
2132 QuicDataWriter* writer) {
2133 uint8_t type = 0;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002134 if (header.version_flag) {
2135 type = static_cast<uint8_t>(
fayang36825da2019-08-21 14:01:27 -07002136 FLAGS_LONG_HEADER | FLAGS_FIXED_BIT |
2137 LongHeaderTypeToOnWireValue(header.long_packet_type) |
2138 PacketNumberLengthToOnWireValue(header.packet_number_length));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002139 } else {
fayang36825da2019-08-21 14:01:27 -07002140 type = static_cast<uint8_t>(
2141 FLAGS_FIXED_BIT |
2142 PacketNumberLengthToOnWireValue(header.packet_number_length));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002143 }
2144 return writer->WriteUInt8(type);
2145}
2146
2147bool QuicFramer::AppendIetfPacketHeader(const QuicPacketHeader& header,
2148 QuicDataWriter* writer,
2149 size_t* length_field_offset) {
2150 QUIC_DVLOG(1) << ENDPOINT << "Appending IETF header: " << header;
QUICHE team2252b702019-05-14 23:55:14 -04002151 QuicConnectionId server_connection_id =
2152 GetServerConnectionIdAsSender(header, perspective_);
2153 QUIC_BUG_IF(!QuicUtils::IsConnectionIdValidForVersion(server_connection_id,
2154 transport_version()))
QUICHE teama6ef0a62019-03-07 20:34:33 -05002155 << "AppendIetfPacketHeader: attempted to use connection ID "
QUICHE team2252b702019-05-14 23:55:14 -04002156 << server_connection_id << " which is invalid with version "
QUICHE teama6ef0a62019-03-07 20:34:33 -05002157 << QuicVersionToString(transport_version());
2158 if (!AppendIetfHeaderTypeByte(header, writer)) {
2159 return false;
2160 }
2161
2162 if (header.version_flag) {
2163 // Append version for long header.
2164 QuicVersionLabel version_label = CreateQuicVersionLabel(version_);
nharpereaab5ad2019-05-31 12:23:25 -07002165 if (!writer->WriteUInt32(version_label)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002166 return false;
2167 }
2168 }
2169
2170 // Append connection ID.
dschinazi1f485a12019-05-13 11:57:01 -07002171 if (!AppendIetfConnectionIds(
dschinazi48ac9192019-07-31 00:07:26 -07002172 header.version_flag, version_.HasLengthPrefixedConnectionIds(),
dschinazi1f485a12019-05-13 11:57:01 -07002173 header.destination_connection_id_included != CONNECTION_ID_ABSENT
2174 ? header.destination_connection_id
2175 : EmptyQuicConnectionId(),
2176 header.source_connection_id_included != CONNECTION_ID_ABSENT
2177 ? header.source_connection_id
2178 : EmptyQuicConnectionId(),
2179 writer)) {
2180 return false;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002181 }
dschinazi1f485a12019-05-13 11:57:01 -07002182
dschinazi7b9278c2019-05-20 07:36:21 -07002183 last_serialized_server_connection_id_ = server_connection_id;
dschinazi346b7ce2019-06-05 01:38:18 -07002184 if (version_.SupportsClientConnectionIds()) {
2185 last_serialized_client_connection_id_ =
2186 GetClientConnectionIdAsSender(header, perspective_);
2187 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002188
2189 if (QuicVersionHasLongHeaderLengths(transport_version()) &&
2190 header.version_flag) {
2191 if (header.long_packet_type == INITIAL) {
dschinazic075ffa2019-06-27 16:17:37 -07002192 DCHECK_NE(VARIABLE_LENGTH_INTEGER_LENGTH_0,
2193 header.retry_token_length_length)
2194 << ENDPOINT << ParsedQuicVersionToString(version_)
2195 << " bad retry token length length in header: " << header;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002196 // Write retry token length.
2197 if (!writer->WriteVarInt62(header.retry_token.length(),
2198 header.retry_token_length_length)) {
2199 return false;
2200 }
2201 // Write retry token.
2202 if (!header.retry_token.empty() &&
2203 !writer->WriteStringPiece(header.retry_token)) {
2204 return false;
2205 }
2206 }
2207 if (length_field_offset != nullptr) {
2208 *length_field_offset = writer->length();
2209 }
2210 // Add fake length to reserve two bytes to add length in later.
2211 writer->WriteVarInt62(256);
2212 } else if (length_field_offset != nullptr) {
2213 *length_field_offset = 0;
2214 }
2215
2216 // Append packet number.
2217 if (!AppendPacketNumber(header.packet_number_length, header.packet_number,
2218 writer)) {
2219 return false;
2220 }
nharper55fa6132019-05-07 19:37:21 -07002221 last_written_packet_number_length_ = header.packet_number_length;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002222
2223 if (!header.version_flag) {
2224 return true;
2225 }
2226
2227 if (header.nonce != nullptr) {
2228 DCHECK(header.version_flag);
2229 DCHECK_EQ(ZERO_RTT_PROTECTED, header.long_packet_type);
2230 DCHECK_EQ(Perspective::IS_SERVER, perspective_);
2231 if (!writer->WriteBytes(header.nonce, kDiversificationNonceSize)) {
2232 return false;
2233 }
2234 }
2235
2236 return true;
2237}
2238
2239const QuicTime::Delta QuicFramer::CalculateTimestampFromWire(
2240 uint32_t time_delta_us) {
2241 // The new time_delta might have wrapped to the next epoch, or it
2242 // might have reverse wrapped to the previous epoch, or it might
2243 // remain in the same epoch. Select the time closest to the previous
2244 // time.
2245 //
2246 // epoch_delta is the delta between epochs. A delta is 4 bytes of
2247 // microseconds.
2248 const uint64_t epoch_delta = UINT64_C(1) << 32;
2249 uint64_t epoch = last_timestamp_.ToMicroseconds() & ~(epoch_delta - 1);
2250 // Wrapping is safe here because a wrapped value will not be ClosestTo below.
2251 uint64_t prev_epoch = epoch - epoch_delta;
2252 uint64_t next_epoch = epoch + epoch_delta;
2253
2254 uint64_t time = ClosestTo(
2255 last_timestamp_.ToMicroseconds(), epoch + time_delta_us,
2256 ClosestTo(last_timestamp_.ToMicroseconds(), prev_epoch + time_delta_us,
2257 next_epoch + time_delta_us));
2258
2259 return QuicTime::Delta::FromMicroseconds(time);
2260}
2261
2262uint64_t QuicFramer::CalculatePacketNumberFromWire(
2263 QuicPacketNumberLength packet_number_length,
2264 QuicPacketNumber base_packet_number,
2265 uint64_t packet_number) const {
2266 // The new packet number might have wrapped to the next epoch, or
2267 // it might have reverse wrapped to the previous epoch, or it might
2268 // remain in the same epoch. Select the packet number closest to the
2269 // next expected packet number, the previous packet number plus 1.
2270
2271 // epoch_delta is the delta between epochs the packet number was serialized
2272 // with, so the correct value is likely the same epoch as the last sequence
2273 // number or an adjacent epoch.
2274 if (!base_packet_number.IsInitialized()) {
2275 return packet_number;
2276 }
2277 const uint64_t epoch_delta = UINT64_C(1) << (8 * packet_number_length);
2278 uint64_t next_packet_number = base_packet_number.ToUint64() + 1;
2279 uint64_t epoch = base_packet_number.ToUint64() & ~(epoch_delta - 1);
2280 uint64_t prev_epoch = epoch - epoch_delta;
2281 uint64_t next_epoch = epoch + epoch_delta;
2282
2283 return ClosestTo(next_packet_number, epoch + packet_number,
2284 ClosestTo(next_packet_number, prev_epoch + packet_number,
2285 next_epoch + packet_number));
2286}
2287
2288bool QuicFramer::ProcessPublicHeader(QuicDataReader* reader,
2289 bool packet_has_ietf_packet_header,
2290 QuicPacketHeader* header) {
2291 if (packet_has_ietf_packet_header) {
2292 return ProcessIetfPacketHeader(reader, header);
2293 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002294 uint8_t public_flags;
2295 if (!reader->ReadBytes(&public_flags, 1)) {
2296 set_detailed_error("Unable to read public flags.");
2297 return false;
2298 }
2299
2300 header->reset_flag = (public_flags & PACKET_PUBLIC_FLAGS_RST) != 0;
2301 header->version_flag = (public_flags & PACKET_PUBLIC_FLAGS_VERSION) != 0;
2302
2303 if (validate_flags_ && !header->version_flag &&
2304 public_flags > PACKET_PUBLIC_FLAGS_MAX) {
2305 set_detailed_error("Illegal public flags value.");
2306 return false;
2307 }
2308
2309 if (header->reset_flag && header->version_flag) {
2310 set_detailed_error("Got version flag in reset packet");
2311 return false;
2312 }
2313
QUICHE team2252b702019-05-14 23:55:14 -04002314 QuicConnectionId* header_connection_id = &header->destination_connection_id;
2315 QuicConnectionIdIncluded* header_connection_id_included =
2316 &header->destination_connection_id_included;
dschinazi5e1a7b22019-07-31 12:23:21 -07002317 if (perspective_ == Perspective::IS_CLIENT) {
QUICHE team2252b702019-05-14 23:55:14 -04002318 header_connection_id = &header->source_connection_id;
2319 header_connection_id_included = &header->source_connection_id_included;
2320 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002321 switch (public_flags & PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID) {
2322 case PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID:
QUICHE team2252b702019-05-14 23:55:14 -04002323 if (!reader->ReadConnectionId(header_connection_id,
QUICHE teama6ef0a62019-03-07 20:34:33 -05002324 kQuicDefaultConnectionIdLength)) {
2325 set_detailed_error("Unable to read ConnectionId.");
2326 return false;
2327 }
QUICHE team2252b702019-05-14 23:55:14 -04002328 *header_connection_id_included = CONNECTION_ID_PRESENT;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002329 break;
2330 case PACKET_PUBLIC_FLAGS_0BYTE_CONNECTION_ID:
QUICHE team2252b702019-05-14 23:55:14 -04002331 *header_connection_id_included = CONNECTION_ID_ABSENT;
dschinazi7b9278c2019-05-20 07:36:21 -07002332 *header_connection_id = last_serialized_server_connection_id_;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002333 break;
2334 }
2335
2336 header->packet_number_length = ReadSequenceNumberLength(
2337 public_flags >> kPublicHeaderSequenceNumberShift);
2338
2339 // Read the version only if the packet is from the client.
2340 // version flag from the server means version negotiation packet.
2341 if (header->version_flag && perspective_ == Perspective::IS_SERVER) {
2342 QuicVersionLabel version_label;
fayang40315542019-05-09 09:19:09 -07002343 if (!ProcessVersionLabel(reader, &version_label)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002344 set_detailed_error("Unable to read protocol version.");
2345 return false;
2346 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002347 // If the version from the new packet is the same as the version of this
2348 // framer, then the public flags should be set to something we understand.
2349 // If not, this raises an error.
QUICHE teama6ef0a62019-03-07 20:34:33 -05002350 ParsedQuicVersion version = ParseQuicVersionLabel(version_label);
2351 if (version == version_ && public_flags > PACKET_PUBLIC_FLAGS_MAX) {
2352 set_detailed_error("Illegal public flags value.");
2353 return false;
2354 }
2355 header->version = version;
2356 }
2357
2358 // A nonce should only be present in packets from the server to the client,
2359 // which are neither version negotiation nor public reset packets.
2360 if (public_flags & PACKET_PUBLIC_FLAGS_NONCE &&
2361 !(public_flags & PACKET_PUBLIC_FLAGS_VERSION) &&
2362 !(public_flags & PACKET_PUBLIC_FLAGS_RST) &&
2363 // The nonce flag from a client is ignored and is assumed to be an older
2364 // client indicating an eight-byte connection ID.
2365 perspective_ == Perspective::IS_CLIENT) {
2366 if (!reader->ReadBytes(reinterpret_cast<uint8_t*>(last_nonce_.data()),
2367 last_nonce_.size())) {
2368 set_detailed_error("Unable to read nonce.");
2369 return false;
2370 }
2371 header->nonce = &last_nonce_;
2372 } else {
2373 header->nonce = nullptr;
2374 }
2375
2376 return true;
2377}
2378
2379// static
2380QuicPacketNumberLength QuicFramer::GetMinPacketNumberLength(
dschinazi17d42422019-06-18 16:35:07 -07002381 QuicTransportVersion /*version*/,
QUICHE teama6ef0a62019-03-07 20:34:33 -05002382 QuicPacketNumber packet_number) {
2383 DCHECK(packet_number.IsInitialized());
2384 if (packet_number < QuicPacketNumber(1 << (PACKET_1BYTE_PACKET_NUMBER * 8))) {
2385 return PACKET_1BYTE_PACKET_NUMBER;
2386 } else if (packet_number <
2387 QuicPacketNumber(1 << (PACKET_2BYTE_PACKET_NUMBER * 8))) {
2388 return PACKET_2BYTE_PACKET_NUMBER;
2389 } else if (packet_number <
2390 QuicPacketNumber(UINT64_C(1)
2391 << (PACKET_4BYTE_PACKET_NUMBER * 8))) {
2392 return PACKET_4BYTE_PACKET_NUMBER;
2393 } else {
2394 return PACKET_6BYTE_PACKET_NUMBER;
2395 }
2396}
2397
2398// static
2399uint8_t QuicFramer::GetPacketNumberFlags(
2400 QuicPacketNumberLength packet_number_length) {
2401 switch (packet_number_length) {
2402 case PACKET_1BYTE_PACKET_NUMBER:
2403 return PACKET_FLAGS_1BYTE_PACKET;
2404 case PACKET_2BYTE_PACKET_NUMBER:
2405 return PACKET_FLAGS_2BYTE_PACKET;
2406 case PACKET_4BYTE_PACKET_NUMBER:
2407 return PACKET_FLAGS_4BYTE_PACKET;
2408 case PACKET_6BYTE_PACKET_NUMBER:
2409 case PACKET_8BYTE_PACKET_NUMBER:
2410 return PACKET_FLAGS_8BYTE_PACKET;
2411 default:
2412 QUIC_BUG << "Unreachable case statement.";
2413 return PACKET_FLAGS_8BYTE_PACKET;
2414 }
2415}
2416
2417// static
2418QuicFramer::AckFrameInfo QuicFramer::GetAckFrameInfo(
2419 const QuicAckFrame& frame) {
2420 AckFrameInfo new_ack_info;
2421 if (frame.packets.Empty()) {
2422 return new_ack_info;
2423 }
2424 // The first block is the last interval. It isn't encoded with the gap-length
2425 // encoding, so skip it.
2426 new_ack_info.first_block_length = frame.packets.LastIntervalLength();
2427 auto itr = frame.packets.rbegin();
2428 QuicPacketNumber previous_start = itr->min();
2429 new_ack_info.max_block_length = PacketNumberIntervalLength(*itr);
2430 ++itr;
2431
2432 // Don't do any more work after getting information for 256 ACK blocks; any
2433 // more can't be encoded anyway.
2434 for (; itr != frame.packets.rend() &&
2435 new_ack_info.num_ack_blocks < std::numeric_limits<uint8_t>::max();
2436 previous_start = itr->min(), ++itr) {
2437 const auto& interval = *itr;
2438 const QuicPacketCount total_gap = previous_start - interval.max();
2439 new_ack_info.num_ack_blocks +=
2440 (total_gap + std::numeric_limits<uint8_t>::max() - 1) /
2441 std::numeric_limits<uint8_t>::max();
2442 new_ack_info.max_block_length = std::max(
2443 new_ack_info.max_block_length, PacketNumberIntervalLength(interval));
2444 }
2445 return new_ack_info;
2446}
2447
2448bool QuicFramer::ProcessUnauthenticatedHeader(QuicDataReader* encrypted_reader,
2449 QuicPacketHeader* header) {
QUICHE team10b22a12019-03-21 15:31:42 -07002450 QuicPacketNumber base_packet_number;
2451 if (supports_multiple_packet_number_spaces_) {
nharper55fa6132019-05-07 19:37:21 -07002452 PacketNumberSpace pn_space = GetPacketNumberSpace(*header);
2453 if (pn_space == NUM_PACKET_NUMBER_SPACES) {
2454 set_detailed_error("Unable to determine packet number space.");
2455 return RaiseError(QUIC_INVALID_PACKET_HEADER);
2456 }
2457 base_packet_number = largest_decrypted_packet_numbers_[pn_space];
QUICHE team10b22a12019-03-21 15:31:42 -07002458 } else {
2459 base_packet_number = largest_packet_number_;
2460 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002461 uint64_t full_packet_number;
2462 if (!ProcessAndCalculatePacketNumber(
2463 encrypted_reader, header->packet_number_length, base_packet_number,
2464 &full_packet_number)) {
2465 set_detailed_error("Unable to read packet number.");
2466 return RaiseError(QUIC_INVALID_PACKET_HEADER);
2467 }
2468
2469 if (!IsValidFullPacketNumber(full_packet_number, transport_version())) {
2470 set_detailed_error("packet numbers cannot be 0.");
2471 return RaiseError(QUIC_INVALID_PACKET_HEADER);
2472 }
2473 header->packet_number = QuicPacketNumber(full_packet_number);
2474
2475 if (!visitor_->OnUnauthenticatedHeader(*header)) {
2476 set_detailed_error(
2477 "Visitor asked to stop processing of unauthenticated header.");
2478 return false;
2479 }
nharper3f283562019-05-02 16:37:12 -07002480 // The function we are in is called because the framer believes that it is
2481 // processing a packet that uses the non-IETF (i.e. Google QUIC) packet header
2482 // type. Usually, the framer makes that decision based on the framer's
2483 // version, but when the framer is used with Perspective::IS_SERVER, then
2484 // before version negotiation is complete (specifically, before
2485 // InferPacketHeaderTypeFromVersion is called), this decision is made based on
2486 // the type byte of the packet.
2487 //
2488 // If the framer's version KnowsWhichDecrypterToUse, then that version expects
2489 // to use the IETF packet header type. If that's the case and we're in this
2490 // function, then the packet received is invalid: the framer was expecting an
2491 // IETF packet header and didn't get one.
2492 if (version().KnowsWhichDecrypterToUse()) {
nharpera745e392019-04-19 12:05:15 -07002493 set_detailed_error("Invalid public header type for expected version.");
2494 return RaiseError(QUIC_INVALID_PACKET_HEADER);
2495 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002496 return true;
2497}
2498
2499bool QuicFramer::ProcessIetfHeaderTypeByte(QuicDataReader* reader,
2500 QuicPacketHeader* header) {
2501 uint8_t type;
2502 if (!reader->ReadBytes(&type, 1)) {
dschinazi48ac9192019-07-31 00:07:26 -07002503 set_detailed_error("Unable to read first byte.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05002504 return false;
2505 }
dschinazi244f6dc2019-05-06 15:45:16 -07002506 header->type_byte = type;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002507 // Determine whether this is a long or short header.
fayangccbab732019-05-13 10:11:25 -07002508 header->form = GetIetfPacketHeaderFormat(type);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002509 if (header->form == IETF_QUIC_LONG_HEADER_PACKET) {
2510 // Version is always present in long headers.
2511 header->version_flag = true;
dschinazi346b7ce2019-06-05 01:38:18 -07002512 // In versions that do not support client connection IDs, we mark the
2513 // corresponding connection ID as absent.
QUICHE teama6ef0a62019-03-07 20:34:33 -05002514 header->destination_connection_id_included =
dschinazi346b7ce2019-06-05 01:38:18 -07002515 (perspective_ == Perspective::IS_SERVER ||
2516 version_.SupportsClientConnectionIds())
2517 ? CONNECTION_ID_PRESENT
2518 : CONNECTION_ID_ABSENT;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002519 header->source_connection_id_included =
dschinazi346b7ce2019-06-05 01:38:18 -07002520 (perspective_ == Perspective::IS_CLIENT ||
2521 version_.SupportsClientConnectionIds())
2522 ? CONNECTION_ID_PRESENT
2523 : CONNECTION_ID_ABSENT;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002524 // Read version tag.
2525 QuicVersionLabel version_label;
fayang40315542019-05-09 09:19:09 -07002526 if (!ProcessVersionLabel(reader, &version_label)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002527 set_detailed_error("Unable to read protocol version.");
2528 return false;
2529 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002530 if (!version_label) {
2531 // Version label is 0 indicating this is a version negotiation packet.
2532 header->long_packet_type = VERSION_NEGOTIATION;
2533 } else {
2534 header->version = ParseQuicVersionLabel(version_label);
2535 if (header->version.transport_version != QUIC_VERSION_UNSUPPORTED) {
fayang36825da2019-08-21 14:01:27 -07002536 if (!(type & FLAGS_FIXED_BIT)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002537 set_detailed_error("Fixed bit is 0 in long header.");
2538 return false;
2539 }
fayang36825da2019-08-21 14:01:27 -07002540 if (!GetLongHeaderType(type, &header->long_packet_type)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002541 set_detailed_error("Illegal long header type value.");
2542 return false;
2543 }
dschinazi244f6dc2019-05-06 15:45:16 -07002544 if (header->long_packet_type == RETRY) {
2545 if (!version().SupportsRetry()) {
2546 set_detailed_error("RETRY not supported in this version.");
2547 return false;
2548 }
2549 if (perspective_ == Perspective::IS_SERVER) {
2550 set_detailed_error("Client-initiated RETRY is invalid.");
2551 return false;
2552 }
nharper55fa6132019-05-07 19:37:21 -07002553 } else if (!header->version.HasHeaderProtection()) {
fayang36825da2019-08-21 14:01:27 -07002554 header->packet_number_length = GetLongHeaderPacketNumberLength(type);
nharper2ceb97c2019-04-19 11:38:59 -07002555 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002556 }
2557 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002558
2559 QUIC_DVLOG(1) << ENDPOINT << "Received IETF long header: "
2560 << QuicUtils::QuicLongHeaderTypetoString(
2561 header->long_packet_type);
2562 return true;
2563 }
2564
2565 QUIC_DVLOG(1) << ENDPOINT << "Received IETF short header";
2566 // Version is not present in short headers.
2567 header->version_flag = false;
dschinazi346b7ce2019-06-05 01:38:18 -07002568 // In versions that do not support client connection IDs, the client will not
2569 // receive destination connection IDs.
QUICHE teama6ef0a62019-03-07 20:34:33 -05002570 header->destination_connection_id_included =
dschinazi346b7ce2019-06-05 01:38:18 -07002571 (perspective_ == Perspective::IS_SERVER ||
2572 version_.SupportsClientConnectionIds())
2573 ? CONNECTION_ID_PRESENT
2574 : CONNECTION_ID_ABSENT;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002575 header->source_connection_id_included = CONNECTION_ID_ABSENT;
fayang36825da2019-08-21 14:01:27 -07002576 if (!(type & FLAGS_FIXED_BIT)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002577 set_detailed_error("Fixed bit is 0 in short header.");
2578 return false;
2579 }
fayang36825da2019-08-21 14:01:27 -07002580 if (!header->version.HasHeaderProtection()) {
2581 header->packet_number_length = GetShortHeaderPacketNumberLength(type);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002582 }
2583 QUIC_DVLOG(1) << "packet_number_length = " << header->packet_number_length;
2584 return true;
2585}
2586
fayang40315542019-05-09 09:19:09 -07002587// static
2588bool QuicFramer::ProcessVersionLabel(QuicDataReader* reader,
2589 QuicVersionLabel* version_label) {
nharpereaab5ad2019-05-31 12:23:25 -07002590 if (!reader->ReadUInt32(version_label)) {
fayang40315542019-05-09 09:19:09 -07002591 return false;
2592 }
fayang40315542019-05-09 09:19:09 -07002593 return true;
2594}
2595
2596// static
fayangccbab732019-05-13 10:11:25 -07002597bool QuicFramer::ProcessAndValidateIetfConnectionIdLength(
2598 QuicDataReader* reader,
fayang40315542019-05-09 09:19:09 -07002599 ParsedQuicVersion version,
dschinazi334f0232019-05-29 16:08:53 -07002600 Perspective perspective,
dschinazi8ff74822019-05-28 16:37:20 -07002601 bool should_update_expected_server_connection_id_length,
2602 uint8_t* expected_server_connection_id_length,
fayang40315542019-05-09 09:19:09 -07002603 uint8_t* destination_connection_id_length,
fayangccbab732019-05-13 10:11:25 -07002604 uint8_t* source_connection_id_length,
2605 std::string* detailed_error) {
2606 uint8_t connection_id_lengths_byte;
2607 if (!reader->ReadBytes(&connection_id_lengths_byte, 1)) {
2608 *detailed_error = "Unable to read ConnectionId length.";
2609 return false;
2610 }
fayang40315542019-05-09 09:19:09 -07002611 uint8_t dcil =
2612 (connection_id_lengths_byte & kDestinationConnectionIdLengthMask) >> 4;
2613 if (dcil != 0) {
2614 dcil += kConnectionIdLengthAdjustment;
2615 }
fayang40315542019-05-09 09:19:09 -07002616 uint8_t scil = connection_id_lengths_byte & kSourceConnectionIdLengthMask;
2617 if (scil != 0) {
2618 scil += kConnectionIdLengthAdjustment;
2619 }
dschinazi334f0232019-05-29 16:08:53 -07002620 if (should_update_expected_server_connection_id_length) {
2621 uint8_t server_connection_id_length =
2622 perspective == Perspective::IS_SERVER ? dcil : scil;
2623 if (*expected_server_connection_id_length != server_connection_id_length) {
2624 QUIC_DVLOG(1) << "Updating expected_server_connection_id_length: "
2625 << static_cast<int>(*expected_server_connection_id_length)
2626 << " -> " << static_cast<int>(server_connection_id_length);
2627 *expected_server_connection_id_length = server_connection_id_length;
2628 }
2629 }
dschinazi8ff74822019-05-28 16:37:20 -07002630 if (!should_update_expected_server_connection_id_length &&
fayangde8a2222019-05-16 10:52:39 -07002631 (dcil != *destination_connection_id_length ||
fayang40315542019-05-09 09:19:09 -07002632 scil != *source_connection_id_length) &&
fayang40315542019-05-09 09:19:09 -07002633 !QuicUtils::VariableLengthConnectionIdAllowedForVersion(
2634 version.transport_version)) {
2635 // TODO(dschinazi): use the framer's version once the
2636 // OnProtocolVersionMismatch call is moved to before this is run.
2637 QUIC_DVLOG(1) << "dcil: " << static_cast<uint32_t>(dcil)
2638 << ", scil: " << static_cast<uint32_t>(scil);
fayangccbab732019-05-13 10:11:25 -07002639 *detailed_error = "Invalid ConnectionId length.";
fayang40315542019-05-09 09:19:09 -07002640 return false;
2641 }
2642 *destination_connection_id_length = dcil;
2643 *source_connection_id_length = scil;
2644 return true;
2645}
2646
dschinazib953d022019-08-01 18:05:58 -07002647bool QuicFramer::ValidateReceivedConnectionIds(const QuicPacketHeader& header) {
2648 if (!QuicUtils::IsConnectionIdValidForVersion(
2649 GetServerConnectionIdAsRecipient(header, perspective_),
2650 transport_version())) {
2651 set_detailed_error("Received server connection ID with invalid length.");
2652 return false;
2653 }
2654
2655 if (version_.SupportsClientConnectionIds() &&
2656 !QuicUtils::IsConnectionIdValidForVersion(
2657 GetClientConnectionIdAsRecipient(header, perspective_),
2658 transport_version())) {
2659 set_detailed_error("Received client connection ID with invalid length.");
2660 return false;
2661 }
2662 return true;
2663}
2664
QUICHE teama6ef0a62019-03-07 20:34:33 -05002665bool QuicFramer::ProcessIetfPacketHeader(QuicDataReader* reader,
2666 QuicPacketHeader* header) {
dschinazi48ac9192019-07-31 00:07:26 -07002667 if (version_.HasLengthPrefixedConnectionIds()) {
2668 uint8_t expected_destination_connection_id_length =
2669 perspective_ == Perspective::IS_CLIENT
2670 ? expected_client_connection_id_length_
2671 : expected_server_connection_id_length_;
2672 QuicVersionLabel version_label;
2673 bool has_length_prefix;
2674 std::string detailed_error;
2675 QuicErrorCode parse_result = QuicFramer::ParsePublicHeader(
2676 reader, expected_destination_connection_id_length,
2677 VersionHasIetfInvariantHeader(version_.transport_version),
2678 &header->type_byte, &header->form, &header->version_flag,
2679 &has_length_prefix, &version_label, &header->version,
2680 &header->destination_connection_id, &header->source_connection_id,
2681 &header->long_packet_type, &header->retry_token_length_length,
2682 &header->retry_token, &detailed_error);
2683 if (parse_result != QUIC_NO_ERROR) {
2684 set_detailed_error(detailed_error);
2685 return false;
2686 }
2687 header->destination_connection_id_included = CONNECTION_ID_PRESENT;
2688 header->source_connection_id_included =
2689 header->version_flag ? CONNECTION_ID_PRESENT : CONNECTION_ID_ABSENT;
2690 if (header->source_connection_id_included == CONNECTION_ID_ABSENT) {
2691 DCHECK(header->source_connection_id.IsEmpty());
2692 if (perspective_ == Perspective::IS_CLIENT) {
2693 header->source_connection_id = last_serialized_server_connection_id_;
2694 } else {
2695 header->source_connection_id = last_serialized_client_connection_id_;
2696 }
2697 }
dschinazib953d022019-08-01 18:05:58 -07002698
2699 if (!ValidateReceivedConnectionIds(*header)) {
2700 return false;
2701 }
2702
dschinazi48ac9192019-07-31 00:07:26 -07002703 if (header->version_flag &&
fayang36825da2019-08-21 14:01:27 -07002704 header->long_packet_type != VERSION_NEGOTIATION &&
dschinazi48ac9192019-07-31 00:07:26 -07002705 !(header->type_byte & FLAGS_FIXED_BIT)) {
2706 set_detailed_error("Fixed bit is 0 in long header.");
2707 return false;
2708 }
fayang36825da2019-08-21 14:01:27 -07002709 if (!header->version_flag && !(header->type_byte & FLAGS_FIXED_BIT)) {
dschinazi48ac9192019-07-31 00:07:26 -07002710 set_detailed_error("Fixed bit is 0 in short header.");
2711 return false;
2712 }
2713 if (!header->version_flag) {
fayang36825da2019-08-21 14:01:27 -07002714 if (!version_.HasHeaderProtection()) {
2715 header->packet_number_length =
2716 GetShortHeaderPacketNumberLength(header->type_byte);
dschinazi48ac9192019-07-31 00:07:26 -07002717 }
2718 return true;
2719 }
2720 if (header->long_packet_type == RETRY) {
2721 if (!version().SupportsRetry()) {
2722 set_detailed_error("RETRY not supported in this version.");
2723 return false;
2724 }
2725 if (perspective_ == Perspective::IS_SERVER) {
2726 set_detailed_error("Client-initiated RETRY is invalid.");
2727 return false;
2728 }
2729 return true;
2730 }
2731 if (!header->version.HasHeaderProtection()) {
fayang36825da2019-08-21 14:01:27 -07002732 header->packet_number_length =
2733 GetLongHeaderPacketNumberLength(header->type_byte);
dschinazi48ac9192019-07-31 00:07:26 -07002734 }
2735
2736 return true;
2737 }
2738
QUICHE teama6ef0a62019-03-07 20:34:33 -05002739 if (!ProcessIetfHeaderTypeByte(reader, header)) {
2740 return false;
2741 }
2742
2743 uint8_t destination_connection_id_length =
2744 header->destination_connection_id_included == CONNECTION_ID_PRESENT
dschinazi346b7ce2019-06-05 01:38:18 -07002745 ? (perspective_ == Perspective::IS_SERVER
2746 ? expected_server_connection_id_length_
2747 : expected_client_connection_id_length_)
QUICHE teama6ef0a62019-03-07 20:34:33 -05002748 : 0;
2749 uint8_t source_connection_id_length =
2750 header->source_connection_id_included == CONNECTION_ID_PRESENT
dschinazi346b7ce2019-06-05 01:38:18 -07002751 ? (perspective_ == Perspective::IS_CLIENT
2752 ? expected_server_connection_id_length_
2753 : expected_client_connection_id_length_)
QUICHE teama6ef0a62019-03-07 20:34:33 -05002754 : 0;
2755 if (header->form == IETF_QUIC_LONG_HEADER_PACKET) {
fayangccbab732019-05-13 10:11:25 -07002756 if (!ProcessAndValidateIetfConnectionIdLength(
dschinazi334f0232019-05-29 16:08:53 -07002757 reader, header->version, perspective_,
fayang91475c42019-06-19 08:04:26 -07002758 /*should_update_expected_server_connection_id_length=*/false,
dschinazi8ff74822019-05-28 16:37:20 -07002759 &expected_server_connection_id_length_,
2760 &destination_connection_id_length, &source_connection_id_length,
2761 &detailed_error_)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002762 return false;
2763 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002764 }
2765
2766 // Read connection ID.
2767 if (!reader->ReadConnectionId(&header->destination_connection_id,
2768 destination_connection_id_length)) {
dschinazi48ac9192019-07-31 00:07:26 -07002769 set_detailed_error("Unable to read destination connection ID.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05002770 return false;
2771 }
2772
2773 if (!reader->ReadConnectionId(&header->source_connection_id,
2774 source_connection_id_length)) {
dschinazi48ac9192019-07-31 00:07:26 -07002775 set_detailed_error("Unable to read source connection ID.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05002776 return false;
2777 }
2778
dschinazi5e1a7b22019-07-31 12:23:21 -07002779 if (header->source_connection_id_included == CONNECTION_ID_ABSENT) {
2780 if (!header->source_connection_id.IsEmpty()) {
2781 DCHECK(!version_.SupportsClientConnectionIds());
2782 set_detailed_error("Client connection ID not supported in this version.");
2783 return false;
QUICHE team2252b702019-05-14 23:55:14 -04002784 }
dschinazi5e1a7b22019-07-31 12:23:21 -07002785 if (perspective_ == Perspective::IS_CLIENT) {
2786 header->source_connection_id = last_serialized_server_connection_id_;
2787 } else {
2788 header->source_connection_id = last_serialized_client_connection_id_;
QUICHE team2252b702019-05-14 23:55:14 -04002789 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002790 }
2791
dschinazib953d022019-08-01 18:05:58 -07002792 return ValidateReceivedConnectionIds(*header);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002793}
2794
2795bool QuicFramer::ProcessAndCalculatePacketNumber(
2796 QuicDataReader* reader,
2797 QuicPacketNumberLength packet_number_length,
2798 QuicPacketNumber base_packet_number,
2799 uint64_t* packet_number) {
2800 uint64_t wire_packet_number;
2801 if (!reader->ReadBytesToUInt64(packet_number_length, &wire_packet_number)) {
2802 return false;
2803 }
2804
2805 // TODO(ianswett): Explore the usefulness of trying multiple packet numbers
2806 // in case the first guess is incorrect.
2807 *packet_number = CalculatePacketNumberFromWire(
2808 packet_number_length, base_packet_number, wire_packet_number);
2809 return true;
2810}
2811
2812bool QuicFramer::ProcessFrameData(QuicDataReader* reader,
2813 const QuicPacketHeader& header) {
fkastenholz305e1732019-06-18 05:01:22 -07002814 DCHECK(!VersionHasIetfQuicFrames(version_.transport_version))
2815 << "IETF QUIC Framing negotiated but attempting to process frames as "
2816 "non-IETF QUIC.";
QUICHE teama6ef0a62019-03-07 20:34:33 -05002817 if (reader->IsDoneReading()) {
2818 set_detailed_error("Packet has no frames.");
2819 return RaiseError(QUIC_MISSING_PAYLOAD);
2820 }
dschinazi118934b2019-06-13 18:09:08 -07002821 QUIC_DVLOG(2) << ENDPOINT << "Processing packet with header " << header;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002822 while (!reader->IsDoneReading()) {
2823 uint8_t frame_type;
2824 if (!reader->ReadBytes(&frame_type, 1)) {
2825 set_detailed_error("Unable to read frame type.");
2826 return RaiseError(QUIC_INVALID_FRAME_DATA);
2827 }
fayang36825da2019-08-21 14:01:27 -07002828 const uint8_t special_mask = transport_version() <= QUIC_VERSION_43
QUICHE teama6ef0a62019-03-07 20:34:33 -05002829 ? kQuicFrameTypeBrokenMask
2830 : kQuicFrameTypeSpecialMask;
2831 if (frame_type & special_mask) {
2832 // Stream Frame
2833 if (frame_type & kQuicFrameTypeStreamMask) {
2834 QuicStreamFrame frame;
2835 if (!ProcessStreamFrame(reader, frame_type, &frame)) {
2836 return RaiseError(QUIC_INVALID_STREAM_DATA);
2837 }
dschinazi118934b2019-06-13 18:09:08 -07002838 QUIC_DVLOG(2) << ENDPOINT << "Processing stream frame " << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002839 if (!visitor_->OnStreamFrame(frame)) {
2840 QUIC_DVLOG(1) << ENDPOINT
2841 << "Visitor asked to stop further processing.";
2842 // Returning true since there was no parsing error.
2843 return true;
2844 }
2845 continue;
2846 }
2847
2848 // Ack Frame
2849 if (frame_type & kQuicFrameTypeAckMask) {
2850 if (!ProcessAckFrame(reader, frame_type)) {
2851 return RaiseError(QUIC_INVALID_ACK_DATA);
2852 }
dschinazi118934b2019-06-13 18:09:08 -07002853 QUIC_DVLOG(2) << ENDPOINT << "Processing ACK frame";
QUICHE teama6ef0a62019-03-07 20:34:33 -05002854 continue;
2855 }
2856
2857 // This was a special frame type that did not match any
2858 // of the known ones. Error.
2859 set_detailed_error("Illegal frame type.");
2860 QUIC_DLOG(WARNING) << ENDPOINT << "Illegal frame type: "
2861 << static_cast<int>(frame_type);
2862 return RaiseError(QUIC_INVALID_FRAME_DATA);
2863 }
2864
2865 switch (frame_type) {
2866 case PADDING_FRAME: {
2867 QuicPaddingFrame frame;
2868 ProcessPaddingFrame(reader, &frame);
dschinazi118934b2019-06-13 18:09:08 -07002869 QUIC_DVLOG(2) << ENDPOINT << "Processing padding frame " << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002870 if (!visitor_->OnPaddingFrame(frame)) {
2871 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
2872 // Returning true since there was no parsing error.
2873 return true;
2874 }
2875 continue;
2876 }
2877
2878 case RST_STREAM_FRAME: {
2879 QuicRstStreamFrame frame;
2880 if (!ProcessRstStreamFrame(reader, &frame)) {
2881 return RaiseError(QUIC_INVALID_RST_STREAM_DATA);
2882 }
dschinazi118934b2019-06-13 18:09:08 -07002883 QUIC_DVLOG(2) << ENDPOINT << "Processing reset stream frame " << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002884 if (!visitor_->OnRstStreamFrame(frame)) {
2885 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
2886 // Returning true since there was no parsing error.
2887 return true;
2888 }
2889 continue;
2890 }
2891
2892 case CONNECTION_CLOSE_FRAME: {
2893 QuicConnectionCloseFrame frame;
2894 if (!ProcessConnectionCloseFrame(reader, &frame)) {
2895 return RaiseError(QUIC_INVALID_CONNECTION_CLOSE_DATA);
2896 }
2897
dschinazi118934b2019-06-13 18:09:08 -07002898 QUIC_DVLOG(2) << ENDPOINT << "Processing connection close frame "
2899 << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002900 if (!visitor_->OnConnectionCloseFrame(frame)) {
2901 QUIC_DVLOG(1) << ENDPOINT
2902 << "Visitor asked to stop further processing.";
2903 // Returning true since there was no parsing error.
2904 return true;
2905 }
2906 continue;
2907 }
2908
2909 case GOAWAY_FRAME: {
2910 QuicGoAwayFrame goaway_frame;
2911 if (!ProcessGoAwayFrame(reader, &goaway_frame)) {
2912 return RaiseError(QUIC_INVALID_GOAWAY_DATA);
2913 }
dschinazi118934b2019-06-13 18:09:08 -07002914 QUIC_DVLOG(2) << ENDPOINT << "Processing go away frame "
2915 << goaway_frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002916 if (!visitor_->OnGoAwayFrame(goaway_frame)) {
2917 QUIC_DVLOG(1) << ENDPOINT
2918 << "Visitor asked to stop further processing.";
2919 // Returning true since there was no parsing error.
2920 return true;
2921 }
2922 continue;
2923 }
2924
2925 case WINDOW_UPDATE_FRAME: {
2926 QuicWindowUpdateFrame window_update_frame;
2927 if (!ProcessWindowUpdateFrame(reader, &window_update_frame)) {
2928 return RaiseError(QUIC_INVALID_WINDOW_UPDATE_DATA);
2929 }
dschinazi118934b2019-06-13 18:09:08 -07002930 QUIC_DVLOG(2) << ENDPOINT << "Processing window update frame "
2931 << window_update_frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002932 if (!visitor_->OnWindowUpdateFrame(window_update_frame)) {
2933 QUIC_DVLOG(1) << ENDPOINT
2934 << "Visitor asked to stop further processing.";
2935 // Returning true since there was no parsing error.
2936 return true;
2937 }
2938 continue;
2939 }
2940
2941 case BLOCKED_FRAME: {
2942 QuicBlockedFrame blocked_frame;
2943 if (!ProcessBlockedFrame(reader, &blocked_frame)) {
2944 return RaiseError(QUIC_INVALID_BLOCKED_DATA);
2945 }
dschinazi118934b2019-06-13 18:09:08 -07002946 QUIC_DVLOG(2) << ENDPOINT << "Processing blocked frame "
2947 << blocked_frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002948 if (!visitor_->OnBlockedFrame(blocked_frame)) {
2949 QUIC_DVLOG(1) << ENDPOINT
2950 << "Visitor asked to stop further processing.";
2951 // Returning true since there was no parsing error.
2952 return true;
2953 }
2954 continue;
2955 }
2956
2957 case STOP_WAITING_FRAME: {
ianswett97b690b2019-05-02 15:12:43 -07002958 if (GetQuicReloadableFlag(quic_do_not_accept_stop_waiting) &&
fayang36825da2019-08-21 14:01:27 -07002959 version_.transport_version > QUIC_VERSION_43) {
ianswett97b690b2019-05-02 15:12:43 -07002960 QUIC_RELOADABLE_FLAG_COUNT(quic_do_not_accept_stop_waiting);
2961 set_detailed_error("STOP WAITING not supported in version 44+.");
2962 return RaiseError(QUIC_INVALID_STOP_WAITING_DATA);
2963 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002964 QuicStopWaitingFrame stop_waiting_frame;
2965 if (!ProcessStopWaitingFrame(reader, header, &stop_waiting_frame)) {
2966 return RaiseError(QUIC_INVALID_STOP_WAITING_DATA);
2967 }
dschinazi118934b2019-06-13 18:09:08 -07002968 QUIC_DVLOG(2) << ENDPOINT << "Processing stop waiting frame "
2969 << stop_waiting_frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002970 if (!visitor_->OnStopWaitingFrame(stop_waiting_frame)) {
2971 QUIC_DVLOG(1) << ENDPOINT
2972 << "Visitor asked to stop further processing.";
2973 // Returning true since there was no parsing error.
2974 return true;
2975 }
2976 continue;
2977 }
2978 case PING_FRAME: {
2979 // Ping has no payload.
2980 QuicPingFrame ping_frame;
2981 if (!visitor_->OnPingFrame(ping_frame)) {
2982 QUIC_DVLOG(1) << ENDPOINT
2983 << "Visitor asked to stop further processing.";
2984 // Returning true since there was no parsing error.
2985 return true;
2986 }
dschinazi118934b2019-06-13 18:09:08 -07002987 QUIC_DVLOG(2) << ENDPOINT << "Processing ping frame " << ping_frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002988 continue;
2989 }
2990 case IETF_EXTENSION_MESSAGE_NO_LENGTH:
2991 QUIC_FALLTHROUGH_INTENDED;
2992 case IETF_EXTENSION_MESSAGE: {
2993 QuicMessageFrame message_frame;
2994 if (!ProcessMessageFrame(reader,
2995 frame_type == IETF_EXTENSION_MESSAGE_NO_LENGTH,
2996 &message_frame)) {
2997 return RaiseError(QUIC_INVALID_MESSAGE_DATA);
2998 }
dschinazi118934b2019-06-13 18:09:08 -07002999 QUIC_DVLOG(2) << ENDPOINT << "Processing message frame "
3000 << message_frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003001 if (!visitor_->OnMessageFrame(message_frame)) {
3002 QUIC_DVLOG(1) << ENDPOINT
3003 << "Visitor asked to stop further processing.";
3004 // Returning true since there was no parsing error.
3005 return true;
3006 }
3007 break;
3008 }
3009 case CRYPTO_FRAME: {
QUICHE teamea740082019-03-11 17:58:43 -07003010 if (!QuicVersionUsesCryptoFrames(version_.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05003011 set_detailed_error("Illegal frame type.");
3012 return RaiseError(QUIC_INVALID_FRAME_DATA);
3013 }
3014 QuicCryptoFrame frame;
3015 if (!ProcessCryptoFrame(reader, &frame)) {
3016 return RaiseError(QUIC_INVALID_FRAME_DATA);
3017 }
dschinazi118934b2019-06-13 18:09:08 -07003018 QUIC_DVLOG(2) << ENDPOINT << "Processing crypto frame " << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003019 if (!visitor_->OnCryptoFrame(frame)) {
3020 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3021 // Returning true since there was no parsing error.
3022 return true;
3023 }
3024 break;
3025 }
3026
3027 default:
3028 set_detailed_error("Illegal frame type.");
3029 QUIC_DLOG(WARNING) << ENDPOINT << "Illegal frame type: "
3030 << static_cast<int>(frame_type);
3031 return RaiseError(QUIC_INVALID_FRAME_DATA);
3032 }
3033 }
3034
3035 return true;
3036}
3037
3038bool QuicFramer::ProcessIetfFrameData(QuicDataReader* reader,
3039 const QuicPacketHeader& header) {
fkastenholz305e1732019-06-18 05:01:22 -07003040 DCHECK(VersionHasIetfQuicFrames(version_.transport_version))
3041 << "Attempt to process frames as IETF frames but version ("
3042 << version_.transport_version << ") does not support IETF Framing.";
3043
QUICHE teama6ef0a62019-03-07 20:34:33 -05003044 if (reader->IsDoneReading()) {
3045 set_detailed_error("Packet has no frames.");
3046 return RaiseError(QUIC_MISSING_PAYLOAD);
3047 }
dschinazi118934b2019-06-13 18:09:08 -07003048
3049 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF packet with header " << header;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003050 while (!reader->IsDoneReading()) {
3051 uint64_t frame_type;
3052 // Will be the number of bytes into which frame_type was encoded.
3053 size_t encoded_bytes = reader->BytesRemaining();
3054 if (!reader->ReadVarInt62(&frame_type)) {
3055 set_detailed_error("Unable to read frame type.");
3056 return RaiseError(QUIC_INVALID_FRAME_DATA);
3057 }
fkastenholza3660102019-08-28 05:19:24 -07003058 current_received_frame_type_ = frame_type;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003059
3060 // Is now the number of bytes into which the frame type was encoded.
3061 encoded_bytes -= reader->BytesRemaining();
3062
3063 // Check that the frame type is minimally encoded.
3064 if (encoded_bytes !=
3065 static_cast<size_t>(QuicDataWriter::GetVarInt62Len(frame_type))) {
3066 // The frame type was not minimally encoded.
3067 set_detailed_error("Frame type not minimally encoded.");
3068 return RaiseError(IETF_QUIC_PROTOCOL_VIOLATION);
3069 }
3070
3071 if (IS_IETF_STREAM_FRAME(frame_type)) {
3072 QuicStreamFrame frame;
3073 if (!ProcessIetfStreamFrame(reader, frame_type, &frame)) {
3074 return RaiseError(QUIC_INVALID_STREAM_DATA);
3075 }
dschinazi118934b2019-06-13 18:09:08 -07003076 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF stream frame " << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003077 if (!visitor_->OnStreamFrame(frame)) {
3078 QUIC_DVLOG(1) << ENDPOINT
3079 << "Visitor asked to stop further processing.";
3080 // Returning true since there was no parsing error.
3081 return true;
3082 }
3083 } else {
3084 switch (frame_type) {
3085 case IETF_PADDING: {
3086 QuicPaddingFrame frame;
3087 ProcessPaddingFrame(reader, &frame);
dschinazi118934b2019-06-13 18:09:08 -07003088 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF padding frame "
3089 << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003090 if (!visitor_->OnPaddingFrame(frame)) {
3091 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3092 // Returning true since there was no parsing error.
3093 return true;
3094 }
3095 break;
3096 }
3097 case IETF_RST_STREAM: {
3098 QuicRstStreamFrame frame;
3099 if (!ProcessIetfResetStreamFrame(reader, &frame)) {
3100 return RaiseError(QUIC_INVALID_RST_STREAM_DATA);
3101 }
dschinazi118934b2019-06-13 18:09:08 -07003102 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF reset stream frame "
3103 << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003104 if (!visitor_->OnRstStreamFrame(frame)) {
3105 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3106 // Returning true since there was no parsing error.
3107 return true;
3108 }
3109 break;
3110 }
fkastenholz04bd4f32019-04-16 12:24:38 -07003111 case IETF_APPLICATION_CLOSE:
QUICHE teama6ef0a62019-03-07 20:34:33 -05003112 case IETF_CONNECTION_CLOSE: {
3113 QuicConnectionCloseFrame frame;
fkastenholze9d71a82019-04-09 05:12:13 -07003114 if (!ProcessIetfConnectionCloseFrame(
fkastenholz04bd4f32019-04-16 12:24:38 -07003115 reader,
3116 (frame_type == IETF_CONNECTION_CLOSE)
3117 ? IETF_QUIC_TRANSPORT_CONNECTION_CLOSE
3118 : IETF_QUIC_APPLICATION_CONNECTION_CLOSE,
3119 &frame)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05003120 return RaiseError(QUIC_INVALID_CONNECTION_CLOSE_DATA);
3121 }
dschinazi118934b2019-06-13 18:09:08 -07003122 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF connection close frame "
3123 << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003124 if (!visitor_->OnConnectionCloseFrame(frame)) {
3125 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3126 // Returning true since there was no parsing error.
3127 return true;
3128 }
3129 break;
3130 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05003131 case IETF_MAX_DATA: {
3132 QuicWindowUpdateFrame frame;
3133 if (!ProcessMaxDataFrame(reader, &frame)) {
3134 return RaiseError(QUIC_INVALID_MAX_DATA_FRAME_DATA);
3135 }
3136 // TODO(fkastenholz): Or should we create a new visitor function,
3137 // OnMaxDataFrame()?
dschinazi118934b2019-06-13 18:09:08 -07003138 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF max data frame "
3139 << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003140 if (!visitor_->OnWindowUpdateFrame(frame)) {
3141 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3142 // Returning true since there was no parsing error.
3143 return true;
3144 }
3145 break;
3146 }
3147 case IETF_MAX_STREAM_DATA: {
3148 QuicWindowUpdateFrame frame;
3149 if (!ProcessMaxStreamDataFrame(reader, &frame)) {
3150 return RaiseError(QUIC_INVALID_MAX_STREAM_DATA_FRAME_DATA);
3151 }
3152 // TODO(fkastenholz): Or should we create a new visitor function,
3153 // OnMaxStreamDataFrame()?
dschinazi118934b2019-06-13 18:09:08 -07003154 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF max stream data frame "
3155 << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003156 if (!visitor_->OnWindowUpdateFrame(frame)) {
3157 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3158 // Returning true since there was no parsing error.
3159 return true;
3160 }
3161 break;
3162 }
3163 case IETF_MAX_STREAMS_BIDIRECTIONAL:
3164 case IETF_MAX_STREAMS_UNIDIRECTIONAL: {
fkastenholz3c4eabf2019-04-22 07:49:59 -07003165 QuicMaxStreamsFrame frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003166 if (!ProcessMaxStreamsFrame(reader, &frame, frame_type)) {
fkastenholz3c4eabf2019-04-22 07:49:59 -07003167 return RaiseError(QUIC_MAX_STREAMS_DATA);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003168 }
fkastenholz3c4eabf2019-04-22 07:49:59 -07003169 QUIC_CODE_COUNT_N(quic_max_streams_received, 1, 2);
dschinazi118934b2019-06-13 18:09:08 -07003170 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF max streams frame "
3171 << frame;
fkastenholz3c4eabf2019-04-22 07:49:59 -07003172 if (!visitor_->OnMaxStreamsFrame(frame)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05003173 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3174 // Returning true since there was no parsing error.
3175 return true;
3176 }
3177 break;
3178 }
3179 case IETF_PING: {
3180 // Ping has no payload.
3181 QuicPingFrame ping_frame;
dschinazi118934b2019-06-13 18:09:08 -07003182 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF ping frame "
3183 << ping_frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003184 if (!visitor_->OnPingFrame(ping_frame)) {
3185 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3186 // Returning true since there was no parsing error.
3187 return true;
3188 }
3189 break;
3190 }
3191 case IETF_BLOCKED: {
3192 QuicBlockedFrame frame;
3193 if (!ProcessIetfBlockedFrame(reader, &frame)) {
3194 return RaiseError(QUIC_INVALID_BLOCKED_DATA);
3195 }
dschinazi118934b2019-06-13 18:09:08 -07003196 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF blocked frame "
3197 << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003198 if (!visitor_->OnBlockedFrame(frame)) {
3199 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3200 // Returning true since there was no parsing error.
3201 return true;
3202 }
3203 break;
3204 }
3205 case IETF_STREAM_BLOCKED: {
3206 QuicBlockedFrame frame;
3207 if (!ProcessStreamBlockedFrame(reader, &frame)) {
3208 return RaiseError(QUIC_INVALID_STREAM_BLOCKED_DATA);
3209 }
dschinazi118934b2019-06-13 18:09:08 -07003210 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF stream blocked frame "
3211 << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003212 if (!visitor_->OnBlockedFrame(frame)) {
3213 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3214 // Returning true since there was no parsing error.
3215 return true;
3216 }
3217 break;
3218 }
3219 case IETF_STREAMS_BLOCKED_UNIDIRECTIONAL:
3220 case IETF_STREAMS_BLOCKED_BIDIRECTIONAL: {
fkastenholz3c4eabf2019-04-22 07:49:59 -07003221 QuicStreamsBlockedFrame frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003222 if (!ProcessStreamsBlockedFrame(reader, &frame, frame_type)) {
fkastenholz3c4eabf2019-04-22 07:49:59 -07003223 return RaiseError(QUIC_STREAMS_BLOCKED_DATA);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003224 }
fkastenholz3c4eabf2019-04-22 07:49:59 -07003225 QUIC_CODE_COUNT_N(quic_streams_blocked_received, 1, 2);
dschinazi118934b2019-06-13 18:09:08 -07003226 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF streams blocked frame "
3227 << frame;
fkastenholz3c4eabf2019-04-22 07:49:59 -07003228 if (!visitor_->OnStreamsBlockedFrame(frame)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05003229 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3230 // Returning true since there was no parsing error.
3231 return true;
3232 }
3233 break;
3234 }
3235 case IETF_NEW_CONNECTION_ID: {
3236 QuicNewConnectionIdFrame frame;
3237 if (!ProcessNewConnectionIdFrame(reader, &frame)) {
3238 return RaiseError(QUIC_INVALID_NEW_CONNECTION_ID_DATA);
3239 }
dschinazi118934b2019-06-13 18:09:08 -07003240 QUIC_DVLOG(2) << ENDPOINT
3241 << "Processing IETF new connection ID frame " << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003242 if (!visitor_->OnNewConnectionIdFrame(frame)) {
3243 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3244 // Returning true since there was no parsing error.
3245 return true;
3246 }
3247 break;
3248 }
3249 case IETF_RETIRE_CONNECTION_ID: {
3250 QuicRetireConnectionIdFrame frame;
3251 if (!ProcessRetireConnectionIdFrame(reader, &frame)) {
3252 return RaiseError(QUIC_INVALID_RETIRE_CONNECTION_ID_DATA);
3253 }
dschinazi118934b2019-06-13 18:09:08 -07003254 QUIC_DVLOG(2) << ENDPOINT
3255 << "Processing IETF retire connection ID frame "
3256 << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003257 if (!visitor_->OnRetireConnectionIdFrame(frame)) {
3258 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3259 // Returning true since there was no parsing error.
3260 return true;
3261 }
3262 break;
3263 }
3264 case IETF_NEW_TOKEN: {
3265 QuicNewTokenFrame frame;
3266 if (!ProcessNewTokenFrame(reader, &frame)) {
3267 return RaiseError(QUIC_INVALID_NEW_TOKEN);
3268 }
dschinazi118934b2019-06-13 18:09:08 -07003269 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF new token frame "
3270 << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003271 if (!visitor_->OnNewTokenFrame(frame)) {
3272 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3273 // Returning true since there was no parsing error.
3274 return true;
3275 }
3276 break;
3277 }
3278 case IETF_STOP_SENDING: {
3279 QuicStopSendingFrame frame;
3280 if (!ProcessStopSendingFrame(reader, &frame)) {
3281 return RaiseError(QUIC_INVALID_STOP_SENDING_FRAME_DATA);
3282 }
dschinazi118934b2019-06-13 18:09:08 -07003283 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF stop sending frame "
3284 << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003285 if (!visitor_->OnStopSendingFrame(frame)) {
3286 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3287 // Returning true since there was no parsing error.
3288 return true;
3289 }
3290 break;
3291 }
3292 case IETF_ACK_ECN:
3293 case IETF_ACK: {
3294 QuicAckFrame frame;
3295 if (!ProcessIetfAckFrame(reader, frame_type, &frame)) {
3296 return RaiseError(QUIC_INVALID_ACK_DATA);
3297 }
dschinazi118934b2019-06-13 18:09:08 -07003298 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF ACK frame " << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003299 break;
3300 }
3301 case IETF_PATH_CHALLENGE: {
3302 QuicPathChallengeFrame frame;
3303 if (!ProcessPathChallengeFrame(reader, &frame)) {
3304 return RaiseError(QUIC_INVALID_PATH_CHALLENGE_DATA);
3305 }
dschinazi118934b2019-06-13 18:09:08 -07003306 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF path challenge frame "
3307 << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003308 if (!visitor_->OnPathChallengeFrame(frame)) {
3309 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3310 // Returning true since there was no parsing error.
3311 return true;
3312 }
3313 break;
3314 }
3315 case IETF_PATH_RESPONSE: {
3316 QuicPathResponseFrame frame;
3317 if (!ProcessPathResponseFrame(reader, &frame)) {
3318 return RaiseError(QUIC_INVALID_PATH_RESPONSE_DATA);
3319 }
dschinazi118934b2019-06-13 18:09:08 -07003320 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF path response frame "
3321 << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003322 if (!visitor_->OnPathResponseFrame(frame)) {
3323 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3324 // Returning true since there was no parsing error.
3325 return true;
3326 }
3327 break;
3328 }
3329 case IETF_EXTENSION_MESSAGE_NO_LENGTH:
3330 QUIC_FALLTHROUGH_INTENDED;
3331 case IETF_EXTENSION_MESSAGE: {
3332 QuicMessageFrame message_frame;
3333 if (!ProcessMessageFrame(
3334 reader, frame_type == IETF_EXTENSION_MESSAGE_NO_LENGTH,
3335 &message_frame)) {
3336 return RaiseError(QUIC_INVALID_MESSAGE_DATA);
3337 }
dschinazi118934b2019-06-13 18:09:08 -07003338 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF message frame "
3339 << message_frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003340 if (!visitor_->OnMessageFrame(message_frame)) {
3341 QUIC_DVLOG(1) << ENDPOINT
3342 << "Visitor asked to stop further processing.";
3343 // Returning true since there was no parsing error.
3344 return true;
3345 }
3346 break;
3347 }
3348 case IETF_CRYPTO: {
3349 QuicCryptoFrame frame;
3350 if (!ProcessCryptoFrame(reader, &frame)) {
3351 return RaiseError(QUIC_INVALID_FRAME_DATA);
3352 }
dschinazi118934b2019-06-13 18:09:08 -07003353 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF crypto frame " << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003354 if (!visitor_->OnCryptoFrame(frame)) {
3355 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3356 // Returning true since there was no parsing error.
3357 return true;
3358 }
3359 break;
3360 }
3361
3362 default:
3363 set_detailed_error("Illegal frame type.");
3364 QUIC_DLOG(WARNING)
3365 << ENDPOINT
3366 << "Illegal frame type: " << static_cast<int>(frame_type);
3367 return RaiseError(QUIC_INVALID_FRAME_DATA);
3368 }
3369 }
3370 }
3371 return true;
3372}
3373
3374namespace {
3375// Create a mask that sets the last |num_bits| to 1 and the rest to 0.
3376inline uint8_t GetMaskFromNumBits(uint8_t num_bits) {
3377 return (1u << num_bits) - 1;
3378}
3379
3380// Extract |num_bits| from |flags| offset by |offset|.
3381uint8_t ExtractBits(uint8_t flags, uint8_t num_bits, uint8_t offset) {
3382 return (flags >> offset) & GetMaskFromNumBits(num_bits);
3383}
3384
3385// Extract the bit at position |offset| from |flags| as a bool.
3386bool ExtractBit(uint8_t flags, uint8_t offset) {
3387 return ((flags >> offset) & GetMaskFromNumBits(1)) != 0;
3388}
3389
3390// Set |num_bits|, offset by |offset| to |val| in |flags|.
3391void SetBits(uint8_t* flags, uint8_t val, uint8_t num_bits, uint8_t offset) {
3392 DCHECK_LE(val, GetMaskFromNumBits(num_bits));
3393 *flags |= val << offset;
3394}
3395
3396// Set the bit at position |offset| to |val| in |flags|.
3397void SetBit(uint8_t* flags, bool val, uint8_t offset) {
3398 SetBits(flags, val ? 1 : 0, 1, offset);
3399}
3400} // namespace
3401
3402bool QuicFramer::ProcessStreamFrame(QuicDataReader* reader,
3403 uint8_t frame_type,
3404 QuicStreamFrame* frame) {
3405 uint8_t stream_flags = frame_type;
3406
3407 uint8_t stream_id_length = 0;
3408 uint8_t offset_length = 4;
3409 bool has_data_length = true;
3410 stream_flags &= ~kQuicFrameTypeStreamMask;
3411
3412 // Read from right to left: StreamID, Offset, Data Length, Fin.
3413 stream_id_length = (stream_flags & kQuicStreamIDLengthMask) + 1;
3414 stream_flags >>= kQuicStreamIdShift;
3415
3416 offset_length = (stream_flags & kQuicStreamOffsetMask);
3417 // There is no encoding for 1 byte, only 0 and 2 through 8.
3418 if (offset_length > 0) {
3419 offset_length += 1;
3420 }
3421 stream_flags >>= kQuicStreamShift;
3422
3423 has_data_length =
3424 (stream_flags & kQuicStreamDataLengthMask) == kQuicStreamDataLengthMask;
3425 stream_flags >>= kQuicStreamDataLengthShift;
3426
3427 frame->fin = (stream_flags & kQuicStreamFinMask) == kQuicStreamFinShift;
3428
3429 uint64_t stream_id;
3430 if (!reader->ReadBytesToUInt64(stream_id_length, &stream_id)) {
3431 set_detailed_error("Unable to read stream_id.");
3432 return false;
3433 }
3434 frame->stream_id = static_cast<QuicStreamId>(stream_id);
3435
3436 if (!reader->ReadBytesToUInt64(offset_length, &frame->offset)) {
3437 set_detailed_error("Unable to read offset.");
3438 return false;
3439 }
3440
3441 // TODO(ianswett): Don't use QuicStringPiece as an intermediary.
3442 QuicStringPiece data;
3443 if (has_data_length) {
3444 if (!reader->ReadStringPiece16(&data)) {
3445 set_detailed_error("Unable to read frame data.");
3446 return false;
3447 }
3448 } else {
3449 if (!reader->ReadStringPiece(&data, reader->BytesRemaining())) {
3450 set_detailed_error("Unable to read frame data.");
3451 return false;
3452 }
3453 }
3454 frame->data_buffer = data.data();
3455 frame->data_length = static_cast<uint16_t>(data.length());
3456
3457 return true;
3458}
3459
3460bool QuicFramer::ProcessIetfStreamFrame(QuicDataReader* reader,
3461 uint8_t frame_type,
3462 QuicStreamFrame* frame) {
3463 // Read stream id from the frame. It's always present.
fkastenholz3c4eabf2019-04-22 07:49:59 -07003464 if (!reader->ReadVarIntU32(&frame->stream_id)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05003465 set_detailed_error("Unable to read stream_id.");
3466 return false;
3467 }
3468
3469 // If we have a data offset, read it. If not, set to 0.
3470 if (frame_type & IETF_STREAM_FRAME_OFF_BIT) {
3471 if (!reader->ReadVarInt62(&frame->offset)) {
3472 set_detailed_error("Unable to read stream data offset.");
3473 return false;
3474 }
3475 } else {
3476 // no offset in the frame, ensure it's 0 in the Frame.
3477 frame->offset = 0;
3478 }
3479
3480 // If we have a data length, read it. If not, set to 0.
3481 if (frame_type & IETF_STREAM_FRAME_LEN_BIT) {
3482 QuicIetfStreamDataLength length;
3483 if (!reader->ReadVarInt62(&length)) {
3484 set_detailed_error("Unable to read stream data length.");
3485 return false;
3486 }
3487 if (length > 0xffff) {
3488 set_detailed_error("Stream data length is too large.");
3489 return false;
3490 }
3491 frame->data_length = length;
3492 } else {
3493 // no length in the frame, it is the number of bytes remaining in the
3494 // packet.
3495 frame->data_length = reader->BytesRemaining();
3496 }
3497
3498 if (frame_type & IETF_STREAM_FRAME_FIN_BIT) {
3499 frame->fin = true;
3500 } else {
3501 frame->fin = false;
3502 }
3503
3504 // TODO(ianswett): Don't use QuicStringPiece as an intermediary.
3505 QuicStringPiece data;
3506 if (!reader->ReadStringPiece(&data, frame->data_length)) {
3507 set_detailed_error("Unable to read frame data.");
3508 return false;
3509 }
3510 frame->data_buffer = data.data();
3511 frame->data_length = static_cast<QuicIetfStreamDataLength>(data.length());
3512
3513 return true;
3514}
3515
3516bool QuicFramer::ProcessCryptoFrame(QuicDataReader* reader,
3517 QuicCryptoFrame* frame) {
3518 if (!reader->ReadVarInt62(&frame->offset)) {
3519 set_detailed_error("Unable to read crypto data offset.");
3520 return false;
3521 }
3522 uint64_t len;
3523 if (!reader->ReadVarInt62(&len) ||
3524 len > std::numeric_limits<QuicPacketLength>::max()) {
3525 set_detailed_error("Invalid data length.");
3526 return false;
3527 }
3528 frame->data_length = len;
3529
3530 // TODO(ianswett): Don't use QuicStringPiece as an intermediary.
3531 QuicStringPiece data;
3532 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();
3537 return true;
3538}
3539
3540bool QuicFramer::ProcessAckFrame(QuicDataReader* reader, uint8_t frame_type) {
3541 const bool has_ack_blocks =
3542 ExtractBit(frame_type, kQuicHasMultipleAckBlocksOffset);
3543 uint8_t num_ack_blocks = 0;
3544 uint8_t num_received_packets = 0;
3545
3546 // Determine the two lengths from the frame type: largest acked length,
3547 // ack block length.
3548 const QuicPacketNumberLength ack_block_length = ReadAckPacketNumberLength(
3549 version_.transport_version,
3550 ExtractBits(frame_type, kQuicSequenceNumberLengthNumBits,
3551 kActBlockLengthOffset));
3552 const QuicPacketNumberLength largest_acked_length = ReadAckPacketNumberLength(
3553 version_.transport_version,
3554 ExtractBits(frame_type, kQuicSequenceNumberLengthNumBits,
3555 kLargestAckedOffset));
3556
3557 uint64_t largest_acked;
3558 if (!reader->ReadBytesToUInt64(largest_acked_length, &largest_acked)) {
3559 set_detailed_error("Unable to read largest acked.");
3560 return false;
3561 }
3562
3563 if (largest_acked < first_sending_packet_number_.ToUint64()) {
3564 // Connection always sends packet starting from kFirstSendingPacketNumber >
3565 // 0, peer has observed an unsent packet.
3566 set_detailed_error("Largest acked is 0.");
3567 return false;
3568 }
3569
3570 uint64_t ack_delay_time_us;
3571 if (!reader->ReadUFloat16(&ack_delay_time_us)) {
3572 set_detailed_error("Unable to read ack delay time.");
3573 return false;
3574 }
3575
3576 if (!visitor_->OnAckFrameStart(
3577 QuicPacketNumber(largest_acked),
3578 ack_delay_time_us == kUFloat16MaxValue
3579 ? QuicTime::Delta::Infinite()
3580 : QuicTime::Delta::FromMicroseconds(ack_delay_time_us))) {
3581 // The visitor suppresses further processing of the packet. Although this is
3582 // not a parsing error, returns false as this is in middle of processing an
3583 // ack frame,
3584 set_detailed_error("Visitor suppresses further processing of ack frame.");
3585 return false;
3586 }
3587
3588 if (has_ack_blocks && !reader->ReadUInt8(&num_ack_blocks)) {
3589 set_detailed_error("Unable to read num of ack blocks.");
3590 return false;
3591 }
3592
3593 uint64_t first_block_length;
3594 if (!reader->ReadBytesToUInt64(ack_block_length, &first_block_length)) {
3595 set_detailed_error("Unable to read first ack block length.");
3596 return false;
3597 }
3598
3599 if (first_block_length == 0) {
3600 set_detailed_error("First block length is zero.");
3601 return false;
3602 }
3603 bool first_ack_block_underflow = first_block_length > largest_acked + 1;
3604 if (first_block_length + first_sending_packet_number_.ToUint64() >
3605 largest_acked + 1) {
3606 first_ack_block_underflow = true;
3607 }
3608 if (first_ack_block_underflow) {
3609 set_detailed_error(QuicStrCat("Underflow with first ack block length ",
3610 first_block_length, " largest acked is ",
3611 largest_acked, ".")
3612 .c_str());
3613 return false;
3614 }
3615
3616 uint64_t first_received = largest_acked + 1 - first_block_length;
3617 if (!visitor_->OnAckRange(QuicPacketNumber(first_received),
3618 QuicPacketNumber(largest_acked + 1))) {
3619 // The visitor suppresses further processing of the packet. Although
3620 // this is not a parsing error, returns false as this is in middle
3621 // of processing an ack frame,
3622 set_detailed_error("Visitor suppresses further processing of ack frame.");
3623 return false;
3624 }
3625
3626 if (num_ack_blocks > 0) {
3627 for (size_t i = 0; i < num_ack_blocks; ++i) {
3628 uint8_t gap = 0;
3629 if (!reader->ReadUInt8(&gap)) {
3630 set_detailed_error("Unable to read gap to next ack block.");
3631 return false;
3632 }
3633 uint64_t current_block_length;
3634 if (!reader->ReadBytesToUInt64(ack_block_length, &current_block_length)) {
3635 set_detailed_error("Unable to ack block length.");
3636 return false;
3637 }
3638 bool ack_block_underflow = first_received < gap + current_block_length;
3639 if (first_received < gap + current_block_length +
3640 first_sending_packet_number_.ToUint64()) {
3641 ack_block_underflow = true;
3642 }
3643 if (ack_block_underflow) {
3644 set_detailed_error(
3645 QuicStrCat("Underflow with ack block length ", current_block_length,
3646 ", end of block is ", first_received - gap, ".")
3647 .c_str());
3648 return false;
3649 }
3650
3651 first_received -= (gap + current_block_length);
3652 if (current_block_length > 0) {
3653 if (!visitor_->OnAckRange(
3654 QuicPacketNumber(first_received),
3655 QuicPacketNumber(first_received) + current_block_length)) {
3656 // The visitor suppresses further processing of the packet. Although
3657 // this is not a parsing error, returns false as this is in middle
3658 // of processing an ack frame,
3659 set_detailed_error(
3660 "Visitor suppresses further processing of ack frame.");
3661 return false;
3662 }
3663 }
3664 }
3665 }
3666
3667 if (!reader->ReadUInt8(&num_received_packets)) {
3668 set_detailed_error("Unable to read num received packets.");
3669 return false;
3670 }
3671
3672 if (!ProcessTimestampsInAckFrame(num_received_packets,
3673 QuicPacketNumber(largest_acked), reader)) {
3674 return false;
3675 }
3676
3677 // Done processing the ACK frame.
3678 return visitor_->OnAckFrameEnd(QuicPacketNumber(first_received));
3679}
3680
3681bool QuicFramer::ProcessTimestampsInAckFrame(uint8_t num_received_packets,
3682 QuicPacketNumber largest_acked,
3683 QuicDataReader* reader) {
3684 if (num_received_packets == 0) {
3685 return true;
3686 }
3687 uint8_t delta_from_largest_observed;
3688 if (!reader->ReadUInt8(&delta_from_largest_observed)) {
3689 set_detailed_error("Unable to read sequence delta in received packets.");
3690 return false;
3691 }
3692
3693 if (largest_acked.ToUint64() <= delta_from_largest_observed) {
3694 set_detailed_error(QuicStrCat("delta_from_largest_observed too high: ",
3695 delta_from_largest_observed,
3696 ", largest_acked: ", largest_acked.ToUint64())
3697 .c_str());
3698 return false;
3699 }
3700
3701 // Time delta from the framer creation.
3702 uint32_t time_delta_us;
3703 if (!reader->ReadUInt32(&time_delta_us)) {
3704 set_detailed_error("Unable to read time delta in received packets.");
3705 return false;
3706 }
3707
3708 QuicPacketNumber seq_num = largest_acked - delta_from_largest_observed;
3709 if (process_timestamps_) {
3710 last_timestamp_ = CalculateTimestampFromWire(time_delta_us);
3711
3712 visitor_->OnAckTimestamp(seq_num, creation_time_ + last_timestamp_);
3713 }
3714
3715 for (uint8_t i = 1; i < num_received_packets; ++i) {
3716 if (!reader->ReadUInt8(&delta_from_largest_observed)) {
3717 set_detailed_error("Unable to read sequence delta in received packets.");
3718 return false;
3719 }
3720 if (largest_acked.ToUint64() <= delta_from_largest_observed) {
3721 set_detailed_error(
3722 QuicStrCat("delta_from_largest_observed too high: ",
3723 delta_from_largest_observed,
3724 ", largest_acked: ", largest_acked.ToUint64())
3725 .c_str());
3726 return false;
3727 }
3728 seq_num = largest_acked - delta_from_largest_observed;
3729
3730 // Time delta from the previous timestamp.
3731 uint64_t incremental_time_delta_us;
3732 if (!reader->ReadUFloat16(&incremental_time_delta_us)) {
3733 set_detailed_error(
3734 "Unable to read incremental time delta in received packets.");
3735 return false;
3736 }
3737
3738 if (process_timestamps_) {
3739 last_timestamp_ = last_timestamp_ + QuicTime::Delta::FromMicroseconds(
3740 incremental_time_delta_us);
3741 visitor_->OnAckTimestamp(seq_num, creation_time_ + last_timestamp_);
3742 }
3743 }
3744 return true;
3745}
3746
3747bool QuicFramer::ProcessIetfAckFrame(QuicDataReader* reader,
3748 uint64_t frame_type,
3749 QuicAckFrame* ack_frame) {
3750 uint64_t largest_acked;
3751 if (!reader->ReadVarInt62(&largest_acked)) {
3752 set_detailed_error("Unable to read largest acked.");
3753 return false;
3754 }
3755 if (largest_acked < first_sending_packet_number_.ToUint64()) {
3756 // Connection always sends packet starting from kFirstSendingPacketNumber >
3757 // 0, peer has observed an unsent packet.
3758 set_detailed_error("Largest acked is 0.");
3759 return false;
3760 }
3761 ack_frame->largest_acked = static_cast<QuicPacketNumber>(largest_acked);
3762 uint64_t ack_delay_time_in_us;
3763 if (!reader->ReadVarInt62(&ack_delay_time_in_us)) {
3764 set_detailed_error("Unable to read ack delay time.");
3765 return false;
3766 }
3767
QUICHE teama6ef0a62019-03-07 20:34:33 -05003768 if (ack_delay_time_in_us == kVarInt62MaxValue) {
3769 ack_frame->ack_delay_time = QuicTime::Delta::Infinite();
3770 } else {
fkastenholz4dc4ba32019-07-30 09:55:25 -07003771 ack_delay_time_in_us = (ack_delay_time_in_us << peer_ack_delay_exponent_);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003772 ack_frame->ack_delay_time =
3773 QuicTime::Delta::FromMicroseconds(ack_delay_time_in_us);
3774 }
3775 if (frame_type == IETF_ACK_ECN) {
3776 ack_frame->ecn_counters_populated = true;
3777 if (!reader->ReadVarInt62(&ack_frame->ect_0_count)) {
3778 set_detailed_error("Unable to read ack ect_0_count.");
3779 return false;
3780 }
3781 if (!reader->ReadVarInt62(&ack_frame->ect_1_count)) {
3782 set_detailed_error("Unable to read ack ect_1_count.");
3783 return false;
3784 }
3785 if (!reader->ReadVarInt62(&ack_frame->ecn_ce_count)) {
3786 set_detailed_error("Unable to read ack ecn_ce_count.");
3787 return false;
3788 }
3789 } else {
3790 ack_frame->ecn_counters_populated = false;
3791 ack_frame->ect_0_count = 0;
3792 ack_frame->ect_1_count = 0;
3793 ack_frame->ecn_ce_count = 0;
3794 }
3795 if (!visitor_->OnAckFrameStart(QuicPacketNumber(largest_acked),
3796 ack_frame->ack_delay_time)) {
3797 // The visitor suppresses further processing of the packet. Although this is
3798 // not a parsing error, returns false as this is in middle of processing an
3799 // ACK frame.
3800 set_detailed_error("Visitor suppresses further processing of ACK frame.");
3801 return false;
3802 }
3803
3804 // Get number of ACK blocks from the packet.
3805 uint64_t ack_block_count;
3806 if (!reader->ReadVarInt62(&ack_block_count)) {
3807 set_detailed_error("Unable to read ack block count.");
3808 return false;
3809 }
3810 // There always is a first ACK block, which is the (number of packets being
3811 // acked)-1, up to and including the packet at largest_acked. Therefore if the
3812 // value is 0, then only largest is acked. If it is 1, then largest-1,
3813 // largest] are acked, etc
3814 uint64_t ack_block_value;
3815 if (!reader->ReadVarInt62(&ack_block_value)) {
3816 set_detailed_error("Unable to read first ack block length.");
3817 return false;
3818 }
3819 // Calculate the packets being acked in the first block.
3820 // +1 because AddRange implementation requires [low,high)
3821 uint64_t block_high = largest_acked + 1;
3822 uint64_t block_low = largest_acked - ack_block_value;
3823
3824 // ack_block_value is the number of packets preceding the
3825 // largest_acked packet which are in the block being acked. Thus,
3826 // its maximum value is largest_acked-1. Test this, reporting an
3827 // error if the value is wrong.
3828 if (ack_block_value + first_sending_packet_number_.ToUint64() >
3829 largest_acked) {
3830 set_detailed_error(QuicStrCat("Underflow with first ack block length ",
3831 ack_block_value + 1, " largest acked is ",
3832 largest_acked, ".")
3833 .c_str());
3834 return false;
3835 }
3836
3837 if (!visitor_->OnAckRange(QuicPacketNumber(block_low),
3838 QuicPacketNumber(block_high))) {
3839 // The visitor suppresses further processing of the packet. Although
3840 // this is not a parsing error, returns false as this is in middle
3841 // of processing an ACK frame.
3842 set_detailed_error("Visitor suppresses further processing of ACK frame.");
3843 return false;
3844 }
3845
3846 while (ack_block_count != 0) {
3847 uint64_t gap_block_value;
3848 // Get the sizes of the gap and ack blocks,
3849 if (!reader->ReadVarInt62(&gap_block_value)) {
3850 set_detailed_error("Unable to read gap block value.");
3851 return false;
3852 }
3853 // It's an error if the gap is larger than the space from packet
3854 // number 0 to the start of the block that's just been acked, PLUS
3855 // there must be space for at least 1 packet to be acked. For
3856 // example, if block_low is 10 and gap_block_value is 9, it means
3857 // the gap block is 10 packets long, leaving no room for a packet
3858 // to be acked. Thus, gap_block_value+2 can not be larger than
3859 // block_low.
3860 // The test is written this way to detect wrap-arounds.
3861 if ((gap_block_value + 2) > block_low) {
3862 set_detailed_error(
3863 QuicStrCat("Underflow with gap block length ", gap_block_value + 1,
3864 " previous ack block start is ", block_low, ".")
3865 .c_str());
3866 return false;
3867 }
3868
3869 // Adjust block_high to be the top of the next ack block.
3870 // There is a gap of |gap_block_value| packets between the bottom
3871 // of ack block N and top of block N+1. Note that gap_block_value
3872 // is he size of the gap minus 1 (per the QUIC protocol), and
3873 // block_high is the packet number of the first packet of the gap
3874 // (per the implementation of OnAckRange/AddAckRange, below).
3875 block_high = block_low - 1 - gap_block_value;
3876
3877 if (!reader->ReadVarInt62(&ack_block_value)) {
3878 set_detailed_error("Unable to read ack block value.");
3879 return false;
3880 }
3881 if (ack_block_value + first_sending_packet_number_.ToUint64() >
3882 (block_high - 1)) {
3883 set_detailed_error(
3884 QuicStrCat("Underflow with ack block length ", ack_block_value + 1,
3885 " latest ack block end is ", block_high - 1, ".")
3886 .c_str());
3887 return false;
3888 }
3889 // Calculate the low end of the new nth ack block. The +1 is
3890 // because the encoded value is the blocksize-1.
3891 block_low = block_high - 1 - ack_block_value;
3892 if (!visitor_->OnAckRange(QuicPacketNumber(block_low),
3893 QuicPacketNumber(block_high))) {
3894 // The visitor suppresses further processing of the packet. Although
3895 // this is not a parsing error, returns false as this is in middle
3896 // of processing an ACK frame.
3897 set_detailed_error("Visitor suppresses further processing of ACK frame.");
3898 return false;
3899 }
3900
3901 // Another one done.
3902 ack_block_count--;
3903 }
3904
3905 return visitor_->OnAckFrameEnd(QuicPacketNumber(block_low));
3906}
3907
3908bool QuicFramer::ProcessStopWaitingFrame(QuicDataReader* reader,
3909 const QuicPacketHeader& header,
3910 QuicStopWaitingFrame* stop_waiting) {
3911 uint64_t least_unacked_delta;
3912 if (!reader->ReadBytesToUInt64(header.packet_number_length,
3913 &least_unacked_delta)) {
3914 set_detailed_error("Unable to read least unacked delta.");
3915 return false;
3916 }
3917 if (header.packet_number.ToUint64() <= least_unacked_delta) {
3918 set_detailed_error("Invalid unacked delta.");
3919 return false;
3920 }
3921 stop_waiting->least_unacked = header.packet_number - least_unacked_delta;
3922
3923 return true;
3924}
3925
3926bool QuicFramer::ProcessRstStreamFrame(QuicDataReader* reader,
3927 QuicRstStreamFrame* frame) {
3928 if (!reader->ReadUInt32(&frame->stream_id)) {
3929 set_detailed_error("Unable to read stream_id.");
3930 return false;
3931 }
3932
3933 if (!reader->ReadUInt64(&frame->byte_offset)) {
3934 set_detailed_error("Unable to read rst stream sent byte offset.");
3935 return false;
3936 }
3937
3938 uint32_t error_code;
3939 if (!reader->ReadUInt32(&error_code)) {
3940 set_detailed_error("Unable to read rst stream error code.");
3941 return false;
3942 }
3943
3944 if (error_code >= QUIC_STREAM_LAST_ERROR) {
3945 // Ignore invalid stream error code if any.
3946 error_code = QUIC_STREAM_LAST_ERROR;
3947 }
3948
3949 frame->error_code = static_cast<QuicRstStreamErrorCode>(error_code);
3950
3951 return true;
3952}
3953
3954bool QuicFramer::ProcessConnectionCloseFrame(QuicDataReader* reader,
3955 QuicConnectionCloseFrame* frame) {
3956 uint32_t error_code;
fkastenholze9d71a82019-04-09 05:12:13 -07003957 frame->close_type = GOOGLE_QUIC_CONNECTION_CLOSE;
3958
QUICHE teama6ef0a62019-03-07 20:34:33 -05003959 if (!reader->ReadUInt32(&error_code)) {
3960 set_detailed_error("Unable to read connection close error code.");
3961 return false;
3962 }
3963
3964 if (error_code >= QUIC_LAST_ERROR) {
3965 // Ignore invalid QUIC error code if any.
3966 error_code = QUIC_LAST_ERROR;
3967 }
3968
fkastenholze9d71a82019-04-09 05:12:13 -07003969 frame->quic_error_code = static_cast<QuicErrorCode>(error_code);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003970
fkastenholza14a7ae2019-08-07 05:21:22 -07003971 // For Google QUIC connection closes, copy the Google QUIC error code to
3972 // the extracted error code field so that the Google QUIC error code is always
3973 // available in extracted_error_code.
3974 frame->extracted_error_code = frame->quic_error_code;
3975
QUICHE teama6ef0a62019-03-07 20:34:33 -05003976 QuicStringPiece error_details;
3977 if (!reader->ReadStringPiece16(&error_details)) {
3978 set_detailed_error("Unable to read connection close error details.");
3979 return false;
3980 }
vasilvvc48c8712019-03-11 13:38:16 -07003981 frame->error_details = std::string(error_details);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003982
3983 return true;
3984}
3985
3986bool QuicFramer::ProcessGoAwayFrame(QuicDataReader* reader,
3987 QuicGoAwayFrame* frame) {
3988 uint32_t error_code;
3989 if (!reader->ReadUInt32(&error_code)) {
3990 set_detailed_error("Unable to read go away error code.");
3991 return false;
3992 }
3993
3994 if (error_code >= QUIC_LAST_ERROR) {
3995 // Ignore invalid QUIC error code if any.
3996 error_code = QUIC_LAST_ERROR;
3997 }
3998 frame->error_code = static_cast<QuicErrorCode>(error_code);
3999
4000 uint32_t stream_id;
4001 if (!reader->ReadUInt32(&stream_id)) {
4002 set_detailed_error("Unable to read last good stream id.");
4003 return false;
4004 }
4005 frame->last_good_stream_id = static_cast<QuicStreamId>(stream_id);
4006
4007 QuicStringPiece reason_phrase;
4008 if (!reader->ReadStringPiece16(&reason_phrase)) {
4009 set_detailed_error("Unable to read goaway reason.");
4010 return false;
4011 }
vasilvvc48c8712019-03-11 13:38:16 -07004012 frame->reason_phrase = std::string(reason_phrase);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004013
4014 return true;
4015}
4016
4017bool QuicFramer::ProcessWindowUpdateFrame(QuicDataReader* reader,
4018 QuicWindowUpdateFrame* frame) {
4019 if (!reader->ReadUInt32(&frame->stream_id)) {
4020 set_detailed_error("Unable to read stream_id.");
4021 return false;
4022 }
4023
4024 if (!reader->ReadUInt64(&frame->byte_offset)) {
4025 set_detailed_error("Unable to read window byte_offset.");
4026 return false;
4027 }
4028
4029 return true;
4030}
4031
4032bool QuicFramer::ProcessBlockedFrame(QuicDataReader* reader,
4033 QuicBlockedFrame* frame) {
fkastenholz305e1732019-06-18 05:01:22 -07004034 DCHECK(!VersionHasIetfQuicFrames(version_.transport_version))
4035 << "Attempt to process non-IETF QUIC frames in an IETF QUIC version.";
QUICHE teama6ef0a62019-03-07 20:34:33 -05004036
4037 if (!reader->ReadUInt32(&frame->stream_id)) {
4038 set_detailed_error("Unable to read stream_id.");
4039 return false;
4040 }
4041
4042 return true;
4043}
4044
4045void QuicFramer::ProcessPaddingFrame(QuicDataReader* reader,
4046 QuicPaddingFrame* frame) {
4047 // Type byte has been read.
4048 frame->num_padding_bytes = 1;
4049 uint8_t next_byte;
4050 while (!reader->IsDoneReading() && reader->PeekByte() == 0x00) {
4051 reader->ReadBytes(&next_byte, 1);
4052 DCHECK_EQ(0x00, next_byte);
4053 ++frame->num_padding_bytes;
4054 }
4055}
4056
4057bool QuicFramer::ProcessMessageFrame(QuicDataReader* reader,
4058 bool no_message_length,
4059 QuicMessageFrame* frame) {
4060 if (no_message_length) {
4061 QuicStringPiece remaining(reader->ReadRemainingPayload());
4062 frame->data = remaining.data();
4063 frame->message_length = remaining.length();
4064 return true;
4065 }
4066
4067 uint64_t message_length;
4068 if (!reader->ReadVarInt62(&message_length)) {
4069 set_detailed_error("Unable to read message length");
4070 return false;
4071 }
4072
4073 QuicStringPiece message_piece;
4074 if (!reader->ReadStringPiece(&message_piece, message_length)) {
4075 set_detailed_error("Unable to read message data");
4076 return false;
4077 }
4078
4079 frame->data = message_piece.data();
4080 frame->message_length = message_length;
4081
4082 return true;
4083}
4084
4085// static
4086QuicStringPiece QuicFramer::GetAssociatedDataFromEncryptedPacket(
4087 QuicTransportVersion version,
4088 const QuicEncryptedPacket& encrypted,
4089 QuicConnectionIdLength destination_connection_id_length,
4090 QuicConnectionIdLength source_connection_id_length,
4091 bool includes_version,
4092 bool includes_diversification_nonce,
4093 QuicPacketNumberLength packet_number_length,
4094 QuicVariableLengthIntegerLength retry_token_length_length,
4095 uint64_t retry_token_length,
4096 QuicVariableLengthIntegerLength length_length) {
4097 // TODO(ianswett): This is identical to QuicData::AssociatedData.
4098 return QuicStringPiece(
4099 encrypted.data(),
4100 GetStartOfEncryptedData(version, destination_connection_id_length,
4101 source_connection_id_length, includes_version,
4102 includes_diversification_nonce,
4103 packet_number_length, retry_token_length_length,
4104 retry_token_length, length_length));
4105}
4106
4107void QuicFramer::SetDecrypter(EncryptionLevel level,
4108 std::unique_ptr<QuicDecrypter> decrypter) {
QUICHE team76086e42019-03-25 15:12:29 -07004109 DCHECK_EQ(alternative_decrypter_level_, NUM_ENCRYPTION_LEVELS);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004110 DCHECK_GE(level, decrypter_level_);
zhongyi546cc452019-04-12 15:27:49 -07004111 DCHECK(!version_.KnowsWhichDecrypterToUse());
dschinazi4b5a68a2019-08-15 15:45:36 -07004112 QUIC_DVLOG(1) << ENDPOINT << "Setting decrypter from level "
4113 << QuicUtils::EncryptionLevelToString(decrypter_level_)
4114 << " to " << QuicUtils::EncryptionLevelToString(level);
QUICHE team76086e42019-03-25 15:12:29 -07004115 decrypter_[decrypter_level_] = nullptr;
4116 decrypter_[level] = std::move(decrypter);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004117 decrypter_level_ = level;
4118}
4119
4120void QuicFramer::SetAlternativeDecrypter(
4121 EncryptionLevel level,
4122 std::unique_ptr<QuicDecrypter> decrypter,
4123 bool latch_once_used) {
QUICHE team76086e42019-03-25 15:12:29 -07004124 DCHECK_NE(level, decrypter_level_);
zhongyi546cc452019-04-12 15:27:49 -07004125 DCHECK(!version_.KnowsWhichDecrypterToUse());
dschinazi4b5a68a2019-08-15 15:45:36 -07004126 QUIC_DVLOG(1) << ENDPOINT << "Setting alternative decrypter from level "
4127 << QuicUtils::EncryptionLevelToString(
4128 alternative_decrypter_level_)
4129 << " to " << QuicUtils::EncryptionLevelToString(level);
QUICHE team76086e42019-03-25 15:12:29 -07004130 if (alternative_decrypter_level_ != NUM_ENCRYPTION_LEVELS) {
4131 decrypter_[alternative_decrypter_level_] = nullptr;
4132 }
4133 decrypter_[level] = std::move(decrypter);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004134 alternative_decrypter_level_ = level;
4135 alternative_decrypter_latch_ = latch_once_used;
4136}
4137
zhongyi546cc452019-04-12 15:27:49 -07004138void QuicFramer::InstallDecrypter(EncryptionLevel level,
4139 std::unique_ptr<QuicDecrypter> decrypter) {
4140 DCHECK(version_.KnowsWhichDecrypterToUse());
dschinazi4b5a68a2019-08-15 15:45:36 -07004141 QUIC_DVLOG(1) << ENDPOINT << "Installing decrypter at level "
4142 << QuicUtils::EncryptionLevelToString(level);
zhongyi546cc452019-04-12 15:27:49 -07004143 decrypter_[level] = std::move(decrypter);
4144}
4145
4146void QuicFramer::RemoveDecrypter(EncryptionLevel level) {
4147 DCHECK(version_.KnowsWhichDecrypterToUse());
dschinazi4b5a68a2019-08-15 15:45:36 -07004148 QUIC_DVLOG(1) << ENDPOINT << "Removing decrypter at level "
4149 << QuicUtils::EncryptionLevelToString(level);
zhongyi546cc452019-04-12 15:27:49 -07004150 decrypter_[level] = nullptr;
4151}
4152
4153const QuicDecrypter* QuicFramer::GetDecrypter(EncryptionLevel level) const {
4154 DCHECK(version_.KnowsWhichDecrypterToUse());
4155 return decrypter_[level].get();
4156}
4157
QUICHE teama6ef0a62019-03-07 20:34:33 -05004158const QuicDecrypter* QuicFramer::decrypter() const {
QUICHE team76086e42019-03-25 15:12:29 -07004159 return decrypter_[decrypter_level_].get();
QUICHE teama6ef0a62019-03-07 20:34:33 -05004160}
4161
4162const QuicDecrypter* QuicFramer::alternative_decrypter() const {
QUICHE team76086e42019-03-25 15:12:29 -07004163 if (alternative_decrypter_level_ == NUM_ENCRYPTION_LEVELS) {
4164 return nullptr;
4165 }
4166 return decrypter_[alternative_decrypter_level_].get();
QUICHE teama6ef0a62019-03-07 20:34:33 -05004167}
4168
4169void QuicFramer::SetEncrypter(EncryptionLevel level,
4170 std::unique_ptr<QuicEncrypter> encrypter) {
4171 DCHECK_GE(level, 0);
4172 DCHECK_LT(level, NUM_ENCRYPTION_LEVELS);
dschinazi4b5a68a2019-08-15 15:45:36 -07004173 QUIC_DVLOG(1) << ENDPOINT << "Setting encrypter at level "
4174 << QuicUtils::EncryptionLevelToString(level);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004175 encrypter_[level] = std::move(encrypter);
4176}
4177
nharper4a5a76c2019-09-13 13:44:37 -07004178void QuicFramer::SetInitialObfuscators(QuicConnectionId connection_id) {
4179 CrypterPair crypters;
4180 CryptoUtils::CreateInitialObfuscators(perspective_, version_, connection_id,
4181 &crypters);
4182 encrypter_[ENCRYPTION_INITIAL] = std::move(crypters.encrypter);
4183 decrypter_[ENCRYPTION_INITIAL] = std::move(crypters.decrypter);
4184}
4185
QUICHE teama6ef0a62019-03-07 20:34:33 -05004186size_t QuicFramer::EncryptInPlace(EncryptionLevel level,
4187 QuicPacketNumber packet_number,
4188 size_t ad_len,
4189 size_t total_len,
4190 size_t buffer_len,
4191 char* buffer) {
4192 DCHECK(packet_number.IsInitialized());
dschinazi2c5386e2019-04-16 16:37:37 -07004193 if (encrypter_[level] == nullptr) {
4194 QUIC_BUG << ENDPOINT
4195 << "Attempted to encrypt in place without encrypter at level "
4196 << QuicUtils::EncryptionLevelToString(level);
4197 RaiseError(QUIC_ENCRYPTION_FAILURE);
4198 return 0;
4199 }
4200
QUICHE teama6ef0a62019-03-07 20:34:33 -05004201 size_t output_length = 0;
4202 if (!encrypter_[level]->EncryptPacket(
4203 packet_number.ToUint64(),
4204 QuicStringPiece(buffer, ad_len), // Associated data
4205 QuicStringPiece(buffer + ad_len, total_len - ad_len), // Plaintext
4206 buffer + ad_len, // Destination buffer
4207 &output_length, buffer_len - ad_len)) {
4208 RaiseError(QUIC_ENCRYPTION_FAILURE);
4209 return 0;
4210 }
nharper55fa6132019-05-07 19:37:21 -07004211 if (version_.HasHeaderProtection() &&
4212 !ApplyHeaderProtection(level, buffer, ad_len + output_length, ad_len)) {
4213 QUIC_DLOG(ERROR) << "Applying header protection failed.";
4214 RaiseError(QUIC_ENCRYPTION_FAILURE);
4215 return 0;
4216 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004217
4218 return ad_len + output_length;
4219}
4220
nharper55fa6132019-05-07 19:37:21 -07004221namespace {
4222
4223const size_t kHPSampleLen = 16;
4224
4225constexpr bool IsLongHeader(uint8_t type_byte) {
4226 return (type_byte & FLAGS_LONG_HEADER) != 0;
4227}
4228
4229} // namespace
4230
4231bool QuicFramer::ApplyHeaderProtection(EncryptionLevel level,
4232 char* buffer,
4233 size_t buffer_len,
4234 size_t ad_len) {
4235 QuicDataReader buffer_reader(buffer, buffer_len);
4236 QuicDataWriter buffer_writer(buffer_len, buffer);
4237 // The sample starts 4 bytes after the start of the packet number.
4238 if (ad_len < last_written_packet_number_length_) {
4239 return false;
4240 }
4241 size_t pn_offset = ad_len - last_written_packet_number_length_;
4242 // Sample the ciphertext and generate the mask to use for header protection.
4243 size_t sample_offset = pn_offset + 4;
4244 QuicDataReader sample_reader(buffer, buffer_len);
4245 QuicStringPiece sample;
4246 if (!sample_reader.Seek(sample_offset) ||
4247 !sample_reader.ReadStringPiece(&sample, kHPSampleLen)) {
4248 QUIC_BUG << "Not enough bytes to sample: sample_offset " << sample_offset
4249 << ", sample len: " << kHPSampleLen
4250 << ", buffer len: " << buffer_len;
4251 return false;
4252 }
4253
4254 std::string mask = encrypter_[level]->GenerateHeaderProtectionMask(sample);
4255 if (mask.empty()) {
4256 QUIC_BUG << "Unable to generate header protection mask.";
4257 return false;
4258 }
4259 QuicDataReader mask_reader(mask.data(), mask.size());
4260
4261 // Apply the mask to the 4 or 5 least significant bits of the first byte.
4262 uint8_t bitmask = 0x1f;
4263 uint8_t type_byte;
4264 if (!buffer_reader.ReadUInt8(&type_byte)) {
4265 return false;
4266 }
4267 QuicLongHeaderType header_type;
4268 if (IsLongHeader(type_byte)) {
4269 bitmask = 0x0f;
fayang36825da2019-08-21 14:01:27 -07004270 if (!GetLongHeaderType(type_byte, &header_type)) {
nharper55fa6132019-05-07 19:37:21 -07004271 return false;
4272 }
4273 }
4274 uint8_t mask_byte;
4275 if (!mask_reader.ReadUInt8(&mask_byte) ||
4276 !buffer_writer.WriteUInt8(type_byte ^ (mask_byte & bitmask))) {
4277 return false;
4278 }
4279
4280 // Adjust |pn_offset| to account for the diversification nonce.
4281 if (IsLongHeader(type_byte) && header_type == ZERO_RTT_PROTECTED &&
4282 perspective_ == Perspective::IS_SERVER &&
4283 version_.handshake_protocol == PROTOCOL_QUIC_CRYPTO) {
4284 if (pn_offset <= kDiversificationNonceSize) {
4285 QUIC_BUG << "Expected diversification nonce, but not enough bytes";
4286 return false;
4287 }
4288 pn_offset -= kDiversificationNonceSize;
4289 }
4290 // Advance the reader and writer to the packet number. Both the reader and
4291 // writer have each read/written one byte.
4292 if (!buffer_writer.Seek(pn_offset - 1) ||
4293 !buffer_reader.Seek(pn_offset - 1)) {
4294 return false;
4295 }
4296 // Apply the rest of the mask to the packet number.
4297 for (size_t i = 0; i < last_written_packet_number_length_; ++i) {
4298 uint8_t buffer_byte;
4299 uint8_t mask_byte;
4300 if (!mask_reader.ReadUInt8(&mask_byte) ||
4301 !buffer_reader.ReadUInt8(&buffer_byte) ||
4302 !buffer_writer.WriteUInt8(buffer_byte ^ mask_byte)) {
4303 return false;
4304 }
4305 }
4306 return true;
4307}
4308
4309bool QuicFramer::RemoveHeaderProtection(QuicDataReader* reader,
4310 const QuicEncryptedPacket& packet,
4311 QuicPacketHeader* header,
4312 uint64_t* full_packet_number,
4313 std::vector<char>* associated_data) {
4314 EncryptionLevel expected_decryption_level = GetEncryptionLevel(*header);
4315 QuicDecrypter* decrypter = decrypter_[expected_decryption_level].get();
4316 if (decrypter == nullptr) {
4317 QUIC_DVLOG(1)
dschinazi4b5a68a2019-08-15 15:45:36 -07004318 << ENDPOINT
nharper55fa6132019-05-07 19:37:21 -07004319 << "No decrypter available for removing header protection at level "
dschinazi4b5a68a2019-08-15 15:45:36 -07004320 << QuicUtils::EncryptionLevelToString(expected_decryption_level);
nharper55fa6132019-05-07 19:37:21 -07004321 return false;
4322 }
4323
4324 bool has_diversification_nonce =
4325 header->form == IETF_QUIC_LONG_HEADER_PACKET &&
4326 header->long_packet_type == ZERO_RTT_PROTECTED &&
4327 perspective_ == Perspective::IS_CLIENT &&
4328 version_.handshake_protocol == PROTOCOL_QUIC_CRYPTO;
4329
4330 // Read a sample from the ciphertext and compute the mask to use for header
4331 // protection.
4332 QuicStringPiece remaining_packet = reader->PeekRemainingPayload();
4333 QuicDataReader sample_reader(remaining_packet);
4334
4335 // The sample starts 4 bytes after the start of the packet number.
4336 QuicStringPiece pn;
4337 if (!sample_reader.ReadStringPiece(&pn, 4)) {
4338 QUIC_DVLOG(1) << "Not enough data to sample";
4339 return false;
4340 }
4341 if (has_diversification_nonce) {
4342 // In Google QUIC, the diversification nonce comes between the packet number
4343 // and the sample.
4344 if (!sample_reader.Seek(kDiversificationNonceSize)) {
4345 QUIC_DVLOG(1) << "No diversification nonce to skip over";
4346 return false;
4347 }
4348 }
4349 std::string mask = decrypter->GenerateHeaderProtectionMask(&sample_reader);
4350 QuicDataReader mask_reader(mask.data(), mask.size());
4351 if (mask.empty()) {
4352 QUIC_DVLOG(1) << "Failed to compute mask";
4353 return false;
4354 }
4355
4356 // Unmask the rest of the type byte.
4357 uint8_t bitmask = 0x1f;
4358 if (IsLongHeader(header->type_byte)) {
4359 bitmask = 0x0f;
4360 }
4361 uint8_t mask_byte;
4362 if (!mask_reader.ReadUInt8(&mask_byte)) {
4363 QUIC_DVLOG(1) << "No first byte to read from mask";
4364 return false;
4365 }
4366 header->type_byte ^= (mask_byte & bitmask);
4367
4368 // Compute the packet number length.
4369 header->packet_number_length =
4370 static_cast<QuicPacketNumberLength>((header->type_byte & 0x03) + 1);
4371
4372 char pn_buffer[IETF_MAX_PACKET_NUMBER_LENGTH] = {};
4373 QuicDataWriter pn_writer(QUIC_ARRAYSIZE(pn_buffer), pn_buffer);
4374
4375 // Read the (protected) packet number from the reader and unmask the packet
4376 // number.
4377 for (size_t i = 0; i < header->packet_number_length; ++i) {
4378 uint8_t protected_pn_byte, mask_byte;
4379 if (!mask_reader.ReadUInt8(&mask_byte) ||
4380 !reader->ReadUInt8(&protected_pn_byte) ||
4381 !pn_writer.WriteUInt8(protected_pn_byte ^ mask_byte)) {
4382 QUIC_DVLOG(1) << "Failed to unmask packet number";
4383 return false;
4384 }
4385 }
4386 QuicDataReader packet_number_reader(pn_writer.data(), pn_writer.length());
4387 QuicPacketNumber base_packet_number;
4388 if (supports_multiple_packet_number_spaces_) {
4389 PacketNumberSpace pn_space = GetPacketNumberSpace(*header);
4390 if (pn_space == NUM_PACKET_NUMBER_SPACES) {
4391 return false;
4392 }
4393 base_packet_number = largest_decrypted_packet_numbers_[pn_space];
4394 } else {
4395 base_packet_number = largest_packet_number_;
4396 }
4397 if (!ProcessAndCalculatePacketNumber(
4398 &packet_number_reader, header->packet_number_length,
4399 base_packet_number, full_packet_number)) {
4400 return false;
4401 }
4402
4403 // Get the associated data, and apply the same unmasking operations to it.
4404 QuicStringPiece ad = GetAssociatedDataFromEncryptedPacket(
4405 version_.transport_version, packet,
4406 GetIncludedDestinationConnectionIdLength(*header),
4407 GetIncludedSourceConnectionIdLength(*header), header->version_flag,
4408 has_diversification_nonce, header->packet_number_length,
4409 header->retry_token_length_length, header->retry_token.length(),
4410 header->length_length);
4411 *associated_data = std::vector<char>(ad.begin(), ad.end());
4412 QuicDataWriter ad_writer(associated_data->size(), associated_data->data());
4413
4414 // Apply the unmasked type byte and packet number to |associated_data|.
4415 if (!ad_writer.WriteUInt8(header->type_byte)) {
4416 return false;
4417 }
4418 // Put the packet number at the end of the AD, or if there's a diversification
4419 // nonce, before that (which is at the end of the AD).
4420 size_t seek_len = ad_writer.remaining() - header->packet_number_length;
4421 if (has_diversification_nonce) {
4422 seek_len -= kDiversificationNonceSize;
4423 }
4424 if (!ad_writer.Seek(seek_len) ||
4425 !ad_writer.WriteBytes(pn_writer.data(), pn_writer.length())) {
4426 QUIC_DVLOG(1) << "Failed to apply unmasking operations to AD";
4427 return false;
4428 }
4429
4430 return true;
4431}
4432
QUICHE teama6ef0a62019-03-07 20:34:33 -05004433size_t QuicFramer::EncryptPayload(EncryptionLevel level,
4434 QuicPacketNumber packet_number,
4435 const QuicPacket& packet,
4436 char* buffer,
4437 size_t buffer_len) {
4438 DCHECK(packet_number.IsInitialized());
dschinazi2c5386e2019-04-16 16:37:37 -07004439 if (encrypter_[level] == nullptr) {
4440 QUIC_BUG << ENDPOINT << "Attempted to encrypt without encrypter at level "
4441 << QuicUtils::EncryptionLevelToString(level);
4442 RaiseError(QUIC_ENCRYPTION_FAILURE);
4443 return 0;
4444 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004445
4446 QuicStringPiece associated_data =
4447 packet.AssociatedData(version_.transport_version);
4448 // Copy in the header, because the encrypter only populates the encrypted
4449 // plaintext content.
4450 const size_t ad_len = associated_data.length();
4451 memmove(buffer, associated_data.data(), ad_len);
4452 // Encrypt the plaintext into the buffer.
4453 size_t output_length = 0;
4454 if (!encrypter_[level]->EncryptPacket(
4455 packet_number.ToUint64(), associated_data,
4456 packet.Plaintext(version_.transport_version), buffer + ad_len,
4457 &output_length, buffer_len - ad_len)) {
4458 RaiseError(QUIC_ENCRYPTION_FAILURE);
4459 return 0;
4460 }
nharper55fa6132019-05-07 19:37:21 -07004461 if (version_.HasHeaderProtection() &&
4462 !ApplyHeaderProtection(level, buffer, ad_len + output_length, ad_len)) {
4463 QUIC_DLOG(ERROR) << "Applying header protection failed.";
4464 RaiseError(QUIC_ENCRYPTION_FAILURE);
4465 return 0;
4466 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004467
4468 return ad_len + output_length;
4469}
4470
4471size_t QuicFramer::GetCiphertextSize(EncryptionLevel level,
4472 size_t plaintext_size) const {
4473 return encrypter_[level]->GetCiphertextSize(plaintext_size);
4474}
4475
4476size_t QuicFramer::GetMaxPlaintextSize(size_t ciphertext_size) {
4477 // In order to keep the code simple, we don't have the current encryption
4478 // level to hand. Both the NullEncrypter and AES-GCM have a tag length of 12.
4479 size_t min_plaintext_size = ciphertext_size;
4480
QUICHE team6987b4a2019-03-15 16:23:04 -07004481 for (int i = ENCRYPTION_INITIAL; i < NUM_ENCRYPTION_LEVELS; i++) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05004482 if (encrypter_[i] != nullptr) {
4483 size_t size = encrypter_[i]->GetMaxPlaintextSize(ciphertext_size);
4484 if (size < min_plaintext_size) {
4485 min_plaintext_size = size;
4486 }
4487 }
4488 }
4489
4490 return min_plaintext_size;
4491}
4492
4493bool QuicFramer::DecryptPayload(QuicStringPiece encrypted,
4494 QuicStringPiece associated_data,
4495 const QuicPacketHeader& header,
4496 char* decrypted_buffer,
4497 size_t buffer_length,
QUICHE team10b22a12019-03-21 15:31:42 -07004498 size_t* decrypted_length,
4499 EncryptionLevel* decrypted_level) {
nharper855d2172019-05-02 16:17:46 -07004500 if (!EncryptionLevelIsValid(decrypter_level_)) {
4501 QUIC_BUG << "Attempted to decrypt with bad decrypter_level_";
4502 return false;
4503 }
zhongyi546cc452019-04-12 15:27:49 -07004504 EncryptionLevel level = decrypter_level_;
4505 QuicDecrypter* decrypter = decrypter_[level].get();
QUICHE team76086e42019-03-25 15:12:29 -07004506 QuicDecrypter* alternative_decrypter = nullptr;
zhongyi546cc452019-04-12 15:27:49 -07004507 if (version().KnowsWhichDecrypterToUse()) {
nharper855d2172019-05-02 16:17:46 -07004508 if (header.form == GOOGLE_QUIC_PACKET) {
4509 QUIC_BUG << "Attempted to decrypt GOOGLE_QUIC_PACKET with a version that "
4510 "knows which decrypter to use";
4511 return false;
4512 }
zhongyi546cc452019-04-12 15:27:49 -07004513 level = GetEncryptionLevel(header);
nharper855d2172019-05-02 16:17:46 -07004514 if (!EncryptionLevelIsValid(level)) {
4515 QUIC_BUG << "Attempted to decrypt with bad level";
4516 return false;
4517 }
zhongyi546cc452019-04-12 15:27:49 -07004518 decrypter = decrypter_[level].get();
4519 if (decrypter == nullptr) {
4520 return false;
4521 }
4522 if (level == ENCRYPTION_ZERO_RTT &&
4523 perspective_ == Perspective::IS_CLIENT && header.nonce != nullptr) {
4524 decrypter->SetDiversificationNonce(*header.nonce);
4525 }
4526 } else if (alternative_decrypter_level_ != NUM_ENCRYPTION_LEVELS) {
nharper855d2172019-05-02 16:17:46 -07004527 if (!EncryptionLevelIsValid(alternative_decrypter_level_)) {
4528 QUIC_BUG << "Attempted to decrypt with bad alternative_decrypter_level_";
4529 return false;
4530 }
QUICHE team76086e42019-03-25 15:12:29 -07004531 alternative_decrypter = decrypter_[alternative_decrypter_level_].get();
4532 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004533
nharper855d2172019-05-02 16:17:46 -07004534 if (decrypter == nullptr) {
ianswettf919fb22019-05-13 06:42:11 -07004535 QUIC_BUG << "Attempting to decrypt without decrypter, encryption level:"
4536 << level << " version:" << version();
nharper855d2172019-05-02 16:17:46 -07004537 return false;
4538 }
zhongyi546cc452019-04-12 15:27:49 -07004539
4540 bool success = decrypter->DecryptPacket(
QUICHE teama6ef0a62019-03-07 20:34:33 -05004541 header.packet_number.ToUint64(), associated_data, encrypted,
4542 decrypted_buffer, decrypted_length, buffer_length);
4543 if (success) {
zhongyi546cc452019-04-12 15:27:49 -07004544 visitor_->OnDecryptedPacket(level);
4545 *decrypted_level = level;
QUICHE team76086e42019-03-25 15:12:29 -07004546 } else if (alternative_decrypter != nullptr) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05004547 if (header.nonce != nullptr) {
4548 DCHECK_EQ(perspective_, Perspective::IS_CLIENT);
QUICHE team76086e42019-03-25 15:12:29 -07004549 alternative_decrypter->SetDiversificationNonce(*header.nonce);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004550 }
4551 bool try_alternative_decryption = true;
4552 if (alternative_decrypter_level_ == ENCRYPTION_ZERO_RTT) {
4553 if (perspective_ == Perspective::IS_CLIENT) {
4554 if (header.nonce == nullptr) {
4555 // Can not use INITIAL decryption without a diversification nonce.
4556 try_alternative_decryption = false;
4557 }
4558 } else {
4559 DCHECK(header.nonce == nullptr);
4560 }
4561 }
4562
4563 if (try_alternative_decryption) {
QUICHE team76086e42019-03-25 15:12:29 -07004564 success = alternative_decrypter->DecryptPacket(
QUICHE teama6ef0a62019-03-07 20:34:33 -05004565 header.packet_number.ToUint64(), associated_data, encrypted,
4566 decrypted_buffer, decrypted_length, buffer_length);
4567 }
4568 if (success) {
4569 visitor_->OnDecryptedPacket(alternative_decrypter_level_);
QUICHE team10b22a12019-03-21 15:31:42 -07004570 *decrypted_level = decrypter_level_;
QUICHE teama6ef0a62019-03-07 20:34:33 -05004571 if (alternative_decrypter_latch_) {
nharper855d2172019-05-02 16:17:46 -07004572 if (!EncryptionLevelIsValid(alternative_decrypter_level_)) {
4573 QUIC_BUG << "Attempted to latch alternate decrypter with bad "
4574 "alternative_decrypter_level_";
4575 return false;
4576 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004577 // Switch to the alternative decrypter and latch so that we cannot
4578 // switch back.
QUICHE teama6ef0a62019-03-07 20:34:33 -05004579 decrypter_level_ = alternative_decrypter_level_;
QUICHE team76086e42019-03-25 15:12:29 -07004580 alternative_decrypter_level_ = NUM_ENCRYPTION_LEVELS;
QUICHE teama6ef0a62019-03-07 20:34:33 -05004581 } else {
4582 // Switch the alternative decrypter so that we use it first next time.
QUICHE teama6ef0a62019-03-07 20:34:33 -05004583 EncryptionLevel level = alternative_decrypter_level_;
4584 alternative_decrypter_level_ = decrypter_level_;
4585 decrypter_level_ = level;
4586 }
4587 }
4588 }
4589
4590 if (!success) {
dschinazi965ce092019-05-23 06:29:01 -07004591 QUIC_DVLOG(1) << ENDPOINT << "DecryptPacket failed for: " << header;
QUICHE teama6ef0a62019-03-07 20:34:33 -05004592 return false;
4593 }
4594
4595 return true;
4596}
4597
4598size_t QuicFramer::GetIetfAckFrameSize(const QuicAckFrame& frame) {
4599 // Type byte, largest_acked, and delay_time are straight-forward.
4600 size_t ack_frame_size = kQuicFrameTypeSize;
4601 QuicPacketNumber largest_acked = LargestAcked(frame);
4602 ack_frame_size += QuicDataWriter::GetVarInt62Len(largest_acked.ToUint64());
4603 uint64_t ack_delay_time_us;
4604 ack_delay_time_us = frame.ack_delay_time.ToMicroseconds();
fkastenholz4dc4ba32019-07-30 09:55:25 -07004605 ack_delay_time_us = ack_delay_time_us >> local_ack_delay_exponent_;
QUICHE teama6ef0a62019-03-07 20:34:33 -05004606 ack_frame_size += QuicDataWriter::GetVarInt62Len(ack_delay_time_us);
4607
4608 // If |ecn_counters_populated| is true and any of the ecn counters is non-0
4609 // then the ecn counters are included...
4610 if (frame.ecn_counters_populated &&
4611 (frame.ect_0_count || frame.ect_1_count || frame.ecn_ce_count)) {
4612 ack_frame_size += QuicDataWriter::GetVarInt62Len(frame.ect_0_count);
4613 ack_frame_size += QuicDataWriter::GetVarInt62Len(frame.ect_1_count);
4614 ack_frame_size += QuicDataWriter::GetVarInt62Len(frame.ecn_ce_count);
4615 }
4616
4617 // The rest (ack_block_count, first_ack_block, and additional ack
4618 // blocks, if any) depends:
4619 uint64_t ack_block_count = frame.packets.NumIntervals();
4620 if (ack_block_count == 0) {
4621 // If the QuicAckFrame has no Intervals, then it is interpreted
4622 // as an ack of a single packet at QuicAckFrame.largest_acked.
4623 // The resulting ack will consist of only the frame's
4624 // largest_ack & first_ack_block fields. The first ack block will be 0
4625 // (indicating a single packet) and the ack block_count will be 0.
4626 // Each 0 takes 1 byte when VarInt62 encoded.
4627 ack_frame_size += 2;
4628 return ack_frame_size;
4629 }
4630
4631 auto itr = frame.packets.rbegin();
4632 QuicPacketNumber ack_block_largest = largest_acked;
4633 QuicPacketNumber ack_block_smallest;
4634 if ((itr->max() - 1) == largest_acked) {
4635 // If largest_acked + 1 is equal to the Max() of the first Interval
4636 // in the QuicAckFrame then the first Interval is the first ack block of the
4637 // frame; remaining Intervals are additional ack blocks. The QuicAckFrame's
4638 // first Interval is encoded in the frame's largest_acked/first_ack_block,
4639 // the remaining Intervals are encoded in additional ack blocks in the
4640 // frame, and the packet's ack_block_count is the number of QuicAckFrame
4641 // Intervals - 1.
4642 ack_block_smallest = itr->min();
4643 itr++;
4644 ack_block_count--;
4645 } else {
4646 // If QuicAckFrame.largest_acked is NOT equal to the Max() of
4647 // the first Interval then it is interpreted as acking a single
4648 // packet at QuicAckFrame.largest_acked, with additional
4649 // Intervals indicating additional ack blocks. The encoding is
4650 // a) The packet's largest_acked is the QuicAckFrame's largest
4651 // acked,
4652 // b) the first ack block size is 0,
4653 // c) The packet's ack_block_count is the number of QuicAckFrame
4654 // Intervals, and
4655 // d) The QuicAckFrame Intervals are encoded in additional ack
4656 // blocks in the packet.
4657 ack_block_smallest = largest_acked;
4658 }
4659 size_t ack_block_count_size = QuicDataWriter::GetVarInt62Len(ack_block_count);
4660 ack_frame_size += ack_block_count_size;
4661
4662 uint64_t first_ack_block = ack_block_largest - ack_block_smallest;
4663 size_t first_ack_block_size = QuicDataWriter::GetVarInt62Len(first_ack_block);
4664 ack_frame_size += first_ack_block_size;
4665
4666 // Account for the remaining Intervals, if any.
4667 while (ack_block_count != 0) {
4668 uint64_t gap_size = ack_block_smallest - itr->max();
4669 // Decrement per the protocol specification
4670 size_t size_of_gap_size = QuicDataWriter::GetVarInt62Len(gap_size - 1);
4671 ack_frame_size += size_of_gap_size;
4672
4673 uint64_t block_size = itr->max() - itr->min();
4674 // Decrement per the protocol specification
4675 size_t size_of_block_size = QuicDataWriter::GetVarInt62Len(block_size - 1);
4676 ack_frame_size += size_of_block_size;
4677
4678 ack_block_smallest = itr->min();
4679 itr++;
4680 ack_block_count--;
4681 }
4682
4683 return ack_frame_size;
4684}
4685
4686size_t QuicFramer::GetAckFrameSize(
4687 const QuicAckFrame& ack,
dschinazi17d42422019-06-18 16:35:07 -07004688 QuicPacketNumberLength /*packet_number_length*/) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05004689 DCHECK(!ack.packets.Empty());
4690 size_t ack_size = 0;
4691
fkastenholz305e1732019-06-18 05:01:22 -07004692 if (VersionHasIetfQuicFrames(version_.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05004693 return GetIetfAckFrameSize(ack);
4694 }
4695 AckFrameInfo ack_info = GetAckFrameInfo(ack);
4696 QuicPacketNumberLength largest_acked_length =
4697 GetMinPacketNumberLength(version_.transport_version, LargestAcked(ack));
4698 QuicPacketNumberLength ack_block_length = GetMinPacketNumberLength(
4699 version_.transport_version, QuicPacketNumber(ack_info.max_block_length));
4700
4701 ack_size =
4702 GetMinAckFrameSize(version_.transport_version, largest_acked_length);
4703 // First ack block length.
4704 ack_size += ack_block_length;
4705 if (ack_info.num_ack_blocks != 0) {
4706 ack_size += kNumberOfAckBlocksSize;
4707 ack_size += std::min(ack_info.num_ack_blocks, kMaxAckBlocks) *
4708 (ack_block_length + PACKET_1BYTE_PACKET_NUMBER);
4709 }
4710
4711 // Include timestamps.
4712 if (process_timestamps_) {
4713 ack_size += GetAckFrameTimeStampSize(ack);
4714 }
4715
4716 return ack_size;
4717}
4718
4719size_t QuicFramer::GetAckFrameTimeStampSize(const QuicAckFrame& ack) {
4720 if (ack.received_packet_times.empty()) {
4721 return 0;
4722 }
4723
4724 return kQuicNumTimestampsLength + kQuicFirstTimestampLength +
4725 (kQuicTimestampLength + kQuicTimestampPacketNumberGapLength) *
4726 (ack.received_packet_times.size() - 1);
4727}
4728
4729size_t QuicFramer::ComputeFrameLength(
4730 const QuicFrame& frame,
4731 bool last_frame_in_packet,
4732 QuicPacketNumberLength packet_number_length) {
4733 switch (frame.type) {
4734 case STREAM_FRAME:
4735 return GetMinStreamFrameSize(
4736 version_.transport_version, frame.stream_frame.stream_id,
4737 frame.stream_frame.offset, last_frame_in_packet,
4738 frame.stream_frame.data_length) +
4739 frame.stream_frame.data_length;
4740 case CRYPTO_FRAME:
4741 return GetMinCryptoFrameSize(frame.crypto_frame->offset,
4742 frame.crypto_frame->data_length) +
4743 frame.crypto_frame->data_length;
4744 case ACK_FRAME: {
4745 return GetAckFrameSize(*frame.ack_frame, packet_number_length);
4746 }
4747 case STOP_WAITING_FRAME:
4748 return GetStopWaitingFrameSize(version_.transport_version,
4749 packet_number_length);
4750 case MTU_DISCOVERY_FRAME:
4751 // MTU discovery frames are serialized as ping frames.
4752 return kQuicFrameTypeSize;
4753 case MESSAGE_FRAME:
4754 return GetMessageFrameSize(version_.transport_version,
4755 last_frame_in_packet,
4756 frame.message_frame->message_length);
4757 case PADDING_FRAME:
4758 DCHECK(false);
4759 return 0;
4760 default:
4761 return GetRetransmittableControlFrameSize(version_.transport_version,
4762 frame);
4763 }
4764}
4765
4766bool QuicFramer::AppendTypeByte(const QuicFrame& frame,
4767 bool last_frame_in_packet,
4768 QuicDataWriter* writer) {
fkastenholz305e1732019-06-18 05:01:22 -07004769 if (VersionHasIetfQuicFrames(version_.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05004770 return AppendIetfTypeByte(frame, last_frame_in_packet, writer);
4771 }
4772 uint8_t type_byte = 0;
4773 switch (frame.type) {
4774 case STREAM_FRAME:
4775 type_byte =
4776 GetStreamFrameTypeByte(frame.stream_frame, last_frame_in_packet);
4777 break;
4778 case ACK_FRAME:
4779 return true;
4780 case MTU_DISCOVERY_FRAME:
4781 type_byte = static_cast<uint8_t>(PING_FRAME);
4782 break;
QUICHE teama6ef0a62019-03-07 20:34:33 -05004783 case NEW_CONNECTION_ID_FRAME:
4784 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -07004785 "Attempt to append NEW_CONNECTION_ID frame and not in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05004786 return RaiseError(QUIC_INTERNAL_ERROR);
4787 case RETIRE_CONNECTION_ID_FRAME:
4788 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -07004789 "Attempt to append RETIRE_CONNECTION_ID frame and not in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05004790 return RaiseError(QUIC_INTERNAL_ERROR);
4791 case NEW_TOKEN_FRAME:
4792 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -07004793 "Attempt to append NEW_TOKEN frame and not in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05004794 return RaiseError(QUIC_INTERNAL_ERROR);
fkastenholz3c4eabf2019-04-22 07:49:59 -07004795 case MAX_STREAMS_FRAME:
QUICHE teama6ef0a62019-03-07 20:34:33 -05004796 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -07004797 "Attempt to append MAX_STREAMS frame and not in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05004798 return RaiseError(QUIC_INTERNAL_ERROR);
fkastenholz3c4eabf2019-04-22 07:49:59 -07004799 case STREAMS_BLOCKED_FRAME:
QUICHE teama6ef0a62019-03-07 20:34:33 -05004800 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -07004801 "Attempt to append STREAMS_BLOCKED frame and not in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05004802 return RaiseError(QUIC_INTERNAL_ERROR);
4803 case PATH_RESPONSE_FRAME:
4804 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -07004805 "Attempt to append PATH_RESPONSE frame and not in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05004806 return RaiseError(QUIC_INTERNAL_ERROR);
4807 case PATH_CHALLENGE_FRAME:
4808 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -07004809 "Attempt to append PATH_CHALLENGE frame and not in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05004810 return RaiseError(QUIC_INTERNAL_ERROR);
4811 case STOP_SENDING_FRAME:
4812 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -07004813 "Attempt to append STOP_SENDING frame and not in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05004814 return RaiseError(QUIC_INTERNAL_ERROR);
4815 case MESSAGE_FRAME:
4816 return true;
4817
4818 default:
4819 type_byte = static_cast<uint8_t>(frame.type);
4820 break;
4821 }
4822
4823 return writer->WriteUInt8(type_byte);
4824}
4825
4826bool QuicFramer::AppendIetfTypeByte(const QuicFrame& frame,
4827 bool last_frame_in_packet,
4828 QuicDataWriter* writer) {
4829 uint8_t type_byte = 0;
4830 switch (frame.type) {
4831 case PADDING_FRAME:
4832 type_byte = IETF_PADDING;
4833 break;
4834 case RST_STREAM_FRAME:
4835 type_byte = IETF_RST_STREAM;
4836 break;
4837 case CONNECTION_CLOSE_FRAME:
fkastenholz72f509b2019-04-10 09:17:49 -07004838 switch (frame.connection_close_frame->close_type) {
4839 case IETF_QUIC_APPLICATION_CONNECTION_CLOSE:
4840 type_byte = IETF_APPLICATION_CLOSE;
4841 break;
4842 case IETF_QUIC_TRANSPORT_CONNECTION_CLOSE:
4843 type_byte = IETF_CONNECTION_CLOSE;
4844 break;
4845 default:
4846 set_detailed_error("Invalid QuicConnectionCloseFrame type.");
4847 return RaiseError(QUIC_INTERNAL_ERROR);
4848 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004849 break;
4850 case GOAWAY_FRAME:
4851 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -07004852 "Attempt to create non-IETF QUIC GOAWAY frame in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05004853 return RaiseError(QUIC_INTERNAL_ERROR);
4854 case WINDOW_UPDATE_FRAME:
4855 // Depending on whether there is a stream ID or not, will be either a
4856 // MAX_STREAM_DATA frame or a MAX_DATA frame.
4857 if (frame.window_update_frame->stream_id ==
4858 QuicUtils::GetInvalidStreamId(transport_version())) {
4859 type_byte = IETF_MAX_DATA;
4860 } else {
4861 type_byte = IETF_MAX_STREAM_DATA;
4862 }
4863 break;
4864 case BLOCKED_FRAME:
4865 if (frame.blocked_frame->stream_id ==
4866 QuicUtils::GetInvalidStreamId(transport_version())) {
4867 type_byte = IETF_BLOCKED;
4868 } else {
4869 type_byte = IETF_STREAM_BLOCKED;
4870 }
4871 break;
4872 case STOP_WAITING_FRAME:
4873 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -07004874 "Attempt to append type byte of STOP WAITING frame in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05004875 return RaiseError(QUIC_INTERNAL_ERROR);
4876 case PING_FRAME:
4877 type_byte = IETF_PING;
4878 break;
4879 case STREAM_FRAME:
4880 type_byte =
4881 GetStreamFrameTypeByte(frame.stream_frame, last_frame_in_packet);
4882 break;
4883 case ACK_FRAME:
4884 // Do nothing here, AppendIetfAckFrameAndTypeByte() will put the type byte
4885 // in the buffer.
4886 return true;
4887 case MTU_DISCOVERY_FRAME:
4888 // The path MTU discovery frame is encoded as a PING frame on the wire.
4889 type_byte = IETF_PING;
4890 break;
QUICHE teama6ef0a62019-03-07 20:34:33 -05004891 case NEW_CONNECTION_ID_FRAME:
4892 type_byte = IETF_NEW_CONNECTION_ID;
4893 break;
4894 case RETIRE_CONNECTION_ID_FRAME:
4895 type_byte = IETF_RETIRE_CONNECTION_ID;
4896 break;
4897 case NEW_TOKEN_FRAME:
4898 type_byte = IETF_NEW_TOKEN;
4899 break;
fkastenholz3c4eabf2019-04-22 07:49:59 -07004900 case MAX_STREAMS_FRAME:
4901 if (frame.max_streams_frame.unidirectional) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05004902 type_byte = IETF_MAX_STREAMS_UNIDIRECTIONAL;
fkastenholz3c4eabf2019-04-22 07:49:59 -07004903 } else {
4904 type_byte = IETF_MAX_STREAMS_BIDIRECTIONAL;
QUICHE teama6ef0a62019-03-07 20:34:33 -05004905 }
4906 break;
fkastenholz3c4eabf2019-04-22 07:49:59 -07004907 case STREAMS_BLOCKED_FRAME:
4908 if (frame.streams_blocked_frame.unidirectional) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05004909 type_byte = IETF_STREAMS_BLOCKED_UNIDIRECTIONAL;
fkastenholz3c4eabf2019-04-22 07:49:59 -07004910 } else {
4911 type_byte = IETF_STREAMS_BLOCKED_BIDIRECTIONAL;
QUICHE teama6ef0a62019-03-07 20:34:33 -05004912 }
4913 break;
4914 case PATH_RESPONSE_FRAME:
4915 type_byte = IETF_PATH_RESPONSE;
4916 break;
4917 case PATH_CHALLENGE_FRAME:
4918 type_byte = IETF_PATH_CHALLENGE;
4919 break;
4920 case STOP_SENDING_FRAME:
4921 type_byte = IETF_STOP_SENDING;
4922 break;
4923 case MESSAGE_FRAME:
4924 return true;
4925 case CRYPTO_FRAME:
4926 type_byte = IETF_CRYPTO;
4927 break;
4928 default:
4929 QUIC_BUG << "Attempt to generate a frame type for an unsupported value: "
4930 << frame.type;
4931 return false;
4932 }
4933 return writer->WriteUInt8(type_byte);
4934}
4935
4936// static
4937bool QuicFramer::AppendPacketNumber(QuicPacketNumberLength packet_number_length,
4938 QuicPacketNumber packet_number,
4939 QuicDataWriter* writer) {
4940 DCHECK(packet_number.IsInitialized());
4941 if (!IsValidPacketNumberLength(packet_number_length)) {
4942 QUIC_BUG << "Invalid packet_number_length: " << packet_number_length;
4943 return false;
4944 }
4945 return writer->WriteBytesToUInt64(packet_number_length,
4946 packet_number.ToUint64());
4947}
4948
4949// static
4950bool QuicFramer::AppendStreamId(size_t stream_id_length,
4951 QuicStreamId stream_id,
4952 QuicDataWriter* writer) {
4953 if (stream_id_length == 0 || stream_id_length > 4) {
4954 QUIC_BUG << "Invalid stream_id_length: " << stream_id_length;
4955 return false;
4956 }
4957 return writer->WriteBytesToUInt64(stream_id_length, stream_id);
4958}
4959
4960// static
4961bool QuicFramer::AppendStreamOffset(size_t offset_length,
4962 QuicStreamOffset offset,
4963 QuicDataWriter* writer) {
4964 if (offset_length == 1 || offset_length > 8) {
4965 QUIC_BUG << "Invalid stream_offset_length: " << offset_length;
4966 return false;
4967 }
4968
4969 return writer->WriteBytesToUInt64(offset_length, offset);
4970}
4971
4972// static
4973bool QuicFramer::AppendAckBlock(uint8_t gap,
4974 QuicPacketNumberLength length_length,
4975 uint64_t length,
4976 QuicDataWriter* writer) {
4977 if (length == 0) {
4978 if (!IsValidPacketNumberLength(length_length)) {
4979 QUIC_BUG << "Invalid packet_number_length: " << length_length;
4980 return false;
4981 }
4982 return writer->WriteUInt8(gap) &&
4983 writer->WriteBytesToUInt64(length_length, length);
4984 }
4985 return writer->WriteUInt8(gap) &&
4986 AppendPacketNumber(length_length, QuicPacketNumber(length), writer);
4987}
4988
4989bool QuicFramer::AppendStreamFrame(const QuicStreamFrame& frame,
4990 bool no_stream_frame_length,
4991 QuicDataWriter* writer) {
fkastenholz305e1732019-06-18 05:01:22 -07004992 if (VersionHasIetfQuicFrames(version_.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05004993 return AppendIetfStreamFrame(frame, no_stream_frame_length, writer);
4994 }
4995 if (!AppendStreamId(GetStreamIdSize(frame.stream_id), frame.stream_id,
4996 writer)) {
4997 QUIC_BUG << "Writing stream id size failed.";
4998 return false;
4999 }
5000 if (!AppendStreamOffset(
5001 GetStreamOffsetSize(version_.transport_version, frame.offset),
5002 frame.offset, writer)) {
5003 QUIC_BUG << "Writing offset size failed.";
5004 return false;
5005 }
5006 if (!no_stream_frame_length) {
dschinazi878cfb52019-06-17 17:12:58 -07005007 static_assert(
wubeff50282019-06-19 09:04:30 -07005008 std::numeric_limits<decltype(frame.data_length)>::max() <=
dschinazi878cfb52019-06-17 17:12:58 -07005009 std::numeric_limits<uint16_t>::max(),
5010 "If frame.data_length can hold more than a uint16_t than we need to "
5011 "check that frame.data_length <= std::numeric_limits<uint16_t>::max()");
5012 if (!writer->WriteUInt16(static_cast<uint16_t>(frame.data_length))) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005013 QUIC_BUG << "Writing stream frame length failed";
5014 return false;
5015 }
5016 }
5017
5018 if (data_producer_ != nullptr) {
5019 DCHECK_EQ(nullptr, frame.data_buffer);
5020 if (frame.data_length == 0) {
5021 return true;
5022 }
5023 if (data_producer_->WriteStreamData(frame.stream_id, frame.offset,
5024 frame.data_length,
5025 writer) != WRITE_SUCCESS) {
5026 QUIC_BUG << "Writing frame data failed.";
5027 return false;
5028 }
5029 return true;
5030 }
5031
5032 if (!writer->WriteBytes(frame.data_buffer, frame.data_length)) {
5033 QUIC_BUG << "Writing frame data failed.";
5034 return false;
5035 }
5036 return true;
5037}
5038
QUICHE teama6ef0a62019-03-07 20:34:33 -05005039bool QuicFramer::AppendNewTokenFrame(const QuicNewTokenFrame& frame,
5040 QuicDataWriter* writer) {
5041 if (!writer->WriteVarInt62(static_cast<uint64_t>(frame.token.length()))) {
5042 set_detailed_error("Writing token length failed.");
5043 return false;
5044 }
5045 if (!writer->WriteBytes(frame.token.data(), frame.token.length())) {
5046 set_detailed_error("Writing token buffer failed.");
5047 return false;
5048 }
5049 return true;
5050}
5051
5052bool QuicFramer::ProcessNewTokenFrame(QuicDataReader* reader,
5053 QuicNewTokenFrame* frame) {
5054 uint64_t length;
5055 if (!reader->ReadVarInt62(&length)) {
5056 set_detailed_error("Unable to read new token length.");
5057 return false;
5058 }
5059 if (length > kMaxNewTokenTokenLength) {
5060 set_detailed_error("Token length larger than maximum.");
5061 return false;
5062 }
5063
5064 // TODO(ianswett): Don't use QuicStringPiece as an intermediary.
5065 QuicStringPiece data;
5066 if (!reader->ReadStringPiece(&data, length)) {
5067 set_detailed_error("Unable to read new token data.");
5068 return false;
5069 }
vasilvvc48c8712019-03-11 13:38:16 -07005070 frame->token = std::string(data);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005071 return true;
5072}
5073
5074// Add a new ietf-format stream frame.
5075// Bits controlling whether there is a frame-length and frame-offset
5076// are in the QuicStreamFrame.
5077bool QuicFramer::AppendIetfStreamFrame(const QuicStreamFrame& frame,
5078 bool last_frame_in_packet,
5079 QuicDataWriter* writer) {
5080 if (!writer->WriteVarInt62(static_cast<uint64_t>(frame.stream_id))) {
5081 set_detailed_error("Writing stream id failed.");
5082 return false;
5083 }
5084
5085 if (frame.offset != 0) {
5086 if (!writer->WriteVarInt62(static_cast<uint64_t>(frame.offset))) {
5087 set_detailed_error("Writing data offset failed.");
5088 return false;
5089 }
5090 }
5091
5092 if (!last_frame_in_packet) {
5093 if (!writer->WriteVarInt62(frame.data_length)) {
5094 set_detailed_error("Writing data length failed.");
5095 return false;
5096 }
5097 }
5098
5099 if (frame.data_length == 0) {
5100 return true;
5101 }
5102 if (data_producer_ == nullptr) {
5103 if (!writer->WriteBytes(frame.data_buffer, frame.data_length)) {
5104 set_detailed_error("Writing frame data failed.");
5105 return false;
5106 }
5107 } else {
5108 DCHECK_EQ(nullptr, frame.data_buffer);
5109
5110 if (data_producer_->WriteStreamData(frame.stream_id, frame.offset,
5111 frame.data_length,
5112 writer) != WRITE_SUCCESS) {
5113 set_detailed_error("Writing frame data failed.");
5114 return false;
5115 }
5116 }
5117 return true;
5118}
5119
5120bool QuicFramer::AppendCryptoFrame(const QuicCryptoFrame& frame,
5121 QuicDataWriter* writer) {
5122 if (!writer->WriteVarInt62(static_cast<uint64_t>(frame.offset))) {
5123 set_detailed_error("Writing data offset failed.");
5124 return false;
5125 }
5126 if (!writer->WriteVarInt62(static_cast<uint64_t>(frame.data_length))) {
5127 set_detailed_error("Writing data length failed.");
5128 return false;
5129 }
5130 if (data_producer_ == nullptr) {
5131 if (frame.data_buffer == nullptr ||
5132 !writer->WriteBytes(frame.data_buffer, frame.data_length)) {
5133 set_detailed_error("Writing frame data failed.");
5134 return false;
5135 }
5136 } else {
5137 DCHECK_EQ(nullptr, frame.data_buffer);
5138 if (!data_producer_->WriteCryptoData(frame.level, frame.offset,
5139 frame.data_length, writer)) {
5140 return false;
5141 }
5142 }
5143 return true;
5144}
5145
5146void QuicFramer::set_version(const ParsedQuicVersion version) {
5147 DCHECK(IsSupportedVersion(version)) << ParsedQuicVersionToString(version);
5148 version_ = version;
5149}
5150
5151bool QuicFramer::AppendAckFrameAndTypeByte(const QuicAckFrame& frame,
5152 QuicDataWriter* writer) {
fkastenholz305e1732019-06-18 05:01:22 -07005153 if (VersionHasIetfQuicFrames(transport_version())) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005154 return AppendIetfAckFrameAndTypeByte(frame, writer);
5155 }
5156
5157 const AckFrameInfo new_ack_info = GetAckFrameInfo(frame);
5158 QuicPacketNumber largest_acked = LargestAcked(frame);
5159 QuicPacketNumberLength largest_acked_length =
5160 GetMinPacketNumberLength(version_.transport_version, largest_acked);
5161 QuicPacketNumberLength ack_block_length =
5162 GetMinPacketNumberLength(version_.transport_version,
5163 QuicPacketNumber(new_ack_info.max_block_length));
5164 // Calculate available bytes for timestamps and ack blocks.
5165 int32_t available_timestamp_and_ack_block_bytes =
5166 writer->capacity() - writer->length() - ack_block_length -
5167 GetMinAckFrameSize(version_.transport_version, largest_acked_length) -
5168 (new_ack_info.num_ack_blocks != 0 ? kNumberOfAckBlocksSize : 0);
5169 DCHECK_LE(0, available_timestamp_and_ack_block_bytes);
5170
5171 // Write out the type byte by setting the low order bits and doing shifts
5172 // to make room for the next bit flags to be set.
5173 // Whether there are multiple ack blocks.
5174 uint8_t type_byte = 0;
5175 SetBit(&type_byte, new_ack_info.num_ack_blocks != 0,
5176 kQuicHasMultipleAckBlocksOffset);
5177
5178 SetBits(&type_byte, GetPacketNumberFlags(largest_acked_length),
5179 kQuicSequenceNumberLengthNumBits, kLargestAckedOffset);
5180
5181 SetBits(&type_byte, GetPacketNumberFlags(ack_block_length),
5182 kQuicSequenceNumberLengthNumBits, kActBlockLengthOffset);
5183
5184 type_byte |= kQuicFrameTypeAckMask;
5185
5186 if (!writer->WriteUInt8(type_byte)) {
5187 return false;
5188 }
5189
5190 size_t max_num_ack_blocks = available_timestamp_and_ack_block_bytes /
5191 (ack_block_length + PACKET_1BYTE_PACKET_NUMBER);
5192
5193 // Number of ack blocks.
5194 size_t num_ack_blocks =
5195 std::min(new_ack_info.num_ack_blocks, max_num_ack_blocks);
5196 if (num_ack_blocks > std::numeric_limits<uint8_t>::max()) {
5197 num_ack_blocks = std::numeric_limits<uint8_t>::max();
5198 }
5199
5200 // Largest acked.
5201 if (!AppendPacketNumber(largest_acked_length, largest_acked, writer)) {
5202 return false;
5203 }
5204
5205 // Largest acked delta time.
5206 uint64_t ack_delay_time_us = kUFloat16MaxValue;
5207 if (!frame.ack_delay_time.IsInfinite()) {
5208 DCHECK_LE(0u, frame.ack_delay_time.ToMicroseconds());
5209 ack_delay_time_us = frame.ack_delay_time.ToMicroseconds();
5210 }
5211 if (!writer->WriteUFloat16(ack_delay_time_us)) {
5212 return false;
5213 }
5214
5215 if (num_ack_blocks > 0) {
5216 if (!writer->WriteBytes(&num_ack_blocks, 1)) {
5217 return false;
5218 }
5219 }
5220
5221 // First ack block length.
5222 if (!AppendPacketNumber(ack_block_length,
5223 QuicPacketNumber(new_ack_info.first_block_length),
5224 writer)) {
5225 return false;
5226 }
5227
5228 // Ack blocks.
5229 if (num_ack_blocks > 0) {
5230 size_t num_ack_blocks_written = 0;
5231 // Append, in descending order from the largest ACKed packet, a series of
5232 // ACK blocks that represents the successfully acknoweldged packets. Each
5233 // appended gap/block length represents a descending delta from the previous
5234 // block. i.e.:
5235 // |--- length ---|--- gap ---|--- length ---|--- gap ---|--- largest ---|
5236 // For gaps larger than can be represented by a single encoded gap, a 0
5237 // length gap of the maximum is used, i.e.:
5238 // |--- length ---|--- gap ---|- 0 -|--- gap ---|--- largest ---|
5239 auto itr = frame.packets.rbegin();
5240 QuicPacketNumber previous_start = itr->min();
5241 ++itr;
5242
5243 for (;
5244 itr != frame.packets.rend() && num_ack_blocks_written < num_ack_blocks;
5245 previous_start = itr->min(), ++itr) {
5246 const auto& interval = *itr;
5247 const uint64_t total_gap = previous_start - interval.max();
5248 const size_t num_encoded_gaps =
5249 (total_gap + std::numeric_limits<uint8_t>::max() - 1) /
5250 std::numeric_limits<uint8_t>::max();
QUICHE teama6ef0a62019-03-07 20:34:33 -05005251
5252 // Append empty ACK blocks because the gap is longer than a single gap.
5253 for (size_t i = 1;
5254 i < num_encoded_gaps && num_ack_blocks_written < num_ack_blocks;
5255 ++i) {
5256 if (!AppendAckBlock(std::numeric_limits<uint8_t>::max(),
5257 ack_block_length, 0, writer)) {
5258 return false;
5259 }
5260 ++num_ack_blocks_written;
5261 }
5262 if (num_ack_blocks_written >= num_ack_blocks) {
5263 if (QUIC_PREDICT_FALSE(num_ack_blocks_written != num_ack_blocks)) {
5264 QUIC_BUG << "Wrote " << num_ack_blocks_written
5265 << ", expected to write " << num_ack_blocks;
5266 }
5267 break;
5268 }
5269
5270 const uint8_t last_gap =
5271 total_gap -
5272 (num_encoded_gaps - 1) * std::numeric_limits<uint8_t>::max();
5273 // Append the final ACK block with a non-empty size.
5274 if (!AppendAckBlock(last_gap, ack_block_length,
5275 PacketNumberIntervalLength(interval), writer)) {
5276 return false;
5277 }
5278 ++num_ack_blocks_written;
5279 }
5280 DCHECK_EQ(num_ack_blocks, num_ack_blocks_written);
5281 }
5282 // Timestamps.
5283 // If we don't process timestamps or if we don't have enough available space
5284 // to append all the timestamps, don't append any of them.
5285 if (process_timestamps_ && writer->capacity() - writer->length() >=
5286 GetAckFrameTimeStampSize(frame)) {
5287 if (!AppendTimestampsToAckFrame(frame, writer)) {
5288 return false;
5289 }
5290 } else {
5291 uint8_t num_received_packets = 0;
5292 if (!writer->WriteBytes(&num_received_packets, 1)) {
5293 return false;
5294 }
5295 }
5296
5297 return true;
5298}
5299
5300bool QuicFramer::AppendTimestampsToAckFrame(const QuicAckFrame& frame,
5301 QuicDataWriter* writer) {
5302 DCHECK_GE(std::numeric_limits<uint8_t>::max(),
5303 frame.received_packet_times.size());
5304 // num_received_packets is only 1 byte.
5305 if (frame.received_packet_times.size() >
5306 std::numeric_limits<uint8_t>::max()) {
5307 return false;
5308 }
5309
5310 uint8_t num_received_packets = frame.received_packet_times.size();
5311 if (!writer->WriteBytes(&num_received_packets, 1)) {
5312 return false;
5313 }
5314 if (num_received_packets == 0) {
5315 return true;
5316 }
5317
5318 auto it = frame.received_packet_times.begin();
5319 QuicPacketNumber packet_number = it->first;
5320 uint64_t delta_from_largest_observed = LargestAcked(frame) - packet_number;
5321
5322 DCHECK_GE(std::numeric_limits<uint8_t>::max(), delta_from_largest_observed);
5323 if (delta_from_largest_observed > std::numeric_limits<uint8_t>::max()) {
5324 return false;
5325 }
5326
5327 if (!writer->WriteUInt8(delta_from_largest_observed)) {
5328 return false;
5329 }
5330
5331 // Use the lowest 4 bytes of the time delta from the creation_time_.
5332 const uint64_t time_epoch_delta_us = UINT64_C(1) << 32;
5333 uint32_t time_delta_us =
5334 static_cast<uint32_t>((it->second - creation_time_).ToMicroseconds() &
5335 (time_epoch_delta_us - 1));
5336 if (!writer->WriteUInt32(time_delta_us)) {
5337 return false;
5338 }
5339
5340 QuicTime prev_time = it->second;
5341
5342 for (++it; it != frame.received_packet_times.end(); ++it) {
5343 packet_number = it->first;
5344 delta_from_largest_observed = LargestAcked(frame) - packet_number;
5345
5346 if (delta_from_largest_observed > std::numeric_limits<uint8_t>::max()) {
5347 return false;
5348 }
5349
5350 if (!writer->WriteUInt8(delta_from_largest_observed)) {
5351 return false;
5352 }
5353
5354 uint64_t frame_time_delta_us = (it->second - prev_time).ToMicroseconds();
5355 prev_time = it->second;
5356 if (!writer->WriteUFloat16(frame_time_delta_us)) {
5357 return false;
5358 }
5359 }
5360 return true;
5361}
5362
5363bool QuicFramer::AppendStopWaitingFrame(const QuicPacketHeader& header,
5364 const QuicStopWaitingFrame& frame,
5365 QuicDataWriter* writer) {
fayangd4291e42019-05-30 10:31:21 -07005366 DCHECK(!VersionHasIetfInvariantHeader(version_.transport_version));
QUICHE teama6ef0a62019-03-07 20:34:33 -05005367 DCHECK(frame.least_unacked.IsInitialized() &&
5368 header.packet_number >= frame.least_unacked);
5369 const uint64_t least_unacked_delta =
5370 header.packet_number - frame.least_unacked;
5371 const uint64_t length_shift = header.packet_number_length * 8;
5372
5373 if (least_unacked_delta >> length_shift > 0) {
5374 QUIC_BUG << "packet_number_length " << header.packet_number_length
5375 << " is too small for least_unacked_delta: " << least_unacked_delta
5376 << " packet_number:" << header.packet_number
5377 << " least_unacked:" << frame.least_unacked
5378 << " version:" << version_.transport_version;
5379 return false;
5380 }
5381 if (least_unacked_delta == 0) {
5382 return writer->WriteBytesToUInt64(header.packet_number_length,
5383 least_unacked_delta);
5384 }
5385 if (!AppendPacketNumber(header.packet_number_length,
5386 QuicPacketNumber(least_unacked_delta), writer)) {
5387 QUIC_BUG << " seq failed: " << header.packet_number_length;
5388 return false;
5389 }
5390
5391 return true;
5392}
5393
5394int QuicFramer::CalculateIetfAckBlockCount(const QuicAckFrame& frame,
dschinazi17d42422019-06-18 16:35:07 -07005395 QuicDataWriter* /*writer*/,
QUICHE teama6ef0a62019-03-07 20:34:33 -05005396 size_t available_space) {
5397 // Number of blocks requested in the frame
5398 uint64_t ack_block_count = frame.packets.NumIntervals();
5399
5400 auto itr = frame.packets.rbegin();
5401
5402 int actual_block_count = 1;
5403 uint64_t block_length = itr->max() - itr->min();
5404 size_t encoded_size = QuicDataWriter::GetVarInt62Len(block_length);
5405 if (encoded_size > available_space) {
5406 return 0;
5407 }
5408 available_space -= encoded_size;
5409 QuicPacketNumber previous_ack_end = itr->min();
5410 ack_block_count--;
5411
5412 while (ack_block_count) {
5413 // Each block is a gap followed by another ACK. Calculate each value,
5414 // determine the encoded lengths, and check against the available space.
5415 itr++;
5416 size_t gap = previous_ack_end - itr->max() - 1;
5417 encoded_size = QuicDataWriter::GetVarInt62Len(gap);
5418
5419 // Add the ACK block.
5420 block_length = itr->max() - itr->min();
5421 encoded_size += QuicDataWriter::GetVarInt62Len(block_length);
5422
5423 if (encoded_size > available_space) {
5424 // No room for this block, so what we've
5425 // done up to now is all that can be done.
5426 return actual_block_count;
5427 }
5428 available_space -= encoded_size;
5429 actual_block_count++;
5430 previous_ack_end = itr->min();
5431 ack_block_count--;
5432 }
5433 // Ran through the whole thing! We can do all blocks.
5434 return actual_block_count;
5435}
5436
5437bool QuicFramer::AppendIetfAckFrameAndTypeByte(const QuicAckFrame& frame,
5438 QuicDataWriter* writer) {
5439 // Assume frame is an IETF_ACK frame. If |ecn_counters_populated| is true and
5440 // any of the ECN counters is non-0 then turn it into an IETF_ACK+ECN frame.
5441 uint8_t type = IETF_ACK;
5442 if (frame.ecn_counters_populated &&
5443 (frame.ect_0_count || frame.ect_1_count || frame.ecn_ce_count)) {
5444 type = IETF_ACK_ECN;
5445 }
5446
5447 if (!writer->WriteUInt8(type)) {
5448 set_detailed_error("No room for frame-type");
5449 return false;
5450 }
5451
5452 QuicPacketNumber largest_acked = LargestAcked(frame);
5453 if (!writer->WriteVarInt62(largest_acked.ToUint64())) {
5454 set_detailed_error("No room for largest-acked in ack frame");
5455 return false;
5456 }
5457
5458 uint64_t ack_delay_time_us = kVarInt62MaxValue;
5459 if (!frame.ack_delay_time.IsInfinite()) {
5460 DCHECK_LE(0u, frame.ack_delay_time.ToMicroseconds());
5461 ack_delay_time_us = frame.ack_delay_time.ToMicroseconds();
fkastenholz4dc4ba32019-07-30 09:55:25 -07005462 ack_delay_time_us = ack_delay_time_us >> local_ack_delay_exponent_;
QUICHE teama6ef0a62019-03-07 20:34:33 -05005463 }
5464
5465 if (!writer->WriteVarInt62(ack_delay_time_us)) {
5466 set_detailed_error("No room for ack-delay in ack frame");
5467 return false;
5468 }
5469 if (type == IETF_ACK_ECN) {
5470 // Encode the ACK ECN fields
5471 if (!writer->WriteVarInt62(frame.ect_0_count)) {
5472 set_detailed_error("No room for ect_0_count in ack frame");
5473 return false;
5474 }
5475 if (!writer->WriteVarInt62(frame.ect_1_count)) {
5476 set_detailed_error("No room for ect_1_count in ack frame");
5477 return false;
5478 }
5479 if (!writer->WriteVarInt62(frame.ecn_ce_count)) {
5480 set_detailed_error("No room for ecn_ce_count in ack frame");
5481 return false;
5482 }
5483 }
5484
5485 uint64_t ack_block_count = frame.packets.NumIntervals();
5486 if (ack_block_count == 0) {
5487 // If the QuicAckFrame has no Intervals, then it is interpreted
5488 // as an ack of a single packet at QuicAckFrame.largest_acked.
5489 // The resulting ack will consist of only the frame's
5490 // largest_ack & first_ack_block fields. The first ack block will be 0
5491 // (indicating a single packet) and the ack block_count will be 0.
5492 if (!writer->WriteVarInt62(0)) {
5493 set_detailed_error("No room for ack block count in ack frame");
5494 return false;
5495 }
5496 // size of the first block is 1 packet
5497 if (!writer->WriteVarInt62(0)) {
5498 set_detailed_error("No room for first ack block in ack frame");
5499 return false;
5500 }
5501 return true;
5502 }
5503 // Case 2 or 3
5504 auto itr = frame.packets.rbegin();
5505
5506 QuicPacketNumber ack_block_largest(largest_acked);
5507 QuicPacketNumber ack_block_smallest;
5508 if ((itr->max() - 1) == QuicPacketNumber(largest_acked)) {
5509 // If largest_acked + 1 is equal to the Max() of the first Interval
5510 // in the QuicAckFrame then the first Interval is the first ack block of the
5511 // frame; remaining Intervals are additional ack blocks. The QuicAckFrame's
5512 // first Interval is encoded in the frame's largest_acked/first_ack_block,
5513 // the remaining Intervals are encoded in additional ack blocks in the
5514 // frame, and the packet's ack_block_count is the number of QuicAckFrame
5515 // Intervals - 1.
5516 ack_block_smallest = itr->min();
5517 itr++;
5518 ack_block_count--;
5519 } else {
5520 // If QuicAckFrame.largest_acked is NOT equal to the Max() of
5521 // the first Interval then it is interpreted as acking a single
5522 // packet at QuicAckFrame.largest_acked, with additional
5523 // Intervals indicating additional ack blocks. The encoding is
5524 // a) The packet's largest_acked is the QuicAckFrame's largest
5525 // acked,
5526 // b) the first ack block size is 0,
5527 // c) The packet's ack_block_count is the number of QuicAckFrame
5528 // Intervals, and
5529 // d) The QuicAckFrame Intervals are encoded in additional ack
5530 // blocks in the packet.
5531 ack_block_smallest = largest_acked;
5532 }
5533
5534 if (!writer->WriteVarInt62(ack_block_count)) {
5535 set_detailed_error("No room for ack block count in ack frame");
5536 return false;
5537 }
5538
5539 uint64_t first_ack_block = ack_block_largest - ack_block_smallest;
5540 if (!writer->WriteVarInt62(first_ack_block)) {
5541 set_detailed_error("No room for first ack block in ack frame");
5542 return false;
5543 }
5544
5545 // For the remaining QuicAckFrame Intervals, if any
5546 while (ack_block_count != 0) {
5547 uint64_t gap_size = ack_block_smallest - itr->max();
5548 if (!writer->WriteVarInt62(gap_size - 1)) {
5549 set_detailed_error("No room for gap block in ack frame");
5550 return false;
5551 }
5552
5553 uint64_t block_size = itr->max() - itr->min();
5554 if (!writer->WriteVarInt62(block_size - 1)) {
5555 set_detailed_error("No room for nth ack block in ack frame");
5556 return false;
5557 }
5558
5559 ack_block_smallest = itr->min();
5560 itr++;
5561 ack_block_count--;
5562 }
5563 return true;
5564}
5565
5566bool QuicFramer::AppendRstStreamFrame(const QuicRstStreamFrame& frame,
5567 QuicDataWriter* writer) {
fkastenholz305e1732019-06-18 05:01:22 -07005568 if (VersionHasIetfQuicFrames(version_.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005569 return AppendIetfResetStreamFrame(frame, writer);
5570 }
5571 if (!writer->WriteUInt32(frame.stream_id)) {
5572 return false;
5573 }
5574
5575 if (!writer->WriteUInt64(frame.byte_offset)) {
5576 return false;
5577 }
5578
5579 uint32_t error_code = static_cast<uint32_t>(frame.error_code);
5580 if (!writer->WriteUInt32(error_code)) {
5581 return false;
5582 }
5583
5584 return true;
5585}
5586
5587bool QuicFramer::AppendConnectionCloseFrame(
5588 const QuicConnectionCloseFrame& frame,
5589 QuicDataWriter* writer) {
fkastenholz305e1732019-06-18 05:01:22 -07005590 if (VersionHasIetfQuicFrames(version_.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005591 return AppendIetfConnectionCloseFrame(frame, writer);
5592 }
fkastenholze9d71a82019-04-09 05:12:13 -07005593 uint32_t error_code = static_cast<uint32_t>(frame.quic_error_code);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005594 if (!writer->WriteUInt32(error_code)) {
5595 return false;
5596 }
5597 if (!writer->WriteStringPiece16(TruncateErrorString(frame.error_details))) {
5598 return false;
5599 }
5600 return true;
5601}
5602
5603bool QuicFramer::AppendGoAwayFrame(const QuicGoAwayFrame& frame,
5604 QuicDataWriter* writer) {
5605 uint32_t error_code = static_cast<uint32_t>(frame.error_code);
5606 if (!writer->WriteUInt32(error_code)) {
5607 return false;
5608 }
5609 uint32_t stream_id = static_cast<uint32_t>(frame.last_good_stream_id);
5610 if (!writer->WriteUInt32(stream_id)) {
5611 return false;
5612 }
5613 if (!writer->WriteStringPiece16(TruncateErrorString(frame.reason_phrase))) {
5614 return false;
5615 }
5616 return true;
5617}
5618
5619bool QuicFramer::AppendWindowUpdateFrame(const QuicWindowUpdateFrame& frame,
5620 QuicDataWriter* writer) {
5621 uint32_t stream_id = static_cast<uint32_t>(frame.stream_id);
5622 if (!writer->WriteUInt32(stream_id)) {
5623 return false;
5624 }
5625 if (!writer->WriteUInt64(frame.byte_offset)) {
5626 return false;
5627 }
5628 return true;
5629}
5630
5631bool QuicFramer::AppendBlockedFrame(const QuicBlockedFrame& frame,
5632 QuicDataWriter* writer) {
fkastenholz305e1732019-06-18 05:01:22 -07005633 if (VersionHasIetfQuicFrames(version_.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005634 if (frame.stream_id == QuicUtils::GetInvalidStreamId(transport_version())) {
5635 return AppendIetfBlockedFrame(frame, writer);
5636 }
5637 return AppendStreamBlockedFrame(frame, writer);
5638 }
5639 uint32_t stream_id = static_cast<uint32_t>(frame.stream_id);
5640 if (!writer->WriteUInt32(stream_id)) {
5641 return false;
5642 }
5643 return true;
5644}
5645
5646bool QuicFramer::AppendPaddingFrame(const QuicPaddingFrame& frame,
5647 QuicDataWriter* writer) {
5648 if (frame.num_padding_bytes == 0) {
5649 return false;
5650 }
5651 if (frame.num_padding_bytes < 0) {
5652 QUIC_BUG_IF(frame.num_padding_bytes != -1);
5653 writer->WritePadding();
5654 return true;
5655 }
5656 // Please note, num_padding_bytes includes type byte which has been written.
5657 return writer->WritePaddingBytes(frame.num_padding_bytes - 1);
5658}
5659
5660bool QuicFramer::AppendMessageFrameAndTypeByte(const QuicMessageFrame& frame,
5661 bool last_frame_in_packet,
5662 QuicDataWriter* writer) {
5663 uint8_t type_byte = last_frame_in_packet ? IETF_EXTENSION_MESSAGE_NO_LENGTH
5664 : IETF_EXTENSION_MESSAGE;
5665 if (!writer->WriteUInt8(type_byte)) {
5666 return false;
5667 }
5668 if (!last_frame_in_packet && !writer->WriteVarInt62(frame.message_length)) {
5669 return false;
5670 }
5671 for (const auto& slice : frame.message_data) {
5672 if (!writer->WriteBytes(slice.data(), slice.length())) {
5673 return false;
5674 }
5675 }
5676 return true;
5677}
5678
5679bool QuicFramer::RaiseError(QuicErrorCode error) {
5680 QUIC_DLOG(INFO) << ENDPOINT << "Error: " << QuicErrorCodeToString(error)
5681 << " detail: " << detailed_error_;
5682 set_error(error);
nharper55fa6132019-05-07 19:37:21 -07005683 if (visitor_) {
5684 visitor_->OnError(this);
5685 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05005686 return false;
5687}
5688
5689bool QuicFramer::IsVersionNegotiation(
5690 const QuicPacketHeader& header,
5691 bool packet_has_ietf_packet_header) const {
dschinazi072da7c2019-05-07 17:57:42 -07005692 if (!packet_has_ietf_packet_header &&
5693 perspective_ == Perspective::IS_CLIENT) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005694 return header.version_flag;
5695 }
5696 if (header.form == IETF_QUIC_SHORT_HEADER_PACKET) {
5697 return false;
5698 }
5699 return header.long_packet_type == VERSION_NEGOTIATION;
5700}
5701
QUICHE teama6ef0a62019-03-07 20:34:33 -05005702bool QuicFramer::AppendIetfConnectionCloseFrame(
5703 const QuicConnectionCloseFrame& frame,
5704 QuicDataWriter* writer) {
fkastenholz72f509b2019-04-10 09:17:49 -07005705 if (frame.close_type != IETF_QUIC_TRANSPORT_CONNECTION_CLOSE &&
5706 frame.close_type != IETF_QUIC_APPLICATION_CONNECTION_CLOSE) {
5707 QUIC_BUG << "Invalid close_type for writing IETF CONNECTION CLOSE.";
5708 set_detailed_error("Invalid close_type for writing IETF CONNECTION CLOSE.");
5709 return false;
5710 }
5711
fkastenholz88d08f42019-09-06 07:38:04 -07005712 if (!writer->WriteVarInt62(
5713 (frame.close_type == IETF_QUIC_TRANSPORT_CONNECTION_CLOSE)
5714 ? frame.transport_error_code
5715 : frame.application_error_code)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005716 set_detailed_error("Can not write connection close frame error code");
5717 return false;
5718 }
fkastenholze9d71a82019-04-09 05:12:13 -07005719
fkastenholz72f509b2019-04-10 09:17:49 -07005720 if (frame.close_type == IETF_QUIC_TRANSPORT_CONNECTION_CLOSE) {
5721 // Write the frame-type of the frame causing the error only
5722 // if it's a CONNECTION_CLOSE/Transport.
5723 if (!writer->WriteVarInt62(frame.transport_close_frame_type)) {
5724 set_detailed_error("Writing frame type failed.");
5725 return false;
5726 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05005727 }
5728
fkastenholzb4dade72019-08-05 06:54:20 -07005729 // There may be additional error information available in the extracted error
5730 // code. Encode the error information in the reason phrase and serialize the
5731 // result.
5732 std::string final_error_string =
5733 GenerateErrorString(frame.error_details, frame.extracted_error_code);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005734 if (!writer->WriteStringPieceVarInt62(
fkastenholzb4dade72019-08-05 06:54:20 -07005735 TruncateErrorString(final_error_string))) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005736 set_detailed_error("Can not write connection close phrase");
5737 return false;
5738 }
5739 return true;
5740}
5741
QUICHE teama6ef0a62019-03-07 20:34:33 -05005742bool QuicFramer::ProcessIetfConnectionCloseFrame(
5743 QuicDataReader* reader,
fkastenholze9d71a82019-04-09 05:12:13 -07005744 QuicConnectionCloseType type,
QUICHE teama6ef0a62019-03-07 20:34:33 -05005745 QuicConnectionCloseFrame* frame) {
fkastenholze9d71a82019-04-09 05:12:13 -07005746 frame->close_type = type;
fkastenholzb4dade72019-08-05 06:54:20 -07005747
fkastenholz88d08f42019-09-06 07:38:04 -07005748 uint64_t error_code;
fkastenholzd57d3f92019-07-16 09:05:17 -07005749 if (!reader->ReadVarInt62(&error_code)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005750 set_detailed_error("Unable to read connection close error code.");
5751 return false;
5752 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05005753
fkastenholzd57d3f92019-07-16 09:05:17 -07005754 if (frame->close_type == IETF_QUIC_TRANSPORT_CONNECTION_CLOSE) {
fkastenholz88d08f42019-09-06 07:38:04 -07005755 frame->transport_error_code =
5756 static_cast<QuicIetfTransportErrorCodes>(error_code);
fkastenholzd57d3f92019-07-16 09:05:17 -07005757 } else if (frame->close_type == IETF_QUIC_APPLICATION_CONNECTION_CLOSE) {
fkastenholz88d08f42019-09-06 07:38:04 -07005758 frame->application_error_code = error_code;
fkastenholzd57d3f92019-07-16 09:05:17 -07005759 }
fkastenholzb4dade72019-08-05 06:54:20 -07005760
fkastenholz72f509b2019-04-10 09:17:49 -07005761 if (type == IETF_QUIC_TRANSPORT_CONNECTION_CLOSE) {
5762 // The frame-type of the frame causing the error is present only
5763 // if it's a CONNECTION_CLOSE/Transport.
5764 if (!reader->ReadVarInt62(&frame->transport_close_frame_type)) {
5765 set_detailed_error("Unable to read connection close frame type.");
5766 return false;
5767 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05005768 }
5769
5770 uint64_t phrase_length;
5771 if (!reader->ReadVarInt62(&phrase_length)) {
5772 set_detailed_error("Unable to read connection close error details.");
5773 return false;
5774 }
fkastenholzb4dade72019-08-05 06:54:20 -07005775
QUICHE teama6ef0a62019-03-07 20:34:33 -05005776 QuicStringPiece phrase;
5777 if (!reader->ReadStringPiece(&phrase, static_cast<size_t>(phrase_length))) {
5778 set_detailed_error("Unable to read connection close error details.");
5779 return false;
5780 }
vasilvvc48c8712019-03-11 13:38:16 -07005781 frame->error_details = std::string(phrase);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005782
fkastenholzb4dade72019-08-05 06:54:20 -07005783 // The frame may have an extracted error code in it. Look for it and
5784 // extract it. If it's not present, MaybeExtract will return
5785 // QUIC_IETF_GQUIC_ERROR_MISSING.
fkastenholz488a4622019-08-26 06:24:46 -07005786 MaybeExtractQuicErrorCode(frame);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005787 return true;
5788}
5789
5790// IETF Quic Path Challenge/Response frames.
5791bool QuicFramer::ProcessPathChallengeFrame(QuicDataReader* reader,
5792 QuicPathChallengeFrame* frame) {
5793 if (!reader->ReadBytes(frame->data_buffer.data(),
5794 frame->data_buffer.size())) {
5795 set_detailed_error("Can not read path challenge data.");
5796 return false;
5797 }
5798 return true;
5799}
5800
5801bool QuicFramer::ProcessPathResponseFrame(QuicDataReader* reader,
5802 QuicPathResponseFrame* frame) {
5803 if (!reader->ReadBytes(frame->data_buffer.data(),
5804 frame->data_buffer.size())) {
5805 set_detailed_error("Can not read path response data.");
5806 return false;
5807 }
5808 return true;
5809}
5810
5811bool QuicFramer::AppendPathChallengeFrame(const QuicPathChallengeFrame& frame,
5812 QuicDataWriter* writer) {
5813 if (!writer->WriteBytes(frame.data_buffer.data(), frame.data_buffer.size())) {
5814 set_detailed_error("Writing Path Challenge data failed.");
5815 return false;
5816 }
5817 return true;
5818}
5819
5820bool QuicFramer::AppendPathResponseFrame(const QuicPathResponseFrame& frame,
5821 QuicDataWriter* writer) {
5822 if (!writer->WriteBytes(frame.data_buffer.data(), frame.data_buffer.size())) {
5823 set_detailed_error("Writing Path Response data failed.");
5824 return false;
5825 }
5826 return true;
5827}
5828
5829// Add a new ietf-format stream reset frame.
5830// General format is
5831// stream id
5832// application error code
5833// final offset
5834bool QuicFramer::AppendIetfResetStreamFrame(const QuicRstStreamFrame& frame,
5835 QuicDataWriter* writer) {
5836 if (!writer->WriteVarInt62(static_cast<uint64_t>(frame.stream_id))) {
5837 set_detailed_error("Writing reset-stream stream id failed.");
5838 return false;
5839 }
fkastenholz07300e52019-07-16 11:51:37 -07005840 if (!writer->WriteVarInt62(static_cast<uint64_t>(frame.ietf_error_code))) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005841 set_detailed_error("Writing reset-stream error code failed.");
5842 return false;
5843 }
5844 if (!writer->WriteVarInt62(static_cast<uint64_t>(frame.byte_offset))) {
5845 set_detailed_error("Writing reset-stream final-offset failed.");
5846 return false;
5847 }
5848 return true;
5849}
5850
5851bool QuicFramer::ProcessIetfResetStreamFrame(QuicDataReader* reader,
5852 QuicRstStreamFrame* frame) {
5853 // Get Stream ID from frame. ReadVarIntStreamID returns false
5854 // if either A) there is a read error or B) the resulting value of
5855 // the Stream ID is larger than the maximum allowed value.
fkastenholz3c4eabf2019-04-22 07:49:59 -07005856 if (!reader->ReadVarIntU32(&frame->stream_id)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005857 set_detailed_error("Unable to read rst stream stream id.");
5858 return false;
5859 }
5860
fkastenholz07300e52019-07-16 11:51:37 -07005861 uint64_t error_code;
5862 if (!reader->ReadVarInt62(&error_code)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005863 set_detailed_error("Unable to read rst stream error code.");
5864 return false;
5865 }
fkastenholz07300e52019-07-16 11:51:37 -07005866 if (error_code > 0xffff) {
5867 frame->ietf_error_code = 0xffff;
5868 QUIC_DLOG(ERROR) << "Reset stream error code (" << error_code
5869 << ") > 0xffff";
5870 } else {
5871 frame->ietf_error_code = static_cast<uint16_t>(error_code);
5872 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05005873
5874 if (!reader->ReadVarInt62(&frame->byte_offset)) {
5875 set_detailed_error("Unable to read rst stream sent byte offset.");
5876 return false;
5877 }
5878 return true;
5879}
5880
5881bool QuicFramer::ProcessStopSendingFrame(
5882 QuicDataReader* reader,
5883 QuicStopSendingFrame* stop_sending_frame) {
fkastenholz3c4eabf2019-04-22 07:49:59 -07005884 if (!reader->ReadVarIntU32(&stop_sending_frame->stream_id)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005885 set_detailed_error("Unable to read stop sending stream id.");
5886 return false;
5887 }
5888
fkastenholz733552e2019-07-16 11:16:58 -07005889 uint64_t error_code;
5890 if (!reader->ReadVarInt62(&error_code)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005891 set_detailed_error("Unable to read stop sending application error code.");
5892 return false;
5893 }
fkastenholz733552e2019-07-16 11:16:58 -07005894 // TODO(fkastenholz): when error codes go to uint64_t, remove this.
5895 if (error_code > 0xffff) {
5896 stop_sending_frame->application_error_code = 0xffff;
5897 QUIC_DLOG(ERROR) << "Stop sending error code (" << error_code
5898 << ") > 0xffff";
5899 } else {
5900 stop_sending_frame->application_error_code =
5901 static_cast<uint16_t>(error_code);
5902 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05005903 return true;
5904}
5905
5906bool QuicFramer::AppendStopSendingFrame(
5907 const QuicStopSendingFrame& stop_sending_frame,
5908 QuicDataWriter* writer) {
5909 if (!writer->WriteVarInt62(stop_sending_frame.stream_id)) {
5910 set_detailed_error("Can not write stop sending stream id");
5911 return false;
5912 }
fkastenholz733552e2019-07-16 11:16:58 -07005913 if (!writer->WriteVarInt62(
5914 static_cast<uint64_t>(stop_sending_frame.application_error_code))) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005915 set_detailed_error("Can not write application error code");
5916 return false;
5917 }
5918 return true;
5919}
5920
5921// Append/process IETF-Format MAX_DATA Frame
5922bool QuicFramer::AppendMaxDataFrame(const QuicWindowUpdateFrame& frame,
5923 QuicDataWriter* writer) {
5924 if (!writer->WriteVarInt62(frame.byte_offset)) {
5925 set_detailed_error("Can not write MAX_DATA byte-offset");
5926 return false;
5927 }
5928 return true;
5929}
5930
5931bool QuicFramer::ProcessMaxDataFrame(QuicDataReader* reader,
5932 QuicWindowUpdateFrame* frame) {
5933 frame->stream_id = QuicUtils::GetInvalidStreamId(transport_version());
5934 if (!reader->ReadVarInt62(&frame->byte_offset)) {
5935 set_detailed_error("Can not read MAX_DATA byte-offset");
5936 return false;
5937 }
5938 return true;
5939}
5940
5941// Append/process IETF-Format MAX_STREAM_DATA Frame
5942bool QuicFramer::AppendMaxStreamDataFrame(const QuicWindowUpdateFrame& frame,
5943 QuicDataWriter* writer) {
5944 if (!writer->WriteVarInt62(frame.stream_id)) {
5945 set_detailed_error("Can not write MAX_STREAM_DATA stream id");
5946 return false;
5947 }
5948 if (!writer->WriteVarInt62(frame.byte_offset)) {
5949 set_detailed_error("Can not write MAX_STREAM_DATA byte-offset");
5950 return false;
5951 }
5952 return true;
5953}
5954
5955bool QuicFramer::ProcessMaxStreamDataFrame(QuicDataReader* reader,
5956 QuicWindowUpdateFrame* frame) {
fkastenholz3c4eabf2019-04-22 07:49:59 -07005957 if (!reader->ReadVarIntU32(&frame->stream_id)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005958 set_detailed_error("Can not read MAX_STREAM_DATA stream id");
5959 return false;
5960 }
5961 if (!reader->ReadVarInt62(&frame->byte_offset)) {
5962 set_detailed_error("Can not read MAX_STREAM_DATA byte-count");
5963 return false;
5964 }
5965 return true;
5966}
5967
fkastenholz3c4eabf2019-04-22 07:49:59 -07005968bool QuicFramer::AppendMaxStreamsFrame(const QuicMaxStreamsFrame& frame,
QUICHE teama6ef0a62019-03-07 20:34:33 -05005969 QuicDataWriter* writer) {
fkastenholz3c4eabf2019-04-22 07:49:59 -07005970 if (!writer->WriteVarInt62(frame.stream_count)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005971 set_detailed_error("Can not write MAX_STREAMS stream count");
5972 return false;
5973 }
5974 return true;
5975}
5976
5977bool QuicFramer::ProcessMaxStreamsFrame(QuicDataReader* reader,
fkastenholz3c4eabf2019-04-22 07:49:59 -07005978 QuicMaxStreamsFrame* frame,
QUICHE teama6ef0a62019-03-07 20:34:33 -05005979 uint64_t frame_type) {
fkastenholz3c4eabf2019-04-22 07:49:59 -07005980 if (!reader->ReadVarIntU32(&frame->stream_count)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005981 set_detailed_error("Can not read MAX_STREAMS stream count.");
5982 return false;
5983 }
fkastenholz3c4eabf2019-04-22 07:49:59 -07005984 frame->unidirectional = (frame_type == IETF_MAX_STREAMS_UNIDIRECTIONAL);
5985 return true;
QUICHE teama6ef0a62019-03-07 20:34:33 -05005986}
5987
5988bool QuicFramer::AppendIetfBlockedFrame(const QuicBlockedFrame& frame,
5989 QuicDataWriter* writer) {
5990 if (!writer->WriteVarInt62(frame.offset)) {
5991 set_detailed_error("Can not write blocked offset.");
5992 return false;
5993 }
5994 return true;
5995}
5996
5997bool QuicFramer::ProcessIetfBlockedFrame(QuicDataReader* reader,
5998 QuicBlockedFrame* frame) {
5999 // Indicates that it is a BLOCKED frame (as opposed to STREAM_BLOCKED).
6000 frame->stream_id = QuicUtils::GetInvalidStreamId(transport_version());
6001 if (!reader->ReadVarInt62(&frame->offset)) {
6002 set_detailed_error("Can not read blocked offset.");
6003 return false;
6004 }
6005 return true;
6006}
6007
6008bool QuicFramer::AppendStreamBlockedFrame(const QuicBlockedFrame& frame,
6009 QuicDataWriter* writer) {
6010 if (!writer->WriteVarInt62(frame.stream_id)) {
6011 set_detailed_error("Can not write stream blocked stream id.");
6012 return false;
6013 }
6014 if (!writer->WriteVarInt62(frame.offset)) {
6015 set_detailed_error("Can not write stream blocked offset.");
6016 return false;
6017 }
6018 return true;
6019}
6020
6021bool QuicFramer::ProcessStreamBlockedFrame(QuicDataReader* reader,
6022 QuicBlockedFrame* frame) {
fkastenholz3c4eabf2019-04-22 07:49:59 -07006023 if (!reader->ReadVarIntU32(&frame->stream_id)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05006024 set_detailed_error("Can not read stream blocked stream id.");
6025 return false;
6026 }
6027 if (!reader->ReadVarInt62(&frame->offset)) {
6028 set_detailed_error("Can not read stream blocked offset.");
6029 return false;
6030 }
6031 return true;
6032}
6033
fkastenholz3c4eabf2019-04-22 07:49:59 -07006034bool QuicFramer::AppendStreamsBlockedFrame(const QuicStreamsBlockedFrame& frame,
6035 QuicDataWriter* writer) {
6036 if (!writer->WriteVarInt62(frame.stream_count)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05006037 set_detailed_error("Can not write STREAMS_BLOCKED stream count");
6038 return false;
6039 }
6040 return true;
6041}
6042
6043bool QuicFramer::ProcessStreamsBlockedFrame(QuicDataReader* reader,
fkastenholz3c4eabf2019-04-22 07:49:59 -07006044 QuicStreamsBlockedFrame* frame,
QUICHE teama6ef0a62019-03-07 20:34:33 -05006045 uint64_t frame_type) {
fkastenholz3c4eabf2019-04-22 07:49:59 -07006046 if (!reader->ReadVarIntU32(&frame->stream_count)) {
6047 set_detailed_error("Can not read STREAMS_BLOCKED stream count.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05006048 return false;
6049 }
fkastenholz3c4eabf2019-04-22 07:49:59 -07006050 frame->unidirectional = (frame_type == IETF_STREAMS_BLOCKED_UNIDIRECTIONAL);
6051
QUICHE teama6ef0a62019-03-07 20:34:33 -05006052 // TODO(fkastenholz): handle properly when the STREAMS_BLOCKED
6053 // frame is implemented and passed up to the stream ID manager.
fkastenholz3c4eabf2019-04-22 07:49:59 -07006054 if (frame->stream_count >
6055 QuicUtils::GetMaxStreamCount(
6056 (frame_type == IETF_STREAMS_BLOCKED_UNIDIRECTIONAL),
6057 ((perspective_ == Perspective::IS_CLIENT)
6058 ? Perspective::IS_SERVER
6059 : Perspective::IS_CLIENT))) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05006060 // If stream count is such that the resulting stream ID would exceed our
6061 // implementation limit, generate an error.
6062 set_detailed_error(
6063 "STREAMS_BLOCKED stream count exceeds implementation limit.");
6064 return false;
6065 }
fkastenholz3c4eabf2019-04-22 07:49:59 -07006066 return true;
QUICHE teama6ef0a62019-03-07 20:34:33 -05006067}
6068
6069bool QuicFramer::AppendNewConnectionIdFrame(
6070 const QuicNewConnectionIdFrame& frame,
6071 QuicDataWriter* writer) {
6072 if (!writer->WriteVarInt62(frame.sequence_number)) {
6073 set_detailed_error("Can not write New Connection ID sequence number");
6074 return false;
6075 }
fkastenholz1c19fc22019-07-12 11:06:19 -07006076 if (!writer->WriteVarInt62(frame.retire_prior_to)) {
6077 set_detailed_error("Can not write New Connection ID retire_prior_to");
6078 return false;
6079 }
dschinazicf5b1e22019-07-17 18:35:17 -07006080 if (!writer->WriteLengthPrefixedConnectionId(frame.connection_id)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05006081 set_detailed_error("Can not write New Connection ID frame connection ID");
6082 return false;
6083 }
6084
6085 if (!writer->WriteBytes(
6086 static_cast<const void*>(&frame.stateless_reset_token),
6087 sizeof(frame.stateless_reset_token))) {
6088 set_detailed_error("Can not write New Connection ID Reset Token");
6089 return false;
6090 }
6091 return true;
6092}
6093
6094bool QuicFramer::ProcessNewConnectionIdFrame(QuicDataReader* reader,
6095 QuicNewConnectionIdFrame* frame) {
6096 if (!reader->ReadVarInt62(&frame->sequence_number)) {
6097 set_detailed_error(
6098 "Unable to read new connection ID frame sequence number.");
6099 return false;
6100 }
6101
fkastenholz1c19fc22019-07-12 11:06:19 -07006102 if (!reader->ReadVarInt62(&frame->retire_prior_to)) {
6103 set_detailed_error(
6104 "Unable to read new connection ID frame retire_prior_to.");
6105 return false;
6106 }
6107 if (frame->retire_prior_to > frame->sequence_number) {
6108 set_detailed_error("Retire_prior_to > sequence_number.");
6109 return false;
6110 }
dschinazicf5b1e22019-07-17 18:35:17 -07006111
6112 if (!reader->ReadLengthPrefixedConnectionId(&frame->connection_id)) {
6113 set_detailed_error("Unable to read new connection ID frame connection id.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05006114 return false;
6115 }
6116
dschinazicf5b1e22019-07-17 18:35:17 -07006117 if (!QuicUtils::IsConnectionIdValidForVersion(frame->connection_id,
6118 transport_version())) {
QUICHE team0131a5b2019-03-20 15:23:27 -07006119 set_detailed_error("Invalid new connection ID length for version.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05006120 return false;
6121 }
6122
QUICHE teama6ef0a62019-03-07 20:34:33 -05006123 if (!reader->ReadBytes(&frame->stateless_reset_token,
6124 sizeof(frame->stateless_reset_token))) {
6125 set_detailed_error("Can not read new connection ID frame reset token.");
6126 return false;
6127 }
6128 return true;
6129}
6130
6131bool QuicFramer::AppendRetireConnectionIdFrame(
6132 const QuicRetireConnectionIdFrame& frame,
6133 QuicDataWriter* writer) {
6134 if (!writer->WriteVarInt62(frame.sequence_number)) {
6135 set_detailed_error("Can not write Retire Connection ID sequence number");
6136 return false;
6137 }
6138 return true;
6139}
6140
6141bool QuicFramer::ProcessRetireConnectionIdFrame(
6142 QuicDataReader* reader,
6143 QuicRetireConnectionIdFrame* frame) {
6144 if (!reader->ReadVarInt62(&frame->sequence_number)) {
6145 set_detailed_error(
6146 "Unable to read retire connection ID frame sequence number.");
6147 return false;
6148 }
6149 return true;
6150}
6151
6152uint8_t QuicFramer::GetStreamFrameTypeByte(const QuicStreamFrame& frame,
6153 bool last_frame_in_packet) const {
fkastenholz305e1732019-06-18 05:01:22 -07006154 if (VersionHasIetfQuicFrames(version_.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05006155 return GetIetfStreamFrameTypeByte(frame, last_frame_in_packet);
6156 }
6157 uint8_t type_byte = 0;
6158 // Fin bit.
6159 type_byte |= frame.fin ? kQuicStreamFinMask : 0;
6160
6161 // Data Length bit.
6162 type_byte <<= kQuicStreamDataLengthShift;
6163 type_byte |= last_frame_in_packet ? 0 : kQuicStreamDataLengthMask;
6164
6165 // Offset 3 bits.
6166 type_byte <<= kQuicStreamShift;
6167 const size_t offset_len =
6168 GetStreamOffsetSize(version_.transport_version, frame.offset);
6169 if (offset_len > 0) {
6170 type_byte |= offset_len - 1;
6171 }
6172
6173 // stream id 2 bits.
6174 type_byte <<= kQuicStreamIdShift;
6175 type_byte |= GetStreamIdSize(frame.stream_id) - 1;
6176 type_byte |= kQuicFrameTypeStreamMask; // Set Stream Frame Type to 1.
6177
6178 return type_byte;
6179}
6180
6181uint8_t QuicFramer::GetIetfStreamFrameTypeByte(
6182 const QuicStreamFrame& frame,
6183 bool last_frame_in_packet) const {
fkastenholz305e1732019-06-18 05:01:22 -07006184 DCHECK(VersionHasIetfQuicFrames(version_.transport_version));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006185 uint8_t type_byte = IETF_STREAM;
6186 if (!last_frame_in_packet) {
6187 type_byte |= IETF_STREAM_FRAME_LEN_BIT;
6188 }
6189 if (frame.offset != 0) {
6190 type_byte |= IETF_STREAM_FRAME_OFF_BIT;
6191 }
6192 if (frame.fin) {
6193 type_byte |= IETF_STREAM_FRAME_FIN_BIT;
6194 }
6195 return type_byte;
6196}
6197
6198void QuicFramer::InferPacketHeaderTypeFromVersion() {
6199 // This function should only be called when server connection negotiates the
6200 // version.
6201 DCHECK(perspective_ == Perspective::IS_SERVER &&
6202 !infer_packet_header_type_from_version_);
6203 infer_packet_header_type_from_version_ = true;
6204}
6205
QUICHE team10b22a12019-03-21 15:31:42 -07006206void QuicFramer::EnableMultiplePacketNumberSpacesSupport() {
6207 if (supports_multiple_packet_number_spaces_) {
6208 QUIC_BUG << "Multiple packet number spaces has already been enabled";
6209 return;
6210 }
6211 if (largest_packet_number_.IsInitialized()) {
6212 QUIC_BUG << "Try to enable multiple packet number spaces support after any "
6213 "packet has been received.";
6214 return;
6215 }
6216
6217 supports_multiple_packet_number_spaces_ = true;
6218}
6219
fayangccbab732019-05-13 10:11:25 -07006220// static
6221QuicErrorCode QuicFramer::ProcessPacketDispatcher(
6222 const QuicEncryptedPacket& packet,
dschinazib42a8c52019-05-30 09:45:01 -07006223 uint8_t expected_destination_connection_id_length,
fayangccbab732019-05-13 10:11:25 -07006224 PacketHeaderFormat* format,
6225 bool* version_flag,
6226 QuicVersionLabel* version_label,
fayangccbab732019-05-13 10:11:25 -07006227 QuicConnectionId* destination_connection_id,
dschinazib42a8c52019-05-30 09:45:01 -07006228 QuicConnectionId* source_connection_id,
fayangccbab732019-05-13 10:11:25 -07006229 std::string* detailed_error) {
dschinazi48ac9192019-07-31 00:07:26 -07006230 DCHECK(!GetQuicReloadableFlag(quic_use_parse_public_header));
fayangccbab732019-05-13 10:11:25 -07006231 QuicDataReader reader(packet.data(), packet.length());
6232
dschinazib42a8c52019-05-30 09:45:01 -07006233 *source_connection_id = EmptyQuicConnectionId();
fayangccbab732019-05-13 10:11:25 -07006234 uint8_t first_byte;
6235 if (!reader.ReadBytes(&first_byte, 1)) {
6236 *detailed_error = "Unable to read first byte.";
6237 return QUIC_INVALID_PACKET_HEADER;
6238 }
dschinazib42a8c52019-05-30 09:45:01 -07006239 uint8_t destination_connection_id_length = 0, source_connection_id_length = 0;
fayangccbab732019-05-13 10:11:25 -07006240 if (!QuicUtils::IsIetfPacketHeader(first_byte)) {
6241 *format = GOOGLE_QUIC_PACKET;
6242 *version_flag = (first_byte & PACKET_PUBLIC_FLAGS_VERSION) != 0;
dschinazib42a8c52019-05-30 09:45:01 -07006243 destination_connection_id_length =
fayangccbab732019-05-13 10:11:25 -07006244 first_byte & PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID;
dschinazib42a8c52019-05-30 09:45:01 -07006245 if (destination_connection_id_length == 0 ||
fayangccbab732019-05-13 10:11:25 -07006246 !reader.ReadConnectionId(destination_connection_id,
dschinazib42a8c52019-05-30 09:45:01 -07006247 destination_connection_id_length)) {
fayangccbab732019-05-13 10:11:25 -07006248 *detailed_error = "Unable to read ConnectionId.";
6249 return QUIC_INVALID_PACKET_HEADER;
6250 }
6251 if (*version_flag && !ProcessVersionLabel(&reader, version_label)) {
6252 *detailed_error = "Unable to read protocol version.";
6253 return QUIC_INVALID_PACKET_HEADER;
6254 }
6255 return QUIC_NO_ERROR;
6256 }
6257
6258 *format = GetIetfPacketHeaderFormat(first_byte);
6259 QUIC_DVLOG(1) << "Dispatcher: Processing IETF QUIC packet, format: "
6260 << *format;
6261 *version_flag = *format == IETF_QUIC_LONG_HEADER_PACKET;
6262 if (*format == IETF_QUIC_LONG_HEADER_PACKET) {
6263 if (!ProcessVersionLabel(&reader, version_label)) {
6264 *detailed_error = "Unable to read protocol version.";
6265 return QUIC_INVALID_PACKET_HEADER;
6266 }
dschinazi8ff74822019-05-28 16:37:20 -07006267 // Set should_update_expected_server_connection_id_length to true to bypass
fayangccbab732019-05-13 10:11:25 -07006268 // connection ID lengths validation.
dschinazi8ff74822019-05-28 16:37:20 -07006269 uint8_t unused_expected_server_connection_id_length = 0;
fayangccbab732019-05-13 10:11:25 -07006270 if (!ProcessAndValidateIetfConnectionIdLength(
6271 &reader, ParseQuicVersionLabel(*version_label),
dschinazi334f0232019-05-29 16:08:53 -07006272 Perspective::IS_SERVER,
dschinazi8ff74822019-05-28 16:37:20 -07006273 /*should_update_expected_server_connection_id_length=*/true,
6274 &unused_expected_server_connection_id_length,
dschinazib42a8c52019-05-30 09:45:01 -07006275 &destination_connection_id_length, &source_connection_id_length,
6276 detailed_error)) {
fayangccbab732019-05-13 10:11:25 -07006277 return QUIC_INVALID_PACKET_HEADER;
6278 }
6279 } else {
dschinazib42a8c52019-05-30 09:45:01 -07006280 // For short header packets, expected_destination_connection_id_length
6281 // is used to determine the destination_connection_id_length.
6282 destination_connection_id_length =
6283 expected_destination_connection_id_length;
6284 DCHECK_EQ(0, source_connection_id_length);
fayangccbab732019-05-13 10:11:25 -07006285 }
6286 // Read destination connection ID.
6287 if (!reader.ReadConnectionId(destination_connection_id,
dschinazib42a8c52019-05-30 09:45:01 -07006288 destination_connection_id_length)) {
6289 *detailed_error = "Unable to read destination connection ID.";
6290 return QUIC_INVALID_PACKET_HEADER;
6291 }
6292 // Read source connection ID.
dschinazi5e1a7b22019-07-31 12:23:21 -07006293 if (!reader.ReadConnectionId(source_connection_id,
dschinazib42a8c52019-05-30 09:45:01 -07006294 source_connection_id_length)) {
6295 *detailed_error = "Unable to read source connection ID.";
fayangccbab732019-05-13 10:11:25 -07006296 return QUIC_INVALID_PACKET_HEADER;
6297 }
6298 return QUIC_NO_ERROR;
6299}
6300
dschinazide0f6dc2019-05-15 16:10:11 -07006301// static
dschinazi48ac9192019-07-31 00:07:26 -07006302QuicErrorCode QuicFramer::ParsePublicHeaderDispatcher(
6303 const QuicEncryptedPacket& packet,
6304 uint8_t expected_destination_connection_id_length,
6305 PacketHeaderFormat* format,
6306 bool* version_present,
6307 bool* has_length_prefix,
6308 QuicVersionLabel* version_label,
6309 ParsedQuicVersion* parsed_version,
6310 QuicConnectionId* destination_connection_id,
6311 QuicConnectionId* source_connection_id,
6312 bool* retry_token_present,
6313 QuicStringPiece* retry_token,
6314 std::string* detailed_error) {
6315 QuicDataReader reader(packet.data(), packet.length());
6316 if (reader.IsDoneReading()) {
6317 *detailed_error = "Unable to read first byte.";
6318 return QUIC_INVALID_PACKET_HEADER;
6319 }
6320 const uint8_t first_byte = reader.PeekByte();
6321 const bool ietf_format = QuicUtils::IsIetfPacketHeader(first_byte);
6322 uint8_t unused_first_byte;
6323 QuicVariableLengthIntegerLength retry_token_length_length;
6324 QuicLongHeaderType unused_log_packet_type;
6325 const QuicErrorCode error_code = ParsePublicHeader(
6326 &reader, expected_destination_connection_id_length, ietf_format,
6327 &unused_first_byte, format, version_present, has_length_prefix,
6328 version_label, parsed_version, destination_connection_id,
6329 source_connection_id, &unused_log_packet_type, &retry_token_length_length,
6330 retry_token, detailed_error);
6331 *retry_token_present =
6332 retry_token_length_length != VARIABLE_LENGTH_INTEGER_LENGTH_0;
6333 return error_code;
6334}
6335
6336// static
6337QuicErrorCode QuicFramer::ParsePublicHeaderGoogleQuic(
6338 QuicDataReader* reader,
6339 uint8_t* first_byte,
6340 PacketHeaderFormat* format,
6341 bool* version_present,
6342 QuicVersionLabel* version_label,
dschinazi243eabc2019-08-05 16:15:29 -07006343 ParsedQuicVersion* parsed_version,
dschinazi48ac9192019-07-31 00:07:26 -07006344 QuicConnectionId* destination_connection_id,
6345 std::string* detailed_error) {
6346 *format = GOOGLE_QUIC_PACKET;
6347 *version_present = (*first_byte & PACKET_PUBLIC_FLAGS_VERSION) != 0;
6348 uint8_t destination_connection_id_length = 0;
6349 if ((*first_byte & PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID) != 0) {
6350 destination_connection_id_length = kQuicDefaultConnectionIdLength;
6351 }
6352 if (!reader->ReadConnectionId(destination_connection_id,
6353 destination_connection_id_length)) {
6354 *detailed_error = "Unable to read ConnectionId.";
6355 return QUIC_INVALID_PACKET_HEADER;
6356 }
dschinazi243eabc2019-08-05 16:15:29 -07006357 if (*version_present) {
6358 if (!ProcessVersionLabel(reader, version_label)) {
6359 *detailed_error = "Unable to read protocol version.";
6360 return QUIC_INVALID_PACKET_HEADER;
6361 }
6362 *parsed_version = ParseQuicVersionLabel(*version_label);
dschinazi48ac9192019-07-31 00:07:26 -07006363 }
6364 return QUIC_NO_ERROR;
6365}
6366
6367namespace {
6368
6369inline bool PacketHasLengthPrefixedConnectionIds(
6370 const QuicDataReader& reader,
6371 ParsedQuicVersion parsed_version,
6372 QuicVersionLabel version_label,
6373 uint8_t first_byte) {
6374 if (parsed_version.transport_version != QUIC_VERSION_UNSUPPORTED) {
6375 return parsed_version.HasLengthPrefixedConnectionIds();
6376 }
6377
6378 // Received unsupported version, check known old unsupported versions.
6379 if (QuicVersionLabelUses4BitConnectionIdLength(version_label)) {
6380 return false;
6381 }
6382
6383 // Received unknown version, check connection ID length byte.
6384 if (reader.IsDoneReading()) {
6385 // This check is required to safely peek the connection ID length byte.
6386 return true;
6387 }
6388 const uint8_t connection_id_length_byte = reader.PeekByte();
6389
6390 // Check for packets produced by older versions of
6391 // QuicFramer::WriteClientVersionNegotiationProbePacket
6392 if (first_byte == 0xc0 && (connection_id_length_byte & 0x0f) == 0 &&
6393 connection_id_length_byte >= 0x50 && version_label == 0xcabadaba) {
6394 return false;
6395 }
6396
6397 // Check for munged packets with version tag PROX.
6398 if ((connection_id_length_byte & 0x0f) == 0 &&
6399 connection_id_length_byte >= 0x20 && version_label == 0x50524F58) {
6400 return false;
6401 }
6402
6403 return true;
6404}
6405
6406inline bool ParseLongHeaderConnectionIds(
6407 QuicDataReader* reader,
6408 bool has_length_prefix,
6409 QuicConnectionId* destination_connection_id,
6410 QuicConnectionId* source_connection_id,
6411 std::string* detailed_error) {
6412 if (has_length_prefix) {
6413 if (!reader->ReadLengthPrefixedConnectionId(destination_connection_id)) {
6414 *detailed_error = "Unable to read destination connection ID.";
6415 return false;
6416 }
6417 if (!reader->ReadLengthPrefixedConnectionId(source_connection_id)) {
6418 *detailed_error = "Unable to read source connection ID.";
6419 return false;
6420 }
6421 } else {
6422 // Parse connection ID lengths.
6423 uint8_t connection_id_lengths_byte;
6424 if (!reader->ReadUInt8(&connection_id_lengths_byte)) {
6425 *detailed_error = "Unable to read connection ID lengths.";
6426 return false;
6427 }
6428 uint8_t destination_connection_id_length =
6429 (connection_id_lengths_byte & kDestinationConnectionIdLengthMask) >> 4;
6430 if (destination_connection_id_length != 0) {
6431 destination_connection_id_length += kConnectionIdLengthAdjustment;
6432 }
6433 uint8_t source_connection_id_length =
6434 connection_id_lengths_byte & kSourceConnectionIdLengthMask;
6435 if (source_connection_id_length != 0) {
6436 source_connection_id_length += kConnectionIdLengthAdjustment;
6437 }
6438
6439 // Read destination connection ID.
6440 if (!reader->ReadConnectionId(destination_connection_id,
6441 destination_connection_id_length)) {
6442 *detailed_error = "Unable to read destination connection ID.";
6443 return false;
6444 }
6445
6446 // Read source connection ID.
6447 if (!reader->ReadConnectionId(source_connection_id,
6448 source_connection_id_length)) {
6449 *detailed_error = "Unable to read source connection ID.";
6450 return false;
6451 }
6452 }
6453 return true;
6454}
6455
6456} // namespace
6457
6458// static
6459QuicErrorCode QuicFramer::ParsePublicHeader(
6460 QuicDataReader* reader,
6461 uint8_t expected_destination_connection_id_length,
6462 bool ietf_format,
6463 uint8_t* first_byte,
6464 PacketHeaderFormat* format,
6465 bool* version_present,
6466 bool* has_length_prefix,
6467 QuicVersionLabel* version_label,
6468 ParsedQuicVersion* parsed_version,
6469 QuicConnectionId* destination_connection_id,
6470 QuicConnectionId* source_connection_id,
6471 QuicLongHeaderType* long_packet_type,
6472 QuicVariableLengthIntegerLength* retry_token_length_length,
6473 QuicStringPiece* retry_token,
6474 std::string* detailed_error) {
6475 *version_present = false;
6476 *has_length_prefix = false;
6477 *version_label = 0;
6478 *parsed_version = UnsupportedQuicVersion();
6479 *source_connection_id = EmptyQuicConnectionId();
6480 *long_packet_type = INVALID_PACKET_TYPE;
6481 *retry_token_length_length = VARIABLE_LENGTH_INTEGER_LENGTH_0;
6482 *retry_token = QuicStringPiece();
6483 *detailed_error = "";
6484
6485 if (!reader->ReadUInt8(first_byte)) {
6486 *detailed_error = "Unable to read first byte.";
6487 return QUIC_INVALID_PACKET_HEADER;
6488 }
6489
6490 if (!ietf_format) {
6491 return ParsePublicHeaderGoogleQuic(
6492 reader, first_byte, format, version_present, version_label,
dschinazi243eabc2019-08-05 16:15:29 -07006493 parsed_version, destination_connection_id, detailed_error);
dschinazi48ac9192019-07-31 00:07:26 -07006494 }
6495
6496 *format = GetIetfPacketHeaderFormat(*first_byte);
6497
6498 if (*format == IETF_QUIC_SHORT_HEADER_PACKET) {
6499 // Read destination connection ID using
6500 // expected_destination_connection_id_length to determine its length.
6501 if (!reader->ReadConnectionId(destination_connection_id,
6502 expected_destination_connection_id_length)) {
6503 *detailed_error = "Unable to read destination connection ID.";
6504 return QUIC_INVALID_PACKET_HEADER;
6505 }
6506 return QUIC_NO_ERROR;
6507 }
6508
6509 DCHECK_EQ(IETF_QUIC_LONG_HEADER_PACKET, *format);
6510 *version_present = true;
6511 if (!ProcessVersionLabel(reader, version_label)) {
6512 *detailed_error = "Unable to read protocol version.";
6513 return QUIC_INVALID_PACKET_HEADER;
6514 }
6515
6516 if (*version_label == 0) {
6517 *long_packet_type = VERSION_NEGOTIATION;
6518 }
6519
6520 // Parse version.
6521 *parsed_version = ParseQuicVersionLabel(*version_label);
6522
6523 // Figure out which IETF QUIC invariants this packet follows.
6524 *has_length_prefix = PacketHasLengthPrefixedConnectionIds(
6525 *reader, *parsed_version, *version_label, *first_byte);
6526
6527 // Parse connection IDs.
6528 if (!ParseLongHeaderConnectionIds(reader, *has_length_prefix,
6529 destination_connection_id,
6530 source_connection_id, detailed_error)) {
6531 return QUIC_INVALID_PACKET_HEADER;
6532 }
6533
6534 if (parsed_version->transport_version == QUIC_VERSION_UNSUPPORTED) {
6535 // Skip parsing of long packet type and retry token for unknown versions.
6536 return QUIC_NO_ERROR;
6537 }
6538
6539 // Parse long packet type.
fayang36825da2019-08-21 14:01:27 -07006540 if (!GetLongHeaderType(*first_byte, long_packet_type)) {
dschinazi48ac9192019-07-31 00:07:26 -07006541 *detailed_error = "Unable to parse long packet type.";
6542 return QUIC_INVALID_PACKET_HEADER;
6543 }
6544
6545 if (!parsed_version->SupportsRetry() || *long_packet_type != INITIAL) {
6546 // Retry token is only present on initial packets for some versions.
6547 return QUIC_NO_ERROR;
6548 }
6549
6550 *retry_token_length_length = reader->PeekVarInt62Length();
6551 uint64_t retry_token_length;
6552 if (!reader->ReadVarInt62(&retry_token_length)) {
6553 *retry_token_length_length = VARIABLE_LENGTH_INTEGER_LENGTH_0;
6554 *detailed_error = "Unable to read retry token length.";
6555 return QUIC_INVALID_PACKET_HEADER;
6556 }
6557
6558 if (!reader->ReadStringPiece(retry_token, retry_token_length)) {
6559 *detailed_error = "Unable to read retry token.";
6560 return QUIC_INVALID_PACKET_HEADER;
6561 }
6562
6563 return QUIC_NO_ERROR;
6564}
6565
6566// static
dschinazide0f6dc2019-05-15 16:10:11 -07006567bool QuicFramer::WriteClientVersionNegotiationProbePacket(
6568 char* packet_bytes,
6569 QuicByteCount packet_length,
6570 const char* destination_connection_id_bytes,
6571 uint8_t destination_connection_id_length) {
6572 if (packet_bytes == nullptr) {
6573 QUIC_BUG << "Invalid packet_bytes";
6574 return false;
6575 }
6576 if (packet_length < kMinPacketSizeForVersionNegotiation ||
6577 packet_length > 65535) {
6578 QUIC_BUG << "Invalid packet_length";
6579 return false;
6580 }
dschinazib012d212019-08-01 18:07:26 -07006581 if (destination_connection_id_length > kQuicMaxConnectionId4BitLength ||
dschinazi19dc2b52019-07-17 19:54:43 -07006582 destination_connection_id_length <
6583 kQuicMinimumInitialConnectionIdLength) {
dschinazide0f6dc2019-05-15 16:10:11 -07006584 QUIC_BUG << "Invalid connection_id_length";
6585 return false;
6586 }
dschinazi48ac9192019-07-31 00:07:26 -07006587 const bool use_length_prefix =
6588 GetQuicFlag(FLAGS_quic_prober_uses_length_prefixed_connection_ids);
6589 const uint8_t last_version_byte = use_length_prefix ? 0xda : 0xba;
dschinazide0f6dc2019-05-15 16:10:11 -07006590 // clang-format off
dschinazi48ac9192019-07-31 00:07:26 -07006591 const unsigned char packet_start_bytes[] = {
dschinazide0f6dc2019-05-15 16:10:11 -07006592 // IETF long header with fixed bit set, type initial, all-0 encrypted bits.
6593 0xc0,
6594 // Version, part of the IETF space reserved for negotiation.
6595 // This intentionally differs from QuicVersionReservedForNegotiation()
6596 // to allow differentiating them over the wire.
dschinazi48ac9192019-07-31 00:07:26 -07006597 0xca, 0xba, 0xda, last_version_byte,
dschinazide0f6dc2019-05-15 16:10:11 -07006598 };
6599 // clang-format on
6600 static_assert(sizeof(packet_start_bytes) == 5, "bad packet_start_bytes size");
6601 QuicDataWriter writer(packet_length, packet_bytes);
6602 if (!writer.WriteBytes(packet_start_bytes, sizeof(packet_start_bytes))) {
6603 QUIC_BUG << "Failed to write packet start";
6604 return false;
6605 }
6606
6607 QuicConnectionId destination_connection_id(destination_connection_id_bytes,
6608 destination_connection_id_length);
dschinazi48ac9192019-07-31 00:07:26 -07006609 if (!AppendIetfConnectionIds(
6610 /*version_flag=*/true, use_length_prefix, destination_connection_id,
6611 EmptyQuicConnectionId(), &writer)) {
dschinazide0f6dc2019-05-15 16:10:11 -07006612 QUIC_BUG << "Failed to write connection IDs";
6613 return false;
6614 }
6615 // Add 8 bytes of zeroes followed by 8 bytes of ones to ensure that this does
6616 // not parse with any known version. The zeroes make sure that packet numbers,
6617 // retry token lengths and payload lengths are parsed as zero, and if the
6618 // zeroes are treated as padding frames, 0xff is known to not parse as a
6619 // valid frame type.
6620 if (!writer.WriteUInt64(0) ||
6621 !writer.WriteUInt64(std::numeric_limits<uint64_t>::max())) {
6622 QUIC_BUG << "Failed to write 18 bytes";
6623 return false;
6624 }
6625 // Make sure the polite greeting below is padded to a 16-byte boundary to
6626 // make it easier to read in tcpdump.
6627 while (writer.length() % 16 != 0) {
6628 if (!writer.WriteUInt8(0)) {
6629 QUIC_BUG << "Failed to write padding byte";
6630 return false;
6631 }
6632 }
6633 // Add a polite greeting in case a human sees this in tcpdump.
6634 static const char polite_greeting[] =
6635 "This packet only exists to trigger IETF QUIC version negotiation. "
6636 "Please respond with a Version Negotiation packet indicating what "
6637 "versions you support. Thank you and have a nice day.";
6638 if (!writer.WriteBytes(polite_greeting, sizeof(polite_greeting))) {
6639 QUIC_BUG << "Failed to write polite greeting";
6640 return false;
6641 }
6642 // Fill the rest of the packet with zeroes.
6643 writer.WritePadding();
6644 DCHECK_EQ(0u, writer.remaining());
6645 return true;
6646}
6647
6648// static
6649bool QuicFramer::ParseServerVersionNegotiationProbeResponse(
6650 const char* packet_bytes,
6651 QuicByteCount packet_length,
6652 char* source_connection_id_bytes,
6653 uint8_t* source_connection_id_length_out,
6654 std::string* detailed_error) {
6655 if (detailed_error == nullptr) {
6656 QUIC_BUG << "Invalid error_details";
6657 return false;
6658 }
6659 *detailed_error = "";
6660 if (packet_bytes == nullptr) {
6661 *detailed_error = "Invalid packet_bytes";
6662 return false;
6663 }
6664 if (packet_length < 6) {
6665 *detailed_error = "Invalid packet_length";
6666 return false;
6667 }
6668 if (source_connection_id_bytes == nullptr) {
6669 *detailed_error = "Invalid source_connection_id_bytes";
6670 return false;
6671 }
6672 if (source_connection_id_length_out == nullptr) {
6673 *detailed_error = "Invalid source_connection_id_length_out";
6674 return false;
6675 }
6676 QuicDataReader reader(packet_bytes, packet_length);
6677 uint8_t type_byte = 0;
6678 if (!reader.ReadUInt8(&type_byte)) {
6679 *detailed_error = "Failed to read type byte";
6680 return false;
6681 }
6682 if ((type_byte & 0x80) == 0) {
6683 *detailed_error = "Packet does not have long header";
6684 return false;
6685 }
6686 uint32_t version = 0;
6687 if (!reader.ReadUInt32(&version)) {
6688 *detailed_error = "Failed to read version";
6689 return false;
6690 }
6691 if (version != 0) {
6692 *detailed_error = "Packet is not a version negotiation packet";
6693 return false;
6694 }
dschinazi48ac9192019-07-31 00:07:26 -07006695 const bool use_length_prefix =
6696 GetQuicFlag(FLAGS_quic_prober_uses_length_prefixed_connection_ids);
dschinazide0f6dc2019-05-15 16:10:11 -07006697 QuicConnectionId destination_connection_id, source_connection_id;
dschinazi48ac9192019-07-31 00:07:26 -07006698 if (use_length_prefix) {
6699 if (!reader.ReadLengthPrefixedConnectionId(&destination_connection_id)) {
6700 *detailed_error = "Failed to read destination connection ID";
6701 return false;
6702 }
6703 if (!reader.ReadLengthPrefixedConnectionId(&source_connection_id)) {
6704 *detailed_error = "Failed to read source connection ID";
6705 return false;
6706 }
6707 } else {
6708 uint8_t expected_server_connection_id_length = 0,
6709 destination_connection_id_length = 0,
6710 source_connection_id_length = 0;
6711 if (!ProcessAndValidateIetfConnectionIdLength(
6712 &reader, UnsupportedQuicVersion(), Perspective::IS_CLIENT,
6713 /*should_update_expected_server_connection_id_length=*/true,
6714 &expected_server_connection_id_length,
6715 &destination_connection_id_length, &source_connection_id_length,
6716 detailed_error)) {
6717 return false;
6718 }
6719 if (!reader.ReadConnectionId(&destination_connection_id,
6720 destination_connection_id_length)) {
6721 *detailed_error = "Failed to read destination connection ID";
6722 return false;
6723 }
6724 if (!reader.ReadConnectionId(&source_connection_id,
6725 source_connection_id_length)) {
6726 *detailed_error = "Failed to read source connection ID";
6727 return false;
6728 }
dschinazide0f6dc2019-05-15 16:10:11 -07006729 }
dschinazi48ac9192019-07-31 00:07:26 -07006730
6731 if (destination_connection_id.length() != 0) {
6732 *detailed_error = "Received unexpected destination connection ID length";
dschinazide0f6dc2019-05-15 16:10:11 -07006733 return false;
6734 }
6735
dschinaziccbe0e02019-08-13 12:15:00 -07006736 if (!use_length_prefix && source_connection_id.length() == 0) {
6737 // We received a bad response due to b/139330014.
6738 // Reparse the packet assuming length prefixes.
6739 // This is a temporary client-side workaround until cl/263172621 is
6740 // deployed on production servers.
6741 // TODO(dschinazi): remove this client-side workaround once the server-side
6742 // fix is deployed.
6743 QuicDataReader reader2(packet_bytes, packet_length);
6744 uint8_t type_byte2 = 0;
6745 uint32_t version2 = 0;
6746 QuicConnectionId destination_connection_id2, source_connection_id2;
6747 if (reader2.ReadUInt8(&type_byte2) && reader2.ReadUInt32(&version2) &&
6748 reader2.ReadLengthPrefixedConnectionId(&destination_connection_id2) &&
6749 reader2.ReadLengthPrefixedConnectionId(&source_connection_id2) &&
6750 (type_byte2 & 0x80) != 0 && version2 == 0 &&
6751 destination_connection_id2.length() == 0 &&
6752 source_connection_id2.length() != 0) {
6753 source_connection_id = source_connection_id2;
6754 }
6755 }
6756
dschinazide0f6dc2019-05-15 16:10:11 -07006757 memcpy(source_connection_id_bytes, source_connection_id.data(),
dschinazi48ac9192019-07-31 00:07:26 -07006758 source_connection_id.length());
6759 *source_connection_id_length_out = source_connection_id.length();
dschinazide0f6dc2019-05-15 16:10:11 -07006760
6761 return true;
6762}
6763
fkastenholzb4dade72019-08-05 06:54:20 -07006764// Look for and parse the error code from the "<quic_error_code>:" text that
6765// may be present at the start of the CONNECTION_CLOSE error details string.
6766// This text, inserted by the peer if it's using Google's QUIC implementation,
6767// contains additional error information that narrows down the exact error. If
6768// the string is not found, or is not properly formed, it returns
6769// ErrorCode::QUIC_IETF_GQUIC_ERROR_MISSING
fkastenholz488a4622019-08-26 06:24:46 -07006770void MaybeExtractQuicErrorCode(QuicConnectionCloseFrame* frame) {
6771 std::vector<QuicStringPiece> ed =
6772 QuicTextUtils::Split(frame->error_details, ':');
fkastenholzb4dade72019-08-05 06:54:20 -07006773 uint64_t extracted_error_code;
6774 if (ed.size() < 2 || !QuicTextUtils::IsAllDigits(ed[0]) ||
6775 !QuicTextUtils::StringToUint64(ed[0], &extracted_error_code)) {
fkastenholz488a4622019-08-26 06:24:46 -07006776 frame->extracted_error_code = QUIC_IETF_GQUIC_ERROR_MISSING;
6777 return;
fkastenholzb4dade72019-08-05 06:54:20 -07006778 }
fkastenholz488a4622019-08-26 06:24:46 -07006779 // Return the error code (numeric) and the error details string without the
6780 // error code prefix. Note that Split returns everything up to, but not
6781 // including, the split character, so the length of ed[0] is just the number
6782 // of digits in the error number. In removing the prefix, 1 is added to the
6783 // length to account for the :
6784 QuicStringPiece x = QuicStringPiece(frame->error_details);
6785 x.remove_prefix(ed[0].length() + 1);
6786 frame->error_details = std::string(x);
6787 frame->extracted_error_code =
6788 static_cast<QuicErrorCode>(extracted_error_code);
fkastenholzb4dade72019-08-05 06:54:20 -07006789}
6790
QUICHE teama6ef0a62019-03-07 20:34:33 -05006791#undef ENDPOINT // undef for jumbo builds
6792} // namespace quic