blob: c667e9b5411c2699e2966d42a665916759cb95c3 [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),
fkastenholz4dc4ba32019-07-30 09:55:25 -0700427 last_written_packet_number_length_(0),
428 peer_ack_delay_exponent_(kDefaultAckDelayExponent),
429 local_ack_delay_exponent_(kDefaultAckDelayExponent) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500430 DCHECK(!supported_versions.empty());
431 version_ = supported_versions_[0];
QUICHE team76086e42019-03-25 15:12:29 -0700432 decrypter_[ENCRYPTION_INITIAL] = QuicMakeUnique<NullDecrypter>(perspective);
QUICHE team6987b4a2019-03-15 16:23:04 -0700433 encrypter_[ENCRYPTION_INITIAL] = QuicMakeUnique<NullEncrypter>(perspective);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500434}
435
436QuicFramer::~QuicFramer() {}
437
438// static
439size_t QuicFramer::GetMinStreamFrameSize(QuicTransportVersion version,
440 QuicStreamId stream_id,
441 QuicStreamOffset offset,
442 bool last_frame_in_packet,
443 QuicPacketLength data_length) {
fkastenholz305e1732019-06-18 05:01:22 -0700444 if (VersionHasIetfQuicFrames(version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500445 return kQuicFrameTypeSize + QuicDataWriter::GetVarInt62Len(stream_id) +
446 (last_frame_in_packet
447 ? 0
448 : QuicDataWriter::GetVarInt62Len(data_length)) +
449 (offset != 0 ? QuicDataWriter::GetVarInt62Len(offset) : 0);
450 }
451 return kQuicFrameTypeSize + GetStreamIdSize(stream_id) +
452 GetStreamOffsetSize(version, offset) +
453 (last_frame_in_packet ? 0 : kQuicStreamPayloadLengthSize);
454}
455
456// static
457size_t QuicFramer::GetMinCryptoFrameSize(QuicStreamOffset offset,
458 QuicPacketLength data_length) {
459 return kQuicFrameTypeSize + QuicDataWriter::GetVarInt62Len(offset) +
460 QuicDataWriter::GetVarInt62Len(data_length);
461}
462
463// static
464size_t QuicFramer::GetMessageFrameSize(QuicTransportVersion version,
465 bool last_frame_in_packet,
466 QuicByteCount length) {
fayangd4291e42019-05-30 10:31:21 -0700467 QUIC_BUG_IF(!VersionSupportsMessageFrames(version))
QUICHE teama6ef0a62019-03-07 20:34:33 -0500468 << "Try to serialize MESSAGE frame in " << version;
469 return kQuicFrameTypeSize +
470 (last_frame_in_packet ? 0 : QuicDataWriter::GetVarInt62Len(length)) +
471 length;
472}
473
474// static
475size_t QuicFramer::GetMinAckFrameSize(
476 QuicTransportVersion version,
477 QuicPacketNumberLength largest_observed_length) {
fkastenholz305e1732019-06-18 05:01:22 -0700478 if (VersionHasIetfQuicFrames(version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500479 // The minimal ack frame consists of the following four fields: Largest
480 // Acknowledged, ACK Delay, ACK Block Count, and First ACK Block. Minimum
481 // size of each is 1 byte.
482 return kQuicFrameTypeSize + 4;
483 }
484 size_t min_size = kQuicFrameTypeSize + largest_observed_length +
485 kQuicDeltaTimeLargestObservedSize;
486 return min_size + kQuicNumTimestampsSize;
487}
488
489// static
490size_t QuicFramer::GetStopWaitingFrameSize(
dschinazi17d42422019-06-18 16:35:07 -0700491 QuicTransportVersion /*version*/,
QUICHE teama6ef0a62019-03-07 20:34:33 -0500492 QuicPacketNumberLength packet_number_length) {
493 size_t min_size = kQuicFrameTypeSize + packet_number_length;
494 return min_size;
495}
496
497// static
498size_t QuicFramer::GetRstStreamFrameSize(QuicTransportVersion version,
499 const QuicRstStreamFrame& frame) {
fkastenholz305e1732019-06-18 05:01:22 -0700500 if (VersionHasIetfQuicFrames(version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500501 return QuicDataWriter::GetVarInt62Len(frame.stream_id) +
502 QuicDataWriter::GetVarInt62Len(frame.byte_offset) +
fkastenholz07300e52019-07-16 11:51:37 -0700503 kQuicFrameTypeSize +
504 QuicDataWriter::GetVarInt62Len(frame.ietf_error_code);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500505 }
506 return kQuicFrameTypeSize + kQuicMaxStreamIdSize + kQuicMaxStreamOffsetSize +
507 kQuicErrorCodeSize;
508}
509
510// static
fkastenholza037b8b2019-05-07 06:00:05 -0700511size_t QuicFramer::GetConnectionCloseFrameSize(
QUICHE teama6ef0a62019-03-07 20:34:33 -0500512 QuicTransportVersion version,
513 const QuicConnectionCloseFrame& frame) {
fkastenholz305e1732019-06-18 05:01:22 -0700514 if (!VersionHasIetfQuicFrames(version)) {
515 // Not IETF QUIC, return Google QUIC CONNECTION CLOSE frame size.
fkastenholza037b8b2019-05-07 06:00:05 -0700516 return kQuicFrameTypeSize + kQuicErrorCodeSize +
517 kQuicErrorDetailsLengthSize +
518 TruncatedErrorStringSize(frame.error_details);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500519 }
fkastenholzb4dade72019-08-05 06:54:20 -0700520
521 // Prepend the extra error information to the string and get the result's
522 // length.
523 const size_t truncated_error_string_size = TruncatedErrorStringSize(
524 GenerateErrorString(frame.error_details, frame.extracted_error_code));
525
fkastenholzd57d3f92019-07-16 09:05:17 -0700526 uint64_t close_code = 0;
527 if (frame.close_type == IETF_QUIC_TRANSPORT_CONNECTION_CLOSE) {
528 close_code = static_cast<uint64_t>(frame.transport_error_code);
529 } else if (frame.close_type == IETF_QUIC_APPLICATION_CONNECTION_CLOSE) {
530 close_code = static_cast<uint64_t>(frame.application_error_code);
531 }
fkastenholzb4dade72019-08-05 06:54:20 -0700532
fkastenholza037b8b2019-05-07 06:00:05 -0700533 const size_t frame_size =
534 truncated_error_string_size +
535 QuicDataWriter::GetVarInt62Len(truncated_error_string_size) +
fkastenholzd57d3f92019-07-16 09:05:17 -0700536 kQuicFrameTypeSize + QuicDataWriter::GetVarInt62Len(close_code);
fkastenholza037b8b2019-05-07 06:00:05 -0700537 if (frame.close_type == IETF_QUIC_APPLICATION_CONNECTION_CLOSE) {
538 return frame_size;
539 }
fkastenholzb4dade72019-08-05 06:54:20 -0700540 // The Transport close frame has the transport_close_frame_type, so include
541 // its length.
fkastenholza037b8b2019-05-07 06:00:05 -0700542 return frame_size +
543 QuicDataWriter::GetVarInt62Len(frame.transport_close_frame_type);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500544}
545
546// static
QUICHE teama6ef0a62019-03-07 20:34:33 -0500547size_t QuicFramer::GetMinGoAwayFrameSize() {
548 return kQuicFrameTypeSize + kQuicErrorCodeSize + kQuicErrorDetailsLengthSize +
549 kQuicMaxStreamIdSize;
550}
551
552// static
553size_t QuicFramer::GetWindowUpdateFrameSize(
554 QuicTransportVersion version,
555 const QuicWindowUpdateFrame& frame) {
fkastenholz305e1732019-06-18 05:01:22 -0700556 if (!VersionHasIetfQuicFrames(version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500557 return kQuicFrameTypeSize + kQuicMaxStreamIdSize + kQuicMaxStreamOffsetSize;
558 }
559 if (frame.stream_id == QuicUtils::GetInvalidStreamId(version)) {
560 // Frame would be a MAX DATA frame, which has only a Maximum Data field.
561 return kQuicFrameTypeSize +
562 QuicDataWriter::GetVarInt62Len(frame.byte_offset);
563 }
564 // Frame would be MAX STREAM DATA, has Maximum Stream Data and Stream ID
565 // fields.
566 return kQuicFrameTypeSize +
567 QuicDataWriter::GetVarInt62Len(frame.byte_offset) +
568 QuicDataWriter::GetVarInt62Len(frame.stream_id);
569}
570
571// static
572size_t QuicFramer::GetMaxStreamsFrameSize(QuicTransportVersion version,
fkastenholz3c4eabf2019-04-22 07:49:59 -0700573 const QuicMaxStreamsFrame& frame) {
fkastenholz305e1732019-06-18 05:01:22 -0700574 if (!VersionHasIetfQuicFrames(version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500575 QUIC_BUG << "In version " << version
fkastenholz305e1732019-06-18 05:01:22 -0700576 << ", which does not support IETF Frames, and tried to serialize "
577 "MaxStreams Frame.";
QUICHE teama6ef0a62019-03-07 20:34:33 -0500578 }
fkastenholz3c4eabf2019-04-22 07:49:59 -0700579 return kQuicFrameTypeSize +
580 QuicDataWriter::GetVarInt62Len(frame.stream_count);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500581}
582
583// static
584size_t QuicFramer::GetStreamsBlockedFrameSize(
585 QuicTransportVersion version,
fkastenholz3c4eabf2019-04-22 07:49:59 -0700586 const QuicStreamsBlockedFrame& frame) {
fkastenholz305e1732019-06-18 05:01:22 -0700587 if (!VersionHasIetfQuicFrames(version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500588 QUIC_BUG << "In version " << version
fkastenholz305e1732019-06-18 05:01:22 -0700589 << ", which does not support IETF frames, and tried to serialize "
590 "StreamsBlocked Frame.";
QUICHE teama6ef0a62019-03-07 20:34:33 -0500591 }
592
fkastenholz3c4eabf2019-04-22 07:49:59 -0700593 return kQuicFrameTypeSize +
594 QuicDataWriter::GetVarInt62Len(frame.stream_count);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500595}
596
597// static
598size_t QuicFramer::GetBlockedFrameSize(QuicTransportVersion version,
599 const QuicBlockedFrame& frame) {
fkastenholz305e1732019-06-18 05:01:22 -0700600 if (!VersionHasIetfQuicFrames(version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500601 return kQuicFrameTypeSize + kQuicMaxStreamIdSize;
602 }
603 if (frame.stream_id == QuicUtils::GetInvalidStreamId(version)) {
604 // return size of IETF QUIC Blocked frame
605 return kQuicFrameTypeSize + QuicDataWriter::GetVarInt62Len(frame.offset);
606 }
607 // return size of IETF QUIC Stream Blocked frame.
608 return kQuicFrameTypeSize + QuicDataWriter::GetVarInt62Len(frame.offset) +
609 QuicDataWriter::GetVarInt62Len(frame.stream_id);
610}
611
612// static
613size_t QuicFramer::GetStopSendingFrameSize(const QuicStopSendingFrame& frame) {
614 return kQuicFrameTypeSize + QuicDataWriter::GetVarInt62Len(frame.stream_id) +
fkastenholz733552e2019-07-16 11:16:58 -0700615 QuicDataWriter::GetVarInt62Len(frame.application_error_code);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500616}
617
618// static
619size_t QuicFramer::GetPathChallengeFrameSize(
620 const QuicPathChallengeFrame& frame) {
621 return kQuicFrameTypeSize + sizeof(frame.data_buffer);
622}
623
624// static
625size_t QuicFramer::GetPathResponseFrameSize(
626 const QuicPathResponseFrame& frame) {
627 return kQuicFrameTypeSize + sizeof(frame.data_buffer);
628}
629
630// static
631size_t QuicFramer::GetRetransmittableControlFrameSize(
632 QuicTransportVersion version,
633 const QuicFrame& frame) {
634 switch (frame.type) {
635 case PING_FRAME:
636 // Ping has no payload.
637 return kQuicFrameTypeSize;
638 case RST_STREAM_FRAME:
639 return GetRstStreamFrameSize(version, *frame.rst_stream_frame);
640 case CONNECTION_CLOSE_FRAME:
fkastenholza037b8b2019-05-07 06:00:05 -0700641 return GetConnectionCloseFrameSize(version,
642 *frame.connection_close_frame);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500643 case GOAWAY_FRAME:
644 return GetMinGoAwayFrameSize() +
645 TruncatedErrorStringSize(frame.goaway_frame->reason_phrase);
646 case WINDOW_UPDATE_FRAME:
fkastenholz305e1732019-06-18 05:01:22 -0700647 // For IETF QUIC, this could be either a MAX DATA or MAX STREAM DATA.
QUICHE teama6ef0a62019-03-07 20:34:33 -0500648 // GetWindowUpdateFrameSize figures this out and returns the correct
649 // length.
650 return GetWindowUpdateFrameSize(version, *frame.window_update_frame);
651 case BLOCKED_FRAME:
652 return GetBlockedFrameSize(version, *frame.blocked_frame);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500653 case NEW_CONNECTION_ID_FRAME:
654 return GetNewConnectionIdFrameSize(*frame.new_connection_id_frame);
655 case RETIRE_CONNECTION_ID_FRAME:
656 return GetRetireConnectionIdFrameSize(*frame.retire_connection_id_frame);
657 case NEW_TOKEN_FRAME:
658 return GetNewTokenFrameSize(*frame.new_token_frame);
fkastenholz3c4eabf2019-04-22 07:49:59 -0700659 case MAX_STREAMS_FRAME:
660 return GetMaxStreamsFrameSize(version, frame.max_streams_frame);
661 case STREAMS_BLOCKED_FRAME:
662 return GetStreamsBlockedFrameSize(version, frame.streams_blocked_frame);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500663 case PATH_RESPONSE_FRAME:
664 return GetPathResponseFrameSize(*frame.path_response_frame);
665 case PATH_CHALLENGE_FRAME:
666 return GetPathChallengeFrameSize(*frame.path_challenge_frame);
667 case STOP_SENDING_FRAME:
668 return GetStopSendingFrameSize(*frame.stop_sending_frame);
669
670 case STREAM_FRAME:
671 case ACK_FRAME:
672 case STOP_WAITING_FRAME:
673 case MTU_DISCOVERY_FRAME:
674 case PADDING_FRAME:
675 case MESSAGE_FRAME:
676 case CRYPTO_FRAME:
677 case NUM_FRAME_TYPES:
678 DCHECK(false);
679 return 0;
680 }
681
682 // Not reachable, but some Chrome compilers can't figure that out. *sigh*
683 DCHECK(false);
684 return 0;
685}
686
687// static
688size_t QuicFramer::GetStreamIdSize(QuicStreamId stream_id) {
689 // Sizes are 1 through 4 bytes.
690 for (int i = 1; i <= 4; ++i) {
691 stream_id >>= 8;
692 if (stream_id == 0) {
693 return i;
694 }
695 }
696 QUIC_BUG << "Failed to determine StreamIDSize.";
697 return 4;
698}
699
700// static
dschinazi17d42422019-06-18 16:35:07 -0700701size_t QuicFramer::GetStreamOffsetSize(QuicTransportVersion /*version*/,
QUICHE teama6ef0a62019-03-07 20:34:33 -0500702 QuicStreamOffset offset) {
703 // 0 is a special case.
704 if (offset == 0) {
705 return 0;
706 }
707 // 2 through 8 are the remaining sizes.
708 offset >>= 8;
709 for (int i = 2; i <= 8; ++i) {
710 offset >>= 8;
711 if (offset == 0) {
712 return i;
713 }
714 }
715 QUIC_BUG << "Failed to determine StreamOffsetSize.";
716 return 8;
717}
718
719// static
720size_t QuicFramer::GetNewConnectionIdFrameSize(
721 const QuicNewConnectionIdFrame& frame) {
722 return kQuicFrameTypeSize +
723 QuicDataWriter::GetVarInt62Len(frame.sequence_number) +
fkastenholz1c19fc22019-07-12 11:06:19 -0700724 QuicDataWriter::GetVarInt62Len(frame.retire_prior_to) +
QUICHE teama6ef0a62019-03-07 20:34:33 -0500725 kConnectionIdLengthSize + frame.connection_id.length() +
726 sizeof(frame.stateless_reset_token);
727}
728
729// static
730size_t QuicFramer::GetRetireConnectionIdFrameSize(
731 const QuicRetireConnectionIdFrame& frame) {
732 return kQuicFrameTypeSize +
733 QuicDataWriter::GetVarInt62Len(frame.sequence_number);
734}
735
736// static
737size_t QuicFramer::GetNewTokenFrameSize(const QuicNewTokenFrame& frame) {
738 return kQuicFrameTypeSize +
739 QuicDataWriter::GetVarInt62Len(frame.token.length()) +
740 frame.token.length();
741}
742
743// TODO(nharper): Change this method to take a ParsedQuicVersion.
744bool QuicFramer::IsSupportedTransportVersion(
745 const QuicTransportVersion version) const {
746 for (ParsedQuicVersion supported_version : supported_versions_) {
747 if (version == supported_version.transport_version) {
748 return true;
749 }
750 }
751 return false;
752}
753
754bool QuicFramer::IsSupportedVersion(const ParsedQuicVersion version) const {
755 for (const ParsedQuicVersion& supported_version : supported_versions_) {
756 if (version == supported_version) {
757 return true;
758 }
759 }
760 return false;
761}
762
763size_t QuicFramer::GetSerializedFrameLength(
764 const QuicFrame& frame,
765 size_t free_bytes,
766 bool first_frame,
767 bool last_frame,
768 QuicPacketNumberLength packet_number_length) {
769 // Prevent a rare crash reported in b/19458523.
770 if (frame.type == ACK_FRAME && frame.ack_frame == nullptr) {
771 QUIC_BUG << "Cannot compute the length of a null ack frame. free_bytes:"
772 << free_bytes << " first_frame:" << first_frame
773 << " last_frame:" << last_frame
774 << " seq num length:" << packet_number_length;
775 set_error(QUIC_INTERNAL_ERROR);
776 visitor_->OnError(this);
777 return 0;
778 }
779 if (frame.type == PADDING_FRAME) {
780 if (frame.padding_frame.num_padding_bytes == -1) {
781 // Full padding to the end of the packet.
782 return free_bytes;
783 } else {
784 // Lite padding.
785 return free_bytes <
786 static_cast<size_t>(frame.padding_frame.num_padding_bytes)
787 ? free_bytes
788 : frame.padding_frame.num_padding_bytes;
789 }
790 }
791
792 size_t frame_len =
793 ComputeFrameLength(frame, last_frame, packet_number_length);
794 if (frame_len <= free_bytes) {
795 // Frame fits within packet. Note that acks may be truncated.
796 return frame_len;
797 }
798 // Only truncate the first frame in a packet, so if subsequent ones go
799 // over, stop including more frames.
800 if (!first_frame) {
801 return 0;
802 }
803 bool can_truncate =
804 frame.type == ACK_FRAME &&
805 free_bytes >= GetMinAckFrameSize(version_.transport_version,
806 PACKET_6BYTE_PACKET_NUMBER);
807 if (can_truncate) {
dschinazi66dea072019-04-09 11:41:06 -0700808 // Truncate the frame so the packet will not exceed kMaxOutgoingPacketSize.
QUICHE teama6ef0a62019-03-07 20:34:33 -0500809 // Note that we may not use every byte of the writer in this case.
810 QUIC_DLOG(INFO) << ENDPOINT
811 << "Truncating large frame, free bytes: " << free_bytes;
812 return free_bytes;
813 }
814 return 0;
815}
816
817QuicFramer::AckFrameInfo::AckFrameInfo()
818 : max_block_length(0), first_block_length(0), num_ack_blocks(0) {}
819
820QuicFramer::AckFrameInfo::AckFrameInfo(const AckFrameInfo& other) = default;
821
822QuicFramer::AckFrameInfo::~AckFrameInfo() {}
823
824bool QuicFramer::WriteIetfLongHeaderLength(const QuicPacketHeader& header,
825 QuicDataWriter* writer,
826 size_t length_field_offset,
827 EncryptionLevel level) {
828 if (!QuicVersionHasLongHeaderLengths(transport_version()) ||
829 !header.version_flag || length_field_offset == 0) {
830 return true;
831 }
832 if (writer->length() < length_field_offset ||
833 writer->length() - length_field_offset <
834 kQuicDefaultLongHeaderLengthLength) {
835 set_detailed_error("Invalid length_field_offset.");
836 QUIC_BUG << "Invalid length_field_offset.";
837 return false;
838 }
839 size_t length_to_write = writer->length() - length_field_offset -
840 kQuicDefaultLongHeaderLengthLength;
841 // Add length of auth tag.
842 length_to_write = GetCiphertextSize(level, length_to_write);
843
844 QuicDataWriter length_writer(writer->length() - length_field_offset,
845 writer->data() + length_field_offset);
846 if (!length_writer.WriteVarInt62(length_to_write,
847 kQuicDefaultLongHeaderLengthLength)) {
848 set_detailed_error("Failed to overwrite long header length.");
849 QUIC_BUG << "Failed to overwrite long header length.";
850 return false;
851 }
852 return true;
853}
854
855size_t QuicFramer::BuildDataPacket(const QuicPacketHeader& header,
856 const QuicFrames& frames,
857 char* buffer,
858 size_t packet_length,
859 EncryptionLevel level) {
860 QuicDataWriter writer(packet_length, buffer);
861 size_t length_field_offset = 0;
862 if (!AppendPacketHeader(header, &writer, &length_field_offset)) {
863 QUIC_BUG << "AppendPacketHeader failed";
864 return 0;
865 }
866
fkastenholz305e1732019-06-18 05:01:22 -0700867 if (VersionHasIetfQuicFrames(transport_version())) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500868 if (AppendIetfFrames(frames, &writer) == 0) {
869 return 0;
870 }
871 if (!WriteIetfLongHeaderLength(header, &writer, length_field_offset,
872 level)) {
873 return 0;
874 }
875 return writer.length();
876 }
877 // TODO(dschinazi) if we enable long header lengths before v99, we need to
878 // add support for fixing up lengths in QuicFramer::BuildDataPacket.
879 DCHECK(!QuicVersionHasLongHeaderLengths(transport_version()));
880
881 size_t i = 0;
882 for (const QuicFrame& frame : frames) {
883 // Determine if we should write stream frame length in header.
884 const bool last_frame_in_packet = i == frames.size() - 1;
885 if (!AppendTypeByte(frame, last_frame_in_packet, &writer)) {
886 QUIC_BUG << "AppendTypeByte failed";
887 return 0;
888 }
889
890 switch (frame.type) {
891 case PADDING_FRAME:
892 if (!AppendPaddingFrame(frame.padding_frame, &writer)) {
893 QUIC_BUG << "AppendPaddingFrame of "
894 << frame.padding_frame.num_padding_bytes << " failed";
895 return 0;
896 }
897 break;
898 case STREAM_FRAME:
899 if (!AppendStreamFrame(frame.stream_frame, last_frame_in_packet,
900 &writer)) {
901 QUIC_BUG << "AppendStreamFrame failed";
902 return 0;
903 }
904 break;
905 case ACK_FRAME:
906 if (!AppendAckFrameAndTypeByte(*frame.ack_frame, &writer)) {
907 QUIC_BUG << "AppendAckFrameAndTypeByte failed: " << detailed_error_;
908 return 0;
909 }
910 break;
911 case STOP_WAITING_FRAME:
912 if (!AppendStopWaitingFrame(header, frame.stop_waiting_frame,
913 &writer)) {
914 QUIC_BUG << "AppendStopWaitingFrame failed";
915 return 0;
916 }
917 break;
918 case MTU_DISCOVERY_FRAME:
919 // MTU discovery frames are serialized as ping frames.
920 QUIC_FALLTHROUGH_INTENDED;
921 case PING_FRAME:
922 // Ping has no payload.
923 break;
924 case RST_STREAM_FRAME:
925 if (!AppendRstStreamFrame(*frame.rst_stream_frame, &writer)) {
926 QUIC_BUG << "AppendRstStreamFrame failed";
927 return 0;
928 }
929 break;
930 case CONNECTION_CLOSE_FRAME:
931 if (!AppendConnectionCloseFrame(*frame.connection_close_frame,
932 &writer)) {
933 QUIC_BUG << "AppendConnectionCloseFrame failed";
934 return 0;
935 }
936 break;
937 case GOAWAY_FRAME:
938 if (!AppendGoAwayFrame(*frame.goaway_frame, &writer)) {
939 QUIC_BUG << "AppendGoAwayFrame failed";
940 return 0;
941 }
942 break;
943 case WINDOW_UPDATE_FRAME:
944 if (!AppendWindowUpdateFrame(*frame.window_update_frame, &writer)) {
945 QUIC_BUG << "AppendWindowUpdateFrame failed";
946 return 0;
947 }
948 break;
949 case BLOCKED_FRAME:
950 if (!AppendBlockedFrame(*frame.blocked_frame, &writer)) {
951 QUIC_BUG << "AppendBlockedFrame failed";
952 return 0;
953 }
954 break;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500955 case NEW_CONNECTION_ID_FRAME:
956 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -0700957 "Attempt to append NEW_CONNECTION_ID frame and not in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -0500958 return RaiseError(QUIC_INTERNAL_ERROR);
959 case RETIRE_CONNECTION_ID_FRAME:
960 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -0700961 "Attempt to append RETIRE_CONNECTION_ID frame and not in IETF "
962 "QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -0500963 return RaiseError(QUIC_INTERNAL_ERROR);
964 case NEW_TOKEN_FRAME:
965 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -0700966 "Attempt to append NEW_TOKEN_ID frame and not in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -0500967 return RaiseError(QUIC_INTERNAL_ERROR);
fkastenholz3c4eabf2019-04-22 07:49:59 -0700968 case MAX_STREAMS_FRAME:
QUICHE teama6ef0a62019-03-07 20:34:33 -0500969 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -0700970 "Attempt to append MAX_STREAMS frame and not in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -0500971 return RaiseError(QUIC_INTERNAL_ERROR);
fkastenholz3c4eabf2019-04-22 07:49:59 -0700972 case STREAMS_BLOCKED_FRAME:
QUICHE teama6ef0a62019-03-07 20:34:33 -0500973 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -0700974 "Attempt to append STREAMS_BLOCKED frame and not in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -0500975 return RaiseError(QUIC_INTERNAL_ERROR);
976 case PATH_RESPONSE_FRAME:
977 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -0700978 "Attempt to append PATH_RESPONSE frame and not in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -0500979 return RaiseError(QUIC_INTERNAL_ERROR);
980 case PATH_CHALLENGE_FRAME:
981 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -0700982 "Attempt to append PATH_CHALLENGE frame and not in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -0500983 return RaiseError(QUIC_INTERNAL_ERROR);
984 case STOP_SENDING_FRAME:
985 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -0700986 "Attempt to append STOP_SENDING frame and not in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -0500987 return RaiseError(QUIC_INTERNAL_ERROR);
988 case MESSAGE_FRAME:
989 if (!AppendMessageFrameAndTypeByte(*frame.message_frame,
990 last_frame_in_packet, &writer)) {
991 QUIC_BUG << "AppendMessageFrame failed";
992 return 0;
993 }
994 break;
995 case CRYPTO_FRAME:
QUICHE teamea740082019-03-11 17:58:43 -0700996 if (!QuicVersionUsesCryptoFrames(version_.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500997 set_detailed_error(
998 "Attempt to append CRYPTO frame in version prior to 47.");
999 return RaiseError(QUIC_INTERNAL_ERROR);
1000 }
1001 if (!AppendCryptoFrame(*frame.crypto_frame, &writer)) {
1002 QUIC_BUG << "AppendCryptoFrame failed";
1003 return 0;
1004 }
1005 break;
1006 default:
1007 RaiseError(QUIC_INVALID_FRAME_DATA);
1008 QUIC_BUG << "QUIC_INVALID_FRAME_DATA";
1009 return 0;
1010 }
1011 ++i;
1012 }
1013
1014 return writer.length();
1015}
1016
1017size_t QuicFramer::AppendIetfFrames(const QuicFrames& frames,
1018 QuicDataWriter* writer) {
1019 size_t i = 0;
1020 for (const QuicFrame& frame : frames) {
1021 // Determine if we should write stream frame length in header.
1022 const bool last_frame_in_packet = i == frames.size() - 1;
1023 if (!AppendIetfTypeByte(frame, last_frame_in_packet, writer)) {
1024 QUIC_BUG << "AppendIetfTypeByte failed: " << detailed_error();
1025 return 0;
1026 }
1027
1028 switch (frame.type) {
1029 case PADDING_FRAME:
1030 if (!AppendPaddingFrame(frame.padding_frame, writer)) {
1031 QUIC_BUG << "AppendPaddingFrame of "
1032 << frame.padding_frame.num_padding_bytes
1033 << " failed: " << detailed_error();
1034 return 0;
1035 }
1036 break;
1037 case STREAM_FRAME:
1038 if (!AppendStreamFrame(frame.stream_frame, last_frame_in_packet,
1039 writer)) {
1040 QUIC_BUG << "AppendStreamFrame failed: " << detailed_error();
1041 return 0;
1042 }
1043 break;
1044 case ACK_FRAME:
1045 if (!AppendIetfAckFrameAndTypeByte(*frame.ack_frame, writer)) {
QUICHE team4fe0b942019-03-08 09:25:06 -05001046 QUIC_BUG << "AppendIetfAckFrameAndTypeByte failed: "
1047 << detailed_error();
QUICHE teama6ef0a62019-03-07 20:34:33 -05001048 return 0;
1049 }
1050 break;
1051 case STOP_WAITING_FRAME:
1052 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -07001053 "Attempt to append STOP WAITING frame in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05001054 return RaiseError(QUIC_INTERNAL_ERROR);
1055 case MTU_DISCOVERY_FRAME:
1056 // MTU discovery frames are serialized as ping frames.
1057 QUIC_FALLTHROUGH_INTENDED;
1058 case PING_FRAME:
1059 // Ping has no payload.
1060 break;
1061 case RST_STREAM_FRAME:
1062 if (!AppendRstStreamFrame(*frame.rst_stream_frame, writer)) {
1063 QUIC_BUG << "AppendRstStreamFrame failed: " << detailed_error();
1064 return 0;
1065 }
1066 break;
1067 case CONNECTION_CLOSE_FRAME:
fkastenholz72f509b2019-04-10 09:17:49 -07001068 if (!AppendIetfConnectionCloseFrame(*frame.connection_close_frame,
1069 writer)) {
1070 QUIC_BUG << "AppendIetfConnectionCloseFrame failed: "
1071 << detailed_error();
QUICHE teama6ef0a62019-03-07 20:34:33 -05001072 return 0;
1073 }
1074 break;
1075 case GOAWAY_FRAME:
fkastenholz305e1732019-06-18 05:01:22 -07001076 set_detailed_error("Attempt to append GOAWAY frame in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05001077 return RaiseError(QUIC_INTERNAL_ERROR);
1078 case WINDOW_UPDATE_FRAME:
1079 // Depending on whether there is a stream ID or not, will be either a
1080 // MAX STREAM DATA frame or a MAX DATA frame.
1081 if (frame.window_update_frame->stream_id ==
1082 QuicUtils::GetInvalidStreamId(transport_version())) {
1083 if (!AppendMaxDataFrame(*frame.window_update_frame, writer)) {
1084 QUIC_BUG << "AppendMaxDataFrame failed: " << detailed_error();
1085 return 0;
1086 }
1087 } else {
1088 if (!AppendMaxStreamDataFrame(*frame.window_update_frame, writer)) {
1089 QUIC_BUG << "AppendMaxStreamDataFrame failed: " << detailed_error();
1090 return 0;
1091 }
1092 }
1093 break;
1094 case BLOCKED_FRAME:
1095 if (!AppendBlockedFrame(*frame.blocked_frame, writer)) {
1096 QUIC_BUG << "AppendBlockedFrame failed: " << detailed_error();
1097 return 0;
1098 }
1099 break;
fkastenholz3c4eabf2019-04-22 07:49:59 -07001100 case MAX_STREAMS_FRAME:
1101 if (!AppendMaxStreamsFrame(frame.max_streams_frame, writer)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001102 QUIC_BUG << "AppendMaxStreamsFrame failed" << detailed_error();
1103 return 0;
1104 }
1105 break;
fkastenholz3c4eabf2019-04-22 07:49:59 -07001106 case STREAMS_BLOCKED_FRAME:
1107 if (!AppendStreamsBlockedFrame(frame.streams_blocked_frame, writer)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001108 QUIC_BUG << "AppendStreamsBlockedFrame failed" << detailed_error();
1109 return 0;
1110 }
1111 break;
1112 case NEW_CONNECTION_ID_FRAME:
1113 if (!AppendNewConnectionIdFrame(*frame.new_connection_id_frame,
1114 writer)) {
1115 QUIC_BUG << "AppendNewConnectionIdFrame failed: " << detailed_error();
1116 return 0;
1117 }
1118 break;
1119 case RETIRE_CONNECTION_ID_FRAME:
1120 if (!AppendRetireConnectionIdFrame(*frame.retire_connection_id_frame,
1121 writer)) {
1122 QUIC_BUG << "AppendRetireConnectionIdFrame failed: "
1123 << detailed_error();
1124 return 0;
1125 }
1126 break;
1127 case NEW_TOKEN_FRAME:
1128 if (!AppendNewTokenFrame(*frame.new_token_frame, writer)) {
1129 QUIC_BUG << "AppendNewTokenFrame failed: " << detailed_error();
1130 return 0;
1131 }
1132 break;
1133 case STOP_SENDING_FRAME:
1134 if (!AppendStopSendingFrame(*frame.stop_sending_frame, writer)) {
1135 QUIC_BUG << "AppendStopSendingFrame failed: " << detailed_error();
1136 return 0;
1137 }
1138 break;
1139 case PATH_CHALLENGE_FRAME:
1140 if (!AppendPathChallengeFrame(*frame.path_challenge_frame, writer)) {
1141 QUIC_BUG << "AppendPathChallengeFrame failed: " << detailed_error();
1142 return 0;
1143 }
1144 break;
1145 case PATH_RESPONSE_FRAME:
1146 if (!AppendPathResponseFrame(*frame.path_response_frame, writer)) {
1147 QUIC_BUG << "AppendPathResponseFrame failed: " << detailed_error();
1148 return 0;
1149 }
1150 break;
1151 case MESSAGE_FRAME:
1152 if (!AppendMessageFrameAndTypeByte(*frame.message_frame,
1153 last_frame_in_packet, writer)) {
1154 QUIC_BUG << "AppendMessageFrame failed: " << detailed_error();
1155 return 0;
1156 }
1157 break;
1158 case CRYPTO_FRAME:
1159 if (!AppendCryptoFrame(*frame.crypto_frame, writer)) {
1160 QUIC_BUG << "AppendCryptoFrame failed: " << detailed_error();
1161 return 0;
1162 }
1163 break;
1164 default:
1165 RaiseError(QUIC_INVALID_FRAME_DATA);
1166 set_detailed_error("Tried to append unknown frame type.");
1167 QUIC_BUG << "QUIC_INVALID_FRAME_DATA";
1168 return 0;
1169 }
1170 ++i;
1171 }
1172
1173 return writer->length();
1174}
1175
rch67cb9df2019-03-26 16:52:07 -07001176size_t QuicFramer::BuildConnectivityProbingPacket(
QUICHE teama6ef0a62019-03-07 20:34:33 -05001177 const QuicPacketHeader& header,
1178 char* buffer,
1179 size_t packet_length,
1180 EncryptionLevel level) {
1181 QuicFrames frames;
1182
1183 // Write a PING frame, which has no data payload.
1184 QuicPingFrame ping_frame;
1185 frames.push_back(QuicFrame(ping_frame));
1186
1187 // Add padding to the rest of the packet.
1188 QuicPaddingFrame padding_frame;
1189 frames.push_back(QuicFrame(padding_frame));
1190
1191 return BuildDataPacket(header, frames, buffer, packet_length, level);
1192}
1193
QUICHE teama6ef0a62019-03-07 20:34:33 -05001194size_t QuicFramer::BuildPaddedPathChallengePacket(
1195 const QuicPacketHeader& header,
1196 char* buffer,
1197 size_t packet_length,
1198 QuicPathFrameBuffer* payload,
1199 QuicRandom* randomizer,
1200 EncryptionLevel level) {
fkastenholz305e1732019-06-18 05:01:22 -07001201 if (!VersionHasIetfQuicFrames(version_.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001202 QUIC_BUG << "Attempt to build a PATH_CHALLENGE Connectivity Probing "
1203 "packet and not doing IETF QUIC";
1204 return 0;
1205 }
1206 QuicFrames frames;
1207
1208 // Write a PATH_CHALLENGE frame, which has a random 8-byte payload
1209 randomizer->RandBytes(payload->data(), payload->size());
1210
1211 QuicPathChallengeFrame path_challenge_frame(0, *payload);
1212 frames.push_back(QuicFrame(&path_challenge_frame));
1213
1214 // Add padding to the rest of the packet in order to assess Path MTU
1215 // characteristics.
1216 QuicPaddingFrame padding_frame;
1217 frames.push_back(QuicFrame(padding_frame));
1218
1219 return BuildDataPacket(header, frames, buffer, packet_length, level);
1220}
1221
1222size_t QuicFramer::BuildPathResponsePacket(
1223 const QuicPacketHeader& header,
1224 char* buffer,
1225 size_t packet_length,
1226 const QuicDeque<QuicPathFrameBuffer>& payloads,
1227 const bool is_padded,
1228 EncryptionLevel level) {
1229 if (payloads.empty()) {
1230 QUIC_BUG
1231 << "Attempt to generate connectivity response with no request payloads";
1232 return 0;
1233 }
fkastenholz305e1732019-06-18 05:01:22 -07001234 if (!VersionHasIetfQuicFrames(version_.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001235 QUIC_BUG << "Attempt to build a PATH_RESPONSE Connectivity Probing "
1236 "packet and not doing IETF QUIC";
1237 return 0;
1238 }
1239
1240 std::vector<std::unique_ptr<QuicPathResponseFrame>> path_response_frames;
1241 for (const QuicPathFrameBuffer& payload : payloads) {
1242 // Note that the control frame ID can be 0 since this is not retransmitted.
1243 path_response_frames.push_back(
1244 QuicMakeUnique<QuicPathResponseFrame>(0, payload));
1245 }
1246
1247 QuicFrames frames;
1248 for (const std::unique_ptr<QuicPathResponseFrame>& path_response_frame :
1249 path_response_frames) {
1250 frames.push_back(QuicFrame(path_response_frame.get()));
1251 }
1252
1253 if (is_padded) {
1254 // Add padding to the rest of the packet in order to assess Path MTU
1255 // characteristics.
1256 QuicPaddingFrame padding_frame;
1257 frames.push_back(QuicFrame(padding_frame));
1258 }
1259
1260 return BuildDataPacket(header, frames, buffer, packet_length, level);
1261}
1262
1263// static
1264std::unique_ptr<QuicEncryptedPacket> QuicFramer::BuildPublicResetPacket(
1265 const QuicPublicResetPacket& packet) {
1266 CryptoHandshakeMessage reset;
1267 reset.set_tag(kPRST);
1268 reset.SetValue(kRNON, packet.nonce_proof);
1269 if (packet.client_address.host().address_family() !=
1270 IpAddressFamily::IP_UNSPEC) {
1271 // packet.client_address is non-empty.
1272 QuicSocketAddressCoder address_coder(packet.client_address);
vasilvvc48c8712019-03-11 13:38:16 -07001273 std::string serialized_address = address_coder.Encode();
QUICHE teama6ef0a62019-03-07 20:34:33 -05001274 if (serialized_address.empty()) {
1275 return nullptr;
1276 }
1277 reset.SetStringPiece(kCADR, serialized_address);
1278 }
1279 if (!packet.endpoint_id.empty()) {
1280 reset.SetStringPiece(kEPID, packet.endpoint_id);
1281 }
1282 const QuicData& reset_serialized = reset.GetSerialized();
1283
1284 size_t len = kPublicFlagsSize + packet.connection_id.length() +
1285 reset_serialized.length();
1286 std::unique_ptr<char[]> buffer(new char[len]);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001287 QuicDataWriter writer(len, buffer.get());
1288
1289 uint8_t flags = static_cast<uint8_t>(PACKET_PUBLIC_FLAGS_RST |
1290 PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID);
1291 // This hack makes post-v33 public reset packet look like pre-v33 packets.
1292 flags |= static_cast<uint8_t>(PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID_OLD);
1293 if (!writer.WriteUInt8(flags)) {
1294 return nullptr;
1295 }
1296
1297 if (!writer.WriteConnectionId(packet.connection_id)) {
1298 return nullptr;
1299 }
1300
1301 if (!writer.WriteBytes(reset_serialized.data(), reset_serialized.length())) {
1302 return nullptr;
1303 }
1304
1305 return QuicMakeUnique<QuicEncryptedPacket>(buffer.release(), len, true);
1306}
1307
1308// static
1309std::unique_ptr<QuicEncryptedPacket> QuicFramer::BuildIetfStatelessResetPacket(
dschinazi17d42422019-06-18 16:35:07 -07001310 QuicConnectionId /*connection_id*/,
QUICHE teama6ef0a62019-03-07 20:34:33 -05001311 QuicUint128 stateless_reset_token) {
1312 QUIC_DVLOG(1) << "Building IETF stateless reset packet.";
1313 size_t len = kPacketHeaderTypeSize + kMinRandomBytesLengthInStatelessReset +
1314 sizeof(stateless_reset_token);
1315 std::unique_ptr<char[]> buffer(new char[len]);
1316 QuicDataWriter writer(len, buffer.get());
1317
1318 uint8_t type = 0;
1319 type |= FLAGS_FIXED_BIT;
1320 type |= FLAGS_SHORT_HEADER_RESERVED_1;
1321 type |= FLAGS_SHORT_HEADER_RESERVED_2;
fayang36825da2019-08-21 14:01:27 -07001322 type |= PacketNumberLengthToOnWireValue(PACKET_1BYTE_PACKET_NUMBER);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001323
1324 // Append type byte.
1325 if (!writer.WriteUInt8(type)) {
1326 return nullptr;
1327 }
1328 // Append random bytes.
1329 if (!writer.WriteRandomBytes(QuicRandom::GetInstance(),
1330 kMinRandomBytesLengthInStatelessReset)) {
1331 return nullptr;
1332 }
1333
1334 // Append stateless reset token.
1335 if (!writer.WriteBytes(&stateless_reset_token,
1336 sizeof(stateless_reset_token))) {
1337 return nullptr;
1338 }
1339 return QuicMakeUnique<QuicEncryptedPacket>(buffer.release(), len, true);
1340}
1341
1342// static
1343std::unique_ptr<QuicEncryptedPacket> QuicFramer::BuildVersionNegotiationPacket(
dschinazi8ff74822019-05-28 16:37:20 -07001344 QuicConnectionId server_connection_id,
dschinazib417d602019-05-29 13:08:45 -07001345 QuicConnectionId client_connection_id,
QUICHE teama6ef0a62019-03-07 20:34:33 -05001346 bool ietf_quic,
dschinazi48ac9192019-07-31 00:07:26 -07001347 bool use_length_prefix,
QUICHE teama6ef0a62019-03-07 20:34:33 -05001348 const ParsedQuicVersionVector& versions) {
dschinazi1ac22cc2019-06-25 11:47:50 -07001349 ParsedQuicVersionVector wire_versions = versions;
1350 if (!GetQuicReloadableFlag(quic_version_negotiation_grease)) {
1351 if (wire_versions.empty()) {
1352 wire_versions = {QuicVersionReservedForNegotiation()};
1353 }
1354 } else {
1355 // Add a version reserved for negotiation as suggested by the
1356 // "Using Reserved Versions" section of draft-ietf-quic-transport.
1357 QUIC_RELOADABLE_FLAG_COUNT_N(quic_version_negotiation_grease, 1, 2);
1358 if (wire_versions.empty()) {
1359 // Ensure that version negotiation packets we send have at least two
1360 // versions. This guarantees that, under all circumstances, all QUIC
1361 // packets we send are at least 14 bytes long.
1362 wire_versions = {QuicVersionReservedForNegotiation(),
1363 QuicVersionReservedForNegotiation()};
1364 } else {
1365 // This is not uniformely distributed but is acceptable since no security
1366 // depends on this randomness.
1367 size_t version_index = 0;
1368 const bool disable_randomness =
1369 GetQuicFlag(FLAGS_quic_disable_version_negotiation_grease_randomness);
1370 if (!disable_randomness) {
1371 version_index = QuicRandom::GetInstance()->RandUint64() %
1372 (wire_versions.size() + 1);
1373 }
1374 wire_versions.insert(wire_versions.begin() + version_index,
1375 QuicVersionReservedForNegotiation());
1376 }
1377 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001378 if (ietf_quic) {
dschinazi1ac22cc2019-06-25 11:47:50 -07001379 return BuildIetfVersionNegotiationPacket(
dschinazi48ac9192019-07-31 00:07:26 -07001380 use_length_prefix, server_connection_id, client_connection_id,
1381 wire_versions);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001382 }
dschinazib417d602019-05-29 13:08:45 -07001383
1384 // The GQUIC encoding does not support encoding client connection IDs.
1385 DCHECK(client_connection_id.IsEmpty());
dschinazi48ac9192019-07-31 00:07:26 -07001386 // The GQUIC encoding does not support length-prefixed connection IDs.
1387 DCHECK(!use_length_prefix);
dschinazib417d602019-05-29 13:08:45 -07001388
dschinazi1ac22cc2019-06-25 11:47:50 -07001389 DCHECK(!wire_versions.empty());
dschinazi8ff74822019-05-28 16:37:20 -07001390 size_t len = kPublicFlagsSize + server_connection_id.length() +
dschinazi1ac22cc2019-06-25 11:47:50 -07001391 wire_versions.size() * kQuicVersionSize;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001392 std::unique_ptr<char[]> buffer(new char[len]);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001393 QuicDataWriter writer(len, buffer.get());
1394
1395 uint8_t flags = static_cast<uint8_t>(
1396 PACKET_PUBLIC_FLAGS_VERSION | PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID |
1397 // TODO(rch): Remove this QUIC_VERSION_32 is retired.
1398 PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID_OLD);
1399 if (!writer.WriteUInt8(flags)) {
1400 return nullptr;
1401 }
1402
dschinazi8ff74822019-05-28 16:37:20 -07001403 if (!writer.WriteConnectionId(server_connection_id)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001404 return nullptr;
1405 }
1406
dschinazi1ac22cc2019-06-25 11:47:50 -07001407 for (const ParsedQuicVersion& version : wire_versions) {
nharpereaab5ad2019-05-31 12:23:25 -07001408 if (!writer.WriteUInt32(CreateQuicVersionLabel(version))) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001409 return nullptr;
1410 }
1411 }
1412
1413 return QuicMakeUnique<QuicEncryptedPacket>(buffer.release(), len, true);
1414}
1415
1416// static
1417std::unique_ptr<QuicEncryptedPacket>
1418QuicFramer::BuildIetfVersionNegotiationPacket(
dschinazi48ac9192019-07-31 00:07:26 -07001419 bool use_length_prefix,
dschinazib417d602019-05-29 13:08:45 -07001420 QuicConnectionId server_connection_id,
1421 QuicConnectionId client_connection_id,
QUICHE teama6ef0a62019-03-07 20:34:33 -05001422 const ParsedQuicVersionVector& versions) {
dschinazi48ac9192019-07-31 00:07:26 -07001423 QUIC_DVLOG(1) << "Building IETF version negotiation packet with"
1424 << (use_length_prefix ? "" : "out")
1425 << " length prefix, server_connection_id "
1426 << server_connection_id << " client_connection_id "
1427 << client_connection_id << " versions "
dschinazi5a354c92019-05-09 12:18:53 -07001428 << ParsedQuicVersionVectorToString(versions);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001429 DCHECK(!versions.empty());
1430 size_t len = kPacketHeaderTypeSize + kConnectionIdLengthSize +
dschinazib417d602019-05-29 13:08:45 -07001431 client_connection_id.length() + server_connection_id.length() +
QUICHE teama6ef0a62019-03-07 20:34:33 -05001432 (versions.size() + 1) * kQuicVersionSize;
dschinazi48ac9192019-07-31 00:07:26 -07001433 if (use_length_prefix) {
1434 // When using length-prefixed connection IDs, packets carry two lengths
1435 // instead of one.
1436 len += kConnectionIdLengthSize;
1437 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001438 std::unique_ptr<char[]> buffer(new char[len]);
1439 QuicDataWriter writer(len, buffer.get());
1440
1441 // TODO(fayang): Randomly select a value for the type.
dschinazi0366de92019-06-18 20:00:27 -07001442 uint8_t type = static_cast<uint8_t>(FLAGS_LONG_HEADER | FLAGS_FIXED_BIT);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001443 if (!writer.WriteUInt8(type)) {
1444 return nullptr;
1445 }
1446
1447 if (!writer.WriteUInt32(0)) {
1448 return nullptr;
1449 }
1450
dschinazi48ac9192019-07-31 00:07:26 -07001451 if (!AppendIetfConnectionIds(true, use_length_prefix, client_connection_id,
1452 server_connection_id, &writer)) {
dschinazi1f485a12019-05-13 11:57:01 -07001453 return nullptr;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001454 }
1455
1456 for (const ParsedQuicVersion& version : versions) {
nharpereaab5ad2019-05-31 12:23:25 -07001457 if (!writer.WriteUInt32(CreateQuicVersionLabel(version))) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001458 return nullptr;
1459 }
1460 }
1461
1462 return QuicMakeUnique<QuicEncryptedPacket>(buffer.release(), len, true);
1463}
1464
1465bool QuicFramer::ProcessPacket(const QuicEncryptedPacket& packet) {
1466 QuicDataReader reader(packet.data(), packet.length());
1467
1468 bool packet_has_ietf_packet_header = false;
1469 if (infer_packet_header_type_from_version_) {
1470 packet_has_ietf_packet_header =
fayangd4291e42019-05-30 10:31:21 -07001471 VersionHasIetfInvariantHeader(version_.transport_version);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001472 } else if (!reader.IsDoneReading()) {
1473 uint8_t type = reader.PeekByte();
1474 packet_has_ietf_packet_header = QuicUtils::IsIetfPacketHeader(type);
1475 }
1476 if (packet_has_ietf_packet_header) {
1477 QUIC_DVLOG(1) << ENDPOINT << "Processing IETF QUIC packet.";
1478 }
1479
1480 visitor_->OnPacket();
1481
1482 QuicPacketHeader header;
1483 if (!ProcessPublicHeader(&reader, packet_has_ietf_packet_header, &header)) {
1484 DCHECK_NE("", detailed_error_);
1485 QUIC_DVLOG(1) << ENDPOINT << "Unable to process public header. Error: "
1486 << detailed_error_;
1487 DCHECK_NE("", detailed_error_);
1488 RecordDroppedPacketReason(DroppedPacketReason::INVALID_PUBLIC_HEADER);
1489 return RaiseError(QUIC_INVALID_PACKET_HEADER);
1490 }
1491
1492 if (!visitor_->OnUnauthenticatedPublicHeader(header)) {
1493 // The visitor suppresses further processing of the packet.
1494 return true;
1495 }
1496
dschinazie0df3f72019-05-06 16:37:51 -07001497 if (IsVersionNegotiation(header, packet_has_ietf_packet_header)) {
dschinazi072da7c2019-05-07 17:57:42 -07001498 if (perspective_ == Perspective::IS_CLIENT) {
1499 QUIC_DVLOG(1) << "Client received version negotiation packet";
1500 return ProcessVersionNegotiationPacket(&reader, header);
1501 } else {
1502 QUIC_DLOG(ERROR) << "Server received version negotiation packet";
1503 set_detailed_error("Server received version negotiation packet.");
1504 return RaiseError(QUIC_INVALID_VERSION_NEGOTIATION_PACKET);
1505 }
dschinazie0df3f72019-05-06 16:37:51 -07001506 }
1507
1508 if (header.version_flag && header.version != version_) {
1509 if (perspective_ == Perspective::IS_SERVER) {
fayang8aba1ff2019-06-21 12:00:54 -07001510 if (!visitor_->OnProtocolVersionMismatch(header.version)) {
dschinazie0df3f72019-05-06 16:37:51 -07001511 RecordDroppedPacketReason(DroppedPacketReason::VERSION_MISMATCH);
1512 return true;
1513 }
1514 } else {
1515 // A client received a packet of a different version but that packet is
1516 // not a version negotiation packet. It is therefore invalid and dropped.
1517 QUIC_DLOG(ERROR) << "Client received unexpected version "
1518 << ParsedQuicVersionToString(header.version)
1519 << " instead of " << ParsedQuicVersionToString(version_);
1520 set_detailed_error("Client received unexpected version.");
1521 return RaiseError(QUIC_INVALID_VERSION);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001522 }
1523 }
1524
1525 bool rv;
dschinazie0df3f72019-05-06 16:37:51 -07001526 if (header.long_packet_type == RETRY) {
dschinazi244f6dc2019-05-06 15:45:16 -07001527 rv = ProcessRetryPacket(&reader, header);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001528 } else if (header.reset_flag) {
1529 rv = ProcessPublicResetPacket(&reader, header);
dschinazie8d7fa72019-04-05 14:44:40 -07001530 } else if (packet.length() <= kMaxIncomingPacketSize) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001531 // The optimized decryption algorithm implementations run faster when
1532 // operating on aligned memory.
dschinazie8d7fa72019-04-05 14:44:40 -07001533 QUIC_CACHELINE_ALIGNED char buffer[kMaxIncomingPacketSize];
QUICHE teama6ef0a62019-03-07 20:34:33 -05001534 if (packet_has_ietf_packet_header) {
1535 rv = ProcessIetfDataPacket(&reader, &header, packet, buffer,
dschinazie8d7fa72019-04-05 14:44:40 -07001536 QUIC_ARRAYSIZE(buffer));
QUICHE teama6ef0a62019-03-07 20:34:33 -05001537 } else {
dschinazie8d7fa72019-04-05 14:44:40 -07001538 rv = ProcessDataPacket(&reader, &header, packet, buffer,
1539 QUIC_ARRAYSIZE(buffer));
QUICHE teama6ef0a62019-03-07 20:34:33 -05001540 }
1541 } else {
1542 std::unique_ptr<char[]> large_buffer(new char[packet.length()]);
1543 if (packet_has_ietf_packet_header) {
1544 rv = ProcessIetfDataPacket(&reader, &header, packet, large_buffer.get(),
1545 packet.length());
1546 } else {
1547 rv = ProcessDataPacket(&reader, &header, packet, large_buffer.get(),
1548 packet.length());
1549 }
1550 QUIC_BUG_IF(rv) << "QUIC should never successfully process packets larger"
dschinazie8d7fa72019-04-05 14:44:40 -07001551 << "than kMaxIncomingPacketSize. packet size:"
1552 << packet.length();
QUICHE teama6ef0a62019-03-07 20:34:33 -05001553 }
1554 return rv;
1555}
1556
1557bool QuicFramer::ProcessVersionNegotiationPacket(
1558 QuicDataReader* reader,
1559 const QuicPacketHeader& header) {
1560 DCHECK_EQ(Perspective::IS_CLIENT, perspective_);
1561
QUICHE team2252b702019-05-14 23:55:14 -04001562 QuicVersionNegotiationPacket packet(
1563 GetServerConnectionIdAsRecipient(header, perspective_));
QUICHE teama6ef0a62019-03-07 20:34:33 -05001564 // Try reading at least once to raise error if the packet is invalid.
1565 do {
1566 QuicVersionLabel version_label;
fayang40315542019-05-09 09:19:09 -07001567 if (!ProcessVersionLabel(reader, &version_label)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001568 set_detailed_error("Unable to read supported version in negotiation.");
1569 RecordDroppedPacketReason(
1570 DroppedPacketReason::INVALID_VERSION_NEGOTIATION_PACKET);
1571 return RaiseError(QUIC_INVALID_VERSION_NEGOTIATION_PACKET);
1572 }
nharper4fd11052019-06-04 14:23:22 -07001573 ParsedQuicVersion parsed_version = ParseQuicVersionLabel(version_label);
1574 if (parsed_version != UnsupportedQuicVersion()) {
1575 packet.versions.push_back(parsed_version);
1576 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001577 } while (!reader->IsDoneReading());
1578
dschinazi5a354c92019-05-09 12:18:53 -07001579 QUIC_DLOG(INFO) << ENDPOINT << "parsed version negotiation: "
1580 << ParsedQuicVersionVectorToString(packet.versions);
1581
QUICHE teama6ef0a62019-03-07 20:34:33 -05001582 visitor_->OnVersionNegotiationPacket(packet);
1583 return true;
1584}
1585
dschinazi244f6dc2019-05-06 15:45:16 -07001586bool QuicFramer::ProcessRetryPacket(QuicDataReader* reader,
1587 const QuicPacketHeader& header) {
1588 DCHECK_EQ(Perspective::IS_CLIENT, perspective_);
1589
dschinazi244f6dc2019-05-06 15:45:16 -07001590 QuicConnectionId original_destination_connection_id;
dschinazi48ac9192019-07-31 00:07:26 -07001591 if (version_.HasLengthPrefixedConnectionIds()) {
1592 // Parse Original Destination Connection ID.
1593 if (!reader->ReadLengthPrefixedConnectionId(
1594 &original_destination_connection_id)) {
1595 set_detailed_error("Unable to read Original Destination ConnectionId.");
1596 return false;
1597 }
1598 } else {
1599 // Parse Original Destination Connection ID Length.
1600 uint8_t odcil = header.type_byte & 0xf;
1601 if (odcil != 0) {
1602 odcil += kConnectionIdLengthAdjustment;
1603 }
1604
1605 // Parse Original Destination Connection ID.
1606 if (!reader->ReadConnectionId(&original_destination_connection_id, odcil)) {
1607 set_detailed_error("Unable to read Original Destination ConnectionId.");
1608 return false;
1609 }
dschinazi244f6dc2019-05-06 15:45:16 -07001610 }
1611
dschinazib953d022019-08-01 18:05:58 -07001612 if (!QuicUtils::IsConnectionIdValidForVersion(
1613 original_destination_connection_id, transport_version())) {
1614 set_detailed_error(
1615 "Received Original Destination ConnectionId with invalid length.");
1616 return false;
1617 }
1618
dschinazi244f6dc2019-05-06 15:45:16 -07001619 QuicStringPiece retry_token = reader->ReadRemainingPayload();
1620 visitor_->OnRetryPacket(original_destination_connection_id,
1621 header.source_connection_id, retry_token);
1622 return true;
1623}
1624
QUICHE teama6ef0a62019-03-07 20:34:33 -05001625// Seeks the current packet to check for a coalesced packet at the end.
1626// If the IETF length field only spans part of the outer packet,
1627// then there is a coalesced packet after this one.
1628void QuicFramer::MaybeProcessCoalescedPacket(
1629 const QuicDataReader& encrypted_reader,
1630 uint64_t remaining_bytes_length,
1631 const QuicPacketHeader& header) {
1632 if (header.remaining_packet_length >= remaining_bytes_length) {
1633 // There is no coalesced packet.
1634 return;
1635 }
1636
1637 QuicStringPiece remaining_data = encrypted_reader.PeekRemainingPayload();
1638 DCHECK_EQ(remaining_data.length(), remaining_bytes_length);
1639
1640 const char* coalesced_data =
1641 remaining_data.data() + header.remaining_packet_length;
1642 uint64_t coalesced_data_length =
1643 remaining_bytes_length - header.remaining_packet_length;
1644 QuicDataReader coalesced_reader(coalesced_data, coalesced_data_length);
1645
1646 QuicPacketHeader coalesced_header;
1647 if (!ProcessIetfPacketHeader(&coalesced_reader, &coalesced_header)) {
1648 QUIC_PEER_BUG << ENDPOINT
1649 << "Failed to parse received coalesced header of length "
1650 << coalesced_data_length << ": "
1651 << QuicTextUtils::HexEncode(coalesced_data,
1652 coalesced_data_length)
1653 << " previous header was " << header;
1654 return;
1655 }
1656
1657 if (coalesced_header.destination_connection_id !=
1658 header.destination_connection_id ||
1659 (coalesced_header.form != IETF_QUIC_SHORT_HEADER_PACKET &&
1660 coalesced_header.version != header.version)) {
1661 QUIC_PEER_BUG << ENDPOINT << "Received mismatched coalesced header "
1662 << coalesced_header << " previous header was " << header;
1663 return;
1664 }
1665
1666 QuicEncryptedPacket coalesced_packet(coalesced_data, coalesced_data_length,
1667 /*owns_buffer=*/false);
1668 visitor_->OnCoalescedPacket(coalesced_packet);
1669}
1670
1671bool QuicFramer::MaybeProcessIetfLength(QuicDataReader* encrypted_reader,
1672 QuicPacketHeader* header) {
1673 if (!QuicVersionHasLongHeaderLengths(header->version.transport_version) ||
1674 header->form != IETF_QUIC_LONG_HEADER_PACKET ||
1675 (header->long_packet_type != INITIAL &&
1676 header->long_packet_type != HANDSHAKE &&
1677 header->long_packet_type != ZERO_RTT_PROTECTED)) {
1678 return true;
1679 }
1680 header->length_length = encrypted_reader->PeekVarInt62Length();
1681 if (!encrypted_reader->ReadVarInt62(&header->remaining_packet_length)) {
1682 set_detailed_error("Unable to read long header payload length.");
1683 return RaiseError(QUIC_INVALID_PACKET_HEADER);
1684 }
1685 uint64_t remaining_bytes_length = encrypted_reader->BytesRemaining();
1686 if (header->remaining_packet_length > remaining_bytes_length) {
1687 set_detailed_error("Long header payload length longer than packet.");
1688 return RaiseError(QUIC_INVALID_PACKET_HEADER);
1689 }
1690
1691 MaybeProcessCoalescedPacket(*encrypted_reader, remaining_bytes_length,
1692 *header);
1693
1694 if (!encrypted_reader->TruncateRemaining(header->remaining_packet_length)) {
1695 set_detailed_error("Length TruncateRemaining failed.");
1696 QUIC_BUG << "Length TruncateRemaining failed.";
1697 return RaiseError(QUIC_INVALID_PACKET_HEADER);
1698 }
1699 return true;
1700}
1701
1702bool QuicFramer::ProcessIetfDataPacket(QuicDataReader* encrypted_reader,
1703 QuicPacketHeader* header,
1704 const QuicEncryptedPacket& packet,
1705 char* decrypted_buffer,
1706 size_t buffer_length) {
1707 DCHECK_NE(GOOGLE_QUIC_PACKET, header->form);
1708 DCHECK(!header->has_possible_stateless_reset_token);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001709 header->length_length = VARIABLE_LENGTH_INTEGER_LENGTH_0;
1710 header->remaining_packet_length = 0;
1711 if (header->form == IETF_QUIC_SHORT_HEADER_PACKET &&
1712 perspective_ == Perspective::IS_CLIENT) {
1713 // Peek possible stateless reset token. Will only be used on decryption
1714 // failure.
1715 QuicStringPiece remaining = encrypted_reader->PeekRemainingPayload();
1716 if (remaining.length() >= sizeof(header->possible_stateless_reset_token)) {
1717 header->has_possible_stateless_reset_token = true;
1718 memcpy(&header->possible_stateless_reset_token,
1719 &remaining.data()[remaining.length() -
1720 sizeof(header->possible_stateless_reset_token)],
1721 sizeof(header->possible_stateless_reset_token));
1722 }
1723 }
1724
QUICHE teama6ef0a62019-03-07 20:34:33 -05001725 if (!MaybeProcessIetfLength(encrypted_reader, header)) {
1726 return false;
1727 }
1728
nharper55fa6132019-05-07 19:37:21 -07001729 QuicStringPiece associated_data;
1730 std::vector<char> ad_storage;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001731 if (header->form == IETF_QUIC_SHORT_HEADER_PACKET ||
1732 header->long_packet_type != VERSION_NEGOTIATION) {
dschinazi072da7c2019-05-07 17:57:42 -07001733 DCHECK(header->form == IETF_QUIC_SHORT_HEADER_PACKET ||
1734 header->long_packet_type == INITIAL ||
1735 header->long_packet_type == HANDSHAKE ||
1736 header->long_packet_type == ZERO_RTT_PROTECTED);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001737 // Process packet number.
QUICHE team10b22a12019-03-21 15:31:42 -07001738 QuicPacketNumber base_packet_number;
1739 if (supports_multiple_packet_number_spaces_) {
nharper55fa6132019-05-07 19:37:21 -07001740 PacketNumberSpace pn_space = GetPacketNumberSpace(*header);
1741 if (pn_space == NUM_PACKET_NUMBER_SPACES) {
1742 return RaiseError(QUIC_INVALID_PACKET_HEADER);
1743 }
1744 base_packet_number = largest_decrypted_packet_numbers_[pn_space];
QUICHE team10b22a12019-03-21 15:31:42 -07001745 } else {
1746 base_packet_number = largest_packet_number_;
1747 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001748 uint64_t full_packet_number;
nharper55fa6132019-05-07 19:37:21 -07001749 bool hp_removal_failed = false;
1750 if (version_.HasHeaderProtection()) {
1751 if (!RemoveHeaderProtection(encrypted_reader, packet, header,
1752 &full_packet_number, &ad_storage)) {
1753 hp_removal_failed = true;
1754 }
1755 associated_data = QuicStringPiece(ad_storage.data(), ad_storage.size());
1756 } else if (!ProcessAndCalculatePacketNumber(
1757 encrypted_reader, header->packet_number_length,
1758 base_packet_number, &full_packet_number)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001759 set_detailed_error("Unable to read packet number.");
1760 RecordDroppedPacketReason(DroppedPacketReason::INVALID_PACKET_NUMBER);
1761 return RaiseError(QUIC_INVALID_PACKET_HEADER);
1762 }
1763
nharper55fa6132019-05-07 19:37:21 -07001764 if (hp_removal_failed ||
1765 !IsValidFullPacketNumber(full_packet_number, transport_version())) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001766 if (IsIetfStatelessResetPacket(*header)) {
1767 // This is a stateless reset packet.
1768 QuicIetfStatelessResetPacket packet(
1769 *header, header->possible_stateless_reset_token);
1770 visitor_->OnAuthenticatedIetfStatelessResetPacket(packet);
1771 return true;
1772 }
nharper55fa6132019-05-07 19:37:21 -07001773 if (hp_removal_failed) {
dschinazi4b5a68a2019-08-15 15:45:36 -07001774 if (GetQuicRestartFlag(quic_framer_uses_undecryptable_upcall)) {
1775 QUIC_RESTART_FLAG_COUNT_N(quic_framer_uses_undecryptable_upcall, 5,
1776 7);
1777 const EncryptionLevel decryption_level = GetEncryptionLevel(*header);
1778 const bool has_decryption_key =
1779 decrypter_[decryption_level] != nullptr;
1780 visitor_->OnUndecryptablePacket(
1781 QuicEncryptedPacket(encrypted_reader->FullPayload()),
1782 decryption_level, has_decryption_key);
1783 }
nharper55fa6132019-05-07 19:37:21 -07001784 set_detailed_error("Unable to decrypt header protection.");
1785 return RaiseError(QUIC_DECRYPTION_FAILURE);
1786 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001787 RecordDroppedPacketReason(DroppedPacketReason::INVALID_PACKET_NUMBER);
1788 set_detailed_error("packet numbers cannot be 0.");
1789 return RaiseError(QUIC_INVALID_PACKET_HEADER);
1790 }
1791 header->packet_number = QuicPacketNumber(full_packet_number);
1792 }
1793
1794 // A nonce should only present in SHLO from the server to the client when
1795 // using QUIC crypto.
1796 if (header->form == IETF_QUIC_LONG_HEADER_PACKET &&
1797 header->long_packet_type == ZERO_RTT_PROTECTED &&
1798 perspective_ == Perspective::IS_CLIENT &&
1799 version_.handshake_protocol == PROTOCOL_QUIC_CRYPTO) {
1800 if (!encrypted_reader->ReadBytes(
1801 reinterpret_cast<uint8_t*>(last_nonce_.data()),
1802 last_nonce_.size())) {
1803 set_detailed_error("Unable to read nonce.");
1804 RecordDroppedPacketReason(
1805 DroppedPacketReason::INVALID_DIVERSIFICATION_NONCE);
1806 return RaiseError(QUIC_INVALID_PACKET_HEADER);
1807 }
1808
1809 header->nonce = &last_nonce_;
1810 } else {
1811 header->nonce = nullptr;
1812 }
1813
1814 if (!visitor_->OnUnauthenticatedHeader(*header)) {
1815 set_detailed_error(
1816 "Visitor asked to stop processing of unauthenticated header.");
1817 return false;
1818 }
1819
1820 QuicStringPiece encrypted = encrypted_reader->ReadRemainingPayload();
nharper55fa6132019-05-07 19:37:21 -07001821 if (!version_.HasHeaderProtection()) {
1822 associated_data = GetAssociatedDataFromEncryptedPacket(
1823 version_.transport_version, packet,
1824 GetIncludedDestinationConnectionIdLength(*header),
1825 GetIncludedSourceConnectionIdLength(*header), header->version_flag,
1826 header->nonce != nullptr, header->packet_number_length,
1827 header->retry_token_length_length, header->retry_token.length(),
1828 header->length_length);
1829 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001830
1831 size_t decrypted_length = 0;
QUICHE team10b22a12019-03-21 15:31:42 -07001832 EncryptionLevel decrypted_level;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001833 if (!DecryptPayload(encrypted, associated_data, *header, decrypted_buffer,
QUICHE team10b22a12019-03-21 15:31:42 -07001834 buffer_length, &decrypted_length, &decrypted_level)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001835 if (IsIetfStatelessResetPacket(*header)) {
1836 // This is a stateless reset packet.
1837 QuicIetfStatelessResetPacket packet(
1838 *header, header->possible_stateless_reset_token);
1839 visitor_->OnAuthenticatedIetfStatelessResetPacket(packet);
1840 return true;
1841 }
dschinazi4b5a68a2019-08-15 15:45:36 -07001842 if (GetQuicRestartFlag(quic_framer_uses_undecryptable_upcall)) {
1843 QUIC_RESTART_FLAG_COUNT_N(quic_framer_uses_undecryptable_upcall, 6, 7);
1844 const EncryptionLevel decryption_level = GetEncryptionLevel(*header);
1845 const bool has_decryption_key = version_.KnowsWhichDecrypterToUse() &&
1846 decrypter_[decryption_level] != nullptr;
1847 visitor_->OnUndecryptablePacket(
1848 QuicEncryptedPacket(encrypted_reader->FullPayload()),
1849 decryption_level, has_decryption_key);
1850 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001851 set_detailed_error("Unable to decrypt payload.");
1852 RecordDroppedPacketReason(DroppedPacketReason::DECRYPTION_FAILURE);
1853 return RaiseError(QUIC_DECRYPTION_FAILURE);
1854 }
1855 QuicDataReader reader(decrypted_buffer, decrypted_length);
1856
1857 // Update the largest packet number after we have decrypted the packet
1858 // so we are confident is not attacker controlled.
QUICHE team10b22a12019-03-21 15:31:42 -07001859 if (supports_multiple_packet_number_spaces_) {
1860 largest_decrypted_packet_numbers_[QuicUtils::GetPacketNumberSpace(
1861 decrypted_level)]
1862 .UpdateMax(header->packet_number);
1863 } else {
1864 largest_packet_number_.UpdateMax(header->packet_number);
1865 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001866
1867 if (!visitor_->OnPacketHeader(*header)) {
1868 RecordDroppedPacketReason(DroppedPacketReason::INVALID_PACKET_NUMBER);
1869 // The visitor suppresses further processing of the packet.
1870 return true;
1871 }
1872
dschinazie8d7fa72019-04-05 14:44:40 -07001873 if (packet.length() > kMaxIncomingPacketSize) {
1874 set_detailed_error("Packet too large.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05001875 return RaiseError(QUIC_PACKET_TOO_LARGE);
1876 }
1877
1878 // Handle the payload.
fkastenholz305e1732019-06-18 05:01:22 -07001879 if (VersionHasIetfQuicFrames(version_.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001880 if (!ProcessIetfFrameData(&reader, *header)) {
1881 DCHECK_NE(QUIC_NO_ERROR, error_); // ProcessIetfFrameData sets the error.
1882 DCHECK_NE("", detailed_error_);
1883 QUIC_DLOG(WARNING) << ENDPOINT << "Unable to process frame data. Error: "
1884 << detailed_error_;
1885 return false;
1886 }
1887 } else {
1888 if (!ProcessFrameData(&reader, *header)) {
1889 DCHECK_NE(QUIC_NO_ERROR, error_); // ProcessFrameData sets the error.
1890 DCHECK_NE("", detailed_error_);
1891 QUIC_DLOG(WARNING) << ENDPOINT << "Unable to process frame data. Error: "
1892 << detailed_error_;
1893 return false;
1894 }
1895 }
1896
1897 visitor_->OnPacketComplete();
1898 return true;
1899}
1900
1901bool QuicFramer::ProcessDataPacket(QuicDataReader* encrypted_reader,
1902 QuicPacketHeader* header,
1903 const QuicEncryptedPacket& packet,
1904 char* decrypted_buffer,
1905 size_t buffer_length) {
1906 if (!ProcessUnauthenticatedHeader(encrypted_reader, header)) {
1907 DCHECK_NE("", detailed_error_);
1908 QUIC_DVLOG(1)
1909 << ENDPOINT
1910 << "Unable to process packet header. Stopping parsing. Error: "
1911 << detailed_error_;
1912 RecordDroppedPacketReason(DroppedPacketReason::INVALID_PACKET_NUMBER);
1913 return false;
1914 }
1915
1916 QuicStringPiece encrypted = encrypted_reader->ReadRemainingPayload();
1917 QuicStringPiece associated_data = GetAssociatedDataFromEncryptedPacket(
1918 version_.transport_version, packet,
1919 GetIncludedDestinationConnectionIdLength(*header),
1920 GetIncludedSourceConnectionIdLength(*header), header->version_flag,
1921 header->nonce != nullptr, header->packet_number_length,
1922 header->retry_token_length_length, header->retry_token.length(),
1923 header->length_length);
1924
1925 size_t decrypted_length = 0;
QUICHE team10b22a12019-03-21 15:31:42 -07001926 EncryptionLevel decrypted_level;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001927 if (!DecryptPayload(encrypted, associated_data, *header, decrypted_buffer,
QUICHE team10b22a12019-03-21 15:31:42 -07001928 buffer_length, &decrypted_length, &decrypted_level)) {
dschinazi4b5a68a2019-08-15 15:45:36 -07001929 if (GetQuicRestartFlag(quic_framer_uses_undecryptable_upcall)) {
1930 QUIC_RESTART_FLAG_COUNT_N(quic_framer_uses_undecryptable_upcall, 7, 7);
1931 const EncryptionLevel decryption_level = decrypter_level_;
1932 // This version uses trial decryption so we always report to our visitor
1933 // that we are not certain we have the correct decryption key.
1934 const bool has_decryption_key = false;
1935 visitor_->OnUndecryptablePacket(
1936 QuicEncryptedPacket(encrypted_reader->FullPayload()),
1937 decryption_level, has_decryption_key);
1938 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001939 RecordDroppedPacketReason(DroppedPacketReason::DECRYPTION_FAILURE);
1940 set_detailed_error("Unable to decrypt payload.");
1941 return RaiseError(QUIC_DECRYPTION_FAILURE);
1942 }
1943
1944 QuicDataReader reader(decrypted_buffer, decrypted_length);
1945
1946 // Update the largest packet number after we have decrypted the packet
1947 // so we are confident is not attacker controlled.
QUICHE team10b22a12019-03-21 15:31:42 -07001948 if (supports_multiple_packet_number_spaces_) {
1949 largest_decrypted_packet_numbers_[QuicUtils::GetPacketNumberSpace(
1950 decrypted_level)]
1951 .UpdateMax(header->packet_number);
1952 } else {
1953 largest_packet_number_.UpdateMax(header->packet_number);
1954 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001955
1956 if (!visitor_->OnPacketHeader(*header)) {
1957 // The visitor suppresses further processing of the packet.
1958 return true;
1959 }
1960
dschinazie8d7fa72019-04-05 14:44:40 -07001961 if (packet.length() > kMaxIncomingPacketSize) {
1962 set_detailed_error("Packet too large.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05001963 return RaiseError(QUIC_PACKET_TOO_LARGE);
1964 }
1965
1966 // Handle the payload.
1967 if (!ProcessFrameData(&reader, *header)) {
1968 DCHECK_NE(QUIC_NO_ERROR, error_); // ProcessFrameData sets the error.
1969 DCHECK_NE("", detailed_error_);
1970 QUIC_DLOG(WARNING) << ENDPOINT << "Unable to process frame data. Error: "
1971 << detailed_error_;
1972 return false;
1973 }
1974
1975 visitor_->OnPacketComplete();
1976 return true;
1977}
1978
1979bool QuicFramer::ProcessPublicResetPacket(QuicDataReader* reader,
1980 const QuicPacketHeader& header) {
QUICHE team2252b702019-05-14 23:55:14 -04001981 QuicPublicResetPacket packet(
1982 GetServerConnectionIdAsRecipient(header, perspective_));
QUICHE teama6ef0a62019-03-07 20:34:33 -05001983
1984 std::unique_ptr<CryptoHandshakeMessage> reset(
1985 CryptoFramer::ParseMessage(reader->ReadRemainingPayload()));
1986 if (!reset.get()) {
1987 set_detailed_error("Unable to read reset message.");
1988 RecordDroppedPacketReason(DroppedPacketReason::INVALID_PUBLIC_RESET_PACKET);
1989 return RaiseError(QUIC_INVALID_PUBLIC_RST_PACKET);
1990 }
1991 if (reset->tag() != kPRST) {
1992 set_detailed_error("Incorrect message tag.");
1993 RecordDroppedPacketReason(DroppedPacketReason::INVALID_PUBLIC_RESET_PACKET);
1994 return RaiseError(QUIC_INVALID_PUBLIC_RST_PACKET);
1995 }
1996
1997 if (reset->GetUint64(kRNON, &packet.nonce_proof) != QUIC_NO_ERROR) {
1998 set_detailed_error("Unable to read nonce proof.");
1999 RecordDroppedPacketReason(DroppedPacketReason::INVALID_PUBLIC_RESET_PACKET);
2000 return RaiseError(QUIC_INVALID_PUBLIC_RST_PACKET);
2001 }
2002 // TODO(satyamshekhar): validate nonce to protect against DoS.
2003
2004 QuicStringPiece address;
2005 if (reset->GetStringPiece(kCADR, &address)) {
2006 QuicSocketAddressCoder address_coder;
2007 if (address_coder.Decode(address.data(), address.length())) {
2008 packet.client_address =
2009 QuicSocketAddress(address_coder.ip(), address_coder.port());
2010 }
2011 }
2012
2013 QuicStringPiece endpoint_id;
2014 if (perspective_ == Perspective::IS_CLIENT &&
2015 reset->GetStringPiece(kEPID, &endpoint_id)) {
vasilvvc48c8712019-03-11 13:38:16 -07002016 packet.endpoint_id = std::string(endpoint_id);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002017 packet.endpoint_id += '\0';
2018 }
2019
2020 visitor_->OnPublicResetPacket(packet);
2021 return true;
2022}
2023
2024bool QuicFramer::IsIetfStatelessResetPacket(
2025 const QuicPacketHeader& header) const {
2026 QUIC_BUG_IF(header.has_possible_stateless_reset_token &&
2027 perspective_ != Perspective::IS_CLIENT)
2028 << "has_possible_stateless_reset_token can only be true at client side.";
2029 return header.form == IETF_QUIC_SHORT_HEADER_PACKET &&
2030 header.has_possible_stateless_reset_token &&
2031 visitor_->IsValidStatelessResetToken(
2032 header.possible_stateless_reset_token);
2033}
2034
2035bool QuicFramer::HasEncrypterOfEncryptionLevel(EncryptionLevel level) const {
2036 return encrypter_[level] != nullptr;
2037}
2038
2039bool QuicFramer::AppendPacketHeader(const QuicPacketHeader& header,
2040 QuicDataWriter* writer,
2041 size_t* length_field_offset) {
fayangd4291e42019-05-30 10:31:21 -07002042 if (VersionHasIetfInvariantHeader(transport_version())) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002043 return AppendIetfPacketHeader(header, writer, length_field_offset);
2044 }
2045 QUIC_DVLOG(1) << ENDPOINT << "Appending header: " << header;
2046 uint8_t public_flags = 0;
2047 if (header.reset_flag) {
2048 public_flags |= PACKET_PUBLIC_FLAGS_RST;
2049 }
2050 if (header.version_flag) {
2051 public_flags |= PACKET_PUBLIC_FLAGS_VERSION;
2052 }
2053
2054 public_flags |= GetPacketNumberFlags(header.packet_number_length)
2055 << kPublicHeaderSequenceNumberShift;
2056
2057 if (header.nonce != nullptr) {
2058 DCHECK_EQ(Perspective::IS_SERVER, perspective_);
2059 public_flags |= PACKET_PUBLIC_FLAGS_NONCE;
2060 }
QUICHE team2252b702019-05-14 23:55:14 -04002061
dschinazi7b9278c2019-05-20 07:36:21 -07002062 QuicConnectionId server_connection_id =
QUICHE team2252b702019-05-14 23:55:14 -04002063 GetServerConnectionIdAsSender(header, perspective_);
dschinazi7b9278c2019-05-20 07:36:21 -07002064 QuicConnectionIdIncluded server_connection_id_included =
QUICHE team2252b702019-05-14 23:55:14 -04002065 GetServerConnectionIdIncludedAsSender(header, perspective_);
2066 DCHECK_EQ(CONNECTION_ID_ABSENT,
dschinazic075ffa2019-06-27 16:17:37 -07002067 GetClientConnectionIdIncludedAsSender(header, perspective_))
2068 << ENDPOINT << ParsedQuicVersionToString(version_)
2069 << " invalid header: " << header;
QUICHE team2252b702019-05-14 23:55:14 -04002070
dschinazi7b9278c2019-05-20 07:36:21 -07002071 switch (server_connection_id_included) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002072 case CONNECTION_ID_ABSENT:
2073 if (!writer->WriteUInt8(public_flags |
2074 PACKET_PUBLIC_FLAGS_0BYTE_CONNECTION_ID)) {
2075 return false;
2076 }
2077 break;
2078 case CONNECTION_ID_PRESENT:
2079 QUIC_BUG_IF(!QuicUtils::IsConnectionIdValidForVersion(
dschinazi7b9278c2019-05-20 07:36:21 -07002080 server_connection_id, transport_version()))
QUICHE teama6ef0a62019-03-07 20:34:33 -05002081 << "AppendPacketHeader: attempted to use connection ID "
dschinazi7b9278c2019-05-20 07:36:21 -07002082 << server_connection_id << " which is invalid with version "
QUICHE teama6ef0a62019-03-07 20:34:33 -05002083 << QuicVersionToString(transport_version());
2084
2085 public_flags |= PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID;
2086 if (perspective_ == Perspective::IS_CLIENT) {
2087 public_flags |= PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID_OLD;
2088 }
2089 if (!writer->WriteUInt8(public_flags) ||
dschinazi7b9278c2019-05-20 07:36:21 -07002090 !writer->WriteConnectionId(server_connection_id)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002091 return false;
2092 }
2093 break;
2094 }
dschinazi7b9278c2019-05-20 07:36:21 -07002095 last_serialized_server_connection_id_ = server_connection_id;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002096
2097 if (header.version_flag) {
2098 DCHECK_EQ(Perspective::IS_CLIENT, perspective_);
2099 QuicVersionLabel version_label = CreateQuicVersionLabel(version_);
nharpereaab5ad2019-05-31 12:23:25 -07002100 if (!writer->WriteUInt32(version_label)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002101 return false;
2102 }
2103
2104 QUIC_DVLOG(1) << ENDPOINT << "label = '"
2105 << QuicVersionLabelToString(version_label) << "'";
2106 }
2107
2108 if (header.nonce != nullptr &&
2109 !writer->WriteBytes(header.nonce, kDiversificationNonceSize)) {
2110 return false;
2111 }
2112
2113 if (!AppendPacketNumber(header.packet_number_length, header.packet_number,
2114 writer)) {
2115 return false;
2116 }
2117
2118 return true;
2119}
2120
2121bool QuicFramer::AppendIetfHeaderTypeByte(const QuicPacketHeader& header,
2122 QuicDataWriter* writer) {
2123 uint8_t type = 0;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002124 if (header.version_flag) {
2125 type = static_cast<uint8_t>(
fayang36825da2019-08-21 14:01:27 -07002126 FLAGS_LONG_HEADER | FLAGS_FIXED_BIT |
2127 LongHeaderTypeToOnWireValue(header.long_packet_type) |
2128 PacketNumberLengthToOnWireValue(header.packet_number_length));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002129 } else {
fayang36825da2019-08-21 14:01:27 -07002130 type = static_cast<uint8_t>(
2131 FLAGS_FIXED_BIT |
2132 PacketNumberLengthToOnWireValue(header.packet_number_length));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002133 }
2134 return writer->WriteUInt8(type);
2135}
2136
2137bool QuicFramer::AppendIetfPacketHeader(const QuicPacketHeader& header,
2138 QuicDataWriter* writer,
2139 size_t* length_field_offset) {
2140 QUIC_DVLOG(1) << ENDPOINT << "Appending IETF header: " << header;
QUICHE team2252b702019-05-14 23:55:14 -04002141 QuicConnectionId server_connection_id =
2142 GetServerConnectionIdAsSender(header, perspective_);
2143 QUIC_BUG_IF(!QuicUtils::IsConnectionIdValidForVersion(server_connection_id,
2144 transport_version()))
QUICHE teama6ef0a62019-03-07 20:34:33 -05002145 << "AppendIetfPacketHeader: attempted to use connection ID "
QUICHE team2252b702019-05-14 23:55:14 -04002146 << server_connection_id << " which is invalid with version "
QUICHE teama6ef0a62019-03-07 20:34:33 -05002147 << QuicVersionToString(transport_version());
2148 if (!AppendIetfHeaderTypeByte(header, writer)) {
2149 return false;
2150 }
2151
2152 if (header.version_flag) {
2153 // Append version for long header.
2154 QuicVersionLabel version_label = CreateQuicVersionLabel(version_);
nharpereaab5ad2019-05-31 12:23:25 -07002155 if (!writer->WriteUInt32(version_label)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002156 return false;
2157 }
2158 }
2159
2160 // Append connection ID.
dschinazi1f485a12019-05-13 11:57:01 -07002161 if (!AppendIetfConnectionIds(
dschinazi48ac9192019-07-31 00:07:26 -07002162 header.version_flag, version_.HasLengthPrefixedConnectionIds(),
dschinazi1f485a12019-05-13 11:57:01 -07002163 header.destination_connection_id_included != CONNECTION_ID_ABSENT
2164 ? header.destination_connection_id
2165 : EmptyQuicConnectionId(),
2166 header.source_connection_id_included != CONNECTION_ID_ABSENT
2167 ? header.source_connection_id
2168 : EmptyQuicConnectionId(),
2169 writer)) {
2170 return false;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002171 }
dschinazi1f485a12019-05-13 11:57:01 -07002172
dschinazi7b9278c2019-05-20 07:36:21 -07002173 last_serialized_server_connection_id_ = server_connection_id;
dschinazi346b7ce2019-06-05 01:38:18 -07002174 if (version_.SupportsClientConnectionIds()) {
2175 last_serialized_client_connection_id_ =
2176 GetClientConnectionIdAsSender(header, perspective_);
2177 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002178
2179 if (QuicVersionHasLongHeaderLengths(transport_version()) &&
2180 header.version_flag) {
2181 if (header.long_packet_type == INITIAL) {
dschinazic075ffa2019-06-27 16:17:37 -07002182 DCHECK_NE(VARIABLE_LENGTH_INTEGER_LENGTH_0,
2183 header.retry_token_length_length)
2184 << ENDPOINT << ParsedQuicVersionToString(version_)
2185 << " bad retry token length length in header: " << header;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002186 // Write retry token length.
2187 if (!writer->WriteVarInt62(header.retry_token.length(),
2188 header.retry_token_length_length)) {
2189 return false;
2190 }
2191 // Write retry token.
2192 if (!header.retry_token.empty() &&
2193 !writer->WriteStringPiece(header.retry_token)) {
2194 return false;
2195 }
2196 }
2197 if (length_field_offset != nullptr) {
2198 *length_field_offset = writer->length();
2199 }
2200 // Add fake length to reserve two bytes to add length in later.
2201 writer->WriteVarInt62(256);
2202 } else if (length_field_offset != nullptr) {
2203 *length_field_offset = 0;
2204 }
2205
2206 // Append packet number.
2207 if (!AppendPacketNumber(header.packet_number_length, header.packet_number,
2208 writer)) {
2209 return false;
2210 }
nharper55fa6132019-05-07 19:37:21 -07002211 last_written_packet_number_length_ = header.packet_number_length;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002212
2213 if (!header.version_flag) {
2214 return true;
2215 }
2216
2217 if (header.nonce != nullptr) {
2218 DCHECK(header.version_flag);
2219 DCHECK_EQ(ZERO_RTT_PROTECTED, header.long_packet_type);
2220 DCHECK_EQ(Perspective::IS_SERVER, perspective_);
2221 if (!writer->WriteBytes(header.nonce, kDiversificationNonceSize)) {
2222 return false;
2223 }
2224 }
2225
2226 return true;
2227}
2228
2229const QuicTime::Delta QuicFramer::CalculateTimestampFromWire(
2230 uint32_t time_delta_us) {
2231 // The new time_delta might have wrapped to the next epoch, or it
2232 // might have reverse wrapped to the previous epoch, or it might
2233 // remain in the same epoch. Select the time closest to the previous
2234 // time.
2235 //
2236 // epoch_delta is the delta between epochs. A delta is 4 bytes of
2237 // microseconds.
2238 const uint64_t epoch_delta = UINT64_C(1) << 32;
2239 uint64_t epoch = last_timestamp_.ToMicroseconds() & ~(epoch_delta - 1);
2240 // Wrapping is safe here because a wrapped value will not be ClosestTo below.
2241 uint64_t prev_epoch = epoch - epoch_delta;
2242 uint64_t next_epoch = epoch + epoch_delta;
2243
2244 uint64_t time = ClosestTo(
2245 last_timestamp_.ToMicroseconds(), epoch + time_delta_us,
2246 ClosestTo(last_timestamp_.ToMicroseconds(), prev_epoch + time_delta_us,
2247 next_epoch + time_delta_us));
2248
2249 return QuicTime::Delta::FromMicroseconds(time);
2250}
2251
2252uint64_t QuicFramer::CalculatePacketNumberFromWire(
2253 QuicPacketNumberLength packet_number_length,
2254 QuicPacketNumber base_packet_number,
2255 uint64_t packet_number) const {
2256 // The new packet number might have wrapped to the next epoch, or
2257 // it might have reverse wrapped to the previous epoch, or it might
2258 // remain in the same epoch. Select the packet number closest to the
2259 // next expected packet number, the previous packet number plus 1.
2260
2261 // epoch_delta is the delta between epochs the packet number was serialized
2262 // with, so the correct value is likely the same epoch as the last sequence
2263 // number or an adjacent epoch.
2264 if (!base_packet_number.IsInitialized()) {
2265 return packet_number;
2266 }
2267 const uint64_t epoch_delta = UINT64_C(1) << (8 * packet_number_length);
2268 uint64_t next_packet_number = base_packet_number.ToUint64() + 1;
2269 uint64_t epoch = base_packet_number.ToUint64() & ~(epoch_delta - 1);
2270 uint64_t prev_epoch = epoch - epoch_delta;
2271 uint64_t next_epoch = epoch + epoch_delta;
2272
2273 return ClosestTo(next_packet_number, epoch + packet_number,
2274 ClosestTo(next_packet_number, prev_epoch + packet_number,
2275 next_epoch + packet_number));
2276}
2277
2278bool QuicFramer::ProcessPublicHeader(QuicDataReader* reader,
2279 bool packet_has_ietf_packet_header,
2280 QuicPacketHeader* header) {
2281 if (packet_has_ietf_packet_header) {
2282 return ProcessIetfPacketHeader(reader, header);
2283 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002284 uint8_t public_flags;
2285 if (!reader->ReadBytes(&public_flags, 1)) {
2286 set_detailed_error("Unable to read public flags.");
2287 return false;
2288 }
2289
2290 header->reset_flag = (public_flags & PACKET_PUBLIC_FLAGS_RST) != 0;
2291 header->version_flag = (public_flags & PACKET_PUBLIC_FLAGS_VERSION) != 0;
2292
2293 if (validate_flags_ && !header->version_flag &&
2294 public_flags > PACKET_PUBLIC_FLAGS_MAX) {
2295 set_detailed_error("Illegal public flags value.");
2296 return false;
2297 }
2298
2299 if (header->reset_flag && header->version_flag) {
2300 set_detailed_error("Got version flag in reset packet");
2301 return false;
2302 }
2303
QUICHE team2252b702019-05-14 23:55:14 -04002304 QuicConnectionId* header_connection_id = &header->destination_connection_id;
2305 QuicConnectionIdIncluded* header_connection_id_included =
2306 &header->destination_connection_id_included;
dschinazi5e1a7b22019-07-31 12:23:21 -07002307 if (perspective_ == Perspective::IS_CLIENT) {
QUICHE team2252b702019-05-14 23:55:14 -04002308 header_connection_id = &header->source_connection_id;
2309 header_connection_id_included = &header->source_connection_id_included;
2310 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002311 switch (public_flags & PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID) {
2312 case PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID:
QUICHE team2252b702019-05-14 23:55:14 -04002313 if (!reader->ReadConnectionId(header_connection_id,
QUICHE teama6ef0a62019-03-07 20:34:33 -05002314 kQuicDefaultConnectionIdLength)) {
2315 set_detailed_error("Unable to read ConnectionId.");
2316 return false;
2317 }
QUICHE team2252b702019-05-14 23:55:14 -04002318 *header_connection_id_included = CONNECTION_ID_PRESENT;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002319 break;
2320 case PACKET_PUBLIC_FLAGS_0BYTE_CONNECTION_ID:
QUICHE team2252b702019-05-14 23:55:14 -04002321 *header_connection_id_included = CONNECTION_ID_ABSENT;
dschinazi7b9278c2019-05-20 07:36:21 -07002322 *header_connection_id = last_serialized_server_connection_id_;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002323 break;
2324 }
2325
2326 header->packet_number_length = ReadSequenceNumberLength(
2327 public_flags >> kPublicHeaderSequenceNumberShift);
2328
2329 // Read the version only if the packet is from the client.
2330 // version flag from the server means version negotiation packet.
2331 if (header->version_flag && perspective_ == Perspective::IS_SERVER) {
2332 QuicVersionLabel version_label;
fayang40315542019-05-09 09:19:09 -07002333 if (!ProcessVersionLabel(reader, &version_label)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002334 set_detailed_error("Unable to read protocol version.");
2335 return false;
2336 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002337 // If the version from the new packet is the same as the version of this
2338 // framer, then the public flags should be set to something we understand.
2339 // If not, this raises an error.
QUICHE teama6ef0a62019-03-07 20:34:33 -05002340 ParsedQuicVersion version = ParseQuicVersionLabel(version_label);
2341 if (version == version_ && public_flags > PACKET_PUBLIC_FLAGS_MAX) {
2342 set_detailed_error("Illegal public flags value.");
2343 return false;
2344 }
2345 header->version = version;
2346 }
2347
2348 // A nonce should only be present in packets from the server to the client,
2349 // which are neither version negotiation nor public reset packets.
2350 if (public_flags & PACKET_PUBLIC_FLAGS_NONCE &&
2351 !(public_flags & PACKET_PUBLIC_FLAGS_VERSION) &&
2352 !(public_flags & PACKET_PUBLIC_FLAGS_RST) &&
2353 // The nonce flag from a client is ignored and is assumed to be an older
2354 // client indicating an eight-byte connection ID.
2355 perspective_ == Perspective::IS_CLIENT) {
2356 if (!reader->ReadBytes(reinterpret_cast<uint8_t*>(last_nonce_.data()),
2357 last_nonce_.size())) {
2358 set_detailed_error("Unable to read nonce.");
2359 return false;
2360 }
2361 header->nonce = &last_nonce_;
2362 } else {
2363 header->nonce = nullptr;
2364 }
2365
2366 return true;
2367}
2368
2369// static
2370QuicPacketNumberLength QuicFramer::GetMinPacketNumberLength(
dschinazi17d42422019-06-18 16:35:07 -07002371 QuicTransportVersion /*version*/,
QUICHE teama6ef0a62019-03-07 20:34:33 -05002372 QuicPacketNumber packet_number) {
2373 DCHECK(packet_number.IsInitialized());
2374 if (packet_number < QuicPacketNumber(1 << (PACKET_1BYTE_PACKET_NUMBER * 8))) {
2375 return PACKET_1BYTE_PACKET_NUMBER;
2376 } else if (packet_number <
2377 QuicPacketNumber(1 << (PACKET_2BYTE_PACKET_NUMBER * 8))) {
2378 return PACKET_2BYTE_PACKET_NUMBER;
2379 } else if (packet_number <
2380 QuicPacketNumber(UINT64_C(1)
2381 << (PACKET_4BYTE_PACKET_NUMBER * 8))) {
2382 return PACKET_4BYTE_PACKET_NUMBER;
2383 } else {
2384 return PACKET_6BYTE_PACKET_NUMBER;
2385 }
2386}
2387
2388// static
2389uint8_t QuicFramer::GetPacketNumberFlags(
2390 QuicPacketNumberLength packet_number_length) {
2391 switch (packet_number_length) {
2392 case PACKET_1BYTE_PACKET_NUMBER:
2393 return PACKET_FLAGS_1BYTE_PACKET;
2394 case PACKET_2BYTE_PACKET_NUMBER:
2395 return PACKET_FLAGS_2BYTE_PACKET;
2396 case PACKET_4BYTE_PACKET_NUMBER:
2397 return PACKET_FLAGS_4BYTE_PACKET;
2398 case PACKET_6BYTE_PACKET_NUMBER:
2399 case PACKET_8BYTE_PACKET_NUMBER:
2400 return PACKET_FLAGS_8BYTE_PACKET;
2401 default:
2402 QUIC_BUG << "Unreachable case statement.";
2403 return PACKET_FLAGS_8BYTE_PACKET;
2404 }
2405}
2406
2407// static
2408QuicFramer::AckFrameInfo QuicFramer::GetAckFrameInfo(
2409 const QuicAckFrame& frame) {
2410 AckFrameInfo new_ack_info;
2411 if (frame.packets.Empty()) {
2412 return new_ack_info;
2413 }
2414 // The first block is the last interval. It isn't encoded with the gap-length
2415 // encoding, so skip it.
2416 new_ack_info.first_block_length = frame.packets.LastIntervalLength();
2417 auto itr = frame.packets.rbegin();
2418 QuicPacketNumber previous_start = itr->min();
2419 new_ack_info.max_block_length = PacketNumberIntervalLength(*itr);
2420 ++itr;
2421
2422 // Don't do any more work after getting information for 256 ACK blocks; any
2423 // more can't be encoded anyway.
2424 for (; itr != frame.packets.rend() &&
2425 new_ack_info.num_ack_blocks < std::numeric_limits<uint8_t>::max();
2426 previous_start = itr->min(), ++itr) {
2427 const auto& interval = *itr;
2428 const QuicPacketCount total_gap = previous_start - interval.max();
2429 new_ack_info.num_ack_blocks +=
2430 (total_gap + std::numeric_limits<uint8_t>::max() - 1) /
2431 std::numeric_limits<uint8_t>::max();
2432 new_ack_info.max_block_length = std::max(
2433 new_ack_info.max_block_length, PacketNumberIntervalLength(interval));
2434 }
2435 return new_ack_info;
2436}
2437
2438bool QuicFramer::ProcessUnauthenticatedHeader(QuicDataReader* encrypted_reader,
2439 QuicPacketHeader* header) {
QUICHE team10b22a12019-03-21 15:31:42 -07002440 QuicPacketNumber base_packet_number;
2441 if (supports_multiple_packet_number_spaces_) {
nharper55fa6132019-05-07 19:37:21 -07002442 PacketNumberSpace pn_space = GetPacketNumberSpace(*header);
2443 if (pn_space == NUM_PACKET_NUMBER_SPACES) {
2444 set_detailed_error("Unable to determine packet number space.");
2445 return RaiseError(QUIC_INVALID_PACKET_HEADER);
2446 }
2447 base_packet_number = largest_decrypted_packet_numbers_[pn_space];
QUICHE team10b22a12019-03-21 15:31:42 -07002448 } else {
2449 base_packet_number = largest_packet_number_;
2450 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002451 uint64_t full_packet_number;
2452 if (!ProcessAndCalculatePacketNumber(
2453 encrypted_reader, header->packet_number_length, base_packet_number,
2454 &full_packet_number)) {
2455 set_detailed_error("Unable to read packet number.");
2456 return RaiseError(QUIC_INVALID_PACKET_HEADER);
2457 }
2458
2459 if (!IsValidFullPacketNumber(full_packet_number, transport_version())) {
2460 set_detailed_error("packet numbers cannot be 0.");
2461 return RaiseError(QUIC_INVALID_PACKET_HEADER);
2462 }
2463 header->packet_number = QuicPacketNumber(full_packet_number);
2464
2465 if (!visitor_->OnUnauthenticatedHeader(*header)) {
2466 set_detailed_error(
2467 "Visitor asked to stop processing of unauthenticated header.");
2468 return false;
2469 }
nharper3f283562019-05-02 16:37:12 -07002470 // The function we are in is called because the framer believes that it is
2471 // processing a packet that uses the non-IETF (i.e. Google QUIC) packet header
2472 // type. Usually, the framer makes that decision based on the framer's
2473 // version, but when the framer is used with Perspective::IS_SERVER, then
2474 // before version negotiation is complete (specifically, before
2475 // InferPacketHeaderTypeFromVersion is called), this decision is made based on
2476 // the type byte of the packet.
2477 //
2478 // If the framer's version KnowsWhichDecrypterToUse, then that version expects
2479 // to use the IETF packet header type. If that's the case and we're in this
2480 // function, then the packet received is invalid: the framer was expecting an
2481 // IETF packet header and didn't get one.
2482 if (version().KnowsWhichDecrypterToUse()) {
nharpera745e392019-04-19 12:05:15 -07002483 set_detailed_error("Invalid public header type for expected version.");
2484 return RaiseError(QUIC_INVALID_PACKET_HEADER);
2485 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002486 return true;
2487}
2488
2489bool QuicFramer::ProcessIetfHeaderTypeByte(QuicDataReader* reader,
2490 QuicPacketHeader* header) {
2491 uint8_t type;
2492 if (!reader->ReadBytes(&type, 1)) {
dschinazi48ac9192019-07-31 00:07:26 -07002493 set_detailed_error("Unable to read first byte.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05002494 return false;
2495 }
dschinazi244f6dc2019-05-06 15:45:16 -07002496 header->type_byte = type;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002497 // Determine whether this is a long or short header.
fayangccbab732019-05-13 10:11:25 -07002498 header->form = GetIetfPacketHeaderFormat(type);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002499 if (header->form == IETF_QUIC_LONG_HEADER_PACKET) {
2500 // Version is always present in long headers.
2501 header->version_flag = true;
dschinazi346b7ce2019-06-05 01:38:18 -07002502 // In versions that do not support client connection IDs, we mark the
2503 // corresponding connection ID as absent.
QUICHE teama6ef0a62019-03-07 20:34:33 -05002504 header->destination_connection_id_included =
dschinazi346b7ce2019-06-05 01:38:18 -07002505 (perspective_ == Perspective::IS_SERVER ||
2506 version_.SupportsClientConnectionIds())
2507 ? CONNECTION_ID_PRESENT
2508 : CONNECTION_ID_ABSENT;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002509 header->source_connection_id_included =
dschinazi346b7ce2019-06-05 01:38:18 -07002510 (perspective_ == Perspective::IS_CLIENT ||
2511 version_.SupportsClientConnectionIds())
2512 ? CONNECTION_ID_PRESENT
2513 : CONNECTION_ID_ABSENT;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002514 // Read version tag.
2515 QuicVersionLabel version_label;
fayang40315542019-05-09 09:19:09 -07002516 if (!ProcessVersionLabel(reader, &version_label)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002517 set_detailed_error("Unable to read protocol version.");
2518 return false;
2519 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002520 if (!version_label) {
2521 // Version label is 0 indicating this is a version negotiation packet.
2522 header->long_packet_type = VERSION_NEGOTIATION;
2523 } else {
2524 header->version = ParseQuicVersionLabel(version_label);
2525 if (header->version.transport_version != QUIC_VERSION_UNSUPPORTED) {
fayang36825da2019-08-21 14:01:27 -07002526 if (!(type & FLAGS_FIXED_BIT)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002527 set_detailed_error("Fixed bit is 0 in long header.");
2528 return false;
2529 }
fayang36825da2019-08-21 14:01:27 -07002530 if (!GetLongHeaderType(type, &header->long_packet_type)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002531 set_detailed_error("Illegal long header type value.");
2532 return false;
2533 }
dschinazi244f6dc2019-05-06 15:45:16 -07002534 if (header->long_packet_type == RETRY) {
2535 if (!version().SupportsRetry()) {
2536 set_detailed_error("RETRY not supported in this version.");
2537 return false;
2538 }
2539 if (perspective_ == Perspective::IS_SERVER) {
2540 set_detailed_error("Client-initiated RETRY is invalid.");
2541 return false;
2542 }
nharper55fa6132019-05-07 19:37:21 -07002543 } else if (!header->version.HasHeaderProtection()) {
fayang36825da2019-08-21 14:01:27 -07002544 header->packet_number_length = GetLongHeaderPacketNumberLength(type);
nharper2ceb97c2019-04-19 11:38:59 -07002545 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002546 }
2547 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002548
2549 QUIC_DVLOG(1) << ENDPOINT << "Received IETF long header: "
2550 << QuicUtils::QuicLongHeaderTypetoString(
2551 header->long_packet_type);
2552 return true;
2553 }
2554
2555 QUIC_DVLOG(1) << ENDPOINT << "Received IETF short header";
2556 // Version is not present in short headers.
2557 header->version_flag = false;
dschinazi346b7ce2019-06-05 01:38:18 -07002558 // In versions that do not support client connection IDs, the client will not
2559 // receive destination connection IDs.
QUICHE teama6ef0a62019-03-07 20:34:33 -05002560 header->destination_connection_id_included =
dschinazi346b7ce2019-06-05 01:38:18 -07002561 (perspective_ == Perspective::IS_SERVER ||
2562 version_.SupportsClientConnectionIds())
2563 ? CONNECTION_ID_PRESENT
2564 : CONNECTION_ID_ABSENT;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002565 header->source_connection_id_included = CONNECTION_ID_ABSENT;
fayang36825da2019-08-21 14:01:27 -07002566 if (!(type & FLAGS_FIXED_BIT)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002567 set_detailed_error("Fixed bit is 0 in short header.");
2568 return false;
2569 }
fayang36825da2019-08-21 14:01:27 -07002570 if (!header->version.HasHeaderProtection()) {
2571 header->packet_number_length = GetShortHeaderPacketNumberLength(type);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002572 }
2573 QUIC_DVLOG(1) << "packet_number_length = " << header->packet_number_length;
2574 return true;
2575}
2576
fayang40315542019-05-09 09:19:09 -07002577// static
2578bool QuicFramer::ProcessVersionLabel(QuicDataReader* reader,
2579 QuicVersionLabel* version_label) {
nharpereaab5ad2019-05-31 12:23:25 -07002580 if (!reader->ReadUInt32(version_label)) {
fayang40315542019-05-09 09:19:09 -07002581 return false;
2582 }
fayang40315542019-05-09 09:19:09 -07002583 return true;
2584}
2585
2586// static
fayangccbab732019-05-13 10:11:25 -07002587bool QuicFramer::ProcessAndValidateIetfConnectionIdLength(
2588 QuicDataReader* reader,
fayang40315542019-05-09 09:19:09 -07002589 ParsedQuicVersion version,
dschinazi334f0232019-05-29 16:08:53 -07002590 Perspective perspective,
dschinazi8ff74822019-05-28 16:37:20 -07002591 bool should_update_expected_server_connection_id_length,
2592 uint8_t* expected_server_connection_id_length,
fayang40315542019-05-09 09:19:09 -07002593 uint8_t* destination_connection_id_length,
fayangccbab732019-05-13 10:11:25 -07002594 uint8_t* source_connection_id_length,
2595 std::string* detailed_error) {
2596 uint8_t connection_id_lengths_byte;
2597 if (!reader->ReadBytes(&connection_id_lengths_byte, 1)) {
2598 *detailed_error = "Unable to read ConnectionId length.";
2599 return false;
2600 }
fayang40315542019-05-09 09:19:09 -07002601 uint8_t dcil =
2602 (connection_id_lengths_byte & kDestinationConnectionIdLengthMask) >> 4;
2603 if (dcil != 0) {
2604 dcil += kConnectionIdLengthAdjustment;
2605 }
fayang40315542019-05-09 09:19:09 -07002606 uint8_t scil = connection_id_lengths_byte & kSourceConnectionIdLengthMask;
2607 if (scil != 0) {
2608 scil += kConnectionIdLengthAdjustment;
2609 }
dschinazi334f0232019-05-29 16:08:53 -07002610 if (should_update_expected_server_connection_id_length) {
2611 uint8_t server_connection_id_length =
2612 perspective == Perspective::IS_SERVER ? dcil : scil;
2613 if (*expected_server_connection_id_length != server_connection_id_length) {
2614 QUIC_DVLOG(1) << "Updating expected_server_connection_id_length: "
2615 << static_cast<int>(*expected_server_connection_id_length)
2616 << " -> " << static_cast<int>(server_connection_id_length);
2617 *expected_server_connection_id_length = server_connection_id_length;
2618 }
2619 }
dschinazi8ff74822019-05-28 16:37:20 -07002620 if (!should_update_expected_server_connection_id_length &&
fayangde8a2222019-05-16 10:52:39 -07002621 (dcil != *destination_connection_id_length ||
fayang40315542019-05-09 09:19:09 -07002622 scil != *source_connection_id_length) &&
fayang40315542019-05-09 09:19:09 -07002623 !QuicUtils::VariableLengthConnectionIdAllowedForVersion(
2624 version.transport_version)) {
2625 // TODO(dschinazi): use the framer's version once the
2626 // OnProtocolVersionMismatch call is moved to before this is run.
2627 QUIC_DVLOG(1) << "dcil: " << static_cast<uint32_t>(dcil)
2628 << ", scil: " << static_cast<uint32_t>(scil);
fayangccbab732019-05-13 10:11:25 -07002629 *detailed_error = "Invalid ConnectionId length.";
fayang40315542019-05-09 09:19:09 -07002630 return false;
2631 }
2632 *destination_connection_id_length = dcil;
2633 *source_connection_id_length = scil;
2634 return true;
2635}
2636
dschinazib953d022019-08-01 18:05:58 -07002637bool QuicFramer::ValidateReceivedConnectionIds(const QuicPacketHeader& header) {
2638 if (!QuicUtils::IsConnectionIdValidForVersion(
2639 GetServerConnectionIdAsRecipient(header, perspective_),
2640 transport_version())) {
2641 set_detailed_error("Received server connection ID with invalid length.");
2642 return false;
2643 }
2644
2645 if (version_.SupportsClientConnectionIds() &&
2646 !QuicUtils::IsConnectionIdValidForVersion(
2647 GetClientConnectionIdAsRecipient(header, perspective_),
2648 transport_version())) {
2649 set_detailed_error("Received client connection ID with invalid length.");
2650 return false;
2651 }
2652 return true;
2653}
2654
QUICHE teama6ef0a62019-03-07 20:34:33 -05002655bool QuicFramer::ProcessIetfPacketHeader(QuicDataReader* reader,
2656 QuicPacketHeader* header) {
dschinazi48ac9192019-07-31 00:07:26 -07002657 if (version_.HasLengthPrefixedConnectionIds()) {
2658 uint8_t expected_destination_connection_id_length =
2659 perspective_ == Perspective::IS_CLIENT
2660 ? expected_client_connection_id_length_
2661 : expected_server_connection_id_length_;
2662 QuicVersionLabel version_label;
2663 bool has_length_prefix;
2664 std::string detailed_error;
2665 QuicErrorCode parse_result = QuicFramer::ParsePublicHeader(
2666 reader, expected_destination_connection_id_length,
2667 VersionHasIetfInvariantHeader(version_.transport_version),
2668 &header->type_byte, &header->form, &header->version_flag,
2669 &has_length_prefix, &version_label, &header->version,
2670 &header->destination_connection_id, &header->source_connection_id,
2671 &header->long_packet_type, &header->retry_token_length_length,
2672 &header->retry_token, &detailed_error);
2673 if (parse_result != QUIC_NO_ERROR) {
2674 set_detailed_error(detailed_error);
2675 return false;
2676 }
2677 header->destination_connection_id_included = CONNECTION_ID_PRESENT;
2678 header->source_connection_id_included =
2679 header->version_flag ? CONNECTION_ID_PRESENT : CONNECTION_ID_ABSENT;
2680 if (header->source_connection_id_included == CONNECTION_ID_ABSENT) {
2681 DCHECK(header->source_connection_id.IsEmpty());
2682 if (perspective_ == Perspective::IS_CLIENT) {
2683 header->source_connection_id = last_serialized_server_connection_id_;
2684 } else {
2685 header->source_connection_id = last_serialized_client_connection_id_;
2686 }
2687 }
dschinazib953d022019-08-01 18:05:58 -07002688
2689 if (!ValidateReceivedConnectionIds(*header)) {
2690 return false;
2691 }
2692
dschinazi48ac9192019-07-31 00:07:26 -07002693 if (header->version_flag &&
fayang36825da2019-08-21 14:01:27 -07002694 header->long_packet_type != VERSION_NEGOTIATION &&
dschinazi48ac9192019-07-31 00:07:26 -07002695 !(header->type_byte & FLAGS_FIXED_BIT)) {
2696 set_detailed_error("Fixed bit is 0 in long header.");
2697 return false;
2698 }
fayang36825da2019-08-21 14:01:27 -07002699 if (!header->version_flag && !(header->type_byte & FLAGS_FIXED_BIT)) {
dschinazi48ac9192019-07-31 00:07:26 -07002700 set_detailed_error("Fixed bit is 0 in short header.");
2701 return false;
2702 }
2703 if (!header->version_flag) {
fayang36825da2019-08-21 14:01:27 -07002704 if (!version_.HasHeaderProtection()) {
2705 header->packet_number_length =
2706 GetShortHeaderPacketNumberLength(header->type_byte);
dschinazi48ac9192019-07-31 00:07:26 -07002707 }
2708 return true;
2709 }
2710 if (header->long_packet_type == RETRY) {
2711 if (!version().SupportsRetry()) {
2712 set_detailed_error("RETRY not supported in this version.");
2713 return false;
2714 }
2715 if (perspective_ == Perspective::IS_SERVER) {
2716 set_detailed_error("Client-initiated RETRY is invalid.");
2717 return false;
2718 }
2719 return true;
2720 }
2721 if (!header->version.HasHeaderProtection()) {
fayang36825da2019-08-21 14:01:27 -07002722 header->packet_number_length =
2723 GetLongHeaderPacketNumberLength(header->type_byte);
dschinazi48ac9192019-07-31 00:07:26 -07002724 }
2725
2726 return true;
2727 }
2728
QUICHE teama6ef0a62019-03-07 20:34:33 -05002729 if (!ProcessIetfHeaderTypeByte(reader, header)) {
2730 return false;
2731 }
2732
2733 uint8_t destination_connection_id_length =
2734 header->destination_connection_id_included == CONNECTION_ID_PRESENT
dschinazi346b7ce2019-06-05 01:38:18 -07002735 ? (perspective_ == Perspective::IS_SERVER
2736 ? expected_server_connection_id_length_
2737 : expected_client_connection_id_length_)
QUICHE teama6ef0a62019-03-07 20:34:33 -05002738 : 0;
2739 uint8_t source_connection_id_length =
2740 header->source_connection_id_included == CONNECTION_ID_PRESENT
dschinazi346b7ce2019-06-05 01:38:18 -07002741 ? (perspective_ == Perspective::IS_CLIENT
2742 ? expected_server_connection_id_length_
2743 : expected_client_connection_id_length_)
QUICHE teama6ef0a62019-03-07 20:34:33 -05002744 : 0;
2745 if (header->form == IETF_QUIC_LONG_HEADER_PACKET) {
fayangccbab732019-05-13 10:11:25 -07002746 if (!ProcessAndValidateIetfConnectionIdLength(
dschinazi334f0232019-05-29 16:08:53 -07002747 reader, header->version, perspective_,
fayang91475c42019-06-19 08:04:26 -07002748 /*should_update_expected_server_connection_id_length=*/false,
dschinazi8ff74822019-05-28 16:37:20 -07002749 &expected_server_connection_id_length_,
2750 &destination_connection_id_length, &source_connection_id_length,
2751 &detailed_error_)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002752 return false;
2753 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002754 }
2755
2756 // Read connection ID.
2757 if (!reader->ReadConnectionId(&header->destination_connection_id,
2758 destination_connection_id_length)) {
dschinazi48ac9192019-07-31 00:07:26 -07002759 set_detailed_error("Unable to read destination connection ID.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05002760 return false;
2761 }
2762
2763 if (!reader->ReadConnectionId(&header->source_connection_id,
2764 source_connection_id_length)) {
dschinazi48ac9192019-07-31 00:07:26 -07002765 set_detailed_error("Unable to read source connection ID.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05002766 return false;
2767 }
2768
dschinazi5e1a7b22019-07-31 12:23:21 -07002769 if (header->source_connection_id_included == CONNECTION_ID_ABSENT) {
2770 if (!header->source_connection_id.IsEmpty()) {
2771 DCHECK(!version_.SupportsClientConnectionIds());
2772 set_detailed_error("Client connection ID not supported in this version.");
2773 return false;
QUICHE team2252b702019-05-14 23:55:14 -04002774 }
dschinazi5e1a7b22019-07-31 12:23:21 -07002775 if (perspective_ == Perspective::IS_CLIENT) {
2776 header->source_connection_id = last_serialized_server_connection_id_;
2777 } else {
2778 header->source_connection_id = last_serialized_client_connection_id_;
QUICHE team2252b702019-05-14 23:55:14 -04002779 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002780 }
2781
dschinazib953d022019-08-01 18:05:58 -07002782 return ValidateReceivedConnectionIds(*header);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002783}
2784
2785bool QuicFramer::ProcessAndCalculatePacketNumber(
2786 QuicDataReader* reader,
2787 QuicPacketNumberLength packet_number_length,
2788 QuicPacketNumber base_packet_number,
2789 uint64_t* packet_number) {
2790 uint64_t wire_packet_number;
2791 if (!reader->ReadBytesToUInt64(packet_number_length, &wire_packet_number)) {
2792 return false;
2793 }
2794
2795 // TODO(ianswett): Explore the usefulness of trying multiple packet numbers
2796 // in case the first guess is incorrect.
2797 *packet_number = CalculatePacketNumberFromWire(
2798 packet_number_length, base_packet_number, wire_packet_number);
2799 return true;
2800}
2801
2802bool QuicFramer::ProcessFrameData(QuicDataReader* reader,
2803 const QuicPacketHeader& header) {
fkastenholz305e1732019-06-18 05:01:22 -07002804 DCHECK(!VersionHasIetfQuicFrames(version_.transport_version))
2805 << "IETF QUIC Framing negotiated but attempting to process frames as "
2806 "non-IETF QUIC.";
QUICHE teama6ef0a62019-03-07 20:34:33 -05002807 if (reader->IsDoneReading()) {
2808 set_detailed_error("Packet has no frames.");
2809 return RaiseError(QUIC_MISSING_PAYLOAD);
2810 }
dschinazi118934b2019-06-13 18:09:08 -07002811 QUIC_DVLOG(2) << ENDPOINT << "Processing packet with header " << header;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002812 while (!reader->IsDoneReading()) {
2813 uint8_t frame_type;
2814 if (!reader->ReadBytes(&frame_type, 1)) {
2815 set_detailed_error("Unable to read frame type.");
2816 return RaiseError(QUIC_INVALID_FRAME_DATA);
2817 }
fayang36825da2019-08-21 14:01:27 -07002818 const uint8_t special_mask = transport_version() <= QUIC_VERSION_43
QUICHE teama6ef0a62019-03-07 20:34:33 -05002819 ? kQuicFrameTypeBrokenMask
2820 : kQuicFrameTypeSpecialMask;
2821 if (frame_type & special_mask) {
2822 // Stream Frame
2823 if (frame_type & kQuicFrameTypeStreamMask) {
2824 QuicStreamFrame frame;
2825 if (!ProcessStreamFrame(reader, frame_type, &frame)) {
2826 return RaiseError(QUIC_INVALID_STREAM_DATA);
2827 }
dschinazi118934b2019-06-13 18:09:08 -07002828 QUIC_DVLOG(2) << ENDPOINT << "Processing stream frame " << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002829 if (!visitor_->OnStreamFrame(frame)) {
2830 QUIC_DVLOG(1) << ENDPOINT
2831 << "Visitor asked to stop further processing.";
2832 // Returning true since there was no parsing error.
2833 return true;
2834 }
2835 continue;
2836 }
2837
2838 // Ack Frame
2839 if (frame_type & kQuicFrameTypeAckMask) {
2840 if (!ProcessAckFrame(reader, frame_type)) {
2841 return RaiseError(QUIC_INVALID_ACK_DATA);
2842 }
dschinazi118934b2019-06-13 18:09:08 -07002843 QUIC_DVLOG(2) << ENDPOINT << "Processing ACK frame";
QUICHE teama6ef0a62019-03-07 20:34:33 -05002844 continue;
2845 }
2846
2847 // This was a special frame type that did not match any
2848 // of the known ones. Error.
2849 set_detailed_error("Illegal frame type.");
2850 QUIC_DLOG(WARNING) << ENDPOINT << "Illegal frame type: "
2851 << static_cast<int>(frame_type);
2852 return RaiseError(QUIC_INVALID_FRAME_DATA);
2853 }
2854
2855 switch (frame_type) {
2856 case PADDING_FRAME: {
2857 QuicPaddingFrame frame;
2858 ProcessPaddingFrame(reader, &frame);
dschinazi118934b2019-06-13 18:09:08 -07002859 QUIC_DVLOG(2) << ENDPOINT << "Processing padding frame " << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002860 if (!visitor_->OnPaddingFrame(frame)) {
2861 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
2862 // Returning true since there was no parsing error.
2863 return true;
2864 }
2865 continue;
2866 }
2867
2868 case RST_STREAM_FRAME: {
2869 QuicRstStreamFrame frame;
2870 if (!ProcessRstStreamFrame(reader, &frame)) {
2871 return RaiseError(QUIC_INVALID_RST_STREAM_DATA);
2872 }
dschinazi118934b2019-06-13 18:09:08 -07002873 QUIC_DVLOG(2) << ENDPOINT << "Processing reset stream frame " << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002874 if (!visitor_->OnRstStreamFrame(frame)) {
2875 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
2876 // Returning true since there was no parsing error.
2877 return true;
2878 }
2879 continue;
2880 }
2881
2882 case CONNECTION_CLOSE_FRAME: {
2883 QuicConnectionCloseFrame frame;
2884 if (!ProcessConnectionCloseFrame(reader, &frame)) {
2885 return RaiseError(QUIC_INVALID_CONNECTION_CLOSE_DATA);
2886 }
2887
dschinazi118934b2019-06-13 18:09:08 -07002888 QUIC_DVLOG(2) << ENDPOINT << "Processing connection close frame "
2889 << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002890 if (!visitor_->OnConnectionCloseFrame(frame)) {
2891 QUIC_DVLOG(1) << ENDPOINT
2892 << "Visitor asked to stop further processing.";
2893 // Returning true since there was no parsing error.
2894 return true;
2895 }
2896 continue;
2897 }
2898
2899 case GOAWAY_FRAME: {
2900 QuicGoAwayFrame goaway_frame;
2901 if (!ProcessGoAwayFrame(reader, &goaway_frame)) {
2902 return RaiseError(QUIC_INVALID_GOAWAY_DATA);
2903 }
dschinazi118934b2019-06-13 18:09:08 -07002904 QUIC_DVLOG(2) << ENDPOINT << "Processing go away frame "
2905 << goaway_frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002906 if (!visitor_->OnGoAwayFrame(goaway_frame)) {
2907 QUIC_DVLOG(1) << ENDPOINT
2908 << "Visitor asked to stop further processing.";
2909 // Returning true since there was no parsing error.
2910 return true;
2911 }
2912 continue;
2913 }
2914
2915 case WINDOW_UPDATE_FRAME: {
2916 QuicWindowUpdateFrame window_update_frame;
2917 if (!ProcessWindowUpdateFrame(reader, &window_update_frame)) {
2918 return RaiseError(QUIC_INVALID_WINDOW_UPDATE_DATA);
2919 }
dschinazi118934b2019-06-13 18:09:08 -07002920 QUIC_DVLOG(2) << ENDPOINT << "Processing window update frame "
2921 << window_update_frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002922 if (!visitor_->OnWindowUpdateFrame(window_update_frame)) {
2923 QUIC_DVLOG(1) << ENDPOINT
2924 << "Visitor asked to stop further processing.";
2925 // Returning true since there was no parsing error.
2926 return true;
2927 }
2928 continue;
2929 }
2930
2931 case BLOCKED_FRAME: {
2932 QuicBlockedFrame blocked_frame;
2933 if (!ProcessBlockedFrame(reader, &blocked_frame)) {
2934 return RaiseError(QUIC_INVALID_BLOCKED_DATA);
2935 }
dschinazi118934b2019-06-13 18:09:08 -07002936 QUIC_DVLOG(2) << ENDPOINT << "Processing blocked frame "
2937 << blocked_frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002938 if (!visitor_->OnBlockedFrame(blocked_frame)) {
2939 QUIC_DVLOG(1) << ENDPOINT
2940 << "Visitor asked to stop further processing.";
2941 // Returning true since there was no parsing error.
2942 return true;
2943 }
2944 continue;
2945 }
2946
2947 case STOP_WAITING_FRAME: {
ianswett97b690b2019-05-02 15:12:43 -07002948 if (GetQuicReloadableFlag(quic_do_not_accept_stop_waiting) &&
fayang36825da2019-08-21 14:01:27 -07002949 version_.transport_version > QUIC_VERSION_43) {
ianswett97b690b2019-05-02 15:12:43 -07002950 QUIC_RELOADABLE_FLAG_COUNT(quic_do_not_accept_stop_waiting);
2951 set_detailed_error("STOP WAITING not supported in version 44+.");
2952 return RaiseError(QUIC_INVALID_STOP_WAITING_DATA);
2953 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002954 QuicStopWaitingFrame stop_waiting_frame;
2955 if (!ProcessStopWaitingFrame(reader, header, &stop_waiting_frame)) {
2956 return RaiseError(QUIC_INVALID_STOP_WAITING_DATA);
2957 }
dschinazi118934b2019-06-13 18:09:08 -07002958 QUIC_DVLOG(2) << ENDPOINT << "Processing stop waiting frame "
2959 << stop_waiting_frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002960 if (!visitor_->OnStopWaitingFrame(stop_waiting_frame)) {
2961 QUIC_DVLOG(1) << ENDPOINT
2962 << "Visitor asked to stop further processing.";
2963 // Returning true since there was no parsing error.
2964 return true;
2965 }
2966 continue;
2967 }
2968 case PING_FRAME: {
2969 // Ping has no payload.
2970 QuicPingFrame ping_frame;
2971 if (!visitor_->OnPingFrame(ping_frame)) {
2972 QUIC_DVLOG(1) << ENDPOINT
2973 << "Visitor asked to stop further processing.";
2974 // Returning true since there was no parsing error.
2975 return true;
2976 }
dschinazi118934b2019-06-13 18:09:08 -07002977 QUIC_DVLOG(2) << ENDPOINT << "Processing ping frame " << ping_frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002978 continue;
2979 }
2980 case IETF_EXTENSION_MESSAGE_NO_LENGTH:
2981 QUIC_FALLTHROUGH_INTENDED;
2982 case IETF_EXTENSION_MESSAGE: {
2983 QuicMessageFrame message_frame;
2984 if (!ProcessMessageFrame(reader,
2985 frame_type == IETF_EXTENSION_MESSAGE_NO_LENGTH,
2986 &message_frame)) {
2987 return RaiseError(QUIC_INVALID_MESSAGE_DATA);
2988 }
dschinazi118934b2019-06-13 18:09:08 -07002989 QUIC_DVLOG(2) << ENDPOINT << "Processing message frame "
2990 << message_frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002991 if (!visitor_->OnMessageFrame(message_frame)) {
2992 QUIC_DVLOG(1) << ENDPOINT
2993 << "Visitor asked to stop further processing.";
2994 // Returning true since there was no parsing error.
2995 return true;
2996 }
2997 break;
2998 }
2999 case CRYPTO_FRAME: {
QUICHE teamea740082019-03-11 17:58:43 -07003000 if (!QuicVersionUsesCryptoFrames(version_.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05003001 set_detailed_error("Illegal frame type.");
3002 return RaiseError(QUIC_INVALID_FRAME_DATA);
3003 }
3004 QuicCryptoFrame frame;
3005 if (!ProcessCryptoFrame(reader, &frame)) {
3006 return RaiseError(QUIC_INVALID_FRAME_DATA);
3007 }
dschinazi118934b2019-06-13 18:09:08 -07003008 QUIC_DVLOG(2) << ENDPOINT << "Processing crypto frame " << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003009 if (!visitor_->OnCryptoFrame(frame)) {
3010 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3011 // Returning true since there was no parsing error.
3012 return true;
3013 }
3014 break;
3015 }
3016
3017 default:
3018 set_detailed_error("Illegal frame type.");
3019 QUIC_DLOG(WARNING) << ENDPOINT << "Illegal frame type: "
3020 << static_cast<int>(frame_type);
3021 return RaiseError(QUIC_INVALID_FRAME_DATA);
3022 }
3023 }
3024
3025 return true;
3026}
3027
3028bool QuicFramer::ProcessIetfFrameData(QuicDataReader* reader,
3029 const QuicPacketHeader& header) {
fkastenholz305e1732019-06-18 05:01:22 -07003030 DCHECK(VersionHasIetfQuicFrames(version_.transport_version))
3031 << "Attempt to process frames as IETF frames but version ("
3032 << version_.transport_version << ") does not support IETF Framing.";
3033
QUICHE teama6ef0a62019-03-07 20:34:33 -05003034 if (reader->IsDoneReading()) {
3035 set_detailed_error("Packet has no frames.");
3036 return RaiseError(QUIC_MISSING_PAYLOAD);
3037 }
dschinazi118934b2019-06-13 18:09:08 -07003038
3039 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF packet with header " << header;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003040 while (!reader->IsDoneReading()) {
3041 uint64_t frame_type;
3042 // Will be the number of bytes into which frame_type was encoded.
3043 size_t encoded_bytes = reader->BytesRemaining();
3044 if (!reader->ReadVarInt62(&frame_type)) {
3045 set_detailed_error("Unable to read frame type.");
3046 return RaiseError(QUIC_INVALID_FRAME_DATA);
3047 }
3048
3049 // Is now the number of bytes into which the frame type was encoded.
3050 encoded_bytes -= reader->BytesRemaining();
3051
3052 // Check that the frame type is minimally encoded.
3053 if (encoded_bytes !=
3054 static_cast<size_t>(QuicDataWriter::GetVarInt62Len(frame_type))) {
3055 // The frame type was not minimally encoded.
3056 set_detailed_error("Frame type not minimally encoded.");
3057 return RaiseError(IETF_QUIC_PROTOCOL_VIOLATION);
3058 }
3059
3060 if (IS_IETF_STREAM_FRAME(frame_type)) {
3061 QuicStreamFrame frame;
3062 if (!ProcessIetfStreamFrame(reader, frame_type, &frame)) {
3063 return RaiseError(QUIC_INVALID_STREAM_DATA);
3064 }
dschinazi118934b2019-06-13 18:09:08 -07003065 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF stream frame " << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003066 if (!visitor_->OnStreamFrame(frame)) {
3067 QUIC_DVLOG(1) << ENDPOINT
3068 << "Visitor asked to stop further processing.";
3069 // Returning true since there was no parsing error.
3070 return true;
3071 }
3072 } else {
3073 switch (frame_type) {
3074 case IETF_PADDING: {
3075 QuicPaddingFrame frame;
3076 ProcessPaddingFrame(reader, &frame);
dschinazi118934b2019-06-13 18:09:08 -07003077 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF padding frame "
3078 << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003079 if (!visitor_->OnPaddingFrame(frame)) {
3080 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3081 // Returning true since there was no parsing error.
3082 return true;
3083 }
3084 break;
3085 }
3086 case IETF_RST_STREAM: {
3087 QuicRstStreamFrame frame;
3088 if (!ProcessIetfResetStreamFrame(reader, &frame)) {
3089 return RaiseError(QUIC_INVALID_RST_STREAM_DATA);
3090 }
dschinazi118934b2019-06-13 18:09:08 -07003091 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF reset stream frame "
3092 << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003093 if (!visitor_->OnRstStreamFrame(frame)) {
3094 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3095 // Returning true since there was no parsing error.
3096 return true;
3097 }
3098 break;
3099 }
fkastenholz04bd4f32019-04-16 12:24:38 -07003100 case IETF_APPLICATION_CLOSE:
QUICHE teama6ef0a62019-03-07 20:34:33 -05003101 case IETF_CONNECTION_CLOSE: {
3102 QuicConnectionCloseFrame frame;
fkastenholze9d71a82019-04-09 05:12:13 -07003103 if (!ProcessIetfConnectionCloseFrame(
fkastenholz04bd4f32019-04-16 12:24:38 -07003104 reader,
3105 (frame_type == IETF_CONNECTION_CLOSE)
3106 ? IETF_QUIC_TRANSPORT_CONNECTION_CLOSE
3107 : IETF_QUIC_APPLICATION_CONNECTION_CLOSE,
3108 &frame)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05003109 return RaiseError(QUIC_INVALID_CONNECTION_CLOSE_DATA);
3110 }
dschinazi118934b2019-06-13 18:09:08 -07003111 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF connection close frame "
3112 << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003113 if (!visitor_->OnConnectionCloseFrame(frame)) {
3114 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3115 // Returning true since there was no parsing error.
3116 return true;
3117 }
3118 break;
3119 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05003120 case IETF_MAX_DATA: {
3121 QuicWindowUpdateFrame frame;
3122 if (!ProcessMaxDataFrame(reader, &frame)) {
3123 return RaiseError(QUIC_INVALID_MAX_DATA_FRAME_DATA);
3124 }
3125 // TODO(fkastenholz): Or should we create a new visitor function,
3126 // OnMaxDataFrame()?
dschinazi118934b2019-06-13 18:09:08 -07003127 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF max data frame "
3128 << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003129 if (!visitor_->OnWindowUpdateFrame(frame)) {
3130 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3131 // Returning true since there was no parsing error.
3132 return true;
3133 }
3134 break;
3135 }
3136 case IETF_MAX_STREAM_DATA: {
3137 QuicWindowUpdateFrame frame;
3138 if (!ProcessMaxStreamDataFrame(reader, &frame)) {
3139 return RaiseError(QUIC_INVALID_MAX_STREAM_DATA_FRAME_DATA);
3140 }
3141 // TODO(fkastenholz): Or should we create a new visitor function,
3142 // OnMaxStreamDataFrame()?
dschinazi118934b2019-06-13 18:09:08 -07003143 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF max stream data frame "
3144 << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003145 if (!visitor_->OnWindowUpdateFrame(frame)) {
3146 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3147 // Returning true since there was no parsing error.
3148 return true;
3149 }
3150 break;
3151 }
3152 case IETF_MAX_STREAMS_BIDIRECTIONAL:
3153 case IETF_MAX_STREAMS_UNIDIRECTIONAL: {
fkastenholz3c4eabf2019-04-22 07:49:59 -07003154 QuicMaxStreamsFrame frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003155 if (!ProcessMaxStreamsFrame(reader, &frame, frame_type)) {
fkastenholz3c4eabf2019-04-22 07:49:59 -07003156 return RaiseError(QUIC_MAX_STREAMS_DATA);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003157 }
fkastenholz3c4eabf2019-04-22 07:49:59 -07003158 QUIC_CODE_COUNT_N(quic_max_streams_received, 1, 2);
dschinazi118934b2019-06-13 18:09:08 -07003159 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF max streams frame "
3160 << frame;
fkastenholz3c4eabf2019-04-22 07:49:59 -07003161 if (!visitor_->OnMaxStreamsFrame(frame)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05003162 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3163 // Returning true since there was no parsing error.
3164 return true;
3165 }
3166 break;
3167 }
3168 case IETF_PING: {
3169 // Ping has no payload.
3170 QuicPingFrame ping_frame;
dschinazi118934b2019-06-13 18:09:08 -07003171 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF ping frame "
3172 << ping_frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003173 if (!visitor_->OnPingFrame(ping_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_BLOCKED: {
3181 QuicBlockedFrame frame;
3182 if (!ProcessIetfBlockedFrame(reader, &frame)) {
3183 return RaiseError(QUIC_INVALID_BLOCKED_DATA);
3184 }
dschinazi118934b2019-06-13 18:09:08 -07003185 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF blocked frame "
3186 << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003187 if (!visitor_->OnBlockedFrame(frame)) {
3188 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3189 // Returning true since there was no parsing error.
3190 return true;
3191 }
3192 break;
3193 }
3194 case IETF_STREAM_BLOCKED: {
3195 QuicBlockedFrame frame;
3196 if (!ProcessStreamBlockedFrame(reader, &frame)) {
3197 return RaiseError(QUIC_INVALID_STREAM_BLOCKED_DATA);
3198 }
dschinazi118934b2019-06-13 18:09:08 -07003199 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF stream blocked frame "
3200 << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003201 if (!visitor_->OnBlockedFrame(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_STREAMS_BLOCKED_UNIDIRECTIONAL:
3209 case IETF_STREAMS_BLOCKED_BIDIRECTIONAL: {
fkastenholz3c4eabf2019-04-22 07:49:59 -07003210 QuicStreamsBlockedFrame frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003211 if (!ProcessStreamsBlockedFrame(reader, &frame, frame_type)) {
fkastenholz3c4eabf2019-04-22 07:49:59 -07003212 return RaiseError(QUIC_STREAMS_BLOCKED_DATA);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003213 }
fkastenholz3c4eabf2019-04-22 07:49:59 -07003214 QUIC_CODE_COUNT_N(quic_streams_blocked_received, 1, 2);
dschinazi118934b2019-06-13 18:09:08 -07003215 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF streams blocked frame "
3216 << frame;
fkastenholz3c4eabf2019-04-22 07:49:59 -07003217 if (!visitor_->OnStreamsBlockedFrame(frame)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05003218 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3219 // Returning true since there was no parsing error.
3220 return true;
3221 }
3222 break;
3223 }
3224 case IETF_NEW_CONNECTION_ID: {
3225 QuicNewConnectionIdFrame frame;
3226 if (!ProcessNewConnectionIdFrame(reader, &frame)) {
3227 return RaiseError(QUIC_INVALID_NEW_CONNECTION_ID_DATA);
3228 }
dschinazi118934b2019-06-13 18:09:08 -07003229 QUIC_DVLOG(2) << ENDPOINT
3230 << "Processing IETF new connection ID frame " << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003231 if (!visitor_->OnNewConnectionIdFrame(frame)) {
3232 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3233 // Returning true since there was no parsing error.
3234 return true;
3235 }
3236 break;
3237 }
3238 case IETF_RETIRE_CONNECTION_ID: {
3239 QuicRetireConnectionIdFrame frame;
3240 if (!ProcessRetireConnectionIdFrame(reader, &frame)) {
3241 return RaiseError(QUIC_INVALID_RETIRE_CONNECTION_ID_DATA);
3242 }
dschinazi118934b2019-06-13 18:09:08 -07003243 QUIC_DVLOG(2) << ENDPOINT
3244 << "Processing IETF retire connection ID frame "
3245 << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003246 if (!visitor_->OnRetireConnectionIdFrame(frame)) {
3247 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3248 // Returning true since there was no parsing error.
3249 return true;
3250 }
3251 break;
3252 }
3253 case IETF_NEW_TOKEN: {
3254 QuicNewTokenFrame frame;
3255 if (!ProcessNewTokenFrame(reader, &frame)) {
3256 return RaiseError(QUIC_INVALID_NEW_TOKEN);
3257 }
dschinazi118934b2019-06-13 18:09:08 -07003258 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF new token frame "
3259 << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003260 if (!visitor_->OnNewTokenFrame(frame)) {
3261 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3262 // Returning true since there was no parsing error.
3263 return true;
3264 }
3265 break;
3266 }
3267 case IETF_STOP_SENDING: {
3268 QuicStopSendingFrame frame;
3269 if (!ProcessStopSendingFrame(reader, &frame)) {
3270 return RaiseError(QUIC_INVALID_STOP_SENDING_FRAME_DATA);
3271 }
dschinazi118934b2019-06-13 18:09:08 -07003272 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF stop sending frame "
3273 << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003274 if (!visitor_->OnStopSendingFrame(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_ACK_ECN:
3282 case IETF_ACK: {
3283 QuicAckFrame frame;
3284 if (!ProcessIetfAckFrame(reader, frame_type, &frame)) {
3285 return RaiseError(QUIC_INVALID_ACK_DATA);
3286 }
dschinazi118934b2019-06-13 18:09:08 -07003287 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF ACK frame " << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003288 break;
3289 }
3290 case IETF_PATH_CHALLENGE: {
3291 QuicPathChallengeFrame frame;
3292 if (!ProcessPathChallengeFrame(reader, &frame)) {
3293 return RaiseError(QUIC_INVALID_PATH_CHALLENGE_DATA);
3294 }
dschinazi118934b2019-06-13 18:09:08 -07003295 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF path challenge frame "
3296 << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003297 if (!visitor_->OnPathChallengeFrame(frame)) {
3298 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3299 // Returning true since there was no parsing error.
3300 return true;
3301 }
3302 break;
3303 }
3304 case IETF_PATH_RESPONSE: {
3305 QuicPathResponseFrame frame;
3306 if (!ProcessPathResponseFrame(reader, &frame)) {
3307 return RaiseError(QUIC_INVALID_PATH_RESPONSE_DATA);
3308 }
dschinazi118934b2019-06-13 18:09:08 -07003309 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF path response frame "
3310 << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003311 if (!visitor_->OnPathResponseFrame(frame)) {
3312 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3313 // Returning true since there was no parsing error.
3314 return true;
3315 }
3316 break;
3317 }
3318 case IETF_EXTENSION_MESSAGE_NO_LENGTH:
3319 QUIC_FALLTHROUGH_INTENDED;
3320 case IETF_EXTENSION_MESSAGE: {
3321 QuicMessageFrame message_frame;
3322 if (!ProcessMessageFrame(
3323 reader, frame_type == IETF_EXTENSION_MESSAGE_NO_LENGTH,
3324 &message_frame)) {
3325 return RaiseError(QUIC_INVALID_MESSAGE_DATA);
3326 }
dschinazi118934b2019-06-13 18:09:08 -07003327 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF message frame "
3328 << message_frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003329 if (!visitor_->OnMessageFrame(message_frame)) {
3330 QUIC_DVLOG(1) << ENDPOINT
3331 << "Visitor asked to stop further processing.";
3332 // Returning true since there was no parsing error.
3333 return true;
3334 }
3335 break;
3336 }
3337 case IETF_CRYPTO: {
3338 QuicCryptoFrame frame;
3339 if (!ProcessCryptoFrame(reader, &frame)) {
3340 return RaiseError(QUIC_INVALID_FRAME_DATA);
3341 }
dschinazi118934b2019-06-13 18:09:08 -07003342 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF crypto frame " << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003343 if (!visitor_->OnCryptoFrame(frame)) {
3344 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3345 // Returning true since there was no parsing error.
3346 return true;
3347 }
3348 break;
3349 }
3350
3351 default:
3352 set_detailed_error("Illegal frame type.");
3353 QUIC_DLOG(WARNING)
3354 << ENDPOINT
3355 << "Illegal frame type: " << static_cast<int>(frame_type);
3356 return RaiseError(QUIC_INVALID_FRAME_DATA);
3357 }
3358 }
3359 }
3360 return true;
3361}
3362
3363namespace {
3364// Create a mask that sets the last |num_bits| to 1 and the rest to 0.
3365inline uint8_t GetMaskFromNumBits(uint8_t num_bits) {
3366 return (1u << num_bits) - 1;
3367}
3368
3369// Extract |num_bits| from |flags| offset by |offset|.
3370uint8_t ExtractBits(uint8_t flags, uint8_t num_bits, uint8_t offset) {
3371 return (flags >> offset) & GetMaskFromNumBits(num_bits);
3372}
3373
3374// Extract the bit at position |offset| from |flags| as a bool.
3375bool ExtractBit(uint8_t flags, uint8_t offset) {
3376 return ((flags >> offset) & GetMaskFromNumBits(1)) != 0;
3377}
3378
3379// Set |num_bits|, offset by |offset| to |val| in |flags|.
3380void SetBits(uint8_t* flags, uint8_t val, uint8_t num_bits, uint8_t offset) {
3381 DCHECK_LE(val, GetMaskFromNumBits(num_bits));
3382 *flags |= val << offset;
3383}
3384
3385// Set the bit at position |offset| to |val| in |flags|.
3386void SetBit(uint8_t* flags, bool val, uint8_t offset) {
3387 SetBits(flags, val ? 1 : 0, 1, offset);
3388}
3389} // namespace
3390
3391bool QuicFramer::ProcessStreamFrame(QuicDataReader* reader,
3392 uint8_t frame_type,
3393 QuicStreamFrame* frame) {
3394 uint8_t stream_flags = frame_type;
3395
3396 uint8_t stream_id_length = 0;
3397 uint8_t offset_length = 4;
3398 bool has_data_length = true;
3399 stream_flags &= ~kQuicFrameTypeStreamMask;
3400
3401 // Read from right to left: StreamID, Offset, Data Length, Fin.
3402 stream_id_length = (stream_flags & kQuicStreamIDLengthMask) + 1;
3403 stream_flags >>= kQuicStreamIdShift;
3404
3405 offset_length = (stream_flags & kQuicStreamOffsetMask);
3406 // There is no encoding for 1 byte, only 0 and 2 through 8.
3407 if (offset_length > 0) {
3408 offset_length += 1;
3409 }
3410 stream_flags >>= kQuicStreamShift;
3411
3412 has_data_length =
3413 (stream_flags & kQuicStreamDataLengthMask) == kQuicStreamDataLengthMask;
3414 stream_flags >>= kQuicStreamDataLengthShift;
3415
3416 frame->fin = (stream_flags & kQuicStreamFinMask) == kQuicStreamFinShift;
3417
3418 uint64_t stream_id;
3419 if (!reader->ReadBytesToUInt64(stream_id_length, &stream_id)) {
3420 set_detailed_error("Unable to read stream_id.");
3421 return false;
3422 }
3423 frame->stream_id = static_cast<QuicStreamId>(stream_id);
3424
3425 if (!reader->ReadBytesToUInt64(offset_length, &frame->offset)) {
3426 set_detailed_error("Unable to read offset.");
3427 return false;
3428 }
3429
3430 // TODO(ianswett): Don't use QuicStringPiece as an intermediary.
3431 QuicStringPiece data;
3432 if (has_data_length) {
3433 if (!reader->ReadStringPiece16(&data)) {
3434 set_detailed_error("Unable to read frame data.");
3435 return false;
3436 }
3437 } else {
3438 if (!reader->ReadStringPiece(&data, reader->BytesRemaining())) {
3439 set_detailed_error("Unable to read frame data.");
3440 return false;
3441 }
3442 }
3443 frame->data_buffer = data.data();
3444 frame->data_length = static_cast<uint16_t>(data.length());
3445
3446 return true;
3447}
3448
3449bool QuicFramer::ProcessIetfStreamFrame(QuicDataReader* reader,
3450 uint8_t frame_type,
3451 QuicStreamFrame* frame) {
3452 // Read stream id from the frame. It's always present.
fkastenholz3c4eabf2019-04-22 07:49:59 -07003453 if (!reader->ReadVarIntU32(&frame->stream_id)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05003454 set_detailed_error("Unable to read stream_id.");
3455 return false;
3456 }
3457
3458 // If we have a data offset, read it. If not, set to 0.
3459 if (frame_type & IETF_STREAM_FRAME_OFF_BIT) {
3460 if (!reader->ReadVarInt62(&frame->offset)) {
3461 set_detailed_error("Unable to read stream data offset.");
3462 return false;
3463 }
3464 } else {
3465 // no offset in the frame, ensure it's 0 in the Frame.
3466 frame->offset = 0;
3467 }
3468
3469 // If we have a data length, read it. If not, set to 0.
3470 if (frame_type & IETF_STREAM_FRAME_LEN_BIT) {
3471 QuicIetfStreamDataLength length;
3472 if (!reader->ReadVarInt62(&length)) {
3473 set_detailed_error("Unable to read stream data length.");
3474 return false;
3475 }
3476 if (length > 0xffff) {
3477 set_detailed_error("Stream data length is too large.");
3478 return false;
3479 }
3480 frame->data_length = length;
3481 } else {
3482 // no length in the frame, it is the number of bytes remaining in the
3483 // packet.
3484 frame->data_length = reader->BytesRemaining();
3485 }
3486
3487 if (frame_type & IETF_STREAM_FRAME_FIN_BIT) {
3488 frame->fin = true;
3489 } else {
3490 frame->fin = false;
3491 }
3492
3493 // TODO(ianswett): Don't use QuicStringPiece as an intermediary.
3494 QuicStringPiece data;
3495 if (!reader->ReadStringPiece(&data, frame->data_length)) {
3496 set_detailed_error("Unable to read frame data.");
3497 return false;
3498 }
3499 frame->data_buffer = data.data();
3500 frame->data_length = static_cast<QuicIetfStreamDataLength>(data.length());
3501
3502 return true;
3503}
3504
3505bool QuicFramer::ProcessCryptoFrame(QuicDataReader* reader,
3506 QuicCryptoFrame* frame) {
3507 if (!reader->ReadVarInt62(&frame->offset)) {
3508 set_detailed_error("Unable to read crypto data offset.");
3509 return false;
3510 }
3511 uint64_t len;
3512 if (!reader->ReadVarInt62(&len) ||
3513 len > std::numeric_limits<QuicPacketLength>::max()) {
3514 set_detailed_error("Invalid data length.");
3515 return false;
3516 }
3517 frame->data_length = len;
3518
3519 // TODO(ianswett): Don't use QuicStringPiece as an intermediary.
3520 QuicStringPiece data;
3521 if (!reader->ReadStringPiece(&data, frame->data_length)) {
3522 set_detailed_error("Unable to read frame data.");
3523 return false;
3524 }
3525 frame->data_buffer = data.data();
3526 return true;
3527}
3528
3529bool QuicFramer::ProcessAckFrame(QuicDataReader* reader, uint8_t frame_type) {
3530 const bool has_ack_blocks =
3531 ExtractBit(frame_type, kQuicHasMultipleAckBlocksOffset);
3532 uint8_t num_ack_blocks = 0;
3533 uint8_t num_received_packets = 0;
3534
3535 // Determine the two lengths from the frame type: largest acked length,
3536 // ack block length.
3537 const QuicPacketNumberLength ack_block_length = ReadAckPacketNumberLength(
3538 version_.transport_version,
3539 ExtractBits(frame_type, kQuicSequenceNumberLengthNumBits,
3540 kActBlockLengthOffset));
3541 const QuicPacketNumberLength largest_acked_length = ReadAckPacketNumberLength(
3542 version_.transport_version,
3543 ExtractBits(frame_type, kQuicSequenceNumberLengthNumBits,
3544 kLargestAckedOffset));
3545
3546 uint64_t largest_acked;
3547 if (!reader->ReadBytesToUInt64(largest_acked_length, &largest_acked)) {
3548 set_detailed_error("Unable to read largest acked.");
3549 return false;
3550 }
3551
3552 if (largest_acked < first_sending_packet_number_.ToUint64()) {
3553 // Connection always sends packet starting from kFirstSendingPacketNumber >
3554 // 0, peer has observed an unsent packet.
3555 set_detailed_error("Largest acked is 0.");
3556 return false;
3557 }
3558
3559 uint64_t ack_delay_time_us;
3560 if (!reader->ReadUFloat16(&ack_delay_time_us)) {
3561 set_detailed_error("Unable to read ack delay time.");
3562 return false;
3563 }
3564
3565 if (!visitor_->OnAckFrameStart(
3566 QuicPacketNumber(largest_acked),
3567 ack_delay_time_us == kUFloat16MaxValue
3568 ? QuicTime::Delta::Infinite()
3569 : QuicTime::Delta::FromMicroseconds(ack_delay_time_us))) {
3570 // The visitor suppresses further processing of the packet. Although this is
3571 // not a parsing error, returns false as this is in middle of processing an
3572 // ack frame,
3573 set_detailed_error("Visitor suppresses further processing of ack frame.");
3574 return false;
3575 }
3576
3577 if (has_ack_blocks && !reader->ReadUInt8(&num_ack_blocks)) {
3578 set_detailed_error("Unable to read num of ack blocks.");
3579 return false;
3580 }
3581
3582 uint64_t first_block_length;
3583 if (!reader->ReadBytesToUInt64(ack_block_length, &first_block_length)) {
3584 set_detailed_error("Unable to read first ack block length.");
3585 return false;
3586 }
3587
3588 if (first_block_length == 0) {
3589 set_detailed_error("First block length is zero.");
3590 return false;
3591 }
3592 bool first_ack_block_underflow = first_block_length > largest_acked + 1;
3593 if (first_block_length + first_sending_packet_number_.ToUint64() >
3594 largest_acked + 1) {
3595 first_ack_block_underflow = true;
3596 }
3597 if (first_ack_block_underflow) {
3598 set_detailed_error(QuicStrCat("Underflow with first ack block length ",
3599 first_block_length, " largest acked is ",
3600 largest_acked, ".")
3601 .c_str());
3602 return false;
3603 }
3604
3605 uint64_t first_received = largest_acked + 1 - first_block_length;
3606 if (!visitor_->OnAckRange(QuicPacketNumber(first_received),
3607 QuicPacketNumber(largest_acked + 1))) {
3608 // The visitor suppresses further processing of the packet. Although
3609 // this is not a parsing error, returns false as this is in middle
3610 // of processing an ack frame,
3611 set_detailed_error("Visitor suppresses further processing of ack frame.");
3612 return false;
3613 }
3614
3615 if (num_ack_blocks > 0) {
3616 for (size_t i = 0; i < num_ack_blocks; ++i) {
3617 uint8_t gap = 0;
3618 if (!reader->ReadUInt8(&gap)) {
3619 set_detailed_error("Unable to read gap to next ack block.");
3620 return false;
3621 }
3622 uint64_t current_block_length;
3623 if (!reader->ReadBytesToUInt64(ack_block_length, &current_block_length)) {
3624 set_detailed_error("Unable to ack block length.");
3625 return false;
3626 }
3627 bool ack_block_underflow = first_received < gap + current_block_length;
3628 if (first_received < gap + current_block_length +
3629 first_sending_packet_number_.ToUint64()) {
3630 ack_block_underflow = true;
3631 }
3632 if (ack_block_underflow) {
3633 set_detailed_error(
3634 QuicStrCat("Underflow with ack block length ", current_block_length,
3635 ", end of block is ", first_received - gap, ".")
3636 .c_str());
3637 return false;
3638 }
3639
3640 first_received -= (gap + current_block_length);
3641 if (current_block_length > 0) {
3642 if (!visitor_->OnAckRange(
3643 QuicPacketNumber(first_received),
3644 QuicPacketNumber(first_received) + current_block_length)) {
3645 // The visitor suppresses further processing of the packet. Although
3646 // this is not a parsing error, returns false as this is in middle
3647 // of processing an ack frame,
3648 set_detailed_error(
3649 "Visitor suppresses further processing of ack frame.");
3650 return false;
3651 }
3652 }
3653 }
3654 }
3655
3656 if (!reader->ReadUInt8(&num_received_packets)) {
3657 set_detailed_error("Unable to read num received packets.");
3658 return false;
3659 }
3660
3661 if (!ProcessTimestampsInAckFrame(num_received_packets,
3662 QuicPacketNumber(largest_acked), reader)) {
3663 return false;
3664 }
3665
3666 // Done processing the ACK frame.
3667 return visitor_->OnAckFrameEnd(QuicPacketNumber(first_received));
3668}
3669
3670bool QuicFramer::ProcessTimestampsInAckFrame(uint8_t num_received_packets,
3671 QuicPacketNumber largest_acked,
3672 QuicDataReader* reader) {
3673 if (num_received_packets == 0) {
3674 return true;
3675 }
3676 uint8_t delta_from_largest_observed;
3677 if (!reader->ReadUInt8(&delta_from_largest_observed)) {
3678 set_detailed_error("Unable to read sequence delta in received packets.");
3679 return false;
3680 }
3681
3682 if (largest_acked.ToUint64() <= delta_from_largest_observed) {
3683 set_detailed_error(QuicStrCat("delta_from_largest_observed too high: ",
3684 delta_from_largest_observed,
3685 ", largest_acked: ", largest_acked.ToUint64())
3686 .c_str());
3687 return false;
3688 }
3689
3690 // Time delta from the framer creation.
3691 uint32_t time_delta_us;
3692 if (!reader->ReadUInt32(&time_delta_us)) {
3693 set_detailed_error("Unable to read time delta in received packets.");
3694 return false;
3695 }
3696
3697 QuicPacketNumber seq_num = largest_acked - delta_from_largest_observed;
3698 if (process_timestamps_) {
3699 last_timestamp_ = CalculateTimestampFromWire(time_delta_us);
3700
3701 visitor_->OnAckTimestamp(seq_num, creation_time_ + last_timestamp_);
3702 }
3703
3704 for (uint8_t i = 1; i < num_received_packets; ++i) {
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 if (largest_acked.ToUint64() <= delta_from_largest_observed) {
3710 set_detailed_error(
3711 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 seq_num = largest_acked - delta_from_largest_observed;
3718
3719 // Time delta from the previous timestamp.
3720 uint64_t incremental_time_delta_us;
3721 if (!reader->ReadUFloat16(&incremental_time_delta_us)) {
3722 set_detailed_error(
3723 "Unable to read incremental time delta in received packets.");
3724 return false;
3725 }
3726
3727 if (process_timestamps_) {
3728 last_timestamp_ = last_timestamp_ + QuicTime::Delta::FromMicroseconds(
3729 incremental_time_delta_us);
3730 visitor_->OnAckTimestamp(seq_num, creation_time_ + last_timestamp_);
3731 }
3732 }
3733 return true;
3734}
3735
3736bool QuicFramer::ProcessIetfAckFrame(QuicDataReader* reader,
3737 uint64_t frame_type,
3738 QuicAckFrame* ack_frame) {
3739 uint64_t largest_acked;
3740 if (!reader->ReadVarInt62(&largest_acked)) {
3741 set_detailed_error("Unable to read largest acked.");
3742 return false;
3743 }
3744 if (largest_acked < first_sending_packet_number_.ToUint64()) {
3745 // Connection always sends packet starting from kFirstSendingPacketNumber >
3746 // 0, peer has observed an unsent packet.
3747 set_detailed_error("Largest acked is 0.");
3748 return false;
3749 }
3750 ack_frame->largest_acked = static_cast<QuicPacketNumber>(largest_acked);
3751 uint64_t ack_delay_time_in_us;
3752 if (!reader->ReadVarInt62(&ack_delay_time_in_us)) {
3753 set_detailed_error("Unable to read ack delay time.");
3754 return false;
3755 }
3756
QUICHE teama6ef0a62019-03-07 20:34:33 -05003757 if (ack_delay_time_in_us == kVarInt62MaxValue) {
3758 ack_frame->ack_delay_time = QuicTime::Delta::Infinite();
3759 } else {
fkastenholz4dc4ba32019-07-30 09:55:25 -07003760 ack_delay_time_in_us = (ack_delay_time_in_us << peer_ack_delay_exponent_);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003761 ack_frame->ack_delay_time =
3762 QuicTime::Delta::FromMicroseconds(ack_delay_time_in_us);
3763 }
3764 if (frame_type == IETF_ACK_ECN) {
3765 ack_frame->ecn_counters_populated = true;
3766 if (!reader->ReadVarInt62(&ack_frame->ect_0_count)) {
3767 set_detailed_error("Unable to read ack ect_0_count.");
3768 return false;
3769 }
3770 if (!reader->ReadVarInt62(&ack_frame->ect_1_count)) {
3771 set_detailed_error("Unable to read ack ect_1_count.");
3772 return false;
3773 }
3774 if (!reader->ReadVarInt62(&ack_frame->ecn_ce_count)) {
3775 set_detailed_error("Unable to read ack ecn_ce_count.");
3776 return false;
3777 }
3778 } else {
3779 ack_frame->ecn_counters_populated = false;
3780 ack_frame->ect_0_count = 0;
3781 ack_frame->ect_1_count = 0;
3782 ack_frame->ecn_ce_count = 0;
3783 }
3784 if (!visitor_->OnAckFrameStart(QuicPacketNumber(largest_acked),
3785 ack_frame->ack_delay_time)) {
3786 // The visitor suppresses further processing of the packet. Although this is
3787 // not a parsing error, returns false as this is in middle of processing an
3788 // ACK frame.
3789 set_detailed_error("Visitor suppresses further processing of ACK frame.");
3790 return false;
3791 }
3792
3793 // Get number of ACK blocks from the packet.
3794 uint64_t ack_block_count;
3795 if (!reader->ReadVarInt62(&ack_block_count)) {
3796 set_detailed_error("Unable to read ack block count.");
3797 return false;
3798 }
3799 // There always is a first ACK block, which is the (number of packets being
3800 // acked)-1, up to and including the packet at largest_acked. Therefore if the
3801 // value is 0, then only largest is acked. If it is 1, then largest-1,
3802 // largest] are acked, etc
3803 uint64_t ack_block_value;
3804 if (!reader->ReadVarInt62(&ack_block_value)) {
3805 set_detailed_error("Unable to read first ack block length.");
3806 return false;
3807 }
3808 // Calculate the packets being acked in the first block.
3809 // +1 because AddRange implementation requires [low,high)
3810 uint64_t block_high = largest_acked + 1;
3811 uint64_t block_low = largest_acked - ack_block_value;
3812
3813 // ack_block_value is the number of packets preceding the
3814 // largest_acked packet which are in the block being acked. Thus,
3815 // its maximum value is largest_acked-1. Test this, reporting an
3816 // error if the value is wrong.
3817 if (ack_block_value + first_sending_packet_number_.ToUint64() >
3818 largest_acked) {
3819 set_detailed_error(QuicStrCat("Underflow with first ack block length ",
3820 ack_block_value + 1, " largest acked is ",
3821 largest_acked, ".")
3822 .c_str());
3823 return false;
3824 }
3825
3826 if (!visitor_->OnAckRange(QuicPacketNumber(block_low),
3827 QuicPacketNumber(block_high))) {
3828 // The visitor suppresses further processing of the packet. Although
3829 // this is not a parsing error, returns false as this is in middle
3830 // of processing an ACK frame.
3831 set_detailed_error("Visitor suppresses further processing of ACK frame.");
3832 return false;
3833 }
3834
3835 while (ack_block_count != 0) {
3836 uint64_t gap_block_value;
3837 // Get the sizes of the gap and ack blocks,
3838 if (!reader->ReadVarInt62(&gap_block_value)) {
3839 set_detailed_error("Unable to read gap block value.");
3840 return false;
3841 }
3842 // It's an error if the gap is larger than the space from packet
3843 // number 0 to the start of the block that's just been acked, PLUS
3844 // there must be space for at least 1 packet to be acked. For
3845 // example, if block_low is 10 and gap_block_value is 9, it means
3846 // the gap block is 10 packets long, leaving no room for a packet
3847 // to be acked. Thus, gap_block_value+2 can not be larger than
3848 // block_low.
3849 // The test is written this way to detect wrap-arounds.
3850 if ((gap_block_value + 2) > block_low) {
3851 set_detailed_error(
3852 QuicStrCat("Underflow with gap block length ", gap_block_value + 1,
3853 " previous ack block start is ", block_low, ".")
3854 .c_str());
3855 return false;
3856 }
3857
3858 // Adjust block_high to be the top of the next ack block.
3859 // There is a gap of |gap_block_value| packets between the bottom
3860 // of ack block N and top of block N+1. Note that gap_block_value
3861 // is he size of the gap minus 1 (per the QUIC protocol), and
3862 // block_high is the packet number of the first packet of the gap
3863 // (per the implementation of OnAckRange/AddAckRange, below).
3864 block_high = block_low - 1 - gap_block_value;
3865
3866 if (!reader->ReadVarInt62(&ack_block_value)) {
3867 set_detailed_error("Unable to read ack block value.");
3868 return false;
3869 }
3870 if (ack_block_value + first_sending_packet_number_.ToUint64() >
3871 (block_high - 1)) {
3872 set_detailed_error(
3873 QuicStrCat("Underflow with ack block length ", ack_block_value + 1,
3874 " latest ack block end is ", block_high - 1, ".")
3875 .c_str());
3876 return false;
3877 }
3878 // Calculate the low end of the new nth ack block. The +1 is
3879 // because the encoded value is the blocksize-1.
3880 block_low = block_high - 1 - ack_block_value;
3881 if (!visitor_->OnAckRange(QuicPacketNumber(block_low),
3882 QuicPacketNumber(block_high))) {
3883 // The visitor suppresses further processing of the packet. Although
3884 // this is not a parsing error, returns false as this is in middle
3885 // of processing an ACK frame.
3886 set_detailed_error("Visitor suppresses further processing of ACK frame.");
3887 return false;
3888 }
3889
3890 // Another one done.
3891 ack_block_count--;
3892 }
3893
3894 return visitor_->OnAckFrameEnd(QuicPacketNumber(block_low));
3895}
3896
3897bool QuicFramer::ProcessStopWaitingFrame(QuicDataReader* reader,
3898 const QuicPacketHeader& header,
3899 QuicStopWaitingFrame* stop_waiting) {
3900 uint64_t least_unacked_delta;
3901 if (!reader->ReadBytesToUInt64(header.packet_number_length,
3902 &least_unacked_delta)) {
3903 set_detailed_error("Unable to read least unacked delta.");
3904 return false;
3905 }
3906 if (header.packet_number.ToUint64() <= least_unacked_delta) {
3907 set_detailed_error("Invalid unacked delta.");
3908 return false;
3909 }
3910 stop_waiting->least_unacked = header.packet_number - least_unacked_delta;
3911
3912 return true;
3913}
3914
3915bool QuicFramer::ProcessRstStreamFrame(QuicDataReader* reader,
3916 QuicRstStreamFrame* frame) {
3917 if (!reader->ReadUInt32(&frame->stream_id)) {
3918 set_detailed_error("Unable to read stream_id.");
3919 return false;
3920 }
3921
3922 if (!reader->ReadUInt64(&frame->byte_offset)) {
3923 set_detailed_error("Unable to read rst stream sent byte offset.");
3924 return false;
3925 }
3926
3927 uint32_t error_code;
3928 if (!reader->ReadUInt32(&error_code)) {
3929 set_detailed_error("Unable to read rst stream error code.");
3930 return false;
3931 }
3932
3933 if (error_code >= QUIC_STREAM_LAST_ERROR) {
3934 // Ignore invalid stream error code if any.
3935 error_code = QUIC_STREAM_LAST_ERROR;
3936 }
3937
3938 frame->error_code = static_cast<QuicRstStreamErrorCode>(error_code);
3939
3940 return true;
3941}
3942
3943bool QuicFramer::ProcessConnectionCloseFrame(QuicDataReader* reader,
3944 QuicConnectionCloseFrame* frame) {
3945 uint32_t error_code;
fkastenholze9d71a82019-04-09 05:12:13 -07003946 frame->close_type = GOOGLE_QUIC_CONNECTION_CLOSE;
3947
QUICHE teama6ef0a62019-03-07 20:34:33 -05003948 if (!reader->ReadUInt32(&error_code)) {
3949 set_detailed_error("Unable to read connection close error code.");
3950 return false;
3951 }
3952
3953 if (error_code >= QUIC_LAST_ERROR) {
3954 // Ignore invalid QUIC error code if any.
3955 error_code = QUIC_LAST_ERROR;
3956 }
3957
fkastenholze9d71a82019-04-09 05:12:13 -07003958 frame->quic_error_code = static_cast<QuicErrorCode>(error_code);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003959
fkastenholza14a7ae2019-08-07 05:21:22 -07003960 // For Google QUIC connection closes, copy the Google QUIC error code to
3961 // the extracted error code field so that the Google QUIC error code is always
3962 // available in extracted_error_code.
3963 frame->extracted_error_code = frame->quic_error_code;
3964
QUICHE teama6ef0a62019-03-07 20:34:33 -05003965 QuicStringPiece error_details;
3966 if (!reader->ReadStringPiece16(&error_details)) {
3967 set_detailed_error("Unable to read connection close error details.");
3968 return false;
3969 }
vasilvvc48c8712019-03-11 13:38:16 -07003970 frame->error_details = std::string(error_details);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003971
3972 return true;
3973}
3974
3975bool QuicFramer::ProcessGoAwayFrame(QuicDataReader* reader,
3976 QuicGoAwayFrame* frame) {
3977 uint32_t error_code;
3978 if (!reader->ReadUInt32(&error_code)) {
3979 set_detailed_error("Unable to read go away error code.");
3980 return false;
3981 }
3982
3983 if (error_code >= QUIC_LAST_ERROR) {
3984 // Ignore invalid QUIC error code if any.
3985 error_code = QUIC_LAST_ERROR;
3986 }
3987 frame->error_code = static_cast<QuicErrorCode>(error_code);
3988
3989 uint32_t stream_id;
3990 if (!reader->ReadUInt32(&stream_id)) {
3991 set_detailed_error("Unable to read last good stream id.");
3992 return false;
3993 }
3994 frame->last_good_stream_id = static_cast<QuicStreamId>(stream_id);
3995
3996 QuicStringPiece reason_phrase;
3997 if (!reader->ReadStringPiece16(&reason_phrase)) {
3998 set_detailed_error("Unable to read goaway reason.");
3999 return false;
4000 }
vasilvvc48c8712019-03-11 13:38:16 -07004001 frame->reason_phrase = std::string(reason_phrase);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004002
4003 return true;
4004}
4005
4006bool QuicFramer::ProcessWindowUpdateFrame(QuicDataReader* reader,
4007 QuicWindowUpdateFrame* frame) {
4008 if (!reader->ReadUInt32(&frame->stream_id)) {
4009 set_detailed_error("Unable to read stream_id.");
4010 return false;
4011 }
4012
4013 if (!reader->ReadUInt64(&frame->byte_offset)) {
4014 set_detailed_error("Unable to read window byte_offset.");
4015 return false;
4016 }
4017
4018 return true;
4019}
4020
4021bool QuicFramer::ProcessBlockedFrame(QuicDataReader* reader,
4022 QuicBlockedFrame* frame) {
fkastenholz305e1732019-06-18 05:01:22 -07004023 DCHECK(!VersionHasIetfQuicFrames(version_.transport_version))
4024 << "Attempt to process non-IETF QUIC frames in an IETF QUIC version.";
QUICHE teama6ef0a62019-03-07 20:34:33 -05004025
4026 if (!reader->ReadUInt32(&frame->stream_id)) {
4027 set_detailed_error("Unable to read stream_id.");
4028 return false;
4029 }
4030
4031 return true;
4032}
4033
4034void QuicFramer::ProcessPaddingFrame(QuicDataReader* reader,
4035 QuicPaddingFrame* frame) {
4036 // Type byte has been read.
4037 frame->num_padding_bytes = 1;
4038 uint8_t next_byte;
4039 while (!reader->IsDoneReading() && reader->PeekByte() == 0x00) {
4040 reader->ReadBytes(&next_byte, 1);
4041 DCHECK_EQ(0x00, next_byte);
4042 ++frame->num_padding_bytes;
4043 }
4044}
4045
4046bool QuicFramer::ProcessMessageFrame(QuicDataReader* reader,
4047 bool no_message_length,
4048 QuicMessageFrame* frame) {
4049 if (no_message_length) {
4050 QuicStringPiece remaining(reader->ReadRemainingPayload());
4051 frame->data = remaining.data();
4052 frame->message_length = remaining.length();
4053 return true;
4054 }
4055
4056 uint64_t message_length;
4057 if (!reader->ReadVarInt62(&message_length)) {
4058 set_detailed_error("Unable to read message length");
4059 return false;
4060 }
4061
4062 QuicStringPiece message_piece;
4063 if (!reader->ReadStringPiece(&message_piece, message_length)) {
4064 set_detailed_error("Unable to read message data");
4065 return false;
4066 }
4067
4068 frame->data = message_piece.data();
4069 frame->message_length = message_length;
4070
4071 return true;
4072}
4073
4074// static
4075QuicStringPiece QuicFramer::GetAssociatedDataFromEncryptedPacket(
4076 QuicTransportVersion version,
4077 const QuicEncryptedPacket& encrypted,
4078 QuicConnectionIdLength destination_connection_id_length,
4079 QuicConnectionIdLength source_connection_id_length,
4080 bool includes_version,
4081 bool includes_diversification_nonce,
4082 QuicPacketNumberLength packet_number_length,
4083 QuicVariableLengthIntegerLength retry_token_length_length,
4084 uint64_t retry_token_length,
4085 QuicVariableLengthIntegerLength length_length) {
4086 // TODO(ianswett): This is identical to QuicData::AssociatedData.
4087 return QuicStringPiece(
4088 encrypted.data(),
4089 GetStartOfEncryptedData(version, destination_connection_id_length,
4090 source_connection_id_length, includes_version,
4091 includes_diversification_nonce,
4092 packet_number_length, retry_token_length_length,
4093 retry_token_length, length_length));
4094}
4095
4096void QuicFramer::SetDecrypter(EncryptionLevel level,
4097 std::unique_ptr<QuicDecrypter> decrypter) {
QUICHE team76086e42019-03-25 15:12:29 -07004098 DCHECK_EQ(alternative_decrypter_level_, NUM_ENCRYPTION_LEVELS);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004099 DCHECK_GE(level, decrypter_level_);
zhongyi546cc452019-04-12 15:27:49 -07004100 DCHECK(!version_.KnowsWhichDecrypterToUse());
dschinazi4b5a68a2019-08-15 15:45:36 -07004101 QUIC_DVLOG(1) << ENDPOINT << "Setting decrypter from level "
4102 << QuicUtils::EncryptionLevelToString(decrypter_level_)
4103 << " to " << QuicUtils::EncryptionLevelToString(level);
QUICHE team76086e42019-03-25 15:12:29 -07004104 decrypter_[decrypter_level_] = nullptr;
4105 decrypter_[level] = std::move(decrypter);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004106 decrypter_level_ = level;
4107}
4108
4109void QuicFramer::SetAlternativeDecrypter(
4110 EncryptionLevel level,
4111 std::unique_ptr<QuicDecrypter> decrypter,
4112 bool latch_once_used) {
QUICHE team76086e42019-03-25 15:12:29 -07004113 DCHECK_NE(level, decrypter_level_);
zhongyi546cc452019-04-12 15:27:49 -07004114 DCHECK(!version_.KnowsWhichDecrypterToUse());
dschinazi4b5a68a2019-08-15 15:45:36 -07004115 QUIC_DVLOG(1) << ENDPOINT << "Setting alternative decrypter from level "
4116 << QuicUtils::EncryptionLevelToString(
4117 alternative_decrypter_level_)
4118 << " to " << QuicUtils::EncryptionLevelToString(level);
QUICHE team76086e42019-03-25 15:12:29 -07004119 if (alternative_decrypter_level_ != NUM_ENCRYPTION_LEVELS) {
4120 decrypter_[alternative_decrypter_level_] = nullptr;
4121 }
4122 decrypter_[level] = std::move(decrypter);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004123 alternative_decrypter_level_ = level;
4124 alternative_decrypter_latch_ = latch_once_used;
4125}
4126
zhongyi546cc452019-04-12 15:27:49 -07004127void QuicFramer::InstallDecrypter(EncryptionLevel level,
4128 std::unique_ptr<QuicDecrypter> decrypter) {
4129 DCHECK(version_.KnowsWhichDecrypterToUse());
dschinazi4b5a68a2019-08-15 15:45:36 -07004130 QUIC_DVLOG(1) << ENDPOINT << "Installing decrypter at level "
4131 << QuicUtils::EncryptionLevelToString(level);
zhongyi546cc452019-04-12 15:27:49 -07004132 decrypter_[level] = std::move(decrypter);
4133}
4134
4135void QuicFramer::RemoveDecrypter(EncryptionLevel level) {
4136 DCHECK(version_.KnowsWhichDecrypterToUse());
dschinazi4b5a68a2019-08-15 15:45:36 -07004137 QUIC_DVLOG(1) << ENDPOINT << "Removing decrypter at level "
4138 << QuicUtils::EncryptionLevelToString(level);
zhongyi546cc452019-04-12 15:27:49 -07004139 decrypter_[level] = nullptr;
4140}
4141
4142const QuicDecrypter* QuicFramer::GetDecrypter(EncryptionLevel level) const {
4143 DCHECK(version_.KnowsWhichDecrypterToUse());
4144 return decrypter_[level].get();
4145}
4146
QUICHE teama6ef0a62019-03-07 20:34:33 -05004147const QuicDecrypter* QuicFramer::decrypter() const {
QUICHE team76086e42019-03-25 15:12:29 -07004148 return decrypter_[decrypter_level_].get();
QUICHE teama6ef0a62019-03-07 20:34:33 -05004149}
4150
4151const QuicDecrypter* QuicFramer::alternative_decrypter() const {
QUICHE team76086e42019-03-25 15:12:29 -07004152 if (alternative_decrypter_level_ == NUM_ENCRYPTION_LEVELS) {
4153 return nullptr;
4154 }
4155 return decrypter_[alternative_decrypter_level_].get();
QUICHE teama6ef0a62019-03-07 20:34:33 -05004156}
4157
4158void QuicFramer::SetEncrypter(EncryptionLevel level,
4159 std::unique_ptr<QuicEncrypter> encrypter) {
4160 DCHECK_GE(level, 0);
4161 DCHECK_LT(level, NUM_ENCRYPTION_LEVELS);
dschinazi4b5a68a2019-08-15 15:45:36 -07004162 QUIC_DVLOG(1) << ENDPOINT << "Setting encrypter at level "
4163 << QuicUtils::EncryptionLevelToString(level);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004164 encrypter_[level] = std::move(encrypter);
4165}
4166
4167size_t QuicFramer::EncryptInPlace(EncryptionLevel level,
4168 QuicPacketNumber packet_number,
4169 size_t ad_len,
4170 size_t total_len,
4171 size_t buffer_len,
4172 char* buffer) {
4173 DCHECK(packet_number.IsInitialized());
dschinazi2c5386e2019-04-16 16:37:37 -07004174 if (encrypter_[level] == nullptr) {
4175 QUIC_BUG << ENDPOINT
4176 << "Attempted to encrypt in place without encrypter at level "
4177 << QuicUtils::EncryptionLevelToString(level);
4178 RaiseError(QUIC_ENCRYPTION_FAILURE);
4179 return 0;
4180 }
4181
QUICHE teama6ef0a62019-03-07 20:34:33 -05004182 size_t output_length = 0;
4183 if (!encrypter_[level]->EncryptPacket(
4184 packet_number.ToUint64(),
4185 QuicStringPiece(buffer, ad_len), // Associated data
4186 QuicStringPiece(buffer + ad_len, total_len - ad_len), // Plaintext
4187 buffer + ad_len, // Destination buffer
4188 &output_length, buffer_len - ad_len)) {
4189 RaiseError(QUIC_ENCRYPTION_FAILURE);
4190 return 0;
4191 }
nharper55fa6132019-05-07 19:37:21 -07004192 if (version_.HasHeaderProtection() &&
4193 !ApplyHeaderProtection(level, buffer, ad_len + output_length, ad_len)) {
4194 QUIC_DLOG(ERROR) << "Applying header protection failed.";
4195 RaiseError(QUIC_ENCRYPTION_FAILURE);
4196 return 0;
4197 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004198
4199 return ad_len + output_length;
4200}
4201
nharper55fa6132019-05-07 19:37:21 -07004202namespace {
4203
4204const size_t kHPSampleLen = 16;
4205
4206constexpr bool IsLongHeader(uint8_t type_byte) {
4207 return (type_byte & FLAGS_LONG_HEADER) != 0;
4208}
4209
4210} // namespace
4211
4212bool QuicFramer::ApplyHeaderProtection(EncryptionLevel level,
4213 char* buffer,
4214 size_t buffer_len,
4215 size_t ad_len) {
4216 QuicDataReader buffer_reader(buffer, buffer_len);
4217 QuicDataWriter buffer_writer(buffer_len, buffer);
4218 // The sample starts 4 bytes after the start of the packet number.
4219 if (ad_len < last_written_packet_number_length_) {
4220 return false;
4221 }
4222 size_t pn_offset = ad_len - last_written_packet_number_length_;
4223 // Sample the ciphertext and generate the mask to use for header protection.
4224 size_t sample_offset = pn_offset + 4;
4225 QuicDataReader sample_reader(buffer, buffer_len);
4226 QuicStringPiece sample;
4227 if (!sample_reader.Seek(sample_offset) ||
4228 !sample_reader.ReadStringPiece(&sample, kHPSampleLen)) {
4229 QUIC_BUG << "Not enough bytes to sample: sample_offset " << sample_offset
4230 << ", sample len: " << kHPSampleLen
4231 << ", buffer len: " << buffer_len;
4232 return false;
4233 }
4234
4235 std::string mask = encrypter_[level]->GenerateHeaderProtectionMask(sample);
4236 if (mask.empty()) {
4237 QUIC_BUG << "Unable to generate header protection mask.";
4238 return false;
4239 }
4240 QuicDataReader mask_reader(mask.data(), mask.size());
4241
4242 // Apply the mask to the 4 or 5 least significant bits of the first byte.
4243 uint8_t bitmask = 0x1f;
4244 uint8_t type_byte;
4245 if (!buffer_reader.ReadUInt8(&type_byte)) {
4246 return false;
4247 }
4248 QuicLongHeaderType header_type;
4249 if (IsLongHeader(type_byte)) {
4250 bitmask = 0x0f;
fayang36825da2019-08-21 14:01:27 -07004251 if (!GetLongHeaderType(type_byte, &header_type)) {
nharper55fa6132019-05-07 19:37:21 -07004252 return false;
4253 }
4254 }
4255 uint8_t mask_byte;
4256 if (!mask_reader.ReadUInt8(&mask_byte) ||
4257 !buffer_writer.WriteUInt8(type_byte ^ (mask_byte & bitmask))) {
4258 return false;
4259 }
4260
4261 // Adjust |pn_offset| to account for the diversification nonce.
4262 if (IsLongHeader(type_byte) && header_type == ZERO_RTT_PROTECTED &&
4263 perspective_ == Perspective::IS_SERVER &&
4264 version_.handshake_protocol == PROTOCOL_QUIC_CRYPTO) {
4265 if (pn_offset <= kDiversificationNonceSize) {
4266 QUIC_BUG << "Expected diversification nonce, but not enough bytes";
4267 return false;
4268 }
4269 pn_offset -= kDiversificationNonceSize;
4270 }
4271 // Advance the reader and writer to the packet number. Both the reader and
4272 // writer have each read/written one byte.
4273 if (!buffer_writer.Seek(pn_offset - 1) ||
4274 !buffer_reader.Seek(pn_offset - 1)) {
4275 return false;
4276 }
4277 // Apply the rest of the mask to the packet number.
4278 for (size_t i = 0; i < last_written_packet_number_length_; ++i) {
4279 uint8_t buffer_byte;
4280 uint8_t mask_byte;
4281 if (!mask_reader.ReadUInt8(&mask_byte) ||
4282 !buffer_reader.ReadUInt8(&buffer_byte) ||
4283 !buffer_writer.WriteUInt8(buffer_byte ^ mask_byte)) {
4284 return false;
4285 }
4286 }
4287 return true;
4288}
4289
4290bool QuicFramer::RemoveHeaderProtection(QuicDataReader* reader,
4291 const QuicEncryptedPacket& packet,
4292 QuicPacketHeader* header,
4293 uint64_t* full_packet_number,
4294 std::vector<char>* associated_data) {
4295 EncryptionLevel expected_decryption_level = GetEncryptionLevel(*header);
4296 QuicDecrypter* decrypter = decrypter_[expected_decryption_level].get();
4297 if (decrypter == nullptr) {
4298 QUIC_DVLOG(1)
dschinazi4b5a68a2019-08-15 15:45:36 -07004299 << ENDPOINT
nharper55fa6132019-05-07 19:37:21 -07004300 << "No decrypter available for removing header protection at level "
dschinazi4b5a68a2019-08-15 15:45:36 -07004301 << QuicUtils::EncryptionLevelToString(expected_decryption_level);
nharper55fa6132019-05-07 19:37:21 -07004302 return false;
4303 }
4304
4305 bool has_diversification_nonce =
4306 header->form == IETF_QUIC_LONG_HEADER_PACKET &&
4307 header->long_packet_type == ZERO_RTT_PROTECTED &&
4308 perspective_ == Perspective::IS_CLIENT &&
4309 version_.handshake_protocol == PROTOCOL_QUIC_CRYPTO;
4310
4311 // Read a sample from the ciphertext and compute the mask to use for header
4312 // protection.
4313 QuicStringPiece remaining_packet = reader->PeekRemainingPayload();
4314 QuicDataReader sample_reader(remaining_packet);
4315
4316 // The sample starts 4 bytes after the start of the packet number.
4317 QuicStringPiece pn;
4318 if (!sample_reader.ReadStringPiece(&pn, 4)) {
4319 QUIC_DVLOG(1) << "Not enough data to sample";
4320 return false;
4321 }
4322 if (has_diversification_nonce) {
4323 // In Google QUIC, the diversification nonce comes between the packet number
4324 // and the sample.
4325 if (!sample_reader.Seek(kDiversificationNonceSize)) {
4326 QUIC_DVLOG(1) << "No diversification nonce to skip over";
4327 return false;
4328 }
4329 }
4330 std::string mask = decrypter->GenerateHeaderProtectionMask(&sample_reader);
4331 QuicDataReader mask_reader(mask.data(), mask.size());
4332 if (mask.empty()) {
4333 QUIC_DVLOG(1) << "Failed to compute mask";
4334 return false;
4335 }
4336
4337 // Unmask the rest of the type byte.
4338 uint8_t bitmask = 0x1f;
4339 if (IsLongHeader(header->type_byte)) {
4340 bitmask = 0x0f;
4341 }
4342 uint8_t mask_byte;
4343 if (!mask_reader.ReadUInt8(&mask_byte)) {
4344 QUIC_DVLOG(1) << "No first byte to read from mask";
4345 return false;
4346 }
4347 header->type_byte ^= (mask_byte & bitmask);
4348
4349 // Compute the packet number length.
4350 header->packet_number_length =
4351 static_cast<QuicPacketNumberLength>((header->type_byte & 0x03) + 1);
4352
4353 char pn_buffer[IETF_MAX_PACKET_NUMBER_LENGTH] = {};
4354 QuicDataWriter pn_writer(QUIC_ARRAYSIZE(pn_buffer), pn_buffer);
4355
4356 // Read the (protected) packet number from the reader and unmask the packet
4357 // number.
4358 for (size_t i = 0; i < header->packet_number_length; ++i) {
4359 uint8_t protected_pn_byte, mask_byte;
4360 if (!mask_reader.ReadUInt8(&mask_byte) ||
4361 !reader->ReadUInt8(&protected_pn_byte) ||
4362 !pn_writer.WriteUInt8(protected_pn_byte ^ mask_byte)) {
4363 QUIC_DVLOG(1) << "Failed to unmask packet number";
4364 return false;
4365 }
4366 }
4367 QuicDataReader packet_number_reader(pn_writer.data(), pn_writer.length());
4368 QuicPacketNumber base_packet_number;
4369 if (supports_multiple_packet_number_spaces_) {
4370 PacketNumberSpace pn_space = GetPacketNumberSpace(*header);
4371 if (pn_space == NUM_PACKET_NUMBER_SPACES) {
4372 return false;
4373 }
4374 base_packet_number = largest_decrypted_packet_numbers_[pn_space];
4375 } else {
4376 base_packet_number = largest_packet_number_;
4377 }
4378 if (!ProcessAndCalculatePacketNumber(
4379 &packet_number_reader, header->packet_number_length,
4380 base_packet_number, full_packet_number)) {
4381 return false;
4382 }
4383
4384 // Get the associated data, and apply the same unmasking operations to it.
4385 QuicStringPiece ad = GetAssociatedDataFromEncryptedPacket(
4386 version_.transport_version, packet,
4387 GetIncludedDestinationConnectionIdLength(*header),
4388 GetIncludedSourceConnectionIdLength(*header), header->version_flag,
4389 has_diversification_nonce, header->packet_number_length,
4390 header->retry_token_length_length, header->retry_token.length(),
4391 header->length_length);
4392 *associated_data = std::vector<char>(ad.begin(), ad.end());
4393 QuicDataWriter ad_writer(associated_data->size(), associated_data->data());
4394
4395 // Apply the unmasked type byte and packet number to |associated_data|.
4396 if (!ad_writer.WriteUInt8(header->type_byte)) {
4397 return false;
4398 }
4399 // Put the packet number at the end of the AD, or if there's a diversification
4400 // nonce, before that (which is at the end of the AD).
4401 size_t seek_len = ad_writer.remaining() - header->packet_number_length;
4402 if (has_diversification_nonce) {
4403 seek_len -= kDiversificationNonceSize;
4404 }
4405 if (!ad_writer.Seek(seek_len) ||
4406 !ad_writer.WriteBytes(pn_writer.data(), pn_writer.length())) {
4407 QUIC_DVLOG(1) << "Failed to apply unmasking operations to AD";
4408 return false;
4409 }
4410
4411 return true;
4412}
4413
QUICHE teama6ef0a62019-03-07 20:34:33 -05004414size_t QuicFramer::EncryptPayload(EncryptionLevel level,
4415 QuicPacketNumber packet_number,
4416 const QuicPacket& packet,
4417 char* buffer,
4418 size_t buffer_len) {
4419 DCHECK(packet_number.IsInitialized());
dschinazi2c5386e2019-04-16 16:37:37 -07004420 if (encrypter_[level] == nullptr) {
4421 QUIC_BUG << ENDPOINT << "Attempted to encrypt without encrypter at level "
4422 << QuicUtils::EncryptionLevelToString(level);
4423 RaiseError(QUIC_ENCRYPTION_FAILURE);
4424 return 0;
4425 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004426
4427 QuicStringPiece associated_data =
4428 packet.AssociatedData(version_.transport_version);
4429 // Copy in the header, because the encrypter only populates the encrypted
4430 // plaintext content.
4431 const size_t ad_len = associated_data.length();
4432 memmove(buffer, associated_data.data(), ad_len);
4433 // Encrypt the plaintext into the buffer.
4434 size_t output_length = 0;
4435 if (!encrypter_[level]->EncryptPacket(
4436 packet_number.ToUint64(), associated_data,
4437 packet.Plaintext(version_.transport_version), buffer + ad_len,
4438 &output_length, buffer_len - ad_len)) {
4439 RaiseError(QUIC_ENCRYPTION_FAILURE);
4440 return 0;
4441 }
nharper55fa6132019-05-07 19:37:21 -07004442 if (version_.HasHeaderProtection() &&
4443 !ApplyHeaderProtection(level, buffer, ad_len + output_length, ad_len)) {
4444 QUIC_DLOG(ERROR) << "Applying header protection failed.";
4445 RaiseError(QUIC_ENCRYPTION_FAILURE);
4446 return 0;
4447 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004448
4449 return ad_len + output_length;
4450}
4451
4452size_t QuicFramer::GetCiphertextSize(EncryptionLevel level,
4453 size_t plaintext_size) const {
4454 return encrypter_[level]->GetCiphertextSize(plaintext_size);
4455}
4456
4457size_t QuicFramer::GetMaxPlaintextSize(size_t ciphertext_size) {
4458 // In order to keep the code simple, we don't have the current encryption
4459 // level to hand. Both the NullEncrypter and AES-GCM have a tag length of 12.
4460 size_t min_plaintext_size = ciphertext_size;
4461
QUICHE team6987b4a2019-03-15 16:23:04 -07004462 for (int i = ENCRYPTION_INITIAL; i < NUM_ENCRYPTION_LEVELS; i++) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05004463 if (encrypter_[i] != nullptr) {
4464 size_t size = encrypter_[i]->GetMaxPlaintextSize(ciphertext_size);
4465 if (size < min_plaintext_size) {
4466 min_plaintext_size = size;
4467 }
4468 }
4469 }
4470
4471 return min_plaintext_size;
4472}
4473
4474bool QuicFramer::DecryptPayload(QuicStringPiece encrypted,
4475 QuicStringPiece associated_data,
4476 const QuicPacketHeader& header,
4477 char* decrypted_buffer,
4478 size_t buffer_length,
QUICHE team10b22a12019-03-21 15:31:42 -07004479 size_t* decrypted_length,
4480 EncryptionLevel* decrypted_level) {
nharper855d2172019-05-02 16:17:46 -07004481 if (!EncryptionLevelIsValid(decrypter_level_)) {
4482 QUIC_BUG << "Attempted to decrypt with bad decrypter_level_";
4483 return false;
4484 }
zhongyi546cc452019-04-12 15:27:49 -07004485 EncryptionLevel level = decrypter_level_;
4486 QuicDecrypter* decrypter = decrypter_[level].get();
QUICHE team76086e42019-03-25 15:12:29 -07004487 QuicDecrypter* alternative_decrypter = nullptr;
zhongyi546cc452019-04-12 15:27:49 -07004488 if (version().KnowsWhichDecrypterToUse()) {
nharper855d2172019-05-02 16:17:46 -07004489 if (header.form == GOOGLE_QUIC_PACKET) {
4490 QUIC_BUG << "Attempted to decrypt GOOGLE_QUIC_PACKET with a version that "
4491 "knows which decrypter to use";
4492 return false;
4493 }
zhongyi546cc452019-04-12 15:27:49 -07004494 level = GetEncryptionLevel(header);
nharper855d2172019-05-02 16:17:46 -07004495 if (!EncryptionLevelIsValid(level)) {
4496 QUIC_BUG << "Attempted to decrypt with bad level";
4497 return false;
4498 }
zhongyi546cc452019-04-12 15:27:49 -07004499 decrypter = decrypter_[level].get();
4500 if (decrypter == nullptr) {
4501 return false;
4502 }
4503 if (level == ENCRYPTION_ZERO_RTT &&
4504 perspective_ == Perspective::IS_CLIENT && header.nonce != nullptr) {
4505 decrypter->SetDiversificationNonce(*header.nonce);
4506 }
4507 } else if (alternative_decrypter_level_ != NUM_ENCRYPTION_LEVELS) {
nharper855d2172019-05-02 16:17:46 -07004508 if (!EncryptionLevelIsValid(alternative_decrypter_level_)) {
4509 QUIC_BUG << "Attempted to decrypt with bad alternative_decrypter_level_";
4510 return false;
4511 }
QUICHE team76086e42019-03-25 15:12:29 -07004512 alternative_decrypter = decrypter_[alternative_decrypter_level_].get();
4513 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004514
nharper855d2172019-05-02 16:17:46 -07004515 if (decrypter == nullptr) {
ianswettf919fb22019-05-13 06:42:11 -07004516 QUIC_BUG << "Attempting to decrypt without decrypter, encryption level:"
4517 << level << " version:" << version();
nharper855d2172019-05-02 16:17:46 -07004518 return false;
4519 }
zhongyi546cc452019-04-12 15:27:49 -07004520
4521 bool success = decrypter->DecryptPacket(
QUICHE teama6ef0a62019-03-07 20:34:33 -05004522 header.packet_number.ToUint64(), associated_data, encrypted,
4523 decrypted_buffer, decrypted_length, buffer_length);
4524 if (success) {
zhongyi546cc452019-04-12 15:27:49 -07004525 visitor_->OnDecryptedPacket(level);
4526 *decrypted_level = level;
QUICHE team76086e42019-03-25 15:12:29 -07004527 } else if (alternative_decrypter != nullptr) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05004528 if (header.nonce != nullptr) {
4529 DCHECK_EQ(perspective_, Perspective::IS_CLIENT);
QUICHE team76086e42019-03-25 15:12:29 -07004530 alternative_decrypter->SetDiversificationNonce(*header.nonce);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004531 }
4532 bool try_alternative_decryption = true;
4533 if (alternative_decrypter_level_ == ENCRYPTION_ZERO_RTT) {
4534 if (perspective_ == Perspective::IS_CLIENT) {
4535 if (header.nonce == nullptr) {
4536 // Can not use INITIAL decryption without a diversification nonce.
4537 try_alternative_decryption = false;
4538 }
4539 } else {
4540 DCHECK(header.nonce == nullptr);
4541 }
4542 }
4543
4544 if (try_alternative_decryption) {
QUICHE team76086e42019-03-25 15:12:29 -07004545 success = alternative_decrypter->DecryptPacket(
QUICHE teama6ef0a62019-03-07 20:34:33 -05004546 header.packet_number.ToUint64(), associated_data, encrypted,
4547 decrypted_buffer, decrypted_length, buffer_length);
4548 }
4549 if (success) {
4550 visitor_->OnDecryptedPacket(alternative_decrypter_level_);
QUICHE team10b22a12019-03-21 15:31:42 -07004551 *decrypted_level = decrypter_level_;
QUICHE teama6ef0a62019-03-07 20:34:33 -05004552 if (alternative_decrypter_latch_) {
nharper855d2172019-05-02 16:17:46 -07004553 if (!EncryptionLevelIsValid(alternative_decrypter_level_)) {
4554 QUIC_BUG << "Attempted to latch alternate decrypter with bad "
4555 "alternative_decrypter_level_";
4556 return false;
4557 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004558 // Switch to the alternative decrypter and latch so that we cannot
4559 // switch back.
QUICHE teama6ef0a62019-03-07 20:34:33 -05004560 decrypter_level_ = alternative_decrypter_level_;
QUICHE team76086e42019-03-25 15:12:29 -07004561 alternative_decrypter_level_ = NUM_ENCRYPTION_LEVELS;
QUICHE teama6ef0a62019-03-07 20:34:33 -05004562 } else {
4563 // Switch the alternative decrypter so that we use it first next time.
QUICHE teama6ef0a62019-03-07 20:34:33 -05004564 EncryptionLevel level = alternative_decrypter_level_;
4565 alternative_decrypter_level_ = decrypter_level_;
4566 decrypter_level_ = level;
4567 }
4568 }
4569 }
4570
4571 if (!success) {
dschinazi965ce092019-05-23 06:29:01 -07004572 QUIC_DVLOG(1) << ENDPOINT << "DecryptPacket failed for: " << header;
QUICHE teama6ef0a62019-03-07 20:34:33 -05004573 return false;
4574 }
4575
4576 return true;
4577}
4578
4579size_t QuicFramer::GetIetfAckFrameSize(const QuicAckFrame& frame) {
4580 // Type byte, largest_acked, and delay_time are straight-forward.
4581 size_t ack_frame_size = kQuicFrameTypeSize;
4582 QuicPacketNumber largest_acked = LargestAcked(frame);
4583 ack_frame_size += QuicDataWriter::GetVarInt62Len(largest_acked.ToUint64());
4584 uint64_t ack_delay_time_us;
4585 ack_delay_time_us = frame.ack_delay_time.ToMicroseconds();
fkastenholz4dc4ba32019-07-30 09:55:25 -07004586 ack_delay_time_us = ack_delay_time_us >> local_ack_delay_exponent_;
QUICHE teama6ef0a62019-03-07 20:34:33 -05004587 ack_frame_size += QuicDataWriter::GetVarInt62Len(ack_delay_time_us);
4588
4589 // If |ecn_counters_populated| is true and any of the ecn counters is non-0
4590 // then the ecn counters are included...
4591 if (frame.ecn_counters_populated &&
4592 (frame.ect_0_count || frame.ect_1_count || frame.ecn_ce_count)) {
4593 ack_frame_size += QuicDataWriter::GetVarInt62Len(frame.ect_0_count);
4594 ack_frame_size += QuicDataWriter::GetVarInt62Len(frame.ect_1_count);
4595 ack_frame_size += QuicDataWriter::GetVarInt62Len(frame.ecn_ce_count);
4596 }
4597
4598 // The rest (ack_block_count, first_ack_block, and additional ack
4599 // blocks, if any) depends:
4600 uint64_t ack_block_count = frame.packets.NumIntervals();
4601 if (ack_block_count == 0) {
4602 // If the QuicAckFrame has no Intervals, then it is interpreted
4603 // as an ack of a single packet at QuicAckFrame.largest_acked.
4604 // The resulting ack will consist of only the frame's
4605 // largest_ack & first_ack_block fields. The first ack block will be 0
4606 // (indicating a single packet) and the ack block_count will be 0.
4607 // Each 0 takes 1 byte when VarInt62 encoded.
4608 ack_frame_size += 2;
4609 return ack_frame_size;
4610 }
4611
4612 auto itr = frame.packets.rbegin();
4613 QuicPacketNumber ack_block_largest = largest_acked;
4614 QuicPacketNumber ack_block_smallest;
4615 if ((itr->max() - 1) == largest_acked) {
4616 // If largest_acked + 1 is equal to the Max() of the first Interval
4617 // in the QuicAckFrame then the first Interval is the first ack block of the
4618 // frame; remaining Intervals are additional ack blocks. The QuicAckFrame's
4619 // first Interval is encoded in the frame's largest_acked/first_ack_block,
4620 // the remaining Intervals are encoded in additional ack blocks in the
4621 // frame, and the packet's ack_block_count is the number of QuicAckFrame
4622 // Intervals - 1.
4623 ack_block_smallest = itr->min();
4624 itr++;
4625 ack_block_count--;
4626 } else {
4627 // If QuicAckFrame.largest_acked is NOT equal to the Max() of
4628 // the first Interval then it is interpreted as acking a single
4629 // packet at QuicAckFrame.largest_acked, with additional
4630 // Intervals indicating additional ack blocks. The encoding is
4631 // a) The packet's largest_acked is the QuicAckFrame's largest
4632 // acked,
4633 // b) the first ack block size is 0,
4634 // c) The packet's ack_block_count is the number of QuicAckFrame
4635 // Intervals, and
4636 // d) The QuicAckFrame Intervals are encoded in additional ack
4637 // blocks in the packet.
4638 ack_block_smallest = largest_acked;
4639 }
4640 size_t ack_block_count_size = QuicDataWriter::GetVarInt62Len(ack_block_count);
4641 ack_frame_size += ack_block_count_size;
4642
4643 uint64_t first_ack_block = ack_block_largest - ack_block_smallest;
4644 size_t first_ack_block_size = QuicDataWriter::GetVarInt62Len(first_ack_block);
4645 ack_frame_size += first_ack_block_size;
4646
4647 // Account for the remaining Intervals, if any.
4648 while (ack_block_count != 0) {
4649 uint64_t gap_size = ack_block_smallest - itr->max();
4650 // Decrement per the protocol specification
4651 size_t size_of_gap_size = QuicDataWriter::GetVarInt62Len(gap_size - 1);
4652 ack_frame_size += size_of_gap_size;
4653
4654 uint64_t block_size = itr->max() - itr->min();
4655 // Decrement per the protocol specification
4656 size_t size_of_block_size = QuicDataWriter::GetVarInt62Len(block_size - 1);
4657 ack_frame_size += size_of_block_size;
4658
4659 ack_block_smallest = itr->min();
4660 itr++;
4661 ack_block_count--;
4662 }
4663
4664 return ack_frame_size;
4665}
4666
4667size_t QuicFramer::GetAckFrameSize(
4668 const QuicAckFrame& ack,
dschinazi17d42422019-06-18 16:35:07 -07004669 QuicPacketNumberLength /*packet_number_length*/) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05004670 DCHECK(!ack.packets.Empty());
4671 size_t ack_size = 0;
4672
fkastenholz305e1732019-06-18 05:01:22 -07004673 if (VersionHasIetfQuicFrames(version_.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05004674 return GetIetfAckFrameSize(ack);
4675 }
4676 AckFrameInfo ack_info = GetAckFrameInfo(ack);
4677 QuicPacketNumberLength largest_acked_length =
4678 GetMinPacketNumberLength(version_.transport_version, LargestAcked(ack));
4679 QuicPacketNumberLength ack_block_length = GetMinPacketNumberLength(
4680 version_.transport_version, QuicPacketNumber(ack_info.max_block_length));
4681
4682 ack_size =
4683 GetMinAckFrameSize(version_.transport_version, largest_acked_length);
4684 // First ack block length.
4685 ack_size += ack_block_length;
4686 if (ack_info.num_ack_blocks != 0) {
4687 ack_size += kNumberOfAckBlocksSize;
4688 ack_size += std::min(ack_info.num_ack_blocks, kMaxAckBlocks) *
4689 (ack_block_length + PACKET_1BYTE_PACKET_NUMBER);
4690 }
4691
4692 // Include timestamps.
4693 if (process_timestamps_) {
4694 ack_size += GetAckFrameTimeStampSize(ack);
4695 }
4696
4697 return ack_size;
4698}
4699
4700size_t QuicFramer::GetAckFrameTimeStampSize(const QuicAckFrame& ack) {
4701 if (ack.received_packet_times.empty()) {
4702 return 0;
4703 }
4704
4705 return kQuicNumTimestampsLength + kQuicFirstTimestampLength +
4706 (kQuicTimestampLength + kQuicTimestampPacketNumberGapLength) *
4707 (ack.received_packet_times.size() - 1);
4708}
4709
4710size_t QuicFramer::ComputeFrameLength(
4711 const QuicFrame& frame,
4712 bool last_frame_in_packet,
4713 QuicPacketNumberLength packet_number_length) {
4714 switch (frame.type) {
4715 case STREAM_FRAME:
4716 return GetMinStreamFrameSize(
4717 version_.transport_version, frame.stream_frame.stream_id,
4718 frame.stream_frame.offset, last_frame_in_packet,
4719 frame.stream_frame.data_length) +
4720 frame.stream_frame.data_length;
4721 case CRYPTO_FRAME:
4722 return GetMinCryptoFrameSize(frame.crypto_frame->offset,
4723 frame.crypto_frame->data_length) +
4724 frame.crypto_frame->data_length;
4725 case ACK_FRAME: {
4726 return GetAckFrameSize(*frame.ack_frame, packet_number_length);
4727 }
4728 case STOP_WAITING_FRAME:
4729 return GetStopWaitingFrameSize(version_.transport_version,
4730 packet_number_length);
4731 case MTU_DISCOVERY_FRAME:
4732 // MTU discovery frames are serialized as ping frames.
4733 return kQuicFrameTypeSize;
4734 case MESSAGE_FRAME:
4735 return GetMessageFrameSize(version_.transport_version,
4736 last_frame_in_packet,
4737 frame.message_frame->message_length);
4738 case PADDING_FRAME:
4739 DCHECK(false);
4740 return 0;
4741 default:
4742 return GetRetransmittableControlFrameSize(version_.transport_version,
4743 frame);
4744 }
4745}
4746
4747bool QuicFramer::AppendTypeByte(const QuicFrame& frame,
4748 bool last_frame_in_packet,
4749 QuicDataWriter* writer) {
fkastenholz305e1732019-06-18 05:01:22 -07004750 if (VersionHasIetfQuicFrames(version_.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05004751 return AppendIetfTypeByte(frame, last_frame_in_packet, writer);
4752 }
4753 uint8_t type_byte = 0;
4754 switch (frame.type) {
4755 case STREAM_FRAME:
4756 type_byte =
4757 GetStreamFrameTypeByte(frame.stream_frame, last_frame_in_packet);
4758 break;
4759 case ACK_FRAME:
4760 return true;
4761 case MTU_DISCOVERY_FRAME:
4762 type_byte = static_cast<uint8_t>(PING_FRAME);
4763 break;
QUICHE teama6ef0a62019-03-07 20:34:33 -05004764 case NEW_CONNECTION_ID_FRAME:
4765 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -07004766 "Attempt to append NEW_CONNECTION_ID frame and not in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05004767 return RaiseError(QUIC_INTERNAL_ERROR);
4768 case RETIRE_CONNECTION_ID_FRAME:
4769 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -07004770 "Attempt to append RETIRE_CONNECTION_ID frame and not in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05004771 return RaiseError(QUIC_INTERNAL_ERROR);
4772 case NEW_TOKEN_FRAME:
4773 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -07004774 "Attempt to append NEW_TOKEN frame and not in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05004775 return RaiseError(QUIC_INTERNAL_ERROR);
fkastenholz3c4eabf2019-04-22 07:49:59 -07004776 case MAX_STREAMS_FRAME:
QUICHE teama6ef0a62019-03-07 20:34:33 -05004777 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -07004778 "Attempt to append MAX_STREAMS frame and not in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05004779 return RaiseError(QUIC_INTERNAL_ERROR);
fkastenholz3c4eabf2019-04-22 07:49:59 -07004780 case STREAMS_BLOCKED_FRAME:
QUICHE teama6ef0a62019-03-07 20:34:33 -05004781 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -07004782 "Attempt to append STREAMS_BLOCKED frame and not in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05004783 return RaiseError(QUIC_INTERNAL_ERROR);
4784 case PATH_RESPONSE_FRAME:
4785 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -07004786 "Attempt to append PATH_RESPONSE frame and not in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05004787 return RaiseError(QUIC_INTERNAL_ERROR);
4788 case PATH_CHALLENGE_FRAME:
4789 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -07004790 "Attempt to append PATH_CHALLENGE frame and not in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05004791 return RaiseError(QUIC_INTERNAL_ERROR);
4792 case STOP_SENDING_FRAME:
4793 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -07004794 "Attempt to append STOP_SENDING frame and not in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05004795 return RaiseError(QUIC_INTERNAL_ERROR);
4796 case MESSAGE_FRAME:
4797 return true;
4798
4799 default:
4800 type_byte = static_cast<uint8_t>(frame.type);
4801 break;
4802 }
4803
4804 return writer->WriteUInt8(type_byte);
4805}
4806
4807bool QuicFramer::AppendIetfTypeByte(const QuicFrame& frame,
4808 bool last_frame_in_packet,
4809 QuicDataWriter* writer) {
4810 uint8_t type_byte = 0;
4811 switch (frame.type) {
4812 case PADDING_FRAME:
4813 type_byte = IETF_PADDING;
4814 break;
4815 case RST_STREAM_FRAME:
4816 type_byte = IETF_RST_STREAM;
4817 break;
4818 case CONNECTION_CLOSE_FRAME:
fkastenholz72f509b2019-04-10 09:17:49 -07004819 switch (frame.connection_close_frame->close_type) {
4820 case IETF_QUIC_APPLICATION_CONNECTION_CLOSE:
4821 type_byte = IETF_APPLICATION_CLOSE;
4822 break;
4823 case IETF_QUIC_TRANSPORT_CONNECTION_CLOSE:
4824 type_byte = IETF_CONNECTION_CLOSE;
4825 break;
4826 default:
4827 set_detailed_error("Invalid QuicConnectionCloseFrame type.");
4828 return RaiseError(QUIC_INTERNAL_ERROR);
4829 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004830 break;
4831 case GOAWAY_FRAME:
4832 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -07004833 "Attempt to create non-IETF QUIC GOAWAY frame in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05004834 return RaiseError(QUIC_INTERNAL_ERROR);
4835 case WINDOW_UPDATE_FRAME:
4836 // Depending on whether there is a stream ID or not, will be either a
4837 // MAX_STREAM_DATA frame or a MAX_DATA frame.
4838 if (frame.window_update_frame->stream_id ==
4839 QuicUtils::GetInvalidStreamId(transport_version())) {
4840 type_byte = IETF_MAX_DATA;
4841 } else {
4842 type_byte = IETF_MAX_STREAM_DATA;
4843 }
4844 break;
4845 case BLOCKED_FRAME:
4846 if (frame.blocked_frame->stream_id ==
4847 QuicUtils::GetInvalidStreamId(transport_version())) {
4848 type_byte = IETF_BLOCKED;
4849 } else {
4850 type_byte = IETF_STREAM_BLOCKED;
4851 }
4852 break;
4853 case STOP_WAITING_FRAME:
4854 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -07004855 "Attempt to append type byte of STOP WAITING frame in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05004856 return RaiseError(QUIC_INTERNAL_ERROR);
4857 case PING_FRAME:
4858 type_byte = IETF_PING;
4859 break;
4860 case STREAM_FRAME:
4861 type_byte =
4862 GetStreamFrameTypeByte(frame.stream_frame, last_frame_in_packet);
4863 break;
4864 case ACK_FRAME:
4865 // Do nothing here, AppendIetfAckFrameAndTypeByte() will put the type byte
4866 // in the buffer.
4867 return true;
4868 case MTU_DISCOVERY_FRAME:
4869 // The path MTU discovery frame is encoded as a PING frame on the wire.
4870 type_byte = IETF_PING;
4871 break;
QUICHE teama6ef0a62019-03-07 20:34:33 -05004872 case NEW_CONNECTION_ID_FRAME:
4873 type_byte = IETF_NEW_CONNECTION_ID;
4874 break;
4875 case RETIRE_CONNECTION_ID_FRAME:
4876 type_byte = IETF_RETIRE_CONNECTION_ID;
4877 break;
4878 case NEW_TOKEN_FRAME:
4879 type_byte = IETF_NEW_TOKEN;
4880 break;
fkastenholz3c4eabf2019-04-22 07:49:59 -07004881 case MAX_STREAMS_FRAME:
4882 if (frame.max_streams_frame.unidirectional) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05004883 type_byte = IETF_MAX_STREAMS_UNIDIRECTIONAL;
fkastenholz3c4eabf2019-04-22 07:49:59 -07004884 } else {
4885 type_byte = IETF_MAX_STREAMS_BIDIRECTIONAL;
QUICHE teama6ef0a62019-03-07 20:34:33 -05004886 }
4887 break;
fkastenholz3c4eabf2019-04-22 07:49:59 -07004888 case STREAMS_BLOCKED_FRAME:
4889 if (frame.streams_blocked_frame.unidirectional) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05004890 type_byte = IETF_STREAMS_BLOCKED_UNIDIRECTIONAL;
fkastenholz3c4eabf2019-04-22 07:49:59 -07004891 } else {
4892 type_byte = IETF_STREAMS_BLOCKED_BIDIRECTIONAL;
QUICHE teama6ef0a62019-03-07 20:34:33 -05004893 }
4894 break;
4895 case PATH_RESPONSE_FRAME:
4896 type_byte = IETF_PATH_RESPONSE;
4897 break;
4898 case PATH_CHALLENGE_FRAME:
4899 type_byte = IETF_PATH_CHALLENGE;
4900 break;
4901 case STOP_SENDING_FRAME:
4902 type_byte = IETF_STOP_SENDING;
4903 break;
4904 case MESSAGE_FRAME:
4905 return true;
4906 case CRYPTO_FRAME:
4907 type_byte = IETF_CRYPTO;
4908 break;
4909 default:
4910 QUIC_BUG << "Attempt to generate a frame type for an unsupported value: "
4911 << frame.type;
4912 return false;
4913 }
4914 return writer->WriteUInt8(type_byte);
4915}
4916
4917// static
4918bool QuicFramer::AppendPacketNumber(QuicPacketNumberLength packet_number_length,
4919 QuicPacketNumber packet_number,
4920 QuicDataWriter* writer) {
4921 DCHECK(packet_number.IsInitialized());
4922 if (!IsValidPacketNumberLength(packet_number_length)) {
4923 QUIC_BUG << "Invalid packet_number_length: " << packet_number_length;
4924 return false;
4925 }
4926 return writer->WriteBytesToUInt64(packet_number_length,
4927 packet_number.ToUint64());
4928}
4929
4930// static
4931bool QuicFramer::AppendStreamId(size_t stream_id_length,
4932 QuicStreamId stream_id,
4933 QuicDataWriter* writer) {
4934 if (stream_id_length == 0 || stream_id_length > 4) {
4935 QUIC_BUG << "Invalid stream_id_length: " << stream_id_length;
4936 return false;
4937 }
4938 return writer->WriteBytesToUInt64(stream_id_length, stream_id);
4939}
4940
4941// static
4942bool QuicFramer::AppendStreamOffset(size_t offset_length,
4943 QuicStreamOffset offset,
4944 QuicDataWriter* writer) {
4945 if (offset_length == 1 || offset_length > 8) {
4946 QUIC_BUG << "Invalid stream_offset_length: " << offset_length;
4947 return false;
4948 }
4949
4950 return writer->WriteBytesToUInt64(offset_length, offset);
4951}
4952
4953// static
4954bool QuicFramer::AppendAckBlock(uint8_t gap,
4955 QuicPacketNumberLength length_length,
4956 uint64_t length,
4957 QuicDataWriter* writer) {
4958 if (length == 0) {
4959 if (!IsValidPacketNumberLength(length_length)) {
4960 QUIC_BUG << "Invalid packet_number_length: " << length_length;
4961 return false;
4962 }
4963 return writer->WriteUInt8(gap) &&
4964 writer->WriteBytesToUInt64(length_length, length);
4965 }
4966 return writer->WriteUInt8(gap) &&
4967 AppendPacketNumber(length_length, QuicPacketNumber(length), writer);
4968}
4969
4970bool QuicFramer::AppendStreamFrame(const QuicStreamFrame& frame,
4971 bool no_stream_frame_length,
4972 QuicDataWriter* writer) {
fkastenholz305e1732019-06-18 05:01:22 -07004973 if (VersionHasIetfQuicFrames(version_.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05004974 return AppendIetfStreamFrame(frame, no_stream_frame_length, writer);
4975 }
4976 if (!AppendStreamId(GetStreamIdSize(frame.stream_id), frame.stream_id,
4977 writer)) {
4978 QUIC_BUG << "Writing stream id size failed.";
4979 return false;
4980 }
4981 if (!AppendStreamOffset(
4982 GetStreamOffsetSize(version_.transport_version, frame.offset),
4983 frame.offset, writer)) {
4984 QUIC_BUG << "Writing offset size failed.";
4985 return false;
4986 }
4987 if (!no_stream_frame_length) {
dschinazi878cfb52019-06-17 17:12:58 -07004988 static_assert(
wubeff50282019-06-19 09:04:30 -07004989 std::numeric_limits<decltype(frame.data_length)>::max() <=
dschinazi878cfb52019-06-17 17:12:58 -07004990 std::numeric_limits<uint16_t>::max(),
4991 "If frame.data_length can hold more than a uint16_t than we need to "
4992 "check that frame.data_length <= std::numeric_limits<uint16_t>::max()");
4993 if (!writer->WriteUInt16(static_cast<uint16_t>(frame.data_length))) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05004994 QUIC_BUG << "Writing stream frame length failed";
4995 return false;
4996 }
4997 }
4998
4999 if (data_producer_ != nullptr) {
5000 DCHECK_EQ(nullptr, frame.data_buffer);
5001 if (frame.data_length == 0) {
5002 return true;
5003 }
5004 if (data_producer_->WriteStreamData(frame.stream_id, frame.offset,
5005 frame.data_length,
5006 writer) != WRITE_SUCCESS) {
5007 QUIC_BUG << "Writing frame data failed.";
5008 return false;
5009 }
5010 return true;
5011 }
5012
5013 if (!writer->WriteBytes(frame.data_buffer, frame.data_length)) {
5014 QUIC_BUG << "Writing frame data failed.";
5015 return false;
5016 }
5017 return true;
5018}
5019
QUICHE teama6ef0a62019-03-07 20:34:33 -05005020bool QuicFramer::AppendNewTokenFrame(const QuicNewTokenFrame& frame,
5021 QuicDataWriter* writer) {
5022 if (!writer->WriteVarInt62(static_cast<uint64_t>(frame.token.length()))) {
5023 set_detailed_error("Writing token length failed.");
5024 return false;
5025 }
5026 if (!writer->WriteBytes(frame.token.data(), frame.token.length())) {
5027 set_detailed_error("Writing token buffer failed.");
5028 return false;
5029 }
5030 return true;
5031}
5032
5033bool QuicFramer::ProcessNewTokenFrame(QuicDataReader* reader,
5034 QuicNewTokenFrame* frame) {
5035 uint64_t length;
5036 if (!reader->ReadVarInt62(&length)) {
5037 set_detailed_error("Unable to read new token length.");
5038 return false;
5039 }
5040 if (length > kMaxNewTokenTokenLength) {
5041 set_detailed_error("Token length larger than maximum.");
5042 return false;
5043 }
5044
5045 // TODO(ianswett): Don't use QuicStringPiece as an intermediary.
5046 QuicStringPiece data;
5047 if (!reader->ReadStringPiece(&data, length)) {
5048 set_detailed_error("Unable to read new token data.");
5049 return false;
5050 }
vasilvvc48c8712019-03-11 13:38:16 -07005051 frame->token = std::string(data);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005052 return true;
5053}
5054
5055// Add a new ietf-format stream frame.
5056// Bits controlling whether there is a frame-length and frame-offset
5057// are in the QuicStreamFrame.
5058bool QuicFramer::AppendIetfStreamFrame(const QuicStreamFrame& frame,
5059 bool last_frame_in_packet,
5060 QuicDataWriter* writer) {
5061 if (!writer->WriteVarInt62(static_cast<uint64_t>(frame.stream_id))) {
5062 set_detailed_error("Writing stream id failed.");
5063 return false;
5064 }
5065
5066 if (frame.offset != 0) {
5067 if (!writer->WriteVarInt62(static_cast<uint64_t>(frame.offset))) {
5068 set_detailed_error("Writing data offset failed.");
5069 return false;
5070 }
5071 }
5072
5073 if (!last_frame_in_packet) {
5074 if (!writer->WriteVarInt62(frame.data_length)) {
5075 set_detailed_error("Writing data length failed.");
5076 return false;
5077 }
5078 }
5079
5080 if (frame.data_length == 0) {
5081 return true;
5082 }
5083 if (data_producer_ == nullptr) {
5084 if (!writer->WriteBytes(frame.data_buffer, frame.data_length)) {
5085 set_detailed_error("Writing frame data failed.");
5086 return false;
5087 }
5088 } else {
5089 DCHECK_EQ(nullptr, frame.data_buffer);
5090
5091 if (data_producer_->WriteStreamData(frame.stream_id, frame.offset,
5092 frame.data_length,
5093 writer) != WRITE_SUCCESS) {
5094 set_detailed_error("Writing frame data failed.");
5095 return false;
5096 }
5097 }
5098 return true;
5099}
5100
5101bool QuicFramer::AppendCryptoFrame(const QuicCryptoFrame& frame,
5102 QuicDataWriter* writer) {
5103 if (!writer->WriteVarInt62(static_cast<uint64_t>(frame.offset))) {
5104 set_detailed_error("Writing data offset failed.");
5105 return false;
5106 }
5107 if (!writer->WriteVarInt62(static_cast<uint64_t>(frame.data_length))) {
5108 set_detailed_error("Writing data length failed.");
5109 return false;
5110 }
5111 if (data_producer_ == nullptr) {
5112 if (frame.data_buffer == nullptr ||
5113 !writer->WriteBytes(frame.data_buffer, frame.data_length)) {
5114 set_detailed_error("Writing frame data failed.");
5115 return false;
5116 }
5117 } else {
5118 DCHECK_EQ(nullptr, frame.data_buffer);
5119 if (!data_producer_->WriteCryptoData(frame.level, frame.offset,
5120 frame.data_length, writer)) {
5121 return false;
5122 }
5123 }
5124 return true;
5125}
5126
5127void QuicFramer::set_version(const ParsedQuicVersion version) {
5128 DCHECK(IsSupportedVersion(version)) << ParsedQuicVersionToString(version);
5129 version_ = version;
5130}
5131
5132bool QuicFramer::AppendAckFrameAndTypeByte(const QuicAckFrame& frame,
5133 QuicDataWriter* writer) {
fkastenholz305e1732019-06-18 05:01:22 -07005134 if (VersionHasIetfQuicFrames(transport_version())) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005135 return AppendIetfAckFrameAndTypeByte(frame, writer);
5136 }
5137
5138 const AckFrameInfo new_ack_info = GetAckFrameInfo(frame);
5139 QuicPacketNumber largest_acked = LargestAcked(frame);
5140 QuicPacketNumberLength largest_acked_length =
5141 GetMinPacketNumberLength(version_.transport_version, largest_acked);
5142 QuicPacketNumberLength ack_block_length =
5143 GetMinPacketNumberLength(version_.transport_version,
5144 QuicPacketNumber(new_ack_info.max_block_length));
5145 // Calculate available bytes for timestamps and ack blocks.
5146 int32_t available_timestamp_and_ack_block_bytes =
5147 writer->capacity() - writer->length() - ack_block_length -
5148 GetMinAckFrameSize(version_.transport_version, largest_acked_length) -
5149 (new_ack_info.num_ack_blocks != 0 ? kNumberOfAckBlocksSize : 0);
5150 DCHECK_LE(0, available_timestamp_and_ack_block_bytes);
5151
5152 // Write out the type byte by setting the low order bits and doing shifts
5153 // to make room for the next bit flags to be set.
5154 // Whether there are multiple ack blocks.
5155 uint8_t type_byte = 0;
5156 SetBit(&type_byte, new_ack_info.num_ack_blocks != 0,
5157 kQuicHasMultipleAckBlocksOffset);
5158
5159 SetBits(&type_byte, GetPacketNumberFlags(largest_acked_length),
5160 kQuicSequenceNumberLengthNumBits, kLargestAckedOffset);
5161
5162 SetBits(&type_byte, GetPacketNumberFlags(ack_block_length),
5163 kQuicSequenceNumberLengthNumBits, kActBlockLengthOffset);
5164
5165 type_byte |= kQuicFrameTypeAckMask;
5166
5167 if (!writer->WriteUInt8(type_byte)) {
5168 return false;
5169 }
5170
5171 size_t max_num_ack_blocks = available_timestamp_and_ack_block_bytes /
5172 (ack_block_length + PACKET_1BYTE_PACKET_NUMBER);
5173
5174 // Number of ack blocks.
5175 size_t num_ack_blocks =
5176 std::min(new_ack_info.num_ack_blocks, max_num_ack_blocks);
5177 if (num_ack_blocks > std::numeric_limits<uint8_t>::max()) {
5178 num_ack_blocks = std::numeric_limits<uint8_t>::max();
5179 }
5180
5181 // Largest acked.
5182 if (!AppendPacketNumber(largest_acked_length, largest_acked, writer)) {
5183 return false;
5184 }
5185
5186 // Largest acked delta time.
5187 uint64_t ack_delay_time_us = kUFloat16MaxValue;
5188 if (!frame.ack_delay_time.IsInfinite()) {
5189 DCHECK_LE(0u, frame.ack_delay_time.ToMicroseconds());
5190 ack_delay_time_us = frame.ack_delay_time.ToMicroseconds();
5191 }
5192 if (!writer->WriteUFloat16(ack_delay_time_us)) {
5193 return false;
5194 }
5195
5196 if (num_ack_blocks > 0) {
5197 if (!writer->WriteBytes(&num_ack_blocks, 1)) {
5198 return false;
5199 }
5200 }
5201
5202 // First ack block length.
5203 if (!AppendPacketNumber(ack_block_length,
5204 QuicPacketNumber(new_ack_info.first_block_length),
5205 writer)) {
5206 return false;
5207 }
5208
5209 // Ack blocks.
5210 if (num_ack_blocks > 0) {
5211 size_t num_ack_blocks_written = 0;
5212 // Append, in descending order from the largest ACKed packet, a series of
5213 // ACK blocks that represents the successfully acknoweldged packets. Each
5214 // appended gap/block length represents a descending delta from the previous
5215 // block. i.e.:
5216 // |--- length ---|--- gap ---|--- length ---|--- gap ---|--- largest ---|
5217 // For gaps larger than can be represented by a single encoded gap, a 0
5218 // length gap of the maximum is used, i.e.:
5219 // |--- length ---|--- gap ---|- 0 -|--- gap ---|--- largest ---|
5220 auto itr = frame.packets.rbegin();
5221 QuicPacketNumber previous_start = itr->min();
5222 ++itr;
5223
5224 for (;
5225 itr != frame.packets.rend() && num_ack_blocks_written < num_ack_blocks;
5226 previous_start = itr->min(), ++itr) {
5227 const auto& interval = *itr;
5228 const uint64_t total_gap = previous_start - interval.max();
5229 const size_t num_encoded_gaps =
5230 (total_gap + std::numeric_limits<uint8_t>::max() - 1) /
5231 std::numeric_limits<uint8_t>::max();
QUICHE teama6ef0a62019-03-07 20:34:33 -05005232
5233 // Append empty ACK blocks because the gap is longer than a single gap.
5234 for (size_t i = 1;
5235 i < num_encoded_gaps && num_ack_blocks_written < num_ack_blocks;
5236 ++i) {
5237 if (!AppendAckBlock(std::numeric_limits<uint8_t>::max(),
5238 ack_block_length, 0, writer)) {
5239 return false;
5240 }
5241 ++num_ack_blocks_written;
5242 }
5243 if (num_ack_blocks_written >= num_ack_blocks) {
5244 if (QUIC_PREDICT_FALSE(num_ack_blocks_written != num_ack_blocks)) {
5245 QUIC_BUG << "Wrote " << num_ack_blocks_written
5246 << ", expected to write " << num_ack_blocks;
5247 }
5248 break;
5249 }
5250
5251 const uint8_t last_gap =
5252 total_gap -
5253 (num_encoded_gaps - 1) * std::numeric_limits<uint8_t>::max();
5254 // Append the final ACK block with a non-empty size.
5255 if (!AppendAckBlock(last_gap, ack_block_length,
5256 PacketNumberIntervalLength(interval), writer)) {
5257 return false;
5258 }
5259 ++num_ack_blocks_written;
5260 }
5261 DCHECK_EQ(num_ack_blocks, num_ack_blocks_written);
5262 }
5263 // Timestamps.
5264 // If we don't process timestamps or if we don't have enough available space
5265 // to append all the timestamps, don't append any of them.
5266 if (process_timestamps_ && writer->capacity() - writer->length() >=
5267 GetAckFrameTimeStampSize(frame)) {
5268 if (!AppendTimestampsToAckFrame(frame, writer)) {
5269 return false;
5270 }
5271 } else {
5272 uint8_t num_received_packets = 0;
5273 if (!writer->WriteBytes(&num_received_packets, 1)) {
5274 return false;
5275 }
5276 }
5277
5278 return true;
5279}
5280
5281bool QuicFramer::AppendTimestampsToAckFrame(const QuicAckFrame& frame,
5282 QuicDataWriter* writer) {
5283 DCHECK_GE(std::numeric_limits<uint8_t>::max(),
5284 frame.received_packet_times.size());
5285 // num_received_packets is only 1 byte.
5286 if (frame.received_packet_times.size() >
5287 std::numeric_limits<uint8_t>::max()) {
5288 return false;
5289 }
5290
5291 uint8_t num_received_packets = frame.received_packet_times.size();
5292 if (!writer->WriteBytes(&num_received_packets, 1)) {
5293 return false;
5294 }
5295 if (num_received_packets == 0) {
5296 return true;
5297 }
5298
5299 auto it = frame.received_packet_times.begin();
5300 QuicPacketNumber packet_number = it->first;
5301 uint64_t delta_from_largest_observed = LargestAcked(frame) - packet_number;
5302
5303 DCHECK_GE(std::numeric_limits<uint8_t>::max(), delta_from_largest_observed);
5304 if (delta_from_largest_observed > std::numeric_limits<uint8_t>::max()) {
5305 return false;
5306 }
5307
5308 if (!writer->WriteUInt8(delta_from_largest_observed)) {
5309 return false;
5310 }
5311
5312 // Use the lowest 4 bytes of the time delta from the creation_time_.
5313 const uint64_t time_epoch_delta_us = UINT64_C(1) << 32;
5314 uint32_t time_delta_us =
5315 static_cast<uint32_t>((it->second - creation_time_).ToMicroseconds() &
5316 (time_epoch_delta_us - 1));
5317 if (!writer->WriteUInt32(time_delta_us)) {
5318 return false;
5319 }
5320
5321 QuicTime prev_time = it->second;
5322
5323 for (++it; it != frame.received_packet_times.end(); ++it) {
5324 packet_number = it->first;
5325 delta_from_largest_observed = LargestAcked(frame) - packet_number;
5326
5327 if (delta_from_largest_observed > std::numeric_limits<uint8_t>::max()) {
5328 return false;
5329 }
5330
5331 if (!writer->WriteUInt8(delta_from_largest_observed)) {
5332 return false;
5333 }
5334
5335 uint64_t frame_time_delta_us = (it->second - prev_time).ToMicroseconds();
5336 prev_time = it->second;
5337 if (!writer->WriteUFloat16(frame_time_delta_us)) {
5338 return false;
5339 }
5340 }
5341 return true;
5342}
5343
5344bool QuicFramer::AppendStopWaitingFrame(const QuicPacketHeader& header,
5345 const QuicStopWaitingFrame& frame,
5346 QuicDataWriter* writer) {
fayangd4291e42019-05-30 10:31:21 -07005347 DCHECK(!VersionHasIetfInvariantHeader(version_.transport_version));
QUICHE teama6ef0a62019-03-07 20:34:33 -05005348 DCHECK(frame.least_unacked.IsInitialized() &&
5349 header.packet_number >= frame.least_unacked);
5350 const uint64_t least_unacked_delta =
5351 header.packet_number - frame.least_unacked;
5352 const uint64_t length_shift = header.packet_number_length * 8;
5353
5354 if (least_unacked_delta >> length_shift > 0) {
5355 QUIC_BUG << "packet_number_length " << header.packet_number_length
5356 << " is too small for least_unacked_delta: " << least_unacked_delta
5357 << " packet_number:" << header.packet_number
5358 << " least_unacked:" << frame.least_unacked
5359 << " version:" << version_.transport_version;
5360 return false;
5361 }
5362 if (least_unacked_delta == 0) {
5363 return writer->WriteBytesToUInt64(header.packet_number_length,
5364 least_unacked_delta);
5365 }
5366 if (!AppendPacketNumber(header.packet_number_length,
5367 QuicPacketNumber(least_unacked_delta), writer)) {
5368 QUIC_BUG << " seq failed: " << header.packet_number_length;
5369 return false;
5370 }
5371
5372 return true;
5373}
5374
5375int QuicFramer::CalculateIetfAckBlockCount(const QuicAckFrame& frame,
dschinazi17d42422019-06-18 16:35:07 -07005376 QuicDataWriter* /*writer*/,
QUICHE teama6ef0a62019-03-07 20:34:33 -05005377 size_t available_space) {
5378 // Number of blocks requested in the frame
5379 uint64_t ack_block_count = frame.packets.NumIntervals();
5380
5381 auto itr = frame.packets.rbegin();
5382
5383 int actual_block_count = 1;
5384 uint64_t block_length = itr->max() - itr->min();
5385 size_t encoded_size = QuicDataWriter::GetVarInt62Len(block_length);
5386 if (encoded_size > available_space) {
5387 return 0;
5388 }
5389 available_space -= encoded_size;
5390 QuicPacketNumber previous_ack_end = itr->min();
5391 ack_block_count--;
5392
5393 while (ack_block_count) {
5394 // Each block is a gap followed by another ACK. Calculate each value,
5395 // determine the encoded lengths, and check against the available space.
5396 itr++;
5397 size_t gap = previous_ack_end - itr->max() - 1;
5398 encoded_size = QuicDataWriter::GetVarInt62Len(gap);
5399
5400 // Add the ACK block.
5401 block_length = itr->max() - itr->min();
5402 encoded_size += QuicDataWriter::GetVarInt62Len(block_length);
5403
5404 if (encoded_size > available_space) {
5405 // No room for this block, so what we've
5406 // done up to now is all that can be done.
5407 return actual_block_count;
5408 }
5409 available_space -= encoded_size;
5410 actual_block_count++;
5411 previous_ack_end = itr->min();
5412 ack_block_count--;
5413 }
5414 // Ran through the whole thing! We can do all blocks.
5415 return actual_block_count;
5416}
5417
5418bool QuicFramer::AppendIetfAckFrameAndTypeByte(const QuicAckFrame& frame,
5419 QuicDataWriter* writer) {
5420 // Assume frame is an IETF_ACK frame. If |ecn_counters_populated| is true and
5421 // any of the ECN counters is non-0 then turn it into an IETF_ACK+ECN frame.
5422 uint8_t type = IETF_ACK;
5423 if (frame.ecn_counters_populated &&
5424 (frame.ect_0_count || frame.ect_1_count || frame.ecn_ce_count)) {
5425 type = IETF_ACK_ECN;
5426 }
5427
5428 if (!writer->WriteUInt8(type)) {
5429 set_detailed_error("No room for frame-type");
5430 return false;
5431 }
5432
5433 QuicPacketNumber largest_acked = LargestAcked(frame);
5434 if (!writer->WriteVarInt62(largest_acked.ToUint64())) {
5435 set_detailed_error("No room for largest-acked in ack frame");
5436 return false;
5437 }
5438
5439 uint64_t ack_delay_time_us = kVarInt62MaxValue;
5440 if (!frame.ack_delay_time.IsInfinite()) {
5441 DCHECK_LE(0u, frame.ack_delay_time.ToMicroseconds());
5442 ack_delay_time_us = frame.ack_delay_time.ToMicroseconds();
fkastenholz4dc4ba32019-07-30 09:55:25 -07005443 ack_delay_time_us = ack_delay_time_us >> local_ack_delay_exponent_;
QUICHE teama6ef0a62019-03-07 20:34:33 -05005444 }
5445
5446 if (!writer->WriteVarInt62(ack_delay_time_us)) {
5447 set_detailed_error("No room for ack-delay in ack frame");
5448 return false;
5449 }
5450 if (type == IETF_ACK_ECN) {
5451 // Encode the ACK ECN fields
5452 if (!writer->WriteVarInt62(frame.ect_0_count)) {
5453 set_detailed_error("No room for ect_0_count in ack frame");
5454 return false;
5455 }
5456 if (!writer->WriteVarInt62(frame.ect_1_count)) {
5457 set_detailed_error("No room for ect_1_count in ack frame");
5458 return false;
5459 }
5460 if (!writer->WriteVarInt62(frame.ecn_ce_count)) {
5461 set_detailed_error("No room for ecn_ce_count in ack frame");
5462 return false;
5463 }
5464 }
5465
5466 uint64_t ack_block_count = frame.packets.NumIntervals();
5467 if (ack_block_count == 0) {
5468 // If the QuicAckFrame has no Intervals, then it is interpreted
5469 // as an ack of a single packet at QuicAckFrame.largest_acked.
5470 // The resulting ack will consist of only the frame's
5471 // largest_ack & first_ack_block fields. The first ack block will be 0
5472 // (indicating a single packet) and the ack block_count will be 0.
5473 if (!writer->WriteVarInt62(0)) {
5474 set_detailed_error("No room for ack block count in ack frame");
5475 return false;
5476 }
5477 // size of the first block is 1 packet
5478 if (!writer->WriteVarInt62(0)) {
5479 set_detailed_error("No room for first ack block in ack frame");
5480 return false;
5481 }
5482 return true;
5483 }
5484 // Case 2 or 3
5485 auto itr = frame.packets.rbegin();
5486
5487 QuicPacketNumber ack_block_largest(largest_acked);
5488 QuicPacketNumber ack_block_smallest;
5489 if ((itr->max() - 1) == QuicPacketNumber(largest_acked)) {
5490 // If largest_acked + 1 is equal to the Max() of the first Interval
5491 // in the QuicAckFrame then the first Interval is the first ack block of the
5492 // frame; remaining Intervals are additional ack blocks. The QuicAckFrame's
5493 // first Interval is encoded in the frame's largest_acked/first_ack_block,
5494 // the remaining Intervals are encoded in additional ack blocks in the
5495 // frame, and the packet's ack_block_count is the number of QuicAckFrame
5496 // Intervals - 1.
5497 ack_block_smallest = itr->min();
5498 itr++;
5499 ack_block_count--;
5500 } else {
5501 // If QuicAckFrame.largest_acked is NOT equal to the Max() of
5502 // the first Interval then it is interpreted as acking a single
5503 // packet at QuicAckFrame.largest_acked, with additional
5504 // Intervals indicating additional ack blocks. The encoding is
5505 // a) The packet's largest_acked is the QuicAckFrame's largest
5506 // acked,
5507 // b) the first ack block size is 0,
5508 // c) The packet's ack_block_count is the number of QuicAckFrame
5509 // Intervals, and
5510 // d) The QuicAckFrame Intervals are encoded in additional ack
5511 // blocks in the packet.
5512 ack_block_smallest = largest_acked;
5513 }
5514
5515 if (!writer->WriteVarInt62(ack_block_count)) {
5516 set_detailed_error("No room for ack block count in ack frame");
5517 return false;
5518 }
5519
5520 uint64_t first_ack_block = ack_block_largest - ack_block_smallest;
5521 if (!writer->WriteVarInt62(first_ack_block)) {
5522 set_detailed_error("No room for first ack block in ack frame");
5523 return false;
5524 }
5525
5526 // For the remaining QuicAckFrame Intervals, if any
5527 while (ack_block_count != 0) {
5528 uint64_t gap_size = ack_block_smallest - itr->max();
5529 if (!writer->WriteVarInt62(gap_size - 1)) {
5530 set_detailed_error("No room for gap block in ack frame");
5531 return false;
5532 }
5533
5534 uint64_t block_size = itr->max() - itr->min();
5535 if (!writer->WriteVarInt62(block_size - 1)) {
5536 set_detailed_error("No room for nth ack block in ack frame");
5537 return false;
5538 }
5539
5540 ack_block_smallest = itr->min();
5541 itr++;
5542 ack_block_count--;
5543 }
5544 return true;
5545}
5546
5547bool QuicFramer::AppendRstStreamFrame(const QuicRstStreamFrame& frame,
5548 QuicDataWriter* writer) {
fkastenholz305e1732019-06-18 05:01:22 -07005549 if (VersionHasIetfQuicFrames(version_.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005550 return AppendIetfResetStreamFrame(frame, writer);
5551 }
5552 if (!writer->WriteUInt32(frame.stream_id)) {
5553 return false;
5554 }
5555
5556 if (!writer->WriteUInt64(frame.byte_offset)) {
5557 return false;
5558 }
5559
5560 uint32_t error_code = static_cast<uint32_t>(frame.error_code);
5561 if (!writer->WriteUInt32(error_code)) {
5562 return false;
5563 }
5564
5565 return true;
5566}
5567
5568bool QuicFramer::AppendConnectionCloseFrame(
5569 const QuicConnectionCloseFrame& frame,
5570 QuicDataWriter* writer) {
fkastenholz305e1732019-06-18 05:01:22 -07005571 if (VersionHasIetfQuicFrames(version_.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005572 return AppendIetfConnectionCloseFrame(frame, writer);
5573 }
fkastenholze9d71a82019-04-09 05:12:13 -07005574 uint32_t error_code = static_cast<uint32_t>(frame.quic_error_code);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005575 if (!writer->WriteUInt32(error_code)) {
5576 return false;
5577 }
5578 if (!writer->WriteStringPiece16(TruncateErrorString(frame.error_details))) {
5579 return false;
5580 }
5581 return true;
5582}
5583
5584bool QuicFramer::AppendGoAwayFrame(const QuicGoAwayFrame& frame,
5585 QuicDataWriter* writer) {
5586 uint32_t error_code = static_cast<uint32_t>(frame.error_code);
5587 if (!writer->WriteUInt32(error_code)) {
5588 return false;
5589 }
5590 uint32_t stream_id = static_cast<uint32_t>(frame.last_good_stream_id);
5591 if (!writer->WriteUInt32(stream_id)) {
5592 return false;
5593 }
5594 if (!writer->WriteStringPiece16(TruncateErrorString(frame.reason_phrase))) {
5595 return false;
5596 }
5597 return true;
5598}
5599
5600bool QuicFramer::AppendWindowUpdateFrame(const QuicWindowUpdateFrame& frame,
5601 QuicDataWriter* writer) {
5602 uint32_t stream_id = static_cast<uint32_t>(frame.stream_id);
5603 if (!writer->WriteUInt32(stream_id)) {
5604 return false;
5605 }
5606 if (!writer->WriteUInt64(frame.byte_offset)) {
5607 return false;
5608 }
5609 return true;
5610}
5611
5612bool QuicFramer::AppendBlockedFrame(const QuicBlockedFrame& frame,
5613 QuicDataWriter* writer) {
fkastenholz305e1732019-06-18 05:01:22 -07005614 if (VersionHasIetfQuicFrames(version_.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005615 if (frame.stream_id == QuicUtils::GetInvalidStreamId(transport_version())) {
5616 return AppendIetfBlockedFrame(frame, writer);
5617 }
5618 return AppendStreamBlockedFrame(frame, writer);
5619 }
5620 uint32_t stream_id = static_cast<uint32_t>(frame.stream_id);
5621 if (!writer->WriteUInt32(stream_id)) {
5622 return false;
5623 }
5624 return true;
5625}
5626
5627bool QuicFramer::AppendPaddingFrame(const QuicPaddingFrame& frame,
5628 QuicDataWriter* writer) {
5629 if (frame.num_padding_bytes == 0) {
5630 return false;
5631 }
5632 if (frame.num_padding_bytes < 0) {
5633 QUIC_BUG_IF(frame.num_padding_bytes != -1);
5634 writer->WritePadding();
5635 return true;
5636 }
5637 // Please note, num_padding_bytes includes type byte which has been written.
5638 return writer->WritePaddingBytes(frame.num_padding_bytes - 1);
5639}
5640
5641bool QuicFramer::AppendMessageFrameAndTypeByte(const QuicMessageFrame& frame,
5642 bool last_frame_in_packet,
5643 QuicDataWriter* writer) {
5644 uint8_t type_byte = last_frame_in_packet ? IETF_EXTENSION_MESSAGE_NO_LENGTH
5645 : IETF_EXTENSION_MESSAGE;
5646 if (!writer->WriteUInt8(type_byte)) {
5647 return false;
5648 }
5649 if (!last_frame_in_packet && !writer->WriteVarInt62(frame.message_length)) {
5650 return false;
5651 }
5652 for (const auto& slice : frame.message_data) {
5653 if (!writer->WriteBytes(slice.data(), slice.length())) {
5654 return false;
5655 }
5656 }
5657 return true;
5658}
5659
5660bool QuicFramer::RaiseError(QuicErrorCode error) {
5661 QUIC_DLOG(INFO) << ENDPOINT << "Error: " << QuicErrorCodeToString(error)
5662 << " detail: " << detailed_error_;
5663 set_error(error);
nharper55fa6132019-05-07 19:37:21 -07005664 if (visitor_) {
5665 visitor_->OnError(this);
5666 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05005667 return false;
5668}
5669
5670bool QuicFramer::IsVersionNegotiation(
5671 const QuicPacketHeader& header,
5672 bool packet_has_ietf_packet_header) const {
dschinazi072da7c2019-05-07 17:57:42 -07005673 if (!packet_has_ietf_packet_header &&
5674 perspective_ == Perspective::IS_CLIENT) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005675 return header.version_flag;
5676 }
5677 if (header.form == IETF_QUIC_SHORT_HEADER_PACKET) {
5678 return false;
5679 }
5680 return header.long_packet_type == VERSION_NEGOTIATION;
5681}
5682
QUICHE teama6ef0a62019-03-07 20:34:33 -05005683bool QuicFramer::AppendIetfConnectionCloseFrame(
5684 const QuicConnectionCloseFrame& frame,
5685 QuicDataWriter* writer) {
fkastenholz72f509b2019-04-10 09:17:49 -07005686 if (frame.close_type != IETF_QUIC_TRANSPORT_CONNECTION_CLOSE &&
5687 frame.close_type != IETF_QUIC_APPLICATION_CONNECTION_CLOSE) {
5688 QUIC_BUG << "Invalid close_type for writing IETF CONNECTION CLOSE.";
5689 set_detailed_error("Invalid close_type for writing IETF CONNECTION CLOSE.");
5690 return false;
5691 }
5692
fkastenholzd57d3f92019-07-16 09:05:17 -07005693 uint64_t close_code = 0;
5694 if (frame.close_type == IETF_QUIC_TRANSPORT_CONNECTION_CLOSE) {
5695 close_code = static_cast<uint64_t>(frame.transport_error_code);
5696 } else if (frame.close_type == IETF_QUIC_APPLICATION_CONNECTION_CLOSE) {
5697 close_code = static_cast<uint64_t>(frame.application_error_code);
5698 }
5699
5700 if (!writer->WriteVarInt62(close_code)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005701 set_detailed_error("Can not write connection close frame error code");
5702 return false;
5703 }
fkastenholze9d71a82019-04-09 05:12:13 -07005704
fkastenholz72f509b2019-04-10 09:17:49 -07005705 if (frame.close_type == IETF_QUIC_TRANSPORT_CONNECTION_CLOSE) {
5706 // Write the frame-type of the frame causing the error only
5707 // if it's a CONNECTION_CLOSE/Transport.
5708 if (!writer->WriteVarInt62(frame.transport_close_frame_type)) {
5709 set_detailed_error("Writing frame type failed.");
5710 return false;
5711 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05005712 }
5713
fkastenholzb4dade72019-08-05 06:54:20 -07005714 // There may be additional error information available in the extracted error
5715 // code. Encode the error information in the reason phrase and serialize the
5716 // result.
5717 std::string final_error_string =
5718 GenerateErrorString(frame.error_details, frame.extracted_error_code);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005719 if (!writer->WriteStringPieceVarInt62(
fkastenholzb4dade72019-08-05 06:54:20 -07005720 TruncateErrorString(final_error_string))) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005721 set_detailed_error("Can not write connection close phrase");
5722 return false;
5723 }
5724 return true;
5725}
5726
QUICHE teama6ef0a62019-03-07 20:34:33 -05005727bool QuicFramer::ProcessIetfConnectionCloseFrame(
5728 QuicDataReader* reader,
fkastenholze9d71a82019-04-09 05:12:13 -07005729 QuicConnectionCloseType type,
QUICHE teama6ef0a62019-03-07 20:34:33 -05005730 QuicConnectionCloseFrame* frame) {
fkastenholze9d71a82019-04-09 05:12:13 -07005731 frame->close_type = type;
fkastenholzd57d3f92019-07-16 09:05:17 -07005732 uint64_t error_code;
fkastenholzb4dade72019-08-05 06:54:20 -07005733
fkastenholzd57d3f92019-07-16 09:05:17 -07005734 if (!reader->ReadVarInt62(&error_code)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005735 set_detailed_error("Unable to read connection close error code.");
5736 return false;
5737 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05005738
fkastenholzb4dade72019-08-05 06:54:20 -07005739 // TODO(fkastenholz): When error codes uniformly go to uint64, remove the
5740 // range check.
fkastenholzd57d3f92019-07-16 09:05:17 -07005741 if (frame->close_type == IETF_QUIC_TRANSPORT_CONNECTION_CLOSE) {
5742 if (error_code > 0xffff) {
5743 frame->transport_error_code =
5744 static_cast<QuicIetfTransportErrorCodes>(0xffff);
5745 QUIC_DLOG(ERROR) << "Transport error code " << error_code << " > 0xffff";
5746 } else {
5747 frame->transport_error_code =
5748 static_cast<QuicIetfTransportErrorCodes>(error_code);
5749 }
5750 } else if (frame->close_type == IETF_QUIC_APPLICATION_CONNECTION_CLOSE) {
5751 if (error_code > 0xffff) {
5752 frame->application_error_code = 0xffff;
5753 QUIC_DLOG(ERROR) << "Application error code " << error_code
5754 << " > 0xffff";
5755 } else {
5756 frame->application_error_code = static_cast<uint16_t>(error_code);
5757 }
5758 }
fkastenholzb4dade72019-08-05 06:54:20 -07005759
fkastenholz72f509b2019-04-10 09:17:49 -07005760 if (type == IETF_QUIC_TRANSPORT_CONNECTION_CLOSE) {
5761 // The frame-type of the frame causing the error is present only
5762 // if it's a CONNECTION_CLOSE/Transport.
5763 if (!reader->ReadVarInt62(&frame->transport_close_frame_type)) {
5764 set_detailed_error("Unable to read connection close frame type.");
5765 return false;
5766 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05005767 }
5768
5769 uint64_t phrase_length;
5770 if (!reader->ReadVarInt62(&phrase_length)) {
5771 set_detailed_error("Unable to read connection close error details.");
5772 return false;
5773 }
fkastenholzb4dade72019-08-05 06:54:20 -07005774
QUICHE teama6ef0a62019-03-07 20:34:33 -05005775 QuicStringPiece phrase;
5776 if (!reader->ReadStringPiece(&phrase, static_cast<size_t>(phrase_length))) {
5777 set_detailed_error("Unable to read connection close error details.");
5778 return false;
5779 }
vasilvvc48c8712019-03-11 13:38:16 -07005780 frame->error_details = std::string(phrase);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005781
fkastenholzb4dade72019-08-05 06:54:20 -07005782 // The frame may have an extracted error code in it. Look for it and
5783 // extract it. If it's not present, MaybeExtract will return
5784 // QUIC_IETF_GQUIC_ERROR_MISSING.
fkastenholz488a4622019-08-26 06:24:46 -07005785 MaybeExtractQuicErrorCode(frame);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005786 return true;
5787}
5788
5789// IETF Quic Path Challenge/Response frames.
5790bool QuicFramer::ProcessPathChallengeFrame(QuicDataReader* reader,
5791 QuicPathChallengeFrame* frame) {
5792 if (!reader->ReadBytes(frame->data_buffer.data(),
5793 frame->data_buffer.size())) {
5794 set_detailed_error("Can not read path challenge data.");
5795 return false;
5796 }
5797 return true;
5798}
5799
5800bool QuicFramer::ProcessPathResponseFrame(QuicDataReader* reader,
5801 QuicPathResponseFrame* frame) {
5802 if (!reader->ReadBytes(frame->data_buffer.data(),
5803 frame->data_buffer.size())) {
5804 set_detailed_error("Can not read path response data.");
5805 return false;
5806 }
5807 return true;
5808}
5809
5810bool QuicFramer::AppendPathChallengeFrame(const QuicPathChallengeFrame& frame,
5811 QuicDataWriter* writer) {
5812 if (!writer->WriteBytes(frame.data_buffer.data(), frame.data_buffer.size())) {
5813 set_detailed_error("Writing Path Challenge data failed.");
5814 return false;
5815 }
5816 return true;
5817}
5818
5819bool QuicFramer::AppendPathResponseFrame(const QuicPathResponseFrame& frame,
5820 QuicDataWriter* writer) {
5821 if (!writer->WriteBytes(frame.data_buffer.data(), frame.data_buffer.size())) {
5822 set_detailed_error("Writing Path Response data failed.");
5823 return false;
5824 }
5825 return true;
5826}
5827
5828// Add a new ietf-format stream reset frame.
5829// General format is
5830// stream id
5831// application error code
5832// final offset
5833bool QuicFramer::AppendIetfResetStreamFrame(const QuicRstStreamFrame& frame,
5834 QuicDataWriter* writer) {
5835 if (!writer->WriteVarInt62(static_cast<uint64_t>(frame.stream_id))) {
5836 set_detailed_error("Writing reset-stream stream id failed.");
5837 return false;
5838 }
fkastenholz07300e52019-07-16 11:51:37 -07005839 if (!writer->WriteVarInt62(static_cast<uint64_t>(frame.ietf_error_code))) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005840 set_detailed_error("Writing reset-stream error code failed.");
5841 return false;
5842 }
5843 if (!writer->WriteVarInt62(static_cast<uint64_t>(frame.byte_offset))) {
5844 set_detailed_error("Writing reset-stream final-offset failed.");
5845 return false;
5846 }
5847 return true;
5848}
5849
5850bool QuicFramer::ProcessIetfResetStreamFrame(QuicDataReader* reader,
5851 QuicRstStreamFrame* frame) {
5852 // Get Stream ID from frame. ReadVarIntStreamID returns false
5853 // if either A) there is a read error or B) the resulting value of
5854 // the Stream ID is larger than the maximum allowed value.
fkastenholz3c4eabf2019-04-22 07:49:59 -07005855 if (!reader->ReadVarIntU32(&frame->stream_id)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005856 set_detailed_error("Unable to read rst stream stream id.");
5857 return false;
5858 }
5859
fkastenholz07300e52019-07-16 11:51:37 -07005860 uint64_t error_code;
5861 if (!reader->ReadVarInt62(&error_code)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005862 set_detailed_error("Unable to read rst stream error code.");
5863 return false;
5864 }
fkastenholz07300e52019-07-16 11:51:37 -07005865 if (error_code > 0xffff) {
5866 frame->ietf_error_code = 0xffff;
5867 QUIC_DLOG(ERROR) << "Reset stream error code (" << error_code
5868 << ") > 0xffff";
5869 } else {
5870 frame->ietf_error_code = static_cast<uint16_t>(error_code);
5871 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05005872
5873 if (!reader->ReadVarInt62(&frame->byte_offset)) {
5874 set_detailed_error("Unable to read rst stream sent byte offset.");
5875 return false;
5876 }
5877 return true;
5878}
5879
5880bool QuicFramer::ProcessStopSendingFrame(
5881 QuicDataReader* reader,
5882 QuicStopSendingFrame* stop_sending_frame) {
fkastenholz3c4eabf2019-04-22 07:49:59 -07005883 if (!reader->ReadVarIntU32(&stop_sending_frame->stream_id)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005884 set_detailed_error("Unable to read stop sending stream id.");
5885 return false;
5886 }
5887
fkastenholz733552e2019-07-16 11:16:58 -07005888 uint64_t error_code;
5889 if (!reader->ReadVarInt62(&error_code)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005890 set_detailed_error("Unable to read stop sending application error code.");
5891 return false;
5892 }
fkastenholz733552e2019-07-16 11:16:58 -07005893 // TODO(fkastenholz): when error codes go to uint64_t, remove this.
5894 if (error_code > 0xffff) {
5895 stop_sending_frame->application_error_code = 0xffff;
5896 QUIC_DLOG(ERROR) << "Stop sending error code (" << error_code
5897 << ") > 0xffff";
5898 } else {
5899 stop_sending_frame->application_error_code =
5900 static_cast<uint16_t>(error_code);
5901 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05005902 return true;
5903}
5904
5905bool QuicFramer::AppendStopSendingFrame(
5906 const QuicStopSendingFrame& stop_sending_frame,
5907 QuicDataWriter* writer) {
5908 if (!writer->WriteVarInt62(stop_sending_frame.stream_id)) {
5909 set_detailed_error("Can not write stop sending stream id");
5910 return false;
5911 }
fkastenholz733552e2019-07-16 11:16:58 -07005912 if (!writer->WriteVarInt62(
5913 static_cast<uint64_t>(stop_sending_frame.application_error_code))) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005914 set_detailed_error("Can not write application error code");
5915 return false;
5916 }
5917 return true;
5918}
5919
5920// Append/process IETF-Format MAX_DATA Frame
5921bool QuicFramer::AppendMaxDataFrame(const QuicWindowUpdateFrame& frame,
5922 QuicDataWriter* writer) {
5923 if (!writer->WriteVarInt62(frame.byte_offset)) {
5924 set_detailed_error("Can not write MAX_DATA byte-offset");
5925 return false;
5926 }
5927 return true;
5928}
5929
5930bool QuicFramer::ProcessMaxDataFrame(QuicDataReader* reader,
5931 QuicWindowUpdateFrame* frame) {
5932 frame->stream_id = QuicUtils::GetInvalidStreamId(transport_version());
5933 if (!reader->ReadVarInt62(&frame->byte_offset)) {
5934 set_detailed_error("Can not read MAX_DATA byte-offset");
5935 return false;
5936 }
5937 return true;
5938}
5939
5940// Append/process IETF-Format MAX_STREAM_DATA Frame
5941bool QuicFramer::AppendMaxStreamDataFrame(const QuicWindowUpdateFrame& frame,
5942 QuicDataWriter* writer) {
5943 if (!writer->WriteVarInt62(frame.stream_id)) {
5944 set_detailed_error("Can not write MAX_STREAM_DATA stream id");
5945 return false;
5946 }
5947 if (!writer->WriteVarInt62(frame.byte_offset)) {
5948 set_detailed_error("Can not write MAX_STREAM_DATA byte-offset");
5949 return false;
5950 }
5951 return true;
5952}
5953
5954bool QuicFramer::ProcessMaxStreamDataFrame(QuicDataReader* reader,
5955 QuicWindowUpdateFrame* frame) {
fkastenholz3c4eabf2019-04-22 07:49:59 -07005956 if (!reader->ReadVarIntU32(&frame->stream_id)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005957 set_detailed_error("Can not read MAX_STREAM_DATA stream id");
5958 return false;
5959 }
5960 if (!reader->ReadVarInt62(&frame->byte_offset)) {
5961 set_detailed_error("Can not read MAX_STREAM_DATA byte-count");
5962 return false;
5963 }
5964 return true;
5965}
5966
fkastenholz3c4eabf2019-04-22 07:49:59 -07005967bool QuicFramer::AppendMaxStreamsFrame(const QuicMaxStreamsFrame& frame,
QUICHE teama6ef0a62019-03-07 20:34:33 -05005968 QuicDataWriter* writer) {
fkastenholz3c4eabf2019-04-22 07:49:59 -07005969 if (!writer->WriteVarInt62(frame.stream_count)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005970 set_detailed_error("Can not write MAX_STREAMS stream count");
5971 return false;
5972 }
5973 return true;
5974}
5975
5976bool QuicFramer::ProcessMaxStreamsFrame(QuicDataReader* reader,
fkastenholz3c4eabf2019-04-22 07:49:59 -07005977 QuicMaxStreamsFrame* frame,
QUICHE teama6ef0a62019-03-07 20:34:33 -05005978 uint64_t frame_type) {
fkastenholz3c4eabf2019-04-22 07:49:59 -07005979 if (!reader->ReadVarIntU32(&frame->stream_count)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005980 set_detailed_error("Can not read MAX_STREAMS stream count.");
5981 return false;
5982 }
fkastenholz3c4eabf2019-04-22 07:49:59 -07005983 frame->unidirectional = (frame_type == IETF_MAX_STREAMS_UNIDIRECTIONAL);
5984 return true;
QUICHE teama6ef0a62019-03-07 20:34:33 -05005985}
5986
5987bool QuicFramer::AppendIetfBlockedFrame(const QuicBlockedFrame& frame,
5988 QuicDataWriter* writer) {
5989 if (!writer->WriteVarInt62(frame.offset)) {
5990 set_detailed_error("Can not write blocked offset.");
5991 return false;
5992 }
5993 return true;
5994}
5995
5996bool QuicFramer::ProcessIetfBlockedFrame(QuicDataReader* reader,
5997 QuicBlockedFrame* frame) {
5998 // Indicates that it is a BLOCKED frame (as opposed to STREAM_BLOCKED).
5999 frame->stream_id = QuicUtils::GetInvalidStreamId(transport_version());
6000 if (!reader->ReadVarInt62(&frame->offset)) {
6001 set_detailed_error("Can not read blocked offset.");
6002 return false;
6003 }
6004 return true;
6005}
6006
6007bool QuicFramer::AppendStreamBlockedFrame(const QuicBlockedFrame& frame,
6008 QuicDataWriter* writer) {
6009 if (!writer->WriteVarInt62(frame.stream_id)) {
6010 set_detailed_error("Can not write stream blocked stream id.");
6011 return false;
6012 }
6013 if (!writer->WriteVarInt62(frame.offset)) {
6014 set_detailed_error("Can not write stream blocked offset.");
6015 return false;
6016 }
6017 return true;
6018}
6019
6020bool QuicFramer::ProcessStreamBlockedFrame(QuicDataReader* reader,
6021 QuicBlockedFrame* frame) {
fkastenholz3c4eabf2019-04-22 07:49:59 -07006022 if (!reader->ReadVarIntU32(&frame->stream_id)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05006023 set_detailed_error("Can not read stream blocked stream id.");
6024 return false;
6025 }
6026 if (!reader->ReadVarInt62(&frame->offset)) {
6027 set_detailed_error("Can not read stream blocked offset.");
6028 return false;
6029 }
6030 return true;
6031}
6032
fkastenholz3c4eabf2019-04-22 07:49:59 -07006033bool QuicFramer::AppendStreamsBlockedFrame(const QuicStreamsBlockedFrame& frame,
6034 QuicDataWriter* writer) {
6035 if (!writer->WriteVarInt62(frame.stream_count)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05006036 set_detailed_error("Can not write STREAMS_BLOCKED stream count");
6037 return false;
6038 }
6039 return true;
6040}
6041
6042bool QuicFramer::ProcessStreamsBlockedFrame(QuicDataReader* reader,
fkastenholz3c4eabf2019-04-22 07:49:59 -07006043 QuicStreamsBlockedFrame* frame,
QUICHE teama6ef0a62019-03-07 20:34:33 -05006044 uint64_t frame_type) {
fkastenholz3c4eabf2019-04-22 07:49:59 -07006045 if (!reader->ReadVarIntU32(&frame->stream_count)) {
6046 set_detailed_error("Can not read STREAMS_BLOCKED stream count.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05006047 return false;
6048 }
fkastenholz3c4eabf2019-04-22 07:49:59 -07006049 frame->unidirectional = (frame_type == IETF_STREAMS_BLOCKED_UNIDIRECTIONAL);
6050
QUICHE teama6ef0a62019-03-07 20:34:33 -05006051 // TODO(fkastenholz): handle properly when the STREAMS_BLOCKED
6052 // frame is implemented and passed up to the stream ID manager.
fkastenholz3c4eabf2019-04-22 07:49:59 -07006053 if (frame->stream_count >
6054 QuicUtils::GetMaxStreamCount(
6055 (frame_type == IETF_STREAMS_BLOCKED_UNIDIRECTIONAL),
6056 ((perspective_ == Perspective::IS_CLIENT)
6057 ? Perspective::IS_SERVER
6058 : Perspective::IS_CLIENT))) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05006059 // If stream count is such that the resulting stream ID would exceed our
6060 // implementation limit, generate an error.
6061 set_detailed_error(
6062 "STREAMS_BLOCKED stream count exceeds implementation limit.");
6063 return false;
6064 }
fkastenholz3c4eabf2019-04-22 07:49:59 -07006065 return true;
QUICHE teama6ef0a62019-03-07 20:34:33 -05006066}
6067
6068bool QuicFramer::AppendNewConnectionIdFrame(
6069 const QuicNewConnectionIdFrame& frame,
6070 QuicDataWriter* writer) {
6071 if (!writer->WriteVarInt62(frame.sequence_number)) {
6072 set_detailed_error("Can not write New Connection ID sequence number");
6073 return false;
6074 }
fkastenholz1c19fc22019-07-12 11:06:19 -07006075 if (!writer->WriteVarInt62(frame.retire_prior_to)) {
6076 set_detailed_error("Can not write New Connection ID retire_prior_to");
6077 return false;
6078 }
dschinazicf5b1e22019-07-17 18:35:17 -07006079 if (!writer->WriteLengthPrefixedConnectionId(frame.connection_id)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05006080 set_detailed_error("Can not write New Connection ID frame connection ID");
6081 return false;
6082 }
6083
6084 if (!writer->WriteBytes(
6085 static_cast<const void*>(&frame.stateless_reset_token),
6086 sizeof(frame.stateless_reset_token))) {
6087 set_detailed_error("Can not write New Connection ID Reset Token");
6088 return false;
6089 }
6090 return true;
6091}
6092
6093bool QuicFramer::ProcessNewConnectionIdFrame(QuicDataReader* reader,
6094 QuicNewConnectionIdFrame* frame) {
6095 if (!reader->ReadVarInt62(&frame->sequence_number)) {
6096 set_detailed_error(
6097 "Unable to read new connection ID frame sequence number.");
6098 return false;
6099 }
6100
fkastenholz1c19fc22019-07-12 11:06:19 -07006101 if (!reader->ReadVarInt62(&frame->retire_prior_to)) {
6102 set_detailed_error(
6103 "Unable to read new connection ID frame retire_prior_to.");
6104 return false;
6105 }
6106 if (frame->retire_prior_to > frame->sequence_number) {
6107 set_detailed_error("Retire_prior_to > sequence_number.");
6108 return false;
6109 }
dschinazicf5b1e22019-07-17 18:35:17 -07006110
6111 if (!reader->ReadLengthPrefixedConnectionId(&frame->connection_id)) {
6112 set_detailed_error("Unable to read new connection ID frame connection id.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05006113 return false;
6114 }
6115
dschinazicf5b1e22019-07-17 18:35:17 -07006116 if (!QuicUtils::IsConnectionIdValidForVersion(frame->connection_id,
6117 transport_version())) {
QUICHE team0131a5b2019-03-20 15:23:27 -07006118 set_detailed_error("Invalid new connection ID length for version.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05006119 return false;
6120 }
6121
QUICHE teama6ef0a62019-03-07 20:34:33 -05006122 if (!reader->ReadBytes(&frame->stateless_reset_token,
6123 sizeof(frame->stateless_reset_token))) {
6124 set_detailed_error("Can not read new connection ID frame reset token.");
6125 return false;
6126 }
6127 return true;
6128}
6129
6130bool QuicFramer::AppendRetireConnectionIdFrame(
6131 const QuicRetireConnectionIdFrame& frame,
6132 QuicDataWriter* writer) {
6133 if (!writer->WriteVarInt62(frame.sequence_number)) {
6134 set_detailed_error("Can not write Retire Connection ID sequence number");
6135 return false;
6136 }
6137 return true;
6138}
6139
6140bool QuicFramer::ProcessRetireConnectionIdFrame(
6141 QuicDataReader* reader,
6142 QuicRetireConnectionIdFrame* frame) {
6143 if (!reader->ReadVarInt62(&frame->sequence_number)) {
6144 set_detailed_error(
6145 "Unable to read retire connection ID frame sequence number.");
6146 return false;
6147 }
6148 return true;
6149}
6150
6151uint8_t QuicFramer::GetStreamFrameTypeByte(const QuicStreamFrame& frame,
6152 bool last_frame_in_packet) const {
fkastenholz305e1732019-06-18 05:01:22 -07006153 if (VersionHasIetfQuicFrames(version_.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05006154 return GetIetfStreamFrameTypeByte(frame, last_frame_in_packet);
6155 }
6156 uint8_t type_byte = 0;
6157 // Fin bit.
6158 type_byte |= frame.fin ? kQuicStreamFinMask : 0;
6159
6160 // Data Length bit.
6161 type_byte <<= kQuicStreamDataLengthShift;
6162 type_byte |= last_frame_in_packet ? 0 : kQuicStreamDataLengthMask;
6163
6164 // Offset 3 bits.
6165 type_byte <<= kQuicStreamShift;
6166 const size_t offset_len =
6167 GetStreamOffsetSize(version_.transport_version, frame.offset);
6168 if (offset_len > 0) {
6169 type_byte |= offset_len - 1;
6170 }
6171
6172 // stream id 2 bits.
6173 type_byte <<= kQuicStreamIdShift;
6174 type_byte |= GetStreamIdSize(frame.stream_id) - 1;
6175 type_byte |= kQuicFrameTypeStreamMask; // Set Stream Frame Type to 1.
6176
6177 return type_byte;
6178}
6179
6180uint8_t QuicFramer::GetIetfStreamFrameTypeByte(
6181 const QuicStreamFrame& frame,
6182 bool last_frame_in_packet) const {
fkastenholz305e1732019-06-18 05:01:22 -07006183 DCHECK(VersionHasIetfQuicFrames(version_.transport_version));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006184 uint8_t type_byte = IETF_STREAM;
6185 if (!last_frame_in_packet) {
6186 type_byte |= IETF_STREAM_FRAME_LEN_BIT;
6187 }
6188 if (frame.offset != 0) {
6189 type_byte |= IETF_STREAM_FRAME_OFF_BIT;
6190 }
6191 if (frame.fin) {
6192 type_byte |= IETF_STREAM_FRAME_FIN_BIT;
6193 }
6194 return type_byte;
6195}
6196
6197void QuicFramer::InferPacketHeaderTypeFromVersion() {
6198 // This function should only be called when server connection negotiates the
6199 // version.
6200 DCHECK(perspective_ == Perspective::IS_SERVER &&
6201 !infer_packet_header_type_from_version_);
6202 infer_packet_header_type_from_version_ = true;
6203}
6204
QUICHE team10b22a12019-03-21 15:31:42 -07006205void QuicFramer::EnableMultiplePacketNumberSpacesSupport() {
6206 if (supports_multiple_packet_number_spaces_) {
6207 QUIC_BUG << "Multiple packet number spaces has already been enabled";
6208 return;
6209 }
6210 if (largest_packet_number_.IsInitialized()) {
6211 QUIC_BUG << "Try to enable multiple packet number spaces support after any "
6212 "packet has been received.";
6213 return;
6214 }
6215
6216 supports_multiple_packet_number_spaces_ = true;
6217}
6218
fayangccbab732019-05-13 10:11:25 -07006219// static
6220QuicErrorCode QuicFramer::ProcessPacketDispatcher(
6221 const QuicEncryptedPacket& packet,
dschinazib42a8c52019-05-30 09:45:01 -07006222 uint8_t expected_destination_connection_id_length,
fayangccbab732019-05-13 10:11:25 -07006223 PacketHeaderFormat* format,
6224 bool* version_flag,
6225 QuicVersionLabel* version_label,
fayangccbab732019-05-13 10:11:25 -07006226 QuicConnectionId* destination_connection_id,
dschinazib42a8c52019-05-30 09:45:01 -07006227 QuicConnectionId* source_connection_id,
fayangccbab732019-05-13 10:11:25 -07006228 std::string* detailed_error) {
dschinazi48ac9192019-07-31 00:07:26 -07006229 DCHECK(!GetQuicReloadableFlag(quic_use_parse_public_header));
fayangccbab732019-05-13 10:11:25 -07006230 QuicDataReader reader(packet.data(), packet.length());
6231
dschinazib42a8c52019-05-30 09:45:01 -07006232 *source_connection_id = EmptyQuicConnectionId();
fayangccbab732019-05-13 10:11:25 -07006233 uint8_t first_byte;
6234 if (!reader.ReadBytes(&first_byte, 1)) {
6235 *detailed_error = "Unable to read first byte.";
6236 return QUIC_INVALID_PACKET_HEADER;
6237 }
dschinazib42a8c52019-05-30 09:45:01 -07006238 uint8_t destination_connection_id_length = 0, source_connection_id_length = 0;
fayangccbab732019-05-13 10:11:25 -07006239 if (!QuicUtils::IsIetfPacketHeader(first_byte)) {
6240 *format = GOOGLE_QUIC_PACKET;
6241 *version_flag = (first_byte & PACKET_PUBLIC_FLAGS_VERSION) != 0;
dschinazib42a8c52019-05-30 09:45:01 -07006242 destination_connection_id_length =
fayangccbab732019-05-13 10:11:25 -07006243 first_byte & PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID;
dschinazib42a8c52019-05-30 09:45:01 -07006244 if (destination_connection_id_length == 0 ||
fayangccbab732019-05-13 10:11:25 -07006245 !reader.ReadConnectionId(destination_connection_id,
dschinazib42a8c52019-05-30 09:45:01 -07006246 destination_connection_id_length)) {
fayangccbab732019-05-13 10:11:25 -07006247 *detailed_error = "Unable to read ConnectionId.";
6248 return QUIC_INVALID_PACKET_HEADER;
6249 }
6250 if (*version_flag && !ProcessVersionLabel(&reader, version_label)) {
6251 *detailed_error = "Unable to read protocol version.";
6252 return QUIC_INVALID_PACKET_HEADER;
6253 }
6254 return QUIC_NO_ERROR;
6255 }
6256
6257 *format = GetIetfPacketHeaderFormat(first_byte);
6258 QUIC_DVLOG(1) << "Dispatcher: Processing IETF QUIC packet, format: "
6259 << *format;
6260 *version_flag = *format == IETF_QUIC_LONG_HEADER_PACKET;
6261 if (*format == IETF_QUIC_LONG_HEADER_PACKET) {
6262 if (!ProcessVersionLabel(&reader, version_label)) {
6263 *detailed_error = "Unable to read protocol version.";
6264 return QUIC_INVALID_PACKET_HEADER;
6265 }
dschinazi8ff74822019-05-28 16:37:20 -07006266 // Set should_update_expected_server_connection_id_length to true to bypass
fayangccbab732019-05-13 10:11:25 -07006267 // connection ID lengths validation.
dschinazi8ff74822019-05-28 16:37:20 -07006268 uint8_t unused_expected_server_connection_id_length = 0;
fayangccbab732019-05-13 10:11:25 -07006269 if (!ProcessAndValidateIetfConnectionIdLength(
6270 &reader, ParseQuicVersionLabel(*version_label),
dschinazi334f0232019-05-29 16:08:53 -07006271 Perspective::IS_SERVER,
dschinazi8ff74822019-05-28 16:37:20 -07006272 /*should_update_expected_server_connection_id_length=*/true,
6273 &unused_expected_server_connection_id_length,
dschinazib42a8c52019-05-30 09:45:01 -07006274 &destination_connection_id_length, &source_connection_id_length,
6275 detailed_error)) {
fayangccbab732019-05-13 10:11:25 -07006276 return QUIC_INVALID_PACKET_HEADER;
6277 }
6278 } else {
dschinazib42a8c52019-05-30 09:45:01 -07006279 // For short header packets, expected_destination_connection_id_length
6280 // is used to determine the destination_connection_id_length.
6281 destination_connection_id_length =
6282 expected_destination_connection_id_length;
6283 DCHECK_EQ(0, source_connection_id_length);
fayangccbab732019-05-13 10:11:25 -07006284 }
6285 // Read destination connection ID.
6286 if (!reader.ReadConnectionId(destination_connection_id,
dschinazib42a8c52019-05-30 09:45:01 -07006287 destination_connection_id_length)) {
6288 *detailed_error = "Unable to read destination connection ID.";
6289 return QUIC_INVALID_PACKET_HEADER;
6290 }
6291 // Read source connection ID.
dschinazi5e1a7b22019-07-31 12:23:21 -07006292 if (!reader.ReadConnectionId(source_connection_id,
dschinazib42a8c52019-05-30 09:45:01 -07006293 source_connection_id_length)) {
6294 *detailed_error = "Unable to read source connection ID.";
fayangccbab732019-05-13 10:11:25 -07006295 return QUIC_INVALID_PACKET_HEADER;
6296 }
6297 return QUIC_NO_ERROR;
6298}
6299
dschinazide0f6dc2019-05-15 16:10:11 -07006300// static
dschinazi48ac9192019-07-31 00:07:26 -07006301QuicErrorCode QuicFramer::ParsePublicHeaderDispatcher(
6302 const QuicEncryptedPacket& packet,
6303 uint8_t expected_destination_connection_id_length,
6304 PacketHeaderFormat* format,
6305 bool* version_present,
6306 bool* has_length_prefix,
6307 QuicVersionLabel* version_label,
6308 ParsedQuicVersion* parsed_version,
6309 QuicConnectionId* destination_connection_id,
6310 QuicConnectionId* source_connection_id,
6311 bool* retry_token_present,
6312 QuicStringPiece* retry_token,
6313 std::string* detailed_error) {
6314 QuicDataReader reader(packet.data(), packet.length());
6315 if (reader.IsDoneReading()) {
6316 *detailed_error = "Unable to read first byte.";
6317 return QUIC_INVALID_PACKET_HEADER;
6318 }
6319 const uint8_t first_byte = reader.PeekByte();
6320 const bool ietf_format = QuicUtils::IsIetfPacketHeader(first_byte);
6321 uint8_t unused_first_byte;
6322 QuicVariableLengthIntegerLength retry_token_length_length;
6323 QuicLongHeaderType unused_log_packet_type;
6324 const QuicErrorCode error_code = ParsePublicHeader(
6325 &reader, expected_destination_connection_id_length, ietf_format,
6326 &unused_first_byte, format, version_present, has_length_prefix,
6327 version_label, parsed_version, destination_connection_id,
6328 source_connection_id, &unused_log_packet_type, &retry_token_length_length,
6329 retry_token, detailed_error);
6330 *retry_token_present =
6331 retry_token_length_length != VARIABLE_LENGTH_INTEGER_LENGTH_0;
6332 return error_code;
6333}
6334
6335// static
6336QuicErrorCode QuicFramer::ParsePublicHeaderGoogleQuic(
6337 QuicDataReader* reader,
6338 uint8_t* first_byte,
6339 PacketHeaderFormat* format,
6340 bool* version_present,
6341 QuicVersionLabel* version_label,
dschinazi243eabc2019-08-05 16:15:29 -07006342 ParsedQuicVersion* parsed_version,
dschinazi48ac9192019-07-31 00:07:26 -07006343 QuicConnectionId* destination_connection_id,
6344 std::string* detailed_error) {
6345 *format = GOOGLE_QUIC_PACKET;
6346 *version_present = (*first_byte & PACKET_PUBLIC_FLAGS_VERSION) != 0;
6347 uint8_t destination_connection_id_length = 0;
6348 if ((*first_byte & PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID) != 0) {
6349 destination_connection_id_length = kQuicDefaultConnectionIdLength;
6350 }
6351 if (!reader->ReadConnectionId(destination_connection_id,
6352 destination_connection_id_length)) {
6353 *detailed_error = "Unable to read ConnectionId.";
6354 return QUIC_INVALID_PACKET_HEADER;
6355 }
dschinazi243eabc2019-08-05 16:15:29 -07006356 if (*version_present) {
6357 if (!ProcessVersionLabel(reader, version_label)) {
6358 *detailed_error = "Unable to read protocol version.";
6359 return QUIC_INVALID_PACKET_HEADER;
6360 }
6361 *parsed_version = ParseQuicVersionLabel(*version_label);
dschinazi48ac9192019-07-31 00:07:26 -07006362 }
6363 return QUIC_NO_ERROR;
6364}
6365
6366namespace {
6367
6368inline bool PacketHasLengthPrefixedConnectionIds(
6369 const QuicDataReader& reader,
6370 ParsedQuicVersion parsed_version,
6371 QuicVersionLabel version_label,
6372 uint8_t first_byte) {
6373 if (parsed_version.transport_version != QUIC_VERSION_UNSUPPORTED) {
6374 return parsed_version.HasLengthPrefixedConnectionIds();
6375 }
6376
6377 // Received unsupported version, check known old unsupported versions.
6378 if (QuicVersionLabelUses4BitConnectionIdLength(version_label)) {
6379 return false;
6380 }
6381
6382 // Received unknown version, check connection ID length byte.
6383 if (reader.IsDoneReading()) {
6384 // This check is required to safely peek the connection ID length byte.
6385 return true;
6386 }
6387 const uint8_t connection_id_length_byte = reader.PeekByte();
6388
6389 // Check for packets produced by older versions of
6390 // QuicFramer::WriteClientVersionNegotiationProbePacket
6391 if (first_byte == 0xc0 && (connection_id_length_byte & 0x0f) == 0 &&
6392 connection_id_length_byte >= 0x50 && version_label == 0xcabadaba) {
6393 return false;
6394 }
6395
6396 // Check for munged packets with version tag PROX.
6397 if ((connection_id_length_byte & 0x0f) == 0 &&
6398 connection_id_length_byte >= 0x20 && version_label == 0x50524F58) {
6399 return false;
6400 }
6401
6402 return true;
6403}
6404
6405inline bool ParseLongHeaderConnectionIds(
6406 QuicDataReader* reader,
6407 bool has_length_prefix,
6408 QuicConnectionId* destination_connection_id,
6409 QuicConnectionId* source_connection_id,
6410 std::string* detailed_error) {
6411 if (has_length_prefix) {
6412 if (!reader->ReadLengthPrefixedConnectionId(destination_connection_id)) {
6413 *detailed_error = "Unable to read destination connection ID.";
6414 return false;
6415 }
6416 if (!reader->ReadLengthPrefixedConnectionId(source_connection_id)) {
6417 *detailed_error = "Unable to read source connection ID.";
6418 return false;
6419 }
6420 } else {
6421 // Parse connection ID lengths.
6422 uint8_t connection_id_lengths_byte;
6423 if (!reader->ReadUInt8(&connection_id_lengths_byte)) {
6424 *detailed_error = "Unable to read connection ID lengths.";
6425 return false;
6426 }
6427 uint8_t destination_connection_id_length =
6428 (connection_id_lengths_byte & kDestinationConnectionIdLengthMask) >> 4;
6429 if (destination_connection_id_length != 0) {
6430 destination_connection_id_length += kConnectionIdLengthAdjustment;
6431 }
6432 uint8_t source_connection_id_length =
6433 connection_id_lengths_byte & kSourceConnectionIdLengthMask;
6434 if (source_connection_id_length != 0) {
6435 source_connection_id_length += kConnectionIdLengthAdjustment;
6436 }
6437
6438 // Read destination connection ID.
6439 if (!reader->ReadConnectionId(destination_connection_id,
6440 destination_connection_id_length)) {
6441 *detailed_error = "Unable to read destination connection ID.";
6442 return false;
6443 }
6444
6445 // Read source connection ID.
6446 if (!reader->ReadConnectionId(source_connection_id,
6447 source_connection_id_length)) {
6448 *detailed_error = "Unable to read source connection ID.";
6449 return false;
6450 }
6451 }
6452 return true;
6453}
6454
6455} // namespace
6456
6457// static
6458QuicErrorCode QuicFramer::ParsePublicHeader(
6459 QuicDataReader* reader,
6460 uint8_t expected_destination_connection_id_length,
6461 bool ietf_format,
6462 uint8_t* first_byte,
6463 PacketHeaderFormat* format,
6464 bool* version_present,
6465 bool* has_length_prefix,
6466 QuicVersionLabel* version_label,
6467 ParsedQuicVersion* parsed_version,
6468 QuicConnectionId* destination_connection_id,
6469 QuicConnectionId* source_connection_id,
6470 QuicLongHeaderType* long_packet_type,
6471 QuicVariableLengthIntegerLength* retry_token_length_length,
6472 QuicStringPiece* retry_token,
6473 std::string* detailed_error) {
6474 *version_present = false;
6475 *has_length_prefix = false;
6476 *version_label = 0;
6477 *parsed_version = UnsupportedQuicVersion();
6478 *source_connection_id = EmptyQuicConnectionId();
6479 *long_packet_type = INVALID_PACKET_TYPE;
6480 *retry_token_length_length = VARIABLE_LENGTH_INTEGER_LENGTH_0;
6481 *retry_token = QuicStringPiece();
6482 *detailed_error = "";
6483
6484 if (!reader->ReadUInt8(first_byte)) {
6485 *detailed_error = "Unable to read first byte.";
6486 return QUIC_INVALID_PACKET_HEADER;
6487 }
6488
6489 if (!ietf_format) {
6490 return ParsePublicHeaderGoogleQuic(
6491 reader, first_byte, format, version_present, version_label,
dschinazi243eabc2019-08-05 16:15:29 -07006492 parsed_version, destination_connection_id, detailed_error);
dschinazi48ac9192019-07-31 00:07:26 -07006493 }
6494
6495 *format = GetIetfPacketHeaderFormat(*first_byte);
6496
6497 if (*format == IETF_QUIC_SHORT_HEADER_PACKET) {
6498 // Read destination connection ID using
6499 // expected_destination_connection_id_length to determine its length.
6500 if (!reader->ReadConnectionId(destination_connection_id,
6501 expected_destination_connection_id_length)) {
6502 *detailed_error = "Unable to read destination connection ID.";
6503 return QUIC_INVALID_PACKET_HEADER;
6504 }
6505 return QUIC_NO_ERROR;
6506 }
6507
6508 DCHECK_EQ(IETF_QUIC_LONG_HEADER_PACKET, *format);
6509 *version_present = true;
6510 if (!ProcessVersionLabel(reader, version_label)) {
6511 *detailed_error = "Unable to read protocol version.";
6512 return QUIC_INVALID_PACKET_HEADER;
6513 }
6514
6515 if (*version_label == 0) {
6516 *long_packet_type = VERSION_NEGOTIATION;
6517 }
6518
6519 // Parse version.
6520 *parsed_version = ParseQuicVersionLabel(*version_label);
6521
6522 // Figure out which IETF QUIC invariants this packet follows.
6523 *has_length_prefix = PacketHasLengthPrefixedConnectionIds(
6524 *reader, *parsed_version, *version_label, *first_byte);
6525
6526 // Parse connection IDs.
6527 if (!ParseLongHeaderConnectionIds(reader, *has_length_prefix,
6528 destination_connection_id,
6529 source_connection_id, detailed_error)) {
6530 return QUIC_INVALID_PACKET_HEADER;
6531 }
6532
6533 if (parsed_version->transport_version == QUIC_VERSION_UNSUPPORTED) {
6534 // Skip parsing of long packet type and retry token for unknown versions.
6535 return QUIC_NO_ERROR;
6536 }
6537
6538 // Parse long packet type.
fayang36825da2019-08-21 14:01:27 -07006539 if (!GetLongHeaderType(*first_byte, long_packet_type)) {
dschinazi48ac9192019-07-31 00:07:26 -07006540 *detailed_error = "Unable to parse long packet type.";
6541 return QUIC_INVALID_PACKET_HEADER;
6542 }
6543
6544 if (!parsed_version->SupportsRetry() || *long_packet_type != INITIAL) {
6545 // Retry token is only present on initial packets for some versions.
6546 return QUIC_NO_ERROR;
6547 }
6548
6549 *retry_token_length_length = reader->PeekVarInt62Length();
6550 uint64_t retry_token_length;
6551 if (!reader->ReadVarInt62(&retry_token_length)) {
6552 *retry_token_length_length = VARIABLE_LENGTH_INTEGER_LENGTH_0;
6553 *detailed_error = "Unable to read retry token length.";
6554 return QUIC_INVALID_PACKET_HEADER;
6555 }
6556
6557 if (!reader->ReadStringPiece(retry_token, retry_token_length)) {
6558 *detailed_error = "Unable to read retry token.";
6559 return QUIC_INVALID_PACKET_HEADER;
6560 }
6561
6562 return QUIC_NO_ERROR;
6563}
6564
6565// static
dschinazide0f6dc2019-05-15 16:10:11 -07006566bool QuicFramer::WriteClientVersionNegotiationProbePacket(
6567 char* packet_bytes,
6568 QuicByteCount packet_length,
6569 const char* destination_connection_id_bytes,
6570 uint8_t destination_connection_id_length) {
6571 if (packet_bytes == nullptr) {
6572 QUIC_BUG << "Invalid packet_bytes";
6573 return false;
6574 }
6575 if (packet_length < kMinPacketSizeForVersionNegotiation ||
6576 packet_length > 65535) {
6577 QUIC_BUG << "Invalid packet_length";
6578 return false;
6579 }
dschinazib012d212019-08-01 18:07:26 -07006580 if (destination_connection_id_length > kQuicMaxConnectionId4BitLength ||
dschinazi19dc2b52019-07-17 19:54:43 -07006581 destination_connection_id_length <
6582 kQuicMinimumInitialConnectionIdLength) {
dschinazide0f6dc2019-05-15 16:10:11 -07006583 QUIC_BUG << "Invalid connection_id_length";
6584 return false;
6585 }
dschinazi48ac9192019-07-31 00:07:26 -07006586 const bool use_length_prefix =
6587 GetQuicFlag(FLAGS_quic_prober_uses_length_prefixed_connection_ids);
6588 const uint8_t last_version_byte = use_length_prefix ? 0xda : 0xba;
dschinazide0f6dc2019-05-15 16:10:11 -07006589 // clang-format off
dschinazi48ac9192019-07-31 00:07:26 -07006590 const unsigned char packet_start_bytes[] = {
dschinazide0f6dc2019-05-15 16:10:11 -07006591 // IETF long header with fixed bit set, type initial, all-0 encrypted bits.
6592 0xc0,
6593 // Version, part of the IETF space reserved for negotiation.
6594 // This intentionally differs from QuicVersionReservedForNegotiation()
6595 // to allow differentiating them over the wire.
dschinazi48ac9192019-07-31 00:07:26 -07006596 0xca, 0xba, 0xda, last_version_byte,
dschinazide0f6dc2019-05-15 16:10:11 -07006597 };
6598 // clang-format on
6599 static_assert(sizeof(packet_start_bytes) == 5, "bad packet_start_bytes size");
6600 QuicDataWriter writer(packet_length, packet_bytes);
6601 if (!writer.WriteBytes(packet_start_bytes, sizeof(packet_start_bytes))) {
6602 QUIC_BUG << "Failed to write packet start";
6603 return false;
6604 }
6605
6606 QuicConnectionId destination_connection_id(destination_connection_id_bytes,
6607 destination_connection_id_length);
dschinazi48ac9192019-07-31 00:07:26 -07006608 if (!AppendIetfConnectionIds(
6609 /*version_flag=*/true, use_length_prefix, destination_connection_id,
6610 EmptyQuicConnectionId(), &writer)) {
dschinazide0f6dc2019-05-15 16:10:11 -07006611 QUIC_BUG << "Failed to write connection IDs";
6612 return false;
6613 }
6614 // Add 8 bytes of zeroes followed by 8 bytes of ones to ensure that this does
6615 // not parse with any known version. The zeroes make sure that packet numbers,
6616 // retry token lengths and payload lengths are parsed as zero, and if the
6617 // zeroes are treated as padding frames, 0xff is known to not parse as a
6618 // valid frame type.
6619 if (!writer.WriteUInt64(0) ||
6620 !writer.WriteUInt64(std::numeric_limits<uint64_t>::max())) {
6621 QUIC_BUG << "Failed to write 18 bytes";
6622 return false;
6623 }
6624 // Make sure the polite greeting below is padded to a 16-byte boundary to
6625 // make it easier to read in tcpdump.
6626 while (writer.length() % 16 != 0) {
6627 if (!writer.WriteUInt8(0)) {
6628 QUIC_BUG << "Failed to write padding byte";
6629 return false;
6630 }
6631 }
6632 // Add a polite greeting in case a human sees this in tcpdump.
6633 static const char polite_greeting[] =
6634 "This packet only exists to trigger IETF QUIC version negotiation. "
6635 "Please respond with a Version Negotiation packet indicating what "
6636 "versions you support. Thank you and have a nice day.";
6637 if (!writer.WriteBytes(polite_greeting, sizeof(polite_greeting))) {
6638 QUIC_BUG << "Failed to write polite greeting";
6639 return false;
6640 }
6641 // Fill the rest of the packet with zeroes.
6642 writer.WritePadding();
6643 DCHECK_EQ(0u, writer.remaining());
6644 return true;
6645}
6646
6647// static
6648bool QuicFramer::ParseServerVersionNegotiationProbeResponse(
6649 const char* packet_bytes,
6650 QuicByteCount packet_length,
6651 char* source_connection_id_bytes,
6652 uint8_t* source_connection_id_length_out,
6653 std::string* detailed_error) {
6654 if (detailed_error == nullptr) {
6655 QUIC_BUG << "Invalid error_details";
6656 return false;
6657 }
6658 *detailed_error = "";
6659 if (packet_bytes == nullptr) {
6660 *detailed_error = "Invalid packet_bytes";
6661 return false;
6662 }
6663 if (packet_length < 6) {
6664 *detailed_error = "Invalid packet_length";
6665 return false;
6666 }
6667 if (source_connection_id_bytes == nullptr) {
6668 *detailed_error = "Invalid source_connection_id_bytes";
6669 return false;
6670 }
6671 if (source_connection_id_length_out == nullptr) {
6672 *detailed_error = "Invalid source_connection_id_length_out";
6673 return false;
6674 }
6675 QuicDataReader reader(packet_bytes, packet_length);
6676 uint8_t type_byte = 0;
6677 if (!reader.ReadUInt8(&type_byte)) {
6678 *detailed_error = "Failed to read type byte";
6679 return false;
6680 }
6681 if ((type_byte & 0x80) == 0) {
6682 *detailed_error = "Packet does not have long header";
6683 return false;
6684 }
6685 uint32_t version = 0;
6686 if (!reader.ReadUInt32(&version)) {
6687 *detailed_error = "Failed to read version";
6688 return false;
6689 }
6690 if (version != 0) {
6691 *detailed_error = "Packet is not a version negotiation packet";
6692 return false;
6693 }
dschinazi48ac9192019-07-31 00:07:26 -07006694 const bool use_length_prefix =
6695 GetQuicFlag(FLAGS_quic_prober_uses_length_prefixed_connection_ids);
dschinazide0f6dc2019-05-15 16:10:11 -07006696 QuicConnectionId destination_connection_id, source_connection_id;
dschinazi48ac9192019-07-31 00:07:26 -07006697 if (use_length_prefix) {
6698 if (!reader.ReadLengthPrefixedConnectionId(&destination_connection_id)) {
6699 *detailed_error = "Failed to read destination connection ID";
6700 return false;
6701 }
6702 if (!reader.ReadLengthPrefixedConnectionId(&source_connection_id)) {
6703 *detailed_error = "Failed to read source connection ID";
6704 return false;
6705 }
6706 } else {
6707 uint8_t expected_server_connection_id_length = 0,
6708 destination_connection_id_length = 0,
6709 source_connection_id_length = 0;
6710 if (!ProcessAndValidateIetfConnectionIdLength(
6711 &reader, UnsupportedQuicVersion(), Perspective::IS_CLIENT,
6712 /*should_update_expected_server_connection_id_length=*/true,
6713 &expected_server_connection_id_length,
6714 &destination_connection_id_length, &source_connection_id_length,
6715 detailed_error)) {
6716 return false;
6717 }
6718 if (!reader.ReadConnectionId(&destination_connection_id,
6719 destination_connection_id_length)) {
6720 *detailed_error = "Failed to read destination connection ID";
6721 return false;
6722 }
6723 if (!reader.ReadConnectionId(&source_connection_id,
6724 source_connection_id_length)) {
6725 *detailed_error = "Failed to read source connection ID";
6726 return false;
6727 }
dschinazide0f6dc2019-05-15 16:10:11 -07006728 }
dschinazi48ac9192019-07-31 00:07:26 -07006729
6730 if (destination_connection_id.length() != 0) {
6731 *detailed_error = "Received unexpected destination connection ID length";
dschinazide0f6dc2019-05-15 16:10:11 -07006732 return false;
6733 }
6734
dschinaziccbe0e02019-08-13 12:15:00 -07006735 if (!use_length_prefix && source_connection_id.length() == 0) {
6736 // We received a bad response due to b/139330014.
6737 // Reparse the packet assuming length prefixes.
6738 // This is a temporary client-side workaround until cl/263172621 is
6739 // deployed on production servers.
6740 // TODO(dschinazi): remove this client-side workaround once the server-side
6741 // fix is deployed.
6742 QuicDataReader reader2(packet_bytes, packet_length);
6743 uint8_t type_byte2 = 0;
6744 uint32_t version2 = 0;
6745 QuicConnectionId destination_connection_id2, source_connection_id2;
6746 if (reader2.ReadUInt8(&type_byte2) && reader2.ReadUInt32(&version2) &&
6747 reader2.ReadLengthPrefixedConnectionId(&destination_connection_id2) &&
6748 reader2.ReadLengthPrefixedConnectionId(&source_connection_id2) &&
6749 (type_byte2 & 0x80) != 0 && version2 == 0 &&
6750 destination_connection_id2.length() == 0 &&
6751 source_connection_id2.length() != 0) {
6752 source_connection_id = source_connection_id2;
6753 }
6754 }
6755
dschinazide0f6dc2019-05-15 16:10:11 -07006756 memcpy(source_connection_id_bytes, source_connection_id.data(),
dschinazi48ac9192019-07-31 00:07:26 -07006757 source_connection_id.length());
6758 *source_connection_id_length_out = source_connection_id.length();
dschinazide0f6dc2019-05-15 16:10:11 -07006759
6760 return true;
6761}
6762
fkastenholzb4dade72019-08-05 06:54:20 -07006763// Look for and parse the error code from the "<quic_error_code>:" text that
6764// may be present at the start of the CONNECTION_CLOSE error details string.
6765// This text, inserted by the peer if it's using Google's QUIC implementation,
6766// contains additional error information that narrows down the exact error. If
6767// the string is not found, or is not properly formed, it returns
6768// ErrorCode::QUIC_IETF_GQUIC_ERROR_MISSING
fkastenholz488a4622019-08-26 06:24:46 -07006769void MaybeExtractQuicErrorCode(QuicConnectionCloseFrame* frame) {
6770 std::vector<QuicStringPiece> ed =
6771 QuicTextUtils::Split(frame->error_details, ':');
fkastenholzb4dade72019-08-05 06:54:20 -07006772 uint64_t extracted_error_code;
6773 if (ed.size() < 2 || !QuicTextUtils::IsAllDigits(ed[0]) ||
6774 !QuicTextUtils::StringToUint64(ed[0], &extracted_error_code)) {
fkastenholz488a4622019-08-26 06:24:46 -07006775 frame->extracted_error_code = QUIC_IETF_GQUIC_ERROR_MISSING;
6776 return;
fkastenholzb4dade72019-08-05 06:54:20 -07006777 }
fkastenholz488a4622019-08-26 06:24:46 -07006778 // Return the error code (numeric) and the error details string without the
6779 // error code prefix. Note that Split returns everything up to, but not
6780 // including, the split character, so the length of ed[0] is just the number
6781 // of digits in the error number. In removing the prefix, 1 is added to the
6782 // length to account for the :
6783 QuicStringPiece x = QuicStringPiece(frame->error_details);
6784 x.remove_prefix(ed[0].length() + 1);
6785 frame->error_details = std::string(x);
6786 frame->extracted_error_code =
6787 static_cast<QuicErrorCode>(extracted_error_code);
fkastenholzb4dade72019-08-05 06:54:20 -07006788}
6789
QUICHE teama6ef0a62019-03-07 20:34:33 -05006790#undef ENDPOINT // undef for jumbo builds
6791} // namespace quic