blob: 13669d98e17f14be97f1926c8f5e49cf8738a206 [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(
fayangf36e29d2019-06-06 14:03:40 -0700194 QuicTransportVersion version,
QUICHE teama6ef0a62019-03-07 20:34:33 -0500195 QuicPacketNumberLength packet_number_length) {
fayangf36e29d2019-06-06 14:03:40 -0700196 if (version > QUIC_VERSION_44) {
197 return packet_number_length - 1;
198 }
199 switch (packet_number_length) {
200 case PACKET_1BYTE_PACKET_NUMBER:
201 return 0;
202 case PACKET_2BYTE_PACKET_NUMBER:
203 return 1;
204 case PACKET_4BYTE_PACKET_NUMBER:
205 return 2;
206 default:
207 QUIC_BUG << "Invalid packet number length.";
208 return 0;
209 }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500210}
211
212bool GetShortHeaderPacketNumberLength(
213 QuicTransportVersion version,
214 uint8_t type,
215 bool infer_packet_header_type_from_version,
216 QuicPacketNumberLength* packet_number_length) {
217 DCHECK(!(type & FLAGS_LONG_HEADER));
218 const bool two_bits_packet_number_length =
fayangf36e29d2019-06-06 14:03:40 -0700219 infer_packet_header_type_from_version ? version > QUIC_VERSION_44
QUICHE teama6ef0a62019-03-07 20:34:33 -0500220 : (type & FLAGS_FIXED_BIT);
221 if (two_bits_packet_number_length) {
222 *packet_number_length =
223 static_cast<QuicPacketNumberLength>((type & 0x03) + 1);
224 return true;
225 }
226 switch (type & 0x07) {
227 case 0:
228 *packet_number_length = PACKET_1BYTE_PACKET_NUMBER;
229 break;
230 case 1:
231 *packet_number_length = PACKET_2BYTE_PACKET_NUMBER;
232 break;
233 case 2:
234 *packet_number_length = PACKET_4BYTE_PACKET_NUMBER;
235 break;
236 default:
237 *packet_number_length = PACKET_6BYTE_PACKET_NUMBER;
238 return false;
239 }
240 return true;
241}
242
fayangf36e29d2019-06-06 14:03:40 -0700243uint8_t LongHeaderTypeToOnWireValue(QuicTransportVersion version,
244 QuicLongHeaderType type) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500245 switch (type) {
246 case INITIAL:
fayangf36e29d2019-06-06 14:03:40 -0700247 return version > QUIC_VERSION_44 ? 0 : 0x7F;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500248 case ZERO_RTT_PROTECTED:
fayangf36e29d2019-06-06 14:03:40 -0700249 return version > QUIC_VERSION_44 ? 1 << 4 : 0x7C;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500250 case HANDSHAKE:
fayangf36e29d2019-06-06 14:03:40 -0700251 return version > QUIC_VERSION_44 ? 2 << 4 : 0x7D;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500252 case RETRY:
fayangf36e29d2019-06-06 14:03:40 -0700253 return version > QUIC_VERSION_44 ? 3 << 4 : 0x7E;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500254 case VERSION_NEGOTIATION:
255 return 0xF0; // Value does not matter
256 default:
257 QUIC_BUG << "Invalid long header type: " << type;
258 return 0xFF;
259 }
260}
261
262bool GetLongHeaderType(QuicTransportVersion version,
263 uint8_t type,
264 QuicLongHeaderType* long_header_type) {
265 DCHECK((type & FLAGS_LONG_HEADER) && version != QUIC_VERSION_UNSUPPORTED);
fayangf36e29d2019-06-06 14:03:40 -0700266 if (version > QUIC_VERSION_44) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500267 switch ((type & 0x30) >> 4) {
268 case 0:
269 *long_header_type = INITIAL;
270 break;
271 case 1:
272 *long_header_type = ZERO_RTT_PROTECTED;
273 break;
274 case 2:
275 *long_header_type = HANDSHAKE;
276 break;
277 case 3:
278 *long_header_type = RETRY;
279 break;
280 default:
281 QUIC_BUG << "Unreachable statement";
dschinazi072da7c2019-05-07 17:57:42 -0700282 *long_header_type = INVALID_PACKET_TYPE;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500283 return false;
284 }
285 return true;
286 }
287
288 switch (type & 0x7F) {
289 case 0x7F:
290 *long_header_type = INITIAL;
291 break;
292 case 0x7C:
293 *long_header_type = ZERO_RTT_PROTECTED;
294 break;
295 case 0x7D:
296 *long_header_type = HANDSHAKE;
297 break;
298 case 0x7E:
299 *long_header_type = RETRY;
300 break;
301 default:
302 // Invalid packet header type. Whether a packet is version negotiation is
303 // determined by the version field.
304 *long_header_type = INVALID_PACKET_TYPE;
305 return false;
306 }
307 return true;
308}
309
310QuicPacketNumberLength GetLongHeaderPacketNumberLength(
311 QuicTransportVersion version,
312 uint8_t type) {
fayangf36e29d2019-06-06 14:03:40 -0700313 if (version > QUIC_VERSION_44) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500314 return static_cast<QuicPacketNumberLength>((type & 0x03) + 1);
315 }
316 return PACKET_4BYTE_PACKET_NUMBER;
317}
318
QUICHE team10b22a12019-03-21 15:31:42 -0700319// Used to get packet number space before packet gets decrypted.
320PacketNumberSpace GetPacketNumberSpace(const QuicPacketHeader& header) {
321 switch (header.form) {
322 case GOOGLE_QUIC_PACKET:
323 QUIC_BUG << "Try to get packet number space of Google QUIC packet";
324 break;
325 case IETF_QUIC_SHORT_HEADER_PACKET:
326 return APPLICATION_DATA;
327 case IETF_QUIC_LONG_HEADER_PACKET:
328 switch (header.long_packet_type) {
329 case INITIAL:
330 return INITIAL_DATA;
331 case HANDSHAKE:
332 return HANDSHAKE_DATA;
333 case ZERO_RTT_PROTECTED:
334 return APPLICATION_DATA;
335 case VERSION_NEGOTIATION:
336 case RETRY:
337 case INVALID_PACKET_TYPE:
338 QUIC_BUG << "Try to get packet number space of long header type: "
339 << QuicUtils::QuicLongHeaderTypetoString(
340 header.long_packet_type);
341 break;
342 }
343 }
344
345 return NUM_PACKET_NUMBER_SPACES;
346}
347
zhongyi546cc452019-04-12 15:27:49 -0700348EncryptionLevel GetEncryptionLevel(const QuicPacketHeader& header) {
349 switch (header.form) {
350 case GOOGLE_QUIC_PACKET:
351 QUIC_BUG << "Cannot determine EncryptionLevel from Google QUIC header";
352 break;
353 case IETF_QUIC_SHORT_HEADER_PACKET:
354 return ENCRYPTION_FORWARD_SECURE;
355 case IETF_QUIC_LONG_HEADER_PACKET:
356 switch (header.long_packet_type) {
357 case INITIAL:
358 return ENCRYPTION_INITIAL;
359 case HANDSHAKE:
360 return ENCRYPTION_HANDSHAKE;
361 case ZERO_RTT_PROTECTED:
362 return ENCRYPTION_ZERO_RTT;
363 case VERSION_NEGOTIATION:
364 case RETRY:
365 case INVALID_PACKET_TYPE:
366 QUIC_BUG << "No encryption used with type "
367 << QuicUtils::QuicLongHeaderTypetoString(
368 header.long_packet_type);
369 }
370 }
371 return NUM_ENCRYPTION_LEVELS;
372}
373
QUICHE teama6ef0a62019-03-07 20:34:33 -0500374QuicStringPiece TruncateErrorString(QuicStringPiece error) {
375 if (error.length() <= kMaxErrorStringLength) {
376 return error;
377 }
378 return QuicStringPiece(error.data(), kMaxErrorStringLength);
379}
380
381size_t TruncatedErrorStringSize(const QuicStringPiece& error) {
382 if (error.length() < kMaxErrorStringLength) {
383 return error.length();
384 }
385 return kMaxErrorStringLength;
386}
387
388uint8_t GetConnectionIdLengthValue(QuicConnectionIdLength length) {
389 if (length == 0) {
390 return 0;
391 }
392 return static_cast<uint8_t>(length - kConnectionIdLengthAdjustment);
393}
394
395bool IsValidPacketNumberLength(QuicPacketNumberLength packet_number_length) {
396 size_t length = packet_number_length;
397 return length == 1 || length == 2 || length == 4 || length == 6 ||
398 length == 8;
399}
400
401bool IsValidFullPacketNumber(uint64_t full_packet_number,
402 QuicTransportVersion version) {
QUICHE team577718a2019-03-20 09:00:59 -0700403 return full_packet_number > 0 || version == QUIC_VERSION_99;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500404}
405
dschinazi1f485a12019-05-13 11:57:01 -0700406bool AppendIetfConnectionIds(bool version_flag,
dschinazi48ac9192019-07-31 00:07:26 -0700407 bool use_length_prefix,
dschinazi1f485a12019-05-13 11:57:01 -0700408 QuicConnectionId destination_connection_id,
409 QuicConnectionId source_connection_id,
410 QuicDataWriter* writer) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500411 if (!version_flag) {
412 return writer->WriteConnectionId(destination_connection_id);
413 }
414
dschinazi48ac9192019-07-31 00:07:26 -0700415 if (use_length_prefix) {
416 return writer->WriteLengthPrefixedConnectionId(destination_connection_id) &&
417 writer->WriteLengthPrefixedConnectionId(source_connection_id);
418 }
419
QUICHE teama6ef0a62019-03-07 20:34:33 -0500420 // Compute connection ID length byte.
421 uint8_t dcil = GetConnectionIdLengthValue(
422 static_cast<QuicConnectionIdLength>(destination_connection_id.length()));
423 uint8_t scil = GetConnectionIdLengthValue(
424 static_cast<QuicConnectionIdLength>(source_connection_id.length()));
425 uint8_t connection_id_length = dcil << 4 | scil;
426
427 return writer->WriteUInt8(connection_id_length) &&
428 writer->WriteConnectionId(destination_connection_id) &&
429 writer->WriteConnectionId(source_connection_id);
430}
431
432enum class DroppedPacketReason {
433 // General errors
434 INVALID_PUBLIC_HEADER,
435 VERSION_MISMATCH,
436 // Version negotiation packet errors
437 INVALID_VERSION_NEGOTIATION_PACKET,
438 // Public reset packet errors, pre-v44
439 INVALID_PUBLIC_RESET_PACKET,
440 // Data packet errors
441 INVALID_PACKET_NUMBER,
442 INVALID_DIVERSIFICATION_NONCE,
443 DECRYPTION_FAILURE,
444 NUM_REASONS,
445};
446
447void RecordDroppedPacketReason(DroppedPacketReason reason) {
448 QUIC_CLIENT_HISTOGRAM_ENUM("QuicDroppedPacketReason", reason,
449 DroppedPacketReason::NUM_REASONS,
450 "The reason a packet was not processed. Recorded "
451 "each time such a packet is dropped");
452}
453
fayangccbab732019-05-13 10:11:25 -0700454PacketHeaderFormat GetIetfPacketHeaderFormat(uint8_t type_byte) {
455 return type_byte & FLAGS_LONG_HEADER ? IETF_QUIC_LONG_HEADER_PACKET
456 : IETF_QUIC_SHORT_HEADER_PACKET;
457}
458
fkastenholzb4dade72019-08-05 06:54:20 -0700459std::string GenerateErrorString(std::string initial_error_string,
460 QuicErrorCode quic_error_code) {
461 if (quic_error_code == QUIC_IETF_GQUIC_ERROR_MISSING) {
462 // QUIC_IETF_GQUIC_ERROR_MISSING is special -- it means not to encode
463 // the error value in the string.
464 return initial_error_string;
465 }
466 return QuicStrCat(std::to_string(static_cast<unsigned>(quic_error_code)), ":",
467 initial_error_string);
468}
469
QUICHE teama6ef0a62019-03-07 20:34:33 -0500470} // namespace
471
472QuicFramer::QuicFramer(const ParsedQuicVersionVector& supported_versions,
473 QuicTime creation_time,
474 Perspective perspective,
dschinazi8ff74822019-05-28 16:37:20 -0700475 uint8_t expected_server_connection_id_length)
QUICHE teama6ef0a62019-03-07 20:34:33 -0500476 : visitor_(nullptr),
477 error_(QUIC_NO_ERROR),
dschinazi7b9278c2019-05-20 07:36:21 -0700478 last_serialized_server_connection_id_(EmptyQuicConnectionId()),
dschinazi346b7ce2019-06-05 01:38:18 -0700479 last_serialized_client_connection_id_(EmptyQuicConnectionId()),
QUICHE teama6ef0a62019-03-07 20:34:33 -0500480 version_(PROTOCOL_UNSUPPORTED, QUIC_VERSION_UNSUPPORTED),
481 supported_versions_(supported_versions),
QUICHE team6987b4a2019-03-15 16:23:04 -0700482 decrypter_level_(ENCRYPTION_INITIAL),
QUICHE team76086e42019-03-25 15:12:29 -0700483 alternative_decrypter_level_(NUM_ENCRYPTION_LEVELS),
QUICHE teama6ef0a62019-03-07 20:34:33 -0500484 alternative_decrypter_latch_(false),
485 perspective_(perspective),
486 validate_flags_(true),
487 process_timestamps_(false),
488 creation_time_(creation_time),
489 last_timestamp_(QuicTime::Delta::Zero()),
490 first_sending_packet_number_(FirstSendingPacketNumber()),
491 data_producer_(nullptr),
492 infer_packet_header_type_from_version_(perspective ==
493 Perspective::IS_CLIENT),
dschinazi8ff74822019-05-28 16:37:20 -0700494 expected_server_connection_id_length_(
495 expected_server_connection_id_length),
dschinazi346b7ce2019-06-05 01:38:18 -0700496 expected_client_connection_id_length_(0),
nharper55fa6132019-05-07 19:37:21 -0700497 supports_multiple_packet_number_spaces_(false),
fkastenholz4dc4ba32019-07-30 09:55:25 -0700498 last_written_packet_number_length_(0),
499 peer_ack_delay_exponent_(kDefaultAckDelayExponent),
500 local_ack_delay_exponent_(kDefaultAckDelayExponent) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500501 DCHECK(!supported_versions.empty());
502 version_ = supported_versions_[0];
QUICHE team76086e42019-03-25 15:12:29 -0700503 decrypter_[ENCRYPTION_INITIAL] = QuicMakeUnique<NullDecrypter>(perspective);
QUICHE team6987b4a2019-03-15 16:23:04 -0700504 encrypter_[ENCRYPTION_INITIAL] = QuicMakeUnique<NullEncrypter>(perspective);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500505}
506
507QuicFramer::~QuicFramer() {}
508
509// static
510size_t QuicFramer::GetMinStreamFrameSize(QuicTransportVersion version,
511 QuicStreamId stream_id,
512 QuicStreamOffset offset,
513 bool last_frame_in_packet,
514 QuicPacketLength data_length) {
fkastenholz305e1732019-06-18 05:01:22 -0700515 if (VersionHasIetfQuicFrames(version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500516 return kQuicFrameTypeSize + QuicDataWriter::GetVarInt62Len(stream_id) +
517 (last_frame_in_packet
518 ? 0
519 : QuicDataWriter::GetVarInt62Len(data_length)) +
520 (offset != 0 ? QuicDataWriter::GetVarInt62Len(offset) : 0);
521 }
522 return kQuicFrameTypeSize + GetStreamIdSize(stream_id) +
523 GetStreamOffsetSize(version, offset) +
524 (last_frame_in_packet ? 0 : kQuicStreamPayloadLengthSize);
525}
526
527// static
528size_t QuicFramer::GetMinCryptoFrameSize(QuicStreamOffset offset,
529 QuicPacketLength data_length) {
530 return kQuicFrameTypeSize + QuicDataWriter::GetVarInt62Len(offset) +
531 QuicDataWriter::GetVarInt62Len(data_length);
532}
533
534// static
535size_t QuicFramer::GetMessageFrameSize(QuicTransportVersion version,
536 bool last_frame_in_packet,
537 QuicByteCount length) {
fayangd4291e42019-05-30 10:31:21 -0700538 QUIC_BUG_IF(!VersionSupportsMessageFrames(version))
QUICHE teama6ef0a62019-03-07 20:34:33 -0500539 << "Try to serialize MESSAGE frame in " << version;
540 return kQuicFrameTypeSize +
541 (last_frame_in_packet ? 0 : QuicDataWriter::GetVarInt62Len(length)) +
542 length;
543}
544
545// static
546size_t QuicFramer::GetMinAckFrameSize(
547 QuicTransportVersion version,
548 QuicPacketNumberLength largest_observed_length) {
fkastenholz305e1732019-06-18 05:01:22 -0700549 if (VersionHasIetfQuicFrames(version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500550 // The minimal ack frame consists of the following four fields: Largest
551 // Acknowledged, ACK Delay, ACK Block Count, and First ACK Block. Minimum
552 // size of each is 1 byte.
553 return kQuicFrameTypeSize + 4;
554 }
555 size_t min_size = kQuicFrameTypeSize + largest_observed_length +
556 kQuicDeltaTimeLargestObservedSize;
557 return min_size + kQuicNumTimestampsSize;
558}
559
560// static
561size_t QuicFramer::GetStopWaitingFrameSize(
dschinazi17d42422019-06-18 16:35:07 -0700562 QuicTransportVersion /*version*/,
QUICHE teama6ef0a62019-03-07 20:34:33 -0500563 QuicPacketNumberLength packet_number_length) {
564 size_t min_size = kQuicFrameTypeSize + packet_number_length;
565 return min_size;
566}
567
568// static
569size_t QuicFramer::GetRstStreamFrameSize(QuicTransportVersion version,
570 const QuicRstStreamFrame& frame) {
fkastenholz305e1732019-06-18 05:01:22 -0700571 if (VersionHasIetfQuicFrames(version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500572 return QuicDataWriter::GetVarInt62Len(frame.stream_id) +
573 QuicDataWriter::GetVarInt62Len(frame.byte_offset) +
fkastenholz07300e52019-07-16 11:51:37 -0700574 kQuicFrameTypeSize +
575 QuicDataWriter::GetVarInt62Len(frame.ietf_error_code);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500576 }
577 return kQuicFrameTypeSize + kQuicMaxStreamIdSize + kQuicMaxStreamOffsetSize +
578 kQuicErrorCodeSize;
579}
580
581// static
fkastenholza037b8b2019-05-07 06:00:05 -0700582size_t QuicFramer::GetConnectionCloseFrameSize(
QUICHE teama6ef0a62019-03-07 20:34:33 -0500583 QuicTransportVersion version,
584 const QuicConnectionCloseFrame& frame) {
fkastenholz305e1732019-06-18 05:01:22 -0700585 if (!VersionHasIetfQuicFrames(version)) {
586 // Not IETF QUIC, return Google QUIC CONNECTION CLOSE frame size.
fkastenholza037b8b2019-05-07 06:00:05 -0700587 return kQuicFrameTypeSize + kQuicErrorCodeSize +
588 kQuicErrorDetailsLengthSize +
589 TruncatedErrorStringSize(frame.error_details);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500590 }
fkastenholzb4dade72019-08-05 06:54:20 -0700591
592 // Prepend the extra error information to the string and get the result's
593 // length.
594 const size_t truncated_error_string_size = TruncatedErrorStringSize(
595 GenerateErrorString(frame.error_details, frame.extracted_error_code));
596
fkastenholzd57d3f92019-07-16 09:05:17 -0700597 uint64_t close_code = 0;
598 if (frame.close_type == IETF_QUIC_TRANSPORT_CONNECTION_CLOSE) {
599 close_code = static_cast<uint64_t>(frame.transport_error_code);
600 } else if (frame.close_type == IETF_QUIC_APPLICATION_CONNECTION_CLOSE) {
601 close_code = static_cast<uint64_t>(frame.application_error_code);
602 }
fkastenholzb4dade72019-08-05 06:54:20 -0700603
fkastenholza037b8b2019-05-07 06:00:05 -0700604 const size_t frame_size =
605 truncated_error_string_size +
606 QuicDataWriter::GetVarInt62Len(truncated_error_string_size) +
fkastenholzd57d3f92019-07-16 09:05:17 -0700607 kQuicFrameTypeSize + QuicDataWriter::GetVarInt62Len(close_code);
fkastenholza037b8b2019-05-07 06:00:05 -0700608 if (frame.close_type == IETF_QUIC_APPLICATION_CONNECTION_CLOSE) {
609 return frame_size;
610 }
fkastenholzb4dade72019-08-05 06:54:20 -0700611 // The Transport close frame has the transport_close_frame_type, so include
612 // its length.
fkastenholza037b8b2019-05-07 06:00:05 -0700613 return frame_size +
614 QuicDataWriter::GetVarInt62Len(frame.transport_close_frame_type);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500615}
616
617// static
QUICHE teama6ef0a62019-03-07 20:34:33 -0500618size_t QuicFramer::GetMinGoAwayFrameSize() {
619 return kQuicFrameTypeSize + kQuicErrorCodeSize + kQuicErrorDetailsLengthSize +
620 kQuicMaxStreamIdSize;
621}
622
623// static
624size_t QuicFramer::GetWindowUpdateFrameSize(
625 QuicTransportVersion version,
626 const QuicWindowUpdateFrame& frame) {
fkastenholz305e1732019-06-18 05:01:22 -0700627 if (!VersionHasIetfQuicFrames(version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500628 return kQuicFrameTypeSize + kQuicMaxStreamIdSize + kQuicMaxStreamOffsetSize;
629 }
630 if (frame.stream_id == QuicUtils::GetInvalidStreamId(version)) {
631 // Frame would be a MAX DATA frame, which has only a Maximum Data field.
632 return kQuicFrameTypeSize +
633 QuicDataWriter::GetVarInt62Len(frame.byte_offset);
634 }
635 // Frame would be MAX STREAM DATA, has Maximum Stream Data and Stream ID
636 // fields.
637 return kQuicFrameTypeSize +
638 QuicDataWriter::GetVarInt62Len(frame.byte_offset) +
639 QuicDataWriter::GetVarInt62Len(frame.stream_id);
640}
641
642// static
643size_t QuicFramer::GetMaxStreamsFrameSize(QuicTransportVersion version,
fkastenholz3c4eabf2019-04-22 07:49:59 -0700644 const QuicMaxStreamsFrame& frame) {
fkastenholz305e1732019-06-18 05:01:22 -0700645 if (!VersionHasIetfQuicFrames(version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500646 QUIC_BUG << "In version " << version
fkastenholz305e1732019-06-18 05:01:22 -0700647 << ", which does not support IETF Frames, and tried to serialize "
648 "MaxStreams Frame.";
QUICHE teama6ef0a62019-03-07 20:34:33 -0500649 }
fkastenholz3c4eabf2019-04-22 07:49:59 -0700650 return kQuicFrameTypeSize +
651 QuicDataWriter::GetVarInt62Len(frame.stream_count);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500652}
653
654// static
655size_t QuicFramer::GetStreamsBlockedFrameSize(
656 QuicTransportVersion version,
fkastenholz3c4eabf2019-04-22 07:49:59 -0700657 const QuicStreamsBlockedFrame& frame) {
fkastenholz305e1732019-06-18 05:01:22 -0700658 if (!VersionHasIetfQuicFrames(version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500659 QUIC_BUG << "In version " << version
fkastenholz305e1732019-06-18 05:01:22 -0700660 << ", which does not support IETF frames, and tried to serialize "
661 "StreamsBlocked Frame.";
QUICHE teama6ef0a62019-03-07 20:34:33 -0500662 }
663
fkastenholz3c4eabf2019-04-22 07:49:59 -0700664 return kQuicFrameTypeSize +
665 QuicDataWriter::GetVarInt62Len(frame.stream_count);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500666}
667
668// static
669size_t QuicFramer::GetBlockedFrameSize(QuicTransportVersion version,
670 const QuicBlockedFrame& frame) {
fkastenholz305e1732019-06-18 05:01:22 -0700671 if (!VersionHasIetfQuicFrames(version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500672 return kQuicFrameTypeSize + kQuicMaxStreamIdSize;
673 }
674 if (frame.stream_id == QuicUtils::GetInvalidStreamId(version)) {
675 // return size of IETF QUIC Blocked frame
676 return kQuicFrameTypeSize + QuicDataWriter::GetVarInt62Len(frame.offset);
677 }
678 // return size of IETF QUIC Stream Blocked frame.
679 return kQuicFrameTypeSize + QuicDataWriter::GetVarInt62Len(frame.offset) +
680 QuicDataWriter::GetVarInt62Len(frame.stream_id);
681}
682
683// static
684size_t QuicFramer::GetStopSendingFrameSize(const QuicStopSendingFrame& frame) {
685 return kQuicFrameTypeSize + QuicDataWriter::GetVarInt62Len(frame.stream_id) +
fkastenholz733552e2019-07-16 11:16:58 -0700686 QuicDataWriter::GetVarInt62Len(frame.application_error_code);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500687}
688
689// static
690size_t QuicFramer::GetPathChallengeFrameSize(
691 const QuicPathChallengeFrame& frame) {
692 return kQuicFrameTypeSize + sizeof(frame.data_buffer);
693}
694
695// static
696size_t QuicFramer::GetPathResponseFrameSize(
697 const QuicPathResponseFrame& frame) {
698 return kQuicFrameTypeSize + sizeof(frame.data_buffer);
699}
700
701// static
702size_t QuicFramer::GetRetransmittableControlFrameSize(
703 QuicTransportVersion version,
704 const QuicFrame& frame) {
705 switch (frame.type) {
706 case PING_FRAME:
707 // Ping has no payload.
708 return kQuicFrameTypeSize;
709 case RST_STREAM_FRAME:
710 return GetRstStreamFrameSize(version, *frame.rst_stream_frame);
711 case CONNECTION_CLOSE_FRAME:
fkastenholza037b8b2019-05-07 06:00:05 -0700712 return GetConnectionCloseFrameSize(version,
713 *frame.connection_close_frame);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500714 case GOAWAY_FRAME:
715 return GetMinGoAwayFrameSize() +
716 TruncatedErrorStringSize(frame.goaway_frame->reason_phrase);
717 case WINDOW_UPDATE_FRAME:
fkastenholz305e1732019-06-18 05:01:22 -0700718 // For IETF QUIC, this could be either a MAX DATA or MAX STREAM DATA.
QUICHE teama6ef0a62019-03-07 20:34:33 -0500719 // GetWindowUpdateFrameSize figures this out and returns the correct
720 // length.
721 return GetWindowUpdateFrameSize(version, *frame.window_update_frame);
722 case BLOCKED_FRAME:
723 return GetBlockedFrameSize(version, *frame.blocked_frame);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500724 case NEW_CONNECTION_ID_FRAME:
725 return GetNewConnectionIdFrameSize(*frame.new_connection_id_frame);
726 case RETIRE_CONNECTION_ID_FRAME:
727 return GetRetireConnectionIdFrameSize(*frame.retire_connection_id_frame);
728 case NEW_TOKEN_FRAME:
729 return GetNewTokenFrameSize(*frame.new_token_frame);
fkastenholz3c4eabf2019-04-22 07:49:59 -0700730 case MAX_STREAMS_FRAME:
731 return GetMaxStreamsFrameSize(version, frame.max_streams_frame);
732 case STREAMS_BLOCKED_FRAME:
733 return GetStreamsBlockedFrameSize(version, frame.streams_blocked_frame);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500734 case PATH_RESPONSE_FRAME:
735 return GetPathResponseFrameSize(*frame.path_response_frame);
736 case PATH_CHALLENGE_FRAME:
737 return GetPathChallengeFrameSize(*frame.path_challenge_frame);
738 case STOP_SENDING_FRAME:
739 return GetStopSendingFrameSize(*frame.stop_sending_frame);
740
741 case STREAM_FRAME:
742 case ACK_FRAME:
743 case STOP_WAITING_FRAME:
744 case MTU_DISCOVERY_FRAME:
745 case PADDING_FRAME:
746 case MESSAGE_FRAME:
747 case CRYPTO_FRAME:
748 case NUM_FRAME_TYPES:
749 DCHECK(false);
750 return 0;
751 }
752
753 // Not reachable, but some Chrome compilers can't figure that out. *sigh*
754 DCHECK(false);
755 return 0;
756}
757
758// static
759size_t QuicFramer::GetStreamIdSize(QuicStreamId stream_id) {
760 // Sizes are 1 through 4 bytes.
761 for (int i = 1; i <= 4; ++i) {
762 stream_id >>= 8;
763 if (stream_id == 0) {
764 return i;
765 }
766 }
767 QUIC_BUG << "Failed to determine StreamIDSize.";
768 return 4;
769}
770
771// static
dschinazi17d42422019-06-18 16:35:07 -0700772size_t QuicFramer::GetStreamOffsetSize(QuicTransportVersion /*version*/,
QUICHE teama6ef0a62019-03-07 20:34:33 -0500773 QuicStreamOffset offset) {
774 // 0 is a special case.
775 if (offset == 0) {
776 return 0;
777 }
778 // 2 through 8 are the remaining sizes.
779 offset >>= 8;
780 for (int i = 2; i <= 8; ++i) {
781 offset >>= 8;
782 if (offset == 0) {
783 return i;
784 }
785 }
786 QUIC_BUG << "Failed to determine StreamOffsetSize.";
787 return 8;
788}
789
790// static
791size_t QuicFramer::GetNewConnectionIdFrameSize(
792 const QuicNewConnectionIdFrame& frame) {
793 return kQuicFrameTypeSize +
794 QuicDataWriter::GetVarInt62Len(frame.sequence_number) +
fkastenholz1c19fc22019-07-12 11:06:19 -0700795 QuicDataWriter::GetVarInt62Len(frame.retire_prior_to) +
QUICHE teama6ef0a62019-03-07 20:34:33 -0500796 kConnectionIdLengthSize + frame.connection_id.length() +
797 sizeof(frame.stateless_reset_token);
798}
799
800// static
801size_t QuicFramer::GetRetireConnectionIdFrameSize(
802 const QuicRetireConnectionIdFrame& frame) {
803 return kQuicFrameTypeSize +
804 QuicDataWriter::GetVarInt62Len(frame.sequence_number);
805}
806
807// static
808size_t QuicFramer::GetNewTokenFrameSize(const QuicNewTokenFrame& frame) {
809 return kQuicFrameTypeSize +
810 QuicDataWriter::GetVarInt62Len(frame.token.length()) +
811 frame.token.length();
812}
813
814// TODO(nharper): Change this method to take a ParsedQuicVersion.
815bool QuicFramer::IsSupportedTransportVersion(
816 const QuicTransportVersion version) const {
817 for (ParsedQuicVersion supported_version : supported_versions_) {
818 if (version == supported_version.transport_version) {
819 return true;
820 }
821 }
822 return false;
823}
824
825bool QuicFramer::IsSupportedVersion(const ParsedQuicVersion version) const {
826 for (const ParsedQuicVersion& supported_version : supported_versions_) {
827 if (version == supported_version) {
828 return true;
829 }
830 }
831 return false;
832}
833
834size_t QuicFramer::GetSerializedFrameLength(
835 const QuicFrame& frame,
836 size_t free_bytes,
837 bool first_frame,
838 bool last_frame,
839 QuicPacketNumberLength packet_number_length) {
840 // Prevent a rare crash reported in b/19458523.
841 if (frame.type == ACK_FRAME && frame.ack_frame == nullptr) {
842 QUIC_BUG << "Cannot compute the length of a null ack frame. free_bytes:"
843 << free_bytes << " first_frame:" << first_frame
844 << " last_frame:" << last_frame
845 << " seq num length:" << packet_number_length;
846 set_error(QUIC_INTERNAL_ERROR);
847 visitor_->OnError(this);
848 return 0;
849 }
850 if (frame.type == PADDING_FRAME) {
851 if (frame.padding_frame.num_padding_bytes == -1) {
852 // Full padding to the end of the packet.
853 return free_bytes;
854 } else {
855 // Lite padding.
856 return free_bytes <
857 static_cast<size_t>(frame.padding_frame.num_padding_bytes)
858 ? free_bytes
859 : frame.padding_frame.num_padding_bytes;
860 }
861 }
862
863 size_t frame_len =
864 ComputeFrameLength(frame, last_frame, packet_number_length);
865 if (frame_len <= free_bytes) {
866 // Frame fits within packet. Note that acks may be truncated.
867 return frame_len;
868 }
869 // Only truncate the first frame in a packet, so if subsequent ones go
870 // over, stop including more frames.
871 if (!first_frame) {
872 return 0;
873 }
874 bool can_truncate =
875 frame.type == ACK_FRAME &&
876 free_bytes >= GetMinAckFrameSize(version_.transport_version,
877 PACKET_6BYTE_PACKET_NUMBER);
878 if (can_truncate) {
dschinazi66dea072019-04-09 11:41:06 -0700879 // Truncate the frame so the packet will not exceed kMaxOutgoingPacketSize.
QUICHE teama6ef0a62019-03-07 20:34:33 -0500880 // Note that we may not use every byte of the writer in this case.
881 QUIC_DLOG(INFO) << ENDPOINT
882 << "Truncating large frame, free bytes: " << free_bytes;
883 return free_bytes;
884 }
885 return 0;
886}
887
888QuicFramer::AckFrameInfo::AckFrameInfo()
889 : max_block_length(0), first_block_length(0), num_ack_blocks(0) {}
890
891QuicFramer::AckFrameInfo::AckFrameInfo(const AckFrameInfo& other) = default;
892
893QuicFramer::AckFrameInfo::~AckFrameInfo() {}
894
895bool QuicFramer::WriteIetfLongHeaderLength(const QuicPacketHeader& header,
896 QuicDataWriter* writer,
897 size_t length_field_offset,
898 EncryptionLevel level) {
899 if (!QuicVersionHasLongHeaderLengths(transport_version()) ||
900 !header.version_flag || length_field_offset == 0) {
901 return true;
902 }
903 if (writer->length() < length_field_offset ||
904 writer->length() - length_field_offset <
905 kQuicDefaultLongHeaderLengthLength) {
906 set_detailed_error("Invalid length_field_offset.");
907 QUIC_BUG << "Invalid length_field_offset.";
908 return false;
909 }
910 size_t length_to_write = writer->length() - length_field_offset -
911 kQuicDefaultLongHeaderLengthLength;
912 // Add length of auth tag.
913 length_to_write = GetCiphertextSize(level, length_to_write);
914
915 QuicDataWriter length_writer(writer->length() - length_field_offset,
916 writer->data() + length_field_offset);
917 if (!length_writer.WriteVarInt62(length_to_write,
918 kQuicDefaultLongHeaderLengthLength)) {
919 set_detailed_error("Failed to overwrite long header length.");
920 QUIC_BUG << "Failed to overwrite long header length.";
921 return false;
922 }
923 return true;
924}
925
926size_t QuicFramer::BuildDataPacket(const QuicPacketHeader& header,
927 const QuicFrames& frames,
928 char* buffer,
929 size_t packet_length,
930 EncryptionLevel level) {
931 QuicDataWriter writer(packet_length, buffer);
932 size_t length_field_offset = 0;
933 if (!AppendPacketHeader(header, &writer, &length_field_offset)) {
934 QUIC_BUG << "AppendPacketHeader failed";
935 return 0;
936 }
937
fkastenholz305e1732019-06-18 05:01:22 -0700938 if (VersionHasIetfQuicFrames(transport_version())) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500939 if (AppendIetfFrames(frames, &writer) == 0) {
940 return 0;
941 }
942 if (!WriteIetfLongHeaderLength(header, &writer, length_field_offset,
943 level)) {
944 return 0;
945 }
946 return writer.length();
947 }
948 // TODO(dschinazi) if we enable long header lengths before v99, we need to
949 // add support for fixing up lengths in QuicFramer::BuildDataPacket.
950 DCHECK(!QuicVersionHasLongHeaderLengths(transport_version()));
951
952 size_t i = 0;
953 for (const QuicFrame& frame : frames) {
954 // Determine if we should write stream frame length in header.
955 const bool last_frame_in_packet = i == frames.size() - 1;
956 if (!AppendTypeByte(frame, last_frame_in_packet, &writer)) {
957 QUIC_BUG << "AppendTypeByte failed";
958 return 0;
959 }
960
961 switch (frame.type) {
962 case PADDING_FRAME:
963 if (!AppendPaddingFrame(frame.padding_frame, &writer)) {
964 QUIC_BUG << "AppendPaddingFrame of "
965 << frame.padding_frame.num_padding_bytes << " failed";
966 return 0;
967 }
968 break;
969 case STREAM_FRAME:
970 if (!AppendStreamFrame(frame.stream_frame, last_frame_in_packet,
971 &writer)) {
972 QUIC_BUG << "AppendStreamFrame failed";
973 return 0;
974 }
975 break;
976 case ACK_FRAME:
977 if (!AppendAckFrameAndTypeByte(*frame.ack_frame, &writer)) {
978 QUIC_BUG << "AppendAckFrameAndTypeByte failed: " << detailed_error_;
979 return 0;
980 }
981 break;
982 case STOP_WAITING_FRAME:
983 if (!AppendStopWaitingFrame(header, frame.stop_waiting_frame,
984 &writer)) {
985 QUIC_BUG << "AppendStopWaitingFrame failed";
986 return 0;
987 }
988 break;
989 case MTU_DISCOVERY_FRAME:
990 // MTU discovery frames are serialized as ping frames.
991 QUIC_FALLTHROUGH_INTENDED;
992 case PING_FRAME:
993 // Ping has no payload.
994 break;
995 case RST_STREAM_FRAME:
996 if (!AppendRstStreamFrame(*frame.rst_stream_frame, &writer)) {
997 QUIC_BUG << "AppendRstStreamFrame failed";
998 return 0;
999 }
1000 break;
1001 case CONNECTION_CLOSE_FRAME:
1002 if (!AppendConnectionCloseFrame(*frame.connection_close_frame,
1003 &writer)) {
1004 QUIC_BUG << "AppendConnectionCloseFrame failed";
1005 return 0;
1006 }
1007 break;
1008 case GOAWAY_FRAME:
1009 if (!AppendGoAwayFrame(*frame.goaway_frame, &writer)) {
1010 QUIC_BUG << "AppendGoAwayFrame failed";
1011 return 0;
1012 }
1013 break;
1014 case WINDOW_UPDATE_FRAME:
1015 if (!AppendWindowUpdateFrame(*frame.window_update_frame, &writer)) {
1016 QUIC_BUG << "AppendWindowUpdateFrame failed";
1017 return 0;
1018 }
1019 break;
1020 case BLOCKED_FRAME:
1021 if (!AppendBlockedFrame(*frame.blocked_frame, &writer)) {
1022 QUIC_BUG << "AppendBlockedFrame failed";
1023 return 0;
1024 }
1025 break;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001026 case NEW_CONNECTION_ID_FRAME:
1027 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -07001028 "Attempt to append NEW_CONNECTION_ID frame and not in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05001029 return RaiseError(QUIC_INTERNAL_ERROR);
1030 case RETIRE_CONNECTION_ID_FRAME:
1031 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -07001032 "Attempt to append RETIRE_CONNECTION_ID frame and not in IETF "
1033 "QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05001034 return RaiseError(QUIC_INTERNAL_ERROR);
1035 case NEW_TOKEN_FRAME:
1036 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -07001037 "Attempt to append NEW_TOKEN_ID frame and not in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05001038 return RaiseError(QUIC_INTERNAL_ERROR);
fkastenholz3c4eabf2019-04-22 07:49:59 -07001039 case MAX_STREAMS_FRAME:
QUICHE teama6ef0a62019-03-07 20:34:33 -05001040 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -07001041 "Attempt to append MAX_STREAMS frame and not in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05001042 return RaiseError(QUIC_INTERNAL_ERROR);
fkastenholz3c4eabf2019-04-22 07:49:59 -07001043 case STREAMS_BLOCKED_FRAME:
QUICHE teama6ef0a62019-03-07 20:34:33 -05001044 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -07001045 "Attempt to append STREAMS_BLOCKED frame and not in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05001046 return RaiseError(QUIC_INTERNAL_ERROR);
1047 case PATH_RESPONSE_FRAME:
1048 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -07001049 "Attempt to append PATH_RESPONSE frame and not in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05001050 return RaiseError(QUIC_INTERNAL_ERROR);
1051 case PATH_CHALLENGE_FRAME:
1052 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -07001053 "Attempt to append PATH_CHALLENGE frame and not in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05001054 return RaiseError(QUIC_INTERNAL_ERROR);
1055 case STOP_SENDING_FRAME:
1056 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -07001057 "Attempt to append STOP_SENDING frame and not in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05001058 return RaiseError(QUIC_INTERNAL_ERROR);
1059 case MESSAGE_FRAME:
1060 if (!AppendMessageFrameAndTypeByte(*frame.message_frame,
1061 last_frame_in_packet, &writer)) {
1062 QUIC_BUG << "AppendMessageFrame failed";
1063 return 0;
1064 }
1065 break;
1066 case CRYPTO_FRAME:
QUICHE teamea740082019-03-11 17:58:43 -07001067 if (!QuicVersionUsesCryptoFrames(version_.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001068 set_detailed_error(
1069 "Attempt to append CRYPTO frame in version prior to 47.");
1070 return RaiseError(QUIC_INTERNAL_ERROR);
1071 }
1072 if (!AppendCryptoFrame(*frame.crypto_frame, &writer)) {
1073 QUIC_BUG << "AppendCryptoFrame failed";
1074 return 0;
1075 }
1076 break;
1077 default:
1078 RaiseError(QUIC_INVALID_FRAME_DATA);
1079 QUIC_BUG << "QUIC_INVALID_FRAME_DATA";
1080 return 0;
1081 }
1082 ++i;
1083 }
1084
1085 return writer.length();
1086}
1087
1088size_t QuicFramer::AppendIetfFrames(const QuicFrames& frames,
1089 QuicDataWriter* writer) {
1090 size_t i = 0;
1091 for (const QuicFrame& frame : frames) {
1092 // Determine if we should write stream frame length in header.
1093 const bool last_frame_in_packet = i == frames.size() - 1;
1094 if (!AppendIetfTypeByte(frame, last_frame_in_packet, writer)) {
1095 QUIC_BUG << "AppendIetfTypeByte failed: " << detailed_error();
1096 return 0;
1097 }
1098
1099 switch (frame.type) {
1100 case PADDING_FRAME:
1101 if (!AppendPaddingFrame(frame.padding_frame, writer)) {
1102 QUIC_BUG << "AppendPaddingFrame of "
1103 << frame.padding_frame.num_padding_bytes
1104 << " failed: " << detailed_error();
1105 return 0;
1106 }
1107 break;
1108 case STREAM_FRAME:
1109 if (!AppendStreamFrame(frame.stream_frame, last_frame_in_packet,
1110 writer)) {
1111 QUIC_BUG << "AppendStreamFrame failed: " << detailed_error();
1112 return 0;
1113 }
1114 break;
1115 case ACK_FRAME:
1116 if (!AppendIetfAckFrameAndTypeByte(*frame.ack_frame, writer)) {
QUICHE team4fe0b942019-03-08 09:25:06 -05001117 QUIC_BUG << "AppendIetfAckFrameAndTypeByte failed: "
1118 << detailed_error();
QUICHE teama6ef0a62019-03-07 20:34:33 -05001119 return 0;
1120 }
1121 break;
1122 case STOP_WAITING_FRAME:
1123 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -07001124 "Attempt to append STOP WAITING frame in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05001125 return RaiseError(QUIC_INTERNAL_ERROR);
1126 case MTU_DISCOVERY_FRAME:
1127 // MTU discovery frames are serialized as ping frames.
1128 QUIC_FALLTHROUGH_INTENDED;
1129 case PING_FRAME:
1130 // Ping has no payload.
1131 break;
1132 case RST_STREAM_FRAME:
1133 if (!AppendRstStreamFrame(*frame.rst_stream_frame, writer)) {
1134 QUIC_BUG << "AppendRstStreamFrame failed: " << detailed_error();
1135 return 0;
1136 }
1137 break;
1138 case CONNECTION_CLOSE_FRAME:
fkastenholz72f509b2019-04-10 09:17:49 -07001139 if (!AppendIetfConnectionCloseFrame(*frame.connection_close_frame,
1140 writer)) {
1141 QUIC_BUG << "AppendIetfConnectionCloseFrame failed: "
1142 << detailed_error();
QUICHE teama6ef0a62019-03-07 20:34:33 -05001143 return 0;
1144 }
1145 break;
1146 case GOAWAY_FRAME:
fkastenholz305e1732019-06-18 05:01:22 -07001147 set_detailed_error("Attempt to append GOAWAY frame in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05001148 return RaiseError(QUIC_INTERNAL_ERROR);
1149 case WINDOW_UPDATE_FRAME:
1150 // Depending on whether there is a stream ID or not, will be either a
1151 // MAX STREAM DATA frame or a MAX DATA frame.
1152 if (frame.window_update_frame->stream_id ==
1153 QuicUtils::GetInvalidStreamId(transport_version())) {
1154 if (!AppendMaxDataFrame(*frame.window_update_frame, writer)) {
1155 QUIC_BUG << "AppendMaxDataFrame failed: " << detailed_error();
1156 return 0;
1157 }
1158 } else {
1159 if (!AppendMaxStreamDataFrame(*frame.window_update_frame, writer)) {
1160 QUIC_BUG << "AppendMaxStreamDataFrame failed: " << detailed_error();
1161 return 0;
1162 }
1163 }
1164 break;
1165 case BLOCKED_FRAME:
1166 if (!AppendBlockedFrame(*frame.blocked_frame, writer)) {
1167 QUIC_BUG << "AppendBlockedFrame failed: " << detailed_error();
1168 return 0;
1169 }
1170 break;
fkastenholz3c4eabf2019-04-22 07:49:59 -07001171 case MAX_STREAMS_FRAME:
1172 if (!AppendMaxStreamsFrame(frame.max_streams_frame, writer)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001173 QUIC_BUG << "AppendMaxStreamsFrame failed" << detailed_error();
1174 return 0;
1175 }
1176 break;
fkastenholz3c4eabf2019-04-22 07:49:59 -07001177 case STREAMS_BLOCKED_FRAME:
1178 if (!AppendStreamsBlockedFrame(frame.streams_blocked_frame, writer)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001179 QUIC_BUG << "AppendStreamsBlockedFrame failed" << detailed_error();
1180 return 0;
1181 }
1182 break;
1183 case NEW_CONNECTION_ID_FRAME:
1184 if (!AppendNewConnectionIdFrame(*frame.new_connection_id_frame,
1185 writer)) {
1186 QUIC_BUG << "AppendNewConnectionIdFrame failed: " << detailed_error();
1187 return 0;
1188 }
1189 break;
1190 case RETIRE_CONNECTION_ID_FRAME:
1191 if (!AppendRetireConnectionIdFrame(*frame.retire_connection_id_frame,
1192 writer)) {
1193 QUIC_BUG << "AppendRetireConnectionIdFrame failed: "
1194 << detailed_error();
1195 return 0;
1196 }
1197 break;
1198 case NEW_TOKEN_FRAME:
1199 if (!AppendNewTokenFrame(*frame.new_token_frame, writer)) {
1200 QUIC_BUG << "AppendNewTokenFrame failed: " << detailed_error();
1201 return 0;
1202 }
1203 break;
1204 case STOP_SENDING_FRAME:
1205 if (!AppendStopSendingFrame(*frame.stop_sending_frame, writer)) {
1206 QUIC_BUG << "AppendStopSendingFrame failed: " << detailed_error();
1207 return 0;
1208 }
1209 break;
1210 case PATH_CHALLENGE_FRAME:
1211 if (!AppendPathChallengeFrame(*frame.path_challenge_frame, writer)) {
1212 QUIC_BUG << "AppendPathChallengeFrame failed: " << detailed_error();
1213 return 0;
1214 }
1215 break;
1216 case PATH_RESPONSE_FRAME:
1217 if (!AppendPathResponseFrame(*frame.path_response_frame, writer)) {
1218 QUIC_BUG << "AppendPathResponseFrame failed: " << detailed_error();
1219 return 0;
1220 }
1221 break;
1222 case MESSAGE_FRAME:
1223 if (!AppendMessageFrameAndTypeByte(*frame.message_frame,
1224 last_frame_in_packet, writer)) {
1225 QUIC_BUG << "AppendMessageFrame failed: " << detailed_error();
1226 return 0;
1227 }
1228 break;
1229 case CRYPTO_FRAME:
1230 if (!AppendCryptoFrame(*frame.crypto_frame, writer)) {
1231 QUIC_BUG << "AppendCryptoFrame failed: " << detailed_error();
1232 return 0;
1233 }
1234 break;
1235 default:
1236 RaiseError(QUIC_INVALID_FRAME_DATA);
1237 set_detailed_error("Tried to append unknown frame type.");
1238 QUIC_BUG << "QUIC_INVALID_FRAME_DATA";
1239 return 0;
1240 }
1241 ++i;
1242 }
1243
1244 return writer->length();
1245}
1246
rch67cb9df2019-03-26 16:52:07 -07001247size_t QuicFramer::BuildConnectivityProbingPacket(
QUICHE teama6ef0a62019-03-07 20:34:33 -05001248 const QuicPacketHeader& header,
1249 char* buffer,
1250 size_t packet_length,
1251 EncryptionLevel level) {
1252 QuicFrames frames;
1253
1254 // Write a PING frame, which has no data payload.
1255 QuicPingFrame ping_frame;
1256 frames.push_back(QuicFrame(ping_frame));
1257
1258 // Add padding to the rest of the packet.
1259 QuicPaddingFrame padding_frame;
1260 frames.push_back(QuicFrame(padding_frame));
1261
1262 return BuildDataPacket(header, frames, buffer, packet_length, level);
1263}
1264
QUICHE teama6ef0a62019-03-07 20:34:33 -05001265size_t QuicFramer::BuildPaddedPathChallengePacket(
1266 const QuicPacketHeader& header,
1267 char* buffer,
1268 size_t packet_length,
1269 QuicPathFrameBuffer* payload,
1270 QuicRandom* randomizer,
1271 EncryptionLevel level) {
fkastenholz305e1732019-06-18 05:01:22 -07001272 if (!VersionHasIetfQuicFrames(version_.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001273 QUIC_BUG << "Attempt to build a PATH_CHALLENGE Connectivity Probing "
1274 "packet and not doing IETF QUIC";
1275 return 0;
1276 }
1277 QuicFrames frames;
1278
1279 // Write a PATH_CHALLENGE frame, which has a random 8-byte payload
1280 randomizer->RandBytes(payload->data(), payload->size());
1281
1282 QuicPathChallengeFrame path_challenge_frame(0, *payload);
1283 frames.push_back(QuicFrame(&path_challenge_frame));
1284
1285 // Add padding to the rest of the packet in order to assess Path MTU
1286 // characteristics.
1287 QuicPaddingFrame padding_frame;
1288 frames.push_back(QuicFrame(padding_frame));
1289
1290 return BuildDataPacket(header, frames, buffer, packet_length, level);
1291}
1292
1293size_t QuicFramer::BuildPathResponsePacket(
1294 const QuicPacketHeader& header,
1295 char* buffer,
1296 size_t packet_length,
1297 const QuicDeque<QuicPathFrameBuffer>& payloads,
1298 const bool is_padded,
1299 EncryptionLevel level) {
1300 if (payloads.empty()) {
1301 QUIC_BUG
1302 << "Attempt to generate connectivity response with no request payloads";
1303 return 0;
1304 }
fkastenholz305e1732019-06-18 05:01:22 -07001305 if (!VersionHasIetfQuicFrames(version_.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001306 QUIC_BUG << "Attempt to build a PATH_RESPONSE Connectivity Probing "
1307 "packet and not doing IETF QUIC";
1308 return 0;
1309 }
1310
1311 std::vector<std::unique_ptr<QuicPathResponseFrame>> path_response_frames;
1312 for (const QuicPathFrameBuffer& payload : payloads) {
1313 // Note that the control frame ID can be 0 since this is not retransmitted.
1314 path_response_frames.push_back(
1315 QuicMakeUnique<QuicPathResponseFrame>(0, payload));
1316 }
1317
1318 QuicFrames frames;
1319 for (const std::unique_ptr<QuicPathResponseFrame>& path_response_frame :
1320 path_response_frames) {
1321 frames.push_back(QuicFrame(path_response_frame.get()));
1322 }
1323
1324 if (is_padded) {
1325 // Add padding to the rest of the packet in order to assess Path MTU
1326 // characteristics.
1327 QuicPaddingFrame padding_frame;
1328 frames.push_back(QuicFrame(padding_frame));
1329 }
1330
1331 return BuildDataPacket(header, frames, buffer, packet_length, level);
1332}
1333
1334// static
1335std::unique_ptr<QuicEncryptedPacket> QuicFramer::BuildPublicResetPacket(
1336 const QuicPublicResetPacket& packet) {
1337 CryptoHandshakeMessage reset;
1338 reset.set_tag(kPRST);
1339 reset.SetValue(kRNON, packet.nonce_proof);
1340 if (packet.client_address.host().address_family() !=
1341 IpAddressFamily::IP_UNSPEC) {
1342 // packet.client_address is non-empty.
1343 QuicSocketAddressCoder address_coder(packet.client_address);
vasilvvc48c8712019-03-11 13:38:16 -07001344 std::string serialized_address = address_coder.Encode();
QUICHE teama6ef0a62019-03-07 20:34:33 -05001345 if (serialized_address.empty()) {
1346 return nullptr;
1347 }
1348 reset.SetStringPiece(kCADR, serialized_address);
1349 }
1350 if (!packet.endpoint_id.empty()) {
1351 reset.SetStringPiece(kEPID, packet.endpoint_id);
1352 }
1353 const QuicData& reset_serialized = reset.GetSerialized();
1354
1355 size_t len = kPublicFlagsSize + packet.connection_id.length() +
1356 reset_serialized.length();
1357 std::unique_ptr<char[]> buffer(new char[len]);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001358 QuicDataWriter writer(len, buffer.get());
1359
1360 uint8_t flags = static_cast<uint8_t>(PACKET_PUBLIC_FLAGS_RST |
1361 PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID);
1362 // This hack makes post-v33 public reset packet look like pre-v33 packets.
1363 flags |= static_cast<uint8_t>(PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID_OLD);
1364 if (!writer.WriteUInt8(flags)) {
1365 return nullptr;
1366 }
1367
1368 if (!writer.WriteConnectionId(packet.connection_id)) {
1369 return nullptr;
1370 }
1371
1372 if (!writer.WriteBytes(reset_serialized.data(), reset_serialized.length())) {
1373 return nullptr;
1374 }
1375
1376 return QuicMakeUnique<QuicEncryptedPacket>(buffer.release(), len, true);
1377}
1378
1379// static
1380std::unique_ptr<QuicEncryptedPacket> QuicFramer::BuildIetfStatelessResetPacket(
dschinazi17d42422019-06-18 16:35:07 -07001381 QuicConnectionId /*connection_id*/,
QUICHE teama6ef0a62019-03-07 20:34:33 -05001382 QuicUint128 stateless_reset_token) {
1383 QUIC_DVLOG(1) << "Building IETF stateless reset packet.";
1384 size_t len = kPacketHeaderTypeSize + kMinRandomBytesLengthInStatelessReset +
1385 sizeof(stateless_reset_token);
1386 std::unique_ptr<char[]> buffer(new char[len]);
1387 QuicDataWriter writer(len, buffer.get());
1388
1389 uint8_t type = 0;
1390 type |= FLAGS_FIXED_BIT;
1391 type |= FLAGS_SHORT_HEADER_RESERVED_1;
1392 type |= FLAGS_SHORT_HEADER_RESERVED_2;
fayangf36e29d2019-06-06 14:03:40 -07001393 type |= PacketNumberLengthToOnWireValue(QUIC_VERSION_UNSUPPORTED,
1394 PACKET_1BYTE_PACKET_NUMBER);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001395
1396 // Append type byte.
1397 if (!writer.WriteUInt8(type)) {
1398 return nullptr;
1399 }
1400 // Append random bytes.
1401 if (!writer.WriteRandomBytes(QuicRandom::GetInstance(),
1402 kMinRandomBytesLengthInStatelessReset)) {
1403 return nullptr;
1404 }
1405
1406 // Append stateless reset token.
1407 if (!writer.WriteBytes(&stateless_reset_token,
1408 sizeof(stateless_reset_token))) {
1409 return nullptr;
1410 }
1411 return QuicMakeUnique<QuicEncryptedPacket>(buffer.release(), len, true);
1412}
1413
1414// static
1415std::unique_ptr<QuicEncryptedPacket> QuicFramer::BuildVersionNegotiationPacket(
dschinazi8ff74822019-05-28 16:37:20 -07001416 QuicConnectionId server_connection_id,
dschinazib417d602019-05-29 13:08:45 -07001417 QuicConnectionId client_connection_id,
QUICHE teama6ef0a62019-03-07 20:34:33 -05001418 bool ietf_quic,
dschinazi48ac9192019-07-31 00:07:26 -07001419 bool use_length_prefix,
QUICHE teama6ef0a62019-03-07 20:34:33 -05001420 const ParsedQuicVersionVector& versions) {
dschinazi1ac22cc2019-06-25 11:47:50 -07001421 ParsedQuicVersionVector wire_versions = versions;
1422 if (!GetQuicReloadableFlag(quic_version_negotiation_grease)) {
1423 if (wire_versions.empty()) {
1424 wire_versions = {QuicVersionReservedForNegotiation()};
1425 }
1426 } else {
1427 // Add a version reserved for negotiation as suggested by the
1428 // "Using Reserved Versions" section of draft-ietf-quic-transport.
1429 QUIC_RELOADABLE_FLAG_COUNT_N(quic_version_negotiation_grease, 1, 2);
1430 if (wire_versions.empty()) {
1431 // Ensure that version negotiation packets we send have at least two
1432 // versions. This guarantees that, under all circumstances, all QUIC
1433 // packets we send are at least 14 bytes long.
1434 wire_versions = {QuicVersionReservedForNegotiation(),
1435 QuicVersionReservedForNegotiation()};
1436 } else {
1437 // This is not uniformely distributed but is acceptable since no security
1438 // depends on this randomness.
1439 size_t version_index = 0;
1440 const bool disable_randomness =
1441 GetQuicFlag(FLAGS_quic_disable_version_negotiation_grease_randomness);
1442 if (!disable_randomness) {
1443 version_index = QuicRandom::GetInstance()->RandUint64() %
1444 (wire_versions.size() + 1);
1445 }
1446 wire_versions.insert(wire_versions.begin() + version_index,
1447 QuicVersionReservedForNegotiation());
1448 }
1449 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001450 if (ietf_quic) {
dschinazi1ac22cc2019-06-25 11:47:50 -07001451 return BuildIetfVersionNegotiationPacket(
dschinazi48ac9192019-07-31 00:07:26 -07001452 use_length_prefix, server_connection_id, client_connection_id,
1453 wire_versions);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001454 }
dschinazib417d602019-05-29 13:08:45 -07001455
1456 // The GQUIC encoding does not support encoding client connection IDs.
1457 DCHECK(client_connection_id.IsEmpty());
dschinazi48ac9192019-07-31 00:07:26 -07001458 // The GQUIC encoding does not support length-prefixed connection IDs.
1459 DCHECK(!use_length_prefix);
dschinazib417d602019-05-29 13:08:45 -07001460
dschinazi1ac22cc2019-06-25 11:47:50 -07001461 DCHECK(!wire_versions.empty());
dschinazi8ff74822019-05-28 16:37:20 -07001462 size_t len = kPublicFlagsSize + server_connection_id.length() +
dschinazi1ac22cc2019-06-25 11:47:50 -07001463 wire_versions.size() * kQuicVersionSize;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001464 std::unique_ptr<char[]> buffer(new char[len]);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001465 QuicDataWriter writer(len, buffer.get());
1466
1467 uint8_t flags = static_cast<uint8_t>(
1468 PACKET_PUBLIC_FLAGS_VERSION | PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID |
1469 // TODO(rch): Remove this QUIC_VERSION_32 is retired.
1470 PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID_OLD);
1471 if (!writer.WriteUInt8(flags)) {
1472 return nullptr;
1473 }
1474
dschinazi8ff74822019-05-28 16:37:20 -07001475 if (!writer.WriteConnectionId(server_connection_id)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001476 return nullptr;
1477 }
1478
dschinazi1ac22cc2019-06-25 11:47:50 -07001479 for (const ParsedQuicVersion& version : wire_versions) {
nharpereaab5ad2019-05-31 12:23:25 -07001480 if (!writer.WriteUInt32(CreateQuicVersionLabel(version))) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001481 return nullptr;
1482 }
1483 }
1484
1485 return QuicMakeUnique<QuicEncryptedPacket>(buffer.release(), len, true);
1486}
1487
1488// static
1489std::unique_ptr<QuicEncryptedPacket>
1490QuicFramer::BuildIetfVersionNegotiationPacket(
dschinazi48ac9192019-07-31 00:07:26 -07001491 bool use_length_prefix,
dschinazib417d602019-05-29 13:08:45 -07001492 QuicConnectionId server_connection_id,
1493 QuicConnectionId client_connection_id,
QUICHE teama6ef0a62019-03-07 20:34:33 -05001494 const ParsedQuicVersionVector& versions) {
dschinazi48ac9192019-07-31 00:07:26 -07001495 QUIC_DVLOG(1) << "Building IETF version negotiation packet with"
1496 << (use_length_prefix ? "" : "out")
1497 << " length prefix, server_connection_id "
1498 << server_connection_id << " client_connection_id "
1499 << client_connection_id << " versions "
dschinazi5a354c92019-05-09 12:18:53 -07001500 << ParsedQuicVersionVectorToString(versions);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001501 DCHECK(!versions.empty());
1502 size_t len = kPacketHeaderTypeSize + kConnectionIdLengthSize +
dschinazib417d602019-05-29 13:08:45 -07001503 client_connection_id.length() + server_connection_id.length() +
QUICHE teama6ef0a62019-03-07 20:34:33 -05001504 (versions.size() + 1) * kQuicVersionSize;
dschinazi48ac9192019-07-31 00:07:26 -07001505 if (use_length_prefix) {
1506 // When using length-prefixed connection IDs, packets carry two lengths
1507 // instead of one.
1508 len += kConnectionIdLengthSize;
1509 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001510 std::unique_ptr<char[]> buffer(new char[len]);
1511 QuicDataWriter writer(len, buffer.get());
1512
1513 // TODO(fayang): Randomly select a value for the type.
dschinazi0366de92019-06-18 20:00:27 -07001514 uint8_t type = static_cast<uint8_t>(FLAGS_LONG_HEADER | FLAGS_FIXED_BIT);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001515 if (!writer.WriteUInt8(type)) {
1516 return nullptr;
1517 }
1518
1519 if (!writer.WriteUInt32(0)) {
1520 return nullptr;
1521 }
1522
dschinazi48ac9192019-07-31 00:07:26 -07001523 if (!AppendIetfConnectionIds(true, use_length_prefix, client_connection_id,
1524 server_connection_id, &writer)) {
dschinazi1f485a12019-05-13 11:57:01 -07001525 return nullptr;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001526 }
1527
1528 for (const ParsedQuicVersion& version : versions) {
nharpereaab5ad2019-05-31 12:23:25 -07001529 if (!writer.WriteUInt32(CreateQuicVersionLabel(version))) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001530 return nullptr;
1531 }
1532 }
1533
1534 return QuicMakeUnique<QuicEncryptedPacket>(buffer.release(), len, true);
1535}
1536
1537bool QuicFramer::ProcessPacket(const QuicEncryptedPacket& packet) {
1538 QuicDataReader reader(packet.data(), packet.length());
1539
1540 bool packet_has_ietf_packet_header = false;
1541 if (infer_packet_header_type_from_version_) {
1542 packet_has_ietf_packet_header =
fayangd4291e42019-05-30 10:31:21 -07001543 VersionHasIetfInvariantHeader(version_.transport_version);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001544 } else if (!reader.IsDoneReading()) {
1545 uint8_t type = reader.PeekByte();
1546 packet_has_ietf_packet_header = QuicUtils::IsIetfPacketHeader(type);
1547 }
1548 if (packet_has_ietf_packet_header) {
1549 QUIC_DVLOG(1) << ENDPOINT << "Processing IETF QUIC packet.";
1550 }
1551
1552 visitor_->OnPacket();
1553
1554 QuicPacketHeader header;
1555 if (!ProcessPublicHeader(&reader, packet_has_ietf_packet_header, &header)) {
1556 DCHECK_NE("", detailed_error_);
1557 QUIC_DVLOG(1) << ENDPOINT << "Unable to process public header. Error: "
1558 << detailed_error_;
1559 DCHECK_NE("", detailed_error_);
1560 RecordDroppedPacketReason(DroppedPacketReason::INVALID_PUBLIC_HEADER);
1561 return RaiseError(QUIC_INVALID_PACKET_HEADER);
1562 }
1563
1564 if (!visitor_->OnUnauthenticatedPublicHeader(header)) {
1565 // The visitor suppresses further processing of the packet.
1566 return true;
1567 }
1568
dschinazie0df3f72019-05-06 16:37:51 -07001569 if (IsVersionNegotiation(header, packet_has_ietf_packet_header)) {
dschinazi072da7c2019-05-07 17:57:42 -07001570 if (perspective_ == Perspective::IS_CLIENT) {
1571 QUIC_DVLOG(1) << "Client received version negotiation packet";
1572 return ProcessVersionNegotiationPacket(&reader, header);
1573 } else {
1574 QUIC_DLOG(ERROR) << "Server received version negotiation packet";
1575 set_detailed_error("Server received version negotiation packet.");
1576 return RaiseError(QUIC_INVALID_VERSION_NEGOTIATION_PACKET);
1577 }
dschinazie0df3f72019-05-06 16:37:51 -07001578 }
1579
1580 if (header.version_flag && header.version != version_) {
1581 if (perspective_ == Perspective::IS_SERVER) {
fayang8aba1ff2019-06-21 12:00:54 -07001582 if (!visitor_->OnProtocolVersionMismatch(header.version)) {
dschinazie0df3f72019-05-06 16:37:51 -07001583 RecordDroppedPacketReason(DroppedPacketReason::VERSION_MISMATCH);
1584 return true;
1585 }
1586 } else {
1587 // A client received a packet of a different version but that packet is
1588 // not a version negotiation packet. It is therefore invalid and dropped.
1589 QUIC_DLOG(ERROR) << "Client received unexpected version "
1590 << ParsedQuicVersionToString(header.version)
1591 << " instead of " << ParsedQuicVersionToString(version_);
1592 set_detailed_error("Client received unexpected version.");
1593 return RaiseError(QUIC_INVALID_VERSION);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001594 }
1595 }
1596
1597 bool rv;
dschinazie0df3f72019-05-06 16:37:51 -07001598 if (header.long_packet_type == RETRY) {
dschinazi244f6dc2019-05-06 15:45:16 -07001599 rv = ProcessRetryPacket(&reader, header);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001600 } else if (header.reset_flag) {
1601 rv = ProcessPublicResetPacket(&reader, header);
dschinazie8d7fa72019-04-05 14:44:40 -07001602 } else if (packet.length() <= kMaxIncomingPacketSize) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001603 // The optimized decryption algorithm implementations run faster when
1604 // operating on aligned memory.
dschinazie8d7fa72019-04-05 14:44:40 -07001605 QUIC_CACHELINE_ALIGNED char buffer[kMaxIncomingPacketSize];
QUICHE teama6ef0a62019-03-07 20:34:33 -05001606 if (packet_has_ietf_packet_header) {
1607 rv = ProcessIetfDataPacket(&reader, &header, packet, buffer,
dschinazie8d7fa72019-04-05 14:44:40 -07001608 QUIC_ARRAYSIZE(buffer));
QUICHE teama6ef0a62019-03-07 20:34:33 -05001609 } else {
dschinazie8d7fa72019-04-05 14:44:40 -07001610 rv = ProcessDataPacket(&reader, &header, packet, buffer,
1611 QUIC_ARRAYSIZE(buffer));
QUICHE teama6ef0a62019-03-07 20:34:33 -05001612 }
1613 } else {
1614 std::unique_ptr<char[]> large_buffer(new char[packet.length()]);
1615 if (packet_has_ietf_packet_header) {
1616 rv = ProcessIetfDataPacket(&reader, &header, packet, large_buffer.get(),
1617 packet.length());
1618 } else {
1619 rv = ProcessDataPacket(&reader, &header, packet, large_buffer.get(),
1620 packet.length());
1621 }
1622 QUIC_BUG_IF(rv) << "QUIC should never successfully process packets larger"
dschinazie8d7fa72019-04-05 14:44:40 -07001623 << "than kMaxIncomingPacketSize. packet size:"
1624 << packet.length();
QUICHE teama6ef0a62019-03-07 20:34:33 -05001625 }
1626 return rv;
1627}
1628
1629bool QuicFramer::ProcessVersionNegotiationPacket(
1630 QuicDataReader* reader,
1631 const QuicPacketHeader& header) {
1632 DCHECK_EQ(Perspective::IS_CLIENT, perspective_);
1633
QUICHE team2252b702019-05-14 23:55:14 -04001634 QuicVersionNegotiationPacket packet(
1635 GetServerConnectionIdAsRecipient(header, perspective_));
QUICHE teama6ef0a62019-03-07 20:34:33 -05001636 // Try reading at least once to raise error if the packet is invalid.
1637 do {
1638 QuicVersionLabel version_label;
fayang40315542019-05-09 09:19:09 -07001639 if (!ProcessVersionLabel(reader, &version_label)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001640 set_detailed_error("Unable to read supported version in negotiation.");
1641 RecordDroppedPacketReason(
1642 DroppedPacketReason::INVALID_VERSION_NEGOTIATION_PACKET);
1643 return RaiseError(QUIC_INVALID_VERSION_NEGOTIATION_PACKET);
1644 }
nharper4fd11052019-06-04 14:23:22 -07001645 ParsedQuicVersion parsed_version = ParseQuicVersionLabel(version_label);
1646 if (parsed_version != UnsupportedQuicVersion()) {
1647 packet.versions.push_back(parsed_version);
1648 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001649 } while (!reader->IsDoneReading());
1650
dschinazi5a354c92019-05-09 12:18:53 -07001651 QUIC_DLOG(INFO) << ENDPOINT << "parsed version negotiation: "
1652 << ParsedQuicVersionVectorToString(packet.versions);
1653
QUICHE teama6ef0a62019-03-07 20:34:33 -05001654 visitor_->OnVersionNegotiationPacket(packet);
1655 return true;
1656}
1657
dschinazi244f6dc2019-05-06 15:45:16 -07001658bool QuicFramer::ProcessRetryPacket(QuicDataReader* reader,
1659 const QuicPacketHeader& header) {
1660 DCHECK_EQ(Perspective::IS_CLIENT, perspective_);
1661
dschinazi244f6dc2019-05-06 15:45:16 -07001662 QuicConnectionId original_destination_connection_id;
dschinazi48ac9192019-07-31 00:07:26 -07001663 if (version_.HasLengthPrefixedConnectionIds()) {
1664 // Parse Original Destination Connection ID.
1665 if (!reader->ReadLengthPrefixedConnectionId(
1666 &original_destination_connection_id)) {
1667 set_detailed_error("Unable to read Original Destination ConnectionId.");
1668 return false;
1669 }
1670 } else {
1671 // Parse Original Destination Connection ID Length.
1672 uint8_t odcil = header.type_byte & 0xf;
1673 if (odcil != 0) {
1674 odcil += kConnectionIdLengthAdjustment;
1675 }
1676
1677 // Parse Original Destination Connection ID.
1678 if (!reader->ReadConnectionId(&original_destination_connection_id, odcil)) {
1679 set_detailed_error("Unable to read Original Destination ConnectionId.");
1680 return false;
1681 }
dschinazi244f6dc2019-05-06 15:45:16 -07001682 }
1683
dschinazib953d022019-08-01 18:05:58 -07001684 if (!QuicUtils::IsConnectionIdValidForVersion(
1685 original_destination_connection_id, transport_version())) {
1686 set_detailed_error(
1687 "Received Original Destination ConnectionId with invalid length.");
1688 return false;
1689 }
1690
dschinazi244f6dc2019-05-06 15:45:16 -07001691 QuicStringPiece retry_token = reader->ReadRemainingPayload();
1692 visitor_->OnRetryPacket(original_destination_connection_id,
1693 header.source_connection_id, retry_token);
1694 return true;
1695}
1696
QUICHE teama6ef0a62019-03-07 20:34:33 -05001697// Seeks the current packet to check for a coalesced packet at the end.
1698// If the IETF length field only spans part of the outer packet,
1699// then there is a coalesced packet after this one.
1700void QuicFramer::MaybeProcessCoalescedPacket(
1701 const QuicDataReader& encrypted_reader,
1702 uint64_t remaining_bytes_length,
1703 const QuicPacketHeader& header) {
1704 if (header.remaining_packet_length >= remaining_bytes_length) {
1705 // There is no coalesced packet.
1706 return;
1707 }
1708
1709 QuicStringPiece remaining_data = encrypted_reader.PeekRemainingPayload();
1710 DCHECK_EQ(remaining_data.length(), remaining_bytes_length);
1711
1712 const char* coalesced_data =
1713 remaining_data.data() + header.remaining_packet_length;
1714 uint64_t coalesced_data_length =
1715 remaining_bytes_length - header.remaining_packet_length;
1716 QuicDataReader coalesced_reader(coalesced_data, coalesced_data_length);
1717
1718 QuicPacketHeader coalesced_header;
1719 if (!ProcessIetfPacketHeader(&coalesced_reader, &coalesced_header)) {
1720 QUIC_PEER_BUG << ENDPOINT
1721 << "Failed to parse received coalesced header of length "
1722 << coalesced_data_length << ": "
1723 << QuicTextUtils::HexEncode(coalesced_data,
1724 coalesced_data_length)
1725 << " previous header was " << header;
1726 return;
1727 }
1728
1729 if (coalesced_header.destination_connection_id !=
1730 header.destination_connection_id ||
1731 (coalesced_header.form != IETF_QUIC_SHORT_HEADER_PACKET &&
1732 coalesced_header.version != header.version)) {
1733 QUIC_PEER_BUG << ENDPOINT << "Received mismatched coalesced header "
1734 << coalesced_header << " previous header was " << header;
1735 return;
1736 }
1737
1738 QuicEncryptedPacket coalesced_packet(coalesced_data, coalesced_data_length,
1739 /*owns_buffer=*/false);
1740 visitor_->OnCoalescedPacket(coalesced_packet);
1741}
1742
1743bool QuicFramer::MaybeProcessIetfLength(QuicDataReader* encrypted_reader,
1744 QuicPacketHeader* header) {
1745 if (!QuicVersionHasLongHeaderLengths(header->version.transport_version) ||
1746 header->form != IETF_QUIC_LONG_HEADER_PACKET ||
1747 (header->long_packet_type != INITIAL &&
1748 header->long_packet_type != HANDSHAKE &&
1749 header->long_packet_type != ZERO_RTT_PROTECTED)) {
1750 return true;
1751 }
1752 header->length_length = encrypted_reader->PeekVarInt62Length();
1753 if (!encrypted_reader->ReadVarInt62(&header->remaining_packet_length)) {
1754 set_detailed_error("Unable to read long header payload length.");
1755 return RaiseError(QUIC_INVALID_PACKET_HEADER);
1756 }
1757 uint64_t remaining_bytes_length = encrypted_reader->BytesRemaining();
1758 if (header->remaining_packet_length > remaining_bytes_length) {
1759 set_detailed_error("Long header payload length longer than packet.");
1760 return RaiseError(QUIC_INVALID_PACKET_HEADER);
1761 }
1762
1763 MaybeProcessCoalescedPacket(*encrypted_reader, remaining_bytes_length,
1764 *header);
1765
1766 if (!encrypted_reader->TruncateRemaining(header->remaining_packet_length)) {
1767 set_detailed_error("Length TruncateRemaining failed.");
1768 QUIC_BUG << "Length TruncateRemaining failed.";
1769 return RaiseError(QUIC_INVALID_PACKET_HEADER);
1770 }
1771 return true;
1772}
1773
1774bool QuicFramer::ProcessIetfDataPacket(QuicDataReader* encrypted_reader,
1775 QuicPacketHeader* header,
1776 const QuicEncryptedPacket& packet,
1777 char* decrypted_buffer,
1778 size_t buffer_length) {
1779 DCHECK_NE(GOOGLE_QUIC_PACKET, header->form);
1780 DCHECK(!header->has_possible_stateless_reset_token);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001781 header->length_length = VARIABLE_LENGTH_INTEGER_LENGTH_0;
1782 header->remaining_packet_length = 0;
1783 if (header->form == IETF_QUIC_SHORT_HEADER_PACKET &&
1784 perspective_ == Perspective::IS_CLIENT) {
1785 // Peek possible stateless reset token. Will only be used on decryption
1786 // failure.
1787 QuicStringPiece remaining = encrypted_reader->PeekRemainingPayload();
1788 if (remaining.length() >= sizeof(header->possible_stateless_reset_token)) {
1789 header->has_possible_stateless_reset_token = true;
1790 memcpy(&header->possible_stateless_reset_token,
1791 &remaining.data()[remaining.length() -
1792 sizeof(header->possible_stateless_reset_token)],
1793 sizeof(header->possible_stateless_reset_token));
1794 }
1795 }
1796
QUICHE teama6ef0a62019-03-07 20:34:33 -05001797 if (!MaybeProcessIetfLength(encrypted_reader, header)) {
1798 return false;
1799 }
1800
nharper55fa6132019-05-07 19:37:21 -07001801 QuicStringPiece associated_data;
1802 std::vector<char> ad_storage;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001803 if (header->form == IETF_QUIC_SHORT_HEADER_PACKET ||
1804 header->long_packet_type != VERSION_NEGOTIATION) {
dschinazi072da7c2019-05-07 17:57:42 -07001805 DCHECK(header->form == IETF_QUIC_SHORT_HEADER_PACKET ||
1806 header->long_packet_type == INITIAL ||
1807 header->long_packet_type == HANDSHAKE ||
1808 header->long_packet_type == ZERO_RTT_PROTECTED);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001809 // Process packet number.
QUICHE team10b22a12019-03-21 15:31:42 -07001810 QuicPacketNumber base_packet_number;
1811 if (supports_multiple_packet_number_spaces_) {
nharper55fa6132019-05-07 19:37:21 -07001812 PacketNumberSpace pn_space = GetPacketNumberSpace(*header);
1813 if (pn_space == NUM_PACKET_NUMBER_SPACES) {
1814 return RaiseError(QUIC_INVALID_PACKET_HEADER);
1815 }
1816 base_packet_number = largest_decrypted_packet_numbers_[pn_space];
QUICHE team10b22a12019-03-21 15:31:42 -07001817 } else {
1818 base_packet_number = largest_packet_number_;
1819 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001820 uint64_t full_packet_number;
nharper55fa6132019-05-07 19:37:21 -07001821 bool hp_removal_failed = false;
1822 if (version_.HasHeaderProtection()) {
1823 if (!RemoveHeaderProtection(encrypted_reader, packet, header,
1824 &full_packet_number, &ad_storage)) {
1825 hp_removal_failed = true;
1826 }
1827 associated_data = QuicStringPiece(ad_storage.data(), ad_storage.size());
1828 } else if (!ProcessAndCalculatePacketNumber(
1829 encrypted_reader, header->packet_number_length,
1830 base_packet_number, &full_packet_number)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001831 set_detailed_error("Unable to read packet number.");
1832 RecordDroppedPacketReason(DroppedPacketReason::INVALID_PACKET_NUMBER);
1833 return RaiseError(QUIC_INVALID_PACKET_HEADER);
1834 }
1835
nharper55fa6132019-05-07 19:37:21 -07001836 if (hp_removal_failed ||
1837 !IsValidFullPacketNumber(full_packet_number, transport_version())) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001838 if (IsIetfStatelessResetPacket(*header)) {
1839 // This is a stateless reset packet.
1840 QuicIetfStatelessResetPacket packet(
1841 *header, header->possible_stateless_reset_token);
1842 visitor_->OnAuthenticatedIetfStatelessResetPacket(packet);
1843 return true;
1844 }
nharper55fa6132019-05-07 19:37:21 -07001845 if (hp_removal_failed) {
1846 set_detailed_error("Unable to decrypt header protection.");
1847 return RaiseError(QUIC_DECRYPTION_FAILURE);
1848 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001849 RecordDroppedPacketReason(DroppedPacketReason::INVALID_PACKET_NUMBER);
1850 set_detailed_error("packet numbers cannot be 0.");
1851 return RaiseError(QUIC_INVALID_PACKET_HEADER);
1852 }
1853 header->packet_number = QuicPacketNumber(full_packet_number);
1854 }
1855
1856 // A nonce should only present in SHLO from the server to the client when
1857 // using QUIC crypto.
1858 if (header->form == IETF_QUIC_LONG_HEADER_PACKET &&
1859 header->long_packet_type == ZERO_RTT_PROTECTED &&
1860 perspective_ == Perspective::IS_CLIENT &&
1861 version_.handshake_protocol == PROTOCOL_QUIC_CRYPTO) {
1862 if (!encrypted_reader->ReadBytes(
1863 reinterpret_cast<uint8_t*>(last_nonce_.data()),
1864 last_nonce_.size())) {
1865 set_detailed_error("Unable to read nonce.");
1866 RecordDroppedPacketReason(
1867 DroppedPacketReason::INVALID_DIVERSIFICATION_NONCE);
1868 return RaiseError(QUIC_INVALID_PACKET_HEADER);
1869 }
1870
1871 header->nonce = &last_nonce_;
1872 } else {
1873 header->nonce = nullptr;
1874 }
1875
1876 if (!visitor_->OnUnauthenticatedHeader(*header)) {
1877 set_detailed_error(
1878 "Visitor asked to stop processing of unauthenticated header.");
1879 return false;
1880 }
1881
1882 QuicStringPiece encrypted = encrypted_reader->ReadRemainingPayload();
nharper55fa6132019-05-07 19:37:21 -07001883 if (!version_.HasHeaderProtection()) {
1884 associated_data = GetAssociatedDataFromEncryptedPacket(
1885 version_.transport_version, packet,
1886 GetIncludedDestinationConnectionIdLength(*header),
1887 GetIncludedSourceConnectionIdLength(*header), header->version_flag,
1888 header->nonce != nullptr, header->packet_number_length,
1889 header->retry_token_length_length, header->retry_token.length(),
1890 header->length_length);
1891 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001892
1893 size_t decrypted_length = 0;
QUICHE team10b22a12019-03-21 15:31:42 -07001894 EncryptionLevel decrypted_level;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001895 if (!DecryptPayload(encrypted, associated_data, *header, decrypted_buffer,
QUICHE team10b22a12019-03-21 15:31:42 -07001896 buffer_length, &decrypted_length, &decrypted_level)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001897 if (IsIetfStatelessResetPacket(*header)) {
1898 // This is a stateless reset packet.
1899 QuicIetfStatelessResetPacket packet(
1900 *header, header->possible_stateless_reset_token);
1901 visitor_->OnAuthenticatedIetfStatelessResetPacket(packet);
1902 return true;
1903 }
1904 set_detailed_error("Unable to decrypt payload.");
1905 RecordDroppedPacketReason(DroppedPacketReason::DECRYPTION_FAILURE);
1906 return RaiseError(QUIC_DECRYPTION_FAILURE);
1907 }
1908 QuicDataReader reader(decrypted_buffer, decrypted_length);
1909
1910 // Update the largest packet number after we have decrypted the packet
1911 // so we are confident is not attacker controlled.
QUICHE team10b22a12019-03-21 15:31:42 -07001912 if (supports_multiple_packet_number_spaces_) {
1913 largest_decrypted_packet_numbers_[QuicUtils::GetPacketNumberSpace(
1914 decrypted_level)]
1915 .UpdateMax(header->packet_number);
1916 } else {
1917 largest_packet_number_.UpdateMax(header->packet_number);
1918 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001919
1920 if (!visitor_->OnPacketHeader(*header)) {
1921 RecordDroppedPacketReason(DroppedPacketReason::INVALID_PACKET_NUMBER);
1922 // The visitor suppresses further processing of the packet.
1923 return true;
1924 }
1925
dschinazie8d7fa72019-04-05 14:44:40 -07001926 if (packet.length() > kMaxIncomingPacketSize) {
1927 set_detailed_error("Packet too large.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05001928 return RaiseError(QUIC_PACKET_TOO_LARGE);
1929 }
1930
1931 // Handle the payload.
fkastenholz305e1732019-06-18 05:01:22 -07001932 if (VersionHasIetfQuicFrames(version_.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001933 if (!ProcessIetfFrameData(&reader, *header)) {
1934 DCHECK_NE(QUIC_NO_ERROR, error_); // ProcessIetfFrameData sets the error.
1935 DCHECK_NE("", detailed_error_);
1936 QUIC_DLOG(WARNING) << ENDPOINT << "Unable to process frame data. Error: "
1937 << detailed_error_;
1938 return false;
1939 }
1940 } else {
1941 if (!ProcessFrameData(&reader, *header)) {
1942 DCHECK_NE(QUIC_NO_ERROR, error_); // ProcessFrameData sets the error.
1943 DCHECK_NE("", detailed_error_);
1944 QUIC_DLOG(WARNING) << ENDPOINT << "Unable to process frame data. Error: "
1945 << detailed_error_;
1946 return false;
1947 }
1948 }
1949
1950 visitor_->OnPacketComplete();
1951 return true;
1952}
1953
1954bool QuicFramer::ProcessDataPacket(QuicDataReader* encrypted_reader,
1955 QuicPacketHeader* header,
1956 const QuicEncryptedPacket& packet,
1957 char* decrypted_buffer,
1958 size_t buffer_length) {
1959 if (!ProcessUnauthenticatedHeader(encrypted_reader, header)) {
1960 DCHECK_NE("", detailed_error_);
1961 QUIC_DVLOG(1)
1962 << ENDPOINT
1963 << "Unable to process packet header. Stopping parsing. Error: "
1964 << detailed_error_;
1965 RecordDroppedPacketReason(DroppedPacketReason::INVALID_PACKET_NUMBER);
1966 return false;
1967 }
1968
1969 QuicStringPiece encrypted = encrypted_reader->ReadRemainingPayload();
1970 QuicStringPiece associated_data = GetAssociatedDataFromEncryptedPacket(
1971 version_.transport_version, packet,
1972 GetIncludedDestinationConnectionIdLength(*header),
1973 GetIncludedSourceConnectionIdLength(*header), header->version_flag,
1974 header->nonce != nullptr, header->packet_number_length,
1975 header->retry_token_length_length, header->retry_token.length(),
1976 header->length_length);
1977
1978 size_t decrypted_length = 0;
QUICHE team10b22a12019-03-21 15:31:42 -07001979 EncryptionLevel decrypted_level;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001980 if (!DecryptPayload(encrypted, associated_data, *header, decrypted_buffer,
QUICHE team10b22a12019-03-21 15:31:42 -07001981 buffer_length, &decrypted_length, &decrypted_level)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001982 RecordDroppedPacketReason(DroppedPacketReason::DECRYPTION_FAILURE);
1983 set_detailed_error("Unable to decrypt payload.");
1984 return RaiseError(QUIC_DECRYPTION_FAILURE);
1985 }
1986
1987 QuicDataReader reader(decrypted_buffer, decrypted_length);
1988
1989 // Update the largest packet number after we have decrypted the packet
1990 // so we are confident is not attacker controlled.
QUICHE team10b22a12019-03-21 15:31:42 -07001991 if (supports_multiple_packet_number_spaces_) {
1992 largest_decrypted_packet_numbers_[QuicUtils::GetPacketNumberSpace(
1993 decrypted_level)]
1994 .UpdateMax(header->packet_number);
1995 } else {
1996 largest_packet_number_.UpdateMax(header->packet_number);
1997 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001998
1999 if (!visitor_->OnPacketHeader(*header)) {
2000 // The visitor suppresses further processing of the packet.
2001 return true;
2002 }
2003
dschinazie8d7fa72019-04-05 14:44:40 -07002004 if (packet.length() > kMaxIncomingPacketSize) {
2005 set_detailed_error("Packet too large.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05002006 return RaiseError(QUIC_PACKET_TOO_LARGE);
2007 }
2008
2009 // Handle the payload.
2010 if (!ProcessFrameData(&reader, *header)) {
2011 DCHECK_NE(QUIC_NO_ERROR, error_); // ProcessFrameData sets the error.
2012 DCHECK_NE("", detailed_error_);
2013 QUIC_DLOG(WARNING) << ENDPOINT << "Unable to process frame data. Error: "
2014 << detailed_error_;
2015 return false;
2016 }
2017
2018 visitor_->OnPacketComplete();
2019 return true;
2020}
2021
2022bool QuicFramer::ProcessPublicResetPacket(QuicDataReader* reader,
2023 const QuicPacketHeader& header) {
QUICHE team2252b702019-05-14 23:55:14 -04002024 QuicPublicResetPacket packet(
2025 GetServerConnectionIdAsRecipient(header, perspective_));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002026
2027 std::unique_ptr<CryptoHandshakeMessage> reset(
2028 CryptoFramer::ParseMessage(reader->ReadRemainingPayload()));
2029 if (!reset.get()) {
2030 set_detailed_error("Unable to read reset message.");
2031 RecordDroppedPacketReason(DroppedPacketReason::INVALID_PUBLIC_RESET_PACKET);
2032 return RaiseError(QUIC_INVALID_PUBLIC_RST_PACKET);
2033 }
2034 if (reset->tag() != kPRST) {
2035 set_detailed_error("Incorrect message tag.");
2036 RecordDroppedPacketReason(DroppedPacketReason::INVALID_PUBLIC_RESET_PACKET);
2037 return RaiseError(QUIC_INVALID_PUBLIC_RST_PACKET);
2038 }
2039
2040 if (reset->GetUint64(kRNON, &packet.nonce_proof) != QUIC_NO_ERROR) {
2041 set_detailed_error("Unable to read nonce proof.");
2042 RecordDroppedPacketReason(DroppedPacketReason::INVALID_PUBLIC_RESET_PACKET);
2043 return RaiseError(QUIC_INVALID_PUBLIC_RST_PACKET);
2044 }
2045 // TODO(satyamshekhar): validate nonce to protect against DoS.
2046
2047 QuicStringPiece address;
2048 if (reset->GetStringPiece(kCADR, &address)) {
2049 QuicSocketAddressCoder address_coder;
2050 if (address_coder.Decode(address.data(), address.length())) {
2051 packet.client_address =
2052 QuicSocketAddress(address_coder.ip(), address_coder.port());
2053 }
2054 }
2055
2056 QuicStringPiece endpoint_id;
2057 if (perspective_ == Perspective::IS_CLIENT &&
2058 reset->GetStringPiece(kEPID, &endpoint_id)) {
vasilvvc48c8712019-03-11 13:38:16 -07002059 packet.endpoint_id = std::string(endpoint_id);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002060 packet.endpoint_id += '\0';
2061 }
2062
2063 visitor_->OnPublicResetPacket(packet);
2064 return true;
2065}
2066
2067bool QuicFramer::IsIetfStatelessResetPacket(
2068 const QuicPacketHeader& header) const {
2069 QUIC_BUG_IF(header.has_possible_stateless_reset_token &&
2070 perspective_ != Perspective::IS_CLIENT)
2071 << "has_possible_stateless_reset_token can only be true at client side.";
2072 return header.form == IETF_QUIC_SHORT_HEADER_PACKET &&
2073 header.has_possible_stateless_reset_token &&
2074 visitor_->IsValidStatelessResetToken(
2075 header.possible_stateless_reset_token);
2076}
2077
2078bool QuicFramer::HasEncrypterOfEncryptionLevel(EncryptionLevel level) const {
2079 return encrypter_[level] != nullptr;
2080}
2081
2082bool QuicFramer::AppendPacketHeader(const QuicPacketHeader& header,
2083 QuicDataWriter* writer,
2084 size_t* length_field_offset) {
fayangd4291e42019-05-30 10:31:21 -07002085 if (VersionHasIetfInvariantHeader(transport_version())) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002086 return AppendIetfPacketHeader(header, writer, length_field_offset);
2087 }
2088 QUIC_DVLOG(1) << ENDPOINT << "Appending header: " << header;
2089 uint8_t public_flags = 0;
2090 if (header.reset_flag) {
2091 public_flags |= PACKET_PUBLIC_FLAGS_RST;
2092 }
2093 if (header.version_flag) {
2094 public_flags |= PACKET_PUBLIC_FLAGS_VERSION;
2095 }
2096
2097 public_flags |= GetPacketNumberFlags(header.packet_number_length)
2098 << kPublicHeaderSequenceNumberShift;
2099
2100 if (header.nonce != nullptr) {
2101 DCHECK_EQ(Perspective::IS_SERVER, perspective_);
2102 public_flags |= PACKET_PUBLIC_FLAGS_NONCE;
2103 }
QUICHE team2252b702019-05-14 23:55:14 -04002104
dschinazi7b9278c2019-05-20 07:36:21 -07002105 QuicConnectionId server_connection_id =
QUICHE team2252b702019-05-14 23:55:14 -04002106 GetServerConnectionIdAsSender(header, perspective_);
dschinazi7b9278c2019-05-20 07:36:21 -07002107 QuicConnectionIdIncluded server_connection_id_included =
QUICHE team2252b702019-05-14 23:55:14 -04002108 GetServerConnectionIdIncludedAsSender(header, perspective_);
2109 DCHECK_EQ(CONNECTION_ID_ABSENT,
dschinazic075ffa2019-06-27 16:17:37 -07002110 GetClientConnectionIdIncludedAsSender(header, perspective_))
2111 << ENDPOINT << ParsedQuicVersionToString(version_)
2112 << " invalid header: " << header;
QUICHE team2252b702019-05-14 23:55:14 -04002113
dschinazi7b9278c2019-05-20 07:36:21 -07002114 switch (server_connection_id_included) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002115 case CONNECTION_ID_ABSENT:
2116 if (!writer->WriteUInt8(public_flags |
2117 PACKET_PUBLIC_FLAGS_0BYTE_CONNECTION_ID)) {
2118 return false;
2119 }
2120 break;
2121 case CONNECTION_ID_PRESENT:
2122 QUIC_BUG_IF(!QuicUtils::IsConnectionIdValidForVersion(
dschinazi7b9278c2019-05-20 07:36:21 -07002123 server_connection_id, transport_version()))
QUICHE teama6ef0a62019-03-07 20:34:33 -05002124 << "AppendPacketHeader: attempted to use connection ID "
dschinazi7b9278c2019-05-20 07:36:21 -07002125 << server_connection_id << " which is invalid with version "
QUICHE teama6ef0a62019-03-07 20:34:33 -05002126 << QuicVersionToString(transport_version());
2127
2128 public_flags |= PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID;
2129 if (perspective_ == Perspective::IS_CLIENT) {
2130 public_flags |= PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID_OLD;
2131 }
2132 if (!writer->WriteUInt8(public_flags) ||
dschinazi7b9278c2019-05-20 07:36:21 -07002133 !writer->WriteConnectionId(server_connection_id)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002134 return false;
2135 }
2136 break;
2137 }
dschinazi7b9278c2019-05-20 07:36:21 -07002138 last_serialized_server_connection_id_ = server_connection_id;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002139
2140 if (header.version_flag) {
2141 DCHECK_EQ(Perspective::IS_CLIENT, perspective_);
2142 QuicVersionLabel version_label = CreateQuicVersionLabel(version_);
nharpereaab5ad2019-05-31 12:23:25 -07002143 if (!writer->WriteUInt32(version_label)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002144 return false;
2145 }
2146
2147 QUIC_DVLOG(1) << ENDPOINT << "label = '"
2148 << QuicVersionLabelToString(version_label) << "'";
2149 }
2150
2151 if (header.nonce != nullptr &&
2152 !writer->WriteBytes(header.nonce, kDiversificationNonceSize)) {
2153 return false;
2154 }
2155
2156 if (!AppendPacketNumber(header.packet_number_length, header.packet_number,
2157 writer)) {
2158 return false;
2159 }
2160
2161 return true;
2162}
2163
2164bool QuicFramer::AppendIetfHeaderTypeByte(const QuicPacketHeader& header,
2165 QuicDataWriter* writer) {
2166 uint8_t type = 0;
fayangf36e29d2019-06-06 14:03:40 -07002167 if (transport_version() > QUIC_VERSION_44) {
2168 if (header.version_flag) {
2169 type = static_cast<uint8_t>(
2170 FLAGS_LONG_HEADER | FLAGS_FIXED_BIT |
2171 LongHeaderTypeToOnWireValue(transport_version(),
2172 header.long_packet_type) |
2173 PacketNumberLengthToOnWireValue(transport_version(),
2174 header.packet_number_length));
2175 } else {
2176 type = static_cast<uint8_t>(
2177 FLAGS_FIXED_BIT |
2178 PacketNumberLengthToOnWireValue(transport_version(),
2179 header.packet_number_length));
2180 }
2181 return writer->WriteUInt8(type);
2182 }
2183
QUICHE teama6ef0a62019-03-07 20:34:33 -05002184 if (header.version_flag) {
2185 type = static_cast<uint8_t>(
fayangf36e29d2019-06-06 14:03:40 -07002186 FLAGS_LONG_HEADER | LongHeaderTypeToOnWireValue(
2187 transport_version(), header.long_packet_type));
2188 DCHECK_EQ(PACKET_4BYTE_PACKET_NUMBER, header.packet_number_length);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002189 } else {
fayangf36e29d2019-06-06 14:03:40 -07002190 type |= FLAGS_SHORT_HEADER_RESERVED_1;
2191 type |= FLAGS_SHORT_HEADER_RESERVED_2;
2192 DCHECK_GE(PACKET_4BYTE_PACKET_NUMBER, header.packet_number_length);
2193 type |= PacketNumberLengthToOnWireValue(transport_version(),
2194 header.packet_number_length);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002195 }
2196 return writer->WriteUInt8(type);
2197}
2198
2199bool QuicFramer::AppendIetfPacketHeader(const QuicPacketHeader& header,
2200 QuicDataWriter* writer,
2201 size_t* length_field_offset) {
2202 QUIC_DVLOG(1) << ENDPOINT << "Appending IETF header: " << header;
QUICHE team2252b702019-05-14 23:55:14 -04002203 QuicConnectionId server_connection_id =
2204 GetServerConnectionIdAsSender(header, perspective_);
2205 QUIC_BUG_IF(!QuicUtils::IsConnectionIdValidForVersion(server_connection_id,
2206 transport_version()))
QUICHE teama6ef0a62019-03-07 20:34:33 -05002207 << "AppendIetfPacketHeader: attempted to use connection ID "
QUICHE team2252b702019-05-14 23:55:14 -04002208 << server_connection_id << " which is invalid with version "
QUICHE teama6ef0a62019-03-07 20:34:33 -05002209 << QuicVersionToString(transport_version());
2210 if (!AppendIetfHeaderTypeByte(header, writer)) {
2211 return false;
2212 }
2213
2214 if (header.version_flag) {
2215 // Append version for long header.
2216 QuicVersionLabel version_label = CreateQuicVersionLabel(version_);
nharpereaab5ad2019-05-31 12:23:25 -07002217 if (!writer->WriteUInt32(version_label)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002218 return false;
2219 }
2220 }
2221
2222 // Append connection ID.
dschinazi1f485a12019-05-13 11:57:01 -07002223 if (!AppendIetfConnectionIds(
dschinazi48ac9192019-07-31 00:07:26 -07002224 header.version_flag, version_.HasLengthPrefixedConnectionIds(),
dschinazi1f485a12019-05-13 11:57:01 -07002225 header.destination_connection_id_included != CONNECTION_ID_ABSENT
2226 ? header.destination_connection_id
2227 : EmptyQuicConnectionId(),
2228 header.source_connection_id_included != CONNECTION_ID_ABSENT
2229 ? header.source_connection_id
2230 : EmptyQuicConnectionId(),
2231 writer)) {
2232 return false;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002233 }
dschinazi1f485a12019-05-13 11:57:01 -07002234
dschinazi7b9278c2019-05-20 07:36:21 -07002235 last_serialized_server_connection_id_ = server_connection_id;
dschinazi346b7ce2019-06-05 01:38:18 -07002236 if (version_.SupportsClientConnectionIds()) {
2237 last_serialized_client_connection_id_ =
2238 GetClientConnectionIdAsSender(header, perspective_);
2239 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002240
2241 if (QuicVersionHasLongHeaderLengths(transport_version()) &&
2242 header.version_flag) {
2243 if (header.long_packet_type == INITIAL) {
dschinazic075ffa2019-06-27 16:17:37 -07002244 DCHECK_NE(VARIABLE_LENGTH_INTEGER_LENGTH_0,
2245 header.retry_token_length_length)
2246 << ENDPOINT << ParsedQuicVersionToString(version_)
2247 << " bad retry token length length in header: " << header;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002248 // Write retry token length.
2249 if (!writer->WriteVarInt62(header.retry_token.length(),
2250 header.retry_token_length_length)) {
2251 return false;
2252 }
2253 // Write retry token.
2254 if (!header.retry_token.empty() &&
2255 !writer->WriteStringPiece(header.retry_token)) {
2256 return false;
2257 }
2258 }
2259 if (length_field_offset != nullptr) {
2260 *length_field_offset = writer->length();
2261 }
2262 // Add fake length to reserve two bytes to add length in later.
2263 writer->WriteVarInt62(256);
2264 } else if (length_field_offset != nullptr) {
2265 *length_field_offset = 0;
2266 }
2267
2268 // Append packet number.
2269 if (!AppendPacketNumber(header.packet_number_length, header.packet_number,
2270 writer)) {
2271 return false;
2272 }
nharper55fa6132019-05-07 19:37:21 -07002273 last_written_packet_number_length_ = header.packet_number_length;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002274
2275 if (!header.version_flag) {
2276 return true;
2277 }
2278
2279 if (header.nonce != nullptr) {
2280 DCHECK(header.version_flag);
2281 DCHECK_EQ(ZERO_RTT_PROTECTED, header.long_packet_type);
2282 DCHECK_EQ(Perspective::IS_SERVER, perspective_);
2283 if (!writer->WriteBytes(header.nonce, kDiversificationNonceSize)) {
2284 return false;
2285 }
2286 }
2287
2288 return true;
2289}
2290
2291const QuicTime::Delta QuicFramer::CalculateTimestampFromWire(
2292 uint32_t time_delta_us) {
2293 // The new time_delta might have wrapped to the next epoch, or it
2294 // might have reverse wrapped to the previous epoch, or it might
2295 // remain in the same epoch. Select the time closest to the previous
2296 // time.
2297 //
2298 // epoch_delta is the delta between epochs. A delta is 4 bytes of
2299 // microseconds.
2300 const uint64_t epoch_delta = UINT64_C(1) << 32;
2301 uint64_t epoch = last_timestamp_.ToMicroseconds() & ~(epoch_delta - 1);
2302 // Wrapping is safe here because a wrapped value will not be ClosestTo below.
2303 uint64_t prev_epoch = epoch - epoch_delta;
2304 uint64_t next_epoch = epoch + epoch_delta;
2305
2306 uint64_t time = ClosestTo(
2307 last_timestamp_.ToMicroseconds(), epoch + time_delta_us,
2308 ClosestTo(last_timestamp_.ToMicroseconds(), prev_epoch + time_delta_us,
2309 next_epoch + time_delta_us));
2310
2311 return QuicTime::Delta::FromMicroseconds(time);
2312}
2313
2314uint64_t QuicFramer::CalculatePacketNumberFromWire(
2315 QuicPacketNumberLength packet_number_length,
2316 QuicPacketNumber base_packet_number,
2317 uint64_t packet_number) const {
2318 // The new packet number might have wrapped to the next epoch, or
2319 // it might have reverse wrapped to the previous epoch, or it might
2320 // remain in the same epoch. Select the packet number closest to the
2321 // next expected packet number, the previous packet number plus 1.
2322
2323 // epoch_delta is the delta between epochs the packet number was serialized
2324 // with, so the correct value is likely the same epoch as the last sequence
2325 // number or an adjacent epoch.
2326 if (!base_packet_number.IsInitialized()) {
2327 return packet_number;
2328 }
2329 const uint64_t epoch_delta = UINT64_C(1) << (8 * packet_number_length);
2330 uint64_t next_packet_number = base_packet_number.ToUint64() + 1;
2331 uint64_t epoch = base_packet_number.ToUint64() & ~(epoch_delta - 1);
2332 uint64_t prev_epoch = epoch - epoch_delta;
2333 uint64_t next_epoch = epoch + epoch_delta;
2334
2335 return ClosestTo(next_packet_number, epoch + packet_number,
2336 ClosestTo(next_packet_number, prev_epoch + packet_number,
2337 next_epoch + packet_number));
2338}
2339
2340bool QuicFramer::ProcessPublicHeader(QuicDataReader* reader,
2341 bool packet_has_ietf_packet_header,
2342 QuicPacketHeader* header) {
2343 if (packet_has_ietf_packet_header) {
2344 return ProcessIetfPacketHeader(reader, header);
2345 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002346 uint8_t public_flags;
2347 if (!reader->ReadBytes(&public_flags, 1)) {
2348 set_detailed_error("Unable to read public flags.");
2349 return false;
2350 }
2351
2352 header->reset_flag = (public_flags & PACKET_PUBLIC_FLAGS_RST) != 0;
2353 header->version_flag = (public_flags & PACKET_PUBLIC_FLAGS_VERSION) != 0;
2354
2355 if (validate_flags_ && !header->version_flag &&
2356 public_flags > PACKET_PUBLIC_FLAGS_MAX) {
2357 set_detailed_error("Illegal public flags value.");
2358 return false;
2359 }
2360
2361 if (header->reset_flag && header->version_flag) {
2362 set_detailed_error("Got version flag in reset packet");
2363 return false;
2364 }
2365
QUICHE team2252b702019-05-14 23:55:14 -04002366 QuicConnectionId* header_connection_id = &header->destination_connection_id;
2367 QuicConnectionIdIncluded* header_connection_id_included =
2368 &header->destination_connection_id_included;
dschinazi5e1a7b22019-07-31 12:23:21 -07002369 if (perspective_ == Perspective::IS_CLIENT) {
QUICHE team2252b702019-05-14 23:55:14 -04002370 header_connection_id = &header->source_connection_id;
2371 header_connection_id_included = &header->source_connection_id_included;
2372 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002373 switch (public_flags & PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID) {
2374 case PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID:
QUICHE team2252b702019-05-14 23:55:14 -04002375 if (!reader->ReadConnectionId(header_connection_id,
QUICHE teama6ef0a62019-03-07 20:34:33 -05002376 kQuicDefaultConnectionIdLength)) {
2377 set_detailed_error("Unable to read ConnectionId.");
2378 return false;
2379 }
QUICHE team2252b702019-05-14 23:55:14 -04002380 *header_connection_id_included = CONNECTION_ID_PRESENT;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002381 break;
2382 case PACKET_PUBLIC_FLAGS_0BYTE_CONNECTION_ID:
QUICHE team2252b702019-05-14 23:55:14 -04002383 *header_connection_id_included = CONNECTION_ID_ABSENT;
dschinazi7b9278c2019-05-20 07:36:21 -07002384 *header_connection_id = last_serialized_server_connection_id_;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002385 break;
2386 }
2387
2388 header->packet_number_length = ReadSequenceNumberLength(
2389 public_flags >> kPublicHeaderSequenceNumberShift);
2390
2391 // Read the version only if the packet is from the client.
2392 // version flag from the server means version negotiation packet.
2393 if (header->version_flag && perspective_ == Perspective::IS_SERVER) {
2394 QuicVersionLabel version_label;
fayang40315542019-05-09 09:19:09 -07002395 if (!ProcessVersionLabel(reader, &version_label)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002396 set_detailed_error("Unable to read protocol version.");
2397 return false;
2398 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002399 // If the version from the new packet is the same as the version of this
2400 // framer, then the public flags should be set to something we understand.
2401 // If not, this raises an error.
QUICHE teama6ef0a62019-03-07 20:34:33 -05002402 ParsedQuicVersion version = ParseQuicVersionLabel(version_label);
2403 if (version == version_ && public_flags > PACKET_PUBLIC_FLAGS_MAX) {
2404 set_detailed_error("Illegal public flags value.");
2405 return false;
2406 }
2407 header->version = version;
2408 }
2409
2410 // A nonce should only be present in packets from the server to the client,
2411 // which are neither version negotiation nor public reset packets.
2412 if (public_flags & PACKET_PUBLIC_FLAGS_NONCE &&
2413 !(public_flags & PACKET_PUBLIC_FLAGS_VERSION) &&
2414 !(public_flags & PACKET_PUBLIC_FLAGS_RST) &&
2415 // The nonce flag from a client is ignored and is assumed to be an older
2416 // client indicating an eight-byte connection ID.
2417 perspective_ == Perspective::IS_CLIENT) {
2418 if (!reader->ReadBytes(reinterpret_cast<uint8_t*>(last_nonce_.data()),
2419 last_nonce_.size())) {
2420 set_detailed_error("Unable to read nonce.");
2421 return false;
2422 }
2423 header->nonce = &last_nonce_;
2424 } else {
2425 header->nonce = nullptr;
2426 }
2427
2428 return true;
2429}
2430
2431// static
2432QuicPacketNumberLength QuicFramer::GetMinPacketNumberLength(
dschinazi17d42422019-06-18 16:35:07 -07002433 QuicTransportVersion /*version*/,
QUICHE teama6ef0a62019-03-07 20:34:33 -05002434 QuicPacketNumber packet_number) {
2435 DCHECK(packet_number.IsInitialized());
2436 if (packet_number < QuicPacketNumber(1 << (PACKET_1BYTE_PACKET_NUMBER * 8))) {
2437 return PACKET_1BYTE_PACKET_NUMBER;
2438 } else if (packet_number <
2439 QuicPacketNumber(1 << (PACKET_2BYTE_PACKET_NUMBER * 8))) {
2440 return PACKET_2BYTE_PACKET_NUMBER;
2441 } else if (packet_number <
2442 QuicPacketNumber(UINT64_C(1)
2443 << (PACKET_4BYTE_PACKET_NUMBER * 8))) {
2444 return PACKET_4BYTE_PACKET_NUMBER;
2445 } else {
2446 return PACKET_6BYTE_PACKET_NUMBER;
2447 }
2448}
2449
2450// static
2451uint8_t QuicFramer::GetPacketNumberFlags(
2452 QuicPacketNumberLength packet_number_length) {
2453 switch (packet_number_length) {
2454 case PACKET_1BYTE_PACKET_NUMBER:
2455 return PACKET_FLAGS_1BYTE_PACKET;
2456 case PACKET_2BYTE_PACKET_NUMBER:
2457 return PACKET_FLAGS_2BYTE_PACKET;
2458 case PACKET_4BYTE_PACKET_NUMBER:
2459 return PACKET_FLAGS_4BYTE_PACKET;
2460 case PACKET_6BYTE_PACKET_NUMBER:
2461 case PACKET_8BYTE_PACKET_NUMBER:
2462 return PACKET_FLAGS_8BYTE_PACKET;
2463 default:
2464 QUIC_BUG << "Unreachable case statement.";
2465 return PACKET_FLAGS_8BYTE_PACKET;
2466 }
2467}
2468
2469// static
2470QuicFramer::AckFrameInfo QuicFramer::GetAckFrameInfo(
2471 const QuicAckFrame& frame) {
2472 AckFrameInfo new_ack_info;
2473 if (frame.packets.Empty()) {
2474 return new_ack_info;
2475 }
2476 // The first block is the last interval. It isn't encoded with the gap-length
2477 // encoding, so skip it.
2478 new_ack_info.first_block_length = frame.packets.LastIntervalLength();
2479 auto itr = frame.packets.rbegin();
2480 QuicPacketNumber previous_start = itr->min();
2481 new_ack_info.max_block_length = PacketNumberIntervalLength(*itr);
2482 ++itr;
2483
2484 // Don't do any more work after getting information for 256 ACK blocks; any
2485 // more can't be encoded anyway.
2486 for (; itr != frame.packets.rend() &&
2487 new_ack_info.num_ack_blocks < std::numeric_limits<uint8_t>::max();
2488 previous_start = itr->min(), ++itr) {
2489 const auto& interval = *itr;
2490 const QuicPacketCount total_gap = previous_start - interval.max();
2491 new_ack_info.num_ack_blocks +=
2492 (total_gap + std::numeric_limits<uint8_t>::max() - 1) /
2493 std::numeric_limits<uint8_t>::max();
2494 new_ack_info.max_block_length = std::max(
2495 new_ack_info.max_block_length, PacketNumberIntervalLength(interval));
2496 }
2497 return new_ack_info;
2498}
2499
2500bool QuicFramer::ProcessUnauthenticatedHeader(QuicDataReader* encrypted_reader,
2501 QuicPacketHeader* header) {
QUICHE team10b22a12019-03-21 15:31:42 -07002502 QuicPacketNumber base_packet_number;
2503 if (supports_multiple_packet_number_spaces_) {
nharper55fa6132019-05-07 19:37:21 -07002504 PacketNumberSpace pn_space = GetPacketNumberSpace(*header);
2505 if (pn_space == NUM_PACKET_NUMBER_SPACES) {
2506 set_detailed_error("Unable to determine packet number space.");
2507 return RaiseError(QUIC_INVALID_PACKET_HEADER);
2508 }
2509 base_packet_number = largest_decrypted_packet_numbers_[pn_space];
QUICHE team10b22a12019-03-21 15:31:42 -07002510 } else {
2511 base_packet_number = largest_packet_number_;
2512 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002513 uint64_t full_packet_number;
2514 if (!ProcessAndCalculatePacketNumber(
2515 encrypted_reader, header->packet_number_length, base_packet_number,
2516 &full_packet_number)) {
2517 set_detailed_error("Unable to read packet number.");
2518 return RaiseError(QUIC_INVALID_PACKET_HEADER);
2519 }
2520
2521 if (!IsValidFullPacketNumber(full_packet_number, transport_version())) {
2522 set_detailed_error("packet numbers cannot be 0.");
2523 return RaiseError(QUIC_INVALID_PACKET_HEADER);
2524 }
2525 header->packet_number = QuicPacketNumber(full_packet_number);
2526
2527 if (!visitor_->OnUnauthenticatedHeader(*header)) {
2528 set_detailed_error(
2529 "Visitor asked to stop processing of unauthenticated header.");
2530 return false;
2531 }
nharper3f283562019-05-02 16:37:12 -07002532 // The function we are in is called because the framer believes that it is
2533 // processing a packet that uses the non-IETF (i.e. Google QUIC) packet header
2534 // type. Usually, the framer makes that decision based on the framer's
2535 // version, but when the framer is used with Perspective::IS_SERVER, then
2536 // before version negotiation is complete (specifically, before
2537 // InferPacketHeaderTypeFromVersion is called), this decision is made based on
2538 // the type byte of the packet.
2539 //
2540 // If the framer's version KnowsWhichDecrypterToUse, then that version expects
2541 // to use the IETF packet header type. If that's the case and we're in this
2542 // function, then the packet received is invalid: the framer was expecting an
2543 // IETF packet header and didn't get one.
2544 if (version().KnowsWhichDecrypterToUse()) {
nharpera745e392019-04-19 12:05:15 -07002545 set_detailed_error("Invalid public header type for expected version.");
2546 return RaiseError(QUIC_INVALID_PACKET_HEADER);
2547 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002548 return true;
2549}
2550
2551bool QuicFramer::ProcessIetfHeaderTypeByte(QuicDataReader* reader,
2552 QuicPacketHeader* header) {
2553 uint8_t type;
2554 if (!reader->ReadBytes(&type, 1)) {
dschinazi48ac9192019-07-31 00:07:26 -07002555 set_detailed_error("Unable to read first byte.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05002556 return false;
2557 }
dschinazi244f6dc2019-05-06 15:45:16 -07002558 header->type_byte = type;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002559 // Determine whether this is a long or short header.
fayangccbab732019-05-13 10:11:25 -07002560 header->form = GetIetfPacketHeaderFormat(type);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002561 if (header->form == IETF_QUIC_LONG_HEADER_PACKET) {
2562 // Version is always present in long headers.
2563 header->version_flag = true;
dschinazi346b7ce2019-06-05 01:38:18 -07002564 // In versions that do not support client connection IDs, we mark the
2565 // corresponding connection ID as absent.
QUICHE teama6ef0a62019-03-07 20:34:33 -05002566 header->destination_connection_id_included =
dschinazi346b7ce2019-06-05 01:38:18 -07002567 (perspective_ == Perspective::IS_SERVER ||
2568 version_.SupportsClientConnectionIds())
2569 ? CONNECTION_ID_PRESENT
2570 : CONNECTION_ID_ABSENT;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002571 header->source_connection_id_included =
dschinazi346b7ce2019-06-05 01:38:18 -07002572 (perspective_ == Perspective::IS_CLIENT ||
2573 version_.SupportsClientConnectionIds())
2574 ? CONNECTION_ID_PRESENT
2575 : CONNECTION_ID_ABSENT;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002576 // Read version tag.
2577 QuicVersionLabel version_label;
fayang40315542019-05-09 09:19:09 -07002578 if (!ProcessVersionLabel(reader, &version_label)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002579 set_detailed_error("Unable to read protocol version.");
2580 return false;
2581 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002582 if (!version_label) {
2583 // Version label is 0 indicating this is a version negotiation packet.
2584 header->long_packet_type = VERSION_NEGOTIATION;
2585 } else {
2586 header->version = ParseQuicVersionLabel(version_label);
2587 if (header->version.transport_version != QUIC_VERSION_UNSUPPORTED) {
fayangf36e29d2019-06-06 14:03:40 -07002588 if (header->version.transport_version > QUIC_VERSION_44 &&
QUICHE teama6ef0a62019-03-07 20:34:33 -05002589 !(type & FLAGS_FIXED_BIT)) {
2590 set_detailed_error("Fixed bit is 0 in long header.");
2591 return false;
2592 }
2593 if (!GetLongHeaderType(header->version.transport_version, type,
2594 &header->long_packet_type)) {
2595 set_detailed_error("Illegal long header type value.");
2596 return false;
2597 }
dschinazi244f6dc2019-05-06 15:45:16 -07002598 if (header->long_packet_type == RETRY) {
2599 if (!version().SupportsRetry()) {
2600 set_detailed_error("RETRY not supported in this version.");
2601 return false;
2602 }
2603 if (perspective_ == Perspective::IS_SERVER) {
2604 set_detailed_error("Client-initiated RETRY is invalid.");
2605 return false;
2606 }
nharper55fa6132019-05-07 19:37:21 -07002607 } else if (!header->version.HasHeaderProtection()) {
dschinazi244f6dc2019-05-06 15:45:16 -07002608 header->packet_number_length = GetLongHeaderPacketNumberLength(
2609 header->version.transport_version, type);
nharper2ceb97c2019-04-19 11:38:59 -07002610 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002611 }
2612 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002613
2614 QUIC_DVLOG(1) << ENDPOINT << "Received IETF long header: "
2615 << QuicUtils::QuicLongHeaderTypetoString(
2616 header->long_packet_type);
2617 return true;
2618 }
2619
2620 QUIC_DVLOG(1) << ENDPOINT << "Received IETF short header";
2621 // Version is not present in short headers.
2622 header->version_flag = false;
dschinazi346b7ce2019-06-05 01:38:18 -07002623 // In versions that do not support client connection IDs, the client will not
2624 // receive destination connection IDs.
QUICHE teama6ef0a62019-03-07 20:34:33 -05002625 header->destination_connection_id_included =
dschinazi346b7ce2019-06-05 01:38:18 -07002626 (perspective_ == Perspective::IS_SERVER ||
2627 version_.SupportsClientConnectionIds())
2628 ? CONNECTION_ID_PRESENT
2629 : CONNECTION_ID_ABSENT;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002630 header->source_connection_id_included = CONNECTION_ID_ABSENT;
fayangf36e29d2019-06-06 14:03:40 -07002631 if (infer_packet_header_type_from_version_ &&
2632 transport_version() > QUIC_VERSION_44 && !(type & FLAGS_FIXED_BIT)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002633 set_detailed_error("Fixed bit is 0 in short header.");
2634 return false;
2635 }
nharper55fa6132019-05-07 19:37:21 -07002636 if (!header->version.HasHeaderProtection() &&
2637 !GetShortHeaderPacketNumberLength(transport_version(), type,
QUICHE teama6ef0a62019-03-07 20:34:33 -05002638 infer_packet_header_type_from_version_,
2639 &header->packet_number_length)) {
2640 set_detailed_error("Illegal short header type value.");
2641 return false;
2642 }
2643 QUIC_DVLOG(1) << "packet_number_length = " << header->packet_number_length;
2644 return true;
2645}
2646
fayang40315542019-05-09 09:19:09 -07002647// static
2648bool QuicFramer::ProcessVersionLabel(QuicDataReader* reader,
2649 QuicVersionLabel* version_label) {
nharpereaab5ad2019-05-31 12:23:25 -07002650 if (!reader->ReadUInt32(version_label)) {
fayang40315542019-05-09 09:19:09 -07002651 return false;
2652 }
fayang40315542019-05-09 09:19:09 -07002653 return true;
2654}
2655
2656// static
fayangccbab732019-05-13 10:11:25 -07002657bool QuicFramer::ProcessAndValidateIetfConnectionIdLength(
2658 QuicDataReader* reader,
fayang40315542019-05-09 09:19:09 -07002659 ParsedQuicVersion version,
dschinazi334f0232019-05-29 16:08:53 -07002660 Perspective perspective,
dschinazi8ff74822019-05-28 16:37:20 -07002661 bool should_update_expected_server_connection_id_length,
2662 uint8_t* expected_server_connection_id_length,
fayang40315542019-05-09 09:19:09 -07002663 uint8_t* destination_connection_id_length,
fayangccbab732019-05-13 10:11:25 -07002664 uint8_t* source_connection_id_length,
2665 std::string* detailed_error) {
2666 uint8_t connection_id_lengths_byte;
2667 if (!reader->ReadBytes(&connection_id_lengths_byte, 1)) {
2668 *detailed_error = "Unable to read ConnectionId length.";
2669 return false;
2670 }
fayang40315542019-05-09 09:19:09 -07002671 uint8_t dcil =
2672 (connection_id_lengths_byte & kDestinationConnectionIdLengthMask) >> 4;
2673 if (dcil != 0) {
2674 dcil += kConnectionIdLengthAdjustment;
2675 }
fayang40315542019-05-09 09:19:09 -07002676 uint8_t scil = connection_id_lengths_byte & kSourceConnectionIdLengthMask;
2677 if (scil != 0) {
2678 scil += kConnectionIdLengthAdjustment;
2679 }
dschinazi334f0232019-05-29 16:08:53 -07002680 if (should_update_expected_server_connection_id_length) {
2681 uint8_t server_connection_id_length =
2682 perspective == Perspective::IS_SERVER ? dcil : scil;
2683 if (*expected_server_connection_id_length != server_connection_id_length) {
2684 QUIC_DVLOG(1) << "Updating expected_server_connection_id_length: "
2685 << static_cast<int>(*expected_server_connection_id_length)
2686 << " -> " << static_cast<int>(server_connection_id_length);
2687 *expected_server_connection_id_length = server_connection_id_length;
2688 }
2689 }
dschinazi8ff74822019-05-28 16:37:20 -07002690 if (!should_update_expected_server_connection_id_length &&
fayangde8a2222019-05-16 10:52:39 -07002691 (dcil != *destination_connection_id_length ||
fayang40315542019-05-09 09:19:09 -07002692 scil != *source_connection_id_length) &&
fayang40315542019-05-09 09:19:09 -07002693 !QuicUtils::VariableLengthConnectionIdAllowedForVersion(
2694 version.transport_version)) {
2695 // TODO(dschinazi): use the framer's version once the
2696 // OnProtocolVersionMismatch call is moved to before this is run.
2697 QUIC_DVLOG(1) << "dcil: " << static_cast<uint32_t>(dcil)
2698 << ", scil: " << static_cast<uint32_t>(scil);
fayangccbab732019-05-13 10:11:25 -07002699 *detailed_error = "Invalid ConnectionId length.";
fayang40315542019-05-09 09:19:09 -07002700 return false;
2701 }
2702 *destination_connection_id_length = dcil;
2703 *source_connection_id_length = scil;
2704 return true;
2705}
2706
dschinazib953d022019-08-01 18:05:58 -07002707bool QuicFramer::ValidateReceivedConnectionIds(const QuicPacketHeader& header) {
2708 if (!QuicUtils::IsConnectionIdValidForVersion(
2709 GetServerConnectionIdAsRecipient(header, perspective_),
2710 transport_version())) {
2711 set_detailed_error("Received server connection ID with invalid length.");
2712 return false;
2713 }
2714
2715 if (version_.SupportsClientConnectionIds() &&
2716 !QuicUtils::IsConnectionIdValidForVersion(
2717 GetClientConnectionIdAsRecipient(header, perspective_),
2718 transport_version())) {
2719 set_detailed_error("Received client connection ID with invalid length.");
2720 return false;
2721 }
2722 return true;
2723}
2724
QUICHE teama6ef0a62019-03-07 20:34:33 -05002725bool QuicFramer::ProcessIetfPacketHeader(QuicDataReader* reader,
2726 QuicPacketHeader* header) {
dschinazi48ac9192019-07-31 00:07:26 -07002727 if (version_.HasLengthPrefixedConnectionIds()) {
2728 uint8_t expected_destination_connection_id_length =
2729 perspective_ == Perspective::IS_CLIENT
2730 ? expected_client_connection_id_length_
2731 : expected_server_connection_id_length_;
2732 QuicVersionLabel version_label;
2733 bool has_length_prefix;
2734 std::string detailed_error;
2735 QuicErrorCode parse_result = QuicFramer::ParsePublicHeader(
2736 reader, expected_destination_connection_id_length,
2737 VersionHasIetfInvariantHeader(version_.transport_version),
2738 &header->type_byte, &header->form, &header->version_flag,
2739 &has_length_prefix, &version_label, &header->version,
2740 &header->destination_connection_id, &header->source_connection_id,
2741 &header->long_packet_type, &header->retry_token_length_length,
2742 &header->retry_token, &detailed_error);
2743 if (parse_result != QUIC_NO_ERROR) {
2744 set_detailed_error(detailed_error);
2745 return false;
2746 }
2747 header->destination_connection_id_included = CONNECTION_ID_PRESENT;
2748 header->source_connection_id_included =
2749 header->version_flag ? CONNECTION_ID_PRESENT : CONNECTION_ID_ABSENT;
2750 if (header->source_connection_id_included == CONNECTION_ID_ABSENT) {
2751 DCHECK(header->source_connection_id.IsEmpty());
2752 if (perspective_ == Perspective::IS_CLIENT) {
2753 header->source_connection_id = last_serialized_server_connection_id_;
2754 } else {
2755 header->source_connection_id = last_serialized_client_connection_id_;
2756 }
2757 }
dschinazib953d022019-08-01 18:05:58 -07002758
2759 if (!ValidateReceivedConnectionIds(*header)) {
2760 return false;
2761 }
2762
dschinazi48ac9192019-07-31 00:07:26 -07002763 if (header->version_flag &&
2764 header->version.transport_version > QUIC_VERSION_44 &&
2765 !(header->type_byte & FLAGS_FIXED_BIT)) {
2766 set_detailed_error("Fixed bit is 0 in long header.");
2767 return false;
2768 }
2769 if (!header->version_flag && version_.transport_version > QUIC_VERSION_44 &&
2770 !(header->type_byte & FLAGS_FIXED_BIT)) {
2771 set_detailed_error("Fixed bit is 0 in short header.");
2772 return false;
2773 }
2774 if (!header->version_flag) {
2775 if (!version_.HasHeaderProtection() &&
2776 !GetShortHeaderPacketNumberLength(
2777 transport_version(), header->type_byte,
2778 infer_packet_header_type_from_version_,
2779 &header->packet_number_length)) {
2780 set_detailed_error("Failed to get short header packet number length.");
2781 return false;
2782 }
2783 return true;
2784 }
2785 if (header->long_packet_type == RETRY) {
2786 if (!version().SupportsRetry()) {
2787 set_detailed_error("RETRY not supported in this version.");
2788 return false;
2789 }
2790 if (perspective_ == Perspective::IS_SERVER) {
2791 set_detailed_error("Client-initiated RETRY is invalid.");
2792 return false;
2793 }
2794 return true;
2795 }
2796 if (!header->version.HasHeaderProtection()) {
2797 header->packet_number_length = GetLongHeaderPacketNumberLength(
2798 header->version.transport_version, header->type_byte);
2799 }
2800
2801 return true;
2802 }
2803
QUICHE teama6ef0a62019-03-07 20:34:33 -05002804 if (!ProcessIetfHeaderTypeByte(reader, header)) {
2805 return false;
2806 }
2807
2808 uint8_t destination_connection_id_length =
2809 header->destination_connection_id_included == CONNECTION_ID_PRESENT
dschinazi346b7ce2019-06-05 01:38:18 -07002810 ? (perspective_ == Perspective::IS_SERVER
2811 ? expected_server_connection_id_length_
2812 : expected_client_connection_id_length_)
QUICHE teama6ef0a62019-03-07 20:34:33 -05002813 : 0;
2814 uint8_t source_connection_id_length =
2815 header->source_connection_id_included == CONNECTION_ID_PRESENT
dschinazi346b7ce2019-06-05 01:38:18 -07002816 ? (perspective_ == Perspective::IS_CLIENT
2817 ? expected_server_connection_id_length_
2818 : expected_client_connection_id_length_)
QUICHE teama6ef0a62019-03-07 20:34:33 -05002819 : 0;
2820 if (header->form == IETF_QUIC_LONG_HEADER_PACKET) {
fayangccbab732019-05-13 10:11:25 -07002821 if (!ProcessAndValidateIetfConnectionIdLength(
dschinazi334f0232019-05-29 16:08:53 -07002822 reader, header->version, perspective_,
fayang91475c42019-06-19 08:04:26 -07002823 /*should_update_expected_server_connection_id_length=*/false,
dschinazi8ff74822019-05-28 16:37:20 -07002824 &expected_server_connection_id_length_,
2825 &destination_connection_id_length, &source_connection_id_length,
2826 &detailed_error_)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002827 return false;
2828 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002829 }
2830
2831 // Read connection ID.
2832 if (!reader->ReadConnectionId(&header->destination_connection_id,
2833 destination_connection_id_length)) {
dschinazi48ac9192019-07-31 00:07:26 -07002834 set_detailed_error("Unable to read destination connection ID.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05002835 return false;
2836 }
2837
2838 if (!reader->ReadConnectionId(&header->source_connection_id,
2839 source_connection_id_length)) {
dschinazi48ac9192019-07-31 00:07:26 -07002840 set_detailed_error("Unable to read source connection ID.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05002841 return false;
2842 }
2843
dschinazi5e1a7b22019-07-31 12:23:21 -07002844 if (header->source_connection_id_included == CONNECTION_ID_ABSENT) {
2845 if (!header->source_connection_id.IsEmpty()) {
2846 DCHECK(!version_.SupportsClientConnectionIds());
2847 set_detailed_error("Client connection ID not supported in this version.");
2848 return false;
QUICHE team2252b702019-05-14 23:55:14 -04002849 }
dschinazi5e1a7b22019-07-31 12:23:21 -07002850 if (perspective_ == Perspective::IS_CLIENT) {
2851 header->source_connection_id = last_serialized_server_connection_id_;
2852 } else {
2853 header->source_connection_id = last_serialized_client_connection_id_;
QUICHE team2252b702019-05-14 23:55:14 -04002854 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002855 }
2856
dschinazib953d022019-08-01 18:05:58 -07002857 return ValidateReceivedConnectionIds(*header);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002858}
2859
2860bool QuicFramer::ProcessAndCalculatePacketNumber(
2861 QuicDataReader* reader,
2862 QuicPacketNumberLength packet_number_length,
2863 QuicPacketNumber base_packet_number,
2864 uint64_t* packet_number) {
2865 uint64_t wire_packet_number;
2866 if (!reader->ReadBytesToUInt64(packet_number_length, &wire_packet_number)) {
2867 return false;
2868 }
2869
2870 // TODO(ianswett): Explore the usefulness of trying multiple packet numbers
2871 // in case the first guess is incorrect.
2872 *packet_number = CalculatePacketNumberFromWire(
2873 packet_number_length, base_packet_number, wire_packet_number);
2874 return true;
2875}
2876
2877bool QuicFramer::ProcessFrameData(QuicDataReader* reader,
2878 const QuicPacketHeader& header) {
fkastenholz305e1732019-06-18 05:01:22 -07002879 DCHECK(!VersionHasIetfQuicFrames(version_.transport_version))
2880 << "IETF QUIC Framing negotiated but attempting to process frames as "
2881 "non-IETF QUIC.";
QUICHE teama6ef0a62019-03-07 20:34:33 -05002882 if (reader->IsDoneReading()) {
2883 set_detailed_error("Packet has no frames.");
2884 return RaiseError(QUIC_MISSING_PAYLOAD);
2885 }
dschinazi118934b2019-06-13 18:09:08 -07002886 QUIC_DVLOG(2) << ENDPOINT << "Processing packet with header " << header;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002887 while (!reader->IsDoneReading()) {
2888 uint8_t frame_type;
2889 if (!reader->ReadBytes(&frame_type, 1)) {
2890 set_detailed_error("Unable to read frame type.");
2891 return RaiseError(QUIC_INVALID_FRAME_DATA);
2892 }
fayangf36e29d2019-06-06 14:03:40 -07002893 const uint8_t special_mask = transport_version() <= QUIC_VERSION_44
QUICHE teama6ef0a62019-03-07 20:34:33 -05002894 ? kQuicFrameTypeBrokenMask
2895 : kQuicFrameTypeSpecialMask;
2896 if (frame_type & special_mask) {
2897 // Stream Frame
2898 if (frame_type & kQuicFrameTypeStreamMask) {
2899 QuicStreamFrame frame;
2900 if (!ProcessStreamFrame(reader, frame_type, &frame)) {
2901 return RaiseError(QUIC_INVALID_STREAM_DATA);
2902 }
dschinazi118934b2019-06-13 18:09:08 -07002903 QUIC_DVLOG(2) << ENDPOINT << "Processing stream frame " << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002904 if (!visitor_->OnStreamFrame(frame)) {
2905 QUIC_DVLOG(1) << ENDPOINT
2906 << "Visitor asked to stop further processing.";
2907 // Returning true since there was no parsing error.
2908 return true;
2909 }
2910 continue;
2911 }
2912
2913 // Ack Frame
2914 if (frame_type & kQuicFrameTypeAckMask) {
2915 if (!ProcessAckFrame(reader, frame_type)) {
2916 return RaiseError(QUIC_INVALID_ACK_DATA);
2917 }
dschinazi118934b2019-06-13 18:09:08 -07002918 QUIC_DVLOG(2) << ENDPOINT << "Processing ACK frame";
QUICHE teama6ef0a62019-03-07 20:34:33 -05002919 continue;
2920 }
2921
2922 // This was a special frame type that did not match any
2923 // of the known ones. Error.
2924 set_detailed_error("Illegal frame type.");
2925 QUIC_DLOG(WARNING) << ENDPOINT << "Illegal frame type: "
2926 << static_cast<int>(frame_type);
2927 return RaiseError(QUIC_INVALID_FRAME_DATA);
2928 }
2929
2930 switch (frame_type) {
2931 case PADDING_FRAME: {
2932 QuicPaddingFrame frame;
2933 ProcessPaddingFrame(reader, &frame);
dschinazi118934b2019-06-13 18:09:08 -07002934 QUIC_DVLOG(2) << ENDPOINT << "Processing padding frame " << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002935 if (!visitor_->OnPaddingFrame(frame)) {
2936 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
2937 // Returning true since there was no parsing error.
2938 return true;
2939 }
2940 continue;
2941 }
2942
2943 case RST_STREAM_FRAME: {
2944 QuicRstStreamFrame frame;
2945 if (!ProcessRstStreamFrame(reader, &frame)) {
2946 return RaiseError(QUIC_INVALID_RST_STREAM_DATA);
2947 }
dschinazi118934b2019-06-13 18:09:08 -07002948 QUIC_DVLOG(2) << ENDPOINT << "Processing reset stream frame " << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002949 if (!visitor_->OnRstStreamFrame(frame)) {
2950 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
2951 // Returning true since there was no parsing error.
2952 return true;
2953 }
2954 continue;
2955 }
2956
2957 case CONNECTION_CLOSE_FRAME: {
2958 QuicConnectionCloseFrame frame;
2959 if (!ProcessConnectionCloseFrame(reader, &frame)) {
2960 return RaiseError(QUIC_INVALID_CONNECTION_CLOSE_DATA);
2961 }
2962
dschinazi118934b2019-06-13 18:09:08 -07002963 QUIC_DVLOG(2) << ENDPOINT << "Processing connection close frame "
2964 << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002965 if (!visitor_->OnConnectionCloseFrame(frame)) {
2966 QUIC_DVLOG(1) << ENDPOINT
2967 << "Visitor asked to stop further processing.";
2968 // Returning true since there was no parsing error.
2969 return true;
2970 }
2971 continue;
2972 }
2973
2974 case GOAWAY_FRAME: {
2975 QuicGoAwayFrame goaway_frame;
2976 if (!ProcessGoAwayFrame(reader, &goaway_frame)) {
2977 return RaiseError(QUIC_INVALID_GOAWAY_DATA);
2978 }
dschinazi118934b2019-06-13 18:09:08 -07002979 QUIC_DVLOG(2) << ENDPOINT << "Processing go away frame "
2980 << goaway_frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002981 if (!visitor_->OnGoAwayFrame(goaway_frame)) {
2982 QUIC_DVLOG(1) << ENDPOINT
2983 << "Visitor asked to stop further processing.";
2984 // Returning true since there was no parsing error.
2985 return true;
2986 }
2987 continue;
2988 }
2989
2990 case WINDOW_UPDATE_FRAME: {
2991 QuicWindowUpdateFrame window_update_frame;
2992 if (!ProcessWindowUpdateFrame(reader, &window_update_frame)) {
2993 return RaiseError(QUIC_INVALID_WINDOW_UPDATE_DATA);
2994 }
dschinazi118934b2019-06-13 18:09:08 -07002995 QUIC_DVLOG(2) << ENDPOINT << "Processing window update frame "
2996 << window_update_frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002997 if (!visitor_->OnWindowUpdateFrame(window_update_frame)) {
2998 QUIC_DVLOG(1) << ENDPOINT
2999 << "Visitor asked to stop further processing.";
3000 // Returning true since there was no parsing error.
3001 return true;
3002 }
3003 continue;
3004 }
3005
3006 case BLOCKED_FRAME: {
3007 QuicBlockedFrame blocked_frame;
3008 if (!ProcessBlockedFrame(reader, &blocked_frame)) {
3009 return RaiseError(QUIC_INVALID_BLOCKED_DATA);
3010 }
dschinazi118934b2019-06-13 18:09:08 -07003011 QUIC_DVLOG(2) << ENDPOINT << "Processing blocked frame "
3012 << blocked_frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003013 if (!visitor_->OnBlockedFrame(blocked_frame)) {
3014 QUIC_DVLOG(1) << ENDPOINT
3015 << "Visitor asked to stop further processing.";
3016 // Returning true since there was no parsing error.
3017 return true;
3018 }
3019 continue;
3020 }
3021
3022 case STOP_WAITING_FRAME: {
ianswett97b690b2019-05-02 15:12:43 -07003023 if (GetQuicReloadableFlag(quic_do_not_accept_stop_waiting) &&
fayangf36e29d2019-06-06 14:03:40 -07003024 version_.transport_version >= QUIC_VERSION_44) {
ianswett97b690b2019-05-02 15:12:43 -07003025 QUIC_RELOADABLE_FLAG_COUNT(quic_do_not_accept_stop_waiting);
3026 set_detailed_error("STOP WAITING not supported in version 44+.");
3027 return RaiseError(QUIC_INVALID_STOP_WAITING_DATA);
3028 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05003029 QuicStopWaitingFrame stop_waiting_frame;
3030 if (!ProcessStopWaitingFrame(reader, header, &stop_waiting_frame)) {
3031 return RaiseError(QUIC_INVALID_STOP_WAITING_DATA);
3032 }
dschinazi118934b2019-06-13 18:09:08 -07003033 QUIC_DVLOG(2) << ENDPOINT << "Processing stop waiting frame "
3034 << stop_waiting_frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003035 if (!visitor_->OnStopWaitingFrame(stop_waiting_frame)) {
3036 QUIC_DVLOG(1) << ENDPOINT
3037 << "Visitor asked to stop further processing.";
3038 // Returning true since there was no parsing error.
3039 return true;
3040 }
3041 continue;
3042 }
3043 case PING_FRAME: {
3044 // Ping has no payload.
3045 QuicPingFrame ping_frame;
3046 if (!visitor_->OnPingFrame(ping_frame)) {
3047 QUIC_DVLOG(1) << ENDPOINT
3048 << "Visitor asked to stop further processing.";
3049 // Returning true since there was no parsing error.
3050 return true;
3051 }
dschinazi118934b2019-06-13 18:09:08 -07003052 QUIC_DVLOG(2) << ENDPOINT << "Processing ping frame " << ping_frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003053 continue;
3054 }
3055 case IETF_EXTENSION_MESSAGE_NO_LENGTH:
3056 QUIC_FALLTHROUGH_INTENDED;
3057 case IETF_EXTENSION_MESSAGE: {
3058 QuicMessageFrame message_frame;
3059 if (!ProcessMessageFrame(reader,
3060 frame_type == IETF_EXTENSION_MESSAGE_NO_LENGTH,
3061 &message_frame)) {
3062 return RaiseError(QUIC_INVALID_MESSAGE_DATA);
3063 }
dschinazi118934b2019-06-13 18:09:08 -07003064 QUIC_DVLOG(2) << ENDPOINT << "Processing message frame "
3065 << message_frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003066 if (!visitor_->OnMessageFrame(message_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 break;
3073 }
3074 case CRYPTO_FRAME: {
QUICHE teamea740082019-03-11 17:58:43 -07003075 if (!QuicVersionUsesCryptoFrames(version_.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05003076 set_detailed_error("Illegal frame type.");
3077 return RaiseError(QUIC_INVALID_FRAME_DATA);
3078 }
3079 QuicCryptoFrame frame;
3080 if (!ProcessCryptoFrame(reader, &frame)) {
3081 return RaiseError(QUIC_INVALID_FRAME_DATA);
3082 }
dschinazi118934b2019-06-13 18:09:08 -07003083 QUIC_DVLOG(2) << ENDPOINT << "Processing crypto frame " << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003084 if (!visitor_->OnCryptoFrame(frame)) {
3085 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3086 // Returning true since there was no parsing error.
3087 return true;
3088 }
3089 break;
3090 }
3091
3092 default:
3093 set_detailed_error("Illegal frame type.");
3094 QUIC_DLOG(WARNING) << ENDPOINT << "Illegal frame type: "
3095 << static_cast<int>(frame_type);
3096 return RaiseError(QUIC_INVALID_FRAME_DATA);
3097 }
3098 }
3099
3100 return true;
3101}
3102
3103bool QuicFramer::ProcessIetfFrameData(QuicDataReader* reader,
3104 const QuicPacketHeader& header) {
fkastenholz305e1732019-06-18 05:01:22 -07003105 DCHECK(VersionHasIetfQuicFrames(version_.transport_version))
3106 << "Attempt to process frames as IETF frames but version ("
3107 << version_.transport_version << ") does not support IETF Framing.";
3108
QUICHE teama6ef0a62019-03-07 20:34:33 -05003109 if (reader->IsDoneReading()) {
3110 set_detailed_error("Packet has no frames.");
3111 return RaiseError(QUIC_MISSING_PAYLOAD);
3112 }
dschinazi118934b2019-06-13 18:09:08 -07003113
3114 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF packet with header " << header;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003115 while (!reader->IsDoneReading()) {
3116 uint64_t frame_type;
3117 // Will be the number of bytes into which frame_type was encoded.
3118 size_t encoded_bytes = reader->BytesRemaining();
3119 if (!reader->ReadVarInt62(&frame_type)) {
3120 set_detailed_error("Unable to read frame type.");
3121 return RaiseError(QUIC_INVALID_FRAME_DATA);
3122 }
3123
3124 // Is now the number of bytes into which the frame type was encoded.
3125 encoded_bytes -= reader->BytesRemaining();
3126
3127 // Check that the frame type is minimally encoded.
3128 if (encoded_bytes !=
3129 static_cast<size_t>(QuicDataWriter::GetVarInt62Len(frame_type))) {
3130 // The frame type was not minimally encoded.
3131 set_detailed_error("Frame type not minimally encoded.");
3132 return RaiseError(IETF_QUIC_PROTOCOL_VIOLATION);
3133 }
3134
3135 if (IS_IETF_STREAM_FRAME(frame_type)) {
3136 QuicStreamFrame frame;
3137 if (!ProcessIetfStreamFrame(reader, frame_type, &frame)) {
3138 return RaiseError(QUIC_INVALID_STREAM_DATA);
3139 }
dschinazi118934b2019-06-13 18:09:08 -07003140 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF stream frame " << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003141 if (!visitor_->OnStreamFrame(frame)) {
3142 QUIC_DVLOG(1) << ENDPOINT
3143 << "Visitor asked to stop further processing.";
3144 // Returning true since there was no parsing error.
3145 return true;
3146 }
3147 } else {
3148 switch (frame_type) {
3149 case IETF_PADDING: {
3150 QuicPaddingFrame frame;
3151 ProcessPaddingFrame(reader, &frame);
dschinazi118934b2019-06-13 18:09:08 -07003152 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF padding frame "
3153 << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003154 if (!visitor_->OnPaddingFrame(frame)) {
3155 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3156 // Returning true since there was no parsing error.
3157 return true;
3158 }
3159 break;
3160 }
3161 case IETF_RST_STREAM: {
3162 QuicRstStreamFrame frame;
3163 if (!ProcessIetfResetStreamFrame(reader, &frame)) {
3164 return RaiseError(QUIC_INVALID_RST_STREAM_DATA);
3165 }
dschinazi118934b2019-06-13 18:09:08 -07003166 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF reset stream frame "
3167 << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003168 if (!visitor_->OnRstStreamFrame(frame)) {
3169 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3170 // Returning true since there was no parsing error.
3171 return true;
3172 }
3173 break;
3174 }
fkastenholz04bd4f32019-04-16 12:24:38 -07003175 case IETF_APPLICATION_CLOSE:
QUICHE teama6ef0a62019-03-07 20:34:33 -05003176 case IETF_CONNECTION_CLOSE: {
3177 QuicConnectionCloseFrame frame;
fkastenholze9d71a82019-04-09 05:12:13 -07003178 if (!ProcessIetfConnectionCloseFrame(
fkastenholz04bd4f32019-04-16 12:24:38 -07003179 reader,
3180 (frame_type == IETF_CONNECTION_CLOSE)
3181 ? IETF_QUIC_TRANSPORT_CONNECTION_CLOSE
3182 : IETF_QUIC_APPLICATION_CONNECTION_CLOSE,
3183 &frame)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05003184 return RaiseError(QUIC_INVALID_CONNECTION_CLOSE_DATA);
3185 }
dschinazi118934b2019-06-13 18:09:08 -07003186 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF connection close frame "
3187 << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003188 if (!visitor_->OnConnectionCloseFrame(frame)) {
3189 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3190 // Returning true since there was no parsing error.
3191 return true;
3192 }
3193 break;
3194 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05003195 case IETF_MAX_DATA: {
3196 QuicWindowUpdateFrame frame;
3197 if (!ProcessMaxDataFrame(reader, &frame)) {
3198 return RaiseError(QUIC_INVALID_MAX_DATA_FRAME_DATA);
3199 }
3200 // TODO(fkastenholz): Or should we create a new visitor function,
3201 // OnMaxDataFrame()?
dschinazi118934b2019-06-13 18:09:08 -07003202 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF max data frame "
3203 << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003204 if (!visitor_->OnWindowUpdateFrame(frame)) {
3205 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3206 // Returning true since there was no parsing error.
3207 return true;
3208 }
3209 break;
3210 }
3211 case IETF_MAX_STREAM_DATA: {
3212 QuicWindowUpdateFrame frame;
3213 if (!ProcessMaxStreamDataFrame(reader, &frame)) {
3214 return RaiseError(QUIC_INVALID_MAX_STREAM_DATA_FRAME_DATA);
3215 }
3216 // TODO(fkastenholz): Or should we create a new visitor function,
3217 // OnMaxStreamDataFrame()?
dschinazi118934b2019-06-13 18:09:08 -07003218 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF max stream data frame "
3219 << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003220 if (!visitor_->OnWindowUpdateFrame(frame)) {
3221 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3222 // Returning true since there was no parsing error.
3223 return true;
3224 }
3225 break;
3226 }
3227 case IETF_MAX_STREAMS_BIDIRECTIONAL:
3228 case IETF_MAX_STREAMS_UNIDIRECTIONAL: {
fkastenholz3c4eabf2019-04-22 07:49:59 -07003229 QuicMaxStreamsFrame frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003230 if (!ProcessMaxStreamsFrame(reader, &frame, frame_type)) {
fkastenholz3c4eabf2019-04-22 07:49:59 -07003231 return RaiseError(QUIC_MAX_STREAMS_DATA);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003232 }
fkastenholz3c4eabf2019-04-22 07:49:59 -07003233 QUIC_CODE_COUNT_N(quic_max_streams_received, 1, 2);
dschinazi118934b2019-06-13 18:09:08 -07003234 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF max streams frame "
3235 << frame;
fkastenholz3c4eabf2019-04-22 07:49:59 -07003236 if (!visitor_->OnMaxStreamsFrame(frame)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05003237 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3238 // Returning true since there was no parsing error.
3239 return true;
3240 }
3241 break;
3242 }
3243 case IETF_PING: {
3244 // Ping has no payload.
3245 QuicPingFrame ping_frame;
dschinazi118934b2019-06-13 18:09:08 -07003246 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF ping frame "
3247 << ping_frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003248 if (!visitor_->OnPingFrame(ping_frame)) {
3249 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3250 // Returning true since there was no parsing error.
3251 return true;
3252 }
3253 break;
3254 }
3255 case IETF_BLOCKED: {
3256 QuicBlockedFrame frame;
3257 if (!ProcessIetfBlockedFrame(reader, &frame)) {
3258 return RaiseError(QUIC_INVALID_BLOCKED_DATA);
3259 }
dschinazi118934b2019-06-13 18:09:08 -07003260 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF blocked frame "
3261 << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003262 if (!visitor_->OnBlockedFrame(frame)) {
3263 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3264 // Returning true since there was no parsing error.
3265 return true;
3266 }
3267 break;
3268 }
3269 case IETF_STREAM_BLOCKED: {
3270 QuicBlockedFrame frame;
3271 if (!ProcessStreamBlockedFrame(reader, &frame)) {
3272 return RaiseError(QUIC_INVALID_STREAM_BLOCKED_DATA);
3273 }
dschinazi118934b2019-06-13 18:09:08 -07003274 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF stream blocked frame "
3275 << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003276 if (!visitor_->OnBlockedFrame(frame)) {
3277 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3278 // Returning true since there was no parsing error.
3279 return true;
3280 }
3281 break;
3282 }
3283 case IETF_STREAMS_BLOCKED_UNIDIRECTIONAL:
3284 case IETF_STREAMS_BLOCKED_BIDIRECTIONAL: {
fkastenholz3c4eabf2019-04-22 07:49:59 -07003285 QuicStreamsBlockedFrame frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003286 if (!ProcessStreamsBlockedFrame(reader, &frame, frame_type)) {
fkastenholz3c4eabf2019-04-22 07:49:59 -07003287 return RaiseError(QUIC_STREAMS_BLOCKED_DATA);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003288 }
fkastenholz3c4eabf2019-04-22 07:49:59 -07003289 QUIC_CODE_COUNT_N(quic_streams_blocked_received, 1, 2);
dschinazi118934b2019-06-13 18:09:08 -07003290 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF streams blocked frame "
3291 << frame;
fkastenholz3c4eabf2019-04-22 07:49:59 -07003292 if (!visitor_->OnStreamsBlockedFrame(frame)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05003293 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3294 // Returning true since there was no parsing error.
3295 return true;
3296 }
3297 break;
3298 }
3299 case IETF_NEW_CONNECTION_ID: {
3300 QuicNewConnectionIdFrame frame;
3301 if (!ProcessNewConnectionIdFrame(reader, &frame)) {
3302 return RaiseError(QUIC_INVALID_NEW_CONNECTION_ID_DATA);
3303 }
dschinazi118934b2019-06-13 18:09:08 -07003304 QUIC_DVLOG(2) << ENDPOINT
3305 << "Processing IETF new connection ID frame " << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003306 if (!visitor_->OnNewConnectionIdFrame(frame)) {
3307 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3308 // Returning true since there was no parsing error.
3309 return true;
3310 }
3311 break;
3312 }
3313 case IETF_RETIRE_CONNECTION_ID: {
3314 QuicRetireConnectionIdFrame frame;
3315 if (!ProcessRetireConnectionIdFrame(reader, &frame)) {
3316 return RaiseError(QUIC_INVALID_RETIRE_CONNECTION_ID_DATA);
3317 }
dschinazi118934b2019-06-13 18:09:08 -07003318 QUIC_DVLOG(2) << ENDPOINT
3319 << "Processing IETF retire connection ID frame "
3320 << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003321 if (!visitor_->OnRetireConnectionIdFrame(frame)) {
3322 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3323 // Returning true since there was no parsing error.
3324 return true;
3325 }
3326 break;
3327 }
3328 case IETF_NEW_TOKEN: {
3329 QuicNewTokenFrame frame;
3330 if (!ProcessNewTokenFrame(reader, &frame)) {
3331 return RaiseError(QUIC_INVALID_NEW_TOKEN);
3332 }
dschinazi118934b2019-06-13 18:09:08 -07003333 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF new token frame "
3334 << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003335 if (!visitor_->OnNewTokenFrame(frame)) {
3336 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3337 // Returning true since there was no parsing error.
3338 return true;
3339 }
3340 break;
3341 }
3342 case IETF_STOP_SENDING: {
3343 QuicStopSendingFrame frame;
3344 if (!ProcessStopSendingFrame(reader, &frame)) {
3345 return RaiseError(QUIC_INVALID_STOP_SENDING_FRAME_DATA);
3346 }
dschinazi118934b2019-06-13 18:09:08 -07003347 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF stop sending frame "
3348 << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003349 if (!visitor_->OnStopSendingFrame(frame)) {
3350 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3351 // Returning true since there was no parsing error.
3352 return true;
3353 }
3354 break;
3355 }
3356 case IETF_ACK_ECN:
3357 case IETF_ACK: {
3358 QuicAckFrame frame;
3359 if (!ProcessIetfAckFrame(reader, frame_type, &frame)) {
3360 return RaiseError(QUIC_INVALID_ACK_DATA);
3361 }
dschinazi118934b2019-06-13 18:09:08 -07003362 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF ACK frame " << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003363 break;
3364 }
3365 case IETF_PATH_CHALLENGE: {
3366 QuicPathChallengeFrame frame;
3367 if (!ProcessPathChallengeFrame(reader, &frame)) {
3368 return RaiseError(QUIC_INVALID_PATH_CHALLENGE_DATA);
3369 }
dschinazi118934b2019-06-13 18:09:08 -07003370 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF path challenge frame "
3371 << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003372 if (!visitor_->OnPathChallengeFrame(frame)) {
3373 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3374 // Returning true since there was no parsing error.
3375 return true;
3376 }
3377 break;
3378 }
3379 case IETF_PATH_RESPONSE: {
3380 QuicPathResponseFrame frame;
3381 if (!ProcessPathResponseFrame(reader, &frame)) {
3382 return RaiseError(QUIC_INVALID_PATH_RESPONSE_DATA);
3383 }
dschinazi118934b2019-06-13 18:09:08 -07003384 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF path response frame "
3385 << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003386 if (!visitor_->OnPathResponseFrame(frame)) {
3387 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3388 // Returning true since there was no parsing error.
3389 return true;
3390 }
3391 break;
3392 }
3393 case IETF_EXTENSION_MESSAGE_NO_LENGTH:
3394 QUIC_FALLTHROUGH_INTENDED;
3395 case IETF_EXTENSION_MESSAGE: {
3396 QuicMessageFrame message_frame;
3397 if (!ProcessMessageFrame(
3398 reader, frame_type == IETF_EXTENSION_MESSAGE_NO_LENGTH,
3399 &message_frame)) {
3400 return RaiseError(QUIC_INVALID_MESSAGE_DATA);
3401 }
dschinazi118934b2019-06-13 18:09:08 -07003402 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF message frame "
3403 << message_frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003404 if (!visitor_->OnMessageFrame(message_frame)) {
3405 QUIC_DVLOG(1) << ENDPOINT
3406 << "Visitor asked to stop further processing.";
3407 // Returning true since there was no parsing error.
3408 return true;
3409 }
3410 break;
3411 }
3412 case IETF_CRYPTO: {
3413 QuicCryptoFrame frame;
3414 if (!ProcessCryptoFrame(reader, &frame)) {
3415 return RaiseError(QUIC_INVALID_FRAME_DATA);
3416 }
dschinazi118934b2019-06-13 18:09:08 -07003417 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF crypto frame " << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003418 if (!visitor_->OnCryptoFrame(frame)) {
3419 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3420 // Returning true since there was no parsing error.
3421 return true;
3422 }
3423 break;
3424 }
3425
3426 default:
3427 set_detailed_error("Illegal frame type.");
3428 QUIC_DLOG(WARNING)
3429 << ENDPOINT
3430 << "Illegal frame type: " << static_cast<int>(frame_type);
3431 return RaiseError(QUIC_INVALID_FRAME_DATA);
3432 }
3433 }
3434 }
3435 return true;
3436}
3437
3438namespace {
3439// Create a mask that sets the last |num_bits| to 1 and the rest to 0.
3440inline uint8_t GetMaskFromNumBits(uint8_t num_bits) {
3441 return (1u << num_bits) - 1;
3442}
3443
3444// Extract |num_bits| from |flags| offset by |offset|.
3445uint8_t ExtractBits(uint8_t flags, uint8_t num_bits, uint8_t offset) {
3446 return (flags >> offset) & GetMaskFromNumBits(num_bits);
3447}
3448
3449// Extract the bit at position |offset| from |flags| as a bool.
3450bool ExtractBit(uint8_t flags, uint8_t offset) {
3451 return ((flags >> offset) & GetMaskFromNumBits(1)) != 0;
3452}
3453
3454// Set |num_bits|, offset by |offset| to |val| in |flags|.
3455void SetBits(uint8_t* flags, uint8_t val, uint8_t num_bits, uint8_t offset) {
3456 DCHECK_LE(val, GetMaskFromNumBits(num_bits));
3457 *flags |= val << offset;
3458}
3459
3460// Set the bit at position |offset| to |val| in |flags|.
3461void SetBit(uint8_t* flags, bool val, uint8_t offset) {
3462 SetBits(flags, val ? 1 : 0, 1, offset);
3463}
3464} // namespace
3465
3466bool QuicFramer::ProcessStreamFrame(QuicDataReader* reader,
3467 uint8_t frame_type,
3468 QuicStreamFrame* frame) {
3469 uint8_t stream_flags = frame_type;
3470
3471 uint8_t stream_id_length = 0;
3472 uint8_t offset_length = 4;
3473 bool has_data_length = true;
3474 stream_flags &= ~kQuicFrameTypeStreamMask;
3475
3476 // Read from right to left: StreamID, Offset, Data Length, Fin.
3477 stream_id_length = (stream_flags & kQuicStreamIDLengthMask) + 1;
3478 stream_flags >>= kQuicStreamIdShift;
3479
3480 offset_length = (stream_flags & kQuicStreamOffsetMask);
3481 // There is no encoding for 1 byte, only 0 and 2 through 8.
3482 if (offset_length > 0) {
3483 offset_length += 1;
3484 }
3485 stream_flags >>= kQuicStreamShift;
3486
3487 has_data_length =
3488 (stream_flags & kQuicStreamDataLengthMask) == kQuicStreamDataLengthMask;
3489 stream_flags >>= kQuicStreamDataLengthShift;
3490
3491 frame->fin = (stream_flags & kQuicStreamFinMask) == kQuicStreamFinShift;
3492
3493 uint64_t stream_id;
3494 if (!reader->ReadBytesToUInt64(stream_id_length, &stream_id)) {
3495 set_detailed_error("Unable to read stream_id.");
3496 return false;
3497 }
3498 frame->stream_id = static_cast<QuicStreamId>(stream_id);
3499
3500 if (!reader->ReadBytesToUInt64(offset_length, &frame->offset)) {
3501 set_detailed_error("Unable to read offset.");
3502 return false;
3503 }
3504
3505 // TODO(ianswett): Don't use QuicStringPiece as an intermediary.
3506 QuicStringPiece data;
3507 if (has_data_length) {
3508 if (!reader->ReadStringPiece16(&data)) {
3509 set_detailed_error("Unable to read frame data.");
3510 return false;
3511 }
3512 } else {
3513 if (!reader->ReadStringPiece(&data, reader->BytesRemaining())) {
3514 set_detailed_error("Unable to read frame data.");
3515 return false;
3516 }
3517 }
3518 frame->data_buffer = data.data();
3519 frame->data_length = static_cast<uint16_t>(data.length());
3520
3521 return true;
3522}
3523
3524bool QuicFramer::ProcessIetfStreamFrame(QuicDataReader* reader,
3525 uint8_t frame_type,
3526 QuicStreamFrame* frame) {
3527 // Read stream id from the frame. It's always present.
fkastenholz3c4eabf2019-04-22 07:49:59 -07003528 if (!reader->ReadVarIntU32(&frame->stream_id)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05003529 set_detailed_error("Unable to read stream_id.");
3530 return false;
3531 }
3532
3533 // If we have a data offset, read it. If not, set to 0.
3534 if (frame_type & IETF_STREAM_FRAME_OFF_BIT) {
3535 if (!reader->ReadVarInt62(&frame->offset)) {
3536 set_detailed_error("Unable to read stream data offset.");
3537 return false;
3538 }
3539 } else {
3540 // no offset in the frame, ensure it's 0 in the Frame.
3541 frame->offset = 0;
3542 }
3543
3544 // If we have a data length, read it. If not, set to 0.
3545 if (frame_type & IETF_STREAM_FRAME_LEN_BIT) {
3546 QuicIetfStreamDataLength length;
3547 if (!reader->ReadVarInt62(&length)) {
3548 set_detailed_error("Unable to read stream data length.");
3549 return false;
3550 }
3551 if (length > 0xffff) {
3552 set_detailed_error("Stream data length is too large.");
3553 return false;
3554 }
3555 frame->data_length = length;
3556 } else {
3557 // no length in the frame, it is the number of bytes remaining in the
3558 // packet.
3559 frame->data_length = reader->BytesRemaining();
3560 }
3561
3562 if (frame_type & IETF_STREAM_FRAME_FIN_BIT) {
3563 frame->fin = true;
3564 } else {
3565 frame->fin = false;
3566 }
3567
3568 // TODO(ianswett): Don't use QuicStringPiece as an intermediary.
3569 QuicStringPiece data;
3570 if (!reader->ReadStringPiece(&data, frame->data_length)) {
3571 set_detailed_error("Unable to read frame data.");
3572 return false;
3573 }
3574 frame->data_buffer = data.data();
3575 frame->data_length = static_cast<QuicIetfStreamDataLength>(data.length());
3576
3577 return true;
3578}
3579
3580bool QuicFramer::ProcessCryptoFrame(QuicDataReader* reader,
3581 QuicCryptoFrame* frame) {
3582 if (!reader->ReadVarInt62(&frame->offset)) {
3583 set_detailed_error("Unable to read crypto data offset.");
3584 return false;
3585 }
3586 uint64_t len;
3587 if (!reader->ReadVarInt62(&len) ||
3588 len > std::numeric_limits<QuicPacketLength>::max()) {
3589 set_detailed_error("Invalid data length.");
3590 return false;
3591 }
3592 frame->data_length = len;
3593
3594 // TODO(ianswett): Don't use QuicStringPiece as an intermediary.
3595 QuicStringPiece data;
3596 if (!reader->ReadStringPiece(&data, frame->data_length)) {
3597 set_detailed_error("Unable to read frame data.");
3598 return false;
3599 }
3600 frame->data_buffer = data.data();
3601 return true;
3602}
3603
3604bool QuicFramer::ProcessAckFrame(QuicDataReader* reader, uint8_t frame_type) {
3605 const bool has_ack_blocks =
3606 ExtractBit(frame_type, kQuicHasMultipleAckBlocksOffset);
3607 uint8_t num_ack_blocks = 0;
3608 uint8_t num_received_packets = 0;
3609
3610 // Determine the two lengths from the frame type: largest acked length,
3611 // ack block length.
3612 const QuicPacketNumberLength ack_block_length = ReadAckPacketNumberLength(
3613 version_.transport_version,
3614 ExtractBits(frame_type, kQuicSequenceNumberLengthNumBits,
3615 kActBlockLengthOffset));
3616 const QuicPacketNumberLength largest_acked_length = ReadAckPacketNumberLength(
3617 version_.transport_version,
3618 ExtractBits(frame_type, kQuicSequenceNumberLengthNumBits,
3619 kLargestAckedOffset));
3620
3621 uint64_t largest_acked;
3622 if (!reader->ReadBytesToUInt64(largest_acked_length, &largest_acked)) {
3623 set_detailed_error("Unable to read largest acked.");
3624 return false;
3625 }
3626
3627 if (largest_acked < first_sending_packet_number_.ToUint64()) {
3628 // Connection always sends packet starting from kFirstSendingPacketNumber >
3629 // 0, peer has observed an unsent packet.
3630 set_detailed_error("Largest acked is 0.");
3631 return false;
3632 }
3633
3634 uint64_t ack_delay_time_us;
3635 if (!reader->ReadUFloat16(&ack_delay_time_us)) {
3636 set_detailed_error("Unable to read ack delay time.");
3637 return false;
3638 }
3639
3640 if (!visitor_->OnAckFrameStart(
3641 QuicPacketNumber(largest_acked),
3642 ack_delay_time_us == kUFloat16MaxValue
3643 ? QuicTime::Delta::Infinite()
3644 : QuicTime::Delta::FromMicroseconds(ack_delay_time_us))) {
3645 // The visitor suppresses further processing of the packet. Although this is
3646 // not a parsing error, returns false as this is in middle of processing an
3647 // ack frame,
3648 set_detailed_error("Visitor suppresses further processing of ack frame.");
3649 return false;
3650 }
3651
3652 if (has_ack_blocks && !reader->ReadUInt8(&num_ack_blocks)) {
3653 set_detailed_error("Unable to read num of ack blocks.");
3654 return false;
3655 }
3656
3657 uint64_t first_block_length;
3658 if (!reader->ReadBytesToUInt64(ack_block_length, &first_block_length)) {
3659 set_detailed_error("Unable to read first ack block length.");
3660 return false;
3661 }
3662
3663 if (first_block_length == 0) {
3664 set_detailed_error("First block length is zero.");
3665 return false;
3666 }
3667 bool first_ack_block_underflow = first_block_length > largest_acked + 1;
3668 if (first_block_length + first_sending_packet_number_.ToUint64() >
3669 largest_acked + 1) {
3670 first_ack_block_underflow = true;
3671 }
3672 if (first_ack_block_underflow) {
3673 set_detailed_error(QuicStrCat("Underflow with first ack block length ",
3674 first_block_length, " largest acked is ",
3675 largest_acked, ".")
3676 .c_str());
3677 return false;
3678 }
3679
3680 uint64_t first_received = largest_acked + 1 - first_block_length;
3681 if (!visitor_->OnAckRange(QuicPacketNumber(first_received),
3682 QuicPacketNumber(largest_acked + 1))) {
3683 // The visitor suppresses further processing of the packet. Although
3684 // this is not a parsing error, returns false as this is in middle
3685 // of processing an ack frame,
3686 set_detailed_error("Visitor suppresses further processing of ack frame.");
3687 return false;
3688 }
3689
3690 if (num_ack_blocks > 0) {
3691 for (size_t i = 0; i < num_ack_blocks; ++i) {
3692 uint8_t gap = 0;
3693 if (!reader->ReadUInt8(&gap)) {
3694 set_detailed_error("Unable to read gap to next ack block.");
3695 return false;
3696 }
3697 uint64_t current_block_length;
3698 if (!reader->ReadBytesToUInt64(ack_block_length, &current_block_length)) {
3699 set_detailed_error("Unable to ack block length.");
3700 return false;
3701 }
3702 bool ack_block_underflow = first_received < gap + current_block_length;
3703 if (first_received < gap + current_block_length +
3704 first_sending_packet_number_.ToUint64()) {
3705 ack_block_underflow = true;
3706 }
3707 if (ack_block_underflow) {
3708 set_detailed_error(
3709 QuicStrCat("Underflow with ack block length ", current_block_length,
3710 ", end of block is ", first_received - gap, ".")
3711 .c_str());
3712 return false;
3713 }
3714
3715 first_received -= (gap + current_block_length);
3716 if (current_block_length > 0) {
3717 if (!visitor_->OnAckRange(
3718 QuicPacketNumber(first_received),
3719 QuicPacketNumber(first_received) + current_block_length)) {
3720 // The visitor suppresses further processing of the packet. Although
3721 // this is not a parsing error, returns false as this is in middle
3722 // of processing an ack frame,
3723 set_detailed_error(
3724 "Visitor suppresses further processing of ack frame.");
3725 return false;
3726 }
3727 }
3728 }
3729 }
3730
3731 if (!reader->ReadUInt8(&num_received_packets)) {
3732 set_detailed_error("Unable to read num received packets.");
3733 return false;
3734 }
3735
3736 if (!ProcessTimestampsInAckFrame(num_received_packets,
3737 QuicPacketNumber(largest_acked), reader)) {
3738 return false;
3739 }
3740
3741 // Done processing the ACK frame.
3742 return visitor_->OnAckFrameEnd(QuicPacketNumber(first_received));
3743}
3744
3745bool QuicFramer::ProcessTimestampsInAckFrame(uint8_t num_received_packets,
3746 QuicPacketNumber largest_acked,
3747 QuicDataReader* reader) {
3748 if (num_received_packets == 0) {
3749 return true;
3750 }
3751 uint8_t delta_from_largest_observed;
3752 if (!reader->ReadUInt8(&delta_from_largest_observed)) {
3753 set_detailed_error("Unable to read sequence delta in received packets.");
3754 return false;
3755 }
3756
3757 if (largest_acked.ToUint64() <= delta_from_largest_observed) {
3758 set_detailed_error(QuicStrCat("delta_from_largest_observed too high: ",
3759 delta_from_largest_observed,
3760 ", largest_acked: ", largest_acked.ToUint64())
3761 .c_str());
3762 return false;
3763 }
3764
3765 // Time delta from the framer creation.
3766 uint32_t time_delta_us;
3767 if (!reader->ReadUInt32(&time_delta_us)) {
3768 set_detailed_error("Unable to read time delta in received packets.");
3769 return false;
3770 }
3771
3772 QuicPacketNumber seq_num = largest_acked - delta_from_largest_observed;
3773 if (process_timestamps_) {
3774 last_timestamp_ = CalculateTimestampFromWire(time_delta_us);
3775
3776 visitor_->OnAckTimestamp(seq_num, creation_time_ + last_timestamp_);
3777 }
3778
3779 for (uint8_t i = 1; i < num_received_packets; ++i) {
3780 if (!reader->ReadUInt8(&delta_from_largest_observed)) {
3781 set_detailed_error("Unable to read sequence delta in received packets.");
3782 return false;
3783 }
3784 if (largest_acked.ToUint64() <= delta_from_largest_observed) {
3785 set_detailed_error(
3786 QuicStrCat("delta_from_largest_observed too high: ",
3787 delta_from_largest_observed,
3788 ", largest_acked: ", largest_acked.ToUint64())
3789 .c_str());
3790 return false;
3791 }
3792 seq_num = largest_acked - delta_from_largest_observed;
3793
3794 // Time delta from the previous timestamp.
3795 uint64_t incremental_time_delta_us;
3796 if (!reader->ReadUFloat16(&incremental_time_delta_us)) {
3797 set_detailed_error(
3798 "Unable to read incremental time delta in received packets.");
3799 return false;
3800 }
3801
3802 if (process_timestamps_) {
3803 last_timestamp_ = last_timestamp_ + QuicTime::Delta::FromMicroseconds(
3804 incremental_time_delta_us);
3805 visitor_->OnAckTimestamp(seq_num, creation_time_ + last_timestamp_);
3806 }
3807 }
3808 return true;
3809}
3810
3811bool QuicFramer::ProcessIetfAckFrame(QuicDataReader* reader,
3812 uint64_t frame_type,
3813 QuicAckFrame* ack_frame) {
3814 uint64_t largest_acked;
3815 if (!reader->ReadVarInt62(&largest_acked)) {
3816 set_detailed_error("Unable to read largest acked.");
3817 return false;
3818 }
3819 if (largest_acked < first_sending_packet_number_.ToUint64()) {
3820 // Connection always sends packet starting from kFirstSendingPacketNumber >
3821 // 0, peer has observed an unsent packet.
3822 set_detailed_error("Largest acked is 0.");
3823 return false;
3824 }
3825 ack_frame->largest_acked = static_cast<QuicPacketNumber>(largest_acked);
3826 uint64_t ack_delay_time_in_us;
3827 if (!reader->ReadVarInt62(&ack_delay_time_in_us)) {
3828 set_detailed_error("Unable to read ack delay time.");
3829 return false;
3830 }
3831
QUICHE teama6ef0a62019-03-07 20:34:33 -05003832 if (ack_delay_time_in_us == kVarInt62MaxValue) {
3833 ack_frame->ack_delay_time = QuicTime::Delta::Infinite();
3834 } else {
fkastenholz4dc4ba32019-07-30 09:55:25 -07003835 ack_delay_time_in_us = (ack_delay_time_in_us << peer_ack_delay_exponent_);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003836 ack_frame->ack_delay_time =
3837 QuicTime::Delta::FromMicroseconds(ack_delay_time_in_us);
3838 }
3839 if (frame_type == IETF_ACK_ECN) {
3840 ack_frame->ecn_counters_populated = true;
3841 if (!reader->ReadVarInt62(&ack_frame->ect_0_count)) {
3842 set_detailed_error("Unable to read ack ect_0_count.");
3843 return false;
3844 }
3845 if (!reader->ReadVarInt62(&ack_frame->ect_1_count)) {
3846 set_detailed_error("Unable to read ack ect_1_count.");
3847 return false;
3848 }
3849 if (!reader->ReadVarInt62(&ack_frame->ecn_ce_count)) {
3850 set_detailed_error("Unable to read ack ecn_ce_count.");
3851 return false;
3852 }
3853 } else {
3854 ack_frame->ecn_counters_populated = false;
3855 ack_frame->ect_0_count = 0;
3856 ack_frame->ect_1_count = 0;
3857 ack_frame->ecn_ce_count = 0;
3858 }
3859 if (!visitor_->OnAckFrameStart(QuicPacketNumber(largest_acked),
3860 ack_frame->ack_delay_time)) {
3861 // The visitor suppresses further processing of the packet. Although this is
3862 // not a parsing error, returns false as this is in middle of processing an
3863 // ACK frame.
3864 set_detailed_error("Visitor suppresses further processing of ACK frame.");
3865 return false;
3866 }
3867
3868 // Get number of ACK blocks from the packet.
3869 uint64_t ack_block_count;
3870 if (!reader->ReadVarInt62(&ack_block_count)) {
3871 set_detailed_error("Unable to read ack block count.");
3872 return false;
3873 }
3874 // There always is a first ACK block, which is the (number of packets being
3875 // acked)-1, up to and including the packet at largest_acked. Therefore if the
3876 // value is 0, then only largest is acked. If it is 1, then largest-1,
3877 // largest] are acked, etc
3878 uint64_t ack_block_value;
3879 if (!reader->ReadVarInt62(&ack_block_value)) {
3880 set_detailed_error("Unable to read first ack block length.");
3881 return false;
3882 }
3883 // Calculate the packets being acked in the first block.
3884 // +1 because AddRange implementation requires [low,high)
3885 uint64_t block_high = largest_acked + 1;
3886 uint64_t block_low = largest_acked - ack_block_value;
3887
3888 // ack_block_value is the number of packets preceding the
3889 // largest_acked packet which are in the block being acked. Thus,
3890 // its maximum value is largest_acked-1. Test this, reporting an
3891 // error if the value is wrong.
3892 if (ack_block_value + first_sending_packet_number_.ToUint64() >
3893 largest_acked) {
3894 set_detailed_error(QuicStrCat("Underflow with first ack block length ",
3895 ack_block_value + 1, " largest acked is ",
3896 largest_acked, ".")
3897 .c_str());
3898 return false;
3899 }
3900
3901 if (!visitor_->OnAckRange(QuicPacketNumber(block_low),
3902 QuicPacketNumber(block_high))) {
3903 // The visitor suppresses further processing of the packet. Although
3904 // this is not a parsing error, returns false as this is in middle
3905 // of processing an ACK frame.
3906 set_detailed_error("Visitor suppresses further processing of ACK frame.");
3907 return false;
3908 }
3909
3910 while (ack_block_count != 0) {
3911 uint64_t gap_block_value;
3912 // Get the sizes of the gap and ack blocks,
3913 if (!reader->ReadVarInt62(&gap_block_value)) {
3914 set_detailed_error("Unable to read gap block value.");
3915 return false;
3916 }
3917 // It's an error if the gap is larger than the space from packet
3918 // number 0 to the start of the block that's just been acked, PLUS
3919 // there must be space for at least 1 packet to be acked. For
3920 // example, if block_low is 10 and gap_block_value is 9, it means
3921 // the gap block is 10 packets long, leaving no room for a packet
3922 // to be acked. Thus, gap_block_value+2 can not be larger than
3923 // block_low.
3924 // The test is written this way to detect wrap-arounds.
3925 if ((gap_block_value + 2) > block_low) {
3926 set_detailed_error(
3927 QuicStrCat("Underflow with gap block length ", gap_block_value + 1,
3928 " previous ack block start is ", block_low, ".")
3929 .c_str());
3930 return false;
3931 }
3932
3933 // Adjust block_high to be the top of the next ack block.
3934 // There is a gap of |gap_block_value| packets between the bottom
3935 // of ack block N and top of block N+1. Note that gap_block_value
3936 // is he size of the gap minus 1 (per the QUIC protocol), and
3937 // block_high is the packet number of the first packet of the gap
3938 // (per the implementation of OnAckRange/AddAckRange, below).
3939 block_high = block_low - 1 - gap_block_value;
3940
3941 if (!reader->ReadVarInt62(&ack_block_value)) {
3942 set_detailed_error("Unable to read ack block value.");
3943 return false;
3944 }
3945 if (ack_block_value + first_sending_packet_number_.ToUint64() >
3946 (block_high - 1)) {
3947 set_detailed_error(
3948 QuicStrCat("Underflow with ack block length ", ack_block_value + 1,
3949 " latest ack block end is ", block_high - 1, ".")
3950 .c_str());
3951 return false;
3952 }
3953 // Calculate the low end of the new nth ack block. The +1 is
3954 // because the encoded value is the blocksize-1.
3955 block_low = block_high - 1 - ack_block_value;
3956 if (!visitor_->OnAckRange(QuicPacketNumber(block_low),
3957 QuicPacketNumber(block_high))) {
3958 // The visitor suppresses further processing of the packet. Although
3959 // this is not a parsing error, returns false as this is in middle
3960 // of processing an ACK frame.
3961 set_detailed_error("Visitor suppresses further processing of ACK frame.");
3962 return false;
3963 }
3964
3965 // Another one done.
3966 ack_block_count--;
3967 }
3968
3969 return visitor_->OnAckFrameEnd(QuicPacketNumber(block_low));
3970}
3971
3972bool QuicFramer::ProcessStopWaitingFrame(QuicDataReader* reader,
3973 const QuicPacketHeader& header,
3974 QuicStopWaitingFrame* stop_waiting) {
3975 uint64_t least_unacked_delta;
3976 if (!reader->ReadBytesToUInt64(header.packet_number_length,
3977 &least_unacked_delta)) {
3978 set_detailed_error("Unable to read least unacked delta.");
3979 return false;
3980 }
3981 if (header.packet_number.ToUint64() <= least_unacked_delta) {
3982 set_detailed_error("Invalid unacked delta.");
3983 return false;
3984 }
3985 stop_waiting->least_unacked = header.packet_number - least_unacked_delta;
3986
3987 return true;
3988}
3989
3990bool QuicFramer::ProcessRstStreamFrame(QuicDataReader* reader,
3991 QuicRstStreamFrame* frame) {
3992 if (!reader->ReadUInt32(&frame->stream_id)) {
3993 set_detailed_error("Unable to read stream_id.");
3994 return false;
3995 }
3996
3997 if (!reader->ReadUInt64(&frame->byte_offset)) {
3998 set_detailed_error("Unable to read rst stream sent byte offset.");
3999 return false;
4000 }
4001
4002 uint32_t error_code;
4003 if (!reader->ReadUInt32(&error_code)) {
4004 set_detailed_error("Unable to read rst stream error code.");
4005 return false;
4006 }
4007
4008 if (error_code >= QUIC_STREAM_LAST_ERROR) {
4009 // Ignore invalid stream error code if any.
4010 error_code = QUIC_STREAM_LAST_ERROR;
4011 }
4012
4013 frame->error_code = static_cast<QuicRstStreamErrorCode>(error_code);
4014
4015 return true;
4016}
4017
4018bool QuicFramer::ProcessConnectionCloseFrame(QuicDataReader* reader,
4019 QuicConnectionCloseFrame* frame) {
4020 uint32_t error_code;
fkastenholze9d71a82019-04-09 05:12:13 -07004021 frame->close_type = GOOGLE_QUIC_CONNECTION_CLOSE;
4022
QUICHE teama6ef0a62019-03-07 20:34:33 -05004023 if (!reader->ReadUInt32(&error_code)) {
4024 set_detailed_error("Unable to read connection close error code.");
4025 return false;
4026 }
4027
4028 if (error_code >= QUIC_LAST_ERROR) {
4029 // Ignore invalid QUIC error code if any.
4030 error_code = QUIC_LAST_ERROR;
4031 }
4032
fkastenholze9d71a82019-04-09 05:12:13 -07004033 frame->quic_error_code = static_cast<QuicErrorCode>(error_code);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004034
fkastenholza14a7ae2019-08-07 05:21:22 -07004035 // For Google QUIC connection closes, copy the Google QUIC error code to
4036 // the extracted error code field so that the Google QUIC error code is always
4037 // available in extracted_error_code.
4038 frame->extracted_error_code = frame->quic_error_code;
4039
QUICHE teama6ef0a62019-03-07 20:34:33 -05004040 QuicStringPiece error_details;
4041 if (!reader->ReadStringPiece16(&error_details)) {
4042 set_detailed_error("Unable to read connection close error details.");
4043 return false;
4044 }
vasilvvc48c8712019-03-11 13:38:16 -07004045 frame->error_details = std::string(error_details);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004046
4047 return true;
4048}
4049
4050bool QuicFramer::ProcessGoAwayFrame(QuicDataReader* reader,
4051 QuicGoAwayFrame* frame) {
4052 uint32_t error_code;
4053 if (!reader->ReadUInt32(&error_code)) {
4054 set_detailed_error("Unable to read go away error code.");
4055 return false;
4056 }
4057
4058 if (error_code >= QUIC_LAST_ERROR) {
4059 // Ignore invalid QUIC error code if any.
4060 error_code = QUIC_LAST_ERROR;
4061 }
4062 frame->error_code = static_cast<QuicErrorCode>(error_code);
4063
4064 uint32_t stream_id;
4065 if (!reader->ReadUInt32(&stream_id)) {
4066 set_detailed_error("Unable to read last good stream id.");
4067 return false;
4068 }
4069 frame->last_good_stream_id = static_cast<QuicStreamId>(stream_id);
4070
4071 QuicStringPiece reason_phrase;
4072 if (!reader->ReadStringPiece16(&reason_phrase)) {
4073 set_detailed_error("Unable to read goaway reason.");
4074 return false;
4075 }
vasilvvc48c8712019-03-11 13:38:16 -07004076 frame->reason_phrase = std::string(reason_phrase);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004077
4078 return true;
4079}
4080
4081bool QuicFramer::ProcessWindowUpdateFrame(QuicDataReader* reader,
4082 QuicWindowUpdateFrame* frame) {
4083 if (!reader->ReadUInt32(&frame->stream_id)) {
4084 set_detailed_error("Unable to read stream_id.");
4085 return false;
4086 }
4087
4088 if (!reader->ReadUInt64(&frame->byte_offset)) {
4089 set_detailed_error("Unable to read window byte_offset.");
4090 return false;
4091 }
4092
4093 return true;
4094}
4095
4096bool QuicFramer::ProcessBlockedFrame(QuicDataReader* reader,
4097 QuicBlockedFrame* frame) {
fkastenholz305e1732019-06-18 05:01:22 -07004098 DCHECK(!VersionHasIetfQuicFrames(version_.transport_version))
4099 << "Attempt to process non-IETF QUIC frames in an IETF QUIC version.";
QUICHE teama6ef0a62019-03-07 20:34:33 -05004100
4101 if (!reader->ReadUInt32(&frame->stream_id)) {
4102 set_detailed_error("Unable to read stream_id.");
4103 return false;
4104 }
4105
4106 return true;
4107}
4108
4109void QuicFramer::ProcessPaddingFrame(QuicDataReader* reader,
4110 QuicPaddingFrame* frame) {
4111 // Type byte has been read.
4112 frame->num_padding_bytes = 1;
4113 uint8_t next_byte;
4114 while (!reader->IsDoneReading() && reader->PeekByte() == 0x00) {
4115 reader->ReadBytes(&next_byte, 1);
4116 DCHECK_EQ(0x00, next_byte);
4117 ++frame->num_padding_bytes;
4118 }
4119}
4120
4121bool QuicFramer::ProcessMessageFrame(QuicDataReader* reader,
4122 bool no_message_length,
4123 QuicMessageFrame* frame) {
4124 if (no_message_length) {
4125 QuicStringPiece remaining(reader->ReadRemainingPayload());
4126 frame->data = remaining.data();
4127 frame->message_length = remaining.length();
4128 return true;
4129 }
4130
4131 uint64_t message_length;
4132 if (!reader->ReadVarInt62(&message_length)) {
4133 set_detailed_error("Unable to read message length");
4134 return false;
4135 }
4136
4137 QuicStringPiece message_piece;
4138 if (!reader->ReadStringPiece(&message_piece, message_length)) {
4139 set_detailed_error("Unable to read message data");
4140 return false;
4141 }
4142
4143 frame->data = message_piece.data();
4144 frame->message_length = message_length;
4145
4146 return true;
4147}
4148
4149// static
4150QuicStringPiece QuicFramer::GetAssociatedDataFromEncryptedPacket(
4151 QuicTransportVersion version,
4152 const QuicEncryptedPacket& encrypted,
4153 QuicConnectionIdLength destination_connection_id_length,
4154 QuicConnectionIdLength source_connection_id_length,
4155 bool includes_version,
4156 bool includes_diversification_nonce,
4157 QuicPacketNumberLength packet_number_length,
4158 QuicVariableLengthIntegerLength retry_token_length_length,
4159 uint64_t retry_token_length,
4160 QuicVariableLengthIntegerLength length_length) {
4161 // TODO(ianswett): This is identical to QuicData::AssociatedData.
4162 return QuicStringPiece(
4163 encrypted.data(),
4164 GetStartOfEncryptedData(version, destination_connection_id_length,
4165 source_connection_id_length, includes_version,
4166 includes_diversification_nonce,
4167 packet_number_length, retry_token_length_length,
4168 retry_token_length, length_length));
4169}
4170
4171void QuicFramer::SetDecrypter(EncryptionLevel level,
4172 std::unique_ptr<QuicDecrypter> decrypter) {
QUICHE team76086e42019-03-25 15:12:29 -07004173 DCHECK_EQ(alternative_decrypter_level_, NUM_ENCRYPTION_LEVELS);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004174 DCHECK_GE(level, decrypter_level_);
zhongyi546cc452019-04-12 15:27:49 -07004175 DCHECK(!version_.KnowsWhichDecrypterToUse());
QUICHE team76086e42019-03-25 15:12:29 -07004176 decrypter_[decrypter_level_] = nullptr;
4177 decrypter_[level] = std::move(decrypter);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004178 decrypter_level_ = level;
4179}
4180
4181void QuicFramer::SetAlternativeDecrypter(
4182 EncryptionLevel level,
4183 std::unique_ptr<QuicDecrypter> decrypter,
4184 bool latch_once_used) {
QUICHE team76086e42019-03-25 15:12:29 -07004185 DCHECK_NE(level, decrypter_level_);
zhongyi546cc452019-04-12 15:27:49 -07004186 DCHECK(!version_.KnowsWhichDecrypterToUse());
QUICHE team76086e42019-03-25 15:12:29 -07004187 if (alternative_decrypter_level_ != NUM_ENCRYPTION_LEVELS) {
4188 decrypter_[alternative_decrypter_level_] = nullptr;
4189 }
4190 decrypter_[level] = std::move(decrypter);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004191 alternative_decrypter_level_ = level;
4192 alternative_decrypter_latch_ = latch_once_used;
4193}
4194
zhongyi546cc452019-04-12 15:27:49 -07004195void QuicFramer::InstallDecrypter(EncryptionLevel level,
4196 std::unique_ptr<QuicDecrypter> decrypter) {
4197 DCHECK(version_.KnowsWhichDecrypterToUse());
4198 decrypter_[level] = std::move(decrypter);
4199}
4200
4201void QuicFramer::RemoveDecrypter(EncryptionLevel level) {
4202 DCHECK(version_.KnowsWhichDecrypterToUse());
4203 decrypter_[level] = nullptr;
4204}
4205
4206const QuicDecrypter* QuicFramer::GetDecrypter(EncryptionLevel level) const {
4207 DCHECK(version_.KnowsWhichDecrypterToUse());
4208 return decrypter_[level].get();
4209}
4210
QUICHE teama6ef0a62019-03-07 20:34:33 -05004211const QuicDecrypter* QuicFramer::decrypter() const {
QUICHE team76086e42019-03-25 15:12:29 -07004212 return decrypter_[decrypter_level_].get();
QUICHE teama6ef0a62019-03-07 20:34:33 -05004213}
4214
4215const QuicDecrypter* QuicFramer::alternative_decrypter() const {
QUICHE team76086e42019-03-25 15:12:29 -07004216 if (alternative_decrypter_level_ == NUM_ENCRYPTION_LEVELS) {
4217 return nullptr;
4218 }
4219 return decrypter_[alternative_decrypter_level_].get();
QUICHE teama6ef0a62019-03-07 20:34:33 -05004220}
4221
4222void QuicFramer::SetEncrypter(EncryptionLevel level,
4223 std::unique_ptr<QuicEncrypter> encrypter) {
4224 DCHECK_GE(level, 0);
4225 DCHECK_LT(level, NUM_ENCRYPTION_LEVELS);
4226 encrypter_[level] = std::move(encrypter);
4227}
4228
4229size_t QuicFramer::EncryptInPlace(EncryptionLevel level,
4230 QuicPacketNumber packet_number,
4231 size_t ad_len,
4232 size_t total_len,
4233 size_t buffer_len,
4234 char* buffer) {
4235 DCHECK(packet_number.IsInitialized());
dschinazi2c5386e2019-04-16 16:37:37 -07004236 if (encrypter_[level] == nullptr) {
4237 QUIC_BUG << ENDPOINT
4238 << "Attempted to encrypt in place without encrypter at level "
4239 << QuicUtils::EncryptionLevelToString(level);
4240 RaiseError(QUIC_ENCRYPTION_FAILURE);
4241 return 0;
4242 }
4243
QUICHE teama6ef0a62019-03-07 20:34:33 -05004244 size_t output_length = 0;
4245 if (!encrypter_[level]->EncryptPacket(
4246 packet_number.ToUint64(),
4247 QuicStringPiece(buffer, ad_len), // Associated data
4248 QuicStringPiece(buffer + ad_len, total_len - ad_len), // Plaintext
4249 buffer + ad_len, // Destination buffer
4250 &output_length, buffer_len - ad_len)) {
4251 RaiseError(QUIC_ENCRYPTION_FAILURE);
4252 return 0;
4253 }
nharper55fa6132019-05-07 19:37:21 -07004254 if (version_.HasHeaderProtection() &&
4255 !ApplyHeaderProtection(level, buffer, ad_len + output_length, ad_len)) {
4256 QUIC_DLOG(ERROR) << "Applying header protection failed.";
4257 RaiseError(QUIC_ENCRYPTION_FAILURE);
4258 return 0;
4259 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004260
4261 return ad_len + output_length;
4262}
4263
nharper55fa6132019-05-07 19:37:21 -07004264namespace {
4265
4266const size_t kHPSampleLen = 16;
4267
4268constexpr bool IsLongHeader(uint8_t type_byte) {
4269 return (type_byte & FLAGS_LONG_HEADER) != 0;
4270}
4271
4272} // namespace
4273
4274bool QuicFramer::ApplyHeaderProtection(EncryptionLevel level,
4275 char* buffer,
4276 size_t buffer_len,
4277 size_t ad_len) {
4278 QuicDataReader buffer_reader(buffer, buffer_len);
4279 QuicDataWriter buffer_writer(buffer_len, buffer);
4280 // The sample starts 4 bytes after the start of the packet number.
4281 if (ad_len < last_written_packet_number_length_) {
4282 return false;
4283 }
4284 size_t pn_offset = ad_len - last_written_packet_number_length_;
4285 // Sample the ciphertext and generate the mask to use for header protection.
4286 size_t sample_offset = pn_offset + 4;
4287 QuicDataReader sample_reader(buffer, buffer_len);
4288 QuicStringPiece sample;
4289 if (!sample_reader.Seek(sample_offset) ||
4290 !sample_reader.ReadStringPiece(&sample, kHPSampleLen)) {
4291 QUIC_BUG << "Not enough bytes to sample: sample_offset " << sample_offset
4292 << ", sample len: " << kHPSampleLen
4293 << ", buffer len: " << buffer_len;
4294 return false;
4295 }
4296
4297 std::string mask = encrypter_[level]->GenerateHeaderProtectionMask(sample);
4298 if (mask.empty()) {
4299 QUIC_BUG << "Unable to generate header protection mask.";
4300 return false;
4301 }
4302 QuicDataReader mask_reader(mask.data(), mask.size());
4303
4304 // Apply the mask to the 4 or 5 least significant bits of the first byte.
4305 uint8_t bitmask = 0x1f;
4306 uint8_t type_byte;
4307 if (!buffer_reader.ReadUInt8(&type_byte)) {
4308 return false;
4309 }
4310 QuicLongHeaderType header_type;
4311 if (IsLongHeader(type_byte)) {
4312 bitmask = 0x0f;
4313 if (!GetLongHeaderType(version_.transport_version, type_byte,
4314 &header_type)) {
4315 return false;
4316 }
4317 }
4318 uint8_t mask_byte;
4319 if (!mask_reader.ReadUInt8(&mask_byte) ||
4320 !buffer_writer.WriteUInt8(type_byte ^ (mask_byte & bitmask))) {
4321 return false;
4322 }
4323
4324 // Adjust |pn_offset| to account for the diversification nonce.
4325 if (IsLongHeader(type_byte) && header_type == ZERO_RTT_PROTECTED &&
4326 perspective_ == Perspective::IS_SERVER &&
4327 version_.handshake_protocol == PROTOCOL_QUIC_CRYPTO) {
4328 if (pn_offset <= kDiversificationNonceSize) {
4329 QUIC_BUG << "Expected diversification nonce, but not enough bytes";
4330 return false;
4331 }
4332 pn_offset -= kDiversificationNonceSize;
4333 }
4334 // Advance the reader and writer to the packet number. Both the reader and
4335 // writer have each read/written one byte.
4336 if (!buffer_writer.Seek(pn_offset - 1) ||
4337 !buffer_reader.Seek(pn_offset - 1)) {
4338 return false;
4339 }
4340 // Apply the rest of the mask to the packet number.
4341 for (size_t i = 0; i < last_written_packet_number_length_; ++i) {
4342 uint8_t buffer_byte;
4343 uint8_t mask_byte;
4344 if (!mask_reader.ReadUInt8(&mask_byte) ||
4345 !buffer_reader.ReadUInt8(&buffer_byte) ||
4346 !buffer_writer.WriteUInt8(buffer_byte ^ mask_byte)) {
4347 return false;
4348 }
4349 }
4350 return true;
4351}
4352
4353bool QuicFramer::RemoveHeaderProtection(QuicDataReader* reader,
4354 const QuicEncryptedPacket& packet,
4355 QuicPacketHeader* header,
4356 uint64_t* full_packet_number,
4357 std::vector<char>* associated_data) {
4358 EncryptionLevel expected_decryption_level = GetEncryptionLevel(*header);
4359 QuicDecrypter* decrypter = decrypter_[expected_decryption_level].get();
4360 if (decrypter == nullptr) {
4361 QUIC_DVLOG(1)
4362 << "No decrypter available for removing header protection at level "
4363 << expected_decryption_level;
4364 return false;
4365 }
4366
4367 bool has_diversification_nonce =
4368 header->form == IETF_QUIC_LONG_HEADER_PACKET &&
4369 header->long_packet_type == ZERO_RTT_PROTECTED &&
4370 perspective_ == Perspective::IS_CLIENT &&
4371 version_.handshake_protocol == PROTOCOL_QUIC_CRYPTO;
4372
4373 // Read a sample from the ciphertext and compute the mask to use for header
4374 // protection.
4375 QuicStringPiece remaining_packet = reader->PeekRemainingPayload();
4376 QuicDataReader sample_reader(remaining_packet);
4377
4378 // The sample starts 4 bytes after the start of the packet number.
4379 QuicStringPiece pn;
4380 if (!sample_reader.ReadStringPiece(&pn, 4)) {
4381 QUIC_DVLOG(1) << "Not enough data to sample";
4382 return false;
4383 }
4384 if (has_diversification_nonce) {
4385 // In Google QUIC, the diversification nonce comes between the packet number
4386 // and the sample.
4387 if (!sample_reader.Seek(kDiversificationNonceSize)) {
4388 QUIC_DVLOG(1) << "No diversification nonce to skip over";
4389 return false;
4390 }
4391 }
4392 std::string mask = decrypter->GenerateHeaderProtectionMask(&sample_reader);
4393 QuicDataReader mask_reader(mask.data(), mask.size());
4394 if (mask.empty()) {
4395 QUIC_DVLOG(1) << "Failed to compute mask";
4396 return false;
4397 }
4398
4399 // Unmask the rest of the type byte.
4400 uint8_t bitmask = 0x1f;
4401 if (IsLongHeader(header->type_byte)) {
4402 bitmask = 0x0f;
4403 }
4404 uint8_t mask_byte;
4405 if (!mask_reader.ReadUInt8(&mask_byte)) {
4406 QUIC_DVLOG(1) << "No first byte to read from mask";
4407 return false;
4408 }
4409 header->type_byte ^= (mask_byte & bitmask);
4410
4411 // Compute the packet number length.
4412 header->packet_number_length =
4413 static_cast<QuicPacketNumberLength>((header->type_byte & 0x03) + 1);
4414
4415 char pn_buffer[IETF_MAX_PACKET_NUMBER_LENGTH] = {};
4416 QuicDataWriter pn_writer(QUIC_ARRAYSIZE(pn_buffer), pn_buffer);
4417
4418 // Read the (protected) packet number from the reader and unmask the packet
4419 // number.
4420 for (size_t i = 0; i < header->packet_number_length; ++i) {
4421 uint8_t protected_pn_byte, mask_byte;
4422 if (!mask_reader.ReadUInt8(&mask_byte) ||
4423 !reader->ReadUInt8(&protected_pn_byte) ||
4424 !pn_writer.WriteUInt8(protected_pn_byte ^ mask_byte)) {
4425 QUIC_DVLOG(1) << "Failed to unmask packet number";
4426 return false;
4427 }
4428 }
4429 QuicDataReader packet_number_reader(pn_writer.data(), pn_writer.length());
4430 QuicPacketNumber base_packet_number;
4431 if (supports_multiple_packet_number_spaces_) {
4432 PacketNumberSpace pn_space = GetPacketNumberSpace(*header);
4433 if (pn_space == NUM_PACKET_NUMBER_SPACES) {
4434 return false;
4435 }
4436 base_packet_number = largest_decrypted_packet_numbers_[pn_space];
4437 } else {
4438 base_packet_number = largest_packet_number_;
4439 }
4440 if (!ProcessAndCalculatePacketNumber(
4441 &packet_number_reader, header->packet_number_length,
4442 base_packet_number, full_packet_number)) {
4443 return false;
4444 }
4445
4446 // Get the associated data, and apply the same unmasking operations to it.
4447 QuicStringPiece ad = GetAssociatedDataFromEncryptedPacket(
4448 version_.transport_version, packet,
4449 GetIncludedDestinationConnectionIdLength(*header),
4450 GetIncludedSourceConnectionIdLength(*header), header->version_flag,
4451 has_diversification_nonce, header->packet_number_length,
4452 header->retry_token_length_length, header->retry_token.length(),
4453 header->length_length);
4454 *associated_data = std::vector<char>(ad.begin(), ad.end());
4455 QuicDataWriter ad_writer(associated_data->size(), associated_data->data());
4456
4457 // Apply the unmasked type byte and packet number to |associated_data|.
4458 if (!ad_writer.WriteUInt8(header->type_byte)) {
4459 return false;
4460 }
4461 // Put the packet number at the end of the AD, or if there's a diversification
4462 // nonce, before that (which is at the end of the AD).
4463 size_t seek_len = ad_writer.remaining() - header->packet_number_length;
4464 if (has_diversification_nonce) {
4465 seek_len -= kDiversificationNonceSize;
4466 }
4467 if (!ad_writer.Seek(seek_len) ||
4468 !ad_writer.WriteBytes(pn_writer.data(), pn_writer.length())) {
4469 QUIC_DVLOG(1) << "Failed to apply unmasking operations to AD";
4470 return false;
4471 }
4472
4473 return true;
4474}
4475
QUICHE teama6ef0a62019-03-07 20:34:33 -05004476size_t QuicFramer::EncryptPayload(EncryptionLevel level,
4477 QuicPacketNumber packet_number,
4478 const QuicPacket& packet,
4479 char* buffer,
4480 size_t buffer_len) {
4481 DCHECK(packet_number.IsInitialized());
dschinazi2c5386e2019-04-16 16:37:37 -07004482 if (encrypter_[level] == nullptr) {
4483 QUIC_BUG << ENDPOINT << "Attempted to encrypt without encrypter at level "
4484 << QuicUtils::EncryptionLevelToString(level);
4485 RaiseError(QUIC_ENCRYPTION_FAILURE);
4486 return 0;
4487 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004488
4489 QuicStringPiece associated_data =
4490 packet.AssociatedData(version_.transport_version);
4491 // Copy in the header, because the encrypter only populates the encrypted
4492 // plaintext content.
4493 const size_t ad_len = associated_data.length();
4494 memmove(buffer, associated_data.data(), ad_len);
4495 // Encrypt the plaintext into the buffer.
4496 size_t output_length = 0;
4497 if (!encrypter_[level]->EncryptPacket(
4498 packet_number.ToUint64(), associated_data,
4499 packet.Plaintext(version_.transport_version), buffer + ad_len,
4500 &output_length, buffer_len - ad_len)) {
4501 RaiseError(QUIC_ENCRYPTION_FAILURE);
4502 return 0;
4503 }
nharper55fa6132019-05-07 19:37:21 -07004504 if (version_.HasHeaderProtection() &&
4505 !ApplyHeaderProtection(level, buffer, ad_len + output_length, ad_len)) {
4506 QUIC_DLOG(ERROR) << "Applying header protection failed.";
4507 RaiseError(QUIC_ENCRYPTION_FAILURE);
4508 return 0;
4509 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004510
4511 return ad_len + output_length;
4512}
4513
4514size_t QuicFramer::GetCiphertextSize(EncryptionLevel level,
4515 size_t plaintext_size) const {
4516 return encrypter_[level]->GetCiphertextSize(plaintext_size);
4517}
4518
4519size_t QuicFramer::GetMaxPlaintextSize(size_t ciphertext_size) {
4520 // In order to keep the code simple, we don't have the current encryption
4521 // level to hand. Both the NullEncrypter and AES-GCM have a tag length of 12.
4522 size_t min_plaintext_size = ciphertext_size;
4523
QUICHE team6987b4a2019-03-15 16:23:04 -07004524 for (int i = ENCRYPTION_INITIAL; i < NUM_ENCRYPTION_LEVELS; i++) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05004525 if (encrypter_[i] != nullptr) {
4526 size_t size = encrypter_[i]->GetMaxPlaintextSize(ciphertext_size);
4527 if (size < min_plaintext_size) {
4528 min_plaintext_size = size;
4529 }
4530 }
4531 }
4532
4533 return min_plaintext_size;
4534}
4535
4536bool QuicFramer::DecryptPayload(QuicStringPiece encrypted,
4537 QuicStringPiece associated_data,
4538 const QuicPacketHeader& header,
4539 char* decrypted_buffer,
4540 size_t buffer_length,
QUICHE team10b22a12019-03-21 15:31:42 -07004541 size_t* decrypted_length,
4542 EncryptionLevel* decrypted_level) {
nharper855d2172019-05-02 16:17:46 -07004543 if (!EncryptionLevelIsValid(decrypter_level_)) {
4544 QUIC_BUG << "Attempted to decrypt with bad decrypter_level_";
4545 return false;
4546 }
zhongyi546cc452019-04-12 15:27:49 -07004547 EncryptionLevel level = decrypter_level_;
4548 QuicDecrypter* decrypter = decrypter_[level].get();
QUICHE team76086e42019-03-25 15:12:29 -07004549 QuicDecrypter* alternative_decrypter = nullptr;
zhongyi546cc452019-04-12 15:27:49 -07004550 if (version().KnowsWhichDecrypterToUse()) {
nharper855d2172019-05-02 16:17:46 -07004551 if (header.form == GOOGLE_QUIC_PACKET) {
4552 QUIC_BUG << "Attempted to decrypt GOOGLE_QUIC_PACKET with a version that "
4553 "knows which decrypter to use";
4554 return false;
4555 }
zhongyi546cc452019-04-12 15:27:49 -07004556 level = GetEncryptionLevel(header);
nharper855d2172019-05-02 16:17:46 -07004557 if (!EncryptionLevelIsValid(level)) {
4558 QUIC_BUG << "Attempted to decrypt with bad level";
4559 return false;
4560 }
zhongyi546cc452019-04-12 15:27:49 -07004561 decrypter = decrypter_[level].get();
4562 if (decrypter == nullptr) {
4563 return false;
4564 }
4565 if (level == ENCRYPTION_ZERO_RTT &&
4566 perspective_ == Perspective::IS_CLIENT && header.nonce != nullptr) {
4567 decrypter->SetDiversificationNonce(*header.nonce);
4568 }
4569 } else if (alternative_decrypter_level_ != NUM_ENCRYPTION_LEVELS) {
nharper855d2172019-05-02 16:17:46 -07004570 if (!EncryptionLevelIsValid(alternative_decrypter_level_)) {
4571 QUIC_BUG << "Attempted to decrypt with bad alternative_decrypter_level_";
4572 return false;
4573 }
QUICHE team76086e42019-03-25 15:12:29 -07004574 alternative_decrypter = decrypter_[alternative_decrypter_level_].get();
4575 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004576
nharper855d2172019-05-02 16:17:46 -07004577 if (decrypter == nullptr) {
ianswettf919fb22019-05-13 06:42:11 -07004578 QUIC_BUG << "Attempting to decrypt without decrypter, encryption level:"
4579 << level << " version:" << version();
nharper855d2172019-05-02 16:17:46 -07004580 return false;
4581 }
zhongyi546cc452019-04-12 15:27:49 -07004582
4583 bool success = decrypter->DecryptPacket(
QUICHE teama6ef0a62019-03-07 20:34:33 -05004584 header.packet_number.ToUint64(), associated_data, encrypted,
4585 decrypted_buffer, decrypted_length, buffer_length);
4586 if (success) {
zhongyi546cc452019-04-12 15:27:49 -07004587 visitor_->OnDecryptedPacket(level);
4588 *decrypted_level = level;
QUICHE team76086e42019-03-25 15:12:29 -07004589 } else if (alternative_decrypter != nullptr) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05004590 if (header.nonce != nullptr) {
4591 DCHECK_EQ(perspective_, Perspective::IS_CLIENT);
QUICHE team76086e42019-03-25 15:12:29 -07004592 alternative_decrypter->SetDiversificationNonce(*header.nonce);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004593 }
4594 bool try_alternative_decryption = true;
4595 if (alternative_decrypter_level_ == ENCRYPTION_ZERO_RTT) {
4596 if (perspective_ == Perspective::IS_CLIENT) {
4597 if (header.nonce == nullptr) {
4598 // Can not use INITIAL decryption without a diversification nonce.
4599 try_alternative_decryption = false;
4600 }
4601 } else {
4602 DCHECK(header.nonce == nullptr);
4603 }
4604 }
4605
4606 if (try_alternative_decryption) {
QUICHE team76086e42019-03-25 15:12:29 -07004607 success = alternative_decrypter->DecryptPacket(
QUICHE teama6ef0a62019-03-07 20:34:33 -05004608 header.packet_number.ToUint64(), associated_data, encrypted,
4609 decrypted_buffer, decrypted_length, buffer_length);
4610 }
4611 if (success) {
4612 visitor_->OnDecryptedPacket(alternative_decrypter_level_);
QUICHE team10b22a12019-03-21 15:31:42 -07004613 *decrypted_level = decrypter_level_;
QUICHE teama6ef0a62019-03-07 20:34:33 -05004614 if (alternative_decrypter_latch_) {
nharper855d2172019-05-02 16:17:46 -07004615 if (!EncryptionLevelIsValid(alternative_decrypter_level_)) {
4616 QUIC_BUG << "Attempted to latch alternate decrypter with bad "
4617 "alternative_decrypter_level_";
4618 return false;
4619 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004620 // Switch to the alternative decrypter and latch so that we cannot
4621 // switch back.
QUICHE teama6ef0a62019-03-07 20:34:33 -05004622 decrypter_level_ = alternative_decrypter_level_;
QUICHE team76086e42019-03-25 15:12:29 -07004623 alternative_decrypter_level_ = NUM_ENCRYPTION_LEVELS;
QUICHE teama6ef0a62019-03-07 20:34:33 -05004624 } else {
4625 // Switch the alternative decrypter so that we use it first next time.
QUICHE teama6ef0a62019-03-07 20:34:33 -05004626 EncryptionLevel level = alternative_decrypter_level_;
4627 alternative_decrypter_level_ = decrypter_level_;
4628 decrypter_level_ = level;
4629 }
4630 }
4631 }
4632
4633 if (!success) {
dschinazi965ce092019-05-23 06:29:01 -07004634 QUIC_DVLOG(1) << ENDPOINT << "DecryptPacket failed for: " << header;
QUICHE teama6ef0a62019-03-07 20:34:33 -05004635 return false;
4636 }
4637
4638 return true;
4639}
4640
4641size_t QuicFramer::GetIetfAckFrameSize(const QuicAckFrame& frame) {
4642 // Type byte, largest_acked, and delay_time are straight-forward.
4643 size_t ack_frame_size = kQuicFrameTypeSize;
4644 QuicPacketNumber largest_acked = LargestAcked(frame);
4645 ack_frame_size += QuicDataWriter::GetVarInt62Len(largest_acked.ToUint64());
4646 uint64_t ack_delay_time_us;
4647 ack_delay_time_us = frame.ack_delay_time.ToMicroseconds();
fkastenholz4dc4ba32019-07-30 09:55:25 -07004648 ack_delay_time_us = ack_delay_time_us >> local_ack_delay_exponent_;
QUICHE teama6ef0a62019-03-07 20:34:33 -05004649 ack_frame_size += QuicDataWriter::GetVarInt62Len(ack_delay_time_us);
4650
4651 // If |ecn_counters_populated| is true and any of the ecn counters is non-0
4652 // then the ecn counters are included...
4653 if (frame.ecn_counters_populated &&
4654 (frame.ect_0_count || frame.ect_1_count || frame.ecn_ce_count)) {
4655 ack_frame_size += QuicDataWriter::GetVarInt62Len(frame.ect_0_count);
4656 ack_frame_size += QuicDataWriter::GetVarInt62Len(frame.ect_1_count);
4657 ack_frame_size += QuicDataWriter::GetVarInt62Len(frame.ecn_ce_count);
4658 }
4659
4660 // The rest (ack_block_count, first_ack_block, and additional ack
4661 // blocks, if any) depends:
4662 uint64_t ack_block_count = frame.packets.NumIntervals();
4663 if (ack_block_count == 0) {
4664 // If the QuicAckFrame has no Intervals, then it is interpreted
4665 // as an ack of a single packet at QuicAckFrame.largest_acked.
4666 // The resulting ack will consist of only the frame's
4667 // largest_ack & first_ack_block fields. The first ack block will be 0
4668 // (indicating a single packet) and the ack block_count will be 0.
4669 // Each 0 takes 1 byte when VarInt62 encoded.
4670 ack_frame_size += 2;
4671 return ack_frame_size;
4672 }
4673
4674 auto itr = frame.packets.rbegin();
4675 QuicPacketNumber ack_block_largest = largest_acked;
4676 QuicPacketNumber ack_block_smallest;
4677 if ((itr->max() - 1) == largest_acked) {
4678 // If largest_acked + 1 is equal to the Max() of the first Interval
4679 // in the QuicAckFrame then the first Interval is the first ack block of the
4680 // frame; remaining Intervals are additional ack blocks. The QuicAckFrame's
4681 // first Interval is encoded in the frame's largest_acked/first_ack_block,
4682 // the remaining Intervals are encoded in additional ack blocks in the
4683 // frame, and the packet's ack_block_count is the number of QuicAckFrame
4684 // Intervals - 1.
4685 ack_block_smallest = itr->min();
4686 itr++;
4687 ack_block_count--;
4688 } else {
4689 // If QuicAckFrame.largest_acked is NOT equal to the Max() of
4690 // the first Interval then it is interpreted as acking a single
4691 // packet at QuicAckFrame.largest_acked, with additional
4692 // Intervals indicating additional ack blocks. The encoding is
4693 // a) The packet's largest_acked is the QuicAckFrame's largest
4694 // acked,
4695 // b) the first ack block size is 0,
4696 // c) The packet's ack_block_count is the number of QuicAckFrame
4697 // Intervals, and
4698 // d) The QuicAckFrame Intervals are encoded in additional ack
4699 // blocks in the packet.
4700 ack_block_smallest = largest_acked;
4701 }
4702 size_t ack_block_count_size = QuicDataWriter::GetVarInt62Len(ack_block_count);
4703 ack_frame_size += ack_block_count_size;
4704
4705 uint64_t first_ack_block = ack_block_largest - ack_block_smallest;
4706 size_t first_ack_block_size = QuicDataWriter::GetVarInt62Len(first_ack_block);
4707 ack_frame_size += first_ack_block_size;
4708
4709 // Account for the remaining Intervals, if any.
4710 while (ack_block_count != 0) {
4711 uint64_t gap_size = ack_block_smallest - itr->max();
4712 // Decrement per the protocol specification
4713 size_t size_of_gap_size = QuicDataWriter::GetVarInt62Len(gap_size - 1);
4714 ack_frame_size += size_of_gap_size;
4715
4716 uint64_t block_size = itr->max() - itr->min();
4717 // Decrement per the protocol specification
4718 size_t size_of_block_size = QuicDataWriter::GetVarInt62Len(block_size - 1);
4719 ack_frame_size += size_of_block_size;
4720
4721 ack_block_smallest = itr->min();
4722 itr++;
4723 ack_block_count--;
4724 }
4725
4726 return ack_frame_size;
4727}
4728
4729size_t QuicFramer::GetAckFrameSize(
4730 const QuicAckFrame& ack,
dschinazi17d42422019-06-18 16:35:07 -07004731 QuicPacketNumberLength /*packet_number_length*/) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05004732 DCHECK(!ack.packets.Empty());
4733 size_t ack_size = 0;
4734
fkastenholz305e1732019-06-18 05:01:22 -07004735 if (VersionHasIetfQuicFrames(version_.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05004736 return GetIetfAckFrameSize(ack);
4737 }
4738 AckFrameInfo ack_info = GetAckFrameInfo(ack);
4739 QuicPacketNumberLength largest_acked_length =
4740 GetMinPacketNumberLength(version_.transport_version, LargestAcked(ack));
4741 QuicPacketNumberLength ack_block_length = GetMinPacketNumberLength(
4742 version_.transport_version, QuicPacketNumber(ack_info.max_block_length));
4743
4744 ack_size =
4745 GetMinAckFrameSize(version_.transport_version, largest_acked_length);
4746 // First ack block length.
4747 ack_size += ack_block_length;
4748 if (ack_info.num_ack_blocks != 0) {
4749 ack_size += kNumberOfAckBlocksSize;
4750 ack_size += std::min(ack_info.num_ack_blocks, kMaxAckBlocks) *
4751 (ack_block_length + PACKET_1BYTE_PACKET_NUMBER);
4752 }
4753
4754 // Include timestamps.
4755 if (process_timestamps_) {
4756 ack_size += GetAckFrameTimeStampSize(ack);
4757 }
4758
4759 return ack_size;
4760}
4761
4762size_t QuicFramer::GetAckFrameTimeStampSize(const QuicAckFrame& ack) {
4763 if (ack.received_packet_times.empty()) {
4764 return 0;
4765 }
4766
4767 return kQuicNumTimestampsLength + kQuicFirstTimestampLength +
4768 (kQuicTimestampLength + kQuicTimestampPacketNumberGapLength) *
4769 (ack.received_packet_times.size() - 1);
4770}
4771
4772size_t QuicFramer::ComputeFrameLength(
4773 const QuicFrame& frame,
4774 bool last_frame_in_packet,
4775 QuicPacketNumberLength packet_number_length) {
4776 switch (frame.type) {
4777 case STREAM_FRAME:
4778 return GetMinStreamFrameSize(
4779 version_.transport_version, frame.stream_frame.stream_id,
4780 frame.stream_frame.offset, last_frame_in_packet,
4781 frame.stream_frame.data_length) +
4782 frame.stream_frame.data_length;
4783 case CRYPTO_FRAME:
4784 return GetMinCryptoFrameSize(frame.crypto_frame->offset,
4785 frame.crypto_frame->data_length) +
4786 frame.crypto_frame->data_length;
4787 case ACK_FRAME: {
4788 return GetAckFrameSize(*frame.ack_frame, packet_number_length);
4789 }
4790 case STOP_WAITING_FRAME:
4791 return GetStopWaitingFrameSize(version_.transport_version,
4792 packet_number_length);
4793 case MTU_DISCOVERY_FRAME:
4794 // MTU discovery frames are serialized as ping frames.
4795 return kQuicFrameTypeSize;
4796 case MESSAGE_FRAME:
4797 return GetMessageFrameSize(version_.transport_version,
4798 last_frame_in_packet,
4799 frame.message_frame->message_length);
4800 case PADDING_FRAME:
4801 DCHECK(false);
4802 return 0;
4803 default:
4804 return GetRetransmittableControlFrameSize(version_.transport_version,
4805 frame);
4806 }
4807}
4808
4809bool QuicFramer::AppendTypeByte(const QuicFrame& frame,
4810 bool last_frame_in_packet,
4811 QuicDataWriter* writer) {
fkastenholz305e1732019-06-18 05:01:22 -07004812 if (VersionHasIetfQuicFrames(version_.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05004813 return AppendIetfTypeByte(frame, last_frame_in_packet, writer);
4814 }
4815 uint8_t type_byte = 0;
4816 switch (frame.type) {
4817 case STREAM_FRAME:
4818 type_byte =
4819 GetStreamFrameTypeByte(frame.stream_frame, last_frame_in_packet);
4820 break;
4821 case ACK_FRAME:
4822 return true;
4823 case MTU_DISCOVERY_FRAME:
4824 type_byte = static_cast<uint8_t>(PING_FRAME);
4825 break;
QUICHE teama6ef0a62019-03-07 20:34:33 -05004826 case NEW_CONNECTION_ID_FRAME:
4827 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -07004828 "Attempt to append NEW_CONNECTION_ID frame and not in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05004829 return RaiseError(QUIC_INTERNAL_ERROR);
4830 case RETIRE_CONNECTION_ID_FRAME:
4831 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -07004832 "Attempt to append RETIRE_CONNECTION_ID frame and not in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05004833 return RaiseError(QUIC_INTERNAL_ERROR);
4834 case NEW_TOKEN_FRAME:
4835 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -07004836 "Attempt to append NEW_TOKEN frame and not in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05004837 return RaiseError(QUIC_INTERNAL_ERROR);
fkastenholz3c4eabf2019-04-22 07:49:59 -07004838 case MAX_STREAMS_FRAME:
QUICHE teama6ef0a62019-03-07 20:34:33 -05004839 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -07004840 "Attempt to append MAX_STREAMS frame and not in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05004841 return RaiseError(QUIC_INTERNAL_ERROR);
fkastenholz3c4eabf2019-04-22 07:49:59 -07004842 case STREAMS_BLOCKED_FRAME:
QUICHE teama6ef0a62019-03-07 20:34:33 -05004843 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -07004844 "Attempt to append STREAMS_BLOCKED frame and not in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05004845 return RaiseError(QUIC_INTERNAL_ERROR);
4846 case PATH_RESPONSE_FRAME:
4847 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -07004848 "Attempt to append PATH_RESPONSE frame and not in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05004849 return RaiseError(QUIC_INTERNAL_ERROR);
4850 case PATH_CHALLENGE_FRAME:
4851 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -07004852 "Attempt to append PATH_CHALLENGE frame and not in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05004853 return RaiseError(QUIC_INTERNAL_ERROR);
4854 case STOP_SENDING_FRAME:
4855 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -07004856 "Attempt to append STOP_SENDING frame and not in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05004857 return RaiseError(QUIC_INTERNAL_ERROR);
4858 case MESSAGE_FRAME:
4859 return true;
4860
4861 default:
4862 type_byte = static_cast<uint8_t>(frame.type);
4863 break;
4864 }
4865
4866 return writer->WriteUInt8(type_byte);
4867}
4868
4869bool QuicFramer::AppendIetfTypeByte(const QuicFrame& frame,
4870 bool last_frame_in_packet,
4871 QuicDataWriter* writer) {
4872 uint8_t type_byte = 0;
4873 switch (frame.type) {
4874 case PADDING_FRAME:
4875 type_byte = IETF_PADDING;
4876 break;
4877 case RST_STREAM_FRAME:
4878 type_byte = IETF_RST_STREAM;
4879 break;
4880 case CONNECTION_CLOSE_FRAME:
fkastenholz72f509b2019-04-10 09:17:49 -07004881 switch (frame.connection_close_frame->close_type) {
4882 case IETF_QUIC_APPLICATION_CONNECTION_CLOSE:
4883 type_byte = IETF_APPLICATION_CLOSE;
4884 break;
4885 case IETF_QUIC_TRANSPORT_CONNECTION_CLOSE:
4886 type_byte = IETF_CONNECTION_CLOSE;
4887 break;
4888 default:
4889 set_detailed_error("Invalid QuicConnectionCloseFrame type.");
4890 return RaiseError(QUIC_INTERNAL_ERROR);
4891 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004892 break;
4893 case GOAWAY_FRAME:
4894 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -07004895 "Attempt to create non-IETF QUIC GOAWAY frame in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05004896 return RaiseError(QUIC_INTERNAL_ERROR);
4897 case WINDOW_UPDATE_FRAME:
4898 // Depending on whether there is a stream ID or not, will be either a
4899 // MAX_STREAM_DATA frame or a MAX_DATA frame.
4900 if (frame.window_update_frame->stream_id ==
4901 QuicUtils::GetInvalidStreamId(transport_version())) {
4902 type_byte = IETF_MAX_DATA;
4903 } else {
4904 type_byte = IETF_MAX_STREAM_DATA;
4905 }
4906 break;
4907 case BLOCKED_FRAME:
4908 if (frame.blocked_frame->stream_id ==
4909 QuicUtils::GetInvalidStreamId(transport_version())) {
4910 type_byte = IETF_BLOCKED;
4911 } else {
4912 type_byte = IETF_STREAM_BLOCKED;
4913 }
4914 break;
4915 case STOP_WAITING_FRAME:
4916 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -07004917 "Attempt to append type byte of STOP WAITING frame in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05004918 return RaiseError(QUIC_INTERNAL_ERROR);
4919 case PING_FRAME:
4920 type_byte = IETF_PING;
4921 break;
4922 case STREAM_FRAME:
4923 type_byte =
4924 GetStreamFrameTypeByte(frame.stream_frame, last_frame_in_packet);
4925 break;
4926 case ACK_FRAME:
4927 // Do nothing here, AppendIetfAckFrameAndTypeByte() will put the type byte
4928 // in the buffer.
4929 return true;
4930 case MTU_DISCOVERY_FRAME:
4931 // The path MTU discovery frame is encoded as a PING frame on the wire.
4932 type_byte = IETF_PING;
4933 break;
QUICHE teama6ef0a62019-03-07 20:34:33 -05004934 case NEW_CONNECTION_ID_FRAME:
4935 type_byte = IETF_NEW_CONNECTION_ID;
4936 break;
4937 case RETIRE_CONNECTION_ID_FRAME:
4938 type_byte = IETF_RETIRE_CONNECTION_ID;
4939 break;
4940 case NEW_TOKEN_FRAME:
4941 type_byte = IETF_NEW_TOKEN;
4942 break;
fkastenholz3c4eabf2019-04-22 07:49:59 -07004943 case MAX_STREAMS_FRAME:
4944 if (frame.max_streams_frame.unidirectional) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05004945 type_byte = IETF_MAX_STREAMS_UNIDIRECTIONAL;
fkastenholz3c4eabf2019-04-22 07:49:59 -07004946 } else {
4947 type_byte = IETF_MAX_STREAMS_BIDIRECTIONAL;
QUICHE teama6ef0a62019-03-07 20:34:33 -05004948 }
4949 break;
fkastenholz3c4eabf2019-04-22 07:49:59 -07004950 case STREAMS_BLOCKED_FRAME:
4951 if (frame.streams_blocked_frame.unidirectional) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05004952 type_byte = IETF_STREAMS_BLOCKED_UNIDIRECTIONAL;
fkastenholz3c4eabf2019-04-22 07:49:59 -07004953 } else {
4954 type_byte = IETF_STREAMS_BLOCKED_BIDIRECTIONAL;
QUICHE teama6ef0a62019-03-07 20:34:33 -05004955 }
4956 break;
4957 case PATH_RESPONSE_FRAME:
4958 type_byte = IETF_PATH_RESPONSE;
4959 break;
4960 case PATH_CHALLENGE_FRAME:
4961 type_byte = IETF_PATH_CHALLENGE;
4962 break;
4963 case STOP_SENDING_FRAME:
4964 type_byte = IETF_STOP_SENDING;
4965 break;
4966 case MESSAGE_FRAME:
4967 return true;
4968 case CRYPTO_FRAME:
4969 type_byte = IETF_CRYPTO;
4970 break;
4971 default:
4972 QUIC_BUG << "Attempt to generate a frame type for an unsupported value: "
4973 << frame.type;
4974 return false;
4975 }
4976 return writer->WriteUInt8(type_byte);
4977}
4978
4979// static
4980bool QuicFramer::AppendPacketNumber(QuicPacketNumberLength packet_number_length,
4981 QuicPacketNumber packet_number,
4982 QuicDataWriter* writer) {
4983 DCHECK(packet_number.IsInitialized());
4984 if (!IsValidPacketNumberLength(packet_number_length)) {
4985 QUIC_BUG << "Invalid packet_number_length: " << packet_number_length;
4986 return false;
4987 }
4988 return writer->WriteBytesToUInt64(packet_number_length,
4989 packet_number.ToUint64());
4990}
4991
4992// static
4993bool QuicFramer::AppendStreamId(size_t stream_id_length,
4994 QuicStreamId stream_id,
4995 QuicDataWriter* writer) {
4996 if (stream_id_length == 0 || stream_id_length > 4) {
4997 QUIC_BUG << "Invalid stream_id_length: " << stream_id_length;
4998 return false;
4999 }
5000 return writer->WriteBytesToUInt64(stream_id_length, stream_id);
5001}
5002
5003// static
5004bool QuicFramer::AppendStreamOffset(size_t offset_length,
5005 QuicStreamOffset offset,
5006 QuicDataWriter* writer) {
5007 if (offset_length == 1 || offset_length > 8) {
5008 QUIC_BUG << "Invalid stream_offset_length: " << offset_length;
5009 return false;
5010 }
5011
5012 return writer->WriteBytesToUInt64(offset_length, offset);
5013}
5014
5015// static
5016bool QuicFramer::AppendAckBlock(uint8_t gap,
5017 QuicPacketNumberLength length_length,
5018 uint64_t length,
5019 QuicDataWriter* writer) {
5020 if (length == 0) {
5021 if (!IsValidPacketNumberLength(length_length)) {
5022 QUIC_BUG << "Invalid packet_number_length: " << length_length;
5023 return false;
5024 }
5025 return writer->WriteUInt8(gap) &&
5026 writer->WriteBytesToUInt64(length_length, length);
5027 }
5028 return writer->WriteUInt8(gap) &&
5029 AppendPacketNumber(length_length, QuicPacketNumber(length), writer);
5030}
5031
5032bool QuicFramer::AppendStreamFrame(const QuicStreamFrame& frame,
5033 bool no_stream_frame_length,
5034 QuicDataWriter* writer) {
fkastenholz305e1732019-06-18 05:01:22 -07005035 if (VersionHasIetfQuicFrames(version_.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005036 return AppendIetfStreamFrame(frame, no_stream_frame_length, writer);
5037 }
5038 if (!AppendStreamId(GetStreamIdSize(frame.stream_id), frame.stream_id,
5039 writer)) {
5040 QUIC_BUG << "Writing stream id size failed.";
5041 return false;
5042 }
5043 if (!AppendStreamOffset(
5044 GetStreamOffsetSize(version_.transport_version, frame.offset),
5045 frame.offset, writer)) {
5046 QUIC_BUG << "Writing offset size failed.";
5047 return false;
5048 }
5049 if (!no_stream_frame_length) {
dschinazi878cfb52019-06-17 17:12:58 -07005050 static_assert(
wubeff50282019-06-19 09:04:30 -07005051 std::numeric_limits<decltype(frame.data_length)>::max() <=
dschinazi878cfb52019-06-17 17:12:58 -07005052 std::numeric_limits<uint16_t>::max(),
5053 "If frame.data_length can hold more than a uint16_t than we need to "
5054 "check that frame.data_length <= std::numeric_limits<uint16_t>::max()");
5055 if (!writer->WriteUInt16(static_cast<uint16_t>(frame.data_length))) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005056 QUIC_BUG << "Writing stream frame length failed";
5057 return false;
5058 }
5059 }
5060
5061 if (data_producer_ != nullptr) {
5062 DCHECK_EQ(nullptr, frame.data_buffer);
5063 if (frame.data_length == 0) {
5064 return true;
5065 }
5066 if (data_producer_->WriteStreamData(frame.stream_id, frame.offset,
5067 frame.data_length,
5068 writer) != WRITE_SUCCESS) {
5069 QUIC_BUG << "Writing frame data failed.";
5070 return false;
5071 }
5072 return true;
5073 }
5074
5075 if (!writer->WriteBytes(frame.data_buffer, frame.data_length)) {
5076 QUIC_BUG << "Writing frame data failed.";
5077 return false;
5078 }
5079 return true;
5080}
5081
QUICHE teama6ef0a62019-03-07 20:34:33 -05005082bool QuicFramer::AppendNewTokenFrame(const QuicNewTokenFrame& frame,
5083 QuicDataWriter* writer) {
5084 if (!writer->WriteVarInt62(static_cast<uint64_t>(frame.token.length()))) {
5085 set_detailed_error("Writing token length failed.");
5086 return false;
5087 }
5088 if (!writer->WriteBytes(frame.token.data(), frame.token.length())) {
5089 set_detailed_error("Writing token buffer failed.");
5090 return false;
5091 }
5092 return true;
5093}
5094
5095bool QuicFramer::ProcessNewTokenFrame(QuicDataReader* reader,
5096 QuicNewTokenFrame* frame) {
5097 uint64_t length;
5098 if (!reader->ReadVarInt62(&length)) {
5099 set_detailed_error("Unable to read new token length.");
5100 return false;
5101 }
5102 if (length > kMaxNewTokenTokenLength) {
5103 set_detailed_error("Token length larger than maximum.");
5104 return false;
5105 }
5106
5107 // TODO(ianswett): Don't use QuicStringPiece as an intermediary.
5108 QuicStringPiece data;
5109 if (!reader->ReadStringPiece(&data, length)) {
5110 set_detailed_error("Unable to read new token data.");
5111 return false;
5112 }
vasilvvc48c8712019-03-11 13:38:16 -07005113 frame->token = std::string(data);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005114 return true;
5115}
5116
5117// Add a new ietf-format stream frame.
5118// Bits controlling whether there is a frame-length and frame-offset
5119// are in the QuicStreamFrame.
5120bool QuicFramer::AppendIetfStreamFrame(const QuicStreamFrame& frame,
5121 bool last_frame_in_packet,
5122 QuicDataWriter* writer) {
5123 if (!writer->WriteVarInt62(static_cast<uint64_t>(frame.stream_id))) {
5124 set_detailed_error("Writing stream id failed.");
5125 return false;
5126 }
5127
5128 if (frame.offset != 0) {
5129 if (!writer->WriteVarInt62(static_cast<uint64_t>(frame.offset))) {
5130 set_detailed_error("Writing data offset failed.");
5131 return false;
5132 }
5133 }
5134
5135 if (!last_frame_in_packet) {
5136 if (!writer->WriteVarInt62(frame.data_length)) {
5137 set_detailed_error("Writing data length failed.");
5138 return false;
5139 }
5140 }
5141
5142 if (frame.data_length == 0) {
5143 return true;
5144 }
5145 if (data_producer_ == nullptr) {
5146 if (!writer->WriteBytes(frame.data_buffer, frame.data_length)) {
5147 set_detailed_error("Writing frame data failed.");
5148 return false;
5149 }
5150 } else {
5151 DCHECK_EQ(nullptr, frame.data_buffer);
5152
5153 if (data_producer_->WriteStreamData(frame.stream_id, frame.offset,
5154 frame.data_length,
5155 writer) != WRITE_SUCCESS) {
5156 set_detailed_error("Writing frame data failed.");
5157 return false;
5158 }
5159 }
5160 return true;
5161}
5162
5163bool QuicFramer::AppendCryptoFrame(const QuicCryptoFrame& frame,
5164 QuicDataWriter* writer) {
5165 if (!writer->WriteVarInt62(static_cast<uint64_t>(frame.offset))) {
5166 set_detailed_error("Writing data offset failed.");
5167 return false;
5168 }
5169 if (!writer->WriteVarInt62(static_cast<uint64_t>(frame.data_length))) {
5170 set_detailed_error("Writing data length failed.");
5171 return false;
5172 }
5173 if (data_producer_ == nullptr) {
5174 if (frame.data_buffer == nullptr ||
5175 !writer->WriteBytes(frame.data_buffer, frame.data_length)) {
5176 set_detailed_error("Writing frame data failed.");
5177 return false;
5178 }
5179 } else {
5180 DCHECK_EQ(nullptr, frame.data_buffer);
5181 if (!data_producer_->WriteCryptoData(frame.level, frame.offset,
5182 frame.data_length, writer)) {
5183 return false;
5184 }
5185 }
5186 return true;
5187}
5188
5189void QuicFramer::set_version(const ParsedQuicVersion version) {
5190 DCHECK(IsSupportedVersion(version)) << ParsedQuicVersionToString(version);
5191 version_ = version;
5192}
5193
5194bool QuicFramer::AppendAckFrameAndTypeByte(const QuicAckFrame& frame,
5195 QuicDataWriter* writer) {
fkastenholz305e1732019-06-18 05:01:22 -07005196 if (VersionHasIetfQuicFrames(transport_version())) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005197 return AppendIetfAckFrameAndTypeByte(frame, writer);
5198 }
5199
5200 const AckFrameInfo new_ack_info = GetAckFrameInfo(frame);
5201 QuicPacketNumber largest_acked = LargestAcked(frame);
5202 QuicPacketNumberLength largest_acked_length =
5203 GetMinPacketNumberLength(version_.transport_version, largest_acked);
5204 QuicPacketNumberLength ack_block_length =
5205 GetMinPacketNumberLength(version_.transport_version,
5206 QuicPacketNumber(new_ack_info.max_block_length));
5207 // Calculate available bytes for timestamps and ack blocks.
5208 int32_t available_timestamp_and_ack_block_bytes =
5209 writer->capacity() - writer->length() - ack_block_length -
5210 GetMinAckFrameSize(version_.transport_version, largest_acked_length) -
5211 (new_ack_info.num_ack_blocks != 0 ? kNumberOfAckBlocksSize : 0);
5212 DCHECK_LE(0, available_timestamp_and_ack_block_bytes);
5213
5214 // Write out the type byte by setting the low order bits and doing shifts
5215 // to make room for the next bit flags to be set.
5216 // Whether there are multiple ack blocks.
5217 uint8_t type_byte = 0;
5218 SetBit(&type_byte, new_ack_info.num_ack_blocks != 0,
5219 kQuicHasMultipleAckBlocksOffset);
5220
5221 SetBits(&type_byte, GetPacketNumberFlags(largest_acked_length),
5222 kQuicSequenceNumberLengthNumBits, kLargestAckedOffset);
5223
5224 SetBits(&type_byte, GetPacketNumberFlags(ack_block_length),
5225 kQuicSequenceNumberLengthNumBits, kActBlockLengthOffset);
5226
5227 type_byte |= kQuicFrameTypeAckMask;
5228
5229 if (!writer->WriteUInt8(type_byte)) {
5230 return false;
5231 }
5232
5233 size_t max_num_ack_blocks = available_timestamp_and_ack_block_bytes /
5234 (ack_block_length + PACKET_1BYTE_PACKET_NUMBER);
5235
5236 // Number of ack blocks.
5237 size_t num_ack_blocks =
5238 std::min(new_ack_info.num_ack_blocks, max_num_ack_blocks);
5239 if (num_ack_blocks > std::numeric_limits<uint8_t>::max()) {
5240 num_ack_blocks = std::numeric_limits<uint8_t>::max();
5241 }
5242
5243 // Largest acked.
5244 if (!AppendPacketNumber(largest_acked_length, largest_acked, writer)) {
5245 return false;
5246 }
5247
5248 // Largest acked delta time.
5249 uint64_t ack_delay_time_us = kUFloat16MaxValue;
5250 if (!frame.ack_delay_time.IsInfinite()) {
5251 DCHECK_LE(0u, frame.ack_delay_time.ToMicroseconds());
5252 ack_delay_time_us = frame.ack_delay_time.ToMicroseconds();
5253 }
5254 if (!writer->WriteUFloat16(ack_delay_time_us)) {
5255 return false;
5256 }
5257
5258 if (num_ack_blocks > 0) {
5259 if (!writer->WriteBytes(&num_ack_blocks, 1)) {
5260 return false;
5261 }
5262 }
5263
5264 // First ack block length.
5265 if (!AppendPacketNumber(ack_block_length,
5266 QuicPacketNumber(new_ack_info.first_block_length),
5267 writer)) {
5268 return false;
5269 }
5270
5271 // Ack blocks.
5272 if (num_ack_blocks > 0) {
5273 size_t num_ack_blocks_written = 0;
5274 // Append, in descending order from the largest ACKed packet, a series of
5275 // ACK blocks that represents the successfully acknoweldged packets. Each
5276 // appended gap/block length represents a descending delta from the previous
5277 // block. i.e.:
5278 // |--- length ---|--- gap ---|--- length ---|--- gap ---|--- largest ---|
5279 // For gaps larger than can be represented by a single encoded gap, a 0
5280 // length gap of the maximum is used, i.e.:
5281 // |--- length ---|--- gap ---|- 0 -|--- gap ---|--- largest ---|
5282 auto itr = frame.packets.rbegin();
5283 QuicPacketNumber previous_start = itr->min();
5284 ++itr;
5285
5286 for (;
5287 itr != frame.packets.rend() && num_ack_blocks_written < num_ack_blocks;
5288 previous_start = itr->min(), ++itr) {
5289 const auto& interval = *itr;
5290 const uint64_t total_gap = previous_start - interval.max();
5291 const size_t num_encoded_gaps =
5292 (total_gap + std::numeric_limits<uint8_t>::max() - 1) /
5293 std::numeric_limits<uint8_t>::max();
QUICHE teama6ef0a62019-03-07 20:34:33 -05005294
5295 // Append empty ACK blocks because the gap is longer than a single gap.
5296 for (size_t i = 1;
5297 i < num_encoded_gaps && num_ack_blocks_written < num_ack_blocks;
5298 ++i) {
5299 if (!AppendAckBlock(std::numeric_limits<uint8_t>::max(),
5300 ack_block_length, 0, writer)) {
5301 return false;
5302 }
5303 ++num_ack_blocks_written;
5304 }
5305 if (num_ack_blocks_written >= num_ack_blocks) {
5306 if (QUIC_PREDICT_FALSE(num_ack_blocks_written != num_ack_blocks)) {
5307 QUIC_BUG << "Wrote " << num_ack_blocks_written
5308 << ", expected to write " << num_ack_blocks;
5309 }
5310 break;
5311 }
5312
5313 const uint8_t last_gap =
5314 total_gap -
5315 (num_encoded_gaps - 1) * std::numeric_limits<uint8_t>::max();
5316 // Append the final ACK block with a non-empty size.
5317 if (!AppendAckBlock(last_gap, ack_block_length,
5318 PacketNumberIntervalLength(interval), writer)) {
5319 return false;
5320 }
5321 ++num_ack_blocks_written;
5322 }
5323 DCHECK_EQ(num_ack_blocks, num_ack_blocks_written);
5324 }
5325 // Timestamps.
5326 // If we don't process timestamps or if we don't have enough available space
5327 // to append all the timestamps, don't append any of them.
5328 if (process_timestamps_ && writer->capacity() - writer->length() >=
5329 GetAckFrameTimeStampSize(frame)) {
5330 if (!AppendTimestampsToAckFrame(frame, writer)) {
5331 return false;
5332 }
5333 } else {
5334 uint8_t num_received_packets = 0;
5335 if (!writer->WriteBytes(&num_received_packets, 1)) {
5336 return false;
5337 }
5338 }
5339
5340 return true;
5341}
5342
5343bool QuicFramer::AppendTimestampsToAckFrame(const QuicAckFrame& frame,
5344 QuicDataWriter* writer) {
5345 DCHECK_GE(std::numeric_limits<uint8_t>::max(),
5346 frame.received_packet_times.size());
5347 // num_received_packets is only 1 byte.
5348 if (frame.received_packet_times.size() >
5349 std::numeric_limits<uint8_t>::max()) {
5350 return false;
5351 }
5352
5353 uint8_t num_received_packets = frame.received_packet_times.size();
5354 if (!writer->WriteBytes(&num_received_packets, 1)) {
5355 return false;
5356 }
5357 if (num_received_packets == 0) {
5358 return true;
5359 }
5360
5361 auto it = frame.received_packet_times.begin();
5362 QuicPacketNumber packet_number = it->first;
5363 uint64_t delta_from_largest_observed = LargestAcked(frame) - packet_number;
5364
5365 DCHECK_GE(std::numeric_limits<uint8_t>::max(), delta_from_largest_observed);
5366 if (delta_from_largest_observed > std::numeric_limits<uint8_t>::max()) {
5367 return false;
5368 }
5369
5370 if (!writer->WriteUInt8(delta_from_largest_observed)) {
5371 return false;
5372 }
5373
5374 // Use the lowest 4 bytes of the time delta from the creation_time_.
5375 const uint64_t time_epoch_delta_us = UINT64_C(1) << 32;
5376 uint32_t time_delta_us =
5377 static_cast<uint32_t>((it->second - creation_time_).ToMicroseconds() &
5378 (time_epoch_delta_us - 1));
5379 if (!writer->WriteUInt32(time_delta_us)) {
5380 return false;
5381 }
5382
5383 QuicTime prev_time = it->second;
5384
5385 for (++it; it != frame.received_packet_times.end(); ++it) {
5386 packet_number = it->first;
5387 delta_from_largest_observed = LargestAcked(frame) - packet_number;
5388
5389 if (delta_from_largest_observed > std::numeric_limits<uint8_t>::max()) {
5390 return false;
5391 }
5392
5393 if (!writer->WriteUInt8(delta_from_largest_observed)) {
5394 return false;
5395 }
5396
5397 uint64_t frame_time_delta_us = (it->second - prev_time).ToMicroseconds();
5398 prev_time = it->second;
5399 if (!writer->WriteUFloat16(frame_time_delta_us)) {
5400 return false;
5401 }
5402 }
5403 return true;
5404}
5405
5406bool QuicFramer::AppendStopWaitingFrame(const QuicPacketHeader& header,
5407 const QuicStopWaitingFrame& frame,
5408 QuicDataWriter* writer) {
fayangd4291e42019-05-30 10:31:21 -07005409 DCHECK(!VersionHasIetfInvariantHeader(version_.transport_version));
QUICHE teama6ef0a62019-03-07 20:34:33 -05005410 DCHECK(frame.least_unacked.IsInitialized() &&
5411 header.packet_number >= frame.least_unacked);
5412 const uint64_t least_unacked_delta =
5413 header.packet_number - frame.least_unacked;
5414 const uint64_t length_shift = header.packet_number_length * 8;
5415
5416 if (least_unacked_delta >> length_shift > 0) {
5417 QUIC_BUG << "packet_number_length " << header.packet_number_length
5418 << " is too small for least_unacked_delta: " << least_unacked_delta
5419 << " packet_number:" << header.packet_number
5420 << " least_unacked:" << frame.least_unacked
5421 << " version:" << version_.transport_version;
5422 return false;
5423 }
5424 if (least_unacked_delta == 0) {
5425 return writer->WriteBytesToUInt64(header.packet_number_length,
5426 least_unacked_delta);
5427 }
5428 if (!AppendPacketNumber(header.packet_number_length,
5429 QuicPacketNumber(least_unacked_delta), writer)) {
5430 QUIC_BUG << " seq failed: " << header.packet_number_length;
5431 return false;
5432 }
5433
5434 return true;
5435}
5436
5437int QuicFramer::CalculateIetfAckBlockCount(const QuicAckFrame& frame,
dschinazi17d42422019-06-18 16:35:07 -07005438 QuicDataWriter* /*writer*/,
QUICHE teama6ef0a62019-03-07 20:34:33 -05005439 size_t available_space) {
5440 // Number of blocks requested in the frame
5441 uint64_t ack_block_count = frame.packets.NumIntervals();
5442
5443 auto itr = frame.packets.rbegin();
5444
5445 int actual_block_count = 1;
5446 uint64_t block_length = itr->max() - itr->min();
5447 size_t encoded_size = QuicDataWriter::GetVarInt62Len(block_length);
5448 if (encoded_size > available_space) {
5449 return 0;
5450 }
5451 available_space -= encoded_size;
5452 QuicPacketNumber previous_ack_end = itr->min();
5453 ack_block_count--;
5454
5455 while (ack_block_count) {
5456 // Each block is a gap followed by another ACK. Calculate each value,
5457 // determine the encoded lengths, and check against the available space.
5458 itr++;
5459 size_t gap = previous_ack_end - itr->max() - 1;
5460 encoded_size = QuicDataWriter::GetVarInt62Len(gap);
5461
5462 // Add the ACK block.
5463 block_length = itr->max() - itr->min();
5464 encoded_size += QuicDataWriter::GetVarInt62Len(block_length);
5465
5466 if (encoded_size > available_space) {
5467 // No room for this block, so what we've
5468 // done up to now is all that can be done.
5469 return actual_block_count;
5470 }
5471 available_space -= encoded_size;
5472 actual_block_count++;
5473 previous_ack_end = itr->min();
5474 ack_block_count--;
5475 }
5476 // Ran through the whole thing! We can do all blocks.
5477 return actual_block_count;
5478}
5479
5480bool QuicFramer::AppendIetfAckFrameAndTypeByte(const QuicAckFrame& frame,
5481 QuicDataWriter* writer) {
5482 // Assume frame is an IETF_ACK frame. If |ecn_counters_populated| is true and
5483 // any of the ECN counters is non-0 then turn it into an IETF_ACK+ECN frame.
5484 uint8_t type = IETF_ACK;
5485 if (frame.ecn_counters_populated &&
5486 (frame.ect_0_count || frame.ect_1_count || frame.ecn_ce_count)) {
5487 type = IETF_ACK_ECN;
5488 }
5489
5490 if (!writer->WriteUInt8(type)) {
5491 set_detailed_error("No room for frame-type");
5492 return false;
5493 }
5494
5495 QuicPacketNumber largest_acked = LargestAcked(frame);
5496 if (!writer->WriteVarInt62(largest_acked.ToUint64())) {
5497 set_detailed_error("No room for largest-acked in ack frame");
5498 return false;
5499 }
5500
5501 uint64_t ack_delay_time_us = kVarInt62MaxValue;
5502 if (!frame.ack_delay_time.IsInfinite()) {
5503 DCHECK_LE(0u, frame.ack_delay_time.ToMicroseconds());
5504 ack_delay_time_us = frame.ack_delay_time.ToMicroseconds();
fkastenholz4dc4ba32019-07-30 09:55:25 -07005505 ack_delay_time_us = ack_delay_time_us >> local_ack_delay_exponent_;
QUICHE teama6ef0a62019-03-07 20:34:33 -05005506 }
5507
5508 if (!writer->WriteVarInt62(ack_delay_time_us)) {
5509 set_detailed_error("No room for ack-delay in ack frame");
5510 return false;
5511 }
5512 if (type == IETF_ACK_ECN) {
5513 // Encode the ACK ECN fields
5514 if (!writer->WriteVarInt62(frame.ect_0_count)) {
5515 set_detailed_error("No room for ect_0_count in ack frame");
5516 return false;
5517 }
5518 if (!writer->WriteVarInt62(frame.ect_1_count)) {
5519 set_detailed_error("No room for ect_1_count in ack frame");
5520 return false;
5521 }
5522 if (!writer->WriteVarInt62(frame.ecn_ce_count)) {
5523 set_detailed_error("No room for ecn_ce_count in ack frame");
5524 return false;
5525 }
5526 }
5527
5528 uint64_t ack_block_count = frame.packets.NumIntervals();
5529 if (ack_block_count == 0) {
5530 // If the QuicAckFrame has no Intervals, then it is interpreted
5531 // as an ack of a single packet at QuicAckFrame.largest_acked.
5532 // The resulting ack will consist of only the frame's
5533 // largest_ack & first_ack_block fields. The first ack block will be 0
5534 // (indicating a single packet) and the ack block_count will be 0.
5535 if (!writer->WriteVarInt62(0)) {
5536 set_detailed_error("No room for ack block count in ack frame");
5537 return false;
5538 }
5539 // size of the first block is 1 packet
5540 if (!writer->WriteVarInt62(0)) {
5541 set_detailed_error("No room for first ack block in ack frame");
5542 return false;
5543 }
5544 return true;
5545 }
5546 // Case 2 or 3
5547 auto itr = frame.packets.rbegin();
5548
5549 QuicPacketNumber ack_block_largest(largest_acked);
5550 QuicPacketNumber ack_block_smallest;
5551 if ((itr->max() - 1) == QuicPacketNumber(largest_acked)) {
5552 // If largest_acked + 1 is equal to the Max() of the first Interval
5553 // in the QuicAckFrame then the first Interval is the first ack block of the
5554 // frame; remaining Intervals are additional ack blocks. The QuicAckFrame's
5555 // first Interval is encoded in the frame's largest_acked/first_ack_block,
5556 // the remaining Intervals are encoded in additional ack blocks in the
5557 // frame, and the packet's ack_block_count is the number of QuicAckFrame
5558 // Intervals - 1.
5559 ack_block_smallest = itr->min();
5560 itr++;
5561 ack_block_count--;
5562 } else {
5563 // If QuicAckFrame.largest_acked is NOT equal to the Max() of
5564 // the first Interval then it is interpreted as acking a single
5565 // packet at QuicAckFrame.largest_acked, with additional
5566 // Intervals indicating additional ack blocks. The encoding is
5567 // a) The packet's largest_acked is the QuicAckFrame's largest
5568 // acked,
5569 // b) the first ack block size is 0,
5570 // c) The packet's ack_block_count is the number of QuicAckFrame
5571 // Intervals, and
5572 // d) The QuicAckFrame Intervals are encoded in additional ack
5573 // blocks in the packet.
5574 ack_block_smallest = largest_acked;
5575 }
5576
5577 if (!writer->WriteVarInt62(ack_block_count)) {
5578 set_detailed_error("No room for ack block count in ack frame");
5579 return false;
5580 }
5581
5582 uint64_t first_ack_block = ack_block_largest - ack_block_smallest;
5583 if (!writer->WriteVarInt62(first_ack_block)) {
5584 set_detailed_error("No room for first ack block in ack frame");
5585 return false;
5586 }
5587
5588 // For the remaining QuicAckFrame Intervals, if any
5589 while (ack_block_count != 0) {
5590 uint64_t gap_size = ack_block_smallest - itr->max();
5591 if (!writer->WriteVarInt62(gap_size - 1)) {
5592 set_detailed_error("No room for gap block in ack frame");
5593 return false;
5594 }
5595
5596 uint64_t block_size = itr->max() - itr->min();
5597 if (!writer->WriteVarInt62(block_size - 1)) {
5598 set_detailed_error("No room for nth ack block in ack frame");
5599 return false;
5600 }
5601
5602 ack_block_smallest = itr->min();
5603 itr++;
5604 ack_block_count--;
5605 }
5606 return true;
5607}
5608
5609bool QuicFramer::AppendRstStreamFrame(const QuicRstStreamFrame& frame,
5610 QuicDataWriter* writer) {
fkastenholz305e1732019-06-18 05:01:22 -07005611 if (VersionHasIetfQuicFrames(version_.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005612 return AppendIetfResetStreamFrame(frame, writer);
5613 }
5614 if (!writer->WriteUInt32(frame.stream_id)) {
5615 return false;
5616 }
5617
5618 if (!writer->WriteUInt64(frame.byte_offset)) {
5619 return false;
5620 }
5621
5622 uint32_t error_code = static_cast<uint32_t>(frame.error_code);
5623 if (!writer->WriteUInt32(error_code)) {
5624 return false;
5625 }
5626
5627 return true;
5628}
5629
5630bool QuicFramer::AppendConnectionCloseFrame(
5631 const QuicConnectionCloseFrame& frame,
5632 QuicDataWriter* writer) {
fkastenholz305e1732019-06-18 05:01:22 -07005633 if (VersionHasIetfQuicFrames(version_.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005634 return AppendIetfConnectionCloseFrame(frame, writer);
5635 }
fkastenholze9d71a82019-04-09 05:12:13 -07005636 uint32_t error_code = static_cast<uint32_t>(frame.quic_error_code);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005637 if (!writer->WriteUInt32(error_code)) {
5638 return false;
5639 }
5640 if (!writer->WriteStringPiece16(TruncateErrorString(frame.error_details))) {
5641 return false;
5642 }
5643 return true;
5644}
5645
5646bool QuicFramer::AppendGoAwayFrame(const QuicGoAwayFrame& frame,
5647 QuicDataWriter* writer) {
5648 uint32_t error_code = static_cast<uint32_t>(frame.error_code);
5649 if (!writer->WriteUInt32(error_code)) {
5650 return false;
5651 }
5652 uint32_t stream_id = static_cast<uint32_t>(frame.last_good_stream_id);
5653 if (!writer->WriteUInt32(stream_id)) {
5654 return false;
5655 }
5656 if (!writer->WriteStringPiece16(TruncateErrorString(frame.reason_phrase))) {
5657 return false;
5658 }
5659 return true;
5660}
5661
5662bool QuicFramer::AppendWindowUpdateFrame(const QuicWindowUpdateFrame& frame,
5663 QuicDataWriter* writer) {
5664 uint32_t stream_id = static_cast<uint32_t>(frame.stream_id);
5665 if (!writer->WriteUInt32(stream_id)) {
5666 return false;
5667 }
5668 if (!writer->WriteUInt64(frame.byte_offset)) {
5669 return false;
5670 }
5671 return true;
5672}
5673
5674bool QuicFramer::AppendBlockedFrame(const QuicBlockedFrame& frame,
5675 QuicDataWriter* writer) {
fkastenholz305e1732019-06-18 05:01:22 -07005676 if (VersionHasIetfQuicFrames(version_.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005677 if (frame.stream_id == QuicUtils::GetInvalidStreamId(transport_version())) {
5678 return AppendIetfBlockedFrame(frame, writer);
5679 }
5680 return AppendStreamBlockedFrame(frame, writer);
5681 }
5682 uint32_t stream_id = static_cast<uint32_t>(frame.stream_id);
5683 if (!writer->WriteUInt32(stream_id)) {
5684 return false;
5685 }
5686 return true;
5687}
5688
5689bool QuicFramer::AppendPaddingFrame(const QuicPaddingFrame& frame,
5690 QuicDataWriter* writer) {
5691 if (frame.num_padding_bytes == 0) {
5692 return false;
5693 }
5694 if (frame.num_padding_bytes < 0) {
5695 QUIC_BUG_IF(frame.num_padding_bytes != -1);
5696 writer->WritePadding();
5697 return true;
5698 }
5699 // Please note, num_padding_bytes includes type byte which has been written.
5700 return writer->WritePaddingBytes(frame.num_padding_bytes - 1);
5701}
5702
5703bool QuicFramer::AppendMessageFrameAndTypeByte(const QuicMessageFrame& frame,
5704 bool last_frame_in_packet,
5705 QuicDataWriter* writer) {
5706 uint8_t type_byte = last_frame_in_packet ? IETF_EXTENSION_MESSAGE_NO_LENGTH
5707 : IETF_EXTENSION_MESSAGE;
5708 if (!writer->WriteUInt8(type_byte)) {
5709 return false;
5710 }
5711 if (!last_frame_in_packet && !writer->WriteVarInt62(frame.message_length)) {
5712 return false;
5713 }
5714 for (const auto& slice : frame.message_data) {
5715 if (!writer->WriteBytes(slice.data(), slice.length())) {
5716 return false;
5717 }
5718 }
5719 return true;
5720}
5721
5722bool QuicFramer::RaiseError(QuicErrorCode error) {
5723 QUIC_DLOG(INFO) << ENDPOINT << "Error: " << QuicErrorCodeToString(error)
5724 << " detail: " << detailed_error_;
5725 set_error(error);
nharper55fa6132019-05-07 19:37:21 -07005726 if (visitor_) {
5727 visitor_->OnError(this);
5728 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05005729 return false;
5730}
5731
5732bool QuicFramer::IsVersionNegotiation(
5733 const QuicPacketHeader& header,
5734 bool packet_has_ietf_packet_header) const {
dschinazi072da7c2019-05-07 17:57:42 -07005735 if (!packet_has_ietf_packet_header &&
5736 perspective_ == Perspective::IS_CLIENT) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005737 return header.version_flag;
5738 }
5739 if (header.form == IETF_QUIC_SHORT_HEADER_PACKET) {
5740 return false;
5741 }
5742 return header.long_packet_type == VERSION_NEGOTIATION;
5743}
5744
QUICHE teama6ef0a62019-03-07 20:34:33 -05005745bool QuicFramer::AppendIetfConnectionCloseFrame(
5746 const QuicConnectionCloseFrame& frame,
5747 QuicDataWriter* writer) {
fkastenholz72f509b2019-04-10 09:17:49 -07005748 if (frame.close_type != IETF_QUIC_TRANSPORT_CONNECTION_CLOSE &&
5749 frame.close_type != IETF_QUIC_APPLICATION_CONNECTION_CLOSE) {
5750 QUIC_BUG << "Invalid close_type for writing IETF CONNECTION CLOSE.";
5751 set_detailed_error("Invalid close_type for writing IETF CONNECTION CLOSE.");
5752 return false;
5753 }
5754
fkastenholzd57d3f92019-07-16 09:05:17 -07005755 uint64_t close_code = 0;
5756 if (frame.close_type == IETF_QUIC_TRANSPORT_CONNECTION_CLOSE) {
5757 close_code = static_cast<uint64_t>(frame.transport_error_code);
5758 } else if (frame.close_type == IETF_QUIC_APPLICATION_CONNECTION_CLOSE) {
5759 close_code = static_cast<uint64_t>(frame.application_error_code);
5760 }
5761
5762 if (!writer->WriteVarInt62(close_code)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005763 set_detailed_error("Can not write connection close frame error code");
5764 return false;
5765 }
fkastenholze9d71a82019-04-09 05:12:13 -07005766
fkastenholz72f509b2019-04-10 09:17:49 -07005767 if (frame.close_type == IETF_QUIC_TRANSPORT_CONNECTION_CLOSE) {
5768 // Write the frame-type of the frame causing the error only
5769 // if it's a CONNECTION_CLOSE/Transport.
5770 if (!writer->WriteVarInt62(frame.transport_close_frame_type)) {
5771 set_detailed_error("Writing frame type failed.");
5772 return false;
5773 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05005774 }
5775
fkastenholzb4dade72019-08-05 06:54:20 -07005776 // There may be additional error information available in the extracted error
5777 // code. Encode the error information in the reason phrase and serialize the
5778 // result.
5779 std::string final_error_string =
5780 GenerateErrorString(frame.error_details, frame.extracted_error_code);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005781 if (!writer->WriteStringPieceVarInt62(
fkastenholzb4dade72019-08-05 06:54:20 -07005782 TruncateErrorString(final_error_string))) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005783 set_detailed_error("Can not write connection close phrase");
5784 return false;
5785 }
5786 return true;
5787}
5788
QUICHE teama6ef0a62019-03-07 20:34:33 -05005789bool QuicFramer::ProcessIetfConnectionCloseFrame(
5790 QuicDataReader* reader,
fkastenholze9d71a82019-04-09 05:12:13 -07005791 QuicConnectionCloseType type,
QUICHE teama6ef0a62019-03-07 20:34:33 -05005792 QuicConnectionCloseFrame* frame) {
fkastenholze9d71a82019-04-09 05:12:13 -07005793 frame->close_type = type;
fkastenholzd57d3f92019-07-16 09:05:17 -07005794 uint64_t error_code;
fkastenholzb4dade72019-08-05 06:54:20 -07005795
fkastenholzd57d3f92019-07-16 09:05:17 -07005796 if (!reader->ReadVarInt62(&error_code)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005797 set_detailed_error("Unable to read connection close error code.");
5798 return false;
5799 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05005800
fkastenholzb4dade72019-08-05 06:54:20 -07005801 // TODO(fkastenholz): When error codes uniformly go to uint64, remove the
5802 // range check.
fkastenholzd57d3f92019-07-16 09:05:17 -07005803 if (frame->close_type == IETF_QUIC_TRANSPORT_CONNECTION_CLOSE) {
5804 if (error_code > 0xffff) {
5805 frame->transport_error_code =
5806 static_cast<QuicIetfTransportErrorCodes>(0xffff);
5807 QUIC_DLOG(ERROR) << "Transport error code " << error_code << " > 0xffff";
5808 } else {
5809 frame->transport_error_code =
5810 static_cast<QuicIetfTransportErrorCodes>(error_code);
5811 }
5812 } else if (frame->close_type == IETF_QUIC_APPLICATION_CONNECTION_CLOSE) {
5813 if (error_code > 0xffff) {
5814 frame->application_error_code = 0xffff;
5815 QUIC_DLOG(ERROR) << "Application error code " << error_code
5816 << " > 0xffff";
5817 } else {
5818 frame->application_error_code = static_cast<uint16_t>(error_code);
5819 }
5820 }
fkastenholzb4dade72019-08-05 06:54:20 -07005821
fkastenholz72f509b2019-04-10 09:17:49 -07005822 if (type == IETF_QUIC_TRANSPORT_CONNECTION_CLOSE) {
5823 // The frame-type of the frame causing the error is present only
5824 // if it's a CONNECTION_CLOSE/Transport.
5825 if (!reader->ReadVarInt62(&frame->transport_close_frame_type)) {
5826 set_detailed_error("Unable to read connection close frame type.");
5827 return false;
5828 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05005829 }
5830
5831 uint64_t phrase_length;
5832 if (!reader->ReadVarInt62(&phrase_length)) {
5833 set_detailed_error("Unable to read connection close error details.");
5834 return false;
5835 }
fkastenholzb4dade72019-08-05 06:54:20 -07005836
QUICHE teama6ef0a62019-03-07 20:34:33 -05005837 QuicStringPiece phrase;
5838 if (!reader->ReadStringPiece(&phrase, static_cast<size_t>(phrase_length))) {
5839 set_detailed_error("Unable to read connection close error details.");
5840 return false;
5841 }
vasilvvc48c8712019-03-11 13:38:16 -07005842 frame->error_details = std::string(phrase);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005843
fkastenholzb4dade72019-08-05 06:54:20 -07005844 // The frame may have an extracted error code in it. Look for it and
5845 // extract it. If it's not present, MaybeExtract will return
5846 // QUIC_IETF_GQUIC_ERROR_MISSING.
5847 frame->extracted_error_code = MaybeExtractQuicErrorCode(phrase);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005848 return true;
5849}
5850
5851// IETF Quic Path Challenge/Response frames.
5852bool QuicFramer::ProcessPathChallengeFrame(QuicDataReader* reader,
5853 QuicPathChallengeFrame* frame) {
5854 if (!reader->ReadBytes(frame->data_buffer.data(),
5855 frame->data_buffer.size())) {
5856 set_detailed_error("Can not read path challenge data.");
5857 return false;
5858 }
5859 return true;
5860}
5861
5862bool QuicFramer::ProcessPathResponseFrame(QuicDataReader* reader,
5863 QuicPathResponseFrame* frame) {
5864 if (!reader->ReadBytes(frame->data_buffer.data(),
5865 frame->data_buffer.size())) {
5866 set_detailed_error("Can not read path response data.");
5867 return false;
5868 }
5869 return true;
5870}
5871
5872bool QuicFramer::AppendPathChallengeFrame(const QuicPathChallengeFrame& frame,
5873 QuicDataWriter* writer) {
5874 if (!writer->WriteBytes(frame.data_buffer.data(), frame.data_buffer.size())) {
5875 set_detailed_error("Writing Path Challenge data failed.");
5876 return false;
5877 }
5878 return true;
5879}
5880
5881bool QuicFramer::AppendPathResponseFrame(const QuicPathResponseFrame& frame,
5882 QuicDataWriter* writer) {
5883 if (!writer->WriteBytes(frame.data_buffer.data(), frame.data_buffer.size())) {
5884 set_detailed_error("Writing Path Response data failed.");
5885 return false;
5886 }
5887 return true;
5888}
5889
5890// Add a new ietf-format stream reset frame.
5891// General format is
5892// stream id
5893// application error code
5894// final offset
5895bool QuicFramer::AppendIetfResetStreamFrame(const QuicRstStreamFrame& frame,
5896 QuicDataWriter* writer) {
5897 if (!writer->WriteVarInt62(static_cast<uint64_t>(frame.stream_id))) {
5898 set_detailed_error("Writing reset-stream stream id failed.");
5899 return false;
5900 }
fkastenholz07300e52019-07-16 11:51:37 -07005901 if (!writer->WriteVarInt62(static_cast<uint64_t>(frame.ietf_error_code))) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005902 set_detailed_error("Writing reset-stream error code failed.");
5903 return false;
5904 }
5905 if (!writer->WriteVarInt62(static_cast<uint64_t>(frame.byte_offset))) {
5906 set_detailed_error("Writing reset-stream final-offset failed.");
5907 return false;
5908 }
5909 return true;
5910}
5911
5912bool QuicFramer::ProcessIetfResetStreamFrame(QuicDataReader* reader,
5913 QuicRstStreamFrame* frame) {
5914 // Get Stream ID from frame. ReadVarIntStreamID returns false
5915 // if either A) there is a read error or B) the resulting value of
5916 // the Stream ID is larger than the maximum allowed value.
fkastenholz3c4eabf2019-04-22 07:49:59 -07005917 if (!reader->ReadVarIntU32(&frame->stream_id)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005918 set_detailed_error("Unable to read rst stream stream id.");
5919 return false;
5920 }
5921
fkastenholz07300e52019-07-16 11:51:37 -07005922 uint64_t error_code;
5923 if (!reader->ReadVarInt62(&error_code)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005924 set_detailed_error("Unable to read rst stream error code.");
5925 return false;
5926 }
fkastenholz07300e52019-07-16 11:51:37 -07005927 if (error_code > 0xffff) {
5928 frame->ietf_error_code = 0xffff;
5929 QUIC_DLOG(ERROR) << "Reset stream error code (" << error_code
5930 << ") > 0xffff";
5931 } else {
5932 frame->ietf_error_code = static_cast<uint16_t>(error_code);
5933 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05005934
5935 if (!reader->ReadVarInt62(&frame->byte_offset)) {
5936 set_detailed_error("Unable to read rst stream sent byte offset.");
5937 return false;
5938 }
5939 return true;
5940}
5941
5942bool QuicFramer::ProcessStopSendingFrame(
5943 QuicDataReader* reader,
5944 QuicStopSendingFrame* stop_sending_frame) {
fkastenholz3c4eabf2019-04-22 07:49:59 -07005945 if (!reader->ReadVarIntU32(&stop_sending_frame->stream_id)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005946 set_detailed_error("Unable to read stop sending stream id.");
5947 return false;
5948 }
5949
fkastenholz733552e2019-07-16 11:16:58 -07005950 uint64_t error_code;
5951 if (!reader->ReadVarInt62(&error_code)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005952 set_detailed_error("Unable to read stop sending application error code.");
5953 return false;
5954 }
fkastenholz733552e2019-07-16 11:16:58 -07005955 // TODO(fkastenholz): when error codes go to uint64_t, remove this.
5956 if (error_code > 0xffff) {
5957 stop_sending_frame->application_error_code = 0xffff;
5958 QUIC_DLOG(ERROR) << "Stop sending error code (" << error_code
5959 << ") > 0xffff";
5960 } else {
5961 stop_sending_frame->application_error_code =
5962 static_cast<uint16_t>(error_code);
5963 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05005964 return true;
5965}
5966
5967bool QuicFramer::AppendStopSendingFrame(
5968 const QuicStopSendingFrame& stop_sending_frame,
5969 QuicDataWriter* writer) {
5970 if (!writer->WriteVarInt62(stop_sending_frame.stream_id)) {
5971 set_detailed_error("Can not write stop sending stream id");
5972 return false;
5973 }
fkastenholz733552e2019-07-16 11:16:58 -07005974 if (!writer->WriteVarInt62(
5975 static_cast<uint64_t>(stop_sending_frame.application_error_code))) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005976 set_detailed_error("Can not write application error code");
5977 return false;
5978 }
5979 return true;
5980}
5981
5982// Append/process IETF-Format MAX_DATA Frame
5983bool QuicFramer::AppendMaxDataFrame(const QuicWindowUpdateFrame& frame,
5984 QuicDataWriter* writer) {
5985 if (!writer->WriteVarInt62(frame.byte_offset)) {
5986 set_detailed_error("Can not write MAX_DATA byte-offset");
5987 return false;
5988 }
5989 return true;
5990}
5991
5992bool QuicFramer::ProcessMaxDataFrame(QuicDataReader* reader,
5993 QuicWindowUpdateFrame* frame) {
5994 frame->stream_id = QuicUtils::GetInvalidStreamId(transport_version());
5995 if (!reader->ReadVarInt62(&frame->byte_offset)) {
5996 set_detailed_error("Can not read MAX_DATA byte-offset");
5997 return false;
5998 }
5999 return true;
6000}
6001
6002// Append/process IETF-Format MAX_STREAM_DATA Frame
6003bool QuicFramer::AppendMaxStreamDataFrame(const QuicWindowUpdateFrame& frame,
6004 QuicDataWriter* writer) {
6005 if (!writer->WriteVarInt62(frame.stream_id)) {
6006 set_detailed_error("Can not write MAX_STREAM_DATA stream id");
6007 return false;
6008 }
6009 if (!writer->WriteVarInt62(frame.byte_offset)) {
6010 set_detailed_error("Can not write MAX_STREAM_DATA byte-offset");
6011 return false;
6012 }
6013 return true;
6014}
6015
6016bool QuicFramer::ProcessMaxStreamDataFrame(QuicDataReader* reader,
6017 QuicWindowUpdateFrame* frame) {
fkastenholz3c4eabf2019-04-22 07:49:59 -07006018 if (!reader->ReadVarIntU32(&frame->stream_id)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05006019 set_detailed_error("Can not read MAX_STREAM_DATA stream id");
6020 return false;
6021 }
6022 if (!reader->ReadVarInt62(&frame->byte_offset)) {
6023 set_detailed_error("Can not read MAX_STREAM_DATA byte-count");
6024 return false;
6025 }
6026 return true;
6027}
6028
fkastenholz3c4eabf2019-04-22 07:49:59 -07006029bool QuicFramer::AppendMaxStreamsFrame(const QuicMaxStreamsFrame& frame,
QUICHE teama6ef0a62019-03-07 20:34:33 -05006030 QuicDataWriter* writer) {
fkastenholz3c4eabf2019-04-22 07:49:59 -07006031 if (!writer->WriteVarInt62(frame.stream_count)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05006032 set_detailed_error("Can not write MAX_STREAMS stream count");
6033 return false;
6034 }
6035 return true;
6036}
6037
6038bool QuicFramer::ProcessMaxStreamsFrame(QuicDataReader* reader,
fkastenholz3c4eabf2019-04-22 07:49:59 -07006039 QuicMaxStreamsFrame* frame,
QUICHE teama6ef0a62019-03-07 20:34:33 -05006040 uint64_t frame_type) {
fkastenholz3c4eabf2019-04-22 07:49:59 -07006041 if (!reader->ReadVarIntU32(&frame->stream_count)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05006042 set_detailed_error("Can not read MAX_STREAMS stream count.");
6043 return false;
6044 }
fkastenholz3c4eabf2019-04-22 07:49:59 -07006045 frame->unidirectional = (frame_type == IETF_MAX_STREAMS_UNIDIRECTIONAL);
6046 return true;
QUICHE teama6ef0a62019-03-07 20:34:33 -05006047}
6048
6049bool QuicFramer::AppendIetfBlockedFrame(const QuicBlockedFrame& frame,
6050 QuicDataWriter* writer) {
6051 if (!writer->WriteVarInt62(frame.offset)) {
6052 set_detailed_error("Can not write blocked offset.");
6053 return false;
6054 }
6055 return true;
6056}
6057
6058bool QuicFramer::ProcessIetfBlockedFrame(QuicDataReader* reader,
6059 QuicBlockedFrame* frame) {
6060 // Indicates that it is a BLOCKED frame (as opposed to STREAM_BLOCKED).
6061 frame->stream_id = QuicUtils::GetInvalidStreamId(transport_version());
6062 if (!reader->ReadVarInt62(&frame->offset)) {
6063 set_detailed_error("Can not read blocked offset.");
6064 return false;
6065 }
6066 return true;
6067}
6068
6069bool QuicFramer::AppendStreamBlockedFrame(const QuicBlockedFrame& frame,
6070 QuicDataWriter* writer) {
6071 if (!writer->WriteVarInt62(frame.stream_id)) {
6072 set_detailed_error("Can not write stream blocked stream id.");
6073 return false;
6074 }
6075 if (!writer->WriteVarInt62(frame.offset)) {
6076 set_detailed_error("Can not write stream blocked offset.");
6077 return false;
6078 }
6079 return true;
6080}
6081
6082bool QuicFramer::ProcessStreamBlockedFrame(QuicDataReader* reader,
6083 QuicBlockedFrame* frame) {
fkastenholz3c4eabf2019-04-22 07:49:59 -07006084 if (!reader->ReadVarIntU32(&frame->stream_id)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05006085 set_detailed_error("Can not read stream blocked stream id.");
6086 return false;
6087 }
6088 if (!reader->ReadVarInt62(&frame->offset)) {
6089 set_detailed_error("Can not read stream blocked offset.");
6090 return false;
6091 }
6092 return true;
6093}
6094
fkastenholz3c4eabf2019-04-22 07:49:59 -07006095bool QuicFramer::AppendStreamsBlockedFrame(const QuicStreamsBlockedFrame& frame,
6096 QuicDataWriter* writer) {
6097 if (!writer->WriteVarInt62(frame.stream_count)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05006098 set_detailed_error("Can not write STREAMS_BLOCKED stream count");
6099 return false;
6100 }
6101 return true;
6102}
6103
6104bool QuicFramer::ProcessStreamsBlockedFrame(QuicDataReader* reader,
fkastenholz3c4eabf2019-04-22 07:49:59 -07006105 QuicStreamsBlockedFrame* frame,
QUICHE teama6ef0a62019-03-07 20:34:33 -05006106 uint64_t frame_type) {
fkastenholz3c4eabf2019-04-22 07:49:59 -07006107 if (!reader->ReadVarIntU32(&frame->stream_count)) {
6108 set_detailed_error("Can not read STREAMS_BLOCKED stream count.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05006109 return false;
6110 }
fkastenholz3c4eabf2019-04-22 07:49:59 -07006111 frame->unidirectional = (frame_type == IETF_STREAMS_BLOCKED_UNIDIRECTIONAL);
6112
QUICHE teama6ef0a62019-03-07 20:34:33 -05006113 // TODO(fkastenholz): handle properly when the STREAMS_BLOCKED
6114 // frame is implemented and passed up to the stream ID manager.
fkastenholz3c4eabf2019-04-22 07:49:59 -07006115 if (frame->stream_count >
6116 QuicUtils::GetMaxStreamCount(
6117 (frame_type == IETF_STREAMS_BLOCKED_UNIDIRECTIONAL),
6118 ((perspective_ == Perspective::IS_CLIENT)
6119 ? Perspective::IS_SERVER
6120 : Perspective::IS_CLIENT))) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05006121 // If stream count is such that the resulting stream ID would exceed our
6122 // implementation limit, generate an error.
6123 set_detailed_error(
6124 "STREAMS_BLOCKED stream count exceeds implementation limit.");
6125 return false;
6126 }
fkastenholz3c4eabf2019-04-22 07:49:59 -07006127 return true;
QUICHE teama6ef0a62019-03-07 20:34:33 -05006128}
6129
6130bool QuicFramer::AppendNewConnectionIdFrame(
6131 const QuicNewConnectionIdFrame& frame,
6132 QuicDataWriter* writer) {
6133 if (!writer->WriteVarInt62(frame.sequence_number)) {
6134 set_detailed_error("Can not write New Connection ID sequence number");
6135 return false;
6136 }
fkastenholz1c19fc22019-07-12 11:06:19 -07006137 if (!writer->WriteVarInt62(frame.retire_prior_to)) {
6138 set_detailed_error("Can not write New Connection ID retire_prior_to");
6139 return false;
6140 }
dschinazicf5b1e22019-07-17 18:35:17 -07006141 if (!writer->WriteLengthPrefixedConnectionId(frame.connection_id)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05006142 set_detailed_error("Can not write New Connection ID frame connection ID");
6143 return false;
6144 }
6145
6146 if (!writer->WriteBytes(
6147 static_cast<const void*>(&frame.stateless_reset_token),
6148 sizeof(frame.stateless_reset_token))) {
6149 set_detailed_error("Can not write New Connection ID Reset Token");
6150 return false;
6151 }
6152 return true;
6153}
6154
6155bool QuicFramer::ProcessNewConnectionIdFrame(QuicDataReader* reader,
6156 QuicNewConnectionIdFrame* frame) {
6157 if (!reader->ReadVarInt62(&frame->sequence_number)) {
6158 set_detailed_error(
6159 "Unable to read new connection ID frame sequence number.");
6160 return false;
6161 }
6162
fkastenholz1c19fc22019-07-12 11:06:19 -07006163 if (!reader->ReadVarInt62(&frame->retire_prior_to)) {
6164 set_detailed_error(
6165 "Unable to read new connection ID frame retire_prior_to.");
6166 return false;
6167 }
6168 if (frame->retire_prior_to > frame->sequence_number) {
6169 set_detailed_error("Retire_prior_to > sequence_number.");
6170 return false;
6171 }
dschinazicf5b1e22019-07-17 18:35:17 -07006172
6173 if (!reader->ReadLengthPrefixedConnectionId(&frame->connection_id)) {
6174 set_detailed_error("Unable to read new connection ID frame connection id.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05006175 return false;
6176 }
6177
dschinazicf5b1e22019-07-17 18:35:17 -07006178 if (!QuicUtils::IsConnectionIdValidForVersion(frame->connection_id,
6179 transport_version())) {
QUICHE team0131a5b2019-03-20 15:23:27 -07006180 set_detailed_error("Invalid new connection ID length for version.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05006181 return false;
6182 }
6183
QUICHE teama6ef0a62019-03-07 20:34:33 -05006184 if (!reader->ReadBytes(&frame->stateless_reset_token,
6185 sizeof(frame->stateless_reset_token))) {
6186 set_detailed_error("Can not read new connection ID frame reset token.");
6187 return false;
6188 }
6189 return true;
6190}
6191
6192bool QuicFramer::AppendRetireConnectionIdFrame(
6193 const QuicRetireConnectionIdFrame& frame,
6194 QuicDataWriter* writer) {
6195 if (!writer->WriteVarInt62(frame.sequence_number)) {
6196 set_detailed_error("Can not write Retire Connection ID sequence number");
6197 return false;
6198 }
6199 return true;
6200}
6201
6202bool QuicFramer::ProcessRetireConnectionIdFrame(
6203 QuicDataReader* reader,
6204 QuicRetireConnectionIdFrame* frame) {
6205 if (!reader->ReadVarInt62(&frame->sequence_number)) {
6206 set_detailed_error(
6207 "Unable to read retire connection ID frame sequence number.");
6208 return false;
6209 }
6210 return true;
6211}
6212
6213uint8_t QuicFramer::GetStreamFrameTypeByte(const QuicStreamFrame& frame,
6214 bool last_frame_in_packet) const {
fkastenholz305e1732019-06-18 05:01:22 -07006215 if (VersionHasIetfQuicFrames(version_.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05006216 return GetIetfStreamFrameTypeByte(frame, last_frame_in_packet);
6217 }
6218 uint8_t type_byte = 0;
6219 // Fin bit.
6220 type_byte |= frame.fin ? kQuicStreamFinMask : 0;
6221
6222 // Data Length bit.
6223 type_byte <<= kQuicStreamDataLengthShift;
6224 type_byte |= last_frame_in_packet ? 0 : kQuicStreamDataLengthMask;
6225
6226 // Offset 3 bits.
6227 type_byte <<= kQuicStreamShift;
6228 const size_t offset_len =
6229 GetStreamOffsetSize(version_.transport_version, frame.offset);
6230 if (offset_len > 0) {
6231 type_byte |= offset_len - 1;
6232 }
6233
6234 // stream id 2 bits.
6235 type_byte <<= kQuicStreamIdShift;
6236 type_byte |= GetStreamIdSize(frame.stream_id) - 1;
6237 type_byte |= kQuicFrameTypeStreamMask; // Set Stream Frame Type to 1.
6238
6239 return type_byte;
6240}
6241
6242uint8_t QuicFramer::GetIetfStreamFrameTypeByte(
6243 const QuicStreamFrame& frame,
6244 bool last_frame_in_packet) const {
fkastenholz305e1732019-06-18 05:01:22 -07006245 DCHECK(VersionHasIetfQuicFrames(version_.transport_version));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006246 uint8_t type_byte = IETF_STREAM;
6247 if (!last_frame_in_packet) {
6248 type_byte |= IETF_STREAM_FRAME_LEN_BIT;
6249 }
6250 if (frame.offset != 0) {
6251 type_byte |= IETF_STREAM_FRAME_OFF_BIT;
6252 }
6253 if (frame.fin) {
6254 type_byte |= IETF_STREAM_FRAME_FIN_BIT;
6255 }
6256 return type_byte;
6257}
6258
6259void QuicFramer::InferPacketHeaderTypeFromVersion() {
6260 // This function should only be called when server connection negotiates the
6261 // version.
6262 DCHECK(perspective_ == Perspective::IS_SERVER &&
6263 !infer_packet_header_type_from_version_);
6264 infer_packet_header_type_from_version_ = true;
6265}
6266
QUICHE team10b22a12019-03-21 15:31:42 -07006267void QuicFramer::EnableMultiplePacketNumberSpacesSupport() {
6268 if (supports_multiple_packet_number_spaces_) {
6269 QUIC_BUG << "Multiple packet number spaces has already been enabled";
6270 return;
6271 }
6272 if (largest_packet_number_.IsInitialized()) {
6273 QUIC_BUG << "Try to enable multiple packet number spaces support after any "
6274 "packet has been received.";
6275 return;
6276 }
6277
6278 supports_multiple_packet_number_spaces_ = true;
6279}
6280
fayangccbab732019-05-13 10:11:25 -07006281// static
6282QuicErrorCode QuicFramer::ProcessPacketDispatcher(
6283 const QuicEncryptedPacket& packet,
dschinazib42a8c52019-05-30 09:45:01 -07006284 uint8_t expected_destination_connection_id_length,
fayangccbab732019-05-13 10:11:25 -07006285 PacketHeaderFormat* format,
6286 bool* version_flag,
6287 QuicVersionLabel* version_label,
fayangccbab732019-05-13 10:11:25 -07006288 QuicConnectionId* destination_connection_id,
dschinazib42a8c52019-05-30 09:45:01 -07006289 QuicConnectionId* source_connection_id,
fayangccbab732019-05-13 10:11:25 -07006290 std::string* detailed_error) {
dschinazi48ac9192019-07-31 00:07:26 -07006291 DCHECK(!GetQuicReloadableFlag(quic_use_parse_public_header));
fayangccbab732019-05-13 10:11:25 -07006292 QuicDataReader reader(packet.data(), packet.length());
6293
dschinazib42a8c52019-05-30 09:45:01 -07006294 *source_connection_id = EmptyQuicConnectionId();
fayangccbab732019-05-13 10:11:25 -07006295 uint8_t first_byte;
6296 if (!reader.ReadBytes(&first_byte, 1)) {
6297 *detailed_error = "Unable to read first byte.";
6298 return QUIC_INVALID_PACKET_HEADER;
6299 }
dschinazib42a8c52019-05-30 09:45:01 -07006300 uint8_t destination_connection_id_length = 0, source_connection_id_length = 0;
fayangccbab732019-05-13 10:11:25 -07006301 if (!QuicUtils::IsIetfPacketHeader(first_byte)) {
6302 *format = GOOGLE_QUIC_PACKET;
6303 *version_flag = (first_byte & PACKET_PUBLIC_FLAGS_VERSION) != 0;
dschinazib42a8c52019-05-30 09:45:01 -07006304 destination_connection_id_length =
fayangccbab732019-05-13 10:11:25 -07006305 first_byte & PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID;
dschinazib42a8c52019-05-30 09:45:01 -07006306 if (destination_connection_id_length == 0 ||
fayangccbab732019-05-13 10:11:25 -07006307 !reader.ReadConnectionId(destination_connection_id,
dschinazib42a8c52019-05-30 09:45:01 -07006308 destination_connection_id_length)) {
fayangccbab732019-05-13 10:11:25 -07006309 *detailed_error = "Unable to read ConnectionId.";
6310 return QUIC_INVALID_PACKET_HEADER;
6311 }
6312 if (*version_flag && !ProcessVersionLabel(&reader, version_label)) {
6313 *detailed_error = "Unable to read protocol version.";
6314 return QUIC_INVALID_PACKET_HEADER;
6315 }
6316 return QUIC_NO_ERROR;
6317 }
6318
6319 *format = GetIetfPacketHeaderFormat(first_byte);
6320 QUIC_DVLOG(1) << "Dispatcher: Processing IETF QUIC packet, format: "
6321 << *format;
6322 *version_flag = *format == IETF_QUIC_LONG_HEADER_PACKET;
6323 if (*format == IETF_QUIC_LONG_HEADER_PACKET) {
6324 if (!ProcessVersionLabel(&reader, version_label)) {
6325 *detailed_error = "Unable to read protocol version.";
6326 return QUIC_INVALID_PACKET_HEADER;
6327 }
dschinazi8ff74822019-05-28 16:37:20 -07006328 // Set should_update_expected_server_connection_id_length to true to bypass
fayangccbab732019-05-13 10:11:25 -07006329 // connection ID lengths validation.
dschinazi8ff74822019-05-28 16:37:20 -07006330 uint8_t unused_expected_server_connection_id_length = 0;
fayangccbab732019-05-13 10:11:25 -07006331 if (!ProcessAndValidateIetfConnectionIdLength(
6332 &reader, ParseQuicVersionLabel(*version_label),
dschinazi334f0232019-05-29 16:08:53 -07006333 Perspective::IS_SERVER,
dschinazi8ff74822019-05-28 16:37:20 -07006334 /*should_update_expected_server_connection_id_length=*/true,
6335 &unused_expected_server_connection_id_length,
dschinazib42a8c52019-05-30 09:45:01 -07006336 &destination_connection_id_length, &source_connection_id_length,
6337 detailed_error)) {
fayangccbab732019-05-13 10:11:25 -07006338 return QUIC_INVALID_PACKET_HEADER;
6339 }
6340 } else {
dschinazib42a8c52019-05-30 09:45:01 -07006341 // For short header packets, expected_destination_connection_id_length
6342 // is used to determine the destination_connection_id_length.
6343 destination_connection_id_length =
6344 expected_destination_connection_id_length;
6345 DCHECK_EQ(0, source_connection_id_length);
fayangccbab732019-05-13 10:11:25 -07006346 }
6347 // Read destination connection ID.
6348 if (!reader.ReadConnectionId(destination_connection_id,
dschinazib42a8c52019-05-30 09:45:01 -07006349 destination_connection_id_length)) {
6350 *detailed_error = "Unable to read destination connection ID.";
6351 return QUIC_INVALID_PACKET_HEADER;
6352 }
6353 // Read source connection ID.
dschinazi5e1a7b22019-07-31 12:23:21 -07006354 if (!reader.ReadConnectionId(source_connection_id,
dschinazib42a8c52019-05-30 09:45:01 -07006355 source_connection_id_length)) {
6356 *detailed_error = "Unable to read source connection ID.";
fayangccbab732019-05-13 10:11:25 -07006357 return QUIC_INVALID_PACKET_HEADER;
6358 }
6359 return QUIC_NO_ERROR;
6360}
6361
dschinazide0f6dc2019-05-15 16:10:11 -07006362// static
dschinazi48ac9192019-07-31 00:07:26 -07006363QuicErrorCode QuicFramer::ParsePublicHeaderDispatcher(
6364 const QuicEncryptedPacket& packet,
6365 uint8_t expected_destination_connection_id_length,
6366 PacketHeaderFormat* format,
6367 bool* version_present,
6368 bool* has_length_prefix,
6369 QuicVersionLabel* version_label,
6370 ParsedQuicVersion* parsed_version,
6371 QuicConnectionId* destination_connection_id,
6372 QuicConnectionId* source_connection_id,
6373 bool* retry_token_present,
6374 QuicStringPiece* retry_token,
6375 std::string* detailed_error) {
6376 QuicDataReader reader(packet.data(), packet.length());
6377 if (reader.IsDoneReading()) {
6378 *detailed_error = "Unable to read first byte.";
6379 return QUIC_INVALID_PACKET_HEADER;
6380 }
6381 const uint8_t first_byte = reader.PeekByte();
6382 const bool ietf_format = QuicUtils::IsIetfPacketHeader(first_byte);
6383 uint8_t unused_first_byte;
6384 QuicVariableLengthIntegerLength retry_token_length_length;
6385 QuicLongHeaderType unused_log_packet_type;
6386 const QuicErrorCode error_code = ParsePublicHeader(
6387 &reader, expected_destination_connection_id_length, ietf_format,
6388 &unused_first_byte, format, version_present, has_length_prefix,
6389 version_label, parsed_version, destination_connection_id,
6390 source_connection_id, &unused_log_packet_type, &retry_token_length_length,
6391 retry_token, detailed_error);
6392 *retry_token_present =
6393 retry_token_length_length != VARIABLE_LENGTH_INTEGER_LENGTH_0;
6394 return error_code;
6395}
6396
6397// static
6398QuicErrorCode QuicFramer::ParsePublicHeaderGoogleQuic(
6399 QuicDataReader* reader,
6400 uint8_t* first_byte,
6401 PacketHeaderFormat* format,
6402 bool* version_present,
6403 QuicVersionLabel* version_label,
dschinazi243eabc2019-08-05 16:15:29 -07006404 ParsedQuicVersion* parsed_version,
dschinazi48ac9192019-07-31 00:07:26 -07006405 QuicConnectionId* destination_connection_id,
6406 std::string* detailed_error) {
6407 *format = GOOGLE_QUIC_PACKET;
6408 *version_present = (*first_byte & PACKET_PUBLIC_FLAGS_VERSION) != 0;
6409 uint8_t destination_connection_id_length = 0;
6410 if ((*first_byte & PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID) != 0) {
6411 destination_connection_id_length = kQuicDefaultConnectionIdLength;
6412 }
6413 if (!reader->ReadConnectionId(destination_connection_id,
6414 destination_connection_id_length)) {
6415 *detailed_error = "Unable to read ConnectionId.";
6416 return QUIC_INVALID_PACKET_HEADER;
6417 }
dschinazi243eabc2019-08-05 16:15:29 -07006418 if (*version_present) {
6419 if (!ProcessVersionLabel(reader, version_label)) {
6420 *detailed_error = "Unable to read protocol version.";
6421 return QUIC_INVALID_PACKET_HEADER;
6422 }
6423 *parsed_version = ParseQuicVersionLabel(*version_label);
dschinazi48ac9192019-07-31 00:07:26 -07006424 }
6425 return QUIC_NO_ERROR;
6426}
6427
6428namespace {
6429
6430inline bool PacketHasLengthPrefixedConnectionIds(
6431 const QuicDataReader& reader,
6432 ParsedQuicVersion parsed_version,
6433 QuicVersionLabel version_label,
6434 uint8_t first_byte) {
6435 if (parsed_version.transport_version != QUIC_VERSION_UNSUPPORTED) {
6436 return parsed_version.HasLengthPrefixedConnectionIds();
6437 }
6438
6439 // Received unsupported version, check known old unsupported versions.
6440 if (QuicVersionLabelUses4BitConnectionIdLength(version_label)) {
6441 return false;
6442 }
6443
6444 // Received unknown version, check connection ID length byte.
6445 if (reader.IsDoneReading()) {
6446 // This check is required to safely peek the connection ID length byte.
6447 return true;
6448 }
6449 const uint8_t connection_id_length_byte = reader.PeekByte();
6450
6451 // Check for packets produced by older versions of
6452 // QuicFramer::WriteClientVersionNegotiationProbePacket
6453 if (first_byte == 0xc0 && (connection_id_length_byte & 0x0f) == 0 &&
6454 connection_id_length_byte >= 0x50 && version_label == 0xcabadaba) {
6455 return false;
6456 }
6457
6458 // Check for munged packets with version tag PROX.
6459 if ((connection_id_length_byte & 0x0f) == 0 &&
6460 connection_id_length_byte >= 0x20 && version_label == 0x50524F58) {
6461 return false;
6462 }
6463
6464 return true;
6465}
6466
6467inline bool ParseLongHeaderConnectionIds(
6468 QuicDataReader* reader,
6469 bool has_length_prefix,
6470 QuicConnectionId* destination_connection_id,
6471 QuicConnectionId* source_connection_id,
6472 std::string* detailed_error) {
6473 if (has_length_prefix) {
6474 if (!reader->ReadLengthPrefixedConnectionId(destination_connection_id)) {
6475 *detailed_error = "Unable to read destination connection ID.";
6476 return false;
6477 }
6478 if (!reader->ReadLengthPrefixedConnectionId(source_connection_id)) {
6479 *detailed_error = "Unable to read source connection ID.";
6480 return false;
6481 }
6482 } else {
6483 // Parse connection ID lengths.
6484 uint8_t connection_id_lengths_byte;
6485 if (!reader->ReadUInt8(&connection_id_lengths_byte)) {
6486 *detailed_error = "Unable to read connection ID lengths.";
6487 return false;
6488 }
6489 uint8_t destination_connection_id_length =
6490 (connection_id_lengths_byte & kDestinationConnectionIdLengthMask) >> 4;
6491 if (destination_connection_id_length != 0) {
6492 destination_connection_id_length += kConnectionIdLengthAdjustment;
6493 }
6494 uint8_t source_connection_id_length =
6495 connection_id_lengths_byte & kSourceConnectionIdLengthMask;
6496 if (source_connection_id_length != 0) {
6497 source_connection_id_length += kConnectionIdLengthAdjustment;
6498 }
6499
6500 // Read destination connection ID.
6501 if (!reader->ReadConnectionId(destination_connection_id,
6502 destination_connection_id_length)) {
6503 *detailed_error = "Unable to read destination connection ID.";
6504 return false;
6505 }
6506
6507 // Read source connection ID.
6508 if (!reader->ReadConnectionId(source_connection_id,
6509 source_connection_id_length)) {
6510 *detailed_error = "Unable to read source connection ID.";
6511 return false;
6512 }
6513 }
6514 return true;
6515}
6516
6517} // namespace
6518
6519// static
6520QuicErrorCode QuicFramer::ParsePublicHeader(
6521 QuicDataReader* reader,
6522 uint8_t expected_destination_connection_id_length,
6523 bool ietf_format,
6524 uint8_t* first_byte,
6525 PacketHeaderFormat* format,
6526 bool* version_present,
6527 bool* has_length_prefix,
6528 QuicVersionLabel* version_label,
6529 ParsedQuicVersion* parsed_version,
6530 QuicConnectionId* destination_connection_id,
6531 QuicConnectionId* source_connection_id,
6532 QuicLongHeaderType* long_packet_type,
6533 QuicVariableLengthIntegerLength* retry_token_length_length,
6534 QuicStringPiece* retry_token,
6535 std::string* detailed_error) {
6536 *version_present = false;
6537 *has_length_prefix = false;
6538 *version_label = 0;
6539 *parsed_version = UnsupportedQuicVersion();
6540 *source_connection_id = EmptyQuicConnectionId();
6541 *long_packet_type = INVALID_PACKET_TYPE;
6542 *retry_token_length_length = VARIABLE_LENGTH_INTEGER_LENGTH_0;
6543 *retry_token = QuicStringPiece();
6544 *detailed_error = "";
6545
6546 if (!reader->ReadUInt8(first_byte)) {
6547 *detailed_error = "Unable to read first byte.";
6548 return QUIC_INVALID_PACKET_HEADER;
6549 }
6550
6551 if (!ietf_format) {
6552 return ParsePublicHeaderGoogleQuic(
6553 reader, first_byte, format, version_present, version_label,
dschinazi243eabc2019-08-05 16:15:29 -07006554 parsed_version, destination_connection_id, detailed_error);
dschinazi48ac9192019-07-31 00:07:26 -07006555 }
6556
6557 *format = GetIetfPacketHeaderFormat(*first_byte);
6558
6559 if (*format == IETF_QUIC_SHORT_HEADER_PACKET) {
6560 // Read destination connection ID using
6561 // expected_destination_connection_id_length to determine its length.
6562 if (!reader->ReadConnectionId(destination_connection_id,
6563 expected_destination_connection_id_length)) {
6564 *detailed_error = "Unable to read destination connection ID.";
6565 return QUIC_INVALID_PACKET_HEADER;
6566 }
6567 return QUIC_NO_ERROR;
6568 }
6569
6570 DCHECK_EQ(IETF_QUIC_LONG_HEADER_PACKET, *format);
6571 *version_present = true;
6572 if (!ProcessVersionLabel(reader, version_label)) {
6573 *detailed_error = "Unable to read protocol version.";
6574 return QUIC_INVALID_PACKET_HEADER;
6575 }
6576
6577 if (*version_label == 0) {
6578 *long_packet_type = VERSION_NEGOTIATION;
6579 }
6580
6581 // Parse version.
6582 *parsed_version = ParseQuicVersionLabel(*version_label);
6583
6584 // Figure out which IETF QUIC invariants this packet follows.
6585 *has_length_prefix = PacketHasLengthPrefixedConnectionIds(
6586 *reader, *parsed_version, *version_label, *first_byte);
6587
6588 // Parse connection IDs.
6589 if (!ParseLongHeaderConnectionIds(reader, *has_length_prefix,
6590 destination_connection_id,
6591 source_connection_id, detailed_error)) {
6592 return QUIC_INVALID_PACKET_HEADER;
6593 }
6594
6595 if (parsed_version->transport_version == QUIC_VERSION_UNSUPPORTED) {
6596 // Skip parsing of long packet type and retry token for unknown versions.
6597 return QUIC_NO_ERROR;
6598 }
6599
6600 // Parse long packet type.
6601 if (!GetLongHeaderType(parsed_version->transport_version, *first_byte,
6602 long_packet_type)) {
6603 *detailed_error = "Unable to parse long packet type.";
6604 return QUIC_INVALID_PACKET_HEADER;
6605 }
6606
6607 if (!parsed_version->SupportsRetry() || *long_packet_type != INITIAL) {
6608 // Retry token is only present on initial packets for some versions.
6609 return QUIC_NO_ERROR;
6610 }
6611
6612 *retry_token_length_length = reader->PeekVarInt62Length();
6613 uint64_t retry_token_length;
6614 if (!reader->ReadVarInt62(&retry_token_length)) {
6615 *retry_token_length_length = VARIABLE_LENGTH_INTEGER_LENGTH_0;
6616 *detailed_error = "Unable to read retry token length.";
6617 return QUIC_INVALID_PACKET_HEADER;
6618 }
6619
6620 if (!reader->ReadStringPiece(retry_token, retry_token_length)) {
6621 *detailed_error = "Unable to read retry token.";
6622 return QUIC_INVALID_PACKET_HEADER;
6623 }
6624
6625 return QUIC_NO_ERROR;
6626}
6627
6628// static
dschinazide0f6dc2019-05-15 16:10:11 -07006629bool QuicFramer::WriteClientVersionNegotiationProbePacket(
6630 char* packet_bytes,
6631 QuicByteCount packet_length,
6632 const char* destination_connection_id_bytes,
6633 uint8_t destination_connection_id_length) {
6634 if (packet_bytes == nullptr) {
6635 QUIC_BUG << "Invalid packet_bytes";
6636 return false;
6637 }
6638 if (packet_length < kMinPacketSizeForVersionNegotiation ||
6639 packet_length > 65535) {
6640 QUIC_BUG << "Invalid packet_length";
6641 return false;
6642 }
dschinazib012d212019-08-01 18:07:26 -07006643 if (destination_connection_id_length > kQuicMaxConnectionId4BitLength ||
dschinazi19dc2b52019-07-17 19:54:43 -07006644 destination_connection_id_length <
6645 kQuicMinimumInitialConnectionIdLength) {
dschinazide0f6dc2019-05-15 16:10:11 -07006646 QUIC_BUG << "Invalid connection_id_length";
6647 return false;
6648 }
dschinazi48ac9192019-07-31 00:07:26 -07006649 const bool use_length_prefix =
6650 GetQuicFlag(FLAGS_quic_prober_uses_length_prefixed_connection_ids);
6651 const uint8_t last_version_byte = use_length_prefix ? 0xda : 0xba;
dschinazide0f6dc2019-05-15 16:10:11 -07006652 // clang-format off
dschinazi48ac9192019-07-31 00:07:26 -07006653 const unsigned char packet_start_bytes[] = {
dschinazide0f6dc2019-05-15 16:10:11 -07006654 // IETF long header with fixed bit set, type initial, all-0 encrypted bits.
6655 0xc0,
6656 // Version, part of the IETF space reserved for negotiation.
6657 // This intentionally differs from QuicVersionReservedForNegotiation()
6658 // to allow differentiating them over the wire.
dschinazi48ac9192019-07-31 00:07:26 -07006659 0xca, 0xba, 0xda, last_version_byte,
dschinazide0f6dc2019-05-15 16:10:11 -07006660 };
6661 // clang-format on
6662 static_assert(sizeof(packet_start_bytes) == 5, "bad packet_start_bytes size");
6663 QuicDataWriter writer(packet_length, packet_bytes);
6664 if (!writer.WriteBytes(packet_start_bytes, sizeof(packet_start_bytes))) {
6665 QUIC_BUG << "Failed to write packet start";
6666 return false;
6667 }
6668
6669 QuicConnectionId destination_connection_id(destination_connection_id_bytes,
6670 destination_connection_id_length);
dschinazi48ac9192019-07-31 00:07:26 -07006671 if (!AppendIetfConnectionIds(
6672 /*version_flag=*/true, use_length_prefix, destination_connection_id,
6673 EmptyQuicConnectionId(), &writer)) {
dschinazide0f6dc2019-05-15 16:10:11 -07006674 QUIC_BUG << "Failed to write connection IDs";
6675 return false;
6676 }
6677 // Add 8 bytes of zeroes followed by 8 bytes of ones to ensure that this does
6678 // not parse with any known version. The zeroes make sure that packet numbers,
6679 // retry token lengths and payload lengths are parsed as zero, and if the
6680 // zeroes are treated as padding frames, 0xff is known to not parse as a
6681 // valid frame type.
6682 if (!writer.WriteUInt64(0) ||
6683 !writer.WriteUInt64(std::numeric_limits<uint64_t>::max())) {
6684 QUIC_BUG << "Failed to write 18 bytes";
6685 return false;
6686 }
6687 // Make sure the polite greeting below is padded to a 16-byte boundary to
6688 // make it easier to read in tcpdump.
6689 while (writer.length() % 16 != 0) {
6690 if (!writer.WriteUInt8(0)) {
6691 QUIC_BUG << "Failed to write padding byte";
6692 return false;
6693 }
6694 }
6695 // Add a polite greeting in case a human sees this in tcpdump.
6696 static const char polite_greeting[] =
6697 "This packet only exists to trigger IETF QUIC version negotiation. "
6698 "Please respond with a Version Negotiation packet indicating what "
6699 "versions you support. Thank you and have a nice day.";
6700 if (!writer.WriteBytes(polite_greeting, sizeof(polite_greeting))) {
6701 QUIC_BUG << "Failed to write polite greeting";
6702 return false;
6703 }
6704 // Fill the rest of the packet with zeroes.
6705 writer.WritePadding();
6706 DCHECK_EQ(0u, writer.remaining());
6707 return true;
6708}
6709
6710// static
6711bool QuicFramer::ParseServerVersionNegotiationProbeResponse(
6712 const char* packet_bytes,
6713 QuicByteCount packet_length,
6714 char* source_connection_id_bytes,
6715 uint8_t* source_connection_id_length_out,
6716 std::string* detailed_error) {
6717 if (detailed_error == nullptr) {
6718 QUIC_BUG << "Invalid error_details";
6719 return false;
6720 }
6721 *detailed_error = "";
6722 if (packet_bytes == nullptr) {
6723 *detailed_error = "Invalid packet_bytes";
6724 return false;
6725 }
6726 if (packet_length < 6) {
6727 *detailed_error = "Invalid packet_length";
6728 return false;
6729 }
6730 if (source_connection_id_bytes == nullptr) {
6731 *detailed_error = "Invalid source_connection_id_bytes";
6732 return false;
6733 }
6734 if (source_connection_id_length_out == nullptr) {
6735 *detailed_error = "Invalid source_connection_id_length_out";
6736 return false;
6737 }
6738 QuicDataReader reader(packet_bytes, packet_length);
6739 uint8_t type_byte = 0;
6740 if (!reader.ReadUInt8(&type_byte)) {
6741 *detailed_error = "Failed to read type byte";
6742 return false;
6743 }
6744 if ((type_byte & 0x80) == 0) {
6745 *detailed_error = "Packet does not have long header";
6746 return false;
6747 }
6748 uint32_t version = 0;
6749 if (!reader.ReadUInt32(&version)) {
6750 *detailed_error = "Failed to read version";
6751 return false;
6752 }
6753 if (version != 0) {
6754 *detailed_error = "Packet is not a version negotiation packet";
6755 return false;
6756 }
dschinazi48ac9192019-07-31 00:07:26 -07006757 const bool use_length_prefix =
6758 GetQuicFlag(FLAGS_quic_prober_uses_length_prefixed_connection_ids);
dschinazide0f6dc2019-05-15 16:10:11 -07006759 QuicConnectionId destination_connection_id, source_connection_id;
dschinazi48ac9192019-07-31 00:07:26 -07006760 if (use_length_prefix) {
6761 if (!reader.ReadLengthPrefixedConnectionId(&destination_connection_id)) {
6762 *detailed_error = "Failed to read destination connection ID";
6763 return false;
6764 }
6765 if (!reader.ReadLengthPrefixedConnectionId(&source_connection_id)) {
6766 *detailed_error = "Failed to read source connection ID";
6767 return false;
6768 }
6769 } else {
6770 uint8_t expected_server_connection_id_length = 0,
6771 destination_connection_id_length = 0,
6772 source_connection_id_length = 0;
6773 if (!ProcessAndValidateIetfConnectionIdLength(
6774 &reader, UnsupportedQuicVersion(), Perspective::IS_CLIENT,
6775 /*should_update_expected_server_connection_id_length=*/true,
6776 &expected_server_connection_id_length,
6777 &destination_connection_id_length, &source_connection_id_length,
6778 detailed_error)) {
6779 return false;
6780 }
6781 if (!reader.ReadConnectionId(&destination_connection_id,
6782 destination_connection_id_length)) {
6783 *detailed_error = "Failed to read destination connection ID";
6784 return false;
6785 }
6786 if (!reader.ReadConnectionId(&source_connection_id,
6787 source_connection_id_length)) {
6788 *detailed_error = "Failed to read source connection ID";
6789 return false;
6790 }
dschinazide0f6dc2019-05-15 16:10:11 -07006791 }
dschinazi48ac9192019-07-31 00:07:26 -07006792
6793 if (destination_connection_id.length() != 0) {
6794 *detailed_error = "Received unexpected destination connection ID length";
dschinazide0f6dc2019-05-15 16:10:11 -07006795 return false;
6796 }
6797
6798 memcpy(source_connection_id_bytes, source_connection_id.data(),
dschinazi48ac9192019-07-31 00:07:26 -07006799 source_connection_id.length());
6800 *source_connection_id_length_out = source_connection_id.length();
dschinazide0f6dc2019-05-15 16:10:11 -07006801
6802 return true;
6803}
6804
fkastenholzb4dade72019-08-05 06:54:20 -07006805// Look for and parse the error code from the "<quic_error_code>:" text that
6806// may be present at the start of the CONNECTION_CLOSE error details string.
6807// This text, inserted by the peer if it's using Google's QUIC implementation,
6808// contains additional error information that narrows down the exact error. If
6809// the string is not found, or is not properly formed, it returns
6810// ErrorCode::QUIC_IETF_GQUIC_ERROR_MISSING
6811QuicErrorCode MaybeExtractQuicErrorCode(QuicStringPiece error_details) {
6812 std::vector<QuicStringPiece> ed = QuicTextUtils::Split(error_details, ':');
6813 uint64_t extracted_error_code;
6814 if (ed.size() < 2 || !QuicTextUtils::IsAllDigits(ed[0]) ||
6815 !QuicTextUtils::StringToUint64(ed[0], &extracted_error_code)) {
6816 return QUIC_IETF_GQUIC_ERROR_MISSING;
6817 }
6818 return static_cast<QuicErrorCode>(extracted_error_code);
6819}
6820
QUICHE teama6ef0a62019-03-07 20:34:33 -05006821#undef ENDPOINT // undef for jumbo builds
6822} // namespace quic