blob: 83ea19bdb0d9f594400d54923d79ef09d964796f [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"
QUICHE teama6ef0a62019-03-07 20:34:33 -050027#include "net/third_party/quiche/src/quic/core/quic_socket_address_coder.h"
28#include "net/third_party/quiche/src/quic/core/quic_stream_frame_data_producer.h"
29#include "net/third_party/quiche/src/quic/core/quic_types.h"
30#include "net/third_party/quiche/src/quic/core/quic_utils.h"
31#include "net/third_party/quiche/src/quic/core/quic_versions.h"
32#include "net/third_party/quiche/src/quic/platform/api/quic_aligned.h"
dschinazie8d7fa72019-04-05 14:44:40 -070033#include "net/third_party/quiche/src/quic/platform/api/quic_arraysize.h"
QUICHE teama6ef0a62019-03-07 20:34:33 -050034#include "net/third_party/quiche/src/quic/platform/api/quic_bug_tracker.h"
35#include "net/third_party/quiche/src/quic/platform/api/quic_client_stats.h"
QUICHE teama6ef0a62019-03-07 20:34:33 -050036#include "net/third_party/quiche/src/quic/platform/api/quic_fallthrough.h"
37#include "net/third_party/quiche/src/quic/platform/api/quic_flag_utils.h"
38#include "net/third_party/quiche/src/quic/platform/api/quic_flags.h"
39#include "net/third_party/quiche/src/quic/platform/api/quic_logging.h"
40#include "net/third_party/quiche/src/quic/platform/api/quic_map_util.h"
41#include "net/third_party/quiche/src/quic/platform/api/quic_ptr_util.h"
42#include "net/third_party/quiche/src/quic/platform/api/quic_stack_trace.h"
43#include "net/third_party/quiche/src/quic/platform/api/quic_str_cat.h"
QUICHE teama6ef0a62019-03-07 20:34:33 -050044#include "net/third_party/quiche/src/quic/platform/api/quic_text_utils.h"
45
46namespace quic {
47
48namespace {
49
50#define ENDPOINT \
51 (perspective_ == Perspective::IS_SERVER ? "Server: " : "Client: ")
52
53// How much to shift the timestamp in the IETF Ack frame.
54// TODO(fkastenholz) when we get real IETF QUIC, need to get
55// the currect shift from the transport parameters.
56const int kIetfAckTimestampShift = 3;
57
58// Number of bits the packet number length bits are shifted from the right
59// edge of the header.
60const uint8_t kPublicHeaderSequenceNumberShift = 4;
61
62// There are two interpretations for the Frame Type byte in the QUIC protocol,
63// resulting in two Frame Types: Special Frame Types and Regular Frame Types.
64//
65// Regular Frame Types use the Frame Type byte simply. Currently defined
66// Regular Frame Types are:
67// Padding : 0b 00000000 (0x00)
68// ResetStream : 0b 00000001 (0x01)
69// ConnectionClose : 0b 00000010 (0x02)
70// GoAway : 0b 00000011 (0x03)
71// WindowUpdate : 0b 00000100 (0x04)
72// Blocked : 0b 00000101 (0x05)
73//
74// Special Frame Types encode both a Frame Type and corresponding flags
75// all in the Frame Type byte. Currently defined Special Frame Types
76// are:
77// Stream : 0b 1xxxxxxx
78// Ack : 0b 01xxxxxx
79//
80// Semantics of the flag bits above (the x bits) depends on the frame type.
81
82// Masks to determine if the frame type is a special use
83// and for specific special frame types.
84const uint8_t kQuicFrameTypeBrokenMask = 0xE0; // 0b 11100000
85const uint8_t kQuicFrameTypeSpecialMask = 0xC0; // 0b 11000000
86const uint8_t kQuicFrameTypeStreamMask = 0x80;
87const uint8_t kQuicFrameTypeAckMask = 0x40;
88static_assert(kQuicFrameTypeSpecialMask ==
89 (kQuicFrameTypeStreamMask | kQuicFrameTypeAckMask),
90 "Invalid kQuicFrameTypeSpecialMask");
91
92// The stream type format is 1FDOOOSS, where
93// F is the fin bit.
94// D is the data length bit (0 or 2 bytes).
95// OO/OOO are the size of the offset.
96// SS is the size of the stream ID.
97// Note that the stream encoding can not be determined by inspection. It can
98// be determined only by knowing the QUIC Version.
99// Stream frame relative shifts and masks for interpreting the stream flags.
100// StreamID may be 1, 2, 3, or 4 bytes.
101const uint8_t kQuicStreamIdShift = 2;
102const uint8_t kQuicStreamIDLengthMask = 0x03;
103
104// Offset may be 0, 2, 4, or 8 bytes.
105const uint8_t kQuicStreamShift = 3;
106const uint8_t kQuicStreamOffsetMask = 0x07;
107
108// Data length may be 0 or 2 bytes.
109const uint8_t kQuicStreamDataLengthShift = 1;
110const uint8_t kQuicStreamDataLengthMask = 0x01;
111
112// Fin bit may be set or not.
113const uint8_t kQuicStreamFinShift = 1;
114const uint8_t kQuicStreamFinMask = 0x01;
115
116// The format is 01M0LLOO, where
117// M if set, there are multiple ack blocks in the frame.
118// LL is the size of the largest ack field.
119// OO is the size of the ack blocks offset field.
120// packet number size shift used in AckFrames.
121const uint8_t kQuicSequenceNumberLengthNumBits = 2;
122const uint8_t kActBlockLengthOffset = 0;
123const uint8_t kLargestAckedOffset = 2;
124
125// Acks may have only one ack block.
126const uint8_t kQuicHasMultipleAckBlocksOffset = 5;
127
128// Timestamps are 4 bytes followed by 2 bytes.
129const uint8_t kQuicNumTimestampsLength = 1;
130const uint8_t kQuicFirstTimestampLength = 4;
131const uint8_t kQuicTimestampLength = 2;
132// Gaps between packet numbers are 1 byte.
133const uint8_t kQuicTimestampPacketNumberGapLength = 1;
134
135// Maximum length of encoded error strings.
136const int kMaxErrorStringLength = 256;
137
138const uint8_t kConnectionIdLengthAdjustment = 3;
139const uint8_t kDestinationConnectionIdLengthMask = 0xF0;
140const uint8_t kSourceConnectionIdLengthMask = 0x0F;
141
142// Returns the absolute value of the difference between |a| and |b|.
143uint64_t Delta(uint64_t a, uint64_t b) {
144 // Since these are unsigned numbers, we can't just return abs(a - b)
145 if (a < b) {
146 return b - a;
147 }
148 return a - b;
149}
150
151uint64_t ClosestTo(uint64_t target, uint64_t a, uint64_t b) {
152 return (Delta(target, a) < Delta(target, b)) ? a : b;
153}
154
155uint64_t PacketNumberIntervalLength(
156 const QuicInterval<QuicPacketNumber>& interval) {
157 if (interval.Empty()) {
158 return 0u;
159 }
160 return interval.max() - interval.min();
161}
162
163QuicPacketNumberLength ReadSequenceNumberLength(uint8_t flags) {
164 switch (flags & PACKET_FLAGS_8BYTE_PACKET) {
165 case PACKET_FLAGS_8BYTE_PACKET:
166 return PACKET_6BYTE_PACKET_NUMBER;
167 case PACKET_FLAGS_4BYTE_PACKET:
168 return PACKET_4BYTE_PACKET_NUMBER;
169 case PACKET_FLAGS_2BYTE_PACKET:
170 return PACKET_2BYTE_PACKET_NUMBER;
171 case PACKET_FLAGS_1BYTE_PACKET:
172 return PACKET_1BYTE_PACKET_NUMBER;
173 default:
174 QUIC_BUG << "Unreachable case statement.";
175 return PACKET_6BYTE_PACKET_NUMBER;
176 }
177}
178
dschinazi17d42422019-06-18 16:35:07 -0700179QuicPacketNumberLength ReadAckPacketNumberLength(
180 QuicTransportVersion /*version*/,
181 uint8_t flags) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500182 switch (flags & PACKET_FLAGS_8BYTE_PACKET) {
183 case PACKET_FLAGS_8BYTE_PACKET:
184 return PACKET_6BYTE_PACKET_NUMBER;
185 case PACKET_FLAGS_4BYTE_PACKET:
186 return PACKET_4BYTE_PACKET_NUMBER;
187 case PACKET_FLAGS_2BYTE_PACKET:
188 return PACKET_2BYTE_PACKET_NUMBER;
189 case PACKET_FLAGS_1BYTE_PACKET:
190 return PACKET_1BYTE_PACKET_NUMBER;
191 default:
192 QUIC_BUG << "Unreachable case statement.";
193 return PACKET_6BYTE_PACKET_NUMBER;
194 }
195}
196
197uint8_t PacketNumberLengthToOnWireValue(
fayangf36e29d2019-06-06 14:03:40 -0700198 QuicTransportVersion version,
QUICHE teama6ef0a62019-03-07 20:34:33 -0500199 QuicPacketNumberLength packet_number_length) {
fayangf36e29d2019-06-06 14:03:40 -0700200 if (version > QUIC_VERSION_44) {
201 return packet_number_length - 1;
202 }
203 switch (packet_number_length) {
204 case PACKET_1BYTE_PACKET_NUMBER:
205 return 0;
206 case PACKET_2BYTE_PACKET_NUMBER:
207 return 1;
208 case PACKET_4BYTE_PACKET_NUMBER:
209 return 2;
210 default:
211 QUIC_BUG << "Invalid packet number length.";
212 return 0;
213 }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500214}
215
216bool GetShortHeaderPacketNumberLength(
217 QuicTransportVersion version,
218 uint8_t type,
219 bool infer_packet_header_type_from_version,
220 QuicPacketNumberLength* packet_number_length) {
221 DCHECK(!(type & FLAGS_LONG_HEADER));
222 const bool two_bits_packet_number_length =
fayangf36e29d2019-06-06 14:03:40 -0700223 infer_packet_header_type_from_version ? version > QUIC_VERSION_44
QUICHE teama6ef0a62019-03-07 20:34:33 -0500224 : (type & FLAGS_FIXED_BIT);
225 if (two_bits_packet_number_length) {
226 *packet_number_length =
227 static_cast<QuicPacketNumberLength>((type & 0x03) + 1);
228 return true;
229 }
230 switch (type & 0x07) {
231 case 0:
232 *packet_number_length = PACKET_1BYTE_PACKET_NUMBER;
233 break;
234 case 1:
235 *packet_number_length = PACKET_2BYTE_PACKET_NUMBER;
236 break;
237 case 2:
238 *packet_number_length = PACKET_4BYTE_PACKET_NUMBER;
239 break;
240 default:
241 *packet_number_length = PACKET_6BYTE_PACKET_NUMBER;
242 return false;
243 }
244 return true;
245}
246
fayangf36e29d2019-06-06 14:03:40 -0700247uint8_t LongHeaderTypeToOnWireValue(QuicTransportVersion version,
248 QuicLongHeaderType type) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500249 switch (type) {
250 case INITIAL:
fayangf36e29d2019-06-06 14:03:40 -0700251 return version > QUIC_VERSION_44 ? 0 : 0x7F;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500252 case ZERO_RTT_PROTECTED:
fayangf36e29d2019-06-06 14:03:40 -0700253 return version > QUIC_VERSION_44 ? 1 << 4 : 0x7C;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500254 case HANDSHAKE:
fayangf36e29d2019-06-06 14:03:40 -0700255 return version > QUIC_VERSION_44 ? 2 << 4 : 0x7D;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500256 case RETRY:
fayangf36e29d2019-06-06 14:03:40 -0700257 return version > QUIC_VERSION_44 ? 3 << 4 : 0x7E;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500258 case VERSION_NEGOTIATION:
259 return 0xF0; // Value does not matter
260 default:
261 QUIC_BUG << "Invalid long header type: " << type;
262 return 0xFF;
263 }
264}
265
266bool GetLongHeaderType(QuicTransportVersion version,
267 uint8_t type,
268 QuicLongHeaderType* long_header_type) {
269 DCHECK((type & FLAGS_LONG_HEADER) && version != QUIC_VERSION_UNSUPPORTED);
fayangf36e29d2019-06-06 14:03:40 -0700270 if (version > QUIC_VERSION_44) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500271 switch ((type & 0x30) >> 4) {
272 case 0:
273 *long_header_type = INITIAL;
274 break;
275 case 1:
276 *long_header_type = ZERO_RTT_PROTECTED;
277 break;
278 case 2:
279 *long_header_type = HANDSHAKE;
280 break;
281 case 3:
282 *long_header_type = RETRY;
283 break;
284 default:
285 QUIC_BUG << "Unreachable statement";
dschinazi072da7c2019-05-07 17:57:42 -0700286 *long_header_type = INVALID_PACKET_TYPE;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500287 return false;
288 }
289 return true;
290 }
291
292 switch (type & 0x7F) {
293 case 0x7F:
294 *long_header_type = INITIAL;
295 break;
296 case 0x7C:
297 *long_header_type = ZERO_RTT_PROTECTED;
298 break;
299 case 0x7D:
300 *long_header_type = HANDSHAKE;
301 break;
302 case 0x7E:
303 *long_header_type = RETRY;
304 break;
305 default:
306 // Invalid packet header type. Whether a packet is version negotiation is
307 // determined by the version field.
308 *long_header_type = INVALID_PACKET_TYPE;
309 return false;
310 }
311 return true;
312}
313
314QuicPacketNumberLength GetLongHeaderPacketNumberLength(
315 QuicTransportVersion version,
316 uint8_t type) {
fayangf36e29d2019-06-06 14:03:40 -0700317 if (version > QUIC_VERSION_44) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500318 return static_cast<QuicPacketNumberLength>((type & 0x03) + 1);
319 }
320 return PACKET_4BYTE_PACKET_NUMBER;
321}
322
QUICHE team10b22a12019-03-21 15:31:42 -0700323// Used to get packet number space before packet gets decrypted.
324PacketNumberSpace GetPacketNumberSpace(const QuicPacketHeader& header) {
325 switch (header.form) {
326 case GOOGLE_QUIC_PACKET:
327 QUIC_BUG << "Try to get packet number space of Google QUIC packet";
328 break;
329 case IETF_QUIC_SHORT_HEADER_PACKET:
330 return APPLICATION_DATA;
331 case IETF_QUIC_LONG_HEADER_PACKET:
332 switch (header.long_packet_type) {
333 case INITIAL:
334 return INITIAL_DATA;
335 case HANDSHAKE:
336 return HANDSHAKE_DATA;
337 case ZERO_RTT_PROTECTED:
338 return APPLICATION_DATA;
339 case VERSION_NEGOTIATION:
340 case RETRY:
341 case INVALID_PACKET_TYPE:
342 QUIC_BUG << "Try to get packet number space of long header type: "
343 << QuicUtils::QuicLongHeaderTypetoString(
344 header.long_packet_type);
345 break;
346 }
347 }
348
349 return NUM_PACKET_NUMBER_SPACES;
350}
351
zhongyi546cc452019-04-12 15:27:49 -0700352EncryptionLevel GetEncryptionLevel(const QuicPacketHeader& header) {
353 switch (header.form) {
354 case GOOGLE_QUIC_PACKET:
355 QUIC_BUG << "Cannot determine EncryptionLevel from Google QUIC header";
356 break;
357 case IETF_QUIC_SHORT_HEADER_PACKET:
358 return ENCRYPTION_FORWARD_SECURE;
359 case IETF_QUIC_LONG_HEADER_PACKET:
360 switch (header.long_packet_type) {
361 case INITIAL:
362 return ENCRYPTION_INITIAL;
363 case HANDSHAKE:
364 return ENCRYPTION_HANDSHAKE;
365 case ZERO_RTT_PROTECTED:
366 return ENCRYPTION_ZERO_RTT;
367 case VERSION_NEGOTIATION:
368 case RETRY:
369 case INVALID_PACKET_TYPE:
370 QUIC_BUG << "No encryption used with type "
371 << QuicUtils::QuicLongHeaderTypetoString(
372 header.long_packet_type);
373 }
374 }
375 return NUM_ENCRYPTION_LEVELS;
376}
377
QUICHE teama6ef0a62019-03-07 20:34:33 -0500378QuicStringPiece TruncateErrorString(QuicStringPiece error) {
379 if (error.length() <= kMaxErrorStringLength) {
380 return error;
381 }
382 return QuicStringPiece(error.data(), kMaxErrorStringLength);
383}
384
385size_t TruncatedErrorStringSize(const QuicStringPiece& error) {
386 if (error.length() < kMaxErrorStringLength) {
387 return error.length();
388 }
389 return kMaxErrorStringLength;
390}
391
392uint8_t GetConnectionIdLengthValue(QuicConnectionIdLength length) {
393 if (length == 0) {
394 return 0;
395 }
396 return static_cast<uint8_t>(length - kConnectionIdLengthAdjustment);
397}
398
399bool IsValidPacketNumberLength(QuicPacketNumberLength packet_number_length) {
400 size_t length = packet_number_length;
401 return length == 1 || length == 2 || length == 4 || length == 6 ||
402 length == 8;
403}
404
405bool IsValidFullPacketNumber(uint64_t full_packet_number,
406 QuicTransportVersion version) {
QUICHE team577718a2019-03-20 09:00:59 -0700407 return full_packet_number > 0 || version == QUIC_VERSION_99;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500408}
409
dschinazi1f485a12019-05-13 11:57:01 -0700410bool AppendIetfConnectionIds(bool version_flag,
411 QuicConnectionId destination_connection_id,
412 QuicConnectionId source_connection_id,
413 QuicDataWriter* writer) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500414 if (!version_flag) {
415 return writer->WriteConnectionId(destination_connection_id);
416 }
417
418 // Compute connection ID length byte.
419 uint8_t dcil = GetConnectionIdLengthValue(
420 static_cast<QuicConnectionIdLength>(destination_connection_id.length()));
421 uint8_t scil = GetConnectionIdLengthValue(
422 static_cast<QuicConnectionIdLength>(source_connection_id.length()));
423 uint8_t connection_id_length = dcil << 4 | scil;
424
425 return writer->WriteUInt8(connection_id_length) &&
426 writer->WriteConnectionId(destination_connection_id) &&
427 writer->WriteConnectionId(source_connection_id);
428}
429
430enum class DroppedPacketReason {
431 // General errors
432 INVALID_PUBLIC_HEADER,
433 VERSION_MISMATCH,
434 // Version negotiation packet errors
435 INVALID_VERSION_NEGOTIATION_PACKET,
436 // Public reset packet errors, pre-v44
437 INVALID_PUBLIC_RESET_PACKET,
438 // Data packet errors
439 INVALID_PACKET_NUMBER,
440 INVALID_DIVERSIFICATION_NONCE,
441 DECRYPTION_FAILURE,
442 NUM_REASONS,
443};
444
445void RecordDroppedPacketReason(DroppedPacketReason reason) {
446 QUIC_CLIENT_HISTOGRAM_ENUM("QuicDroppedPacketReason", reason,
447 DroppedPacketReason::NUM_REASONS,
448 "The reason a packet was not processed. Recorded "
449 "each time such a packet is dropped");
450}
451
fayangccbab732019-05-13 10:11:25 -0700452PacketHeaderFormat GetIetfPacketHeaderFormat(uint8_t type_byte) {
453 return type_byte & FLAGS_LONG_HEADER ? IETF_QUIC_LONG_HEADER_PACKET
454 : IETF_QUIC_SHORT_HEADER_PACKET;
455}
456
QUICHE teama6ef0a62019-03-07 20:34:33 -0500457} // namespace
458
459QuicFramer::QuicFramer(const ParsedQuicVersionVector& supported_versions,
460 QuicTime creation_time,
461 Perspective perspective,
dschinazi8ff74822019-05-28 16:37:20 -0700462 uint8_t expected_server_connection_id_length)
QUICHE teama6ef0a62019-03-07 20:34:33 -0500463 : visitor_(nullptr),
464 error_(QUIC_NO_ERROR),
dschinazi7b9278c2019-05-20 07:36:21 -0700465 last_serialized_server_connection_id_(EmptyQuicConnectionId()),
dschinazi346b7ce2019-06-05 01:38:18 -0700466 last_serialized_client_connection_id_(EmptyQuicConnectionId()),
QUICHE teama6ef0a62019-03-07 20:34:33 -0500467 version_(PROTOCOL_UNSUPPORTED, QUIC_VERSION_UNSUPPORTED),
468 supported_versions_(supported_versions),
QUICHE team6987b4a2019-03-15 16:23:04 -0700469 decrypter_level_(ENCRYPTION_INITIAL),
QUICHE team76086e42019-03-25 15:12:29 -0700470 alternative_decrypter_level_(NUM_ENCRYPTION_LEVELS),
QUICHE teama6ef0a62019-03-07 20:34:33 -0500471 alternative_decrypter_latch_(false),
472 perspective_(perspective),
473 validate_flags_(true),
474 process_timestamps_(false),
475 creation_time_(creation_time),
476 last_timestamp_(QuicTime::Delta::Zero()),
477 first_sending_packet_number_(FirstSendingPacketNumber()),
478 data_producer_(nullptr),
479 infer_packet_header_type_from_version_(perspective ==
480 Perspective::IS_CLIENT),
dschinazi8ff74822019-05-28 16:37:20 -0700481 expected_server_connection_id_length_(
482 expected_server_connection_id_length),
dschinazi346b7ce2019-06-05 01:38:18 -0700483 expected_client_connection_id_length_(0),
nharper55fa6132019-05-07 19:37:21 -0700484 supports_multiple_packet_number_spaces_(false),
485 last_written_packet_number_length_(0) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500486 DCHECK(!supported_versions.empty());
487 version_ = supported_versions_[0];
QUICHE team76086e42019-03-25 15:12:29 -0700488 decrypter_[ENCRYPTION_INITIAL] = QuicMakeUnique<NullDecrypter>(perspective);
QUICHE team6987b4a2019-03-15 16:23:04 -0700489 encrypter_[ENCRYPTION_INITIAL] = QuicMakeUnique<NullEncrypter>(perspective);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500490}
491
492QuicFramer::~QuicFramer() {}
493
494// static
495size_t QuicFramer::GetMinStreamFrameSize(QuicTransportVersion version,
496 QuicStreamId stream_id,
497 QuicStreamOffset offset,
498 bool last_frame_in_packet,
499 QuicPacketLength data_length) {
fkastenholz305e1732019-06-18 05:01:22 -0700500 if (VersionHasIetfQuicFrames(version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500501 return kQuicFrameTypeSize + QuicDataWriter::GetVarInt62Len(stream_id) +
502 (last_frame_in_packet
503 ? 0
504 : QuicDataWriter::GetVarInt62Len(data_length)) +
505 (offset != 0 ? QuicDataWriter::GetVarInt62Len(offset) : 0);
506 }
507 return kQuicFrameTypeSize + GetStreamIdSize(stream_id) +
508 GetStreamOffsetSize(version, offset) +
509 (last_frame_in_packet ? 0 : kQuicStreamPayloadLengthSize);
510}
511
512// static
513size_t QuicFramer::GetMinCryptoFrameSize(QuicStreamOffset offset,
514 QuicPacketLength data_length) {
515 return kQuicFrameTypeSize + QuicDataWriter::GetVarInt62Len(offset) +
516 QuicDataWriter::GetVarInt62Len(data_length);
517}
518
519// static
520size_t QuicFramer::GetMessageFrameSize(QuicTransportVersion version,
521 bool last_frame_in_packet,
522 QuicByteCount length) {
fayangd4291e42019-05-30 10:31:21 -0700523 QUIC_BUG_IF(!VersionSupportsMessageFrames(version))
QUICHE teama6ef0a62019-03-07 20:34:33 -0500524 << "Try to serialize MESSAGE frame in " << version;
525 return kQuicFrameTypeSize +
526 (last_frame_in_packet ? 0 : QuicDataWriter::GetVarInt62Len(length)) +
527 length;
528}
529
530// static
531size_t QuicFramer::GetMinAckFrameSize(
532 QuicTransportVersion version,
533 QuicPacketNumberLength largest_observed_length) {
fkastenholz305e1732019-06-18 05:01:22 -0700534 if (VersionHasIetfQuicFrames(version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500535 // The minimal ack frame consists of the following four fields: Largest
536 // Acknowledged, ACK Delay, ACK Block Count, and First ACK Block. Minimum
537 // size of each is 1 byte.
538 return kQuicFrameTypeSize + 4;
539 }
540 size_t min_size = kQuicFrameTypeSize + largest_observed_length +
541 kQuicDeltaTimeLargestObservedSize;
542 return min_size + kQuicNumTimestampsSize;
543}
544
545// static
546size_t QuicFramer::GetStopWaitingFrameSize(
dschinazi17d42422019-06-18 16:35:07 -0700547 QuicTransportVersion /*version*/,
QUICHE teama6ef0a62019-03-07 20:34:33 -0500548 QuicPacketNumberLength packet_number_length) {
549 size_t min_size = kQuicFrameTypeSize + packet_number_length;
550 return min_size;
551}
552
553// static
554size_t QuicFramer::GetRstStreamFrameSize(QuicTransportVersion version,
555 const QuicRstStreamFrame& frame) {
fkastenholz305e1732019-06-18 05:01:22 -0700556 if (VersionHasIetfQuicFrames(version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500557 return QuicDataWriter::GetVarInt62Len(frame.stream_id) +
558 QuicDataWriter::GetVarInt62Len(frame.byte_offset) +
559 kQuicFrameTypeSize + kQuicIetfQuicErrorCodeSize;
560 }
561 return kQuicFrameTypeSize + kQuicMaxStreamIdSize + kQuicMaxStreamOffsetSize +
562 kQuicErrorCodeSize;
563}
564
565// static
fkastenholza037b8b2019-05-07 06:00:05 -0700566size_t QuicFramer::GetConnectionCloseFrameSize(
QUICHE teama6ef0a62019-03-07 20:34:33 -0500567 QuicTransportVersion version,
568 const QuicConnectionCloseFrame& frame) {
fkastenholz305e1732019-06-18 05:01:22 -0700569 if (!VersionHasIetfQuicFrames(version)) {
570 // Not IETF QUIC, return Google QUIC CONNECTION CLOSE frame size.
fkastenholza037b8b2019-05-07 06:00:05 -0700571 return kQuicFrameTypeSize + kQuicErrorCodeSize +
572 kQuicErrorDetailsLengthSize +
573 TruncatedErrorStringSize(frame.error_details);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500574 }
fkastenholza037b8b2019-05-07 06:00:05 -0700575 // TODO(fkastenholz): For complete support of IETF QUIC CONNECTION_CLOSE,
576 // check if the frame is a Transport close and if the frame's
577 // extracted_error_code is not QUIC_IETF_GQUIC_ERROR_MISSING. If so,
578 // extend the error string to include " QuicErrorCode: #"
579 const size_t truncated_error_string_size =
580 TruncatedErrorStringSize(frame.error_details);
581 const size_t frame_size =
582 truncated_error_string_size +
583 QuicDataWriter::GetVarInt62Len(truncated_error_string_size) +
584 kQuicFrameTypeSize + kQuicIetfQuicErrorCodeSize;
585 if (frame.close_type == IETF_QUIC_APPLICATION_CONNECTION_CLOSE) {
586 return frame_size;
587 }
588 // frame includes the transport_close_frame_type, so include its length.
589 return frame_size +
590 QuicDataWriter::GetVarInt62Len(frame.transport_close_frame_type);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500591}
592
593// static
QUICHE teama6ef0a62019-03-07 20:34:33 -0500594size_t QuicFramer::GetMinGoAwayFrameSize() {
595 return kQuicFrameTypeSize + kQuicErrorCodeSize + kQuicErrorDetailsLengthSize +
596 kQuicMaxStreamIdSize;
597}
598
599// static
600size_t QuicFramer::GetWindowUpdateFrameSize(
601 QuicTransportVersion version,
602 const QuicWindowUpdateFrame& frame) {
fkastenholz305e1732019-06-18 05:01:22 -0700603 if (!VersionHasIetfQuicFrames(version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500604 return kQuicFrameTypeSize + kQuicMaxStreamIdSize + kQuicMaxStreamOffsetSize;
605 }
606 if (frame.stream_id == QuicUtils::GetInvalidStreamId(version)) {
607 // Frame would be a MAX DATA frame, which has only a Maximum Data field.
608 return kQuicFrameTypeSize +
609 QuicDataWriter::GetVarInt62Len(frame.byte_offset);
610 }
611 // Frame would be MAX STREAM DATA, has Maximum Stream Data and Stream ID
612 // fields.
613 return kQuicFrameTypeSize +
614 QuicDataWriter::GetVarInt62Len(frame.byte_offset) +
615 QuicDataWriter::GetVarInt62Len(frame.stream_id);
616}
617
618// static
619size_t QuicFramer::GetMaxStreamsFrameSize(QuicTransportVersion version,
fkastenholz3c4eabf2019-04-22 07:49:59 -0700620 const QuicMaxStreamsFrame& frame) {
fkastenholz305e1732019-06-18 05:01:22 -0700621 if (!VersionHasIetfQuicFrames(version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500622 QUIC_BUG << "In version " << version
fkastenholz305e1732019-06-18 05:01:22 -0700623 << ", which does not support IETF Frames, and tried to serialize "
624 "MaxStreams Frame.";
QUICHE teama6ef0a62019-03-07 20:34:33 -0500625 }
fkastenholz3c4eabf2019-04-22 07:49:59 -0700626 return kQuicFrameTypeSize +
627 QuicDataWriter::GetVarInt62Len(frame.stream_count);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500628}
629
630// static
631size_t QuicFramer::GetStreamsBlockedFrameSize(
632 QuicTransportVersion version,
fkastenholz3c4eabf2019-04-22 07:49:59 -0700633 const QuicStreamsBlockedFrame& frame) {
fkastenholz305e1732019-06-18 05:01:22 -0700634 if (!VersionHasIetfQuicFrames(version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500635 QUIC_BUG << "In version " << version
fkastenholz305e1732019-06-18 05:01:22 -0700636 << ", which does not support IETF frames, and tried to serialize "
637 "StreamsBlocked Frame.";
QUICHE teama6ef0a62019-03-07 20:34:33 -0500638 }
639
fkastenholz3c4eabf2019-04-22 07:49:59 -0700640 return kQuicFrameTypeSize +
641 QuicDataWriter::GetVarInt62Len(frame.stream_count);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500642}
643
644// static
645size_t QuicFramer::GetBlockedFrameSize(QuicTransportVersion version,
646 const QuicBlockedFrame& frame) {
fkastenholz305e1732019-06-18 05:01:22 -0700647 if (!VersionHasIetfQuicFrames(version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500648 return kQuicFrameTypeSize + kQuicMaxStreamIdSize;
649 }
650 if (frame.stream_id == QuicUtils::GetInvalidStreamId(version)) {
651 // return size of IETF QUIC Blocked frame
652 return kQuicFrameTypeSize + QuicDataWriter::GetVarInt62Len(frame.offset);
653 }
654 // return size of IETF QUIC Stream Blocked frame.
655 return kQuicFrameTypeSize + QuicDataWriter::GetVarInt62Len(frame.offset) +
656 QuicDataWriter::GetVarInt62Len(frame.stream_id);
657}
658
659// static
660size_t QuicFramer::GetStopSendingFrameSize(const QuicStopSendingFrame& frame) {
661 return kQuicFrameTypeSize + QuicDataWriter::GetVarInt62Len(frame.stream_id) +
662 sizeof(QuicApplicationErrorCode);
663}
664
665// static
666size_t QuicFramer::GetPathChallengeFrameSize(
667 const QuicPathChallengeFrame& frame) {
668 return kQuicFrameTypeSize + sizeof(frame.data_buffer);
669}
670
671// static
672size_t QuicFramer::GetPathResponseFrameSize(
673 const QuicPathResponseFrame& frame) {
674 return kQuicFrameTypeSize + sizeof(frame.data_buffer);
675}
676
677// static
678size_t QuicFramer::GetRetransmittableControlFrameSize(
679 QuicTransportVersion version,
680 const QuicFrame& frame) {
681 switch (frame.type) {
682 case PING_FRAME:
683 // Ping has no payload.
684 return kQuicFrameTypeSize;
685 case RST_STREAM_FRAME:
686 return GetRstStreamFrameSize(version, *frame.rst_stream_frame);
687 case CONNECTION_CLOSE_FRAME:
fkastenholza037b8b2019-05-07 06:00:05 -0700688 return GetConnectionCloseFrameSize(version,
689 *frame.connection_close_frame);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500690 case GOAWAY_FRAME:
691 return GetMinGoAwayFrameSize() +
692 TruncatedErrorStringSize(frame.goaway_frame->reason_phrase);
693 case WINDOW_UPDATE_FRAME:
fkastenholz305e1732019-06-18 05:01:22 -0700694 // For IETF QUIC, this could be either a MAX DATA or MAX STREAM DATA.
QUICHE teama6ef0a62019-03-07 20:34:33 -0500695 // GetWindowUpdateFrameSize figures this out and returns the correct
696 // length.
697 return GetWindowUpdateFrameSize(version, *frame.window_update_frame);
698 case BLOCKED_FRAME:
699 return GetBlockedFrameSize(version, *frame.blocked_frame);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500700 case NEW_CONNECTION_ID_FRAME:
701 return GetNewConnectionIdFrameSize(*frame.new_connection_id_frame);
702 case RETIRE_CONNECTION_ID_FRAME:
703 return GetRetireConnectionIdFrameSize(*frame.retire_connection_id_frame);
704 case NEW_TOKEN_FRAME:
705 return GetNewTokenFrameSize(*frame.new_token_frame);
fkastenholz3c4eabf2019-04-22 07:49:59 -0700706 case MAX_STREAMS_FRAME:
707 return GetMaxStreamsFrameSize(version, frame.max_streams_frame);
708 case STREAMS_BLOCKED_FRAME:
709 return GetStreamsBlockedFrameSize(version, frame.streams_blocked_frame);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500710 case PATH_RESPONSE_FRAME:
711 return GetPathResponseFrameSize(*frame.path_response_frame);
712 case PATH_CHALLENGE_FRAME:
713 return GetPathChallengeFrameSize(*frame.path_challenge_frame);
714 case STOP_SENDING_FRAME:
715 return GetStopSendingFrameSize(*frame.stop_sending_frame);
716
717 case STREAM_FRAME:
718 case ACK_FRAME:
719 case STOP_WAITING_FRAME:
720 case MTU_DISCOVERY_FRAME:
721 case PADDING_FRAME:
722 case MESSAGE_FRAME:
723 case CRYPTO_FRAME:
724 case NUM_FRAME_TYPES:
725 DCHECK(false);
726 return 0;
727 }
728
729 // Not reachable, but some Chrome compilers can't figure that out. *sigh*
730 DCHECK(false);
731 return 0;
732}
733
734// static
735size_t QuicFramer::GetStreamIdSize(QuicStreamId stream_id) {
736 // Sizes are 1 through 4 bytes.
737 for (int i = 1; i <= 4; ++i) {
738 stream_id >>= 8;
739 if (stream_id == 0) {
740 return i;
741 }
742 }
743 QUIC_BUG << "Failed to determine StreamIDSize.";
744 return 4;
745}
746
747// static
dschinazi17d42422019-06-18 16:35:07 -0700748size_t QuicFramer::GetStreamOffsetSize(QuicTransportVersion /*version*/,
QUICHE teama6ef0a62019-03-07 20:34:33 -0500749 QuicStreamOffset offset) {
750 // 0 is a special case.
751 if (offset == 0) {
752 return 0;
753 }
754 // 2 through 8 are the remaining sizes.
755 offset >>= 8;
756 for (int i = 2; i <= 8; ++i) {
757 offset >>= 8;
758 if (offset == 0) {
759 return i;
760 }
761 }
762 QUIC_BUG << "Failed to determine StreamOffsetSize.";
763 return 8;
764}
765
766// static
767size_t QuicFramer::GetNewConnectionIdFrameSize(
768 const QuicNewConnectionIdFrame& frame) {
769 return kQuicFrameTypeSize +
770 QuicDataWriter::GetVarInt62Len(frame.sequence_number) +
771 kConnectionIdLengthSize + frame.connection_id.length() +
772 sizeof(frame.stateless_reset_token);
773}
774
775// static
776size_t QuicFramer::GetRetireConnectionIdFrameSize(
777 const QuicRetireConnectionIdFrame& frame) {
778 return kQuicFrameTypeSize +
779 QuicDataWriter::GetVarInt62Len(frame.sequence_number);
780}
781
782// static
783size_t QuicFramer::GetNewTokenFrameSize(const QuicNewTokenFrame& frame) {
784 return kQuicFrameTypeSize +
785 QuicDataWriter::GetVarInt62Len(frame.token.length()) +
786 frame.token.length();
787}
788
789// TODO(nharper): Change this method to take a ParsedQuicVersion.
790bool QuicFramer::IsSupportedTransportVersion(
791 const QuicTransportVersion version) const {
792 for (ParsedQuicVersion supported_version : supported_versions_) {
793 if (version == supported_version.transport_version) {
794 return true;
795 }
796 }
797 return false;
798}
799
800bool QuicFramer::IsSupportedVersion(const ParsedQuicVersion version) const {
801 for (const ParsedQuicVersion& supported_version : supported_versions_) {
802 if (version == supported_version) {
803 return true;
804 }
805 }
806 return false;
807}
808
809size_t QuicFramer::GetSerializedFrameLength(
810 const QuicFrame& frame,
811 size_t free_bytes,
812 bool first_frame,
813 bool last_frame,
814 QuicPacketNumberLength packet_number_length) {
815 // Prevent a rare crash reported in b/19458523.
816 if (frame.type == ACK_FRAME && frame.ack_frame == nullptr) {
817 QUIC_BUG << "Cannot compute the length of a null ack frame. free_bytes:"
818 << free_bytes << " first_frame:" << first_frame
819 << " last_frame:" << last_frame
820 << " seq num length:" << packet_number_length;
821 set_error(QUIC_INTERNAL_ERROR);
822 visitor_->OnError(this);
823 return 0;
824 }
825 if (frame.type == PADDING_FRAME) {
826 if (frame.padding_frame.num_padding_bytes == -1) {
827 // Full padding to the end of the packet.
828 return free_bytes;
829 } else {
830 // Lite padding.
831 return free_bytes <
832 static_cast<size_t>(frame.padding_frame.num_padding_bytes)
833 ? free_bytes
834 : frame.padding_frame.num_padding_bytes;
835 }
836 }
837
838 size_t frame_len =
839 ComputeFrameLength(frame, last_frame, packet_number_length);
840 if (frame_len <= free_bytes) {
841 // Frame fits within packet. Note that acks may be truncated.
842 return frame_len;
843 }
844 // Only truncate the first frame in a packet, so if subsequent ones go
845 // over, stop including more frames.
846 if (!first_frame) {
847 return 0;
848 }
849 bool can_truncate =
850 frame.type == ACK_FRAME &&
851 free_bytes >= GetMinAckFrameSize(version_.transport_version,
852 PACKET_6BYTE_PACKET_NUMBER);
853 if (can_truncate) {
dschinazi66dea072019-04-09 11:41:06 -0700854 // Truncate the frame so the packet will not exceed kMaxOutgoingPacketSize.
QUICHE teama6ef0a62019-03-07 20:34:33 -0500855 // Note that we may not use every byte of the writer in this case.
856 QUIC_DLOG(INFO) << ENDPOINT
857 << "Truncating large frame, free bytes: " << free_bytes;
858 return free_bytes;
859 }
860 return 0;
861}
862
863QuicFramer::AckFrameInfo::AckFrameInfo()
864 : max_block_length(0), first_block_length(0), num_ack_blocks(0) {}
865
866QuicFramer::AckFrameInfo::AckFrameInfo(const AckFrameInfo& other) = default;
867
868QuicFramer::AckFrameInfo::~AckFrameInfo() {}
869
870bool QuicFramer::WriteIetfLongHeaderLength(const QuicPacketHeader& header,
871 QuicDataWriter* writer,
872 size_t length_field_offset,
873 EncryptionLevel level) {
874 if (!QuicVersionHasLongHeaderLengths(transport_version()) ||
875 !header.version_flag || length_field_offset == 0) {
876 return true;
877 }
878 if (writer->length() < length_field_offset ||
879 writer->length() - length_field_offset <
880 kQuicDefaultLongHeaderLengthLength) {
881 set_detailed_error("Invalid length_field_offset.");
882 QUIC_BUG << "Invalid length_field_offset.";
883 return false;
884 }
885 size_t length_to_write = writer->length() - length_field_offset -
886 kQuicDefaultLongHeaderLengthLength;
887 // Add length of auth tag.
888 length_to_write = GetCiphertextSize(level, length_to_write);
889
890 QuicDataWriter length_writer(writer->length() - length_field_offset,
891 writer->data() + length_field_offset);
892 if (!length_writer.WriteVarInt62(length_to_write,
893 kQuicDefaultLongHeaderLengthLength)) {
894 set_detailed_error("Failed to overwrite long header length.");
895 QUIC_BUG << "Failed to overwrite long header length.";
896 return false;
897 }
898 return true;
899}
900
901size_t QuicFramer::BuildDataPacket(const QuicPacketHeader& header,
902 const QuicFrames& frames,
903 char* buffer,
904 size_t packet_length,
905 EncryptionLevel level) {
906 QuicDataWriter writer(packet_length, buffer);
907 size_t length_field_offset = 0;
908 if (!AppendPacketHeader(header, &writer, &length_field_offset)) {
909 QUIC_BUG << "AppendPacketHeader failed";
910 return 0;
911 }
912
fkastenholz305e1732019-06-18 05:01:22 -0700913 if (VersionHasIetfQuicFrames(transport_version())) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500914 if (AppendIetfFrames(frames, &writer) == 0) {
915 return 0;
916 }
917 if (!WriteIetfLongHeaderLength(header, &writer, length_field_offset,
918 level)) {
919 return 0;
920 }
921 return writer.length();
922 }
923 // TODO(dschinazi) if we enable long header lengths before v99, we need to
924 // add support for fixing up lengths in QuicFramer::BuildDataPacket.
925 DCHECK(!QuicVersionHasLongHeaderLengths(transport_version()));
926
927 size_t i = 0;
928 for (const QuicFrame& frame : frames) {
929 // Determine if we should write stream frame length in header.
930 const bool last_frame_in_packet = i == frames.size() - 1;
931 if (!AppendTypeByte(frame, last_frame_in_packet, &writer)) {
932 QUIC_BUG << "AppendTypeByte failed";
933 return 0;
934 }
935
936 switch (frame.type) {
937 case PADDING_FRAME:
938 if (!AppendPaddingFrame(frame.padding_frame, &writer)) {
939 QUIC_BUG << "AppendPaddingFrame of "
940 << frame.padding_frame.num_padding_bytes << " failed";
941 return 0;
942 }
943 break;
944 case STREAM_FRAME:
945 if (!AppendStreamFrame(frame.stream_frame, last_frame_in_packet,
946 &writer)) {
947 QUIC_BUG << "AppendStreamFrame failed";
948 return 0;
949 }
950 break;
951 case ACK_FRAME:
952 if (!AppendAckFrameAndTypeByte(*frame.ack_frame, &writer)) {
953 QUIC_BUG << "AppendAckFrameAndTypeByte failed: " << detailed_error_;
954 return 0;
955 }
956 break;
957 case STOP_WAITING_FRAME:
958 if (!AppendStopWaitingFrame(header, frame.stop_waiting_frame,
959 &writer)) {
960 QUIC_BUG << "AppendStopWaitingFrame failed";
961 return 0;
962 }
963 break;
964 case MTU_DISCOVERY_FRAME:
965 // MTU discovery frames are serialized as ping frames.
966 QUIC_FALLTHROUGH_INTENDED;
967 case PING_FRAME:
968 // Ping has no payload.
969 break;
970 case RST_STREAM_FRAME:
971 if (!AppendRstStreamFrame(*frame.rst_stream_frame, &writer)) {
972 QUIC_BUG << "AppendRstStreamFrame failed";
973 return 0;
974 }
975 break;
976 case CONNECTION_CLOSE_FRAME:
977 if (!AppendConnectionCloseFrame(*frame.connection_close_frame,
978 &writer)) {
979 QUIC_BUG << "AppendConnectionCloseFrame failed";
980 return 0;
981 }
982 break;
983 case GOAWAY_FRAME:
984 if (!AppendGoAwayFrame(*frame.goaway_frame, &writer)) {
985 QUIC_BUG << "AppendGoAwayFrame failed";
986 return 0;
987 }
988 break;
989 case WINDOW_UPDATE_FRAME:
990 if (!AppendWindowUpdateFrame(*frame.window_update_frame, &writer)) {
991 QUIC_BUG << "AppendWindowUpdateFrame failed";
992 return 0;
993 }
994 break;
995 case BLOCKED_FRAME:
996 if (!AppendBlockedFrame(*frame.blocked_frame, &writer)) {
997 QUIC_BUG << "AppendBlockedFrame failed";
998 return 0;
999 }
1000 break;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001001 case NEW_CONNECTION_ID_FRAME:
1002 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -07001003 "Attempt to append NEW_CONNECTION_ID frame and not in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05001004 return RaiseError(QUIC_INTERNAL_ERROR);
1005 case RETIRE_CONNECTION_ID_FRAME:
1006 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -07001007 "Attempt to append RETIRE_CONNECTION_ID frame and not in IETF "
1008 "QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05001009 return RaiseError(QUIC_INTERNAL_ERROR);
1010 case NEW_TOKEN_FRAME:
1011 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -07001012 "Attempt to append NEW_TOKEN_ID frame and not in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05001013 return RaiseError(QUIC_INTERNAL_ERROR);
fkastenholz3c4eabf2019-04-22 07:49:59 -07001014 case MAX_STREAMS_FRAME:
QUICHE teama6ef0a62019-03-07 20:34:33 -05001015 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -07001016 "Attempt to append MAX_STREAMS frame and not in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05001017 return RaiseError(QUIC_INTERNAL_ERROR);
fkastenholz3c4eabf2019-04-22 07:49:59 -07001018 case STREAMS_BLOCKED_FRAME:
QUICHE teama6ef0a62019-03-07 20:34:33 -05001019 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -07001020 "Attempt to append STREAMS_BLOCKED frame and not in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05001021 return RaiseError(QUIC_INTERNAL_ERROR);
1022 case PATH_RESPONSE_FRAME:
1023 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -07001024 "Attempt to append PATH_RESPONSE frame and not in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05001025 return RaiseError(QUIC_INTERNAL_ERROR);
1026 case PATH_CHALLENGE_FRAME:
1027 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -07001028 "Attempt to append PATH_CHALLENGE frame and not in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05001029 return RaiseError(QUIC_INTERNAL_ERROR);
1030 case STOP_SENDING_FRAME:
1031 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -07001032 "Attempt to append STOP_SENDING frame and not in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05001033 return RaiseError(QUIC_INTERNAL_ERROR);
1034 case MESSAGE_FRAME:
1035 if (!AppendMessageFrameAndTypeByte(*frame.message_frame,
1036 last_frame_in_packet, &writer)) {
1037 QUIC_BUG << "AppendMessageFrame failed";
1038 return 0;
1039 }
1040 break;
1041 case CRYPTO_FRAME:
QUICHE teamea740082019-03-11 17:58:43 -07001042 if (!QuicVersionUsesCryptoFrames(version_.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001043 set_detailed_error(
1044 "Attempt to append CRYPTO frame in version prior to 47.");
1045 return RaiseError(QUIC_INTERNAL_ERROR);
1046 }
1047 if (!AppendCryptoFrame(*frame.crypto_frame, &writer)) {
1048 QUIC_BUG << "AppendCryptoFrame failed";
1049 return 0;
1050 }
1051 break;
1052 default:
1053 RaiseError(QUIC_INVALID_FRAME_DATA);
1054 QUIC_BUG << "QUIC_INVALID_FRAME_DATA";
1055 return 0;
1056 }
1057 ++i;
1058 }
1059
1060 return writer.length();
1061}
1062
1063size_t QuicFramer::AppendIetfFrames(const QuicFrames& frames,
1064 QuicDataWriter* writer) {
1065 size_t i = 0;
1066 for (const QuicFrame& frame : frames) {
1067 // Determine if we should write stream frame length in header.
1068 const bool last_frame_in_packet = i == frames.size() - 1;
1069 if (!AppendIetfTypeByte(frame, last_frame_in_packet, writer)) {
1070 QUIC_BUG << "AppendIetfTypeByte failed: " << detailed_error();
1071 return 0;
1072 }
1073
1074 switch (frame.type) {
1075 case PADDING_FRAME:
1076 if (!AppendPaddingFrame(frame.padding_frame, writer)) {
1077 QUIC_BUG << "AppendPaddingFrame of "
1078 << frame.padding_frame.num_padding_bytes
1079 << " failed: " << detailed_error();
1080 return 0;
1081 }
1082 break;
1083 case STREAM_FRAME:
1084 if (!AppendStreamFrame(frame.stream_frame, last_frame_in_packet,
1085 writer)) {
1086 QUIC_BUG << "AppendStreamFrame failed: " << detailed_error();
1087 return 0;
1088 }
1089 break;
1090 case ACK_FRAME:
1091 if (!AppendIetfAckFrameAndTypeByte(*frame.ack_frame, writer)) {
QUICHE team4fe0b942019-03-08 09:25:06 -05001092 QUIC_BUG << "AppendIetfAckFrameAndTypeByte failed: "
1093 << detailed_error();
QUICHE teama6ef0a62019-03-07 20:34:33 -05001094 return 0;
1095 }
1096 break;
1097 case STOP_WAITING_FRAME:
1098 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -07001099 "Attempt to append STOP WAITING frame in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05001100 return RaiseError(QUIC_INTERNAL_ERROR);
1101 case MTU_DISCOVERY_FRAME:
1102 // MTU discovery frames are serialized as ping frames.
1103 QUIC_FALLTHROUGH_INTENDED;
1104 case PING_FRAME:
1105 // Ping has no payload.
1106 break;
1107 case RST_STREAM_FRAME:
1108 if (!AppendRstStreamFrame(*frame.rst_stream_frame, writer)) {
1109 QUIC_BUG << "AppendRstStreamFrame failed: " << detailed_error();
1110 return 0;
1111 }
1112 break;
1113 case CONNECTION_CLOSE_FRAME:
fkastenholz72f509b2019-04-10 09:17:49 -07001114 if (!AppendIetfConnectionCloseFrame(*frame.connection_close_frame,
1115 writer)) {
1116 QUIC_BUG << "AppendIetfConnectionCloseFrame failed: "
1117 << detailed_error();
QUICHE teama6ef0a62019-03-07 20:34:33 -05001118 return 0;
1119 }
1120 break;
1121 case GOAWAY_FRAME:
fkastenholz305e1732019-06-18 05:01:22 -07001122 set_detailed_error("Attempt to append GOAWAY frame in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05001123 return RaiseError(QUIC_INTERNAL_ERROR);
1124 case WINDOW_UPDATE_FRAME:
1125 // Depending on whether there is a stream ID or not, will be either a
1126 // MAX STREAM DATA frame or a MAX DATA frame.
1127 if (frame.window_update_frame->stream_id ==
1128 QuicUtils::GetInvalidStreamId(transport_version())) {
1129 if (!AppendMaxDataFrame(*frame.window_update_frame, writer)) {
1130 QUIC_BUG << "AppendMaxDataFrame failed: " << detailed_error();
1131 return 0;
1132 }
1133 } else {
1134 if (!AppendMaxStreamDataFrame(*frame.window_update_frame, writer)) {
1135 QUIC_BUG << "AppendMaxStreamDataFrame failed: " << detailed_error();
1136 return 0;
1137 }
1138 }
1139 break;
1140 case BLOCKED_FRAME:
1141 if (!AppendBlockedFrame(*frame.blocked_frame, writer)) {
1142 QUIC_BUG << "AppendBlockedFrame failed: " << detailed_error();
1143 return 0;
1144 }
1145 break;
fkastenholz3c4eabf2019-04-22 07:49:59 -07001146 case MAX_STREAMS_FRAME:
1147 if (!AppendMaxStreamsFrame(frame.max_streams_frame, writer)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001148 QUIC_BUG << "AppendMaxStreamsFrame failed" << detailed_error();
1149 return 0;
1150 }
1151 break;
fkastenholz3c4eabf2019-04-22 07:49:59 -07001152 case STREAMS_BLOCKED_FRAME:
1153 if (!AppendStreamsBlockedFrame(frame.streams_blocked_frame, writer)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001154 QUIC_BUG << "AppendStreamsBlockedFrame failed" << detailed_error();
1155 return 0;
1156 }
1157 break;
1158 case NEW_CONNECTION_ID_FRAME:
1159 if (!AppendNewConnectionIdFrame(*frame.new_connection_id_frame,
1160 writer)) {
1161 QUIC_BUG << "AppendNewConnectionIdFrame failed: " << detailed_error();
1162 return 0;
1163 }
1164 break;
1165 case RETIRE_CONNECTION_ID_FRAME:
1166 if (!AppendRetireConnectionIdFrame(*frame.retire_connection_id_frame,
1167 writer)) {
1168 QUIC_BUG << "AppendRetireConnectionIdFrame failed: "
1169 << detailed_error();
1170 return 0;
1171 }
1172 break;
1173 case NEW_TOKEN_FRAME:
1174 if (!AppendNewTokenFrame(*frame.new_token_frame, writer)) {
1175 QUIC_BUG << "AppendNewTokenFrame failed: " << detailed_error();
1176 return 0;
1177 }
1178 break;
1179 case STOP_SENDING_FRAME:
1180 if (!AppendStopSendingFrame(*frame.stop_sending_frame, writer)) {
1181 QUIC_BUG << "AppendStopSendingFrame failed: " << detailed_error();
1182 return 0;
1183 }
1184 break;
1185 case PATH_CHALLENGE_FRAME:
1186 if (!AppendPathChallengeFrame(*frame.path_challenge_frame, writer)) {
1187 QUIC_BUG << "AppendPathChallengeFrame failed: " << detailed_error();
1188 return 0;
1189 }
1190 break;
1191 case PATH_RESPONSE_FRAME:
1192 if (!AppendPathResponseFrame(*frame.path_response_frame, writer)) {
1193 QUIC_BUG << "AppendPathResponseFrame failed: " << detailed_error();
1194 return 0;
1195 }
1196 break;
1197 case MESSAGE_FRAME:
1198 if (!AppendMessageFrameAndTypeByte(*frame.message_frame,
1199 last_frame_in_packet, writer)) {
1200 QUIC_BUG << "AppendMessageFrame failed: " << detailed_error();
1201 return 0;
1202 }
1203 break;
1204 case CRYPTO_FRAME:
1205 if (!AppendCryptoFrame(*frame.crypto_frame, writer)) {
1206 QUIC_BUG << "AppendCryptoFrame failed: " << detailed_error();
1207 return 0;
1208 }
1209 break;
1210 default:
1211 RaiseError(QUIC_INVALID_FRAME_DATA);
1212 set_detailed_error("Tried to append unknown frame type.");
1213 QUIC_BUG << "QUIC_INVALID_FRAME_DATA";
1214 return 0;
1215 }
1216 ++i;
1217 }
1218
1219 return writer->length();
1220}
1221
rch67cb9df2019-03-26 16:52:07 -07001222size_t QuicFramer::BuildConnectivityProbingPacket(
QUICHE teama6ef0a62019-03-07 20:34:33 -05001223 const QuicPacketHeader& header,
1224 char* buffer,
1225 size_t packet_length,
1226 EncryptionLevel level) {
1227 QuicFrames frames;
1228
1229 // Write a PING frame, which has no data payload.
1230 QuicPingFrame ping_frame;
1231 frames.push_back(QuicFrame(ping_frame));
1232
1233 // Add padding to the rest of the packet.
1234 QuicPaddingFrame padding_frame;
1235 frames.push_back(QuicFrame(padding_frame));
1236
1237 return BuildDataPacket(header, frames, buffer, packet_length, level);
1238}
1239
QUICHE teama6ef0a62019-03-07 20:34:33 -05001240size_t QuicFramer::BuildPaddedPathChallengePacket(
1241 const QuicPacketHeader& header,
1242 char* buffer,
1243 size_t packet_length,
1244 QuicPathFrameBuffer* payload,
1245 QuicRandom* randomizer,
1246 EncryptionLevel level) {
fkastenholz305e1732019-06-18 05:01:22 -07001247 if (!VersionHasIetfQuicFrames(version_.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001248 QUIC_BUG << "Attempt to build a PATH_CHALLENGE Connectivity Probing "
1249 "packet and not doing IETF QUIC";
1250 return 0;
1251 }
1252 QuicFrames frames;
1253
1254 // Write a PATH_CHALLENGE frame, which has a random 8-byte payload
1255 randomizer->RandBytes(payload->data(), payload->size());
1256
1257 QuicPathChallengeFrame path_challenge_frame(0, *payload);
1258 frames.push_back(QuicFrame(&path_challenge_frame));
1259
1260 // Add padding to the rest of the packet in order to assess Path MTU
1261 // characteristics.
1262 QuicPaddingFrame padding_frame;
1263 frames.push_back(QuicFrame(padding_frame));
1264
1265 return BuildDataPacket(header, frames, buffer, packet_length, level);
1266}
1267
1268size_t QuicFramer::BuildPathResponsePacket(
1269 const QuicPacketHeader& header,
1270 char* buffer,
1271 size_t packet_length,
1272 const QuicDeque<QuicPathFrameBuffer>& payloads,
1273 const bool is_padded,
1274 EncryptionLevel level) {
1275 if (payloads.empty()) {
1276 QUIC_BUG
1277 << "Attempt to generate connectivity response with no request payloads";
1278 return 0;
1279 }
fkastenholz305e1732019-06-18 05:01:22 -07001280 if (!VersionHasIetfQuicFrames(version_.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001281 QUIC_BUG << "Attempt to build a PATH_RESPONSE Connectivity Probing "
1282 "packet and not doing IETF QUIC";
1283 return 0;
1284 }
1285
1286 std::vector<std::unique_ptr<QuicPathResponseFrame>> path_response_frames;
1287 for (const QuicPathFrameBuffer& payload : payloads) {
1288 // Note that the control frame ID can be 0 since this is not retransmitted.
1289 path_response_frames.push_back(
1290 QuicMakeUnique<QuicPathResponseFrame>(0, payload));
1291 }
1292
1293 QuicFrames frames;
1294 for (const std::unique_ptr<QuicPathResponseFrame>& path_response_frame :
1295 path_response_frames) {
1296 frames.push_back(QuicFrame(path_response_frame.get()));
1297 }
1298
1299 if (is_padded) {
1300 // Add padding to the rest of the packet in order to assess Path MTU
1301 // characteristics.
1302 QuicPaddingFrame padding_frame;
1303 frames.push_back(QuicFrame(padding_frame));
1304 }
1305
1306 return BuildDataPacket(header, frames, buffer, packet_length, level);
1307}
1308
1309// static
1310std::unique_ptr<QuicEncryptedPacket> QuicFramer::BuildPublicResetPacket(
1311 const QuicPublicResetPacket& packet) {
1312 CryptoHandshakeMessage reset;
1313 reset.set_tag(kPRST);
1314 reset.SetValue(kRNON, packet.nonce_proof);
1315 if (packet.client_address.host().address_family() !=
1316 IpAddressFamily::IP_UNSPEC) {
1317 // packet.client_address is non-empty.
1318 QuicSocketAddressCoder address_coder(packet.client_address);
vasilvvc48c8712019-03-11 13:38:16 -07001319 std::string serialized_address = address_coder.Encode();
QUICHE teama6ef0a62019-03-07 20:34:33 -05001320 if (serialized_address.empty()) {
1321 return nullptr;
1322 }
1323 reset.SetStringPiece(kCADR, serialized_address);
1324 }
1325 if (!packet.endpoint_id.empty()) {
1326 reset.SetStringPiece(kEPID, packet.endpoint_id);
1327 }
1328 const QuicData& reset_serialized = reset.GetSerialized();
1329
1330 size_t len = kPublicFlagsSize + packet.connection_id.length() +
1331 reset_serialized.length();
1332 std::unique_ptr<char[]> buffer(new char[len]);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001333 QuicDataWriter writer(len, buffer.get());
1334
1335 uint8_t flags = static_cast<uint8_t>(PACKET_PUBLIC_FLAGS_RST |
1336 PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID);
1337 // This hack makes post-v33 public reset packet look like pre-v33 packets.
1338 flags |= static_cast<uint8_t>(PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID_OLD);
1339 if (!writer.WriteUInt8(flags)) {
1340 return nullptr;
1341 }
1342
1343 if (!writer.WriteConnectionId(packet.connection_id)) {
1344 return nullptr;
1345 }
1346
1347 if (!writer.WriteBytes(reset_serialized.data(), reset_serialized.length())) {
1348 return nullptr;
1349 }
1350
1351 return QuicMakeUnique<QuicEncryptedPacket>(buffer.release(), len, true);
1352}
1353
1354// static
1355std::unique_ptr<QuicEncryptedPacket> QuicFramer::BuildIetfStatelessResetPacket(
dschinazi17d42422019-06-18 16:35:07 -07001356 QuicConnectionId /*connection_id*/,
QUICHE teama6ef0a62019-03-07 20:34:33 -05001357 QuicUint128 stateless_reset_token) {
1358 QUIC_DVLOG(1) << "Building IETF stateless reset packet.";
1359 size_t len = kPacketHeaderTypeSize + kMinRandomBytesLengthInStatelessReset +
1360 sizeof(stateless_reset_token);
1361 std::unique_ptr<char[]> buffer(new char[len]);
1362 QuicDataWriter writer(len, buffer.get());
1363
1364 uint8_t type = 0;
1365 type |= FLAGS_FIXED_BIT;
1366 type |= FLAGS_SHORT_HEADER_RESERVED_1;
1367 type |= FLAGS_SHORT_HEADER_RESERVED_2;
fayangf36e29d2019-06-06 14:03:40 -07001368 type |= PacketNumberLengthToOnWireValue(QUIC_VERSION_UNSUPPORTED,
1369 PACKET_1BYTE_PACKET_NUMBER);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001370
1371 // Append type byte.
1372 if (!writer.WriteUInt8(type)) {
1373 return nullptr;
1374 }
1375 // Append random bytes.
1376 if (!writer.WriteRandomBytes(QuicRandom::GetInstance(),
1377 kMinRandomBytesLengthInStatelessReset)) {
1378 return nullptr;
1379 }
1380
1381 // Append stateless reset token.
1382 if (!writer.WriteBytes(&stateless_reset_token,
1383 sizeof(stateless_reset_token))) {
1384 return nullptr;
1385 }
1386 return QuicMakeUnique<QuicEncryptedPacket>(buffer.release(), len, true);
1387}
1388
1389// static
1390std::unique_ptr<QuicEncryptedPacket> QuicFramer::BuildVersionNegotiationPacket(
dschinazi8ff74822019-05-28 16:37:20 -07001391 QuicConnectionId server_connection_id,
dschinazib417d602019-05-29 13:08:45 -07001392 QuicConnectionId client_connection_id,
QUICHE teama6ef0a62019-03-07 20:34:33 -05001393 bool ietf_quic,
1394 const ParsedQuicVersionVector& versions) {
1395 if (ietf_quic) {
dschinazib417d602019-05-29 13:08:45 -07001396 return BuildIetfVersionNegotiationPacket(server_connection_id,
1397 client_connection_id, versions);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001398 }
dschinazib417d602019-05-29 13:08:45 -07001399
1400 // The GQUIC encoding does not support encoding client connection IDs.
1401 DCHECK(client_connection_id.IsEmpty());
1402
QUICHE teama6ef0a62019-03-07 20:34:33 -05001403 DCHECK(!versions.empty());
dschinazi8ff74822019-05-28 16:37:20 -07001404 size_t len = kPublicFlagsSize + server_connection_id.length() +
QUICHE teama6ef0a62019-03-07 20:34:33 -05001405 versions.size() * kQuicVersionSize;
1406 std::unique_ptr<char[]> buffer(new char[len]);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001407 QuicDataWriter writer(len, buffer.get());
1408
1409 uint8_t flags = static_cast<uint8_t>(
1410 PACKET_PUBLIC_FLAGS_VERSION | PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID |
1411 // TODO(rch): Remove this QUIC_VERSION_32 is retired.
1412 PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID_OLD);
1413 if (!writer.WriteUInt8(flags)) {
1414 return nullptr;
1415 }
1416
dschinazi8ff74822019-05-28 16:37:20 -07001417 if (!writer.WriteConnectionId(server_connection_id)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001418 return nullptr;
1419 }
1420
1421 for (const ParsedQuicVersion& version : versions) {
nharpereaab5ad2019-05-31 12:23:25 -07001422 if (!writer.WriteUInt32(CreateQuicVersionLabel(version))) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001423 return nullptr;
1424 }
1425 }
1426
1427 return QuicMakeUnique<QuicEncryptedPacket>(buffer.release(), len, true);
1428}
1429
1430// static
1431std::unique_ptr<QuicEncryptedPacket>
1432QuicFramer::BuildIetfVersionNegotiationPacket(
dschinazib417d602019-05-29 13:08:45 -07001433 QuicConnectionId server_connection_id,
1434 QuicConnectionId client_connection_id,
QUICHE teama6ef0a62019-03-07 20:34:33 -05001435 const ParsedQuicVersionVector& versions) {
dschinazi5a354c92019-05-09 12:18:53 -07001436 QUIC_DVLOG(1) << "Building IETF version negotiation packet: "
1437 << ParsedQuicVersionVectorToString(versions);
dschinazib417d602019-05-29 13:08:45 -07001438 DCHECK(client_connection_id.IsEmpty() ||
1439 GetQuicRestartFlag(quic_do_not_override_connection_id));
QUICHE teama6ef0a62019-03-07 20:34:33 -05001440 DCHECK(!versions.empty());
1441 size_t len = kPacketHeaderTypeSize + kConnectionIdLengthSize +
dschinazib417d602019-05-29 13:08:45 -07001442 client_connection_id.length() + server_connection_id.length() +
QUICHE teama6ef0a62019-03-07 20:34:33 -05001443 (versions.size() + 1) * kQuicVersionSize;
1444 std::unique_ptr<char[]> buffer(new char[len]);
1445 QuicDataWriter writer(len, buffer.get());
1446
1447 // TODO(fayang): Randomly select a value for the type.
dschinazi0366de92019-06-18 20:00:27 -07001448 uint8_t type = static_cast<uint8_t>(FLAGS_LONG_HEADER | FLAGS_FIXED_BIT);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001449 if (!writer.WriteUInt8(type)) {
1450 return nullptr;
1451 }
1452
1453 if (!writer.WriteUInt32(0)) {
1454 return nullptr;
1455 }
1456
dschinazib417d602019-05-29 13:08:45 -07001457 if (!AppendIetfConnectionIds(true, client_connection_id, server_connection_id,
1458 &writer)) {
dschinazi1f485a12019-05-13 11:57:01 -07001459 return nullptr;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001460 }
1461
1462 for (const ParsedQuicVersion& version : versions) {
nharpereaab5ad2019-05-31 12:23:25 -07001463 if (!writer.WriteUInt32(CreateQuicVersionLabel(version))) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001464 return nullptr;
1465 }
1466 }
1467
1468 return QuicMakeUnique<QuicEncryptedPacket>(buffer.release(), len, true);
1469}
1470
1471bool QuicFramer::ProcessPacket(const QuicEncryptedPacket& packet) {
1472 QuicDataReader reader(packet.data(), packet.length());
1473
1474 bool packet_has_ietf_packet_header = false;
1475 if (infer_packet_header_type_from_version_) {
1476 packet_has_ietf_packet_header =
fayangd4291e42019-05-30 10:31:21 -07001477 VersionHasIetfInvariantHeader(version_.transport_version);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001478 } else if (!reader.IsDoneReading()) {
1479 uint8_t type = reader.PeekByte();
1480 packet_has_ietf_packet_header = QuicUtils::IsIetfPacketHeader(type);
1481 }
1482 if (packet_has_ietf_packet_header) {
1483 QUIC_DVLOG(1) << ENDPOINT << "Processing IETF QUIC packet.";
1484 }
1485
1486 visitor_->OnPacket();
1487
1488 QuicPacketHeader header;
1489 if (!ProcessPublicHeader(&reader, packet_has_ietf_packet_header, &header)) {
1490 DCHECK_NE("", detailed_error_);
1491 QUIC_DVLOG(1) << ENDPOINT << "Unable to process public header. Error: "
1492 << detailed_error_;
1493 DCHECK_NE("", detailed_error_);
1494 RecordDroppedPacketReason(DroppedPacketReason::INVALID_PUBLIC_HEADER);
1495 return RaiseError(QUIC_INVALID_PACKET_HEADER);
1496 }
1497
1498 if (!visitor_->OnUnauthenticatedPublicHeader(header)) {
1499 // The visitor suppresses further processing of the packet.
1500 return true;
1501 }
1502
dschinazie0df3f72019-05-06 16:37:51 -07001503 if (IsVersionNegotiation(header, packet_has_ietf_packet_header)) {
dschinazi072da7c2019-05-07 17:57:42 -07001504 if (perspective_ == Perspective::IS_CLIENT) {
1505 QUIC_DVLOG(1) << "Client received version negotiation packet";
1506 return ProcessVersionNegotiationPacket(&reader, header);
1507 } else {
1508 QUIC_DLOG(ERROR) << "Server received version negotiation packet";
1509 set_detailed_error("Server received version negotiation packet.");
1510 return RaiseError(QUIC_INVALID_VERSION_NEGOTIATION_PACKET);
1511 }
dschinazie0df3f72019-05-06 16:37:51 -07001512 }
1513
1514 if (header.version_flag && header.version != version_) {
1515 if (perspective_ == Perspective::IS_SERVER) {
1516 if (!visitor_->OnProtocolVersionMismatch(header.version, header.form)) {
1517 RecordDroppedPacketReason(DroppedPacketReason::VERSION_MISMATCH);
1518 return true;
1519 }
1520 } else {
1521 // A client received a packet of a different version but that packet is
1522 // not a version negotiation packet. It is therefore invalid and dropped.
1523 QUIC_DLOG(ERROR) << "Client received unexpected version "
1524 << ParsedQuicVersionToString(header.version)
1525 << " instead of " << ParsedQuicVersionToString(version_);
1526 set_detailed_error("Client received unexpected version.");
1527 return RaiseError(QUIC_INVALID_VERSION);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001528 }
1529 }
1530
1531 bool rv;
dschinazie0df3f72019-05-06 16:37:51 -07001532 if (header.long_packet_type == RETRY) {
dschinazi244f6dc2019-05-06 15:45:16 -07001533 rv = ProcessRetryPacket(&reader, header);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001534 } else if (header.reset_flag) {
1535 rv = ProcessPublicResetPacket(&reader, header);
dschinazie8d7fa72019-04-05 14:44:40 -07001536 } else if (packet.length() <= kMaxIncomingPacketSize) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001537 // The optimized decryption algorithm implementations run faster when
1538 // operating on aligned memory.
dschinazie8d7fa72019-04-05 14:44:40 -07001539 QUIC_CACHELINE_ALIGNED char buffer[kMaxIncomingPacketSize];
QUICHE teama6ef0a62019-03-07 20:34:33 -05001540 if (packet_has_ietf_packet_header) {
1541 rv = ProcessIetfDataPacket(&reader, &header, packet, buffer,
dschinazie8d7fa72019-04-05 14:44:40 -07001542 QUIC_ARRAYSIZE(buffer));
QUICHE teama6ef0a62019-03-07 20:34:33 -05001543 } else {
dschinazie8d7fa72019-04-05 14:44:40 -07001544 rv = ProcessDataPacket(&reader, &header, packet, buffer,
1545 QUIC_ARRAYSIZE(buffer));
QUICHE teama6ef0a62019-03-07 20:34:33 -05001546 }
1547 } else {
1548 std::unique_ptr<char[]> large_buffer(new char[packet.length()]);
1549 if (packet_has_ietf_packet_header) {
1550 rv = ProcessIetfDataPacket(&reader, &header, packet, large_buffer.get(),
1551 packet.length());
1552 } else {
1553 rv = ProcessDataPacket(&reader, &header, packet, large_buffer.get(),
1554 packet.length());
1555 }
1556 QUIC_BUG_IF(rv) << "QUIC should never successfully process packets larger"
dschinazie8d7fa72019-04-05 14:44:40 -07001557 << "than kMaxIncomingPacketSize. packet size:"
1558 << packet.length();
QUICHE teama6ef0a62019-03-07 20:34:33 -05001559 }
1560 return rv;
1561}
1562
1563bool QuicFramer::ProcessVersionNegotiationPacket(
1564 QuicDataReader* reader,
1565 const QuicPacketHeader& header) {
1566 DCHECK_EQ(Perspective::IS_CLIENT, perspective_);
1567
QUICHE team2252b702019-05-14 23:55:14 -04001568 QuicVersionNegotiationPacket packet(
1569 GetServerConnectionIdAsRecipient(header, perspective_));
QUICHE teama6ef0a62019-03-07 20:34:33 -05001570 // Try reading at least once to raise error if the packet is invalid.
1571 do {
1572 QuicVersionLabel version_label;
fayang40315542019-05-09 09:19:09 -07001573 if (!ProcessVersionLabel(reader, &version_label)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001574 set_detailed_error("Unable to read supported version in negotiation.");
1575 RecordDroppedPacketReason(
1576 DroppedPacketReason::INVALID_VERSION_NEGOTIATION_PACKET);
1577 return RaiseError(QUIC_INVALID_VERSION_NEGOTIATION_PACKET);
1578 }
nharper4fd11052019-06-04 14:23:22 -07001579 ParsedQuicVersion parsed_version = ParseQuicVersionLabel(version_label);
1580 if (parsed_version != UnsupportedQuicVersion()) {
1581 packet.versions.push_back(parsed_version);
1582 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001583 } while (!reader->IsDoneReading());
1584
dschinazi5a354c92019-05-09 12:18:53 -07001585 QUIC_DLOG(INFO) << ENDPOINT << "parsed version negotiation: "
1586 << ParsedQuicVersionVectorToString(packet.versions);
1587
QUICHE teama6ef0a62019-03-07 20:34:33 -05001588 visitor_->OnVersionNegotiationPacket(packet);
1589 return true;
1590}
1591
dschinazi244f6dc2019-05-06 15:45:16 -07001592bool QuicFramer::ProcessRetryPacket(QuicDataReader* reader,
1593 const QuicPacketHeader& header) {
1594 DCHECK_EQ(Perspective::IS_CLIENT, perspective_);
1595
1596 // Parse Original Destination Connection ID Length.
1597 uint8_t odcil = header.type_byte & 0xf;
1598 if (odcil != 0) {
1599 odcil += kConnectionIdLengthAdjustment;
1600 }
1601
1602 // Parse Original Destination Connection ID.
1603 QuicConnectionId original_destination_connection_id;
1604 if (!reader->ReadConnectionId(&original_destination_connection_id, odcil)) {
1605 set_detailed_error("Unable to read Original Destination ConnectionId.");
1606 return false;
1607 }
1608
1609 QuicStringPiece retry_token = reader->ReadRemainingPayload();
1610 visitor_->OnRetryPacket(original_destination_connection_id,
1611 header.source_connection_id, retry_token);
1612 return true;
1613}
1614
QUICHE teama6ef0a62019-03-07 20:34:33 -05001615bool QuicFramer::MaybeProcessIetfInitialRetryToken(
1616 QuicDataReader* encrypted_reader,
1617 QuicPacketHeader* header) {
1618 if (!QuicVersionHasLongHeaderLengths(header->version.transport_version) ||
1619 header->form != IETF_QUIC_LONG_HEADER_PACKET ||
1620 header->long_packet_type != INITIAL) {
1621 return true;
1622 }
1623 uint64_t retry_token_length = 0;
1624 header->retry_token_length_length = encrypted_reader->PeekVarInt62Length();
1625 if (!encrypted_reader->ReadVarInt62(&retry_token_length)) {
1626 set_detailed_error("Unable to read INITIAL retry token length.");
1627 return RaiseError(QUIC_INVALID_PACKET_HEADER);
1628 }
1629 header->retry_token = encrypted_reader->PeekRemainingPayload();
1630 // Safety check to avoid spending ressources if malformed.
1631 // At this point header->retry_token contains the rest of the packet
1632 // so its length() is the amount of data remaining in the packet.
1633 if (retry_token_length > header->retry_token.length()) {
1634 set_detailed_error("INITIAL token length longer than packet.");
1635 return RaiseError(QUIC_INVALID_PACKET_HEADER);
1636 }
1637 // Resize retry_token to make it only contain the retry token.
1638 header->retry_token.remove_suffix(header->retry_token.length() -
1639 retry_token_length);
1640 // Advance encrypted_reader by retry_token_length.
1641 uint8_t wasted_byte;
1642 for (uint64_t i = 0; i < retry_token_length; ++i) {
1643 if (!encrypted_reader->ReadUInt8(&wasted_byte)) {
1644 set_detailed_error("Unable to read INITIAL retry token.");
1645 return RaiseError(QUIC_INVALID_PACKET_HEADER);
1646 }
1647 }
1648 return true;
1649}
1650
1651// Seeks the current packet to check for a coalesced packet at the end.
1652// If the IETF length field only spans part of the outer packet,
1653// then there is a coalesced packet after this one.
1654void QuicFramer::MaybeProcessCoalescedPacket(
1655 const QuicDataReader& encrypted_reader,
1656 uint64_t remaining_bytes_length,
1657 const QuicPacketHeader& header) {
1658 if (header.remaining_packet_length >= remaining_bytes_length) {
1659 // There is no coalesced packet.
1660 return;
1661 }
1662
1663 QuicStringPiece remaining_data = encrypted_reader.PeekRemainingPayload();
1664 DCHECK_EQ(remaining_data.length(), remaining_bytes_length);
1665
1666 const char* coalesced_data =
1667 remaining_data.data() + header.remaining_packet_length;
1668 uint64_t coalesced_data_length =
1669 remaining_bytes_length - header.remaining_packet_length;
1670 QuicDataReader coalesced_reader(coalesced_data, coalesced_data_length);
1671
1672 QuicPacketHeader coalesced_header;
1673 if (!ProcessIetfPacketHeader(&coalesced_reader, &coalesced_header)) {
1674 QUIC_PEER_BUG << ENDPOINT
1675 << "Failed to parse received coalesced header of length "
1676 << coalesced_data_length << ": "
1677 << QuicTextUtils::HexEncode(coalesced_data,
1678 coalesced_data_length)
1679 << " previous header was " << header;
1680 return;
1681 }
1682
1683 if (coalesced_header.destination_connection_id !=
1684 header.destination_connection_id ||
1685 (coalesced_header.form != IETF_QUIC_SHORT_HEADER_PACKET &&
1686 coalesced_header.version != header.version)) {
1687 QUIC_PEER_BUG << ENDPOINT << "Received mismatched coalesced header "
1688 << coalesced_header << " previous header was " << header;
1689 return;
1690 }
1691
1692 QuicEncryptedPacket coalesced_packet(coalesced_data, coalesced_data_length,
1693 /*owns_buffer=*/false);
1694 visitor_->OnCoalescedPacket(coalesced_packet);
1695}
1696
1697bool QuicFramer::MaybeProcessIetfLength(QuicDataReader* encrypted_reader,
1698 QuicPacketHeader* header) {
1699 if (!QuicVersionHasLongHeaderLengths(header->version.transport_version) ||
1700 header->form != IETF_QUIC_LONG_HEADER_PACKET ||
1701 (header->long_packet_type != INITIAL &&
1702 header->long_packet_type != HANDSHAKE &&
1703 header->long_packet_type != ZERO_RTT_PROTECTED)) {
1704 return true;
1705 }
1706 header->length_length = encrypted_reader->PeekVarInt62Length();
1707 if (!encrypted_reader->ReadVarInt62(&header->remaining_packet_length)) {
1708 set_detailed_error("Unable to read long header payload length.");
1709 return RaiseError(QUIC_INVALID_PACKET_HEADER);
1710 }
1711 uint64_t remaining_bytes_length = encrypted_reader->BytesRemaining();
1712 if (header->remaining_packet_length > remaining_bytes_length) {
1713 set_detailed_error("Long header payload length longer than packet.");
1714 return RaiseError(QUIC_INVALID_PACKET_HEADER);
1715 }
1716
1717 MaybeProcessCoalescedPacket(*encrypted_reader, remaining_bytes_length,
1718 *header);
1719
1720 if (!encrypted_reader->TruncateRemaining(header->remaining_packet_length)) {
1721 set_detailed_error("Length TruncateRemaining failed.");
1722 QUIC_BUG << "Length TruncateRemaining failed.";
1723 return RaiseError(QUIC_INVALID_PACKET_HEADER);
1724 }
1725 return true;
1726}
1727
1728bool QuicFramer::ProcessIetfDataPacket(QuicDataReader* encrypted_reader,
1729 QuicPacketHeader* header,
1730 const QuicEncryptedPacket& packet,
1731 char* decrypted_buffer,
1732 size_t buffer_length) {
1733 DCHECK_NE(GOOGLE_QUIC_PACKET, header->form);
1734 DCHECK(!header->has_possible_stateless_reset_token);
1735 header->retry_token_length_length = VARIABLE_LENGTH_INTEGER_LENGTH_0;
1736 header->retry_token = QuicStringPiece();
1737 header->length_length = VARIABLE_LENGTH_INTEGER_LENGTH_0;
1738 header->remaining_packet_length = 0;
1739 if (header->form == IETF_QUIC_SHORT_HEADER_PACKET &&
1740 perspective_ == Perspective::IS_CLIENT) {
1741 // Peek possible stateless reset token. Will only be used on decryption
1742 // failure.
1743 QuicStringPiece remaining = encrypted_reader->PeekRemainingPayload();
1744 if (remaining.length() >= sizeof(header->possible_stateless_reset_token)) {
1745 header->has_possible_stateless_reset_token = true;
1746 memcpy(&header->possible_stateless_reset_token,
1747 &remaining.data()[remaining.length() -
1748 sizeof(header->possible_stateless_reset_token)],
1749 sizeof(header->possible_stateless_reset_token));
1750 }
1751 }
1752
1753 if (!MaybeProcessIetfInitialRetryToken(encrypted_reader, header)) {
1754 return false;
1755 }
1756
1757 if (!MaybeProcessIetfLength(encrypted_reader, header)) {
1758 return false;
1759 }
1760
nharper55fa6132019-05-07 19:37:21 -07001761 QuicStringPiece associated_data;
1762 std::vector<char> ad_storage;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001763 if (header->form == IETF_QUIC_SHORT_HEADER_PACKET ||
1764 header->long_packet_type != VERSION_NEGOTIATION) {
dschinazi072da7c2019-05-07 17:57:42 -07001765 DCHECK(header->form == IETF_QUIC_SHORT_HEADER_PACKET ||
1766 header->long_packet_type == INITIAL ||
1767 header->long_packet_type == HANDSHAKE ||
1768 header->long_packet_type == ZERO_RTT_PROTECTED);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001769 // Process packet number.
QUICHE team10b22a12019-03-21 15:31:42 -07001770 QuicPacketNumber base_packet_number;
1771 if (supports_multiple_packet_number_spaces_) {
nharper55fa6132019-05-07 19:37:21 -07001772 PacketNumberSpace pn_space = GetPacketNumberSpace(*header);
1773 if (pn_space == NUM_PACKET_NUMBER_SPACES) {
1774 return RaiseError(QUIC_INVALID_PACKET_HEADER);
1775 }
1776 base_packet_number = largest_decrypted_packet_numbers_[pn_space];
QUICHE team10b22a12019-03-21 15:31:42 -07001777 } else {
1778 base_packet_number = largest_packet_number_;
1779 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001780 uint64_t full_packet_number;
nharper55fa6132019-05-07 19:37:21 -07001781 bool hp_removal_failed = false;
1782 if (version_.HasHeaderProtection()) {
1783 if (!RemoveHeaderProtection(encrypted_reader, packet, header,
1784 &full_packet_number, &ad_storage)) {
1785 hp_removal_failed = true;
1786 }
1787 associated_data = QuicStringPiece(ad_storage.data(), ad_storage.size());
1788 } else if (!ProcessAndCalculatePacketNumber(
1789 encrypted_reader, header->packet_number_length,
1790 base_packet_number, &full_packet_number)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001791 set_detailed_error("Unable to read packet number.");
1792 RecordDroppedPacketReason(DroppedPacketReason::INVALID_PACKET_NUMBER);
1793 return RaiseError(QUIC_INVALID_PACKET_HEADER);
1794 }
1795
nharper55fa6132019-05-07 19:37:21 -07001796 if (hp_removal_failed ||
1797 !IsValidFullPacketNumber(full_packet_number, transport_version())) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001798 if (IsIetfStatelessResetPacket(*header)) {
1799 // This is a stateless reset packet.
1800 QuicIetfStatelessResetPacket packet(
1801 *header, header->possible_stateless_reset_token);
1802 visitor_->OnAuthenticatedIetfStatelessResetPacket(packet);
1803 return true;
1804 }
nharper55fa6132019-05-07 19:37:21 -07001805 if (hp_removal_failed) {
1806 set_detailed_error("Unable to decrypt header protection.");
1807 return RaiseError(QUIC_DECRYPTION_FAILURE);
1808 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001809 RecordDroppedPacketReason(DroppedPacketReason::INVALID_PACKET_NUMBER);
1810 set_detailed_error("packet numbers cannot be 0.");
1811 return RaiseError(QUIC_INVALID_PACKET_HEADER);
1812 }
1813 header->packet_number = QuicPacketNumber(full_packet_number);
1814 }
1815
1816 // A nonce should only present in SHLO from the server to the client when
1817 // using QUIC crypto.
1818 if (header->form == IETF_QUIC_LONG_HEADER_PACKET &&
1819 header->long_packet_type == ZERO_RTT_PROTECTED &&
1820 perspective_ == Perspective::IS_CLIENT &&
1821 version_.handshake_protocol == PROTOCOL_QUIC_CRYPTO) {
1822 if (!encrypted_reader->ReadBytes(
1823 reinterpret_cast<uint8_t*>(last_nonce_.data()),
1824 last_nonce_.size())) {
1825 set_detailed_error("Unable to read nonce.");
1826 RecordDroppedPacketReason(
1827 DroppedPacketReason::INVALID_DIVERSIFICATION_NONCE);
1828 return RaiseError(QUIC_INVALID_PACKET_HEADER);
1829 }
1830
1831 header->nonce = &last_nonce_;
1832 } else {
1833 header->nonce = nullptr;
1834 }
1835
1836 if (!visitor_->OnUnauthenticatedHeader(*header)) {
1837 set_detailed_error(
1838 "Visitor asked to stop processing of unauthenticated header.");
1839 return false;
1840 }
1841
1842 QuicStringPiece encrypted = encrypted_reader->ReadRemainingPayload();
nharper55fa6132019-05-07 19:37:21 -07001843 if (!version_.HasHeaderProtection()) {
1844 associated_data = GetAssociatedDataFromEncryptedPacket(
1845 version_.transport_version, packet,
1846 GetIncludedDestinationConnectionIdLength(*header),
1847 GetIncludedSourceConnectionIdLength(*header), header->version_flag,
1848 header->nonce != nullptr, header->packet_number_length,
1849 header->retry_token_length_length, header->retry_token.length(),
1850 header->length_length);
1851 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001852
1853 size_t decrypted_length = 0;
QUICHE team10b22a12019-03-21 15:31:42 -07001854 EncryptionLevel decrypted_level;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001855 if (!DecryptPayload(encrypted, associated_data, *header, decrypted_buffer,
QUICHE team10b22a12019-03-21 15:31:42 -07001856 buffer_length, &decrypted_length, &decrypted_level)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001857 if (IsIetfStatelessResetPacket(*header)) {
1858 // This is a stateless reset packet.
1859 QuicIetfStatelessResetPacket packet(
1860 *header, header->possible_stateless_reset_token);
1861 visitor_->OnAuthenticatedIetfStatelessResetPacket(packet);
1862 return true;
1863 }
1864 set_detailed_error("Unable to decrypt payload.");
1865 RecordDroppedPacketReason(DroppedPacketReason::DECRYPTION_FAILURE);
1866 return RaiseError(QUIC_DECRYPTION_FAILURE);
1867 }
1868 QuicDataReader reader(decrypted_buffer, decrypted_length);
1869
1870 // Update the largest packet number after we have decrypted the packet
1871 // so we are confident is not attacker controlled.
QUICHE team10b22a12019-03-21 15:31:42 -07001872 if (supports_multiple_packet_number_spaces_) {
1873 largest_decrypted_packet_numbers_[QuicUtils::GetPacketNumberSpace(
1874 decrypted_level)]
1875 .UpdateMax(header->packet_number);
1876 } else {
1877 largest_packet_number_.UpdateMax(header->packet_number);
1878 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001879
1880 if (!visitor_->OnPacketHeader(*header)) {
1881 RecordDroppedPacketReason(DroppedPacketReason::INVALID_PACKET_NUMBER);
1882 // The visitor suppresses further processing of the packet.
1883 return true;
1884 }
1885
dschinazie8d7fa72019-04-05 14:44:40 -07001886 if (packet.length() > kMaxIncomingPacketSize) {
1887 set_detailed_error("Packet too large.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05001888 return RaiseError(QUIC_PACKET_TOO_LARGE);
1889 }
1890
1891 // Handle the payload.
fkastenholz305e1732019-06-18 05:01:22 -07001892 if (VersionHasIetfQuicFrames(version_.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001893 if (!ProcessIetfFrameData(&reader, *header)) {
1894 DCHECK_NE(QUIC_NO_ERROR, error_); // ProcessIetfFrameData sets the error.
1895 DCHECK_NE("", detailed_error_);
1896 QUIC_DLOG(WARNING) << ENDPOINT << "Unable to process frame data. Error: "
1897 << detailed_error_;
1898 return false;
1899 }
1900 } else {
1901 if (!ProcessFrameData(&reader, *header)) {
1902 DCHECK_NE(QUIC_NO_ERROR, error_); // ProcessFrameData sets the error.
1903 DCHECK_NE("", detailed_error_);
1904 QUIC_DLOG(WARNING) << ENDPOINT << "Unable to process frame data. Error: "
1905 << detailed_error_;
1906 return false;
1907 }
1908 }
1909
1910 visitor_->OnPacketComplete();
1911 return true;
1912}
1913
1914bool QuicFramer::ProcessDataPacket(QuicDataReader* encrypted_reader,
1915 QuicPacketHeader* header,
1916 const QuicEncryptedPacket& packet,
1917 char* decrypted_buffer,
1918 size_t buffer_length) {
1919 if (!ProcessUnauthenticatedHeader(encrypted_reader, header)) {
1920 DCHECK_NE("", detailed_error_);
1921 QUIC_DVLOG(1)
1922 << ENDPOINT
1923 << "Unable to process packet header. Stopping parsing. Error: "
1924 << detailed_error_;
1925 RecordDroppedPacketReason(DroppedPacketReason::INVALID_PACKET_NUMBER);
1926 return false;
1927 }
1928
1929 QuicStringPiece encrypted = encrypted_reader->ReadRemainingPayload();
1930 QuicStringPiece associated_data = GetAssociatedDataFromEncryptedPacket(
1931 version_.transport_version, packet,
1932 GetIncludedDestinationConnectionIdLength(*header),
1933 GetIncludedSourceConnectionIdLength(*header), header->version_flag,
1934 header->nonce != nullptr, header->packet_number_length,
1935 header->retry_token_length_length, header->retry_token.length(),
1936 header->length_length);
1937
1938 size_t decrypted_length = 0;
QUICHE team10b22a12019-03-21 15:31:42 -07001939 EncryptionLevel decrypted_level;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001940 if (!DecryptPayload(encrypted, associated_data, *header, decrypted_buffer,
QUICHE team10b22a12019-03-21 15:31:42 -07001941 buffer_length, &decrypted_length, &decrypted_level)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001942 RecordDroppedPacketReason(DroppedPacketReason::DECRYPTION_FAILURE);
1943 set_detailed_error("Unable to decrypt payload.");
1944 return RaiseError(QUIC_DECRYPTION_FAILURE);
1945 }
1946
1947 QuicDataReader reader(decrypted_buffer, decrypted_length);
1948
1949 // Update the largest packet number after we have decrypted the packet
1950 // so we are confident is not attacker controlled.
QUICHE team10b22a12019-03-21 15:31:42 -07001951 if (supports_multiple_packet_number_spaces_) {
1952 largest_decrypted_packet_numbers_[QuicUtils::GetPacketNumberSpace(
1953 decrypted_level)]
1954 .UpdateMax(header->packet_number);
1955 } else {
1956 largest_packet_number_.UpdateMax(header->packet_number);
1957 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001958
1959 if (!visitor_->OnPacketHeader(*header)) {
1960 // The visitor suppresses further processing of the packet.
1961 return true;
1962 }
1963
dschinazie8d7fa72019-04-05 14:44:40 -07001964 if (packet.length() > kMaxIncomingPacketSize) {
1965 set_detailed_error("Packet too large.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05001966 return RaiseError(QUIC_PACKET_TOO_LARGE);
1967 }
1968
1969 // Handle the payload.
1970 if (!ProcessFrameData(&reader, *header)) {
1971 DCHECK_NE(QUIC_NO_ERROR, error_); // ProcessFrameData sets the error.
1972 DCHECK_NE("", detailed_error_);
1973 QUIC_DLOG(WARNING) << ENDPOINT << "Unable to process frame data. Error: "
1974 << detailed_error_;
1975 return false;
1976 }
1977
1978 visitor_->OnPacketComplete();
1979 return true;
1980}
1981
1982bool QuicFramer::ProcessPublicResetPacket(QuicDataReader* reader,
1983 const QuicPacketHeader& header) {
QUICHE team2252b702019-05-14 23:55:14 -04001984 QuicPublicResetPacket packet(
1985 GetServerConnectionIdAsRecipient(header, perspective_));
QUICHE teama6ef0a62019-03-07 20:34:33 -05001986
1987 std::unique_ptr<CryptoHandshakeMessage> reset(
1988 CryptoFramer::ParseMessage(reader->ReadRemainingPayload()));
1989 if (!reset.get()) {
1990 set_detailed_error("Unable to read reset message.");
1991 RecordDroppedPacketReason(DroppedPacketReason::INVALID_PUBLIC_RESET_PACKET);
1992 return RaiseError(QUIC_INVALID_PUBLIC_RST_PACKET);
1993 }
1994 if (reset->tag() != kPRST) {
1995 set_detailed_error("Incorrect message tag.");
1996 RecordDroppedPacketReason(DroppedPacketReason::INVALID_PUBLIC_RESET_PACKET);
1997 return RaiseError(QUIC_INVALID_PUBLIC_RST_PACKET);
1998 }
1999
2000 if (reset->GetUint64(kRNON, &packet.nonce_proof) != QUIC_NO_ERROR) {
2001 set_detailed_error("Unable to read nonce proof.");
2002 RecordDroppedPacketReason(DroppedPacketReason::INVALID_PUBLIC_RESET_PACKET);
2003 return RaiseError(QUIC_INVALID_PUBLIC_RST_PACKET);
2004 }
2005 // TODO(satyamshekhar): validate nonce to protect against DoS.
2006
2007 QuicStringPiece address;
2008 if (reset->GetStringPiece(kCADR, &address)) {
2009 QuicSocketAddressCoder address_coder;
2010 if (address_coder.Decode(address.data(), address.length())) {
2011 packet.client_address =
2012 QuicSocketAddress(address_coder.ip(), address_coder.port());
2013 }
2014 }
2015
2016 QuicStringPiece endpoint_id;
2017 if (perspective_ == Perspective::IS_CLIENT &&
2018 reset->GetStringPiece(kEPID, &endpoint_id)) {
vasilvvc48c8712019-03-11 13:38:16 -07002019 packet.endpoint_id = std::string(endpoint_id);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002020 packet.endpoint_id += '\0';
2021 }
2022
2023 visitor_->OnPublicResetPacket(packet);
2024 return true;
2025}
2026
2027bool QuicFramer::IsIetfStatelessResetPacket(
2028 const QuicPacketHeader& header) const {
2029 QUIC_BUG_IF(header.has_possible_stateless_reset_token &&
2030 perspective_ != Perspective::IS_CLIENT)
2031 << "has_possible_stateless_reset_token can only be true at client side.";
2032 return header.form == IETF_QUIC_SHORT_HEADER_PACKET &&
2033 header.has_possible_stateless_reset_token &&
2034 visitor_->IsValidStatelessResetToken(
2035 header.possible_stateless_reset_token);
2036}
2037
2038bool QuicFramer::HasEncrypterOfEncryptionLevel(EncryptionLevel level) const {
2039 return encrypter_[level] != nullptr;
2040}
2041
2042bool QuicFramer::AppendPacketHeader(const QuicPacketHeader& header,
2043 QuicDataWriter* writer,
2044 size_t* length_field_offset) {
fayangd4291e42019-05-30 10:31:21 -07002045 if (VersionHasIetfInvariantHeader(transport_version())) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002046 return AppendIetfPacketHeader(header, writer, length_field_offset);
2047 }
2048 QUIC_DVLOG(1) << ENDPOINT << "Appending header: " << header;
2049 uint8_t public_flags = 0;
2050 if (header.reset_flag) {
2051 public_flags |= PACKET_PUBLIC_FLAGS_RST;
2052 }
2053 if (header.version_flag) {
2054 public_flags |= PACKET_PUBLIC_FLAGS_VERSION;
2055 }
2056
2057 public_flags |= GetPacketNumberFlags(header.packet_number_length)
2058 << kPublicHeaderSequenceNumberShift;
2059
2060 if (header.nonce != nullptr) {
2061 DCHECK_EQ(Perspective::IS_SERVER, perspective_);
2062 public_flags |= PACKET_PUBLIC_FLAGS_NONCE;
2063 }
QUICHE team2252b702019-05-14 23:55:14 -04002064
dschinazi7b9278c2019-05-20 07:36:21 -07002065 QuicConnectionId server_connection_id =
QUICHE team2252b702019-05-14 23:55:14 -04002066 GetServerConnectionIdAsSender(header, perspective_);
dschinazi7b9278c2019-05-20 07:36:21 -07002067 QuicConnectionIdIncluded server_connection_id_included =
QUICHE team2252b702019-05-14 23:55:14 -04002068 GetServerConnectionIdIncludedAsSender(header, perspective_);
2069 DCHECK_EQ(CONNECTION_ID_ABSENT,
2070 GetClientConnectionIdIncludedAsSender(header, perspective_));
2071
dschinazi7b9278c2019-05-20 07:36:21 -07002072 switch (server_connection_id_included) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002073 case CONNECTION_ID_ABSENT:
2074 if (!writer->WriteUInt8(public_flags |
2075 PACKET_PUBLIC_FLAGS_0BYTE_CONNECTION_ID)) {
2076 return false;
2077 }
2078 break;
2079 case CONNECTION_ID_PRESENT:
2080 QUIC_BUG_IF(!QuicUtils::IsConnectionIdValidForVersion(
dschinazi7b9278c2019-05-20 07:36:21 -07002081 server_connection_id, transport_version()))
QUICHE teama6ef0a62019-03-07 20:34:33 -05002082 << "AppendPacketHeader: attempted to use connection ID "
dschinazi7b9278c2019-05-20 07:36:21 -07002083 << server_connection_id << " which is invalid with version "
QUICHE teama6ef0a62019-03-07 20:34:33 -05002084 << QuicVersionToString(transport_version());
2085
2086 public_flags |= PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID;
2087 if (perspective_ == Perspective::IS_CLIENT) {
2088 public_flags |= PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID_OLD;
2089 }
2090 if (!writer->WriteUInt8(public_flags) ||
dschinazi7b9278c2019-05-20 07:36:21 -07002091 !writer->WriteConnectionId(server_connection_id)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002092 return false;
2093 }
2094 break;
2095 }
dschinazi7b9278c2019-05-20 07:36:21 -07002096 last_serialized_server_connection_id_ = server_connection_id;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002097
2098 if (header.version_flag) {
2099 DCHECK_EQ(Perspective::IS_CLIENT, perspective_);
2100 QuicVersionLabel version_label = CreateQuicVersionLabel(version_);
nharpereaab5ad2019-05-31 12:23:25 -07002101 if (!writer->WriteUInt32(version_label)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002102 return false;
2103 }
2104
2105 QUIC_DVLOG(1) << ENDPOINT << "label = '"
2106 << QuicVersionLabelToString(version_label) << "'";
2107 }
2108
2109 if (header.nonce != nullptr &&
2110 !writer->WriteBytes(header.nonce, kDiversificationNonceSize)) {
2111 return false;
2112 }
2113
2114 if (!AppendPacketNumber(header.packet_number_length, header.packet_number,
2115 writer)) {
2116 return false;
2117 }
2118
2119 return true;
2120}
2121
2122bool QuicFramer::AppendIetfHeaderTypeByte(const QuicPacketHeader& header,
2123 QuicDataWriter* writer) {
2124 uint8_t type = 0;
fayangf36e29d2019-06-06 14:03:40 -07002125 if (transport_version() > QUIC_VERSION_44) {
2126 if (header.version_flag) {
2127 type = static_cast<uint8_t>(
2128 FLAGS_LONG_HEADER | FLAGS_FIXED_BIT |
2129 LongHeaderTypeToOnWireValue(transport_version(),
2130 header.long_packet_type) |
2131 PacketNumberLengthToOnWireValue(transport_version(),
2132 header.packet_number_length));
2133 } else {
2134 type = static_cast<uint8_t>(
2135 FLAGS_FIXED_BIT |
2136 PacketNumberLengthToOnWireValue(transport_version(),
2137 header.packet_number_length));
2138 }
2139 return writer->WriteUInt8(type);
2140 }
2141
QUICHE teama6ef0a62019-03-07 20:34:33 -05002142 if (header.version_flag) {
2143 type = static_cast<uint8_t>(
fayangf36e29d2019-06-06 14:03:40 -07002144 FLAGS_LONG_HEADER | LongHeaderTypeToOnWireValue(
2145 transport_version(), header.long_packet_type));
2146 DCHECK_EQ(PACKET_4BYTE_PACKET_NUMBER, header.packet_number_length);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002147 } else {
fayangf36e29d2019-06-06 14:03:40 -07002148 type |= FLAGS_SHORT_HEADER_RESERVED_1;
2149 type |= FLAGS_SHORT_HEADER_RESERVED_2;
2150 DCHECK_GE(PACKET_4BYTE_PACKET_NUMBER, header.packet_number_length);
2151 type |= PacketNumberLengthToOnWireValue(transport_version(),
2152 header.packet_number_length);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002153 }
2154 return writer->WriteUInt8(type);
2155}
2156
2157bool QuicFramer::AppendIetfPacketHeader(const QuicPacketHeader& header,
2158 QuicDataWriter* writer,
2159 size_t* length_field_offset) {
2160 QUIC_DVLOG(1) << ENDPOINT << "Appending IETF header: " << header;
QUICHE team2252b702019-05-14 23:55:14 -04002161 QuicConnectionId server_connection_id =
2162 GetServerConnectionIdAsSender(header, perspective_);
2163 QUIC_BUG_IF(!QuicUtils::IsConnectionIdValidForVersion(server_connection_id,
2164 transport_version()))
QUICHE teama6ef0a62019-03-07 20:34:33 -05002165 << "AppendIetfPacketHeader: attempted to use connection ID "
QUICHE team2252b702019-05-14 23:55:14 -04002166 << server_connection_id << " which is invalid with version "
QUICHE teama6ef0a62019-03-07 20:34:33 -05002167 << QuicVersionToString(transport_version());
2168 if (!AppendIetfHeaderTypeByte(header, writer)) {
2169 return false;
2170 }
2171
2172 if (header.version_flag) {
2173 // Append version for long header.
2174 QuicVersionLabel version_label = CreateQuicVersionLabel(version_);
nharpereaab5ad2019-05-31 12:23:25 -07002175 if (!writer->WriteUInt32(version_label)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002176 return false;
2177 }
2178 }
2179
2180 // Append connection ID.
dschinazi1f485a12019-05-13 11:57:01 -07002181 if (!AppendIetfConnectionIds(
2182 header.version_flag,
2183 header.destination_connection_id_included != CONNECTION_ID_ABSENT
2184 ? header.destination_connection_id
2185 : EmptyQuicConnectionId(),
2186 header.source_connection_id_included != CONNECTION_ID_ABSENT
2187 ? header.source_connection_id
2188 : EmptyQuicConnectionId(),
2189 writer)) {
2190 return false;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002191 }
dschinazi1f485a12019-05-13 11:57:01 -07002192
dschinazi7b9278c2019-05-20 07:36:21 -07002193 last_serialized_server_connection_id_ = server_connection_id;
dschinazi346b7ce2019-06-05 01:38:18 -07002194 if (version_.SupportsClientConnectionIds()) {
2195 last_serialized_client_connection_id_ =
2196 GetClientConnectionIdAsSender(header, perspective_);
2197 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002198
2199 if (QuicVersionHasLongHeaderLengths(transport_version()) &&
2200 header.version_flag) {
2201 if (header.long_packet_type == INITIAL) {
2202 // Write retry token length.
2203 if (!writer->WriteVarInt62(header.retry_token.length(),
2204 header.retry_token_length_length)) {
2205 return false;
2206 }
2207 // Write retry token.
2208 if (!header.retry_token.empty() &&
2209 !writer->WriteStringPiece(header.retry_token)) {
2210 return false;
2211 }
2212 }
2213 if (length_field_offset != nullptr) {
2214 *length_field_offset = writer->length();
2215 }
2216 // Add fake length to reserve two bytes to add length in later.
2217 writer->WriteVarInt62(256);
2218 } else if (length_field_offset != nullptr) {
2219 *length_field_offset = 0;
2220 }
2221
2222 // Append packet number.
2223 if (!AppendPacketNumber(header.packet_number_length, header.packet_number,
2224 writer)) {
2225 return false;
2226 }
nharper55fa6132019-05-07 19:37:21 -07002227 last_written_packet_number_length_ = header.packet_number_length;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002228
2229 if (!header.version_flag) {
2230 return true;
2231 }
2232
2233 if (header.nonce != nullptr) {
2234 DCHECK(header.version_flag);
2235 DCHECK_EQ(ZERO_RTT_PROTECTED, header.long_packet_type);
2236 DCHECK_EQ(Perspective::IS_SERVER, perspective_);
2237 if (!writer->WriteBytes(header.nonce, kDiversificationNonceSize)) {
2238 return false;
2239 }
2240 }
2241
2242 return true;
2243}
2244
2245const QuicTime::Delta QuicFramer::CalculateTimestampFromWire(
2246 uint32_t time_delta_us) {
2247 // The new time_delta might have wrapped to the next epoch, or it
2248 // might have reverse wrapped to the previous epoch, or it might
2249 // remain in the same epoch. Select the time closest to the previous
2250 // time.
2251 //
2252 // epoch_delta is the delta between epochs. A delta is 4 bytes of
2253 // microseconds.
2254 const uint64_t epoch_delta = UINT64_C(1) << 32;
2255 uint64_t epoch = last_timestamp_.ToMicroseconds() & ~(epoch_delta - 1);
2256 // Wrapping is safe here because a wrapped value will not be ClosestTo below.
2257 uint64_t prev_epoch = epoch - epoch_delta;
2258 uint64_t next_epoch = epoch + epoch_delta;
2259
2260 uint64_t time = ClosestTo(
2261 last_timestamp_.ToMicroseconds(), epoch + time_delta_us,
2262 ClosestTo(last_timestamp_.ToMicroseconds(), prev_epoch + time_delta_us,
2263 next_epoch + time_delta_us));
2264
2265 return QuicTime::Delta::FromMicroseconds(time);
2266}
2267
2268uint64_t QuicFramer::CalculatePacketNumberFromWire(
2269 QuicPacketNumberLength packet_number_length,
2270 QuicPacketNumber base_packet_number,
2271 uint64_t packet_number) const {
2272 // The new packet number might have wrapped to the next epoch, or
2273 // it might have reverse wrapped to the previous epoch, or it might
2274 // remain in the same epoch. Select the packet number closest to the
2275 // next expected packet number, the previous packet number plus 1.
2276
2277 // epoch_delta is the delta between epochs the packet number was serialized
2278 // with, so the correct value is likely the same epoch as the last sequence
2279 // number or an adjacent epoch.
2280 if (!base_packet_number.IsInitialized()) {
2281 return packet_number;
2282 }
2283 const uint64_t epoch_delta = UINT64_C(1) << (8 * packet_number_length);
2284 uint64_t next_packet_number = base_packet_number.ToUint64() + 1;
2285 uint64_t epoch = base_packet_number.ToUint64() & ~(epoch_delta - 1);
2286 uint64_t prev_epoch = epoch - epoch_delta;
2287 uint64_t next_epoch = epoch + epoch_delta;
2288
2289 return ClosestTo(next_packet_number, epoch + packet_number,
2290 ClosestTo(next_packet_number, prev_epoch + packet_number,
2291 next_epoch + packet_number));
2292}
2293
2294bool QuicFramer::ProcessPublicHeader(QuicDataReader* reader,
2295 bool packet_has_ietf_packet_header,
2296 QuicPacketHeader* header) {
2297 if (packet_has_ietf_packet_header) {
2298 return ProcessIetfPacketHeader(reader, header);
2299 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002300 uint8_t public_flags;
2301 if (!reader->ReadBytes(&public_flags, 1)) {
2302 set_detailed_error("Unable to read public flags.");
2303 return false;
2304 }
2305
2306 header->reset_flag = (public_flags & PACKET_PUBLIC_FLAGS_RST) != 0;
2307 header->version_flag = (public_flags & PACKET_PUBLIC_FLAGS_VERSION) != 0;
2308
2309 if (validate_flags_ && !header->version_flag &&
2310 public_flags > PACKET_PUBLIC_FLAGS_MAX) {
2311 set_detailed_error("Illegal public flags value.");
2312 return false;
2313 }
2314
2315 if (header->reset_flag && header->version_flag) {
2316 set_detailed_error("Got version flag in reset packet");
2317 return false;
2318 }
2319
QUICHE team2252b702019-05-14 23:55:14 -04002320 QuicConnectionId* header_connection_id = &header->destination_connection_id;
2321 QuicConnectionIdIncluded* header_connection_id_included =
2322 &header->destination_connection_id_included;
2323 if (perspective_ == Perspective::IS_CLIENT &&
2324 GetQuicRestartFlag(quic_do_not_override_connection_id)) {
2325 header_connection_id = &header->source_connection_id;
2326 header_connection_id_included = &header->source_connection_id_included;
2327 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002328 switch (public_flags & PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID) {
2329 case PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID:
QUICHE team2252b702019-05-14 23:55:14 -04002330 if (!reader->ReadConnectionId(header_connection_id,
QUICHE teama6ef0a62019-03-07 20:34:33 -05002331 kQuicDefaultConnectionIdLength)) {
2332 set_detailed_error("Unable to read ConnectionId.");
2333 return false;
2334 }
QUICHE team2252b702019-05-14 23:55:14 -04002335 *header_connection_id_included = CONNECTION_ID_PRESENT;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002336 break;
2337 case PACKET_PUBLIC_FLAGS_0BYTE_CONNECTION_ID:
QUICHE team2252b702019-05-14 23:55:14 -04002338 *header_connection_id_included = CONNECTION_ID_ABSENT;
dschinazi7b9278c2019-05-20 07:36:21 -07002339 *header_connection_id = last_serialized_server_connection_id_;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002340 break;
2341 }
2342
2343 header->packet_number_length = ReadSequenceNumberLength(
2344 public_flags >> kPublicHeaderSequenceNumberShift);
2345
2346 // Read the version only if the packet is from the client.
2347 // version flag from the server means version negotiation packet.
2348 if (header->version_flag && perspective_ == Perspective::IS_SERVER) {
2349 QuicVersionLabel version_label;
fayang40315542019-05-09 09:19:09 -07002350 if (!ProcessVersionLabel(reader, &version_label)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002351 set_detailed_error("Unable to read protocol version.");
2352 return false;
2353 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002354 // If the version from the new packet is the same as the version of this
2355 // framer, then the public flags should be set to something we understand.
2356 // If not, this raises an error.
QUICHE teama6ef0a62019-03-07 20:34:33 -05002357 ParsedQuicVersion version = ParseQuicVersionLabel(version_label);
2358 if (version == version_ && public_flags > PACKET_PUBLIC_FLAGS_MAX) {
2359 set_detailed_error("Illegal public flags value.");
2360 return false;
2361 }
2362 header->version = version;
2363 }
2364
2365 // A nonce should only be present in packets from the server to the client,
2366 // which are neither version negotiation nor public reset packets.
2367 if (public_flags & PACKET_PUBLIC_FLAGS_NONCE &&
2368 !(public_flags & PACKET_PUBLIC_FLAGS_VERSION) &&
2369 !(public_flags & PACKET_PUBLIC_FLAGS_RST) &&
2370 // The nonce flag from a client is ignored and is assumed to be an older
2371 // client indicating an eight-byte connection ID.
2372 perspective_ == Perspective::IS_CLIENT) {
2373 if (!reader->ReadBytes(reinterpret_cast<uint8_t*>(last_nonce_.data()),
2374 last_nonce_.size())) {
2375 set_detailed_error("Unable to read nonce.");
2376 return false;
2377 }
2378 header->nonce = &last_nonce_;
2379 } else {
2380 header->nonce = nullptr;
2381 }
2382
2383 return true;
2384}
2385
2386// static
2387QuicPacketNumberLength QuicFramer::GetMinPacketNumberLength(
dschinazi17d42422019-06-18 16:35:07 -07002388 QuicTransportVersion /*version*/,
QUICHE teama6ef0a62019-03-07 20:34:33 -05002389 QuicPacketNumber packet_number) {
2390 DCHECK(packet_number.IsInitialized());
2391 if (packet_number < QuicPacketNumber(1 << (PACKET_1BYTE_PACKET_NUMBER * 8))) {
2392 return PACKET_1BYTE_PACKET_NUMBER;
2393 } else if (packet_number <
2394 QuicPacketNumber(1 << (PACKET_2BYTE_PACKET_NUMBER * 8))) {
2395 return PACKET_2BYTE_PACKET_NUMBER;
2396 } else if (packet_number <
2397 QuicPacketNumber(UINT64_C(1)
2398 << (PACKET_4BYTE_PACKET_NUMBER * 8))) {
2399 return PACKET_4BYTE_PACKET_NUMBER;
2400 } else {
2401 return PACKET_6BYTE_PACKET_NUMBER;
2402 }
2403}
2404
2405// static
2406uint8_t QuicFramer::GetPacketNumberFlags(
2407 QuicPacketNumberLength packet_number_length) {
2408 switch (packet_number_length) {
2409 case PACKET_1BYTE_PACKET_NUMBER:
2410 return PACKET_FLAGS_1BYTE_PACKET;
2411 case PACKET_2BYTE_PACKET_NUMBER:
2412 return PACKET_FLAGS_2BYTE_PACKET;
2413 case PACKET_4BYTE_PACKET_NUMBER:
2414 return PACKET_FLAGS_4BYTE_PACKET;
2415 case PACKET_6BYTE_PACKET_NUMBER:
2416 case PACKET_8BYTE_PACKET_NUMBER:
2417 return PACKET_FLAGS_8BYTE_PACKET;
2418 default:
2419 QUIC_BUG << "Unreachable case statement.";
2420 return PACKET_FLAGS_8BYTE_PACKET;
2421 }
2422}
2423
2424// static
2425QuicFramer::AckFrameInfo QuicFramer::GetAckFrameInfo(
2426 const QuicAckFrame& frame) {
2427 AckFrameInfo new_ack_info;
2428 if (frame.packets.Empty()) {
2429 return new_ack_info;
2430 }
2431 // The first block is the last interval. It isn't encoded with the gap-length
2432 // encoding, so skip it.
2433 new_ack_info.first_block_length = frame.packets.LastIntervalLength();
2434 auto itr = frame.packets.rbegin();
2435 QuicPacketNumber previous_start = itr->min();
2436 new_ack_info.max_block_length = PacketNumberIntervalLength(*itr);
2437 ++itr;
2438
2439 // Don't do any more work after getting information for 256 ACK blocks; any
2440 // more can't be encoded anyway.
2441 for (; itr != frame.packets.rend() &&
2442 new_ack_info.num_ack_blocks < std::numeric_limits<uint8_t>::max();
2443 previous_start = itr->min(), ++itr) {
2444 const auto& interval = *itr;
2445 const QuicPacketCount total_gap = previous_start - interval.max();
2446 new_ack_info.num_ack_blocks +=
2447 (total_gap + std::numeric_limits<uint8_t>::max() - 1) /
2448 std::numeric_limits<uint8_t>::max();
2449 new_ack_info.max_block_length = std::max(
2450 new_ack_info.max_block_length, PacketNumberIntervalLength(interval));
2451 }
2452 return new_ack_info;
2453}
2454
2455bool QuicFramer::ProcessUnauthenticatedHeader(QuicDataReader* encrypted_reader,
2456 QuicPacketHeader* header) {
QUICHE team10b22a12019-03-21 15:31:42 -07002457 QuicPacketNumber base_packet_number;
2458 if (supports_multiple_packet_number_spaces_) {
nharper55fa6132019-05-07 19:37:21 -07002459 PacketNumberSpace pn_space = GetPacketNumberSpace(*header);
2460 if (pn_space == NUM_PACKET_NUMBER_SPACES) {
2461 set_detailed_error("Unable to determine packet number space.");
2462 return RaiseError(QUIC_INVALID_PACKET_HEADER);
2463 }
2464 base_packet_number = largest_decrypted_packet_numbers_[pn_space];
QUICHE team10b22a12019-03-21 15:31:42 -07002465 } else {
2466 base_packet_number = largest_packet_number_;
2467 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002468 uint64_t full_packet_number;
2469 if (!ProcessAndCalculatePacketNumber(
2470 encrypted_reader, header->packet_number_length, base_packet_number,
2471 &full_packet_number)) {
2472 set_detailed_error("Unable to read packet number.");
2473 return RaiseError(QUIC_INVALID_PACKET_HEADER);
2474 }
2475
2476 if (!IsValidFullPacketNumber(full_packet_number, transport_version())) {
2477 set_detailed_error("packet numbers cannot be 0.");
2478 return RaiseError(QUIC_INVALID_PACKET_HEADER);
2479 }
2480 header->packet_number = QuicPacketNumber(full_packet_number);
2481
2482 if (!visitor_->OnUnauthenticatedHeader(*header)) {
2483 set_detailed_error(
2484 "Visitor asked to stop processing of unauthenticated header.");
2485 return false;
2486 }
nharper3f283562019-05-02 16:37:12 -07002487 // The function we are in is called because the framer believes that it is
2488 // processing a packet that uses the non-IETF (i.e. Google QUIC) packet header
2489 // type. Usually, the framer makes that decision based on the framer's
2490 // version, but when the framer is used with Perspective::IS_SERVER, then
2491 // before version negotiation is complete (specifically, before
2492 // InferPacketHeaderTypeFromVersion is called), this decision is made based on
2493 // the type byte of the packet.
2494 //
2495 // If the framer's version KnowsWhichDecrypterToUse, then that version expects
2496 // to use the IETF packet header type. If that's the case and we're in this
2497 // function, then the packet received is invalid: the framer was expecting an
2498 // IETF packet header and didn't get one.
2499 if (version().KnowsWhichDecrypterToUse()) {
nharpera745e392019-04-19 12:05:15 -07002500 set_detailed_error("Invalid public header type for expected version.");
2501 return RaiseError(QUIC_INVALID_PACKET_HEADER);
2502 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002503 return true;
2504}
2505
2506bool QuicFramer::ProcessIetfHeaderTypeByte(QuicDataReader* reader,
2507 QuicPacketHeader* header) {
2508 uint8_t type;
2509 if (!reader->ReadBytes(&type, 1)) {
2510 set_detailed_error("Unable to read type.");
2511 return false;
2512 }
dschinazi244f6dc2019-05-06 15:45:16 -07002513 header->type_byte = type;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002514 // Determine whether this is a long or short header.
fayangccbab732019-05-13 10:11:25 -07002515 header->form = GetIetfPacketHeaderFormat(type);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002516 if (header->form == IETF_QUIC_LONG_HEADER_PACKET) {
2517 // Version is always present in long headers.
2518 header->version_flag = true;
dschinazi346b7ce2019-06-05 01:38:18 -07002519 // In versions that do not support client connection IDs, we mark the
2520 // corresponding connection ID as absent.
QUICHE teama6ef0a62019-03-07 20:34:33 -05002521 header->destination_connection_id_included =
dschinazi346b7ce2019-06-05 01:38:18 -07002522 (perspective_ == Perspective::IS_SERVER ||
2523 version_.SupportsClientConnectionIds())
2524 ? CONNECTION_ID_PRESENT
2525 : CONNECTION_ID_ABSENT;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002526 header->source_connection_id_included =
dschinazi346b7ce2019-06-05 01:38:18 -07002527 (perspective_ == Perspective::IS_CLIENT ||
2528 version_.SupportsClientConnectionIds())
2529 ? CONNECTION_ID_PRESENT
2530 : CONNECTION_ID_ABSENT;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002531 // Read version tag.
2532 QuicVersionLabel version_label;
fayang40315542019-05-09 09:19:09 -07002533 if (!ProcessVersionLabel(reader, &version_label)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002534 set_detailed_error("Unable to read protocol version.");
2535 return false;
2536 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002537 if (!version_label) {
2538 // Version label is 0 indicating this is a version negotiation packet.
2539 header->long_packet_type = VERSION_NEGOTIATION;
2540 } else {
2541 header->version = ParseQuicVersionLabel(version_label);
2542 if (header->version.transport_version != QUIC_VERSION_UNSUPPORTED) {
fayangf36e29d2019-06-06 14:03:40 -07002543 if (header->version.transport_version > QUIC_VERSION_44 &&
QUICHE teama6ef0a62019-03-07 20:34:33 -05002544 !(type & FLAGS_FIXED_BIT)) {
2545 set_detailed_error("Fixed bit is 0 in long header.");
2546 return false;
2547 }
2548 if (!GetLongHeaderType(header->version.transport_version, type,
2549 &header->long_packet_type)) {
2550 set_detailed_error("Illegal long header type value.");
2551 return false;
2552 }
dschinazi244f6dc2019-05-06 15:45:16 -07002553 if (header->long_packet_type == RETRY) {
2554 if (!version().SupportsRetry()) {
2555 set_detailed_error("RETRY not supported in this version.");
2556 return false;
2557 }
2558 if (perspective_ == Perspective::IS_SERVER) {
2559 set_detailed_error("Client-initiated RETRY is invalid.");
2560 return false;
2561 }
nharper55fa6132019-05-07 19:37:21 -07002562 } else if (!header->version.HasHeaderProtection()) {
dschinazi244f6dc2019-05-06 15:45:16 -07002563 header->packet_number_length = GetLongHeaderPacketNumberLength(
2564 header->version.transport_version, type);
nharper2ceb97c2019-04-19 11:38:59 -07002565 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002566 }
2567 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002568
2569 QUIC_DVLOG(1) << ENDPOINT << "Received IETF long header: "
2570 << QuicUtils::QuicLongHeaderTypetoString(
2571 header->long_packet_type);
2572 return true;
2573 }
2574
2575 QUIC_DVLOG(1) << ENDPOINT << "Received IETF short header";
2576 // Version is not present in short headers.
2577 header->version_flag = false;
dschinazi346b7ce2019-06-05 01:38:18 -07002578 // In versions that do not support client connection IDs, the client will not
2579 // receive destination connection IDs.
QUICHE teama6ef0a62019-03-07 20:34:33 -05002580 header->destination_connection_id_included =
dschinazi346b7ce2019-06-05 01:38:18 -07002581 (perspective_ == Perspective::IS_SERVER ||
2582 version_.SupportsClientConnectionIds())
2583 ? CONNECTION_ID_PRESENT
2584 : CONNECTION_ID_ABSENT;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002585 header->source_connection_id_included = CONNECTION_ID_ABSENT;
fayangf36e29d2019-06-06 14:03:40 -07002586 if (infer_packet_header_type_from_version_ &&
2587 transport_version() > QUIC_VERSION_44 && !(type & FLAGS_FIXED_BIT)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002588 set_detailed_error("Fixed bit is 0 in short header.");
2589 return false;
2590 }
nharper55fa6132019-05-07 19:37:21 -07002591 if (!header->version.HasHeaderProtection() &&
2592 !GetShortHeaderPacketNumberLength(transport_version(), type,
QUICHE teama6ef0a62019-03-07 20:34:33 -05002593 infer_packet_header_type_from_version_,
2594 &header->packet_number_length)) {
2595 set_detailed_error("Illegal short header type value.");
2596 return false;
2597 }
2598 QUIC_DVLOG(1) << "packet_number_length = " << header->packet_number_length;
2599 return true;
2600}
2601
fayang40315542019-05-09 09:19:09 -07002602// static
2603bool QuicFramer::ProcessVersionLabel(QuicDataReader* reader,
2604 QuicVersionLabel* version_label) {
nharpereaab5ad2019-05-31 12:23:25 -07002605 if (!reader->ReadUInt32(version_label)) {
fayang40315542019-05-09 09:19:09 -07002606 return false;
2607 }
fayang40315542019-05-09 09:19:09 -07002608 return true;
2609}
2610
2611// static
fayangccbab732019-05-13 10:11:25 -07002612bool QuicFramer::ProcessAndValidateIetfConnectionIdLength(
2613 QuicDataReader* reader,
fayang40315542019-05-09 09:19:09 -07002614 ParsedQuicVersion version,
dschinazi334f0232019-05-29 16:08:53 -07002615 Perspective perspective,
dschinazi8ff74822019-05-28 16:37:20 -07002616 bool should_update_expected_server_connection_id_length,
2617 uint8_t* expected_server_connection_id_length,
fayang40315542019-05-09 09:19:09 -07002618 uint8_t* destination_connection_id_length,
fayangccbab732019-05-13 10:11:25 -07002619 uint8_t* source_connection_id_length,
2620 std::string* detailed_error) {
2621 uint8_t connection_id_lengths_byte;
2622 if (!reader->ReadBytes(&connection_id_lengths_byte, 1)) {
2623 *detailed_error = "Unable to read ConnectionId length.";
2624 return false;
2625 }
fayang40315542019-05-09 09:19:09 -07002626 uint8_t dcil =
2627 (connection_id_lengths_byte & kDestinationConnectionIdLengthMask) >> 4;
2628 if (dcil != 0) {
2629 dcil += kConnectionIdLengthAdjustment;
2630 }
fayang40315542019-05-09 09:19:09 -07002631 uint8_t scil = connection_id_lengths_byte & kSourceConnectionIdLengthMask;
2632 if (scil != 0) {
2633 scil += kConnectionIdLengthAdjustment;
2634 }
dschinazi334f0232019-05-29 16:08:53 -07002635 if (should_update_expected_server_connection_id_length) {
2636 uint8_t server_connection_id_length =
2637 perspective == Perspective::IS_SERVER ? dcil : scil;
2638 if (*expected_server_connection_id_length != server_connection_id_length) {
2639 QUIC_DVLOG(1) << "Updating expected_server_connection_id_length: "
2640 << static_cast<int>(*expected_server_connection_id_length)
2641 << " -> " << static_cast<int>(server_connection_id_length);
2642 *expected_server_connection_id_length = server_connection_id_length;
2643 }
2644 }
dschinazi8ff74822019-05-28 16:37:20 -07002645 if (!should_update_expected_server_connection_id_length &&
fayangde8a2222019-05-16 10:52:39 -07002646 (dcil != *destination_connection_id_length ||
fayang40315542019-05-09 09:19:09 -07002647 scil != *source_connection_id_length) &&
fayang40315542019-05-09 09:19:09 -07002648 !QuicUtils::VariableLengthConnectionIdAllowedForVersion(
2649 version.transport_version)) {
2650 // TODO(dschinazi): use the framer's version once the
2651 // OnProtocolVersionMismatch call is moved to before this is run.
2652 QUIC_DVLOG(1) << "dcil: " << static_cast<uint32_t>(dcil)
2653 << ", scil: " << static_cast<uint32_t>(scil);
fayangccbab732019-05-13 10:11:25 -07002654 *detailed_error = "Invalid ConnectionId length.";
fayang40315542019-05-09 09:19:09 -07002655 return false;
2656 }
2657 *destination_connection_id_length = dcil;
2658 *source_connection_id_length = scil;
2659 return true;
2660}
2661
QUICHE teama6ef0a62019-03-07 20:34:33 -05002662bool QuicFramer::ProcessIetfPacketHeader(QuicDataReader* reader,
2663 QuicPacketHeader* header) {
2664 if (!ProcessIetfHeaderTypeByte(reader, header)) {
2665 return false;
2666 }
2667
2668 uint8_t destination_connection_id_length =
2669 header->destination_connection_id_included == CONNECTION_ID_PRESENT
dschinazi346b7ce2019-06-05 01:38:18 -07002670 ? (perspective_ == Perspective::IS_SERVER
2671 ? expected_server_connection_id_length_
2672 : expected_client_connection_id_length_)
QUICHE teama6ef0a62019-03-07 20:34:33 -05002673 : 0;
2674 uint8_t source_connection_id_length =
2675 header->source_connection_id_included == CONNECTION_ID_PRESENT
dschinazi346b7ce2019-06-05 01:38:18 -07002676 ? (perspective_ == Perspective::IS_CLIENT
2677 ? expected_server_connection_id_length_
2678 : expected_client_connection_id_length_)
QUICHE teama6ef0a62019-03-07 20:34:33 -05002679 : 0;
2680 if (header->form == IETF_QUIC_LONG_HEADER_PACKET) {
fayangccbab732019-05-13 10:11:25 -07002681 if (!ProcessAndValidateIetfConnectionIdLength(
dschinazi334f0232019-05-29 16:08:53 -07002682 reader, header->version, perspective_,
fayang91475c42019-06-19 08:04:26 -07002683 /*should_update_expected_server_connection_id_length=*/false,
dschinazi8ff74822019-05-28 16:37:20 -07002684 &expected_server_connection_id_length_,
2685 &destination_connection_id_length, &source_connection_id_length,
2686 &detailed_error_)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002687 return false;
2688 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002689 }
2690
QUICHE team0131a5b2019-03-20 15:23:27 -07002691 DCHECK_LE(destination_connection_id_length, kQuicMaxConnectionIdLength);
2692 DCHECK_LE(source_connection_id_length, kQuicMaxConnectionIdLength);
2693
QUICHE teama6ef0a62019-03-07 20:34:33 -05002694 // Read connection ID.
2695 if (!reader->ReadConnectionId(&header->destination_connection_id,
2696 destination_connection_id_length)) {
2697 set_detailed_error("Unable to read Destination ConnectionId.");
2698 return false;
2699 }
2700
2701 if (!reader->ReadConnectionId(&header->source_connection_id,
2702 source_connection_id_length)) {
2703 set_detailed_error("Unable to read Source ConnectionId.");
2704 return false;
2705 }
2706
QUICHE team2252b702019-05-14 23:55:14 -04002707 if (!GetQuicRestartFlag(quic_do_not_override_connection_id)) {
2708 if (header->source_connection_id_included == CONNECTION_ID_PRESENT) {
dschinazi7d066ca2019-05-15 17:59:49 -07002709 DCHECK_EQ(Perspective::IS_CLIENT, perspective_);
2710 DCHECK_EQ(IETF_QUIC_LONG_HEADER_PACKET, header->form);
2711 if (!header->destination_connection_id.IsEmpty()) {
2712 set_detailed_error("Client connection ID not supported yet.");
2713 return false;
2714 }
QUICHE team2252b702019-05-14 23:55:14 -04002715 // Set destination connection ID to source connection ID.
QUICHE team2252b702019-05-14 23:55:14 -04002716 header->destination_connection_id = header->source_connection_id;
2717 } else if (header->destination_connection_id_included ==
2718 CONNECTION_ID_ABSENT) {
dschinazi7b9278c2019-05-20 07:36:21 -07002719 header->destination_connection_id = last_serialized_server_connection_id_;
QUICHE team2252b702019-05-14 23:55:14 -04002720 }
2721 } else {
dschinazib9bdd052019-06-05 03:06:33 -07002722 QUIC_RESTART_FLAG_COUNT_N(quic_do_not_override_connection_id, 5, 7);
QUICHE team2252b702019-05-14 23:55:14 -04002723 if (header->source_connection_id_included == CONNECTION_ID_ABSENT) {
dschinazi346b7ce2019-06-05 01:38:18 -07002724 if (!header->source_connection_id.IsEmpty()) {
2725 DCHECK(!version_.SupportsClientConnectionIds());
2726 set_detailed_error(
2727 "Client connection ID not supported in this version.");
2728 return false;
2729 }
2730 if (perspective_ == Perspective::IS_CLIENT) {
2731 header->source_connection_id = last_serialized_server_connection_id_;
2732 } else {
2733 header->source_connection_id = last_serialized_client_connection_id_;
2734 }
QUICHE team2252b702019-05-14 23:55:14 -04002735 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002736 }
2737
2738 return true;
2739}
2740
2741bool QuicFramer::ProcessAndCalculatePacketNumber(
2742 QuicDataReader* reader,
2743 QuicPacketNumberLength packet_number_length,
2744 QuicPacketNumber base_packet_number,
2745 uint64_t* packet_number) {
2746 uint64_t wire_packet_number;
2747 if (!reader->ReadBytesToUInt64(packet_number_length, &wire_packet_number)) {
2748 return false;
2749 }
2750
2751 // TODO(ianswett): Explore the usefulness of trying multiple packet numbers
2752 // in case the first guess is incorrect.
2753 *packet_number = CalculatePacketNumberFromWire(
2754 packet_number_length, base_packet_number, wire_packet_number);
2755 return true;
2756}
2757
2758bool QuicFramer::ProcessFrameData(QuicDataReader* reader,
2759 const QuicPacketHeader& header) {
fkastenholz305e1732019-06-18 05:01:22 -07002760 DCHECK(!VersionHasIetfQuicFrames(version_.transport_version))
2761 << "IETF QUIC Framing negotiated but attempting to process frames as "
2762 "non-IETF QUIC.";
QUICHE teama6ef0a62019-03-07 20:34:33 -05002763 if (reader->IsDoneReading()) {
2764 set_detailed_error("Packet has no frames.");
2765 return RaiseError(QUIC_MISSING_PAYLOAD);
2766 }
dschinazi118934b2019-06-13 18:09:08 -07002767 QUIC_DVLOG(2) << ENDPOINT << "Processing packet with header " << header;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002768 while (!reader->IsDoneReading()) {
2769 uint8_t frame_type;
2770 if (!reader->ReadBytes(&frame_type, 1)) {
2771 set_detailed_error("Unable to read frame type.");
2772 return RaiseError(QUIC_INVALID_FRAME_DATA);
2773 }
fayangf36e29d2019-06-06 14:03:40 -07002774 const uint8_t special_mask = transport_version() <= QUIC_VERSION_44
QUICHE teama6ef0a62019-03-07 20:34:33 -05002775 ? kQuicFrameTypeBrokenMask
2776 : kQuicFrameTypeSpecialMask;
2777 if (frame_type & special_mask) {
2778 // Stream Frame
2779 if (frame_type & kQuicFrameTypeStreamMask) {
2780 QuicStreamFrame frame;
2781 if (!ProcessStreamFrame(reader, frame_type, &frame)) {
2782 return RaiseError(QUIC_INVALID_STREAM_DATA);
2783 }
dschinazi118934b2019-06-13 18:09:08 -07002784 QUIC_DVLOG(2) << ENDPOINT << "Processing stream frame " << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002785 if (!visitor_->OnStreamFrame(frame)) {
2786 QUIC_DVLOG(1) << ENDPOINT
2787 << "Visitor asked to stop further processing.";
2788 // Returning true since there was no parsing error.
2789 return true;
2790 }
2791 continue;
2792 }
2793
2794 // Ack Frame
2795 if (frame_type & kQuicFrameTypeAckMask) {
2796 if (!ProcessAckFrame(reader, frame_type)) {
2797 return RaiseError(QUIC_INVALID_ACK_DATA);
2798 }
dschinazi118934b2019-06-13 18:09:08 -07002799 QUIC_DVLOG(2) << ENDPOINT << "Processing ACK frame";
QUICHE teama6ef0a62019-03-07 20:34:33 -05002800 continue;
2801 }
2802
2803 // This was a special frame type that did not match any
2804 // of the known ones. Error.
2805 set_detailed_error("Illegal frame type.");
2806 QUIC_DLOG(WARNING) << ENDPOINT << "Illegal frame type: "
2807 << static_cast<int>(frame_type);
2808 return RaiseError(QUIC_INVALID_FRAME_DATA);
2809 }
2810
2811 switch (frame_type) {
2812 case PADDING_FRAME: {
2813 QuicPaddingFrame frame;
2814 ProcessPaddingFrame(reader, &frame);
dschinazi118934b2019-06-13 18:09:08 -07002815 QUIC_DVLOG(2) << ENDPOINT << "Processing padding frame " << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002816 if (!visitor_->OnPaddingFrame(frame)) {
2817 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
2818 // Returning true since there was no parsing error.
2819 return true;
2820 }
2821 continue;
2822 }
2823
2824 case RST_STREAM_FRAME: {
2825 QuicRstStreamFrame frame;
2826 if (!ProcessRstStreamFrame(reader, &frame)) {
2827 return RaiseError(QUIC_INVALID_RST_STREAM_DATA);
2828 }
dschinazi118934b2019-06-13 18:09:08 -07002829 QUIC_DVLOG(2) << ENDPOINT << "Processing reset stream frame " << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002830 if (!visitor_->OnRstStreamFrame(frame)) {
2831 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
2832 // Returning true since there was no parsing error.
2833 return true;
2834 }
2835 continue;
2836 }
2837
2838 case CONNECTION_CLOSE_FRAME: {
2839 QuicConnectionCloseFrame frame;
2840 if (!ProcessConnectionCloseFrame(reader, &frame)) {
2841 return RaiseError(QUIC_INVALID_CONNECTION_CLOSE_DATA);
2842 }
2843
dschinazi118934b2019-06-13 18:09:08 -07002844 QUIC_DVLOG(2) << ENDPOINT << "Processing connection close frame "
2845 << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002846 if (!visitor_->OnConnectionCloseFrame(frame)) {
2847 QUIC_DVLOG(1) << ENDPOINT
2848 << "Visitor asked to stop further processing.";
2849 // Returning true since there was no parsing error.
2850 return true;
2851 }
2852 continue;
2853 }
2854
2855 case GOAWAY_FRAME: {
2856 QuicGoAwayFrame goaway_frame;
2857 if (!ProcessGoAwayFrame(reader, &goaway_frame)) {
2858 return RaiseError(QUIC_INVALID_GOAWAY_DATA);
2859 }
dschinazi118934b2019-06-13 18:09:08 -07002860 QUIC_DVLOG(2) << ENDPOINT << "Processing go away frame "
2861 << goaway_frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002862 if (!visitor_->OnGoAwayFrame(goaway_frame)) {
2863 QUIC_DVLOG(1) << ENDPOINT
2864 << "Visitor asked to stop further processing.";
2865 // Returning true since there was no parsing error.
2866 return true;
2867 }
2868 continue;
2869 }
2870
2871 case WINDOW_UPDATE_FRAME: {
2872 QuicWindowUpdateFrame window_update_frame;
2873 if (!ProcessWindowUpdateFrame(reader, &window_update_frame)) {
2874 return RaiseError(QUIC_INVALID_WINDOW_UPDATE_DATA);
2875 }
dschinazi118934b2019-06-13 18:09:08 -07002876 QUIC_DVLOG(2) << ENDPOINT << "Processing window update frame "
2877 << window_update_frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002878 if (!visitor_->OnWindowUpdateFrame(window_update_frame)) {
2879 QUIC_DVLOG(1) << ENDPOINT
2880 << "Visitor asked to stop further processing.";
2881 // Returning true since there was no parsing error.
2882 return true;
2883 }
2884 continue;
2885 }
2886
2887 case BLOCKED_FRAME: {
2888 QuicBlockedFrame blocked_frame;
2889 if (!ProcessBlockedFrame(reader, &blocked_frame)) {
2890 return RaiseError(QUIC_INVALID_BLOCKED_DATA);
2891 }
dschinazi118934b2019-06-13 18:09:08 -07002892 QUIC_DVLOG(2) << ENDPOINT << "Processing blocked frame "
2893 << blocked_frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002894 if (!visitor_->OnBlockedFrame(blocked_frame)) {
2895 QUIC_DVLOG(1) << ENDPOINT
2896 << "Visitor asked to stop further processing.";
2897 // Returning true since there was no parsing error.
2898 return true;
2899 }
2900 continue;
2901 }
2902
2903 case STOP_WAITING_FRAME: {
ianswett97b690b2019-05-02 15:12:43 -07002904 if (GetQuicReloadableFlag(quic_do_not_accept_stop_waiting) &&
fayangf36e29d2019-06-06 14:03:40 -07002905 version_.transport_version >= QUIC_VERSION_44) {
ianswett97b690b2019-05-02 15:12:43 -07002906 QUIC_RELOADABLE_FLAG_COUNT(quic_do_not_accept_stop_waiting);
2907 set_detailed_error("STOP WAITING not supported in version 44+.");
2908 return RaiseError(QUIC_INVALID_STOP_WAITING_DATA);
2909 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002910 QuicStopWaitingFrame stop_waiting_frame;
2911 if (!ProcessStopWaitingFrame(reader, header, &stop_waiting_frame)) {
2912 return RaiseError(QUIC_INVALID_STOP_WAITING_DATA);
2913 }
dschinazi118934b2019-06-13 18:09:08 -07002914 QUIC_DVLOG(2) << ENDPOINT << "Processing stop waiting frame "
2915 << stop_waiting_frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002916 if (!visitor_->OnStopWaitingFrame(stop_waiting_frame)) {
2917 QUIC_DVLOG(1) << ENDPOINT
2918 << "Visitor asked to stop further processing.";
2919 // Returning true since there was no parsing error.
2920 return true;
2921 }
2922 continue;
2923 }
2924 case PING_FRAME: {
2925 // Ping has no payload.
2926 QuicPingFrame ping_frame;
2927 if (!visitor_->OnPingFrame(ping_frame)) {
2928 QUIC_DVLOG(1) << ENDPOINT
2929 << "Visitor asked to stop further processing.";
2930 // Returning true since there was no parsing error.
2931 return true;
2932 }
dschinazi118934b2019-06-13 18:09:08 -07002933 QUIC_DVLOG(2) << ENDPOINT << "Processing ping frame " << ping_frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002934 continue;
2935 }
2936 case IETF_EXTENSION_MESSAGE_NO_LENGTH:
2937 QUIC_FALLTHROUGH_INTENDED;
2938 case IETF_EXTENSION_MESSAGE: {
2939 QuicMessageFrame message_frame;
2940 if (!ProcessMessageFrame(reader,
2941 frame_type == IETF_EXTENSION_MESSAGE_NO_LENGTH,
2942 &message_frame)) {
2943 return RaiseError(QUIC_INVALID_MESSAGE_DATA);
2944 }
dschinazi118934b2019-06-13 18:09:08 -07002945 QUIC_DVLOG(2) << ENDPOINT << "Processing message frame "
2946 << message_frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002947 if (!visitor_->OnMessageFrame(message_frame)) {
2948 QUIC_DVLOG(1) << ENDPOINT
2949 << "Visitor asked to stop further processing.";
2950 // Returning true since there was no parsing error.
2951 return true;
2952 }
2953 break;
2954 }
2955 case CRYPTO_FRAME: {
QUICHE teamea740082019-03-11 17:58:43 -07002956 if (!QuicVersionUsesCryptoFrames(version_.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002957 set_detailed_error("Illegal frame type.");
2958 return RaiseError(QUIC_INVALID_FRAME_DATA);
2959 }
2960 QuicCryptoFrame frame;
2961 if (!ProcessCryptoFrame(reader, &frame)) {
2962 return RaiseError(QUIC_INVALID_FRAME_DATA);
2963 }
dschinazi118934b2019-06-13 18:09:08 -07002964 QUIC_DVLOG(2) << ENDPOINT << "Processing crypto frame " << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002965 if (!visitor_->OnCryptoFrame(frame)) {
2966 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
2967 // Returning true since there was no parsing error.
2968 return true;
2969 }
2970 break;
2971 }
2972
2973 default:
2974 set_detailed_error("Illegal frame type.");
2975 QUIC_DLOG(WARNING) << ENDPOINT << "Illegal frame type: "
2976 << static_cast<int>(frame_type);
2977 return RaiseError(QUIC_INVALID_FRAME_DATA);
2978 }
2979 }
2980
2981 return true;
2982}
2983
2984bool QuicFramer::ProcessIetfFrameData(QuicDataReader* reader,
2985 const QuicPacketHeader& header) {
fkastenholz305e1732019-06-18 05:01:22 -07002986 DCHECK(VersionHasIetfQuicFrames(version_.transport_version))
2987 << "Attempt to process frames as IETF frames but version ("
2988 << version_.transport_version << ") does not support IETF Framing.";
2989
QUICHE teama6ef0a62019-03-07 20:34:33 -05002990 if (reader->IsDoneReading()) {
2991 set_detailed_error("Packet has no frames.");
2992 return RaiseError(QUIC_MISSING_PAYLOAD);
2993 }
dschinazi118934b2019-06-13 18:09:08 -07002994
2995 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF packet with header " << header;
QUICHE teama6ef0a62019-03-07 20:34:33 -05002996 while (!reader->IsDoneReading()) {
2997 uint64_t frame_type;
2998 // Will be the number of bytes into which frame_type was encoded.
2999 size_t encoded_bytes = reader->BytesRemaining();
3000 if (!reader->ReadVarInt62(&frame_type)) {
3001 set_detailed_error("Unable to read frame type.");
3002 return RaiseError(QUIC_INVALID_FRAME_DATA);
3003 }
3004
3005 // Is now the number of bytes into which the frame type was encoded.
3006 encoded_bytes -= reader->BytesRemaining();
3007
3008 // Check that the frame type is minimally encoded.
3009 if (encoded_bytes !=
3010 static_cast<size_t>(QuicDataWriter::GetVarInt62Len(frame_type))) {
3011 // The frame type was not minimally encoded.
3012 set_detailed_error("Frame type not minimally encoded.");
3013 return RaiseError(IETF_QUIC_PROTOCOL_VIOLATION);
3014 }
3015
3016 if (IS_IETF_STREAM_FRAME(frame_type)) {
3017 QuicStreamFrame frame;
3018 if (!ProcessIetfStreamFrame(reader, frame_type, &frame)) {
3019 return RaiseError(QUIC_INVALID_STREAM_DATA);
3020 }
dschinazi118934b2019-06-13 18:09:08 -07003021 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF stream frame " << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003022 if (!visitor_->OnStreamFrame(frame)) {
3023 QUIC_DVLOG(1) << ENDPOINT
3024 << "Visitor asked to stop further processing.";
3025 // Returning true since there was no parsing error.
3026 return true;
3027 }
3028 } else {
3029 switch (frame_type) {
3030 case IETF_PADDING: {
3031 QuicPaddingFrame frame;
3032 ProcessPaddingFrame(reader, &frame);
dschinazi118934b2019-06-13 18:09:08 -07003033 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF padding frame "
3034 << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003035 if (!visitor_->OnPaddingFrame(frame)) {
3036 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3037 // Returning true since there was no parsing error.
3038 return true;
3039 }
3040 break;
3041 }
3042 case IETF_RST_STREAM: {
3043 QuicRstStreamFrame frame;
3044 if (!ProcessIetfResetStreamFrame(reader, &frame)) {
3045 return RaiseError(QUIC_INVALID_RST_STREAM_DATA);
3046 }
dschinazi118934b2019-06-13 18:09:08 -07003047 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF reset stream frame "
3048 << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003049 if (!visitor_->OnRstStreamFrame(frame)) {
3050 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3051 // Returning true since there was no parsing error.
3052 return true;
3053 }
3054 break;
3055 }
fkastenholz04bd4f32019-04-16 12:24:38 -07003056 case IETF_APPLICATION_CLOSE:
QUICHE teama6ef0a62019-03-07 20:34:33 -05003057 case IETF_CONNECTION_CLOSE: {
3058 QuicConnectionCloseFrame frame;
fkastenholze9d71a82019-04-09 05:12:13 -07003059 if (!ProcessIetfConnectionCloseFrame(
fkastenholz04bd4f32019-04-16 12:24:38 -07003060 reader,
3061 (frame_type == IETF_CONNECTION_CLOSE)
3062 ? IETF_QUIC_TRANSPORT_CONNECTION_CLOSE
3063 : IETF_QUIC_APPLICATION_CONNECTION_CLOSE,
3064 &frame)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05003065 return RaiseError(QUIC_INVALID_CONNECTION_CLOSE_DATA);
3066 }
dschinazi118934b2019-06-13 18:09:08 -07003067 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF connection close frame "
3068 << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003069 if (!visitor_->OnConnectionCloseFrame(frame)) {
3070 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3071 // Returning true since there was no parsing error.
3072 return true;
3073 }
3074 break;
3075 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05003076 case IETF_MAX_DATA: {
3077 QuicWindowUpdateFrame frame;
3078 if (!ProcessMaxDataFrame(reader, &frame)) {
3079 return RaiseError(QUIC_INVALID_MAX_DATA_FRAME_DATA);
3080 }
3081 // TODO(fkastenholz): Or should we create a new visitor function,
3082 // OnMaxDataFrame()?
dschinazi118934b2019-06-13 18:09:08 -07003083 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF max data frame "
3084 << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003085 if (!visitor_->OnWindowUpdateFrame(frame)) {
3086 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3087 // Returning true since there was no parsing error.
3088 return true;
3089 }
3090 break;
3091 }
3092 case IETF_MAX_STREAM_DATA: {
3093 QuicWindowUpdateFrame frame;
3094 if (!ProcessMaxStreamDataFrame(reader, &frame)) {
3095 return RaiseError(QUIC_INVALID_MAX_STREAM_DATA_FRAME_DATA);
3096 }
3097 // TODO(fkastenholz): Or should we create a new visitor function,
3098 // OnMaxStreamDataFrame()?
dschinazi118934b2019-06-13 18:09:08 -07003099 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF max stream data frame "
3100 << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003101 if (!visitor_->OnWindowUpdateFrame(frame)) {
3102 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3103 // Returning true since there was no parsing error.
3104 return true;
3105 }
3106 break;
3107 }
3108 case IETF_MAX_STREAMS_BIDIRECTIONAL:
3109 case IETF_MAX_STREAMS_UNIDIRECTIONAL: {
fkastenholz3c4eabf2019-04-22 07:49:59 -07003110 QuicMaxStreamsFrame frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003111 if (!ProcessMaxStreamsFrame(reader, &frame, frame_type)) {
fkastenholz3c4eabf2019-04-22 07:49:59 -07003112 return RaiseError(QUIC_MAX_STREAMS_DATA);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003113 }
fkastenholz3c4eabf2019-04-22 07:49:59 -07003114 QUIC_CODE_COUNT_N(quic_max_streams_received, 1, 2);
dschinazi118934b2019-06-13 18:09:08 -07003115 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF max streams frame "
3116 << frame;
fkastenholz3c4eabf2019-04-22 07:49:59 -07003117 if (!visitor_->OnMaxStreamsFrame(frame)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05003118 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3119 // Returning true since there was no parsing error.
3120 return true;
3121 }
3122 break;
3123 }
3124 case IETF_PING: {
3125 // Ping has no payload.
3126 QuicPingFrame ping_frame;
dschinazi118934b2019-06-13 18:09:08 -07003127 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF ping frame "
3128 << ping_frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003129 if (!visitor_->OnPingFrame(ping_frame)) {
3130 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3131 // Returning true since there was no parsing error.
3132 return true;
3133 }
3134 break;
3135 }
3136 case IETF_BLOCKED: {
3137 QuicBlockedFrame frame;
3138 if (!ProcessIetfBlockedFrame(reader, &frame)) {
3139 return RaiseError(QUIC_INVALID_BLOCKED_DATA);
3140 }
dschinazi118934b2019-06-13 18:09:08 -07003141 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF blocked frame "
3142 << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003143 if (!visitor_->OnBlockedFrame(frame)) {
3144 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3145 // Returning true since there was no parsing error.
3146 return true;
3147 }
3148 break;
3149 }
3150 case IETF_STREAM_BLOCKED: {
3151 QuicBlockedFrame frame;
3152 if (!ProcessStreamBlockedFrame(reader, &frame)) {
3153 return RaiseError(QUIC_INVALID_STREAM_BLOCKED_DATA);
3154 }
dschinazi118934b2019-06-13 18:09:08 -07003155 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF stream blocked frame "
3156 << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003157 if (!visitor_->OnBlockedFrame(frame)) {
3158 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3159 // Returning true since there was no parsing error.
3160 return true;
3161 }
3162 break;
3163 }
3164 case IETF_STREAMS_BLOCKED_UNIDIRECTIONAL:
3165 case IETF_STREAMS_BLOCKED_BIDIRECTIONAL: {
fkastenholz3c4eabf2019-04-22 07:49:59 -07003166 QuicStreamsBlockedFrame frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003167 if (!ProcessStreamsBlockedFrame(reader, &frame, frame_type)) {
fkastenholz3c4eabf2019-04-22 07:49:59 -07003168 return RaiseError(QUIC_STREAMS_BLOCKED_DATA);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003169 }
fkastenholz3c4eabf2019-04-22 07:49:59 -07003170 QUIC_CODE_COUNT_N(quic_streams_blocked_received, 1, 2);
dschinazi118934b2019-06-13 18:09:08 -07003171 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF streams blocked frame "
3172 << frame;
fkastenholz3c4eabf2019-04-22 07:49:59 -07003173 if (!visitor_->OnStreamsBlockedFrame(frame)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05003174 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3175 // Returning true since there was no parsing error.
3176 return true;
3177 }
3178 break;
3179 }
3180 case IETF_NEW_CONNECTION_ID: {
3181 QuicNewConnectionIdFrame frame;
3182 if (!ProcessNewConnectionIdFrame(reader, &frame)) {
3183 return RaiseError(QUIC_INVALID_NEW_CONNECTION_ID_DATA);
3184 }
dschinazi118934b2019-06-13 18:09:08 -07003185 QUIC_DVLOG(2) << ENDPOINT
3186 << "Processing IETF new connection ID frame " << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003187 if (!visitor_->OnNewConnectionIdFrame(frame)) {
3188 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3189 // Returning true since there was no parsing error.
3190 return true;
3191 }
3192 break;
3193 }
3194 case IETF_RETIRE_CONNECTION_ID: {
3195 QuicRetireConnectionIdFrame frame;
3196 if (!ProcessRetireConnectionIdFrame(reader, &frame)) {
3197 return RaiseError(QUIC_INVALID_RETIRE_CONNECTION_ID_DATA);
3198 }
dschinazi118934b2019-06-13 18:09:08 -07003199 QUIC_DVLOG(2) << ENDPOINT
3200 << "Processing IETF retire connection ID frame "
3201 << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003202 if (!visitor_->OnRetireConnectionIdFrame(frame)) {
3203 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3204 // Returning true since there was no parsing error.
3205 return true;
3206 }
3207 break;
3208 }
3209 case IETF_NEW_TOKEN: {
3210 QuicNewTokenFrame frame;
3211 if (!ProcessNewTokenFrame(reader, &frame)) {
3212 return RaiseError(QUIC_INVALID_NEW_TOKEN);
3213 }
dschinazi118934b2019-06-13 18:09:08 -07003214 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF new token frame "
3215 << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003216 if (!visitor_->OnNewTokenFrame(frame)) {
3217 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3218 // Returning true since there was no parsing error.
3219 return true;
3220 }
3221 break;
3222 }
3223 case IETF_STOP_SENDING: {
3224 QuicStopSendingFrame frame;
3225 if (!ProcessStopSendingFrame(reader, &frame)) {
3226 return RaiseError(QUIC_INVALID_STOP_SENDING_FRAME_DATA);
3227 }
dschinazi118934b2019-06-13 18:09:08 -07003228 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF stop sending frame "
3229 << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003230 if (!visitor_->OnStopSendingFrame(frame)) {
3231 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3232 // Returning true since there was no parsing error.
3233 return true;
3234 }
3235 break;
3236 }
3237 case IETF_ACK_ECN:
3238 case IETF_ACK: {
3239 QuicAckFrame frame;
3240 if (!ProcessIetfAckFrame(reader, frame_type, &frame)) {
3241 return RaiseError(QUIC_INVALID_ACK_DATA);
3242 }
dschinazi118934b2019-06-13 18:09:08 -07003243 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF ACK frame " << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003244 break;
3245 }
3246 case IETF_PATH_CHALLENGE: {
3247 QuicPathChallengeFrame frame;
3248 if (!ProcessPathChallengeFrame(reader, &frame)) {
3249 return RaiseError(QUIC_INVALID_PATH_CHALLENGE_DATA);
3250 }
dschinazi118934b2019-06-13 18:09:08 -07003251 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF path challenge frame "
3252 << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003253 if (!visitor_->OnPathChallengeFrame(frame)) {
3254 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3255 // Returning true since there was no parsing error.
3256 return true;
3257 }
3258 break;
3259 }
3260 case IETF_PATH_RESPONSE: {
3261 QuicPathResponseFrame frame;
3262 if (!ProcessPathResponseFrame(reader, &frame)) {
3263 return RaiseError(QUIC_INVALID_PATH_RESPONSE_DATA);
3264 }
dschinazi118934b2019-06-13 18:09:08 -07003265 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF path response frame "
3266 << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003267 if (!visitor_->OnPathResponseFrame(frame)) {
3268 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3269 // Returning true since there was no parsing error.
3270 return true;
3271 }
3272 break;
3273 }
3274 case IETF_EXTENSION_MESSAGE_NO_LENGTH:
3275 QUIC_FALLTHROUGH_INTENDED;
3276 case IETF_EXTENSION_MESSAGE: {
3277 QuicMessageFrame message_frame;
3278 if (!ProcessMessageFrame(
3279 reader, frame_type == IETF_EXTENSION_MESSAGE_NO_LENGTH,
3280 &message_frame)) {
3281 return RaiseError(QUIC_INVALID_MESSAGE_DATA);
3282 }
dschinazi118934b2019-06-13 18:09:08 -07003283 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF message frame "
3284 << message_frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003285 if (!visitor_->OnMessageFrame(message_frame)) {
3286 QUIC_DVLOG(1) << ENDPOINT
3287 << "Visitor asked to stop further processing.";
3288 // Returning true since there was no parsing error.
3289 return true;
3290 }
3291 break;
3292 }
3293 case IETF_CRYPTO: {
3294 QuicCryptoFrame frame;
3295 if (!ProcessCryptoFrame(reader, &frame)) {
3296 return RaiseError(QUIC_INVALID_FRAME_DATA);
3297 }
dschinazi118934b2019-06-13 18:09:08 -07003298 QUIC_DVLOG(2) << ENDPOINT << "Processing IETF crypto frame " << frame;
QUICHE teama6ef0a62019-03-07 20:34:33 -05003299 if (!visitor_->OnCryptoFrame(frame)) {
3300 QUIC_DVLOG(1) << "Visitor asked to stop further processing.";
3301 // Returning true since there was no parsing error.
3302 return true;
3303 }
3304 break;
3305 }
3306
3307 default:
3308 set_detailed_error("Illegal frame type.");
3309 QUIC_DLOG(WARNING)
3310 << ENDPOINT
3311 << "Illegal frame type: " << static_cast<int>(frame_type);
3312 return RaiseError(QUIC_INVALID_FRAME_DATA);
3313 }
3314 }
3315 }
3316 return true;
3317}
3318
3319namespace {
3320// Create a mask that sets the last |num_bits| to 1 and the rest to 0.
3321inline uint8_t GetMaskFromNumBits(uint8_t num_bits) {
3322 return (1u << num_bits) - 1;
3323}
3324
3325// Extract |num_bits| from |flags| offset by |offset|.
3326uint8_t ExtractBits(uint8_t flags, uint8_t num_bits, uint8_t offset) {
3327 return (flags >> offset) & GetMaskFromNumBits(num_bits);
3328}
3329
3330// Extract the bit at position |offset| from |flags| as a bool.
3331bool ExtractBit(uint8_t flags, uint8_t offset) {
3332 return ((flags >> offset) & GetMaskFromNumBits(1)) != 0;
3333}
3334
3335// Set |num_bits|, offset by |offset| to |val| in |flags|.
3336void SetBits(uint8_t* flags, uint8_t val, uint8_t num_bits, uint8_t offset) {
3337 DCHECK_LE(val, GetMaskFromNumBits(num_bits));
3338 *flags |= val << offset;
3339}
3340
3341// Set the bit at position |offset| to |val| in |flags|.
3342void SetBit(uint8_t* flags, bool val, uint8_t offset) {
3343 SetBits(flags, val ? 1 : 0, 1, offset);
3344}
3345} // namespace
3346
3347bool QuicFramer::ProcessStreamFrame(QuicDataReader* reader,
3348 uint8_t frame_type,
3349 QuicStreamFrame* frame) {
3350 uint8_t stream_flags = frame_type;
3351
3352 uint8_t stream_id_length = 0;
3353 uint8_t offset_length = 4;
3354 bool has_data_length = true;
3355 stream_flags &= ~kQuicFrameTypeStreamMask;
3356
3357 // Read from right to left: StreamID, Offset, Data Length, Fin.
3358 stream_id_length = (stream_flags & kQuicStreamIDLengthMask) + 1;
3359 stream_flags >>= kQuicStreamIdShift;
3360
3361 offset_length = (stream_flags & kQuicStreamOffsetMask);
3362 // There is no encoding for 1 byte, only 0 and 2 through 8.
3363 if (offset_length > 0) {
3364 offset_length += 1;
3365 }
3366 stream_flags >>= kQuicStreamShift;
3367
3368 has_data_length =
3369 (stream_flags & kQuicStreamDataLengthMask) == kQuicStreamDataLengthMask;
3370 stream_flags >>= kQuicStreamDataLengthShift;
3371
3372 frame->fin = (stream_flags & kQuicStreamFinMask) == kQuicStreamFinShift;
3373
3374 uint64_t stream_id;
3375 if (!reader->ReadBytesToUInt64(stream_id_length, &stream_id)) {
3376 set_detailed_error("Unable to read stream_id.");
3377 return false;
3378 }
3379 frame->stream_id = static_cast<QuicStreamId>(stream_id);
3380
3381 if (!reader->ReadBytesToUInt64(offset_length, &frame->offset)) {
3382 set_detailed_error("Unable to read offset.");
3383 return false;
3384 }
3385
3386 // TODO(ianswett): Don't use QuicStringPiece as an intermediary.
3387 QuicStringPiece data;
3388 if (has_data_length) {
3389 if (!reader->ReadStringPiece16(&data)) {
3390 set_detailed_error("Unable to read frame data.");
3391 return false;
3392 }
3393 } else {
3394 if (!reader->ReadStringPiece(&data, reader->BytesRemaining())) {
3395 set_detailed_error("Unable to read frame data.");
3396 return false;
3397 }
3398 }
3399 frame->data_buffer = data.data();
3400 frame->data_length = static_cast<uint16_t>(data.length());
3401
3402 return true;
3403}
3404
3405bool QuicFramer::ProcessIetfStreamFrame(QuicDataReader* reader,
3406 uint8_t frame_type,
3407 QuicStreamFrame* frame) {
3408 // Read stream id from the frame. It's always present.
fkastenholz3c4eabf2019-04-22 07:49:59 -07003409 if (!reader->ReadVarIntU32(&frame->stream_id)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05003410 set_detailed_error("Unable to read stream_id.");
3411 return false;
3412 }
3413
3414 // If we have a data offset, read it. If not, set to 0.
3415 if (frame_type & IETF_STREAM_FRAME_OFF_BIT) {
3416 if (!reader->ReadVarInt62(&frame->offset)) {
3417 set_detailed_error("Unable to read stream data offset.");
3418 return false;
3419 }
3420 } else {
3421 // no offset in the frame, ensure it's 0 in the Frame.
3422 frame->offset = 0;
3423 }
3424
3425 // If we have a data length, read it. If not, set to 0.
3426 if (frame_type & IETF_STREAM_FRAME_LEN_BIT) {
3427 QuicIetfStreamDataLength length;
3428 if (!reader->ReadVarInt62(&length)) {
3429 set_detailed_error("Unable to read stream data length.");
3430 return false;
3431 }
3432 if (length > 0xffff) {
3433 set_detailed_error("Stream data length is too large.");
3434 return false;
3435 }
3436 frame->data_length = length;
3437 } else {
3438 // no length in the frame, it is the number of bytes remaining in the
3439 // packet.
3440 frame->data_length = reader->BytesRemaining();
3441 }
3442
3443 if (frame_type & IETF_STREAM_FRAME_FIN_BIT) {
3444 frame->fin = true;
3445 } else {
3446 frame->fin = false;
3447 }
3448
3449 // TODO(ianswett): Don't use QuicStringPiece as an intermediary.
3450 QuicStringPiece data;
3451 if (!reader->ReadStringPiece(&data, frame->data_length)) {
3452 set_detailed_error("Unable to read frame data.");
3453 return false;
3454 }
3455 frame->data_buffer = data.data();
3456 frame->data_length = static_cast<QuicIetfStreamDataLength>(data.length());
3457
3458 return true;
3459}
3460
3461bool QuicFramer::ProcessCryptoFrame(QuicDataReader* reader,
3462 QuicCryptoFrame* frame) {
3463 if (!reader->ReadVarInt62(&frame->offset)) {
3464 set_detailed_error("Unable to read crypto data offset.");
3465 return false;
3466 }
3467 uint64_t len;
3468 if (!reader->ReadVarInt62(&len) ||
3469 len > std::numeric_limits<QuicPacketLength>::max()) {
3470 set_detailed_error("Invalid data length.");
3471 return false;
3472 }
3473 frame->data_length = len;
3474
3475 // TODO(ianswett): Don't use QuicStringPiece as an intermediary.
3476 QuicStringPiece data;
3477 if (!reader->ReadStringPiece(&data, frame->data_length)) {
3478 set_detailed_error("Unable to read frame data.");
3479 return false;
3480 }
3481 frame->data_buffer = data.data();
3482 return true;
3483}
3484
3485bool QuicFramer::ProcessAckFrame(QuicDataReader* reader, uint8_t frame_type) {
3486 const bool has_ack_blocks =
3487 ExtractBit(frame_type, kQuicHasMultipleAckBlocksOffset);
3488 uint8_t num_ack_blocks = 0;
3489 uint8_t num_received_packets = 0;
3490
3491 // Determine the two lengths from the frame type: largest acked length,
3492 // ack block length.
3493 const QuicPacketNumberLength ack_block_length = ReadAckPacketNumberLength(
3494 version_.transport_version,
3495 ExtractBits(frame_type, kQuicSequenceNumberLengthNumBits,
3496 kActBlockLengthOffset));
3497 const QuicPacketNumberLength largest_acked_length = ReadAckPacketNumberLength(
3498 version_.transport_version,
3499 ExtractBits(frame_type, kQuicSequenceNumberLengthNumBits,
3500 kLargestAckedOffset));
3501
3502 uint64_t largest_acked;
3503 if (!reader->ReadBytesToUInt64(largest_acked_length, &largest_acked)) {
3504 set_detailed_error("Unable to read largest acked.");
3505 return false;
3506 }
3507
3508 if (largest_acked < first_sending_packet_number_.ToUint64()) {
3509 // Connection always sends packet starting from kFirstSendingPacketNumber >
3510 // 0, peer has observed an unsent packet.
3511 set_detailed_error("Largest acked is 0.");
3512 return false;
3513 }
3514
3515 uint64_t ack_delay_time_us;
3516 if (!reader->ReadUFloat16(&ack_delay_time_us)) {
3517 set_detailed_error("Unable to read ack delay time.");
3518 return false;
3519 }
3520
3521 if (!visitor_->OnAckFrameStart(
3522 QuicPacketNumber(largest_acked),
3523 ack_delay_time_us == kUFloat16MaxValue
3524 ? QuicTime::Delta::Infinite()
3525 : QuicTime::Delta::FromMicroseconds(ack_delay_time_us))) {
3526 // The visitor suppresses further processing of the packet. Although this is
3527 // not a parsing error, returns false as this is in middle of processing an
3528 // ack frame,
3529 set_detailed_error("Visitor suppresses further processing of ack frame.");
3530 return false;
3531 }
3532
3533 if (has_ack_blocks && !reader->ReadUInt8(&num_ack_blocks)) {
3534 set_detailed_error("Unable to read num of ack blocks.");
3535 return false;
3536 }
3537
3538 uint64_t first_block_length;
3539 if (!reader->ReadBytesToUInt64(ack_block_length, &first_block_length)) {
3540 set_detailed_error("Unable to read first ack block length.");
3541 return false;
3542 }
3543
3544 if (first_block_length == 0) {
3545 set_detailed_error("First block length is zero.");
3546 return false;
3547 }
3548 bool first_ack_block_underflow = first_block_length > largest_acked + 1;
3549 if (first_block_length + first_sending_packet_number_.ToUint64() >
3550 largest_acked + 1) {
3551 first_ack_block_underflow = true;
3552 }
3553 if (first_ack_block_underflow) {
3554 set_detailed_error(QuicStrCat("Underflow with first ack block length ",
3555 first_block_length, " largest acked is ",
3556 largest_acked, ".")
3557 .c_str());
3558 return false;
3559 }
3560
3561 uint64_t first_received = largest_acked + 1 - first_block_length;
3562 if (!visitor_->OnAckRange(QuicPacketNumber(first_received),
3563 QuicPacketNumber(largest_acked + 1))) {
3564 // The visitor suppresses further processing of the packet. Although
3565 // this is not a parsing error, returns false as this is in middle
3566 // of processing an ack frame,
3567 set_detailed_error("Visitor suppresses further processing of ack frame.");
3568 return false;
3569 }
3570
3571 if (num_ack_blocks > 0) {
3572 for (size_t i = 0; i < num_ack_blocks; ++i) {
3573 uint8_t gap = 0;
3574 if (!reader->ReadUInt8(&gap)) {
3575 set_detailed_error("Unable to read gap to next ack block.");
3576 return false;
3577 }
3578 uint64_t current_block_length;
3579 if (!reader->ReadBytesToUInt64(ack_block_length, &current_block_length)) {
3580 set_detailed_error("Unable to ack block length.");
3581 return false;
3582 }
3583 bool ack_block_underflow = first_received < gap + current_block_length;
3584 if (first_received < gap + current_block_length +
3585 first_sending_packet_number_.ToUint64()) {
3586 ack_block_underflow = true;
3587 }
3588 if (ack_block_underflow) {
3589 set_detailed_error(
3590 QuicStrCat("Underflow with ack block length ", current_block_length,
3591 ", end of block is ", first_received - gap, ".")
3592 .c_str());
3593 return false;
3594 }
3595
3596 first_received -= (gap + current_block_length);
3597 if (current_block_length > 0) {
3598 if (!visitor_->OnAckRange(
3599 QuicPacketNumber(first_received),
3600 QuicPacketNumber(first_received) + current_block_length)) {
3601 // The visitor suppresses further processing of the packet. Although
3602 // this is not a parsing error, returns false as this is in middle
3603 // of processing an ack frame,
3604 set_detailed_error(
3605 "Visitor suppresses further processing of ack frame.");
3606 return false;
3607 }
3608 }
3609 }
3610 }
3611
3612 if (!reader->ReadUInt8(&num_received_packets)) {
3613 set_detailed_error("Unable to read num received packets.");
3614 return false;
3615 }
3616
3617 if (!ProcessTimestampsInAckFrame(num_received_packets,
3618 QuicPacketNumber(largest_acked), reader)) {
3619 return false;
3620 }
3621
3622 // Done processing the ACK frame.
3623 return visitor_->OnAckFrameEnd(QuicPacketNumber(first_received));
3624}
3625
3626bool QuicFramer::ProcessTimestampsInAckFrame(uint8_t num_received_packets,
3627 QuicPacketNumber largest_acked,
3628 QuicDataReader* reader) {
3629 if (num_received_packets == 0) {
3630 return true;
3631 }
3632 uint8_t delta_from_largest_observed;
3633 if (!reader->ReadUInt8(&delta_from_largest_observed)) {
3634 set_detailed_error("Unable to read sequence delta in received packets.");
3635 return false;
3636 }
3637
3638 if (largest_acked.ToUint64() <= delta_from_largest_observed) {
3639 set_detailed_error(QuicStrCat("delta_from_largest_observed too high: ",
3640 delta_from_largest_observed,
3641 ", largest_acked: ", largest_acked.ToUint64())
3642 .c_str());
3643 return false;
3644 }
3645
3646 // Time delta from the framer creation.
3647 uint32_t time_delta_us;
3648 if (!reader->ReadUInt32(&time_delta_us)) {
3649 set_detailed_error("Unable to read time delta in received packets.");
3650 return false;
3651 }
3652
3653 QuicPacketNumber seq_num = largest_acked - delta_from_largest_observed;
3654 if (process_timestamps_) {
3655 last_timestamp_ = CalculateTimestampFromWire(time_delta_us);
3656
3657 visitor_->OnAckTimestamp(seq_num, creation_time_ + last_timestamp_);
3658 }
3659
3660 for (uint8_t i = 1; i < num_received_packets; ++i) {
3661 if (!reader->ReadUInt8(&delta_from_largest_observed)) {
3662 set_detailed_error("Unable to read sequence delta in received packets.");
3663 return false;
3664 }
3665 if (largest_acked.ToUint64() <= delta_from_largest_observed) {
3666 set_detailed_error(
3667 QuicStrCat("delta_from_largest_observed too high: ",
3668 delta_from_largest_observed,
3669 ", largest_acked: ", largest_acked.ToUint64())
3670 .c_str());
3671 return false;
3672 }
3673 seq_num = largest_acked - delta_from_largest_observed;
3674
3675 // Time delta from the previous timestamp.
3676 uint64_t incremental_time_delta_us;
3677 if (!reader->ReadUFloat16(&incremental_time_delta_us)) {
3678 set_detailed_error(
3679 "Unable to read incremental time delta in received packets.");
3680 return false;
3681 }
3682
3683 if (process_timestamps_) {
3684 last_timestamp_ = last_timestamp_ + QuicTime::Delta::FromMicroseconds(
3685 incremental_time_delta_us);
3686 visitor_->OnAckTimestamp(seq_num, creation_time_ + last_timestamp_);
3687 }
3688 }
3689 return true;
3690}
3691
3692bool QuicFramer::ProcessIetfAckFrame(QuicDataReader* reader,
3693 uint64_t frame_type,
3694 QuicAckFrame* ack_frame) {
3695 uint64_t largest_acked;
3696 if (!reader->ReadVarInt62(&largest_acked)) {
3697 set_detailed_error("Unable to read largest acked.");
3698 return false;
3699 }
3700 if (largest_acked < first_sending_packet_number_.ToUint64()) {
3701 // Connection always sends packet starting from kFirstSendingPacketNumber >
3702 // 0, peer has observed an unsent packet.
3703 set_detailed_error("Largest acked is 0.");
3704 return false;
3705 }
3706 ack_frame->largest_acked = static_cast<QuicPacketNumber>(largest_acked);
3707 uint64_t ack_delay_time_in_us;
3708 if (!reader->ReadVarInt62(&ack_delay_time_in_us)) {
3709 set_detailed_error("Unable to read ack delay time.");
3710 return false;
3711 }
3712
3713 // TODO(fkastenholz) when we get real IETF QUIC, need to get
3714 // the currect shift from the transport parameters.
3715 if (ack_delay_time_in_us == kVarInt62MaxValue) {
3716 ack_frame->ack_delay_time = QuicTime::Delta::Infinite();
3717 } else {
3718 ack_delay_time_in_us = (ack_delay_time_in_us << kIetfAckTimestampShift);
3719 ack_frame->ack_delay_time =
3720 QuicTime::Delta::FromMicroseconds(ack_delay_time_in_us);
3721 }
3722 if (frame_type == IETF_ACK_ECN) {
3723 ack_frame->ecn_counters_populated = true;
3724 if (!reader->ReadVarInt62(&ack_frame->ect_0_count)) {
3725 set_detailed_error("Unable to read ack ect_0_count.");
3726 return false;
3727 }
3728 if (!reader->ReadVarInt62(&ack_frame->ect_1_count)) {
3729 set_detailed_error("Unable to read ack ect_1_count.");
3730 return false;
3731 }
3732 if (!reader->ReadVarInt62(&ack_frame->ecn_ce_count)) {
3733 set_detailed_error("Unable to read ack ecn_ce_count.");
3734 return false;
3735 }
3736 } else {
3737 ack_frame->ecn_counters_populated = false;
3738 ack_frame->ect_0_count = 0;
3739 ack_frame->ect_1_count = 0;
3740 ack_frame->ecn_ce_count = 0;
3741 }
3742 if (!visitor_->OnAckFrameStart(QuicPacketNumber(largest_acked),
3743 ack_frame->ack_delay_time)) {
3744 // The visitor suppresses further processing of the packet. Although this is
3745 // not a parsing error, returns false as this is in middle of processing an
3746 // ACK frame.
3747 set_detailed_error("Visitor suppresses further processing of ACK frame.");
3748 return false;
3749 }
3750
3751 // Get number of ACK blocks from the packet.
3752 uint64_t ack_block_count;
3753 if (!reader->ReadVarInt62(&ack_block_count)) {
3754 set_detailed_error("Unable to read ack block count.");
3755 return false;
3756 }
3757 // There always is a first ACK block, which is the (number of packets being
3758 // acked)-1, up to and including the packet at largest_acked. Therefore if the
3759 // value is 0, then only largest is acked. If it is 1, then largest-1,
3760 // largest] are acked, etc
3761 uint64_t ack_block_value;
3762 if (!reader->ReadVarInt62(&ack_block_value)) {
3763 set_detailed_error("Unable to read first ack block length.");
3764 return false;
3765 }
3766 // Calculate the packets being acked in the first block.
3767 // +1 because AddRange implementation requires [low,high)
3768 uint64_t block_high = largest_acked + 1;
3769 uint64_t block_low = largest_acked - ack_block_value;
3770
3771 // ack_block_value is the number of packets preceding the
3772 // largest_acked packet which are in the block being acked. Thus,
3773 // its maximum value is largest_acked-1. Test this, reporting an
3774 // error if the value is wrong.
3775 if (ack_block_value + first_sending_packet_number_.ToUint64() >
3776 largest_acked) {
3777 set_detailed_error(QuicStrCat("Underflow with first ack block length ",
3778 ack_block_value + 1, " largest acked is ",
3779 largest_acked, ".")
3780 .c_str());
3781 return false;
3782 }
3783
3784 if (!visitor_->OnAckRange(QuicPacketNumber(block_low),
3785 QuicPacketNumber(block_high))) {
3786 // The visitor suppresses further processing of the packet. Although
3787 // this is not a parsing error, returns false as this is in middle
3788 // of processing an ACK frame.
3789 set_detailed_error("Visitor suppresses further processing of ACK frame.");
3790 return false;
3791 }
3792
3793 while (ack_block_count != 0) {
3794 uint64_t gap_block_value;
3795 // Get the sizes of the gap and ack blocks,
3796 if (!reader->ReadVarInt62(&gap_block_value)) {
3797 set_detailed_error("Unable to read gap block value.");
3798 return false;
3799 }
3800 // It's an error if the gap is larger than the space from packet
3801 // number 0 to the start of the block that's just been acked, PLUS
3802 // there must be space for at least 1 packet to be acked. For
3803 // example, if block_low is 10 and gap_block_value is 9, it means
3804 // the gap block is 10 packets long, leaving no room for a packet
3805 // to be acked. Thus, gap_block_value+2 can not be larger than
3806 // block_low.
3807 // The test is written this way to detect wrap-arounds.
3808 if ((gap_block_value + 2) > block_low) {
3809 set_detailed_error(
3810 QuicStrCat("Underflow with gap block length ", gap_block_value + 1,
3811 " previous ack block start is ", block_low, ".")
3812 .c_str());
3813 return false;
3814 }
3815
3816 // Adjust block_high to be the top of the next ack block.
3817 // There is a gap of |gap_block_value| packets between the bottom
3818 // of ack block N and top of block N+1. Note that gap_block_value
3819 // is he size of the gap minus 1 (per the QUIC protocol), and
3820 // block_high is the packet number of the first packet of the gap
3821 // (per the implementation of OnAckRange/AddAckRange, below).
3822 block_high = block_low - 1 - gap_block_value;
3823
3824 if (!reader->ReadVarInt62(&ack_block_value)) {
3825 set_detailed_error("Unable to read ack block value.");
3826 return false;
3827 }
3828 if (ack_block_value + first_sending_packet_number_.ToUint64() >
3829 (block_high - 1)) {
3830 set_detailed_error(
3831 QuicStrCat("Underflow with ack block length ", ack_block_value + 1,
3832 " latest ack block end is ", block_high - 1, ".")
3833 .c_str());
3834 return false;
3835 }
3836 // Calculate the low end of the new nth ack block. The +1 is
3837 // because the encoded value is the blocksize-1.
3838 block_low = block_high - 1 - ack_block_value;
3839 if (!visitor_->OnAckRange(QuicPacketNumber(block_low),
3840 QuicPacketNumber(block_high))) {
3841 // The visitor suppresses further processing of the packet. Although
3842 // this is not a parsing error, returns false as this is in middle
3843 // of processing an ACK frame.
3844 set_detailed_error("Visitor suppresses further processing of ACK frame.");
3845 return false;
3846 }
3847
3848 // Another one done.
3849 ack_block_count--;
3850 }
3851
3852 return visitor_->OnAckFrameEnd(QuicPacketNumber(block_low));
3853}
3854
3855bool QuicFramer::ProcessStopWaitingFrame(QuicDataReader* reader,
3856 const QuicPacketHeader& header,
3857 QuicStopWaitingFrame* stop_waiting) {
3858 uint64_t least_unacked_delta;
3859 if (!reader->ReadBytesToUInt64(header.packet_number_length,
3860 &least_unacked_delta)) {
3861 set_detailed_error("Unable to read least unacked delta.");
3862 return false;
3863 }
3864 if (header.packet_number.ToUint64() <= least_unacked_delta) {
3865 set_detailed_error("Invalid unacked delta.");
3866 return false;
3867 }
3868 stop_waiting->least_unacked = header.packet_number - least_unacked_delta;
3869
3870 return true;
3871}
3872
3873bool QuicFramer::ProcessRstStreamFrame(QuicDataReader* reader,
3874 QuicRstStreamFrame* frame) {
3875 if (!reader->ReadUInt32(&frame->stream_id)) {
3876 set_detailed_error("Unable to read stream_id.");
3877 return false;
3878 }
3879
3880 if (!reader->ReadUInt64(&frame->byte_offset)) {
3881 set_detailed_error("Unable to read rst stream sent byte offset.");
3882 return false;
3883 }
3884
3885 uint32_t error_code;
3886 if (!reader->ReadUInt32(&error_code)) {
3887 set_detailed_error("Unable to read rst stream error code.");
3888 return false;
3889 }
3890
3891 if (error_code >= QUIC_STREAM_LAST_ERROR) {
3892 // Ignore invalid stream error code if any.
3893 error_code = QUIC_STREAM_LAST_ERROR;
3894 }
3895
3896 frame->error_code = static_cast<QuicRstStreamErrorCode>(error_code);
3897
3898 return true;
3899}
3900
3901bool QuicFramer::ProcessConnectionCloseFrame(QuicDataReader* reader,
3902 QuicConnectionCloseFrame* frame) {
3903 uint32_t error_code;
fkastenholze9d71a82019-04-09 05:12:13 -07003904 frame->close_type = GOOGLE_QUIC_CONNECTION_CLOSE;
3905
QUICHE teama6ef0a62019-03-07 20:34:33 -05003906 if (!reader->ReadUInt32(&error_code)) {
3907 set_detailed_error("Unable to read connection close error code.");
3908 return false;
3909 }
3910
3911 if (error_code >= QUIC_LAST_ERROR) {
3912 // Ignore invalid QUIC error code if any.
3913 error_code = QUIC_LAST_ERROR;
3914 }
3915
fkastenholze9d71a82019-04-09 05:12:13 -07003916 frame->quic_error_code = static_cast<QuicErrorCode>(error_code);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003917
3918 QuicStringPiece error_details;
3919 if (!reader->ReadStringPiece16(&error_details)) {
3920 set_detailed_error("Unable to read connection close error details.");
3921 return false;
3922 }
vasilvvc48c8712019-03-11 13:38:16 -07003923 frame->error_details = std::string(error_details);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003924
3925 return true;
3926}
3927
3928bool QuicFramer::ProcessGoAwayFrame(QuicDataReader* reader,
3929 QuicGoAwayFrame* frame) {
3930 uint32_t error_code;
3931 if (!reader->ReadUInt32(&error_code)) {
3932 set_detailed_error("Unable to read go away error code.");
3933 return false;
3934 }
3935
3936 if (error_code >= QUIC_LAST_ERROR) {
3937 // Ignore invalid QUIC error code if any.
3938 error_code = QUIC_LAST_ERROR;
3939 }
3940 frame->error_code = static_cast<QuicErrorCode>(error_code);
3941
3942 uint32_t stream_id;
3943 if (!reader->ReadUInt32(&stream_id)) {
3944 set_detailed_error("Unable to read last good stream id.");
3945 return false;
3946 }
3947 frame->last_good_stream_id = static_cast<QuicStreamId>(stream_id);
3948
3949 QuicStringPiece reason_phrase;
3950 if (!reader->ReadStringPiece16(&reason_phrase)) {
3951 set_detailed_error("Unable to read goaway reason.");
3952 return false;
3953 }
vasilvvc48c8712019-03-11 13:38:16 -07003954 frame->reason_phrase = std::string(reason_phrase);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003955
3956 return true;
3957}
3958
3959bool QuicFramer::ProcessWindowUpdateFrame(QuicDataReader* reader,
3960 QuicWindowUpdateFrame* frame) {
3961 if (!reader->ReadUInt32(&frame->stream_id)) {
3962 set_detailed_error("Unable to read stream_id.");
3963 return false;
3964 }
3965
3966 if (!reader->ReadUInt64(&frame->byte_offset)) {
3967 set_detailed_error("Unable to read window byte_offset.");
3968 return false;
3969 }
3970
3971 return true;
3972}
3973
3974bool QuicFramer::ProcessBlockedFrame(QuicDataReader* reader,
3975 QuicBlockedFrame* frame) {
fkastenholz305e1732019-06-18 05:01:22 -07003976 DCHECK(!VersionHasIetfQuicFrames(version_.transport_version))
3977 << "Attempt to process non-IETF QUIC frames in an IETF QUIC version.";
QUICHE teama6ef0a62019-03-07 20:34:33 -05003978
3979 if (!reader->ReadUInt32(&frame->stream_id)) {
3980 set_detailed_error("Unable to read stream_id.");
3981 return false;
3982 }
3983
3984 return true;
3985}
3986
3987void QuicFramer::ProcessPaddingFrame(QuicDataReader* reader,
3988 QuicPaddingFrame* frame) {
3989 // Type byte has been read.
3990 frame->num_padding_bytes = 1;
3991 uint8_t next_byte;
3992 while (!reader->IsDoneReading() && reader->PeekByte() == 0x00) {
3993 reader->ReadBytes(&next_byte, 1);
3994 DCHECK_EQ(0x00, next_byte);
3995 ++frame->num_padding_bytes;
3996 }
3997}
3998
3999bool QuicFramer::ProcessMessageFrame(QuicDataReader* reader,
4000 bool no_message_length,
4001 QuicMessageFrame* frame) {
4002 if (no_message_length) {
4003 QuicStringPiece remaining(reader->ReadRemainingPayload());
4004 frame->data = remaining.data();
4005 frame->message_length = remaining.length();
4006 return true;
4007 }
4008
4009 uint64_t message_length;
4010 if (!reader->ReadVarInt62(&message_length)) {
4011 set_detailed_error("Unable to read message length");
4012 return false;
4013 }
4014
4015 QuicStringPiece message_piece;
4016 if (!reader->ReadStringPiece(&message_piece, message_length)) {
4017 set_detailed_error("Unable to read message data");
4018 return false;
4019 }
4020
4021 frame->data = message_piece.data();
4022 frame->message_length = message_length;
4023
4024 return true;
4025}
4026
4027// static
4028QuicStringPiece QuicFramer::GetAssociatedDataFromEncryptedPacket(
4029 QuicTransportVersion version,
4030 const QuicEncryptedPacket& encrypted,
4031 QuicConnectionIdLength destination_connection_id_length,
4032 QuicConnectionIdLength source_connection_id_length,
4033 bool includes_version,
4034 bool includes_diversification_nonce,
4035 QuicPacketNumberLength packet_number_length,
4036 QuicVariableLengthIntegerLength retry_token_length_length,
4037 uint64_t retry_token_length,
4038 QuicVariableLengthIntegerLength length_length) {
4039 // TODO(ianswett): This is identical to QuicData::AssociatedData.
4040 return QuicStringPiece(
4041 encrypted.data(),
4042 GetStartOfEncryptedData(version, destination_connection_id_length,
4043 source_connection_id_length, includes_version,
4044 includes_diversification_nonce,
4045 packet_number_length, retry_token_length_length,
4046 retry_token_length, length_length));
4047}
4048
4049void QuicFramer::SetDecrypter(EncryptionLevel level,
4050 std::unique_ptr<QuicDecrypter> decrypter) {
QUICHE team76086e42019-03-25 15:12:29 -07004051 DCHECK_EQ(alternative_decrypter_level_, NUM_ENCRYPTION_LEVELS);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004052 DCHECK_GE(level, decrypter_level_);
zhongyi546cc452019-04-12 15:27:49 -07004053 DCHECK(!version_.KnowsWhichDecrypterToUse());
QUICHE team76086e42019-03-25 15:12:29 -07004054 decrypter_[decrypter_level_] = nullptr;
4055 decrypter_[level] = std::move(decrypter);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004056 decrypter_level_ = level;
4057}
4058
4059void QuicFramer::SetAlternativeDecrypter(
4060 EncryptionLevel level,
4061 std::unique_ptr<QuicDecrypter> decrypter,
4062 bool latch_once_used) {
QUICHE team76086e42019-03-25 15:12:29 -07004063 DCHECK_NE(level, decrypter_level_);
zhongyi546cc452019-04-12 15:27:49 -07004064 DCHECK(!version_.KnowsWhichDecrypterToUse());
QUICHE team76086e42019-03-25 15:12:29 -07004065 if (alternative_decrypter_level_ != NUM_ENCRYPTION_LEVELS) {
4066 decrypter_[alternative_decrypter_level_] = nullptr;
4067 }
4068 decrypter_[level] = std::move(decrypter);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004069 alternative_decrypter_level_ = level;
4070 alternative_decrypter_latch_ = latch_once_used;
4071}
4072
zhongyi546cc452019-04-12 15:27:49 -07004073void QuicFramer::InstallDecrypter(EncryptionLevel level,
4074 std::unique_ptr<QuicDecrypter> decrypter) {
4075 DCHECK(version_.KnowsWhichDecrypterToUse());
4076 decrypter_[level] = std::move(decrypter);
4077}
4078
4079void QuicFramer::RemoveDecrypter(EncryptionLevel level) {
4080 DCHECK(version_.KnowsWhichDecrypterToUse());
4081 decrypter_[level] = nullptr;
4082}
4083
4084const QuicDecrypter* QuicFramer::GetDecrypter(EncryptionLevel level) const {
4085 DCHECK(version_.KnowsWhichDecrypterToUse());
4086 return decrypter_[level].get();
4087}
4088
QUICHE teama6ef0a62019-03-07 20:34:33 -05004089const QuicDecrypter* QuicFramer::decrypter() const {
QUICHE team76086e42019-03-25 15:12:29 -07004090 return decrypter_[decrypter_level_].get();
QUICHE teama6ef0a62019-03-07 20:34:33 -05004091}
4092
4093const QuicDecrypter* QuicFramer::alternative_decrypter() const {
QUICHE team76086e42019-03-25 15:12:29 -07004094 if (alternative_decrypter_level_ == NUM_ENCRYPTION_LEVELS) {
4095 return nullptr;
4096 }
4097 return decrypter_[alternative_decrypter_level_].get();
QUICHE teama6ef0a62019-03-07 20:34:33 -05004098}
4099
4100void QuicFramer::SetEncrypter(EncryptionLevel level,
4101 std::unique_ptr<QuicEncrypter> encrypter) {
4102 DCHECK_GE(level, 0);
4103 DCHECK_LT(level, NUM_ENCRYPTION_LEVELS);
4104 encrypter_[level] = std::move(encrypter);
4105}
4106
4107size_t QuicFramer::EncryptInPlace(EncryptionLevel level,
4108 QuicPacketNumber packet_number,
4109 size_t ad_len,
4110 size_t total_len,
4111 size_t buffer_len,
4112 char* buffer) {
4113 DCHECK(packet_number.IsInitialized());
dschinazi2c5386e2019-04-16 16:37:37 -07004114 if (encrypter_[level] == nullptr) {
4115 QUIC_BUG << ENDPOINT
4116 << "Attempted to encrypt in place without encrypter at level "
4117 << QuicUtils::EncryptionLevelToString(level);
4118 RaiseError(QUIC_ENCRYPTION_FAILURE);
4119 return 0;
4120 }
4121
QUICHE teama6ef0a62019-03-07 20:34:33 -05004122 size_t output_length = 0;
4123 if (!encrypter_[level]->EncryptPacket(
4124 packet_number.ToUint64(),
4125 QuicStringPiece(buffer, ad_len), // Associated data
4126 QuicStringPiece(buffer + ad_len, total_len - ad_len), // Plaintext
4127 buffer + ad_len, // Destination buffer
4128 &output_length, buffer_len - ad_len)) {
4129 RaiseError(QUIC_ENCRYPTION_FAILURE);
4130 return 0;
4131 }
nharper55fa6132019-05-07 19:37:21 -07004132 if (version_.HasHeaderProtection() &&
4133 !ApplyHeaderProtection(level, buffer, ad_len + output_length, ad_len)) {
4134 QUIC_DLOG(ERROR) << "Applying header protection failed.";
4135 RaiseError(QUIC_ENCRYPTION_FAILURE);
4136 return 0;
4137 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004138
4139 return ad_len + output_length;
4140}
4141
nharper55fa6132019-05-07 19:37:21 -07004142namespace {
4143
4144const size_t kHPSampleLen = 16;
4145
4146constexpr bool IsLongHeader(uint8_t type_byte) {
4147 return (type_byte & FLAGS_LONG_HEADER) != 0;
4148}
4149
4150} // namespace
4151
4152bool QuicFramer::ApplyHeaderProtection(EncryptionLevel level,
4153 char* buffer,
4154 size_t buffer_len,
4155 size_t ad_len) {
4156 QuicDataReader buffer_reader(buffer, buffer_len);
4157 QuicDataWriter buffer_writer(buffer_len, buffer);
4158 // The sample starts 4 bytes after the start of the packet number.
4159 if (ad_len < last_written_packet_number_length_) {
4160 return false;
4161 }
4162 size_t pn_offset = ad_len - last_written_packet_number_length_;
4163 // Sample the ciphertext and generate the mask to use for header protection.
4164 size_t sample_offset = pn_offset + 4;
4165 QuicDataReader sample_reader(buffer, buffer_len);
4166 QuicStringPiece sample;
4167 if (!sample_reader.Seek(sample_offset) ||
4168 !sample_reader.ReadStringPiece(&sample, kHPSampleLen)) {
4169 QUIC_BUG << "Not enough bytes to sample: sample_offset " << sample_offset
4170 << ", sample len: " << kHPSampleLen
4171 << ", buffer len: " << buffer_len;
4172 return false;
4173 }
4174
4175 std::string mask = encrypter_[level]->GenerateHeaderProtectionMask(sample);
4176 if (mask.empty()) {
4177 QUIC_BUG << "Unable to generate header protection mask.";
4178 return false;
4179 }
4180 QuicDataReader mask_reader(mask.data(), mask.size());
4181
4182 // Apply the mask to the 4 or 5 least significant bits of the first byte.
4183 uint8_t bitmask = 0x1f;
4184 uint8_t type_byte;
4185 if (!buffer_reader.ReadUInt8(&type_byte)) {
4186 return false;
4187 }
4188 QuicLongHeaderType header_type;
4189 if (IsLongHeader(type_byte)) {
4190 bitmask = 0x0f;
4191 if (!GetLongHeaderType(version_.transport_version, type_byte,
4192 &header_type)) {
4193 return false;
4194 }
4195 }
4196 uint8_t mask_byte;
4197 if (!mask_reader.ReadUInt8(&mask_byte) ||
4198 !buffer_writer.WriteUInt8(type_byte ^ (mask_byte & bitmask))) {
4199 return false;
4200 }
4201
4202 // Adjust |pn_offset| to account for the diversification nonce.
4203 if (IsLongHeader(type_byte) && header_type == ZERO_RTT_PROTECTED &&
4204 perspective_ == Perspective::IS_SERVER &&
4205 version_.handshake_protocol == PROTOCOL_QUIC_CRYPTO) {
4206 if (pn_offset <= kDiversificationNonceSize) {
4207 QUIC_BUG << "Expected diversification nonce, but not enough bytes";
4208 return false;
4209 }
4210 pn_offset -= kDiversificationNonceSize;
4211 }
4212 // Advance the reader and writer to the packet number. Both the reader and
4213 // writer have each read/written one byte.
4214 if (!buffer_writer.Seek(pn_offset - 1) ||
4215 !buffer_reader.Seek(pn_offset - 1)) {
4216 return false;
4217 }
4218 // Apply the rest of the mask to the packet number.
4219 for (size_t i = 0; i < last_written_packet_number_length_; ++i) {
4220 uint8_t buffer_byte;
4221 uint8_t mask_byte;
4222 if (!mask_reader.ReadUInt8(&mask_byte) ||
4223 !buffer_reader.ReadUInt8(&buffer_byte) ||
4224 !buffer_writer.WriteUInt8(buffer_byte ^ mask_byte)) {
4225 return false;
4226 }
4227 }
4228 return true;
4229}
4230
4231bool QuicFramer::RemoveHeaderProtection(QuicDataReader* reader,
4232 const QuicEncryptedPacket& packet,
4233 QuicPacketHeader* header,
4234 uint64_t* full_packet_number,
4235 std::vector<char>* associated_data) {
4236 EncryptionLevel expected_decryption_level = GetEncryptionLevel(*header);
4237 QuicDecrypter* decrypter = decrypter_[expected_decryption_level].get();
4238 if (decrypter == nullptr) {
4239 QUIC_DVLOG(1)
4240 << "No decrypter available for removing header protection at level "
4241 << expected_decryption_level;
4242 return false;
4243 }
4244
4245 bool has_diversification_nonce =
4246 header->form == IETF_QUIC_LONG_HEADER_PACKET &&
4247 header->long_packet_type == ZERO_RTT_PROTECTED &&
4248 perspective_ == Perspective::IS_CLIENT &&
4249 version_.handshake_protocol == PROTOCOL_QUIC_CRYPTO;
4250
4251 // Read a sample from the ciphertext and compute the mask to use for header
4252 // protection.
4253 QuicStringPiece remaining_packet = reader->PeekRemainingPayload();
4254 QuicDataReader sample_reader(remaining_packet);
4255
4256 // The sample starts 4 bytes after the start of the packet number.
4257 QuicStringPiece pn;
4258 if (!sample_reader.ReadStringPiece(&pn, 4)) {
4259 QUIC_DVLOG(1) << "Not enough data to sample";
4260 return false;
4261 }
4262 if (has_diversification_nonce) {
4263 // In Google QUIC, the diversification nonce comes between the packet number
4264 // and the sample.
4265 if (!sample_reader.Seek(kDiversificationNonceSize)) {
4266 QUIC_DVLOG(1) << "No diversification nonce to skip over";
4267 return false;
4268 }
4269 }
4270 std::string mask = decrypter->GenerateHeaderProtectionMask(&sample_reader);
4271 QuicDataReader mask_reader(mask.data(), mask.size());
4272 if (mask.empty()) {
4273 QUIC_DVLOG(1) << "Failed to compute mask";
4274 return false;
4275 }
4276
4277 // Unmask the rest of the type byte.
4278 uint8_t bitmask = 0x1f;
4279 if (IsLongHeader(header->type_byte)) {
4280 bitmask = 0x0f;
4281 }
4282 uint8_t mask_byte;
4283 if (!mask_reader.ReadUInt8(&mask_byte)) {
4284 QUIC_DVLOG(1) << "No first byte to read from mask";
4285 return false;
4286 }
4287 header->type_byte ^= (mask_byte & bitmask);
4288
4289 // Compute the packet number length.
4290 header->packet_number_length =
4291 static_cast<QuicPacketNumberLength>((header->type_byte & 0x03) + 1);
4292
4293 char pn_buffer[IETF_MAX_PACKET_NUMBER_LENGTH] = {};
4294 QuicDataWriter pn_writer(QUIC_ARRAYSIZE(pn_buffer), pn_buffer);
4295
4296 // Read the (protected) packet number from the reader and unmask the packet
4297 // number.
4298 for (size_t i = 0; i < header->packet_number_length; ++i) {
4299 uint8_t protected_pn_byte, mask_byte;
4300 if (!mask_reader.ReadUInt8(&mask_byte) ||
4301 !reader->ReadUInt8(&protected_pn_byte) ||
4302 !pn_writer.WriteUInt8(protected_pn_byte ^ mask_byte)) {
4303 QUIC_DVLOG(1) << "Failed to unmask packet number";
4304 return false;
4305 }
4306 }
4307 QuicDataReader packet_number_reader(pn_writer.data(), pn_writer.length());
4308 QuicPacketNumber base_packet_number;
4309 if (supports_multiple_packet_number_spaces_) {
4310 PacketNumberSpace pn_space = GetPacketNumberSpace(*header);
4311 if (pn_space == NUM_PACKET_NUMBER_SPACES) {
4312 return false;
4313 }
4314 base_packet_number = largest_decrypted_packet_numbers_[pn_space];
4315 } else {
4316 base_packet_number = largest_packet_number_;
4317 }
4318 if (!ProcessAndCalculatePacketNumber(
4319 &packet_number_reader, header->packet_number_length,
4320 base_packet_number, full_packet_number)) {
4321 return false;
4322 }
4323
4324 // Get the associated data, and apply the same unmasking operations to it.
4325 QuicStringPiece ad = GetAssociatedDataFromEncryptedPacket(
4326 version_.transport_version, packet,
4327 GetIncludedDestinationConnectionIdLength(*header),
4328 GetIncludedSourceConnectionIdLength(*header), header->version_flag,
4329 has_diversification_nonce, header->packet_number_length,
4330 header->retry_token_length_length, header->retry_token.length(),
4331 header->length_length);
4332 *associated_data = std::vector<char>(ad.begin(), ad.end());
4333 QuicDataWriter ad_writer(associated_data->size(), associated_data->data());
4334
4335 // Apply the unmasked type byte and packet number to |associated_data|.
4336 if (!ad_writer.WriteUInt8(header->type_byte)) {
4337 return false;
4338 }
4339 // Put the packet number at the end of the AD, or if there's a diversification
4340 // nonce, before that (which is at the end of the AD).
4341 size_t seek_len = ad_writer.remaining() - header->packet_number_length;
4342 if (has_diversification_nonce) {
4343 seek_len -= kDiversificationNonceSize;
4344 }
4345 if (!ad_writer.Seek(seek_len) ||
4346 !ad_writer.WriteBytes(pn_writer.data(), pn_writer.length())) {
4347 QUIC_DVLOG(1) << "Failed to apply unmasking operations to AD";
4348 return false;
4349 }
4350
4351 return true;
4352}
4353
QUICHE teama6ef0a62019-03-07 20:34:33 -05004354size_t QuicFramer::EncryptPayload(EncryptionLevel level,
4355 QuicPacketNumber packet_number,
4356 const QuicPacket& packet,
4357 char* buffer,
4358 size_t buffer_len) {
4359 DCHECK(packet_number.IsInitialized());
dschinazi2c5386e2019-04-16 16:37:37 -07004360 if (encrypter_[level] == nullptr) {
4361 QUIC_BUG << ENDPOINT << "Attempted to encrypt without encrypter at level "
4362 << QuicUtils::EncryptionLevelToString(level);
4363 RaiseError(QUIC_ENCRYPTION_FAILURE);
4364 return 0;
4365 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004366
4367 QuicStringPiece associated_data =
4368 packet.AssociatedData(version_.transport_version);
4369 // Copy in the header, because the encrypter only populates the encrypted
4370 // plaintext content.
4371 const size_t ad_len = associated_data.length();
4372 memmove(buffer, associated_data.data(), ad_len);
4373 // Encrypt the plaintext into the buffer.
4374 size_t output_length = 0;
4375 if (!encrypter_[level]->EncryptPacket(
4376 packet_number.ToUint64(), associated_data,
4377 packet.Plaintext(version_.transport_version), buffer + ad_len,
4378 &output_length, buffer_len - ad_len)) {
4379 RaiseError(QUIC_ENCRYPTION_FAILURE);
4380 return 0;
4381 }
nharper55fa6132019-05-07 19:37:21 -07004382 if (version_.HasHeaderProtection() &&
4383 !ApplyHeaderProtection(level, buffer, ad_len + output_length, ad_len)) {
4384 QUIC_DLOG(ERROR) << "Applying header protection failed.";
4385 RaiseError(QUIC_ENCRYPTION_FAILURE);
4386 return 0;
4387 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004388
4389 return ad_len + output_length;
4390}
4391
4392size_t QuicFramer::GetCiphertextSize(EncryptionLevel level,
4393 size_t plaintext_size) const {
4394 return encrypter_[level]->GetCiphertextSize(plaintext_size);
4395}
4396
4397size_t QuicFramer::GetMaxPlaintextSize(size_t ciphertext_size) {
4398 // In order to keep the code simple, we don't have the current encryption
4399 // level to hand. Both the NullEncrypter and AES-GCM have a tag length of 12.
4400 size_t min_plaintext_size = ciphertext_size;
4401
QUICHE team6987b4a2019-03-15 16:23:04 -07004402 for (int i = ENCRYPTION_INITIAL; i < NUM_ENCRYPTION_LEVELS; i++) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05004403 if (encrypter_[i] != nullptr) {
4404 size_t size = encrypter_[i]->GetMaxPlaintextSize(ciphertext_size);
4405 if (size < min_plaintext_size) {
4406 min_plaintext_size = size;
4407 }
4408 }
4409 }
4410
4411 return min_plaintext_size;
4412}
4413
4414bool QuicFramer::DecryptPayload(QuicStringPiece encrypted,
4415 QuicStringPiece associated_data,
4416 const QuicPacketHeader& header,
4417 char* decrypted_buffer,
4418 size_t buffer_length,
QUICHE team10b22a12019-03-21 15:31:42 -07004419 size_t* decrypted_length,
4420 EncryptionLevel* decrypted_level) {
nharper855d2172019-05-02 16:17:46 -07004421 if (!EncryptionLevelIsValid(decrypter_level_)) {
4422 QUIC_BUG << "Attempted to decrypt with bad decrypter_level_";
4423 return false;
4424 }
zhongyi546cc452019-04-12 15:27:49 -07004425 EncryptionLevel level = decrypter_level_;
4426 QuicDecrypter* decrypter = decrypter_[level].get();
QUICHE team76086e42019-03-25 15:12:29 -07004427 QuicDecrypter* alternative_decrypter = nullptr;
zhongyi546cc452019-04-12 15:27:49 -07004428 if (version().KnowsWhichDecrypterToUse()) {
nharper855d2172019-05-02 16:17:46 -07004429 if (header.form == GOOGLE_QUIC_PACKET) {
4430 QUIC_BUG << "Attempted to decrypt GOOGLE_QUIC_PACKET with a version that "
4431 "knows which decrypter to use";
4432 return false;
4433 }
zhongyi546cc452019-04-12 15:27:49 -07004434 level = GetEncryptionLevel(header);
nharper855d2172019-05-02 16:17:46 -07004435 if (!EncryptionLevelIsValid(level)) {
4436 QUIC_BUG << "Attempted to decrypt with bad level";
4437 return false;
4438 }
zhongyi546cc452019-04-12 15:27:49 -07004439 decrypter = decrypter_[level].get();
4440 if (decrypter == nullptr) {
4441 return false;
4442 }
4443 if (level == ENCRYPTION_ZERO_RTT &&
4444 perspective_ == Perspective::IS_CLIENT && header.nonce != nullptr) {
4445 decrypter->SetDiversificationNonce(*header.nonce);
4446 }
4447 } else if (alternative_decrypter_level_ != NUM_ENCRYPTION_LEVELS) {
nharper855d2172019-05-02 16:17:46 -07004448 if (!EncryptionLevelIsValid(alternative_decrypter_level_)) {
4449 QUIC_BUG << "Attempted to decrypt with bad alternative_decrypter_level_";
4450 return false;
4451 }
QUICHE team76086e42019-03-25 15:12:29 -07004452 alternative_decrypter = decrypter_[alternative_decrypter_level_].get();
4453 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004454
nharper855d2172019-05-02 16:17:46 -07004455 if (decrypter == nullptr) {
ianswettf919fb22019-05-13 06:42:11 -07004456 QUIC_BUG << "Attempting to decrypt without decrypter, encryption level:"
4457 << level << " version:" << version();
nharper855d2172019-05-02 16:17:46 -07004458 return false;
4459 }
zhongyi546cc452019-04-12 15:27:49 -07004460
4461 bool success = decrypter->DecryptPacket(
QUICHE teama6ef0a62019-03-07 20:34:33 -05004462 header.packet_number.ToUint64(), associated_data, encrypted,
4463 decrypted_buffer, decrypted_length, buffer_length);
4464 if (success) {
zhongyi546cc452019-04-12 15:27:49 -07004465 visitor_->OnDecryptedPacket(level);
4466 *decrypted_level = level;
QUICHE team76086e42019-03-25 15:12:29 -07004467 } else if (alternative_decrypter != nullptr) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05004468 if (header.nonce != nullptr) {
4469 DCHECK_EQ(perspective_, Perspective::IS_CLIENT);
QUICHE team76086e42019-03-25 15:12:29 -07004470 alternative_decrypter->SetDiversificationNonce(*header.nonce);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004471 }
4472 bool try_alternative_decryption = true;
4473 if (alternative_decrypter_level_ == ENCRYPTION_ZERO_RTT) {
4474 if (perspective_ == Perspective::IS_CLIENT) {
4475 if (header.nonce == nullptr) {
4476 // Can not use INITIAL decryption without a diversification nonce.
4477 try_alternative_decryption = false;
4478 }
4479 } else {
4480 DCHECK(header.nonce == nullptr);
4481 }
4482 }
4483
4484 if (try_alternative_decryption) {
QUICHE team76086e42019-03-25 15:12:29 -07004485 success = alternative_decrypter->DecryptPacket(
QUICHE teama6ef0a62019-03-07 20:34:33 -05004486 header.packet_number.ToUint64(), associated_data, encrypted,
4487 decrypted_buffer, decrypted_length, buffer_length);
4488 }
4489 if (success) {
4490 visitor_->OnDecryptedPacket(alternative_decrypter_level_);
QUICHE team10b22a12019-03-21 15:31:42 -07004491 *decrypted_level = decrypter_level_;
QUICHE teama6ef0a62019-03-07 20:34:33 -05004492 if (alternative_decrypter_latch_) {
nharper855d2172019-05-02 16:17:46 -07004493 if (!EncryptionLevelIsValid(alternative_decrypter_level_)) {
4494 QUIC_BUG << "Attempted to latch alternate decrypter with bad "
4495 "alternative_decrypter_level_";
4496 return false;
4497 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004498 // Switch to the alternative decrypter and latch so that we cannot
4499 // switch back.
QUICHE teama6ef0a62019-03-07 20:34:33 -05004500 decrypter_level_ = alternative_decrypter_level_;
QUICHE team76086e42019-03-25 15:12:29 -07004501 alternative_decrypter_level_ = NUM_ENCRYPTION_LEVELS;
QUICHE teama6ef0a62019-03-07 20:34:33 -05004502 } else {
4503 // Switch the alternative decrypter so that we use it first next time.
QUICHE teama6ef0a62019-03-07 20:34:33 -05004504 EncryptionLevel level = alternative_decrypter_level_;
4505 alternative_decrypter_level_ = decrypter_level_;
4506 decrypter_level_ = level;
4507 }
4508 }
4509 }
4510
4511 if (!success) {
dschinazi965ce092019-05-23 06:29:01 -07004512 QUIC_DVLOG(1) << ENDPOINT << "DecryptPacket failed for: " << header;
QUICHE teama6ef0a62019-03-07 20:34:33 -05004513 return false;
4514 }
4515
4516 return true;
4517}
4518
4519size_t QuicFramer::GetIetfAckFrameSize(const QuicAckFrame& frame) {
4520 // Type byte, largest_acked, and delay_time are straight-forward.
4521 size_t ack_frame_size = kQuicFrameTypeSize;
4522 QuicPacketNumber largest_acked = LargestAcked(frame);
4523 ack_frame_size += QuicDataWriter::GetVarInt62Len(largest_acked.ToUint64());
4524 uint64_t ack_delay_time_us;
4525 ack_delay_time_us = frame.ack_delay_time.ToMicroseconds();
4526 ack_delay_time_us = ack_delay_time_us >> kIetfAckTimestampShift;
4527 ack_frame_size += QuicDataWriter::GetVarInt62Len(ack_delay_time_us);
4528
4529 // If |ecn_counters_populated| is true and any of the ecn counters is non-0
4530 // then the ecn counters are included...
4531 if (frame.ecn_counters_populated &&
4532 (frame.ect_0_count || frame.ect_1_count || frame.ecn_ce_count)) {
4533 ack_frame_size += QuicDataWriter::GetVarInt62Len(frame.ect_0_count);
4534 ack_frame_size += QuicDataWriter::GetVarInt62Len(frame.ect_1_count);
4535 ack_frame_size += QuicDataWriter::GetVarInt62Len(frame.ecn_ce_count);
4536 }
4537
4538 // The rest (ack_block_count, first_ack_block, and additional ack
4539 // blocks, if any) depends:
4540 uint64_t ack_block_count = frame.packets.NumIntervals();
4541 if (ack_block_count == 0) {
4542 // If the QuicAckFrame has no Intervals, then it is interpreted
4543 // as an ack of a single packet at QuicAckFrame.largest_acked.
4544 // The resulting ack will consist of only the frame's
4545 // largest_ack & first_ack_block fields. The first ack block will be 0
4546 // (indicating a single packet) and the ack block_count will be 0.
4547 // Each 0 takes 1 byte when VarInt62 encoded.
4548 ack_frame_size += 2;
4549 return ack_frame_size;
4550 }
4551
4552 auto itr = frame.packets.rbegin();
4553 QuicPacketNumber ack_block_largest = largest_acked;
4554 QuicPacketNumber ack_block_smallest;
4555 if ((itr->max() - 1) == largest_acked) {
4556 // If largest_acked + 1 is equal to the Max() of the first Interval
4557 // in the QuicAckFrame then the first Interval is the first ack block of the
4558 // frame; remaining Intervals are additional ack blocks. The QuicAckFrame's
4559 // first Interval is encoded in the frame's largest_acked/first_ack_block,
4560 // the remaining Intervals are encoded in additional ack blocks in the
4561 // frame, and the packet's ack_block_count is the number of QuicAckFrame
4562 // Intervals - 1.
4563 ack_block_smallest = itr->min();
4564 itr++;
4565 ack_block_count--;
4566 } else {
4567 // If QuicAckFrame.largest_acked is NOT equal to the Max() of
4568 // the first Interval then it is interpreted as acking a single
4569 // packet at QuicAckFrame.largest_acked, with additional
4570 // Intervals indicating additional ack blocks. The encoding is
4571 // a) The packet's largest_acked is the QuicAckFrame's largest
4572 // acked,
4573 // b) the first ack block size is 0,
4574 // c) The packet's ack_block_count is the number of QuicAckFrame
4575 // Intervals, and
4576 // d) The QuicAckFrame Intervals are encoded in additional ack
4577 // blocks in the packet.
4578 ack_block_smallest = largest_acked;
4579 }
4580 size_t ack_block_count_size = QuicDataWriter::GetVarInt62Len(ack_block_count);
4581 ack_frame_size += ack_block_count_size;
4582
4583 uint64_t first_ack_block = ack_block_largest - ack_block_smallest;
4584 size_t first_ack_block_size = QuicDataWriter::GetVarInt62Len(first_ack_block);
4585 ack_frame_size += first_ack_block_size;
4586
4587 // Account for the remaining Intervals, if any.
4588 while (ack_block_count != 0) {
4589 uint64_t gap_size = ack_block_smallest - itr->max();
4590 // Decrement per the protocol specification
4591 size_t size_of_gap_size = QuicDataWriter::GetVarInt62Len(gap_size - 1);
4592 ack_frame_size += size_of_gap_size;
4593
4594 uint64_t block_size = itr->max() - itr->min();
4595 // Decrement per the protocol specification
4596 size_t size_of_block_size = QuicDataWriter::GetVarInt62Len(block_size - 1);
4597 ack_frame_size += size_of_block_size;
4598
4599 ack_block_smallest = itr->min();
4600 itr++;
4601 ack_block_count--;
4602 }
4603
4604 return ack_frame_size;
4605}
4606
4607size_t QuicFramer::GetAckFrameSize(
4608 const QuicAckFrame& ack,
dschinazi17d42422019-06-18 16:35:07 -07004609 QuicPacketNumberLength /*packet_number_length*/) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05004610 DCHECK(!ack.packets.Empty());
4611 size_t ack_size = 0;
4612
fkastenholz305e1732019-06-18 05:01:22 -07004613 if (VersionHasIetfQuicFrames(version_.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05004614 return GetIetfAckFrameSize(ack);
4615 }
4616 AckFrameInfo ack_info = GetAckFrameInfo(ack);
4617 QuicPacketNumberLength largest_acked_length =
4618 GetMinPacketNumberLength(version_.transport_version, LargestAcked(ack));
4619 QuicPacketNumberLength ack_block_length = GetMinPacketNumberLength(
4620 version_.transport_version, QuicPacketNumber(ack_info.max_block_length));
4621
4622 ack_size =
4623 GetMinAckFrameSize(version_.transport_version, largest_acked_length);
4624 // First ack block length.
4625 ack_size += ack_block_length;
4626 if (ack_info.num_ack_blocks != 0) {
4627 ack_size += kNumberOfAckBlocksSize;
4628 ack_size += std::min(ack_info.num_ack_blocks, kMaxAckBlocks) *
4629 (ack_block_length + PACKET_1BYTE_PACKET_NUMBER);
4630 }
4631
4632 // Include timestamps.
4633 if (process_timestamps_) {
4634 ack_size += GetAckFrameTimeStampSize(ack);
4635 }
4636
4637 return ack_size;
4638}
4639
4640size_t QuicFramer::GetAckFrameTimeStampSize(const QuicAckFrame& ack) {
4641 if (ack.received_packet_times.empty()) {
4642 return 0;
4643 }
4644
4645 return kQuicNumTimestampsLength + kQuicFirstTimestampLength +
4646 (kQuicTimestampLength + kQuicTimestampPacketNumberGapLength) *
4647 (ack.received_packet_times.size() - 1);
4648}
4649
4650size_t QuicFramer::ComputeFrameLength(
4651 const QuicFrame& frame,
4652 bool last_frame_in_packet,
4653 QuicPacketNumberLength packet_number_length) {
4654 switch (frame.type) {
4655 case STREAM_FRAME:
4656 return GetMinStreamFrameSize(
4657 version_.transport_version, frame.stream_frame.stream_id,
4658 frame.stream_frame.offset, last_frame_in_packet,
4659 frame.stream_frame.data_length) +
4660 frame.stream_frame.data_length;
4661 case CRYPTO_FRAME:
4662 return GetMinCryptoFrameSize(frame.crypto_frame->offset,
4663 frame.crypto_frame->data_length) +
4664 frame.crypto_frame->data_length;
4665 case ACK_FRAME: {
4666 return GetAckFrameSize(*frame.ack_frame, packet_number_length);
4667 }
4668 case STOP_WAITING_FRAME:
4669 return GetStopWaitingFrameSize(version_.transport_version,
4670 packet_number_length);
4671 case MTU_DISCOVERY_FRAME:
4672 // MTU discovery frames are serialized as ping frames.
4673 return kQuicFrameTypeSize;
4674 case MESSAGE_FRAME:
4675 return GetMessageFrameSize(version_.transport_version,
4676 last_frame_in_packet,
4677 frame.message_frame->message_length);
4678 case PADDING_FRAME:
4679 DCHECK(false);
4680 return 0;
4681 default:
4682 return GetRetransmittableControlFrameSize(version_.transport_version,
4683 frame);
4684 }
4685}
4686
4687bool QuicFramer::AppendTypeByte(const QuicFrame& frame,
4688 bool last_frame_in_packet,
4689 QuicDataWriter* writer) {
fkastenholz305e1732019-06-18 05:01:22 -07004690 if (VersionHasIetfQuicFrames(version_.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05004691 return AppendIetfTypeByte(frame, last_frame_in_packet, writer);
4692 }
4693 uint8_t type_byte = 0;
4694 switch (frame.type) {
4695 case STREAM_FRAME:
4696 type_byte =
4697 GetStreamFrameTypeByte(frame.stream_frame, last_frame_in_packet);
4698 break;
4699 case ACK_FRAME:
4700 return true;
4701 case MTU_DISCOVERY_FRAME:
4702 type_byte = static_cast<uint8_t>(PING_FRAME);
4703 break;
QUICHE teama6ef0a62019-03-07 20:34:33 -05004704 case NEW_CONNECTION_ID_FRAME:
4705 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -07004706 "Attempt to append NEW_CONNECTION_ID frame and not in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05004707 return RaiseError(QUIC_INTERNAL_ERROR);
4708 case RETIRE_CONNECTION_ID_FRAME:
4709 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -07004710 "Attempt to append RETIRE_CONNECTION_ID frame and not in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05004711 return RaiseError(QUIC_INTERNAL_ERROR);
4712 case NEW_TOKEN_FRAME:
4713 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -07004714 "Attempt to append NEW_TOKEN frame and not in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05004715 return RaiseError(QUIC_INTERNAL_ERROR);
fkastenholz3c4eabf2019-04-22 07:49:59 -07004716 case MAX_STREAMS_FRAME:
QUICHE teama6ef0a62019-03-07 20:34:33 -05004717 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -07004718 "Attempt to append MAX_STREAMS frame and not in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05004719 return RaiseError(QUIC_INTERNAL_ERROR);
fkastenholz3c4eabf2019-04-22 07:49:59 -07004720 case STREAMS_BLOCKED_FRAME:
QUICHE teama6ef0a62019-03-07 20:34:33 -05004721 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -07004722 "Attempt to append STREAMS_BLOCKED frame and not in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05004723 return RaiseError(QUIC_INTERNAL_ERROR);
4724 case PATH_RESPONSE_FRAME:
4725 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -07004726 "Attempt to append PATH_RESPONSE frame and not in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05004727 return RaiseError(QUIC_INTERNAL_ERROR);
4728 case PATH_CHALLENGE_FRAME:
4729 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -07004730 "Attempt to append PATH_CHALLENGE frame and not in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05004731 return RaiseError(QUIC_INTERNAL_ERROR);
4732 case STOP_SENDING_FRAME:
4733 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -07004734 "Attempt to append STOP_SENDING frame and not in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05004735 return RaiseError(QUIC_INTERNAL_ERROR);
4736 case MESSAGE_FRAME:
4737 return true;
4738
4739 default:
4740 type_byte = static_cast<uint8_t>(frame.type);
4741 break;
4742 }
4743
4744 return writer->WriteUInt8(type_byte);
4745}
4746
4747bool QuicFramer::AppendIetfTypeByte(const QuicFrame& frame,
4748 bool last_frame_in_packet,
4749 QuicDataWriter* writer) {
4750 uint8_t type_byte = 0;
4751 switch (frame.type) {
4752 case PADDING_FRAME:
4753 type_byte = IETF_PADDING;
4754 break;
4755 case RST_STREAM_FRAME:
4756 type_byte = IETF_RST_STREAM;
4757 break;
4758 case CONNECTION_CLOSE_FRAME:
fkastenholz72f509b2019-04-10 09:17:49 -07004759 switch (frame.connection_close_frame->close_type) {
4760 case IETF_QUIC_APPLICATION_CONNECTION_CLOSE:
4761 type_byte = IETF_APPLICATION_CLOSE;
4762 break;
4763 case IETF_QUIC_TRANSPORT_CONNECTION_CLOSE:
4764 type_byte = IETF_CONNECTION_CLOSE;
4765 break;
4766 default:
4767 set_detailed_error("Invalid QuicConnectionCloseFrame type.");
4768 return RaiseError(QUIC_INTERNAL_ERROR);
4769 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004770 break;
4771 case GOAWAY_FRAME:
4772 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -07004773 "Attempt to create non-IETF QUIC GOAWAY frame in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05004774 return RaiseError(QUIC_INTERNAL_ERROR);
4775 case WINDOW_UPDATE_FRAME:
4776 // Depending on whether there is a stream ID or not, will be either a
4777 // MAX_STREAM_DATA frame or a MAX_DATA frame.
4778 if (frame.window_update_frame->stream_id ==
4779 QuicUtils::GetInvalidStreamId(transport_version())) {
4780 type_byte = IETF_MAX_DATA;
4781 } else {
4782 type_byte = IETF_MAX_STREAM_DATA;
4783 }
4784 break;
4785 case BLOCKED_FRAME:
4786 if (frame.blocked_frame->stream_id ==
4787 QuicUtils::GetInvalidStreamId(transport_version())) {
4788 type_byte = IETF_BLOCKED;
4789 } else {
4790 type_byte = IETF_STREAM_BLOCKED;
4791 }
4792 break;
4793 case STOP_WAITING_FRAME:
4794 set_detailed_error(
fkastenholz305e1732019-06-18 05:01:22 -07004795 "Attempt to append type byte of STOP WAITING frame in IETF QUIC.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05004796 return RaiseError(QUIC_INTERNAL_ERROR);
4797 case PING_FRAME:
4798 type_byte = IETF_PING;
4799 break;
4800 case STREAM_FRAME:
4801 type_byte =
4802 GetStreamFrameTypeByte(frame.stream_frame, last_frame_in_packet);
4803 break;
4804 case ACK_FRAME:
4805 // Do nothing here, AppendIetfAckFrameAndTypeByte() will put the type byte
4806 // in the buffer.
4807 return true;
4808 case MTU_DISCOVERY_FRAME:
4809 // The path MTU discovery frame is encoded as a PING frame on the wire.
4810 type_byte = IETF_PING;
4811 break;
QUICHE teama6ef0a62019-03-07 20:34:33 -05004812 case NEW_CONNECTION_ID_FRAME:
4813 type_byte = IETF_NEW_CONNECTION_ID;
4814 break;
4815 case RETIRE_CONNECTION_ID_FRAME:
4816 type_byte = IETF_RETIRE_CONNECTION_ID;
4817 break;
4818 case NEW_TOKEN_FRAME:
4819 type_byte = IETF_NEW_TOKEN;
4820 break;
fkastenholz3c4eabf2019-04-22 07:49:59 -07004821 case MAX_STREAMS_FRAME:
4822 if (frame.max_streams_frame.unidirectional) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05004823 type_byte = IETF_MAX_STREAMS_UNIDIRECTIONAL;
fkastenholz3c4eabf2019-04-22 07:49:59 -07004824 } else {
4825 type_byte = IETF_MAX_STREAMS_BIDIRECTIONAL;
QUICHE teama6ef0a62019-03-07 20:34:33 -05004826 }
4827 break;
fkastenholz3c4eabf2019-04-22 07:49:59 -07004828 case STREAMS_BLOCKED_FRAME:
4829 if (frame.streams_blocked_frame.unidirectional) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05004830 type_byte = IETF_STREAMS_BLOCKED_UNIDIRECTIONAL;
fkastenholz3c4eabf2019-04-22 07:49:59 -07004831 } else {
4832 type_byte = IETF_STREAMS_BLOCKED_BIDIRECTIONAL;
QUICHE teama6ef0a62019-03-07 20:34:33 -05004833 }
4834 break;
4835 case PATH_RESPONSE_FRAME:
4836 type_byte = IETF_PATH_RESPONSE;
4837 break;
4838 case PATH_CHALLENGE_FRAME:
4839 type_byte = IETF_PATH_CHALLENGE;
4840 break;
4841 case STOP_SENDING_FRAME:
4842 type_byte = IETF_STOP_SENDING;
4843 break;
4844 case MESSAGE_FRAME:
4845 return true;
4846 case CRYPTO_FRAME:
4847 type_byte = IETF_CRYPTO;
4848 break;
4849 default:
4850 QUIC_BUG << "Attempt to generate a frame type for an unsupported value: "
4851 << frame.type;
4852 return false;
4853 }
4854 return writer->WriteUInt8(type_byte);
4855}
4856
4857// static
4858bool QuicFramer::AppendPacketNumber(QuicPacketNumberLength packet_number_length,
4859 QuicPacketNumber packet_number,
4860 QuicDataWriter* writer) {
4861 DCHECK(packet_number.IsInitialized());
4862 if (!IsValidPacketNumberLength(packet_number_length)) {
4863 QUIC_BUG << "Invalid packet_number_length: " << packet_number_length;
4864 return false;
4865 }
4866 return writer->WriteBytesToUInt64(packet_number_length,
4867 packet_number.ToUint64());
4868}
4869
4870// static
4871bool QuicFramer::AppendStreamId(size_t stream_id_length,
4872 QuicStreamId stream_id,
4873 QuicDataWriter* writer) {
4874 if (stream_id_length == 0 || stream_id_length > 4) {
4875 QUIC_BUG << "Invalid stream_id_length: " << stream_id_length;
4876 return false;
4877 }
4878 return writer->WriteBytesToUInt64(stream_id_length, stream_id);
4879}
4880
4881// static
4882bool QuicFramer::AppendStreamOffset(size_t offset_length,
4883 QuicStreamOffset offset,
4884 QuicDataWriter* writer) {
4885 if (offset_length == 1 || offset_length > 8) {
4886 QUIC_BUG << "Invalid stream_offset_length: " << offset_length;
4887 return false;
4888 }
4889
4890 return writer->WriteBytesToUInt64(offset_length, offset);
4891}
4892
4893// static
4894bool QuicFramer::AppendAckBlock(uint8_t gap,
4895 QuicPacketNumberLength length_length,
4896 uint64_t length,
4897 QuicDataWriter* writer) {
4898 if (length == 0) {
4899 if (!IsValidPacketNumberLength(length_length)) {
4900 QUIC_BUG << "Invalid packet_number_length: " << length_length;
4901 return false;
4902 }
4903 return writer->WriteUInt8(gap) &&
4904 writer->WriteBytesToUInt64(length_length, length);
4905 }
4906 return writer->WriteUInt8(gap) &&
4907 AppendPacketNumber(length_length, QuicPacketNumber(length), writer);
4908}
4909
4910bool QuicFramer::AppendStreamFrame(const QuicStreamFrame& frame,
4911 bool no_stream_frame_length,
4912 QuicDataWriter* writer) {
fkastenholz305e1732019-06-18 05:01:22 -07004913 if (VersionHasIetfQuicFrames(version_.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05004914 return AppendIetfStreamFrame(frame, no_stream_frame_length, writer);
4915 }
4916 if (!AppendStreamId(GetStreamIdSize(frame.stream_id), frame.stream_id,
4917 writer)) {
4918 QUIC_BUG << "Writing stream id size failed.";
4919 return false;
4920 }
4921 if (!AppendStreamOffset(
4922 GetStreamOffsetSize(version_.transport_version, frame.offset),
4923 frame.offset, writer)) {
4924 QUIC_BUG << "Writing offset size failed.";
4925 return false;
4926 }
4927 if (!no_stream_frame_length) {
dschinazi878cfb52019-06-17 17:12:58 -07004928 static_assert(
wubeff50282019-06-19 09:04:30 -07004929 std::numeric_limits<decltype(frame.data_length)>::max() <=
dschinazi878cfb52019-06-17 17:12:58 -07004930 std::numeric_limits<uint16_t>::max(),
4931 "If frame.data_length can hold more than a uint16_t than we need to "
4932 "check that frame.data_length <= std::numeric_limits<uint16_t>::max()");
4933 if (!writer->WriteUInt16(static_cast<uint16_t>(frame.data_length))) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05004934 QUIC_BUG << "Writing stream frame length failed";
4935 return false;
4936 }
4937 }
4938
4939 if (data_producer_ != nullptr) {
4940 DCHECK_EQ(nullptr, frame.data_buffer);
4941 if (frame.data_length == 0) {
4942 return true;
4943 }
4944 if (data_producer_->WriteStreamData(frame.stream_id, frame.offset,
4945 frame.data_length,
4946 writer) != WRITE_SUCCESS) {
4947 QUIC_BUG << "Writing frame data failed.";
4948 return false;
4949 }
4950 return true;
4951 }
4952
4953 if (!writer->WriteBytes(frame.data_buffer, frame.data_length)) {
4954 QUIC_BUG << "Writing frame data failed.";
4955 return false;
4956 }
4957 return true;
4958}
4959
QUICHE teama6ef0a62019-03-07 20:34:33 -05004960bool QuicFramer::AppendNewTokenFrame(const QuicNewTokenFrame& frame,
4961 QuicDataWriter* writer) {
4962 if (!writer->WriteVarInt62(static_cast<uint64_t>(frame.token.length()))) {
4963 set_detailed_error("Writing token length failed.");
4964 return false;
4965 }
4966 if (!writer->WriteBytes(frame.token.data(), frame.token.length())) {
4967 set_detailed_error("Writing token buffer failed.");
4968 return false;
4969 }
4970 return true;
4971}
4972
4973bool QuicFramer::ProcessNewTokenFrame(QuicDataReader* reader,
4974 QuicNewTokenFrame* frame) {
4975 uint64_t length;
4976 if (!reader->ReadVarInt62(&length)) {
4977 set_detailed_error("Unable to read new token length.");
4978 return false;
4979 }
4980 if (length > kMaxNewTokenTokenLength) {
4981 set_detailed_error("Token length larger than maximum.");
4982 return false;
4983 }
4984
4985 // TODO(ianswett): Don't use QuicStringPiece as an intermediary.
4986 QuicStringPiece data;
4987 if (!reader->ReadStringPiece(&data, length)) {
4988 set_detailed_error("Unable to read new token data.");
4989 return false;
4990 }
vasilvvc48c8712019-03-11 13:38:16 -07004991 frame->token = std::string(data);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004992 return true;
4993}
4994
4995// Add a new ietf-format stream frame.
4996// Bits controlling whether there is a frame-length and frame-offset
4997// are in the QuicStreamFrame.
4998bool QuicFramer::AppendIetfStreamFrame(const QuicStreamFrame& frame,
4999 bool last_frame_in_packet,
5000 QuicDataWriter* writer) {
5001 if (!writer->WriteVarInt62(static_cast<uint64_t>(frame.stream_id))) {
5002 set_detailed_error("Writing stream id failed.");
5003 return false;
5004 }
5005
5006 if (frame.offset != 0) {
5007 if (!writer->WriteVarInt62(static_cast<uint64_t>(frame.offset))) {
5008 set_detailed_error("Writing data offset failed.");
5009 return false;
5010 }
5011 }
5012
5013 if (!last_frame_in_packet) {
5014 if (!writer->WriteVarInt62(frame.data_length)) {
5015 set_detailed_error("Writing data length failed.");
5016 return false;
5017 }
5018 }
5019
5020 if (frame.data_length == 0) {
5021 return true;
5022 }
5023 if (data_producer_ == nullptr) {
5024 if (!writer->WriteBytes(frame.data_buffer, frame.data_length)) {
5025 set_detailed_error("Writing frame data failed.");
5026 return false;
5027 }
5028 } else {
5029 DCHECK_EQ(nullptr, frame.data_buffer);
5030
5031 if (data_producer_->WriteStreamData(frame.stream_id, frame.offset,
5032 frame.data_length,
5033 writer) != WRITE_SUCCESS) {
5034 set_detailed_error("Writing frame data failed.");
5035 return false;
5036 }
5037 }
5038 return true;
5039}
5040
5041bool QuicFramer::AppendCryptoFrame(const QuicCryptoFrame& frame,
5042 QuicDataWriter* writer) {
5043 if (!writer->WriteVarInt62(static_cast<uint64_t>(frame.offset))) {
5044 set_detailed_error("Writing data offset failed.");
5045 return false;
5046 }
5047 if (!writer->WriteVarInt62(static_cast<uint64_t>(frame.data_length))) {
5048 set_detailed_error("Writing data length failed.");
5049 return false;
5050 }
5051 if (data_producer_ == nullptr) {
5052 if (frame.data_buffer == nullptr ||
5053 !writer->WriteBytes(frame.data_buffer, frame.data_length)) {
5054 set_detailed_error("Writing frame data failed.");
5055 return false;
5056 }
5057 } else {
5058 DCHECK_EQ(nullptr, frame.data_buffer);
5059 if (!data_producer_->WriteCryptoData(frame.level, frame.offset,
5060 frame.data_length, writer)) {
5061 return false;
5062 }
5063 }
5064 return true;
5065}
5066
5067void QuicFramer::set_version(const ParsedQuicVersion version) {
5068 DCHECK(IsSupportedVersion(version)) << ParsedQuicVersionToString(version);
5069 version_ = version;
5070}
5071
5072bool QuicFramer::AppendAckFrameAndTypeByte(const QuicAckFrame& frame,
5073 QuicDataWriter* writer) {
fkastenholz305e1732019-06-18 05:01:22 -07005074 if (VersionHasIetfQuicFrames(transport_version())) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005075 return AppendIetfAckFrameAndTypeByte(frame, writer);
5076 }
5077
5078 const AckFrameInfo new_ack_info = GetAckFrameInfo(frame);
5079 QuicPacketNumber largest_acked = LargestAcked(frame);
5080 QuicPacketNumberLength largest_acked_length =
5081 GetMinPacketNumberLength(version_.transport_version, largest_acked);
5082 QuicPacketNumberLength ack_block_length =
5083 GetMinPacketNumberLength(version_.transport_version,
5084 QuicPacketNumber(new_ack_info.max_block_length));
5085 // Calculate available bytes for timestamps and ack blocks.
5086 int32_t available_timestamp_and_ack_block_bytes =
5087 writer->capacity() - writer->length() - ack_block_length -
5088 GetMinAckFrameSize(version_.transport_version, largest_acked_length) -
5089 (new_ack_info.num_ack_blocks != 0 ? kNumberOfAckBlocksSize : 0);
5090 DCHECK_LE(0, available_timestamp_and_ack_block_bytes);
5091
5092 // Write out the type byte by setting the low order bits and doing shifts
5093 // to make room for the next bit flags to be set.
5094 // Whether there are multiple ack blocks.
5095 uint8_t type_byte = 0;
5096 SetBit(&type_byte, new_ack_info.num_ack_blocks != 0,
5097 kQuicHasMultipleAckBlocksOffset);
5098
5099 SetBits(&type_byte, GetPacketNumberFlags(largest_acked_length),
5100 kQuicSequenceNumberLengthNumBits, kLargestAckedOffset);
5101
5102 SetBits(&type_byte, GetPacketNumberFlags(ack_block_length),
5103 kQuicSequenceNumberLengthNumBits, kActBlockLengthOffset);
5104
5105 type_byte |= kQuicFrameTypeAckMask;
5106
5107 if (!writer->WriteUInt8(type_byte)) {
5108 return false;
5109 }
5110
5111 size_t max_num_ack_blocks = available_timestamp_and_ack_block_bytes /
5112 (ack_block_length + PACKET_1BYTE_PACKET_NUMBER);
5113
5114 // Number of ack blocks.
5115 size_t num_ack_blocks =
5116 std::min(new_ack_info.num_ack_blocks, max_num_ack_blocks);
5117 if (num_ack_blocks > std::numeric_limits<uint8_t>::max()) {
5118 num_ack_blocks = std::numeric_limits<uint8_t>::max();
5119 }
5120
5121 // Largest acked.
5122 if (!AppendPacketNumber(largest_acked_length, largest_acked, writer)) {
5123 return false;
5124 }
5125
5126 // Largest acked delta time.
5127 uint64_t ack_delay_time_us = kUFloat16MaxValue;
5128 if (!frame.ack_delay_time.IsInfinite()) {
5129 DCHECK_LE(0u, frame.ack_delay_time.ToMicroseconds());
5130 ack_delay_time_us = frame.ack_delay_time.ToMicroseconds();
5131 }
5132 if (!writer->WriteUFloat16(ack_delay_time_us)) {
5133 return false;
5134 }
5135
5136 if (num_ack_blocks > 0) {
5137 if (!writer->WriteBytes(&num_ack_blocks, 1)) {
5138 return false;
5139 }
5140 }
5141
5142 // First ack block length.
5143 if (!AppendPacketNumber(ack_block_length,
5144 QuicPacketNumber(new_ack_info.first_block_length),
5145 writer)) {
5146 return false;
5147 }
5148
5149 // Ack blocks.
5150 if (num_ack_blocks > 0) {
5151 size_t num_ack_blocks_written = 0;
5152 // Append, in descending order from the largest ACKed packet, a series of
5153 // ACK blocks that represents the successfully acknoweldged packets. Each
5154 // appended gap/block length represents a descending delta from the previous
5155 // block. i.e.:
5156 // |--- length ---|--- gap ---|--- length ---|--- gap ---|--- largest ---|
5157 // For gaps larger than can be represented by a single encoded gap, a 0
5158 // length gap of the maximum is used, i.e.:
5159 // |--- length ---|--- gap ---|- 0 -|--- gap ---|--- largest ---|
5160 auto itr = frame.packets.rbegin();
5161 QuicPacketNumber previous_start = itr->min();
5162 ++itr;
5163
5164 for (;
5165 itr != frame.packets.rend() && num_ack_blocks_written < num_ack_blocks;
5166 previous_start = itr->min(), ++itr) {
5167 const auto& interval = *itr;
5168 const uint64_t total_gap = previous_start - interval.max();
5169 const size_t num_encoded_gaps =
5170 (total_gap + std::numeric_limits<uint8_t>::max() - 1) /
5171 std::numeric_limits<uint8_t>::max();
QUICHE teama6ef0a62019-03-07 20:34:33 -05005172
5173 // Append empty ACK blocks because the gap is longer than a single gap.
5174 for (size_t i = 1;
5175 i < num_encoded_gaps && num_ack_blocks_written < num_ack_blocks;
5176 ++i) {
5177 if (!AppendAckBlock(std::numeric_limits<uint8_t>::max(),
5178 ack_block_length, 0, writer)) {
5179 return false;
5180 }
5181 ++num_ack_blocks_written;
5182 }
5183 if (num_ack_blocks_written >= num_ack_blocks) {
5184 if (QUIC_PREDICT_FALSE(num_ack_blocks_written != num_ack_blocks)) {
5185 QUIC_BUG << "Wrote " << num_ack_blocks_written
5186 << ", expected to write " << num_ack_blocks;
5187 }
5188 break;
5189 }
5190
5191 const uint8_t last_gap =
5192 total_gap -
5193 (num_encoded_gaps - 1) * std::numeric_limits<uint8_t>::max();
5194 // Append the final ACK block with a non-empty size.
5195 if (!AppendAckBlock(last_gap, ack_block_length,
5196 PacketNumberIntervalLength(interval), writer)) {
5197 return false;
5198 }
5199 ++num_ack_blocks_written;
5200 }
5201 DCHECK_EQ(num_ack_blocks, num_ack_blocks_written);
5202 }
5203 // Timestamps.
5204 // If we don't process timestamps or if we don't have enough available space
5205 // to append all the timestamps, don't append any of them.
5206 if (process_timestamps_ && writer->capacity() - writer->length() >=
5207 GetAckFrameTimeStampSize(frame)) {
5208 if (!AppendTimestampsToAckFrame(frame, writer)) {
5209 return false;
5210 }
5211 } else {
5212 uint8_t num_received_packets = 0;
5213 if (!writer->WriteBytes(&num_received_packets, 1)) {
5214 return false;
5215 }
5216 }
5217
5218 return true;
5219}
5220
5221bool QuicFramer::AppendTimestampsToAckFrame(const QuicAckFrame& frame,
5222 QuicDataWriter* writer) {
5223 DCHECK_GE(std::numeric_limits<uint8_t>::max(),
5224 frame.received_packet_times.size());
5225 // num_received_packets is only 1 byte.
5226 if (frame.received_packet_times.size() >
5227 std::numeric_limits<uint8_t>::max()) {
5228 return false;
5229 }
5230
5231 uint8_t num_received_packets = frame.received_packet_times.size();
5232 if (!writer->WriteBytes(&num_received_packets, 1)) {
5233 return false;
5234 }
5235 if (num_received_packets == 0) {
5236 return true;
5237 }
5238
5239 auto it = frame.received_packet_times.begin();
5240 QuicPacketNumber packet_number = it->first;
5241 uint64_t delta_from_largest_observed = LargestAcked(frame) - packet_number;
5242
5243 DCHECK_GE(std::numeric_limits<uint8_t>::max(), delta_from_largest_observed);
5244 if (delta_from_largest_observed > std::numeric_limits<uint8_t>::max()) {
5245 return false;
5246 }
5247
5248 if (!writer->WriteUInt8(delta_from_largest_observed)) {
5249 return false;
5250 }
5251
5252 // Use the lowest 4 bytes of the time delta from the creation_time_.
5253 const uint64_t time_epoch_delta_us = UINT64_C(1) << 32;
5254 uint32_t time_delta_us =
5255 static_cast<uint32_t>((it->second - creation_time_).ToMicroseconds() &
5256 (time_epoch_delta_us - 1));
5257 if (!writer->WriteUInt32(time_delta_us)) {
5258 return false;
5259 }
5260
5261 QuicTime prev_time = it->second;
5262
5263 for (++it; it != frame.received_packet_times.end(); ++it) {
5264 packet_number = it->first;
5265 delta_from_largest_observed = LargestAcked(frame) - packet_number;
5266
5267 if (delta_from_largest_observed > std::numeric_limits<uint8_t>::max()) {
5268 return false;
5269 }
5270
5271 if (!writer->WriteUInt8(delta_from_largest_observed)) {
5272 return false;
5273 }
5274
5275 uint64_t frame_time_delta_us = (it->second - prev_time).ToMicroseconds();
5276 prev_time = it->second;
5277 if (!writer->WriteUFloat16(frame_time_delta_us)) {
5278 return false;
5279 }
5280 }
5281 return true;
5282}
5283
5284bool QuicFramer::AppendStopWaitingFrame(const QuicPacketHeader& header,
5285 const QuicStopWaitingFrame& frame,
5286 QuicDataWriter* writer) {
fayangd4291e42019-05-30 10:31:21 -07005287 DCHECK(!VersionHasIetfInvariantHeader(version_.transport_version));
QUICHE teama6ef0a62019-03-07 20:34:33 -05005288 DCHECK(frame.least_unacked.IsInitialized() &&
5289 header.packet_number >= frame.least_unacked);
5290 const uint64_t least_unacked_delta =
5291 header.packet_number - frame.least_unacked;
5292 const uint64_t length_shift = header.packet_number_length * 8;
5293
5294 if (least_unacked_delta >> length_shift > 0) {
5295 QUIC_BUG << "packet_number_length " << header.packet_number_length
5296 << " is too small for least_unacked_delta: " << least_unacked_delta
5297 << " packet_number:" << header.packet_number
5298 << " least_unacked:" << frame.least_unacked
5299 << " version:" << version_.transport_version;
5300 return false;
5301 }
5302 if (least_unacked_delta == 0) {
5303 return writer->WriteBytesToUInt64(header.packet_number_length,
5304 least_unacked_delta);
5305 }
5306 if (!AppendPacketNumber(header.packet_number_length,
5307 QuicPacketNumber(least_unacked_delta), writer)) {
5308 QUIC_BUG << " seq failed: " << header.packet_number_length;
5309 return false;
5310 }
5311
5312 return true;
5313}
5314
5315int QuicFramer::CalculateIetfAckBlockCount(const QuicAckFrame& frame,
dschinazi17d42422019-06-18 16:35:07 -07005316 QuicDataWriter* /*writer*/,
QUICHE teama6ef0a62019-03-07 20:34:33 -05005317 size_t available_space) {
5318 // Number of blocks requested in the frame
5319 uint64_t ack_block_count = frame.packets.NumIntervals();
5320
5321 auto itr = frame.packets.rbegin();
5322
5323 int actual_block_count = 1;
5324 uint64_t block_length = itr->max() - itr->min();
5325 size_t encoded_size = QuicDataWriter::GetVarInt62Len(block_length);
5326 if (encoded_size > available_space) {
5327 return 0;
5328 }
5329 available_space -= encoded_size;
5330 QuicPacketNumber previous_ack_end = itr->min();
5331 ack_block_count--;
5332
5333 while (ack_block_count) {
5334 // Each block is a gap followed by another ACK. Calculate each value,
5335 // determine the encoded lengths, and check against the available space.
5336 itr++;
5337 size_t gap = previous_ack_end - itr->max() - 1;
5338 encoded_size = QuicDataWriter::GetVarInt62Len(gap);
5339
5340 // Add the ACK block.
5341 block_length = itr->max() - itr->min();
5342 encoded_size += QuicDataWriter::GetVarInt62Len(block_length);
5343
5344 if (encoded_size > available_space) {
5345 // No room for this block, so what we've
5346 // done up to now is all that can be done.
5347 return actual_block_count;
5348 }
5349 available_space -= encoded_size;
5350 actual_block_count++;
5351 previous_ack_end = itr->min();
5352 ack_block_count--;
5353 }
5354 // Ran through the whole thing! We can do all blocks.
5355 return actual_block_count;
5356}
5357
5358bool QuicFramer::AppendIetfAckFrameAndTypeByte(const QuicAckFrame& frame,
5359 QuicDataWriter* writer) {
5360 // Assume frame is an IETF_ACK frame. If |ecn_counters_populated| is true and
5361 // any of the ECN counters is non-0 then turn it into an IETF_ACK+ECN frame.
5362 uint8_t type = IETF_ACK;
5363 if (frame.ecn_counters_populated &&
5364 (frame.ect_0_count || frame.ect_1_count || frame.ecn_ce_count)) {
5365 type = IETF_ACK_ECN;
5366 }
5367
5368 if (!writer->WriteUInt8(type)) {
5369 set_detailed_error("No room for frame-type");
5370 return false;
5371 }
5372
5373 QuicPacketNumber largest_acked = LargestAcked(frame);
5374 if (!writer->WriteVarInt62(largest_acked.ToUint64())) {
5375 set_detailed_error("No room for largest-acked in ack frame");
5376 return false;
5377 }
5378
5379 uint64_t ack_delay_time_us = kVarInt62MaxValue;
5380 if (!frame.ack_delay_time.IsInfinite()) {
5381 DCHECK_LE(0u, frame.ack_delay_time.ToMicroseconds());
5382 ack_delay_time_us = frame.ack_delay_time.ToMicroseconds();
5383 // TODO(fkastenholz): Use the shift from TLS transport parameters.
5384 ack_delay_time_us = ack_delay_time_us >> kIetfAckTimestampShift;
5385 }
5386
5387 if (!writer->WriteVarInt62(ack_delay_time_us)) {
5388 set_detailed_error("No room for ack-delay in ack frame");
5389 return false;
5390 }
5391 if (type == IETF_ACK_ECN) {
5392 // Encode the ACK ECN fields
5393 if (!writer->WriteVarInt62(frame.ect_0_count)) {
5394 set_detailed_error("No room for ect_0_count in ack frame");
5395 return false;
5396 }
5397 if (!writer->WriteVarInt62(frame.ect_1_count)) {
5398 set_detailed_error("No room for ect_1_count in ack frame");
5399 return false;
5400 }
5401 if (!writer->WriteVarInt62(frame.ecn_ce_count)) {
5402 set_detailed_error("No room for ecn_ce_count in ack frame");
5403 return false;
5404 }
5405 }
5406
5407 uint64_t ack_block_count = frame.packets.NumIntervals();
5408 if (ack_block_count == 0) {
5409 // If the QuicAckFrame has no Intervals, then it is interpreted
5410 // as an ack of a single packet at QuicAckFrame.largest_acked.
5411 // The resulting ack will consist of only the frame's
5412 // largest_ack & first_ack_block fields. The first ack block will be 0
5413 // (indicating a single packet) and the ack block_count will be 0.
5414 if (!writer->WriteVarInt62(0)) {
5415 set_detailed_error("No room for ack block count in ack frame");
5416 return false;
5417 }
5418 // size of the first block is 1 packet
5419 if (!writer->WriteVarInt62(0)) {
5420 set_detailed_error("No room for first ack block in ack frame");
5421 return false;
5422 }
5423 return true;
5424 }
5425 // Case 2 or 3
5426 auto itr = frame.packets.rbegin();
5427
5428 QuicPacketNumber ack_block_largest(largest_acked);
5429 QuicPacketNumber ack_block_smallest;
5430 if ((itr->max() - 1) == QuicPacketNumber(largest_acked)) {
5431 // If largest_acked + 1 is equal to the Max() of the first Interval
5432 // in the QuicAckFrame then the first Interval is the first ack block of the
5433 // frame; remaining Intervals are additional ack blocks. The QuicAckFrame's
5434 // first Interval is encoded in the frame's largest_acked/first_ack_block,
5435 // the remaining Intervals are encoded in additional ack blocks in the
5436 // frame, and the packet's ack_block_count is the number of QuicAckFrame
5437 // Intervals - 1.
5438 ack_block_smallest = itr->min();
5439 itr++;
5440 ack_block_count--;
5441 } else {
5442 // If QuicAckFrame.largest_acked is NOT equal to the Max() of
5443 // the first Interval then it is interpreted as acking a single
5444 // packet at QuicAckFrame.largest_acked, with additional
5445 // Intervals indicating additional ack blocks. The encoding is
5446 // a) The packet's largest_acked is the QuicAckFrame's largest
5447 // acked,
5448 // b) the first ack block size is 0,
5449 // c) The packet's ack_block_count is the number of QuicAckFrame
5450 // Intervals, and
5451 // d) The QuicAckFrame Intervals are encoded in additional ack
5452 // blocks in the packet.
5453 ack_block_smallest = largest_acked;
5454 }
5455
5456 if (!writer->WriteVarInt62(ack_block_count)) {
5457 set_detailed_error("No room for ack block count in ack frame");
5458 return false;
5459 }
5460
5461 uint64_t first_ack_block = ack_block_largest - ack_block_smallest;
5462 if (!writer->WriteVarInt62(first_ack_block)) {
5463 set_detailed_error("No room for first ack block in ack frame");
5464 return false;
5465 }
5466
5467 // For the remaining QuicAckFrame Intervals, if any
5468 while (ack_block_count != 0) {
5469 uint64_t gap_size = ack_block_smallest - itr->max();
5470 if (!writer->WriteVarInt62(gap_size - 1)) {
5471 set_detailed_error("No room for gap block in ack frame");
5472 return false;
5473 }
5474
5475 uint64_t block_size = itr->max() - itr->min();
5476 if (!writer->WriteVarInt62(block_size - 1)) {
5477 set_detailed_error("No room for nth ack block in ack frame");
5478 return false;
5479 }
5480
5481 ack_block_smallest = itr->min();
5482 itr++;
5483 ack_block_count--;
5484 }
5485 return true;
5486}
5487
5488bool QuicFramer::AppendRstStreamFrame(const QuicRstStreamFrame& frame,
5489 QuicDataWriter* writer) {
fkastenholz305e1732019-06-18 05:01:22 -07005490 if (VersionHasIetfQuicFrames(version_.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005491 return AppendIetfResetStreamFrame(frame, writer);
5492 }
5493 if (!writer->WriteUInt32(frame.stream_id)) {
5494 return false;
5495 }
5496
5497 if (!writer->WriteUInt64(frame.byte_offset)) {
5498 return false;
5499 }
5500
5501 uint32_t error_code = static_cast<uint32_t>(frame.error_code);
5502 if (!writer->WriteUInt32(error_code)) {
5503 return false;
5504 }
5505
5506 return true;
5507}
5508
5509bool QuicFramer::AppendConnectionCloseFrame(
5510 const QuicConnectionCloseFrame& frame,
5511 QuicDataWriter* writer) {
fkastenholz305e1732019-06-18 05:01:22 -07005512 if (VersionHasIetfQuicFrames(version_.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005513 return AppendIetfConnectionCloseFrame(frame, writer);
5514 }
fkastenholze9d71a82019-04-09 05:12:13 -07005515 uint32_t error_code = static_cast<uint32_t>(frame.quic_error_code);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005516 if (!writer->WriteUInt32(error_code)) {
5517 return false;
5518 }
5519 if (!writer->WriteStringPiece16(TruncateErrorString(frame.error_details))) {
5520 return false;
5521 }
5522 return true;
5523}
5524
5525bool QuicFramer::AppendGoAwayFrame(const QuicGoAwayFrame& frame,
5526 QuicDataWriter* writer) {
5527 uint32_t error_code = static_cast<uint32_t>(frame.error_code);
5528 if (!writer->WriteUInt32(error_code)) {
5529 return false;
5530 }
5531 uint32_t stream_id = static_cast<uint32_t>(frame.last_good_stream_id);
5532 if (!writer->WriteUInt32(stream_id)) {
5533 return false;
5534 }
5535 if (!writer->WriteStringPiece16(TruncateErrorString(frame.reason_phrase))) {
5536 return false;
5537 }
5538 return true;
5539}
5540
5541bool QuicFramer::AppendWindowUpdateFrame(const QuicWindowUpdateFrame& frame,
5542 QuicDataWriter* writer) {
5543 uint32_t stream_id = static_cast<uint32_t>(frame.stream_id);
5544 if (!writer->WriteUInt32(stream_id)) {
5545 return false;
5546 }
5547 if (!writer->WriteUInt64(frame.byte_offset)) {
5548 return false;
5549 }
5550 return true;
5551}
5552
5553bool QuicFramer::AppendBlockedFrame(const QuicBlockedFrame& frame,
5554 QuicDataWriter* writer) {
fkastenholz305e1732019-06-18 05:01:22 -07005555 if (VersionHasIetfQuicFrames(version_.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005556 if (frame.stream_id == QuicUtils::GetInvalidStreamId(transport_version())) {
5557 return AppendIetfBlockedFrame(frame, writer);
5558 }
5559 return AppendStreamBlockedFrame(frame, writer);
5560 }
5561 uint32_t stream_id = static_cast<uint32_t>(frame.stream_id);
5562 if (!writer->WriteUInt32(stream_id)) {
5563 return false;
5564 }
5565 return true;
5566}
5567
5568bool QuicFramer::AppendPaddingFrame(const QuicPaddingFrame& frame,
5569 QuicDataWriter* writer) {
5570 if (frame.num_padding_bytes == 0) {
5571 return false;
5572 }
5573 if (frame.num_padding_bytes < 0) {
5574 QUIC_BUG_IF(frame.num_padding_bytes != -1);
5575 writer->WritePadding();
5576 return true;
5577 }
5578 // Please note, num_padding_bytes includes type byte which has been written.
5579 return writer->WritePaddingBytes(frame.num_padding_bytes - 1);
5580}
5581
5582bool QuicFramer::AppendMessageFrameAndTypeByte(const QuicMessageFrame& frame,
5583 bool last_frame_in_packet,
5584 QuicDataWriter* writer) {
5585 uint8_t type_byte = last_frame_in_packet ? IETF_EXTENSION_MESSAGE_NO_LENGTH
5586 : IETF_EXTENSION_MESSAGE;
5587 if (!writer->WriteUInt8(type_byte)) {
5588 return false;
5589 }
5590 if (!last_frame_in_packet && !writer->WriteVarInt62(frame.message_length)) {
5591 return false;
5592 }
5593 for (const auto& slice : frame.message_data) {
5594 if (!writer->WriteBytes(slice.data(), slice.length())) {
5595 return false;
5596 }
5597 }
5598 return true;
5599}
5600
5601bool QuicFramer::RaiseError(QuicErrorCode error) {
5602 QUIC_DLOG(INFO) << ENDPOINT << "Error: " << QuicErrorCodeToString(error)
5603 << " detail: " << detailed_error_;
5604 set_error(error);
nharper55fa6132019-05-07 19:37:21 -07005605 if (visitor_) {
5606 visitor_->OnError(this);
5607 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05005608 return false;
5609}
5610
5611bool QuicFramer::IsVersionNegotiation(
5612 const QuicPacketHeader& header,
5613 bool packet_has_ietf_packet_header) const {
dschinazi072da7c2019-05-07 17:57:42 -07005614 if (!packet_has_ietf_packet_header &&
5615 perspective_ == Perspective::IS_CLIENT) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005616 return header.version_flag;
5617 }
5618 if (header.form == IETF_QUIC_SHORT_HEADER_PACKET) {
5619 return false;
5620 }
5621 return header.long_packet_type == VERSION_NEGOTIATION;
5622}
5623
QUICHE teama6ef0a62019-03-07 20:34:33 -05005624bool QuicFramer::AppendIetfConnectionCloseFrame(
5625 const QuicConnectionCloseFrame& frame,
5626 QuicDataWriter* writer) {
fkastenholz72f509b2019-04-10 09:17:49 -07005627 if (frame.close_type != IETF_QUIC_TRANSPORT_CONNECTION_CLOSE &&
5628 frame.close_type != IETF_QUIC_APPLICATION_CONNECTION_CLOSE) {
5629 QUIC_BUG << "Invalid close_type for writing IETF CONNECTION CLOSE.";
5630 set_detailed_error("Invalid close_type for writing IETF CONNECTION CLOSE.");
5631 return false;
5632 }
5633
fkastenholze9d71a82019-04-09 05:12:13 -07005634 if (!writer->WriteUInt16(frame.application_error_code)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005635 set_detailed_error("Can not write connection close frame error code");
5636 return false;
5637 }
fkastenholze9d71a82019-04-09 05:12:13 -07005638
fkastenholz72f509b2019-04-10 09:17:49 -07005639 if (frame.close_type == IETF_QUIC_TRANSPORT_CONNECTION_CLOSE) {
5640 // Write the frame-type of the frame causing the error only
5641 // if it's a CONNECTION_CLOSE/Transport.
5642 if (!writer->WriteVarInt62(frame.transport_close_frame_type)) {
5643 set_detailed_error("Writing frame type failed.");
5644 return false;
5645 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05005646 }
5647
fkastenholz72f509b2019-04-10 09:17:49 -07005648 // TODO(fkastenholz): For full IETF CONNECTION CLOSE support,
5649 // if this is a Transport CONNECTION_CLOSE and the extended
5650 // error is not QUIC_IETF_GQUIC_ERROR_MISSING then append the extended
5651 // "QuicErrorCode: #" string to the phrase.
QUICHE teama6ef0a62019-03-07 20:34:33 -05005652 if (!writer->WriteStringPieceVarInt62(
5653 TruncateErrorString(frame.error_details))) {
5654 set_detailed_error("Can not write connection close phrase");
5655 return false;
5656 }
5657 return true;
5658}
5659
QUICHE teama6ef0a62019-03-07 20:34:33 -05005660bool QuicFramer::ProcessIetfConnectionCloseFrame(
5661 QuicDataReader* reader,
fkastenholze9d71a82019-04-09 05:12:13 -07005662 QuicConnectionCloseType type,
QUICHE teama6ef0a62019-03-07 20:34:33 -05005663 QuicConnectionCloseFrame* frame) {
fkastenholze9d71a82019-04-09 05:12:13 -07005664 frame->close_type = type;
QUICHE teama6ef0a62019-03-07 20:34:33 -05005665 uint16_t code;
5666 if (!reader->ReadUInt16(&code)) {
5667 set_detailed_error("Unable to read connection close error code.");
5668 return false;
5669 }
fkastenholze9d71a82019-04-09 05:12:13 -07005670 frame->transport_error_code = static_cast<QuicIetfTransportErrorCodes>(code);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005671
fkastenholz72f509b2019-04-10 09:17:49 -07005672 if (type == IETF_QUIC_TRANSPORT_CONNECTION_CLOSE) {
5673 // The frame-type of the frame causing the error is present only
5674 // if it's a CONNECTION_CLOSE/Transport.
5675 if (!reader->ReadVarInt62(&frame->transport_close_frame_type)) {
5676 set_detailed_error("Unable to read connection close frame type.");
5677 return false;
5678 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05005679 }
5680
5681 uint64_t phrase_length;
5682 if (!reader->ReadVarInt62(&phrase_length)) {
5683 set_detailed_error("Unable to read connection close error details.");
5684 return false;
5685 }
5686 QuicStringPiece phrase;
5687 if (!reader->ReadStringPiece(&phrase, static_cast<size_t>(phrase_length))) {
5688 set_detailed_error("Unable to read connection close error details.");
5689 return false;
5690 }
fkastenholz72f509b2019-04-10 09:17:49 -07005691 // TODO(fkastenholz): when full support is done, add code here
5692 // to extract the extended error code from the reason phrase
5693 // and set it into frame->extracted_error_code.
vasilvvc48c8712019-03-11 13:38:16 -07005694 frame->error_details = std::string(phrase);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005695
5696 return true;
5697}
5698
5699// IETF Quic Path Challenge/Response frames.
5700bool QuicFramer::ProcessPathChallengeFrame(QuicDataReader* reader,
5701 QuicPathChallengeFrame* frame) {
5702 if (!reader->ReadBytes(frame->data_buffer.data(),
5703 frame->data_buffer.size())) {
5704 set_detailed_error("Can not read path challenge data.");
5705 return false;
5706 }
5707 return true;
5708}
5709
5710bool QuicFramer::ProcessPathResponseFrame(QuicDataReader* reader,
5711 QuicPathResponseFrame* frame) {
5712 if (!reader->ReadBytes(frame->data_buffer.data(),
5713 frame->data_buffer.size())) {
5714 set_detailed_error("Can not read path response data.");
5715 return false;
5716 }
5717 return true;
5718}
5719
5720bool QuicFramer::AppendPathChallengeFrame(const QuicPathChallengeFrame& frame,
5721 QuicDataWriter* writer) {
5722 if (!writer->WriteBytes(frame.data_buffer.data(), frame.data_buffer.size())) {
5723 set_detailed_error("Writing Path Challenge data failed.");
5724 return false;
5725 }
5726 return true;
5727}
5728
5729bool QuicFramer::AppendPathResponseFrame(const QuicPathResponseFrame& frame,
5730 QuicDataWriter* writer) {
5731 if (!writer->WriteBytes(frame.data_buffer.data(), frame.data_buffer.size())) {
5732 set_detailed_error("Writing Path Response data failed.");
5733 return false;
5734 }
5735 return true;
5736}
5737
5738// Add a new ietf-format stream reset frame.
5739// General format is
5740// stream id
5741// application error code
5742// final offset
5743bool QuicFramer::AppendIetfResetStreamFrame(const QuicRstStreamFrame& frame,
5744 QuicDataWriter* writer) {
5745 if (!writer->WriteVarInt62(static_cast<uint64_t>(frame.stream_id))) {
5746 set_detailed_error("Writing reset-stream stream id failed.");
5747 return false;
5748 }
5749 if (!writer->WriteUInt16(frame.ietf_error_code)) {
5750 set_detailed_error("Writing reset-stream error code failed.");
5751 return false;
5752 }
5753 if (!writer->WriteVarInt62(static_cast<uint64_t>(frame.byte_offset))) {
5754 set_detailed_error("Writing reset-stream final-offset failed.");
5755 return false;
5756 }
5757 return true;
5758}
5759
5760bool QuicFramer::ProcessIetfResetStreamFrame(QuicDataReader* reader,
5761 QuicRstStreamFrame* frame) {
5762 // Get Stream ID from frame. ReadVarIntStreamID returns false
5763 // if either A) there is a read error or B) the resulting value of
5764 // the Stream ID is larger than the maximum allowed value.
fkastenholz3c4eabf2019-04-22 07:49:59 -07005765 if (!reader->ReadVarIntU32(&frame->stream_id)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005766 set_detailed_error("Unable to read rst stream stream id.");
5767 return false;
5768 }
5769
5770 if (!reader->ReadUInt16(&frame->ietf_error_code)) {
5771 set_detailed_error("Unable to read rst stream error code.");
5772 return false;
5773 }
5774
5775 if (!reader->ReadVarInt62(&frame->byte_offset)) {
5776 set_detailed_error("Unable to read rst stream sent byte offset.");
5777 return false;
5778 }
5779 return true;
5780}
5781
5782bool QuicFramer::ProcessStopSendingFrame(
5783 QuicDataReader* reader,
5784 QuicStopSendingFrame* stop_sending_frame) {
fkastenholz3c4eabf2019-04-22 07:49:59 -07005785 if (!reader->ReadVarIntU32(&stop_sending_frame->stream_id)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005786 set_detailed_error("Unable to read stop sending stream id.");
5787 return false;
5788 }
5789
5790 if (!reader->ReadUInt16(&stop_sending_frame->application_error_code)) {
5791 set_detailed_error("Unable to read stop sending application error code.");
5792 return false;
5793 }
5794 return true;
5795}
5796
5797bool QuicFramer::AppendStopSendingFrame(
5798 const QuicStopSendingFrame& stop_sending_frame,
5799 QuicDataWriter* writer) {
5800 if (!writer->WriteVarInt62(stop_sending_frame.stream_id)) {
5801 set_detailed_error("Can not write stop sending stream id");
5802 return false;
5803 }
5804 if (!writer->WriteUInt16(stop_sending_frame.application_error_code)) {
5805 set_detailed_error("Can not write application error code");
5806 return false;
5807 }
5808 return true;
5809}
5810
5811// Append/process IETF-Format MAX_DATA Frame
5812bool QuicFramer::AppendMaxDataFrame(const QuicWindowUpdateFrame& frame,
5813 QuicDataWriter* writer) {
5814 if (!writer->WriteVarInt62(frame.byte_offset)) {
5815 set_detailed_error("Can not write MAX_DATA byte-offset");
5816 return false;
5817 }
5818 return true;
5819}
5820
5821bool QuicFramer::ProcessMaxDataFrame(QuicDataReader* reader,
5822 QuicWindowUpdateFrame* frame) {
5823 frame->stream_id = QuicUtils::GetInvalidStreamId(transport_version());
5824 if (!reader->ReadVarInt62(&frame->byte_offset)) {
5825 set_detailed_error("Can not read MAX_DATA byte-offset");
5826 return false;
5827 }
5828 return true;
5829}
5830
5831// Append/process IETF-Format MAX_STREAM_DATA Frame
5832bool QuicFramer::AppendMaxStreamDataFrame(const QuicWindowUpdateFrame& frame,
5833 QuicDataWriter* writer) {
5834 if (!writer->WriteVarInt62(frame.stream_id)) {
5835 set_detailed_error("Can not write MAX_STREAM_DATA stream id");
5836 return false;
5837 }
5838 if (!writer->WriteVarInt62(frame.byte_offset)) {
5839 set_detailed_error("Can not write MAX_STREAM_DATA byte-offset");
5840 return false;
5841 }
5842 return true;
5843}
5844
5845bool QuicFramer::ProcessMaxStreamDataFrame(QuicDataReader* reader,
5846 QuicWindowUpdateFrame* frame) {
fkastenholz3c4eabf2019-04-22 07:49:59 -07005847 if (!reader->ReadVarIntU32(&frame->stream_id)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005848 set_detailed_error("Can not read MAX_STREAM_DATA stream id");
5849 return false;
5850 }
5851 if (!reader->ReadVarInt62(&frame->byte_offset)) {
5852 set_detailed_error("Can not read MAX_STREAM_DATA byte-count");
5853 return false;
5854 }
5855 return true;
5856}
5857
fkastenholz3c4eabf2019-04-22 07:49:59 -07005858bool QuicFramer::AppendMaxStreamsFrame(const QuicMaxStreamsFrame& frame,
QUICHE teama6ef0a62019-03-07 20:34:33 -05005859 QuicDataWriter* writer) {
fkastenholz3c4eabf2019-04-22 07:49:59 -07005860 if (!writer->WriteVarInt62(frame.stream_count)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005861 set_detailed_error("Can not write MAX_STREAMS stream count");
5862 return false;
5863 }
5864 return true;
5865}
5866
5867bool QuicFramer::ProcessMaxStreamsFrame(QuicDataReader* reader,
fkastenholz3c4eabf2019-04-22 07:49:59 -07005868 QuicMaxStreamsFrame* frame,
QUICHE teama6ef0a62019-03-07 20:34:33 -05005869 uint64_t frame_type) {
fkastenholz3c4eabf2019-04-22 07:49:59 -07005870 if (!reader->ReadVarIntU32(&frame->stream_count)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005871 set_detailed_error("Can not read MAX_STREAMS stream count.");
5872 return false;
5873 }
fkastenholz3c4eabf2019-04-22 07:49:59 -07005874 frame->unidirectional = (frame_type == IETF_MAX_STREAMS_UNIDIRECTIONAL);
5875 return true;
QUICHE teama6ef0a62019-03-07 20:34:33 -05005876}
5877
5878bool QuicFramer::AppendIetfBlockedFrame(const QuicBlockedFrame& frame,
5879 QuicDataWriter* writer) {
5880 if (!writer->WriteVarInt62(frame.offset)) {
5881 set_detailed_error("Can not write blocked offset.");
5882 return false;
5883 }
5884 return true;
5885}
5886
5887bool QuicFramer::ProcessIetfBlockedFrame(QuicDataReader* reader,
5888 QuicBlockedFrame* frame) {
5889 // Indicates that it is a BLOCKED frame (as opposed to STREAM_BLOCKED).
5890 frame->stream_id = QuicUtils::GetInvalidStreamId(transport_version());
5891 if (!reader->ReadVarInt62(&frame->offset)) {
5892 set_detailed_error("Can not read blocked offset.");
5893 return false;
5894 }
5895 return true;
5896}
5897
5898bool QuicFramer::AppendStreamBlockedFrame(const QuicBlockedFrame& frame,
5899 QuicDataWriter* writer) {
5900 if (!writer->WriteVarInt62(frame.stream_id)) {
5901 set_detailed_error("Can not write stream blocked stream id.");
5902 return false;
5903 }
5904 if (!writer->WriteVarInt62(frame.offset)) {
5905 set_detailed_error("Can not write stream blocked offset.");
5906 return false;
5907 }
5908 return true;
5909}
5910
5911bool QuicFramer::ProcessStreamBlockedFrame(QuicDataReader* reader,
5912 QuicBlockedFrame* frame) {
fkastenholz3c4eabf2019-04-22 07:49:59 -07005913 if (!reader->ReadVarIntU32(&frame->stream_id)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005914 set_detailed_error("Can not read stream blocked stream id.");
5915 return false;
5916 }
5917 if (!reader->ReadVarInt62(&frame->offset)) {
5918 set_detailed_error("Can not read stream blocked offset.");
5919 return false;
5920 }
5921 return true;
5922}
5923
fkastenholz3c4eabf2019-04-22 07:49:59 -07005924bool QuicFramer::AppendStreamsBlockedFrame(const QuicStreamsBlockedFrame& frame,
5925 QuicDataWriter* writer) {
5926 if (!writer->WriteVarInt62(frame.stream_count)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005927 set_detailed_error("Can not write STREAMS_BLOCKED stream count");
5928 return false;
5929 }
5930 return true;
5931}
5932
5933bool QuicFramer::ProcessStreamsBlockedFrame(QuicDataReader* reader,
fkastenholz3c4eabf2019-04-22 07:49:59 -07005934 QuicStreamsBlockedFrame* frame,
QUICHE teama6ef0a62019-03-07 20:34:33 -05005935 uint64_t frame_type) {
fkastenholz3c4eabf2019-04-22 07:49:59 -07005936 if (!reader->ReadVarIntU32(&frame->stream_count)) {
5937 set_detailed_error("Can not read STREAMS_BLOCKED stream count.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05005938 return false;
5939 }
fkastenholz3c4eabf2019-04-22 07:49:59 -07005940 frame->unidirectional = (frame_type == IETF_STREAMS_BLOCKED_UNIDIRECTIONAL);
5941
QUICHE teama6ef0a62019-03-07 20:34:33 -05005942 // TODO(fkastenholz): handle properly when the STREAMS_BLOCKED
5943 // frame is implemented and passed up to the stream ID manager.
fkastenholz3c4eabf2019-04-22 07:49:59 -07005944 if (frame->stream_count >
5945 QuicUtils::GetMaxStreamCount(
5946 (frame_type == IETF_STREAMS_BLOCKED_UNIDIRECTIONAL),
5947 ((perspective_ == Perspective::IS_CLIENT)
5948 ? Perspective::IS_SERVER
5949 : Perspective::IS_CLIENT))) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005950 // If stream count is such that the resulting stream ID would exceed our
5951 // implementation limit, generate an error.
5952 set_detailed_error(
5953 "STREAMS_BLOCKED stream count exceeds implementation limit.");
5954 return false;
5955 }
fkastenholz3c4eabf2019-04-22 07:49:59 -07005956 return true;
QUICHE teama6ef0a62019-03-07 20:34:33 -05005957}
5958
5959bool QuicFramer::AppendNewConnectionIdFrame(
5960 const QuicNewConnectionIdFrame& frame,
5961 QuicDataWriter* writer) {
5962 if (!writer->WriteVarInt62(frame.sequence_number)) {
5963 set_detailed_error("Can not write New Connection ID sequence number");
5964 return false;
5965 }
5966 if (!writer->WriteUInt8(frame.connection_id.length())) {
5967 set_detailed_error(
5968 "Can not write New Connection ID frame connection ID Length");
5969 return false;
5970 }
5971 if (!writer->WriteConnectionId(frame.connection_id)) {
5972 set_detailed_error("Can not write New Connection ID frame connection ID");
5973 return false;
5974 }
5975
5976 if (!writer->WriteBytes(
5977 static_cast<const void*>(&frame.stateless_reset_token),
5978 sizeof(frame.stateless_reset_token))) {
5979 set_detailed_error("Can not write New Connection ID Reset Token");
5980 return false;
5981 }
5982 return true;
5983}
5984
5985bool QuicFramer::ProcessNewConnectionIdFrame(QuicDataReader* reader,
5986 QuicNewConnectionIdFrame* frame) {
5987 if (!reader->ReadVarInt62(&frame->sequence_number)) {
5988 set_detailed_error(
5989 "Unable to read new connection ID frame sequence number.");
5990 return false;
5991 }
5992
5993 uint8_t connection_id_length;
5994 if (!reader->ReadUInt8(&connection_id_length)) {
5995 set_detailed_error(
5996 "Unable to read new connection ID frame connection id length.");
5997 return false;
5998 }
5999
QUICHE team0131a5b2019-03-20 15:23:27 -07006000 if (connection_id_length > kQuicMaxConnectionIdLength) {
6001 set_detailed_error("New connection ID length too high.");
6002 return false;
6003 }
6004
QUICHE team8e2e4532019-03-14 14:37:56 -07006005 if (connection_id_length != kQuicDefaultConnectionIdLength &&
6006 !QuicUtils::VariableLengthConnectionIdAllowedForVersion(
6007 transport_version())) {
QUICHE team0131a5b2019-03-20 15:23:27 -07006008 set_detailed_error("Invalid new connection ID length for version.");
QUICHE teama6ef0a62019-03-07 20:34:33 -05006009 return false;
6010 }
6011
6012 if (!reader->ReadConnectionId(&frame->connection_id, connection_id_length)) {
6013 set_detailed_error("Unable to read new connection ID frame connection id.");
6014 return false;
6015 }
6016
6017 if (!reader->ReadBytes(&frame->stateless_reset_token,
6018 sizeof(frame->stateless_reset_token))) {
6019 set_detailed_error("Can not read new connection ID frame reset token.");
6020 return false;
6021 }
6022 return true;
6023}
6024
6025bool QuicFramer::AppendRetireConnectionIdFrame(
6026 const QuicRetireConnectionIdFrame& frame,
6027 QuicDataWriter* writer) {
6028 if (!writer->WriteVarInt62(frame.sequence_number)) {
6029 set_detailed_error("Can not write Retire Connection ID sequence number");
6030 return false;
6031 }
6032 return true;
6033}
6034
6035bool QuicFramer::ProcessRetireConnectionIdFrame(
6036 QuicDataReader* reader,
6037 QuicRetireConnectionIdFrame* frame) {
6038 if (!reader->ReadVarInt62(&frame->sequence_number)) {
6039 set_detailed_error(
6040 "Unable to read retire connection ID frame sequence number.");
6041 return false;
6042 }
6043 return true;
6044}
6045
6046uint8_t QuicFramer::GetStreamFrameTypeByte(const QuicStreamFrame& frame,
6047 bool last_frame_in_packet) const {
fkastenholz305e1732019-06-18 05:01:22 -07006048 if (VersionHasIetfQuicFrames(version_.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05006049 return GetIetfStreamFrameTypeByte(frame, last_frame_in_packet);
6050 }
6051 uint8_t type_byte = 0;
6052 // Fin bit.
6053 type_byte |= frame.fin ? kQuicStreamFinMask : 0;
6054
6055 // Data Length bit.
6056 type_byte <<= kQuicStreamDataLengthShift;
6057 type_byte |= last_frame_in_packet ? 0 : kQuicStreamDataLengthMask;
6058
6059 // Offset 3 bits.
6060 type_byte <<= kQuicStreamShift;
6061 const size_t offset_len =
6062 GetStreamOffsetSize(version_.transport_version, frame.offset);
6063 if (offset_len > 0) {
6064 type_byte |= offset_len - 1;
6065 }
6066
6067 // stream id 2 bits.
6068 type_byte <<= kQuicStreamIdShift;
6069 type_byte |= GetStreamIdSize(frame.stream_id) - 1;
6070 type_byte |= kQuicFrameTypeStreamMask; // Set Stream Frame Type to 1.
6071
6072 return type_byte;
6073}
6074
6075uint8_t QuicFramer::GetIetfStreamFrameTypeByte(
6076 const QuicStreamFrame& frame,
6077 bool last_frame_in_packet) const {
fkastenholz305e1732019-06-18 05:01:22 -07006078 DCHECK(VersionHasIetfQuicFrames(version_.transport_version));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006079 uint8_t type_byte = IETF_STREAM;
6080 if (!last_frame_in_packet) {
6081 type_byte |= IETF_STREAM_FRAME_LEN_BIT;
6082 }
6083 if (frame.offset != 0) {
6084 type_byte |= IETF_STREAM_FRAME_OFF_BIT;
6085 }
6086 if (frame.fin) {
6087 type_byte |= IETF_STREAM_FRAME_FIN_BIT;
6088 }
6089 return type_byte;
6090}
6091
6092void QuicFramer::InferPacketHeaderTypeFromVersion() {
6093 // This function should only be called when server connection negotiates the
6094 // version.
6095 DCHECK(perspective_ == Perspective::IS_SERVER &&
6096 !infer_packet_header_type_from_version_);
6097 infer_packet_header_type_from_version_ = true;
6098}
6099
QUICHE team10b22a12019-03-21 15:31:42 -07006100void QuicFramer::EnableMultiplePacketNumberSpacesSupport() {
6101 if (supports_multiple_packet_number_spaces_) {
6102 QUIC_BUG << "Multiple packet number spaces has already been enabled";
6103 return;
6104 }
6105 if (largest_packet_number_.IsInitialized()) {
6106 QUIC_BUG << "Try to enable multiple packet number spaces support after any "
6107 "packet has been received.";
6108 return;
6109 }
6110
6111 supports_multiple_packet_number_spaces_ = true;
6112}
6113
fayangccbab732019-05-13 10:11:25 -07006114// static
6115QuicErrorCode QuicFramer::ProcessPacketDispatcher(
6116 const QuicEncryptedPacket& packet,
dschinazib42a8c52019-05-30 09:45:01 -07006117 uint8_t expected_destination_connection_id_length,
fayangccbab732019-05-13 10:11:25 -07006118 PacketHeaderFormat* format,
6119 bool* version_flag,
6120 QuicVersionLabel* version_label,
fayangccbab732019-05-13 10:11:25 -07006121 QuicConnectionId* destination_connection_id,
dschinazib42a8c52019-05-30 09:45:01 -07006122 QuicConnectionId* source_connection_id,
fayangccbab732019-05-13 10:11:25 -07006123 std::string* detailed_error) {
6124 QuicDataReader reader(packet.data(), packet.length());
6125
dschinazib42a8c52019-05-30 09:45:01 -07006126 *source_connection_id = EmptyQuicConnectionId();
fayangccbab732019-05-13 10:11:25 -07006127 uint8_t first_byte;
6128 if (!reader.ReadBytes(&first_byte, 1)) {
6129 *detailed_error = "Unable to read first byte.";
6130 return QUIC_INVALID_PACKET_HEADER;
6131 }
dschinazib42a8c52019-05-30 09:45:01 -07006132 uint8_t destination_connection_id_length = 0, source_connection_id_length = 0;
fayangccbab732019-05-13 10:11:25 -07006133 if (!QuicUtils::IsIetfPacketHeader(first_byte)) {
6134 *format = GOOGLE_QUIC_PACKET;
6135 *version_flag = (first_byte & PACKET_PUBLIC_FLAGS_VERSION) != 0;
dschinazib42a8c52019-05-30 09:45:01 -07006136 destination_connection_id_length =
fayangccbab732019-05-13 10:11:25 -07006137 first_byte & PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID;
dschinazib42a8c52019-05-30 09:45:01 -07006138 if (destination_connection_id_length == 0 ||
fayangccbab732019-05-13 10:11:25 -07006139 !reader.ReadConnectionId(destination_connection_id,
dschinazib42a8c52019-05-30 09:45:01 -07006140 destination_connection_id_length)) {
fayangccbab732019-05-13 10:11:25 -07006141 *detailed_error = "Unable to read ConnectionId.";
6142 return QUIC_INVALID_PACKET_HEADER;
6143 }
6144 if (*version_flag && !ProcessVersionLabel(&reader, version_label)) {
6145 *detailed_error = "Unable to read protocol version.";
6146 return QUIC_INVALID_PACKET_HEADER;
6147 }
6148 return QUIC_NO_ERROR;
6149 }
6150
6151 *format = GetIetfPacketHeaderFormat(first_byte);
6152 QUIC_DVLOG(1) << "Dispatcher: Processing IETF QUIC packet, format: "
6153 << *format;
6154 *version_flag = *format == IETF_QUIC_LONG_HEADER_PACKET;
6155 if (*format == IETF_QUIC_LONG_HEADER_PACKET) {
6156 if (!ProcessVersionLabel(&reader, version_label)) {
6157 *detailed_error = "Unable to read protocol version.";
6158 return QUIC_INVALID_PACKET_HEADER;
6159 }
dschinazi8ff74822019-05-28 16:37:20 -07006160 // Set should_update_expected_server_connection_id_length to true to bypass
fayangccbab732019-05-13 10:11:25 -07006161 // connection ID lengths validation.
dschinazi8ff74822019-05-28 16:37:20 -07006162 uint8_t unused_expected_server_connection_id_length = 0;
fayangccbab732019-05-13 10:11:25 -07006163 if (!ProcessAndValidateIetfConnectionIdLength(
6164 &reader, ParseQuicVersionLabel(*version_label),
dschinazi334f0232019-05-29 16:08:53 -07006165 Perspective::IS_SERVER,
dschinazi8ff74822019-05-28 16:37:20 -07006166 /*should_update_expected_server_connection_id_length=*/true,
6167 &unused_expected_server_connection_id_length,
dschinazib42a8c52019-05-30 09:45:01 -07006168 &destination_connection_id_length, &source_connection_id_length,
6169 detailed_error)) {
fayangccbab732019-05-13 10:11:25 -07006170 return QUIC_INVALID_PACKET_HEADER;
6171 }
6172 } else {
dschinazib42a8c52019-05-30 09:45:01 -07006173 // For short header packets, expected_destination_connection_id_length
6174 // is used to determine the destination_connection_id_length.
6175 destination_connection_id_length =
6176 expected_destination_connection_id_length;
6177 DCHECK_EQ(0, source_connection_id_length);
fayangccbab732019-05-13 10:11:25 -07006178 }
6179 // Read destination connection ID.
6180 if (!reader.ReadConnectionId(destination_connection_id,
dschinazib42a8c52019-05-30 09:45:01 -07006181 destination_connection_id_length)) {
6182 *detailed_error = "Unable to read destination connection ID.";
6183 return QUIC_INVALID_PACKET_HEADER;
6184 }
6185 // Read source connection ID.
6186 if (GetQuicRestartFlag(quic_do_not_override_connection_id) &&
6187 !reader.ReadConnectionId(source_connection_id,
6188 source_connection_id_length)) {
6189 *detailed_error = "Unable to read source connection ID.";
fayangccbab732019-05-13 10:11:25 -07006190 return QUIC_INVALID_PACKET_HEADER;
6191 }
6192 return QUIC_NO_ERROR;
6193}
6194
dschinazide0f6dc2019-05-15 16:10:11 -07006195// static
6196bool QuicFramer::WriteClientVersionNegotiationProbePacket(
6197 char* packet_bytes,
6198 QuicByteCount packet_length,
6199 const char* destination_connection_id_bytes,
6200 uint8_t destination_connection_id_length) {
6201 if (packet_bytes == nullptr) {
6202 QUIC_BUG << "Invalid packet_bytes";
6203 return false;
6204 }
6205 if (packet_length < kMinPacketSizeForVersionNegotiation ||
6206 packet_length > 65535) {
6207 QUIC_BUG << "Invalid packet_length";
6208 return false;
6209 }
6210 if (destination_connection_id_length > kQuicMaxConnectionIdLength ||
6211 (destination_connection_id_length > 0 &&
6212 destination_connection_id_length < 4)) {
6213 QUIC_BUG << "Invalid connection_id_length";
6214 return false;
6215 }
6216 // clang-format off
6217 static const unsigned char packet_start_bytes[] = {
6218 // IETF long header with fixed bit set, type initial, all-0 encrypted bits.
6219 0xc0,
6220 // Version, part of the IETF space reserved for negotiation.
6221 // This intentionally differs from QuicVersionReservedForNegotiation()
6222 // to allow differentiating them over the wire.
6223 0xca, 0xba, 0xda, 0xba,
6224 };
6225 // clang-format on
6226 static_assert(sizeof(packet_start_bytes) == 5, "bad packet_start_bytes size");
6227 QuicDataWriter writer(packet_length, packet_bytes);
6228 if (!writer.WriteBytes(packet_start_bytes, sizeof(packet_start_bytes))) {
6229 QUIC_BUG << "Failed to write packet start";
6230 return false;
6231 }
6232
6233 QuicConnectionId destination_connection_id(destination_connection_id_bytes,
6234 destination_connection_id_length);
6235 if (!AppendIetfConnectionIds(/*version_flag=*/true, destination_connection_id,
6236 EmptyQuicConnectionId(), &writer)) {
6237 QUIC_BUG << "Failed to write connection IDs";
6238 return false;
6239 }
6240 // Add 8 bytes of zeroes followed by 8 bytes of ones to ensure that this does
6241 // not parse with any known version. The zeroes make sure that packet numbers,
6242 // retry token lengths and payload lengths are parsed as zero, and if the
6243 // zeroes are treated as padding frames, 0xff is known to not parse as a
6244 // valid frame type.
6245 if (!writer.WriteUInt64(0) ||
6246 !writer.WriteUInt64(std::numeric_limits<uint64_t>::max())) {
6247 QUIC_BUG << "Failed to write 18 bytes";
6248 return false;
6249 }
6250 // Make sure the polite greeting below is padded to a 16-byte boundary to
6251 // make it easier to read in tcpdump.
6252 while (writer.length() % 16 != 0) {
6253 if (!writer.WriteUInt8(0)) {
6254 QUIC_BUG << "Failed to write padding byte";
6255 return false;
6256 }
6257 }
6258 // Add a polite greeting in case a human sees this in tcpdump.
6259 static const char polite_greeting[] =
6260 "This packet only exists to trigger IETF QUIC version negotiation. "
6261 "Please respond with a Version Negotiation packet indicating what "
6262 "versions you support. Thank you and have a nice day.";
6263 if (!writer.WriteBytes(polite_greeting, sizeof(polite_greeting))) {
6264 QUIC_BUG << "Failed to write polite greeting";
6265 return false;
6266 }
6267 // Fill the rest of the packet with zeroes.
6268 writer.WritePadding();
6269 DCHECK_EQ(0u, writer.remaining());
6270 return true;
6271}
6272
6273// static
6274bool QuicFramer::ParseServerVersionNegotiationProbeResponse(
6275 const char* packet_bytes,
6276 QuicByteCount packet_length,
6277 char* source_connection_id_bytes,
6278 uint8_t* source_connection_id_length_out,
6279 std::string* detailed_error) {
6280 if (detailed_error == nullptr) {
6281 QUIC_BUG << "Invalid error_details";
6282 return false;
6283 }
6284 *detailed_error = "";
6285 if (packet_bytes == nullptr) {
6286 *detailed_error = "Invalid packet_bytes";
6287 return false;
6288 }
6289 if (packet_length < 6) {
6290 *detailed_error = "Invalid packet_length";
6291 return false;
6292 }
6293 if (source_connection_id_bytes == nullptr) {
6294 *detailed_error = "Invalid source_connection_id_bytes";
6295 return false;
6296 }
6297 if (source_connection_id_length_out == nullptr) {
6298 *detailed_error = "Invalid source_connection_id_length_out";
6299 return false;
6300 }
6301 QuicDataReader reader(packet_bytes, packet_length);
6302 uint8_t type_byte = 0;
6303 if (!reader.ReadUInt8(&type_byte)) {
6304 *detailed_error = "Failed to read type byte";
6305 return false;
6306 }
6307 if ((type_byte & 0x80) == 0) {
6308 *detailed_error = "Packet does not have long header";
6309 return false;
6310 }
6311 uint32_t version = 0;
6312 if (!reader.ReadUInt32(&version)) {
6313 *detailed_error = "Failed to read version";
6314 return false;
6315 }
6316 if (version != 0) {
6317 *detailed_error = "Packet is not a version negotiation packet";
6318 return false;
6319 }
dschinazi8ff74822019-05-28 16:37:20 -07006320 uint8_t expected_server_connection_id_length = 0,
dschinazide0f6dc2019-05-15 16:10:11 -07006321 destination_connection_id_length = 0, source_connection_id_length = 0;
6322 if (!ProcessAndValidateIetfConnectionIdLength(
dschinazi334f0232019-05-29 16:08:53 -07006323 &reader, UnsupportedQuicVersion(), Perspective::IS_CLIENT,
dschinazi8ff74822019-05-28 16:37:20 -07006324 /*should_update_expected_server_connection_id_length=*/true,
6325 &expected_server_connection_id_length,
6326 &destination_connection_id_length, &source_connection_id_length,
6327 detailed_error)) {
dschinazide0f6dc2019-05-15 16:10:11 -07006328 return false;
6329 }
6330 if (destination_connection_id_length != 0) {
6331 *detailed_error = "Received unexpected destination connection ID length";
6332 return false;
6333 }
6334 QuicConnectionId destination_connection_id, source_connection_id;
6335 if (!reader.ReadConnectionId(&destination_connection_id,
6336 destination_connection_id_length)) {
6337 *detailed_error = "Failed to read destination connection ID";
6338 return false;
6339 }
6340 if (!reader.ReadConnectionId(&source_connection_id,
6341 source_connection_id_length)) {
6342 *detailed_error = "Failed to read source connection ID";
6343 return false;
6344 }
6345
6346 memcpy(source_connection_id_bytes, source_connection_id.data(),
6347 source_connection_id_length);
6348 *source_connection_id_length_out = source_connection_id_length;
6349
6350 return true;
6351}
6352
QUICHE teama6ef0a62019-03-07 20:34:33 -05006353#undef ENDPOINT // undef for jumbo builds
6354} // namespace quic