blob: 6b55cfcaa2837a442f901ee3406b5a4a03445dad [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) {
dschinaziecad9642019-10-01 10:44:17 -0700866 QUIC_BUG_IF(header.version_flag &&
867 VersionHasIetfInvariantHeader(transport_version()) &&
868 header.long_packet_type == RETRY && !frames.empty())
869 << "IETF RETRY packets cannot contain frames " << header;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500870 QuicDataWriter writer(packet_length, buffer);
871 size_t length_field_offset = 0;
872 if (!AppendPacketHeader(header, &writer, &length_field_offset)) {
873 QUIC_BUG << "AppendPacketHeader failed";
874 return 0;
875 }
876
fkastenholz305e1732019-06-18 05:01:22 -0700877 if (VersionHasIetfQuicFrames(transport_version())) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500878 if (AppendIetfFrames(frames, &writer) == 0) {
879 return 0;
880 }
881 if (!WriteIetfLongHeaderLength(header, &writer, length_field_offset,
882 level)) {
883 return 0;
884 }
885 return writer.length();
886 }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500887
888 size_t i = 0;
889 for (const QuicFrame& frame : frames) {
890 // Determine if we should write stream frame length in header.
891 const bool last_frame_in_packet = i == frames.size() - 1;
892 if (!AppendTypeByte(frame, last_frame_in_packet, &writer)) {
893 QUIC_BUG << "AppendTypeByte failed";
894 return 0;
895 }
896
897 switch (frame.type) {
898 case PADDING_FRAME:
899 if (!AppendPaddingFrame(frame.padding_frame, &writer)) {
900 QUIC_BUG << "AppendPaddingFrame of "
901 << frame.padding_frame.num_padding_bytes << " failed";
902 return 0;
903 }
904 break;
905 case STREAM_FRAME:
906 if (!AppendStreamFrame(frame.stream_frame, last_frame_in_packet,
907 &writer)) {
908 QUIC_BUG << "AppendStreamFrame failed";
909 return 0;
910 }
911 break;
912 case ACK_FRAME:
913 if (!AppendAckFrameAndTypeByte(*frame.ack_frame, &writer)) {
914 QUIC_BUG << "AppendAckFrameAndTypeByte failed: " << detailed_error_;
915 return 0;
916 }
917 break;
918 case STOP_WAITING_FRAME:
919 if (!AppendStopWaitingFrame(header, frame.stop_waiting_frame,
920 &writer)) {
921 QUIC_BUG << "AppendStopWaitingFrame failed";
922 return 0;
923 }
924 break;
925 case MTU_DISCOVERY_FRAME:
926 // MTU discovery frames are serialized as ping frames.
927 QUIC_FALLTHROUGH_INTENDED;
928 case PING_FRAME:
929 // Ping has no payload.
930 break;
931 case RST_STREAM_FRAME:
932 if (!AppendRstStreamFrame(*frame.rst_stream_frame, &writer)) {
933 QUIC_BUG << "AppendRstStreamFrame failed";
934 return 0;
935 }
936 break;
937 case CONNECTION_CLOSE_FRAME:
938 if (!AppendConnectionCloseFrame(*frame.connection_close_frame,
939 &writer)) {
940 QUIC_BUG << "AppendConnectionCloseFrame failed";
941 return 0;
942 }
943 break;
944 case GOAWAY_FRAME:
945 if (!AppendGoAwayFrame(*frame.goaway_frame, &writer)) {
946 QUIC_BUG << "AppendGoAwayFrame failed";
947 return 0;
948 }
949 break;
950 case WINDOW_UPDATE_FRAME:
951 if (!AppendWindowUpdateFrame(*frame.window_update_frame, &writer)) {
952 QUIC_BUG << "AppendWindowUpdateFrame failed";
953 return 0;
954 }
955 break;
956 case BLOCKED_FRAME:
957 if (!AppendBlockedFrame(*frame.blocked_frame, &writer)) {
958 QUIC_BUG << "AppendBlockedFrame failed";
959 return 0;
960 }
961 break;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500962 case NEW_CONNECTION_ID_FRAME:
963 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -0700964 "Attempt to append NEW_CONNECTION_ID frame and not in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -0500965 return RaiseError(QUIC_INTERNAL_ERROR);
966 case RETIRE_CONNECTION_ID_FRAME:
967 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -0700968 "Attempt to append RETIRE_CONNECTION_ID frame and not in IETF "
969 "QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -0500970 return RaiseError(QUIC_INTERNAL_ERROR);
971 case NEW_TOKEN_FRAME:
972 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -0700973 "Attempt to append NEW_TOKEN_ID 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 MAX_STREAMS_FRAME:
QUICHE teama6ef0a62019-03-07 20:34:33 -0500976 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -0700977 "Attempt to append MAX_STREAMS frame and not in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -0500978 return RaiseError(QUIC_INTERNAL_ERROR);
fkastenholz3c4eabf2019-04-22 07:49:59 -0700979 case STREAMS_BLOCKED_FRAME:
QUICHE teama6ef0a62019-03-07 20:34:33 -0500980 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -0700981 "Attempt to append STREAMS_BLOCKED frame and not in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -0500982 return RaiseError(QUIC_INTERNAL_ERROR);
983 case PATH_RESPONSE_FRAME:
984 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -0700985 "Attempt to append PATH_RESPONSE frame and not in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -0500986 return RaiseError(QUIC_INTERNAL_ERROR);
987 case PATH_CHALLENGE_FRAME:
988 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -0700989 "Attempt to append PATH_CHALLENGE frame and not in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -0500990 return RaiseError(QUIC_INTERNAL_ERROR);
991 case STOP_SENDING_FRAME:
992 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -0700993 "Attempt to append STOP_SENDING frame and not in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -0500994 return RaiseError(QUIC_INTERNAL_ERROR);
995 case MESSAGE_FRAME:
996 if (!AppendMessageFrameAndTypeByte(*frame.message_frame,
997 last_frame_in_packet, &writer)) {
998 QUIC_BUG << "AppendMessageFrame failed";
999 return 0;
1000 }
1001 break;
1002 case CRYPTO_FRAME:
QUICHE teamea740082019-03-11 17:58:43 -07001003 if (!QuicVersionUsesCryptoFrames(version_.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001004 set_detailed_error(
1005 "Attempt to append CRYPTO frame in version prior to 47.");
1006 return RaiseError(QUIC_INTERNAL_ERROR);
1007 }
1008 if (!AppendCryptoFrame(*frame.crypto_frame, &writer)) {
1009 QUIC_BUG << "AppendCryptoFrame failed";
1010 return 0;
1011 }
1012 break;
1013 default:
1014 RaiseError(QUIC_INVALID_FRAME_DATA);
1015 QUIC_BUG << "QUIC_INVALID_FRAME_DATA";
1016 return 0;
1017 }
1018 ++i;
1019 }
1020
dschinazid1428492019-09-17 23:59:30 -07001021 if (!WriteIetfLongHeaderLength(header, &writer, length_field_offset, level)) {
1022 return 0;
1023 }
1024
QUICHE teama6ef0a62019-03-07 20:34:33 -05001025 return writer.length();
1026}
1027
1028size_t QuicFramer::AppendIetfFrames(const QuicFrames& frames,
1029 QuicDataWriter* writer) {
1030 size_t i = 0;
1031 for (const QuicFrame& frame : frames) {
1032 // Determine if we should write stream frame length in header.
1033 const bool last_frame_in_packet = i == frames.size() - 1;
1034 if (!AppendIetfTypeByte(frame, last_frame_in_packet, writer)) {
1035 QUIC_BUG << "AppendIetfTypeByte failed: " << detailed_error();
1036 return 0;
1037 }
1038
1039 switch (frame.type) {
1040 case PADDING_FRAME:
1041 if (!AppendPaddingFrame(frame.padding_frame, writer)) {
1042 QUIC_BUG << "AppendPaddingFrame of "
1043 << frame.padding_frame.num_padding_bytes
1044 << " failed: " << detailed_error();
1045 return 0;
1046 }
1047 break;
1048 case STREAM_FRAME:
1049 if (!AppendStreamFrame(frame.stream_frame, last_frame_in_packet,
1050 writer)) {
1051 QUIC_BUG << "AppendStreamFrame failed: " << detailed_error();
1052 return 0;
1053 }
1054 break;
1055 case ACK_FRAME:
1056 if (!AppendIetfAckFrameAndTypeByte(*frame.ack_frame, writer)) {
QUICHE team4fe0b942019-03-08 09:25:06 -05001057 QUIC_BUG << "AppendIetfAckFrameAndTypeByte failed: "
1058 << detailed_error();
QUICHE teama6ef0a62019-03-07 20:34:33 -05001059 return 0;
1060 }
1061 break;
1062 case STOP_WAITING_FRAME:
1063 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -07001064 "Attempt to append STOP WAITING frame in IETF QUIC.");
dschinazi4a64ab62019-10-01 12:54:00 -07001065 RaiseError(QUIC_INTERNAL_ERROR);
1066 QUIC_BUG << detailed_error();
1067 return 0;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001068 case MTU_DISCOVERY_FRAME:
1069 // MTU discovery frames are serialized as ping frames.
1070 QUIC_FALLTHROUGH_INTENDED;
1071 case PING_FRAME:
1072 // Ping has no payload.
1073 break;
1074 case RST_STREAM_FRAME:
1075 if (!AppendRstStreamFrame(*frame.rst_stream_frame, writer)) {
1076 QUIC_BUG << "AppendRstStreamFrame failed: " << detailed_error();
1077 return 0;
1078 }
1079 break;
1080 case CONNECTION_CLOSE_FRAME:
fkastenholz72f509b2019-04-10 09:17:49 -07001081 if (!AppendIetfConnectionCloseFrame(*frame.connection_close_frame,
1082 writer)) {
1083 QUIC_BUG << "AppendIetfConnectionCloseFrame failed: "
1084 << detailed_error();
QUICHE teama6ef0a62019-03-07 20:34:33 -05001085 return 0;
1086 }
1087 break;
1088 case GOAWAY_FRAME:
fkastenholz305e1732019-06-18 05:01:22 -07001089 set_detailed_error("Attempt to append GOAWAY frame in IETF QUIC.");
dschinazi4a64ab62019-10-01 12:54:00 -07001090 RaiseError(QUIC_INTERNAL_ERROR);
1091 QUIC_BUG << detailed_error();
1092 return 0;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001093 case WINDOW_UPDATE_FRAME:
1094 // Depending on whether there is a stream ID or not, will be either a
1095 // MAX STREAM DATA frame or a MAX DATA frame.
1096 if (frame.window_update_frame->stream_id ==
1097 QuicUtils::GetInvalidStreamId(transport_version())) {
1098 if (!AppendMaxDataFrame(*frame.window_update_frame, writer)) {
1099 QUIC_BUG << "AppendMaxDataFrame failed: " << detailed_error();
1100 return 0;
1101 }
1102 } else {
1103 if (!AppendMaxStreamDataFrame(*frame.window_update_frame, writer)) {
1104 QUIC_BUG << "AppendMaxStreamDataFrame failed: " << detailed_error();
1105 return 0;
1106 }
1107 }
1108 break;
1109 case BLOCKED_FRAME:
1110 if (!AppendBlockedFrame(*frame.blocked_frame, writer)) {
1111 QUIC_BUG << "AppendBlockedFrame failed: " << detailed_error();
1112 return 0;
1113 }
1114 break;
fkastenholz3c4eabf2019-04-22 07:49:59 -07001115 case MAX_STREAMS_FRAME:
1116 if (!AppendMaxStreamsFrame(frame.max_streams_frame, writer)) {
dschinazi4a64ab62019-10-01 12:54:00 -07001117 QUIC_BUG << "AppendMaxStreamsFrame failed: " << detailed_error();
QUICHE teama6ef0a62019-03-07 20:34:33 -05001118 return 0;
1119 }
1120 break;
fkastenholz3c4eabf2019-04-22 07:49:59 -07001121 case STREAMS_BLOCKED_FRAME:
1122 if (!AppendStreamsBlockedFrame(frame.streams_blocked_frame, writer)) {
dschinazi4a64ab62019-10-01 12:54:00 -07001123 QUIC_BUG << "AppendStreamsBlockedFrame failed: " << detailed_error();
QUICHE teama6ef0a62019-03-07 20:34:33 -05001124 return 0;
1125 }
1126 break;
1127 case NEW_CONNECTION_ID_FRAME:
1128 if (!AppendNewConnectionIdFrame(*frame.new_connection_id_frame,
1129 writer)) {
1130 QUIC_BUG << "AppendNewConnectionIdFrame failed: " << detailed_error();
1131 return 0;
1132 }
1133 break;
1134 case RETIRE_CONNECTION_ID_FRAME:
1135 if (!AppendRetireConnectionIdFrame(*frame.retire_connection_id_frame,
1136 writer)) {
1137 QUIC_BUG << "AppendRetireConnectionIdFrame failed: "
1138 << detailed_error();
1139 return 0;
1140 }
1141 break;
1142 case NEW_TOKEN_FRAME:
1143 if (!AppendNewTokenFrame(*frame.new_token_frame, writer)) {
1144 QUIC_BUG << "AppendNewTokenFrame failed: " << detailed_error();
1145 return 0;
1146 }
1147 break;
1148 case STOP_SENDING_FRAME:
1149 if (!AppendStopSendingFrame(*frame.stop_sending_frame, writer)) {
1150 QUIC_BUG << "AppendStopSendingFrame failed: " << detailed_error();
1151 return 0;
1152 }
1153 break;
1154 case PATH_CHALLENGE_FRAME:
1155 if (!AppendPathChallengeFrame(*frame.path_challenge_frame, writer)) {
1156 QUIC_BUG << "AppendPathChallengeFrame failed: " << detailed_error();
1157 return 0;
1158 }
1159 break;
1160 case PATH_RESPONSE_FRAME:
1161 if (!AppendPathResponseFrame(*frame.path_response_frame, writer)) {
1162 QUIC_BUG << "AppendPathResponseFrame failed: " << detailed_error();
1163 return 0;
1164 }
1165 break;
1166 case MESSAGE_FRAME:
1167 if (!AppendMessageFrameAndTypeByte(*frame.message_frame,
1168 last_frame_in_packet, writer)) {
1169 QUIC_BUG << "AppendMessageFrame failed: " << detailed_error();
1170 return 0;
1171 }
1172 break;
1173 case CRYPTO_FRAME:
1174 if (!AppendCryptoFrame(*frame.crypto_frame, writer)) {
1175 QUIC_BUG << "AppendCryptoFrame failed: " << detailed_error();
1176 return 0;
1177 }
1178 break;
1179 default:
QUICHE teama6ef0a62019-03-07 20:34:33 -05001180 set_detailed_error("Tried to append unknown frame type.");
dschinazi4a64ab62019-10-01 12:54:00 -07001181 RaiseError(QUIC_INVALID_FRAME_DATA);
1182 QUIC_BUG << "QUIC_INVALID_FRAME_DATA: " << frame.type;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001183 return 0;
1184 }
1185 ++i;
1186 }
1187
1188 return writer->length();
1189}
1190
rch67cb9df2019-03-26 16:52:07 -07001191size_t QuicFramer::BuildConnectivityProbingPacket(
QUICHE teama6ef0a62019-03-07 20:34:33 -05001192 const QuicPacketHeader& header,
1193 char* buffer,
1194 size_t packet_length,
1195 EncryptionLevel level) {
1196 QuicFrames frames;
1197
1198 // Write a PING frame, which has no data payload.
1199 QuicPingFrame ping_frame;
1200 frames.push_back(QuicFrame(ping_frame));
1201
1202 // Add padding to the rest of the packet.
1203 QuicPaddingFrame padding_frame;
1204 frames.push_back(QuicFrame(padding_frame));
1205
1206 return BuildDataPacket(header, frames, buffer, packet_length, level);
1207}
1208
QUICHE teama6ef0a62019-03-07 20:34:33 -05001209size_t QuicFramer::BuildPaddedPathChallengePacket(
1210 const QuicPacketHeader& header,
1211 char* buffer,
1212 size_t packet_length,
1213 QuicPathFrameBuffer* payload,
1214 QuicRandom* randomizer,
1215 EncryptionLevel level) {
fkastenholz305e1732019-06-18 05:01:22 -07001216 if (!VersionHasIetfQuicFrames(version_.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001217 QUIC_BUG << "Attempt to build a PATH_CHALLENGE Connectivity Probing "
1218 "packet and not doing IETF QUIC";
1219 return 0;
1220 }
1221 QuicFrames frames;
1222
1223 // Write a PATH_CHALLENGE frame, which has a random 8-byte payload
1224 randomizer->RandBytes(payload->data(), payload->size());
1225
1226 QuicPathChallengeFrame path_challenge_frame(0, *payload);
1227 frames.push_back(QuicFrame(&path_challenge_frame));
1228
1229 // Add padding to the rest of the packet in order to assess Path MTU
1230 // characteristics.
1231 QuicPaddingFrame padding_frame;
1232 frames.push_back(QuicFrame(padding_frame));
1233
1234 return BuildDataPacket(header, frames, buffer, packet_length, level);
1235}
1236
1237size_t QuicFramer::BuildPathResponsePacket(
1238 const QuicPacketHeader& header,
1239 char* buffer,
1240 size_t packet_length,
1241 const QuicDeque<QuicPathFrameBuffer>& payloads,
1242 const bool is_padded,
1243 EncryptionLevel level) {
1244 if (payloads.empty()) {
1245 QUIC_BUG
1246 << "Attempt to generate connectivity response with no request payloads";
1247 return 0;
1248 }
fkastenholz305e1732019-06-18 05:01:22 -07001249 if (!VersionHasIetfQuicFrames(version_.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001250 QUIC_BUG << "Attempt to build a PATH_RESPONSE Connectivity Probing "
1251 "packet and not doing IETF QUIC";
1252 return 0;
1253 }
1254
1255 std::vector<std::unique_ptr<QuicPathResponseFrame>> path_response_frames;
1256 for (const QuicPathFrameBuffer& payload : payloads) {
1257 // Note that the control frame ID can be 0 since this is not retransmitted.
1258 path_response_frames.push_back(
vasilvv0fc587f2019-09-06 13:33:08 -07001259 std::make_unique<QuicPathResponseFrame>(0, payload));
QUICHE teama6ef0a62019-03-07 20:34:33 -05001260 }
1261
1262 QuicFrames frames;
1263 for (const std::unique_ptr<QuicPathResponseFrame>& path_response_frame :
1264 path_response_frames) {
1265 frames.push_back(QuicFrame(path_response_frame.get()));
1266 }
1267
1268 if (is_padded) {
1269 // Add padding to the rest of the packet in order to assess Path MTU
1270 // characteristics.
1271 QuicPaddingFrame padding_frame;
1272 frames.push_back(QuicFrame(padding_frame));
1273 }
1274
1275 return BuildDataPacket(header, frames, buffer, packet_length, level);
1276}
1277
1278// static
1279std::unique_ptr<QuicEncryptedPacket> QuicFramer::BuildPublicResetPacket(
1280 const QuicPublicResetPacket& packet) {
1281 CryptoHandshakeMessage reset;
1282 reset.set_tag(kPRST);
1283 reset.SetValue(kRNON, packet.nonce_proof);
1284 if (packet.client_address.host().address_family() !=
1285 IpAddressFamily::IP_UNSPEC) {
1286 // packet.client_address is non-empty.
1287 QuicSocketAddressCoder address_coder(packet.client_address);
vasilvvc48c8712019-03-11 13:38:16 -07001288 std::string serialized_address = address_coder.Encode();
QUICHE teama6ef0a62019-03-07 20:34:33 -05001289 if (serialized_address.empty()) {
1290 return nullptr;
1291 }
1292 reset.SetStringPiece(kCADR, serialized_address);
1293 }
1294 if (!packet.endpoint_id.empty()) {
1295 reset.SetStringPiece(kEPID, packet.endpoint_id);
1296 }
1297 const QuicData& reset_serialized = reset.GetSerialized();
1298
1299 size_t len = kPublicFlagsSize + packet.connection_id.length() +
1300 reset_serialized.length();
1301 std::unique_ptr<char[]> buffer(new char[len]);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001302 QuicDataWriter writer(len, buffer.get());
1303
1304 uint8_t flags = static_cast<uint8_t>(PACKET_PUBLIC_FLAGS_RST |
1305 PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID);
1306 // This hack makes post-v33 public reset packet look like pre-v33 packets.
1307 flags |= static_cast<uint8_t>(PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID_OLD);
1308 if (!writer.WriteUInt8(flags)) {
1309 return nullptr;
1310 }
1311
1312 if (!writer.WriteConnectionId(packet.connection_id)) {
1313 return nullptr;
1314 }
1315
1316 if (!writer.WriteBytes(reset_serialized.data(), reset_serialized.length())) {
1317 return nullptr;
1318 }
1319
vasilvv0fc587f2019-09-06 13:33:08 -07001320 return std::make_unique<QuicEncryptedPacket>(buffer.release(), len, true);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001321}
1322
1323// static
1324std::unique_ptr<QuicEncryptedPacket> QuicFramer::BuildIetfStatelessResetPacket(
dschinazi17d42422019-06-18 16:35:07 -07001325 QuicConnectionId /*connection_id*/,
QUICHE teama6ef0a62019-03-07 20:34:33 -05001326 QuicUint128 stateless_reset_token) {
1327 QUIC_DVLOG(1) << "Building IETF stateless reset packet.";
1328 size_t len = kPacketHeaderTypeSize + kMinRandomBytesLengthInStatelessReset +
1329 sizeof(stateless_reset_token);
1330 std::unique_ptr<char[]> buffer(new char[len]);
1331 QuicDataWriter writer(len, buffer.get());
1332
1333 uint8_t type = 0;
1334 type |= FLAGS_FIXED_BIT;
1335 type |= FLAGS_SHORT_HEADER_RESERVED_1;
1336 type |= FLAGS_SHORT_HEADER_RESERVED_2;
fayang36825da2019-08-21 14:01:27 -07001337 type |= PacketNumberLengthToOnWireValue(PACKET_1BYTE_PACKET_NUMBER);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001338
1339 // Append type byte.
1340 if (!writer.WriteUInt8(type)) {
1341 return nullptr;
1342 }
1343 // Append random bytes.
1344 if (!writer.WriteRandomBytes(QuicRandom::GetInstance(),
1345 kMinRandomBytesLengthInStatelessReset)) {
1346 return nullptr;
1347 }
1348
1349 // Append stateless reset token.
1350 if (!writer.WriteBytes(&stateless_reset_token,
1351 sizeof(stateless_reset_token))) {
1352 return nullptr;
1353 }
vasilvv0fc587f2019-09-06 13:33:08 -07001354 return std::make_unique<QuicEncryptedPacket>(buffer.release(), len, true);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001355}
1356
1357// static
1358std::unique_ptr<QuicEncryptedPacket> QuicFramer::BuildVersionNegotiationPacket(
dschinazi8ff74822019-05-28 16:37:20 -07001359 QuicConnectionId server_connection_id,
dschinazib417d602019-05-29 13:08:45 -07001360 QuicConnectionId client_connection_id,
QUICHE teama6ef0a62019-03-07 20:34:33 -05001361 bool ietf_quic,
dschinazi48ac9192019-07-31 00:07:26 -07001362 bool use_length_prefix,
QUICHE teama6ef0a62019-03-07 20:34:33 -05001363 const ParsedQuicVersionVector& versions) {
dschinazi1ac22cc2019-06-25 11:47:50 -07001364 ParsedQuicVersionVector wire_versions = versions;
1365 if (!GetQuicReloadableFlag(quic_version_negotiation_grease)) {
1366 if (wire_versions.empty()) {
1367 wire_versions = {QuicVersionReservedForNegotiation()};
1368 }
1369 } else {
1370 // Add a version reserved for negotiation as suggested by the
1371 // "Using Reserved Versions" section of draft-ietf-quic-transport.
1372 QUIC_RELOADABLE_FLAG_COUNT_N(quic_version_negotiation_grease, 1, 2);
1373 if (wire_versions.empty()) {
1374 // Ensure that version negotiation packets we send have at least two
1375 // versions. This guarantees that, under all circumstances, all QUIC
1376 // packets we send are at least 14 bytes long.
1377 wire_versions = {QuicVersionReservedForNegotiation(),
1378 QuicVersionReservedForNegotiation()};
1379 } else {
1380 // This is not uniformely distributed but is acceptable since no security
1381 // depends on this randomness.
1382 size_t version_index = 0;
1383 const bool disable_randomness =
1384 GetQuicFlag(FLAGS_quic_disable_version_negotiation_grease_randomness);
1385 if (!disable_randomness) {
1386 version_index = QuicRandom::GetInstance()->RandUint64() %
1387 (wire_versions.size() + 1);
1388 }
1389 wire_versions.insert(wire_versions.begin() + version_index,
1390 QuicVersionReservedForNegotiation());
1391 }
1392 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001393 if (ietf_quic) {
dschinazi1ac22cc2019-06-25 11:47:50 -07001394 return BuildIetfVersionNegotiationPacket(
dschinazi48ac9192019-07-31 00:07:26 -07001395 use_length_prefix, server_connection_id, client_connection_id,
1396 wire_versions);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001397 }
dschinazib417d602019-05-29 13:08:45 -07001398
1399 // The GQUIC encoding does not support encoding client connection IDs.
1400 DCHECK(client_connection_id.IsEmpty());
dschinazi48ac9192019-07-31 00:07:26 -07001401 // The GQUIC encoding does not support length-prefixed connection IDs.
1402 DCHECK(!use_length_prefix);
dschinazib417d602019-05-29 13:08:45 -07001403
dschinazi1ac22cc2019-06-25 11:47:50 -07001404 DCHECK(!wire_versions.empty());
dschinazi8ff74822019-05-28 16:37:20 -07001405 size_t len = kPublicFlagsSize + server_connection_id.length() +
dschinazi1ac22cc2019-06-25 11:47:50 -07001406 wire_versions.size() * kQuicVersionSize;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001407 std::unique_ptr<char[]> buffer(new char[len]);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001408 QuicDataWriter writer(len, buffer.get());
1409
1410 uint8_t flags = static_cast<uint8_t>(
1411 PACKET_PUBLIC_FLAGS_VERSION | PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID |
1412 // TODO(rch): Remove this QUIC_VERSION_32 is retired.
1413 PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID_OLD);
1414 if (!writer.WriteUInt8(flags)) {
1415 return nullptr;
1416 }
1417
dschinazi8ff74822019-05-28 16:37:20 -07001418 if (!writer.WriteConnectionId(server_connection_id)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001419 return nullptr;
1420 }
1421
dschinazi1ac22cc2019-06-25 11:47:50 -07001422 for (const ParsedQuicVersion& version : wire_versions) {
nharpereaab5ad2019-05-31 12:23:25 -07001423 if (!writer.WriteUInt32(CreateQuicVersionLabel(version))) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001424 return nullptr;
1425 }
1426 }
1427
vasilvv0fc587f2019-09-06 13:33:08 -07001428 return std::make_unique<QuicEncryptedPacket>(buffer.release(), len, true);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001429}
1430
1431// static
1432std::unique_ptr<QuicEncryptedPacket>
1433QuicFramer::BuildIetfVersionNegotiationPacket(
dschinazi48ac9192019-07-31 00:07:26 -07001434 bool use_length_prefix,
dschinazib417d602019-05-29 13:08:45 -07001435 QuicConnectionId server_connection_id,
1436 QuicConnectionId client_connection_id,
QUICHE teama6ef0a62019-03-07 20:34:33 -05001437 const ParsedQuicVersionVector& versions) {
dschinazi48ac9192019-07-31 00:07:26 -07001438 QUIC_DVLOG(1) << "Building IETF version negotiation packet with"
1439 << (use_length_prefix ? "" : "out")
1440 << " length prefix, server_connection_id "
1441 << server_connection_id << " client_connection_id "
1442 << client_connection_id << " versions "
dschinazi5a354c92019-05-09 12:18:53 -07001443 << ParsedQuicVersionVectorToString(versions);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001444 DCHECK(!versions.empty());
1445 size_t len = kPacketHeaderTypeSize + kConnectionIdLengthSize +
dschinazib417d602019-05-29 13:08:45 -07001446 client_connection_id.length() + server_connection_id.length() +
QUICHE teama6ef0a62019-03-07 20:34:33 -05001447 (versions.size() + 1) * kQuicVersionSize;
dschinazi48ac9192019-07-31 00:07:26 -07001448 if (use_length_prefix) {
1449 // When using length-prefixed connection IDs, packets carry two lengths
1450 // instead of one.
1451 len += kConnectionIdLengthSize;
1452 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001453 std::unique_ptr<char[]> buffer(new char[len]);
1454 QuicDataWriter writer(len, buffer.get());
1455
1456 // TODO(fayang): Randomly select a value for the type.
dschinazi0366de92019-06-18 20:00:27 -07001457 uint8_t type = static_cast<uint8_t>(FLAGS_LONG_HEADER | FLAGS_FIXED_BIT);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001458 if (!writer.WriteUInt8(type)) {
1459 return nullptr;
1460 }
1461
1462 if (!writer.WriteUInt32(0)) {
1463 return nullptr;
1464 }
1465
dschinazi48ac9192019-07-31 00:07:26 -07001466 if (!AppendIetfConnectionIds(true, use_length_prefix, client_connection_id,
1467 server_connection_id, &writer)) {
dschinazi1f485a12019-05-13 11:57:01 -07001468 return nullptr;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001469 }
1470
1471 for (const ParsedQuicVersion& version : versions) {
nharpereaab5ad2019-05-31 12:23:25 -07001472 if (!writer.WriteUInt32(CreateQuicVersionLabel(version))) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001473 return nullptr;
1474 }
1475 }
1476
vasilvv0fc587f2019-09-06 13:33:08 -07001477 return std::make_unique<QuicEncryptedPacket>(buffer.release(), len, true);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001478}
1479
1480bool QuicFramer::ProcessPacket(const QuicEncryptedPacket& packet) {
1481 QuicDataReader reader(packet.data(), packet.length());
1482
1483 bool packet_has_ietf_packet_header = false;
1484 if (infer_packet_header_type_from_version_) {
1485 packet_has_ietf_packet_header =
fayangd4291e42019-05-30 10:31:21 -07001486 VersionHasIetfInvariantHeader(version_.transport_version);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001487 } else if (!reader.IsDoneReading()) {
1488 uint8_t type = reader.PeekByte();
1489 packet_has_ietf_packet_header = QuicUtils::IsIetfPacketHeader(type);
1490 }
1491 if (packet_has_ietf_packet_header) {
1492 QUIC_DVLOG(1) << ENDPOINT << "Processing IETF QUIC packet.";
1493 }
1494
1495 visitor_->OnPacket();
1496
1497 QuicPacketHeader header;
1498 if (!ProcessPublicHeader(&reader, packet_has_ietf_packet_header, &header)) {
1499 DCHECK_NE("", detailed_error_);
1500 QUIC_DVLOG(1) << ENDPOINT << "Unable to process public header. Error: "
1501 << detailed_error_;
1502 DCHECK_NE("", detailed_error_);
1503 RecordDroppedPacketReason(DroppedPacketReason::INVALID_PUBLIC_HEADER);
1504 return RaiseError(QUIC_INVALID_PACKET_HEADER);
1505 }
1506
1507 if (!visitor_->OnUnauthenticatedPublicHeader(header)) {
1508 // The visitor suppresses further processing of the packet.
1509 return true;
1510 }
1511
dschinazie0df3f72019-05-06 16:37:51 -07001512 if (IsVersionNegotiation(header, packet_has_ietf_packet_header)) {
dschinazi072da7c2019-05-07 17:57:42 -07001513 if (perspective_ == Perspective::IS_CLIENT) {
1514 QUIC_DVLOG(1) << "Client received version negotiation packet";
1515 return ProcessVersionNegotiationPacket(&reader, header);
1516 } else {
1517 QUIC_DLOG(ERROR) << "Server received version negotiation packet";
1518 set_detailed_error("Server received version negotiation packet.");
1519 return RaiseError(QUIC_INVALID_VERSION_NEGOTIATION_PACKET);
1520 }
dschinazie0df3f72019-05-06 16:37:51 -07001521 }
1522
1523 if (header.version_flag && header.version != version_) {
1524 if (perspective_ == Perspective::IS_SERVER) {
fayang8aba1ff2019-06-21 12:00:54 -07001525 if (!visitor_->OnProtocolVersionMismatch(header.version)) {
dschinazie0df3f72019-05-06 16:37:51 -07001526 RecordDroppedPacketReason(DroppedPacketReason::VERSION_MISMATCH);
1527 return true;
1528 }
1529 } else {
1530 // A client received a packet of a different version but that packet is
1531 // not a version negotiation packet. It is therefore invalid and dropped.
1532 QUIC_DLOG(ERROR) << "Client received unexpected version "
1533 << ParsedQuicVersionToString(header.version)
1534 << " instead of " << ParsedQuicVersionToString(version_);
1535 set_detailed_error("Client received unexpected version.");
1536 return RaiseError(QUIC_INVALID_VERSION);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001537 }
1538 }
1539
1540 bool rv;
dschinazie0df3f72019-05-06 16:37:51 -07001541 if (header.long_packet_type == RETRY) {
dschinazi244f6dc2019-05-06 15:45:16 -07001542 rv = ProcessRetryPacket(&reader, header);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001543 } else if (header.reset_flag) {
1544 rv = ProcessPublicResetPacket(&reader, header);
dschinazie8d7fa72019-04-05 14:44:40 -07001545 } else if (packet.length() <= kMaxIncomingPacketSize) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001546 // The optimized decryption algorithm implementations run faster when
1547 // operating on aligned memory.
dschinazie8d7fa72019-04-05 14:44:40 -07001548 QUIC_CACHELINE_ALIGNED char buffer[kMaxIncomingPacketSize];
QUICHE teama6ef0a62019-03-07 20:34:33 -05001549 if (packet_has_ietf_packet_header) {
1550 rv = ProcessIetfDataPacket(&reader, &header, packet, buffer,
dschinazie8d7fa72019-04-05 14:44:40 -07001551 QUIC_ARRAYSIZE(buffer));
QUICHE teama6ef0a62019-03-07 20:34:33 -05001552 } else {
dschinazie8d7fa72019-04-05 14:44:40 -07001553 rv = ProcessDataPacket(&reader, &header, packet, buffer,
1554 QUIC_ARRAYSIZE(buffer));
QUICHE teama6ef0a62019-03-07 20:34:33 -05001555 }
1556 } else {
1557 std::unique_ptr<char[]> large_buffer(new char[packet.length()]);
1558 if (packet_has_ietf_packet_header) {
1559 rv = ProcessIetfDataPacket(&reader, &header, packet, large_buffer.get(),
1560 packet.length());
1561 } else {
1562 rv = ProcessDataPacket(&reader, &header, packet, large_buffer.get(),
1563 packet.length());
1564 }
1565 QUIC_BUG_IF(rv) << "QUIC should never successfully process packets larger"
dschinazie8d7fa72019-04-05 14:44:40 -07001566 << "than kMaxIncomingPacketSize. packet size:"
1567 << packet.length();
QUICHE teama6ef0a62019-03-07 20:34:33 -05001568 }
1569 return rv;
1570}
1571
1572bool QuicFramer::ProcessVersionNegotiationPacket(
1573 QuicDataReader* reader,
1574 const QuicPacketHeader& header) {
1575 DCHECK_EQ(Perspective::IS_CLIENT, perspective_);
1576
QUICHE team2252b702019-05-14 23:55:14 -04001577 QuicVersionNegotiationPacket packet(
1578 GetServerConnectionIdAsRecipient(header, perspective_));
QUICHE teama6ef0a62019-03-07 20:34:33 -05001579 // Try reading at least once to raise error if the packet is invalid.
1580 do {
1581 QuicVersionLabel version_label;
fayang40315542019-05-09 09:19:09 -07001582 if (!ProcessVersionLabel(reader, &version_label)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001583 set_detailed_error("Unable to read supported version in negotiation.");
1584 RecordDroppedPacketReason(
1585 DroppedPacketReason::INVALID_VERSION_NEGOTIATION_PACKET);
1586 return RaiseError(QUIC_INVALID_VERSION_NEGOTIATION_PACKET);
1587 }
nharper4fd11052019-06-04 14:23:22 -07001588 ParsedQuicVersion parsed_version = ParseQuicVersionLabel(version_label);
1589 if (parsed_version != UnsupportedQuicVersion()) {
1590 packet.versions.push_back(parsed_version);
1591 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001592 } while (!reader->IsDoneReading());
1593
dschinazi5a354c92019-05-09 12:18:53 -07001594 QUIC_DLOG(INFO) << ENDPOINT << "parsed version negotiation: "
1595 << ParsedQuicVersionVectorToString(packet.versions);
1596
QUICHE teama6ef0a62019-03-07 20:34:33 -05001597 visitor_->OnVersionNegotiationPacket(packet);
1598 return true;
1599}
1600
dschinazi244f6dc2019-05-06 15:45:16 -07001601bool QuicFramer::ProcessRetryPacket(QuicDataReader* reader,
1602 const QuicPacketHeader& header) {
1603 DCHECK_EQ(Perspective::IS_CLIENT, perspective_);
1604
dschinazi244f6dc2019-05-06 15:45:16 -07001605 QuicConnectionId original_destination_connection_id;
dschinazi48ac9192019-07-31 00:07:26 -07001606 if (version_.HasLengthPrefixedConnectionIds()) {
1607 // Parse Original Destination Connection ID.
1608 if (!reader->ReadLengthPrefixedConnectionId(
1609 &original_destination_connection_id)) {
1610 set_detailed_error("Unable to read Original Destination ConnectionId.");
1611 return false;
1612 }
1613 } else {
1614 // Parse Original Destination Connection ID Length.
1615 uint8_t odcil = header.type_byte & 0xf;
1616 if (odcil != 0) {
1617 odcil += kConnectionIdLengthAdjustment;
1618 }
1619
1620 // Parse Original Destination Connection ID.
1621 if (!reader->ReadConnectionId(&original_destination_connection_id, odcil)) {
1622 set_detailed_error("Unable to read Original Destination ConnectionId.");
1623 return false;
1624 }
dschinazi244f6dc2019-05-06 15:45:16 -07001625 }
1626
dschinazib953d022019-08-01 18:05:58 -07001627 if (!QuicUtils::IsConnectionIdValidForVersion(
1628 original_destination_connection_id, transport_version())) {
1629 set_detailed_error(
1630 "Received Original Destination ConnectionId with invalid length.");
1631 return false;
1632 }
1633
dschinazi244f6dc2019-05-06 15:45:16 -07001634 QuicStringPiece retry_token = reader->ReadRemainingPayload();
1635 visitor_->OnRetryPacket(original_destination_connection_id,
1636 header.source_connection_id, retry_token);
1637 return true;
1638}
1639
QUICHE teama6ef0a62019-03-07 20:34:33 -05001640// Seeks the current packet to check for a coalesced packet at the end.
1641// If the IETF length field only spans part of the outer packet,
1642// then there is a coalesced packet after this one.
1643void QuicFramer::MaybeProcessCoalescedPacket(
1644 const QuicDataReader& encrypted_reader,
1645 uint64_t remaining_bytes_length,
1646 const QuicPacketHeader& header) {
1647 if (header.remaining_packet_length >= remaining_bytes_length) {
1648 // There is no coalesced packet.
1649 return;
1650 }
1651
1652 QuicStringPiece remaining_data = encrypted_reader.PeekRemainingPayload();
1653 DCHECK_EQ(remaining_data.length(), remaining_bytes_length);
1654
1655 const char* coalesced_data =
1656 remaining_data.data() + header.remaining_packet_length;
1657 uint64_t coalesced_data_length =
1658 remaining_bytes_length - header.remaining_packet_length;
1659 QuicDataReader coalesced_reader(coalesced_data, coalesced_data_length);
1660
1661 QuicPacketHeader coalesced_header;
1662 if (!ProcessIetfPacketHeader(&coalesced_reader, &coalesced_header)) {
1663 QUIC_PEER_BUG << ENDPOINT
1664 << "Failed to parse received coalesced header of length "
1665 << coalesced_data_length << ": "
1666 << QuicTextUtils::HexEncode(coalesced_data,
1667 coalesced_data_length)
1668 << " previous header was " << header;
1669 return;
1670 }
1671
1672 if (coalesced_header.destination_connection_id !=
1673 header.destination_connection_id ||
1674 (coalesced_header.form != IETF_QUIC_SHORT_HEADER_PACKET &&
1675 coalesced_header.version != header.version)) {
1676 QUIC_PEER_BUG << ENDPOINT << "Received mismatched coalesced header "
1677 << coalesced_header << " previous header was " << header;
1678 return;
1679 }
1680
1681 QuicEncryptedPacket coalesced_packet(coalesced_data, coalesced_data_length,
1682 /*owns_buffer=*/false);
1683 visitor_->OnCoalescedPacket(coalesced_packet);
1684}
1685
1686bool QuicFramer::MaybeProcessIetfLength(QuicDataReader* encrypted_reader,
1687 QuicPacketHeader* header) {
1688 if (!QuicVersionHasLongHeaderLengths(header->version.transport_version) ||
1689 header->form != IETF_QUIC_LONG_HEADER_PACKET ||
1690 (header->long_packet_type != INITIAL &&
1691 header->long_packet_type != HANDSHAKE &&
1692 header->long_packet_type != ZERO_RTT_PROTECTED)) {
1693 return true;
1694 }
1695 header->length_length = encrypted_reader->PeekVarInt62Length();
1696 if (!encrypted_reader->ReadVarInt62(&header->remaining_packet_length)) {
1697 set_detailed_error("Unable to read long header payload length.");
1698 return RaiseError(QUIC_INVALID_PACKET_HEADER);
1699 }
1700 uint64_t remaining_bytes_length = encrypted_reader->BytesRemaining();
1701 if (header->remaining_packet_length > remaining_bytes_length) {
1702 set_detailed_error("Long header payload length longer than packet.");
1703 return RaiseError(QUIC_INVALID_PACKET_HEADER);
1704 }
1705
1706 MaybeProcessCoalescedPacket(*encrypted_reader, remaining_bytes_length,
1707 *header);
1708
1709 if (!encrypted_reader->TruncateRemaining(header->remaining_packet_length)) {
1710 set_detailed_error("Length TruncateRemaining failed.");
1711 QUIC_BUG << "Length TruncateRemaining failed.";
1712 return RaiseError(QUIC_INVALID_PACKET_HEADER);
1713 }
1714 return true;
1715}
1716
1717bool QuicFramer::ProcessIetfDataPacket(QuicDataReader* encrypted_reader,
1718 QuicPacketHeader* header,
1719 const QuicEncryptedPacket& packet,
1720 char* decrypted_buffer,
1721 size_t buffer_length) {
1722 DCHECK_NE(GOOGLE_QUIC_PACKET, header->form);
1723 DCHECK(!header->has_possible_stateless_reset_token);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001724 header->length_length = VARIABLE_LENGTH_INTEGER_LENGTH_0;
1725 header->remaining_packet_length = 0;
1726 if (header->form == IETF_QUIC_SHORT_HEADER_PACKET &&
1727 perspective_ == Perspective::IS_CLIENT) {
1728 // Peek possible stateless reset token. Will only be used on decryption
1729 // failure.
1730 QuicStringPiece remaining = encrypted_reader->PeekRemainingPayload();
1731 if (remaining.length() >= sizeof(header->possible_stateless_reset_token)) {
1732 header->has_possible_stateless_reset_token = true;
1733 memcpy(&header->possible_stateless_reset_token,
1734 &remaining.data()[remaining.length() -
1735 sizeof(header->possible_stateless_reset_token)],
1736 sizeof(header->possible_stateless_reset_token));
1737 }
1738 }
1739
QUICHE teama6ef0a62019-03-07 20:34:33 -05001740 if (!MaybeProcessIetfLength(encrypted_reader, header)) {
1741 return false;
1742 }
1743
nharper55fa6132019-05-07 19:37:21 -07001744 QuicStringPiece associated_data;
1745 std::vector<char> ad_storage;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001746 if (header->form == IETF_QUIC_SHORT_HEADER_PACKET ||
1747 header->long_packet_type != VERSION_NEGOTIATION) {
dschinazi072da7c2019-05-07 17:57:42 -07001748 DCHECK(header->form == IETF_QUIC_SHORT_HEADER_PACKET ||
1749 header->long_packet_type == INITIAL ||
1750 header->long_packet_type == HANDSHAKE ||
1751 header->long_packet_type == ZERO_RTT_PROTECTED);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001752 // Process packet number.
QUICHE team10b22a12019-03-21 15:31:42 -07001753 QuicPacketNumber base_packet_number;
1754 if (supports_multiple_packet_number_spaces_) {
nharper55fa6132019-05-07 19:37:21 -07001755 PacketNumberSpace pn_space = GetPacketNumberSpace(*header);
1756 if (pn_space == NUM_PACKET_NUMBER_SPACES) {
1757 return RaiseError(QUIC_INVALID_PACKET_HEADER);
1758 }
1759 base_packet_number = largest_decrypted_packet_numbers_[pn_space];
QUICHE team10b22a12019-03-21 15:31:42 -07001760 } else {
1761 base_packet_number = largest_packet_number_;
1762 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001763 uint64_t full_packet_number;
nharper55fa6132019-05-07 19:37:21 -07001764 bool hp_removal_failed = false;
1765 if (version_.HasHeaderProtection()) {
1766 if (!RemoveHeaderProtection(encrypted_reader, packet, header,
1767 &full_packet_number, &ad_storage)) {
1768 hp_removal_failed = true;
1769 }
1770 associated_data = QuicStringPiece(ad_storage.data(), ad_storage.size());
1771 } else if (!ProcessAndCalculatePacketNumber(
1772 encrypted_reader, header->packet_number_length,
1773 base_packet_number, &full_packet_number)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001774 set_detailed_error("Unable to read packet number.");
1775 RecordDroppedPacketReason(DroppedPacketReason::INVALID_PACKET_NUMBER);
1776 return RaiseError(QUIC_INVALID_PACKET_HEADER);
1777 }
1778
nharper55fa6132019-05-07 19:37:21 -07001779 if (hp_removal_failed ||
1780 !IsValidFullPacketNumber(full_packet_number, transport_version())) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001781 if (IsIetfStatelessResetPacket(*header)) {
1782 // This is a stateless reset packet.
1783 QuicIetfStatelessResetPacket packet(
1784 *header, header->possible_stateless_reset_token);
1785 visitor_->OnAuthenticatedIetfStatelessResetPacket(packet);
1786 return true;
1787 }
nharper55fa6132019-05-07 19:37:21 -07001788 if (hp_removal_failed) {
dschinazi4b5a68a2019-08-15 15:45:36 -07001789 if (GetQuicRestartFlag(quic_framer_uses_undecryptable_upcall)) {
1790 QUIC_RESTART_FLAG_COUNT_N(quic_framer_uses_undecryptable_upcall, 5,
1791 7);
1792 const EncryptionLevel decryption_level = GetEncryptionLevel(*header);
1793 const bool has_decryption_key =
1794 decrypter_[decryption_level] != nullptr;
1795 visitor_->OnUndecryptablePacket(
1796 QuicEncryptedPacket(encrypted_reader->FullPayload()),
1797 decryption_level, has_decryption_key);
1798 }
nharper55fa6132019-05-07 19:37:21 -07001799 set_detailed_error("Unable to decrypt header protection.");
1800 return RaiseError(QUIC_DECRYPTION_FAILURE);
1801 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001802 RecordDroppedPacketReason(DroppedPacketReason::INVALID_PACKET_NUMBER);
1803 set_detailed_error("packet numbers cannot be 0.");
1804 return RaiseError(QUIC_INVALID_PACKET_HEADER);
1805 }
1806 header->packet_number = QuicPacketNumber(full_packet_number);
1807 }
1808
1809 // A nonce should only present in SHLO from the server to the client when
1810 // using QUIC crypto.
1811 if (header->form == IETF_QUIC_LONG_HEADER_PACKET &&
1812 header->long_packet_type == ZERO_RTT_PROTECTED &&
1813 perspective_ == Perspective::IS_CLIENT &&
1814 version_.handshake_protocol == PROTOCOL_QUIC_CRYPTO) {
1815 if (!encrypted_reader->ReadBytes(
1816 reinterpret_cast<uint8_t*>(last_nonce_.data()),
1817 last_nonce_.size())) {
1818 set_detailed_error("Unable to read nonce.");
1819 RecordDroppedPacketReason(
1820 DroppedPacketReason::INVALID_DIVERSIFICATION_NONCE);
1821 return RaiseError(QUIC_INVALID_PACKET_HEADER);
1822 }
1823
1824 header->nonce = &last_nonce_;
1825 } else {
1826 header->nonce = nullptr;
1827 }
1828
1829 if (!visitor_->OnUnauthenticatedHeader(*header)) {
1830 set_detailed_error(
1831 "Visitor asked to stop processing of unauthenticated header.");
1832 return false;
1833 }
1834
1835 QuicStringPiece encrypted = encrypted_reader->ReadRemainingPayload();
nharper55fa6132019-05-07 19:37:21 -07001836 if (!version_.HasHeaderProtection()) {
1837 associated_data = GetAssociatedDataFromEncryptedPacket(
1838 version_.transport_version, packet,
1839 GetIncludedDestinationConnectionIdLength(*header),
1840 GetIncludedSourceConnectionIdLength(*header), header->version_flag,
1841 header->nonce != nullptr, header->packet_number_length,
1842 header->retry_token_length_length, header->retry_token.length(),
1843 header->length_length);
1844 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001845
1846 size_t decrypted_length = 0;
QUICHE team10b22a12019-03-21 15:31:42 -07001847 EncryptionLevel decrypted_level;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001848 if (!DecryptPayload(encrypted, associated_data, *header, decrypted_buffer,
QUICHE team10b22a12019-03-21 15:31:42 -07001849 buffer_length, &decrypted_length, &decrypted_level)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001850 if (IsIetfStatelessResetPacket(*header)) {
1851 // This is a stateless reset packet.
1852 QuicIetfStatelessResetPacket packet(
1853 *header, header->possible_stateless_reset_token);
1854 visitor_->OnAuthenticatedIetfStatelessResetPacket(packet);
1855 return true;
1856 }
dschinazi4b5a68a2019-08-15 15:45:36 -07001857 if (GetQuicRestartFlag(quic_framer_uses_undecryptable_upcall)) {
1858 QUIC_RESTART_FLAG_COUNT_N(quic_framer_uses_undecryptable_upcall, 6, 7);
1859 const EncryptionLevel decryption_level = GetEncryptionLevel(*header);
1860 const bool has_decryption_key = version_.KnowsWhichDecrypterToUse() &&
1861 decrypter_[decryption_level] != nullptr;
1862 visitor_->OnUndecryptablePacket(
1863 QuicEncryptedPacket(encrypted_reader->FullPayload()),
1864 decryption_level, has_decryption_key);
1865 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001866 set_detailed_error("Unable to decrypt payload.");
1867 RecordDroppedPacketReason(DroppedPacketReason::DECRYPTION_FAILURE);
1868 return RaiseError(QUIC_DECRYPTION_FAILURE);
1869 }
1870 QuicDataReader reader(decrypted_buffer, decrypted_length);
1871
1872 // Update the largest packet number after we have decrypted the packet
1873 // so we are confident is not attacker controlled.
QUICHE team10b22a12019-03-21 15:31:42 -07001874 if (supports_multiple_packet_number_spaces_) {
1875 largest_decrypted_packet_numbers_[QuicUtils::GetPacketNumberSpace(
1876 decrypted_level)]
1877 .UpdateMax(header->packet_number);
1878 } else {
1879 largest_packet_number_.UpdateMax(header->packet_number);
1880 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001881
1882 if (!visitor_->OnPacketHeader(*header)) {
1883 RecordDroppedPacketReason(DroppedPacketReason::INVALID_PACKET_NUMBER);
1884 // The visitor suppresses further processing of the packet.
1885 return true;
1886 }
1887
dschinazie8d7fa72019-04-05 14:44:40 -07001888 if (packet.length() > kMaxIncomingPacketSize) {
1889 set_detailed_error("Packet too large.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05001890 return RaiseError(QUIC_PACKET_TOO_LARGE);
1891 }
1892
1893 // Handle the payload.
fkastenholz305e1732019-06-18 05:01:22 -07001894 if (VersionHasIetfQuicFrames(version_.transport_version)) {
fkastenholza3660102019-08-28 05:19:24 -07001895 current_received_frame_type_ = 0;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001896 if (!ProcessIetfFrameData(&reader, *header)) {
fkastenholza3660102019-08-28 05:19:24 -07001897 current_received_frame_type_ = 0;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001898 DCHECK_NE(QUIC_NO_ERROR, error_); // ProcessIetfFrameData sets the error.
1899 DCHECK_NE("", detailed_error_);
1900 QUIC_DLOG(WARNING) << ENDPOINT << "Unable to process frame data. Error: "
1901 << detailed_error_;
1902 return false;
1903 }
fkastenholza3660102019-08-28 05:19:24 -07001904 current_received_frame_type_ = 0;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001905 } else {
1906 if (!ProcessFrameData(&reader, *header)) {
1907 DCHECK_NE(QUIC_NO_ERROR, error_); // ProcessFrameData sets the error.
1908 DCHECK_NE("", detailed_error_);
1909 QUIC_DLOG(WARNING) << ENDPOINT << "Unable to process frame data. Error: "
1910 << detailed_error_;
1911 return false;
1912 }
1913 }
1914
1915 visitor_->OnPacketComplete();
1916 return true;
1917}
1918
1919bool QuicFramer::ProcessDataPacket(QuicDataReader* encrypted_reader,
1920 QuicPacketHeader* header,
1921 const QuicEncryptedPacket& packet,
1922 char* decrypted_buffer,
1923 size_t buffer_length) {
1924 if (!ProcessUnauthenticatedHeader(encrypted_reader, header)) {
1925 DCHECK_NE("", detailed_error_);
1926 QUIC_DVLOG(1)
1927 << ENDPOINT
1928 << "Unable to process packet header. Stopping parsing. Error: "
1929 << detailed_error_;
1930 RecordDroppedPacketReason(DroppedPacketReason::INVALID_PACKET_NUMBER);
1931 return false;
1932 }
1933
1934 QuicStringPiece encrypted = encrypted_reader->ReadRemainingPayload();
1935 QuicStringPiece associated_data = GetAssociatedDataFromEncryptedPacket(
1936 version_.transport_version, packet,
1937 GetIncludedDestinationConnectionIdLength(*header),
1938 GetIncludedSourceConnectionIdLength(*header), header->version_flag,
1939 header->nonce != nullptr, header->packet_number_length,
1940 header->retry_token_length_length, header->retry_token.length(),
1941 header->length_length);
1942
1943 size_t decrypted_length = 0;
QUICHE team10b22a12019-03-21 15:31:42 -07001944 EncryptionLevel decrypted_level;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001945 if (!DecryptPayload(encrypted, associated_data, *header, decrypted_buffer,
QUICHE team10b22a12019-03-21 15:31:42 -07001946 buffer_length, &decrypted_length, &decrypted_level)) {
dschinazi4b5a68a2019-08-15 15:45:36 -07001947 if (GetQuicRestartFlag(quic_framer_uses_undecryptable_upcall)) {
1948 QUIC_RESTART_FLAG_COUNT_N(quic_framer_uses_undecryptable_upcall, 7, 7);
1949 const EncryptionLevel decryption_level = decrypter_level_;
1950 // This version uses trial decryption so we always report to our visitor
1951 // that we are not certain we have the correct decryption key.
1952 const bool has_decryption_key = false;
1953 visitor_->OnUndecryptablePacket(
1954 QuicEncryptedPacket(encrypted_reader->FullPayload()),
1955 decryption_level, has_decryption_key);
1956 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001957 RecordDroppedPacketReason(DroppedPacketReason::DECRYPTION_FAILURE);
1958 set_detailed_error("Unable to decrypt payload.");
1959 return RaiseError(QUIC_DECRYPTION_FAILURE);
1960 }
1961
1962 QuicDataReader reader(decrypted_buffer, decrypted_length);
1963
1964 // Update the largest packet number after we have decrypted the packet
1965 // so we are confident is not attacker controlled.
QUICHE team10b22a12019-03-21 15:31:42 -07001966 if (supports_multiple_packet_number_spaces_) {
1967 largest_decrypted_packet_numbers_[QuicUtils::GetPacketNumberSpace(
1968 decrypted_level)]
1969 .UpdateMax(header->packet_number);
1970 } else {
1971 largest_packet_number_.UpdateMax(header->packet_number);
1972 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001973
1974 if (!visitor_->OnPacketHeader(*header)) {
1975 // The visitor suppresses further processing of the packet.
1976 return true;
1977 }
1978
dschinazie8d7fa72019-04-05 14:44:40 -07001979 if (packet.length() > kMaxIncomingPacketSize) {
1980 set_detailed_error("Packet too large.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05001981 return RaiseError(QUIC_PACKET_TOO_LARGE);
1982 }
1983
1984 // Handle the payload.
1985 if (!ProcessFrameData(&reader, *header)) {
1986 DCHECK_NE(QUIC_NO_ERROR, error_); // ProcessFrameData sets the error.
1987 DCHECK_NE("", detailed_error_);
1988 QUIC_DLOG(WARNING) << ENDPOINT << "Unable to process frame data. Error: "
1989 << detailed_error_;
1990 return false;
1991 }
1992
1993 visitor_->OnPacketComplete();
1994 return true;
1995}
1996
1997bool QuicFramer::ProcessPublicResetPacket(QuicDataReader* reader,
1998 const QuicPacketHeader& header) {
QUICHE team2252b702019-05-14 23:55:14 -04001999 QuicPublicResetPacket packet(
2000 GetServerConnectionIdAsRecipient(header, perspective_));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002001
2002 std::unique_ptr<CryptoHandshakeMessage> reset(
2003 CryptoFramer::ParseMessage(reader->ReadRemainingPayload()));
2004 if (!reset.get()) {
2005 set_detailed_error("Unable to read reset message.");
2006 RecordDroppedPacketReason(DroppedPacketReason::INVALID_PUBLIC_RESET_PACKET);
2007 return RaiseError(QUIC_INVALID_PUBLIC_RST_PACKET);
2008 }
2009 if (reset->tag() != kPRST) {
2010 set_detailed_error("Incorrect message tag.");
2011 RecordDroppedPacketReason(DroppedPacketReason::INVALID_PUBLIC_RESET_PACKET);
2012 return RaiseError(QUIC_INVALID_PUBLIC_RST_PACKET);
2013 }
2014
2015 if (reset->GetUint64(kRNON, &packet.nonce_proof) != QUIC_NO_ERROR) {
2016 set_detailed_error("Unable to read nonce proof.");
2017 RecordDroppedPacketReason(DroppedPacketReason::INVALID_PUBLIC_RESET_PACKET);
2018 return RaiseError(QUIC_INVALID_PUBLIC_RST_PACKET);
2019 }
2020 // TODO(satyamshekhar): validate nonce to protect against DoS.
2021
2022 QuicStringPiece address;
2023 if (reset->GetStringPiece(kCADR, &address)) {
2024 QuicSocketAddressCoder address_coder;
2025 if (address_coder.Decode(address.data(), address.length())) {
2026 packet.client_address =
2027 QuicSocketAddress(address_coder.ip(), address_coder.port());
2028 }
2029 }
2030
2031 QuicStringPiece endpoint_id;
2032 if (perspective_ == Perspective::IS_CLIENT &&
2033 reset->GetStringPiece(kEPID, &endpoint_id)) {
vasilvvc48c8712019-03-11 13:38:16 -07002034 packet.endpoint_id = std::string(endpoint_id);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002035 packet.endpoint_id += '\0';
2036 }
2037
2038 visitor_->OnPublicResetPacket(packet);
2039 return true;
2040}
2041
2042bool QuicFramer::IsIetfStatelessResetPacket(
2043 const QuicPacketHeader& header) const {
2044 QUIC_BUG_IF(header.has_possible_stateless_reset_token &&
2045 perspective_ != Perspective::IS_CLIENT)
2046 << "has_possible_stateless_reset_token can only be true at client side.";
2047 return header.form == IETF_QUIC_SHORT_HEADER_PACKET &&
2048 header.has_possible_stateless_reset_token &&
2049 visitor_->IsValidStatelessResetToken(
2050 header.possible_stateless_reset_token);
2051}
2052
2053bool QuicFramer::HasEncrypterOfEncryptionLevel(EncryptionLevel level) const {
2054 return encrypter_[level] != nullptr;
2055}
2056
2057bool QuicFramer::AppendPacketHeader(const QuicPacketHeader& header,
2058 QuicDataWriter* writer,
2059 size_t* length_field_offset) {
fayangd4291e42019-05-30 10:31:21 -07002060 if (VersionHasIetfInvariantHeader(transport_version())) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002061 return AppendIetfPacketHeader(header, writer, length_field_offset);
2062 }
2063 QUIC_DVLOG(1) << ENDPOINT << "Appending header: " << header;
2064 uint8_t public_flags = 0;
2065 if (header.reset_flag) {
2066 public_flags |= PACKET_PUBLIC_FLAGS_RST;
2067 }
2068 if (header.version_flag) {
2069 public_flags |= PACKET_PUBLIC_FLAGS_VERSION;
2070 }
2071
2072 public_flags |= GetPacketNumberFlags(header.packet_number_length)
2073 << kPublicHeaderSequenceNumberShift;
2074
2075 if (header.nonce != nullptr) {
2076 DCHECK_EQ(Perspective::IS_SERVER, perspective_);
2077 public_flags |= PACKET_PUBLIC_FLAGS_NONCE;
2078 }
QUICHE team2252b702019-05-14 23:55:14 -04002079
dschinazi7b9278c2019-05-20 07:36:21 -07002080 QuicConnectionId server_connection_id =
QUICHE team2252b702019-05-14 23:55:14 -04002081 GetServerConnectionIdAsSender(header, perspective_);
dschinazi7b9278c2019-05-20 07:36:21 -07002082 QuicConnectionIdIncluded server_connection_id_included =
QUICHE team2252b702019-05-14 23:55:14 -04002083 GetServerConnectionIdIncludedAsSender(header, perspective_);
2084 DCHECK_EQ(CONNECTION_ID_ABSENT,
dschinazic075ffa2019-06-27 16:17:37 -07002085 GetClientConnectionIdIncludedAsSender(header, perspective_))
2086 << ENDPOINT << ParsedQuicVersionToString(version_)
2087 << " invalid header: " << header;
QUICHE team2252b702019-05-14 23:55:14 -04002088
dschinazi7b9278c2019-05-20 07:36:21 -07002089 switch (server_connection_id_included) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002090 case CONNECTION_ID_ABSENT:
2091 if (!writer->WriteUInt8(public_flags |
2092 PACKET_PUBLIC_FLAGS_0BYTE_CONNECTION_ID)) {
2093 return false;
2094 }
2095 break;
2096 case CONNECTION_ID_PRESENT:
2097 QUIC_BUG_IF(!QuicUtils::IsConnectionIdValidForVersion(
dschinazi7b9278c2019-05-20 07:36:21 -07002098 server_connection_id, transport_version()))
QUICHE teama6ef0a62019-03-07 20:34:33 -05002099 << "AppendPacketHeader: attempted to use connection ID "
dschinazi7b9278c2019-05-20 07:36:21 -07002100 << server_connection_id << " which is invalid with version "
QUICHE teama6ef0a62019-03-07 20:34:33 -05002101 << QuicVersionToString(transport_version());
2102
2103 public_flags |= PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID;
2104 if (perspective_ == Perspective::IS_CLIENT) {
2105 public_flags |= PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID_OLD;
2106 }
2107 if (!writer->WriteUInt8(public_flags) ||
dschinazi7b9278c2019-05-20 07:36:21 -07002108 !writer->WriteConnectionId(server_connection_id)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002109 return false;
2110 }
2111 break;
2112 }
dschinazi7b9278c2019-05-20 07:36:21 -07002113 last_serialized_server_connection_id_ = server_connection_id;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002114
2115 if (header.version_flag) {
2116 DCHECK_EQ(Perspective::IS_CLIENT, perspective_);
2117 QuicVersionLabel version_label = CreateQuicVersionLabel(version_);
nharpereaab5ad2019-05-31 12:23:25 -07002118 if (!writer->WriteUInt32(version_label)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002119 return false;
2120 }
2121
2122 QUIC_DVLOG(1) << ENDPOINT << "label = '"
2123 << QuicVersionLabelToString(version_label) << "'";
2124 }
2125
2126 if (header.nonce != nullptr &&
2127 !writer->WriteBytes(header.nonce, kDiversificationNonceSize)) {
2128 return false;
2129 }
2130
2131 if (!AppendPacketNumber(header.packet_number_length, header.packet_number,
2132 writer)) {
2133 return false;
2134 }
2135
2136 return true;
2137}
2138
2139bool QuicFramer::AppendIetfHeaderTypeByte(const QuicPacketHeader& header,
2140 QuicDataWriter* writer) {
2141 uint8_t type = 0;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002142 if (header.version_flag) {
2143 type = static_cast<uint8_t>(
fayang36825da2019-08-21 14:01:27 -07002144 FLAGS_LONG_HEADER | FLAGS_FIXED_BIT |
2145 LongHeaderTypeToOnWireValue(header.long_packet_type) |
2146 PacketNumberLengthToOnWireValue(header.packet_number_length));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002147 } else {
fayang36825da2019-08-21 14:01:27 -07002148 type = static_cast<uint8_t>(
2149 FLAGS_FIXED_BIT |
2150 PacketNumberLengthToOnWireValue(header.packet_number_length));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002151 }
2152 return writer->WriteUInt8(type);
2153}
2154
2155bool QuicFramer::AppendIetfPacketHeader(const QuicPacketHeader& header,
2156 QuicDataWriter* writer,
2157 size_t* length_field_offset) {
2158 QUIC_DVLOG(1) << ENDPOINT << "Appending IETF header: " << header;
QUICHE team2252b702019-05-14 23:55:14 -04002159 QuicConnectionId server_connection_id =
2160 GetServerConnectionIdAsSender(header, perspective_);
2161 QUIC_BUG_IF(!QuicUtils::IsConnectionIdValidForVersion(server_connection_id,
2162 transport_version()))
QUICHE teama6ef0a62019-03-07 20:34:33 -05002163 << "AppendIetfPacketHeader: attempted to use connection ID "
QUICHE team2252b702019-05-14 23:55:14 -04002164 << server_connection_id << " which is invalid with version "
QUICHE teama6ef0a62019-03-07 20:34:33 -05002165 << QuicVersionToString(transport_version());
2166 if (!AppendIetfHeaderTypeByte(header, writer)) {
2167 return false;
2168 }
2169
2170 if (header.version_flag) {
dschinaziecad9642019-10-01 10:44:17 -07002171 DCHECK_NE(VERSION_NEGOTIATION, header.long_packet_type)
2172 << "QuicFramer::AppendIetfPacketHeader does not support sending "
2173 "version negotiation packets, use "
2174 "QuicFramer::BuildVersionNegotiationPacket instead "
2175 << header;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002176 // Append version for long header.
2177 QuicVersionLabel version_label = CreateQuicVersionLabel(version_);
nharpereaab5ad2019-05-31 12:23:25 -07002178 if (!writer->WriteUInt32(version_label)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002179 return false;
2180 }
2181 }
2182
2183 // Append connection ID.
dschinazi1f485a12019-05-13 11:57:01 -07002184 if (!AppendIetfConnectionIds(
dschinazi48ac9192019-07-31 00:07:26 -07002185 header.version_flag, version_.HasLengthPrefixedConnectionIds(),
dschinazi1f485a12019-05-13 11:57:01 -07002186 header.destination_connection_id_included != CONNECTION_ID_ABSENT
2187 ? header.destination_connection_id
2188 : EmptyQuicConnectionId(),
2189 header.source_connection_id_included != CONNECTION_ID_ABSENT
2190 ? header.source_connection_id
2191 : EmptyQuicConnectionId(),
2192 writer)) {
2193 return false;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002194 }
dschinazi1f485a12019-05-13 11:57:01 -07002195
dschinazi7b9278c2019-05-20 07:36:21 -07002196 last_serialized_server_connection_id_ = server_connection_id;
dschinazi346b7ce2019-06-05 01:38:18 -07002197 if (version_.SupportsClientConnectionIds()) {
2198 last_serialized_client_connection_id_ =
2199 GetClientConnectionIdAsSender(header, perspective_);
2200 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002201
dschinaziecad9642019-10-01 10:44:17 -07002202 // TODO(b/141924462) Remove this QUIC_BUG once we do support sending RETRY.
2203 QUIC_BUG_IF(header.version_flag && header.long_packet_type == RETRY)
2204 << "Sending IETF RETRY packets is not currently supported " << header;
2205
QUICHE teama6ef0a62019-03-07 20:34:33 -05002206 if (QuicVersionHasLongHeaderLengths(transport_version()) &&
2207 header.version_flag) {
2208 if (header.long_packet_type == INITIAL) {
dschinazic075ffa2019-06-27 16:17:37 -07002209 DCHECK_NE(VARIABLE_LENGTH_INTEGER_LENGTH_0,
2210 header.retry_token_length_length)
2211 << ENDPOINT << ParsedQuicVersionToString(version_)
2212 << " bad retry token length length in header: " << header;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002213 // Write retry token length.
2214 if (!writer->WriteVarInt62(header.retry_token.length(),
2215 header.retry_token_length_length)) {
2216 return false;
2217 }
2218 // Write retry token.
2219 if (!header.retry_token.empty() &&
2220 !writer->WriteStringPiece(header.retry_token)) {
2221 return false;
2222 }
2223 }
2224 if (length_field_offset != nullptr) {
2225 *length_field_offset = writer->length();
2226 }
2227 // Add fake length to reserve two bytes to add length in later.
2228 writer->WriteVarInt62(256);
2229 } else if (length_field_offset != nullptr) {
2230 *length_field_offset = 0;
2231 }
2232
2233 // Append packet number.
2234 if (!AppendPacketNumber(header.packet_number_length, header.packet_number,
2235 writer)) {
2236 return false;
2237 }
nharper55fa6132019-05-07 19:37:21 -07002238 last_written_packet_number_length_ = header.packet_number_length;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002239
2240 if (!header.version_flag) {
2241 return true;
2242 }
2243
2244 if (header.nonce != nullptr) {
2245 DCHECK(header.version_flag);
2246 DCHECK_EQ(ZERO_RTT_PROTECTED, header.long_packet_type);
2247 DCHECK_EQ(Perspective::IS_SERVER, perspective_);
2248 if (!writer->WriteBytes(header.nonce, kDiversificationNonceSize)) {
2249 return false;
2250 }
2251 }
2252
2253 return true;
2254}
2255
2256const QuicTime::Delta QuicFramer::CalculateTimestampFromWire(
2257 uint32_t time_delta_us) {
2258 // The new time_delta might have wrapped to the next epoch, or it
2259 // might have reverse wrapped to the previous epoch, or it might
2260 // remain in the same epoch. Select the time closest to the previous
2261 // time.
2262 //
2263 // epoch_delta is the delta between epochs. A delta is 4 bytes of
2264 // microseconds.
2265 const uint64_t epoch_delta = UINT64_C(1) << 32;
2266 uint64_t epoch = last_timestamp_.ToMicroseconds() & ~(epoch_delta - 1);
2267 // Wrapping is safe here because a wrapped value will not be ClosestTo below.
2268 uint64_t prev_epoch = epoch - epoch_delta;
2269 uint64_t next_epoch = epoch + epoch_delta;
2270
2271 uint64_t time = ClosestTo(
2272 last_timestamp_.ToMicroseconds(), epoch + time_delta_us,
2273 ClosestTo(last_timestamp_.ToMicroseconds(), prev_epoch + time_delta_us,
2274 next_epoch + time_delta_us));
2275
2276 return QuicTime::Delta::FromMicroseconds(time);
2277}
2278
2279uint64_t QuicFramer::CalculatePacketNumberFromWire(
2280 QuicPacketNumberLength packet_number_length,
2281 QuicPacketNumber base_packet_number,
2282 uint64_t packet_number) const {
2283 // The new packet number might have wrapped to the next epoch, or
2284 // it might have reverse wrapped to the previous epoch, or it might
2285 // remain in the same epoch. Select the packet number closest to the
2286 // next expected packet number, the previous packet number plus 1.
2287
2288 // epoch_delta is the delta between epochs the packet number was serialized
2289 // with, so the correct value is likely the same epoch as the last sequence
2290 // number or an adjacent epoch.
2291 if (!base_packet_number.IsInitialized()) {
2292 return packet_number;
2293 }
2294 const uint64_t epoch_delta = UINT64_C(1) << (8 * packet_number_length);
2295 uint64_t next_packet_number = base_packet_number.ToUint64() + 1;
2296 uint64_t epoch = base_packet_number.ToUint64() & ~(epoch_delta - 1);
2297 uint64_t prev_epoch = epoch - epoch_delta;
2298 uint64_t next_epoch = epoch + epoch_delta;
2299
2300 return ClosestTo(next_packet_number, epoch + packet_number,
2301 ClosestTo(next_packet_number, prev_epoch + packet_number,
2302 next_epoch + packet_number));
2303}
2304
2305bool QuicFramer::ProcessPublicHeader(QuicDataReader* reader,
2306 bool packet_has_ietf_packet_header,
2307 QuicPacketHeader* header) {
2308 if (packet_has_ietf_packet_header) {
2309 return ProcessIetfPacketHeader(reader, header);
2310 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002311 uint8_t public_flags;
2312 if (!reader->ReadBytes(&public_flags, 1)) {
2313 set_detailed_error("Unable to read public flags.");
2314 return false;
2315 }
2316
2317 header->reset_flag = (public_flags & PACKET_PUBLIC_FLAGS_RST) != 0;
2318 header->version_flag = (public_flags & PACKET_PUBLIC_FLAGS_VERSION) != 0;
2319
2320 if (validate_flags_ && !header->version_flag &&
2321 public_flags > PACKET_PUBLIC_FLAGS_MAX) {
2322 set_detailed_error("Illegal public flags value.");
2323 return false;
2324 }
2325
2326 if (header->reset_flag && header->version_flag) {
2327 set_detailed_error("Got version flag in reset packet");
2328 return false;
2329 }
2330
QUICHE team2252b702019-05-14 23:55:14 -04002331 QuicConnectionId* header_connection_id = &header->destination_connection_id;
2332 QuicConnectionIdIncluded* header_connection_id_included =
2333 &header->destination_connection_id_included;
dschinazi5e1a7b22019-07-31 12:23:21 -07002334 if (perspective_ == Perspective::IS_CLIENT) {
QUICHE team2252b702019-05-14 23:55:14 -04002335 header_connection_id = &header->source_connection_id;
2336 header_connection_id_included = &header->source_connection_id_included;
2337 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002338 switch (public_flags & PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID) {
2339 case PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID:
QUICHE team2252b702019-05-14 23:55:14 -04002340 if (!reader->ReadConnectionId(header_connection_id,
QUICHE teama6ef0a62019-03-07 20:34:33 -05002341 kQuicDefaultConnectionIdLength)) {
2342 set_detailed_error("Unable to read ConnectionId.");
2343 return false;
2344 }
QUICHE team2252b702019-05-14 23:55:14 -04002345 *header_connection_id_included = CONNECTION_ID_PRESENT;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002346 break;
2347 case PACKET_PUBLIC_FLAGS_0BYTE_CONNECTION_ID:
QUICHE team2252b702019-05-14 23:55:14 -04002348 *header_connection_id_included = CONNECTION_ID_ABSENT;
dschinazi7b9278c2019-05-20 07:36:21 -07002349 *header_connection_id = last_serialized_server_connection_id_;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002350 break;
2351 }
2352
2353 header->packet_number_length = ReadSequenceNumberLength(
2354 public_flags >> kPublicHeaderSequenceNumberShift);
2355
2356 // Read the version only if the packet is from the client.
2357 // version flag from the server means version negotiation packet.
2358 if (header->version_flag && perspective_ == Perspective::IS_SERVER) {
2359 QuicVersionLabel version_label;
fayang40315542019-05-09 09:19:09 -07002360 if (!ProcessVersionLabel(reader, &version_label)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002361 set_detailed_error("Unable to read protocol version.");
2362 return false;
2363 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002364 // If the version from the new packet is the same as the version of this
2365 // framer, then the public flags should be set to something we understand.
2366 // If not, this raises an error.
QUICHE teama6ef0a62019-03-07 20:34:33 -05002367 ParsedQuicVersion version = ParseQuicVersionLabel(version_label);
2368 if (version == version_ && public_flags > PACKET_PUBLIC_FLAGS_MAX) {
2369 set_detailed_error("Illegal public flags value.");
2370 return false;
2371 }
2372 header->version = version;
2373 }
2374
2375 // A nonce should only be present in packets from the server to the client,
2376 // which are neither version negotiation nor public reset packets.
2377 if (public_flags & PACKET_PUBLIC_FLAGS_NONCE &&
2378 !(public_flags & PACKET_PUBLIC_FLAGS_VERSION) &&
2379 !(public_flags & PACKET_PUBLIC_FLAGS_RST) &&
2380 // The nonce flag from a client is ignored and is assumed to be an older
2381 // client indicating an eight-byte connection ID.
2382 perspective_ == Perspective::IS_CLIENT) {
2383 if (!reader->ReadBytes(reinterpret_cast<uint8_t*>(last_nonce_.data()),
2384 last_nonce_.size())) {
2385 set_detailed_error("Unable to read nonce.");
2386 return false;
2387 }
2388 header->nonce = &last_nonce_;
2389 } else {
2390 header->nonce = nullptr;
2391 }
2392
2393 return true;
2394}
2395
2396// static
2397QuicPacketNumberLength QuicFramer::GetMinPacketNumberLength(
dschinazi17d42422019-06-18 16:35:07 -07002398 QuicTransportVersion /*version*/,
QUICHE teama6ef0a62019-03-07 20:34:33 -05002399 QuicPacketNumber packet_number) {
2400 DCHECK(packet_number.IsInitialized());
2401 if (packet_number < QuicPacketNumber(1 << (PACKET_1BYTE_PACKET_NUMBER * 8))) {
2402 return PACKET_1BYTE_PACKET_NUMBER;
2403 } else if (packet_number <
2404 QuicPacketNumber(1 << (PACKET_2BYTE_PACKET_NUMBER * 8))) {
2405 return PACKET_2BYTE_PACKET_NUMBER;
2406 } else if (packet_number <
2407 QuicPacketNumber(UINT64_C(1)
2408 << (PACKET_4BYTE_PACKET_NUMBER * 8))) {
2409 return PACKET_4BYTE_PACKET_NUMBER;
2410 } else {
2411 return PACKET_6BYTE_PACKET_NUMBER;
2412 }
2413}
2414
2415// static
2416uint8_t QuicFramer::GetPacketNumberFlags(
2417 QuicPacketNumberLength packet_number_length) {
2418 switch (packet_number_length) {
2419 case PACKET_1BYTE_PACKET_NUMBER:
2420 return PACKET_FLAGS_1BYTE_PACKET;
2421 case PACKET_2BYTE_PACKET_NUMBER:
2422 return PACKET_FLAGS_2BYTE_PACKET;
2423 case PACKET_4BYTE_PACKET_NUMBER:
2424 return PACKET_FLAGS_4BYTE_PACKET;
2425 case PACKET_6BYTE_PACKET_NUMBER:
2426 case PACKET_8BYTE_PACKET_NUMBER:
2427 return PACKET_FLAGS_8BYTE_PACKET;
2428 default:
2429 QUIC_BUG << "Unreachable case statement.";
2430 return PACKET_FLAGS_8BYTE_PACKET;
2431 }
2432}
2433
2434// static
2435QuicFramer::AckFrameInfo QuicFramer::GetAckFrameInfo(
2436 const QuicAckFrame& frame) {
2437 AckFrameInfo new_ack_info;
2438 if (frame.packets.Empty()) {
2439 return new_ack_info;
2440 }
2441 // The first block is the last interval. It isn't encoded with the gap-length
2442 // encoding, so skip it.
2443 new_ack_info.first_block_length = frame.packets.LastIntervalLength();
2444 auto itr = frame.packets.rbegin();
2445 QuicPacketNumber previous_start = itr->min();
2446 new_ack_info.max_block_length = PacketNumberIntervalLength(*itr);
2447 ++itr;
2448
2449 // Don't do any more work after getting information for 256 ACK blocks; any
2450 // more can't be encoded anyway.
2451 for (; itr != frame.packets.rend() &&
2452 new_ack_info.num_ack_blocks < std::numeric_limits<uint8_t>::max();
2453 previous_start = itr->min(), ++itr) {
2454 const auto& interval = *itr;
2455 const QuicPacketCount total_gap = previous_start - interval.max();
2456 new_ack_info.num_ack_blocks +=
2457 (total_gap + std::numeric_limits<uint8_t>::max() - 1) /
2458 std::numeric_limits<uint8_t>::max();
2459 new_ack_info.max_block_length = std::max(
2460 new_ack_info.max_block_length, PacketNumberIntervalLength(interval));
2461 }
2462 return new_ack_info;
2463}
2464
2465bool QuicFramer::ProcessUnauthenticatedHeader(QuicDataReader* encrypted_reader,
2466 QuicPacketHeader* header) {
QUICHE team10b22a12019-03-21 15:31:42 -07002467 QuicPacketNumber base_packet_number;
2468 if (supports_multiple_packet_number_spaces_) {
nharper55fa6132019-05-07 19:37:21 -07002469 PacketNumberSpace pn_space = GetPacketNumberSpace(*header);
2470 if (pn_space == NUM_PACKET_NUMBER_SPACES) {
2471 set_detailed_error("Unable to determine packet number space.");
2472 return RaiseError(QUIC_INVALID_PACKET_HEADER);
2473 }
2474 base_packet_number = largest_decrypted_packet_numbers_[pn_space];
QUICHE team10b22a12019-03-21 15:31:42 -07002475 } else {
2476 base_packet_number = largest_packet_number_;
2477 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002478 uint64_t full_packet_number;
2479 if (!ProcessAndCalculatePacketNumber(
2480 encrypted_reader, header->packet_number_length, base_packet_number,
2481 &full_packet_number)) {
2482 set_detailed_error("Unable to read packet number.");
2483 return RaiseError(QUIC_INVALID_PACKET_HEADER);
2484 }
2485
2486 if (!IsValidFullPacketNumber(full_packet_number, transport_version())) {
2487 set_detailed_error("packet numbers cannot be 0.");
2488 return RaiseError(QUIC_INVALID_PACKET_HEADER);
2489 }
2490 header->packet_number = QuicPacketNumber(full_packet_number);
2491
2492 if (!visitor_->OnUnauthenticatedHeader(*header)) {
2493 set_detailed_error(
2494 "Visitor asked to stop processing of unauthenticated header.");
2495 return false;
2496 }
nharper3f283562019-05-02 16:37:12 -07002497 // The function we are in is called because the framer believes that it is
2498 // processing a packet that uses the non-IETF (i.e. Google QUIC) packet header
2499 // type. Usually, the framer makes that decision based on the framer's
2500 // version, but when the framer is used with Perspective::IS_SERVER, then
2501 // before version negotiation is complete (specifically, before
2502 // InferPacketHeaderTypeFromVersion is called), this decision is made based on
2503 // the type byte of the packet.
2504 //
2505 // If the framer's version KnowsWhichDecrypterToUse, then that version expects
2506 // to use the IETF packet header type. If that's the case and we're in this
2507 // function, then the packet received is invalid: the framer was expecting an
2508 // IETF packet header and didn't get one.
2509 if (version().KnowsWhichDecrypterToUse()) {
nharpera745e392019-04-19 12:05:15 -07002510 set_detailed_error("Invalid public header type for expected version.");
2511 return RaiseError(QUIC_INVALID_PACKET_HEADER);
2512 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002513 return true;
2514}
2515
2516bool QuicFramer::ProcessIetfHeaderTypeByte(QuicDataReader* reader,
2517 QuicPacketHeader* header) {
2518 uint8_t type;
2519 if (!reader->ReadBytes(&type, 1)) {
dschinazi48ac9192019-07-31 00:07:26 -07002520 set_detailed_error("Unable to read first byte.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05002521 return false;
2522 }
dschinazi244f6dc2019-05-06 15:45:16 -07002523 header->type_byte = type;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002524 // Determine whether this is a long or short header.
fayangccbab732019-05-13 10:11:25 -07002525 header->form = GetIetfPacketHeaderFormat(type);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002526 if (header->form == IETF_QUIC_LONG_HEADER_PACKET) {
2527 // Version is always present in long headers.
2528 header->version_flag = true;
dschinazi346b7ce2019-06-05 01:38:18 -07002529 // In versions that do not support client connection IDs, we mark the
2530 // corresponding connection ID as absent.
QUICHE teama6ef0a62019-03-07 20:34:33 -05002531 header->destination_connection_id_included =
dschinazi346b7ce2019-06-05 01:38:18 -07002532 (perspective_ == Perspective::IS_SERVER ||
2533 version_.SupportsClientConnectionIds())
2534 ? CONNECTION_ID_PRESENT
2535 : CONNECTION_ID_ABSENT;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002536 header->source_connection_id_included =
dschinazi346b7ce2019-06-05 01:38:18 -07002537 (perspective_ == Perspective::IS_CLIENT ||
2538 version_.SupportsClientConnectionIds())
2539 ? CONNECTION_ID_PRESENT
2540 : CONNECTION_ID_ABSENT;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002541 // Read version tag.
2542 QuicVersionLabel version_label;
fayang40315542019-05-09 09:19:09 -07002543 if (!ProcessVersionLabel(reader, &version_label)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002544 set_detailed_error("Unable to read protocol version.");
2545 return false;
2546 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002547 if (!version_label) {
2548 // Version label is 0 indicating this is a version negotiation packet.
2549 header->long_packet_type = VERSION_NEGOTIATION;
2550 } else {
2551 header->version = ParseQuicVersionLabel(version_label);
2552 if (header->version.transport_version != QUIC_VERSION_UNSUPPORTED) {
fayang36825da2019-08-21 14:01:27 -07002553 if (!(type & FLAGS_FIXED_BIT)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002554 set_detailed_error("Fixed bit is 0 in long header.");
2555 return false;
2556 }
fayang36825da2019-08-21 14:01:27 -07002557 if (!GetLongHeaderType(type, &header->long_packet_type)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002558 set_detailed_error("Illegal long header type value.");
2559 return false;
2560 }
dschinazi244f6dc2019-05-06 15:45:16 -07002561 if (header->long_packet_type == RETRY) {
2562 if (!version().SupportsRetry()) {
2563 set_detailed_error("RETRY not supported in this version.");
2564 return false;
2565 }
2566 if (perspective_ == Perspective::IS_SERVER) {
2567 set_detailed_error("Client-initiated RETRY is invalid.");
2568 return false;
2569 }
nharper55fa6132019-05-07 19:37:21 -07002570 } else if (!header->version.HasHeaderProtection()) {
fayang36825da2019-08-21 14:01:27 -07002571 header->packet_number_length = GetLongHeaderPacketNumberLength(type);
nharper2ceb97c2019-04-19 11:38:59 -07002572 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002573 }
2574 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002575
2576 QUIC_DVLOG(1) << ENDPOINT << "Received IETF long header: "
2577 << QuicUtils::QuicLongHeaderTypetoString(
2578 header->long_packet_type);
2579 return true;
2580 }
2581
2582 QUIC_DVLOG(1) << ENDPOINT << "Received IETF short header";
2583 // Version is not present in short headers.
2584 header->version_flag = false;
dschinazi346b7ce2019-06-05 01:38:18 -07002585 // In versions that do not support client connection IDs, the client will not
2586 // receive destination connection IDs.
QUICHE teama6ef0a62019-03-07 20:34:33 -05002587 header->destination_connection_id_included =
dschinazi346b7ce2019-06-05 01:38:18 -07002588 (perspective_ == Perspective::IS_SERVER ||
2589 version_.SupportsClientConnectionIds())
2590 ? CONNECTION_ID_PRESENT
2591 : CONNECTION_ID_ABSENT;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002592 header->source_connection_id_included = CONNECTION_ID_ABSENT;
fayang36825da2019-08-21 14:01:27 -07002593 if (!(type & FLAGS_FIXED_BIT)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002594 set_detailed_error("Fixed bit is 0 in short header.");
2595 return false;
2596 }
fayang36825da2019-08-21 14:01:27 -07002597 if (!header->version.HasHeaderProtection()) {
2598 header->packet_number_length = GetShortHeaderPacketNumberLength(type);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002599 }
2600 QUIC_DVLOG(1) << "packet_number_length = " << header->packet_number_length;
2601 return true;
2602}
2603
fayang40315542019-05-09 09:19:09 -07002604// static
2605bool QuicFramer::ProcessVersionLabel(QuicDataReader* reader,
2606 QuicVersionLabel* version_label) {
nharpereaab5ad2019-05-31 12:23:25 -07002607 if (!reader->ReadUInt32(version_label)) {
fayang40315542019-05-09 09:19:09 -07002608 return false;
2609 }
fayang40315542019-05-09 09:19:09 -07002610 return true;
2611}
2612
2613// static
fayangccbab732019-05-13 10:11:25 -07002614bool QuicFramer::ProcessAndValidateIetfConnectionIdLength(
2615 QuicDataReader* reader,
fayang40315542019-05-09 09:19:09 -07002616 ParsedQuicVersion version,
dschinazi334f0232019-05-29 16:08:53 -07002617 Perspective perspective,
dschinazi8ff74822019-05-28 16:37:20 -07002618 bool should_update_expected_server_connection_id_length,
2619 uint8_t* expected_server_connection_id_length,
fayang40315542019-05-09 09:19:09 -07002620 uint8_t* destination_connection_id_length,
fayangccbab732019-05-13 10:11:25 -07002621 uint8_t* source_connection_id_length,
2622 std::string* detailed_error) {
2623 uint8_t connection_id_lengths_byte;
2624 if (!reader->ReadBytes(&connection_id_lengths_byte, 1)) {
2625 *detailed_error = "Unable to read ConnectionId length.";
2626 return false;
2627 }
fayang40315542019-05-09 09:19:09 -07002628 uint8_t dcil =
2629 (connection_id_lengths_byte & kDestinationConnectionIdLengthMask) >> 4;
2630 if (dcil != 0) {
2631 dcil += kConnectionIdLengthAdjustment;
2632 }
fayang40315542019-05-09 09:19:09 -07002633 uint8_t scil = connection_id_lengths_byte & kSourceConnectionIdLengthMask;
2634 if (scil != 0) {
2635 scil += kConnectionIdLengthAdjustment;
2636 }
dschinazi334f0232019-05-29 16:08:53 -07002637 if (should_update_expected_server_connection_id_length) {
2638 uint8_t server_connection_id_length =
2639 perspective == Perspective::IS_SERVER ? dcil : scil;
2640 if (*expected_server_connection_id_length != server_connection_id_length) {
2641 QUIC_DVLOG(1) << "Updating expected_server_connection_id_length: "
2642 << static_cast<int>(*expected_server_connection_id_length)
2643 << " -> " << static_cast<int>(server_connection_id_length);
2644 *expected_server_connection_id_length = server_connection_id_length;
2645 }
2646 }
dschinazi8ff74822019-05-28 16:37:20 -07002647 if (!should_update_expected_server_connection_id_length &&
fayangde8a2222019-05-16 10:52:39 -07002648 (dcil != *destination_connection_id_length ||
fayang40315542019-05-09 09:19:09 -07002649 scil != *source_connection_id_length) &&
fayang40315542019-05-09 09:19:09 -07002650 !QuicUtils::VariableLengthConnectionIdAllowedForVersion(
2651 version.transport_version)) {
2652 // TODO(dschinazi): use the framer's version once the
2653 // OnProtocolVersionMismatch call is moved to before this is run.
2654 QUIC_DVLOG(1) << "dcil: " << static_cast<uint32_t>(dcil)
2655 << ", scil: " << static_cast<uint32_t>(scil);
fayangccbab732019-05-13 10:11:25 -07002656 *detailed_error = "Invalid ConnectionId length.";
fayang40315542019-05-09 09:19:09 -07002657 return false;
2658 }
2659 *destination_connection_id_length = dcil;
2660 *source_connection_id_length = scil;
2661 return true;
2662}
2663
dschinazib953d022019-08-01 18:05:58 -07002664bool QuicFramer::ValidateReceivedConnectionIds(const QuicPacketHeader& header) {
2665 if (!QuicUtils::IsConnectionIdValidForVersion(
2666 GetServerConnectionIdAsRecipient(header, perspective_),
2667 transport_version())) {
2668 set_detailed_error("Received server connection ID with invalid length.");
2669 return false;
2670 }
2671
2672 if (version_.SupportsClientConnectionIds() &&
2673 !QuicUtils::IsConnectionIdValidForVersion(
2674 GetClientConnectionIdAsRecipient(header, perspective_),
2675 transport_version())) {
2676 set_detailed_error("Received client connection ID with invalid length.");
2677 return false;
2678 }
2679 return true;
2680}
2681
QUICHE teama6ef0a62019-03-07 20:34:33 -05002682bool QuicFramer::ProcessIetfPacketHeader(QuicDataReader* reader,
2683 QuicPacketHeader* header) {
dschinazi48ac9192019-07-31 00:07:26 -07002684 if (version_.HasLengthPrefixedConnectionIds()) {
2685 uint8_t expected_destination_connection_id_length =
2686 perspective_ == Perspective::IS_CLIENT
2687 ? expected_client_connection_id_length_
2688 : expected_server_connection_id_length_;
2689 QuicVersionLabel version_label;
2690 bool has_length_prefix;
2691 std::string detailed_error;
2692 QuicErrorCode parse_result = QuicFramer::ParsePublicHeader(
2693 reader, expected_destination_connection_id_length,
2694 VersionHasIetfInvariantHeader(version_.transport_version),
2695 &header->type_byte, &header->form, &header->version_flag,
2696 &has_length_prefix, &version_label, &header->version,
2697 &header->destination_connection_id, &header->source_connection_id,
2698 &header->long_packet_type, &header->retry_token_length_length,
2699 &header->retry_token, &detailed_error);
2700 if (parse_result != QUIC_NO_ERROR) {
2701 set_detailed_error(detailed_error);
2702 return false;
2703 }
2704 header->destination_connection_id_included = CONNECTION_ID_PRESENT;
2705 header->source_connection_id_included =
2706 header->version_flag ? CONNECTION_ID_PRESENT : CONNECTION_ID_ABSENT;
2707 if (header->source_connection_id_included == CONNECTION_ID_ABSENT) {
2708 DCHECK(header->source_connection_id.IsEmpty());
2709 if (perspective_ == Perspective::IS_CLIENT) {
2710 header->source_connection_id = last_serialized_server_connection_id_;
2711 } else {
2712 header->source_connection_id = last_serialized_client_connection_id_;
2713 }
2714 }
dschinazib953d022019-08-01 18:05:58 -07002715
2716 if (!ValidateReceivedConnectionIds(*header)) {
2717 return false;
2718 }
2719
dschinazi48ac9192019-07-31 00:07:26 -07002720 if (header->version_flag &&
fayang36825da2019-08-21 14:01:27 -07002721 header->long_packet_type != VERSION_NEGOTIATION &&
dschinazi48ac9192019-07-31 00:07:26 -07002722 !(header->type_byte & FLAGS_FIXED_BIT)) {
2723 set_detailed_error("Fixed bit is 0 in long header.");
2724 return false;
2725 }
fayang36825da2019-08-21 14:01:27 -07002726 if (!header->version_flag && !(header->type_byte & FLAGS_FIXED_BIT)) {
dschinazi48ac9192019-07-31 00:07:26 -07002727 set_detailed_error("Fixed bit is 0 in short header.");
2728 return false;
2729 }
2730 if (!header->version_flag) {
fayang36825da2019-08-21 14:01:27 -07002731 if (!version_.HasHeaderProtection()) {
2732 header->packet_number_length =
2733 GetShortHeaderPacketNumberLength(header->type_byte);
dschinazi48ac9192019-07-31 00:07:26 -07002734 }
2735 return true;
2736 }
2737 if (header->long_packet_type == RETRY) {
2738 if (!version().SupportsRetry()) {
2739 set_detailed_error("RETRY not supported in this version.");
2740 return false;
2741 }
2742 if (perspective_ == Perspective::IS_SERVER) {
2743 set_detailed_error("Client-initiated RETRY is invalid.");
2744 return false;
2745 }
2746 return true;
2747 }
2748 if (!header->version.HasHeaderProtection()) {
fayang36825da2019-08-21 14:01:27 -07002749 header->packet_number_length =
2750 GetLongHeaderPacketNumberLength(header->type_byte);
dschinazi48ac9192019-07-31 00:07:26 -07002751 }
2752
2753 return true;
2754 }
2755
QUICHE teama6ef0a62019-03-07 20:34:33 -05002756 if (!ProcessIetfHeaderTypeByte(reader, header)) {
2757 return false;
2758 }
2759
2760 uint8_t destination_connection_id_length =
2761 header->destination_connection_id_included == CONNECTION_ID_PRESENT
dschinazi346b7ce2019-06-05 01:38:18 -07002762 ? (perspective_ == Perspective::IS_SERVER
2763 ? expected_server_connection_id_length_
2764 : expected_client_connection_id_length_)
QUICHE teama6ef0a62019-03-07 20:34:33 -05002765 : 0;
2766 uint8_t source_connection_id_length =
2767 header->source_connection_id_included == CONNECTION_ID_PRESENT
dschinazi346b7ce2019-06-05 01:38:18 -07002768 ? (perspective_ == Perspective::IS_CLIENT
2769 ? expected_server_connection_id_length_
2770 : expected_client_connection_id_length_)
QUICHE teama6ef0a62019-03-07 20:34:33 -05002771 : 0;
2772 if (header->form == IETF_QUIC_LONG_HEADER_PACKET) {
fayangccbab732019-05-13 10:11:25 -07002773 if (!ProcessAndValidateIetfConnectionIdLength(
dschinazi334f0232019-05-29 16:08:53 -07002774 reader, header->version, perspective_,
fayang91475c42019-06-19 08:04:26 -07002775 /*should_update_expected_server_connection_id_length=*/false,
dschinazi8ff74822019-05-28 16:37:20 -07002776 &expected_server_connection_id_length_,
2777 &destination_connection_id_length, &source_connection_id_length,
2778 &detailed_error_)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002779 return false;
2780 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002781 }
2782
2783 // Read connection ID.
2784 if (!reader->ReadConnectionId(&header->destination_connection_id,
2785 destination_connection_id_length)) {
dschinazi48ac9192019-07-31 00:07:26 -07002786 set_detailed_error("Unable to read destination connection ID.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05002787 return false;
2788 }
2789
2790 if (!reader->ReadConnectionId(&header->source_connection_id,
2791 source_connection_id_length)) {
dschinazi48ac9192019-07-31 00:07:26 -07002792 set_detailed_error("Unable to read source connection ID.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05002793 return false;
2794 }
2795
dschinazi5e1a7b22019-07-31 12:23:21 -07002796 if (header->source_connection_id_included == CONNECTION_ID_ABSENT) {
2797 if (!header->source_connection_id.IsEmpty()) {
2798 DCHECK(!version_.SupportsClientConnectionIds());
2799 set_detailed_error("Client connection ID not supported in this version.");
2800 return false;
QUICHE team2252b702019-05-14 23:55:14 -04002801 }
dschinazi5e1a7b22019-07-31 12:23:21 -07002802 if (perspective_ == Perspective::IS_CLIENT) {
2803 header->source_connection_id = last_serialized_server_connection_id_;
2804 } else {
2805 header->source_connection_id = last_serialized_client_connection_id_;
QUICHE team2252b702019-05-14 23:55:14 -04002806 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002807 }
2808
dschinazib953d022019-08-01 18:05:58 -07002809 return ValidateReceivedConnectionIds(*header);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002810}
2811
2812bool QuicFramer::ProcessAndCalculatePacketNumber(
2813 QuicDataReader* reader,
2814 QuicPacketNumberLength packet_number_length,
2815 QuicPacketNumber base_packet_number,
2816 uint64_t* packet_number) {
2817 uint64_t wire_packet_number;
2818 if (!reader->ReadBytesToUInt64(packet_number_length, &wire_packet_number)) {
2819 return false;
2820 }
2821
2822 // TODO(ianswett): Explore the usefulness of trying multiple packet numbers
2823 // in case the first guess is incorrect.
2824 *packet_number = CalculatePacketNumberFromWire(
2825 packet_number_length, base_packet_number, wire_packet_number);
2826 return true;
2827}
2828
2829bool QuicFramer::ProcessFrameData(QuicDataReader* reader,
2830 const QuicPacketHeader& header) {
fkastenholz305e1732019-06-18 05:01:22 -07002831 DCHECK(!VersionHasIetfQuicFrames(version_.transport_version))
2832 << "IETF QUIC Framing negotiated but attempting to process frames as "
2833 "non-IETF QUIC.";
QUICHE teama6ef0a62019-03-07 20:34:33 -05002834 if (reader->IsDoneReading()) {
2835 set_detailed_error("Packet has no frames.");
2836 return RaiseError(QUIC_MISSING_PAYLOAD);
2837 }
dschinazi118934b2019-06-13 18:09:08 -07002838 QUIC_DVLOG(2) << ENDPOINT << "Processing packet with header " << header;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002839 while (!reader->IsDoneReading()) {
2840 uint8_t frame_type;
2841 if (!reader->ReadBytes(&frame_type, 1)) {
2842 set_detailed_error("Unable to read frame type.");
2843 return RaiseError(QUIC_INVALID_FRAME_DATA);
2844 }
fayang36825da2019-08-21 14:01:27 -07002845 const uint8_t special_mask = transport_version() <= QUIC_VERSION_43
QUICHE teama6ef0a62019-03-07 20:34:33 -05002846 ? kQuicFrameTypeBrokenMask
2847 : kQuicFrameTypeSpecialMask;
2848 if (frame_type & special_mask) {
2849 // Stream Frame
2850 if (frame_type & kQuicFrameTypeStreamMask) {
2851 QuicStreamFrame frame;
2852 if (!ProcessStreamFrame(reader, frame_type, &frame)) {
2853 return RaiseError(QUIC_INVALID_STREAM_DATA);
2854 }
dschinazi118934b2019-06-13 18:09:08 -07002855 QUIC_DVLOG(2) << ENDPOINT << "Processing stream frame " << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002856 if (!visitor_->OnStreamFrame(frame)) {
2857 QUIC_DVLOG(1) << ENDPOINT
2858 << "Visitor asked to stop further processing.";
2859 // Returning true since there was no parsing error.
2860 return true;
2861 }
2862 continue;
2863 }
2864
2865 // Ack Frame
2866 if (frame_type & kQuicFrameTypeAckMask) {
2867 if (!ProcessAckFrame(reader, frame_type)) {
2868 return RaiseError(QUIC_INVALID_ACK_DATA);
2869 }
dschinazi118934b2019-06-13 18:09:08 -07002870 QUIC_DVLOG(2) << ENDPOINT << "Processing ACK frame";
QUICHE teama6ef0a62019-03-07 20:34:33 -05002871 continue;
2872 }
2873
2874 // This was a special frame type that did not match any
2875 // of the known ones. Error.
2876 set_detailed_error("Illegal frame type.");
2877 QUIC_DLOG(WARNING) << ENDPOINT << "Illegal frame type: "
2878 << static_cast<int>(frame_type);
2879 return RaiseError(QUIC_INVALID_FRAME_DATA);
2880 }
2881
2882 switch (frame_type) {
2883 case PADDING_FRAME: {
2884 QuicPaddingFrame frame;
2885 ProcessPaddingFrame(reader, &frame);
dschinazi118934b2019-06-13 18:09:08 -07002886 QUIC_DVLOG(2) << ENDPOINT << "Processing padding frame " << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002887 if (!visitor_->OnPaddingFrame(frame)) {
2888 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
2889 // Returning true since there was no parsing error.
2890 return true;
2891 }
2892 continue;
2893 }
2894
2895 case RST_STREAM_FRAME: {
2896 QuicRstStreamFrame frame;
2897 if (!ProcessRstStreamFrame(reader, &frame)) {
2898 return RaiseError(QUIC_INVALID_RST_STREAM_DATA);
2899 }
dschinazi118934b2019-06-13 18:09:08 -07002900 QUIC_DVLOG(2) << ENDPOINT << "Processing reset stream frame " << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002901 if (!visitor_->OnRstStreamFrame(frame)) {
2902 QUIC_DVLOG(1) << "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 CONNECTION_CLOSE_FRAME: {
2910 QuicConnectionCloseFrame frame;
2911 if (!ProcessConnectionCloseFrame(reader, &frame)) {
2912 return RaiseError(QUIC_INVALID_CONNECTION_CLOSE_DATA);
2913 }
2914
dschinazi118934b2019-06-13 18:09:08 -07002915 QUIC_DVLOG(2) << ENDPOINT << "Processing connection close frame "
2916 << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002917 if (!visitor_->OnConnectionCloseFrame(frame)) {
2918 QUIC_DVLOG(1) << ENDPOINT
2919 << "Visitor asked to stop further processing.";
2920 // Returning true since there was no parsing error.
2921 return true;
2922 }
2923 continue;
2924 }
2925
2926 case GOAWAY_FRAME: {
2927 QuicGoAwayFrame goaway_frame;
2928 if (!ProcessGoAwayFrame(reader, &goaway_frame)) {
2929 return RaiseError(QUIC_INVALID_GOAWAY_DATA);
2930 }
dschinazi118934b2019-06-13 18:09:08 -07002931 QUIC_DVLOG(2) << ENDPOINT << "Processing go away frame "
2932 << goaway_frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002933 if (!visitor_->OnGoAwayFrame(goaway_frame)) {
2934 QUIC_DVLOG(1) << ENDPOINT
2935 << "Visitor asked to stop further processing.";
2936 // Returning true since there was no parsing error.
2937 return true;
2938 }
2939 continue;
2940 }
2941
2942 case WINDOW_UPDATE_FRAME: {
2943 QuicWindowUpdateFrame window_update_frame;
2944 if (!ProcessWindowUpdateFrame(reader, &window_update_frame)) {
2945 return RaiseError(QUIC_INVALID_WINDOW_UPDATE_DATA);
2946 }
dschinazi118934b2019-06-13 18:09:08 -07002947 QUIC_DVLOG(2) << ENDPOINT << "Processing window update frame "
2948 << window_update_frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002949 if (!visitor_->OnWindowUpdateFrame(window_update_frame)) {
2950 QUIC_DVLOG(1) << ENDPOINT
2951 << "Visitor asked to stop further processing.";
2952 // Returning true since there was no parsing error.
2953 return true;
2954 }
2955 continue;
2956 }
2957
2958 case BLOCKED_FRAME: {
2959 QuicBlockedFrame blocked_frame;
2960 if (!ProcessBlockedFrame(reader, &blocked_frame)) {
2961 return RaiseError(QUIC_INVALID_BLOCKED_DATA);
2962 }
dschinazi118934b2019-06-13 18:09:08 -07002963 QUIC_DVLOG(2) << ENDPOINT << "Processing blocked frame "
2964 << blocked_frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002965 if (!visitor_->OnBlockedFrame(blocked_frame)) {
2966 QUIC_DVLOG(1) << ENDPOINT
2967 << "Visitor asked to stop further processing.";
2968 // Returning true since there was no parsing error.
2969 return true;
2970 }
2971 continue;
2972 }
2973
2974 case STOP_WAITING_FRAME: {
ianswett97b690b2019-05-02 15:12:43 -07002975 if (GetQuicReloadableFlag(quic_do_not_accept_stop_waiting) &&
fayang36825da2019-08-21 14:01:27 -07002976 version_.transport_version > QUIC_VERSION_43) {
ianswett97b690b2019-05-02 15:12:43 -07002977 QUIC_RELOADABLE_FLAG_COUNT(quic_do_not_accept_stop_waiting);
2978 set_detailed_error("STOP WAITING not supported in version 44+.");
2979 return RaiseError(QUIC_INVALID_STOP_WAITING_DATA);
2980 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002981 QuicStopWaitingFrame stop_waiting_frame;
2982 if (!ProcessStopWaitingFrame(reader, header, &stop_waiting_frame)) {
2983 return RaiseError(QUIC_INVALID_STOP_WAITING_DATA);
2984 }
dschinazi118934b2019-06-13 18:09:08 -07002985 QUIC_DVLOG(2) << ENDPOINT << "Processing stop waiting frame "
2986 << stop_waiting_frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002987 if (!visitor_->OnStopWaitingFrame(stop_waiting_frame)) {
2988 QUIC_DVLOG(1) << ENDPOINT
2989 << "Visitor asked to stop further processing.";
2990 // Returning true since there was no parsing error.
2991 return true;
2992 }
2993 continue;
2994 }
2995 case PING_FRAME: {
2996 // Ping has no payload.
2997 QuicPingFrame ping_frame;
2998 if (!visitor_->OnPingFrame(ping_frame)) {
2999 QUIC_DVLOG(1) << ENDPOINT
3000 << "Visitor asked to stop further processing.";
3001 // Returning true since there was no parsing error.
3002 return true;
3003 }
dschinazi118934b2019-06-13 18:09:08 -07003004 QUIC_DVLOG(2) << ENDPOINT << "Processing ping frame " << ping_frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003005 continue;
3006 }
3007 case IETF_EXTENSION_MESSAGE_NO_LENGTH:
3008 QUIC_FALLTHROUGH_INTENDED;
3009 case IETF_EXTENSION_MESSAGE: {
3010 QuicMessageFrame message_frame;
3011 if (!ProcessMessageFrame(reader,
3012 frame_type == IETF_EXTENSION_MESSAGE_NO_LENGTH,
3013 &message_frame)) {
3014 return RaiseError(QUIC_INVALID_MESSAGE_DATA);
3015 }
dschinazi118934b2019-06-13 18:09:08 -07003016 QUIC_DVLOG(2) << ENDPOINT << "Processing message frame "
3017 << message_frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003018 if (!visitor_->OnMessageFrame(message_frame)) {
3019 QUIC_DVLOG(1) << ENDPOINT
3020 << "Visitor asked to stop further processing.";
3021 // Returning true since there was no parsing error.
3022 return true;
3023 }
3024 break;
3025 }
3026 case CRYPTO_FRAME: {
QUICHE teamea740082019-03-11 17:58:43 -07003027 if (!QuicVersionUsesCryptoFrames(version_.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05003028 set_detailed_error("Illegal frame type.");
3029 return RaiseError(QUIC_INVALID_FRAME_DATA);
3030 }
3031 QuicCryptoFrame frame;
3032 if (!ProcessCryptoFrame(reader, &frame)) {
3033 return RaiseError(QUIC_INVALID_FRAME_DATA);
3034 }
dschinazi118934b2019-06-13 18:09:08 -07003035 QUIC_DVLOG(2) << ENDPOINT << "Processing crypto frame " << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003036 if (!visitor_->OnCryptoFrame(frame)) {
3037 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3038 // Returning true since there was no parsing error.
3039 return true;
3040 }
3041 break;
3042 }
3043
3044 default:
3045 set_detailed_error("Illegal frame type.");
3046 QUIC_DLOG(WARNING) << ENDPOINT << "Illegal frame type: "
3047 << static_cast<int>(frame_type);
3048 return RaiseError(QUIC_INVALID_FRAME_DATA);
3049 }
3050 }
3051
3052 return true;
3053}
3054
3055bool QuicFramer::ProcessIetfFrameData(QuicDataReader* reader,
3056 const QuicPacketHeader& header) {
fkastenholz305e1732019-06-18 05:01:22 -07003057 DCHECK(VersionHasIetfQuicFrames(version_.transport_version))
3058 << "Attempt to process frames as IETF frames but version ("
3059 << version_.transport_version << ") does not support IETF Framing.";
3060
QUICHE teama6ef0a62019-03-07 20:34:33 -05003061 if (reader->IsDoneReading()) {
3062 set_detailed_error("Packet has no frames.");
3063 return RaiseError(QUIC_MISSING_PAYLOAD);
3064 }
dschinazi118934b2019-06-13 18:09:08 -07003065
3066 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF packet with header " << header;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003067 while (!reader->IsDoneReading()) {
3068 uint64_t frame_type;
3069 // Will be the number of bytes into which frame_type was encoded.
3070 size_t encoded_bytes = reader->BytesRemaining();
3071 if (!reader->ReadVarInt62(&frame_type)) {
3072 set_detailed_error("Unable to read frame type.");
3073 return RaiseError(QUIC_INVALID_FRAME_DATA);
3074 }
fkastenholza3660102019-08-28 05:19:24 -07003075 current_received_frame_type_ = frame_type;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003076
3077 // Is now the number of bytes into which the frame type was encoded.
3078 encoded_bytes -= reader->BytesRemaining();
3079
3080 // Check that the frame type is minimally encoded.
3081 if (encoded_bytes !=
3082 static_cast<size_t>(QuicDataWriter::GetVarInt62Len(frame_type))) {
3083 // The frame type was not minimally encoded.
3084 set_detailed_error("Frame type not minimally encoded.");
3085 return RaiseError(IETF_QUIC_PROTOCOL_VIOLATION);
3086 }
3087
3088 if (IS_IETF_STREAM_FRAME(frame_type)) {
3089 QuicStreamFrame frame;
3090 if (!ProcessIetfStreamFrame(reader, frame_type, &frame)) {
3091 return RaiseError(QUIC_INVALID_STREAM_DATA);
3092 }
dschinazi118934b2019-06-13 18:09:08 -07003093 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF stream frame " << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003094 if (!visitor_->OnStreamFrame(frame)) {
3095 QUIC_DVLOG(1) << ENDPOINT
3096 << "Visitor asked to stop further processing.";
3097 // Returning true since there was no parsing error.
3098 return true;
3099 }
3100 } else {
3101 switch (frame_type) {
3102 case IETF_PADDING: {
3103 QuicPaddingFrame frame;
3104 ProcessPaddingFrame(reader, &frame);
dschinazi118934b2019-06-13 18:09:08 -07003105 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF padding frame "
3106 << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003107 if (!visitor_->OnPaddingFrame(frame)) {
3108 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3109 // Returning true since there was no parsing error.
3110 return true;
3111 }
3112 break;
3113 }
3114 case IETF_RST_STREAM: {
3115 QuicRstStreamFrame frame;
3116 if (!ProcessIetfResetStreamFrame(reader, &frame)) {
3117 return RaiseError(QUIC_INVALID_RST_STREAM_DATA);
3118 }
dschinazi118934b2019-06-13 18:09:08 -07003119 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF reset stream frame "
3120 << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003121 if (!visitor_->OnRstStreamFrame(frame)) {
3122 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3123 // Returning true since there was no parsing error.
3124 return true;
3125 }
3126 break;
3127 }
fkastenholz04bd4f32019-04-16 12:24:38 -07003128 case IETF_APPLICATION_CLOSE:
QUICHE teama6ef0a62019-03-07 20:34:33 -05003129 case IETF_CONNECTION_CLOSE: {
3130 QuicConnectionCloseFrame frame;
fkastenholze9d71a82019-04-09 05:12:13 -07003131 if (!ProcessIetfConnectionCloseFrame(
fkastenholz04bd4f32019-04-16 12:24:38 -07003132 reader,
3133 (frame_type == IETF_CONNECTION_CLOSE)
3134 ? IETF_QUIC_TRANSPORT_CONNECTION_CLOSE
3135 : IETF_QUIC_APPLICATION_CONNECTION_CLOSE,
3136 &frame)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05003137 return RaiseError(QUIC_INVALID_CONNECTION_CLOSE_DATA);
3138 }
dschinazi118934b2019-06-13 18:09:08 -07003139 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF connection close frame "
3140 << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003141 if (!visitor_->OnConnectionCloseFrame(frame)) {
3142 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3143 // Returning true since there was no parsing error.
3144 return true;
3145 }
3146 break;
3147 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05003148 case IETF_MAX_DATA: {
3149 QuicWindowUpdateFrame frame;
3150 if (!ProcessMaxDataFrame(reader, &frame)) {
3151 return RaiseError(QUIC_INVALID_MAX_DATA_FRAME_DATA);
3152 }
3153 // TODO(fkastenholz): Or should we create a new visitor function,
3154 // OnMaxDataFrame()?
dschinazi118934b2019-06-13 18:09:08 -07003155 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF max data frame "
3156 << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003157 if (!visitor_->OnWindowUpdateFrame(frame)) {
3158 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3159 // Returning true since there was no parsing error.
3160 return true;
3161 }
3162 break;
3163 }
3164 case IETF_MAX_STREAM_DATA: {
3165 QuicWindowUpdateFrame frame;
3166 if (!ProcessMaxStreamDataFrame(reader, &frame)) {
3167 return RaiseError(QUIC_INVALID_MAX_STREAM_DATA_FRAME_DATA);
3168 }
3169 // TODO(fkastenholz): Or should we create a new visitor function,
3170 // OnMaxStreamDataFrame()?
dschinazi118934b2019-06-13 18:09:08 -07003171 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF max stream data frame "
3172 << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003173 if (!visitor_->OnWindowUpdateFrame(frame)) {
3174 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3175 // Returning true since there was no parsing error.
3176 return true;
3177 }
3178 break;
3179 }
3180 case IETF_MAX_STREAMS_BIDIRECTIONAL:
3181 case IETF_MAX_STREAMS_UNIDIRECTIONAL: {
fkastenholz3c4eabf2019-04-22 07:49:59 -07003182 QuicMaxStreamsFrame frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003183 if (!ProcessMaxStreamsFrame(reader, &frame, frame_type)) {
fkastenholz3c4eabf2019-04-22 07:49:59 -07003184 return RaiseError(QUIC_MAX_STREAMS_DATA);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003185 }
fkastenholz3c4eabf2019-04-22 07:49:59 -07003186 QUIC_CODE_COUNT_N(quic_max_streams_received, 1, 2);
dschinazi118934b2019-06-13 18:09:08 -07003187 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF max streams frame "
3188 << frame;
fkastenholz3c4eabf2019-04-22 07:49:59 -07003189 if (!visitor_->OnMaxStreamsFrame(frame)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05003190 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3191 // Returning true since there was no parsing error.
3192 return true;
3193 }
3194 break;
3195 }
3196 case IETF_PING: {
3197 // Ping has no payload.
3198 QuicPingFrame ping_frame;
dschinazi118934b2019-06-13 18:09:08 -07003199 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF ping frame "
3200 << ping_frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003201 if (!visitor_->OnPingFrame(ping_frame)) {
3202 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3203 // Returning true since there was no parsing error.
3204 return true;
3205 }
3206 break;
3207 }
3208 case IETF_BLOCKED: {
3209 QuicBlockedFrame frame;
3210 if (!ProcessIetfBlockedFrame(reader, &frame)) {
3211 return RaiseError(QUIC_INVALID_BLOCKED_DATA);
3212 }
dschinazi118934b2019-06-13 18:09:08 -07003213 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF blocked frame "
3214 << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003215 if (!visitor_->OnBlockedFrame(frame)) {
3216 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3217 // Returning true since there was no parsing error.
3218 return true;
3219 }
3220 break;
3221 }
3222 case IETF_STREAM_BLOCKED: {
3223 QuicBlockedFrame frame;
3224 if (!ProcessStreamBlockedFrame(reader, &frame)) {
3225 return RaiseError(QUIC_INVALID_STREAM_BLOCKED_DATA);
3226 }
dschinazi118934b2019-06-13 18:09:08 -07003227 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF stream blocked frame "
3228 << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003229 if (!visitor_->OnBlockedFrame(frame)) {
3230 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3231 // Returning true since there was no parsing error.
3232 return true;
3233 }
3234 break;
3235 }
3236 case IETF_STREAMS_BLOCKED_UNIDIRECTIONAL:
3237 case IETF_STREAMS_BLOCKED_BIDIRECTIONAL: {
fkastenholz3c4eabf2019-04-22 07:49:59 -07003238 QuicStreamsBlockedFrame frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003239 if (!ProcessStreamsBlockedFrame(reader, &frame, frame_type)) {
fkastenholz3c4eabf2019-04-22 07:49:59 -07003240 return RaiseError(QUIC_STREAMS_BLOCKED_DATA);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003241 }
fkastenholz3c4eabf2019-04-22 07:49:59 -07003242 QUIC_CODE_COUNT_N(quic_streams_blocked_received, 1, 2);
dschinazi118934b2019-06-13 18:09:08 -07003243 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF streams blocked frame "
3244 << frame;
fkastenholz3c4eabf2019-04-22 07:49:59 -07003245 if (!visitor_->OnStreamsBlockedFrame(frame)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05003246 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3247 // Returning true since there was no parsing error.
3248 return true;
3249 }
3250 break;
3251 }
3252 case IETF_NEW_CONNECTION_ID: {
3253 QuicNewConnectionIdFrame frame;
3254 if (!ProcessNewConnectionIdFrame(reader, &frame)) {
3255 return RaiseError(QUIC_INVALID_NEW_CONNECTION_ID_DATA);
3256 }
dschinazi118934b2019-06-13 18:09:08 -07003257 QUIC_DVLOG(2) << ENDPOINT
3258 << "Processing IETF new connection ID frame " << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003259 if (!visitor_->OnNewConnectionIdFrame(frame)) {
3260 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3261 // Returning true since there was no parsing error.
3262 return true;
3263 }
3264 break;
3265 }
3266 case IETF_RETIRE_CONNECTION_ID: {
3267 QuicRetireConnectionIdFrame frame;
3268 if (!ProcessRetireConnectionIdFrame(reader, &frame)) {
3269 return RaiseError(QUIC_INVALID_RETIRE_CONNECTION_ID_DATA);
3270 }
dschinazi118934b2019-06-13 18:09:08 -07003271 QUIC_DVLOG(2) << ENDPOINT
3272 << "Processing IETF retire connection ID frame "
3273 << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003274 if (!visitor_->OnRetireConnectionIdFrame(frame)) {
3275 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3276 // Returning true since there was no parsing error.
3277 return true;
3278 }
3279 break;
3280 }
3281 case IETF_NEW_TOKEN: {
3282 QuicNewTokenFrame frame;
3283 if (!ProcessNewTokenFrame(reader, &frame)) {
3284 return RaiseError(QUIC_INVALID_NEW_TOKEN);
3285 }
dschinazi118934b2019-06-13 18:09:08 -07003286 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF new token frame "
3287 << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003288 if (!visitor_->OnNewTokenFrame(frame)) {
3289 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3290 // Returning true since there was no parsing error.
3291 return true;
3292 }
3293 break;
3294 }
3295 case IETF_STOP_SENDING: {
3296 QuicStopSendingFrame frame;
3297 if (!ProcessStopSendingFrame(reader, &frame)) {
3298 return RaiseError(QUIC_INVALID_STOP_SENDING_FRAME_DATA);
3299 }
dschinazi118934b2019-06-13 18:09:08 -07003300 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF stop sending frame "
3301 << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003302 if (!visitor_->OnStopSendingFrame(frame)) {
3303 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3304 // Returning true since there was no parsing error.
3305 return true;
3306 }
3307 break;
3308 }
3309 case IETF_ACK_ECN:
3310 case IETF_ACK: {
3311 QuicAckFrame frame;
3312 if (!ProcessIetfAckFrame(reader, frame_type, &frame)) {
3313 return RaiseError(QUIC_INVALID_ACK_DATA);
3314 }
dschinazi118934b2019-06-13 18:09:08 -07003315 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF ACK frame " << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003316 break;
3317 }
3318 case IETF_PATH_CHALLENGE: {
3319 QuicPathChallengeFrame frame;
3320 if (!ProcessPathChallengeFrame(reader, &frame)) {
3321 return RaiseError(QUIC_INVALID_PATH_CHALLENGE_DATA);
3322 }
dschinazi118934b2019-06-13 18:09:08 -07003323 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF path challenge frame "
3324 << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003325 if (!visitor_->OnPathChallengeFrame(frame)) {
3326 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3327 // Returning true since there was no parsing error.
3328 return true;
3329 }
3330 break;
3331 }
3332 case IETF_PATH_RESPONSE: {
3333 QuicPathResponseFrame frame;
3334 if (!ProcessPathResponseFrame(reader, &frame)) {
3335 return RaiseError(QUIC_INVALID_PATH_RESPONSE_DATA);
3336 }
dschinazi118934b2019-06-13 18:09:08 -07003337 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF path response frame "
3338 << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003339 if (!visitor_->OnPathResponseFrame(frame)) {
3340 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3341 // Returning true since there was no parsing error.
3342 return true;
3343 }
3344 break;
3345 }
3346 case IETF_EXTENSION_MESSAGE_NO_LENGTH:
3347 QUIC_FALLTHROUGH_INTENDED;
3348 case IETF_EXTENSION_MESSAGE: {
3349 QuicMessageFrame message_frame;
3350 if (!ProcessMessageFrame(
3351 reader, frame_type == IETF_EXTENSION_MESSAGE_NO_LENGTH,
3352 &message_frame)) {
3353 return RaiseError(QUIC_INVALID_MESSAGE_DATA);
3354 }
dschinazi118934b2019-06-13 18:09:08 -07003355 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF message frame "
3356 << message_frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003357 if (!visitor_->OnMessageFrame(message_frame)) {
3358 QUIC_DVLOG(1) << ENDPOINT
3359 << "Visitor asked to stop further processing.";
3360 // Returning true since there was no parsing error.
3361 return true;
3362 }
3363 break;
3364 }
3365 case IETF_CRYPTO: {
3366 QuicCryptoFrame frame;
3367 if (!ProcessCryptoFrame(reader, &frame)) {
3368 return RaiseError(QUIC_INVALID_FRAME_DATA);
3369 }
dschinazi118934b2019-06-13 18:09:08 -07003370 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF crypto frame " << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003371 if (!visitor_->OnCryptoFrame(frame)) {
3372 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3373 // Returning true since there was no parsing error.
3374 return true;
3375 }
3376 break;
3377 }
3378
3379 default:
3380 set_detailed_error("Illegal frame type.");
3381 QUIC_DLOG(WARNING)
3382 << ENDPOINT
3383 << "Illegal frame type: " << static_cast<int>(frame_type);
3384 return RaiseError(QUIC_INVALID_FRAME_DATA);
3385 }
3386 }
3387 }
3388 return true;
3389}
3390
3391namespace {
3392// Create a mask that sets the last |num_bits| to 1 and the rest to 0.
3393inline uint8_t GetMaskFromNumBits(uint8_t num_bits) {
3394 return (1u << num_bits) - 1;
3395}
3396
3397// Extract |num_bits| from |flags| offset by |offset|.
3398uint8_t ExtractBits(uint8_t flags, uint8_t num_bits, uint8_t offset) {
3399 return (flags >> offset) & GetMaskFromNumBits(num_bits);
3400}
3401
3402// Extract the bit at position |offset| from |flags| as a bool.
3403bool ExtractBit(uint8_t flags, uint8_t offset) {
3404 return ((flags >> offset) & GetMaskFromNumBits(1)) != 0;
3405}
3406
3407// Set |num_bits|, offset by |offset| to |val| in |flags|.
3408void SetBits(uint8_t* flags, uint8_t val, uint8_t num_bits, uint8_t offset) {
3409 DCHECK_LE(val, GetMaskFromNumBits(num_bits));
3410 *flags |= val << offset;
3411}
3412
3413// Set the bit at position |offset| to |val| in |flags|.
3414void SetBit(uint8_t* flags, bool val, uint8_t offset) {
3415 SetBits(flags, val ? 1 : 0, 1, offset);
3416}
3417} // namespace
3418
3419bool QuicFramer::ProcessStreamFrame(QuicDataReader* reader,
3420 uint8_t frame_type,
3421 QuicStreamFrame* frame) {
3422 uint8_t stream_flags = frame_type;
3423
3424 uint8_t stream_id_length = 0;
3425 uint8_t offset_length = 4;
3426 bool has_data_length = true;
3427 stream_flags &= ~kQuicFrameTypeStreamMask;
3428
3429 // Read from right to left: StreamID, Offset, Data Length, Fin.
3430 stream_id_length = (stream_flags & kQuicStreamIDLengthMask) + 1;
3431 stream_flags >>= kQuicStreamIdShift;
3432
3433 offset_length = (stream_flags & kQuicStreamOffsetMask);
3434 // There is no encoding for 1 byte, only 0 and 2 through 8.
3435 if (offset_length > 0) {
3436 offset_length += 1;
3437 }
3438 stream_flags >>= kQuicStreamShift;
3439
3440 has_data_length =
3441 (stream_flags & kQuicStreamDataLengthMask) == kQuicStreamDataLengthMask;
3442 stream_flags >>= kQuicStreamDataLengthShift;
3443
3444 frame->fin = (stream_flags & kQuicStreamFinMask) == kQuicStreamFinShift;
3445
3446 uint64_t stream_id;
3447 if (!reader->ReadBytesToUInt64(stream_id_length, &stream_id)) {
3448 set_detailed_error("Unable to read stream_id.");
3449 return false;
3450 }
3451 frame->stream_id = static_cast<QuicStreamId>(stream_id);
3452
3453 if (!reader->ReadBytesToUInt64(offset_length, &frame->offset)) {
3454 set_detailed_error("Unable to read offset.");
3455 return false;
3456 }
3457
3458 // TODO(ianswett): Don't use QuicStringPiece as an intermediary.
3459 QuicStringPiece data;
3460 if (has_data_length) {
3461 if (!reader->ReadStringPiece16(&data)) {
3462 set_detailed_error("Unable to read frame data.");
3463 return false;
3464 }
3465 } else {
3466 if (!reader->ReadStringPiece(&data, reader->BytesRemaining())) {
3467 set_detailed_error("Unable to read frame data.");
3468 return false;
3469 }
3470 }
3471 frame->data_buffer = data.data();
3472 frame->data_length = static_cast<uint16_t>(data.length());
3473
3474 return true;
3475}
3476
3477bool QuicFramer::ProcessIetfStreamFrame(QuicDataReader* reader,
3478 uint8_t frame_type,
3479 QuicStreamFrame* frame) {
3480 // Read stream id from the frame. It's always present.
fkastenholz3c4eabf2019-04-22 07:49:59 -07003481 if (!reader->ReadVarIntU32(&frame->stream_id)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05003482 set_detailed_error("Unable to read stream_id.");
3483 return false;
3484 }
3485
3486 // If we have a data offset, read it. If not, set to 0.
3487 if (frame_type & IETF_STREAM_FRAME_OFF_BIT) {
3488 if (!reader->ReadVarInt62(&frame->offset)) {
3489 set_detailed_error("Unable to read stream data offset.");
3490 return false;
3491 }
3492 } else {
3493 // no offset in the frame, ensure it's 0 in the Frame.
3494 frame->offset = 0;
3495 }
3496
3497 // If we have a data length, read it. If not, set to 0.
3498 if (frame_type & IETF_STREAM_FRAME_LEN_BIT) {
3499 QuicIetfStreamDataLength length;
3500 if (!reader->ReadVarInt62(&length)) {
3501 set_detailed_error("Unable to read stream data length.");
3502 return false;
3503 }
3504 if (length > 0xffff) {
3505 set_detailed_error("Stream data length is too large.");
3506 return false;
3507 }
3508 frame->data_length = length;
3509 } else {
3510 // no length in the frame, it is the number of bytes remaining in the
3511 // packet.
3512 frame->data_length = reader->BytesRemaining();
3513 }
3514
3515 if (frame_type & IETF_STREAM_FRAME_FIN_BIT) {
3516 frame->fin = true;
3517 } else {
3518 frame->fin = false;
3519 }
3520
3521 // TODO(ianswett): Don't use QuicStringPiece as an intermediary.
3522 QuicStringPiece data;
3523 if (!reader->ReadStringPiece(&data, frame->data_length)) {
3524 set_detailed_error("Unable to read frame data.");
3525 return false;
3526 }
3527 frame->data_buffer = data.data();
3528 frame->data_length = static_cast<QuicIetfStreamDataLength>(data.length());
3529
3530 return true;
3531}
3532
3533bool QuicFramer::ProcessCryptoFrame(QuicDataReader* reader,
3534 QuicCryptoFrame* frame) {
3535 if (!reader->ReadVarInt62(&frame->offset)) {
3536 set_detailed_error("Unable to read crypto data offset.");
3537 return false;
3538 }
3539 uint64_t len;
3540 if (!reader->ReadVarInt62(&len) ||
3541 len > std::numeric_limits<QuicPacketLength>::max()) {
3542 set_detailed_error("Invalid data length.");
3543 return false;
3544 }
3545 frame->data_length = len;
3546
3547 // TODO(ianswett): Don't use QuicStringPiece as an intermediary.
3548 QuicStringPiece data;
3549 if (!reader->ReadStringPiece(&data, frame->data_length)) {
3550 set_detailed_error("Unable to read frame data.");
3551 return false;
3552 }
3553 frame->data_buffer = data.data();
3554 return true;
3555}
3556
3557bool QuicFramer::ProcessAckFrame(QuicDataReader* reader, uint8_t frame_type) {
3558 const bool has_ack_blocks =
3559 ExtractBit(frame_type, kQuicHasMultipleAckBlocksOffset);
3560 uint8_t num_ack_blocks = 0;
3561 uint8_t num_received_packets = 0;
3562
3563 // Determine the two lengths from the frame type: largest acked length,
3564 // ack block length.
3565 const QuicPacketNumberLength ack_block_length = ReadAckPacketNumberLength(
3566 version_.transport_version,
3567 ExtractBits(frame_type, kQuicSequenceNumberLengthNumBits,
3568 kActBlockLengthOffset));
3569 const QuicPacketNumberLength largest_acked_length = ReadAckPacketNumberLength(
3570 version_.transport_version,
3571 ExtractBits(frame_type, kQuicSequenceNumberLengthNumBits,
3572 kLargestAckedOffset));
3573
3574 uint64_t largest_acked;
3575 if (!reader->ReadBytesToUInt64(largest_acked_length, &largest_acked)) {
3576 set_detailed_error("Unable to read largest acked.");
3577 return false;
3578 }
3579
3580 if (largest_acked < first_sending_packet_number_.ToUint64()) {
3581 // Connection always sends packet starting from kFirstSendingPacketNumber >
3582 // 0, peer has observed an unsent packet.
3583 set_detailed_error("Largest acked is 0.");
3584 return false;
3585 }
3586
3587 uint64_t ack_delay_time_us;
3588 if (!reader->ReadUFloat16(&ack_delay_time_us)) {
3589 set_detailed_error("Unable to read ack delay time.");
3590 return false;
3591 }
3592
3593 if (!visitor_->OnAckFrameStart(
3594 QuicPacketNumber(largest_acked),
3595 ack_delay_time_us == kUFloat16MaxValue
3596 ? QuicTime::Delta::Infinite()
3597 : QuicTime::Delta::FromMicroseconds(ack_delay_time_us))) {
3598 // The visitor suppresses further processing of the packet. Although this is
3599 // not a parsing error, returns false as this is in middle of processing an
3600 // ack frame,
3601 set_detailed_error("Visitor suppresses further processing of ack frame.");
3602 return false;
3603 }
3604
3605 if (has_ack_blocks && !reader->ReadUInt8(&num_ack_blocks)) {
3606 set_detailed_error("Unable to read num of ack blocks.");
3607 return false;
3608 }
3609
3610 uint64_t first_block_length;
3611 if (!reader->ReadBytesToUInt64(ack_block_length, &first_block_length)) {
3612 set_detailed_error("Unable to read first ack block length.");
3613 return false;
3614 }
3615
3616 if (first_block_length == 0) {
3617 set_detailed_error("First block length is zero.");
3618 return false;
3619 }
3620 bool first_ack_block_underflow = first_block_length > largest_acked + 1;
3621 if (first_block_length + first_sending_packet_number_.ToUint64() >
3622 largest_acked + 1) {
3623 first_ack_block_underflow = true;
3624 }
3625 if (first_ack_block_underflow) {
3626 set_detailed_error(QuicStrCat("Underflow with first ack block length ",
3627 first_block_length, " largest acked is ",
3628 largest_acked, ".")
3629 .c_str());
3630 return false;
3631 }
3632
3633 uint64_t first_received = largest_acked + 1 - first_block_length;
3634 if (!visitor_->OnAckRange(QuicPacketNumber(first_received),
3635 QuicPacketNumber(largest_acked + 1))) {
3636 // The visitor suppresses further processing of the packet. Although
3637 // this is not a parsing error, returns false as this is in middle
3638 // of processing an ack frame,
3639 set_detailed_error("Visitor suppresses further processing of ack frame.");
3640 return false;
3641 }
3642
3643 if (num_ack_blocks > 0) {
3644 for (size_t i = 0; i < num_ack_blocks; ++i) {
3645 uint8_t gap = 0;
3646 if (!reader->ReadUInt8(&gap)) {
3647 set_detailed_error("Unable to read gap to next ack block.");
3648 return false;
3649 }
3650 uint64_t current_block_length;
3651 if (!reader->ReadBytesToUInt64(ack_block_length, &current_block_length)) {
3652 set_detailed_error("Unable to ack block length.");
3653 return false;
3654 }
3655 bool ack_block_underflow = first_received < gap + current_block_length;
3656 if (first_received < gap + current_block_length +
3657 first_sending_packet_number_.ToUint64()) {
3658 ack_block_underflow = true;
3659 }
3660 if (ack_block_underflow) {
3661 set_detailed_error(
3662 QuicStrCat("Underflow with ack block length ", current_block_length,
3663 ", end of block is ", first_received - gap, ".")
3664 .c_str());
3665 return false;
3666 }
3667
3668 first_received -= (gap + current_block_length);
3669 if (current_block_length > 0) {
3670 if (!visitor_->OnAckRange(
3671 QuicPacketNumber(first_received),
3672 QuicPacketNumber(first_received) + current_block_length)) {
3673 // The visitor suppresses further processing of the packet. Although
3674 // this is not a parsing error, returns false as this is in middle
3675 // of processing an ack frame,
3676 set_detailed_error(
3677 "Visitor suppresses further processing of ack frame.");
3678 return false;
3679 }
3680 }
3681 }
3682 }
3683
3684 if (!reader->ReadUInt8(&num_received_packets)) {
3685 set_detailed_error("Unable to read num received packets.");
3686 return false;
3687 }
3688
3689 if (!ProcessTimestampsInAckFrame(num_received_packets,
3690 QuicPacketNumber(largest_acked), reader)) {
3691 return false;
3692 }
3693
3694 // Done processing the ACK frame.
3695 return visitor_->OnAckFrameEnd(QuicPacketNumber(first_received));
3696}
3697
3698bool QuicFramer::ProcessTimestampsInAckFrame(uint8_t num_received_packets,
3699 QuicPacketNumber largest_acked,
3700 QuicDataReader* reader) {
3701 if (num_received_packets == 0) {
3702 return true;
3703 }
3704 uint8_t delta_from_largest_observed;
3705 if (!reader->ReadUInt8(&delta_from_largest_observed)) {
3706 set_detailed_error("Unable to read sequence delta in received packets.");
3707 return false;
3708 }
3709
3710 if (largest_acked.ToUint64() <= delta_from_largest_observed) {
3711 set_detailed_error(QuicStrCat("delta_from_largest_observed too high: ",
3712 delta_from_largest_observed,
3713 ", largest_acked: ", largest_acked.ToUint64())
3714 .c_str());
3715 return false;
3716 }
3717
3718 // Time delta from the framer creation.
3719 uint32_t time_delta_us;
3720 if (!reader->ReadUInt32(&time_delta_us)) {
3721 set_detailed_error("Unable to read time delta in received packets.");
3722 return false;
3723 }
3724
3725 QuicPacketNumber seq_num = largest_acked - delta_from_largest_observed;
3726 if (process_timestamps_) {
3727 last_timestamp_ = CalculateTimestampFromWire(time_delta_us);
3728
3729 visitor_->OnAckTimestamp(seq_num, creation_time_ + last_timestamp_);
3730 }
3731
3732 for (uint8_t i = 1; i < num_received_packets; ++i) {
3733 if (!reader->ReadUInt8(&delta_from_largest_observed)) {
3734 set_detailed_error("Unable to read sequence delta in received packets.");
3735 return false;
3736 }
3737 if (largest_acked.ToUint64() <= delta_from_largest_observed) {
3738 set_detailed_error(
3739 QuicStrCat("delta_from_largest_observed too high: ",
3740 delta_from_largest_observed,
3741 ", largest_acked: ", largest_acked.ToUint64())
3742 .c_str());
3743 return false;
3744 }
3745 seq_num = largest_acked - delta_from_largest_observed;
3746
3747 // Time delta from the previous timestamp.
3748 uint64_t incremental_time_delta_us;
3749 if (!reader->ReadUFloat16(&incremental_time_delta_us)) {
3750 set_detailed_error(
3751 "Unable to read incremental time delta in received packets.");
3752 return false;
3753 }
3754
3755 if (process_timestamps_) {
3756 last_timestamp_ = last_timestamp_ + QuicTime::Delta::FromMicroseconds(
3757 incremental_time_delta_us);
3758 visitor_->OnAckTimestamp(seq_num, creation_time_ + last_timestamp_);
3759 }
3760 }
3761 return true;
3762}
3763
3764bool QuicFramer::ProcessIetfAckFrame(QuicDataReader* reader,
3765 uint64_t frame_type,
3766 QuicAckFrame* ack_frame) {
3767 uint64_t largest_acked;
3768 if (!reader->ReadVarInt62(&largest_acked)) {
3769 set_detailed_error("Unable to read largest acked.");
3770 return false;
3771 }
3772 if (largest_acked < first_sending_packet_number_.ToUint64()) {
3773 // Connection always sends packet starting from kFirstSendingPacketNumber >
3774 // 0, peer has observed an unsent packet.
3775 set_detailed_error("Largest acked is 0.");
3776 return false;
3777 }
3778 ack_frame->largest_acked = static_cast<QuicPacketNumber>(largest_acked);
3779 uint64_t ack_delay_time_in_us;
3780 if (!reader->ReadVarInt62(&ack_delay_time_in_us)) {
3781 set_detailed_error("Unable to read ack delay time.");
3782 return false;
3783 }
3784
QUICHE teama6ef0a62019-03-07 20:34:33 -05003785 if (ack_delay_time_in_us == kVarInt62MaxValue) {
3786 ack_frame->ack_delay_time = QuicTime::Delta::Infinite();
3787 } else {
fkastenholz4dc4ba32019-07-30 09:55:25 -07003788 ack_delay_time_in_us = (ack_delay_time_in_us << peer_ack_delay_exponent_);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003789 ack_frame->ack_delay_time =
3790 QuicTime::Delta::FromMicroseconds(ack_delay_time_in_us);
3791 }
3792 if (frame_type == IETF_ACK_ECN) {
3793 ack_frame->ecn_counters_populated = true;
3794 if (!reader->ReadVarInt62(&ack_frame->ect_0_count)) {
3795 set_detailed_error("Unable to read ack ect_0_count.");
3796 return false;
3797 }
3798 if (!reader->ReadVarInt62(&ack_frame->ect_1_count)) {
3799 set_detailed_error("Unable to read ack ect_1_count.");
3800 return false;
3801 }
3802 if (!reader->ReadVarInt62(&ack_frame->ecn_ce_count)) {
3803 set_detailed_error("Unable to read ack ecn_ce_count.");
3804 return false;
3805 }
3806 } else {
3807 ack_frame->ecn_counters_populated = false;
3808 ack_frame->ect_0_count = 0;
3809 ack_frame->ect_1_count = 0;
3810 ack_frame->ecn_ce_count = 0;
3811 }
3812 if (!visitor_->OnAckFrameStart(QuicPacketNumber(largest_acked),
3813 ack_frame->ack_delay_time)) {
3814 // The visitor suppresses further processing of the packet. Although this is
3815 // not a parsing error, returns false as this is in middle of processing an
3816 // ACK frame.
3817 set_detailed_error("Visitor suppresses further processing of ACK frame.");
3818 return false;
3819 }
3820
3821 // Get number of ACK blocks from the packet.
3822 uint64_t ack_block_count;
3823 if (!reader->ReadVarInt62(&ack_block_count)) {
3824 set_detailed_error("Unable to read ack block count.");
3825 return false;
3826 }
3827 // There always is a first ACK block, which is the (number of packets being
3828 // acked)-1, up to and including the packet at largest_acked. Therefore if the
3829 // value is 0, then only largest is acked. If it is 1, then largest-1,
3830 // largest] are acked, etc
3831 uint64_t ack_block_value;
3832 if (!reader->ReadVarInt62(&ack_block_value)) {
3833 set_detailed_error("Unable to read first ack block length.");
3834 return false;
3835 }
3836 // Calculate the packets being acked in the first block.
3837 // +1 because AddRange implementation requires [low,high)
3838 uint64_t block_high = largest_acked + 1;
3839 uint64_t block_low = largest_acked - ack_block_value;
3840
3841 // ack_block_value is the number of packets preceding the
3842 // largest_acked packet which are in the block being acked. Thus,
3843 // its maximum value is largest_acked-1. Test this, reporting an
3844 // error if the value is wrong.
3845 if (ack_block_value + first_sending_packet_number_.ToUint64() >
3846 largest_acked) {
3847 set_detailed_error(QuicStrCat("Underflow with first ack block length ",
3848 ack_block_value + 1, " largest acked is ",
3849 largest_acked, ".")
3850 .c_str());
3851 return false;
3852 }
3853
3854 if (!visitor_->OnAckRange(QuicPacketNumber(block_low),
3855 QuicPacketNumber(block_high))) {
3856 // The visitor suppresses further processing of the packet. Although
3857 // this is not a parsing error, returns false as this is in middle
3858 // of processing an ACK frame.
3859 set_detailed_error("Visitor suppresses further processing of ACK frame.");
3860 return false;
3861 }
3862
3863 while (ack_block_count != 0) {
3864 uint64_t gap_block_value;
3865 // Get the sizes of the gap and ack blocks,
3866 if (!reader->ReadVarInt62(&gap_block_value)) {
3867 set_detailed_error("Unable to read gap block value.");
3868 return false;
3869 }
3870 // It's an error if the gap is larger than the space from packet
3871 // number 0 to the start of the block that's just been acked, PLUS
3872 // there must be space for at least 1 packet to be acked. For
3873 // example, if block_low is 10 and gap_block_value is 9, it means
3874 // the gap block is 10 packets long, leaving no room for a packet
3875 // to be acked. Thus, gap_block_value+2 can not be larger than
3876 // block_low.
3877 // The test is written this way to detect wrap-arounds.
3878 if ((gap_block_value + 2) > block_low) {
3879 set_detailed_error(
3880 QuicStrCat("Underflow with gap block length ", gap_block_value + 1,
3881 " previous ack block start is ", block_low, ".")
3882 .c_str());
3883 return false;
3884 }
3885
3886 // Adjust block_high to be the top of the next ack block.
3887 // There is a gap of |gap_block_value| packets between the bottom
3888 // of ack block N and top of block N+1. Note that gap_block_value
3889 // is he size of the gap minus 1 (per the QUIC protocol), and
3890 // block_high is the packet number of the first packet of the gap
3891 // (per the implementation of OnAckRange/AddAckRange, below).
3892 block_high = block_low - 1 - gap_block_value;
3893
3894 if (!reader->ReadVarInt62(&ack_block_value)) {
3895 set_detailed_error("Unable to read ack block value.");
3896 return false;
3897 }
3898 if (ack_block_value + first_sending_packet_number_.ToUint64() >
3899 (block_high - 1)) {
3900 set_detailed_error(
3901 QuicStrCat("Underflow with ack block length ", ack_block_value + 1,
3902 " latest ack block end is ", block_high - 1, ".")
3903 .c_str());
3904 return false;
3905 }
3906 // Calculate the low end of the new nth ack block. The +1 is
3907 // because the encoded value is the blocksize-1.
3908 block_low = block_high - 1 - ack_block_value;
3909 if (!visitor_->OnAckRange(QuicPacketNumber(block_low),
3910 QuicPacketNumber(block_high))) {
3911 // The visitor suppresses further processing of the packet. Although
3912 // this is not a parsing error, returns false as this is in middle
3913 // of processing an ACK frame.
3914 set_detailed_error("Visitor suppresses further processing of ACK frame.");
3915 return false;
3916 }
3917
3918 // Another one done.
3919 ack_block_count--;
3920 }
3921
3922 return visitor_->OnAckFrameEnd(QuicPacketNumber(block_low));
3923}
3924
3925bool QuicFramer::ProcessStopWaitingFrame(QuicDataReader* reader,
3926 const QuicPacketHeader& header,
3927 QuicStopWaitingFrame* stop_waiting) {
3928 uint64_t least_unacked_delta;
3929 if (!reader->ReadBytesToUInt64(header.packet_number_length,
3930 &least_unacked_delta)) {
3931 set_detailed_error("Unable to read least unacked delta.");
3932 return false;
3933 }
3934 if (header.packet_number.ToUint64() <= least_unacked_delta) {
3935 set_detailed_error("Invalid unacked delta.");
3936 return false;
3937 }
3938 stop_waiting->least_unacked = header.packet_number - least_unacked_delta;
3939
3940 return true;
3941}
3942
3943bool QuicFramer::ProcessRstStreamFrame(QuicDataReader* reader,
3944 QuicRstStreamFrame* frame) {
3945 if (!reader->ReadUInt32(&frame->stream_id)) {
3946 set_detailed_error("Unable to read stream_id.");
3947 return false;
3948 }
3949
3950 if (!reader->ReadUInt64(&frame->byte_offset)) {
3951 set_detailed_error("Unable to read rst stream sent byte offset.");
3952 return false;
3953 }
3954
3955 uint32_t error_code;
3956 if (!reader->ReadUInt32(&error_code)) {
3957 set_detailed_error("Unable to read rst stream error code.");
3958 return false;
3959 }
3960
3961 if (error_code >= QUIC_STREAM_LAST_ERROR) {
3962 // Ignore invalid stream error code if any.
3963 error_code = QUIC_STREAM_LAST_ERROR;
3964 }
3965
3966 frame->error_code = static_cast<QuicRstStreamErrorCode>(error_code);
3967
3968 return true;
3969}
3970
3971bool QuicFramer::ProcessConnectionCloseFrame(QuicDataReader* reader,
3972 QuicConnectionCloseFrame* frame) {
3973 uint32_t error_code;
fkastenholze9d71a82019-04-09 05:12:13 -07003974 frame->close_type = GOOGLE_QUIC_CONNECTION_CLOSE;
3975
QUICHE teama6ef0a62019-03-07 20:34:33 -05003976 if (!reader->ReadUInt32(&error_code)) {
3977 set_detailed_error("Unable to read connection close error code.");
3978 return false;
3979 }
3980
3981 if (error_code >= QUIC_LAST_ERROR) {
3982 // Ignore invalid QUIC error code if any.
3983 error_code = QUIC_LAST_ERROR;
3984 }
3985
fkastenholze9d71a82019-04-09 05:12:13 -07003986 frame->quic_error_code = static_cast<QuicErrorCode>(error_code);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003987
fkastenholza14a7ae2019-08-07 05:21:22 -07003988 // For Google QUIC connection closes, copy the Google QUIC error code to
3989 // the extracted error code field so that the Google QUIC error code is always
3990 // available in extracted_error_code.
3991 frame->extracted_error_code = frame->quic_error_code;
3992
QUICHE teama6ef0a62019-03-07 20:34:33 -05003993 QuicStringPiece error_details;
3994 if (!reader->ReadStringPiece16(&error_details)) {
3995 set_detailed_error("Unable to read connection close error details.");
3996 return false;
3997 }
vasilvvc48c8712019-03-11 13:38:16 -07003998 frame->error_details = std::string(error_details);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003999
4000 return true;
4001}
4002
4003bool QuicFramer::ProcessGoAwayFrame(QuicDataReader* reader,
4004 QuicGoAwayFrame* frame) {
4005 uint32_t error_code;
4006 if (!reader->ReadUInt32(&error_code)) {
4007 set_detailed_error("Unable to read go away error code.");
4008 return false;
4009 }
4010
4011 if (error_code >= QUIC_LAST_ERROR) {
4012 // Ignore invalid QUIC error code if any.
4013 error_code = QUIC_LAST_ERROR;
4014 }
4015 frame->error_code = static_cast<QuicErrorCode>(error_code);
4016
4017 uint32_t stream_id;
4018 if (!reader->ReadUInt32(&stream_id)) {
4019 set_detailed_error("Unable to read last good stream id.");
4020 return false;
4021 }
4022 frame->last_good_stream_id = static_cast<QuicStreamId>(stream_id);
4023
4024 QuicStringPiece reason_phrase;
4025 if (!reader->ReadStringPiece16(&reason_phrase)) {
4026 set_detailed_error("Unable to read goaway reason.");
4027 return false;
4028 }
vasilvvc48c8712019-03-11 13:38:16 -07004029 frame->reason_phrase = std::string(reason_phrase);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004030
4031 return true;
4032}
4033
4034bool QuicFramer::ProcessWindowUpdateFrame(QuicDataReader* reader,
4035 QuicWindowUpdateFrame* frame) {
4036 if (!reader->ReadUInt32(&frame->stream_id)) {
4037 set_detailed_error("Unable to read stream_id.");
4038 return false;
4039 }
4040
4041 if (!reader->ReadUInt64(&frame->byte_offset)) {
4042 set_detailed_error("Unable to read window byte_offset.");
4043 return false;
4044 }
4045
4046 return true;
4047}
4048
4049bool QuicFramer::ProcessBlockedFrame(QuicDataReader* reader,
4050 QuicBlockedFrame* frame) {
fkastenholz305e1732019-06-18 05:01:22 -07004051 DCHECK(!VersionHasIetfQuicFrames(version_.transport_version))
4052 << "Attempt to process non-IETF QUIC frames in an IETF QUIC version.";
QUICHE teama6ef0a62019-03-07 20:34:33 -05004053
4054 if (!reader->ReadUInt32(&frame->stream_id)) {
4055 set_detailed_error("Unable to read stream_id.");
4056 return false;
4057 }
4058
4059 return true;
4060}
4061
4062void QuicFramer::ProcessPaddingFrame(QuicDataReader* reader,
4063 QuicPaddingFrame* frame) {
4064 // Type byte has been read.
4065 frame->num_padding_bytes = 1;
4066 uint8_t next_byte;
4067 while (!reader->IsDoneReading() && reader->PeekByte() == 0x00) {
4068 reader->ReadBytes(&next_byte, 1);
4069 DCHECK_EQ(0x00, next_byte);
4070 ++frame->num_padding_bytes;
4071 }
4072}
4073
4074bool QuicFramer::ProcessMessageFrame(QuicDataReader* reader,
4075 bool no_message_length,
4076 QuicMessageFrame* frame) {
4077 if (no_message_length) {
4078 QuicStringPiece remaining(reader->ReadRemainingPayload());
4079 frame->data = remaining.data();
4080 frame->message_length = remaining.length();
4081 return true;
4082 }
4083
4084 uint64_t message_length;
4085 if (!reader->ReadVarInt62(&message_length)) {
4086 set_detailed_error("Unable to read message length");
4087 return false;
4088 }
4089
4090 QuicStringPiece message_piece;
4091 if (!reader->ReadStringPiece(&message_piece, message_length)) {
4092 set_detailed_error("Unable to read message data");
4093 return false;
4094 }
4095
4096 frame->data = message_piece.data();
4097 frame->message_length = message_length;
4098
4099 return true;
4100}
4101
4102// static
4103QuicStringPiece QuicFramer::GetAssociatedDataFromEncryptedPacket(
4104 QuicTransportVersion version,
4105 const QuicEncryptedPacket& encrypted,
4106 QuicConnectionIdLength destination_connection_id_length,
4107 QuicConnectionIdLength source_connection_id_length,
4108 bool includes_version,
4109 bool includes_diversification_nonce,
4110 QuicPacketNumberLength packet_number_length,
4111 QuicVariableLengthIntegerLength retry_token_length_length,
4112 uint64_t retry_token_length,
4113 QuicVariableLengthIntegerLength length_length) {
4114 // TODO(ianswett): This is identical to QuicData::AssociatedData.
4115 return QuicStringPiece(
4116 encrypted.data(),
4117 GetStartOfEncryptedData(version, destination_connection_id_length,
4118 source_connection_id_length, includes_version,
4119 includes_diversification_nonce,
4120 packet_number_length, retry_token_length_length,
4121 retry_token_length, length_length));
4122}
4123
4124void QuicFramer::SetDecrypter(EncryptionLevel level,
4125 std::unique_ptr<QuicDecrypter> decrypter) {
QUICHE team76086e42019-03-25 15:12:29 -07004126 DCHECK_EQ(alternative_decrypter_level_, NUM_ENCRYPTION_LEVELS);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004127 DCHECK_GE(level, decrypter_level_);
zhongyi546cc452019-04-12 15:27:49 -07004128 DCHECK(!version_.KnowsWhichDecrypterToUse());
dschinazi4b5a68a2019-08-15 15:45:36 -07004129 QUIC_DVLOG(1) << ENDPOINT << "Setting decrypter from level "
dschinazief79a5f2019-10-04 10:32:54 -07004130 << EncryptionLevelToString(decrypter_level_) << " to "
4131 << EncryptionLevelToString(level);
QUICHE team76086e42019-03-25 15:12:29 -07004132 decrypter_[decrypter_level_] = nullptr;
4133 decrypter_[level] = std::move(decrypter);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004134 decrypter_level_ = level;
4135}
4136
4137void QuicFramer::SetAlternativeDecrypter(
4138 EncryptionLevel level,
4139 std::unique_ptr<QuicDecrypter> decrypter,
4140 bool latch_once_used) {
QUICHE team76086e42019-03-25 15:12:29 -07004141 DCHECK_NE(level, decrypter_level_);
zhongyi546cc452019-04-12 15:27:49 -07004142 DCHECK(!version_.KnowsWhichDecrypterToUse());
dschinazi4b5a68a2019-08-15 15:45:36 -07004143 QUIC_DVLOG(1) << ENDPOINT << "Setting alternative decrypter from level "
dschinazief79a5f2019-10-04 10:32:54 -07004144 << EncryptionLevelToString(alternative_decrypter_level_)
4145 << " to " << EncryptionLevelToString(level);
QUICHE team76086e42019-03-25 15:12:29 -07004146 if (alternative_decrypter_level_ != NUM_ENCRYPTION_LEVELS) {
4147 decrypter_[alternative_decrypter_level_] = nullptr;
4148 }
4149 decrypter_[level] = std::move(decrypter);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004150 alternative_decrypter_level_ = level;
4151 alternative_decrypter_latch_ = latch_once_used;
4152}
4153
zhongyi546cc452019-04-12 15:27:49 -07004154void QuicFramer::InstallDecrypter(EncryptionLevel level,
4155 std::unique_ptr<QuicDecrypter> decrypter) {
4156 DCHECK(version_.KnowsWhichDecrypterToUse());
dschinazi4b5a68a2019-08-15 15:45:36 -07004157 QUIC_DVLOG(1) << ENDPOINT << "Installing decrypter at level "
dschinazief79a5f2019-10-04 10:32:54 -07004158 << EncryptionLevelToString(level);
zhongyi546cc452019-04-12 15:27:49 -07004159 decrypter_[level] = std::move(decrypter);
4160}
4161
4162void QuicFramer::RemoveDecrypter(EncryptionLevel level) {
4163 DCHECK(version_.KnowsWhichDecrypterToUse());
dschinazi4b5a68a2019-08-15 15:45:36 -07004164 QUIC_DVLOG(1) << ENDPOINT << "Removing decrypter at level "
dschinazief79a5f2019-10-04 10:32:54 -07004165 << EncryptionLevelToString(level);
zhongyi546cc452019-04-12 15:27:49 -07004166 decrypter_[level] = nullptr;
4167}
4168
4169const QuicDecrypter* QuicFramer::GetDecrypter(EncryptionLevel level) const {
4170 DCHECK(version_.KnowsWhichDecrypterToUse());
4171 return decrypter_[level].get();
4172}
4173
QUICHE teama6ef0a62019-03-07 20:34:33 -05004174const QuicDecrypter* QuicFramer::decrypter() const {
QUICHE team76086e42019-03-25 15:12:29 -07004175 return decrypter_[decrypter_level_].get();
QUICHE teama6ef0a62019-03-07 20:34:33 -05004176}
4177
4178const QuicDecrypter* QuicFramer::alternative_decrypter() const {
QUICHE team76086e42019-03-25 15:12:29 -07004179 if (alternative_decrypter_level_ == NUM_ENCRYPTION_LEVELS) {
4180 return nullptr;
4181 }
4182 return decrypter_[alternative_decrypter_level_].get();
QUICHE teama6ef0a62019-03-07 20:34:33 -05004183}
4184
4185void QuicFramer::SetEncrypter(EncryptionLevel level,
4186 std::unique_ptr<QuicEncrypter> encrypter) {
4187 DCHECK_GE(level, 0);
4188 DCHECK_LT(level, NUM_ENCRYPTION_LEVELS);
dschinazi4b5a68a2019-08-15 15:45:36 -07004189 QUIC_DVLOG(1) << ENDPOINT << "Setting encrypter at level "
dschinazief79a5f2019-10-04 10:32:54 -07004190 << EncryptionLevelToString(level);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004191 encrypter_[level] = std::move(encrypter);
4192}
4193
nharper4a5a76c2019-09-13 13:44:37 -07004194void QuicFramer::SetInitialObfuscators(QuicConnectionId connection_id) {
4195 CrypterPair crypters;
4196 CryptoUtils::CreateInitialObfuscators(perspective_, version_, connection_id,
4197 &crypters);
4198 encrypter_[ENCRYPTION_INITIAL] = std::move(crypters.encrypter);
4199 decrypter_[ENCRYPTION_INITIAL] = std::move(crypters.decrypter);
4200}
4201
QUICHE teama6ef0a62019-03-07 20:34:33 -05004202size_t QuicFramer::EncryptInPlace(EncryptionLevel level,
4203 QuicPacketNumber packet_number,
4204 size_t ad_len,
4205 size_t total_len,
4206 size_t buffer_len,
4207 char* buffer) {
4208 DCHECK(packet_number.IsInitialized());
dschinazi2c5386e2019-04-16 16:37:37 -07004209 if (encrypter_[level] == nullptr) {
4210 QUIC_BUG << ENDPOINT
4211 << "Attempted to encrypt in place without encrypter at level "
dschinazief79a5f2019-10-04 10:32:54 -07004212 << EncryptionLevelToString(level);
dschinazi2c5386e2019-04-16 16:37:37 -07004213 RaiseError(QUIC_ENCRYPTION_FAILURE);
4214 return 0;
4215 }
4216
QUICHE teama6ef0a62019-03-07 20:34:33 -05004217 size_t output_length = 0;
4218 if (!encrypter_[level]->EncryptPacket(
4219 packet_number.ToUint64(),
4220 QuicStringPiece(buffer, ad_len), // Associated data
4221 QuicStringPiece(buffer + ad_len, total_len - ad_len), // Plaintext
4222 buffer + ad_len, // Destination buffer
4223 &output_length, buffer_len - ad_len)) {
4224 RaiseError(QUIC_ENCRYPTION_FAILURE);
4225 return 0;
4226 }
nharper55fa6132019-05-07 19:37:21 -07004227 if (version_.HasHeaderProtection() &&
4228 !ApplyHeaderProtection(level, buffer, ad_len + output_length, ad_len)) {
4229 QUIC_DLOG(ERROR) << "Applying header protection failed.";
4230 RaiseError(QUIC_ENCRYPTION_FAILURE);
4231 return 0;
4232 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004233
4234 return ad_len + output_length;
4235}
4236
nharper55fa6132019-05-07 19:37:21 -07004237namespace {
4238
4239const size_t kHPSampleLen = 16;
4240
4241constexpr bool IsLongHeader(uint8_t type_byte) {
4242 return (type_byte & FLAGS_LONG_HEADER) != 0;
4243}
4244
4245} // namespace
4246
4247bool QuicFramer::ApplyHeaderProtection(EncryptionLevel level,
4248 char* buffer,
4249 size_t buffer_len,
4250 size_t ad_len) {
4251 QuicDataReader buffer_reader(buffer, buffer_len);
4252 QuicDataWriter buffer_writer(buffer_len, buffer);
4253 // The sample starts 4 bytes after the start of the packet number.
4254 if (ad_len < last_written_packet_number_length_) {
4255 return false;
4256 }
4257 size_t pn_offset = ad_len - last_written_packet_number_length_;
4258 // Sample the ciphertext and generate the mask to use for header protection.
4259 size_t sample_offset = pn_offset + 4;
4260 QuicDataReader sample_reader(buffer, buffer_len);
4261 QuicStringPiece sample;
4262 if (!sample_reader.Seek(sample_offset) ||
4263 !sample_reader.ReadStringPiece(&sample, kHPSampleLen)) {
4264 QUIC_BUG << "Not enough bytes to sample: sample_offset " << sample_offset
4265 << ", sample len: " << kHPSampleLen
4266 << ", buffer len: " << buffer_len;
4267 return false;
4268 }
4269
4270 std::string mask = encrypter_[level]->GenerateHeaderProtectionMask(sample);
4271 if (mask.empty()) {
4272 QUIC_BUG << "Unable to generate header protection mask.";
4273 return false;
4274 }
4275 QuicDataReader mask_reader(mask.data(), mask.size());
4276
4277 // Apply the mask to the 4 or 5 least significant bits of the first byte.
4278 uint8_t bitmask = 0x1f;
4279 uint8_t type_byte;
4280 if (!buffer_reader.ReadUInt8(&type_byte)) {
4281 return false;
4282 }
4283 QuicLongHeaderType header_type;
4284 if (IsLongHeader(type_byte)) {
4285 bitmask = 0x0f;
fayang36825da2019-08-21 14:01:27 -07004286 if (!GetLongHeaderType(type_byte, &header_type)) {
nharper55fa6132019-05-07 19:37:21 -07004287 return false;
4288 }
4289 }
4290 uint8_t mask_byte;
4291 if (!mask_reader.ReadUInt8(&mask_byte) ||
4292 !buffer_writer.WriteUInt8(type_byte ^ (mask_byte & bitmask))) {
4293 return false;
4294 }
4295
4296 // Adjust |pn_offset| to account for the diversification nonce.
4297 if (IsLongHeader(type_byte) && header_type == ZERO_RTT_PROTECTED &&
4298 perspective_ == Perspective::IS_SERVER &&
4299 version_.handshake_protocol == PROTOCOL_QUIC_CRYPTO) {
4300 if (pn_offset <= kDiversificationNonceSize) {
4301 QUIC_BUG << "Expected diversification nonce, but not enough bytes";
4302 return false;
4303 }
4304 pn_offset -= kDiversificationNonceSize;
4305 }
4306 // Advance the reader and writer to the packet number. Both the reader and
4307 // writer have each read/written one byte.
4308 if (!buffer_writer.Seek(pn_offset - 1) ||
4309 !buffer_reader.Seek(pn_offset - 1)) {
4310 return false;
4311 }
4312 // Apply the rest of the mask to the packet number.
4313 for (size_t i = 0; i < last_written_packet_number_length_; ++i) {
4314 uint8_t buffer_byte;
4315 uint8_t mask_byte;
4316 if (!mask_reader.ReadUInt8(&mask_byte) ||
4317 !buffer_reader.ReadUInt8(&buffer_byte) ||
4318 !buffer_writer.WriteUInt8(buffer_byte ^ mask_byte)) {
4319 return false;
4320 }
4321 }
4322 return true;
4323}
4324
4325bool QuicFramer::RemoveHeaderProtection(QuicDataReader* reader,
4326 const QuicEncryptedPacket& packet,
4327 QuicPacketHeader* header,
4328 uint64_t* full_packet_number,
4329 std::vector<char>* associated_data) {
4330 EncryptionLevel expected_decryption_level = GetEncryptionLevel(*header);
4331 QuicDecrypter* decrypter = decrypter_[expected_decryption_level].get();
4332 if (decrypter == nullptr) {
4333 QUIC_DVLOG(1)
dschinazi4b5a68a2019-08-15 15:45:36 -07004334 << ENDPOINT
nharper55fa6132019-05-07 19:37:21 -07004335 << "No decrypter available for removing header protection at level "
dschinazief79a5f2019-10-04 10:32:54 -07004336 << EncryptionLevelToString(expected_decryption_level);
nharper55fa6132019-05-07 19:37:21 -07004337 return false;
4338 }
4339
4340 bool has_diversification_nonce =
4341 header->form == IETF_QUIC_LONG_HEADER_PACKET &&
4342 header->long_packet_type == ZERO_RTT_PROTECTED &&
4343 perspective_ == Perspective::IS_CLIENT &&
4344 version_.handshake_protocol == PROTOCOL_QUIC_CRYPTO;
4345
4346 // Read a sample from the ciphertext and compute the mask to use for header
4347 // protection.
4348 QuicStringPiece remaining_packet = reader->PeekRemainingPayload();
4349 QuicDataReader sample_reader(remaining_packet);
4350
4351 // The sample starts 4 bytes after the start of the packet number.
4352 QuicStringPiece pn;
4353 if (!sample_reader.ReadStringPiece(&pn, 4)) {
4354 QUIC_DVLOG(1) << "Not enough data to sample";
4355 return false;
4356 }
4357 if (has_diversification_nonce) {
4358 // In Google QUIC, the diversification nonce comes between the packet number
4359 // and the sample.
4360 if (!sample_reader.Seek(kDiversificationNonceSize)) {
4361 QUIC_DVLOG(1) << "No diversification nonce to skip over";
4362 return false;
4363 }
4364 }
4365 std::string mask = decrypter->GenerateHeaderProtectionMask(&sample_reader);
4366 QuicDataReader mask_reader(mask.data(), mask.size());
4367 if (mask.empty()) {
4368 QUIC_DVLOG(1) << "Failed to compute mask";
4369 return false;
4370 }
4371
4372 // Unmask the rest of the type byte.
4373 uint8_t bitmask = 0x1f;
4374 if (IsLongHeader(header->type_byte)) {
4375 bitmask = 0x0f;
4376 }
4377 uint8_t mask_byte;
4378 if (!mask_reader.ReadUInt8(&mask_byte)) {
4379 QUIC_DVLOG(1) << "No first byte to read from mask";
4380 return false;
4381 }
4382 header->type_byte ^= (mask_byte & bitmask);
4383
4384 // Compute the packet number length.
4385 header->packet_number_length =
4386 static_cast<QuicPacketNumberLength>((header->type_byte & 0x03) + 1);
4387
4388 char pn_buffer[IETF_MAX_PACKET_NUMBER_LENGTH] = {};
4389 QuicDataWriter pn_writer(QUIC_ARRAYSIZE(pn_buffer), pn_buffer);
4390
4391 // Read the (protected) packet number from the reader and unmask the packet
4392 // number.
4393 for (size_t i = 0; i < header->packet_number_length; ++i) {
4394 uint8_t protected_pn_byte, mask_byte;
4395 if (!mask_reader.ReadUInt8(&mask_byte) ||
4396 !reader->ReadUInt8(&protected_pn_byte) ||
4397 !pn_writer.WriteUInt8(protected_pn_byte ^ mask_byte)) {
4398 QUIC_DVLOG(1) << "Failed to unmask packet number";
4399 return false;
4400 }
4401 }
4402 QuicDataReader packet_number_reader(pn_writer.data(), pn_writer.length());
4403 QuicPacketNumber base_packet_number;
4404 if (supports_multiple_packet_number_spaces_) {
4405 PacketNumberSpace pn_space = GetPacketNumberSpace(*header);
4406 if (pn_space == NUM_PACKET_NUMBER_SPACES) {
4407 return false;
4408 }
4409 base_packet_number = largest_decrypted_packet_numbers_[pn_space];
4410 } else {
4411 base_packet_number = largest_packet_number_;
4412 }
4413 if (!ProcessAndCalculatePacketNumber(
4414 &packet_number_reader, header->packet_number_length,
4415 base_packet_number, full_packet_number)) {
4416 return false;
4417 }
4418
4419 // Get the associated data, and apply the same unmasking operations to it.
4420 QuicStringPiece ad = GetAssociatedDataFromEncryptedPacket(
4421 version_.transport_version, packet,
4422 GetIncludedDestinationConnectionIdLength(*header),
4423 GetIncludedSourceConnectionIdLength(*header), header->version_flag,
4424 has_diversification_nonce, header->packet_number_length,
4425 header->retry_token_length_length, header->retry_token.length(),
4426 header->length_length);
4427 *associated_data = std::vector<char>(ad.begin(), ad.end());
4428 QuicDataWriter ad_writer(associated_data->size(), associated_data->data());
4429
4430 // Apply the unmasked type byte and packet number to |associated_data|.
4431 if (!ad_writer.WriteUInt8(header->type_byte)) {
4432 return false;
4433 }
4434 // Put the packet number at the end of the AD, or if there's a diversification
4435 // nonce, before that (which is at the end of the AD).
4436 size_t seek_len = ad_writer.remaining() - header->packet_number_length;
4437 if (has_diversification_nonce) {
4438 seek_len -= kDiversificationNonceSize;
4439 }
4440 if (!ad_writer.Seek(seek_len) ||
4441 !ad_writer.WriteBytes(pn_writer.data(), pn_writer.length())) {
4442 QUIC_DVLOG(1) << "Failed to apply unmasking operations to AD";
4443 return false;
4444 }
4445
4446 return true;
4447}
4448
QUICHE teama6ef0a62019-03-07 20:34:33 -05004449size_t QuicFramer::EncryptPayload(EncryptionLevel level,
4450 QuicPacketNumber packet_number,
4451 const QuicPacket& packet,
4452 char* buffer,
4453 size_t buffer_len) {
4454 DCHECK(packet_number.IsInitialized());
dschinazi2c5386e2019-04-16 16:37:37 -07004455 if (encrypter_[level] == nullptr) {
4456 QUIC_BUG << ENDPOINT << "Attempted to encrypt without encrypter at level "
dschinazief79a5f2019-10-04 10:32:54 -07004457 << EncryptionLevelToString(level);
dschinazi2c5386e2019-04-16 16:37:37 -07004458 RaiseError(QUIC_ENCRYPTION_FAILURE);
4459 return 0;
4460 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004461
4462 QuicStringPiece associated_data =
4463 packet.AssociatedData(version_.transport_version);
4464 // Copy in the header, because the encrypter only populates the encrypted
4465 // plaintext content.
4466 const size_t ad_len = associated_data.length();
4467 memmove(buffer, associated_data.data(), ad_len);
4468 // Encrypt the plaintext into the buffer.
4469 size_t output_length = 0;
4470 if (!encrypter_[level]->EncryptPacket(
4471 packet_number.ToUint64(), associated_data,
4472 packet.Plaintext(version_.transport_version), buffer + ad_len,
4473 &output_length, buffer_len - ad_len)) {
4474 RaiseError(QUIC_ENCRYPTION_FAILURE);
4475 return 0;
4476 }
nharper55fa6132019-05-07 19:37:21 -07004477 if (version_.HasHeaderProtection() &&
4478 !ApplyHeaderProtection(level, buffer, ad_len + output_length, ad_len)) {
4479 QUIC_DLOG(ERROR) << "Applying header protection failed.";
4480 RaiseError(QUIC_ENCRYPTION_FAILURE);
4481 return 0;
4482 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004483
4484 return ad_len + output_length;
4485}
4486
4487size_t QuicFramer::GetCiphertextSize(EncryptionLevel level,
4488 size_t plaintext_size) const {
4489 return encrypter_[level]->GetCiphertextSize(plaintext_size);
4490}
4491
4492size_t QuicFramer::GetMaxPlaintextSize(size_t ciphertext_size) {
4493 // In order to keep the code simple, we don't have the current encryption
4494 // level to hand. Both the NullEncrypter and AES-GCM have a tag length of 12.
4495 size_t min_plaintext_size = ciphertext_size;
4496
QUICHE team6987b4a2019-03-15 16:23:04 -07004497 for (int i = ENCRYPTION_INITIAL; i < NUM_ENCRYPTION_LEVELS; i++) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05004498 if (encrypter_[i] != nullptr) {
4499 size_t size = encrypter_[i]->GetMaxPlaintextSize(ciphertext_size);
4500 if (size < min_plaintext_size) {
4501 min_plaintext_size = size;
4502 }
4503 }
4504 }
4505
4506 return min_plaintext_size;
4507}
4508
4509bool QuicFramer::DecryptPayload(QuicStringPiece encrypted,
4510 QuicStringPiece associated_data,
4511 const QuicPacketHeader& header,
4512 char* decrypted_buffer,
4513 size_t buffer_length,
QUICHE team10b22a12019-03-21 15:31:42 -07004514 size_t* decrypted_length,
4515 EncryptionLevel* decrypted_level) {
nharper855d2172019-05-02 16:17:46 -07004516 if (!EncryptionLevelIsValid(decrypter_level_)) {
4517 QUIC_BUG << "Attempted to decrypt with bad decrypter_level_";
4518 return false;
4519 }
zhongyi546cc452019-04-12 15:27:49 -07004520 EncryptionLevel level = decrypter_level_;
4521 QuicDecrypter* decrypter = decrypter_[level].get();
QUICHE team76086e42019-03-25 15:12:29 -07004522 QuicDecrypter* alternative_decrypter = nullptr;
zhongyi546cc452019-04-12 15:27:49 -07004523 if (version().KnowsWhichDecrypterToUse()) {
nharper855d2172019-05-02 16:17:46 -07004524 if (header.form == GOOGLE_QUIC_PACKET) {
4525 QUIC_BUG << "Attempted to decrypt GOOGLE_QUIC_PACKET with a version that "
4526 "knows which decrypter to use";
4527 return false;
4528 }
zhongyi546cc452019-04-12 15:27:49 -07004529 level = GetEncryptionLevel(header);
nharper855d2172019-05-02 16:17:46 -07004530 if (!EncryptionLevelIsValid(level)) {
4531 QUIC_BUG << "Attempted to decrypt with bad level";
4532 return false;
4533 }
zhongyi546cc452019-04-12 15:27:49 -07004534 decrypter = decrypter_[level].get();
4535 if (decrypter == nullptr) {
4536 return false;
4537 }
4538 if (level == ENCRYPTION_ZERO_RTT &&
4539 perspective_ == Perspective::IS_CLIENT && header.nonce != nullptr) {
4540 decrypter->SetDiversificationNonce(*header.nonce);
4541 }
4542 } else if (alternative_decrypter_level_ != NUM_ENCRYPTION_LEVELS) {
nharper855d2172019-05-02 16:17:46 -07004543 if (!EncryptionLevelIsValid(alternative_decrypter_level_)) {
4544 QUIC_BUG << "Attempted to decrypt with bad alternative_decrypter_level_";
4545 return false;
4546 }
QUICHE team76086e42019-03-25 15:12:29 -07004547 alternative_decrypter = decrypter_[alternative_decrypter_level_].get();
4548 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004549
nharper855d2172019-05-02 16:17:46 -07004550 if (decrypter == nullptr) {
ianswettf919fb22019-05-13 06:42:11 -07004551 QUIC_BUG << "Attempting to decrypt without decrypter, encryption level:"
4552 << level << " version:" << version();
nharper855d2172019-05-02 16:17:46 -07004553 return false;
4554 }
zhongyi546cc452019-04-12 15:27:49 -07004555
4556 bool success = decrypter->DecryptPacket(
QUICHE teama6ef0a62019-03-07 20:34:33 -05004557 header.packet_number.ToUint64(), associated_data, encrypted,
4558 decrypted_buffer, decrypted_length, buffer_length);
4559 if (success) {
zhongyi546cc452019-04-12 15:27:49 -07004560 visitor_->OnDecryptedPacket(level);
4561 *decrypted_level = level;
QUICHE team76086e42019-03-25 15:12:29 -07004562 } else if (alternative_decrypter != nullptr) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05004563 if (header.nonce != nullptr) {
4564 DCHECK_EQ(perspective_, Perspective::IS_CLIENT);
QUICHE team76086e42019-03-25 15:12:29 -07004565 alternative_decrypter->SetDiversificationNonce(*header.nonce);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004566 }
4567 bool try_alternative_decryption = true;
4568 if (alternative_decrypter_level_ == ENCRYPTION_ZERO_RTT) {
4569 if (perspective_ == Perspective::IS_CLIENT) {
4570 if (header.nonce == nullptr) {
4571 // Can not use INITIAL decryption without a diversification nonce.
4572 try_alternative_decryption = false;
4573 }
4574 } else {
4575 DCHECK(header.nonce == nullptr);
4576 }
4577 }
4578
4579 if (try_alternative_decryption) {
QUICHE team76086e42019-03-25 15:12:29 -07004580 success = alternative_decrypter->DecryptPacket(
QUICHE teama6ef0a62019-03-07 20:34:33 -05004581 header.packet_number.ToUint64(), associated_data, encrypted,
4582 decrypted_buffer, decrypted_length, buffer_length);
4583 }
4584 if (success) {
4585 visitor_->OnDecryptedPacket(alternative_decrypter_level_);
QUICHE team10b22a12019-03-21 15:31:42 -07004586 *decrypted_level = decrypter_level_;
QUICHE teama6ef0a62019-03-07 20:34:33 -05004587 if (alternative_decrypter_latch_) {
nharper855d2172019-05-02 16:17:46 -07004588 if (!EncryptionLevelIsValid(alternative_decrypter_level_)) {
4589 QUIC_BUG << "Attempted to latch alternate decrypter with bad "
4590 "alternative_decrypter_level_";
4591 return false;
4592 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004593 // Switch to the alternative decrypter and latch so that we cannot
4594 // switch back.
QUICHE teama6ef0a62019-03-07 20:34:33 -05004595 decrypter_level_ = alternative_decrypter_level_;
QUICHE team76086e42019-03-25 15:12:29 -07004596 alternative_decrypter_level_ = NUM_ENCRYPTION_LEVELS;
QUICHE teama6ef0a62019-03-07 20:34:33 -05004597 } else {
4598 // Switch the alternative decrypter so that we use it first next time.
QUICHE teama6ef0a62019-03-07 20:34:33 -05004599 EncryptionLevel level = alternative_decrypter_level_;
4600 alternative_decrypter_level_ = decrypter_level_;
4601 decrypter_level_ = level;
4602 }
4603 }
4604 }
4605
4606 if (!success) {
dschinazi965ce092019-05-23 06:29:01 -07004607 QUIC_DVLOG(1) << ENDPOINT << "DecryptPacket failed for: " << header;
QUICHE teama6ef0a62019-03-07 20:34:33 -05004608 return false;
4609 }
4610
4611 return true;
4612}
4613
4614size_t QuicFramer::GetIetfAckFrameSize(const QuicAckFrame& frame) {
4615 // Type byte, largest_acked, and delay_time are straight-forward.
4616 size_t ack_frame_size = kQuicFrameTypeSize;
4617 QuicPacketNumber largest_acked = LargestAcked(frame);
4618 ack_frame_size += QuicDataWriter::GetVarInt62Len(largest_acked.ToUint64());
4619 uint64_t ack_delay_time_us;
4620 ack_delay_time_us = frame.ack_delay_time.ToMicroseconds();
fkastenholz4dc4ba32019-07-30 09:55:25 -07004621 ack_delay_time_us = ack_delay_time_us >> local_ack_delay_exponent_;
QUICHE teama6ef0a62019-03-07 20:34:33 -05004622 ack_frame_size += QuicDataWriter::GetVarInt62Len(ack_delay_time_us);
4623
4624 // If |ecn_counters_populated| is true and any of the ecn counters is non-0
4625 // then the ecn counters are included...
4626 if (frame.ecn_counters_populated &&
4627 (frame.ect_0_count || frame.ect_1_count || frame.ecn_ce_count)) {
4628 ack_frame_size += QuicDataWriter::GetVarInt62Len(frame.ect_0_count);
4629 ack_frame_size += QuicDataWriter::GetVarInt62Len(frame.ect_1_count);
4630 ack_frame_size += QuicDataWriter::GetVarInt62Len(frame.ecn_ce_count);
4631 }
4632
4633 // The rest (ack_block_count, first_ack_block, and additional ack
4634 // blocks, if any) depends:
4635 uint64_t ack_block_count = frame.packets.NumIntervals();
4636 if (ack_block_count == 0) {
4637 // If the QuicAckFrame has no Intervals, then it is interpreted
4638 // as an ack of a single packet at QuicAckFrame.largest_acked.
4639 // The resulting ack will consist of only the frame's
4640 // largest_ack & first_ack_block fields. The first ack block will be 0
4641 // (indicating a single packet) and the ack block_count will be 0.
4642 // Each 0 takes 1 byte when VarInt62 encoded.
4643 ack_frame_size += 2;
4644 return ack_frame_size;
4645 }
4646
4647 auto itr = frame.packets.rbegin();
4648 QuicPacketNumber ack_block_largest = largest_acked;
4649 QuicPacketNumber ack_block_smallest;
4650 if ((itr->max() - 1) == largest_acked) {
4651 // If largest_acked + 1 is equal to the Max() of the first Interval
4652 // in the QuicAckFrame then the first Interval is the first ack block of the
4653 // frame; remaining Intervals are additional ack blocks. The QuicAckFrame's
4654 // first Interval is encoded in the frame's largest_acked/first_ack_block,
4655 // the remaining Intervals are encoded in additional ack blocks in the
4656 // frame, and the packet's ack_block_count is the number of QuicAckFrame
4657 // Intervals - 1.
4658 ack_block_smallest = itr->min();
4659 itr++;
4660 ack_block_count--;
4661 } else {
4662 // If QuicAckFrame.largest_acked is NOT equal to the Max() of
4663 // the first Interval then it is interpreted as acking a single
4664 // packet at QuicAckFrame.largest_acked, with additional
4665 // Intervals indicating additional ack blocks. The encoding is
4666 // a) The packet's largest_acked is the QuicAckFrame's largest
4667 // acked,
4668 // b) the first ack block size is 0,
4669 // c) The packet's ack_block_count is the number of QuicAckFrame
4670 // Intervals, and
4671 // d) The QuicAckFrame Intervals are encoded in additional ack
4672 // blocks in the packet.
4673 ack_block_smallest = largest_acked;
4674 }
4675 size_t ack_block_count_size = QuicDataWriter::GetVarInt62Len(ack_block_count);
4676 ack_frame_size += ack_block_count_size;
4677
4678 uint64_t first_ack_block = ack_block_largest - ack_block_smallest;
4679 size_t first_ack_block_size = QuicDataWriter::GetVarInt62Len(first_ack_block);
4680 ack_frame_size += first_ack_block_size;
4681
4682 // Account for the remaining Intervals, if any.
4683 while (ack_block_count != 0) {
4684 uint64_t gap_size = ack_block_smallest - itr->max();
4685 // Decrement per the protocol specification
4686 size_t size_of_gap_size = QuicDataWriter::GetVarInt62Len(gap_size - 1);
4687 ack_frame_size += size_of_gap_size;
4688
4689 uint64_t block_size = itr->max() - itr->min();
4690 // Decrement per the protocol specification
4691 size_t size_of_block_size = QuicDataWriter::GetVarInt62Len(block_size - 1);
4692 ack_frame_size += size_of_block_size;
4693
4694 ack_block_smallest = itr->min();
4695 itr++;
4696 ack_block_count--;
4697 }
4698
4699 return ack_frame_size;
4700}
4701
4702size_t QuicFramer::GetAckFrameSize(
4703 const QuicAckFrame& ack,
dschinazi17d42422019-06-18 16:35:07 -07004704 QuicPacketNumberLength /*packet_number_length*/) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05004705 DCHECK(!ack.packets.Empty());
4706 size_t ack_size = 0;
4707
fkastenholz305e1732019-06-18 05:01:22 -07004708 if (VersionHasIetfQuicFrames(version_.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05004709 return GetIetfAckFrameSize(ack);
4710 }
4711 AckFrameInfo ack_info = GetAckFrameInfo(ack);
4712 QuicPacketNumberLength largest_acked_length =
4713 GetMinPacketNumberLength(version_.transport_version, LargestAcked(ack));
4714 QuicPacketNumberLength ack_block_length = GetMinPacketNumberLength(
4715 version_.transport_version, QuicPacketNumber(ack_info.max_block_length));
4716
4717 ack_size =
4718 GetMinAckFrameSize(version_.transport_version, largest_acked_length);
4719 // First ack block length.
4720 ack_size += ack_block_length;
4721 if (ack_info.num_ack_blocks != 0) {
4722 ack_size += kNumberOfAckBlocksSize;
4723 ack_size += std::min(ack_info.num_ack_blocks, kMaxAckBlocks) *
4724 (ack_block_length + PACKET_1BYTE_PACKET_NUMBER);
4725 }
4726
4727 // Include timestamps.
4728 if (process_timestamps_) {
4729 ack_size += GetAckFrameTimeStampSize(ack);
4730 }
4731
4732 return ack_size;
4733}
4734
4735size_t QuicFramer::GetAckFrameTimeStampSize(const QuicAckFrame& ack) {
4736 if (ack.received_packet_times.empty()) {
4737 return 0;
4738 }
4739
4740 return kQuicNumTimestampsLength + kQuicFirstTimestampLength +
4741 (kQuicTimestampLength + kQuicTimestampPacketNumberGapLength) *
4742 (ack.received_packet_times.size() - 1);
4743}
4744
4745size_t QuicFramer::ComputeFrameLength(
4746 const QuicFrame& frame,
4747 bool last_frame_in_packet,
4748 QuicPacketNumberLength packet_number_length) {
4749 switch (frame.type) {
4750 case STREAM_FRAME:
4751 return GetMinStreamFrameSize(
4752 version_.transport_version, frame.stream_frame.stream_id,
4753 frame.stream_frame.offset, last_frame_in_packet,
4754 frame.stream_frame.data_length) +
4755 frame.stream_frame.data_length;
4756 case CRYPTO_FRAME:
4757 return GetMinCryptoFrameSize(frame.crypto_frame->offset,
4758 frame.crypto_frame->data_length) +
4759 frame.crypto_frame->data_length;
4760 case ACK_FRAME: {
4761 return GetAckFrameSize(*frame.ack_frame, packet_number_length);
4762 }
4763 case STOP_WAITING_FRAME:
4764 return GetStopWaitingFrameSize(version_.transport_version,
4765 packet_number_length);
4766 case MTU_DISCOVERY_FRAME:
4767 // MTU discovery frames are serialized as ping frames.
4768 return kQuicFrameTypeSize;
4769 case MESSAGE_FRAME:
4770 return GetMessageFrameSize(version_.transport_version,
4771 last_frame_in_packet,
4772 frame.message_frame->message_length);
4773 case PADDING_FRAME:
4774 DCHECK(false);
4775 return 0;
4776 default:
4777 return GetRetransmittableControlFrameSize(version_.transport_version,
4778 frame);
4779 }
4780}
4781
4782bool QuicFramer::AppendTypeByte(const QuicFrame& frame,
4783 bool last_frame_in_packet,
4784 QuicDataWriter* writer) {
fkastenholz305e1732019-06-18 05:01:22 -07004785 if (VersionHasIetfQuicFrames(version_.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05004786 return AppendIetfTypeByte(frame, last_frame_in_packet, writer);
4787 }
4788 uint8_t type_byte = 0;
4789 switch (frame.type) {
4790 case STREAM_FRAME:
4791 type_byte =
4792 GetStreamFrameTypeByte(frame.stream_frame, last_frame_in_packet);
4793 break;
4794 case ACK_FRAME:
4795 return true;
4796 case MTU_DISCOVERY_FRAME:
4797 type_byte = static_cast<uint8_t>(PING_FRAME);
4798 break;
QUICHE teama6ef0a62019-03-07 20:34:33 -05004799 case NEW_CONNECTION_ID_FRAME:
4800 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -07004801 "Attempt to append NEW_CONNECTION_ID frame and not in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05004802 return RaiseError(QUIC_INTERNAL_ERROR);
4803 case RETIRE_CONNECTION_ID_FRAME:
4804 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -07004805 "Attempt to append RETIRE_CONNECTION_ID frame and not in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05004806 return RaiseError(QUIC_INTERNAL_ERROR);
4807 case NEW_TOKEN_FRAME:
4808 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -07004809 "Attempt to append NEW_TOKEN frame and not in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05004810 return RaiseError(QUIC_INTERNAL_ERROR);
fkastenholz3c4eabf2019-04-22 07:49:59 -07004811 case MAX_STREAMS_FRAME:
QUICHE teama6ef0a62019-03-07 20:34:33 -05004812 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -07004813 "Attempt to append MAX_STREAMS frame and not in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05004814 return RaiseError(QUIC_INTERNAL_ERROR);
fkastenholz3c4eabf2019-04-22 07:49:59 -07004815 case STREAMS_BLOCKED_FRAME:
QUICHE teama6ef0a62019-03-07 20:34:33 -05004816 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -07004817 "Attempt to append STREAMS_BLOCKED frame and not in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05004818 return RaiseError(QUIC_INTERNAL_ERROR);
4819 case PATH_RESPONSE_FRAME:
4820 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -07004821 "Attempt to append PATH_RESPONSE frame and not in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05004822 return RaiseError(QUIC_INTERNAL_ERROR);
4823 case PATH_CHALLENGE_FRAME:
4824 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -07004825 "Attempt to append PATH_CHALLENGE frame and not in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05004826 return RaiseError(QUIC_INTERNAL_ERROR);
4827 case STOP_SENDING_FRAME:
4828 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -07004829 "Attempt to append STOP_SENDING frame and not in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05004830 return RaiseError(QUIC_INTERNAL_ERROR);
4831 case MESSAGE_FRAME:
4832 return true;
4833
4834 default:
4835 type_byte = static_cast<uint8_t>(frame.type);
4836 break;
4837 }
4838
4839 return writer->WriteUInt8(type_byte);
4840}
4841
4842bool QuicFramer::AppendIetfTypeByte(const QuicFrame& frame,
4843 bool last_frame_in_packet,
4844 QuicDataWriter* writer) {
4845 uint8_t type_byte = 0;
4846 switch (frame.type) {
4847 case PADDING_FRAME:
4848 type_byte = IETF_PADDING;
4849 break;
4850 case RST_STREAM_FRAME:
4851 type_byte = IETF_RST_STREAM;
4852 break;
4853 case CONNECTION_CLOSE_FRAME:
fkastenholz72f509b2019-04-10 09:17:49 -07004854 switch (frame.connection_close_frame->close_type) {
4855 case IETF_QUIC_APPLICATION_CONNECTION_CLOSE:
4856 type_byte = IETF_APPLICATION_CLOSE;
4857 break;
4858 case IETF_QUIC_TRANSPORT_CONNECTION_CLOSE:
4859 type_byte = IETF_CONNECTION_CLOSE;
4860 break;
4861 default:
4862 set_detailed_error("Invalid QuicConnectionCloseFrame type.");
4863 return RaiseError(QUIC_INTERNAL_ERROR);
4864 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004865 break;
4866 case GOAWAY_FRAME:
4867 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -07004868 "Attempt to create non-IETF QUIC GOAWAY frame in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05004869 return RaiseError(QUIC_INTERNAL_ERROR);
4870 case WINDOW_UPDATE_FRAME:
4871 // Depending on whether there is a stream ID or not, will be either a
4872 // MAX_STREAM_DATA frame or a MAX_DATA frame.
4873 if (frame.window_update_frame->stream_id ==
4874 QuicUtils::GetInvalidStreamId(transport_version())) {
4875 type_byte = IETF_MAX_DATA;
4876 } else {
4877 type_byte = IETF_MAX_STREAM_DATA;
4878 }
4879 break;
4880 case BLOCKED_FRAME:
4881 if (frame.blocked_frame->stream_id ==
4882 QuicUtils::GetInvalidStreamId(transport_version())) {
4883 type_byte = IETF_BLOCKED;
4884 } else {
4885 type_byte = IETF_STREAM_BLOCKED;
4886 }
4887 break;
4888 case STOP_WAITING_FRAME:
4889 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -07004890 "Attempt to append type byte of STOP WAITING frame in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05004891 return RaiseError(QUIC_INTERNAL_ERROR);
4892 case PING_FRAME:
4893 type_byte = IETF_PING;
4894 break;
4895 case STREAM_FRAME:
4896 type_byte =
4897 GetStreamFrameTypeByte(frame.stream_frame, last_frame_in_packet);
4898 break;
4899 case ACK_FRAME:
4900 // Do nothing here, AppendIetfAckFrameAndTypeByte() will put the type byte
4901 // in the buffer.
4902 return true;
4903 case MTU_DISCOVERY_FRAME:
4904 // The path MTU discovery frame is encoded as a PING frame on the wire.
4905 type_byte = IETF_PING;
4906 break;
QUICHE teama6ef0a62019-03-07 20:34:33 -05004907 case NEW_CONNECTION_ID_FRAME:
4908 type_byte = IETF_NEW_CONNECTION_ID;
4909 break;
4910 case RETIRE_CONNECTION_ID_FRAME:
4911 type_byte = IETF_RETIRE_CONNECTION_ID;
4912 break;
4913 case NEW_TOKEN_FRAME:
4914 type_byte = IETF_NEW_TOKEN;
4915 break;
fkastenholz3c4eabf2019-04-22 07:49:59 -07004916 case MAX_STREAMS_FRAME:
4917 if (frame.max_streams_frame.unidirectional) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05004918 type_byte = IETF_MAX_STREAMS_UNIDIRECTIONAL;
fkastenholz3c4eabf2019-04-22 07:49:59 -07004919 } else {
4920 type_byte = IETF_MAX_STREAMS_BIDIRECTIONAL;
QUICHE teama6ef0a62019-03-07 20:34:33 -05004921 }
4922 break;
fkastenholz3c4eabf2019-04-22 07:49:59 -07004923 case STREAMS_BLOCKED_FRAME:
4924 if (frame.streams_blocked_frame.unidirectional) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05004925 type_byte = IETF_STREAMS_BLOCKED_UNIDIRECTIONAL;
fkastenholz3c4eabf2019-04-22 07:49:59 -07004926 } else {
4927 type_byte = IETF_STREAMS_BLOCKED_BIDIRECTIONAL;
QUICHE teama6ef0a62019-03-07 20:34:33 -05004928 }
4929 break;
4930 case PATH_RESPONSE_FRAME:
4931 type_byte = IETF_PATH_RESPONSE;
4932 break;
4933 case PATH_CHALLENGE_FRAME:
4934 type_byte = IETF_PATH_CHALLENGE;
4935 break;
4936 case STOP_SENDING_FRAME:
4937 type_byte = IETF_STOP_SENDING;
4938 break;
4939 case MESSAGE_FRAME:
4940 return true;
4941 case CRYPTO_FRAME:
4942 type_byte = IETF_CRYPTO;
4943 break;
4944 default:
4945 QUIC_BUG << "Attempt to generate a frame type for an unsupported value: "
4946 << frame.type;
4947 return false;
4948 }
4949 return writer->WriteUInt8(type_byte);
4950}
4951
4952// static
4953bool QuicFramer::AppendPacketNumber(QuicPacketNumberLength packet_number_length,
4954 QuicPacketNumber packet_number,
4955 QuicDataWriter* writer) {
4956 DCHECK(packet_number.IsInitialized());
4957 if (!IsValidPacketNumberLength(packet_number_length)) {
4958 QUIC_BUG << "Invalid packet_number_length: " << packet_number_length;
4959 return false;
4960 }
4961 return writer->WriteBytesToUInt64(packet_number_length,
4962 packet_number.ToUint64());
4963}
4964
4965// static
4966bool QuicFramer::AppendStreamId(size_t stream_id_length,
4967 QuicStreamId stream_id,
4968 QuicDataWriter* writer) {
4969 if (stream_id_length == 0 || stream_id_length > 4) {
4970 QUIC_BUG << "Invalid stream_id_length: " << stream_id_length;
4971 return false;
4972 }
4973 return writer->WriteBytesToUInt64(stream_id_length, stream_id);
4974}
4975
4976// static
4977bool QuicFramer::AppendStreamOffset(size_t offset_length,
4978 QuicStreamOffset offset,
4979 QuicDataWriter* writer) {
4980 if (offset_length == 1 || offset_length > 8) {
4981 QUIC_BUG << "Invalid stream_offset_length: " << offset_length;
4982 return false;
4983 }
4984
4985 return writer->WriteBytesToUInt64(offset_length, offset);
4986}
4987
4988// static
4989bool QuicFramer::AppendAckBlock(uint8_t gap,
4990 QuicPacketNumberLength length_length,
4991 uint64_t length,
4992 QuicDataWriter* writer) {
4993 if (length == 0) {
4994 if (!IsValidPacketNumberLength(length_length)) {
4995 QUIC_BUG << "Invalid packet_number_length: " << length_length;
4996 return false;
4997 }
4998 return writer->WriteUInt8(gap) &&
4999 writer->WriteBytesToUInt64(length_length, length);
5000 }
5001 return writer->WriteUInt8(gap) &&
5002 AppendPacketNumber(length_length, QuicPacketNumber(length), writer);
5003}
5004
5005bool QuicFramer::AppendStreamFrame(const QuicStreamFrame& frame,
5006 bool no_stream_frame_length,
5007 QuicDataWriter* writer) {
fkastenholz305e1732019-06-18 05:01:22 -07005008 if (VersionHasIetfQuicFrames(version_.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005009 return AppendIetfStreamFrame(frame, no_stream_frame_length, writer);
5010 }
5011 if (!AppendStreamId(GetStreamIdSize(frame.stream_id), frame.stream_id,
5012 writer)) {
5013 QUIC_BUG << "Writing stream id size failed.";
5014 return false;
5015 }
5016 if (!AppendStreamOffset(
5017 GetStreamOffsetSize(version_.transport_version, frame.offset),
5018 frame.offset, writer)) {
5019 QUIC_BUG << "Writing offset size failed.";
5020 return false;
5021 }
5022 if (!no_stream_frame_length) {
dschinazi878cfb52019-06-17 17:12:58 -07005023 static_assert(
wubeff50282019-06-19 09:04:30 -07005024 std::numeric_limits<decltype(frame.data_length)>::max() <=
dschinazi878cfb52019-06-17 17:12:58 -07005025 std::numeric_limits<uint16_t>::max(),
5026 "If frame.data_length can hold more than a uint16_t than we need to "
5027 "check that frame.data_length <= std::numeric_limits<uint16_t>::max()");
5028 if (!writer->WriteUInt16(static_cast<uint16_t>(frame.data_length))) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005029 QUIC_BUG << "Writing stream frame length failed";
5030 return false;
5031 }
5032 }
5033
5034 if (data_producer_ != nullptr) {
5035 DCHECK_EQ(nullptr, frame.data_buffer);
5036 if (frame.data_length == 0) {
5037 return true;
5038 }
5039 if (data_producer_->WriteStreamData(frame.stream_id, frame.offset,
5040 frame.data_length,
5041 writer) != WRITE_SUCCESS) {
5042 QUIC_BUG << "Writing frame data failed.";
5043 return false;
5044 }
5045 return true;
5046 }
5047
5048 if (!writer->WriteBytes(frame.data_buffer, frame.data_length)) {
5049 QUIC_BUG << "Writing frame data failed.";
5050 return false;
5051 }
5052 return true;
5053}
5054
QUICHE teama6ef0a62019-03-07 20:34:33 -05005055bool QuicFramer::AppendNewTokenFrame(const QuicNewTokenFrame& frame,
5056 QuicDataWriter* writer) {
5057 if (!writer->WriteVarInt62(static_cast<uint64_t>(frame.token.length()))) {
5058 set_detailed_error("Writing token length failed.");
5059 return false;
5060 }
5061 if (!writer->WriteBytes(frame.token.data(), frame.token.length())) {
5062 set_detailed_error("Writing token buffer failed.");
5063 return false;
5064 }
5065 return true;
5066}
5067
5068bool QuicFramer::ProcessNewTokenFrame(QuicDataReader* reader,
5069 QuicNewTokenFrame* frame) {
5070 uint64_t length;
5071 if (!reader->ReadVarInt62(&length)) {
5072 set_detailed_error("Unable to read new token length.");
5073 return false;
5074 }
5075 if (length > kMaxNewTokenTokenLength) {
5076 set_detailed_error("Token length larger than maximum.");
5077 return false;
5078 }
5079
5080 // TODO(ianswett): Don't use QuicStringPiece as an intermediary.
5081 QuicStringPiece data;
5082 if (!reader->ReadStringPiece(&data, length)) {
5083 set_detailed_error("Unable to read new token data.");
5084 return false;
5085 }
vasilvvc48c8712019-03-11 13:38:16 -07005086 frame->token = std::string(data);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005087 return true;
5088}
5089
5090// Add a new ietf-format stream frame.
5091// Bits controlling whether there is a frame-length and frame-offset
5092// are in the QuicStreamFrame.
5093bool QuicFramer::AppendIetfStreamFrame(const QuicStreamFrame& frame,
5094 bool last_frame_in_packet,
5095 QuicDataWriter* writer) {
5096 if (!writer->WriteVarInt62(static_cast<uint64_t>(frame.stream_id))) {
5097 set_detailed_error("Writing stream id failed.");
5098 return false;
5099 }
5100
5101 if (frame.offset != 0) {
5102 if (!writer->WriteVarInt62(static_cast<uint64_t>(frame.offset))) {
5103 set_detailed_error("Writing data offset failed.");
5104 return false;
5105 }
5106 }
5107
5108 if (!last_frame_in_packet) {
5109 if (!writer->WriteVarInt62(frame.data_length)) {
5110 set_detailed_error("Writing data length failed.");
5111 return false;
5112 }
5113 }
5114
5115 if (frame.data_length == 0) {
5116 return true;
5117 }
5118 if (data_producer_ == nullptr) {
5119 if (!writer->WriteBytes(frame.data_buffer, frame.data_length)) {
5120 set_detailed_error("Writing frame data failed.");
5121 return false;
5122 }
5123 } else {
5124 DCHECK_EQ(nullptr, frame.data_buffer);
5125
5126 if (data_producer_->WriteStreamData(frame.stream_id, frame.offset,
5127 frame.data_length,
5128 writer) != WRITE_SUCCESS) {
5129 set_detailed_error("Writing frame data failed.");
5130 return false;
5131 }
5132 }
5133 return true;
5134}
5135
5136bool QuicFramer::AppendCryptoFrame(const QuicCryptoFrame& frame,
5137 QuicDataWriter* writer) {
5138 if (!writer->WriteVarInt62(static_cast<uint64_t>(frame.offset))) {
5139 set_detailed_error("Writing data offset failed.");
5140 return false;
5141 }
5142 if (!writer->WriteVarInt62(static_cast<uint64_t>(frame.data_length))) {
5143 set_detailed_error("Writing data length failed.");
5144 return false;
5145 }
5146 if (data_producer_ == nullptr) {
5147 if (frame.data_buffer == nullptr ||
5148 !writer->WriteBytes(frame.data_buffer, frame.data_length)) {
5149 set_detailed_error("Writing frame data failed.");
5150 return false;
5151 }
5152 } else {
5153 DCHECK_EQ(nullptr, frame.data_buffer);
5154 if (!data_producer_->WriteCryptoData(frame.level, frame.offset,
5155 frame.data_length, writer)) {
5156 return false;
5157 }
5158 }
5159 return true;
5160}
5161
5162void QuicFramer::set_version(const ParsedQuicVersion version) {
5163 DCHECK(IsSupportedVersion(version)) << ParsedQuicVersionToString(version);
5164 version_ = version;
5165}
5166
5167bool QuicFramer::AppendAckFrameAndTypeByte(const QuicAckFrame& frame,
5168 QuicDataWriter* writer) {
fkastenholz305e1732019-06-18 05:01:22 -07005169 if (VersionHasIetfQuicFrames(transport_version())) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005170 return AppendIetfAckFrameAndTypeByte(frame, writer);
5171 }
5172
5173 const AckFrameInfo new_ack_info = GetAckFrameInfo(frame);
5174 QuicPacketNumber largest_acked = LargestAcked(frame);
5175 QuicPacketNumberLength largest_acked_length =
5176 GetMinPacketNumberLength(version_.transport_version, largest_acked);
5177 QuicPacketNumberLength ack_block_length =
5178 GetMinPacketNumberLength(version_.transport_version,
5179 QuicPacketNumber(new_ack_info.max_block_length));
5180 // Calculate available bytes for timestamps and ack blocks.
5181 int32_t available_timestamp_and_ack_block_bytes =
5182 writer->capacity() - writer->length() - ack_block_length -
5183 GetMinAckFrameSize(version_.transport_version, largest_acked_length) -
5184 (new_ack_info.num_ack_blocks != 0 ? kNumberOfAckBlocksSize : 0);
5185 DCHECK_LE(0, available_timestamp_and_ack_block_bytes);
5186
5187 // Write out the type byte by setting the low order bits and doing shifts
5188 // to make room for the next bit flags to be set.
5189 // Whether there are multiple ack blocks.
5190 uint8_t type_byte = 0;
5191 SetBit(&type_byte, new_ack_info.num_ack_blocks != 0,
5192 kQuicHasMultipleAckBlocksOffset);
5193
5194 SetBits(&type_byte, GetPacketNumberFlags(largest_acked_length),
5195 kQuicSequenceNumberLengthNumBits, kLargestAckedOffset);
5196
5197 SetBits(&type_byte, GetPacketNumberFlags(ack_block_length),
5198 kQuicSequenceNumberLengthNumBits, kActBlockLengthOffset);
5199
5200 type_byte |= kQuicFrameTypeAckMask;
5201
5202 if (!writer->WriteUInt8(type_byte)) {
5203 return false;
5204 }
5205
5206 size_t max_num_ack_blocks = available_timestamp_and_ack_block_bytes /
5207 (ack_block_length + PACKET_1BYTE_PACKET_NUMBER);
5208
5209 // Number of ack blocks.
5210 size_t num_ack_blocks =
5211 std::min(new_ack_info.num_ack_blocks, max_num_ack_blocks);
5212 if (num_ack_blocks > std::numeric_limits<uint8_t>::max()) {
5213 num_ack_blocks = std::numeric_limits<uint8_t>::max();
5214 }
5215
5216 // Largest acked.
5217 if (!AppendPacketNumber(largest_acked_length, largest_acked, writer)) {
5218 return false;
5219 }
5220
5221 // Largest acked delta time.
5222 uint64_t ack_delay_time_us = kUFloat16MaxValue;
5223 if (!frame.ack_delay_time.IsInfinite()) {
5224 DCHECK_LE(0u, frame.ack_delay_time.ToMicroseconds());
5225 ack_delay_time_us = frame.ack_delay_time.ToMicroseconds();
5226 }
5227 if (!writer->WriteUFloat16(ack_delay_time_us)) {
5228 return false;
5229 }
5230
5231 if (num_ack_blocks > 0) {
5232 if (!writer->WriteBytes(&num_ack_blocks, 1)) {
5233 return false;
5234 }
5235 }
5236
5237 // First ack block length.
5238 if (!AppendPacketNumber(ack_block_length,
5239 QuicPacketNumber(new_ack_info.first_block_length),
5240 writer)) {
5241 return false;
5242 }
5243
5244 // Ack blocks.
5245 if (num_ack_blocks > 0) {
5246 size_t num_ack_blocks_written = 0;
5247 // Append, in descending order from the largest ACKed packet, a series of
5248 // ACK blocks that represents the successfully acknoweldged packets. Each
5249 // appended gap/block length represents a descending delta from the previous
5250 // block. i.e.:
5251 // |--- length ---|--- gap ---|--- length ---|--- gap ---|--- largest ---|
5252 // For gaps larger than can be represented by a single encoded gap, a 0
5253 // length gap of the maximum is used, i.e.:
5254 // |--- length ---|--- gap ---|- 0 -|--- gap ---|--- largest ---|
5255 auto itr = frame.packets.rbegin();
5256 QuicPacketNumber previous_start = itr->min();
5257 ++itr;
5258
5259 for (;
5260 itr != frame.packets.rend() && num_ack_blocks_written < num_ack_blocks;
5261 previous_start = itr->min(), ++itr) {
5262 const auto& interval = *itr;
5263 const uint64_t total_gap = previous_start - interval.max();
5264 const size_t num_encoded_gaps =
5265 (total_gap + std::numeric_limits<uint8_t>::max() - 1) /
5266 std::numeric_limits<uint8_t>::max();
QUICHE teama6ef0a62019-03-07 20:34:33 -05005267
5268 // Append empty ACK blocks because the gap is longer than a single gap.
5269 for (size_t i = 1;
5270 i < num_encoded_gaps && num_ack_blocks_written < num_ack_blocks;
5271 ++i) {
5272 if (!AppendAckBlock(std::numeric_limits<uint8_t>::max(),
5273 ack_block_length, 0, writer)) {
5274 return false;
5275 }
5276 ++num_ack_blocks_written;
5277 }
5278 if (num_ack_blocks_written >= num_ack_blocks) {
5279 if (QUIC_PREDICT_FALSE(num_ack_blocks_written != num_ack_blocks)) {
5280 QUIC_BUG << "Wrote " << num_ack_blocks_written
5281 << ", expected to write " << num_ack_blocks;
5282 }
5283 break;
5284 }
5285
5286 const uint8_t last_gap =
5287 total_gap -
5288 (num_encoded_gaps - 1) * std::numeric_limits<uint8_t>::max();
5289 // Append the final ACK block with a non-empty size.
5290 if (!AppendAckBlock(last_gap, ack_block_length,
5291 PacketNumberIntervalLength(interval), writer)) {
5292 return false;
5293 }
5294 ++num_ack_blocks_written;
5295 }
5296 DCHECK_EQ(num_ack_blocks, num_ack_blocks_written);
5297 }
5298 // Timestamps.
5299 // If we don't process timestamps or if we don't have enough available space
5300 // to append all the timestamps, don't append any of them.
5301 if (process_timestamps_ && writer->capacity() - writer->length() >=
5302 GetAckFrameTimeStampSize(frame)) {
5303 if (!AppendTimestampsToAckFrame(frame, writer)) {
5304 return false;
5305 }
5306 } else {
5307 uint8_t num_received_packets = 0;
5308 if (!writer->WriteBytes(&num_received_packets, 1)) {
5309 return false;
5310 }
5311 }
5312
5313 return true;
5314}
5315
5316bool QuicFramer::AppendTimestampsToAckFrame(const QuicAckFrame& frame,
5317 QuicDataWriter* writer) {
5318 DCHECK_GE(std::numeric_limits<uint8_t>::max(),
5319 frame.received_packet_times.size());
5320 // num_received_packets is only 1 byte.
5321 if (frame.received_packet_times.size() >
5322 std::numeric_limits<uint8_t>::max()) {
5323 return false;
5324 }
5325
5326 uint8_t num_received_packets = frame.received_packet_times.size();
5327 if (!writer->WriteBytes(&num_received_packets, 1)) {
5328 return false;
5329 }
5330 if (num_received_packets == 0) {
5331 return true;
5332 }
5333
5334 auto it = frame.received_packet_times.begin();
5335 QuicPacketNumber packet_number = it->first;
5336 uint64_t delta_from_largest_observed = LargestAcked(frame) - packet_number;
5337
5338 DCHECK_GE(std::numeric_limits<uint8_t>::max(), delta_from_largest_observed);
5339 if (delta_from_largest_observed > std::numeric_limits<uint8_t>::max()) {
5340 return false;
5341 }
5342
5343 if (!writer->WriteUInt8(delta_from_largest_observed)) {
5344 return false;
5345 }
5346
5347 // Use the lowest 4 bytes of the time delta from the creation_time_.
5348 const uint64_t time_epoch_delta_us = UINT64_C(1) << 32;
5349 uint32_t time_delta_us =
5350 static_cast<uint32_t>((it->second - creation_time_).ToMicroseconds() &
5351 (time_epoch_delta_us - 1));
5352 if (!writer->WriteUInt32(time_delta_us)) {
5353 return false;
5354 }
5355
5356 QuicTime prev_time = it->second;
5357
5358 for (++it; it != frame.received_packet_times.end(); ++it) {
5359 packet_number = it->first;
5360 delta_from_largest_observed = LargestAcked(frame) - packet_number;
5361
5362 if (delta_from_largest_observed > std::numeric_limits<uint8_t>::max()) {
5363 return false;
5364 }
5365
5366 if (!writer->WriteUInt8(delta_from_largest_observed)) {
5367 return false;
5368 }
5369
5370 uint64_t frame_time_delta_us = (it->second - prev_time).ToMicroseconds();
5371 prev_time = it->second;
5372 if (!writer->WriteUFloat16(frame_time_delta_us)) {
5373 return false;
5374 }
5375 }
5376 return true;
5377}
5378
5379bool QuicFramer::AppendStopWaitingFrame(const QuicPacketHeader& header,
5380 const QuicStopWaitingFrame& frame,
5381 QuicDataWriter* writer) {
fayangd4291e42019-05-30 10:31:21 -07005382 DCHECK(!VersionHasIetfInvariantHeader(version_.transport_version));
QUICHE teama6ef0a62019-03-07 20:34:33 -05005383 DCHECK(frame.least_unacked.IsInitialized() &&
5384 header.packet_number >= frame.least_unacked);
5385 const uint64_t least_unacked_delta =
5386 header.packet_number - frame.least_unacked;
5387 const uint64_t length_shift = header.packet_number_length * 8;
5388
5389 if (least_unacked_delta >> length_shift > 0) {
5390 QUIC_BUG << "packet_number_length " << header.packet_number_length
5391 << " is too small for least_unacked_delta: " << least_unacked_delta
5392 << " packet_number:" << header.packet_number
5393 << " least_unacked:" << frame.least_unacked
5394 << " version:" << version_.transport_version;
5395 return false;
5396 }
5397 if (least_unacked_delta == 0) {
5398 return writer->WriteBytesToUInt64(header.packet_number_length,
5399 least_unacked_delta);
5400 }
5401 if (!AppendPacketNumber(header.packet_number_length,
5402 QuicPacketNumber(least_unacked_delta), writer)) {
5403 QUIC_BUG << " seq failed: " << header.packet_number_length;
5404 return false;
5405 }
5406
5407 return true;
5408}
5409
5410int QuicFramer::CalculateIetfAckBlockCount(const QuicAckFrame& frame,
dschinazi17d42422019-06-18 16:35:07 -07005411 QuicDataWriter* /*writer*/,
QUICHE teama6ef0a62019-03-07 20:34:33 -05005412 size_t available_space) {
5413 // Number of blocks requested in the frame
5414 uint64_t ack_block_count = frame.packets.NumIntervals();
5415
5416 auto itr = frame.packets.rbegin();
5417
5418 int actual_block_count = 1;
5419 uint64_t block_length = itr->max() - itr->min();
5420 size_t encoded_size = QuicDataWriter::GetVarInt62Len(block_length);
5421 if (encoded_size > available_space) {
5422 return 0;
5423 }
5424 available_space -= encoded_size;
5425 QuicPacketNumber previous_ack_end = itr->min();
5426 ack_block_count--;
5427
5428 while (ack_block_count) {
5429 // Each block is a gap followed by another ACK. Calculate each value,
5430 // determine the encoded lengths, and check against the available space.
5431 itr++;
5432 size_t gap = previous_ack_end - itr->max() - 1;
5433 encoded_size = QuicDataWriter::GetVarInt62Len(gap);
5434
5435 // Add the ACK block.
5436 block_length = itr->max() - itr->min();
5437 encoded_size += QuicDataWriter::GetVarInt62Len(block_length);
5438
5439 if (encoded_size > available_space) {
5440 // No room for this block, so what we've
5441 // done up to now is all that can be done.
5442 return actual_block_count;
5443 }
5444 available_space -= encoded_size;
5445 actual_block_count++;
5446 previous_ack_end = itr->min();
5447 ack_block_count--;
5448 }
5449 // Ran through the whole thing! We can do all blocks.
5450 return actual_block_count;
5451}
5452
5453bool QuicFramer::AppendIetfAckFrameAndTypeByte(const QuicAckFrame& frame,
5454 QuicDataWriter* writer) {
5455 // Assume frame is an IETF_ACK frame. If |ecn_counters_populated| is true and
5456 // any of the ECN counters is non-0 then turn it into an IETF_ACK+ECN frame.
5457 uint8_t type = IETF_ACK;
5458 if (frame.ecn_counters_populated &&
5459 (frame.ect_0_count || frame.ect_1_count || frame.ecn_ce_count)) {
5460 type = IETF_ACK_ECN;
5461 }
5462
5463 if (!writer->WriteUInt8(type)) {
5464 set_detailed_error("No room for frame-type");
5465 return false;
5466 }
5467
5468 QuicPacketNumber largest_acked = LargestAcked(frame);
5469 if (!writer->WriteVarInt62(largest_acked.ToUint64())) {
5470 set_detailed_error("No room for largest-acked in ack frame");
5471 return false;
5472 }
5473
5474 uint64_t ack_delay_time_us = kVarInt62MaxValue;
5475 if (!frame.ack_delay_time.IsInfinite()) {
5476 DCHECK_LE(0u, frame.ack_delay_time.ToMicroseconds());
5477 ack_delay_time_us = frame.ack_delay_time.ToMicroseconds();
fkastenholz4dc4ba32019-07-30 09:55:25 -07005478 ack_delay_time_us = ack_delay_time_us >> local_ack_delay_exponent_;
QUICHE teama6ef0a62019-03-07 20:34:33 -05005479 }
5480
5481 if (!writer->WriteVarInt62(ack_delay_time_us)) {
5482 set_detailed_error("No room for ack-delay in ack frame");
5483 return false;
5484 }
5485 if (type == IETF_ACK_ECN) {
5486 // Encode the ACK ECN fields
5487 if (!writer->WriteVarInt62(frame.ect_0_count)) {
5488 set_detailed_error("No room for ect_0_count in ack frame");
5489 return false;
5490 }
5491 if (!writer->WriteVarInt62(frame.ect_1_count)) {
5492 set_detailed_error("No room for ect_1_count in ack frame");
5493 return false;
5494 }
5495 if (!writer->WriteVarInt62(frame.ecn_ce_count)) {
5496 set_detailed_error("No room for ecn_ce_count in ack frame");
5497 return false;
5498 }
5499 }
5500
5501 uint64_t ack_block_count = frame.packets.NumIntervals();
5502 if (ack_block_count == 0) {
5503 // If the QuicAckFrame has no Intervals, then it is interpreted
5504 // as an ack of a single packet at QuicAckFrame.largest_acked.
5505 // The resulting ack will consist of only the frame's
5506 // largest_ack & first_ack_block fields. The first ack block will be 0
5507 // (indicating a single packet) and the ack block_count will be 0.
5508 if (!writer->WriteVarInt62(0)) {
5509 set_detailed_error("No room for ack block count in ack frame");
5510 return false;
5511 }
5512 // size of the first block is 1 packet
5513 if (!writer->WriteVarInt62(0)) {
5514 set_detailed_error("No room for first ack block in ack frame");
5515 return false;
5516 }
5517 return true;
5518 }
5519 // Case 2 or 3
5520 auto itr = frame.packets.rbegin();
5521
5522 QuicPacketNumber ack_block_largest(largest_acked);
5523 QuicPacketNumber ack_block_smallest;
5524 if ((itr->max() - 1) == QuicPacketNumber(largest_acked)) {
5525 // If largest_acked + 1 is equal to the Max() of the first Interval
5526 // in the QuicAckFrame then the first Interval is the first ack block of the
5527 // frame; remaining Intervals are additional ack blocks. The QuicAckFrame's
5528 // first Interval is encoded in the frame's largest_acked/first_ack_block,
5529 // the remaining Intervals are encoded in additional ack blocks in the
5530 // frame, and the packet's ack_block_count is the number of QuicAckFrame
5531 // Intervals - 1.
5532 ack_block_smallest = itr->min();
5533 itr++;
5534 ack_block_count--;
5535 } else {
5536 // If QuicAckFrame.largest_acked is NOT equal to the Max() of
5537 // the first Interval then it is interpreted as acking a single
5538 // packet at QuicAckFrame.largest_acked, with additional
5539 // Intervals indicating additional ack blocks. The encoding is
5540 // a) The packet's largest_acked is the QuicAckFrame's largest
5541 // acked,
5542 // b) the first ack block size is 0,
5543 // c) The packet's ack_block_count is the number of QuicAckFrame
5544 // Intervals, and
5545 // d) The QuicAckFrame Intervals are encoded in additional ack
5546 // blocks in the packet.
5547 ack_block_smallest = largest_acked;
5548 }
5549
5550 if (!writer->WriteVarInt62(ack_block_count)) {
5551 set_detailed_error("No room for ack block count in ack frame");
5552 return false;
5553 }
5554
5555 uint64_t first_ack_block = ack_block_largest - ack_block_smallest;
5556 if (!writer->WriteVarInt62(first_ack_block)) {
5557 set_detailed_error("No room for first ack block in ack frame");
5558 return false;
5559 }
5560
5561 // For the remaining QuicAckFrame Intervals, if any
5562 while (ack_block_count != 0) {
5563 uint64_t gap_size = ack_block_smallest - itr->max();
5564 if (!writer->WriteVarInt62(gap_size - 1)) {
5565 set_detailed_error("No room for gap block in ack frame");
5566 return false;
5567 }
5568
5569 uint64_t block_size = itr->max() - itr->min();
5570 if (!writer->WriteVarInt62(block_size - 1)) {
5571 set_detailed_error("No room for nth ack block in ack frame");
5572 return false;
5573 }
5574
5575 ack_block_smallest = itr->min();
5576 itr++;
5577 ack_block_count--;
5578 }
5579 return true;
5580}
5581
5582bool QuicFramer::AppendRstStreamFrame(const QuicRstStreamFrame& frame,
5583 QuicDataWriter* writer) {
fkastenholz305e1732019-06-18 05:01:22 -07005584 if (VersionHasIetfQuicFrames(version_.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005585 return AppendIetfResetStreamFrame(frame, writer);
5586 }
5587 if (!writer->WriteUInt32(frame.stream_id)) {
5588 return false;
5589 }
5590
5591 if (!writer->WriteUInt64(frame.byte_offset)) {
5592 return false;
5593 }
5594
5595 uint32_t error_code = static_cast<uint32_t>(frame.error_code);
5596 if (!writer->WriteUInt32(error_code)) {
5597 return false;
5598 }
5599
5600 return true;
5601}
5602
5603bool QuicFramer::AppendConnectionCloseFrame(
5604 const QuicConnectionCloseFrame& frame,
5605 QuicDataWriter* writer) {
fkastenholz305e1732019-06-18 05:01:22 -07005606 if (VersionHasIetfQuicFrames(version_.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005607 return AppendIetfConnectionCloseFrame(frame, writer);
5608 }
fkastenholze9d71a82019-04-09 05:12:13 -07005609 uint32_t error_code = static_cast<uint32_t>(frame.quic_error_code);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005610 if (!writer->WriteUInt32(error_code)) {
5611 return false;
5612 }
5613 if (!writer->WriteStringPiece16(TruncateErrorString(frame.error_details))) {
5614 return false;
5615 }
5616 return true;
5617}
5618
5619bool QuicFramer::AppendGoAwayFrame(const QuicGoAwayFrame& frame,
5620 QuicDataWriter* writer) {
5621 uint32_t error_code = static_cast<uint32_t>(frame.error_code);
5622 if (!writer->WriteUInt32(error_code)) {
5623 return false;
5624 }
5625 uint32_t stream_id = static_cast<uint32_t>(frame.last_good_stream_id);
5626 if (!writer->WriteUInt32(stream_id)) {
5627 return false;
5628 }
5629 if (!writer->WriteStringPiece16(TruncateErrorString(frame.reason_phrase))) {
5630 return false;
5631 }
5632 return true;
5633}
5634
5635bool QuicFramer::AppendWindowUpdateFrame(const QuicWindowUpdateFrame& frame,
5636 QuicDataWriter* writer) {
5637 uint32_t stream_id = static_cast<uint32_t>(frame.stream_id);
5638 if (!writer->WriteUInt32(stream_id)) {
5639 return false;
5640 }
5641 if (!writer->WriteUInt64(frame.byte_offset)) {
5642 return false;
5643 }
5644 return true;
5645}
5646
5647bool QuicFramer::AppendBlockedFrame(const QuicBlockedFrame& frame,
5648 QuicDataWriter* writer) {
fkastenholz305e1732019-06-18 05:01:22 -07005649 if (VersionHasIetfQuicFrames(version_.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005650 if (frame.stream_id == QuicUtils::GetInvalidStreamId(transport_version())) {
5651 return AppendIetfBlockedFrame(frame, writer);
5652 }
5653 return AppendStreamBlockedFrame(frame, writer);
5654 }
5655 uint32_t stream_id = static_cast<uint32_t>(frame.stream_id);
5656 if (!writer->WriteUInt32(stream_id)) {
5657 return false;
5658 }
5659 return true;
5660}
5661
5662bool QuicFramer::AppendPaddingFrame(const QuicPaddingFrame& frame,
5663 QuicDataWriter* writer) {
5664 if (frame.num_padding_bytes == 0) {
5665 return false;
5666 }
5667 if (frame.num_padding_bytes < 0) {
5668 QUIC_BUG_IF(frame.num_padding_bytes != -1);
5669 writer->WritePadding();
5670 return true;
5671 }
5672 // Please note, num_padding_bytes includes type byte which has been written.
5673 return writer->WritePaddingBytes(frame.num_padding_bytes - 1);
5674}
5675
5676bool QuicFramer::AppendMessageFrameAndTypeByte(const QuicMessageFrame& frame,
5677 bool last_frame_in_packet,
5678 QuicDataWriter* writer) {
5679 uint8_t type_byte = last_frame_in_packet ? IETF_EXTENSION_MESSAGE_NO_LENGTH
5680 : IETF_EXTENSION_MESSAGE;
5681 if (!writer->WriteUInt8(type_byte)) {
5682 return false;
5683 }
5684 if (!last_frame_in_packet && !writer->WriteVarInt62(frame.message_length)) {
5685 return false;
5686 }
5687 for (const auto& slice : frame.message_data) {
5688 if (!writer->WriteBytes(slice.data(), slice.length())) {
5689 return false;
5690 }
5691 }
5692 return true;
5693}
5694
5695bool QuicFramer::RaiseError(QuicErrorCode error) {
5696 QUIC_DLOG(INFO) << ENDPOINT << "Error: " << QuicErrorCodeToString(error)
5697 << " detail: " << detailed_error_;
5698 set_error(error);
nharper55fa6132019-05-07 19:37:21 -07005699 if (visitor_) {
5700 visitor_->OnError(this);
5701 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05005702 return false;
5703}
5704
5705bool QuicFramer::IsVersionNegotiation(
5706 const QuicPacketHeader& header,
5707 bool packet_has_ietf_packet_header) const {
dschinazi072da7c2019-05-07 17:57:42 -07005708 if (!packet_has_ietf_packet_header &&
5709 perspective_ == Perspective::IS_CLIENT) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005710 return header.version_flag;
5711 }
5712 if (header.form == IETF_QUIC_SHORT_HEADER_PACKET) {
5713 return false;
5714 }
5715 return header.long_packet_type == VERSION_NEGOTIATION;
5716}
5717
QUICHE teama6ef0a62019-03-07 20:34:33 -05005718bool QuicFramer::AppendIetfConnectionCloseFrame(
5719 const QuicConnectionCloseFrame& frame,
5720 QuicDataWriter* writer) {
fkastenholz72f509b2019-04-10 09:17:49 -07005721 if (frame.close_type != IETF_QUIC_TRANSPORT_CONNECTION_CLOSE &&
5722 frame.close_type != IETF_QUIC_APPLICATION_CONNECTION_CLOSE) {
5723 QUIC_BUG << "Invalid close_type for writing IETF CONNECTION CLOSE.";
5724 set_detailed_error("Invalid close_type for writing IETF CONNECTION CLOSE.");
5725 return false;
5726 }
5727
fkastenholz88d08f42019-09-06 07:38:04 -07005728 if (!writer->WriteVarInt62(
5729 (frame.close_type == IETF_QUIC_TRANSPORT_CONNECTION_CLOSE)
5730 ? frame.transport_error_code
5731 : frame.application_error_code)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005732 set_detailed_error("Can not write connection close frame error code");
5733 return false;
5734 }
fkastenholze9d71a82019-04-09 05:12:13 -07005735
fkastenholz72f509b2019-04-10 09:17:49 -07005736 if (frame.close_type == IETF_QUIC_TRANSPORT_CONNECTION_CLOSE) {
5737 // Write the frame-type of the frame causing the error only
5738 // if it's a CONNECTION_CLOSE/Transport.
5739 if (!writer->WriteVarInt62(frame.transport_close_frame_type)) {
5740 set_detailed_error("Writing frame type failed.");
5741 return false;
5742 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05005743 }
5744
fkastenholzb4dade72019-08-05 06:54:20 -07005745 // There may be additional error information available in the extracted error
5746 // code. Encode the error information in the reason phrase and serialize the
5747 // result.
5748 std::string final_error_string =
5749 GenerateErrorString(frame.error_details, frame.extracted_error_code);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005750 if (!writer->WriteStringPieceVarInt62(
fkastenholzb4dade72019-08-05 06:54:20 -07005751 TruncateErrorString(final_error_string))) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005752 set_detailed_error("Can not write connection close phrase");
5753 return false;
5754 }
5755 return true;
5756}
5757
QUICHE teama6ef0a62019-03-07 20:34:33 -05005758bool QuicFramer::ProcessIetfConnectionCloseFrame(
5759 QuicDataReader* reader,
fkastenholze9d71a82019-04-09 05:12:13 -07005760 QuicConnectionCloseType type,
QUICHE teama6ef0a62019-03-07 20:34:33 -05005761 QuicConnectionCloseFrame* frame) {
fkastenholze9d71a82019-04-09 05:12:13 -07005762 frame->close_type = type;
fkastenholzb4dade72019-08-05 06:54:20 -07005763
fkastenholz88d08f42019-09-06 07:38:04 -07005764 uint64_t error_code;
fkastenholzd57d3f92019-07-16 09:05:17 -07005765 if (!reader->ReadVarInt62(&error_code)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005766 set_detailed_error("Unable to read connection close error code.");
5767 return false;
5768 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05005769
fkastenholzd57d3f92019-07-16 09:05:17 -07005770 if (frame->close_type == IETF_QUIC_TRANSPORT_CONNECTION_CLOSE) {
fkastenholz88d08f42019-09-06 07:38:04 -07005771 frame->transport_error_code =
5772 static_cast<QuicIetfTransportErrorCodes>(error_code);
fkastenholzd57d3f92019-07-16 09:05:17 -07005773 } else if (frame->close_type == IETF_QUIC_APPLICATION_CONNECTION_CLOSE) {
fkastenholz88d08f42019-09-06 07:38:04 -07005774 frame->application_error_code = error_code;
fkastenholzd57d3f92019-07-16 09:05:17 -07005775 }
fkastenholzb4dade72019-08-05 06:54:20 -07005776
fkastenholz72f509b2019-04-10 09:17:49 -07005777 if (type == IETF_QUIC_TRANSPORT_CONNECTION_CLOSE) {
5778 // The frame-type of the frame causing the error is present only
5779 // if it's a CONNECTION_CLOSE/Transport.
5780 if (!reader->ReadVarInt62(&frame->transport_close_frame_type)) {
5781 set_detailed_error("Unable to read connection close frame type.");
5782 return false;
5783 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05005784 }
5785
5786 uint64_t phrase_length;
5787 if (!reader->ReadVarInt62(&phrase_length)) {
5788 set_detailed_error("Unable to read connection close error details.");
5789 return false;
5790 }
fkastenholzb4dade72019-08-05 06:54:20 -07005791
QUICHE teama6ef0a62019-03-07 20:34:33 -05005792 QuicStringPiece phrase;
5793 if (!reader->ReadStringPiece(&phrase, static_cast<size_t>(phrase_length))) {
5794 set_detailed_error("Unable to read connection close error details.");
5795 return false;
5796 }
vasilvvc48c8712019-03-11 13:38:16 -07005797 frame->error_details = std::string(phrase);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005798
fkastenholzb4dade72019-08-05 06:54:20 -07005799 // The frame may have an extracted error code in it. Look for it and
5800 // extract it. If it's not present, MaybeExtract will return
5801 // QUIC_IETF_GQUIC_ERROR_MISSING.
fkastenholz488a4622019-08-26 06:24:46 -07005802 MaybeExtractQuicErrorCode(frame);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005803 return true;
5804}
5805
5806// IETF Quic Path Challenge/Response frames.
5807bool QuicFramer::ProcessPathChallengeFrame(QuicDataReader* reader,
5808 QuicPathChallengeFrame* frame) {
5809 if (!reader->ReadBytes(frame->data_buffer.data(),
5810 frame->data_buffer.size())) {
5811 set_detailed_error("Can not read path challenge data.");
5812 return false;
5813 }
5814 return true;
5815}
5816
5817bool QuicFramer::ProcessPathResponseFrame(QuicDataReader* reader,
5818 QuicPathResponseFrame* frame) {
5819 if (!reader->ReadBytes(frame->data_buffer.data(),
5820 frame->data_buffer.size())) {
5821 set_detailed_error("Can not read path response data.");
5822 return false;
5823 }
5824 return true;
5825}
5826
5827bool QuicFramer::AppendPathChallengeFrame(const QuicPathChallengeFrame& frame,
5828 QuicDataWriter* writer) {
5829 if (!writer->WriteBytes(frame.data_buffer.data(), frame.data_buffer.size())) {
5830 set_detailed_error("Writing Path Challenge data failed.");
5831 return false;
5832 }
5833 return true;
5834}
5835
5836bool QuicFramer::AppendPathResponseFrame(const QuicPathResponseFrame& frame,
5837 QuicDataWriter* writer) {
5838 if (!writer->WriteBytes(frame.data_buffer.data(), frame.data_buffer.size())) {
5839 set_detailed_error("Writing Path Response data failed.");
5840 return false;
5841 }
5842 return true;
5843}
5844
5845// Add a new ietf-format stream reset frame.
5846// General format is
5847// stream id
5848// application error code
5849// final offset
5850bool QuicFramer::AppendIetfResetStreamFrame(const QuicRstStreamFrame& frame,
5851 QuicDataWriter* writer) {
5852 if (!writer->WriteVarInt62(static_cast<uint64_t>(frame.stream_id))) {
5853 set_detailed_error("Writing reset-stream stream id failed.");
5854 return false;
5855 }
fkastenholz07300e52019-07-16 11:51:37 -07005856 if (!writer->WriteVarInt62(static_cast<uint64_t>(frame.ietf_error_code))) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005857 set_detailed_error("Writing reset-stream error code failed.");
5858 return false;
5859 }
5860 if (!writer->WriteVarInt62(static_cast<uint64_t>(frame.byte_offset))) {
5861 set_detailed_error("Writing reset-stream final-offset failed.");
5862 return false;
5863 }
5864 return true;
5865}
5866
5867bool QuicFramer::ProcessIetfResetStreamFrame(QuicDataReader* reader,
5868 QuicRstStreamFrame* frame) {
5869 // Get Stream ID from frame. ReadVarIntStreamID returns false
5870 // if either A) there is a read error or B) the resulting value of
5871 // the Stream ID is larger than the maximum allowed value.
fkastenholz3c4eabf2019-04-22 07:49:59 -07005872 if (!reader->ReadVarIntU32(&frame->stream_id)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005873 set_detailed_error("Unable to read rst stream stream id.");
5874 return false;
5875 }
5876
fkastenholz07300e52019-07-16 11:51:37 -07005877 uint64_t error_code;
5878 if (!reader->ReadVarInt62(&error_code)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005879 set_detailed_error("Unable to read rst stream error code.");
5880 return false;
5881 }
fkastenholz07300e52019-07-16 11:51:37 -07005882 if (error_code > 0xffff) {
5883 frame->ietf_error_code = 0xffff;
5884 QUIC_DLOG(ERROR) << "Reset stream error code (" << error_code
5885 << ") > 0xffff";
5886 } else {
5887 frame->ietf_error_code = static_cast<uint16_t>(error_code);
5888 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05005889
5890 if (!reader->ReadVarInt62(&frame->byte_offset)) {
5891 set_detailed_error("Unable to read rst stream sent byte offset.");
5892 return false;
5893 }
5894 return true;
5895}
5896
5897bool QuicFramer::ProcessStopSendingFrame(
5898 QuicDataReader* reader,
5899 QuicStopSendingFrame* stop_sending_frame) {
fkastenholz3c4eabf2019-04-22 07:49:59 -07005900 if (!reader->ReadVarIntU32(&stop_sending_frame->stream_id)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005901 set_detailed_error("Unable to read stop sending stream id.");
5902 return false;
5903 }
5904
fkastenholz733552e2019-07-16 11:16:58 -07005905 uint64_t error_code;
5906 if (!reader->ReadVarInt62(&error_code)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005907 set_detailed_error("Unable to read stop sending application error code.");
5908 return false;
5909 }
fkastenholz733552e2019-07-16 11:16:58 -07005910 // TODO(fkastenholz): when error codes go to uint64_t, remove this.
5911 if (error_code > 0xffff) {
5912 stop_sending_frame->application_error_code = 0xffff;
5913 QUIC_DLOG(ERROR) << "Stop sending error code (" << error_code
5914 << ") > 0xffff";
5915 } else {
5916 stop_sending_frame->application_error_code =
5917 static_cast<uint16_t>(error_code);
5918 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05005919 return true;
5920}
5921
5922bool QuicFramer::AppendStopSendingFrame(
5923 const QuicStopSendingFrame& stop_sending_frame,
5924 QuicDataWriter* writer) {
5925 if (!writer->WriteVarInt62(stop_sending_frame.stream_id)) {
5926 set_detailed_error("Can not write stop sending stream id");
5927 return false;
5928 }
fkastenholz733552e2019-07-16 11:16:58 -07005929 if (!writer->WriteVarInt62(
5930 static_cast<uint64_t>(stop_sending_frame.application_error_code))) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005931 set_detailed_error("Can not write application error code");
5932 return false;
5933 }
5934 return true;
5935}
5936
5937// Append/process IETF-Format MAX_DATA Frame
5938bool QuicFramer::AppendMaxDataFrame(const QuicWindowUpdateFrame& frame,
5939 QuicDataWriter* writer) {
5940 if (!writer->WriteVarInt62(frame.byte_offset)) {
5941 set_detailed_error("Can not write MAX_DATA byte-offset");
5942 return false;
5943 }
5944 return true;
5945}
5946
5947bool QuicFramer::ProcessMaxDataFrame(QuicDataReader* reader,
5948 QuicWindowUpdateFrame* frame) {
5949 frame->stream_id = QuicUtils::GetInvalidStreamId(transport_version());
5950 if (!reader->ReadVarInt62(&frame->byte_offset)) {
5951 set_detailed_error("Can not read MAX_DATA byte-offset");
5952 return false;
5953 }
5954 return true;
5955}
5956
5957// Append/process IETF-Format MAX_STREAM_DATA Frame
5958bool QuicFramer::AppendMaxStreamDataFrame(const QuicWindowUpdateFrame& frame,
5959 QuicDataWriter* writer) {
5960 if (!writer->WriteVarInt62(frame.stream_id)) {
5961 set_detailed_error("Can not write MAX_STREAM_DATA stream id");
5962 return false;
5963 }
5964 if (!writer->WriteVarInt62(frame.byte_offset)) {
5965 set_detailed_error("Can not write MAX_STREAM_DATA byte-offset");
5966 return false;
5967 }
5968 return true;
5969}
5970
5971bool QuicFramer::ProcessMaxStreamDataFrame(QuicDataReader* reader,
5972 QuicWindowUpdateFrame* frame) {
fkastenholz3c4eabf2019-04-22 07:49:59 -07005973 if (!reader->ReadVarIntU32(&frame->stream_id)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005974 set_detailed_error("Can not read MAX_STREAM_DATA stream id");
5975 return false;
5976 }
5977 if (!reader->ReadVarInt62(&frame->byte_offset)) {
5978 set_detailed_error("Can not read MAX_STREAM_DATA byte-count");
5979 return false;
5980 }
5981 return true;
5982}
5983
fkastenholz3c4eabf2019-04-22 07:49:59 -07005984bool QuicFramer::AppendMaxStreamsFrame(const QuicMaxStreamsFrame& frame,
QUICHE teama6ef0a62019-03-07 20:34:33 -05005985 QuicDataWriter* writer) {
fkastenholz3c4eabf2019-04-22 07:49:59 -07005986 if (!writer->WriteVarInt62(frame.stream_count)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005987 set_detailed_error("Can not write MAX_STREAMS stream count");
5988 return false;
5989 }
5990 return true;
5991}
5992
5993bool QuicFramer::ProcessMaxStreamsFrame(QuicDataReader* reader,
fkastenholz3c4eabf2019-04-22 07:49:59 -07005994 QuicMaxStreamsFrame* frame,
QUICHE teama6ef0a62019-03-07 20:34:33 -05005995 uint64_t frame_type) {
fkastenholz3c4eabf2019-04-22 07:49:59 -07005996 if (!reader->ReadVarIntU32(&frame->stream_count)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005997 set_detailed_error("Can not read MAX_STREAMS stream count.");
5998 return false;
5999 }
fkastenholz3c4eabf2019-04-22 07:49:59 -07006000 frame->unidirectional = (frame_type == IETF_MAX_STREAMS_UNIDIRECTIONAL);
6001 return true;
QUICHE teama6ef0a62019-03-07 20:34:33 -05006002}
6003
6004bool QuicFramer::AppendIetfBlockedFrame(const QuicBlockedFrame& frame,
6005 QuicDataWriter* writer) {
6006 if (!writer->WriteVarInt62(frame.offset)) {
6007 set_detailed_error("Can not write blocked offset.");
6008 return false;
6009 }
6010 return true;
6011}
6012
6013bool QuicFramer::ProcessIetfBlockedFrame(QuicDataReader* reader,
6014 QuicBlockedFrame* frame) {
6015 // Indicates that it is a BLOCKED frame (as opposed to STREAM_BLOCKED).
6016 frame->stream_id = QuicUtils::GetInvalidStreamId(transport_version());
6017 if (!reader->ReadVarInt62(&frame->offset)) {
6018 set_detailed_error("Can not read blocked offset.");
6019 return false;
6020 }
6021 return true;
6022}
6023
6024bool QuicFramer::AppendStreamBlockedFrame(const QuicBlockedFrame& frame,
6025 QuicDataWriter* writer) {
6026 if (!writer->WriteVarInt62(frame.stream_id)) {
6027 set_detailed_error("Can not write stream blocked stream id.");
6028 return false;
6029 }
6030 if (!writer->WriteVarInt62(frame.offset)) {
6031 set_detailed_error("Can not write stream blocked offset.");
6032 return false;
6033 }
6034 return true;
6035}
6036
6037bool QuicFramer::ProcessStreamBlockedFrame(QuicDataReader* reader,
6038 QuicBlockedFrame* frame) {
fkastenholz3c4eabf2019-04-22 07:49:59 -07006039 if (!reader->ReadVarIntU32(&frame->stream_id)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05006040 set_detailed_error("Can not read stream blocked stream id.");
6041 return false;
6042 }
6043 if (!reader->ReadVarInt62(&frame->offset)) {
6044 set_detailed_error("Can not read stream blocked offset.");
6045 return false;
6046 }
6047 return true;
6048}
6049
fkastenholz3c4eabf2019-04-22 07:49:59 -07006050bool QuicFramer::AppendStreamsBlockedFrame(const QuicStreamsBlockedFrame& frame,
6051 QuicDataWriter* writer) {
6052 if (!writer->WriteVarInt62(frame.stream_count)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05006053 set_detailed_error("Can not write STREAMS_BLOCKED stream count");
6054 return false;
6055 }
6056 return true;
6057}
6058
6059bool QuicFramer::ProcessStreamsBlockedFrame(QuicDataReader* reader,
fkastenholz3c4eabf2019-04-22 07:49:59 -07006060 QuicStreamsBlockedFrame* frame,
QUICHE teama6ef0a62019-03-07 20:34:33 -05006061 uint64_t frame_type) {
fkastenholz3c4eabf2019-04-22 07:49:59 -07006062 if (!reader->ReadVarIntU32(&frame->stream_count)) {
6063 set_detailed_error("Can not read STREAMS_BLOCKED stream count.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05006064 return false;
6065 }
fkastenholz3c4eabf2019-04-22 07:49:59 -07006066 frame->unidirectional = (frame_type == IETF_STREAMS_BLOCKED_UNIDIRECTIONAL);
6067
QUICHE teama6ef0a62019-03-07 20:34:33 -05006068 // TODO(fkastenholz): handle properly when the STREAMS_BLOCKED
6069 // frame is implemented and passed up to the stream ID manager.
fkastenholz3c4eabf2019-04-22 07:49:59 -07006070 if (frame->stream_count >
6071 QuicUtils::GetMaxStreamCount(
6072 (frame_type == IETF_STREAMS_BLOCKED_UNIDIRECTIONAL),
6073 ((perspective_ == Perspective::IS_CLIENT)
6074 ? Perspective::IS_SERVER
6075 : Perspective::IS_CLIENT))) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05006076 // If stream count is such that the resulting stream ID would exceed our
6077 // implementation limit, generate an error.
6078 set_detailed_error(
6079 "STREAMS_BLOCKED stream count exceeds implementation limit.");
6080 return false;
6081 }
fkastenholz3c4eabf2019-04-22 07:49:59 -07006082 return true;
QUICHE teama6ef0a62019-03-07 20:34:33 -05006083}
6084
6085bool QuicFramer::AppendNewConnectionIdFrame(
6086 const QuicNewConnectionIdFrame& frame,
6087 QuicDataWriter* writer) {
6088 if (!writer->WriteVarInt62(frame.sequence_number)) {
6089 set_detailed_error("Can not write New Connection ID sequence number");
6090 return false;
6091 }
fkastenholz1c19fc22019-07-12 11:06:19 -07006092 if (!writer->WriteVarInt62(frame.retire_prior_to)) {
6093 set_detailed_error("Can not write New Connection ID retire_prior_to");
6094 return false;
6095 }
dschinazicf5b1e22019-07-17 18:35:17 -07006096 if (!writer->WriteLengthPrefixedConnectionId(frame.connection_id)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05006097 set_detailed_error("Can not write New Connection ID frame connection ID");
6098 return false;
6099 }
6100
6101 if (!writer->WriteBytes(
6102 static_cast<const void*>(&frame.stateless_reset_token),
6103 sizeof(frame.stateless_reset_token))) {
6104 set_detailed_error("Can not write New Connection ID Reset Token");
6105 return false;
6106 }
6107 return true;
6108}
6109
6110bool QuicFramer::ProcessNewConnectionIdFrame(QuicDataReader* reader,
6111 QuicNewConnectionIdFrame* frame) {
6112 if (!reader->ReadVarInt62(&frame->sequence_number)) {
6113 set_detailed_error(
6114 "Unable to read new connection ID frame sequence number.");
6115 return false;
6116 }
6117
fkastenholz1c19fc22019-07-12 11:06:19 -07006118 if (!reader->ReadVarInt62(&frame->retire_prior_to)) {
6119 set_detailed_error(
6120 "Unable to read new connection ID frame retire_prior_to.");
6121 return false;
6122 }
6123 if (frame->retire_prior_to > frame->sequence_number) {
6124 set_detailed_error("Retire_prior_to > sequence_number.");
6125 return false;
6126 }
dschinazicf5b1e22019-07-17 18:35:17 -07006127
6128 if (!reader->ReadLengthPrefixedConnectionId(&frame->connection_id)) {
6129 set_detailed_error("Unable to read new connection ID frame connection id.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05006130 return false;
6131 }
6132
dschinazicf5b1e22019-07-17 18:35:17 -07006133 if (!QuicUtils::IsConnectionIdValidForVersion(frame->connection_id,
6134 transport_version())) {
QUICHE team0131a5b2019-03-20 15:23:27 -07006135 set_detailed_error("Invalid new connection ID length for version.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05006136 return false;
6137 }
6138
QUICHE teama6ef0a62019-03-07 20:34:33 -05006139 if (!reader->ReadBytes(&frame->stateless_reset_token,
6140 sizeof(frame->stateless_reset_token))) {
6141 set_detailed_error("Can not read new connection ID frame reset token.");
6142 return false;
6143 }
6144 return true;
6145}
6146
6147bool QuicFramer::AppendRetireConnectionIdFrame(
6148 const QuicRetireConnectionIdFrame& frame,
6149 QuicDataWriter* writer) {
6150 if (!writer->WriteVarInt62(frame.sequence_number)) {
6151 set_detailed_error("Can not write Retire Connection ID sequence number");
6152 return false;
6153 }
6154 return true;
6155}
6156
6157bool QuicFramer::ProcessRetireConnectionIdFrame(
6158 QuicDataReader* reader,
6159 QuicRetireConnectionIdFrame* frame) {
6160 if (!reader->ReadVarInt62(&frame->sequence_number)) {
6161 set_detailed_error(
6162 "Unable to read retire connection ID frame sequence number.");
6163 return false;
6164 }
6165 return true;
6166}
6167
6168uint8_t QuicFramer::GetStreamFrameTypeByte(const QuicStreamFrame& frame,
6169 bool last_frame_in_packet) const {
fkastenholz305e1732019-06-18 05:01:22 -07006170 if (VersionHasIetfQuicFrames(version_.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05006171 return GetIetfStreamFrameTypeByte(frame, last_frame_in_packet);
6172 }
6173 uint8_t type_byte = 0;
6174 // Fin bit.
6175 type_byte |= frame.fin ? kQuicStreamFinMask : 0;
6176
6177 // Data Length bit.
6178 type_byte <<= kQuicStreamDataLengthShift;
6179 type_byte |= last_frame_in_packet ? 0 : kQuicStreamDataLengthMask;
6180
6181 // Offset 3 bits.
6182 type_byte <<= kQuicStreamShift;
6183 const size_t offset_len =
6184 GetStreamOffsetSize(version_.transport_version, frame.offset);
6185 if (offset_len > 0) {
6186 type_byte |= offset_len - 1;
6187 }
6188
6189 // stream id 2 bits.
6190 type_byte <<= kQuicStreamIdShift;
6191 type_byte |= GetStreamIdSize(frame.stream_id) - 1;
6192 type_byte |= kQuicFrameTypeStreamMask; // Set Stream Frame Type to 1.
6193
6194 return type_byte;
6195}
6196
6197uint8_t QuicFramer::GetIetfStreamFrameTypeByte(
6198 const QuicStreamFrame& frame,
6199 bool last_frame_in_packet) const {
fkastenholz305e1732019-06-18 05:01:22 -07006200 DCHECK(VersionHasIetfQuicFrames(version_.transport_version));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006201 uint8_t type_byte = IETF_STREAM;
6202 if (!last_frame_in_packet) {
6203 type_byte |= IETF_STREAM_FRAME_LEN_BIT;
6204 }
6205 if (frame.offset != 0) {
6206 type_byte |= IETF_STREAM_FRAME_OFF_BIT;
6207 }
6208 if (frame.fin) {
6209 type_byte |= IETF_STREAM_FRAME_FIN_BIT;
6210 }
6211 return type_byte;
6212}
6213
6214void QuicFramer::InferPacketHeaderTypeFromVersion() {
6215 // This function should only be called when server connection negotiates the
6216 // version.
6217 DCHECK(perspective_ == Perspective::IS_SERVER &&
6218 !infer_packet_header_type_from_version_);
6219 infer_packet_header_type_from_version_ = true;
6220}
6221
QUICHE team10b22a12019-03-21 15:31:42 -07006222void QuicFramer::EnableMultiplePacketNumberSpacesSupport() {
6223 if (supports_multiple_packet_number_spaces_) {
6224 QUIC_BUG << "Multiple packet number spaces has already been enabled";
6225 return;
6226 }
6227 if (largest_packet_number_.IsInitialized()) {
6228 QUIC_BUG << "Try to enable multiple packet number spaces support after any "
6229 "packet has been received.";
6230 return;
6231 }
6232
6233 supports_multiple_packet_number_spaces_ = true;
6234}
6235
fayangccbab732019-05-13 10:11:25 -07006236// static
6237QuicErrorCode QuicFramer::ProcessPacketDispatcher(
6238 const QuicEncryptedPacket& packet,
dschinazib42a8c52019-05-30 09:45:01 -07006239 uint8_t expected_destination_connection_id_length,
fayangccbab732019-05-13 10:11:25 -07006240 PacketHeaderFormat* format,
6241 bool* version_flag,
6242 QuicVersionLabel* version_label,
fayangccbab732019-05-13 10:11:25 -07006243 QuicConnectionId* destination_connection_id,
dschinazib42a8c52019-05-30 09:45:01 -07006244 QuicConnectionId* source_connection_id,
fayangccbab732019-05-13 10:11:25 -07006245 std::string* detailed_error) {
dschinazi48ac9192019-07-31 00:07:26 -07006246 DCHECK(!GetQuicReloadableFlag(quic_use_parse_public_header));
fayangccbab732019-05-13 10:11:25 -07006247 QuicDataReader reader(packet.data(), packet.length());
6248
dschinazib42a8c52019-05-30 09:45:01 -07006249 *source_connection_id = EmptyQuicConnectionId();
fayangccbab732019-05-13 10:11:25 -07006250 uint8_t first_byte;
6251 if (!reader.ReadBytes(&first_byte, 1)) {
6252 *detailed_error = "Unable to read first byte.";
6253 return QUIC_INVALID_PACKET_HEADER;
6254 }
dschinazib42a8c52019-05-30 09:45:01 -07006255 uint8_t destination_connection_id_length = 0, source_connection_id_length = 0;
fayangccbab732019-05-13 10:11:25 -07006256 if (!QuicUtils::IsIetfPacketHeader(first_byte)) {
6257 *format = GOOGLE_QUIC_PACKET;
6258 *version_flag = (first_byte & PACKET_PUBLIC_FLAGS_VERSION) != 0;
dschinazib42a8c52019-05-30 09:45:01 -07006259 destination_connection_id_length =
fayangccbab732019-05-13 10:11:25 -07006260 first_byte & PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID;
dschinazib42a8c52019-05-30 09:45:01 -07006261 if (destination_connection_id_length == 0 ||
fayangccbab732019-05-13 10:11:25 -07006262 !reader.ReadConnectionId(destination_connection_id,
dschinazib42a8c52019-05-30 09:45:01 -07006263 destination_connection_id_length)) {
fayangccbab732019-05-13 10:11:25 -07006264 *detailed_error = "Unable to read ConnectionId.";
6265 return QUIC_INVALID_PACKET_HEADER;
6266 }
6267 if (*version_flag && !ProcessVersionLabel(&reader, version_label)) {
6268 *detailed_error = "Unable to read protocol version.";
6269 return QUIC_INVALID_PACKET_HEADER;
6270 }
6271 return QUIC_NO_ERROR;
6272 }
6273
6274 *format = GetIetfPacketHeaderFormat(first_byte);
6275 QUIC_DVLOG(1) << "Dispatcher: Processing IETF QUIC packet, format: "
6276 << *format;
6277 *version_flag = *format == IETF_QUIC_LONG_HEADER_PACKET;
6278 if (*format == IETF_QUIC_LONG_HEADER_PACKET) {
6279 if (!ProcessVersionLabel(&reader, version_label)) {
6280 *detailed_error = "Unable to read protocol version.";
6281 return QUIC_INVALID_PACKET_HEADER;
6282 }
dschinazi8ff74822019-05-28 16:37:20 -07006283 // Set should_update_expected_server_connection_id_length to true to bypass
fayangccbab732019-05-13 10:11:25 -07006284 // connection ID lengths validation.
dschinazi8ff74822019-05-28 16:37:20 -07006285 uint8_t unused_expected_server_connection_id_length = 0;
fayangccbab732019-05-13 10:11:25 -07006286 if (!ProcessAndValidateIetfConnectionIdLength(
6287 &reader, ParseQuicVersionLabel(*version_label),
dschinazi334f0232019-05-29 16:08:53 -07006288 Perspective::IS_SERVER,
dschinazi8ff74822019-05-28 16:37:20 -07006289 /*should_update_expected_server_connection_id_length=*/true,
6290 &unused_expected_server_connection_id_length,
dschinazib42a8c52019-05-30 09:45:01 -07006291 &destination_connection_id_length, &source_connection_id_length,
6292 detailed_error)) {
fayangccbab732019-05-13 10:11:25 -07006293 return QUIC_INVALID_PACKET_HEADER;
6294 }
6295 } else {
dschinazib42a8c52019-05-30 09:45:01 -07006296 // For short header packets, expected_destination_connection_id_length
6297 // is used to determine the destination_connection_id_length.
6298 destination_connection_id_length =
6299 expected_destination_connection_id_length;
6300 DCHECK_EQ(0, source_connection_id_length);
fayangccbab732019-05-13 10:11:25 -07006301 }
6302 // Read destination connection ID.
6303 if (!reader.ReadConnectionId(destination_connection_id,
dschinazib42a8c52019-05-30 09:45:01 -07006304 destination_connection_id_length)) {
6305 *detailed_error = "Unable to read destination connection ID.";
6306 return QUIC_INVALID_PACKET_HEADER;
6307 }
6308 // Read source connection ID.
dschinazi5e1a7b22019-07-31 12:23:21 -07006309 if (!reader.ReadConnectionId(source_connection_id,
dschinazib42a8c52019-05-30 09:45:01 -07006310 source_connection_id_length)) {
6311 *detailed_error = "Unable to read source connection ID.";
fayangccbab732019-05-13 10:11:25 -07006312 return QUIC_INVALID_PACKET_HEADER;
6313 }
6314 return QUIC_NO_ERROR;
6315}
6316
dschinazide0f6dc2019-05-15 16:10:11 -07006317// static
dschinazi48ac9192019-07-31 00:07:26 -07006318QuicErrorCode QuicFramer::ParsePublicHeaderDispatcher(
6319 const QuicEncryptedPacket& packet,
6320 uint8_t expected_destination_connection_id_length,
6321 PacketHeaderFormat* format,
fayange3f2f7b2019-09-19 17:01:57 -07006322 QuicLongHeaderType* long_packet_type,
dschinazi48ac9192019-07-31 00:07:26 -07006323 bool* version_present,
6324 bool* has_length_prefix,
6325 QuicVersionLabel* version_label,
6326 ParsedQuicVersion* parsed_version,
6327 QuicConnectionId* destination_connection_id,
6328 QuicConnectionId* source_connection_id,
6329 bool* retry_token_present,
6330 QuicStringPiece* retry_token,
6331 std::string* detailed_error) {
6332 QuicDataReader reader(packet.data(), packet.length());
6333 if (reader.IsDoneReading()) {
6334 *detailed_error = "Unable to read first byte.";
6335 return QUIC_INVALID_PACKET_HEADER;
6336 }
6337 const uint8_t first_byte = reader.PeekByte();
6338 const bool ietf_format = QuicUtils::IsIetfPacketHeader(first_byte);
6339 uint8_t unused_first_byte;
6340 QuicVariableLengthIntegerLength retry_token_length_length;
fayange3f2f7b2019-09-19 17:01:57 -07006341 QuicErrorCode error_code = ParsePublicHeader(
dschinazi48ac9192019-07-31 00:07:26 -07006342 &reader, expected_destination_connection_id_length, ietf_format,
6343 &unused_first_byte, format, version_present, has_length_prefix,
6344 version_label, parsed_version, destination_connection_id,
fayange3f2f7b2019-09-19 17:01:57 -07006345 source_connection_id, long_packet_type, &retry_token_length_length,
dschinazi48ac9192019-07-31 00:07:26 -07006346 retry_token, detailed_error);
6347 *retry_token_present =
6348 retry_token_length_length != VARIABLE_LENGTH_INTEGER_LENGTH_0;
6349 return error_code;
6350}
6351
6352// static
6353QuicErrorCode QuicFramer::ParsePublicHeaderGoogleQuic(
6354 QuicDataReader* reader,
6355 uint8_t* first_byte,
6356 PacketHeaderFormat* format,
6357 bool* version_present,
6358 QuicVersionLabel* version_label,
dschinazi243eabc2019-08-05 16:15:29 -07006359 ParsedQuicVersion* parsed_version,
dschinazi48ac9192019-07-31 00:07:26 -07006360 QuicConnectionId* destination_connection_id,
6361 std::string* detailed_error) {
6362 *format = GOOGLE_QUIC_PACKET;
6363 *version_present = (*first_byte & PACKET_PUBLIC_FLAGS_VERSION) != 0;
6364 uint8_t destination_connection_id_length = 0;
6365 if ((*first_byte & PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID) != 0) {
6366 destination_connection_id_length = kQuicDefaultConnectionIdLength;
6367 }
6368 if (!reader->ReadConnectionId(destination_connection_id,
6369 destination_connection_id_length)) {
6370 *detailed_error = "Unable to read ConnectionId.";
6371 return QUIC_INVALID_PACKET_HEADER;
6372 }
dschinazi243eabc2019-08-05 16:15:29 -07006373 if (*version_present) {
6374 if (!ProcessVersionLabel(reader, version_label)) {
6375 *detailed_error = "Unable to read protocol version.";
6376 return QUIC_INVALID_PACKET_HEADER;
6377 }
6378 *parsed_version = ParseQuicVersionLabel(*version_label);
dschinazi48ac9192019-07-31 00:07:26 -07006379 }
6380 return QUIC_NO_ERROR;
6381}
6382
6383namespace {
6384
dschinazi81eb4e02019-09-27 17:12:17 -07006385const QuicVersionLabel kProxVersionLabel = 0x50524F58; // "PROX"
6386
dschinazi48ac9192019-07-31 00:07:26 -07006387inline bool PacketHasLengthPrefixedConnectionIds(
6388 const QuicDataReader& reader,
6389 ParsedQuicVersion parsed_version,
6390 QuicVersionLabel version_label,
6391 uint8_t first_byte) {
6392 if (parsed_version.transport_version != QUIC_VERSION_UNSUPPORTED) {
6393 return parsed_version.HasLengthPrefixedConnectionIds();
6394 }
6395
6396 // Received unsupported version, check known old unsupported versions.
6397 if (QuicVersionLabelUses4BitConnectionIdLength(version_label)) {
6398 return false;
6399 }
6400
6401 // Received unknown version, check connection ID length byte.
6402 if (reader.IsDoneReading()) {
6403 // This check is required to safely peek the connection ID length byte.
6404 return true;
6405 }
6406 const uint8_t connection_id_length_byte = reader.PeekByte();
6407
6408 // Check for packets produced by older versions of
6409 // QuicFramer::WriteClientVersionNegotiationProbePacket
6410 if (first_byte == 0xc0 && (connection_id_length_byte & 0x0f) == 0 &&
6411 connection_id_length_byte >= 0x50 && version_label == 0xcabadaba) {
6412 return false;
6413 }
6414
6415 // Check for munged packets with version tag PROX.
6416 if ((connection_id_length_byte & 0x0f) == 0 &&
dschinazi81eb4e02019-09-27 17:12:17 -07006417 connection_id_length_byte >= 0x20 && version_label == kProxVersionLabel) {
dschinazi48ac9192019-07-31 00:07:26 -07006418 return false;
6419 }
6420
6421 return true;
6422}
6423
6424inline bool ParseLongHeaderConnectionIds(
6425 QuicDataReader* reader,
6426 bool has_length_prefix,
dschinazi81eb4e02019-09-27 17:12:17 -07006427 QuicVersionLabel version_label,
dschinazi48ac9192019-07-31 00:07:26 -07006428 QuicConnectionId* destination_connection_id,
6429 QuicConnectionId* source_connection_id,
6430 std::string* detailed_error) {
6431 if (has_length_prefix) {
6432 if (!reader->ReadLengthPrefixedConnectionId(destination_connection_id)) {
6433 *detailed_error = "Unable to read destination connection ID.";
6434 return false;
6435 }
6436 if (!reader->ReadLengthPrefixedConnectionId(source_connection_id)) {
dschinazi81eb4e02019-09-27 17:12:17 -07006437 if (GetQuicReloadableFlag(quic_parse_prox_source_connection_id) &&
6438 version_label == kProxVersionLabel) {
6439 QUIC_RELOADABLE_FLAG_COUNT(quic_parse_prox_source_connection_id);
6440 // The "PROX" version does not follow the length-prefixed invariants,
6441 // and can therefore attempt to read a payload byte and interpret it
6442 // as the source connection ID length, which could fail to parse.
6443 // In that scenario we keep the source connection ID empty but mark
6444 // parsing as successful.
6445 return true;
6446 }
dschinazi48ac9192019-07-31 00:07:26 -07006447 *detailed_error = "Unable to read source connection ID.";
6448 return false;
6449 }
6450 } else {
6451 // Parse connection ID lengths.
6452 uint8_t connection_id_lengths_byte;
6453 if (!reader->ReadUInt8(&connection_id_lengths_byte)) {
6454 *detailed_error = "Unable to read connection ID lengths.";
6455 return false;
6456 }
6457 uint8_t destination_connection_id_length =
6458 (connection_id_lengths_byte & kDestinationConnectionIdLengthMask) >> 4;
6459 if (destination_connection_id_length != 0) {
6460 destination_connection_id_length += kConnectionIdLengthAdjustment;
6461 }
6462 uint8_t source_connection_id_length =
6463 connection_id_lengths_byte & kSourceConnectionIdLengthMask;
6464 if (source_connection_id_length != 0) {
6465 source_connection_id_length += kConnectionIdLengthAdjustment;
6466 }
6467
6468 // Read destination connection ID.
6469 if (!reader->ReadConnectionId(destination_connection_id,
6470 destination_connection_id_length)) {
6471 *detailed_error = "Unable to read destination connection ID.";
6472 return false;
6473 }
6474
6475 // Read source connection ID.
6476 if (!reader->ReadConnectionId(source_connection_id,
6477 source_connection_id_length)) {
6478 *detailed_error = "Unable to read source connection ID.";
6479 return false;
6480 }
6481 }
6482 return true;
6483}
6484
6485} // namespace
6486
6487// static
6488QuicErrorCode QuicFramer::ParsePublicHeader(
6489 QuicDataReader* reader,
6490 uint8_t expected_destination_connection_id_length,
6491 bool ietf_format,
6492 uint8_t* first_byte,
6493 PacketHeaderFormat* format,
6494 bool* version_present,
6495 bool* has_length_prefix,
6496 QuicVersionLabel* version_label,
6497 ParsedQuicVersion* parsed_version,
6498 QuicConnectionId* destination_connection_id,
6499 QuicConnectionId* source_connection_id,
6500 QuicLongHeaderType* long_packet_type,
6501 QuicVariableLengthIntegerLength* retry_token_length_length,
6502 QuicStringPiece* retry_token,
6503 std::string* detailed_error) {
6504 *version_present = false;
6505 *has_length_prefix = false;
6506 *version_label = 0;
6507 *parsed_version = UnsupportedQuicVersion();
6508 *source_connection_id = EmptyQuicConnectionId();
6509 *long_packet_type = INVALID_PACKET_TYPE;
6510 *retry_token_length_length = VARIABLE_LENGTH_INTEGER_LENGTH_0;
6511 *retry_token = QuicStringPiece();
6512 *detailed_error = "";
6513
6514 if (!reader->ReadUInt8(first_byte)) {
6515 *detailed_error = "Unable to read first byte.";
6516 return QUIC_INVALID_PACKET_HEADER;
6517 }
6518
6519 if (!ietf_format) {
6520 return ParsePublicHeaderGoogleQuic(
6521 reader, first_byte, format, version_present, version_label,
dschinazi243eabc2019-08-05 16:15:29 -07006522 parsed_version, destination_connection_id, detailed_error);
dschinazi48ac9192019-07-31 00:07:26 -07006523 }
6524
6525 *format = GetIetfPacketHeaderFormat(*first_byte);
6526
6527 if (*format == IETF_QUIC_SHORT_HEADER_PACKET) {
6528 // Read destination connection ID using
6529 // expected_destination_connection_id_length to determine its length.
6530 if (!reader->ReadConnectionId(destination_connection_id,
6531 expected_destination_connection_id_length)) {
6532 *detailed_error = "Unable to read destination connection ID.";
6533 return QUIC_INVALID_PACKET_HEADER;
6534 }
6535 return QUIC_NO_ERROR;
6536 }
6537
6538 DCHECK_EQ(IETF_QUIC_LONG_HEADER_PACKET, *format);
6539 *version_present = true;
6540 if (!ProcessVersionLabel(reader, version_label)) {
6541 *detailed_error = "Unable to read protocol version.";
6542 return QUIC_INVALID_PACKET_HEADER;
6543 }
6544
6545 if (*version_label == 0) {
6546 *long_packet_type = VERSION_NEGOTIATION;
6547 }
6548
6549 // Parse version.
6550 *parsed_version = ParseQuicVersionLabel(*version_label);
6551
6552 // Figure out which IETF QUIC invariants this packet follows.
6553 *has_length_prefix = PacketHasLengthPrefixedConnectionIds(
6554 *reader, *parsed_version, *version_label, *first_byte);
6555
6556 // Parse connection IDs.
dschinazi81eb4e02019-09-27 17:12:17 -07006557 if (!ParseLongHeaderConnectionIds(reader, *has_length_prefix, *version_label,
dschinazi48ac9192019-07-31 00:07:26 -07006558 destination_connection_id,
6559 source_connection_id, detailed_error)) {
6560 return QUIC_INVALID_PACKET_HEADER;
6561 }
6562
6563 if (parsed_version->transport_version == QUIC_VERSION_UNSUPPORTED) {
6564 // Skip parsing of long packet type and retry token for unknown versions.
6565 return QUIC_NO_ERROR;
6566 }
6567
6568 // Parse long packet type.
fayang36825da2019-08-21 14:01:27 -07006569 if (!GetLongHeaderType(*first_byte, long_packet_type)) {
dschinazi48ac9192019-07-31 00:07:26 -07006570 *detailed_error = "Unable to parse long packet type.";
6571 return QUIC_INVALID_PACKET_HEADER;
6572 }
6573
6574 if (!parsed_version->SupportsRetry() || *long_packet_type != INITIAL) {
6575 // Retry token is only present on initial packets for some versions.
6576 return QUIC_NO_ERROR;
6577 }
6578
6579 *retry_token_length_length = reader->PeekVarInt62Length();
6580 uint64_t retry_token_length;
6581 if (!reader->ReadVarInt62(&retry_token_length)) {
6582 *retry_token_length_length = VARIABLE_LENGTH_INTEGER_LENGTH_0;
6583 *detailed_error = "Unable to read retry token length.";
6584 return QUIC_INVALID_PACKET_HEADER;
6585 }
6586
6587 if (!reader->ReadStringPiece(retry_token, retry_token_length)) {
6588 *detailed_error = "Unable to read retry token.";
6589 return QUIC_INVALID_PACKET_HEADER;
6590 }
6591
6592 return QUIC_NO_ERROR;
6593}
6594
6595// static
dschinazide0f6dc2019-05-15 16:10:11 -07006596bool QuicFramer::WriteClientVersionNegotiationProbePacket(
6597 char* packet_bytes,
6598 QuicByteCount packet_length,
6599 const char* destination_connection_id_bytes,
6600 uint8_t destination_connection_id_length) {
6601 if (packet_bytes == nullptr) {
6602 QUIC_BUG << "Invalid packet_bytes";
6603 return false;
6604 }
6605 if (packet_length < kMinPacketSizeForVersionNegotiation ||
6606 packet_length > 65535) {
6607 QUIC_BUG << "Invalid packet_length";
6608 return false;
6609 }
dschinazib012d212019-08-01 18:07:26 -07006610 if (destination_connection_id_length > kQuicMaxConnectionId4BitLength ||
dschinazi19dc2b52019-07-17 19:54:43 -07006611 destination_connection_id_length <
6612 kQuicMinimumInitialConnectionIdLength) {
dschinazide0f6dc2019-05-15 16:10:11 -07006613 QUIC_BUG << "Invalid connection_id_length";
6614 return false;
6615 }
dschinazi48ac9192019-07-31 00:07:26 -07006616 const bool use_length_prefix =
6617 GetQuicFlag(FLAGS_quic_prober_uses_length_prefixed_connection_ids);
6618 const uint8_t last_version_byte = use_length_prefix ? 0xda : 0xba;
dschinazide0f6dc2019-05-15 16:10:11 -07006619 // clang-format off
dschinazi48ac9192019-07-31 00:07:26 -07006620 const unsigned char packet_start_bytes[] = {
dschinazide0f6dc2019-05-15 16:10:11 -07006621 // IETF long header with fixed bit set, type initial, all-0 encrypted bits.
6622 0xc0,
6623 // Version, part of the IETF space reserved for negotiation.
6624 // This intentionally differs from QuicVersionReservedForNegotiation()
6625 // to allow differentiating them over the wire.
dschinazi48ac9192019-07-31 00:07:26 -07006626 0xca, 0xba, 0xda, last_version_byte,
dschinazide0f6dc2019-05-15 16:10:11 -07006627 };
6628 // clang-format on
6629 static_assert(sizeof(packet_start_bytes) == 5, "bad packet_start_bytes size");
6630 QuicDataWriter writer(packet_length, packet_bytes);
6631 if (!writer.WriteBytes(packet_start_bytes, sizeof(packet_start_bytes))) {
6632 QUIC_BUG << "Failed to write packet start";
6633 return false;
6634 }
6635
6636 QuicConnectionId destination_connection_id(destination_connection_id_bytes,
6637 destination_connection_id_length);
dschinazi48ac9192019-07-31 00:07:26 -07006638 if (!AppendIetfConnectionIds(
6639 /*version_flag=*/true, use_length_prefix, destination_connection_id,
6640 EmptyQuicConnectionId(), &writer)) {
dschinazide0f6dc2019-05-15 16:10:11 -07006641 QUIC_BUG << "Failed to write connection IDs";
6642 return false;
6643 }
6644 // Add 8 bytes of zeroes followed by 8 bytes of ones to ensure that this does
6645 // not parse with any known version. The zeroes make sure that packet numbers,
6646 // retry token lengths and payload lengths are parsed as zero, and if the
6647 // zeroes are treated as padding frames, 0xff is known to not parse as a
6648 // valid frame type.
6649 if (!writer.WriteUInt64(0) ||
6650 !writer.WriteUInt64(std::numeric_limits<uint64_t>::max())) {
6651 QUIC_BUG << "Failed to write 18 bytes";
6652 return false;
6653 }
6654 // Make sure the polite greeting below is padded to a 16-byte boundary to
6655 // make it easier to read in tcpdump.
6656 while (writer.length() % 16 != 0) {
6657 if (!writer.WriteUInt8(0)) {
6658 QUIC_BUG << "Failed to write padding byte";
6659 return false;
6660 }
6661 }
6662 // Add a polite greeting in case a human sees this in tcpdump.
6663 static const char polite_greeting[] =
6664 "This packet only exists to trigger IETF QUIC version negotiation. "
6665 "Please respond with a Version Negotiation packet indicating what "
6666 "versions you support. Thank you and have a nice day.";
6667 if (!writer.WriteBytes(polite_greeting, sizeof(polite_greeting))) {
6668 QUIC_BUG << "Failed to write polite greeting";
6669 return false;
6670 }
6671 // Fill the rest of the packet with zeroes.
6672 writer.WritePadding();
6673 DCHECK_EQ(0u, writer.remaining());
6674 return true;
6675}
6676
6677// static
6678bool QuicFramer::ParseServerVersionNegotiationProbeResponse(
6679 const char* packet_bytes,
6680 QuicByteCount packet_length,
6681 char* source_connection_id_bytes,
6682 uint8_t* source_connection_id_length_out,
6683 std::string* detailed_error) {
6684 if (detailed_error == nullptr) {
6685 QUIC_BUG << "Invalid error_details";
6686 return false;
6687 }
6688 *detailed_error = "";
6689 if (packet_bytes == nullptr) {
6690 *detailed_error = "Invalid packet_bytes";
6691 return false;
6692 }
6693 if (packet_length < 6) {
6694 *detailed_error = "Invalid packet_length";
6695 return false;
6696 }
6697 if (source_connection_id_bytes == nullptr) {
6698 *detailed_error = "Invalid source_connection_id_bytes";
6699 return false;
6700 }
6701 if (source_connection_id_length_out == nullptr) {
6702 *detailed_error = "Invalid source_connection_id_length_out";
6703 return false;
6704 }
6705 QuicDataReader reader(packet_bytes, packet_length);
6706 uint8_t type_byte = 0;
6707 if (!reader.ReadUInt8(&type_byte)) {
6708 *detailed_error = "Failed to read type byte";
6709 return false;
6710 }
6711 if ((type_byte & 0x80) == 0) {
6712 *detailed_error = "Packet does not have long header";
6713 return false;
6714 }
6715 uint32_t version = 0;
6716 if (!reader.ReadUInt32(&version)) {
6717 *detailed_error = "Failed to read version";
6718 return false;
6719 }
6720 if (version != 0) {
6721 *detailed_error = "Packet is not a version negotiation packet";
6722 return false;
6723 }
dschinazi48ac9192019-07-31 00:07:26 -07006724 const bool use_length_prefix =
6725 GetQuicFlag(FLAGS_quic_prober_uses_length_prefixed_connection_ids);
dschinazide0f6dc2019-05-15 16:10:11 -07006726 QuicConnectionId destination_connection_id, source_connection_id;
dschinazi48ac9192019-07-31 00:07:26 -07006727 if (use_length_prefix) {
6728 if (!reader.ReadLengthPrefixedConnectionId(&destination_connection_id)) {
6729 *detailed_error = "Failed to read destination connection ID";
6730 return false;
6731 }
6732 if (!reader.ReadLengthPrefixedConnectionId(&source_connection_id)) {
6733 *detailed_error = "Failed to read source connection ID";
6734 return false;
6735 }
6736 } else {
6737 uint8_t expected_server_connection_id_length = 0,
6738 destination_connection_id_length = 0,
6739 source_connection_id_length = 0;
6740 if (!ProcessAndValidateIetfConnectionIdLength(
6741 &reader, UnsupportedQuicVersion(), Perspective::IS_CLIENT,
6742 /*should_update_expected_server_connection_id_length=*/true,
6743 &expected_server_connection_id_length,
6744 &destination_connection_id_length, &source_connection_id_length,
6745 detailed_error)) {
6746 return false;
6747 }
6748 if (!reader.ReadConnectionId(&destination_connection_id,
6749 destination_connection_id_length)) {
6750 *detailed_error = "Failed to read destination connection ID";
6751 return false;
6752 }
6753 if (!reader.ReadConnectionId(&source_connection_id,
6754 source_connection_id_length)) {
6755 *detailed_error = "Failed to read source connection ID";
6756 return false;
6757 }
dschinazide0f6dc2019-05-15 16:10:11 -07006758 }
dschinazi48ac9192019-07-31 00:07:26 -07006759
6760 if (destination_connection_id.length() != 0) {
6761 *detailed_error = "Received unexpected destination connection ID length";
dschinazide0f6dc2019-05-15 16:10:11 -07006762 return false;
6763 }
6764
dschinaziccbe0e02019-08-13 12:15:00 -07006765 if (!use_length_prefix && source_connection_id.length() == 0) {
6766 // We received a bad response due to b/139330014.
6767 // Reparse the packet assuming length prefixes.
6768 // This is a temporary client-side workaround until cl/263172621 is
6769 // deployed on production servers.
6770 // TODO(dschinazi): remove this client-side workaround once the server-side
6771 // fix is deployed.
6772 QuicDataReader reader2(packet_bytes, packet_length);
6773 uint8_t type_byte2 = 0;
6774 uint32_t version2 = 0;
6775 QuicConnectionId destination_connection_id2, source_connection_id2;
6776 if (reader2.ReadUInt8(&type_byte2) && reader2.ReadUInt32(&version2) &&
6777 reader2.ReadLengthPrefixedConnectionId(&destination_connection_id2) &&
6778 reader2.ReadLengthPrefixedConnectionId(&source_connection_id2) &&
6779 (type_byte2 & 0x80) != 0 && version2 == 0 &&
6780 destination_connection_id2.length() == 0 &&
6781 source_connection_id2.length() != 0) {
6782 source_connection_id = source_connection_id2;
6783 }
6784 }
6785
dschinazide0f6dc2019-05-15 16:10:11 -07006786 memcpy(source_connection_id_bytes, source_connection_id.data(),
dschinazi48ac9192019-07-31 00:07:26 -07006787 source_connection_id.length());
6788 *source_connection_id_length_out = source_connection_id.length();
dschinazide0f6dc2019-05-15 16:10:11 -07006789
6790 return true;
6791}
6792
fkastenholzb4dade72019-08-05 06:54:20 -07006793// Look for and parse the error code from the "<quic_error_code>:" text that
6794// may be present at the start of the CONNECTION_CLOSE error details string.
6795// This text, inserted by the peer if it's using Google's QUIC implementation,
6796// contains additional error information that narrows down the exact error. If
6797// the string is not found, or is not properly formed, it returns
6798// ErrorCode::QUIC_IETF_GQUIC_ERROR_MISSING
fkastenholz488a4622019-08-26 06:24:46 -07006799void MaybeExtractQuicErrorCode(QuicConnectionCloseFrame* frame) {
6800 std::vector<QuicStringPiece> ed =
6801 QuicTextUtils::Split(frame->error_details, ':');
fkastenholzb4dade72019-08-05 06:54:20 -07006802 uint64_t extracted_error_code;
6803 if (ed.size() < 2 || !QuicTextUtils::IsAllDigits(ed[0]) ||
6804 !QuicTextUtils::StringToUint64(ed[0], &extracted_error_code)) {
fkastenholz488a4622019-08-26 06:24:46 -07006805 frame->extracted_error_code = QUIC_IETF_GQUIC_ERROR_MISSING;
6806 return;
fkastenholzb4dade72019-08-05 06:54:20 -07006807 }
fkastenholz488a4622019-08-26 06:24:46 -07006808 // Return the error code (numeric) and the error details string without the
6809 // error code prefix. Note that Split returns everything up to, but not
6810 // including, the split character, so the length of ed[0] is just the number
6811 // of digits in the error number. In removing the prefix, 1 is added to the
6812 // length to account for the :
6813 QuicStringPiece x = QuicStringPiece(frame->error_details);
6814 x.remove_prefix(ed[0].length() + 1);
6815 frame->error_details = std::string(x);
6816 frame->extracted_error_code =
6817 static_cast<QuicErrorCode>(extracted_error_code);
fkastenholzb4dade72019-08-05 06:54:20 -07006818}
6819
QUICHE teama6ef0a62019-03-07 20:34:33 -05006820#undef ENDPOINT // undef for jumbo builds
6821} // namespace quic